@qntx/wallet-chains 0.8.1 → 0.10.0

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/dist/evm.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { ChainError } from "./index.mjs";
2
- import { n as requestBase } from "./account-ref-C2qrDbVT.mjs";
3
- import { a as isCanonicalHex, c as normalizeEvmTransaction, d as isEvmAddress, i as canonicalHex, l as checksumEvmAddress, n as typedDataWarnings, o as isRecord, r as assertHex, s as networkChainId, t as parseTypedData, u as evmAddressFromPublicKey } from "./typed-data-Cf1g7JVv.mjs";
1
+ import { n as parseSignIn, t as ChainError } from "./src-8NZeEnrW.mjs";
2
+ import { n as requestBase } from "./account-ref-D2rW_qlI.mjs";
3
+ import { _ as checksumEvmAddress, a as sameFields, c as typedDataMessages, d as canonicalHex, f as isCanonicalHex, g as quantityBigInt, h as normalizeEvmTransaction, i as parseTypedData, l as typedDataUint, m as networkChainId, n as domainChainId, o as typedDataAddress, p as isRecord, r as isTypedDataMessage, s as typedDataBytes, t as MAX_UINT48, u as assertHex, v as evmAddressFromPublicKey, y as isEvmAddress } from "./typed-data-J5g2WemC.mjs";
4
4
  import * as TypedData from "ox/TypedData";
5
5
  import * as AbiFunction from "ox/AbiFunction";
6
6
  import * as Hex from "ox/Hex";
@@ -10,6 +10,9 @@ import * as Signature from "ox/Signature";
10
10
  import * as TxEnvelopeEip1559 from "ox/TxEnvelopeEip1559";
11
11
  import * as TxEnvelopeEip2930 from "ox/TxEnvelopeEip2930";
12
12
  import * as TxEnvelopeLegacy from "ox/TxEnvelopeLegacy";
13
+ // src/evm/assets.ts
14
+ /** The native asset id in `AssetFlow` and simulated asset changes. */
15
+ const EVM_NATIVE_ASSET = "native";
13
16
  // src/evm/tokens.ts
14
17
  const USDC = Object.freeze({
15
18
  symbol: "USDC",
@@ -38,15 +41,383 @@ const evmTokenTable = Object.freeze({
38
41
  })
39
42
  });
40
43
  const lookupEvmToken = (table, chainId, address) => table[String(chainId)]?.[address];
