felix-mcp 2.0.129 → 2.0.133
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +50 -48
- package/dist/arc-first-deposit.js +366 -0
- package/dist/arc-polygon-funding.js +1207 -0
- package/dist/arc-venue-app-policy.js +24 -0
- package/dist/funding.js +27 -2
- package/dist/getting-started-guide.js +58 -57
- package/dist/index.js +1143 -125
- package/dist/manual-policy.js +281 -0
- package/dist/redact-output.js +3 -1
- package/package.json +1 -1
- package/server.json +2 -2
|
@@ -0,0 +1,1207 @@
|
|
|
1
|
+
// ARC_POLYGON_CLIENT_2026_09_26: the local driver for the engine's Relay-first
|
|
2
|
+
// Arc home Safe -> the SAME account owner's Polygon USDC.e -> Polymarket pUSD
|
|
3
|
+
// (/v1/arc-home/polygon-fundings/*, engine services/arc_home_polygon_funding.py
|
|
4
|
+
// + services/arc_home_polymarket_relay_continuation.py; contract fixture
|
|
5
|
+
// fixtures/arc_polygon_route_contract_20260926.json, GENERATED from the
|
|
6
|
+
// engine's route responses).
|
|
7
|
+
//
|
|
8
|
+
// ENABLED 2026-09-27 (A5, ARC_POLYGON_MCP_POLICY_2026_09_27): ARC_POLYGON_CLIENT_ENABLED
|
|
9
|
+
// lists the tool and index.ts hands the driver the production policy from
|
|
10
|
+
// src/arc-polygon-policy.ts. SHIPPED_ARC_POLYGON_POLICY stays EMPTY (the value
|
|
11
|
+
// an unaccepted or unconfigured build degrades to). The driver refuses before
|
|
12
|
+
// any request unless the policy supplies reviewed evidence for every release gate:
|
|
13
|
+
// 1. trustedSolvers -- Relay solvers for Arc -> Polygon orders;
|
|
14
|
+
// 2. verifyDepositoryRuntime -- the Relay depository's code on Arc;
|
|
15
|
+
// 3. relayExtraData -- the reviewed Relay fill-contract word the
|
|
16
|
+
// order's output and BOTH refunds carry;
|
|
17
|
+
// 4. verifySafeState -- the Safe's nonce/threshold/modules;
|
|
18
|
+
// 5. verifyPolygonCredit -- an independent Polygon read of the
|
|
19
|
+
// credited USDC.e fill to the owner;
|
|
20
|
+
// 6. verifyPmCredit -- an independent Polygon read that the
|
|
21
|
+
// owner's PM wallet received the pUSD.
|
|
22
|
+
//
|
|
23
|
+
// Before the ONE local Arc signature the client re-derives, from pins and the
|
|
24
|
+
// policy (never server authority): the Relay order id and the solver it
|
|
25
|
+
// recovers to; input exactly the amount in Arc USDC; exactly one output on
|
|
26
|
+
// Polygon, USDC.e, to the SAME owner, minimum >= the client's 1% floor and any
|
|
27
|
+
// requested minimum; refunds exactly Arc USDC -> the Safe and Polygon USDC.e ->
|
|
28
|
+
// the owner; the SafeTx: canonical, chain 5042, DELEGATECALL only to the pinned
|
|
29
|
+
// MultiSendCallOnly with EXACTLY approve(depository, amount), depositErc20(safe,
|
|
30
|
+
// USDC, amount, orderId) and the ONE pinned $1 Polymarket funding fee to the
|
|
31
|
+
// pinned treasury. It signs its OWN rebuilt typed data, journals the prepared
|
|
32
|
+
// identity and signature before submitting, and never signs again.
|
|
33
|
+
//
|
|
34
|
+
// Money truth: `money_moved` is true only from the engine's durable source
|
|
35
|
+
// evidence or this client's journal of a verified credit; "unknown" after any
|
|
36
|
+
// local signature; false only before one. Owner-PM usability is reported only
|
|
37
|
+
// after the engine's confirm AND this client's own read (gate 6). Agent-wallet
|
|
38
|
+
// funding is a SEPARATE owner-signed transfer this driver never makes.
|
|
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, USDC_E, 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
|
+
export const ARC_POLYGON_CLIENT_ENABLED = true;
|
|
44
|
+
export const ARC_POLYGON_TOOL = "fund_polymarket_from_arc";
|
|
45
|
+
export const ROUTE_PREFIX = "/v1/arc-home/polygon-fundings";
|
|
46
|
+
export const ARC_USDC = ARC_USDC_CHECKSUM.toLowerCase();
|
|
47
|
+
export const POLYGON_CHAIN_ID = 137;
|
|
48
|
+
export const POLYGON_USDC_E = USDC_E;
|
|
49
|
+
// Same values funding.ts pins for prediction_fund (re-checked there at execution).
|
|
50
|
+
export const PUSD_POLYGON = "0xc011a7e12a19f7b1f670d46f03b03f3342e82dfb";
|
|
51
|
+
export const PM_ONRAMP = "0x93070a847efef7f70739046a929d47a521f5b8ee";
|
|
52
|
+
export const MIN_AMOUNT_UNITS = 5000000n;
|
|
53
|
+
export const MAX_AMOUNT_UNITS = 25000000n;
|
|
54
|
+
export const MAX_ALL_IN_COST_BPS = 100n;
|
|
55
|
+
// ARC_RELAY_PLATFORM_FEE_2026_09_26: the ONE $1 prediction/Polymarket funding
|
|
56
|
+
// fee, paid by the Safe inside the SAME owner-signed SafeTx. THIS client's pins.
|
|
57
|
+
export const POLYMARKET_FUNDING_FEE_UNITS = 1000000n;
|
|
58
|
+
export const FELIX_FEE_TREASURY = "0xdc9c35bf585fba2a39bcd17bdfe343277b595cad";
|
|
59
|
+
export const POLYGON_FEE_DISCLOSURE = "A flat 1.00 USDC network fee is paid from your Arc home Safe to Felix's treasury in the same transaction "
|
|
60
|
+
+ "as the deposit. It is the only Felix fee for this Polymarket funding (the pUSD step does not charge it "
|
|
61
|
+
+ "again), it is charged only if that transaction executes, and it is not refunded if Relay later refunds.";
|
|
62
|
+
const ORDER_DEADLINE_MARGIN_S = 60;
|
|
63
|
+
const QUOTE_SIGNING_MARGIN_S = 60;
|
|
64
|
+
const ORDER_MAX_DEADLINE_S = 8 * 86_400;
|
|
65
|
+
const DEFAULT_MAX_POLLS = 60;
|
|
66
|
+
const MIN_POLL_MS = 2_000;
|
|
67
|
+
const MAX_POLL_MS = 30_000;
|
|
68
|
+
const MAX_GAS_ROUNDS = 8; // the engine's _POLYGON_MAX_GRANTS_PER_FUNDING
|
|
69
|
+
// The engine's _POLYGON_GRANT_CAP_WEI and funding.ts's Polygon signer cap (0.25 POL).
|
|
70
|
+
export const POLYGON_GAS_GRANT_CAP_WEI = 250000000000000000n;
|
|
71
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
72
|
+
const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
|
|
73
|
+
const HASH = /^0x[0-9a-fA-F]{64}$/;
|
|
74
|
+
const UINT = /^(0|[1-9][0-9]{0,40})$/;
|
|
75
|
+
const APPROVE_ABI = [{ type: "function", name: "approve", stateMutability: "nonpayable",
|
|
76
|
+
inputs: [{ name: "spender", type: "address" }, { name: "amount", type: "uint256" }], outputs: [{ type: "bool" }] }];
|
|
77
|
+
const TRANSFER_ABI = [{ type: "function", name: "transfer", stateMutability: "nonpayable",
|
|
78
|
+
inputs: [{ name: "to", type: "address" }, { name: "amount", type: "uint256" }], outputs: [{ type: "bool" }] }];
|
|
79
|
+
const DEPOSIT_ABI = [{ type: "function", name: "depositErc20", stateMutability: "nonpayable",
|
|
80
|
+
inputs: [{ name: "depositor", type: "address" }, { name: "token", type: "address" },
|
|
81
|
+
{ name: "amount", type: "uint256" }, { name: "id", type: "bytes32" }], outputs: [] }];
|
|
82
|
+
export const CP = {
|
|
83
|
+
scope: "pgfund:scope",
|
|
84
|
+
prepared: "pgfund:prepared",
|
|
85
|
+
signed: "pgfund:signed",
|
|
86
|
+
submission: "pgfund:submission-started",
|
|
87
|
+
credited: "pgfund:credited",
|
|
88
|
+
pmPrepared: "pgfund:pm-prepared",
|
|
89
|
+
pmBroadcastStarted: "pgfund:pm-broadcast-started",
|
|
90
|
+
pmLastSubmitted: "pgfund:pm-last-submitted",
|
|
91
|
+
pmSent: "pgfund:pm-sent",
|
|
92
|
+
pmApprovalMissing: "pgfund:pm-approval-missing",
|
|
93
|
+
completed: "pgfund:completed",
|
|
94
|
+
};
|
|
95
|
+
export const SHIPPED_ARC_POLYGON_POLICY = Object.freeze({
|
|
96
|
+
trustedSolvers: Object.freeze([]),
|
|
97
|
+
verifyDepositoryRuntime: null,
|
|
98
|
+
relayExtraData: null,
|
|
99
|
+
verifySafeState: null,
|
|
100
|
+
verifyPolygonCredit: null,
|
|
101
|
+
verifyPmCredit: null,
|
|
102
|
+
});
|
|
103
|
+
export function policyGaps(policy) {
|
|
104
|
+
const gaps = [];
|
|
105
|
+
const solvers = policy?.trustedSolvers;
|
|
106
|
+
if (!Array.isArray(solvers) || !solvers.length || !solvers.every((s) => typeof s === "string" && ADDRESS.test(s))) {
|
|
107
|
+
gaps.push("arc_polygon_solver_unverified");
|
|
108
|
+
}
|
|
109
|
+
if (typeof policy?.verifyDepositoryRuntime !== "function")
|
|
110
|
+
gaps.push("arc_polygon_depository_runtime_unverified");
|
|
111
|
+
if (typeof policy?.relayExtraData !== "string" || !HASH.test(policy.relayExtraData)) {
|
|
112
|
+
gaps.push("arc_polygon_relay_extra_data_unverified");
|
|
113
|
+
}
|
|
114
|
+
if (typeof policy?.verifySafeState !== "function")
|
|
115
|
+
gaps.push("arc_polygon_safe_state_unverified");
|
|
116
|
+
if (typeof policy?.verifyPolygonCredit !== "function")
|
|
117
|
+
gaps.push("arc_polygon_credit_read_unverified");
|
|
118
|
+
if (typeof policy?.verifyPmCredit !== "function")
|
|
119
|
+
gaps.push("arc_polygon_pm_credit_read_unverified");
|
|
120
|
+
return gaps;
|
|
121
|
+
}
|
|
122
|
+
export class ArcPolygonHostileServer extends Error {
|
|
123
|
+
constructor(message) {
|
|
124
|
+
super(message);
|
|
125
|
+
this.name = "ArcPolygonHostileServer";
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
function hostile(message) {
|
|
129
|
+
throw new ArcPolygonHostileServer(message);
|
|
130
|
+
}
|
|
131
|
+
function isRecord(value) {
|
|
132
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
133
|
+
}
|
|
134
|
+
function lower(value, name) {
|
|
135
|
+
if (typeof value !== "string" || !ADDRESS.test(value))
|
|
136
|
+
hostile(`${name} is not an address`);
|
|
137
|
+
return value.toLowerCase();
|
|
138
|
+
}
|
|
139
|
+
function units(value, name) {
|
|
140
|
+
if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0)
|
|
141
|
+
return BigInt(value);
|
|
142
|
+
if (typeof value !== "string" || !UINT.test(value))
|
|
143
|
+
hostile(`${name} is not exact integer units`);
|
|
144
|
+
return BigInt(value);
|
|
145
|
+
}
|
|
146
|
+
function floorUnits(amount) {
|
|
147
|
+
return (amount * (10000n - MAX_ALL_IN_COST_BPS) + 9999n) / 10000n;
|
|
148
|
+
}
|
|
149
|
+
/** Exact 6-decimal USD -> units; anything with more precision or not a finite number is refused. */
|
|
150
|
+
function usdUnits(value, name) {
|
|
151
|
+
const text = typeof value === "number" && Number.isFinite(value) ? value.toFixed(6) : value;
|
|
152
|
+
const match = typeof text === "string" ? /^(0|[1-9][0-9]{0,12})(?:\.([0-9]{1,6}))?$/.exec(text) : null;
|
|
153
|
+
if (!match)
|
|
154
|
+
hostile(`${name} is not an exact USD amount`);
|
|
155
|
+
return BigInt(match[1]) * 1000000n + BigInt((match[2] || "").padEnd(6, "0"));
|
|
156
|
+
}
|
|
157
|
+
/** The whole prepared view -> a plan this client would sign, or a refusal. */
|
|
158
|
+
export async function verifyPrepared(view, ctx) {
|
|
159
|
+
if (!isRecord(view))
|
|
160
|
+
hostile("the prepared view is not an object");
|
|
161
|
+
const v = view;
|
|
162
|
+
if (v.kind !== "arc_polygon_funding" || v.phase !== "prepared" || v.provider !== "relay"
|
|
163
|
+
|| v.route_kind !== "arc_safe_to_polygon_owner_usdce" || v.route_intent !== "polymarket_funding") {
|
|
164
|
+
hostile("the view is not a prepared Arc -> Polygon Polymarket funding");
|
|
165
|
+
}
|
|
166
|
+
const fundingId = typeof v.id === "string" && UUID.test(v.id) ? v.id : hostile("funding id is invalid");
|
|
167
|
+
if (v.source_chain_id !== ARC_MAINNET_CHAIN_ID || v.destination_chain_id !== POLYGON_CHAIN_ID
|
|
168
|
+
|| lower(v.destination_token, "destination_token") !== POLYGON_USDC_E) {
|
|
169
|
+
hostile("the route is not Arc USDC -> Polygon USDC.e");
|
|
170
|
+
}
|
|
171
|
+
if (lower(v.safe, "safe") !== ctx.safe || lower(v.owner, "owner") !== ctx.owner
|
|
172
|
+
|| lower(v.recipient, "recipient") !== ctx.owner) {
|
|
173
|
+
hostile("the funding is not from this account's Safe to its own owner");
|
|
174
|
+
}
|
|
175
|
+
if (units(v.amount_units, "amount_units") !== ctx.amount)
|
|
176
|
+
hostile("the funding amount changed");
|
|
177
|
+
const quoteExpiresAt = Number(v.quote_expires_at);
|
|
178
|
+
if (!Number.isSafeInteger(quoteExpiresAt) || quoteExpiresAt <= 0)
|
|
179
|
+
hostile("quote expiry is invalid");
|
|
180
|
+
// -------- the Relay order: recompute, recover, bind every field
|
|
181
|
+
const relay = v.relay_order;
|
|
182
|
+
if (!isRecord(relay))
|
|
183
|
+
hostile("relay_order is missing");
|
|
184
|
+
const r = relay;
|
|
185
|
+
const orderId = String(r.order_id || "").toLowerCase();
|
|
186
|
+
if (!HASH.test(orderId) || String(v.order_id || "").toLowerCase() !== orderId)
|
|
187
|
+
hostile("order id is invalid or inconsistent");
|
|
188
|
+
const signature = String(r.order_signature || "");
|
|
189
|
+
if (!/^0x[0-9a-fA-F]{130}$/.test(signature))
|
|
190
|
+
hostile("order signature is not 65 bytes");
|
|
191
|
+
let message;
|
|
192
|
+
try {
|
|
193
|
+
message = relayOrderMessage(r.order_data);
|
|
194
|
+
}
|
|
195
|
+
catch (error) {
|
|
196
|
+
hostile(`relay_order is malformed: ${error.message}`);
|
|
197
|
+
}
|
|
198
|
+
let recomputed;
|
|
199
|
+
try {
|
|
200
|
+
recomputed = hashStruct({ types: RELAY_ORDER_TYPES, primaryType: "Order", data: message }).toLowerCase();
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
hostile("relay_order does not hash as a Relay v1 order");
|
|
204
|
+
}
|
|
205
|
+
if (recomputed !== orderId)
|
|
206
|
+
hostile("the order id is not the hash of the signed order");
|
|
207
|
+
let recovered;
|
|
208
|
+
try {
|
|
209
|
+
recovered = (await recoverMessageAddress({ message: { raw: orderId }, signature: signature })).toLowerCase();
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
hostile("the order signature does not recover");
|
|
213
|
+
}
|
|
214
|
+
const trusted = new Set(ctx.policy.trustedSolvers.map((s) => s.toLowerCase()));
|
|
215
|
+
if (recovered !== message.solver.toLowerCase() || recovered !== lower(r.solver, "relay_order.solver")
|
|
216
|
+
|| recovered !== lower(v.solver, "solver") || !trusted.has(recovered)) {
|
|
217
|
+
hostile("the order is not signed by a Relay solver the reviewed policy trusts");
|
|
218
|
+
}
|
|
219
|
+
if (message.version !== "v1" || message.solverChainId !== "base")
|
|
220
|
+
hostile("the order is not a Relay v1 order");
|
|
221
|
+
const payment = message.inputs[0].payment;
|
|
222
|
+
if (payment.chainId !== "arc" || payment.currency !== ARC_USDC || payment.amount !== ctx.amount || payment.weight !== 1n) {
|
|
223
|
+
hostile("the order does not take exactly the amount in Arc USDC");
|
|
224
|
+
}
|
|
225
|
+
const output = message.output;
|
|
226
|
+
const paid = output.payments[0];
|
|
227
|
+
if (output.chainId !== "polygon" || paid.recipient !== ctx.owner || paid.currency !== POLYGON_USDC_E) {
|
|
228
|
+
hostile("the order does not pay Polygon USDC.e to this account's own owner");
|
|
229
|
+
}
|
|
230
|
+
const floor = floorUnits(ctx.amount);
|
|
231
|
+
if (paid.minimumAmount < floor || paid.minimumAmount < (ctx.requestedMinimum ?? 0n)
|
|
232
|
+
|| paid.minimumAmount > paid.expectedAmount || paid.expectedAmount > ctx.amount) {
|
|
233
|
+
hostile("the order's signed minimum is below the client's floor or above what is deposited");
|
|
234
|
+
}
|
|
235
|
+
const extra = String(ctx.policy.relayExtraData).toLowerCase();
|
|
236
|
+
if (output.calls.length !== 0 || output.extraData !== extra || message.fees.length !== 0) {
|
|
237
|
+
hostile("the order carries calls, fees or an unreviewed fill extraData");
|
|
238
|
+
}
|
|
239
|
+
if (output.deadline < ctx.nowS + ORDER_DEADLINE_MARGIN_S)
|
|
240
|
+
hostile("the order is expired or about to");
|
|
241
|
+
if (output.deadline > ctx.nowS + ORDER_MAX_DEADLINE_S)
|
|
242
|
+
hostile("the order's deadline is beyond the 8-day bound");
|
|
243
|
+
const refunds = new Set(message.inputs[0].refunds.map((refund) => {
|
|
244
|
+
if (refund.minimumAmount !== 0n || refund.deadline !== output.deadline || refund.extraData !== extra) {
|
|
245
|
+
hostile("an order refund is not the reviewed refund");
|
|
246
|
+
}
|
|
247
|
+
return `${refund.chainId}|${refund.recipient}|${refund.currency}`;
|
|
248
|
+
}));
|
|
249
|
+
if (refunds.size !== 2 || !refunds.has(`arc|${ctx.safe}|${ARC_USDC}`)
|
|
250
|
+
|| !refunds.has(`polygon|${ctx.owner}|${POLYGON_USDC_E}`)) {
|
|
251
|
+
hostile("the order refunds someone other than the Safe on Arc and the owner on Polygon");
|
|
252
|
+
}
|
|
253
|
+
const viewMinimum = units(v.minimum_credit_units, "minimum_credit_units");
|
|
254
|
+
if (viewMinimum !== paid.minimumAmount || units(v.expected_credit_units, "expected_credit_units") !== paid.expectedAmount) {
|
|
255
|
+
hostile("the funding's credit bounds are not the signed order's");
|
|
256
|
+
}
|
|
257
|
+
if (Number(v.order_deadline) !== output.deadline)
|
|
258
|
+
hostile("the order deadline is inconsistent");
|
|
259
|
+
// -------- the SafeTx: canonical shape, exact packed calls, recomputed digest
|
|
260
|
+
const safeTx = v.safe_transaction;
|
|
261
|
+
if (!isRecord(safeTx))
|
|
262
|
+
hostile("safe_transaction is missing");
|
|
263
|
+
const st = safeTx;
|
|
264
|
+
let shape;
|
|
265
|
+
try {
|
|
266
|
+
shape = assertArcSafeTxShape(st.typed_data, { safe: ctx.safe, chainId: ARC_MAINNET_CHAIN_ID });
|
|
267
|
+
}
|
|
268
|
+
catch (error) {
|
|
269
|
+
hostile(`the SafeTx is not canonical: ${error.message}`);
|
|
270
|
+
}
|
|
271
|
+
if (shape.operation !== 1 || shape.to.toLowerCase() !== SAFE_MULTISEND_CALL_ONLY.toLowerCase()) {
|
|
272
|
+
hostile("the SafeTx is not a DELEGATECALL to the pinned MultiSendCallOnly");
|
|
273
|
+
}
|
|
274
|
+
let calls;
|
|
275
|
+
try {
|
|
276
|
+
calls = decodeMultiSendCallOnly(shape.data);
|
|
277
|
+
}
|
|
278
|
+
catch (error) {
|
|
279
|
+
hostile(`the SafeTx batch does not decode: ${error.message}`);
|
|
280
|
+
}
|
|
281
|
+
const expectedCalls = [
|
|
282
|
+
{ to: ARC_USDC, data: encodeFunctionData({ abi: APPROVE_ABI, functionName: "approve",
|
|
283
|
+
args: [getAddress(RELAY_DEPOSITORY), ctx.amount] }).toLowerCase() },
|
|
284
|
+
{ to: RELAY_DEPOSITORY, data: encodeFunctionData({ abi: DEPOSIT_ABI, functionName: "depositErc20",
|
|
285
|
+
args: [getAddress(ctx.safe), getAddress(ARC_USDC), ctx.amount, orderId] }).toLowerCase() },
|
|
286
|
+
{ to: ARC_USDC, data: encodeFunctionData({ abi: TRANSFER_ABI, functionName: "transfer",
|
|
287
|
+
args: [getAddress(FELIX_FEE_TREASURY), POLYMARKET_FUNDING_FEE_UNITS] }).toLowerCase() },
|
|
288
|
+
];
|
|
289
|
+
if (calls.length !== 3 || calls.some((call, i) => call.operation !== 0
|
|
290
|
+
|| call.to.toLowerCase() !== expectedCalls[i].to || call.data.toLowerCase() !== expectedCalls[i].data)) {
|
|
291
|
+
hostile("the SafeTx does not make exactly the approve, the deposit for this order and the pinned network fee");
|
|
292
|
+
}
|
|
293
|
+
const disclosed = v.network_fee;
|
|
294
|
+
if (!isRecord(disclosed) || String(disclosed.fee_units) !== POLYMARKET_FUNDING_FEE_UNITS.toString()
|
|
295
|
+
|| String(disclosed.recipient || "").toLowerCase() !== FELIX_FEE_TREASURY
|
|
296
|
+
|| disclosed.refundable !== false || Number(disclosed.chain_id) !== ARC_MAINNET_CHAIN_ID) {
|
|
297
|
+
hostile("the disclosed network fee is not the fee in the SafeTx");
|
|
298
|
+
}
|
|
299
|
+
const claimed = String(st.safe_tx_hash || "").toLowerCase();
|
|
300
|
+
const typedData = rebuildTypedData(shape.data, shape.nonce, ctx.safe);
|
|
301
|
+
const digest = arcSafeTxHash(typedData).toLowerCase();
|
|
302
|
+
if (!HASH.test(claimed) || claimed !== digest || arcSafeTxHash(st.typed_data).toLowerCase() !== digest) {
|
|
303
|
+
hostile("the SafeTx digest is not the digest of the calls this client rebuilt");
|
|
304
|
+
}
|
|
305
|
+
return { fundingId, orderId, solver: recovered, safeTxHash: digest, nonce: shape.nonce, quoteExpiresAt,
|
|
306
|
+
orderDeadline: Number(output.deadline), signedMinimumUnits: paid.minimumAmount, typedData };
|
|
307
|
+
}
|
|
308
|
+
function rebuildTypedData(data, nonce, safe) {
|
|
309
|
+
return {
|
|
310
|
+
domain: { chainId: ARC_MAINNET_CHAIN_ID, verifyingContract: getAddress(safe) },
|
|
311
|
+
types: {
|
|
312
|
+
EIP712Domain: [{ name: "chainId", type: "uint256" }, { name: "verifyingContract", type: "address" }],
|
|
313
|
+
SafeTx: [
|
|
314
|
+
{ name: "to", type: "address" }, { name: "value", type: "uint256" }, { name: "data", type: "bytes" },
|
|
315
|
+
{ name: "operation", type: "uint8" }, { name: "safeTxGas", type: "uint256" },
|
|
316
|
+
{ name: "baseGas", type: "uint256" }, { name: "gasPrice", type: "uint256" },
|
|
317
|
+
{ name: "gasToken", type: "address" }, { name: "refundReceiver", type: "address" },
|
|
318
|
+
{ name: "nonce", type: "uint256" },
|
|
319
|
+
],
|
|
320
|
+
},
|
|
321
|
+
primaryType: "SafeTx",
|
|
322
|
+
message: {
|
|
323
|
+
to: SAFE_MULTISEND_CALL_ONLY, value: "0", data, operation: 1, safeTxGas: "0", baseGas: "0",
|
|
324
|
+
gasPrice: "0", gasToken: "0x0000000000000000000000000000000000000000",
|
|
325
|
+
refundReceiver: "0x0000000000000000000000000000000000000000", nonce: String(nonce),
|
|
326
|
+
},
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
/** Every later view: same funding, same Safe, owner, amount and order. */
|
|
330
|
+
export function assertView(view, plan) {
|
|
331
|
+
if (!isRecord(view))
|
|
332
|
+
hostile("the funding view is not an object");
|
|
333
|
+
const v = view;
|
|
334
|
+
if (v.phase === "source_not_executed") {
|
|
335
|
+
// Engine closed_funding_view (safe-invalidation closure): it carries no plan
|
|
336
|
+
// fields, so bind what it does carry -- this funding, the Polygon writer and,
|
|
337
|
+
// once this client journaled one, the exact SafeTx it names. Its claim is
|
|
338
|
+
// never accepted as proof here; the caller holds it as unverified.
|
|
339
|
+
const closure = isRecord(v.safe_invalidation_closure) ? v.safe_invalidation_closure : {};
|
|
340
|
+
if (v.id !== plan.fundingId || closure.operation_id !== plan.fundingId || closure.writer !== "polygon"
|
|
341
|
+
|| (plan.safeTxHash !== undefined && String(closure.safe_tx_hash || "").toLowerCase() !== plan.safeTxHash)
|
|
342
|
+
|| v.money_moved === false || v.owner_wallet_delivery_proven === true || v.venue_usable === true) {
|
|
343
|
+
hostile("the closure is not for this funding's exact SafeTx");
|
|
344
|
+
}
|
|
345
|
+
return v;
|
|
346
|
+
}
|
|
347
|
+
if (v.id !== plan.fundingId || v.kind !== "arc_polygon_funding")
|
|
348
|
+
hostile("the server answered for another funding");
|
|
349
|
+
if (lower(v.safe, "safe") !== plan.safe || lower(v.owner, "owner") !== plan.owner
|
|
350
|
+
|| lower(v.recipient, "recipient") !== plan.owner) {
|
|
351
|
+
hostile("the funding's Safe or owner changed");
|
|
352
|
+
}
|
|
353
|
+
if (units(v.amount_units, "amount_units") !== plan.amount)
|
|
354
|
+
hostile("the funding amount changed");
|
|
355
|
+
if (String(v.order_id || "").toLowerCase() !== plan.orderId)
|
|
356
|
+
hostile("the funding's order changed");
|
|
357
|
+
if (v.venue_usable === true)
|
|
358
|
+
hostile("an owner-wallet delivery is never venue usable");
|
|
359
|
+
return v;
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* RELAY_A5_FRESH_JOURNAL_2026_09_28: a funding the passive lookup found past
|
|
363
|
+
* "prepared" under THIS key, before this client journaled it (the journal that
|
|
364
|
+
* signed it was lost). Its signed order is no longer served, so only what the
|
|
365
|
+
* view binds is checked: this Safe, owner and amount (assertView), Arc USDC ->
|
|
366
|
+
* Polygon USDC.e for Polymarket, a solver the reviewed policy trusts, and
|
|
367
|
+
* credit bounds within this client's own floor. The result is a journal entry
|
|
368
|
+
* that is only ever RECONCILED: it carries no typed data and is never signed.
|
|
369
|
+
* Completion still needs this client's own Polygon read of the order's fill
|
|
370
|
+
* (verifyPolygonCredit); the Arc source SafeTx is bound on first sight.
|
|
371
|
+
*/
|
|
372
|
+
export function adoptLookedUp(view, ctx) {
|
|
373
|
+
const fundingId = typeof view.id === "string" && UUID.test(view.id) ? view.id : hostile("the looked-up funding id is invalid");
|
|
374
|
+
const orderId = String(view.order_id || "").toLowerCase();
|
|
375
|
+
if (!HASH.test(orderId))
|
|
376
|
+
hostile("the looked-up funding carries no order");
|
|
377
|
+
if (view.route_kind !== "arc_safe_to_polygon_owner_usdce" || view.route_intent !== "polymarket_funding"
|
|
378
|
+
|| view.source_chain_id !== ARC_MAINNET_CHAIN_ID || view.destination_chain_id !== POLYGON_CHAIN_ID
|
|
379
|
+
|| lower(view.destination_token, "destination_token") !== POLYGON_USDC_E) {
|
|
380
|
+
hostile("the looked-up funding is not an Arc USDC -> Polygon USDC.e Polymarket funding");
|
|
381
|
+
}
|
|
382
|
+
const solver = lower(view.solver, "solver");
|
|
383
|
+
if (!ctx.policy.trustedSolvers.map((s) => s.toLowerCase()).includes(solver)) {
|
|
384
|
+
hostile("the looked-up funding's solver is not one the reviewed policy trusts");
|
|
385
|
+
}
|
|
386
|
+
const minimum = units(view.minimum_credit_units, "minimum_credit_units");
|
|
387
|
+
const expected = units(view.expected_credit_units, "expected_credit_units");
|
|
388
|
+
if (minimum < floorUnits(ctx.amount) || minimum < (ctx.requestedMinimum ?? 0n) || minimum > expected || expected > ctx.amount) {
|
|
389
|
+
hostile("the looked-up funding's credit bounds are outside this client's floor");
|
|
390
|
+
}
|
|
391
|
+
const deadline = Number(view.order_deadline);
|
|
392
|
+
if (!Number.isSafeInteger(deadline) || deadline <= 0)
|
|
393
|
+
hostile("the looked-up funding's order deadline is invalid");
|
|
394
|
+
const source = isRecord(view.source) ? view.source : null;
|
|
395
|
+
const sourceDigest = source ? String(source.safe_tx_hash || "").toLowerCase() : "";
|
|
396
|
+
return {
|
|
397
|
+
funding_id: fundingId, order_id: orderId, solver, amount_units: ctx.amount.toString(), owner: ctx.owner, safe: ctx.safe,
|
|
398
|
+
signed_minimum_units: minimum.toString(), order_deadline: deadline,
|
|
399
|
+
safe_tx_hash: HASH.test(sourceDigest) ? sourceDigest : null,
|
|
400
|
+
adopted_by_lookup: true, adopted_phase: String(view.phase),
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
/** A credited view, bound to what THIS client journaled (engine public_view fields). */
|
|
404
|
+
export function assertCredit(view, prepared, signed) {
|
|
405
|
+
const credit = view.credit;
|
|
406
|
+
const source = view.source;
|
|
407
|
+
if (view.phase !== "credited" || view.money_moved !== true || view.owner_wallet_delivery_proven !== true
|
|
408
|
+
|| !isRecord(credit) || !isRecord(source)) {
|
|
409
|
+
hostile("the credited view carries no credit or source");
|
|
410
|
+
}
|
|
411
|
+
const src = source;
|
|
412
|
+
if (src.state !== "verified" || String(src.safe_tx_hash || "").toLowerCase() !== signed.safe_tx_hash
|
|
413
|
+
|| signed.safe_tx_hash !== prepared.safe_tx_hash || !HASH.test(String(src.tx_hash || ""))
|
|
414
|
+
|| String(src.amount_units) !== prepared.amount_units) {
|
|
415
|
+
hostile("the Arc source proof is not the SafeTx this client signed");
|
|
416
|
+
}
|
|
417
|
+
const fee = view.network_fee;
|
|
418
|
+
if (!isRecord(fee) || fee.state !== "paid"
|
|
419
|
+
|| String(fee.fee_units) !== POLYMARKET_FUNDING_FEE_UNITS.toString()
|
|
420
|
+
|| String(fee.recipient || "").toLowerCase() !== FELIX_FEE_TREASURY
|
|
421
|
+
|| String(fee.tx_hash || "").toLowerCase() !== String(src.tx_hash).toLowerCase()) {
|
|
422
|
+
hostile("the network fee is not reported paid in the source execution this client signed");
|
|
423
|
+
}
|
|
424
|
+
const c = credit;
|
|
425
|
+
const binding = c.order_binding;
|
|
426
|
+
if (c.state !== "credited" || Number(c.chain_id) !== POLYGON_CHAIN_ID || lower(c.recipient, "credit.recipient") !== String(prepared.owner)
|
|
427
|
+
|| lower(c.token, "credit.token") !== POLYGON_USDC_E || !HASH.test(String(c.tx_hash || ""))
|
|
428
|
+
|| !HASH.test(String(c.block_hash || "")) || !isRecord(binding)
|
|
429
|
+
|| String(binding.order_id || "").toLowerCase() !== prepared.order_id
|
|
430
|
+
|| lower(binding.solver, "order_binding.solver") !== prepared.solver
|
|
431
|
+
|| String(binding.tx_hash || "").toLowerCase() !== String(c.tx_hash).toLowerCase()) {
|
|
432
|
+
hostile("the credit is not this order's USDC.e fill to the owner");
|
|
433
|
+
}
|
|
434
|
+
const amount = units(c.amount_units, "credit.amount_units");
|
|
435
|
+
const minimum = BigInt(String(prepared.signed_minimum_units));
|
|
436
|
+
if (amount < minimum || amount > BigInt(String(prepared.amount_units)))
|
|
437
|
+
hostile("the credit is outside the signed bounds");
|
|
438
|
+
const blockNumber = Number(c.block_number);
|
|
439
|
+
if (!Number.isSafeInteger(blockNumber) || blockNumber <= 0)
|
|
440
|
+
hostile("the credit block is invalid");
|
|
441
|
+
return { owner: String(prepared.owner), orderId: String(prepared.order_id), solver: String(prepared.solver),
|
|
442
|
+
txHash: String(c.tx_hash).toLowerCase(), blockHash: String(c.block_hash).toLowerCase(), blockNumber,
|
|
443
|
+
amountUnits: amount, minimumUnits: minimum, orderDeadline: Number(prepared.order_deadline) };
|
|
444
|
+
}
|
|
445
|
+
/** The prediction_fund leg the continuation hands out: the SAME credited amount into THIS owner's PM wallet. */
|
|
446
|
+
export function assertPredictionFund(response, ctx) {
|
|
447
|
+
if (!isRecord(response))
|
|
448
|
+
hostile("the continuation answer is not an object");
|
|
449
|
+
const r = response;
|
|
450
|
+
if (r.funding_id !== ctx.fundingId || r.status !== "prediction_fund_prepared" || r.ok !== true) {
|
|
451
|
+
hostile("the continuation answered for another funding or state");
|
|
452
|
+
}
|
|
453
|
+
if (r.agent_wallet_funded !== false || r.owner_pm_usable !== false)
|
|
454
|
+
hostile("the continuation claims usability before evidence");
|
|
455
|
+
const fee = r.network_fee;
|
|
456
|
+
if (!isRecord(fee) || fee.state !== "paid_at_arc_source" || fee.second_charge !== false
|
|
457
|
+
|| String(fee.tx_hash || "").toLowerCase() !== ctx.sourceTxHash) {
|
|
458
|
+
hostile("the continuation does not bind the ONE fee paid at the Arc source");
|
|
459
|
+
}
|
|
460
|
+
const fund = r.prediction_fund;
|
|
461
|
+
if (!isRecord(fund))
|
|
462
|
+
hostile("prediction_fund is missing");
|
|
463
|
+
const p = fund;
|
|
464
|
+
if (p.operation !== "prediction_fund" || Number(p.chain_id) !== POLYGON_CHAIN_ID
|
|
465
|
+
|| lower(p.owner_address, "owner_address") !== ctx.owner
|
|
466
|
+
|| lower(p.source_token, "source_token") !== POLYGON_USDC_E
|
|
467
|
+
|| lower(p.destination_token, "destination_token") !== PUSD_POLYGON
|
|
468
|
+
|| lower(p.destination_wallet, "destination_wallet") !== ctx.pmWallet
|
|
469
|
+
|| lower(p.fixed_contract, "fixed_contract") !== PM_ONRAMP) {
|
|
470
|
+
hostile("the prediction_fund is not USDC.e -> pUSD into this owner's own PM wallet");
|
|
471
|
+
}
|
|
472
|
+
if (usdUnits(p.amount_usd, "amount_usd") !== ctx.creditedUnits
|
|
473
|
+
|| usdUnits(p.minimum_destination_usd, "minimum_destination_usd") !== ctx.creditedUnits) {
|
|
474
|
+
hostile("the prediction_fund amount is not exactly the credited USDC.e");
|
|
475
|
+
}
|
|
476
|
+
// Bound to the Arc-source payment: owes nothing more, and the fee instruction
|
|
477
|
+
// (if disclosed) is the Arc fee already paid -- this client never pays it again.
|
|
478
|
+
if (p.fee_status !== "paid" || typeof p.fee_obligation_id !== "string" || !UUID.test(p.fee_obligation_id)) {
|
|
479
|
+
hostile("the prediction_fund is not bound to the paid Arc-source fee");
|
|
480
|
+
}
|
|
481
|
+
const transfer = p.fee_transfer;
|
|
482
|
+
if (transfer !== undefined && (!isRecord(transfer) || Number(transfer.chain_id) !== ARC_MAINNET_CHAIN_ID
|
|
483
|
+
|| String(transfer.to || "").toLowerCase() !== FELIX_FEE_TREASURY
|
|
484
|
+
|| String(transfer.amount_units) !== POLYMARKET_FUNDING_FEE_UNITS.toString())) {
|
|
485
|
+
hostile("the prediction_fund discloses a fee other than the Arc-source fee");
|
|
486
|
+
}
|
|
487
|
+
if (typeof p.intent_token !== "string" || !p.intent_token || p.intent_token.length > 16_000) {
|
|
488
|
+
hostile("the prediction_fund intent token is invalid");
|
|
489
|
+
}
|
|
490
|
+
return p;
|
|
491
|
+
}
|
|
492
|
+
/** The grant this client may sign: THIS account, Polygon, this owner, within the local cap. */
|
|
493
|
+
export function assertGasGrantRequest(fund, ctx) {
|
|
494
|
+
const sponsorship = fund.gas_sponsorship;
|
|
495
|
+
const auth = isRecord(sponsorship) ? sponsorship.authorization : undefined;
|
|
496
|
+
if (!isRecord(sponsorship) || sponsorship.status !== "signature_required" || !isRecord(auth)) {
|
|
497
|
+
hostile("the gas sponsorship is not a grant request");
|
|
498
|
+
}
|
|
499
|
+
const a = auth;
|
|
500
|
+
const amount = units(typeof a.amount_wei === "number" ? String(a.amount_wei) : a.amount_wei, "gas grant amount_wei");
|
|
501
|
+
if (a.kind !== "user_grant" || String(a.user_id || "").toLowerCase() !== ctx.accountId
|
|
502
|
+
|| Number(a.chain_id) !== POLYGON_CHAIN_ID || lower(a.recipient, "gas grant recipient") !== ctx.owner
|
|
503
|
+
|| amount <= 0n || amount > POLYGON_GAS_GRANT_CAP_WEI
|
|
504
|
+
|| !Number.isSafeInteger(Number(a.sponsor_nonce)) || Number(a.sponsor_nonce) < 0) {
|
|
505
|
+
hostile("the gas grant is not for this account's owner on Polygon within the local cap");
|
|
506
|
+
}
|
|
507
|
+
return a;
|
|
508
|
+
}
|
|
509
|
+
// ------------------------------------------------------------------ driver
|
|
510
|
+
function httpStatus(response) {
|
|
511
|
+
const meta = isRecord(response._meta) ? response._meta : {};
|
|
512
|
+
const status = Number(meta.http_status);
|
|
513
|
+
return Number.isInteger(status) ? status : undefined;
|
|
514
|
+
}
|
|
515
|
+
function errorOf(response) {
|
|
516
|
+
if (isRecord(response.error))
|
|
517
|
+
return response.error;
|
|
518
|
+
const detail = isRecord(response.detail) ? response.detail.error : undefined;
|
|
519
|
+
return isRecord(detail) ? detail : {};
|
|
520
|
+
}
|
|
521
|
+
function definitiveRefusal(response) {
|
|
522
|
+
const status = httpStatus(response);
|
|
523
|
+
return status !== undefined && [400, 401, 403, 404, 409, 422].includes(status);
|
|
524
|
+
}
|
|
525
|
+
function failed(response) {
|
|
526
|
+
const status = httpStatus(response);
|
|
527
|
+
return response.ok === false || (status !== undefined && status >= 400);
|
|
528
|
+
}
|
|
529
|
+
export async function driveArcPolygonFunding(request, deps) {
|
|
530
|
+
// A funding adopted by the lookup after a lost journal may have been signed by
|
|
531
|
+
// the lost client: it counts as signed for every movement answer.
|
|
532
|
+
const adopted = () => deps.getCheckpoint(CP.prepared)?.adopted_by_lookup === true;
|
|
533
|
+
const signedAnything = () => Boolean(deps.getCheckpoint(CP.signed)) || adopted();
|
|
534
|
+
const movement = (view) => {
|
|
535
|
+
if (deps.getCheckpoint(CP.credited) || deps.getCheckpoint(CP.completed))
|
|
536
|
+
return true;
|
|
537
|
+
if (view && view.money_moved === true)
|
|
538
|
+
return true;
|
|
539
|
+
// After a local signature nothing the server SAYS proves "not moved".
|
|
540
|
+
if (signedAnything())
|
|
541
|
+
return "unknown";
|
|
542
|
+
return false;
|
|
543
|
+
};
|
|
544
|
+
const credited = () => deps.getCheckpoint(CP.credited);
|
|
545
|
+
const result = (ok, status, fields) => ({
|
|
546
|
+
ok, status, route: "arc_polygon_polymarket", account_id: deps.accountId,
|
|
547
|
+
funding_id: deps.getCheckpoint(CP.prepared)?.funding_id ?? null,
|
|
548
|
+
owner_wallet_delivery_proven: Boolean(credited()),
|
|
549
|
+
owner_pm_usable: false, agent_wallet_funded: false,
|
|
550
|
+
...(adopted() ? { adopted_by_lookup: true } : {}),
|
|
551
|
+
network_fee: { units: POLYMARKET_FUNDING_FEE_UNITS.toString(), recipient: FELIX_FEE_TREASURY,
|
|
552
|
+
refundable: false, disclosure: POLYGON_FEE_DISCLOSURE },
|
|
553
|
+
...fields,
|
|
554
|
+
money_moved: fields.money_moved ?? movement(), user_funds_moved: fields.money_moved ?? movement(),
|
|
555
|
+
});
|
|
556
|
+
const refuse = (code, message, extra = {}) => result(false, "refused", { error: { code, message }, money_moved: movement(), ...extra });
|
|
557
|
+
const hold = (code, message, view, extra = {}) => result(false, "reconciliation_required", {
|
|
558
|
+
error: { code, message }, money_moved: movement(view), reconciliation_required: true,
|
|
559
|
+
next_action: "reconcile_do_not_resign", server_reason: view?.reason ?? null, ...extra,
|
|
560
|
+
});
|
|
561
|
+
// SAFE_NONCE_INVALIDATION_2026_09_28 (A3a): the exact call that releases this
|
|
562
|
+
// funding's reserved Safe nonce, never a fresh prepare.
|
|
563
|
+
const release = (fundingId, reason) => {
|
|
564
|
+
const p = deps.getCheckpoint(CP.prepared);
|
|
565
|
+
return {
|
|
566
|
+
next_action: SAFE_INVALIDATION_TOOL,
|
|
567
|
+
safe_nonce_invalidation: invalidationSuggestion("polygon", String(fundingId ?? p?.funding_id ?? ""), typeof p?.nonce === "number" ? p.nonce : null, reason),
|
|
568
|
+
};
|
|
569
|
+
};
|
|
570
|
+
// SAFE_NONCE_HARDENING_2026_09_28 (engine A5 closure): 'closed' is TERMINAL. Felix
|
|
571
|
+
// support closed a held funding whose Arc source executed (operator_close:
|
|
572
|
+
// only reconciliation_required with verified source evidence). It is final and
|
|
573
|
+
// no longer holds the account's one-open slot; nothing more is submitted,
|
|
574
|
+
// signed or invalidated. The resolution is Felix's record, not a proof here,
|
|
575
|
+
// and it never reports owner-wallet delivery or Polymarket use.
|
|
576
|
+
const operatorClosed = (view) => {
|
|
577
|
+
const raw = isRecord(view.resolution) ? view.resolution : {};
|
|
578
|
+
const resolution = {
|
|
579
|
+
outcome: typeof raw.outcome === "string" ? raw.outcome : null,
|
|
580
|
+
closed_at: Number.isSafeInteger(raw.closed_at) ? raw.closed_at : null,
|
|
581
|
+
held_reason: typeof raw.held_reason === "string" ? raw.held_reason : null,
|
|
582
|
+
note: typeof raw.note === "string" ? raw.note.slice(0, 500) : null,
|
|
583
|
+
};
|
|
584
|
+
return result(false, "closed", {
|
|
585
|
+
error: { code: "arc_polygon_closed_by_operator",
|
|
586
|
+
message: "Felix support closed this funding after its Arc source executed and it was held (resolution: "
|
|
587
|
+
+ `${resolution.outcome ?? "unspecified"}). The journey is final: nothing more is submitted or signed, `
|
|
588
|
+
+ "and it no longer blocks a new funding. This client has not verified the resolution and this funding "
|
|
589
|
+
+ "did not fund Polymarket; check the Arc Safe and the owner's Polygon balances." },
|
|
590
|
+
funding_id: view.id ?? null, server_phase: "closed", terminal: true, verified: false, resolution,
|
|
591
|
+
...(Array.isArray(view.refunds) ? { refunds: view.refunds } : {}),
|
|
592
|
+
money_moved: movement(view), owner_pm_usable: false, next_action: "none",
|
|
593
|
+
});
|
|
594
|
+
};
|
|
595
|
+
// -------- request and policy: refuse before any request
|
|
596
|
+
const amount = request.amount_units;
|
|
597
|
+
const requestedMinimum = request.minimum_credit_units;
|
|
598
|
+
if (amount < MIN_AMOUNT_UNITS || amount > MAX_AMOUNT_UNITS) {
|
|
599
|
+
return refuse("arc_polygon_amount_invalid", "amount_units must be 5 to 25 USDC.");
|
|
600
|
+
}
|
|
601
|
+
if (requestedMinimum !== null && (requestedMinimum <= 0n || requestedMinimum > amount)) {
|
|
602
|
+
return refuse("arc_polygon_minimum_invalid", "minimum_credit_units must be positive and no more than the amount.");
|
|
603
|
+
}
|
|
604
|
+
const accountId = typeof deps.accountId === "string" ? deps.accountId.toLowerCase() : "";
|
|
605
|
+
if (!UUID.test(accountId))
|
|
606
|
+
return refuse("child_account_required", "Select the funding account with use_child_account first.");
|
|
607
|
+
const owner = typeof deps.owner === "string" && ADDRESS.test(deps.owner) ? deps.owner.toLowerCase() : "";
|
|
608
|
+
if (!owner)
|
|
609
|
+
return refuse("client_signature_required", "A local owner key is required.");
|
|
610
|
+
const gaps = policyGaps(deps.policy);
|
|
611
|
+
if (gaps.length) {
|
|
612
|
+
return refuse("arc_polygon_policy_unverified", "This client has no reviewed evidence for every release gate of the Arc -> Polygon Polymarket route; "
|
|
613
|
+
+ "nothing was prepared or signed.", { policy_gaps: gaps, fallback: "arc_home_fund_venue (venue polymarket)" });
|
|
614
|
+
}
|
|
615
|
+
// A thrown transport error is an UNKNOWN outcome, never a client failure.
|
|
616
|
+
const api = async (method, path, body, opts) => {
|
|
617
|
+
try {
|
|
618
|
+
const out = await deps.call(method, path, body, opts);
|
|
619
|
+
return isRecord(out) ? out : { ok: false, error: { code: "invalid_response", outcome_unknown: true } };
|
|
620
|
+
}
|
|
621
|
+
catch (error) {
|
|
622
|
+
return { ok: false, error: { code: "transport_lost", outcome_unknown: true,
|
|
623
|
+
message: String(error?.message || error).slice(0, 200) } };
|
|
624
|
+
}
|
|
625
|
+
};
|
|
626
|
+
const startedAt = deps.now();
|
|
627
|
+
const budget = deps.pollBudgetMs ?? 45_000;
|
|
628
|
+
const maxPolls = deps.maxPolls ?? DEFAULT_MAX_POLLS;
|
|
629
|
+
let polls = 0;
|
|
630
|
+
let delay = MIN_POLL_MS;
|
|
631
|
+
const pause = async () => { await deps.sleep(delay); delay = Math.min(MAX_POLL_MS, delay * 2); };
|
|
632
|
+
const outOfBudget = () => polls >= maxPolls || deps.now() - startedAt > budget;
|
|
633
|
+
try {
|
|
634
|
+
const safe = lower(await deps.expectedSafe(), "verified Arc home Safe");
|
|
635
|
+
const scope = { account_id: accountId, owner, safe, amount_units: amount.toString(),
|
|
636
|
+
minimum_credit_units: requestedMinimum === null ? null : requestedMinimum.toString() };
|
|
637
|
+
const savedScope = deps.getCheckpoint(CP.scope);
|
|
638
|
+
if (savedScope && JSON.stringify(savedScope) !== JSON.stringify(scope)) {
|
|
639
|
+
return refuse("arc_polygon_scope_conflict", "This idempotency key belongs to a different account, Safe, owner or amount.");
|
|
640
|
+
}
|
|
641
|
+
if (!savedScope)
|
|
642
|
+
deps.saveCheckpoint(CP.scope, scope);
|
|
643
|
+
const done = deps.getCheckpoint(CP.completed);
|
|
644
|
+
if (done && isRecord(done.result))
|
|
645
|
+
return done.result;
|
|
646
|
+
// -------- prepare (idempotent by key), verified before it is saved
|
|
647
|
+
// The ONE prepare request: sent once to prepare, and replayed byte-for-byte
|
|
648
|
+
// (same key) as the fresh admission check immediately before signing.
|
|
649
|
+
const prepareBody = { account_id: accountId, amount_units: Number(amount), route_intent: "polymarket_funding",
|
|
650
|
+
...(requestedMinimum === null ? {} : { minimum_credit_units: Number(requestedMinimum) }) };
|
|
651
|
+
const prepareKey = deps.stageKey("pgfund-prepare");
|
|
652
|
+
let prepared = deps.getCheckpoint(CP.prepared);
|
|
653
|
+
if (!prepared) {
|
|
654
|
+
// A lost prepare answer: the PASSIVE owner-scoped lookup finds the funding
|
|
655
|
+
// this key already created (reachable during a freeze, halt or containment;
|
|
656
|
+
// no quote, nonce, grant or write). A found funding is never permission to
|
|
657
|
+
// sign -- the signing-time admission replay below still decides. 404 only
|
|
658
|
+
// means none exists under this key; only then is a new prepare requested.
|
|
659
|
+
const found = await api("GET", `${ROUTE_PREFIX}/lookup?account_id=${encodeURIComponent(accountId)}`, undefined, { idempotencyKey: prepareKey });
|
|
660
|
+
if (!failed(found)) {
|
|
661
|
+
if (found.phase !== "prepared") {
|
|
662
|
+
// RELAY_A5_FRESH_JOURNAL_2026_09_28: created under this key and already
|
|
663
|
+
// advanced before THIS journal saw it -- typically signed by a client whose
|
|
664
|
+
// journal was lost. Never "never signed", never a re-prepare or a new
|
|
665
|
+
// signature: adopt its bound identity and RECONCILE it (the credit is
|
|
666
|
+
// proven by this client's own Polygon read; the Polymarket leg follows).
|
|
667
|
+
if (found.phase === "source_not_executed") {
|
|
668
|
+
assertView(found, { fundingId: String(found.id), owner, safe, amount, orderId: "" });
|
|
669
|
+
return hold("arc_polygon_closure_reported_unverified", "Felix reports that this key's funding was closed after its Safe nonce was invalidated (its original "
|
|
670
|
+
+ "calls were not committed). This client has not verified that claim. Do not start a new funding "
|
|
671
|
+
+ "until reconciled.", found, { funding_id: found.id, server_phase: "source_not_executed", verified: false,
|
|
672
|
+
next_action: "none" });
|
|
673
|
+
}
|
|
674
|
+
const v = assertView(found, { fundingId: String(found.id), owner, safe, amount,
|
|
675
|
+
orderId: String(found.order_id || "").toLowerCase() });
|
|
676
|
+
if (v.phase === "closed")
|
|
677
|
+
return operatorClosed(v);
|
|
678
|
+
const adoptedPlan = adoptLookedUp(v, { owner, safe, amount, requestedMinimum, policy: deps.policy });
|
|
679
|
+
deps.saveCheckpoint(CP.prepared, adoptedPlan);
|
|
680
|
+
prepared = adoptedPlan;
|
|
681
|
+
}
|
|
682
|
+
else {
|
|
683
|
+
const plan = await verifyPrepared(found, {
|
|
684
|
+
owner, safe, amount, requestedMinimum, nowS: Math.floor(deps.now() / 1000), policy: deps.policy,
|
|
685
|
+
});
|
|
686
|
+
prepared = {
|
|
687
|
+
funding_id: plan.fundingId, order_id: plan.orderId, solver: plan.solver, safe_tx_hash: plan.safeTxHash,
|
|
688
|
+
nonce: plan.nonce, quote_expires_at: plan.quoteExpiresAt, order_deadline: plan.orderDeadline,
|
|
689
|
+
amount_units: amount.toString(), owner, safe,
|
|
690
|
+
signed_minimum_units: plan.signedMinimumUnits.toString(), typed_data: plan.typedData,
|
|
691
|
+
recovered_by_lookup: true,
|
|
692
|
+
};
|
|
693
|
+
deps.saveCheckpoint(CP.prepared, prepared);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
else if (httpStatus(found) !== 404) {
|
|
697
|
+
if (definitiveRefusal(found)) {
|
|
698
|
+
return refuse(String(errorOf(found).reason || errorOf(found).code || "arc_polygon_lookup_refused"), "Felix refused the lookup for this key; nothing was prepared or signed.", { server_error: errorOf(found) });
|
|
699
|
+
}
|
|
700
|
+
return result(false, "in_progress", { money_moved: false, next_action: "resume_with_same_idempotency_key",
|
|
701
|
+
error: { code: "arc_polygon_lookup_unavailable", message: "Retry with the same key; nothing was signed." } });
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
if (!prepared) {
|
|
705
|
+
const response = await api("POST", `${ROUTE_PREFIX}/prepare`, prepareBody, { idempotencyKey: prepareKey });
|
|
706
|
+
if (response.ok === false && !definitiveRefusal(response) && httpStatus(response) === undefined) {
|
|
707
|
+
return result(false, "in_progress", { money_moved: false, next_action: "resume_with_same_idempotency_key",
|
|
708
|
+
error: { code: "arc_polygon_prepare_outcome_unknown", message: "Retry with the same key; nothing was signed." } });
|
|
709
|
+
}
|
|
710
|
+
if (failed(response)) {
|
|
711
|
+
// B5: an in_progress refusal names this account's own open funding; A3a:
|
|
712
|
+
// a reserved-nonce refusal names the invalidation that releases it.
|
|
713
|
+
const open = openJourneyId(response);
|
|
714
|
+
const guidance = open
|
|
715
|
+
? await describeOpenJourney(api, { id: open, readPath: `${ROUTE_PREFIX}/${open}`, accountId,
|
|
716
|
+
writer: "polygon", resumeTool: ARC_POLYGON_TOOL })
|
|
717
|
+
: safeNonceRefusalGuidance(response) ?? {};
|
|
718
|
+
return refuse(String(errorOf(response).reason || errorOf(response).code || "arc_polygon_prepare_refused"), "Felix did not prepare the funding; nothing was signed.", { server_error: errorOf(response), ...guidance });
|
|
719
|
+
}
|
|
720
|
+
const plan = await verifyPrepared(response, {
|
|
721
|
+
owner, safe, amount, requestedMinimum, nowS: Math.floor(deps.now() / 1000), policy: deps.policy,
|
|
722
|
+
});
|
|
723
|
+
prepared = {
|
|
724
|
+
funding_id: plan.fundingId, order_id: plan.orderId, solver: plan.solver, safe_tx_hash: plan.safeTxHash,
|
|
725
|
+
nonce: plan.nonce, quote_expires_at: plan.quoteExpiresAt, order_deadline: plan.orderDeadline,
|
|
726
|
+
amount_units: amount.toString(), owner, safe,
|
|
727
|
+
signed_minimum_units: plan.signedMinimumUnits.toString(), typed_data: plan.typedData,
|
|
728
|
+
};
|
|
729
|
+
deps.saveCheckpoint(CP.prepared, prepared);
|
|
730
|
+
}
|
|
731
|
+
const plan = { fundingId: String(prepared.funding_id), owner, safe, amount, orderId: String(prepared.order_id),
|
|
732
|
+
safeTxHash: HASH.test(String(prepared.safe_tx_hash || "")) ? String(prepared.safe_tx_hash) : undefined };
|
|
733
|
+
const base = `${ROUTE_PREFIX}/${plan.fundingId}`;
|
|
734
|
+
// -------- sign once: fresh server read, fresh gates, then journal the bytes
|
|
735
|
+
if (!deps.getCheckpoint(CP.signed) && !credited() && !adopted()) {
|
|
736
|
+
const read = await api("GET", `${base}?account_id=${encodeURIComponent(accountId)}`);
|
|
737
|
+
if (failed(read)) {
|
|
738
|
+
if (definitiveRefusal(read))
|
|
739
|
+
return hold(String(errorOf(read).reason || "arc_polygon_read_refused"), "Felix would not read the funding.");
|
|
740
|
+
return result(false, "in_progress", { error: { code: "arc_polygon_read_unavailable", message: "Retry with the same key." } });
|
|
741
|
+
}
|
|
742
|
+
const current = assertView(read, plan);
|
|
743
|
+
if (current.phase === "closed")
|
|
744
|
+
return operatorClosed(current);
|
|
745
|
+
if (current.phase !== "prepared") {
|
|
746
|
+
const proven = current.money_moved === true || isRecord(current.source)
|
|
747
|
+
|| ["credited", "refunded", "source_confirmed", "source_not_executed"].includes(String(current.phase));
|
|
748
|
+
return result(false, String(current.phase), {
|
|
749
|
+
money_moved: "unknown", ...(proven ? { next_action: "reconcile" } : release()),
|
|
750
|
+
error: { code: "arc_polygon_unsigned_funding_advanced",
|
|
751
|
+
message: "Felix stopped offering this funding before this client signed it. It is being "
|
|
752
|
+
+ "observed for an execution of the exact issued transaction; do not prepare a new one." },
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
const again = await verifyPrepared(current, {
|
|
756
|
+
owner, safe, amount, requestedMinimum, nowS: Math.floor(deps.now() / 1000), policy: deps.policy,
|
|
757
|
+
});
|
|
758
|
+
if (again.orderId !== prepared.order_id || again.safeTxHash !== prepared.safe_tx_hash || again.nonce !== prepared.nonce) {
|
|
759
|
+
hostile("the server changed the prepared order or SafeTx");
|
|
760
|
+
}
|
|
761
|
+
if (again.quoteExpiresAt - Math.floor(deps.now() / 1000) < QUOTE_SIGNING_MARGIN_S) {
|
|
762
|
+
return result(false, "in_progress", { error: { code: "arc_polygon_quote_expiring",
|
|
763
|
+
message: "The quote is too close to expiry to sign. Nothing was signed; it will expire." } });
|
|
764
|
+
}
|
|
765
|
+
let runtimeOk = false;
|
|
766
|
+
let safeOk = false;
|
|
767
|
+
try {
|
|
768
|
+
runtimeOk = (await deps.policy.verifyDepositoryRuntime()) === true;
|
|
769
|
+
}
|
|
770
|
+
catch {
|
|
771
|
+
runtimeOk = false;
|
|
772
|
+
}
|
|
773
|
+
try {
|
|
774
|
+
safeOk = (await deps.policy.verifySafeState(safe, Number(prepared.nonce))) === true;
|
|
775
|
+
}
|
|
776
|
+
catch {
|
|
777
|
+
safeOk = false;
|
|
778
|
+
}
|
|
779
|
+
if (!runtimeOk)
|
|
780
|
+
return refuse("arc_polygon_depository_runtime_unverified", "The depository runtime is not proven; nothing was signed.");
|
|
781
|
+
if (!safeOk)
|
|
782
|
+
return refuse("arc_polygon_safe_state_unverified", "The Safe's nonce/owners are not proven; nothing was signed.");
|
|
783
|
+
const signingS = Math.floor(deps.now() / 1000);
|
|
784
|
+
if (again.quoteExpiresAt - signingS < QUOTE_SIGNING_MARGIN_S || again.orderDeadline - signingS < ORDER_DEADLINE_MARGIN_S) {
|
|
785
|
+
return result(false, "in_progress", { error: { code: "arc_polygon_quote_expiring",
|
|
786
|
+
message: "The quote expired while its proofs were read. Nothing was signed; it will expire." } });
|
|
787
|
+
}
|
|
788
|
+
// Fresh admission AFTER the slow policy reads, immediately before signing:
|
|
789
|
+
// the same-key prepare replay runs the engine's full new-work admission
|
|
790
|
+
// (freeze, halt, the account's containment) and must hand back this exact
|
|
791
|
+
// funding. A passive status read is not admission. Nothing is signed on refusal.
|
|
792
|
+
const admitted = await api("POST", `${ROUTE_PREFIX}/prepare`, prepareBody, { idempotencyKey: prepareKey });
|
|
793
|
+
if (failed(admitted)) {
|
|
794
|
+
if (definitiveRefusal(admitted) || (httpStatus(admitted) ?? 0) >= 500) {
|
|
795
|
+
return refuse(String(errorOf(admitted).reason || errorOf(admitted).code || "arc_polygon_admission_refused"), "Felix did not re-admit this funding at signing time; nothing was signed.", { server_error: errorOf(admitted) });
|
|
796
|
+
}
|
|
797
|
+
return result(false, "in_progress", { error: { code: "arc_polygon_admission_unknown",
|
|
798
|
+
message: "The signing-time admission check did not answer; nothing was signed. Retry with the same key." } });
|
|
799
|
+
}
|
|
800
|
+
const readmitted = await verifyPrepared(admitted, {
|
|
801
|
+
owner, safe, amount, requestedMinimum, nowS: Math.floor(deps.now() / 1000), policy: deps.policy,
|
|
802
|
+
});
|
|
803
|
+
if (readmitted.fundingId !== plan.fundingId || readmitted.orderId !== prepared.order_id
|
|
804
|
+
|| readmitted.safeTxHash !== prepared.safe_tx_hash || readmitted.nonce !== prepared.nonce) {
|
|
805
|
+
hostile("the signing-time admission answered with another funding, order or SafeTx");
|
|
806
|
+
}
|
|
807
|
+
const signature = await deps.signSafeTx(prepared.typed_data);
|
|
808
|
+
if (!/^0x[0-9a-fA-F]{130}$/.test(signature))
|
|
809
|
+
return refuse("client_signing_failed", "The local signature is malformed; nothing was sent.");
|
|
810
|
+
deps.saveCheckpoint(CP.signed, { funding_id: plan.fundingId, safe_tx_hash: prepared.safe_tx_hash, signature,
|
|
811
|
+
signed_at_ms: deps.now() });
|
|
812
|
+
}
|
|
813
|
+
// -------- submit the SAME bytes at most once per invocation; reconcile until credited
|
|
814
|
+
if (!credited()) {
|
|
815
|
+
const signed = deps.getCheckpoint(CP.signed);
|
|
816
|
+
if (signed && (signed.funding_id !== plan.fundingId || signed.safe_tx_hash !== prepared.safe_tx_hash)) {
|
|
817
|
+
hostile("the journaled signature is for another funding");
|
|
818
|
+
}
|
|
819
|
+
if (!signed && !adopted())
|
|
820
|
+
hostile("the funding advanced without a journaled signature");
|
|
821
|
+
// B2: a definitive submit refusal, surfaced with the step that resolves it.
|
|
822
|
+
const submitRefusal = (response) => {
|
|
823
|
+
const error = errorOf(response);
|
|
824
|
+
const code = String(error.reason || error.code || "arc_polygon_submit_refused");
|
|
825
|
+
const expiresAt = Number(prepared.quote_expires_at);
|
|
826
|
+
const common = { money_moved: movement(), submit_refused: true, server_error: error,
|
|
827
|
+
quote_expires_at: Number.isSafeInteger(expiresAt) ? expiresAt : null };
|
|
828
|
+
if (error.next_action === ENGINE_OBSERVE_NEXT_ACTION || /(expired|safe_nonce_changed)$/.test(code)) {
|
|
829
|
+
return result(false, "submit_refused", { ...common, ...release(),
|
|
830
|
+
error: { code, message: "Felix will not submit this funding. It is observed for the exact signed SafeTx; "
|
|
831
|
+
+ "invalidate its Safe nonce to cancel it for good. Do not prepare a new funding meanwhile." } });
|
|
832
|
+
}
|
|
833
|
+
const [next, message] = code === "arc_admission_frozen"
|
|
834
|
+
? ["resume_before_quote_expiry", "Felix paused new Arc money movement (for example during a deploy). The "
|
|
835
|
+
+ "signature is journaled; resume with the same idempotency_key before quote_expires_at."]
|
|
836
|
+
: /insufficient_balance$/.test(code)
|
|
837
|
+
? ["fund_safe_then_resume", "The Arc home Safe does not hold the amount plus the network fee. Add USDC to "
|
|
838
|
+
+ "the Safe, then resume with the same idempotency_key before quote_expires_at."]
|
|
839
|
+
: ["resume_with_same_idempotency_key", "Felix refused the submission now. The signature is journaled; "
|
|
840
|
+
+ "resume with the same idempotency_key before quote_expires_at to offer the SAME bytes again."];
|
|
841
|
+
return result(false, "submit_refused", { ...common, next_action: next, error: { code, message },
|
|
842
|
+
...(code === "arc_admission_frozen" ? { safe_nonce_invalidation_if_expired: release().safe_nonce_invalidation } : {}) });
|
|
843
|
+
};
|
|
844
|
+
let offered = false;
|
|
845
|
+
for (;;) {
|
|
846
|
+
if (outOfBudget()) {
|
|
847
|
+
return result(true, "in_progress", { money_moved: movement(), next_action: "resume_with_same_idempotency_key" });
|
|
848
|
+
}
|
|
849
|
+
polls += 1;
|
|
850
|
+
const current = await api("POST", `${base}/reconcile`, { account_id: accountId }, { retryOnError: true });
|
|
851
|
+
if (failed(current)) {
|
|
852
|
+
if (httpStatus(current) === 404)
|
|
853
|
+
hostile("the server lost the funding");
|
|
854
|
+
if (definitiveRefusal(current)) {
|
|
855
|
+
return hold(String(errorOf(current).reason || "arc_polygon_reconcile_refused"), "Felix refused to advance the funding. Nothing more is signed.");
|
|
856
|
+
}
|
|
857
|
+
await pause();
|
|
858
|
+
continue;
|
|
859
|
+
}
|
|
860
|
+
const view = assertView(current, plan);
|
|
861
|
+
const phase = String(view.phase);
|
|
862
|
+
if (phase === "prepared") {
|
|
863
|
+
if (!signed)
|
|
864
|
+
hostile("an adopted funding went back to prepared");
|
|
865
|
+
if (offered) {
|
|
866
|
+
await pause();
|
|
867
|
+
continue;
|
|
868
|
+
}
|
|
869
|
+
offered = true;
|
|
870
|
+
if (!deps.getCheckpoint(CP.submission))
|
|
871
|
+
deps.saveCheckpoint(CP.submission, { funding_id: plan.fundingId });
|
|
872
|
+
// Exactly one transport attempt with the journaled bytes; never re-signed.
|
|
873
|
+
// A refusal before the journal (e.g. an exhausted sponsorship budget)
|
|
874
|
+
// leaves it prepared; a later invocation offers the SAME bytes again.
|
|
875
|
+
const submitted = await api("POST", `${base}/submit`, { account_id: accountId, safe_signature: signed.signature }, { retryOnError: false });
|
|
876
|
+
// B2: a DEFINITIVE refusal is surfaced now; a lost/5xx answer is resolved by reconcile.
|
|
877
|
+
if (failed(submitted) && definitiveRefusal(submitted))
|
|
878
|
+
return submitRefusal(submitted);
|
|
879
|
+
continue;
|
|
880
|
+
}
|
|
881
|
+
if (phase === "credited") {
|
|
882
|
+
let binding = signed;
|
|
883
|
+
if (!binding) {
|
|
884
|
+
// Adopted: bind the Arc source's SafeTx once, from the first credited view.
|
|
885
|
+
const source = isRecord(view.source) ? view.source : {};
|
|
886
|
+
const digest = String(source.safe_tx_hash || "").toLowerCase();
|
|
887
|
+
if (!HASH.test(digest))
|
|
888
|
+
hostile("the adopted funding's credited view names no source SafeTx");
|
|
889
|
+
if (!HASH.test(String(prepared.safe_tx_hash || ""))) {
|
|
890
|
+
prepared = { ...prepared, safe_tx_hash: digest };
|
|
891
|
+
deps.saveCheckpoint(CP.prepared, prepared);
|
|
892
|
+
}
|
|
893
|
+
binding = { safe_tx_hash: String(prepared.safe_tx_hash) };
|
|
894
|
+
}
|
|
895
|
+
const claim = assertCredit(view, prepared, binding);
|
|
896
|
+
let proven = false;
|
|
897
|
+
try {
|
|
898
|
+
proven = (await deps.policy.verifyPolygonCredit(claim)) === true;
|
|
899
|
+
}
|
|
900
|
+
catch {
|
|
901
|
+
proven = false;
|
|
902
|
+
}
|
|
903
|
+
if (!proven) {
|
|
904
|
+
await pause();
|
|
905
|
+
continue;
|
|
906
|
+
} // no independent read, no credit
|
|
907
|
+
deps.saveCheckpoint(CP.credited, {
|
|
908
|
+
funding_id: plan.fundingId, credited_units: claim.amountUnits.toString(), credit_tx_hash: claim.txHash,
|
|
909
|
+
source_tx_hash: String(view.source.tx_hash).toLowerCase(),
|
|
910
|
+
});
|
|
911
|
+
break;
|
|
912
|
+
}
|
|
913
|
+
if (phase === "refunded") {
|
|
914
|
+
return hold("arc_polygon_refund_reported_unverified", "Felix reports that Relay refunded this funding. This client has not verified the refund; check the "
|
|
915
|
+
+ "Arc Safe and the owner's Polygon balances. Do not start a new funding until reconciled.", view, { server_phase: "refunded", verified: false });
|
|
916
|
+
}
|
|
917
|
+
if (phase === "closed")
|
|
918
|
+
return operatorClosed(view);
|
|
919
|
+
if (phase === "source_not_executed") {
|
|
920
|
+
return hold("arc_polygon_closure_reported_unverified", "Felix reports that the funding's original Safe calls were not committed (closure). This client has "
|
|
921
|
+
+ "not verified that claim and holds a signed SafeTx; check the Arc Safe balance and nonce. Do not "
|
|
922
|
+
+ "start a new funding until reconciled.", view, { server_phase: "source_not_executed", verified: false });
|
|
923
|
+
}
|
|
924
|
+
if (phase === "reconciliation_required") {
|
|
925
|
+
if (view.next_action === ENGINE_OBSERVE_NEXT_ACTION) {
|
|
926
|
+
// A3a: the issued SafeTx is released only by the owner's no-op at its nonce.
|
|
927
|
+
return hold("arc_polygon_observe_only", "Felix is observing the issued transaction; nothing more is "
|
|
928
|
+
+ "submitted. Its Safe nonce stays reserved until the owner invalidates it.", view, release());
|
|
929
|
+
}
|
|
930
|
+
await pause(); // source_proof_pending and similar holds resolve by reconcile
|
|
931
|
+
continue;
|
|
932
|
+
}
|
|
933
|
+
await pause(); // submitted / source_confirmed
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
// -------- Polymarket leg: only after an independently verified owner-wallet credit
|
|
937
|
+
const credit = credited();
|
|
938
|
+
const creditedUnits = BigInt(String(credit.credited_units));
|
|
939
|
+
const pmWallet = lower(await deps.expectedPmWallet(), "the account's Polymarket wallet");
|
|
940
|
+
let pm = deps.getCheckpoint(CP.pmPrepared);
|
|
941
|
+
const pmBody = (grant) => ({ account_id: accountId, ...(grant ? { gas_grant: grant } : {}) });
|
|
942
|
+
const fetchPm = async (grant) => {
|
|
943
|
+
const response = await api("POST", `${base}/polymarket/prepare`, pmBody(grant), { retryOnError: true });
|
|
944
|
+
if (failed(response)) {
|
|
945
|
+
if (definitiveRefusal(response)) {
|
|
946
|
+
const code = String(errorOf(response).reason || errorOf(response).code || "arc_polygon_pm_prepare_refused");
|
|
947
|
+
if (code === "arc_polymarket_relay_gas_grant_sequence_taken")
|
|
948
|
+
return undefined; // another request holds it: re-read
|
|
949
|
+
return hold(code, "Felix refused the Polymarket step. The USDC.e was credited to your own Polygon wallet; "
|
|
950
|
+
+ "its current balance is not re-verified here.");
|
|
951
|
+
}
|
|
952
|
+
return undefined;
|
|
953
|
+
}
|
|
954
|
+
if (response.status === "prediction_fund_prepare_expired") {
|
|
955
|
+
return hold("arc_polygon_pm_prepare_expired", "The original Polymarket funding intent expired and is never reissued; confirm its transactions or "
|
|
956
|
+
+ "contact support. The USDC.e was credited to your own Polygon wallet; its current balance is not "
|
|
957
|
+
+ "re-verified here.", undefined, { next_action: String(response.next_action || "contact_support") });
|
|
958
|
+
}
|
|
959
|
+
return assertPredictionFund(response, { fundingId: plan.fundingId, owner, pmWallet, creditedUnits,
|
|
960
|
+
sourceTxHash: String(credit.source_tx_hash) });
|
|
961
|
+
};
|
|
962
|
+
const isHold = (value) => Boolean(value && value.status === "reconciliation_required");
|
|
963
|
+
// What this client journaled of the pUSD leg, by stage. A wrap that was ever
|
|
964
|
+
// STARTED may have been broadcast: evidence only, never a second wrap. An
|
|
965
|
+
// approval alone is recoverable on the SAME child: the wrap never started.
|
|
966
|
+
const journaled = () => {
|
|
967
|
+
const stages = new Set();
|
|
968
|
+
const last = deps.getCheckpoint(CP.pmLastSubmitted);
|
|
969
|
+
const transactions = (Array.isArray(last?.transactions) ? last.transactions : []).filter(isRecord);
|
|
970
|
+
for (const t of transactions)
|
|
971
|
+
stages.add(String(t.stage));
|
|
972
|
+
const started = deps.getCheckpoint(CP.pmBroadcastStarted);
|
|
973
|
+
if (started)
|
|
974
|
+
stages.add(String(started.stage));
|
|
975
|
+
return { stages, transactions };
|
|
976
|
+
};
|
|
977
|
+
const execute = async (fund, approvalAlreadySent = false) => {
|
|
978
|
+
// Fresh admission immediately before local pUSD signing: the SAME child's
|
|
979
|
+
// replay runs the route's freeze/halt/containment gates again.
|
|
980
|
+
polls += 1;
|
|
981
|
+
const admitted = await fetchPm();
|
|
982
|
+
if (isHold(admitted))
|
|
983
|
+
return admitted;
|
|
984
|
+
if (!admitted) {
|
|
985
|
+
return result(true, "in_progress", { money_moved: true, next_action: "resume_with_same_idempotency_key",
|
|
986
|
+
error: { code: "arc_polygon_pm_admission_unknown", message: "The pUSD admission check did not answer; nothing was sent." } });
|
|
987
|
+
}
|
|
988
|
+
if (admitted.intent_token !== fund.intent_token)
|
|
989
|
+
hostile("the continuation handed out a second child intent");
|
|
990
|
+
const amountUsd = Number(creditedUnits) / 1_000_000;
|
|
991
|
+
const submitted = [...journaled().transactions];
|
|
992
|
+
let secondApprovalRefused = false;
|
|
993
|
+
try {
|
|
994
|
+
const executed = await deps.executePredictionFund(admitted, amountUsd, {
|
|
995
|
+
beforeBroadcast: (stage, transactionHash, nonce) => {
|
|
996
|
+
// Durable stage guard, independent of the executor: a journal that
|
|
997
|
+
// already holds an approval never lets a second one be broadcast.
|
|
998
|
+
if (stage === "approval" && journaled().stages.has("approval")) {
|
|
999
|
+
secondApprovalRefused = true;
|
|
1000
|
+
throw new Error("a second pUSD approval was refused by the journal stage guard");
|
|
1001
|
+
}
|
|
1002
|
+
deps.saveCheckpoint(CP.pmBroadcastStarted, { stage, transaction_hash: transactionHash, nonce, started_at_ms: deps.now() });
|
|
1003
|
+
},
|
|
1004
|
+
onSubmitted: (stage, transactionHash) => {
|
|
1005
|
+
submitted.push({ stage, transaction_hash: transactionHash });
|
|
1006
|
+
deps.saveCheckpoint(CP.pmLastSubmitted, { transactions: [...submitted] });
|
|
1007
|
+
},
|
|
1008
|
+
}, { approvalAlreadySent });
|
|
1009
|
+
const hashes = [...new Set([...submitted.map((t) => String(t.transaction_hash)), ...executed.transaction_hashes])];
|
|
1010
|
+
deps.saveCheckpoint(CP.pmSent, { transaction_hashes: hashes });
|
|
1011
|
+
}
|
|
1012
|
+
catch (error) {
|
|
1013
|
+
if (!journaled().stages.size) {
|
|
1014
|
+
return result(false, "refused", { money_moved: true, next_action: "resume_with_same_idempotency_key",
|
|
1015
|
+
error: { code: "arc_polygon_pm_not_sent",
|
|
1016
|
+
message: `The pUSD step was not sent: ${String(error?.message || error).slice(0, 160)}. `
|
|
1017
|
+
+ "The USDC.e was credited to your own Polygon wallet; its current balance is not re-verified here." } });
|
|
1018
|
+
}
|
|
1019
|
+
const missing = secondApprovalRefused
|
|
1020
|
+
|| String(error?.message || "").startsWith("prediction_fund_approval_missing");
|
|
1021
|
+
if (missing && !journaled().stages.has("wrap")) {
|
|
1022
|
+
deps.saveCheckpoint(CP.pmApprovalMissing, { funding_id: plan.fundingId, detected_at_ms: deps.now() });
|
|
1023
|
+
return hold("arc_polygon_pm_approval_missing", "The journaled pUSD approval is no longer sufficient (the allowance changed). No second approval is "
|
|
1024
|
+
+ "signed or sent; reconcile the owner wallet's USDC.e allowance before resuming.", undefined, { money_moved: true, transaction_hashes: journaled().transactions.map((t) => t.transaction_hash) });
|
|
1025
|
+
}
|
|
1026
|
+
if (!journaled().stages.has("wrap")) {
|
|
1027
|
+
return result(true, "in_progress", { money_moved: true, next_action: "resume_with_same_idempotency_key",
|
|
1028
|
+
error: { code: "arc_polygon_pm_approval_only", message: "Only the approval was sent; the wrap resumes on this same intent." } });
|
|
1029
|
+
}
|
|
1030
|
+
// A wrap may have been broadcast: evidence with every known hash; never re-send.
|
|
1031
|
+
}
|
|
1032
|
+
return undefined;
|
|
1033
|
+
};
|
|
1034
|
+
if (!deps.getCheckpoint(CP.pmSent) && !journaled().stages.size) {
|
|
1035
|
+
// Complete gas on the SAME child, bounded; then journal the exact intent.
|
|
1036
|
+
let fund;
|
|
1037
|
+
for (let round = 0; round <= MAX_GAS_ROUNDS; round += 1) {
|
|
1038
|
+
if (outOfBudget())
|
|
1039
|
+
return result(true, "in_progress", { money_moved: true, next_action: "resume_with_same_idempotency_key" });
|
|
1040
|
+
polls += 1;
|
|
1041
|
+
fund = await fetchPm();
|
|
1042
|
+
if (isHold(fund))
|
|
1043
|
+
return fund;
|
|
1044
|
+
if (!fund) {
|
|
1045
|
+
await pause();
|
|
1046
|
+
continue;
|
|
1047
|
+
}
|
|
1048
|
+
if (pm && fund.intent_token !== pm.intent_token)
|
|
1049
|
+
hostile("the continuation handed out a second child intent");
|
|
1050
|
+
const gasState = isRecord(fund.gas_sponsorship) ? String(fund.gas_sponsorship.status || "") : "";
|
|
1051
|
+
if (gasState === "grant_pending_reconciliation") {
|
|
1052
|
+
await pause();
|
|
1053
|
+
continue;
|
|
1054
|
+
}
|
|
1055
|
+
if (gasState !== "signature_required")
|
|
1056
|
+
break;
|
|
1057
|
+
const request = assertGasGrantRequest(fund, { accountId, owner });
|
|
1058
|
+
const grant = await deps.signGasGrant(fund);
|
|
1059
|
+
if (!grant)
|
|
1060
|
+
return refuse("arc_polygon_gas_grant_unsigned", "The gas grant could not be signed locally; nothing was sent.");
|
|
1061
|
+
if (["kind", "user_id", "chain_id", "recipient", "amount_wei", "sponsor_nonce", "expires_at"]
|
|
1062
|
+
.some((field) => String(grant[field]) !== String(request[field]))) {
|
|
1063
|
+
hostile("the signed gas grant differs from the verified request");
|
|
1064
|
+
}
|
|
1065
|
+
polls += 1;
|
|
1066
|
+
const granted = await fetchPm(grant);
|
|
1067
|
+
if (isHold(granted))
|
|
1068
|
+
return granted;
|
|
1069
|
+
if (granted && granted.intent_token !== fund.intent_token)
|
|
1070
|
+
hostile("the gas grant produced another child intent");
|
|
1071
|
+
fund = granted ?? fund;
|
|
1072
|
+
const after = granted && isRecord(granted.gas_sponsorship) ? String(granted.gas_sponsorship.status || "") : "";
|
|
1073
|
+
if (granted && after !== "signature_required" && after !== "grant_pending_reconciliation")
|
|
1074
|
+
break;
|
|
1075
|
+
// Unresolved (pending) or unknown: wait and re-read the SAME child; the engine
|
|
1076
|
+
// accepts no further grant for it until the pending one is resolved.
|
|
1077
|
+
await pause();
|
|
1078
|
+
}
|
|
1079
|
+
if (!fund)
|
|
1080
|
+
return result(true, "in_progress", { money_moved: true, next_action: "resume_with_same_idempotency_key" });
|
|
1081
|
+
const gas = isRecord(fund.gas_sponsorship) ? fund.gas_sponsorship : {};
|
|
1082
|
+
const gasReady = gas.needed === false || (gas.status === "sponsored" && HASH.test(String(gas.tx_hash || "")));
|
|
1083
|
+
if (!gasReady) {
|
|
1084
|
+
return result(true, "in_progress", { money_moved: true, next_action: "resume_with_same_idempotency_key",
|
|
1085
|
+
error: { code: "arc_polygon_pm_gas_pending", message: "Polygon gas for the pUSD step is not ready yet." } });
|
|
1086
|
+
}
|
|
1087
|
+
if (!pm) {
|
|
1088
|
+
deps.saveCheckpoint(CP.pmPrepared, { funding_id: plan.fundingId, intent_token: fund.intent_token, prediction_fund: fund });
|
|
1089
|
+
}
|
|
1090
|
+
pm = deps.getCheckpoint(CP.pmPrepared);
|
|
1091
|
+
const stop = await execute(fund);
|
|
1092
|
+
if (stop)
|
|
1093
|
+
return stop;
|
|
1094
|
+
}
|
|
1095
|
+
else if (!deps.getCheckpoint(CP.pmSent) && !journaled().stages.has("wrap")) {
|
|
1096
|
+
// Approval-only recovery on the EXACT same child: never re-approve and never
|
|
1097
|
+
// guess the wrap. The wrap runs only once a read proves the approval landed
|
|
1098
|
+
// and the owner has nothing pending.
|
|
1099
|
+
if (!pm)
|
|
1100
|
+
hostile("an approval was journaled without its prediction_fund intent");
|
|
1101
|
+
let ready = false;
|
|
1102
|
+
try {
|
|
1103
|
+
ready = (await deps.pmApprovalReady(pm.prediction_fund)) === true;
|
|
1104
|
+
}
|
|
1105
|
+
catch {
|
|
1106
|
+
ready = false;
|
|
1107
|
+
}
|
|
1108
|
+
if (!ready && deps.getCheckpoint(CP.pmApprovalMissing)) {
|
|
1109
|
+
return hold("arc_polygon_pm_approval_missing", "The journaled pUSD approval is no longer sufficient (the allowance changed). No second approval is "
|
|
1110
|
+
+ "signed or sent; reconcile the owner wallet's USDC.e allowance before resuming.", undefined, { money_moved: true, transaction_hashes: journaled().transactions.map((t) => t.transaction_hash) });
|
|
1111
|
+
}
|
|
1112
|
+
if (!ready) {
|
|
1113
|
+
return result(true, "in_progress", { money_moved: true, next_action: "resume_with_same_idempotency_key",
|
|
1114
|
+
transaction_hashes: journaled().transactions.map((t) => t.transaction_hash),
|
|
1115
|
+
error: { code: "arc_polygon_pm_approval_pending",
|
|
1116
|
+
message: "The pUSD approval is not yet proven on chain; nothing more is sent until it is." } });
|
|
1117
|
+
}
|
|
1118
|
+
const stop = await execute(pm.prediction_fund, true);
|
|
1119
|
+
if (stop)
|
|
1120
|
+
return stop;
|
|
1121
|
+
}
|
|
1122
|
+
// -------- evidence: only the hashes this client journaled; never a second broadcast
|
|
1123
|
+
const sent = deps.getCheckpoint(CP.pmSent);
|
|
1124
|
+
const known = new Set();
|
|
1125
|
+
for (const h of (Array.isArray(sent?.transaction_hashes) ? sent.transaction_hashes : []))
|
|
1126
|
+
known.add(String(h));
|
|
1127
|
+
const last = deps.getCheckpoint(CP.pmLastSubmitted);
|
|
1128
|
+
for (const t of (Array.isArray(last?.transactions) ? last.transactions : [])) {
|
|
1129
|
+
if (isRecord(t))
|
|
1130
|
+
known.add(String(t.transaction_hash));
|
|
1131
|
+
}
|
|
1132
|
+
const started = deps.getCheckpoint(CP.pmBroadcastStarted);
|
|
1133
|
+
if (started && HASH.test(String(started.transaction_hash || "")))
|
|
1134
|
+
known.add(String(started.transaction_hash));
|
|
1135
|
+
if (!deps.getCheckpoint(CP.pmSent) && !journaled().stages.has("wrap")) {
|
|
1136
|
+
return result(true, "in_progress", { money_moved: true, next_action: "resume_with_same_idempotency_key",
|
|
1137
|
+
error: { code: "arc_polygon_pm_wrap_not_started", message: "The pUSD wrap has not been sent yet." } });
|
|
1138
|
+
}
|
|
1139
|
+
const hashes = [...known].filter((h) => HASH.test(h)).slice(0, 5);
|
|
1140
|
+
if (!hashes.length) {
|
|
1141
|
+
return hold("arc_polygon_pm_hashes_unknown", "A pUSD transaction may have been sent but no hash was journaled. "
|
|
1142
|
+
+ "Do not fund again; reconcile the owner wallet.", undefined, { money_moved: true });
|
|
1143
|
+
}
|
|
1144
|
+
for (;;) {
|
|
1145
|
+
if (outOfBudget()) {
|
|
1146
|
+
return result(true, "in_progress", { money_moved: true, next_action: "resume_with_same_idempotency_key",
|
|
1147
|
+
transaction_hashes: hashes });
|
|
1148
|
+
}
|
|
1149
|
+
polls += 1;
|
|
1150
|
+
const evidence = await api("POST", `${base}/polymarket/evidence`, { account_id: accountId, transaction_hashes: hashes }, { retryOnError: true });
|
|
1151
|
+
if (failed(evidence)) {
|
|
1152
|
+
if (definitiveRefusal(evidence)) {
|
|
1153
|
+
return hold(String(errorOf(evidence).reason || "arc_polygon_pm_evidence_refused"), "Felix would not confirm the pUSD step. Do not fund again.", undefined, { transaction_hashes: hashes });
|
|
1154
|
+
}
|
|
1155
|
+
await pause();
|
|
1156
|
+
continue;
|
|
1157
|
+
}
|
|
1158
|
+
if (evidence.funding_id !== plan.fundingId || evidence.agent_wallet_funded !== false) {
|
|
1159
|
+
hostile("the evidence answer is for another funding or claims agent funding");
|
|
1160
|
+
}
|
|
1161
|
+
if (evidence.status === "owner_pm_usable" && evidence.owner_pm_usable === true
|
|
1162
|
+
&& evidence.evidence_kind === "polymarket_spendable_pusd_credit") {
|
|
1163
|
+
let proven = false;
|
|
1164
|
+
try {
|
|
1165
|
+
proven = (await deps.policy.verifyPmCredit({ owner, pmWallet, amountUnits: creditedUnits,
|
|
1166
|
+
transactionHashes: hashes })) === true;
|
|
1167
|
+
}
|
|
1168
|
+
catch {
|
|
1169
|
+
proven = false;
|
|
1170
|
+
}
|
|
1171
|
+
if (!proven) {
|
|
1172
|
+
await pause();
|
|
1173
|
+
continue;
|
|
1174
|
+
} // the engine's confirm alone is not usability
|
|
1175
|
+
const final = result(true, "completed", {
|
|
1176
|
+
money_moved: true, owner_pm_usable: true, credited_units: creditedUnits.toString(),
|
|
1177
|
+
destination: { venue: "polymarket", wallet: pmWallet, token: PUSD_POLYGON, owner },
|
|
1178
|
+
// Exactly what owner_pm_usable rests on -- nothing more is claimed.
|
|
1179
|
+
owner_pm_usable_basis: {
|
|
1180
|
+
felix_confirm: "current pUSD balance of the PM wallet read by Felix at confirmation",
|
|
1181
|
+
client_proof: deps.policy.clientProofBasis
|
|
1182
|
+
?? "historical wrap receipt (verifyPmCredit), not a current balance or approval",
|
|
1183
|
+
not_claimed: ["agent_wallet_funding", "current_spendability_after_confirmation", "venue_order_readiness"],
|
|
1184
|
+
},
|
|
1185
|
+
transaction_hashes: hashes, agent_wallet_funded: false,
|
|
1186
|
+
network_fee: { units: POLYMARKET_FUNDING_FEE_UNITS.toString(), recipient: FELIX_FEE_TREASURY,
|
|
1187
|
+
state: "paid", tx_hash: String(credit.source_tx_hash), refundable: false,
|
|
1188
|
+
disclosure: POLYGON_FEE_DISCLOSURE },
|
|
1189
|
+
next_action: "fund_agent_wallet_separately_if_needed",
|
|
1190
|
+
});
|
|
1191
|
+
deps.saveCheckpoint(CP.completed, { result: final });
|
|
1192
|
+
return final;
|
|
1193
|
+
}
|
|
1194
|
+
if (evidence.owner_pm_usable === true)
|
|
1195
|
+
hostile("usability claimed without the pUSD credit evidence kind");
|
|
1196
|
+
await pause(); // venue_pending
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
catch (error) {
|
|
1200
|
+
if (error instanceof ArcPolygonHostileServer) {
|
|
1201
|
+
return hold("arc_polygon_server_untrusted", error.message);
|
|
1202
|
+
}
|
|
1203
|
+
if (signedAnything())
|
|
1204
|
+
return hold("arc_polygon_client_failed_after_signing", String(error?.message || error).slice(0, 200));
|
|
1205
|
+
return refuse("arc_polygon_client_failed", String(error?.message || error).slice(0, 200));
|
|
1206
|
+
}
|
|
1207
|
+
}
|