@swarm-tips/client 0.2.13 → 0.3.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.
- package/README.md +59 -18
- package/SBOM.spdx.json +5 -5
- package/dist/agent.d.ts +176 -0
- package/dist/agent.js +561 -0
- package/dist/auth/token-manager.d.ts +33 -0
- package/dist/auth/token-manager.js +175 -0
- package/dist/cli/keyfile.d.ts +24 -0
- package/dist/cli/keyfile.js +97 -0
- package/dist/cli/swarm.d.ts +14 -0
- package/dist/cli/swarm.js +516 -0
- package/dist/coordination-game/api.d.ts +4 -4
- package/dist/coordination-game/api.js +8 -8
- package/dist/errors.d.ts +1 -1
- package/dist/generated/openapi.d.ts +1963 -0
- package/dist/generated/openapi.js +8 -0
- package/dist/http.d.ts +6 -3
- package/dist/http.js +18 -4
- package/dist/inbox/client.d.ts +16 -1
- package/dist/inbox/client.js +48 -2
- package/dist/inbox/index.d.ts +1 -1
- package/dist/index.d.ts +7 -2
- package/dist/index.js +7 -2
- package/dist/shillbot/api.d.ts +49 -2
- package/dist/shillbot/api.js +377 -33
- package/dist/signer/evm.d.ts +25 -0
- package/dist/signer/evm.js +249 -0
- package/dist/signer/index.d.ts +3 -0
- package/dist/signer/index.js +3 -0
- package/dist/signer/solana.d.ts +24 -0
- package/dist/signer/solana.js +183 -0
- package/dist/signer/types.d.ts +30 -0
- package/dist/signer/types.js +31 -0
- package/dist/swarm/index.d.ts +1 -0
- package/dist/swarm/index.js +9 -2
- package/dist/version.d.ts +1 -0
- package/dist/version.js +1 -0
- package/package.json +5 -3
package/dist/agent.js
ADDED
|
@@ -0,0 +1,561 @@
|
|
|
1
|
+
import { Buffer } from "buffer";
|
|
2
|
+
import { Connection, Transaction, VersionedTransaction } from "@solana/web3.js";
|
|
3
|
+
import { WalletTokenManager } from "./auth/token-manager.js";
|
|
4
|
+
import { CoordinationGameApiClient } from "./coordination-game/api.js";
|
|
5
|
+
import { SwarmClientError } from "./errors.js";
|
|
6
|
+
import { InboxClient, } from "./inbox/client.js";
|
|
7
|
+
import { ShillbotApiClient, estimateSolanaNetworkFeeLamports, signBroadcastPreparedTransaction, validatePreparedEvmCall, validatePreparedTransaction, } from "./shillbot/api.js";
|
|
8
|
+
import { inspectTransaction } from "./shillbot/index.js";
|
|
9
|
+
import { SwarmClient, } from "./swarm/index.js";
|
|
10
|
+
import { shillbotProtocol } from "./vow/decoders/shillbot.js";
|
|
11
|
+
import { verifyV1 } from "./vow/verify.js";
|
|
12
|
+
const DEFAULT_SOLANA_RPC = {
|
|
13
|
+
mainnet: "https://api.mainnet-beta.solana.com",
|
|
14
|
+
devnet: "https://api.devnet.solana.com",
|
|
15
|
+
};
|
|
16
|
+
const ACTIVE_TOURNAMENT_ID = {
|
|
17
|
+
mainnet: 3,
|
|
18
|
+
devnet: 1003,
|
|
19
|
+
};
|
|
20
|
+
function isFeePayerAlreadySigned(encodedTx) {
|
|
21
|
+
const bytes = Buffer.from(encodedTx, "base64");
|
|
22
|
+
try {
|
|
23
|
+
const vtx = VersionedTransaction.deserialize(bytes);
|
|
24
|
+
return vtx.signatures.length > 0 && vtx.signatures[0].some((b) => b !== 0);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
const ltx = Transaction.from(bytes);
|
|
28
|
+
const sig = ltx.signatures[0]?.signature;
|
|
29
|
+
return Boolean(sig && sig.some((b) => b !== 0));
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function parseTimestampMs(value) {
|
|
33
|
+
if (typeof value === "number" && Number.isFinite(value) && value > 0) {
|
|
34
|
+
return value > 1e12 ? value : value * 1_000;
|
|
35
|
+
}
|
|
36
|
+
if (typeof value === "string" && value.trim()) {
|
|
37
|
+
const trimmed = value.trim();
|
|
38
|
+
if (/^\d+$/.test(trimmed)) {
|
|
39
|
+
const n = Number(trimmed);
|
|
40
|
+
return n > 1e12 ? n : n * 1_000;
|
|
41
|
+
}
|
|
42
|
+
const parsed = Date.parse(trimmed);
|
|
43
|
+
if (!Number.isNaN(parsed))
|
|
44
|
+
return parsed;
|
|
45
|
+
}
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
function extractBodyBigInt(body, keys) {
|
|
49
|
+
if (!body || typeof body !== "object")
|
|
50
|
+
return undefined;
|
|
51
|
+
const rec = body;
|
|
52
|
+
for (const key of keys) {
|
|
53
|
+
const val = rec[key];
|
|
54
|
+
if (typeof val === "bigint")
|
|
55
|
+
return val;
|
|
56
|
+
if (typeof val === "number" && Number.isFinite(val))
|
|
57
|
+
return BigInt(Math.trunc(val));
|
|
58
|
+
if (typeof val === "string" && /^\d+$/.test(val.trim()))
|
|
59
|
+
return BigInt(val.trim());
|
|
60
|
+
}
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
function extractCreateEscrowLamports(encodedTx) {
|
|
64
|
+
try {
|
|
65
|
+
const inspected = inspectTransaction(encodedTx);
|
|
66
|
+
for (const ix of inspected.instructions) {
|
|
67
|
+
const data = Buffer.from(ix.data_base64, "base64");
|
|
68
|
+
if (data.length >= 24) {
|
|
69
|
+
const view = new DataView(data.buffer, data.byteOffset + 16, 8);
|
|
70
|
+
return view.getBigUint64(0, true);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
// Validated structurally right after via validatePreparedTransaction.
|
|
76
|
+
}
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Unified non-custodial client for Swarm Tips, Shillbot, Inbox/Topics, and Coordination Game.
|
|
81
|
+
*/
|
|
82
|
+
export class SwarmAgent {
|
|
83
|
+
network;
|
|
84
|
+
rpcUrl;
|
|
85
|
+
shillbotUrl;
|
|
86
|
+
gameUrl;
|
|
87
|
+
mcpUrl;
|
|
88
|
+
maxEscrowSpendLamports;
|
|
89
|
+
maxEscrowSpendWei;
|
|
90
|
+
maxNetworkFeeLamports;
|
|
91
|
+
signer;
|
|
92
|
+
fetchImpl;
|
|
93
|
+
tokenManager;
|
|
94
|
+
shillbotClient;
|
|
95
|
+
swarmClient;
|
|
96
|
+
inboxClient;
|
|
97
|
+
gameClient;
|
|
98
|
+
auth;
|
|
99
|
+
discovery;
|
|
100
|
+
tasks;
|
|
101
|
+
campaigns;
|
|
102
|
+
inbox;
|
|
103
|
+
topics;
|
|
104
|
+
games;
|
|
105
|
+
constructor(options = {}) {
|
|
106
|
+
this.network = options.network ?? "mainnet";
|
|
107
|
+
this.rpcUrl = (options.rpcUrl ?? DEFAULT_SOLANA_RPC[this.network]).replace(/\/$/, "");
|
|
108
|
+
this.shillbotUrl = (options.shillbotUrl ?? "https://api.shillbot.org").replace(/\/$/, "");
|
|
109
|
+
this.gameUrl = (options.gameUrl ?? "https://api.coordination.game").replace(/\/$/, "");
|
|
110
|
+
this.mcpUrl = (options.mcpUrl ?? "https://mcp.swarm.tips").replace(/\/$/, "");
|
|
111
|
+
this.maxEscrowSpendLamports = options.maxEscrowSpendLamports ?? 0n;
|
|
112
|
+
this.maxEscrowSpendWei = options.maxEscrowSpendWei ?? 0n;
|
|
113
|
+
this.maxNetworkFeeLamports = options.maxNetworkFeeLamports ?? 100000n;
|
|
114
|
+
this.signer = options.signer;
|
|
115
|
+
const rawFetch = options.fetch ?? globalThis.fetch;
|
|
116
|
+
if (!rawFetch) {
|
|
117
|
+
throw new SwarmClientError({
|
|
118
|
+
code: "INVALID_ARGUMENT",
|
|
119
|
+
operation: "agent.constructor",
|
|
120
|
+
message: "A fetch implementation is required",
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
this.fetchImpl = options.fetch
|
|
124
|
+
? (input, init) => options.fetch(input, init)
|
|
125
|
+
: rawFetch.bind(globalThis);
|
|
126
|
+
this.tokenManager = new WalletTokenManager({
|
|
127
|
+
signer: options.signer,
|
|
128
|
+
token: options.token,
|
|
129
|
+
gameUrl: this.gameUrl,
|
|
130
|
+
fetch: this.fetchImpl,
|
|
131
|
+
});
|
|
132
|
+
const getToken = () => this.tokenManager.getToken();
|
|
133
|
+
const onUnauthorized = () => this.tokenManager.invalidate();
|
|
134
|
+
this.shillbotClient = new ShillbotApiClient({
|
|
135
|
+
baseUrl: this.shillbotUrl,
|
|
136
|
+
fetch: this.fetchImpl,
|
|
137
|
+
network: this.network,
|
|
138
|
+
getToken,
|
|
139
|
+
onUnauthorized,
|
|
140
|
+
});
|
|
141
|
+
this.swarmClient = new SwarmClient({
|
|
142
|
+
baseUrl: this.mcpUrl,
|
|
143
|
+
fetch: this.fetchImpl,
|
|
144
|
+
});
|
|
145
|
+
this.inboxClient = new InboxClient({
|
|
146
|
+
baseUrl: this.mcpUrl,
|
|
147
|
+
storage: null,
|
|
148
|
+
fetchFn: this.fetchImpl,
|
|
149
|
+
getToken,
|
|
150
|
+
onUnauthorized,
|
|
151
|
+
});
|
|
152
|
+
this.gameClient = new CoordinationGameApiClient({
|
|
153
|
+
baseUrl: this.gameUrl,
|
|
154
|
+
fetch: this.fetchImpl,
|
|
155
|
+
network: this.network,
|
|
156
|
+
getToken,
|
|
157
|
+
onUnauthorized,
|
|
158
|
+
});
|
|
159
|
+
const self = this;
|
|
160
|
+
this.auth = {
|
|
161
|
+
getToken: () => self.tokenManager.getToken(),
|
|
162
|
+
authenticate: () => self.tokenManager.authenticate(),
|
|
163
|
+
get walletAddress() {
|
|
164
|
+
return self.tokenManager.walletAddress;
|
|
165
|
+
},
|
|
166
|
+
};
|
|
167
|
+
this.discovery = {
|
|
168
|
+
async listings(opts) {
|
|
169
|
+
let items = await self.swarmClient.listings();
|
|
170
|
+
if (opts?.category) {
|
|
171
|
+
items = items.filter((item) => item.category === opts.category);
|
|
172
|
+
}
|
|
173
|
+
if (opts?.chain) {
|
|
174
|
+
items = items.filter((item) => item.reward_chain === opts.chain);
|
|
175
|
+
}
|
|
176
|
+
if (opts?.limit !== undefined) {
|
|
177
|
+
items = items.slice(0, opts.limit);
|
|
178
|
+
}
|
|
179
|
+
return items;
|
|
180
|
+
},
|
|
181
|
+
searchMcp: (query, opts) => self.swarmClient.search(query, opts?.limit ?? 30),
|
|
182
|
+
earningCandidates: (opts) => self.swarmClient.earningCandidates(opts?.limit),
|
|
183
|
+
reputation: (wallet, net) => self.swarmClient.reputation(wallet, net ?? self.network),
|
|
184
|
+
leaderboard: (limit) => self.swarmClient.leaderboard(limit),
|
|
185
|
+
};
|
|
186
|
+
this.tasks = {
|
|
187
|
+
listAvailable: (limit = 50) => self.shillbotClient.listTasks(limit),
|
|
188
|
+
get: (id) => self.shillbotClient.getTask(id),
|
|
189
|
+
async mine() {
|
|
190
|
+
const res = await self.shillbotClient.listAgentTasks();
|
|
191
|
+
return Array.isArray(res) ? res : (res.tasks ?? []);
|
|
192
|
+
},
|
|
193
|
+
earnings: () => self.shillbotClient.earnings(),
|
|
194
|
+
onboard: () => self.shillbotClient.onboard(),
|
|
195
|
+
claim: (id, sponsor = "auto") => self.shillbotClient.claimTask(id, sponsor),
|
|
196
|
+
claimAndExecute: (id, opts) => self.executeClaimOrSubmit(id, "claim", undefined, opts),
|
|
197
|
+
submit: (id, body) => self.shillbotClient.submitTask(id, body),
|
|
198
|
+
submitAndExecute: (id, contentId, opts) => self.executeClaimOrSubmit(id, "submit", contentId, opts),
|
|
199
|
+
buildVerify: (id) => self.shillbotClient.buildVerify(id, {
|
|
200
|
+
payer: self.auth.walletAddress,
|
|
201
|
+
mcpBaseUrl: self.mcpUrl,
|
|
202
|
+
network: self.network,
|
|
203
|
+
}),
|
|
204
|
+
async verifyAndExecute(id, opts) {
|
|
205
|
+
const prepared = await self.tasks.buildVerify(id);
|
|
206
|
+
return self.executePreparedAction(id, "verify", prepared, {
|
|
207
|
+
connection: opts?.connection,
|
|
208
|
+
});
|
|
209
|
+
},
|
|
210
|
+
buildFinalize: (id) => self.shillbotClient.buildFinalize(id),
|
|
211
|
+
async finalizeAndExecute(id, opts) {
|
|
212
|
+
const prepared = await self.tasks.buildFinalize(id);
|
|
213
|
+
return self.executePreparedAction(id, "finalize", prepared, {
|
|
214
|
+
connection: opts?.connection,
|
|
215
|
+
});
|
|
216
|
+
},
|
|
217
|
+
nextAction: (task) => SwarmAgent.adviseNextAction(task),
|
|
218
|
+
async verifyVow(urlOrJson, opts) {
|
|
219
|
+
let attestation = urlOrJson;
|
|
220
|
+
if (typeof urlOrJson === "string") {
|
|
221
|
+
const trimmed = urlOrJson.trim();
|
|
222
|
+
if (/^https?:\/\//i.test(trimmed)) {
|
|
223
|
+
const resp = await self.fetchImpl(trimmed, { method: "GET" });
|
|
224
|
+
if (!resp.ok) {
|
|
225
|
+
throw new SwarmClientError({
|
|
226
|
+
code: "HTTP_ERROR",
|
|
227
|
+
operation: "tasks.verifyVow",
|
|
228
|
+
message: `Failed to fetch VOW attestation: HTTP ${resp.status}`,
|
|
229
|
+
status: resp.status,
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
attestation = await resp.json();
|
|
233
|
+
}
|
|
234
|
+
else {
|
|
235
|
+
try {
|
|
236
|
+
attestation = JSON.parse(trimmed);
|
|
237
|
+
}
|
|
238
|
+
catch (cause) {
|
|
239
|
+
throw new SwarmClientError({
|
|
240
|
+
code: "INVALID_ARGUMENT",
|
|
241
|
+
operation: "tasks.verifyVow",
|
|
242
|
+
message: "Expected VOW URL, JSON string, or object",
|
|
243
|
+
cause,
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
const net = attestation &&
|
|
249
|
+
typeof attestation === "object" &&
|
|
250
|
+
attestation.network === "devnet"
|
|
251
|
+
? "devnet"
|
|
252
|
+
: self.network;
|
|
253
|
+
const conn = opts?.connection ??
|
|
254
|
+
new Connection(opts?.rpcUrl ?? DEFAULT_SOLANA_RPC[net], "confirmed");
|
|
255
|
+
return verifyV1(attestation, shillbotProtocol, conn);
|
|
256
|
+
},
|
|
257
|
+
};
|
|
258
|
+
this.campaigns = {
|
|
259
|
+
list: () => self.shillbotClient.listCampaigns(),
|
|
260
|
+
get: (id) => self.shillbotClient.campaign(id),
|
|
261
|
+
tasks: (id) => self.shillbotClient.campaignTasks(id),
|
|
262
|
+
metrics: (id) => self.shillbotClient.campaignMetrics(id),
|
|
263
|
+
create: (body) => self.shillbotClient.createCampaign(body),
|
|
264
|
+
fund: (id, body) => self.shillbotClient.fundCampaignTask(id, body),
|
|
265
|
+
async fundAndExecute(id, body, opts) {
|
|
266
|
+
// Pre-flight C9 spend check on request body if amount is specified directly
|
|
267
|
+
const requestedLamports = extractBodyBigInt(body, [
|
|
268
|
+
"amount_lamports",
|
|
269
|
+
"escrow_lamports",
|
|
270
|
+
"budget_lamports",
|
|
271
|
+
]);
|
|
272
|
+
if (requestedLamports !== undefined && requestedLamports > self.maxEscrowSpendLamports) {
|
|
273
|
+
throw new SwarmClientError({
|
|
274
|
+
code: "SPEND_CAP_EXCEEDED",
|
|
275
|
+
operation: "campaigns.fundAndExecute",
|
|
276
|
+
message: `Requested escrow ${requestedLamports} lamports exceeds maxEscrowSpendLamports (${self.maxEscrowSpendLamports})`,
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
const requestedWei = extractBodyBigInt(body, [
|
|
280
|
+
"amount_wei",
|
|
281
|
+
"escrow_wei",
|
|
282
|
+
"value_wei",
|
|
283
|
+
]);
|
|
284
|
+
if (requestedWei !== undefined && requestedWei > self.maxEscrowSpendWei) {
|
|
285
|
+
throw new SwarmClientError({
|
|
286
|
+
code: "SPEND_CAP_EXCEEDED",
|
|
287
|
+
operation: "campaigns.fundAndExecute",
|
|
288
|
+
message: `Requested escrow ${requestedWei} wei exceeds maxEscrowSpendWei (${self.maxEscrowSpendWei})`,
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
const prepared = await self.shillbotClient.fundCampaignTask(id, body);
|
|
292
|
+
return self.executePreparedAction(prepared.task_id ?? id, "create", prepared, {
|
|
293
|
+
connection: opts?.connection,
|
|
294
|
+
chain: opts?.chain,
|
|
295
|
+
expectedEscrowLamports: requestedLamports,
|
|
296
|
+
});
|
|
297
|
+
},
|
|
298
|
+
approve: (id) => self.shillbotClient.approveTask(id),
|
|
299
|
+
async approveAndExecute(id, opts) {
|
|
300
|
+
const prepared = await self.shillbotClient.approveTask(id);
|
|
301
|
+
return self.executePreparedAction(id, "approve", prepared, {
|
|
302
|
+
connection: opts?.connection,
|
|
303
|
+
chain: opts?.chain,
|
|
304
|
+
});
|
|
305
|
+
},
|
|
306
|
+
};
|
|
307
|
+
this.inbox = {
|
|
308
|
+
list: (opts) => self.inboxClient.listMessages(opts),
|
|
309
|
+
open: (refs) => self.inboxClient.openMessages(refs.map((ref) => (typeof ref === "string" ? { msg_id: ref } : ref))),
|
|
310
|
+
ackIds: (refs) => self.inboxClient.ackMessageIds(refs.map((ref) => (typeof ref === "string" ? ref : ref.msg_id))),
|
|
311
|
+
messages: (threadId, opts) => threadId ? self.inboxClient.getThread(threadId, opts) : self.inboxClient.getMessages(opts),
|
|
312
|
+
send: (toWallet, body, opts) => self.inboxClient.send(toWallet, body, opts?.threadId, opts?.intent, opts?.deliveryKey),
|
|
313
|
+
ack: (upToCursor) => self.inboxClient.ack(upToCursor),
|
|
314
|
+
mute: (threadId, muted = true) => self.inboxClient.muteThread(threadId, muted),
|
|
315
|
+
};
|
|
316
|
+
this.topics = {
|
|
317
|
+
read: (topicId, opts) => self.inboxClient.readTopic(topicId, opts),
|
|
318
|
+
publish: (topicId, body, opts) => self.inboxClient.publishPost(topicId, body, opts),
|
|
319
|
+
report: (topicId, postId, reason) => self.inboxClient.reportPost(topicId, postId, reason),
|
|
320
|
+
};
|
|
321
|
+
this.games = {
|
|
322
|
+
api: this.gameClient,
|
|
323
|
+
availability: (net) => {
|
|
324
|
+
const targetNet = net ?? self.network;
|
|
325
|
+
const suffix = targetNet === "devnet" ? "?network=devnet" : "";
|
|
326
|
+
return self.gameClient.http.get(`/availability${suffix}`);
|
|
327
|
+
},
|
|
328
|
+
leaderboard: (net, opts) => {
|
|
329
|
+
const targetNet = net ?? self.network;
|
|
330
|
+
const tournamentId = opts?.tournamentId ?? ACTIVE_TOURNAMENT_ID[targetNet];
|
|
331
|
+
const limit = opts?.limit ?? 20;
|
|
332
|
+
const suffix = targetNet === "devnet" ? `&network=devnet` : "";
|
|
333
|
+
return self.gameClient.http.get(`/tournaments/${encodeURIComponent(String(tournamentId))}/leaderboard?limit=${encodeURIComponent(String(limit))}${suffix}`);
|
|
334
|
+
},
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
requireSigner() {
|
|
338
|
+
if (!this.signer) {
|
|
339
|
+
throw new SwarmClientError({
|
|
340
|
+
code: "AUTH_REQUIRED",
|
|
341
|
+
operation: "agent.signer",
|
|
342
|
+
message: "A non-custodial SwarmSigner is required to sign and execute transactions",
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
return this.signer;
|
|
346
|
+
}
|
|
347
|
+
async executeClaimOrSubmit(id, action, contentId, opts) {
|
|
348
|
+
const sponsorMode = opts?.sponsor ?? "auto";
|
|
349
|
+
const sponsorQuery = sponsorMode === "none" ? "false" : sponsorMode === "true" ? "true" : "auto";
|
|
350
|
+
let prepared;
|
|
351
|
+
try {
|
|
352
|
+
if (action === "claim") {
|
|
353
|
+
prepared = await this.shillbotClient.claimTask(id, sponsorQuery);
|
|
354
|
+
}
|
|
355
|
+
else {
|
|
356
|
+
const suffix = sponsorMode !== "none" ? `?sponsor=${encodeURIComponent(sponsorQuery)}` : "";
|
|
357
|
+
prepared = await this.shillbotClient.post(`/tasks/${encodeURIComponent(id)}/submit${suffix}`, { content_id: contentId, ...(opts?.extra ?? {}) });
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
catch (err) {
|
|
361
|
+
if (action === "claim" &&
|
|
362
|
+
sponsorMode !== "none" &&
|
|
363
|
+
err instanceof SwarmClientError &&
|
|
364
|
+
err.code === "HTTP_ERROR" &&
|
|
365
|
+
(err.status === 400 || err.status === 403 || err.status === 412) &&
|
|
366
|
+
/onboard|agent_state|bootstrap/i.test(err.message)) {
|
|
367
|
+
await this.shillbotClient.onboard();
|
|
368
|
+
prepared = await this.shillbotClient.claimTask(id, sponsorQuery);
|
|
369
|
+
}
|
|
370
|
+
else {
|
|
371
|
+
throw err;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
// If Solana transaction is a gasless sponsor template (fee_payer !== wallet & unsigned by sponsor),
|
|
375
|
+
// exchange it via POST /tasks/{id}/sponsor before signing locally.
|
|
376
|
+
if (prepared.transaction &&
|
|
377
|
+
sponsorMode !== "none" &&
|
|
378
|
+
this.signer?.chain === "solana") {
|
|
379
|
+
const inspected = validatePreparedTransaction(prepared.transaction, {
|
|
380
|
+
action,
|
|
381
|
+
network: this.network,
|
|
382
|
+
wallet: this.signer.address,
|
|
383
|
+
taskPda: prepared.task_pda,
|
|
384
|
+
});
|
|
385
|
+
if (inspected.fee_payer !== this.signer.address &&
|
|
386
|
+
!isFeePayerAlreadySigned(prepared.transaction)) {
|
|
387
|
+
const sponsored = await this.shillbotClient.sponsorTask(id, {
|
|
388
|
+
action,
|
|
389
|
+
unsigned_transaction: prepared.transaction,
|
|
390
|
+
});
|
|
391
|
+
prepared = {
|
|
392
|
+
...prepared,
|
|
393
|
+
...sponsored,
|
|
394
|
+
task_pda: sponsored.task_pda ?? prepared.task_pda,
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
return this.executePreparedAction(id, action, prepared, {
|
|
399
|
+
connection: opts?.connection,
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
async executePreparedAction(id, action, prepared, opts) {
|
|
403
|
+
const signer = this.requireSigner();
|
|
404
|
+
if (prepared.evm_call && signer.chain === "evm") {
|
|
405
|
+
return this.executeEvmAction(id, action, prepared, signer, opts.chain);
|
|
406
|
+
}
|
|
407
|
+
if (signer.chain !== "solana") {
|
|
408
|
+
throw new SwarmClientError({
|
|
409
|
+
code: "INVALID_ARGUMENT",
|
|
410
|
+
operation: `tasks.${action}AndExecute`,
|
|
411
|
+
message: "Prepared transaction targets Solana, but configured signer is EVM",
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
return this.executeSolanaAction(id, action, prepared, signer, opts);
|
|
415
|
+
}
|
|
416
|
+
async executeEvmAction(id, action, prepared, signer, chain) {
|
|
417
|
+
if (!signer.sendTransaction) {
|
|
418
|
+
throw new SwarmClientError({
|
|
419
|
+
code: "INVALID_ARGUMENT",
|
|
420
|
+
operation: `tasks.${action}AndExecute`,
|
|
421
|
+
message: "Configured EVM signer does not implement sendTransaction",
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
// Check C9 spend cap first so spend cap errors use SPEND_CAP_EXCEEDED
|
|
425
|
+
const rawVal = prepared.evm_call?.value_wei ??
|
|
426
|
+
prepared.evm_call?.value ??
|
|
427
|
+
"0";
|
|
428
|
+
const callValueWei = BigInt(String(rawVal));
|
|
429
|
+
if (action === "create" && callValueWei > this.maxEscrowSpendWei) {
|
|
430
|
+
throw new SwarmClientError({
|
|
431
|
+
code: "SPEND_CAP_EXCEEDED",
|
|
432
|
+
operation: "campaigns.fundAndExecute",
|
|
433
|
+
message: `EVM escrow value ${callValueWei} wei exceeds maxEscrowSpendWei (${this.maxEscrowSpendWei})`,
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
const validated = validatePreparedEvmCall(prepared.evm_call, {
|
|
437
|
+
action,
|
|
438
|
+
chain,
|
|
439
|
+
maxValueWei: action === "create" ? this.maxEscrowSpendWei : 0n,
|
|
440
|
+
});
|
|
441
|
+
const txHash = await signer.sendTransaction({
|
|
442
|
+
to: validated.to,
|
|
443
|
+
data: validated.data,
|
|
444
|
+
value: validated.value,
|
|
445
|
+
});
|
|
446
|
+
const confirmation = await this.shillbotClient.confirmTask(id, {
|
|
447
|
+
tx_signature: txHash,
|
|
448
|
+
action,
|
|
449
|
+
task_pda: prepared.task_pda,
|
|
450
|
+
});
|
|
451
|
+
return {
|
|
452
|
+
task_id: id,
|
|
453
|
+
signature: txHash,
|
|
454
|
+
task_pda: prepared.task_pda,
|
|
455
|
+
confirmation,
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
async executeSolanaAction(id, action, prepared, signer, opts) {
|
|
459
|
+
if (!prepared.transaction) {
|
|
460
|
+
throw new SwarmClientError({
|
|
461
|
+
code: "INVALID_RESPONSE",
|
|
462
|
+
operation: `tasks.${action}AndExecute`,
|
|
463
|
+
message: `Server response for ${action} omitted base64 transaction`,
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
if (action === "create") {
|
|
467
|
+
const txEscrow = extractCreateEscrowLamports(prepared.transaction);
|
|
468
|
+
if (txEscrow !== undefined && txEscrow > this.maxEscrowSpendLamports) {
|
|
469
|
+
throw new SwarmClientError({
|
|
470
|
+
code: "SPEND_CAP_EXCEEDED",
|
|
471
|
+
operation: "campaigns.fundAndExecute",
|
|
472
|
+
message: `Prepared create_task escrow ${txEscrow} lamports exceeds maxEscrowSpendLamports (${this.maxEscrowSpendLamports})`,
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
const expected = {
|
|
477
|
+
action,
|
|
478
|
+
network: this.network,
|
|
479
|
+
wallet: signer.address,
|
|
480
|
+
taskPda: prepared.task_pda,
|
|
481
|
+
...(action === "create" && opts.expectedEscrowLamports !== undefined
|
|
482
|
+
? { escrowLamports: opts.expectedEscrowLamports }
|
|
483
|
+
: {}),
|
|
484
|
+
};
|
|
485
|
+
const inspected = validatePreparedTransaction(prepared.transaction, expected);
|
|
486
|
+
// C9 Network Fee Cap check whenever the agent's wallet pays transaction fees
|
|
487
|
+
const estimatedFeeLamports = estimateSolanaNetworkFeeLamports(inspected, signer.address);
|
|
488
|
+
if (estimatedFeeLamports > this.maxNetworkFeeLamports) {
|
|
489
|
+
throw new SwarmClientError({
|
|
490
|
+
code: "SPEND_CAP_EXCEEDED",
|
|
491
|
+
operation: `tasks.${action}AndExecute`,
|
|
492
|
+
message: `Estimated Solana network fee ${estimatedFeeLamports} lamports exceeds maxNetworkFeeLamports (${this.maxNetworkFeeLamports})`,
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
const connection = opts.connection ?? new Connection(this.rpcUrl, "confirmed");
|
|
496
|
+
const signature = await signBroadcastPreparedTransaction({
|
|
497
|
+
connection,
|
|
498
|
+
transaction: prepared.transaction,
|
|
499
|
+
expected,
|
|
500
|
+
sign: (tx) => signer.signTransaction(tx),
|
|
501
|
+
});
|
|
502
|
+
const confirmation = await this.shillbotClient.confirmTask(id, {
|
|
503
|
+
tx_signature: signature,
|
|
504
|
+
action,
|
|
505
|
+
task_pda: prepared.task_pda,
|
|
506
|
+
});
|
|
507
|
+
return {
|
|
508
|
+
task_id: id,
|
|
509
|
+
signature,
|
|
510
|
+
task_pda: prepared.task_pda,
|
|
511
|
+
confirmation,
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
static adviseNextAction(task, nowMs = Date.now()) {
|
|
515
|
+
const rawState = String(task.state ?? task.status ?? "").trim().toLowerCase();
|
|
516
|
+
if (rawState === "open") {
|
|
517
|
+
return { step: "claim" };
|
|
518
|
+
}
|
|
519
|
+
if (rawState === "claimed") {
|
|
520
|
+
return { step: "submit" };
|
|
521
|
+
}
|
|
522
|
+
if (rawState === "submitted" || rawState === "pending_approval" || rawState === "approved") {
|
|
523
|
+
if (rawState === "pending_approval" ||
|
|
524
|
+
(rawState === "submitted" && task.requires_approval === true && !task.approved_at)) {
|
|
525
|
+
return { step: "wait_attestation" };
|
|
526
|
+
}
|
|
527
|
+
const attestationReadyMs = parseTimestampMs(task.attestation_ready_at) ??
|
|
528
|
+
parseTimestampMs(task.verify_not_before) ??
|
|
529
|
+
parseTimestampMs(task.not_before);
|
|
530
|
+
if (attestationReadyMs !== undefined && attestationReadyMs > nowMs) {
|
|
531
|
+
return {
|
|
532
|
+
step: "wait_attestation",
|
|
533
|
+
not_before: new Date(attestationReadyMs).toISOString(),
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
if (task.composite_score === null &&
|
|
537
|
+
task.verification_hash === undefined &&
|
|
538
|
+
attestationReadyMs === undefined &&
|
|
539
|
+
task.awaiting_attestation === true) {
|
|
540
|
+
return { step: "wait_attestation" };
|
|
541
|
+
}
|
|
542
|
+
return { step: "verify" };
|
|
543
|
+
}
|
|
544
|
+
if (rawState === "verified") {
|
|
545
|
+
const challengeDeadlineMs = parseTimestampMs(task.challenge_deadline) ??
|
|
546
|
+
parseTimestampMs(task.challengeDeadline) ??
|
|
547
|
+
parseTimestampMs(task.finalize_not_before);
|
|
548
|
+
if (challengeDeadlineMs !== undefined && challengeDeadlineMs > nowMs) {
|
|
549
|
+
return {
|
|
550
|
+
step: "wait_challenge",
|
|
551
|
+
not_before: new Date(challengeDeadlineMs).toISOString(),
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
return { step: "finalize" };
|
|
555
|
+
}
|
|
556
|
+
return { step: "done" };
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
export function createSwarmAgent(options = {}) {
|
|
560
|
+
return new SwarmAgent(options);
|
|
561
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type FetchLike } from "../http.js";
|
|
2
|
+
import type { SwarmSigner } from "../signer/types.js";
|
|
3
|
+
export type TokenProvider = string | (() => Promise<string | undefined> | string | undefined);
|
|
4
|
+
export interface WalletTokenManagerOptions {
|
|
5
|
+
signer?: SwarmSigner;
|
|
6
|
+
token?: TokenProvider;
|
|
7
|
+
gameUrl?: string;
|
|
8
|
+
fetch?: FetchLike;
|
|
9
|
+
now?: () => number;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Non-custodial JWT manager backed by `game-api` wallet challenges:
|
|
13
|
+
* - Solana: `POST /auth/challenge` + `POST /auth/verify` (Ed25519 detached bs58)
|
|
14
|
+
* - EVM: `POST /auth/evm/challenge` + `POST /auth/evm/verify` (EIP-191 personal_sign)
|
|
15
|
+
*
|
|
16
|
+
* Caches minted tokens until `(exp - 60) * 1000`, deduplicates concurrent refresh
|
|
17
|
+
* calls, and exposes `invalidate()` for single-retry 401 recovery.
|
|
18
|
+
*/
|
|
19
|
+
export declare class WalletTokenManager {
|
|
20
|
+
readonly signer?: SwarmSigner;
|
|
21
|
+
private readonly staticToken?;
|
|
22
|
+
private readonly customGetToken?;
|
|
23
|
+
private readonly http;
|
|
24
|
+
private readonly now;
|
|
25
|
+
private cachedToken;
|
|
26
|
+
private expiresAtMs;
|
|
27
|
+
private inFlight;
|
|
28
|
+
constructor(options?: WalletTokenManagerOptions);
|
|
29
|
+
get walletAddress(): string | undefined;
|
|
30
|
+
invalidate(): void;
|
|
31
|
+
getToken(): Promise<string | undefined>;
|
|
32
|
+
authenticate(): Promise<string>;
|
|
33
|
+
}
|