@lifi/sdk
Version:
LI.FI Any-to-Any Cross-Chain-Swap SDK
72 lines • 3.13 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getWalletBalances = exports.getTokenBalance = void 0;
exports.getTokenBalances = getTokenBalances;
exports.getTokenBalancesByChain = getTokenBalancesByChain;
const config_js_1 = require("../config.js");
const errors_js_1 = require("../errors/errors.js");
const request_js_1 = require("../request.js");
const typeguards_js_1 = require("../typeguards.js");
const getTokenBalance = async (walletAddress, token) => {
const tokenAmounts = await getTokenBalances(walletAddress, [token]);
return tokenAmounts.length ? tokenAmounts[0] : null;
};
exports.getTokenBalance = getTokenBalance;
async function getTokenBalances(walletAddress, tokens) {
const tokensByChain = tokens.reduce((tokens, token) => {
if (!tokens[token.chainId]) {
tokens[token.chainId] = [];
}
tokens[token.chainId].push(token);
return tokens;
}, {});
const tokenAmountsByChain = await getTokenBalancesByChain(walletAddress, tokensByChain);
return Object.values(tokenAmountsByChain).flat();
}
async function getTokenBalancesByChain(walletAddress, tokensByChain) {
if (!walletAddress) {
throw new errors_js_1.ValidationError('Missing walletAddress.');
}
const tokenList = Object.values(tokensByChain).flat();
const invalidTokens = tokenList.filter((token) => !(0, typeguards_js_1.isToken)(token));
if (invalidTokens.length) {
throw new errors_js_1.ValidationError('Invalid tokens passed.');
}
const provider = config_js_1.config
.get()
.providers.find((provider) => provider.isAddress(walletAddress));
if (!provider) {
throw new Error(`SDK Token Provider for ${walletAddress} is not found.`);
}
const tokenAmountsByChain = {};
const tokenAmountsSettled = await Promise.allSettled(Object.keys(tokensByChain).map(async (chainIdStr) => {
const chainId = Number.parseInt(chainIdStr, 10);
const chain = await config_js_1.config.getChainById(chainId);
if (provider.type === chain.chainType) {
const tokenAmounts = await provider.getBalance(walletAddress, tokensByChain[chainId]);
tokenAmountsByChain[chainId] = tokenAmounts;
}
else {
tokenAmountsByChain[chainId] = tokensByChain[chainId];
}
}));
if (config_js_1.config.get().debug) {
for (const result of tokenAmountsSettled) {
if (result.status === 'rejected') {
console.warn("Couldn't fetch token balance.", result.reason);
}
}
}
return tokenAmountsByChain;
}
const getWalletBalances = async (walletAddress, options) => {
if (!walletAddress) {
throw new errors_js_1.ValidationError('Missing walletAddress.');
}
const response = await (0, request_js_1.request)(`${config_js_1.config.get().apiUrl}/wallets/${walletAddress}/balances?extended=true`, {
signal: options?.signal,
});
return (response?.balances || {});
};
exports.getWalletBalances = getWalletBalances;
//# sourceMappingURL=balance.js.map