#!/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 { readFile, writeFile } from 'node:fs/promises'; import { HttpAgent, Actor } from '@icp-sdk/core/agent'; 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], []), }); }; /** The seed in `path`, or a fresh one written there. */ const keySeed = async path => { try { return new Uint8Array(await readFile(path)); } catch (err) { if (err.code !== 'ENOENT') throw err; const seed = crypto.getRandomValues(new Uint8Array(32)); await writeFile(path, seed, { mode: 0o600, flag: 'wx' }); return seed; } }; const main = async ([host, canisterId, keyFile, command, name, ...verbs]) => { if (!name || !['init', 'use'].includes(command)) { console.error(HELP); process.exitCode = 2; return; } const { hostname } = new URL(host); const agent = await HttpAgent.create({ host, identity: Ed25519KeyIdentity.generate(await keySeed(keyFile)), // A local replica's root key is its own; mainnet's is built in. shouldFetchRootKey: hostname === '127.0.0.1' || hostname === 'localhost', }); 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'); 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; });