7 Commits

Author SHA1 Message Date
Filipe Soccol
c1542707c2 Merge remote-tracking branch 'origin/type-check' into buy-refactor 2025-06-30 08:58:01 -03:00
hueso
dd351acb2e Stronger typings💪 2025-06-29 18:19:30 -03:00
Filipe Soccol
2370051243 Update all code to be able to release. Still having issues on Release transaction. 2025-06-28 12:16:36 -03:00
Filipe Soccol
ed5d3b5726 Fixed spinner in offers. 2025-06-27 16:47:06 -03:00
Filipe Soccol
2e246f7560 Removed all tests and test libraries. 2025-06-27 16:42:25 -03:00
Filipe Soccol
81c8b04c7a Refactored variable names to be concise. 2025-06-27 16:34:29 -03:00
Filipe Soccol
cf61f5ecfd Fix issues with locking and solicitation. 2025-06-27 15:59:34 -03:00
47 changed files with 3429 additions and 4302 deletions

View File

@@ -115,4 +115,6 @@ curl -X POST \
-d '{"query": "{ depositAddeds { id seller token amount } }"}' \ -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/sepolia
https://api.studio.thegraph.com/query/113713/p-2-pix/1 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" }'

View File

@@ -5,9 +5,7 @@
"start": "vite --host=0.0.0.0 --port 3000", "start": "vite --host=0.0.0.0 --port 3000",
"build": "run-p type-check build-only", "build": "run-p type-check build-only",
"preview": "vite preview", "preview": "vite preview",
"test": "vitest",
"serve": "vue-cli-service serve", "serve": "vue-cli-service serve",
"coverage": "vitest run --coverage",
"build-only": "vite build", "build-only": "vite build",
"type-check": "vue-tsc --skipLibCheck --noEmit", "type-check": "vue-tsc --skipLibCheck --noEmit",
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --ignore-path .gitignore --fix", "lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --ignore-path .gitignore --fix",
@@ -22,8 +20,6 @@
"@web3-onboard/vue": "^2.9.0", "@web3-onboard/vue": "^2.9.0",
"alchemy-sdk": "^2.3.0", "alchemy-sdk": "^2.3.0",
"axios": "^1.2.1", "axios": "^1.2.1",
"crc": "^3.8.0",
"ethers": "^6.13.4",
"marked": "^4.2.12", "marked": "^4.2.12",
"qrcode": "^1.5.1", "qrcode": "^1.5.1",
"viem": "^2.31.3", "viem": "^2.31.3",
@@ -37,29 +33,25 @@
"@babel/preset-typescript": "^7.18.6", "@babel/preset-typescript": "^7.18.6",
"@rushstack/eslint-patch": "^1.1.4", "@rushstack/eslint-patch": "^1.1.4",
"@types/crc": "^3.8.0", "@types/crc": "^3.8.0",
"@types/jest": "^27.0.0",
"@types/marked": "^4.0.8", "@types/marked": "^4.0.8",
"@types/node": "^16.11.68", "@types/node": "^16.11.68",
"@types/qrcode": "^1.5.0", "@types/qrcode": "^1.5.0",
"@types/vue-markdown": "^2.2.1", "@types/vue-markdown": "^2.2.1",
"@vitejs/plugin-vue": "^3.1.2", "@vitejs/plugin-vue": "^3.1.2",
"@vitejs/plugin-vue-jsx": "^2.0.1", "@vitejs/plugin-vue-jsx": "^2.0.1",
"@vitest/coverage-c8": "^0.28.2",
"@vue/eslint-config-prettier": "^7.0.0", "@vue/eslint-config-prettier": "^7.0.0",
"@vue/eslint-config-typescript": "^11.0.0", "@vue/eslint-config-typescript": "^11.0.0",
"@vue/test-utils": "^2.2.7",
"@vue/tsconfig": "^0.1.3", "@vue/tsconfig": "^0.1.3",
"@wagmi/cli": "^2.3.1",
"autoprefixer": "^10.4.12", "autoprefixer": "^10.4.12",
"eslint": "^8.22.0", "eslint": "^8.22.0",
"eslint-plugin-vue": "^9.3.0", "eslint-plugin-vue": "^9.3.0",
"jsdom": "^21.1.0",
"npm-run-all": "^4.1.5", "npm-run-all": "^4.1.5",
"postcss": "^8.4.18", "postcss": "^8.4.18",
"prettier": "^2.7.1", "prettier": "^2.7.1",
"tailwindcss": "^3.2.1", "tailwindcss": "^3.2.1",
"typescript": "~5.8.2", "typescript": "~5.8.2",
"vite": "^3.1.8", "vite": "^3.1.8",
"vitest": "^0.28.1",
"vue-tsc": "^2.2.8" "vue-tsc": "^2.2.8"
} }
} }

View File

@@ -1,98 +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 { 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);
});
});

