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

# Source format

> One JSON document says what the nodes read, how the reads become one value, and how that value becomes the 32 signed bytes.

A **source** defines one value. It is a single JSON document with up to four typed inputs (`http`, `evm`, `starknet`, `svm`), a transform that computes over exact decimals, assertions that must hold, a declared 32-byte output and, optionally, a median tolerance policy. Its `sourceId` is the keccak256 hash of its canonical bytes, so a source needs no registration, no creation step and no owner.

Only nodes evaluate a source. The gateway and the SDK parse, validate, canonicalize and hash it, and reject an invalid document with the path of the field that is wrong before anything is fetched or paid for.

## Build a source with the SDK

The common case is one JSON number from one URL:

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

const source = jsonPriceSource({
  url: "https://api.drand.sh/public/1000",
  path: "$.round",  // JSONPath to the value
  decimals: 0,      // signed as an int256 scaled by 10^0
});

source.idHex; // "0xb40f93879f3c4813045b3861e4fd6d57ea064e9ea6c6a4dd3f16906b214ffcac"
```

`jsonPriceSource` also takes `headers`, `valueIs: "string"` for a number sent as a JSON string, and `tolerance` (see [Aggregation](#aggregation)). Anything else is built with `defineSource` and the `sx` builders, which fill in the defaults and turn JS numbers into strings:

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

// EUR/USD from a JSON array, refused unless positive.
const source = defineSource({
  inputs: {
    fx: sx.httpInput({
      url: "https://api.example.com/rates",
      decode: sx.jsonDecode({
        rate: "$.data[?(@.pair.base=='EUR' && @.pair.quote=='USD')].rate",
      }),
    }),
  },
  transform: sx.rescale(sx.num(sx.ref("fx.rate")), { scale: 6 }), // the rate is a JSON string
  assert: [sx.gt(sx.ref("$out"), sx.cst(0))],
  output: { type: "int256", decimals: 6 },
});
```

A document that breaks a rule throws a `SourceError` naming the path. The builders for inputs are `sx.httpInput`, `sx.evmCall`, `sx.evmStorage`, `sx.evmBalance`, `sx.starknetCall`, `sx.svmAccount`, `sx.svmAccountInfo` and `sx.svmTokenSupply`; for decoders `sx.jsonDecode`, `sx.csvDecode`, `sx.xmlDecode`, `sx.textDecode`, `sx.abiDecode`, `sx.feltsDecode`, `sx.layoutDecode` and `sx.rawDecode`. Every operator below has a builder of the same name (`if` is `sx.iff`, `in` is `sx.inList`, constants are `sx.cst`).