44
+ // src/evm/approval.ts
45
+ const MAX_UINT256 = 2n ** 256n - 1n;
46
+ const MAX_UINT160 = 2n ** 160n - 1n;
47
+ /** The canonical Permit2 deployment (the same address on every supported chain). */
48
+ const PERMIT2_ADDRESS = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
49
+ /** A fungible-token allowance; `max` is the type's maximum, which marks it unlimited. */
50
+ const allowanceChange = (token, spender, value, change, max, chainId, table, extra = {}) => {
51
+ const known = lookupEvmToken(table, chainId, token);
52
+ return {
53
+ kind: "allowance",
54
+ spender,
55
+ amount: {
56
+ asset: token,
57
+ amount: value.toString(10),
58
+ ...known === void 0 ? {} : {
59
+ symbol: known.symbol,
60
+ decimals: known.decimals
61
+ }
62
+ },
63
+ change,
64
+ unlimited: change !== "decrease" && value === max,
65
+ ...extra,
66
+ verified: known !== void 0
67
+ };
68
+ };
69
+ // src/evm/permit.ts
70
+ const isMessage = isTypedDataMessage;
71
+ const address = typedDataAddress;
72
+ const uint = typedDataUint;
73
+ const DETAILS = [
74
+ "address token",
75
+ "uint160 amount",
76
+ "uint48 expiration",
77
+ "uint48 nonce"
78
+ ];
79
+ const PERMISSIONS = ["address token", "uint256 amount"];
80
+ const WITNESS_WARNING = {
81
+ kind: "permit2-witness",
82
+ message: "the permit carries a witness with further terms"
83
+ };
84
+ const entries = (value) => Array.isArray(value) && value.length > 0 && value.every(isMessage) ? value : void 0;
85
+ const permit = (...approvals) => ({
86
+ approvals,
87
+ warnings: []
88
+ });
89
+ /**
90
+ * The permit a typed-data document grants, or `undefined` when its shape is not exactly one of the
91
+ * recognized ones. `chainId` is the request network's, used for the built-in token table.
92
+ */
93
+ function recognizePermit(json, chainId, table) {
94
+ const { types, primaryType, message, domain } = json;
95
+ const verifying = address(domain["verifyingContract"]);
96
+ if (verifying === void 0) return;
97
+ const spender = address(message["spender"]);
98
+ if (spender === void 0) return;
99
+ const allow = (token, value, change, max, extra = {}) => allowanceChange(token, spender, value, change, max, chainId, table, extra);
100
+ if (primaryType === "Permit") {
101
+ if (sameFields(types, "Permit", [
102
+ "address owner",
103
+ "address spender",
104
+ "uint256 value",
105
+ "uint256 nonce",
106
+ "uint256 deadline"
107
+ ])) {
108
+ const value = uint(message["value"], MAX_UINT256);
109
+ return value === void 0 ? void 0 : permit(allow(verifying, value, "set", MAX_UINT256));
110
+ }
111
+ if (sameFields(types, "Permit", [
112
+ "address holder",
113
+ "address spender",
114
+ "uint256 nonce",
115
+ "uint256 expiry",
116
+ "bool allowed"
117
+ ])) {
118
+ const { allowed } = message;
119
+ return typeof allowed === "boolean" ? permit(allow(verifying, allowed ? MAX_UINT256 : 0n, "set", MAX_UINT256)) : void 0;
120
+ }
121
+ return;
122
+ }
123
+ if (verifying.toLowerCase() !== "0x000000000022D473030F116dDEE9F6B43aC78BA3".toLowerCase()) return;
124
+ return recognizePermit2(types, primaryType, message, allow);
125
+ }
126
+ const recognizePermit2 = (types, primaryType, message, allow) => {
127
+ const via = "permit2";
128
+ const allowance = (details) => {
129
+ const token = address(details["token"]);
130
+ const amount = uint(details["amount"], MAX_UINT160);
131
+ const expiration = uint(details["expiration"], MAX_UINT48);
132
+ return token === void 0 || amount === void 0 || expiration === void 0 ? void 0 : allow(token, amount, "set", MAX_UINT160, {
133
+ via,
134
+ expiration: Number(expiration)
135
+ });
136
+ };
137
+ const transfer = (permitted, deadline) => {
138
+ const token = address(permitted["token"]);
139
+ const amount = uint(permitted["amount"], MAX_UINT256);
140
+ return token === void 0 || amount === void 0 ? void 0 : allow(token, amount, "transfer", MAX_UINT256, {
141
+ via,
142
+ ...deadline <= MAX_UINT48 ? { expiration: Number(deadline) } : {}
143
+ });
144
+ };
145
+ const all = (list, build) => {
146
+ const built = list?.map(build);
147
+ return built === void 0 || built.some((a) => a === void 0) ? void 0 : permit(...built.filter((a) => a !== void 0));
148
+ };
149
+ if (primaryType === "PermitSingle") {
150
+ const { details } = message;
151
+ return sameFields(types, primaryType, [
152
+ "PermitDetails details",
153
+ "address spender",
154
+ "uint256 sigDeadline"
155
+ ]) && sameFields(types, "PermitDetails", DETAILS) && isMessage(details) ? all([details], allowance) : void 0;
156
+ }
157
+ if (primaryType === "PermitBatch") return sameFields(types, primaryType, [
158
+ "PermitDetails[] details",
159
+ "address spender",
160
+ "uint256 sigDeadline"
161
+ ]) && sameFields(types, "PermitDetails", DETAILS) ? all(entries(message["details"]), allowance) : void 0;
162
+ const witness = primaryType.includes("Witness");
163
+ const batch = primaryType.includes("Batch");
164
+ const expected = batch ? [
165
+ "TokenPermissions[] permitted",
166
+ "address spender",
167
+ "uint256 nonce",
168
+ "uint256 deadline"
169
+ ] : [
170
+ "TokenPermissions permitted",
171
+ "address spender",
172
+ "uint256 nonce",
173
+ "uint256 deadline"
174
+ ];
175
+ if (primaryType !== `Permit${batch ? "Batch" : ""}${witness ? "Witness" : ""}TransferFrom`) return;
176
+ const own = types[primaryType];
177
+ const last = own?.at(-1);
178
+ const fieldsOk = witness ? sameFields({
179
+ ...types,
180
+ [primaryType]: own?.slice(0, -1) ?? []
181
+ }, primaryType, expected) && last?.name === "witness" && types[last.type] !== void 0 : sameFields(types, primaryType, expected);
182
+ const deadline = uint(message["deadline"], MAX_UINT256);
183
+ if (!fieldsOk || !sameFields(types, "TokenPermissions", PERMISSIONS) || deadline === void 0) return;
184
+ const { permitted } = message;
185
+ const result = batch ? all(entries(permitted), (item) => transfer(item, deadline)) : isMessage(permitted) ? all([permitted], (item) => transfer(item, deadline)) : void 0;
186
+ return result === void 0 || !witness ? result : {
187
+ approvals: result.approvals,
188
+ warnings: [WITNESS_WARNING]
189
+ };
190
+ };
191
+ // src/evm/safe.ts
192
+ /**
193
+ * Recognition of Safe `SafeTx` typed data. A document is recognized only when the primary type is
194
+ * `SafeTx` with exactly the canonical field list and the domain names a `verifyingContract` (the
195
+ * Safe); any other shape stays an opaque message. A `delegatecall` to a canonical MultiSendCallOnly
196
+ * contract is unpacked into its inner calls; anything else stays a single opaque call.
197
+ */
198
+ /**
199
+ * Canonical MultiSendCallOnly deployments (safe-global/safe-deployments): 1.3.0, the 1.3.0 eip155
200
+ * variant and 1.4.1, lowercase for a checksum-insensitive compare.
201
+ */
202
+ const SAFE_MULTISEND_CALL_ONLY = /* @__PURE__ */ new Set([
203
+ "0x40a2accbd92bca938b02010e17a5b8929b49130d",
204
+ "0xa1dabef33b3b82c7814b6d82a79e50f4ac44102b",
205
+ "0x9641d764fc13c8b624c04430c7356c1c7c8102e2"
206
+ ]);
207
+ const SAFE_TX = [
208
+ "address to",
209
+ "uint256 value",
210
+ "bytes data",
211
+ "uint8 operation",
212
+ "uint256 safeTxGas",
213
+ "uint256 baseGas",
214
+ "uint256 gasPrice",
215
+ "address gasToken",
216
+ "address refundReceiver",
217
+ "uint256 nonce"
218
+ ];
219
+ const MULTISEND = AbiFunction.from("function multiSend(bytes transactions)");
220
+ /**
221
+ * Packed MultiSend entries (`uint8 operation, address to, uint256 value, uint256 dataLength, bytes
222
+ * data` repeated). `undefined` when `data` is not a `multiSend(bytes)` call, a byte is truncated or
223
+ * trailing, or an entry's operation is not 0 — the caller falls back to one opaque call.
224
+ */
225
+ const multiSendEntries = (data) => {
226
+ if (!data.toLowerCase().startsWith("0x8d80ff0a")) return;
227
+ let packed;
228
+ try {
229
+ const decoded = AbiFunction.decodeData(MULTISEND, data);
230
+ const first = Array.isArray(decoded) ? decoded[0] : void 0;
231
+ if (typeof first !== "string") return;
232
+ packed = first;
233
+ } catch {
234
+ return;
235
+ }
236
+ if (!packed.startsWith("0x")) return;
237
+ const hex = packed.slice(2).toLowerCase();
238
+ const calls = [];
239
+ let offset = 0;
240
+ while (offset < hex.length) {
241
+ if (hex.length - offset < 170) return;
242
+ if (Number.parseInt(hex.slice(offset, offset + 2), 16) !== 0) return;
243
+ const to = `0x${hex.slice(offset + 2, offset + 42)}`;
244
+ const value = BigInt(`0x${hex.slice(offset + 42, offset + 106)}`);
245
+ const length = BigInt(`0x${hex.slice(offset + 106, offset + 170)}`);
246
+ offset += 170;
247
+ if (length * 2n > BigInt(hex.length - offset)) return;
248
+ calls.push({
249
+ to: checksumEvmAddress(to),
250
+ value,
251
+ data: `0x${hex.slice(offset, offset + Number(length) * 2)}`
252
+ });
253
+ offset += Number(length) * 2;
254
+ }
255
+ return calls;
256
+ };
257
+ /**
258
+ * The Safe transaction a typed-data document signs, or `undefined` when its shape is not exactly
259
+ * the recognized one. `decode` decodes one inner call (the transaction rules without a fee); the
260
+ * caller injects it bound to the request's network and token table.
261
+ */
262
+ function recognizeSafe(json, decode) {
263
+ const { types, primaryType, message, domain } = json;
264
+ if (primaryType !== "SafeTx" || !sameFields(types, "SafeTx", SAFE_TX)) return;
265
+ const safe = typedDataAddress(domain["verifyingContract"]);
266
+ const to = typedDataAddress(message["to"]);
267
+ const value = typedDataUint(message["value"], MAX_UINT256);
268
+ const data = typedDataBytes(message["data"]);
269
+ const operation = typedDataUint(message["operation"], 255n);
270
+ const safeTxGas = typedDataUint(message["safeTxGas"], MAX_UINT256);
271
+ const baseGas = typedDataUint(message["baseGas"], MAX_UINT256);
272
+ const gasPrice = typedDataUint(message["gasPrice"], MAX_UINT256);
273
+ const gasToken = typedDataAddress(message["gasToken"]);
274
+ const refundReceiver = typedDataAddress(message["refundReceiver"]);
275
+ const nonce = typedDataUint(message["nonce"], MAX_UINT256);
276
+ if (safe === void 0 || to === void 0 || value === void 0 || data === void 0 || operation === void 0 || operation > 1n || safeTxGas === void 0 || baseGas === void 0 || gasPrice === void 0 || gasToken === void 0 || refundReceiver === void 0 || nonce === void 0) return;
277
+ const inner = operation === 1n && SAFE_MULTISEND_CALL_ONLY.has(to.toLowerCase()) ? multiSendEntries(data) : void 0;
278
+ const calls = (inner ?? [{
279
+ to,
280
+ value,
281
+ data
282
+ }]).map(decode);
283
+ return {
284
+ safe: {
285
+ safe,
286
+ nonce: nonce.toString(10),
287
+ operation: operation === 0n ? "call" : "delegatecall",
288
+ to,
289
+ value: value.toString(10),
290
+ data,
291
+ calls,
292
+ ...gasPrice > 0n ? { refund: {
293
+ gasPrice: gasPrice.toString(10),
294
+ gasToken,
295
+ refundReceiver
296
+ } } : {}
297
+ },
298
+ multisend: inner !== void 0
299
+ };
300
+ }
301
+ // src/evm/seaport.ts
302
+ /** Seaport 1.5 and 1.6 deployments, lowercase for a checksum-insensitive compare. */
303
+ const SEAPORT_CONTRACTS = /* @__PURE__ */ new Set(["0x0000000000000068f116a894984e2db1123eb395", "0x00000000000000adc04c56bf30ac9d3c0aaf14dc"]);
304
+ /** Seaport `itemType` values 0–5; an item type outside the list is not recognized. */
305
+ const ITEM_KINDS = [
306
+ "native",
307
+ "erc20",
308
+ "erc721",
309
+ "erc1155",
310
+ "erc721-criteria",
311
+ "erc1155-criteria"
312
+ ];
313
+ const ITEM_FIELDS = [
314
+ "uint8 itemType",
315
+ "address token",
316
+ "uint256 identifierOrCriteria",
317
+ "uint256 startAmount",
318
+ "uint256 endAmount"
319
+ ];
320
+ const typesMatch = (types) => Object.keys(types).length === 3 && sameFields(types, "OrderComponents", [
321
+ "address offerer",
322
+ "address zone",
323
+ "OfferItem[] offer",
324
+ "ConsiderationItem[] consideration",
325
+ "uint8 orderType",
326
+ "uint256 startTime",
327
+ "uint256 endTime",
328
+ "bytes32 zoneHash",
329
+ "uint256 salt",
330
+ "bytes32 conduitKey",
331
+ "uint256 counter"
332
+ ]) && sameFields(types, "OfferItem", ITEM_FIELDS) && sameFields(types, "ConsiderationItem", [...ITEM_FIELDS, "address recipient"]);
333
+ const amount = (kind, token, value, chainId, table) => {
334
+ if (kind === "native") return {
335
+ asset: EVM_NATIVE_ASSET,
336
+ amount: value.toString(10),
337
+ symbol: "ETH",
338
+ decimals: 18
339
+ };
340
+ if (kind === "erc20") {
341
+ const found = lookupEvmToken(table, chainId, token);
342
+ return {
343
+ asset: token,
344
+ amount: value.toString(10),
345
+ ...found === void 0 ? {} : {
346
+ symbol: found.symbol,
347
+ decimals: found.decimals
348
+ }
349
+ };
350
+ }
351
+ return {
352
+ asset: token,
353
+ amount: value.toString(10)
354
+ };
355
+ };
356
+ const item = (message, chainId, table) => {
357
+ const itemType = typedDataUint(message["itemType"], 255n);
358
+ const token = typedDataAddress(message["token"]);
359
+ const identifier = typedDataUint(message["identifierOrCriteria"], MAX_UINT256);
360
+ const start = typedDataUint(message["startAmount"], MAX_UINT256);
361
+ const end = typedDataUint(message["endAmount"], MAX_UINT256);
362
+ const kind = itemType === void 0 ? void 0 : ITEM_KINDS[Number(itemType)];
363
+ if (token === void 0 || identifier === void 0 || start === void 0 || end === void 0 || kind === void 0) return;
364
+ return {
365
+ kind,
366
+ token,
367
+ identifier: identifier.toString(10),
368
+ startAmount: amount(kind, token, start, chainId, table),
369
+ endAmount: amount(kind, token, end, chainId, table)
370
+ };
371
+ };
372
+ const all = (list, build) => {
373
+ const built = list?.map(build);
374
+ return built === void 0 || built.some((entry) => entry === void 0) ? void 0 : built.filter((entry) => entry !== void 0);
375
+ };
376
+ /**
377
+ * The Seaport order a typed-data document signs, or `undefined` when its shape is not exactly the
378
+ * recognized one. `chainId` is the request network's, used for the built-in token table.
379
+ */
380
+ function recognizeSeaport(json, chainId, table) {
381
+ const { types, primaryType, message, domain } = json;
382
+ if (primaryType !== "OrderComponents" || !typesMatch(types)) return;
383
+ const verifying = typedDataAddress(domain["verifyingContract"]);
384
+ if (domain["name"] !== "Seaport" || verifying === void 0 || !SEAPORT_CONTRACTS.has(verifying.toLowerCase())) return;
385
+ const offerer = typedDataAddress(message["offerer"]);
386
+ const zone = typedDataAddress(message["zone"]);
387
+ const startTime = typedDataUint(message["startTime"], MAX_UINT256);
388
+ const endTime = typedDataUint(message["endTime"], MAX_UINT256);
389
+ const offer = all(typedDataMessages(message["offer"]), (entry) => item(entry, chainId, table));
390
+ const consideration = all(typedDataMessages(message["consideration"]), (entry) => {
391
+ const base = item(entry, chainId, table);
392
+ const recipient = typedDataAddress(entry["recipient"]);
393
+ return base === void 0 || recipient === void 0 ? void 0 : {
394
+ ...base,
395
+ recipient
396
+ };
397
+ });
398
+ if (offerer === void 0 || zone === void 0 || startTime === void 0 || endTime === void 0 || offer === void 0 || consideration === void 0) return;
399
+ return {
400
+ offerer,
401
+ zone,
402
+ startTime: startTime <= MAX_UINT48 ? Number(startTime) : void 0,
403
+ endTime: endTime <= MAX_UINT48 ? Number(endTime) : void 0,
404
+ offer,
405
+ consideration
406
+ };
407
+ }
41
408
  // src/evm/decode.ts
