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

# Write and test a policy

> Build a multi-venue source with a policy, check it for free with analysis, preview and simulation, then request a round and read its outcome safely.

This guide builds a BTC/USD source that reads three exchanges, signs their median when at least two agree, and signs a declared fallback (`-1`) when they do not. You check it for free before paying for a round, then request one and read its outcome off-chain and on-chain. For how policies work, see [Policies](https://docs.molpha.io/concepts/policies.md). For the source format itself, see [Sources](https://docs.molpha.io/concepts/sources.md).

The snippets use `@molpha/sdk` 0.3.0 (ESM only, Node.js 20.19 or later). Steps 1 to 4 need no wallet and cost nothing.

```bash theme={null}
npm install @molpha/sdk @anchor-lang/core bn.js
```

## 1. Write the source

```ts theme={null}
import { defineSource, sx } from "@molpha/sdk";

// One http input per venue, each decoding a single field: price.
const venue = (url: string, path: string) =>
  sx.httpInput({ url, decode: sx.jsonDecode({ price: path }) });

// A candidate's value: the venue's price string as a decimal, at 2 decimals.
const candidate = (name: string) => ({
  value: sx.rescale(sx.num(sx.ref(`${name}.price`)), { scale: 2 }),
});

export const source = defineSource({
  inputs: {
    coinbase: venue("https://api.coinbase.com/v2/prices/BTC-USD/spot", "$.data.amount"),
    kraken: venue("https://api.kraken.com/0/public/Ticker?pair=XBTUSD", "$.result.XXBTZUSD.c[0]"),
    bitstamp: venue("https://www.bitstamp.net/api/v2/ticker/btcusd/", "$.last"),
  },
  policy: {
    candidates: {
      coinbase: candidate("coinbase"),
      kraken: candidate("kraken"),
      bitstamp: candidate("bitstamp"),
    },
    // At least 2 venues must qualify, and the qualifying prices must lie within 1% of the median.
    combine: { op: "median", minQualifying: 2, maxSpreadBps: 100 },
    // Signed under the same sourceId when the policy concludes INCONCLUSIVE.
    fallback: sx.cst("-1"),
  },
  transform: sx.ref("$agg"),
  // A price is never negative, so no result can be the fallback.
  assert: [sx.gte(sx.ref("$out"), sx.cst("0"))],
  output: { type: "int256", decimals: 2 },
  aggregation: { maxDeviationBps: 50, maxAgeMs: 3000 },
});

console.log(source.idHex); // the sourceId: it commits to the policy and the fallback
```

What each part does:

* **Candidates.** Every input is a candidate here. A candidate whose fetch or decode fails is disqualified (`onError` defaults to `disqualify`). Add `rules` to disqualify a candidate on its own data. For example, if an input also decoded a `ts` field (unix seconds), `rules: [sx.lte(sx.sub(sx.ref("$ts"), sx.ref("kraken.ts")), sx.cst("5"))]` would disqualify a quote older than 5 seconds.
* **Combine.** `median` signs the lower median of the qualifying values. Fewer than 2 qualifying venues is INCONCLUSIVE `0x01`; a spread above 100 bps is INCONCLUSIVE `0x02`.
* **Independence.** With two or more candidates `defineSource` sets `distinctHosts`: the three URLs must have different host names.
* **Fallback.** `-1` is signed for an INCONCLUSIVE result. The assertion `$out >= 0` makes it impossible for a real price to encode to the same word.
* **Tolerance.** Nodes read live prices at slightly different moments, so the source uses tolerance aggregation. In exact mode every signer would have to read byte-identical prices from all three venues.

`defineSource` validates the whole document and throws a `SourceError` naming the path of the first problem, before any request.

## 2. Analyze it

`analyzeSource` describes the source without fetching anything. `fallbackWords` lists the 32-byte words the fallback can sign:

```ts theme={null}
import { analyzeSource, fallbackWords } from "@molpha/sdk";

const analysis = analyzeSource(source);
console.log(analysis.policy?.fallback);
// { values: ["0xffff...ff9c"], reachable: false }
console.log(analysis.warnings);
// [{ code: "fallbackTolerance", path: "policy.inconclusive.fallback" }]
console.log(analysis.fetchesPerNode); // 3: every node reads every venue

const FALLBACK_WORDS = fallbackWords(source);
// ["0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9c"]
```

`-1` at 2 decimals is signed as `-100` in two's complement. Keep `FALLBACK_WORDS`: it is what you compare a verified value with.

Check two things before going further:

* `policy.fallback.reachable` is `false`. If it is `true` (warning `fallbackReachable`), a conclusive result can be the same word as the fallback and nobody can tell them apart. Add or tighten an assertion.
* Each warning is expected. Here `fallbackTolerance` says that a signed fallback is still a value: written to a Solana feed, it replaces the feed's last price. Step 7 shows how to avoid that.

The warnings and their meaning are listed under [Analysis](https://docs.molpha.io/concepts/policies.md#analysis). From an agent, the MCP tool `analyze_source` returns the same analysis plus the fallback words, locally and without a wallet.

## 3. Preview it against live data

`POST /v1/source/preview` fetches the inputs and evaluates the source the way a node would, twice, a second apart. Nothing is signed or charged.

```ts theme={null}
import { DEFAULT_GATEWAY_ENDPOINT } from "@molpha/sdk";

const gateway = DEFAULT_GATEWAY_ENDPOINT.replace(/\/+$/, ""); // https://gateway.molpha.io

const res = await fetch(`${gateway}/v1/source/preview`, {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({ source: source.doc }),
});
const { data } = await res.json();
console.log(data.value?.display, data.stable);
console.log(data.policy);
// { candidates: [{ name: "bitstamp", qualified: true, value: "..." }, ...],
//   n: 3, agg: "...", outcome: "conclusive", signed: false }
```

`stable: false` means the second run gave another value or failed. For a live price that is normal; for an exact-mode source it means nodes would disagree. If the preview fails, `data.error` gives the `stage`, `input` and `message`, and `data.inputs` holds each response it fetched. Previews are rate limited per client address (HTTP `429` with `Retry-After`).

## 4. Simulate failures

A preview shows today's data. To see what the policy does when a venue is down, stale or out of line, evaluate it over inputs you choose with `simulateSource`. It calls `POST /v1/source/simulate`, which runs the nodes' own evaluator. Nothing is fetched, signed or charged.

Give every input exactly one of a response `body` (decoded with the source's own decode block), decoded `fields`, or an `error` (`fetch` or `decode`):

```ts theme={null}
import { simulateSource } from "@molpha/sdk";

// Two venues down: one qualifying candidate is not enough.
const down = await simulateSource(gateway, source.doc, {
  coinbase: { body: '{"data":{"amount":"96000.10"}}' },
  kraken: { error: "fetch" },
  bitstamp: { error: "fetch" },
});
console.log(down.policy?.outcome, down.policy?.reason, down.policy?.signed);
// "inconclusive" "0x01" true
console.log(down.value?.display); // "-1": the fallback is what nodes would sign

// Three venues, too far apart.
const apart = await simulateSource(gateway, source.doc, {
  coinbase: { body: '{"data":{"amount":"96000"}}' },
  kraken: { body: '{"result":{"XXBTZUSD":{"c":["99000.0","1"]}}}' },
  bitstamp: { fields: { price: { type: "string", value: "90000" } } },
});
console.log(apart.policy?.reason); // "0x02": the spread is above 100 bps
```

| Result field | Meaning |
| - | - |
| `value` | What nodes would sign: `encoded`, `display`, `type`, `decimals`. Absent when the source refused |
| `error` | Where it refused: `stage`, `input`, `message`. Without a fallback an INCONCLUSIVE result shows `stage: "policy inconclusive"` |
| `policy.candidates[]` | `qualified`, and for a disqualified one `rule` (index of the first false rule) or `error` (`fetch`, `eval`) |
| `policy.n`, `policy.agg` | Qualifying candidates and the combined value |
| `policy.outcome`, `policy.reason` | `conclusive` or `inconclusive`, and the reason code |
| `policy.signed` | `true` when the fallback is the value |

Pass `{ timestampMs }` as the fourth argument to evaluate at a chosen round time (unix milliseconds on the 100 ms grid), which matters for rules that read `$ts` or `$tsMs`. A malformed request, such as a missing input, throws `SimulateError` with the HTTP `status`. With a `MolphaSDK` instance, `sdk.gateway.simulateSource(source.doc, inputs)` does the same on the client's first gateway.

From an agent, the MCP tool `simulate_source` takes the same `source` and `inputs` and asks the configured gateway.

A good set of cases before you pay: all venues healthy, each venue down alone, all but one down, one venue far from the others, and a value that should trip each rule.

## 5. Request a round

A policy round is requested and priced like any other. The snippets from here use `sdk`, set up with a Solana devnet wallet that has a subscription (see the [backend quickstart](https://docs.molpha.io/quickstarts/backend.md)):

```ts theme={null}
import { homedir } from "node:os";
import { join } from "node:path";
import { web3 } from "@anchor-lang/core";
import { MolphaSDK } from "@molpha/sdk";
import { walletFromKeypairFile } from "@molpha/sdk/utils";

const sdk = new MolphaSDK({
  connection: new web3.Connection("https://api.devnet.solana.com", "confirmed"),
  wallet: walletFromKeypairFile(join(homedir(), ".config/solana/id.json")),
});

const signaturesRequired = 3;
const result = await sdk.gateway.requestSignedData({ source, signaturesRequired });
```

Two admission rules apply to a source with a fallback. A request that breaks one gets HTTP `400` and is never retried:

* `signaturesRequired` must be above the registry's redundancy buffer (2 on the current devnet deployment, so any quorum of 3 or more).
* `requireProvider` cannot be set.

If the policy concludes INCONCLUSIVE, the round still succeeds and returns the signed fallback.

> [!WARNING]
>
> Without a fallback, an INCONCLUSIVE round is refused with HTTP `503` (`node round failed: policy inconclusive: reason 0x01 (insufficient sources)`). The SDK treats a `503` as a busy gateway and retries up to `maxRetries` (6 by default), and each retry is a new round that spends quota or needs another payment. For a policy source without a fallback, pass `maxRetries: 1` or `2`.

## 6. Read the outcome

Read the outcome from the signed value, never from a label:

```ts theme={null}
import { readOutcome } from "@molpha/sdk";

const outcome = readOutcome(result.payload, source);
if (outcome === null) throw new Error("not an attestation of this source");

if (outcome.kind === "fallback") {
  // INCONCLUSIVE: the signed value is -1. result.reason is a hint, e.g. "0x01".
  console.log("inconclusive", result.reason);
} else {
  console.log("price", result.value);
}
```

`readOutcome` returns `null` when the attestation's `sourceId` is not this source's, or its value is not one 32-byte word. Otherwise a value among `fallbackWords(source)` is `fallback`, and anything else is `conclusive`.

The SDK also fills `result.outcome` the same way, from the signed value. `result.reason` is the reason code the nodes reported. It is not signed: show it, log it, but do not settle anything on it.

### See why

`result.roundId` is the round's ID. The round archive serves the round and each node's [receipt](https://docs.molpha.io/concepts/policies.md#receipts) under it, free and without a key:

```ts theme={null}
const archived = await fetch(`https://indexer.molpha.io/v1/rounds/${result.roundId}`).then((r) => r.json());
for (const { node, receipt } of archived.receipts ?? []) {
  console.log(node, receipt.outcome, receipt.reason, receipt.inputs.map((i: any) => `${i.name}:${i.ok ? "ok" : i.error}`));
}
```

Each receipt shows which inputs the node read (`bodyHash` for an http body), which candidates qualified and why not, and the outcome the node reached. Receipts are unsigned and arrive a few seconds after the round. Private and paid-source rounds have none.

## 7. Consume it on-chain

A verifier checks the signature, not the outcome. Your consumer must compare the verified value with the fallback words.

### EVM and Starknet

Hard-code the fallback words of your pinned source, and branch on them after verification:

```solidity theme={null}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4 <0.9.0;

import {IVerifier} from "@molpha/evm-verifier/interfaces/IVerifier.sol";
import {MolphaLib} from "@molpha/evm-verifier/consumer/MolphaLib.sol";

contract BtcConsumer {
    using MolphaLib for IVerifier;
    using MolphaLib for MolphaLib.Latest;

    // fallbackWords(source)[0]: -1 at 2 decimals.
    bytes32 internal constant FALLBACK = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9c;

    IVerifier public immutable VERIFIER;
    MolphaLib.Policy internal policy;
    MolphaLib.Latest internal latest;

    int256 public lastPrice;
    bool public inconclusive;

    constructor(IVerifier verifier, bytes32 sourceId) {
        VERIFIER = verifier;
        policy = MolphaLib.Policy({sourceId: sourceId, minSignatures: 3, maxAge: 60});
    }

    function update(IVerifier.Attestation calldata att) external {
        VERIFIER.requireValid(att, policy); // source, quorum floor, freshness, signature
        latest.acceptNewer(att.payload);    // replay guard
        if (att.payload.value == FALLBACK) {
            inconclusive = true;            // keep lastPrice; pause, wait or refund
            return;
        }
        inconclusive = false;
        lastPrice = MolphaLib.asInt256(att.payload.value);
    }
}
```

A fallback that reads `$reason` or `$n` has several words: check against all of them. On Starknet, compare the verified `value` with the same words. See [EVM verifier](https://docs.molpha.io/verifiers/evm.md) and [Starknet verifier](https://docs.molpha.io/verifiers/starknet.md) for the rest of the consumer duties.

If the outcome settles something (a market, a payout), also close the door on outcome shopping: someone can request rounds until one gives the outcome they want. Accept only attestations whose `timestamp / 1000` falls inside your resolution window, and only the first one you accept.

### Solana

The program writes any verified value to the submitter's feed, so a submitted fallback replaces the feed's last price. Feeds are keyed by submitter, so only your own submits reach your feed. Check the outcome before you submit:

```ts theme={null}
if (readOutcome(result.payload, source)?.kind === "conclusive") {
  await sdk.solana.submitAttestation(result);
}
```

Do not use `sdk.requestAndSubmit` for such a source: it submits whatever the round returned. A program that reads another submitter's feed should compare the feed's value with the fallback words as well.

> [!NOTE]
>
> A continuously updated price feed is usually better served by a policy with no fallback: an INCONCLUSIVE round is then refused, and the feed keeps its last good value. Keep a fallback for consumers that must act on "no answer", such as settlement and verdict sources.

## Checklist

* `analyzeSource(source).policy.fallback.reachable` is `false`, and every warning is understood.
* Simulated: all venues healthy, each venue down, all but one down, a divergent venue.
* `signaturesRequired` is above the redundancy buffer if the source has a fallback; `maxRetries` is low if it has none.
* The outcome is read from the signed value (`readOutcome`, or a comparison with the fallback words on-chain), never from `reason` or the archive's `result`.
* Fallbacks are not written to Solana feeds that consumers read as prices.

> [card] [Policies](https://docs.molpha.io/concepts/policies.md)
>
> Combinators, reason codes, signing modes and receipts.

> [card] [Sources](https://docs.molpha.io/concepts/sources.md)
>
> Inputs, decoders, transforms and outputs.

> [card] [MCP tools](https://docs.molpha.io/mcp/tools.md)
>
> `analyze_source` and `simulate_source` for agents.


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