Compare commits
7 Commits
73ba77ca4f
...
c1542707c2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c1542707c2 | ||
|
|
dd351acb2e | ||
|
|
2370051243 | ||
|
|
ed5d3b5726 | ||
|
|
2e246f7560 | ||
|
|
81c8b04c7a | ||
|
|
cf61f5ecfd |
@ -115,4 +115,6 @@ curl -X POST \
|
||||
-d '{"query": "{ depositAddeds { id seller token amount } }"}' \
|
||||
https://api.studio.thegraph.com/query/113713/p-2-pix/sepolia
|
||||
|
||||
https://api.studio.thegraph.com/query/113713/p-2-pix/1
|
||||
https://api.studio.thegraph.com/query/113713/p-2-pix/1
|
||||
|
||||
curl --request POST --url 'https://api.hm.bb.com.br/testes-portal-desenvolvedor/v1/boletos-pix/pagar?gw-app-key=95cad3f03fd9013a9d15005056825665' --header 'content-type: application/json' --data '{"pix":"00020101021226070503***63041654" }'
|
||||
10
package.json
10
package.json
@ -5,9 +5,7 @@
|
||||
"start": "vite --host=0.0.0.0 --port 3000",
|
||||
"build": "run-p type-check build-only",
|
||||
"preview": "vite preview",
|
||||
"test": "vitest",
|
||||
"serve": "vue-cli-service serve",
|
||||
"coverage": "vitest run --coverage",
|
||||
"build-only": "vite build",
|
||||
"type-check": "vue-tsc --skipLibCheck --noEmit",
|
||||
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --ignore-path .gitignore --fix",
|
||||
@ -22,8 +20,6 @@
|
||||
"@web3-onboard/vue": "^2.9.0",
|
||||
"alchemy-sdk": "^2.3.0",
|
||||
"axios": "^1.2.1",
|
||||
"crc": "^3.8.0",
|
||||
"ethers": "^6.13.4",
|
||||
"marked": "^4.2.12",
|
||||
"qrcode": "^1.5.1",
|
||||
"viem": "^2.31.3",
|
||||
@ -37,29 +33,25 @@
|
||||
"@babel/preset-typescript": "^7.18.6",
|
||||
"@rushstack/eslint-patch": "^1.1.4",
|
||||
"@types/crc": "^3.8.0",
|
||||
"@types/jest": "^27.0.0",
|
||||
"@types/marked": "^4.0.8",
|
||||
"@types/node": "^16.11.68",
|
||||
"@types/qrcode": "^1.5.0",
|
||||
"@types/vue-markdown": "^2.2.1",
|
||||
"@vitejs/plugin-vue": "^3.1.2",
|
||||
"@vitejs/plugin-vue-jsx": "^2.0.1",
|
||||
"@vitest/coverage-c8": "^0.28.2",
|
||||
"@vue/eslint-config-prettier": "^7.0.0",
|
||||
"@vue/eslint-config-typescript": "^11.0.0",
|
||||
"@vue/test-utils": "^2.2.7",
|
||||
"@vue/tsconfig": "^0.1.3",
|
||||
"@wagmi/cli": "^2.3.1",
|
||||
"autoprefixer": "^10.4.12",
|
||||
"eslint": "^8.22.0",
|
||||
"eslint-plugin-vue": "^9.3.0",
|
||||
"jsdom": "^21.1.0",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"postcss": "^8.4.18",
|
||||
"prettier": "^2.7.1",
|
||||
"tailwindcss": "^3.2.1",
|
||||
"typescript": "~5.8.2",
|
||||
"vite": "^3.1.8",
|
||||
"vitest": "^0.28.1",
|
||||
"vue-tsc": "^2.2.8"
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,98 +0,0 @@
|
||||
import { expectTypeOf, it, expect } from "vitest";
|
||||
import {
|
||||
getTokenAddress,
|
||||
getP2PixAddress,
|
||||
getProviderUrl,
|
||||
isPossibleNetwork,
|
||||
} from "../addresses";
|
||||
|
||||
import { setActivePinia, createPinia } from "pinia";
|
||||
import { NetworkEnum, TokenEnum } from "@/model/NetworkEnum";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
|
||||
describe("addresses.ts types", () => {
|
||||
it("My addresses.ts types work properly", () => {
|
||||
expectTypeOf(getTokenAddress).toBeFunction();
|
||||
expectTypeOf(getP2PixAddress).toBeFunction();
|
||||
expectTypeOf(getProviderUrl).toBeFunction();
|
||||
expectTypeOf(isPossibleNetwork).toBeFunction();
|
||||
});
|
||||
});
|
||||
|
||||
describe("addresses.ts functions", () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
});
|
||||
|
||||
it("getTokenAddress Ethereum", () => {
|
||||
const user = useUser();
|
||||
user.setNetworkId(11155111);
|
||||
expect(getTokenAddress(TokenEnum.BRZ)).toBe(
|
||||
"0x4A2886EAEc931e04297ed336Cc55c4eb7C75BA00"
|
||||
);
|
||||
});
|
||||
|
||||
it("getTokenAddress Rootstock", () => {
|
||||
const user = useUser();
|
||||
user.setNetworkId(30);
|
||||
expect(getTokenAddress(TokenEnum.BRZ)).toBe(
|
||||
"0xfE841c74250e57640390f46d914C88d22C51e82e"
|
||||
);
|
||||
});
|
||||
|
||||
it("getTokenAddress Default", () => {
|
||||
expect(getTokenAddress(TokenEnum.BRZ)).toBe(
|
||||
"0x4A2886EAEc931e04297ed336Cc55c4eb7C75BA00"
|
||||
);
|
||||
});
|
||||
|
||||
it("getP2PixAddress Ethereum", () => {
|
||||
const user = useUser();
|
||||
user.setNetworkId(11155111);
|
||||
expect(getP2PixAddress()).toBe(
|
||||
"0x2414817FF64A114d91eCFA16a834d3fCf69103d4"
|
||||
);
|
||||
});
|
||||
|
||||
it("getP2PixAddress Rootstock", () => {
|
||||
const user = useUser();
|
||||
user.setNetworkId(30);
|
||||
expect(getP2PixAddress()).toBe(
|
||||
"0x98ba35eb14b38D6Aa709338283af3e922476dE34"
|
||||
);
|
||||
});
|
||||
|
||||
it("getP2PixAddress Default", () => {
|
||||
expect(getP2PixAddress()).toBe(
|
||||
"0x2414817FF64A114d91eCFA16a834d3fCf69103d4"
|
||||
);
|
||||
});
|
||||
|
||||
it("getProviderUrl Ethereum", () => {
|
||||
const user = useUser();
|
||||
user.setNetworkId(11155111);
|
||||
expect(getProviderUrl()).toBe(import.meta.env.VITE_GOERLI_API_URL);
|
||||
});
|
||||
|
||||
it("getProviderUrl Rootstock", () => {
|
||||
const user = useUser();
|
||||
user.setNetworkId(30);
|
||||
expect(getProviderUrl()).toBe(import.meta.env.VITE_ROOTSTOCK_API_URL);
|
||||
});
|
||||
|
||||
it("getProviderUrl Default", () => {
|
||||
expect(getProviderUrl()).toBe(import.meta.env.VITE_GOERLI_API_URL);
|
||||
});
|
||||
|
||||
it("isPossibleNetwork Returns", () => {
|
||||
const user = useUser();
|
||||
user.setNetworkId(11155111);
|
||||
expect(isPossibleNetwork(0x5 as NetworkEnum)).toBe(true);
|
||||
expect(isPossibleNetwork(5 as NetworkEnum)).toBe(true);
|
||||
expect(isPossibleNetwork(0x13881 as NetworkEnum)).toBe(true);
|
||||
expect(isPossibleNetwork(80001 as NetworkEnum)).toBe(true);
|
||||
|
||||
expect(isPossibleNetwork(NaN as NetworkEnum)).toBe(false);
|
||||
expect(isPossibleNetwork(0x55 as NetworkEnum)).toBe(false);
|
||||
});
|
||||
});
|
||||
2266
src/blockchain/abi.ts
Normal file
2266
src/blockchain/abi.ts
Normal file
File diff suppressed because it is too large
Load Diff
@ -1,9 +1,9 @@
|
||||
import { useUser } from "@/composables/useUser";
|
||||
import { NetworkEnum, TokenEnum } from "@/model/NetworkEnum";
|
||||
import { createPublicClient, http } from "viem";
|
||||
import { createPublicClient, http, type Address } from "viem";
|
||||
import { sepolia, rootstock } from "viem/chains";
|
||||
|
||||
const Tokens: { [key in NetworkEnum]: { [key in TokenEnum]: string } } = {
|
||||
const Tokens: { [key in NetworkEnum]: { [key in TokenEnum]: Address } } = {
|
||||
[NetworkEnum.sepolia]: {
|
||||
BRZ: "0x3eBE67A2C7bdB2081CBd34ba3281E90377462289",
|
||||
// BRX: "0x3eBE67A2C7bdB2081CBd34ba3281E90377462289",
|
||||
@ -14,7 +14,7 @@ const Tokens: { [key in NetworkEnum]: { [key in TokenEnum]: string } } = {
|
||||
},
|
||||
};
|
||||
|
||||
export const getTokenByAddress = (address: string) => {
|
||||
export const getTokenByAddress = (address: Address) => {
|
||||
const user = useUser();
|
||||
const networksTokens = Tokens[user.networkName.value];
|
||||
for (const [token, tokenAddress] of Object.entries(networksTokens)) {
|
||||
@ -28,19 +28,23 @@ export const getTokenByAddress = (address: string) => {
|
||||
export const getTokenAddress = (
|
||||
token: TokenEnum,
|
||||
network?: NetworkEnum
|
||||
): string => {
|
||||
): Address => {
|
||||
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): Address => {
|
||||
const user = useUser();
|
||||
const possibleP2PixAddresses: { [key in NetworkEnum]: string } = {
|
||||
const possibleP2PixAddresses: { [key in NetworkEnum]: Address } = {
|
||||
[NetworkEnum.sepolia]: "0xb7cD135F5eFD9760981e02E2a898790b688939fe",
|
||||
[NetworkEnum.rootstock]: "0x98ba35eb14b38D6Aa709338283af3e922476dE34",
|
||||
};
|
||||
|
||||
return possibleP2PixAddresses[network ? network : user.networkName.value];
|
||||
return possibleP2PixAddresses[
|
||||
network ? network : user.networkName.value
|
||||
];
|
||||
};
|
||||
|
||||
export const getProviderUrl = (network?: NetworkEnum): string => {
|
||||
@ -54,7 +58,6 @@ export const getProviderUrl = (network?: NetworkEnum): string => {
|
||||
};
|
||||
|
||||
export const getProviderByNetwork = (network: NetworkEnum) => {
|
||||
console.log("network", network);
|
||||
const chain = network === NetworkEnum.sepolia ? sepolia : rootstock;
|
||||
return createPublicClient({
|
||||
chain,
|
||||
|
||||
@ -1,34 +1,55 @@
|
||||
import { getContract } from "./provider";
|
||||
import { getTokenAddress } from "./addresses";
|
||||
import { parseEther } from "viem";
|
||||
import {
|
||||
bytesToHex,
|
||||
encodeAbiParameters,
|
||||
keccak256,
|
||||
parseAbiParameters,
|
||||
parseEther,
|
||||
stringToBytes,
|
||||
stringToHex,
|
||||
toBytes,
|
||||
type Address,
|
||||
} from "viem";
|
||||
import type { TokenEnum } from "@/model/NetworkEnum";
|
||||
|
||||
export const addLock = async (
|
||||
sellerAddress: string,
|
||||
tokenAddress: string,
|
||||
sellerAddress: Address,
|
||||
tokenAddress: Address,
|
||||
amount: number
|
||||
): Promise<string> => {
|
||||
const { address, abi, wallet, client } = await getContract();
|
||||
): Promise<bigint> => {
|
||||
const { address, abi, wallet, client, account } = await getContract();
|
||||
const parsedAmount = parseEther(amount.toString());
|
||||
|
||||
const { request } = await client.simulateContract({
|
||||
if (!wallet) {
|
||||
throw new Error("Wallet not connected");
|
||||
}
|
||||
|
||||
const { result, request } = await client.simulateContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "lock",
|
||||
args: [sellerAddress, tokenAddress, parsedAmount, [], []],
|
||||
account,
|
||||
});
|
||||
console.log(wallet);
|
||||
const hash = await wallet.writeContract(request);
|
||||
const receipt = await client.waitForTransactionReceipt({ hash });
|
||||
|
||||
return receipt.status ? receipt.logs[0].topics[2] : "";
|
||||
if (!receipt.status)
|
||||
throw new Error("Transaction failed: " + receipt.transactionHash);
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
export const withdrawDeposit = async (
|
||||
amount: string,
|
||||
token: TokenEnum
|
||||
): Promise<boolean> => {
|
||||
const { address, abi, wallet, client } = await getContract();
|
||||
const { address, abi, wallet, client, account } = await getContract();
|
||||
|
||||
if (!wallet) {
|
||||
throw new Error("Wallet not connected");
|
||||
}
|
||||
|
||||
const tokenAddress = getTokenAddress(token);
|
||||
|
||||
@ -37,22 +58,36 @@ export const withdrawDeposit = async (
|
||||
abi,
|
||||
functionName: "withdraw",
|
||||
args: [tokenAddress, parseEther(amount), []],
|
||||
account
|
||||
});
|
||||
|
||||
const hash = await wallet.writeContract(request);
|
||||
const receipt = await client.waitForTransactionReceipt({ hash });
|
||||
|
||||
return receipt.status;
|
||||
return receipt.status === "success";
|
||||
};
|
||||
|
||||
export const releaseLock = async (solicitation: any): Promise<any> => {
|
||||
const { address, abi, wallet, client } = await getContract();
|
||||
export const releaseLock = async (
|
||||
lockID: bigint,
|
||||
pixtarget: string,
|
||||
signature: string
|
||||
): Promise<any> => {
|
||||
const { address, abi, wallet, client, account } = await getContract();
|
||||
|
||||
console.log("Releasing lock", { lockID, pixtarget, signature });
|
||||
if (!wallet) {
|
||||
throw new Error("Wallet not connected");
|
||||
}
|
||||
|
||||
// Convert pixtarget to bytes32
|
||||
const pixTimestamp = keccak256(stringToHex(pixtarget, { size: 32 }) );
|
||||
|
||||
const { request } = await client.simulateContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "release",
|
||||
args: [solicitation.lockId, solicitation.e2eId],
|
||||
args: [BigInt(lockID), pixTimestamp, stringToHex(signature)],
|
||||
account
|
||||
});
|
||||
|
||||
const hash = await wallet.writeContract(request);
|
||||
|
||||
@ -1,13 +1,14 @@
|
||||
import { useUser } from "@/composables/useUser";
|
||||
import { formatEther, toHex, type PublicClient } from "viem";
|
||||
import { formatEther, toHex, stringToHex } from "viem";
|
||||
import type { PublicClient, Address } from "viem";
|
||||
|
||||
import p2pix from "@/utils/smart_contract_files/P2PIX.json";
|
||||
import { getContract } from "./provider";
|
||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||
import { getP2PixAddress, getTokenAddress } from "./addresses";
|
||||
import { getNetworkSubgraphURL, NetworkEnum } from "@/model/NetworkEnum";
|
||||
import { p2PixAbi } from "./abi"
|
||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||
import { getNetworkSubgraphURL, NetworkEnum, TokenEnum } from "@/model/NetworkEnum";
|
||||
import type { UnreleasedLock } from "@/model/UnreleasedLock";
|
||||
import type { Pix } from "@/model/Pix";
|
||||
import type { LockStatus } from "@/model/LockStatus"
|
||||
|
||||
const getNetworksLiquidity = async (): Promise<void> => {
|
||||
const user = useUser();
|
||||
@ -30,10 +31,13 @@ const getNetworksLiquidity = async (): Promise<void> => {
|
||||
user.setLoadingNetworkLiquidity(false);
|
||||
};
|
||||
|
||||
const getPixKey = async (seller: string, token: string): Promise<string> => {
|
||||
const getParticipantID = async (
|
||||
seller: string,
|
||||
token: string
|
||||
): Promise<string> => {
|
||||
const { address, abi, client } = await getContract();
|
||||
|
||||
const pixKeyHex = await client.readContract({
|
||||
const participantIDHex = await client.readContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "getPixTarget",
|
||||
@ -42,13 +46,14 @@ const getPixKey = async (seller: string, token: string): Promise<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");
|
||||
typeof participantIDHex === "string"
|
||||
? participantIDHex
|
||||
: toHex(participantIDHex as bigint);
|
||||
if (!hexString) throw new Error("Participant ID not found");
|
||||
const bytes = new Uint8Array(
|
||||
// @ts-ignore
|
||||
hexString
|
||||
.slice(2)
|
||||
.match(/.{1,2}/g)
|
||||
.match(/.{1,2}/g)!
|
||||
.map((byte: string) => parseInt(byte, 16))
|
||||
);
|
||||
// Remove null bytes from the end of the string
|
||||
@ -56,17 +61,17 @@ const getPixKey = async (seller: string, token: string): Promise<string> => {
|
||||
};
|
||||
|
||||
const getValidDeposits = async (
|
||||
token: string,
|
||||
token: Address,
|
||||
network: NetworkEnum,
|
||||
contractInfo?: { client: any; address: string }
|
||||
contractInfo?: { client: PublicClient; address: Address }
|
||||
): Promise<ValidDeposit[]> => {
|
||||
let client: PublicClient, address, abi;
|
||||
let client: PublicClient, abi;
|
||||
|
||||
if (contractInfo) {
|
||||
({ client, address } = contractInfo);
|
||||
abi = p2pix.abi;
|
||||
({ client } = contractInfo);
|
||||
abi = p2PixAbi;
|
||||
} else {
|
||||
({ address, abi, client } = await getContract(true));
|
||||
({ abi, client } = await getContract(true));
|
||||
}
|
||||
|
||||
// TODO: Remove this once we have a subgraph for rootstock
|
||||
@ -97,11 +102,11 @@ const getValidDeposits = async (
|
||||
const depositData = await depositLogs.json();
|
||||
const depositAddeds = depositData.data.depositAddeds;
|
||||
const uniqueSellers = depositAddeds.reduce(
|
||||
(acc: Record<string, boolean>, deposit: any) => {
|
||||
(acc: Record<Address, boolean>, deposit: any) => {
|
||||
acc[deposit.seller] = true;
|
||||
return acc;
|
||||
},
|
||||
{} as Record<string, boolean>
|
||||
{} as Record<Address, boolean>
|
||||
);
|
||||
|
||||
if (!contractInfo) {
|
||||
@ -111,7 +116,7 @@ const getValidDeposits = async (
|
||||
|
||||
const depositList: { [key: string]: ValidDeposit } = {};
|
||||
|
||||
const sellersList = Object.keys(uniqueSellers);
|
||||
const sellersList = Object.keys(uniqueSellers) as Address[];
|
||||
// Use multicall to batch all getBalance requests
|
||||
const balanceCalls = sellersList.map((seller) => ({
|
||||
address: getP2PixAddress(network),
|
||||
@ -130,12 +135,12 @@ const getValidDeposits = async (
|
||||
|
||||
if (!mappedBalance.error && mappedBalance.result) {
|
||||
const validDeposit: ValidDeposit = {
|
||||
token: token,
|
||||
token,
|
||||
blockNumber: 0,
|
||||
remaining: Number(formatEther(mappedBalance.result as bigint)),
|
||||
seller: seller,
|
||||
seller,
|
||||
network,
|
||||
pixKey: "",
|
||||
participantID: "",
|
||||
};
|
||||
depositList[seller + token] = validDeposit;
|
||||
}
|
||||
@ -144,28 +149,22 @@ const getValidDeposits = async (
|
||||
};
|
||||
|
||||
const getUnreleasedLockById = async (
|
||||
lockID: string
|
||||
lockID: bigint
|
||||
): Promise<UnreleasedLock> => {
|
||||
const { address, abi, client } = await getContract();
|
||||
const pixData: Pix = {
|
||||
pixKey: "",
|
||||
};
|
||||
|
||||
const lock = await client.readContract({
|
||||
const [ , , , amount, token, seller ] = await client.readContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "mapLocks",
|
||||
args: [BigInt(lockID)],
|
||||
args: [lockID],
|
||||
});
|
||||
|
||||
const pixTarget = lock.pixTarget;
|
||||
const amount = formatEther(lock.amount);
|
||||
pixData.pixKey = pixTarget;
|
||||
pixData.value = Number(amount);
|
||||
|
||||
return {
|
||||
lockID: lockID,
|
||||
pix: pixData,
|
||||
lockID,
|
||||
amount: Number(formatEther(amount)),
|
||||
tokenAddress: token,
|
||||
sellerAddress: seller,
|
||||
};
|
||||
};
|
||||
|
||||
@ -173,5 +172,5 @@ export {
|
||||
getValidDeposits,
|
||||
getNetworksLiquidity,
|
||||
getUnreleasedLockById,
|
||||
getPixKey,
|
||||
getParticipantID,
|
||||
};
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import p2pix from "@/utils/smart_contract_files/P2PIX.json";
|
||||
import { p2PixAbi } from "./abi";
|
||||
import { updateWalletStatus } from "./wallet";
|
||||
import { getProviderUrl, getP2PixAddress } from "./addresses";
|
||||
import {
|
||||
@ -12,11 +12,9 @@ import {
|
||||
import { sepolia, rootstock } from "viem/chains";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
|
||||
let publicClient: PublicClient | null = null;
|
||||
let walletClient: WalletClient | null = null;
|
||||
|
||||
const getPublicClient: PublicClient | null = (onlyRpcProvider = false) => {
|
||||
if (onlyRpcProvider) {
|
||||
const getPublicClient = (): PublicClient => {
|
||||
const user = useUser();
|
||||
const rpcUrl = getProviderUrl();
|
||||
return createPublicClient({
|
||||
@ -24,36 +22,32 @@ const getPublicClient: PublicClient | null = (onlyRpcProvider = false) => {
|
||||
Number(user.networkName.value) === sepolia.id ? sepolia : rootstock,
|
||||
transport: http(rpcUrl),
|
||||
});
|
||||
}
|
||||
return publicClient;
|
||||
};
|
||||
|
||||
const getWalletClient: WalletClient | null = () => {
|
||||
const getWalletClient = (): WalletClient | null => {
|
||||
return walletClient;
|
||||
};
|
||||
|
||||
const getContract = async (onlyRpcProvider = false) => {
|
||||
const client = getPublicClient(onlyRpcProvider);
|
||||
const client = getPublicClient();
|
||||
const address = getP2PixAddress();
|
||||
const abi = p2pix.abi;
|
||||
const wallet = getWalletClient();
|
||||
const abi = p2PixAbi;
|
||||
const wallet = onlyRpcProvider ? null : getWalletClient();
|
||||
|
||||
const [account] = wallet ? await wallet.getAddresses() : [""];
|
||||
if (!client) {
|
||||
throw new Error("Public client not initialized");
|
||||
}
|
||||
|
||||
const [account] = wallet ? await wallet.getAddresses() : [null];
|
||||
|
||||
return { address, abi, client, wallet, account };
|
||||
};
|
||||
|
||||
const connectProvider = async (p: any): Promise<void> => {
|
||||
console.log("Connecting to wallet provider...");
|
||||
const user = useUser();
|
||||
const chain =
|
||||
Number(user.networkName.value) === sepolia.id ? sepolia : rootstock;
|
||||
|
||||
publicClient = createPublicClient({
|
||||
chain,
|
||||
transport: custom(p),
|
||||
});
|
||||
|
||||
const [account] = await p!.request({ method: "eth_requestAccounts" });
|
||||
|
||||
walletClient = createWalletClient({
|
||||
|
||||
@ -1,8 +1,9 @@
|
||||
import { getContract, getPublicClient, getWalletClient } from "./provider";
|
||||
import { getTokenAddress, getP2PixAddress } from "./addresses";
|
||||
import { parseEther, toHex } from "viem";
|
||||
import { sepolia, rootstock } from "viem/chains";
|
||||
|
||||
import mockToken from "../utils/smart_contract_files/MockToken.json";
|
||||
import { mockTokenAbi } from "./abi";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
import { createParticipant } from "@/utils/bbPay";
|
||||
import type { Participant } from "@/utils/bbPay";
|
||||
@ -25,19 +26,21 @@ const approveTokens = async (participant: Participant): Promise<any> => {
|
||||
// Check if the token is already approved
|
||||
const allowance = await publicClient.readContract({
|
||||
address: tokenAddress,
|
||||
abi: mockToken.abi,
|
||||
abi: mockTokenAbi,
|
||||
functionName: "allowance",
|
||||
args: [account, getP2PixAddress()],
|
||||
});
|
||||
|
||||
if (allowance < parseEther(participant.offer.toString())) {
|
||||
if ( allowance < parseEther(participant.offer.toString()) ) {
|
||||
// Approve tokens
|
||||
const chain = user.networkId.value === sepolia.id ? sepolia : rootstock;
|
||||
const hash = await walletClient.writeContract({
|
||||
address: tokenAddress,
|
||||
abi: mockToken.abi,
|
||||
abi: mockTokenAbi,
|
||||
functionName: "approve",
|
||||
args: [getP2PixAddress(), parseEther(participant.offer.toString())],
|
||||
account,
|
||||
chain,
|
||||
});
|
||||
|
||||
await publicClient.waitForTransactionReceipt({ hash });
|
||||
@ -59,19 +62,23 @@ const addDeposit = async (): Promise<any> => {
|
||||
|
||||
const sellerId = await createParticipant(user.seller.value);
|
||||
user.setSellerId(sellerId.id);
|
||||
|
||||
if (!sellerId.id) {
|
||||
throw new Error("Failed to create participant");
|
||||
}
|
||||
const chain = user.networkId.value === sepolia.id ? sepolia : rootstock;
|
||||
const hash = await walletClient.writeContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "deposit",
|
||||
args: [
|
||||
user.networkId + "-" + sellerId.id,
|
||||
user.networkId.value + "-" + sellerId.id,
|
||||
toHex("", { size: 32 }),
|
||||
getTokenAddress(user.selectedToken.value),
|
||||
parseEther(user.seller.value.offer.toString()),
|
||||
true,
|
||||
],
|
||||
account,
|
||||
chain,
|
||||
});
|
||||
|
||||
const receipt = await client.waitForTransactionReceipt({ hash });
|
||||
|
||||
@ -1,17 +1,15 @@
|
||||
import { decodeEventLog, formatEther, type Log } from "viem";
|
||||
import { formatEther, hexToString, type Address } from "viem";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
|
||||
import { getPublicClient, getWalletClient, getContract } from "./provider";
|
||||
import { getTokenAddress } from "./addresses";
|
||||
|
||||
import p2pix from "@/utils/smart_contract_files/P2PIX.json";
|
||||
|
||||
import { getValidDeposits } from "./events";
|
||||
import { getValidDeposits, getUnreleasedLockById } from "./events";
|
||||
|
||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||
import type { WalletTransaction } from "@/model/WalletTransaction";
|
||||
import type { UnreleasedLock } from "@/model/UnreleasedLock";
|
||||
import type { Pix } from "@/model/Pix";
|
||||
import { LockStatus } from "@/model/LockStatus";
|
||||
import { getNetworkSubgraphURL } from "@/model/NetworkEnum";
|
||||
|
||||
export const updateWalletStatus = async (): Promise<void> => {
|
||||
@ -34,7 +32,7 @@ export const updateWalletStatus = async (): Promise<void> => {
|
||||
};
|
||||
|
||||
export const listValidDepositTransactionsByWalletAddress = async (
|
||||
walletAddress: string
|
||||
walletAddress: Address
|
||||
): Promise<ValidDeposit[]> => {
|
||||
const user = useUser();
|
||||
const walletDeposits = await getValidDeposits(
|
||||
@ -52,61 +50,19 @@ export const listValidDepositTransactionsByWalletAddress = async (
|
||||
return [];
|
||||
};
|
||||
|
||||
const getLockStatus = async (id: bigint): Promise<number> => {
|
||||
const getLockStatus = async (id: bigint): Promise<LockStatus> => {
|
||||
const { address, abi, client } = await getContract();
|
||||
const result = await client.readContract({
|
||||
const [ sortedIDs , status ] = await client.readContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "getLocksStatus",
|
||||
args: [[id]],
|
||||
});
|
||||
return result[1][0];
|
||||
};
|
||||
|
||||
const filterLockStatus = async (
|
||||
transactions: Log[]
|
||||
): Promise<WalletTransaction[]> => {
|
||||
const txs: WalletTransaction[] = [];
|
||||
|
||||
for (const transaction of transactions) {
|
||||
try {
|
||||
const decoded = decodeEventLog({
|
||||
abi: p2pix.abi,
|
||||
data: transaction.data,
|
||||
topics: transaction.topics,
|
||||
});
|
||||
|
||||
if (!decoded || !decoded.args) continue;
|
||||
|
||||
// Type assertion to handle the args safely
|
||||
const args = decoded.args as Record<string, any>;
|
||||
|
||||
const tx: WalletTransaction = {
|
||||
token: args.token ? String(args.token) : "",
|
||||
blockNumber: Number(transaction.blockNumber),
|
||||
amount: args.amount ? Number(formatEther(args.amount)) : -1,
|
||||
seller: args.seller ? String(args.seller) : "",
|
||||
buyer: args.buyer ? String(args.buyer) : "",
|
||||
event: decoded.eventName || "",
|
||||
lockStatus:
|
||||
decoded.eventName == "LockAdded" && args.lockID
|
||||
? 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 status[0];
|
||||
};
|
||||
|
||||
export const listAllTransactionByWalletAddress = async (
|
||||
walletAddress: string
|
||||
walletAddress: Address
|
||||
): Promise<WalletTransaction[]> => {
|
||||
const user = useUser();
|
||||
|
||||
@ -118,6 +74,7 @@ export const listAllTransactionByWalletAddress = async (
|
||||
query: `
|
||||
{
|
||||
depositAddeds(where: {seller: "${walletAddress.toLowerCase()}"}) {
|
||||
id
|
||||
seller
|
||||
token
|
||||
amount
|
||||
@ -129,7 +86,6 @@ export const listAllTransactionByWalletAddress = async (
|
||||
buyer
|
||||
lockID
|
||||
seller
|
||||
token
|
||||
amount
|
||||
blockTimestamp
|
||||
blockNumber
|
||||
@ -138,7 +94,6 @@ export const listAllTransactionByWalletAddress = async (
|
||||
lockReleaseds(where: {buyer: "${walletAddress.toLowerCase()}"}) {
|
||||
buyer
|
||||
lockId
|
||||
e2eId
|
||||
blockTimestamp
|
||||
blockNumber
|
||||
transactionHash
|
||||
@ -155,7 +110,6 @@ export const listAllTransactionByWalletAddress = async (
|
||||
`,
|
||||
};
|
||||
|
||||
console.log("Fetching transactions from subgraph");
|
||||
const response = await fetch(getNetworkSubgraphURL(network), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@ -165,14 +119,11 @@ export const listAllTransactionByWalletAddress = async (
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
console.log("Subgraph data fetched:", data);
|
||||
|
||||
// Convert all transactions to common WalletTransaction format
|
||||
const transactions: WalletTransaction[] = [];
|
||||
|
||||
// Process deposit added events
|
||||
if (data.data?.depositAddeds) {
|
||||
console.log("Processing deposit events");
|
||||
for (const deposit of data.data.depositAddeds) {
|
||||
transactions.push({
|
||||
token: deposit.token,
|
||||
@ -181,7 +132,7 @@ export const listAllTransactionByWalletAddress = async (
|
||||
seller: deposit.seller,
|
||||
buyer: "",
|
||||
event: "DepositAdded",
|
||||
lockStatus: -1,
|
||||
lockStatus: undefined,
|
||||
transactionHash: deposit.transactionHash,
|
||||
});
|
||||
}
|
||||
@ -189,7 +140,6 @@ export const listAllTransactionByWalletAddress = async (
|
||||
|
||||
// Process lock added events
|
||||
if (data.data?.lockAddeds) {
|
||||
console.log("Processing lock events");
|
||||
for (const lock of data.data.lockAddeds) {
|
||||
// Get lock status from the contract
|
||||
const lockStatus = await getLockStatus(BigInt(lock.lockID));
|
||||
@ -210,16 +160,15 @@ export const listAllTransactionByWalletAddress = async (
|
||||
|
||||
// Process lock released events
|
||||
if (data.data?.lockReleaseds) {
|
||||
console.log("Processing release events");
|
||||
for (const release of data.data.lockReleaseds) {
|
||||
transactions.push({
|
||||
token: "", // Subgraph doesn't provide token in this event, we could enhance this later
|
||||
token: undefined, // Subgraph doesn't provide token in this event, we could enhance this later
|
||||
blockNumber: parseInt(release.blockNumber),
|
||||
amount: -1, // Amount not available in this event
|
||||
seller: "",
|
||||
buyer: release.buyer,
|
||||
event: "LockReleased",
|
||||
lockStatus: -1,
|
||||
lockStatus: undefined,
|
||||
transactionHash: release.transactionHash,
|
||||
transactionID: release.lockId.toString(),
|
||||
});
|
||||
@ -228,7 +177,6 @@ export const listAllTransactionByWalletAddress = async (
|
||||
|
||||
// Process deposit withdrawn events
|
||||
if (data.data?.depositWithdrawns) {
|
||||
console.log("Processing withdrawal events");
|
||||
for (const withdrawal of data.data.depositWithdrawns) {
|
||||
transactions.push({
|
||||
token: withdrawal.token,
|
||||
@ -237,7 +185,7 @@ export const listAllTransactionByWalletAddress = async (
|
||||
seller: withdrawal.seller,
|
||||
buyer: "",
|
||||
event: "DepositWithdrawn",
|
||||
lockStatus: -1,
|
||||
lockStatus: undefined,
|
||||
transactionHash: withdrawal.transactionHash,
|
||||
});
|
||||
}
|
||||
@ -249,7 +197,7 @@ export const listAllTransactionByWalletAddress = async (
|
||||
|
||||
// get wallet's release transactions
|
||||
export const listReleaseTransactionByWalletAddress = async (
|
||||
walletAddress: string
|
||||
walletAddress: Address
|
||||
) => {
|
||||
const user = useUser();
|
||||
const network = user.networkName.value;
|
||||
@ -313,7 +261,7 @@ export const listReleaseTransactionByWalletAddress = async (
|
||||
.filter((decoded: any) => decoded !== null);
|
||||
};
|
||||
|
||||
const listLockTransactionByWalletAddress = async (walletAddress: string) => {
|
||||
const listLockTransactionByWalletAddress = async (walletAddress: Address) => {
|
||||
const user = useUser();
|
||||
const network = user.networkName.value;
|
||||
|
||||
@ -325,7 +273,6 @@ const listLockTransactionByWalletAddress = async (walletAddress: string) => {
|
||||
buyer
|
||||
lockID
|
||||
seller
|
||||
token
|
||||
amount
|
||||
blockTimestamp
|
||||
blockNumber
|
||||
@ -383,10 +330,9 @@ const listLockTransactionByWalletAddress = async (walletAddress: string) => {
|
||||
}
|
||||
};
|
||||
|
||||
const listLockTransactionBySellerAddress = async (sellerAddress: string) => {
|
||||
const listLockTransactionBySellerAddress = async (sellerAddress: Address) => {
|
||||
const user = useUser();
|
||||
const network = user.networkName.value;
|
||||
console.log("Will get locks as seller", sellerAddress);
|
||||
|
||||
// Query subgraph for lock added transactions where seller matches
|
||||
const subgraphQuery = {
|
||||
@ -456,54 +402,32 @@ const listLockTransactionBySellerAddress = async (sellerAddress: string) => {
|
||||
};
|
||||
|
||||
export const checkUnreleasedLock = async (
|
||||
walletAddress: string
|
||||
walletAddress: Address
|
||||
): Promise<UnreleasedLock | undefined> => {
|
||||
const { address, abi, client } = await getContract();
|
||||
const pixData: Pix = {
|
||||
pixKey: "",
|
||||
};
|
||||
|
||||
const addedLocks = await listLockTransactionByWalletAddress(walletAddress);
|
||||
|
||||
if (!addedLocks.length) return undefined;
|
||||
|
||||
const lockIds = addedLocks.map((lock: any) => lock.args.lockID);
|
||||
|
||||
const lockStatus = await client.readContract({
|
||||
const [ sortedIDs, status ] = await client.readContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "getLocksStatus",
|
||||
args: [lockIds],
|
||||
});
|
||||
|
||||
const unreleasedLockId = lockStatus[1].findIndex(
|
||||
(status: number) => status == 1
|
||||
const unreleasedLockId = status.findIndex(
|
||||
(status: LockStatus) => status == LockStatus.Active
|
||||
);
|
||||
|
||||
if (unreleasedLockId !== -1) {
|
||||
const lockID = lockStatus[0][unreleasedLockId];
|
||||
|
||||
const lock = await client.readContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "mapLocks",
|
||||
args: [lockID],
|
||||
});
|
||||
|
||||
const pixTarget = lock.pixTarget;
|
||||
const amount = formatEther(lock.amount);
|
||||
pixData.pixKey = pixTarget;
|
||||
pixData.value = Number(amount);
|
||||
|
||||
return {
|
||||
lockID,
|
||||
pix: pixData,
|
||||
};
|
||||
}
|
||||
|
||||
if (unreleasedLockId !== -1)
|
||||
return getUnreleasedLockById(sortedIDs[unreleasedLockId]);
|
||||
};
|
||||
|
||||
export const getActiveLockAmount = async (
|
||||
walletAddress: string
|
||||
walletAddress: Address
|
||||
): Promise<number> => {
|
||||
const { address, abi, client } = await getContract(true);
|
||||
const lockSeller = await listLockTransactionBySellerAddress(walletAddress);
|
||||
@ -512,19 +436,19 @@ export const getActiveLockAmount = async (
|
||||
|
||||
const lockIds = lockSeller.map((lock: any) => lock.args.lockID);
|
||||
|
||||
const lockStatus = await client.readContract({
|
||||
const [ sortedIDs, status ] = await client.readContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "getLocksStatus",
|
||||
args: [lockIds],
|
||||
});
|
||||
|
||||
const mapLocksRequests = lockStatus[0].map((id: bigint) =>
|
||||
const mapLocksRequests = status.map((id: LockStatus) =>
|
||||
client.readContract({
|
||||
address,
|
||||
address: address,
|
||||
abi,
|
||||
functionName: "mapLocks",
|
||||
args: [id],
|
||||
args: [BigInt(id)],
|
||||
})
|
||||
);
|
||||
|
||||
@ -533,9 +457,24 @@ export const getActiveLockAmount = async (
|
||||
});
|
||||
|
||||
return mapLocksResults.reduce((total: number, lock: any, index: number) => {
|
||||
if (lockStatus[1][index] === 1) {
|
||||
if (status[index] === 1) {
|
||||
return total + Number(formatEther(lock.amount));
|
||||
}
|
||||
return total;
|
||||
}, 0);
|
||||
};
|
||||
|
||||
export const getSellerParticipantId = async (
|
||||
sellerAddress: Address,
|
||||
tokenAddress: Address
|
||||
): Promise<string> => {
|
||||
const { address, abi, client } = await getContract();
|
||||
|
||||
const participantId = await client.readContract({
|
||||
address,
|
||||
abi,
|
||||
functionName: "getPixTarget",
|
||||
args: [sellerAddress, tokenAddress],
|
||||
});
|
||||
return hexToString(participantId);
|
||||
};
|
||||
|
||||
@ -1,37 +0,0 @@
|
||||
import { mount } from "@vue/test-utils";
|
||||
import BuyConfirmedComponent from "../BuyConfirmedComponent.vue";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
|
||||
describe("BuyConfirmedComponent.vue", async () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
});
|
||||
|
||||
const wrapper = mount(BuyConfirmedComponent, {
|
||||
props: {
|
||||
tokenAmount: 1,
|
||||
isCurrentStep: false,
|
||||
},
|
||||
});
|
||||
|
||||
// test("Test component Header Text", () => {
|
||||
// expect(wrapper.html()).toContain("Os tokens já foram transferidos");
|
||||
// expect(wrapper.html()).toContain("para a sua carteira!");
|
||||
// });
|
||||
|
||||
// test("Test component Container Text", () => {
|
||||
// expect(wrapper.html()).toContain("Tokens recebidos");
|
||||
// expect(wrapper.html()).toContain("BRZ");
|
||||
// expect(wrapper.html()).toContain("Não encontrou os tokens?");
|
||||
// expect(wrapper.html()).toContain("Clique no botão abaixo para");
|
||||
// expect(wrapper.html()).toContain("cadastrar o BRZ em sua carteira.");
|
||||
// });
|
||||
|
||||
test("Test makeAnotherTransactionEmit", async () => {
|
||||
wrapper.vm.$emit("makeAnotherTransaction");
|
||||
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
expect(wrapper.emitted("makeAnotherTransaction")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@ -1,27 +0,0 @@
|
||||
import { mount } from "@vue/test-utils";
|
||||
import CustomButton from "../CustomButton.vue";
|
||||
|
||||
describe("CustomButton.vue", () => {
|
||||
test("Test button content", () => {
|
||||
const wrapper = mount(CustomButton, {
|
||||
props: {
|
||||
text: "Testing",
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.html()).toContain("Testing");
|
||||
});
|
||||
|
||||
test("Test if disabled props works", () => {
|
||||
const wrapper = mount(CustomButton, {
|
||||
props: {
|
||||
isDisabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
//@ts-ignore
|
||||
const button = wrapper.find(".button") as HTMLButtonElement;
|
||||
//@ts-ignore
|
||||
expect(button.element.disabled).toBe(true);
|
||||
});
|
||||
});
|
||||
@ -19,7 +19,7 @@ if (props.isRedirectModal) {
|
||||
<template>
|
||||
<div>
|
||||
<div
|
||||
class="modal-overlay inset-0 fixed justify-center backdrop-blur-sm sm:backdrop-blur-none"
|
||||
class="modal-overlay inset-0 fixed hidden md:block justify-center backdrop-blur-sm sm:backdrop-blur-none"
|
||||
v-if="!isRedirectModal"
|
||||
>
|
||||
<div class="modal px-5 text-center">
|
||||
|
||||
@ -1,27 +0,0 @@
|
||||
import { mount } from "@vue/test-utils";
|
||||
import CustomModal from "../CustomModal.vue";
|
||||
|
||||
describe("CustomModal test", () => {
|
||||
test("Test custom modal when receive is redirect modal props as false", () => {
|
||||
const wrapper = mount(CustomModal, {
|
||||
props: {
|
||||
isRedirectModal: false,
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.html()).toContain("ATENÇÃO!");
|
||||
expect(wrapper.html()).toContain("Entendi");
|
||||
});
|
||||
|
||||
test("Test custom modal when receive is redirect modal props as true", () => {
|
||||
const wrapper = mount(CustomModal, {
|
||||
props: {
|
||||
isRedirectModal: true,
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.html()).toContain("Retomar a última compra?");
|
||||
expect(wrapper.html()).toContain("Não");
|
||||
expect(wrapper.html()).toContain("Sim");
|
||||
});
|
||||
});
|
||||
@ -7,7 +7,6 @@ import { ref, watch, onMounted } from "vue";
|
||||
import SpinnerComponent from "../SpinnerComponent.vue";
|
||||
import { decimalCount } from "@/utils/decimalCount";
|
||||
import { debounce } from "@/utils/debounce";
|
||||
import { getTokenByAddress } from "@/blockchain/addresses";
|
||||
import { useFloating, arrow, offset, flip, shift } from "@floating-ui/vue";
|
||||
|
||||
const user = useUser();
|
||||
@ -160,10 +159,14 @@ showInitialItems();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="main-container max-w-md" v-if="loadingWalletTransactions">
|
||||
<div
|
||||
class="main-container max-w-md flex justify-center items-center min-h-[200px] w-16 h-16"
|
||||
v-if="loadingWalletTransactions"
|
||||
>
|
||||
Carregando ofertas...
|
||||
<SpinnerComponent width="8" height="8"></SpinnerComponent>
|
||||
</div>
|
||||
<div class="main-container max-w-md" v-if="!loadingWalletTransactions">
|
||||
<div class="main-container max-w-md" v-else>
|
||||
<div
|
||||
class="w-full bg-white p-4 sm:p-6 rounded-lg"
|
||||
v-if="props.validDeposits.length > 0"
|
||||
@ -174,12 +177,12 @@ showInitialItems();
|
||||
Saldo disponível
|
||||
</p>
|
||||
<p class="text-xl leading-7 font-semibold text-gray-900">
|
||||
{{ getRemaining() }} {{ etherStore.selectedToken }}
|
||||
{{ getRemaining() }} {{ user.selectedToken.value }}
|
||||
</p>
|
||||
<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">{{
|
||||
`com ${activeLockAmount.toFixed(2)} ${
|
||||
etherStore.selectedToken
|
||||
user.selectedToken.value
|
||||
} em lock`
|
||||
}}</span>
|
||||
<div
|
||||
@ -283,10 +286,10 @@ showInitialItems();
|
||||
class="text-xl sm:text-xl leading-7 font-semibold text-gray-900"
|
||||
>
|
||||
{{ item.amount }}
|
||||
{{ getTokenByAddress(item.token) }}
|
||||
<!-- {{ getTokenByAddress(item.token) }} -->
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<div class="flex flex-col items-center justify-center">
|
||||
<div
|
||||
class="bg-amber-300 status-text"
|
||||
v-if="getEventName(item.event) == 'Reserva' && item.lockStatus == 1"
|
||||
@ -409,6 +412,7 @@ p {
|
||||
}
|
||||
|
||||
input[type="number"] {
|
||||
appearance: textfield;
|
||||
-moz-appearance: textfield;
|
||||
}
|
||||
|
||||
|
||||
@ -1,85 +0,0 @@
|
||||
import { describe, expect, beforeEach } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import ListingComponent from "../ListingComponent.vue";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
import { MockValidDeposits } from "@/model/mock/ValidDepositMock";
|
||||
import { MockWalletTransactions } from "@/model/mock/WalletTransactionMock";
|
||||
|
||||
describe("ListingComponent.vue", () => {
|
||||
beforeEach(() => {
|
||||
useUser().setLoadingWalletTransactions(false);
|
||||
});
|
||||
|
||||
test("Test Message when an empty array is received", () => {
|
||||
const wrapper = mount(ListingComponent, {
|
||||
props: {
|
||||
validDeposits: [],
|
||||
walletTransactions: [],
|
||||
activeLockAmount: 0,
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.html()).toContain("Não há nenhuma transação anterior");
|
||||
});
|
||||
|
||||
test("Test number of elements in the list first render", () => {
|
||||
const wrapper = mount(ListingComponent, {
|
||||
props: {
|
||||
validDeposits: [],
|
||||
walletTransactions: MockWalletTransactions,
|
||||
activeLockAmount: 0,
|
||||
},
|
||||
});
|
||||
|
||||
const elements = wrapper.findAll(".item-container");
|
||||
|
||||
expect(elements).toHaveLength(3);
|
||||
});
|
||||
|
||||
test("Test load more button behavior", async () => {
|
||||
const wrapper = mount(ListingComponent, {
|
||||
props: {
|
||||
validDeposits: MockValidDeposits,
|
||||
walletTransactions: MockWalletTransactions,
|
||||
activeLockAmount: 0,
|
||||
},
|
||||
});
|
||||
const btn = wrapper.find("button");
|
||||
|
||||
let elements = wrapper.findAll(".item-container");
|
||||
expect(elements).toHaveLength(3);
|
||||
|
||||
await btn.trigger("click");
|
||||
|
||||
elements = wrapper.findAll(".item-container");
|
||||
|
||||
expect(elements).toHaveLength(5);
|
||||
});
|
||||
|
||||
test("Test withdraw offer button emit", async () => {
|
||||
const wrapper = mount(ListingComponent, {
|
||||
props: {
|
||||
validDeposits: MockValidDeposits,
|
||||
walletTransactions: MockWalletTransactions,
|
||||
activeLockAmount: 0,
|
||||
},
|
||||
});
|
||||
wrapper.vm.$emit("depositWithdrawn");
|
||||
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
expect(wrapper.emitted("depositWithdrawn")).toBeTruthy();
|
||||
});
|
||||
|
||||
test("Test should render lock info when active lock amount is greater than 0", () => {
|
||||
const wrapper = mount(ListingComponent, {
|
||||
props: {
|
||||
validDeposits: MockValidDeposits,
|
||||
walletTransactions: [],
|
||||
activeLockAmount: 50,
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.html()).toContain("com 50.00 BRZ em lock");
|
||||
});
|
||||
});
|
||||
@ -1,27 +0,0 @@
|
||||
import { mount } from "@vue/test-utils";
|
||||
import LoadingComponent from "../LoadingComponent.vue";
|
||||
|
||||
describe("Loading.vue", () => {
|
||||
test("Test loading content with received props", () => {
|
||||
const wrapper = mount(LoadingComponent, {
|
||||
props: {
|
||||
title: "MockTitle",
|
||||
message: "MockMessage",
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.html()).toContain("MockTitle");
|
||||
expect(wrapper.html()).toContain("MockMessage");
|
||||
});
|
||||
|
||||
test("Test default text if props title isnt passed", () => {
|
||||
const wrapper = mount(LoadingComponent, {
|
||||
props: {
|
||||
message: "MockMessage",
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.html()).toContain("Confirme em sua carteira");
|
||||
expect(wrapper.html()).toContain("MockMessage");
|
||||
});
|
||||
});
|
||||
@ -1,28 +1,124 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onUnmounted, ref } from "vue";
|
||||
import { ref, onMounted, onUnmounted } from "vue";
|
||||
import CustomButton from "@/components/CustomButton/CustomButton.vue";
|
||||
import CustomModal from "@/components//CustomModal/CustomModal.vue";
|
||||
import SpinnerComponent from "@/components/SpinnerComponent.vue";
|
||||
import { createSolicitation, getSolicitation, type Offer } from "@/utils/bbPay";
|
||||
import { getSellerParticipantId } from "@/blockchain/wallet";
|
||||
import { getUnreleasedLockById } from "@/blockchain/events";
|
||||
import QRCode from "qrcode";
|
||||
|
||||
// Props
|
||||
interface Props {
|
||||
lockID: string;
|
||||
}
|
||||
|
||||
const props = defineProps<Props>();
|
||||
|
||||
const windowSize = ref<number>(window.innerWidth);
|
||||
const qrCode = ref<string>("");
|
||||
const isPixValid = ref<boolean>(false);
|
||||
const qrCodeSvg = ref<string>("");
|
||||
const showWarnModal = ref<boolean>(true);
|
||||
const pixTarget = ref<string>("");
|
||||
const releaseSignature = ref<string>("");
|
||||
const solicitationData = ref<any>(null);
|
||||
const pollingInterval = ref<NodeJS.Timeout | null>(null);
|
||||
|
||||
// Function to generate QR code SVG
|
||||
const generateQrCodeSvg = async (text: string) => {
|
||||
try {
|
||||
const svgString = await QRCode.toString(text, {
|
||||
type: "svg",
|
||||
width: 192, // 48 * 4 for better quality
|
||||
margin: 2,
|
||||
color: {
|
||||
dark: "#000000",
|
||||
light: "#FFFFFF",
|
||||
},
|
||||
});
|
||||
qrCodeSvg.value = svgString;
|
||||
} catch (error) {
|
||||
console.error("Error generating QR code SVG:", error);
|
||||
}
|
||||
};
|
||||
|
||||
// Emits
|
||||
const emit = defineEmits(["pixValidated"]);
|
||||
|
||||
onMounted(() => {
|
||||
window.addEventListener(
|
||||
"resize",
|
||||
() => (windowSize.value = window.innerWidth)
|
||||
);
|
||||
// Function to check solicitation status
|
||||
const checkSolicitationStatus = async () => {
|
||||
if (!solicitationData.value?.numeroSolicitacao) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await getSolicitation(
|
||||
solicitationData.value.numeroSolicitacao
|
||||
);
|
||||
|
||||
if (response.signature) {
|
||||
pixTarget.value = response.pixTarget;
|
||||
releaseSignature.value = response.signature;
|
||||
// Stop polling when payment is confirmed
|
||||
if (pollingInterval.value) {
|
||||
clearInterval(pollingInterval.value);
|
||||
pollingInterval.value = null;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error checking solicitation status:", error);
|
||||
}
|
||||
};
|
||||
|
||||
// Function to start polling
|
||||
const startPolling = () => {
|
||||
// Clear any existing interval
|
||||
if (pollingInterval.value) {
|
||||
clearInterval(pollingInterval.value);
|
||||
}
|
||||
|
||||
// Start new polling interval (10 seconds)
|
||||
pollingInterval.value = setInterval(checkSolicitationStatus, 10000);
|
||||
};
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const { tokenAddress, sellerAddress, amount } = await getUnreleasedLockById(
|
||||
BigInt(props.lockID)
|
||||
);
|
||||
|
||||
const participantId = await getSellerParticipantId(
|
||||
sellerAddress,
|
||||
tokenAddress
|
||||
);
|
||||
|
||||
const offer: Offer = {
|
||||
amount,
|
||||
sellerId: participantId,
|
||||
};
|
||||
|
||||
const response = await createSolicitation(offer);
|
||||
solicitationData.value = response;
|
||||
|
||||
// Update qrCode if the response contains QR code data
|
||||
if (response?.informacoesPIX?.textoQrCode) {
|
||||
qrCode.value = response.informacoesPIX?.textoQrCode;
|
||||
// Generate SVG QR code
|
||||
await generateQrCodeSvg(qrCode.value);
|
||||
}
|
||||
|
||||
// Start polling for solicitation status
|
||||
startPolling();
|
||||
} catch (error) {
|
||||
console.error("Error creating solicitation:", error);
|
||||
}
|
||||
});
|
||||
|
||||
// Clean up interval on component unmount
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener(
|
||||
"resize",
|
||||
() => (windowSize.value = window.innerWidth)
|
||||
);
|
||||
if (pollingInterval.value) {
|
||||
clearInterval(pollingInterval.value);
|
||||
pollingInterval.value = null;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
@ -43,7 +139,17 @@ onUnmounted(() => {
|
||||
<div
|
||||
class="flex-col items-center justify-center flex w-full bg-white sm:p-8 p-4 rounded-lg break-normal"
|
||||
>
|
||||
<img alt="Qr code image" :src="qrCode" class="w-48 h-48" />
|
||||
<div
|
||||
v-if="qrCodeSvg"
|
||||
v-html="qrCodeSvg"
|
||||
class="w-48 h-48 flex items-center justify-center"
|
||||
></div>
|
||||
<div
|
||||
v-else
|
||||
class="w-48 h-48 flex items-center justify-center rounded-lg"
|
||||
>
|
||||
<SpinnerComponent width="8" height="8"></SpinnerComponent>
|
||||
</div>
|
||||
<span class="text-center font-bold">Código pix</span>
|
||||
<div class="break-words w-4/5">
|
||||
<span class="text-center text-xs">
|
||||
@ -59,13 +165,17 @@ onUnmounted(() => {
|
||||
/>
|
||||
</div>
|
||||
<CustomButton
|
||||
:is-disabled="isPixValid == false"
|
||||
:text="'Enviar para a rede'"
|
||||
@button-clicked="emit('pixValidated', releaseSignature)"
|
||||
:is-disabled="releaseSignature === ''"
|
||||
:text="
|
||||
releaseSignature ? 'Enviar para a rede' : 'Validando pagamento...'
|
||||
"
|
||||
@button-clicked="
|
||||
emit('pixValidated', { pixTarget, signature: releaseSignature })
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
<CustomModal
|
||||
v-if="showWarnModal && windowSize <= 500"
|
||||
v-if="showWarnModal"
|
||||
@close-modal="showWarnModal = false"
|
||||
:isRedirectModal="false"
|
||||
/>
|
||||
@ -122,6 +232,7 @@ h2 {
|
||||
}
|
||||
|
||||
input[type="number"] {
|
||||
appearance: textfield;
|
||||
-moz-appearance: textfield;
|
||||
}
|
||||
|
||||
|
||||
@ -38,7 +38,7 @@ const selectedDeposits = ref<ValidDeposit[]>();
|
||||
|
||||
import ChevronDown from "@/assets/chevronDown.svg";
|
||||
import { useOnboard } from "@web3-onboard/vue";
|
||||
import { getPixKey } from "@/blockchain/events";
|
||||
import { getParticipantID } from "@/blockchain/events";
|
||||
|
||||
// Emits
|
||||
const emit = defineEmits(["tokenBuy"]);
|
||||
@ -54,7 +54,7 @@ const emitConfirmButton = async (): Promise<void> => {
|
||||
(d) => d.network === Number(networkName.value)
|
||||
);
|
||||
if (!deposit) return;
|
||||
deposit.pixKey = await getPixKey(deposit.seller, deposit.token);
|
||||
deposit.participantID = await getParticipantID(deposit.seller, deposit.token);
|
||||
emit("tokenBuy", deposit, tokenValue.value);
|
||||
};
|
||||
|
||||
@ -90,6 +90,8 @@ const handleSelectedToken = (token: TokenEnum): void => {
|
||||
// Verify if there is a valid deposit to buy
|
||||
const verifyLiquidity = (): void => {
|
||||
enableConfirmButton.value = false;
|
||||
if (!walletAddress.value)
|
||||
return;
|
||||
const selDeposits = verifyNetworkLiquidity(
|
||||
tokenValue.value,
|
||||
walletAddress.value,
|
||||
|
||||
@ -57,6 +57,8 @@ watch(connectedChain, (newVal: any) => {
|
||||
});
|
||||
|
||||
const formatWalletAddress = (): string => {
|
||||
if (!walletAddress.value)
|
||||
throw new Error("Wallet not connected");
|
||||
const walletAddressLength = walletAddress.value.length;
|
||||
const initialText = walletAddress.value.substring(0, 5);
|
||||
const finalText = walletAddress.value.substring(
|
||||
@ -67,7 +69,7 @@ const formatWalletAddress = (): string => {
|
||||
};
|
||||
|
||||
const disconnectUser = async (): Promise<void> => {
|
||||
user.setWalletAddress("");
|
||||
user.setWalletAddress(null);
|
||||
await disconnectWallet({ label: connectedWallet.value?.label || "" });
|
||||
closeMenu();
|
||||
};
|
||||
|
||||
@ -1,35 +0,0 @@
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import TopBar from "../TopBar.vue";
|
||||
import { useUser } from "@/composables/useUser";
|
||||
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
|
||||
describe("TopBar.vue", () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
});
|
||||
|
||||
it("should render connect wallet button", () => {
|
||||
const wrapper = mount(TopBar);
|
||||
expect(wrapper.html()).toContain("Conectar carteira");
|
||||
});
|
||||
|
||||
it("should render button to change to seller view when in buyer screen", () => {
|
||||
const wrapper = mount(TopBar);
|
||||
expect(wrapper.html()).toContain("Quero vender");
|
||||
});
|
||||
|
||||
it("should render button to change to seller view when in buyer screen", () => {
|
||||
const user = useUser();
|
||||
user.setSellerView(true);
|
||||
const wrapper = mount(TopBar);
|
||||
expect(wrapper.html()).toContain("Quero comprar");
|
||||
});
|
||||
|
||||
it("should render the P2Pix logo correctly", () => {
|
||||
const wrapper = mount(TopBar);
|
||||
const img = wrapper.findAll(".logo");
|
||||
expect(img.length).toBe(2);
|
||||
});
|
||||
});
|
||||
@ -3,8 +3,9 @@ import { NetworkEnum, TokenEnum } from "../model/NetworkEnum";
|
||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||
import type { Participant } from "../utils/bbPay";
|
||||
import { NetworkById } from "@/model/Networks";
|
||||
import type { Address } from "viem"
|
||||
|
||||
const walletAddress = ref("");
|
||||
const walletAddress = ref<Address | null>(null);
|
||||
const balance = ref("");
|
||||
const networkId = ref(11155111);
|
||||
const networkName = ref(NetworkEnum.sepolia);
|
||||
@ -19,7 +20,7 @@ const sellerId = ref("");
|
||||
|
||||
export function useUser() {
|
||||
// Actions become regular functions
|
||||
const setWalletAddress = (address: string) => {
|
||||
const setWalletAddress = (address: Address | null) => {
|
||||
walletAddress.value = address;
|
||||
};
|
||||
|
||||
|
||||
8
src/model/LockStatus.ts
Normal file
8
src/model/LockStatus.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import type { Address } from "viem";
|
||||
|
||||
export enum LockStatus { // from DataTypes.sol
|
||||
Inexistent = 0, // Uninitialized Lock
|
||||
Active = 1, // Valid Lock
|
||||
Expired = 2, // Expired Lock
|
||||
Released = 3 // Already released Lock
|
||||
}
|
||||
@ -3,13 +3,13 @@ export enum NetworkEnum {
|
||||
rootstock = 31,
|
||||
}
|
||||
|
||||
export const getNetworkSubgraphURL = (network: NetworkEnum | number) => {
|
||||
const networkMap: Record<number, string> = {
|
||||
export const getNetworkSubgraphURL = (network: NetworkEnum) => {
|
||||
const networkMap: Record<NetworkEnum, string> = {
|
||||
[NetworkEnum.sepolia]: import.meta.env.VITE_SEPOLIA_SUBGRAPH_URL || "",
|
||||
[NetworkEnum.rootstock]: import.meta.env.VITE_RSK_SUBGRAPH_URL || "",
|
||||
};
|
||||
|
||||
return networkMap[typeof network === "number" ? network : network] || "";
|
||||
return networkMap[network] || "";
|
||||
};
|
||||
|
||||
export enum TokenEnum {
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
export type Pix = {
|
||||
pixKey: string;
|
||||
merchantCity?: string;
|
||||
merchantName?: string;
|
||||
value?: number;
|
||||
transactionId?: string;
|
||||
message?: string;
|
||||
cep?: string;
|
||||
currency?: number;
|
||||
countryCode?: string;
|
||||
pixKey: string;
|
||||
merchantCity?: string;
|
||||
merchantName?: string;
|
||||
value?: number;
|
||||
transactionId?: string;
|
||||
message?: string;
|
||||
cep?: string;
|
||||
currency?: number;
|
||||
countryCode?: string;
|
||||
};
|
||||
|
||||
@ -1,6 +1,8 @@
|
||||
import type { Pix } from "./Pix";
|
||||
import { Address } from "viem";
|
||||
|
||||
export type UnreleasedLock = {
|
||||
lockID: string;
|
||||
pix: Pix;
|
||||
lockID: bigint;
|
||||
sellerAddress: Address;
|
||||
tokenAddress: Address;
|
||||
amount: number;
|
||||
};
|
||||
|
||||
@ -1,11 +1,12 @@
|
||||
import { NetworkEnum } from "./NetworkEnum";
|
||||
import type { Address } from "viem";
|
||||
|
||||
export type ValidDeposit = {
|
||||
token: string;
|
||||
token: Address;
|
||||
blockNumber: number;
|
||||
remaining: number;
|
||||
seller: string;
|
||||
pixKey: string;
|
||||
seller: Address;
|
||||
participantID: string;
|
||||
network: NetworkEnum;
|
||||
open?: boolean;
|
||||
};
|
||||
|
||||
@ -1,11 +1,14 @@
|
||||
import type { LockStatus } from "@/model/LockStatus"
|
||||
import type { Address } from "viem"
|
||||
|
||||
export type WalletTransaction = {
|
||||
token: string;
|
||||
token?: Address;
|
||||
blockNumber: number;
|
||||
amount: number;
|
||||
seller: string;
|
||||
buyer: string;
|
||||
event: string;
|
||||
lockStatus: number;
|
||||
lockStatus?: LockStatus;
|
||||
transactionHash: string;
|
||||
transactionID?: string;
|
||||
};
|
||||
|
||||
@ -1,120 +0,0 @@
|
||||
import { vi } from "vitest";
|
||||
|
||||
export const MockEvents = [
|
||||
{
|
||||
blockNumber: 1,
|
||||
blockHash: "0x8",
|
||||
transactionIndex: 1,
|
||||
removed: false,
|
||||
address: "0x0",
|
||||
data: "0x0",
|
||||
topics: ["0x0", "0x0"],
|
||||
transactionHash: "0x0",
|
||||
logIndex: 1,
|
||||
event: "DepositAdded",
|
||||
eventSignature: "DepositAdded(address,uint256,address,uint256)",
|
||||
args: [
|
||||
"0x0",
|
||||
{
|
||||
type: "BigNumber",
|
||||
hex: "0x00",
|
||||
},
|
||||
"0x0",
|
||||
{
|
||||
type: "BigNumber",
|
||||
hex: "0x6c6b935b8bbd400000",
|
||||
},
|
||||
],
|
||||
getBlock: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
getTransaction: vi.fn(),
|
||||
getTransactionReceipt: vi.fn(),
|
||||
},
|
||||
{
|
||||
blockNumber: 2,
|
||||
blockHash: "0x8",
|
||||
transactionIndex: 2,
|
||||
removed: false,
|
||||
address: "0x0",
|
||||
data: "0x0",
|
||||
topics: ["0x0", "0x0"],
|
||||
transactionHash: "0x0",
|
||||
logIndex: 2,
|
||||
event: "LockAdded",
|
||||
eventSignature: "LockAdded(address,uint256,address,uint256)",
|
||||
args: [
|
||||
"0x0",
|
||||
{
|
||||
type: "BigNumber",
|
||||
hex: "0x00",
|
||||
},
|
||||
"0x0",
|
||||
{
|
||||
type: "BigNumber",
|
||||
hex: "0x6c6b935b8bbd400000",
|
||||
},
|
||||
],
|
||||
getBlock: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
getTransaction: vi.fn(),
|
||||
getTransactionReceipt: vi.fn(),
|
||||
},
|
||||
{
|
||||
blockNumber: 3,
|
||||
blockHash: "0x8",
|
||||
transactionIndex: 3,
|
||||
removed: false,
|
||||
address: "0x0",
|
||||
data: "0x0",
|
||||
topics: ["0x0", "0x0"],
|
||||
transactionHash: "0x0",
|
||||
logIndex: 3,
|
||||
event: "LockReleased",
|
||||
eventSignature: "LockReleased(address,uint256,address,uint256)",
|
||||
args: [
|
||||
"0x0",
|
||||
{
|
||||
type: "BigNumber",
|
||||
hex: "0x00",
|
||||
},
|
||||
"0x0",
|
||||
{
|
||||
type: "BigNumber",
|
||||
hex: "0x6c6b935b8bbd400000",
|
||||
},
|
||||
],
|
||||
getBlock: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
getTransaction: vi.fn(),
|
||||
getTransactionReceipt: vi.fn(),
|
||||
},
|
||||
{
|
||||
blockNumber: 4,
|
||||
blockHash: "0x8",
|
||||
transactionIndex: 4,
|
||||
removed: false,
|
||||
address: "0x0",
|
||||
data: "0x0",
|
||||
topics: ["0x0", "0x0"],
|
||||
transactionHash: "0x0",
|
||||
logIndex: 4,
|
||||
event: "LockReleased",
|
||||
eventSignature: "LockReleased(address,uint256,address,uint256)",
|
||||
args: [
|
||||
"0x0",
|
||||
{
|
||||
type: "BigNumber",
|
||||
hex: "0x00",
|
||||
},
|
||||
"0x0",
|
||||
{
|
||||
type: "BigNumber",
|
||||
hex: "0x6c6b935b8bbd400000",
|
||||
},
|
||||
],
|
||||
getBlock: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
getTransaction: vi.fn(),
|
||||
getTransactionReceipt: vi.fn(),
|
||||
},
|
||||
];
|
||||
@ -1,45 +0,0 @@
|
||||
import type { ValidDeposit } from "../ValidDeposit";
|
||||
import { NetworkEnum } from "@/model/NetworkEnum";
|
||||
|
||||
export const MockValidDeposits: ValidDeposit[] = [
|
||||
{
|
||||
blockNumber: 1,
|
||||
token: "1",
|
||||
remaining: 70,
|
||||
seller: "mockedSellerAddress",
|
||||
pixKey: "123456789",
|
||||
network: NetworkEnum.sepolia,
|
||||
},
|
||||
{
|
||||
blockNumber: 2,
|
||||
token: "2",
|
||||
remaining: 200,
|
||||
seller: "mockedSellerAddress",
|
||||
pixKey: "123456789",
|
||||
network: NetworkEnum.sepolia,
|
||||
},
|
||||
{
|
||||
blockNumber: 3,
|
||||
token: "3",
|
||||
remaining: 1250,
|
||||
seller: "mockedSellerAddress",
|
||||
pixKey: "123456789",
|
||||
network: NetworkEnum.sepolia,
|
||||
},
|
||||
{
|
||||
blockNumber: 4,
|
||||
token: "4",
|
||||
remaining: 4000,
|
||||
seller: "mockedSellerAddress",
|
||||
pixKey: "123456789",
|
||||
network: NetworkEnum.sepolia,
|
||||
},
|
||||
{
|
||||
blockNumber: 5,
|
||||
token: "5",
|
||||
remaining: 2000,
|
||||
seller: "mockedSellerAddress",
|
||||
pixKey: "123456789",
|
||||
network: NetworkEnum.sepolia,
|
||||
},
|
||||
];
|
||||
@ -1,54 +0,0 @@
|
||||
import type { WalletTransaction } from "../WalletTransaction";
|
||||
|
||||
export const MockWalletTransactions: WalletTransaction[] = [
|
||||
{
|
||||
blockNumber: 1,
|
||||
token: "1",
|
||||
amount: 70,
|
||||
seller: "mockedSellerAddress",
|
||||
buyer: "mockedBuyerAddress",
|
||||
event: "Deposit",
|
||||
lockStatus: 0,
|
||||
transactionHash: "1",
|
||||
},
|
||||
{
|
||||
blockNumber: 2,
|
||||
token: "2",
|
||||
amount: 200,
|
||||
seller: "mockedSellerAddress",
|
||||
buyer: "mockedBuyerAddress",
|
||||
event: "Lock",
|
||||
lockStatus: 1,
|
||||
transactionHash: "2",
|
||||
},
|
||||
{
|
||||
blockNumber: 3,
|
||||
token: "3",
|
||||
amount: 1250,
|
||||
seller: "mockedSellerAddress",
|
||||
buyer: "mockedBuyerAddress",
|
||||
event: "Release",
|
||||
lockStatus: 2,
|
||||
transactionHash: "3",
|
||||
},
|
||||
{
|
||||
blockNumber: 4,
|
||||
token: "4",
|
||||
amount: 4000,
|
||||
seller: "mockedSellerAddress",
|
||||
buyer: "mockedBuyerAddress",
|
||||
event: "Deposit",
|
||||
lockStatus: 0,
|
||||
transactionHash: "4",
|
||||
},
|
||||
{
|
||||
blockNumber: 5,
|
||||
token: "5",
|
||||
amount: 2000,
|
||||
seller: "mockedSellerAddress",
|
||||
buyer: "mockedBuyerAddress",
|
||||
event: "Deposit",
|
||||
lockStatus: 3,
|
||||
transactionHash: "5",
|
||||
},
|
||||
];
|
||||
@ -1,76 +0,0 @@
|
||||
import qrcode from "qrcode";
|
||||
import type { QRCodeToDataURLOptions } from "qrcode";
|
||||
import { crc16ccitt } from "crc";
|
||||
import type { Pix } from "@/model/Pix";
|
||||
|
||||
const pix = ({
|
||||
pixKey,
|
||||
merchantCity = "city",
|
||||
merchantName = "name",
|
||||
value,
|
||||
message,
|
||||
cep,
|
||||
transactionId = "***",
|
||||
currency = 986,
|
||||
countryCode = "BR",
|
||||
}: Pix) => {
|
||||
const payloadKeyString = generatePixKey(pixKey, message);
|
||||
|
||||
const payload: string[] = [
|
||||
formatEMV("00", "01"), //Payload Format Indicator
|
||||
formatEMV("26", payloadKeyString), // Merchant Account Information
|
||||
formatEMV("52", "0000"), //Merchant Category Code
|
||||
formatEMV("53", String(currency)), // Transaction Currency
|
||||
];
|
||||
|
||||
if (String(value) === "0") {
|
||||
value = undefined;
|
||||
}
|
||||
if (value) {
|
||||
payload.push(formatEMV("54", value.toFixed(2)));
|
||||
}
|
||||
|
||||
payload.push(formatEMV("58", countryCode.toUpperCase())); // Country Code
|
||||
payload.push(formatEMV("59", merchantName)); // Merchant Name
|
||||
payload.push(formatEMV("60", merchantCity)); // Merchant City
|
||||
|
||||
if (cep) {
|
||||
payload.push(formatEMV("61", cep)); // Postal Code
|
||||
}
|
||||
|
||||
payload.push(formatEMV("62", formatEMV("05", transactionId))); // Additional Data Field Template
|
||||
|
||||
payload.push("6304");
|
||||
|
||||
const stringPayload = payload.join("");
|
||||
const crcResult = crc16ccitt(stringPayload)
|
||||
.toString(16)
|
||||
.toUpperCase()
|
||||
.padStart(4, "0");
|
||||
|
||||
const payloadPIX = `${stringPayload}${crcResult}`;
|
||||
|
||||
return {
|
||||
payload: (): string => payloadPIX,
|
||||
base64QrCode: (options?: QRCodeToDataURLOptions): Promise<string> =>
|
||||
qrcode.toDataURL(payloadPIX, options),
|
||||
};
|
||||
};
|
||||
|
||||
const generatePixKey = (pixKey: string, message?: string): string => {
|
||||
const payload: string[] = [
|
||||
formatEMV("00", "BR.GOV.BCB.PIX"),
|
||||
formatEMV("01", pixKey),
|
||||
];
|
||||
if (message) {
|
||||
payload.push(formatEMV("02", message));
|
||||
}
|
||||
return payload.join("");
|
||||
};
|
||||
|
||||
const formatEMV = (id: string, param: string): string => {
|
||||
const len = param?.length?.toString().padStart(2, "0");
|
||||
return `${id}${len}${param}`;
|
||||
};
|
||||
|
||||
export { pix };
|
||||
@ -1,24 +0,0 @@
|
||||
import { it, expect, vi, type Mock } from "vitest";
|
||||
import { debounce } from "../debounce";
|
||||
|
||||
vi.useFakeTimers();
|
||||
|
||||
describe("debounce function test", () => {
|
||||
let mockFunction: Mock;
|
||||
let debounceFunction: Function;
|
||||
|
||||
beforeEach(() => {
|
||||
mockFunction = vi.fn();
|
||||
debounceFunction = debounce(mockFunction, 1000);
|
||||
});
|
||||
|
||||
it("debounce function will be executed just once", () => {
|
||||
for (let i = 0; i < 100; i++) {
|
||||
debounceFunction();
|
||||
}
|
||||
|
||||
vi.runAllTimers();
|
||||
|
||||
expect(mockFunction).toBeCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@ -1,12 +0,0 @@
|
||||
import { it, expect } from "vitest";
|
||||
import { decimalCount } from "../decimalCount";
|
||||
|
||||
describe("decimalCount function test", () => {
|
||||
it("decimalCount should return length 1 of decimal", () => {
|
||||
expect(decimalCount("4.1")).toEqual(1);
|
||||
});
|
||||
|
||||
it("decimalCount should return length 0 because no decimal found", () => {
|
||||
expect(decimalCount("5")).toEqual(0);
|
||||
});
|
||||
});
|
||||
@ -1,25 +0,0 @@
|
||||
import { MockValidDeposits } from "@/model/mock/ValidDepositMock";
|
||||
import { it, expect, vi } from "vitest";
|
||||
import { verifyNetworkLiquidity } from "../networkLiquidity";
|
||||
|
||||
vi.useFakeTimers();
|
||||
|
||||
describe("verifyNetworkLiquidity function test", () => {
|
||||
it("verifyNetworkLiquidity should return an element from valid deposit list when searching for other deposits", () => {
|
||||
const liquidityElement = verifyNetworkLiquidity(
|
||||
MockValidDeposits[0].remaining,
|
||||
"strangeWalletAddress",
|
||||
MockValidDeposits
|
||||
);
|
||||
expect(liquidityElement).toEqual(MockValidDeposits[0]);
|
||||
});
|
||||
|
||||
it("verifyNetworkLiquidity should return undefined when all deposits on valid deposit list match connected wallet addres", () => {
|
||||
const liquidityElement = verifyNetworkLiquidity(
|
||||
MockValidDeposits[0].remaining,
|
||||
MockValidDeposits[0].seller,
|
||||
[MockValidDeposits[0]]
|
||||
);
|
||||
expect(liquidityElement).toEqual(undefined);
|
||||
});
|
||||
});
|
||||
@ -1,5 +1,3 @@
|
||||
import { off } from "process";
|
||||
|
||||
export interface Participant {
|
||||
offer: string;
|
||||
chainID: number;
|
||||
@ -17,7 +15,6 @@ export interface ParticipantWithID extends Participant {
|
||||
|
||||
export interface Offer {
|
||||
amount: number;
|
||||
lockId: string;
|
||||
sellerId: string;
|
||||
}
|
||||
|
||||
@ -25,7 +22,6 @@ export interface Offer {
|
||||
// https://apoio.developers.bb.com.br/sandbox/spec/665797498bb48200130fc32c
|
||||
|
||||
export const createParticipant = async (participant: Participant) => {
|
||||
console.log("Creating participant", participant);
|
||||
const response = await fetch(`${import.meta.env.VITE_APP_API_URL}/register`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
@ -41,8 +37,14 @@ export const createParticipant = async (participant: Participant) => {
|
||||
codigoIspb: participant.bankIspb,
|
||||
}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Error creating participant: ${response.statusText}`);
|
||||
}
|
||||
const data = await response.json();
|
||||
return { ...participant, id: data.id } as ParticipantWithID;
|
||||
if (data.errors || data.erros) {
|
||||
throw new Error(`Error creating participant: ${JSON.stringify(data)}`);
|
||||
}
|
||||
return { ...participant, id: data.numeroParticipante } as ParticipantWithID;
|
||||
};
|
||||
|
||||
export const createSolicitation = async (offer: Offer) => {
|
||||
@ -53,7 +55,7 @@ export const createSolicitation = async (offer: Offer) => {
|
||||
},
|
||||
body: JSON.stringify({
|
||||
amount: offer.amount,
|
||||
pixTarget: offer.sellerId,
|
||||
pixTarget: offer.sellerId.split("-").pop(),
|
||||
}),
|
||||
});
|
||||
return response.json();
|
||||
@ -64,14 +66,10 @@ export const getSolicitation = async (id: string) => {
|
||||
`${import.meta.env.VITE_APP_API_URL}/release/${id}`
|
||||
);
|
||||
|
||||
const obj: any = response.json();
|
||||
const obj: any = await response.json();
|
||||
|
||||
return {
|
||||
id: obj.numeroSolicitacao,
|
||||
lockId: obj.codigoConciliacaoSolicitacao,
|
||||
amount: obj.valorSolicitacao,
|
||||
qrcode: obj.pix.textoQrCode,
|
||||
status: obj.valorSomatorioPagamentosEfetivados >= obj.valorSolicitacao,
|
||||
signature: obj.assinatura,
|
||||
pixTarget: obj.pixTarget,
|
||||
signature: obj.signature,
|
||||
};
|
||||
};
|
||||
|
||||
@ -1,8 +1,9 @@
|
||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||
import type { Address } from "viem";
|
||||
|
||||
const verifyNetworkLiquidity = (
|
||||
tokenValue: number,
|
||||
walletAddress: string,
|
||||
walletAddress: Address,
|
||||
validDepositList: ValidDeposit[]
|
||||
): ValidDeposit[] => {
|
||||
const filteredDepositList = validDepositList
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -24,7 +24,6 @@ const openItem = (index: number) => {
|
||||
faq.value[selectedSection.value].items[index].content = marked(
|
||||
faq.value[selectedSection.value].items[index].content
|
||||
);
|
||||
console.log(marked(faq.value[selectedSection.value].items[index].content));
|
||||
};
|
||||
</script>
|
||||
|
||||
|
||||
@ -12,6 +12,7 @@ import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||
import { getUnreleasedLockById } from "@/blockchain/events";
|
||||
import CustomAlert from "@/components/CustomAlert/CustomAlert.vue";
|
||||
import { getSolicitation } from "@/utils/bbPay";
|
||||
import type { Address } from "viem";
|
||||
|
||||
enum Step {
|
||||
Search,
|
||||
@ -25,7 +26,8 @@ user.setSellerView(false);
|
||||
// States
|
||||
const { loadingLock, walletAddress, networkName } = user;
|
||||
const flowStep = ref<Step>(Step.Search);
|
||||
const pixTarget = ref<string>();
|
||||
const participantID = ref<string>();
|
||||
const sellerAddress = ref<Address>();
|
||||
const tokenAmount = ref<number>();
|
||||
const lockID = ref<string>("");
|
||||
const loadingRelease = ref<boolean>(false);
|
||||
@ -37,7 +39,7 @@ const confirmBuyClick = async (
|
||||
selectedDeposit: ValidDeposit,
|
||||
tokenValue: number
|
||||
) => {
|
||||
pixTarget.value = selectedDeposit.pixKey;
|
||||
participantID.value = selectedDeposit.participantID;
|
||||
tokenAmount.value = tokenValue;
|
||||
|
||||
if (selectedDeposit) {
|
||||
@ -46,7 +48,7 @@ const confirmBuyClick = async (
|
||||
|
||||
await addLock(selectedDeposit.seller, selectedDeposit.token, tokenValue)
|
||||
.then((_lockID) => {
|
||||
lockID.value = _lockID;
|
||||
lockID.value = String(_lockID);
|
||||
})
|
||||
.catch((err) => {
|
||||
console.log(err);
|
||||
@ -57,28 +59,32 @@ const confirmBuyClick = async (
|
||||
}
|
||||
};
|
||||
|
||||
const releaseTransaction = async (lockId: string) => {
|
||||
const releaseTransaction = async ({
|
||||
pixTarget,
|
||||
signature,
|
||||
}: {
|
||||
pixTarget: string;
|
||||
signature: string;
|
||||
}) => {
|
||||
flowStep.value = Step.List;
|
||||
showBuyAlert.value = true;
|
||||
loadingRelease.value = true;
|
||||
|
||||
const solicitation = await getSolicitation(lockId);
|
||||
const release = await releaseLock(BigInt(lockID.value), pixTarget, signature);
|
||||
await release.wait();
|
||||
|
||||
if (solicitation.status) {
|
||||
const release = await releaseLock(solicitation);
|
||||
await release.wait();
|
||||
|
||||
await updateWalletStatus();
|
||||
loadingRelease.value = false;
|
||||
}
|
||||
await updateWalletStatus();
|
||||
loadingRelease.value = false;
|
||||
};
|
||||
|
||||
const checkForUnreleasedLocks = async (): Promise<void> => {
|
||||
const walletLocks = await checkUnreleasedLock(walletAddress.value);
|
||||
if (walletLocks) {
|
||||
lockID.value = walletLocks.lockID;
|
||||
tokenAmount.value = walletLocks.pix.value;
|
||||
pixTarget.value = walletLocks.pix.pixKey;
|
||||
if (!walletAddress.value)
|
||||
throw new Error("Wallet not connected");
|
||||
const lock = await checkUnreleasedLock(walletAddress.value);
|
||||
if (lock) {
|
||||
lockID.value = String(lock.lockID);
|
||||
tokenAmount.value = lock.amount;
|
||||
sellerAddress.value = lock.sellerAddress;
|
||||
showModal.value = true;
|
||||
} else {
|
||||
flowStep.value = Step.Search;
|
||||
@ -87,11 +93,11 @@ const checkForUnreleasedLocks = async (): Promise<void> => {
|
||||
};
|
||||
|
||||
if (paramLockID) {
|
||||
const lockToRedirect = await getUnreleasedLockById(paramLockID as string);
|
||||
const lockToRedirect = await getUnreleasedLockById(paramLockID);
|
||||
if (lockToRedirect) {
|
||||
lockID.value = lockToRedirect.lockID;
|
||||
tokenAmount.value = lockToRedirect.pix.value;
|
||||
pixTarget.value = lockToRedirect.pix.pixKey;
|
||||
lockID.value = String(lockToRedirect.lockID);
|
||||
tokenAmount.value = lockToRedirect.amount;
|
||||
sellerAddress.value = lockToRedirect.sellerAddress;
|
||||
flowStep.value = Step.Buy;
|
||||
} else {
|
||||
flowStep.value = Step.Search;
|
||||
@ -134,8 +140,7 @@ onMounted(async () => {
|
||||
/>
|
||||
<div v-if="flowStep == Step.Buy">
|
||||
<QrCodeComponent
|
||||
:sellerId="String(pixTarget)"
|
||||
:amount="tokenAmount"
|
||||
:lockID="lockID"
|
||||
@pix-validated="releaseTransaction"
|
||||
v-if="!loadingLock"
|
||||
/>
|
||||
|
||||
@ -48,19 +48,15 @@ const callWithdraw = async (amount: string) => {
|
||||
const getWalletTransactions = async () => {
|
||||
user.setLoadingWalletTransactions(true);
|
||||
if (walletAddress.value) {
|
||||
console.log("Will fetch all required data...");
|
||||
const walletDeposits = await listValidDepositTransactionsByWalletAddress(
|
||||
walletAddress.value
|
||||
);
|
||||
console.log("Fetched deposits");
|
||||
|
||||
const allUserTransactions = await listAllTransactionByWalletAddress(
|
||||
walletAddress.value
|
||||
);
|
||||
console.log("Fetched all transactions");
|
||||
|
||||
activeLockAmount.value = await getActiveLockAmount(walletAddress.value);
|
||||
console.log("Fetched active lock amount");
|
||||
|
||||
if (walletDeposits) {
|
||||
depositList.value = walletDeposits;
|
||||
|
||||
@ -2,7 +2,6 @@
|
||||
"extends": "@vue/tsconfig/tsconfig.node.json",
|
||||
"include": [
|
||||
"vite.config.*",
|
||||
"vitest.config.*",
|
||||
"cypress.config.*",
|
||||
"playwright.config.*"
|
||||
],
|
||||
|
||||
@ -8,13 +8,13 @@
|
||||
],
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"strict": true,
|
||||
"paths": {
|
||||
"@/*": [
|
||||
"./src/*"
|
||||
]
|
||||
},
|
||||
"types": [
|
||||
"jest",
|
||||
"node"
|
||||
],
|
||||
"resolveJsonModule": true,
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { fileURLToPath, URL } from "node:url";
|
||||
|
||||
import { defineConfig } from "vitest/config";
|
||||
import { defineConfig } from "vite";
|
||||
import vue from "@vitejs/plugin-vue";
|
||||
import vueJsx from "@vitejs/plugin-vue-jsx";
|
||||
import svgLoader from "vite-svg-loader";
|
||||
@ -21,17 +21,6 @@ export default defineConfig({
|
||||
},
|
||||
},
|
||||
},
|
||||
test: {
|
||||
globals: true,
|
||||
environment: "jsdom",
|
||||
coverage: {
|
||||
provider: "c8",
|
||||
all: true,
|
||||
src: ["./src"],
|
||||
exclude: ["model/**", "**/__tests__/**"],
|
||||
reporter: ["text", "lcov", "html"],
|
||||
},
|
||||
},
|
||||
plugins: [vue(), vueJsx(), svgLoader()],
|
||||
resolve: {
|
||||
alias: {
|
||||
|
||||
11
wagmi.config.ts
Normal file
11
wagmi.config.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { defineConfig } from '@wagmi/cli'
|
||||
import { hardhat } from '@wagmi/cli/plugins'
|
||||
|
||||
export default defineConfig({
|
||||
out: 'src/blockchain/abi.ts',
|
||||
contracts: [],
|
||||
plugins: [
|
||||
hardhat({
|
||||
project: '../p2pix-smart-contracts',
|
||||
}),],
|
||||
})
|
||||
Loading…
x
Reference in New Issue
Block a user