Fix issues with locking and solicitation.
This commit is contained in:
parent
73ba77ca4f
commit
cf61f5ecfd
@ -6,7 +6,6 @@ import {
|
||||
isPossibleNetwork,
|
||||
} from "../addresses";
|
||||
|
||||
import { setActivePinia, createPinia } from "pinia";
|
||||
import { NetworkEnum, TokenEnum } from "@/model/NetworkEnum";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
|
||||
@ -20,10 +19,6 @@ describe("addresses.ts types", () => {
|
||||
});
|
||||
|
||||
describe("addresses.ts functions", () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
});
|
||||
|
||||
it("getTokenAddress Ethereum", () => {
|
||||
const user = useUser();
|
||||
user.setNetworkId(11155111);
|
||||
|
@ -28,19 +28,23 @@ export const getTokenByAddress = (address: string) => {
|
||||
export const getTokenAddress = (
|
||||
token: TokenEnum,
|
||||
network?: NetworkEnum
|
||||
): string => {
|
||||
): `0x${string}` => {
|
||||
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 possibleP2PixAddresses: { [key in NetworkEnum]: string } = {
|
||||
[NetworkEnum.sepolia]: "0xb7cD135F5eFD9760981e02E2a898790b688939fe",
|
||||
[NetworkEnum.rootstock]: "0x98ba35eb14b38D6Aa709338283af3e922476dE34",
|
||||
};
|
||||
|
||||
return possibleP2PixAddresses[network ? network : user.networkName.value];
|
||||
return possibleP2PixAddresses[
|
||||
network ? network : user.networkName.value
|
||||
] as `0x${string}`;
|
||||
};
|
||||
|
||||
export const getProviderUrl = (network?: NetworkEnum): string => {
|
||||
@ -54,7 +58,6 @@ export const getProviderUrl = (network?: NetworkEnum): string => {
|
||||
};
|
||||
|
||||
export const getProviderByNetwork = (network: NetworkEnum) => {
|
||||
console.log("network", network);
|
||||
const chain = network === NetworkEnum.sepolia ? sepolia : rootstock;
|
||||
return createPublicClient({
|
||||
chain,
|
||||
|
@ -8,51 +8,65 @@ export const addLock = async (
|
||||
tokenAddress: string,
|
||||
amount: number
|
||||
): Promise<string> => {
|
||||
const { address, abi, wallet, client } = await getContract();
|
||||
const { address, abi, wallet, client, account } = await getContract();
|
||||
const parsedAmount = parseEther(amount.toString());
|
||||
|
||||
if (!wallet) {
|
||||
throw new Error("Wallet not connected");
|
||||
}
|
||||
|
||||
const { request } = await client.simulateContract({
|
||||
address,
|
||||
address: address as `0x${string}`,
|
||||
abi,
|
||||
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 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 (
|
||||
amount: string,
|
||||
token: TokenEnum
|
||||
): 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 { request } = await client.simulateContract({
|
||||
address,
|
||||
address: address as `0x${string}`,
|
||||
abi,
|
||||
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 receipt = await client.waitForTransactionReceipt({ hash });
|
||||
|
||||
return receipt.status;
|
||||
return receipt.status === "success";
|
||||
};
|
||||
|
||||
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({
|
||||
address,
|
||||
address: address as `0x${string}`,
|
||||
abi,
|
||||
functionName: "release",
|
||||
args: [solicitation.lockId, solicitation.e2eId],
|
||||
account: account as `0x${string}`,
|
||||
});
|
||||
|
||||
const hash = await wallet.writeContract(request);
|
||||
|
@ -7,7 +7,6 @@ import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||
import { getP2PixAddress, getTokenAddress } from "./addresses";
|
||||
import { getNetworkSubgraphURL, NetworkEnum } from "@/model/NetworkEnum";
|
||||
import type { UnreleasedLock } from "@/model/UnreleasedLock";
|
||||
import type { Pix } from "@/model/Pix";
|
||||
|
||||
const getNetworksLiquidity = async (): Promise<void> => {
|
||||
const user = useUser();
|
||||
@ -34,7 +33,7 @@ const getPixKey = async (seller: string, token: string): Promise<string> => {
|
||||
const { address, abi, client } = await getContract();
|
||||
|
||||
const pixKeyHex = await client.readContract({
|
||||
address,
|
||||
address: address as `0x${string}`,
|
||||
abi,
|
||||
functionName: "getPixTarget",
|
||||
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
|
||||
const hexString =
|
||||
typeof pixKeyHex === "string" ? pixKeyHex : toHex(pixKeyHex);
|
||||
typeof pixKeyHex === "string" ? pixKeyHex : toHex(pixKeyHex as bigint);
|
||||
if (!hexString) throw new Error("PixKey not found");
|
||||
const bytes = new Uint8Array(
|
||||
// @ts-ignore
|
||||
hexString
|
||||
.slice(2)
|
||||
.match(/.{1,2}/g)
|
||||
.match(/.{1,2}/g)!
|
||||
.map((byte: string) => parseInt(byte, 16))
|
||||
);
|
||||
// Remove null bytes from the end of the string
|
||||
@ -60,13 +58,13 @@ const getValidDeposits = async (
|
||||
network: NetworkEnum,
|
||||
contractInfo?: { client: any; address: string }
|
||||
): Promise<ValidDeposit[]> => {
|
||||
let client: PublicClient, address, abi;
|
||||
let client: PublicClient, abi;
|
||||
|
||||
if (contractInfo) {
|
||||
({ client, address } = contractInfo);
|
||||
({ client } = contractInfo);
|
||||
abi = p2pix.abi;
|
||||
} else {
|
||||
({ address, abi, client } = await getContract(true));
|
||||
({ abi, client } = await getContract(true));
|
||||
}
|
||||
|
||||
// TODO: Remove this once we have a subgraph for rootstock
|
||||
@ -114,7 +112,7 @@ const getValidDeposits = async (
|
||||
const sellersList = Object.keys(uniqueSellers);
|
||||
// Use multicall to batch all getBalance requests
|
||||
const balanceCalls = sellersList.map((seller) => ({
|
||||
address: getP2PixAddress(network),
|
||||
address: getP2PixAddress(network) as `0x${string}`,
|
||||
abi,
|
||||
functionName: "getBalance",
|
||||
args: [seller, token],
|
||||
@ -147,25 +145,31 @@ const getUnreleasedLockById = async (
|
||||
lockID: string
|
||||
): Promise<UnreleasedLock> => {
|
||||
const { address, abi, client } = await getContract();
|
||||
const pixData: Pix = {
|
||||
pixKey: "",
|
||||
};
|
||||
|
||||
const lock = await client.readContract({
|
||||
address,
|
||||
address: address as `0x${string}`,
|
||||
abi,
|
||||
functionName: "mapLocks",
|
||||
args: [BigInt(lockID)],
|
||||
});
|
||||
|
||||
const pixTarget = lock.pixTarget;
|
||||
const amount = formatEther(lock.amount);
|
||||
pixData.pixKey = pixTarget;
|
||||
pixData.value = Number(amount);
|
||||
// Type the lock result as an array (based on the smart contract structure)
|
||||
const lockData = lock as [
|
||||
bigint,
|
||||
string,
|
||||
string,
|
||||
bigint,
|
||||
string,
|
||||
string,
|
||||
string
|
||||
];
|
||||
const amount = formatEther(lockData[3]);
|
||||
|
||||
return {
|
||||
lockID: lockID,
|
||||
pix: pixData,
|
||||
amount: Number(amount),
|
||||
tokenAddress: lockData[4] as `0x${string}`,
|
||||
sellerAddress: lockData[6] as `0x${string}`,
|
||||
};
|
||||
};
|
||||
|
||||
|
@ -15,7 +15,7 @@ import { useUser } from "@/composables/useUser";
|
||||
let publicClient: PublicClient | null = null;
|
||||
let walletClient: WalletClient | null = null;
|
||||
|
||||
const getPublicClient: PublicClient | null = (onlyRpcProvider = false) => {
|
||||
const getPublicClient = (onlyRpcProvider = false): PublicClient | null => {
|
||||
if (onlyRpcProvider) {
|
||||
const user = useUser();
|
||||
const rpcUrl = getProviderUrl();
|
||||
@ -28,7 +28,7 @@ const getPublicClient: PublicClient | null = (onlyRpcProvider = false) => {
|
||||
return publicClient;
|
||||
};
|
||||
|
||||
const getWalletClient: WalletClient | null = () => {
|
||||
const getWalletClient = (): WalletClient | null => {
|
||||
return walletClient;
|
||||
};
|
||||
|
||||
@ -38,13 +38,16 @@ const getContract = async (onlyRpcProvider = false) => {
|
||||
const abi = p2pix.abi;
|
||||
const wallet = getWalletClient();
|
||||
|
||||
if (!client) {
|
||||
throw new Error("Public client not initialized");
|
||||
}
|
||||
|
||||
const [account] = wallet ? await wallet.getAddresses() : [""];
|
||||
|
||||
return { address, abi, client, wallet, account };
|
||||
};
|
||||
|
||||
const connectProvider = async (p: any): Promise<void> => {
|
||||
console.log("Connecting to wallet provider...");
|
||||
const user = useUser();
|
||||
const chain =
|
||||
Number(user.networkName.value) === sepolia.id ? sepolia : rootstock;
|
||||
|
@ -1,6 +1,7 @@
|
||||
import { getContract, getPublicClient, getWalletClient } from "./provider";
|
||||
import { getTokenAddress, getP2PixAddress } from "./addresses";
|
||||
import { parseEther, toHex } from "viem";
|
||||
import { sepolia, rootstock } from "viem/chains";
|
||||
|
||||
import mockToken from "../utils/smart_contract_files/MockToken.json";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
@ -24,20 +25,25 @@ const approveTokens = async (participant: Participant): Promise<any> => {
|
||||
|
||||
// Check if the token is already approved
|
||||
const allowance = await publicClient.readContract({
|
||||
address: tokenAddress,
|
||||
address: tokenAddress as `0x${string}`,
|
||||
abi: mockToken.abi,
|
||||
functionName: "allowance",
|
||||
args: [account, getP2PixAddress()],
|
||||
});
|
||||
|
||||
if (allowance < parseEther(participant.offer.toString())) {
|
||||
if ((allowance as bigint) < parseEther(participant.offer.toString())) {
|
||||
// Approve tokens
|
||||
const chain = user.networkId.value === sepolia.id ? sepolia : rootstock;
|
||||
const hash = await walletClient.writeContract({
|
||||
address: tokenAddress,
|
||||
address: tokenAddress as `0x${string}`,
|
||||
abi: mockToken.abi,
|
||||
functionName: "approve",
|
||||
args: [getP2PixAddress(), parseEther(participant.offer.toString())],
|
||||
args: [
|
||||
getP2PixAddress() as `0x${string}`,
|
||||
parseEther(participant.offer.toString()),
|
||||
],
|
||||
account,
|
||||
chain,
|
||||
});
|
||||
|
||||
await publicClient.waitForTransactionReceipt({ hash });
|
||||
@ -59,19 +65,23 @@ const addDeposit = async (): Promise<any> => {
|
||||
|
||||
const sellerId = await createParticipant(user.seller.value);
|
||||
user.setSellerId(sellerId.id);
|
||||
|
||||
if (!sellerId.id) {
|
||||
throw new Error("Failed to create participant");
|
||||
}
|
||||
const chain = user.networkId.value === sepolia.id ? sepolia : rootstock;
|
||||
const hash = await walletClient.writeContract({
|
||||
address,
|
||||
address: address as `0x${string}`,
|
||||
abi,
|
||||
functionName: "deposit",
|
||||
args: [
|
||||
user.networkId + "-" + sellerId.id,
|
||||
user.networkId.value + "-" + sellerId.id,
|
||||
toHex("", { size: 32 }),
|
||||
getTokenAddress(user.selectedToken.value),
|
||||
getTokenAddress(user.selectedToken.value) as `0x${string}`,
|
||||
parseEther(user.seller.value.offer.toString()),
|
||||
true,
|
||||
],
|
||||
account,
|
||||
chain,
|
||||
});
|
||||
|
||||
const receipt = await client.waitForTransactionReceipt({ hash });
|
||||
|
@ -1,17 +1,14 @@
|
||||
import { decodeEventLog, formatEther, type Log } from "viem";
|
||||
import { formatEther } from "viem";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
|
||||
import { getPublicClient, getWalletClient, getContract } from "./provider";
|
||||
import { getTokenAddress } from "./addresses";
|
||||
|
||||
import p2pix from "@/utils/smart_contract_files/P2PIX.json";
|
||||
|
||||
import { getValidDeposits } from "./events";
|
||||
|
||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||
import type { WalletTransaction } from "@/model/WalletTransaction";
|
||||
import type { UnreleasedLock } from "@/model/UnreleasedLock";
|
||||
import type { Pix } from "@/model/Pix";
|
||||
import { getNetworkSubgraphURL } from "@/model/NetworkEnum";
|
||||
|
||||
export const updateWalletStatus = async (): Promise<void> => {
|
||||
@ -55,54 +52,12 @@ export const listValidDepositTransactionsByWalletAddress = async (
|
||||
const getLockStatus = async (id: bigint): Promise<number> => {
|
||||
const { address, abi, client } = await getContract();
|
||||
const result = await client.readContract({
|
||||
address,
|
||||
address: address as `0x${string}`,
|
||||
abi,
|
||||
functionName: "getLocksStatus",
|
||||
args: [[id]],
|
||||
});
|
||||
return result[1][0];
|
||||
};
|
||||
|
||||
const filterLockStatus = async (
|
||||
transactions: Log[]
|
||||
): Promise<WalletTransaction[]> => {
|
||||
const txs: WalletTransaction[] = [];
|
||||
|
||||
for (const transaction of transactions) {
|
||||
try {
|
||||
const decoded = decodeEventLog({
|
||||
abi: p2pix.abi,
|
||||
data: transaction.data,
|
||||
topics: transaction.topics,
|
||||
});
|
||||
|
||||
if (!decoded || !decoded.args) continue;
|
||||
|
||||
// Type assertion to handle the args safely
|
||||
const args = decoded.args as Record<string, any>;
|
||||
|
||||
const tx: WalletTransaction = {
|
||||
token: args.token ? String(args.token) : "",
|
||||
blockNumber: Number(transaction.blockNumber),
|
||||
amount: args.amount ? Number(formatEther(args.amount)) : -1,
|
||||
seller: args.seller ? String(args.seller) : "",
|
||||
buyer: args.buyer ? String(args.buyer) : "",
|
||||
event: decoded.eventName || "",
|
||||
lockStatus:
|
||||
decoded.eventName == "LockAdded" && args.lockID
|
||||
? await getLockStatus(args.lockID)
|
||||
: -1,
|
||||
transactionHash: transaction.transactionHash
|
||||
? transaction.transactionHash
|
||||
: "",
|
||||
transactionID: args.lockID ? args.lockID.toString() : "",
|
||||
};
|
||||
txs.push(tx);
|
||||
} catch (error) {
|
||||
console.error("Error decoding log", error);
|
||||
}
|
||||
}
|
||||
return txs;
|
||||
return (result as any)[1][0] as number;
|
||||
};
|
||||
|
||||
export const listAllTransactionByWalletAddress = async (
|
||||
@ -118,6 +73,7 @@ export const listAllTransactionByWalletAddress = async (
|
||||
query: `
|
||||
{
|
||||
depositAddeds(where: {seller: "${walletAddress.toLowerCase()}"}) {
|
||||
id
|
||||
seller
|
||||
token
|
||||
amount
|
||||
@ -129,7 +85,6 @@ export const listAllTransactionByWalletAddress = async (
|
||||
buyer
|
||||
lockID
|
||||
seller
|
||||
token
|
||||
amount
|
||||
blockTimestamp
|
||||
blockNumber
|
||||
@ -138,7 +93,6 @@ export const listAllTransactionByWalletAddress = async (
|
||||
lockReleaseds(where: {buyer: "${walletAddress.toLowerCase()}"}) {
|
||||
buyer
|
||||
lockId
|
||||
e2eId
|
||||
blockTimestamp
|
||||
blockNumber
|
||||
transactionHash
|
||||
@ -155,7 +109,6 @@ export const listAllTransactionByWalletAddress = async (
|
||||
`,
|
||||
};
|
||||
|
||||
console.log("Fetching transactions from subgraph");
|
||||
const response = await fetch(getNetworkSubgraphURL(network), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@ -165,14 +118,12 @@ export const listAllTransactionByWalletAddress = async (
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
console.log("Subgraph data fetched:", data);
|
||||
|
||||
console.log("Subgraph data:", data);
|
||||
// Convert all transactions to common WalletTransaction format
|
||||
const transactions: WalletTransaction[] = [];
|
||||
|
||||
// Process deposit added events
|
||||
if (data.data?.depositAddeds) {
|
||||
console.log("Processing deposit events");
|
||||
for (const deposit of data.data.depositAddeds) {
|
||||
transactions.push({
|
||||
token: deposit.token,
|
||||
@ -189,7 +140,6 @@ export const listAllTransactionByWalletAddress = async (
|
||||
|
||||
// Process lock added events
|
||||
if (data.data?.lockAddeds) {
|
||||
console.log("Processing lock events");
|
||||
for (const lock of data.data.lockAddeds) {
|
||||
// Get lock status from the contract
|
||||
const lockStatus = await getLockStatus(BigInt(lock.lockID));
|
||||
@ -210,7 +160,6 @@ export const listAllTransactionByWalletAddress = async (
|
||||
|
||||
// Process lock released events
|
||||
if (data.data?.lockReleaseds) {
|
||||
console.log("Processing release events");
|
||||
for (const release of data.data.lockReleaseds) {
|
||||
transactions.push({
|
||||
token: "", // 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
|
||||
if (data.data?.depositWithdrawns) {
|
||||
console.log("Processing withdrawal events");
|
||||
for (const withdrawal of data.data.depositWithdrawns) {
|
||||
transactions.push({
|
||||
token: withdrawal.token,
|
||||
@ -325,7 +273,6 @@ const listLockTransactionByWalletAddress = async (walletAddress: string) => {
|
||||
buyer
|
||||
lockID
|
||||
seller
|
||||
token
|
||||
amount
|
||||
blockTimestamp
|
||||
blockNumber
|
||||
@ -386,7 +333,6 @@ const listLockTransactionByWalletAddress = async (walletAddress: string) => {
|
||||
const listLockTransactionBySellerAddress = async (sellerAddress: string) => {
|
||||
const user = useUser();
|
||||
const network = user.networkName.value;
|
||||
console.log("Will get locks as seller", sellerAddress);
|
||||
|
||||
// Query subgraph for lock added transactions where seller matches
|
||||
const subgraphQuery = {
|
||||
@ -459,10 +405,6 @@ export const checkUnreleasedLock = async (
|
||||
walletAddress: string
|
||||
): Promise<UnreleasedLock | undefined> => {
|
||||
const { address, abi, client } = await getContract();
|
||||
const pixData: Pix = {
|
||||
pixKey: "",
|
||||
};
|
||||
|
||||
const addedLocks = await listLockTransactionByWalletAddress(walletAddress);
|
||||
|
||||
if (!addedLocks.length) return undefined;
|
||||
@ -470,34 +412,43 @@ export const checkUnreleasedLock = async (
|
||||
const lockIds = addedLocks.map((lock: any) => lock.args.lockID);
|
||||
|
||||
const lockStatus = await client.readContract({
|
||||
address,
|
||||
address: address as `0x${string}`,
|
||||
abi,
|
||||
functionName: "getLocksStatus",
|
||||
args: [lockIds],
|
||||
});
|
||||
|
||||
const unreleasedLockId = lockStatus[1].findIndex(
|
||||
const lockStatusResult = lockStatus as [bigint[], number[]];
|
||||
const unreleasedLockId = lockStatusResult[1].findIndex(
|
||||
(status: number) => status == 1
|
||||
);
|
||||
|
||||
if (unreleasedLockId !== -1) {
|
||||
const lockID = lockStatus[0][unreleasedLockId];
|
||||
const lockID = lockStatusResult[0][unreleasedLockId];
|
||||
|
||||
const lock = await client.readContract({
|
||||
address,
|
||||
address: address as `0x${string}`,
|
||||
abi,
|
||||
functionName: "mapLocks",
|
||||
args: [lockID],
|
||||
});
|
||||
|
||||
const pixTarget = lock.pixTarget;
|
||||
const amount = formatEther(lock.amount);
|
||||
pixData.pixKey = pixTarget;
|
||||
pixData.value = Number(amount);
|
||||
const lockData = lock as [
|
||||
bigint,
|
||||
string,
|
||||
string,
|
||||
bigint,
|
||||
string,
|
||||
string,
|
||||
string
|
||||
];
|
||||
const amount = formatEther(lockData[0]);
|
||||
|
||||
return {
|
||||
lockID,
|
||||
pix: pixData,
|
||||
lockID: lockID.toString(),
|
||||
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 lockStatus = await client.readContract({
|
||||
address,
|
||||
address: address as `0x${string}`,
|
||||
abi,
|
||||
functionName: "getLocksStatus",
|
||||
args: [lockIds],
|
||||
});
|
||||
|
||||
const mapLocksRequests = lockStatus[0].map((id: bigint) =>
|
||||
const lockStatusResult = lockStatus as [bigint[], number[]];
|
||||
const mapLocksRequests = lockStatusResult[0].map((id: bigint) =>
|
||||
client.readContract({
|
||||
address,
|
||||
address: address as `0x${string}`,
|
||||
abi,
|
||||
functionName: "mapLocks",
|
||||
args: [id],
|
||||
@ -533,9 +485,24 @@ export const getActiveLockAmount = async (
|
||||
});
|
||||
|
||||
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;
|
||||
}, 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;
|
||||
};
|
||||
|
@ -1,12 +1,7 @@
|
||||
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,
|
||||
|
@ -19,7 +19,7 @@ if (props.isRedirectModal) {
|
||||
<template>
|
||||
<div>
|
||||
<div
|
||||
class="modal-overlay inset-0 fixed justify-center backdrop-blur-sm sm:backdrop-blur-none"
|
||||
class="modal-overlay inset-0 fixed hidden md:block justify-center backdrop-blur-sm sm:backdrop-blur-none"
|
||||
v-if="!isRedirectModal"
|
||||
>
|
||||
<div class="modal px-5 text-center">
|
||||
|
@ -7,7 +7,6 @@ import { ref, watch, onMounted } from "vue";
|
||||
import SpinnerComponent from "../SpinnerComponent.vue";
|
||||
import { decimalCount } from "@/utils/decimalCount";
|
||||
import { debounce } from "@/utils/debounce";
|
||||
import { getTokenByAddress } from "@/blockchain/addresses";
|
||||
import { useFloating, arrow, offset, flip, shift } from "@floating-ui/vue";
|
||||
|
||||
const user = useUser();
|
||||
@ -174,12 +173,12 @@ showInitialItems();
|
||||
Saldo disponível
|
||||
</p>
|
||||
<p class="text-xl leading-7 font-semibold text-gray-900">
|
||||
{{ getRemaining() }} {{ etherStore.selectedToken }}
|
||||
{{ getRemaining() }} {{ user.selectedToken.value }}
|
||||
</p>
|
||||
<div class="flex gap-2 w-32 sm:w-56" v-if="activeLockAmount != 0">
|
||||
<span class="text-xs font-normal text-gray-400" ref="infoText">{{
|
||||
`com ${activeLockAmount.toFixed(2)} ${
|
||||
etherStore.selectedToken
|
||||
user.selectedToken.value
|
||||
} em lock`
|
||||
}}</span>
|
||||
<div
|
||||
@ -283,10 +282,10 @@ showInitialItems();
|
||||
class="text-xl sm:text-xl leading-7 font-semibold text-gray-900"
|
||||
>
|
||||
{{ item.amount }}
|
||||
{{ getTokenByAddress(item.token) }}
|
||||
<!-- {{ getTokenByAddress(item.token) }} -->
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<div class="flex flex-col items-center justify-center">
|
||||
<div
|
||||
class="bg-amber-300 status-text"
|
||||
v-if="getEventName(item.event) == 'Reserva' && item.lockStatus == 1"
|
||||
@ -409,6 +408,7 @@ p {
|
||||
}
|
||||
|
||||
input[type="number"] {
|
||||
appearance: textfield;
|
||||
-moz-appearance: textfield;
|
||||
}
|
||||
|
||||
|
@ -1,28 +1,54 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onUnmounted, ref } from "vue";
|
||||
import { ref, onMounted } from "vue";
|
||||
import CustomButton from "@/components/CustomButton/CustomButton.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 isPixValid = ref<boolean>(false);
|
||||
const showWarnModal = ref<boolean>(true);
|
||||
const releaseSignature = ref<string>("");
|
||||
const solicitationData = ref<any>(null);
|
||||
|
||||
// Emits
|
||||
const emit = defineEmits(["pixValidated"]);
|
||||
|
||||
onMounted(() => {
|
||||
window.addEventListener(
|
||||
"resize",
|
||||
() => (windowSize.value = window.innerWidth)
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const { tokenAddress, sellerAddress, amount } = await getUnreleasedLockById(
|
||||
props.lockID
|
||||
);
|
||||
});
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener(
|
||||
"resize",
|
||||
() => (windowSize.value = window.innerWidth)
|
||||
|
||||
const participantId = await getSellerParticipantId(
|
||||
sellerAddress as `0x${string}`,
|
||||
tokenAddress
|
||||
);
|
||||
|
||||
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>
|
||||
|
||||
@ -65,7 +91,7 @@ onUnmounted(() => {
|
||||
/>
|
||||
</div>
|
||||
<CustomModal
|
||||
v-if="showWarnModal && windowSize <= 500"
|
||||
v-if="showWarnModal"
|
||||
@close-modal="showWarnModal = false"
|
||||
:isRedirectModal="false"
|
||||
/>
|
||||
@ -122,6 +148,7 @@ h2 {
|
||||
}
|
||||
|
||||
input[type="number"] {
|
||||
appearance: textfield;
|
||||
-moz-appearance: textfield;
|
||||
}
|
||||
|
||||
|
@ -1,15 +1,8 @@
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { describe, it, expect } 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");
|
||||
@ -20,13 +13,6 @@ describe("TopBar.vue", () => {
|
||||
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");
|
||||
|
@ -1,6 +1,8 @@
|
||||
import type { Pix } from "./Pix";
|
||||
import { Address } from "viem";
|
||||
|
||||
export type UnreleasedLock = {
|
||||
lockID: string;
|
||||
pix: Pix;
|
||||
sellerAddress?: Address;
|
||||
tokenAddress: Address;
|
||||
amount: number;
|
||||
};
|
||||
|
@ -17,7 +17,6 @@ export interface ParticipantWithID extends Participant {
|
||||
|
||||
export interface Offer {
|
||||
amount: number;
|
||||
lockId: string;
|
||||
sellerId: string;
|
||||
}
|
||||
|
||||
@ -41,11 +40,18 @@ export const createParticipant = async (participant: Participant) => {
|
||||
codigoIspb: participant.bankIspb,
|
||||
}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Error creating participant: ${response.statusText}`);
|
||||
}
|
||||
const data = await response.json();
|
||||
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) => {
|
||||
console.log("Creating solicitation", offer);
|
||||
const response = await fetch(`${import.meta.env.VITE_APP_API_URL}/request`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@ -53,7 +59,7 @@ export const createSolicitation = async (offer: Offer) => {
|
||||
},
|
||||
body: JSON.stringify({
|
||||
amount: offer.amount,
|
||||
pixTarget: offer.sellerId,
|
||||
pixTarget: offer.sellerId.split("-").pop(),
|
||||
}),
|
||||
});
|
||||
return response.json();
|
||||
|
@ -74,11 +74,11 @@ const releaseTransaction = async (lockId: string) => {
|
||||
};
|
||||
|
||||
const checkForUnreleasedLocks = async (): Promise<void> => {
|
||||
const walletLocks = await checkUnreleasedLock(walletAddress.value);
|
||||
if (walletLocks) {
|
||||
lockID.value = walletLocks.lockID;
|
||||
tokenAmount.value = walletLocks.pix.value;
|
||||
pixTarget.value = walletLocks.pix.pixKey;
|
||||
const lock = await checkUnreleasedLock(walletAddress.value);
|
||||
if (lock) {
|
||||
lockID.value = lock.lockID;
|
||||
tokenAmount.value = lock.amount;
|
||||
pixTarget.value = lock.sellerAddress;
|
||||
showModal.value = true;
|
||||
} else {
|
||||
flowStep.value = Step.Search;
|
||||
@ -90,8 +90,8 @@ if (paramLockID) {
|
||||
const lockToRedirect = await getUnreleasedLockById(paramLockID as string);
|
||||
if (lockToRedirect) {
|
||||
lockID.value = lockToRedirect.lockID;
|
||||
tokenAmount.value = lockToRedirect.pix.value;
|
||||
pixTarget.value = lockToRedirect.pix.pixKey;
|
||||
tokenAmount.value = lockToRedirect.amount;
|
||||
pixTarget.value = lockToRedirect.sellerAddress;
|
||||
flowStep.value = Step.Buy;
|
||||
} else {
|
||||
flowStep.value = Step.Search;
|
||||
@ -135,7 +135,8 @@ onMounted(async () => {
|
||||
<div v-if="flowStep == Step.Buy">
|
||||
<QrCodeComponent
|
||||
:sellerId="String(pixTarget)"
|
||||
:amount="tokenAmount"
|
||||
:amount="tokenAmount || 0"
|
||||
:lockID="lockID"
|
||||
@pix-validated="releaseTransaction"
|
||||
v-if="!loadingLock"
|
||||
/>
|
||||
|
Loading…
x
Reference in New Issue
Block a user