Compare commits
51 Commits
9cda680494
...
refactor/n
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e5516972a | ||
|
|
a3e3f0506c | ||
|
|
976c48ac4b | ||
|
|
7bcf5d90c2 | ||
|
|
358ae7410f | ||
|
|
a906fa136d | ||
|
|
7ec73e8c6f | ||
|
|
84afed78fb | ||
|
|
2b6be86b2e | ||
|
|
fdc03068f2 | ||
|
|
c58e91e073 | ||
|
|
13c0fcc681 | ||
|
|
5c1d560d0c | ||
|
|
a24ee193d4 | ||
|
|
9b325ac917 | ||
|
|
c3d770f713 | ||
|
|
3ef1694217 | ||
|
|
2b707e81c2 | ||
|
|
f6a9ab854c | ||
|
|
474af2fbfc | ||
|
|
4af059f6b7 | ||
|
|
23163be99d | ||
|
|
c1542707c2 | ||
|
|
dd351acb2e | ||
|
|
2370051243 | ||
|
|
ed5d3b5726 | ||
|
|
2e246f7560 | ||
|
|
81c8b04c7a | ||
|
|
cf61f5ecfd | ||
|
|
73ba77ca4f | ||
|
|
c7b2f1643c | ||
|
|
fa2def812c | ||
|
|
8a1dab4764 | ||
|
|
75c02ed1b9 | ||
|
|
8eb10f493f | ||
|
|
1ec4780e14 | ||
|
|
0186afe971 | ||
|
|
bca93282ac | ||
|
|
fe06c46c3f | ||
|
|
4908dff58b | ||
|
|
9fa2b34a5d | ||
|
|
e93cac6086 | ||
|
|
3227e3209c | ||
|
|
54cff28ba0 | ||
|
|
d5f9c8f6fa | ||
|
|
0f17a67e00 | ||
|
|
c90f468d3c | ||
|
|
c4dae86b5f | ||
|
|
92f6cb4d35 | ||
|
|
b956c8ec2b | ||
|
|
1d429f039a |
16
README.md
@@ -102,3 +102,19 @@ cd P2Pix-Front-End
|
||||
# Run docker-compose up command
|
||||
docker-compose up
|
||||
```
|
||||
|
||||
### Backend Communication
|
||||
|
||||
Backend Repo: `https://gitea.kosmos.org/hueso/helpix`
|
||||
|
||||
Backend Endpoint: `https://api.p2pix.co/release/1279331`
|
||||
|
||||
curl -X POST \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer {api-key}" \
|
||||
-d '{"query": "{ depositAddeds { id seller token amount } }"}' \
|
||||
https://api.studio.thegraph.com/query/113713/p-2-pix/sepolia
|
||||
|
||||
https://api.studio.thegraph.com/query/113713/p-2-pix/1
|
||||
|
||||
curl --request POST --url 'https://api.hm.bb.com.br/testes-portal-desenvolvedor/v1/boletos-pix/pagar?gw-app-key=95cad3f03fd9013a9d15005056825665' --header 'content-type: application/json' --data '{"pix":"00020101021226070503***63041654" }'
|
||||
12285
package-lock.json
generated
Normal file
20
package.json
@@ -5,12 +5,10 @@
|
||||
"start": "vite --host=0.0.0.0 --port 3000",
|
||||
"build": "run-p type-check build-only",
|
||||
"preview": "vite preview",
|
||||
"test": "vitest",
|
||||
"serve": "vue-cli-service serve",
|
||||
"coverage": "vitest run --coverage",
|
||||
"build-only": "vite build",
|
||||
"type-check": "vue-tsc --skipLibCheck --noEmit",
|
||||
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --ignore-path .gitignore",
|
||||
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --ignore-path .gitignore --fix",
|
||||
"lint:fix": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -22,12 +20,9 @@
|
||||
"@web3-onboard/vue": "^2.9.0",
|
||||
"alchemy-sdk": "^2.3.0",
|
||||
"axios": "^1.2.1",
|
||||
"crc": "^3.8.0",
|
||||
"ethers": "^6.13.4",
|
||||
"marked": "^4.2.12",
|
||||
"pinia": "^2.0.23",
|
||||
"qrcode": "^1.5.1",
|
||||
"viem": "2.x",
|
||||
"viem": "^2.31.3",
|
||||
"vite-svg-loader": "^5.1.0",
|
||||
"vue": "^3.2.41",
|
||||
"vue-markdown": "^2.2.4",
|
||||
@@ -36,32 +31,27 @@
|
||||
"devDependencies": {
|
||||
"@babel/preset-env": "^7.20.2",
|
||||
"@babel/preset-typescript": "^7.18.6",
|
||||
"@pinia/testing": "^0.0.14",
|
||||
"@rushstack/eslint-patch": "^1.1.4",
|
||||
"@types/crc": "^3.8.0",
|
||||
"@types/jest": "^27.0.0",
|
||||
"@types/marked": "^4.0.8",
|
||||
"@types/node": "^16.11.68",
|
||||
"@types/qrcode": "^1.5.0",
|
||||
"@types/vue-markdown": "^2.2.1",
|
||||
"@vitejs/plugin-vue": "^3.1.2",
|
||||
"@vitejs/plugin-vue-jsx": "^2.0.1",
|
||||
"@vitest/coverage-c8": "^0.28.2",
|
||||
"@vue/eslint-config-prettier": "^7.0.0",
|
||||
"@vue/eslint-config-typescript": "^11.0.0",
|
||||
"@vue/test-utils": "^2.2.7",
|
||||
"@vue/tsconfig": "^0.1.3",
|
||||
"@wagmi/cli": "^2.3.1",
|
||||
"autoprefixer": "^10.4.12",
|
||||
"eslint": "^8.22.0",
|
||||
"eslint-plugin-vue": "^9.3.0",
|
||||
"jsdom": "^21.1.0",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"postcss": "^8.4.18",
|
||||
"prettier": "^2.7.1",
|
||||
"tailwindcss": "^3.2.1",
|
||||
"typescript": "~4.7.4",
|
||||
"typescript": "~5.8.2",
|
||||
"vite": "^3.1.8",
|
||||
"vitest": "^0.28.1",
|
||||
"vue-tsc": "^1.0.8"
|
||||
"vue-tsc": "^2.2.8"
|
||||
}
|
||||
}
|
||||
|
||||
29
src/App.vue
@@ -1,31 +1,25 @@
|
||||
<script setup lang="ts">
|
||||
import { useRoute } from "vue-router";
|
||||
import TopBar from "@/components/TopBar/TopBar.vue";
|
||||
import SpinnerComponent from "@/components/SpinnerComponent.vue";
|
||||
import SpinnerComponent from "@/components/ui/SpinnerComponent.vue";
|
||||
import ToasterComponent from "@/components/ui/ToasterComponent.vue";
|
||||
import { init, useOnboard } from "@web3-onboard/vue";
|
||||
import injectedModule from "@web3-onboard/injected-wallets";
|
||||
import { Networks } from "./model/Networks";
|
||||
import { NetworkEnum } from "./model/NetworkEnum";
|
||||
import { Networks, DEFAULT_NETWORK } from "@/config/networks";
|
||||
import { ref } from "vue";
|
||||
|
||||
const route = useRoute();
|
||||
const injected = injectedModule();
|
||||
const targetNetwork = ref(DEFAULT_NETWORK);
|
||||
|
||||
const web3Onboard = init({
|
||||
wallets: [injected],
|
||||
chains: [
|
||||
{
|
||||
id: Networks[NetworkEnum.sepolia].chainId,
|
||||
token: "ETH",
|
||||
label: "Sepolia",
|
||||
rpcUrl: import.meta.env.VITE_SEPOLIA_API_URL,
|
||||
},
|
||||
{
|
||||
id: Networks[NetworkEnum.rootstock].chainId,
|
||||
token: "tRBTC",
|
||||
label: "Rootstock Testnet",
|
||||
rpcUrl: import.meta.env.VITE_ROOTSTOCK_API_URL,
|
||||
},
|
||||
],
|
||||
chains: Object.values(Networks).map((network) => ({
|
||||
id: network.id,
|
||||
token: network.nativeCurrency.symbol,
|
||||
label: network.name,
|
||||
rpcUrl: network.rpcUrls.default.http[0],
|
||||
})),
|
||||
connect: {
|
||||
autoConnectLastWallet: true,
|
||||
},
|
||||
@@ -58,5 +52,6 @@ if (!connectedWallet) {
|
||||
</Transition>
|
||||
</template>
|
||||
</RouterView>
|
||||
<ToasterComponent :targetNetwork="targetNetwork" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -28,3 +28,9 @@ a,
|
||||
.main-container {
|
||||
@apply flex w-full md:max-w-lg flex-col justify-center items-center px-4 sm:px-8 py-4 sm:py-6 gap-4 rounded-lg border border-gray-500 backdrop-blur-md drop-shadow-lg shadow-lg mt-10;
|
||||
}
|
||||
|
||||
input[type="number"] {
|
||||
appearance: textfield;
|
||||
-webkit-appearance: textfield;
|
||||
-moz-appearance: textfield;
|
||||
}
|
||||
|
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 1.4 KiB |
|
Before Width: | Height: | Size: 1.6 KiB After Width: | Height: | Size: 1.6 KiB |
76
src/assets/networks/rootstock-testnet.svg
Normal file
|
After Width: | Height: | Size: 79 KiB |
|
Before Width: | Height: | Size: 30 KiB After Width: | Height: | Size: 30 KiB |
|
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 1.4 KiB |
|
Before Width: | Height: | Size: 644 B After Width: | Height: | Size: 644 B |
|
Before Width: | Height: | Size: 1.0 KiB After Width: | Height: | Size: 1.0 KiB |
@@ -19,3 +19,14 @@
|
||||
opacity: 0;
|
||||
transform: translateY(15px);
|
||||
}
|
||||
|
||||
.resize-enter-active,
|
||||
.resize-leave-active {
|
||||
max-height: 100px;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.resize-enter-from,
|
||||
.resize-leave-to {
|
||||
max-height: 0px;
|
||||
}
|
||||
|
||||
@@ -1,121 +0,0 @@
|
||||
import { expectTypeOf, it, expect } from "vitest";
|
||||
import {
|
||||
getTokenAddress,
|
||||
getP2PixAddress,
|
||||
getProviderUrl,
|
||||
isPossibleNetwork,
|
||||
} from "../addresses";
|
||||
|
||||
import { setActivePinia, createPinia } from "pinia";
|
||||
import { NetworkEnum, TokenEnum } from "@/model/NetworkEnum";
|
||||
import { useEtherStore } from "@/store/ether";
|
||||
|
||||
describe("addresses.ts types", () => {
|
||||
it("My addresses.ts types work properly", () => {
|
||||
expectTypeOf(getTokenAddress).toBeFunction();
|
||||
expectTypeOf(getP2PixAddress).toBeFunction();
|
||||
expectTypeOf(getProviderUrl).toBeFunction();
|
||||
expectTypeOf(isPossibleNetwork).toBeFunction();
|
||||
});
|
||||
});
|
||||
|
||||
describe("addresses.ts functions", () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
});
|
||||
|
||||
it("getTokenAddress Ethereum", () => {
|
||||
const etherStore = useEtherStore();
|
||||
etherStore.setNetworkId(NetworkEnum.sepolia);
|
||||
expect(getTokenAddress(TokenEnum.BRZ)).toBe(
|
||||
"0x4A2886EAEc931e04297ed336Cc55c4eb7C75BA00"
|
||||
);
|
||||
});
|
||||
|
||||
it("getTokenAddress Polygon", () => {
|
||||
const etherStore = useEtherStore();
|
||||
etherStore.setNetworkId(NetworkEnum.polygon);
|
||||
expect(getTokenAddress(TokenEnum.BRZ)).toBe(
|
||||
"0xC86042E9F2977C62Da8c9dDF7F9c40fde4796A29"
|
||||
);
|
||||
});
|
||||
|
||||
it("getTokenAddress Rootstock", () => {
|
||||
const etherStore = useEtherStore();
|
||||
etherStore.setNetworkId(NetworkEnum.rootstock);
|
||||
expect(getTokenAddress(TokenEnum.BRZ)).toBe(
|
||||
"0xfE841c74250e57640390f46d914C88d22C51e82e"
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
it("getTokenAddress Default", () => {
|
||||
expect(getTokenAddress(TokenEnum.BRZ)).toBe(
|
||||
"0x4A2886EAEc931e04297ed336Cc55c4eb7C75BA00"
|
||||
);
|
||||
});
|
||||
|
||||
it("getP2PixAddress Ethereum", () => {
|
||||
const etherStore = useEtherStore();
|
||||
etherStore.setNetworkId(NetworkEnum.sepolia);
|
||||
expect(getP2PixAddress()).toBe(
|
||||
"0x2414817FF64A114d91eCFA16a834d3fCf69103d4"
|
||||
);
|
||||
});
|
||||
|
||||
it("getP2PixAddress Polygon", () => {
|
||||
const etherStore = useEtherStore();
|
||||
etherStore.setNetworkId(NetworkEnum.polygon);
|
||||
expect(getP2PixAddress()).toBe(
|
||||
"0x4A2886EAEc931e04297ed336Cc55c4eb7C75BA00"
|
||||
);
|
||||
});
|
||||
|
||||
it("getP2PixAddress Rootstock", () => {
|
||||
const etherStore = useEtherStore();
|
||||
etherStore.setNetworkId(NetworkEnum.rootstock);
|
||||
expect(getP2PixAddress()).toBe(
|
||||
"0x98ba35eb14b38D6Aa709338283af3e922476dE34"
|
||||
);
|
||||
});
|
||||
|
||||
it("getP2PixAddress Default", () => {
|
||||
expect(getP2PixAddress()).toBe(
|
||||
"0x2414817FF64A114d91eCFA16a834d3fCf69103d4"
|
||||
);
|
||||
});
|
||||
|
||||
it("getProviderUrl Ethereum", () => {
|
||||
const etherStore = useEtherStore();
|
||||
etherStore.setNetworkId(NetworkEnum.sepolia);
|
||||
expect(getProviderUrl()).toBe(import.meta.env.VITE_GOERLI_API_URL);
|
||||
});
|
||||
|
||||
it("getProviderUrl Polygon", () => {
|
||||
const etherStore = useEtherStore();
|
||||
etherStore.setNetworkId(NetworkEnum.polygon);
|
||||
expect(getProviderUrl()).toBe(import.meta.env.VITE_MUMBAI_API_URL);
|
||||
});
|
||||
|
||||
it("getProviderUrl Rootstock", () => {
|
||||
const etherStore = useEtherStore();
|
||||
etherStore.setNetworkId(NetworkEnum.rootstock);
|
||||
expect(getProviderUrl()).toBe(import.meta.env.VITE_ROOTSTOCK_API_URL);
|
||||
});
|
||||
|
||||
it("getProviderUrl Default", () => {
|
||||
expect(getProviderUrl()).toBe(import.meta.env.VITE_GOERLI_API_URL);
|
||||
});
|
||||
|
||||
it("isPossibleNetwork Returns", () => {
|
||||
const etherStore = useEtherStore();
|
||||
etherStore.setNetworkId(NetworkEnum.sepolia);
|
||||
expect(isPossibleNetwork(0x5)).toBe(true);
|
||||
expect(isPossibleNetwork(5)).toBe(true);
|
||||
expect(isPossibleNetwork(0x13881)).toBe(true);
|
||||
expect(isPossibleNetwork(80001)).toBe(true);
|
||||
|
||||
expect(isPossibleNetwork(NaN)).toBe(false);
|
||||
expect(isPossibleNetwork(0x55)).toBe(false);
|
||||
});
|
||||
});
|
||||
2266
src/blockchain/abi.ts
Normal file
@@ -1,70 +0,0 @@
|
||||
import { useEtherStore } from "@/store/ether";
|
||||
import { NetworkEnum, TokenEnum } from "@/model/NetworkEnum";
|
||||
import { JsonRpcProvider } from "ethers";
|
||||
|
||||
const Tokens: { [key in NetworkEnum]: { [key in TokenEnum]: string } } = {
|
||||
[NetworkEnum.sepolia]: {
|
||||
BRZ: "0x3eBE67A2C7bdB2081CBd34ba3281E90377462289",
|
||||
// BRX: "0x3eBE67A2C7bdB2081CBd34ba3281E90377462289",
|
||||
},
|
||||
[NetworkEnum.rootstock]: {
|
||||
BRZ: "0xfE841c74250e57640390f46d914C88d22C51e82e",
|
||||
// BRX: "0xfE841c74250e57640390f46d914C88d22C51e82e",
|
||||
},
|
||||
};
|
||||
|
||||
export const getTokenByAddress = (address: string) => {
|
||||
for (const network of Object.values(NetworkEnum).filter(
|
||||
(v) => !isNaN(Number(v))
|
||||
)) {
|
||||
for (const token of Object.keys(Tokens[network as NetworkEnum])) {
|
||||
if (address === Tokens[network as NetworkEnum][token as TokenEnum]) {
|
||||
return token as TokenEnum;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const getTokenAddress = (token: TokenEnum, network?: NetworkEnum): string => {
|
||||
const etherStore = useEtherStore();
|
||||
return Tokens[network ? network : etherStore.networkName][token];
|
||||
};
|
||||
|
||||
const getP2PixAddress = (network?: NetworkEnum): string => {
|
||||
const etherStore = useEtherStore();
|
||||
const possibleP2PixAddresses: { [key in NetworkEnum]: string } = {
|
||||
[NetworkEnum.sepolia]: "0xb7cD135F5eFD9760981e02E2a898790b688939fe",
|
||||
[NetworkEnum.rootstock]: "0x98ba35eb14b38D6Aa709338283af3e922476dE34",
|
||||
};
|
||||
|
||||
return possibleP2PixAddresses[network ? network : etherStore.networkName];
|
||||
};
|
||||
|
||||
const getProviderUrl = (network?: NetworkEnum): string => {
|
||||
const etherStore = useEtherStore();
|
||||
const possibleProvidersUrls: { [key in NetworkEnum]: string } = {
|
||||
[NetworkEnum.sepolia]: import.meta.env.VITE_SEPOLIA_API_URL,
|
||||
[NetworkEnum.rootstock]: import.meta.env.VITE_RSK_API_URL,
|
||||
};
|
||||
|
||||
return possibleProvidersUrls[network || etherStore.networkName];
|
||||
};
|
||||
|
||||
const getProviderByNetwork = (network: NetworkEnum): JsonRpcProvider => {
|
||||
console.log("network", network);
|
||||
return new JsonRpcProvider(getProviderUrl(network), network);
|
||||
};
|
||||
|
||||
const isPossibleNetwork = (networkChain: NetworkEnum): boolean => {
|
||||
return Number(networkChain) in NetworkEnum;
|
||||
};
|
||||
|
||||
export {
|
||||
getTokenAddress,
|
||||
getProviderUrl,
|
||||
isPossibleNetwork,
|
||||
getP2PixAddress,
|
||||
getProviderByNetwork,
|
||||
};
|
||||
@@ -1,97 +1,82 @@
|
||||
import { getContract, getProvider } from "./provider";
|
||||
import { getP2PixAddress, getTokenAddress } from "./addresses";
|
||||
|
||||
import p2pix from "@/utils/smart_contract_files/P2PIX.json";
|
||||
|
||||
import { getContract } from "./provider";
|
||||
import { ChainContract } from "viem";
|
||||
import {
|
||||
solidityPackedKeccak256,
|
||||
encodeBytes32String,
|
||||
Signature,
|
||||
Contract,
|
||||
getBytes,
|
||||
Wallet,
|
||||
parseEther,
|
||||
} from "ethers";
|
||||
import type { TokenEnum } from "@/model/NetworkEnum";
|
||||
type Address,
|
||||
type TransactionReceipt,
|
||||
} from "viem";
|
||||
|
||||
const addLock = async (
|
||||
seller: string,
|
||||
token: string,
|
||||
export const addLock = async (
|
||||
sellerAddress: Address,
|
||||
tokenAddress: Address,
|
||||
amount: number
|
||||
): Promise<string> => {
|
||||
const p2pContract = await getContract();
|
||||
): Promise<bigint> => {
|
||||
const { address, abi, wallet, client, account } = await getContract();
|
||||
const parsedAmount = parseEther(amount.toString());
|
||||
|
||||
const lock = await p2pContract.lock(
|
||||
seller,
|
||||
token,
|
||||
parseEther(String(amount)), // BigNumber
|
||||
[],
|
||||
[]
|
||||
);
|
||||
if (!wallet) {
|
||||
throw new Error("Wallet not connected");
|
||||
}
|
||||
|
||||
const lock_rec = await lock.wait();
|
||||
const [t] = lock_rec.events;
|
||||
const { result, request } = await client.simulateContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "lock",
|
||||
args: [sellerAddress, tokenAddress, parsedAmount, [], []],
|
||||
account,
|
||||
});
|
||||
const hash = await wallet.writeContract(request);
|
||||
const receipt = await client.waitForTransactionReceipt({ hash });
|
||||
|
||||
return String(t.args.lockID);
|
||||
if (!receipt.status)
|
||||
throw new Error("Transaction failed: " + receipt.transactionHash);
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const releaseLock = async (
|
||||
pixKey: string,
|
||||
amount: number,
|
||||
e2eId: string,
|
||||
lockId: string
|
||||
): Promise<any> => {
|
||||
const mockBacenSigner = new Wallet(
|
||||
"0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"
|
||||
);
|
||||
|
||||
const messageToSign = solidityPackedKeccak256(
|
||||
["bytes32", "uint256", "bytes32"],
|
||||
[pixKey, parseEther(String(amount)), encodeBytes32String(e2eId)]
|
||||
);
|
||||
|
||||
const messageHashBytes = getBytes(messageToSign);
|
||||
const flatSig = await mockBacenSigner.signMessage(messageHashBytes);
|
||||
const provider = getProvider();
|
||||
|
||||
const sig = Signature.from(flatSig);
|
||||
console.log(sig);
|
||||
const signer = await provider.getSigner();
|
||||
const p2pContract = new Contract(getP2PixAddress(), p2pix.abi, signer);
|
||||
|
||||
const release = await p2pContract.release(
|
||||
BigInt(lockId),
|
||||
encodeBytes32String(e2eId),
|
||||
flatSig
|
||||
);
|
||||
await release.wait();
|
||||
|
||||
return release;
|
||||
};
|
||||
|
||||
const cancelDeposit = async (depositId: bigint): Promise<any> => {
|
||||
const contract = await getContract();
|
||||
|
||||
const cancel = await contract.cancelDeposit(depositId);
|
||||
await cancel.wait();
|
||||
|
||||
return cancel;
|
||||
};
|
||||
|
||||
const withdrawDeposit = async (
|
||||
export const withdrawDeposit = async (
|
||||
amount: string,
|
||||
token: TokenEnum
|
||||
): Promise<any> => {
|
||||
const contract = await getContract();
|
||||
token: Address
|
||||
): Promise<boolean> => {
|
||||
const { address, abi, wallet, client, account } = await getContract();
|
||||
|
||||
const withdraw = await contract.withdraw(
|
||||
getTokenAddress(token),
|
||||
parseEther(String(amount)),
|
||||
[]
|
||||
);
|
||||
await withdraw.wait();
|
||||
if (!wallet) {
|
||||
throw new Error("Wallet not connected");
|
||||
}
|
||||
|
||||
return withdraw;
|
||||
const { request } = await client.simulateContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "withdraw",
|
||||
args: [token, parseEther(amount), []],
|
||||
account
|
||||
});
|
||||
|
||||
const hash = await wallet.writeContract(request);
|
||||
const receipt = await client.waitForTransactionReceipt({ hash });
|
||||
|
||||
return receipt.status === "success";
|
||||
};
|
||||
|
||||
export { cancelDeposit, withdrawDeposit, addLock, releaseLock };
|
||||
export const releaseLock = async (
|
||||
lockID: bigint,
|
||||
pixTimestamp: `0x${string}`&{lenght:34},
|
||||
signature: `0x${string}`
|
||||
): Promise<TransactionReceipt> => {
|
||||
const { address, abi, wallet, client, account } = await getContract();
|
||||
|
||||
if (!wallet) {
|
||||
throw new Error("Wallet not connected");
|
||||
}
|
||||
|
||||
const { request } = await client.simulateContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "release",
|
||||
args: [BigInt(lockID), pixTimestamp, signature],
|
||||
account
|
||||
});
|
||||
|
||||
const hash = await wallet.writeContract(request);
|
||||
return client.waitForTransactionReceipt({ hash });
|
||||
};
|
||||
|
||||
@@ -1,55 +1,56 @@
|
||||
import { useEtherStore } from "@/store/ether";
|
||||
import { Contract, formatEther, Interface } from "ethers";
|
||||
|
||||
import p2pix from "@/utils/smart_contract_files/P2PIX.json";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
import { formatEther, toHex, stringToHex } from "viem";
|
||||
import type { PublicClient, Address } from "viem";
|
||||
import { Networks } from "@/config/networks";
|
||||
import { getContract } from "./provider";
|
||||
import { p2PixAbi } from "./abi"
|
||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||
import {
|
||||
getP2PixAddress,
|
||||
getProviderByNetwork,
|
||||
getTokenAddress,
|
||||
} from "./addresses";
|
||||
import { NetworkEnum } from "@/model/NetworkEnum";
|
||||
import type { NetworkConfig } from "@/model/NetworkEnum";
|
||||
import type { UnreleasedLock } from "@/model/UnreleasedLock";
|
||||
import type { Pix } from "@/model/Pix";
|
||||
import { ChainContract } from "viem";
|
||||
|
||||
const getNetworksLiquidity = async (): Promise<void> => {
|
||||
const etherStore = useEtherStore();
|
||||
etherStore.setLoadingNetworkLiquidity(true);
|
||||
const user = useUser();
|
||||
user.setLoadingNetworkLiquidity(true);
|
||||
|
||||
const depositLists: ValidDeposit[][] = [];
|
||||
|
||||
for (const network of Object.values(NetworkEnum).filter(
|
||||
(v) => !isNaN(Number(v))
|
||||
)) {
|
||||
console.log("getNetworksLiquidity", network);
|
||||
const p2pContract = new Contract(
|
||||
getP2PixAddress(network as NetworkEnum),
|
||||
p2pix.abi,
|
||||
getProviderByNetwork(network as NetworkEnum)
|
||||
);
|
||||
|
||||
depositLists.push(
|
||||
await getValidDeposits(
|
||||
getTokenAddress(etherStore.selectedToken, network as NetworkEnum),
|
||||
network as NetworkEnum,
|
||||
p2pContract
|
||||
)
|
||||
for (const network of Object.values(Networks)) {
|
||||
const deposits = await getValidDeposits(
|
||||
user.network.value.tokens[user.selectedToken.value].address,
|
||||
network
|
||||
);
|
||||
if (deposits) depositLists.push(deposits);
|
||||
}
|
||||
|
||||
etherStore.setDepositsValidList(depositLists.flat());
|
||||
etherStore.setLoadingNetworkLiquidity(false);
|
||||
const allDeposits = depositLists.flat();
|
||||
user.setDepositsValidList(allDeposits);
|
||||
user.setLoadingNetworkLiquidity(false);
|
||||
};
|
||||
|
||||
const getPixKey = async (seller: string, token: string): Promise<string> => {
|
||||
const p2pContract = await getContract();
|
||||
const pixKeyHex = await p2pContract.getPixTarget(seller, token);
|
||||
const getParticipantID = async (
|
||||
seller: Address,
|
||||
token: Address
|
||||
): Promise<string> => {
|
||||
const { address, abi, client } = await getContract();
|
||||
|
||||
const participantIDHex = await client.readContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "getPixTarget",
|
||||
args: [seller, token],
|
||||
});
|
||||
|
||||
// Remove '0x' prefix and convert hex to UTF-8 string
|
||||
const hexString =
|
||||
typeof participantIDHex === "string"
|
||||
? participantIDHex
|
||||
: toHex(participantIDHex as bigint);
|
||||
if (!hexString) throw new Error("Participant ID not found");
|
||||
const bytes = new Uint8Array(
|
||||
pixKeyHex
|
||||
hexString
|
||||
.slice(2)
|
||||
.match(/.{1,2}/g)
|
||||
.match(/.{1,2}/g)!
|
||||
.map((byte: string) => parseInt(byte, 16))
|
||||
);
|
||||
// Remove null bytes from the end of the string
|
||||
@@ -57,75 +58,107 @@ const getPixKey = async (seller: string, token: string): Promise<string> => {
|
||||
};
|
||||
|
||||
const getValidDeposits = async (
|
||||
token: string,
|
||||
network: NetworkEnum,
|
||||
contract?: Contract
|
||||
token: Address,
|
||||
network: NetworkConfig,
|
||||
contractInfo?: { client: PublicClient; address: Address }
|
||||
): Promise<ValidDeposit[]> => {
|
||||
let p2pContract: Contract;
|
||||
let client: PublicClient, abi;
|
||||
|
||||
if (contract) {
|
||||
p2pContract = contract;
|
||||
if (contractInfo) {
|
||||
({ client } = contractInfo);
|
||||
abi = p2PixAbi;
|
||||
} else {
|
||||
p2pContract = await getContract(true);
|
||||
({ abi, client } = await getContract(true));
|
||||
}
|
||||
|
||||
const filterDeposits = p2pContract.filters.DepositAdded(null);
|
||||
const eventsDeposits = await p2pContract.queryFilter(
|
||||
filterDeposits
|
||||
// 0,
|
||||
// "latest"
|
||||
const body = {
|
||||
query: `
|
||||
{
|
||||
depositAddeds(where: { token: "${token}" }) {
|
||||
seller
|
||||
amount
|
||||
blockTimestamp
|
||||
blockNumber
|
||||
}
|
||||
}
|
||||
`,
|
||||
};
|
||||
|
||||
const depositLogs = await fetch( network.subgraphUrls[0], {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
// remove doubles from sellers list
|
||||
const depositData = await depositLogs.json();
|
||||
const depositAddeds = depositData.data.depositAddeds;
|
||||
const uniqueSellers = depositAddeds.reduce(
|
||||
(acc: Record<Address, boolean>, deposit: any) => {
|
||||
acc[deposit.seller] = true;
|
||||
return acc;
|
||||
},
|
||||
{} as Record<Address, boolean>
|
||||
);
|
||||
if (!contract) p2pContract = await getContract(); // get metamask provider contract
|
||||
|
||||
if (!contractInfo) {
|
||||
// Get metamask provider contract
|
||||
({ abi, client } = await getContract(true));
|
||||
}
|
||||
|
||||
const depositList: { [key: string]: ValidDeposit } = {};
|
||||
|
||||
for (const deposit of eventsDeposits) {
|
||||
const IPix2Pix = new Interface(p2pix.abi);
|
||||
const decoded = IPix2Pix.parseLog({
|
||||
topics: deposit.topics,
|
||||
data: deposit.data,
|
||||
});
|
||||
// Get liquidity only for the selected token
|
||||
if (decoded?.args.token != token) continue;
|
||||
const mappedBalance = await p2pContract.getBalance(
|
||||
decoded.args.seller,
|
||||
token
|
||||
);
|
||||
let validDeposit: ValidDeposit | null = null;
|
||||
const sellersList = Object.keys(uniqueSellers) as Address[];
|
||||
// Use multicall to batch all getBalance requests
|
||||
const balanceCalls = sellersList.map((seller) => ({
|
||||
address: (network.contracts?.p2pix as ChainContract).address,
|
||||
abi,
|
||||
functionName: "getBalance",
|
||||
args: [seller, token],
|
||||
}));
|
||||
|
||||
if (mappedBalance) {
|
||||
validDeposit = {
|
||||
token: token,
|
||||
blockNumber: deposit.blockNumber,
|
||||
remaining: Number(formatEther(mappedBalance)),
|
||||
seller: decoded.args.seller,
|
||||
const balanceResults = await client.multicall({
|
||||
contracts: balanceCalls as any,
|
||||
});
|
||||
|
||||
// Process results into the depositList
|
||||
sellersList.forEach((seller, index) => {
|
||||
const mappedBalance = balanceResults[index];
|
||||
|
||||
if (!mappedBalance.error && mappedBalance.result) {
|
||||
const validDeposit: ValidDeposit = {
|
||||
token,
|
||||
blockNumber: 0,
|
||||
remaining: Number(formatEther(mappedBalance.result as bigint)),
|
||||
seller,
|
||||
network,
|
||||
pixKey: "",
|
||||
participantID: "",
|
||||
};
|
||||
depositList[seller + token] = validDeposit;
|
||||
}
|
||||
if (validDeposit) depositList[decoded.args.seller + token] = validDeposit;
|
||||
}
|
||||
|
||||
});
|
||||
return Object.values(depositList);
|
||||
};
|
||||
|
||||
const getUnreleasedLockById = async (
|
||||
lockID: string
|
||||
lockID: bigint
|
||||
): Promise<UnreleasedLock> => {
|
||||
const p2pContract = await getContract();
|
||||
const pixData: Pix = {
|
||||
pixKey: "",
|
||||
};
|
||||
const { address, abi, client } = await getContract();
|
||||
|
||||
const lock = await p2pContract.mapLocks(lockID);
|
||||
|
||||
const pixTarget = lock.pixTarget;
|
||||
const amount = formatEther(lock?.amount);
|
||||
pixData.pixKey = pixTarget;
|
||||
pixData.value = Number(amount);
|
||||
const [ , , , amount, token, seller ] = await client.readContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "mapLocks",
|
||||
args: [lockID],
|
||||
});
|
||||
|
||||
return {
|
||||
lockID: lockID,
|
||||
pix: pixData,
|
||||
lockID,
|
||||
amount: Number(formatEther(amount)),
|
||||
tokenAddress: token,
|
||||
sellerAddress: seller,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -133,5 +166,5 @@ export {
|
||||
getValidDeposits,
|
||||
getNetworksLiquidity,
|
||||
getUnreleasedLockById,
|
||||
getPixKey,
|
||||
getParticipantID,
|
||||
};
|
||||
|
||||
@@ -1,27 +1,63 @@
|
||||
import p2pix from "@/utils/smart_contract_files/P2PIX.json";
|
||||
import { p2PixAbi } from "./abi";
|
||||
import { updateWalletStatus } from "./wallet";
|
||||
import { getProviderUrl, getP2PixAddress } from "./addresses";
|
||||
import { BrowserProvider, JsonRpcProvider, Contract } from "ethers";
|
||||
import {
|
||||
createPublicClient,
|
||||
createWalletClient,
|
||||
custom,
|
||||
http,
|
||||
PublicClient,
|
||||
WalletClient,
|
||||
} from "viem";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
import type { NetworkConfig } from "@/model/NetworkEnum";
|
||||
import type { ChainContract } from "viem";
|
||||
|
||||
let provider: BrowserProvider | JsonRpcProvider | null = null;
|
||||
let walletClient: WalletClient | null = null;
|
||||
|
||||
const getProvider = (onlyAlchemyProvider: boolean = false) => {
|
||||
if (onlyAlchemyProvider) return new JsonRpcProvider(getProviderUrl()); // alchemy provider
|
||||
return provider;
|
||||
const getPublicClient = (): PublicClient => {
|
||||
const user = useUser();
|
||||
const rpcUrl = (user.network.value as NetworkConfig).rpcUrls.default.http[0];
|
||||
const chain = user.network.value;
|
||||
|
||||
return createPublicClient({
|
||||
chain,
|
||||
transport: http(rpcUrl),
|
||||
});
|
||||
};
|
||||
|
||||
const getContract = async (onlyAlchemyProvider: boolean = false) => {
|
||||
const p = getProvider(onlyAlchemyProvider);
|
||||
try {
|
||||
const signer = await p?.getSigner();
|
||||
return new Contract(getP2PixAddress(), p2pix.abi, signer);
|
||||
} catch (err) {
|
||||
return new Contract(getP2PixAddress(), p2pix.abi, p);
|
||||
const getWalletClient = (): WalletClient | null => {
|
||||
return walletClient;
|
||||
};
|
||||
|
||||
const getContract = async (onlyRpcProvider = false) => {
|
||||
const client = getPublicClient();
|
||||
const user = useUser();
|
||||
const address = (user.network.value.contracts?.p2pix as ChainContract).address;
|
||||
const abi = p2PixAbi;
|
||||
const wallet = onlyRpcProvider ? null : getWalletClient();
|
||||
|
||||
if (!client) {
|
||||
throw new Error("Public client not initialized");
|
||||
}
|
||||
|
||||
const [account] = wallet ? await wallet.getAddresses() : [null];
|
||||
|
||||
return { address, abi, client, wallet, account };
|
||||
};
|
||||
|
||||
const connectProvider = async (p: any): Promise<void> => {
|
||||
provider = new BrowserProvider(p, "any");
|
||||
const user = useUser();
|
||||
const chain = user.network.value;
|
||||
|
||||
const [account] = await p!.request({ method: "eth_requestAccounts" });
|
||||
|
||||
walletClient = createWalletClient({
|
||||
account,
|
||||
chain,
|
||||
transport: custom(p),
|
||||
});
|
||||
|
||||
await updateWalletStatus();
|
||||
};
|
||||
export { getProvider, getContract, connectProvider };
|
||||
|
||||
export { getPublicClient, getWalletClient, getContract, connectProvider };
|
||||
|
||||
@@ -1,54 +1,91 @@
|
||||
import { getContract, getProvider } from "./provider";
|
||||
import { getTokenAddress, getP2PixAddress } from "./addresses";
|
||||
import { getContract, getPublicClient, getWalletClient } from "./provider";
|
||||
import { parseEther, toHex, ChainContract } from "viem";
|
||||
import { mockTokenAbi } from "./abi";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
import { createParticipant } from "@/utils/bbPay";
|
||||
import type { Participant } from "@/utils/bbPay";
|
||||
import type { Address } from "viem";
|
||||
|
||||
import { encodeBytes32String, Contract, parseEther } from "ethers";
|
||||
const getP2PixAddress = (): Address => {
|
||||
const user = useUser();
|
||||
return (user.network.value.contracts?.p2pix as ChainContract).address;
|
||||
};
|
||||
|
||||
import mockToken from "../utils/smart_contract_files/MockToken.json";
|
||||
import { useEtherStore } from "@/store/ether";
|
||||
const approveTokens = async (participant: Participant): Promise<any> => {
|
||||
const user = useUser();
|
||||
const publicClient = getPublicClient();
|
||||
const walletClient = getWalletClient();
|
||||
|
||||
const approveTokens = async (tokenQty: string): Promise<any> => {
|
||||
const provider = getProvider();
|
||||
const signer = await provider?.getSigner();
|
||||
const etherStore = useEtherStore();
|
||||
if (!publicClient || !walletClient) {
|
||||
throw new Error("Clients not initialized");
|
||||
}
|
||||
|
||||
const tokenContract = new Contract(
|
||||
getTokenAddress(etherStore.selectedToken),
|
||||
mockToken.abi,
|
||||
signer
|
||||
);
|
||||
user.setSeller(participant);
|
||||
const [account] = await walletClient.getAddresses();
|
||||
|
||||
// Get token address
|
||||
const tokenAddress = user.network.value.tokens[user.selectedToken.value].address;
|
||||
|
||||
// Check if the token is already approved
|
||||
const approved = await tokenContract.allowance(
|
||||
await signer?.getAddress(),
|
||||
getP2PixAddress()
|
||||
);
|
||||
if (approved < parseEther(tokenQty)) {
|
||||
const allowance = await publicClient.readContract({
|
||||
address: tokenAddress,
|
||||
abi: mockTokenAbi,
|
||||
functionName: "allowance",
|
||||
args: [account, getP2PixAddress()],
|
||||
});
|
||||
|
||||
if ( allowance < parseEther(participant.offer.toString()) ) {
|
||||
// Approve tokens
|
||||
const apprv = await tokenContract.approve(
|
||||
getP2PixAddress(),
|
||||
parseEther(tokenQty)
|
||||
);
|
||||
await apprv.wait();
|
||||
const chain = user.network.value;
|
||||
const hash = await walletClient.writeContract({
|
||||
address: tokenAddress,
|
||||
abi: mockTokenAbi,
|
||||
functionName: "approve",
|
||||
args: [getP2PixAddress(), parseEther(participant.offer.toString())],
|
||||
account,
|
||||
chain,
|
||||
});
|
||||
|
||||
await publicClient.waitForTransactionReceipt({ hash });
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const addDeposit = async (tokenQty: string, pixKey: string): Promise<any> => {
|
||||
const p2pContract = await getContract();
|
||||
const etherStore = useEtherStore();
|
||||
const addDeposit = async (): Promise<any> => {
|
||||
const { address, abi, client } = await getContract();
|
||||
const walletClient = getWalletClient();
|
||||
const user = useUser();
|
||||
|
||||
const deposit = await p2pContract.deposit(
|
||||
pixKey,
|
||||
encodeBytes32String(""),
|
||||
getTokenAddress(etherStore.selectedToken),
|
||||
parseEther(tokenQty),
|
||||
true
|
||||
);
|
||||
if (!walletClient) {
|
||||
throw new Error("Wallet client not initialized");
|
||||
}
|
||||
|
||||
await deposit.wait();
|
||||
const [account] = await walletClient.getAddresses();
|
||||
|
||||
return deposit;
|
||||
const sellerId = await createParticipant(user.seller.value);
|
||||
user.setSellerId(sellerId.id);
|
||||
if (!sellerId.id) {
|
||||
throw new Error("Failed to create participant");
|
||||
}
|
||||
const chain = user.network.value;
|
||||
const hash = await walletClient.writeContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "deposit",
|
||||
args: [
|
||||
user.network.value.id + "-" + sellerId.id,
|
||||
toHex("", { size: 32 }),
|
||||
user.network.value.tokens[user.selectedToken.value].address,
|
||||
parseEther(user.seller.value.offer.toString()),
|
||||
true,
|
||||
],
|
||||
account,
|
||||
chain,
|
||||
});
|
||||
|
||||
const receipt = await client.waitForTransactionReceipt({ hash });
|
||||
return receipt;
|
||||
};
|
||||
|
||||
export { approveTokens, addDeposit };
|
||||
|
||||
@@ -1,64 +1,46 @@
|
||||
import {
|
||||
Contract,
|
||||
formatEther,
|
||||
getAddress,
|
||||
Interface,
|
||||
Log,
|
||||
LogDescription,
|
||||
} from "ethers";
|
||||
import { useEtherStore } from "@/store/ether";
|
||||
import { formatEther, type Address } from "viem";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
|
||||
import { getContract, getProvider } from "./provider";
|
||||
import { getTokenAddress, isPossibleNetwork } from "./addresses";
|
||||
import { getPublicClient, getWalletClient, getContract } from "./provider";
|
||||
|
||||
import mockToken from "@/utils/smart_contract_files/MockToken.json";
|
||||
import p2pix from "@/utils/smart_contract_files/P2PIX.json";
|
||||
|
||||
import { getValidDeposits } from "./events";
|
||||
import { getValidDeposits, getUnreleasedLockById } from "./events";
|
||||
|
||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||
import type { WalletTransaction } from "@/model/WalletTransaction";
|
||||
import type { UnreleasedLock } from "@/model/UnreleasedLock";
|
||||
import type { Pix } from "@/model/Pix";
|
||||
import { LockStatus } from "@/model/LockStatus";
|
||||
|
||||
export const updateWalletStatus = async (): Promise<void> => {
|
||||
const etherStore = useEtherStore();
|
||||
const user = useUser();
|
||||
|
||||
const provider = await getProvider();
|
||||
const signer = await provider?.getSigner();
|
||||
const publicClient = getPublicClient();
|
||||
const walletClient = getWalletClient();
|
||||
|
||||
const { chainId } = await provider?.getNetwork();
|
||||
if (!isPossibleNetwork(Number(chainId))) {
|
||||
window.alert("Invalid chain!:" + chainId);
|
||||
if (!publicClient || !walletClient) {
|
||||
console.error("Client not initialized");
|
||||
return;
|
||||
}
|
||||
etherStore.setNetworkId(Number(chainId));
|
||||
|
||||
const mockTokenContract = new Contract(
|
||||
getTokenAddress(etherStore.selectedToken),
|
||||
mockToken.abi,
|
||||
signer
|
||||
);
|
||||
// Get balance
|
||||
const [account] = await walletClient.getAddresses();
|
||||
const balance = await publicClient.getBalance({ address: account });
|
||||
|
||||
const walletAddress = await provider?.send("eth_requestAccounts", []);
|
||||
const balance = await mockTokenContract.balanceOf(walletAddress[0]);
|
||||
|
||||
etherStore.setBalance(formatEther(balance));
|
||||
etherStore.setWalletAddress(getAddress(walletAddress[0]));
|
||||
user.setWalletAddress(account);
|
||||
user.setBalance(formatEther(balance));
|
||||
};
|
||||
|
||||
export const listValidDepositTransactionsByWalletAddress = async (
|
||||
walletAddress: string
|
||||
walletAddress: Address
|
||||
): Promise<ValidDeposit[]> => {
|
||||
const etherStore = useEtherStore();
|
||||
const user = useUser();
|
||||
const walletDeposits = await getValidDeposits(
|
||||
getTokenAddress(etherStore.selectedToken),
|
||||
etherStore.networkName
|
||||
user.network.value.tokens[user.selectedToken.value].address,
|
||||
user.network.value
|
||||
);
|
||||
if (walletDeposits) {
|
||||
return walletDeposits
|
||||
.filter((deposit) => deposit.seller == walletAddress)
|
||||
.sort((a, b) => {
|
||||
.sort((a: ValidDeposit, b: ValidDeposit) => {
|
||||
return b.blockNumber - a.blockNumber;
|
||||
});
|
||||
}
|
||||
@@ -66,235 +48,416 @@ export const listValidDepositTransactionsByWalletAddress = async (
|
||||
return [];
|
||||
};
|
||||
|
||||
const getLockStatus = async (id: [BigInt]): Promise<number> => {
|
||||
const p2pContract = await getContract();
|
||||
const res = await p2pContract.getLocksStatus([id]);
|
||||
return res[1][0];
|
||||
};
|
||||
|
||||
const filterLockStatus = async (
|
||||
transactions: Log[]
|
||||
): Promise<WalletTransaction[]> => {
|
||||
const txs: WalletTransaction[] = [];
|
||||
|
||||
for (const transaction of transactions) {
|
||||
const IPix2Pix = new Interface(p2pix.abi);
|
||||
const decoded = IPix2Pix.parseLog({
|
||||
topics: transaction.topics,
|
||||
data: transaction.data,
|
||||
});
|
||||
if (!decoded) continue;
|
||||
const tx: WalletTransaction = {
|
||||
token: decoded.args.token ? decoded.args.token : "",
|
||||
blockNumber: transaction.blockNumber,
|
||||
amount: decoded.args.amount
|
||||
? Number(formatEther(decoded.args.amount))
|
||||
: -1,
|
||||
seller: decoded.args.seller ? decoded.args.seller : "",
|
||||
buyer: decoded.args.buyer ? decoded.args.buyer : "",
|
||||
event: decoded.name,
|
||||
lockStatus:
|
||||
decoded.name == "LockAdded"
|
||||
? await getLockStatus(decoded.args.lockID)
|
||||
: -1,
|
||||
transactionHash: transaction.transactionHash
|
||||
? transaction.transactionHash
|
||||
: "",
|
||||
transactionID: decoded.args.lockID ? decoded.args.lockID.toString() : "",
|
||||
};
|
||||
txs.push(tx);
|
||||
}
|
||||
return txs;
|
||||
const getLockStatus = async (id: bigint): Promise<LockStatus> => {
|
||||
const { address, abi, client } = await getContract();
|
||||
const [ sortedIDs , status ] = await client.readContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "getLocksStatus",
|
||||
args: [[id]],
|
||||
});
|
||||
return status[0];
|
||||
};
|
||||
|
||||
export const listAllTransactionByWalletAddress = async (
|
||||
walletAddress: string
|
||||
walletAddress: Address
|
||||
): Promise<WalletTransaction[]> => {
|
||||
const p2pContract = await getContract(true);
|
||||
const user = useUser();
|
||||
|
||||
// Get deposits
|
||||
const filterDeposits = p2pContract.filters.DepositAdded([walletAddress]);
|
||||
const eventsDeposits = await p2pContract.queryFilter(
|
||||
filterDeposits,
|
||||
0,
|
||||
"latest"
|
||||
);
|
||||
console.log("Fetched all wallet deposits");
|
||||
// Get the current network for the subgraph URL
|
||||
const network = user.network.value;
|
||||
|
||||
// Get locks
|
||||
const filterAddedLocks = p2pContract.filters.LockAdded([walletAddress]);
|
||||
const eventsAddedLocks = await p2pContract.queryFilter(
|
||||
filterAddedLocks,
|
||||
0,
|
||||
"latest"
|
||||
);
|
||||
console.log("Fetched all wallet locks");
|
||||
// Query subgraph for all relevant transactions
|
||||
const subgraphQuery = {
|
||||
query: `
|
||||
{
|
||||
depositAddeds(where: {seller: "${walletAddress.toLowerCase()}"}) {
|
||||
id
|
||||
seller
|
||||
token
|
||||
amount
|
||||
blockTimestamp
|
||||
blockNumber
|
||||
transactionHash
|
||||
}
|
||||
lockAddeds(where: {buyer: "${walletAddress.toLowerCase()}"}) {
|
||||
buyer
|
||||
lockID
|
||||
seller
|
||||
amount
|
||||
blockTimestamp
|
||||
blockNumber
|
||||
transactionHash
|
||||
}
|
||||
lockReleaseds(where: {buyer: "${walletAddress.toLowerCase()}"}) {
|
||||
buyer
|
||||
lockId
|
||||
blockTimestamp
|
||||
blockNumber
|
||||
transactionHash
|
||||
}
|
||||
depositWithdrawns(where: {seller: "${walletAddress.toLowerCase()}"}) {
|
||||
seller
|
||||
token
|
||||
amount
|
||||
blockTimestamp
|
||||
blockNumber
|
||||
transactionHash
|
||||
}
|
||||
}
|
||||
`,
|
||||
};
|
||||
|
||||
// Get released locks
|
||||
const filterReleasedLocks = p2pContract.filters.LockReleased([walletAddress]);
|
||||
const eventsReleasedLocks = await p2pContract.queryFilter(
|
||||
filterReleasedLocks,
|
||||
0,
|
||||
"latest"
|
||||
);
|
||||
console.log("Fetched all wallet released locks");
|
||||
const response = await fetch(network.subgraphUrls[0], {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(subgraphQuery),
|
||||
});
|
||||
|
||||
// Get withdrawn deposits
|
||||
const filterWithdrawnDeposits = p2pContract.filters.DepositWithdrawn([
|
||||
walletAddress,
|
||||
]);
|
||||
const eventsWithdrawnDeposits = await p2pContract.queryFilter(
|
||||
filterWithdrawnDeposits
|
||||
);
|
||||
console.log("Fetched all wallet withdrawn deposits");
|
||||
const data = await response.json();
|
||||
// Convert all transactions to common WalletTransaction format
|
||||
const transactions: WalletTransaction[] = [];
|
||||
|
||||
const lockStatusFiltered = await filterLockStatus(
|
||||
[
|
||||
...eventsDeposits,
|
||||
...eventsAddedLocks,
|
||||
...eventsReleasedLocks,
|
||||
...eventsWithdrawnDeposits,
|
||||
].sort((a, b) => {
|
||||
return b.blockNumber - a.blockNumber;
|
||||
})
|
||||
);
|
||||
// Process deposit added events
|
||||
if (data.data?.depositAddeds) {
|
||||
for (const deposit of data.data.depositAddeds) {
|
||||
transactions.push({
|
||||
token: deposit.token,
|
||||
blockNumber: parseInt(deposit.blockNumber),
|
||||
amount: parseFloat(formatEther(BigInt(deposit.amount))),
|
||||
seller: deposit.seller,
|
||||
buyer: "",
|
||||
event: "DepositAdded",
|
||||
lockStatus: undefined,
|
||||
transactionHash: deposit.transactionHash,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return lockStatusFiltered;
|
||||
// Process lock added events
|
||||
if (data.data?.lockAddeds) {
|
||||
for (const lock of data.data.lockAddeds) {
|
||||
// Get lock status from the contract
|
||||
const lockStatus = await getLockStatus(BigInt(lock.lockID));
|
||||
|
||||
transactions.push({
|
||||
token: lock.token,
|
||||
blockNumber: parseInt(lock.blockNumber),
|
||||
amount: parseFloat(formatEther(BigInt(lock.amount))),
|
||||
seller: lock.seller,
|
||||
buyer: lock.buyer,
|
||||
event: "LockAdded",
|
||||
lockStatus: lockStatus,
|
||||
transactionHash: lock.transactionHash,
|
||||
transactionID: lock.lockID.toString(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Process lock released events
|
||||
if (data.data?.lockReleaseds) {
|
||||
for (const release of data.data.lockReleaseds) {
|
||||
transactions.push({
|
||||
token: undefined, // Subgraph doesn't provide token in this event, we could enhance this later
|
||||
blockNumber: parseInt(release.blockNumber),
|
||||
amount: -1, // Amount not available in this event
|
||||
seller: "",
|
||||
buyer: release.buyer,
|
||||
event: "LockReleased",
|
||||
lockStatus: undefined,
|
||||
transactionHash: release.transactionHash,
|
||||
transactionID: release.lockId.toString(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Process deposit withdrawn events
|
||||
if (data.data?.depositWithdrawns) {
|
||||
for (const withdrawal of data.data.depositWithdrawns) {
|
||||
transactions.push({
|
||||
token: withdrawal.token,
|
||||
blockNumber: parseInt(withdrawal.blockNumber),
|
||||
amount: parseFloat(formatEther(BigInt(withdrawal.amount))),
|
||||
seller: withdrawal.seller,
|
||||
buyer: "",
|
||||
event: "DepositWithdrawn",
|
||||
lockStatus: undefined,
|
||||
transactionHash: withdrawal.transactionHash,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Sort transactions by block number (newest first)
|
||||
return transactions.sort((a, b) => b.blockNumber - a.blockNumber);
|
||||
};
|
||||
|
||||
// get wallet's release transactions
|
||||
export const listReleaseTransactionByWalletAddress = async (
|
||||
walletAddress: string
|
||||
): Promise<LogDescription[]> => {
|
||||
const p2pContract = await getContract(true);
|
||||
walletAddress: Address
|
||||
) => {
|
||||
const user = useUser();
|
||||
const network = user.network.value;
|
||||
|
||||
const filterReleasedLocks = p2pContract.filters.LockReleased([walletAddress]);
|
||||
const eventsReleasedLocks = await p2pContract.queryFilter(
|
||||
filterReleasedLocks,
|
||||
0,
|
||||
"latest"
|
||||
);
|
||||
|
||||
return eventsReleasedLocks
|
||||
.sort((a, b) => {
|
||||
return b.blockNumber - a.blockNumber;
|
||||
})
|
||||
.map((lock) => {
|
||||
const IPix2Pix = new Interface(p2pix.abi);
|
||||
const decoded = IPix2Pix.parseLog({
|
||||
topics: lock.topics,
|
||||
data: lock.data,
|
||||
});
|
||||
return decoded;
|
||||
})
|
||||
.filter((lock) => lock !== null);
|
||||
};
|
||||
|
||||
const listLockTransactionByWalletAddress = async (
|
||||
walletAddress: string
|
||||
): Promise<LogDescription[]> => {
|
||||
const p2pContract = await getContract(true);
|
||||
|
||||
const filterAddedLocks = p2pContract.filters.LockAdded([walletAddress]);
|
||||
const eventsReleasedLocks = await p2pContract.queryFilter(filterAddedLocks);
|
||||
|
||||
return eventsReleasedLocks
|
||||
.sort((a, b) => {
|
||||
return b.blockNumber - a.blockNumber;
|
||||
})
|
||||
.map((lock) => {
|
||||
const IPix2Pix = new Interface(p2pix.abi);
|
||||
const decoded = IPix2Pix.parseLog({
|
||||
topics: lock.topics,
|
||||
data: lock.data,
|
||||
});
|
||||
return decoded;
|
||||
})
|
||||
.filter((lock) => lock !== null);
|
||||
};
|
||||
|
||||
const listLockTransactionBySellerAddress = async (
|
||||
sellerAddress: string
|
||||
): Promise<LogDescription[]> => {
|
||||
const p2pContract = await getContract(true);
|
||||
console.log("Will get locks as seller", sellerAddress);
|
||||
const filterAddedLocks = p2pContract.filters.LockAdded();
|
||||
const eventsReleasedLocks = await p2pContract.queryFilter(
|
||||
filterAddedLocks
|
||||
// 0,
|
||||
// "latest"
|
||||
);
|
||||
return eventsReleasedLocks
|
||||
.map((lock) => {
|
||||
const IPix2Pix = new Interface(p2pix.abi);
|
||||
const decoded = IPix2Pix.parseLog({
|
||||
topics: lock.topics,
|
||||
data: lock.data,
|
||||
});
|
||||
return decoded;
|
||||
})
|
||||
.filter((lock) => lock !== null)
|
||||
.filter(
|
||||
(lock) => lock.args.seller.toLowerCase() == sellerAddress.toLowerCase()
|
||||
);
|
||||
};
|
||||
|
||||
export const checkUnreleasedLock = async (
|
||||
walletAddress: string
|
||||
): Promise<UnreleasedLock | undefined> => {
|
||||
const p2pContract = await getContract();
|
||||
const pixData: Pix = {
|
||||
pixKey: "",
|
||||
// Query subgraph for release transactions
|
||||
const subgraphQuery = {
|
||||
query: `
|
||||
{
|
||||
lockReleaseds(where: {buyer: "${walletAddress.toLowerCase()}"}) {
|
||||
buyer
|
||||
lockId
|
||||
e2eId
|
||||
blockTimestamp
|
||||
blockNumber
|
||||
transactionHash
|
||||
}
|
||||
}
|
||||
`,
|
||||
};
|
||||
|
||||
const addedLocks = await listLockTransactionByWalletAddress(walletAddress);
|
||||
const lockStatus = await p2pContract.getLocksStatus(
|
||||
addedLocks.map((lock) => lock.args?.lockID)
|
||||
);
|
||||
const unreleasedLockId = lockStatus[1].findIndex(
|
||||
(lockStatus: number) => lockStatus == 1
|
||||
);
|
||||
// Fetch data from subgraph
|
||||
const response = await fetch(network.subgraphUrls[0], {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(subgraphQuery),
|
||||
});
|
||||
|
||||
if (unreleasedLockId != -1) {
|
||||
const _lockID = lockStatus[0][unreleasedLockId];
|
||||
const lock = await p2pContract.mapLocks(_lockID);
|
||||
const data = await response.json();
|
||||
|
||||
const pixTarget = lock.pixTarget;
|
||||
const amount = formatEther(lock?.amount);
|
||||
pixData.pixKey = pixTarget;
|
||||
pixData.value = Number(amount);
|
||||
// Process the subgraph response into the same format as the previous implementation
|
||||
if (!data.data?.lockReleaseds) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return {
|
||||
lockID: _lockID,
|
||||
pix: pixData,
|
||||
};
|
||||
// Transform the subgraph data to match the event log decode format
|
||||
return data.data.lockReleaseds
|
||||
.sort((a: any, b: any) => {
|
||||
return parseInt(b.blockNumber) - parseInt(a.blockNumber);
|
||||
})
|
||||
.map((release: any) => {
|
||||
try {
|
||||
// Create a structure similar to the decoded event log
|
||||
return {
|
||||
eventName: "LockReleased",
|
||||
args: {
|
||||
buyer: release.buyer,
|
||||
lockID: BigInt(release.lockId),
|
||||
e2eId: release.e2eId,
|
||||
},
|
||||
// Add any other necessary fields to match the original return format
|
||||
blockNumber: BigInt(release.blockNumber),
|
||||
transactionHash: release.transactionHash,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error processing subgraph data", error);
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter((decoded: any) => decoded !== null);
|
||||
};
|
||||
|
||||
const listLockTransactionByWalletAddress = async (walletAddress: Address) => {
|
||||
const user = useUser();
|
||||
const network = user.network.value;
|
||||
|
||||
// Query subgraph for lock added transactions
|
||||
const subgraphQuery = {
|
||||
query: `
|
||||
{
|
||||
lockAddeds(where: {buyer: "${walletAddress.toLowerCase()}"}) {
|
||||
buyer
|
||||
lockID
|
||||
seller
|
||||
amount
|
||||
blockTimestamp
|
||||
blockNumber
|
||||
transactionHash
|
||||
}
|
||||
}
|
||||
`,
|
||||
};
|
||||
|
||||
try {
|
||||
// Fetch data from subgraph
|
||||
const response = await fetch(network.subgraphUrls[0], {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(subgraphQuery),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!data.data?.lockAddeds) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Transform the subgraph data to match the event log decode format
|
||||
return data.data.lockAddeds
|
||||
.sort((a: any, b: any) => {
|
||||
return parseInt(b.blockNumber) - parseInt(a.blockNumber);
|
||||
})
|
||||
.map((lock: any) => {
|
||||
try {
|
||||
// Create a structure similar to the decoded event log
|
||||
return {
|
||||
eventName: "LockAdded",
|
||||
args: {
|
||||
buyer: lock.buyer,
|
||||
lockID: BigInt(lock.lockID),
|
||||
seller: lock.seller,
|
||||
token: lock.token,
|
||||
amount: BigInt(lock.amount),
|
||||
},
|
||||
// Add other necessary fields to match the original format
|
||||
blockNumber: BigInt(lock.blockNumber),
|
||||
transactionHash: lock.transactionHash,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error processing subgraph data", error);
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter((decoded: any) => decoded !== null);
|
||||
} catch (error) {
|
||||
console.error("Error fetching from subgraph:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const listLockTransactionBySellerAddress = async (sellerAddress: Address) => {
|
||||
const user = useUser();
|
||||
const network = user.network.value;
|
||||
|
||||
// Query subgraph for lock added transactions where seller matches
|
||||
const subgraphQuery = {
|
||||
query: `
|
||||
{
|
||||
lockAddeds(where: {seller: "${sellerAddress.toLowerCase()}"}) {
|
||||
buyer
|
||||
lockID
|
||||
seller
|
||||
token
|
||||
amount
|
||||
blockTimestamp
|
||||
blockNumber
|
||||
transactionHash
|
||||
}
|
||||
}
|
||||
`,
|
||||
};
|
||||
|
||||
try {
|
||||
// Fetch data from subgraph
|
||||
const response = await fetch(network.subgraphUrls[0], {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(subgraphQuery),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!data.data?.lockAddeds) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Transform the subgraph data to match the event log decode format
|
||||
return data.data.lockAddeds
|
||||
.sort((a: any, b: any) => {
|
||||
return parseInt(b.blockNumber) - parseInt(a.blockNumber);
|
||||
})
|
||||
.map((lock: any) => {
|
||||
try {
|
||||
// Create a structure similar to the decoded event log
|
||||
return {
|
||||
eventName: "LockAdded",
|
||||
args: {
|
||||
buyer: lock.buyer,
|
||||
lockID: BigInt(lock.lockID),
|
||||
seller: lock.seller,
|
||||
token: lock.token,
|
||||
amount: BigInt(lock.amount),
|
||||
},
|
||||
// Add other necessary fields to match the original format
|
||||
blockNumber: BigInt(lock.blockNumber),
|
||||
transactionHash: lock.transactionHash,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error processing subgraph data", error);
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter((decoded: any) => decoded !== null);
|
||||
} catch (error) {
|
||||
console.error("Error fetching from subgraph:", error);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const checkUnreleasedLock = async (
|
||||
walletAddress: Address
|
||||
): Promise<UnreleasedLock | undefined> => {
|
||||
const { address, abi, client } = await getContract();
|
||||
const addedLocks = await listLockTransactionByWalletAddress(walletAddress);
|
||||
|
||||
if (!addedLocks.length) return undefined;
|
||||
|
||||
const lockIds = addedLocks.map((lock: any) => lock.args.lockID);
|
||||
|
||||
const [ sortedIDs, status ] = await client.readContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "getLocksStatus",
|
||||
args: [lockIds],
|
||||
});
|
||||
|
||||
const unreleasedLockId = status.findIndex(
|
||||
(status: LockStatus) => status == LockStatus.Active
|
||||
);
|
||||
|
||||
if (unreleasedLockId !== -1)
|
||||
return getUnreleasedLockById(sortedIDs[unreleasedLockId]);
|
||||
};
|
||||
|
||||
export const getActiveLockAmount = async (
|
||||
walletAddress: string
|
||||
walletAddress: Address
|
||||
): Promise<number> => {
|
||||
const p2pContract = await getContract(true);
|
||||
const { address, abi, client } = await getContract(true);
|
||||
const lockSeller = await listLockTransactionBySellerAddress(walletAddress);
|
||||
|
||||
const lockStatus = await p2pContract.getLocksStatus(
|
||||
lockSeller.map((lock) => lock.args?.lockID)
|
||||
if (!lockSeller.length) return 0;
|
||||
|
||||
const lockIds = lockSeller.map((lock: any) => lock.args.lockID);
|
||||
|
||||
const [ sortedIDs, status ] = await client.readContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "getLocksStatus",
|
||||
args: [lockIds],
|
||||
});
|
||||
|
||||
const mapLocksRequests = status.map((id: LockStatus) =>
|
||||
client.readContract({
|
||||
address: address,
|
||||
abi,
|
||||
functionName: "mapLocks",
|
||||
args: [BigInt(id)],
|
||||
})
|
||||
);
|
||||
|
||||
const activeLockAmount = await lockStatus[1].reduce(
|
||||
async (sumValue: Promise<number>, currentStatus: number, index: number) => {
|
||||
const currValue = await sumValue;
|
||||
let valueToSum = 0;
|
||||
const mapLocksResults = await client.multicall({
|
||||
contracts: mapLocksRequests as any,
|
||||
});
|
||||
|
||||
if (currentStatus == 1) {
|
||||
const lock = await p2pContract.mapLocks(lockStatus[0][index]);
|
||||
valueToSum = Number(formatEther(lock?.amount));
|
||||
}
|
||||
|
||||
return currValue + valueToSum;
|
||||
},
|
||||
Promise.resolve(0)
|
||||
);
|
||||
|
||||
return activeLockAmount;
|
||||
return mapLocksResults.reduce((total: number, lock: any, index: number) => {
|
||||
if (status[index] === 1) {
|
||||
return total + Number(formatEther(lock.amount));
|
||||
}
|
||||
return total;
|
||||
}, 0);
|
||||
};
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import { mount } from "@vue/test-utils";
|
||||
import BuyConfirmedComponent from "../BuyConfirmedComponent.vue";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
|
||||
describe("BuyConfirmedComponent.vue", async () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
});
|
||||
|
||||
const wrapper = mount(BuyConfirmedComponent, {
|
||||
props: {
|
||||
tokenAmount: 1,
|
||||
isCurrentStep: false,
|
||||
},
|
||||
});
|
||||
|
||||
// test("Test component Header Text", () => {
|
||||
// expect(wrapper.html()).toContain("Os tokens já foram transferidos");
|
||||
// expect(wrapper.html()).toContain("para a sua carteira!");
|
||||
// });
|
||||
|
||||
// test("Test component Container Text", () => {
|
||||
// expect(wrapper.html()).toContain("Tokens recebidos");
|
||||
// expect(wrapper.html()).toContain("BRZ");
|
||||
// expect(wrapper.html()).toContain("Não encontrou os tokens?");
|
||||
// expect(wrapper.html()).toContain("Clique no botão abaixo para");
|
||||
// expect(wrapper.html()).toContain("cadastrar o BRZ em sua carteira.");
|
||||
// });
|
||||
|
||||
test("Test makeAnotherTransactionEmit", async () => {
|
||||
wrapper.vm.$emit("makeAnotherTransaction");
|
||||
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
expect(wrapper.emitted("makeAnotherTransaction")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -5,13 +5,12 @@ import {
|
||||
listAllTransactionByWalletAddress,
|
||||
listValidDepositTransactionsByWalletAddress,
|
||||
} from "@/blockchain/wallet";
|
||||
import CustomButton from "@/components/CustomButton/CustomButton.vue";
|
||||
import CustomButton from "@/components/ui/CustomButton.vue";
|
||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||
import type { WalletTransaction } from "@/model/WalletTransaction";
|
||||
import { useEtherStore } from "@/store/ether";
|
||||
import { storeToRefs } from "pinia";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
import { onMounted, ref, watch } from "vue";
|
||||
import ListingComponent from "../ListingComponent/ListingComponent.vue";
|
||||
import ListingComponent from "@/components/ListingComponent/ListingComponent.vue";
|
||||
|
||||
// props
|
||||
const props = defineProps<{
|
||||
@@ -19,8 +18,8 @@ const props = defineProps<{
|
||||
isCurrentStep: boolean;
|
||||
}>();
|
||||
|
||||
const etherStore = useEtherStore();
|
||||
const { walletAddress } = storeToRefs(etherStore);
|
||||
const user = useUser();
|
||||
const { walletAddress } = useUser();
|
||||
|
||||
const lastWalletTransactions = ref<WalletTransaction[]>([]);
|
||||
const depositList = ref<ValidDeposit[]>([]);
|
||||
@@ -29,7 +28,7 @@ const activeLockAmount = ref<number>(0);
|
||||
// methods
|
||||
|
||||
const getWalletTransactions = async () => {
|
||||
etherStore.setLoadingWalletTransactions(true);
|
||||
user.setLoadingWalletTransactions(true);
|
||||
if (walletAddress.value) {
|
||||
const walletDeposits = await listValidDepositTransactionsByWalletAddress(
|
||||
walletAddress.value
|
||||
@@ -48,20 +47,20 @@ const getWalletTransactions = async () => {
|
||||
lastWalletTransactions.value = allUserTransactions;
|
||||
}
|
||||
}
|
||||
etherStore.setLoadingWalletTransactions(false);
|
||||
user.setLoadingWalletTransactions(false);
|
||||
};
|
||||
|
||||
const callWithdraw = async (amount: string) => {
|
||||
if (amount) {
|
||||
etherStore.setLoadingWalletTransactions(true);
|
||||
const withdraw = await withdrawDeposit(amount, etherStore.selectedToken);
|
||||
user.setLoadingWalletTransactions(true);
|
||||
const withdraw = await withdrawDeposit(amount, user.network.value.tokens[user.selectedToken.value].address);
|
||||
if (withdraw) {
|
||||
console.log("Saque realizado!");
|
||||
await getWalletTransactions();
|
||||
} else {
|
||||
console.log("Não foi possível realizar o saque!");
|
||||
}
|
||||
etherStore.setLoadingWalletTransactions(false);
|
||||
user.setLoadingWalletTransactions(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -93,14 +92,14 @@ onMounted(async () => {
|
||||
<div>
|
||||
<p>Tokens recebidos</p>
|
||||
<p class="text-2xl text-gray-900">
|
||||
{{ props.tokenAmount }} {{ etherStore.selectedToken }}
|
||||
{{ props.tokenAmount }} {{ user.selectedToken }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="my-5">
|
||||
<p class="text-sm">
|
||||
<b>Não encontrou os tokens? </b><br />Clique no botão abaixo para
|
||||
<br />
|
||||
cadastrar o {{ etherStore.selectedToken }} em sua carteira.
|
||||
cadastrar o {{ user.selectedToken }} em sua carteira.
|
||||
</p>
|
||||
</div>
|
||||
<CustomButton :text="'Cadastrar token'" @buttonClicked="() => {}" />
|
||||
@@ -150,10 +149,6 @@ p {
|
||||
@apply font-medium text-base text-gray-900;
|
||||
}
|
||||
|
||||
input[type="number"] {
|
||||
-moz-appearance: textfield;
|
||||
}
|
||||
|
||||
input[type="number"]::-webkit-inner-spin-button,
|
||||
input[type="number"]::-webkit-outer-spin-button {
|
||||
-webkit-appearance: none;
|
||||
@@ -1,30 +1,28 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from "vue";
|
||||
import CustomButton from "@/components/CustomButton/CustomButton.vue";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
import SpinnerComponent from "@/components/ui/SpinnerComponent.vue";
|
||||
import CustomButton from "@/components/ui/CustomButton.vue";
|
||||
import { debounce } from "@/utils/debounce";
|
||||
import { useEtherStore } from "@/store/ether";
|
||||
import { storeToRefs } from "pinia";
|
||||
import { verifyNetworkLiquidity } from "@/utils/networkLiquidity";
|
||||
import { NetworkEnum } from "@/model/NetworkEnum";
|
||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||
import { decimalCount } from "@/utils/decimalCount";
|
||||
import SpinnerComponent from "./SpinnerComponent.vue";
|
||||
import { getTokenImage } from "@/utils/imagesPath";
|
||||
import { onClickOutside } from "@vueuse/core";
|
||||
|
||||
import { Networks } from "@/config/networks";
|
||||
import { TokenEnum } from "@/model/NetworkEnum";
|
||||
|
||||
// Store reference
|
||||
const etherStore = useEtherStore();
|
||||
const user = useUser();
|
||||
const selectTokenToggle = ref<boolean>(false);
|
||||
|
||||
const {
|
||||
walletAddress,
|
||||
networkName,
|
||||
network,
|
||||
selectedToken,
|
||||
depositsValidList,
|
||||
loadingNetworkLiquidity,
|
||||
} = storeToRefs(etherStore);
|
||||
} = user;
|
||||
|
||||
// html references
|
||||
const tokenDropdownRef = ref<any>(null);
|
||||
@@ -34,11 +32,12 @@ const tokenValue = ref<number>(0);
|
||||
const enableConfirmButton = ref<boolean>(false);
|
||||
const hasLiquidity = ref<boolean>(true);
|
||||
const validDecimals = ref<boolean>(true);
|
||||
const identification = ref<string>("");
|
||||
const selectedDeposits = ref<ValidDeposit[]>();
|
||||
|
||||
import ChevronDown from "@/assets/chevronDown.svg";
|
||||
import { useOnboard } from "@web3-onboard/vue";
|
||||
import { getPixKey } from "@/blockchain/events";
|
||||
import { getParticipantID } from "@/blockchain/events";
|
||||
|
||||
// Emits
|
||||
const emit = defineEmits(["tokenBuy"]);
|
||||
@@ -51,10 +50,10 @@ const connectAccount = async (): Promise<void> => {
|
||||
|
||||
const emitConfirmButton = async (): Promise<void> => {
|
||||
const deposit = selectedDeposits.value?.find(
|
||||
(d) => d.network === networkName.value
|
||||
(d) => d.network === network.value
|
||||
);
|
||||
if (!deposit) return;
|
||||
deposit.pixKey = await getPixKey(deposit.seller, deposit.token);
|
||||
deposit.participantID = await getParticipantID(deposit.seller, deposit.token);
|
||||
emit("tokenBuy", deposit, tokenValue.value);
|
||||
};
|
||||
|
||||
@@ -83,33 +82,42 @@ onClickOutside(tokenDropdownRef, () => {
|
||||
});
|
||||
|
||||
const handleSelectedToken = (token: TokenEnum): void => {
|
||||
etherStore.setSelectedToken(token);
|
||||
user.setSelectedToken(token);
|
||||
selectTokenToggle.value = false;
|
||||
};
|
||||
|
||||
// Verify if there is a valid deposit to buy
|
||||
const verifyLiquidity = (): void => {
|
||||
enableConfirmButton.value = false;
|
||||
if (!walletAddress.value)
|
||||
return;
|
||||
const selDeposits = verifyNetworkLiquidity(
|
||||
tokenValue.value,
|
||||
walletAddress.value,
|
||||
depositsValidList.value
|
||||
);
|
||||
|
||||
selectedDeposits.value = selDeposits;
|
||||
hasLiquidity.value = !!selDeposits.find(
|
||||
(d) => d.network === networkName.value
|
||||
(d) => d.network === network.value
|
||||
);
|
||||
enableOrDisableConfirmButton();
|
||||
};
|
||||
|
||||
const enableOrDisableConfirmButton = (): void => {
|
||||
enableConfirmButton.value =
|
||||
!!selectedDeposits.value &&
|
||||
!!selectedDeposits.value.find((d) => d.network === networkName.value);
|
||||
if (!selectedDeposits.value) {
|
||||
enableConfirmButton.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!selectedDeposits.value.find((d) => d.network === network.value)) {
|
||||
enableConfirmButton.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
enableConfirmButton.value = true;
|
||||
};
|
||||
|
||||
watch(networkName, (): void => {
|
||||
watch(network, (): void => {
|
||||
verifyLiquidity();
|
||||
enableOrDisableConfirmButton();
|
||||
});
|
||||
@@ -117,6 +125,16 @@ watch(networkName, (): void => {
|
||||
watch(walletAddress, (): void => {
|
||||
verifyLiquidity();
|
||||
});
|
||||
|
||||
// Add form submission handler
|
||||
const handleSubmit = async (e: Event): Promise<void> => {
|
||||
e.preventDefault();
|
||||
if (walletAddress.value) {
|
||||
await emitConfirmButton();
|
||||
} else {
|
||||
await connectAccount();
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -132,7 +150,7 @@ watch(walletAddress, (): void => {
|
||||
tokens após realizar o Pix</span
|
||||
>
|
||||
</div>
|
||||
<div class="main-container">
|
||||
<form class="main-container" @submit="handleSubmit">
|
||||
<div class="backdrop-blur -z-10 w-full h-full"></div>
|
||||
<div
|
||||
class="flex flex-col w-full bg-white sm:px-10 px-6 py-5 rounded-lg border-y-10"
|
||||
@@ -140,14 +158,16 @@ watch(walletAddress, (): void => {
|
||||
<div class="flex justify-between sm:w-full items-center">
|
||||
<input
|
||||
type="number"
|
||||
name="tokenAmount"
|
||||
class="border-none outline-none text-lg text-gray-900"
|
||||
v-bind:class="{
|
||||
'font-semibold': tokenValue != undefined,
|
||||
'text-xl': tokenValue != undefined,
|
||||
}"
|
||||
@input="debounce(handleInputEvent, 500)($event)"
|
||||
placeholder="0 "
|
||||
placeholder="0"
|
||||
step=".01"
|
||||
required
|
||||
/>
|
||||
<div class="relative overflow-visible">
|
||||
<button
|
||||
@@ -218,7 +238,7 @@ watch(walletAddress, (): void => {
|
||||
height="24"
|
||||
v-if="
|
||||
selectedDeposits &&
|
||||
selectedDeposits.find((d) => d.network == NetworkEnum.rootstock)
|
||||
selectedDeposits.find((d) => d.network == Networks.rootstockTestnet)
|
||||
"
|
||||
/>
|
||||
<img
|
||||
@@ -228,7 +248,7 @@ watch(walletAddress, (): void => {
|
||||
height="24"
|
||||
v-if="
|
||||
selectedDeposits &&
|
||||
selectedDeposits.find((d) => d.network == NetworkEnum.sepolia)
|
||||
selectedDeposits.find((d) => d.network == Networks.sepolia)
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
@@ -252,7 +272,9 @@ watch(walletAddress, (): void => {
|
||||
</div>
|
||||
<div
|
||||
class="flex justify-center"
|
||||
v-else-if="!hasLiquidity && !loadingNetworkLiquidity"
|
||||
v-else-if="
|
||||
!hasLiquidity && !loadingNetworkLiquidity && tokenValue > 0
|
||||
"
|
||||
>
|
||||
<span class="text-red-500 font-normal text-sm"
|
||||
>Atualmente não há liquidez nas rede selecionada para sua
|
||||
@@ -260,18 +282,33 @@ watch(walletAddress, (): void => {
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
<CustomButton
|
||||
v-if="!walletAddress"
|
||||
:text="'Conectar carteira'"
|
||||
@buttonClicked="connectAccount()"
|
||||
/>
|
||||
|
||||
<div
|
||||
class="flex flex-col w-full bg-white sm:px-10 px-6 py-4 rounded-lg border-y-10"
|
||||
>
|
||||
<input
|
||||
type="text"
|
||||
v-model="identification"
|
||||
maxlength="14"
|
||||
:pattern="'^\\d{11}$|^\\d{14}$'"
|
||||
class="border-none outline-none sm:text-lg text-sm text-gray-900 w-full"
|
||||
placeholder="Digite seu CPF ou CNPJ (somente números)"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Action buttons -->
|
||||
<CustomButton
|
||||
v-if="walletAddress"
|
||||
:text="'Confirmar compra'"
|
||||
:is-disabled="!enableConfirmButton"
|
||||
@buttonClicked="emitConfirmButton()"
|
||||
type="submit"
|
||||
text="Confirmar Oferta"
|
||||
/>
|
||||
</div>
|
||||
<CustomButton
|
||||
v-else
|
||||
text="Conectar carteira"
|
||||
@buttonClicked="connectAccount()"
|
||||
/>
|
||||
</form>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -306,4 +343,10 @@ input[type="number"]::-webkit-inner-spin-button,
|
||||
input[type="number"]::-webkit-outer-spin-button {
|
||||
-webkit-appearance: none;
|
||||
}
|
||||
|
||||
.custom-button {
|
||||
@apply w-full py-3 px-6 rounded-lg font-semibold text-white bg-indigo-600
|
||||
hover:bg-indigo-700 disabled:bg-gray-400 disabled:cursor-not-allowed
|
||||
transition-colors duration-200;
|
||||
}
|
||||
</style>
|
||||
294
src/components/BuyerSteps/QrCodeComponent.vue
Normal file
@@ -0,0 +1,294 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, onUnmounted } from "vue";
|
||||
import CustomButton from "@/components/ui/CustomButton.vue";
|
||||
import CustomModal from "@/components/ui/CustomModal.vue";
|
||||
import SpinnerComponent from "@/components/ui/SpinnerComponent.vue";
|
||||
import { createSolicitation, getSolicitation, type Offer } from "@/utils/bbPay";
|
||||
import { getParticipantID } from "@/blockchain/events";
|
||||
import { getUnreleasedLockById } from "@/blockchain/events";
|
||||
import QRCode from "qrcode";
|
||||
|
||||
// Props
|
||||
interface Props {
|
||||
lockID: string;
|
||||
}
|
||||
|
||||
const props = defineProps<Props>();
|
||||
|
||||
const qrCode = ref<string>("");
|
||||
const qrCodeSvg = ref<string>("");
|
||||
const showWarnModal = ref<boolean>(true);
|
||||
const pixTimestamp = ref<string>("");
|
||||
const releaseSignature = ref<string>("");
|
||||
const solicitationData = ref<any>(null);
|
||||
const pollingInterval = ref<NodeJS.Timeout | null>(null);
|
||||
const copyFeedback = ref<boolean>(false);
|
||||
const copyFeedbackTimeout = ref<NodeJS.Timeout | null>(null);
|
||||
|
||||
// Function to generate QR code SVG
|
||||
const generateQrCodeSvg = async (text: string) => {
|
||||
try {
|
||||
const svgString = await QRCode.toString(text, {
|
||||
type: "svg",
|
||||
width: 192, // 48 * 4 for better quality
|
||||
margin: 2,
|
||||
color: {
|
||||
dark: "#000000",
|
||||
light: "#FFFFFF",
|
||||
},
|
||||
});
|
||||
qrCodeSvg.value = svgString;
|
||||
} catch (error) {
|
||||
console.error("Error generating QR code SVG:", error);
|
||||
}
|
||||
};
|
||||
|
||||
// Emits
|
||||
const emit = defineEmits(["pixValidated"]);
|
||||
|
||||
// Function to check solicitation status
|
||||
const checkSolicitationStatus = async () => {
|
||||
if (!solicitationData.value?.numeroSolicitacao) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await getSolicitation(
|
||||
solicitationData.value.numeroSolicitacao
|
||||
);
|
||||
|
||||
if (response.signature) {
|
||||
pixTimestamp.value = response.pixTimestamp;
|
||||
releaseSignature.value = response.signature;
|
||||
// Stop polling when payment is confirmed
|
||||
if (pollingInterval.value) {
|
||||
clearInterval(pollingInterval.value);
|
||||
pollingInterval.value = null;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error checking solicitation status:", error);
|
||||
}
|
||||
};
|
||||
|
||||
// Function to start polling
|
||||
const startPolling = () => {
|
||||
// Clear any existing interval
|
||||
if (pollingInterval.value) {
|
||||
clearInterval(pollingInterval.value);
|
||||
}
|
||||
|
||||
// Start new polling interval (10 seconds)
|
||||
pollingInterval.value = setInterval(checkSolicitationStatus, 10000);
|
||||
};
|
||||
|
||||
|
||||
const copyToClipboard = async () => {
|
||||
if (!qrCode.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await navigator.clipboard.writeText(qrCode.value);
|
||||
|
||||
if (copyFeedbackTimeout.value) {
|
||||
clearTimeout(copyFeedbackTimeout.value);
|
||||
}
|
||||
|
||||
copyFeedback.value = true;
|
||||
|
||||
copyFeedbackTimeout.value = setTimeout(() => {
|
||||
copyFeedback.value = false;
|
||||
}, 2000);
|
||||
} catch (error) {
|
||||
console.error("Error copying to clipboard:", error);
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const { tokenAddress, sellerAddress, amount } = await getUnreleasedLockById(
|
||||
BigInt(props.lockID)
|
||||
);
|
||||
|
||||
const participantId = await getParticipantID(
|
||||
sellerAddress,
|
||||
tokenAddress
|
||||
);
|
||||
|
||||
const offer: Offer = {
|
||||
amount,
|
||||
sellerId: participantId,
|
||||
};
|
||||
|
||||
const response = await createSolicitation(offer);
|
||||
solicitationData.value = response;
|
||||
|
||||
// Update qrCode if the response contains QR code data
|
||||
if (response?.informacoesPIX?.textoQrCode) {
|
||||
qrCode.value = response.informacoesPIX?.textoQrCode;
|
||||
// Generate SVG QR code
|
||||
await generateQrCodeSvg(qrCode.value);
|
||||
}
|
||||
|
||||
// Start polling for solicitation status
|
||||
startPolling();
|
||||
} catch (error) {
|
||||
console.error("Error creating solicitation:", error);
|
||||
}
|
||||
});
|
||||
|
||||
// Clean up interval on component unmount
|
||||
onUnmounted(() => {
|
||||
if (pollingInterval.value) {
|
||||
clearInterval(pollingInterval.value);
|
||||
pollingInterval.value = null;
|
||||
}
|
||||
if (copyFeedbackTimeout.value) {
|
||||
clearTimeout(copyFeedbackTimeout.value);
|
||||
copyFeedbackTimeout.value = null;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<div class="text-container">
|
||||
<span
|
||||
class="text font-extrabold lg:text-2xl text-xl sm:max-w-[30rem] max-w-[24rem]"
|
||||
>
|
||||
Utilize o QR Code ou copie o código para realizar o Pix
|
||||
</span>
|
||||
<span class="text font-medium lg:text-md text-sm max-w-[28rem]">
|
||||
Após realizar o Pix no banco de sua preferência, clique no botão abaixo
|
||||
para liberação dos tokens.
|
||||
</span>
|
||||
</div>
|
||||
<div class="main-container max-w-md text-black">
|
||||
<div
|
||||
class="flex-col items-center justify-center flex w-full bg-white sm:p-8 p-4 rounded-lg break-normal"
|
||||
>
|
||||
<div
|
||||
v-if="qrCodeSvg"
|
||||
v-html="qrCodeSvg"
|
||||
class="w-48 h-48 flex items-center justify-center"
|
||||
></div>
|
||||
<div
|
||||
v-else
|
||||
class="w-48 h-48 flex items-center justify-center rounded-lg"
|
||||
>
|
||||
<SpinnerComponent width="8" height="8"></SpinnerComponent>
|
||||
</div>
|
||||
<span class="text-center font-bold">Código pix</span>
|
||||
<div class="break-words w-4/5">
|
||||
<span class="text-center text-xs">
|
||||
{{ qrCode }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex flex-col items-center gap-1">
|
||||
<img
|
||||
alt="Copy PIX code"
|
||||
src="@/assets/copyPix.svg?url"
|
||||
width="16"
|
||||
height="16"
|
||||
class="pt-2 cursor-pointer hover:opacity-70 transition-opacity"
|
||||
@click="copyToClipboard"
|
||||
/>
|
||||
<transition name="fade">
|
||||
<span
|
||||
v-if="copyFeedback"
|
||||
class="text-xs text-emerald-500 font-semibold"
|
||||
>
|
||||
Código copiado!
|
||||
</span>
|
||||
</transition>
|
||||
</div>
|
||||
</div>
|
||||
<CustomButton
|
||||
:is-disabled="releaseSignature === ''"
|
||||
:text="
|
||||
releaseSignature ? 'Enviar para a rede' : 'Validando pagamento...'
|
||||
"
|
||||
@button-clicked="
|
||||
emit('pixValidated', { pixTimestamp, signature: releaseSignature })
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
<CustomModal
|
||||
v-if="showWarnModal"
|
||||
@close-modal="showWarnModal = false"
|
||||
:isRedirectModal="false"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.page {
|
||||
@apply flex flex-col items-center justify-center w-full mt-16;
|
||||
}
|
||||
|
||||
::placeholder {
|
||||
/* Most modern browsers support this now. */
|
||||
color: #9ca3af;
|
||||
}
|
||||
|
||||
h4 {
|
||||
color: #080808;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
h2 {
|
||||
color: #080808;
|
||||
}
|
||||
|
||||
.form-input {
|
||||
@apply rounded-lg border border-gray-200 p-2 text-black;
|
||||
}
|
||||
|
||||
.form-label {
|
||||
@apply font-semibold tracking-wide text-emerald-50;
|
||||
}
|
||||
|
||||
.custom-divide {
|
||||
width: 100%;
|
||||
border-bottom: 1px solid #d1d5db;
|
||||
}
|
||||
.bottom-position {
|
||||
top: -20px;
|
||||
right: 50%;
|
||||
transform: translateX(50%);
|
||||
}
|
||||
|
||||
.text-container {
|
||||
@apply flex flex-col items-center justify-center gap-4;
|
||||
}
|
||||
|
||||
.text {
|
||||
@apply text-white text-center;
|
||||
}
|
||||
|
||||
.blur-container {
|
||||
@apply flex flex-col justify-center items-center px-8 py-6 gap-2 rounded-lg shadow-md shadow-gray-600 backdrop-blur-md mt-6 max-w-screen-sm;
|
||||
}
|
||||
|
||||
input[type="number"] {
|
||||
appearance: textfield;
|
||||
-moz-appearance: textfield;
|
||||
}
|
||||
|
||||
input[type="number"]::-webkit-inner-spin-button,
|
||||
input[type="number"]::-webkit-outer-spin-button {
|
||||
-webkit-appearance: none;
|
||||
}
|
||||
|
||||
/* Fade transition for copy feedback */
|
||||
.fade-enter-active,
|
||||
.fade-leave-active {
|
||||
transition: opacity 0.3s ease;
|
||||
}
|
||||
|
||||
.fade-enter-from,
|
||||
.fade-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
</style>
|
||||
@@ -1,26 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
const props = defineProps({
|
||||
text: String,
|
||||
isDisabled: Boolean,
|
||||
});
|
||||
|
||||
const emit = defineEmits(["buttonClicked"]);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button
|
||||
type="button"
|
||||
class="button"
|
||||
@click="emit('buttonClicked')"
|
||||
v-bind:class="{ 'opacity-70': props.isDisabled }"
|
||||
:disabled="props.isDisabled ? props.isDisabled : false"
|
||||
>
|
||||
{{ props.text }}
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.button {
|
||||
@apply rounded-lg w-full text-base font-semibold text-gray-900 p-4 bg-amber-400;
|
||||
}
|
||||
</style>
|
||||
@@ -1,27 +0,0 @@
|
||||
import { mount } from "@vue/test-utils";
|
||||
import CustomButton from "../CustomButton.vue";
|
||||
|
||||
describe("CustomButton.vue", () => {
|
||||
test("Test button content", () => {
|
||||
const wrapper = mount(CustomButton, {
|
||||
props: {
|
||||
text: "Testing",
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.html()).toContain("Testing");
|
||||
});
|
||||
|
||||
test("Test if disabled props works", () => {
|
||||
const wrapper = mount(CustomButton, {
|
||||
props: {
|
||||
isDisabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
//@ts-ignore
|
||||
const button = wrapper.find(".button") as HTMLButtonElement;
|
||||
//@ts-ignore
|
||||
expect(button.element.disabled).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,27 +0,0 @@
|
||||
import { mount } from "@vue/test-utils";
|
||||
import CustomModal from "../CustomModal.vue";
|
||||
|
||||
describe("CustomModal test", () => {
|
||||
test("Test custom modal when receive is redirect modal props as false", () => {
|
||||
const wrapper = mount(CustomModal, {
|
||||
props: {
|
||||
isRedirectModal: false,
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.html()).toContain("ATENÇÃO!");
|
||||
expect(wrapper.html()).toContain("Entendi");
|
||||
});
|
||||
|
||||
test("Test custom modal when receive is redirect modal props as true", () => {
|
||||
const wrapper = mount(CustomModal, {
|
||||
props: {
|
||||
isRedirectModal: true,
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.html()).toContain("Retomar a última compra?");
|
||||
expect(wrapper.html()).toContain("Não");
|
||||
expect(wrapper.html()).toContain("Sim");
|
||||
});
|
||||
});
|
||||
215
src/components/ListingComponent/BalanceCard.vue
Normal file
@@ -0,0 +1,215 @@
|
||||
<script setup lang="ts">
|
||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||
import { ref, watch, onMounted, computed } from "vue";
|
||||
import { debounce } from "@/utils/debounce";
|
||||
import { decimalCount } from "@/utils/decimalCount";
|
||||
import { useFloating, arrow, offset, flip, shift } from "@floating-ui/vue";
|
||||
import IconButton from "../ui/IconButton.vue";
|
||||
import withdrawIcon from "@/assets/withdraw.svg?url";
|
||||
|
||||
const props = defineProps<{
|
||||
validDeposits: ValidDeposit[];
|
||||
activeLockAmount: number;
|
||||
selectedToken: string;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
withdraw: [amount: string];
|
||||
}>();
|
||||
|
||||
const withdrawAmount = ref<string>("");
|
||||
const isCollapsibleOpen = ref<boolean>(false);
|
||||
const validDecimals = ref<boolean>(true);
|
||||
const validWithdrawAmount = ref<boolean>(true);
|
||||
const enableConfirmButton = ref<boolean>(false);
|
||||
const showInfoTooltip = ref<boolean>(false);
|
||||
const floatingArrow = ref(null);
|
||||
|
||||
const reference = ref<HTMLElement | null>(null);
|
||||
const floating = ref<HTMLElement | null>(null);
|
||||
const infoText = ref<HTMLElement | null>(null);
|
||||
|
||||
const remaining = computed(() => {
|
||||
if (props.validDeposits.length > 0) {
|
||||
const deposit = props.validDeposits[0];
|
||||
return deposit ? deposit.remaining : 0;
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
|
||||
const handleInputEvent = (event: any): void => {
|
||||
const { value } = event.target;
|
||||
|
||||
if (decimalCount(String(value)) > 2) {
|
||||
validDecimals.value = false;
|
||||
enableConfirmButton.value = false;
|
||||
return;
|
||||
}
|
||||
validDecimals.value = true;
|
||||
|
||||
if (value > remaining.value) {
|
||||
validWithdrawAmount.value = false;
|
||||
enableConfirmButton.value = false;
|
||||
return;
|
||||
}
|
||||
validWithdrawAmount.value = true;
|
||||
enableConfirmButton.value = true;
|
||||
};
|
||||
|
||||
const callWithdraw = () => {
|
||||
if (enableConfirmButton.value && withdrawAmount.value) {
|
||||
emit("withdraw", withdrawAmount.value);
|
||||
// Reset form after withdraw
|
||||
withdrawAmount.value = "";
|
||||
isCollapsibleOpen.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const openWithdrawForm = () => {
|
||||
isCollapsibleOpen.value = true;
|
||||
};
|
||||
|
||||
const cancelWithdraw = () => {
|
||||
isCollapsibleOpen.value = false;
|
||||
withdrawAmount.value = "";
|
||||
validDecimals.value = true;
|
||||
validWithdrawAmount.value = true;
|
||||
enableConfirmButton.value = false;
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
useFloating(reference, floating, {
|
||||
placement: "right",
|
||||
middleware: [
|
||||
offset(10),
|
||||
flip(),
|
||||
shift(),
|
||||
arrow({ element: floatingArrow }),
|
||||
],
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="w-full bg-white p-4 sm:p-6 rounded-lg">
|
||||
<div class="flex justify-between items-center">
|
||||
<div>
|
||||
<p class="text-sm leading-5 font-medium text-gray-600">
|
||||
Saldo disponível
|
||||
</p>
|
||||
<p class="text-xl leading-7 font-semibold text-gray-900">
|
||||
{{ remaining }} {{ selectedToken }}
|
||||
</p>
|
||||
<div class="flex gap-2 w-32 sm:w-56" v-if="activeLockAmount != 0">
|
||||
<span class="text-xs font-normal text-gray-400" ref="infoText">
|
||||
{{ `com ${activeLockAmount.toFixed(2)} ${selectedToken} em lock` }}
|
||||
</span>
|
||||
<div
|
||||
class="absolute mt-[2px] md-view"
|
||||
:style="{ left: `${(infoText?.clientWidth ?? 108) + 4}px` }"
|
||||
>
|
||||
<img
|
||||
alt="info image"
|
||||
src="@/assets/info.svg?url"
|
||||
aria-describedby="tooltip"
|
||||
ref="reference"
|
||||
@mouseover="showInfoTooltip = true"
|
||||
@mouseout="showInfoTooltip = false"
|
||||
/>
|
||||
<div
|
||||
role="tooltip"
|
||||
ref="floating"
|
||||
class="w-56 z-50 tooltip md-view"
|
||||
v-if="showInfoTooltip"
|
||||
>
|
||||
Valor "em lock" significa que a quantia está aguardando
|
||||
confirmação de compra e só estará disponível para saque caso a
|
||||
transação expire.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-show="!isCollapsibleOpen" class="flex justify-end items-center">
|
||||
<IconButton
|
||||
text="Sacar"
|
||||
:icon="withdrawIcon"
|
||||
variant="outline"
|
||||
size="md"
|
||||
:full-width="false"
|
||||
@click="openWithdrawForm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pt-5">
|
||||
<div v-show="isCollapsibleOpen" class="py-2 w-100">
|
||||
<p class="text-sm leading-5 font-medium">Valor do saque</p>
|
||||
<input
|
||||
type="number"
|
||||
@input="debounce(handleInputEvent, 500)($event)"
|
||||
placeholder="0"
|
||||
class="text-2xl text-gray-900 w-full outline-none"
|
||||
v-model="withdrawAmount"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex justify-center" v-if="!validDecimals">
|
||||
<span class="text-red-500 font-normal text-sm">
|
||||
Por favor utilize no máximo 2 casas decimais
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex justify-center" v-else-if="!validWithdrawAmount">
|
||||
<span class="text-red-500 font-normal text-sm">
|
||||
Saldo insuficiente
|
||||
</span>
|
||||
</div>
|
||||
<hr v-show="isCollapsibleOpen" class="pb-3" />
|
||||
<div
|
||||
v-show="isCollapsibleOpen"
|
||||
class="flex justify-between items-center"
|
||||
>
|
||||
<h1
|
||||
@click="cancelWithdraw"
|
||||
class="text-black font-medium cursor-pointer hover:text-gray-600 transition-colors"
|
||||
>
|
||||
Cancelar
|
||||
</h1>
|
||||
|
||||
<IconButton
|
||||
text="Sacar"
|
||||
:icon="withdrawIcon"
|
||||
variant="outline"
|
||||
size="md"
|
||||
:full-width="false"
|
||||
:disabled="!enableConfirmButton"
|
||||
@click="callWithdraw"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
p {
|
||||
@apply text-gray-900;
|
||||
}
|
||||
|
||||
.tooltip {
|
||||
@apply bg-white text-gray-900 font-medium text-xs md:text-base px-3 py-2 rounded border-2 border-emerald-500 left-5 top-[-3rem];
|
||||
}
|
||||
|
||||
input[type="number"] {
|
||||
appearance: textfield;
|
||||
-moz-appearance: textfield;
|
||||
}
|
||||
|
||||
input[type="number"]::-webkit-inner-spin-button,
|
||||
input[type="number"]::-webkit-outer-spin-button {
|
||||
-webkit-appearance: none;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 640px) {
|
||||
.md-view {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,18 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
import { withdrawDeposit } from "@/blockchain/buyerMethods";
|
||||
import { NetworkEnum } from "@/model/NetworkEnum";
|
||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||
import type { WalletTransaction } from "@/model/WalletTransaction";
|
||||
import { useEtherStore } from "@/store/ether";
|
||||
import { storeToRefs } from "pinia";
|
||||
import { ref, watch, onMounted } from "vue";
|
||||
import SpinnerComponent from "../SpinnerComponent.vue";
|
||||
import { decimalCount } from "@/utils/decimalCount";
|
||||
import { debounce } from "@/utils/debounce";
|
||||
import { getTokenByAddress } from "@/blockchain/addresses";
|
||||
import { useFloating, arrow, offset, flip, shift } from "@floating-ui/vue";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
import { ref, watch } from "vue";
|
||||
import SpinnerComponent from "../ui/SpinnerComponent.vue";
|
||||
import BalanceCard from "./BalanceCard.vue";
|
||||
import TransactionCard from "./TransactionCard.vue";
|
||||
|
||||
const etherStore = useEtherStore();
|
||||
const user = useUser();
|
||||
|
||||
// props
|
||||
const props = defineProps<{
|
||||
@@ -23,82 +18,12 @@ const props = defineProps<{
|
||||
|
||||
const emit = defineEmits(["depositWithdrawn"]);
|
||||
|
||||
const { loadingWalletTransactions } = storeToRefs(etherStore);
|
||||
const remaining = ref<number>(0.0);
|
||||
const { loadingWalletTransactions } = user;
|
||||
|
||||
const itemsToShow = ref<WalletTransaction[]>([]);
|
||||
const withdrawAmount = ref<string>("");
|
||||
const withdrawButtonOpacity = ref<number>(0.6);
|
||||
const withdrawButtonCursor = ref<string>("not-allowed");
|
||||
const isCollapsibleOpen = ref<boolean>(false);
|
||||
const validDecimals = ref<boolean>(true);
|
||||
const validWithdrawAmount = ref<boolean>(true);
|
||||
const enableConfirmButton = ref<boolean>(false);
|
||||
const showInfoTooltip = ref<boolean>(false);
|
||||
const floatingArrow = ref(null);
|
||||
|
||||
const reference = ref<HTMLElement | null>(null);
|
||||
const floating = ref<HTMLElement | null>(null);
|
||||
const infoText = ref<HTMLElement | null>(null);
|
||||
|
||||
// Debounce methods
|
||||
const handleInputEvent = (event: any): void => {
|
||||
const { value } = event.target;
|
||||
|
||||
if (decimalCount(String(value)) > 2) {
|
||||
validDecimals.value = false;
|
||||
enableConfirmButton.value = false;
|
||||
return;
|
||||
}
|
||||
validDecimals.value = true;
|
||||
|
||||
if (value > remaining.value) {
|
||||
validWithdrawAmount.value = false;
|
||||
enableConfirmButton.value = false;
|
||||
return;
|
||||
}
|
||||
validWithdrawAmount.value = true;
|
||||
enableConfirmButton.value = true;
|
||||
};
|
||||
|
||||
const callWithdraw = () => {
|
||||
emit("depositWithdrawn", withdrawAmount.value);
|
||||
};
|
||||
|
||||
watch(enableConfirmButton, (): void => {
|
||||
if (!enableConfirmButton.value) {
|
||||
withdrawButtonOpacity.value = 0.7;
|
||||
withdrawButtonCursor.value = "not-allowed";
|
||||
} else {
|
||||
withdrawButtonOpacity.value = 1;
|
||||
withdrawButtonCursor.value = "pointer";
|
||||
}
|
||||
});
|
||||
|
||||
watch(withdrawAmount, (): void => {
|
||||
if (!withdrawAmount.value || !enableConfirmButton.value) {
|
||||
withdrawButtonOpacity.value = 0.7;
|
||||
withdrawButtonCursor.value = "not-allowed";
|
||||
} else {
|
||||
withdrawButtonOpacity.value = 1;
|
||||
withdrawButtonCursor.value = "pointer";
|
||||
}
|
||||
});
|
||||
|
||||
const getRemaining = (): number => {
|
||||
if (props.validDeposits instanceof Array) {
|
||||
// Here we are getting only the first element of the list because
|
||||
// in this release only the BRL token is being used.
|
||||
const deposit = props.validDeposits[0];
|
||||
remaining.value = deposit ? deposit.remaining : 0;
|
||||
return deposit ? deposit.remaining : 0;
|
||||
}
|
||||
return 0;
|
||||
};
|
||||
|
||||
const getExplorer = (): string => {
|
||||
return etherStore.networkName == NetworkEnum.sepolia
|
||||
? "Etherscan"
|
||||
: "Polygonscan";
|
||||
const callWithdraw = (amount: string) => {
|
||||
emit("depositWithdrawn", amount);
|
||||
};
|
||||
|
||||
const showInitialItems = (): void => {
|
||||
@@ -106,10 +31,7 @@ const showInitialItems = (): void => {
|
||||
};
|
||||
|
||||
const openEtherscanUrl = (transactionHash: string): void => {
|
||||
const networkUrl =
|
||||
etherStore.networkName == NetworkEnum.sepolia
|
||||
? "sepolia.etherscan.io"
|
||||
: "mumbai.polygonscan.com";
|
||||
const networkUrl = user.network.value.blockExplorers?.default.url;
|
||||
const url = `https://${networkUrl}/tx/${transactionHash}`;
|
||||
window.open(url, "_blank");
|
||||
};
|
||||
@@ -121,31 +43,6 @@ const loadMore = (): void => {
|
||||
);
|
||||
};
|
||||
|
||||
const getEventName = (event: string | undefined): string => {
|
||||
if (!event) return "Desconhecido";
|
||||
|
||||
const possibleEventName: { [key: string]: string } = {
|
||||
DepositAdded: "Oferta",
|
||||
LockAdded: "Reserva",
|
||||
LockReleased: "Compra",
|
||||
DepositWithdrawn: "Retirada",
|
||||
};
|
||||
|
||||
return possibleEventName[event];
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
useFloating(reference, floating, {
|
||||
placement: "right",
|
||||
middleware: [
|
||||
offset(10),
|
||||
flip(),
|
||||
shift(),
|
||||
arrow({ element: floatingArrow }),
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
// watch props changes
|
||||
watch(props, async (): Promise<void> => {
|
||||
const itemsToShowQty = itemsToShow.value.length;
|
||||
@@ -162,183 +59,31 @@ showInitialItems();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="main-container max-w-md" v-if="loadingWalletTransactions">
|
||||
<div
|
||||
class="main-container max-w-md flex justify-center items-center min-h-[200px] w-16 h-16"
|
||||
v-if="loadingWalletTransactions"
|
||||
>
|
||||
Carregando ofertas...
|
||||
<SpinnerComponent width="8" height="8"></SpinnerComponent>
|
||||
</div>
|
||||
<div class="main-container max-w-md" v-if="!loadingWalletTransactions">
|
||||
<div
|
||||
class="w-full bg-white p-4 sm:p-6 rounded-lg"
|
||||
<div class="main-container max-w-md" v-else>
|
||||
<BalanceCard
|
||||
v-if="props.validDeposits.length > 0"
|
||||
>
|
||||
<div class="flex justify-between items-center">
|
||||
<div>
|
||||
<p class="text-sm leading-5 font-medium text-gray-600">
|
||||
Saldo disponível
|
||||
</p>
|
||||
<p class="text-xl leading-7 font-semibold text-gray-900">
|
||||
{{ getRemaining() }} {{ etherStore.selectedToken }}
|
||||
</p>
|
||||
<div class="flex gap-2 w-32 sm:w-56" v-if="activeLockAmount != 0">
|
||||
<span class="text-xs font-normal text-gray-400" ref="infoText">{{
|
||||
`com ${activeLockAmount.toFixed(2)} ${
|
||||
etherStore.selectedToken
|
||||
} em lock`
|
||||
}}</span>
|
||||
<div
|
||||
class="absolute mt-[2px] md-view"
|
||||
:style="{ left: `${(infoText?.clientWidth ?? 108) + 4}px` }"
|
||||
>
|
||||
<img
|
||||
alt="info image"
|
||||
src="@/assets/info.svg?url"
|
||||
aria-describedby="tooltip"
|
||||
ref="reference"
|
||||
@mouseover="showInfoTooltip = true"
|
||||
@mouseout="showInfoTooltip = false"
|
||||
/>
|
||||
<div
|
||||
role="tooltip"
|
||||
ref="floating"
|
||||
class="w-56 z-50 tooltip md-view"
|
||||
v-if="showInfoTooltip"
|
||||
>
|
||||
Valor “em lock” significa que a quantia está aguardando
|
||||
confirmação de compra e só estará disponível para saque caso a
|
||||
transação expire.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-show="!isCollapsibleOpen" class="flex justify-end items-center">
|
||||
<div
|
||||
class="flex gap-2 cursor-pointer items-center justify-self-center border-2 p-2 border-amber-300 rounded-md"
|
||||
@click="[(isCollapsibleOpen = true)]"
|
||||
>
|
||||
<img
|
||||
alt="Withdraw image"
|
||||
src="@/assets/withdraw.svg?url"
|
||||
class="w-3 h-3 sm:w-4 sm:h-4"
|
||||
/>
|
||||
<span class="last-release-info">Sacar</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pt-5">
|
||||
<div v-show="isCollapsibleOpen" class="py-2 w-100">
|
||||
<p class="text-sm leading-5 font-medium">Valor do saque</p>
|
||||
<input
|
||||
type="number"
|
||||
name=""
|
||||
@input="debounce(handleInputEvent, 500)($event)"
|
||||
placeholder="0"
|
||||
class="text-2xl text-gray-900 w-full outline-none"
|
||||
v-model="withdrawAmount"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex justify-center" v-if="!validDecimals">
|
||||
<span class="text-red-500 font-normal text-sm"
|
||||
>Por favor utilize no máximo 2 casas decimais</span
|
||||
>
|
||||
</div>
|
||||
<div class="flex justify-center" v-else-if="!validWithdrawAmount">
|
||||
<span class="text-red-500 font-normal text-sm"
|
||||
>Saldo insuficiente</span
|
||||
>
|
||||
</div>
|
||||
<hr v-show="isCollapsibleOpen" class="pb-3" />
|
||||
<div
|
||||
v-show="isCollapsibleOpen"
|
||||
class="flex justify-between items-center"
|
||||
>
|
||||
<h1
|
||||
@click="[(isCollapsibleOpen = false)]"
|
||||
class="text-black font-medium cursor-pointer"
|
||||
>
|
||||
Cancelar
|
||||
</h1>
|
||||
:valid-deposits="props.validDeposits"
|
||||
:active-lock-amount="activeLockAmount"
|
||||
:selected-token="user.selectedToken.value"
|
||||
@withdraw="callWithdraw"
|
||||
/>
|
||||
|
||||
<div
|
||||
class="withdraw-button flex gap-2 items-center justify-self-center border-2 p-2 border-amber-300 rounded-md"
|
||||
@click="callWithdraw"
|
||||
>
|
||||
<img
|
||||
alt="Withdraw image"
|
||||
src="@/assets/withdraw.svg?url"
|
||||
class="w-3 h-3 sm:w-4 sm:h-4"
|
||||
/>
|
||||
<span class="last-release-info">Sacar</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="w-full bg-white p-4 sm:p-6 rounded-lg"
|
||||
<TransactionCard
|
||||
v-for="item in itemsToShow"
|
||||
:key="item.blockNumber"
|
||||
>
|
||||
<div class="item-container">
|
||||
<div class="flex flex-col self-start">
|
||||
<span class="text-xs sm:text-sm leading-5 font-medium text-gray-600">
|
||||
{{ getEventName(item.event) }}
|
||||
</span>
|
||||
<span
|
||||
class="text-xl sm:text-xl leading-7 font-semibold text-gray-900"
|
||||
>
|
||||
{{ item.amount }}
|
||||
{{ getTokenByAddress(item.token) }}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<div
|
||||
class="bg-amber-300 status-text"
|
||||
v-if="getEventName(item.event) == 'Reserva' && item.lockStatus == 1"
|
||||
>
|
||||
Em Aberto
|
||||
</div>
|
||||
<div
|
||||
class="bg-[#94A3B8] status-text"
|
||||
v-if="getEventName(item.event) == 'Reserva' && item.lockStatus == 2"
|
||||
>
|
||||
Expirado
|
||||
</div>
|
||||
<div
|
||||
class="bg-emerald-300 status-text"
|
||||
v-if="
|
||||
(getEventName(item.event) == 'Reserva' && item.lockStatus == 3) ||
|
||||
getEventName(item.event) != 'Reserva'
|
||||
"
|
||||
>
|
||||
Finalizado
|
||||
</div>
|
||||
<div
|
||||
class="flex gap-2 cursor-pointer items-center justify-self-center w-full"
|
||||
@click="openEtherscanUrl(item.transactionHash)"
|
||||
v-if="getEventName(item.event) != 'Reserva' || item.lockStatus != 1"
|
||||
>
|
||||
<span class="last-release-info">{{ getExplorer() }}</span>
|
||||
<img
|
||||
alt="Redirect image"
|
||||
src="@/assets/redirect.svg?url"
|
||||
class="w-3 h-3 sm:w-4 sm:h-4"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
class="flex gap-2 justify-self-center w-full"
|
||||
v-if="getEventName(item.event) == 'Reserva' && item.lockStatus == 1"
|
||||
>
|
||||
<RouterLink
|
||||
:to="{
|
||||
name: 'home',
|
||||
force: true,
|
||||
state: { lockID: item.transactionID },
|
||||
}"
|
||||
class="router-button"
|
||||
>Continuar</RouterLink
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
:selected-token="user.selectedToken.value"
|
||||
:transaction="item"
|
||||
:network-name="user.network.value.name"
|
||||
@open-explorer="openEtherscanUrl"
|
||||
/>
|
||||
|
||||
<div
|
||||
class="flex flex-col justify-center items-center w-full mt-2 gap-2"
|
||||
v-if="
|
||||
@@ -348,14 +93,14 @@ showInitialItems();
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="text-white font-semibold"
|
||||
class="text-white font-semibold border-2 border-amber-300 rounded-lg px-4 py-2 hover:bg-amber-300/10 transition-colors cursor-pointer"
|
||||
@click="loadMore()"
|
||||
>
|
||||
Carregar mais
|
||||
</button>
|
||||
<span class="text-gray-300">
|
||||
({{ itemsToShow.length }} de {{ props.walletTransactions.length }}
|
||||
transações )
|
||||
<span class="text-gray-300 text-sm">
|
||||
{{ itemsToShow.length }} de {{ props.walletTransactions.length }}
|
||||
transações
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -366,62 +111,5 @@ showInitialItems();
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.page {
|
||||
@apply flex flex-col items-center justify-center w-full mt-16;
|
||||
}
|
||||
|
||||
p {
|
||||
@apply text-gray-900;
|
||||
}
|
||||
|
||||
.text-container {
|
||||
@apply flex flex-col items-center justify-center gap-4;
|
||||
}
|
||||
|
||||
.item-container {
|
||||
@apply flex justify-between items-center;
|
||||
}
|
||||
|
||||
.status-text {
|
||||
@apply text-xs sm:text-base font-medium text-gray-900 rounded-lg text-center mb-2 px-2 py-1 mt-4;
|
||||
}
|
||||
.text {
|
||||
@apply text-white text-center;
|
||||
}
|
||||
|
||||
.grid-container {
|
||||
@apply grid grid-cols-4 grid-flow-row items-center px-8 py-6 gap-4 rounded-lg shadow-md shadow-gray-600 backdrop-blur-md mt-10 w-auto;
|
||||
}
|
||||
|
||||
.last-release-info {
|
||||
@apply font-medium text-xs sm:text-sm text-gray-900 justify-self-center;
|
||||
}
|
||||
|
||||
.tooltip {
|
||||
@apply bg-white text-gray-900 font-medium text-xs md:text-base px-3 py-2 rounded border-2 border-emerald-500 left-5 top-[-3rem];
|
||||
}
|
||||
|
||||
.router-button {
|
||||
@apply rounded-lg border-amber-300 border-2 px-3 py-2 text-gray-900 font-semibold sm:text-base text-xs hover:bg-transparent w-full text-center;
|
||||
}
|
||||
|
||||
.withdraw-button {
|
||||
opacity: v-bind(withdrawButtonOpacity);
|
||||
cursor: v-bind(withdrawButtonCursor);
|
||||
}
|
||||
|
||||
input[type="number"] {
|
||||
-moz-appearance: textfield;
|
||||
}
|
||||
|
||||
input[type="number"]::-webkit-inner-spin-button,
|
||||
input[type="number"]::-webkit-outer-spin-button {
|
||||
-webkit-appearance: none;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 640px) {
|
||||
.md-view {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
/* Minimal styles - most styles moved to child components */
|
||||
</style>
|
||||
|
||||
124
src/components/ListingComponent/TransactionCard.vue
Normal file
@@ -0,0 +1,124 @@
|
||||
<script setup lang="ts">
|
||||
import type { WalletTransaction } from "@/model/WalletTransaction";
|
||||
import { TokenEnum } from "@/model/NetworkEnum";
|
||||
import { computed } from "vue";
|
||||
import StatusBadge, { type StatusType } from "../ui/StatusBadge.vue";
|
||||
import { Networks } from "@/config/networks";
|
||||
|
||||
const props = defineProps<{
|
||||
transaction: WalletTransaction;
|
||||
networkName: keyof typeof Networks;
|
||||
selectedToken: TokenEnum;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
openExplorer: [transactionHash: string];
|
||||
}>();
|
||||
|
||||
const eventName = computed(() => {
|
||||
if (!props.transaction.event) return "Desconhecido";
|
||||
|
||||
const possibleEventName: { [key: string]: string } = {
|
||||
DepositAdded: "Oferta",
|
||||
LockAdded: "Reserva",
|
||||
LockReleased: "Compra",
|
||||
DepositWithdrawn: "Retirada",
|
||||
};
|
||||
|
||||
return possibleEventName[props.transaction.event] || "Desconhecido";
|
||||
});
|
||||
|
||||
const explorerName = computed(() => {
|
||||
return Networks[props.networkName].blockExplorers?.default.name;
|
||||
});
|
||||
|
||||
const statusType = computed((): StatusType => {
|
||||
if (eventName.value === "Reserva") {
|
||||
switch (props.transaction.lockStatus) {
|
||||
case 1:
|
||||
return "open";
|
||||
case 2:
|
||||
return "expired";
|
||||
case 3:
|
||||
return "completed";
|
||||
default:
|
||||
return "completed";
|
||||
}
|
||||
}
|
||||
return "completed";
|
||||
});
|
||||
|
||||
const showExplorerLink = computed(() => {
|
||||
return eventName.value !== "Reserva" || props.transaction.lockStatus !== 1;
|
||||
});
|
||||
|
||||
const showContinueButton = computed(() => {
|
||||
return eventName.value === "Reserva" && props.transaction.lockStatus === 1;
|
||||
});
|
||||
|
||||
const handleExplorerClick = () => {
|
||||
emit("openExplorer", props.transaction.transactionHash);
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="w-full bg-white p-4 sm:p-6 rounded-lg">
|
||||
<div class="item-container">
|
||||
<div class="flex flex-col self-start">
|
||||
<span class="text-xs sm:text-sm leading-5 font-medium text-gray-600">
|
||||
{{ eventName }}
|
||||
</span>
|
||||
<span class="text-xl sm:text-xl leading-7 font-semibold text-gray-900">
|
||||
{{ transaction.amount }} {{ selectedToken }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex flex-col items-center justify-center">
|
||||
<div class="mb-2 mt-4">
|
||||
<StatusBadge :status="statusType" />
|
||||
</div>
|
||||
<div
|
||||
v-if="showExplorerLink"
|
||||
class="flex gap-2 cursor-pointer items-center justify-self-center w-full"
|
||||
@click="handleExplorerClick"
|
||||
>
|
||||
<span class="last-release-info">{{ explorerName }}</span>
|
||||
<img
|
||||
alt="Redirect image"
|
||||
src="@/assets/redirect.svg?url"
|
||||
class="w-3 h-3 sm:w-4 sm:h-4"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
v-if="showContinueButton"
|
||||
class="flex gap-2 justify-self-center w-full"
|
||||
>
|
||||
<RouterLink
|
||||
:to="{
|
||||
name: 'home',
|
||||
force: true,
|
||||
state: { lockID: transaction.transactionID },
|
||||
}"
|
||||
class="router-button"
|
||||
>
|
||||
Continuar
|
||||
</RouterLink>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.item-container {
|
||||
@apply flex justify-between items-center;
|
||||
}
|
||||
|
||||
.last-release-info {
|
||||
@apply font-medium text-xs sm:text-sm text-gray-900 justify-self-center;
|
||||
}
|
||||
|
||||
.router-button {
|
||||
@apply rounded-lg border-amber-300 border-2 px-3 py-2 text-gray-900 font-semibold sm:text-base text-xs hover:bg-transparent w-full text-center;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
import { mount } from "@vue/test-utils";
|
||||
import ListingComponent from "@/components/ListingComponent/ListingComponent.vue";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { expect } from "vitest";
|
||||
import { MockValidDeposits } from "@/model/mock/ValidDepositMock";
|
||||
import { MockWalletTransactions } from "@/model/mock/WalletTransactionMock";
|
||||
import { useEtherStore } from "@/store/ether";
|
||||
|
||||
describe("ListingComponent.vue", () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
useEtherStore().setLoadingWalletTransactions(false);
|
||||
});
|
||||
|
||||
test("Test Message when an empty array is received", () => {
|
||||
const wrapper = mount(ListingComponent, {
|
||||
props: {
|
||||
validDeposits: [],
|
||||
walletTransactions: [],
|
||||
activeLockAmount: 0,
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.html()).toContain("Não há nenhuma transação anterior");
|
||||
});
|
||||
|
||||
test("Test number of elements in the list first render", () => {
|
||||
const wrapper = mount(ListingComponent, {
|
||||
props: {
|
||||
validDeposits: [],
|
||||
walletTransactions: MockWalletTransactions,
|
||||
activeLockAmount: 0,
|
||||
},
|
||||
});
|
||||
|
||||
const elements = wrapper.findAll(".item-container");
|
||||
|
||||
expect(elements).toHaveLength(3);
|
||||
});
|
||||
|
||||
test("Test load more button behavior", async () => {
|
||||
const wrapper = mount(ListingComponent, {
|
||||
props: {
|
||||
validDeposits: MockValidDeposits,
|
||||
walletTransactions: MockWalletTransactions,
|
||||
activeLockAmount: 0,
|
||||
},
|
||||
});
|
||||
const btn = wrapper.find("button");
|
||||
|
||||
let elements = wrapper.findAll(".item-container");
|
||||
expect(elements).toHaveLength(3);
|
||||
|
||||
await btn.trigger("click");
|
||||
|
||||
elements = wrapper.findAll(".item-container");
|
||||
|
||||
expect(elements).toHaveLength(5);
|
||||
});
|
||||
|
||||
test("Test withdraw offer button emit", async () => {
|
||||
const wrapper = mount(ListingComponent, {
|
||||
props: {
|
||||
validDeposits: MockValidDeposits,
|
||||
walletTransactions: MockWalletTransactions,
|
||||
activeLockAmount: 0,
|
||||
},
|
||||
});
|
||||
wrapper.vm.$emit("depositWithdrawn");
|
||||
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
expect(wrapper.emitted("depositWithdrawn")).toBeTruthy();
|
||||
});
|
||||
|
||||
test("Test should render lock info when active lock amount is greater than 0", () => {
|
||||
const wrapper = mount(ListingComponent, {
|
||||
props: {
|
||||
validDeposits: MockValidDeposits,
|
||||
walletTransactions: [],
|
||||
activeLockAmount: 50,
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.html()).toContain("com 50.00 BRZ em lock");
|
||||
});
|
||||
});
|
||||
@@ -1,27 +0,0 @@
|
||||
import { mount } from "@vue/test-utils";
|
||||
import LoadingComponent from "../LoadingComponent.vue";
|
||||
|
||||
describe("Loading.vue", () => {
|
||||
test("Test loading content with received props", () => {
|
||||
const wrapper = mount(LoadingComponent, {
|
||||
props: {
|
||||
title: "MockTitle",
|
||||
message: "MockMessage",
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.html()).toContain("MockTitle");
|
||||
expect(wrapper.html()).toContain("MockMessage");
|
||||
});
|
||||
|
||||
test("Test default text if props title isnt passed", () => {
|
||||
const wrapper = mount(LoadingComponent, {
|
||||
props: {
|
||||
message: "MockMessage",
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.html()).toContain("Confirme em sua carteira");
|
||||
expect(wrapper.html()).toContain("MockMessage");
|
||||
});
|
||||
});
|
||||
@@ -1,196 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { pix } from "@/utils/QrCodePix";
|
||||
import { onMounted, onUnmounted, ref } from "vue";
|
||||
import { debounce } from "@/utils/debounce";
|
||||
import CustomButton from "@/components/CustomButton/CustomButton.vue";
|
||||
import CustomModal from "@/components//CustomModal/CustomModal.vue";
|
||||
import api from "@/services/index";
|
||||
|
||||
// props and store references
|
||||
const props = defineProps({
|
||||
pixTarget: String,
|
||||
tokenValue: Number,
|
||||
});
|
||||
|
||||
const windowSize = ref<number>(window.innerWidth);
|
||||
const qrCode = ref<string>("");
|
||||
const qrCodePayload = ref<string>("");
|
||||
const isPixValid = ref<boolean>(false);
|
||||
const isCodeInputEmpty = ref<boolean>(true);
|
||||
const showWarnModal = ref<boolean>(true);
|
||||
const e2eId = ref<string>("");
|
||||
|
||||
// Emits
|
||||
const emit = defineEmits(["pixValidated"]);
|
||||
|
||||
const pixQrCode = pix({
|
||||
pixKey: props.pixTarget ?? "",
|
||||
value: props.tokenValue,
|
||||
});
|
||||
|
||||
pixQrCode.base64QrCode().then((code: string) => {
|
||||
qrCode.value = code;
|
||||
});
|
||||
|
||||
qrCodePayload.value = pixQrCode.payload();
|
||||
|
||||
const handleInputEvent = async (event: any): Promise<void> => {
|
||||
const { value } = event.target;
|
||||
e2eId.value = value;
|
||||
await validatePix();
|
||||
};
|
||||
|
||||
const validatePix = async (): Promise<void> => {
|
||||
if (e2eId.value == "") {
|
||||
isPixValid.value = false;
|
||||
isCodeInputEmpty.value = true;
|
||||
return;
|
||||
}
|
||||
const sellerPixKey = props.pixTarget;
|
||||
const transactionValue = props.tokenValue;
|
||||
|
||||
if (sellerPixKey && transactionValue) {
|
||||
const body_req = {
|
||||
e2e_id: e2eId.value,
|
||||
pix_key: sellerPixKey,
|
||||
pix_value: transactionValue,
|
||||
};
|
||||
|
||||
isCodeInputEmpty.value = false;
|
||||
|
||||
try {
|
||||
await api.post("validate_pix", body_req);
|
||||
isPixValid.value = true;
|
||||
} catch (error) {
|
||||
isPixValid.value = false;
|
||||
}
|
||||
} else {
|
||||
isCodeInputEmpty.value = false;
|
||||
isPixValid.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
window.addEventListener(
|
||||
"resize",
|
||||
() => (windowSize.value = window.innerWidth)
|
||||
);
|
||||
});
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener(
|
||||
"resize",
|
||||
() => (windowSize.value = window.innerWidth)
|
||||
);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<div class="text-container">
|
||||
<span
|
||||
class="text font-extrabold lg:text-2xl text-xl sm:max-w-[30rem] max-w-[24rem]"
|
||||
>
|
||||
Utilize o QR Code ou copie o código para realizar o Pix
|
||||
</span>
|
||||
<span class="text font-medium lg:text-md text-sm max-w-[28rem]">
|
||||
Após realizar o Pix no banco de sua preferência, clique no botão abaixo
|
||||
para gerar a assinatura para liberação dos tokens.
|
||||
</span>
|
||||
</div>
|
||||
<div class="main-container max-w-md text-black">
|
||||
<div
|
||||
class="flex-col items-center justify-center flex w-full bg-white sm:p-8 p-4 rounded-lg break-normal"
|
||||
>
|
||||
<img alt="Qr code image" :src="qrCode" class="w-48 h-48" />
|
||||
<span class="text-center font-bold">Código pix</span>
|
||||
<div class="break-words w-4/5">
|
||||
<span class="text-center text-xs">
|
||||
{{ qrCodePayload }}
|
||||
</span>
|
||||
</div>
|
||||
<img
|
||||
alt="Copy PIX code"
|
||||
src="@/assets/copyPix.svg?url"
|
||||
width="16"
|
||||
height="16"
|
||||
class="pt-2 lg:mb-5 cursor-pointer"
|
||||
/>
|
||||
<span class="text-xs text-start hidden sm:inline-block">
|
||||
<strong>ATENÇÃO!</strong> A transação só será processada após inserir
|
||||
o código de autenticação. Caso contrário não conseguiremos comprovar o
|
||||
seu depósito e não será possível transferir os tokens para sua
|
||||
carteira. Confira aqui como encontrar o código no comprovante.
|
||||
</span>
|
||||
</div>
|
||||
<CustomButton
|
||||
:is-disabled="isPixValid == false"
|
||||
:text="'Enviar para a rede'"
|
||||
@button-clicked="emit('pixValidated', e2eId)"
|
||||
/>
|
||||
</div>
|
||||
<CustomModal
|
||||
v-if="showWarnModal && windowSize <= 500"
|
||||
@close-modal="showWarnModal = false"
|
||||
:isRedirectModal="false"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.page {
|
||||
@apply flex flex-col items-center justify-center w-full mt-16;
|
||||
}
|
||||
|
||||
::placeholder {
|
||||
/* Most modern browsers support this now. */
|
||||
color: #9ca3af;
|
||||
}
|
||||
|
||||
h4 {
|
||||
color: #080808;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
h2 {
|
||||
color: #080808;
|
||||
}
|
||||
|
||||
.form-input {
|
||||
@apply rounded-lg border border-gray-200 p-2 text-black;
|
||||
}
|
||||
|
||||
.form-label {
|
||||
@apply font-semibold tracking-wide text-emerald-50;
|
||||
}
|
||||
|
||||
.custom-divide {
|
||||
width: 100%;
|
||||
border-bottom: 1px solid #d1d5db;
|
||||
}
|
||||
.bottom-position {
|
||||
top: -20px;
|
||||
right: 50%;
|
||||
transform: translateX(50%);
|
||||
}
|
||||
|
||||
.text-container {
|
||||
@apply flex flex-col items-center justify-center gap-4;
|
||||
}
|
||||
|
||||
.text {
|
||||
@apply text-white text-center;
|
||||
}
|
||||
|
||||
.blur-container {
|
||||
@apply flex flex-col justify-center items-center px-8 py-6 gap-2 rounded-lg shadow-md shadow-gray-600 backdrop-blur-md mt-6 max-w-screen-sm;
|
||||
}
|
||||
|
||||
input[type="number"] {
|
||||
-moz-appearance: textfield;
|
||||
}
|
||||
|
||||
input[type="number"]::-webkit-inner-spin-button,
|
||||
input[type="number"]::-webkit-outer-spin-button {
|
||||
-webkit-appearance: none;
|
||||
}
|
||||
</style>
|
||||
343
src/components/SellerSteps/SellerComponent.vue
Normal file
@@ -0,0 +1,343 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed } from "vue";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
import CustomButton from "@/components/ui/CustomButton.vue";
|
||||
import { postProcessKey } from "@/utils/pixKeyFormat";
|
||||
import { TokenEnum } from "@/model/NetworkEnum";
|
||||
import { getTokenImage } from "@/utils/imagesPath";
|
||||
import { useOnboard } from "@web3-onboard/vue";
|
||||
import ChevronDown from "@/assets/chevron.svg";
|
||||
|
||||
// Import the bank list
|
||||
import bankList from "@/utils/files/isbpList.json";
|
||||
import type { Participant } from "@/utils/bbPay";
|
||||
|
||||
// Define Bank interface
|
||||
interface Bank {
|
||||
ISPB: string;
|
||||
longName: string;
|
||||
}
|
||||
|
||||
// html references
|
||||
const tokenDropdownRef = ref<any>(null);
|
||||
const formRef = ref<HTMLFormElement | null>(null);
|
||||
|
||||
// Reactive state
|
||||
const user = useUser();
|
||||
const { walletAddress, selectedToken } = user;
|
||||
|
||||
const offer = ref<string>("");
|
||||
const identification = ref<string>("");
|
||||
const account = ref<string>("");
|
||||
const branch = ref<string>("");
|
||||
const accountType = ref<string>("");
|
||||
const selectTokenToggle = ref<boolean>(false);
|
||||
const savingsVariation = ref<string>("");
|
||||
const errors = ref<{ [key: string]: string }>({});
|
||||
|
||||
// Bank selection
|
||||
const bankSearchQuery = ref<string>("");
|
||||
const showBankList = ref<boolean>(false);
|
||||
const selectedBank = ref<Bank | null>(null);
|
||||
|
||||
const filteredBanks = computed(() => {
|
||||
if (!bankSearchQuery.value) return [];
|
||||
return bankList
|
||||
.filter((bank) =>
|
||||
bank.longName.toLowerCase().includes(bankSearchQuery.value.toLowerCase())
|
||||
)
|
||||
.slice(0, 5);
|
||||
});
|
||||
|
||||
const handleBankSelect = (bank: Bank) => {
|
||||
selectedBank.value = bank;
|
||||
bankSearchQuery.value = bank.longName;
|
||||
showBankList.value = false;
|
||||
};
|
||||
|
||||
// Emits
|
||||
const emit = defineEmits(["approveTokens"]);
|
||||
|
||||
// Methods
|
||||
const connectAccount = async (): Promise<void> => {
|
||||
const { connectWallet } = useOnboard();
|
||||
await connectWallet();
|
||||
};
|
||||
|
||||
const handleSubmit = (e: Event): void => {
|
||||
e.preventDefault();
|
||||
|
||||
const processedIdentification = postProcessKey(identification.value);
|
||||
|
||||
const data: Participant = {
|
||||
offer: offer.value,
|
||||
chainID: user.network.value.id,
|
||||
identification: processedIdentification,
|
||||
bankIspb: selectedBank.value?.ISPB,
|
||||
accountType: accountType.value,
|
||||
account: account.value,
|
||||
branch: branch.value,
|
||||
savingsVariation: savingsVariation.value || "",
|
||||
};
|
||||
|
||||
emit("approveTokens", data);
|
||||
};
|
||||
|
||||
// Token selection
|
||||
const openTokenSelection = (): void => {
|
||||
selectTokenToggle.value = true;
|
||||
};
|
||||
|
||||
const handleSelectedToken = (token: TokenEnum): void => {
|
||||
user.setSelectedToken(token);
|
||||
selectTokenToggle.value = false;
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page w-full">
|
||||
<div class="text-container">
|
||||
<span
|
||||
class="text font-extrabold sm:text-5xl text-3xl sm:max-w-[29rem] max-w-[20rem]"
|
||||
>
|
||||
Venda cripto e receba em Pix
|
||||
</span>
|
||||
<span
|
||||
class="text font-medium sm:text-base text-xs sm:max-w-[28rem] max-w-[30rem] sm:tracking-normal tracking-wide"
|
||||
>
|
||||
Digite sua oferta, informe a chave Pix, selecione a rede, aprove o envio
|
||||
da transação e confirme sua oferta.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<form ref="formRef" @submit="handleSubmit" class="main-container">
|
||||
<!-- Offer input -->
|
||||
<div
|
||||
class="flex justify-between items-center w-full bg-white sm:px-10 px-6 py-5 rounded-lg border-y-10 gap-4"
|
||||
>
|
||||
<input
|
||||
type="number"
|
||||
v-model="offer"
|
||||
class="border-none outline-none text-gray-900 sm:w-fit w-3/4 flex-grow"
|
||||
:class="{
|
||||
'!font-medium': offer !== undefined && offer !== '',
|
||||
'text-xl': offer !== undefined && offer !== '',
|
||||
}"
|
||||
min="0.01"
|
||||
max="999999999.99"
|
||||
pattern="\d+(\.\d{0,2})?"
|
||||
placeholder="Digite sua oferta (mínimo R$0,01)"
|
||||
step=".01"
|
||||
required
|
||||
/>
|
||||
<div class="relative overflow-visible">
|
||||
<button
|
||||
ref="tokenDropdownRef"
|
||||
class="flex flex-row items-center p-2 bg-gray-300 hover:bg-gray-200 focus:outline-indigo-800 focus:outline-2 rounded-3xl min-w-fit gap-2 transition-colors"
|
||||
@click="openTokenSelection()"
|
||||
>
|
||||
<img
|
||||
alt="Token image"
|
||||
class="sm:w-fit w-4"
|
||||
:src="getTokenImage(selectedToken)"
|
||||
/>
|
||||
<span
|
||||
class="text-gray-900 sm:text-lg text-md font-medium"
|
||||
id="token"
|
||||
>
|
||||
{{ selectedToken }}
|
||||
</span>
|
||||
<ChevronDown
|
||||
class="text-gray-900 pr-4 sm:pr-0 transition-all duration-500 ease-in-out"
|
||||
:class="{ 'scale-y-[-1]': selectTokenToggle }"
|
||||
alt="Chevron Down"
|
||||
/>
|
||||
</button>
|
||||
<transition name="dropdown">
|
||||
<div
|
||||
v-if="selectTokenToggle"
|
||||
class="mt-2 text-gray-900 absolute right-0 z-50 w-full min-w-max"
|
||||
>
|
||||
<div
|
||||
class="bg-white rounded-xl z-10 border border-gray-300 drop-shadow-md shadow-md overflow-clip"
|
||||
>
|
||||
<div
|
||||
v-for="token in TokenEnum"
|
||||
:key="token"
|
||||
class="flex menu-button gap-2 px-4 cursor-pointer hover:bg-gray-300 transition-colors"
|
||||
@click="handleSelectedToken(token)"
|
||||
>
|
||||
<img
|
||||
:alt="token + ' logo'"
|
||||
width="20"
|
||||
height="20"
|
||||
:src="getTokenImage(token)"
|
||||
/>
|
||||
<span
|
||||
class="text-gray-900 py-4 text-end font-semibold text-sm"
|
||||
>
|
||||
{{ token }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</transition>
|
||||
</div>
|
||||
</div>
|
||||
<!-- CPF or CNPJ input -->
|
||||
<div
|
||||
class="flex flex-col w-full bg-white sm:px-10 px-6 py-4 rounded-lg border-y-10"
|
||||
>
|
||||
<input
|
||||
type="text"
|
||||
v-model="identification"
|
||||
maxlength="14"
|
||||
:pattern="'^\\d{11}$|^\\d{14}$'"
|
||||
class="border-none outline-none sm:text-lg text-sm text-gray-900 w-full"
|
||||
:class="{ 'text-xl font-medium': identification }"
|
||||
placeholder="Digite seu CPF ou CNPJ (somente números)"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<!-- Bank selection -->
|
||||
<div
|
||||
class="flex flex-col w-full bg-white sm:px-10 px-6 py-4 rounded-lg border-y-10"
|
||||
>
|
||||
<div class="relative">
|
||||
<input
|
||||
type="text"
|
||||
v-model="bankSearchQuery"
|
||||
class="border-none outline-none sm:text-lg text-sm text-gray-900 w-full"
|
||||
:class="{ 'text-xl font-medium': bankSearchQuery }"
|
||||
placeholder="Buscar banco"
|
||||
@focus="showBankList = true"
|
||||
required
|
||||
/>
|
||||
<div
|
||||
v-if="showBankList && filteredBanks.length > 0"
|
||||
class="absolute top-full left-0 right-0 mt-1 bg-white border border-gray-200 rounded-md shadow-lg z-50 max-h-60 overflow-y-auto"
|
||||
>
|
||||
<div
|
||||
v-for="bank in filteredBanks"
|
||||
:key="bank.ISPB"
|
||||
class="px-4 py-2 hover:bg-gray-100 cursor-pointer transition-colors"
|
||||
@click="handleBankSelect(bank)"
|
||||
>
|
||||
<div class="text-sm font-medium text-gray-900">
|
||||
{{ bank.longName }}
|
||||
</div>
|
||||
<div class="text-xs text-gray-500">ISPB: {{ bank.ISPB }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<span v-if="errors.bank" class="text-red-500 text-sm mt-2">{{
|
||||
errors.bank
|
||||
}}</span>
|
||||
</div>
|
||||
<!-- Account and Branch inputs -->
|
||||
<div
|
||||
class="flex flex-col w-full bg-white sm:px-10 px-6 py-4 rounded-lg border-y-10"
|
||||
>
|
||||
<div class="flex gap-4">
|
||||
<div class="flex-1">
|
||||
<input
|
||||
type="text"
|
||||
v-model="account"
|
||||
class="border-none outline-none sm:text-lg text-sm text-gray-900 w-full"
|
||||
:class="{ 'text-xl font-medium': account }"
|
||||
placeholder="Número da conta"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div class="flex-1">
|
||||
<input
|
||||
type="text"
|
||||
v-model="branch"
|
||||
class="border-none outline-none sm:text-lg text-sm text-gray-900 w-full"
|
||||
:class="{ 'text-xl font-medium': branch }"
|
||||
placeholder="Agência"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Account Type Selection -->
|
||||
<div
|
||||
class="flex flex-col w-full bg-white sm:px-10 px-6 py-4 rounded-lg border-y-10"
|
||||
>
|
||||
<div class="flex gap-4">
|
||||
<div class="flex-1">
|
||||
<select
|
||||
v-model="accountType"
|
||||
class="border-none outline-none sm:text-lg text-sm text-gray-900 w-full"
|
||||
required
|
||||
>
|
||||
<option value="" disabled selected>Tipo de conta</option>
|
||||
<option value="1">Conta Corrente</option>
|
||||
<option value="2">Conta Poupança</option>
|
||||
<option value="3">Conta Salário</option>
|
||||
<option value="4">Conta Pré-Paga</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Savings Account Variation -->
|
||||
<Transition name="resize">
|
||||
<input
|
||||
v-if="accountType === '2'"
|
||||
type="text"
|
||||
v-model="savingsVariation"
|
||||
class="border-none outline-none sm:text-lg text-sm text-gray-900 w-full bg-white sm:px-10 px-6 py-4 rounded-lg border-y-10"
|
||||
:class="{ 'text-xl font-medium': savingsVariation }"
|
||||
placeholder="Variação da poupança"
|
||||
required
|
||||
/>
|
||||
</Transition>
|
||||
<!-- Action buttons -->
|
||||
<CustomButton v-if="walletAddress" type="submit" text="Aprovar tokens" />
|
||||
<CustomButton
|
||||
v-else
|
||||
text="Conectar carteira"
|
||||
@buttonClicked="connectAccount()"
|
||||
/>
|
||||
</form>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.custom-divide {
|
||||
width: 100%;
|
||||
border-bottom: 1px solid #d1d5db;
|
||||
}
|
||||
.bottom-position {
|
||||
top: -20px;
|
||||
right: 50%;
|
||||
transform: translateX(50%);
|
||||
}
|
||||
|
||||
.page {
|
||||
@apply flex flex-col items-center justify-center w-full mt-16;
|
||||
}
|
||||
|
||||
.text-container {
|
||||
@apply flex flex-col items-center justify-center gap-4;
|
||||
}
|
||||
|
||||
.text {
|
||||
@apply text-white text-center;
|
||||
}
|
||||
|
||||
input[type="number"] {
|
||||
-moz-appearance: textfield;
|
||||
appearance: textfield;
|
||||
}
|
||||
|
||||
input[type="number"]::-webkit-inner-spin-button,
|
||||
input[type="number"]::-webkit-outer-spin-button {
|
||||
-webkit-appearance: none;
|
||||
}
|
||||
|
||||
input {
|
||||
@apply sm:text-lg text-sm;
|
||||
}
|
||||
</style>
|
||||
@@ -1,17 +1,15 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import CustomButton from "@/components/CustomButton/CustomButton.vue";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
import CustomButton from "@/components/ui/CustomButton.vue";
|
||||
import { debounce } from "@/utils/debounce";
|
||||
import { decimalCount } from "@/utils/decimalCount";
|
||||
|
||||
import { useEtherStore } from "@/store/ether";
|
||||
import { getTokenImage } from "@/utils/imagesPath";
|
||||
import { storeToRefs } from "pinia";
|
||||
import { useOnboard } from "@web3-onboard/vue";
|
||||
|
||||
// Store
|
||||
const etherStore = useEtherStore();
|
||||
const { walletAddress } = storeToRefs(etherStore);
|
||||
const user = useUser();
|
||||
const { walletAddress } = user;
|
||||
|
||||
// Reactive state
|
||||
const tokenValue = ref<number>(0);
|
||||
@@ -76,10 +74,10 @@ const handleInputEvent = (event: any): void => {
|
||||
<img
|
||||
alt="Token image"
|
||||
class="w-fit"
|
||||
:src="getTokenImage(etherStore.selectedToken)"
|
||||
:src="getTokenImage(user.selectedToken.value)"
|
||||
/>
|
||||
<span class="text-gray-900 text-lg w-fit" id="token">{{
|
||||
etherStore.selectedToken
|
||||
user.selectedToken
|
||||
}}</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -153,10 +151,6 @@ const handleInputEvent = (event: any): void => {
|
||||
@apply text-white text-center;
|
||||
}
|
||||
|
||||
input[type="number"] {
|
||||
-moz-appearance: textfield;
|
||||
}
|
||||
|
||||
input[type="number"]::-webkit-inner-spin-button,
|
||||
input[type="number"]::-webkit-outer-spin-button {
|
||||
-webkit-appearance: none;
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
import CustomButton from "@/components/CustomButton/CustomButton.vue";
|
||||
import CustomButton from "@/components/ui/CustomButton.vue";
|
||||
|
||||
// Emits
|
||||
const emit = defineEmits(["sendNetwork"]);
|
||||
|
||||
// props and store references
|
||||
const props = defineProps({
|
||||
pixKey: String,
|
||||
sellerId: String,
|
||||
offer: Number,
|
||||
selectedToken: String,
|
||||
});
|
||||
@@ -26,7 +26,7 @@ const props = defineProps({
|
||||
os tokens de volta.</span
|
||||
>
|
||||
</div>
|
||||
<div class="main-container sm:w-1/3">
|
||||
<div class="main-container">
|
||||
<div
|
||||
class="flex flex-col w-full bg-white px-10 py-5 rounded-lg border-y-10"
|
||||
>
|
||||
@@ -39,7 +39,7 @@ const props = defineProps({
|
||||
<div class="my-3">
|
||||
<p>Chave Pix</p>
|
||||
<p class="text-xl text-gray-900 break-words">
|
||||
{{ props.pixKey }}
|
||||
{{ props.sellerId }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="mb-5">
|
||||
@@ -79,10 +79,6 @@ p {
|
||||
@apply font-medium text-base;
|
||||
}
|
||||
|
||||
input[type="number"] {
|
||||
-moz-appearance: textfield;
|
||||
}
|
||||
|
||||
input[type="number"]::-webkit-inner-spin-button,
|
||||
input[type="number"]::-webkit-outer-spin-button {
|
||||
-webkit-appearance: none;
|
||||
|
||||
@@ -1,263 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import CustomButton from "../CustomButton/CustomButton.vue";
|
||||
import { debounce } from "@/utils/debounce";
|
||||
import { decimalCount } from "@/utils/decimalCount";
|
||||
import { pixFormatValidation, postProcessKey } from "@/utils/pixKeyFormat";
|
||||
import { useEtherStore } from "@/store/ether";
|
||||
import { storeToRefs } from "pinia";
|
||||
import { connectProvider } from "@/blockchain/provider";
|
||||
import { TokenEnum } from "@/model/NetworkEnum";
|
||||
import { getTokenImage } from "@/utils/imagesPath";
|
||||
import { onClickOutside } from "@vueuse/core";
|
||||
import { useOnboard } from "@web3-onboard/vue";
|
||||
|
||||
import ChevronDown from "@/assets/chevron.svg";
|
||||
|
||||
// html references
|
||||
const tokenDropdownRef = ref<any>(null);
|
||||
|
||||
// Reactive state
|
||||
const etherStore = useEtherStore();
|
||||
const { walletAddress, selectedToken } = storeToRefs(etherStore);
|
||||
|
||||
const offer = ref<string>("");
|
||||
const pixKey = ref<string>("");
|
||||
const selectTokenToggle = ref<boolean>(false);
|
||||
|
||||
const enableSelectButton = ref<boolean>(false);
|
||||
const hasLiquidity = ref<boolean>(true);
|
||||
const validDecimals = ref<boolean>(true);
|
||||
const validPixFormat = ref<boolean>(true);
|
||||
|
||||
// Emits
|
||||
const emit = defineEmits(["approveTokens"]);
|
||||
|
||||
// Blockchain methods
|
||||
const connectAccount = async (): Promise<void> => {
|
||||
const { connectWallet } = useOnboard();
|
||||
await connectWallet();
|
||||
};
|
||||
|
||||
// Debounce methods
|
||||
const handleInputEvent = (event: any): void => {
|
||||
const { value } = event.target;
|
||||
|
||||
offer.value = value;
|
||||
|
||||
if (decimalCount(offer.value) > 2) {
|
||||
validDecimals.value = false;
|
||||
enableSelectButton.value = false;
|
||||
return;
|
||||
}
|
||||
validDecimals.value = true;
|
||||
};
|
||||
|
||||
const handlePixKeyInputEvent = (event: any): void => {
|
||||
const { value } = event.target;
|
||||
|
||||
pixKey.value = value;
|
||||
|
||||
if (pixFormatValidation(pixKey.value)) {
|
||||
validPixFormat.value = true;
|
||||
enableSelectButton.value = true;
|
||||
return;
|
||||
}
|
||||
|
||||
enableSelectButton.value = false;
|
||||
validPixFormat.value = false;
|
||||
};
|
||||
|
||||
const openTokenSelection = (): void => {
|
||||
selectTokenToggle.value = true;
|
||||
};
|
||||
|
||||
onClickOutside(tokenDropdownRef, () => {
|
||||
selectTokenToggle.value = false;
|
||||
});
|
||||
|
||||
const handleSelectedToken = (token: TokenEnum): void => {
|
||||
etherStore.setSelectedToken(token);
|
||||
selectTokenToggle.value = false;
|
||||
};
|
||||
|
||||
const handleSellClick = async (
|
||||
offer: string,
|
||||
pixKey: string
|
||||
): Promise<void> => {
|
||||
const postProcessedPixKey = postProcessKey(pixKey);
|
||||
emit("approveTokens", { offer, postProcessedPixKey });
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page w-full">
|
||||
<div class="text-container">
|
||||
<span
|
||||
class="text font-extrabold sm:text-5xl text-3xl sm:max-w-[29rem] max-w-[20rem]"
|
||||
>Venda cripto e receba em Pix</span
|
||||
>
|
||||
<span
|
||||
class="text font-medium sm:text-base text-xs sm:max-w-[28rem] max-w-[30rem] sm:tracking-normal tracking-wide"
|
||||
>Digite sua oferta, informe a chave Pix, selecione a rede, aprove o
|
||||
envio da transação e confirme sua oferta.</span
|
||||
>
|
||||
</div>
|
||||
<div class="main-container">
|
||||
<div class="backdrop-blur -z-10 w-full h-full"></div>
|
||||
<div
|
||||
class="flex flex-col w-full bg-white sm:px-10 px-6 py-5 rounded-lg border-y-10"
|
||||
>
|
||||
<div class="flex justify-between items-center">
|
||||
<input
|
||||
type="number"
|
||||
v-model="offer"
|
||||
class="border-none outline-none text-gray-900 sm:w-fit w-3/4"
|
||||
:class="{
|
||||
'!font-medium': offer !== undefined && offer !== '',
|
||||
'text-xl': offer !== undefined && offer !== '',
|
||||
}"
|
||||
@input="debounce(handleInputEvent, 500)($event)"
|
||||
placeholder="Digite sua oferta"
|
||||
step=".01"
|
||||
/>
|
||||
<div class="relative overflow-visible">
|
||||
<button
|
||||
ref="tokenDropdownRef"
|
||||
class="flex flex-row items-center p-2 bg-gray-300 hover:bg-gray-200 focus:outline-indigo-800 focus:outline-2 rounded-3xl min-w-fit gap-2 transition-colors"
|
||||
@click="openTokenSelection()"
|
||||
>
|
||||
<img
|
||||
alt="Token image"
|
||||
class="sm:w-fit w-4"
|
||||
:src="getTokenImage(selectedToken)"
|
||||
/>
|
||||
<span
|
||||
class="text-gray-900 sm:text-lg text-md font-medium"
|
||||
id="token"
|
||||
>
|
||||
{{ selectedToken }}
|
||||
</span>
|
||||
<ChevronDown
|
||||
class="text-gray-900 pr-4 sm:pr-0 transition-all duration-500 ease-in-out"
|
||||
:class="{ 'scale-y-[-1]': selectTokenToggle }"
|
||||
alt="Chevron Down"
|
||||
/>
|
||||
</button>
|
||||
<transition name="dropdown">
|
||||
<div
|
||||
v-if="selectTokenToggle"
|
||||
class="mt-2 text-gray-900 absolute right-0 z-50 w-full min-w-max"
|
||||
>
|
||||
<div
|
||||
class="bg-white rounded-xl z-10 border border-gray-300 drop-shadow-md shadow-md overflow-clip"
|
||||
>
|
||||
<div
|
||||
v-for="token in TokenEnum"
|
||||
:key="token"
|
||||
class="flex menu-button gap-2 px-4 cursor-pointer hover:bg-gray-300 transition-colors"
|
||||
@click="handleSelectedToken(token)"
|
||||
>
|
||||
<img
|
||||
:alt="token + ' logo'"
|
||||
width="20"
|
||||
height="20"
|
||||
:src="getTokenImage(token)"
|
||||
/>
|
||||
<span
|
||||
class="text-gray-900 py-4 text-end font-semibold text-sm"
|
||||
>
|
||||
{{ token }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</transition>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex pt-2 justify-center" v-if="!validDecimals">
|
||||
<span class="text-red-500 font-normal text-sm"
|
||||
>Por favor utilize no máximo 2 casas decimais</span
|
||||
>
|
||||
</div>
|
||||
<div class="flex pt-2 justify-center" v-else-if="!hasLiquidity">
|
||||
<span class="text-red-500 font-normal text-sm"
|
||||
>Atualmente não há liquidez nas redes para sua demanda</span
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="flex flex-col w-full bg-white sm:px-10 px-6 py-8 rounded-lg border-y-10"
|
||||
>
|
||||
<div class="flex justify-between w-full items-center">
|
||||
<input
|
||||
@input="debounce(handlePixKeyInputEvent, 500)($event)"
|
||||
type="text"
|
||||
v-model="pixKey"
|
||||
class="border-none outline-none sm:text-lg text-sm text-gray-900 w-fit"
|
||||
:class="{
|
||||
'!font-medium': pixKey !== undefined && pixKey !== '',
|
||||
'text-xl': pixKey !== undefined && pixKey !== '',
|
||||
}"
|
||||
placeholder="Digite a chave Pix"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex pt-2 justify-center" v-if="!validPixFormat">
|
||||
<span class="text-red-500 font-normal text-sm"
|
||||
>Por favor utilize telefone, CPF ou CNPJ</span
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
<CustomButton
|
||||
v-if="walletAddress"
|
||||
:text="'Aprovar tokens'"
|
||||
:isDisabled="!validDecimals || !validPixFormat"
|
||||
@buttonClicked="handleSellClick(offer, pixKey)"
|
||||
/>
|
||||
<CustomButton
|
||||
v-if="!walletAddress"
|
||||
:text="'Conectar carteira'"
|
||||
@buttonClicked="connectAccount()"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.custom-divide {
|
||||
width: 100%;
|
||||
border-bottom: 1px solid #d1d5db;
|
||||
}
|
||||
.bottom-position {
|
||||
top: -20px;
|
||||
right: 50%;
|
||||
transform: translateX(50%);
|
||||
}
|
||||
|
||||
.page {
|
||||
@apply flex flex-col items-center justify-center w-full mt-16;
|
||||
}
|
||||
|
||||
.text-container {
|
||||
@apply flex flex-col items-center justify-center gap-4;
|
||||
}
|
||||
|
||||
.text {
|
||||
@apply text-white text-center;
|
||||
}
|
||||
|
||||
input[type="number"] {
|
||||
-moz-appearance: textfield;
|
||||
appearance: textfield;
|
||||
}
|
||||
|
||||
input[type="number"]::-webkit-inner-spin-button,
|
||||
input[type="number"]::-webkit-outer-spin-button {
|
||||
-webkit-appearance: none;
|
||||
}
|
||||
|
||||
input {
|
||||
@apply sm:text-lg text-sm;
|
||||
}
|
||||
</style>
|
||||
@@ -1,12 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
import { storeToRefs } from "pinia";
|
||||
import { useEtherStore } from "@/store/ether";
|
||||
import { ref, watch } from "vue";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
import { onClickOutside } from "@vueuse/core";
|
||||
import { NetworkEnum } from "@/model/NetworkEnum";
|
||||
import { getNetworkImage } from "@/utils/imagesPath";
|
||||
import { Networks } from "@/model/Networks";
|
||||
|
||||
import { Networks } from "@/config/networks";
|
||||
import { useOnboard } from "@web3-onboard/vue";
|
||||
|
||||
import ChevronDown from "@/assets/chevronDown.svg";
|
||||
@@ -14,11 +11,12 @@ import TwitterIcon from "@/assets/twitterIcon.svg";
|
||||
import LinkedinIcon from "@/assets/linkedinIcon.svg";
|
||||
import GithubIcon from "@/assets/githubIcon.svg";
|
||||
import { connectProvider } from "@/blockchain/provider";
|
||||
import { DEFAULT_NETWORK } from "@/config/networks";
|
||||
import type { NetworkConfig } from "@/model/NetworkEnum";
|
||||
|
||||
// Store reference
|
||||
const etherStore = useEtherStore();
|
||||
|
||||
const { walletAddress, sellerView } = storeToRefs(etherStore);
|
||||
// Use the new composable
|
||||
const user = useUser();
|
||||
const { walletAddress, sellerView, network } = user;
|
||||
|
||||
const menuOpenToggle = ref<boolean>(false);
|
||||
const infoMenuOpenToggle = ref<boolean>(false);
|
||||
@@ -38,14 +36,29 @@ const connnectWallet = async (): Promise<void> => {
|
||||
watch(connectedWallet, async (newVal: any) => {
|
||||
connectProvider(newVal.provider);
|
||||
const addresses = await newVal.provider.request({ method: "eth_accounts" });
|
||||
etherStore.setWalletAddress(addresses.shift());
|
||||
user.setWalletAddress(addresses.shift());
|
||||
});
|
||||
|
||||
watch(connectedChain, (newVal: any) => {
|
||||
etherStore.setNetworkId(newVal?.id);
|
||||
// Check if connected chain is valid, otherwise default to Sepolia
|
||||
if (
|
||||
!newVal ||
|
||||
!Object.values(Networks).some(
|
||||
(network) => network.id === Number(newVal.id)
|
||||
)
|
||||
) {
|
||||
console.log(
|
||||
"Invalid or unsupported network detected, defaulting to Sepolia"
|
||||
);
|
||||
user.setNetwork(DEFAULT_NETWORK);
|
||||
return;
|
||||
}
|
||||
user.setNetworkById(newVal?.id);
|
||||
});
|
||||
|
||||
const formatWalletAddress = (): string => {
|
||||
if (!walletAddress.value)
|
||||
throw new Error("Wallet not connected");
|
||||
const walletAddressLength = walletAddress.value.length;
|
||||
const initialText = walletAddress.value.substring(0, 5);
|
||||
const finalText = walletAddress.value.substring(
|
||||
@@ -56,7 +69,7 @@ const formatWalletAddress = (): string => {
|
||||
};
|
||||
|
||||
const disconnectUser = async (): Promise<void> => {
|
||||
etherStore.setWalletAddress("");
|
||||
user.setWalletAddress(null);
|
||||
await disconnectWallet({ label: connectedWallet.value?.label || "" });
|
||||
closeMenu();
|
||||
};
|
||||
@@ -65,14 +78,15 @@ const closeMenu = (): void => {
|
||||
menuOpenToggle.value = false;
|
||||
};
|
||||
|
||||
const networkChange = async (network: NetworkEnum): Promise<void> => {
|
||||
const networkChange = async (network: NetworkConfig): Promise<void> => {
|
||||
currencyMenuOpenToggle.value = false;
|
||||
const chainId = network.id.toString(16)
|
||||
try {
|
||||
await setChain({
|
||||
chainId: Networks[network].chainId,
|
||||
chainId: `0x${chainId}`,
|
||||
wallet: connectedWallet.value?.label || "",
|
||||
});
|
||||
etherStore.setNetworkId(network);
|
||||
user.setNetwork(network);
|
||||
} catch (error) {
|
||||
console.log("Error changing network", error);
|
||||
}
|
||||
@@ -245,7 +259,7 @@ onClickOutside(infoMenuRef, () => {
|
||||
>
|
||||
<img
|
||||
alt="Choosed network image"
|
||||
:src="getNetworkImage(NetworkEnum[etherStore.networkName])"
|
||||
:src="getNetworkImage(network.name)"
|
||||
height="24"
|
||||
width="24"
|
||||
/>
|
||||
@@ -253,7 +267,9 @@ onClickOutside(infoMenuRef, () => {
|
||||
class="default-text hidden sm:inline-block text-gray-50 group-hover:text-gray-900 transition-all duration-500 ease-in-out whitespace-nowrap text-ellipsis overflow-hidden"
|
||||
:class="{ '!text-gray-900': currencyMenuOpenToggle }"
|
||||
>
|
||||
{{ Networks[etherStore.networkName].chainName }}
|
||||
{{
|
||||
user.network.value.name || "Invalid Chain"
|
||||
}}
|
||||
</span>
|
||||
<div
|
||||
class="transition-all duration-500 ease-in-out mt-1"
|
||||
@@ -275,20 +291,20 @@ onClickOutside(infoMenuRef, () => {
|
||||
class="mt-2 bg-white rounded-md border border-gray-300 drop-shadow-md shadow-md overflow-clip"
|
||||
>
|
||||
<div
|
||||
v-for="(chainData, network) in Networks"
|
||||
:key="network"
|
||||
v-for="network in Networks"
|
||||
:key="network.id"
|
||||
class="menu-button p-4 gap-2 cursor-pointer hover:bg-gray-200 flex items-center !justify-start whitespace-nowrap transition-colors duration-150 ease-in-out"
|
||||
@click="networkChange(network)"
|
||||
>
|
||||
<img
|
||||
:alt="chainData.chainName + ' image'"
|
||||
:alt="network.name + ' image'"
|
||||
width="20"
|
||||
height="20"
|
||||
:src="getNetworkImage(NetworkEnum[network])"
|
||||
:src="getNetworkImage(network.name)"
|
||||
class="mr-2 ml-1"
|
||||
/>
|
||||
<span class="text-gray-900 font-semibold text-sm">
|
||||
{{ chainData.chainName }}
|
||||
{{ network.name }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="w-full flex justify-center">
|
||||
@@ -445,19 +461,19 @@ onClickOutside(infoMenuRef, () => {
|
||||
<div class="pl-4 mt-2 h-full">
|
||||
<div class="bg-white rounded-md z-10 h-full">
|
||||
<div
|
||||
v-for="(chainData, network) in Networks"
|
||||
:key="network"
|
||||
v-for="network in Networks"
|
||||
:key="network.id"
|
||||
class="menu-button gap-2 sm:px-4 rounded-md cursor-pointer py-2 px-4"
|
||||
@click="networkChange(network)"
|
||||
>
|
||||
<img
|
||||
:alt="chainData.chainName + 'image'"
|
||||
:alt="network.name + 'image'"
|
||||
width="20"
|
||||
height="20"
|
||||
:src="getNetworkImage(NetworkEnum[network])"
|
||||
:src="getNetworkImage(network.name)"
|
||||
/>
|
||||
<span class="text-gray-900 py-4 text-end font-bold text-sm">
|
||||
{{ chainData.chainName }}
|
||||
{{ network.name }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
/* eslint-disable no-undef */
|
||||
import { shallowMount } from "@vue/test-utils";
|
||||
import TopBar from "../TopBar.vue";
|
||||
import { useEtherStore } from "../../../store/ether";
|
||||
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
|
||||
describe("TopBar.vue", () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
});
|
||||
|
||||
it("should render connect wallet button", () => {
|
||||
const wrapper = shallowMount(TopBar);
|
||||
expect(wrapper.html()).toContain("Conectar carteira");
|
||||
});
|
||||
|
||||
it("should render button to change to seller view when in buyer screen", () => {
|
||||
const wrapper = shallowMount(TopBar);
|
||||
expect(wrapper.html()).toContain("Quero vender");
|
||||
});
|
||||
|
||||
it("should render button to change to seller view when in buyer screen", () => {
|
||||
const etherStore = useEtherStore();
|
||||
etherStore.setSellerView(true);
|
||||
const wrapper = shallowMount(TopBar);
|
||||
expect(wrapper.html()).toContain("Quero comprar");
|
||||
});
|
||||
|
||||
it("should render the P2Pix logo correctly", () => {
|
||||
const wrapper = shallowMount(TopBar);
|
||||
const img = wrapper.findAll(".logo");
|
||||
expect(img.length).toBe(2);
|
||||
});
|
||||
});
|
||||
208
src/components/ui/AmountInput.vue
Normal file
@@ -0,0 +1,208 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch, computed } from "vue";
|
||||
import { TokenEnum } from "@/model/NetworkEnum";
|
||||
import { decimalCount } from "@/utils/decimalCount";
|
||||
import { debounce } from "@/utils/debounce";
|
||||
import TokenSelector from "./TokenSelector.vue";
|
||||
import ErrorMessage from "./ErrorMessage.vue";
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
modelValue: number;
|
||||
selectedToken: TokenEnum;
|
||||
placeholder?: string;
|
||||
showTokenSelector?: boolean;
|
||||
showConversion?: boolean;
|
||||
conversionRate?: number;
|
||||
minValue?: number;
|
||||
maxValue?: number;
|
||||
disabled?: boolean;
|
||||
required?: boolean;
|
||||
}>(),
|
||||
{
|
||||
placeholder: "0",
|
||||
showTokenSelector: true,
|
||||
showConversion: true,
|
||||
conversionRate: 1,
|
||||
minValue: 0,
|
||||
disabled: false,
|
||||
required: false,
|
||||
}
|
||||
);
|
||||
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [value: number];
|
||||
"update:selectedToken": [token: TokenEnum];
|
||||
error: [message: string | null];
|
||||
valid: [isValid: boolean];
|
||||
}>();
|
||||
|
||||
const inputValue = ref<string>(String(props.modelValue || ""));
|
||||
const validDecimals = ref(true);
|
||||
const validRange = ref(true);
|
||||
|
||||
const convertedValue = computed(() => {
|
||||
return (props.modelValue * props.conversionRate).toFixed(2);
|
||||
});
|
||||
|
||||
const errorMessage = computed(() => {
|
||||
if (!validDecimals.value) {
|
||||
return "Por favor utilize no máximo 2 casas decimais";
|
||||
}
|
||||
if (!validRange.value) {
|
||||
if (props.minValue && props.modelValue < props.minValue) {
|
||||
return `Valor mínimo: ${props.minValue}`;
|
||||
}
|
||||
if (props.maxValue && props.modelValue > props.maxValue) {
|
||||
return `Valor máximo: ${props.maxValue}`;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const isValid = computed(() => {
|
||||
return validDecimals.value && validRange.value;
|
||||
});
|
||||
|
||||
const handleInput = (event: Event) => {
|
||||
const target = event.target as HTMLInputElement;
|
||||
const value = target.value;
|
||||
inputValue.value = value;
|
||||
|
||||
const numValue = Number(value);
|
||||
|
||||
// Validar decimais
|
||||
if (decimalCount(value) > 2) {
|
||||
validDecimals.value = false;
|
||||
emit("error", "Por favor utilize no máximo 2 casas decimais");
|
||||
emit("valid", false);
|
||||
return;
|
||||
}
|
||||
validDecimals.value = true;
|
||||
|
||||
// Validar range
|
||||
if (props.minValue !== undefined && numValue < props.minValue) {
|
||||
validRange.value = false;
|
||||
emit("error", `Valor mínimo: ${props.minValue}`);
|
||||
emit("valid", false);
|
||||
return;
|
||||
}
|
||||
if (props.maxValue !== undefined && numValue > props.maxValue) {
|
||||
validRange.value = false;
|
||||
emit("error", `Valor máximo: ${props.maxValue}`);
|
||||
emit("valid", false);
|
||||
return;
|
||||
}
|
||||
validRange.value = true;
|
||||
|
||||
emit("update:modelValue", numValue);
|
||||
emit("error", null);
|
||||
emit("valid", true);
|
||||
};
|
||||
|
||||
const debouncedHandleInput = debounce(handleInput, 500);
|
||||
|
||||
const handleTokenChange = (token: TokenEnum) => {
|
||||
emit("update:selectedToken", token);
|
||||
};
|
||||
|
||||
watch(() => props.modelValue, (newVal) => {
|
||||
if (newVal !== Number(inputValue.value)) {
|
||||
inputValue.value = String(newVal || "");
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="amount-input-container">
|
||||
<div class="input-row">
|
||||
<input
|
||||
type="number"
|
||||
:value="inputValue"
|
||||
:placeholder="placeholder"
|
||||
:disabled="disabled"
|
||||
:required="required"
|
||||
class="amount-input"
|
||||
:class="{
|
||||
'font-semibold text-xl': modelValue > 0,
|
||||
'has-error': !isValid,
|
||||
}"
|
||||
step="0.01"
|
||||
@input="debouncedHandleInput"
|
||||
/>
|
||||
|
||||
<TokenSelector
|
||||
v-if="showTokenSelector"
|
||||
:model-value="selectedToken"
|
||||
:disabled="disabled"
|
||||
size="md"
|
||||
@update:model-value="handleTokenChange"
|
||||
/>
|
||||
|
||||
<div v-else class="token-display">
|
||||
{{ selectedToken }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="divider"></div>
|
||||
|
||||
<div class="info-row">
|
||||
<p v-if="showConversion" class="conversion-text">
|
||||
~ R$ {{ convertedValue }}
|
||||
</p>
|
||||
<slot name="extra-info"></slot>
|
||||
</div>
|
||||
|
||||
<ErrorMessage
|
||||
v-if="errorMessage"
|
||||
:message="errorMessage"
|
||||
type="error"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.amount-input-container {
|
||||
@apply flex flex-col w-full gap-2;
|
||||
}
|
||||
|
||||
.input-row {
|
||||
@apply flex justify-between items-center w-full gap-4;
|
||||
}
|
||||
|
||||
.amount-input {
|
||||
@apply border-none outline-none text-lg text-gray-900 flex-1 bg-transparent;
|
||||
appearance: textfield;
|
||||
-moz-appearance: textfield;
|
||||
}
|
||||
|
||||
.amount-input::-webkit-inner-spin-button,
|
||||
.amount-input::-webkit-outer-spin-button {
|
||||
-webkit-appearance: none;
|
||||
}
|
||||
|
||||
.amount-input:disabled {
|
||||
@apply opacity-50 cursor-not-allowed;
|
||||
}
|
||||
|
||||
.amount-input.has-error {
|
||||
@apply text-red-500;
|
||||
}
|
||||
|
||||
.token-display {
|
||||
@apply flex items-center px-3 py-2 bg-gray-300 rounded-3xl min-w-fit text-gray-900 font-medium;
|
||||
}
|
||||
|
||||
.divider {
|
||||
@apply w-full border-b border-gray-300 my-2;
|
||||
}
|
||||
|
||||
.info-row {
|
||||
@apply flex justify-between items-center;
|
||||
}
|
||||
|
||||
.conversion-text {
|
||||
@apply text-gray-500 font-normal text-sm;
|
||||
}
|
||||
</style>
|
||||
|
||||
137
src/components/ui/BankSelector.vue
Normal file
@@ -0,0 +1,137 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import bankList from "@/utils/files/isbpList.json";
|
||||
|
||||
export interface Bank {
|
||||
ISPB: string;
|
||||
longName: string;
|
||||
}
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
modelValue: string | null;
|
||||
disabled?: boolean;
|
||||
placeholder?: string;
|
||||
}>(),
|
||||
{
|
||||
disabled: false,
|
||||
placeholder: "Busque e selecione seu banco",
|
||||
}
|
||||
);
|
||||
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [value: string];
|
||||
change: [bank: Bank];
|
||||
}>();
|
||||
|
||||
const bankItems = computed(() => {
|
||||
return bankList.map((bank) => ({
|
||||
value: bank.ISPB,
|
||||
label: bank.longName,
|
||||
bank: bank,
|
||||
}));
|
||||
});
|
||||
|
||||
const selectedItem = computed(() => {
|
||||
if (!props.modelValue) return null;
|
||||
return bankItems.value.find((item) => item.value === props.modelValue);
|
||||
});
|
||||
|
||||
const searchQuery = computed({
|
||||
get: () => selectedItem.value?.label || "",
|
||||
set: (value: string) => {
|
||||
// Handled by input
|
||||
},
|
||||
});
|
||||
|
||||
const filteredBanks = computed(() => {
|
||||
if (!searchQuery.value) return [];
|
||||
|
||||
const query = searchQuery.value.toLowerCase();
|
||||
return bankList
|
||||
.filter((bank) => bank.longName.toLowerCase().includes(query))
|
||||
.slice(0, 10);
|
||||
});
|
||||
|
||||
const showBankList = computed(() => {
|
||||
return filteredBanks.value.length > 0 && searchQuery.value.length > 0;
|
||||
});
|
||||
|
||||
const selectBank = (bank: Bank) => {
|
||||
emit("update:modelValue", bank.ISPB);
|
||||
emit("change", bank);
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="bank-selector">
|
||||
<input
|
||||
type="text"
|
||||
v-model="searchQuery"
|
||||
:placeholder="placeholder"
|
||||
:disabled="disabled"
|
||||
class="bank-input"
|
||||
autocomplete="off"
|
||||
/>
|
||||
|
||||
<transition name="dropdown-fade">
|
||||
<div v-if="showBankList" class="bank-list">
|
||||
<div
|
||||
v-for="bank in filteredBanks"
|
||||
:key="bank.ISPB"
|
||||
class="bank-item"
|
||||
@click="selectBank(bank)"
|
||||
>
|
||||
<span class="bank-name">{{ bank.longName }}</span>
|
||||
<span class="bank-ispb">{{ bank.ISPB }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</transition>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.bank-selector {
|
||||
@apply relative w-full;
|
||||
}
|
||||
|
||||
.bank-input {
|
||||
@apply w-full px-4 py-3 border-none outline-none rounded-lg bg-white text-gray-900 text-sm;
|
||||
}
|
||||
|
||||
.bank-input:focus {
|
||||
@apply ring-2 ring-indigo-800;
|
||||
}
|
||||
|
||||
.bank-input:disabled {
|
||||
@apply opacity-50 cursor-not-allowed bg-gray-100;
|
||||
}
|
||||
|
||||
.bank-list {
|
||||
@apply absolute top-full left-0 right-0 mt-2 bg-white rounded-lg border border-gray-300 shadow-lg z-50 max-h-64 overflow-y-auto;
|
||||
}
|
||||
|
||||
.bank-item {
|
||||
@apply flex justify-between items-center px-4 py-3 cursor-pointer hover:bg-gray-100 transition-colors;
|
||||
}
|
||||
|
||||
.bank-name {
|
||||
@apply text-gray-900 font-medium text-sm flex-1;
|
||||
}
|
||||
|
||||
.bank-ispb {
|
||||
@apply text-gray-500 text-xs ml-2;
|
||||
}
|
||||
|
||||
/* Animação */
|
||||
.dropdown-fade-enter-active,
|
||||
.dropdown-fade-leave-active {
|
||||
@apply transition-all duration-200;
|
||||
}
|
||||
|
||||
.dropdown-fade-enter-from,
|
||||
.dropdown-fade-leave-to {
|
||||
@apply opacity-0 -translate-y-2;
|
||||
}
|
||||
</style>
|
||||
|
||||
161
src/components/ui/CustomButton.vue
Normal file
@@ -0,0 +1,161 @@
|
||||
<script setup lang="ts">
|
||||
export type ButtonVariant = "primary" | "secondary" | "outline" | "ghost";
|
||||
export type ButtonSize = "sm" | "md" | "lg" | "xl";
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
text: string;
|
||||
isDisabled?: boolean;
|
||||
variant?: ButtonVariant;
|
||||
size?: ButtonSize;
|
||||
icon?: string;
|
||||
iconPosition?: "left" | "right";
|
||||
fullWidth?: boolean;
|
||||
loading?: boolean;
|
||||
}>(),
|
||||
{
|
||||
isDisabled: false,
|
||||
variant: "primary",
|
||||
size: "xl",
|
||||
iconPosition: "left",
|
||||
fullWidth: true,
|
||||
loading: false,
|
||||
}
|
||||
);
|
||||
|
||||
const emit = defineEmits(["buttonClicked"]);
|
||||
|
||||
const handleClick = () => {
|
||||
if (!props.isDisabled && !props.loading) {
|
||||
emit("buttonClicked");
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button
|
||||
type="button"
|
||||
:class="[
|
||||
'button',
|
||||
`variant-${variant}`,
|
||||
`size-${size}`,
|
||||
{ 'is-disabled': isDisabled || loading, 'full-width': fullWidth },
|
||||
]"
|
||||
:disabled="isDisabled || loading"
|
||||
@click="handleClick"
|
||||
>
|
||||
<span v-if="loading" class="loader"></span>
|
||||
<template v-else>
|
||||
<img
|
||||
v-if="icon && iconPosition === 'left'"
|
||||
:src="icon"
|
||||
:alt="`${text} icon`"
|
||||
class="button-icon"
|
||||
/>
|
||||
<span class="button-text">{{ text }}</span>
|
||||
<img
|
||||
v-if="icon && iconPosition === 'right'"
|
||||
:src="icon"
|
||||
:alt="`${text} icon`"
|
||||
class="button-icon"
|
||||
/>
|
||||
</template>
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.button {
|
||||
@apply rounded-lg font-semibold transition-all duration-200 cursor-pointer flex items-center justify-center gap-2;
|
||||
}
|
||||
|
||||
.button:hover:not(.is-disabled) {
|
||||
@apply transform scale-[1.02];
|
||||
}
|
||||
|
||||
.button.is-disabled {
|
||||
@apply opacity-70 cursor-not-allowed;
|
||||
}
|
||||
|
||||
.button.full-width {
|
||||
@apply w-full;
|
||||
}
|
||||
|
||||
/* Variantes */
|
||||
.variant-primary {
|
||||
@apply bg-amber-400 text-gray-900 border-2 border-amber-400;
|
||||
}
|
||||
|
||||
.variant-primary:hover:not(.is-disabled) {
|
||||
@apply bg-amber-500 border-amber-500;
|
||||
}
|
||||
|
||||
.variant-secondary {
|
||||
@apply bg-gray-200 text-gray-900 border-2 border-gray-300;
|
||||
}
|
||||
|
||||
.variant-secondary:hover:not(.is-disabled) {
|
||||
@apply bg-gray-300 border-gray-400;
|
||||
}
|
||||
|
||||
.variant-outline {
|
||||
@apply bg-transparent text-gray-900 border-2 border-amber-400;
|
||||
}
|
||||
|
||||
.variant-outline:hover:not(.is-disabled) {
|
||||
@apply bg-amber-400/10;
|
||||
}
|
||||
|
||||
.variant-ghost {
|
||||
@apply bg-transparent text-gray-900 border-2 border-transparent;
|
||||
}
|
||||
|
||||
.variant-ghost:hover:not(.is-disabled) {
|
||||
@apply bg-gray-100;
|
||||
}
|
||||
|
||||
/* Tamanhos */
|
||||
.size-sm {
|
||||
@apply px-2 py-1 text-xs;
|
||||
}
|
||||
|
||||
.size-sm .button-icon {
|
||||
@apply w-3 h-3;
|
||||
}
|
||||
|
||||
.size-md {
|
||||
@apply px-3 py-2 text-sm;
|
||||
}
|
||||
|
||||
.size-md .button-icon {
|
||||
@apply w-4 h-4;
|
||||
}
|
||||
|
||||
.size-lg {
|
||||
@apply px-4 py-3 text-base;
|
||||
}
|
||||
|
||||
.size-lg .button-icon {
|
||||
@apply w-5 h-5;
|
||||
}
|
||||
|
||||
.size-xl {
|
||||
@apply p-4 text-base;
|
||||
}
|
||||
|
||||
.size-xl .button-icon {
|
||||
@apply w-5 h-5;
|
||||
}
|
||||
|
||||
.button-icon {
|
||||
@apply flex-shrink-0;
|
||||
}
|
||||
|
||||
.button-text {
|
||||
@apply font-semibold;
|
||||
}
|
||||
|
||||
/* Loader animation */
|
||||
.loader {
|
||||
@apply w-5 h-5 border-2 border-gray-900 border-t-transparent rounded-full animate-spin;
|
||||
}
|
||||
</style>
|
||||
@@ -19,7 +19,7 @@ if (props.isRedirectModal) {
|
||||
<template>
|
||||
<div>
|
||||
<div
|
||||
class="modal-overlay inset-0 fixed justify-center backdrop-blur-sm sm:backdrop-blur-none"
|
||||
class="modal-overlay inset-0 fixed hidden md:block justify-center backdrop-blur-sm sm:backdrop-blur-none"
|
||||
v-if="!isRedirectModal"
|
||||
>
|
||||
<div class="modal px-5 text-center">
|
||||
248
src/components/ui/Dropdown.vue
Normal file
@@ -0,0 +1,248 @@
|
||||
<script setup lang="ts" generic="T">
|
||||
import { ref, computed } from "vue";
|
||||
import { onClickOutside } from "@vueuse/core";
|
||||
import ChevronDown from "@/assets/chevronDown.svg";
|
||||
|
||||
export interface DropdownItem<T = any> {
|
||||
value: T;
|
||||
label: string;
|
||||
icon?: string;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
items: DropdownItem<T>[];
|
||||
modelValue: T;
|
||||
placeholder?: string;
|
||||
searchable?: boolean;
|
||||
disabled?: boolean;
|
||||
size?: "sm" | "md" | "lg";
|
||||
showIcon?: boolean;
|
||||
}>(),
|
||||
{
|
||||
placeholder: "Selecione...",
|
||||
searchable: false,
|
||||
disabled: false,
|
||||
size: "md",
|
||||
showIcon: true,
|
||||
}
|
||||
);
|
||||
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [value: T];
|
||||
change: [value: T];
|
||||
}>();
|
||||
|
||||
const isOpen = ref(false);
|
||||
const searchQuery = ref("");
|
||||
const dropdownRef = ref<HTMLElement | null>(null);
|
||||
|
||||
const selectedItem = computed(() => {
|
||||
return props.items.find((item) => item.value === props.modelValue);
|
||||
});
|
||||
|
||||
const filteredItems = computed(() => {
|
||||
if (!props.searchable || !searchQuery.value) {
|
||||
return props.items;
|
||||
}
|
||||
|
||||
const query = searchQuery.value.toLowerCase();
|
||||
return props.items.filter((item) =>
|
||||
item.label.toLowerCase().includes(query)
|
||||
);
|
||||
});
|
||||
|
||||
const toggleDropdown = () => {
|
||||
if (!props.disabled) {
|
||||
isOpen.value = !isOpen.value;
|
||||
if (!isOpen.value) {
|
||||
searchQuery.value = "";
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const selectItem = (item: DropdownItem<T>) => {
|
||||
if (!item.disabled) {
|
||||
emit("update:modelValue", item.value);
|
||||
emit("change", item.value);
|
||||
isOpen.value = false;
|
||||
searchQuery.value = "";
|
||||
}
|
||||
};
|
||||
|
||||
onClickOutside(dropdownRef, () => {
|
||||
isOpen.value = false;
|
||||
searchQuery.value = "";
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="dropdownRef" class="dropdown-container">
|
||||
<button
|
||||
type="button"
|
||||
:class="[
|
||||
'dropdown-trigger',
|
||||
`size-${size}`,
|
||||
{ disabled: disabled, open: isOpen },
|
||||
]"
|
||||
@click="toggleDropdown"
|
||||
>
|
||||
<img
|
||||
v-if="selectedItem?.icon && showIcon"
|
||||
:src="selectedItem.icon"
|
||||
:alt="selectedItem.label"
|
||||
class="item-icon"
|
||||
/>
|
||||
<span class="selected-text">
|
||||
{{ selectedItem?.label || placeholder }}
|
||||
</span>
|
||||
<ChevronDown
|
||||
class="chevron"
|
||||
:class="{ rotated: isOpen }"
|
||||
/>
|
||||
</button>
|
||||
|
||||
<transition name="dropdown-fade">
|
||||
<div v-if="isOpen" class="dropdown-menu">
|
||||
<input
|
||||
v-if="searchable"
|
||||
v-model="searchQuery"
|
||||
type="text"
|
||||
class="search-input"
|
||||
placeholder="Buscar..."
|
||||
@click.stop
|
||||
/>
|
||||
|
||||
<div class="items-container">
|
||||
<div
|
||||
v-for="item in filteredItems"
|
||||
:key="String(item.value)"
|
||||
:class="[
|
||||
'dropdown-item',
|
||||
{
|
||||
selected: item.value === modelValue,
|
||||
disabled: item.disabled,
|
||||
},
|
||||
]"
|
||||
@click="selectItem(item)"
|
||||
>
|
||||
<img
|
||||
v-if="item.icon && showIcon"
|
||||
:src="item.icon"
|
||||
:alt="item.label"
|
||||
class="item-icon"
|
||||
/>
|
||||
<span class="item-label">{{ item.label }}</span>
|
||||
</div>
|
||||
|
||||
<div v-if="filteredItems.length === 0" class="no-results">
|
||||
Nenhum resultado encontrado
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</transition>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.dropdown-container {
|
||||
@apply relative inline-block;
|
||||
}
|
||||
|
||||
.dropdown-trigger {
|
||||
@apply flex items-center gap-2 bg-gray-300 hover:bg-gray-200 rounded-3xl transition-colors cursor-pointer border-none outline-none;
|
||||
}
|
||||
|
||||
.dropdown-trigger:focus {
|
||||
@apply outline-2 outline-indigo-800;
|
||||
}
|
||||
|
||||
.dropdown-trigger.disabled {
|
||||
@apply opacity-50 cursor-not-allowed;
|
||||
}
|
||||
|
||||
.dropdown-trigger.disabled:hover {
|
||||
@apply bg-gray-300;
|
||||
}
|
||||
|
||||
.size-sm {
|
||||
@apply px-2 py-1 text-sm;
|
||||
}
|
||||
|
||||
.size-md {
|
||||
@apply px-3 py-2 text-base;
|
||||
}
|
||||
|
||||
.size-lg {
|
||||
@apply px-4 py-3 text-lg;
|
||||
}
|
||||
|
||||
.item-icon {
|
||||
@apply sm:w-fit w-4 flex-shrink-0;
|
||||
}
|
||||
|
||||
.selected-text {
|
||||
@apply text-gray-900 font-medium min-w-fit;
|
||||
}
|
||||
|
||||
.chevron {
|
||||
@apply transition-transform duration-300 invert pr-1;
|
||||
}
|
||||
|
||||
.chevron.rotated {
|
||||
@apply rotate-180;
|
||||
}
|
||||
|
||||
.dropdown-menu {
|
||||
@apply absolute right-0 mt-2 bg-white rounded-xl border border-gray-300 shadow-md z-50 min-w-max w-full;
|
||||
}
|
||||
|
||||
.search-input {
|
||||
@apply w-full px-4 py-3 border-b border-gray-200 outline-none text-gray-900;
|
||||
}
|
||||
|
||||
.search-input:focus {
|
||||
@apply border-indigo-800;
|
||||
}
|
||||
|
||||
.items-container {
|
||||
@apply max-h-64 overflow-y-auto;
|
||||
}
|
||||
|
||||
.dropdown-item {
|
||||
@apply flex items-center gap-2 px-4 py-4 cursor-pointer hover:bg-gray-300 transition-colors text-gray-900 font-semibold text-sm;
|
||||
}
|
||||
|
||||
.dropdown-item.selected {
|
||||
@apply bg-gray-100;
|
||||
}
|
||||
|
||||
.dropdown-item.disabled {
|
||||
@apply opacity-50 cursor-not-allowed;
|
||||
}
|
||||
|
||||
.dropdown-item.disabled:hover {
|
||||
@apply bg-transparent;
|
||||
}
|
||||
|
||||
.item-label {
|
||||
@apply text-end;
|
||||
}
|
||||
|
||||
.no-results {
|
||||
@apply px-4 py-6 text-center text-gray-500 text-sm;
|
||||
}
|
||||
|
||||
/* Animação */
|
||||
.dropdown-fade-enter-active,
|
||||
.dropdown-fade-leave-active {
|
||||
@apply transition-all duration-200;
|
||||
}
|
||||
|
||||
.dropdown-fade-enter-from,
|
||||
.dropdown-fade-leave-to {
|
||||
@apply opacity-0 -translate-y-2;
|
||||
}
|
||||
</style>
|
||||
|
||||
55
src/components/ui/ErrorMessage.vue
Normal file
@@ -0,0 +1,55 @@
|
||||
<script setup lang="ts">
|
||||
export type ErrorType = "error" | "warning" | "info";
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
message: string;
|
||||
type?: ErrorType;
|
||||
centered?: boolean;
|
||||
icon?: boolean;
|
||||
}>(),
|
||||
{
|
||||
type: "error",
|
||||
centered: true,
|
||||
icon: false,
|
||||
}
|
||||
);
|
||||
|
||||
const colorClasses = {
|
||||
error: "text-red-500",
|
||||
warning: "text-amber-500",
|
||||
info: "text-blue-500",
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div :class="['error-message-container', { centered: centered }]">
|
||||
<div :class="['error-message', colorClasses[type]]">
|
||||
<span v-if="icon" class="icon">⚠</span>
|
||||
<span class="message">{{ message }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.error-message-container {
|
||||
@apply flex w-full;
|
||||
}
|
||||
|
||||
.error-message-container.centered {
|
||||
@apply justify-center;
|
||||
}
|
||||
|
||||
.error-message {
|
||||
@apply font-normal text-sm flex items-center gap-2;
|
||||
}
|
||||
|
||||
.icon {
|
||||
@apply text-base;
|
||||
}
|
||||
|
||||
.message {
|
||||
@apply leading-tight;
|
||||
}
|
||||
</style>
|
||||
|
||||
55
src/components/ui/FormCard.vue
Normal file
@@ -0,0 +1,55 @@
|
||||
<script setup lang="ts">
|
||||
export type FormCardPadding = "sm" | "md" | "lg";
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
padding?: FormCardPadding;
|
||||
fullWidth?: boolean;
|
||||
noBorder?: boolean;
|
||||
}>(),
|
||||
{
|
||||
padding: "md",
|
||||
fullWidth: true,
|
||||
noBorder: false,
|
||||
}
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
:class="[
|
||||
'form-card',
|
||||
`padding-${padding}`,
|
||||
{ 'full-width': fullWidth, 'no-border': noBorder },
|
||||
]"
|
||||
>
|
||||
<slot></slot>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.form-card {
|
||||
@apply flex flex-col bg-white rounded-lg;
|
||||
}
|
||||
|
||||
.form-card:not(.no-border) {
|
||||
@apply border-y-10;
|
||||
}
|
||||
|
||||
.form-card.full-width {
|
||||
@apply w-full;
|
||||
}
|
||||
|
||||
.padding-sm {
|
||||
@apply px-4 py-3;
|
||||
}
|
||||
|
||||
.padding-md {
|
||||
@apply sm:px-10 px-6 py-5;
|
||||
}
|
||||
|
||||
.padding-lg {
|
||||
@apply px-12 py-8;
|
||||
}
|
||||
</style>
|
||||
|
||||
147
src/components/ui/IconButton.vue
Normal file
@@ -0,0 +1,147 @@
|
||||
<script setup lang="ts">
|
||||
export type IconButtonVariant = "primary" | "secondary" | "outline" | "ghost";
|
||||
export type IconButtonSize = "sm" | "md" | "lg";
|
||||
export type IconPosition = "left" | "right";
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
text: string;
|
||||
icon?: string;
|
||||
variant?: IconButtonVariant;
|
||||
size?: IconButtonSize;
|
||||
iconPosition?: IconPosition;
|
||||
disabled?: boolean;
|
||||
fullWidth?: boolean;
|
||||
}>(),
|
||||
{
|
||||
variant: "outline",
|
||||
size: "md",
|
||||
iconPosition: "left",
|
||||
disabled: false,
|
||||
fullWidth: false,
|
||||
}
|
||||
);
|
||||
|
||||
const emit = defineEmits<{
|
||||
click: [];
|
||||
}>();
|
||||
|
||||
const handleClick = () => {
|
||||
if (!props.disabled) {
|
||||
emit("click");
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button
|
||||
type="button"
|
||||
:class="[
|
||||
'icon-button',
|
||||
`variant-${variant}`,
|
||||
`size-${size}`,
|
||||
{ 'is-disabled': disabled, 'full-width': fullWidth },
|
||||
]"
|
||||
:disabled="disabled"
|
||||
@click="handleClick"
|
||||
>
|
||||
<img
|
||||
v-if="icon && iconPosition === 'left'"
|
||||
:src="icon"
|
||||
:alt="`${text} icon`"
|
||||
class="button-icon"
|
||||
/>
|
||||
<span class="button-text">{{ text }}</span>
|
||||
<img
|
||||
v-if="icon && iconPosition === 'right'"
|
||||
:src="icon"
|
||||
:alt="`${text} icon`"
|
||||
class="button-icon"
|
||||
/>
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.icon-button {
|
||||
@apply flex items-center justify-center gap-2 font-medium rounded-lg transition-all duration-200 cursor-pointer;
|
||||
}
|
||||
|
||||
.icon-button:hover:not(.is-disabled) {
|
||||
@apply transform scale-[1.02];
|
||||
}
|
||||
|
||||
.icon-button.is-disabled {
|
||||
@apply opacity-60 cursor-not-allowed;
|
||||
}
|
||||
|
||||
.icon-button.full-width {
|
||||
@apply w-full;
|
||||
}
|
||||
|
||||
/* Variantes */
|
||||
.variant-primary {
|
||||
@apply bg-amber-400 text-gray-900 border-2 border-amber-400;
|
||||
}
|
||||
|
||||
.variant-primary:hover:not(.is-disabled) {
|
||||
@apply bg-amber-500 border-amber-500;
|
||||
}
|
||||
|
||||
.variant-secondary {
|
||||
@apply bg-gray-200 text-gray-900 border-2 border-gray-300;
|
||||
}
|
||||
|
||||
.variant-secondary:hover:not(.is-disabled) {
|
||||
@apply bg-gray-300 border-gray-400;
|
||||
}
|
||||
|
||||
.variant-outline {
|
||||
@apply bg-transparent text-gray-900 border-2 border-amber-300;
|
||||
}
|
||||
|
||||
.variant-outline:hover:not(.is-disabled) {
|
||||
@apply bg-amber-300/10;
|
||||
}
|
||||
|
||||
.variant-ghost {
|
||||
@apply bg-transparent text-gray-900 border-2 border-transparent;
|
||||
}
|
||||
|
||||
.variant-ghost:hover:not(.is-disabled) {
|
||||
@apply bg-gray-100;
|
||||
}
|
||||
|
||||
/* Tamanhos */
|
||||
.size-sm {
|
||||
@apply px-2 py-1 text-xs;
|
||||
}
|
||||
|
||||
.size-sm .button-icon {
|
||||
@apply w-3 h-3;
|
||||
}
|
||||
|
||||
.size-md {
|
||||
@apply px-3 py-2 text-sm;
|
||||
}
|
||||
|
||||
.size-md .button-icon {
|
||||
@apply w-4 h-4;
|
||||
}
|
||||
|
||||
.size-lg {
|
||||
@apply px-4 py-3 text-base;
|
||||
}
|
||||
|
||||
.size-lg .button-icon {
|
||||
@apply w-5 h-5;
|
||||
}
|
||||
|
||||
.button-text {
|
||||
@apply font-semibold;
|
||||
}
|
||||
|
||||
.button-icon {
|
||||
@apply flex-shrink-0;
|
||||
}
|
||||
</style>
|
||||
|
||||
91
src/components/ui/InfoTooltip.vue
Normal file
@@ -0,0 +1,91 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from "vue";
|
||||
import { useFloating, arrow, offset, flip, shift } from "@floating-ui/vue";
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
text: string;
|
||||
placement?: "top" | "bottom" | "left" | "right";
|
||||
iconSrc?: string;
|
||||
showOnHover?: boolean;
|
||||
}>(),
|
||||
{
|
||||
placement: "right",
|
||||
iconSrc: "",
|
||||
showOnHover: true,
|
||||
}
|
||||
);
|
||||
|
||||
const showTooltip = ref<boolean>(false);
|
||||
const reference = ref<HTMLElement | null>(null);
|
||||
const floating = ref<HTMLElement | null>(null);
|
||||
const floatingArrow = ref(null);
|
||||
|
||||
onMounted(() => {
|
||||
useFloating(reference, floating, {
|
||||
placement: props.placement,
|
||||
middleware: [offset(10), flip(), shift(), arrow({ element: floatingArrow })],
|
||||
});
|
||||
});
|
||||
|
||||
const handleMouseOver = () => {
|
||||
if (props.showOnHover) {
|
||||
showTooltip.value = true;
|
||||
}
|
||||
};
|
||||
|
||||
const handleMouseOut = () => {
|
||||
if (props.showOnHover) {
|
||||
showTooltip.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const toggleTooltip = () => {
|
||||
if (!props.showOnHover) {
|
||||
showTooltip.value = !showTooltip.value;
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="info-tooltip-container">
|
||||
<img
|
||||
:src="iconSrc || '/src/assets/info.svg'"
|
||||
alt="info icon"
|
||||
class="info-icon"
|
||||
ref="reference"
|
||||
@mouseover="handleMouseOver"
|
||||
@mouseout="handleMouseOut"
|
||||
@click="toggleTooltip"
|
||||
/>
|
||||
<div
|
||||
v-if="showTooltip"
|
||||
role="tooltip"
|
||||
ref="floating"
|
||||
class="tooltip-content"
|
||||
>
|
||||
{{ text }}
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.info-tooltip-container {
|
||||
@apply relative inline-block;
|
||||
}
|
||||
|
||||
.info-icon {
|
||||
@apply cursor-pointer transition-opacity hover:opacity-70;
|
||||
}
|
||||
|
||||
.tooltip-content {
|
||||
@apply bg-white text-gray-900 font-medium text-xs md:text-sm px-3 py-2 rounded border-2 border-emerald-500 z-50 max-w-xs shadow-lg;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 640px) {
|
||||
.tooltip-content {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
60
src/components/ui/LoadingState.vue
Normal file
@@ -0,0 +1,60 @@
|
||||
<script setup lang="ts">
|
||||
import SpinnerComponent from "./SpinnerComponent.vue";
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
message?: string;
|
||||
size?: "sm" | "md" | "lg";
|
||||
centered?: boolean;
|
||||
inline?: boolean;
|
||||
}>(),
|
||||
{
|
||||
message: "Carregando...",
|
||||
size: "md",
|
||||
centered: true,
|
||||
inline: false,
|
||||
}
|
||||
);
|
||||
|
||||
const sizeMap = {
|
||||
sm: { spinner: "4", text: "text-sm" },
|
||||
md: { spinner: "6", text: "text-base" },
|
||||
lg: { spinner: "8", text: "text-lg" },
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
:class="[
|
||||
'loading-state',
|
||||
{ centered: centered, inline: inline },
|
||||
]"
|
||||
>
|
||||
<span v-if="message" :class="['loading-message', sizeMap[size].text]">
|
||||
{{ message }}
|
||||
</span>
|
||||
<SpinnerComponent
|
||||
:width="sizeMap[size].spinner"
|
||||
:height="sizeMap[size].spinner"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.loading-state {
|
||||
@apply flex items-center gap-2;
|
||||
}
|
||||
|
||||
.loading-state.centered {
|
||||
@apply justify-center;
|
||||
}
|
||||
|
||||
.loading-state.inline {
|
||||
@apply inline-flex;
|
||||
}
|
||||
|
||||
.loading-message {
|
||||
@apply text-gray-900 font-normal;
|
||||
}
|
||||
</style>
|
||||
|
||||
72
src/components/ui/NetworkBadges.vue
Normal file
@@ -0,0 +1,72 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { getNetworkImage } from "@/utils/imagesPath";
|
||||
import type { NetworkConfig } from "@/model/NetworkEnum";
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
networks: NetworkConfig[];
|
||||
size?: "sm" | "md" | "lg";
|
||||
showLabel?: boolean;
|
||||
}>(),
|
||||
{
|
||||
size: "md",
|
||||
showLabel: false,
|
||||
}
|
||||
);
|
||||
|
||||
const sizeMap = {
|
||||
sm: 16,
|
||||
md: 24,
|
||||
lg: 32,
|
||||
};
|
||||
|
||||
const networkData = computed(() => {
|
||||
return props.networks.map((network) => ({
|
||||
network,
|
||||
image: getNetworkImage(network.name),
|
||||
name: network.name,
|
||||
}));
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="network-badges">
|
||||
<div
|
||||
v-for="data in networkData"
|
||||
:key="data.network.id"
|
||||
class="network-badge"
|
||||
:title="data.name"
|
||||
>
|
||||
<img
|
||||
:alt="`${data.name} logo`"
|
||||
:src="data.image"
|
||||
:width="sizeMap[size]"
|
||||
:height="sizeMap[size]"
|
||||
class="network-icon"
|
||||
/>
|
||||
<span v-if="showLabel" class="network-label">
|
||||
{{ data.name }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.network-badges {
|
||||
@apply flex gap-2 items-center;
|
||||
}
|
||||
|
||||
.network-badge {
|
||||
@apply flex items-center gap-1;
|
||||
}
|
||||
|
||||
.network-icon {
|
||||
@apply flex-shrink-0;
|
||||
}
|
||||
|
||||
.network-label {
|
||||
@apply text-sm font-medium text-gray-900;
|
||||
}
|
||||
</style>
|
||||
|
||||
50
src/components/ui/NetworkSelector.vue
Normal file
@@ -0,0 +1,50 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { Networks } from "@/config/networks";
|
||||
import type { NetworkConfig } from "@/model/NetworkEnum";
|
||||
import { getNetworkImage } from "@/utils/imagesPath";
|
||||
import Dropdown, { type DropdownItem } from "./Dropdown.vue";
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
modelValue: NetworkConfig;
|
||||
disabled?: boolean;
|
||||
size?: "sm" | "md" | "lg";
|
||||
availableNetworks?: NetworkConfig[];
|
||||
}>(),
|
||||
{
|
||||
disabled: false,
|
||||
size: "md",
|
||||
}
|
||||
);
|
||||
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [value: NetworkConfig];
|
||||
change: [value: NetworkConfig];
|
||||
}>();
|
||||
|
||||
const networkItems = computed((): DropdownItem<NetworkConfig>[] => {
|
||||
return Object.values(Networks).map((network) => ({
|
||||
value: network,
|
||||
label: network.name,
|
||||
icon: getNetworkImage(network.name),
|
||||
}));
|
||||
});
|
||||
|
||||
const handleChange = (value: NetworkConfig) => {
|
||||
emit("update:modelValue", value);
|
||||
emit("change", value);
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dropdown
|
||||
:model-value="modelValue"
|
||||
:items="networkItems"
|
||||
:disabled="disabled"
|
||||
:size="size"
|
||||
:show-icon="true"
|
||||
@update:model-value="handleChange"
|
||||
/>
|
||||
</template>
|
||||
|
||||
66
src/components/ui/PageHeader.vue
Normal file
@@ -0,0 +1,66 @@
|
||||
<script setup lang="ts">
|
||||
export type HeaderSize = "sm" | "md" | "lg";
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
size?: HeaderSize;
|
||||
centered?: boolean;
|
||||
}>(),
|
||||
{
|
||||
size: "lg",
|
||||
centered: true,
|
||||
}
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
:class="['page-header', `size-${size}`, { centered: centered }]"
|
||||
>
|
||||
<h1 class="title text-white font-extrabold">
|
||||
{{ title }}
|
||||
</h1>
|
||||
<p v-if="subtitle" class="subtitle text-white font-medium">
|
||||
{{ subtitle }}
|
||||
</p>
|
||||
<slot></slot>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.page-header {
|
||||
@apply flex flex-col gap-4;
|
||||
}
|
||||
|
||||
.page-header.centered {
|
||||
@apply items-center justify-center text-center;
|
||||
}
|
||||
|
||||
/* Tamanhos */
|
||||
.size-sm .title {
|
||||
@apply sm:text-2xl text-xl sm:max-w-[20rem] max-w-[16rem];
|
||||
}
|
||||
|
||||
.size-sm .subtitle {
|
||||
@apply sm:text-sm text-xs sm:max-w-[18rem] max-w-[14rem];
|
||||
}
|
||||
|
||||
.size-md .title {
|
||||
@apply sm:text-4xl text-2xl sm:max-w-[28rem] max-w-[22rem];
|
||||
}
|
||||
|
||||
.size-md .subtitle {
|
||||
@apply sm:text-base text-sm sm:max-w-[26rem] max-w-[20rem];
|
||||
}
|
||||
|
||||
.size-lg .title {
|
||||
@apply sm:text-5xl text-3xl sm:max-w-[29rem] max-w-[20rem];
|
||||
}
|
||||
|
||||
.size-lg .subtitle {
|
||||
@apply sm:text-base text-sm sm:max-w-[28rem] max-w-[30rem] sm:tracking-normal tracking-wide;
|
||||
}
|
||||
</style>
|
||||
|
||||
50
src/components/ui/StatusBadge.vue
Normal file
@@ -0,0 +1,50 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
|
||||
export type StatusType = "open" | "expired" | "completed" | "pending";
|
||||
|
||||
const props = defineProps<{
|
||||
status: StatusType;
|
||||
customText?: string;
|
||||
}>();
|
||||
|
||||
const statusConfig = computed(() => {
|
||||
const configs: Record<StatusType, { text: string; color: string }> = {
|
||||
open: {
|
||||
text: "Em Aberto",
|
||||
color: "bg-amber-300",
|
||||
},
|
||||
expired: {
|
||||
text: "Expirado",
|
||||
color: "bg-[#94A3B8]",
|
||||
},
|
||||
completed: {
|
||||
text: "Finalizado",
|
||||
color: "bg-emerald-300",
|
||||
},
|
||||
pending: {
|
||||
text: "Pendente",
|
||||
color: "bg-gray-300",
|
||||
},
|
||||
};
|
||||
|
||||
return configs[props.status];
|
||||
});
|
||||
|
||||
const displayText = computed(() => {
|
||||
return props.customText || statusConfig.value.text;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div :class="[statusConfig.color, 'status-badge']">
|
||||
{{ displayText }}
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.status-badge {
|
||||
@apply text-xs sm:text-base font-medium text-gray-900 rounded-lg text-center px-2 py-1;
|
||||
}
|
||||
</style>
|
||||
|
||||
83
src/components/ui/ToasterComponent.vue
Normal file
@@ -0,0 +1,83 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch, onMounted } from "vue";
|
||||
import { useOnboard } from "@web3-onboard/vue";
|
||||
import { Networks } from "@/config/networks";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
|
||||
const { connectedWallet } = useOnboard();
|
||||
const user = useUser();
|
||||
const { network } = user;
|
||||
|
||||
const isWrongNetwork = ref(false);
|
||||
const targetNetworkName = computed(() => network.value.name);
|
||||
|
||||
const checkNetwork = () => {
|
||||
if (connectedWallet.value) {
|
||||
const chainId = connectedWallet.value.chains[0].id;
|
||||
isWrongNetwork.value = Number(chainId) !== network.value.id;
|
||||
} else {
|
||||
isWrongNetwork.value = false; // No wallet connected yet
|
||||
}
|
||||
};
|
||||
|
||||
const switchNetwork = async () => {
|
||||
try {
|
||||
if (connectedWallet.value && connectedWallet.value.provider) {
|
||||
let chainId = network.value.id.toString(16);
|
||||
await connectedWallet.value.provider.request({
|
||||
method: "wallet_switchEthereumChain",
|
||||
params: [
|
||||
{
|
||||
chainId: `0x${chainId}`,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to switch network:", error);
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(checkNetwork);
|
||||
watch(connectedWallet, checkNetwork);
|
||||
watch(network, checkNetwork, { immediate: true });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<transition name="slide-up" appear>
|
||||
<div
|
||||
v-if="isWrongNetwork"
|
||||
class="fixed bottom-0 left-0 right-0 bg-red-500 text-white p-4 flex justify-between items-center z-50"
|
||||
>
|
||||
<div>
|
||||
<span class="font-bold">Wrong network!</span>
|
||||
<span> Please switch to {{ targetNetworkName }}.</span>
|
||||
</div>
|
||||
<button
|
||||
@click="switchNetwork"
|
||||
class="bg-white text-red-500 px-4 py-2 rounded font-bold hover:bg-gray-100 transition-colors"
|
||||
>
|
||||
Switch Network
|
||||
</button>
|
||||
</div>
|
||||
</transition>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.slide-up-enter-active,
|
||||
.slide-up-leave-active {
|
||||
transition: transform 0.3s ease, opacity 0.3s ease;
|
||||
}
|
||||
|
||||
.slide-up-enter-from,
|
||||
.slide-up-leave-to {
|
||||
transform: translateY(100%);
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.slide-up-enter-to,
|
||||
.slide-up-leave-from {
|
||||
transform: translateY(0);
|
||||
opacity: 1;
|
||||
}
|
||||
</style>
|
||||
48
src/components/ui/TokenSelector.vue
Normal file
@@ -0,0 +1,48 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { TokenEnum } from "@/model/NetworkEnum";
|
||||
import { getTokenImage } from "@/utils/imagesPath";
|
||||
import Dropdown, { type DropdownItem } from "./Dropdown.vue";
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
modelValue: TokenEnum;
|
||||
disabled?: boolean;
|
||||
size?: "sm" | "md" | "lg";
|
||||
}>(),
|
||||
{
|
||||
disabled: false,
|
||||
size: "md",
|
||||
}
|
||||
);
|
||||
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [value: TokenEnum];
|
||||
change: [value: TokenEnum];
|
||||
}>();
|
||||
|
||||
const tokenItems = computed((): DropdownItem<TokenEnum>[] => {
|
||||
return Object.values(TokenEnum).map((token) => ({
|
||||
value: token,
|
||||
label: token,
|
||||
icon: getTokenImage(token),
|
||||
}));
|
||||
});
|
||||
|
||||
const handleChange = (value: TokenEnum) => {
|
||||
emit("update:modelValue", value);
|
||||
emit("change", value);
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dropdown
|
||||
:model-value="modelValue"
|
||||
:items="tokenItems"
|
||||
:disabled="disabled"
|
||||
:size="size"
|
||||
:show-icon="true"
|
||||
@update:model-value="handleChange"
|
||||
/>
|
||||
</template>
|
||||
|
||||
152
src/components/ui/WalletConnectButton.vue
Normal file
@@ -0,0 +1,152 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed } from "vue";
|
||||
import { onClickOutside } from "@vueuse/core";
|
||||
import CustomButton from "./CustomButton.vue";
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
walletAddress: string | null;
|
||||
variant?: "primary" | "secondary" | "outline";
|
||||
showMenu?: boolean;
|
||||
}>(),
|
||||
{
|
||||
variant: "primary",
|
||||
showMenu: true,
|
||||
}
|
||||
);
|
||||
|
||||
const emit = defineEmits<{
|
||||
connect: [];
|
||||
disconnect: [];
|
||||
viewTransactions: [];
|
||||
}>();
|
||||
|
||||
const menuOpen = ref(false);
|
||||
const menuRef = ref<HTMLElement | null>(null);
|
||||
|
||||
const isConnected = computed(() => {
|
||||
return !!props.walletAddress;
|
||||
});
|
||||
|
||||
const formattedAddress = computed(() => {
|
||||
if (!props.walletAddress) return "";
|
||||
|
||||
const address = props.walletAddress;
|
||||
const length = address.length;
|
||||
const start = address.substring(0, 5);
|
||||
const end = address.substring(length - 4, length);
|
||||
|
||||
return `${start}...${end}`;
|
||||
});
|
||||
|
||||
const handleConnect = () => {
|
||||
emit("connect");
|
||||
};
|
||||
|
||||
const handleDisconnect = () => {
|
||||
menuOpen.value = false;
|
||||
emit("disconnect");
|
||||
};
|
||||
|
||||
const handleViewTransactions = () => {
|
||||
menuOpen.value = false;
|
||||
emit("viewTransactions");
|
||||
};
|
||||
|
||||
const toggleMenu = () => {
|
||||
if (isConnected.value && props.showMenu) {
|
||||
menuOpen.value = !menuOpen.value;
|
||||
}
|
||||
};
|
||||
|
||||
onClickOutside(menuRef, () => {
|
||||
menuOpen.value = false;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="wallet-connect-container">
|
||||
<CustomButton
|
||||
v-if="!isConnected"
|
||||
text="Conectar carteira"
|
||||
:variant="variant"
|
||||
@button-clicked="handleConnect"
|
||||
/>
|
||||
|
||||
<div v-else ref="menuRef" class="wallet-connected">
|
||||
<button
|
||||
type="button"
|
||||
class="wallet-button"
|
||||
@click="toggleMenu"
|
||||
>
|
||||
<span class="wallet-address">{{ formattedAddress }}</span>
|
||||
<div class="wallet-indicator"></div>
|
||||
</button>
|
||||
|
||||
<transition name="menu-fade">
|
||||
<div v-if="menuOpen && showMenu" class="wallet-menu">
|
||||
<button
|
||||
type="button"
|
||||
class="menu-item"
|
||||
@click="handleViewTransactions"
|
||||
>
|
||||
<span>Ver transações</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="menu-item disconnect"
|
||||
@click="handleDisconnect"
|
||||
>
|
||||
<span>Desconectar</span>
|
||||
</button>
|
||||
</div>
|
||||
</transition>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.wallet-connect-container {
|
||||
@apply relative inline-block;
|
||||
}
|
||||
|
||||
.wallet-connected {
|
||||
@apply relative;
|
||||
}
|
||||
|
||||
.wallet-button {
|
||||
@apply flex items-center gap-3 px-4 py-2 bg-white border-2 border-amber-400 rounded-lg hover:bg-amber-50 transition-colors cursor-pointer;
|
||||
}
|
||||
|
||||
.wallet-address {
|
||||
@apply text-gray-900 font-semibold text-sm;
|
||||
}
|
||||
|
||||
.wallet-indicator {
|
||||
@apply w-2 h-2 bg-emerald-500 rounded-full;
|
||||
}
|
||||
|
||||
.wallet-menu {
|
||||
@apply absolute top-full right-0 mt-2 bg-white rounded-lg border border-gray-300 shadow-lg z-50 min-w-[200px] overflow-hidden;
|
||||
}
|
||||
|
||||
.menu-item {
|
||||
@apply w-full px-4 py-3 text-left text-gray-900 font-medium text-sm hover:bg-gray-100 transition-colors cursor-pointer border-none;
|
||||
}
|
||||
|
||||
.menu-item.disconnect {
|
||||
@apply text-red-500 hover:bg-red-50;
|
||||
}
|
||||
|
||||
/* Animação */
|
||||
.menu-fade-enter-active,
|
||||
.menu-fade-leave-active {
|
||||
@apply transition-all duration-200;
|
||||
}
|
||||
|
||||
.menu-fade-enter-from,
|
||||
.menu-fade-leave-to {
|
||||
@apply opacity-0 -translate-y-2;
|
||||
}
|
||||
</style>
|
||||
|
||||
125
src/composables/useUser.ts
Normal file
@@ -0,0 +1,125 @@
|
||||
import { ref } from "vue";
|
||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||
import type { Participant } from "../utils/bbPay";
|
||||
import type { Address } from "viem"
|
||||
import { DEFAULT_NETWORK, Networks } from "@/config/networks";
|
||||
import { TokenEnum, NetworkConfig } from "@/model/NetworkEnum"
|
||||
|
||||
const walletAddress = ref<Address | null>(null);
|
||||
const balance = ref("");
|
||||
const network = ref(DEFAULT_NETWORK);
|
||||
const selectedToken = ref<TokenEnum>(TokenEnum.BRZ);
|
||||
const loadingLock = ref(false);
|
||||
const sellerView = ref(false);
|
||||
const depositsValidList = ref<ValidDeposit[]>([]);
|
||||
const loadingWalletTransactions = ref(false);
|
||||
const loadingNetworkLiquidity = ref(false);
|
||||
const seller = ref<Participant>({} as Participant);
|
||||
const sellerId = ref("");
|
||||
|
||||
export function useUser() {
|
||||
// Actions become regular functions
|
||||
const setWalletAddress = (address: Address | null) => {
|
||||
walletAddress.value = address;
|
||||
};
|
||||
|
||||
const setBalance = (newBalance: string) => {
|
||||
balance.value = newBalance;
|
||||
};
|
||||
|
||||
const setSelectedToken = (token: TokenEnum) => {
|
||||
selectedToken.value = token;
|
||||
};
|
||||
|
||||
const setNetwork = (chain: NetworkConfig) => {
|
||||
network.value = chain;
|
||||
};
|
||||
|
||||
const setNetworkById = (id: string | number) => {
|
||||
let chainId: number;
|
||||
|
||||
if (typeof id === 'string') {
|
||||
// Parse hex string or number string to number
|
||||
if (id.startsWith('0x')) {
|
||||
chainId = parseInt(id, 16);
|
||||
} else {
|
||||
chainId = parseInt(id, 10);
|
||||
}
|
||||
} else {
|
||||
chainId = id;
|
||||
}
|
||||
|
||||
// Find network by chain ID
|
||||
const chain = Object.values(Networks).find(n => n.id === chainId);
|
||||
if (chain) {
|
||||
network.value = chain;
|
||||
}
|
||||
};
|
||||
|
||||
const setLoadingLock = (isLoading: boolean) => {
|
||||
loadingLock.value = isLoading;
|
||||
};
|
||||
|
||||
const setSellerView = (view: boolean) => {
|
||||
sellerView.value = view;
|
||||
};
|
||||
|
||||
const setDepositsValidList = (deposits: ValidDeposit[]) => {
|
||||
depositsValidList.value = deposits;
|
||||
};
|
||||
|
||||
const setLoadingWalletTransactions = (isLoading: boolean) => {
|
||||
loadingWalletTransactions.value = isLoading;
|
||||
};
|
||||
|
||||
const setLoadingNetworkLiquidity = (isLoading: boolean) => {
|
||||
loadingNetworkLiquidity.value = isLoading;
|
||||
};
|
||||
|
||||
const setSeller = (newSeller: Participant) => {
|
||||
seller.value = newSeller;
|
||||
};
|
||||
|
||||
const setSellerId = (id: string) => {
|
||||
sellerId.value = id;
|
||||
};
|
||||
|
||||
// Getters become computed or regular functions
|
||||
const getValidDepositByWalletAddress = (address: string) => {
|
||||
return depositsValidList.value
|
||||
.filter((deposit) => deposit.seller == address)
|
||||
.sort((a, b) => b.blockNumber - a.blockNumber);
|
||||
};
|
||||
|
||||
return {
|
||||
// State
|
||||
walletAddress,
|
||||
balance,
|
||||
network,
|
||||
selectedToken,
|
||||
loadingLock,
|
||||
sellerView,
|
||||
depositsValidList,
|
||||
loadingWalletTransactions,
|
||||
loadingNetworkLiquidity,
|
||||
seller,
|
||||
sellerId,
|
||||
|
||||
// Actions
|
||||
setWalletAddress,
|
||||
setBalance,
|
||||
setSelectedToken,
|
||||
setNetwork,
|
||||
setNetworkById,
|
||||
setLoadingLock,
|
||||
setSellerView,
|
||||
setDepositsValidList,
|
||||
setLoadingWalletTransactions,
|
||||
setLoadingNetworkLiquidity,
|
||||
setSeller,
|
||||
setSellerId,
|
||||
|
||||
// Getters
|
||||
getValidDepositByWalletAddress,
|
||||
};
|
||||
}
|
||||
24
src/config/networks.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { sepolia, rootstockTestnet } from "viem/chains";
|
||||
import { NetworkConfig } from "@/model/NetworkEnum"
|
||||
// TODO: import addresses from p2pix-smart-contracts deployments
|
||||
|
||||
export const Networks: {[key:string]: NetworkConfig} = {
|
||||
sepolia: { ...sepolia,
|
||||
rpcUrls: { default: { http: [import.meta.env.VITE_SEPOLIA_API_URL]}},
|
||||
contracts: { ...sepolia.contracts,
|
||||
p2pix: {address:"0xb7cD135F5eFD9760981e02E2a898790b688939fe"} },
|
||||
tokens: {
|
||||
BRZ: {address:"0x3eBE67A2C7bdB2081CBd34ba3281E90377462289"} },
|
||||
subgraphUrls: [import.meta.env.VITE_SEPOLIA_SUBGRAPH_URL]
|
||||
},
|
||||
rootstockTestnet: { ...rootstockTestnet,
|
||||
rpcUrls: { default: { http: [import.meta.env.VITE_RSK_API_URL]}},
|
||||
contracts: { ...rootstockTestnet.contracts,
|
||||
p2pix: {address:"0x57Dcba05980761169508886eEdc6f5E7EC0411Dc"} },
|
||||
tokens: {
|
||||
BRZ: {address:"0xfE841c74250e57640390f46d914C88d22C51e82e"} },
|
||||
subgraphUrls: [import.meta.env.VITE_RSK_SUBGRAPH_URL]
|
||||
},
|
||||
};
|
||||
|
||||
export const DEFAULT_NETWORK = Networks.sepolia;
|
||||
@@ -1,7 +1,6 @@
|
||||
import { createApp } from "vue";
|
||||
import App from "./App.vue";
|
||||
import router from "./router";
|
||||
import { createPinia } from "pinia";
|
||||
|
||||
import "./assets/main.css";
|
||||
import "./assets/transitions.css";
|
||||
@@ -9,6 +8,5 @@ import "./assets/transitions.css";
|
||||
const app = createApp(App);
|
||||
|
||||
app.use(router);
|
||||
app.use(createPinia());
|
||||
|
||||
app.mount("#app");
|
||||
|
||||
5
src/model/Bank.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export interface Bank {
|
||||
COMPE: string;
|
||||
ISPB: string;
|
||||
longName: string;
|
||||
}
|
||||
8
src/model/LockStatus.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import type { Address } from "viem";
|
||||
|
||||
export enum LockStatus { // from DataTypes.sol
|
||||
Inexistent = 0, // Uninitialized Lock
|
||||
Active = 1, // Valid Lock
|
||||
Expired = 2, // Expired Lock
|
||||
Released = 3 // Already released Lock
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
export enum NetworkEnum {
|
||||
sepolia = 11155111,
|
||||
rootstock = 31,
|
||||
}
|
||||
import type { Chain, ChainContract } from "viem";
|
||||
|
||||
export enum TokenEnum {
|
||||
BRZ = "BRZ",
|
||||
BRZ = 'BRZ',
|
||||
// BRX = 'BRX'
|
||||
}
|
||||
export type NetworkConfig = Chain & {
|
||||
tokens: Record<TokenEnum, ChainContract>,
|
||||
subgraphUrls: string[]
|
||||
};
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import { NetworkEnum } from "@/model/NetworkEnum";
|
||||
|
||||
export const Networks = {
|
||||
[NetworkEnum.sepolia]: {
|
||||
chainId: "0xAA36A7",
|
||||
chainName: "Sepolia Testnet",
|
||||
},
|
||||
[NetworkEnum.rootstock]: {
|
||||
chainId: "0x1F",
|
||||
chainName: "Rootstock Testnet",
|
||||
rpcUrls: ["https://public-node.testnet.rsk.co/"],
|
||||
iconUrls: [
|
||||
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACQAAAAoCAYAAACWwljjAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAPOSURBVHgBxVhNUhpBFH6vGdxp4S4LoSYnEE8gnEA4AbpMJUQ4gXgCRJK1egLxBOIJJCdwJElVllMu49Cd1z04zD/dY1H5qihmut/M93VPv59uhHdAXFaPAaEDgA2/BaeA4hq/zG+gIBAKQoyr9yshid4Jdn+2oQAYFIC4rA2zxUhgS3yrDqEAjGdIDD/YYG09aRl7L7vYd10wgPkMlcoNfdvtFhjCXJBAeyO2S5gLQuFo25bEIxjCCt8oN2Z46I+Mu4A4SbjwojQBi1+BDl5LP+JNYlhtQRmPsjjQN1ILldwY7JTXOuD9bWL/jxO8dFy7oL9TyMcIu/PeSghxlLduQUA9jwPXiAk98HLw5jFiaFfAEjRLImPR0qi7z+2VmArZ7zzqcDAS01ljCKqf7QSjxb7jKkIhTohu6rOCq64RjsNiFEo7x7ocSNMvlddhPWb0CQ6gAAw4HKZpKGFDcWhzSEG6kbQCm4dLbi9m+XlpBTHea2D31zTSNtxrAGMNdcP5FPuxfhlKdCHgASUJxcd7zUcobkAPXvkzWGyf7uVCt2M2DtkMljaHSxu92WWLAz8OjWsD+juD/4tzcpqBSh3yQrmwoNFFMZNuDB7bJRsp/hzMMQqeT+NQ96KtNEBK+SG+23XgHgUyy8FPjpPozy3M4sZwh1/nLRMOK26Mn50Z5IHjA6XkBugJSn1XHkeBbK8dJsxsl0jMEOUpm0o9+gkX+7+TI0E+0x6Hsk0ijyNYQ/4OAqWn2aF+5cLxEoRq6idqtyEPtFhp/XyMNI2p9ADFUc/iYL5h7YzEXEEyptj04mvVHxkGP4F8MS4sWDsqRr4DbyGZRiIcqCKtpRMYeTMcpVVAFewqMVPSjUkMVQTBp6BPVKeiTqN65E0qP1AvIArWC98qcQsms39oDeBEtoXFKFgLbQ76ZKiXiRH2E01UF9Go+kGDh32/LWHZAD2OQ7mGdLO4ndrqWaHZyNyD6XJUWEq6yIQqReOweCe49ivD2DNUIutjJgXpHwyUtyPbY/IMWehfBA0IZxQSQoW9rKXL+ltq0oKqYC+RB6yLKys4xEw/Idde5R02cTGOcgh1LSNnid+nihIqcN0tr48MhL89L2uoG+Dqv5Px/IwqAhkqnEi296M1OyLPqVCgdKhcuKNjlUnQL4X78cRk1E1JlMkBME1sFE0gRrRJZGs3iT44bRZP5z0wQJHzIZMMbpztN1t+FDhsMBe0YNfatimHDetgLGiZGkYapqPwYt6YIAWPDYI9fSrETfjkwwSFT2EVrV/USY+r+/GGNp2I7zoW/gdR9aOdZ/lPGgAAAABJRU5ErkJggg==",
|
||||
],
|
||||
nativeCurrency: {
|
||||
name: "tRBTC",
|
||||
symbol: "tRBTC",
|
||||
decimals: 18,
|
||||
},
|
||||
blockExplorerUrls: ["https://explorer.testnet.rootstock.io/"],
|
||||
},
|
||||
};
|
||||
@@ -1,11 +1,11 @@
|
||||
export type Pix = {
|
||||
pixKey: string;
|
||||
merchantCity?: string;
|
||||
merchantName?: string;
|
||||
value?: number;
|
||||
transactionId?: string;
|
||||
message?: string;
|
||||
cep?: string;
|
||||
currency?: number;
|
||||
countryCode?: string;
|
||||
pixKey: string;
|
||||
merchantCity?: string;
|
||||
merchantName?: string;
|
||||
value?: number;
|
||||
transactionId?: string;
|
||||
message?: string;
|
||||
cep?: string;
|
||||
currency?: number;
|
||||
countryCode?: string;
|
||||
};
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { Pix } from "./Pix";
|
||||
import { Address } from "viem";
|
||||
|
||||
export type UnreleasedLock = {
|
||||
lockID: string;
|
||||
pix: Pix;
|
||||
lockID: bigint;
|
||||
sellerAddress: Address;
|
||||
tokenAddress: Address;
|
||||
amount: number;
|
||||
};
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { NetworkEnum } from "./NetworkEnum";
|
||||
import type { Address } from "viem";
|
||||
import type { NetworkConfig } from "@/model/NetworkEnum";
|
||||
|
||||
export type ValidDeposit = {
|
||||
token: string;
|
||||
token: Address;
|
||||
blockNumber: number;
|
||||
remaining: number;
|
||||
seller: string;
|
||||
pixKey: string;
|
||||
network: NetworkEnum;
|
||||
seller: Address;
|
||||
participantID: string;
|
||||
network: NetworkConfig;
|
||||
open?: boolean;
|
||||
};
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import type { LockStatus } from "@/model/LockStatus"
|
||||
import type { Address } from "viem"
|
||||
|
||||
export type WalletTransaction = {
|
||||
token: string;
|
||||
token?: Address;
|
||||
blockNumber: number;
|
||||
amount: number;
|
||||
seller: string;
|
||||
buyer: string;
|
||||
event: string;
|
||||
lockStatus: number;
|
||||
lockStatus?: LockStatus;
|
||||
transactionHash: string;
|
||||
transactionID?: string;
|
||||
};
|
||||
|
||||
@@ -1,121 +0,0 @@
|
||||
import type { Event } from "ethers";
|
||||
import { vi } from "vitest";
|
||||
|
||||
export const MockEvents: Event[] = [
|
||||
{
|
||||
blockNumber: 1,
|
||||
blockHash: "0x8",
|
||||
transactionIndex: 1,
|
||||
removed: false,
|
||||
address: "0x0",
|
||||
data: "0x0",
|
||||
topics: ["0x0", "0x0"],
|
||||
transactionHash: "0x0",
|
||||
logIndex: 1,
|
||||
event: "DepositAdded",
|
||||
eventSignature: "DepositAdded(address,uint256,address,uint256)",
|
||||
args: [
|
||||
"0x0",
|
||||
{
|
||||
type: "BigNumber",
|
||||
hex: "0x00",
|
||||
},
|
||||
"0x0",
|
||||
{
|
||||
type: "BigNumber",
|
||||
hex: "0x6c6b935b8bbd400000",
|
||||
},
|
||||
],
|
||||
getBlock: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
getTransaction: vi.fn(),
|
||||
getTransactionReceipt: vi.fn(),
|
||||
},
|
||||
{
|
||||
blockNumber: 2,
|
||||
blockHash: "0x8",
|
||||
transactionIndex: 2,
|
||||
removed: false,
|
||||
address: "0x0",
|
||||
data: "0x0",
|
||||
topics: ["0x0", "0x0"],
|
||||
transactionHash: "0x0",
|
||||
logIndex: 2,
|
||||
event: "LockAdded",
|
||||
eventSignature: "LockAdded(address,uint256,address,uint256)",
|
||||
args: [
|
||||
"0x0",
|
||||
{
|
||||
type: "BigNumber",
|
||||
hex: "0x00",
|
||||
},
|
||||
"0x0",
|
||||
{
|
||||
type: "BigNumber",
|
||||
hex: "0x6c6b935b8bbd400000",
|
||||
},
|
||||
],
|
||||
getBlock: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
getTransaction: vi.fn(),
|
||||
getTransactionReceipt: vi.fn(),
|
||||
},
|
||||
{
|
||||
blockNumber: 3,
|
||||
blockHash: "0x8",
|
||||
transactionIndex: 3,
|
||||
removed: false,
|
||||
address: "0x0",
|
||||
data: "0x0",
|
||||
topics: ["0x0", "0x0"],
|
||||
transactionHash: "0x0",
|
||||
logIndex: 3,
|
||||
event: "LockReleased",
|
||||
eventSignature: "LockReleased(address,uint256,address,uint256)",
|
||||
args: [
|
||||
"0x0",
|
||||
{
|
||||
type: "BigNumber",
|
||||
hex: "0x00",
|
||||
},
|
||||
"0x0",
|
||||
{
|
||||
type: "BigNumber",
|
||||
hex: "0x6c6b935b8bbd400000",
|
||||
},
|
||||
],
|
||||
getBlock: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
getTransaction: vi.fn(),
|
||||
getTransactionReceipt: vi.fn(),
|
||||
},
|
||||
{
|
||||
blockNumber: 4,
|
||||
blockHash: "0x8",
|
||||
transactionIndex: 4,
|
||||
removed: false,
|
||||
address: "0x0",
|
||||
data: "0x0",
|
||||
topics: ["0x0", "0x0"],
|
||||
transactionHash: "0x0",
|
||||
logIndex: 4,
|
||||
event: "LockReleased",
|
||||
eventSignature: "LockReleased(address,uint256,address,uint256)",
|
||||
args: [
|
||||
"0x0",
|
||||
{
|
||||
type: "BigNumber",
|
||||
hex: "0x00",
|
||||
},
|
||||
"0x0",
|
||||
{
|
||||
type: "BigNumber",
|
||||
hex: "0x6c6b935b8bbd400000",
|
||||
},
|
||||
],
|
||||
getBlock: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
getTransaction: vi.fn(),
|
||||
getTransactionReceipt: vi.fn(),
|
||||
},
|
||||
];
|
||||
@@ -1,39 +0,0 @@
|
||||
import type { ValidDeposit } from "../ValidDeposit";
|
||||
|
||||
export const MockValidDeposits: ValidDeposit[] = [
|
||||
{
|
||||
blockNumber: 1,
|
||||
token: "1",
|
||||
remaining: 70,
|
||||
seller: "mockedSellerAddress",
|
||||
pixKey: "123456789",
|
||||
},
|
||||
{
|
||||
blockNumber: 2,
|
||||
token: "2",
|
||||
remaining: 200,
|
||||
seller: "mockedSellerAddress",
|
||||
pixKey: "123456789",
|
||||
},
|
||||
{
|
||||
blockNumber: 3,
|
||||
token: "3",
|
||||
remaining: 1250,
|
||||
seller: "mockedSellerAddress",
|
||||
pixKey: "123456789",
|
||||
},
|
||||
{
|
||||
blockNumber: 4,
|
||||
token: "4",
|
||||
remaining: 4000,
|
||||
seller: "mockedSellerAddress",
|
||||
pixKey: "123456789",
|
||||
},
|
||||
{
|
||||
blockNumber: 5,
|
||||
token: "5",
|
||||
remaining: 2000,
|
||||
seller: "mockedSellerAddress",
|
||||
pixKey: "123456789",
|
||||
},
|
||||
];
|
||||
@@ -1,54 +0,0 @@
|
||||
import type { WalletTransaction } from "../WalletTransaction";
|
||||
|
||||
export const MockWalletTransactions: WalletTransaction[] = [
|
||||
{
|
||||
blockNumber: 1,
|
||||
token: "1",
|
||||
amount: 70,
|
||||
seller: "mockedSellerAddress",
|
||||
buyer: "mockedBuyerAddress",
|
||||
event: "Deposit",
|
||||
lockStatus: 0,
|
||||
transactionHash: "1",
|
||||
},
|
||||
{
|
||||
blockNumber: 2,
|
||||
token: "2",
|
||||
amount: 200,
|
||||
seller: "mockedSellerAddress",
|
||||
buyer: "mockedBuyerAddress",
|
||||
event: "Lock",
|
||||
lockStatus: 1,
|
||||
transactionHash: "2",
|
||||
},
|
||||
{
|
||||
blockNumber: 3,
|
||||
token: "3",
|
||||
amount: 1250,
|
||||
seller: "mockedSellerAddress",
|
||||
buyer: "mockedBuyerAddress",
|
||||
event: "Release",
|
||||
lockStatus: 2,
|
||||
transactionHash: "3",
|
||||
},
|
||||
{
|
||||
blockNumber: 4,
|
||||
token: "4",
|
||||
amount: 4000,
|
||||
seller: "mockedSellerAddress",
|
||||
buyer: "mockedBuyerAddress",
|
||||
event: "Deposit",
|
||||
lockStatus: 0,
|
||||
transactionHash: "4",
|
||||
},
|
||||
{
|
||||
blockNumber: 5,
|
||||
token: "5",
|
||||
amount: 2000,
|
||||
seller: "mockedSellerAddress",
|
||||
buyer: "mockedBuyerAddress",
|
||||
event: "Deposit",
|
||||
lockStatus: 3,
|
||||
transactionHash: "5",
|
||||
},
|
||||
];
|
||||
@@ -1,14 +0,0 @@
|
||||
/* eslint-disable @typescript-eslint/no-non-null-assertion */
|
||||
import axios from "axios";
|
||||
|
||||
const defaultConfig = {
|
||||
"Content-Type": "application/json",
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
};
|
||||
|
||||
const api = axios.create({
|
||||
...defaultConfig,
|
||||
baseURL: import.meta.env.VITE_API_URL,
|
||||
});
|
||||
|
||||
export default api;
|
||||
@@ -1,56 +0,0 @@
|
||||
import { NetworkEnum, TokenEnum } from "../model/NetworkEnum";
|
||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||
import { defineStore } from "pinia";
|
||||
|
||||
export const useEtherStore = defineStore("ether", {
|
||||
state: () => ({
|
||||
walletAddress: "",
|
||||
balance: "",
|
||||
networkName: NetworkEnum.sepolia,
|
||||
selectedToken: TokenEnum.BRZ,
|
||||
loadingLock: false,
|
||||
sellerView: false,
|
||||
depositsValidList: [] as ValidDeposit[],
|
||||
loadingWalletTransactions: false,
|
||||
loadingNetworkLiquidity: false,
|
||||
}),
|
||||
actions: {
|
||||
setWalletAddress(walletAddress: string) {
|
||||
this.walletAddress = walletAddress;
|
||||
},
|
||||
setBalance(balance: string) {
|
||||
this.balance = balance;
|
||||
},
|
||||
setSelectedToken(token: TokenEnum) {
|
||||
this.selectedToken = token;
|
||||
},
|
||||
setNetworkId(networkName: NetworkEnum) {
|
||||
this.networkName = Number(networkName);
|
||||
},
|
||||
setLoadingLock(isLoadingLock: boolean) {
|
||||
this.loadingLock = isLoadingLock;
|
||||
},
|
||||
setSellerView(sellerView: boolean) {
|
||||
this.sellerView = sellerView;
|
||||
},
|
||||
setDepositsValidList(depositsValidList: ValidDeposit[]) {
|
||||
this.depositsValidList = depositsValidList;
|
||||
},
|
||||
setLoadingWalletTransactions(isLoadingWalletTransactions: boolean) {
|
||||
this.loadingWalletTransactions = isLoadingWalletTransactions;
|
||||
},
|
||||
setLoadingNetworkLiquidity(isLoadingNetworkLiquidity: boolean) {
|
||||
this.loadingNetworkLiquidity = isLoadingNetworkLiquidity;
|
||||
},
|
||||
},
|
||||
getters: {
|
||||
getValidDepositByWalletAddress: (state) => {
|
||||
return (walletAddress: string) =>
|
||||
state.depositsValidList
|
||||
.filter((deposit) => deposit.seller == walletAddress)
|
||||
.sort((a, b) => {
|
||||
return b.blockNumber - a.blockNumber;
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -1,76 +0,0 @@
|
||||
import qrcode from "qrcode";
|
||||
import type { QRCodeToDataURLOptions } from "qrcode";
|
||||
import { crc16ccitt } from "crc";
|
||||
import type { Pix } from "@/model/Pix";
|
||||
|
||||
const pix = ({
|
||||
pixKey,
|
||||
merchantCity = "city",
|
||||
merchantName = "name",
|
||||
value,
|
||||
message,
|
||||
cep,
|
||||
transactionId = "***",
|
||||
currency = 986,
|
||||
countryCode = "BR",
|
||||
}: Pix) => {
|
||||
const payloadKeyString = generatePixKey(pixKey, message);
|
||||
|
||||
const payload: string[] = [
|
||||
formatEMV("00", "01"), //Payload Format Indicator
|
||||
formatEMV("26", payloadKeyString), // Merchant Account Information
|
||||
formatEMV("52", "0000"), //Merchant Category Code
|
||||
formatEMV("53", String(currency)), // Transaction Currency
|
||||
];
|
||||
|
||||
if (String(value) === "0") {
|
||||
value = undefined;
|
||||
}
|
||||
if (value) {
|
||||
payload.push(formatEMV("54", value.toFixed(2)));
|
||||
}
|
||||
|
||||
payload.push(formatEMV("58", countryCode.toUpperCase())); // Country Code
|
||||
payload.push(formatEMV("59", merchantName)); // Merchant Name
|
||||
payload.push(formatEMV("60", merchantCity)); // Merchant City
|
||||
|
||||
if (cep) {
|
||||
payload.push(formatEMV("61", cep)); // Postal Code
|
||||
}
|
||||
|
||||
payload.push(formatEMV("62", formatEMV("05", transactionId))); // Additional Data Field Template
|
||||
|
||||
payload.push("6304");
|
||||
|
||||
const stringPayload = payload.join("");
|
||||
const crcResult = crc16ccitt(stringPayload)
|
||||
.toString(16)
|
||||
.toUpperCase()
|
||||
.padStart(4, "0");
|
||||
|
||||
const payloadPIX = `${stringPayload}${crcResult}`;
|
||||
|
||||
return {
|
||||
payload: (): string => payloadPIX,
|
||||
base64QrCode: (options?: QRCodeToDataURLOptions): Promise<string> =>
|
||||
qrcode.toDataURL(payloadPIX, options),
|
||||
};
|
||||
};
|
||||
|
||||
const generatePixKey = (pixKey: string, message?: string): string => {
|
||||
const payload: string[] = [
|
||||
formatEMV("00", "BR.GOV.BCB.PIX"),
|
||||
formatEMV("01", pixKey),
|
||||
];
|
||||
if (message) {
|
||||
payload.push(formatEMV("02", message));
|
||||
}
|
||||
return payload.join("");
|
||||
};
|
||||
|
||||
const formatEMV = (id: string, param: string): string => {
|
||||
const len = param?.length?.toString().padStart(2, "0");
|
||||
return `${id}${len}${param}`;
|
||||
};
|
||||
|
||||
export { pix };
|
||||
@@ -1,24 +0,0 @@
|
||||
import { it, expect, vi, type Mock } from "vitest";
|
||||
import { debounce } from "../debounce";
|
||||
|
||||
vi.useFakeTimers();
|
||||
|
||||
describe("debounce function test", () => {
|
||||
let mockFunction: Mock;
|
||||
let debounceFunction: Function;
|
||||
|
||||
beforeEach(() => {
|
||||
mockFunction = vi.fn();
|
||||
debounceFunction = debounce(mockFunction, 1000);
|
||||
});
|
||||
|
||||
it("debounce function will be executed just once", () => {
|
||||
for (let i = 0; i < 100; i++) {
|
||||
debounceFunction();
|
||||
}
|
||||
|
||||
vi.runAllTimers();
|
||||
|
||||
expect(mockFunction).toBeCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -1,12 +0,0 @@
|
||||
import { it, expect } from "vitest";
|
||||
import { decimalCount } from "../decimalCount";
|
||||
|
||||
describe("decimalCount function test", () => {
|
||||
it("decimalCount should return length 1 of decimal", () => {
|
||||
expect(decimalCount("4.1")).toEqual(1);
|
||||
});
|
||||
|
||||
it("decimalCount should return length 0 because no decimal found", () => {
|
||||
expect(decimalCount("5")).toEqual(0);
|
||||
});
|
||||
});
|
||||
@@ -1,25 +0,0 @@
|
||||
import { MockValidDeposits } from "@/model/mock/ValidDepositMock";
|
||||
import { it, expect, vi } from "vitest";
|
||||
import { verifyNetworkLiquidity } from "../networkLiquidity";
|
||||
|
||||
vi.useFakeTimers();
|
||||
|
||||
describe("verifyNetworkLiquidity function test", () => {
|
||||
it("verifyNetworkLiquidity should return an element from valid deposit list when searching for other deposits", () => {
|
||||
const liquidityElement = verifyNetworkLiquidity(
|
||||
MockValidDeposits[0].remaining,
|
||||
"strangeWalletAddress",
|
||||
MockValidDeposits
|
||||
);
|
||||
expect(liquidityElement).toEqual(MockValidDeposits[0]);
|
||||
});
|
||||
|
||||
it("verifyNetworkLiquidity should return undefined when all deposits on valid deposit list match connected wallet addres", () => {
|
||||
const liquidityElement = verifyNetworkLiquidity(
|
||||
MockValidDeposits[0].remaining,
|
||||
MockValidDeposits[0].seller,
|
||||
[MockValidDeposits[0]]
|
||||
);
|
||||
expect(liquidityElement).toEqual(undefined);
|
||||
});
|
||||
});
|
||||
75
src/utils/bbPay.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
export interface Participant {
|
||||
offer: string;
|
||||
chainID: number;
|
||||
identification: string;
|
||||
bankIspb?: string;
|
||||
accountType: string;
|
||||
account: string;
|
||||
branch: string;
|
||||
savingsVariation?: string;
|
||||
}
|
||||
|
||||
export interface ParticipantWithID extends Participant {
|
||||
id: string;
|
||||
}
|
||||
|
||||
export interface Offer {
|
||||
amount: number;
|
||||
sellerId: string;
|
||||
}
|
||||
|
||||
// Specs for BB Pay Sandbox
|
||||
// https://apoio.developers.bb.com.br/sandbox/spec/665797498bb48200130fc32c
|
||||
|
||||
export const createParticipant = async (participant: Participant) => {
|
||||
const response = await fetch(`${import.meta.env.VITE_APP_API_URL}/register`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
chainID: participant.chainID,
|
||||
tipoDocumento: 1,
|
||||
numeroDocumento: participant.identification,
|
||||
numeroConta: participant.account,
|
||||
numeroAgencia: participant.branch,
|
||||
tipoConta: participant.accountType,
|
||||
codigoIspb: participant.bankIspb,
|
||||
}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Error creating participant: ${response.statusText}`);
|
||||
}
|
||||
const data = await response.json();
|
||||
if (data.errors || data.erros) {
|
||||
throw new Error(`Error creating participant: ${JSON.stringify(data)}`);
|
||||
}
|
||||
return { ...participant, id: data.numeroParticipante } as ParticipantWithID;
|
||||
};
|
||||
|
||||
export const createSolicitation = async (offer: Offer) => {
|
||||
const response = await fetch(`${import.meta.env.VITE_APP_API_URL}/request`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
amount: offer.amount,
|
||||
pixTarget: offer.sellerId.split("-").pop(),
|
||||
}),
|
||||
});
|
||||
return response.json();
|
||||
};
|
||||
|
||||
export const getSolicitation = async (id: bigint): Promise<{pixTimestamp: `0x${string}`, signature: `0x${string}`}> => {
|
||||
const response = await fetch(
|
||||
`${import.meta.env.VITE_APP_API_URL}/release/${id}`
|
||||
);
|
||||
|
||||
const obj = await response.json();
|
||||
|
||||
return {
|
||||
pixTimestamp: obj.pixTimestamp,
|
||||
signature: obj.signature,
|
||||
};
|
||||
};
|
||||
2142
src/utils/files/isbpList.json
Normal file
@@ -1,21 +1,11 @@
|
||||
import type { TokenEnum } from "@/model/NetworkEnum";
|
||||
|
||||
export const imagesPath = import.meta.glob<string>("@/assets/*.{png,svg}", {
|
||||
eager: true,
|
||||
query: "?url",
|
||||
import: "default",
|
||||
});
|
||||
import { Networks } from "@/config/networks";
|
||||
|
||||
export const getNetworkImage = (networkName: string): string => {
|
||||
const path = Object.keys(imagesPath).find((key) =>
|
||||
key.endsWith(`${networkName.toLowerCase()}.svg`)
|
||||
);
|
||||
return path ? imagesPath[path] : "";
|
||||
const normalizedName = networkName.toLowerCase().replace(/[^a-z0-9]/g, '-');
|
||||
return new URL(`../assets/networks/${normalizedName}.svg`, import.meta.url).href;
|
||||
};
|
||||
|
||||
export const getTokenImage = (tokenName: TokenEnum): string => {
|
||||
const path = Object.keys(imagesPath).find((key) =>
|
||||
key.endsWith(`${tokenName.toLowerCase()}.svg`)
|
||||
);
|
||||
return path ? imagesPath[path] : "";
|
||||
return new URL(`../assets/tokens/${tokenName.toLowerCase()}.svg`, import.meta.url).href;
|
||||
};
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||
import type { Address } from "viem";
|
||||
|
||||
const verifyNetworkLiquidity = (
|
||||
tokenValue: number,
|
||||
walletAddress: string,
|
||||
walletAddress: Address,
|
||||
validDepositList: ValidDeposit[]
|
||||
): ValidDeposit[] => {
|
||||
const filteredDepositList = validDepositList
|
||||
|
||||
@@ -24,7 +24,6 @@ const openItem = (index: number) => {
|
||||
faq.value[selectedSection.value].items[index].content = marked(
|
||||
faq.value[selectedSection.value].items[index].content
|
||||
);
|
||||
console.log(marked(faq.value[selectedSection.value].items[index].content));
|
||||
};
|
||||
</script>
|
||||
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
<script setup lang="ts">
|
||||
import SearchComponent from "@/components/SearchComponent.vue";
|
||||
import LoadingComponent from "@/components/LoadingComponent/LoadingComponent.vue";
|
||||
import BuyConfirmedComponent from "@/components/BuyConfirmedComponent/BuyConfirmedComponent.vue";
|
||||
import SearchComponent from "@/components/BuyerSteps/BuyerSearchComponent.vue";
|
||||
import LoadingComponent from "@/components/ui/LoadingComponent.vue";
|
||||
import BuyConfirmedComponent from "@/components/BuyerSteps/BuyConfirmedComponent.vue";
|
||||
import { ref, onMounted, watch } from "vue";
|
||||
import { useEtherStore } from "@/store/ether";
|
||||
import QrCodeComponent from "@/components/QrCodeComponent.vue";
|
||||
import { storeToRefs } from "pinia";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
import QrCodeComponent from "@/components/BuyerSteps/QrCodeComponent.vue";
|
||||
import { addLock, releaseLock } from "@/blockchain/buyerMethods";
|
||||
import { updateWalletStatus, checkUnreleasedLock } from "@/blockchain/wallet";
|
||||
import { getNetworksLiquidity } from "@/blockchain/events";
|
||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||
import { getUnreleasedLockById } from "@/blockchain/events";
|
||||
import CustomAlert from "@/components/CustomAlert/CustomAlert.vue";
|
||||
import CustomAlert from "@/components/ui/CustomAlert.vue";
|
||||
import { getSolicitation } from "@/utils/bbPay";
|
||||
import type { Address } from "viem";
|
||||
|
||||
enum Step {
|
||||
Search,
|
||||
@@ -19,13 +20,14 @@ enum Step {
|
||||
List,
|
||||
}
|
||||
|
||||
const etherStore = useEtherStore();
|
||||
etherStore.setSellerView(false);
|
||||
const user = useUser();
|
||||
user.setSellerView(false);
|
||||
|
||||
// States
|
||||
const { loadingLock, walletAddress, networkName } = storeToRefs(etherStore);
|
||||
const { loadingLock, walletAddress, network } = user;
|
||||
const flowStep = ref<Step>(Step.Search);
|
||||
const pixTarget = ref<string>();
|
||||
const participantID = ref<string>();
|
||||
const sellerAddress = ref<Address>();
|
||||
const tokenAmount = ref<number>();
|
||||
const lockID = ref<string>("");
|
||||
const loadingRelease = ref<boolean>(false);
|
||||
@@ -37,54 +39,48 @@ const confirmBuyClick = async (
|
||||
selectedDeposit: ValidDeposit,
|
||||
tokenValue: number
|
||||
) => {
|
||||
// finish buy screen
|
||||
pixTarget.value = selectedDeposit.pixKey;
|
||||
participantID.value = selectedDeposit.participantID;
|
||||
tokenAmount.value = tokenValue;
|
||||
|
||||
// Makes lock with deposit ID and the Amount
|
||||
if (selectedDeposit) {
|
||||
flowStep.value = Step.Buy;
|
||||
etherStore.setLoadingLock(true);
|
||||
user.setLoadingLock(true);
|
||||
|
||||
await addLock(selectedDeposit.seller, selectedDeposit.token, tokenValue)
|
||||
.then((_lockID) => {
|
||||
lockID.value = _lockID;
|
||||
lockID.value = String(_lockID);
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log(err);
|
||||
flowStep.value = Step.Search;
|
||||
});
|
||||
|
||||
etherStore.setLoadingLock(false);
|
||||
user.setLoadingLock(false);
|
||||
}
|
||||
};
|
||||
|
||||
const releaseTransaction = async (e2eId: string) => {
|
||||
const releaseTransaction = async (params: {
|
||||
pixTimestamp: `0x${string}`&{lenght:34},
|
||||
signature: `0x${string}`,
|
||||
}) => {
|
||||
flowStep.value = Step.List;
|
||||
showBuyAlert.value = true;
|
||||
loadingRelease.value = true;
|
||||
|
||||
if (lockID.value && tokenAmount.value && pixTarget.value) {
|
||||
const release = await releaseLock(
|
||||
pixTarget.value,
|
||||
tokenAmount.value,
|
||||
e2eId,
|
||||
lockID.value
|
||||
);
|
||||
await release.wait();
|
||||
const release = await releaseLock(BigInt(lockID.value), params.pixTimestamp, params.signature);
|
||||
|
||||
await updateWalletStatus();
|
||||
loadingRelease.value = false;
|
||||
}
|
||||
await updateWalletStatus();
|
||||
loadingRelease.value = false;
|
||||
};
|
||||
|
||||
const checkForUnreleasedLocks = async (): Promise<void> => {
|
||||
console.log("Checking for unreleased locks");
|
||||
const walletLocks = await checkUnreleasedLock(walletAddress.value);
|
||||
if (walletLocks) {
|
||||
lockID.value = walletLocks.lockID;
|
||||
tokenAmount.value = walletLocks.pix.value;
|
||||
pixTarget.value = walletLocks.pix.pixKey;
|
||||
if (!walletAddress.value)
|
||||
throw new Error("Wallet not connected");
|
||||
const lock = await checkUnreleasedLock(walletAddress.value);
|
||||
if (lock) {
|
||||
lockID.value = String(lock.lockID);
|
||||
tokenAmount.value = lock.amount;
|
||||
sellerAddress.value = lock.sellerAddress;
|
||||
showModal.value = true;
|
||||
} else {
|
||||
flowStep.value = Step.Search;
|
||||
@@ -93,11 +89,11 @@ const checkForUnreleasedLocks = async (): Promise<void> => {
|
||||
};
|
||||
|
||||
if (paramLockID) {
|
||||
const lockToRedirect = await getUnreleasedLockById(paramLockID as string);
|
||||
const lockToRedirect = await getUnreleasedLockById(paramLockID);
|
||||
if (lockToRedirect) {
|
||||
lockID.value = lockToRedirect.lockID;
|
||||
tokenAmount.value = lockToRedirect.pix.value;
|
||||
pixTarget.value = lockToRedirect.pix.pixKey;
|
||||
lockID.value = String(lockToRedirect.lockID);
|
||||
tokenAmount.value = lockToRedirect.amount;
|
||||
sellerAddress.value = lockToRedirect.sellerAddress;
|
||||
flowStep.value = Step.Buy;
|
||||
} else {
|
||||
flowStep.value = Step.Search;
|
||||
@@ -107,7 +103,7 @@ if (paramLockID) {
|
||||
await checkForUnreleasedLocks();
|
||||
});
|
||||
|
||||
watch(networkName, async () => {
|
||||
watch(network, async () => {
|
||||
if (walletAddress.value) await checkForUnreleasedLocks();
|
||||
});
|
||||
}
|
||||
@@ -140,8 +136,7 @@ onMounted(async () => {
|
||||
/>
|
||||
<div v-if="flowStep == Step.Buy">
|
||||
<QrCodeComponent
|
||||
:pixTarget="String(pixTarget)"
|
||||
:tokenValue="tokenAmount"
|
||||
:lockID="lockID"
|
||||
@pix-validated="releaseTransaction"
|
||||
v-if="!loadingLock"
|
||||
/>
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
import { useEtherStore } from "@/store/ether";
|
||||
import { storeToRefs } from "pinia";
|
||||
import { ref, onMounted, watch } from "vue";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
import ListingComponent from "@/components/ListingComponent/ListingComponent.vue";
|
||||
import LoadingComponent from "@/components/LoadingComponent/LoadingComponent.vue";
|
||||
import CustomAlert from "@/components/CustomAlert/CustomAlert.vue";
|
||||
import { ref, watch, onMounted } from "vue";
|
||||
import LoadingComponent from "@/components/ui/LoadingComponent.vue";
|
||||
import CustomAlert from "@/components/ui/CustomAlert.vue";
|
||||
import {
|
||||
listValidDepositTransactionsByWalletAddress,
|
||||
listAllTransactionByWalletAddress,
|
||||
@@ -16,8 +15,8 @@ import type { WalletTransaction } from "@/model/WalletTransaction";
|
||||
|
||||
import router from "@/router/index";
|
||||
|
||||
const etherStore = useEtherStore();
|
||||
const { walletAddress, networkName, selectedToken } = storeToRefs(etherStore);
|
||||
const user = useUser();
|
||||
const { walletAddress, network, selectedToken } = user;
|
||||
const loadingWithdraw = ref<boolean>(false);
|
||||
const showAlert = ref<boolean>(false);
|
||||
|
||||
@@ -30,7 +29,9 @@ const callWithdraw = async (amount: string) => {
|
||||
loadingWithdraw.value = true;
|
||||
let withdraw;
|
||||
try {
|
||||
withdraw = await withdrawDeposit(amount, selectedToken.value);
|
||||
withdraw = await withdrawDeposit(
|
||||
amount,
|
||||
network.value.tokens[selectedToken.value].address);
|
||||
} catch {
|
||||
loadingWithdraw.value = false;
|
||||
}
|
||||
@@ -47,21 +48,17 @@ const callWithdraw = async (amount: string) => {
|
||||
};
|
||||
|
||||
const getWalletTransactions = async () => {
|
||||
etherStore.setLoadingWalletTransactions(true);
|
||||
user.setLoadingWalletTransactions(true);
|
||||
if (walletAddress.value) {
|
||||
console.log("Will fetch all required data...");
|
||||
const walletDeposits = await listValidDepositTransactionsByWalletAddress(
|
||||
walletAddress.value
|
||||
);
|
||||
console.log("Fetched deposits");
|
||||
|
||||
const allUserTransactions = await listAllTransactionByWalletAddress(
|
||||
walletAddress.value
|
||||
);
|
||||
console.log("Fetched all transactions");
|
||||
|
||||
activeLockAmount.value = await getActiveLockAmount(walletAddress.value);
|
||||
console.log("Fetched active lock amount");
|
||||
|
||||
if (walletDeposits) {
|
||||
depositList.value = walletDeposits;
|
||||
@@ -70,7 +67,7 @@ const getWalletTransactions = async () => {
|
||||
transactionsList.value = allUserTransactions;
|
||||
}
|
||||
}
|
||||
etherStore.setLoadingWalletTransactions(false);
|
||||
user.setLoadingWalletTransactions(false);
|
||||
};
|
||||
|
||||
onMounted(async () => {
|
||||
@@ -84,7 +81,7 @@ watch(walletAddress, async () => {
|
||||
await getWalletTransactions();
|
||||
});
|
||||
|
||||
watch(networkName, async () => {
|
||||
watch(network, async () => {
|
||||
await getWalletTransactions();
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
import WantSellComponent from "@/components/SellerSteps/WantSellComponent.vue";
|
||||
import SendNetwork from "@/components/SellerSteps/SendNetwork.vue";
|
||||
import LoadingComponent from "@/components/LoadingComponent/LoadingComponent.vue";
|
||||
import { approveTokens, addDeposit } from "@/blockchain/sellerMethods";
|
||||
|
||||
import { ref } from "vue";
|
||||
import { useEtherStore } from "@/store/ether";
|
||||
import CustomAlert from "@/components/CustomAlert/CustomAlert.vue";
|
||||
|
||||
import SellerComponent from "@/components/SellerSteps/SellerComponent.vue";
|
||||
import SendNetwork from "@/components/SellerSteps/SendNetwork.vue";
|
||||
import LoadingComponent from "@/components/ui/LoadingComponent.vue";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
import { approveTokens, addDeposit } from "@/blockchain/sellerMethods";
|
||||
import CustomAlert from "@/components/ui/CustomAlert.vue";
|
||||
import type { Participant } from "@/utils/bbPay";
|
||||
|
||||
enum Step {
|
||||
Search,
|
||||
@@ -14,26 +15,18 @@ enum Step {
|
||||
Network,
|
||||
}
|
||||
|
||||
const etherStore = useEtherStore();
|
||||
etherStore.setSellerView(true);
|
||||
const user = useUser();
|
||||
user.setSellerView(true);
|
||||
|
||||
const flowStep = ref<Step>(Step.Sell);
|
||||
const loading = ref<boolean>(false);
|
||||
|
||||
const offerValue = ref<string>("");
|
||||
const pixKeyBuyer = ref<string>("");
|
||||
const showAlert = ref<boolean>(false);
|
||||
|
||||
// Verificar tipagem
|
||||
const approveOffer = async (args: {
|
||||
offer: string;
|
||||
postProcessedPixKey: string;
|
||||
}) => {
|
||||
const approveOffer = async (args: Participant) => {
|
||||
loading.value = true;
|
||||
try {
|
||||
offerValue.value = args.offer;
|
||||
pixKeyBuyer.value = args.postProcessedPixKey;
|
||||
await approveTokens(args.offer);
|
||||
await approveTokens(args);
|
||||
flowStep.value = Step.Network;
|
||||
loading.value = false;
|
||||
} catch (err) {
|
||||
@@ -46,8 +39,8 @@ const approveOffer = async (args: {
|
||||
const sendNetwork = async () => {
|
||||
loading.value = true;
|
||||
try {
|
||||
if (offerValue.value && pixKeyBuyer.value) {
|
||||
await addDeposit(String(offerValue.value), pixKeyBuyer.value);
|
||||
if (user.seller.value) {
|
||||
await addDeposit();
|
||||
flowStep.value = Step.Sell;
|
||||
loading.value = false;
|
||||
showAlert.value = true;
|
||||
@@ -63,7 +56,7 @@ const sendNetwork = async () => {
|
||||
<template>
|
||||
<div>
|
||||
<div v-if="flowStep == Step.Sell">
|
||||
<WantSellComponent v-if="!loading" @approve-tokens="approveOffer" />
|
||||
<SellerComponent v-if="!loading" @approve-tokens="approveOffer" />
|
||||
<LoadingComponent
|
||||
v-if="loading"
|
||||
:message="'A transação está sendo enviada para a rede.'"
|
||||
@@ -76,9 +69,9 @@ const sendNetwork = async () => {
|
||||
/>
|
||||
<div v-if="flowStep == Step.Network">
|
||||
<SendNetwork
|
||||
:pixKey="pixKeyBuyer"
|
||||
:offer="Number(offerValue)"
|
||||
:selected-token="etherStore.selectedToken"
|
||||
:sellerId="Number(user.sellerId.value)"
|
||||
:offer="Number(user.seller.value.offer)"
|
||||
:selected-token="user.selectedToken.value"
|
||||
v-if="!loading"
|
||||
@send-network="sendNetwork"
|
||||
/>
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
"extends": "@vue/tsconfig/tsconfig.node.json",
|
||||
"include": [
|
||||
"vite.config.*",
|
||||
"vitest.config.*",
|
||||
"cypress.config.*",
|
||||
"playwright.config.*"
|
||||
],
|
||||
|
||||
@@ -3,17 +3,18 @@
|
||||
"include": [
|
||||
"env.d.ts",
|
||||
"src/**/*",
|
||||
"src/**/*.vue"
|
||||
"src/**/*.vue",
|
||||
"scripts"
|
||||
],
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"strict": true,
|
||||
"paths": {
|
||||
"@/*": [
|
||||
"./src/*"
|
||||
]
|
||||
},
|
||||
"types": [
|
||||
"jest",
|
||||
"node"
|
||||
],
|
||||
"resolveJsonModule": true,
|
||||
@@ -24,6 +25,9 @@
|
||||
"esnext",
|
||||
"dom"
|
||||
],
|
||||
"preserveValueImports": false,
|
||||
"importsNotUsedAsValues": "remove",
|
||||
"verbatimModuleSyntax": false
|
||||
},
|
||||
"references": [
|
||||
{
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { fileURLToPath, URL } from "node:url";
|
||||
|
||||
import { defineConfig } from "vitest/config";
|
||||
import { defineConfig } from "vite";
|
||||
import vue from "@vitejs/plugin-vue";
|
||||
import vueJsx from "@vitejs/plugin-vue-jsx";
|
||||
import svgLoader from "vite-svg-loader";
|
||||
@@ -10,21 +10,24 @@ export default defineConfig({
|
||||
build: {
|
||||
target: "esnext",
|
||||
},
|
||||
test: {
|
||||
globals: true,
|
||||
environment: "jsdom",
|
||||
coverage: {
|
||||
provider: "c8",
|
||||
all: true,
|
||||
src: ["./src"],
|
||||
exclude: ["model/**", "**/__tests__/**"],
|
||||
reporter: ["text", "lcov", "html"],
|
||||
optimizeDeps: {
|
||||
esbuildOptions: {
|
||||
target: "esnext",
|
||||
define: {
|
||||
global: "globalThis",
|
||||
},
|
||||
supported: {
|
||||
bigint: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [vue(), vueJsx(), svgLoader()],
|
||||
resolve: {
|
||||
alias: {
|
||||
"@": fileURLToPath(new URL("./src", import.meta.url)),
|
||||
"viem/errors": fileURLToPath(
|
||||
new URL("./node_modules/viem/errors", import.meta.url)
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
11
wagmi.config.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { defineConfig } from '@wagmi/cli'
|
||||
import { hardhat } from '@wagmi/cli/plugins'
|
||||
|
||||
export default defineConfig({
|
||||
out: 'src/blockchain/abi.ts',
|
||||
contracts: [],
|
||||
plugins: [
|
||||
hardhat({
|
||||
project: '../p2pix-smart-contracts',
|
||||
}),],
|
||||
})
|
||||