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