@shippedcalls/sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +85 -2
  3. package/dist/abi.d.ts +1623 -0
  4. package/dist/abi.js +2096 -0
  5. package/dist/abi.js.map +1 -0
  6. package/dist/canonical.d.ts +2 -0
  7. package/dist/canonical.js +25 -0
  8. package/dist/canonical.js.map +1 -0
  9. package/dist/chain.d.ts +19 -0
  10. package/dist/chain.js +38 -0
  11. package/dist/chain.js.map +1 -0
  12. package/dist/cli.d.ts +2 -0
  13. package/dist/cli.js +294 -0
  14. package/dist/cli.js.map +1 -0
  15. package/dist/client.d.ts +154 -0
  16. package/dist/client.js +402 -0
  17. package/dist/client.js.map +1 -0
  18. package/dist/errors.d.ts +10 -0
  19. package/dist/errors.js +51 -0
  20. package/dist/errors.js.map +1 -0
  21. package/dist/hashes.d.ts +12 -0
  22. package/dist/hashes.js +25 -0
  23. package/dist/hashes.js.map +1 -0
  24. package/dist/index.d.ts +8 -0
  25. package/dist/index.js +8 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/odds.d.ts +40 -0
  28. package/dist/odds.js +70 -0
  29. package/dist/odds.js.map +1 -0
  30. package/dist/types.d.ts +406 -0
  31. package/dist/types.js +2 -0
  32. package/dist/types.js.map +1 -0
  33. package/package.json +32 -4
  34. package/skill/SKILL.md +60 -0
  35. package/skill/references/api.md +59 -0
  36. package/skill/references/funding.md +27 -0
  37. package/skill/references/settlement.md +39 -0
  38. package/skill/references/write-path.md +66 -0
  39. package/skill/scripts/calls.sh +3 -0
  40. package/src/abi.ts +2098 -0
  41. package/src/canonical.ts +24 -0
  42. package/src/chain.ts +41 -0
  43. package/src/cli.ts +286 -0
  44. package/src/client.ts +430 -0
  45. package/src/errors.ts +49 -0
  46. package/src/hashes.ts +32 -0
  47. package/src/index.ts +8 -0
  48. package/src/odds.ts +79 -0
  49. package/src/types.ts +299 -0
