Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat/get all balances #214

Merged
merged 20 commits into from
Oct 25, 2023
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
7f48992
feat: add service to fetch evm token balances
genaroibc Oct 10, 2023
7a38420
feat: add methods to fetch cosmos and evm token balances
genaroibc Oct 10, 2023
68adfe4
refactor: simplify types and responses
genaroibc Oct 10, 2023
462eedc
fix: change wrong import path
genaroibc Oct 10, 2023
62c6197
refactor: extract constants
genaroibc Oct 10, 2023
937b9dd
feat: filter tokens by chain ids
genaroibc Oct 11, 2023
432984a
feat: fetch native tokens balances and refactor services
genaroibc Oct 11, 2023
a48f7eb
refactor: rpc urls
genaroibc Oct 11, 2023
651d27a
feat: add service to fetch cosmos balances
genaroibc Oct 14, 2023
4134c9c
feat: add method to get cosmos balances
genaroibc Oct 14, 2023
d8e69ad
feat: return balance in wei instead of formatted
genaroibc Oct 14, 2023
0716155
feat: use cointype and derived address to fetch cosmos balances
genaroibc Oct 20, 2023
bd9dd74
feat: add method to get all balances
genaroibc Oct 24, 2023
9d29205
feat: fetch balances for evm and cosmos chains
genaroibc Oct 24, 2023
8b66179
fix: compare chain ids as strings
genaroibc Oct 24, 2023
81c5267
fix: correctly filter chains
genaroibc Oct 24, 2023
4ff3b47
Merge branch 'main' into feat/get-all-balances
genaroibc Oct 25, 2023
4ad643a
feat: return all chain balances, rename amount to balance, and return…
genaroibc Oct 25, 2023
a9c8b73
Merge branch 'feat/get-all-balances' of https://github.com/0xsquid/sq…
genaroibc Oct 25, 2023
dbc7b65
Merge branch 'main' into feat/get-all-balances
genaroibc Oct 25, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,12 @@
"release:dry": "release-it --dry-run"
},
"dependencies": {
"axios": "^0.27.2",
"ethers": "^5.7.1",
"@cosmjs/encoding": "^0.31.0",
"@cosmjs/stargate": "^0.31.0",
"cosmjs-types": "^0.8.0"
"axios": "^0.27.2",
"cosmjs-types": "^0.8.0",
"ethereum-multicall": "2.21.0",
"ethers": "^5.7.1"
},
"resolutions": {
"semver": "^7.5.4"
Expand Down
25 changes: 25 additions & 0 deletions src/constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,28 @@ export const uint256MaxValue =
"115792089237316195423570985008687907853269984665640564039457584007913129639935";

export const nativeTokenConstant = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";

export const NATIVE_EVM_TOKEN_ADDRESS =
"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
export const MULTICALL_ADDRESS = "0xcA11bde05977b3631167028862bE2a173976CA11";
export const multicallAbi = [
{
inputs: [
{
internalType: "address",
name: "account",
type: "address"
}
],
name: "getEthBalance",
outputs: [
{
internalType: "uint256",
name: "",
type: "uint256"
}
],
stateMutability: "view",
type: "function"
}
];
16 changes: 16 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { MsgExecuteContract } from "cosmjs-types/cosmwasm/wasm/v1/tx";
import { BigNumber, ethers, UnsignedTransaction } from "ethers";

import {
AllBalancesResult,
Allowance,
Approve,
ApproveRoute,
Expand All @@ -26,6 +27,7 @@ import {
RouteParamsData,
RouteResponse,
StatusResponse,
TokenBalance,
TokenData,
TransactionRequest,
ValidateBalanceAndApproval,
Expand All @@ -42,6 +44,7 @@ import { nativeTokenConstant, uint256MaxValue } from "./constants";
import { ErrorType, SquidError } from "./error";
import { getChainData, getTokenData } from "./utils";
import { setAxiosInterceptors } from "./utils/setAxiosInterceptors";
import { getAllEvmTokensBalance } from "./services/getEvmBalances";

const baseUrl = "https://testnet.api.0xsquid.com/";

Expand Down Expand Up @@ -730,6 +733,19 @@ export class Squid {

return response.data.price;
}

public async getAllEvmBalances({
genaroibc marked this conversation as resolved.
Show resolved Hide resolved
userAddress,
chains
}: {
userAddress: string;
chains: number[];
}): Promise<TokenBalance[]> {
return getAllEvmTokensBalance(
this.tokens.filter(t => chains.includes(Number(t.chainId))),
userAddress
);
}
}

export * from "./types";
197 changes: 197 additions & 0 deletions src/services/getEvmBalances.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
import { ethers } from "ethers";
import { Multicall, ContractCallContext } from "ethereum-multicall";
import { TokenBalance, TokenData } from "types";
import {
NATIVE_EVM_TOKEN_ADDRESS,
multicallAbi,
MULTICALL_ADDRESS
} from "../constants";

type ContractAddress = `0x${string}`;

const CHAINS_WITHOUT_MULTICALL = [314, 3141]; // Filecoin, & Filecoin testnet
const CHAINS_WITHOUT_MULTICALL_RPC_URLS: Record<number, string> = {
314: "https://rpc.ankr.com/filecoin",
3141: "https://rpc.ankr.com/filecoin"
};

const getTokensBalanceSupportingMultiCall = async (
tokens: TokenData[],
userAddress?: ContractAddress
): Promise<TokenBalance[]> => {
if (!userAddress) return [];

const ETHEREUM_RPC_URL = "https://eth.meowrpc.com";
const provider = new ethers.providers.JsonRpcProvider(ETHEREUM_RPC_URL);

const contractCallContext: ContractCallContext[] = tokens.map(token => {
const isNativeToken =
token.address.toLowerCase() === NATIVE_EVM_TOKEN_ADDRESS.toLowerCase();

return {
abi: isNativeToken
? multicallAbi
: [
{
name: "balanceOf",
type: "function",
inputs: [{ name: "_owner", type: "address" }],
outputs: [{ name: "balance", type: "uint256" }],
stateMutability: "view"
}
],
contractAddress: isNativeToken ? MULTICALL_ADDRESS : token.address,
reference: token.symbol,
calls: [
{
reference: isNativeToken ? "getEthBalance" : "balanceOf",
methodName: isNativeToken ? "getEthBalance" : "balanceOf",
methodParameters: [userAddress]
}
]
};
});

const multicallInstance = new Multicall({
ethersProvider: provider,
tryAggregate: true
});

const { results } = (await multicallInstance.call(contractCallContext)) ?? {
results: {}
};

const tokenBalances: TokenBalance[] = [];

for (const symbol in results) {
const data = results[symbol].callsReturnContext[0] ?? {};

const { decimals = 18, address = "0x" } =
tokens.find(t => t.symbol === symbol) ?? {};

const balanceInDecimal = ethers.utils.formatUnits(
data.returnValues[0]?.hex ?? "0x000",
decimals
);

const mappedBalance: TokenBalance = {
symbol,
address,
decimals,
balanceInDecimal
};

tokenBalances.push(mappedBalance);
}

return tokenBalances;
};

const getTokensBalanceWithoutMultiCall = async (
tokens: TokenData[],
userAddress: ContractAddress
): Promise<TokenBalance[]> => {
const balances: (TokenBalance | null)[] = await Promise.all(
tokens.map(async t => {
let balance: TokenBalance | null;
try {
if (t.address === NATIVE_EVM_TOKEN_ADDRESS) {
balance = await fetchBalance({
token: t,
userAddress
});
} else {
balance = await fetchBalance({
token: t,
userAddress
});
}

return balance;
} catch (error) {
return null;
}
})
);

// filter out null values
return balances.filter(Boolean) as TokenBalance[];
};

export const getAllEvmTokensBalance = async (
evmTokens: TokenData[],
userAddress: string
): Promise<TokenBalance[]> => {
try {
// Some tokens don't support multicall, so we need to fetch them with Promise.all
// TODO: Once we support multicall on all chains, we can remove this split
const splittedTokensByMultiCallSupport = evmTokens.reduce(
(acc, token) => {
if (CHAINS_WITHOUT_MULTICALL.includes(Number(token.chainId))) {
acc[0].push(token);
} else {
acc[1].push(token);
}
return acc;
},
[[], []] as TokenData[][]
);

const tokensNotSupportingMulticall = splittedTokensByMultiCallSupport[0];
const tokensSupportingMulticall = splittedTokensByMultiCallSupport[1];

const tokensMulticall = await getTokensBalanceSupportingMultiCall(
tokensSupportingMulticall,
userAddress as ContractAddress
);

const tokensNotMultiCall = await getTokensBalanceWithoutMultiCall(
tokensNotSupportingMulticall,
userAddress as ContractAddress
);

return [...tokensMulticall, ...tokensNotMultiCall];
} catch (error) {
console.error(error);
return [];
}
};

type FetchBalanceParams = {
token: TokenData;
userAddress: ContractAddress;
};

async function fetchBalance({
token,
userAddress
}: FetchBalanceParams): Promise<TokenBalance | null> {
try {
const provider = new ethers.providers.JsonRpcProvider(
CHAINS_WITHOUT_MULTICALL_RPC_URLS[Number(token.chainId)]
);

const tokenAbi = ["function balanceOf(address) view returns (uint256)"];
const tokenContract = new ethers.Contract(
token.address ?? "",
tokenAbi,
provider
);

const balance = await tokenContract.balanceOf(userAddress);

if (!token) return null;

const { decimals, symbol, address } = token;

return {
address,
balanceInDecimal: balance.toString(),
decimals,
symbol
};
} catch (error) {
console.error("Error fetching token balance:", error);
return null;
}
}
12 changes: 12 additions & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -503,3 +503,15 @@ export type CoinTypeAddress = {

export const IBC_TRANSFER_TYPE = "/ibc.applications.transfer.v1.MsgTransfer";
export const WASM_TYPE = "/cosmwasm.wasm.v1.MsgExecuteContract";

export type TokenBalance = {
symbol: string;
address: string;
decimals: number;
balanceInDecimal: string;
genaroibc marked this conversation as resolved.
Show resolved Hide resolved
};

export type AllBalancesResult = {
cosmosBalances: TokenBalance[];
evmBalances: TokenBalance[];
};