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.
- package/README.md +338 -30
- package/THIRD_PARTY_NOTICES.md +5 -0
- package/dist/agent-ops-guide.js +172 -2
- package/dist/arc-hl-return-ports.js +366 -0
- package/dist/arc-hl-return.js +1547 -0
- package/dist/arc-home.js +1161 -0
- package/dist/arc-hypercore-funding.js +1076 -0
- package/dist/arc-hypercore-return.js +826 -0
- package/dist/arc-pm-return.js +859 -0
- package/dist/arc-safe-invalidation-hints.js +209 -0
- package/dist/arc-safe-invalidation.js +672 -0
- package/dist/arc-settlement.js +682 -0
- package/dist/arc-venue-app-policy.js +30 -0
- package/dist/funding.js +1030 -68
- package/dist/getting-started-guide.js +138 -23
- package/dist/http-rate-subject.js +164 -0
- package/dist/http-server.js +167 -70
- package/dist/index.js +7182 -653
- package/dist/key-backup.js +46 -8
- package/dist/legal.js +1 -1
- package/dist/money-journal-identity.js +63 -6
- package/dist/polymarket.js +17 -7
- package/dist/public-venue.js +35 -0
- package/dist/redact-output.js +80 -0
- package/dist/rpc-endpoints.js +133 -0
- package/dist/safe-error.js +2 -1
- package/dist/safe-migration.js +7 -3
- package/dist/safe-onboarding.js +58 -49
- package/dist/safe-policy.js +39 -28
- package/dist/strategy-guide.js +18 -8
- package/package.json +55 -8
- package/server.json +2 -2
|
@@ -0,0 +1,1547 @@
|
|
|
1
|
+
// HL_ARC_RETURN_CLIENT_2026_09_23: offline client driver for the engine's
|
|
2
|
+
// Hyperliquid -> Arc home Safe return (/v1/arc-home/returns/*, deployed engine
|
|
3
|
+
// 01e3726b4, docs/ARC_HOME_HYPERLIQUID_RETURN.md, services/arc_home_hyperliquid_return.py).
|
|
4
|
+
//
|
|
5
|
+
// The return has two owner-signed stages and no server signer:
|
|
6
|
+
// 1. venue: ONE Hyperliquid withdraw3 whose destination is the owner's own
|
|
7
|
+
// Arbitrum EOA. The owner signs it and posts it to Hyperliquid; the engine
|
|
8
|
+
// proves it against one exact HyperCore ledger row (nonce-bound) plus the
|
|
9
|
+
// owner's measured Arbitrum native-USDC arrival.
|
|
10
|
+
// 2. arc deposit: ONE Arc deposit (Circle Gateway, Arbitrum domain 3 -> Arc
|
|
11
|
+
// domain 26) whose engine store key is derived from the stage-1 intent id.
|
|
12
|
+
// The owner signs the burn intent, broadcasts the Arbitrum approve +
|
|
13
|
+
// GatewayWallet.deposit calls it may need, reports the source hash, then
|
|
14
|
+
// signs the Arc mint SafeTx that Felix's relayer carries into the Safe.
|
|
15
|
+
//
|
|
16
|
+
// This module is deliberately NOT registered as an MCP tool and is not wired
|
|
17
|
+
// into index.ts. Every port (Felix API, owner signer, Hyperliquid, Arbitrum,
|
|
18
|
+
// Arc, journal, clock) is injected, so it runs fully offline.
|
|
19
|
+
//
|
|
20
|
+
// Invariants the driver holds on its own, whatever any server answers:
|
|
21
|
+
// * One caller idempotency key. Stage 1 uses it verbatim. Stage 2 (a different
|
|
22
|
+
// engine route, which the engine's idempotency store would treat as a
|
|
23
|
+
// conflicting body under the same key) uses one key derived from it and
|
|
24
|
+
// pinned in the scope checkpoint; the driver never mints any other key.
|
|
25
|
+
// * One owner, one child account, one Safe, one amount. A journal bound to
|
|
26
|
+
// that scope refuses any other before a network call; account_id is sent on
|
|
27
|
+
// every call and every signer payload must name the pinned owner and Safe.
|
|
28
|
+
// * One withdrawal. The withdraw3 (nonce = action.time) is pinned from the
|
|
29
|
+
// first prepare, signed at most once, and only those exact bytes are ever
|
|
30
|
+
// re-posted to Hyperliquid. After a payload is pinned the driver never
|
|
31
|
+
// calls prepare again, so it can never obtain a second signable withdrawal.
|
|
32
|
+
// * Exact ledger evidence. "arrived" is accepted only if the driver's own read
|
|
33
|
+
// of the HyperCore ledger finds exactly one withdraw row for the pinned
|
|
34
|
+
// nonce whose hash, amount and fee match the engine's evidence, and
|
|
35
|
+
// arrived == amount - ledger fee exactly (the canary's fee abort criterion).
|
|
36
|
+
// * One Arc deposit. The deposit operation id is pinned from the first
|
|
37
|
+
// arc-deposit answer and must carry the pinned intent id; a lost answer is
|
|
38
|
+
// recovered under the same derived key or by locating the operation whose
|
|
39
|
+
// /returns view carries the pinned intent id -- never by opening another.
|
|
40
|
+
// * Checkpoint before every irreversible byte leaves the process: the signed
|
|
41
|
+
// withdraw3 before it is posted, the burn-intent signature before it is
|
|
42
|
+
// reported, the exact signed Arbitrum transactions and their hashes before
|
|
43
|
+
// broadcast, the mint SafeTx signature before it is relayed. Resumes re-send
|
|
44
|
+
// those exact bytes and never re-sign.
|
|
45
|
+
// * Never a false money_moved:false. After the withdraw3 submission marker,
|
|
46
|
+
// movement is "unknown" until the driver's own ledger proof makes it true.
|
|
47
|
+
// * Completion only on a finalized Arc Safe credit: engine phase "completed"
|
|
48
|
+
// with home_usable, AND a finalized Arc mint receipt that transfers exactly
|
|
49
|
+
// the planned value from 0x0 to the Safe, AND a Safe balance increase of at
|
|
50
|
+
// least that value across the mint block, read at finalized heights.
|
|
51
|
+
import { redactOutput } from "./redact-output.js";
|
|
52
|
+
import { recordVenueIs } from "./public-venue.js";
|
|
53
|
+
import { createHash } from "node:crypto";
|
|
54
|
+
import { privateKeyToAccount } from "viem/accounts";
|
|
55
|
+
import { assertBurnIntentMatches, settlementOwnerAddress, signBurnIntent } from "./arc-settlement.js";
|
|
56
|
+
import { getRuntimeOwnerPrivateKey } from "./secret-state.js";
|
|
57
|
+
import { encodeFunctionData, getAddress, hashTypedData, keccak256, parseAbi, parseSignature, recoverTypedDataAddress, } from "viem";
|
|
58
|
+
export const HL_ARC_RETURN_CHECKPOINT_PREFIX = "hlret";
|
|
59
|
+
// HL_WITHDRAW3_EVIDENCE_2026_09_23 (engine docs/HL_WITHDRAW3_EVIDENCE_2026_09_23.md):
|
|
60
|
+
// for real withdraw3 actions the HyperCore ledger row and Bridge2's
|
|
61
|
+
// FinalizedWithdrawal carry nonce == signed time * 1000, and the ledger `usdc`
|
|
62
|
+
// is the NET payout (signed amount - fee, with `fee` reported separately).
|
|
63
|
+
// Only these relations are accepted; nothing else is guessed or tolerated.
|
|
64
|
+
export const HL_LEDGER_NONCE_PER_SIGNED_MS = 1000;
|
|
65
|
+
// The only write path this driver accepts for the owner's Arbitrum source
|
|
66
|
+
// calls: a Felix-scoped relay that binds each raw transaction to this return's
|
|
67
|
+
// Arc-home deposit. A generic public RPC is not a substitute. The engine does
|
|
68
|
+
// not offer such a relay yet (ARC_HL_RETURN_DRIVER.md gap G1), so production
|
|
69
|
+
// wiring passes none and a NEW return is refused before anything is prepared.
|
|
70
|
+
export const HL_ARC_ARBITRUM_BROADCAST_SCOPE = "felix_arc_home_deposit_source";
|
|
71
|
+
// Names avoid the ":sent" / ":submitted" / ":confirmed" suffixes that
|
|
72
|
+
// index.ts workflowProgress reads as "money moved", except venue:confirmed,
|
|
73
|
+
// which is only saved once the ledger proves the debit.
|
|
74
|
+
const CP = {
|
|
75
|
+
scope: "hlret:scope",
|
|
76
|
+
prepareStarted: "hlret:prepare-started",
|
|
77
|
+
prepared: "hlret:prepared",
|
|
78
|
+
venueSigned: "hlret:venue:signed",
|
|
79
|
+
venueBaseline: "hlret:venue:arbitrum-baseline",
|
|
80
|
+
venueSubmissionStarted: "hlret:venue:submission-started",
|
|
81
|
+
venueSubmits: "hlret:venue:submit-attempts",
|
|
82
|
+
venueAccepted: "hlret:venue:accepted",
|
|
83
|
+
venueOutcomeUnknown: "hlret:venue:outcome-unknown",
|
|
84
|
+
venueRejected: "hlret:venue:rejected",
|
|
85
|
+
venueConfirmed: "hlret:venue:confirmed",
|
|
86
|
+
deposit: "hlret:deposit",
|
|
87
|
+
burnSigned: "hlret:burn:signed",
|
|
88
|
+
sourceSigned: "hlret:source:signed",
|
|
89
|
+
sourceBroadcastStarted: "hlret:source:broadcast-started",
|
|
90
|
+
sourceReported: "hlret:source:reported",
|
|
91
|
+
mintSignatures: "hlret:mint:signatures",
|
|
92
|
+
// G4: {count, operation_id} of the latest recovery row, saved before the old
|
|
93
|
+
// row's per-deposit checkpoints are archived.
|
|
94
|
+
recoveries: "hlret:deposit:recoveries",
|
|
95
|
+
completed: "hlret:completed",
|
|
96
|
+
};
|
|
97
|
+
const recoveryArchiveCp = (n) => `hlret:deposit:recovery:${n}:archive`;
|
|
98
|
+
// Checkpoints that belong to ONE deposit row and are archived (never reused)
|
|
99
|
+
// when that row is recovered.
|
|
100
|
+
const PER_DEPOSIT_CHECKPOINTS = [
|
|
101
|
+
"hlret:deposit", "hlret:burn:signed", "hlret:source:signed", "hlret:source:broadcast-started",
|
|
102
|
+
"hlret:source:reported", "hlret:mint:signatures",
|
|
103
|
+
];
|
|
104
|
+
const MAX_CLIENT_DEPOSIT_RECOVERIES = 2;
|
|
105
|
+
const mintCp = (safeTxHash) => `hlret:mint:${safeTxHash}:signed`;
|
|
106
|
+
// ---------------------------------------------------------------- constants
|
|
107
|
+
// Mirrored from the engine so the client refuses before signing rather than
|
|
108
|
+
// after the engine refuses. A drift here fails closed.
|
|
109
|
+
const HL_SIGNATURE_CHAIN_ID_HEX = "0x66eee";
|
|
110
|
+
const HL_SIGNATURE_CHAIN_ID = 421614;
|
|
111
|
+
const HL_CHAIN = "Mainnet";
|
|
112
|
+
const HL_WITHDRAW_FEE_CEILING_UNITS = 1000000n; // withdraw3 flat $1
|
|
113
|
+
const HL_EVIDENCE_WINDOW_MS = 30 * 60 * 1000; // funding_nc._HL_WITHDRAWAL_EVIDENCE_WINDOW_MS
|
|
114
|
+
const HL_NONCE_ACCEPT_WINDOW_SECONDS = 2 * 24 * 60 * 60;
|
|
115
|
+
const HL_NONCE_MAX_SKEW_MS = 5 * 60 * 1000;
|
|
116
|
+
// Sign only while the engine's 30-minute ledger evidence window can still bind
|
|
117
|
+
// the withdrawal: a payload older than this is never signed.
|
|
118
|
+
const HL_NONCE_MAX_SIGN_AGE_MS = 20 * 60 * 1000;
|
|
119
|
+
const MIN_RETURN_UNITS = 2000000n; // arc_home_hyperliquid_return.MIN_RETURN_UNITS
|
|
120
|
+
const ARB_CHAIN_ID = 42161;
|
|
121
|
+
const ARB_DOMAIN = 3;
|
|
122
|
+
const ARB_USDC = getAddress("0xaf88d065e77c8cC2239327C5EDb3A432268e5831");
|
|
123
|
+
const GATEWAY_WALLET = getAddress("0x77777777Dcc4d5A8B6E418Fd04D8997ef11000eE");
|
|
124
|
+
const GATEWAY_MINTER = getAddress("0x2222222d7164433c4C09B0b0D809a9b52C04C205");
|
|
125
|
+
const ARC_CHAIN_ID = 5042;
|
|
126
|
+
const ARC_DOMAIN = 26;
|
|
127
|
+
const ARC_USDC = getAddress("0x3600000000000000000000000000000000000000");
|
|
128
|
+
const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
|
|
129
|
+
const ZERO_BYTES32 = `0x${"0".repeat(64)}`;
|
|
130
|
+
// arc_funding_routes: Circle base fee for source domain 3 x 1.1 + 0.5 bps.
|
|
131
|
+
const GATEWAY_BASE_FEE_UNITS_ARB = 10000n;
|
|
132
|
+
const GATEWAY_MAX_FEE_CEILING_UNITS = 5000000n;
|
|
133
|
+
const SOURCE_APPROVE_GAS = 100000n;
|
|
134
|
+
const SOURCE_DEPOSIT_GAS = 200000n;
|
|
135
|
+
const MAX_ARB_FEE_PER_GAS = 5000000000n; // 5 gwei: ~50x a normal Arbitrum base fee
|
|
136
|
+
const SOURCE_SIGN_HEADROOM_SECONDS = 120; // the Arc deposit row expires 600 s after prepare
|
|
137
|
+
const MAX_VENUE_SUBMITS = 3; // the first post + two identical re-posts
|
|
138
|
+
const MAX_SOURCE_SENDS = 4;
|
|
139
|
+
const MAX_MINT_SIGNATURES = 4;
|
|
140
|
+
const MAX_MINT_POSTS = 3;
|
|
141
|
+
const MAX_ARRIVAL_UNPROVEN_RETRIES = 6;
|
|
142
|
+
const DEPOSIT_KEY_SUFFIX = ":hl-arc-deposit";
|
|
143
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
144
|
+
const ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
|
|
145
|
+
const HASH_RE = /^0x[0-9a-fA-F]{64}$/;
|
|
146
|
+
const HEX_RE = /^0x(?:[0-9a-fA-F]{2})*$/;
|
|
147
|
+
const UINT_RE = /^(0|[1-9][0-9]*)$/;
|
|
148
|
+
const IDEMPOTENCY_KEY_RE = /^[\x21-\x7e]{8,110}$/;
|
|
149
|
+
const ABI = parseAbi([
|
|
150
|
+
"function approve(address spender,uint256 amount) returns (bool)",
|
|
151
|
+
"function deposit(address token,uint256 value)",
|
|
152
|
+
"function gatewayMint(bytes attestationPayload,bytes signature)",
|
|
153
|
+
]);
|
|
154
|
+
const HL_WITHDRAW_TYPES = {
|
|
155
|
+
"HyperliquidTransaction:Withdraw": [
|
|
156
|
+
{ name: "hyperliquidChain", type: "string" },
|
|
157
|
+
{ name: "destination", type: "string" },
|
|
158
|
+
{ name: "amount", type: "string" },
|
|
159
|
+
{ name: "time", type: "uint64" },
|
|
160
|
+
],
|
|
161
|
+
};
|
|
162
|
+
const HL_DOMAIN_TYPES = [
|
|
163
|
+
{ name: "name", type: "string" }, { name: "version", type: "string" },
|
|
164
|
+
{ name: "chainId", type: "uint256" }, { name: "verifyingContract", type: "address" },
|
|
165
|
+
];
|
|
166
|
+
const BURN_INTENT_TYPES = {
|
|
167
|
+
TransferSpec: [
|
|
168
|
+
{ name: "version", type: "uint32" },
|
|
169
|
+
{ name: "sourceDomain", type: "uint32" },
|
|
170
|
+
{ name: "destinationDomain", type: "uint32" },
|
|
171
|
+
{ name: "sourceContract", type: "bytes32" },
|
|
172
|
+
{ name: "destinationContract", type: "bytes32" },
|
|
173
|
+
{ name: "sourceToken", type: "bytes32" },
|
|
174
|
+
{ name: "destinationToken", type: "bytes32" },
|
|
175
|
+
{ name: "sourceDepositor", type: "bytes32" },
|
|
176
|
+
{ name: "destinationRecipient", type: "bytes32" },
|
|
177
|
+
{ name: "sourceSigner", type: "bytes32" },
|
|
178
|
+
{ name: "destinationCaller", type: "bytes32" },
|
|
179
|
+
{ name: "value", type: "uint256" },
|
|
180
|
+
{ name: "salt", type: "bytes32" },
|
|
181
|
+
{ name: "hookData", type: "bytes" },
|
|
182
|
+
],
|
|
183
|
+
BurnIntent: [
|
|
184
|
+
{ name: "maxBlockHeight", type: "uint256" },
|
|
185
|
+
{ name: "maxFee", type: "uint256" },
|
|
186
|
+
{ name: "spec", type: "TransferSpec" },
|
|
187
|
+
],
|
|
188
|
+
};
|
|
189
|
+
const BURN_DOMAIN_TYPES = [{ name: "name", type: "string" }, { name: "version", type: "string" }];
|
|
190
|
+
const SAFE_TX_TYPES = {
|
|
191
|
+
SafeTx: [
|
|
192
|
+
{ name: "to", type: "address" }, { name: "value", type: "uint256" },
|
|
193
|
+
{ name: "data", type: "bytes" }, { name: "operation", type: "uint8" },
|
|
194
|
+
{ name: "safeTxGas", type: "uint256" }, { name: "baseGas", type: "uint256" },
|
|
195
|
+
{ name: "gasPrice", type: "uint256" }, { name: "gasToken", type: "address" },
|
|
196
|
+
{ name: "refundReceiver", type: "address" }, { name: "nonce", type: "uint256" },
|
|
197
|
+
],
|
|
198
|
+
};
|
|
199
|
+
const SAFE_DOMAIN_TYPES = [
|
|
200
|
+
{ name: "chainId", type: "uint256" }, { name: "verifyingContract", type: "address" },
|
|
201
|
+
];
|
|
202
|
+
// ------------------------------------------------------------------ helpers
|
|
203
|
+
class Stop extends Error {
|
|
204
|
+
result;
|
|
205
|
+
constructor(result) {
|
|
206
|
+
super(result.reason || result.status);
|
|
207
|
+
this.result = result;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
class Wait {
|
|
211
|
+
reason;
|
|
212
|
+
constructor(reason) {
|
|
213
|
+
this.reason = reason;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
function isRecord(value) {
|
|
217
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
218
|
+
}
|
|
219
|
+
function lower(value) {
|
|
220
|
+
return typeof value === "string" ? value.toLowerCase() : "";
|
|
221
|
+
}
|
|
222
|
+
function sameAddress(left, right) {
|
|
223
|
+
return typeof left === "string" && typeof right === "string"
|
|
224
|
+
&& ADDRESS_RE.test(left) && ADDRESS_RE.test(right) && left.toLowerCase() === right.toLowerCase();
|
|
225
|
+
}
|
|
226
|
+
function canonical(value) {
|
|
227
|
+
if (typeof value === "bigint")
|
|
228
|
+
return JSON.stringify(value.toString());
|
|
229
|
+
if (Array.isArray(value))
|
|
230
|
+
return `[${value.map(canonical).join(",")}]`;
|
|
231
|
+
if (isRecord(value)) {
|
|
232
|
+
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
|
|
233
|
+
}
|
|
234
|
+
return JSON.stringify(value);
|
|
235
|
+
}
|
|
236
|
+
function digest(value) {
|
|
237
|
+
return createHash("sha256").update(canonical(value)).digest("hex");
|
|
238
|
+
}
|
|
239
|
+
function exactKeys(value, keys) {
|
|
240
|
+
return isRecord(value)
|
|
241
|
+
&& JSON.stringify(Object.keys(value).sort()) === JSON.stringify([...keys].sort());
|
|
242
|
+
}
|
|
243
|
+
function uint(value) {
|
|
244
|
+
if (typeof value === "bigint")
|
|
245
|
+
return value >= 0n ? value : null;
|
|
246
|
+
if (typeof value === "number")
|
|
247
|
+
return Number.isSafeInteger(value) && value >= 0 ? BigInt(value) : null;
|
|
248
|
+
if (typeof value === "string" && UINT_RE.test(value) && value.length <= 78)
|
|
249
|
+
return BigInt(value);
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
// Exact six-decimal USDC text ("3", "2.5", "3.000000") -> units, else null.
|
|
253
|
+
function usdcTextUnits(value) {
|
|
254
|
+
const text = typeof value === "number" && Number.isFinite(value) ? String(value) : value;
|
|
255
|
+
if (typeof text !== "string")
|
|
256
|
+
return null;
|
|
257
|
+
const match = /^(0|[1-9][0-9]{0,12})(?:\.([0-9]{1,6}))?$/.exec(text);
|
|
258
|
+
if (!match)
|
|
259
|
+
return null;
|
|
260
|
+
return BigInt(match[1]) * 1000000n + BigInt((match[2] || "").padEnd(6, "0"));
|
|
261
|
+
}
|
|
262
|
+
function unitsDecimal(units) {
|
|
263
|
+
const whole = units / 1000000n;
|
|
264
|
+
const fraction = (units % 1000000n).toString().padStart(6, "0");
|
|
265
|
+
return `${whole}.${fraction}`;
|
|
266
|
+
}
|
|
267
|
+
// funding_nc: f"{units/1e6:.6f}".rstrip("0").rstrip(".")
|
|
268
|
+
function hlAmountText(units) {
|
|
269
|
+
return unitsDecimal(units).replace(/0+$/, "").replace(/\.$/, "");
|
|
270
|
+
}
|
|
271
|
+
export function gatewayMaxFeeUnits(arrivedUnits) {
|
|
272
|
+
const buffered = (GATEWAY_BASE_FEE_UNITS_ARB * 11n + 9n) / 10n;
|
|
273
|
+
const transfer = (arrivedUnits * 5n + 99999n) / 100000n;
|
|
274
|
+
return buffered + transfer;
|
|
275
|
+
}
|
|
276
|
+
function bytes32Address(address) {
|
|
277
|
+
return `0x${"0".repeat(24)}${address.slice(2).toLowerCase()}`;
|
|
278
|
+
}
|
|
279
|
+
function httpStatus(result) {
|
|
280
|
+
const meta = isRecord(result._meta) ? result._meta : {};
|
|
281
|
+
return typeof meta.http_status === "number" ? meta.http_status : undefined;
|
|
282
|
+
}
|
|
283
|
+
function errorOf(result) {
|
|
284
|
+
return isRecord(result.error) ? result.error : {};
|
|
285
|
+
}
|
|
286
|
+
function errorCode(result) {
|
|
287
|
+
const error = errorOf(result);
|
|
288
|
+
return typeof error.reason === "string" ? error.reason
|
|
289
|
+
: typeof error.code === "string" ? error.code : "unknown_error";
|
|
290
|
+
}
|
|
291
|
+
function failed(result) {
|
|
292
|
+
if (result.ok === false)
|
|
293
|
+
return true;
|
|
294
|
+
const status = httpStatus(result);
|
|
295
|
+
return status === undefined || status >= 400;
|
|
296
|
+
}
|
|
297
|
+
// A response the server definitely produced and that refuses the request.
|
|
298
|
+
// Anything else -- transport loss, deadline, 5xx, 408/425/429, 409
|
|
299
|
+
// idempotency_in_progress -- is uncertain: the request may have taken effect.
|
|
300
|
+
function definitiveRefusal(result) {
|
|
301
|
+
if (!failed(result))
|
|
302
|
+
return false;
|
|
303
|
+
const status = httpStatus(result);
|
|
304
|
+
if (status === undefined || status < 400 || status >= 500)
|
|
305
|
+
return false;
|
|
306
|
+
if (status === 408 || status === 425 || status === 429)
|
|
307
|
+
return false;
|
|
308
|
+
if (errorOf(result).code === "idempotency_in_progress")
|
|
309
|
+
return false;
|
|
310
|
+
if (errorOf(result).outcome_unknown === true)
|
|
311
|
+
return false;
|
|
312
|
+
return true;
|
|
313
|
+
}
|
|
314
|
+
function strongest(...values) {
|
|
315
|
+
if (values.includes(true))
|
|
316
|
+
return true;
|
|
317
|
+
if (values.includes("unknown"))
|
|
318
|
+
return "unknown";
|
|
319
|
+
return false;
|
|
320
|
+
}
|
|
321
|
+
class Driver {
|
|
322
|
+
request;
|
|
323
|
+
ports;
|
|
324
|
+
options;
|
|
325
|
+
amount;
|
|
326
|
+
owner;
|
|
327
|
+
safe;
|
|
328
|
+
depositKey;
|
|
329
|
+
nowMs;
|
|
330
|
+
sleep;
|
|
331
|
+
view = null; // latest deposit public_record
|
|
332
|
+
arrivalRetries = 0;
|
|
333
|
+
freshScope = false;
|
|
334
|
+
reconciledSinceMintPost = false;
|
|
335
|
+
constructor(request, ports, options) {
|
|
336
|
+
this.request = request;
|
|
337
|
+
this.ports = ports;
|
|
338
|
+
this.options = options;
|
|
339
|
+
this.amount = uint(request.amount_units) ?? 0n;
|
|
340
|
+
this.owner = ADDRESS_RE.test(String(request.expected_owner)) ? getAddress(request.expected_owner) : "";
|
|
341
|
+
this.safe = ADDRESS_RE.test(String(request.expected_safe)) ? getAddress(request.expected_safe) : "";
|
|
342
|
+
this.depositKey = `${request.idempotency_key}${DEPOSIT_KEY_SUFFIX}`;
|
|
343
|
+
this.nowMs = ports.nowMs ?? (() => Date.now());
|
|
344
|
+
this.sleep = ports.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
345
|
+
}
|
|
346
|
+
// ------------------------------------------------------------ journal
|
|
347
|
+
cp(name) {
|
|
348
|
+
return this.ports.journal.getCheckpoint(name);
|
|
349
|
+
}
|
|
350
|
+
save(name, value) {
|
|
351
|
+
this.ports.journal.saveCheckpoint(name, value);
|
|
352
|
+
}
|
|
353
|
+
movement() {
|
|
354
|
+
if (this.cp(CP.venueConfirmed))
|
|
355
|
+
return true;
|
|
356
|
+
if (this.cp(CP.venueSubmissionStarted))
|
|
357
|
+
return "unknown";
|
|
358
|
+
return false;
|
|
359
|
+
}
|
|
360
|
+
result(status, fields) {
|
|
361
|
+
const moved = strongest(this.movement(), fields.money_moved);
|
|
362
|
+
const prepared = this.cp(CP.prepared);
|
|
363
|
+
const deposit = this.cp(CP.deposit);
|
|
364
|
+
const proven = this.cp(CP.venueConfirmed);
|
|
365
|
+
return {
|
|
366
|
+
ok: status === "completed" || status === "in_progress",
|
|
367
|
+
status,
|
|
368
|
+
account_id: this.request.account_id,
|
|
369
|
+
idempotency_key: this.request.idempotency_key,
|
|
370
|
+
intent_id: prepared?.intent_id ?? null,
|
|
371
|
+
operation_id: deposit?.operation_id ?? null,
|
|
372
|
+
stage: deposit ? "arc_deposit" : "venue_withdrawal",
|
|
373
|
+
home_usable: false,
|
|
374
|
+
...(proven ? { venue: { ...proven } } : {}),
|
|
375
|
+
...fields,
|
|
376
|
+
money_moved: moved,
|
|
377
|
+
user_funds_moved: moved,
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
stop(status, reason, next, hint, extra = {}) {
|
|
381
|
+
throw new Stop(this.result(status, { reason, next_action: next, hint, ...extra }));
|
|
382
|
+
}
|
|
383
|
+
hold(reason, hint, extra = {}) {
|
|
384
|
+
this.stop("reconciliation_required", reason, "reconcile_do_not_resign", hint, extra);
|
|
385
|
+
}
|
|
386
|
+
async api(method, path, body, key) {
|
|
387
|
+
try {
|
|
388
|
+
const out = await this.ports.api(method, path, body, key ? { idempotencyKey: key } : undefined);
|
|
389
|
+
return isRecord(out) ? out : { ok: false, error: { code: "invalid_response", outcome_unknown: true } };
|
|
390
|
+
}
|
|
391
|
+
catch (error) {
|
|
392
|
+
return {
|
|
393
|
+
ok: false,
|
|
394
|
+
error: { code: "transport_lost", outcome_unknown: true, message: String(error?.message || error) },
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
accountQuery() {
|
|
399
|
+
return `account_id=${encodeURIComponent(this.request.account_id)}`;
|
|
400
|
+
}
|
|
401
|
+
// ------------------------------------------------------------ run
|
|
402
|
+
async run() {
|
|
403
|
+
this.checkScope();
|
|
404
|
+
const done = this.cp(CP.completed);
|
|
405
|
+
if (done && isRecord(done.result))
|
|
406
|
+
return done.result;
|
|
407
|
+
const maxSteps = this.options.maxSteps ?? 400;
|
|
408
|
+
const pollMs = this.options.pollMs ?? 5_000;
|
|
409
|
+
let lastWait = "starting";
|
|
410
|
+
for (let step = 0; step < maxSteps; step++) {
|
|
411
|
+
const outcome = await this.step();
|
|
412
|
+
if (outcome instanceof Wait) {
|
|
413
|
+
lastWait = outcome.reason;
|
|
414
|
+
await this.sleep(pollMs);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
return this.result("in_progress", {
|
|
418
|
+
reason: lastWait,
|
|
419
|
+
next_action: "resume_with_same_idempotency_key",
|
|
420
|
+
hint: "The return is still moving. Resume with the same arguments; nothing will be re-signed.",
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
arcReady() {
|
|
424
|
+
const arc = this.ports.arc;
|
|
425
|
+
return !!arc && typeof arc.finalizedBlock === "function" && typeof arc.usdcBalance === "function"
|
|
426
|
+
&& typeof arc.mintReceipt === "function";
|
|
427
|
+
}
|
|
428
|
+
broadcastReady() {
|
|
429
|
+
const port = this.ports.arbitrumBroadcast;
|
|
430
|
+
return !!port && port.scope === HL_ARC_ARBITRUM_BROADCAST_SCOPE
|
|
431
|
+
&& typeof port.sendRawTransaction === "function";
|
|
432
|
+
}
|
|
433
|
+
checkScope() {
|
|
434
|
+
const r = this.request;
|
|
435
|
+
const invalid = (reason, hint) => {
|
|
436
|
+
throw new Stop({
|
|
437
|
+
ok: false, status: "refused", account_id: String(r.account_id), idempotency_key: String(r.idempotency_key),
|
|
438
|
+
intent_id: null, operation_id: null, stage: "venue_withdrawal",
|
|
439
|
+
money_moved: false, user_funds_moved: false, home_usable: false,
|
|
440
|
+
next_action: "fix_request", reason, hint,
|
|
441
|
+
});
|
|
442
|
+
};
|
|
443
|
+
if (!UUID_RE.test(String(r.account_id)))
|
|
444
|
+
invalid("hl_return_account_invalid", "account_id must be the child account UUID.");
|
|
445
|
+
if (!IDEMPOTENCY_KEY_RE.test(String(r.idempotency_key))) {
|
|
446
|
+
invalid("hl_return_idempotency_key_invalid", "idempotency_key must be 8-110 printable characters.");
|
|
447
|
+
}
|
|
448
|
+
if (uint(r.amount_units) === null || this.amount < MIN_RETURN_UNITS) {
|
|
449
|
+
invalid("hl_return_amount_invalid", "amount_units must be integer USDC units of at least 2.000000.");
|
|
450
|
+
}
|
|
451
|
+
if (!this.owner || !this.safe)
|
|
452
|
+
invalid("hl_return_address_invalid", "expected_owner and expected_safe must be addresses.");
|
|
453
|
+
if (!sameAddress(this.ports.signer.address, this.owner)) {
|
|
454
|
+
invalid("hl_return_owner_key_mismatch", "The local owner key is not the account's owner EOA.");
|
|
455
|
+
}
|
|
456
|
+
const scope = {
|
|
457
|
+
account_id: r.account_id.toLowerCase(),
|
|
458
|
+
amount_units: this.amount.toString(),
|
|
459
|
+
idempotency_key: r.idempotency_key,
|
|
460
|
+
deposit_idempotency_key: this.depositKey,
|
|
461
|
+
owner: this.owner.toLowerCase(),
|
|
462
|
+
safe: this.safe.toLowerCase(),
|
|
463
|
+
allow_high_fee_loss: r.allow_high_fee_loss === true,
|
|
464
|
+
accept_amount_adjustment: r.accept_amount_adjustment === true,
|
|
465
|
+
};
|
|
466
|
+
const existing = this.cp(CP.scope);
|
|
467
|
+
if (!this.cp(CP.prepareStarted) && !this.arcReady()) {
|
|
468
|
+
invalid("hl_return_arc_reader_unavailable", "This client has no Arc reader to prove the finalized Safe credit, so it will not start a return it "
|
|
469
|
+
+ "could not confirm. Nothing was prepared or signed.");
|
|
470
|
+
}
|
|
471
|
+
if (!this.cp(CP.prepareStarted) && !this.broadcastReady()) {
|
|
472
|
+
invalid("hl_return_arbitrum_broadcast_unavailable", "This client has no Felix-scoped Arbitrum relay for the Arc deposit's source calls, so it will not start "
|
|
473
|
+
+ "a withdrawal it could not finish. Nothing was prepared or signed.");
|
|
474
|
+
}
|
|
475
|
+
if (existing && canonical(existing) !== canonical(scope)) {
|
|
476
|
+
invalid("hl_return_scope_conflict", "This idempotency key is bound to a different account, owner, Safe or amount. It is never re-used for another return.");
|
|
477
|
+
}
|
|
478
|
+
if (!existing) {
|
|
479
|
+
this.freshScope = true;
|
|
480
|
+
this.save(CP.scope, scope);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
async step() {
|
|
484
|
+
const prepared = this.cp(CP.prepared);
|
|
485
|
+
if (!prepared)
|
|
486
|
+
return this.prepare();
|
|
487
|
+
if (!this.cp(CP.venueConfirmed))
|
|
488
|
+
return this.venueStage(prepared);
|
|
489
|
+
const deposit = this.cp(CP.deposit);
|
|
490
|
+
if (!deposit && !this.arcReady()) {
|
|
491
|
+
this.hold("hl_return_arc_reader_unavailable", "The withdrawal has arrived in the owner's Arbitrum wallet, but this client cannot read Arc to prove the "
|
|
492
|
+
+ "home credit. No deposit was opened; never sign another withdrawal.", { money_moved: true });
|
|
493
|
+
}
|
|
494
|
+
if (!deposit && !this.broadcastReady()) {
|
|
495
|
+
this.hold("hl_return_arbitrum_broadcast_unavailable", "The withdrawal has arrived in the owner's Arbitrum wallet, but this client has no Felix-scoped relay for "
|
|
496
|
+
+ "the Arc deposit's source calls. No deposit was opened; the USDC stays in the owner's wallet. "
|
|
497
|
+
+ "Never sign another withdrawal.", { money_moved: true });
|
|
498
|
+
}
|
|
499
|
+
if (!deposit)
|
|
500
|
+
return this.openDeposit(prepared);
|
|
501
|
+
return this.depositStage(prepared, deposit);
|
|
502
|
+
}
|
|
503
|
+
// ------------------------------------------------------------ stage 1: prepare
|
|
504
|
+
async prepare() {
|
|
505
|
+
const body = {
|
|
506
|
+
account_id: this.request.account_id,
|
|
507
|
+
amount: unitsDecimal(this.amount),
|
|
508
|
+
allow_high_fee_loss: this.request.allow_high_fee_loss === true,
|
|
509
|
+
};
|
|
510
|
+
if (!this.cp(CP.prepareStarted))
|
|
511
|
+
this.save(CP.prepareStarted, { at_ms: this.nowMs() });
|
|
512
|
+
const out = await this.api("POST", "/v1/arc-home/returns/prepare", body, this.request.idempotency_key);
|
|
513
|
+
if (failed(out)) {
|
|
514
|
+
const code = errorCode(out);
|
|
515
|
+
if (!definitiveRefusal(out))
|
|
516
|
+
return new Wait(`prepare_uncertain:${code}`);
|
|
517
|
+
if (code === "idempotency_send_unknown") {
|
|
518
|
+
// The engine never recorded a payload under this key; the slot is the
|
|
519
|
+
// payload's durable record and the route resumes a lapsed claim.
|
|
520
|
+
return new Wait("prepare_idempotency_pending");
|
|
521
|
+
}
|
|
522
|
+
if (isRecord(out.error) && out.error.reason === "arc_home_hl_return_prepare_not_launch_enabled") {
|
|
523
|
+
this.stop("refused", "arc_home_hl_return_prepare_not_launch_enabled", "none_route_not_launch_enabled", "Felix has not enabled new Hyperliquid returns to the Arc home. Nothing was prepared or signed; "
|
|
524
|
+
+ "any return already under way can still be resumed.", { money_moved: false, error: errorOf(out) });
|
|
525
|
+
}
|
|
526
|
+
this.stop("refused", code, code === "arc_home_hl_return_in_progress"
|
|
527
|
+
? "finish_or_wait_for_open_return" : "read_error", "Felix refused to prepare the Hyperliquid withdrawal. Nothing was signed under this key.", { money_moved: false, error: errorOf(out) });
|
|
528
|
+
}
|
|
529
|
+
const pinned = this.validatePrepared(out);
|
|
530
|
+
const nonce = pinned.action.time;
|
|
531
|
+
if (this.nowMs() - nonce > HL_NONCE_MAX_SIGN_AGE_MS)
|
|
532
|
+
return this.stalePayload(pinned);
|
|
533
|
+
this.save(CP.prepared, pinned);
|
|
534
|
+
}
|
|
535
|
+
// The same key replayed a payload too old to sign safely. This process never
|
|
536
|
+
// signed it if its journal is continuous (prepare-started predates this run);
|
|
537
|
+
// after a journal loss an earlier process may have. The ledger decides.
|
|
538
|
+
async stalePayload(pinned) {
|
|
539
|
+
const ledger = await this.ledgerRow(pinned);
|
|
540
|
+
if (ledger.kind === "unreadable")
|
|
541
|
+
return new Wait("hyperliquid_ledger_unreadable");
|
|
542
|
+
if (ledger.kind === "one") {
|
|
543
|
+
this.save(CP.prepared, { ...pinned, adopted: true });
|
|
544
|
+
this.save(CP.venueSubmissionStarted, { nonce: pinned.action.time, adopted: true, at_ms: this.nowMs() });
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
if (ledger.kind === "ambiguous") {
|
|
548
|
+
this.hold("hl_return_ledger_ambiguous", "The ledger shows more than one row for this withdrawal nonce.", { money_moved: "unknown" });
|
|
549
|
+
}
|
|
550
|
+
this.stop(this.freshScope ? "reconciliation_required" : "refused", "hl_return_prepared_payload_stale", "wait_for_hold_until", "Felix replayed a withdrawal payload too old to sign inside its evidence window. It was not signed here; "
|
|
551
|
+
+ "the account's return slot stays held until hold_until.", { money_moved: this.freshScope ? "unknown" : false, residual_risk: ["return_slot_held_until_hold_until"] });
|
|
552
|
+
}
|
|
553
|
+
validatePrepared(out) {
|
|
554
|
+
const bad = (why) => this.hold("hl_return_prepare_payload_invalid", `The prepared withdrawal failed the client check (${why}); it was not signed.`, { money_moved: false });
|
|
555
|
+
// venue:"hyperliquid" arrives as market:"crypto" through the public API scrub.
|
|
556
|
+
if (out.ok !== true || !recordVenueIs(out, "hyperliquid") || out.home !== "arc"
|
|
557
|
+
|| out.stage !== "venue_withdrawal" || out.status !== "venue_withdrawal_prepared"
|
|
558
|
+
|| out.money_moved !== false || out.home_usable !== false || out.operation_created !== false) {
|
|
559
|
+
bad("stage");
|
|
560
|
+
}
|
|
561
|
+
const intentId = out.intent_id;
|
|
562
|
+
const token = out.intent_token;
|
|
563
|
+
if (typeof intentId !== "string" || !intentId || typeof token !== "string" || !token || token.length > 16_000) {
|
|
564
|
+
bad("intent");
|
|
565
|
+
}
|
|
566
|
+
if (!sameAddress(out.owner_address, this.owner) || !sameAddress(out.fixed_recipient, this.owner))
|
|
567
|
+
bad("owner_or_recipient");
|
|
568
|
+
const units = uint(out.amount_units);
|
|
569
|
+
const requested = uint(out.requested_amount_units);
|
|
570
|
+
if (units === null || requested !== this.amount || units <= 0n || units > this.amount)
|
|
571
|
+
bad("amount");
|
|
572
|
+
const adjusted = units !== this.amount;
|
|
573
|
+
if (adjusted !== (out.amount_adjusted_to_available === true))
|
|
574
|
+
bad("adjustment_flag");
|
|
575
|
+
if (adjusted && this.request.accept_amount_adjustment !== true) {
|
|
576
|
+
this.stop("refused", "hl_return_amount_adjusted", "wait_for_hold_until_or_resume_with_accept_amount_adjustment", "Felix down-adjusted the withdrawal to keep collateral reserved. It was not signed. "
|
|
577
|
+
+ "The account's return slot stays held until hold_until; resume with accept_amount_adjustment to sign it.", { money_moved: false, residual_risk: ["return_slot_held_until_hold_until"] });
|
|
578
|
+
}
|
|
579
|
+
if (units < MIN_RETURN_UNITS)
|
|
580
|
+
bad("below_minimum");
|
|
581
|
+
const fee = uint(out.expected_venue_fee_units);
|
|
582
|
+
if (fee === null || fee > HL_WITHDRAW_FEE_CEILING_UNITS)
|
|
583
|
+
bad("venue_fee");
|
|
584
|
+
const action = out.action;
|
|
585
|
+
if (!exactKeys(action, ["type", "destination", "amount", "time", "signatureChainId", "hyperliquidChain"])
|
|
586
|
+
|| action.type !== "withdraw3" || action.signatureChainId !== HL_SIGNATURE_CHAIN_ID_HEX
|
|
587
|
+
|| action.hyperliquidChain !== HL_CHAIN || !sameAddress(action.destination, this.owner)
|
|
588
|
+
|| action.amount !== hlAmountText(units)
|
|
589
|
+
|| typeof action.time !== "number" || !Number.isSafeInteger(action.time) || action.time <= 0) {
|
|
590
|
+
bad("action");
|
|
591
|
+
}
|
|
592
|
+
const nonce = action.time;
|
|
593
|
+
if (nonce - this.nowMs() > HL_NONCE_MAX_SKEW_MS)
|
|
594
|
+
bad("nonce_in_future");
|
|
595
|
+
const holdUntil = out.hold_until;
|
|
596
|
+
if (typeof holdUntil !== "number" || !Number.isSafeInteger(holdUntil)
|
|
597
|
+
|| holdUntil < Math.floor(nonce / 1000) + HL_NONCE_ACCEPT_WINDOW_SECONDS) {
|
|
598
|
+
bad("hold_until");
|
|
599
|
+
}
|
|
600
|
+
const typed = out.typed_data;
|
|
601
|
+
if (!exactKeys(typed, ["domain", "types", "primaryType", "message"]))
|
|
602
|
+
bad("typed_data");
|
|
603
|
+
const t = typed;
|
|
604
|
+
const domain = t.domain;
|
|
605
|
+
if (!exactKeys(domain, ["name", "version", "chainId", "verifyingContract"])
|
|
606
|
+
|| domain.name !== "HyperliquidSignTransaction" || domain.version !== "1"
|
|
607
|
+
|| domain.chainId !== HL_SIGNATURE_CHAIN_ID || !sameAddress(domain.verifyingContract, ZERO_ADDRESS)
|
|
608
|
+
|| t.primaryType !== "HyperliquidTransaction:Withdraw"
|
|
609
|
+
|| canonical(t.types) !== canonical({ ...HL_WITHDRAW_TYPES, EIP712Domain: HL_DOMAIN_TYPES })) {
|
|
610
|
+
bad("typed_data_domain");
|
|
611
|
+
}
|
|
612
|
+
const a = action;
|
|
613
|
+
if (!exactKeys(t.message, ["hyperliquidChain", "destination", "amount", "time"])
|
|
614
|
+
|| canonical(t.message) !== canonical({
|
|
615
|
+
hyperliquidChain: a.hyperliquidChain, destination: a.destination, amount: a.amount, time: a.time,
|
|
616
|
+
})) {
|
|
617
|
+
bad("typed_data_message");
|
|
618
|
+
}
|
|
619
|
+
return {
|
|
620
|
+
intent_id: intentId,
|
|
621
|
+
intent_token: token,
|
|
622
|
+
amount_units: units.toString(),
|
|
623
|
+
hold_until: holdUntil,
|
|
624
|
+
action: a,
|
|
625
|
+
typed_data: t,
|
|
626
|
+
payload_digest: digest({ action: a, typed_data: t }),
|
|
627
|
+
};
|
|
628
|
+
}
|
|
629
|
+
// ------------------------------------------------------------ stage 1: venue
|
|
630
|
+
async venueStage(prepared) {
|
|
631
|
+
if (prepared.adopted)
|
|
632
|
+
return this.venueEvidence(prepared, null);
|
|
633
|
+
let signed = this.cp(CP.venueSigned);
|
|
634
|
+
if (!signed) {
|
|
635
|
+
if (this.cp(CP.venueSubmissionStarted)) {
|
|
636
|
+
// A submission marker without its signature means the journal was lost
|
|
637
|
+
// or tampered with: never produce a second signature.
|
|
638
|
+
this.hold("hl_return_venue_signature_missing", "The withdrawal may have been posted; it is not re-signed.");
|
|
639
|
+
}
|
|
640
|
+
if (digest({ action: prepared.action, typed_data: prepared.typed_data }) !== prepared.payload_digest) {
|
|
641
|
+
this.hold("hl_return_prepared_pin_tampered", "The pinned withdrawal payload changed; it is not signed.");
|
|
642
|
+
}
|
|
643
|
+
const typed = prepared.typed_data;
|
|
644
|
+
const message = { ...typed.message, time: BigInt(typed.message.time) };
|
|
645
|
+
const typedData = {
|
|
646
|
+
domain: typed.domain, types: HL_WITHDRAW_TYPES,
|
|
647
|
+
primaryType: "HyperliquidTransaction:Withdraw", message,
|
|
648
|
+
};
|
|
649
|
+
const signature = await this.ports.signer.signTypedData(typedData);
|
|
650
|
+
const recovered = await recoverTypedDataAddress({ ...typedData, signature });
|
|
651
|
+
if (!sameAddress(recovered, this.owner)) {
|
|
652
|
+
this.hold("hl_return_venue_signature_invalid", "The owner key produced a signature for another address.", { money_moved: false });
|
|
653
|
+
}
|
|
654
|
+
signed = { signature, payload_digest: prepared.payload_digest };
|
|
655
|
+
this.save(CP.venueSigned, signed);
|
|
656
|
+
}
|
|
657
|
+
if (signed.payload_digest !== prepared.payload_digest) {
|
|
658
|
+
this.hold("hl_return_prepared_pin_tampered", "The signed withdrawal no longer matches its pinned payload.");
|
|
659
|
+
}
|
|
660
|
+
if (!this.cp(CP.venueSubmissionStarted)) {
|
|
661
|
+
// Baseline for the driver's own Arbitrum arrival check, read before any
|
|
662
|
+
// byte of the withdrawal leaves the process.
|
|
663
|
+
const baseline = await this.ports.arbitrum.usdcBalance(this.owner);
|
|
664
|
+
this.save(CP.venueBaseline, { units: baseline.toString() });
|
|
665
|
+
return this.postWithdraw(prepared, signed.signature);
|
|
666
|
+
}
|
|
667
|
+
return this.venueEvidence(prepared, signed.signature);
|
|
668
|
+
}
|
|
669
|
+
async postWithdraw(prepared, signature) {
|
|
670
|
+
const attempts = Number(this.cp(CP.venueSubmits)?.count ?? 0);
|
|
671
|
+
if (attempts >= MAX_VENUE_SUBMITS)
|
|
672
|
+
return new Wait("venue_submit_budget_spent");
|
|
673
|
+
this.save(CP.venueSubmits, { count: attempts + 1 });
|
|
674
|
+
if (!this.cp(CP.venueSubmissionStarted)) {
|
|
675
|
+
this.save(CP.venueSubmissionStarted, { nonce: prepared.action.time, at_ms: this.nowMs() });
|
|
676
|
+
}
|
|
677
|
+
const split = parseSignature(signature);
|
|
678
|
+
const body = {
|
|
679
|
+
action: prepared.action,
|
|
680
|
+
nonce: prepared.action.time,
|
|
681
|
+
signature: { r: split.r, s: split.s, v: Number(split.v) },
|
|
682
|
+
vaultAddress: null,
|
|
683
|
+
expiresAfter: null,
|
|
684
|
+
};
|
|
685
|
+
let answer = null;
|
|
686
|
+
try {
|
|
687
|
+
answer = await this.ports.hyperliquid.submitWithdraw(body);
|
|
688
|
+
}
|
|
689
|
+
catch {
|
|
690
|
+
answer = null;
|
|
691
|
+
}
|
|
692
|
+
if (answer && answer.status === "ok") {
|
|
693
|
+
this.save(CP.venueAccepted, { at_ms: this.nowMs() });
|
|
694
|
+
return;
|
|
695
|
+
}
|
|
696
|
+
const message = answer ? String(redactOutput(String(answer.response ?? answer.error ?? ""))).slice(0, 240) : "";
|
|
697
|
+
if (!answer || /nonce/i.test(message)) {
|
|
698
|
+
// Lost, or "nonce already used" after a lost first answer: the ledger decides.
|
|
699
|
+
this.save(CP.venueOutcomeUnknown, { at_ms: this.nowMs(), message });
|
|
700
|
+
return;
|
|
701
|
+
}
|
|
702
|
+
this.save(CP.venueRejected, { at_ms: this.nowMs(), message });
|
|
703
|
+
}
|
|
704
|
+
async venueEvidence(prepared, signature) {
|
|
705
|
+
const out = await this.api("POST", "/v1/arc-home/returns/venue-evidence", {
|
|
706
|
+
account_id: this.request.account_id, intent_token: prepared.intent_token,
|
|
707
|
+
});
|
|
708
|
+
if (failed(out)) {
|
|
709
|
+
const code = errorCode(out);
|
|
710
|
+
if (definitiveRefusal(out) && (code === "arc_home_hl_return_intent_denied"
|
|
711
|
+
|| code === "arc_home_hl_return_intent_mismatch")) {
|
|
712
|
+
this.hold(code, "Felix will not read this withdrawal's evidence for this credential. Do not sign another withdrawal.", { error: errorOf(out) });
|
|
713
|
+
}
|
|
714
|
+
return new Wait(`venue_evidence_unavailable:${code}`);
|
|
715
|
+
}
|
|
716
|
+
if (out.intent_id !== prepared.intent_id || out.resend_permitted !== false
|
|
717
|
+
|| out.home_usable !== false || String(out.amount_units) !== prepared.amount_units
|
|
718
|
+
|| out.stage !== "venue_withdrawal") {
|
|
719
|
+
this.hold("hl_return_evidence_mismatch", "The venue evidence does not describe the pinned withdrawal.");
|
|
720
|
+
}
|
|
721
|
+
if (out.status === "venue_withdrawal_pending") {
|
|
722
|
+
return signature ? this.maybeRepost(prepared, signature) : new Wait("venue_withdrawal_pending");
|
|
723
|
+
}
|
|
724
|
+
if (out.status === "reconciliation_required") {
|
|
725
|
+
const opId = out.arc_deposit_operation_id;
|
|
726
|
+
if (typeof opId === "string" && UUID_RE.test(opId)) {
|
|
727
|
+
// This return's own deposit already drained the payout (the engine
|
|
728
|
+
// does not latch that case); the deposit row, not venue evidence,
|
|
729
|
+
// governs. Without the driver's own venue proof it cannot pin that
|
|
730
|
+
// row, so it holds and names it rather than guessing.
|
|
731
|
+
if (this.cp(CP.venueConfirmed))
|
|
732
|
+
return this.recoverDepositById(prepared, opId);
|
|
733
|
+
this.hold("hl_return_deposit_exists_journal_incomplete", "An Arc deposit for this withdrawal already exists, but this client's journal no longer holds the venue "
|
|
734
|
+
+ "proof it needs to drive it. Read the deposit with its operation id; never open another deposit or sign "
|
|
735
|
+
+ "another withdrawal.", { money_moved: true, operation_id: opId });
|
|
736
|
+
}
|
|
737
|
+
const ledger = await this.ledgerRow(prepared);
|
|
738
|
+
const reason = typeof out.reason === "string" ? out.reason : "unspecified";
|
|
739
|
+
this.hold(`hl_return_venue_${reason}`, reason === "hyperliquid_payout_not_intact"
|
|
740
|
+
? "The Hyperliquid payout is proven but the owner's Arbitrum wallet no longer holds all of it. Felix will "
|
|
741
|
+
+ "not open the automated Arc deposit. Never sign a second withdrawal."
|
|
742
|
+
: "Felix could not bind the withdrawal to its own Bridge2 payout. Never sign a second withdrawal.", { money_moved: ledger.kind === "one" ? true : "unknown",
|
|
743
|
+
venue: { reason, arrival_transaction_hash: lower(out.arrival_transaction_hash) || null,
|
|
744
|
+
bridge2_payout_units: typeof out.bridge2_payout_units === "string" ? out.bridge2_payout_units : null } });
|
|
745
|
+
}
|
|
746
|
+
if (out.status !== "arbitrum_arrived") {
|
|
747
|
+
this.hold("hl_return_evidence_status_unknown", "Felix answered an unknown venue status.");
|
|
748
|
+
}
|
|
749
|
+
const arrived = uint(out.spoke_arrived_units);
|
|
750
|
+
const fee = uint(out.venue_fee_units);
|
|
751
|
+
const ledgerHash = lower(out.source_ledger_hash);
|
|
752
|
+
const payoutHash = lower(out.arrival_transaction_hash);
|
|
753
|
+
const expectedBridgeNonce = prepared.action.time * HL_LEDGER_NONCE_PER_SIGNED_MS;
|
|
754
|
+
if (arrived === null || fee === null || !HASH_RE.test(ledgerHash) || out.money_moved !== true
|
|
755
|
+
|| !HASH_RE.test(payoutHash) || out.arrival_bridge2_nonce !== expectedBridgeNonce) {
|
|
756
|
+
this.hold("hl_return_evidence_invalid", "Felix's arrival evidence is incomplete or is not bound to this withdrawal's own Bridge2 payout.");
|
|
757
|
+
}
|
|
758
|
+
const ledger = await this.ledgerRow(prepared);
|
|
759
|
+
if (ledger.kind === "unreadable")
|
|
760
|
+
return new Wait("hyperliquid_ledger_unreadable");
|
|
761
|
+
if (ledger.kind !== "one") {
|
|
762
|
+
this.hold("hl_return_ledger_unproven", `Felix reports an arrival the Hyperliquid ledger does not show exactly once (${ledger.kind}).`, { money_moved: "unknown" });
|
|
763
|
+
}
|
|
764
|
+
const row = ledger.row;
|
|
765
|
+
const amount = BigInt(prepared.amount_units);
|
|
766
|
+
// Observed: ledger usdc is net, so usdc + fee == signed amount and the
|
|
767
|
+
// arrival is exactly that net payout.
|
|
768
|
+
if (row.hash !== ledgerHash || row.usdc + row.fee !== amount || row.fee !== fee
|
|
769
|
+
|| row.fee > HL_WITHDRAW_FEE_CEILING_UNITS || arrived !== row.usdc) {
|
|
770
|
+
this.hold("hl_return_venue_fee_mismatch", "The ledger row, the fee and the Arbitrum arrival do not agree exactly. Canary abort criterion.", { money_moved: true, venue: { ledger_hash: row.hash, ledger_fee_units: row.fee.toString(),
|
|
771
|
+
engine_fee_units: fee.toString(), arrived_units: arrived.toString() } });
|
|
772
|
+
}
|
|
773
|
+
const baseline = uint(this.cp(CP.venueBaseline)?.units);
|
|
774
|
+
const balance = prepared.adopted ? 0n : await this.ports.arbitrum.usdcBalance(this.owner);
|
|
775
|
+
if (!prepared.adopted && (baseline === null || balance < baseline + arrived)) {
|
|
776
|
+
this.hold("hl_return_arbitrum_arrival_unconfirmed", "The owner's Arbitrum USDC did not rise by the proven arrival since the withdrawal was posted.", { money_moved: true });
|
|
777
|
+
}
|
|
778
|
+
this.save(CP.venueConfirmed, {
|
|
779
|
+
ledger_hash: row.hash, ledger_time_ms: row.time,
|
|
780
|
+
bridge2_payout_tx: payoutHash, bridge2_nonce: String(expectedBridgeNonce),
|
|
781
|
+
venue_fee_units: row.fee.toString(), arrived_units: arrived.toString(),
|
|
782
|
+
arrival_measured_by_driver: !prepared.adopted,
|
|
783
|
+
});
|
|
784
|
+
}
|
|
785
|
+
async maybeRepost(prepared, signature) {
|
|
786
|
+
if (this.cp(CP.venueAccepted))
|
|
787
|
+
return new Wait("venue_withdrawal_pending");
|
|
788
|
+
const nonce = prepared.action.time;
|
|
789
|
+
if (this.nowMs() > nonce + HL_EVIDENCE_WINDOW_MS - 5 * 60 * 1000) {
|
|
790
|
+
// No re-post that Felix's evidence window could no longer bind.
|
|
791
|
+
return new Wait("venue_withdrawal_pending");
|
|
792
|
+
}
|
|
793
|
+
const ledger = await this.ledgerRow(prepared);
|
|
794
|
+
if (ledger.kind !== "none")
|
|
795
|
+
return new Wait("venue_withdrawal_pending");
|
|
796
|
+
if (this.cp(CP.venueRejected) && !this.cp(CP.venueOutcomeUnknown)) {
|
|
797
|
+
this.stop("reconciliation_required", "hl_return_venue_rejected", "wait_for_hold_until", "Hyperliquid refused the signed withdrawal and the ledger shows no debit. It is not re-signed; "
|
|
798
|
+
+ "the account's return slot stays held until hold_until.", { money_moved: false, residual_risk: ["signed_withdraw3_valid_until_hold_until"] });
|
|
799
|
+
}
|
|
800
|
+
// The exact signed bytes, again: one nonce, so at most one can land.
|
|
801
|
+
await this.postWithdraw(prepared, signature);
|
|
802
|
+
return new Wait("venue_withdrawal_reposted");
|
|
803
|
+
}
|
|
804
|
+
async ledgerRow(prepared) {
|
|
805
|
+
const nonce = prepared.action.time;
|
|
806
|
+
const ledgerNonce = nonce * HL_LEDGER_NONCE_PER_SIGNED_MS;
|
|
807
|
+
let rows;
|
|
808
|
+
try {
|
|
809
|
+
rows = await this.ports.hyperliquid.ledger(this.owner, nonce, Math.min(this.nowMs(), nonce + HL_EVIDENCE_WINDOW_MS));
|
|
810
|
+
}
|
|
811
|
+
catch {
|
|
812
|
+
return { kind: "unreadable" };
|
|
813
|
+
}
|
|
814
|
+
if (!Array.isArray(rows))
|
|
815
|
+
return { kind: "unreadable" };
|
|
816
|
+
const matches = [];
|
|
817
|
+
for (const row of rows) {
|
|
818
|
+
if (!isRecord(row) || !isRecord(row.delta) || row.delta.type !== "withdraw")
|
|
819
|
+
continue;
|
|
820
|
+
if (row.delta.nonce !== ledgerNonce)
|
|
821
|
+
continue;
|
|
822
|
+
// `usdc` is the net payout; a row without its fee cannot be read as net.
|
|
823
|
+
const usdc = usdcTextUnits(row.delta.usdc);
|
|
824
|
+
const fee = row.delta.fee === undefined ? null : usdcTextUnits(row.delta.fee);
|
|
825
|
+
const hash = lower(row.hash);
|
|
826
|
+
if (usdc === null || fee === null || !HASH_RE.test(hash) || typeof row.time !== "number") {
|
|
827
|
+
return { kind: "ambiguous" };
|
|
828
|
+
}
|
|
829
|
+
matches.push({ hash, time: row.time, usdc, fee });
|
|
830
|
+
}
|
|
831
|
+
if (matches.length > 1)
|
|
832
|
+
return { kind: "ambiguous" };
|
|
833
|
+
if (matches.length === 0)
|
|
834
|
+
return { kind: "none" };
|
|
835
|
+
return { kind: "one", row: matches[0] };
|
|
836
|
+
}
|
|
837
|
+
// ------------------------------------------------------------ stage 2: open
|
|
838
|
+
async openDeposit(prepared) {
|
|
839
|
+
const recovered = this.cp(CP.recoveries);
|
|
840
|
+
if (recovered && typeof recovered.operation_id === "string") {
|
|
841
|
+
// A recovery row was recorded before the old pin was archived: never go
|
|
842
|
+
// back to arc-deposit, which would only replay the dead row.
|
|
843
|
+
return this.recoverDepositById(prepared, recovered.operation_id);
|
|
844
|
+
}
|
|
845
|
+
const proven = this.cp(CP.venueConfirmed);
|
|
846
|
+
const arrived = BigInt(proven.arrived_units);
|
|
847
|
+
const fee = gatewayMaxFeeUnits(arrived);
|
|
848
|
+
if (fee >= arrived) {
|
|
849
|
+
this.hold("hl_return_below_gateway_fee", "The Arbitrum arrival is below Circle's Gateway fee ceiling; it stays in the owner's Arbitrum wallet.", { money_moved: true });
|
|
850
|
+
}
|
|
851
|
+
const out = await this.api("POST", "/v1/arc-home/returns/arc-deposit", {
|
|
852
|
+
account_id: this.request.account_id, intent_token: prepared.intent_token, max_fee_units: fee.toString(),
|
|
853
|
+
}, this.depositKey);
|
|
854
|
+
if (failed(out)) {
|
|
855
|
+
const code = errorCode(out);
|
|
856
|
+
if (code === "idempotency_send_unknown")
|
|
857
|
+
return this.recoverDeposit(prepared);
|
|
858
|
+
if (!definitiveRefusal(out))
|
|
859
|
+
return new Wait(`arc_deposit_uncertain:${code}`);
|
|
860
|
+
if (code === "arc_home_hl_return_spoke_arrival_unproven" && ++this.arrivalRetries <= MAX_ARRIVAL_UNPROVEN_RETRIES) {
|
|
861
|
+
return new Wait(code);
|
|
862
|
+
}
|
|
863
|
+
this.hold(code, "Felix refused to open this withdrawal's Arc deposit. The arrival stays in the owner's Arbitrum wallet; "
|
|
864
|
+
+ "never sign another withdrawal.", { error: errorOf(out), money_moved: true });
|
|
865
|
+
}
|
|
866
|
+
this.pinDeposit(prepared, out, arrived, fee);
|
|
867
|
+
}
|
|
868
|
+
// The deposit row exists or is being created, but this key's answer was
|
|
869
|
+
// never recorded. Find the operation whose /returns view carries our intent.
|
|
870
|
+
async recoverDeposit(prepared) {
|
|
871
|
+
const list = await this.api("GET", `/v1/arc-home/operations?${this.accountQuery()}&limit=50`);
|
|
872
|
+
if (failed(list) || !Array.isArray(list.operations))
|
|
873
|
+
return new Wait("arc_deposit_recovery_unavailable");
|
|
874
|
+
const matches = [];
|
|
875
|
+
for (const op of list.operations) {
|
|
876
|
+
if (!isRecord(op) || op.kind !== "arc_deposit_in" || !UUID_RE.test(String(op.operation_id)))
|
|
877
|
+
continue;
|
|
878
|
+
const view = await this.api("GET", `/v1/arc-home/returns/${op.operation_id}?${this.accountQuery()}`);
|
|
879
|
+
if (failed(view)) {
|
|
880
|
+
if (errorCode(view) === "arc_home_hl_return_operation_mismatch")
|
|
881
|
+
continue;
|
|
882
|
+
return new Wait("arc_deposit_recovery_unavailable");
|
|
883
|
+
}
|
|
884
|
+
if (view.intent_id === prepared.intent_id)
|
|
885
|
+
matches.push(view);
|
|
886
|
+
}
|
|
887
|
+
if (matches.length > 1)
|
|
888
|
+
this.hold("hl_return_duplicate_deposit", "Two Arc deposits name this withdrawal.");
|
|
889
|
+
if (matches.length === 0) {
|
|
890
|
+
this.hold("hl_return_deposit_unrecoverable", "The Arc deposit request's outcome was never recorded and no deposit names this withdrawal yet. "
|
|
891
|
+
+ "The arrival is in the owner's Arbitrum wallet; do not open another deposit for it.", { money_moved: true });
|
|
892
|
+
}
|
|
893
|
+
const proven = this.cp(CP.venueConfirmed);
|
|
894
|
+
const arrived = BigInt(proven.arrived_units);
|
|
895
|
+
this.pinDeposit(prepared, matches[0], arrived, gatewayMaxFeeUnits(arrived));
|
|
896
|
+
}
|
|
897
|
+
async recoverDepositById(prepared, operationId) {
|
|
898
|
+
const pinned = this.cp(CP.deposit);
|
|
899
|
+
if (pinned && pinned.operation_id !== operationId) {
|
|
900
|
+
this.hold("hl_return_duplicate_deposit", "Felix names a different Arc deposit than the one this return opened.");
|
|
901
|
+
}
|
|
902
|
+
const view = await this.api("GET", `/v1/arc-home/returns/${operationId}?${this.accountQuery()}`);
|
|
903
|
+
if (failed(view))
|
|
904
|
+
return new Wait("arc_deposit_recovery_unavailable");
|
|
905
|
+
if (view.intent_id !== prepared.intent_id) {
|
|
906
|
+
this.hold("hl_return_deposit_identity_mismatch", "The named Arc deposit belongs to another withdrawal.");
|
|
907
|
+
}
|
|
908
|
+
if (pinned)
|
|
909
|
+
return;
|
|
910
|
+
const proven = this.cp(CP.venueConfirmed);
|
|
911
|
+
const arrived = BigInt(proven.arrived_units);
|
|
912
|
+
this.pinDeposit(prepared, view, arrived, gatewayMaxFeeUnits(arrived));
|
|
913
|
+
}
|
|
914
|
+
pinDeposit(prepared, out, arrived, fee) {
|
|
915
|
+
const proven = this.cp(CP.venueConfirmed);
|
|
916
|
+
const value = arrived - fee;
|
|
917
|
+
const bad = (why) => this.hold("hl_return_deposit_plan_invalid", `The Arc deposit failed the client check (${why}); nothing was signed for it.`, { money_moved: true });
|
|
918
|
+
if (!UUID_RE.test(String(out.operation_id)) || out.kind !== "arc_deposit_in"
|
|
919
|
+
|| out.intent_id !== prepared.intent_id || out.purpose !== "hyperliquid_arc_home_return"
|
|
920
|
+
|| !recordVenueIs(out, "hyperliquid") || out.home !== "arc" || out.stage !== "arc_deposit") {
|
|
921
|
+
bad("identity");
|
|
922
|
+
}
|
|
923
|
+
if (String(out.spoke_arrived_units) !== proven.arrived_units
|
|
924
|
+
|| String(out.venue_fee_units) !== proven.venue_fee_units
|
|
925
|
+
|| String(out.requested_amount_units) !== prepared.amount_units) {
|
|
926
|
+
bad("proven_amounts");
|
|
927
|
+
}
|
|
928
|
+
const shortfall = this.checkPlan(out, value, fee);
|
|
929
|
+
const burn = out.burn_intent_typed_data;
|
|
930
|
+
const pin = {
|
|
931
|
+
operation_id: String(out.operation_id),
|
|
932
|
+
value_units: value.toString(),
|
|
933
|
+
max_fee_units: fee.toString(),
|
|
934
|
+
shortfall_units: shortfall.toString(),
|
|
935
|
+
burn_digest: digest(burn),
|
|
936
|
+
source_calls_digest: digest(out.source_calls),
|
|
937
|
+
expires_at: Number(out.expires_at),
|
|
938
|
+
max_block_height: String((burn.message.maxBlockHeight)),
|
|
939
|
+
};
|
|
940
|
+
const existing = this.cp(CP.deposit);
|
|
941
|
+
if (existing && canonical(existing) !== canonical(pin))
|
|
942
|
+
bad("pin_changed");
|
|
943
|
+
this.save(CP.deposit, pin);
|
|
944
|
+
this.view = out;
|
|
945
|
+
}
|
|
946
|
+
// Every field of the plan the owner will sign, against pinned values only.
|
|
947
|
+
checkPlan(view, value, fee) {
|
|
948
|
+
const bad = (why) => this.hold("hl_return_deposit_plan_invalid", `The Arc deposit failed the client check (${why}); nothing was signed for it.`, { money_moved: true });
|
|
949
|
+
if (view.destination_chain !== "arc" || !sameAddress(view.destination, this.safe)
|
|
950
|
+
|| String(view.amount_units) !== value.toString() || String(view.max_fee_units) !== fee.toString()
|
|
951
|
+
|| fee > GATEWAY_MAX_FEE_CEILING_UNITS
|
|
952
|
+
|| view.mint_gas_payer !== "owner_signed_safe_tx_felix_sponsored"
|
|
953
|
+
|| typeof view.expires_at !== "number" || !Number.isSafeInteger(view.expires_at)) {
|
|
954
|
+
bad("plan");
|
|
955
|
+
}
|
|
956
|
+
const typed = view.burn_intent_typed_data;
|
|
957
|
+
if (!exactKeys(typed, ["types", "primaryType", "domain", "message"]))
|
|
958
|
+
bad("burn_typed_data");
|
|
959
|
+
const t = typed;
|
|
960
|
+
if (t.primaryType !== "BurnIntent" || !exactKeys(t.domain, ["name", "version"])
|
|
961
|
+
|| t.domain.name !== "GatewayWallet" || t.domain.version !== "1"
|
|
962
|
+
|| canonical(t.types) !== canonical({ ...BURN_INTENT_TYPES, EIP712Domain: BURN_DOMAIN_TYPES })) {
|
|
963
|
+
bad("burn_domain");
|
|
964
|
+
}
|
|
965
|
+
const message = t.message;
|
|
966
|
+
if (!exactKeys(message, ["maxBlockHeight", "maxFee", "spec"]))
|
|
967
|
+
bad("burn_message");
|
|
968
|
+
const m = message;
|
|
969
|
+
const maxBlock = uint(m.maxBlockHeight);
|
|
970
|
+
if (maxBlock === null || maxBlock <= 0n || uint(m.maxFee) !== fee)
|
|
971
|
+
bad("burn_fee_or_height");
|
|
972
|
+
const spec = m.spec;
|
|
973
|
+
const specKeys = BURN_INTENT_TYPES.TransferSpec.map((field) => field.name);
|
|
974
|
+
if (!exactKeys(spec, specKeys))
|
|
975
|
+
bad("burn_spec_keys");
|
|
976
|
+
const s = spec;
|
|
977
|
+
const expected = {
|
|
978
|
+
version: 1, sourceDomain: ARB_DOMAIN, destinationDomain: ARC_DOMAIN,
|
|
979
|
+
sourceContract: bytes32Address(GATEWAY_WALLET), destinationContract: bytes32Address(GATEWAY_MINTER),
|
|
980
|
+
sourceToken: bytes32Address(ARB_USDC), destinationToken: bytes32Address(ARC_USDC),
|
|
981
|
+
sourceDepositor: bytes32Address(this.owner), destinationRecipient: bytes32Address(this.safe),
|
|
982
|
+
sourceSigner: bytes32Address(this.owner), destinationCaller: ZERO_BYTES32, hookData: "0x",
|
|
983
|
+
};
|
|
984
|
+
for (const [field, want] of Object.entries(expected)) {
|
|
985
|
+
const got = typeof s[field] === "string" ? lower(s[field]) : s[field];
|
|
986
|
+
if (got !== want)
|
|
987
|
+
bad(`burn_spec_${field}`);
|
|
988
|
+
}
|
|
989
|
+
if (uint(s.value) !== value)
|
|
990
|
+
bad("burn_value");
|
|
991
|
+
if (typeof s.salt !== "string" || !HASH_RE.test(s.salt) || BigInt(s.salt) === 0n)
|
|
992
|
+
bad("burn_salt");
|
|
993
|
+
try {
|
|
994
|
+
// The same validator prepare_arc_transfer uses. Its owner_address mode
|
|
995
|
+
// requires the recipient to be the owner, which is wrong here (the
|
|
996
|
+
// recipient is the Arc home Safe, pinned above), so it is not passed.
|
|
997
|
+
assertBurnIntentMatches(t, {
|
|
998
|
+
source_domain: ARB_DOMAIN, destination_domain: ARC_DOMAIN,
|
|
999
|
+
amount_units: value, maximum_fee_units: fee,
|
|
1000
|
+
});
|
|
1001
|
+
}
|
|
1002
|
+
catch {
|
|
1003
|
+
bad("burn_settlement_validator");
|
|
1004
|
+
}
|
|
1005
|
+
const shortfall = uint(view.gateway_shortfall_units);
|
|
1006
|
+
if (shortfall === null || shortfall > value + fee)
|
|
1007
|
+
bad("shortfall");
|
|
1008
|
+
const calls = view.source_calls;
|
|
1009
|
+
if (!Array.isArray(calls))
|
|
1010
|
+
bad("source_calls");
|
|
1011
|
+
if (shortfall === 0n) {
|
|
1012
|
+
if (calls.length !== 0)
|
|
1013
|
+
bad("source_calls_unexpected");
|
|
1014
|
+
return 0n;
|
|
1015
|
+
}
|
|
1016
|
+
const wantCalls = [
|
|
1017
|
+
{ chain_id: ARB_CHAIN_ID, from: this.owner, to: ARB_USDC, value: "0",
|
|
1018
|
+
data: encodeFunctionData({ abi: ABI, functionName: "approve", args: [GATEWAY_WALLET, shortfall] }) },
|
|
1019
|
+
{ chain_id: ARB_CHAIN_ID, from: this.owner, to: GATEWAY_WALLET, value: "0",
|
|
1020
|
+
data: encodeFunctionData({ abi: ABI, functionName: "deposit", args: [ARB_USDC, shortfall] }) },
|
|
1021
|
+
];
|
|
1022
|
+
if (calls.length !== 2)
|
|
1023
|
+
bad("source_calls_count");
|
|
1024
|
+
calls.forEach((call, index) => {
|
|
1025
|
+
const want = wantCalls[index];
|
|
1026
|
+
if (!exactKeys(call, ["chain_id", "from", "to", "data", "value"])
|
|
1027
|
+
|| call.chain_id !== want.chain_id || !sameAddress(call.from, want.from)
|
|
1028
|
+
|| !sameAddress(call.to, want.to) || lower(call.data) !== want.data.toLowerCase()
|
|
1029
|
+
|| String(call.value) !== "0") {
|
|
1030
|
+
bad(`source_call_${index}`);
|
|
1031
|
+
}
|
|
1032
|
+
});
|
|
1033
|
+
return shortfall;
|
|
1034
|
+
}
|
|
1035
|
+
// ------------------------------------------------------------ stage 2: drive
|
|
1036
|
+
async depositStage(prepared, pin) {
|
|
1037
|
+
if (!this.view) {
|
|
1038
|
+
const out = await this.api("GET", `/v1/arc-home/returns/${pin.operation_id}?${this.accountQuery()}`);
|
|
1039
|
+
if (failed(out))
|
|
1040
|
+
return new Wait(`deposit_view_unavailable:${errorCode(out)}`);
|
|
1041
|
+
if (out.intent_id !== prepared.intent_id)
|
|
1042
|
+
this.hold("hl_return_deposit_intent_mismatch", "The deposit names another withdrawal.");
|
|
1043
|
+
this.acceptView(out, pin);
|
|
1044
|
+
}
|
|
1045
|
+
const view = this.view;
|
|
1046
|
+
const phase = String(view.phase);
|
|
1047
|
+
if (phase === "completed")
|
|
1048
|
+
return this.proveCompletion(prepared, pin);
|
|
1049
|
+
if (phase === "expired" || phase === "cancelled")
|
|
1050
|
+
return this.recoverExpired(prepared, pin);
|
|
1051
|
+
if (["rejected", "attestation_expired"].includes(phase)) {
|
|
1052
|
+
const source = this.cp(CP.sourceBroadcastStarted);
|
|
1053
|
+
this.hold(`hl_return_deposit_${phase}`, source
|
|
1054
|
+
? "The Arc deposit ended without a home credit after the source deposit was broadcast. "
|
|
1055
|
+
+ "Funds are the owner's on Arbitrum or in the owner's Gateway balance; reconcile, never re-run the withdrawal."
|
|
1056
|
+
: "The Arc deposit ended before any source transaction was broadcast. The arrival is in the owner's "
|
|
1057
|
+
+ "Arbitrum wallet; move it with an ordinary Arc deposit. Never re-run the withdrawal.", { money_moved: true });
|
|
1058
|
+
}
|
|
1059
|
+
if (phase === "prepared")
|
|
1060
|
+
return this.sourceStep(pin);
|
|
1061
|
+
if (phase === "burn_attested" && isRecord(view.mint_safe_transaction))
|
|
1062
|
+
return this.mintStep(pin);
|
|
1063
|
+
if (["source_submitted", "gateway_funded", "burn_attested", "mint_submitted"].includes(phase)) {
|
|
1064
|
+
return this.reconcile(pin);
|
|
1065
|
+
}
|
|
1066
|
+
this.hold("hl_return_deposit_phase_unknown", `Felix reported an unknown deposit phase (${phase}).`);
|
|
1067
|
+
}
|
|
1068
|
+
// G4: the row expired or was cancelled before any burn. Felix may reopen it
|
|
1069
|
+
// once (per attempt) without a second money move; the engine proves the old
|
|
1070
|
+
// relayed source deposit final, and this client additionally never asks
|
|
1071
|
+
// while its own broadcast has no receipt.
|
|
1072
|
+
async recoverExpired(prepared, pin) {
|
|
1073
|
+
const count = Number(this.cp(CP.recoveries)?.count ?? 0);
|
|
1074
|
+
if (!Number.isSafeInteger(count) || count >= MAX_CLIENT_DEPOSIT_RECOVERIES) {
|
|
1075
|
+
this.hold("hl_return_deposit_recovery_limit", "This return's Arc deposit expired too many times. The USDC is the owner's on Arbitrum or in Gateway; "
|
|
1076
|
+
+ "reconcile manually. Never sign another withdrawal.", { money_moved: true });
|
|
1077
|
+
}
|
|
1078
|
+
const signed = this.cp(CP.sourceSigned);
|
|
1079
|
+
if (this.cp(CP.sourceBroadcastStarted) && signed) {
|
|
1080
|
+
for (const hash of signed.hashes) {
|
|
1081
|
+
const receipt = await this.ports.arbitrum.receipt(hash).catch(() => null);
|
|
1082
|
+
if (!receipt)
|
|
1083
|
+
return new Wait("expired_row_source_unsettled");
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
const out = await this.api("POST", "/v1/arc-home/returns/arc-deposit/recover", {
|
|
1087
|
+
account_id: this.request.account_id, intent_token: prepared.intent_token,
|
|
1088
|
+
expired_operation_id: pin.operation_id, max_fee_units: pin.max_fee_units,
|
|
1089
|
+
}, `${this.depositKey}:recover:${count + 1}`);
|
|
1090
|
+
if (failed(out)) {
|
|
1091
|
+
const code = errorCode(out);
|
|
1092
|
+
if (!definitiveRefusal(out) || isRecord(out.error) && out.error.retryable === true
|
|
1093
|
+
|| ["arc_home_hl_return_source_not_final", "arc_home_hl_return_source_broadcast_in_flight",
|
|
1094
|
+
"arc_home_hl_return_store_unavailable"].includes(code)) {
|
|
1095
|
+
return new Wait(`deposit_recovery_pending:${code}`);
|
|
1096
|
+
}
|
|
1097
|
+
this.hold(code, "Felix will not reopen this return's Arc deposit. The USDC is the owner's on Arbitrum or in "
|
|
1098
|
+
+ "Gateway; never sign another withdrawal.", { money_moved: true, error: errorOf(out) });
|
|
1099
|
+
}
|
|
1100
|
+
if (out.recovered_from_operation_id !== pin.operation_id || out.intent_id !== prepared.intent_id
|
|
1101
|
+
|| !UUID_RE.test(String(out.operation_id)) || out.operation_id === pin.operation_id) {
|
|
1102
|
+
this.hold("hl_return_deposit_recovery_invalid", "Felix's reopened deposit does not follow the expired one.");
|
|
1103
|
+
}
|
|
1104
|
+
// Record the new row FIRST, then archive every per-deposit checkpoint of
|
|
1105
|
+
// the old row so none of its signatures or hashes can be reused.
|
|
1106
|
+
const next = count + 1;
|
|
1107
|
+
const archive = { expired_operation_id: pin.operation_id };
|
|
1108
|
+
for (const name of PER_DEPOSIT_CHECKPOINTS) {
|
|
1109
|
+
const value = this.ports.journal.getCheckpoint(name);
|
|
1110
|
+
if (value !== undefined)
|
|
1111
|
+
archive[name] = value;
|
|
1112
|
+
}
|
|
1113
|
+
this.save(recoveryArchiveCp(next), archive);
|
|
1114
|
+
this.save(CP.recoveries, { count: next, operation_id: String(out.operation_id), at_ms: this.nowMs() });
|
|
1115
|
+
for (const name of PER_DEPOSIT_CHECKPOINTS)
|
|
1116
|
+
this.ports.journal.deleteCheckpoint(name);
|
|
1117
|
+
this.view = null;
|
|
1118
|
+
const proven = this.cp(CP.venueConfirmed);
|
|
1119
|
+
const arrived = BigInt(proven.arrived_units);
|
|
1120
|
+
this.pinDeposit(prepared, out, arrived, gatewayMaxFeeUnits(arrived));
|
|
1121
|
+
}
|
|
1122
|
+
acceptView(view, pin) {
|
|
1123
|
+
if (view.operation_id !== pin.operation_id || view.kind !== "arc_deposit_in") {
|
|
1124
|
+
this.hold("hl_return_deposit_identity_changed", "Felix answered for a different operation.");
|
|
1125
|
+
}
|
|
1126
|
+
if (digest(view.burn_intent_typed_data) !== pin.burn_digest
|
|
1127
|
+
|| digest(view.source_calls) !== pin.source_calls_digest
|
|
1128
|
+
|| String(view.amount_units) !== pin.value_units || String(view.max_fee_units) !== pin.max_fee_units
|
|
1129
|
+
|| !sameAddress(view.destination, this.safe)) {
|
|
1130
|
+
this.hold("hl_return_deposit_plan_changed", "The deposit plan changed after it was pinned; nothing is signed.");
|
|
1131
|
+
}
|
|
1132
|
+
const order = ["prepared", "source_submitted", "gateway_funded", "burn_attested", "mint_submitted", "completed"];
|
|
1133
|
+
const previous = this.view ? order.indexOf(String(this.view.phase)) : -1;
|
|
1134
|
+
const next = order.indexOf(String(view.phase));
|
|
1135
|
+
if (previous >= 0 && next >= 0 && next < previous) {
|
|
1136
|
+
this.hold("hl_return_deposit_phase_regressed", "Felix's deposit phase went backwards; nothing is re-sent.");
|
|
1137
|
+
}
|
|
1138
|
+
this.view = view;
|
|
1139
|
+
}
|
|
1140
|
+
async signBurn(pin) {
|
|
1141
|
+
const existing = this.cp(CP.burnSigned);
|
|
1142
|
+
if (existing) {
|
|
1143
|
+
if (existing.burn_digest !== pin.burn_digest)
|
|
1144
|
+
this.hold("hl_return_burn_pin_changed", "The burn intent changed.");
|
|
1145
|
+
return existing.signature;
|
|
1146
|
+
}
|
|
1147
|
+
const typed = this.view.burn_intent_typed_data;
|
|
1148
|
+
const m = typed.message;
|
|
1149
|
+
const s = m.spec;
|
|
1150
|
+
const typedData = {
|
|
1151
|
+
domain: typed.domain,
|
|
1152
|
+
types: BURN_INTENT_TYPES,
|
|
1153
|
+
primaryType: "BurnIntent",
|
|
1154
|
+
message: {
|
|
1155
|
+
maxBlockHeight: uint(m.maxBlockHeight), maxFee: uint(m.maxFee),
|
|
1156
|
+
spec: { ...s, value: uint(s.value) },
|
|
1157
|
+
},
|
|
1158
|
+
};
|
|
1159
|
+
const signature = await this.ports.signer.signTypedData(typedData);
|
|
1160
|
+
const recovered = await recoverTypedDataAddress({ ...typedData, signature });
|
|
1161
|
+
if (!sameAddress(recovered, this.owner))
|
|
1162
|
+
this.hold("hl_return_burn_signature_invalid", "Owner signature mismatch.");
|
|
1163
|
+
this.save(CP.burnSigned, { signature, burn_digest: pin.burn_digest });
|
|
1164
|
+
return signature;
|
|
1165
|
+
}
|
|
1166
|
+
async sourceStep(pin) {
|
|
1167
|
+
const shortfall = BigInt(pin.shortfall_units);
|
|
1168
|
+
const signedSource = this.cp(CP.sourceSigned);
|
|
1169
|
+
if (!signedSource && !this.cp(CP.burnSigned)
|
|
1170
|
+
&& Math.floor(this.nowMs() / 1000) > pin.expires_at - SOURCE_SIGN_HEADROOM_SECONDS) {
|
|
1171
|
+
// Too close to the deposit row's TTL to finish the source leg: sign
|
|
1172
|
+
// nothing, let reconcile expire the row, and report where the money is.
|
|
1173
|
+
return this.reconcile(pin);
|
|
1174
|
+
}
|
|
1175
|
+
const burnSignature = await this.signBurn(pin);
|
|
1176
|
+
if (shortfall > 0n) {
|
|
1177
|
+
const sent = await this.sourceTransactions(pin, shortfall);
|
|
1178
|
+
if (sent instanceof Wait)
|
|
1179
|
+
return sent;
|
|
1180
|
+
}
|
|
1181
|
+
return this.reportSource(pin, burnSignature);
|
|
1182
|
+
}
|
|
1183
|
+
// Resolves (void) only once the node acknowledged both exact signed
|
|
1184
|
+
// transactions or they are mined; the source report names the deposit hash,
|
|
1185
|
+
// so it is never sent for bytes no node has seen.
|
|
1186
|
+
async sourceTransactions(pin, shortfall) {
|
|
1187
|
+
let signed = this.cp(CP.sourceSigned);
|
|
1188
|
+
const arbitrum = this.ports.arbitrum;
|
|
1189
|
+
if (!signed) {
|
|
1190
|
+
if (this.cp(CP.sourceBroadcastStarted)) {
|
|
1191
|
+
this.hold("hl_return_source_signature_missing", "A source broadcast was started but its signed bytes are missing.");
|
|
1192
|
+
}
|
|
1193
|
+
if (Math.floor(this.nowMs() / 1000) > pin.expires_at - SOURCE_SIGN_HEADROOM_SECONDS) {
|
|
1194
|
+
return this.reconcile(pin);
|
|
1195
|
+
}
|
|
1196
|
+
const balance = await arbitrum.usdcBalance(this.owner);
|
|
1197
|
+
if (balance < shortfall) {
|
|
1198
|
+
this.hold("hl_return_arbitrum_balance_short", "The owner's Arbitrum USDC no longer covers the Gateway deposit.", { money_moved: true });
|
|
1199
|
+
}
|
|
1200
|
+
const nonce = await arbitrum.pendingNonce(this.owner);
|
|
1201
|
+
const fees = await arbitrum.fees();
|
|
1202
|
+
if (!Number.isSafeInteger(nonce) || nonce < 0 || fees.maxFeePerGas <= 0n
|
|
1203
|
+
|| fees.maxFeePerGas > MAX_ARB_FEE_PER_GAS || fees.maxPriorityFeePerGas > fees.maxFeePerGas) {
|
|
1204
|
+
return new Wait("arbitrum_fees_out_of_bounds");
|
|
1205
|
+
}
|
|
1206
|
+
const base = { chainId: ARB_CHAIN_ID, type: "eip1559", value: 0n,
|
|
1207
|
+
maxFeePerGas: fees.maxFeePerGas, maxPriorityFeePerGas: fees.maxPriorityFeePerGas };
|
|
1208
|
+
const approve = await this.ports.signer.signTransaction({ ...base, nonce, to: ARB_USDC, gas: SOURCE_APPROVE_GAS,
|
|
1209
|
+
data: encodeFunctionData({ abi: ABI, functionName: "approve", args: [GATEWAY_WALLET, shortfall] }) });
|
|
1210
|
+
const deposit = await this.ports.signer.signTransaction({ ...base, nonce: nonce + 1, to: GATEWAY_WALLET,
|
|
1211
|
+
gas: SOURCE_DEPOSIT_GAS,
|
|
1212
|
+
data: encodeFunctionData({ abi: ABI, functionName: "deposit", args: [ARB_USDC, shortfall] }) });
|
|
1213
|
+
signed = {
|
|
1214
|
+
nonce, raws: [approve, deposit], hashes: [keccak256(approve), keccak256(deposit)],
|
|
1215
|
+
accepted: [false, false], sends: 0,
|
|
1216
|
+
};
|
|
1217
|
+
this.save(CP.sourceSigned, signed);
|
|
1218
|
+
}
|
|
1219
|
+
const receipts = await Promise.all(signed.hashes.map((hash) => arbitrum.receipt(hash).catch(() => undefined)));
|
|
1220
|
+
if (receipts.some((receipt) => receipt === undefined))
|
|
1221
|
+
return new Wait("arbitrum_receipt_unreadable");
|
|
1222
|
+
if (receipts.some((receipt) => receipt && receipt.success === false)) {
|
|
1223
|
+
this.hold("hl_return_source_reverted", "An owner source transaction reverted; nothing is re-signed.", { money_moved: true });
|
|
1224
|
+
}
|
|
1225
|
+
const accepted = signed.accepted.map((value, index) => value || Boolean(receipts[index]));
|
|
1226
|
+
if (accepted.every(Boolean)) {
|
|
1227
|
+
if (!signed.accepted.every(Boolean))
|
|
1228
|
+
this.save(CP.sourceSigned, { ...signed, accepted });
|
|
1229
|
+
return;
|
|
1230
|
+
}
|
|
1231
|
+
if (this.cp(CP.sourceBroadcastStarted)) {
|
|
1232
|
+
const latest = await arbitrum.latestNonce(this.owner).catch(() => -1);
|
|
1233
|
+
if (latest < 0)
|
|
1234
|
+
return new Wait("arbitrum_nonce_unreadable");
|
|
1235
|
+
const consumedElsewhere = (!receipts[0] && latest > signed.nonce) || (!receipts[1] && latest > signed.nonce + 1);
|
|
1236
|
+
if (consumedElsewhere) {
|
|
1237
|
+
this.hold("hl_return_source_nonce_consumed", "The owner's Arbitrum nonce was used by another transaction; the signed source calls can no longer land "
|
|
1238
|
+
+ "as signed and are never re-signed.", { money_moved: true });
|
|
1239
|
+
}
|
|
1240
|
+
if (signed.sends >= MAX_SOURCE_SENDS)
|
|
1241
|
+
return new Wait("arbitrum_source_unacknowledged");
|
|
1242
|
+
}
|
|
1243
|
+
else {
|
|
1244
|
+
this.save(CP.sourceBroadcastStarted, { hashes: signed.hashes, at_ms: this.nowMs() });
|
|
1245
|
+
}
|
|
1246
|
+
signed = { ...signed, accepted, sends: signed.sends + 1 };
|
|
1247
|
+
this.save(CP.sourceSigned, signed);
|
|
1248
|
+
for (let index = 0; index < signed.raws.length; index++) {
|
|
1249
|
+
if (accepted[index])
|
|
1250
|
+
continue;
|
|
1251
|
+
let hash;
|
|
1252
|
+
try {
|
|
1253
|
+
const broadcaster = this.ports.arbitrumBroadcast;
|
|
1254
|
+
if (!broadcaster || !this.broadcastReady()) {
|
|
1255
|
+
this.hold("hl_return_arbitrum_broadcast_unavailable", "The signed source calls are saved but this client has no Felix-scoped Arbitrum relay to send them. "
|
|
1256
|
+
+ "They are never re-signed.", { money_moved: true });
|
|
1257
|
+
}
|
|
1258
|
+
hash = lower(await broadcaster.sendRawTransaction(signed.raws[index], pin.operation_id));
|
|
1259
|
+
}
|
|
1260
|
+
catch {
|
|
1261
|
+
// Lost, "already known" or "nonce too low": the same bytes are re-sent
|
|
1262
|
+
// next step and the hash's receipt decides; never a new signature.
|
|
1263
|
+
continue;
|
|
1264
|
+
}
|
|
1265
|
+
if (hash !== signed.hashes[index]) {
|
|
1266
|
+
this.hold("hl_return_source_hash_mismatch", "The Arbitrum node answered a different transaction hash.", { money_moved: true });
|
|
1267
|
+
}
|
|
1268
|
+
accepted[index] = true;
|
|
1269
|
+
}
|
|
1270
|
+
this.save(CP.sourceSigned, { ...signed, accepted });
|
|
1271
|
+
if (!accepted.every(Boolean))
|
|
1272
|
+
return new Wait("arbitrum_source_unacknowledged");
|
|
1273
|
+
}
|
|
1274
|
+
async reportSource(pin, burnSignature) {
|
|
1275
|
+
const shortfall = BigInt(pin.shortfall_units);
|
|
1276
|
+
const signed = this.cp(CP.sourceSigned);
|
|
1277
|
+
const body = { account_id: this.request.account_id, burn_intent_signature: burnSignature };
|
|
1278
|
+
if (shortfall > 0n)
|
|
1279
|
+
body.source_tx_hash = signed.hashes[1];
|
|
1280
|
+
const out = await this.api("POST", `/v1/arc-home/deposits/${pin.operation_id}/source-submitted`, body);
|
|
1281
|
+
if (failed(out)) {
|
|
1282
|
+
const code = errorCode(out);
|
|
1283
|
+
if (Math.floor(this.nowMs() / 1000) >= pin.expires_at) {
|
|
1284
|
+
// Past the row's TTL the report can no longer land; reconcile shows
|
|
1285
|
+
// whether the row expired (then G4 recovery takes over) or advanced.
|
|
1286
|
+
return this.reconcile(pin);
|
|
1287
|
+
}
|
|
1288
|
+
if (!definitiveRefusal(out) || code === "arc_withdrawal_revision_conflict")
|
|
1289
|
+
return new Wait(`source_report_uncertain:${code}`);
|
|
1290
|
+
if (code === "arc_withdrawal_phase_conflict") {
|
|
1291
|
+
// Moved on without this report (or a lost earlier answer): re-read.
|
|
1292
|
+
this.view = null;
|
|
1293
|
+
return new Wait(code);
|
|
1294
|
+
}
|
|
1295
|
+
this.hold(code, "Felix refused the source report. Nothing is re-signed.", { error: errorOf(out), money_moved: true });
|
|
1296
|
+
}
|
|
1297
|
+
this.acceptView(out, pin);
|
|
1298
|
+
this.save(CP.sourceReported, { at_ms: this.nowMs() });
|
|
1299
|
+
}
|
|
1300
|
+
async reconcile(pin) {
|
|
1301
|
+
const before = String(this.view?.phase);
|
|
1302
|
+
const out = await this.api("POST", `/v1/arc-home/operations/${pin.operation_id}/reconcile`, {
|
|
1303
|
+
account_id: this.request.account_id,
|
|
1304
|
+
});
|
|
1305
|
+
if (failed(out)) {
|
|
1306
|
+
this.view = null;
|
|
1307
|
+
return new Wait(`reconcile_pending:${errorCode(out)}`);
|
|
1308
|
+
}
|
|
1309
|
+
this.acceptView(out, pin);
|
|
1310
|
+
const after = String(out.phase);
|
|
1311
|
+
const minted = after === "burn_attested" && isRecord(out.mint_safe_transaction);
|
|
1312
|
+
if (after === before && !minted)
|
|
1313
|
+
return new Wait(`deposit_${after}`);
|
|
1314
|
+
}
|
|
1315
|
+
async mintStep(pin) {
|
|
1316
|
+
const view = this.view;
|
|
1317
|
+
const mint = view.mint_safe_transaction;
|
|
1318
|
+
const typed = mint.typed_data;
|
|
1319
|
+
const safeTxHash = lower(mint.safe_tx_hash);
|
|
1320
|
+
const bad = (why) => this.hold("hl_return_mint_payload_invalid", `The Arc mint SafeTx failed the client check (${why}); it was not signed.`, { money_moved: true });
|
|
1321
|
+
if (mint.step !== "gateway_mint" || !HASH_RE.test(safeTxHash))
|
|
1322
|
+
bad("identity");
|
|
1323
|
+
if (!exactKeys(typed, ["domain", "types", "primaryType", "message"]))
|
|
1324
|
+
bad("typed_data");
|
|
1325
|
+
const t = typed;
|
|
1326
|
+
if (t.primaryType !== "SafeTx" || !exactKeys(t.domain, ["chainId", "verifyingContract"])
|
|
1327
|
+
|| t.domain.chainId !== ARC_CHAIN_ID
|
|
1328
|
+
|| !sameAddress(t.domain.verifyingContract, this.safe)
|
|
1329
|
+
|| canonical(t.types) !== canonical({ ...SAFE_TX_TYPES, EIP712Domain: SAFE_DOMAIN_TYPES })) {
|
|
1330
|
+
bad("domain");
|
|
1331
|
+
}
|
|
1332
|
+
const attestation = view.attestation;
|
|
1333
|
+
const attestationSignature = view.attestation_signature;
|
|
1334
|
+
if (typeof attestation !== "string" || !HEX_RE.test(attestation) || attestation === "0x"
|
|
1335
|
+
|| typeof attestationSignature !== "string" || !HEX_RE.test(attestationSignature)
|
|
1336
|
+
|| attestationSignature === "0x") {
|
|
1337
|
+
bad("attestation");
|
|
1338
|
+
}
|
|
1339
|
+
const mintData = encodeFunctionData({
|
|
1340
|
+
abi: ABI, functionName: "gatewayMint", args: [attestation, attestationSignature],
|
|
1341
|
+
});
|
|
1342
|
+
const call = view.mint_call;
|
|
1343
|
+
if (!isRecord(call) || call.chain_id !== ARC_CHAIN_ID || !sameAddress(call.to, GATEWAY_MINTER)
|
|
1344
|
+
|| lower(call.data) !== mintData.toLowerCase() || String(call.value) !== "0") {
|
|
1345
|
+
bad("mint_call");
|
|
1346
|
+
}
|
|
1347
|
+
const m = t.message;
|
|
1348
|
+
if (!exactKeys(m, SAFE_TX_TYPES.SafeTx.map((field) => field.name)))
|
|
1349
|
+
bad("message_keys");
|
|
1350
|
+
const msg = m;
|
|
1351
|
+
if (!sameAddress(msg.to, GATEWAY_MINTER) || uint(msg.value) !== 0n || lower(msg.data) !== mintData.toLowerCase()
|
|
1352
|
+
|| msg.operation !== 0 || uint(msg.safeTxGas) !== 0n || uint(msg.baseGas) !== 0n || uint(msg.gasPrice) !== 0n
|
|
1353
|
+
|| !sameAddress(msg.gasToken, ZERO_ADDRESS) || !sameAddress(msg.refundReceiver, ZERO_ADDRESS)
|
|
1354
|
+
|| uint(msg.nonce) === null) {
|
|
1355
|
+
bad("message");
|
|
1356
|
+
}
|
|
1357
|
+
const typedData = {
|
|
1358
|
+
domain: t.domain,
|
|
1359
|
+
types: SAFE_TX_TYPES,
|
|
1360
|
+
primaryType: "SafeTx",
|
|
1361
|
+
message: { ...msg, value: 0n, safeTxGas: 0n, baseGas: 0n, gasPrice: 0n, nonce: uint(msg.nonce) },
|
|
1362
|
+
};
|
|
1363
|
+
if (hashTypedData(typedData).toLowerCase() !== safeTxHash)
|
|
1364
|
+
bad("safe_tx_hash");
|
|
1365
|
+
let signed = this.cp(mintCp(safeTxHash));
|
|
1366
|
+
if (!signed) {
|
|
1367
|
+
const all = this.cp(CP.mintSignatures)?.hashes ?? [];
|
|
1368
|
+
if (all.length >= MAX_MINT_SIGNATURES) {
|
|
1369
|
+
this.hold("hl_return_mint_signature_budget", "Too many Arc mint SafeTx re-preparations; reconcile manually.", { money_moved: true });
|
|
1370
|
+
}
|
|
1371
|
+
const signature = await this.ports.signer.signTypedData(typedData);
|
|
1372
|
+
const recovered = await recoverTypedDataAddress({ ...typedData, signature });
|
|
1373
|
+
if (!sameAddress(recovered, this.owner))
|
|
1374
|
+
this.hold("hl_return_mint_signature_invalid", "Owner signature mismatch.");
|
|
1375
|
+
this.save(CP.mintSignatures, { hashes: [...all, safeTxHash] });
|
|
1376
|
+
signed = { signature };
|
|
1377
|
+
this.save(mintCp(safeTxHash), signed);
|
|
1378
|
+
}
|
|
1379
|
+
const postsCp = `hlret:mint:${safeTxHash}:posts`;
|
|
1380
|
+
const posts = Number(this.cp(postsCp)?.count ?? 0);
|
|
1381
|
+
if (posts > 0 && !this.reconciledSinceMintPost) {
|
|
1382
|
+
// An earlier post of this exact signature had no recorded answer: let
|
|
1383
|
+
// reconcile prove or re-relay it before the same bytes are posted again.
|
|
1384
|
+
this.reconciledSinceMintPost = true;
|
|
1385
|
+
return this.reconcile(pin);
|
|
1386
|
+
}
|
|
1387
|
+
if (posts >= MAX_MINT_POSTS)
|
|
1388
|
+
return new Wait("mint_signature_post_budget_spent");
|
|
1389
|
+
this.save(postsCp, { count: posts + 1 });
|
|
1390
|
+
this.reconciledSinceMintPost = false;
|
|
1391
|
+
const out = await this.api("POST", `/v1/arc-home/operations/${pin.operation_id}/mint-signature`, {
|
|
1392
|
+
account_id: this.request.account_id, signature: signed.signature,
|
|
1393
|
+
});
|
|
1394
|
+
if (failed(out)) {
|
|
1395
|
+
this.view = null; // re-read: a changed Safe nonce yields a new SafeTx
|
|
1396
|
+
const code = errorCode(out);
|
|
1397
|
+
if (definitiveRefusal(out) && !["arc_withdrawal_safe_nonce_changed", "arc_withdrawal_phase_conflict",
|
|
1398
|
+
"arc_withdrawal_revision_conflict"].includes(code)) {
|
|
1399
|
+
this.hold(code, "Felix refused the Arc mint signature.", { error: errorOf(out), money_moved: true });
|
|
1400
|
+
}
|
|
1401
|
+
return new Wait(`mint_signature_pending:${code}`);
|
|
1402
|
+
}
|
|
1403
|
+
this.acceptView(out, pin);
|
|
1404
|
+
}
|
|
1405
|
+
// ------------------------------------------------------------ completion
|
|
1406
|
+
async proveCompletion(prepared, pin) {
|
|
1407
|
+
const proven = this.cp(CP.venueConfirmed);
|
|
1408
|
+
const out = await this.api("GET", `/v1/arc-home/returns/${pin.operation_id}?${this.accountQuery()}`);
|
|
1409
|
+
if (failed(out))
|
|
1410
|
+
return new Wait(`completion_view_unavailable:${errorCode(out)}`);
|
|
1411
|
+
this.acceptView(out, pin);
|
|
1412
|
+
if (out.status !== "home_usable" || out.home_usable !== true || out.phase !== "completed" || out.terminal !== true
|
|
1413
|
+
|| out.money_moved !== true || out.intent_id !== prepared.intent_id
|
|
1414
|
+
|| String(out.home_credit_units) !== pin.value_units
|
|
1415
|
+
|| String(out.spoke_arrived_units) !== proven.arrived_units
|
|
1416
|
+
|| String(out.venue_fee_units) !== proven.venue_fee_units) {
|
|
1417
|
+
this.hold("hl_return_completion_view_invalid", "Felix's completed view does not match the pinned return.", { money_moved: true });
|
|
1418
|
+
}
|
|
1419
|
+
const mintHash = lower(out.mint_tx_hash);
|
|
1420
|
+
if (!HASH_RE.test(mintHash))
|
|
1421
|
+
this.hold("hl_return_mint_hash_missing", "Felix reports completion without a mint hash.");
|
|
1422
|
+
const arc = this.ports.arc;
|
|
1423
|
+
if (!arc || !this.arcReady())
|
|
1424
|
+
return new Wait("arc_reader_unavailable_completion_unproven");
|
|
1425
|
+
let receipt;
|
|
1426
|
+
try {
|
|
1427
|
+
receipt = await arc.mintReceipt(mintHash, pin.operation_id);
|
|
1428
|
+
}
|
|
1429
|
+
catch {
|
|
1430
|
+
return new Wait("arc_receipt_unreadable");
|
|
1431
|
+
}
|
|
1432
|
+
if (!receipt || receipt.finalized !== true)
|
|
1433
|
+
return new Wait("arc_mint_not_finalized");
|
|
1434
|
+
const value = BigInt(pin.value_units);
|
|
1435
|
+
const credits = (receipt.usdc_transfers || []).filter((log) => sameAddress(log.to, this.safe));
|
|
1436
|
+
const exact = credits.filter((log) => sameAddress(log.token, ARC_USDC) && sameAddress(log.from, ZERO_ADDRESS)
|
|
1437
|
+
&& uint(log.value) === value);
|
|
1438
|
+
if (receipt.success !== true || exact.length !== 1 || credits.length !== 1) {
|
|
1439
|
+
this.hold("hl_return_arc_credit_unproven", "The finalized Arc mint receipt does not credit the Safe with exactly the planned value.", { money_moved: true });
|
|
1440
|
+
}
|
|
1441
|
+
const native = receipt.native_usdc_transfers || [];
|
|
1442
|
+
let nativeIn = 0n;
|
|
1443
|
+
let nativeOut = 0n;
|
|
1444
|
+
for (const log of native) {
|
|
1445
|
+
if (!sameAddress(log.token, "0xfffffffffffffffffffffffffffffffffffffffe"))
|
|
1446
|
+
continue;
|
|
1447
|
+
const amount = uint(log.value);
|
|
1448
|
+
if (amount === null) {
|
|
1449
|
+
this.hold("hl_return_arc_native_credit_unproven", "The mint receipt has a malformed native Arc credit.", { money_moved: true });
|
|
1450
|
+
}
|
|
1451
|
+
if (sameAddress(log.to, this.safe))
|
|
1452
|
+
nativeIn += amount;
|
|
1453
|
+
if (sameAddress(log.from, this.safe))
|
|
1454
|
+
nativeOut += amount;
|
|
1455
|
+
}
|
|
1456
|
+
if (nativeIn - nativeOut < value * 10n ** 12n) {
|
|
1457
|
+
this.hold("hl_return_arc_native_credit_unproven", "The mint transaction does not prove the Safe retained its native Arc USDC credit.", { money_moved: true });
|
|
1458
|
+
}
|
|
1459
|
+
let finalized;
|
|
1460
|
+
let before;
|
|
1461
|
+
let after;
|
|
1462
|
+
try {
|
|
1463
|
+
finalized = await arc.finalizedBlock(pin.operation_id);
|
|
1464
|
+
if (finalized < receipt.block_number)
|
|
1465
|
+
return new Wait("arc_mint_not_finalized");
|
|
1466
|
+
before = await arc.usdcBalance(this.safe, receipt.block_number - 1, pin.operation_id);
|
|
1467
|
+
after = await arc.usdcBalance(this.safe, receipt.block_number, pin.operation_id);
|
|
1468
|
+
}
|
|
1469
|
+
catch {
|
|
1470
|
+
return new Wait("arc_balance_unreadable");
|
|
1471
|
+
}
|
|
1472
|
+
const result = this.result("completed", {
|
|
1473
|
+
home_usable: true,
|
|
1474
|
+
money_moved: true,
|
|
1475
|
+
next_action: "none",
|
|
1476
|
+
hint: "Hyperliquid capital is in the Arc home Safe, proven from a finalized mint receipt and Safe balance.",
|
|
1477
|
+
credit: {
|
|
1478
|
+
operation_id: pin.operation_id,
|
|
1479
|
+
mint_tx_hash: mintHash,
|
|
1480
|
+
mint_block: receipt.block_number,
|
|
1481
|
+
finalized_block: finalized,
|
|
1482
|
+
home_credit_units: pin.value_units,
|
|
1483
|
+
gateway_max_fee_units: pin.max_fee_units,
|
|
1484
|
+
safe_balance_before_units: before.toString(),
|
|
1485
|
+
safe_balance_after_units: after.toString(),
|
|
1486
|
+
},
|
|
1487
|
+
});
|
|
1488
|
+
this.save(CP.completed, { result: result });
|
|
1489
|
+
throw new Stop(result);
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1492
|
+
export async function driveHlArcReturn(request, ports, options = {}) {
|
|
1493
|
+
const driver = new Driver(request, ports, options);
|
|
1494
|
+
try {
|
|
1495
|
+
return await driver.run();
|
|
1496
|
+
}
|
|
1497
|
+
catch (error) {
|
|
1498
|
+
if (error instanceof Stop)
|
|
1499
|
+
return error.result;
|
|
1500
|
+
// A port or journal failure mid-step. Movement is read from the journal as
|
|
1501
|
+
// it stands, so a failure after a submission marker never reads "false".
|
|
1502
|
+
const journal = ports.journal;
|
|
1503
|
+
const moved = journal.getCheckpoint(CP.venueConfirmed) ? true
|
|
1504
|
+
: journal.getCheckpoint(CP.venueSubmissionStarted) ? "unknown" : false;
|
|
1505
|
+
const prepared = journal.getCheckpoint(CP.prepared);
|
|
1506
|
+
const deposit = journal.getCheckpoint(CP.deposit);
|
|
1507
|
+
return {
|
|
1508
|
+
ok: false,
|
|
1509
|
+
status: "in_progress",
|
|
1510
|
+
account_id: String(request.account_id),
|
|
1511
|
+
idempotency_key: String(request.idempotency_key),
|
|
1512
|
+
intent_id: prepared?.intent_id ?? null,
|
|
1513
|
+
operation_id: deposit?.operation_id ?? null,
|
|
1514
|
+
stage: deposit ? "arc_deposit" : "venue_withdrawal",
|
|
1515
|
+
money_moved: moved,
|
|
1516
|
+
user_funds_moved: moved,
|
|
1517
|
+
home_usable: false,
|
|
1518
|
+
next_action: "resume_with_same_idempotency_key",
|
|
1519
|
+
reason: "hl_return_driver_interrupted",
|
|
1520
|
+
error: { message: String(redactOutput(String(error?.message || error))).slice(0, 240) },
|
|
1521
|
+
hint: "The driver stopped mid-step. Resume with the same arguments; saved signatures are re-used, never re-made.",
|
|
1522
|
+
};
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
// Production signer: the SAME owner key and burn-intent signer the Arc
|
|
1526
|
+
// settlement tools use. Owner-local only: null under the hosted HTTP transport
|
|
1527
|
+
// or without a local owner key, so the driver then refuses at checkScope
|
|
1528
|
+
// (hl_return_owner_key_mismatch) before any call.
|
|
1529
|
+
export function settlementSignerPort() {
|
|
1530
|
+
const address = settlementOwnerAddress();
|
|
1531
|
+
const key = getRuntimeOwnerPrivateKey();
|
|
1532
|
+
if (!address || !/^0x[0-9a-fA-F]{64}$/.test(key))
|
|
1533
|
+
return null;
|
|
1534
|
+
const account = privateKeyToAccount(key);
|
|
1535
|
+
return {
|
|
1536
|
+
address,
|
|
1537
|
+
signTypedData: (typedData) => (typedData.primaryType === "BurnIntent"
|
|
1538
|
+
? signBurnIntent(typedData)
|
|
1539
|
+
: account.signTypedData(typedData)),
|
|
1540
|
+
signTransaction: (transaction) => account.signTransaction(transaction),
|
|
1541
|
+
};
|
|
1542
|
+
}
|
|
1543
|
+
// Pinned chain constants for the production ports (arc-hl-return-ports.ts).
|
|
1544
|
+
export const HL_ARC_CHAIN = {
|
|
1545
|
+
ARB_CHAIN_ID, ARB_USDC, GATEWAY_WALLET, ARC_CHAIN_ID, ARC_USDC,
|
|
1546
|
+
};
|
|
1547
|
+
export const __test = { gatewayMaxFeeUnits, hlAmountText, usdcTextUnits, DEPOSIT_KEY_SUFFIX };
|