@qntx/wallet-chains 0.9.0 → 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";
@@ -41,14 +41,383 @@ const evmTokenTable = Object.freeze({
41
41
  })
42
42
  });
43
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
+ }
44
408
  // src/evm/decode.ts
45
409
  const ERC20_TRANSFER = AbiFunction.from("function transfer(address to, uint256 amount)");
46
410
  const ERC20_APPROVE = AbiFunction.from("function approve(address spender, uint256 amount)");
47
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)");
48
418
  const ERC721_TRANSFER_FROM = AbiFunction.from("function transferFrom(address from, address to, uint256 tokenId)");
49
419
  const ERC721_SAFE_FROM = AbiFunction.from("function safeTransferFrom(address from, address to, uint256 tokenId)");
50
420
  const ERC1155_SAFE_FROM = AbiFunction.from("function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes data)");
51
- const MAX_UINT256 = 2n ** 256n - 1n;
52
421
  const argAddress = (args, index) => {
53
422
  const value = args[index];
54
423
  if (typeof value !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(value)) throw new ChainError("invalid-request", "decoded argument is not an address");
@@ -82,19 +451,19 @@ const weiAmount = (wei, symbol, decimals) => ({
82
451
  ...symbol === void 0 ? {} : { symbol },
83
452
  ...decimals === void 0 ? {} : { decimals }
84
453
  });
85
- const feeWei = (tx) => BigInt(tx.gas) * (tx.type === "eip1559" ? BigInt(tx.maxFeePerGas) : BigInt(tx.gasPrice));
86
- 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) => [{
87
456
  to,
88
- amount: weiAmount(BigInt(tx.value)),
457
+ amount: weiAmount(value),
89
458
  verified: true
90
459
  }];
