3 Commits

Author SHA1 Message Date
hueso
6d3f67af1b tweaked getTokenByAddress
Some checks failed
Deploy FrontEnd / deploy-staging (push) Has been cancelled
Deploy FrontEnd / deploy-production (push) Has been cancelled
CI script / lint (push) Has been cancelled
CI script / build (push) Has been cancelled
CI script / SonarCloud (push) Has been cancelled
2025-06-22 15:02:08 -03:00
hueso
4578474d3d unified networks list 2025-06-22 15:02:08 -03:00
hueso
9d9ed7a3dd fix type errors 2025-06-22 01:17:10 -03:00
10 changed files with 120 additions and 89 deletions

View File

@@ -5,8 +5,8 @@ import SpinnerComponent from "@/components/SpinnerComponent.vue";
import ToasterComponent from "@/components/ToasterComponent.vue"; import ToasterComponent from "@/components/ToasterComponent.vue";
import { init, useOnboard } from "@web3-onboard/vue"; import { init, useOnboard } from "@web3-onboard/vue";
import injectedModule from "@web3-onboard/injected-wallets"; import injectedModule from "@web3-onboard/injected-wallets";
import { Networks } from "./model/Networks"; import { Networks } from "@/model/Networks";
import { NetworkEnum } from "./model/NetworkEnum"; import { NetworkEnum } from "@/model/NetworkEnum";
import { ref } from "vue"; import { ref } from "vue";
const route = useRoute(); const route = useRoute();
@@ -15,20 +15,12 @@ const targetNetwork = ref(NetworkEnum.sepolia);
const web3Onboard = init({ const web3Onboard = init({
wallets: [injected], wallets: [injected],
chains: [ chains: Object.entries(Networks).map(([, network]) => ({
{ id: network.chainId,
id: Networks[NetworkEnum.sepolia].chainId, token: network.token,
token: "ETH", label: network.chainName,
label: "Sepolia", rpcUrl: network.rpcUrl,
rpcUrl: import.meta.env.VITE_SEPOLIA_API_URL, })),
},
{
id: Networks[NetworkEnum.rootstock].chainId,
token: "tRBTC",
label: "Rootstock Testnet",
rpcUrl: import.meta.env.VITE_ROOTSTOCK_API_URL,
},
],
connect: { connect: {
autoConnectLastWallet: true, autoConnectLastWallet: true,
}, },

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",
@@ -14,12 +14,12 @@ const Tokens: { [key in NetworkEnum]: { [key in TokenEnum]: string } } = {
}, },
}; };
export const getTokenByAddress = (address: string) => { export const getTokenByAddress = (address: `0x${string}`) => {
const user = useUser(); for ( let network in NetworkEnum ) {
const networksTokens = Tokens[user.networkName.value]; for (const token of Object.keys(Tokens[Number(network) as NetworkEnum])) {
for (const [token, tokenAddress] of Object.entries(networksTokens)) { if (address === Tokens[Number(network) as NetworkEnum][token as TokenEnum]) {
if (tokenAddress.toLowerCase() === address.toLowerCase()) { return token as TokenEnum;
return token; }
} }
} }
return null; return null;
@@ -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

View File

@@ -2,7 +2,7 @@ import { ref } from "vue";
import { NetworkEnum, TokenEnum } from "../model/NetworkEnum"; 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 { Networks } from "@/model/Networks";
const walletAddress = ref(""); const walletAddress = ref("");
const balance = ref(""); const balance = ref("");
@@ -32,7 +32,7 @@ export function useUser() {
}; };
const setNetworkId = (network: string | number) => { const setNetworkId = (network: string | number) => {
networkName.value = NetworkById(network) || NetworkEnum.sepolia; networkName.value = Number(network) as NetworkEnum || NetworkEnum.sepolia;
networkId.value = Number(network); networkId.value = Number(network);
}; };

View File

@@ -1,37 +1,26 @@
import { NetworkEnum } from "@/model/NetworkEnum"; import { NetworkEnum } from "./NetworkEnum";
export const NetworkById = ( export interface NetworkConfig {
chainId: string | number chainId: string;
): NetworkEnum | undefined => { chainName: string;
const normalizedChainId = token: string;
typeof chainId === "number" ? chainId : Number(chainId); rpcUrl?: string;
blockExplorerUrl?: string;
}
for (const [network, details] of Object.entries(Networks)) { export const Networks: { [key in NetworkEnum]: NetworkConfig } = {
if (Number(details.chainId) === normalizedChainId) {
return network as unknown as NetworkEnum;
}
}
return undefined;
};
export const Networks = {
[NetworkEnum.sepolia]: { [NetworkEnum.sepolia]: {
chainId: "0xAA36A7", chainId: "0xaa36a7",
chainName: "Sepolia Testnet", chainName: "Sepolia",
token: "ETH",
rpcUrl: import.meta.env.VITE_SEPOLIA_API_URL,
blockExplorerUrl: "https://sepolia.etherscan.io",
}, },
[NetworkEnum.rootstock]: { [NetworkEnum.rootstock]: {
chainId: "0x1F", chainId: "0x1f",
chainName: "Rootstock Testnet", chainName: "Rootstock Testnet",
rpcUrls: ["https://public-node.testnet.rsk.co/"], token: "tRBTC",
iconUrls: [ rpcUrl: import.meta.env.VITE_ROOTSTOCK_API_URL,
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACQAAAAoCAYAAACWwljjAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAPOSURBVHgBxVhNUhpBFH6vGdxp4S4LoSYnEE8gnEA4AbpMJUQ4gXgCRJK1egLxBOIJJCdwJElVllMu49Cd1z04zD/dY1H5qihmut/M93VPv59uhHdAXFaPAaEDgA2/BaeA4hq/zG+gIBAKQoyr9yshid4Jdn+2oQAYFIC4rA2zxUhgS3yrDqEAjGdIDD/YYG09aRl7L7vYd10wgPkMlcoNfdvtFhjCXJBAeyO2S5gLQuFo25bEIxjCCt8oN2Z46I+Mu4A4SbjwojQBi1+BDl5LP+JNYlhtQRmPsjjQN1ILldwY7JTXOuD9bWL/jxO8dFy7oL9TyMcIu/PeSghxlLduQUA9jwPXiAk98HLw5jFiaFfAEjRLImPR0qi7z+2VmArZ7zzqcDAS01ljCKqf7QSjxb7jKkIhTohu6rOCq64RjsNiFEo7x7ocSNMvlddhPWb0CQ6gAAw4HKZpKGFDcWhzSEG6kbQCm4dLbi9m+XlpBTHea2D31zTSNtxrAGMNdcP5FPuxfhlKdCHgASUJxcd7zUcobkAPXvkzWGyf7uVCt2M2DtkMljaHSxu92WWLAz8OjWsD+juD/4tzcpqBSh3yQrmwoNFFMZNuDB7bJRsp/hzMMQqeT+NQ96KtNEBK+SG+23XgHgUyy8FPjpPozy3M4sZwh1/nLRMOK26Mn50Z5IHjA6XkBugJSn1XHkeBbK8dJsxsl0jMEOUpm0o9+gkX+7+TI0E+0x6Hsk0ijyNYQ/4OAqWn2aF+5cLxEoRq6idqtyEPtFhp/XyMNI2p9ADFUc/iYL5h7YzEXEEyptj04mvVHxkGP4F8MS4sWDsqRr4DbyGZRiIcqCKtpRMYeTMcpVVAFewqMVPSjUkMVQTBp6BPVKeiTqN65E0qP1AvIArWC98qcQsms39oDeBEtoXFKFgLbQ76ZKiXiRH2E01UF9Go+kGDh32/LWHZAD2OQ7mGdLO4ndrqWaHZyNyD6XJUWEq6yIQqReOweCe49ivD2DNUIutjJgXpHwyUtyPbY/IMWehfBA0IZxQSQoW9rKXL+ltq0oKqYC+RB6yLKys4xEw/Idde5R02cTGOcgh1LSNnid+nihIqcN0tr48MhL89L2uoG+Dqv5Px/IwqAhkqnEi296M1OyLPqVCgdKhcuKNjlUnQL4X78cRk1E1JlMkBME1sFE0gRrRJZGs3iT44bRZP5z0wQJHzIZMMbpztN1t+FDhsMBe0YNfatimHDetgLGiZGkYapqPwYt6YIAWPDYI9fSrETfjkwwSFT2EVrV/USY+r+/GGNp2I7zoW/gdR9aOdZ/lPGgAAAABJRU5ErkJggg==", blockExplorerUrl: "https://explorer.testnet.rsk.co",
],
nativeCurrency: {
name: "tRBTC",
symbol: "tRBTC",
decimals: 18,
},
blockExplorerUrls: ["https://explorer.testnet.rootstock.io/"],
}, },
}; };