Stronger typings💪

This commit is contained in:
hueso
2025-06-29 18:19:30 -03:00
parent 2370051243
commit dd351acb2e
24 changed files with 2424 additions and 12561 deletions

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 { NetworkEnum, TokenEnum } from "@/model/NetworkEnum";
import { createPublicClient, http } from "viem";
import { createPublicClient, http, type Address } from "viem";
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]: {
BRZ: "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 networksTokens = Tokens[user.networkName.value];
for (const [token, tokenAddress] of Object.entries(networksTokens)) {
@@ -28,23 +28,23 @@ export const getTokenByAddress = (address: string) => {
export const getTokenAddress = (
token: TokenEnum,
network?: NetworkEnum
): `0x${string}` => {
): Address => {
const user = useUser();
return Tokens[network ? network : user.networkName.value][
token
] as `0x${string}`;
];
};
export const getP2PixAddress = (network?: NetworkEnum): `0x${string}` => {
export const getP2PixAddress = (network?: NetworkEnum): Address => {
const user = useUser();
const possibleP2PixAddresses: { [key in NetworkEnum]: string } = {
const possibleP2PixAddresses: { [key in NetworkEnum]: Address } = {
[NetworkEnum.sepolia]: "0xb7cD135F5eFD9760981e02E2a898790b688939fe",
[NetworkEnum.rootstock]: "0x98ba35eb14b38D6Aa709338283af3e922476dE34",
};
return possibleP2PixAddresses[
network ? network : user.networkName.value
] as `0x${string}`;
];
};
export const getProviderUrl = (network?: NetworkEnum): string => {

View File

@@ -9,14 +9,15 @@ import {
stringToBytes,
stringToHex,
toBytes,
type Address,
} from "viem";
import type { TokenEnum } from "@/model/NetworkEnum";
export const addLock = async (
sellerAddress: string,
tokenAddress: string,
sellerAddress: Address,
tokenAddress: Address,
amount: number
): Promise<string> => {
): Promise<bigint> => {
const { address, abi, wallet, client, account } = await getContract();
const parsedAmount = parseEther(amount.toString());
@@ -24,17 +25,20 @@ export const addLock = async (
throw new Error("Wallet not connected");
}
const { request } = await client.simulateContract({
address: address as `0x${string}`,
const { result, request } = await client.simulateContract({
address,
abi,
functionName: "lock",
args: [sellerAddress, tokenAddress as `0x${string}`, parsedAmount, [], []],
account: account as `0x${string}`,
args: [sellerAddress, tokenAddress, parsedAmount, [], []],
account,
});
const hash = await wallet.writeContract(request);
const receipt = await client.waitForTransactionReceipt({ hash });
return receipt.status === "success" ? receipt.logs[0].topics[2] ?? "" : "";
if (!receipt.status)
throw new Error("Transaction failed: " + receipt.transactionHash);
return result;
};
export const withdrawDeposit = async (
@@ -50,11 +54,11 @@ export const withdrawDeposit = async (
const tokenAddress = getTokenAddress(token);
const { request } = await client.simulateContract({
address: address as `0x${string}`,
address,
abi,
functionName: "withdraw",
args: [tokenAddress as `0x${string}`, parseEther(amount), []],
account: account as `0x${string}`,
args: [tokenAddress, parseEther(amount), []],
account
});
const hash = await wallet.writeContract(request);
@@ -64,7 +68,7 @@ export const withdrawDeposit = async (
};
export const releaseLock = async (
lockID: string,
lockID: bigint,
pixtarget: string,
signature: string
): Promise<any> => {
@@ -76,14 +80,14 @@ export const releaseLock = async (
}
// Convert pixtarget to bytes32
const pixTimestamp = keccak256(stringToBytes(pixtarget));
const pixTimestamp = keccak256(stringToHex(pixtarget, { size: 32 }) );
const { request } = await client.simulateContract({
address: address as `0x${string}`,
address,
abi,
functionName: "release",
args: [BigInt(lockID), pixTimestamp, signature],
account: account as `0x${string}`,
args: [BigInt(lockID), pixTimestamp, stringToHex(signature)],
account
});
const hash = await wallet.writeContract(request);

View File

@@ -1,12 +1,14 @@
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 type { ValidDeposit } from "@/model/ValidDeposit";
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 { LockStatus } from "@/model/LockStatus"
const getNetworksLiquidity = async (): Promise<void> => {
const user = useUser();
@@ -36,7 +38,7 @@ const getParticipantID = async (
const { address, abi, client } = await getContract();
const participantIDHex = await client.readContract({
address: address as `0x${string}`,
address,
abi,
functionName: "getPixTarget",
args: [seller, token],
@@ -59,15 +61,15 @@ const getParticipantID = async (
};
const getValidDeposits = async (
token: string,
token: Address,
network: NetworkEnum,
contractInfo?: { client: any; address: string }
contractInfo?: { client: PublicClient; address: Address }
): Promise<ValidDeposit[]> => {
let client: PublicClient, abi;
if (contractInfo) {
({ client } = contractInfo);
abi = p2pix.abi;
abi = p2PixAbi;
} else {
({ abi, client } = await getContract(true));
}
@@ -100,11 +102,11 @@ const getValidDeposits = async (
const depositData = await depositLogs.json();
const depositAddeds = depositData.data.depositAddeds;
const uniqueSellers = depositAddeds.reduce(
(acc: Record<string, boolean>, deposit: any) => {
(acc: Record<Address, boolean>, deposit: any) => {
acc[deposit.seller] = true;
return acc;
},
{} as Record<string, boolean>
{} as Record<Address, boolean>
);
if (!contractInfo) {
@@ -114,10 +116,10 @@ const getValidDeposits = async (
const depositList: { [key: string]: ValidDeposit } = {};
const sellersList = Object.keys(uniqueSellers);
const sellersList = Object.keys(uniqueSellers) as Address[];
// Use multicall to batch all getBalance requests
const balanceCalls = sellersList.map((seller) => ({
address: getP2PixAddress(network) as `0x${string}`,
address: getP2PixAddress(network),
abi,
functionName: "getBalance",
args: [seller, token],
@@ -133,10 +135,10 @@ const getValidDeposits = async (
if (!mappedBalance.error && mappedBalance.result) {
const validDeposit: ValidDeposit = {
token: token,
token,
blockNumber: 0,
remaining: Number(formatEther(mappedBalance.result as bigint)),
seller: seller,
seller,
network,
participantID: "",
};
@@ -147,34 +149,22 @@ const getValidDeposits = async (
};
const getUnreleasedLockById = async (
lockID: string
lockID: bigint
): Promise<UnreleasedLock> => {
const { address, abi, client } = await getContract();
const lock = await client.readContract({
address: address as `0x${string}`,
const [ , , , amount, token, seller ] = await client.readContract({
address,
abi,
functionName: "mapLocks",
args: [BigInt(lockID)],
args: [lockID],
});
// 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,
amount: Number(amount),
tokenAddress: lockData[4] as `0x${string}`,
sellerAddress: lockData[6] as `0x${string}`,
lockID,
amount: Number(formatEther(amount)),
tokenAddress: token,
sellerAddress: seller,
};
};

View File

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

View File

@@ -3,7 +3,7 @@ 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 { mockTokenAbi } from "./abi";
import { useUser } from "@/composables/useUser";
import { createParticipant } from "@/utils/bbPay";
import type { Participant } from "@/utils/bbPay";
@@ -25,23 +25,20 @@ const approveTokens = async (participant: Participant): Promise<any> => {
// Check if the token is already approved
const allowance = await publicClient.readContract({
address: tokenAddress as `0x${string}`,
abi: mockToken.abi,
address: tokenAddress,
abi: mockTokenAbi,
functionName: "allowance",
args: [account, getP2PixAddress()],
});
if ((allowance as bigint) < parseEther(participant.offer.toString())) {
if ( allowance < parseEther(participant.offer.toString()) ) {
// Approve tokens
const chain = user.networkId.value === sepolia.id ? sepolia : rootstock;
const hash = await walletClient.writeContract({
address: tokenAddress as `0x${string}`,
abi: mockToken.abi,
address: tokenAddress,
abi: mockTokenAbi,
functionName: "approve",
args: [
getP2PixAddress() as `0x${string}`,
parseEther(participant.offer.toString()),
],
args: [getP2PixAddress(), parseEther(participant.offer.toString())],
account,
chain,
});
@@ -70,13 +67,13 @@ const addDeposit = async (): Promise<any> => {
}
const chain = user.networkId.value === sepolia.id ? sepolia : rootstock;
const hash = await walletClient.writeContract({
address: address as `0x${string}`,
address,
abi,
functionName: "deposit",
args: [
user.networkId.value + "-" + sellerId.id,
toHex("", { size: 32 }),
getTokenAddress(user.selectedToken.value) as `0x${string}`,
getTokenAddress(user.selectedToken.value),
parseEther(user.seller.value.offer.toString()),
true,
],

View File

@@ -1,14 +1,15 @@
import { formatEther } from "viem";
import { formatEther, hexToString, type Address } from "viem";
import { useUser } from "@/composables/useUser";
import { getPublicClient, getWalletClient, getContract } from "./provider";
import { getTokenAddress } from "./addresses";
import { getValidDeposits } from "./events";
import { getValidDeposits, getUnreleasedLockById } from "./events";
import type { ValidDeposit } from "@/model/ValidDeposit";
import type { WalletTransaction } from "@/model/WalletTransaction";
import type { UnreleasedLock } from "@/model/UnreleasedLock";
import { LockStatus } from "@/model/LockStatus";
import { getNetworkSubgraphURL } from "@/model/NetworkEnum";
export const updateWalletStatus = async (): Promise<void> => {
@@ -31,7 +32,7 @@ export const updateWalletStatus = async (): Promise<void> => {
};
export const listValidDepositTransactionsByWalletAddress = async (
walletAddress: string
walletAddress: Address
): Promise<ValidDeposit[]> => {
const user = useUser();
const walletDeposits = await getValidDeposits(
@@ -49,19 +50,19 @@ export const listValidDepositTransactionsByWalletAddress = async (
return [];
};
const getLockStatus = async (id: bigint): Promise<number> => {
const getLockStatus = async (id: bigint): Promise<LockStatus> => {
const { address, abi, client } = await getContract();
const result = await client.readContract({
address: address as `0x${string}`,
const [ sortedIDs , status ] = await client.readContract({
address,
abi,
functionName: "getLocksStatus",
args: [[id]],
});
return (result as any)[1][0] as number;
return status[0];
};
export const listAllTransactionByWalletAddress = async (
walletAddress: string
walletAddress: Address
): Promise<WalletTransaction[]> => {
const user = useUser();
@@ -131,7 +132,7 @@ export const listAllTransactionByWalletAddress = async (
seller: deposit.seller,
buyer: "",
event: "DepositAdded",
lockStatus: -1,
lockStatus: undefined,
transactionHash: deposit.transactionHash,
});
}
@@ -161,13 +162,13 @@ export const listAllTransactionByWalletAddress = async (
if (data.data?.lockReleaseds) {
for (const release of data.data.lockReleaseds) {
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),
amount: -1, // Amount not available in this event
seller: "",
buyer: release.buyer,
event: "LockReleased",
lockStatus: -1,
lockStatus: undefined,
transactionHash: release.transactionHash,
transactionID: release.lockId.toString(),
});
@@ -184,7 +185,7 @@ export const listAllTransactionByWalletAddress = async (
seller: withdrawal.seller,
buyer: "",
event: "DepositWithdrawn",
lockStatus: -1,
lockStatus: undefined,
transactionHash: withdrawal.transactionHash,
});
}
@@ -196,7 +197,7 @@ export const listAllTransactionByWalletAddress = async (
// get wallet's release transactions
export const listReleaseTransactionByWalletAddress = async (
walletAddress: string
walletAddress: Address
) => {
const user = useUser();
const network = user.networkName.value;
@@ -260,7 +261,7 @@ export const listReleaseTransactionByWalletAddress = async (
.filter((decoded: any) => decoded !== null);
};
const listLockTransactionByWalletAddress = async (walletAddress: string) => {
const listLockTransactionByWalletAddress = async (walletAddress: Address) => {
const user = useUser();
const network = user.networkName.value;
@@ -329,7 +330,7 @@ const listLockTransactionByWalletAddress = async (walletAddress: string) => {
}
};
const listLockTransactionBySellerAddress = async (sellerAddress: string) => {
const listLockTransactionBySellerAddress = async (sellerAddress: Address) => {
const user = useUser();
const network = user.networkName.value;
@@ -401,7 +402,7 @@ const listLockTransactionBySellerAddress = async (sellerAddress: string) => {
};
export const checkUnreleasedLock = async (
walletAddress: string
walletAddress: Address
): Promise<UnreleasedLock | undefined> => {
const { address, abi, client } = await getContract();
const addedLocks = await listLockTransactionByWalletAddress(walletAddress);
@@ -410,50 +411,23 @@ export const checkUnreleasedLock = async (
const lockIds = addedLocks.map((lock: any) => lock.args.lockID);
const lockStatus = await client.readContract({
address: address as `0x${string}`,
const [ sortedIDs, status ] = await client.readContract({
address,
abi,
functionName: "getLocksStatus",
args: [lockIds],
});
const lockStatusResult = lockStatus as [bigint[], number[]];
const unreleasedLockId = lockStatusResult[1].findIndex(
(status: number) => status == 1
const unreleasedLockId = status.findIndex(
(status: LockStatus) => status == LockStatus.Active
);
if (unreleasedLockId !== -1) {
const lockID = lockStatusResult[0][unreleasedLockId];
const lock = await client.readContract({
address: address as `0x${string}`,
abi,
functionName: "mapLocks",
args: [lockID],
});
const lockData = lock as [
bigint,
string,
string,
bigint,
string,
string,
string
];
const amount = formatEther(lockData[0]);
return {
lockID: lockID.toString(),
amount: Number(amount),
sellerAddress: lockData[1] as `0x${string}`,
tokenAddress: lockData[4] as `0x${string}`,
};
}
if (unreleasedLockId !== -1)
return getUnreleasedLockById(sortedIDs[unreleasedLockId]);
};
export const getActiveLockAmount = async (
walletAddress: string
walletAddress: Address
): Promise<number> => {
const { address, abi, client } = await getContract(true);
const lockSeller = await listLockTransactionBySellerAddress(walletAddress);
@@ -462,20 +436,19 @@ export const getActiveLockAmount = async (
const lockIds = lockSeller.map((lock: any) => lock.args.lockID);
const lockStatus = await client.readContract({
address: address as `0x${string}`,
const [ sortedIDs, status ] = await client.readContract({
address,
abi,
functionName: "getLocksStatus",
args: [lockIds],
});
const lockStatusResult = lockStatus as [bigint[], number[]];
const mapLocksRequests = lockStatusResult[0].map((id: bigint) =>
const mapLocksRequests = status.map((id: LockStatus) =>
client.readContract({
address: address as `0x${string}`,
address: address,
abi,
functionName: "mapLocks",
args: [id],
args: [BigInt(id)],
})
);
@@ -484,7 +457,7 @@ export const getActiveLockAmount = async (
});
return mapLocksResults.reduce((total: number, lock: any, index: number) => {
if (lockStatusResult[1][index] === 1) {
if (status[index] === 1) {
return total + Number(formatEther(lock.amount));
}
return total;
@@ -492,16 +465,16 @@ export const getActiveLockAmount = async (
};
export const getSellerParticipantId = async (
sellerAddress: string,
tokenAddress: string
sellerAddress: Address,
tokenAddress: Address
): Promise<string> => {
const { address, abi, client } = await getContract();
const participantId = await client.readContract({
address: address as `0x${string}`,
address,
abi,
functionName: "getPixTarget",
args: [sellerAddress, tokenAddress],
});
return participantId as string;
return hexToString(participantId);
};