@cmdoss/agent-pass-plugin 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 (68) hide show
  1. package/README.md +131 -2
  2. package/dist/agentpass.js +199 -0
  3. package/dist/cli.js +37 -0
  4. package/dist/domain.js +103 -0
  5. package/dist/engine.js +260 -0
  6. package/dist/http.js +170 -0
  7. package/dist/mcp.js +259 -0
  8. package/dist/onboarding.js +258 -0
  9. package/dist/public/catalog.js +35 -0
  10. package/dist/public/http.js +89 -0
  11. package/dist/public-server.js +11 -0
  12. package/dist/runtime/config.js +16 -0
  13. package/dist/runtime/installation.js +107 -0
  14. package/dist/runtime/lock.js +38 -0
  15. package/dist/runtime/paths.js +56 -0
  16. package/dist/runtime/setup.js +155 -0
  17. package/dist/sdk-ui.js +48 -0
  18. package/dist/server.js +107 -0
  19. package/dist/shared/constants.js +9 -0
  20. package/dist/store.js +84 -0
  21. package/dist/testnet/adapter.js +275 -0
  22. package/dist/testnet/authorization.js +620 -0
  23. package/dist/testnet/chain/codec.js +68 -0
  24. package/dist/testnet/chain/inspection.js +54 -0
  25. package/dist/testnet/chain/policy.js +78 -0
  26. package/dist/testnet/chain/prepared.js +150 -0
  27. package/dist/testnet/chain/receipt.js +49 -0
  28. package/dist/testnet/chain/sdk.js +34 -0
  29. package/dist/testnet/chain/types.js +1 -0
  30. package/dist/testnet/engine.js +395 -0
  31. package/dist/testnet/http.js +139 -0
  32. package/dist/testnet/model.js +49 -0
  33. package/dist/testnet/policy.js +44 -0
  34. package/dist/testnet/read-model.js +217 -0
  35. package/dist/testnet/repository.js +62 -0
  36. package/dist/testnet/runner.js +306 -0
  37. package/dist/testnet/types.js +1 -0
  38. package/dist/workflows.js +379 -0
  39. package/docs/agent-pass-integration.md +75 -0
  40. package/docs/architecture.md +93 -0
  41. package/docs/npm-release.md +83 -0
  42. package/npm-shrinkwrap.json +5376 -0
  43. package/package.json +72 -4
  44. package/public/assets/agent-pass-plugin-client.js +16 -0
  45. package/public/assets/agent-pass-plugin-sdk.js +1 -0
  46. package/public/assets/sui-payment-rails.avif +0 -0
  47. package/public/assets/sui-payments-hero.json +1 -0
  48. package/public/fonts/TWKEverett-Medium.woff2 +0 -0
  49. package/public/fonts/TWKEverett-Regular.woff2 +0 -0
  50. package/public/fonts/TWKEverettMono-Medium.woff2 +0 -0
  51. package/public/fonts/TWKEverettMono-Regular.woff2 +0 -0
  52. package/public/index.html +81 -0
  53. package/public/styles/base.css +117 -0
  54. package/public/styles/catalog.css +279 -0
  55. package/public/styles/controls.css +118 -0
  56. package/public/styles/dialog.css +257 -0
  57. package/public/styles/home.css +82 -0
  58. package/public/styles/layout.css +45 -0
  59. package/public/styles/plans.css +271 -0
  60. package/public/styles/responsive.css +643 -0
  61. package/public/styles/review.css +150 -0
  62. package/public/styles/sdk-wallet.css +125 -0
  63. package/public/styles/sdk.css +441 -0
  64. package/public/styles/shell.css +348 -0
  65. package/public/styles/tokens.css +75 -0
  66. package/public/styles.css +11 -0
  67. package/scripts/setup.mjs +10 -0
  68. package/skills/agent-pass-plugin-trading/SKILL.md +60 -0
