Files
captoys/client/counter.mjs
T
dckc da6c3f02ce feat(client): pipeline sends on the fetch's answer
Sends target an answer before it settles (Host.vowSend), so the fetch
and every send cross in one update call. Add icp.yaml for icp-cli, the
successor to dfx.

Generated-by: Claude Code (claude-opus-5-5)
2026-11-18 05:53:10 -06:00

67 lines
2.4 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 it each
VERB (incr, decr, value; default: incr incr decr) without waiting for the
fetch, then print 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');
// Pipelined: the sends target the fetch's answer before it settles, so
// the fetch and every send cross in one update call.
const counter = peer.fetch('counter');
const answers = (verbs.length ? verbs : ['incr', 'incr', 'decr']).map(verb => [verb, peer.send(counter, verb)]);
await peer.flush();
for (const [verb, answer] of answers) console.log(verb, peer.valueOf(answer));
};
main(process.argv.slice(2)).catch(err => {
console.error(err);
process.exitCode = 1;
});