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

# Keys, notes and scanning

> Derive a spend key from a wallet signature, publish an address or a view key, and discover owned notes from RPC or through an indexer.

A Fluton Pool wallet is one secret: the spend key. Everything else (the shielded address people pay, the view key an auditor reads with, and the notes the pool holds for you) is derived from it or discovered with it. This page covers the pool client's key and scanning modules; [Keys and view keys](https://docs.fluton.io/concepts/keys-and-view-keys.md) explains why the split works.

## Spend key

`deriveSpendKey` asks a wallet to sign one fixed, domain-bound message and hashes the signature into a field element:

```ts theme={null}
import { deriveSpendKey, spendKeyMessage, spendKeyFromSignature } from "@fluton/sdk";

const spendKey = await deriveSpendKey(walletClient, { chainId: 42161, pool });
```

The message is built by `spendKeyMessage({ chainId, pool })`. It names the chain and the pool (the address lower-cased, so its checksum does not matter), and spells out what signing does:

```text theme={null}
Fluton - shielded spend key

Signing this message derives the SECRET key that controls your shielded balance and
decrypts your private payment history. Only sign it inside the Fluton app.

Chain ID: 42161
Pool: 0x…
```

The derivation is `keccak256("fluton-spend-key" || signature)`, of which 31 bytes become the key, so the result is always below the BN254 field size with no modular bias. `spendKeyFromSignature` does that step on its own and is a pure function of the signature bytes.

Ethereum wallets sign with RFC 6979 deterministic nonces, so the same account always produces the same signature and therefore the same spend key, on any device, with nothing stored. One account derives the same key, and the same shielded address, every time; another account, another pool or another chain each derive an unrelated key.

```ts theme={null}
const k1 = await deriveSpendKey(walletClient, { chainId, pool });
const k2 = await deriveSpendKey(walletClient, { chainId, pool });
// k1 === k2, and 0n < k1 < FIELD_SIZE
const address = await shieldedAddressFromSpendKey(k1); // the same on every device
```

> [!WARNING]
>
> Anyone who obtains that signature owns the shielded balance and can decrypt the whole note history.

A key that is not wallet-derived works just as well: `randomFieldElement()` produces one, and `keypairFromPrivate(spendKey)` turns any spend key into the keypair that notes are built with.

## Shielded address

The address a payer needs is the spend public key plus the x25519 key that notes are encrypted to:

```ts theme={null}
import { shieldedAddressFromSpendKey, parseShieldedAddress } from "@fluton/sdk";

const address = await shieldedAddressFromSpendKey(spendKey); // "pp-addr:<spendPubHex>:<encPubHex>"
const { publicKey, encryptionKey } = parseShieldedAddress(address);
```

`parseShieldedAddress` rejects anything that is not exactly three `pp-addr:`-prefixed parts with a 32-byte encryption key and a public key inside the field, so an address pasted into a form is validated before it reaches a proof. The encryption keypair itself is derived from the spend key by `encryptionKeypairFromSpendKey`, which is why one secret recovers everything.

## View key

`viewKeyFromSpendKey` derives read-only access. A `ViewKey` is three values: the Poseidon spend public key, the `nullifierKey` (`Poseidon(spendKey, NULLIFIER_KEY_DOMAIN)`) and the 32-byte x25519 `encryptionSecret`. All three are one-way from the spend key:

```ts theme={null}
import { viewKeyFromSpendKey, serializeViewKey, parseViewKey, scanShieldedNotes } from "@fluton/sdk";

const view = await viewKeyFromSpendKey(spendKey);
const shareable = serializeViewKey(view); // "pp-view:<spendPubHex>:<nullifierKeyHex>:<encSecretHex>"
const notes = await scanShieldedNotes(publicClient, pool, parseViewKey(shareable), scan);
```

With those three values a holder decrypts every note ever sent to the address, rebuilds each commitment, and computes each nullifier, so they see the balance, the history and which notes are spent. `shieldedAddressFromViewKey` returns the same address as the spend key's, and `keypairFromViewKey` returns a view-only keypair that computes identical commitments and nullifiers. What it cannot do is spend: `buildTransactionInputs` rejects a view-only note with a *watch-only* error, because the circuit needs the private key itself. A viewer also does not learn the recipient or amount of outgoing payments, only that a note was spent and what change came back.

## Scan for notes

`scanShieldedNotes` is the receiving half of a private transfer and, at the same time, full recovery of a wallet from chain data:

```ts theme={null}
import { scanShieldedNotes } from "@fluton/sdk";

const { notes, spendable, balances } = await scanShieldedNotes(publicClient, pool, spendKey, scan);
```

