|
| 1 | +import { BinaryParser } from '../serdes/binary-parser' |
| 2 | +import { SerializedType } from './serialized-type' |
| 3 | +import { writeInt32BE, writeInt64BE, readInt32BE, readInt64BE } from '../utils' |
| 4 | + |
| 5 | +/** |
| 6 | + * Constants for mantissa and exponent normalization per XRPL Number spec. |
| 7 | + * These define allowed magnitude for mantissa and exponent after normalization. |
| 8 | + */ |
| 9 | +const MIN_MANTISSA = BigInt('1000000000000000') |
| 10 | +const MAX_MANTISSA = BigInt('9999999999999999') |
| 11 | +const MIN_EXPONENT = -32768 |
| 12 | +const MAX_EXPONENT = 32768 |
| 13 | +const DEFAULT_VALUE_EXPONENT = -2147483648 |
| 14 | + |
| 15 | +/** |
| 16 | + * Extract mantissa, exponent, and sign from a number string. |
| 17 | + * |
| 18 | + * @param val - The string representing the number (may be integer, decimal, or scientific notation). |
| 19 | + * @returns Object containing mantissa (BigInt), exponent (number), and isNegative (boolean). |
| 20 | + * @throws Error if the string cannot be parsed as a valid number. |
| 21 | + * |
| 22 | + * Examples: |
| 23 | + * '123' -> { mantissa: 123n, exponent: 0, isNegative: false } |
| 24 | + * '-00123.45' -> { mantissa: -12345n, exponent: -2, isNegative: true } |
| 25 | + * '+7.1e2' -> { mantissa: 71n, exponent: -1 + 2 = 1, isNegative: false } |
| 26 | + */ |
| 27 | +function extractNumberPartsFromString(val: string): { |
| 28 | + mantissa: bigint |
| 29 | + exponent: number |
| 30 | + isNegative: boolean |
| 31 | +} { |
| 32 | + /** |
| 33 | + * Regex for parsing decimal/float/scientific number strings with optional sign, integer, decimal, and exponent parts. |
| 34 | + * |
| 35 | + * Pattern: /^([-+]?)([0-9]+)(?:\.([0-9]+))?(?:[eE]([+-]?[0-9]+))?$/ |
| 36 | + * |
| 37 | + * Breakdown: |
| 38 | + * 1. ([-+]?) - Optional '+' or '-' sign at the start. |
| 39 | + * 2. ([0-9]+) - Integer part: one or more digits (leading zeros allowed). |
| 40 | + * 3. (?:\.([0-9]+))? - Optional decimal point followed by one or more digits. |
| 41 | + * 4. (?:[eE]([+-]?[0-9]+))? - Optional exponent, starting with 'e' or 'E', optional sign, and digits. |
| 42 | + * |
| 43 | + * Notes: |
| 44 | + * - Leading zeros are accepted and normalized by code after parsing. |
| 45 | + * - Empty decimal ('123.') and missing integer ('.456') are NOT matched—must be fully specified. |
| 46 | + */ |
| 47 | + const regex = /^([-+]?)([0-9]+)(?:\.([0-9]+))?(?:[eE]([+-]?[0-9]+))?$/ |
| 48 | + const match = regex.exec(val) |
| 49 | + if (!match) throw new Error(`Unable to parse number from string: ${val}`) |
| 50 | + |
| 51 | + const [, sign, intPart, fracPart, expPart] = match |
| 52 | + // Remove leading zeros (unless the entire intPart is zeros) |
| 53 | + const cleanIntPart = intPart.replace(/^0+(?=\d)/, '') || '0' |
| 54 | + |
| 55 | + let mantissaStr = cleanIntPart |
| 56 | + let exponent = 0 |
| 57 | + |
| 58 | + if (fracPart) { |
| 59 | + mantissaStr += fracPart |
| 60 | + exponent -= fracPart.length |
| 61 | + } |
| 62 | + if (expPart) exponent += parseInt(expPart, 10) |
| 63 | + |
| 64 | + let mantissa = BigInt(mantissaStr) |
| 65 | + if (sign === '-') mantissa = -mantissa |
| 66 | + const isNegative = mantissa < BigInt(0) |
| 67 | + |
| 68 | + return { mantissa, exponent, isNegative } |
| 69 | +} |
| 70 | + |
| 71 | +/** |
| 72 | + * Normalize the mantissa and exponent to XRPL constraints. |
| 73 | + * |
| 74 | + * Ensures that after normalization, the mantissa is between MIN_MANTISSA and MAX_MANTISSA (unless zero). |
| 75 | + * Adjusts the exponent as needed by shifting the mantissa left/right (multiplying/dividing by 10). |
| 76 | + * |
| 77 | + * @param mantissa - The unnormalized mantissa (BigInt). |
| 78 | + * @param exponent - The unnormalized exponent (number). |
| 79 | + * @returns An object with normalized mantissa and exponent. |
| 80 | + * @throws Error if the number cannot be normalized within allowed exponent range. |
| 81 | + */ |
| 82 | +function normalize( |
| 83 | + mantissa: bigint, |
| 84 | + exponent: number, |
| 85 | +): { mantissa: bigint; exponent: number } { |
| 86 | + let m = mantissa < BigInt(0) ? -mantissa : mantissa |
| 87 | + const isNegative = mantissa < BigInt(0) |
| 88 | + |
| 89 | + while (m !== BigInt(0) && m < MIN_MANTISSA && exponent > MIN_EXPONENT) { |
| 90 | + exponent -= 1 |
| 91 | + m *= BigInt(10) |
| 92 | + } |
| 93 | + while (m > MAX_MANTISSA) { |
| 94 | + if (exponent >= MAX_EXPONENT) |
| 95 | + throw new Error('Mantissa and exponent are too large') |
| 96 | + exponent += 1 |
| 97 | + m /= BigInt(10) |
| 98 | + } |
| 99 | + if (isNegative) m = -m |
| 100 | + return { mantissa: m, exponent } |
| 101 | +} |
| 102 | + |
| 103 | +/** |
| 104 | + * STNumber: Encodes XRPL's "Number" type. |
| 105 | + * |
| 106 | + * - Always encoded as 12 bytes: 8-byte signed mantissa, 4-byte signed exponent, both big-endian. |
| 107 | + * - Can only be constructed from a valid number string or another STNumber instance. |
| 108 | + * |
| 109 | + * Usage: |
| 110 | + * STNumber.from("1.2345e5") |
| 111 | + * STNumber.from("-123") |
| 112 | + * STNumber.fromParser(parser) |
| 113 | + */ |
| 114 | +export class STNumber extends SerializedType { |
| 115 | + /** 12 zero bytes, represents canonical zero. */ |
| 116 | + static defaultBytes = new Uint8Array(12) |
| 117 | + |
| 118 | + /** |
| 119 | + * Construct a STNumber from 12 bytes (8 for mantissa, 4 for exponent). |
| 120 | + * @param bytes - 12-byte Uint8Array |
| 121 | + * @throws Error if input is not a Uint8Array of length 12. |
| 122 | + */ |
| 123 | + constructor(bytes?: Uint8Array) { |
| 124 | + const used = bytes ?? STNumber.defaultBytes |
| 125 | + if (!(used instanceof Uint8Array) || used.length !== 12) { |
| 126 | + throw new Error( |
| 127 | + `STNumber must be constructed from a 12-byte Uint8Array, got ${used?.length}`, |
| 128 | + ) |
| 129 | + } |
| 130 | + super(used) |
| 131 | + } |
| 132 | + |
| 133 | + /** |
| 134 | + * Construct from a number string (or another STNumber). |
| 135 | + * |
| 136 | + * @param value - A string, or STNumber instance. |
| 137 | + * @returns STNumber instance. |
| 138 | + * @throws Error if not a string or STNumber. |
| 139 | + */ |
| 140 | + static from(value: unknown): STNumber { |
| 141 | + if (value instanceof STNumber) { |
| 142 | + return value |
| 143 | + } |
| 144 | + if (typeof value === 'string') { |
| 145 | + return STNumber.fromValue(value) |
| 146 | + } |
| 147 | + throw new Error( |
| 148 | + 'STNumber.from: Only string or STNumber instance is supported', |
| 149 | + ) |
| 150 | + } |
| 151 | + |
| 152 | + /** |
| 153 | + * Construct from a number string (integer, decimal, or scientific notation). |
| 154 | + * Handles normalization to XRPL Number constraints. |
| 155 | + * |
| 156 | + * @param val - The number as a string (e.g. '1.23', '-123e5'). |
| 157 | + * @returns STNumber instance |
| 158 | + * @throws Error if val is not a valid number string. |
| 159 | + */ |
| 160 | + static fromValue(val: string): STNumber { |
| 161 | + const { mantissa, exponent, isNegative } = extractNumberPartsFromString(val) |
| 162 | + let normalizedMantissa: bigint |
| 163 | + let normalizedExponent: number |
| 164 | + |
| 165 | + if (mantissa === BigInt(0) && exponent === 0 && !isNegative) { |
| 166 | + normalizedMantissa = BigInt(0) |
| 167 | + normalizedExponent = DEFAULT_VALUE_EXPONENT |
| 168 | + } else { |
| 169 | + ;({ mantissa: normalizedMantissa, exponent: normalizedExponent } = |
| 170 | + normalize(mantissa, exponent)) |
| 171 | + } |
| 172 | + |
| 173 | + const bytes = new Uint8Array(12) |
| 174 | + writeInt64BE(bytes, normalizedMantissa, 0) |
| 175 | + writeInt32BE(bytes, normalizedExponent, 8) |
| 176 | + return new STNumber(bytes) |
| 177 | + } |
| 178 | + |
| 179 | + /** |
| 180 | + * Read a STNumber from a BinaryParser stream (12 bytes). |
| 181 | + * @param parser - BinaryParser positioned at the start of a number |
| 182 | + * @returns STNumber instance |
| 183 | + */ |
| 184 | + static fromParser(parser: BinaryParser): STNumber { |
| 185 | + return new STNumber(parser.read(12)) |
| 186 | + } |
| 187 | + |
| 188 | + /** |
| 189 | + * Convert this STNumber to a normalized string representation. |
| 190 | + * The output is decimal or scientific notation, depending on exponent range. |
| 191 | + * Follows XRPL convention: zero is "0", other values are normalized to a canonical string. |
| 192 | + * |
| 193 | + * @returns String representation of the value |
| 194 | + */ |
| 195 | + // eslint-disable-next-line complexity -- required |
| 196 | + toJSON(): string { |
| 197 | + const b = this.bytes |
| 198 | + if (!b || b.length !== 12) |
| 199 | + throw new Error('STNumber internal bytes not set or wrong length') |
| 200 | + |
| 201 | + // Signed 64-bit mantissa |
| 202 | + const mantissa = readInt64BE(b, 0) |
| 203 | + // Signed 32-bit exponent |
| 204 | + const exponent = readInt32BE(b, 8) |
| 205 | + |
| 206 | + // Special zero: XRPL encodes canonical zero as mantissa=0, exponent=DEFAULT_VALUE_EXPONENT. |
| 207 | + if (mantissa === BigInt(0) && exponent === DEFAULT_VALUE_EXPONENT) { |
| 208 | + return '0' |
| 209 | + } |
| 210 | + if (exponent === 0) return mantissa.toString() |
| 211 | + |
| 212 | + // Use scientific notation for small/large exponents, decimal otherwise |
| 213 | + if (exponent < -25 || exponent > -5) { |
| 214 | + return `${mantissa}e${exponent}` |
| 215 | + } |
| 216 | + |
| 217 | + // Decimal rendering for -25 <= exp <= -5 |
| 218 | + const isNegative = mantissa < BigInt(0) |
| 219 | + const mantissaAbs = mantissa < BigInt(0) ? -mantissa : mantissa |
| 220 | + |
| 221 | + const padPrefix = 27 |
| 222 | + const padSuffix = 23 |
| 223 | + const mantissaStr = mantissaAbs.toString() |
| 224 | + const rawValue = '0'.repeat(padPrefix) + mantissaStr + '0'.repeat(padSuffix) |
| 225 | + const OFFSET = exponent + 43 |
| 226 | + const integerPart = rawValue.slice(0, OFFSET).replace(/^0+/, '') || '0' |
| 227 | + const fractionPart = rawValue.slice(OFFSET).replace(/0+$/, '') |
| 228 | + |
| 229 | + return `${isNegative ? '-' : ''}${integerPart}${ |
| 230 | + fractionPart ? '.' + fractionPart : '' |
| 231 | + }` |
| 232 | + } |
| 233 | +} |
0 commit comments