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:
1 parent
ed7d662d56
commit
9db91b1b9c
8 files changed
+287
-86
No files matched your search
@@ -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);
|
||||
};
|
||||
+2
-45
@@ -17,31 +17,7 @@ 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;
|
||||
}
|
||||
};
|
||||
import { connect } from './connect.js';
|
||||
|
||||
const main = async ([host, canisterId, keyFile, command, name, ...verbs]) => {
|
||||
if (!name || !['init', 'use'].includes(command)) {
|
||||
@@ -49,26 +25,7 @@ const main = async ([host, canisterId, keyFile, command, name, ...verbs]) => {
|
||||
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);
|
||||
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. */
|
||||
|
||||
+13
-11
@@ -78,7 +78,10 @@ export const openPeer = async ({ module, seed, carry }, canisterId) => {
|
||||
const valueOf = slot => {
|
||||
const kind = wasm.client_result_kind(slot);
|
||||
if (kind === 0) throw Error(`answer ${slot} still pending after the canister went quiet`);
|
||||
if (kind === 3) throw Error(`answer ${slot} broke`);
|
||||
if (kind === 3) {
|
||||
check(wasm.client_result_broken(slot), 'broken');
|
||||
throw Error(`answer ${slot} broke: ${decoder.decode(staged())}`);
|
||||
}
|
||||
if (kind === 4) return undefined;
|
||||
return kind === 2 ? Number(wasm.client_result_integer(slot)) : { slot };
|
||||
};
|
||||
@@ -94,22 +97,21 @@ export const openPeer = async ({ module, seed, carry }, canisterId) => {
|
||||
/** @returns {Answer} the capability published as `name` */
|
||||
fetch: name => ({ slot: slotOf(withBytes(encoder.encode(name), (p, n) => wasm.client_fetch(p, n)), 'fetch') }),
|
||||
/**
|
||||
* Send `verb` to `target` with the arguments in `args`: at most one
|
||||
* string, then at most one settled reference.
|
||||
* Send `verb` to `target`, without waiting for it to settle.
|
||||
*
|
||||
* @param {Answer} target
|
||||
* @param {string} verb
|
||||
* @param {...(string | Answer)} args
|
||||
* @param {...(string | bigint | Answer)} args strings, integers, and
|
||||
* answers that have settled to references
|
||||
* @returns {Answer} `target`'s answer
|
||||
*/
|
||||
send: (target, verb, ...args) => {
|
||||
const text = args.find(arg => typeof arg === 'string');
|
||||
const object = args.find(arg => typeof arg === 'object');
|
||||
const status = withBytes(encoder.encode(verb), (verbPtr, verbLen) =>
|
||||
withBytes(encoder.encode(text ?? ''), (textPtr, textLen) =>
|
||||
wasm.client_send(target.slot, verbPtr, verbLen, textPtr, text === undefined ? -1 : textLen, object ? object.slot : -1),
|
||||
),
|
||||
);
|
||||
for (const arg of args) {
|
||||
if (typeof arg === 'string') check(withBytes(encoder.encode(arg), wasm.client_arg_text), 'argument');
|
||||
else if (typeof arg === 'bigint') check(wasm.client_arg_integer(arg), 'argument');
|
||||
else check(wasm.client_arg_reference(arg.slot), 'argument');
|
||||
}
|
||||
const status = withBytes(encoder.encode(verb), (p, n) => wasm.client_send(target.slot, p, n));
|
||||
return { slot: slotOf(status, 'send') };
|
||||
},
|
||||
flush,
|
||||
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* @file Alice buys a widget from Bob, over ERTP in the canister.
|
||||
*/
|
||||
const HELP = `usage: shop.mjs HOST CANISTER_ID KEY_FILE STEP
|
||||
|
||||
Each STEP runs as the principal whose key is in KEY_FILE (made if missing):
|
||||
|
||||
mint issue moola, mint 10 into a purse kept at home as "wallet",
|
||||
and post the moola issuer on the board
|
||||
open issue widgets, stock one, and post a shop selling it for 3
|
||||
moola, paid into a purse kept at home as "proceeds"
|
||||
buy pay 3 moola from "wallet" for the widget, and keep it in a
|
||||
purse at home as "closet"
|
||||
balances show each purse kept at home
|
||||
|
||||
Run mint and buy as Alice, open as Bob.`;
|
||||
|
||||
import { connect } from './connect.js';
|
||||
|
||||
const steps = {
|
||||
async mint(peer, home, board) {
|
||||
const mint = peer.send(peer.fetch('makeIssuerKit'), 'make', 'moola');
|
||||
const moola = peer.send(mint, 'getIssuer');
|
||||
const wallet = peer.send(moola, 'makeEmptyPurse');
|
||||
const minted = peer.send(mint, 'mintPayment', 10n);
|
||||
await peer.flush();
|
||||
const deposited = peer.send(wallet, 'deposit', minted);
|
||||
peer.send(home, 'init', 'wallet', wallet);
|
||||
peer.send(board, 'init', 'moola', moola);
|
||||
await peer.flush();
|
||||
console.log('minted', peer.valueOf(deposited), 'moola into wallet');
|
||||
},
|
||||
async open(peer, home, board) {
|
||||
const mint = peer.send(peer.fetch('makeIssuerKit'), 'make', 'widget');
|
||||
const widgets = peer.send(mint, 'getIssuer');
|
||||
const stock = peer.send(widgets, 'makeEmptyPurse');
|
||||
const widget = peer.send(mint, 'mintPayment', 1n);
|
||||
const proceeds = peer.send(peer.send(board, 'get', 'moola'), 'makeEmptyPurse');
|
||||
await peer.flush();
|
||||
const stocked = peer.send(stock, 'deposit', widget);
|
||||
const shop = peer.send(peer.fetch('makeShop'), 'make', 3n, proceeds, stock);
|
||||
peer.send(home, 'init', 'proceeds', proceeds);
|
||||
peer.send(board, 'init', 'widget', widgets);
|
||||
await peer.flush();
|
||||
peer.send(board, 'init', 'bobs-shop', shop);
|
||||
await peer.flush();
|
||||
console.log('stocked', peer.valueOf(stocked), 'widget; shop open at 3 moola');
|
||||
},
|
||||
async buy(peer, home, board) {
|
||||
const wallet = peer.send(home, 'get', 'wallet');
|
||||
const pay = peer.send(wallet, 'withdraw', 3n);
|
||||
const shop = peer.send(board, 'get', 'bobs-shop');
|
||||
await peer.flush();
|
||||
const goods = peer.send(shop, 'buy', pay);
|
||||
await peer.flush();
|
||||
try {
|
||||
peer.valueOf(goods);
|
||||
} catch (err) {
|
||||
// The shop refused; the payment still holds what was withdrawn.
|
||||
const back = peer.send(wallet, 'deposit', pay);
|
||||
await peer.flush();
|
||||
console.log('refunded', peer.valueOf(back), 'moola to wallet');
|
||||
throw err;
|
||||
}
|
||||
const closet = peer.send(peer.send(board, 'get', 'widget'), 'makeEmptyPurse');
|
||||
await peer.flush();
|
||||
const got = peer.send(closet, 'deposit', goods);
|
||||
peer.send(home, 'init', 'closet', closet);
|
||||
await peer.flush();
|
||||
console.log('bought', peer.valueOf(got), 'widget into closet');
|
||||
},
|
||||
async balances(peer, home) {
|
||||
const names = ['wallet', 'closet', 'proceeds'];
|
||||
const amounts = names.map(name => peer.send(peer.send(home, 'get', name), 'getCurrentAmount'));
|
||||
await peer.flush();
|
||||
names.forEach((name, i) => {
|
||||
let amount;
|
||||
try {
|
||||
amount = peer.valueOf(amounts[i]);
|
||||
} catch (err) {
|
||||
amount = `none (${err.message})`;
|
||||
}
|
||||
console.log(name, amount);
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
const main = async ([host, canisterId, keyFile, step]) => {
|
||||
if (!Object.hasOwn(steps, step ?? '')) {
|
||||
console.error(HELP);
|
||||
process.exitCode = 2;
|
||||
return;
|
||||
}
|
||||
const peer = await connect(host, canisterId, keyFile);
|
||||
await steps[step](peer, peer.fetch('home'), peer.fetch('board'));
|
||||
};
|
||||
|
||||
main(process.argv.slice(2)).catch(err => {
|
||||
console.error(err);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
Reference in new issue
Block a user