UNPKG

@zebec-network/exchange-card-sdk

Version:
86 lines (85 loc) 3.05 kB
import { BigNumber } from "bignumber.js"; import { ALEO_NETWORK_CLIENT_URL } from "./constants"; /** * Convert ALGO to microAlgos * @param algos Amount in ALGO * @returns Amount in microAlgos */ export function parseAlgo(algos) { return BigInt(BigNumber(algos).times(1_000_000).toFixed(0)); } /** * Convert microAlgos to ALGO * @param microAlgos Amount in microAlgos * @returns Amount in ALGO */ export function formatAlgo(microAlgos) { return BigNumber(microAlgos).div(1_000_000).toFixed(); } /** * Convert Amount to micro-token amount (base units) * @param amount Amount in decimal units * @param decimals Number of decimals for the asset * @returns Amount in micro-token base units */ export function parseAlgorandAsset(amount, decimals) { return BigInt(BigNumber(amount).times(BigNumber(10).pow(decimals)).toFixed(0)); } /** * Convert micro-token Amount to Amount * @param microAmount Amount in micro units * @param decimals Number of decimals for the asset * @returns Amount in decimal units */ export function formatAlgorandAsset(microAmount, decimals) { return BigNumber(microAmount).div(BigNumber(10).pow(decimals)).toFixed(); } const ALGORAND_ASSET_DECIMALS_CACHE = new Map(); /** * * @param client Algod Client * @param assetId asset index of Asset * @returns */ export async function getAssetDecimals(client, assetId) { // Check if we already have this value cached if (ALGORAND_ASSET_DECIMALS_CACHE.has(assetId)) { const value = ALGORAND_ASSET_DECIMALS_CACHE.get(assetId); if (value) { return value; } else { throw new Error("Cached value is undefined, this should not happen"); } } const assetInfo = await client.getAssetByID(assetId).do(); const decimals = assetInfo.params.decimals; // Cache the result for future use ALGORAND_ASSET_DECIMALS_CACHE.set(assetId, decimals); return decimals; } /** * Convert credits to microcredits */ export function toMicroUnits(credits, decimals = 6, typeSuffix) { return `${BigNumber(credits).times(BigNumber(10).pow(decimals)).toFixed(0)}${typeSuffix || ""}`; } /** * Convert microcredits to credits */ export function fromMicroUnits(microcredits, decimals = 6) { return BigNumber(microcredits).div(BigNumber(10).pow(decimals)).toFixed(); } export async function getTokenBySymbol(tokenSymbol, network = "mainnet") { const response = await fetch(`${ALEO_NETWORK_CLIENT_URL}/${network}/tokens?symbol=${encodeURIComponent(tokenSymbol)}`); if (!response.ok) { const body = await response.text().catch(() => ""); throw new Error(`Failed to fetch token decimals for ${tokenSymbol}: ${response.statusText} ${body}`.trim()); } const result = await response.json(); const tokens = Array.isArray(result) ? result : result?.data; if (!Array.isArray(tokens) || tokens.length === 0) { throw new Error(`No token found with symbol ${tokenSymbol}`); } return tokens.find((token) => token.verified) ?? tokens[0]; }