Skip to main content

Try it Live

Run Uint examples in the interactive playground

    Why Use tryFrom?

    tryFrom is ideal for user input validation and parsing untrusted data:

    User Input

    function handleUserInput(input: string) {
      const value = Uint.tryFrom(input)
    
      if (value === undefined) {
        return { error: "Invalid number format" }
      }
    
      return { value }
    }
    
    // Usage
    handleUserInput("123")      // { value: BrandedUint256 }
    handleUserInput("0xff")     // { value: BrandedUint256 }
    handleUserInput("invalid")  // { error: "Invalid number format" }
    handleUserInput("-1")       // { error: "Invalid number format" }
    

    API Response Parsing

    interface ApiResponse {
      balance: string
      nonce: string
    }
    
    function parseApiResponse(data: ApiResponse) {
      const balance = Uint.tryFrom(data.balance)
      const nonce = Uint.tryFrom(data.nonce)
    
      if (!balance || !nonce) {
        throw new Error("Invalid API response")
      }
    
      return { balance, nonce }
    }
    

    Form Validation

    function validateAmount(input: string): { valid: boolean; value?: BrandedUint256; error?: string } {
      if (input.trim() === "") {
        return { valid: false, error: "Amount required" }
      }
    
      const value = Uint.tryFrom(input)
    
      if (value === undefined) {
        return { valid: false, error: "Invalid amount format" }
      }
    
      if (value.isZero()) {
        return { valid: false, error: "Amount must be greater than zero" }
      }
    
      return { valid: true, value }
    }
    

    Error Cases

    tryFrom returns undefined for all error cases that from would throw:

    Negative Values

    Uint.tryFrom(-1n)          // undefined
    Uint.tryFrom(-100)         // undefined
    Uint.tryFrom("-1")         // undefined
    

    Overflow

    Uint.tryFrom(2n ** 256n)   // undefined
    Uint.tryFrom(2n ** 257n)   // undefined
    
    // String exceeding max
    const tooLarge = "115792089237316195423570985008687907853269984665640564039457584007913129639936"
    Uint.tryFrom(tooLarge)     // undefined (max + 1)
    

    Invalid Format

    Uint.tryFrom("invalid")    // undefined
    Uint.tryFrom("0xGG")       // undefined
    Uint.tryFrom("")           // undefined
    Uint.tryFrom("  ")         // undefined
    

    Non-Integer Numbers

    Uint.tryFrom(3.14)         // undefined
    Uint.tryFrom(1.5)          // undefined
    Uint.tryFrom(NaN)          // undefined
    Uint.tryFrom(Infinity)     // undefined
    

    Pattern Comparison

    Without tryFrom (verbose error handling)

    function parse(input: string): BrandedUint256 | null {
      try {
        return Uint(input)
      } catch (error) {
        console.error("Parse failed:", error)
        return null
      }
    }
    

    With tryFrom (clean)

    function parse(input: string): BrandedUint256 | null {
      return Uint.tryFrom(input) ?? null
    }
    

    Type Guards

    Combine with type guards for type narrowing:
    function processValue(input: string | bigint): void {
      const value = Uint.tryFrom(input)
    
      // TypeScript knows value is BrandedUint256 | undefined
      if (value === undefined) {
        console.log("Invalid input")
        return
      }
    
      // TypeScript knows value is BrandedUint256 here
      console.log(value.toHex())
    }
    

    Usage Patterns

    Optional Values

    interface Transaction {
      value: BrandedUint256
      gasPrice?: BrandedUint256
    }
    
    function parseTransaction(data: any): Transaction | null {
      const value = Uint.tryFrom(data.value)
      if (!value) return null
    
      const gasPrice = data.gasPrice !== undefined
        ? Uint.tryFrom(data.gasPrice)
        : undefined
    
      return { value, gasPrice }
    }
    

    Fallback Values

    function getAmountOrDefault(input: string): BrandedUint256 {
      return Uint.tryFrom(input) ?? Uint.ZERO
    }
    
    function getAmountOrMax(input: string): BrandedUint256 {
      return Uint.tryFrom(input) ?? Uint.MAX
    }
    

    Validation Chain

    function validateAndParse(input: string): BrandedUint256 {
      const value = Uint.tryFrom(input)
    
      if (value === undefined) {
        throw new Error("Invalid format")
      }
    
      if (value.isZero()) {
        throw new Error("Value must be non-zero")
      }
    
      const max = Uint(2n ** 128n)
      if (value.greaterThan(max)) {
        throw new Error("Value too large")
      }
    
      return value
    }
    

    Performance

    tryFrom has identical performance to from - just wraps in try/catch internally. No performance penalty for using the safe version.

    See Also