# State & Mappings

## Top-Level State

Fields declared inside the contract body become **persistent state** in the generated artifact:

```cxs
@CX30
@target(CX3JS)
token St {
    name = "St"
    symbol = "ST"
    totalSupply = 0
    owner = sender
}
```

## `mapping`

Two surface forms are accepted:

```text
mapping balances: address => uint256
mapping allowances(address => address => uint256)
```

The `(...)` form is a **nested type chain**, not a `(paramName => paramName => type)` shape - each segment before the final `uint256` must be a **type** (e.g. `address`), not an arbitrary name like `owner`/`spender` (`CXSParser.js`). The compiler does not stop you: `owner => spender => uint256` compiles, with `owner` and `spender` silently read as type names. Use descriptive names only in the mapping's own identifier (`allowances`), and index with two keys at the call site: `allowances[owner][spender]`.

Read / write:

```text
balances[sender] = balances[sender] + 1
v = balances[who]
```

## State arrays

Arrays may appear as **contract state fields**; `push`, `pop`, `length` and `a[i] = v` persist the change:

```cxs
@CX30
@target(CX3WASM)
token TicketLedger {
    ticketIds: uint256[] = []
    flags: bool[] = []

    name = "T"
    symbol = "T"
    totalSupply = 0
    owner = sender

    add(id: uint256) {
        ticketIds.push(id)
        flags.push(false)
    }

    @view
    count() -> uint256 {
        return ticketIds.length
    }
}
```

| Form | CX3JS | CX3WASM |
|------|-------|---------|
| Numeric or `bool` elements, `uint256[]` | JSON array | Fixed-width elements |
| `string[]`, `address[]`, `bytes32[]` | JSON array | Each item length-prefixed |
| Fixed size `uint256[4]`, arrays of structs | JSON array | Compile error **`UNSUPPORTED_ON_WASM`** - declare `uint256[]`, or use a mapping `uint256 => T` with a count |

Reading or writing past the end of an array reverts on both targets.

For upgrade-sensitive layouts, run **`checkUpgradeSafety`** before changing array fields - see **Upgrade Safety & Storage Layout**.

## `struct`

A `struct` can be the value of a mapping on both targets: `items[id] = Item { name: n, qty: 1 }`, `items[id].qty = 5` and `items[id].qty` read or write one field. CX3JS stores the struct as one JSON value, CX3WASM one storage key per field. See **Statements & Constructs Reference**.

## Chain-standard storage keys

The chain answers `totalSupply`, `balanceOf` and `allowance` reads from contract state directly, so a token should keep its supply in **`totalSupply`**, balances in **`mapping balances: address => uint256`** and allowances in **`mapping allowances: address => address => uint256`**. Wallets, the explorer and the SDK then show it without calling the contract.

## Next

**Functions & Modifiers**
