near-contract-sim is for testing NEAR smart contracts from Rust. It runs
nearcore's own runtime inside #[test], so a test deploys the
contract's wasm, sends signed transactions and follows every receipt
they spawn, in milliseconds, and cross-contract bugs show up in cargo test, not on a sandbox. One tool replaces a contract's near-sdk unit
tests (testing_env!) and its near-workspaces sandbox tests.
- Fast: a call takes milliseconds, with no node to start
- Self-contained: no node, no network, no sandbox binary
- Cross-contract calls: every promise, callback, refund and yield
runs, nothing mocked
- Real gas: matches a
neard sandbox, receipt by receipt
(fidelity)
- Your clock: set the time and height, the past included; yields time
out on cue
- Who paid whom: each call's own NEAR and token moves, exact while
other calls run in the same blocks
- Stubs and faults: make a callee answer as the test says, fail any
spawned call, or land a receipt late
- State in and out: typed contract state, and state records as
sandbox_patch_state takes them
Everyday tests are the core, and most users need only them. The audit
layer on top, explore, is experimental: its API changes more often, and
the CHANGELOG lists each break.
🔗 Test cross-contract calls
A unit test can call one method, but it can't follow the promise that
method returns. Here every receipt a call spawns runs, in the blocks a
single-shard chain runs it, with the gas a node charges. near-sdk's
cross-contract example computes a factorial by calling itself
(tests/docs.rs):
let out =
sim.call("alice.near", "factorial.near", "factorial").args_json(json!({"n": 3})).transact();
assert_eq!(out.json::<u32>(), 6);
// factorial(3) calls factorial(2), which calls factorial(1); callbacks multiply on the way back.
let callbacks = out.receipts.iter().filter(|r| r.method_names == ["factorial_mult"]);
assert!(callbacks.count() == 2 && out.receipts.iter().all(|r| r.is_success()), "{out}");
When an assertion fails, it prints the receipt tree and a gas table, so
you see which hop broke and why. Here, a call that ran out of gas:
tx 29HYHB… signed by alice.near at #3 (conversion 0.31 Tgas) -> FAILURE: out of gas (Exceeded the prepaid gas)
└─ #4 status.near::set_status attached 0.20 Tgas, burnt 1.09 Tgas (0.20 + 0.89 exec fees) FAILED: out of gas (Exceeded the prepaid gas)
log: alice.near set_status with message hi
⏰ Control the clock
Contracts that read env::block_timestamp() are hard to test on a node,
since its clock is the wall clock. Here the clock is a value you set, and
blocks happen when you ask for them. advance_to skips ahead cheaply, so
a week of 1 s blocks costs little, and a yield that nobody resumes times
out on cue (tests/docs.rs):
sim.set_timestamp_ns(1_577_836_800_000_000_000); // 2020-01-01, or any time, the past included
sim.advance_to(sim.height() + 7 * 86_400); // a week of 1 s blocks: 604,800 blocks
assert_eq!(sim.timestamp_ns(), 1_577_836_800_000_000_000 + 7 * 86_400 * 1_000_000_000);
sim.call("alice.near", "probe.near", "start_yield").transact().assert_success();
sim.advance_to(sim.yields()[0].expires_at); // the yield times out
sim.settle();
assert_eq!(sim.view("probe.near", "last", ()).json::<String>(), "timeout");
💥 Fail the branch nobody tests
A callback runs whether or not the call it waited on succeeded, and must
refund or roll back when it didn't. That branch is where funds go
missing, and it rarely runs in a test, since every callee succeeds. Here
any spawned call can fail, run short of gas or land late, and
out.effects() reads only that transaction's moves, so it stays exact
while other calls overlap it. A vault withdraw whose payout fails
(tests/vault.rs):
let w = withdraw(&mut sim, "alice.near", 40)
.inject(Receipts::callback("on_withdraw"), Fault::PromiseFailed)
.transact();
assert_eq!(w.u128(), 0);
assert_eq!(w.effects().token_net(TOKEN, "alice.near"), Ok(Delta::ZERO));
assert_eq!(w.effects().token_net(VAULT, "alice.near"), Ok(Delta::ZERO), "{w}");
// PromiseFailed at the callback starves the call it waits on: that call shows OutOfGas.
assert_eq!(w.expect_receipt("ft_transfer").fault, Some(Fault::OutOfGas));