Skip to content

Commit

Permalink
refactor: pools command, make helpers work both in Node.js and browser (
Browse files Browse the repository at this point in the history
  • Loading branch information
fadeev authored Oct 17, 2023
1 parent 6fb6087 commit bad7fe3
Show file tree
Hide file tree
Showing 15 changed files with 401 additions and 544 deletions.
101 changes: 101 additions & 0 deletions helpers/balances.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { getEndpoints } from "@zetachain/networks/dist/src/getEndpoints";
import networks from "@zetachain/networks/dist/src/networks";
import { getAddress } from "@zetachain/protocol-contracts";
import ZetaEth from "@zetachain/protocol-contracts/abi/evm/Zeta.eth.sol/ZetaEth.json";
import ZRC20 from "@zetachain/protocol-contracts/abi/zevm/ZRC20.sol/ZRC20.json";
import { ethers } from "ethers";
import { formatEther } from "ethers/lib/utils";

const fetchBitcoinBalance = async (address: string) => {
const API = getEndpoints("esplora", "btc_testnet")[0].url;
if (API === undefined) throw new Error("fetchBitcoinBalance: API not found");

try {
const response = await fetch(`${API}/address/${address}`);
const data = await response.json();
const { funded_txo_sum, spent_txo_sum } = data.chain_stats;
const balance = funded_txo_sum - spent_txo_sum;
return {
native: `${balance / 100000000}`,
networkName: "btc_testnet",
};
} catch (error) {}
};

const fetchNativeBalance = async (address: string, provider: any) => {
const balance = await provider.getBalance(address);
return parseFloat(formatEther(balance)).toFixed(2);
};

const fetchZetaBalance = async (
address: string,
provider: any,
networkName: string
) => {
if (networkName === "zeta_testnet") return "";
const zetaAddress = getAddress("zetaToken", networkName as any);
const contract = new ethers.Contract(zetaAddress, ZetaEth.abi, provider);
const balance = await contract.balanceOf(address);
return parseFloat(formatEther(balance)).toFixed(2);
};

const fetchBalances = async (
address: string,
provider: any,
networkName: string
) => {
try {
const native = await fetchNativeBalance(address, provider);
const zeta = await fetchZetaBalance(address, provider, networkName);
const isZeta = networkName === "zeta_testnet";
const zrc20 = isZeta ? { zrc20: await fetchZRC20Balance(address) } : {};
/* eslint-disable */
return { networkName, native, zeta, ...zrc20 };
/* eslint-enable */
} catch (error) {}
};

const fetchZRC20Balance = async (address: string) => {
const api = getEndpoints("evm", "zeta_testnet");
if (api.length < 1) return;
const rpc = api[0].url;
const provider = new ethers.providers.JsonRpcProvider(rpc);
const promises = Object.keys(networks).map(async (networkName) => {
try {
const zrc20 = getAddress("zrc20", networkName);
const contract = new ethers.Contract(zrc20, ZRC20.abi, provider);
const balance = await contract.balanceOf(address);
const denom = networks[networkName].assets[0].symbol;
if (balance > 0) {
const b = parseFloat(formatEther(balance)).toFixed(2);
return `${b} ${denom}`;
}
} catch (error) {}
});

const result = await Promise.all(promises);

// tBTC ZRC-20 balance
const btcZRC20 = "0x65a45c57636f9BcCeD4fe193A602008578BcA90b"; // TODO: use getAddress("zrc20", "btc_testnet") when available
const contract = new ethers.Contract(btcZRC20, ZRC20.abi, provider);
const balance = (await contract.balanceOf(address)) / 100000000;
if (balance > 0) {
result.push(`${balance} tBTC`);
}

return result.filter((item) => item !== undefined).join(", ");
};

export const getBalances = async (address, btc_address = null) => {
const balancePromises = Object.keys(networks).map((networkName) => {
const api = getEndpoints("evm", networkName as any);
if (api.length >= 1) {
const rpc = api[0].url;
const provider = new ethers.providers.JsonRpcProvider(rpc);
return fetchBalances(address, provider, networkName);
}
});
const balances = await Promise.all(balancePromises);
if (btc_address) balances.push(await fetchBitcoinBalance(btc_address));
return balances.filter((balance) => balance != null);
};
109 changes: 0 additions & 109 deletions helpers/evm.ts

This file was deleted.

17 changes: 9 additions & 8 deletions helpers/fees.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { getEndpoints } from "@zetachain/networks";
import { getHardhatConfigNetworks } from "@zetachain/networks";
import { getEndpoints } from "@zetachain/networks/dist/src/getEndpoints";
import networks from "@zetachain/networks/dist/src/networks";
import { getAddress } from "@zetachain/protocol-contracts";
import ZRC20 from "@zetachain/protocol-contracts/abi/zevm/ZRC20.sol/ZRC20.json";
import axios from "axios";
import { ethers } from "ethers";
import { formatEther } from "ethers/lib/utils";
import fetch from "isomorphic-fetch";

const formatTo18Decimals = (n: any) => parseFloat(formatEther(n)).toFixed(18);

export const fetchZEVMFees = async (network: string) => {
const { url } = getHardhatConfigNetworks()["zeta_testnet"] as any;
const url = getEndpoints("evm", "zeta_testnet")[0].url;

const provider = new ethers.providers.JsonRpcProvider(url);
const btcZRC20 = "0x65a45c57636f9BcCeD4fe193A602008578BcA90b"; // TODO: use getAddress("zrc20", "btc_testnet") when available
Expand Down Expand Up @@ -37,10 +37,11 @@ export const fetchCCMFees = async (network: string, gas: Number = 500000) => {
throw new Error("getEndpoints: API endpoint not found");
}

const chainID = getHardhatConfigNetworks()[network].chainId;
const chainID = networks[network as keyof typeof networks]?.chain_id;

const url = `${API}/zeta-chain/crosschain/convertGasToZeta?chainId=${chainID}&gasLimit=${gas}`;
const { data } = await axios.get(url);
const response = await fetch(url);
const data = await response.json();

const gasFee = ethers.BigNumber.from(data.outboundGasInZeta);
const protocolFee = ethers.BigNumber.from(data.protocolFeeInZeta);
Expand All @@ -59,10 +60,10 @@ export const fetchFees = async (gas: Number) => {
feesZEVM: {} as Record<string, any>,
};

const networks = [...Object.keys(getHardhatConfigNetworks()), "btc_testnet"];
const networkList = [...Object.keys(networks), "btc_testnet"];

await Promise.all(
networks.map(async (n) => {
networkList.map(async (n) => {
try {
const zevmFees = await fetchZEVMFees(n);
if (zevmFees) fees.feesZEVM[n] = zevmFees;
Expand Down
76 changes: 0 additions & 76 deletions helpers/helpers.ts

This file was deleted.

4 changes: 2 additions & 2 deletions helpers/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export * from "./evm";
export * from "./balances";
export * from "./fees";
export * from "./helpers";
export * from "./pools";
export * from "./tx";
54 changes: 54 additions & 0 deletions helpers/pools.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import UniswapV2Factory from "@uniswap/v2-core/build/UniswapV2Factory.json";
import UniswapV2Pair from "@uniswap/v2-core/build/UniswapV2Pair.json";
import { getEndpoints } from "@zetachain/networks/dist/src/getEndpoints";
import { getAddress } from "@zetachain/protocol-contracts";
import { ethers } from "ethers";
import fetch from "isomorphic-fetch";

export const getPools = async () => {
const api = getEndpoints("cosmos-http", "zeta_testnet")[0]?.url;
const endpoint = `${api}/zeta-chain/zetacore/fungible/foreign_coins`;
const response = await fetch(endpoint);
const data = await response.json();

const rpc = getEndpoints("evm", "zeta_testnet")[0]?.url;
const provider = new ethers.providers.JsonRpcProvider(rpc);

const uniswapV2FactoryAddress = getAddress(
"uniswapv2Factory",
"zeta_testnet"
);
const zetaTokenAddress = getAddress("zetaToken", "zeta_testnet");

const UniswapV2FactoryContract = new ethers.Contract(
uniswapV2FactoryAddress,
UniswapV2Factory.abi,
provider
);

const poolPromises = data.foreignCoins.map(async (token: any) => {
const zrc20Address = token.zrc20_contract_address;
const pair = await UniswapV2FactoryContract.getPair(
zrc20Address,
zetaTokenAddress
);

let reservesZRC20 = "0";
let reservesZETA = "0";

if (pair !== ethers.constants.AddressZero) {
const uniswapPairContract = new ethers.Contract(
pair,
UniswapV2Pair.abi,
provider
);
const reserves = await uniswapPairContract.getReserves();
reservesZRC20 = ethers.utils.formatEther(reserves[0]);
reservesZETA = ethers.utils.formatEther(reserves[1]);
}
return { ...token, reservesZETA, reservesZRC20 };
});

const pools = await Promise.all(poolPromises);
return pools;
};
Loading

0 comments on commit bad7fe3

Please sign in to comment.