@@ -0,0 +1,395 @@
1
+ import { STRATEGY_VERSION } from "../shared/constants.js";
2
+ import { randomUUID } from "node:crypto";
3
+ import { fingerprint, testnetInput, units, } from "./model.js";
4
+ import { validatePlan } from "./policy.js";
5
+ import { TestnetReadModel } from "./read-model.js";
6
+ import { TestnetRepository } from "./repository.js";
7
+ import { TestnetRunner } from "./runner.js";
8
+ const terminal = new Set(["stopped", "completed", "revoked"]);
9
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
10
+ /** Commands coordinate immutable plans, owner authorization and local controls. */
11
+ export class TestnetEngine {
12
+ store;
13
+ authorization;
14
+ adapter;
15
+ now;
16
+ fault;
17
+ repository;
18
+ readModel;
19
+ runner;
20
+ get heartbeat() {
21
+ return this.runner.heartbeat;
22
+ }
23
+ proposals = new Map();
24
+ refreshes = new Map();
25
+ constructor(store, authorization, adapter, now = Date.now, fault) {
26
+ this.store = store;
27
+ this.authorization = authorization;
28
+ this.adapter = adapter;
29
+ this.now = now;
30
+ this.fault = fault;
31
+ this.repository = new TestnetRepository(store, now);
32
+ this.readModel = new TestnetReadModel(this.repository, adapter, now, () => this.runner?.heartbeat ?? 0);
33
+ this.runner = new TestnetRunner(this.repository, adapter, this.readModel, (id) => this.requestInfo(id), now, fault);
34
+ }
35
+ async capabilities() {
36
+ return {
37
+ ...(await this.authorization.deployment()),
38
+ defaults: { gasSui: "0.02", gasCapSui: "0.05", gasDailySui: "0.01" },
39
+ directions: ["usdc_to_sui", "sui_to_usdc"],
40
+ mode: "testnet",
41
+ };
42
+ }
43
+ async create(raw) {
44
+ const input = testnetInput.parse(raw);
45
+ const deployment = await this.authorization.deployment();
46
+ if (deployment.network !== "testnet")
47
+ throw new Error("Only the bundled testnet deployment is permitted");
48
+ const coinIn = deployment.coins.find((c) => c.symbol === (input.direction === "usdc_to_sui" ? "USDC" : "SUI"));
49
+ const coinOut = deployment.coins.find((c) => c.symbol === (input.direction === "usdc_to_sui" ? "SUI" : "USDC"));
50
+ if (!coinIn || !coinOut)
51
+ throw new Error("Deployment does not support the selected demo pair");
52
+ const pool = deployment.pools.find((p) => p.venue === input.venue &&
53
+ [p.coinA, p.coinB].includes(coinIn.type) &&
54
+ [p.coinA, p.coinB].includes(coinOut.type));
55
+ if (!pool)
56
+ throw new Error("Selected venue has no bundled pool for this pair");
57
+ const amount = units(input.amountIn, coinIn.decimals), budget = units(input.budgetIn, coinIn.decimals), daily = units(input.dailyLimitIn, coinIn.decimals);
58
+ if (BigInt(amount) <= 0n ||
59
+ BigInt(amount) > BigInt(budget) ||
60
+ BigInt(amount) > BigInt(daily))
61
+ throw new Error("Budget and daily cap must each cover one complete positive order");
62
+ if (BigInt(budget) >
63
+ BigInt(units(coinIn.symbol === "USDC" ? "10000" : "100", coinIn.decimals)))
64
+ throw new Error("Testnet plan budget is limited to 10000 demo USDC or 100 test SUI");
65
+ units(input.limitPrice, 6);
66
+ const gas = units(input.gasSui, 9), gasCap = units(input.gasCapSui, 9), gasDaily = units(input.gasDailySui, 9);
67
+ if (BigInt(gas) < 10000000n ||
68
+ BigInt(gas) > 1000000000n ||
69
+ BigInt(gasCap) > 2000000000n ||
70
+ BigInt(gasDaily) > BigInt(gasCap))
71
+ throw new Error("Review a gas stipend between 0.01 and 1 test SUI and gas limits up to 2 test SUI");
72
+ if (this.repository.plans().some((p) => !terminal.has(p.status)))
73
+ throw new Error("Stop the existing testnet plan first (one active plan per local runner)");
74
+ if (this.repository.intents().some((i) => i.state === "submitted"))
75
+ throw new Error("Reconcile the unresolved digest before creating another plan");
76
+ const id = randomUUID(), now = this.now(), reviewHash = fingerprint({
77
+ id,
78
+ input,
79
+ version: STRATEGY_VERSION,
80
+ route: { coinIn, coinOut, poolId: pool.poolId, venue: pool.venue },
81
+ });
82
+ const policy = {
83
+ planId: id,
84
+ planHash: reviewHash,
85
+ name: `Agent Pass Plugin ${id}`,
86
+ expectedOwner: input.expectedOwner,
87
+ direction: input.direction,
88
+ amountIn: amount,
89
+ budgetIn: budget,
90
+ dailyLimitIn: daily,
91
+ limitPrice: input.limitPrice,
92
+ durationDays: input.durationDays,
93
+ gasSui: input.gasSui,
94
+ gasCapSui: input.gasCapSui,
95
+ gasDailySui: input.gasDailySui,
96
+ poolId: pool.poolId,
97
+ venue: pool.venue,
98
+ coinIn,
99
+ coinOut,
100
+ };
101
+ const plan = {
102
+ id,
103
+ input,
104
+ policy,
105
+ reviewHash,
106
+ status: "draft",
107
+ createdAt: new Date(now).toISOString(),
108
+ expiresAt: new Date(now + input.durationDays * 86400000).toISOString(),
109
+ spent: "0",
110
+ output: "0",
111
+ gas: "0",
112
+ nextRunAt: now,
113
+ lastReason: "Review and sign the exact testnet Agent Pass rules before starting",
114
+ epoch: 0,
115
+ history: [],
116
+ };
117
+ this.repository.event(plan, "created", plan.lastReason);
118
+ this.repository.save(plan);
119
+ return this.view(plan);
120
+ }
121
+ async requestAuthorization(planId, requestId) {
122
+ if (!uuid.test(requestId))
123
+ throw new Error("requestId must be a UUID");
124
+ const plan = this.repository.get(planId);
125
+ validatePlan(plan);
126
+ let request = this.repository
127
+ .requests()
128
+ .find((r) => r.requestId === requestId);
129
+ if (request &&
130
+ (request.planId !== planId ||
131
+ request.payloadHash !== plan.reviewHash ||
132
+ request.kind !== "authorization"))
133
+ throw new Error("Retry key was already used for a different request");
134
+ if (request?.authorization)
135
+ return this.requestInfo(request.id);
136
+ if (!request) {
137
+ const canonical = this.repository
138
+ .requests()
139
+ .find((r) => r.planId === planId &&
140
+ r.payloadHash === plan.reviewHash &&
141
+ r.kind === "authorization");
142
+ if (canonical)
143
+ return this.requestAuthorization(planId, canonical.requestId);
144
+ }
145
+ if (plan.status !== "draft")
146
+ throw new Error("Only a draft can request authorization");
147
+ if (!request) {
148
+ const at = this.now();
149
+ request = {
150
+ id: randomUUID(),
151
+ requestId,
152
+ planId,
153
+ reviewHash: plan.reviewHash,
154
+ payloadHash: plan.reviewHash,
155
+ status: "pending",
156
+ kind: "authorization",
157
+ createdAt: new Date(at).toISOString(),
158
+ expiresAt: plan.expiresAt,
159
+ };
160
+ this.repository.saveRequest(request);
161
+ }
162
+ const stable = request;
163
+ let operation = this.proposals.get(stable.id);
164
+ if (!operation) {
165
+ operation = (async () => {
166
+ const authorization = stable.authorization ??
167
+ (await this.authorization.propose(plan.policy, stable.id));
168
+ const fresh = this.repository.get(planId);
169
+ validatePlan(fresh);
170
+ if (fresh.reviewHash !== stable.payloadHash)
171
+ throw new Error("Plan changed during authorization");
172
+ fresh.authorization = authorization;
173
+ stable.authorization = authorization;
174
+ delete stable.error;
175
+ this.store.transaction(() => {
176
+ this.repository.save(fresh);
177
+ this.repository.saveRequest(stable);
178
+ });
179
+ return this.publicRequest(stable);
180
+ })().finally(() => this.proposals.delete(stable.id));
181
+ this.proposals.set(stable.id, operation);
182
+ }
183
+ return await operation;
184
+ }
185
+ publicRequest(request) {
186
+ const plan = this.repository.get(request.planId), a = request.authorization;
187
+ return {
188
+ id: request.id,
189
+ requestId: request.requestId,
190
+ mode: "testnet",
191
+ kind: request.kind,
192
+ planId: request.planId,
193
+ reviewHash: request.reviewHash,
194
+ status: request.status,
195
+ createdAt: request.createdAt,
196
+ expiresAt: request.expiresAt,
197
+ reviewUrl: a?.reviewUrl,
198
+ rules: a?.rules ?? "",
199
+ warnings: a?.warnings ?? [],
200
+ expectedOwner: plan.input.expectedOwner,
201
+ authorizationStatus: a?.status,
202
+ passId: a?.binding?.passId,
203
+ sessionAddress: a?.sessionAddress,
204
+ error: request.error,
205
+ };
206
+ }
207
+ async requestInfo(id) {
208
+ let pending = this.refreshes.get(id);
209
+ if (!pending) {
210
+ pending = this.refreshRequest(id).finally(() => this.refreshes.delete(id));
211
+ this.refreshes.set(id, pending);
212
+ }
213
+ return this.publicRequest(await pending);
214
+ }
215
+ async refreshRequest(id) {
216
+ const request = this.repository.requests().find((r) => r.id === id);
217
+ if (!request)
218
+ throw new Error("Testnet review request not found");
219
+ if (!request.authorization)
220
+ return request;
221
+ const plan = this.repository.get(request.planId);
222
+ validatePlan(plan);
223
+ if (request.payloadHash !== plan.reviewHash)
224
+ throw new Error("The reviewed plan changed");
225
+ const authorization = await this.authorization.inspect(plan.policy, request.authorization);
226
+ const fresh = this.repository.get(plan.id);
227
+ validatePlan(fresh);
228
+ if (fresh.reviewHash !== request.payloadHash)
229
+ throw new Error("Plan changed during authorization inspection");
230
+ fresh.authorization = authorization;
231
+ request.authorization = authorization;
232
+ if (authorization.binding && authorization.status === "active") {
233
+ if (authorization.binding.planHash !== fresh.reviewHash ||
234
+ authorization.binding.owner !== fresh.input.expectedOwner)
235
+ throw new Error("Authorized owner or plan does not match");
236
+ if (fresh.binding &&
237
+ (fresh.binding.passId !== authorization.binding.passId ||
238
+ fresh.binding.sessionId !== authorization.binding.sessionId ||
239
+ fresh.binding.sessionAddress !==
240
+ authorization.binding.sessionAddress ||
241
+ fresh.binding.policyHash !== authorization.binding.policyHash ||
242
+ fresh.binding.deploymentHash !==
243
+ authorization.binding.deploymentHash ||
244
+ fresh.binding.authorizationDigest !==
245
+ authorization.binding.authorizationDigest))
246
+ throw new Error("A plan cannot replace its already-bound Agent Pass; create a new reviewed plan");
247
+ fresh.binding = authorization.binding;
248
+ fresh.approvalHash = fresh.reviewHash;
249
+ fresh.expiresAt = authorization.binding.expiresAt;
250
+ request.status = request.kind === "revocation" ? "pending" : "confirmed";
251
+ if (fresh.status === "draft") {
252
+ fresh.status = "approved";
253
+ this.repository.event(fresh, "approved", "Matching onchain Agent Pass verified. Start remains a separate action");
254
+ }
255
+ }
256
+ else if (["revoked", "closed"].includes(authorization.status)) {
257
+ request.status = request.kind === "revocation" ? "confirmed" : "revoked";
258
+ if (fresh.status !== "revoked") {
259
+ fresh.status = "revoked";
260
+ fresh.epoch++;
261
+ this.repository.event(fresh, "revoked", "Onchain revocation confirmed; no new transactions will be submitted");
262
+ }
263
+ }
264
+ else if (["mismatch", "expired"].includes(authorization.status)) {
265
+ request.status = authorization.status;
266
+ if (!terminal.has(fresh.status)) {
267
+ fresh.status = "blocked";
268
+ fresh.epoch++;
269
+ this.repository.event(fresh, "blocked", `Agent Pass ${authorization.status}; execution disabled`);
270
+ }
271
+ }
272
+ this.store.transaction(() => {
273
+ this.repository.save(fresh);
274
+ this.repository.saveRequest(request);
275
+ });
276
+ return request;
277
+ }
278
+ async control(id, action) {
279
+ let plan = this.repository.get(id);
280
+ validatePlan(plan);
281
+ if (["pause", "stop", "revoke"].includes(action)) {
282
+ if (action === "pause" && plan.status !== "running")
283
+ throw new Error("Only a running plan can be paused");
284
+ if (action === "stop" && terminal.has(plan.status))
285
+ return this.view(plan);
286
+ plan.status =
287
+ action === "pause"
288
+ ? "paused"
289
+ : action === "stop"
290
+ ? "stopped"
291
+ : "revoking";
292
+ plan.epoch++;
293
+ this.repository.event(plan, action === "revoke" ? "revocation_requested" : action, action === "revoke"
294
+ ? "New submissions stopped locally. Owner must sign onchain revocation"
295
+ : "New submissions stopped; holdings remain with the owner");
296
+ this.repository.save(plan);
297
+ if (action === "revoke") {
298
+ if (!plan.binding) {
299
+ plan.status = "stopped";
300
+ this.repository.save(plan);
301
+ return this.view(plan);
302
+ }
303
+ const result = await this.authorization.revoke(plan.binding);
304
+ const fresh = this.repository.get(id);
305
+ fresh.revocationUrl = result.reviewUrl;
306
+ this.repository.save(fresh);
307
+ const existing = this.repository
308
+ .requests()
309
+ .find((r) => r.planId === id &&
310
+ r.kind === "revocation" &&
311
+ r.status === "pending");
312
+ if (!existing)
313
+ this.repository.saveRequest({
314
+ id: randomUUID(),
315
+ requestId: randomUUID(),
316
+ planId: id,
317
+ reviewHash: fresh.reviewHash,
318
+ payloadHash: fresh.reviewHash,
319
+ kind: "revocation",
320
+ status: "pending",
321
+ authorization: fresh.authorization,
322
+ createdAt: new Date(this.now()).toISOString(),
323
+ expiresAt: fresh.expiresAt,
324
+ });
325
+ return { ...this.view(fresh), reviewUrl: result.reviewUrl };
326
+ }
327
+ return this.view(plan);
328
+ }
329
+ if (!["start", "resume"].includes(action))
330
+ throw new Error("Unknown testnet control");
331
+ const allowed = action === "start" ? ["approved"] : ["paused", "blocked"];
332
+ if (!allowed.includes(plan.status) ||
333
+ !plan.binding ||
334
+ plan.approvalHash !== plan.reviewHash)
335
+ throw new Error("A matching active onchain authorization is required");
336
+ if (this.repository.intents().some((i) => i.state === "submitted"))
337
+ throw new Error("Reconcile the unresolved digest before resuming");
338
+ const epoch = plan.epoch, inspection = await this.adapter.inspect(plan.binding, plan.policy);
339
+ plan = this.repository.get(id);
340
+ if (plan.epoch !== epoch || !allowed.includes(plan.status))
341
+ throw new Error("Plan changed while checking permission");
342
+ validatePlan(plan);
343
+ this.readModel.rememberInspection(id, inspection);
344
+ if (!inspection.active || inspection.revoked || inspection.expired)
345
+ throw new Error(inspection.reason || "Agent Pass is not active");
346
+ if (BigInt(inspection.ownerInputBalance) < BigInt(plan.policy.amountIn))
347
+ throw new Error("Insufficient testnet input address balance; fund the owner through the official review page");
348
+ if (BigInt(inspection.agentGasBalance) < 10000000n)
349
+ throw new Error("Agent gas float is below 0.01 test SUI; review funding before starting");
350
+ plan.status = "running";
351
+ plan.nextRunAt =
352
+ action === "start" ? this.now() : Math.max(plan.nextRunAt, this.now());
353
+ this.repository.event(plan, action, "Independent testnet loop enabled; missed opportunities will not replay");
354
+ this.repository.save(plan);
355
+ return this.view(plan);
356
+ }
357
+ async close() {
358
+ for (const plan of this.repository.plans())
359
+ if (plan.status === "running") {
360
+ plan.status = "paused";
361
+ plan.epoch++;
362
+ this.repository.event(plan, "paused", "Local service stopped; explicit resume is required");
363
+ this.repository.save(plan);
364
+ }
365
+ await this.authorization.close();
366
+ await this.adapter.close();
367
+ }
368
+ view(planOrId) {
369
+ return this.readModel.view(planOrId);
370
+ }
371
+ status() {
372
+ return this.readModel.status();
373
+ }
374
+ portfolio() {
375
+ return this.readModel.portfolio();
376
+ }
377
+ account() {
378
+ return this.readModel.account();
379
+ }
380
+ catalog(query = "") {
381
+ return this.readModel.catalog(query);
382
+ }
383
+ strategy(id) {
384
+ return this.readModel.strategy(id);
385
+ }
386
+ transactions(planId) {
387
+ return this.readModel.transactions(planId);
388
+ }
389
+ recover() {
390
+ return this.runner.recover();
391
+ }
392
+ tick() {
393
+ return this.runner.tick();
394
+ }
395
+ }
@@ -0,0 +1,139 @@
1
+ import { z } from "zod";
2
+ import { getIntegrationStatus } from "../agentpass.js";
3
+ export function registerTestnetRoutes(app, engine, onboarding) {
4
+ const id = z.string().uuid();
5
+ const params = (req) => z.object({ id }).parse(req.params).id;
6
+ app.get("/api/status", async () => ({
7
+ ...engine.status(),
8
+ integration: {
9
+ mode: "testnet",
10
+ adapter: "official-agent-pass",
11
+ mainnetEnabled: false,
12
+ authorizationRequired: true,
13
+ },
14
+ onboarding: {
15
+ requiredTool: "onboard",
16
+ completion: "fresh_browser_wallet_connection",
17
+ authorizationGranted: false,
18
+ },
19
+ }));
20
+ app.post("/api/onboarding", async (req) => {
21
+ const body = z
22
+ .object({
23
+ requestId: id,
24
+ retryBrowser: z.boolean().optional(),
25
+ openBrowser: z.boolean().optional(),
26
+ clientName: z.string().trim().min(1).max(100).optional(),
27
+ })
28
+ .strict()
29
+ .parse(req.body);
30
+ return onboarding.begin(body.requestId, body.retryBrowser, body.openBrowser, body.clientName);
31
+ });
32
+ app.get("/api/onboarding/:id", async (req) => onboarding.status(params(req)));
33
+ app.post("/api/onboarding/:id/connection", async (req) => {
34
+ const body = z
35
+ .object({
36
+ browserId: id,
37
+ address: z
38
+ .string()
39
+ .regex(/^0x[0-9a-fA-F]{64}$/)
40
+ .nullable(),
41
+ })
42
+ .strict()
43
+ .parse(req.body);
44
+ const result = onboarding.complete(params(req), body.browserId, body.address?.toLowerCase() ?? null);
45
+ engine.store.write("testnet:ownerHint", onboarding.currentConnection().address);
46
+ return result;
47
+ });
48
+ app.get("/api/testnet/capabilities", async () => engine.capabilities());
49
+ app.get("/api/integration", async () => {
50
+ const sdk = await getIntegrationStatus({ probeNetwork: true });
51
+ return {
52
+ sdk: sdk.sdk,
53
+ node: sdk.node,
54
+ testnet: sdk.testnet,
55
+ mode: "testnet",
56
+ executionAdapter: "official-agent-pass",
57
+ authorizationRequired: true,
58
+ mainnetEnabled: false,
59
+ warnings: sdk.warnings,
60
+ sessionConfigured: engine
61
+ .status()
62
+ .plans.some((p) => p.authorization?.passId),
63
+ nextSteps: [
64
+ "Create a testnet plan with exact owner-selected limits, open its official wallet review and sign personally. Start only after the matching onchain pass is verified.",
65
+ ],
66
+ };
67
+ });
68
+ app.post("/api/plans", async (req) => engine.create(req.body));
69
+ app.get("/api/plans/:id", async (req) => engine.view(params(req)));
70
+ app.post("/api/plans/:id/authorization", async (req) => engine.requestAuthorization(params(req), z.object({ requestId: id }).strict().parse(req.body).requestId));
71
+ app.get("/api/requests/:id", async (req) => engine.requestInfo(params(req)));
72
+ app.post("/api/requests/:id/confirm", async (_req, reply) => reply.code(409).send({
73
+ error: "Testnet authorization is confirmed from verified chain state. Open the official Agent Pass wallet review; local confirmation cannot approve a pass.",
74
+ }));
75
+ app.post("/api/plans/:id/approve", async (_req, reply) => reply.code(410).send({
76
+ error: "Use the official Agent Pass review and wait for verified owner authorization.",
77
+ }));
78
+ app.post("/api/plans/:id/:action", async (req) => {
79
+ const p = z
80
+ .object({
81
+ id,
82
+ action: z.enum(["start", "pause", "resume", "stop", "revoke"]),
83
+ })
84
+ .parse(req.params);
85
+ return engine.control(p.id, p.action);
86
+ });
87
+ app.get("/api/account", async () => {
88
+ const connection = onboarding.currentConnection();
89
+ return {
90
+ ...engine.account(),
91
+ connected: connection.connected,
92
+ account: connection.address ? { id: connection.address } : null,
93
+ onboardingComplete: connection.connected,
94
+ };
95
+ });
96
+ app.post("/api/wallet/identity", async (req) => {
97
+ const { address, browserId } = z
98
+ .object({
99
+ address: z
100
+ .string()
101
+ .regex(/^0x[0-9a-fA-F]{64}$/)
102
+ .nullable(),
103
+ browserId: id.optional(),
104
+ })
105
+ .strict()
106
+ .parse(req.body);
107
+ onboarding.observe(browserId ?? "legacy", address?.toLowerCase() ?? null);
108
+ engine.store.write("testnet:ownerHint", onboarding.currentConnection().address);
109
+ return { mode: "testnet", address, authorizationGranted: false };
110
+ });
111
+ app.post("/api/account/requests", async (_req, reply) => reply.code(409).send({
112
+ error: "Testnet uses the connected owner wallet. Create a bounded plan and request its Agent Pass authorization; no simulated account review is needed.",
113
+ }));
114
+ app.post("/api/funding/requests", async (_req, reply) => {
115
+ const plans = engine.status().plans;
116
+ const reviewUrl = plans.find((p) => p.authorization?.reviewUrl)
117
+ ?.authorization?.reviewUrl;
118
+ return reply.code(409).send({
119
+ error: "Testnet funding must be performed by the owner in the official wallet review. Virtual USDC credits are disabled.",
120
+ reviewUrl,
121
+ account: engine.account(),
122
+ });
123
+ });
124
+ app.post("/api/logout", async () => {
125
+ onboarding.disconnectAll();
126
+ engine.store.write("testnet:ownerHint", null);
127
+ return { mode: "testnet", connected: false, jobsStopped: false };
128
+ });
129
+ app.get("/api/strategies", async (req) => engine.catalog(z.object({ query: z.string().max(100).optional() }).parse(req.query)
130
+ .query));
131
+ app.get("/api/strategies/:id", async (req) => engine.strategy(z
132
+ .enum(["steady-dca", "price-watch"])
133
+ .parse(req.params.id)));
134
+ app.get("/api/portfolio", async () => engine.portfolio());
135
+ app.get("/api/transactions", async (req) => engine.transactions(z.object({ planId: id.optional() }).parse(req.query).planId));
136
+ app.post("/api/paper/market", async (_req, reply) => reply.code(409).send({
137
+ error: "Paper prices cannot modify Testnet execution or valuation.",
138
+ }));
139
+ }
@@ -0,0 +1,49 @@
1
+ import { createHash } from "node:crypto";
2
+ import { z } from "zod";
3
+ const decimal = z
4
+ .string()
5
+ .max(40)
6
+ .regex(/^(0|[1-9]\d*)(\.\d+)?$/)
7
+ .refine((v) => /[1-9]/.test(v), "Amount must be positive");
8
+ export const testnetInput = z
9
+ .object({
10
+ mode: z.literal("testnet"),
11
+ network: z.literal("testnet"),
12
+ expectedOwner: z
13
+ .string()
14
+ .regex(/^0x[0-9a-fA-F]{64}$/)
15
+ .transform((v) => v.toLowerCase()),
16
+ botId: z.enum(["steady-dca", "price-watch"]),
17
+ direction: z.enum(["usdc_to_sui", "sui_to_usdc"]),
18
+ amountIn: decimal,
19
+ budgetIn: decimal,
20
+ dailyLimitIn: decimal,
21
+ limitPrice: decimal,
22
+ intervalSeconds: z.number().int().min(5).max(86400).default(60),
23
+ durationDays: z.number().int().min(1).max(7),
24
+ slippageBps: z.number().int().min(1).max(500).default(50),
25
+ venue: z.enum(["cetus", "deepbook"]).default("cetus"),
26
+ gasSui: decimal.default("0.02"),
27
+ gasCapSui: decimal.default("0.05"),
28
+ gasDailySui: decimal.default("0.01"),
29
+ })
30
+ .strict();
31
+ export function units(value, decimals) {
32
+ if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(value))
33
+ throw new Error("Invalid decimal amount");
34
+ const [whole, fraction = ""] = value.split(".");
35
+ if (fraction.length > decimals)
36
+ throw new Error(`Use at most ${decimals} decimal places`);
37
+ const result = BigInt(whole) * 10n ** BigInt(decimals) +
38
+ BigInt(fraction.padEnd(decimals, "0") || "0");
39
+ if (result > 18446744073709551615n)
40
+ throw new Error("Amount exceeds the chain u64 limit");
41
+ return result.toString();
42
+ }
43
+ export function display(value, decimals) {
44
+ const number = BigInt(value), negative = number < 0n, magnitude = negative ? -number : number;
45
+ const digits = magnitude.toString().padStart(decimals + 1, "0");
46
+ const fraction = decimals ? digits.slice(-decimals).replace(/0+$/, "") : "";
47
+ return `${negative ? "-" : ""}${decimals ? digits.slice(0, -decimals) : digits}${fraction ? `.${fraction}` : ""}`;
48
+ }
49
+ export const fingerprint = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
@@ -0,0 +1,44 @@
1
+ import { STRATEGY_VERSION } from "../shared/constants.js";
2
+ import { fingerprint, units } from "./model.js";
3
+ export function validatePlan(plan) {
4
+ const expected = fingerprint({
5
+ id: plan.id,
6
+ input: plan.input,
7
+ version: STRATEGY_VERSION,
8
+ route: {
9
+ coinIn: plan.policy.coinIn,
10
+ coinOut: plan.policy.coinOut,
11
+ poolId: plan.policy.poolId,
12
+ venue: plan.policy.venue,
13
+ },
14
+ });
15
+ if (expected !== plan.reviewHash || plan.policy.planHash !== expected)
16
+ throw new Error("Plan fingerprint changed; a new authorization is required");
17
+ const p = plan.policy, i = plan.input;
18
+ if (p.planId !== plan.id ||
19
+ p.expectedOwner !== i.expectedOwner ||
20
+ p.direction !== i.direction ||
21
+ p.amountIn !== units(i.amountIn, p.coinIn.decimals) ||
22
+ p.budgetIn !== units(i.budgetIn, p.coinIn.decimals) ||
23
+ p.dailyLimitIn !== units(i.dailyLimitIn, p.coinIn.decimals) ||
24
+ p.limitPrice !== i.limitPrice ||
25
+ p.durationDays !== i.durationDays ||
26
+ p.gasSui !== i.gasSui ||
27
+ p.gasCapSui !== i.gasCapSui ||
28
+ p.gasDailySui !== i.gasDailySui ||
29
+ p.venue !== i.venue)
30
+ throw new Error("Persisted policy differs from the reviewed plan configuration");
31
+ }
32
+ export function guardPlan(plan, now, epoch) {
33
+ validatePlan(plan);
34
+ if (plan.status !== "running" ||
35
+ (epoch !== undefined && plan.epoch !== epoch))
36
+ throw new Error("Plan paused, stopped or changed before submission");
37
+ if (!plan.binding ||
38
+ plan.approvalHash !== plan.reviewHash ||
39
+ plan.binding.planHash !== plan.reviewHash)
40
+ throw new Error("No matching onchain authorization");
41
+ if (Date.parse(plan.expiresAt) <= now ||
42
+ Date.parse(plan.binding.expiresAt) <= now)
43
+ throw new Error("Authorization expired");
44
+ }