<!-- source: https://www.secondlayer.tools/docs/contract-state -->

# Contract State

Know what changed in any Stacks contract, when, and who changed it.

Every map and variable write from block 1, with the transaction that made it.

One key, one call, for any transaction:

```bash
curl "$SECONDLAYER_API_URL/v1/index/events?event_type=nested_contract_call&tx_id=0xf53d86108ccd4a7d7418101a86e4030ebe8c9ff942d47888987d5f6bac7c279b" \
  -H "Authorization: Bearer sk-sl_…"
```

```ts
import { Index } from "@secondlayer/sdk";

const index = new Index();

const { events } = await index.events.list({
  eventType: "nested_contract_call",
  txId: "0xf53d86108ccd4a7d7418101a86e4030ebe8c9ff942d47888987d5f6bac7c279b",
});
```

```json response.json status=200
{
  "events": [
    {
      "cursor": "1230200:13",
      "block_height": 1230200,
      "block_time": "2025-05-21T09:56:51.000Z",
      "tx_id": "0xf53d86108ccd4a7d7418101a86e4030ebe8c9ff942d47888987d5f6bac7c279b",
      "tx_index": 0,
      "event_index": 13,
      "event_type": "nested_contract_call",
      "contract_id": "SP26BVHEKMZSAKZ4PZ5SFPZVMRHDKH99D2Z38TK1Y.kiki-token",
      "sender": "SP1E5PQRC5Y4WWEY1BP80254TGR2HDCSN5NF0VSFR",
      "caller": "SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.token-wkiki",
      "function_name": "transfer",
      "function_args": ["0x0100000000000000000000009062fc6a00", "0x05165c5b5f0c2f89ce3bc15d9001149a860516b3352d", "0x0616402da2c079e5d31d58b9cfc7286d1b1eb2f7834e0f616d6d2d7661756c742d76322d3031", "0x09"],
      "raw_result": "0x0703"
    }
  ]
}
```

That ALEX swap ran 22 calls between contracts and wrote two maps; the response shows one. A transaction id is enough.

## What You Can Know