It takes the spend key or a view key and returns three things: `notes`, every discovered note as `{ utxo, spent }`; `spendable`, the unspent ones (ready to spend as they are, when the key was a spend key); and `balances`, an `AssetBalances` map of unspent value per asset id. Amounts of different assets are never added together: `balancesOf` sums per asset id.

Discovery is trial decryption. Every `NewCommitment` ciphertext is handed to `tryDecryptNote` with the scanner's encryption keys; a blob that is not addressed to this key fails authentication and is skipped, which is the normal case. Each blob is exactly `NOTE_CIPHERTEXT_LENGTH` (168) bytes, so its size says nothing about the note inside. A decrypted plaintext is accepted only if `isCanonicalOpening` holds for it, because Poseidon reduces its inputs modulo the field: without that check a sender could commit to 0, encrypt the field size, and show a wallet a balance it does not have. [Notes and proofs](https://docs.fluton.io/concepts/notes-and-proofs.md) gives the ranges a canonical opening has to be in. The note is then rebuilt and its commitment compared with the leaf, which authenticates the asset too (the commitment hashes it), so a transfer that kept its asset private on-chain is still recovered as the right asset. A note naming an asset the pool does not list is ignored.

Spent status comes from the pool: `isSpent` per note on a plain scan, or from the verified nullifier set when an indexer is used.

### From RPC, in pages

`ScanOptions` is the scan window:

**fromBlock** `bigint`

First block to scan: the pool's deployment block. Default 0.

**chunkSize** `bigint`

Maximum blocks per `eth_getLogs` call. Left unset, the whole range goes in one call, which only a local node will answer.

**toBlock** `bigint`

Last block to scan. Default: the latest block, read fresh so a scan never ends at a stale head.

**indexer** `IndexerSource`

An optional indexer to read history from, verified on-chain, with an RPC fallback on any doubt.

A deployment publishes the first two as `deployBlock` and `logChunk` ([Deployments](https://docs.fluton.io/reference/deployments.md) lists the values): a client scans from `deployBlock` in `logChunk`-sized pages by passing them as `fromBlock` and `chunkSize`, so a hosted endpoint is asked for a bounded range from the deployment block instead of the whole chain.

An RPC scan refuses incomplete logs rather than build a tree the pool never had: the leaf positions must follow one another without a gap, must start at leaf 0 when no `fromBlock` was given, and must be whole join-splits. Every transaction appends exactly three leaves. A leaf's position names its tree as well as its place in it, because the pool starts another tree when the current one is full ([Notes and proofs](https://docs.fluton.io/concepts/notes-and-proofs.md#the-merkle-tree)).

### Through an indexer

An `IndexerSource` points the scan at a standalone indexer, such as the one the hosted wallet uses:

```ts theme={null}
const scan = {
  fromBlock: deployBlock, // from the deployment
  chunkSize: logChunk,
  indexer: { url: "https://indexer.example.org", chainId: 42161, pool },
};
```

The client treats it as an untrusted accelerator and checks everything before it trusts a single leaf:

**1. Identity and health**

`/health` must name this chain and this pool and report `healthy: true`, and it must carry an `indexedBlock`.

**2. Shape**

Every page of `/commitments` and `/nullifiers` must agree on the indexed block and the total, the commitments must be contiguous from leaf 0 and inside the field, and each ciphertext must be valid hex.

**3. The tail from RPC**

Anything after the indexer's `indexedBlock` is read from RPC up to a pinned block, and the first tail leaf must continue exactly where the indexer stopped.

**4. The pool decides**

At that pinned block, the merged list must match the chain: the rebuilt trees end at the pool's `treeNumber()` and `nextIndex()`, the current tree hashes to `getLastRoot()`, the root of every full tree is one the pool knows (`isKnownRoot`), the nullifiers number `nullifierCount()` with no repeats, and the leaf count is whole transactions. Receipt scans add `depositNonce()`.

Any failure raises an `IndexerError`, which `reportIndexerFallback` logs through the source's `onFallback` (or `console.warn`), and the scan continues as a plain RPC scan. Requests carry no identifying input at all: the client downloads the full lists and trial-decrypts locally.

One gap remains by design. An indexer could alter a note's ciphertext (the commitment and the root stay valid) and so hide that note from discovery. It cannot steal or forge anything, and a scan with `indexer` left out recovers the note.

Next: [Deposits, withdrawals and transfers](https://docs.fluton.io/sdk/transactions.md) builds on these keys and on the tree this scan rebuilds. [Notes and proofs](https://docs.fluton.io/concepts/notes-and-proofs.md) covers the note format itself.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.