@swarm-tips/client 0.2.13 → 0.4.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.
@@ -1,37 +1,346 @@
1
1
  import { Buffer } from "buffer";
2
- import { ComputeBudgetProgram, Secp256k1Program } from "@solana/web3.js";
2
+ import { ComputeBudgetProgram, Secp256k1Program, } from "@solana/web3.js";
3
3
  import { HttpClient } from "../http.js";
4
4
  import { SwarmClientError } from "../errors.js";
5
5
  import { SHILLBOT_PROGRAM_ID, inspectTransaction, shillbotInstructionDiscriminator, signAndBroadcast, } from "./index.js";
6
+ function decodeJwtWallet(token) {
7
+ if (!token)
8
+ return undefined;
9
+ const parts = token.split(".");
10
+ if (parts.length < 2)
11
+ return undefined;
12
+ try {
13
+ const b64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
14
+ const padded = b64 + "=".repeat((4 - (b64.length % 4)) % 4);
15
+ const decoded = JSON.parse(Buffer.from(padded, "base64").toString("utf8"));
16
+ if (typeof decoded.wallet === "string" && decoded.wallet)
17
+ return decoded.wallet;
18
+ if (typeof decoded.sub === "string" && decoded.sub)
19
+ return decoded.sub;
20
+ }
21
+ catch {
22
+ // Non-JWT opaque token; caller can supply opts.payer explicitly.
23
+ }
24
+ return undefined;
25
+ }
6
26
  export class ShillbotApiClient {
7
27
  http;
8
- constructor(options) { this.http = new HttpClient(options); }
9
- get(path) { return this.http.get(path); }
10
- post(path, body) { return this.http.post(path, body); }
11
- patch(path, body) { return this.http.patch(path, body); }
12
- listTasks(limit = 50) { return this.get(`/tasks?limit=${encodeURIComponent(String(limit))}`); }
13
- listAgentTasks() { return this.get("/agent/tasks"); }
14
- listPendingApproval() { return this.get("/tasks?status=pending_approval"); }
15
- listCampaigns() { return this.get("/campaigns"); }
16
- campaign(id) { return this.get(`/campaigns/${encodeURIComponent(id)}`); }
17
- campaignTasks(id) { return this.get(`/campaigns/${encodeURIComponent(id)}/tasks`); }
18
- campaignMetrics(id) { return this.get(`/campaigns/${encodeURIComponent(id)}/metrics`); }
19
- createCampaign(body) { return this.post("/campaigns", body); }
20
- updateCampaign(id, action) { return this.patch(`/campaigns/${encodeURIComponent(id)}`, { action }); }
21
- fundCampaignTask(id, body) { return this.post(`/campaigns/${encodeURIComponent(id)}/fund`, body); }
22
- onboard() { return this.post("/agent/onboard"); }
23
- earnings() { return this.get("/agent/earnings"); }
24
- claimTask(id, sponsor = "auto") { return this.post(`/tasks/${encodeURIComponent(id)}/claim?sponsor=${encodeURIComponent(sponsor)}`); }
25
- submitTask(id, body) { return this.post(`/tasks/${encodeURIComponent(id)}/submit`, body); }
26
- approveTask(id) { return this.post(`/tasks/${encodeURIComponent(id)}/approve`); }
27
- buildVerify(id) { return this.post(`/tasks/${encodeURIComponent(id)}/build-verify`); }
28
- buildFinalize(id) { return this.post(`/tasks/${encodeURIComponent(id)}/build-finalize`); }
29
- confirmTask(id, body) { return this.post(`/tasks/${encodeURIComponent(id)}/confirm`, body); }
28
+ constructor(options) {
29
+ this.http = new HttpClient(options);
30
+ }
31
+ get(path) {
32
+ return this.http.get(path);
33
+ }
34
+ post(path, body) {
35
+ return this.http.post(path, body);
36
+ }
37
+ patch(path, body) {
38
+ return this.http.patch(path, body);
39
+ }
40
+ listTasks(limit = 50) {
41
+ return this.get(`/tasks?limit=${encodeURIComponent(String(limit))}`);
42
+ }
43
+ getTask(id) {
44
+ return this.get(`/tasks/${encodeURIComponent(id)}`);
45
+ }
46
+ listAgentTasks() {
47
+ return this.get("/agent/tasks");
48
+ }
49
+ listPendingApproval() {
50
+ return this.get("/tasks?status=pending_approval");
51
+ }
52
+ listCampaigns() {
53
+ return this.get("/campaigns");
54
+ }
55
+ campaign(id) {
56
+ return this.get(`/campaigns/${encodeURIComponent(id)}`);
57
+ }
58
+ campaignTasks(id) {
59
+ return this.get(`/campaigns/${encodeURIComponent(id)}/tasks`);
60
+ }
61
+ campaignMetrics(id) {
62
+ return this.get(`/campaigns/${encodeURIComponent(id)}/metrics`);
63
+ }
64
+ createCampaign(body) {
65
+ return this.post("/campaigns", body);
66
+ }
67
+ updateCampaign(id, action) {
68
+ return this.patch(`/campaigns/${encodeURIComponent(id)}`, { action });
69
+ }
70
+ fundCampaignTask(id, body) {
71
+ return this.post(`/campaigns/${encodeURIComponent(id)}/fund`, body);
72
+ }
73
+ onboard() {
74
+ return this.post("/agent/onboard");
75
+ }
76
+ earnings() {
77
+ return this.get("/agent/earnings");
78
+ }
79
+ claimTask(id, sponsor = "auto") {
80
+ return this.post(`/tasks/${encodeURIComponent(id)}/claim?sponsor=${encodeURIComponent(sponsor)}`);
81
+ }
82
+ sponsorTask(id, body) {
83
+ return this.post(`/tasks/${encodeURIComponent(id)}/sponsor`, body);
84
+ }
85
+ submitTask(id, body) {
86
+ return this.post(`/tasks/${encodeURIComponent(id)}/submit`, body);
87
+ }
88
+ preflightTask(id, body) {
89
+ return this.post(`/tasks/${encodeURIComponent(id)}/preflight`, body);
90
+ }
91
+ approveTask(id) {
92
+ return this.post(`/tasks/${encodeURIComponent(id)}/approve`);
93
+ }
94
+ getVerificationData(id, network) {
95
+ const suffix = network && network !== "mainnet" ? `?network=${encodeURIComponent(network)}` : "";
96
+ return this.post(`/tasks/${encodeURIComponent(id)}/build-verify${suffix}`);
97
+ }
98
+ async buildVerify(id, opts) {
99
+ const mcpBaseUrl = (opts?.mcpBaseUrl ?? "https://mcp.swarm.tips").replace(/\/$/, "");
100
+ const resolvedNetwork = opts?.network ?? (this.http.network === "devnet" ? "devnet" : "mainnet");
101
+ const token = await this.http.getToken?.();
102
+ const payer = opts?.payer ?? decodeJwtWallet(token);
103
+ const postMcpBuildVerify = async (payload) => {
104
+ const mcpHttp = new HttpClient({
105
+ baseUrl: mcpBaseUrl,
106
+ fetch: this.http.fetchImpl,
107
+ getToken: this.http.getToken,
108
+ });
109
+ return mcpHttp.post("/internal/build-verify-tx", payload);
110
+ };
111
+ const oneHopBody = {
112
+ task_id: id,
113
+ network: resolvedNetwork,
114
+ ...(payer ? { payer } : {}),
115
+ };
116
+ try {
117
+ const direct = await postMcpBuildVerify(oneHopBody);
118
+ return {
119
+ ...direct,
120
+ task_id: direct.task_id ?? id,
121
+ transaction: direct.transaction,
122
+ task_pda: direct.task_pda,
123
+ transaction_intent: direct.transaction_intent,
124
+ };
125
+ }
126
+ catch (err) {
127
+ if (!(err instanceof SwarmClientError) ||
128
+ err.code !== "HTTP_ERROR" ||
129
+ (err.status !== 400 && err.status !== 422)) {
130
+ throw err;
131
+ }
132
+ const vdata = await this.getVerificationData(id, resolvedNetwork);
133
+ const fallback = await postMcpBuildVerify({
134
+ task_id: id,
135
+ ...(payer ? { payer } : {}),
136
+ network: resolvedNetwork,
137
+ task_pda: vdata.task_pda,
138
+ score: vdata.composite_score,
139
+ hash: vdata.verification_hash,
140
+ feed: vdata.switchboard_feed,
141
+ ...(vdata.global_state ? { global_state: vdata.global_state } : {}),
142
+ });
143
+ return {
144
+ ...fallback,
145
+ task_id: fallback.task_id ?? id,
146
+ transaction: fallback.transaction,
147
+ task_pda: fallback.task_pda ?? vdata.task_pda,
148
+ transaction_intent: fallback.transaction_intent,
149
+ };
150
+ }
151
+ }
152
+ buildFinalize(id) {
153
+ return this.post(`/tasks/${encodeURIComponent(id)}/build-finalize`);
154
+ }
155
+ confirmTask(id, body) {
156
+ return this.post(`/tasks/${encodeURIComponent(id)}/confirm`, body);
157
+ }
30
158
  }
