#!/usr/bin/env node /** * @file Call the Counter canister over OCapN. */ const HELP = `usage: counter.mjs HOST CANISTER_ID KEY_FILE init NAME [--abandon-all] counter.mjs HOST CANISTER_ID KEY_FILE use NAME [VERB...] [--abandon-all] 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. A principal has one session at a time; --abandon-all first ends the one a previous run left open. 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 argv => { const abandonAll = argv.includes('--abandon-all'); const [host, canisterId, keyFile, command, name, ...verbs] = argv.filter(arg => arg !== '--abandon-all'); if (!name || !['init', 'use'].includes(command)) { console.error(HELP); process.exitCode = 2; return; } const peer = await connect(host, canisterId, keyFile, { abandonAll }); 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; });