Skip to content

Commit

Permalink
Move TokenBalances Covalent route to backend (#1211)
Browse files Browse the repository at this point in the history
* replace covalant tokenBalance route with backend api

* point development backend url to staging

* fix lint errors

* update the Query for token fetching

* resolved updateAt comment
  • Loading branch information
sepehr2github authored Feb 1, 2024
1 parent 208ce6d commit 236fc32
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 68 deletions.
33 changes: 10 additions & 23 deletions src/services/token/domain/covalent-token.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,14 @@
export type CovalentBaseToken = {
contract_decimals: number;
contract_name: string;
contract_ticker_symbol: string;
contract_address: string;
logo_url: string;
export type TokenItemType = {
balance: string;
contractAddress: string;
contractDecimals: number;
contractName: string;
contractTickerSymbol: string;
logoUrl: string;
nativeToken: boolean;
};

export type CovalentTokenBalance = {
export type TokenBalanceResponse = {
updated_at: string;
items: Array<
CovalentBaseToken & {
native_token: boolean;
nft_data: CovalentNFTData;

// this is BigInt value that needs to be adjusted using the
// decimals for human-friendly display
balance: string;
}
>;
};

// TODO: flesh this out when NFT support
// has been added
type CovalentNFTData = {
token_id: string;
items: Array<TokenItemType>;
};
107 changes: 62 additions & 45 deletions src/services/token/token-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {getTokenInfo, isNativeToken} from 'utils/tokens';
import {CoingeckoError, Token} from './domain';
import {AlchemyTransfer} from './domain/alchemy-transfer';
import {CovalentResponse} from './domain/covalent-response';
import {CovalentTokenBalance} from './domain/covalent-token';
import {TokenBalanceResponse} from './domain/covalent-token';
import {
CovalentTokenTransfer,
CovalentTransferInfo,
Expand Down Expand Up @@ -141,6 +141,31 @@ class TokenService {
return token;
};

tokenBalanceQueryDocument = gql`
query TokensBalances(
$currency: String!
$network: Network!
$address: String!
) {
tokensBalances(
currency: $currency
network: $network
address: $address
) {
updatedAt
items {
contractAddress
contractName
contractTickerSymbol
contractDecimals
logoUrl
nativeToken
balance
}
}
}
`;

// Note: Purposefully not including a function to fetch token balances
// via Alchemy because we want to slowly remove the Alchemy dependency
// F.F. [01/01/2023]
Expand All @@ -150,9 +175,7 @@ class TokenService {
ignoreZeroBalances = true,
nativeTokenBalance,
}: IFetchTokenBalancesParams): Promise<AssetBalance[] | null> => {
const {networkId} = CHAIN_METADATA[network].covalent ?? {};

if (!networkId) {
if (!network) {
console.info(
`fetchTokenBalances - network ${network} not supported by Covalent`
);
Expand All @@ -161,53 +184,47 @@ class TokenService {

const {nativeCurrency} = CHAIN_METADATA[network];

const endpoint = `/${networkId}/address/${address}/balances_v2/?quote-currency=${this.defaultCurrency}`;
const url = `${this.baseUrl.covalent}${endpoint}`;
const authToken = window.btoa(`${COVALENT_API_KEY}:`);
const headers = {Authorization: `Basic ${authToken}`};

const res = await fetch(url, {headers});
const parsed: CovalentResponse<CovalentTokenBalance | null> =
await res.json();
const data = parsed.data;
const {tokensBalances: data} = await request(
aragonGateway.backendUrl,
this.tokenBalanceQueryDocument,
{network, address, currency: this.defaultCurrency}
);

if (parsed.error || data == null) {
if (data.error || data == null) {
console.info(
`fetchTokenBalances - Covalent returned error: ${parsed.error_message}`
`fetchTokenBalances - Covalent returned error: ${data.error_message}`
);
return null;
}

return data.items.flatMap(({native_token, ...item}) => {
if (
ignoreZeroBalances &&
((native_token && nativeTokenBalance === BigInt(0)) ||
BigNumber.from(item.balance).isZero())
)
// ignore zero balances if indicated
return [];

return {
id: native_token ? AddressZero : item.contract_address,
address: native_token ? AddressZero : item.contract_address,
name: native_token ? nativeCurrency.name : item.contract_name,
symbol: native_token
? nativeCurrency.symbol
: item.contract_ticker_symbol?.toUpperCase(),
decimals: native_token
? nativeCurrency.decimals
: item.contract_decimals,
type: (native_token
? TokenType.NATIVE
: item.nft_data
? TokenType.ERC721
: TokenType.ERC20) as tokenType,
balance: native_token
? (nativeTokenBalance as bigint)
: BigInt(item.balance),
updateDate: new Date(data.updated_at),
};
});
return (data as TokenBalanceResponse).items.flatMap(
({nativeToken, ...item}) => {
if (
ignoreZeroBalances &&
((nativeToken && nativeTokenBalance === BigInt(0)) ||
BigNumber.from(item.balance).isZero())
)
// ignore zero balances if indicated
return [];

return {
id: nativeToken ? AddressZero : item.contractAddress,
address: nativeToken ? AddressZero : item.contractAddress,
name: nativeToken ? nativeCurrency.name : item.contractName,
symbol: nativeToken
? nativeCurrency.symbol
: item.contractTickerSymbol?.toUpperCase(),
decimals: nativeToken
? nativeCurrency.decimals
: item.contractDecimals,
type: (nativeToken ? TokenType.NATIVE : TokenType.ERC20) as tokenType,
balance: nativeToken
? (nativeTokenBalance as bigint)
: BigInt(item.balance),
updateDate: new Date(data.updatedAt),
};
}
);
};

fetchErc20Deposits = async ({
Expand Down

0 comments on commit 236fc32

Please sign in to comment.