42
409
  const ERC20_TRANSFER = AbiFunction.from("function transfer(address to, uint256 amount)");
43
410
  const ERC20_APPROVE = AbiFunction.from("function approve(address spender, uint256 amount)");
44
411
  const ERC20_INCREASE = AbiFunction.from("function increaseAllowance(address spender, uint256 amount)");
412
+ const ERC20_DECREASE = AbiFunction.from("function decreaseAllowance(address spender, uint256 subtractedValue)");
413
+ const SET_APPROVAL_FOR_ALL = AbiFunction.from("function setApprovalForAll(address operator, bool approved)");
414
+ const PERMIT2_APPROVE = AbiFunction.from("function approve(address token, address spender, uint160 amount, uint48 expiration)");
415
+ const PERMIT2_LOCKDOWN = AbiFunction.from("function lockdown((address token, address spender)[] approvals)");
416
+ const ERC721_SAFE_FROM_DATA = AbiFunction.from("function safeTransferFrom(address from, address to, uint256 tokenId, bytes data)");
417
+ const ERC1155_SAFE_BATCH_FROM = AbiFunction.from("function safeBatchTransferFrom(address from, address to, uint256[] ids, uint256[] amounts, bytes data)");
45
418
  const ERC721_TRANSFER_FROM = AbiFunction.from("function transferFrom(address from, address to, uint256 tokenId)");
