<!-- source: https://www.secondlayer.tools/docs/local-chain -->

# Local Chain

Run Secondlayer against a Clarinet devnet: Streams, Index, Subgraphs and Webhooks, with no cloud and no account.

## Connect

Run it inside your Clarinet project.

```text ~/clarinet-project
$ secondlayer devnet connect
Secondlayer stack up
  api      → http://localhost:3800
  indexer  → http://localhost:3700

The api is published on 127.0.0.1 only: /v1 reads need no credential.
Writes (deploys, webhooks) send INSTANCE_TOKEN=dev-instance-token.
```

| You need | Why |
| --- | --- |
| [Clarinet](https://github.com/hirosystems/clarinet) and a `Clarinet.toml` project | The devnet and your contracts |
| Docker (Docker Desktop, or [OrbStack](https://orbstack.dev) on macOS) | Runs Postgres and the runtime |
| The CLI: `bun add -g @secondlayer/cli` | Provides `secondlayer devnet` |

| Connect does | Detail |
| --- | --- |
| Patches `settings/Devnet.toml` | The devnet node forwards events to the indexer on `:3700` |
| Writes `.secondlayer/docker-compose.yml` | Postgres plus the one-box runtime image, the one [Self-host](https://www.secondlayer.tools/docs/self-host.md) runs |
| Pulls and starts both | `docker compose up -d` |
| Sets local credentials | A fixed instance token, a public dev signing key for webhooks, an allowlist so webhooks reach your localhost receiver |

## Start and call

The devnet deploys your contracts and streams every block to the indexer.

```bash
clarinet devnet start
```

Drop services you don't need in `settings/Devnet.toml` by setting them to `true`:

| Key | Saves | Costs you |
| --- | --- | --- |
| `disable_stacks_explorer` | memory | the explorer UI |
| `disable_bitcoin_explorer` | memory | the Bitcoin explorer UI |
| `disable_stacks_api` | memory, `:3999` | the [faucet](#mock-sbtc) and the default `devnet` chain node URL |
| `disable_postgres` | memory, `:5432` | the Stacks API, which needs it |

### Send a call

Use [@secondlayer/stacks](https://stacks.secondlayer.tools/guide/transactions) against the devnet node: the `devnet` chain defaults to the Stacks API on `:3999`, so set `transport` when that API is off.

```bash
bun add @secondlayer/stacks
```

```ts call.ts
import { createWalletClient, http } from "@secondlayer/stacks";
import { privateKeyToAccount } from "@secondlayer/stacks/accounts";
import { devnet } from "@secondlayer/stacks/chains";

const client = createWalletClient({
	account: privateKeyToAccount(
		"753b7cc01a1a2e86221266a154af739463fce51219d97e4f856cd7200c3bd2a601", // devnet deployer, from settings/Devnet.toml
	),
	chain: devnet,
	transport: http("http://localhost:20443"), // the devnet node; the Stacks API on :3999 may be off
});

const txid = await client.callContract({
	contract: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.counter",
	functionName: "increment",
	args: [],
});
console.log(txid);
```

The reads below use a `counter` contract that prints an event on each call:

```clarity contracts/counter.clar
(define-data-var counter uint u0)
(define-public (increment)
  (let ((new-value (+ (var-get counter) u1)))
    (var-set counter new-value)
    (print {event: "incremented", value: new-value})
    (ok new-value)))
```

## Read it back

Reads need no credential (loopback only). Call `increment` a few times first.

### Streams

Raw events from the node. The newest blocks are held back as a reorg margin, so an event appears a couple of blocks later.

```bash
curl "http://localhost:3800/v1/streams/events?contract_id=ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.counter"
```

```json
{
  "events": [
    {
      "cursor": "69:0",
      "block_height": 69,
      "tx_id": "0x606013dd2a02400045e1d28ab7d1d84649014e4d81063daa1cc83d45af3149ff",
      "event_type": "print",
      "contract_id": "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.counter",
      "payload": { "topic": "print", "raw_value": "0x0c00000002056576656e74…" },
      "canonical": true,
      "finalized": false
    }
  ],
  "next_cursor": "69:0",
  ...
}
```

### Index

Decoded transactions and events. The id needs its `0x` prefix, which `broadcastTransaction` leaves off.

```bash
curl "http://localhost:3800/v1/index/transactions/0x606013dd2a02400045e1d28ab7d1d84649014e4d81063daa1cc83d45af3149ff"
curl "http://localhost:3800/v1/index/events?contract_id=ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.counter&event_type=print"
```

```json
{
  "transaction": {
    "tx_id": "0x606013dd2a02400045e1d28ab7d1d84649014e4d81063daa1cc83d45af3149ff",
    "block_height": 69,
    "tx_type": "contract_call",
    "status": "success",
    "contract_call": {
      "contract_id": "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.counter",
      "function_name": "increment",
      "result": "1"
    },
    ...
  },
  ...
}
```

```json
{
  "events": [
    {
      "cursor": "69:0",
      "event_type": "print",
      "contract_id": "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.counter",
      "payload": { "topic": "print", "value": { "event": "incremented", "value": "1" } }
    }
  ],
  ...
}
```

### Subgraphs

Generate a subgraph from indexed prints (send a call first), deploy it, then read its table. `dev-instance-token` is a local value, not a secret.

```bash
secondlayer subgraphs create counter --from-contract ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.counter
export SECONDLAYER_API_URL=http://localhost:3800
export INSTANCE_TOKEN=dev-instance-token
secondlayer subgraphs deploy subgraphs/counter.ts
curl "$SECONDLAYER_API_URL/v1/subgraphs/counter/counter?_limit=5"
```

```json
{
  "rows": [
    {
      "_id": "1",
      "_block_height": "69",
      "_tx_id": "0x606013dd2a02400045e1d28ab7d1d84649014e4d81063daa1cc83d45af3149ff",
      "topic": "print",
      "value": { "event": "incremented", "value": "1" }
    },
    ...
  ],
  "next_cursor": "3",
  "tip": { "block_height": "77", "subgraph_height": 77, "blocks_behind": 0 }
}
```

### Webhooks

A receiver on your machine is `host.docker.internal`, not `localhost`.

```ts receiver.ts
Bun.serve({
	port: 4999,
	hostname: "0.0.0.0",
	async fetch(request) {
		console.log(
			[...request.headers.keys()].filter((key) => key.includes("signature")).join(","),
			await request.text(),
		);
		return new Response("ok");
	},
});
```

```bash
secondlayer webhooks create counter-prints -u http://host.docker.internal:4999/hook \
  --trigger '{"type":"print_event","contractId":"ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.counter"}'
```

The receiver logs one line per call:

```text
webhook-signature,x-secondlayer-signature,x-secondlayer-signature-keyid {"type":"chain.print_event.apply","timestamp":"2026-11-03T17:59:56.000Z","data":{"event":{"data":{"topic":"print","value":{"event":"incremented","value":"1"},…},"type":"contract_event","tx_id":"0x606013dd…49ff","event_index":0},"action":"apply","trigger":"print_event","canonical":true,"block_height":69}}
```

Deliveries are signed with a public dev key: `GET /api/webhooks/signing-key` returns it ([verification](https://www.secondlayer.tools/docs/webhooks.md)).

## Operate

Commands for the running stack.

### Mock sBTC

Mint mock sBTC on your devnet. It needs the Stacks API on `:3999`, so leave `disable_stacks_api` off.

```bash
secondlayer devnet faucet --to ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM
```

```text
  minting 1000000 sats to ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM
  via ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.sbtc-deposit as signer ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM
✓ Minted 1000000 sats of mock sBTC to ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.
  tx 954d9045f1cfbe86db4c837952b59dea34ae857849aa3299f0fdac1544aaf601
  Mock sBTC on your devnet — not the canonical asset.
```

| Flag | Default | Purpose |
| --- | --- | --- |
| `--to <address>` | required | Recipient Stacks address |
| `--amount <sats>` | `1000000` | Amount in sats, minimum 546 |
| `--contract <id>` | `<deployer>.sbtc-deposit` | sBTC deposit contract |
| `--rpc-url <url>` | `http://localhost:3999` | Devnet node RPC |

### Watch it work

`-w` refreshes every 2s; `--limit <n>` sets the recent rows.

```text ~/clarinet-project
$ secondlayer devnet status
STACK
  ● indexer   healthy   :3700
  ● api       healthy   :3800

INGEST
  chain tip 77   indexed 77   lag caught up   last block 57s ago

SUBGRAPHS
  counter   active   block 77   counter · 3 rows

ACTIVITY  (recent)
     72  counter          print  {"even…"3"}
     70  counter          print  {"even…"2"}
     69  counter          print  {"even…"1"}
```

Services are `secondlayer` and `postgres`.

```bash
secondlayer devnet logs secondlayer -f
```

### Options

| Flag | Default | Purpose |
| --- | --- | --- |
| `--project <dir>` | nearest `Clarinet.toml` | Clarinet project directory |
| `--image-tag <tag>` | `latest` | Published image tag to run |
| `--owner <owner>` | Secondlayer namespace | ghcr image owner to pull from |
| `--no-up` | none | Patch config and write compose without starting Docker |

### Tear down

```bash
secondlayer devnet down            # stop the stack
secondlayer devnet down --purge    # stop and wipe the local index volumes
```

## Read next

- [Self-host](https://www.secondlayer.tools/docs/self-host.md)
- [Webhooks](https://www.secondlayer.tools/docs/webhooks.md)

## Notes for agents

- From inside a Clarinet project: 'secondlayer devnet connect', then 'clarinet devnet start'; confirm 'curl http://localhost:3800/health'.
- The txid from callContract has no 0x; /v1/index/transactions/<txid> needs it. Streams holds back the newest blocks as a reorg margin.
- Deploys are writes: INSTANCE_TOKEN=dev-instance-token. Webhook receivers use host.docker.internal. The faucet needs the Stacks API on :3999.

## 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`
