Fix issues with locking and solicitation.

This commit is contained in:
Filipe Soccol 2025-06-27 15:59:34 -03:00
parent 73ba77ca4f
commit cf61f5ecfd
16 changed files with 202 additions and 189 deletions

View File

@ -6,7 +6,6 @@ import {
isPossibleNetwork, isPossibleNetwork,
} from "../addresses"; } from "../addresses";
import { setActivePinia, createPinia } from "pinia";
import { NetworkEnum, TokenEnum } from "@/model/NetworkEnum"; import { NetworkEnum, TokenEnum } from "@/model/NetworkEnum";
import { useUser } from "@/composables/useUser"; import { useUser } from "@/composables/useUser";
@ -20,10 +19,6 @@ describe("addresses.ts types", () => {
}); });
describe("addresses.ts functions", () => { describe("addresses.ts functions", () => {
beforeEach(() => {
setActivePinia(createPinia());
});
it("getTokenAddress Ethereum", () => { it("getTokenAddress Ethereum", () => {
const user = useUser(); const user = useUser();
user.setNetworkId(11155111); user.setNetworkId(11155111);

View File

@ -28,19 +28,23 @@ export const getTokenByAddress = (address: string) => {
export const getTokenAddress = ( export const getTokenAddress = (
token: TokenEnum, token: TokenEnum,
network?: NetworkEnum network?: NetworkEnum
): string => { ): `0x${string}` => {
const user = useUser(); const user = useUser();
return Tokens[network ? network : user.networkName.value][token]; return Tokens[network ? network : user.networkName.value][
token
] as `0x${string}`;
}; };
export const getP2PixAddress = (network?: NetworkEnum): string => { export const getP2PixAddress = (network?: NetworkEnum): `0x${string}` => {
const user = useUser(); const user = useUser();
const possibleP2PixAddresses: { [key in NetworkEnum]: string } = { const possibleP2PixAddresses: { [key in NetworkEnum]: string } = {
[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
] as `0x${string}`;
}; };
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

@ -8,51 +8,65 @@ export const addLock = async (
tokenAddress: string, tokenAddress: string,
amount: number amount: number
): Promise<string> => { ): Promise<string> => {
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());
if (!wallet) {
throw new Error("Wallet not connected");
}
const { request } = await client.simulateContract({ const { request } = await client.simulateContract({
address, address: address as `0x${string}`,
abi, abi,
functionName: "lock", functionName: "lock",
args: [sellerAddress, tokenAddress, parsedAmount, [], []], args: [sellerAddress, tokenAddress as `0x${string}`, parsedAmount, [], []],
account: account as `0x${string}`,
}); });
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] : ""; return receipt.status === "success" ? receipt.logs[0].topics[2] ?? "" : "";
}; };
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);
const { request } = await client.simulateContract({ const { request } = await client.simulateContract({
address, address: address as `0x${string}`,
abi, abi,
functionName: "withdraw", functionName: "withdraw",
args: [tokenAddress, parseEther(amount), []], args: [tokenAddress as `0x${string}`, parseEther(amount), []],
account: account as `0x${string}`,
}); });
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 (solicitation: any): Promise<any> => {
const { address, abi, wallet, client } = await getContract(); const { address, abi, wallet, client, account } = await getContract();
if (!wallet) {
throw new Error("Wallet not connected");
}
const { request } = await client.simulateContract({ const { request } = await client.simulateContract({
address, address: address as `0x${string}`,
abi, abi,
functionName: "release", functionName: "release",
args: [solicitation.lockId, solicitation.e2eId], args: [solicitation.lockId, solicitation.e2eId],
account: account as `0x${string}`,
}); });
const hash = await wallet.writeContract(request); const hash = await wallet.writeContract(request);

View File

@ -7,7 +7,6 @@ import type { ValidDeposit } from "@/model/ValidDeposit";
import { getP2PixAddress, getTokenAddress } from "./addresses"; import { getP2PixAddress, getTokenAddress } from "./addresses";
import { getNetworkSubgraphURL, NetworkEnum } from "@/model/NetworkEnum"; import { getNetworkSubgraphURL, NetworkEnum } from "@/model/NetworkEnum";
import type { UnreleasedLock } from "@/model/UnreleasedLock"; import type { UnreleasedLock } from "@/model/UnreleasedLock";
import type { Pix } from "@/model/Pix";
const getNetworksLiquidity = async (): Promise<void> => { const getNetworksLiquidity = async (): Promise<void> => {
const user = useUser(); const user = useUser();
@ -34,7 +33,7 @@ const getPixKey = 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 pixKeyHex = await client.readContract({
address, address: address as `0x${string}`,
abi, abi,
functionName: "getPixTarget", functionName: "getPixTarget",
args: [seller, token], args: [seller, token],
@ -42,13 +41,12 @@ 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 pixKeyHex === "string" ? pixKeyHex : toHex(pixKeyHex as bigint);
if (!hexString) throw new Error("PixKey not found"); if (!hexString) throw new Error("PixKey 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
@ -60,13 +58,13 @@ const getValidDeposits = async (
network: NetworkEnum, network: NetworkEnum,
contractInfo?: { client: any; address: string } contractInfo?: { client: any; address: string }
): 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 = p2pix.abi;
} 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
@ -114,7 +112,7 @@ const getValidDeposits = async (
const sellersList = Object.keys(uniqueSellers); const sellersList = Object.keys(uniqueSellers);
// 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) as `0x${string}`,
abi, abi,
functionName: "getBalance", functionName: "getBalance",
args: [seller, token], args: [seller, token],
@ -147,25 +145,31 @@ const getUnreleasedLockById = async (
lockID: string lockID: string
): 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 lock = await client.readContract({
address, address: address as `0x${string}`,
abi, abi,
functionName: "mapLocks", functionName: "mapLocks",
args: [BigInt(lockID)], args: [BigInt(lockID)],
}); });
const pixTarget = lock.pixTarget; // Type the lock result as an array (based on the smart contract structure)
const amount = formatEther(lock.amount); const lockData = lock as [
pixData.pixKey = pixTarget; bigint,
pixData.value = Number(amount); string,
string,
bigint,
string,
string,
string
];
const amount = formatEther(lockData[3]);
return { return {
lockID: lockID, lockID: lockID,
pix: pixData, amount: Number(amount),
tokenAddress: lockData[4] as `0x${string}`,
sellerAddress: lockData[6] as `0x${string}`,
}; };
}; };

View File

@ -15,7 +15,7 @@ import { useUser } from "@/composables/useUser";
let publicClient: PublicClient | null = null; let publicClient: PublicClient | null = null;
let walletClient: WalletClient | null = null; let walletClient: WalletClient | null = null;
const getPublicClient: PublicClient | null = (onlyRpcProvider = false) => { const getPublicClient = (onlyRpcProvider = false): PublicClient | null => {
if (onlyRpcProvider) { if (onlyRpcProvider) {
const user = useUser(); const user = useUser();
const rpcUrl = getProviderUrl(); const rpcUrl = getProviderUrl();
@ -28,7 +28,7 @@ const getPublicClient: PublicClient | null = (onlyRpcProvider = false) => {
return publicClient; return publicClient;
}; };
const getWalletClient: WalletClient | null = () => { const getWalletClient = (): WalletClient | null => {
return walletClient; return walletClient;
}; };
@ -38,13 +38,16 @@ const getContract = async (onlyRpcProvider = false) => {
const abi = p2pix.abi; const abi = p2pix.abi;
const wallet = getWalletClient(); const wallet = getWalletClient();
if (!client) {
throw new Error("Public client not initialized");
}
const [account] = wallet ? await wallet.getAddresses() : [""]; const [account] = wallet ? await wallet.getAddresses() : [""];
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;

View File

@ -1,6 +1,7 @@
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 mockToken from "../utils/smart_contract_files/MockToken.json";
import { useUser } from "@/composables/useUser"; import { useUser } from "@/composables/useUser";
@ -24,20 +25,25 @@ 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 as `0x${string}`,
abi: mockToken.abi, abi: mockToken.abi,
functionName: "allowance", functionName: "allowance",
args: [account, getP2PixAddress()], args: [account, getP2PixAddress()],
}); });
if (allowance < parseEther(participant.offer.toString())) { if ((allowance as bigint) < 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 as `0x${string}`,
abi: mockToken.abi, abi: mockToken.abi,
functionName: "approve", functionName: "approve",
args: [getP2PixAddress(), parseEther(participant.offer.toString())], args: [
getP2PixAddress() as `0x${string}`,
parseEther(participant.offer.toString()),
],
account, account,
chain,
}); });
await publicClient.waitForTransactionReceipt({ hash }); await publicClient.waitForTransactionReceipt({ hash });
@ -59,19 +65,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: address as `0x${string}`,
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) as `0x${string}`,
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,14 @@
import { decodeEventLog, formatEther, type Log } from "viem"; import { formatEther } 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 } 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 { getNetworkSubgraphURL } from "@/model/NetworkEnum"; import { getNetworkSubgraphURL } from "@/model/NetworkEnum";
export const updateWalletStatus = async (): Promise<void> => { export const updateWalletStatus = async (): Promise<void> => {
@ -55,54 +52,12 @@ export const listValidDepositTransactionsByWalletAddress = async (
const getLockStatus = async (id: bigint): Promise<number> => { const getLockStatus = async (id: bigint): Promise<number> => {
const { address, abi, client } = await getContract(); const { address, abi, client } = await getContract();
const result = await client.readContract({ const result = await client.readContract({
address, address: address as `0x${string}`,
abi, abi,
functionName: "getLocksStatus", functionName: "getLocksStatus",
args: [[id]], args: [[id]],
}); });
return result[1][0]; return (result as any)[1][0] as number;
};
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 (
@ -118,6 +73,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 +85,6 @@ export const listAllTransactionByWalletAddress = async (
buyer buyer
lockID lockID
seller seller
token
amount amount
blockTimestamp blockTimestamp
blockNumber blockNumber
@ -138,7 +93,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 +109,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 +118,12 @@ export const listAllTransactionByWalletAddress = async (
}); });
const data = await response.json(); const data = await response.json();
console.log("Subgraph data fetched:", data); console.log("Subgraph data:", 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,
@ -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,7 +160,6 @@ 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: "", // Subgraph doesn't provide token in this event, we could enhance this later
@ -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,
@ -325,7 +273,6 @@ const listLockTransactionByWalletAddress = async (walletAddress: string) => {
buyer buyer
lockID lockID
seller seller
token
amount amount
blockTimestamp blockTimestamp
blockNumber blockNumber
@ -386,7 +333,6 @@ const listLockTransactionByWalletAddress = async (walletAddress: string) => {
const listLockTransactionBySellerAddress = async (sellerAddress: string) => { const listLockTransactionBySellerAddress = async (sellerAddress: string) => {
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 = {
@ -459,10 +405,6 @@ export const checkUnreleasedLock = async (
walletAddress: string walletAddress: string
): 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;
@ -470,34 +412,43 @@ export const checkUnreleasedLock = async (
const lockIds = addedLocks.map((lock: any) => lock.args.lockID); const lockIds = addedLocks.map((lock: any) => lock.args.lockID);
const lockStatus = await client.readContract({ const lockStatus = await client.readContract({
address, address: address as `0x${string}`,
abi, abi,
functionName: "getLocksStatus", functionName: "getLocksStatus",
args: [lockIds], args: [lockIds],
}); });
const unreleasedLockId = lockStatus[1].findIndex( const lockStatusResult = lockStatus as [bigint[], number[]];
const unreleasedLockId = lockStatusResult[1].findIndex(
(status: number) => status == 1 (status: number) => status == 1
); );
if (unreleasedLockId !== -1) { if (unreleasedLockId !== -1) {
const lockID = lockStatus[0][unreleasedLockId]; const lockID = lockStatusResult[0][unreleasedLockId];
const lock = await client.readContract({ const lock = await client.readContract({
address, address: address as `0x${string}`,
abi, abi,
functionName: "mapLocks", functionName: "mapLocks",
args: [lockID], args: [lockID],
}); });
const pixTarget = lock.pixTarget; const lockData = lock as [
const amount = formatEther(lock.amount); bigint,
pixData.pixKey = pixTarget; string,
pixData.value = Number(amount); string,
bigint,
string,
string,
string
];
const amount = formatEther(lockData[0]);
return { return {
lockID, lockID: lockID.toString(),
pix: pixData, amount: Number(amount),
sellerAddress: lockData[1] as `0x${string}`,
tokenAddress: lockData[4] as `0x${string}`,
}; };
} }
}; };
@ -513,15 +464,16 @@ 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 lockStatus = await client.readContract({
address, address: address as `0x${string}`,
abi, abi,
functionName: "getLocksStatus", functionName: "getLocksStatus",
args: [lockIds], args: [lockIds],
}); });
const mapLocksRequests = lockStatus[0].map((id: bigint) => const lockStatusResult = lockStatus as [bigint[], number[]];
const mapLocksRequests = lockStatusResult[0].map((id: bigint) =>
client.readContract({ client.readContract({
address, address: address as `0x${string}`,
abi, abi,
functionName: "mapLocks", functionName: "mapLocks",
args: [id], args: [id],
@ -533,9 +485,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 (lockStatusResult[1][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: string,
tokenAddress: string
): Promise<string> => {
const { address, abi, client } = await getContract();
const participantId = await client.readContract({
address: address as `0x${string}`,
abi,
functionName: "getPixTarget",
args: [sellerAddress, tokenAddress],
});
return participantId as string;
};

View File

@ -1,12 +1,7 @@
import { mount } from "@vue/test-utils"; import { mount } from "@vue/test-utils";
import BuyConfirmedComponent from "../BuyConfirmedComponent.vue"; import BuyConfirmedComponent from "../BuyConfirmedComponent.vue";
import { createPinia, setActivePinia } from "pinia";
describe("BuyConfirmedComponent.vue", async () => { describe("BuyConfirmedComponent.vue", async () => {
beforeEach(() => {
setActivePinia(createPinia());
});
const wrapper = mount(BuyConfirmedComponent, { const wrapper = mount(BuyConfirmedComponent, {
props: { props: {
tokenAmount: 1, tokenAmount: 1,

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

@ -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();
@ -174,12 +173,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 +282,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 +408,7 @@ p {
} }
input[type="number"] { input[type="number"] {
appearance: textfield;
-moz-appearance: textfield; -moz-appearance: textfield;
} }

View File

@ -1,28 +1,54 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, onUnmounted, ref } from "vue"; import { ref, onMounted } 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 { createSolicitation, type Offer } from "@/utils/bbPay";
import { getSellerParticipantId } from "@/blockchain/wallet";
import { hexToString } from "viem";
import { getUnreleasedLockById } from "@/blockchain/events";
// 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 isPixValid = ref<boolean>(false);
const showWarnModal = ref<boolean>(true); const showWarnModal = ref<boolean>(true);
const releaseSignature = ref<string>(""); const releaseSignature = ref<string>("");
const solicitationData = ref<any>(null);
// Emits // Emits
const emit = defineEmits(["pixValidated"]); const emit = defineEmits(["pixValidated"]);
onMounted(() => { onMounted(async () => {
window.addEventListener( try {
"resize", const { tokenAddress, sellerAddress, amount } = await getUnreleasedLockById(
() => (windowSize.value = window.innerWidth) props.lockID
); );
});
onUnmounted(() => { const participantId = await getSellerParticipantId(
window.removeEventListener( sellerAddress as `0x${string}`,
"resize", tokenAddress
() => (windowSize.value = window.innerWidth)
); );
const offer: Offer = {
amount,
sellerId: hexToString(participantId as `0x${string}`, { size: 32 }),
};
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;
}
} catch (error) {
console.error("Error creating solicitation:", error);
}
}); });
</script> </script>
@ -65,7 +91,7 @@ onUnmounted(() => {
/> />
</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 +148,7 @@ h2 {
} }
input[type="number"] { input[type="number"] {
appearance: textfield;
-moz-appearance: textfield; -moz-appearance: textfield;
} }

View File

@ -1,15 +1,8 @@
import { describe, it, expect, beforeEach } from "vitest"; import { describe, it, expect } from "vitest";
import { mount } from "@vue/test-utils"; import { mount } from "@vue/test-utils";
import TopBar from "../TopBar.vue"; import TopBar from "../TopBar.vue";
import { useUser } from "@/composables/useUser";
import { createPinia, setActivePinia } from "pinia";
describe("TopBar.vue", () => { describe("TopBar.vue", () => {
beforeEach(() => {
setActivePinia(createPinia());
});
it("should render connect wallet button", () => { it("should render connect wallet button", () => {
const wrapper = mount(TopBar); const wrapper = mount(TopBar);
expect(wrapper.html()).toContain("Conectar carteira"); expect(wrapper.html()).toContain("Conectar carteira");
@ -20,13 +13,6 @@ describe("TopBar.vue", () => {
expect(wrapper.html()).toContain("Quero vender"); 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", () => { it("should render the P2Pix logo correctly", () => {
const wrapper = mount(TopBar); const wrapper = mount(TopBar);
const img = wrapper.findAll(".logo"); const img = wrapper.findAll(".logo");

View File

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

View File

@ -17,7 +17,6 @@ export interface ParticipantWithID extends Participant {
export interface Offer { export interface Offer {
amount: number; amount: number;
lockId: string;
sellerId: string; sellerId: string;
} }
@ -41,11 +40,18 @@ 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) => {
console.log("Creating solicitation", offer);
const response = await fetch(`${import.meta.env.VITE_APP_API_URL}/request`, { const response = await fetch(`${import.meta.env.VITE_APP_API_URL}/request`, {
method: "POST", method: "POST",
headers: { headers: {
@ -53,7 +59,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();

View File

@ -74,11 +74,11 @@ const releaseTransaction = async (lockId: string) => {
}; };
const checkForUnreleasedLocks = async (): Promise<void> => { const checkForUnreleasedLocks = async (): Promise<void> => {
const walletLocks = await checkUnreleasedLock(walletAddress.value); const lock = await checkUnreleasedLock(walletAddress.value);
if (walletLocks) { if (lock) {
lockID.value = walletLocks.lockID; lockID.value = lock.lockID;
tokenAmount.value = walletLocks.pix.value; tokenAmount.value = lock.amount;
pixTarget.value = walletLocks.pix.pixKey; pixTarget.value = lock.sellerAddress;
showModal.value = true; showModal.value = true;
} else { } else {
flowStep.value = Step.Search; flowStep.value = Step.Search;
@ -90,8 +90,8 @@ if (paramLockID) {
const lockToRedirect = await getUnreleasedLockById(paramLockID as string); const lockToRedirect = await getUnreleasedLockById(paramLockID as string);
if (lockToRedirect) { if (lockToRedirect) {
lockID.value = lockToRedirect.lockID; lockID.value = lockToRedirect.lockID;
tokenAmount.value = lockToRedirect.pix.value; tokenAmount.value = lockToRedirect.amount;
pixTarget.value = lockToRedirect.pix.pixKey; pixTarget.value = lockToRedirect.sellerAddress;
flowStep.value = Step.Buy; flowStep.value = Step.Buy;
} else { } else {
flowStep.value = Step.Search; flowStep.value = Step.Search;
@ -135,7 +135,8 @@ onMounted(async () => {
<div v-if="flowStep == Step.Buy"> <div v-if="flowStep == Step.Buy">
<QrCodeComponent <QrCodeComponent
:sellerId="String(pixTarget)" :sellerId="String(pixTarget)"
:amount="tokenAmount" :amount="tokenAmount || 0"
:lockID="lockID"
@pix-validated="releaseTransaction" @pix-validated="releaseTransaction"
v-if="!loadingLock" v-if="!loadingLock"
/> />