Balances
The goal of getBalances
is to resolve amounts to contracts returned previously e.g. amount
of tokens, underlyings and rewards.
Because aTokens, stable and variable debt tokens are ERC20 contracts, we can use balanceOf
method to retrieve user balances.
We can then add amount to the contract and the underlying.
import { getERC20BalanceOf } from "@lib/erc20";
async function getLendingPoolBalances(ctx: BalancesContext, contracts: Contract[]) {
const balances: Balance[] = await getERC20BalanceOf(ctx, contracts as Token[])
// use the same amount for underlyings
for (const balance of balances) {
if (balance.amount > 0n && balance.underlyings) {
balance.underlyings[0] = { ...balance.underlyings[0], amount: balance.amount }
}
}
return balances
}
Only contracts the user interacted with are passed to getBalances
.
A contract interaction is defined as follow:
- account made a transaction to this contract
- account received this token through event
"Transfer(address,address,uint256)"
In this example, this means pools
can be either undefined
(the user haven't used any of these contracts) or a subset
of pools.
To help manage undefined
values and resolve balances, we'll use resolveBalances
available in @lib/balance
.
This function maps grouped contracts to a "resolver": a function that takes contracts in and return balances (contracts + amount) out.
import { getERC20BalanceOf } from "@lib/erc20";
import { resolveBalances } from "@lib/balance";
export const getBalances: GetBalancesHandler<typeof getContracts> = async (
ctx,
contracts
) => {
const balances = await resolveBalances<typeof getContracts>(ctx, contracts, {
pools: getLendingPoolBalances,
});
return {
balances,
};
};