shop.mjs runs the ERTP story step by step as the principal of a key file; connect.js holds the session setup it shares with counter.mjs. The client stages any number of string, integer, and reference arguments, and reports why an answer broke. A new start from a caller closes that caller's old session, so a client can come back with the same key. Generated-by: Claude Code (claude-opus-5-5)
53 lines
1.8 KiB
JavaScript
53 lines
1.8 KiB
JavaScript
#!/usr/bin/env node
|
|
/**
|
|
* @file Call the Counter canister over OCapN.
|
|
*/
|
|
const HELP = `usage: counter.mjs HOST CANISTER_ID KEY_FILE init NAME
|
|
counter.mjs HOST CANISTER_ID KEY_FILE use NAME [VERB...]
|
|
|
|
Open a CapTP session to the canister as the principal whose Ed25519 seed is
|
|
in KEY_FILE (32 bytes, made if missing), then:
|
|
|
|
init NAME make a counter, count on it (incr incr decr), and keep it in
|
|
your home under NAME
|
|
use NAME get the counter kept under NAME and send it each VERB
|
|
(incr, decr, value; default: incr value)
|
|
|
|
Each run's sends are pipelined: one update call after the handshake, plus
|
|
one for init. HOST is the replica, e.g. http://127.0.0.1:4960, or
|
|
https://icp-api.io.`;
|
|
|
|
import { connect } from './connect.js';
|
|
|
|
const main = async ([host, canisterId, keyFile, command, name, ...verbs]) => {
|
|
if (!name || !['init', 'use'].includes(command)) {
|
|
console.error(HELP);
|
|
process.exitCode = 2;
|
|
return;
|
|
}
|
|
const peer = await connect(host, canisterId, keyFile);
|
|
console.log('session open');
|
|
const home = peer.fetch('home');
|
|
/** Send each verb without waiting, then print each answer. */
|
|
const countOn = async (counter, sends) => {
|
|
const answers = sends.map(verb => [verb, peer.send(counter, verb)]);
|
|
await peer.flush();
|
|
for (const [verb, answer] of answers) console.log(verb, peer.valueOf(answer));
|
|
};
|
|
if (command === 'init') {
|
|
const counter = peer.send(peer.fetch('makeCounter'), 'make');
|
|
await countOn(counter, ['incr', 'incr', 'decr']);
|
|
const kept = peer.send(home, 'init', name, counter);
|
|
await peer.flush();
|
|
peer.valueOf(kept);
|
|
console.log(`kept as ${name}`);
|
|
} else {
|
|
await countOn(peer.send(home, 'get', name), verbs.length ? verbs : ['incr', 'value']);
|
|
}
|
|
};
|
|
|
|
main(process.argv.slice(2)).catch(err => {
|
|
console.error(err);
|
|
process.exitCode = 1;
|
|
});
|