46
419
  const ERC721_SAFE_FROM = AbiFunction.from("function safeTransferFrom(address from, address to, uint256 tokenId)");
47
420
  const ERC1155_SAFE_FROM = AbiFunction.from("function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes data)");
48
- const NATIVE_ASSET = "native";
49
- const MAX_UINT256 = 2n ** 256n - 1n;
50
421
  const argAddress = (args, index) => {
51
422
  const value = args[index];
52
423
  if (typeof value !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(value)) throw new ChainError("invalid-request", "decoded argument is not an address");
@@ -75,24 +446,24 @@ const tryCall = (fn, data) => {
75
446
  }
76
447
  };
77
448
  const weiAmount = (wei, symbol, decimals) => ({
78
- asset: NATIVE_ASSET,
449
+ asset: EVM_NATIVE_ASSET,
79
450
  amount: wei.toString(10),
80
451
  ...symbol === void 0 ? {} : { symbol },
81
452
  ...decimals === void 0 ? {} : { decimals }
82
453
  });
83
- const feeWei = (tx) => BigInt(tx.gas) * (tx.type === "eip1559" ? BigInt(tx.maxFeePerGas) : BigInt(tx.gasPrice));
84
- const nativeOutflow = (tx, to) => [{
454
+ const feeWei = (tx) => quantityBigInt(tx.gas, "tx.gas") * (tx.type === "eip1559" ? quantityBigInt(tx.maxFeePerGas, "tx.maxFeePerGas") : quantityBigInt(tx.gasPrice, "tx.gasPrice"));
455
+ const nativeOutflow = (value, to) => [{
85
456
  to,
86
- amount: weiAmount(BigInt(tx.value)),
457
+ amount: weiAmount(value),
87
458
  verified: true
88
459
  }];
89
- const tokenFlow = (tx, to, amount, chainId, table) => {
90
- const token = lookupEvmToken(table, chainId, tx.to ?? "");
460
+ const tokenFlow = (target, to, amount, chainId, table) => {
461
+ const token = lookupEvmToken(table, chainId, target);
91
462
  return {
92
463
  flows: [{
93
464
  to,
94
465
  amount: {
95
- asset: tx.to ?? "",
466
+ asset: target,
96
467
  amount: amount.toString(10),
97
468
  ...token === void 0 ? {} : {
98
469
  symbol: token.symbol,
@@ -104,13 +475,25 @@ const tokenFlow = (tx, to, amount, chainId, table) => {
104
475
  verified: token !== void 0
105
476
  };
106
477
  };
107
- const approvalChange = (tx, spender, amount) => ({
108
- asset: tx.to ?? "",
109
- spender,
110
- amount: amount.toString(10),
111
- unlimited: amount === MAX_UINT256,
112
- verified: false
113
- });
478
+ const argBool = (args, index) => {
479
+ const value = args[index];
480
+ if (typeof value !== "boolean") throw new ChainError("invalid-request", "decoded argument is not a bool");
481
+ return value;
482
+ };
483
+ const argList = (args, index) => {
484
+ const value = args[index];
485
+ if (!Array.isArray(value)) throw new ChainError("invalid-request", "decoded argument is not an array");
486
+ return value;
487
+ };
488
+ const argSeconds = (args, index) => {
489
+ const value = args[index];
490
+ if (typeof value !== "number" && typeof value !== "bigint") throw new ChainError("invalid-request", "decoded argument is not an integer");
491
+ return Number(value);
492
+ };
493
+ const pairField = (pair, key) => {
494
+ const value = typeof pair === "object" && pair !== null ? Reflect.get(pair, key) : "";
495
+ return argAddress([value], 0);
496
+ };
114
497
  const nftFlow = (asset, to, id) => [{
115
498
  to,
116
499
  amount: {
@@ -119,19 +502,21 @@ const nftFlow = (asset, to, id) => [{
119
502
  },
120
503
  verified: false
121
504
  }];
122
- const decodeTransaction = (request, table) => {
123
- const { tx } = request;
124
- const chainId = networkChainId(request.network);
125
- const data = tx.data.toLowerCase();
126
- const fee = { max: weiAmount(feeWei(tx)) };
505
+ /**
506
+ * The call rules shared by a whole transaction and a Safe's inner calls: the same selector table
507
+ * produces the intent; `fee` is `undefined` for a call that is not itself a transaction.
508
+ */
509
+ const decodeCall = (call, network, fee, table) => {
510
+ const chainId = networkChainId(network);
511
+ const data = call.data.toLowerCase();
127
512
  const base = {
128
513
  family: "evm",
129
- network: request.network,
514
+ network,
130
515
  approvals: [],
131
516
  warnings: []
132
517
  };
133
518
  if (data === "0x") {
134
- if (tx.to === void 0) return {
519
+ if (call.to === void 0) return {
135
520
  ...base,
136
521
  summary: "contract-call",
137
522
  outflows: [],
@@ -141,14 +526,14 @@ const decodeTransaction = (request, table) => {
141
526
  return {
142
527
  ...base,
143
528
  summary: "transfer",
144
- outflows: nativeOutflow(tx, tx.to),
529
+ outflows: nativeOutflow(call.value, call.to),
145
530
  fee,
146
531
  verifiability: "full"
147
532
  };
148
533
  }
149
534
  const transferArgs = tryCall(ERC20_TRANSFER, data);
150
535
  if (transferArgs !== void 0) {
151
- const { flows, verified } = tokenFlow(tx, argAddress(transferArgs, 0), argUint(transferArgs, 1), chainId, table);
536
+ const { flows, verified } = tokenFlow(call.to ?? "", argAddress(transferArgs, 0), argUint(transferArgs, 1), chainId, table);
152
537
  return {
153
538
  ...base,
154
539
  summary: "transfer",
@@ -157,42 +542,64 @@ const decodeTransaction = (request, table) => {
157
542
  verifiability: verified ? "full" : "partial"
158
543
  };
159
544
  }
160
- const approveArgs = tryCall(ERC20_APPROVE, data);
161
- if (approveArgs !== void 0) return {
162
- ...base,
163
- summary: "approve",
164
- outflows: [],
165
- approvals: [approvalChange(tx, argAddress(approveArgs, 0), argUint(approveArgs, 1))],
166
- fee,
167
- verifiability: "partial"
168
- };
169
- const increaseArgs = tryCall(ERC20_INCREASE, data);
170
- if (increaseArgs !== void 0) return {
545
+ const partial = (summary, outflows, approvals) => ({
171
546
  ...base,
172
- summary: "approve",
173
- outflows: [],
174
- approvals: [approvalChange(tx, argAddress(increaseArgs, 0), argUint(increaseArgs, 1))],
547
+ summary,
548
+ outflows,
549
+ approvals,
175
550
  fee,
176
551
  verifiability: "partial"
177
- };
178
- for (const fn of [ERC721_TRANSFER_FROM, ERC721_SAFE_FROM]) {
552
+ });
553
+ const token = call.to ?? "";
554
+ if (token.toLowerCase() === "0x000000000022D473030F116dDEE9F6B43aC78BA3".toLowerCase()) {
555
+ const permitArgs = tryCall(PERMIT2_APPROVE, data);
556
+ if (permitArgs !== void 0) {
557
+ const amount = argUint(permitArgs, 2);
558
+ return partial("approve", [], [allowanceChange(argAddress(permitArgs, 0), argAddress(permitArgs, 1), amount, "set", MAX_UINT160, chainId, table, {
559
+ via: "permit2",
560
+ expiration: argSeconds(permitArgs, 3)
561
+ })]);
562
+ }
563
+ const lockdownArgs = tryCall(PERMIT2_LOCKDOWN, data);
564
+ if (lockdownArgs !== void 0) return partial("approve", [], argList(lockdownArgs, 0).map((pair) => allowanceChange(pairField(pair, "token"), pairField(pair, "spender"), 0n, "set", MAX_UINT160, chainId, table, { via: "permit2" })));
565
+ }
566
+ for (const [fn, change] of [
567
+ [ERC20_APPROVE, "set"],
568
+ [ERC20_INCREASE, "increase"],
569
+ [ERC20_DECREASE, "decrease"]
570
+ ]) {
179
571
  const args = tryCall(fn, data);
180
- if (args !== void 0) return {
181
- ...base,
182
- summary: "transfer",
183
- outflows: nftFlow(tx.to ?? "", argAddress(args, 1), argUint(args, 2)),
184
- fee,
185
- verifiability: "partial"
186
- };
572
+ if (args !== void 0) return partial("approve", [], [allowanceChange(token, argAddress(args, 0), argUint(args, 1), change, MAX_UINT256, chainId, table)]);
573
+ }
574
+ const operatorArgs = tryCall(SET_APPROVAL_FOR_ALL, data);
575
+ if (operatorArgs !== void 0) return partial("approve", [], [{
576
+ kind: "operator",
577
+ asset: token,
578
+ spender: argAddress(operatorArgs, 0),
579
+ approved: argBool(operatorArgs, 1),
580
+ verified: false
581
+ }]);
582
+ const transferFromArgs = tryCall(ERC721_TRANSFER_FROM, data);
583
+ if (transferFromArgs !== void 0) {
584
+ const to = argAddress(transferFromArgs, 1);
585
+ const id = argUint(transferFromArgs, 2);
586
+ if (lookupEvmToken(table, chainId, token) !== void 0) return partial("transfer", tokenFlow(token, to, id, chainId, table).flows, []);
587
+ return partial("transfer", nftFlow(token, to, id), []);
588
+ }
589
+ for (const fn of [ERC721_SAFE_FROM, ERC721_SAFE_FROM_DATA]) {
590
+ const args = tryCall(fn, data);
591
+ if (args !== void 0) return partial("transfer", nftFlow(token, argAddress(args, 1), argUint(args, 2)), []);
187
592
  }
188
593
  const erc1155Args = tryCall(ERC1155_SAFE_FROM, data);
189
- if (erc1155Args !== void 0) return {
190
- ...base,
191
- summary: "transfer",
192
- outflows: nftFlow(tx.to ?? "", argAddress(erc1155Args, 1), argUint(erc1155Args, 2)),
193
- fee,
194
- verifiability: "partial"
195
- };
594
+ if (erc1155Args !== void 0) return partial("transfer", nftFlow(token, argAddress(erc1155Args, 1), argUint(erc1155Args, 2)), []);
595
+ const batchArgs = tryCall(ERC1155_SAFE_BATCH_FROM, data);
596
+ if (batchArgs !== void 0) {
597
+ const ids = argList(batchArgs, 2);
598
+ if (ids.length > 0 && ids.length === argList(batchArgs, 3).length) {
599
+ const to = argAddress(batchArgs, 1);
600
+ return partial("transfer", ids.flatMap((id) => nftFlow(token, to, argUint([id], 0))), []);
601
+ }
602
+ }
196
603
  return {
197
604
  ...base,
198
605
  summary: "contract-call",
@@ -201,6 +608,46 @@ const decodeTransaction = (request, table) => {
201
608
  verifiability: "opaque"
202
609
  };
203
610
  };
611
+ const decodeTransaction = (request, table) => {
612
+ const { tx } = request;
613
+ return decodeCall({
614
+ to: tx.to,
615
+ value: quantityBigInt(tx.value, "tx.value"),
616
+ data: tx.data
617
+ }, request.network, { max: weiAmount(feeWei(tx)) }, table);
618
+ };
619
+ /** The five EIP-712 domain fields a wallet shows; anything malformed is left out. */
620
+ const displayDomain = (domain) => {
621
+ const { name, version, verifyingContract, salt } = domain;
622
+ const chainId = domainChainId(domain);
623
+ return {
624
+ ...typeof name === "string" ? { name } : {},
625
+ ...typeof version === "string" ? { version } : {},
626
+ ...chainId === void 0 ? {} : { chainId },
627
+ ...typeof verifyingContract === "string" && /^0x[0-9a-fA-F]{40}$/.test(verifyingContract) ? { verifyingContract: checksumEvmAddress(verifyingContract) } : {},
628
+ ...typeof salt === "string" ? { salt } : {}
629
+ };
630
+ };
631
+ /** Strict UTF-8 text with any sign-in recognition, else the raw bytes as hex. */
632
+ const messageContent = (bytes) => {
633
+ try {
634
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
635
+ const signIn = parseSignIn(text, "evm");
636
+ return signIn === void 0 ? {
637
+ kind: "text",
638
+ text
639
+ } : {
640
+ kind: "text",
641
+ text,
642
+ signIn
643
+ };
644
+ } catch {
645
+ return {
646
+ kind: "bytes",
647
+ hex: `0x${[...bytes].map((b) => b.toString(16).padStart(2, "0")).join("")}`
648
+ };
649
+ }
650
+ };
204
651
  /** What the signer can guarantee about this request (WD-065). */
205
652
  const verifiabilityEvm = (request) => decodeEvm(request).verifiability;
206
653
  /**
@@ -217,19 +664,34 @@ const decodeEvm = (request, table = evmTokenTable) => {
217
664
  approvals: [],
218
665
  fee: void 0,
219
666
  warnings: [],
667
+ message: messageContent(request.message),
220
668
  verifiability: "opaque"
221
669
  };
222
670
  if (request.kind !== "evm.typed-data") throw new ChainError("unsupported", `unsupported sign request kind: ${request.kind}`);
223
- const parsed = parseTypedData(request.typedData, request.network);
671
+ const { json } = parseTypedData(request.typedData);
672
+ const chainId = networkChainId(request.network);
673
+ const permit = recognizePermit(json, chainId, table);
674
+ const seaport = permit === void 0 ? recognizeSeaport(json, chainId, table) : void 0;
675
+ const safe = permit === void 0 && seaport === void 0 ? recognizeSafe(json, (call) => decodeCall(call, request.network, void 0, table)) : void 0;
676
+ const message = {
677
+ kind: "typed-data",
678
+ primaryType: json.primaryType,
679
+ domain: displayDomain(json.domain),
680
+ data: json.message,
681
+ ...seaport === void 0 ? {} : { seaport },
682
+ ...safe === void 0 ? {} : { safe: safe.safe }
683
+ };
684
+ const summary = seaport === void 0 ? safe === void 0 ? permit === void 0 ? "message" : "approve" : safe.multisend ? "batch" : safe.safe.calls[0]?.summary ?? "contract-call" : "swap";
224
685
  return {
225
686
  family: "evm",
226
687
  network: request.network,
227
- summary: "message",
688
+ summary,
228
689
  outflows: [],
229
- approvals: [],
690
+ approvals: permit?.approvals ?? [],
230
691
  fee: void 0,
231
- warnings: typedDataWarnings(parsed),
232
- verifiability: "opaque"
692
+ warnings: permit?.warnings ?? [],
693
+ message,
694
+ verifiability: permit === void 0 ? "opaque" : "partial"
233
695
  };
234
696
  };
235
697
  // src/evm/recover.ts
@@ -305,7 +767,7 @@ const recoverEvmSigner = (request, result) => {
305
767
  });
306
768
  }
307
769
  if (request.kind === "evm.typed-data") {
308
- const { json } = parseTypedData(request.typedData, request.network);
770
+ const { json } = parseTypedData(request.typedData);
309
771
  const payload = TypedData.getSignPayload(json);
310
772
  return Secp256k1.recoverAddress({
311
773
  payload,
@@ -346,7 +808,9 @@ const normalizeEvm = (request) => {
346
808
  if (request["kind"] === "evm.typed-data") {
347
809
  const { typedData } = request;
348
810
  if (typeof typedData !== "string") throw new ChainError("invalid-request", "typed-data payload must be the JSON source string");
349
- parseTypedData(typedData, network);
811
+ const { json } = parseTypedData(typedData);
812
+ const domainChain = domainChainId(json.domain);
813
+ if (domainChain !== void 0 && domainChain !== chainId) throw new ChainError("chain-id-mismatch", `typed-data domain.chainId ${domainChain} does not match network ${network}`);
350
814
  return {
351
815
  kind: "evm.typed-data",
352
816
  network,
@@ -356,6 +820,6 @@ const normalizeEvm = (request) => {
356
820
  }
357
821
  throw new ChainError("unsupported", `unsupported sign request kind: ${request["kind"]}`);
358
822
  };
359
- export { canonicalHex, checksumEvmAddress, decodeEvm, evmAddressFromPublicKey, evmTokenTable, isCanonicalHex, isEvmAddress, lookupEvmToken, networkChainId, normalizeEvm, normalizeEvmTransaction, parseTypedData, recoverEvmSigner, verifiabilityEvm };
823
+ export { EVM_NATIVE_ASSET, PERMIT2_ADDRESS, SAFE_MULTISEND_CALL_ONLY, canonicalHex, checksumEvmAddress, decodeEvm, evmAddressFromPublicKey, evmTokenTable, isCanonicalHex, isEvmAddress, lookupEvmToken, networkChainId, normalizeEvm, normalizeEvmTransaction, parseTypedData, recoverEvmSigner, verifiabilityEvm };
360
824
 
361
825
  //# sourceMappingURL=evm.mjs.map