fix type errors

This commit is contained in:
hueso 2025-06-22 01:17:10 -03:00
parent 73ba77ca4f
commit 9d9ed7a3dd
7 changed files with 86 additions and 36 deletions

View File

@ -3,7 +3,7 @@ import { NetworkEnum, TokenEnum } from "@/model/NetworkEnum";
import { createPublicClient, http } from "viem"; import { createPublicClient, http } 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]: `0x${string}` } } = {
[NetworkEnum.sepolia]: { [NetworkEnum.sepolia]: {
BRZ: "0x3eBE67A2C7bdB2081CBd34ba3281E90377462289", BRZ: "0x3eBE67A2C7bdB2081CBd34ba3281E90377462289",
// BRX: "0x3eBE67A2C7bdB2081CBd34ba3281E90377462289", // BRX: "0x3eBE67A2C7bdB2081CBd34ba3281E90377462289",
@ -28,14 +28,14 @@ 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];
}; };
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]: `0x${string}` } = {
[NetworkEnum.sepolia]: "0xb7cD135F5eFD9760981e02E2a898790b688939fe", [NetworkEnum.sepolia]: "0xb7cD135F5eFD9760981e02E2a898790b688939fe",
[NetworkEnum.rootstock]: "0x98ba35eb14b38D6Aa709338283af3e922476dE34", [NetworkEnum.rootstock]: "0x98ba35eb14b38D6Aa709338283af3e922476dE34",
}; };

View File

@ -8,7 +8,7 @@ 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());
const { request } = await client.simulateContract({ const { request } = await client.simulateContract({
@ -16,19 +16,31 @@ export const addLock = async (
abi, abi,
functionName: "lock", functionName: "lock",
args: [sellerAddress, tokenAddress, parsedAmount, [], []], args: [sellerAddress, tokenAddress, parsedAmount, [], []],
account,
}); });
console.log(wallet); console.log(wallet);
if (!wallet) {
throw new Error("Wallet is undefined");
}
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);
const topic = receipt.logs[0]?.topics[2];
if (!topic) {
throw new Error("Topic is undefined");
}
return topic;
}; };
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();
const tokenAddress = getTokenAddress(token); const tokenAddress = getTokenAddress(token);
@ -37,24 +49,38 @@ export const withdrawDeposit = async (
abi, abi,
functionName: "withdraw", functionName: "withdraw",
args: [tokenAddress, parseEther(amount), []], args: [tokenAddress, parseEther(amount), []],
account
}); });
if (!wallet) {
throw new Error("Wallet is undefined");
}
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; if ( receipt.status == "success"){
return true;
} else {
return false;
}
}; };
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();
const { request } = await client.simulateContract({ const { request } = await client.simulateContract({
address, address,
abi, abi,
functionName: "release", functionName: "release",
args: [solicitation.lockId, solicitation.e2eId], args: [solicitation.lockId, solicitation.e2eId],
account
}); });
if (!wallet) {
throw new Error("Wallet is undefined");
}
const hash = await wallet.writeContract(request); const hash = await wallet.writeContract(request);
return client.waitForTransactionReceipt({ hash }); return client.waitForTransactionReceipt({ hash });
}; };

View File

@ -1,5 +1,5 @@
import { useUser } from "@/composables/useUser"; import { useUser } from "@/composables/useUser";
import { formatEther, toHex, type PublicClient } from "viem"; import { formatEther, toHex, type PublicClient, type ByteArray } from "viem";
import p2pix from "@/utils/smart_contract_files/P2PIX.json"; import p2pix from "@/utils/smart_contract_files/P2PIX.json";
import { getContract } from "./provider"; import { getContract } from "./provider";
@ -9,6 +9,28 @@ import { getNetworkSubgraphURL, NetworkEnum } from "@/model/NetworkEnum";
import type { UnreleasedLock } from "@/model/UnreleasedLock"; import type { UnreleasedLock } from "@/model/UnreleasedLock";
import type { Pix } from "@/model/Pix"; import type { Pix } from "@/model/Pix";
export interface Lock { // from DataTypes.sol
counter: bigint;
expirationBlock: bigint;
pixTarget: string;
amount: bigint;
token: `0x${string}`;
buyerAddress: `0x${string}`;
seller: `0x${string}`;
}
export enum LockStatus {
Inexistent = 0, // Uninitialized Lock
Active = 1, // Valid Lock
Expired = 2, // Expired Lock
Released = 3 // Already released Lock
}
export interface GetLocksStatusResponse {
sortedIDs: number[];
status: LockStatus[];
}
const getNetworksLiquidity = async (): Promise<void> => { const getNetworksLiquidity = async (): Promise<void> => {
const user = useUser(); const user = useUser();
user.setLoadingNetworkLiquidity(true); user.setLoadingNetworkLiquidity(true);
@ -38,7 +60,7 @@ const getPixKey = async (seller: string, token: string): Promise<string> => {
abi, abi,
functionName: "getPixTarget", functionName: "getPixTarget",
args: [seller, token], args: [seller, token],
}); }) as ByteArray;
// Remove '0x' prefix and convert hex to UTF-8 string // Remove '0x' prefix and convert hex to UTF-8 string
const hexString = const hexString =
@ -156,7 +178,7 @@ const getUnreleasedLockById = async (
abi, abi,
functionName: "mapLocks", functionName: "mapLocks",
args: [BigInt(lockID)], args: [BigInt(lockID)],
}); }) as Lock;
const pixTarget = lock.pixTarget; const pixTarget = lock.pixTarget;
const amount = formatEther(lock.amount); const amount = formatEther(lock.amount);

