felix-mcp 2.0.110 → 2.0.123

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1168 @@
1
+ // ARC_HOME_2026_09_17: the Arc home is the owner's 1-of-1 Safe on Arc (chain
2
+ // 5042) with the reviewed scoped hub module. Every money movement out of that
3
+ // Safe is signed locally by the client-held owner key, and this module is the
4
+ // only place that decides whether a server payload deserves a signature.
5
+ //
6
+ // The rule: never blind-sign. Each signing path re-derives what it expects
7
+ // (Safe address from CREATE2, SafeTx digest from the typed data, calldata from
8
+ // the intent, module address from the create call) and refuses on any
9
+ // mismatch. Felix pays Arc gas because every SafeTx carries zero gasPrice,
10
+ // zero safeTxGas/baseGas and a zero refundReceiver; a payload that sets any of
11
+ // those would let a relayer drain the Safe for "gas", so they are checked.
12
+ import { concatHex, createPublicClient, defineChain, encodeAbiParameters, encodeFunctionData, getAddress, hashStruct, hashTypedData, http, keccak256, pad, parseAbi, toFunctionSelector, } from "viem";
13
+ import { privateKeyToAccount } from "viem/accounts";
14
+ import { getRuntimeOwnerPrivateKey } from "./secret-state.js";
15
+ import { ARC_BROADCAST_RECEIPT_GRACE_MS, broadcastSignedTransaction, relayRetry, } from "./arc-settlement.js";
16
+ const PRIVATE_KEY_RE = /^0x[0-9a-fA-F]{64}$/;
17
+ const ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
18
+ const BYTES32_RE = /^0x[0-9a-fA-F]{64}$/;
19
+ const HEX_RE = /^0x([0-9a-fA-F]{2})*$/;
20
+ const UNITS_RE = /^(?:0|[1-9][0-9]{0,29})$/;
21
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
22
+ export const ARC_MAINNET_CHAIN_ID = 5042;
23
+ export const ARC_TESTNET_CHAIN_ID = 5_042_002;
24
+ export const ARC_GATEWAY_DOMAIN = 26;
25
+ export const ARC_HOME_PROOF_VERSION = "Felix Arc hub Safe v1";
26
+ export const ARC_HUB_MODULE_VERSION = 3;
27
+ export const ARC_HUB_AGENT_AUTHORITY = "sweep_home";
28
+ export const ARC_HUB_MODULE_SALT_TAG = "felix-arc-hub-module-v3";
29
+ export const ARC_HOME_PREPARE_TTL_SECONDS = 600;
30
+ export const ARC_HOME_MAX_FEE_UNITS = 5000000n;
31
+ export const ARC_HOME_CHALLENGE_MAX_TTL_SECONDS = 900;
32
+ export const ARC_HOME_DELEGATION_MAX_DAYS = 90;
33
+ // Pinned Arc mainnet settlement addresses (primary-sourced, identical to the
34
+ // engine's activation manifest pins).
35
+ export const ARC_USDC = getAddress("0x3600000000000000000000000000000000000000");
36
+ export const ARC_GATEWAY_WALLET = getAddress("0x77777777Dcc4d5A8B6E418Fd04D8997ef11000eE");
37
+ export const ARC_GATEWAY_MINTER = getAddress("0x2222222d7164433c4C09B0b0D809a9b52C04C205");
38
+ // Canonical Safe 1.3.0 deployments (same addresses on Arc and Polygon).
39
+ export const SAFE_PROXY_FACTORY = getAddress("0xa6B71E26C5e0845f74c812102Ca7114b6a896AB2");
40
+ export const SAFE_L2_SINGLETON = getAddress("0x3E5c63644E683549055b9Be8653de26E0B4CD36E");
41
+ export const SAFE_FALLBACK_HANDLER = getAddress("0xf48f2B2d2a534e402487b3ee7C18c33Aec0Fe5e4");
42
+ export const SAFE_MULTISEND_CALL_ONLY = getAddress("0x40A2aCCbd92BCA938b02010E17A5b8929b49130D");
43
+ export const SAFE_CREATE_CALL = getAddress("0x7cbB62EaA69F79e6873cD1ecB2392971036cFAa4");
44
+ export const ARC_HOME_HUB_SAFE_SALT_NONCE = 0n;
45
+ const ZERO_ADDRESS = getAddress("0x0000000000000000000000000000000000000000");
46
+ // Safe 1.3.0 GnosisSafeProxy creation code, as returned by
47
+ // SafeProxyFactory.proxyCreationCode(). Pinned so the Safe CREATE2 prediction
48
+ // needs no network call, and hash-checked so a bad paste cannot silently
49
+ // change a predicted address.
50
+ export const SAFE_PROXY_CREATION_CODE = ("0x608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b81019080805190"
51
+ + "60200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16141561"
52
+ + "00ca576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602281526020"
53
+ + "01806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff02191690"
54
+ + "8373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffff"
55
+ + "ffffffffffffffff600054167fa619486e00000000000000000000000000000000000000000000000000000000600035141560505780600052602060"
56
+ + "00f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a49180"
57
+ + "76d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070"
58
+ + "726f7669646564");
59
+ export const SAFE_PROXY_CREATION_CODE_HASH = "0x44425997c3cd3b9f0cd37ae80e154b1bfc14d921d252ee5368c53f1ccb5c932b";
60
+ export const ARC_HOME_CHAIN = "arc";
61
+ export const ARC_HOME_EXTERNAL_CHAINS = {
62
+ ethereum: { domain: 0, chain_id: 1, usdc: getAddress("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48") },
63
+ arbitrum: { domain: 3, chain_id: 42161, usdc: getAddress("0xaf88d065e77c8cC2239327C5EDb3A432268e5831") },
64
+ base: { domain: 6, chain_id: 8453, usdc: getAddress("0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913") },
65
+ polygon: { domain: 7, chain_id: 137, usdc: getAddress("0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359") },
66
+ };
67
+ export const ARC_HOME_WITHDRAWAL_CHAINS = [ARC_HOME_CHAIN, ...Object.keys(ARC_HOME_EXTERNAL_CHAINS)].sort();
68
+ export const ARC_HOME_DEPOSIT_CHAINS = Object.keys(ARC_HOME_EXTERNAL_CHAINS).sort();
69
+ const TRANSFER_SELECTOR = toFunctionSelector("function transfer(address,uint256)");
70
+ const APPROVE_SELECTOR = toFunctionSelector("function approve(address,uint256)");
71
+ const DEPOSIT_SELECTOR = toFunctionSelector("function deposit(address,uint256)");
72
+ const ADD_DELEGATE_SELECTOR = toFunctionSelector("function addDelegate(address,address)");
73
+ const GATEWAY_MINT_SELECTOR = toFunctionSelector("function gatewayMint(bytes,bytes)");
74
+ const MULTISEND_SELECTOR = toFunctionSelector("function multiSend(bytes)");
75
+ const ENABLE_MODULE_SELECTOR = toFunctionSelector("function enableModule(address)");
76
+ const PERFORM_CREATE2_SELECTOR = toFunctionSelector("function performCreate2(uint256,bytes,bytes32)");
77
+ const SAFE_TX_FIELDS = [
78
+ { name: "to", type: "address" },
79
+ { name: "value", type: "uint256" },
80
+ { name: "data", type: "bytes" },
81
+ { name: "operation", type: "uint8" },
82
+ { name: "safeTxGas", type: "uint256" },
83
+ { name: "baseGas", type: "uint256" },
84
+ { name: "gasPrice", type: "uint256" },
85
+ { name: "gasToken", type: "address" },
86
+ { name: "refundReceiver", type: "address" },
87
+ { name: "nonce", type: "uint256" },
88
+ ];
89
+ const SAFE_TX_DOMAIN_FIELDS = [
90
+ { name: "chainId", type: "uint256" },
91
+ { name: "verifyingContract", type: "address" },
92
+ ];
93
+ // Pinned Circle Gateway burn-intent types. The server's own `types` object is
94
+ // never used for signing: a swapped type list would change the digest while
95
+ // the human-readable message stayed innocent.
96
+ const BURN_INTENT_TYPES = {
97
+ TransferSpec: [
98
+ { name: "version", type: "uint32" },
99
+ { name: "sourceDomain", type: "uint32" },
100
+ { name: "destinationDomain", type: "uint32" },
101
+ { name: "sourceContract", type: "bytes32" },
102
+ { name: "destinationContract", type: "bytes32" },
103
+ { name: "sourceToken", type: "bytes32" },
104
+ { name: "destinationToken", type: "bytes32" },
105
+ { name: "sourceDepositor", type: "bytes32" },
106
+ { name: "destinationRecipient", type: "bytes32" },
107
+ { name: "sourceSigner", type: "bytes32" },
108
+ { name: "destinationCaller", type: "bytes32" },
109
+ { name: "value", type: "uint256" },
110
+ { name: "salt", type: "bytes32" },
111
+ { name: "hookData", type: "bytes" },
112
+ ],
113
+ BurnIntent: [
114
+ { name: "maxBlockHeight", type: "uint256" },
115
+ { name: "maxFee", type: "uint256" },
116
+ { name: "spec", type: "TransferSpec" },
117
+ ],
118
+ };
119
+ export class ArcHomeError extends Error {
120
+ code;
121
+ moneyMoved;
122
+ constructor(code, message, moneyMoved = false) {
123
+ super(message);
124
+ this.code = code;
125
+ this.moneyMoved = moneyMoved;
126
+ }
127
+ }
128
+ function fail(code, message) {
129
+ throw new ArcHomeError(code, message);
130
+ }
131
+ function text(value, name) {
132
+ const output = typeof value === "string" ? value.trim() : "";
133
+ if (!output)
134
+ fail("arc_home_plan_invalid", `The Arc home response is missing ${name}.`);
135
+ return output;
136
+ }
137
+ function address(value, name) {
138
+ const output = text(value, name);
139
+ if (!ADDRESS_RE.test(output))
140
+ fail("arc_home_plan_invalid", `The Arc home response has an invalid ${name}.`);
141
+ return getAddress(output);
142
+ }
143
+ function hex(value, name) {
144
+ const output = text(value, name);
145
+ if (!HEX_RE.test(output))
146
+ fail("arc_home_plan_invalid", `The Arc home response has an invalid ${name}.`);
147
+ return output.toLowerCase();
148
+ }
149
+ function integer(value, name) {
150
+ if (typeof value === "string" && /^(?:0|[1-9][0-9]{0,15})$/.test(value))
151
+ return Number(value);
152
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
153
+ fail("arc_home_plan_invalid", `The Arc home response has an invalid ${name}.`);
154
+ }
155
+ return value;
156
+ }
157
+ export function parseUnits(value, name) {
158
+ const raw = typeof value === "number" && Number.isSafeInteger(value) && value >= 0
159
+ ? String(value)
160
+ : text(value, name);
161
+ if (!UNITS_RE.test(raw))
162
+ fail("arc_home_plan_invalid", `The Arc home response has an invalid ${name}.`);
163
+ return BigInt(raw);
164
+ }
165
+ export function arcUsdToUnits(amount, name = "amount", maximum = 10_000_000) {
166
+ if (!Number.isFinite(amount) || amount <= 0 || amount > maximum) {
167
+ fail("invalid_argument", `${name} must be a positive USDC amount of at most ${maximum}.`);
168
+ }
169
+ const [whole, fraction = ""] = amount.toFixed(6).split(".");
170
+ const units = BigInt(whole) * 1000000n + BigInt(fraction.padEnd(6, "0"));
171
+ if (Math.abs(Number(units) / 1_000_000 - amount) > 0.0000005) {
172
+ fail("invalid_argument", `${name} must have at most six decimal places.`);
173
+ }
174
+ return units;
175
+ }
176
+ export function unitsToUsd(units) {
177
+ const value = typeof units === "bigint" ? units : BigInt(String(units));
178
+ return Number(value) / 1_000_000;
179
+ }
180
+ export function unitsToAmountString(units) {
181
+ const whole = units / 1000000n;
182
+ const fraction = (units % 1000000n).toString().padStart(6, "0");
183
+ return `${whole}.${fraction}`;
184
+ }
185
+ function sameAddress(left, right) {
186
+ return typeof left === "string" && typeof right === "string"
187
+ && ADDRESS_RE.test(left) && ADDRESS_RE.test(right)
188
+ && left.slice(2).toLowerCase() === right.slice(2).toLowerCase();
189
+ }
190
+ function addressAsBytes32(value) {
191
+ return `0x${"0".repeat(24)}${value.slice(2).toLowerCase()}`;
192
+ }
193
+ function record(value, name) {
194
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
195
+ fail("arc_home_plan_invalid", `The Arc home response has an invalid ${name}.`);
196
+ }
197
+ return value;
198
+ }
199
+ // --------------------------------------------------------------------------- owner key
200
+ function ownerKeyOrThrow(privateKey) {
201
+ if (process.env.FELIX_MCP_TRANSPORT === "http") {
202
+ fail("local_signer_unavailable", "Client-held signing is disabled on the hosted MCP transport.");
203
+ }
204
+ const key = privateKey || getRuntimeOwnerPrivateKey();
205
+ if (!PRIVATE_KEY_RE.test(key || "")) {
206
+ fail("client_signature_required", "Configure FELIX_OWNER_PRIVATE_KEY in a trusted local launcher before using the Arc home.");
207
+ }
208
+ return key;
209
+ }
210
+ export function arcHomeOwnerAddress(privateKey) {
211
+ return privateKeyToAccount(ownerKeyOrThrow(privateKey)).address;
212
+ }
213
+ // --------------------------------------------------------------------------- CREATE2 predictions
214
+ function safeSetupInitializer(owner) {
215
+ return encodeFunctionData({
216
+ abi: parseAbi([
217
+ "function setup(address[] owners,uint256 threshold,address to,bytes data,address fallbackHandler,address paymentToken,uint256 payment,address paymentReceiver)",
218
+ ]),
219
+ functionName: "setup",
220
+ args: [[owner], 1n, ZERO_ADDRESS, "0x", SAFE_FALLBACK_HANDLER, ZERO_ADDRESS, 0n, ZERO_ADDRESS],
221
+ });
222
+ }
223
+ function create2Address(deployer, salt, initCodeHash) {
224
+ const digest = keccak256(concatHex(["0xff", deployer.toLowerCase(), salt, initCodeHash]));
225
+ return getAddress(`0x${digest.slice(-40)}`);
226
+ }
227
+ /** The owner's hub Safe address: identical on Arc and Polygon (salt nonce 0). */
228
+ export function predictArcHomeSafe(owner, saltNonce = ARC_HOME_HUB_SAFE_SALT_NONCE) {
229
+ const ownerAddress = address(owner, "owner_address");
230
+ if (keccak256(SAFE_PROXY_CREATION_CODE) !== SAFE_PROXY_CREATION_CODE_HASH) {
231
+ fail("arc_home_safe_prediction_unavailable", "The pinned Safe proxy creation code does not match its pinned hash.");
232
+ }
233
+ const initializerHash = keccak256(safeSetupInitializer(ownerAddress));
234
+ const salt = keccak256(concatHex([initializerHash, pad(`0x${saltNonce.toString(16)}`, { size: 32 })]));
235
+ const deployment = concatHex([
236
+ SAFE_PROXY_CREATION_CODE,
237
+ encodeAbiParameters([{ type: "uint256" }], [BigInt(SAFE_L2_SINGLETON)]),
238
+ ]);
239
+ return create2Address(SAFE_PROXY_FACTORY, salt, keccak256(deployment));
240
+ }
241
+ /** Module salt the engine uses: keccak(tag || safe). */
242
+ export function arcHomeModuleSalt(safe) {
243
+ return keccak256(concatHex([
244
+ `0x${Buffer.from(ARC_HUB_MODULE_SALT_TAG, "utf8").toString("hex")}`,
245
+ address(safe, "safe").toLowerCase(),
246
+ ]));
247
+ }
248
+ /** The module a CreateCall.performCreate2 payload will actually create. */
249
+ export function predictArcHomeModule(initCode, salt) {
250
+ return create2Address(SAFE_CREATE_CALL, salt, keccak256(initCode));
251
+ }
252
+ function decodeAddressAmount(data, selector, name) {
253
+ if (data.length !== 2 + 8 + 64 + 64 || data.slice(0, 10).toLowerCase() !== selector.toLowerCase()) {
254
+ fail("arc_home_plan_inconsistent", `The prepared ${name} call is not the expected function.`);
255
+ }
256
+ const word = data.slice(10, 74);
257
+ if (!/^0{24}[0-9a-fA-F]{40}$/.test(word)) {
258
+ fail("arc_home_plan_inconsistent", `The prepared ${name} call has a malformed address argument.`);
259
+ }
260
+ return { address: getAddress(`0x${word.slice(24)}`), amount: BigInt(`0x${data.slice(74, 138)}`) };
261
+ }
262
+ function decodeTwoAddresses(data, selector, name) {
263
+ if (data.length !== 2 + 8 + 64 + 64 || data.slice(0, 10).toLowerCase() !== selector.toLowerCase()) {
264
+ fail("arc_home_plan_inconsistent", `The prepared ${name} call is not the expected function.`);
265
+ }
266
+ const words = [data.slice(10, 74), data.slice(74, 138)];
267
+ for (const word of words) {
268
+ if (!/^0{24}[0-9a-fA-F]{40}$/.test(word)) {
269
+ fail("arc_home_plan_inconsistent", `The prepared ${name} call has a malformed address argument.`);
270
+ }
271
+ }
272
+ return { first: getAddress(`0x${words[0].slice(24)}`), second: getAddress(`0x${words[1].slice(24)}`) };
273
+ }
274
+ function decodeSingleAddress(data, selector, name) {
275
+ if (data.length !== 2 + 8 + 64 || data.slice(0, 10).toLowerCase() !== selector.toLowerCase()) {
276
+ fail("arc_home_plan_inconsistent", `The prepared ${name} call is not the expected function.`);
277
+ }
278
+ const word = data.slice(10, 74);
279
+ if (!/^0{24}[0-9a-fA-F]{40}$/.test(word)) {
280
+ fail("arc_home_plan_inconsistent", `The prepared ${name} call has a malformed address argument.`);
281
+ }
282
+ return getAddress(`0x${word.slice(24)}`);
283
+ }
284
+ /** Decode MultiSendCallOnly.multiSend(bytes) into its packed CALLs. */
285
+ export function decodeMultiSendCallOnly(data) {
286
+ if (data.slice(0, 10).toLowerCase() !== MULTISEND_SELECTOR.toLowerCase()) {
287
+ fail("arc_home_plan_inconsistent", "The prepared batch is not MultiSendCallOnly.multiSend.");
288
+ }
289
+ const body = data.slice(10);
290
+ if (body.length < 128)
291
+ fail("arc_home_plan_inconsistent", "The prepared batch payload is truncated.");
292
+ const offset = Number(BigInt(`0x${body.slice(0, 64)}`));
293
+ if (offset !== 32)
294
+ fail("arc_home_plan_inconsistent", "The prepared batch payload is not canonically encoded.");
295
+ const length = Number(BigInt(`0x${body.slice(64, 128)}`));
296
+ const packed = body.slice(128, 128 + length * 2);
297
+ if (packed.length !== length * 2)
298
+ fail("arc_home_plan_inconsistent", "The prepared batch payload is truncated.");
299
+ const calls = [];
300
+ let cursor = 0;
301
+ while (cursor < packed.length) {
302
+ if (packed.length - cursor < 2 + 40 + 64 + 64) {
303
+ fail("arc_home_plan_inconsistent", "The prepared batch contains a truncated call.");
304
+ }
305
+ const operation = Number.parseInt(packed.slice(cursor, cursor + 2), 16);
306
+ const to = getAddress(`0x${packed.slice(cursor + 2, cursor + 42)}`);
307
+ const value = BigInt(`0x${packed.slice(cursor + 42, cursor + 106)}`);
308
+ const dataLength = Number(BigInt(`0x${packed.slice(cursor + 106, cursor + 170)}`));
309
+ const callData = `0x${packed.slice(cursor + 170, cursor + 170 + dataLength * 2)}`;
310
+ if (callData.length !== 2 + dataLength * 2) {
311
+ fail("arc_home_plan_inconsistent", "The prepared batch contains a truncated call payload.");
312
+ }
313
+ // MultiSendCallOnly rejects DELEGATECALL on chain; refuse it locally too.
314
+ if (operation !== 0)
315
+ fail("arc_home_plan_inconsistent", "A batched Arc home call is not a plain CALL.");
316
+ if (value !== 0n)
317
+ fail("arc_home_plan_inconsistent", "A batched Arc home call moves native value.");
318
+ calls.push({ to, data: callData, operation });
319
+ cursor += 170 + dataLength * 2;
320
+ if (calls.length > 8)
321
+ fail("arc_home_plan_inconsistent", "The prepared batch has too many calls.");
322
+ }
323
+ if (!calls.length)
324
+ fail("arc_home_plan_inconsistent", "The prepared batch has no calls.");
325
+ return calls;
326
+ }
327
+ /** Domain, types, zero gas/refund fields and canonical shape. No intent yet. */
328
+ export function assertArcSafeTxShape(typedData, expected) {
329
+ const payload = record(typedData, "typed_data");
330
+ if (payload.primaryType !== "SafeTx") {
331
+ fail("arc_home_plan_inconsistent", "The Arc home typed data is not a SafeTx.");
332
+ }
333
+ const types = record(payload.types, "typed_data.types");
334
+ const names = Object.keys(types).sort();
335
+ if (names.length !== 2 || names[0] !== "EIP712Domain" || names[1] !== "SafeTx"
336
+ || JSON.stringify(types.SafeTx) !== JSON.stringify(SAFE_TX_FIELDS)
337
+ || JSON.stringify(types.EIP712Domain) !== JSON.stringify(SAFE_TX_DOMAIN_FIELDS)) {
338
+ fail("arc_home_plan_inconsistent", "The Arc home SafeTx types are not the canonical Safe 1.3.0 types.");
339
+ }
340
+ const domain = record(payload.domain, "typed_data.domain");
341
+ if (Object.keys(domain).length !== 2) {
342
+ fail("arc_home_plan_inconsistent", "The Arc home SafeTx domain carries unexpected fields.");
343
+ }
344
+ const chainId = integer(domain.chainId, "typed_data.domain.chainId");
345
+ if (chainId !== expected.chainId) {
346
+ fail("arc_home_wrong_chain", `The Arc home SafeTx is for chain ${chainId}, not the Arc home chain ${expected.chainId}.`);
347
+ }
348
+ if (!sameAddress(domain.verifyingContract, expected.safe)) {
349
+ fail("arc_home_wrong_safe", "The Arc home SafeTx is for a different Safe than this account's verified Arc home.");
350
+ }
351
+ const message = record(payload.message, "typed_data.message");
352
+ const allowed = new Set(SAFE_TX_FIELDS.map((field) => String(field.name)));
353
+ for (const key of Object.keys(message)) {
354
+ if (!allowed.has(key))
355
+ fail("arc_home_plan_inconsistent", "The Arc home SafeTx message carries unexpected fields.");
356
+ }
357
+ if (parseUnits(message.value, "SafeTx.value") !== 0n) {
358
+ fail("arc_home_plan_inconsistent", "The Arc home SafeTx moves native value.");
359
+ }
360
+ for (const field of ["safeTxGas", "baseGas", "gasPrice"]) {
361
+ if (parseUnits(message[field], `SafeTx.${field}`) !== 0n) {
362
+ fail("arc_home_refund_not_zero", `The Arc home SafeTx sets a non-zero ${field}, which would let the relayer charge the Safe.`);
363
+ }
364
+ }
365
+ for (const field of ["gasToken", "refundReceiver"]) {
366
+ if (!sameAddress(message[field], ZERO_ADDRESS)) {
367
+ fail("arc_home_refund_not_zero", `The Arc home SafeTx sets a non-zero ${field}, which would let the relayer charge the Safe.`);
368
+ }
369
+ }
370
+ const operation = integer(message.operation, "SafeTx.operation");
371
+ const to = address(message.to, "SafeTx.to");
372
+ if (operation !== 0 && operation !== 1) {
373
+ fail("arc_home_plan_inconsistent", "The Arc home SafeTx operation is neither CALL nor DELEGATECALL.");
374
+ }
375
+ if (operation === 1 && !sameAddress(to, SAFE_MULTISEND_CALL_ONLY)) {
376
+ fail("arc_home_delegatecall_forbidden", "The Arc home SafeTx delegatecalls a contract other than the pinned MultiSendCallOnly.");
377
+ }
378
+ return {
379
+ to,
380
+ data: hex(message.data, "SafeTx.data"),
381
+ operation,
382
+ nonce: integer(message.nonce, "SafeTx.nonce"),
383
+ chainId,
384
+ safe: getAddress(expected.safe),
385
+ };
386
+ }
387
+ /** Full EIP-712 digest, which is also the Safe transaction hash. */
388
+ export function arcSafeTxHash(typedData) {
389
+ const payload = record(typedData, "typed_data");
390
+ const domain = record(payload.domain, "typed_data.domain");
391
+ const message = record(payload.message, "typed_data.message");
392
+ return hashTypedData({
393
+ domain: {
394
+ chainId: integer(domain.chainId, "domain.chainId"),
395
+ verifyingContract: address(domain.verifyingContract, "domain.verifyingContract"),
396
+ },
397
+ types: { SafeTx: SAFE_TX_FIELDS },
398
+ primaryType: "SafeTx",
399
+ message: safeTxMessageForSigning(message),
400
+ });
401
+ }
402
+ /** The EIP-712 struct hash only (what the hub onboarding calls safetx_digest). */
403
+ export function arcSafeTxStructHash(typedData) {
404
+ const payload = record(typedData, "typed_data");
405
+ const message = record(payload.message, "typed_data.message");
406
+ return hashStruct({
407
+ data: safeTxMessageForSigning(message),
408
+ primaryType: "SafeTx",
409
+ types: { SafeTx: SAFE_TX_FIELDS },
410
+ });
411
+ }
412
+ function safeTxMessageForSigning(message) {
413
+ return {
414
+ to: address(message.to, "SafeTx.to"),
415
+ value: parseUnits(message.value, "SafeTx.value"),
416
+ data: hex(message.data, "SafeTx.data"),
417
+ operation: integer(message.operation, "SafeTx.operation"),
418
+ safeTxGas: parseUnits(message.safeTxGas, "SafeTx.safeTxGas"),
419
+ baseGas: parseUnits(message.baseGas, "SafeTx.baseGas"),
420
+ gasPrice: parseUnits(message.gasPrice, "SafeTx.gasPrice"),
421
+ gasToken: address(message.gasToken, "SafeTx.gasToken"),
422
+ refundReceiver: address(message.refundReceiver, "SafeTx.refundReceiver"),
423
+ nonce: parseUnits(message.nonce, "SafeTx.nonce"),
424
+ };
425
+ }
426
+ /**
427
+ * Decide whether one prepared Arc-home SafeTx does exactly what the owner
428
+ * asked for. `step` comes from the engine record and is never trusted on its
429
+ * own: the calldata itself must decode to the claimed intent.
430
+ */
431
+ export function assertArcHomeSafeTx(entry, intent) {
432
+ const shape = assertArcSafeTxShape(entry.typed_data, { safe: intent.safe, chainId: intent.chainId });
433
+ const claimed = text(entry.safe_tx_hash, "safe_tx_hash");
434
+ if (!BYTES32_RE.test(claimed) || claimed.toLowerCase() !== arcSafeTxHash(entry.typed_data).toLowerCase()) {
435
+ fail("arc_home_digest_mismatch", "The Arc home safe_tx_hash does not match the typed data it was sent with.");
436
+ }
437
+ const steps = text(entry.step, "safe_transactions[].step").split("+");
438
+ const allowedPlans = new Set([
439
+ "transfer",
440
+ "add_delegate",
441
+ "approve+gateway_deposit",
442
+ "add_delegate+approve+gateway_deposit",
443
+ "gateway_mint",
444
+ ]);
445
+ if (!allowedPlans.has(entry.step)) {
446
+ const knownSteps = new Set(["transfer", "add_delegate", "approve", "gateway_deposit", "gateway_mint"]);
447
+ if (steps.some((step) => !knownSteps.has(step))) {
448
+ fail("arc_home_unknown_step", "The Arc home plan contains an unsupported step.");
449
+ }
450
+ fail("arc_home_plan_inconsistent", "The Arc home SafeTx has an unsupported step sequence.");
451
+ }
452
+ const calls = shape.operation === 1
453
+ ? decodeMultiSendCallOnly(shape.data)
454
+ : [{ to: shape.to, data: shape.data, operation: 0 }];
455
+ if (calls.length !== steps.length) {
456
+ fail("arc_home_plan_inconsistent", "The Arc home SafeTx does not contain the steps it claims.");
457
+ }
458
+ const exposure = intent.amountUnits + intent.maxFeeUnits;
459
+ for (let index = 0; index < calls.length; index += 1) {
460
+ const call = calls[index];
461
+ const step = steps[index];
462
+ if (step === "transfer") {
463
+ if (!sameAddress(call.to, intent.usdc)) {
464
+ fail("arc_home_plan_inconsistent", "The Arc home transfer does not target the Arc USDC contract.");
465
+ }
466
+ const decoded = decodeAddressAmount(call.data, TRANSFER_SELECTOR, "transfer");
467
+ if (!sameAddress(decoded.address, intent.destination)) {
468
+ fail("arc_home_wrong_recipient", "The Arc home transfer pays an address other than the requested destination.");
469
+ }
470
+ if (decoded.amount !== intent.amountUnits) {
471
+ fail("arc_home_wrong_amount", "The Arc home transfer amount differs from the requested amount.");
472
+ }
473
+ }
474
+ else if (step === "add_delegate") {
475
+ if (!sameAddress(call.to, intent.gatewayWallet)) {
476
+ fail("arc_home_plan_inconsistent", "The Arc home delegate call does not target the Gateway wallet.");
477
+ }
478
+ const decoded = decodeTwoAddresses(call.data, ADD_DELEGATE_SELECTOR, "addDelegate");
479
+ if (!sameAddress(decoded.first, intent.usdc) || !sameAddress(decoded.second, intent.owner)) {
480
+ fail("arc_home_delegate_not_owner", "The Arc home Gateway delegate is not the owner EOA for Arc USDC.");
481
+ }
482
+ }
483
+ else if (step === "approve") {
484
+ if (!sameAddress(call.to, intent.usdc)) {
485
+ fail("arc_home_plan_inconsistent", "The Arc home approval does not target the Arc USDC contract.");
486
+ }
487
+ const decoded = decodeAddressAmount(call.data, APPROVE_SELECTOR, "approve");
488
+ if (!sameAddress(decoded.address, intent.gatewayWallet)) {
489
+ fail("arc_home_plan_inconsistent", "The Arc home approval spender is not the Circle Gateway wallet.");
490
+ }
491
+ if (decoded.amount === 0n || decoded.amount > exposure) {
492
+ fail("arc_home_wrong_amount", "The Arc home approval exceeds the requested amount plus fee ceiling.");
493
+ }
494
+ }
495
+ else if (step === "gateway_deposit") {
496
+ if (!sameAddress(call.to, intent.gatewayWallet)) {
497
+ fail("arc_home_plan_inconsistent", "The Arc home Gateway deposit does not target the Gateway wallet.");
498
+ }
499
+ const decoded = decodeAddressAmount(call.data, DEPOSIT_SELECTOR, "deposit");
500
+ if (!sameAddress(decoded.address, intent.usdc)) {
501
+ fail("arc_home_plan_inconsistent", "The Arc home Gateway deposit is not denominated in Arc USDC.");
502
+ }
503
+ if (decoded.amount === 0n || decoded.amount > exposure) {
504
+ fail("arc_home_wrong_amount", "The Arc home Gateway deposit exceeds the requested amount plus fee ceiling.");
505
+ }
506
+ }
507
+ else if (step === "gateway_mint") {
508
+ if (!sameAddress(call.to, intent.gatewayMinter)) {
509
+ fail("arc_home_plan_inconsistent", "The Arc home mint does not target the pinned Circle Gateway minter.");
510
+ }
511
+ if (call.data.slice(0, 10).toLowerCase() !== GATEWAY_MINT_SELECTOR.toLowerCase()) {
512
+ fail("arc_home_plan_inconsistent", "The Arc home mint call is not gatewayMint(bytes,bytes).");
513
+ }
514
+ }
515
+ else {
516
+ fail("arc_home_unknown_step", `The Arc home plan contains an unsupported step "${step}".`);
517
+ }
518
+ }
519
+ // approve and deposit must be for the same amount, and never an approval
520
+ // without its deposit in the same atomic batch.
521
+ const approveIndex = steps.indexOf("approve");
522
+ const depositIndex = steps.indexOf("gateway_deposit");
523
+ if ((approveIndex === -1) !== (depositIndex === -1)) {
524
+ fail("arc_home_plan_inconsistent", "An Arc home Gateway approval and its deposit must be in the same SafeTx.");
525
+ }
526
+ if (approveIndex !== -1 && depositIndex !== -1) {
527
+ const approved = decodeAddressAmount(calls[approveIndex].data, APPROVE_SELECTOR, "approve").amount;
528
+ const deposited = decodeAddressAmount(calls[depositIndex].data, DEPOSIT_SELECTOR, "deposit").amount;
529
+ if (approved !== deposited) {
530
+ fail("arc_home_wrong_amount", "The Arc home Gateway approval and deposit amounts differ.");
531
+ }
532
+ }
533
+ return shape;
534
+ }
535
+ export function assertArcHomeWithdrawalSafeTransactions(kind, entries) {
536
+ if (kind === "arc_same_chain") {
537
+ if (entries.length !== 1 || entries[0].step !== "transfer") {
538
+ fail("arc_home_plan_invalid", "A same-chain Arc home withdrawal must contain one transfer SafeTx.");
539
+ }
540
+ return;
541
+ }
542
+ if (kind !== "arc_cross_chain") {
543
+ fail("arc_home_plan_invalid", "An Arc home deposit is not a withdrawal.");
544
+ }
545
+ const preparationSteps = new Set([
546
+ "add_delegate",
547
+ "approve+gateway_deposit",
548
+ "add_delegate+approve+gateway_deposit",
549
+ ]);
550
+ if (entries.length > 1 || (entries.length === 1 && !preparationSteps.has(entries[0].step))) {
551
+ fail("arc_home_plan_invalid", "A cross-chain Arc home withdrawal has an invalid SafeTx plan.");
552
+ }
553
+ }
554
+ export function assertArcHomeBurnIntent(typedData, expected) {
555
+ const payload = record(typedData, "burn_intent_typed_data");
556
+ const domain = record(payload.domain, "burn_intent.domain");
557
+ if (payload.primaryType !== "BurnIntent" || domain.name !== "GatewayWallet" || domain.version !== "1"
558
+ || Object.keys(domain).length !== 2) {
559
+ fail("arc_home_plan_inconsistent", "The Arc home burn intent is not a Circle GatewayWallet intent.");
560
+ }
561
+ const message = record(payload.message, "burn_intent.message");
562
+ const spec = record(message.spec, "burn_intent.spec");
563
+ if (parseUnits(spec.value, "burn_intent.spec.value") !== expected.amountUnits) {
564
+ fail("arc_home_wrong_amount", "The Arc home burn intent amount differs from the requested amount.");
565
+ }
566
+ if (parseUnits(message.maxFee, "burn_intent.maxFee") > expected.maxFeeUnits) {
567
+ fail("arc_home_fee_above_ceiling", "The Arc home burn intent fee ceiling exceeds the approved maximum fee.");
568
+ }
569
+ if (integer(spec.sourceDomain, "burn_intent.spec.sourceDomain") !== expected.sourceDomain
570
+ || integer(spec.destinationDomain, "burn_intent.spec.destinationDomain") !== expected.destinationDomain) {
571
+ fail("arc_home_plan_inconsistent", "The Arc home burn intent route differs from the requested route.");
572
+ }
573
+ if (text(spec.hookData, "burn_intent.spec.hookData") !== "0x") {
574
+ fail("arc_home_plan_inconsistent", "The Arc home burn intent carries hook data, which Felix never uses.");
575
+ }
576
+ const bindings = [
577
+ ["sourceToken", expected.sourceToken],
578
+ ["destinationToken", expected.destinationToken],
579
+ ["sourceDepositor", expected.sourceDepositor],
580
+ ["destinationRecipient", expected.destinationRecipient],
581
+ ["sourceSigner", expected.sourceSigner],
582
+ ];
583
+ for (const [field, wanted] of bindings) {
584
+ const word = text(spec[field], `burn_intent.spec.${field}`);
585
+ if (!BYTES32_RE.test(word) || word.toLowerCase() !== addressAsBytes32(wanted)) {
586
+ const code = field === "destinationRecipient" ? "arc_home_wrong_recipient" : "arc_home_plan_inconsistent";
587
+ fail(code, `The Arc home burn intent ${field} is not ${wanted}.`);
588
+ }
589
+ }
590
+ const caller = text(spec.destinationCaller, "burn_intent.spec.destinationCaller");
591
+ if (!BYTES32_RE.test(caller) || BigInt(caller) !== 0n) {
592
+ fail("arc_home_plan_inconsistent", "The Arc home burn intent restricts the destination caller.");
593
+ }
594
+ const salt = text(spec.salt, "burn_intent.spec.salt");
595
+ if (!BYTES32_RE.test(salt) || BigInt(salt) === 0n) {
596
+ fail("arc_home_plan_invalid", "The Arc home burn intent salt is invalid.");
597
+ }
598
+ parseUnits(message.maxBlockHeight, "burn_intent.maxBlockHeight");
599
+ }
600
+ const ARC_PROOF_FIELDS = [
601
+ "domain", "account_id", "chain_id", "safe", "owner", "home", "agent", "agent_authority",
602
+ "module_version", "module_runtime_hash", "collateral", "exchanges", "max_operation_units",
603
+ "daily_limit_units", "lifetime_limit_units", "delegation_expires_at", "nonce", "challenge_expires_at",
604
+ ];
605
+ /**
606
+ * Verify the onboarding challenge before the owner proof is signed: the proof
607
+ * must describe the owner's own Safe (CREATE2-predicted locally), a home equal
608
+ * to the owner, the exact limits requested, an agent that is not the owner,
609
+ * and a short expiry.
610
+ */
611
+ export function assertArcHubChallenge(init, expected, now = Math.floor(Date.now() / 1000)) {
612
+ const payload = record(init, "onboarding/init response");
613
+ if (payload.proof_scheme !== "personal_sign") {
614
+ fail("arc_home_proof_scheme_unsupported", "Felix asked for an Arc home proof scheme this client does not implement.");
615
+ }
616
+ const chainId = integer(payload.chain_id, "chain_id");
617
+ const wantedChain = expected.chainId ?? ARC_MAINNET_CHAIN_ID;
618
+ if (chainId !== wantedChain) {
619
+ fail("arc_home_wrong_chain", `Arc home onboarding returned chain ${chainId}, not ${wantedChain}.`);
620
+ }
621
+ const safe = address(payload.safe, "safe");
622
+ const module = address(payload.module, "module");
623
+ const agent = address(payload.agent, "agent");
624
+ const home = address(payload.home, "home");
625
+ const message = text(payload.proof_message, "proof_message");
626
+ const challengeToken = text(payload.challenge_token, "challenge_token");
627
+ const expiresAt = integer(payload.expires_at, "expires_at");
628
+ const lines = message.split("\n");
629
+ if (lines[0] !== ARC_HOME_PROOF_VERSION) {
630
+ fail("arc_home_proof_invalid", "Felix returned the wrong Arc home proof version line.");
631
+ }
632
+ const fields = {};
633
+ for (const line of lines.slice(1)) {
634
+ const split = line.indexOf(":");
635
+ if (split <= 0)
636
+ fail("arc_home_proof_invalid", "Felix returned a malformed Arc home proof line.");
637
+ const key = line.slice(0, split);
638
+ const value = line.slice(split + 1);
639
+ if (!value || fields[key] !== undefined) {
640
+ fail("arc_home_proof_invalid", "Felix returned duplicate or empty Arc home proof fields.");
641
+ }
642
+ fields[key] = value;
643
+ }
644
+ if (JSON.stringify(Object.keys(fields).sort()) !== JSON.stringify([...ARC_PROOF_FIELDS].sort())) {
645
+ fail("arc_home_proof_invalid", "The Arc home proof does not carry exactly the expected fields.");
646
+ }
647
+ if (!sameAddress(expected.owner, fields.owner)) {
648
+ fail("arc_home_proof_owner_mismatch", "The Arc home proof names an owner other than this client's local owner key.");
649
+ }
650
+ if (!sameAddress(fields.owner, payload.owner ?? fields.owner) && payload.owner !== undefined) {
651
+ fail("arc_home_proof_invalid", "The Arc home proof owner differs from the response owner.");
652
+ }
653
+ if (!sameAddress(fields.home, fields.owner) || !sameAddress(home, fields.owner)) {
654
+ fail("arc_home_sweep_home_not_owner", "The Arc home agent sweep home is not the owner address.");
655
+ }
656
+ if (!sameAddress(fields.safe, safe)) {
657
+ fail("arc_home_proof_invalid", "The Arc home proof Safe differs from the response Safe.");
658
+ }
659
+ if (!sameAddress(fields.agent, agent)) {
660
+ fail("arc_home_proof_invalid", "The Arc home proof agent differs from the response agent.");
661
+ }
662
+ if (sameAddress(fields.agent, fields.owner)) {
663
+ fail("arc_home_proof_invalid", "The Arc home proof makes the owner its own agent.");
664
+ }
665
+ if (Number(fields.chain_id) !== chainId) {
666
+ fail("arc_home_wrong_chain", "The Arc home proof chain id differs from the response chain id.");
667
+ }
668
+ if (fields.agent_authority !== ARC_HUB_AGENT_AUTHORITY) {
669
+ fail("arc_home_proof_authority_unexpected", `The Arc home proof grants "${fields.agent_authority}" instead of ${ARC_HUB_AGENT_AUTHORITY}.`);
670
+ }
671
+ if (Number(fields.module_version) !== ARC_HUB_MODULE_VERSION) {
672
+ fail("arc_home_proof_module_version", "The Arc home proof is for a different hub module version.");
673
+ }
674
+ if (fields.exchanges !== "none") {
675
+ fail("arc_home_proof_exchanges_not_empty", "The Arc home proof authorizes exchanges; Arc must have none.");
676
+ }
677
+ if (!sameAddress(fields.collateral, ARC_USDC)) {
678
+ fail("arc_home_proof_collateral_unexpected", "The Arc home proof binds a collateral token other than Arc USDC.");
679
+ }
680
+ if (!BYTES32_RE.test(`0x${fields.module_runtime_hash.replace(/^0x/, "")}`)) {
681
+ fail("arc_home_proof_invalid", "The Arc home proof module runtime hash is malformed.");
682
+ }
683
+ const limits = [
684
+ ["max_operation_units", expected.maxOperationUnits],
685
+ ["daily_limit_units", expected.dailyLimitUnits],
686
+ ["lifetime_limit_units", expected.lifetimeLimitUnits],
687
+ ];
688
+ for (const [field, wanted] of limits) {
689
+ if (!UNITS_RE.test(fields[field]) || BigInt(fields[field]) !== wanted) {
690
+ fail("arc_home_proof_limits_mismatch", `The Arc home proof ${field} is not the limit this client requested.`);
691
+ }
692
+ }
693
+ const delegationExpires = Number(fields.delegation_expires_at);
694
+ const wantedExpiry = now + expected.delegationDays * 86_400;
695
+ if (!Number.isSafeInteger(delegationExpires) || Math.abs(delegationExpires - wantedExpiry) > 900) {
696
+ fail("arc_home_proof_delegation_mismatch", "The Arc home proof delegation window is not the window this client requested.");
697
+ }
698
+ if (delegationExpires <= now || delegationExpires > now + ARC_HOME_DELEGATION_MAX_DAYS * 86_400) {
699
+ fail("arc_home_proof_delegation_mismatch", "The Arc home proof delegation window is out of bounds.");
700
+ }
701
+ const challengeExpires = Number(fields.challenge_expires_at);
702
+ if (!Number.isSafeInteger(challengeExpires) || challengeExpires !== expiresAt
703
+ || challengeExpires <= now || challengeExpires > now + ARC_HOME_CHALLENGE_MAX_TTL_SECONDS) {
704
+ fail("arc_home_challenge_window_invalid", "The Arc home challenge expiry is missing, stale, or too far in the future.");
705
+ }
706
+ if (expected.accountId && fields.account_id !== expected.accountId) {
707
+ fail("arc_home_proof_account_mismatch", "The Arc home proof is bound to a different Felix account.");
708
+ }
709
+ const predicted = predictArcHomeSafe(expected.owner);
710
+ if (!sameAddress(predicted, safe)) {
711
+ fail("arc_home_safe_prediction_mismatch", "The Arc home Safe is not the CREATE2 Safe this owner key controls.");
712
+ }
713
+ return {
714
+ safe, module, agent, home, owner: getAddress(expected.owner),
715
+ chainId, message, challengeToken, expiresAt, fields,
716
+ };
717
+ }
718
+ /**
719
+ * Verify the activation SafeTx before signing it. For `activate_module` the
720
+ * module address is re-derived from the CreateCall payload itself, so a
721
+ * substituted module cannot hide behind a matching field.
722
+ */
723
+ export function assertArcHubActivation(deploy, expected) {
724
+ const payload = record(deploy, "onboarding/deploy response");
725
+ if (payload.status !== "awaiting_owner_signature") {
726
+ fail("arc_home_activation_unexpected", "Felix did not return an Arc home activation awaiting the owner signature.");
727
+ }
728
+ if (payload.signature_scheme !== "eth_signTypedData_v4") {
729
+ fail("arc_home_proof_scheme_unsupported", "Felix asked for an activation signature scheme this client does not implement.");
730
+ }
731
+ const route = text(payload.route, "route");
732
+ if (route !== "activate_module" && route !== "enable_module") {
733
+ fail("arc_home_activation_unexpected", `Felix returned an unsupported Arc home activation route "${route}".`);
734
+ }
735
+ const safe = address(payload.safe, "safe");
736
+ const module = address(payload.module, "module");
737
+ if (!sameAddress(safe, expected.safe)) {
738
+ fail("arc_home_wrong_safe", "The Arc home activation targets a different Safe than the verified challenge.");
739
+ }
740
+ if (!sameAddress(module, expected.module)) {
741
+ fail("arc_home_activation_module_mismatch", "The Arc home activation module differs from the module in the signed challenge.");
742
+ }
743
+ const typedData = record(payload.typed_data, "typed_data");
744
+ const shape = assertArcSafeTxShape(typedData, { safe, chainId: expected.chainId });
745
+ const claimedDigest = text(payload.safetx_digest, "safetx_digest");
746
+ if (!BYTES32_RE.test(claimedDigest)) {
747
+ fail("arc_home_plan_invalid", "The Arc home activation digest is malformed.");
748
+ }
749
+ const structHash = arcSafeTxStructHash(typedData).toLowerCase();
750
+ const fullDigest = arcSafeTxHash(typedData).toLowerCase();
751
+ if (![structHash, fullDigest].includes(claimedDigest.toLowerCase())) {
752
+ fail("arc_home_digest_mismatch", "The Arc home activation digest does not match its typed data.");
753
+ }
754
+ if (route === "enable_module") {
755
+ if (shape.operation !== 0 || !sameAddress(shape.to, safe)) {
756
+ fail("arc_home_plan_inconsistent", "The Arc home enable-module SafeTx does not call the Safe itself.");
757
+ }
758
+ const enabled = decodeSingleAddress(shape.data, ENABLE_MODULE_SELECTOR, "enableModule");
759
+ if (!sameAddress(enabled, module)) {
760
+ fail("arc_home_activation_module_mismatch", "The Arc home enable-module SafeTx enables a different module.");
761
+ }
762
+ }
763
+ else {
764
+ if (shape.operation !== 1 || !sameAddress(shape.to, SAFE_MULTISEND_CALL_ONLY)) {
765
+ fail("arc_home_plan_inconsistent", "The Arc home activation SafeTx is not a MultiSendCallOnly batch.");
766
+ }
767
+ const calls = decodeMultiSendCallOnly(shape.data);
768
+ if (calls.length !== 2) {
769
+ fail("arc_home_plan_inconsistent", "The Arc home activation batch does not contain exactly create and enable.");
770
+ }
771
+ if (!sameAddress(calls[0].to, SAFE_CREATE_CALL)) {
772
+ fail("arc_home_plan_inconsistent", "The Arc home activation does not create the module through the canonical CreateCall.");
773
+ }
774
+ const created = decodePerformCreate2(calls[0].data);
775
+ if (created.value !== 0n) {
776
+ fail("arc_home_plan_inconsistent", "The Arc home module creation sends native value.");
777
+ }
778
+ if (created.salt.toLowerCase() !== arcHomeModuleSalt(safe).toLowerCase()) {
779
+ fail("arc_home_plan_inconsistent", "The Arc home module creation uses a salt that is not derived from this Safe.");
780
+ }
781
+ const predictedModule = predictArcHomeModule(created.initCode, created.salt);
782
+ if (!sameAddress(predictedModule, module)) {
783
+ fail("arc_home_activation_module_mismatch", "The Arc home activation would create a module at a different address than it claims.");
784
+ }
785
+ if (!sameAddress(calls[1].to, safe)) {
786
+ fail("arc_home_plan_inconsistent", "The Arc home activation second call does not target the Safe.");
787
+ }
788
+ const enabled = decodeSingleAddress(calls[1].data, ENABLE_MODULE_SELECTOR, "enableModule");
789
+ if (!sameAddress(enabled, module)) {
790
+ fail("arc_home_activation_module_mismatch", "The Arc home activation enables a module other than the one it creates.");
791
+ }
792
+ }
793
+ return {
794
+ route,
795
+ safe,
796
+ module,
797
+ typedData,
798
+ activationToken: text(payload.activation_token, "activation_token"),
799
+ digest: fullDigest,
800
+ };
801
+ }
802
+ function decodePerformCreate2(data) {
803
+ if (data.slice(0, 10).toLowerCase() !== PERFORM_CREATE2_SELECTOR.toLowerCase()) {
804
+ fail("arc_home_plan_inconsistent", "The Arc home module creation is not CreateCall.performCreate2.");
805
+ }
806
+ const body = data.slice(10);
807
+ if (body.length < 192)
808
+ fail("arc_home_plan_inconsistent", "The Arc home module creation payload is truncated.");
809
+ const value = BigInt(`0x${body.slice(0, 64)}`);
810
+ const offset = Number(BigInt(`0x${body.slice(64, 128)}`));
811
+ const salt = `0x${body.slice(128, 192)}`;
812
+ if (offset !== 96)
813
+ fail("arc_home_plan_inconsistent", "The Arc home module creation payload is not canonically encoded.");
814
+ const lengthStart = offset * 2;
815
+ if (body.length < lengthStart + 64)
816
+ fail("arc_home_plan_inconsistent", "The Arc home module creation payload is truncated.");
817
+ const length = Number(BigInt(`0x${body.slice(lengthStart, lengthStart + 64)}`));
818
+ const initCode = `0x${body.slice(lengthStart + 64, lengthStart + 64 + length * 2)}`;
819
+ if (initCode.length !== 2 + length * 2 || length === 0) {
820
+ fail("arc_home_plan_inconsistent", "The Arc home module init code is truncated.");
821
+ }
822
+ return { value, initCode, salt };
823
+ }
824
+ // --------------------------------------------------------------------------- signing
825
+ export async function signArcHomeSafeTx(typedData, privateKey) {
826
+ const account = privateKeyToAccount(ownerKeyOrThrow(privateKey));
827
+ const payload = record(typedData, "typed_data");
828
+ const domain = record(payload.domain, "typed_data.domain");
829
+ return account.signTypedData({
830
+ domain: {
831
+ chainId: integer(domain.chainId, "domain.chainId"),
832
+ verifyingContract: address(domain.verifyingContract, "domain.verifyingContract"),
833
+ },
834
+ types: { SafeTx: SAFE_TX_FIELDS },
835
+ primaryType: "SafeTx",
836
+ message: safeTxMessageForSigning(record(payload.message, "typed_data.message")),
837
+ });
838
+ }
839
+ export async function signArcHomeBurnIntent(typedData, privateKey) {
840
+ const account = privateKeyToAccount(ownerKeyOrThrow(privateKey));
841
+ const payload = record(typedData, "burn_intent_typed_data");
842
+ const message = record(payload.message, "burn_intent.message");
843
+ const spec = record(message.spec, "burn_intent.spec");
844
+ const coerced = {
845
+ maxBlockHeight: parseUnits(message.maxBlockHeight, "burn_intent.maxBlockHeight"),
846
+ maxFee: parseUnits(message.maxFee, "burn_intent.maxFee"),
847
+ spec: {
848
+ version: integer(spec.version, "burn_intent.spec.version"),
849
+ sourceDomain: integer(spec.sourceDomain, "burn_intent.spec.sourceDomain"),
850
+ destinationDomain: integer(spec.destinationDomain, "burn_intent.spec.destinationDomain"),
851
+ sourceContract: text(spec.sourceContract, "burn_intent.spec.sourceContract"),
852
+ destinationContract: text(spec.destinationContract, "burn_intent.spec.destinationContract"),
853
+ sourceToken: text(spec.sourceToken, "burn_intent.spec.sourceToken"),
854
+ destinationToken: text(spec.destinationToken, "burn_intent.spec.destinationToken"),
855
+ sourceDepositor: text(spec.sourceDepositor, "burn_intent.spec.sourceDepositor"),
856
+ destinationRecipient: text(spec.destinationRecipient, "burn_intent.spec.destinationRecipient"),
857
+ sourceSigner: text(spec.sourceSigner, "burn_intent.spec.sourceSigner"),
858
+ destinationCaller: text(spec.destinationCaller, "burn_intent.spec.destinationCaller"),
859
+ value: parseUnits(spec.value, "burn_intent.spec.value"),
860
+ salt: text(spec.salt, "burn_intent.spec.salt"),
861
+ hookData: hex(spec.hookData, "burn_intent.spec.hookData"),
862
+ },
863
+ };
864
+ return account.signTypedData({
865
+ domain: { name: "GatewayWallet", version: "1" },
866
+ types: BURN_INTENT_TYPES,
867
+ primaryType: "BurnIntent",
868
+ message: coerced,
869
+ });
870
+ }
871
+ export async function signArcHomeOwnerProof(message, privateKey) {
872
+ const account = privateKeyToAccount(ownerKeyOrThrow(privateKey));
873
+ if (!message.startsWith(`${ARC_HOME_PROOF_VERSION}\n`)) {
874
+ fail("arc_home_proof_invalid", "Refusing to personal-sign a message that is not an Arc home hub proof.");
875
+ }
876
+ return account.signMessage({ message });
877
+ }
878
+ export function parseArcHomeRecord(payload) {
879
+ const body = record(payload, "arc home operation");
880
+ const operationId = text(body.operation_id, "operation_id");
881
+ if (!UUID_RE.test(operationId))
882
+ fail("arc_home_plan_invalid", "The Arc home operation id is not a UUID.");
883
+ const kind = text(body.kind, "kind");
884
+ if (!["arc_same_chain", "arc_cross_chain", "arc_deposit_in"].includes(kind)) {
885
+ fail("arc_home_plan_invalid", `The Arc home operation kind "${kind}" is unsupported.`);
886
+ }
887
+ const safeTransactions = Array.isArray(body.safe_transactions) ? body.safe_transactions : [];
888
+ const mintSafeTx = body.mint_safe_transaction ?? null;
889
+ const sourceCalls = Array.isArray(body.source_calls) ? body.source_calls : null;
890
+ const mintCall = body.mint_call ?? null;
891
+ return {
892
+ operation_id: operationId,
893
+ kind: kind,
894
+ phase: text(body.phase, "phase"),
895
+ revision: integer(body.revision ?? 0, "revision"),
896
+ terminal: body.terminal === true,
897
+ destination_chain: text(body.destination_chain, "destination_chain"),
898
+ destination: address(body.destination, "destination"),
899
+ amount_units: parseUnits(body.amount_units, "amount_units"),
900
+ max_fee_units: parseUnits(body.max_fee_units ?? "0", "max_fee_units"),
901
+ mint_gas_payer: typeof body.mint_gas_payer === "string" ? body.mint_gas_payer : null,
902
+ expires_at: body.expires_at === null || body.expires_at === undefined
903
+ ? null
904
+ : integer(body.expires_at, "expires_at"),
905
+ safe_transactions: safeTransactions.map((entry, index) => {
906
+ const item = record(entry, `safe_transactions[${index}]`);
907
+ return {
908
+ step: text(item.step, `safe_transactions[${index}].step`),
909
+ nonce: integer(item.nonce ?? 0, `safe_transactions[${index}].nonce`),
910
+ safe_tx_hash: text(item.safe_tx_hash, `safe_transactions[${index}].safe_tx_hash`),
911
+ typed_data: record(item.typed_data, `safe_transactions[${index}].typed_data`),
912
+ tx_hash: typeof item.tx_hash === "string" ? item.tx_hash : null,
913
+ };
914
+ }),
915
+ burn_intent_typed_data: body.burn_intent_typed_data
916
+ ? record(body.burn_intent_typed_data, "burn_intent_typed_data")
917
+ : null,
918
+ source_calls: sourceCalls
919
+ ? sourceCalls.map((entry, index) => {
920
+ const item = record(entry, `source_calls[${index}]`);
921
+ return {
922
+ chain_id: integer(item.chain_id, `source_calls[${index}].chain_id`),
923
+ from: address(item.from, `source_calls[${index}].from`),
924
+ to: address(item.to, `source_calls[${index}].to`),
925
+ data: hex(item.data, `source_calls[${index}].data`),
926
+ };
927
+ })
928
+ : null,
929
+ attestation: typeof body.attestation === "string" ? body.attestation : null,
930
+ mint_call: mintCall
931
+ ? (() => {
932
+ const item = record(mintCall, "mint_call");
933
+ return {
934
+ chain_id: integer(item.chain_id, "mint_call.chain_id"),
935
+ to: address(item.to, "mint_call.to"),
936
+ data: hex(item.data, "mint_call.data"),
937
+ };
938
+ })()
939
+ : null,
940
+ mint_safe_transaction: mintSafeTx
941
+ ? (() => {
942
+ const item = record(mintSafeTx, "mint_safe_transaction");
943
+ return {
944
+ step: typeof item.step === "string" ? item.step : "gateway_mint",
945
+ nonce: integer(record(record(item.typed_data, "mint typed_data").message, "mint message").nonce, "mint nonce"),
946
+ safe_tx_hash: text(item.safe_tx_hash, "mint_safe_transaction.safe_tx_hash"),
947
+ typed_data: record(item.typed_data, "mint_safe_transaction.typed_data"),
948
+ tx_hash: typeof item.tx_hash === "string" ? item.tx_hash : null,
949
+ };
950
+ })()
951
+ : null,
952
+ mint_tx_hash: typeof body.mint_tx_hash === "string" ? body.mint_tx_hash : null,
953
+ next_action: typeof body.next_action === "string" ? body.next_action : "none",
954
+ ...(typeof body.purpose === "string" ? { purpose: body.purpose } : {}),
955
+ ...(typeof body.venue === "string" ? { venue: body.venue } : {}),
956
+ raw: body,
957
+ };
958
+ }
959
+ /** Customer-safe projection: never echoes typed data or signatures. */
960
+ export function publicArcHomeRecord(parsed) {
961
+ return {
962
+ operation_id: parsed.operation_id,
963
+ kind: parsed.kind,
964
+ phase: parsed.phase,
965
+ terminal: parsed.terminal,
966
+ destination_chain: parsed.destination_chain,
967
+ destination: parsed.destination,
968
+ amount_usd: unitsToUsd(parsed.amount_units),
969
+ max_fee_usd: unitsToUsd(parsed.max_fee_units),
970
+ fee_payer: parsed.max_fee_units > 0n ? "owner" : null,
971
+ mint_gas_payer: parsed.mint_gas_payer,
972
+ arc_gas_payer: "felix_arc_sponsor",
973
+ safe_transactions: parsed.safe_transactions.map((entry) => ({
974
+ step: entry.step, nonce: entry.nonce, safe_tx_hash: entry.safe_tx_hash, tx_hash: entry.tx_hash,
975
+ })),
976
+ mint_call: parsed.mint_call,
977
+ mint_tx_hash: parsed.mint_tx_hash,
978
+ next_action: parsed.next_action,
979
+ ...(parsed.purpose ? { purpose: parsed.purpose } : {}),
980
+ ...(parsed.venue ? { venue: parsed.venue } : {}),
981
+ };
982
+ }
983
+ // --------------------------------------------------------------------------- source-chain broadcasting
984
+ export function arcHomeChainRpcUrl(chain) {
985
+ const name = chain.toUpperCase();
986
+ const candidates = [
987
+ process.env[`FELIX_${name}_RPC_URL`],
988
+ name === "POLYGON" ? process.env.FELIX_POLYGON_RPC_URL : undefined,
989
+ ];
990
+ for (const candidate of candidates) {
991
+ if (typeof candidate === "string" && /^https?:\/\//.test(candidate))
992
+ return candidate;
993
+ }
994
+ return undefined;
995
+ }
996
+ function ownerChain(chainId) {
997
+ return defineChain({
998
+ id: chainId,
999
+ name: `arc-home-source-${chainId}`,
1000
+ nativeCurrency: { name: "Native", symbol: "NATIVE", decimals: 18 },
1001
+ rpcUrls: { default: { http: [] } },
1002
+ });
1003
+ }
1004
+ export function assertArcHomeSourceCalls(calls, expected) {
1005
+ if (calls.length !== 2) {
1006
+ fail("arc_home_plan_inconsistent", "An Arc home deposit needs exactly an approval and a Gateway deposit.");
1007
+ }
1008
+ for (const call of calls) {
1009
+ if (call.chain_id !== expected.sourceChainId) {
1010
+ fail("arc_home_plan_inconsistent", "An Arc home deposit source call is not on the requested source chain.");
1011
+ }
1012
+ if (!sameAddress(call.from, expected.owner)) {
1013
+ fail("arc_home_plan_inconsistent", "An Arc home deposit source call is not sent from the owner EOA.");
1014
+ }
1015
+ }
1016
+ if (!sameAddress(calls[0].to, expected.usdc)) {
1017
+ fail("arc_home_plan_inconsistent", "The Arc home deposit approval does not target the source-chain USDC contract.");
1018
+ }
1019
+ const approve = decodeAddressAmount(calls[0].data, APPROVE_SELECTOR, "approve");
1020
+ if (!sameAddress(approve.address, expected.gatewayWallet) || approve.amount !== expected.exposureUnits) {
1021
+ fail("arc_home_wrong_amount", "The Arc home deposit approval is not exactly amount plus fee to the Gateway wallet.");
1022
+ }
1023
+ if (!sameAddress(calls[1].to, expected.gatewayWallet)) {
1024
+ fail("arc_home_plan_inconsistent", "The Arc home deposit call does not target the Gateway wallet.");
1025
+ }
1026
+ const deposit = decodeAddressAmount(calls[1].data, DEPOSIT_SELECTOR, "deposit");
1027
+ if (!sameAddress(deposit.address, expected.usdc) || deposit.amount !== expected.exposureUnits) {
1028
+ fail("arc_home_wrong_amount", "The Arc home Gateway deposit is not exactly amount plus fee in source USDC.");
1029
+ }
1030
+ }
1031
+ /**
1032
+ * Sign and broadcast one owner-paid source-chain call through an explicitly
1033
+ * configured RPC. There is no public-RPC default: an unset URL fails before
1034
+ * anything is signed.
1035
+ */
1036
+ export async function broadcastOwnerCall(chain, call, options = {}) {
1037
+ const url = arcHomeChainRpcUrl(chain);
1038
+ if (!url) {
1039
+ fail("arc_home_source_rpc_unconfigured", `Set FELIX_${chain.toUpperCase()}_RPC_URL to your own ${chain} RPC endpoint; Felix never broadcasts owner-paid ${chain} gas for you and this client never uses a public RPC.`);
1040
+ }
1041
+ const account = privateKeyToAccount(ownerKeyOrThrow(options.privateKey));
1042
+ const client = createPublicClient({ chain: ownerChain(call.chain_id), transport: http(url, { retryCount: 0, timeout: 30_000 }) });
1043
+ const relayClient = client;
1044
+ if (options.knownHash) {
1045
+ const receipt = await relayRetry("eth_getTransactionReceipt", () => client.request({
1046
+ method: "eth_getTransactionReceipt", params: [options.knownHash],
1047
+ }));
1048
+ if (receipt)
1049
+ return { transaction_hash: options.knownHash, nonce: -1 };
1050
+ fail("arc_home_receipt_unknown", "The previously signed Arc home transaction has no receipt yet. Reconcile its hash before signing again.");
1051
+ }
1052
+ const observedChainId = await relayRetry("eth_chainId", () => client.getChainId());
1053
+ if (observedChainId !== call.chain_id) {
1054
+ fail("arc_home_source_rpc_mismatch", `The configured ${chain} RPC reports chain ${observedChainId}, not ${call.chain_id}.`);
1055
+ }
1056
+ const [nonce, balance, block] = await Promise.all([
1057
+ relayRetry("eth_getTransactionCount", () => client.getTransactionCount({ address: account.address, blockTag: "pending" })),
1058
+ relayRetry("eth_getBalance", () => client.getBalance({ address: account.address })),
1059
+ relayRetry("eth_getBlockByNumber", () => client.getBlock({ blockTag: "latest" })),
1060
+ ]);
1061
+ let priority = 1000000000n;
1062
+ try {
1063
+ priority = BigInt(await relayRetry("eth_maxPriorityFeePerGas", () => client.request({ method: "eth_maxPriorityFeePerGas" })));
1064
+ }
1065
+ catch {
1066
+ priority = 1000000000n;
1067
+ }
1068
+ const baseFee = block.baseFeePerGas ?? await relayRetry("eth_gasPrice", () => client.getGasPrice());
1069
+ const maxFeePerGas = baseFee * 2n + priority;
1070
+ const estimated = await relayRetry("eth_estimateGas", () => client.estimateGas({
1071
+ account: account.address, to: call.to, data: call.data, value: 0n,
1072
+ }));
1073
+ const gas = estimated * 13n / 10n;
1074
+ const maxGas = options.maxGas ?? 1500000n;
1075
+ if (estimated <= 0n || gas > maxGas) {
1076
+ fail("arc_home_source_gas_out_of_bounds", `The ${chain} gas estimate for this Arc home deposit call is outside the client ceiling.`);
1077
+ }
1078
+ if (balance < gas * maxFeePerGas) {
1079
+ fail("arc_home_source_insufficient_gas", `The owner wallet cannot pay ${chain} gas for this Arc home deposit; it needs about ${(gas * maxFeePerGas).toString()} wei.`);
1080
+ }
1081
+ const serialized = await account.signTransaction({
1082
+ chainId: call.chain_id,
1083
+ type: "eip1559",
1084
+ to: call.to,
1085
+ data: call.data,
1086
+ value: 0n,
1087
+ gas,
1088
+ nonce,
1089
+ maxFeePerGas,
1090
+ maxPriorityFeePerGas: priority < maxFeePerGas ? priority : maxFeePerGas,
1091
+ });
1092
+ const transactionHash = keccak256(serialized);
1093
+ options.beforeBroadcast?.({ transaction_hash: transactionHash, nonce });
1094
+ await broadcastSignedTransaction(relayClient, {
1095
+ serialized_transaction: serialized,
1096
+ transaction_hash: transactionHash,
1097
+ nonce,
1098
+ owner: account.address,
1099
+ chain_id: call.chain_id,
1100
+ }, { receiptGraceMs: ARC_BROADCAST_RECEIPT_GRACE_MS });
1101
+ return { transaction_hash: transactionHash, nonce };
1102
+ }
1103
+ export async function waitForOwnerReceipt(chain, chainId, hash, timeoutMs = 240_000) {
1104
+ const url = arcHomeChainRpcUrl(chain);
1105
+ if (!url)
1106
+ return null;
1107
+ const client = createPublicClient({ chain: ownerChain(chainId), transport: http(url, { retryCount: 0, timeout: 30_000 }) });
1108
+ const deadline = Date.now() + timeoutMs;
1109
+ for (;;) {
1110
+ const raw = await relayRetry("eth_getTransactionReceipt", () => client.request({
1111
+ method: "eth_getTransactionReceipt", params: [hash],
1112
+ }));
1113
+ if (raw && typeof raw === "object") {
1114
+ return { status: raw.status === "0x1" ? "success" : "reverted" };
1115
+ }
1116
+ if (Date.now() >= deadline)
1117
+ return null;
1118
+ await new Promise((resolve) => setTimeout(resolve, 3_000));
1119
+ }
1120
+ }
1121
+ /**
1122
+ * Parse `/v1/arc-home/account`. A registered Safe must be owned by the local
1123
+ * owner key and must be that key's CREATE2 Safe, or nothing is trusted.
1124
+ */
1125
+ export function parseArcHomeAccount(payload, expectedOwner) {
1126
+ const body = record(payload, "arc-home/account");
1127
+ if (body.registered !== true) {
1128
+ return {
1129
+ registered: false, chain_id: null, safe: null, owner: null, modules: [],
1130
+ verified: false, onboarding_required: true,
1131
+ };
1132
+ }
1133
+ const safe = address(body.safe, "safe");
1134
+ const owner = address(body.owner, "owner");
1135
+ const chainId = integer(body.chain_id, "chain_id");
1136
+ if (expectedOwner && !sameAddress(owner, expectedOwner)) {
1137
+ fail("arc_home_owner_mismatch", "The registered Arc home Safe is owned by a different address than this client's owner key.");
1138
+ }
1139
+ if (expectedOwner && !sameAddress(safe, predictArcHomeSafe(expectedOwner))) {
1140
+ fail("arc_home_safe_prediction_mismatch", "The registered Arc home Safe is not the CREATE2 Safe this owner key controls.");
1141
+ }
1142
+ const modules = Array.isArray(body.modules)
1143
+ ? body.modules.map((entry, index) => address(entry, `modules[${index}]`))
1144
+ : [];
1145
+ return {
1146
+ registered: true,
1147
+ chain_id: chainId,
1148
+ safe,
1149
+ owner,
1150
+ modules,
1151
+ verified: body.verified === true,
1152
+ onboarding_required: false,
1153
+ };
1154
+ }
1155
+ /** Pin a reported deposit destination to the Safe derived from the local owner. */
1156
+ export function arcHomeSafeFromDepositResponse(payload, expectedOwner) {
1157
+ const body = record(payload, "deposit-address");
1158
+ const arc = record(body.arc, "deposit-address.arc");
1159
+ const owner = address(body.address, "deposit-address.address");
1160
+ const safe = address(arc.address, "deposit-address.arc.address");
1161
+ if (body.home_chain !== "arc" || arc.verified !== true
1162
+ || arc.chain_id !== ARC_MAINNET_CHAIN_ID || arc.address_role !== "arc_home_safe"
1163
+ || !sameAddress(owner, expectedOwner)
1164
+ || !sameAddress(safe, predictArcHomeSafe(expectedOwner))) {
1165
+ fail("arc_home_destination_mismatch", "The reported Arc destination does not match this local owner's Safe.");
1166
+ }
1167
+ return safe;
1168
+ }