feat: Alice buys a widget from Bob, from the JS client

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)
This commit is contained in:
dckc committed 2026-11-18 06:40:09 -06:00
1 parent ed7d662d56
commit 9db91b1b9c
8 files changed
+287 -86

No files matched your search

+58
View File
@@ -0,0 +1,58 @@
/**
* @file Open a CapTP session to the canister as the principal of a key file.
*/
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;
}
};
/**
* Open a session to `canisterId` at `host` as the principal whose Ed25519
* seed is in `keyFile` (32 bytes, made if missing), logging each update call.
*
* @param {string} host the replica, e.g. https://icp-api.io
* @param {string} canisterId
* @param {string} keyFile
*/
export const connect = async (host, canisterId, keyFile) => {
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));
return openPeer({ module, seed, carry }, canisterId);
};