import Big from 'big.js'; import { Result } from './result.js'; /** * Input validation helpers returning Result for SDK parameters. */ // Pre-compiled regex patterns for efficiency const ADDRESS_PATTERN = /^0x[a-fA-F0-9]{40}$/; // Case-insensitive: callers may pass 'avax/usdc' and have it normalized // to canonical 'AVAX/USDC' downstream (e.g. via normalizeTradingPair). const PAIR_PATTERN = /^[A-Za-z0-9_-]+\/[A-Za-z0-9_-]+$/; const ORDER_ID_HEX_BODY_PATTERN = /^[0-9a-fA-F]+$/; const TOKEN_SYMBOL_PATTERN = /^[A-Z0-9]{1,10}$/; /** * Validate that a value is a positive finite number (> 0). * * Accepts `number`, numeric `string`, `bigint`, and `Big` so callers * wanting precision-exact arithmetic (for amounts on pairs with strict * display decimals) can pass `new Big('2933')`, `'2933.5'`, or * `2933n` rather than a float. Strings are parsed via Big.js so * non-numeric input produces a precise failure message. */ export function validatePositiveNumber(value: unknown, paramName: string): Result { if (typeof value === 'boolean') { // booleans coerce to 0/1 in arithmetic contexts — reject so `true` does // not silently slip through as `amount=1`. return Result.fail(`${paramName} must be a number, got boolean`); } if (typeof value === 'number') { if (isNaN(value)) { return Result.fail(`${paramName} must be a number, got NaN`); } if (!isFinite(value)) { return Result.fail(`${paramName} must be finite, got ${value}`); } if (value <= 0) { return Result.fail(`${paramName} must be positive, got ${value}`); } return Result.ok(null); } if (typeof value === 'bigint') { if (value <= 0n) { return Result.fail(`${paramName} must be positive, got ${value}`); } return Result.ok(null); } if (value instanceof Big) { if (value.lte(0)) { return Result.fail(`${paramName} must be positive, got ${value.toString()}`); } return Result.ok(null); } if (typeof value === 'string') { let parsed: Big; try { parsed = new Big(value); } catch { return Result.fail(`${paramName} must be a numeric string, got ${JSON.stringify(value)}`); } if (parsed.lte(0)) { return Result.fail(`${paramName} must be positive, got ${value}`); } return Result.ok(null); } return Result.fail(`${paramName} must be a number, got ${typeof value}`); } /** * Validate that a value is a positive integer (> 0). */ export function validatePositiveInt(value: number, paramName: string): Result { if (typeof value !== 'number' || isNaN(value)) { return Result.fail(`${paramName} must be a number, got ${typeof value}`); } if (!Number.isInteger(value)) { return Result.fail(`${paramName} must be an integer, got ${value}`); } if (value <= 0) { return Result.fail(`${paramName} must be positive, got ${value}`); } return Result.ok(null); } /** * Validate that a value is a non-negative number (>= 0). */ export function validateNonNegativeFloat(value: number, paramName: string): Result { if (typeof value !== 'number' || isNaN(value)) { return Result.fail(`${paramName} must be a number, got ${typeof value}`); } if (value < 0) { return Result.fail(`${paramName} must be non-negative, got ${value}`); } if (!isFinite(value)) { return Result.fail(`${paramName} must be finite, got ${value}`); } return Result.ok(null); } /** * Validate Ethereum address format. */ export function validateAddress(address: string, paramName: string = 'address'): Result { if (typeof address !== 'string') { return Result.fail(`${paramName} must be a string, got ${typeof address}`); } if (!address.trim()) { return Result.fail(`${paramName} cannot be empty`); } if (!ADDRESS_PATTERN.test(address)) { return Result.fail(`${paramName} must be a valid Ethereum address (0x + 40 hex chars), got ${address}`); } return Result.ok(null); } /** * Validate trading pair format (e.g., "AVAX/USDC"). */ export function validatePairFormat(pair: string, paramName: string = 'pair'): Result { if (typeof pair !== 'string') { return Result.fail(`${paramName} must be a string, got ${typeof pair}`); } if (!pair.trim()) { return Result.fail(`${paramName} cannot be empty`); } if (!PAIR_PATTERN.test(pair)) { return Result.fail(`${paramName} must be in format 'BASE/QUOTE' (e.g., 'AVAX/USDC'), got '${pair}'`); } return Result.ok(null); } /** * Validate order ID format (hex, decimal, UTF-8 client id, or 32-byte buffer). */ export function validateOrderIdFormat( orderId: string | Uint8Array, paramName: string = 'orderId' ): Result { if (orderId instanceof Uint8Array) { if (orderId.length !== 32) { return Result.fail( `Invalid ${paramName}: bytes must be exactly 32 bytes (bytes32), got ${orderId.length} bytes` ); } return Result.ok(null); } if (typeof orderId !== 'string') { return Result.fail(`Invalid ${paramName}: must be string or bytes, got ${typeof orderId}`); } const value = orderId.trim(); if (!value) { return Result.fail(`Invalid ${paramName}: cannot be empty`); } if (/^0x/i.test(value)) { const hexStr = value.slice(2).toLowerCase(); if (!hexStr) { return Result.fail(`Invalid ${paramName}: hex string cannot be empty after '0x'`); } if (!ORDER_ID_HEX_BODY_PATTERN.test(hexStr)) { return Result.fail(`Invalid ${paramName}: contains invalid hex characters`); } if (hexStr.length % 2 !== 0) { return Result.fail( `Invalid ${paramName}: hex string must have an even number of characters` ); } if (hexStr.length > 64) { return Result.fail( `Invalid ${paramName}: hex string too long for bytes32 (max 64 hex chars), got ${hexStr.length} chars` ); } return Result.ok(null); } if (/^\d+$/.test(value)) { return Result.ok(null); } if (value.length === 64 && ORDER_ID_HEX_BODY_PATTERN.test(value)) { return Result.ok(null); } const encoded = new TextEncoder().encode(value); if (encoded.length > 32) { return Result.fail( `Invalid ${paramName}: plain string form must fit in 32 bytes, got ${encoded.length} bytes` ); } return Result.ok(null); } /** * Validate token symbol format. */ export function validateTokenSymbol(token: string, paramName: string = 'token'): Result { if (typeof token !== 'string') { return Result.fail(`${paramName} must be a string, got ${typeof token}`); } if (!token.trim()) { return Result.fail(`${paramName} cannot be empty`); } if (!TOKEN_SYMBOL_PATTERN.test(token)) { return Result.fail(`${paramName} must be 1-10 uppercase alphanumeric characters, got '${token}'`); } return Result.ok(null); } /** * Validate chain identifier (chain ID number or chain name string). */ export function validateChainIdentifier( identifier: number | string, paramName: string = 'chainIdentifier' ): Result { if (typeof identifier === 'number') { if (!Number.isInteger(identifier) || identifier <= 0) { return Result.fail(`${paramName} must be a positive integer, got ${identifier}`); } return Result.ok(null); } if (typeof identifier === 'string') { if (!identifier.trim()) { return Result.fail(`${paramName} cannot be empty`); } return Result.ok(null); } return Result.fail(`${paramName} must be a number or string, got ${typeof identifier}`); } /** * Validate order parameters. */ export function validateOrderParams( pair: string, amount: number, price: number | null, orderType: string ): Result { // Validate pair const pairResult = validatePairFormat(pair, 'pair'); if (!pairResult.success) return pairResult; // Validate amount const amountResult = validatePositiveNumber(amount, 'amount'); if (!amountResult.success) return amountResult; // Validate order type const validTypes = ['LIMIT', 'MARKET']; const upperType = orderType.toUpperCase(); if (!validTypes.includes(upperType)) { return Result.fail(`orderType must be 'LIMIT' or 'MARKET', got '${orderType}'`); } // Validate price for LIMIT orders if (upperType === 'LIMIT') { if (price === null || price === undefined) { return Result.fail('price is required for LIMIT orders'); } const priceResult = validatePositiveNumber(price, 'price'); if (!priceResult.success) return priceResult; } return Result.ok(null); } /** * Validate transfer parameters. */ export function validateTransferParams( token: string, amount: number, toAddress: string ): Result { // Validate token const tokenResult = validateTokenSymbol(token, 'token'); if (!tokenResult.success) return tokenResult; // Validate amount const amountResult = validatePositiveNumber(amount, 'amount'); if (!amountResult.success) return amountResult; // Validate address const addressResult = validateAddress(toAddress, 'toAddress'); if (!addressResult.success) return addressResult; return Result.ok(null); } /** * Validate swap parameters. */ export function validateSwapParams( fromToken: string, toToken: string, amount: number ): Result { // Validate fromToken const fromResult = validateTokenSymbol(fromToken, 'fromToken'); if (!fromResult.success) return fromResult; // Validate toToken const toResult = validateTokenSymbol(toToken, 'toToken'); if (!toResult.success) return toResult; // Tokens must be different if (fromToken.toUpperCase() === toToken.toUpperCase()) { return Result.fail('fromToken and toToken must be different'); } // Validate amount const amountResult = validatePositiveNumber(amount, 'amount'); if (!amountResult.success) return amountResult; return Result.ok(null); }