91
- const tokenFlow = (tx, to, amount, chainId, table) => {
92
- const token = lookupEvmToken(table, chainId, tx.to ?? "");
460
+ const tokenFlow = (target, to, amount, chainId, table) => {
461
+ const token = lookupEvmToken(table, chainId, target);
93
462
  return {
94
463
  flows: [{
95
464
  to,
96
465
  amount: {
97
- asset: tx.to ?? "",
466
+ asset: target,
98
467
  amount: amount.toString(10),
99
468
  ...token === void 0 ? {} : {
100
469
  symbol: token.symbol,
@@ -106,13 +475,25 @@ const tokenFlow = (tx, to, amount, chainId, table) => {
106
475
  verified: token !== void 0
107
476
  };
108
477
  };
109
- const approvalChange = (tx, spender, amount) => ({
110
- asset: tx.to ?? "",
111
- spender,
112
- amount: amount.toString(10),
113
- unlimited: amount === MAX_UINT256,
114
- verified: false
115
- });
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
+ };
116
497
  const nftFlow = (asset, to, id) => [{
117
498
  to,
118
499
  amount: {
@@ -121,19 +502,21 @@ const nftFlow = (asset, to, id) => [{
121
502
  },
122
503
  verified: false
123
504
  }];
124
- const decodeTransaction = (request, table) => {
125
- const { tx } = request;
126
- const chainId = networkChainId(request.network);
127
- const data = tx.data.toLowerCase();
128
- 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();
129
512
  const base = {
130
513
  family: "evm",
131
- network: request.network,
514
+ network,
132
515
  approvals: [],
133
516
  warnings: []
134
517
  };
135
518
  if (data === "0x") {
136
- if (tx.to === void 0) return {
519
+ if (call.to === void 0) return {
137
520
  ...base,
138
521
  summary: "contract-call",
139
522
  outflows: [],
@@ -143,14 +526,14 @@ const decodeTransaction = (request, table) => {
143
526
  return {
144
527
  ...base,
145
528
  summary: "transfer",
146
- outflows: nativeOutflow(tx, tx.to),
529
+ outflows: nativeOutflow(call.value, call.to),
147
530
  fee,
148
531
  verifiability: "full"
149
532
  };
150
533
  }
151
534
  const transferArgs = tryCall(ERC20_TRANSFER, data);
152
535
  if (transferArgs !== void 0) {
153
- 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);
154
537
  return {
155
538
  ...base,
156
539
  summary: "transfer",
@@ -159,42 +542,64 @@ const decodeTransaction = (request, table) => {
159
542
  verifiability: verified ? "full" : "partial"
160
543
  };
161
544
  }
162
- const approveArgs = tryCall(ERC20_APPROVE, data);
163
- if (approveArgs !== void 0) return {
164
- ...base,
165
- summary: "approve",
166
- outflows: [],
167
- approvals: [approvalChange(tx, argAddress(approveArgs, 0), argUint(approveArgs, 1))],
168
- fee,
169
- verifiability: "partial"
170
- };
171
- const increaseArgs = tryCall(ERC20_INCREASE, data);
172
- if (increaseArgs !== void 0) return {
545
+ const partial = (summary, outflows, approvals) => ({
173
546
  ...base,
174
- summary: "approve",
175
- outflows: [],
176
- approvals: [approvalChange(tx, argAddress(increaseArgs, 0), argUint(increaseArgs, 1))],
547
+ summary,
548
+ outflows,
549
+ approvals,
177
550
  fee,
178
551
  verifiability: "partial"
179
- };
180
- 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
+ ]) {
181
571
  const args = tryCall(fn, data);
182
- if (args !== void 0) return {
183
- ...base,
184
- summary: "transfer",
185
- outflows: nftFlow(tx.to ?? "", argAddress(args, 1), argUint(args, 2)),
186
- fee,
187
- verifiability: "partial"
188
- };
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)), []);
189
592
  }
190
593
  const erc1155Args = tryCall(ERC1155_SAFE_FROM, data);
191
- if (erc1155Args !== void 0) return {
192
- ...base,
193
- summary: "transfer",
194
- outflows: nftFlow(tx.to ?? "", argAddress(erc1155Args, 1), argUint(erc1155Args, 2)),
195
- fee,
196
- verifiability: "partial"
197
- };
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
+ }
198
603
  return {
199
604
  ...base,
200
605
  summary: "contract-call",
@@ -203,6 +608,46 @@ const decodeTransaction = (request, table) => {
203
608
  verifiability: "opaque"
204
609
  };
205
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
+ };
206
651
  /** What the signer can guarantee about this request (WD-065). */
207
652
  const verifiabilityEvm = (request) => decodeEvm(request).verifiability;
208
653
  /**
@@ -219,19 +664,34 @@ const decodeEvm = (request, table = evmTokenTable) => {
219
664
  approvals: [],
220
665
  fee: void 0,
221
666
  warnings: [],
667
+ message: messageContent(request.message),
222
668
  verifiability: "opaque"
223
669
  };
224
670
  if (request.kind !== "evm.typed-data") throw new ChainError("unsupported", `unsupported sign request kind: ${request.kind}`);
225
- 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";
226
685
  return {
227
686
  family: "evm",
228
687
  network: request.network,
229
- summary: "message",
688
+ summary,
230
689
  outflows: [],
231
- approvals: [],
690
+ approvals: permit?.approvals ?? [],
232
691
  fee: void 0,
233
- warnings: typedDataWarnings(parsed),
234
- verifiability: "opaque"
692
+ warnings: permit?.warnings ?? [],
693
+ message,
694
+ verifiability: permit === void 0 ? "opaque" : "partial"
235
695
  };
236
696
  };
237
697
  // src/evm/recover.ts
@@ -307,7 +767,7 @@ const recoverEvmSigner = (request, result) => {
307
767
  });
308
768
  }
309
769
  if (request.kind === "evm.typed-data") {
310
- const { json } = parseTypedData(request.typedData, request.network);
770
+ const { json } = parseTypedData(request.typedData);
311
771
  const payload = TypedData.getSignPayload(json);
312
772
  return Secp256k1.recoverAddress({
313
773
  payload,
@@ -348,7 +808,9 @@ const normalizeEvm = (request) => {
348
808
  if (request["kind"] === "evm.typed-data") {
349
809
  const { typedData } = request;
350
810
  if (typeof typedData !== "string") throw new ChainError("invalid-request", "typed-data payload must be the JSON source string");
351
- 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}`);
352
814
  return {
353
815
  kind: "evm.typed-data",
354
816
  network,
@@ -358,6 +820,6 @@ const normalizeEvm = (request) => {
358
820
  }
359
821
  throw new ChainError("unsupported", `unsupported sign request kind: ${request["kind"]}`);
360
822
  };
361
- export { EVM_NATIVE_ASSET, 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 };
362
824
 
363
825
  //# sourceMappingURL=evm.mjs.map