UNPKG

@wuwei-labs/srsly

Version:
76 lines 3.08 kB
"use strict"; /** * @purpose SOL parameter conversion utilities * * Converts user-friendly SOL amounts to lamports (smallest unit) for use with Solana programs. * 1 SOL = 1,000,000,000 lamports (9 decimal places) */ Object.defineProperty(exports, "__esModule", { value: true }); exports.convertSol = convertSol; /** * Lamports per SOL (9 decimal places) */ const LAMPORTS_PER_SOL = 1_000_000_000; const MAX_U64 = 18446744073709551615n; /** * Convert SOL parameter to lamports (smallest unit) * * @param amount - Amount in any supported format * @returns Amount in lamports as bigint (u64 for Solana program) * @throws Error if amount is invalid, negative, or non-integer lamports * * @example * ```typescript * convertSol(10_000_000) // 10_000_000n lamports (0.01 SOL) * convertSol({ sol: 0.1 }) // 100_000_000n lamports (0.1 SOL) * convertSol({ lamports: 10_000_000 }) // 10_000_000n lamports * ``` */ function convertSol(amount) { // Bare number / bigint — treat as lamports. if (typeof amount === 'number' || typeof amount === 'bigint') { return toLamportsBigInt(amount, 'lamports'); } if (typeof amount !== 'object' || amount === null) { throw new Error(`Invalid SOL amount type. Expected number, bigint, or object. Got: ${typeof amount}`); } if ('sol' in amount && amount.sol !== undefined) { if (amount.sol < 0) { throw new Error(`SOL amount must be non-negative, got ${amount.sol}`); } return toLamportsBigInt(amount.sol * LAMPORTS_PER_SOL, 'sol'); } if ('lamports' in amount && amount.lamports !== undefined) { return toLamportsBigInt(amount.lamports, 'lamports'); } throw new Error(`Invalid SOL amount format. Expected number, bigint, { sol: number }, or { lamports: number | bigint }. ` + `Got: ${JSON.stringify(amount)}`); } function toLamportsBigInt(raw, unit) { if (typeof raw === 'bigint') { if (raw < 0n) throw new Error(`Amount must be non-negative, got ${raw}`); if (raw > MAX_U64) throw new Error(`Amount too large. Max u64: ${MAX_U64}, got: ${raw}`); return raw; } if (!Number.isFinite(raw)) { throw new Error(`Amount must be a finite number, got ${raw}`); } if (raw < 0) { throw new Error(`Amount must be non-negative, got ${raw}`); } // Bare numbers + { lamports } must be integers (lamports are atomic). // The `{ sol: ... }` path arrives here already multiplied by 1e9 — round // down to absorb floating-point drift like 0.1 * 1e9 → 99999999.99999999. const value = unit === 'sol' ? Math.round(raw) : raw; if (!Number.isInteger(value)) { throw new Error(`Lamports must be a whole number, got ${raw}. ` + `For sub-lamport precision use \`{ sol: ${raw / LAMPORTS_PER_SOL} }\` instead.`); } const big = BigInt(value); if (big > MAX_U64) throw new Error(`Amount too large. Max u64: ${MAX_U64}, got: ${big}`); return big; } //# sourceMappingURL=sol.js.map