felix-mcp 2.0.123 → 2.0.129

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.
@@ -0,0 +1,1076 @@
1
+ // HYPERCORE_DIRECT_CLIENT_2026_09_26: the local driver for the engine's
2
+ // Arc home Safe -> the SAME account's HyperCore perps balance, direct via Relay
3
+ // (/v1/arc-home/hypercore-fundings/*, engine services/arc_home_hypercore_funding.py).
4
+ //
5
+ // DISABLED BY DEFAULT, twice over:
6
+ // * HYPERCORE_DIRECT_CLIENT_ENABLED = false keeps the tool unlisted and refused;
7
+ // * SHIPPED_HYPERCORE_POLICY is EMPTY. The driver refuses before any request
8
+ // unless a policy supplies reviewed evidence for every release gate:
9
+ // 1. trustedSolvers -- no Arc -> HyperCore Relay solver is verified yet;
10
+ // 2. verifyDepositoryRuntime -- the Relay depository's code on Arc;
11
+ // 3. arcRefundExtraData -- the Arc refund extraData word Relay signs;
12
+ // 6. verifySafeState -- the Safe's nonce/threshold/modules at signing.
13
+ // Nothing here mirrors an unreviewed value as a production pin; test
14
+ // fixtures inject a test-only policy.
15
+ // Gate 4 is checked live: a bounded public Hyperliquid `userAbstraction`
16
+ // read before signing; anything but "default" (perps credit) refuses.
17
+ // Gate 5 is disclosed, not strengthened: completion attribution is
18
+ // Relay-attested (Relay's oracle-written order mapping, checked by Felix),
19
+ // plus this client's own Hyperliquid ledger read of exactly one matching
20
+ // perps send. It is not a cryptographic proof that the send filled THIS order.
21
+ //
22
+ // Before ANY local signature the client re-derives, from pins and the policy,
23
+ // never from server authority:
24
+ // * the Relay order id (EIP-712 struct hash) and the solver it recovers to;
25
+ // * input: exactly the amount in Arc USDC; output: exactly one payment on
26
+ // `hyperliquid`, HyperCore USDC, to the SAME owner, minimum >= the client's
27
+ // 1% floor and any requested minimum, no fees/calls/extraData, live deadline;
28
+ // * refunds: exactly Arc USDC -> the Safe (policy extraData) and HyperCore
29
+ // USDC -> the owner, minimum 0, the order deadline;
30
+ // * the SafeTx: canonical Safe 1.3.0 types, chain 5042, the verified Safe,
31
+ // zero value/gas/refund fields, DELEGATECALL only to the pinned
32
+ // MultiSendCallOnly, whose packed calls must be EXACTLY
33
+ // USDC.approve(depository, amount) and depository.depositErc20(safe, USDC,
34
+ // amount, orderId), then the pinned Arc USDC fee transfer; the digest is
35
+ // recomputed and must equal the server's.
36
+ // The client signs its OWN rebuilt typed data. It journals the prepared
37
+ // identity and the exact signature before submitting, submits once per
38
+ // invocation, and resumes the same key without ever signing again.
39
+ import { encodeFunctionData, getAddress, hashStruct, recoverMessageAddress } from "viem";
40
+ import { ARC_MAINNET_CHAIN_ID, ARC_USDC as ARC_USDC_CHECKSUM, SAFE_MULTISEND_CALL_ONLY, arcSafeTxHash, assertArcSafeTxShape, decodeMultiSendCallOnly, } from "./arc-home.js";
41
+ import { RELAY_DEPOSITORY, RELAY_ORDER_TYPES, relayOrderMessage } from "./arc-pm-return.js";
42
+ import { ENGINE_OBSERVE_NEXT_ACTION, SAFE_INVALIDATION_TOOL, describeOpenJourney, invalidationSuggestion, openJourneyId, safeNonceRefusalGuidance, } from "./arc-safe-invalidation-hints.js";
43
+ // Enabled 2026-09-27 (A4_ENABLEMENT, operator accepted Relay attribution); the
44
+ // launch policy still refuses without a private Arc proof quorum, and the
45
+ // engine still gates on ROUTE_REVIEWED + FELIX_ARC_HYPERCORE_DIRECT_ENABLED.
46
+ export const HYPERCORE_DIRECT_CLIENT_ENABLED = true;
47
+ export const HYPERCORE_TOOL = "fund_hypercore_from_arc";
48
+ export const ARC_USDC = ARC_USDC_CHECKSUM.toLowerCase();
49
+ export const USDC_HYPERCORE = "0x00000000000000000000000000000000";
50
+ export const HYPERCORE_UNITS_PER_USDC_UNIT = 100n; // HyperCore USDC is 8 decimals
51
+ export const MIN_AMOUNT_UNITS = 5000000n;
52
+ export const MAX_AMOUNT_UNITS = 25000000n;
53
+ // Provider deduction only. The separately disclosed Felix fee is additional.
54
+ export const MAX_ALL_IN_COST_BPS = 100n;
55
+ // ARC_RELAY_PLATFORM_FEE_2026_09_26: Felix's flat network fee for HyperCore
56
+ // funding (the existing $1.00 Hyperliquid crypto-funding fee), paid by the Safe
57
+ // in the SAME SafeTx as the deposit. These are THIS client's own pins: the
58
+ // exact recipient and the exact amount it will sign for (its owner cap). A
59
+ // server that asks for any other fee, recipient or shape is refused; no server
60
+ // field is ever the authority for what is signed.
61
+ export const HYPERCORE_NETWORK_FEE_UNITS = 1000000n;
62
+ export const FELIX_FEE_TREASURY = "0xdc9c35bf585fba2a39bcd17bdfe343277b595cad";
63
+ export const HYPERCORE_FEE_DISCLOSURE = "A flat 1.00 USDC network fee is paid from your Arc home Safe to Felix's treasury in the same transaction "
64
+ + "as the deposit. It is charged only if that transaction executes, and it is not refunded if Relay later "
65
+ + "refunds the principal.";
66
+ // HYPERCORE_ACTIVATION_2026_09_28: an owner with no HyperCore account yet
67
+ // (Hyperliquid userRole "missing") pays Hyperliquid's one-time new-account fee,
68
+ // passed on by Relay (fees.relayerGas, 1.20 USDC on 2026-09-27) and DEDUCTED
69
+ // FROM THE HYPERCORE CREDIT. The engine admits it only with the owner's explicit
70
+ // `accept_activation_cost_units` (engine relay_arc_hypercore_adapter
71
+ // MAX_ACTIVATION_COST_UNITS); this client never accepts it on its own. This is
72
+ // THIS client's own ceiling, mirrored from the engine's reviewed one: a plan or
73
+ // refusal naming any other ceiling, or a cost above it, is refused.
74
+ export const MAX_ACTIVATION_COST_UNITS = 1500000n;
75
+ export const HYPERCORE_ACTIVATION_NEXT_ACTION = "accept_activation_cost";
76
+ export const HYPERCORE_ACTIVATION_DISCLOSURE = "A brand-new HyperCore account pays Hyperliquid's one-time account activation fee (passed on by Relay) on its "
77
+ + "first deposit. It is deducted from this funding's HyperCore credit, once; it is separate from Relay's transfer "
78
+ + "cost (at most 1% of the principal) and from Felix's 1.00 USDC network fee. It is charged only when you pass "
79
+ + "accept_activation_cost_usd, and never above what you accept (at most 1.5 USDC).";
80
+ const ORDER_DEADLINE_MARGIN_S = 60;
81
+ const QUOTE_SIGNING_MARGIN_S = 60;
82
+ // Mirrors the engine adapter's _MAX_DEADLINE_SECONDS: a Relay order may not
83
+ // promise delivery further out than 8 days.
84
+ const ORDER_MAX_DEADLINE_S = 8 * 86_400;
85
+ // Mirrors the engine adapter's CREDIT_LATE_WINDOW_MS: a credit counts only
86
+ // within an hour of the proven Arc source block.
87
+ const CREDIT_LATE_WINDOW_MS = 3_600_000;
88
+ // Tolerated disagreement between this client's clock and chain/engine time.
89
+ const CLOCK_SKEW_MS = 60_000;
90
+ const DEFAULT_MAX_POLLS = 60;
91
+ const MIN_POLL_MS = 2_000;
92
+ const MAX_POLL_MS = 30_000;
93
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
94
+ const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
95
+ const HASH = /^0x[0-9a-fA-F]{64}$/;
96
+ const UINT = /^(0|[1-9][0-9]{0,40})$/;
97
+ const APPROVE_ABI = [{ type: "function", name: "approve", stateMutability: "nonpayable",
98
+ inputs: [{ name: "spender", type: "address" }, { name: "amount", type: "uint256" }], outputs: [{ type: "bool" }] }];
99
+ const TRANSFER_ABI = [{ type: "function", name: "transfer", stateMutability: "nonpayable",
100
+ inputs: [{ name: "to", type: "address" }, { name: "amount", type: "uint256" }], outputs: [{ type: "bool" }] }];
101
+ const DEPOSIT_ABI = [{ type: "function", name: "depositErc20", stateMutability: "nonpayable",
102
+ inputs: [{ name: "depositor", type: "address" }, { name: "token", type: "address" },
103
+ { name: "amount", type: "uint256" }, { name: "id", type: "bytes32" }], outputs: [] }];
104
+ export const CP = {
105
+ scope: "hcfund:scope",
106
+ prepared: "hcfund:prepared",
107
+ signed: "hcfund:signed",
108
+ submission: "hcfund:submission-started",
109
+ completed: "hcfund:completed",
110
+ };
111
+ export const SHIPPED_HYPERCORE_POLICY = Object.freeze({
112
+ trustedSolvers: Object.freeze([]),
113
+ verifyDepositoryRuntime: null,
114
+ arcRefundExtraData: null,
115
+ verifySafeState: null,
116
+ });
117
+ /** Every gate the policy leaves unproven, by stable code. Empty = complete. */
118
+ export function policyGaps(policy) {
119
+ const gaps = [];
120
+ const solvers = policy?.trustedSolvers;
121
+ if (!Array.isArray(solvers) || !solvers.length || !solvers.every((s) => typeof s === "string" && ADDRESS.test(s))) {
122
+ gaps.push("hypercore_solver_unverified");
123
+ }
124
+ if (typeof policy?.verifyDepositoryRuntime !== "function")
125
+ gaps.push("hypercore_depository_runtime_unverified");
126
+ if (typeof policy?.arcRefundExtraData !== "string" || !HASH.test(policy.arcRefundExtraData)) {
127
+ gaps.push("hypercore_refund_policy_unverified");
128
+ }
129
+ if (typeof policy?.verifySafeState !== "function")
130
+ gaps.push("hypercore_safe_state_unverified");
131
+ return gaps;
132
+ }
133
+ export class HypercoreHostileServer extends Error {
134
+ constructor(message) {
135
+ super(message);
136
+ this.name = "HypercoreHostileServer";
137
+ }
138
+ }
139
+ function hostile(message) {
140
+ throw new HypercoreHostileServer(message);
141
+ }
142
+ function isRecord(value) {
143
+ return typeof value === "object" && value !== null && !Array.isArray(value);
144
+ }
145
+ function lower(value, name) {
146
+ if (typeof value !== "string" || !ADDRESS.test(value))
147
+ hostile(`${name} is not an address`);
148
+ return value.toLowerCase();
149
+ }
150
+ function units(value, name) {
151
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0)
152
+ return BigInt(value);
153
+ if (typeof value !== "string" || !UINT.test(value))
154
+ hostile(`${name} is not exact integer units`);
155
+ return BigInt(value);
156
+ }
157
+ function floorUnits(amount) {
158
+ return (amount * (10000n - MAX_ALL_IN_COST_BPS) + 9999n) / 10000n;
159
+ }
160
+ function ceilDiv(a, b) {
161
+ return (a + b - 1n) / b;
162
+ }
163
+ function usdText(value) {
164
+ const frac = (value % 1000000n).toString().padStart(6, "0").replace(/0+$/, "");
165
+ return `${value / 1000000n}${frac ? `.${frac}` : ""}`;
166
+ }
167
+ /**
168
+ * The plan's HyperCore activation, bound to THIS client's acceptance. Without
169
+ * an acceptance a plan may carry no activation cost at all; with one, the plan
170
+ * must journal exactly that acceptance, the client's own ceiling, and a cost
171
+ * no higher than what was accepted (an existing account costs 0).
172
+ */
173
+ function verifyActivationTerms(raw, accepted) {
174
+ if (accepted === null) {
175
+ if (raw === undefined || raw === null)
176
+ return { cost: 0n, transfer: null };
177
+ if (!isRecord(raw) || units(raw.activation_cost_units, "hypercore_activation.activation_cost_units") !== 0n) {
178
+ hostile("the plan charges a HyperCore activation the owner did not accept");
179
+ }
180
+ return { cost: 0n, transfer: null };
181
+ }
182
+ if (!isRecord(raw))
183
+ hostile("the plan does not journal the owner's HyperCore activation acceptance");
184
+ const a = raw;
185
+ if (units(a.accepted_activation_cost_units, "hypercore_activation.accepted_activation_cost_units") !== accepted) {
186
+ hostile("the plan journals a different HyperCore activation acceptance than the owner's");
187
+ }
188
+ if (units(a.max_activation_cost_units, "hypercore_activation.max_activation_cost_units") !== MAX_ACTIVATION_COST_UNITS) {
189
+ hostile("the plan's HyperCore activation ceiling is not this client's");
190
+ }
191
+ const cost = units(a.activation_cost_units, "hypercore_activation.activation_cost_units");
192
+ if (cost > accepted || cost > MAX_ACTIVATION_COST_UNITS) {
193
+ hostile(`the plan's HyperCore activation cost (${usdText(cost)} USDC) is above what the owner accepted `
194
+ + `(${usdText(accepted)} USDC)`);
195
+ }
196
+ if (cost > 0n && (a.account_role !== "missing" || a.required !== true
197
+ || typeof a.disclosure !== "string" || !a.disclosure.trim())) {
198
+ hostile("the plan charges a HyperCore activation for an account it does not disclose as missing");
199
+ }
200
+ if (cost === 0n && a.required === true)
201
+ hostile("the plan requires a HyperCore activation it does not price");
202
+ return { cost, transfer: units(a.transfer_cost_units, "hypercore_activation.transfer_cost_units") };
203
+ }
204
+ /** The whole prepared view -> a plan this client would sign, or a refusal. */
205
+ export async function verifyPrepared(view, ctx) {
206
+ if (!isRecord(view))
207
+ hostile("the prepared view is not an object");
208
+ const v = view;
209
+ if (v.kind !== "arc_hypercore_funding" || v.phase !== "prepared" || v.provider !== "relay"
210
+ || v.destination_class !== "hypercore_perps" || v.route_kind !== "direct_arc_home_to_hypercore_perps") {
211
+ hostile("the view is not a prepared Arc -> HyperCore perps funding");
212
+ }
213
+ const fundingId = typeof v.id === "string" && UUID.test(v.id) ? v.id : hostile("funding id is invalid");
214
+ if (v.source_chain_id !== ARC_MAINNET_CHAIN_ID || v.destination_chain_id !== 1337)
215
+ hostile("the chains are not Arc -> HyperCore");
216
+ if (lower(v.safe, "safe") !== ctx.safe || lower(v.owner, "owner") !== ctx.owner
217
+ || lower(v.recipient, "recipient") !== ctx.owner) {
218
+ hostile("the funding is not from this account's Safe to its own owner");
219
+ }
220
+ if (units(v.amount_units, "amount_units") !== ctx.amount)
221
+ hostile("the funding amount changed");
222
+ const quoteExpiresAt = Number(v.quote_expires_at);
223
+ if (!Number.isSafeInteger(quoteExpiresAt) || quoteExpiresAt <= 0)
224
+ hostile("quote expiry is invalid");
225
+ // -------- the Relay order: recompute, recover, and bind every field
226
+ const relay = v.relay_order;
227
+ if (!isRecord(relay))
228
+ hostile("relay_order is missing");
229
+ const r = relay;
230
+ const orderId = String(r.order_id || "").toLowerCase();
231
+ if (!HASH.test(orderId) || String(v.order_id || "").toLowerCase() !== orderId)
232
+ hostile("order id is invalid or inconsistent");
233
+ const signature = String(r.order_signature || "");
234
+ if (!/^0x[0-9a-fA-F]{130}$/.test(signature))
235
+ hostile("order signature is not 65 bytes");
236
+ let message;
237
+ try {
238
+ message = relayOrderMessage(r.order_data);
239
+ }
240
+ catch (error) {
241
+ hostile(`relay_order is malformed: ${error.message}`);
242
+ }
243
+ let recomputed;
244
+ try {
245
+ recomputed = hashStruct({ types: RELAY_ORDER_TYPES, primaryType: "Order", data: message }).toLowerCase();
246
+ }
247
+ catch {
248
+ hostile("relay_order does not hash as a Relay v1 order");
249
+ }
250
+ if (recomputed !== orderId)
251
+ hostile("the order id is not the hash of the signed order");
252
+ let recovered;
253
+ try {
254
+ recovered = (await recoverMessageAddress({ message: { raw: orderId }, signature: signature })).toLowerCase();
255
+ }
256
+ catch {
257
+ hostile("the order signature does not recover");
258
+ }
259
+ const trusted = new Set(ctx.policy.trustedSolvers.map((s) => s.toLowerCase()));
260
+ if (recovered !== message.solver.toLowerCase() || recovered !== lower(r.solver, "relay_order.solver")
261
+ || recovered !== lower(v.solver, "solver") || !trusted.has(recovered)) {
262
+ hostile("the order is not signed by a Relay solver the reviewed policy trusts");
263
+ }
264
+ if (message.version !== "v1" || message.solverChainId !== "base")
265
+ hostile("the order is not a Relay v1 order");
266
+ const payment = message.inputs[0].payment;
267
+ if (payment.chainId !== "arc" || payment.currency !== ARC_USDC || payment.amount !== ctx.amount || payment.weight !== 1n) {
268
+ hostile("the order does not take exactly the amount in Arc USDC");
269
+ }
270
+ const output = message.output;
271
+ const paid = output.payments[0];
272
+ if (output.chainId !== "hyperliquid" || paid.recipient !== ctx.owner || paid.currency !== USDC_HYPERCORE) {
273
+ hostile("the order does not pay HyperCore USDC to this account's own owner");
274
+ }
275
+ const scaledAmount = ctx.amount * HYPERCORE_UNITS_PER_USDC_UNIT;
276
+ // HYPERCORE_ACTIVATION_2026_09_28: the 1% cap still bounds the TRANSFER; an
277
+ // accepted, disclosed one-time activation lowers the credit floor by exactly
278
+ // its cost (never by more than the owner accepted).
279
+ const accepted = ctx.acceptedActivation ?? null;
280
+ const activation = verifyActivationTerms(v.hypercore_activation, accepted);
281
+ const floorCredit = floorUnits(ctx.amount) - activation.cost;
282
+ const floor = floorCredit * HYPERCORE_UNITS_PER_USDC_UNIT;
283
+ const requested = (ctx.requestedMinimum ?? 0n) * HYPERCORE_UNITS_PER_USDC_UNIT;
284
+ if (paid.minimumAmount < floor || paid.minimumAmount < requested || paid.minimumAmount > paid.expectedAmount
285
+ || paid.expectedAmount + activation.cost * HYPERCORE_UNITS_PER_USDC_UNIT > scaledAmount) {
286
+ hostile("the order's signed minimum is below the client's floor or above what is deposited");
287
+ }
288
+ if (output.calls.length !== 0 || output.extraData !== "0x" || message.fees.length !== 0) {
289
+ hostile("the order carries calls, extra data or fees");
290
+ }
291
+ if (output.deadline < ctx.nowS + ORDER_DEADLINE_MARGIN_S)
292
+ hostile("the order is expired or about to");
293
+ if (output.deadline > ctx.nowS + ORDER_MAX_DEADLINE_S)
294
+ hostile("the order's deadline is beyond the 8-day bound");
295
+ const extra = String(ctx.policy.arcRefundExtraData).toLowerCase();
296
+ const refunds = new Set(message.inputs[0].refunds.map((refund) => {
297
+ const expectedExtra = refund.chainId === "arc" ? extra : "0x";
298
+ if (refund.minimumAmount !== 0n || refund.deadline !== output.deadline || refund.extraData !== expectedExtra) {
299
+ hostile("an order refund is not the reviewed refund");
300
+ }
301
+ return `${refund.chainId}|${refund.recipient}|${refund.currency}`;
302
+ }));
303
+ if (refunds.size !== 2 || !refunds.has(`arc|${ctx.safe}|${ARC_USDC}`)
304
+ || !refunds.has(`hyperliquid|${ctx.owner}|${USDC_HYPERCORE}`)) {
305
+ hostile("the order refunds someone other than the Safe on Arc and the owner on HyperCore");
306
+ }
307
+ const signedMinimumUnits = ceilDiv(paid.minimumAmount, HYPERCORE_UNITS_PER_USDC_UNIT);
308
+ const viewMinimum = units(v.minimum_credit_units, "minimum_credit_units");
309
+ if (viewMinimum < signedMinimumUnits || viewMinimum < floorCredit || viewMinimum > ctx.amount) {
310
+ hostile("the funding's minimum credit is not bound by the signed order");
311
+ }
312
+ if (accepted !== null) {
313
+ // The activation's credit math, re-derived from the SIGNED order (the
314
+ // engine's validate_arc_hypercore_quote): principal - activation - Relay's
315
+ // transfer cost = the expected credit; the transfer cost stays within 1%;
316
+ // the disclosed minimum is max(requested, floor, Relay's signed minimum).
317
+ const expected = paid.expectedAmount / HYPERCORE_UNITS_PER_USDC_UNIT;
318
+ const transfer = activation.transfer;
319
+ if (units(v.expected_credit_units, "expected_credit_units") !== expected
320
+ || transfer === null || expected + activation.cost + transfer !== ctx.amount
321
+ || transfer > ctx.amount - floorUnits(ctx.amount)
322
+ || units(v.quoted_cost_units, "quoted_cost_units") !== ctx.amount - expected) {
323
+ hostile("the disclosed credit math (principal - activation - transfer cost) is not the signed order's");
324
+ }
325
+ const floorMinimum = [ctx.requestedMinimum ?? 0n, floorCredit, signedMinimumUnits]
326
+ .reduce((a, b) => (a > b ? a : b));
327
+ if (viewMinimum !== floorMinimum)
328
+ hostile("the disclosed minimum credit is not the signed order's");
329
+ }
330
+ // -------- the SafeTx: canonical shape, exact packed calls, recomputed digest
331
+ const safeTx = v.safe_transaction;
332
+ if (!isRecord(safeTx))
333
+ hostile("safe_transaction is missing");
334
+ const st = safeTx;
335
+ let shape;
336
+ try {
337
+ shape = assertArcSafeTxShape(st.typed_data, { safe: ctx.safe, chainId: ARC_MAINNET_CHAIN_ID });
338
+ }
339
+ catch (error) {
340
+ hostile(`the SafeTx is not canonical: ${error.message}`);
341
+ }
342
+ if (shape.operation !== 1 || shape.to.toLowerCase() !== SAFE_MULTISEND_CALL_ONLY.toLowerCase()) {
343
+ hostile("the SafeTx is not a DELEGATECALL to the pinned MultiSendCallOnly");
344
+ }
345
+ let calls;
346
+ try {
347
+ calls = decodeMultiSendCallOnly(shape.data);
348
+ }
349
+ catch (error) {
350
+ hostile(`the SafeTx batch does not decode: ${error.message}`);
351
+ }
352
+ // Relay's two steps, then exactly one fee transfer to THIS client's pinned
353
+ // treasury for THIS client's pinned amount. Rebuilt locally; compared byte for byte.
354
+ const expectedCalls = [
355
+ { to: ARC_USDC, data: encodeFunctionData({ abi: APPROVE_ABI, functionName: "approve",
356
+ args: [getAddress(RELAY_DEPOSITORY), ctx.amount] }).toLowerCase() },
357
+ { to: RELAY_DEPOSITORY, data: encodeFunctionData({ abi: DEPOSIT_ABI, functionName: "depositErc20",
358
+ args: [getAddress(ctx.safe), getAddress(ARC_USDC), ctx.amount, orderId] }).toLowerCase() },
359
+ { to: ARC_USDC, data: encodeFunctionData({ abi: TRANSFER_ABI, functionName: "transfer",
360
+ args: [getAddress(FELIX_FEE_TREASURY), HYPERCORE_NETWORK_FEE_UNITS] }).toLowerCase() },
361
+ ];
362
+ if (calls.length !== 3 || calls.some((call, i) => call.operation !== 0
363
+ || call.to.toLowerCase() !== expectedCalls[i].to || call.data.toLowerCase() !== expectedCalls[i].data)) {
364
+ hostile("the SafeTx does not make exactly the approve, the deposit for this order and the pinned network fee");
365
+ }
366
+ // The server's disclosure must agree with what is signed (it is not the authority).
367
+ const disclosed = v.network_fee;
368
+ if (!isRecord(disclosed) || String(disclosed.fee_units) !== HYPERCORE_NETWORK_FEE_UNITS.toString()
369
+ || String(disclosed.recipient || "").toLowerCase() !== FELIX_FEE_TREASURY
370
+ || disclosed.refundable !== false) {
371
+ hostile("the disclosed network fee is not the fee in the SafeTx");
372
+ }
373
+ const claimed = String(st.safe_tx_hash || "").toLowerCase();
374
+ const typedData = rebuildTypedData(shape.data, shape.nonce, ctx.safe);
375
+ const digest = arcSafeTxHash(typedData).toLowerCase();
376
+ if (!HASH.test(claimed) || claimed !== digest || arcSafeTxHash(st.typed_data).toLowerCase() !== digest) {
377
+ hostile("the SafeTx digest is not the digest of the calls this client rebuilt");
378
+ }
379
+ return { fundingId, orderId, solver: recovered, safeTxHash: digest, nonce: shape.nonce, quoteExpiresAt,
380
+ orderDeadline: Number(output.deadline), signedMinimumUnits, typedData, activationCostUnits: activation.cost };
381
+ }
382
+ /** The client's OWN typed data: the only thing it ever signs. */
383
+ function rebuildTypedData(data, nonce, safe) {
384
+ return {
385
+ domain: { chainId: ARC_MAINNET_CHAIN_ID, verifyingContract: getAddress(safe) },
386
+ types: {
387
+ EIP712Domain: [{ name: "chainId", type: "uint256" }, { name: "verifyingContract", type: "address" }],
388
+ SafeTx: [
389
+ { name: "to", type: "address" }, { name: "value", type: "uint256" }, { name: "data", type: "bytes" },
390
+ { name: "operation", type: "uint8" }, { name: "safeTxGas", type: "uint256" },
391
+ { name: "baseGas", type: "uint256" }, { name: "gasPrice", type: "uint256" },
392
+ { name: "gasToken", type: "address" }, { name: "refundReceiver", type: "address" },
393
+ { name: "nonce", type: "uint256" },
394
+ ],
395
+ },
396
+ primaryType: "SafeTx",
397
+ message: {
398
+ to: SAFE_MULTISEND_CALL_ONLY, value: "0", data, operation: 1, safeTxGas: "0", baseGas: "0",
399
+ gasPrice: "0", gasToken: "0x0000000000000000000000000000000000000000",
400
+ refundReceiver: "0x0000000000000000000000000000000000000000", nonce: String(nonce),
401
+ },
402
+ };
403
+ }
404
+ /** Every later view: same funding, same Safe, owner and amount. */
405
+ export function assertView(view, plan) {
406
+ if (!isRecord(view))
407
+ hostile("the funding view is not an object");
408
+ const v = view;
409
+ if (v.phase === "source_not_executed") {
410
+ // SAFE_NONCE_INVALIDATION_2026_09_28: the engine's closed_funding_view after
411
+ // an owner invalidation closed this funding. It carries no plan fields, so
412
+ // bind what it does carry: this funding, the HyperCore writer and, once
413
+ // this client journaled one, the exact SafeTx it names.
414
+ const closure = isRecord(v.safe_invalidation_closure) ? v.safe_invalidation_closure : {};
415
+ if (v.id !== plan.fundingId || closure.operation_id !== plan.fundingId || closure.writer !== "hypercore"
416
+ || (plan.safeTxHash !== undefined && String(closure.safe_tx_hash || "").toLowerCase() !== plan.safeTxHash)
417
+ || v.money_moved === true || v.venue_usable === true) {
418
+ hostile("the closure is not for this funding's exact SafeTx");
419
+ }
420
+ return v;
421
+ }
422
+ if (v.id !== plan.fundingId || v.kind !== "arc_hypercore_funding")
423
+ hostile("the server answered for another funding");
424
+ if (lower(v.safe, "safe") !== plan.safe || lower(v.owner, "owner") !== plan.owner
425
+ || lower(v.recipient, "recipient") !== plan.owner) {
426
+ hostile("the funding's Safe or owner changed");
427
+ }
428
+ if (units(v.amount_units, "amount_units") !== plan.amount)
429
+ hostile("the funding amount changed");
430
+ if (v.venue_usable === true && v.phase !== "completed")
431
+ hostile("venue_usable without completion");
432
+ return v;
433
+ }
434
+ function positiveInt(value, field, allowZero = false) {
435
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < (allowZero ? 0 : 1)) {
436
+ hostile(`${field} is not a ${allowZero ? "non-negative" : "positive"} integer`);
437
+ }
438
+ return value;
439
+ }
440
+ /**
441
+ * A completed view, bound to what THIS client journaled: the order it verified
442
+ * and the SafeTx digest it signed. Fields are exactly those the engine's
443
+ * public_view emits (fixtures/hypercore_engine_views.json): source_proof is
444
+ * verify_arc_source's output plus the executed block_hash and safe_tx_hash
445
+ * (it carries no order_id; the order is bound by the top-level order_id and
446
+ * order_binding, and on chain by the engine's RelayErc20Deposit check).
447
+ */
448
+ export function assertCompletion(view, prepared, signed) {
449
+ const credit = view.credit;
450
+ if (view.phase !== "completed" || view.venue_usable !== true || view.money_moved !== true || !isRecord(credit)) {
451
+ hostile("completion carries no credit");
452
+ }
453
+ if (String(view.order_id || "").toLowerCase() !== prepared.order_id
454
+ || String(view.solver || "").toLowerCase() !== prepared.solver) {
455
+ hostile("the completion is for another order");
456
+ }
457
+ const source = view.source_proof;
458
+ if (!isRecord(source))
459
+ hostile("the completion carries no Arc source proof");
460
+ const src = source;
461
+ if (src.state !== "verified" || String(src.safe_tx_hash || "").toLowerCase() !== signed.safe_tx_hash
462
+ || signed.safe_tx_hash !== prepared.safe_tx_hash || !HASH.test(String(src.tx_hash || ""))
463
+ || !HASH.test(String(src.block_hash || "")) || String(src.amount_units) !== prepared.amount_units) {
464
+ hostile("the Arc source proof is not the SafeTx this client signed");
465
+ }
466
+ positiveInt(src.block_number, "source_proof.block_number");
467
+ positiveInt(src.log_index, "source_proof.log_index", true);
468
+ const timings = isRecord(view.timings) ? view.timings : {};
469
+ const sourceMs = positiveInt(timings.source_block_time_ms, "timings.source_block_time_ms");
470
+ const signedMs = Number(signed.signed_at_ms);
471
+ if (!Number.isSafeInteger(signedMs) || sourceMs < signedMs - CLOCK_SKEW_MS) {
472
+ hostile("the Arc source executed before this client signed");
473
+ }
474
+ const binding = view.order_binding;
475
+ if (!isRecord(binding) || binding.state !== "bound" || binding.attribution !== "relay_attested"
476
+ || String(binding.order_id || "").toLowerCase() !== prepared.order_id) {
477
+ hostile("the completion has no Relay order binding for this order");
478
+ }
479
+ // The fee this client signed must be reported paid in the SAME source execution.
480
+ const paidFee = view.network_fee;
481
+ if (!isRecord(paidFee) || paidFee.state !== "paid"
482
+ || String(paidFee.fee_units) !== HYPERCORE_NETWORK_FEE_UNITS.toString()
483
+ || String(paidFee.recipient || "").toLowerCase() !== FELIX_FEE_TREASURY
484
+ || String(paidFee.tx_hash || "").toLowerCase() !== String(src.tx_hash).toLowerCase()
485
+ || String(paidFee.block_hash || "").toLowerCase() !== String(src.block_hash).toLowerCase()) {
486
+ hostile("the network fee is not reported paid in the source execution this client signed");
487
+ }
488
+ const c = credit;
489
+ if (c.state !== "verified" || c.destination_class !== "hypercore_perps" || c.usable_credit_proven !== true) {
490
+ hostile("the credit is not a verified perps credit");
491
+ }
492
+ if (lower(c.solver, "credit.solver") !== prepared.solver)
493
+ hostile("the credit is from another solver");
494
+ if (!HASH.test(String(c.ledger_hash || "")))
495
+ hostile("the credit names no ledger hash");
496
+ const amount = units(c.amount_units, "credit.amount_units");
497
+ if (amount < BigInt(String(prepared.signed_minimum_units)) || amount > BigInt(String(prepared.amount_units))) {
498
+ hostile("the credit is outside the signed bounds");
499
+ }
500
+ positiveInt(c.nonce, "credit.nonce");
501
+ const creditMs = positiveInt(c.ledger_time_ms, "credit.ledger_time_ms");
502
+ if (creditMs < sourceMs || creditMs > sourceMs + CREDIT_LATE_WINDOW_MS) {
503
+ hostile("the credit is outside the window after the Arc source");
504
+ }
505
+ return c;
506
+ }
507
+ function usdToUnits(value) {
508
+ const text = typeof value === "number" ? String(value) : value;
509
+ if (typeof text !== "string")
510
+ return null;
511
+ const match = /^(0|[1-9][0-9]{0,12})(?:\.([0-9]{1,6}))?$/.exec(text);
512
+ return match ? BigInt(match[1]) * 1000000n + BigInt((match[2] || "").padEnd(6, "0")) : null;
513
+ }
514
+ /**
515
+ * This client's own read: exactly one ledger row with the credit's hash, perps
516
+ * to perps, at the credit's time and sendAsset nonce (the value Relay's oracle
517
+ * maps to the order), inside the signing/source window.
518
+ */
519
+ export function ledgerConfirms(rows, credit, owner, window) {
520
+ const matching = rows.filter((row) => isRecord(row) && String(row.hash || "").toLowerCase()
521
+ === String(credit.ledger_hash).toLowerCase());
522
+ if (!matching.length)
523
+ return "none";
524
+ if (matching.length !== 1)
525
+ return "mismatch";
526
+ const delta = matching[0].delta;
527
+ if (!isRecord(delta))
528
+ return "mismatch";
529
+ const d = delta;
530
+ const ok = d.type === "send" && String(d.user || "").toLowerCase() === String(credit.solver).toLowerCase()
531
+ && String(d.destination || "").toLowerCase() === owner && d.sourceDex === "" && d.destinationDex === ""
532
+ && d.token === "USDC" && usdToUnits(d.amount) === BigInt(String(credit.amount_units));
533
+ const time = matching[0].time;
534
+ const timed = time === credit.ledger_time_ms && d.nonce === credit.nonce
535
+ && typeof time === "number" && time >= window.fromMs && time <= window.toMs;
536
+ return ok && timed ? "one" : "mismatch";
537
+ }
538
+ // ------------------------------------------------------------------ driver
539
+ function httpStatus(response) {
540
+ const meta = isRecord(response._meta) ? response._meta : {};
541
+ const status = Number(meta.http_status);
542
+ return Number.isInteger(status) ? status : undefined;
543
+ }
544
+ function errorOf(response) {
545
+ if (isRecord(response.error))
546
+ return response.error;
547
+ const detail = isRecord(response.detail) ? response.detail.error : undefined;
548
+ return isRecord(detail) ? detail : {};
549
+ }
550
+ function definitiveRefusal(response) {
551
+ const status = httpStatus(response);
552
+ return status !== undefined && [400, 401, 403, 404, 409, 422].includes(status);
553
+ }
554
+ /**
555
+ * Read at most ``maxBytes`` of a response body, counting bytes as they stream
556
+ * in; on overflow the stream is cancelled (and the caller's abort fires) before
557
+ * the rest is ever buffered. A missing body reads as empty.
558
+ */
559
+ export async function readCappedText(response, maxBytes, abort) {
560
+ const reader = response.body?.getReader();
561
+ if (!reader)
562
+ return "";
563
+ const chunks = [];
564
+ let total = 0;
565
+ for (;;) {
566
+ const { done, value } = await reader.read();
567
+ if (done)
568
+ break;
569
+ total += value.byteLength;
570
+ if (total > maxBytes) {
571
+ abort?.();
572
+ await reader.cancel().catch(() => undefined);
573
+ throw new Error("response body exceeds its bound");
574
+ }
575
+ chunks.push(value);
576
+ }
577
+ const joined = new Uint8Array(total);
578
+ let offset = 0;
579
+ for (const chunk of chunks) {
580
+ joined.set(chunk, offset);
581
+ offset += chunk.byteLength;
582
+ }
583
+ return new TextDecoder("utf-8", { fatal: true }).decode(joined);
584
+ }
585
+ const ACTIVATION_REFUSALS = new Set([
586
+ "hypercore_account_activation_required", "hypercore_activation_cost_not_accepted",
587
+ "hypercore_activation_cost_unsupported",
588
+ ]);
589
+ export async function driveHypercoreFunding(request, deps) {
590
+ const signedAnything = () => Boolean(deps.getCheckpoint(CP.signed));
591
+ const movement = (view) => {
592
+ if (deps.getCheckpoint(CP.completed))
593
+ return true;
594
+ if (view && view.money_moved === true)
595
+ return true;
596
+ // After a local signature nothing the server SAYS proves "not moved": an
597
+ // unspent Safe nonce keeps the signed SafeTx executable by anyone holding
598
+ // it, and the public view carries no client-verifiable failure proof.
599
+ if (signedAnything())
600
+ return "unknown";
601
+ return false;
602
+ };
603
+ const acceptedActivation = request.accept_activation_cost_units ?? null;
604
+ // HYPERCORE_ACTIVATION_2026_09_28: the owner's acceptance and, once prepared,
605
+ // the cost the plan journals, on every answer of a run that accepted one.
606
+ const activationDisclosure = () => {
607
+ if (acceptedActivation === null)
608
+ return null;
609
+ const prepared = deps.getCheckpoint(CP.prepared);
610
+ const cost = typeof prepared?.activation_cost_units === "string" ? prepared.activation_cost_units : null;
611
+ return { accepted_activation_cost_units: acceptedActivation.toString(),
612
+ accepted_activation_cost_usd: usdText(acceptedActivation),
613
+ activation_cost_units: cost, activation_cost_usd: cost === null ? null : usdText(BigInt(cost)),
614
+ deducted_from: "hypercore_credit", one_time: true, disclosure: HYPERCORE_ACTIVATION_DISCLOSURE };
615
+ };
616
+ const result = (ok, status, fields) => ({
617
+ ok, status, route: "arc_hypercore_direct", account_id: deps.accountId,
618
+ funding_id: deps.getCheckpoint(CP.prepared)?.funding_id ?? null,
619
+ attribution: "relay_attested", venue_usable: false,
620
+ // Disclosed on every answer, including before anything is signed.
621
+ network_fee: { units: HYPERCORE_NETWORK_FEE_UNITS.toString(), recipient: FELIX_FEE_TREASURY,
622
+ refundable: false, disclosure: HYPERCORE_FEE_DISCLOSURE },
623
+ ...(acceptedActivation === null ? {} : { hypercore_activation: activationDisclosure() }),
624
+ ...fields,
625
+ money_moved: fields.money_moved ?? movement(), user_funds_moved: fields.money_moved ?? movement(),
626
+ });
627
+ const refuse = (code, message, extra = {}) => result(false, "refused", { error: { code, message }, money_moved: movement(), ...extra });
628
+ const hold = (code, message, view, extra = {}) => result(false, "reconciliation_required", {
629
+ error: { code, message }, money_moved: movement(view), reconciliation_required: true,
630
+ next_action: "reconcile_do_not_resign", server_reason: view?.reason ?? null, ...extra,
631
+ });
632
+ // SAFE_NONCE_INVALIDATION_2026_09_28 (A3a): the exact call that releases this
633
+ // funding's reserved Safe nonce, never a fresh prepare.
634
+ const release = (reason) => {
635
+ const p = deps.getCheckpoint(CP.prepared);
636
+ return {
637
+ next_action: SAFE_INVALIDATION_TOOL,
638
+ safe_nonce_invalidation: invalidationSuggestion("hypercore", String(p?.funding_id ?? ""), typeof p?.nonce === "number" ? p.nonce : null, reason),
639
+ };
640
+ };
641
+ const sourceProven = (view) => view.money_moved === true || isRecord(view.source_proof)
642
+ // "rejected" is reached only on proof that the exact SafeTx executed (and failed): its nonce is spent.
643
+ || ["completed", "refunded", "source_confirmed", "closed", "source_not_executed", "rejected"].includes(String(view.phase));
644
+ // -------- request and policy: refuse before any request
645
+ const amount = request.amount_units;
646
+ const requestedMinimum = request.minimum_credit_units;
647
+ if (amount < MIN_AMOUNT_UNITS || amount > MAX_AMOUNT_UNITS) {
648
+ return refuse("hypercore_amount_invalid", "amount_units must be 5 to 25 USDC.");
649
+ }
650
+ if (requestedMinimum !== null && (requestedMinimum <= 0n || requestedMinimum > amount)) {
651
+ return refuse("hypercore_minimum_invalid", "minimum_credit_units must be positive and no more than the amount.");
652
+ }
653
+ if (acceptedActivation !== null && (acceptedActivation <= 0n || acceptedActivation > MAX_ACTIVATION_COST_UNITS)) {
654
+ return refuse("hypercore_activation_acceptance_invalid", "accept_activation_cost_usd must be more than 0 and at most 1.5 USDC; nothing was prepared or signed.");
655
+ }
656
+ const accountId = typeof deps.accountId === "string" ? deps.accountId.toLowerCase() : "";
657
+ if (!UUID.test(accountId))
658
+ return refuse("child_account_required", "Select the funding account with use_child_account first.");
659
+ const owner = typeof deps.owner === "string" && ADDRESS.test(deps.owner) ? deps.owner.toLowerCase() : "";
660
+ if (!owner)
661
+ return refuse("client_signature_required", "A local owner key is required.");
662
+ const gaps = policyGaps(deps.policy);
663
+ if (gaps.length) {
664
+ return refuse("hypercore_policy_unverified", "This client has no reviewed evidence for every release gate of the direct HyperCore route; nothing was prepared or signed.", { policy_gaps: gaps, fallback: "arc_home_fund_venue (venue hyperliquid, via Arbitrum)" });
665
+ }
666
+ // HYPERCORE_ACTIVATION_2026_09_28: the engine's definitive activation refusal
667
+ // at prepare (nothing inserted, nothing to sign), surfaced with the exact cost
668
+ // and the exact opt-in re-call. Never accepted on the owner's behalf. This key
669
+ // stays bound to the request as made, so the re-call names a NEW key.
670
+ const activationRefusal = (error) => {
671
+ const code = String(error.reason || error.code || "");
672
+ if (!ACTIVATION_REFUSALS.has(code))
673
+ return null;
674
+ const exact = (value) => {
675
+ const text = typeof value === "number" && Number.isSafeInteger(value) ? String(value) : value;
676
+ return typeof text === "string" && UINT.test(text) ? BigInt(text) : null;
677
+ };
678
+ const cost = exact(error.activation_cost_units);
679
+ const ceiling = exact(error.max_activation_cost_units);
680
+ const expected = exact(error.expected_credit_units);
681
+ const minimum = exact(error.minimum_credit_units);
682
+ const hypercoreActivation = {
683
+ required: true, account_role: "missing",
684
+ activation_cost_units: cost === null ? null : cost.toString(),
685
+ activation_cost_usd: cost === null ? null : usdText(cost),
686
+ max_activation_cost_units: MAX_ACTIVATION_COST_UNITS.toString(),
687
+ accepted_activation_cost_units: acceptedActivation === null ? null : acceptedActivation.toString(),
688
+ expected_credit_units: expected === null ? null : expected.toString(),
689
+ minimum_credit_units: minimum === null ? null : minimum.toString(),
690
+ deducted_from: "hypercore_credit", one_time: true, disclosure: HYPERCORE_ACTIVATION_DISCLOSURE,
691
+ };
692
+ const common = { money_moved: false, user_funds_moved: false, server_error: error,
693
+ hypercore_activation: hypercoreActivation };
694
+ if (code === "hypercore_activation_cost_unsupported" || cost === null || cost <= 0n
695
+ || cost > MAX_ACTIVATION_COST_UNITS || (ceiling !== null && ceiling !== MAX_ACTIVATION_COST_UNITS)
696
+ || (acceptedActivation !== null && cost <= acceptedActivation)) {
697
+ return result(false, "refused", { ...common, next_action: "contact_support",
698
+ error: { code, message: "The owner's HyperCore account needs a one-time activation this client cannot act on: "
699
+ + `its cost is unstated, inconsistent with the acceptance, or above this client's ${usdText(MAX_ACTIVATION_COST_UNITS)} `
700
+ + "USDC ceiling. Nothing was prepared or signed." } });
701
+ }
702
+ const recallArguments = {
703
+ amount_usd: Number(usdText(amount)),
704
+ ...(requestedMinimum === null ? {} : { minimum_credit_usd: Number(usdText(requestedMinimum)) }),
705
+ accept_activation_cost_usd: Number(usdText(cost)),
706
+ idempotency_key: "<a NEW idempotency_key>",
707
+ };
708
+ const credit = expected === null ? "" : ` Expected HyperCore credit after it: about ${usdText(expected)} USDC`
709
+ + (minimum === null ? "." : ` (at least ${usdText(minimum)} USDC).`);
710
+ return result(false, "refused", { ...common, next_action: HYPERCORE_ACTIVATION_NEXT_ACTION,
711
+ recall: { tool: HYPERCORE_TOOL, arguments: recallArguments,
712
+ note: "Only if the owner accepts this one-time cost. Use a NEW idempotency_key: this one stays bound to the "
713
+ + "request without that acceptance. Nothing was prepared or signed under it." },
714
+ error: { code, message: `The owner's HyperCore account does not exist yet. Hyperliquid's one-time account `
715
+ + `activation costs ${usdText(cost)} USDC, deducted from this funding's HyperCore credit (in addition to `
716
+ + `Relay's transfer cost, at most 1%, and Felix's 1.00 USDC network fee).${credit} Nothing was prepared or `
717
+ + `signed. To proceed, the owner must opt in: call ${HYPERCORE_TOOL} again with accept_activation_cost_usd: `
718
+ + `${usdText(cost)} and a NEW idempotency_key.` } });
719
+ };
720
+ // Every Felix call: a thrown transport error is an UNKNOWN outcome, never a
721
+ // client failure; reconcile (idempotent) resolves it.
722
+ const api = async (method, path, body, opts) => {
723
+ try {
724
+ const out = await deps.call(method, path, body, opts);
725
+ return isRecord(out) ? out : { ok: false, error: { code: "invalid_response", outcome_unknown: true } };
726
+ }
727
+ catch (error) {
728
+ return { ok: false, error: { code: "transport_lost", outcome_unknown: true,
729
+ message: String(error?.message || error).slice(0, 200) } };
730
+ }
731
+ };
732
+ const startedAt = deps.now();
733
+ const budget = deps.pollBudgetMs ?? 45_000;
734
+ const maxPolls = deps.maxPolls ?? DEFAULT_MAX_POLLS;
735
+ let delay = MIN_POLL_MS;
736
+ const pause = async () => { await deps.sleep(delay); delay = Math.min(MAX_POLL_MS, delay * 2); };
737
+ try {
738
+ const safe = lower(await deps.expectedSafe(), "verified Arc home Safe");
739
+ // The acceptance is part of the key's scope (only when given, so a journal
740
+ // written before it existed keeps its exact scope): a resume carries the
741
+ // SAME acceptance; any other acceptance on this key refuses before a request.
742
+ const scope = { account_id: accountId, owner, safe, amount_units: amount.toString(),
743
+ minimum_credit_units: requestedMinimum === null ? null : requestedMinimum.toString(),
744
+ ...(acceptedActivation === null ? {} : { accept_activation_cost_units: acceptedActivation.toString() }) };
745
+ const savedScope = deps.getCheckpoint(CP.scope);
746
+ if (savedScope && JSON.stringify(savedScope) !== JSON.stringify(scope)) {
747
+ const savedAcceptance = savedScope.accept_activation_cost_units ?? null;
748
+ if (savedAcceptance !== (scope.accept_activation_cost_units ?? null)) {
749
+ return refuse("hypercore_activation_acceptance_conflict", "This idempotency key was used with a different HyperCore activation acceptance. Resume it with exactly "
750
+ + "the original accept_activation_cost_usd, or start a new funding with a new idempotency_key.", { journaled_accept_activation_cost_units: savedAcceptance });
751
+ }
752
+ return refuse("hypercore_scope_conflict", "This idempotency key belongs to a different account, Safe, owner or amount.");
753
+ }
754
+ if (!savedScope)
755
+ deps.saveCheckpoint(CP.scope, scope);
756
+ const done = deps.getCheckpoint(CP.completed);
757
+ if (done && isRecord(done.result))
758
+ return done.result;
759
+ const abstractionIsDefault = async () => {
760
+ let answer;
761
+ try {
762
+ answer = await deps.hyperliquid.abstraction(owner);
763
+ }
764
+ catch {
765
+ return "hypercore_account_mode_unreadable";
766
+ }
767
+ return answer === "default" ? null : "hypercore_account_mode_unsupported";
768
+ };
769
+ // -------- prepare (idempotent by key), verified before it is saved
770
+ let prepared = deps.getCheckpoint(CP.prepared);
771
+ if (!prepared) {
772
+ const mode = await abstractionIsDefault();
773
+ if (mode)
774
+ return refuse(mode, "The owner's HyperCore account is not in default (perps) mode; nothing was prepared.");
775
+ const response = await api("POST", "/v1/arc-home/hypercore-fundings/prepare", {
776
+ account_id: accountId, amount_units: Number(amount),
777
+ ...(requestedMinimum === null ? {} : { minimum_credit_units: Number(requestedMinimum) }),
778
+ // Engine routes_arc_hypercore.Prepare: StrictInt, 0 < x <= MAX_ACTIVATION_COST_UNITS.
779
+ ...(acceptedActivation === null ? {} : { accept_activation_cost_units: Number(acceptedActivation) }),
780
+ }, { idempotencyKey: deps.stageKey("hcfund-prepare") });
781
+ if (response.ok === false && !definitiveRefusal(response) && !safeNonceRefusalGuidance(response)) {
782
+ // Prepare hands out an unsigned plan at most; the same key replays it.
783
+ return result(false, "in_progress", { money_moved: false, next_action: "resume_with_same_idempotency_key",
784
+ error: { code: "hypercore_prepare_outcome_unknown", message: "Retry with the same key; nothing was signed." } });
785
+ }
786
+ if (response.ok === false || httpStatus(response) !== undefined && httpStatus(response) >= 400) {
787
+ const activationAnswer = activationRefusal(errorOf(response));
788
+ if (activationAnswer)
789
+ return activationAnswer;
790
+ // B5: an in_progress refusal names the account's own open funding; A3a:
791
+ // a reserved-nonce refusal names the invalidation that releases it.
792
+ const open = openJourneyId(response);
793
+ const guidance = open
794
+ ? await describeOpenJourney(api, { id: open, readPath: `/v1/arc-home/hypercore-fundings/${open}`,
795
+ accountId, writer: "hypercore", resumeTool: HYPERCORE_TOOL })
796
+ : safeNonceRefusalGuidance(response) ?? {};
797
+ return refuse(String(errorOf(response).reason || errorOf(response).code || "hypercore_prepare_refused"), "Felix did not prepare the funding; nothing was signed.", { server_error: errorOf(response), ...guidance });
798
+ }
799
+ const plan = await verifyPrepared(response, {
800
+ owner, safe, amount, requestedMinimum, nowS: Math.floor(deps.now() / 1000), policy: deps.policy,
801
+ acceptedActivation,
802
+ });
803
+ prepared = {
804
+ funding_id: plan.fundingId, order_id: plan.orderId, solver: plan.solver, safe_tx_hash: plan.safeTxHash,
805
+ nonce: plan.nonce, quote_expires_at: plan.quoteExpiresAt, order_deadline: plan.orderDeadline,
806
+ amount_units: amount.toString(),
807
+ signed_minimum_units: plan.signedMinimumUnits.toString(), typed_data: plan.typedData,
808
+ // Journaled with the plan (only when accepted, so older journals keep
809
+ // their shape): the signing re-read must disclose the SAME cost.
810
+ ...(acceptedActivation === null ? {} : {
811
+ accepted_activation_cost_units: acceptedActivation.toString(),
812
+ activation_cost_units: plan.activationCostUnits.toString(),
813
+ }),
814
+ };
815
+ deps.saveCheckpoint(CP.prepared, prepared);
816
+ }
817
+ const plan = { fundingId: String(prepared.funding_id), owner, safe, amount, safeTxHash: String(prepared.safe_tx_hash) };
818
+ const base = `/v1/arc-home/hypercore-fundings/${plan.fundingId}`;
819
+ // -------- sign once: fresh server read, fresh gates, then journal the bytes
820
+ if (!deps.getCheckpoint(CP.signed)) {
821
+ const read = await api("GET", `${base}?account_id=${encodeURIComponent(accountId)}`);
822
+ if (read.ok === false) {
823
+ if (definitiveRefusal(read))
824
+ return hold(String(errorOf(read).reason || "hypercore_read_refused"), "Felix would not read the funding.");
825
+ return result(false, "in_progress", { error: { code: "hypercore_read_unavailable", message: "Retry with the same key." } });
826
+ }
827
+ const current = assertView(read, plan);
828
+ if (current.phase !== "prepared") {
829
+ // This client never signed it, but the issued SafeTx could still be signed
830
+ // and sent with the owner key elsewhere, and its Safe nonce stays reserved:
831
+ // never "not moved", never a fresh prepare. Felix observes the exact hash;
832
+ // the owner's no-op invalidation (A3a) releases the nonce and closes it.
833
+ if (current.phase === "source_not_executed") {
834
+ return result(false, "source_not_executed", { money_moved: "unknown", next_action: "none",
835
+ safe_invalidation_closure: current.safe_invalidation_closure ?? null,
836
+ error: { code: "hypercore_closed_by_invalidation",
837
+ message: "This funding was closed after its Safe nonce was invalidated; it is not retried." } });
838
+ }
839
+ return result(false, String(current.phase), {
840
+ money_moved: "unknown", ...(sourceProven(current) ? { next_action: "reconcile" } : release()),
841
+ error: { code: "hypercore_unsigned_funding_advanced",
842
+ message: "Felix stopped offering this funding before this client signed it. It is being "
843
+ + "observed for an execution of the exact issued transaction; do not prepare a new one." },
844
+ });
845
+ }
846
+ if ((prepared.accepted_activation_cost_units ?? null) !== (acceptedActivation?.toString() ?? null)) {
847
+ hostile("the journaled plan was prepared under a different HyperCore activation acceptance");
848
+ }
849
+ const again = await verifyPrepared(current, {
850
+ owner, safe, amount, requestedMinimum, nowS: Math.floor(deps.now() / 1000), policy: deps.policy,
851
+ acceptedActivation,
852
+ });
853
+ if (again.orderId !== prepared.order_id || again.safeTxHash !== prepared.safe_tx_hash || again.nonce !== prepared.nonce) {
854
+ hostile("the server changed the prepared order or SafeTx");
855
+ }
856
+ if (again.activationCostUnits.toString() !== String(prepared.activation_cost_units ?? "0")) {
857
+ hostile("the server changed the prepared HyperCore activation cost");
858
+ }
859
+ if (again.quoteExpiresAt - Math.floor(deps.now() / 1000) < QUOTE_SIGNING_MARGIN_S) {
860
+ return result(false, "in_progress", { error: { code: "hypercore_quote_expiring",
861
+ message: "The quote is too close to expiry to sign. Nothing was signed; it will expire." } });
862
+ }
863
+ const mode = await abstractionIsDefault();
864
+ if (mode)
865
+ return refuse(mode, "The owner's HyperCore account is not in default (perps) mode; nothing was signed.");
866
+ let runtimeOk = false;
867
+ let safeOk = false;
868
+ try {
869
+ runtimeOk = (await deps.policy.verifyDepositoryRuntime()) === true;
870
+ }
871
+ catch {
872
+ runtimeOk = false;
873
+ }
874
+ try {
875
+ safeOk = (await deps.policy.verifySafeState(safe, Number(prepared.nonce))) === true;
876
+ }
877
+ catch {
878
+ safeOk = false;
879
+ }
880
+ if (!runtimeOk)
881
+ return refuse("hypercore_depository_runtime_unverified", "The depository runtime is not proven; nothing was signed.");
882
+ if (!safeOk)
883
+ return refuse("hypercore_safe_state_unverified", "The Safe's nonce/owners are not proven; nothing was signed.");
884
+ // The proofs above are slow reads: re-check the signing window at the last moment.
885
+ const signingS = Math.floor(deps.now() / 1000);
886
+ if (again.quoteExpiresAt - signingS < QUOTE_SIGNING_MARGIN_S
887
+ || again.orderDeadline - signingS < ORDER_DEADLINE_MARGIN_S) {
888
+ return result(false, "in_progress", { error: { code: "hypercore_quote_expiring",
889
+ message: "The quote expired while its proofs were read. Nothing was signed; it will expire." } });
890
+ }
891
+ const signature = await deps.signSafeTx(prepared.typed_data);
892
+ if (!/^0x[0-9a-fA-F]{130}$/.test(signature))
893
+ return refuse("client_signing_failed", "The local signature is malformed; nothing was sent.");
894
+ deps.saveCheckpoint(CP.signed, { funding_id: plan.fundingId, safe_tx_hash: prepared.safe_tx_hash, signature,
895
+ signed_at_ms: deps.now() });
896
+ }
897
+ // -------- submit the SAME bytes at most once per invocation; reconcile resolves the rest
898
+ const signed = deps.getCheckpoint(CP.signed);
899
+ if (signed.funding_id !== plan.fundingId || signed.safe_tx_hash !== prepared.safe_tx_hash) {
900
+ hostile("the journaled signature is for another funding");
901
+ }
902
+ // B2: a definitive submit refusal, surfaced with the step that resolves it.
903
+ // The signature stays journaled; nothing is ever re-signed.
904
+ const submitRefusal = (response) => {
905
+ const error = errorOf(response);
906
+ const code = String(error.reason || error.code || "hypercore_submit_refused");
907
+ const expiresAt = Number(prepared.quote_expires_at);
908
+ const common = { money_moved: movement(), submit_refused: true, server_error: error,
909
+ quote_expires_at: Number.isSafeInteger(expiresAt) ? expiresAt : null };
910
+ if (code === "arc_admission_frozen") {
911
+ return result(false, "submit_refused", { ...common, next_action: "resume_before_quote_expiry",
912
+ safe_nonce_invalidation_if_expired: release().safe_nonce_invalidation,
913
+ error: { code, message: "Felix paused new Arc money movement (for example during a deploy). The signature is "
914
+ + "journaled; resume with the same idempotency_key before quote_expires_at. If the quote expires first, "
915
+ + "invalidate this funding's Safe nonce with invalidate_safe_nonce; never prepare a new funding meanwhile." } });
916
+ }
917
+ if (code === "arc_hypercore_funding_insufficient_balance") {
918
+ return result(false, "submit_refused", { ...common, next_action: "fund_safe_then_resume",
919
+ error: { code, message: "The Arc home Safe does not hold the amount plus the network fee. Add USDC to the "
920
+ + "Safe, then resume with the same idempotency_key before quote_expires_at." } });
921
+ }
922
+ if (code === "arc_hypercore_funding_owner_signature_mismatch") {
923
+ return hold(code, "Felix did not accept this client's signature as the Safe owner's.", undefined, { server_error: error, next_action: "contact_support" });
924
+ }
925
+ if (error.next_action === ENGINE_OBSERVE_NEXT_ACTION || code === "arc_hypercore_funding_expired"
926
+ || code === "arc_hypercore_funding_safe_nonce_changed") {
927
+ return result(false, "submit_refused", { ...common, ...release(),
928
+ error: { code, message: "Felix will not submit this funding (its quote expired, its fee terms changed or "
929
+ + "the Safe nonce moved). It is observed for the exact signed SafeTx; invalidate its Safe nonce to cancel "
930
+ + "it for good. Do not prepare a new funding meanwhile." } });
931
+ }
932
+ return result(false, "submit_refused", { ...common, next_action: "resume_with_same_idempotency_key",
933
+ error: { code, message: "Felix refused the submission now. The signature is journaled; resume with the same "
934
+ + "idempotency_key before quote_expires_at to offer the SAME bytes again." } });
935
+ };
936
+ let offered = false;
937
+ let polls = 0;
938
+ for (;;) {
939
+ if (polls >= maxPolls || deps.now() - startedAt > budget) {
940
+ return result(true, "in_progress", { money_moved: movement(), next_action: "resume_with_same_idempotency_key" });
941
+ }
942
+ polls += 1;
943
+ const current = await api("POST", `${base}/reconcile`, { account_id: accountId }, { retryOnError: true });
944
+ if (current.ok === false) {
945
+ if (httpStatus(current) === 404)
946
+ hostile("the server lost the funding");
947
+ if (definitiveRefusal(current)) {
948
+ return hold(String(errorOf(current).reason || "hypercore_reconcile_refused"), "Felix refused to advance the funding. Nothing more is signed.");
949
+ }
950
+ await pause();
951
+ continue;
952
+ }
953
+ const view = assertView(current, plan);
954
+ const phase = String(view.phase);
955
+ if (phase === "prepared") {
956
+ if (offered) {
957
+ await pause();
958
+ continue;
959
+ }
960
+ offered = true;
961
+ if (!deps.getCheckpoint(CP.submission))
962
+ deps.saveCheckpoint(CP.submission, { funding_id: plan.fundingId });
963
+ // Exactly one transport attempt with the journaled bytes; never re-signed.
964
+ const submitted = await api("POST", `${base}/submit`, { account_id: accountId, safe_signature: signed.signature }, { retryOnError: false });
965
+ // B2 (MCP-SWALLOWS-SUBMIT-REFUSAL): a DEFINITIVE refusal is surfaced now,
966
+ // with the next step; a lost/5xx answer is resolved by reconcile below.
967
+ if (submitted.ok === false && definitiveRefusal(submitted))
968
+ return submitRefusal(submitted);
969
+ continue;
970
+ }
971
+ if (phase === "completed") {
972
+ const credit = assertCompletion(view, prepared, signed);
973
+ const sourceMs = Number(view.timings.source_block_time_ms);
974
+ const window = { fromMs: sourceMs, toMs: Math.min(sourceMs + CREDIT_LATE_WINDOW_MS, deps.now() + CLOCK_SKEW_MS) };
975
+ let rows;
976
+ try {
977
+ // The credit cannot precede the proven Arc source (itself after this client's signature).
978
+ rows = await deps.hyperliquid.ledger(owner, window.fromMs, deps.now());
979
+ }
980
+ catch {
981
+ await pause();
982
+ continue; // no ledger read, no success
983
+ }
984
+ const confirms = ledgerConfirms(rows, credit, owner, window);
985
+ if (confirms === "none") {
986
+ await pause();
987
+ continue;
988
+ }
989
+ if (confirms !== "one") {
990
+ return hold("hypercore_ledger_mismatch", "The HyperCore ledger does not show exactly this perps credit.", view);
991
+ }
992
+ const done = result(true, "completed", {
993
+ money_moved: true, venue_usable: true, credited_units: credit.amount_units,
994
+ ledger_hash: credit.ledger_hash, destination: { venue: "hyperliquid", class: "hypercore_perps", owner },
995
+ attribution: "relay_attested",
996
+ network_fee: { units: HYPERCORE_NETWORK_FEE_UNITS.toString(), recipient: FELIX_FEE_TREASURY,
997
+ state: "paid", tx_hash: String(view.network_fee.tx_hash), refundable: false,
998
+ disclosure: HYPERCORE_FEE_DISCLOSURE },
999
+ attribution_note: "Relay's oracle-written order mapping, checked by Felix, plus this client's own "
1000
+ + "ledger read of exactly one matching perps send. Not a cryptographic proof that the send filled this order.",
1001
+ next_action: "none",
1002
+ });
1003
+ deps.saveCheckpoint(CP.completed, { result: done });
1004
+ return done;
1005
+ }
1006
+ // Server-reported terminal outcomes this client cannot verify locally (no
1007
+ // proof hook yet): reported as the server's claim, never as "did not move",
1008
+ // "fully refunded" or "safe to retry with a new key".
1009
+ if (phase === "refunded") {
1010
+ return hold("hypercore_refund_reported_unverified", "Felix reports that Relay refunded this funding. This client has not verified the refund or that "
1011
+ + "nothing reached HyperCore perps; check both balances. Do not start a new funding until reconciled.", view, { server_phase: "refunded", refund: view.refund ?? view.refunds ?? null, verified: false });
1012
+ }
1013
+ if (phase === "rejected") {
1014
+ let proven = false;
1015
+ if (typeof view.execution_tx === "string" && HASH.test(view.execution_tx)
1016
+ && typeof deps.policy.verifyExecutionFailure === "function") {
1017
+ try {
1018
+ proven = await deps.policy.verifyExecutionFailure({
1019
+ safe, safeTxHash: String(prepared.safe_tx_hash), signedNonce: Number(prepared.nonce),
1020
+ executionTx: view.execution_tx,
1021
+ }) === true;
1022
+ }
1023
+ catch {
1024
+ proven = false;
1025
+ }
1026
+ }
1027
+ if (proven) {
1028
+ // Keep the signed journal. Do not automatically create another funding
1029
+ // or cache a server terminal claim as a successful venue credit.
1030
+ return result(false, "rejected", {
1031
+ money_moved: false, verified: true, reconciliation_required: false,
1032
+ execution_tx: view.execution_tx, next_action: "review_failed_funding",
1033
+ error: { code: "hypercore_safe_execution_failed",
1034
+ message: "Independent Arc reads prove this signed Safe transaction failed, moved no USDC, "
1035
+ + "and consumed its nonce. No replacement funding was created." },
1036
+ network_fee: { units: HYPERCORE_NETWORK_FEE_UNITS.toString(), recipient: FELIX_FEE_TREASURY,
1037
+ state: "not_charged", refundable: false, disclosure: HYPERCORE_FEE_DISCLOSURE },
1038
+ });
1039
+ }
1040
+ return hold("hypercore_rejected_unverified", "Felix reports the Safe execution failed, but this client cannot verify it and holds a signed SafeTx "
1041
+ + "that may still be executable. Do not start a new funding; contact support.", view, { server_phase: "rejected", next_action: "contact_support", verified: false });
1042
+ }
1043
+ if (phase === "expired" || phase === "cancelled") {
1044
+ // A3a: the signed SafeTx may still be executable while its nonce is
1045
+ // unspent; the owner's no-op at that nonce cancels it for good.
1046
+ return result(false, phase, { money_moved: movement(view),
1047
+ ...release("The funding ended unsubmitted while this client holds a signed SafeTx; invalidating its Safe "
1048
+ + "nonce cancels that SafeTx for good and releases the Safe for new Felix operations."),
1049
+ error: { code: `hypercore_${phase}_after_signing`,
1050
+ message: "The funding ended unsubmitted, but this client holds a signed SafeTx whose Safe nonce may be unspent." } });
1051
+ }
1052
+ if (phase === "source_not_executed") {
1053
+ return hold("hypercore_closure_reported_unverified", "Felix reports this funding closed after its Safe nonce was invalidated (the original calls were not "
1054
+ + "committed). This funding's journal does not verify that claim; invalidate_safe_nonce's own result "
1055
+ + "carries this client's proof. Do not start a new funding until reconciled.", view, { server_phase: "source_not_executed", verified: false, next_action: "none" });
1056
+ }
1057
+ if (phase === "reconciliation_required" && !sourceProven(view)
1058
+ && (view.next_action === ENGINE_OBSERVE_NEXT_ACTION || view.reason === "relay_attempts_exhausted")) {
1059
+ return hold("hypercore_reconciliation_required", "Felix will not submit this funding again. Its Safe nonce "
1060
+ + "stays reserved until the owner invalidates it.", view, release());
1061
+ }
1062
+ if (phase === "reconciliation_required" || phase === "closed") {
1063
+ return hold(`hypercore_${phase}`, "Felix needs reconciliation before this funding can continue.", view);
1064
+ }
1065
+ await pause(); // relaying / source_confirmed
1066
+ }
1067
+ }
1068
+ catch (error) {
1069
+ if (error instanceof HypercoreHostileServer) {
1070
+ return hold("hypercore_server_untrusted", error.message);
1071
+ }
1072
+ if (signedAnything())
1073
+ return hold("hypercore_client_failed_after_signing", String(error?.message || error).slice(0, 200));
1074
+ return refuse("hypercore_client_failed", String(error?.message || error).slice(0, 200));
1075
+ }
1076
+ }