# @cosmjs/math Agent Guide

> **Package**: `@cosmjs/math` v0.38.0 **Purpose**: Safe integer math and decimal
> arithmetic **Layer**: Foundation Layer (no CosmJS dependencies)

## Package Overview

Provides safe integer types (Uint32, Uint53, Uint64, Int53) and `Decimal` type
for financial calculations. Prevents JavaScript number precision issues.

## Key Exports

| Export    | Purpose                                | Range               |
| --------- | -------------------------------------- | ------------------- |
| `Uint32`  | 32-bit unsigned integer                | 0 to 2^32-1         |
| `Uint53`  | 53-bit unsigned integer (JS safe)      | 0 to 2^53-1         |
| `Uint64`  | 64-bit unsigned integer (string-based) | 0 to 2^64-1         |
| `Int53`   | 53-bit signed integer                  | -(2^53-1) to 2^53-1 |
| `Decimal` | Arbitrary precision decimal            | Unlimited           |

## Common Usage

### Safe Integers

```typescript
import { Uint53, Uint64 } from "@cosmjs/math";

// Uint53 for amounts within JS safe range
const amount = new Uint53(1000000);
amount.toNumber(); // 1000000

// Uint64 for large amounts (uses strings internally)
const largeAmount = Uint64.fromString("9007199254740993");
largeAmount.toString(); // "9007199254740993"
```

### Decimal Arithmetic

```typescript
import { Decimal } from "@cosmjs/math";

// Create from atomics (smallest unit)
const amount = Decimal.fromAtomics("1000000", 6); // 1.000000
amount.toString(); // "1"

// Arithmetic
const sum = amount.plus(Decimal.fromAtomics("500000", 6));
sum.toString(); // "1.5"

// Multiplication
const doubled = amount.multiply(Decimal.fromUserInput("2", 6));
doubled.toString(); // "2"

// Get atomics back
doubled.atomics; // "2000000"
```

### Common Patterns

```typescript
// Token amounts (6 decimals like ATOM)
const atomAmount = Decimal.fromAtomics("1000000", 6);
console.log(atomAmount.toString()); // "1"

// Adding fees
const fee = Decimal.fromAtomics("5000", 6); // 0.005
const total = atomAmount.plus(fee);

// Converting to display
const display = total.toString(); // "1.005"

// Converting back to atomics for transactions
const atomics = total.atomics; // "1005000"
```

## Common Mistakes

❌ **WRONG**: Using JavaScript numbers for large amounts

```typescript
const amount = 9007199254740993; // Loses precision!
```

✅ **CORRECT**: Use Uint64 or Decimal

```typescript
const amount = Uint64.fromString("9007199254740993");
// or
const amount = Decimal.fromAtomics("9007199254740993", 0);
```

❌ **WRONG**: Floating point arithmetic

```typescript
const total = 0.1 + 0.2; // 0.30000000000000004
```

✅ **CORRECT**: Use Decimal

```typescript
const total = Decimal.fromUserInput("0.1", 18).plus(
  Decimal.fromUserInput("0.2", 18),
);
total.toString(); // "0.3"
```

---

**Last Updated**: January 6, 2026 **Package Version**: 0.38.0


