@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,217 @@
1
+ import { STRATEGY_VERSION, VALUATION_MAX_AGE_MS } from "../shared/constants.js";
2
+ import { testnetCatalog, testnetStrategy } from "../public/catalog.js";
3
+ import { display, fingerprint } from "./model.js";
4
+ /** Public DTOs and fresh observational balances; never submits transactions. */
5
+ export class TestnetReadModel {
6
+ repository;
7
+ adapter;
8
+ now;
9
+ heartbeat;
10
+ inspections = new Map();
11
+ inspectionTimes = new Map();
12
+ constructor(repository, adapter, now, heartbeat) {
13
+ this.repository = repository;
14
+ this.adapter = adapter;
15
+ this.now = now;
16
+ this.heartbeat = heartbeat;
17
+ }
18
+ publicAuthorization(plan) {
19
+ const a = plan.authorization;
20
+ return a
21
+ ? {
22
+ status: a.status,
23
+ reviewUrl: a.reviewUrl,
24
+ rules: a.rules,
25
+ warnings: a.warnings,
26
+ sessionAddress: a.sessionAddress,
27
+ passId: plan.binding?.passId,
28
+ owner: plan.binding?.owner,
29
+ }
30
+ : null;
31
+ }
32
+ view(planOrId) {
33
+ const plan = typeof planOrId === "string" ? this.repository.get(planOrId) : planOrId;
34
+ const input = plan.input, policy = plan.policy;
35
+ const stored = plan.valuation;
36
+ const fresh = Boolean(stored && this.now() - stored.at <= VALUATION_MAX_AGE_MS);
37
+ const valuation = stored
38
+ ? {
39
+ price: stored.price,
40
+ asOf: new Date(stored.at).toISOString(),
41
+ source: stored.source,
42
+ gasExcluded: true,
43
+ fresh,
44
+ }
45
+ : null;
46
+ const spentIn = display(plan.spent, policy.coinIn.decimals), holdingsOut = display(plan.output, policy.coinOut.decimals);
47
+ const pnl = valuation && input.direction === "usdc_to_sui"
48
+ ? Number(holdingsOut) * Number(valuation.price) - Number(spentIn)
49
+ : null;
50
+ return {
51
+ ...input,
52
+ id: plan.id,
53
+ mode: "testnet",
54
+ botVersion: STRATEGY_VERSION,
55
+ skillHash: fingerprint({
56
+ botId: input.botId,
57
+ version: STRATEGY_VERSION,
58
+ direction: input.direction,
59
+ }),
60
+ status: plan.status,
61
+ reviewHash: plan.reviewHash,
62
+ approvalHash: plan.approvalHash,
63
+ createdAt: plan.createdAt,
64
+ expiresAt: plan.expiresAt,
65
+ lastReason: plan.lastReason,
66
+ nextRunAt: plan.nextRunAt,
67
+ coinIn: policy.coinIn,
68
+ coinOut: policy.coinOut,
69
+ spentIn,
70
+ holdingsIn: display((BigInt(policy.budgetIn) - BigInt(plan.spent)).toString(), policy.coinIn.decimals),
71
+ holdingsOut,
72
+ gasSui: input.gasSui,
73
+ gasSpentSui: plan.gas,
74
+ pnlUsdc: pnl,
75
+ pnlReason: input.direction === "sui_to_usdc"
76
+ ? "Acquisition cost basis for input SUI is unavailable; sale proceeds are not profit"
77
+ : !valuation
78
+ ? "No confirmed venue valuation"
79
+ : fresh
80
+ ? null
81
+ : `Profit uses the last confirmed venue mark from ${valuation.asOf}; it is not a live quote`,
82
+ valuation,
83
+ authorization: this.publicAuthorization(plan),
84
+ revocationUrl: plan.status === "revoking" ? plan.revocationUrl : undefined,
85
+ history: plan.history
86
+ .slice(-200)
87
+ .reverse()
88
+ .map((event) => ({
89
+ ...event,
90
+ mode: "testnet",
91
+ coinIn: policy.coinIn,
92
+ coinOut: policy.coinOut,
93
+ explorerUrl: event.digest
94
+ ? `https://suiscan.xyz/testnet/tx/${encodeURIComponent(event.digest)}`
95
+ : undefined,
96
+ })),
97
+ };
98
+ }
99
+ status() {
100
+ const plans = this.repository.plans();
101
+ const owner = plans[0]?.input.expectedOwner;
102
+ const observedAt = plans[0]
103
+ ? this.inspectionTimes.get(plans[0].id)
104
+ : undefined;
105
+ const inspection = plans[0] &&
106
+ observedAt !== undefined &&
107
+ this.now() - observedAt <= VALUATION_MAX_AGE_MS
108
+ ? this.inspections.get(plans[0].id)
109
+ : undefined;
110
+ const sample = plans.find((p) => p.valuation && this.now() - p.valuation.at < VALUATION_MAX_AGE_MS)?.valuation;
111
+ return {
112
+ mode: "testnet",
113
+ network: "testnet",
114
+ owner: owner ?? null,
115
+ plans: plans.map((p) => this.view(p)),
116
+ catalog: this.catalog(),
117
+ market: {
118
+ price: sample ? Number(sample.price) : null,
119
+ asOf: sample ? new Date(sample.at).toISOString() : null,
120
+ source: sample?.source ?? null,
121
+ },
122
+ wallet: {
123
+ ...this.walletView(inspection, plans[0]),
124
+ asOf: inspection && observedAt !== undefined
125
+ ? new Date(observedAt).toISOString()
126
+ : null,
127
+ source: inspection ? "Fresh onchain address-balance inspection" : null,
128
+ },
129
+ runner: {
130
+ heartbeat: this.heartbeat()
131
+ ? new Date(this.heartbeat()).toISOString()
132
+ : null,
133
+ intervalMs: 1000,
134
+ },
135
+ };
136
+ }
137
+ walletView(inspection, plan) {
138
+ if (!inspection || !plan)
139
+ return { usdc: null, sui: null, gasSui: null };
140
+ const input = Number(display(inspection.ownerInputBalance, plan.policy.coinIn.decimals)), output = Number(display(inspection.ownerOutputBalance, plan.policy.coinOut.decimals));
141
+ return {
142
+ usdc: plan.input.direction === "usdc_to_sui" ? input : output,
143
+ sui: plan.input.direction === "sui_to_usdc" ? input : output,
144
+ gasSui: Number(display(inspection.agentGasBalance, 9)),
145
+ };
146
+ }
147
+ portfolio() {
148
+ const status = this.status(), pnl = status.plans.map((p) => p.pnlUsdc);
149
+ return {
150
+ ...status,
151
+ totalValueUsdc: status.market.price !== null &&
152
+ status.wallet.usdc !== null &&
153
+ status.wallet.sui !== null
154
+ ? status.wallet.usdc + status.wallet.sui * status.market.price
155
+ : null,
156
+ totalPnlUsdc: pnl.length && pnl.every((p) => p !== null)
157
+ ? pnl.reduce((a, b) => a + b, 0)
158
+ : null,
159
+ };
160
+ }
161
+ account() {
162
+ const status = this.status(), hint = this.repository.store.read("testnet:ownerHint", null);
163
+ return {
164
+ mode: "testnet",
165
+ connected: Boolean(hint),
166
+ account: hint ? { id: hint } : null,
167
+ authorizedOwner: status.owner,
168
+ wallet: status.wallet,
169
+ authorizationGranted: false,
170
+ };
171
+ }
172
+ sampleSize = (id) => this.repository
173
+ .plans()
174
+ .filter((plan) => plan.input.botId === id)
175
+ .reduce((count, plan) => count +
176
+ plan.history.filter((event) => event.type === "filled").length, 0);
177
+ catalog(query = "") {
178
+ return testnetCatalog(query, this.sampleSize);
179
+ }
180
+ strategy(id) {
181
+ return testnetStrategy(id, this.sampleSize);
182
+ }
183
+ transactions(planId) {
184
+ return (planId ? [this.repository.get(planId)] : this.repository.plans())
185
+ .flatMap((plan) => this.view(plan)
186
+ .history.filter((e) => [
187
+ "filled",
188
+ "failed",
189
+ "accounting_unverified",
190
+ "blocked",
191
+ "cancelled",
192
+ ].includes(e.type))
193
+ .map((event) => ({
194
+ ...event,
195
+ planId: plan.id,
196
+ botId: plan.input.botId,
197
+ })))
198
+ .sort((a, b) => b.at.localeCompare(a.at));
199
+ }
200
+ rememberInspection(id, inspection) {
201
+ this.inspections.set(id, inspection);
202
+ this.inspectionTimes.set(id, this.now());
203
+ }
204
+ async refreshBalances(planId) {
205
+ const plan = this.repository.get(planId);
206
+ if (!plan.binding)
207
+ return;
208
+ try {
209
+ this.rememberInspection(planId, await this.adapter.inspect(plan.binding, plan.policy));
210
+ }
211
+ catch {
212
+ // A confirmed fill remains confirmed; stale pre-fill balances must not look current.
213
+ this.inspections.delete(planId);
214
+ this.inspectionTimes.delete(planId);
215
+ }
216
+ }
217
+ }
@@ -0,0 +1,62 @@
1
+ import { randomUUID } from "node:crypto";
2
+ /** Durable Testnet records. Existing SQLite keys and transaction boundaries are preserved. */
3
+ export class TestnetRepository {
4
+ store;
5
+ now;
6
+ constructor(store, now) {
7
+ this.store = store;
8
+ this.now = now;
9
+ }
10
+ plans() {
11
+ return this.store.read("testnet:plans", []);
12
+ }
13
+ save(plan) {
14
+ const all = this.plans();
15
+ const index = all.findIndex((p) => p.id === plan.id);
16
+ if (index < 0)
17
+ all.unshift(plan);
18
+ else
19
+ all[index] = plan;
20
+ this.store.write("testnet:plans", all);
21
+ }
22
+ get(id) {
23
+ const plan = this.plans().find((p) => p.id === id);
24
+ if (!plan)
25
+ throw new Error("Testnet plan not found");
26
+ return plan;
27
+ }
28
+ intents() {
29
+ return this.store.read("testnet:intents", []);
30
+ }
31
+ saveIntent(intent) {
32
+ const all = this.intents();
33
+ const index = all.findIndex((i) => i.id === intent.id);
34
+ if (index < 0)
35
+ all.push(intent);
36
+ else
37
+ all[index] = intent;
38
+ this.store.write("testnet:intents", all);
39
+ }
40
+ requests() {
41
+ return this.store.read("testnet:requests", []);
42
+ }
43
+ saveRequest(request) {
44
+ const all = this.requests();
45
+ const index = all.findIndex((r) => r.id === request.id);
46
+ if (index < 0)
47
+ all.push(request);
48
+ else
49
+ all[index] = request;
50
+ this.store.write("testnet:requests", all);
51
+ }
52
+ event(plan, type, reason, extra = {}) {
53
+ plan.lastReason = reason;
54
+ plan.history.push({
55
+ id: randomUUID(),
56
+ at: new Date(this.now()).toISOString(),
57
+ type,
58
+ reason,
59
+ ...extra,
60
+ });
61
+ }
62
+ }
@@ -0,0 +1,306 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { display, units } from "./model.js";
3
+ import { guardPlan } from "./policy.js";
4
+ const day = (at) => new Date(at).toISOString().slice(0, 10);
5
+ const sum = (values) => values.reduce((total, value) => total + BigInt(value), 0n).toString();
6
+ const signedUnits = (value, decimals) => value.startsWith("-")
7
+ ? -BigInt(units(value.slice(1), decimals))
8
+ : BigInt(units(value, decimals));
9
+ const safeError = (error) => error instanceof Error
10
+ ? error.message.slice(0, 400)
11
+ : "Testnet operation failed";
12
+ /** One independent loop: persist intent, guard, submit, reconcile exactly once. */
13
+ export class TestnetRunner {
14
+ repository;
15
+ adapter;
16
+ readModel;
17
+ refreshReview;
18
+ now;
19
+ fault;
20
+ heartbeat = 0;
21
+ ticking = false;
22
+ constructor(repository, adapter, readModel, refreshReview, now, fault) {
23
+ this.repository = repository;
24
+ this.adapter = adapter;
25
+ this.readModel = readModel;
26
+ this.refreshReview = refreshReview;
27
+ this.now = now;
28
+ this.fault = fault;
29
+ }
30
+ recover() {
31
+ this.repository.store.transaction(() => {
32
+ for (const plan of this.repository.plans())
33
+ if (plan.status === "running") {
34
+ plan.status = "paused";
35
+ plan.epoch++;
36
+ this.repository.event(plan, "recovered", "Runner restarted. Explicit resume is required after pending digest reconciliation");
37
+ this.repository.save(plan);
38
+ }
39
+ for (const intent of this.repository.intents())
40
+ if (["prepared", "signed"].includes(intent.state)) {
41
+ intent.state = "cancelled";
42
+ this.repository.saveIntent(intent);
43
+ }
44
+ });
45
+ }
46
+ settle(intent, receipt) {
47
+ this.repository.store.transaction(() => {
48
+ const current = this.repository.intents().find((i) => i.id === intent.id);
49
+ if (!current || current.state === "settled")
50
+ return;
51
+ if (receipt.digest !== intent.prepared.digest)
52
+ throw new Error("Receipt digest differs from persisted transaction");
53
+ const plan = this.repository.get(intent.planId);
54
+ if (receipt.success && !receipt.accountingVerified) {
55
+ if (plan.status === "running") {
56
+ plan.status = "blocked";
57
+ plan.epoch++;
58
+ }
59
+ if (!plan.history.some((event) => event.type === "accounting_unverified" &&
60
+ event.digest === receipt.digest))
61
+ this.repository.event(plan, "accounting_unverified", "Confirmed digest has incomplete fill accounting. No new order or resume is permitted until reconciliation succeeds", {
62
+ digest: receipt.digest,
63
+ txId: receipt.digest,
64
+ gasSui: receipt.gasSui,
65
+ accountingVerified: false,
66
+ });
67
+ current.receipt = receipt;
68
+ current.state = "submitted";
69
+ this.repository.saveIntent(current);
70
+ this.repository.save(plan);
71
+ return;
72
+ }
73
+ plan.gas = display((signedUnits(plan.gas, 9) + signedUnits(receipt.gasSui, 9)).toString(), 9);
74
+ if (receipt.success && receipt.accountingVerified) {
75
+ if (BigInt(receipt.amountIn) <= 0n ||
76
+ BigInt(receipt.amountIn) > BigInt(intent.prepared.amountIn) ||
77
+ BigInt(receipt.amountOut) < BigInt(intent.prepared.minOut))
78
+ throw new Error("Confirmed amounts violate the persisted swap bounds");
79
+ plan.spent = (BigInt(plan.spent) + BigInt(receipt.amountIn)).toString();
80
+ plan.output = (BigInt(plan.output) + BigInt(receipt.amountOut)).toString();
81
+ plan.lastTradeDay = day(receipt.at);
82
+ this.repository.event(plan, "filled", "Confirmed testnet swap; amounts reconciled from chain effects", {
83
+ at: new Date(receipt.at).toISOString(),
84
+ digest: receipt.digest,
85
+ txId: receipt.digest,
86
+ amountIn: display(receipt.amountIn, plan.policy.coinIn.decimals),
87
+ amountOut: display(receipt.amountOut, plan.policy.coinOut.decimals),
88
+ gasSui: receipt.gasSui,
89
+ accountingVerified: true,
90
+ });
91
+ if (plan.status === "running" &&
92
+ BigInt(plan.spent) + BigInt(plan.policy.amountIn) >
93
+ BigInt(plan.policy.budgetIn)) {
94
+ plan.status = "completed";
95
+ this.repository.event(plan, "completed", "Remaining approved budget cannot fund a complete order");
96
+ }
97
+ }
98
+ else {
99
+ if (plan.status === "running") {
100
+ plan.status = "blocked";
101
+ plan.epoch++;
102
+ }
103
+ this.repository.event(plan, receipt.success ? "accounting_unverified" : "failed", receipt.success
104
+ ? "Transaction confirmed but fill accounting is incomplete. Reconciliation is required before further trading"
105
+ : receipt.error || "Testnet transaction failed; gas was recorded", {
106
+ digest: receipt.digest,
107
+ txId: receipt.digest,
108
+ gasSui: receipt.gasSui,
109
+ accountingVerified: false,
110
+ });
111
+ }
112
+ current.state = "settled";
113
+ current.receipt = receipt;
114
+ this.repository.saveIntent(current);
115
+ this.repository.save(plan);
116
+ });
117
+ }
118
+ async reconcile() {
119
+ for (const intent of this.repository
120
+ .intents()
121
+ .filter((i) => i.state === "submitted")) {
122
+ const plan = this.repository.get(intent.planId);
123
+ if (!plan.binding)
124
+ continue;
125
+ const receipt = intent.receipt &&
126
+ (!intent.receipt.success || intent.receipt.accountingVerified)
127
+ ? { status: "confirmed", receipt: intent.receipt }
128
+ : await this.adapter
129
+ .lookup(plan.binding, intent.prepared)
130
+ .catch(() => ({ status: "pending" }));
131
+ if (receipt.status === "confirmed") {
132
+ this.settle(intent, receipt.receipt);
133
+ await this.readModel.refreshBalances(intent.planId);
134
+ }
135
+ }
136
+ }
137
+ async tick() {
138
+ if (this.ticking)
139
+ return;
140
+ this.ticking = true;
141
+ this.heartbeat = this.now();
142
+ try {
143
+ await this.reconcile();
144
+ for (const request of this.repository
145
+ .requests()
146
+ .filter((r) => r.authorization && r.status === "pending"))
147
+ await this.refreshReview(request.id).catch(() => undefined);
148
+ for (const original of this.repository.plans()) {
149
+ if (original.status !== "running" ||
150
+ original.nextRunAt > this.now() ||
151
+ this.repository
152
+ .intents()
153
+ .some((i) => i.planId === original.id && i.state === "submitted"))
154
+ continue;
155
+ const id = original.id, epoch = original.epoch;
156
+ try {
157
+ guardPlan(original, this.now(), epoch);
158
+ original.nextRunAt =
159
+ this.now() + original.input.intervalSeconds * 1000;
160
+ this.repository.save(original);
161
+ const inspection = await this.adapter.inspect(original.binding, original.policy);
162
+ this.readModel.rememberInspection(id, inspection);
163
+ let plan = this.repository.get(id);
164
+ guardPlan(plan, this.now(), epoch);
165
+ if (!inspection.active || inspection.revoked || inspection.expired)
166
+ throw new Error(inspection.reason || "Onchain permission is no longer active");
167
+ if (BigInt(inspection.ownerInputBalance) <
168
+ BigInt(plan.policy.amountIn) ||
169
+ BigInt(inspection.agentGasBalance) < 10000000n)
170
+ throw new Error("Insufficient testnet input address balance or agent gas");
171
+ const today = day(inspection.chainTimeMs), todaySpent = sum(plan.history
172
+ .filter((h) => h.type === "filled" && h.at.slice(0, 10) === today)
173
+ .map((h) => units(h.amountIn, plan.policy.coinIn.decimals)));
174
+ if (BigInt(plan.spent) + BigInt(plan.policy.amountIn) >
175
+ BigInt(plan.policy.budgetIn)) {
176
+ plan.status = "completed";
177
+ this.repository.event(plan, "completed", "Approved total budget exhausted");
178
+ this.repository.save(plan);
179
+ continue;
180
+ }
181
+ if (BigInt(todaySpent) + BigInt(plan.policy.amountIn) >
182
+ BigInt(plan.policy.dailyLimitIn) ||
183
+ BigInt(inspection.dailyRemaining) < BigInt(plan.policy.amountIn)) {
184
+ this.repository.event(plan, "waiting", "Daily cap reached; waiting for the next chain UTC day");
185
+ this.repository.save(plan);
186
+ continue;
187
+ }
188
+ if (BigInt(inspection.allowanceRemaining) < BigInt(plan.policy.amountIn))
189
+ throw new Error("Onchain spending allowance is exhausted");
190
+ if (plan.input.botId === "price-watch" &&
191
+ plan.lastTradeDay === today) {
192
+ this.repository.event(plan, "waiting", "Price Watch already traded today");
193
+ this.repository.save(plan);
194
+ continue;
195
+ }
196
+ const quote = await this.adapter.quote(plan.binding, plan.policy, plan.policy.amountIn);
197
+ plan = this.repository.get(id);
198
+ guardPlan(plan, this.now(), epoch);
199
+ if (this.now() - quote.at > 15_000 ||
200
+ quote.at > this.now() + 1000 ||
201
+ quote.poolId !== plan.policy.poolId ||
202
+ BigInt(quote.amountIn) <= 0n ||
203
+ BigInt(quote.amountIn) > BigInt(plan.policy.amountIn) ||
204
+ BigInt(quote.amountOut) <= 0n)
205
+ throw new Error("Quote is stale, empty or outside the approved route/sizing");
206
+ plan.valuation = {
207
+ price: quote.price,
208
+ at: quote.at,
209
+ source: `${plan.input.venue} executable testnet demo quote`,
210
+ };
211
+ this.repository.save(plan);
212
+ const price = BigInt(units(quote.price, 9)), limit = BigInt(units(plan.input.limitPrice, 9));
213
+ if (plan.input.direction === "usdc_to_sui"
214
+ ? price > limit
215
+ : price < limit) {
216
+ this.repository.event(plan, "waiting", "Current executable price is outside the owner-selected limit");
217
+ this.repository.save(plan);
218
+ continue;
219
+ }
220
+ const prepared = await this.adapter.prepare(plan.binding, plan.policy, quote, plan.input.slippageBps);
221
+ plan = this.repository.get(id);
222
+ guardPlan(plan, this.now(), epoch);
223
+ if (this.now() - prepared.quoteAt > 15_000 ||
224
+ prepared.expiresAt <= this.now())
225
+ throw new Error("Transaction preparation exceeded quote freshness/validity");
226
+ const intent = {
227
+ id: randomUUID(),
228
+ planId: id,
229
+ planHash: plan.reviewHash,
230
+ epoch,
231
+ createdAt: this.now(),
232
+ prepared,
233
+ state: "prepared",
234
+ };
235
+ this.repository.saveIntent(intent);
236
+ this.fault?.("after_prepare");
237
+ const signed = await this.adapter.sign(plan.binding, prepared);
238
+ intent.signed = signed;
239
+ intent.state = "signed";
240
+ this.repository.saveIntent(intent);
241
+ this.fault?.("after_sign");
242
+ plan = this.repository.get(id);
243
+ try {
244
+ guardPlan(plan, this.now(), epoch);
245
+ if (signed.digest !== prepared.digest ||
246
+ prepared.expiresAt <= this.now() ||
247
+ this.now() - prepared.quoteAt > 15_000)
248
+ throw new Error("Signed transaction no longer matches a fresh eligible intent");
249
+ }
250
+ catch (error) {
251
+ intent.state = "cancelled";
252
+ this.repository.saveIntent(intent);
253
+ throw error;
254
+ }
255
+ intent.state = "submitted";
256
+ intent.submittedAt = this.now();
257
+ this.repository.saveIntent(intent);
258
+ this.fault?.("after_submission_intent");
259
+ let broadcastReady = false;
260
+ const result = await this.adapter
261
+ .submit(plan.binding, prepared, signed, () => {
262
+ try {
263
+ guardPlan(this.repository.get(id), this.now(), epoch);
264
+ if (prepared.expiresAt <= this.now() ||
265
+ this.now() - prepared.quoteAt > 15_000)
266
+ throw new Error("Quote or transaction expired before broadcast");
267
+ broadcastReady = true;
268
+ }
269
+ catch (error) {
270
+ intent.state = "cancelled";
271
+ this.repository.saveIntent(intent);
272
+ throw error;
273
+ }
274
+ })
275
+ .catch((error) => {
276
+ if (!broadcastReady) {
277
+ intent.state = "cancelled";
278
+ this.repository.saveIntent(intent);
279
+ throw error;
280
+ }
281
+ return { status: "pending" };
282
+ });
283
+ if (result.status === "confirmed") {
284
+ intent.receipt = result.receipt;
285
+ this.repository.saveIntent(intent);
286
+ this.fault?.("after_receipt");
287
+ this.settle(intent, result.receipt);
288
+ await this.readModel.refreshBalances(id);
289
+ }
290
+ }
291
+ catch (error) {
292
+ const plan = this.repository.get(id);
293
+ if (plan.status === "running") {
294
+ plan.status = "blocked";
295
+ plan.epoch++;
296
+ this.repository.event(plan, "blocked", safeError(error));
297
+ this.repository.save(plan);
298
+ }
299
+ }
300
+ }
301
+ }
302
+ finally {
303
+ this.ticking = false;
304
+ }
305
+ }
306
+ }
@@ -0,0 +1 @@
1
+ export {};