felix-mcp 2.0.110 → 2.0.128

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,859 @@
1
+ // PM_ARC_RETURN_CLIENT_2026_09_23: the local driver for the composed
2
+ // Polymarket -> Arc home Safe return (/v1/arc-home/pm-returns, whose child is a
3
+ // /v1/arc-home/relay-returns journey). The server journals, relays and proves;
4
+ // this client only signs, locally, what it has independently checked, and never
5
+ // tells the user money did not move once it has signed anything.
6
+ //
7
+ // Every effect is injected (API, owner-local signers, the encrypted workflow
8
+ // journal, clock, sleep) so the state machine is exercised offline against
9
+ // honest, lossy and hostile servers (test_pm_arc_return_driver.mjs).
10
+ //
11
+ // Launch: PM_ARC_RETURN_CLIENT_ENABLED is false. The server gate
12
+ // (PM_COMPOSED_RETURN_ENABLED) is also closed; either one keeps this route off.
13
+ import { redactOutput } from "./redact-output.js";
14
+ import { createHash } from "node:crypto";
15
+ import { decodeFunctionData, encodeFunctionData, getAddress, hashStruct, keccak256, parseAbi, recoverMessageAddress, } from "viem";
16
+ export const PM_ARC_RETURN_CLIENT_ENABLED = false;
17
+ // Pinned: the only contracts a Polymarket -> Arc return may touch.
18
+ export const POLYGON_CHAIN_ID = 137;
19
+ export const ARC_CHAIN_ID = 5042;
20
+ export const PUSD = "0xc011a7e12a19f7b1f670d46f03b03f3342e82dfb";
21
+ export const OFFRAMP = "0x2957922eb93258b93368531d39facca3b4dc5854";
22
+ export const USDC_E = "0x2791bca1f2de4661ed88a30c99a7a9449aa84174";
23
+ export const RELAY_DEPOSITORY = "0x4cd00e387622c35bddb9b4c962c136462338bc31";
24
+ export const ARC_USDC = "0x3600000000000000000000000000000000000000";
25
+ // Bounds the client enforces on its own, whatever the server says.
26
+ export const MAX_RELAY_GAS = 750000n;
27
+ export const MAX_FEE_PER_GAS_WEI = 1000000000000n;
28
+ export const MAX_ALL_IN_COST_BPS = 100n;
29
+ export const MIN_AMOUNT_UNITS = 5000000n;
30
+ export const MAX_AMOUNT_UNITS = 2000000000n;
31
+ export const MAX_RELAY_ATTEMPTS = 4;
32
+ // Relay solvers this client accepts a signed order from. Pinned in the client
33
+ // on purpose: a server cannot add to it. Changing it is a reviewed release.
34
+ export const RELAY_TRUSTED_SOLVERS = [
35
+ "0xf70da97812cb96acdf810712aa562db8dfa3dbef",
36
+ ];
37
+ const ORDER_DEADLINE_MARGIN_S = 60;
38
+ // Relay's v1 order schema (Felix: retail_relay_funding_adapter._RELAY_ORDER_TYPES).
39
+ // The order id is the EIP-712 struct hash of the order, with no domain.
40
+ export const RELAY_ORDER_TYPES = {
41
+ Order: [
42
+ { name: "version", type: "string" }, { name: "solverChainId", type: "string" },
43
+ { name: "solver", type: "address" }, { name: "salt", type: "uint256" },
44
+ { name: "inputs", type: "Input[]" }, { name: "output", type: "Output" }, { name: "fees", type: "Fee[]" },
45
+ ],
46
+ Input: [{ name: "payment", type: "InputPayment" }, { name: "refunds", type: "InputRefund[]" }],
47
+ InputPayment: [
48
+ { name: "chainId", type: "string" }, { name: "currency", type: "bytes" },
49
+ { name: "amount", type: "uint256" }, { name: "weight", type: "uint256" },
50
+ ],
51
+ InputRefund: [
52
+ { name: "chainId", type: "string" }, { name: "recipient", type: "bytes" },
53
+ { name: "currency", type: "bytes" }, { name: "minimumAmount", type: "uint256" },
54
+ { name: "deadline", type: "uint32" }, { name: "extraData", type: "bytes" },
55
+ ],
56
+ Output: [
57
+ { name: "chainId", type: "string" }, { name: "payments", type: "OutputPayment[]" },
58
+ { name: "deadline", type: "uint32" }, { name: "calls", type: "bytes[]" }, { name: "extraData", type: "bytes" },
59
+ ],
60
+ OutputPayment: [
61
+ { name: "recipient", type: "bytes" }, { name: "currency", type: "bytes" },
62
+ { name: "minimumAmount", type: "uint256" }, { name: "expectedAmount", type: "uint256" },
63
+ ],
64
+ Fee: [
65
+ { name: "recipientChainId", type: "string" }, { name: "recipient", type: "bytes" },
66
+ { name: "currencyChainId", type: "string" }, { name: "currency", type: "bytes" },
67
+ { name: "amount", type: "uint256" },
68
+ ],
69
+ };
70
+ const BATCH_SIGNING_MARGIN_S = 120;
71
+ const QUOTE_SIGNING_MARGIN_S = 45;
72
+ const DEFAULT_POLL_BUDGET_MS = 10 * 60_000;
73
+ const DEFAULT_MAX_POLLS = 120;
74
+ const MIN_POLL_MS = 2_000;
75
+ const MAX_POLL_MS = 30_000;
76
+ const PHASES = new Set([
77
+ "venue_prepared", "venue_submitted", "venue_confirmed", "relay_open",
78
+ "reconciliation_required", "completed", "expired", "refunded", "closed",
79
+ ]);
80
+ const CHILD_PHASES = new Set([
81
+ "prepared", "source_submitted", "source_confirmed", "reconciliation_required",
82
+ "completed", "expired", "source_reverted", "source_dropped", "refunded", "closed",
83
+ ]);
84
+ const CHILD_NO_MOVE = new Set(["expired", "source_reverted", "source_dropped"]);
85
+ // A journey may only move forward. A server that walks one back is not trusted.
86
+ const PHASE_RANK = {
87
+ venue_prepared: 0, venue_submitted: 1, reconciliation_required: 1, venue_confirmed: 2,
88
+ relay_open: 3, completed: 4, expired: 4, refunded: 4, closed: 4,
89
+ };
90
+ const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
91
+ const TX_HASH = /^0x[0-9a-fA-F]{64}$/;
92
+ const UINT = /^(0|[1-9][0-9]{0,30})$/;
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 ABI = parseAbi([
95
+ "function approve(address spender, uint256 amount) returns (bool)",
96
+ "function unwrap(address token, address recipient, uint256 amount)",
97
+ "function depositErc20(address depositor, address token, uint256 amount, bytes32 id)",
98
+ ]);
99
+ export class PmArcReturnHostileServer extends Error {
100
+ constructor(message) {
101
+ super(message);
102
+ this.name = "PmArcReturnHostileServer";
103
+ }
104
+ }
105
+ function isRecord(value) {
106
+ return typeof value === "object" && value !== null && !Array.isArray(value);
107
+ }
108
+ function hostile(message) {
109
+ throw new PmArcReturnHostileServer(message);
110
+ }
111
+ function lower(value, name) {
112
+ if (typeof value !== "string" || !ADDRESS.test(value))
113
+ hostile(`${name} is not an address`);
114
+ return value.toLowerCase();
115
+ }
116
+ function units(value, name) {
117
+ if (typeof value !== "string" || !UINT.test(value))
118
+ hostile(`${name} is not exact integer units`);
119
+ return BigInt(value);
120
+ }
121
+ function digest(value) {
122
+ return createHash("sha256").update(JSON.stringify(value)).digest("hex");
123
+ }
124
+ // ------------------------------------------------------------------ checks
125
+ export function assertVenueBatch(batch, owner, amount) {
126
+ if (!isRecord(batch))
127
+ hostile("venue_batch is missing");
128
+ if (batch.chain_id !== POLYGON_CHAIN_ID || batch.signature_scheme !== "eip712"
129
+ || batch.primary_type !== "Batch")
130
+ hostile("venue_batch is not a Polygon EIP-712 Batch");
131
+ if (lower(batch.owner, "venue_batch.owner") !== owner)
132
+ hostile("venue_batch is not for the local owner");
133
+ lower(batch.wallet, "venue_batch.wallet");
134
+ units(batch.nonce, "venue_batch.nonce");
135
+ units(batch.deadline, "venue_batch.deadline");
136
+ const calls = batch.calls;
137
+ if (!Array.isArray(calls) || calls.length !== 2 || !calls.every(isRecord)) {
138
+ hostile("venue_batch must be exactly approve then unwrap");
139
+ }
140
+ const [approve, unwrap] = calls;
141
+ const expectedApprove = encodeFunctionData({ abi: ABI, functionName: "approve", args: [getAddress(OFFRAMP), amount] });
142
+ const expectedUnwrap = encodeFunctionData({
143
+ abi: ABI, functionName: "unwrap", args: [getAddress(USDC_E), getAddress(owner), amount],
144
+ });
145
+ if (lower(approve.target, "approve.target") !== PUSD || String(approve.value) !== "0"
146
+ || String(approve.data).toLowerCase() !== expectedApprove.toLowerCase()) {
147
+ hostile("venue_batch approve is not exactly pUSD.approve(OFFRAMP, amount)");
148
+ }
149
+ if (lower(unwrap.target, "unwrap.target") !== OFFRAMP || String(unwrap.value) !== "0"
150
+ || String(unwrap.data).toLowerCase() !== expectedUnwrap.toLowerCase()) {
151
+ hostile("venue_batch unwrap does not pay exactly the amount to the local owner");
152
+ }
153
+ return batch;
154
+ }
155
+ export function assertRelayChild(child, journey) {
156
+ if (!isRecord(child))
157
+ hostile("relay_return is missing");
158
+ if (typeof child.id !== "string" || !UUID.test(child.id))
159
+ hostile("relay_return.id is invalid");
160
+ if (!CHILD_PHASES.has(String(child.phase)))
161
+ hostile("relay_return.phase is unknown");
162
+ if (child.kind !== undefined && child.kind !== "arc_relay_return")
163
+ hostile("relay_return.kind is wrong");
164
+ if (lower(child.owner, "relay_return.owner") !== journey.owner)
165
+ hostile("relay_return owner changed");
166
+ if (lower(child.recipient, "relay_return.recipient") !== journey.recipient) {
167
+ hostile("relay_return pays a different recipient than the journey's Arc home Safe");
168
+ }
169
+ if (units(child.amount_units, "relay_return.amount_units") !== journey.amount) {
170
+ hostile("relay_return moves a different amount than the proven withdrawal");
171
+ }
172
+ if (child.source !== undefined && child.source !== "prediction_market")
173
+ hostile("relay_return source is wrong");
174
+ if (isRecord(child.provenance) && child.provenance.journey_id !== journey.id) {
175
+ hostile("relay_return provenance names another journey");
176
+ }
177
+ if (child.destination_chain_id !== undefined && child.destination_chain_id !== ARC_CHAIN_ID) {
178
+ hostile("relay_return destination is not Arc");
179
+ }
180
+ if (child.destination_token !== undefined && lower(child.destination_token, "destination_token") !== ARC_USDC) {
181
+ hostile("relay_return destination token is not Arc USDC");
182
+ }
183
+ const minimum = units(child.minimum_credit_units, "relay_return.minimum_credit_units");
184
+ const floor = (journey.amount * (10000n - MAX_ALL_IN_COST_BPS) + 9999n) / 10000n;
185
+ if (minimum < floor || minimum > journey.amount) {
186
+ hostile("relay_return minimum credit is below the client's 1% floor");
187
+ }
188
+ if (child.home_usable === true && child.phase !== "completed")
189
+ hostile("relay_return claims home_usable early");
190
+ return child;
191
+ }
192
+ function transaction(value, owner, name) {
193
+ if (!isRecord(value))
194
+ hostile(`${name} is missing`);
195
+ if (lower(value.from, `${name}.from`) !== owner)
196
+ hostile(`${name} is not from the local owner`);
197
+ if (value.chain_id !== POLYGON_CHAIN_ID)
198
+ hostile(`${name} is not on Polygon`);
199
+ if (String(value.value) !== "0")
200
+ hostile(`${name} moves native value`);
201
+ const gas = units(value.gas_limit, `${name}.gas_limit`);
202
+ const maxFee = units(value.max_fee_per_gas, `${name}.max_fee_per_gas`);
203
+ const priority = units(value.max_priority_fee_per_gas, `${name}.max_priority_fee_per_gas`);
204
+ if (gas <= 0n || gas > MAX_RELAY_GAS)
205
+ hostile(`${name} gas is outside the client bound`);
206
+ if (maxFee <= 0n || maxFee > MAX_FEE_PER_GAS_WEI || priority <= 0n || priority > maxFee) {
207
+ hostile(`${name} fees are outside the client bound`);
208
+ }
209
+ if (typeof value.data !== "string" || !/^0x[0-9a-fA-F]+$/.test(value.data) || value.data.length > 4_096) {
210
+ hostile(`${name} calldata is malformed`);
211
+ }
212
+ return {
213
+ chainId: POLYGON_CHAIN_ID, to: getAddress(lower(value.to, `${name}.to`)),
214
+ data: value.data.toLowerCase(), value: 0n, gas, maxFeePerGas: maxFee,
215
+ maxPriorityFeePerGas: priority,
216
+ };
217
+ }
218
+ export function assertRelayPair(child, owner, amount) {
219
+ const steps = child.transactions;
220
+ if (!Array.isArray(steps) || steps.length !== 2 || !steps.every(isRecord)
221
+ || steps[0].step !== "approve" || steps[1].step !== "deposit") {
222
+ hostile("relay_return must hand out exactly approve then deposit");
223
+ }
224
+ const approve = transaction(steps[0], owner, "approve");
225
+ const deposit = transaction(steps[1], owner, "deposit");
226
+ const expectedApprove = encodeFunctionData({
227
+ abi: ABI, functionName: "approve", args: [getAddress(RELAY_DEPOSITORY), amount],
228
+ });
229
+ if (approve.to.toLowerCase() !== USDC_E || approve.data !== expectedApprove.toLowerCase()) {
230
+ hostile("approve is not exactly USDC.e.approve(Relay depository, amount)");
231
+ }
232
+ if (deposit.to.toLowerCase() !== RELAY_DEPOSITORY)
233
+ hostile("deposit is not sent to the pinned Relay depository");
234
+ let decoded;
235
+ try {
236
+ decoded = decodeFunctionData({ abi: ABI, data: deposit.data });
237
+ }
238
+ catch {
239
+ hostile("deposit calldata does not decode");
240
+ }
241
+ if (decoded.functionName !== "depositErc20")
242
+ hostile("deposit is not depositErc20");
243
+ const [depositor, token, deposited, orderId] = decoded.args;
244
+ const reencoded = encodeFunctionData({
245
+ abi: ABI, functionName: "depositErc20", args: [getAddress(depositor), getAddress(token), deposited, orderId],
246
+ });
247
+ if (depositor.toLowerCase() !== owner || token.toLowerCase() !== USDC_E || deposited !== amount
248
+ || reencoded.toLowerCase() !== deposit.data) {
249
+ hostile("deposit is not exactly depositErc20(owner, USDC.e, amount, order)");
250
+ }
251
+ const expires = Number(child.quote_expires_at);
252
+ if (!Number.isSafeInteger(expires) || expires <= 0)
253
+ hostile("relay_return quote expiry is invalid");
254
+ const signing = child.signing;
255
+ if (!isRecord(signing) || signing.chain_id !== POLYGON_CHAIN_ID
256
+ || !Number.isSafeInteger(signing.owner_nonce) || signing.owner_nonce < 0
257
+ || signing.owner_nonce >= 2 ** 32 - 1) {
258
+ hostile("relay_return carries no usable owner nonce to sign with");
259
+ }
260
+ const nonce = signing.owner_nonce;
261
+ return {
262
+ approve: { ...approve, nonce }, deposit: { ...deposit, nonce: nonce + 1 }, quoteExpiresAt: expires,
263
+ orderId: orderId.toLowerCase(),
264
+ };
265
+ }
266
+ function exactKeys(value, keys, name) {
267
+ if (!isRecord(value) || Object.keys(value).length !== keys.length || !keys.every((key) => key in value)) {
268
+ hostile(`${name} does not have exactly the Relay v1 order fields`);
269
+ }
270
+ return value;
271
+ }
272
+ function hexBytes(value, name) {
273
+ if (typeof value !== "string" || !/^0x([0-9a-fA-F]{2})*$/.test(value))
274
+ hostile(`${name} is not hex bytes`);
275
+ return value.toLowerCase();
276
+ }
277
+ const UINT256_MAX = (1n << 256n) - 1n;
278
+ const SALT_DECIMAL = /^(0|[1-9][0-9]{0,77})$/;
279
+ const SALT_HEX = /^0x[0-9a-fA-F]{1,64}$/;
280
+ /**
281
+ * RELAY_ORDER_SALT_2026_09_26: the order's `salt` is a full-width uint256 and
282
+ * real Relay orders carry it as 0x hex (32 bytes); the monetary `units` reader
283
+ * is deliberately bounded far below that and stays unchanged. Accept exactly a
284
+ * canonical decimal (no sign, fraction, whitespace or leading zeros) or 0x hex
285
+ * of at most 32 bytes, as a string, or a safe non-negative JS integer; reject
286
+ * anything above 2^256-1.
287
+ */
288
+ export function orderSalt(value, name = "order.salt") {
289
+ if (typeof value === "number") {
290
+ if (Number.isSafeInteger(value) && value >= 0)
291
+ return BigInt(value);
292
+ hostile(`${name} is not a safe integer`);
293
+ }
294
+ if (typeof value !== "string" || value.length > 78 || !(SALT_DECIMAL.test(value) || SALT_HEX.test(value))) {
295
+ hostile(`${name} is not a uint256`);
296
+ }
297
+ const salt = BigInt(value);
298
+ if (salt > UINT256_MAX)
299
+ hostile(`${name} overflows uint256`);
300
+ return salt;
301
+ }
302
+ function orderUint(value, name) {
303
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0)
304
+ return BigInt(value);
305
+ return units(value, name);
306
+ }
307
+ function text(value, name) {
308
+ if (typeof value !== "string" || value.length === 0 || value.length > 64)
309
+ hostile(`${name} is not a short string`);
310
+ return value;
311
+ }
312
+ /** The order as typed EIP-712 data, every field present, every type exact. */
313
+ export function relayOrderMessage(order) {
314
+ const o = exactKeys(order, ["version", "solverChainId", "solver", "salt", "inputs", "output", "fees"], "order");
315
+ if (!Array.isArray(o.inputs) || o.inputs.length !== 1)
316
+ hostile("order must have exactly one input");
317
+ const input = exactKeys(o.inputs[0], ["payment", "refunds"], "order.inputs[0]");
318
+ const payment = exactKeys(input.payment, ["chainId", "currency", "amount", "weight"], "order input payment");
319
+ if (!Array.isArray(input.refunds) || input.refunds.length !== 2)
320
+ hostile("order must have exactly two refunds");
321
+ const output = exactKeys(o.output, ["chainId", "payments", "deadline", "calls", "extraData"], "order.output");
322
+ if (!Array.isArray(output.payments) || output.payments.length !== 1)
323
+ hostile("order must pay exactly one output");
324
+ if (!Array.isArray(output.calls) || !Array.isArray(o.fees))
325
+ hostile("order calls and fees must be lists");
326
+ return {
327
+ version: text(o.version, "order.version"),
328
+ solverChainId: text(o.solverChainId, "order.solverChainId"),
329
+ solver: getAddress(lower(o.solver, "order.solver")),
330
+ salt: orderSalt(o.salt, "order.salt"),
331
+ inputs: [{
332
+ payment: {
333
+ chainId: text(payment.chainId, "payment.chainId"), currency: hexBytes(payment.currency, "payment.currency"),
334
+ amount: orderUint(payment.amount, "payment.amount"), weight: orderUint(payment.weight, "payment.weight"),
335
+ },
336
+ refunds: input.refunds.map((refund, index) => {
337
+ const r = exactKeys(refund, ["chainId", "recipient", "currency", "minimumAmount", "deadline", "extraData"], `order refund ${index}`);
338
+ return {
339
+ chainId: text(r.chainId, "refund.chainId"), recipient: hexBytes(r.recipient, "refund.recipient"),
340
+ currency: hexBytes(r.currency, "refund.currency"), minimumAmount: orderUint(r.minimumAmount, "refund.minimumAmount"),
341
+ deadline: Number(orderUint(r.deadline, "refund.deadline")), extraData: hexBytes(r.extraData, "refund.extraData"),
342
+ };
343
+ }),
344
+ }],
345
+ output: {
346
+ chainId: text(output.chainId, "output.chainId"),
347
+ payments: output.payments.map((item) => {
348
+ const p = exactKeys(item, ["recipient", "currency", "minimumAmount", "expectedAmount"], "order output payment");
349
+ return {
350
+ recipient: hexBytes(p.recipient, "payment.recipient"), currency: hexBytes(p.currency, "payment.currency"),
351
+ minimumAmount: orderUint(p.minimumAmount, "payment.minimumAmount"),
352
+ expectedAmount: orderUint(p.expectedAmount, "payment.expectedAmount"),
353
+ };
354
+ }),
355
+ deadline: Number(orderUint(output.deadline, "output.deadline")),
356
+ calls: output.calls.map((call, index) => hexBytes(call, `output.calls[${index}]`)),
357
+ extraData: hexBytes(output.extraData, "output.extraData"),
358
+ },
359
+ fees: o.fees.map((fee, index) => {
360
+ const f = exactKeys(fee, ["recipientChainId", "recipient", "currencyChainId", "currency", "amount"], `order fee ${index}`);
361
+ return {
362
+ recipientChainId: text(f.recipientChainId, "fee.recipientChainId"), recipient: hexBytes(f.recipient, "fee.recipient"),
363
+ currencyChainId: text(f.currencyChainId, "fee.currencyChainId"), currency: hexBytes(f.currency, "fee.currency"),
364
+ amount: orderUint(f.amount, "fee.amount"),
365
+ };
366
+ }),
367
+ };
368
+ }
369
+ /**
370
+ * Bind the Arc credit to the Safe before any Relay source signature.
371
+ *
372
+ * Recompute the order's EIP-712 id and require it to equal both the order id
373
+ * Felix names and the one the deposit calldata commits to. Recover the solver
374
+ * from its signature and require it in the client's pinned set. Then require
375
+ * the order itself to:
376
+ * - pay exactly one output on Arc, in Arc USDC, to the journey's Safe, at a
377
+ * signed minimum no lower than the client's 1% floor;
378
+ * - take exactly the amount in Polygon USDC.e;
379
+ * - refund only the owner, on both chains;
380
+ * - carry no fees and no calls, with a live deadline.
381
+ */
382
+ export async function assertRelayOrder(child, journey, depositOrderId, trustedSolvers, nowS) {
383
+ const relay = exactKeys(child.relay_order, ["order_id", "solver", "order_data", "order_signature"], "relay_order");
384
+ const orderId = hexBytes(relay.order_id, "relay_order.order_id");
385
+ if (!TX_HASH.test(orderId))
386
+ hostile("relay_order.order_id is not 32 bytes");
387
+ const signature = hexBytes(relay.order_signature, "relay_order.order_signature");
388
+ if (signature.length !== 132)
389
+ hostile("relay_order.order_signature is not 65 bytes");
390
+ const message = relayOrderMessage(relay.order_data);
391
+ let recomputed;
392
+ try {
393
+ recomputed = hashStruct({ types: RELAY_ORDER_TYPES, primaryType: "Order", data: message }).toLowerCase();
394
+ }
395
+ catch {
396
+ hostile("relay_order does not hash as a Relay v1 order");
397
+ }
398
+ if (recomputed !== orderId || depositOrderId !== orderId) {
399
+ hostile("the signed order is not the order the deposit commits to");
400
+ }
401
+ let recovered;
402
+ try {
403
+ recovered = (await recoverMessageAddress({ message: { raw: orderId }, signature })).toLowerCase();
404
+ }
405
+ catch {
406
+ hostile("the order signature does not recover");
407
+ }
408
+ const trusted = new Set(trustedSolvers.map((solver) => solver.toLowerCase()));
409
+ if (recovered !== message.solver.toLowerCase() || recovered !== lower(relay.solver, "relay_order.solver")
410
+ || !trusted.has(recovered)) {
411
+ hostile("the order is not signed by a Relay solver this client trusts");
412
+ }
413
+ if (message.version !== "v1" || message.solverChainId !== "base")
414
+ hostile("the order is not a Relay v1 order");
415
+ const payment = message.inputs[0].payment;
416
+ if (payment.chainId !== "polygon" || payment.currency !== USDC_E || payment.amount !== journey.amount
417
+ || payment.weight !== 1n) {
418
+ hostile("the order does not take exactly the amount in Polygon USDC.e");
419
+ }
420
+ const output = message.output;
421
+ const paid = output.payments[0];
422
+ const floor = (journey.amount * (10000n - MAX_ALL_IN_COST_BPS) + 9999n) / 10000n;
423
+ if (output.chainId !== "arc" || paid.recipient !== journey.recipient || paid.currency !== ARC_USDC) {
424
+ hostile("the signed order does not pay the journey's Arc home Safe in Arc USDC");
425
+ }
426
+ if (paid.minimumAmount < floor || paid.minimumAmount > paid.expectedAmount || paid.expectedAmount > journey.amount) {
427
+ hostile("the signed order's minimum is below the client's 1% floor");
428
+ }
429
+ if (output.calls.length !== 0 || output.extraData !== "0x" || message.fees.length !== 0) {
430
+ hostile("the signed order carries calls, extra data or fees");
431
+ }
432
+ if (output.deadline < nowS + ORDER_DEADLINE_MARGIN_S)
433
+ hostile("the signed order is expired or about to");
434
+ const refunds = new Set(message.inputs[0].refunds.map((refund) => {
435
+ if (refund.minimumAmount !== 0n || refund.deadline !== output.deadline || refund.extraData !== "0x") {
436
+ hostile("an order refund is not the plain owner refund");
437
+ }
438
+ return `${refund.chainId}|${refund.recipient}|${refund.currency}`;
439
+ }));
440
+ if (refunds.size !== 2 || !refunds.has(`polygon|${journey.owner}|${USDC_E}`)
441
+ || !refunds.has(`arc|${journey.owner}|${ARC_USDC}`)) {
442
+ hostile("the order refunds someone other than the owner");
443
+ }
444
+ return { orderId, solver: recovered, signedMinimum: paid.minimumAmount, deadline: output.deadline };
445
+ }
446
+ export function assertJourney(view, expected) {
447
+ if (!isRecord(view))
448
+ hostile("the journey view is not an object");
449
+ if (view.ok === false)
450
+ hostile("the journey view is an error");
451
+ if (typeof view.id !== "string" || !UUID.test(view.id))
452
+ hostile("journey id is invalid");
453
+ if (expected.id && view.id !== expected.id)
454
+ hostile("the server answered for a different journey");
455
+ if (view.kind !== "arc_pm_relay_return")
456
+ hostile("journey kind is wrong");
457
+ if (!PHASES.has(String(view.phase)))
458
+ hostile("journey phase is unknown");
459
+ if (lower(view.owner, "journey.owner") !== expected.owner)
460
+ hostile("journey owner is not the local owner");
461
+ if (units(view.amount_units, "journey.amount_units") !== expected.amount)
462
+ hostile("journey amount changed");
463
+ const recipient = lower(view.recipient, "journey.recipient");
464
+ if (expected.recipient && recipient !== expected.recipient)
465
+ hostile("journey recipient (Arc home Safe) changed");
466
+ if (view.destination_chain_id !== ARC_CHAIN_ID || lower(view.destination_token, "destination_token") !== ARC_USDC) {
467
+ hostile("journey destination is not Arc USDC");
468
+ }
469
+ if (view.home_usable === true && view.phase !== "completed")
470
+ hostile("journey claims home_usable early");
471
+ if (view.phase === "completed" && view.money_moved === false)
472
+ hostile("a completed journey cannot have moved nothing");
473
+ return view;
474
+ }
475
+ function blockNumber(value, name, allowZero = false) {
476
+ if (!Number.isSafeInteger(value) || value < (allowZero ? 0 : 1)) {
477
+ hostile(`${name} is not a valid block or log index`);
478
+ }
479
+ return value;
480
+ }
481
+ /** Bind the server's finalized credit evidence to the locally signed Relay leg. */
482
+ export function assertCompletion(view, journey, submission) {
483
+ if (!isRecord(submission) || submission.journey_id !== journey.id
484
+ || typeof submission.child_id !== "string" || !UUID.test(submission.child_id)
485
+ || typeof submission.order_id !== "string" || !TX_HASH.test(submission.order_id)
486
+ || typeof submission.deposit_hash !== "string" || !TX_HASH.test(submission.deposit_hash)) {
487
+ hostile("completion has no matching journaled Relay submission");
488
+ }
489
+ const orderId = submission.order_id.toLowerCase();
490
+ const depositHash = submission.deposit_hash.toLowerCase();
491
+ const solver = lower(submission.solver, "journaled solver");
492
+ const signedMinimum = units(submission.signed_minimum_units, "journaled signed minimum");
493
+ const child = assertRelayChild(view.relay_return, journey);
494
+ if (child.kind !== "arc_relay_return" || child.source !== "prediction_market"
495
+ || !isRecord(child.provenance) || child.provenance.journey_id !== journey.id
496
+ || child.destination_chain_id !== ARC_CHAIN_ID || lower(child.destination_token, "relay_return.destination_token") !== ARC_USDC
497
+ || view.relay_return_id !== submission.child_id || child.id !== submission.child_id
498
+ || typeof child.order_id !== "string" || child.order_id.toLowerCase() !== orderId
499
+ || lower(child.solver, "relay_return.solver") !== solver
500
+ || typeof child.deposit_hash !== "string" || child.deposit_hash.toLowerCase() !== depositHash) {
501
+ hostile("completed Relay child is not the journaled signed order and deposit");
502
+ }
503
+ const source = child.source_proof;
504
+ if (!isRecord(source) || source.state !== "verified" || source.tx_hash !== depositHash
505
+ || units(source.amount_units, "source_proof.amount_units") !== journey.amount) {
506
+ hostile("completion has no matching proven Relay source deposit");
507
+ }
508
+ blockNumber(source.block_number, "source_proof.block_number");
509
+ const credit = child.credit;
510
+ if (view.home_usable !== true || child.phase !== "completed" || child.home_usable !== true
511
+ || !isRecord(credit) || credit.state !== "credited"
512
+ || typeof credit.tx_hash !== "string" || !TX_HASH.test(credit.tx_hash)
513
+ || typeof credit.order_id !== "string" || credit.order_id.toLowerCase() !== orderId
514
+ || typeof credit.source_tx_hash !== "string" || credit.source_tx_hash.toLowerCase() !== depositHash
515
+ || lower(credit.recipient, "credit.recipient") !== journey.recipient
516
+ || lower(credit.token, "credit.token") !== ARC_USDC) {
517
+ hostile("completion without a finalized Arc credit");
518
+ }
519
+ const creditBlock = blockNumber(credit.block_number, "credit.block_number");
520
+ if (blockNumber(credit.finalized_block_number, "credit.finalized_block_number") < creditBlock) {
521
+ hostile("Arc credit is not finalized");
522
+ }
523
+ blockNumber(credit.log_index, "credit.log_index", true);
524
+ const credited = units(credit.amount_units, "credit.amount_units");
525
+ const served = units(child.minimum_credit_units, "relay_return.minimum_credit_units");
526
+ // The credit must meet what the solver SIGNED, whatever minimum Felix reports.
527
+ const minimum = served > signedMinimum ? served : signedMinimum;
528
+ if (credited < minimum || credited > journey.amount)
529
+ hostile("the Arc credit is outside the signed bounds");
530
+ return { credit, credited, minimum };
531
+ }
532
+ function result(ok, fields) {
533
+ const moved = fields.money_moved;
534
+ return {
535
+ ok,
536
+ ...fields,
537
+ user_funds_moved: moved,
538
+ home_usable: fields.home_usable === true,
539
+ reconciliation_required: fields.reconciliation_required === true,
540
+ };
541
+ }
542
+ function failure(code, message, fields) {
543
+ return result(false, { error: { code, message }, ...fields });
544
+ }
545
+ // ------------------------------------------------------------------ driver
546
+ const CK = {
547
+ journey: "pm-arc:journey",
548
+ venueSubmission: "pm-arc-venue:submission-started",
549
+ venueConfirmed: "pm-arc-venue:confirmed",
550
+ relaySubmission: "pm-arc-relay:broadcast-started",
551
+ completed: "pm-arc:completed",
552
+ };
553
+ function amountText(amount) {
554
+ const whole = amount / 1000000n;
555
+ const fraction = (amount % 1000000n).toString().padStart(6, "0");
556
+ return `${whole}.${fraction}`;
557
+ }
558
+ function errorCode(response) {
559
+ return isRecord(response.error) && typeof response.error.code === "string" ? response.error.code : "unknown_error";
560
+ }
561
+ function httpStatus(response) {
562
+ const meta = isRecord(response._meta) ? response._meta : {};
563
+ const status = Number(meta.http_status);
564
+ return Number.isInteger(status) ? status : undefined;
565
+ }
566
+ /** A definitive refusal that created nothing (validation/auth/gate), never a lost outcome. */
567
+ function definitiveRefusal(response) {
568
+ const status = httpStatus(response);
569
+ return status !== undefined && [400, 401, 403, 404, 409, 422].includes(status);
570
+ }
571
+ export async function drivePmArcReturn(amountUnits, deps) {
572
+ if (amountUnits < MIN_AMOUNT_UNITS || amountUnits > MAX_AMOUNT_UNITS) {
573
+ return failure("pm_arc_return_amount_invalid", "The amount is outside the 5 to 2,000 USDC launch bounds.", {
574
+ money_moved: false,
575
+ });
576
+ }
577
+ const owner = deps.ownerAddress().toLowerCase();
578
+ if (!ADDRESS.test(owner)) {
579
+ return failure("client_signature_required", "A local owner key is required.", { money_moved: false });
580
+ }
581
+ const budgetMs = deps.pollBudgetMs ?? DEFAULT_POLL_BUDGET_MS;
582
+ const maxPolls = deps.maxPolls ?? DEFAULT_MAX_POLLS;
583
+ const startedAt = deps.now();
584
+ let polls = 0;
585
+ let pollDelay = MIN_POLL_MS;
586
+ let saved = deps.getCheckpoint(CK.journey);
587
+ // Once anything was signed, "nothing moved" needs the server's chain proof.
588
+ const signedAnything = () => Boolean(deps.getCheckpoint(CK.venueSubmission) || deps.getCheckpoint(CK.relaySubmission));
589
+ const movement = (view) => {
590
+ if (deps.getCheckpoint(CK.venueConfirmed) || deps.getCheckpoint(CK.completed))
591
+ return true;
592
+ if (!view)
593
+ return signedAnything() ? "unknown" : false;
594
+ if (view.money_moved === true)
595
+ return true;
596
+ if (view.money_moved === false) {
597
+ // Once the owner has signed a batch, no expiry proof makes it "not
598
+ // moved": the deposit wallet is upgradeable, so today's nonce semantics
599
+ // do not bind a future implementation (security review 2026-09-23).
600
+ return signedAnything() ? "unknown" : false;
601
+ }
602
+ return signedAnything() ? "unknown" : (view.phase === "venue_prepared" ? false : "unknown");
603
+ };
604
+ const inFlight = (view, message) => failure("pm_arc_return_in_progress", message, {
605
+ status: "in_progress", journey_id: saved?.journey_id ?? null, phase: view?.phase ?? null,
606
+ money_moved: movement(view), resume: "Call again with the same idempotency_key; nothing will be signed twice.",
607
+ });
608
+ const held = (view, code, message) => failure(code, message, {
609
+ status: "reconciliation_required", journey_id: saved?.journey_id ?? null, phase: view?.phase ?? null,
610
+ money_moved: movement(view), reconciliation_required: true,
611
+ server_reason: view?.reason ?? null,
612
+ resume: "Do not sign anything else for this return. Call again with the same idempotency_key to re-read proof.",
613
+ });
614
+ try {
615
+ const expectedSafe = lower(await deps.expectedSafe(), "verified Arc home Safe");
616
+ if (saved && lower(saved.recipient, "saved Arc home Safe") !== expectedSafe) {
617
+ hostile("the saved return targets a different Arc home Safe");
618
+ }
619
+ // ---------------------------------------------------------- prepare
620
+ if (!saved) {
621
+ const attempt = 1;
622
+ const response = await deps.call("POST", "/v1/arc-home/pm-returns/prepare", { amount: amountText(amountUnits) }, {
623
+ idempotencyKey: deps.stageKey(`pm-arc-prepare:${attempt}`),
624
+ });
625
+ if (response.ok === false) {
626
+ // Prepare hands out an unsigned batch at most: nothing can have moved.
627
+ return failure(errorCode(response), "Felix did not open the Polymarket -> Arc return.", {
628
+ money_moved: false, server_error: response.error ?? null,
629
+ });
630
+ }
631
+ const view = assertJourney(response, { owner, amount: amountUnits, recipient: expectedSafe });
632
+ saved = { journey_id: view.id, recipient: lower(view.recipient, "recipient"), attempt };
633
+ deps.saveCheckpoint(CK.journey, saved);
634
+ }
635
+ const journey = {
636
+ id: String(saved.journey_id), owner, recipient: String(saved.recipient), amount: amountUnits,
637
+ };
638
+ const base = `/v1/arc-home/pm-returns/${journey.id}`;
639
+ let lastRank = -1;
640
+ let relayAttempts = 0;
641
+ // One submission per leg per invocation. The server accepts the same bytes
642
+ // idempotently, but this client never offers them in a loop.
643
+ let venueOffered = false;
644
+ let relayOfferedFor = null;
645
+ for (;;) {
646
+ if (polls >= maxPolls || deps.now() - startedAt > budgetMs) {
647
+ return inFlight(undefined, "The return is still settling. Polling stopped at its bound.");
648
+ }
649
+ polls += 1;
650
+ const reconciled = await deps.call("POST", `${base}/reconcile`, {}, { retryOnError: true });
651
+ if (reconciled.ok === false) {
652
+ if (httpStatus(reconciled) === 404)
653
+ hostile("the server lost the journey it created");
654
+ await deps.sleep(pollDelay);
655
+ pollDelay = Math.min(MAX_POLL_MS, pollDelay * 2);
656
+ continue;
657
+ }
658
+ const view = assertJourney(reconciled, { id: journey.id, owner, amount: amountUnits, recipient: journey.recipient });
659
+ const rank = PHASE_RANK[String(view.phase)];
660
+ if (rank < lastRank && view.phase !== "reconciliation_required")
661
+ hostile("the journey moved backwards");
662
+ lastRank = Math.max(lastRank, rank);
663
+ const phase = String(view.phase);
664
+ if (phase === "completed") {
665
+ const done = assertCompletion(view, journey, deps.getCheckpoint(CK.relaySubmission));
666
+ deps.saveCheckpoint(CK.completed, {
667
+ journey_id: journey.id, credit_tx_hash: done.credit.tx_hash,
668
+ credited_units: String(done.credited),
669
+ });
670
+ return result(true, {
671
+ status: "completed", journey_id: journey.id, phase, money_moved: true, home_usable: true,
672
+ destination: { chain_id: ARC_CHAIN_ID, token: ARC_USDC, safe: journey.recipient },
673
+ credited_units: String(done.credited), minimum_credit_units: String(done.minimum),
674
+ credit_tx_hash: done.credit.tx_hash,
675
+ });
676
+ }
677
+ if (phase === "refunded") {
678
+ return failure("pm_arc_return_refunded", "Relay refunded the return to the owner wallet; nothing reached the Arc home.", {
679
+ status: "refunded", journey_id: journey.id, phase, money_moved: true, refund: view.refund ?? null,
680
+ });
681
+ }
682
+ if (phase === "closed") {
683
+ return failure("pm_arc_return_closed", "An operator closed this return after reconciliation; it credited nothing.", {
684
+ status: "closed", journey_id: journey.id, phase, money_moved: movement(view),
685
+ resolution: view.resolution ?? view.relay_resolution ?? null,
686
+ });
687
+ }
688
+ if (phase === "expired") {
689
+ // The server no longer releases a PM batch by expiry; an old or odd
690
+ // server that does gets no "not moved" from this client after signing.
691
+ const proof = isRecord(view.expiry_proof) ? view.expiry_proof : null;
692
+ return failure("pm_arc_return_expired", "Felix reports the withdrawal batch expired.", {
693
+ status: "expired", journey_id: journey.id, phase, money_moved: movement(view),
694
+ expiry_proof: proof, trust_assumption: proof?.trust ?? null,
695
+ });
696
+ }
697
+ if (phase === "reconciliation_required" && view.reason === "venue_batch_nonce_consumed_elsewhere") {
698
+ const proof = isRecord(view.expiry_proof) ? view.expiry_proof : null;
699
+ return failure("pm_arc_return_batch_superseded_held", "The withdrawal batch's nonce was used by another owner batch, so it did not run under the current wallet "
700
+ + "implementation. The return slot stays held: the wallet is upgradeable, so that proof is not permanent.", {
701
+ status: "reconciliation_required", journey_id: journey.id, phase, money_moved: movement(view),
702
+ reconciliation_required: true, expiry_proof: proof,
703
+ proof_well_formed: consumptionProof(proof), trust_assumption: proof?.trust ?? null,
704
+ residual_risk: "A future deposit-wallet upgrade could make the old signed batch executable. It can "
705
+ + "only move this return's pUSD amount to the owner's own Polygon wallet.",
706
+ required_action: view.required_action ?? null,
707
+ resume: "Felix support can close the held return with a recorded residual; nothing else releases it.",
708
+ });
709
+ }
710
+ if (phase === "reconciliation_required" && view.reason === "venue_batch_nonce_unconsumed") {
711
+ return failure("pm_arc_return_batch_nonce_unconsumed", "The withdrawal batch is past its deadline but its nonce is unused. The slot stays held until the owner consumes it.", {
712
+ status: "reconciliation_required", journey_id: journey.id, phase, money_moved: movement(view),
713
+ reconciliation_required: true, required_action: view.required_action ?? null,
714
+ unconsumed_at: view.unconsumed_at ?? null,
715
+ resume: "After any owner-signed Polymarket deposit-wallet action finalizes, call again with the same idempotency_key.",
716
+ });
717
+ }
718
+ if (phase === "reconciliation_required") {
719
+ return held(view, "pm_arc_return_reconciliation_required", "Felix needs reconciliation before this return can continue.");
720
+ }
721
+ if (phase === "venue_prepared" && !venueOffered) {
722
+ venueOffered = true;
723
+ const outcome = await submitVenue(view, journey, deps);
724
+ if (outcome)
725
+ return outcome === "held" ? held(view, "pm_arc_return_batch_changed", "The server changed a batch after it was signed.") : inFlight(view, outcome);
726
+ continue;
727
+ }
728
+ else if (phase === "venue_confirmed" || (phase === "relay_open" && needsNewChild(view))) {
729
+ deps.saveCheckpoint(CK.venueConfirmed, { journey_id: journey.id });
730
+ if (phase === "relay_open") {
731
+ const previous = deps.getCheckpoint(CK.relaySubmission);
732
+ const child = assertRelayChild(view.relay_return, journey);
733
+ if (previous) {
734
+ if (previous.journey_id !== journey.id || previous.child_id !== child.id) {
735
+ hostile("the server replaced a signed Relay child without its no-move outcome");
736
+ }
737
+ deps.saveCheckpoint(CK.relaySubmission, { ...previous, replaceable: true });
738
+ }
739
+ }
740
+ if (++relayAttempts > MAX_RELAY_ATTEMPTS)
741
+ hostile("the server keeps opening Relay attempts");
742
+ const opened = await deps.call("POST", `${base}/relay/prepare`, {}, { retryOnError: true });
743
+ if (opened.ok === false && definitiveRefusal(opened)) {
744
+ return held(view, errorCode(opened), "Felix refused to open the Relay leg; the withdrawn USDC.e is in the owner wallet.");
745
+ }
746
+ continue;
747
+ }
748
+ else if (phase === "relay_open") {
749
+ deps.saveCheckpoint(CK.venueConfirmed, { journey_id: journey.id });
750
+ const child = assertRelayChild(view.relay_return, journey);
751
+ if (child.phase === "prepared" && relayOfferedFor !== child.id) {
752
+ relayOfferedFor = String(child.id);
753
+ const outcome = await submitRelay(child, journey, deps);
754
+ if (outcome)
755
+ return inFlight(view, outcome);
756
+ continue;
757
+ }
758
+ }
759
+ await deps.sleep(pollDelay);
760
+ pollDelay = Math.min(MAX_POLL_MS, pollDelay * 2);
761
+ }
762
+ }
763
+ catch (error) {
764
+ if (error instanceof PmArcReturnHostileServer) {
765
+ return held(undefined, "pm_arc_return_server_untrusted", error.message);
766
+ }
767
+ if (signedAnything() || deps.getCheckpoint(CK.venueConfirmed)) {
768
+ return held(undefined, "pm_arc_return_reconciliation_required", error instanceof Error ? String(redactOutput(error.message)).slice(0, 300) : "The return could not be driven further.");
769
+ }
770
+ return failure("pm_arc_return_client_failed", "The return failed before anything was signed.", {
771
+ money_moved: false, journey_id: saved?.journey_id ?? null,
772
+ });
773
+ }
774
+ }
775
+ /**
776
+ * A well-formed proof that the batch nonce went to another batch, at a
777
+ * finalized block, with the upgradeable-wallet trust model stated. It is shown
778
+ * to the owner as evidence; it never releases the slot or turns
779
+ * money_moved to false (the wallet can be upgraded).
780
+ */
781
+ export function consumptionProof(proof) {
782
+ if (!isRecord(proof) || proof.kind !== "venue_nonce_consumed_without_withdrawal")
783
+ return false;
784
+ if (typeof proof.chain_nonce !== "string" || typeof proof.batch_nonce !== "string"
785
+ || !UINT.test(proof.chain_nonce) || !UINT.test(proof.batch_nonce)
786
+ || BigInt(proof.chain_nonce) <= BigInt(proof.batch_nonce))
787
+ return false;
788
+ const trust = proof.trust;
789
+ return isRecord(trust) && trust.model === "upgradeable_deposit_wallet"
790
+ && typeof trust.not_proven === "string" && typeof trust.holds_while === "string";
791
+ }
792
+ function needsNewChild(view) {
793
+ const child = view.relay_return;
794
+ return isRecord(child) && CHILD_NO_MOVE.has(String(child.phase)) && view.next_action === "prepare_relay_return";
795
+ }
796
+ /** Sign the venue batch once, journal it, submit. A lost response is only ever "unknown". */
797
+ async function submitVenue(view, journey, deps) {
798
+ const batch = assertVenueBatch(view.venue_batch, journey.owner, journey.amount);
799
+ const batchDigest = digest({ wallet: batch.wallet, nonce: batch.nonce, deadline: batch.deadline, calls: batch.calls });
800
+ const previous = deps.getCheckpoint(CK.venueSubmission);
801
+ let signed;
802
+ if (previous) {
803
+ // Already signed: the SAME bytes may be offered again (the server never
804
+ // journaled them, it still says venue_prepared). A different batch is refused.
805
+ if (previous.journey_id !== journey.id || previous.batch_digest !== batchDigest)
806
+ return "held";
807
+ signed = previous.signed_request;
808
+ }
809
+ else {
810
+ if (Number(batch.deadline) - Math.floor(deps.now() / 1000) < BATCH_SIGNING_MARGIN_S) {
811
+ return "The venue batch is too close to its deadline to sign; the server will prove it expired.";
812
+ }
813
+ signed = await deps.signVenueBatch(batch, journey.amount);
814
+ deps.saveCheckpoint(CK.venueSubmission, {
815
+ journey_id: journey.id, batch_digest: batchDigest, signed_request: signed,
816
+ started_at: new Date(deps.now()).toISOString(),
817
+ });
818
+ }
819
+ // Exactly one transport attempt: an ambiguous outcome is resolved by reconcile.
820
+ await deps.call("POST", `/v1/arc-home/pm-returns/${journey.id}/submit`, { signed_request: signed }, {
821
+ retryOnError: false,
822
+ });
823
+ return null;
824
+ }
825
+ /** Sign the Relay pair once at the server-observed nonce, journal the raw bytes, submit. */
826
+ async function submitRelay(child, journey, deps) {
827
+ const previous = deps.getCheckpoint(CK.relaySubmission);
828
+ if (previous && (previous.journey_id !== journey.id
829
+ || (previous.child_id !== child.id && previous.replaceable !== true))) {
830
+ hostile("the server substituted a prepared Relay child after signing");
831
+ }
832
+ let approveRaw;
833
+ let depositRaw;
834
+ if (previous && previous.child_id === child.id) {
835
+ approveRaw = previous.approve_raw;
836
+ depositRaw = previous.deposit_raw;
837
+ }
838
+ else {
839
+ const pair = assertRelayPair(child, journey.owner, journey.amount);
840
+ const nowS = Math.floor(deps.now() / 1000);
841
+ if (pair.quoteExpiresAt - nowS < QUOTE_SIGNING_MARGIN_S) {
842
+ return "The Relay quote is too close to expiry to sign; the next call opens a fresh one.";
843
+ }
844
+ // No source signature until the solver-signed order provably pays the Safe.
845
+ const order = await assertRelayOrder(child, journey, pair.orderId, deps.trustedSolvers ?? RELAY_TRUSTED_SOLVERS, nowS);
846
+ approveRaw = await deps.signPolygonTransaction(pair.approve);
847
+ depositRaw = await deps.signPolygonTransaction(pair.deposit);
848
+ deps.saveCheckpoint(CK.relaySubmission, {
849
+ journey_id: journey.id, child_id: child.id, approve_raw: approveRaw, deposit_raw: depositRaw,
850
+ approve_hash: keccak256(approveRaw), deposit_hash: keccak256(depositRaw),
851
+ nonce: pair.approve.nonce, order_id: order.orderId, solver: order.solver,
852
+ signed_minimum_units: String(order.signedMinimum), started_at: new Date(deps.now()).toISOString(),
853
+ });
854
+ }
855
+ await deps.call("POST", `/v1/arc-home/pm-returns/${journey.id}/relay/submit`, {
856
+ signed_approve_transaction: approveRaw, signed_deposit_transaction: depositRaw,
857
+ }, { retryOnError: false });
858
+ return null;
859
+ }