@swarm-tips/client 0.4.9 → 0.4.11

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.
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
1
+ import { closeSync, constants as fsConstants, lstatSync, mkdirSync, openSync, writeFileSync, } from "node:fs";
2
2
  import { join, resolve } from "node:path";
3
3
  import { CliUsageError } from "./keyfile.js";
4
4
  export const DEFAULT_LEAN_TOOLCHAINS = {
@@ -10,6 +10,11 @@ export const DEFAULT_LEAN_TOOLCHAINS = {
10
10
  export const DEFAULT_MATHLIB_REV_V2_V3 = "c5ea00351c28e24afc9f0f84379aa41082b1188f";
11
11
  export const DEFAULT_MATHLIB_REV_V4 = "51e6992efd06126df61a496bebf8f49482a4e129";
12
12
  export const DEFAULT_ZETA23_REV_V4 = "3635e74826a4c1fcece7d1cd2b6fa75e43a00510";
13
+ const LEAN_TOOLCHAIN_RE = /^leanprover\/lean4:v[0-9]+\.[0-9]+\.[0-9]+(-rc[0-9]+)?$/;
14
+ const GIT_COMMIT_SHA_RE = /^[0-9a-f]{40}$/;
15
+ const TASK_ID_RE = /^[A-Za-z0-9:._-]{1,128}$/;
16
+ const MODE_RE = /^[a-z0-9_-]{1,32}$/;
17
+ const IMPORT_IDENT_RE = /^[A-Za-z0-9_.]+$/;
13
18
  function parsePositiveIntDirective(statementLean, key) {
14
19
  const re = new RegExp(`^\\s*--\\s*swarm:${key}\\s*=\\s*(\\d+)\\s*$`, "m");
15
20
  const match = re.exec(statementLean);
@@ -26,13 +31,21 @@ function asLeanEnv(value) {
26
31
  ? value
27
32
  : undefined;
28
33
  }
29
- function nonEmptyString(value) {
30
- return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
31
- }
32
34
  function positiveInt(value) {
33
35
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
34
36
  }
37
+ function validateOptionalPattern(value, pattern, field, description) {
38
+ if (value === undefined || value === null)
39
+ return undefined;
40
+ if (typeof value !== "string" || !pattern.test(value)) {
41
+ throw new CliUsageError(`Invalid ${field} in task metadata: expected ${description}.`);
42
+ }
43
+ return value;
44
+ }
35
45
  export function extractLeanWorkspaceSpec(task, taskId) {
46
+ if (typeof taskId !== "string" || !TASK_ID_RE.test(taskId)) {
47
+ throw new CliUsageError(`Invalid task_id "${String(taskId)}": expected 1-128 characters matching [A-Za-z0-9:._-].`);
48
+ }
36
49
  if (task.platform !== 10) {
37
50
  throw new CliUsageError(`Task "${taskId}" is not a LeanProof task (platform=${String(task.platform)}, expected 10).`);
38
51
  }
@@ -42,27 +55,39 @@ export function extractLeanWorkspaceSpec(task, taskId) {
42
55
  }
43
56
  const env = asLeanEnv(task.lean_environment);
44
57
  const rawPolicy = positiveInt(env?.lean_policy) ?? positiveInt(task.lean_policy) ?? 1;
45
- const leanToolchain = nonEmptyString(env?.lean_toolchain) ??
58
+ const leanToolchain = validateOptionalPattern(env?.lean_toolchain, LEAN_TOOLCHAIN_RE, "lean_toolchain", "official leanprover/lean4:v<major>.<minor>.<patch>[-rc<N>] toolchain") ??
46
59
  DEFAULT_LEAN_TOOLCHAINS[rawPolicy] ??
47
60
  DEFAULT_LEAN_TOOLCHAINS[1];
48
61
  const defaultMode = rawPolicy === 4 ? "composable" : rawPolicy === 2 || rawPolicy === 3 ? "mathlib" : "self-contained";
49
- const mode = nonEmptyString(env?.mode) ?? defaultMode;
62
+ const mode = validateOptionalPattern(env?.mode, MODE_RE, "mode", "1-32 characters matching [a-z0-9_-]") ?? defaultMode;
50
63
  const defaultImports = rawPolicy === 4
51
64
  ? ["Mathlib", "Zeta23", "SwarmProofs"]
52
65
  : rawPolicy === 2 || rawPolicy === 3
53
66
  ? ["Mathlib"]
54
67
  : [];
55
- const importAllowlist = Array.isArray(env?.import_allowlist)
56
- ? env.import_allowlist.filter((item) => typeof item === "string" && item.trim().length > 0)
57
- : defaultImports;
58
- const mathlibRev = nonEmptyString(env?.mathlib_rev) ??
68
+ let importAllowlist;
69
+ if (env?.import_allowlist !== undefined && env?.import_allowlist !== null) {
70
+ if (!Array.isArray(env.import_allowlist)) {
71
+ throw new CliUsageError("Invalid import_allowlist in task metadata: expected array of Lean module names.");
72
+ }
73
+ importAllowlist = env.import_allowlist.map((item) => {
74
+ if (typeof item !== "string" || !IMPORT_IDENT_RE.test(item)) {
75
+ throw new CliUsageError(`Invalid import_allowlist entry "${String(item)}": expected Lean module identifier matching [A-Za-z0-9_.]+.`);
76
+ }
77
+ return item;
78
+ });
79
+ }
80
+ else {
81
+ importAllowlist = defaultImports;
82
+ }
83
+ const mathlibRev = validateOptionalPattern(env?.mathlib_rev, GIT_COMMIT_SHA_RE, "mathlib_rev", "40-character lowercase hex git commit SHA") ??
59
84
  (rawPolicy === 4
60
85
  ? DEFAULT_MATHLIB_REV_V4
61
86
  : rawPolicy === 2 || rawPolicy === 3
62
87
  ? DEFAULT_MATHLIB_REV_V2_V3
63
88
  : undefined);
64
- const zeta23Rev = nonEmptyString(env?.zeta23_rev) ?? (rawPolicy === 4 ? DEFAULT_ZETA23_REV_V4 : undefined);
65
- const swarmProofsRev = nonEmptyString(env?.swarm_proofs_rev);
89
+ const zeta23Rev = validateOptionalPattern(env?.zeta23_rev, GIT_COMMIT_SHA_RE, "zeta23_rev", "40-character lowercase hex git commit SHA") ?? (rawPolicy === 4 ? DEFAULT_ZETA23_REV_V4 : undefined);
90
+ const swarmProofsRev = validateOptionalPattern(env?.swarm_proofs_rev, GIT_COMMIT_SHA_RE, "swarm_proofs_rev", "40-character lowercase hex git commit SHA");
66
91
  const allowsDisproof = typeof env?.allows_disproof === "boolean"
67
92
  ? env.allows_disproof
68
93
  : hasBidirectionalDirective(statementLean);
@@ -191,19 +216,64 @@ export function buildLeanWorkspaceFiles(task, taskId) {
191
216
  "README.md": buildReadmeMd(spec),
192
217
  };
193
218
  }
219
+ function safeLstat(path) {
220
+ try {
221
+ return lstatSync(path);
222
+ }
223
+ catch (err) {
224
+ if (err?.code === "ENOENT")
225
+ return undefined;
226
+ throw err;
227
+ }
228
+ }
229
+ function writeFileNoFollow(dest, content) {
230
+ const noFollow = fsConstants.O_NOFOLLOW ?? 0;
231
+ const flags = fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_TRUNC | noFollow;
232
+ let fd;
233
+ try {
234
+ fd = openSync(dest, flags, 0o644);
235
+ }
236
+ catch (err) {
237
+ const code = err?.code;
238
+ if (code === "ELOOP" || code === "EMLINK") {
239
+ throw new CliUsageError(`Refusing to write through symbolic link at ${dest}.`);
240
+ }
241
+ throw err;
242
+ }
243
+ try {
244
+ writeFileSync(fd, content, "utf8");
245
+ }
246
+ finally {
247
+ closeSync(fd);
248
+ }
249
+ }
194
250
  /**
195
251
  * Materialize a Lean 4 prover workspace on disk. Refuses to overwrite any
196
- * existing non-empty target file unless `force === true`.
252
+ * existing non-empty target file unless `force === true`, and unconditionally
253
+ * refuses symbolic links (live or dangling) at the target directory or any
254
+ * destination file path even when `force === true`.
197
255
  */
198
256
  export function scaffoldLeanWorkspace(task, taskId, targetDir, force = false) {
199
257
  const spec = extractLeanWorkspaceSpec(task, taskId);
200
258
  const files = buildLeanWorkspaceFiles(task, taskId);
201
259
  const resolvedDir = resolve(targetDir);
260
+ const dirStat = safeLstat(resolvedDir);
261
+ if (dirStat) {
262
+ if (dirStat.isSymbolicLink()) {
263
+ throw new CliUsageError(`Refusing to scaffold into symbolic link directory: ${resolvedDir}.`);
264
+ }
265
+ if (!dirStat.isDirectory()) {
266
+ throw new CliUsageError(`Target path exists and is not a directory: ${resolvedDir}.`);
267
+ }
268
+ }
202
269
  const existingNonEmpty = [];
203
270
  for (const relName of Object.keys(files)) {
204
271
  const dest = join(resolvedDir, relName);
205
- if (existsSync(dest)) {
206
- const stat = statSync(dest);
272
+ const stat = safeLstat(dest);
273
+ if (stat) {
274
+ if (stat.isSymbolicLink()) {
275
+ throw new CliUsageError(`Refusing to write through symbolic link target file: ${dest}.`);
276
+ }
207
277
  if (stat.isDirectory() || stat.size > 0) {
208
278
  existingNonEmpty.push(relName);
209
279
  }
@@ -215,7 +285,12 @@ export function scaffoldLeanWorkspace(task, taskId, targetDir, force = false) {
215
285
  mkdirSync(resolvedDir, { recursive: true });
216
286
  const written = [];
217
287
  for (const [relName, content] of Object.entries(files)) {
218
- writeFileSync(join(resolvedDir, relName), content, "utf8");
288
+ const dest = join(resolvedDir, relName);
289
+ const postStat = safeLstat(dest);
290
+ if (postStat?.isSymbolicLink()) {
291
+ throw new CliUsageError(`Refusing to write through symbolic link target file: ${dest}.`);
292
+ }
293
+ writeFileNoFollow(dest, content);
219
294
  written.push(relName);
220
295
  }
221
296
  return {
package/dist/cli/swarm.js CHANGED
@@ -482,9 +482,16 @@ export async function runSwarmCli(argv, io = {}) {
482
482
  if (!arg) {
483
483
  throw new CliUsageError("Usage: swarm tasks next <task-json-or-id>");
484
484
  }
485
- const taskObj = arg.trim().startsWith("{")
486
- ? JSON.parse(arg)
487
- : await agent.tasks.get(arg.trim());
485
+ let taskObj;
486
+ if (arg.trim().startsWith("{")) {
487
+ taskObj = JSON.parse(arg);
488
+ }
489
+ else {
490
+ if (agent.auth.walletAddress) {
491
+ await agent.auth.authenticate().catch(() => undefined);
492
+ }
493
+ taskObj = await agent.tasks.get(arg.trim());
494
+ }
488
495
  writeOutput(stdout, jsonMode, agent.tasks.nextAction(taskObj));
489
496
  return 0;
490
497
  }
@@ -20,17 +20,27 @@ const DEFAULT_RPC = {
20
20
  async function main() {
21
21
  const args = process.argv.slice(2);
22
22
  if (args.length === 0 || args[0] === "--help" || args[0] === "-h") {
23
- process.stderr.write("Usage: vow-verify <attestation.json> [--rpc <url>]\n" +
24
- " vow-verify - [--rpc <url>] (read from stdin)\n");
23
+ process.stderr.write("Usage: vow-verify <attestation.json> [--network mainnet|devnet] [--rpc <url>]\n" +
24
+ " vow-verify - [--network mainnet|devnet] [--rpc <url>] (read from stdin)\n");
25
25
  return 2;
26
26
  }
27
27
  const path = args[0];
28
28
  let rpcUrlOverride;
29
+ let expectedNetwork = "mainnet";
29
30
  for (let i = 1; i < args.length; i++) {
30
31
  if (args[i] === "--rpc" && i + 1 < args.length) {
31
32
  rpcUrlOverride = args[i + 1];
32
33
  i++;
33
34
  }
35
+ else if (args[i] === "--network" && i + 1 < args.length) {
36
+ const candidate = args[i + 1];
37
+ if (candidate !== "mainnet" && candidate !== "devnet") {
38
+ process.stderr.write(`invalid --network "${candidate}" (expected "mainnet" or "devnet")\n`);
39
+ return 2;
40
+ }
41
+ expectedNetwork = candidate;
42
+ i++;
43
+ }
34
44
  }
35
45
  let raw;
36
46
  try {
@@ -48,14 +58,9 @@ async function main() {
48
58
  process.stderr.write(`invalid JSON in ${path}: ${e.message}\n`);
49
59
  return 2;
50
60
  }
51
- const network = typeof attestation === "object" &&
52
- attestation !== null &&
53
- typeof attestation.network === "string"
54
- ? attestation.network
55
- : "mainnet";
56
- const rpcUrl = rpcUrlOverride ?? DEFAULT_RPC[network] ?? DEFAULT_RPC.mainnet;
61
+ const rpcUrl = rpcUrlOverride ?? DEFAULT_RPC[expectedNetwork];
57
62
  const rpc = new Connection(rpcUrl, "confirmed");
58
- const verdict = await verifyV1(attestation, shillbotProtocol, rpc);
63
+ const verdict = await verifyV1(attestation, shillbotProtocol, rpc, undefined, expectedNetwork);
59
64
  process.stdout.write(JSON.stringify(verdict, null, 2) + "\n");
60
65
  return verdict.valid ? 0 : 1;
61
66
  }
@@ -4022,17 +4022,29 @@ export type Shillbot = {
4022
4022
  ];
4023
4023
  "type": "u8";
4024
4024
  },
4025
+ {
4026
+ "name": "payoutRouteKind";
4027
+ "docs": [
4028
+ "Kind of `payout_to` route recorded at `set_payout_to` time (P2-01,",
4029
+ "carved from `_reserved` — bytewise-compatible with existing on-chain",
4030
+ "tasks because legacy `_reserved` bytes are zero):",
4031
+ "- `0` (`PAYOUT_ROUTE_UNSET_OR_LEGACY`): unset or legacy pre-upgrade task",
4032
+ "- `1` (`PAYOUT_ROUTE_EXTENSION_CREDIT`): `extension-credit` Advance PDA",
4033
+ "- `2` (`PAYOUT_ROUTE_SYSTEM_WALLET`): explicit System-owned EOA wallet"
4034
+ ];
4035
+ "type": "u8";
4036
+ },
4025
4037
  {
4026
4038
  "name": "reserved";
4027
4039
  "docs": [
4028
4040
  "Reserved space for future fields without reallocation.",
4029
- "Reduced from 20 → 19 by D1 (`requires_approval`) → 18 by the",
4030
- "2026-07-07 `verification_kind` carve."
4041
+ "Reduced from 20 → 19 by D1 (`requires_approval`) → 18 by",
4042
+ "`verification_kind` → 17 by `payout_route_kind`."
4031
4043
  ];
4032
4044
  "type": {
4033
4045
  "array": [
4034
4046
  "u8",
4035
- 18
4047
+ 17
4036
4048
  ];
4037
4049
  };
4038
4050
  },
@@ -4016,17 +4016,29 @@
4016
4016
  ],
4017
4017
  "type": "u8"
4018
4018
  },
4019
+ {
4020
+ "name": "payout_route_kind",
4021
+ "docs": [
4022
+ "Kind of `payout_to` route recorded at `set_payout_to` time (P2-01,",
4023
+ "carved from `_reserved` — bytewise-compatible with existing on-chain",
4024
+ "tasks because legacy `_reserved` bytes are zero):",
4025
+ "- `0` (`PAYOUT_ROUTE_UNSET_OR_LEGACY`): unset or legacy pre-upgrade task",
4026
+ "- `1` (`PAYOUT_ROUTE_EXTENSION_CREDIT`): `extension-credit` Advance PDA",
4027
+ "- `2` (`PAYOUT_ROUTE_SYSTEM_WALLET`): explicit System-owned EOA wallet"
4028
+ ],
4029
+ "type": "u8"
4030
+ },
4019
4031
  {
4020
4032
  "name": "_reserved",
4021
4033
  "docs": [
4022
4034
  "Reserved space for future fields without reallocation.",
4023
- "Reduced from 20 → 19 by D1 (`requires_approval`) → 18 by the",
4024
- "2026-07-07 `verification_kind` carve."
4035
+ "Reduced from 20 → 19 by D1 (`requires_approval`) → 18 by",
4036
+ "`verification_kind` → 17 by `payout_route_kind`."
4025
4037
  ],
4026
4038
  "type": {
4027
4039
  "array": [
4028
4040
  "u8",
4029
- 18
4041
+ 17
4030
4042
  ]
4031
4043
  }
4032
4044
  },
@@ -1,5 +1,7 @@
1
1
  import { type Hex } from "viem";
2
2
  import type { CoordinationGameApiClient, EvmMatchPayload, XMatchPayload, XOutcomeCertPayload } from "../api.js";
3
+ /** Maximum horizon (7 days) allowed for relay-supplied `fund_deadline` / `match_deadline`. */
4
+ export declare const MAX_XCHAIN_DEADLINE_HORIZON_SECS: bigint;
3
5
  export declare function unpadAddress(word: string): Hex;
4
6
  /**
5
7
  * Normalize a 65-byte `0x` secp256k1 `[r||s||v]` signature so `v` is in the
@@ -51,6 +53,10 @@ export interface EvmFundCall {
51
53
  export interface EvmFundPin {
52
54
  contract: Hex;
53
55
  stakeWei: bigint;
56
+ /** Expected local EVM session key address (`leg_b.session_key`). Verified whenever provided. */
57
+ sessionKey?: Hex;
58
+ /** Optional Unix-seconds clock override for deadline horizon validation. */
59
+ nowSec?: number;
54
60
  }
55
61
  /**
56
62
  * Reconstruct the `CertLib.MatchLiveCert` tuple expected by `CrossChainGame`
@@ -1,8 +1,30 @@
1
1
  import { createPublicClient, encodeFunctionData, http, keccak256, toBytes, } from "viem";
2
2
  import { CROSS_CHAIN_GAME_ABI } from "./abi.js";
3
+ const ZERO_ADDRESS_HEX = "0000000000000000000000000000000000000000";
4
+ /** Maximum horizon (7 days) allowed for relay-supplied `fund_deadline` / `match_deadline`. */
5
+ export const MAX_XCHAIN_DEADLINE_HORIZON_SECS = 7n * 86400n;
3
6
  export function unpadAddress(word) {
4
- const hex = word.startsWith("0x") ? word.slice(2) : word;
5
- return `0x${hex.slice(-40)}`;
7
+ if (typeof word !== "string") {
8
+ throw new Error("invalid EVM address: expected hex string");
9
+ }
10
+ const hex = word.startsWith("0x") || word.startsWith("0X") ? word.slice(2) : word;
11
+ let addr;
12
+ if (/^[0-9a-fA-F]{40}$/.test(hex)) {
13
+ addr = hex.toLowerCase();
14
+ }
15
+ else if (/^[0-9a-fA-F]{64}$/.test(hex)) {
16
+ if (!hex.startsWith("000000000000000000000000")) {
17
+ throw new Error(`invalid 32-byte padded EVM address: non-zero high 12 bytes in ${word}`);
18
+ }
19
+ addr = hex.slice(24).toLowerCase();
20
+ }
21
+ else {
22
+ throw new Error(`invalid EVM address: expected 20-byte or zero-padded 32-byte hex, got ${word}`);
23
+ }
24
+ if (addr === ZERO_ADDRESS_HEX) {
25
+ throw new Error("invalid EVM address: zero address is not allowed");
26
+ }
27
+ return `0x${addr}`;
6
28
  }
7
29
  /**
8
30
  * Normalize a 65-byte `0x` secp256k1 `[r||s||v]` signature so `v` is in the
@@ -16,10 +38,12 @@ export function normalizeEvmSigV(sig) {
16
38
  }
17
39
  const body = sig.slice(2).toLowerCase();
18
40
  const rs = body.slice(0, 128);
19
- let v = parseInt(body.slice(128, 130), 16);
20
- if (v < 27)
21
- v += 27;
22
- return `0x${rs}${v.toString(16).padStart(2, "0")}`;
41
+ const v = parseInt(body.slice(128, 130), 16);
42
+ if (v !== 0 && v !== 1 && v !== 27 && v !== 28) {
43
+ throw new Error(`invalid secp256k1 signature recovery id v=${v}; expected 0, 1, 27, or 28`);
44
+ }
45
+ const normalizedV = v < 27 ? v + 27 : v;
46
+ return `0x${rs}${normalizedV.toString(16).padStart(2, "0")}`;
23
47
  }
24
48
  export async function findCrossChainMatch(api, input, options = {}) {
25
49
  const resolvedToken = options.token ?? input.token;
@@ -67,15 +91,24 @@ export async function findEvmMatch(api, input, options = {}) {
67
91
  throw new Error("no opponent found before timeout");
68
92
  }
69
93
  function verifyPin(match, pin) {
94
+ const pinnedContract = unpadAddress(pin.contract);
70
95
  const to = unpadAddress(match.leg_b.contract);
71
- if (to.toLowerCase() !== pin.contract.toLowerCase()) {
72
- throw new Error(`relay leg_b.contract ${to} != pinned CrossChainGame ${pin.contract}`);
96
+ if (to !== pinnedContract) {
97
+ throw new Error(`relay leg_b.contract ${to} != pinned CrossChainGame ${pinnedContract}`);
73
98
  }
74
99
  const stakeWei = BigInt(match.leg_b.stake_base_units);
75
100
  if (stakeWei !== pin.stakeWei) {
76
101
  throw new Error(`relay leg_b.stake ${stakeWei} != pinned stake ${pin.stakeWei}`);
77
102
  }
78
- return { to, stakeWei };
103
+ const legBSessionKey = unpadAddress(match.leg_b.session_key);
104
+ const legASessionKey = unpadAddress(match.leg_a.session_key);
105
+ if (pin.sessionKey !== undefined) {
106
+ const pinnedSessionKey = unpadAddress(pin.sessionKey);
107
+ if (legBSessionKey !== pinnedSessionKey) {
108
+ throw new Error(`relay leg_b.session_key ${legBSessionKey} != pinned sessionKey ${pinnedSessionKey}`);
109
+ }
110
+ }
111
+ return { to, stakeWei, legBSessionKey, legASessionKey };
79
112
  }
80
113
  function legTupleFromPayload(leg) {
81
114
  return {
@@ -108,18 +141,35 @@ export function certTupleFromMatchPayload(match) {
108
141
  };
109
142
  }
110
143
  export function buildEvmFundCall(match, pin) {
111
- const { to, stakeWei } = verifyPin(match, pin);
144
+ const { to, stakeWei, legBSessionKey, legASessionKey } = verifyPin(match, pin);
145
+ if (match.a_is_p1 !== 0 && match.a_is_p1 !== 1) {
146
+ throw new Error(`invalid a_is_p1=${String(match.a_is_p1)}; expected 0 or 1`);
147
+ }
148
+ const fundDeadline = BigInt(match.fund_deadline);
149
+ const matchDeadline = BigInt(match.match_deadline);
150
+ const nowSec = BigInt(pin.nowSec !== undefined ? Math.floor(pin.nowSec) : Math.floor(Date.now() / 1000));
151
+ const maxDeadline = nowSec + MAX_XCHAIN_DEADLINE_HORIZON_SECS;
152
+ if (fundDeadline <= 0n || matchDeadline <= 0n) {
153
+ throw new Error(`invalid deadlines (fund_deadline=${fundDeadline}, match_deadline=${matchDeadline}): must be > 0`);
154
+ }
155
+ if (matchDeadline < fundDeadline) {
156
+ throw new Error(`invalid deadlines: match_deadline (${matchDeadline}) < fund_deadline (${fundDeadline})`);
157
+ }
158
+ if (fundDeadline > maxDeadline || matchDeadline > maxDeadline) {
159
+ throw new Error(`relay deadline exceeds 7-day horizon (fund_deadline=${fundDeadline}, match_deadline=${matchDeadline}, max=${maxDeadline})`);
160
+ }
161
+ const operatorSig = normalizeEvmSigV(match.create_match_operator_sig);
112
162
  const data = encodeFunctionData({
113
163
  abi: CROSS_CHAIN_GAME_ABI,
114
164
  functionName: "createMatch",
115
165
  args: [
116
166
  match.match_id,
117
- unpadAddress(match.leg_b.session_key),
118
- unpadAddress(match.leg_a.session_key),
167
+ legBSessionKey,
168
+ legASessionKey,
119
169
  match.a_is_p1 === 0,
120
- BigInt(match.fund_deadline),
121
- BigInt(match.match_deadline),
122
- match.create_match_operator_sig,
170
+ fundDeadline,
171
+ matchDeadline,
172
+ operatorSig,
123
173
  ],
124
174
  });
125
175
  return { to, data, value: stakeWei };
@@ -316,6 +316,9 @@ export class InboxClient {
316
316
  if (!challenge.nonce) {
317
317
  throw new InboxApiError(0, "session challenge returned no nonce");
318
318
  }
319
+ if (typeof challenge.nonce !== "string" || !/^[0-9a-f]{64}$/.test(challenge.nonce)) {
320
+ throw new InboxApiError(0, "session challenge nonce must be 64 lowercase hex characters; refusing to sign arbitrary payload");
321
+ }
319
322
  const signature = await signNonce(challenge.nonce);
320
323
  const verified = await this.postUnauthed(SESSION_PATH, { wallet, nonce: challenge.nonce, signature });
321
324
  if (!verified.session_id) {
@@ -216,7 +216,10 @@ export declare class ShillbotApiClient {
216
216
  post<T>(path: string, body?: unknown): Promise<T>;
217
217
  patch<T>(path: string, body?: unknown): Promise<T>;
218
218
  listTasks<TTask = unknown>(limit?: number): Promise<TaskListResponse<TTask>>;
219
- getTask<TTask = unknown>(id: string, network?: "mainnet" | "devnet"): Promise<TTask>;
219
+ getTask<TTask = unknown>(id: string, networkOrOpts?: "mainnet" | "devnet" | {
220
+ network?: "mainnet" | "devnet";
221
+ token?: string | null;
222
+ }): Promise<TTask>;
220
223
  listAgentTasks<TTask = unknown>(): Promise<TTask[] | TaskListResponse<TTask>>;
221
224
  listPendingApproval<TTask = unknown>(networkOrOpts?: "mainnet" | "devnet" | {
222
225
  network?: "mainnet" | "devnet";
@@ -272,10 +275,111 @@ export interface PreparedTransactionExpectation {
272
275
  export declare const SHILLBOT_ESCROW_DEPLOYMENTS: Readonly<Record<string, `0x${string}`>>;
273
276
  /** Canonical 4-byte function selectors for `ShillbotEscrow.sol` lifecycle actions. */
274
277
  export declare const SHILLBOT_EVM_SELECTORS: Readonly<Record<Action, `0x${string}`>>;
278
+ /** Canonical ABI for `ShillbotEscrow.sol` lifecycle functions (`P2-27`). */
279
+ export declare const SHILLBOT_ESCROW_ABI: readonly [{
280
+ readonly type: "function";
281
+ readonly name: "createTask";
282
+ readonly stateMutability: "payable";
283
+ readonly inputs: readonly [{
284
+ readonly name: "statementCommitment";
285
+ readonly type: "bytes32";
286
+ }, {
287
+ readonly name: "policyId";
288
+ readonly type: "bytes32";
289
+ }, {
290
+ readonly name: "verificationKind";
291
+ readonly type: "uint8";
292
+ }, {
293
+ readonly name: "deadline";
294
+ readonly type: "uint64";
295
+ }, {
296
+ readonly name: "requiresApproval";
297
+ readonly type: "bool";
298
+ }];
299
+ readonly outputs: readonly [{
300
+ readonly name: "taskId";
301
+ readonly type: "uint64";
302
+ }];
303
+ }, {
304
+ readonly type: "function";
305
+ readonly name: "claimTask";
306
+ readonly stateMutability: "nonpayable";
307
+ readonly inputs: readonly [{
308
+ readonly name: "taskId";
309
+ readonly type: "uint64";
310
+ }];
311
+ readonly outputs: readonly [];
312
+ }, {
313
+ readonly type: "function";
314
+ readonly name: "submitWork";
315
+ readonly stateMutability: "nonpayable";
316
+ readonly inputs: readonly [{
317
+ readonly name: "taskId";
318
+ readonly type: "uint64";
319
+ }, {
320
+ readonly name: "contentIdHash";
321
+ readonly type: "bytes32";
322
+ }, {
323
+ readonly name: "artifactHash";
324
+ readonly type: "bytes32";
325
+ }];
326
+ readonly outputs: readonly [];
327
+ }, {
328
+ readonly type: "function";
329
+ readonly name: "approveTask";
330
+ readonly stateMutability: "nonpayable";
331
+ readonly inputs: readonly [{
332
+ readonly name: "taskId";
333
+ readonly type: "uint64";
334
+ }];
335
+ readonly outputs: readonly [];
336
+ }, {
337
+ readonly type: "function";
338
+ readonly name: "verifyTaskAttested";
339
+ readonly stateMutability: "nonpayable";
340
+ readonly inputs: readonly [{
341
+ readonly name: "taskId";
342
+ readonly type: "uint64";
343
+ }, {
344
+ readonly name: "score";
345
+ readonly type: "uint64";
346
+ }, {
347
+ readonly name: "sig";
348
+ readonly type: "bytes";
349
+ }];
350
+ readonly outputs: readonly [];
351
+ }, {
352
+ readonly type: "function";
353
+ readonly name: "finalizeTask";
354
+ readonly stateMutability: "nonpayable";
355
+ readonly inputs: readonly [{
356
+ readonly name: "taskId";
357
+ readonly type: "uint64";
358
+ }];
359
+ readonly outputs: readonly [];
360
+ }, {
361
+ readonly type: "function";
362
+ readonly name: "expireTask";
363
+ readonly stateMutability: "nonpayable";
364
+ readonly inputs: readonly [{
365
+ readonly name: "taskId";
366
+ readonly type: "uint64";
367
+ }];
368
+ readonly outputs: readonly [];
369
+ }];
275
370
  export interface PreparedEvmCallExpectation {
276
371
  action: Action;
277
372
  chain?: string;
278
373
  maxValueWei?: bigint;
374
+ taskId?: bigint | number | string;
375
+ contentIdHash?: `0x${string}`;
376
+ artifactHash?: `0x${string}`;
377
+ statementCommitment?: `0x${string}`;
378
+ policyId?: `0x${string}`;
379
+ verificationKind?: number;
380
+ deadline?: bigint | number | string;
381
+ requiresApproval?: boolean;
382
+ score?: bigint | number | string;
279
383
  }
280
384
  export interface ValidatedEvmCall {
281
385
  to: `0x${string}`;
@@ -285,9 +389,9 @@ export interface ValidatedEvmCall {
285
389
  }
286
390
  export declare function normalizeEvmChainId(chain: string | number): string;
287
391
  /**
288
- * C10 fail-closed local validator for server-prepared EVM `ShillbotEscrow` calls.
289
- * Verifies canonical contract address for `chain`, 4-byte function selector for
290
- * `action`, and `value_wei <= maxValueWei` (strictly `0n` on non-create actions).
392
+ * C10 + P2-27 fail-closed local validator for server-prepared EVM `ShillbotEscrow` calls.
393
+ * Verifies canonical contract address for `chain`, 4-byte function selector and full ABI-decoded
394
+ * calldata arguments for `action`, and `value_wei <= maxValueWei` (strictly `0n` on non-create actions).
291
395
  */
292
396
  export declare function validatePreparedEvmCall(evmCall: unknown, expected: PreparedEvmCallExpectation): ValidatedEvmCall;
293
397
  /**