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 17 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"
}
];
119 changes: 118 additions & 1 deletion 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 {
ChainType,
Allowance,
Approve,
ApproveRoute,
Expand All @@ -26,11 +27,15 @@ import {
RouteParamsData,
RouteResponse,
StatusResponse,
TokenBalance,
TokenData,
TransactionRequest,
ValidateBalanceAndApproval,
WASM_TYPE,
WasmHookMsg
WasmHookMsg,
CosmosChain,
CosmosAddress,
CosmosBalance
} from "./types";

import { TxRaw } from "cosmjs-types/cosmos/tx/v1beta1/tx";
Expand All @@ -42,6 +47,8 @@ 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";
import { getCosmosBalances } from "./services/getCosmosBalances";

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

Expand Down Expand Up @@ -731,6 +738,116 @@ 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: (string | number)[];
}): Promise<TokenBalance[]> {
// remove invalid and duplicate chains and convert to number
const filteredChains = new Set(chains.map(Number).filter(c => !isNaN(c)));

return getAllEvmTokensBalance(
this.tokens.filter(t => filteredChains.has(Number(t.chainId))),
userAddress
);
}

public async getAllCosmosBalances({
addresses,
chainIds = []
}: {
addresses: CosmosAddress[];
chainIds?: (string | number)[];
}) {
const cosmosChains = this.chains.filter(c =>
c.chainType === ChainType.Cosmos &&
// if chainIds is not provided, return all cosmos chains
chainIds.length === 0
? true
: // else return only chains that are in chainIds
chainIds?.includes(c.chainId)
) as CosmosChain[];

return getCosmosBalances({
addresses,
cosmosChains
});
}

public async getAllBalances({
chainIds,
cosmosAddresses,
evmAddress
}: {
chainIds?: (string | number)[];
cosmosAddresses?: CosmosAddress[];
evmAddress?: string;
}): Promise<{
cosmosBalances?: CosmosBalance[];
evmBalances?: TokenBalance[];
}> {
if (!chainIds) {
// fetch balances for all chains compatible with provided addresses
const evmBalances = evmAddress
? await this.getAllEvmBalances({
chains: this.tokens.map(t => String(t.chainId)),
userAddress: evmAddress
})
: [];

const cosmosBalances = cosmosAddresses
? await this.getAllCosmosBalances({
addresses: cosmosAddresses
})
: [];

return {
evmBalances,
cosmosBalances
};
}

const normalizedChainIds = chainIds.map(String);

// fetch balances for provided chains
const [evmChainIds, cosmosChainIds] = this.chains.reduce(
(cosmosAndEvmChains, chain) => {
if (!normalizedChainIds.includes(String(chain.chainId))) {
return cosmosAndEvmChains;
}

if (chain.chainType === ChainType.Cosmos) {
cosmosAndEvmChains[1].push(chain.chainId);
} else {
cosmosAndEvmChains[0].push(chain.chainId);
}
return cosmosAndEvmChains;
},

[[], []] as [(string | number)[], (string | number)[]]
);

const evmBalances = evmAddress
? await this.getAllEvmBalances({
chains: evmChainIds,
userAddress: evmAddress
})
: [];

const cosmosBalances = cosmosAddresses
? await this.getAllCosmosBalances({
addresses: cosmosAddresses,
chainIds: cosmosChainIds
})
: [];

return {
evmBalances,
cosmosBalances
};

public async getFromAmount({
fromToken,
toAmount,
Expand Down
51 changes: 51 additions & 0 deletions src/services/getCosmosBalances.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { StargateClient } from "@cosmjs/stargate";
import { ChainType, CosmosAddress, CosmosBalance, CosmosChain } from "../types";
import { fromBech32, toBech32 } from "@cosmjs/encoding";

const deriveCosmosAddress = (chainPrefix: string, address: string): string => {
return toBech32(chainPrefix, fromBech32(address).data);
};

export async function getCosmosBalances({
addresses,
cosmosChains
}: {
addresses: CosmosAddress[];
cosmosChains: CosmosChain[];
}): Promise<CosmosBalance[]> {
const balances: CosmosBalance[] = [];

for (const chain of cosmosChains) {
if (chain.chainType !== ChainType.Cosmos) continue;

const addressData = addresses.find(
address => address.coinType === chain.coinType
);

if (!addressData) continue;

const cosmosAddress = deriveCosmosAddress(
chain.bech32Config.bech32PrefixAccAddr,
addressData.address
);

try {
const client = await StargateClient.connect(chain.rpc);
const [account] = (await client.getAllBalances(cosmosAddress)) ?? [];

if (!account) continue;

const { amount, denom } = account;

balances.push({
amount,
denom,
chainId: String(chain.chainId)
});
} catch (error) {
//
}
}

return balances;
}
Loading