> ## Documentation Index
> Fetch the complete documentation index at: https://voltaire.tevm.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# Uint.tryFrom

> Safe constructor returning undefined instead of throwing

<Card title="Try it Live" icon="play" href="https://playground.tevm.sh?example=primitives/uint.ts">
  Run Uint examples in the interactive playground
</Card>

<Tabs />

## Why Use tryFrom?

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

### User Input

```typescript theme={null}
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

```typescript theme={null}
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

```typescript theme={null}
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

```typescript theme={null}
Uint.tryFrom(-1n)          // undefined
Uint.tryFrom(-100)         // undefined
Uint.tryFrom("-1")         // undefined
```

### Overflow

```typescript theme={null}
Uint.tryFrom(2n ** 256n)   // undefined
Uint.tryFrom(2n ** 257n)   // undefined

// String exceeding max
const tooLarge = "115792089237316195423570985008687907853269984665640564039457584007913129639936"
Uint.tryFrom(tooLarge)     // undefined (max + 1)
```

### Invalid Format

```typescript theme={null}
Uint.tryFrom("invalid")    // undefined
Uint.tryFrom("0xGG")       // undefined
Uint.tryFrom("")           // undefined
Uint.tryFrom("  ")         // undefined
```

### Non-Integer Numbers

```typescript theme={null}
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)

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

### With tryFrom (clean)

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

## Type Guards

Combine with type guards for type narrowing:

```typescript theme={null}
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

```typescript theme={null}
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

```typescript theme={null}
function getAmountOrDefault(input: string): BrandedUint256 {
  return Uint.tryFrom(input) ?? Uint.ZERO
}

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

### Validation Chain

```typescript theme={null}
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

* [from](/primitives/uint256/from) - Universal constructor (throws)
* [isValid](/primitives/uint256/is-valid) - Type guard validation
* [fromHex](/primitives/uint256/from-hex) - From hex string
* [fromBigInt](/primitives/uint256/from-bigint) - From BigInt
* [fromNumber](/primitives/uint256/from-number) - From number