2266
src/blockchain/abi.ts Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +1,9 @@
import { useUser } from "@/composables/useUser"; import { useUser } from "@/composables/useUser";
import { NetworkEnum, TokenEnum } from "@/model/NetworkEnum"; import { NetworkEnum, TokenEnum } from "@/model/NetworkEnum";
import { createPublicClient, http } from "viem"; import { createPublicClient, http, type Address } from "viem";
import { sepolia, rootstock } from "viem/chains"; import { sepolia, rootstock } from "viem/chains";
const Tokens: { [key in NetworkEnum]: { [key in TokenEnum]: string } } = { const Tokens: { [key in NetworkEnum]: { [key in TokenEnum]: Address } } = {
[NetworkEnum.sepolia]: { [NetworkEnum.sepolia]: {
BRZ: "0x3eBE67A2C7bdB2081CBd34ba3281E90377462289", BRZ: "0x3eBE67A2C7bdB2081CBd34ba3281E90377462289",
// BRX: "0x3eBE67A2C7bdB2081CBd34ba3281E90377462289", // BRX: "0x3eBE67A2C7bdB2081CBd34ba3281E90377462289",
@@ -14,7 +14,7 @@ const Tokens: { [key in NetworkEnum]: { [key in TokenEnum]: string } } = {
}, },
}; };
export const getTokenByAddress = (address: string) => { export const getTokenByAddress = (address: Address) => {
const user = useUser(); const user = useUser();
const networksTokens = Tokens[user.networkName.value]; const networksTokens = Tokens[user.networkName.value];
for (const [token, tokenAddress] of Object.entries(networksTokens)) { for (const [token, tokenAddress] of Object.entries(networksTokens)) {
@@ -28,19 +28,23 @@ export const getTokenByAddress = (address: string) => {
export const getTokenAddress = ( export const getTokenAddress = (
token: TokenEnum, token: TokenEnum,
network?: NetworkEnum network?: NetworkEnum
): string => { ): Address => {
const user = useUser(); const user = useUser();
return Tokens[network ? network : user.networkName.value][token]; return Tokens[network ? network : user.networkName.value][
token
];
}; };
export const getP2PixAddress = (network?: NetworkEnum): string => { export const getP2PixAddress = (network?: NetworkEnum): Address => {
const user = useUser(); const user = useUser();
const possibleP2PixAddresses: { [key in NetworkEnum]: string } = { const possibleP2PixAddresses: { [key in NetworkEnum]: Address } = {
[NetworkEnum.sepolia]: "0xb7cD135F5eFD9760981e02E2a898790b688939fe", [NetworkEnum.sepolia]: "0xb7cD135F5eFD9760981e02E2a898790b688939fe",
[NetworkEnum.rootstock]: "0x98ba35eb14b38D6Aa709338283af3e922476dE34", [NetworkEnum.rootstock]: "0x98ba35eb14b38D6Aa709338283af3e922476dE34",
}; };
return possibleP2PixAddresses[network ? network : user.networkName.value]; return possibleP2PixAddresses[
network ? network : user.networkName.value
];
}; };
export const getProviderUrl = (network?: NetworkEnum): string => { export const getProviderUrl = (network?: NetworkEnum): string => {
@@ -54,7 +58,6 @@ export const getProviderUrl = (network?: NetworkEnum): string => {
}; };
export const getProviderByNetwork = (network: NetworkEnum) => { export const getProviderByNetwork = (network: NetworkEnum) => {
console.log("network", network);
const chain = network === NetworkEnum.sepolia ? sepolia : rootstock; const chain = network === NetworkEnum.sepolia ? sepolia : rootstock;
return createPublicClient({ return createPublicClient({
chain, chain,

View File

@@ -1,34 +1,55 @@
import { getContract } from "./provider"; import { getContract } from "./provider";
import { getTokenAddress } from "./addresses"; import { getTokenAddress } from "./addresses";
import { parseEther } from "viem"; import {
bytesToHex,
encodeAbiParameters,
keccak256,
parseAbiParameters,
parseEther,
stringToBytes,
stringToHex,
toBytes,
type Address,
} from "viem";
import type { TokenEnum } from "@/model/NetworkEnum"; import type { TokenEnum } from "@/model/NetworkEnum";
export const addLock = async ( export const addLock = async (
sellerAddress: string, sellerAddress: Address,
tokenAddress: string, tokenAddress: Address,
amount: number amount: number
): Promise<string> => { ): Promise<bigint> => {
const { address, abi, wallet, client } = await getContract(); const { address, abi, wallet, client, account } = await getContract();
const parsedAmount = parseEther(amount.toString()); const parsedAmount = parseEther(amount.toString());
const { request } = await client.simulateContract({ if (!wallet) {
throw new Error("Wallet not connected");
}
const { result, request } = await client.simulateContract({
address, address,
abi, abi,
functionName: "lock", functionName: "lock",
args: [sellerAddress, tokenAddress, parsedAmount, [], []], args: [sellerAddress, tokenAddress, parsedAmount, [], []],
account,
}); });
console.log(wallet);
const hash = await wallet.writeContract(request); const hash = await wallet.writeContract(request);
const receipt = await client.waitForTransactionReceipt({ hash }); const receipt = await client.waitForTransactionReceipt({ hash });
return receipt.status ? receipt.logs[0].topics[2] : ""; if (!receipt.status)
throw new Error("Transaction failed: " + receipt.transactionHash);
return result;
}; };
export const withdrawDeposit = async ( export const withdrawDeposit = async (
amount: string, amount: string,
token: TokenEnum token: TokenEnum
): Promise<boolean> => { ): Promise<boolean> => {
const { address, abi, wallet, client } = await getContract(); const { address, abi, wallet, client, account } = await getContract();
if (!wallet) {
throw new Error("Wallet not connected");
}
const tokenAddress = getTokenAddress(token); const tokenAddress = getTokenAddress(token);
@@ -37,22 +58,36 @@ export const withdrawDeposit = async (
abi, abi,
functionName: "withdraw", functionName: "withdraw",
args: [tokenAddress, parseEther(amount), []], args: [tokenAddress, parseEther(amount), []],
account
}); });
const hash = await wallet.writeContract(request); const hash = await wallet.writeContract(request);
const receipt = await client.waitForTransactionReceipt({ hash }); const receipt = await client.waitForTransactionReceipt({ hash });
return receipt.status; return receipt.status === "success";
}; };
export const releaseLock = async (solicitation: any): Promise<any> => { export const releaseLock = async (
const { address, abi, wallet, client } = await getContract(); 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 }) );
const { request } = await client.simulateContract({ const { request } = await client.simulateContract({
address, address,
abi, abi,
functionName: "release", functionName: "release",
args: [solicitation.lockId, solicitation.e2eId], args: [BigInt(lockID), pixTimestamp, stringToHex(signature)],
account
}); });
const hash = await wallet.writeContract(request); const hash = await wallet.writeContract(request);

View File

@@ -1,13 +1,14 @@
import { useUser } from "@/composables/useUser"; import { useUser } from "@/composables/useUser";
import { formatEther, toHex, type PublicClient } from "viem"; import { formatEther, toHex, stringToHex } from "viem";
import type { PublicClient, Address } from "viem";
import p2pix from "@/utils/smart_contract_files/P2PIX.json";
import { getContract } from "./provider"; import { getContract } from "./provider";
import type { ValidDeposit } from "@/model/ValidDeposit";
import { getP2PixAddress, getTokenAddress } from "./addresses"; import { getP2PixAddress, getTokenAddress } from "./addresses";
import { getNetworkSubgraphURL, NetworkEnum } from "@/model/NetworkEnum"; import { p2PixAbi } from "./abi"
import type { ValidDeposit } from "@/model/ValidDeposit";
import { getNetworkSubgraphURL, NetworkEnum, TokenEnum } from "@/model/NetworkEnum";
import type { UnreleasedLock } from "@/model/UnreleasedLock"; import type { UnreleasedLock } from "@/model/UnreleasedLock";
import type { Pix } from "@/model/Pix"; import type { LockStatus } from "@/model/LockStatus"
const getNetworksLiquidity = async (): Promise<void> => { const getNetworksLiquidity = async (): Promise<void> => {
const user = useUser(); const user = useUser();
@@ -30,10 +31,13 @@ const getNetworksLiquidity = async (): Promise<void> => {
user.setLoadingNetworkLiquidity(false); user.setLoadingNetworkLiquidity(false);
}; };
const getPixKey = async (seller: string, token: string): Promise<string> => { const getParticipantID = async (
seller: string,
token: string
): Promise<string> => {
const { address, abi, client } = await getContract(); const { address, abi, client } = await getContract();
const pixKeyHex = await client.readContract({ const participantIDHex = await client.readContract({
address, address,
abi, abi,
functionName: "getPixTarget", functionName: "getPixTarget",
@@ -42,13 +46,14 @@ const getPixKey = async (seller: string, token: string): Promise<string> => {
// Remove '0x' prefix and convert hex to UTF-8 string // Remove '0x' prefix and convert hex to UTF-8 string
const hexString = const hexString =
typeof pixKeyHex === "string" ? pixKeyHex : toHex(pixKeyHex); typeof participantIDHex === "string"
if (!hexString) throw new Error("PixKey not found"); ? participantIDHex
: toHex(participantIDHex as bigint);
if (!hexString) throw new Error("Participant ID not found");
const bytes = new Uint8Array( const bytes = new Uint8Array(
// @ts-ignore
hexString hexString
.slice(2) .slice(2)
.match(/.{1,2}/g) .match(/.{1,2}/g)!
.map((byte: string) => parseInt(byte, 16)) .map((byte: string) => parseInt(byte, 16))
); );
// Remove null bytes from the end of the string // Remove null bytes from the end of the string
@@ -56,17 +61,17 @@ const getPixKey = async (seller: string, token: string): Promise<string> => {
}; };
const getValidDeposits = async ( const getValidDeposits = async (
token: string, token: Address,
network: NetworkEnum, network: NetworkEnum,
contractInfo?: { client: any; address: string } contractInfo?: { client: PublicClient; address: Address }
): Promise<ValidDeposit[]> => { ): Promise<ValidDeposit[]> => {
let client: PublicClient, address, abi; let client: PublicClient, abi;
if (contractInfo) { if (contractInfo) {
({ client, address } = contractInfo); ({ client } = contractInfo);
abi = p2pix.abi; abi = p2PixAbi;
} else { } else {
({ address, abi, client } = await getContract(true)); ({ abi, client } = await getContract(true));
} }
// TODO: Remove this once we have a subgraph for rootstock // TODO: Remove this once we have a subgraph for rootstock
@@ -97,11 +102,11 @@ const getValidDeposits = async (
const depositData = await depositLogs.json(); const depositData = await depositLogs.json();
const depositAddeds = depositData.data.depositAddeds; const depositAddeds = depositData.data.depositAddeds;
const uniqueSellers = depositAddeds.reduce( const uniqueSellers = depositAddeds.reduce(
(acc: Record<string, boolean>, deposit: any) => { (acc: Record<Address, boolean>, deposit: any) => {
acc[deposit.seller] = true; acc[deposit.seller] = true;
return acc; return acc;
}, },
{} as Record<string, boolean> {} as Record<Address, boolean>
); );
if (!contractInfo) { if (!contractInfo) {
@@ -111,7 +116,7 @@ const getValidDeposits = async (
const depositList: { [key: string]: ValidDeposit } = {}; const depositList: { [key: string]: ValidDeposit } = {};
const sellersList = Object.keys(uniqueSellers); const sellersList = Object.keys(uniqueSellers) as Address[];
// Use multicall to batch all getBalance requests // Use multicall to batch all getBalance requests
const balanceCalls = sellersList.map((seller) => ({ const balanceCalls = sellersList.map((seller) => ({
address: getP2PixAddress(network), address: getP2PixAddress(network),
@@ -130,12 +135,12 @@ const getValidDeposits = async (
if (!mappedBalance.error && mappedBalance.result) { if (!mappedBalance.error && mappedBalance.result) {
const validDeposit: ValidDeposit = { const validDeposit: ValidDeposit = {
token: token, token,
blockNumber: 0, blockNumber: 0,
remaining: Number(formatEther(mappedBalance.result as bigint)), remaining: Number(formatEther(mappedBalance.result as bigint)),
seller: seller, seller,
network, network,
pixKey: "", participantID: "",
}; };
depositList[seller + token] = validDeposit; depositList[seller + token] = validDeposit;
} }
@@ -144,28 +149,22 @@ const getValidDeposits = async (
}; };
const getUnreleasedLockById = async ( const getUnreleasedLockById = async (
lockID: string lockID: bigint
): Promise<UnreleasedLock> => { ): Promise<UnreleasedLock> => {
const { address, abi, client } = await getContract(); const { address, abi, client } = await getContract();
const pixData: Pix = {
pixKey: "",
};
const lock = await client.readContract({ const [ , , , amount, token, seller ] = await client.readContract({
address, address,
abi, abi,
functionName: "mapLocks", functionName: "mapLocks",
args: [BigInt(lockID)], args: [lockID],
}); });
const pixTarget = lock.pixTarget;
const amount = formatEther(lock.amount);
pixData.pixKey = pixTarget;
pixData.value = Number(amount);
return { return {
lockID: lockID, lockID,
pix: pixData, amount: Number(formatEther(amount)),
tokenAddress: token,
sellerAddress: seller,
}; };
}; };
@@ -173,5 +172,5 @@ export {
getValidDeposits, getValidDeposits,
getNetworksLiquidity, getNetworksLiquidity,
getUnreleasedLockById, getUnreleasedLockById,
getPixKey, getParticipantID,
}; };

View File

@@ -1,4 +1,4 @@
import p2pix from "@/utils/smart_contract_files/P2PIX.json"; import { p2PixAbi } from "./abi";
import { updateWalletStatus } from "./wallet"; import { updateWalletStatus } from "./wallet";
import { getProviderUrl, getP2PixAddress } from "./addresses"; import { getProviderUrl, getP2PixAddress } from "./addresses";
import { import {
@@ -12,11 +12,9 @@ import {
import { sepolia, rootstock } from "viem/chains"; import { sepolia, rootstock } from "viem/chains";
import { useUser } from "@/composables/useUser"; import { useUser } from "@/composables/useUser";
let publicClient: PublicClient | null = null;
let walletClient: WalletClient | null = null; let walletClient: WalletClient | null = null;
const getPublicClient: PublicClient | null = (onlyRpcProvider = false) => { const getPublicClient = (): PublicClient => {
if (onlyRpcProvider) {
const user = useUser(); const user = useUser();
const rpcUrl = getProviderUrl(); const rpcUrl = getProviderUrl();
return createPublicClient({ return createPublicClient({
@@ -24,36 +22,32 @@ const getPublicClient: PublicClient | null = (onlyRpcProvider = false) => {
Number(user.networkName.value) === sepolia.id ? sepolia : rootstock, Number(user.networkName.value) === sepolia.id ? sepolia : rootstock,
transport: http(rpcUrl), transport: http(rpcUrl),
}); });
}
return publicClient;
}; };
const getWalletClient: WalletClient | null = () => { const getWalletClient = (): WalletClient | null => {
return walletClient; return walletClient;
}; };
const getContract = async (onlyRpcProvider = false) => { const getContract = async (onlyRpcProvider = false) => {
const client = getPublicClient(onlyRpcProvider); const client = getPublicClient();
const address = getP2PixAddress(); const address = getP2PixAddress();
const abi = p2pix.abi; const abi = p2PixAbi;
const wallet = getWalletClient(); const wallet = onlyRpcProvider ? null : getWalletClient();
const [account] = wallet ? await wallet.getAddresses() : [""]; if (!client) {
throw new Error("Public client not initialized");
}
const [account] = wallet ? await wallet.getAddresses() : [null];
return { address, abi, client, wallet, account }; return { address, abi, client, wallet, account };
}; };
const connectProvider = async (p: any): Promise<void> => { const connectProvider = async (p: any): Promise<void> => {
console.log("Connecting to wallet provider...");
const user = useUser(); const user = useUser();
const chain = const chain =
Number(user.networkName.value) === sepolia.id ? sepolia : rootstock; Number(user.networkName.value) === sepolia.id ? sepolia : rootstock;
publicClient = createPublicClient({
chain,
transport: custom(p),
});
const [account] = await p!.request({ method: "eth_requestAccounts" }); const [account] = await p!.request({ method: "eth_requestAccounts" });
walletClient = createWalletClient({ walletClient = createWalletClient({

View File

@@ -1,8 +1,9 @@
import { getContract, getPublicClient, getWalletClient } from "./provider"; import { getContract, getPublicClient, getWalletClient } from "./provider";
import { getTokenAddress, getP2PixAddress } from "./addresses"; import { getTokenAddress, getP2PixAddress } from "./addresses";
import { parseEther, toHex } from "viem"; import { parseEther, toHex } from "viem";
import { sepolia, rootstock } from "viem/chains";
import mockToken from "../utils/smart_contract_files/MockToken.json"; import { mockTokenAbi } from "./abi";
import { useUser } from "@/composables/useUser"; import { useUser } from "@/composables/useUser";
import { createParticipant } from "@/utils/bbPay"; import { createParticipant } from "@/utils/bbPay";
import type { Participant } from "@/utils/bbPay"; import type { Participant } from "@/utils/bbPay";
@@ -25,19 +26,21 @@ const approveTokens = async (participant: Participant): Promise<any> => {
// Check if the token is already approved // Check if the token is already approved
const allowance = await publicClient.readContract({ const allowance = await publicClient.readContract({
address: tokenAddress, address: tokenAddress,
abi: mockToken.abi, abi: mockTokenAbi,
functionName: "allowance", functionName: "allowance",
args: [account, getP2PixAddress()], args: [account, getP2PixAddress()],
}); });
if (allowance < parseEther(participant.offer.toString())) { if ( allowance < parseEther(participant.offer.toString()) ) {
// Approve tokens // Approve tokens
const chain = user.networkId.value === sepolia.id ? sepolia : rootstock;
const hash = await walletClient.writeContract({ const hash = await walletClient.writeContract({
address: tokenAddress, address: tokenAddress,
abi: mockToken.abi, abi: mockTokenAbi,
functionName: "approve", functionName: "approve",
args: [getP2PixAddress(), parseEther(participant.offer.toString())], args: [getP2PixAddress(), parseEther(participant.offer.toString())],
account, account,
chain,
}); });
await publicClient.waitForTransactionReceipt({ hash }); await publicClient.waitForTransactionReceipt({ hash });
@@ -59,19 +62,23 @@ const addDeposit = async (): Promise<any> => {
const sellerId = await createParticipant(user.seller.value); const sellerId = await createParticipant(user.seller.value);
user.setSellerId(sellerId.id); 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({ const hash = await walletClient.writeContract({
address, address,
abi, abi,
functionName: "deposit", functionName: "deposit",
args: [ args: [
user.networkId + "-" + sellerId.id, user.networkId.value + "-" + sellerId.id,
toHex("", { size: 32 }), toHex("", { size: 32 }),
getTokenAddress(user.selectedToken.value), getTokenAddress(user.selectedToken.value),
parseEther(user.seller.value.offer.toString()), parseEther(user.seller.value.offer.toString()),
true, true,
], ],
account, account,
chain,
}); });
const receipt = await client.waitForTransactionReceipt({ hash }); const receipt = await client.waitForTransactionReceipt({ hash });

View File

@@ -1,17 +1,15 @@
import { decodeEventLog, formatEther, type Log } from "viem"; import { formatEther, hexToString, type Address } from "viem";
import { useUser } from "@/composables/useUser"; import { useUser } from "@/composables/useUser";
import { getPublicClient, getWalletClient, getContract } from "./provider"; import { getPublicClient, getWalletClient, getContract } from "./provider";
import { getTokenAddress } from "./addresses"; import { getTokenAddress } from "./addresses";
import p2pix from "@/utils/smart_contract_files/P2PIX.json"; import { getValidDeposits, getUnreleasedLockById } from "./events";
import { getValidDeposits } from "./events";
import type { ValidDeposit } from "@/model/ValidDeposit"; import type { ValidDeposit } from "@/model/ValidDeposit";
import type { WalletTransaction } from "@/model/WalletTransaction"; import type { WalletTransaction } from "@/model/WalletTransaction";
import type { UnreleasedLock } from "@/model/UnreleasedLock"; import type { UnreleasedLock } from "@/model/UnreleasedLock";
import type { Pix } from "@/model/Pix"; import { LockStatus } from "@/model/LockStatus";
import { getNetworkSubgraphURL } from "@/model/NetworkEnum"; import { getNetworkSubgraphURL } from "@/model/NetworkEnum";
export const updateWalletStatus = async (): Promise<void> => { export const updateWalletStatus = async (): Promise<void> => {
@@ -34,7 +32,7 @@ export const updateWalletStatus = async (): Promise<void> => {
}; };
export const listValidDepositTransactionsByWalletAddress = async ( export const listValidDepositTransactionsByWalletAddress = async (
walletAddress: string walletAddress: Address
): Promise<ValidDeposit[]> => { ): Promise<ValidDeposit[]> => {
const user = useUser(); const user = useUser();
const walletDeposits = await getValidDeposits( const walletDeposits = await getValidDeposits(
@@ -52,61 +50,19 @@ export const listValidDepositTransactionsByWalletAddress = async (
return []; return [];
}; };
const getLockStatus = async (id: bigint): Promise<number> => { const getLockStatus = async (id: bigint): Promise<LockStatus> => {
const { address, abi, client } = await getContract(); const { address, abi, client } = await getContract();
const result = await client.readContract({ const [ sortedIDs , status ] = await client.readContract({
address, address,
abi, abi,
functionName: "getLocksStatus", functionName: "getLocksStatus",
args: [[id]], args: [[id]],
}); });
return result[1][0]; return status[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 ( export const listAllTransactionByWalletAddress = async (
walletAddress: string walletAddress: Address
): Promise<WalletTransaction[]> => { ): Promise<WalletTransaction[]> => {
const user = useUser(); const user = useUser();
@@ -118,6 +74,7 @@ export const listAllTransactionByWalletAddress = async (
query: ` query: `
{ {
depositAddeds(where: {seller: "${walletAddress.toLowerCase()}"}) { depositAddeds(where: {seller: "${walletAddress.toLowerCase()}"}) {
id
seller seller
token token
amount amount
@@ -129,7 +86,6 @@ export const listAllTransactionByWalletAddress = async (
buyer buyer
lockID lockID
seller seller
token
amount amount
blockTimestamp blockTimestamp
blockNumber blockNumber
@@ -138,7 +94,6 @@ export const listAllTransactionByWalletAddress = async (
lockReleaseds(where: {buyer: "${walletAddress.toLowerCase()}"}) { lockReleaseds(where: {buyer: "${walletAddress.toLowerCase()}"}) {
buyer buyer
lockId lockId
e2eId
blockTimestamp blockTimestamp
blockNumber blockNumber
transactionHash transactionHash
@@ -155,7 +110,6 @@ export const listAllTransactionByWalletAddress = async (
`, `,
}; };
console.log("Fetching transactions from subgraph");
const response = await fetch(getNetworkSubgraphURL(network), { const response = await fetch(getNetworkSubgraphURL(network), {
method: "POST", method: "POST",
headers: { headers: {
@@ -165,14 +119,11 @@ export const listAllTransactionByWalletAddress = async (
}); });
const data = await response.json(); const data = await response.json();
console.log("Subgraph data fetched:", data);
// Convert all transactions to common WalletTransaction format // Convert all transactions to common WalletTransaction format
const transactions: WalletTransaction[] = []; const transactions: WalletTransaction[] = [];
// Process deposit added events // Process deposit added events
if (data.data?.depositAddeds) { if (data.data?.depositAddeds) {
console.log("Processing deposit events");
for (const deposit of data.data.depositAddeds) { for (const deposit of data.data.depositAddeds) {
transactions.push({ transactions.push({
token: deposit.token, token: deposit.token,
@@ -181,7 +132,7 @@ export const listAllTransactionByWalletAddress = async (
seller: deposit.seller, seller: deposit.seller,
buyer: "", buyer: "",
event: "DepositAdded", event: "DepositAdded",
lockStatus: -1, lockStatus: undefined,
transactionHash: deposit.transactionHash, transactionHash: deposit.transactionHash,
}); });
} }
@@ -189,7 +140,6 @@ export const listAllTransactionByWalletAddress = async (
// Process lock added events // Process lock added events
if (data.data?.lockAddeds) { if (data.data?.lockAddeds) {
console.log("Processing lock events");
for (const lock of data.data.lockAddeds) { for (const lock of data.data.lockAddeds) {
// Get lock status from the contract // Get lock status from the contract
const lockStatus = await getLockStatus(BigInt(lock.lockID)); const lockStatus = await getLockStatus(BigInt(lock.lockID));
@@ -210,16 +160,15 @@ export const listAllTransactionByWalletAddress = async (
// Process lock released events // Process lock released events
if (data.data?.lockReleaseds) { if (data.data?.lockReleaseds) {
console.log("Processing release events");
for (const release of data.data.lockReleaseds) { for (const release of data.data.lockReleaseds) {
transactions.push({ transactions.push({
token: "", // Subgraph doesn't provide token in this event, we could enhance this later token: undefined, // Subgraph doesn't provide token in this event, we could enhance this later
blockNumber: parseInt(release.blockNumber), blockNumber: parseInt(release.blockNumber),
amount: -1, // Amount not available in this event amount: -1, // Amount not available in this event
seller: "", seller: "",
buyer: release.buyer, buyer: release.buyer,
event: "LockReleased", event: "LockReleased",
lockStatus: -1, lockStatus: undefined,
transactionHash: release.transactionHash, transactionHash: release.transactionHash,
transactionID: release.lockId.toString(), transactionID: release.lockId.toString(),
}); });
@@ -228,7 +177,6 @@ export const listAllTransactionByWalletAddress = async (
// Process deposit withdrawn events // Process deposit withdrawn events
if (data.data?.depositWithdrawns) { if (data.data?.depositWithdrawns) {
console.log("Processing withdrawal events");
for (const withdrawal of data.data.depositWithdrawns) { for (const withdrawal of data.data.depositWithdrawns) {
transactions.push({ transactions.push({
token: withdrawal.token, token: withdrawal.token,
@@ -237,7 +185,7 @@ export const listAllTransactionByWalletAddress = async (
seller: withdrawal.seller, seller: withdrawal.seller,
buyer: "", buyer: "",
event: "DepositWithdrawn", event: "DepositWithdrawn",
lockStatus: -1, lockStatus: undefined,
transactionHash: withdrawal.transactionHash, transactionHash: withdrawal.transactionHash,
}); });
} }
@@ -249,7 +197,7 @@ export const listAllTransactionByWalletAddress = async (
// get wallet's release transactions // get wallet's release transactions
export const listReleaseTransactionByWalletAddress = async ( export const listReleaseTransactionByWalletAddress = async (
walletAddress: string walletAddress: Address
) => { ) => {
const user = useUser(); const user = useUser();
const network = user.networkName.value; const network = user.networkName.value;
@@ -313,7 +261,7 @@ export const listReleaseTransactionByWalletAddress = async (
.filter((decoded: any) => decoded !== null); .filter((decoded: any) => decoded !== null);
}; };
const listLockTransactionByWalletAddress = async (walletAddress: string) => { const listLockTransactionByWalletAddress = async (walletAddress: Address) => {
const user = useUser(); const user = useUser();
const network = user.networkName.value; const network = user.networkName.value;
@@ -325,7 +273,6 @@ const listLockTransactionByWalletAddress = async (walletAddress: string) => {
buyer buyer
lockID lockID
seller seller
token
amount amount
blockTimestamp blockTimestamp
blockNumber blockNumber
@@ -383,10 +330,9 @@ const listLockTransactionByWalletAddress = async (walletAddress: string) => {
} }
}; };
const listLockTransactionBySellerAddress = async (sellerAddress: string) => { const listLockTransactionBySellerAddress = async (sellerAddress: Address) => {
const user = useUser(); const user = useUser();
const network = user.networkName.value; const network = user.networkName.value;
console.log("Will get locks as seller", sellerAddress);
// Query subgraph for lock added transactions where seller matches // Query subgraph for lock added transactions where seller matches
const subgraphQuery = { const subgraphQuery = {
@@ -456,54 +402,32 @@ const listLockTransactionBySellerAddress = async (sellerAddress: string) => {
}; };
export const checkUnreleasedLock = async ( export const checkUnreleasedLock = async (
walletAddress: string walletAddress: Address
): Promise<UnreleasedLock | undefined> => { ): Promise<UnreleasedLock | undefined> => {
const { address, abi, client } = await getContract(); const { address, abi, client } = await getContract();
const pixData: Pix = {
pixKey: "",
};
const addedLocks = await listLockTransactionByWalletAddress(walletAddress); const addedLocks = await listLockTransactionByWalletAddress(walletAddress);
if (!addedLocks.length) return undefined; if (!addedLocks.length) return undefined;
const lockIds = addedLocks.map((lock: any) => lock.args.lockID); const lockIds = addedLocks.map((lock: any) => lock.args.lockID);
const lockStatus = await client.readContract({ const [ sortedIDs, status ] = await client.readContract({
address, address,
abi, abi,
functionName: "getLocksStatus", functionName: "getLocksStatus",
args: [lockIds], args: [lockIds],
}); });
const unreleasedLockId = lockStatus[1].findIndex( const unreleasedLockId = status.findIndex(
(status: number) => status == 1 (status: LockStatus) => status == LockStatus.Active
); );
if (unreleasedLockId !== -1) { if (unreleasedLockId !== -1)
const lockID = lockStatus[0][unreleasedLockId]; return getUnreleasedLockById(sortedIDs[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 ( export const getActiveLockAmount = async (
walletAddress: string walletAddress: Address
): Promise<number> => { ): Promise<number> => {
const { address, abi, client } = await getContract(true); const { address, abi, client } = await getContract(true);
const lockSeller = await listLockTransactionBySellerAddress(walletAddress); const lockSeller = await listLockTransactionBySellerAddress(walletAddress);
@@ -512,19 +436,19 @@ export const getActiveLockAmount = async (
const lockIds = lockSeller.map((lock: any) => lock.args.lockID); const lockIds = lockSeller.map((lock: any) => lock.args.lockID);
const lockStatus = await client.readContract({ const [ sortedIDs, status ] = await client.readContract({
address, address,
abi, abi,
functionName: "getLocksStatus", functionName: "getLocksStatus",
args: [lockIds], args: [lockIds],
}); });
const mapLocksRequests = lockStatus[0].map((id: bigint) => const mapLocksRequests = status.map((id: LockStatus) =>
client.readContract({ client.readContract({
address, address: address,
abi, abi,
functionName: "mapLocks", functionName: "mapLocks",
args: [id], args: [BigInt(id)],
}) })
); );
@@ -533,9 +457,24 @@ export const getActiveLockAmount = async (
}); });
return mapLocksResults.reduce((total: number, lock: any, index: number) => { return mapLocksResults.reduce((total: number, lock: any, index: number) => {
if (lockStatus[1][index] === 1) { if (status[index] === 1) {
return total + Number(formatEther(lock.amount)); return total + Number(formatEther(lock.amount));
} }
return total; return total;
}, 0); }, 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);
};

View File

@@ -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();
});
});

View File

@@ -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);
});
});

View File

@@ -19,7 +19,7 @@ if (props.isRedirectModal) {
<template> <template>
<div> <div>
<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" v-if="!isRedirectModal"
> >
<div class="modal px-5 text-center"> <div class="modal px-5 text-center">

View File

@@ -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");
});
});

View File

@@ -7,7 +7,6 @@ import { ref, watch, onMounted } from "vue";
import SpinnerComponent from "../SpinnerComponent.vue"; import SpinnerComponent from "../SpinnerComponent.vue";
import { decimalCount } from "@/utils/decimalCount"; import { decimalCount } from "@/utils/decimalCount";
import { debounce } from "@/utils/debounce"; import { debounce } from "@/utils/debounce";
import { getTokenByAddress } from "@/blockchain/addresses";
import { useFloating, arrow, offset, flip, shift } from "@floating-ui/vue"; import { useFloating, arrow, offset, flip, shift } from "@floating-ui/vue";
const user = useUser(); const user = useUser();
@@ -160,10 +159,14 @@ showInitialItems();
</script> </script>
<template> <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> <SpinnerComponent width="8" height="8"></SpinnerComponent>
</div> </div>
<div class="main-container max-w-md" v-if="!loadingWalletTransactions"> <div class="main-container max-w-md" v-else>
<div <div
class="w-full bg-white p-4 sm:p-6 rounded-lg" class="w-full bg-white p-4 sm:p-6 rounded-lg"
v-if="props.validDeposits.length > 0" v-if="props.validDeposits.length > 0"
@@ -174,12 +177,12 @@ showInitialItems();
Saldo disponível Saldo disponível
</p> </p>
<p class="text-xl leading-7 font-semibold text-gray-900"> <p class="text-xl leading-7 font-semibold text-gray-900">
{{ getRemaining() }} {{ etherStore.selectedToken }} {{ getRemaining() }} {{ user.selectedToken.value }}
</p> </p>
<div class="flex gap-2 w-32 sm:w-56" v-if="activeLockAmount != 0"> <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">{{ <span class="text-xs font-normal text-gray-400" ref="infoText">{{
`com ${activeLockAmount.toFixed(2)} ${ `com ${activeLockAmount.toFixed(2)} ${
etherStore.selectedToken user.selectedToken.value
} em lock` } em lock`
}}</span> }}</span>
<div <div
@@ -283,10 +286,10 @@ showInitialItems();
class="text-xl sm:text-xl leading-7 font-semibold text-gray-900" class="text-xl sm:text-xl leading-7 font-semibold text-gray-900"
> >
{{ item.amount }} {{ item.amount }}
{{ getTokenByAddress(item.token) }} <!-- {{ getTokenByAddress(item.token) }} -->
</span> </span>
</div> </div>
<div> <div class="flex flex-col items-center justify-center">
<div <div
class="bg-amber-300 status-text" class="bg-amber-300 status-text"
v-if="getEventName(item.event) == 'Reserva' && item.lockStatus == 1" v-if="getEventName(item.event) == 'Reserva' && item.lockStatus == 1"
@@ -409,6 +412,7 @@ p {
} }
input[type="number"] { input[type="number"] {
appearance: textfield;
-moz-appearance: textfield; -moz-appearance: textfield;
} }

View File

@@ -1,85 +0,0 @@
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");
});
});

View File

@@ -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");
});
});

View File

@@ -1,28 +1,124 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, onUnmounted, ref } from "vue"; import { ref, onMounted, onUnmounted } from "vue";
import CustomButton from "@/components/CustomButton/CustomButton.vue"; import CustomButton from "@/components/CustomButton/CustomButton.vue";
import CustomModal from "@/components//CustomModal/CustomModal.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 qrCode = ref<string>("");
const isPixValid = ref<boolean>(false); const qrCodeSvg = ref<string>("");
const showWarnModal = ref<boolean>(true); const showWarnModal = ref<boolean>(true);
const pixTarget = ref<string>("");
const releaseSignature = 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 // Emits
const emit = defineEmits(["pixValidated"]); const emit = defineEmits(["pixValidated"]);
onMounted(() => { // Function to check solicitation status
window.addEventListener( const checkSolicitationStatus = async () => {
"resize", if (!solicitationData.value?.numeroSolicitacao) {
() => (windowSize.value = window.innerWidth) 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);
}
}); });
// Clean up interval on component unmount
onUnmounted(() => { onUnmounted(() => {
window.removeEventListener( if (pollingInterval.value) {
"resize", clearInterval(pollingInterval.value);
() => (windowSize.value = window.innerWidth) pollingInterval.value = null;
); }
}); });
</script> </script>
@@ -43,7 +139,17 @@ onUnmounted(() => {
<div <div
class="flex-col items-center justify-center flex w-full bg-white sm:p-8 p-4 rounded-lg break-normal" 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" /> <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> <span class="text-center font-bold">Código pix</span>
<div class="break-words w-4/5"> <div class="break-words w-4/5">
<span class="text-center text-xs"> <span class="text-center text-xs">
@@ -59,13 +165,17 @@ onUnmounted(() => {
/> />
</div> </div>
<CustomButton <CustomButton
:is-disabled="isPixValid == false" :is-disabled="releaseSignature === ''"
:text="'Enviar para a rede'" :text="
@button-clicked="emit('pixValidated', releaseSignature)" releaseSignature ? 'Enviar para a rede' : 'Validando pagamento...'
"
@button-clicked="
emit('pixValidated', { pixTarget, signature: releaseSignature })
"
/> />
</div> </div>
<CustomModal <CustomModal
v-if="showWarnModal && windowSize <= 500" v-if="showWarnModal"
@close-modal="showWarnModal = false" @close-modal="showWarnModal = false"
:isRedirectModal="false" :isRedirectModal="false"
/> />
@@ -122,6 +232,7 @@ h2 {
} }
input[type="number"] { input[type="number"] {
appearance: textfield;
-moz-appearance: textfield; -moz-appearance: textfield;
} }

View File

@@ -38,7 +38,7 @@ const selectedDeposits = ref<ValidDeposit[]>();
import ChevronDown from "@/assets/chevronDown.svg"; import ChevronDown from "@/assets/chevronDown.svg";
import { useOnboard } from "@web3-onboard/vue"; import { useOnboard } from "@web3-onboard/vue";
import { getPixKey } from "@/blockchain/events"; import { getParticipantID } from "@/blockchain/events";
// Emits // Emits
const emit = defineEmits(["tokenBuy"]); const emit = defineEmits(["tokenBuy"]);
@@ -54,7 +54,7 @@ const emitConfirmButton = async (): Promise<void> => {
(d) => d.network === Number(networkName.value) (d) => d.network === Number(networkName.value)
); );
if (!deposit) return; if (!deposit) return;
deposit.pixKey = await getPixKey(deposit.seller, deposit.token); deposit.participantID = await getParticipantID(deposit.seller, deposit.token);
emit("tokenBuy", deposit, tokenValue.value); emit("tokenBuy", deposit, tokenValue.value);
}; };
@@ -90,6 +90,8 @@ const handleSelectedToken = (token: TokenEnum): void => {
// Verify if there is a valid deposit to buy // Verify if there is a valid deposit to buy
const verifyLiquidity = (): void => { const verifyLiquidity = (): void => {
enableConfirmButton.value = false; enableConfirmButton.value = false;
if (!walletAddress.value)
return;
const selDeposits = verifyNetworkLiquidity( const selDeposits = verifyNetworkLiquidity(
tokenValue.value, tokenValue.value,
walletAddress.value, walletAddress.value,

View File

@@ -57,6 +57,8 @@ watch(connectedChain, (newVal: any) => {
}); });
const formatWalletAddress = (): string => { const formatWalletAddress = (): string => {
if (!walletAddress.value)
throw new Error("Wallet not connected");
const walletAddressLength = walletAddress.value.length; const walletAddressLength = walletAddress.value.length;
const initialText = walletAddress.value.substring(0, 5); const initialText = walletAddress.value.substring(0, 5);
const finalText = walletAddress.value.substring( const finalText = walletAddress.value.substring(
@@ -67,7 +69,7 @@ const formatWalletAddress = (): string => {
}; };
const disconnectUser = async (): Promise<void> => { const disconnectUser = async (): Promise<void> => {
user.setWalletAddress(""); user.setWalletAddress(null);
await disconnectWallet({ label: connectedWallet.value?.label || "" }); await disconnectWallet({ label: connectedWallet.value?.label || "" });
closeMenu(); closeMenu();
}; };

View File

@@ -1,35 +0,0 @@
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);
});
});

View File

@@ -3,8 +3,9 @@ import { NetworkEnum, TokenEnum } from "../model/NetworkEnum";
import type { ValidDeposit } from "@/model/ValidDeposit"; import type { ValidDeposit } from "@/model/ValidDeposit";
import type { Participant } from "../utils/bbPay"; import type { Participant } from "../utils/bbPay";
import { NetworkById } from "@/model/Networks"; import { NetworkById } from "@/model/Networks";
import type { Address } from "viem"
const walletAddress = ref(""); const walletAddress = ref<Address | null>(null);
const balance = ref(""); const balance = ref("");
const networkId = ref(11155111); const networkId = ref(11155111);
const networkName = ref(NetworkEnum.sepolia); const networkName = ref(NetworkEnum.sepolia);
@@ -19,7 +20,7 @@ const sellerId = ref("");
export function useUser() { export function useUser() {
// Actions become regular functions // Actions become regular functions
const setWalletAddress = (address: string) => { const setWalletAddress = (address: Address | null) => {
walletAddress.value = address; walletAddress.value = address;
}; };

8
src/model/LockStatus.ts Normal file
View 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
}

View File

@@ -3,13 +3,13 @@ export enum NetworkEnum {
rootstock = 31, rootstock = 31,
} }
export const getNetworkSubgraphURL = (network: NetworkEnum | number) => { export const getNetworkSubgraphURL = (network: NetworkEnum) => {
const networkMap: Record<number, string> = { const networkMap: Record<NetworkEnum, string> = {
[NetworkEnum.sepolia]: import.meta.env.VITE_SEPOLIA_SUBGRAPH_URL || "", [NetworkEnum.sepolia]: import.meta.env.VITE_SEPOLIA_SUBGRAPH_URL || "",
[NetworkEnum.rootstock]: import.meta.env.VITE_RSK_SUBGRAPH_URL || "", [NetworkEnum.rootstock]: import.meta.env.VITE_RSK_SUBGRAPH_URL || "",
}; };
return networkMap[typeof network === "number" ? network : network] || ""; return networkMap[network] || "";
}; };
export enum TokenEnum { export enum TokenEnum {

View File

@@ -1,11 +1,11 @@
export type Pix = { export type Pix = {
pixKey: string; pixKey: string;
merchantCity?: string; merchantCity?: string;
merchantName?: string; merchantName?: string;
value?: number; value?: number;
transactionId?: string; transactionId?: string;
message?: string; message?: string;
cep?: string; cep?: string;
currency?: number; currency?: number;
countryCode?: string; countryCode?: string;
}; };

View File

@@ -1,6 +1,8 @@
import type { Pix } from "./Pix"; import { Address } from "viem";
export type UnreleasedLock = { export type UnreleasedLock = {
lockID: string; lockID: bigint;
pix: Pix; sellerAddress: Address;
tokenAddress: Address;
amount: number;
}; };

View File

@@ -1,11 +1,12 @@
import { NetworkEnum } from "./NetworkEnum"; import { NetworkEnum } from "./NetworkEnum";
import type { Address } from "viem";
export type ValidDeposit = { export type ValidDeposit = {
token: string; token: Address;
blockNumber: number; blockNumber: number;
remaining: number; remaining: number;
seller: string; seller: Address;
pixKey: string; participantID: string;
network: NetworkEnum; network: NetworkEnum;
open?: boolean; open?: boolean;
}; };

View File

@@ -1,11 +1,14 @@
import type { LockStatus } from "@/model/LockStatus"
import type { Address } from "viem"
export type WalletTransaction = { export type WalletTransaction = {
token: string; token?: Address;
blockNumber: number; blockNumber: number;
amount: number; amount: number;
seller: string; seller: string;
buyer: string; buyer: string;
event: string; event: string;
lockStatus: number; lockStatus?: LockStatus;
transactionHash: string; transactionHash: string;
transactionID?: string; transactionID?: string;
}; };

View File

@@ -1,120 +0,0 @@
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(),
},
];

View File

@@ -1,45 +0,0 @@
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,
},
];

View File

@@ -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",
},
];

View File

@@ -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 };

View File

@@ -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);
});
});

View File

@@ -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);
});
});

View File

@@ -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);
});
});

View File

@@ -1,5 +1,3 @@
import { off } from "process";
export interface Participant { export interface Participant {
offer: string; offer: string;
chainID: number; chainID: number;
@@ -17,7 +15,6 @@ export interface ParticipantWithID extends Participant {
export interface Offer { export interface Offer {
amount: number; amount: number;
lockId: string;
sellerId: string; sellerId: string;
} }
@@ -25,7 +22,6 @@ export interface Offer {
// https://apoio.developers.bb.com.br/sandbox/spec/665797498bb48200130fc32c // https://apoio.developers.bb.com.br/sandbox/spec/665797498bb48200130fc32c
export const createParticipant = async (participant: Participant) => { export const createParticipant = async (participant: Participant) => {
console.log("Creating participant", participant);
const response = await fetch(`${import.meta.env.VITE_APP_API_URL}/register`, { const response = await fetch(`${import.meta.env.VITE_APP_API_URL}/register`, {
method: "POST", method: "POST",
headers: { headers: {
@@ -41,8 +37,14 @@ export const createParticipant = async (participant: Participant) => {
codigoIspb: participant.bankIspb, codigoIspb: participant.bankIspb,
}), }),
}); });
if (!response.ok) {
throw new Error(`Error creating participant: ${response.statusText}`);
}
const data = await response.json(); const data = await response.json();
return { ...participant, id: data.id } as ParticipantWithID; 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) => { export const createSolicitation = async (offer: Offer) => {
@@ -53,7 +55,7 @@ export const createSolicitation = async (offer: Offer) => {
}, },
body: JSON.stringify({ body: JSON.stringify({
amount: offer.amount, amount: offer.amount,
pixTarget: offer.sellerId, pixTarget: offer.sellerId.split("-").pop(),
}), }),
}); });
return response.json(); return response.json();
@@ -64,14 +66,10 @@ export const getSolicitation = async (id: string) => {
`${import.meta.env.VITE_APP_API_URL}/release/${id}` `${import.meta.env.VITE_APP_API_URL}/release/${id}`
); );
const obj: any = response.json(); const obj: any = await response.json();
return { return {
id: obj.numeroSolicitacao, pixTarget: obj.pixTarget,
lockId: obj.codigoConciliacaoSolicitacao, signature: obj.signature,
amount: obj.valorSolicitacao,
qrcode: obj.pix.textoQrCode,
status: obj.valorSomatorioPagamentosEfetivados >= obj.valorSolicitacao,
signature: obj.assinatura,
}; };
}; };

View File

@@ -1,8 +1,9 @@
import type { ValidDeposit } from "@/model/ValidDeposit"; import type { ValidDeposit } from "@/model/ValidDeposit";
import type { Address } from "viem";
const verifyNetworkLiquidity = ( const verifyNetworkLiquidity = (
tokenValue: number, tokenValue: number,
walletAddress: string, walletAddress: Address,
validDepositList: ValidDeposit[] validDepositList: ValidDeposit[]
): ValidDeposit[] => { ): ValidDeposit[] => {
const filteredDepositList = validDepositList const filteredDepositList = validDepositList

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -24,7 +24,6 @@ const openItem = (index: number) => {
faq.value[selectedSection.value].items[index].content = marked( faq.value[selectedSection.value].items[index].content = marked(
faq.value[selectedSection.value].items[index].content faq.value[selectedSection.value].items[index].content
); );
console.log(marked(faq.value[selectedSection.value].items[index].content));
}; };
</script> </script>

View File

@@ -12,6 +12,7 @@ import type { ValidDeposit } from "@/model/ValidDeposit";
import { getUnreleasedLockById } from "@/blockchain/events"; import { getUnreleasedLockById } from "@/blockchain/events";
import CustomAlert from "@/components/CustomAlert/CustomAlert.vue"; import CustomAlert from "@/components/CustomAlert/CustomAlert.vue";
import { getSolicitation } from "@/utils/bbPay"; import { getSolicitation } from "@/utils/bbPay";
import type { Address } from "viem";
enum Step { enum Step {
Search, Search,
@@ -25,7 +26,8 @@ user.setSellerView(false);
// States // States
const { loadingLock, walletAddress, networkName } = user; const { loadingLock, walletAddress, networkName } = user;
const flowStep = ref<Step>(Step.Search); const flowStep = ref<Step>(Step.Search);
const pixTarget = ref<string>(); const participantID = ref<string>();
const sellerAddress = ref<Address>();
const tokenAmount = ref<number>(); const tokenAmount = ref<number>();
const lockID = ref<string>(""); const lockID = ref<string>("");
const loadingRelease = ref<boolean>(false); const loadingRelease = ref<boolean>(false);
@@ -37,7 +39,7 @@ const confirmBuyClick = async (
selectedDeposit: ValidDeposit, selectedDeposit: ValidDeposit,
tokenValue: number tokenValue: number
) => { ) => {
pixTarget.value = selectedDeposit.pixKey; participantID.value = selectedDeposit.participantID;
tokenAmount.value = tokenValue; tokenAmount.value = tokenValue;
if (selectedDeposit) { if (selectedDeposit) {
@@ -46,7 +48,7 @@ const confirmBuyClick = async (
await addLock(selectedDeposit.seller, selectedDeposit.token, tokenValue) await addLock(selectedDeposit.seller, selectedDeposit.token, tokenValue)
.then((_lockID) => { .then((_lockID) => {
lockID.value = _lockID; lockID.value = String(_lockID);
}) })
.catch((err) => { .catch((err) => {
console.log(err); console.log(err);
@@ -57,28 +59,32 @@ const confirmBuyClick = async (
} }
}; };
const releaseTransaction = async (lockId: string) => { const releaseTransaction = async ({
pixTarget,
signature,
}: {
pixTarget: string;
signature: string;
}) => {
flowStep.value = Step.List; flowStep.value = Step.List;
showBuyAlert.value = true; showBuyAlert.value = true;
loadingRelease.value = true; loadingRelease.value = true;
const solicitation = await getSolicitation(lockId); const release = await releaseLock(BigInt(lockID.value), pixTarget, signature);
await release.wait();
if (solicitation.status) { await updateWalletStatus();
const release = await releaseLock(solicitation); loadingRelease.value = false;
await release.wait();
await updateWalletStatus();
loadingRelease.value = false;
}
}; };
const checkForUnreleasedLocks = async (): Promise<void> => { const checkForUnreleasedLocks = async (): Promise<void> => {
const walletLocks = await checkUnreleasedLock(walletAddress.value); if (!walletAddress.value)
if (walletLocks) { throw new Error("Wallet not connected");
lockID.value = walletLocks.lockID; const lock = await checkUnreleasedLock(walletAddress.value);
tokenAmount.value = walletLocks.pix.value; if (lock) {
pixTarget.value = walletLocks.pix.pixKey; lockID.value = String(lock.lockID);
tokenAmount.value = lock.amount;
sellerAddress.value = lock.sellerAddress;
showModal.value = true; showModal.value = true;
} else { } else {
flowStep.value = Step.Search; flowStep.value = Step.Search;
@@ -87,11 +93,11 @@ const checkForUnreleasedLocks = async (): Promise<void> => {
}; };
if (paramLockID) { if (paramLockID) {
const lockToRedirect = await getUnreleasedLockById(paramLockID as string); const lockToRedirect = await getUnreleasedLockById(paramLockID);
if (lockToRedirect) { if (lockToRedirect) {
lockID.value = lockToRedirect.lockID; lockID.value = String(lockToRedirect.lockID);
tokenAmount.value = lockToRedirect.pix.value; tokenAmount.value = lockToRedirect.amount;
pixTarget.value = lockToRedirect.pix.pixKey; sellerAddress.value = lockToRedirect.sellerAddress;
flowStep.value = Step.Buy; flowStep.value = Step.Buy;
} else { } else {
flowStep.value = Step.Search; flowStep.value = Step.Search;
@@ -134,8 +140,7 @@ onMounted(async () => {
/> />
<div v-if="flowStep == Step.Buy"> <div v-if="flowStep == Step.Buy">
<QrCodeComponent <QrCodeComponent
:sellerId="String(pixTarget)" :lockID="lockID"
:amount="tokenAmount"
@pix-validated="releaseTransaction" @pix-validated="releaseTransaction"
v-if="!loadingLock" v-if="!loadingLock"
/> />

View File

@@ -48,19 +48,15 @@ const callWithdraw = async (amount: string) => {
const getWalletTransactions = async () => { const getWalletTransactions = async () => {
user.setLoadingWalletTransactions(true); user.setLoadingWalletTransactions(true);
if (walletAddress.value) { if (walletAddress.value) {
console.log("Will fetch all required data...");
const walletDeposits = await listValidDepositTransactionsByWalletAddress( const walletDeposits = await listValidDepositTransactionsByWalletAddress(
walletAddress.value walletAddress.value
); );
console.log("Fetched deposits");
const allUserTransactions = await listAllTransactionByWalletAddress( const allUserTransactions = await listAllTransactionByWalletAddress(
walletAddress.value walletAddress.value
); );
console.log("Fetched all transactions");
activeLockAmount.value = await getActiveLockAmount(walletAddress.value); activeLockAmount.value = await getActiveLockAmount(walletAddress.value);
console.log("Fetched active lock amount");
if (walletDeposits) { if (walletDeposits) {
depositList.value = walletDeposits; depositList.value = walletDeposits;

View File

@@ -2,7 +2,6 @@
"extends": "@vue/tsconfig/tsconfig.node.json", "extends": "@vue/tsconfig/tsconfig.node.json",
"include": [ "include": [
"vite.config.*", "vite.config.*",
"vitest.config.*",
"cypress.config.*", "cypress.config.*",
"playwright.config.*" "playwright.config.*"
], ],

View File

@@ -8,13 +8,13 @@
], ],
"compilerOptions": { "compilerOptions": {
"baseUrl": ".", "baseUrl": ".",
"strict": true,
"paths": { "paths": {
"@/*": [ "@/*": [
"./src/*" "./src/*"
] ]
}, },
"types": [ "types": [
"jest",
"node" "node"
], ],
"resolveJsonModule": true, "resolveJsonModule": true,

View File

@@ -1,6 +1,6 @@
import { fileURLToPath, URL } from "node:url"; import { fileURLToPath, URL } from "node:url";
import { defineConfig } from "vitest/config"; import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue"; import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx"; import vueJsx from "@vitejs/plugin-vue-jsx";
import svgLoader from "vite-svg-loader"; import svgLoader from "vite-svg-loader";
@@ -21,17 +21,6 @@ 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()], plugins: [vue(), vueJsx(), svgLoader()],
resolve: { resolve: {
alias: { alias: {

11
wagmi.config.ts Normal file
View 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',
}),],
})

2595
yarn.lock

File diff suppressed because it is too large Load Diff