@@ -0,0 +1,24 @@
1
+ import { keccak256, stringToBytes } from "viem";
2
+
3
+ // Canonical JSON: keys sorted at every depth, no whitespace, bigints as decimal strings, undefined dropped. Two
4
+ // records that mean the same thing hash the same whatever order they were built in. evidenceSpec and the evidence
5
+ // hash onchain are keccak-256 of this.
6
+ export function canonical(value: unknown): string {
7
+ return JSON.stringify(sorted(value));
8
+ }
9
+
10
+ function sorted(value: unknown): unknown {
11
+ if (typeof value === "bigint") return value.toString();
12
+ if (Array.isArray(value)) return value.map((v) => (v === undefined ? null : sorted(v)));
13
+ if (value && typeof value === "object") {
14
+ const out: Record<string, unknown> = {};
15
+ const record = value as Record<string, unknown>;
16
+ for (const key of Object.keys(record).sort()) {
17
+ if (record[key] !== undefined) out[key] = sorted(record[key]);
18
+ }
19
+ return out;
20
+ }
21
+ return value;
22
+ }
23
+
24
+ export const hashJson = (value: unknown) => keccak256(stringToBytes(canonical(value)));
package/src/chain.ts ADDED
@@ -0,0 +1,41 @@
1
+ import { createPublicClient, createWalletClient, defineChain, fallback, http, type Account, type Chain, type PublicClient, type Transport, type WalletClient } from "viem";
2
+
3
+ export const CHAIN_ID = 4663;
4
+ export const API_URL = "https://calls.shipped.bond";
5
+ export const EXPLORER = "https://robinhoodchain.blockscout.com";
6
+ export const FACTORY = "0xf1F8E31D084B516b62E5646C684F7e955E8dA378" as const;
7
+ export const CALLED_IT = "0x9AA338e1BFe2ee19e715a0dEAaa9596eDF690cE1" as const;
8
+ export const DEEDS = "0xD5Da523ee49CB7Fe855B0C6fa38707190A9D531F" as const;
9
+
10
+ // The order Shipped's own services run: the official endpoint, then POKT, which also serves old state, then dRPC.
11
+ export const RPC_URLS = ["https://rpc.mainnet.chain.robinhood.com", "https://robinhood.api.pocket.network", "https://robinhood.drpc.org"] as const;
12
+
13
+ export function rpcEndpoints(rpc?: string | readonly string[]): string[] {
14
+ if (rpc == null || rpc === "") return [...RPC_URLS];
15
+ const urls = (typeof rpc === "string" ? rpc.split(",") : rpc).map((url) => url.trim()).filter(Boolean);
16
+ if (urls.length === 0) throw new Error("No RPC endpoint given.");
17
+ return urls;
18
+ }
19
+
20
+ export function chainFor(chainId: number, urls: string[]): Chain {
21
+ return defineChain({
22
+ id: chainId,
23
+ name: chainId === CHAIN_ID ? "Robinhood Chain" : `chain ${chainId}`,
24
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
25
+ rpcUrls: { default: { http: urls } },
26
+ ...(chainId === CHAIN_ID ? { blockExplorers: { default: { name: "Blockscout", url: EXPLORER } } } : {}),
27
+ });
28
+ }
29
+
30
+ // The public endpoints answer 429 to bursts and time out now and then; a failed request moves to the next one.
31
+ function transportFor(urls: string[], options: { batch?: boolean; timeout: number }): Transport {
32
+ const transports = urls.map((url) => http(url, options));
33
+ return transports.length === 1 ? transports[0]! : fallback(transports, { retryCount: 0 });
34
+ }
35
+
36
+ export function clientsFor({ chainId, urls, account, transport }: { chainId: number; urls: string[]; account?: Account; transport?: Transport }): { reads: PublicClient; writes: WalletClient | null } {
37
+ const chain = chainFor(chainId, urls);
38
+ const reads = createPublicClient({ chain, transport: transport ?? transportFor(urls, { batch: true, timeout: 10_000 }) });
39
+ const writes = account ? createWalletClient({ account, chain, transport: transport ?? transportFor(urls, { timeout: 10_000 }) }) : null;
40
+ return { reads, writes };
41
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,286 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { createInterface } from "node:readline/promises";
4
+ import { parseArgs } from "node:util";
5
+ import { formatEther } from "viem";
6
+ import { createClient, DEFAULT_MAX_BOND, DEFAULT_MAX_STAKE, prepareOpen, sideOf } from "./client.js";
7
+ import { CallsError } from "./errors.js";
8
+ import { ethToWei } from "./odds.js";
9
+ import type { CallDetail, CallRow, Quote } from "./types.js";
10
+
11
+ const HELP = `calls: read and bet on Shipped Calls, ETH markets on whether a public claim holds, on Robinhood Chain.
12
+
13
+ Read, no wallet needed:
14
+ calls list [--status open] [--type price] [--subject <handle>] [--sort closing|lopsided|pot|newest] [--limit 20] [--offset 0]
15
+ calls get <address>
16
+ calls quote <address> <holds|breaks> <eth>
17
+ calls positions [<wallet>]
18
+ calls proof
19
+
20
+ Write, with CALLS_PRIVATE_KEY set:
21
+ calls bet <address> <holds|breaks> <eth> [--quote] [--yes] [--max-stake <eth>]
22
+ calls claim <address> [--opener]
23
+ calls open --text <sentence> --spec <json|@file> [--handle <x handle>] [--post-url <url>] [--post-text <text>]
24
+ [--deadline <unix>] [--close-at <unix>] [--bond <eth>] [--max-bond <eth>] [--quote] [--yes]
25
+ calls open --text <sentence> --bond-number <n> [--deadline <unix>] [--close-at <unix>] [--bond <eth>] [--quote] [--yes]
26
+
27
+ --quote Show what would be sent and send nothing.
28
+ --yes Skip the confirmation. Without a terminal to confirm in, a bet or an open needs it.
29
+ --max-stake The most one bet may stake. 0.01 ETH unless set here or in CALLS_MAX_STAKE.
30
+ --max-bond The largest bond open may post. 0.02 ETH unless set.
31
+ --json Answer in JSON. A failure is {"error": "...", "code": "..."} with a non-zero exit.
32
+
33
+ Environment:
34
+ CALLS_PRIVATE_KEY The wallet that signs. Reads never need it.
35
+ CALLS_RPC_URL RPC endpoints, comma-separated, tried in order. A public list by default.
36
+ CALLS_API_URL https://calls.shipped.bond by default.
37
+ CALLS_MAX_STAKE The default for --max-stake, in ETH.
38
+
39
+ Details: https://calls.shipped.bond/agents
40
+ `;
41
+
42
+ const FLAGS = {
43
+ json: { type: "boolean" },
44
+ help: { type: "boolean", short: "h" },
45
+ version: { type: "boolean", short: "v" },
46
+ quote: { type: "boolean" },
47
+ yes: { type: "boolean", short: "y" },
48
+ opener: { type: "boolean" },
49
+ "max-stake": { type: "string" },
50
+ "max-bond": { type: "string" },
51
+ status: { type: "string" },
52
+ type: { type: "string" },
53
+ subject: { type: "string" },
54
+ sort: { type: "string" },
55
+ limit: { type: "string" },
56
+ offset: { type: "string" },
57
+ text: { type: "string" },
58
+ spec: { type: "string" },
59
+ handle: { type: "string" },
60
+ "post-url": { type: "string" },
61
+ "post-text": { type: "string" },
62
+ deadline: { type: "string" },
63
+ "close-at": { type: "string" },
64
+ bond: { type: "string" },
65
+ "bond-number": { type: "string" },
66
+ } as const;
67
+
68
+ type Values = ReturnType<typeof parseArgs<{ options: typeof FLAGS; allowPositionals: true }>>["values"];
69
+
70
+ const CONTROL = /[\u0000-\u0009\u000b-\u001f\u007f-\u009f]/g;
71
+ // Call and post text come from whoever wrote them, so nothing in them gets to drive the terminal.
72
+ const clean = (s: string | null | undefined) => String(s ?? "").replace(CONTROL, "");
73
+
74
+ const eth = (wei: string | bigint) => `${formatEther(BigInt(wei))} ETH`;
75
+ const when = (unix: number) => `${new Date(unix * 1000).toISOString().slice(0, 16).replace("T", " ")} UTC`;
76
+ const named = (side: string) => (side === "holds" ? "Holds" : "Breaks");
77
+
78
+ function unixOf(value: string | undefined, what: string): number | undefined {
79
+ if (value == null) return undefined;
80
+ if (!/^\d+$/.test(value)) throw new CallsError(`${what} is unix seconds.`, "bad_time");
81
+ return Number(value);
82
+ }
83
+
84
+ function needs(value: string | undefined, usage: string): string {
85
+ if (!value) throw new CallsError(`Usage: ${usage}`, "usage");
86
+ return value;
87
+ }
88
+
89
+ function specOf(value: string | undefined): Record<string, unknown> | undefined {
90
+ if (value == null) return undefined;
91
+ try {
92
+ return JSON.parse(value.startsWith("@") ? readFileSync(value.slice(1), "utf8") : value) as Record<string, unknown>;
93
+ } catch {
94
+ throw new CallsError("--spec is JSON, or @ and the path of a JSON file.", "bad_spec");
95
+ }
96
+ }
97
+
98
+ function clientFor(values: Values, env: NodeJS.ProcessEnv) {
99
+ const cap = values["max-stake"] ?? env.CALLS_MAX_STAKE;
100
+ return createClient({
101
+ api: env.CALLS_API_URL || undefined,
102
+ rpc: env.CALLS_RPC_URL || undefined,
103
+ privateKey: env.CALLS_PRIVATE_KEY || undefined,
104
+ maxStake: cap ? ethToWei(cap, "--max-stake") : DEFAULT_MAX_STAKE,
105
+ });
106
+ }
107
+
108
+ function rowLines(c: CallRow | CallDetail): string[] {
109
+ const odds = c.status === "open" ? `Holds ${c.odds.holdsMultiple ?? "-"}x, Breaks ${c.odds.breaksMultiple ?? "-"}x` : c.outcome ? `${named(c.outcome)} won` : c.status;
110
+ return [`${c.address} ${c.status} ${c.type} closes ${when(c.closeAt)} pot ${eth(c.pools.total)} ${odds}`, ` ${clean(c.callText) || "(no sentence stored)"}`];
111
+ }
112
+
113
+ function quoteLines(q: Quote, text?: string | null): string[] {
114
+ const lines = text ? [clean(text)] : [];
115
+ lines.push(`${eth(q.amount)} on ${named(q.side)} pays ${eth(q.payout)} (${q.multiple}x) if ${named(q.side)} wins, with the pools as they stand.`);
116
+ lines.push(`Pools after this bet: Holds ${eth(q.poolsAfter.holds)}, Breaks ${eth(q.poolsAfter.breaks)}. Later bets move the payout until betting closes.`);
117
+ if (q.refund) lines.push(`The other side is empty. If it stays empty, every stake comes back and nobody wins.`);
118
+ lines.push(q.bettingOpen ? `Betting closes ${when(q.closeAt)}.` : `Betting is closed on this Call (${q.status}).`);
119
+ return lines;
120
+ }
121
+
122
+ async function confirm(question: string, values: Values, command: string, extra: Record<string, unknown>): Promise<void> {
123
+ if (values.yes) return;
124
+ if (!process.stdin.isTTY) throw Object.assign(new CallsError(`Pass --yes to ${command}, or --quote to see it first. Nothing was sent.`, "needs_confirmation"), { extra });
125
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
126
+ // Closed input answers nothing, which is a no.
127
+ const answer = await new Promise<string>((resolve) => {
128
+ rl.once("close", () => resolve(""));
129
+ rl.question(`${question} [y/N] `).then(resolve, () => resolve(""));
130
+ });
131
+ rl.close();
132
+ if (!/^y(es)?$/i.test(answer.trim())) throw Object.assign(new CallsError("Stopped. Nothing was sent.", "declined"), { extra });
133
+ }
134
+
135
+ async function textOf(client: ReturnType<typeof createClient>, address: string): Promise<string | null> {
136
+ return client.call(address).then((c) => c.callText, () => null);
137
+ }
138
+
139
+ type Answer = { json: unknown; lines: string[] };
140
+
141
+ async function run(command: string | undefined, args: string[], values: Values, env: NodeJS.ProcessEnv): Promise<Answer> {
142
+ const client = clientFor(values, env);
143
+ switch (command) {
144
+ case "list": {
145
+ const calls = await client.calls({
146
+ status: values.status as never,
147
+ type: values.type as never,
148
+ subject: values.subject,
149
+ sort: values.sort as never,
150
+ limit: values.limit ? Number(values.limit) : undefined,
151
+ offset: values.offset ? Number(values.offset) : undefined,
152
+ });
153
+ return { json: { calls }, lines: calls.length ? calls.flatMap(rowLines) : ["No Calls match."] };
154
+ }
155
+ case "get": {
156
+ const address = needs(args[0], "calls get <address>");
157
+ let call: CallDetail;
158
+ try {
159
+ call = await client.call(address);
160
+ } catch (error) {
161
+ if (error instanceof CallsError && error.status === 404 && (await client.isCall(address).catch(() => false))) {
162
+ throw new CallsError("This Call is onchain and the API does not list it yet. A new Call appears within about a minute.", "not_indexed", 404);
163
+ }
164
+ throw error;
165
+ }
166
+ const lines = rowLines(call);
167
+ if (call.post?.url) lines.push(` Post: ${clean(call.post.url)}`);
168
+ lines.push(` Deadline ${when(call.deadline)}. ${call.betCount} bet${call.betCount === 1 ? "" : "s"}. Opener ${call.opener}, bond ${eth(call.bond)}.`);
169
+ if (call.evidence) lines.push(` Evidence: ${call.evidence.url}`);
170
+ if (call.unresolvable) lines.push(` Can't settle as written. Anyone can void it from ${when(call.unresolvable.refundsAt)}, and every stake comes back.`);
171
+ return { json: call, lines };
172
+ }
173
+ case "quote": {
174
+ const usage = "calls quote <address> <holds|breaks> <eth>";
175
+ const address = needs(args[0], usage);
176
+ const side = sideOf(needs(args[1], usage));
177
+ const amount = ethToWei(needs(args[2], usage), "The stake");
178
+ const quote = await client.quote(address, side, amount);
179
+ return { json: quote, lines: quoteLines(quote, await textOf(client, address)) };
180
+ }
181
+ case "bet": {
182
+ const usage = "calls bet <address> <holds|breaks> <eth> [--quote] [--yes] [--max-stake <eth>]";
183
+ const address = needs(args[0], usage);
184
+ const side = sideOf(needs(args[1], usage));
185
+ const amount = ethToWei(needs(args[2], usage), "The stake");
186
+ if (!values.quote && !client.address) throw new CallsError("Set CALLS_PRIVATE_KEY to bet. --quote shows what a bet pays without a wallet.", "no_wallet");
187
+ const [quote, text] = await Promise.all([client.quote(address, side, amount), textOf(client, address)]);
188
+ const lines = quoteLines(quote, text);
189
+ if (values.quote) return { json: { quote }, lines };
190
+ if (!values.json) console.error(lines.join("\n"));
191
+ await confirm(`Stake ${eth(amount)} on ${named(side)}?`, values, "place this bet", { quote });
192
+ const tx = await client.bet(address, side, amount);
193
+ return { json: { quote, tx }, lines: [`Bet placed: ${eth(amount)} on ${named(side)}. ${tx.explorerUrl ?? tx.hash}`] };
194
+ }
195
+ case "claim": {
196
+ const address = needs(args[0], "calls claim <address> [--opener]");
197
+ if (values.opener) {
198
+ const tx = await client.claimOpener(address);
199
+ return { json: tx, lines: [`Paid the opener ${tx.amount ? eth(tx.amount) : ""}. ${tx.explorerUrl ?? tx.hash}`] };
200
+ }
201
+ const tx = await client.claim(address);
202
+ return { json: tx, lines: [`Claimed ${tx.amount ? eth(tx.amount) : ""}. ${tx.explorerUrl ?? tx.hash}`] };
203
+ }
204
+ case "open": {
205
+ const usage = "calls open --text <sentence> --spec <json|@file> | --bond-number <n> [--yes]";
206
+ const input = {
207
+ callText: needs(values.text, usage),
208
+ spec: specOf(values.spec),
209
+ handle: values.handle,
210
+ postUrl: values["post-url"],
211
+ postText: values["post-text"],
212
+ deadline: unixOf(values.deadline, "--deadline"),
213
+ closeAt: unixOf(values["close-at"], "--close-at"),
214
+ bond: values.bond ? ethToWei(values.bond, "--bond") : undefined,
215
+ bondNumber: values["bond-number"] ? Number(values["bond-number"]) : undefined,
216
+ maxBond: values["max-bond"] ? ethToWei(values["max-bond"], "--max-bond") : DEFAULT_MAX_BOND,
217
+ };
218
+ if (!input.spec && input.bondNumber == null) throw new CallsError(`Usage: ${usage}`, "usage");
219
+ if (!values.quote && !client.address) throw new CallsError("Set CALLS_PRIVATE_KEY to open a Call. --quote shows what would be sent without a wallet.", "no_wallet");
220
+ const prepared = prepareOpen(input, client.chainId);
221
+ const lines = [clean(input.callText), `A ${prepared.type} Call with a ${eth(prepared.bond)} bond, stored with Shipped before it opens.`];
222
+ if (values.quote) return { json: { prepared }, lines };
223
+ if (!values.json) console.error(lines.join("\n"));
224
+ await confirm(`Post the ${eth(prepared.bond)} bond and open this Call?`, values, "open this Call", { prepared });
225
+ const opened = await client.open(input);
226
+ return { json: opened, lines: [`Opened ${opened.address}. Betting closes ${when(opened.closeAt)}. ${opened.explorerUrl ?? opened.hash}`] };
227
+ }
228
+ case "positions": {
229
+ const positions = await client.positions(args[0]);
230
+ const lines = [`${positions.address}${positions.balance == null ? "" : ` ${eth(positions.balance)}`}`];
231
+ lines.push(...positions.positions.map((p) => ` ${p.call} Holds ${eth(p.holds)}, Breaks ${eth(p.breaks)}, pays ${eth(p.paysNow)} if its side wins`));
232
+ const owed = positions.settled.filter((s) => s.owed && s.owed !== "0");
233
+ lines.push(...owed.map((s) => ` ${s.call} ${eth(s.owed!)} to claim`));
234
+ if (!positions.positions.length && !owed.length) lines.push(" No open positions and nothing to claim.");
235
+ return { json: positions, lines };
236
+ }
237
+ case "proof": {
238
+ const proof = await client.proof();
239
+ const lines = [`${proof.chain.name} (chain ${proof.chain.id}). Factory ${proof.factory.address}.`];
240
+ lines.push(...proof.contracts.map((c) => ` ${c.name}: ${c.address}${c.sourcify === "exact_match" ? ", source published, exact match" : ""}`));
241
+ if (proof.rules.minBet) lines.push(`Minimum bet ${eth(proof.rules.minBet)}. Fee ${(proof.rules.rakeBps ?? 0) / 100}% of the losing pool. Dispute window ${(proof.rules.disputeWindow ?? 0) / 3600} h.`);
242
+ if (proof.activity) lines.push(`${proof.activity.opened} Calls opened, ${eth(proof.activity.staked)} staked, ${eth(proof.activity.paidOut)} paid out.`);
243
+ if (proof.agents.length) lines.push(`Shipped agents: ${proof.agents.map((a) => a.name).join(", ")}.`);
244
+ return { json: proof, lines };
245
+ }
246
+ default:
247
+ throw new CallsError(`Unknown command "${command}". Try calls --help.`, "usage");
248
+ }
249
+ }
250
+
251
+ async function main(argv: string[], env: NodeJS.ProcessEnv): Promise<number> {
252
+ let parsed: ReturnType<typeof parseArgs<{ options: typeof FLAGS; allowPositionals: true }>>;
253
+ const wantsJson = argv.includes("--json");
254
+ try {
255
+ parsed = parseArgs({ args: argv, options: FLAGS, allowPositionals: true, strict: true });
256
+ } catch (error) {
257
+ return fail(new CallsError(`${(error as Error).message.split(". ")[0]}. Try calls --help.`, "usage"), wantsJson);
258
+ }
259
+ const { values, positionals } = parsed;
260
+ if (values.version) {
261
+ console.log((JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as { version: string }).version);
262
+ return 0;
263
+ }
264
+ const [command, ...args] = positionals;
265
+ if (values.help || !command) {
266
+ console.log(HELP);
267
+ return values.help ? 0 : 1;
268
+ }
269
+ try {
270
+ const answer = await run(command, args, values, env);
271
+ console.log(values.json ? JSON.stringify(answer.json, (_, v) => (typeof v === "bigint" ? v.toString() : v), 2) : answer.lines.join("\n"));
272
+ return 0;
273
+ } catch (error) {
274
+ return fail(error, Boolean(values.json));
275
+ }
276
+ }
277
+
278
+ function fail(error: unknown, json: boolean): number {
279
+ const known = error instanceof CallsError ? error : new CallsError("The request did not go through.", "unknown");
280
+ const extra = (error as { extra?: Record<string, unknown> }).extra;
281
+ if (json) console.log(JSON.stringify({ error: known.message, code: known.code, ...extra }, (_, v) => (typeof v === "bigint" ? v.toString() : v), 2));
282
+ else console.error(`error: ${known.message}`);
283
+ return 1;
284
+ }
285
+
286
+ process.exitCode = await main(process.argv.slice(2), process.env);