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

10922
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -42,6 +42,7 @@
"@vue/eslint-config-prettier": "^7.0.0", "@vue/eslint-config-prettier": "^7.0.0",
"@vue/eslint-config-typescript": "^11.0.0", "@vue/eslint-config-typescript": "^11.0.0",
"@vue/tsconfig": "^0.1.3", "@vue/tsconfig": "^0.1.3",
"@wagmi/cli": "^2.3.1",
"autoprefixer": "^10.4.12", "autoprefixer": "^10.4.12",
"eslint": "^8.22.0", "eslint": "^8.22.0",
"eslint-plugin-vue": "^9.3.0", "eslint-plugin-vue": "^9.3.0",

2266
src/blockchain/abi.ts Normal file

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

@ -1,12 +1,14 @@
import { useUser } from "@/composables/useUser"; import { useUser } from "@/composables/useUser";
import { formatEther, toHex, type PublicClient } from "viem"; import { formatEther, toHex, stringToHex } from "viem";
import type { PublicClient, Address } from "viem";
import p2pix from "@/utils/smart_contract_files/P2PIX.json";
import { getContract } from "./provider"; import { getContract } from "./provider";
import type { ValidDeposit } from "@/model/ValidDeposit";
import { getP2PixAddress, getTokenAddress } from "./addresses"; import { getP2PixAddress, getTokenAddress } from "./addresses";
import { getNetworkSubgraphURL, NetworkEnum } from "@/model/NetworkEnum"; import { p2PixAbi } from "./abi"
import type { ValidDeposit } from "@/model/ValidDeposit";
import { getNetworkSubgraphURL, NetworkEnum, TokenEnum } from "@/model/NetworkEnum";
import type { UnreleasedLock } from "@/model/UnreleasedLock"; import type { UnreleasedLock } from "@/model/UnreleasedLock";
import type { LockStatus } from "@/model/LockStatus"
const getNetworksLiquidity = async (): Promise<void> => { const getNetworksLiquidity = async (): Promise<void> => {
const user = useUser(); const user = useUser();
@ -36,7 +38,7 @@ const getParticipantID = async (
const { address, abi, client } = await getContract(); const { address, abi, client } = await getContract();
const participantIDHex = await client.readContract({ const participantIDHex = await client.readContract({
address: address as `0x${string}`, address,
abi, abi,
functionName: "getPixTarget", functionName: "getPixTarget",
args: [seller, token], args: [seller, token],
@ -59,15 +61,15 @@ const getParticipantID = async (
}; };
const getValidDeposits = async ( const getValidDeposits = async (
token: string, token: Address,
network: NetworkEnum, network: NetworkEnum,
contractInfo?: { client: any; address: string } contractInfo?: { client: PublicClient; address: Address }
): Promise<ValidDeposit[]> => { ): Promise<ValidDeposit[]> => {
let client: PublicClient, abi; let client: PublicClient, abi;
if (contractInfo) { if (contractInfo) {
({ client } = contractInfo); ({ client } = contractInfo);
abi = p2pix.abi; abi = p2PixAbi;
} else { } else {
({ abi, client } = await getContract(true)); ({ abi, client } = await getContract(true));
} }
@ -100,11 +102,11 @@ const getValidDeposits = async (
const depositData = await depositLogs.json(); const depositData = await depositLogs.json();
const depositAddeds = depositData.data.depositAddeds; const depositAddeds = depositData.data.depositAddeds;
const uniqueSellers = depositAddeds.reduce( const uniqueSellers = depositAddeds.reduce(
(acc: Record<string, boolean>, deposit: any) => { (acc: Record<Address, boolean>, deposit: any) => {
acc[deposit.seller] = true; acc[deposit.seller] = true;
return acc; return acc;
}, },
{} as Record<string, boolean> {} as Record<Address, boolean>
); );
if (!contractInfo) { if (!contractInfo) {
@ -114,10 +116,10 @@ const getValidDeposits = async (
const depositList: { [key: string]: ValidDeposit } = {}; const depositList: { [key: string]: ValidDeposit } = {};
const sellersList = Object.keys(uniqueSellers); const sellersList = Object.keys(uniqueSellers) as Address[];
// Use multicall to batch all getBalance requests // Use multicall to batch all getBalance requests
const balanceCalls = sellersList.map((seller) => ({ const balanceCalls = sellersList.map((seller) => ({
address: getP2PixAddress(network) as `0x${string}`, address: getP2PixAddress(network),
abi, abi,
functionName: "getBalance", functionName: "getBalance",
args: [seller, token], args: [seller, token],
@ -133,10 +135,10 @@ const getValidDeposits = async (
if (!mappedBalance.error && mappedBalance.result) { if (!mappedBalance.error && mappedBalance.result) {
const validDeposit: ValidDeposit = { const validDeposit: ValidDeposit = {
token: token, token,
blockNumber: 0, blockNumber: 0,
remaining: Number(formatEther(mappedBalance.result as bigint)), remaining: Number(formatEther(mappedBalance.result as bigint)),
seller: seller, seller,
network, network,
participantID: "", participantID: "",
}; };
@ -147,34 +149,22 @@ const getValidDeposits = async (
}; };
const getUnreleasedLockById = async ( const getUnreleasedLockById = async (
lockID: string lockID: bigint
): Promise<UnreleasedLock> => { ): Promise<UnreleasedLock> => {
const { address, abi, client } = await getContract(); const { address, abi, client } = await getContract();
const lock = await client.readContract({ const [ , , , amount, token, seller ] = await client.readContract({
address: address as `0x${string}`, address,
abi, abi,
functionName: "mapLocks", 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 { return {
lockID: lockID, lockID,
amount: Number(amount), amount: Number(formatEther(amount)),
tokenAddress: lockData[4] as `0x${string}`, tokenAddress: token,
sellerAddress: lockData[6] as `0x${string}`, 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 { updateWalletStatus } from "./wallet";
import { getProviderUrl, getP2PixAddress } from "./addresses"; import { getProviderUrl, getP2PixAddress } from "./addresses";
import { import {
@ -12,11 +12,9 @@ import {
import { sepolia, rootstock } from "viem/chains"; import { sepolia, rootstock } from "viem/chains";
import { useUser } from "@/composables/useUser"; import { useUser } from "@/composables/useUser";
let publicClient: PublicClient | null = null;
let walletClient: WalletClient | null = null; let walletClient: WalletClient | null = null;
const getPublicClient = (onlyRpcProvider = false): PublicClient | null => { const getPublicClient = (): PublicClient => {
if (onlyRpcProvider) {
const user = useUser(); const user = useUser();
const rpcUrl = getProviderUrl(); const rpcUrl = getProviderUrl();
return createPublicClient({ return createPublicClient({
@ -24,8 +22,6 @@ const getPublicClient = (onlyRpcProvider = false): PublicClient | null => {
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 => {
@ -33,16 +29,16 @@ const getWalletClient = (): WalletClient | null => {
}; };
const getContract = async (onlyRpcProvider = false) => { const getContract = async (onlyRpcProvider = false) => {
const client = getPublicClient(onlyRpcProvider); const client = getPublicClient();
const address = getP2PixAddress(); const address = getP2PixAddress();
const abi = p2pix.abi; const abi = p2PixAbi;
const wallet = getWalletClient(); const wallet = onlyRpcProvider ? null : getWalletClient();
if (!client) { if (!client) {
throw new Error("Public client not initialized"); 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 }; return { address, abi, client, wallet, account };
}; };
@ -52,11 +48,6 @@ const connectProvider = async (p: any): Promise<void> => {
const chain = const chain =
Number(user.networkName.value) === sepolia.id ? sepolia : rootstock; Number(user.networkName.value) === sepolia.id ? sepolia : rootstock;
publicClient = createPublicClient({
chain,
transport: custom(p),
});
const [account] = await p!.request({ method: "eth_requestAccounts" }); const [account] = await p!.request({ method: "eth_requestAccounts" });
walletClient = createWalletClient({ walletClient = createWalletClient({

View File

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

View File

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

View File

@ -5,7 +5,6 @@ import CustomModal from "@/components//CustomModal/CustomModal.vue";
import SpinnerComponent from "@/components/SpinnerComponent.vue"; import SpinnerComponent from "@/components/SpinnerComponent.vue";
import { createSolicitation, getSolicitation, type Offer } from "@/utils/bbPay"; import { createSolicitation, getSolicitation, type Offer } from "@/utils/bbPay";
import { getSellerParticipantId } from "@/blockchain/wallet"; import { getSellerParticipantId } from "@/blockchain/wallet";
import { hexToString } from "viem";
import { getUnreleasedLockById } from "@/blockchain/events"; import { getUnreleasedLockById } from "@/blockchain/events";
import QRCode from "qrcode"; import QRCode from "qrcode";
@ -84,17 +83,17 @@ const startPolling = () => {
onMounted(async () => { onMounted(async () => {
try { try {
const { tokenAddress, sellerAddress, amount } = await getUnreleasedLockById( const { tokenAddress, sellerAddress, amount } = await getUnreleasedLockById(
props.lockID BigInt(props.lockID)
); );
const participantId = await getSellerParticipantId( const participantId = await getSellerParticipantId(
sellerAddress as `0x${string}`, sellerAddress,
tokenAddress tokenAddress
); );
const offer: Offer = { const offer: Offer = {
amount, amount,
sellerId: hexToString(participantId as `0x${string}`, { size: 32 }), sellerId: participantId,
}; };
const response = await createSolicitation(offer); const response = await createSolicitation(offer);

View File

@ -90,6 +90,8 @@ const handleSelectedToken = (token: TokenEnum): void => {
// Verify if there is a valid deposit to buy // Verify if there is a valid deposit to buy
const verifyLiquidity = (): void => { const verifyLiquidity = (): void => {
enableConfirmButton.value = false; enableConfirmButton.value = false;
if (!walletAddress.value)
return;
const selDeposits = verifyNetworkLiquidity( const selDeposits = verifyNetworkLiquidity(
tokenValue.value, tokenValue.value,
walletAddress.value, walletAddress.value,

View File

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

View File

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

8
src/model/LockStatus.ts Normal file
View File

@ -0,0 +1,8 @@
import type { Address } from "viem";
export enum LockStatus { // from DataTypes.sol
Inexistent = 0, // Uninitialized Lock
Active = 1, // Valid Lock
Expired = 2, // Expired Lock
Released = 3 // Already released Lock
}

View File

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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -12,6 +12,7 @@ import type { ValidDeposit } from "@/model/ValidDeposit";
import { getUnreleasedLockById } from "@/blockchain/events"; import { getUnreleasedLockById } from "@/blockchain/events";
import CustomAlert from "@/components/CustomAlert/CustomAlert.vue"; import CustomAlert from "@/components/CustomAlert/CustomAlert.vue";
import { getSolicitation } from "@/utils/bbPay"; import { getSolicitation } from "@/utils/bbPay";
import type { Address } from "viem";
enum Step { enum Step {
Search, Search,
@ -26,7 +27,7 @@ user.setSellerView(false);
const { loadingLock, walletAddress, networkName } = user; const { loadingLock, walletAddress, networkName } = user;
const flowStep = ref<Step>(Step.Search); const flowStep = ref<Step>(Step.Search);
const participantID = ref<string>(); const participantID = ref<string>();
const sellerAddress = ref<`0x${string}` | undefined>(); const sellerAddress = ref<Address>();
const tokenAmount = ref<number>(); const tokenAmount = ref<number>();
const lockID = ref<string>(""); const lockID = ref<string>("");
const loadingRelease = ref<boolean>(false); const loadingRelease = ref<boolean>(false);
@ -47,7 +48,7 @@ const confirmBuyClick = async (
await addLock(selectedDeposit.seller, selectedDeposit.token, tokenValue) await addLock(selectedDeposit.seller, selectedDeposit.token, tokenValue)
.then((_lockID) => { .then((_lockID) => {
lockID.value = _lockID; lockID.value = String(_lockID);
}) })
.catch((err) => { .catch((err) => {
console.log(err); console.log(err);
@ -69,7 +70,7 @@ const releaseTransaction = async ({
showBuyAlert.value = true; showBuyAlert.value = true;
loadingRelease.value = true; loadingRelease.value = true;
const release = await releaseLock(lockID.value, pixTarget, signature); const release = await releaseLock(BigInt(lockID.value), pixTarget, signature);
await release.wait(); await release.wait();
await updateWalletStatus(); await updateWalletStatus();
@ -77,9 +78,11 @@ const releaseTransaction = async ({
}; };
const checkForUnreleasedLocks = async (): Promise<void> => { const checkForUnreleasedLocks = async (): Promise<void> => {
if (!walletAddress.value)
throw new Error("Wallet not connected");
const lock = await checkUnreleasedLock(walletAddress.value); const lock = await checkUnreleasedLock(walletAddress.value);
if (lock) { if (lock) {
lockID.value = lock.lockID; lockID.value = String(lock.lockID);
tokenAmount.value = lock.amount; tokenAmount.value = lock.amount;
sellerAddress.value = lock.sellerAddress; sellerAddress.value = lock.sellerAddress;
showModal.value = true; showModal.value = true;
@ -90,9 +93,9 @@ const checkForUnreleasedLocks = async (): Promise<void> => {
}; };
if (paramLockID) { if (paramLockID) {
const lockToRedirect = await getUnreleasedLockById(paramLockID as string); const lockToRedirect = await getUnreleasedLockById(paramLockID);
if (lockToRedirect) { if (lockToRedirect) {
lockID.value = lockToRedirect.lockID; lockID.value = String(lockToRedirect.lockID);
tokenAmount.value = lockToRedirect.amount; tokenAmount.value = lockToRedirect.amount;
sellerAddress.value = lockToRedirect.sellerAddress; sellerAddress.value = lockToRedirect.sellerAddress;
flowStep.value = Step.Buy; flowStep.value = Step.Buy;

View File

@ -8,6 +8,7 @@
], ],
"compilerOptions": { "compilerOptions": {
"baseUrl": ".", "baseUrl": ".",
"strict": true,
"paths": { "paths": {
"@/*": [ "@/*": [
"./src/*" "./src/*"

11
wagmi.config.ts Normal file
View File

@ -0,0 +1,11 @@
import { defineConfig } from '@wagmi/cli'
import { hardhat } from '@wagmi/cli/plugins'
export default defineConfig({
out: 'src/blockchain/abi.ts',
contracts: [],
plugins: [
hardhat({
project: '../p2pix-smart-contracts',
}),],
})