feat: Counter canister and a Node client, over OCapN on a local replica

The canister is freestanding wasm32 importing only ic0. Each caller
principal gets a CapTP session: start carries op:start-session, deliver
carries later frames, and each reply carries the canister's frames.

The client peer is wasm too, driven from Node by @icp-sdk/core. It
holds answer releases so they ride ahead of the next call instead of
costing an update call of their own: handshake, fetch, and each send
are one update call apiece.

Generated-by: Claude Code (claude-opus-5-5)
This commit is contained in:
dckc committed 2026-11-18 05:47:04 -06:00
1 parent 6348422012
commit 1177fc86b6
13 files changed
+787 -14

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env node
/**
* @file Call the Counter canister over OCapN.
*/
const HELP = `usage: counter.mjs HOST CANISTER_ID [VERB...]
Open a CapTP session to the canister, fetch "counter", and send each VERB
(incr, decr, value; default: incr incr decr), printing each answer.
HOST is the replica, e.g. http://127.0.0.1:4959, or https://icp-api.io.
A fresh Ed25519 identity makes each run its own caller, so its own session.`;
import { readFile } from 'node:fs/promises';
import { HttpAgent, Actor } from '@icp-sdk/core/agent';
import { IDL } from '@icp-sdk/core/candid';
import { Ed25519KeyIdentity } from '@icp-sdk/core/identity';
import { openPeer } from './peer.js';
/** The Candid interface in counter.did. */
const idlFactory = ({ IDL }) => {
const Frames = IDL.Vec(IDL.Nat8);
return IDL.Service({
start: IDL.Func([Frames], [Frames], []),
deliver: IDL.Func([Frames], [Frames], []),
});
};
const main = async ([host, canisterId, ...verbs]) => {
if (!host || !canisterId) {
console.error(HELP);
process.exitCode = 2;
return;
}
const local = new URL(host).hostname === '127.0.0.1' || new URL(host).hostname === 'localhost';
const agent = await HttpAgent.create({
host,
identity: Ed25519KeyIdentity.generate(),
// A local replica's root key is its own; mainnet's is built in.
shouldFetchRootKey: local,
});
const actor = Actor.createActor(idlFactory, { agent, canisterId });
const carry = async (method, frames) => {
const t0 = performance.now();
const reply = await actor[method](frames);
console.error(` ${method} ${frames.length}B -> ${reply.length}B in ${Math.round(performance.now() - t0)}ms`);
return reply;
};
const module = await WebAssembly.compile(
await readFile(new URL('../zig-out/bin/client.wasm', import.meta.url)),
);
const seed = crypto.getRandomValues(new Uint8Array(64));
const peer = await openPeer({ module, seed, carry }, canisterId);
console.log('session open');
await peer.fetch('counter');
console.log('fetched counter');
for (const verb of verbs.length ? verbs : ['incr', 'incr', 'decr']) {
console.log(verb, await peer.send(verb));
}
};
main(process.argv.slice(2)).catch(err => {
console.error(err);
process.exitCode = 1;
});
+133
View File
@@ -0,0 +1,133 @@
{
"name": "icp-ocapn-counter-client",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "icp-ocapn-counter-client",
"dependencies": {
"@icp-sdk/core": "6.1.1"
}
},
"node_modules/@dfinity/cbor": {
"version": "0.2.3",
"resolved": "https://registry.npmjs.org/@dfinity/cbor/-/cbor-0.2.3.tgz",
"integrity": "sha512-5GX+9tAf29r94Pxv8nCzrv2/t+AkOfem/c/G61+FA2Wadq7THvc5cvr/AVLH0LpukVfNSWRRHvl1fkCdiB9MMQ==",
"license": "Apache-2.0"
},
"node_modules/@icp-sdk/core": {
"version": "6.1.1",
"resolved": "https://registry.npmjs.org/@icp-sdk/core/-/core-6.1.1.tgz",
"integrity": "sha512-bMRKAJg0zwJyd53feg8D6Qd+ikoxrxzsVrvzmyjxgSwn7znKxBVyCN8GR/NEQ+dYaE+yWuXV0O3C8AiHL2JUqg==",
"license": "Apache-2.0",
"dependencies": {
"@dfinity/cbor": "^0.2.3",
"@noble/curves": "^2.2.0",
"@noble/hashes": "^2.2.0",
"@scure/bip32": "^2.2.0",
"@scure/bip39": "^2.2.0",
"asn1js": "^3.0.7"
}
},
"node_modules/@noble/curves": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.4.0.tgz",
"integrity": "sha512-P4/62zrgfH33CneE3Dn4WhJVA22YUU0eR51wKIan4NVRvwsA0YnPTwWGpNbpuacSujmSFLvyzpyuR30+fbq2Ew==",
"license": "MIT",
"dependencies": {
"@noble/hashes": "2.4.0"
},
"engines": {
"node": ">= 20.19.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@noble/hashes": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz",
"integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==",
"license": "MIT",
"engines": {
"node": ">= 20.19.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@scure/base": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@scure/base/-/base-2.4.0.tgz",
"integrity": "sha512-thZ1TuJwFwBblOhgsjDKvvGirBxNp+wSvY/DR6tJBJOTDhdAAcHJ8Vbr2eFnqaxeca4+t0i9KBf+uHYGWwZORg==",
"license": "MIT",
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@scure/bip32": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-2.4.0.tgz",
"integrity": "sha512-i3DS0CptAocyvqE4n3SUkpzeQK4vJMFwWLofTwRiiKo2aWojBOfyMCgfKw9HVpO6fSY5AK86sHS/Uzn8kK9Few==",
"license": "MIT",
"dependencies": {
"@noble/curves": "2.4.0",
"@noble/hashes": "2.4.0",
"@scure/base": "2.4.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@scure/bip39": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-2.4.0.tgz",
"integrity": "sha512-82dxFbZUYboyOf0AXiydsQrFQ5Q4h9mX+O2UkE91ROYmsc0BKMGZLwDmy96Jpa2+vrtoxomjUhy1RPIgH/r2nA==",
"license": "MIT",
"dependencies": {
"@noble/hashes": "2.4.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/asn1js": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.1.0.tgz",
"integrity": "sha512-HWYi1THkOqguCiO+vwj09ZkQFD2kKEsejYHAYCtX0D80WVdoDnvRc9IukXX/jeb0T9NRWJnRtqwdbHltnFjwXA==",
"license": "BSD-3-Clause",
"dependencies": {
"pvtsutils": "^1.3.6",
"pvutils": "^1.2.0",
"tslib": "^2.8.1"
},
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/pvtsutils": {
"version": "1.3.6",
"resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",
"integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==",
"license": "MIT",
"dependencies": {
"tslib": "^2.8.1"
}
},
"node_modules/pvutils": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.2.0.tgz",
"integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==",
"license": "MIT",
"engines": {
"node": ">=16.0.0"
}
},
"node_modules/tslib": {
"version": "2.9.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz",
"integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==",
"license": "0BSD"
}
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"name": "icp-ocapn-counter-client",
"private": true,
"type": "module",
"dependencies": {
"@icp-sdk/core": "6.1.1"
}
}
+91
View File
@@ -0,0 +1,91 @@
/**
* @file The client peer (`zig-out/bin/client.wasm`) driven over a canister's
* `start` and `deliver` update calls.
*/
const { freeze } = Object;
const decoder = new TextDecoder();
const encoder = new TextEncoder();
/**
* @typedef {(method: 'start' | 'deliver', frames: Uint8Array) => Promise<Uint8Array>} Carry
* one update call: the frames out, the frames in the reply
*/
/**
* Instantiate the client peer and open a session to `canisterId`.
*
* @param {object} io
* @param {WebAssembly.Module} io.module the compiled client.wasm
* @param {Uint8Array} io.seed 64 bytes of fresh entropy
* @param {Carry} io.carry
* @param {string} canisterId the canister's principal, as text
*/
export const openPeer = async ({ module, seed, carry }, canisterId) => {
const { exports: wasm } = await WebAssembly.instantiate(module, {
env: { report: (ptr, len) => console.error(readText(ptr, len)) },
});
const memory = () => new Uint8Array(wasm.memory.buffer);
const readText = (ptr, len) => decoder.decode(memory().slice(ptr, ptr + len));
/** Copy `bytes` into wasm memory for the length of `fn`. */
const withBytes = (bytes, fn) => {
const ptr = wasm.client_alloc(bytes.length || 1);
memory().set(bytes, ptr);
try {
return fn(ptr, bytes.length);
} finally {
wasm.client_free(ptr, bytes.length || 1);
}
};
const staged = () => memory().slice(wasm.client_out_ptr(), wasm.client_out_ptr() + wasm.client_out_len());
const check = (status, what) => {
if (status !== 0) throw Error(`${what}: ${decoder.decode(staged())}`);
};
/**
* Carry staged frames until the canister has nothing more to say. The
* first call of a session is `start`.
*/
let method = 'start';
const pump = async () => {
for (;;) {
const frames = staged();
if (frames.length === 0) return;
const reply = await carry(method, frames);
method = 'deliver';
check(withBytes(reply, wasm.client_feed), 'feed');
check(wasm.client_outbound(), 'outbound');
}
};
check(withBytes(seed, wasm.client_init), 'init');
check(withBytes(encoder.encode(canisterId), wasm.client_dial), 'dial');
await pump();
if (!wasm.client_session_open()) throw Error('session did not open');
/** Wait for the pending call's answer, carrying frames as needed. */
const settle = async () => {
await pump();
const kind = wasm.client_result_kind();
if (kind === 0) throw Error('no answer after the canister went quiet');
if (kind === 3) throw Error('broken');
return kind;
};
return freeze({
/** Fetch the capability published as `name` and make it the target. */
async fetch(name) {
check(withBytes(encoder.encode(name), wasm.client_fetch), 'fetch');
await settle();
check(wasm.client_adopt(), 'adopt');
},
/** Send `verb` to the target; resolve to its integer answer. */
async send(verb) {
check(withBytes(encoder.encode(verb), wasm.client_send), 'send');
await settle();
return Number(wasm.client_result_integer());
},
});
};