Files
captoys/client/counter.mjs
T
dckc 1177fc86b6 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)
2026-11-18 05:47:04 -06:00

65 lines
2.2 KiB
JavaScript

#!/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;
});