Streams
A Stream is a capped, revocable, per-second allowance of a budget, aimed at exactly one service node. Streams are where enforcement lives: the cap bounds total spend, the rate envelope bounds burn speed, and revocation is instant and structural. All of it is enforced by your instance; the client cannot talk it out of a refusal.
Fan-out, delegation, revocation
import { Dynamo, HaltError, usd, units } from "@dynamoprotocol/sdk";
const dynamo = await Dynamo.open({
coreUrl: process.env.DYNAMO_CORE_URL!,
token: process.env.OWNER_API_TOKEN!,
});
const alice = "0x00000000000000000000000000000000000000A1";
const bob = "0x00000000000000000000000000000000000000B2";
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
const budget = await dynamo.openBudget({ funding: "none", cap: usd("15") });
// Fan out: two top-level allowances with independent caps and envelopes.
const research = await budget.stream({ to: alice, rate: units(1_000_000n), cap: units(5_000_000n) });
const writing = await budget.stream({ to: bob, rate: units(1_000_000n), cap: units(6_000_000n) });
// Recursive delegation: a child allowance under research's cap. The engine
// enforces subtree arithmetic structurally - children can never outspend
// their parent's cap, at any depth.
const summarizer = await research.delegate({ to: bob, rate: units(500_000n), cap: units(1_000_000n) });
await sleep(1_300);
await research.tick(units(600_000n));
await summarizer.tick(units(400_000n));
await writing.tick(units(500_000n));
// Free pre-check material - no cost to ask before doing paid work (rule:
// free pre-checks precede paid actions).
const room = await writing.headroom();
if (room.remainingCapUnits <= 0n) throw new Error("expected headroom");
// Revoke research: the WHOLE subtree (research + summarizer) is dead from
// this instant. Anything stamped later - or in this same wall-clock
// second - is structurally unsettleable (see "Settle before you revoke").
await research.revoke();
let halted = false;
try {
await summarizer.tick(units(1n));
} catch (err) {
halted = err instanceof HaltError;
}
if (!halted) throw new Error("a revoked subtree must fail closed");
await sleep(1_100);
await writing.tick(units(300_000n));
// Graceful shutdown: settle the last signed voucher BEFORE revoking, so a
// same-second revocation can strand nothing ("Settle before you revoke").
await writing.checkpoint({ force: true });
await writing.revoke();
await budget.close();
const session = await budget.aggregate();
if (!session.reconciled) throw new Error("engine and settlement layer disagree");
Settle before you revoke
Timestamps at the money layer are whole unix seconds (voucher fields are on-chain uint64 types). On contract version 1, settlement for a revoked stream includes only vouchers signed strictly before the revocation second. At second granularity, a voucher stamped in the revocation second cannot be proven to precede the revocation instant, so the money layer refuses it: fail closed, in the payer's favor.
revoke() settles first (owner-api 1.3.0 and later). Under the subtree's locks the core signs each open stream's outstanding work, force-checkpoints it, waits a bounded time for the settlement layer to pass the last signing time, and only then revokes. The halt never waits on a settlement failure: a stream that cannot settle is named in the signed revoke record and the revoke goes ahead. Work recorded but never signed is never billed.
await stream.checkpoint({ force: true }) is still useful before a revoke: it drives the stream's last signed voucher to settlement immediately and returns the settlement record (or null when nothing is unsettled), as the sample does before revoking writing. The method requires an instance serving owner-api 1.1.0 or later (client 2.1.0; older cores answer with a not-found error - fail closed, never silently dropped).
When the payee settles itself. On a stablecoin core with payee-kit custody (CORE_ESCROW_SETTLEMENT=payee-kit), the core holds no payee key: it hands each signed voucher to the payee, and the payee settles it with its own key (Getting paid as a payee). There, checkpoint({ force: true }) answers 409 state_conflict ("voucher for N units handed to the payee …; awaiting its settle") until the payee's settle lands on chain. That is not a failure: the voucher is signed and the payee can settle it. Wait for the payee's settle (or retry the checkpoint) before you revoke. On contract version 2 with a relayer (CORE_ESCROW_V2_RELAYER_KEY), the core submits the settle itself, and a voucher signed at the revoke instant still settles inside the grace window (Contract version 2).
Fallback for older cores (before owner-api 1.3.0, where revoke() does not settle first; before 1.1.0 checkpoint() does not exist either): let a full wall-clock second elapse between the final tick and revoke(); the settlement run at budget.close() then includes the last signed voucher. On such a core, revoking in the same wall-clock second as the final tick leaves those delivered units billed but unsettled.
Two related facts worth knowing when you audit a session:
session.reconciledasserts the core's settled totals equal what the
settlement layer itself reports. It does not assert that every billed unit settled - units a revoke could not settle leave both sides in agreement at the lower figure.
- If your integration needs the stronger fact, compare
session.totals.billedAmount with session.totals.settledAmount after close: equality means every signed voucher settled.
Fail closed, bill nothing
Each of these refusals throws HaltError and bills zero units (a mandate refusal at open throws MandateError instead). The exact reason is e.code (revoked, cap, rate, exposure, anomaly, frozen, stopped and others); e.reason is the older name, and a freeze or a stop shows reason as revoked:
- Revocation - the tick above: a revoked stream (or any descendant of
a revoked stream) cannot meter.
- Cap - a tick that would cross the stream's hard cap is refused
whole, never partially billed.
- Rate envelope - a tick that outruns accrued allowance
(rate × elapsed) is refused; burn speed is bounded even inside the cap.
- Exposure - a tick that would push the service node's unsettled work
past its exposure bound (the engine defaults, or the operator's CORE_NODE_PROTECTIONS) is refused.
- Anomaly - on a core running the verified runtime (
CORE_VERIFIED=1),
a stream opened with an anomaly envelope (the owner API's anomalyEnvelope field; this SDK does not set it) is stopped for good when its burn exceeds the envelope.
A failed action never costs anything - no unit is billed for refused work, on any rail.
Safe retries: idempotent ticks
Ticks are idempotent per requestRef. Re-sending the same reference - a retry after a timeout, a crashed worker replaying its journal - bills once and returns duplicate: true:
import { Dynamo, usd, units } from "@dynamoprotocol/sdk";
const dynamo = await Dynamo.open({
coreUrl: process.env.DYNAMO_CORE_URL!,
token: process.env.OWNER_API_TOKEN!,
});
const alice = "0x00000000000000000000000000000000000000A1";
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
const budget = await dynamo.openBudget({ funding: "none", cap: usd("5") });
const stream = await budget.stream({ to: alice, rate: units(1_000_000n), cap: units(2_000_000n) });
await sleep(1_100);
const first = await stream.tick(units(700_000n), "job-1");
if (first.duplicate) throw new Error("first billing must not be a duplicate");
// The retry: same requestRef, no double billing.
const retry = await stream.tick(units(700_000n), "job-1");
if (!retry.duplicate) throw new Error("a replayed requestRef must be a duplicate");
if (retry.cumulativeUnits !== first.cumulativeUnits) {
throw new Error("a duplicate must not change the billed total");
}
// A billed requestRef also yields a SIGNED consume receipt - the owner's
// audit record for that request, engine-signed (never a payment proof).
const receipt = await stream.receipt("job-1");
if (receipt.payload.requestRef !== "job-1") throw new Error("receipt must bind the requestRef");
await stream.revoke();
await budget.close();
const session = await budget.aggregate();
if (!session.reconciled) throw new Error("engine and settlement layer disagree");
For delivery-gated billing - bill only if the work delivers - meter AFTER delivery with the delivery's own reference as requestRef: a crashed or failed delivery bills nothing (rule: no cost for failed actions), and a replayed success bills once.