Docs / Simulation & strategies

Run and resume agent simulations

Execute policies one stage at a time and keep a private checkpoint across restarts.

Two execution styles

simulateProcurement runs a complete deterministic round and returns its stage snapshots, transcript, payment plan and synthetic receipts. Use it for unit tests and experiments. startSimulation creates an empty checkpoint; advanceSimulation executes exactly one stage. Use the incremental API for a scheduler or interactive reference application.

import { startSimulation, advanceSimulation, replayRound } from "near-swarmkit";
let checkpoint = startSimulation(options); // no callbacks invoked
checkpoint = await advanceSimulation(checkpoint, options); // buyer demands
checkpoint = await advanceSimulation(checkpoint, options); // seller commitments
// Persist checkpoint atomically before progressing.
checkpoint = await advanceSimulation(checkpoint, options); // reveals
checkpoint = await advanceSimulation(checkpoint, options); // closed allocation
const publicSnapshot = await replayRound(checkpoint.transcript);

Asynchronous policies

Buyer demand and seller offer callbacks may return promises. A seller sees the pooled quantity; both receive the resource, asset and seeded random function. Policies may close over application history, balances or inventory. Keep them free of external side effects: if a host crashes before committing the returned checkpoint, a callback can run again. Hosts should impose timeouts and cancellation around external computations.

Private checkpoints, public transcripts

A SimulationSession includes unrevealed seller offers. It is trusted private state, not an interchange format to accept from strangers. Publish only its transcript or replayed snapshot. The built-in simulation salts are deterministic and must not be used for live hidden bids.

A working economy

The Market reference applies the SDK to 20 GPU buyers and five sellers, or a smaller inference market. It maintains inventory, work consumption, earned income, replenishment costs and utilization-based seller quotes. The same controller runs against IndexedDB in the browser and SQLite in the local service. The tests kill a process after recording a simulated broadcast and recover it in a new process.

git clone https://github.com/mikemoulder/swarmkit-market
cd swarmkit-market
npm ci
npm test
npm run experiment -- 12
npm run build
npm run serve

All these economy runs are simulation. Synthetic receipts and synthetic buyer approvals cannot move real funds. The experiment retains its SQLite database across invocations; use a new database path as the second argument for an independent run.

Runnable example

Download incremental-market.mjs. Run it from a project with near-swarmkit installed. It demonstrates serialization and async policies; the reference application supplies actual durable storage.