chaingate
Version:
Multi-chain cryptocurrency SDK for TypeScript — unified API for Bitcoin, Ethereum, Litecoin, Dogecoin, Bitcoin Cash, Polygon, Arbitrum, and any EVM-compatible chain. Create wallets, query balances, send transactions, and manage tokens and NFTs across UTXO
132 lines (131 loc) • 5.34 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Amount = void 0;
const decimal_js_1 = __importDefault(require("decimal.js"));
const errors_1 = require("../errors");
class Amount {
constructor(amount, baseDecimals, data, marketsCache) {
this.amount = amount;
this.baseDecimals = baseDecimals;
this.data = data;
this.marketsCache = marketsCache;
}
/**
* Creates an Amount from a base-unit value (e.g. `0.005` BTC, `"0.00000001"` BTC).
* Converts the value to the smallest unit (e.g. satoshis, wei) internally.
*
* @param value - Amount in base units. Accepts `number`, `string`, or `bigint`.
*/
static fromDecimal(value, baseDecimals, data, marketsCache) {
const d = new decimal_js_1.default(value.toString()).mul(new decimal_js_1.default(10).pow(baseDecimals));
return new Amount(BigInt(d.toFixed(0)), baseDecimals, data, marketsCache);
}
/**
* Returns the amount in the base unit as a number (e.g. 1.5 BTC, 0.03 ETH).
*/
base() {
return new decimal_js_1.default(this.amount.toString())
.div(new decimal_js_1.default(10).pow(this.baseDecimals))
.toNumber();
}
/**
* Converts this amount to a fiat currency value using live market rates.
*
* Returns `null` when this amount represents a token (only native coins are
* supported) or when the network is not found in the market data.
*
* @param fiat - Fiat currency symbol, case-insensitive (e.g. `"usd"`, `"EUR"`, `"gbp"`).
* Use `"usd"` to get the USD value directly.
* @returns The fiat value of this amount, or `null` if the conversion cannot be performed.
*
* @throws {UnsupportedOperationError} if the fiat currency is not found in the market data.
*
* @example
* ```ts
* const cg = new ChainGate();
* const balance = await cg.explore(cg.networks.bitcoin).getAddressBalance(addr);
* const eur = await balance.confirmed.toCurrency('eur');
* if (eur !== null) {
* console.log(`${eur} EUR`);
* }
* ```
*/
async toCurrency(fiat) {
if (this.isToken) {
return null;
}
const markets = await this.marketsCache.fetch();
const normalizedFiat = fiat.toLowerCase();
// Find the crypto rate (USD) for this network
const cryptoEntry = markets.crypto.find((c) => c.id === this.data.network);
if (!cryptoEntry) {
return null;
}
const rateUsd = new decimal_js_1.default(cryptoEntry.nativeToken.rateUsd);
const baseValue = new decimal_js_1.default(this.amount.toString()).div(new decimal_js_1.default(10).pow(this.baseDecimals));
const valueUsd = baseValue.mul(rateUsd);
// If requesting USD, return directly
if (normalizedFiat === 'usd') {
return valueUsd.toNumber();
}
// Find the fiat exchange rate (relative to USD)
const fiatEntry = markets.fiat.find((f) => f.symbol === normalizedFiat);
if (!fiatEntry) {
throw new errors_1.UnsupportedOperationError(`Unsupported fiat currency "${fiat}". Currency not found in market data.`);
}
const fiatRateUsd = new decimal_js_1.default(fiatEntry.rateUsd);
// fiatRateUsd is "how many USD is 1 unit of this fiat worth"
// To convert USD → fiat: divide by fiatRateUsd
return valueUsd.div(fiatRateUsd).toNumber();
}
/**
* Returns the amount in the smallest unit as a bigint (e.g. satoshis, wei).
*/
min() {
return this.amount;
}
/** Token or coin symbol (e.g. `"ETH"`, `"USDC"`). */
get symbol() {
return this.data.symbol;
}
/** Token or coin name (e.g. `"Ether"`, `"USD Coin"`). */
get name() {
return this.data.name;
}
/** Network identifier (e.g. `"ethereum"`, `"bitcoin"`). */
get network() {
return this.data.network;
}
/** Whether this amount represents a token (has a contract address). */
get isToken() {
return this.data.contractAddress != null;
}
/** Whether this amount represents an NFT (has owned token data). */
get isNFT() {
return this.data.ownedTokens != null && this.data.ownedTokens.length > 0;
}
/**
* Token contract address. Only available when {@link isToken} is `true`.
* @throws Error if this is not a token.
*/
get contractAddress() {
if (this.data.contractAddress == null) {
throw new errors_1.UnsupportedOperationError('contractAddress is only available for tokens (isToken === true)');
}
return this.data.contractAddress;
}
/**
* Owned NFT tokens. Only available when {@link isNFT} is `true`.
* @throws Error if this is not an NFT.
*/
get ownedTokens() {
if (this.data.ownedTokens == null || this.data.ownedTokens.length === 0) {
throw new errors_1.UnsupportedOperationError('ownedTokens is only available for NFTs (isNFT === true)');
}
return this.data.ownedTokens;
}
}
exports.Amount = Amount;