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

Move TokenBalances Covalent route to backend #1211

Merged
merged 6 commits into from
Feb 1, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
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;
Copy link
Contributor

Choose a reason for hiding this comment

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

Is this solely a Covalent token or does this also include the response for a Coingecko call?

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
Loading