For on-chain data you can also start from a [Molpha Data template](https://docs.molpha.io/data/overview.md), which expands a template and its parameters into a source.

## Shape

The source above, written out in full. This is what the gateway and the nodes receive:

```json theme={null}
{
  "v": "1",
  "inputs": {
    "px": {
      "kind": "http",
      "read": { "method": "GET", "url": "https://api.drand.sh/public/1000", "headers": {}, "body": null },
      "decode": { "format": "json", "fields": { "value": { "path": "$.round" } } }
    }
  },
  "transform": { "op": "rescale", "args": [{ "ref": "px.value" }], "scale": "0", "round": "halfEven" },
  "assert": [],
  "output": { "type": "int256", "decimals": "0" },
  "aggregation": null
}
```

| Key | What it is |
| - | - |
| `v` | Format version, `"1"`. |
| `inputs` | One to four named reads. Each yields named, typed fields. |
| `transform` | One expression over the fields. Its result is `$out`. |
| `assert` | Zero to eight conditions that must all be `true`, or no node signs. |
| `output` | How `$out` becomes the signed 32 bytes. |
| `aggregation` | `null` for exact mode, or a median tolerance policy. |
| `provenance` | Optional. The data provider whose signer may co-sign. See [Provenance](#provenance). |
| `policy` | Optional. Candidates, rules and a combinator over the inputs. See [Policies](https://docs.molpha.io/concepts/policies.md). |

Every key of every object is present, and an absent optional is `null`. The exceptions are `provenance` and `policy`, which are left out when unused and never written as `null`. Every number is a string (`"6"`, never `6`). A missing key, an unknown key or a wrong type is rejected with its path.

## Inputs

| `kind` | Extra keys | `read` |
| - | - | - |
| `http` | | `{ method: GET \| POST, url, headers, body }` |
| `evm` | `chain`, `finality` | `call` (`to`, `sig` + `args`, or raw `data`), `storage` (`address`, `slot`), `balance` (`address`) |
| `starknet` | `chain`, `finality` | `call` (`contract`, `selector`, `calldata`), `storage` (`contract`, `key`) |
| `svm` | `chain`, `commitment`, `maxAgeMs` | `account` (`address`, `dataSlice`), `accountInfo` (`address`), `tokenSupply` (`mint`) |

**HTTP.** The URL is committed and sent verbatim: printable ASCII, no spaces, no fragment, no user info, lowercase host. A `body` is `{ contentType, text }`, sent exactly, and only with `POST`. Header names are lowercase; `host`, `content-length`, `content-type`, `connection`, `transfer-encoding`, `te`, `upgrade` and `expect` cannot be set. A response is read up to 1 MB. Nodes refuse loopback, private and other non-public addresses.

**Chain reads.** A chain input names its chain by CAIP-2 id (`eip155:8453`, `starknet:SN_SEPOLIA`, `solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1`), never an RPC endpoint: each node reads through its own providers. EVM and Starknet reads are pinned to a block derived from the round's timestamp, so every node reads the same state. [Chain data sources](https://docs.molpha.io/concepts/chains.md) covers finality, the supported chains and the chains the gateway enables.

**Solana reads.** `account` reads an account's data (limit it with `dataSlice`) and decodes it with a fixed `layout`. `accountInfo` reads an account's metadata, never its data: the fields `lamports`, `owner` (32 bytes), `executable` and `space`. A missing account reads as zero lamports, an all-zero owner, not executable and space 0. `tokenSupply` reads a mint's `amount` and `decimals`. `accountInfo` and `tokenSupply` take `decode: null`. A read whose slot is more than `maxAgeMs` older than the round is refused, and an account owned by the Molpha program cannot be read.

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

// A wallet's SOL balance on devnet, signed with 9 decimals.
const balance = defineSource({
  inputs: {
    acct: sx.svmAccountInfo({
      chain: "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",
      address: WALLET, // base58
      maxAgeMs: 60_000,
    }),
  },
  transform: sx.shift(sx.ref("acct.lamports"), -9), // lamports × 10^-9, exactly
  output: { type: "uint256", decimals: 9 },
});
```

### Decoders

The decoder is declared, never inferred from a content type.

| `format` | For | Fields |
| - | - | - |
| `json` | `http` | `{ name: { path } }`; values are decimals, strings, bools or `null` |
| `csv` | `http` | `{ name: { col, row: { index } \| { match: { col, eq } } } }`, plus `header`, `delimiter`, `trim` |
| `xml` | `http` | `{ name: { path } }` with an absolute path ending in `/text()` or `/@attr` |
| `text` | `http` | `{ name: { regex } }`, an RE2 expression with exactly one capture group |
| `abi` | `evm` | `types` plus `{ name: { pick } }`, a dotted index such as `0` or `1.2` |
| `felts` | `starknet` | `{ name: { at, view } }`, view `felt`, `u256`, `bool`, `shortString` or `i128` |
| `layout` | `svm` | `discriminator` plus `{ name: { offset, type, ring? } }` |
| `raw` | any | none; the whole response as the field `raw` |

**JSON paths** support `$`, `.name`, `['name']`, `[n]` (negative counts from the end), a final `.length()`, and a filter that selects the first matching array element:

* `[?(@.symbol=='BTC')]`, or `!=` for not equal.
* 2 to 4 terms joined by `&&` (one space on each side): `[?(@.LineNumber=='2' && @.TimePeriod=='2026Q2')]`. There is no `||`.
* A term's key may be nested, up to 4 names joined by `.`: `[?(@.position.coin=='BTC')]`.

A term on a key the element lacks fails, for `!=` too. A path that ends on an object or an array, or names a missing key, is an error. Numbers are decoded exactly: an integer above 2^53 keeps every digit.

**Layouts** read fixed offsets in a Solana account: `u8`, `i8`, `bool`, `u16le` to `u128le`, `i16le` to `i128le`, `pubkey` and `bytes[n]`. The `dataSlice` must cover every field and the discriminator, and a discriminator mismatch fails the read. A field can be one slot of a ring buffer, such as an oracle's observation array whose newest slot moves: `ring: { index, back, len, stride }` reads the field at `offset + ((index - back) mod len) * stride`, where `index` names a plain `u8`, `u16le`, `u32le` or `u64le` field of the same decode, `len` is the slot count (1 to 4096), `back: 0` is the slot `index` points at and `back: 1` the one before it. In the SDK, pass `ring` per field to `sx.layoutDecode`.

## Transform

The transform is an expression tree: `{ "ref" }`, `{ "const" }`, `{ "str" }`, `{ "bytes" }`, `{ "bool" }`, or `{ "op", "args", ...params }`. It computes over **exact decimals**: an integer mantissa with up to 36 fractional digits, kept below 2^255 at every step. An overflow, a scale past 36 or a division by zero is an error, never a wrapped or rounded-away value. There is no floating point and no implicit conversion: a JSON string becomes a number only through `num`.

References:

| Reference | Value |
| - | - |
| `input.field` | A decoded field, such as `px.value` |
| `$ts` | The round timestamp in whole seconds |
| `$tsMs` | The round timestamp in milliseconds |
| `$block` | The pinned block or slot; only when the source has exactly one chain input |
| `$out` | The transform's result; in assertions only |

A source with a [policy](https://docs.molpha.io/concepts/policies.md) adds `$value`, `$agg`, `$n` and `$reason`.

| Group | Operators |
| - | - |
| Parse | `num` (mode `dec`, `hex` or `sci`), `int`, `str`, `hexBytes` |
| Arithmetic | `add`, `sub`, `mul`, `min`, `max`, `neg`, `abs` |
| Division | `div` (`scale` and `round` required) |
| Power | `pow(base, exp)` with `scale` and `round`; `exp` is a whole number, \|exp\| below 2^20 |
| Interpolation | `interp(x, x0, y0, …, xn, yn)` with `scale` and `round`: 2 to 16 points, xs never decreasing, clamped at both ends |
| Scale | `rescale` (`scale`, `round`), `shift` (multiply by 10^n, exactly) |
| Compare | `eq`, `ne`, `lt`, `lte`, `gt`, `gte` |
| Select | `if(cond, a, b)`, `coalesce(a, b)` |
| Logic | `and`, `or` (2 to 8 arguments), `not`, `in(x, c1, …, cn)` |
| Bytes | `keccak256`, `concat`, `slice` |
| String | `lower`, `upper` |

Rounding modes are `halfEven`, `down` (toward zero), `up` (away from zero) and `halfUp`. `pow` rounds at each squaring step, the same way on every node, so `1.0001^tick` or `(1 + binStep/10000)^binId` fits at scale 36. `interp` evaluates a piecewise-linear curve, such as a lending protocol's borrow-rate curve, in one node.

```ts theme={null}
// A Uniswap v3 tick to a price ratio: 1.0001^tick, computed at scale 36.
sx.pow(sx.cst("1.0001"), sx.ref("pool.tick"), { scale: 36 });

// Utilization to a borrow rate over a three-point curve.
sx.interp(sx.ref("u.util"), [[sx.cst(0), sx.cst(0)], [sx.cst("0.8"), sx.cst("0.04")], [sx.cst(1), sx.cst("0.75")]], { scale: 18 });
```

The transform and the assertions share a budget of 64 expression nodes (128 with a policy), and no tree is deeper than 12.

## Assertions

An assertion is an expression over the fields and `$out` that must be `true`. If one is false, errors or is not a bool, the node refuses to sign and says which. Use assertions to refuse a response that does not look right, for example a reading older than a minute (`lte(sub($ts, s.updatedAt), 60)` must hold) or an implausible value, so that it can never be attested.

## Output

`output.type` fixes how `$out` becomes the signed 32 bytes.

| `type` | `decimals` | Signed bytes |
| - | - | - |
| `int256` | 0 to 36 | `$out` rescaled half-even to `decimals`, two's complement |
| `uint256` | 0 to 36 | The same; a negative value is an error |
| `bool` | `null` | `0x…00` or `0x…01` |
| `bytes32` | `null` | Bytes, left-padded; more than 32 is an error |
| `string32` | `null` | UTF-8, right-padded with zeros; more than 32 bytes is an error |
| `keccak256` | `null` | `keccak256` of `$out`, which must be bytes or a string of at most 1 KB |

A numeric value is `value / 10^decimals`. For a `keccak256` output the signed value is the hash, and the round's response carries the bytes that were hashed as `valuePreimage`. See [Values](https://docs.molpha.io/concepts/feeds.md#values).

## Aggregation

`aggregation: null` is **exact mode**: every signing node must produce the same 32 bytes. That suits settled data: a finalized price, a document, a chain read pinned to a final block.

For a number that moves between fetches, use **tolerance mode**. Each node runs the whole source, the nodes exchange their results, drop stale observations and outliers, and sign the lower median:

```json theme={null}
"aggregation": { "mode": "tolerance", "rule": "median", "maxDeviationBps": "50", "maxAgeMs": "2000" }
```

| Field | Meaning |
| - | - |
| `rule` | `median`, the only rule. |
| `maxDeviationBps` | A value is in band when it is within this many basis points of the median. |
| `maxDeviationAbs` | Optional. A value within this distance of the median is also in band, in raw output units (the signed integer, before `decimals`). For values near zero, such as an age or a deviation, where a relative band cannot hold. Left out when unused, never `null`. |
| `maxAgeMs` | How old an observation may be, relative to the round's timestamp. Not the same as an `svm` input's `maxAgeMs`. |

* The output must be `int256`, and the round needs `signaturesRequired` of at least 3.
* The median is over each node's final output, after the transform, so a ratio of two moving inputs gets one band.
* `aggregation` is part of the `sourceId`: changing it gives a new source.

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

const btc = jsonPriceSource({
  url: "https://api.example.com/btc-usd",
  path: "$.price",
  valueIs: "string",
  decimals: 8,
  tolerance: { maxDeviationBps: 50, maxAgeMs: 2000 }, // add maxDeviationAbs for an absolute band
});
```

With `defineSource`, pass the same fields as `aggregation`.

## Provenance

`provenance: { "provider": "<id>" }` names the registered data provider whose own signer may co-sign rounds of the source. A request opts in with `requireProvider`: the round is then `signaturesRequired - 1` nodes plus the provider, and there is no fallback to a committee-only round while the provider's signer is down. Provenance is part of the `sourceId`, so the same reads with and without it are two sources. No provider signer is registered on the current deployment yet.

## Policies

A `policy` block qualifies and combines several inputs (median, fallback, majority and more) before the transform, and can declare a value to sign when the inputs do not support a result. See [Policies](https://docs.molpha.io/concepts/policies.md).

## Source ID

```text theme={null}
sourceId = keccak256(canonical source bytes)
```

The canonical form is a strict subset of RFC 8785 (JCS): UTF-8, object keys sorted, no whitespace, strings escaped as `JSON.stringify` does, and no JSON numbers at all. Every number is a string in one fixed spelling (`"6"`, not `"06"` or `"6.0"`), and a string outside its grammar is rejected rather than normalized, because two spellings would be two IDs.

* The gateway and the SDK accept any key order and whitespace and re-sort. A node accepts only the exact canonical bytes.
* The `sourceId` contains no owner, payer, quorum or chain. The same source has the same ID for everyone, on every chain.
* Derive it with `source.idHex`, `deriveSourceIdHex(doc)` or the MCP `derive_source_id` tool, not by hand. The gateway recomputes it, and the SDK refuses a response that names a different one.

## Private sources

An API key can stay out of the source. Write `{{secret.NAME}}` in an `http` input's URL (after the host and port), in a header value or in a body text, and send the values encrypted for the nodes with the SDK's `encrypt` option. The gateway never sees them. The public source, placeholders included, is what is hashed, and a node accepts the decrypted source only if it equals the public one everywhere except at the placeholders. See [Private APIs](https://docs.molpha.io/sdk/gateway-api.md#private-apis).

## Limits

| | |
| - | - |
| Canonical source | 8 KB (16 KB decrypted, for a private source) |
| Inputs / assertions / fields per input | 4 / 8 / 16 |
| Expression nodes / depth | 64 / 12 (128 nodes with a policy) |
| Response or account data per input | 1 MB |
| Headers / header value / body text | 16 / 1024 bytes / 4096 bytes |

## Check a source before you pay

* **Offline.** `defineSource` and `parseSource` validate the document; `checkChains(source)` checks chain inputs against the published chain list; `lintSource(source)` warns about a Solana account read in exact mode that may change every slot.

* **Preview.** `POST /v1/source/preview` on the gateway fetches and evaluates a source the way a node would, twice, one second apart, and returns the decoded fields and the 32 bytes nodes would sign. `stable: false` means the value moved between the two runs, so exact mode is unlikely to agree. Nothing is signed or charged.

  ```bash theme={null}
  curl -s https://gateway.molpha.io/v1/source/preview \
    -H 'content-type: application/json' \
    -d '{"source":{"v":"1","inputs":{"px":{"kind":"http","read":{"method":"GET","url":"https://api.drand.sh/public/1000","headers":{},"body":null},"decode":{"format":"json","fields":{"value":{"path":"$.round"}}}}},"transform":{"op":"rescale","args":[{"ref":"px.value"}],"scale":"0","round":"halfEven"},"assert":[],"output":{"type":"int256","decimals":"0"},"aggregation":null}}'
  # data.value.display is "1000", data.stable is true
  ```

* **Simulate.** `simulateSource(gatewayUrl, source.doc, inputs)` evaluates a source over inputs you supply (a body, decoded fields, or a failed fetch), which is how to test assertions, edge cases and policies. Nothing is fetched or signed.

* **MCP.** `derive_source_id`, `analyze_source` and `simulate_source` do the same from an agent.

## When a round fails

A node reports the stage that failed, and the gateway passes the message on (an HTTP `503` for a source the nodes ran and could not evaluate). The input's name is a suffix, as in `... (input px)`.

| Prefix | Stage |
| - | - |
| `parsing source` | The source is invalid or not canonical |
| `fetching data` | An input failed to fetch or decode; an HTTP status is kept as `api response status <code>` |
| `evaluating source` | The transform failed |
| `source assertion` | An assertion was false |
| `encoding output` | The result does not fit the declared output |
| `evaluating policy`, `policy inconclusive` | See [Policies](https://docs.molpha.io/concepts/policies.md) |


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