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 v2/get all balances #228

Merged
merged 9 commits into from
Oct 30, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
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
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@
"@ethersproject/abstract-signer": "^5.7.0",
"axios": "^1.5.0",
"cosmjs-types": "^0.8.0",
"ethereum-multicall": "^2.21.0",
genaroibc marked this conversation as resolved.
Show resolved Hide resolved
"ethers": "6.7.1",
"ethers-multicall-provider": "^5.0.0",
"lodash": "^4.17.21"
},
"resolutions": {
Expand Down
24 changes: 24 additions & 0 deletions src/constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,27 @@ 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"
}
];
127 changes: 126 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import {
RouteResponse,
StatusResponse,
EvmWallet,
Token
Token,
TokenBalance,
CosmosAddress,
CosmosChain,
CosmosBalance
} from "./types";

import HttpAdapter from "./adapter/HttpAdapter";
Expand All @@ -22,6 +26,8 @@ import { TokensChains } from "./TokensChains";
import { EvmHandler, CosmosHandler } from "./handlers";

import erc20Abi from "./abi/erc20.json";
import { getAllEvmTokensBalance } from "./services/getEvmBalances";
import { getCosmosBalances } from "./services/getCosmosBalances";

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

Expand Down Expand Up @@ -301,4 +307,123 @@ export class Squid extends TokensChains {

return fromAmountPlusSlippage.toString();
}

public async getAllEvmBalances({
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)));
const chainRpcUrls = this.chains.reduce(
(acc, chain) => ({
...acc,
[chain.chainId]: chain.rpc
}),
{}
);

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

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
};
}
}
56 changes: 56 additions & 0 deletions src/services/getCosmosBalances.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
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 cosmosBalances: 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 balances = (await client.getAllBalances(cosmosAddress)) ?? [];

if (balances.length === 0) continue;

balances.forEach(balance => {
const { amount, denom } = balance;

cosmosBalances.push({
balance: amount,
denom,
chainId: String(chain.chainId),
decimals:
chain.currencies.find(currency => currency.coinDenom === denom)
?.coinDecimals ?? 6
});
});
} catch (error) {
//
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

left to return empty array

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After the try-catch block, it returns cosmosBalances, which is an empty array by default:

const cosmosBalances: CosmosBalance[] = [];

}
}

return cosmosBalances;
}
Loading