View File

@ -11,12 +11,10 @@ import {
} from "viem"; } from "viem";
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 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,21 +22,22 @@ 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();
if (!client) {
throw new Error("Public client is not initialized");
}
const address = getP2PixAddress(); const address = getP2PixAddress();
const abi = p2pix.abi; const abi = p2pix.abi;
const wallet = getWalletClient(); const wallet = getWalletClient();
const [account] = wallet ? await wallet.getAddresses() : [""]; const [account] = wallet ? await wallet.getAddresses() : [null];
return { address, abi, client, wallet, account }; return { address, abi, client, wallet, account };
}; };

View File

@ -28,18 +28,19 @@ const approveTokens = async (participant: Participant): Promise<any> => {
abi: mockToken.abi, abi: mockToken.abi,
functionName: "allowance", functionName: "allowance",
args: [account, getP2PixAddress()], args: [account, getP2PixAddress()],
}); }) as bigint;
if (allowance < parseEther(participant.offer.toString())) { if (allowance < parseEther(participant.offer.toString())) {
// Approve tokens // Approve tokens
const hash = await walletClient.writeContract({ const { result } = await publicClient.simulateContract({
address: tokenAddress, address: tokenAddress,
abi: mockToken.abi, abi: mockToken.abi,
functionName: "approve", functionName: "approve",
args: [getP2PixAddress(), parseEther(participant.offer.toString())], args: [getP2PixAddress(), parseEther(participant.offer.toString())],
account, account
}); });
const hash = await walletClient.writeContract(result);
await publicClient.waitForTransactionReceipt({ hash }); await publicClient.waitForTransactionReceipt({ hash });
return true; return true;
} }
@ -48,6 +49,7 @@ const approveTokens = async (participant: Participant): Promise<any> => {
const addDeposit = async (): Promise<any> => { const addDeposit = async (): Promise<any> => {
const { address, abi, client } = await getContract(); const { address, abi, client } = await getContract();
const publicClient = getPublicClient();
const walletClient = getWalletClient(); const walletClient = getWalletClient();
const user = useUser(); const user = useUser();
@ -60,7 +62,7 @@ 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);
const hash = await walletClient.writeContract({ const { result } = await publicClient.simulateContract({
address, address,
abi, abi,
functionName: "deposit", functionName: "deposit",
@ -74,6 +76,7 @@ const addDeposit = async (): Promise<any> => {
account, account,
}); });
const hash = await walletClient.writeContract(result);
const receipt = await client.waitForTransactionReceipt({ hash }); const receipt = await client.waitForTransactionReceipt({ hash });
return receipt; return receipt;
}; };

View File

@ -6,7 +6,7 @@ import { getTokenAddress } from "./addresses";
import p2pix from "@/utils/smart_contract_files/P2PIX.json"; import p2pix from "@/utils/smart_contract_files/P2PIX.json";
import { getValidDeposits } from "./events"; import { getValidDeposits, Lock, LockStatus, GetLocksStatusResponse } 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";
@ -52,15 +52,15 @@ 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]],
}); }) as GetLocksStatusResponse;
return result[1][0]; return status[0];
}; };
const filterLockStatus = async ( const filterLockStatus = async (
@ -469,12 +469,12 @@ 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 { sortedIDs, status: lockStatus } = await client.readContract({
address, address,
abi, abi,
functionName: "getLocksStatus", functionName: "getLocksStatus",
args: [lockIds], args: [lockIds],
}); }) as GetLocksStatusResponse;
const unreleasedLockId = lockStatus[1].findIndex( const unreleasedLockId = lockStatus[1].findIndex(
(status: number) => status == 1 (status: number) => status == 1
@ -488,7 +488,7 @@ export const checkUnreleasedLock = async (
abi, abi,
functionName: "mapLocks", functionName: "mapLocks",
args: [lockID], args: [lockID],
}); }) as Lock;
const pixTarget = lock.pixTarget; const pixTarget = lock.pixTarget;
const amount = formatEther(lock.amount); const amount = formatEther(lock.amount);
@ -512,12 +512,12 @@ 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: lockStatus } = await client.readContract({
address, address,
abi, abi,
functionName: "getLocksStatus", functionName: "getLocksStatus",
args: [lockIds], args: [lockIds],
}); }) as GetLocksStatusResponse;
const mapLocksRequests = lockStatus[0].map((id: bigint) => const mapLocksRequests = lockStatus[0].map((id: bigint) =>
client.readContract({ client.readContract({

View File

@ -174,12 +174,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.networkName.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.networkName.value
} em lock` } em lock`
}}</span> }}</span>
<div <div