zerion-sdk
Version:
A Typed Interface for ZerionAPI
86 lines (85 loc) • 3.29 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.NATIVE_ASSET = void 0;
exports.buildQueryString = buildQueryString;
exports.polygonNativeAssetImplementation = polygonNativeAssetImplementation;
exports.scientificToDecimal = scientificToDecimal;
exports.zerionToTokenBalance = zerionToTokenBalance;
exports.zerionToTokenBalances = zerionToTokenBalances;
exports.isNativeAsset = isNativeAsset;
const viem_1 = require("viem");
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function buildQueryString(params) {
const query = {};
for (const [key, value] of Object.entries(params)) {
if (value === undefined || value === null)
continue; // Skip undefined or null values
if (Array.isArray(value)) {
query[key] = value.join(","); // Join arrays with commas
}
else {
query[key] = value.toString();
}
}
return new URLSearchParams(query).toString();
}
function polygonNativeAssetImplementation() {
// Skip Recognition of MRC20 Token Contract:
// https://polygonscan.com/address/0x0000000000000000000000000000000000001010
// This token has a payable transfer function and messes shit up.
return [
{
chain_id: "polygon",
address: null,
decimals: 18,
},
];
}
function scientificToDecimal(num) {
// If not in scientific notation, return as is
if (!/^\d+\.?\d*e[+-]*\d+$/i.test(num.toString())) {
return num.toString();
}
const parts = num.toString().toLowerCase().split("e");
const mantissa = parts[0];
const exponent = parseInt(parts[1], 10);
// Remove decimal point from mantissa if exists
const [whole = "", decimal = ""] = mantissa.split(".");
const mantissaWithoutPoint = whole + decimal;
if (exponent > 0) {
const zerosToAdd = exponent - decimal.length;
return mantissaWithoutPoint + "0".repeat(Math.max(0, zerosToAdd));
}
else {
const absExponent = Math.abs(exponent);
return `0.${"0".repeat(absExponent - 1)}${mantissaWithoutPoint}`;
}
}
function zerionToTokenBalance(userToken) {
const { meta, balances } = userToken;
const chainId = userToken.chain.chainId;
return {
...(chainId ? { chainId } : {}),
tokenAddress: meta.contractAddress || null,
token: {
name: meta.name,
symbol: meta.symbol,
decimals: meta.decimals,
logoUri: meta.tokenIcon || "",
},
balance: (0, viem_1.parseUnits)(scientificToDecimal(balances.balance), meta.decimals).toString(),
fiatBalance: balances.usdBalance.toFixed(2),
fiatConversion: (balances.price || 0).toFixed(2),
};
}
// Helper function to convert array of UserTokens to TokenBalances
function zerionToTokenBalances(userTokens) {
return userTokens
.filter((token) => !token.meta.isSpam) // Filter out spam tokens
.map(zerionToTokenBalance);
}
// CoW (and many other Dex Protocols use this to represent native asset).
exports.NATIVE_ASSET = (0, viem_1.getAddress)("0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE");
function isNativeAsset(token) {
return token.toLowerCase() === exports.NATIVE_ASSET.toLowerCase();
}