Compare commits
No commits in common. "c1542707c24d1bd720023b985fc6b1bb5f4c2329" and "73ba77ca4fc80b38b5ed6eaa2c035dcf1d962dec" have entirely different histories.
c1542707c2
...
73ba77ca4f
@ -115,6 +115,4 @@ curl -X POST \
|
||||
-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" }'
|
||||
https://api.studio.thegraph.com/query/113713/p-2-pix/1
|
||||
10
package.json
10
package.json
@ -5,7 +5,9 @@
|
||||
"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 --fix",
|
||||
@ -20,6 +22,8 @@
|
||||
"@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",
|
||||
"qrcode": "^1.5.1",
|
||||
"viem": "^2.31.3",
|
||||
@ -33,25 +37,29 @@
|
||||
"@babel/preset-typescript": "^7.18.6",
|
||||
"@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": "~5.8.2",
|
||||
"vite": "^3.1.8",
|
||||
"vitest": "^0.28.1",
|
||||
"vue-tsc": "^2.2.8"
|
||||
}
|
||||
}
|
||||
|
||||
98
src/blockchain/__tests__/addresses.spec.ts
Normal file
98
src/blockchain/__tests__/addresses.spec.ts
Normal file
@ -0,0 +1,98 @@
|
||||
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 { useUser } from "@/composables/useUser";
|
||||
|
||||
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 user = useUser();
|
||||
user.setNetworkId(11155111);
|
||||
expect(getTokenAddress(TokenEnum.BRZ)).toBe(
|
||||
"0x4A2886EAEc931e04297ed336Cc55c4eb7C75BA00"
|
||||
);
|
||||
});
|
||||
|
||||
it("getTokenAddress Rootstock", () => {
|
||||
const user = useUser();
|
||||
user.setNetworkId(30);
|
||||
expect(getTokenAddress(TokenEnum.BRZ)).toBe(
|
||||
"0xfE841c74250e57640390f46d914C88d22C51e82e"
|
||||
);
|
||||
});
|
||||
|
||||
it("getTokenAddress Default", () => {
|
||||
expect(getTokenAddress(TokenEnum.BRZ)).toBe(
|
||||
"0x4A2886EAEc931e04297ed336Cc55c4eb7C75BA00"
|
||||
);
|
||||
});
|
||||
|
||||
it("getP2PixAddress Ethereum", () => {
|
||||
const user = useUser();
|
||||
user.setNetworkId(11155111);
|
||||
expect(getP2PixAddress()).toBe(
|
||||
"0x2414817FF64A114d91eCFA16a834d3fCf69103d4"
|
||||
);
|
||||
});
|
||||
|
||||
it("getP2PixAddress Rootstock", () => {
|
||||
const user = useUser();
|
||||
user.setNetworkId(30);
|
||||
expect(getP2PixAddress()).toBe(
|
||||
"0x98ba35eb14b38D6Aa709338283af3e922476dE34"
|
||||
);
|
||||
});
|
||||
|
||||
it("getP2PixAddress Default", () => {
|
||||
expect(getP2PixAddress()).toBe(
|
||||
"0x2414817FF64A114d91eCFA16a834d3fCf69103d4"
|
||||
);
|
||||
});
|
||||
|
||||
it("getProviderUrl Ethereum", () => {
|
||||
const user = useUser();
|
||||
user.setNetworkId(11155111);
|
||||
expect(getProviderUrl()).toBe(import.meta.env.VITE_GOERLI_API_URL);
|
||||
});
|
||||
|
||||
it("getProviderUrl Rootstock", () => {
|
||||
const user = useUser();
|
||||
user.setNetworkId(30);
|
||||
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 user = useUser();
|
||||
user.setNetworkId(11155111);
|
||||
expect(isPossibleNetwork(0x5 as NetworkEnum)).toBe(true);
|
||||
expect(isPossibleNetwork(5 as NetworkEnum)).toBe(true);
|
||||
expect(isPossibleNetwork(0x13881 as NetworkEnum)).toBe(true);
|
||||
expect(isPossibleNetwork(80001 as NetworkEnum)).toBe(true);
|
||||
|
||||
expect(isPossibleNetwork(NaN as NetworkEnum)).toBe(false);
|
||||
expect(isPossibleNetwork(0x55 as NetworkEnum)).toBe(false);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,9 +1,9 @@
|
||||
import { useUser } from "@/composables/useUser";
|
||||
import { NetworkEnum, TokenEnum } from "@/model/NetworkEnum";
|
||||
import { createPublicClient, http, type Address } from "viem";
|
||||
import { createPublicClient, http } from "viem";
|
||||
import { sepolia, rootstock } from "viem/chains";
|
||||
|
||||
const Tokens: { [key in NetworkEnum]: { [key in TokenEnum]: Address } } = {
|
||||
const Tokens: { [key in NetworkEnum]: { [key in TokenEnum]: string } } = {
|
||||
[NetworkEnum.sepolia]: {
|
||||
BRZ: "0x3eBE67A2C7bdB2081CBd34ba3281E90377462289",
|
||||
// BRX: "0x3eBE67A2C7bdB2081CBd34ba3281E90377462289",
|
||||
@ -14,7 +14,7 @@ const Tokens: { [key in NetworkEnum]: { [key in TokenEnum]: Address } } = {
|
||||
},
|
||||
};
|
||||
|
||||
export const getTokenByAddress = (address: Address) => {
|
||||
export const getTokenByAddress = (address: string) => {
|
||||
const user = useUser();
|
||||
const networksTokens = Tokens[user.networkName.value];
|
||||
for (const [token, tokenAddress] of Object.entries(networksTokens)) {
|
||||
@ -28,23 +28,19 @@ export const getTokenByAddress = (address: Address) => {
|
||||
export const getTokenAddress = (
|
||||
token: TokenEnum,
|
||||
network?: NetworkEnum
|
||||
): Address => {
|
||||
): string => {
|
||||
const user = useUser();
|
||||
return Tokens[network ? network : user.networkName.value][
|
||||
token
|
||||
];
|
||||
return Tokens[network ? network : user.networkName.value][token];
|
||||
};
|
||||
|
||||
export const getP2PixAddress = (network?: NetworkEnum): Address => {
|
||||
export const getP2PixAddress = (network?: NetworkEnum): string => {
|
||||
const user = useUser();
|
||||
const possibleP2PixAddresses: { [key in NetworkEnum]: Address } = {
|
||||
const possibleP2PixAddresses: { [key in NetworkEnum]: string } = {
|
||||
[NetworkEnum.sepolia]: "0xb7cD135F5eFD9760981e02E2a898790b688939fe",
|
||||
[NetworkEnum.rootstock]: "0x98ba35eb14b38D6Aa709338283af3e922476dE34",
|
||||
};
|
||||
|
||||
return possibleP2PixAddresses[
|
||||
network ? network : user.networkName.value
|
||||
];
|
||||
return possibleP2PixAddresses[network ? network : user.networkName.value];
|
||||
};
|
||||
|
||||
export const getProviderUrl = (network?: NetworkEnum): string => {
|
||||
@ -58,6 +54,7 @@ export const getProviderUrl = (network?: NetworkEnum): string => {
|
||||
};
|
||||
|
||||
export const getProviderByNetwork = (network: NetworkEnum) => {
|
||||
console.log("network", network);
|
||||
const chain = network === NetworkEnum.sepolia ? sepolia : rootstock;
|
||||
return createPublicClient({
|
||||
chain,
|
||||
|
||||
@ -1,55 +1,34 @@
|
||||
import { getContract } from "./provider";
|
||||
import { getTokenAddress } from "./addresses";
|
||||
import {
|
||||
bytesToHex,
|
||||
encodeAbiParameters,
|
||||
keccak256,
|
||||
parseAbiParameters,
|
||||
parseEther,
|
||||
stringToBytes,
|
||||
stringToHex,
|
||||
toBytes,
|
||||
type Address,
|
||||
} from "viem";
|
||||
import { parseEther } from "viem";
|
||||
import type { TokenEnum } from "@/model/NetworkEnum";
|
||||
|
||||
export const addLock = async (
|
||||
sellerAddress: Address,
|
||||
tokenAddress: Address,
|
||||
sellerAddress: string,
|
||||
tokenAddress: string,
|
||||
amount: number
|
||||
): Promise<bigint> => {
|
||||
const { address, abi, wallet, client, account } = await getContract();
|
||||
): Promise<string> => {
|
||||
const { address, abi, wallet, client } = await getContract();
|
||||
const parsedAmount = parseEther(amount.toString());
|
||||
|
||||
if (!wallet) {
|
||||
throw new Error("Wallet not connected");
|
||||
}
|
||||
|
||||
const { result, request } = await client.simulateContract({
|
||||
const { request } = await client.simulateContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "lock",
|
||||
args: [sellerAddress, tokenAddress, parsedAmount, [], []],
|
||||
account,
|
||||
});
|
||||
console.log(wallet);
|
||||
const hash = await wallet.writeContract(request);
|
||||
const receipt = await client.waitForTransactionReceipt({ hash });
|
||||
|
||||
if (!receipt.status)
|
||||
throw new Error("Transaction failed: " + receipt.transactionHash);
|
||||
|
||||
return result;
|
||||
return receipt.status ? receipt.logs[0].topics[2] : "";
|
||||
};
|
||||
|
||||
export const withdrawDeposit = async (
|
||||
amount: string,
|
||||
token: TokenEnum
|
||||
): Promise<boolean> => {
|
||||
const { address, abi, wallet, client, account } = await getContract();
|
||||
|
||||
if (!wallet) {
|
||||
throw new Error("Wallet not connected");
|
||||
}
|
||||
const { address, abi, wallet, client } = await getContract();
|
||||
|
||||
const tokenAddress = getTokenAddress(token);
|
||||
|
||||
@ -58,36 +37,22 @@ export const withdrawDeposit = async (
|
||||
abi,
|
||||
functionName: "withdraw",
|
||||
args: [tokenAddress, parseEther(amount), []],
|
||||
account
|
||||
});
|
||||
|
||||
const hash = await wallet.writeContract(request);
|
||||
const receipt = await client.waitForTransactionReceipt({ hash });
|
||||
|
||||
return receipt.status === "success";
|
||||
return receipt.status;
|
||||
};
|
||||
|
||||
export const releaseLock = async (
|
||||
lockID: bigint,
|
||||
pixtarget: string,
|
||||
signature: string
|
||||
): Promise<any> => {
|
||||
const { address, abi, wallet, client, account } = await getContract();
|
||||
|
||||
console.log("Releasing lock", { lockID, pixtarget, signature });
|
||||
if (!wallet) {
|
||||
throw new Error("Wallet not connected");
|
||||
}
|
||||
|
||||
// Convert pixtarget to bytes32
|
||||
const pixTimestamp = keccak256(stringToHex(pixtarget, { size: 32 }) );
|
||||
export const releaseLock = async (solicitation: any): Promise<any> => {
|
||||
const { address, abi, wallet, client } = await getContract();
|
||||
|
||||
const { request } = await client.simulateContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "release",
|
||||
args: [BigInt(lockID), pixTimestamp, stringToHex(signature)],
|
||||
account
|
||||
args: [solicitation.lockId, solicitation.e2eId],
|
||||
});
|
||||
|
||||
const hash = await wallet.writeContract(request);
|
||||
|
||||
@ -1,14 +1,13 @@
|
||||
import { useUser } from "@/composables/useUser";
|
||||
import { formatEther, toHex, stringToHex } from "viem";
|
||||
import type { PublicClient, Address } from "viem";
|
||||
import { formatEther, toHex, type PublicClient } from "viem";
|
||||
|
||||
import p2pix from "@/utils/smart_contract_files/P2PIX.json";
|
||||
import { getContract } from "./provider";
|
||||
import { getP2PixAddress, getTokenAddress } from "./addresses";
|
||||
import { p2PixAbi } from "./abi"
|
||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||
import { getNetworkSubgraphURL, NetworkEnum, TokenEnum } from "@/model/NetworkEnum";
|
||||
import { getP2PixAddress, getTokenAddress } from "./addresses";
|
||||
import { getNetworkSubgraphURL, NetworkEnum } from "@/model/NetworkEnum";
|
||||
import type { UnreleasedLock } from "@/model/UnreleasedLock";
|
||||
import type { LockStatus } from "@/model/LockStatus"
|
||||
import type { Pix } from "@/model/Pix";
|
||||
|
||||
const getNetworksLiquidity = async (): Promise<void> => {
|
||||
const user = useUser();
|
||||
@ -31,13 +30,10 @@ const getNetworksLiquidity = async (): Promise<void> => {
|
||||
user.setLoadingNetworkLiquidity(false);
|
||||
};
|
||||
|
||||
const getParticipantID = async (
|
||||
seller: string,
|
||||
token: string
|
||||
): Promise<string> => {
|
||||
const getPixKey = async (seller: string, token: string): Promise<string> => {
|
||||
const { address, abi, client } = await getContract();
|
||||
|
||||
const participantIDHex = await client.readContract({
|
||||
const pixKeyHex = await client.readContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "getPixTarget",
|
||||
@ -46,14 +42,13 @@ const getParticipantID = async (
|
||||
|
||||
// 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");
|
||||
typeof pixKeyHex === "string" ? pixKeyHex : toHex(pixKeyHex);
|
||||
if (!hexString) throw new Error("PixKey not found");
|
||||
const bytes = new Uint8Array(
|
||||
// @ts-ignore
|
||||
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
|
||||
@ -61,17 +56,17 @@ const getParticipantID = async (
|
||||
};
|
||||
|
||||
const getValidDeposits = async (
|
||||
token: Address,
|
||||
token: string,
|
||||
network: NetworkEnum,
|
||||
contractInfo?: { client: PublicClient; address: Address }
|
||||
contractInfo?: { client: any; address: string }
|
||||
): Promise<ValidDeposit[]> => {
|
||||
let client: PublicClient, abi;
|
||||
let client: PublicClient, address, abi;
|
||||
|
||||
if (contractInfo) {
|
||||
({ client } = contractInfo);
|
||||
abi = p2PixAbi;
|
||||
({ client, address } = contractInfo);
|
||||
abi = p2pix.abi;
|
||||
} else {
|
||||
({ abi, client } = await getContract(true));
|
||||
({ address, abi, client } = await getContract(true));
|
||||
}
|
||||
|
||||
// TODO: Remove this once we have a subgraph for rootstock
|
||||
@ -102,11 +97,11 @@ const getValidDeposits = async (
|
||||
const depositData = await depositLogs.json();
|
||||
const depositAddeds = depositData.data.depositAddeds;
|
||||
const uniqueSellers = depositAddeds.reduce(
|
||||
(acc: Record<Address, boolean>, deposit: any) => {
|
||||
(acc: Record<string, boolean>, deposit: any) => {
|
||||
acc[deposit.seller] = true;
|
||||
return acc;
|
||||
},
|
||||
{} as Record<Address, boolean>
|
||||
{} as Record<string, boolean>
|
||||
);
|
||||
|
||||
if (!contractInfo) {
|
||||
@ -116,7 +111,7 @@ const getValidDeposits = async (
|
||||
|
||||
const depositList: { [key: string]: ValidDeposit } = {};
|
||||
|
||||
const sellersList = Object.keys(uniqueSellers) as Address[];
|
||||
const sellersList = Object.keys(uniqueSellers);
|
||||
// Use multicall to batch all getBalance requests
|
||||
const balanceCalls = sellersList.map((seller) => ({
|
||||
address: getP2PixAddress(network),
|
||||
@ -135,12 +130,12 @@ const getValidDeposits = async (
|
||||
|
||||
if (!mappedBalance.error && mappedBalance.result) {
|
||||
const validDeposit: ValidDeposit = {
|
||||
token,
|
||||
token: token,
|
||||
blockNumber: 0,
|
||||
remaining: Number(formatEther(mappedBalance.result as bigint)),
|
||||
seller,
|
||||
seller: seller,
|
||||
network,
|
||||
participantID: "",
|
||||
pixKey: "",
|
||||
};
|
||||
depositList[seller + token] = validDeposit;
|
||||
}
|
||||
@ -149,22 +144,28 @@ const getValidDeposits = async (
|
||||
};
|
||||
|
||||
const getUnreleasedLockById = async (
|
||||
lockID: bigint
|
||||
lockID: string
|
||||
): Promise<UnreleasedLock> => {
|
||||
const { address, abi, client } = await getContract();
|
||||
const pixData: Pix = {
|
||||
pixKey: "",
|
||||
};
|
||||
|
||||
const [ , , , amount, token, seller ] = await client.readContract({
|
||||
const lock = await client.readContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "mapLocks",
|
||||
args: [lockID],
|
||||
args: [BigInt(lockID)],
|
||||
});
|
||||
|
||||
const pixTarget = lock.pixTarget;
|
||||
const amount = formatEther(lock.amount);
|
||||
pixData.pixKey = pixTarget;
|
||||
pixData.value = Number(amount);
|
||||
|
||||
return {
|
||||
lockID,
|
||||
amount: Number(formatEther(amount)),
|
||||
tokenAddress: token,
|
||||
sellerAddress: seller,
|
||||
lockID: lockID,
|
||||
pix: pixData,
|
||||
};
|
||||
};
|
||||
|
||||
@ -172,5 +173,5 @@ export {
|
||||
getValidDeposits,
|
||||
getNetworksLiquidity,
|
||||
getUnreleasedLockById,
|
||||
getParticipantID,
|
||||
getPixKey,
|
||||
};
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { p2PixAbi } from "./abi";
|
||||
import p2pix from "@/utils/smart_contract_files/P2PIX.json";
|
||||
import { updateWalletStatus } from "./wallet";
|
||||
import { getProviderUrl, getP2PixAddress } from "./addresses";
|
||||
import {
|
||||
@ -12,9 +12,11 @@ import {
|
||||
import { sepolia, rootstock } from "viem/chains";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
|
||||
let publicClient: PublicClient | null = null;
|
||||
let walletClient: WalletClient | null = null;
|
||||
|
||||
const getPublicClient = (): PublicClient => {
|
||||
const getPublicClient: PublicClient | null = (onlyRpcProvider = false) => {
|
||||
if (onlyRpcProvider) {
|
||||
const user = useUser();
|
||||
const rpcUrl = getProviderUrl();
|
||||
return createPublicClient({
|
||||
@ -22,32 +24,36 @@ const getPublicClient = (): PublicClient => {
|
||||
Number(user.networkName.value) === sepolia.id ? sepolia : rootstock,
|
||||
transport: http(rpcUrl),
|
||||
});
|
||||
}
|
||||
return publicClient;
|
||||
};
|
||||
|
||||
const getWalletClient = (): WalletClient | null => {
|
||||
const getWalletClient: WalletClient | null = () => {
|
||||
return walletClient;
|
||||
};
|
||||
|
||||
const getContract = async (onlyRpcProvider = false) => {
|
||||
const client = getPublicClient();
|
||||
const client = getPublicClient(onlyRpcProvider);
|
||||
const address = getP2PixAddress();
|
||||
const abi = p2PixAbi;
|
||||
const wallet = onlyRpcProvider ? null : getWalletClient();
|
||||
const abi = p2pix.abi;
|
||||
const wallet = getWalletClient();
|
||||
|
||||
if (!client) {
|
||||
throw new Error("Public client not initialized");
|
||||
}
|
||||
|
||||
const [account] = wallet ? await wallet.getAddresses() : [null];
|
||||
const [account] = wallet ? await wallet.getAddresses() : [""];
|
||||
|
||||
return { address, abi, client, wallet, account };
|
||||
};
|
||||
|
||||
const connectProvider = async (p: any): Promise<void> => {
|
||||
console.log("Connecting to wallet provider...");
|
||||
const user = useUser();
|
||||
const chain =
|
||||
Number(user.networkName.value) === sepolia.id ? sepolia : rootstock;
|
||||
|
||||
publicClient = createPublicClient({
|
||||
chain,
|
||||
transport: custom(p),
|
||||
});
|
||||
|
||||
const [account] = await p!.request({ method: "eth_requestAccounts" });
|
||||
|
||||
walletClient = createWalletClient({
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { getContract, getPublicClient, getWalletClient } from "./provider";
|
||||
import { getTokenAddress, getP2PixAddress } from "./addresses";
|
||||
import { parseEther, toHex } from "viem";
|
||||
import { sepolia, rootstock } from "viem/chains";
|
||||
|
||||
import { mockTokenAbi } from "./abi";
|
||||
import mockToken from "../utils/smart_contract_files/MockToken.json";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
import { createParticipant } from "@/utils/bbPay";
|
||||
import type { Participant } from "@/utils/bbPay";
|
||||
@ -26,21 +25,19 @@ const approveTokens = async (participant: Participant): Promise<any> => {
|
||||
// Check if the token is already approved
|
||||
const allowance = await publicClient.readContract({
|
||||
address: tokenAddress,
|
||||
abi: mockTokenAbi,
|
||||
abi: mockToken.abi,
|
||||
functionName: "allowance",
|
||||
args: [account, getP2PixAddress()],
|
||||
});
|
||||
|
||||
if ( allowance < parseEther(participant.offer.toString()) ) {
|
||||
if (allowance < parseEther(participant.offer.toString())) {
|
||||
// Approve tokens
|
||||
const chain = user.networkId.value === sepolia.id ? sepolia : rootstock;
|
||||
const hash = await walletClient.writeContract({
|
||||
address: tokenAddress,
|
||||
abi: mockTokenAbi,
|
||||
abi: mockToken.abi,
|
||||
functionName: "approve",
|
||||
args: [getP2PixAddress(), parseEther(participant.offer.toString())],
|
||||
account,
|
||||
chain,
|
||||
});
|
||||
|
||||
await publicClient.waitForTransactionReceipt({ hash });
|
||||
@ -62,23 +59,19 @@ const addDeposit = async (): Promise<any> => {
|
||||
|
||||
const sellerId = await createParticipant(user.seller.value);
|
||||
user.setSellerId(sellerId.id);
|
||||
if (!sellerId.id) {
|
||||
throw new Error("Failed to create participant");
|
||||
}
|
||||
const chain = user.networkId.value === sepolia.id ? sepolia : rootstock;
|
||||
|
||||
const hash = await walletClient.writeContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "deposit",
|
||||
args: [
|
||||
user.networkId.value + "-" + sellerId.id,
|
||||
user.networkId + "-" + sellerId.id,
|
||||
toHex("", { size: 32 }),
|
||||
getTokenAddress(user.selectedToken.value),
|
||||
parseEther(user.seller.value.offer.toString()),
|
||||
true,
|
||||
],
|
||||
account,
|
||||
chain,
|
||||
});
|
||||
|
||||
const receipt = await client.waitForTransactionReceipt({ hash });
|
||||
|
||||
@ -1,15 +1,17 @@
|
||||
import { formatEther, hexToString, type Address } from "viem";
|
||||
import { decodeEventLog, formatEther, type Log } from "viem";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
|
||||
import { getPublicClient, getWalletClient, getContract } from "./provider";
|
||||
import { getTokenAddress } from "./addresses";
|
||||
|
||||
import { getValidDeposits, getUnreleasedLockById } from "./events";
|
||||
import p2pix from "@/utils/smart_contract_files/P2PIX.json";
|
||||
|
||||
import { getValidDeposits } from "./events";
|
||||
|
||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||
import type { WalletTransaction } from "@/model/WalletTransaction";
|
||||
import type { UnreleasedLock } from "@/model/UnreleasedLock";
|
||||
import { LockStatus } from "@/model/LockStatus";
|
||||
import type { Pix } from "@/model/Pix";
|
||||
import { getNetworkSubgraphURL } from "@/model/NetworkEnum";
|
||||
|
||||
export const updateWalletStatus = async (): Promise<void> => {
|
||||
@ -32,7 +34,7 @@ export const updateWalletStatus = async (): Promise<void> => {
|
||||
};
|
||||
|
||||
export const listValidDepositTransactionsByWalletAddress = async (
|
||||
walletAddress: Address
|
||||
walletAddress: string
|
||||
): Promise<ValidDeposit[]> => {
|
||||
const user = useUser();
|
||||
const walletDeposits = await getValidDeposits(
|
||||
@ -50,19 +52,61 @@ export const listValidDepositTransactionsByWalletAddress = async (
|
||||
return [];
|
||||
};
|
||||
|
||||
const getLockStatus = async (id: bigint): Promise<LockStatus> => {
|
||||
const getLockStatus = async (id: bigint): Promise<number> => {
|
||||
const { address, abi, client } = await getContract();
|
||||
const [ sortedIDs , status ] = await client.readContract({
|
||||
const result = await client.readContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "getLocksStatus",
|
||||
args: [[id]],
|
||||
});
|
||||
return status[0];
|
||||
return result[1][0];
|
||||
};
|
||||
|
||||
const filterLockStatus = async (
|
||||
transactions: Log[]
|
||||
): Promise<WalletTransaction[]> => {
|
||||
const txs: WalletTransaction[] = [];
|
||||
|
||||
for (const transaction of transactions) {
|
||||
try {
|
||||
const decoded = decodeEventLog({
|
||||
abi: p2pix.abi,
|
||||
data: transaction.data,
|
||||
topics: transaction.topics,
|
||||
});
|
||||
|
||||
if (!decoded || !decoded.args) continue;
|
||||
|
||||
// Type assertion to handle the args safely
|
||||
const args = decoded.args as Record<string, any>;
|
||||
|
||||
const tx: WalletTransaction = {
|
||||
token: args.token ? String(args.token) : "",
|
||||
blockNumber: Number(transaction.blockNumber),
|
||||
amount: args.amount ? Number(formatEther(args.amount)) : -1,
|
||||
seller: args.seller ? String(args.seller) : "",
|
||||
buyer: args.buyer ? String(args.buyer) : "",
|
||||
event: decoded.eventName || "",
|
||||
lockStatus:
|
||||
decoded.eventName == "LockAdded" && args.lockID
|
||||
? await getLockStatus(args.lockID)
|
||||
: -1,
|
||||
transactionHash: transaction.transactionHash
|
||||
? transaction.transactionHash
|
||||
: "",
|
||||
transactionID: args.lockID ? args.lockID.toString() : "",
|
||||
};
|
||||
txs.push(tx);
|
||||
} catch (error) {
|
||||
console.error("Error decoding log", error);
|
||||
}
|
||||
}
|
||||
return txs;
|
||||
};
|
||||
|
||||
export const listAllTransactionByWalletAddress = async (
|
||||
walletAddress: Address
|
||||
walletAddress: string
|
||||
): Promise<WalletTransaction[]> => {
|
||||
const user = useUser();
|
||||
|
||||
@ -74,7 +118,6 @@ export const listAllTransactionByWalletAddress = async (
|
||||
query: `
|
||||
{
|
||||
depositAddeds(where: {seller: "${walletAddress.toLowerCase()}"}) {
|
||||
id
|
||||
seller
|
||||
token
|
||||
amount
|
||||
@ -86,6 +129,7 @@ export const listAllTransactionByWalletAddress = async (
|
||||
buyer
|
||||
lockID
|
||||
seller
|
||||
token
|
||||
amount
|
||||
blockTimestamp
|
||||
blockNumber
|
||||
@ -94,6 +138,7 @@ export const listAllTransactionByWalletAddress = async (
|
||||
lockReleaseds(where: {buyer: "${walletAddress.toLowerCase()}"}) {
|
||||
buyer
|
||||
lockId
|
||||
e2eId
|
||||
blockTimestamp
|
||||
blockNumber
|
||||
transactionHash
|
||||
@ -110,6 +155,7 @@ export const listAllTransactionByWalletAddress = async (
|
||||
`,
|
||||
};
|
||||
|
||||
console.log("Fetching transactions from subgraph");
|
||||
const response = await fetch(getNetworkSubgraphURL(network), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@ -119,11 +165,14 @@ export const listAllTransactionByWalletAddress = async (
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
console.log("Subgraph data fetched:", data);
|
||||
|
||||
// Convert all transactions to common WalletTransaction format
|
||||
const transactions: WalletTransaction[] = [];
|
||||
|
||||
// Process deposit added events
|
||||
if (data.data?.depositAddeds) {
|
||||
console.log("Processing deposit events");
|
||||
for (const deposit of data.data.depositAddeds) {
|
||||
transactions.push({
|
||||
token: deposit.token,
|
||||
@ -132,7 +181,7 @@ export const listAllTransactionByWalletAddress = async (
|
||||
seller: deposit.seller,
|
||||
buyer: "",
|
||||
event: "DepositAdded",
|
||||
lockStatus: undefined,
|
||||
lockStatus: -1,
|
||||
transactionHash: deposit.transactionHash,
|
||||
});
|
||||
}
|
||||
@ -140,6 +189,7 @@ export const listAllTransactionByWalletAddress = async (
|
||||
|
||||
// Process lock added events
|
||||
if (data.data?.lockAddeds) {
|
||||
console.log("Processing lock events");
|
||||
for (const lock of data.data.lockAddeds) {
|
||||
// Get lock status from the contract
|
||||
const lockStatus = await getLockStatus(BigInt(lock.lockID));
|
||||
@ -160,15 +210,16 @@ export const listAllTransactionByWalletAddress = async (
|
||||
|
||||
// Process lock released events
|
||||
if (data.data?.lockReleaseds) {
|
||||
console.log("Processing release events");
|
||||
for (const release of data.data.lockReleaseds) {
|
||||
transactions.push({
|
||||
token: undefined, // Subgraph doesn't provide token in this event, we could enhance this later
|
||||
token: "", // 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,
|
||||
lockStatus: -1,
|
||||
transactionHash: release.transactionHash,
|
||||
transactionID: release.lockId.toString(),
|
||||
});
|
||||
@ -177,6 +228,7 @@ export const listAllTransactionByWalletAddress = async (
|
||||
|
||||
// Process deposit withdrawn events
|
||||
if (data.data?.depositWithdrawns) {
|
||||
console.log("Processing withdrawal events");
|
||||
for (const withdrawal of data.data.depositWithdrawns) {
|
||||
transactions.push({
|
||||
token: withdrawal.token,
|
||||
@ -185,7 +237,7 @@ export const listAllTransactionByWalletAddress = async (
|
||||
seller: withdrawal.seller,
|
||||
buyer: "",
|
||||
event: "DepositWithdrawn",
|
||||
lockStatus: undefined,
|
||||
lockStatus: -1,
|
||||
transactionHash: withdrawal.transactionHash,
|
||||
});
|
||||
}
|
||||
@ -197,7 +249,7 @@ export const listAllTransactionByWalletAddress = async (
|
||||
|
||||
// get wallet's release transactions
|
||||
export const listReleaseTransactionByWalletAddress = async (
|
||||
walletAddress: Address
|
||||
walletAddress: string
|
||||
) => {
|
||||
const user = useUser();
|
||||
const network = user.networkName.value;
|
||||
@ -261,7 +313,7 @@ export const listReleaseTransactionByWalletAddress = async (
|
||||
.filter((decoded: any) => decoded !== null);
|
||||
};
|
||||
|
||||
const listLockTransactionByWalletAddress = async (walletAddress: Address) => {
|
||||
const listLockTransactionByWalletAddress = async (walletAddress: string) => {
|
||||
const user = useUser();
|
||||
const network = user.networkName.value;
|
||||
|
||||
@ -273,6 +325,7 @@ const listLockTransactionByWalletAddress = async (walletAddress: Address) => {
|
||||
buyer
|
||||
lockID
|
||||
seller
|
||||
token
|
||||
amount
|
||||
blockTimestamp
|
||||
blockNumber
|
||||
@ -330,9 +383,10 @@ const listLockTransactionByWalletAddress = async (walletAddress: Address) => {
|
||||
}
|
||||
};
|
||||
|
||||
const listLockTransactionBySellerAddress = async (sellerAddress: Address) => {
|
||||
const listLockTransactionBySellerAddress = async (sellerAddress: string) => {
|
||||
const user = useUser();
|
||||
const network = user.networkName.value;
|
||||
console.log("Will get locks as seller", sellerAddress);
|
||||
|
||||
// Query subgraph for lock added transactions where seller matches
|
||||
const subgraphQuery = {
|
||||
@ -402,32 +456,54 @@ const listLockTransactionBySellerAddress = async (sellerAddress: Address) => {
|
||||
};
|
||||
|
||||
export const checkUnreleasedLock = async (
|
||||
walletAddress: Address
|
||||
walletAddress: string
|
||||
): Promise<UnreleasedLock | undefined> => {
|
||||
const { address, abi, client } = await getContract();
|
||||
const pixData: Pix = {
|
||||
pixKey: "",
|
||||
};
|
||||
|
||||
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({
|
||||
const lockStatus = await client.readContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "getLocksStatus",
|
||||
args: [lockIds],
|
||||
});
|
||||
|
||||
const unreleasedLockId = status.findIndex(
|
||||
(status: LockStatus) => status == LockStatus.Active
|
||||
const unreleasedLockId = lockStatus[1].findIndex(
|
||||
(status: number) => status == 1
|
||||
);
|
||||
|
||||
if (unreleasedLockId !== -1)
|
||||
return getUnreleasedLockById(sortedIDs[unreleasedLockId]);
|
||||
|
||||
if (unreleasedLockId !== -1) {
|
||||
const lockID = lockStatus[0][unreleasedLockId];
|
||||
|
||||
const lock = await client.readContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "mapLocks",
|
||||
args: [lockID],
|
||||
});
|
||||
|
||||
const pixTarget = lock.pixTarget;
|
||||
const amount = formatEther(lock.amount);
|
||||
pixData.pixKey = pixTarget;
|
||||
pixData.value = Number(amount);
|
||||
|
||||
return {
|
||||
lockID,
|
||||
pix: pixData,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
export const getActiveLockAmount = async (
|
||||
walletAddress: Address
|
||||
walletAddress: string
|
||||
): Promise<number> => {
|
||||
const { address, abi, client } = await getContract(true);
|
||||
const lockSeller = await listLockTransactionBySellerAddress(walletAddress);
|
||||
@ -436,19 +512,19 @@ export const getActiveLockAmount = async (
|
||||
|
||||
const lockIds = lockSeller.map((lock: any) => lock.args.lockID);
|
||||
|
||||
const [ sortedIDs, status ] = await client.readContract({
|
||||
const lockStatus = await client.readContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "getLocksStatus",
|
||||
args: [lockIds],
|
||||
});
|
||||
|
||||
const mapLocksRequests = status.map((id: LockStatus) =>
|
||||
const mapLocksRequests = lockStatus[0].map((id: bigint) =>
|
||||
client.readContract({
|
||||
address: address,
|
||||
address,
|
||||
abi,
|
||||
functionName: "mapLocks",
|
||||
args: [BigInt(id)],
|
||||
args: [id],
|
||||
})
|
||||
);
|
||||
|
||||
@ -457,24 +533,9 @@ export const getActiveLockAmount = async (
|
||||
});
|
||||
|
||||
return mapLocksResults.reduce((total: number, lock: any, index: number) => {
|
||||
if (status[index] === 1) {
|
||||
if (lockStatus[1][index] === 1) {
|
||||
return total + Number(formatEther(lock.amount));
|
||||
}
|
||||
return total;
|
||||
}, 0);
|
||||
};
|
||||
|
||||
export const getSellerParticipantId = async (
|
||||
sellerAddress: Address,
|
||||
tokenAddress: Address
|
||||
): Promise<string> => {
|
||||
const { address, abi, client } = await getContract();
|
||||
|
||||
const participantId = await client.readContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "getPixTarget",
|
||||
args: [sellerAddress, tokenAddress],
|
||||
});
|
||||
return hexToString(participantId);
|
||||
};
|
||||
|
||||
@ -0,0 +1,37 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
27
src/components/CustomButton/__tests__/CustomButton.spec.ts
Normal file
27
src/components/CustomButton/__tests__/CustomButton.spec.ts
Normal file
@ -0,0 +1,27 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@ -19,7 +19,7 @@ if (props.isRedirectModal) {
|
||||
<template>
|
||||
<div>
|
||||
<div
|
||||
class="modal-overlay inset-0 fixed hidden md:block justify-center backdrop-blur-sm sm:backdrop-blur-none"
|
||||
class="modal-overlay inset-0 fixed justify-center backdrop-blur-sm sm:backdrop-blur-none"
|
||||
v-if="!isRedirectModal"
|
||||
>
|
||||
<div class="modal px-5 text-center">
|
||||
|
||||
27
src/components/CustomModal/__tests__/CustomModal.spec.ts
Normal file
27
src/components/CustomModal/__tests__/CustomModal.spec.ts
Normal file
@ -0,0 +1,27 @@
|
||||
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");
|
||||
});
|
||||
});
|
||||
@ -7,6 +7,7 @@ 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";
|
||||
|
||||
const user = useUser();
|
||||
@ -159,14 +160,10 @@ showInitialItems();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="main-container max-w-md flex justify-center items-center min-h-[200px] w-16 h-16"
|
||||
v-if="loadingWalletTransactions"
|
||||
>
|
||||
Carregando ofertas...
|
||||
<div class="main-container max-w-md" v-if="loadingWalletTransactions">
|
||||
<SpinnerComponent width="8" height="8"></SpinnerComponent>
|
||||
</div>
|
||||
<div class="main-container max-w-md" v-else>
|
||||
<div class="main-container max-w-md" v-if="!loadingWalletTransactions">
|
||||
<div
|
||||
class="w-full bg-white p-4 sm:p-6 rounded-lg"
|
||||
v-if="props.validDeposits.length > 0"
|
||||
@ -177,12 +174,12 @@ showInitialItems();
|
||||
Saldo disponível
|
||||
</p>
|
||||
<p class="text-xl leading-7 font-semibold text-gray-900">
|
||||
{{ getRemaining() }} {{ user.selectedToken.value }}
|
||||
{{ 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)} ${
|
||||
user.selectedToken.value
|
||||
etherStore.selectedToken
|
||||
} em lock`
|
||||
}}</span>
|
||||
<div
|
||||
@ -286,10 +283,10 @@ showInitialItems();
|
||||
class="text-xl sm:text-xl leading-7 font-semibold text-gray-900"
|
||||
>
|
||||
{{ item.amount }}
|
||||
<!-- {{ getTokenByAddress(item.token) }} -->
|
||||
{{ getTokenByAddress(item.token) }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex flex-col items-center justify-center">
|
||||
<div>
|
||||
<div
|
||||
class="bg-amber-300 status-text"
|
||||
v-if="getEventName(item.event) == 'Reserva' && item.lockStatus == 1"
|
||||
@ -412,7 +409,6 @@ p {
|
||||
}
|
||||
|
||||
input[type="number"] {
|
||||
appearance: textfield;
|
||||
-moz-appearance: textfield;
|
||||
}
|
||||
|
||||
|
||||
@ -0,0 +1,85 @@
|
||||
import { describe, expect, beforeEach } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import ListingComponent from "../ListingComponent.vue";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
import { MockValidDeposits } from "@/model/mock/ValidDepositMock";
|
||||
import { MockWalletTransactions } from "@/model/mock/WalletTransactionMock";
|
||||
|
||||
describe("ListingComponent.vue", () => {
|
||||
beforeEach(() => {
|
||||
useUser().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");
|
||||
});
|
||||
});
|
||||
@ -0,0 +1,27 @@
|
||||
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,124 +1,28 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, onUnmounted } from "vue";
|
||||
import { onMounted, onUnmounted, ref } from "vue";
|
||||
import CustomButton from "@/components/CustomButton/CustomButton.vue";
|
||||
import CustomModal from "@/components//CustomModal/CustomModal.vue";
|
||||
import SpinnerComponent from "@/components/SpinnerComponent.vue";
|
||||
import { createSolicitation, getSolicitation, type Offer } from "@/utils/bbPay";
|
||||
import { getSellerParticipantId } from "@/blockchain/wallet";
|
||||
import { getUnreleasedLockById } from "@/blockchain/events";
|
||||
import QRCode from "qrcode";
|
||||
|
||||
// Props
|
||||
interface Props {
|
||||
lockID: string;
|
||||
}
|
||||
|
||||
const props = defineProps<Props>();
|
||||
|
||||
const windowSize = ref<number>(window.innerWidth);
|
||||
const qrCode = ref<string>("");
|
||||
const qrCodeSvg = ref<string>("");
|
||||
const isPixValid = ref<boolean>(false);
|
||||
const showWarnModal = ref<boolean>(true);
|
||||
const pixTarget = ref<string>("");
|
||||
const releaseSignature = ref<string>("");
|
||||
const solicitationData = ref<any>(null);
|
||||
const pollingInterval = 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) {
|
||||
pixTarget.value = response.pixTarget;
|
||||
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);
|
||||
};
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const { tokenAddress, sellerAddress, amount } = await getUnreleasedLockById(
|
||||
BigInt(props.lockID)
|
||||
);
|
||||
|
||||
const participantId = await getSellerParticipantId(
|
||||
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);
|
||||
}
|
||||
onMounted(() => {
|
||||
window.addEventListener(
|
||||
"resize",
|
||||
() => (windowSize.value = window.innerWidth)
|
||||
);
|
||||
});
|
||||
|
||||
// Clean up interval on component unmount
|
||||
onUnmounted(() => {
|
||||
if (pollingInterval.value) {
|
||||
clearInterval(pollingInterval.value);
|
||||
pollingInterval.value = null;
|
||||
}
|
||||
window.removeEventListener(
|
||||
"resize",
|
||||
() => (windowSize.value = window.innerWidth)
|
||||
);
|
||||
});
|
||||
</script>
|
||||
|
||||
@ -139,17 +43,7 @@ onUnmounted(() => {
|
||||
<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>
|
||||
<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">
|
||||
@ -165,17 +59,13 @@ onUnmounted(() => {
|
||||
/>
|
||||
</div>
|
||||
<CustomButton
|
||||
:is-disabled="releaseSignature === ''"
|
||||
:text="
|
||||
releaseSignature ? 'Enviar para a rede' : 'Validando pagamento...'
|
||||
"
|
||||
@button-clicked="
|
||||
emit('pixValidated', { pixTarget, signature: releaseSignature })
|
||||
"
|
||||
:is-disabled="isPixValid == false"
|
||||
:text="'Enviar para a rede'"
|
||||
@button-clicked="emit('pixValidated', releaseSignature)"
|
||||
/>
|
||||
</div>
|
||||
<CustomModal
|
||||
v-if="showWarnModal"
|
||||
v-if="showWarnModal && windowSize <= 500"
|
||||
@close-modal="showWarnModal = false"
|
||||
:isRedirectModal="false"
|
||||
/>
|
||||
@ -232,7 +122,6 @@ h2 {
|
||||
}
|
||||
|
||||
input[type="number"] {
|
||||
appearance: textfield;
|
||||
-moz-appearance: textfield;
|
||||
}
|
||||
|
||||
|
||||
@ -38,7 +38,7 @@ const selectedDeposits = ref<ValidDeposit[]>();
|
||||
|
||||
import ChevronDown from "@/assets/chevronDown.svg";
|
||||
import { useOnboard } from "@web3-onboard/vue";
|
||||
import { getParticipantID } from "@/blockchain/events";
|
||||
import { getPixKey } from "@/blockchain/events";
|
||||
|
||||
// Emits
|
||||
const emit = defineEmits(["tokenBuy"]);
|
||||
@ -54,7 +54,7 @@ const emitConfirmButton = async (): Promise<void> => {
|
||||
(d) => d.network === Number(networkName.value)
|
||||
);
|
||||
if (!deposit) return;
|
||||
deposit.participantID = await getParticipantID(deposit.seller, deposit.token);
|
||||
deposit.pixKey = await getPixKey(deposit.seller, deposit.token);
|
||||
emit("tokenBuy", deposit, tokenValue.value);
|
||||
};
|
||||
|
||||
@ -90,8 +90,6 @@ const handleSelectedToken = (token: TokenEnum): void => {
|
||||
// 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,
|
||||
|
||||
@ -57,8 +57,6 @@ watch(connectedChain, (newVal: any) => {
|
||||
});
|
||||
|
||||
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(
|
||||
@ -69,7 +67,7 @@ const formatWalletAddress = (): string => {
|
||||
};
|
||||
|
||||
const disconnectUser = async (): Promise<void> => {
|
||||
user.setWalletAddress(null);
|
||||
user.setWalletAddress("");
|
||||
await disconnectWallet({ label: connectedWallet.value?.label || "" });
|
||||
closeMenu();
|
||||
};
|
||||
|
||||
35
src/components/TopBar/__tests__/TopBar.spec.ts
Normal file
35
src/components/TopBar/__tests__/TopBar.spec.ts
Normal file
@ -0,0 +1,35 @@
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import TopBar from "../TopBar.vue";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
|
||||
describe("TopBar.vue", () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
});
|
||||
|
||||
it("should render connect wallet button", () => {
|
||||
const wrapper = mount(TopBar);
|
||||
expect(wrapper.html()).toContain("Conectar carteira");
|
||||
});
|
||||
|
||||
it("should render button to change to seller view when in buyer screen", () => {
|
||||
const wrapper = mount(TopBar);
|
||||
expect(wrapper.html()).toContain("Quero vender");
|
||||
});
|
||||
|
||||
it("should render button to change to seller view when in buyer screen", () => {
|
||||
const user = useUser();
|
||||
user.setSellerView(true);
|
||||
const wrapper = mount(TopBar);
|
||||
expect(wrapper.html()).toContain("Quero comprar");
|
||||
});
|
||||
|
||||
it("should render the P2Pix logo correctly", () => {
|
||||
const wrapper = mount(TopBar);
|
||||
const img = wrapper.findAll(".logo");
|
||||
expect(img.length).toBe(2);
|
||||
});
|
||||
});
|
||||
@ -3,9 +3,8 @@ import { NetworkEnum, TokenEnum } from "../model/NetworkEnum";
|
||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||
import type { Participant } from "../utils/bbPay";
|
||||
import { NetworkById } from "@/model/Networks";
|
||||
import type { Address } from "viem"
|
||||
|
||||
const walletAddress = ref<Address | null>(null);
|
||||
const walletAddress = ref("");
|
||||
const balance = ref("");
|
||||
const networkId = ref(11155111);
|
||||
const networkName = ref(NetworkEnum.sepolia);
|
||||
@ -20,7 +19,7 @@ const sellerId = ref("");
|
||||
|
||||
export function useUser() {
|
||||
// Actions become regular functions
|
||||
const setWalletAddress = (address: Address | null) => {
|
||||
const setWalletAddress = (address: string) => {
|
||||
walletAddress.value = address;
|
||||
};
|
||||
|
||||
|
||||
@ -1,8 +0,0 @@
|
||||
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
|
||||
}
|
||||
@ -3,13 +3,13 @@ export enum NetworkEnum {
|
||||
rootstock = 31,
|
||||
}
|
||||
|
||||
export const getNetworkSubgraphURL = (network: NetworkEnum) => {
|
||||
const networkMap: Record<NetworkEnum, string> = {
|
||||
export const getNetworkSubgraphURL = (network: NetworkEnum | number) => {
|
||||
const networkMap: Record<number, string> = {
|
||||
[NetworkEnum.sepolia]: import.meta.env.VITE_SEPOLIA_SUBGRAPH_URL || "",
|
||||
[NetworkEnum.rootstock]: import.meta.env.VITE_RSK_SUBGRAPH_URL || "",
|
||||
};
|
||||
|
||||
return networkMap[network] || "";
|
||||
return networkMap[typeof network === "number" ? network : network] || "";
|
||||
};
|
||||
|
||||
export enum TokenEnum {
|
||||
|
||||
@ -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,8 +1,6 @@
|
||||
import { Address } from "viem";
|
||||
import type { Pix } from "./Pix";
|
||||
|
||||
export type UnreleasedLock = {
|
||||
lockID: bigint;
|
||||
sellerAddress: Address;
|
||||
tokenAddress: Address;
|
||||
amount: number;
|
||||
lockID: string;
|
||||
pix: Pix;
|
||||
};
|
||||
|
||||
@ -1,12 +1,11 @@
|
||||
import { NetworkEnum } from "./NetworkEnum";
|
||||
import type { Address } from "viem";
|
||||
|
||||
export type ValidDeposit = {
|
||||
token: Address;
|
||||
token: string;
|
||||
blockNumber: number;
|
||||
remaining: number;
|
||||
seller: Address;
|
||||
participantID: string;
|
||||
seller: string;
|
||||
pixKey: string;
|
||||
network: NetworkEnum;
|
||||
open?: boolean;
|
||||
};
|
||||
|
||||
@ -1,14 +1,11 @@
|
||||
import type { LockStatus } from "@/model/LockStatus"
|
||||
import type { Address } from "viem"
|
||||
|
||||
export type WalletTransaction = {
|
||||
token?: Address;
|
||||
token: string;
|
||||
blockNumber: number;
|
||||
amount: number;
|
||||
seller: string;
|
||||
buyer: string;
|
||||
event: string;
|
||||
lockStatus?: LockStatus;
|
||||
lockStatus: number;
|
||||
transactionHash: string;
|
||||
transactionID?: string;
|
||||
};
|
||||
|
||||
120
src/model/mock/EventMock.ts
Normal file
120
src/model/mock/EventMock.ts
Normal file
@ -0,0 +1,120 @@
|
||||
import { vi } from "vitest";
|
||||
|
||||
export const MockEvents = [
|
||||
{
|
||||
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(),
|
||||
},
|
||||
];
|
||||
45
src/model/mock/ValidDepositMock.ts
Normal file
45
src/model/mock/ValidDepositMock.ts
Normal file
@ -0,0 +1,45 @@
|
||||
import type { ValidDeposit } from "../ValidDeposit";
|
||||
import { NetworkEnum } from "@/model/NetworkEnum";
|
||||
|
||||
export const MockValidDeposits: ValidDeposit[] = [
|
||||
{
|
||||
blockNumber: 1,
|
||||
token: "1",
|
||||
remaining: 70,
|
||||
seller: "mockedSellerAddress",
|
||||
pixKey: "123456789",
|
||||
network: NetworkEnum.sepolia,
|
||||
},
|
||||
{
|
||||
blockNumber: 2,
|
||||
token: "2",
|
||||
remaining: 200,
|
||||
seller: "mockedSellerAddress",
|
||||
pixKey: "123456789",
|
||||
network: NetworkEnum.sepolia,
|
||||
},
|
||||
{
|
||||
blockNumber: 3,
|
||||
token: "3",
|
||||
remaining: 1250,
|
||||
seller: "mockedSellerAddress",
|
||||
pixKey: "123456789",
|
||||
network: NetworkEnum.sepolia,
|
||||
},
|
||||
{
|
||||
blockNumber: 4,
|
||||
token: "4",
|
||||
remaining: 4000,
|
||||
seller: "mockedSellerAddress",
|
||||
pixKey: "123456789",
|
||||
network: NetworkEnum.sepolia,
|
||||
},
|
||||
{
|
||||
blockNumber: 5,
|
||||
token: "5",
|
||||
remaining: 2000,
|
||||
seller: "mockedSellerAddress",
|
||||
pixKey: "123456789",
|
||||
network: NetworkEnum.sepolia,
|
||||
},
|
||||
];
|
||||
54
src/model/mock/WalletTransactionMock.ts
Normal file
54
src/model/mock/WalletTransactionMock.ts
Normal file
@ -0,0 +1,54 @@
|
||||
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",
|
||||
},
|
||||
];
|
||||
76
src/utils/QrCodePix.ts
Normal file
76
src/utils/QrCodePix.ts
Normal file
@ -0,0 +1,76 @@
|
||||
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 };
|
||||
24
src/utils/__tests__/debounce.spec.ts
Normal file
24
src/utils/__tests__/debounce.spec.ts
Normal file
@ -0,0 +1,24 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
12
src/utils/__tests__/decimalCount.spec.ts
Normal file
12
src/utils/__tests__/decimalCount.spec.ts
Normal file
@ -0,0 +1,12 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
25
src/utils/__tests__/networkLiquidity.spec.ts
Normal file
25
src/utils/__tests__/networkLiquidity.spec.ts
Normal file
@ -0,0 +1,25 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@ -1,3 +1,5 @@
|
||||
import { off } from "process";
|
||||
|
||||
export interface Participant {
|
||||
offer: string;
|
||||
chainID: number;
|
||||
@ -15,6 +17,7 @@ export interface ParticipantWithID extends Participant {
|
||||
|
||||
export interface Offer {
|
||||
amount: number;
|
||||
lockId: string;
|
||||
sellerId: string;
|
||||
}
|
||||
|
||||
@ -22,6 +25,7 @@ export interface Offer {
|
||||
// https://apoio.developers.bb.com.br/sandbox/spec/665797498bb48200130fc32c
|
||||
|
||||
export const createParticipant = async (participant: Participant) => {
|
||||
console.log("Creating participant", participant);
|
||||
const response = await fetch(`${import.meta.env.VITE_APP_API_URL}/register`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@ -37,14 +41,8 @@ export const createParticipant = async (participant: Participant) => {
|
||||
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;
|
||||
return { ...participant, id: data.id } as ParticipantWithID;
|
||||
};
|
||||
|
||||
export const createSolicitation = async (offer: Offer) => {
|
||||
@ -55,7 +53,7 @@ export const createSolicitation = async (offer: Offer) => {
|
||||
},
|
||||
body: JSON.stringify({
|
||||
amount: offer.amount,
|
||||
pixTarget: offer.sellerId.split("-").pop(),
|
||||
pixTarget: offer.sellerId,
|
||||
}),
|
||||
});
|
||||
return response.json();
|
||||
@ -66,10 +64,14 @@ export const getSolicitation = async (id: string) => {
|
||||
`${import.meta.env.VITE_APP_API_URL}/release/${id}`
|
||||
);
|
||||
|
||||
const obj: any = await response.json();
|
||||
const obj: any = response.json();
|
||||
|
||||
return {
|
||||
pixTarget: obj.pixTarget,
|
||||
signature: obj.signature,
|
||||
id: obj.numeroSolicitacao,
|
||||
lockId: obj.codigoConciliacaoSolicitacao,
|
||||
amount: obj.valorSolicitacao,
|
||||
qrcode: obj.pix.textoQrCode,
|
||||
status: obj.valorSomatorioPagamentosEfetivados >= obj.valorSolicitacao,
|
||||
signature: obj.assinatura,
|
||||
};
|
||||
};
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||
import type { Address } from "viem";
|
||||
|
||||
const verifyNetworkLiquidity = (
|
||||
tokenValue: number,
|
||||
walletAddress: Address,
|
||||
walletAddress: string,
|
||||
validDepositList: ValidDeposit[]
|
||||
): ValidDeposit[] => {
|
||||
const filteredDepositList = validDepositList
|
||||
|
||||
337
src/utils/smart_contract_files/MockToken.json
Normal file
337
src/utils/smart_contract_files/MockToken.json
Normal file
File diff suppressed because one or more lines are too long
1132
src/utils/smart_contract_files/P2PIX.json
Normal file
1132
src/utils/smart_contract_files/P2PIX.json
Normal file
File diff suppressed because one or more lines are too long
@ -24,6 +24,7 @@ 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>
|
||||
|
||||
|
||||
@ -12,7 +12,6 @@ import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||
import { getUnreleasedLockById } from "@/blockchain/events";
|
||||
import CustomAlert from "@/components/CustomAlert/CustomAlert.vue";
|
||||
import { getSolicitation } from "@/utils/bbPay";
|
||||
import type { Address } from "viem";
|
||||
|
||||
enum Step {
|
||||
Search,
|
||||
@ -26,8 +25,7 @@ user.setSellerView(false);
|
||||
// States
|
||||
const { loadingLock, walletAddress, networkName } = user;
|
||||
const flowStep = ref<Step>(Step.Search);
|
||||
const participantID = ref<string>();
|
||||
const sellerAddress = ref<Address>();
|
||||
const pixTarget = ref<string>();
|
||||
const tokenAmount = ref<number>();
|
||||
const lockID = ref<string>("");
|
||||
const loadingRelease = ref<boolean>(false);
|
||||
@ -39,7 +37,7 @@ const confirmBuyClick = async (
|
||||
selectedDeposit: ValidDeposit,
|
||||
tokenValue: number
|
||||
) => {
|
||||
participantID.value = selectedDeposit.participantID;
|
||||
pixTarget.value = selectedDeposit.pixKey;
|
||||
tokenAmount.value = tokenValue;
|
||||
|
||||
if (selectedDeposit) {
|
||||
@ -48,7 +46,7 @@ const confirmBuyClick = async (
|
||||
|
||||
await addLock(selectedDeposit.seller, selectedDeposit.token, tokenValue)
|
||||
.then((_lockID) => {
|
||||
lockID.value = String(_lockID);
|
||||
lockID.value = _lockID;
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log(err);
|
||||
@ -59,32 +57,28 @@ const confirmBuyClick = async (
|
||||
}
|
||||
};
|
||||
|
||||
const releaseTransaction = async ({
|
||||
pixTarget,
|
||||
signature,
|
||||
}: {
|
||||
pixTarget: string;
|
||||
signature: string;
|
||||
}) => {
|
||||
const releaseTransaction = async (lockId: string) => {
|
||||
flowStep.value = Step.List;
|
||||
showBuyAlert.value = true;
|
||||
loadingRelease.value = true;
|
||||
|
||||
const release = await releaseLock(BigInt(lockID.value), pixTarget, signature);
|
||||
await release.wait();
|
||||
const solicitation = await getSolicitation(lockId);
|
||||
|
||||
await updateWalletStatus();
|
||||
loadingRelease.value = false;
|
||||
if (solicitation.status) {
|
||||
const release = await releaseLock(solicitation);
|
||||
await release.wait();
|
||||
|
||||
await updateWalletStatus();
|
||||
loadingRelease.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const checkForUnreleasedLocks = async (): Promise<void> => {
|
||||
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;
|
||||
const walletLocks = await checkUnreleasedLock(walletAddress.value);
|
||||
if (walletLocks) {
|
||||
lockID.value = walletLocks.lockID;
|
||||
tokenAmount.value = walletLocks.pix.value;
|
||||
pixTarget.value = walletLocks.pix.pixKey;
|
||||
showModal.value = true;
|
||||
} else {
|
||||
flowStep.value = Step.Search;
|
||||
@ -93,11 +87,11 @@ const checkForUnreleasedLocks = async (): Promise<void> => {
|
||||
};
|
||||
|
||||
if (paramLockID) {
|
||||
const lockToRedirect = await getUnreleasedLockById(paramLockID);
|
||||
const lockToRedirect = await getUnreleasedLockById(paramLockID as string);
|
||||
if (lockToRedirect) {
|
||||
lockID.value = String(lockToRedirect.lockID);
|
||||
tokenAmount.value = lockToRedirect.amount;
|
||||
sellerAddress.value = lockToRedirect.sellerAddress;
|
||||
lockID.value = lockToRedirect.lockID;
|
||||
tokenAmount.value = lockToRedirect.pix.value;
|
||||
pixTarget.value = lockToRedirect.pix.pixKey;
|
||||
flowStep.value = Step.Buy;
|
||||
} else {
|
||||
flowStep.value = Step.Search;
|
||||
@ -140,7 +134,8 @@ onMounted(async () => {
|
||||
/>
|
||||
<div v-if="flowStep == Step.Buy">
|
||||
<QrCodeComponent
|
||||
:lockID="lockID"
|
||||
:sellerId="String(pixTarget)"
|
||||
:amount="tokenAmount"
|
||||
@pix-validated="releaseTransaction"
|
||||
v-if="!loadingLock"
|
||||
/>
|
||||
|
||||
@ -48,15 +48,19 @@ const callWithdraw = async (amount: string) => {
|
||||
const getWalletTransactions = async () => {
|
||||
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;
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
"extends": "@vue/tsconfig/tsconfig.node.json",
|
||||
"include": [
|
||||
"vite.config.*",
|
||||
"vitest.config.*",
|
||||
"cypress.config.*",
|
||||
"playwright.config.*"
|
||||
],
|
||||
|
||||
@ -8,13 +8,13 @@
|
||||
],
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"strict": true,
|
||||
"paths": {
|
||||
"@/*": [
|
||||
"./src/*"
|
||||
]
|
||||
},
|
||||
"types": [
|
||||
"jest",
|
||||
"node"
|
||||
],
|
||||
"resolveJsonModule": true,
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { fileURLToPath, URL } from "node:url";
|
||||
|
||||
import { defineConfig } from "vite";
|
||||
import { defineConfig } from "vitest/config";
|
||||
import vue from "@vitejs/plugin-vue";
|
||||
import vueJsx from "@vitejs/plugin-vue-jsx";
|
||||
import svgLoader from "vite-svg-loader";
|
||||
@ -21,6 +21,17 @@ export default defineConfig({
|
||||
},
|
||||
},
|
||||
},
|
||||
test: {
|
||||
globals: true,
|
||||
environment: "jsdom",
|
||||
coverage: {
|
||||
provider: "c8",
|
||||
all: true,
|
||||
src: ["./src"],
|
||||
exclude: ["model/**", "**/__tests__/**"],
|
||||
reporter: ["text", "lcov", "html"],
|
||||
},
|
||||
},
|
||||
plugins: [vue(), vueJsx(), svgLoader()],
|
||||
resolve: {
|
||||
alias: {
|
||||
|
||||
@ -1,11 +0,0 @@
|
||||
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',
|
||||
}),],
|
||||
})
|
||||
Loading…
x
Reference in New Issue
Block a user