Compare commits
20 Commits
3227e3209c
...
buy-refact
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c1542707c2 | ||
|
|
dd351acb2e | ||
|
|
2370051243 | ||
|
|
ed5d3b5726 | ||
|
|
2e246f7560 | ||
|
|
81c8b04c7a | ||
|
|
cf61f5ecfd | ||
|
|
73ba77ca4f | ||
|
|
c7b2f1643c | ||
|
|
fa2def812c | ||
|
|
8a1dab4764 | ||
|
|
75c02ed1b9 | ||
|
|
8eb10f493f | ||
|
|
1ec4780e14 | ||
|
|
0186afe971 | ||
|
|
bca93282ac | ||
|
|
fe06c46c3f | ||
|
|
4908dff58b | ||
|
|
9fa2b34a5d | ||
|
|
e93cac6086 |
16
README.md
16
README.md
@@ -102,3 +102,19 @@ cd P2Pix-Front-End
|
|||||||
# Run docker-compose up command
|
# Run docker-compose up command
|
||||||
docker-compose up
|
docker-compose up
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Backend Communication
|
||||||
|
|
||||||
|
Backend Repo: `https://gitea.kosmos.org/hueso/helpix`
|
||||||
|
|
||||||
|
Backend Endpoint: `https://api.p2pix.co/release/1279331`
|
||||||
|
|
||||||
|
curl -X POST \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-H "Authorization: Bearer {api-key}" \
|
||||||
|
-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
|
||||||
|
|
||||||
|
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" }'
|
||||||
16
package.json
16
package.json
@@ -5,12 +5,10 @@
|
|||||||
"start": "vite --host=0.0.0.0 --port 3000",
|
"start": "vite --host=0.0.0.0 --port 3000",
|
||||||
"build": "run-p type-check build-only",
|
"build": "run-p type-check build-only",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"test": "vitest",
|
|
||||||
"serve": "vue-cli-service serve",
|
"serve": "vue-cli-service serve",
|
||||||
"coverage": "vitest run --coverage",
|
|
||||||
"build-only": "vite build",
|
"build-only": "vite build",
|
||||||
"type-check": "vue-tsc --skipLibCheck --noEmit",
|
"type-check": "vue-tsc --skipLibCheck --noEmit",
|
||||||
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --ignore-path .gitignore",
|
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --ignore-path .gitignore --fix",
|
||||||
"lint:fix": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore"
|
"lint:fix": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -22,12 +20,9 @@
|
|||||||
"@web3-onboard/vue": "^2.9.0",
|
"@web3-onboard/vue": "^2.9.0",
|
||||||
"alchemy-sdk": "^2.3.0",
|
"alchemy-sdk": "^2.3.0",
|
||||||
"axios": "^1.2.1",
|
"axios": "^1.2.1",
|
||||||
"crc": "^3.8.0",
|
|
||||||
"ethers": "^6.13.4",
|
|
||||||
"marked": "^4.2.12",
|
"marked": "^4.2.12",
|
||||||
"pinia": "^2.0.23",
|
|
||||||
"qrcode": "^1.5.1",
|
"qrcode": "^1.5.1",
|
||||||
"viem": "2.x",
|
"viem": "^2.31.3",
|
||||||
"vite-svg-loader": "^5.1.0",
|
"vite-svg-loader": "^5.1.0",
|
||||||
"vue": "^3.2.41",
|
"vue": "^3.2.41",
|
||||||
"vue-markdown": "^2.2.4",
|
"vue-markdown": "^2.2.4",
|
||||||
@@ -36,32 +31,27 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@babel/preset-env": "^7.20.2",
|
"@babel/preset-env": "^7.20.2",
|
||||||
"@babel/preset-typescript": "^7.18.6",
|
"@babel/preset-typescript": "^7.18.6",
|
||||||
"@pinia/testing": "^0.0.14",
|
|
||||||
"@rushstack/eslint-patch": "^1.1.4",
|
"@rushstack/eslint-patch": "^1.1.4",
|
||||||
"@types/crc": "^3.8.0",
|
"@types/crc": "^3.8.0",
|
||||||
"@types/jest": "^27.0.0",
|
|
||||||
"@types/marked": "^4.0.8",
|
"@types/marked": "^4.0.8",
|
||||||
"@types/node": "^16.11.68",
|
"@types/node": "^16.11.68",
|
||||||
"@types/qrcode": "^1.5.0",
|
"@types/qrcode": "^1.5.0",
|
||||||
"@types/vue-markdown": "^2.2.1",
|
"@types/vue-markdown": "^2.2.1",
|
||||||
"@vitejs/plugin-vue": "^3.1.2",
|
"@vitejs/plugin-vue": "^3.1.2",
|
||||||
"@vitejs/plugin-vue-jsx": "^2.0.1",
|
"@vitejs/plugin-vue-jsx": "^2.0.1",
|
||||||
"@vitest/coverage-c8": "^0.28.2",
|
|
||||||
"@vue/eslint-config-prettier": "^7.0.0",
|
"@vue/eslint-config-prettier": "^7.0.0",
|
||||||
"@vue/eslint-config-typescript": "^11.0.0",
|
"@vue/eslint-config-typescript": "^11.0.0",
|
||||||
"@vue/test-utils": "^2.2.7",
|
|
||||||
"@vue/tsconfig": "^0.1.3",
|
"@vue/tsconfig": "^0.1.3",
|
||||||
|
"@wagmi/cli": "^2.3.1",
|
||||||
"autoprefixer": "^10.4.12",
|
"autoprefixer": "^10.4.12",
|
||||||
"eslint": "^8.22.0",
|
"eslint": "^8.22.0",
|
||||||
"eslint-plugin-vue": "^9.3.0",
|
"eslint-plugin-vue": "^9.3.0",
|
||||||
"jsdom": "^21.1.0",
|
|
||||||
"npm-run-all": "^4.1.5",
|
"npm-run-all": "^4.1.5",
|
||||||
"postcss": "^8.4.18",
|
"postcss": "^8.4.18",
|
||||||
"prettier": "^2.7.1",
|
"prettier": "^2.7.1",
|
||||||
"tailwindcss": "^3.2.1",
|
"tailwindcss": "^3.2.1",
|
||||||
"typescript": "~5.8.2",
|
"typescript": "~5.8.2",
|
||||||
"vite": "^3.1.8",
|
"vite": "^3.1.8",
|
||||||
"vitest": "^0.28.1",
|
|
||||||
"vue-tsc": "^2.2.8"
|
"vue-tsc": "^2.2.8"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,13 +2,16 @@
|
|||||||
import { useRoute } from "vue-router";
|
import { useRoute } from "vue-router";
|
||||||
import TopBar from "@/components/TopBar/TopBar.vue";
|
import TopBar from "@/components/TopBar/TopBar.vue";
|
||||||
import SpinnerComponent from "@/components/SpinnerComponent.vue";
|
import SpinnerComponent from "@/components/SpinnerComponent.vue";
|
||||||
|
import ToasterComponent from "@/components/ToasterComponent.vue";
|
||||||
import { init, useOnboard } from "@web3-onboard/vue";
|
import { init, useOnboard } from "@web3-onboard/vue";
|
||||||
import injectedModule from "@web3-onboard/injected-wallets";
|
import injectedModule from "@web3-onboard/injected-wallets";
|
||||||
import { Networks } from "./model/Networks";
|
import { Networks } from "./model/Networks";
|
||||||
import { NetworkEnum } from "./model/NetworkEnum";
|
import { NetworkEnum } from "./model/NetworkEnum";
|
||||||
|
import { ref } from "vue";
|
||||||
|
|
||||||
const route = useRoute();
|
const route = useRoute();
|
||||||
const injected = injectedModule();
|
const injected = injectedModule();
|
||||||
|
const targetNetwork = ref(NetworkEnum.sepolia);
|
||||||
|
|
||||||
const web3Onboard = init({
|
const web3Onboard = init({
|
||||||
wallets: [injected],
|
wallets: [injected],
|
||||||
@@ -58,5 +61,6 @@ if (!connectedWallet) {
|
|||||||
</Transition>
|
</Transition>
|
||||||
</template>
|
</template>
|
||||||
</RouterView>
|
</RouterView>
|
||||||
|
<ToasterComponent :targetNetwork="targetNetwork" />
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -28,3 +28,9 @@ a,
|
|||||||
.main-container {
|
.main-container {
|
||||||
@apply flex w-full md:max-w-lg flex-col justify-center items-center px-4 sm:px-8 py-4 sm:py-6 gap-4 rounded-lg border border-gray-500 backdrop-blur-md drop-shadow-lg shadow-lg mt-10;
|
@apply flex w-full md:max-w-lg flex-col justify-center items-center px-4 sm:px-8 py-4 sm:py-6 gap-4 rounded-lg border border-gray-500 backdrop-blur-md drop-shadow-lg shadow-lg mt-10;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
input[type="number"] {
|
||||||
|
appearance: textfield;
|
||||||
|
-webkit-appearance: textfield;
|
||||||
|
-moz-appearance: textfield;
|
||||||
|
}
|
||||||
@@ -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 { useEtherStore } from "@/store/ether";
|
|
||||||
|
|
||||||
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 etherStore = useEtherStore();
|
|
||||||
etherStore.setNetworkId(NetworkEnum.sepolia);
|
|
||||||
expect(getTokenAddress(TokenEnum.BRZ)).toBe(
|
|
||||||
"0x4A2886EAEc931e04297ed336Cc55c4eb7C75BA00"
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("getTokenAddress Rootstock", () => {
|
|
||||||
const etherStore = useEtherStore();
|
|
||||||
etherStore.setNetworkId(NetworkEnum.rootstock);
|
|
||||||
expect(getTokenAddress(TokenEnum.BRZ)).toBe(
|
|
||||||
"0xfE841c74250e57640390f46d914C88d22C51e82e"
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("getTokenAddress Default", () => {
|
|
||||||
expect(getTokenAddress(TokenEnum.BRZ)).toBe(
|
|
||||||
"0x4A2886EAEc931e04297ed336Cc55c4eb7C75BA00"
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("getP2PixAddress Ethereum", () => {
|
|
||||||
const etherStore = useEtherStore();
|
|
||||||
etherStore.setNetworkId(NetworkEnum.sepolia);
|
|
||||||
expect(getP2PixAddress()).toBe(
|
|
||||||
"0x2414817FF64A114d91eCFA16a834d3fCf69103d4"
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("getP2PixAddress Rootstock", () => {
|
|
||||||
const etherStore = useEtherStore();
|
|
||||||
etherStore.setNetworkId(NetworkEnum.rootstock);
|
|
||||||
expect(getP2PixAddress()).toBe(
|
|
||||||
"0x98ba35eb14b38D6Aa709338283af3e922476dE34"
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("getP2PixAddress Default", () => {
|
|
||||||
expect(getP2PixAddress()).toBe(
|
|
||||||
"0x2414817FF64A114d91eCFA16a834d3fCf69103d4"
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("getProviderUrl Ethereum", () => {
|
|
||||||
const etherStore = useEtherStore();
|
|
||||||
etherStore.setNetworkId(NetworkEnum.sepolia);
|
|
||||||
expect(getProviderUrl()).toBe(import.meta.env.VITE_GOERLI_API_URL);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("getProviderUrl Rootstock", () => {
|
|
||||||
const etherStore = useEtherStore();
|
|
||||||
etherStore.setNetworkId(NetworkEnum.rootstock);
|
|
||||||
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 etherStore = useEtherStore();
|
|
||||||
etherStore.setNetworkId(NetworkEnum.sepolia);
|
|
||||||
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,8 +1,9 @@
|
|||||||
import { useEtherStore } from "@/store/ether";
|
import { useUser } from "@/composables/useUser";
|
||||||
import { NetworkEnum, TokenEnum } from "@/model/NetworkEnum";
|
import { NetworkEnum, TokenEnum } from "@/model/NetworkEnum";
|
||||||
import { JsonRpcProvider } from "ethers";
|
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]: {
|
[NetworkEnum.sepolia]: {
|
||||||
BRZ: "0x3eBE67A2C7bdB2081CBd34ba3281E90377462289",
|
BRZ: "0x3eBE67A2C7bdB2081CBd34ba3281E90377462289",
|
||||||
// BRX: "0x3eBE67A2C7bdB2081CBd34ba3281E90377462289",
|
// BRX: "0x3eBE67A2C7bdB2081CBd34ba3281E90377462289",
|
||||||
@@ -13,58 +14,57 @@ const Tokens: { [key in NetworkEnum]: { [key in TokenEnum]: string } } = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getTokenByAddress = (address: string) => {
|
export const getTokenByAddress = (address: Address) => {
|
||||||
for (const network of Object.values(NetworkEnum).filter(
|
const user = useUser();
|
||||||
(v) => !isNaN(Number(v))
|
const networksTokens = Tokens[user.networkName.value];
|
||||||
)) {
|
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
|
||||||
|
): Address => {
|
||||||
|
const user = useUser();
|
||||||
|
return Tokens[network ? network : user.networkName.value][
|
||||||
|
token
|
||||||
|
];
|
||||||
};
|
};
|
||||||
|
|
||||||
const getP2PixAddress = (network?: NetworkEnum): string => {
|
export const getP2PixAddress = (network?: NetworkEnum): Address => {
|
||||||
const etherStore = useEtherStore();
|
const user = useUser();
|
||||||
const possibleP2PixAddresses: { [key in NetworkEnum]: string } = {
|
const possibleP2PixAddresses: { [key in NetworkEnum]: Address } = {
|
||||||
[NetworkEnum.sepolia]: "0xb7cD135F5eFD9760981e02E2a898790b688939fe",
|
[NetworkEnum.sepolia]: "0xb7cD135F5eFD9760981e02E2a898790b688939fe",
|
||||||
[NetworkEnum.rootstock]: "0x98ba35eb14b38D6Aa709338283af3e922476dE34",
|
[NetworkEnum.rootstock]: "0x98ba35eb14b38D6Aa709338283af3e922476dE34",
|
||||||
};
|
};
|
||||||
|
|
||||||
return possibleP2PixAddresses[network ? network : etherStore.networkName];
|
return possibleP2PixAddresses[
|
||||||
|
network ? network : user.networkName.value
|
||||||
|
];
|
||||||
};
|
};
|
||||||
|
|
||||||
const getProviderUrl = (network?: NetworkEnum): string => {
|
export const getProviderUrl = (network?: NetworkEnum): string => {
|
||||||
const etherStore = useEtherStore();
|
const user = useUser();
|
||||||
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 || user.networkName.value];
|
||||||
};
|
};
|
||||||
|
|
||||||
const getProviderByNetwork = (network: NetworkEnum): JsonRpcProvider => {
|
export const getProviderByNetwork = (network: NetworkEnum) => {
|
||||||
console.log("network", network);
|
const chain = network === NetworkEnum.sepolia ? sepolia : rootstock;
|
||||||
return new JsonRpcProvider(getProviderUrl(network), network);
|
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,94 +1,95 @@
|
|||||||
import { getContract, getProvider } from "./provider";
|
import { getContract } from "./provider";
|
||||||
import { getP2PixAddress, getTokenAddress } from "./addresses";
|
import { getTokenAddress } from "./addresses";
|
||||||
import { encodeBytes32String, Signature, Contract, parseEther } from "ethers";
|
import {
|
||||||
|
bytesToHex,
|
||||||
import p2pix from "@/utils/smart_contract_files/P2PIX.json";
|
encodeAbiParameters,
|
||||||
|
keccak256,
|
||||||
|
parseAbiParameters,
|
||||||
|
parseEther,
|
||||||
|
stringToBytes,
|
||||||
|
stringToHex,
|
||||||
|
toBytes,
|
||||||
|
type Address,
|
||||||
|
} from "viem";
|
||||||
import type { TokenEnum } from "@/model/NetworkEnum";
|
import type { TokenEnum } from "@/model/NetworkEnum";
|
||||||
import { createSolicitation } from "../utils/bbPay";
|
|
||||||
import type { Offer } from "../utils/bbPay";
|
|
||||||
|
|
||||||
const addLock = async (
|
export const addLock = async (
|
||||||
sellerId: string,
|
sellerAddress: Address,
|
||||||
token: string,
|
tokenAddress: Address,
|
||||||
amount: number
|
amount: number
|
||||||
): Promise<string> => {
|
): Promise<bigint> => {
|
||||||
const p2pContract = await getContract();
|
const { address, abi, wallet, client, account } = await getContract();
|
||||||
|
const parsedAmount = parseEther(amount.toString());
|
||||||
|
|
||||||
const lock = await p2pContract.lock(
|
if (!wallet) {
|
||||||
sellerId,
|
throw new Error("Wallet not connected");
|
||||||
token,
|
}
|
||||||
parseEther(String(amount)), // BigNumber
|
|
||||||
[],
|
|
||||||
[]
|
|
||||||
);
|
|
||||||
|
|
||||||
const lock_rec = await lock.wait();
|
const { result, request } = await client.simulateContract({
|
||||||
const [t] = lock_rec.events;
|
address,
|
||||||
|
abi,
|
||||||
|
functionName: "lock",
|
||||||
|
args: [sellerAddress, tokenAddress, parsedAmount, [], []],
|
||||||
|
account,
|
||||||
|
});
|
||||||
|
const hash = await wallet.writeContract(request);
|
||||||
|
const receipt = await client.waitForTransactionReceipt({ hash });
|
||||||
|
|
||||||
const offer: Offer = {
|
if (!receipt.status)
|
||||||
amount,
|
throw new Error("Transaction failed: " + receipt.transactionHash);
|
||||||
lockId: String(t.args.lockID),
|
|
||||||
sellerId: sellerId,
|
|
||||||
};
|
|
||||||
const solicitation = await createSolicitation(offer);
|
|
||||||
|
|
||||||
return;
|
return result;
|
||||||
};
|
};
|
||||||
|
|
||||||
const releaseLock = async (solicitation: any): Promise<any> => {
|
export const withdrawDeposit = async (
|
||||||
// const mockBacenSigner = new Wallet(
|
|
||||||
// "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"
|
|
||||||
// );
|
|
||||||
|
|
||||||
// const messageToSign = solidityPackedKeccak256(
|
|
||||||
// ["bytes32", "uint256", "bytes32"],
|
|
||||||
// [sellerId, parseEther(String(amount)), encodeBytes32String(signature)]
|
|
||||||
// );
|
|
||||||
|
|
||||||
// const messageHashBytes = getBytes(messageToSign);
|
|
||||||
// const flatSig = await mockBacenSigner.signMessage(messageHashBytes);
|
|
||||||
|
|
||||||
const provider = getProvider();
|
|
||||||
|
|
||||||
const sig = Signature.from(flatSig);
|
|
||||||
console.log(sig);
|
|
||||||
const signer = await provider.getSigner();
|
|
||||||
const p2pContract = new Contract(getP2PixAddress(), p2pix.abi, signer);
|
|
||||||
|
|
||||||
const release = await p2pContract.release(
|
|
||||||
BigInt(lockId),
|
|
||||||
encodeBytes32String(e2eId),
|
|
||||||
flatSig
|
|
||||||
);
|
|
||||||
await release.wait();
|
|
||||||
|
|
||||||
return release;
|
|
||||||
};
|
|
||||||
|
|
||||||
const cancelDeposit = async (depositId: bigint): Promise<any> => {
|
|
||||||
const contract = await getContract();
|
|
||||||
|
|
||||||
const cancel = await contract.cancelDeposit(depositId);
|
|
||||||
await cancel.wait();
|
|
||||||
|
|
||||||
return cancel;
|
|
||||||
};
|
|
||||||
|
|
||||||
const withdrawDeposit = async (
|
|
||||||
amount: string,
|
amount: string,
|
||||||
token: TokenEnum
|
token: TokenEnum
|
||||||
): Promise<any> => {
|
): Promise<boolean> => {
|
||||||
const contract = await getContract();
|
const { address, abi, wallet, client, account } = await getContract();
|
||||||
|
|
||||||
const withdraw = await contract.withdraw(
|
if (!wallet) {
|
||||||
getTokenAddress(token),
|
throw new Error("Wallet not connected");
|
||||||
parseEther(String(amount)),
|
}
|
||||||
[]
|
|
||||||
);
|
|
||||||
await withdraw.wait();
|
|
||||||
|
|
||||||
return withdraw;
|
const tokenAddress = getTokenAddress(token);
|
||||||
|
|
||||||
|
const { request } = await client.simulateContract({
|
||||||
|
address,
|
||||||
|
abi,
|
||||||
|
functionName: "withdraw",
|
||||||
|
args: [tokenAddress, parseEther(amount), []],
|
||||||
|
account
|
||||||
|
});
|
||||||
|
|
||||||
|
const hash = await wallet.writeContract(request);
|
||||||
|
const receipt = await client.waitForTransactionReceipt({ hash });
|
||||||
|
|
||||||
|
return receipt.status === "success";
|
||||||
};
|
};
|
||||||
|
|
||||||
export { cancelDeposit, withdrawDeposit, addLock, releaseLock };
|
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: [BigInt(lockID), pixTimestamp, stringToHex(signature)],
|
||||||
|
account
|
||||||
|
});
|
||||||
|
|
||||||
|
const hash = await wallet.writeContract(request);
|
||||||
|
return client.waitForTransactionReceipt({ hash });
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,55 +1,59 @@
|
|||||||
import { useEtherStore } from "@/store/ether";
|
import { useUser } from "@/composables/useUser";
|
||||||
import { Contract, formatEther, Interface } from "ethers";
|
import { formatEther, toHex, stringToHex } from "viem";
|
||||||
|
import type { PublicClient, Address } from "viem";
|
||||||
|
|
||||||
import p2pix from "@/utils/smart_contract_files/P2PIX.json";
|
|
||||||
import { getContract } from "./provider";
|
import { getContract } from "./provider";
|
||||||
|
import { getP2PixAddress, getTokenAddress } from "./addresses";
|
||||||
|
import { p2PixAbi } from "./abi"
|
||||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||||
import {
|
import { getNetworkSubgraphURL, NetworkEnum, TokenEnum } from "@/model/NetworkEnum";
|
||||||
getP2PixAddress,
|
|
||||||
getProviderByNetwork,
|
|
||||||
getTokenAddress,
|
|
||||||
} from "./addresses";
|
|
||||||
import { NetworkEnum } from "@/model/NetworkEnum";
|
|
||||||
import type { UnreleasedLock } from "@/model/UnreleasedLock";
|
import type { UnreleasedLock } from "@/model/UnreleasedLock";
|
||||||
import type { Pix } from "@/model/Pix";
|
import type { LockStatus } from "@/model/LockStatus"
|
||||||
|
|
||||||
const getNetworksLiquidity = async (): Promise<void> => {
|
const getNetworksLiquidity = async (): Promise<void> => {
|
||||||
const etherStore = useEtherStore();
|
const user = useUser();
|
||||||
etherStore.setLoadingNetworkLiquidity(true);
|
user.setLoadingNetworkLiquidity(true);
|
||||||
|
|
||||||
const depositLists: ValidDeposit[][] = [];
|
const depositLists: ValidDeposit[][] = [];
|
||||||
|
|
||||||
for (const network of Object.values(NetworkEnum).filter(
|
for (const network of Object.values(NetworkEnum).filter(
|
||||||
(v) => !isNaN(Number(v))
|
(v) => !isNaN(Number(v))
|
||||||
)) {
|
)) {
|
||||||
console.log("getNetworksLiquidity", network);
|
const deposits = await getValidDeposits(
|
||||||
const p2pContract = new Contract(
|
getTokenAddress(user.selectedToken.value),
|
||||||
getP2PixAddress(network as NetworkEnum),
|
Number(network)
|
||||||
p2pix.abi,
|
|
||||||
getProviderByNetwork(network as NetworkEnum)
|
|
||||||
);
|
|
||||||
|
|
||||||
depositLists.push(
|
|
||||||
await getValidDeposits(
|
|
||||||
getTokenAddress(etherStore.selectedToken, network as NetworkEnum),
|
|
||||||
network as NetworkEnum,
|
|
||||||
p2pContract
|
|
||||||
)
|
|
||||||
);
|
);
|
||||||
|
if (deposits) depositLists.push(deposits);
|
||||||
}
|
}
|
||||||
|
|
||||||
etherStore.setDepositsValidList(depositLists.flat());
|
const allDeposits = depositLists.flat();
|
||||||
etherStore.setLoadingNetworkLiquidity(false);
|
user.setDepositsValidList(allDeposits);
|
||||||
|
user.setLoadingNetworkLiquidity(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
const getPixKey = async (seller: string, token: string): Promise<string> => {
|
const getParticipantID = async (
|
||||||
const p2pContract = await getContract();
|
seller: string,
|
||||||
const pixKeyHex = await p2pContract.getPixTarget(seller, token);
|
token: string
|
||||||
|
): Promise<string> => {
|
||||||
|
const { address, abi, client } = await getContract();
|
||||||
|
|
||||||
|
const participantIDHex = 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 participantIDHex === "string"
|
||||||
|
? participantIDHex
|
||||||
|
: toHex(participantIDHex as bigint);
|
||||||
|
if (!hexString) throw new Error("Participant ID not found");
|
||||||
const bytes = new Uint8Array(
|
const bytes = new Uint8Array(
|
||||||
pixKeyHex
|
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))
|
||||||
);
|
);
|
||||||
// Remove null bytes from the end of the string
|
// Remove null bytes from the end of the string
|
||||||
@@ -57,75 +61,110 @@ const getPixKey = async (seller: string, token: string): Promise<string> => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const getValidDeposits = async (
|
const getValidDeposits = async (
|
||||||
token: string,
|
token: Address,
|
||||||
network: NetworkEnum,
|
network: NetworkEnum,
|
||||||
contract?: Contract
|
contractInfo?: { client: PublicClient; address: Address }
|
||||||
): Promise<ValidDeposit[]> => {
|
): Promise<ValidDeposit[]> => {
|
||||||
let p2pContract: Contract;
|
let client: PublicClient, abi;
|
||||||
|
|
||||||
if (contract) {
|
if (contractInfo) {
|
||||||
p2pContract = contract;
|
({ client } = contractInfo);
|
||||||
|
abi = p2PixAbi;
|
||||||
} else {
|
} else {
|
||||||
p2pContract = await getContract(true);
|
({ abi, client } = await getContract(true));
|
||||||
}
|
}
|
||||||
|
|
||||||
const filterDeposits = p2pContract.filters.DepositAdded(null);
|
// TODO: Remove this once we have a subgraph for rootstock
|
||||||
const eventsDeposits = await p2pContract.queryFilter(
|
if (network === NetworkEnum.rootstock) return [];
|
||||||
filterDeposits
|
|
||||||
// 0,
|
const body = {
|
||||||
// "latest"
|
query: `
|
||||||
|
{
|
||||||
|
depositAddeds(where: { token: "${token}" }) {
|
||||||
|
seller
|
||||||
|
amount
|
||||||
|
blockTimestamp
|
||||||
|
blockNumber
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
};
|
||||||
|
|
||||||
|
const depositLogs = await fetch(getNetworkSubgraphURL(network), {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
|
||||||
|
// remove doubles from sellers list
|
||||||
|
const depositData = await depositLogs.json();
|
||||||
|
const depositAddeds = depositData.data.depositAddeds;
|
||||||
|
const uniqueSellers = depositAddeds.reduce(
|
||||||
|
(acc: Record<Address, boolean>, deposit: any) => {
|
||||||
|
acc[deposit.seller] = true;
|
||||||
|
return acc;
|
||||||
|
},
|
||||||
|
{} as Record<Address, boolean>
|
||||||
);
|
);
|
||||||
if (!contract) p2pContract = await getContract(); // get metamask provider contract
|
|
||||||
|
if (!contractInfo) {
|
||||||
|
// Get metamask provider contract
|
||||||
|
({ abi, client } = await getContract(true));
|
||||||
|
}
|
||||||
|
|
||||||
const depositList: { [key: string]: ValidDeposit } = {};
|
const depositList: { [key: string]: ValidDeposit } = {};
|
||||||
|
|
||||||
for (const deposit of eventsDeposits) {
|
const sellersList = Object.keys(uniqueSellers) as Address[];
|
||||||
const IPix2Pix = new Interface(p2pix.abi);
|
// Use multicall to batch all getBalance requests
|
||||||
const decoded = IPix2Pix.parseLog({
|
const balanceCalls = sellersList.map((seller) => ({
|
||||||
topics: deposit.topics,
|
address: getP2PixAddress(network),
|
||||||
data: deposit.data,
|
abi,
|
||||||
});
|
functionName: "getBalance",
|
||||||
// Get liquidity only for the selected token
|
args: [seller, token],
|
||||||
if (decoded?.args.token != token) continue;
|
}));
|
||||||
const mappedBalance = await p2pContract.getBalance(
|
|
||||||
decoded.args.seller,
|
|
||||||
token
|
|
||||||
);
|
|
||||||
let validDeposit: ValidDeposit | null = null;
|
|
||||||
|
|
||||||
if (mappedBalance) {
|
const balanceResults = await client.multicall({
|
||||||
validDeposit = {
|
contracts: balanceCalls as any,
|
||||||
token: token,
|
});
|
||||||
blockNumber: deposit.blockNumber,
|
|
||||||
remaining: Number(formatEther(mappedBalance)),
|
// Process results into the depositList
|
||||||
seller: decoded.args.seller,
|
sellersList.forEach((seller, index) => {
|
||||||
|
const mappedBalance = balanceResults[index];
|
||||||
|
|
||||||
|
if (!mappedBalance.error && mappedBalance.result) {
|
||||||
|
const validDeposit: ValidDeposit = {
|
||||||
|
token,
|
||||||
|
blockNumber: 0,
|
||||||
|
remaining: Number(formatEther(mappedBalance.result as bigint)),
|
||||||
|
seller,
|
||||||
network,
|
network,
|
||||||
pixKey: "",
|
participantID: "",
|
||||||
};
|
};
|
||||||
|
depositList[seller + token] = validDeposit;
|
||||||
}
|
}
|
||||||
if (validDeposit) depositList[decoded.args.seller + token] = validDeposit;
|
});
|
||||||
}
|
|
||||||
|
|
||||||
return Object.values(depositList);
|
return Object.values(depositList);
|
||||||
};
|
};
|
||||||
|
|
||||||
const getUnreleasedLockById = async (
|
const getUnreleasedLockById = async (
|
||||||
lockID: string
|
lockID: bigint
|
||||||
): Promise<UnreleasedLock> => {
|
): Promise<UnreleasedLock> => {
|
||||||
const p2pContract = await getContract();
|
const { address, abi, client } = await getContract();
|
||||||
const pixData: Pix = {
|
|
||||||
pixKey: "",
|
|
||||||
};
|
|
||||||
|
|
||||||
const lock = await p2pContract.mapLocks(lockID);
|
const [ , , , amount, token, seller ] = await client.readContract({
|
||||||
|
address,
|
||||||
const pixTarget = lock.pixTarget;
|
abi,
|
||||||
const amount = formatEther(lock?.amount);
|
functionName: "mapLocks",
|
||||||
pixData.pixKey = pixTarget;
|
args: [lockID],
|
||||||
pixData.value = Number(amount);
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
lockID: lockID,
|
lockID,
|
||||||
pix: pixData,
|
amount: Number(formatEther(amount)),
|
||||||
|
tokenAddress: token,
|
||||||
|
sellerAddress: seller,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -133,5 +172,5 @@ export {
|
|||||||
getValidDeposits,
|
getValidDeposits,
|
||||||
getNetworksLiquidity,
|
getNetworksLiquidity,
|
||||||
getUnreleasedLockById,
|
getUnreleasedLockById,
|
||||||
getPixKey,
|
getParticipantID,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,27 +1,62 @@
|
|||||||
import p2pix from "@/utils/smart_contract_files/P2PIX.json";
|
import { p2PixAbi } from "./abi";
|
||||||
import { updateWalletStatus } from "./wallet";
|
import { updateWalletStatus } from "./wallet";
|
||||||
import { getProviderUrl, getP2PixAddress } from "./addresses";
|
import { getProviderUrl, getP2PixAddress } from "./addresses";
|
||||||
import { BrowserProvider, JsonRpcProvider, Contract } from "ethers";
|
import {
|
||||||
|
createPublicClient,
|
||||||
|
createWalletClient,
|
||||||
|
custom,
|
||||||
|
http,
|
||||||
|
PublicClient,
|
||||||
|
WalletClient,
|
||||||
|
} from "viem";
|
||||||
|
import { sepolia, rootstock } from "viem/chains";
|
||||||
|
import { useUser } from "@/composables/useUser";
|
||||||
|
|
||||||
let provider: BrowserProvider | JsonRpcProvider | null = null;
|
let walletClient: WalletClient | null = null;
|
||||||
|
|
||||||
const getProvider = (onlyAlchemyProvider: boolean = false) => {
|
const getPublicClient = (): PublicClient => {
|
||||||
if (onlyAlchemyProvider) return new JsonRpcProvider(getProviderUrl()); // alchemy provider
|
const user = useUser();
|
||||||
return provider;
|
const rpcUrl = getProviderUrl();
|
||||||
|
return createPublicClient({
|
||||||
|
chain:
|
||||||
|
Number(user.networkName.value) === sepolia.id ? sepolia : rootstock,
|
||||||
|
transport: http(rpcUrl),
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const getContract = async (onlyAlchemyProvider: boolean = false) => {
|
const getWalletClient = (): WalletClient | null => {
|
||||||
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();
|
||||||
return new Contract(getP2PixAddress(), p2pix.abi, p);
|
const address = getP2PixAddress();
|
||||||
|
const abi = p2PixAbi;
|
||||||
|
const wallet = onlyRpcProvider ? null : getWalletClient();
|
||||||
|
|
||||||
|
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> => {
|
const connectProvider = async (p: any): Promise<void> => {
|
||||||
provider = new BrowserProvider(p, "any");
|
const user = useUser();
|
||||||
|
const chain =
|
||||||
|
Number(user.networkName.value) === sepolia.id ? sepolia : rootstock;
|
||||||
|
|
||||||
|
const [account] = await p!.request({ method: "eth_requestAccounts" });
|
||||||
|
|
||||||
|
walletClient = createWalletClient({
|
||||||
|
account,
|
||||||
|
chain,
|
||||||
|
transport: custom(p),
|
||||||
|
});
|
||||||
|
|
||||||
await updateWalletStatus();
|
await updateWalletStatus();
|
||||||
};
|
};
|
||||||
export { getProvider, getContract, connectProvider };
|
|
||||||
|
export { getPublicClient, getWalletClient, getContract, connectProvider };
|
||||||
|
|||||||
@@ -1,60 +1,88 @@
|
|||||||
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 { sepolia, rootstock } from "viem/chains";
|
||||||
|
|
||||||
import { encodeBytes32String, Contract, parseEther } from "ethers";
|
import { mockTokenAbi } from "./abi";
|
||||||
|
import { useUser } from "@/composables/useUser";
|
||||||
import mockToken from "../utils/smart_contract_files/MockToken.json";
|
|
||||||
import { useEtherStore } from "@/store/ether";
|
|
||||||
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 user = useUser();
|
||||||
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
|
user.setSeller(participant);
|
||||||
);
|
const [account] = await walletClient.getAddresses();
|
||||||
|
|
||||||
|
// Get token address
|
||||||
|
const tokenAddress = getTokenAddress(user.selectedToken.value);
|
||||||
|
|
||||||
// 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: mockTokenAbi,
|
||||||
);
|
functionName: "allowance",
|
||||||
if (approved < parseEther(participant.offer)) {
|
args: [account, getP2PixAddress()],
|
||||||
|
});
|
||||||
|
|
||||||
|
if ( allowance < parseEther(participant.offer.toString()) ) {
|
||||||
// Approve tokens
|
// Approve tokens
|
||||||
const apprv = await tokenContract.approve(
|
const chain = user.networkId.value === sepolia.id ? sepolia : rootstock;
|
||||||
getP2PixAddress(),
|
const hash = await walletClient.writeContract({
|
||||||
parseEther(participant.offer)
|
address: tokenAddress,
|
||||||
);
|
abi: mockTokenAbi,
|
||||||
await apprv.wait();
|
functionName: "approve",
|
||||||
|
args: [getP2PixAddress(), parseEther(participant.offer.toString())],
|
||||||
|
account,
|
||||||
|
chain,
|
||||||
|
});
|
||||||
|
|
||||||
|
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 user = useUser();
|
||||||
|
|
||||||
const sellerId = await createParticipant(etherStore.seller);
|
if (!walletClient) {
|
||||||
etherStore.setSellerId(sellerId.id);
|
throw new Error("Wallet client not initialized");
|
||||||
|
}
|
||||||
|
|
||||||
const deposit = await p2pContract.deposit(
|
const [account] = await walletClient.getAddresses();
|
||||||
sellerId,
|
|
||||||
encodeBytes32String(""),
|
|
||||||
getTokenAddress(etherStore.selectedToken),
|
|
||||||
parseEther(etherStore.seller.offer),
|
|
||||||
true
|
|
||||||
);
|
|
||||||
|
|
||||||
await deposit.wait();
|
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.value + "-" + sellerId.id,
|
||||||
|
toHex("", { size: 32 }),
|
||||||
|
getTokenAddress(user.selectedToken.value),
|
||||||
|
parseEther(user.seller.value.offer.toString()),
|
||||||
|
true,
|
||||||
|
],
|
||||||
|
account,
|
||||||
|
chain,
|
||||||
|
});
|
||||||
|
|
||||||
return deposit;
|
const receipt = await client.waitForTransactionReceipt({ hash });
|
||||||
|
return receipt;
|
||||||
};
|
};
|
||||||
|
|
||||||
export { approveTokens, addDeposit };
|
export { approveTokens, addDeposit };
|
||||||
|
|||||||
@@ -1,64 +1,48 @@
|
|||||||
import {
|
import { formatEther, hexToString, type Address } from "viem";
|
||||||
Contract,
|
import { useUser } from "@/composables/useUser";
|
||||||
formatEther,
|
|
||||||
getAddress,
|
|
||||||
Interface,
|
|
||||||
Log,
|
|
||||||
LogDescription,
|
|
||||||
} from "ethers";
|
|
||||||
import { useEtherStore } from "@/store/ether";
|
|
||||||
|
|
||||||
import { getContract, getProvider } from "./provider";
|
import { getPublicClient, getWalletClient, getContract } from "./provider";
|
||||||
import { getTokenAddress, isPossibleNetwork } from "./addresses";
|
import { getTokenAddress } from "./addresses";
|
||||||
|
|
||||||
import mockToken from "@/utils/smart_contract_files/MockToken.json";
|
import { getValidDeposits, getUnreleasedLockById } from "./events";
|
||||||
import p2pix from "@/utils/smart_contract_files/P2PIX.json";
|
|
||||||
|
|
||||||
import { getValidDeposits } from "./events";
|
|
||||||
|
|
||||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||||
import type { WalletTransaction } from "@/model/WalletTransaction";
|
import type { WalletTransaction } from "@/model/WalletTransaction";
|
||||||
import type { UnreleasedLock } from "@/model/UnreleasedLock";
|
import type { UnreleasedLock } from "@/model/UnreleasedLock";
|
||||||
import type { Pix } from "@/model/Pix";
|
import { LockStatus } from "@/model/LockStatus";
|
||||||
|
import { getNetworkSubgraphURL } from "@/model/NetworkEnum";
|
||||||
|
|
||||||
export const updateWalletStatus = async (): Promise<void> => {
|
export const updateWalletStatus = async (): Promise<void> => {
|
||||||
const etherStore = useEtherStore();
|
const user = useUser();
|
||||||
|
|
||||||
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) {
|
||||||
if (!isPossibleNetwork(Number(chainId))) {
|
console.error("Client not initialized");
|
||||||
window.alert("Invalid chain!:" + chainId);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
etherStore.setNetworkId(Number(chainId));
|
|
||||||
|
|
||||||
const mockTokenContract = new Contract(
|
// Get balance
|
||||||
getTokenAddress(etherStore.selectedToken),
|
const [account] = await walletClient.getAddresses();
|
||||||
mockToken.abi,
|
const balance = await publicClient.getBalance({ address: account });
|
||||||
signer
|
|
||||||
);
|
|
||||||
|
|
||||||
const walletAddress = await provider?.send("eth_requestAccounts", []);
|
user.setWalletAddress(account);
|
||||||
const balance = await mockTokenContract.balanceOf(walletAddress[0]);
|
user.setBalance(formatEther(balance));
|
||||||
|
|
||||||
etherStore.setBalance(formatEther(balance));
|
|
||||||
etherStore.setWalletAddress(getAddress(walletAddress[0]));
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const listValidDepositTransactionsByWalletAddress = async (
|
export const listValidDepositTransactionsByWalletAddress = async (
|
||||||
walletAddress: string
|
walletAddress: Address
|
||||||
): Promise<ValidDeposit[]> => {
|
): Promise<ValidDeposit[]> => {
|
||||||
const etherStore = useEtherStore();
|
const user = useUser();
|
||||||
const walletDeposits = await getValidDeposits(
|
const walletDeposits = await getValidDeposits(
|
||||||
getTokenAddress(etherStore.selectedToken),
|
getTokenAddress(user.selectedToken.value),
|
||||||
etherStore.networkName
|
user.networkName.value
|
||||||
);
|
);
|
||||||
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,235 +50,431 @@ export const listValidDepositTransactionsByWalletAddress = async (
|
|||||||
return [];
|
return [];
|
||||||
};
|
};
|
||||||
|
|
||||||
const getLockStatus = async (id: [BigInt]): Promise<number> => {
|
const getLockStatus = async (id: bigint): Promise<LockStatus> => {
|
||||||
const p2pContract = await getContract();
|
const { address, abi, client } = await getContract();
|
||||||
const res = await p2pContract.getLocksStatus([id]);
|
const [ sortedIDs , status ] = await client.readContract({
|
||||||
return res[1][0];
|
address,
|
||||||
};
|
abi,
|
||||||
|
functionName: "getLocksStatus",
|
||||||
const filterLockStatus = async (
|
args: [[id]],
|
||||||
transactions: Log[]
|
});
|
||||||
): Promise<WalletTransaction[]> => {
|
return status[0];
|
||||||
const txs: WalletTransaction[] = [];
|
|
||||||
|
|
||||||
for (const transaction of transactions) {
|
|
||||||
const IPix2Pix = new Interface(p2pix.abi);
|
|
||||||
const decoded = IPix2Pix.parseLog({
|
|
||||||
topics: transaction.topics,
|
|
||||||
data: transaction.data,
|
|
||||||
});
|
|
||||||
if (!decoded) continue;
|
|
||||||
const tx: WalletTransaction = {
|
|
||||||
token: decoded.args.token ? decoded.args.token : "",
|
|
||||||
blockNumber: transaction.blockNumber,
|
|
||||||
amount: decoded.args.amount
|
|
||||||
? Number(formatEther(decoded.args.amount))
|
|
||||||
: -1,
|
|
||||||
seller: decoded.args.seller ? decoded.args.seller : "",
|
|
||||||
buyer: decoded.args.buyer ? decoded.args.buyer : "",
|
|
||||||
event: decoded.name,
|
|
||||||
lockStatus:
|
|
||||||
decoded.name == "LockAdded"
|
|
||||||
? await getLockStatus(decoded.args.lockID)
|
|
||||||
: -1,
|
|
||||||
transactionHash: transaction.transactionHash
|
|
||||||
? transaction.transactionHash
|
|
||||||
: "",
|
|
||||||
transactionID: decoded.args.lockID ? decoded.args.lockID.toString() : "",
|
|
||||||
};
|
|
||||||
txs.push(tx);
|
|
||||||
}
|
|
||||||
return txs;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const listAllTransactionByWalletAddress = async (
|
export const listAllTransactionByWalletAddress = async (
|
||||||
walletAddress: string
|
walletAddress: Address
|
||||||
): Promise<WalletTransaction[]> => {
|
): Promise<WalletTransaction[]> => {
|
||||||
const p2pContract = await getContract(true);
|
const user = useUser();
|
||||||
|
|
||||||
// Get deposits
|
// Get the current network for the subgraph URL
|
||||||
const filterDeposits = p2pContract.filters.DepositAdded([walletAddress]);
|
const network = user.networkName.value;
|
||||||
const eventsDeposits = await p2pContract.queryFilter(
|
|
||||||
filterDeposits,
|
|
||||||
0,
|
|
||||||
"latest"
|
|
||||||
);
|
|
||||||
console.log("Fetched all wallet deposits");
|
|
||||||
|
|
||||||
// Get locks
|
// Query subgraph for all relevant transactions
|
||||||
const filterAddedLocks = p2pContract.filters.LockAdded([walletAddress]);
|
const subgraphQuery = {
|
||||||
const eventsAddedLocks = await p2pContract.queryFilter(
|
query: `
|
||||||
filterAddedLocks,
|
{
|
||||||
0,
|
depositAddeds(where: {seller: "${walletAddress.toLowerCase()}"}) {
|
||||||
"latest"
|
id
|
||||||
);
|
seller
|
||||||
console.log("Fetched all wallet locks");
|
token
|
||||||
|
amount
|
||||||
|
blockTimestamp
|
||||||
|
blockNumber
|
||||||
|
transactionHash
|
||||||
|
}
|
||||||
|
lockAddeds(where: {buyer: "${walletAddress.toLowerCase()}"}) {
|
||||||
|
buyer
|
||||||
|
lockID
|
||||||
|
seller
|
||||||
|
amount
|
||||||
|
blockTimestamp
|
||||||
|
blockNumber
|
||||||
|
transactionHash
|
||||||
|
}
|
||||||
|
lockReleaseds(where: {buyer: "${walletAddress.toLowerCase()}"}) {
|
||||||
|
buyer
|
||||||
|
lockId
|
||||||
|
blockTimestamp
|
||||||
|
blockNumber
|
||||||
|
transactionHash
|
||||||
|
}
|
||||||
|
depositWithdrawns(where: {seller: "${walletAddress.toLowerCase()}"}) {
|
||||||
|
seller
|
||||||
|
token
|
||||||
|
amount
|
||||||
|
blockTimestamp
|
||||||
|
blockNumber
|
||||||
|
transactionHash
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
};
|
||||||
|
|
||||||
// Get released locks
|
const response = await fetch(getNetworkSubgraphURL(network), {
|
||||||
const filterReleasedLocks = p2pContract.filters.LockReleased([walletAddress]);
|
method: "POST",
|
||||||
const eventsReleasedLocks = await p2pContract.queryFilter(
|
headers: {
|
||||||
filterReleasedLocks,
|
"Content-Type": "application/json",
|
||||||
0,
|
},
|
||||||
"latest"
|
body: JSON.stringify(subgraphQuery),
|
||||||
);
|
});
|
||||||
console.log("Fetched all wallet released locks");
|
|
||||||
|
|
||||||
// Get withdrawn deposits
|
const data = await response.json();
|
||||||
const filterWithdrawnDeposits = p2pContract.filters.DepositWithdrawn([
|
// Convert all transactions to common WalletTransaction format
|
||||||
walletAddress,
|
const transactions: WalletTransaction[] = [];
|
||||||
]);
|
|
||||||
const eventsWithdrawnDeposits = await p2pContract.queryFilter(
|
|
||||||
filterWithdrawnDeposits
|
|
||||||
);
|
|
||||||
console.log("Fetched all wallet withdrawn deposits");
|
|
||||||
|
|
||||||
const lockStatusFiltered = await filterLockStatus(
|
// Process deposit added events
|
||||||
[
|
if (data.data?.depositAddeds) {
|
||||||
...eventsDeposits,
|
for (const deposit of data.data.depositAddeds) {
|
||||||
...eventsAddedLocks,
|
transactions.push({
|
||||||
...eventsReleasedLocks,
|
token: deposit.token,
|
||||||
...eventsWithdrawnDeposits,
|
blockNumber: parseInt(deposit.blockNumber),
|
||||||
].sort((a, b) => {
|
amount: parseFloat(formatEther(BigInt(deposit.amount))),
|
||||||
return b.blockNumber - a.blockNumber;
|
seller: deposit.seller,
|
||||||
})
|
buyer: "",
|
||||||
);
|
event: "DepositAdded",
|
||||||
|
lockStatus: undefined,
|
||||||
|
transactionHash: deposit.transactionHash,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return lockStatusFiltered;
|
// Process lock added events
|
||||||
|
if (data.data?.lockAddeds) {
|
||||||
|
for (const lock of data.data.lockAddeds) {
|
||||||
|
// Get lock status from the contract
|
||||||
|
const lockStatus = await getLockStatus(BigInt(lock.lockID));
|
||||||
|
|
||||||
|
transactions.push({
|
||||||
|
token: lock.token,
|
||||||
|
blockNumber: parseInt(lock.blockNumber),
|
||||||
|
amount: parseFloat(formatEther(BigInt(lock.amount))),
|
||||||
|
seller: lock.seller,
|
||||||
|
buyer: lock.buyer,
|
||||||
|
event: "LockAdded",
|
||||||
|
lockStatus: lockStatus,
|
||||||
|
transactionHash: lock.transactionHash,
|
||||||
|
transactionID: lock.lockID.toString(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process lock released events
|
||||||
|
if (data.data?.lockReleaseds) {
|
||||||
|
for (const release of data.data.lockReleaseds) {
|
||||||
|
transactions.push({
|
||||||
|
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: undefined,
|
||||||
|
transactionHash: release.transactionHash,
|
||||||
|
transactionID: release.lockId.toString(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process deposit withdrawn events
|
||||||
|
if (data.data?.depositWithdrawns) {
|
||||||
|
for (const withdrawal of data.data.depositWithdrawns) {
|
||||||
|
transactions.push({
|
||||||
|
token: withdrawal.token,
|
||||||
|
blockNumber: parseInt(withdrawal.blockNumber),
|
||||||
|
amount: parseFloat(formatEther(BigInt(withdrawal.amount))),
|
||||||
|
seller: withdrawal.seller,
|
||||||
|
buyer: "",
|
||||||
|
event: "DepositWithdrawn",
|
||||||
|
lockStatus: undefined,
|
||||||
|
transactionHash: withdrawal.transactionHash,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort transactions by block number (newest first)
|
||||||
|
return transactions.sort((a, b) => b.blockNumber - a.blockNumber);
|
||||||
};
|
};
|
||||||
|
|
||||||
// get wallet's release transactions
|
// get wallet's release transactions
|
||||||
export const listReleaseTransactionByWalletAddress = async (
|
export const listReleaseTransactionByWalletAddress = async (
|
||||||
walletAddress: string
|
walletAddress: Address
|
||||||
): Promise<LogDescription[]> => {
|
) => {
|
||||||
const p2pContract = await getContract(true);
|
const user = useUser();
|
||||||
|
const network = user.networkName.value;
|
||||||
|
|
||||||
const filterReleasedLocks = p2pContract.filters.LockReleased([walletAddress]);
|
// Query subgraph for release transactions
|
||||||
const eventsReleasedLocks = await p2pContract.queryFilter(
|
const subgraphQuery = {
|
||||||
filterReleasedLocks,
|
query: `
|
||||||
0,
|
{
|
||||||
"latest"
|
lockReleaseds(where: {buyer: "${walletAddress.toLowerCase()}"}) {
|
||||||
);
|
buyer
|
||||||
|
lockId
|
||||||
return eventsReleasedLocks
|
e2eId
|
||||||
.sort((a, b) => {
|
blockTimestamp
|
||||||
return b.blockNumber - a.blockNumber;
|
blockNumber
|
||||||
})
|
transactionHash
|
||||||
.map((lock) => {
|
}
|
||||||
const IPix2Pix = new Interface(p2pix.abi);
|
}
|
||||||
const decoded = IPix2Pix.parseLog({
|
`,
|
||||||
topics: lock.topics,
|
|
||||||
data: lock.data,
|
|
||||||
});
|
|
||||||
return decoded;
|
|
||||||
})
|
|
||||||
.filter((lock) => lock !== null);
|
|
||||||
};
|
|
||||||
|
|
||||||
const listLockTransactionByWalletAddress = async (
|
|
||||||
walletAddress: string
|
|
||||||
): Promise<LogDescription[]> => {
|
|
||||||
const p2pContract = await getContract(true);
|
|
||||||
|
|
||||||
const filterAddedLocks = p2pContract.filters.LockAdded([walletAddress]);
|
|
||||||
const eventsReleasedLocks = await p2pContract.queryFilter(filterAddedLocks);
|
|
||||||
|
|
||||||
return eventsReleasedLocks
|
|
||||||
.sort((a, b) => {
|
|
||||||
return b.blockNumber - a.blockNumber;
|
|
||||||
})
|
|
||||||
.map((lock) => {
|
|
||||||
const IPix2Pix = new Interface(p2pix.abi);
|
|
||||||
const decoded = IPix2Pix.parseLog({
|
|
||||||
topics: lock.topics,
|
|
||||||
data: lock.data,
|
|
||||||
});
|
|
||||||
return decoded;
|
|
||||||
})
|
|
||||||
.filter((lock) => lock !== null);
|
|
||||||
};
|
|
||||||
|
|
||||||
const listLockTransactionBySellerAddress = async (
|
|
||||||
sellerAddress: string
|
|
||||||
): Promise<LogDescription[]> => {
|
|
||||||
const p2pContract = await getContract(true);
|
|
||||||
console.log("Will get locks as seller", sellerAddress);
|
|
||||||
const filterAddedLocks = p2pContract.filters.LockAdded();
|
|
||||||
const eventsReleasedLocks = await p2pContract.queryFilter(
|
|
||||||
filterAddedLocks
|
|
||||||
// 0,
|
|
||||||
// "latest"
|
|
||||||
);
|
|
||||||
return eventsReleasedLocks
|
|
||||||
.map((lock) => {
|
|
||||||
const IPix2Pix = new Interface(p2pix.abi);
|
|
||||||
const decoded = IPix2Pix.parseLog({
|
|
||||||
topics: lock.topics,
|
|
||||||
data: lock.data,
|
|
||||||
});
|
|
||||||
return decoded;
|
|
||||||
})
|
|
||||||
.filter((lock) => lock !== null)
|
|
||||||
.filter(
|
|
||||||
(lock) => lock.args.seller.toLowerCase() == sellerAddress.toLowerCase()
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const checkUnreleasedLock = async (
|
|
||||||
walletAddress: string
|
|
||||||
): Promise<UnreleasedLock | undefined> => {
|
|
||||||
const p2pContract = await getContract();
|
|
||||||
const pixData: Pix = {
|
|
||||||
pixKey: "",
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const addedLocks = await listLockTransactionByWalletAddress(walletAddress);
|
// Fetch data from subgraph
|
||||||
const lockStatus = await p2pContract.getLocksStatus(
|
const response = await fetch(getNetworkSubgraphURL(network), {
|
||||||
addedLocks.map((lock) => lock.args?.lockID)
|
method: "POST",
|
||||||
);
|
headers: {
|
||||||
const unreleasedLockId = lockStatus[1].findIndex(
|
"Content-Type": "application/json",
|
||||||
(lockStatus: number) => lockStatus == 1
|
},
|
||||||
);
|
body: JSON.stringify(subgraphQuery),
|
||||||
|
});
|
||||||
|
|
||||||
if (unreleasedLockId != -1) {
|
const data = await response.json();
|
||||||
const _lockID = lockStatus[0][unreleasedLockId];
|
|
||||||
const lock = await p2pContract.mapLocks(_lockID);
|
|
||||||
|
|
||||||
const pixTarget = lock.pixTarget;
|
// Process the subgraph response into the same format as the previous implementation
|
||||||
const amount = formatEther(lock?.amount);
|
if (!data.data?.lockReleaseds) {
|
||||||
pixData.pixKey = pixTarget;
|
return [];
|
||||||
pixData.value = Number(amount);
|
}
|
||||||
|
|
||||||
return {
|
// Transform the subgraph data to match the event log decode format
|
||||||
lockID: _lockID,
|
return data.data.lockReleaseds
|
||||||
pix: pixData,
|
.sort((a: any, b: any) => {
|
||||||
};
|
return parseInt(b.blockNumber) - parseInt(a.blockNumber);
|
||||||
|
})
|
||||||
|
.map((release: any) => {
|
||||||
|
try {
|
||||||
|
// Create a structure similar to the decoded event log
|
||||||
|
return {
|
||||||
|
eventName: "LockReleased",
|
||||||
|
args: {
|
||||||
|
buyer: release.buyer,
|
||||||
|
lockID: BigInt(release.lockId),
|
||||||
|
e2eId: release.e2eId,
|
||||||
|
},
|
||||||
|
// Add any other necessary fields to match the original return format
|
||||||
|
blockNumber: BigInt(release.blockNumber),
|
||||||
|
transactionHash: release.transactionHash,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error processing subgraph data", error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.filter((decoded: any) => decoded !== null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const listLockTransactionByWalletAddress = async (walletAddress: Address) => {
|
||||||
|
const user = useUser();
|
||||||
|
const network = user.networkName.value;
|
||||||
|
|
||||||
|
// Query subgraph for lock added transactions
|
||||||
|
const subgraphQuery = {
|
||||||
|
query: `
|
||||||
|
{
|
||||||
|
lockAddeds(where: {buyer: "${walletAddress.toLowerCase()}"}) {
|
||||||
|
buyer
|
||||||
|
lockID
|
||||||
|
seller
|
||||||
|
amount
|
||||||
|
blockTimestamp
|
||||||
|
blockNumber
|
||||||
|
transactionHash
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Fetch data from subgraph
|
||||||
|
const response = await fetch(getNetworkSubgraphURL(network), {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify(subgraphQuery),
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (!data.data?.lockAddeds) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Transform the subgraph data to match the event log decode format
|
||||||
|
return data.data.lockAddeds
|
||||||
|
.sort((a: any, b: any) => {
|
||||||
|
return parseInt(b.blockNumber) - parseInt(a.blockNumber);
|
||||||
|
})
|
||||||
|
.map((lock: any) => {
|
||||||
|
try {
|
||||||
|
// Create a structure similar to the decoded event log
|
||||||
|
return {
|
||||||
|
eventName: "LockAdded",
|
||||||
|
args: {
|
||||||
|
buyer: lock.buyer,
|
||||||
|
lockID: BigInt(lock.lockID),
|
||||||
|
seller: lock.seller,
|
||||||
|
token: lock.token,
|
||||||
|
amount: BigInt(lock.amount),
|
||||||
|
},
|
||||||
|
// Add other necessary fields to match the original format
|
||||||
|
blockNumber: BigInt(lock.blockNumber),
|
||||||
|
transactionHash: lock.transactionHash,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error processing subgraph data", error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.filter((decoded: any) => decoded !== null);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching from subgraph:", error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const listLockTransactionBySellerAddress = async (sellerAddress: Address) => {
|
||||||
|
const user = useUser();
|
||||||
|
const network = user.networkName.value;
|
||||||
|
|
||||||
|
// Query subgraph for lock added transactions where seller matches
|
||||||
|
const subgraphQuery = {
|
||||||
|
query: `
|
||||||
|
{
|
||||||
|
lockAddeds(where: {seller: "${sellerAddress.toLowerCase()}"}) {
|
||||||
|
buyer
|
||||||
|
lockID
|
||||||
|
seller
|
||||||
|
token
|
||||||
|
amount
|
||||||
|
blockTimestamp
|
||||||
|
blockNumber
|
||||||
|
transactionHash
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`,
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Fetch data from subgraph
|
||||||
|
const response = await fetch(getNetworkSubgraphURL(network), {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify(subgraphQuery),
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (!data.data?.lockAddeds) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Transform the subgraph data to match the event log decode format
|
||||||
|
return data.data.lockAddeds
|
||||||
|
.sort((a: any, b: any) => {
|
||||||
|
return parseInt(b.blockNumber) - parseInt(a.blockNumber);
|
||||||
|
})
|
||||||
|
.map((lock: any) => {
|
||||||
|
try {
|
||||||
|
// Create a structure similar to the decoded event log
|
||||||
|
return {
|
||||||
|
eventName: "LockAdded",
|
||||||
|
args: {
|
||||||
|
buyer: lock.buyer,
|
||||||
|
lockID: BigInt(lock.lockID),
|
||||||
|
seller: lock.seller,
|
||||||
|
token: lock.token,
|
||||||
|
amount: BigInt(lock.amount),
|
||||||
|
},
|
||||||
|
// Add other necessary fields to match the original format
|
||||||
|
blockNumber: BigInt(lock.blockNumber),
|
||||||
|
transactionHash: lock.transactionHash,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error processing subgraph data", error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.filter((decoded: any) => decoded !== null);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching from subgraph:", error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const checkUnreleasedLock = async (
|
||||||
|
walletAddress: Address
|
||||||
|
): Promise<UnreleasedLock | undefined> => {
|
||||||
|
const { address, abi, client } = await getContract();
|
||||||
|
const addedLocks = await listLockTransactionByWalletAddress(walletAddress);
|
||||||
|
|
||||||
|
if (!addedLocks.length) return undefined;
|
||||||
|
|
||||||
|
const lockIds = addedLocks.map((lock: any) => lock.args.lockID);
|
||||||
|
|
||||||
|
const [ sortedIDs, status ] = await client.readContract({
|
||||||
|
address,
|
||||||
|
abi,
|
||||||
|
functionName: "getLocksStatus",
|
||||||
|
args: [lockIds],
|
||||||
|
});
|
||||||
|
|
||||||
|
const unreleasedLockId = status.findIndex(
|
||||||
|
(status: LockStatus) => status == LockStatus.Active
|
||||||
|
);
|
||||||
|
|
||||||
|
if (unreleasedLockId !== -1)
|
||||||
|
return getUnreleasedLockById(sortedIDs[unreleasedLockId]);
|
||||||
|
};
|
||||||
|
|
||||||
export const getActiveLockAmount = async (
|
export const getActiveLockAmount = async (
|
||||||
walletAddress: string
|
walletAddress: Address
|
||||||
): 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 lockIds = lockSeller.map((lock: any) => lock.args.lockID);
|
||||||
|
|
||||||
|
const [ sortedIDs, status ] = await client.readContract({
|
||||||
|
address,
|
||||||
|
abi,
|
||||||
|
functionName: "getLocksStatus",
|
||||||
|
args: [lockIds],
|
||||||
|
});
|
||||||
|
|
||||||
|
const mapLocksRequests = status.map((id: LockStatus) =>
|
||||||
|
client.readContract({
|
||||||
|
address: address,
|
||||||
|
abi,
|
||||||
|
functionName: "mapLocks",
|
||||||
|
args: [BigInt(id)],
|
||||||
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
const activeLockAmount = await lockStatus[1].reduce(
|
const mapLocksResults = await client.multicall({
|
||||||
async (sumValue: Promise<number>, currentStatus: number, index: number) => {
|
contracts: mapLocksRequests as any,
|
||||||
const currValue = await sumValue;
|
});
|
||||||
let valueToSum = 0;
|
|
||||||
|
|
||||||
if (currentStatus == 1) {
|
return mapLocksResults.reduce((total: number, lock: any, index: number) => {
|
||||||
const lock = await p2pContract.mapLocks(lockStatus[0][index]);
|
if (status[index] === 1) {
|
||||||
valueToSum = Number(formatEther(lock?.amount));
|
return total + Number(formatEther(lock.amount));
|
||||||
}
|
}
|
||||||
|
return total;
|
||||||
return currValue + valueToSum;
|
}, 0);
|
||||||
},
|
};
|
||||||
Promise.resolve(0)
|
|
||||||
);
|
export const getSellerParticipantId = async (
|
||||||
|
sellerAddress: Address,
|
||||||
return activeLockAmount;
|
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);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -8,8 +8,7 @@ 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 { useUser } from "@/composables/useUser";
|
||||||
import { storeToRefs } from "pinia";
|
|
||||||
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 +18,8 @@ const props = defineProps<{
|
|||||||
isCurrentStep: boolean;
|
isCurrentStep: boolean;
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
const etherStore = useEtherStore();
|
const user = useUser();
|
||||||
const { walletAddress } = storeToRefs(etherStore);
|
const { walletAddress } = useUser();
|
||||||
|
|
||||||
const lastWalletTransactions = ref<WalletTransaction[]>([]);
|
const lastWalletTransactions = ref<WalletTransaction[]>([]);
|
||||||
const depositList = ref<ValidDeposit[]>([]);
|
const depositList = ref<ValidDeposit[]>([]);
|
||||||
@@ -29,7 +28,7 @@ const activeLockAmount = ref<number>(0);
|
|||||||
// methods
|
// methods
|
||||||
|
|
||||||
const getWalletTransactions = async () => {
|
const getWalletTransactions = async () => {
|
||||||
etherStore.setLoadingWalletTransactions(true);
|
user.setLoadingWalletTransactions(true);
|
||||||
if (walletAddress.value) {
|
if (walletAddress.value) {
|
||||||
const walletDeposits = await listValidDepositTransactionsByWalletAddress(
|
const walletDeposits = await listValidDepositTransactionsByWalletAddress(
|
||||||
walletAddress.value
|
walletAddress.value
|
||||||
@@ -48,20 +47,20 @@ const getWalletTransactions = async () => {
|
|||||||
lastWalletTransactions.value = allUserTransactions;
|
lastWalletTransactions.value = allUserTransactions;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
etherStore.setLoadingWalletTransactions(false);
|
user.setLoadingWalletTransactions(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
const callWithdraw = async (amount: string) => {
|
const callWithdraw = async (amount: string) => {
|
||||||
if (amount) {
|
if (amount) {
|
||||||
etherStore.setLoadingWalletTransactions(true);
|
user.setLoadingWalletTransactions(true);
|
||||||
const withdraw = await withdrawDeposit(amount, etherStore.selectedToken);
|
const withdraw = await withdrawDeposit(amount, user.selectedToken.value);
|
||||||
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);
|
user.setLoadingWalletTransactions(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -93,14 +92,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 }} {{ user.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 {{ user.selectedToken }} em sua carteira.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<CustomButton :text="'Cadastrar token'" @buttonClicked="() => {}" />
|
<CustomButton :text="'Cadastrar token'" @buttonClicked="() => {}" />
|
||||||
@@ -150,10 +149,6 @@ p {
|
|||||||
@apply font-medium text-base text-gray-900;
|
@apply font-medium text-base text-gray-900;
|
||||||
}
|
}
|
||||||
|
|
||||||
input[type="number"] {
|
|
||||||
-moz-appearance: textfield;
|
|
||||||
}
|
|
||||||
|
|
||||||
input[type="number"]::-webkit-inner-spin-button,
|
input[type="number"]::-webkit-inner-spin-button,
|
||||||
input[type="number"]::-webkit-outer-spin-button {
|
input[type="number"]::-webkit-outer-spin-button {
|
||||||
-webkit-appearance: none;
|
-webkit-appearance: none;
|
||||||
|
|||||||
@@ -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>
|
<template>
|
||||||
<div>
|
<div>
|
||||||
<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"
|
v-if="!isRedirectModal"
|
||||||
>
|
>
|
||||||
<div class="modal px-5 text-center">
|
<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");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,18 +1,15 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
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 { useUser } from "@/composables/useUser";
|
||||||
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";
|
||||||
import { decimalCount } from "@/utils/decimalCount";
|
import { decimalCount } from "@/utils/decimalCount";
|
||||||
import { debounce } from "@/utils/debounce";
|
import { debounce } from "@/utils/debounce";
|
||||||
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 user = useUser();
|
||||||
|
|
||||||
// props
|
// props
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
@@ -23,8 +20,9 @@ const props = defineProps<{
|
|||||||
|
|
||||||
const emit = defineEmits(["depositWithdrawn"]);
|
const emit = defineEmits(["depositWithdrawn"]);
|
||||||
|
|
||||||
const { loadingWalletTransactions } = storeToRefs(etherStore);
|
const { loadingWalletTransactions } = user;
|
||||||
const remaining = ref<number>(0.0);
|
|
||||||
|
const remaining = ref<number>(0);
|
||||||
const itemsToShow = ref<WalletTransaction[]>([]);
|
const itemsToShow = ref<WalletTransaction[]>([]);
|
||||||
const withdrawAmount = ref<string>("");
|
const withdrawAmount = ref<string>("");
|
||||||
const withdrawButtonOpacity = ref<number>(0.6);
|
const withdrawButtonOpacity = ref<number>(0.6);
|
||||||
@@ -85,8 +83,7 @@ watch(withdrawAmount, (): void => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const getRemaining = (): number => {
|
const getRemaining = (): number => {
|
||||||
if (props.validDeposits instanceof Array) {
|
if (props.validDeposits.length > 0) {
|
||||||
// Here we are getting only the first element of the list because
|
|
||||||
// in this release only the BRL token is being used.
|
// in this release only the BRL token is being used.
|
||||||
const deposit = props.validDeposits[0];
|
const deposit = props.validDeposits[0];
|
||||||
remaining.value = deposit ? deposit.remaining : 0;
|
remaining.value = deposit ? deposit.remaining : 0;
|
||||||
@@ -96,7 +93,7 @@ const getRemaining = (): number => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const getExplorer = (): string => {
|
const getExplorer = (): string => {
|
||||||
return etherStore.networkName == NetworkEnum.sepolia
|
return user.networkName.value == NetworkEnum.sepolia
|
||||||
? "Etherscan"
|
? "Etherscan"
|
||||||
: "Polygonscan";
|
: "Polygonscan";
|
||||||
};
|
};
|
||||||
@@ -107,7 +104,7 @@ const showInitialItems = (): void => {
|
|||||||
|
|
||||||
const openEtherscanUrl = (transactionHash: string): void => {
|
const openEtherscanUrl = (transactionHash: string): void => {
|
||||||
const networkUrl =
|
const networkUrl =
|
||||||
etherStore.networkName == NetworkEnum.sepolia
|
user.networkName.value == NetworkEnum.sepolia
|
||||||
? "sepolia.etherscan.io"
|
? "sepolia.etherscan.io"
|
||||||
: "mumbai.polygonscan.com";
|
: "mumbai.polygonscan.com";
|
||||||
const url = `https://${networkUrl}/tx/${transactionHash}`;
|
const url = `https://${networkUrl}/tx/${transactionHash}`;
|
||||||
@@ -162,10 +159,14 @@ showInitialItems();
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<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>
|
<SpinnerComponent width="8" height="8"></SpinnerComponent>
|
||||||
</div>
|
</div>
|
||||||
<div class="main-container max-w-md" v-if="!loadingWalletTransactions">
|
<div class="main-container max-w-md" v-else>
|
||||||
<div
|
<div
|
||||||
class="w-full bg-white p-4 sm:p-6 rounded-lg"
|
class="w-full bg-white p-4 sm:p-6 rounded-lg"
|
||||||
v-if="props.validDeposits.length > 0"
|
v-if="props.validDeposits.length > 0"
|
||||||
@@ -176,12 +177,12 @@ showInitialItems();
|
|||||||
Saldo disponível
|
Saldo disponível
|
||||||
</p>
|
</p>
|
||||||
<p class="text-xl leading-7 font-semibold text-gray-900">
|
<p class="text-xl leading-7 font-semibold text-gray-900">
|
||||||
{{ getRemaining() }} {{ etherStore.selectedToken }}
|
{{ getRemaining() }} {{ user.selectedToken.value }}
|
||||||
</p>
|
</p>
|
||||||
<div class="flex gap-2 w-32 sm:w-56" v-if="activeLockAmount != 0">
|
<div class="flex gap-2 w-32 sm:w-56" v-if="activeLockAmount != 0">
|
||||||
<span class="text-xs font-normal text-gray-400" ref="infoText">{{
|
<span class="text-xs font-normal text-gray-400" ref="infoText">{{
|
||||||
`com ${activeLockAmount.toFixed(2)} ${
|
`com ${activeLockAmount.toFixed(2)} ${
|
||||||
etherStore.selectedToken
|
user.selectedToken.value
|
||||||
} em lock`
|
} em lock`
|
||||||
}}</span>
|
}}</span>
|
||||||
<div
|
<div
|
||||||
@@ -285,10 +286,10 @@ showInitialItems();
|
|||||||
class="text-xl sm:text-xl leading-7 font-semibold text-gray-900"
|
class="text-xl sm:text-xl leading-7 font-semibold text-gray-900"
|
||||||
>
|
>
|
||||||
{{ item.amount }}
|
{{ item.amount }}
|
||||||
{{ getTokenByAddress(item.token) }}
|
<!-- {{ getTokenByAddress(item.token) }} -->
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div class="flex flex-col items-center justify-center">
|
||||||
<div
|
<div
|
||||||
class="bg-amber-300 status-text"
|
class="bg-amber-300 status-text"
|
||||||
v-if="getEventName(item.event) == 'Reserva' && item.lockStatus == 1"
|
v-if="getEventName(item.event) == 'Reserva' && item.lockStatus == 1"
|
||||||
@@ -411,6 +412,7 @@ p {
|
|||||||
}
|
}
|
||||||
|
|
||||||
input[type="number"] {
|
input[type="number"] {
|
||||||
|
appearance: textfield;
|
||||||
-moz-appearance: textfield;
|
-moz-appearance: textfield;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,87 +0,0 @@
|
|||||||
import { mount } from "@vue/test-utils";
|
|
||||||
import ListingComponent from "@/components/ListingComponent/ListingComponent.vue";
|
|
||||||
import { createPinia, setActivePinia } from "pinia";
|
|
||||||
import { expect } from "vitest";
|
|
||||||
import { MockValidDeposits } from "@/model/mock/ValidDepositMock";
|
|
||||||
import { MockWalletTransactions } from "@/model/mock/WalletTransactionMock";
|
|
||||||
import { useEtherStore } from "@/store/ether";
|
|
||||||
|
|
||||||
describe("ListingComponent.vue", () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
setActivePinia(createPinia());
|
|
||||||
useEtherStore().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,36 +1,124 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onMounted, onUnmounted, ref } from "vue";
|
import { ref, onMounted, onUnmounted } from "vue";
|
||||||
import CustomButton from "@/components/CustomButton/CustomButton.vue";
|
import CustomButton from "@/components/CustomButton/CustomButton.vue";
|
||||||
import CustomModal from "@/components//CustomModal/CustomModal.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";
|
import QRCode from "qrcode";
|
||||||
|
|
||||||
// props and store references
|
// Props
|
||||||
const props = defineProps({
|
interface Props {
|
||||||
sellerId: String,
|
lockID: string;
|
||||||
amount: Number,
|
}
|
||||||
qrcode: String,
|
|
||||||
});
|
const props = defineProps<Props>();
|
||||||
|
|
||||||
const windowSize = ref<number>(window.innerWidth);
|
|
||||||
const qrCode = ref<string>("");
|
const qrCode = ref<string>("");
|
||||||
const isPixValid = ref<boolean>(false);
|
const qrCodeSvg = ref<string>("");
|
||||||
const showWarnModal = ref<boolean>(true);
|
const showWarnModal = ref<boolean>(true);
|
||||||
|
const pixTarget = ref<string>("");
|
||||||
const releaseSignature = 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
|
// Emits
|
||||||
const emit = defineEmits(["pixValidated"]);
|
const emit = defineEmits(["pixValidated"]);
|
||||||
|
|
||||||
onMounted(() => {
|
// Function to check solicitation status
|
||||||
window.addEventListener(
|
const checkSolicitationStatus = async () => {
|
||||||
"resize",
|
if (!solicitationData.value?.numeroSolicitacao) {
|
||||||
() => (windowSize.value = window.innerWidth)
|
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(() => {
|
onUnmounted(() => {
|
||||||
window.removeEventListener(
|
if (pollingInterval.value) {
|
||||||
"resize",
|
clearInterval(pollingInterval.value);
|
||||||
() => (windowSize.value = window.innerWidth)
|
pollingInterval.value = null;
|
||||||
);
|
}
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -51,7 +139,17 @@ onUnmounted(() => {
|
|||||||
<div
|
<div
|
||||||
class="flex-col items-center justify-center flex w-full bg-white sm:p-8 p-4 rounded-lg break-normal"
|
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>
|
<span class="text-center font-bold">Código pix</span>
|
||||||
<div class="break-words w-4/5">
|
<div class="break-words w-4/5">
|
||||||
<span class="text-center text-xs">
|
<span class="text-center text-xs">
|
||||||
@@ -67,13 +165,17 @@ onUnmounted(() => {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<CustomButton
|
<CustomButton
|
||||||
:is-disabled="isPixValid == false"
|
:is-disabled="releaseSignature === ''"
|
||||||
:text="'Enviar para a rede'"
|
:text="
|
||||||
@button-clicked="emit('pixValidated', releaseSignature)"
|
releaseSignature ? 'Enviar para a rede' : 'Validando pagamento...'
|
||||||
|
"
|
||||||
|
@button-clicked="
|
||||||
|
emit('pixValidated', { pixTarget, signature: releaseSignature })
|
||||||
|
"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<CustomModal
|
<CustomModal
|
||||||
v-if="showWarnModal && windowSize <= 500"
|
v-if="showWarnModal"
|
||||||
@close-modal="showWarnModal = false"
|
@close-modal="showWarnModal = false"
|
||||||
:isRedirectModal="false"
|
:isRedirectModal="false"
|
||||||
/>
|
/>
|
||||||
@@ -130,6 +232,7 @@ h2 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
input[type="number"] {
|
input[type="number"] {
|
||||||
|
appearance: textfield;
|
||||||
-moz-appearance: textfield;
|
-moz-appearance: textfield;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,21 +1,20 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref, watch } from "vue";
|
import { ref, watch } from "vue";
|
||||||
|
import { useUser } from "@/composables/useUser";
|
||||||
|
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 user = useUser();
|
||||||
const selectTokenToggle = ref<boolean>(false);
|
const selectTokenToggle = ref<boolean>(false);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
@@ -24,7 +23,7 @@ const {
|
|||||||
selectedToken,
|
selectedToken,
|
||||||
depositsValidList,
|
depositsValidList,
|
||||||
loadingNetworkLiquidity,
|
loadingNetworkLiquidity,
|
||||||
} = storeToRefs(etherStore);
|
} = user;
|
||||||
|
|
||||||
// html references
|
// html references
|
||||||
const tokenDropdownRef = ref<any>(null);
|
const tokenDropdownRef = ref<any>(null);
|
||||||
@@ -39,7 +38,7 @@ const selectedDeposits = ref<ValidDeposit[]>();
|
|||||||
|
|
||||||
import ChevronDown from "@/assets/chevronDown.svg";
|
import ChevronDown from "@/assets/chevronDown.svg";
|
||||||
import { useOnboard } from "@web3-onboard/vue";
|
import { useOnboard } from "@web3-onboard/vue";
|
||||||
import { getPixKey } from "@/blockchain/events";
|
import { getParticipantID } from "@/blockchain/events";
|
||||||
|
|
||||||
// Emits
|
// Emits
|
||||||
const emit = defineEmits(["tokenBuy"]);
|
const emit = defineEmits(["tokenBuy"]);
|
||||||
@@ -52,10 +51,10 @@ const connectAccount = async (): Promise<void> => {
|
|||||||
|
|
||||||
const emitConfirmButton = async (): Promise<void> => {
|
const emitConfirmButton = async (): Promise<void> => {
|
||||||
const deposit = selectedDeposits.value?.find(
|
const deposit = selectedDeposits.value?.find(
|
||||||
(d) => d.network === networkName.value
|
(d) => d.network === Number(networkName.value)
|
||||||
);
|
);
|
||||||
if (!deposit) return;
|
if (!deposit) return;
|
||||||
deposit.pixKey = await getPixKey(deposit.seller, deposit.token);
|
deposit.participantID = await getParticipantID(deposit.seller, deposit.token);
|
||||||
emit("tokenBuy", deposit, tokenValue.value);
|
emit("tokenBuy", deposit, tokenValue.value);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -84,22 +83,23 @@ onClickOutside(tokenDropdownRef, () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const handleSelectedToken = (token: TokenEnum): void => {
|
const handleSelectedToken = (token: TokenEnum): void => {
|
||||||
etherStore.setSelectedToken(token);
|
user.setSelectedToken(token);
|
||||||
selectTokenToggle.value = false;
|
selectTokenToggle.value = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Verify if there is a valid deposit to buy
|
// Verify if there is a valid deposit to buy
|
||||||
const verifyLiquidity = (): void => {
|
const verifyLiquidity = (): void => {
|
||||||
enableConfirmButton.value = false;
|
enableConfirmButton.value = false;
|
||||||
|
if (!walletAddress.value)
|
||||||
|
return;
|
||||||
const selDeposits = verifyNetworkLiquidity(
|
const selDeposits = verifyNetworkLiquidity(
|
||||||
tokenValue.value,
|
tokenValue.value,
|
||||||
walletAddress.value,
|
walletAddress.value,
|
||||||
depositsValidList.value
|
depositsValidList.value
|
||||||
);
|
);
|
||||||
|
|
||||||
selectedDeposits.value = selDeposits;
|
selectedDeposits.value = selDeposits;
|
||||||
hasLiquidity.value = !!selDeposits.find(
|
hasLiquidity.value = !!selDeposits.find(
|
||||||
(d) => d.network === networkName.value
|
(d) => d.network === Number(networkName.value)
|
||||||
);
|
);
|
||||||
enableOrDisableConfirmButton();
|
enableOrDisableConfirmButton();
|
||||||
};
|
};
|
||||||
@@ -130,8 +130,6 @@ watch(walletAddress, (): void => {
|
|||||||
// Add form submission handler
|
// Add form submission handler
|
||||||
const handleSubmit = async (e: Event): Promise<void> => {
|
const handleSubmit = async (e: Event): Promise<void> => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (!enableConfirmButton.value) return;
|
|
||||||
|
|
||||||
if (walletAddress.value) {
|
if (walletAddress.value) {
|
||||||
await emitConfirmButton();
|
await emitConfirmButton();
|
||||||
} else {
|
} else {
|
||||||
@@ -275,7 +273,9 @@ const handleSubmit = async (e: Event): Promise<void> => {
|
|||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
class="flex justify-center"
|
class="flex justify-center"
|
||||||
v-else-if="!hasLiquidity && !loadingNetworkLiquidity"
|
v-else-if="
|
||||||
|
!hasLiquidity && !loadingNetworkLiquidity && tokenValue > 0
|
||||||
|
"
|
||||||
>
|
>
|
||||||
<span class="text-red-500 font-normal text-sm"
|
<span class="text-red-500 font-normal text-sm"
|
||||||
>Atualmente não há liquidez nas rede selecionada para sua
|
>Atualmente não há liquidez nas rede selecionada para sua
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
<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 { useUser } from "@/composables/useUser";
|
||||||
import { pixFormatValidation, postProcessKey } from "@/utils/pixKeyFormat";
|
import CustomButton from "@/components/CustomButton/CustomButton.vue";
|
||||||
import { useEtherStore } from "@/store/ether";
|
import { postProcessKey } from "@/utils/pixKeyFormat";
|
||||||
import { storeToRefs } from "pinia";
|
|
||||||
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,10 +23,9 @@ 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 user = useUser();
|
||||||
const { walletAddress, selectedToken } = storeToRefs(etherStore);
|
const { walletAddress, selectedToken } = user;
|
||||||
|
|
||||||
const fullName = ref<string>("");
|
|
||||||
const offer = ref<string>("");
|
const offer = ref<string>("");
|
||||||
const identification = ref<string>("");
|
const identification = ref<string>("");
|
||||||
const account = ref<string>("");
|
const account = ref<string>("");
|
||||||
@@ -73,7 +71,7 @@ const handleSubmit = (e: Event): void => {
|
|||||||
|
|
||||||
const data: Participant = {
|
const data: Participant = {
|
||||||
offer: offer.value,
|
offer: offer.value,
|
||||||
fullName: fullName.value,
|
chainID: user.networkId.value,
|
||||||
identification: processedIdentification,
|
identification: processedIdentification,
|
||||||
bankIspb: selectedBank.value?.ISPB,
|
bankIspb: selectedBank.value?.ISPB,
|
||||||
accountType: accountType.value,
|
accountType: accountType.value,
|
||||||
@@ -91,7 +89,7 @@ const openTokenSelection = (): void => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleSelectedToken = (token: TokenEnum): void => {
|
const handleSelectedToken = (token: TokenEnum): void => {
|
||||||
etherStore.setSelectedToken(token);
|
user.setSelectedToken(token);
|
||||||
selectTokenToggle.value = false;
|
selectTokenToggle.value = false;
|
||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
@@ -186,21 +184,6 @@ const handleSelectedToken = (token: TokenEnum): void => {
|
|||||||
</transition>
|
</transition>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Full name input -->
|
|
||||||
<div
|
|
||||||
class="flex flex-col w-full bg-white sm:px-10 px-6 py-4 rounded-lg border-y-10"
|
|
||||||
>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
v-model="fullName"
|
|
||||||
class="border-none outline-none sm:text-lg text-sm text-gray-900 w-full"
|
|
||||||
maxlength="60"
|
|
||||||
:class="{ 'text-xl font-medium': fullName }"
|
|
||||||
placeholder="Digite seu nome completo"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<!-- CPF or CNPJ input -->
|
<!-- CPF or CNPJ input -->
|
||||||
<div
|
<div
|
||||||
class="flex flex-col w-full bg-white sm:px-10 px-6 py-4 rounded-lg border-y-10"
|
class="flex flex-col w-full bg-white sm:px-10 px-6 py-4 rounded-lg border-y-10"
|
||||||
|
|||||||
@@ -1,17 +1,15 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref } from "vue";
|
import { ref } from "vue";
|
||||||
|
import { useUser } from "@/composables/useUser";
|
||||||
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 user = useUser();
|
||||||
const { walletAddress } = storeToRefs(etherStore);
|
const { walletAddress } = user;
|
||||||
|
|
||||||
// Reactive state
|
// Reactive state
|
||||||
const tokenValue = ref<number>(0);
|
const tokenValue = ref<number>(0);
|
||||||
@@ -76,10 +74,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(user.selectedToken.value)"
|
||||||
/>
|
/>
|
||||||
<span class="text-gray-900 text-lg w-fit" id="token">{{
|
<span class="text-gray-900 text-lg w-fit" id="token">{{
|
||||||
etherStore.selectedToken
|
user.selectedToken
|
||||||
}}</span>
|
}}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -153,10 +151,6 @@ const handleInputEvent = (event: any): void => {
|
|||||||
@apply text-white text-center;
|
@apply text-white text-center;
|
||||||
}
|
}
|
||||||
|
|
||||||
input[type="number"] {
|
|
||||||
-moz-appearance: textfield;
|
|
||||||
}
|
|
||||||
|
|
||||||
input[type="number"]::-webkit-inner-spin-button,
|
input[type="number"]::-webkit-inner-spin-button,
|
||||||
input[type="number"]::-webkit-outer-spin-button {
|
input[type="number"]::-webkit-outer-spin-button {
|
||||||
-webkit-appearance: none;
|
-webkit-appearance: none;
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ const props = defineProps({
|
|||||||
os tokens de volta.</span
|
os tokens de volta.</span
|
||||||
>
|
>
|
||||||
</div>
|
</div>
|
||||||
<div class="main-container sm:w-1/3">
|
<div class="main-container">
|
||||||
<div
|
<div
|
||||||
class="flex flex-col w-full bg-white px-10 py-5 rounded-lg border-y-10"
|
class="flex flex-col w-full bg-white px-10 py-5 rounded-lg border-y-10"
|
||||||
>
|
>
|
||||||
@@ -79,10 +79,6 @@ p {
|
|||||||
@apply font-medium text-base;
|
@apply font-medium text-base;
|
||||||
}
|
}
|
||||||
|
|
||||||
input[type="number"] {
|
|
||||||
-moz-appearance: textfield;
|
|
||||||
}
|
|
||||||
|
|
||||||
input[type="number"]::-webkit-inner-spin-button,
|
input[type="number"]::-webkit-inner-spin-button,
|
||||||
input[type="number"]::-webkit-outer-spin-button {
|
input[type="number"]::-webkit-outer-spin-button {
|
||||||
-webkit-appearance: none;
|
-webkit-appearance: none;
|
||||||
|
|||||||
82
src/components/ToasterComponent.vue
Normal file
82
src/components/ToasterComponent.vue
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, computed, watch, onMounted } from "vue";
|
||||||
|
import { useOnboard } from "@web3-onboard/vue";
|
||||||
|
import { Networks } from "../model/Networks";
|
||||||
|
import { useUser } from "@/composables/useUser";
|
||||||
|
|
||||||
|
const { connectedWallet } = useOnboard();
|
||||||
|
const user = useUser();
|
||||||
|
const { networkId, networkName } = user;
|
||||||
|
|
||||||
|
const isWrongNetwork = ref(false);
|
||||||
|
const targetNetworkName = computed(() => Networks[networkName.value].chainName);
|
||||||
|
|
||||||
|
const checkNetwork = () => {
|
||||||
|
if (connectedWallet.value) {
|
||||||
|
const chainId = connectedWallet.value.chains[0].id;
|
||||||
|
isWrongNetwork.value = Number(chainId) !== networkId.value;
|
||||||
|
} else {
|
||||||
|
isWrongNetwork.value = false; // No wallet connected yet
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const switchNetwork = async () => {
|
||||||
|
try {
|
||||||
|
if (connectedWallet.value && connectedWallet.value.provider) {
|
||||||
|
await connectedWallet.value.provider.request({
|
||||||
|
method: "wallet_switchEthereumChain",
|
||||||
|
params: [
|
||||||
|
{
|
||||||
|
chainId: Networks[networkName.value].chainId,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to switch network:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
onMounted(checkNetwork);
|
||||||
|
watch(connectedWallet, checkNetwork);
|
||||||
|
watch(networkId, checkNetwork, { immediate: true });
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<transition name="slide-up" appear>
|
||||||
|
<div
|
||||||
|
v-if="isWrongNetwork"
|
||||||
|
class="fixed bottom-0 left-0 right-0 bg-red-500 text-white p-4 flex justify-between items-center z-50"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<span class="font-bold">Wrong network!</span>
|
||||||
|
<span> Please switch to {{ targetNetworkName }}.</span>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
@click="switchNetwork"
|
||||||
|
class="bg-white text-red-500 px-4 py-2 rounded font-bold hover:bg-gray-100 transition-colors"
|
||||||
|
>
|
||||||
|
Switch Network
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</transition>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.slide-up-enter-active,
|
||||||
|
.slide-up-leave-active {
|
||||||
|
transition: transform 0.3s ease, opacity 0.3s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.slide-up-enter-from,
|
||||||
|
.slide-up-leave-to {
|
||||||
|
transform: translateY(100%);
|
||||||
|
opacity: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.slide-up-enter-to,
|
||||||
|
.slide-up-leave-from {
|
||||||
|
transform: translateY(0);
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { storeToRefs } from "pinia";
|
|
||||||
import { useEtherStore } from "@/store/ether";
|
|
||||||
import { ref, watch } from "vue";
|
import { ref, watch } from "vue";
|
||||||
|
import { useUser } from "@/composables/useUser";
|
||||||
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";
|
||||||
@@ -15,10 +14,9 @@ import LinkedinIcon from "@/assets/linkedinIcon.svg";
|
|||||||
import GithubIcon from "@/assets/githubIcon.svg";
|
import GithubIcon from "@/assets/githubIcon.svg";
|
||||||
import { connectProvider } from "@/blockchain/provider";
|
import { connectProvider } from "@/blockchain/provider";
|
||||||
|
|
||||||
// Store reference
|
// Use the new composable
|
||||||
const etherStore = useEtherStore();
|
const user = useUser();
|
||||||
|
const { walletAddress, sellerView, networkId } = user;
|
||||||
const { walletAddress, sellerView } = storeToRefs(etherStore);
|
|
||||||
|
|
||||||
const menuOpenToggle = ref<boolean>(false);
|
const menuOpenToggle = ref<boolean>(false);
|
||||||
const infoMenuOpenToggle = ref<boolean>(false);
|
const infoMenuOpenToggle = ref<boolean>(false);
|
||||||
@@ -38,14 +36,29 @@ 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());
|
user.setWalletAddress(addresses.shift());
|
||||||
});
|
});
|
||||||
|
|
||||||
watch(connectedChain, (newVal: any) => {
|
watch(connectedChain, (newVal: any) => {
|
||||||
etherStore.setNetworkId(newVal?.id);
|
// Check if connected chain is valid, otherwise default to Sepolia (NetworkEnum.SEPOLIA)
|
||||||
|
if (
|
||||||
|
!newVal ||
|
||||||
|
!Object.values(Networks).some(
|
||||||
|
(network) => Number(network.chainId) === Number(newVal.id)
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
console.log(
|
||||||
|
"Invalid or unsupported network detected, defaulting to Sepolia"
|
||||||
|
);
|
||||||
|
user.setNetworkId(user.networkId.value);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
user.setNetworkId(newVal?.id);
|
||||||
});
|
});
|
||||||
|
|
||||||
const formatWalletAddress = (): string => {
|
const formatWalletAddress = (): string => {
|
||||||
|
if (!walletAddress.value)
|
||||||
|
throw new Error("Wallet not connected");
|
||||||
const walletAddressLength = walletAddress.value.length;
|
const walletAddressLength = walletAddress.value.length;
|
||||||
const initialText = walletAddress.value.substring(0, 5);
|
const initialText = walletAddress.value.substring(0, 5);
|
||||||
const finalText = walletAddress.value.substring(
|
const finalText = walletAddress.value.substring(
|
||||||
@@ -56,7 +69,7 @@ const formatWalletAddress = (): string => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const disconnectUser = async (): Promise<void> => {
|
const disconnectUser = async (): Promise<void> => {
|
||||||
etherStore.setWalletAddress("");
|
user.setWalletAddress(null);
|
||||||
await disconnectWallet({ label: connectedWallet.value?.label || "" });
|
await disconnectWallet({ label: connectedWallet.value?.label || "" });
|
||||||
closeMenu();
|
closeMenu();
|
||||||
};
|
};
|
||||||
@@ -72,7 +85,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);
|
user.setNetworkId(network);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log("Error changing network", error);
|
console.log("Error changing network", error);
|
||||||
}
|
}
|
||||||
@@ -245,7 +258,7 @@ onClickOutside(infoMenuRef, () => {
|
|||||||
>
|
>
|
||||||
<img
|
<img
|
||||||
alt="Choosed network image"
|
alt="Choosed network image"
|
||||||
:src="getNetworkImage(NetworkEnum[etherStore.networkName])"
|
:src="getNetworkImage(NetworkEnum[user.networkName.value])"
|
||||||
height="24"
|
height="24"
|
||||||
width="24"
|
width="24"
|
||||||
/>
|
/>
|
||||||
@@ -253,7 +266,11 @@ 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[user.networkName.value]
|
||||||
|
? Networks[user.networkName.value].chainName
|
||||||
|
: "Invalid Chain"
|
||||||
|
}}
|
||||||
</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,35 +0,0 @@
|
|||||||
/* eslint-disable no-undef */
|
|
||||||
import { shallowMount } from "@vue/test-utils";
|
|
||||||
import TopBar from "../TopBar.vue";
|
|
||||||
import { useEtherStore } from "../../../store/ether";
|
|
||||||
|
|
||||||
import { createPinia, setActivePinia } from "pinia";
|
|
||||||
|
|
||||||
describe("TopBar.vue", () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
setActivePinia(createPinia());
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should render connect wallet button", () => {
|
|
||||||
const wrapper = shallowMount(TopBar);
|
|
||||||
expect(wrapper.html()).toContain("Conectar carteira");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should render button to change to seller view when in buyer screen", () => {
|
|
||||||
const wrapper = shallowMount(TopBar);
|
|
||||||
expect(wrapper.html()).toContain("Quero vender");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should render button to change to seller view when in buyer screen", () => {
|
|
||||||
const etherStore = useEtherStore();
|
|
||||||
etherStore.setSellerView(true);
|
|
||||||
const wrapper = shallowMount(TopBar);
|
|
||||||
expect(wrapper.html()).toContain("Quero comprar");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should render the P2Pix logo correctly", () => {
|
|
||||||
const wrapper = shallowMount(TopBar);
|
|
||||||
const img = wrapper.findAll(".logo");
|
|
||||||
expect(img.length).toBe(2);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
106
src/composables/useUser.ts
Normal file
106
src/composables/useUser.ts
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
import { ref } from "vue";
|
||||||
|
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<Address | null>(null);
|
||||||
|
const balance = ref("");
|
||||||
|
const networkId = ref(11155111);
|
||||||
|
const networkName = ref(NetworkEnum.sepolia);
|
||||||
|
const selectedToken = ref(TokenEnum.BRZ);
|
||||||
|
const loadingLock = ref(false);
|
||||||
|
const sellerView = ref(false);
|
||||||
|
const depositsValidList = ref<ValidDeposit[]>([]);
|
||||||
|
const loadingWalletTransactions = ref(false);
|
||||||
|
const loadingNetworkLiquidity = ref(false);
|
||||||
|
const seller = ref<Participant>({} as Participant);
|
||||||
|
const sellerId = ref("");
|
||||||
|
|
||||||
|
export function useUser() {
|
||||||
|
// Actions become regular functions
|
||||||
|
const setWalletAddress = (address: Address | null) => {
|
||||||
|
walletAddress.value = address;
|
||||||
|
};
|
||||||
|
|
||||||
|
const setBalance = (newBalance: string) => {
|
||||||
|
balance.value = newBalance;
|
||||||
|
};
|
||||||
|
|
||||||
|
const setSelectedToken = (token: TokenEnum) => {
|
||||||
|
selectedToken.value = token;
|
||||||
|
};
|
||||||
|
|
||||||
|
const setNetworkId = (network: string | number) => {
|
||||||
|
networkName.value = NetworkById(network) || NetworkEnum.sepolia;
|
||||||
|
networkId.value = Number(network);
|
||||||
|
};
|
||||||
|
|
||||||
|
const setLoadingLock = (isLoading: boolean) => {
|
||||||
|
loadingLock.value = isLoading;
|
||||||
|
};
|
||||||
|
|
||||||
|
const setSellerView = (view: boolean) => {
|
||||||
|
sellerView.value = view;
|
||||||
|
};
|
||||||
|
|
||||||
|
const setDepositsValidList = (deposits: ValidDeposit[]) => {
|
||||||
|
depositsValidList.value = deposits;
|
||||||
|
};
|
||||||
|
|
||||||
|
const setLoadingWalletTransactions = (isLoading: boolean) => {
|
||||||
|
loadingWalletTransactions.value = isLoading;
|
||||||
|
};
|
||||||
|
|
||||||
|
const setLoadingNetworkLiquidity = (isLoading: boolean) => {
|
||||||
|
loadingNetworkLiquidity.value = isLoading;
|
||||||
|
};
|
||||||
|
|
||||||
|
const setSeller = (newSeller: Participant) => {
|
||||||
|
seller.value = newSeller;
|
||||||
|
};
|
||||||
|
|
||||||
|
const setSellerId = (id: string) => {
|
||||||
|
sellerId.value = id;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Getters become computed or regular functions
|
||||||
|
const getValidDepositByWalletAddress = (address: string) => {
|
||||||
|
return depositsValidList.value
|
||||||
|
.filter((deposit) => deposit.seller == address)
|
||||||
|
.sort((a, b) => b.blockNumber - a.blockNumber);
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
// State
|
||||||
|
walletAddress,
|
||||||
|
balance,
|
||||||
|
networkId,
|
||||||
|
networkName,
|
||||||
|
selectedToken,
|
||||||
|
loadingLock,
|
||||||
|
sellerView,
|
||||||
|
depositsValidList,
|
||||||
|
loadingWalletTransactions,
|
||||||
|
loadingNetworkLiquidity,
|
||||||
|
seller,
|
||||||
|
sellerId,
|
||||||
|
|
||||||
|
// Actions
|
||||||
|
setWalletAddress,
|
||||||
|
setBalance,
|
||||||
|
setSelectedToken,
|
||||||
|
setNetworkId,
|
||||||
|
setLoadingLock,
|
||||||
|
setSellerView,
|
||||||
|
setDepositsValidList,
|
||||||
|
setLoadingWalletTransactions,
|
||||||
|
setLoadingNetworkLiquidity,
|
||||||
|
setSeller,
|
||||||
|
setSellerId,
|
||||||
|
|
||||||
|
// Getters
|
||||||
|
getValidDepositByWalletAddress,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
import { createApp } from "vue";
|
import { createApp } from "vue";
|
||||||
import App from "./App.vue";
|
import App from "./App.vue";
|
||||||
import router from "./router";
|
import router from "./router";
|
||||||
import { createPinia } from "pinia";
|
|
||||||
|
|
||||||
import "./assets/main.css";
|
import "./assets/main.css";
|
||||||
import "./assets/transitions.css";
|
import "./assets/transitions.css";
|
||||||
@@ -9,6 +8,5 @@ import "./assets/transitions.css";
|
|||||||
const app = createApp(App);
|
const app = createApp(App);
|
||||||
|
|
||||||
app.use(router);
|
app.use(router);
|
||||||
app.use(createPinia());
|
|
||||||
|
|
||||||
app.mount("#app");
|
app.mount("#app");
|
||||||
|
|||||||
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,6 +3,15 @@ export enum NetworkEnum {
|
|||||||
rootstock = 31,
|
rootstock = 31,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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[network] || "";
|
||||||
|
};
|
||||||
|
|
||||||
export enum TokenEnum {
|
export enum TokenEnum {
|
||||||
BRZ = "BRZ",
|
BRZ = "BRZ",
|
||||||
// BRX = 'BRX'
|
// BRX = 'BRX'
|
||||||
|
|||||||
@@ -1,5 +1,20 @@
|
|||||||
import { NetworkEnum } from "@/model/NetworkEnum";
|
import { NetworkEnum } from "@/model/NetworkEnum";
|
||||||
|
|
||||||
|
export const NetworkById = (
|
||||||
|
chainId: string | number
|
||||||
|
): NetworkEnum | undefined => {
|
||||||
|
const normalizedChainId =
|
||||||
|
typeof chainId === "number" ? chainId : Number(chainId);
|
||||||
|
|
||||||
|
for (const [network, details] of Object.entries(Networks)) {
|
||||||
|
if (Number(details.chainId) === normalizedChainId) {
|
||||||
|
return network as unknown as NetworkEnum;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
};
|
||||||
|
|
||||||
export const Networks = {
|
export const Networks = {
|
||||||
[NetworkEnum.sepolia]: {
|
[NetworkEnum.sepolia]: {
|
||||||
chainId: "0xAA36A7",
|
chainId: "0xAA36A7",
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
export type Pix = {
|
export type Pix = {
|
||||||
pixKey: string;
|
pixKey: string;
|
||||||
merchantCity?: string;
|
merchantCity?: string;
|
||||||
merchantName?: string;
|
merchantName?: string;
|
||||||
value?: number;
|
value?: number;
|
||||||
transactionId?: string;
|
transactionId?: string;
|
||||||
message?: string;
|
message?: string;
|
||||||
cep?: string;
|
cep?: string;
|
||||||
currency?: number;
|
currency?: number;
|
||||||
countryCode?: string;
|
countryCode?: string;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import type { Pix } from "./Pix";
|
import { Address } from "viem";
|
||||||
|
|
||||||
export type UnreleasedLock = {
|
export type UnreleasedLock = {
|
||||||
lockID: string;
|
lockID: bigint;
|
||||||
pix: Pix;
|
sellerAddress: Address;
|
||||||
|
tokenAddress: Address;
|
||||||
|
amount: number;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import { NetworkEnum } from "./NetworkEnum";
|
import { NetworkEnum } from "./NetworkEnum";
|
||||||
|
import type { Address } from "viem";
|
||||||
|
|
||||||
export type ValidDeposit = {
|
export type ValidDeposit = {
|
||||||
token: string;
|
token: Address;
|
||||||
blockNumber: number;
|
blockNumber: number;
|
||||||
remaining: number;
|
remaining: number;
|
||||||
seller: string;
|
seller: Address;
|
||||||
pixKey: string;
|
participantID: string;
|
||||||
network: NetworkEnum;
|
network: NetworkEnum;
|
||||||
open?: boolean;
|
open?: boolean;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
|
import type { LockStatus } from "@/model/LockStatus"
|
||||||
|
import type { Address } from "viem"
|
||||||
|
|
||||||
export type WalletTransaction = {
|
export type WalletTransaction = {
|
||||||
token: string;
|
token?: Address;
|
||||||
blockNumber: number;
|
blockNumber: number;
|
||||||
amount: number;
|
amount: number;
|
||||||
seller: string;
|
seller: string;
|
||||||
buyer: string;
|
buyer: string;
|
||||||
event: string;
|
event: string;
|
||||||
lockStatus: number;
|
lockStatus?: LockStatus;
|
||||||
transactionHash: string;
|
transactionHash: string;
|
||||||
transactionID?: string;
|
transactionID?: string;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -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,65 +0,0 @@
|
|||||||
import { NetworkEnum, TokenEnum } from "../model/NetworkEnum";
|
|
||||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
|
||||||
import type { Participant } from "../utils/bbPay";
|
|
||||||
import { defineStore } from "pinia";
|
|
||||||
|
|
||||||
export const useEtherStore = defineStore("ether", {
|
|
||||||
state: () => ({
|
|
||||||
walletAddress: "",
|
|
||||||
balance: "",
|
|
||||||
networkName: NetworkEnum.sepolia,
|
|
||||||
selectedToken: TokenEnum.BRZ,
|
|
||||||
loadingLock: false,
|
|
||||||
sellerView: false,
|
|
||||||
depositsValidList: [] as ValidDeposit[],
|
|
||||||
loadingWalletTransactions: false,
|
|
||||||
loadingNetworkLiquidity: false,
|
|
||||||
seller: {} as Participant,
|
|
||||||
sellerId: "",
|
|
||||||
}),
|
|
||||||
actions: {
|
|
||||||
setWalletAddress(walletAddress: string) {
|
|
||||||
this.walletAddress = walletAddress;
|
|
||||||
},
|
|
||||||
setBalance(balance: string) {
|
|
||||||
this.balance = balance;
|
|
||||||
},
|
|
||||||
setSelectedToken(token: TokenEnum) {
|
|
||||||
this.selectedToken = token;
|
|
||||||
},
|
|
||||||
setNetworkId(networkName: NetworkEnum) {
|
|
||||||
this.networkName = Number(networkName);
|
|
||||||
},
|
|
||||||
setLoadingLock(isLoadingLock: boolean) {
|
|
||||||
this.loadingLock = isLoadingLock;
|
|
||||||
},
|
|
||||||
setSellerView(sellerView: boolean) {
|
|
||||||
this.sellerView = sellerView;
|
|
||||||
},
|
|
||||||
setDepositsValidList(depositsValidList: ValidDeposit[]) {
|
|
||||||
this.depositsValidList = depositsValidList;
|
|
||||||
},
|
|
||||||
setLoadingWalletTransactions(isLoadingWalletTransactions: boolean) {
|
|
||||||
this.loadingWalletTransactions = isLoadingWalletTransactions;
|
|
||||||
},
|
|
||||||
setLoadingNetworkLiquidity(isLoadingNetworkLiquidity: boolean) {
|
|
||||||
this.loadingNetworkLiquidity = isLoadingNetworkLiquidity;
|
|
||||||
},
|
|
||||||
setSeller(seller: Participant) {
|
|
||||||
this.seller = seller;
|
|
||||||
},
|
|
||||||
setSellerId(sellerId: string) {
|
|
||||||
this.sellerId = sellerId;
|
|
||||||
},
|
|
||||||
},
|
|
||||||
getters: {
|
|
||||||
getValidDepositByWalletAddress: (state) => {
|
|
||||||
return (walletAddress: string) =>
|
|
||||||
state.depositsValidList
|
|
||||||
.filter((deposit) => deposit.seller == walletAddress)
|
|
||||||
.sort((a, b) => {
|
|
||||||
return b.blockNumber - a.blockNumber;
|
|
||||||
});
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
@@ -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,6 +1,6 @@
|
|||||||
export interface Participant {
|
export interface Participant {
|
||||||
offer: string;
|
offer: string;
|
||||||
fullName: string;
|
chainID: number;
|
||||||
identification: string;
|
identification: string;
|
||||||
bankIspb?: string;
|
bankIspb?: string;
|
||||||
accountType: string;
|
accountType: string;
|
||||||
@@ -15,7 +15,6 @@ export interface ParticipantWithID extends Participant {
|
|||||||
|
|
||||||
export interface Offer {
|
export interface Offer {
|
||||||
amount: number;
|
amount: number;
|
||||||
lockId: string;
|
|
||||||
sellerId: string;
|
sellerId: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,35 +22,54 @@ export interface Offer {
|
|||||||
// https://apoio.developers.bb.com.br/sandbox/spec/665797498bb48200130fc32c
|
// https://apoio.developers.bb.com.br/sandbox/spec/665797498bb48200130fc32c
|
||||||
|
|
||||||
export const createParticipant = async (participant: Participant) => {
|
export const createParticipant = async (participant: Participant) => {
|
||||||
const response = await fetch(`${process.env.VUE_APP_API_URL}/participants`, {
|
const response = await fetch(`${import.meta.env.VITE_APP_API_URL}/register`, {
|
||||||
method: "PUT",
|
method: "POST",
|
||||||
body: JSON.stringify(participant),
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
chainID: participant.chainID,
|
||||||
|
tipoDocumento: 1,
|
||||||
|
numeroDocumento: participant.identification,
|
||||||
|
numeroConta: participant.account,
|
||||||
|
numeroAgencia: participant.branch,
|
||||||
|
tipoConta: participant.accountType,
|
||||||
|
codigoIspb: participant.bankIspb,
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Error creating participant: ${response.statusText}`);
|
||||||
|
}
|
||||||
const data = await response.json();
|
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) => {
|
export const createSolicitation = async (offer: Offer) => {
|
||||||
const response = await fetch(`${process.env.VUE_APP_API_URL}/solicitation`, {
|
const response = await fetch(`${import.meta.env.VITE_APP_API_URL}/request`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: JSON.stringify(offer),
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
amount: offer.amount,
|
||||||
|
pixTarget: offer.sellerId.split("-").pop(),
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
return response.json();
|
return response.json();
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getSolicitation = async (id: string) => {
|
export const getSolicitation = async (id: string) => {
|
||||||
const response = await fetch(
|
const response = await fetch(
|
||||||
`${process.env.VUE_APP_API_URL}/solicitation/${id}`
|
`${import.meta.env.VITE_APP_API_URL}/release/${id}`
|
||||||
);
|
);
|
||||||
|
|
||||||
const obj: any = response.json();
|
const obj: any = await response.json();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: obj.numeroSolicitacao,
|
pixTarget: obj.pixTarget,
|
||||||
lockId: obj.codigoConciliacaoSolicitacao,
|
signature: obj.signature,
|
||||||
amount: obj.valorSolicitacao,
|
|
||||||
qrcode: obj.pix.textoQrCode,
|
|
||||||
status: obj.valorSomatorioPagamentosEfetivados >= obj.valorSolicitacao,
|
|
||||||
signature: obj.assinatura,
|
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -7,10 +7,19 @@ export const imagesPath = import.meta.glob<string>("@/assets/*.{png,svg}", {
|
|||||||
});
|
});
|
||||||
|
|
||||||
export const getNetworkImage = (networkName: string): string => {
|
export const getNetworkImage = (networkName: string): string => {
|
||||||
const path = Object.keys(imagesPath).find((key) =>
|
try {
|
||||||
key.endsWith(`${networkName.toLowerCase()}.svg`)
|
const path = Object.keys(imagesPath).find((key) =>
|
||||||
);
|
key.endsWith(`${networkName.toLowerCase()}.svg`)
|
||||||
return path ? imagesPath[path] : "";
|
);
|
||||||
|
return path ? imagesPath[path] : "";
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching network image");
|
||||||
|
const path = Object.keys(imagesPath).find((key) =>
|
||||||
|
key.endsWith(`invalidIcon.svg`)
|
||||||
|
);
|
||||||
|
return path ? imagesPath[path] : "";
|
||||||
|
return "";
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getTokenImage = (tokenName: TokenEnum): string => {
|
export const getTokenImage = (tokenName: TokenEnum): string => {
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import type { ValidDeposit } from "@/model/ValidDeposit";
|
import type { ValidDeposit } from "@/model/ValidDeposit";
|
||||||
|
import type { Address } from "viem";
|
||||||
|
|
||||||
const verifyNetworkLiquidity = (
|
const verifyNetworkLiquidity = (
|
||||||
tokenValue: number,
|
tokenValue: number,
|
||||||
walletAddress: string,
|
walletAddress: Address,
|
||||||
validDepositList: ValidDeposit[]
|
validDepositList: ValidDeposit[]
|
||||||
): ValidDeposit[] => {
|
): ValidDeposit[] => {
|
||||||
const filteredDepositList = validDepositList
|
const filteredDepositList = validDepositList
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -24,7 +24,6 @@ const openItem = (index: number) => {
|
|||||||
faq.value[selectedSection.value].items[index].content = marked(
|
faq.value[selectedSection.value].items[index].content = marked(
|
||||||
faq.value[selectedSection.value].items[index].content
|
faq.value[selectedSection.value].items[index].content
|
||||||
);
|
);
|
||||||
console.log(marked(faq.value[selectedSection.value].items[index].content));
|
|
||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|||||||
@@ -3,9 +3,8 @@ 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 { useUser } from "@/composables/useUser";
|
||||||
import QrCodeComponent from "@/components/QrCodeComponent.vue";
|
import QrCodeComponent from "@/components/QrCodeComponent.vue";
|
||||||
import { storeToRefs } from "pinia";
|
|
||||||
import { addLock, releaseLock } from "@/blockchain/buyerMethods";
|
import { addLock, releaseLock } from "@/blockchain/buyerMethods";
|
||||||
import { updateWalletStatus, checkUnreleasedLock } from "@/blockchain/wallet";
|
import { updateWalletStatus, checkUnreleasedLock } from "@/blockchain/wallet";
|
||||||
import { getNetworksLiquidity } from "@/blockchain/events";
|
import { getNetworksLiquidity } from "@/blockchain/events";
|
||||||
@@ -13,6 +12,7 @@ import type { ValidDeposit } from "@/model/ValidDeposit";
|
|||||||
import { getUnreleasedLockById } from "@/blockchain/events";
|
import { getUnreleasedLockById } from "@/blockchain/events";
|
||||||
import CustomAlert from "@/components/CustomAlert/CustomAlert.vue";
|
import CustomAlert from "@/components/CustomAlert/CustomAlert.vue";
|
||||||
import { getSolicitation } from "@/utils/bbPay";
|
import { getSolicitation } from "@/utils/bbPay";
|
||||||
|
import type { Address } from "viem";
|
||||||
|
|
||||||
enum Step {
|
enum Step {
|
||||||
Search,
|
Search,
|
||||||
@@ -20,13 +20,14 @@ enum Step {
|
|||||||
List,
|
List,
|
||||||
}
|
}
|
||||||
|
|
||||||
const etherStore = useEtherStore();
|
const user = useUser();
|
||||||
etherStore.setSellerView(false);
|
user.setSellerView(false);
|
||||||
|
|
||||||
// States
|
// States
|
||||||
const { loadingLock, walletAddress, networkName } = storeToRefs(etherStore);
|
const { loadingLock, walletAddress, networkName } = user;
|
||||||
const flowStep = ref<Step>(Step.Search);
|
const flowStep = ref<Step>(Step.Search);
|
||||||
const pixTarget = ref<string>();
|
const participantID = ref<string>();
|
||||||
|
const sellerAddress = ref<Address>();
|
||||||
const tokenAmount = ref<number>();
|
const tokenAmount = ref<number>();
|
||||||
const lockID = ref<string>("");
|
const lockID = ref<string>("");
|
||||||
const loadingRelease = ref<boolean>(false);
|
const loadingRelease = ref<boolean>(false);
|
||||||
@@ -38,51 +39,52 @@ const confirmBuyClick = async (
|
|||||||
selectedDeposit: ValidDeposit,
|
selectedDeposit: ValidDeposit,
|
||||||
tokenValue: number
|
tokenValue: number
|
||||||
) => {
|
) => {
|
||||||
// finish buy screen
|
participantID.value = selectedDeposit.participantID;
|
||||||
pixTarget.value = selectedDeposit.pixKey;
|
|
||||||
tokenAmount.value = tokenValue;
|
tokenAmount.value = tokenValue;
|
||||||
|
|
||||||
// Makes lock with deposit ID and the Amount
|
|
||||||
if (selectedDeposit) {
|
if (selectedDeposit) {
|
||||||
flowStep.value = Step.Buy;
|
flowStep.value = Step.Buy;
|
||||||
etherStore.setLoadingLock(true);
|
user.setLoadingLock(true);
|
||||||
|
|
||||||
await addLock(selectedDeposit.seller, selectedDeposit.token, tokenValue)
|
await addLock(selectedDeposit.seller, selectedDeposit.token, tokenValue)
|
||||||
.then((_lockID) => {
|
.then((_lockID) => {
|
||||||
lockID.value = _lockID;
|
lockID.value = String(_lockID);
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
console.log(err);
|
console.log(err);
|
||||||
flowStep.value = Step.Search;
|
flowStep.value = Step.Search;
|
||||||
});
|
});
|
||||||
|
|
||||||
etherStore.setLoadingLock(false);
|
user.setLoadingLock(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const releaseTransaction = async (lockId: string) => {
|
const releaseTransaction = async ({
|
||||||
|
pixTarget,
|
||||||
|
signature,
|
||||||
|
}: {
|
||||||
|
pixTarget: string;
|
||||||
|
signature: string;
|
||||||
|
}) => {
|
||||||
flowStep.value = Step.List;
|
flowStep.value = Step.List;
|
||||||
showBuyAlert.value = true;
|
showBuyAlert.value = true;
|
||||||
loadingRelease.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) {
|
await updateWalletStatus();
|
||||||
const release = await releaseLock(solicitation);
|
loadingRelease.value = false;
|
||||||
await release.wait();
|
|
||||||
|
|
||||||
await updateWalletStatus();
|
|
||||||
loadingRelease.value = false;
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const checkForUnreleasedLocks = async (): Promise<void> => {
|
const checkForUnreleasedLocks = async (): Promise<void> => {
|
||||||
console.log("Checking for unreleased locks");
|
if (!walletAddress.value)
|
||||||
const walletLocks = await checkUnreleasedLock(walletAddress.value);
|
throw new Error("Wallet not connected");
|
||||||
if (walletLocks) {
|
const lock = await checkUnreleasedLock(walletAddress.value);
|
||||||
lockID.value = walletLocks.lockID;
|
if (lock) {
|
||||||
tokenAmount.value = walletLocks.pix.value;
|
lockID.value = String(lock.lockID);
|
||||||
pixTarget.value = walletLocks.pix.pixKey;
|
tokenAmount.value = lock.amount;
|
||||||
|
sellerAddress.value = lock.sellerAddress;
|
||||||
showModal.value = true;
|
showModal.value = true;
|
||||||
} else {
|
} else {
|
||||||
flowStep.value = Step.Search;
|
flowStep.value = Step.Search;
|
||||||
@@ -91,11 +93,11 @@ const checkForUnreleasedLocks = async (): Promise<void> => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (paramLockID) {
|
if (paramLockID) {
|
||||||
const lockToRedirect = await getUnreleasedLockById(paramLockID as string);
|
const lockToRedirect = await getUnreleasedLockById(paramLockID);
|
||||||
if (lockToRedirect) {
|
if (lockToRedirect) {
|
||||||
lockID.value = lockToRedirect.lockID;
|
lockID.value = String(lockToRedirect.lockID);
|
||||||
tokenAmount.value = lockToRedirect.pix.value;
|
tokenAmount.value = lockToRedirect.amount;
|
||||||
pixTarget.value = lockToRedirect.pix.pixKey;
|
sellerAddress.value = lockToRedirect.sellerAddress;
|
||||||
flowStep.value = Step.Buy;
|
flowStep.value = Step.Buy;
|
||||||
} else {
|
} else {
|
||||||
flowStep.value = Step.Search;
|
flowStep.value = Step.Search;
|
||||||
@@ -138,8 +140,7 @@ onMounted(async () => {
|
|||||||
/>
|
/>
|
||||||
<div v-if="flowStep == Step.Buy">
|
<div v-if="flowStep == Step.Buy">
|
||||||
<QrCodeComponent
|
<QrCodeComponent
|
||||||
:sellerId="String(pixTarget)"
|
:lockID="lockID"
|
||||||
:amount="tokenAmount"
|
|
||||||
@pix-validated="releaseTransaction"
|
@pix-validated="releaseTransaction"
|
||||||
v-if="!loadingLock"
|
v-if="!loadingLock"
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -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 { useUser } from "@/composables/useUser";
|
||||||
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,
|
||||||
@@ -16,8 +15,8 @@ import type { WalletTransaction } from "@/model/WalletTransaction";
|
|||||||
|
|
||||||
import router from "@/router/index";
|
import router from "@/router/index";
|
||||||
|
|
||||||
const etherStore = useEtherStore();
|
const user = useUser();
|
||||||
const { walletAddress, networkName, selectedToken } = storeToRefs(etherStore);
|
const { walletAddress, networkName, selectedToken } = user;
|
||||||
const loadingWithdraw = ref<boolean>(false);
|
const loadingWithdraw = ref<boolean>(false);
|
||||||
const showAlert = ref<boolean>(false);
|
const showAlert = ref<boolean>(false);
|
||||||
|
|
||||||
@@ -47,21 +46,17 @@ const callWithdraw = async (amount: string) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const getWalletTransactions = async () => {
|
const getWalletTransactions = async () => {
|
||||||
etherStore.setLoadingWalletTransactions(true);
|
user.setLoadingWalletTransactions(true);
|
||||||
if (walletAddress.value) {
|
if (walletAddress.value) {
|
||||||
console.log("Will fetch all required data...");
|
|
||||||
const walletDeposits = await listValidDepositTransactionsByWalletAddress(
|
const walletDeposits = await listValidDepositTransactionsByWalletAddress(
|
||||||
walletAddress.value
|
walletAddress.value
|
||||||
);
|
);
|
||||||
console.log("Fetched deposits");
|
|
||||||
|
|
||||||
const allUserTransactions = await listAllTransactionByWalletAddress(
|
const allUserTransactions = await listAllTransactionByWalletAddress(
|
||||||
walletAddress.value
|
walletAddress.value
|
||||||
);
|
);
|
||||||
console.log("Fetched all transactions");
|
|
||||||
|
|
||||||
activeLockAmount.value = await getActiveLockAmount(walletAddress.value);
|
activeLockAmount.value = await getActiveLockAmount(walletAddress.value);
|
||||||
console.log("Fetched active lock amount");
|
|
||||||
|
|
||||||
if (walletDeposits) {
|
if (walletDeposits) {
|
||||||
depositList.value = walletDeposits;
|
depositList.value = walletDeposits;
|
||||||
@@ -70,7 +65,7 @@ const getWalletTransactions = async () => {
|
|||||||
transactionsList.value = allUserTransactions;
|
transactionsList.value = allUserTransactions;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
etherStore.setLoadingWalletTransactions(false);
|
user.setLoadingWalletTransactions(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import { ref } from "vue";
|
||||||
|
|
||||||
import SellerComponent from "@/components/SellerSteps/SellerComponent.vue";
|
import SellerComponent from "@/components/SellerSteps/SellerComponent.vue";
|
||||||
import SendNetwork from "@/components/SellerSteps/SendNetwork.vue";
|
import SendNetwork from "@/components/SellerSteps/SendNetwork.vue";
|
||||||
import LoadingComponent from "@/components/LoadingComponent/LoadingComponent.vue";
|
import LoadingComponent from "@/components/LoadingComponent/LoadingComponent.vue";
|
||||||
|
import { useUser } from "@/composables/useUser";
|
||||||
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,12 +15,11 @@ enum Step {
|
|||||||
Network,
|
Network,
|
||||||
}
|
}
|
||||||
|
|
||||||
const etherStore = useEtherStore();
|
const user = useUser();
|
||||||
etherStore.setSellerView(true);
|
user.setSellerView(true);
|
||||||
|
|
||||||
const flowStep = ref<Step>(Step.Sell);
|
const flowStep = ref<Step>(Step.Sell);
|
||||||
const loading = ref<boolean>(false);
|
const loading = ref<boolean>(false);
|
||||||
|
|
||||||
const showAlert = ref<boolean>(false);
|
const showAlert = ref<boolean>(false);
|
||||||
|
|
||||||
// Verificar tipagem
|
// Verificar tipagem
|
||||||
@@ -40,7 +39,7 @@ const approveOffer = async (args: Participant) => {
|
|||||||
const sendNetwork = async () => {
|
const sendNetwork = async () => {
|
||||||
loading.value = true;
|
loading.value = true;
|
||||||
try {
|
try {
|
||||||
if (etherStore.seller) {
|
if (user.seller.value) {
|
||||||
await addDeposit();
|
await addDeposit();
|
||||||
flowStep.value = Step.Sell;
|
flowStep.value = Step.Sell;
|
||||||
loading.value = false;
|
loading.value = false;
|
||||||
@@ -70,9 +69,9 @@ const sendNetwork = async () => {
|
|||||||
/>
|
/>
|
||||||
<div v-if="flowStep == Step.Network">
|
<div v-if="flowStep == Step.Network">
|
||||||
<SendNetwork
|
<SendNetwork
|
||||||
:sellerId="etherStore.sellerId"
|
:sellerId="user.sellerId.value"
|
||||||
:offer="Number(etherStore.seller.offer)"
|
:offer="Number(user.seller.value.offer)"
|
||||||
:selected-token="etherStore.selectedToken"
|
:selected-token="user.selectedToken.value"
|
||||||
v-if="!loading"
|
v-if="!loading"
|
||||||
@send-network="sendNetwork"
|
@send-network="sendNetwork"
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
"extends": "@vue/tsconfig/tsconfig.node.json",
|
"extends": "@vue/tsconfig/tsconfig.node.json",
|
||||||
"include": [
|
"include": [
|
||||||
"vite.config.*",
|
"vite.config.*",
|
||||||
"vitest.config.*",
|
|
||||||
"cypress.config.*",
|
"cypress.config.*",
|
||||||
"playwright.config.*"
|
"playwright.config.*"
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -8,13 +8,13 @@
|
|||||||
],
|
],
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"baseUrl": ".",
|
"baseUrl": ".",
|
||||||
|
"strict": true,
|
||||||
"paths": {
|
"paths": {
|
||||||
"@/*": [
|
"@/*": [
|
||||||
"./src/*"
|
"./src/*"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"types": [
|
"types": [
|
||||||
"jest",
|
|
||||||
"node"
|
"node"
|
||||||
],
|
],
|
||||||
"resolveJsonModule": true,
|
"resolveJsonModule": true,
|
||||||
@@ -27,7 +27,7 @@
|
|||||||
],
|
],
|
||||||
"preserveValueImports": false,
|
"preserveValueImports": false,
|
||||||
"importsNotUsedAsValues": "remove",
|
"importsNotUsedAsValues": "remove",
|
||||||
"verbatimModuleSyntax": true
|
"verbatimModuleSyntax": false
|
||||||
},
|
},
|
||||||
"references": [
|
"references": [
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { fileURLToPath, URL } from "node:url";
|
import { fileURLToPath, URL } from "node:url";
|
||||||
|
|
||||||
import { defineConfig } from "vitest/config";
|
import { defineConfig } from "vite";
|
||||||
import vue from "@vitejs/plugin-vue";
|
import vue from "@vitejs/plugin-vue";
|
||||||
import vueJsx from "@vitejs/plugin-vue-jsx";
|
import vueJsx from "@vitejs/plugin-vue-jsx";
|
||||||
import svgLoader from "vite-svg-loader";
|
import svgLoader from "vite-svg-loader";
|
||||||
@@ -21,21 +21,13 @@ 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()],
|
plugins: [vue(), vueJsx(), svgLoader()],
|
||||||
resolve: {
|
resolve: {
|
||||||
alias: {
|
alias: {
|
||||||
"@": fileURLToPath(new URL("./src", import.meta.url)),
|
"@": fileURLToPath(new URL("./src", import.meta.url)),
|
||||||
|
"viem/errors": fileURLToPath(
|
||||||
|
new URL("./node_modules/viem/errors", import.meta.url)
|
||||||
|
),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
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',
|
||||||
|
}),],
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user