Five event types cover what a contract stores and every call it makes. Values are Clarity `0x` hex. Every type filters by contract, transaction and height; the rest are below. Filters: [List events](https://www.secondlayer.tools/docs/api-reference.md#list-events).

| `event_type` | Tells you | Extra filters |
| --- | --- | --- |
| `nested_contract_call` | Who really uses a contract, including apps that route through another one, and calls that failed and were handled | `functionName`, `caller`, `sender` |
| `var_set` | A setting or counter changed | `varName` |
| `map_set` | An entry changed | `map` |
| `map_insert` | A new position, listing or balance | `map` |
| `map_delete` | An entry was removed | `map` |

### Who made the call

Every call between contracts carries two principals.

| Field | Means |
| --- | --- |
| `contract_id` | The contract called |
| `caller` | Who made the call: Clarity's `contract-caller` |
| `sender` | `tx-sender` at that moment. `as-contract` swaps it for the contract that used it |

At the ALEX drain, block 1,508,068, a vault called a fake token, which moved the vault's real tokens.

| Rows | Call | `caller` | `sender` |
| --- | --- | --- | --- |
| 21 | Vault calls the fake token's `transfer-fixed` | vault | vault |
| 14, 16, 18, 20 | Fake token moves aBTC, sBTC, ALEX and sUSDT | fake token | vault |

An unfamiliar `caller` with a vault as `sender` means that contract is moving the vault's tokens. The vault's own call looks normal alone.

## What a Value Was on Any Day

Walk one map's writes to know what any key held after any transaction.

```ts
for await (const write of index.events.walk({
  eventType: "map_set",
  contractId: "SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.amm-vault-v2-01",
  map: "reserve",
  fromHeight: 0,
})) {
  console.log(write.block_height, write.decoded.key, write.decoded.value);
}
// 1230200 SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.token-wkiki 2122910416441083
```

No print carries that write, and a node can't say which transaction set a key. For storage keys rather than named maps, read state writes.

### State Writes

Every key a block wrote, in node order.

```ts
const { state_writes, next_cursor } = await sl.index.stateWrites.list({
  blockHeight: 8054704,
  contractId: "SP1.vault", // only keys under this contract
  txContext: true, // join the writing transaction
});
```

| Field | Means |
| --- | --- |
| `cursor` | `<block_height>:<ordinal>` |
| `block_height`, `ordinal` | The block, and the write's position in node order |
| `tx_index` | `null` for block-level writes |
| `key` | The chain's storage key |
| `value_hex` | The new value |

- `GET /v1/index/state-writes`; `block_height` reads one block, not with a height range.
- Self-hosted rows start where your node first sent the `state_writes` observer key.

## Find Out the Moment It Changes

The same rows stream with `clock: "vm"` through the [checkpointed consumer](https://www.secondlayer.tools/docs/checkpoints.md).

```ts
await sl.streams.events.consume({
  clock: "vm",
  types: ["map_set", "var_set"],
  fromCursor: await db.loadCheckpoint(),
  onBatch: async (rows, ctx) => {
    await db.save(rows, ctx.cursor);
    return ctx.cursor;
  },
  onReorg: (reorg) => db.deleteFromHeight(reorg.fork_point_height),
});
```

A webhook fires on the same types once the block lands, whenever a vault's reserves change:

```ts
import { trigger } from "@secondlayer/sdk";

await sl.webhooks.create({
  name: "vault-reserves",
  url: "https://your.app/hooks/reserves",
  triggers: [
    trigger.mapSet({
      contractId: "SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.amm-vault-v2-01",
      map: "reserve",
    }),
  ],
});
```

A [subgraph](https://www.secondlayer.tools/docs/subgraphs.md) takes `map_set` and `var_set` as sources; built from stored values, anyone can rebuild its rows.

## Limits

The node patch is public; history is a six-week replay from block 1.

| Covered | Not covered |
| --- | --- |
| Values a contract stores, and calls between contracts | Every intermediate value in the code |
| Transactions that landed | Anything before it lands: it warns, it does not prevent. A transaction that fails outright leaves no rows |
| History from block 1, and who made each change | Something new about one key's current value: a node could always read that |
| Stored values, checkable against the block's state root | Calls between contracts: not committed on chain, so not provable |

Reads are metered like event rows ([Keys and Billing](https://www.secondlayer.tools/docs/authentication.md#what-it-costs)), so scope by contract and map. Reading contract state and testing on it use the meters. A hosted webhook or subgraph on contract state needs the [Contract state plan](/pricing#plans): $999 a month, with $100 of usage included. Upgrade from the credits page or the pricing page.

When the plan ends, hosted webhooks on contract state pause and hosted subgraphs on contract state stop. Nothing restarts on its own: resubscribe, then resume each webhook and redeploy each subgraph.

Hosted mainnet has rows from block 1; a self-hosted instance only from the block its node first recorded them.

## Read next

- [API](https://www.secondlayer.tools/docs/api-reference.md)
- [Checkpoints](https://www.secondlayer.tools/docs/checkpoints.md)
- [Subgraphs](https://www.secondlayer.tools/docs/subgraphs.md)
- [Keys and Billing](https://www.secondlayer.tools/docs/authentication.md)

## Notes for agents

- GET /v1/index/events, event_type one of the five; filters function_name, caller, sender, var_name, map. A tx_id read with no height reads its own block; otherwise pass from_height.
- Rows carry decoded { key, value } plus 0x hex raw_key and raw_value.
- nested_contract_call includes handled failures: check raw_result. Calls between contracts are never provable.
- Streams vm cursors carry a vm: prefix and only resume on clock vm. Webhook triggers: nestedContractCall, varSet, mapSet, mapInsert, mapDelete.
- Storage keys per block: GET /v1/index/state-writes.
- Reading contract state and testing on it use the meters. A hosted webhook or subgraph on contract state needs the Contract state plan. The plan is $999 a month or $9,990 a year, $100 of usage included each month (/pricing#plans). Upgrade from the pricing page or the credits page.
- When the plan ends, those webhooks pause (pauseReason plan) and those subgraphs stop. Resubscribe, then resume or redeploy.

## Setup

Ensure setup once, skipping any step already done:
- CLI: `bun add -g @secondlayer/cli`
- Instance: `secondlayer init` writes `INSTANCE_TOKEN`. Loopback `/v1` reads need no key.
- Hosted reads: export `SECONDLAYER_API_KEY` (`sk-sl_*`) or buy credits with `secondlayer credits buy` (`balance`, `refill`), then `secondlayer whoami`
