/** Token amount needed for route economics calculations. */ export type Amount = { /** Quantity in the token's smallest unit. */ baseUnits: string /** Monetary denomination represented by the token. */ currency: string /** Number of decimal places used by the token. */ decimals: number } /** Returns the signed basis-point difference from a reference amount. */ export function differenceBps(options: differenceBps.Options): number | undefined { if (options.reference.currency !== options.value.currency) return undefined const decimals = Math.max(options.reference.decimals, options.value.decimals) const reference = scale(options.reference, decimals) const value = scale(options.value, decimals) if (reference <= 0n) return undefined const precision = 1_000n const measured = Number(((reference - value) * 10_000n * precision) / reference) / 1_000 return Number.isFinite(measured) ? measured : undefined } export declare namespace differenceBps { /** Reference and observed values in the same monetary denomination. */ type Options = { /** Amount treated as the zero-cost reference. */ reference: Amount /** Amount compared with the reference. */ value: Amount } } /** Returns a finite USD amount, or undefined for non-USD denominations. */ export function usd(amount: Amount): number | undefined { if (amount.currency !== 'USD') return undefined return units(amount) } /** Returns a finite amount expressed in whole token units. */ export function units(amount: Amount): number | undefined { const value = Number(amount.baseUnits) / 10 ** amount.decimals return Number.isFinite(value) ? value : undefined } function scale(amount: Amount, decimals: number) { return BigInt(amount.baseUnits) * 10n ** BigInt(decimals - amount.decimals) }