UNPKG

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

149 lines (148 loc) 6 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.NetworkDescriptor = void 0; const decimal_js_1 = __importDefault(require("decimal.js")); const Amount_1 = require("../../utils/Amount"); const errors_1 = require("../../errors"); const RpcUrls_1 = require("../RpcUrls"); /** * Describes a blockchain network supported by ChainGate. * * Each instance carries the full network metadata and exposes the network * identifier via its {@link id} property. * * @example * ```ts * const cg = new ChainGate(); * const btc = cg.networks.bitcoin; * console.log(btc.name); // 'Bitcoin' * console.log(btc.symbol); // 'BTC' * * // Create an Amount for transfers * const amount = btc.amount('0.001'); * ``` */ class NetworkDescriptor { /** @internal */ constructor(id, info, marketsCache, apiKey) { this.id = id; this.name = info.name; this.symbol = info.symbol; this.type = info.type; this.decimals = info.decimals; this.isTestnet = info.isTestnet; this.hasOwnToken = info.hasOwnToken; this.nativeToken = info.nativeToken; this.chainId = info.chainId; this.defaultAddressType = info.defaultAddressType; this.addressTypes = info.addressTypes; this.networkParams = info.networkParams; this.marketsCache = marketsCache; this.rpcUrl = (0, RpcUrls_1.buildRpcUrl)(id, apiKey); } /** * Derives a blockchain address from a compressed public key. * * Each network subclass implements the appropriate derivation algorithm: * - **UTXO** networks: segwit, legacy, or taproot. * - **Bitcoin Cash**: CashAddr or legacy. * - **EVM** networks: EIP-55 checksummed address. * * @param publicKey - Compressed (33-byte) public key. * @param addressType - Address encoding to use. Defaults to the network's * {@link defaultAddressType}. * @returns The derived address string. */ publicKeyToAddress(publicKey, addressType) { void publicKey; void addressType; throw new errors_1.UnsupportedOperationError(`publicKeyToAddress is not implemented for network "${this.id}".`); } /** * Checks whether a string is a valid address for this network. * * Each network subclass implements the appropriate validation: * - **UTXO** networks: base58check and bech32/bech32m decoding. * - **Bitcoin Cash**: CashAddr and legacy Base58Check formats. * - **EVM** networks: hex format and EIP-55 checksum. * * @param address - The address string to validate. * @returns `true` if the address is valid for this network. */ isValidAddress(address) { void address; throw new errors_1.UnsupportedOperationError(`isValidAddress is not implemented for network "${this.id}".`); } /** * Creates an {@link Amount} in base units of the native coin * (e.g. `0.001` for 0.001 BTC, `0.1` for 0.1 ETH). * * Accepts `number`, `string`, `bigint`, or a {@link DecimalLike} instance * (e.g. `decimal.js`) for precision-safe input: * - `btc.amount(0.001)` — convenient shorthand. * - `btc.amount('0.00000001')` — full decimal precision. * - `btc.amount(1n)` — exact integer (1 whole coin). * - `btc.amount(new Decimal('0.001'))` — from a `decimal.js` instance. * * @example * ```ts * const amount = cg.networks.bitcoin.amount('0.001'); * const tx = await btc.transfer(amount, 'bc1q...'); * ``` */ amount(value) { return Amount_1.Amount.fromDecimal(value, this.decimals, this.nativeAmountData(), this.marketsCache); } /** * Creates an {@link Amount} from a fiat currency value, converting it to the * native coin at the current market rate. * * @param fiat - Fiat currency symbol, case-insensitive (e.g. `"usd"`, `"EUR"`). * @param value - The fiat amount (e.g. `50` for $50). Accepts `number`, `string`, `bigint`, or {@link DecimalLike}. * * @example * ```ts * const amount = await cg.networks.ethereum.amountFromCurrency('usd', 50); * const tx = await eth.transfer(amount, '0x...'); * ``` */ async amountFromCurrency(fiat, value) { const normalizedFiat = fiat.toLowerCase(); const markets = await this.marketsCache.fetch(); const cryptoEntry = markets.crypto.find((c) => c.id === this.id); if (!cryptoEntry) { throw new errors_1.UnsupportedOperationError(`No market data found for network "${this.id}".`); } const rateUsd = new decimal_js_1.default(cryptoEntry.nativeToken.rateUsd); let valueUsd; if (normalizedFiat === 'usd') { valueUsd = new decimal_js_1.default(value.toString()); } else { 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.`); } valueUsd = new decimal_js_1.default(value.toString()).mul(new decimal_js_1.default(fiatEntry.rateUsd)); } const cryptoBase = valueUsd.div(rateUsd); const smallest = BigInt(cryptoBase.mul(new decimal_js_1.default(10).pow(this.decimals)).toFixed(0)); return new Amount_1.Amount(smallest, this.decimals, this.nativeAmountData(), this.marketsCache); } /** Returns the network identifier string. */ toString() { return this.id; } /** @internal */ nativeAmountData() { return { symbol: this.nativeToken.symbol, name: this.nativeToken.name, network: this.id, }; } } exports.NetworkDescriptor = NetworkDescriptor;