31
159
  const SWITCHBOARD_PROGRAM_IDS = {
32
160
  mainnet: "SBondMDrcV3K4kxZR1HNVT7osZxAHVHgYXL5Ze1oMUv",
33
161
  devnet: "Aio4gaXjXzJNVLtzwtNVmSqGKpANtXhybbkhtAC94ji2",
34
162
  };
163
+ /** Canonical deployed ShillbotEscrow EVM contracts keyed by CAIP-2 chain ID. */
164
+ export const SHILLBOT_ESCROW_DEPLOYMENTS = {
165
+ "eip155:84532": "0xaFe061778f9A76fCe7da4124dC89DAF8309E5F3c",
166
+ };
167
+ /** Canonical 4-byte function selectors for `ShillbotEscrow.sol` lifecycle actions. */
168
+ export const SHILLBOT_EVM_SELECTORS = {
169
+ create: "0xa4aaf1b3", // createTask(bytes32,bytes32,uint8,uint64,bool)
170
+ claim: "0xe6a81fdd", // claimTask(uint64)
171
+ submit: "0xfb78a429", // submitWork(uint64,bytes32,bytes32)
172
+ approve: "0x97312249", // approveTask(uint64)
173
+ verify: "0x3bae608b", // verifyTaskAttested(uint64,uint64,bytes)
174
+ finalize: "0xcb26e65b", // finalizeTask(uint64)
175
+ };
176
+ function normalizeEvmChainId(chain) {
177
+ const trimmed = chain.trim().toLowerCase();
178
+ if (trimmed === "base-sepolia" || trimmed === "84532")
179
+ return "eip155:84532";
180
+ if (trimmed === "base" || trimmed === "8453")
181
+ return "eip155:8453";
182
+ if (trimmed === "ethereum" || trimmed === "1")
183
+ return "eip155:1";
184
+ if (trimmed === "ethereum-sepolia" || trimmed === "sepolia" || trimmed === "11155111") {
185
+ return "eip155:11155111";
186
+ }
187
+ return trimmed;
188
+ }
189
+ /**
190
+ * C10 fail-closed local validator for server-prepared EVM `ShillbotEscrow` calls.
191
+ * Verifies canonical contract address for `chain`, 4-byte function selector for
192
+ * `action`, and `value_wei <= maxValueWei` (strictly `0n` on non-create actions).
193
+ */
194
+ export function validatePreparedEvmCall(evmCall, expected) {
195
+ if (!evmCall || typeof evmCall !== "object") {
196
+ throw new SwarmClientError({
197
+ code: "TRANSACTION_MISMATCH",
198
+ operation: "shillbot.validatePreparedEvmCall",
199
+ message: "Prepared EVM call must be an object",
200
+ });
201
+ }
202
+ const raw = evmCall;
203
+ if (typeof raw.to !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(raw.to)) {
204
+ throw new SwarmClientError({
205
+ code: "TRANSACTION_MISMATCH",
206
+ operation: "shillbot.validatePreparedEvmCall",
207
+ message: "Prepared EVM call has an invalid target contract address",
208
+ });
209
+ }
210
+ if (typeof raw.data !== "string" ||
211
+ !/^0x[0-9a-fA-F]{8,}$/.test(raw.data) ||
212
+ raw.data.length % 2 !== 0) {
213
+ throw new SwarmClientError({
214
+ code: "TRANSACTION_MISMATCH",
215
+ operation: "shillbot.validatePreparedEvmCall",
216
+ message: "Prepared EVM call data must include at least a 4-byte function selector",
217
+ });
218
+ }
219
+ const callChain = typeof raw.chain === "string"
220
+ ? normalizeEvmChainId(raw.chain)
221
+ : typeof raw.chain_id === "number"
222
+ ? `eip155:${raw.chain_id}`
223
+ : undefined;
224
+ const expectedChain = expected.chain ? normalizeEvmChainId(expected.chain) : undefined;
225
+ if (callChain && expectedChain && callChain !== expectedChain) {
226
+ throw new SwarmClientError({
227
+ code: "TRANSACTION_MISMATCH",
228
+ operation: "shillbot.validatePreparedEvmCall",
229
+ message: `Prepared EVM call chain ${callChain} differs from expected ${expectedChain}`,
230
+ });
231
+ }
232
+ const resolvedChain = expectedChain ?? callChain ?? "eip155:84532";
233
+ const canonicalContract = SHILLBOT_ESCROW_DEPLOYMENTS[resolvedChain];
234
+ if (!canonicalContract) {
235
+ throw new SwarmClientError({
236
+ code: "TRANSACTION_MISMATCH",
237
+ operation: "shillbot.validatePreparedEvmCall",
238
+ message: `No canonical ShillbotEscrow contract deployed for chain ${resolvedChain}`,
239
+ });
240
+ }
241
+ if (raw.to.toLowerCase() !== canonicalContract.toLowerCase()) {
242
+ throw new SwarmClientError({
243
+ code: "TRANSACTION_MISMATCH",
244
+ operation: "shillbot.validatePreparedEvmCall",
245
+ message: `Target contract ${raw.to} does not match canonical ShillbotEscrow ${canonicalContract}`,
246
+ });
247
+ }
248
+ const expectedSelector = SHILLBOT_EVM_SELECTORS[expected.action];
249
+ if (!expectedSelector) {
250
+ throw new SwarmClientError({
251
+ code: "INVALID_ARGUMENT",
252
+ operation: "shillbot.validatePreparedEvmCall",
253
+ message: `Unsupported Shillbot action: ${String(expected.action)}`,
254
+ });
255
+ }
256
+ const actualSelector = raw.data.slice(0, 10).toLowerCase();
257
+ if (actualSelector !== expectedSelector.toLowerCase()) {
258
+ throw new SwarmClientError({
259
+ code: "TRANSACTION_MISMATCH",
260
+ operation: "shillbot.validatePreparedEvmCall",
261
+ message: `Function selector ${actualSelector} does not match expected ${expectedSelector} for ${expected.action}`,
262
+ });
263
+ }
264
+ let valueWei;
265
+ try {
266
+ const rawVal = raw.value_wei ?? raw.value ?? "0";
267
+ valueWei = typeof rawVal === "bigint" ? rawVal : BigInt(String(rawVal));
268
+ }
269
+ catch {
270
+ throw new SwarmClientError({
271
+ code: "TRANSACTION_MISMATCH",
272
+ operation: "shillbot.validatePreparedEvmCall",
273
+ message: "Prepared EVM call value_wei is not a valid integer",
274
+ });
275
+ }
276
+ if (valueWei < 0n) {
277
+ throw new SwarmClientError({
278
+ code: "TRANSACTION_MISMATCH",
279
+ operation: "shillbot.validatePreparedEvmCall",
280
+ message: "Prepared EVM call value_wei cannot be negative",
281
+ });
282
+ }
283
+ if (expected.action !== "create" && valueWei !== 0n) {
284
+ throw new SwarmClientError({
285
+ code: "TRANSACTION_MISMATCH",
286
+ operation: "shillbot.validatePreparedEvmCall",
287
+ message: `Non-create Shillbot EVM action (${expected.action}) must have 0 value_wei, got ${valueWei}`,
288
+ });
289
+ }
290
+ const maxAllowed = expected.action === "create" ? (expected.maxValueWei ?? 0n) : 0n;
291
+ if (valueWei > maxAllowed) {
292
+ throw new SwarmClientError({
293
+ code: "TRANSACTION_MISMATCH",
294
+ operation: "shillbot.validatePreparedEvmCall",
295
+ message: `Prepared EVM call value_wei ${valueWei} exceeds maximum allowed ${maxAllowed}`,
296
+ });
297
+ }
298
+ return {
299
+ to: canonicalContract,
300
+ data: raw.data,
301
+ value: valueWei,
302
+ chain: resolvedChain,
303
+ };
304
+ }
305
+ /**
306
+ * Estimate the maximum Solana network fee (base signature fees + ComputeBudget
307
+ * priority fee) charged to `wallet` for an inspected transaction. Returns `0n`
308
+ * when a third-party sponsor is the `fee_payer`.
309
+ */
310
+ export function estimateSolanaNetworkFeeLamports(inspected, wallet) {
311
+ if (inspected.fee_payer !== wallet)
312
+ return 0n;
313
+ const computeBudgetId = ComputeBudgetProgram.programId.toBase58();
314
+ let computeUnitLimit;
315
+ let microLamportsPerCu = 0n;
316
+ let nonComputeBudgetIxCount = 0;
317
+ for (const ix of inspected.instructions) {
318
+ if (ix.program_id !== computeBudgetId) {
319
+ nonComputeBudgetIxCount += 1;
320
+ continue;
321
+ }
322
+ const data = Buffer.from(ix.data_base64, "base64");
323
+ if (data.length === 0)
324
+ continue;
325
+ const tag = data[0];
326
+ if (tag === 2 && data.length >= 5) {
327
+ computeUnitLimit = BigInt(data.readUInt32LE(1));
328
+ }
329
+ else if (tag === 3 && data.length >= 9) {
330
+ const view = new DataView(data.buffer, data.byteOffset + 1, 8);
331
+ microLamportsPerCu = view.getBigUint64(0, true);
332
+ }
333
+ else if (tag === 1 && data.length >= 9) {
334
+ // Legacy RequestUnitsDeprecated: u32 units + u32 additionalFeeLamports
335
+ const additionalFee = BigInt(data.readUInt32LE(5));
336
+ return BigInt(inspected.signers.length) * 5000n + additionalFee;
337
+ }
338
+ }
339
+ const effectiveUnits = computeUnitLimit ?? BigInt(Math.max(1, nonComputeBudgetIxCount)) * 200000n;
340
+ const priorityFeeLamports = (effectiveUnits * microLamportsPerCu + 999999n) / 1000000n;
341
+ const baseSignatureFeeLamports = BigInt(Math.max(1, inspected.signers.length)) * 5000n;
342
+ return baseSignatureFeeLamports + priorityFeeLamports;
343
+ }
35
344
  export function permittedPreparedProgramIds(action, network) {
36
345
  return action === "verify"
37
346
  ? [SWITCHBOARD_PROGRAM_IDS[network], Secp256k1Program.programId.toBase58()]
@@ -55,34 +364,74 @@ function matchesDiscriminator(dataBase64, action) {
55
364
  */
56
365
  export function validatePreparedTransaction(encoded, expected) {
57
366
  if (expected.network !== "mainnet" && expected.network !== "devnet") {
58
- throw new SwarmClientError({ code: "INVALID_ARGUMENT", operation: "shillbot.validatePreparedTransaction", message: "Unsupported network" });
367
+ throw new SwarmClientError({
368
+ code: "INVALID_ARGUMENT",
369
+ operation: "shillbot.validatePreparedTransaction",
370
+ message: "Unsupported network",
371
+ });
59
372
  }
60
373
  const inspected = inspectTransaction(encoded);
61
374
  if (!inspected.signers.includes(expected.wallet)) {
62
- throw new SwarmClientError({ code: "TRANSACTION_MISMATCH", operation: "shillbot.validatePreparedTransaction", message: "Wallet is not a required signer" });
375
+ throw new SwarmClientError({
376
+ code: "TRANSACTION_MISMATCH",
377
+ operation: "shillbot.validatePreparedTransaction",
378
+ message: "Wallet is not a required signer",
379
+ });
63
380
  }
64
381
  if (expected.feePayer && inspected.fee_payer !== expected.feePayer) {
65
- throw new SwarmClientError({ code: "TRANSACTION_MISMATCH", operation: "shillbot.validatePreparedTransaction", message: "Fee payer differs from expectation" });
382
+ throw new SwarmClientError({
383
+ code: "TRANSACTION_MISMATCH",
384
+ operation: "shillbot.validatePreparedTransaction",
385
+ message: "Fee payer differs from expectation",
386
+ });
66
387
  }
67
388
  const shillbotId = SHILLBOT_PROGRAM_ID.toBase58();
68
389
  const shillbotIxs = inspected.instructions.filter((instruction) => instruction.program_id === shillbotId);
69
390
  const lifecycle = shillbotIxs.filter((instruction) => matchesDiscriminator(instruction.data_base64, expected.action));
70
391
  const companions = shillbotIxs.filter((instruction) => instruction !== lifecycle[0]);
392
+ const claimDisc = shillbotInstructionDiscriminator("claim_task");
71
393
  const payoutDisc = shillbotInstructionDiscriminator("set_payout_to");
394
+ const hasDisc = (ix, disc) => Buffer.from(ix.data_base64, "base64").subarray(0, 8).equals(disc);
395
+ const ixPos = (ix) => inspected.instructions.indexOf(ix);
396
+ const validClaimCompanion = (ix) => hasDisc(ix, claimDisc) &&
397
+ ix.accounts.length >= 4 &&
398
+ (!expected.taskPda || ix.accounts[0] === expected.taskPda) &&
399
+ ix.accounts[0] === lifecycle[0]?.accounts[0] &&
400
+ ix.accounts[3] === expected.wallet;
401
+ const validPayoutCompanion = (ix) => hasDisc(ix, payoutDisc) &&
402
+ ix.accounts.length === 2 &&
403
+ (!expected.taskPda || ix.accounts[0] === expected.taskPda) &&
404
+ ix.accounts[0] === lifecycle[0]?.accounts[0] &&
405
+ ix.accounts[1] === expected.wallet;
72
406
  const validCompanions = companions.length === 0 ||
73
407
  (expected.action === "claim" &&
74
408
  companions.length === 1 &&
75
- Buffer.from(companions[0].data_base64, "base64").subarray(0, 8).equals(payoutDisc) &&
76
- inspected.instructions.indexOf(companions[0]) > inspected.instructions.indexOf(lifecycle[0]) &&
77
- companions[0].accounts.length === 2 &&
78
- (!expected.taskPda || companions[0].accounts[0] === expected.taskPda) &&
79
- companions[0].accounts[1] === expected.wallet);
409
+ validPayoutCompanion(companions[0]) &&
410
+ ixPos(companions[0]) > ixPos(lifecycle[0])) ||
411
+ (expected.action === "submit" &&
412
+ companions.length === 1 &&
413
+ validClaimCompanion(companions[0]) &&
414
+ ixPos(lifecycle[0]) === ixPos(companions[0]) + 1) ||
415
+ (expected.action === "submit" &&
416
+ companions.length === 2 &&
417
+ validClaimCompanion(companions[0]) &&
418
+ validPayoutCompanion(companions[1]) &&
419
+ ixPos(companions[1]) === ixPos(companions[0]) + 1 &&
420
+ ixPos(lifecycle[0]) === ixPos(companions[1]) + 1);
80
421
  if (lifecycle.length !== 1 || !validCompanions) {
81
- throw new SwarmClientError({ code: "TRANSACTION_MISMATCH", operation: "shillbot.validatePreparedTransaction", message: "Expected exactly one matching Shillbot lifecycle instruction" });
422
+ throw new SwarmClientError({
423
+ code: "TRANSACTION_MISMATCH",
424
+ operation: "shillbot.validatePreparedTransaction",
425
+ message: "Expected exactly one matching Shillbot lifecycle instruction",
426
+ });
82
427
  }
83
428
  const taskAccountIndex = expected.action === "create" ? 1 : 0;
84
429
  if (expected.taskPda && lifecycle[0].accounts[taskAccountIndex] !== expected.taskPda) {
85
- throw new SwarmClientError({ code: "TRANSACTION_MISMATCH", operation: "shillbot.validatePreparedTransaction", message: "Task PDA differs from expectation" });
430
+ throw new SwarmClientError({
431
+ code: "TRANSACTION_MISMATCH",
432
+ operation: "shillbot.validatePreparedTransaction",
433
+ message: "Task PDA differs from expectation",
434
+ });
86
435
  }
87
436
  const alwaysAllowed = new Set([
88
437
  shillbotId,
@@ -92,20 +441,103 @@ export function validatePreparedTransaction(encoded, expected) {
92
441
  ]);
93
442
  const unrelated = inspected.instructions.find((instruction) => !alwaysAllowed.has(instruction.program_id));
94
443
  if (unrelated) {
95
- throw new SwarmClientError({ code: "TRANSACTION_MISMATCH", operation: "shillbot.validatePreparedTransaction", message: `Unexpected program ${unrelated.program_id}` });
444
+ throw new SwarmClientError({
445
+ code: "TRANSACTION_MISMATCH",
446
+ operation: "shillbot.validatePreparedTransaction",
447
+ message: `Unexpected program ${unrelated.program_id}`,
448
+ });
96
449
  }
97
450
  if (expected.action === "create" && expected.escrowLamports !== undefined) {
98
451
  const data = Buffer.from(lifecycle[0].data_base64, "base64");
99
- if (data.length < 24)
100
- throw new SwarmClientError({ code: "TRANSACTION_MISMATCH", operation: "shillbot.validatePreparedTransaction", message: "Create instruction is truncated" });
452
+ if (data.length < 24) {
453
+ throw new SwarmClientError({
454
+ code: "TRANSACTION_MISMATCH",
455
+ operation: "shillbot.validatePreparedTransaction",
456
+ message: "Create instruction is truncated",
457
+ });
458
+ }
101
459
  const view = new DataView(data.buffer, data.byteOffset + 16, 8);
102
460
  const amount = view.getBigUint64(0, true);
103
461
  if (amount !== expected.escrowLamports) {
104
- throw new SwarmClientError({ code: "TRANSACTION_MISMATCH", operation: "shillbot.validatePreparedTransaction", message: `Escrow amount ${amount} differs from expected ${expected.escrowLamports}` });
462
+ throw new SwarmClientError({
463
+ code: "TRANSACTION_MISMATCH",
464
+ operation: "shillbot.validatePreparedTransaction",
465
+ message: `Escrow amount ${amount} differs from expected ${expected.escrowLamports}`,
466
+ });
105
467
  }
106
468
  }
107
469
  return inspected;
108
470
  }
471
+ /**
472
+ * Format the canonical EIP-191 message signed by an agent's EVM referral wallet
473
+ * to bind cross-chain EVM conversions to their Solana settlement pubkey (`M2a`).
474
+ */
475
+ export function formatOnChainActionAttributionMessage(targetChainId, agentSolanaPubkey) {
476
+ const caip2 = targetChainId.trim();
477
+ const agent = agentSolanaPubkey.trim();
478
+ if (!caip2.includes(":") || !agent) {
479
+ throw new SwarmClientError({
480
+ code: "INVALID_ARGUMENT",
481
+ operation: "shillbot.formatOnChainActionAttributionMessage",
482
+ message: "targetChainId (CAIP-2) and agentSolanaPubkey are required",
483
+ });
484
+ }
485
+ return `swarm-attr-v1:${caip2}:${agent}`;
486
+ }
487
+ /**
488
+ * Build a canonical `content_id` proof reference for `PlatformType::OnChainAction = 11`:
489
+ * `<caip2>:<tx_id>:<index>[:sig:<base64url_nopad_65B>]`.
490
+ */
491
+ export function buildOnChainActionProofRef(params) {
492
+ const caip2 = params.targetChainId.trim();
493
+ const txId = params.txId.trim();
494
+ if (!caip2.includes(":") || !txId) {
495
+ throw new SwarmClientError({
496
+ code: "INVALID_ARGUMENT",
497
+ operation: "shillbot.buildOnChainActionProofRef",
498
+ message: "targetChainId and txId are required",
499
+ });
500
+ }
501
+ if (!Number.isInteger(params.index) || params.index < 0) {
502
+ throw new SwarmClientError({
503
+ code: "INVALID_ARGUMENT",
504
+ operation: "shillbot.buildOnChainActionProofRef",
505
+ message: "index must be a non-negative integer",
506
+ });
507
+ }
508
+ const normalizedTxId = caip2.startsWith("eip155:") ? txId.toLowerCase() : txId;
509
+ if (params.attributionSignature === undefined) {
510
+ return `${caip2}:${normalizedTxId}:${params.index}`;
511
+ }
512
+ let sigBytes;
513
+ if (typeof params.attributionSignature === "string") {
514
+ const hex = params.attributionSignature.trim().replace(/^0x/i, "");
515
+ if (!/^[0-9a-fA-F]{130}$/.test(hex)) {
516
+ throw new SwarmClientError({
517
+ code: "INVALID_ARGUMENT",
518
+ operation: "shillbot.buildOnChainActionProofRef",
519
+ message: "attributionSignature hex must be 65 bytes (130 hex chars)",
520
+ });
521
+ }
522
+ sigBytes = Buffer.from(hex, "hex");
523
+ }
524
+ else {
525
+ sigBytes = Buffer.from(params.attributionSignature);
526
+ }
527
+ if (sigBytes.length !== 65) {
528
+ throw new SwarmClientError({
529
+ code: "INVALID_ARGUMENT",
530
+ operation: "shillbot.buildOnChainActionProofRef",
531
+ message: `attributionSignature must be 65 bytes, got ${sigBytes.length}`,
532
+ });
533
+ }
534
+ const b64url = sigBytes
535
+ .toString("base64")
536
+ .replace(/\+/g, "-")
537
+ .replace(/\//g, "_")
538
+ .replace(/=+$/g, "");
539
+ return `${caip2}:${normalizedTxId}:${params.index}:sig:${b64url}`;
540
+ }
109
541
  export async function signBroadcastPreparedTransaction(input) {
110
542
  validatePreparedTransaction(input.transaction, input.expected);
111
543
  const timeoutMs = input.timeoutMs ?? 60_000;
@@ -114,7 +546,12 @@ export async function signBroadcastPreparedTransaction(input) {
114
546
  return await Promise.race([
115
547
  signAndBroadcast(input.connection, input.transaction, input.sign, input.confirmation),
116
548
  new Promise((_, reject) => {
117
- timeout = (input.setTimeout ?? globalThis.setTimeout)(() => reject(new SwarmClientError({ code: "TIMEOUT", operation: "shillbot.signBroadcastPreparedTransaction", message: `Transaction did not confirm within ${timeoutMs}ms`, retryable: true })), timeoutMs);
549
+ timeout = (input.setTimeout ?? globalThis.setTimeout)(() => reject(new SwarmClientError({
550
+ code: "TIMEOUT",
551
+ operation: "shillbot.signBroadcastPreparedTransaction",
552
+ message: `Transaction did not confirm within ${timeoutMs}ms`,
553
+ retryable: true,
554
+ })), timeoutMs);
118
555
  }),
119
556
  ]);
120
557
  }
@@ -0,0 +1,25 @@
1
+ import { type EvmSwarmSigner } from "./types.js";
2
+ export interface EvmPrivateKeyOptions {
3
+ chainId?: number;
4
+ rpcUrl?: string;
5
+ }
6
+ export interface EvmWalletClientLike {
7
+ account?: {
8
+ address: `0x${string}`;
9
+ } | `0x${string}`;
10
+ chain?: {
11
+ id: number;
12
+ };
13
+ signMessage: (args: any) => Promise<`0x${string}`>;
14
+ sendTransaction?: (args: any) => Promise<`0x${string}`>;
15
+ }
16
+ /**
17
+ * Create a browser-clean `EvmSwarmSigner` from a `0x`-prefixed 32-byte hex private key.
18
+ * Derives the EIP-55 address and EIP-191 `personal_sign` signatures without requiring
19
+ * optional peer `viem` at module load, and uses `viem` dynamically if `sendTransaction` is called.
20
+ */
21
+ export declare function fromEvmPrivateKey(privateKeyHex: `0x${string}`, opts?: EvmPrivateKeyOptions): EvmSwarmSigner;
22
+ /**
23
+ * Adapt a `viem` / `wagmi` `WalletClient` into a browser-clean `EvmSwarmSigner`.
24
+ */
25
+ export declare function fromEvmWalletClient(walletClient: EvmWalletClientLike): EvmSwarmSigner;