Migrated project to Viem, removing Ethers completelly. Not finished tests.
This commit is contained in:
parent
3227e3209c
commit
e93cac6086
@ -8,7 +8,7 @@ import {
|
|||||||
|
|
||||||
import { setActivePinia, createPinia } from "pinia";
|
import { setActivePinia, createPinia } from "pinia";
|
||||||
import { NetworkEnum, TokenEnum } from "@/model/NetworkEnum";
|
import { NetworkEnum, TokenEnum } from "@/model/NetworkEnum";
|
||||||
import { useEtherStore } from "@/store/ether";
|
import { useViemStore } from "@/store/viem";
|
||||||
|
|
||||||
describe("addresses.ts types", () => {
|
describe("addresses.ts types", () => {
|
||||||
it("My addresses.ts types work properly", () => {
|
it("My addresses.ts types work properly", () => {
|
||||||
@ -25,7 +25,7 @@ describe("addresses.ts functions", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("getTokenAddress Ethereum", () => {
|
it("getTokenAddress Ethereum", () => {
|
||||||
const etherStore = useEtherStore();
|
const etherStore = useViemStore();
|
||||||
etherStore.setNetworkId(NetworkEnum.sepolia);
|
etherStore.setNetworkId(NetworkEnum.sepolia);
|
||||||
expect(getTokenAddress(TokenEnum.BRZ)).toBe(
|
expect(getTokenAddress(TokenEnum.BRZ)).toBe(
|
||||||
"0x4A2886EAEc931e04297ed336Cc55c4eb7C75BA00"
|
"0x4A2886EAEc931e04297ed336Cc55c4eb7C75BA00"
|
||||||
@ -33,7 +33,7 @@ describe("addresses.ts functions", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("getTokenAddress Rootstock", () => {
|
it("getTokenAddress Rootstock", () => {
|
||||||
const etherStore = useEtherStore();
|
const etherStore = useViemStore();
|
||||||
etherStore.setNetworkId(NetworkEnum.rootstock);
|
etherStore.setNetworkId(NetworkEnum.rootstock);
|
||||||
expect(getTokenAddress(TokenEnum.BRZ)).toBe(
|
expect(getTokenAddress(TokenEnum.BRZ)).toBe(
|
||||||
"0xfE841c74250e57640390f46d914C88d22C51e82e"
|
"0xfE841c74250e57640390f46d914C88d22C51e82e"
|
||||||
@ -47,7 +47,7 @@ describe("addresses.ts functions", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("getP2PixAddress Ethereum", () => {
|
it("getP2PixAddress Ethereum", () => {
|
||||||
const etherStore = useEtherStore();
|
const etherStore = useViemStore();
|
||||||
etherStore.setNetworkId(NetworkEnum.sepolia);
|
etherStore.setNetworkId(NetworkEnum.sepolia);
|
||||||
expect(getP2PixAddress()).toBe(
|
expect(getP2PixAddress()).toBe(
|
||||||
"0x2414817FF64A114d91eCFA16a834d3fCf69103d4"
|
"0x2414817FF64A114d91eCFA16a834d3fCf69103d4"
|
||||||
@ -55,7 +55,7 @@ describe("addresses.ts functions", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("getP2PixAddress Rootstock", () => {
|
it("getP2PixAddress Rootstock", () => {
|
||||||
const etherStore = useEtherStore();
|
const etherStore = useViemStore();
|
||||||
etherStore.setNetworkId(NetworkEnum.rootstock);
|
etherStore.setNetworkId(NetworkEnum.rootstock);
|
||||||
expect(getP2PixAddress()).toBe(
|
expect(getP2PixAddress()).toBe(
|
||||||
"0x98ba35eb14b38D6Aa709338283af3e922476dE34"
|
"0x98ba35eb14b38D6Aa709338283af3e922476dE34"
|
||||||
@ -69,13 +69,13 @@ describe("addresses.ts functions", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("getProviderUrl Ethereum", () => {
|
it("getProviderUrl Ethereum", () => {
|
||||||
const etherStore = useEtherStore();
|
const etherStore = useViemStore();
|
||||||
etherStore.setNetworkId(NetworkEnum.sepolia);
|
etherStore.setNetworkId(NetworkEnum.sepolia);
|
||||||
expect(getProviderUrl()).toBe(import.meta.env.VITE_GOERLI_API_URL);
|
expect(getProviderUrl()).toBe(import.meta.env.VITE_GOERLI_API_URL);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("getProviderUrl Rootstock", () => {
|
it("getProviderUrl Rootstock", () => {
|
||||||
const etherStore = useEtherStore();
|
const etherStore = useViemStore();
|
||||||
etherStore.setNetworkId(NetworkEnum.rootstock);
|
etherStore.setNetworkId(NetworkEnum.rootstock);
|
||||||
expect(getProviderUrl()).toBe(import.meta.env.VITE_ROOTSTOCK_API_URL);
|
expect(getProviderUrl()).toBe(import.meta.env.VITE_ROOTSTOCK_API_URL);
|
||||||
});
|
});
|
||||||
@ -85,7 +85,7 @@ describe("addresses.ts functions", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("isPossibleNetwork Returns", () => {
|
it("isPossibleNetwork Returns", () => {
|
||||||
const etherStore = useEtherStore();
|
const etherStore = useViemStore();
|
||||||
etherStore.setNetworkId(NetworkEnum.sepolia);
|
etherStore.setNetworkId(NetworkEnum.sepolia);
|
||||||
expect(isPossibleNetwork(0x5 as NetworkEnum)).toBe(true);
|
expect(isPossibleNetwork(0x5 as NetworkEnum)).toBe(true);
|
||||||
expect(isPossibleNetwork(5 as NetworkEnum)).toBe(true);
|
expect(isPossibleNetwork(5 as NetworkEnum)).toBe(true);
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
import { useEtherStore } from "@/store/ether";
|
import { useViemStore } from "@/store/viem";
|
||||||
import { NetworkEnum, TokenEnum } from "@/model/NetworkEnum";
|
import { NetworkEnum, TokenEnum } from "@/model/NetworkEnum";
|
||||||
import { JsonRpcProvider } from "ethers";
|
import { createPublicClient, http } 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]: string } } = {
|
||||||
[NetworkEnum.sepolia]: {
|
[NetworkEnum.sepolia]: {
|
||||||
@ -14,57 +15,54 @@ const Tokens: { [key in NetworkEnum]: { [key in TokenEnum]: string } } = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const getTokenByAddress = (address: string) => {
|
export const getTokenByAddress = (address: string) => {
|
||||||
for (const network of Object.values(NetworkEnum).filter(
|
const viemStore = useViemStore();
|
||||||
(v) => !isNaN(Number(v))
|
const networksTokens = Tokens[viemStore.networkName];
|
||||||
)) {
|
for (const [token, tokenAddress] of Object.entries(networksTokens)) {
|
||||||
for (const token of Object.keys(Tokens[network as NetworkEnum])) {
|
if (tokenAddress.toLowerCase() === address.toLowerCase()) {
|
||||||
if (address === Tokens[network as NetworkEnum][token as TokenEnum]) {
|
return token;
|
||||||
return token as TokenEnum;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const getTokenAddress = (token: TokenEnum, network?: NetworkEnum): string => {
|
export const getTokenAddress = (
|
||||||
const etherStore = useEtherStore();
|
token: TokenEnum,
|
||||||
return Tokens[network ? network : etherStore.networkName][token];
|
network?: NetworkEnum
|
||||||
|
): string => {
|
||||||
|
const viemStore = useViemStore();
|
||||||
|
return Tokens[network ? network : viemStore.networkName][token];
|
||||||
};
|
};
|
||||||
|
|
||||||
const getP2PixAddress = (network?: NetworkEnum): string => {
|
export const getP2PixAddress = (network?: NetworkEnum): string => {
|
||||||
const etherStore = useEtherStore();
|
const viemStore = useViemStore();
|
||||||
const possibleP2PixAddresses: { [key in NetworkEnum]: string } = {
|
const possibleP2PixAddresses: { [key in NetworkEnum]: string } = {
|
||||||
[NetworkEnum.sepolia]: "0xb7cD135F5eFD9760981e02E2a898790b688939fe",
|
[NetworkEnum.sepolia]: "0x2414817FF64A114d91eCFA16a834d3fCf69103d4",
|
||||||
[NetworkEnum.rootstock]: "0x98ba35eb14b38D6Aa709338283af3e922476dE34",
|
[NetworkEnum.rootstock]: "0x98ba35eb14b38D6Aa709338283af3e922476dE34",
|
||||||
};
|
};
|
||||||
|
|
||||||
return possibleP2PixAddresses[network ? network : etherStore.networkName];
|
return possibleP2PixAddresses[network ? network : viemStore.networkName];
|
||||||
};
|
};
|
||||||
|
|
||||||
const getProviderUrl = (network?: NetworkEnum): string => {
|
export const getProviderUrl = (network?: NetworkEnum): string => {
|
||||||
const etherStore = useEtherStore();
|
const viemStore = useViemStore();
|
||||||
const possibleProvidersUrls: { [key in NetworkEnum]: string } = {
|
const possibleProvidersUrls: { [key in NetworkEnum]: string } = {
|
||||||
[NetworkEnum.sepolia]: import.meta.env.VITE_SEPOLIA_API_URL,
|
[NetworkEnum.sepolia]: import.meta.env.VITE_SEPOLIA_API_URL,
|
||||||
[NetworkEnum.rootstock]: import.meta.env.VITE_RSK_API_URL,
|
[NetworkEnum.rootstock]: import.meta.env.VITE_RSK_API_URL,
|
||||||
};
|
};
|
||||||
|
|
||||||
return possibleProvidersUrls[network || etherStore.networkName];
|
return possibleProvidersUrls[network || viemStore.networkName];
|
||||||
};
|
};
|
||||||
|
|
||||||
const getProviderByNetwork = (network: NetworkEnum): JsonRpcProvider => {
|
export const getProviderByNetwork = (network: NetworkEnum) => {
|
||||||
console.log("network", network);
|
console.log("network", network);
|
||||||
return new JsonRpcProvider(getProviderUrl(network), network);
|
const chain = network === NetworkEnum.sepolia ? sepolia : rootstock;
|
||||||
|
return createPublicClient({
|
||||||
|
chain,
|
||||||
|
transport: http(getProviderUrl(network))
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const isPossibleNetwork = (networkChain: NetworkEnum): boolean => {
|
export const isPossibleNetwork = (networkChain: NetworkEnum): boolean => {
|
||||||
return Number(networkChain) in NetworkEnum;
|
return Number(networkChain) in NetworkEnum;
|
||||||
};
|
};
|
||||||
|
|
||||||
export {
|
|
||||||
getTokenAddress,
|
|
||||||
getProviderUrl,
|
|
||||||
isPossibleNetwork,
|
|
||||||
getP2PixAddress,
|
|
||||||
getProviderByNetwork,
|
|
||||||
};
|
|
||||||
|
@ -1,8 +1,6 @@
|
|||||||
import { getContract, getProvider } from "./provider";
|
import { getContract, getWalletClient } from "./provider";
|
||||||
import { getP2PixAddress, getTokenAddress } from "./addresses";
|
import { getTokenAddress } from "./addresses";
|
||||||
import { encodeBytes32String, Signature, Contract, parseEther } from "ethers";
|
import { parseEther, stringToHex, toHex } from "viem";
|
||||||
|
|
||||||
import p2pix from "@/utils/smart_contract_files/P2PIX.json";
|
|
||||||
|
|
||||||
import type { TokenEnum } from "@/model/NetworkEnum";
|
import type { TokenEnum } from "@/model/NetworkEnum";
|
||||||
import { createSolicitation } from "../utils/bbPay";
|
import { createSolicitation } from "../utils/bbPay";
|
||||||
@ -13,82 +11,131 @@ const addLock = async (
|
|||||||
token: string,
|
token: string,
|
||||||
amount: number
|
amount: number
|
||||||
): Promise<string> => {
|
): Promise<string> => {
|
||||||
const p2pContract = await getContract();
|
const { address, abi, client } = await getContract();
|
||||||
|
const walletClient = getWalletClient();
|
||||||
const lock = await p2pContract.lock(
|
|
||||||
sellerId,
|
if (!walletClient) {
|
||||||
token,
|
throw new Error("Wallet client not initialized");
|
||||||
parseEther(String(amount)), // BigNumber
|
}
|
||||||
[],
|
|
||||||
[]
|
const [account] = await walletClient.getAddresses();
|
||||||
);
|
|
||||||
|
const hash = await walletClient.writeContract({
|
||||||
const lock_rec = await lock.wait();
|
address,
|
||||||
const [t] = lock_rec.events;
|
abi,
|
||||||
|
functionName: 'lock',
|
||||||
|
args: [
|
||||||
|
sellerId,
|
||||||
|
token,
|
||||||
|
parseEther(String(amount)),
|
||||||
|
[],
|
||||||
|
[]
|
||||||
|
],
|
||||||
|
account
|
||||||
|
});
|
||||||
|
|
||||||
|
const receipt = await client.waitForTransactionReceipt({ hash });
|
||||||
|
const logs = receipt.logs;
|
||||||
|
|
||||||
|
// Extract the lockID from transaction logs
|
||||||
|
// This is a simplified approach - in production you'll want more robust log parsing
|
||||||
|
const lockId = logs[0].topics[2]; // Simplified - adjust based on actual event structure
|
||||||
|
|
||||||
const offer: Offer = {
|
const offer: Offer = {
|
||||||
amount,
|
amount,
|
||||||
lockId: String(t.args.lockID),
|
lockId: String(lockId),
|
||||||
sellerId: sellerId,
|
sellerId: sellerId,
|
||||||
};
|
};
|
||||||
const solicitation = await createSolicitation(offer);
|
|
||||||
|
await createSolicitation(offer);
|
||||||
return;
|
|
||||||
|
return String(lockId);
|
||||||
};
|
};
|
||||||
|
|
||||||
const releaseLock = async (solicitation: any): Promise<any> => {
|
const releaseLock = async (
|
||||||
// const mockBacenSigner = new Wallet(
|
pixKey: string,
|
||||||
// "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"
|
amount: number,
|
||||||
// );
|
e2eId: string,
|
||||||
|
lockId: string
|
||||||
// const messageToSign = solidityPackedKeccak256(
|
): Promise<any> => {
|
||||||
// ["bytes32", "uint256", "bytes32"],
|
const { address, abi, client } = await getContract();
|
||||||
// [sellerId, parseEther(String(amount)), encodeBytes32String(signature)]
|
const walletClient = getWalletClient();
|
||||||
// );
|
|
||||||
|
if (!walletClient) {
|
||||||
// const messageHashBytes = getBytes(messageToSign);
|
throw new Error("Wallet client not initialized");
|
||||||
// const flatSig = await mockBacenSigner.signMessage(messageHashBytes);
|
}
|
||||||
|
|
||||||
const provider = getProvider();
|
const [account] = await walletClient.getAddresses();
|
||||||
|
|
||||||
const sig = Signature.from(flatSig);
|
// In a real implementation, you would get this signature from your backend
|
||||||
console.log(sig);
|
// This is just a placeholder for the mock implementation
|
||||||
const signer = await provider.getSigner();
|
const signature = "0x1234567890";
|
||||||
const p2pContract = new Contract(getP2PixAddress(), p2pix.abi, signer);
|
|
||||||
|
const hash = await walletClient.writeContract({
|
||||||
const release = await p2pContract.release(
|
address,
|
||||||
BigInt(lockId),
|
abi,
|
||||||
encodeBytes32String(e2eId),
|
functionName: 'release',
|
||||||
flatSig
|
args: [
|
||||||
);
|
BigInt(lockId),
|
||||||
await release.wait();
|
toHex(e2eId, { size: 32 }),
|
||||||
|
signature
|
||||||
return release;
|
],
|
||||||
|
account
|
||||||
|
});
|
||||||
|
|
||||||
|
const receipt = await client.waitForTransactionReceipt({ hash });
|
||||||
|
return receipt;
|
||||||
};
|
};
|
||||||
|
|
||||||
const cancelDeposit = async (depositId: bigint): Promise<any> => {
|
const cancelDeposit = async (depositId: bigint): Promise<any> => {
|
||||||
const contract = await getContract();
|
const { address, abi, client } = await getContract();
|
||||||
|
const walletClient = getWalletClient();
|
||||||
const cancel = await contract.cancelDeposit(depositId);
|
|
||||||
await cancel.wait();
|
if (!walletClient) {
|
||||||
|
throw new Error("Wallet client not initialized");
|
||||||
return cancel;
|
}
|
||||||
|
|
||||||
|
const [account] = await walletClient.getAddresses();
|
||||||
|
|
||||||
|
const hash = await walletClient.writeContract({
|
||||||
|
address,
|
||||||
|
abi,
|
||||||
|
functionName: 'cancelDeposit',
|
||||||
|
args: [depositId],
|
||||||
|
account
|
||||||
|
});
|
||||||
|
|
||||||
|
const receipt = await client.waitForTransactionReceipt({ hash });
|
||||||
|
return receipt;
|
||||||
};
|
};
|
||||||
|
|
||||||
const withdrawDeposit = async (
|
const withdrawDeposit = async (
|
||||||
amount: string,
|
amount: string,
|
||||||
token: TokenEnum
|
token: TokenEnum
|
||||||
): Promise<any> => {
|
): Promise<any> => {
|
||||||
const contract = await getContract();
|
const { address, abi, client } = await getContract();
|
||||||
|
const walletClient = getWalletClient();
|
||||||
const withdraw = await contract.withdraw(
|
|
||||||
getTokenAddress(token),
|
if (!walletClient) {
|
||||||
parseEther(String(amount)),
|
throw new Error("Wallet client not initialized");
|
||||||
[]
|
}
|
||||||
);
|
|
||||||
await withdraw.wait();
|
const [account] = await walletClient.getAddresses();
|
||||||
|
|
||||||
return withdraw;
|
const hash = await walletClient.writeContract({
|
||||||
|
address,
|
||||||
|
abi,
|
||||||
|
functionName: 'withdraw',
|
||||||
|
args: [
|
||||||
|
getTokenAddress(token),
|
||||||
|
parseEther(String(amount)),
|
||||||
|
[]
|
||||||
|
],
|
||||||
|
account
|
||||||
|
});
|
||||||
|
|
||||||
|
const receipt = await client.waitForTransactionReceipt({ hash });
|
||||||
|
return receipt;
|
||||||
};
|
};
|
||||||
|
|
||||||
export { cancelDeposit, withdrawDeposit, addLock, releaseLock };
|
export { cancelDeposit, withdrawDeposit, addLock, releaseLock };
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
import { useEtherStore } from "@/store/ether";
|
import { useViemStore } from "@/store/viem";
|
||||||
import { Contract, formatEther, Interface } from "ethers";
|
import { formatEther, decodeEventLog, parseAbi, toHex, type PublicClient, type Address } 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";
|
||||||
@ -14,8 +14,8 @@ import type { UnreleasedLock } from "@/model/UnreleasedLock";
|
|||||||
import type { Pix } from "@/model/Pix";
|
import type { Pix } from "@/model/Pix";
|
||||||
|
|
||||||
const getNetworksLiquidity = async (): Promise<void> => {
|
const getNetworksLiquidity = async (): Promise<void> => {
|
||||||
const etherStore = useEtherStore();
|
const viemStore = useViemStore();
|
||||||
etherStore.setLoadingNetworkLiquidity(true);
|
viemStore.setLoadingNetworkLiquidity(true);
|
||||||
|
|
||||||
const depositLists: ValidDeposit[][] = [];
|
const depositLists: ValidDeposit[][] = [];
|
||||||
|
|
||||||
@ -23,31 +23,40 @@ const getNetworksLiquidity = async (): Promise<void> => {
|
|||||||
(v) => !isNaN(Number(v))
|
(v) => !isNaN(Number(v))
|
||||||
)) {
|
)) {
|
||||||
console.log("getNetworksLiquidity", network);
|
console.log("getNetworksLiquidity", network);
|
||||||
const p2pContract = new Contract(
|
|
||||||
getP2PixAddress(network as NetworkEnum),
|
// Get public client for this network
|
||||||
p2pix.abi,
|
const client = getProviderByNetwork(network as NetworkEnum);
|
||||||
getProviderByNetwork(network as NetworkEnum)
|
const address = getP2PixAddress(network as NetworkEnum);
|
||||||
);
|
|
||||||
|
|
||||||
depositLists.push(
|
depositLists.push(
|
||||||
await getValidDeposits(
|
await getValidDeposits(
|
||||||
getTokenAddress(etherStore.selectedToken, network as NetworkEnum),
|
getTokenAddress(viemStore.selectedToken, network as NetworkEnum),
|
||||||
network as NetworkEnum,
|
network as NetworkEnum,
|
||||||
p2pContract
|
{ client, address }
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
etherStore.setDepositsValidList(depositLists.flat());
|
viemStore.setDepositsValidList(depositLists.flat());
|
||||||
etherStore.setLoadingNetworkLiquidity(false);
|
viemStore.setLoadingNetworkLiquidity(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
const getPixKey = async (seller: string, token: string): Promise<string> => {
|
const getPixKey = async (seller: string, token: string): Promise<string> => {
|
||||||
const p2pContract = await getContract();
|
const { address, abi, client } = await getContract();
|
||||||
const pixKeyHex = await p2pContract.getPixTarget(seller, token);
|
|
||||||
|
const pixKeyHex = await client.readContract({
|
||||||
|
address,
|
||||||
|
abi,
|
||||||
|
functionName: 'getPixTarget',
|
||||||
|
args: [seller, token]
|
||||||
|
});
|
||||||
|
|
||||||
// Remove '0x' prefix and convert hex to UTF-8 string
|
// Remove '0x' prefix and convert hex to UTF-8 string
|
||||||
|
const hexString = typeof pixKeyHex === 'string' ? pixKeyHex : toHex(pixKeyHex);
|
||||||
|
if (!hexString) throw new Error("PixKey not found");
|
||||||
const bytes = new Uint8Array(
|
const bytes = new Uint8Array(
|
||||||
pixKeyHex
|
// @ts-ignore
|
||||||
|
hexString
|
||||||
.slice(2)
|
.slice(2)
|
||||||
.match(/.{1,2}/g)
|
.match(/.{1,2}/g)
|
||||||
.map((byte: string) => parseInt(byte, 16))
|
.map((byte: string) => parseInt(byte, 16))
|
||||||
@ -59,50 +68,67 @@ const getPixKey = async (seller: string, token: string): Promise<string> => {
|
|||||||
const getValidDeposits = async (
|
const getValidDeposits = async (
|
||||||
token: string,
|
token: string,
|
||||||
network: NetworkEnum,
|
network: NetworkEnum,
|
||||||
contract?: Contract
|
contractInfo?: { client: any, address: string }
|
||||||
): Promise<ValidDeposit[]> => {
|
): Promise<ValidDeposit[]> => {
|
||||||
let p2pContract: Contract;
|
let client:PublicClient, address, abi;
|
||||||
|
|
||||||
if (contract) {
|
if (contractInfo) {
|
||||||
p2pContract = contract;
|
({ client, address } = contractInfo);
|
||||||
|
abi = p2pix.abi;
|
||||||
} else {
|
} else {
|
||||||
p2pContract = await getContract(true);
|
({ address, abi, client } = await getContract(true));
|
||||||
}
|
}
|
||||||
|
|
||||||
const filterDeposits = p2pContract.filters.DepositAdded(null);
|
const depositLogs = await client.getLogs({
|
||||||
const eventsDeposits = await p2pContract.queryFilter(
|
address,
|
||||||
filterDeposits
|
event: parseAbi([
|
||||||
// 0,
|
"event DepositAdded(address indexed seller, address token, uint256 amount)"
|
||||||
// "latest"
|
])[0],
|
||||||
);
|
fromBlock: 0n,
|
||||||
if (!contract) p2pContract = await getContract(); // get metamask provider contract
|
toBlock: 'latest'
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!contractInfo) {
|
||||||
|
// Get metamask provider contract
|
||||||
|
({ address, abi, client } = await getContract());
|
||||||
|
}
|
||||||
|
|
||||||
const depositList: { [key: string]: ValidDeposit } = {};
|
const depositList: { [key: string]: ValidDeposit } = {};
|
||||||
|
|
||||||
for (const deposit of eventsDeposits) {
|
for (const log of depositLogs) {
|
||||||
const IPix2Pix = new Interface(p2pix.abi);
|
try {
|
||||||
const decoded = IPix2Pix.parseLog({
|
const decoded = decodeEventLog({
|
||||||
topics: deposit.topics,
|
abi,
|
||||||
data: deposit.data,
|
data: log.data,
|
||||||
});
|
topics: log.topics
|
||||||
// Get liquidity only for the selected token
|
});
|
||||||
if (decoded?.args.token != token) continue;
|
|
||||||
const mappedBalance = await p2pContract.getBalance(
|
// Get liquidity only for the selected token
|
||||||
decoded.args.seller,
|
if (decoded?.args.token.toLowerCase() !== token.toLowerCase()) continue;
|
||||||
token
|
|
||||||
);
|
const mappedBalance = await client.readContract({
|
||||||
let validDeposit: ValidDeposit | null = null;
|
address,
|
||||||
|
abi,
|
||||||
|
functionName: 'getBalance',
|
||||||
|
args: [decoded.args.seller, token]
|
||||||
|
});
|
||||||
|
|
||||||
|
let validDeposit: ValidDeposit | null = null;
|
||||||
|
|
||||||
if (mappedBalance) {
|
if (mappedBalance) {
|
||||||
validDeposit = {
|
validDeposit = {
|
||||||
token: token,
|
token: token,
|
||||||
blockNumber: deposit.blockNumber,
|
blockNumber: Number(log.blockNumber),
|
||||||
remaining: Number(formatEther(mappedBalance)),
|
remaining: Number(formatEther(mappedBalance)),
|
||||||
seller: decoded.args.seller,
|
seller: decoded.args.seller,
|
||||||
network,
|
network,
|
||||||
pixKey: "",
|
pixKey: "",
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
if (validDeposit) depositList[decoded.args.seller + token] = validDeposit;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error decoding log", error);
|
||||||
}
|
}
|
||||||
if (validDeposit) depositList[decoded.args.seller + token] = validDeposit;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return Object.values(depositList);
|
return Object.values(depositList);
|
||||||
@ -111,15 +137,20 @@ const getValidDeposits = async (
|
|||||||
const getUnreleasedLockById = async (
|
const getUnreleasedLockById = async (
|
||||||
lockID: string
|
lockID: string
|
||||||
): Promise<UnreleasedLock> => {
|
): Promise<UnreleasedLock> => {
|
||||||
const p2pContract = await getContract();
|
const { address, abi, client } = await getContract();
|
||||||
const pixData: Pix = {
|
const pixData: Pix = {
|
||||||
pixKey: "",
|
pixKey: "",
|
||||||
};
|
};
|
||||||
|
|
||||||
const lock = await p2pContract.mapLocks(lockID);
|
const lock = await client.readContract({
|
||||||
|
address,
|
||||||
|
abi,
|
||||||
|
functionName: 'mapLocks',
|
||||||
|
args: [BigInt(lockID)]
|
||||||
|
});
|
||||||
|
|
||||||
const pixTarget = lock.pixTarget;
|
const pixTarget = lock.pixTarget;
|
||||||
const amount = formatEther(lock?.amount);
|
const amount = formatEther(lock.amount);
|
||||||
pixData.pixKey = pixTarget;
|
pixData.pixKey = pixTarget;
|
||||||
pixData.value = Number(amount);
|
pixData.value = Number(amount);
|
||||||
|
|
||||||
|
@ -1,27 +1,52 @@
|
|||||||
import p2pix from "@/utils/smart_contract_files/P2PIX.json";
|
import p2pix from "@/utils/smart_contract_files/P2PIX.json";
|
||||||
import { updateWalletStatus } from "./wallet";
|
import { updateWalletStatus } from "./wallet";
|
||||||
import { getProviderUrl, getP2PixAddress } from "./addresses";
|
import { getProviderUrl, getP2PixAddress } from "./addresses";
|
||||||
import { BrowserProvider, JsonRpcProvider, Contract } from "ethers";
|
import { createPublicClient, createWalletClient, custom, http } from "viem";
|
||||||
|
import { sepolia, rootstock } from "viem/chains";
|
||||||
|
import { useViemStore } from "@/store/viem";
|
||||||
|
|
||||||
let provider: BrowserProvider | JsonRpcProvider | null = null;
|
let publicClient = null;
|
||||||
|
let walletClient = null;
|
||||||
|
|
||||||
const getProvider = (onlyAlchemyProvider: boolean = false) => {
|
const getPublicClient = (onlyRpcProvider = false) => {
|
||||||
if (onlyAlchemyProvider) return new JsonRpcProvider(getProviderUrl()); // alchemy provider
|
if (onlyRpcProvider) {
|
||||||
return provider;
|
const viemStore = useViemStore();
|
||||||
|
const rpcUrl = getProviderUrl();
|
||||||
|
return createPublicClient({
|
||||||
|
chain: viemStore.networkName === sepolia.id ? sepolia : rootstock,
|
||||||
|
transport: http(rpcUrl)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return publicClient;
|
||||||
};
|
};
|
||||||
|
|
||||||
const getContract = async (onlyAlchemyProvider: boolean = false) => {
|
const getWalletClient = () => {
|
||||||
const p = getProvider(onlyAlchemyProvider);
|
return walletClient;
|
||||||
try {
|
};
|
||||||
const signer = await p?.getSigner();
|
|
||||||
return new Contract(getP2PixAddress(), p2pix.abi, signer);
|
const getContract = async (onlyRpcProvider = false) => {
|
||||||
} catch (err) {
|
const client = getPublicClient(onlyRpcProvider);
|
||||||
return new Contract(getP2PixAddress(), p2pix.abi, p);
|
const address = getP2PixAddress();
|
||||||
}
|
const abi = p2pix.abi;
|
||||||
|
|
||||||
|
return { address, abi, client };
|
||||||
};
|
};
|
||||||
|
|
||||||
const connectProvider = async (p: any): Promise<void> => {
|
const connectProvider = async (p: any): Promise<void> => {
|
||||||
provider = new BrowserProvider(p, "any");
|
const viemStore = useViemStore();
|
||||||
|
const chain = viemStore.networkName === sepolia.id ? sepolia : rootstock;
|
||||||
|
|
||||||
|
publicClient = createPublicClient({
|
||||||
|
chain,
|
||||||
|
transport: custom(p)
|
||||||
|
});
|
||||||
|
|
||||||
|
walletClient = createWalletClient({
|
||||||
|
chain,
|
||||||
|
transport: custom(p)
|
||||||
|
});
|
||||||
|
|
||||||
await updateWalletStatus();
|
await updateWalletStatus();
|
||||||
};
|
};
|
||||||
export { getProvider, getContract, connectProvider };
|
|
||||||
|
export { getPublicClient, getWalletClient, getContract, connectProvider };
|
||||||
|
@ -1,60 +1,81 @@
|
|||||||
import { getContract, getProvider } from "./provider";
|
import { getContract, getPublicClient, getWalletClient } from "./provider";
|
||||||
import { getTokenAddress, getP2PixAddress } from "./addresses";
|
import { getTokenAddress, getP2PixAddress } from "./addresses";
|
||||||
|
import { parseEther, toHex } from "viem";
|
||||||
import { encodeBytes32String, Contract, parseEther } from "ethers";
|
|
||||||
|
|
||||||
import mockToken from "../utils/smart_contract_files/MockToken.json";
|
import mockToken from "../utils/smart_contract_files/MockToken.json";
|
||||||
import { useEtherStore } from "@/store/ether";
|
import { useViemStore } from "@/store/viem";
|
||||||
import { createParticipant } from "@/utils/bbPay";
|
import { createParticipant } from "@/utils/bbPay";
|
||||||
import type { Participant } from "@/utils/bbPay";
|
import type { Participant } from "@/utils/bbPay";
|
||||||
|
|
||||||
const approveTokens = async (participant: Participant): Promise<any> => {
|
const approveTokens = async (participant: Participant): Promise<any> => {
|
||||||
const provider = getProvider();
|
const viemStore = useViemStore();
|
||||||
const signer = await provider?.getSigner();
|
const publicClient = getPublicClient();
|
||||||
const etherStore = useEtherStore();
|
const walletClient = getWalletClient();
|
||||||
|
|
||||||
etherStore.setSeller(participant);
|
if (!publicClient || !walletClient) {
|
||||||
const tokenContract = new Contract(
|
throw new Error("Clients not initialized");
|
||||||
getTokenAddress(etherStore.selectedToken),
|
}
|
||||||
mockToken.abi,
|
|
||||||
signer
|
viemStore.setSeller(participant);
|
||||||
);
|
const [account] = await walletClient.getAddresses();
|
||||||
|
|
||||||
|
// Get token address
|
||||||
|
const tokenAddress = getTokenAddress(viemStore.selectedToken);
|
||||||
|
|
||||||
// Check if the token is already approved
|
// Check if the token is already approved
|
||||||
const approved = await tokenContract.allowance(
|
const allowance = await publicClient.readContract({
|
||||||
await signer?.getAddress(),
|
address: tokenAddress,
|
||||||
getP2PixAddress()
|
abi: mockToken.abi,
|
||||||
);
|
functionName: 'allowance',
|
||||||
if (approved < parseEther(participant.offer)) {
|
args: [account, getP2PixAddress()]
|
||||||
|
});
|
||||||
|
|
||||||
|
if (allowance < parseEther(participant.offer)) {
|
||||||
// Approve tokens
|
// Approve tokens
|
||||||
const apprv = await tokenContract.approve(
|
const hash = await walletClient.writeContract({
|
||||||
getP2PixAddress(),
|
address: tokenAddress,
|
||||||
parseEther(participant.offer)
|
abi: mockToken.abi,
|
||||||
);
|
functionName: 'approve',
|
||||||
await apprv.wait();
|
args: [getP2PixAddress(), parseEther(participant.offer)],
|
||||||
|
account
|
||||||
|
});
|
||||||
|
|
||||||
|
await publicClient.waitForTransactionReceipt({ hash });
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
|
|
||||||
const addDeposit = async (): Promise<any> => {
|
const addDeposit = async (): Promise<any> => {
|
||||||
const p2pContract = await getContract();
|
const { address, abi, client } = await getContract();
|
||||||
const etherStore = useEtherStore();
|
const walletClient = getWalletClient();
|
||||||
|
const viemStore = useViemStore();
|
||||||
const sellerId = await createParticipant(etherStore.seller);
|
|
||||||
etherStore.setSellerId(sellerId.id);
|
if (!walletClient) {
|
||||||
|
throw new Error("Wallet client not initialized");
|
||||||
const deposit = await p2pContract.deposit(
|
}
|
||||||
sellerId,
|
|
||||||
encodeBytes32String(""),
|
const [account] = await walletClient.getAddresses();
|
||||||
getTokenAddress(etherStore.selectedToken),
|
|
||||||
parseEther(etherStore.seller.offer),
|
const sellerId = await createParticipant(viemStore.seller);
|
||||||
true
|
viemStore.setSellerId(sellerId.id);
|
||||||
);
|
|
||||||
|
const hash = await walletClient.writeContract({
|
||||||
await deposit.wait();
|
address,
|
||||||
|
abi,
|
||||||
return deposit;
|
functionName: 'deposit',
|
||||||
|
args: [
|
||||||
|
sellerId.id,
|
||||||
|
toHex("", { size: 32 }),
|
||||||
|
getTokenAddress(viemStore.selectedToken),
|
||||||
|
parseEther(viemStore.seller.offer),
|
||||||
|
true
|
||||||
|
],
|
||||||
|
account
|
||||||
|
});
|
||||||
|
|
||||||
|
const receipt = await client.waitForTransactionReceipt({ hash });
|
||||||
|
return receipt;
|
||||||
};
|
};
|
||||||
|
|
||||||
export { approveTokens, addDeposit };
|
export { approveTokens, addDeposit };
|
||||||
|
@ -1,14 +1,13 @@
|
|||||||
import {
|
import {
|
||||||
Contract,
|
decodeEventLog,
|
||||||
formatEther,
|
formatEther,
|
||||||
getAddress,
|
getAddress,
|
||||||
Interface,
|
type Log,
|
||||||
Log,
|
parseAbi,
|
||||||
LogDescription,
|
} from "viem";
|
||||||
} from "ethers";
|
import { useViemStore } from "@/store/viem";
|
||||||
import { useEtherStore } from "@/store/ether";
|
|
||||||
|
|
||||||
import { getContract, getProvider } from "./provider";
|
import { getPublicClient, getWalletClient, getContract } from "./provider";
|
||||||
import { getTokenAddress, isPossibleNetwork } from "./addresses";
|
import { getTokenAddress, isPossibleNetwork } from "./addresses";
|
||||||
|
|
||||||
import mockToken from "@/utils/smart_contract_files/MockToken.json";
|
import mockToken from "@/utils/smart_contract_files/MockToken.json";
|
||||||
@ -22,43 +21,51 @@ import type { UnreleasedLock } from "@/model/UnreleasedLock";
|
|||||||
import type { Pix } from "@/model/Pix";
|
import type { Pix } from "@/model/Pix";
|
||||||
|
|
||||||
export const updateWalletStatus = async (): Promise<void> => {
|
export const updateWalletStatus = async (): Promise<void> => {
|
||||||
const etherStore = useEtherStore();
|
const viemStore = useViemStore();
|
||||||
|
|
||||||
const provider = await getProvider();
|
const publicClient = getPublicClient();
|
||||||
const signer = await provider?.getSigner();
|
const walletClient = getWalletClient();
|
||||||
const network = await provider?.getNetwork();
|
|
||||||
const chainId = network?.chainId;
|
if (!publicClient || !walletClient) {
|
||||||
|
console.error("Client not initialized");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const chainId = await publicClient.getChainId();
|
||||||
if (!isPossibleNetwork(Number(chainId))) {
|
if (!isPossibleNetwork(Number(chainId))) {
|
||||||
window.alert("Invalid chain!:" + chainId);
|
window.alert("Invalid chain!:" + chainId);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
etherStore.setNetworkId(Number(chainId));
|
viemStore.setNetworkId(Number(chainId));
|
||||||
|
|
||||||
const mockTokenContract = new Contract(
|
// Get account address
|
||||||
getTokenAddress(etherStore.selectedToken),
|
const [address] = await walletClient.getAddresses();
|
||||||
mockToken.abi,
|
|
||||||
signer
|
// Get token balance
|
||||||
);
|
const tokenAddress = getTokenAddress(viemStore.selectedToken);
|
||||||
|
const balanceResult = await publicClient.readContract({
|
||||||
|
address: tokenAddress,
|
||||||
|
abi: mockToken.abi,
|
||||||
|
functionName: 'balanceOf',
|
||||||
|
args: [address]
|
||||||
|
});
|
||||||
|
|
||||||
const walletAddress = await provider?.send("eth_requestAccounts", []);
|
viemStore.setBalance(formatEther(balanceResult));
|
||||||
const balance = await mockTokenContract.balanceOf(walletAddress[0]);
|
viemStore.setWalletAddress(getAddress(address));
|
||||||
|
|
||||||
etherStore.setBalance(formatEther(balance));
|
|
||||||
etherStore.setWalletAddress(getAddress(walletAddress[0]));
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const listValidDepositTransactionsByWalletAddress = async (
|
export const listValidDepositTransactionsByWalletAddress = async (
|
||||||
walletAddress: string
|
walletAddress: string
|
||||||
): Promise<ValidDeposit[]> => {
|
): Promise<ValidDeposit[]> => {
|
||||||
const etherStore = useEtherStore();
|
const viemStore = useViemStore();
|
||||||
const walletDeposits = await getValidDeposits(
|
const walletDeposits = await getValidDeposits(
|
||||||
getTokenAddress(etherStore.selectedToken),
|
getTokenAddress(viemStore.selectedToken),
|
||||||
etherStore.networkName
|
viemStore.networkName
|
||||||
);
|
);
|
||||||
if (walletDeposits) {
|
if (walletDeposits) {
|
||||||
return walletDeposits
|
return walletDeposits
|
||||||
.filter((deposit) => deposit.seller == walletAddress)
|
.filter((deposit) => deposit.seller == walletAddress)
|
||||||
.sort((a, b) => {
|
.sort((a: ValidDeposit, b: ValidDeposit) => {
|
||||||
return b.blockNumber - a.blockNumber;
|
return b.blockNumber - a.blockNumber;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -66,10 +73,15 @@ export const listValidDepositTransactionsByWalletAddress = async (
|
|||||||
return [];
|
return [];
|
||||||
};
|
};
|
||||||
|
|
||||||
const getLockStatus = async (id: [BigInt]): Promise<number> => {
|
const getLockStatus = async (id: bigint): Promise<number> => {
|
||||||
const p2pContract = await getContract();
|
const { address, abi, client } = await getContract();
|
||||||
const res = await p2pContract.getLocksStatus([id]);
|
const result = await client.readContract({
|
||||||
return res[1][0];
|
address,
|
||||||
|
abi,
|
||||||
|
functionName: 'getLocksStatus',
|
||||||
|
args: [[id]]
|
||||||
|
});
|
||||||
|
return result[1][0];
|
||||||
};
|
};
|
||||||
|
|
||||||
const filterLockStatus = async (
|
const filterLockStatus = async (
|
||||||
@ -78,31 +90,40 @@ const filterLockStatus = async (
|
|||||||
const txs: WalletTransaction[] = [];
|
const txs: WalletTransaction[] = [];
|
||||||
|
|
||||||
for (const transaction of transactions) {
|
for (const transaction of transactions) {
|
||||||
const IPix2Pix = new Interface(p2pix.abi);
|
try {
|
||||||
const decoded = IPix2Pix.parseLog({
|
const decoded = decodeEventLog({
|
||||||
topics: transaction.topics,
|
abi: p2pix.abi,
|
||||||
data: transaction.data,
|
data: transaction.data,
|
||||||
});
|
topics: transaction.topics,
|
||||||
if (!decoded) continue;
|
});
|
||||||
const tx: WalletTransaction = {
|
|
||||||
token: decoded.args.token ? decoded.args.token : "",
|
if (!decoded || !decoded.args) continue;
|
||||||
blockNumber: transaction.blockNumber,
|
|
||||||
amount: decoded.args.amount
|
// Type assertion to handle the args safely
|
||||||
? Number(formatEther(decoded.args.amount))
|
const args = decoded.args as Record<string, any>;
|
||||||
: -1,
|
|
||||||
seller: decoded.args.seller ? decoded.args.seller : "",
|
const tx: WalletTransaction = {
|
||||||
buyer: decoded.args.buyer ? decoded.args.buyer : "",
|
token: args.token ? String(args.token) : "",
|
||||||
event: decoded.name,
|
blockNumber: Number(transaction.blockNumber),
|
||||||
lockStatus:
|
amount: args.amount
|
||||||
decoded.name == "LockAdded"
|
? Number(formatEther(args.amount))
|
||||||
? await getLockStatus(decoded.args.lockID)
|
|
||||||
: -1,
|
: -1,
|
||||||
transactionHash: transaction.transactionHash
|
seller: args.seller ? String(args.seller) : "",
|
||||||
? transaction.transactionHash
|
buyer: args.buyer ? String(args.buyer) : "",
|
||||||
: "",
|
event: decoded.eventName || "",
|
||||||
transactionID: decoded.args.lockID ? decoded.args.lockID.toString() : "",
|
lockStatus:
|
||||||
};
|
decoded.eventName == "LockAdded" && args.lockID
|
||||||
txs.push(tx);
|
? await getLockStatus(args.lockID)
|
||||||
|
: -1,
|
||||||
|
transactionHash: transaction.transactionHash
|
||||||
|
? transaction.transactionHash
|
||||||
|
: "",
|
||||||
|
transactionID: args.lockID ? args.lockID.toString() : "",
|
||||||
|
};
|
||||||
|
txs.push(tx);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error decoding log", error);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return txs;
|
return txs;
|
||||||
};
|
};
|
||||||
@ -110,162 +131,212 @@ const filterLockStatus = async (
|
|||||||
export const listAllTransactionByWalletAddress = async (
|
export const listAllTransactionByWalletAddress = async (
|
||||||
walletAddress: string
|
walletAddress: string
|
||||||
): Promise<WalletTransaction[]> => {
|
): Promise<WalletTransaction[]> => {
|
||||||
const p2pContract = await getContract(true);
|
const { address, abi, client } = await getContract(true);
|
||||||
|
|
||||||
// Get deposits
|
// Get deposits
|
||||||
const filterDeposits = p2pContract.filters.DepositAdded([walletAddress]);
|
const depositLogs = await client.getLogs({
|
||||||
const eventsDeposits = await p2pContract.queryFilter(
|
address,
|
||||||
filterDeposits,
|
event: parseAbi(['event DepositAdded(address indexed seller, address token, uint256 amount)'])[0],
|
||||||
0,
|
args: {
|
||||||
"latest"
|
seller: walletAddress
|
||||||
);
|
},
|
||||||
|
fromBlock: 0n,
|
||||||
|
toBlock: 'latest'
|
||||||
|
});
|
||||||
console.log("Fetched all wallet deposits");
|
console.log("Fetched all wallet deposits");
|
||||||
|
|
||||||
// Get locks
|
// Get locks
|
||||||
const filterAddedLocks = p2pContract.filters.LockAdded([walletAddress]);
|
const lockLogs = await client.getLogs({
|
||||||
const eventsAddedLocks = await p2pContract.queryFilter(
|
address,
|
||||||
filterAddedLocks,
|
event: parseAbi(['event LockAdded(address indexed buyer, uint256 indexed lockID, address seller, address token, uint256 amount)'])[0],
|
||||||
0,
|
args: {
|
||||||
"latest"
|
buyer: walletAddress
|
||||||
);
|
},
|
||||||
|
fromBlock: 0n,
|
||||||
|
toBlock: 'latest'
|
||||||
|
});
|
||||||
console.log("Fetched all wallet locks");
|
console.log("Fetched all wallet locks");
|
||||||
|
|
||||||
// Get released locks
|
// Get released locks
|
||||||
const filterReleasedLocks = p2pContract.filters.LockReleased([walletAddress]);
|
const releasedLogs = await client.getLogs({
|
||||||
const eventsReleasedLocks = await p2pContract.queryFilter(
|
address,
|
||||||
filterReleasedLocks,
|
event: parseAbi(['event LockReleased(address indexed buyer, uint256 indexed lockID, string e2eId)'])[0],
|
||||||
0,
|
args: {
|
||||||
"latest"
|
buyer: walletAddress
|
||||||
);
|
},
|
||||||
|
fromBlock: 0n,
|
||||||
|
toBlock: 'latest'
|
||||||
|
});
|
||||||
console.log("Fetched all wallet released locks");
|
console.log("Fetched all wallet released locks");
|
||||||
|
|
||||||
// Get withdrawn deposits
|
// Get withdrawn deposits
|
||||||
const filterWithdrawnDeposits = p2pContract.filters.DepositWithdrawn([
|
const withdrawnLogs = await client.getLogs({
|
||||||
walletAddress,
|
address,
|
||||||
]);
|
event: parseAbi(['event DepositWithdrawn(address indexed seller, address token, uint256 amount)'])[0],
|
||||||
const eventsWithdrawnDeposits = await p2pContract.queryFilter(
|
args: {
|
||||||
filterWithdrawnDeposits
|
seller: walletAddress
|
||||||
);
|
},
|
||||||
|
fromBlock: 0n,
|
||||||
|
toBlock: 'latest'
|
||||||
|
});
|
||||||
console.log("Fetched all wallet withdrawn deposits");
|
console.log("Fetched all wallet withdrawn deposits");
|
||||||
|
|
||||||
const lockStatusFiltered = await filterLockStatus(
|
const allLogs = [
|
||||||
[
|
...depositLogs,
|
||||||
...eventsDeposits,
|
...lockLogs,
|
||||||
...eventsAddedLocks,
|
...releasedLogs,
|
||||||
...eventsReleasedLocks,
|
...withdrawnLogs
|
||||||
...eventsWithdrawnDeposits,
|
].sort((a: Log, b: Log) => {
|
||||||
].sort((a, b) => {
|
return Number(b.blockNumber) - Number(a.blockNumber);
|
||||||
return b.blockNumber - a.blockNumber;
|
});
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
return lockStatusFiltered;
|
return await filterLockStatus(allLogs);
|
||||||
};
|
};
|
||||||
|
|
||||||
// get wallet's release transactions
|
// get wallet's release transactions
|
||||||
export const listReleaseTransactionByWalletAddress = async (
|
export const listReleaseTransactionByWalletAddress = async (
|
||||||
walletAddress: string
|
walletAddress: string
|
||||||
): Promise<LogDescription[]> => {
|
) => {
|
||||||
const p2pContract = await getContract(true);
|
const { address, abi, client } = await getContract(true);
|
||||||
|
|
||||||
const filterReleasedLocks = p2pContract.filters.LockReleased([walletAddress]);
|
const releasedLogs = await client.getLogs({
|
||||||
const eventsReleasedLocks = await p2pContract.queryFilter(
|
address,
|
||||||
filterReleasedLocks,
|
event: parseAbi(['event LockReleased(address indexed buyer, uint256 indexed lockID, string e2eId)'])[0],
|
||||||
0,
|
args: {
|
||||||
"latest"
|
buyer: walletAddress
|
||||||
);
|
},
|
||||||
|
fromBlock: 0n,
|
||||||
|
toBlock: 'latest'
|
||||||
|
});
|
||||||
|
|
||||||
return eventsReleasedLocks
|
return releasedLogs
|
||||||
.sort((a, b) => {
|
.sort((a: Log, b: Log) => {
|
||||||
return b.blockNumber - a.blockNumber;
|
return Number(b.blockNumber) - Number(a.blockNumber);
|
||||||
})
|
})
|
||||||
.map((lock) => {
|
.map((log: Log) => {
|
||||||
const IPix2Pix = new Interface(p2pix.abi);
|
try {
|
||||||
const decoded = IPix2Pix.parseLog({
|
return decodeEventLog({
|
||||||
topics: lock.topics,
|
abi: p2pix.abi,
|
||||||
data: lock.data,
|
data: log.data,
|
||||||
});
|
topics: log.topics
|
||||||
return decoded;
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error decoding log", error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.filter((lock) => lock !== null);
|
.filter((decoded: any) => decoded !== null);
|
||||||
};
|
};
|
||||||
|
|
||||||
const listLockTransactionByWalletAddress = async (
|
const listLockTransactionByWalletAddress = async (
|
||||||
walletAddress: string
|
walletAddress: string
|
||||||
): Promise<LogDescription[]> => {
|
) => {
|
||||||
const p2pContract = await getContract(true);
|
const { address, abi, client } = await getContract(true);
|
||||||
|
|
||||||
const filterAddedLocks = p2pContract.filters.LockAdded([walletAddress]);
|
const lockLogs = await client.getLogs({
|
||||||
const eventsReleasedLocks = await p2pContract.queryFilter(filterAddedLocks);
|
address,
|
||||||
|
event: parseAbi(['event LockAdded(address indexed buyer, uint256 indexed lockID, address seller, address token, uint256 amount)'])[0],
|
||||||
|
args: {
|
||||||
|
buyer: walletAddress
|
||||||
|
},
|
||||||
|
fromBlock: 0n,
|
||||||
|
toBlock: 'latest'
|
||||||
|
});
|
||||||
|
|
||||||
return eventsReleasedLocks
|
return lockLogs
|
||||||
.sort((a, b) => {
|
.sort((a:Log, b:Log) => {
|
||||||
return b.blockNumber - a.blockNumber;
|
return Number(b.blockNumber) - Number(a.blockNumber);
|
||||||
})
|
})
|
||||||
.map((lock) => {
|
.map((log: Log) => {
|
||||||
const IPix2Pix = new Interface(p2pix.abi);
|
try {
|
||||||
const decoded = IPix2Pix.parseLog({
|
return decodeEventLog({
|
||||||
topics: lock.topics,
|
abi: p2pix.abi,
|
||||||
data: lock.data,
|
data: log.data,
|
||||||
});
|
topics: log.topics
|
||||||
return decoded;
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error decoding log", error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.filter((lock) => lock !== null);
|
.filter((decoded:any) => decoded !== null);
|
||||||
};
|
};
|
||||||
|
|
||||||
const listLockTransactionBySellerAddress = async (
|
const listLockTransactionBySellerAddress = async (
|
||||||
sellerAddress: string
|
sellerAddress: string
|
||||||
): Promise<LogDescription[]> => {
|
) => {
|
||||||
const p2pContract = await getContract(true);
|
const { address, abi, client } = await getContract(true);
|
||||||
console.log("Will get locks as seller", sellerAddress);
|
console.log("Will get locks as seller", sellerAddress);
|
||||||
const filterAddedLocks = p2pContract.filters.LockAdded();
|
|
||||||
const eventsReleasedLocks = await p2pContract.queryFilter(
|
const lockLogs = await client.getLogs({
|
||||||
filterAddedLocks
|
address,
|
||||||
// 0,
|
event: parseAbi(['event LockAdded(address indexed buyer, uint256 indexed lockID, address seller, address token, uint256 amount)'])[0],
|
||||||
// "latest"
|
fromBlock: 0n,
|
||||||
);
|
toBlock: 'latest'
|
||||||
return eventsReleasedLocks
|
});
|
||||||
.map((lock) => {
|
|
||||||
const IPix2Pix = new Interface(p2pix.abi);
|
return lockLogs
|
||||||
const decoded = IPix2Pix.parseLog({
|
.map((log: Log) => {
|
||||||
topics: lock.topics,
|
try {
|
||||||
data: lock.data,
|
return decodeEventLog({
|
||||||
});
|
abi: p2pix.abi,
|
||||||
return decoded;
|
data: log.data,
|
||||||
|
topics: log.topics
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error decoding log", error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.filter((lock) => lock !== null)
|
.filter((decoded: any) => decoded !== null)
|
||||||
.filter(
|
.filter(
|
||||||
(lock) => lock.args.seller.toLowerCase() == sellerAddress.toLowerCase()
|
(decoded:any) => decoded.args && decoded.args.seller &&
|
||||||
|
decoded.args.seller.toLowerCase() === sellerAddress.toLowerCase()
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const checkUnreleasedLock = async (
|
export const checkUnreleasedLock = async (
|
||||||
walletAddress: string
|
walletAddress: string
|
||||||
): Promise<UnreleasedLock | undefined> => {
|
): Promise<UnreleasedLock | undefined> => {
|
||||||
const p2pContract = await getContract();
|
const { address, abi, client } = await getContract();
|
||||||
const pixData: Pix = {
|
const pixData: Pix = {
|
||||||
pixKey: "",
|
pixKey: "",
|
||||||
};
|
};
|
||||||
|
|
||||||
const addedLocks = await listLockTransactionByWalletAddress(walletAddress);
|
const addedLocks = await listLockTransactionByWalletAddress(walletAddress);
|
||||||
const lockStatus = await p2pContract.getLocksStatus(
|
|
||||||
addedLocks.map((lock) => lock.args?.lockID)
|
if (!addedLocks.length) return undefined;
|
||||||
);
|
|
||||||
|
const lockIds = addedLocks.map((lock: any) => lock.args.lockID);
|
||||||
|
|
||||||
|
const lockStatus = await client.readContract({
|
||||||
|
address,
|
||||||
|
abi,
|
||||||
|
functionName: 'getLocksStatus',
|
||||||
|
args: [lockIds]
|
||||||
|
});
|
||||||
|
|
||||||
const unreleasedLockId = lockStatus[1].findIndex(
|
const unreleasedLockId = lockStatus[1].findIndex(
|
||||||
(lockStatus: number) => lockStatus == 1
|
(status: number) => status == 1
|
||||||
);
|
);
|
||||||
|
|
||||||
if (unreleasedLockId != -1) {
|
if (unreleasedLockId !== -1) {
|
||||||
const _lockID = lockStatus[0][unreleasedLockId];
|
const lockID = lockStatus[0][unreleasedLockId];
|
||||||
const lock = await p2pContract.mapLocks(_lockID);
|
|
||||||
|
const lock = await client.readContract({
|
||||||
|
address,
|
||||||
|
abi,
|
||||||
|
functionName: 'mapLocks',
|
||||||
|
args: [lockID]
|
||||||
|
});
|
||||||
|
|
||||||
const pixTarget = lock.pixTarget;
|
const pixTarget = lock.pixTarget;
|
||||||
const amount = formatEther(lock?.amount);
|
const amount = formatEther(lock.amount);
|
||||||
pixData.pixKey = pixTarget;
|
pixData.pixKey = pixTarget;
|
||||||
pixData.value = Number(amount);
|
pixData.value = Number(amount);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
lockID: _lockID,
|
lockID,
|
||||||
pix: pixData,
|
pix: pixData,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@ -274,27 +345,33 @@ export const checkUnreleasedLock = async (
|
|||||||
export const getActiveLockAmount = async (
|
export const getActiveLockAmount = async (
|
||||||
walletAddress: string
|
walletAddress: string
|
||||||
): Promise<number> => {
|
): Promise<number> => {
|
||||||
const p2pContract = await getContract(true);
|
const { address, abi, client } = await getContract(true);
|
||||||
const lockSeller = await listLockTransactionBySellerAddress(walletAddress);
|
const lockSeller = await listLockTransactionBySellerAddress(walletAddress);
|
||||||
|
|
||||||
const lockStatus = await p2pContract.getLocksStatus(
|
if (!lockSeller.length) return 0;
|
||||||
lockSeller.map((lock) => lock.args?.lockID)
|
|
||||||
);
|
|
||||||
|
|
||||||
const activeLockAmount = await lockStatus[1].reduce(
|
const lockIds = lockSeller.map((lock: any) => lock.args.lockID);
|
||||||
async (sumValue: Promise<number>, currentStatus: number, index: number) => {
|
|
||||||
const currValue = await sumValue;
|
const lockStatus = await client.readContract({
|
||||||
let valueToSum = 0;
|
address,
|
||||||
|
abi,
|
||||||
|
functionName: 'getLocksStatus',
|
||||||
|
args: [lockIds]
|
||||||
|
});
|
||||||
|
|
||||||
if (currentStatus == 1) {
|
let activeLockAmount = 0;
|
||||||
const lock = await p2pContract.mapLocks(lockStatus[0][index]);
|
for (let i = 0; i < lockStatus[1].length; i++) {
|
||||||
valueToSum = Number(formatEther(lock?.amount));
|
if (lockStatus[1][i] === 1) {
|
||||||
}
|
const lockId = lockStatus[0][i];
|
||||||
|
const lock = await client.readContract({
|
||||||
return currValue + valueToSum;
|
address,
|
||||||
},
|
abi,
|
||||||
Promise.resolve(0)
|
functionName: 'mapLocks',
|
||||||
);
|
args: [lockId]
|
||||||
|
});
|
||||||
|
activeLockAmount += Number(formatEther(lock.amount));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return activeLockAmount;
|
return activeLockAmount;
|
||||||
};
|
};
|
||||||
|
@ -8,8 +8,8 @@ import {
|
|||||||
import CustomButton from "@/components/CustomButton/CustomButton.vue";
|
import CustomButton from "@/components/CustomButton/CustomButton.vue";
|
||||||
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 { useEtherStore } from "@/store/ether";
|
import { useViemStore } from "@/store/viem";
|
||||||
import { storeToRefs } from "pinia";
|
import { NetworkEnum } from "@/model/NetworkEnum";
|
||||||
import { onMounted, ref, watch } from "vue";
|
import { onMounted, ref, watch } from "vue";
|
||||||
import ListingComponent from "../ListingComponent/ListingComponent.vue";
|
import ListingComponent from "../ListingComponent/ListingComponent.vue";
|
||||||
|
|
||||||
@ -19,8 +19,8 @@ const props = defineProps<{
|
|||||||
isCurrentStep: boolean;
|
isCurrentStep: boolean;
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
const etherStore = useEtherStore();
|
const viemStore = useViemStore();
|
||||||
const { walletAddress } = storeToRefs(etherStore);
|
const { walletAddress } = storeToRefs(viemStore);
|
||||||
|
|
||||||
const lastWalletTransactions = ref<WalletTransaction[]>([]);
|
const lastWalletTransactions = ref<WalletTransaction[]>([]);
|
||||||
const depositList = ref<ValidDeposit[]>([]);
|
const depositList = ref<ValidDeposit[]>([]);
|
||||||
@ -29,7 +29,7 @@ const activeLockAmount = ref<number>(0);
|
|||||||
// methods
|
// methods
|
||||||
|
|
||||||
const getWalletTransactions = async () => {
|
const getWalletTransactions = async () => {
|
||||||
etherStore.setLoadingWalletTransactions(true);
|
viemStore.setLoadingWalletTransactions(true);
|
||||||
if (walletAddress.value) {
|
if (walletAddress.value) {
|
||||||
const walletDeposits = await listValidDepositTransactionsByWalletAddress(
|
const walletDeposits = await listValidDepositTransactionsByWalletAddress(
|
||||||
walletAddress.value
|
walletAddress.value
|
||||||
@ -48,20 +48,20 @@ const getWalletTransactions = async () => {
|
|||||||
lastWalletTransactions.value = allUserTransactions;
|
lastWalletTransactions.value = allUserTransactions;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
etherStore.setLoadingWalletTransactions(false);
|
viemStore.setLoadingWalletTransactions(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
const callWithdraw = async (amount: string) => {
|
const callWithdraw = async (amount: string) => {
|
||||||
if (amount) {
|
if (amount) {
|
||||||
etherStore.setLoadingWalletTransactions(true);
|
viemStore.setLoadingWalletTransactions(true);
|
||||||
const withdraw = await withdrawDeposit(amount, etherStore.selectedToken);
|
const withdraw = await withdrawDeposit(amount, viemStore.selectedToken);
|
||||||
if (withdraw) {
|
if (withdraw) {
|
||||||
console.log("Saque realizado!");
|
console.log("Saque realizado!");
|
||||||
await getWalletTransactions();
|
await getWalletTransactions();
|
||||||
} else {
|
} else {
|
||||||
console.log("Não foi possível realizar o saque!");
|
console.log("Não foi possível realizar o saque!");
|
||||||
}
|
}
|
||||||
etherStore.setLoadingWalletTransactions(false);
|
viemStore.setLoadingWalletTransactions(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -93,14 +93,14 @@ onMounted(async () => {
|
|||||||
<div>
|
<div>
|
||||||
<p>Tokens recebidos</p>
|
<p>Tokens recebidos</p>
|
||||||
<p class="text-2xl text-gray-900">
|
<p class="text-2xl text-gray-900">
|
||||||
{{ props.tokenAmount }} {{ etherStore.selectedToken }}
|
{{ props.tokenAmount }} {{ viemStore.selectedToken }}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="my-5">
|
<div class="my-5">
|
||||||
<p class="text-sm">
|
<p class="text-sm">
|
||||||
<b>Não encontrou os tokens? </b><br />Clique no botão abaixo para
|
<b>Não encontrou os tokens? </b><br />Clique no botão abaixo para
|
||||||
<br />
|
<br />
|
||||||
cadastrar o {{ etherStore.selectedToken }} em sua carteira.
|
cadastrar o {{ viemStore.selectedToken }} em sua carteira.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<CustomButton :text="'Cadastrar token'" @buttonClicked="() => {}" />
|
<CustomButton :text="'Cadastrar token'" @buttonClicked="() => {}" />
|
||||||
|
@ -3,7 +3,7 @@ import { withdrawDeposit } from "@/blockchain/buyerMethods";
|
|||||||
import { NetworkEnum } from "@/model/NetworkEnum";
|
import { NetworkEnum } from "@/model/NetworkEnum";
|
||||||
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 { useEtherStore } from "@/store/ether";
|
import { useViemStore } from "@/store/viem";
|
||||||
import { storeToRefs } from "pinia";
|
import { storeToRefs } from "pinia";
|
||||||
import { ref, watch, onMounted } from "vue";
|
import { ref, watch, onMounted } from "vue";
|
||||||
import SpinnerComponent from "../SpinnerComponent.vue";
|
import SpinnerComponent from "../SpinnerComponent.vue";
|
||||||
@ -12,7 +12,7 @@ import { debounce } from "@/utils/debounce";
|
|||||||
import { getTokenByAddress } from "@/blockchain/addresses";
|
import { getTokenByAddress } from "@/blockchain/addresses";
|
||||||
import { useFloating, arrow, offset, flip, shift } from "@floating-ui/vue";
|
import { useFloating, arrow, offset, flip, shift } from "@floating-ui/vue";
|
||||||
|
|
||||||
const etherStore = useEtherStore();
|
const etherStore = useViemStore();
|
||||||
|
|
||||||
// props
|
// props
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
|
@ -1,15 +1,14 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
import { mount } from "@vue/test-utils";
|
import { mount } from "@vue/test-utils";
|
||||||
import ListingComponent from "@/components/ListingComponent/ListingComponent.vue";
|
import ListingComponent from "../ListingComponent.vue";
|
||||||
import { createPinia, setActivePinia } from "pinia";
|
import SpinnerComponent from "../../SpinnerComponent.vue";
|
||||||
import { expect } from "vitest";
|
import { useViemStore } from "@/store/viem";
|
||||||
import { MockValidDeposits } from "@/model/mock/ValidDepositMock";
|
import { MockValidDeposits } from "@/model/mock/ValidDepositMock";
|
||||||
import { MockWalletTransactions } from "@/model/mock/WalletTransactionMock";
|
import { MockWalletTransactions } from "@/model/mock/WalletTransactionMock";
|
||||||
import { useEtherStore } from "@/store/ether";
|
|
||||||
|
|
||||||
describe("ListingComponent.vue", () => {
|
describe("ListingComponent.vue", () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
setActivePinia(createPinia());
|
useViemStore().setLoadingWalletTransactions(false);
|
||||||
useEtherStore().setLoadingWalletTransactions(false);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test("Test Message when an empty array is received", () => {
|
test("Test Message when an empty array is received", () => {
|
||||||
|
@ -1,21 +1,21 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref, watch } from "vue";
|
import { ref, computed, watch } from "vue";
|
||||||
|
import { storeToRefs } from "pinia";
|
||||||
|
import { useViemStore } from "@/store/viem";
|
||||||
|
import SpinnerComponent from "@/components/SpinnerComponent.vue";
|
||||||
import CustomButton from "@/components/CustomButton/CustomButton.vue";
|
import CustomButton from "@/components/CustomButton/CustomButton.vue";
|
||||||
import { debounce } from "@/utils/debounce";
|
import { debounce } from "@/utils/debounce";
|
||||||
import { useEtherStore } from "@/store/ether";
|
|
||||||
import { storeToRefs } from "pinia";
|
|
||||||
import { verifyNetworkLiquidity } from "@/utils/networkLiquidity";
|
import { verifyNetworkLiquidity } from "@/utils/networkLiquidity";
|
||||||
import { NetworkEnum } from "@/model/NetworkEnum";
|
import { NetworkEnum } from "@/model/NetworkEnum";
|
||||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||||
import { decimalCount } from "@/utils/decimalCount";
|
import { decimalCount } from "@/utils/decimalCount";
|
||||||
import SpinnerComponent from "./SpinnerComponent.vue";
|
|
||||||
import { getTokenImage } from "@/utils/imagesPath";
|
import { getTokenImage } from "@/utils/imagesPath";
|
||||||
import { onClickOutside } from "@vueuse/core";
|
import { onClickOutside } from "@vueuse/core";
|
||||||
|
|
||||||
import { TokenEnum } from "@/model/NetworkEnum";
|
import { TokenEnum } from "@/model/NetworkEnum";
|
||||||
|
|
||||||
// Store reference
|
// Store reference
|
||||||
const etherStore = useEtherStore();
|
const viemStore = useViemStore();
|
||||||
const selectTokenToggle = ref<boolean>(false);
|
const selectTokenToggle = ref<boolean>(false);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
@ -24,7 +24,7 @@ const {
|
|||||||
selectedToken,
|
selectedToken,
|
||||||
depositsValidList,
|
depositsValidList,
|
||||||
loadingNetworkLiquidity,
|
loadingNetworkLiquidity,
|
||||||
} = storeToRefs(etherStore);
|
} = storeToRefs(viemStore);
|
||||||
|
|
||||||
// html references
|
// html references
|
||||||
const tokenDropdownRef = ref<any>(null);
|
const tokenDropdownRef = ref<any>(null);
|
||||||
@ -84,7 +84,7 @@ onClickOutside(tokenDropdownRef, () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const handleSelectedToken = (token: TokenEnum): void => {
|
const handleSelectedToken = (token: TokenEnum): void => {
|
||||||
etherStore.setSelectedToken(token);
|
viemStore.setSelectedToken(token);
|
||||||
selectTokenToggle.value = false;
|
selectTokenToggle.value = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, ref } from "vue";
|
import { ref, computed } from "vue";
|
||||||
import CustomButton from "../CustomButton/CustomButton.vue";
|
|
||||||
import { pixFormatValidation, postProcessKey } from "@/utils/pixKeyFormat";
|
|
||||||
import { useEtherStore } from "@/store/ether";
|
|
||||||
import { storeToRefs } from "pinia";
|
import { storeToRefs } from "pinia";
|
||||||
|
import { useViemStore } from "@/store/viem";
|
||||||
|
import CustomButton from "@/components/CustomButton/CustomButton.vue";
|
||||||
|
import { pixFormatValidation, postProcessKey } from "@/utils/pixKeyFormat";
|
||||||
import { TokenEnum } from "@/model/NetworkEnum";
|
import { TokenEnum } from "@/model/NetworkEnum";
|
||||||
import { getTokenImage } from "@/utils/imagesPath";
|
import { getTokenImage } from "@/utils/imagesPath";
|
||||||
import { useOnboard } from "@web3-onboard/vue";
|
import { useOnboard } from "@web3-onboard/vue";
|
||||||
@ -24,8 +24,8 @@ const tokenDropdownRef = ref<any>(null);
|
|||||||
const formRef = ref<HTMLFormElement | null>(null);
|
const formRef = ref<HTMLFormElement | null>(null);
|
||||||
|
|
||||||
// Reactive state
|
// Reactive state
|
||||||
const etherStore = useEtherStore();
|
const viemStore = useViemStore();
|
||||||
const { walletAddress, selectedToken } = storeToRefs(etherStore);
|
const { walletAddress, selectedToken } = storeToRefs(viemStore);
|
||||||
|
|
||||||
const fullName = ref<string>("");
|
const fullName = ref<string>("");
|
||||||
const offer = ref<string>("");
|
const offer = ref<string>("");
|
||||||
@ -91,7 +91,7 @@ const openTokenSelection = (): void => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleSelectedToken = (token: TokenEnum): void => {
|
const handleSelectedToken = (token: TokenEnum): void => {
|
||||||
etherStore.setSelectedToken(token);
|
viemStore.setSelectedToken(token);
|
||||||
selectTokenToggle.value = false;
|
selectTokenToggle.value = false;
|
||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
|
@ -1,17 +1,17 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref } from "vue";
|
import { ref, computed } from "vue";
|
||||||
|
import { storeToRefs } from "pinia";
|
||||||
|
import { useViemStore } from "@/store/viem";
|
||||||
|
import SpinnerComponent from "@/components/SpinnerComponent.vue";
|
||||||
import CustomButton from "@/components/CustomButton/CustomButton.vue";
|
import CustomButton from "@/components/CustomButton/CustomButton.vue";
|
||||||
import { debounce } from "@/utils/debounce";
|
import { debounce } from "@/utils/debounce";
|
||||||
import { decimalCount } from "@/utils/decimalCount";
|
import { decimalCount } from "@/utils/decimalCount";
|
||||||
|
|
||||||
import { useEtherStore } from "@/store/ether";
|
|
||||||
import { getTokenImage } from "@/utils/imagesPath";
|
import { getTokenImage } from "@/utils/imagesPath";
|
||||||
import { storeToRefs } from "pinia";
|
|
||||||
import { useOnboard } from "@web3-onboard/vue";
|
import { useOnboard } from "@web3-onboard/vue";
|
||||||
|
|
||||||
// Store
|
// Store
|
||||||
const etherStore = useEtherStore();
|
const viemStore = useViemStore();
|
||||||
const { walletAddress } = storeToRefs(etherStore);
|
const { walletAddress } = storeToRefs(viemStore);
|
||||||
|
|
||||||
// Reactive state
|
// Reactive state
|
||||||
const tokenValue = ref<number>(0);
|
const tokenValue = ref<number>(0);
|
||||||
@ -76,10 +76,10 @@ const handleInputEvent = (event: any): void => {
|
|||||||
<img
|
<img
|
||||||
alt="Token image"
|
alt="Token image"
|
||||||
class="w-fit"
|
class="w-fit"
|
||||||
:src="getTokenImage(etherStore.selectedToken)"
|
:src="getTokenImage(viemStore.selectedToken)"
|
||||||
/>
|
/>
|
||||||
<span class="text-gray-900 text-lg w-fit" id="token">{{
|
<span class="text-gray-900 text-lg w-fit" id="token">{{
|
||||||
etherStore.selectedToken
|
viemStore.selectedToken
|
||||||
}}</span>
|
}}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
@ -1,7 +1,8 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import { ref, computed, onMounted, watch } from "vue";
|
||||||
|
import { useRouter } from "vue-router";
|
||||||
|
import { useViemStore } from "@/store/viem";
|
||||||
import { storeToRefs } from "pinia";
|
import { storeToRefs } from "pinia";
|
||||||
import { useEtherStore } from "@/store/ether";
|
|
||||||
import { ref, watch } from "vue";
|
|
||||||
import { onClickOutside } from "@vueuse/core";
|
import { onClickOutside } from "@vueuse/core";
|
||||||
import { NetworkEnum } from "@/model/NetworkEnum";
|
import { NetworkEnum } from "@/model/NetworkEnum";
|
||||||
import { getNetworkImage } from "@/utils/imagesPath";
|
import { getNetworkImage } from "@/utils/imagesPath";
|
||||||
@ -16,9 +17,9 @@ import GithubIcon from "@/assets/githubIcon.svg";
|
|||||||
import { connectProvider } from "@/blockchain/provider";
|
import { connectProvider } from "@/blockchain/provider";
|
||||||
|
|
||||||
// Store reference
|
// Store reference
|
||||||
const etherStore = useEtherStore();
|
const viemStore = useViemStore();
|
||||||
|
|
||||||
const { walletAddress, sellerView } = storeToRefs(etherStore);
|
const { walletAddress, sellerView } = storeToRefs(viemStore);
|
||||||
|
|
||||||
const menuOpenToggle = ref<boolean>(false);
|
const menuOpenToggle = ref<boolean>(false);
|
||||||
const infoMenuOpenToggle = ref<boolean>(false);
|
const infoMenuOpenToggle = ref<boolean>(false);
|
||||||
@ -38,11 +39,11 @@ const connnectWallet = async (): Promise<void> => {
|
|||||||
watch(connectedWallet, async (newVal: any) => {
|
watch(connectedWallet, async (newVal: any) => {
|
||||||
connectProvider(newVal.provider);
|
connectProvider(newVal.provider);
|
||||||
const addresses = await newVal.provider.request({ method: "eth_accounts" });
|
const addresses = await newVal.provider.request({ method: "eth_accounts" });
|
||||||
etherStore.setWalletAddress(addresses.shift());
|
viemStore.setWalletAddress(addresses.shift());
|
||||||
});
|
});
|
||||||
|
|
||||||
watch(connectedChain, (newVal: any) => {
|
watch(connectedChain, (newVal: any) => {
|
||||||
etherStore.setNetworkId(newVal?.id);
|
viemStore.setNetworkId(newVal?.id);
|
||||||
});
|
});
|
||||||
|
|
||||||
const formatWalletAddress = (): string => {
|
const formatWalletAddress = (): string => {
|
||||||
@ -56,7 +57,7 @@ const formatWalletAddress = (): string => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const disconnectUser = async (): Promise<void> => {
|
const disconnectUser = async (): Promise<void> => {
|
||||||
etherStore.setWalletAddress("");
|
viemStore.setWalletAddress("");
|
||||||
await disconnectWallet({ label: connectedWallet.value?.label || "" });
|
await disconnectWallet({ label: connectedWallet.value?.label || "" });
|
||||||
closeMenu();
|
closeMenu();
|
||||||
};
|
};
|
||||||
@ -72,7 +73,7 @@ const networkChange = async (network: NetworkEnum): Promise<void> => {
|
|||||||
chainId: Networks[network].chainId,
|
chainId: Networks[network].chainId,
|
||||||
wallet: connectedWallet.value?.label || "",
|
wallet: connectedWallet.value?.label || "",
|
||||||
});
|
});
|
||||||
etherStore.setNetworkId(network);
|
viemStore.setNetworkId(network);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log("Error changing network", error);
|
console.log("Error changing network", error);
|
||||||
}
|
}
|
||||||
@ -245,7 +246,7 @@ onClickOutside(infoMenuRef, () => {
|
|||||||
>
|
>
|
||||||
<img
|
<img
|
||||||
alt="Choosed network image"
|
alt="Choosed network image"
|
||||||
:src="getNetworkImage(NetworkEnum[etherStore.networkName])"
|
:src="getNetworkImage(NetworkEnum[viemStore.networkName])"
|
||||||
height="24"
|
height="24"
|
||||||
width="24"
|
width="24"
|
||||||
/>
|
/>
|
||||||
@ -253,7 +254,7 @@ onClickOutside(infoMenuRef, () => {
|
|||||||
class="default-text hidden sm:inline-block text-gray-50 group-hover:text-gray-900 transition-all duration-500 ease-in-out whitespace-nowrap text-ellipsis overflow-hidden"
|
class="default-text hidden sm:inline-block text-gray-50 group-hover:text-gray-900 transition-all duration-500 ease-in-out whitespace-nowrap text-ellipsis overflow-hidden"
|
||||||
:class="{ '!text-gray-900': currencyMenuOpenToggle }"
|
:class="{ '!text-gray-900': currencyMenuOpenToggle }"
|
||||||
>
|
>
|
||||||
{{ Networks[etherStore.networkName].chainName }}
|
{{ Networks[viemStore.networkName].chainName }}
|
||||||
</span>
|
</span>
|
||||||
<div
|
<div
|
||||||
class="transition-all duration-500 ease-in-out mt-1"
|
class="transition-all duration-500 ease-in-out mt-1"
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
/* eslint-disable no-undef */
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
import { shallowMount } from "@vue/test-utils";
|
import { mount } from "@vue/test-utils";
|
||||||
import TopBar from "../TopBar.vue";
|
import TopBar from "../TopBar.vue";
|
||||||
import { useEtherStore } from "../../../store/ether";
|
import { useViemStore } from "@/store/viem";
|
||||||
|
|
||||||
import { createPinia, setActivePinia } from "pinia";
|
import { createPinia, setActivePinia } from "pinia";
|
||||||
|
|
||||||
@ -11,24 +11,24 @@ describe("TopBar.vue", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should render connect wallet button", () => {
|
it("should render connect wallet button", () => {
|
||||||
const wrapper = shallowMount(TopBar);
|
const wrapper = mount(TopBar);
|
||||||
expect(wrapper.html()).toContain("Conectar carteira");
|
expect(wrapper.html()).toContain("Conectar carteira");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should render button to change to seller view when in buyer screen", () => {
|
it("should render button to change to seller view when in buyer screen", () => {
|
||||||
const wrapper = shallowMount(TopBar);
|
const wrapper = mount(TopBar);
|
||||||
expect(wrapper.html()).toContain("Quero vender");
|
expect(wrapper.html()).toContain("Quero vender");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should render button to change to seller view when in buyer screen", () => {
|
it("should render button to change to seller view when in buyer screen", () => {
|
||||||
const etherStore = useEtherStore();
|
const viemStore = useViemStore();
|
||||||
etherStore.setSellerView(true);
|
viemStore.setSellerView(true);
|
||||||
const wrapper = shallowMount(TopBar);
|
const wrapper = mount(TopBar);
|
||||||
expect(wrapper.html()).toContain("Quero comprar");
|
expect(wrapper.html()).toContain("Quero comprar");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should render the P2Pix logo correctly", () => {
|
it("should render the P2Pix logo correctly", () => {
|
||||||
const wrapper = shallowMount(TopBar);
|
const wrapper = mount(TopBar);
|
||||||
const img = wrapper.findAll(".logo");
|
const img = wrapper.findAll(".logo");
|
||||||
expect(img.length).toBe(2);
|
expect(img.length).toBe(2);
|
||||||
});
|
});
|
||||||
|
@ -3,7 +3,7 @@ import type { ValidDeposit } from "@/model/ValidDeposit";
|
|||||||
import type { Participant } from "../utils/bbPay";
|
import type { Participant } from "../utils/bbPay";
|
||||||
import { defineStore } from "pinia";
|
import { defineStore } from "pinia";
|
||||||
|
|
||||||
export const useEtherStore = defineStore("ether", {
|
export const useViemStore = defineStore("viem", {
|
||||||
state: () => ({
|
state: () => ({
|
||||||
walletAddress: "",
|
walletAddress: "",
|
||||||
balance: "",
|
balance: "",
|
@ -3,7 +3,7 @@ import SearchComponent from "@/components/SearchComponent.vue";
|
|||||||
import LoadingComponent from "@/components/LoadingComponent/LoadingComponent.vue";
|
import LoadingComponent from "@/components/LoadingComponent/LoadingComponent.vue";
|
||||||
import BuyConfirmedComponent from "@/components/BuyConfirmedComponent/BuyConfirmedComponent.vue";
|
import BuyConfirmedComponent from "@/components/BuyConfirmedComponent/BuyConfirmedComponent.vue";
|
||||||
import { ref, onMounted, watch } from "vue";
|
import { ref, onMounted, watch } from "vue";
|
||||||
import { useEtherStore } from "@/store/ether";
|
import { useViemStore } from "@/store/viem";
|
||||||
import QrCodeComponent from "@/components/QrCodeComponent.vue";
|
import QrCodeComponent from "@/components/QrCodeComponent.vue";
|
||||||
import { storeToRefs } from "pinia";
|
import { storeToRefs } from "pinia";
|
||||||
import { addLock, releaseLock } from "@/blockchain/buyerMethods";
|
import { addLock, releaseLock } from "@/blockchain/buyerMethods";
|
||||||
@ -20,11 +20,11 @@ enum Step {
|
|||||||
List,
|
List,
|
||||||
}
|
}
|
||||||
|
|
||||||
const etherStore = useEtherStore();
|
const viemStore = useViemStore();
|
||||||
etherStore.setSellerView(false);
|
viemStore.setSellerView(false);
|
||||||
|
|
||||||
// States
|
// States
|
||||||
const { loadingLock, walletAddress, networkName } = storeToRefs(etherStore);
|
const { loadingLock, walletAddress, networkName } = storeToRefs(viemStore);
|
||||||
const flowStep = ref<Step>(Step.Search);
|
const flowStep = ref<Step>(Step.Search);
|
||||||
const pixTarget = ref<string>();
|
const pixTarget = ref<string>();
|
||||||
const tokenAmount = ref<number>();
|
const tokenAmount = ref<number>();
|
||||||
@ -45,7 +45,7 @@ const confirmBuyClick = async (
|
|||||||
// Makes lock with deposit ID and the Amount
|
// Makes lock with deposit ID and the Amount
|
||||||
if (selectedDeposit) {
|
if (selectedDeposit) {
|
||||||
flowStep.value = Step.Buy;
|
flowStep.value = Step.Buy;
|
||||||
etherStore.setLoadingLock(true);
|
viemStore.setLoadingLock(true);
|
||||||
|
|
||||||
await addLock(selectedDeposit.seller, selectedDeposit.token, tokenValue)
|
await addLock(selectedDeposit.seller, selectedDeposit.token, tokenValue)
|
||||||
.then((_lockID) => {
|
.then((_lockID) => {
|
||||||
@ -56,7 +56,7 @@ const confirmBuyClick = async (
|
|||||||
flowStep.value = Step.Search;
|
flowStep.value = Step.Search;
|
||||||
});
|
});
|
||||||
|
|
||||||
etherStore.setLoadingLock(false);
|
viemStore.setLoadingLock(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -1,10 +1,9 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { useEtherStore } from "@/store/ether";
|
import { ref, onMounted, watch } from "vue";
|
||||||
import { storeToRefs } from "pinia";
|
import { useViemStore } from "@/store/viem";
|
||||||
import ListingComponent from "@/components/ListingComponent/ListingComponent.vue";
|
import ListingComponent from "@/components/ListingComponent/ListingComponent.vue";
|
||||||
import LoadingComponent from "@/components/LoadingComponent/LoadingComponent.vue";
|
import LoadingComponent from "@/components/LoadingComponent/LoadingComponent.vue";
|
||||||
import CustomAlert from "@/components/CustomAlert/CustomAlert.vue";
|
import CustomAlert from "@/components/CustomAlert/CustomAlert.vue";
|
||||||
import { ref, watch, onMounted } from "vue";
|
|
||||||
import {
|
import {
|
||||||
listValidDepositTransactionsByWalletAddress,
|
listValidDepositTransactionsByWalletAddress,
|
||||||
listAllTransactionByWalletAddress,
|
listAllTransactionByWalletAddress,
|
||||||
@ -15,9 +14,10 @@ import type { ValidDeposit } from "@/model/ValidDeposit";
|
|||||||
import type { WalletTransaction } from "@/model/WalletTransaction";
|
import type { WalletTransaction } from "@/model/WalletTransaction";
|
||||||
|
|
||||||
import router from "@/router/index";
|
import router from "@/router/index";
|
||||||
|
import { storeToRefs } from "pinia";
|
||||||
|
|
||||||
const etherStore = useEtherStore();
|
const viemStore = useViemStore();
|
||||||
const { walletAddress, networkName, selectedToken } = storeToRefs(etherStore);
|
const { walletAddress, networkName, selectedToken } = storeToRefs(viemStore);
|
||||||
const loadingWithdraw = ref<boolean>(false);
|
const loadingWithdraw = ref<boolean>(false);
|
||||||
const showAlert = ref<boolean>(false);
|
const showAlert = ref<boolean>(false);
|
||||||
|
|
||||||
@ -47,7 +47,7 @@ const callWithdraw = async (amount: string) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const getWalletTransactions = async () => {
|
const getWalletTransactions = async () => {
|
||||||
etherStore.setLoadingWalletTransactions(true);
|
viemStore.setLoadingWalletTransactions(true);
|
||||||
if (walletAddress.value) {
|
if (walletAddress.value) {
|
||||||
console.log("Will fetch all required data...");
|
console.log("Will fetch all required data...");
|
||||||
const walletDeposits = await listValidDepositTransactionsByWalletAddress(
|
const walletDeposits = await listValidDepositTransactionsByWalletAddress(
|
||||||
@ -70,7 +70,7 @@ const getWalletTransactions = async () => {
|
|||||||
transactionsList.value = allUserTransactions;
|
transactionsList.value = allUserTransactions;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
etherStore.setLoadingWalletTransactions(false);
|
viemStore.setLoadingWalletTransactions(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
|
@ -1,11 +1,15 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import { ref, onMounted, watch } from "vue";
|
||||||
|
import { storeToRefs } from "pinia";
|
||||||
|
|
||||||
import SellerComponent from "@/components/SellerSteps/SellerComponent.vue";
|
import SellerComponent from "@/components/SellerSteps/SellerComponent.vue";
|
||||||
|
import SearchComponent from "@/components/SearchComponent.vue";
|
||||||
import SendNetwork from "@/components/SellerSteps/SendNetwork.vue";
|
import SendNetwork from "@/components/SellerSteps/SendNetwork.vue";
|
||||||
|
import SellerSearchComponent from "@/components/SellerSteps/SellerSearchComponent.vue";
|
||||||
import LoadingComponent from "@/components/LoadingComponent/LoadingComponent.vue";
|
import LoadingComponent from "@/components/LoadingComponent/LoadingComponent.vue";
|
||||||
|
import { useViemStore } from "@/store/viem";
|
||||||
import { approveTokens, addDeposit } from "@/blockchain/sellerMethods";
|
import { approveTokens, addDeposit } from "@/blockchain/sellerMethods";
|
||||||
|
|
||||||
import { ref } from "vue";
|
|
||||||
import { useEtherStore } from "@/store/ether";
|
|
||||||
import CustomAlert from "@/components/CustomAlert/CustomAlert.vue";
|
import CustomAlert from "@/components/CustomAlert/CustomAlert.vue";
|
||||||
import type { Participant } from "@/utils/bbPay";
|
import type { Participant } from "@/utils/bbPay";
|
||||||
|
|
||||||
@ -15,8 +19,8 @@ enum Step {
|
|||||||
Network,
|
Network,
|
||||||
}
|
}
|
||||||
|
|
||||||
const etherStore = useEtherStore();
|
const viemStore = useViemStore();
|
||||||
etherStore.setSellerView(true);
|
viemStore.setSellerView(true);
|
||||||
|
|
||||||
const flowStep = ref<Step>(Step.Sell);
|
const flowStep = ref<Step>(Step.Sell);
|
||||||
const loading = ref<boolean>(false);
|
const loading = ref<boolean>(false);
|
||||||
@ -40,7 +44,7 @@ const approveOffer = async (args: Participant) => {
|
|||||||
const sendNetwork = async () => {
|
const sendNetwork = async () => {
|
||||||
loading.value = true;
|
loading.value = true;
|
||||||
try {
|
try {
|
||||||
if (etherStore.seller) {
|
if (viemStore.seller) {
|
||||||
await addDeposit();
|
await addDeposit();
|
||||||
flowStep.value = Step.Sell;
|
flowStep.value = Step.Sell;
|
||||||
loading.value = false;
|
loading.value = false;
|
||||||
@ -70,9 +74,9 @@ const sendNetwork = async () => {
|
|||||||
/>
|
/>
|
||||||
<div v-if="flowStep == Step.Network">
|
<div v-if="flowStep == Step.Network">
|
||||||
<SendNetwork
|
<SendNetwork
|
||||||
:sellerId="etherStore.sellerId"
|
:sellerId="viemStore.sellerId"
|
||||||
:offer="Number(etherStore.seller.offer)"
|
:offer="Number(viemStore.seller.offer)"
|
||||||
:selected-token="etherStore.selectedToken"
|
:selected-token="viemStore.selectedToken"
|
||||||
v-if="!loading"
|
v-if="!loading"
|
||||||
@send-network="sendNetwork"
|
@send-network="sendNetwork"
|
||||||
/>
|
/>
|
||||||
|
Loading…
x
Reference in New Issue
Block a user