Skip to main content

Try it Live

Run Uint examples in the interactive playground

    BigInt Values

    JavaScript BigInt provides arbitrary precision integers:
    // Small values
    Uint.fromBigInt(0n)
    Uint.fromBigInt(1n)
    Uint.fromBigInt(255n)
    
    // Large values
    Uint.fromBigInt(2n ** 128n)
    Uint.fromBigInt(2n ** 255n)
    
    // Maximum
    Uint.fromBigInt(2n ** 256n - 1n)
    
    BigInt values must be non-negative and less than 2^256. Negative values and overflow throw errors.

    Range Validation

    Valid Range

    // Minimum: 0
    Uint.fromBigInt(0n)
    
    // Maximum: 2^256 - 1
    const max = 115792089237316195423570985008687907853269984665640564039457584007913129639935n
    Uint.fromBigInt(max)
    

    Out of Range

    // Negative values throw
    Uint.fromBigInt(-1n)        // Error: Value cannot be negative
    Uint.fromBigInt(-100n)      // Error: Value cannot be negative
    
    // Overflow throws
    Uint.fromBigInt(2n ** 256n)     // Error: Value exceeds 2^256 - 1
    Uint.fromBigInt(2n ** 257n)     // Error: Value exceeds 2^256 - 1
    

    Usage Patterns

    Computation Results

    // BigInt arithmetic
    const a = 100n
    const b = 50n
    const sum = Uint.fromBigInt(a + b)        // 150
    const product = Uint.fromBigInt(a * b)    // 5000
    
    // With validation
    function safeFromBigInt(value: bigint): BrandedUint256 | null {
      if (value < 0n || value >= 2n ** 256n) {
        return null
      }
      return Uint.fromBigInt(value)
    }
    

    Constants

    // Common Ethereum constants
    const ONE_ETHER = Uint.fromBigInt(10n ** 18n)
    const ONE_GWEI = Uint.fromBigInt(10n ** 9n)
    const MAX_UINT256 = Uint.fromBigInt(2n ** 256n - 1n)
    const MAX_UINT128 = Uint.fromBigInt(2n ** 128n - 1n)
    

    Parsing Large Numbers

    // JSON doesn't support BigInt, must parse strings
    interface ApiResponse {
      balance: string  // BigInt serialized as string
    }
    
    function parseBalance(data: ApiResponse): BrandedUint256 {
      const balanceBigInt = BigInt(data.balance)
      return Uint.fromBigInt(balanceBigInt)
    }
    

    See Also