@qntx/wallet-native 0.9.0 → 0.11.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.
@@ -1,6 +1,6 @@
1
1
  (function() {
2
2
  // \0rolldown/runtime.js
3
- var __defProp = Object.defineProperty;
3
+ var __defProp$1 = Object.defineProperty;
4
4
  var __esmMin = (fn, res, err) => () => {
5
5
  if (err) throw err[0];
6
6
  try {
@@ -9,13 +9,13 @@
9
9
  throw err = [e], e;
10
10
  }
11
11
  };
12
- var __exportAll = (all, no_symbols) => {
12
+ var __exportAll$1 = (all, no_symbols) => {
13
13
  let target = {};
14
- for (var name in all) __defProp(target, name, {
14
+ for (var name in all) __defProp$1(target, name, {
15
15
  get: all[name],
16
16
  enumerable: true
17
17
  });
18
- if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
18
+ if (!no_symbols) __defProp$1(target, Symbol.toStringTag, { value: "Module" });
19
19
  return target;
20
20
  };
21
21
  // node_modules/.bun/@noble+ciphers@2.4.0/node_modules/@noble/ciphers/utils.js
@@ -497,7 +497,7 @@
497
497
  var init_defineProperty = __esmMin((() => {
498
498
  init_toPropertyKey();
499
499
  }));
500
- // packages/wallet/dist/core-Cq5h9X0X.mjs
500
+ // packages/wallet/dist/core-DDfzuSIa.mjs
501
501
  init_defineProperty();
502
502
  /**
503
503
  * Strict validator combinators for the secret-area protocol. Both sides share them: the kernel
@@ -711,9 +711,12 @@
711
711
  origin: union(literal("passkey"), literal("mnemonic")),
712
712
  words: union(literal(12), literal(15), literal(18), literal(21), literal(24)),
713
713
  backup: union(literal("none"), literal("passkey"), literal("mnemonic")),
714
+ passphrase: bool,
714
715
  createdAt: safeTime
715
716
  });
716
- var walletErrorCode = union(literal("locked"), literal("cancelled"), literal("factor-unavailable"), literal("factor-invalidated"), literal("wrong-password"), literal("wrong-passkey"), literal("rate-limited"), literal("invalid-input"), literal("not-found"), literal("already-exists"), literal("conflict"), literal("unsupported"), literal("unavailable"), literal("integrity"), literal("approval-required"), literal("crashed"));
717
+ /** A BIP-39 passphrase on the wire: raw UTF-8 bytes, never empty (the host omits "none"). */
718
+ var passphraseBytes = bytes(1, 1024);
719
+ var walletErrorCode = union(literal("locked"), literal("cancelled"), literal("factor-invalidated"), literal("no-device-credential"), literal("passkey-not-configured"), literal("passkey-prf-unsupported"), literal("wrong-password"), literal("wrong-passkey"), literal("rate-limited"), literal("invalid-input"), literal("not-found"), literal("already-exists"), literal("conflict"), literal("unsupported"), literal("unavailable"), literal("integrity"), literal("approval-required"), literal("crashed"));
717
720
  var createdResult = obj({
718
721
  wallet: walletInfo$1,
719
722
  session: sessionId
@@ -785,7 +788,8 @@
785
788
  presence: true,
786
789
  params: obj({
787
790
  draft: draftId,
788
- answers: arr(bytes(1, 64), 3, 3)
791
+ answers: arr(bytes(1, 64), 3, 3),
792
+ passphrase: opt(passphraseBytes)
789
793
  }),
790
794
  result: createdResult
791
795
  },
@@ -822,10 +826,15 @@
822
826
  params: obj({
823
827
  envelope: str(4e6),
824
828
  backupFactor: backupUnlockFactor,
829
+ passphrases: opt(arr(obj({
830
+ walletId,
831
+ passphrase: passphraseBytes
832
+ }), 1e3)),
825
833
  factor: opt(factor)
826
834
  }),
827
835
  result: obj({
828
836
  wallets: arr(walletInfo$1, 1e3),
837
+ passphraseRequired: arr(str(128), 1e3),
829
838
  session: sessionId
830
839
  })
831
840
  },
@@ -834,6 +843,7 @@
834
843
  presence: true,
835
844
  params: obj({
836
845
  mnemonic: bytes(1, 1024),
846
+ passphrase: opt(passphraseBytes),
837
847
  factor: opt(factor)
838
848
  }),
839
849
  result: createdResult
@@ -845,7 +855,10 @@
845
855
  verify: factor,
846
856
  walletId
847
857
  }),
848
- result: bytes(16, 1024)
858
+ result: obj({
859
+ mnemonic: bytes(16, 1024),
860
+ passphrase: opt(passphraseBytes)
861
+ })
849
862
  },
850
863
  "wallet.delete": {
851
864
  session: true,
@@ -888,7 +901,7 @@
888
901
  var init_objectSpread2 = __esmMin((() => {
889
902
  init_defineProperty();
890
903
  }));
891
- // packages/wallet/dist/protocol-DbpLncEB.mjs
904
+ // packages/wallet/dist/protocol-DqBfdhN5.mjs
892
905
  init_objectSpread2();
893
906
  /**
894
907
  * Backup-envelope wire validators (design/backup.mdx): the strict structural shape the kernel and
@@ -920,7 +933,8 @@
920
933
  var backupHeader = obj({ wallets: arr(obj({
921
934
  walletId: str(128),
922
935
  origin: union(literal("mnemonic"), literal("passkey")),
923
- words: union(literal(12), literal(15), literal(18), literal(21), literal(24))
936
+ words: union(literal(12), literal(15), literal(18), literal(21), literal(24)),
937
+ passphrase: opt(literal(true))
924
938
  }), 1e3) });
925
939
  var backupInfo = obj({
926
940
  id: str(32, /^[0-9a-f]{32}$/),
@@ -1647,7 +1661,8 @@
1647
1661
  var lockReason = union(literal("cold-start"), literal("user"), literal("idle"), literal("background"), literal("expired"), literal("crashed"), literal("invalidated"));
1648
1662
  obj({
1649
1663
  code: walletErrorCode,
1650
- retryAt: opt(safeTime)
1664
+ retryAt: opt(safeTime),
1665
+ detail: opt(str(80, /^[A-Za-z0-9_.:-]+$/))
1651
1666
  });
1652
1667
  obj({
1653
1668
  v: literal(2),
@@ -3314,7 +3329,7 @@
3314
3329
  toWords
3315
3330
  };
3316
3331
  }
3317
- var freeze, powers, asciiDecoder, B2S_CHUNK, hasBase64Builtin, ASCII_WHITESPACE, decodeBase64Builtin, base64Fallback, base64$1, base64urlnopad, B58_GROUP, RADIX_BASE_N_MAX_LENGTH, BASE_N_MAX_BYTES, BASE_N_MAX_CHARS, radixBaseN, genBaseN, radix58, genBase58, base58, createBase58check, BECH_ALPHABET, BECH_UPPERCASE_PRINTABLE, POLYMOD_GENERATORS, bech32, bech32m, _isWellFormedShim, _isWellFormed, utf8err, utf8Fallback, utf8$1, hexFallback, hasHexBuiltin, hexBuiltin, hex$2;
3332
+ var freeze, powers, asciiDecoder, B2S_CHUNK, hasBase64Builtin, ASCII_WHITESPACE, decodeBase64Builtin, base64Fallback, base64$1, base64urlnopad, B58_GROUP, RADIX_BASE_N_MAX_LENGTH, BASE_N_MAX_BYTES, BASE_N_MAX_CHARS, radixBaseN, genBaseN, radix58, genBase58, base58, createBase58check, BECH_ALPHABET, BECH_UPPERCASE_PRINTABLE, POLYMOD_GENERATORS, bech32, bech32m, _isWellFormedShim, _isWellFormed, utf8err, utf8Fallback, utf8$2, hexFallback, hasHexBuiltin, hexBuiltin, hex$2;
3318
3333
  var init_base = __esmMin((() => {
3319
3334
  freeze = (fn) => Object.freeze(fn());
3320
3335
  powers = /* @__PURE__ */ (() => {
@@ -3544,7 +3559,7 @@
3544
3559
  return res.subarray(0, pos);
3545
3560
  }
3546
3561
  }));
3547
- utf8$1 = /* @__PURE__ */ freeze(() => {
3562
+ utf8$2 = /* @__PURE__ */ freeze(() => {
3548
3563
  let _utf8Encoder;
3549
3564
  let _utf8Decoder;
3550
3565
  const utf8Builtin = {
@@ -3601,7 +3616,7 @@
3601
3616
  * input or secret contents.
3602
3617
  */
3603
3618
  var KernelError = class extends Error {
3604
- constructor(code, message, retryAt, corrupted = false) {
3619
+ constructor(code, message, retryAt, corrupted = false, detail) {
3605
3620
  super(message);
3606
3621
  _defineProperty(this, "code", void 0);
3607
3622
  _defineProperty(this, "retryAt", void 0);
@@ -3614,17 +3629,24 @@
3614
3629
  "corrupted",
3615
3630
  void 0
3616
3631
  );
3632
+ _defineProperty(
3633
+ this,
3634
+ /** Platform diagnostic `"<domain>:<code>"` a backend reported; forwarded to the host verbatim. */
3635
+ "detail",
3636
+ void 0
3637
+ );
3617
3638
  this.name = "KernelError";
3618
3639
  this.code = code;
3619
3640
  this.retryAt = retryAt;
3620
3641
  this.corrupted = corrupted;
3642
+ this.detail = detail;
3621
3643
  }
3622
3644
  };
3623
3645
  // packages/wallet-kernel/src/platform.ts
3624
3646
  init_objectSpread2();
3625
- /** The platform authenticator, or `factor-unavailable` where the host runs ceremonies. */
3647
+ /** The platform authenticator, or `unsupported` where the host runs ceremonies. */
3626
3648
  function requirePasskey(platform) {
3627
- if (platform.passkey === void 0) throw new KernelError("factor-unavailable", "this platform runs passkey ceremonies in the host");
3649
+ if (platform.passkey === void 0) throw new KernelError("unsupported", "this platform runs passkey ceremonies in the host");
3628
3650
  return platform.passkey;
3629
3651
  }
3630
3652
  /**
@@ -3669,11 +3691,11 @@
3669
3691
  * factors are exempt.
3670
3692
  */
3671
3693
  function assertFactorKindAvailable(platform, kind) {
3672
- if (platform.keystore !== void 0 !== (kind === "hardware")) throw new KernelError("factor-unavailable", "this factor kind is not available here");
3694
+ if (platform.keystore !== void 0 !== (kind === "hardware")) throw new KernelError("unsupported", "this factor kind is not available here");
3673
3695
  }
3674
- /** The platform keystore, or `factor-unavailable` on hosts without secure hardware. */
3696
+ /** The platform keystore, or `unsupported` on hosts without secure hardware. */
3675
3697
  function requireKeystore(platform) {
3676
- if (platform.keystore === void 0) throw new KernelError("factor-unavailable", "this platform has no hardware keystore");
3698
+ if (platform.keystore === void 0) throw new KernelError("unsupported", "this platform has no hardware keystore");
3677
3699
  return platform.keystore;
3678
3700
  }
3679
3701
  // packages/wallet-kernel/src/prompts.ts
@@ -7463,6 +7485,7 @@
7463
7485
  return value;
7464
7486
  }
7465
7487
  // packages/wallet-kernel/src/vault/headers.ts
7488
+ init_objectSpread2();
7466
7489
  var PURPOSE_PATTERN = /^[a-z0-9-]{1,32}$/;
7467
7490
  var PASSWORD_ITERATIONS$2 = 6e5;
7468
7491
  function encodeHeader(header) {
@@ -7491,13 +7514,14 @@
7491
7514
  purpose: header.purpose,
7492
7515
  createdAt: header.createdAt
7493
7516
  });
7494
- return JSON.stringify({
7517
+ return JSON.stringify(_objectSpread2(_objectSpread2({
7495
7518
  walletId: header.walletId,
7496
7519
  origin: header.origin,
7497
- words: header.words,
7520
+ words: header.words
7521
+ }, header.passphrase === true ? { passphrase: true } : {}), {}, {
7498
7522
  backup: header.backup,
7499
7523
  createdAt: header.createdAt
7500
- });
7524
+ }));
7501
7525
  }
7502
7526
  function asEntropyOrigin(value) {
7503
7527
  if (value !== "passkey" && value !== "mnemonic") throw headerFailure();
@@ -7509,7 +7533,15 @@
7509
7533
  }
7510
7534
  function parseEntropyHeader(text) {
7511
7535
  const object = headerObject(text);
7512
- expectKeys(object, [
7536
+ const flagged = Object.hasOwn(object, "passphrase");
7537
+ expectKeys(object, flagged ? [
7538
+ "walletId",
7539
+ "origin",
7540
+ "words",
7541
+ "passphrase",
7542
+ "backup",
7543
+ "createdAt"
7544
+ ] : [
7513
7545
  "walletId",
7514
7546
  "origin",
7515
7547
  "words",
@@ -7518,13 +7550,16 @@
7518
7550
  ]);
7519
7551
  const { backup } = object;
7520
7552
  if (backup !== "none" && backup !== "passkey" && backup !== "mnemonic") throw headerFailure();
7521
- return {
7553
+ const origin = asEntropyOrigin(object["origin"]);
7554
+ if (flagged && (object["passphrase"] !== true || origin !== "mnemonic")) throw headerFailure();
7555
+ return _objectSpread2(_objectSpread2({
7522
7556
  walletId: asWalletId(object["walletId"]),
7523
- origin: asEntropyOrigin(object["origin"]),
7524
- words: asWords(object["words"]),
7557
+ origin,
7558
+ words: asWords(object["words"])
7559
+ }, flagged ? { passphrase: true } : {}), {}, {
7525
7560
  backup,
7526
7561
  createdAt: asCreatedAt(object["createdAt"])
7527
- };
7562
+ });
7528
7563
  }
7529
7564
  function parseDataKeyHeader(text) {
7530
7565
  const object = headerObject(text);
@@ -7942,7 +7977,7 @@
7942
7977
  let dek;
7943
7978
  if (factor.kind === "hardware") {
7944
7979
  const stored = image.factors.find((f) => f.kind === "hardware");
7945
- if (stored === void 0) throw new KernelError("factor-unavailable", "no hardware factor exists");
7980
+ if (stored === void 0) throw new KernelError("not-found", "no hardware factor exists");
7946
7981
  const kek = await kekFor(platform, factor, stored, corePromptFor(platform.keystore, "unlock"));
7947
7982
  try {
7948
7983
  dek = unwrapDek(kek, stored);
@@ -8004,9 +8039,9 @@
8004
8039
  * compare. A public-key miss — `wrong-password`/`wrong-passkey` — tries the next candidate; every
8005
8040
  * other failure (including corruption-marked integrity) propagates immediately. When no candidate
8006
8041
  * matched, the miss is reported by factor kind: `wrong-password` (or `invalid-input` when no
8007
- * password factor exists), `wrong-passkey`, or for hardware `factor-unavailable` (no hardware
8008
- * factor) / `integrity` (the keystore opened a KEK for another DEK). `prompt` renders the system
8009
- * verification text and runs only for hardware. The verify path never touches the rate limiter.
8042
+ * password factor exists), `wrong-passkey`, or for hardware `not-found` (no hardware factor) /
8043
+ * `integrity` (the keystore opened a KEK for another DEK). `prompt` renders the system verification
8044
+ * text and runs only for hardware. The verify path never touches the rate limiter.
8010
8045
  */
8011
8046
  async function verifyFactor(platform, image, factor, dek, prompt) {
8012
8047
  assertFactorKindAvailable(platform, factor.kind);
@@ -8030,7 +8065,7 @@
8030
8065
  }
8031
8066
  }
8032
8067
  if (factor.kind === "password") throw new KernelError(candidates.length > 0 ? "wrong-password" : "invalid-input", "password did not verify");
8033
- if (factor.kind === "hardware") throw candidates.length > 0 ? new KernelError("integrity", "hardware factor does not open this vault", void 0, true) : new KernelError("factor-unavailable", "no hardware factor exists");
8068
+ if (factor.kind === "hardware") throw candidates.length > 0 ? new KernelError("integrity", "hardware factor does not open this vault", void 0, true) : new KernelError("not-found", "no hardware factor exists");
8034
8069
  throw new KernelError("wrong-passkey", "passkey did not verify");
8035
8070
  }
8036
8071
  /**
@@ -8126,6 +8161,34 @@
8126
8161
  function openRecord(dek, record) {
8127
8162
  return dek.use((bytes) => open(bytes, record.sealed, recordContext(record.kind, record.id), record.header));
8128
8163
  }
8164
+ /**
8165
+ * Splits an `entropy` record's plaintext at the header's entropy length; a payload the header does
8166
+ * not describe (a passphrase flag without bytes, bytes without the flag, more than
8167
+ * {@link MAX_PASSPHRASE_BYTES}) is `integrity`. Copies — the caller wipes `plaintext` and both
8168
+ * parts.
8169
+ */
8170
+ function splitWalletSecret(header, plaintext) {
8171
+ const entropyLength = header.words / 3 * 4;
8172
+ const extra = plaintext.length - entropyLength;
8173
+ if (!(header.passphrase === true ? extra >= 1 && extra <= 1024 : extra === 0)) throw new KernelError("integrity", "wallet record does not match its header");
8174
+ return {
8175
+ entropy: plaintext.slice(0, entropyLength),
8176
+ passphrase: header.passphrase === true ? plaintext.slice(entropyLength) : void 0
8177
+ };
8178
+ }
8179
+ /**
8180
+ * The only way to read an `entropy` record: opens it and splits it with {@link splitWalletSecret}.
8181
+ * The caller wipes both buffers.
8182
+ */
8183
+ function openWalletSecret(dek, record) {
8184
+ const header = parseEntropyHeader(record.header);
8185
+ const plaintext = openRecord(dek, record);
8186
+ try {
8187
+ return splitWalletSecret(header, plaintext);
8188
+ } finally {
8189
+ wipe(plaintext);
8190
+ }
8191
+ }
8129
8192
  function findRecord(image, kind, id) {
8130
8193
  const record = image.records.find((r) => r.kind === kind && r.id === id);
8131
8194
  if (record === void 0) throw new KernelError("not-found", "record not found");
@@ -8188,9 +8251,33 @@
8188
8251
  origin: header.origin,
8189
8252
  words: header.words,
8190
8253
  backup: header.backup,
8254
+ passphrase: header.passphrase === true,
8191
8255
  createdAt: header.createdAt
8192
8256
  };
8193
8257
  }
8258
+ // packages/wallet-kernel/src/commands/passphrase.ts
8259
+ init_utils$2();
8260
+ /**
8261
+ * A wire passphrase (raw UTF-8, wiped here) as the bytes the vault stores: NFKD-normalized, never
8262
+ * trimmed — spaces are significant in BIP-39 — and 1–1024 bytes after normalization.
8263
+ */
8264
+ function normalizePassphrase(wire) {
8265
+ const normalized = utf8ToBytes$1(decodeUtf8Secret(wire).normalize("NFKD"));
8266
+ if (normalized.length === 0 || normalized.length > 1024) {
8267
+ normalized.fill(0);
8268
+ throw new KernelError("invalid-input", "passphrase must be 1-1024 bytes");
8269
+ }
8270
+ return normalized;
8271
+ }
8272
+ /** The text `seedFromMnemonic` takes for stored passphrase bytes (`undefined` → no passphrase). */
8273
+ function passphraseText(passphrase) {
8274
+ if (passphrase === void 0) return "";
8275
+ try {
8276
+ return new TextDecoder("utf-8", { fatal: true }).decode(passphrase);
8277
+ } catch (_unused) {
8278
+ throw new KernelError("integrity", "wallet passphrase is not valid UTF-8");
8279
+ }
8280
+ }
8194
8281
  // node_modules/.bun/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/der.js
8195
8282
  var _0n$8, DERErr, _DER, DER;
8196
8283
  var init_der = __esmMin((() => {
@@ -12251,15 +12338,15 @@ zoo`.split("\n"));
12251
12338
  wipe(password, salt);
12252
12339
  }
12253
12340
  }
12254
- async function seedFromEntropy(entropy, pbkdf2) {
12255
- return seedFromMnemonic(mnemonicFromEntropy(entropy), "", pbkdf2);
12341
+ async function seedFromEntropy(entropy, passphrase, pbkdf2) {
12342
+ return seedFromMnemonic(mnemonicFromEntropy(entropy), passphrase, pbkdf2);
12256
12343
  }
12257
12344
  /**
12258
- * Derives the BIP-39 seed of `entropy`, runs `use`, wipes the seed on every path. Does not own
12259
- * `entropy`.
12345
+ * Derives the BIP-39 seed of `entropy` and `passphrase` ("" for none), runs `use`, wipes the seed
12346
+ * on every path. Does not own `entropy`.
12260
12347
  */
12261
- async function withSeed(pbkdf2, entropy, use) {
12262
- const seed = await seedFromEntropy(entropy, pbkdf2);
12348
+ async function withSeed(pbkdf2, entropy, passphrase, use) {
12349
+ const seed = await seedFromEntropy(entropy, passphrase, pbkdf2);
12263
12350
  try {
12264
12351
  return await use(seed);
12265
12352
  } finally {
@@ -12432,13 +12519,17 @@ zoo`.split("\n"));
12432
12519
  }
12433
12520
  };
12434
12521
  // packages/wallet-kernel/src/commands/vault.ts
12435
- /** Opens a wallet's sealed entropy record, then withSeed; wipes the entropy on every path. */
12522
+ /**
12523
+ * Opens a wallet's sealed entropy record, then withSeed over its entropy and passphrase; wipes both
12524
+ * on every path.
12525
+ */
12436
12526
  async function withWalletSeed(pbkdf2, dek, record, use) {
12437
- const entropy = openRecord(dek, record);
12527
+ const { entropy, passphrase } = openWalletSecret(dek, record);
12438
12528
  try {
12439
- return await withSeed(pbkdf2, entropy, use);
12529
+ return await withSeed(pbkdf2, entropy, passphraseText(passphrase), use);
12440
12530
  } finally {
12441
12531
  wipe(entropy);
12532
+ if (passphrase !== void 0) wipe(passphrase);
12442
12533
  }
12443
12534
  }
12444
12535
  var EMPTY_IMAGE$1 = {
@@ -12527,8 +12618,9 @@ zoo`.split("\n"));
12527
12618
  }
12528
12619
  // packages/wallet-kernel/src/commands/wallets.ts
12529
12620
  init_utils$2();
12530
- async function deriveWalletMaterial(platform, entropy) {
12531
- return withSeed(platform.pbkdf2, entropy, (seed) => {
12621
+ init_objectSpread2();
12622
+ async function deriveWalletMaterial(platform, entropy, passphrase) {
12623
+ return withSeed(platform.pbkdf2, entropy, passphraseText(passphrase), (seed) => {
12532
12624
  const master = masterKey(seed);
12533
12625
  return {
12534
12626
  master,
@@ -12536,13 +12628,14 @@ zoo`.split("\n"));
12536
12628
  };
12537
12629
  });
12538
12630
  }
12539
- /** Entropy → master → walletId. `entropy` is not consumed. */
12540
- async function walletMaterial(platform, entropy, origin, words) {
12541
- const { master, walletId } = await deriveWalletMaterial(platform, entropy);
12631
+ /** Entropy and passphrase → master → walletId. Neither buffer is consumed. */
12632
+ async function walletMaterial(platform, entropy, passphrase, origin, words) {
12633
+ const { master, walletId } = await deriveWalletMaterial(platform, entropy, passphrase);
12542
12634
  try {
12543
12635
  return {
12544
12636
  walletId,
12545
12637
  entropy,
12638
+ passphrase,
12546
12639
  words,
12547
12640
  origin
12548
12641
  };
@@ -12551,24 +12644,28 @@ zoo`.split("\n"));
12551
12644
  }
12552
12645
  }
12553
12646
  function walletInfoOf(material, backup, createdAt) {
12554
- return walletInfo({
12647
+ return walletInfo(_objectSpread2(_objectSpread2({
12555
12648
  walletId: material.walletId,
12556
12649
  origin: material.origin,
12557
12650
  words: material.words,
12558
- backup,
12559
- createdAt
12560
- });
12651
+ backup
12652
+ }, material.passphrase === void 0 ? {} : { passphrase: true }), {}, { createdAt }));
12653
+ }
12654
+ /** The `entropy` record payload: the entropy, then the passphrase bytes when there are any. */
12655
+ function walletSecretPlaintext(entropy, passphrase) {
12656
+ return passphrase === void 0 ? new Uint8Array(entropy) : concatBytes$3(entropy, passphrase);
12561
12657
  }
12562
12658
  /** The entropy record for a new wallet, sealed under `dek`. Consumes nothing. */
12563
12659
  function walletRecord(ctx, dek, material, backup, createdAt) {
12564
- const header = encodeHeader({
12660
+ const header = encodeHeader(_objectSpread2(_objectSpread2({
12565
12661
  walletId: material.walletId,
12566
12662
  origin: material.origin,
12567
- words: material.words,
12663
+ words: material.words
12664
+ }, material.passphrase === void 0 ? {} : { passphrase: true }), {}, {
12568
12665
  backup,
12569
12666
  createdAt
12570
- });
12571
- return sealRecord(ctx.platform, dek, "entropy", material.walletId, header, new Uint8Array(material.entropy));
12667
+ }));
12668
+ return sealRecord(ctx.platform, dek, "entropy", material.walletId, header, walletSecretPlaintext(material.entropy, material.passphrase));
12572
12669
  }
12573
12670
  /**
12574
12671
  * The dynamic gate on every "create or import" command: with an uninitialized vault `factor` is
@@ -12724,6 +12821,14 @@ zoo`.split("\n"));
12724
12821
  };
12725
12822
  }
12726
12823
  async function confirmMnemonic(ctx, params) {
12824
+ const passphrase = params.passphrase === void 0 ? void 0 : normalizePassphrase(params.passphrase);
12825
+ try {
12826
+ return await confirmWithPassphrase(ctx, params, passphrase);
12827
+ } finally {
12828
+ if (passphrase !== void 0) wipe(passphrase);
12829
+ }
12830
+ }
12831
+ async function confirmWithPassphrase(ctx, params, passphrase) {
12727
12832
  const allMatch = ctx.session.getDraft(params.draft).expected.every((expected, i) => {
12728
12833
  const answer = params.answers[i];
12729
12834
  return answer !== void 0 && answer.length === expected.length && equalBytes$3(answer, expected);
@@ -12733,7 +12838,7 @@ zoo`.split("\n"));
12733
12838
  const taken = ctx.session.takeDraft(params.draft);
12734
12839
  try {
12735
12840
  const entropy = taken.entropy.use((bytes) => new Uint8Array(bytes));
12736
- const material = await walletMaterial(ctx.platform, entropy, "mnemonic", taken.words);
12841
+ const material = await walletMaterial(ctx.platform, entropy, passphrase, "mnemonic", taken.words);
12737
12842
  try {
12738
12843
  ensureNewWallet(ctx, material);
12739
12844
  const createdAt = ctx.platform.now();
@@ -12776,9 +12881,20 @@ zoo`.split("\n"));
12776
12881
  }
12777
12882
  async function importMnemonic(ctx, params, requestSession) {
12778
12883
  const gated = gate(ctx, params.factor, requestSession);
12779
- const entropy = entropyFromMnemonic(decodeUtf8Secret(params.mnemonic));
12780
- const material = await walletMaterial(ctx.platform, entropy, "mnemonic", mnemonicWords(entropy));
12884
+ let text;
12781
12885
  try {
12886
+ text = decodeUtf8Secret(params.mnemonic);
12887
+ } catch (error) {
12888
+ var _params$passphrase;
12889
+ (_params$passphrase = params.passphrase) === null || _params$passphrase === void 0 || _params$passphrase.fill(0);
12890
+ throw error;
12891
+ }
12892
+ let passphrase;
12893
+ let entropy;
12894
+ try {
12895
+ passphrase = params.passphrase === void 0 ? void 0 : normalizePassphrase(params.passphrase);
12896
+ entropy = entropyFromMnemonic(text);
12897
+ const material = await walletMaterial(ctx.platform, entropy, passphrase, "mnemonic", mnemonicWords(entropy));
12782
12898
  ensureNewWallet(ctx, material);
12783
12899
  const createdAt = ctx.platform.now();
12784
12900
  const record = walletRecord(ctx, gated.dek, material, "mnemonic", createdAt);
@@ -12788,21 +12904,22 @@ zoo`.split("\n"));
12788
12904
  session
12789
12905
  };
12790
12906
  } finally {
12791
- wipe(entropy);
12907
+ if (entropy !== void 0) wipe(entropy);
12908
+ if (passphrase !== void 0) wipe(passphrase);
12792
12909
  }
12793
12910
  }
12794
12911
  var PURPOSE_WALLET = 1;
12795
12912
  /**
12796
12913
  * One platform ceremony's wallet PRF: the result must be user-verified and carry a 32-byte `first`
12797
- * output; anything else is an authenticator without usable PRF support (`factor-unavailable`). The
12798
- * unused `second` output is wiped.
12914
+ * output; anything else is an authenticator without usable PRF support (`passkey-prf-unsupported`).
12915
+ * The unused `second` output is wiped.
12799
12916
  */
12800
12917
  function walletPrfOf(result) {
12801
12918
  var _result$first;
12802
12919
  if (result.second !== void 0) wipe(result.second);
12803
12920
  if (!result.userVerified || ((_result$first = result.first) === null || _result$first === void 0 ? void 0 : _result$first.length) !== 32) {
12804
12921
  if (result.first !== void 0) wipe(result.first);
12805
- throw new KernelError("factor-unavailable", "the passkey returned no verified PRF output");
12922
+ throw new KernelError("passkey-prf-unsupported", "the passkey returned no verified PRF output");
12806
12923
  }
12807
12924
  return {
12808
12925
  prfWallet: result.first,
@@ -12849,10 +12966,10 @@ zoo`.split("\n"));
12849
12966
  /**
12850
12967
  * Creates or restores a passkey wallet. The ceremony runs where the platform puts it: in the kernel
12851
12968
  * when a platform authenticator exists, in the host (evidence on the wire) otherwise — the other
12852
- * shape is `factor-unavailable`.
12969
+ * shape is `unsupported`.
12853
12970
  */
12854
12971
  async function createWithPasskey(ctx, params, requestSession) {
12855
- if (ctx.platform.passkey !== void 0 !== (params.ceremony === "kernel")) throw new KernelError("factor-unavailable", "this platform runs passkey ceremonies elsewhere");
12972
+ if (ctx.platform.passkey !== void 0 !== (params.ceremony === "kernel")) throw new KernelError("unsupported", "this platform runs passkey ceremonies elsewhere");
12856
12973
  const gated = gate(ctx, params.factor, requestSession);
12857
12974
  let prf;
12858
12975
  try {
@@ -12862,7 +12979,7 @@ zoo`.split("\n"));
12862
12979
  throw error;
12863
12980
  }
12864
12981
  const entropy = entropyFromPrf(prf.prfWallet);
12865
- const material = await walletMaterial(ctx.platform, entropy, "passkey", 12);
12982
+ const material = await walletMaterial(ctx.platform, entropy, void 0, "passkey", 12);
12866
12983
  try {
12867
12984
  ensureNewWallet(ctx, material);
12868
12985
  const createdAt = ctx.platform.now();
@@ -12893,6 +13010,7 @@ zoo`.split("\n"));
12893
13010
  init_sha2();
12894
13011
  init_utils$2();
12895
13012
  init_base();
13013
+ init_objectSpread2();
12896
13014
  var PASSWORD_ITERATIONS = 6e5;
12897
13015
  /** Payload tag byte: wallet entry. */
12898
13016
  var ORIGIN_BYTE = {
@@ -12990,26 +13108,21 @@ zoo`.split("\n"));
12990
13108
  for (const record of ctx.image.records) {
12991
13109
  if (record.kind !== "entropy") continue;
12992
13110
  const header = parseEntropyHeader(record.header);
12993
- const plaintext = openRecord(dek, record);
12994
- try {
12995
- wallets.push({
12996
- walletId: record.id,
12997
- origin: header.origin,
12998
- words: header.words,
12999
- entropy: plaintext
13000
- });
13001
- } catch (error) {
13002
- plaintext.fill(0);
13003
- throw error;
13004
- }
13111
+ const { entropy, passphrase } = openWalletSecret(dek, record);
13112
+ passphrase === null || passphrase === void 0 || passphrase.fill(0);
13113
+ wallets.push(_objectSpread2(_objectSpread2({
13114
+ walletId: record.id,
13115
+ origin: header.origin,
13116
+ words: header.words
13117
+ }, header.passphrase === true ? { passphrase: true } : {}), {}, { entropy }));
13005
13118
  }
13006
13119
  return {
13007
13120
  wallets,
13008
- header: JSON.stringify({ wallets: wallets.map(({ walletId, origin, words }) => ({
13121
+ header: JSON.stringify({ wallets: wallets.map(({ walletId, origin, words, passphrase }) => _objectSpread2({
13009
13122
  walletId,
13010
13123
  origin,
13011
13124
  words
13012
- })) })
13125
+ }, passphrase === true ? { passphrase } : {})) })
13013
13126
  };
13014
13127
  } catch (error) {
13015
13128
  for (const wallet of wallets) wallet.entropy.fill(0);
@@ -13022,7 +13135,7 @@ zoo`.split("\n"));
13022
13135
  var PURPOSE_PROTECTION = 2;
13023
13136
  /**
13024
13137
  * The backup PRF from one platform ceremony: user-verified with a 32-byte `first` output, else
13025
- * `factor-unavailable`. The unused `second` output is wiped.
13138
+ * `passkey-prf-unsupported`. The unused `second` output is wiped.
13026
13139
  */
13027
13140
  function backupMaterialOf(result) {
13028
13141
  var _result$second, _result$first;
@@ -13030,7 +13143,7 @@ zoo`.split("\n"));
13030
13143
  if (!result.userVerified || ((_result$first = result.first) === null || _result$first === void 0 ? void 0 : _result$first.length) !== 32) {
13031
13144
  var _result$first2;
13032
13145
  (_result$first2 = result.first) === null || _result$first2 === void 0 || _result$first2.fill(0);
13033
- throw new KernelError("factor-unavailable", "the passkey returned no verified PRF output");
13146
+ throw new KernelError("passkey-prf-unsupported", "the passkey returned no verified PRF output");
13034
13147
  }
13035
13148
  return {
13036
13149
  kind: "passkey",
@@ -13046,7 +13159,7 @@ zoo`.split("\n"));
13046
13159
  */
13047
13160
  async function backupMaterial(ctx, factor, allowCredentials) {
13048
13161
  if (factor.kind === "password") return factor;
13049
- if (ctx.platform.passkey !== void 0 !== (factor.ceremony === "kernel")) throw new KernelError("factor-unavailable", "this platform runs passkey ceremonies elsewhere");
13162
+ if (ctx.platform.passkey !== void 0 !== (factor.ceremony === "kernel")) throw new KernelError("unsupported", "this platform runs passkey ceremonies elsewhere");
13050
13163
  if (factor.ceremony === "host") return factor;
13051
13164
  const passkey = requirePasskey(ctx.platform);
13052
13165
  const salts = { first: utf8ToBytes$1(factor.backupSalt) };
@@ -13214,6 +13327,21 @@ zoo`.split("\n"));
13214
13327
  * down in one commit so a torn restore can't leave half the secrets.
13215
13328
  */
13216
13329
  async function restoreBackup(ctx, params, requestSession) {
13330
+ const passphrases = /* @__PURE__ */ new Map();
13331
+ try {
13332
+ return await restoreWithPassphrases(ctx, params, requestSession, passphrases);
13333
+ } finally {
13334
+ var _params$passphrases;
13335
+ for (const passphrase of passphrases.values()) passphrase.fill(0);
13336
+ for (const entry of (_params$passphrases = params.passphrases) !== null && _params$passphrases !== void 0 ? _params$passphrases : []) entry.passphrase.fill(0);
13337
+ }
13338
+ }
13339
+ async function restoreWithPassphrases(ctx, params, requestSession, passphrases) {
13340
+ var _params$passphrases2;
13341
+ for (const entry of (_params$passphrases2 = params.passphrases) !== null && _params$passphrases2 !== void 0 ? _params$passphrases2 : []) {
13342
+ if (passphrases.has(entry.walletId)) throw new KernelError("invalid-input", `duplicate passphrase for wallet ${entry.walletId}`);
13343
+ passphrases.set(entry.walletId, normalizePassphrase(entry.passphrase));
13344
+ }
13217
13345
  const envelope = parseEnvelope(params.envelope);
13218
13346
  const credentials = envelope.factors.flatMap((f) => f.kind === "passkey" ? [b64$2.dec(f.credentialId)] : []);
13219
13347
  const bek = await bekFromFactor(ctx.platform, envelope, await backupMaterial(ctx, params.backupFactor, credentials));
@@ -13230,9 +13358,15 @@ zoo`.split("\n"));
13230
13358
  plaintext.fill(0);
13231
13359
  throw new KernelError("integrity", "backup: payload does not match header");
13232
13360
  }
13361
+ const flagged = new Set(header.wallets.filter((w) => w.passphrase === true).map((w) => w.walletId));
13362
+ for (const walletId of passphrases.keys()) if (!flagged.has(walletId)) {
13363
+ plaintext.fill(0);
13364
+ throw new KernelError("invalid-input", `wallet ${walletId} has no passphrase`);
13365
+ }
13233
13366
  const gated = gate(ctx, params.factor, requestSession);
13234
13367
  const records = [];
13235
13368
  const restored = [];
13369
+ const passphraseRequired = [];
13236
13370
  let committed = false;
13237
13371
  try {
13238
13372
  try {
@@ -13242,7 +13376,13 @@ zoo`.split("\n"));
13242
13376
  if (expected === void 0) throw new KernelError("integrity", "backup: wallet count mismatch");
13243
13377
  const words = mnemonicWords(wallet.entropy);
13244
13378
  if (words !== expected.words) throw new KernelError("integrity", "backup: entropy length does not match header");
13245
- const material = await walletMaterial(ctx.platform, wallet.entropy, wallet.origin, words);
13379
+ const passphrase = passphrases.get(expected.walletId);
13380
+ if (passphrase === void 0 && expected.passphrase === true) {
13381
+ if (!ctx.image.records.some((r) => r.kind === "entropy" && r.id === expected.walletId)) passphraseRequired.push(expected.walletId);
13382
+ continue;
13383
+ }
13384
+ const material = await walletMaterial(ctx.platform, wallet.entropy, passphrase, wallet.origin, words);
13385
+ if (passphrase !== void 0 && material.walletId !== expected.walletId) throw new KernelError("invalid-input", `passphrase does not match wallet ${expected.walletId}`);
13246
13386
  if (material.walletId !== expected.walletId || material.origin !== expected.origin) throw new KernelError("integrity", "backup: derived walletId does not match header");
13247
13387
  if (ctx.image.records.some((r) => r.kind === "entropy" && r.id === material.walletId)) continue;
13248
13388
  const backup = material.origin === "passkey" ? "passkey" : "none";
@@ -13255,6 +13395,7 @@ zoo`.split("\n"));
13255
13395
  committed = true;
13256
13396
  return {
13257
13397
  wallets: restored,
13398
+ passphraseRequired,
13258
13399
  session
13259
13400
  };
13260
13401
  } catch (error) {
@@ -13272,25 +13413,29 @@ zoo`.split("\n"));
13272
13413
  // packages/wallet-kernel/src/commands/secrets.ts
13273
13414
  init_utils$2();
13274
13415
  init_objectSpread2();
13275
- /** One-shot export: the mnemonic as UTF-8 bytes (the host wraps it in a wipeable buffer). */
13416
+ /**
13417
+ * One-shot export: the mnemonic as UTF-8 bytes, plus the NFKD passphrase bytes when the wallet has
13418
+ * one (the host wraps both in wipeable buffers).
13419
+ */
13276
13420
  async function exportMnemonic(ctx, params, requestSession) {
13277
13421
  const { dek } = ctx.session.require(requestSession);
13278
13422
  await verifyFactor(ctx.platform, ctx.image, params.verify, dek, corePromptFor(ctx.platform.keystore, "export-mnemonic"));
13279
13423
  const record = findRecord(ctx.image, "entropy", params.walletId);
13280
13424
  const header = parseEntropyHeader(record.header);
13281
- const entropy = openRecord(dek, record);
13425
+ const { entropy, passphrase } = openWalletSecret(dek, record);
13282
13426
  try {
13283
13427
  const exported = utf8ToBytes$1(mnemonicFromEntropy(entropy));
13284
13428
  if (header.backup !== "mnemonic") {
13285
13429
  const updated = encodeHeader(_objectSpread2(_objectSpread2({}, header), {}, { backup: "mnemonic" }));
13286
13430
  await ctx.commit([{
13287
13431
  op: "put-record",
13288
- record: sealRecord(ctx.platform, dek, "entropy", params.walletId, updated, new Uint8Array(entropy))
13432
+ record: sealRecord(ctx.platform, dek, "entropy", params.walletId, updated, walletSecretPlaintext(entropy, passphrase))
13289
13433
  }]);
13290
13434
  }
13291
- return exported;
13435
+ return _objectSpread2({ mnemonic: exported }, passphrase === void 0 ? {} : { passphrase: new Uint8Array(passphrase) });
13292
13436
  } finally {
13293
13437
  wipe(entropy);
13438
+ if (passphrase !== void 0) wipe(passphrase);
13294
13439
  }
13295
13440
  }
13296
13441
  /**
@@ -14661,7 +14806,7 @@ zoo`.split("\n"));
14661
14806
  }
14662
14807
  });
14663
14808
  };
14664
- string = (len, le = false) => validate$4(apply(createBytes(len, le), utf8$1), (value) => {
14809
+ string = (len, le = false) => validate$4(apply(createBytes(len, le), utf8$2), (value) => {
14665
14810
  if (typeof value !== "string") throw new Error(`expected string, got ${typeof value}`);
14666
14811
  return value;
14667
14812
  });
@@ -14843,8 +14988,1357 @@ zoo`.split("\n"));
14843
14988
  return ed25519.verify(signature, message, this.publicKeyRaw);
14844
14989
  }
14845
14990
  };
14846
- // packages/wallet-chains/dist/index.mjs
14991
+ // node_modules/.bun/@qntx+siwx@0.8.0/node_modules/@qntx/siwx/dist/message-B6snBU4B.mjs
14992
+ init_defineProperty();
14993
+ init_objectSpread2();
14994
+ var SYNTAX_MESSAGES = {
14995
+ InvalidUtf8: "invalid UTF-8",
14996
+ CarriageReturn: "CR not allowed",
14997
+ MissingPreamble: "missing preamble marker",
14998
+ MissingAccountSuffix: "missing account suffix",
14999
+ UnexpectedEof: "unexpected end of input",
15000
+ ExpectedBlankLine: "expected blank line",
15001
+ UnexpectedTrailing: "unexpected trailing content",
15002
+ ResourceSyntax: "resource line must start with '- '",
15003
+ InvalidEnvelope: "invalid off-chain message envelope"
15004
+ };
15005
+ function describe(info) {
15006
+ if (info.code === "MessageTooLarge") return `message exceeds maximum size of ${info.max} bytes, got ${info.length}`;
15007
+ if (info.code === "Syntax") return info.syntax === "MissingField" ? `invalid message syntax: missing ${info.field}` : `invalid message syntax: ${SYNTAX_MESSAGES[info.syntax]}`;
15008
+ if (info.code === "InvalidField") return `invalid ${info.field}: ${info.reason}`;
15009
+ if (info.code === "Mismatch") return `${info.field} mismatch: expected ${info.expected}, got ${JSON.stringify(info.actual)}`;
15010
+ if (info.code === "InvalidOrigin") return "invalid origin: not a serialized web origin";
15011
+ if (info.code === "Expired") return "message expired";
15012
+ if (info.code === "NotYetValid") return "message not yet valid";
15013
+ if (info.code === "IssuedAtTooOld") return "issued-at exceeds max age";
15014
+ if (info.code === "InvalidSignature") return `invalid signature: ${info.reason}`;
15015
+ if (info.code === "VerificationFailed") return "verification failed";
15016
+ if (info.code === "Unsupported") return `unsupported: ${info.reason}`;
15017
+ return `backend error: ${info.reason}`;
15018
+ }
15019
+ /** The single error type thrown by every library failure. */
15020
+ var SiwxError = class extends Error {
15021
+ constructor(info) {
15022
+ super(describe(info));
15023
+ _defineProperty(
15024
+ this,
15025
+ /** Structured payload; `code` matches the Rust `Error::code()`. */
15026
+ "info",
15027
+ void 0
15028
+ );
15029
+ this.name = "SiwxError";
15030
+ this.info = info;
15031
+ }
15032
+ /** Stable variant name for cross-language contract tests. */
15033
+ get code() {
15034
+ return this.info.code;
15035
+ }
15036
+ };
15037
+ /** `SiwxError` constructor shorthand for layout failures. */
15038
+ function syntaxError(syntax, field) {
15039
+ if (syntax === "MissingField") {
15040
+ if (field === void 0) throw new RangeError("MissingField requires a field");
15041
+ return new SiwxError({
15042
+ code: "Syntax",
15043
+ syntax,
15044
+ field
15045
+ });
15046
+ }
15047
+ return new SiwxError({
15048
+ code: "Syntax",
15049
+ syntax
15050
+ });
15051
+ }
15052
+ /** `SiwxError` constructor shorthand for a malformed field value. */
15053
+ function fieldError(field, reason) {
15054
+ return new SiwxError({
15055
+ code: "InvalidField",
15056
+ field,
15057
+ reason
15058
+ });
15059
+ }
15060
+ /** `SiwxError` constructor shorthand for a binding mismatch. */
15061
+ function mismatchError(field, expected, actual) {
15062
+ return new SiwxError({
15063
+ code: "Mismatch",
15064
+ field,
15065
+ expected,
15066
+ actual
15067
+ });
15068
+ }
15069
+ //! CAIP-10 `account_id`: `namespace ":" reference ":" address`.
15070
+ /** Every character matches — avoids spread-on-string for Hermes-safe lint. */
15071
+ function everyChar(s, test) {
15072
+ const pred = typeof test === "function" ? test : (c) => test.test(c);
15073
+ for (const c of s) if (!pred(c)) return false;
15074
+ return true;
15075
+ }
15076
+ /**
15077
+ * Validate and build an `account_id`.
15078
+ *
15079
+ * `namespace` is CAIP-2 `[-a-z0-9]{3,8}`; `reference` is `[-_a-zA-Z0-9]{1,32}`; `address` is
15080
+ * `[-.%a-zA-Z0-9]{1,128}`.
15081
+ *
15082
+ * @throws {SiwxError} `InvalidField` `chainId` for bad namespace/reference, `address` for a bad
15083
+ * address.
15084
+ */
15085
+ function createAccountId(namespace, reference, address) {
15086
+ if (namespace.length < 3 || namespace.length > 8 || !everyChar(namespace, /[a-z0-9-]/)) throw fieldError("chainId", "bad CAIP-2 namespace");
15087
+ if (reference.length === 0 || reference.length > 32 || !everyChar(reference, /[A-Za-z0-9_-]/)) throw fieldError("chainId", "bad CAIP-2 reference");
15088
+ if (address.length === 0 || address.length > 128 || !everyChar(address, (c) => /[A-Za-z0-9]/.test(c) || c === "-" || c === "." || c === "%")) throw fieldError("address", "bad CAIP-10 address");
15089
+ return Object.freeze({
15090
+ namespace,
15091
+ reference,
15092
+ address,
15093
+ id: `${namespace}:${reference}:${address}`
15094
+ });
15095
+ }
15096
+ //! Shared pieces of the CAIP-122 text layouts (eip4361 and SIWS): the
15097
+ //! preamble infix/suffix and the optional trailing tags in fixed ABNF order.
15098
+ var MID = " wants you to sign in with your ";
15099
+ var SUFFIX = " account:";
15100
+ /**
15101
+ * Parse the optional trailing tags in fixed ABNF order: `Expiration Time`, `Not Before`, `Request
15102
+ * ID`, `Resources` (with `- ` items). Each may appear at most once and only in this order.
15103
+ */
15104
+ function optionalTags(lines, start) {
15105
+ let i = start;
15106
+ let resources;
15107
+ const take = (tag) => {
15108
+ const line = lines[i];
15109
+ if (line !== void 0 && line.startsWith(tag)) {
15110
+ i++;
15111
+ return line.slice(tag.length);
15112
+ }
15113
+ };
15114
+ const expirationTime = take("Expiration Time: ");
15115
+ const notBefore = take("Not Before: ");
15116
+ const requestId = take("Request ID: ");
15117
+ if (lines[i] === "Resources:") {
15118
+ i++;
15119
+ const list = [];
15120
+ while (i < lines.length) {
15121
+ var _lines$i;
15122
+ const r = (_lines$i = lines[i]) !== null && _lines$i !== void 0 ? _lines$i : "";
15123
+ if (r.startsWith("- ")) {
15124
+ list.push(r.slice(2));
15125
+ i++;
15126
+ } else if (r.startsWith("-")) throw syntaxError("ResourceSyntax");
15127
+ else throw syntaxError("UnexpectedTrailing");
15128
+ }
15129
+ resources = list;
15130
+ }
15131
+ if (i !== lines.length) throw syntaxError("UnexpectedTrailing");
15132
+ return {
15133
+ expirationTime,
15134
+ notBefore,
15135
+ requestId,
15136
+ resources
15137
+ };
15138
+ }
15139
+ /** Maximum accepted signing-text size in bytes. */
15140
+ var MAX_MESSAGE_BYTES = 16384;
15141
+ //! RFC 3986 URI validation, matching Rust `iri-string` exactly:
15142
+ //! `URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]`,
15143
+ //! `authority = [ userinfo "@" ] host [ ":" port ]`, strict dec-octet
15144
+ //! (no leading zeros), IPv6 / IPvFuture / pct-encoding.
15145
+ var UNRESERVED = /[A-Za-z0-9._~-]/;
15146
+ var SUB_DELIM = /[!$&'()*+,;=]/;
15147
+ var HEX$1 = /[0-9A-Fa-f]/;
15148
+ function isScheme(s) {
15149
+ if (s.length === 0 || !/[A-Za-z]/.test(s.charAt(0))) return false;
15150
+ for (const c of s) if (!/[A-Za-z0-9+.-]/.test(c)) return false;
15151
+ return true;
15152
+ }
15153
+ /** `(unreserved / pct-encoded / sub-delims / ":" / "@")*`, ASCII only. */
15154
+ function everyPct(s, allowed) {
15155
+ for (let i = 0; i < s.length; i++) {
15156
+ const c = s.charAt(i);
15157
+ if (c === "%") {
15158
+ if (i + 2 >= s.length || !HEX$1.test(s.charAt(i + 1)) || !HEX$1.test(s.charAt(i + 2))) return false;
15159
+ i += 2;
15160
+ continue;
15161
+ }
15162
+ if (!allowed(c)) return false;
15163
+ }
15164
+ return true;
15165
+ }
15166
+ function isUserinfo(s) {
15167
+ return everyPct(s, (c) => UNRESERVED.test(c) || SUB_DELIM.test(c) || c === ":");
15168
+ }
15169
+ function isRegName(s) {
15170
+ return everyPct(s, (c) => UNRESERVED.test(c) || SUB_DELIM.test(c));
15171
+ }
15172
+ function isPcharString(s) {
15173
+ return everyPct(s, (c) => UNRESERVED.test(c) || SUB_DELIM.test(c) || c === ":" || c === "@");
15174
+ }
15175
+ /** Dec-octet: 0-255, no leading zeros (RFC 3986 strict). */
15176
+ function isDecOctet(s) {
15177
+ if (s.length === 0 || s.length > 3) return false;
15178
+ if (s.length > 1 && s.startsWith("0")) return false;
15179
+ for (const c of s) if (!/[0-9]/.test(c)) return false;
15180
+ return Number(s) <= 255;
15181
+ }
15182
+ function isIPv4(s) {
15183
+ const parts = s.split(".");
15184
+ return parts.length === 4 && parts.every(isDecOctet);
15185
+ }
15186
+ function isH16(s) {
15187
+ return s.length > 0 && s.length <= 4 && s.split("").every((c) => HEX$1.test(c));
15188
+ }
15189
+ /**
15190
+ * Count h16-equivalent groups in one half of an IPv6 literal (an IPv4 tail counts as two groups and
15191
+ * must be last).
15192
+ */
15193
+ function ipv6GroupCount(part) {
15194
+ if (part === "") return 0;
15195
+ let n = 0;
15196
+ const groups = part.split(":");
15197
+ for (const g of groups) {
15198
+ if (g === "") return -1;
15199
+ if (g.includes(".")) {
15200
+ if (g !== groups.at(-1) || !isIPv4(g)) return -1;
15201
+ n += 2;
15202
+ } else if (isH16(g)) n += 1;
15203
+ else return -1;
15204
+ }
15205
+ return n;
15206
+ }
15207
+ /** IPv6address per RFC 3986, with optional IPv4 tail and `::` compression. */
15208
+ function isIPv6(s) {
15209
+ var _halves$, _halves$2, _halves$3;
15210
+ const halves = s.split("::");
15211
+ if (halves.length > 2) return false;
15212
+ if (halves.length === 1) return ipv6GroupCount((_halves$ = halves[0]) !== null && _halves$ !== void 0 ? _halves$ : "") === 8;
15213
+ const hn = ipv6GroupCount((_halves$2 = halves[0]) !== null && _halves$2 !== void 0 ? _halves$2 : "");
15214
+ const tn = ipv6GroupCount((_halves$3 = halves[1]) !== null && _halves$3 !== void 0 ? _halves$3 : "");
15215
+ if (hn === -1 || tn === -1) return false;
15216
+ return hn + tn < 8;
15217
+ }
15218
+ function isIPvFuture(s) {
15219
+ var _m$;
15220
+ const m = /^[vV]([0-9A-Fa-f]+)\.(.*)$/.exec(s);
15221
+ if (m === null) return false;
15222
+ const tail = (_m$ = m[2]) !== null && _m$ !== void 0 ? _m$ : "";
15223
+ if (tail.length === 0) return false;
15224
+ for (const c of tail) if (!(UNRESERVED.test(c) || SUB_DELIM.test(c) || c === ":")) return false;
15225
+ return true;
15226
+ }
15227
+ /** `host = IP-literal / IPv4address / reg-name` (first-match-wins). */
15228
+ function isHost(s) {
15229
+ if (s.startsWith("[")) return s.endsWith("]") && (isIPv6(s.slice(1, -1)) || isIPvFuture(s.slice(1, -1)));
15230
+ if (isIPv4(s)) return true;
15231
+ return isRegName(s);
15232
+ }
15233
+ /** `authority = [ userinfo "@" ] host [ ":" port ]`. */
15234
+ function isAuthority(s) {
15235
+ let rest = s;
15236
+ const at = rest.lastIndexOf("@");
15237
+ if (at !== -1) {
15238
+ if (rest.indexOf("@") !== at) return false;
15239
+ if (!isUserinfo(rest.slice(0, at))) return false;
15240
+ rest = rest.slice(at + 1);
15241
+ }
15242
+ let host = rest;
15243
+ let port = "";
15244
+ if (rest.startsWith("[")) {
15245
+ const end = rest.indexOf("]");
15246
+ if (end === -1) return false;
15247
+ host = rest.slice(0, end + 1);
15248
+ const after = rest.slice(end + 1);
15249
+ if (after !== "") {
15250
+ if (!after.startsWith(":")) return false;
15251
+ port = after.slice(1);
15252
+ }
15253
+ } else {
15254
+ const colon = rest.lastIndexOf(":");
15255
+ if (colon !== -1) {
15256
+ host = rest.slice(0, colon);
15257
+ port = rest.slice(colon + 1);
15258
+ if (host.includes(":")) return false;
15259
+ }
15260
+ }
15261
+ if (port !== "" && !port.split("").every((c) => /[0-9]/.test(c))) return false;
15262
+ return isHost(host);
15263
+ }
15264
+ /** `path` characters: each segment is `*pchar`. */
15265
+ function isPath$1(s) {
15266
+ for (const seg of s.split("/")) if (!isPcharString(seg)) return false;
15267
+ return true;
15268
+ }
15269
+ /** `query` / `fragment`: `*( pchar / "/" / "?" )`. */
15270
+ function isQueryOrFragment(s) {
15271
+ return everyPct(s, (c) => UNRESERVED.test(c) || SUB_DELIM.test(c) || c === ":" || c === "@" || c === "/" || c === "?");
15272
+ }
15273
+ /** RFC 3986 `URI` (absolute, with scheme). */
15274
+ function isUri(s) {
15275
+ const hash = s.indexOf("#");
15276
+ if (hash !== -1 && s.includes("#", hash + 1)) return false;
15277
+ let rest = s;
15278
+ let fragment;
15279
+ if (hash !== -1) {
15280
+ fragment = rest.slice(hash + 1);
15281
+ rest = rest.slice(0, hash);
15282
+ }
15283
+ const q = rest.indexOf("?");
15284
+ let query;
15285
+ if (q !== -1) {
15286
+ query = rest.slice(q + 1);
15287
+ rest = rest.slice(0, q);
15288
+ }
15289
+ const colon = rest.indexOf(":");
15290
+ if (colon === -1) return false;
15291
+ if (!isScheme(rest.slice(0, colon))) return false;
15292
+ let hier = rest.slice(colon + 1);
15293
+ if (hier.startsWith("//")) {
15294
+ hier = hier.slice(2);
15295
+ const slash = hier.indexOf("/");
15296
+ const authority = slash === -1 ? hier : hier.slice(0, slash);
15297
+ const path = slash === -1 ? "" : hier.slice(slash);
15298
+ if (!isAuthority(authority)) return false;
15299
+ if (!isPath$1(path)) return false;
15300
+ } else if (!isPath$1(hier)) return false;
15301
+ if (query !== void 0 && !isQueryOrFragment(query)) return false;
15302
+ if (fragment !== void 0 && !isQueryOrFragment(fragment)) return false;
15303
+ return true;
15304
+ }
15305
+ //! Lexical RFC 3339 `date-time` + instant, mirroring Rust `Timestamp`.
15306
+ var SHAPE = /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/;
15307
+ /** Days since 1970-01-01 for a proleptic-Gregorian y/m/d (Hinnant's algorithm). */
15308
+ function daysFromCivil(y, m, d) {
15309
+ const yy = m <= 2 ? y - 1 : y;
15310
+ const era = Math.floor((yy >= 0 ? yy : yy - 399) / 400);
15311
+ const yoe = yy - era * 400;
15312
+ const doy = Math.floor((153 * (m > 2 ? m - 3 : m + 9) + 2) / 5) + d - 1;
15313
+ const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;
15314
+ return era * 146097 + doe - 719468;
15315
+ }
15316
+ function daysInMonth(year, month) {
15317
+ var _ref;
15318
+ return (_ref = [
15319
+ 31,
15320
+ year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28,
15321
+ 31,
15322
+ 30,
15323
+ 31,
15324
+ 30,
15325
+ 31,
15326
+ 31,
15327
+ 30,
15328
+ 31,
15329
+ 30,
15330
+ 31
15331
+ ][month - 1]) !== null && _ref !== void 0 ? _ref : 0;
15332
+ }
15333
+ /**
15334
+ * Parse an RFC 3339 `date-time`; `undefined` when invalid.
15335
+ *
15336
+ * Requires `T`/`t` and `Z`/`z`/`±HH:MM`; optional fraction; real calendar validity (Feb 30
15337
+ * rejected); leap second `:60` rejected like Rust `time`.
15338
+ */
15339
+ function parseTimestamp(s) {
15340
+ const m = SHAPE.exec(s);
15341
+ if (m === null) return;
15342
+ const [, ys, mos, ds, hs, mis, ss, frac, tz] = m;
15343
+ const year = Number(ys);
15344
+ const month = Number(mos);
15345
+ const day = Number(ds);
15346
+ const hour = Number(hs);
15347
+ const minute = Number(mis);
15348
+ const second = Number(ss);
15349
+ if (month < 1 || month > 12) return;
15350
+ if (day < 1 || day > daysInMonth(year, month)) return;
15351
+ if (hour > 23 || minute > 59 || second > 59) return;
15352
+ let ms = daysFromCivil(year, month, day) * 864e5 + hour * 36e5 + minute * 6e4 + second * 1e3;
15353
+ if (frac !== void 0 && frac.length > 1) ms += Number(frac.slice(1, 4).padEnd(3, "0"));
15354
+ if (tz !== void 0 && tz !== "Z" && tz !== "z") {
15355
+ const oh = Number(tz.slice(1, 3));
15356
+ const om = Number(tz.slice(4, 6));
15357
+ if (oh > 23 || om > 59) return;
15358
+ const off = (oh * 60 + om) * 6e4;
15359
+ ms += tz.startsWith("+") ? -off : off;
15360
+ }
15361
+ if (!Number.isFinite(ms)) return;
15362
+ return {
15363
+ lexeme: s,
15364
+ epochMs: Math.trunc(ms)
15365
+ };
15366
+ }
15367
+ //! Strict UTF-8 helpers.
15368
+ //!
15369
+ //! `TextEncoder`/`TextDecoder` exist on every supported platform (Node,
15370
+ //! browsers, Hermes). Decoding must reject exactly what Rust
15371
+ //! `str::from_utf8` rejects — overlongs, surrogates, > U+10FFFF,
15372
+ //! truncated sequences — so `fatal: true` is used (which follows the
15373
+ //! WHATWG fatal algorithm and rejects all of those).
15374
+ var encoder$1 = new TextEncoder();
15375
+ var fatalDecoder = new TextDecoder("utf-8", { fatal: true });
15376
+ /** Encode `text` as UTF-8 bytes. */
15377
+ function utf8Encode(text) {
15378
+ return encoder$1.encode(text);
15379
+ }
15380
+ /** Decode `bytes` as strict UTF-8; `undefined` on any invalid sequence. */
15381
+ function utf8Decode(bytes) {
15382
+ try {
15383
+ return fatalDecoder.decode(bytes);
15384
+ } catch (_unused2) {
15385
+ return;
15386
+ }
15387
+ }
15388
+ /** UTF-8 byte length of `text` (JS string length counts UTF-16 code units). */
15389
+ function utf8ByteLength(text) {
15390
+ return encoder$1.encode(text).length;
15391
+ }
15392
+ //! CAIP-122 abstract data model: lexical `MessageFields` and the
15393
+ //! validated `Message` produced by `createMessage` (single validation
15394
+ //! path, same check order as Rust `Message::new`).
15395
+ var STATEMENT_CHARS = /* @__PURE__ */ new Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;= ");
15396
+ function isCaip10Address(s) {
15397
+ if (s.length === 0 || s.length > 128) return false;
15398
+ for (const c of s) if (!/[A-Za-z0-9]/.test(c) && c !== "-" && c !== "." && c !== "%") return false;
15399
+ return true;
15400
+ }
15401
+ /**
15402
+ * Validate `fields` and return a frozen [`Message`].
15403
+ *
15404
+ * Check order (as Rust `Message::new`): scheme, domain, address, statement, uri, version, chainId,
15405
+ * nonce, issuedAt, expirationTime, notBefore, requestId, resources.
15406
+ *
15407
+ * @throws {SiwxError} `InvalidField` naming the first invalid field.
15408
+ */
15409
+ function createMessage(fields) {
15410
+ if (fields.scheme !== void 0 && !isScheme(fields.scheme)) throw fieldError("scheme", "not an RFC 3986 scheme");
15411
+ if (fields.domain.length === 0) throw fieldError("domain", "empty");
15412
+ if (fields.domain.includes("@")) throw fieldError("domain", "userinfo not allowed");
15413
+ if (fields.domain.startsWith(":")) throw fieldError("domain", "empty host");
15414
+ if (!isAuthority(fields.domain)) throw fieldError("domain", "not an RFC 3986 authority");
15415
+ if (!isCaip10Address(fields.address)) throw fieldError("address", fields.address.length === 0 || fields.address.length > 128 ? "expected 1..=128 characters" : "bad CAIP-10 charset");
15416
+ if (fields.statement !== void 0) {
15417
+ if (utf8ByteLength(fields.statement) > 4096) throw fieldError("statement", "exceeds maximum size");
15418
+ for (const c of fields.statement) if (!STATEMENT_CHARS.has(c)) throw fieldError("statement", "must be RFC 3986 reserved / unreserved / SP");
15419
+ }
15420
+ checkUri(fields.uri, "uri");
15421
+ if (fields.version !== "1") throw fieldError("version", "must be \"1\"");
15422
+ if (fields.chainId.length === 0) throw fieldError("chainId", "empty");
15423
+ if (fields.chainId.length > 64) throw fieldError("chainId", "exceeds 64 characters");
15424
+ for (const c of fields.chainId) if (!/[A-Za-z0-9]/.test(c) && c !== "-" && c !== "_" && c !== ":") throw fieldError("chainId", "bad charset");
15425
+ if (fields.nonce.length < 8) throw fieldError("nonce", "too short");
15426
+ for (const c of fields.nonce) if (!/[A-Za-z0-9]/.test(c)) throw fieldError("nonce", "not ASCII alphanumeric");
15427
+ if (parseTimestamp(fields.issuedAt) === void 0) throw fieldError("issuedAt", "not an RFC 3339 date-time");
15428
+ if (fields.expirationTime !== void 0 && parseTimestamp(fields.expirationTime) === void 0) throw fieldError("expirationTime", "not an RFC 3339 date-time");
15429
+ if (fields.notBefore !== void 0 && parseTimestamp(fields.notBefore) === void 0) throw fieldError("notBefore", "not an RFC 3339 date-time");
15430
+ if (fields.requestId !== void 0) {
15431
+ if (utf8ByteLength(fields.requestId) > 128) throw fieldError("requestId", "exceeds maximum size");
15432
+ if (!isPcharString(fields.requestId)) throw fieldError("requestId", "must be RFC 3986 *pchar");
15433
+ }
15434
+ if (fields.resources !== void 0) {
15435
+ if (fields.resources.length > 32) throw fieldError("resources", "too many");
15436
+ for (const uri of fields.resources) checkUri(uri, "resources");
15437
+ }
15438
+ const out = _objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2({
15439
+ domain: fields.domain,
15440
+ address: fields.address,
15441
+ uri: fields.uri,
15442
+ version: fields.version,
15443
+ chainId: fields.chainId,
15444
+ nonce: fields.nonce,
15445
+ issuedAt: fields.issuedAt
15446
+ }, fields.scheme === void 0 ? {} : { scheme: fields.scheme }), fields.statement === void 0 ? {} : { statement: fields.statement }), fields.expirationTime === void 0 ? {} : { expirationTime: fields.expirationTime }), fields.notBefore === void 0 ? {} : { notBefore: fields.notBefore }), fields.requestId === void 0 ? {} : { requestId: fields.requestId }), fields.resources === void 0 ? {} : { resources: fields.resources });
15447
+ return Object.freeze(out);
15448
+ }
15449
+ function checkUri(uri, field) {
15450
+ if (uri.length === 0) throw fieldError(field, "empty");
15451
+ if (utf8ByteLength(uri) > 2048) throw fieldError(field, "exceeds maximum size");
15452
+ if (!isUri(uri)) throw fieldError(field, "not an RFC 3986 URI");
15453
+ }
15454
+ // node_modules/.bun/@qntx+siwx@0.8.0/node_modules/@qntx/siwx/dist/rolldown-runtime-D8jQpDG7.mjs
15455
+ var __defProp = Object.defineProperty;
15456
+ var __exportAll = (all, no_symbols) => {
15457
+ let target = {};
15458
+ for (var name in all) __defProp(target, name, {
15459
+ get: all[name],
15460
+ enumerable: true
15461
+ });
15462
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
15463
+ return target;
15464
+ };
15465
+ // node_modules/.bun/@qntx+siwx@0.8.0/node_modules/@qntx/siwx/dist/eip4361-Bf5VppSi.mjs
15466
+ init_objectSpread2();
15467
+ //! ERC-4361 signing-text layout: `format` and its strict inverse `parse`.
15468
+ //! For every accepted text `t`, `format(label, parse(t).message) === t`
15469
+ //! byte-for-byte.
15470
+ function takeTag(line, tag, field) {
15471
+ if (!line.startsWith(tag)) throw syntaxError("MissingField", field);
15472
+ return line.slice(tag.length);
15473
+ }
15474
+ /** Render `message` as an ERC-4361 signing text under `label`. */
15475
+ function format$2(label, message) {
15476
+ let out = "";
15477
+ if (message.scheme !== void 0) out += `${message.scheme}://`;
15478
+ out += `${message.domain + MID + label + SUFFIX}\n`;
15479
+ out += `${message.address}\n\n`;
15480
+ if (message.statement !== void 0) out += `${message.statement}\n`;
15481
+ out += "\n";
15482
+ out += `URI: ${message.uri}\n`;
15483
+ out += `Version: ${message.version}\n`;
15484
+ out += `Chain ID: ${message.chainId}\n`;
15485
+ out += `Nonce: ${message.nonce}\n`;
15486
+ out += `Issued At: ${message.issuedAt}`;
15487
+ if (message.expirationTime !== void 0) out += `\nExpiration Time: ${message.expirationTime}`;
15488
+ if (message.notBefore !== void 0) out += `\nNot Before: ${message.notBefore}`;
15489
+ if (message.requestId !== void 0) out += `\nRequest ID: ${message.requestId}`;
15490
+ if (message.resources !== void 0) {
15491
+ out += "\nResources:";
15492
+ for (const uri of message.resources) out += `\n- ${uri}`;
15493
+ }
15494
+ return out;
15495
+ }
15496
+ /** Parse `text` into a label + validated message. */
15497
+ function parse$1(text) {
15498
+ const byteLength = utf8ByteLength(text);
15499
+ if (byteLength > 16384) throw new SiwxError({
15500
+ code: "MessageTooLarge",
15501
+ length: byteLength,
15502
+ max: MAX_MESSAGE_BYTES
15503
+ });
15504
+ if (text.includes("\r")) throw syntaxError("CarriageReturn");
15505
+ const lines = text.split("\n");
15506
+ let i = 0;
15507
+ const next = () => {
15508
+ const l = lines[i++];
15509
+ if (l === void 0) throw syntaxError("UnexpectedEof");
15510
+ return l;
15511
+ };
15512
+ const preamble = next();
15513
+ const mid = preamble.indexOf(MID);
15514
+ if (mid === -1) throw syntaxError("MissingPreamble");
15515
+ const head = preamble.slice(0, mid);
15516
+ const tail = preamble.slice(mid + MID.length);
15517
+ if (!tail.endsWith(" account:")) throw syntaxError("MissingAccountSuffix");
15518
+ const label = tail.slice(0, -SUFFIX.length);
15519
+ if (label.length === 0) throw fieldError("label", "empty");
15520
+ let scheme;
15521
+ let domain;
15522
+ const proto = head.indexOf("://");
15523
+ if (proto === -1) domain = head;
15524
+ else {
15525
+ scheme = head.slice(0, proto);
15526
+ domain = head.slice(proto + 3);
15527
+ }
15528
+ const address = next();
15529
+ let blanks = 0;
15530
+ while (lines[i + blanks] === "") blanks++;
15531
+ let statement;
15532
+ if (blanks === 1) {
15533
+ i += 1;
15534
+ statement = next();
15535
+ if (next() !== "") throw syntaxError("ExpectedBlankLine");
15536
+ } else if (blanks === 2) i += 2;
15537
+ else if (blanks === 3) {
15538
+ i += 3;
15539
+ statement = "";
15540
+ } else throw syntaxError("ExpectedBlankLine");
15541
+ const uri = takeTag(next(), "URI: ", "uri");
15542
+ const version = takeTag(next(), "Version: ", "version");
15543
+ const chainId = takeTag(next(), "Chain ID: ", "chainId");
15544
+ const nonce = takeTag(next(), "Nonce: ", "nonce");
15545
+ const issuedAt = takeTag(next(), "Issued At: ", "issuedAt");
15546
+ const opt = optionalTags(lines, i);
15547
+ return {
15548
+ label,
15549
+ message: createMessage(_objectSpread2({
15550
+ scheme,
15551
+ domain,
15552
+ address,
15553
+ statement,
15554
+ uri,
15555
+ version,
15556
+ chainId,
15557
+ nonce,
15558
+ issuedAt
15559
+ }, opt))
15560
+ };
15561
+ }
15562
+ /** [`parseBytes`]: UTF-8 strictness then [`parse`]. */
15563
+ function parseBytes$1(bytes) {
15564
+ if (bytes.length > 16384) throw new SiwxError({
15565
+ code: "MessageTooLarge",
15566
+ length: bytes.length,
15567
+ max: MAX_MESSAGE_BYTES
15568
+ });
15569
+ const text = utf8Decode(bytes);
15570
+ if (text === void 0) throw syntaxError("InvalidUtf8");
15571
+ return parse$1(text);
15572
+ }
15573
+ /** [`parseBytes`] plus a required preamble `label`. */
15574
+ function parseLabeled(label, signed) {
15575
+ const parsed = parseBytes$1(signed);
15576
+ if (parsed.label !== label) throw mismatchError("label", label, parsed.label);
15577
+ return parsed.message;
15578
+ }
15579
+ // node_modules/.bun/@noble+hashes@2.4.0/node_modules/@noble/hashes/sha3.js
15580
+ init__u64();
15581
+ init_utils$2();
15582
+ init_defineProperty();
15583
+ var _0n$4 = BigInt(0);
15584
+ var _1n$3 = BigInt(1);
15585
+ var _2n$2 = BigInt(2);
15586
+ var _7n = BigInt(7);
15587
+ var _256n = BigInt(256);
15588
+ var _0x71n = BigInt(113);
15589
+ var SHA3_PI = [];
15590
+ var SHA3_ROTL = [];
15591
+ var _SHA3_IOTA = [];
15592
+ for (let round = 0, R = _1n$3, x = 1, y = 0; round < 24; round++) {
15593
+ [x, y] = [y, (2 * x + 3 * y) % 5];
15594
+ SHA3_PI.push(2 * (5 * y + x));
15595
+ SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
15596
+ let t = _0n$4;
15597
+ for (let j = 0; j < 7; j++) {
15598
+ R = (R << _1n$3 ^ (R >> _7n) * _0x71n) % _256n;
15599
+ if (R & _2n$2) t ^= _1n$3 << (_1n$3 << BigInt(j)) - _1n$3;
15600
+ }
15601
+ _SHA3_IOTA.push(t);
15602
+ }
15603
+ var IOTAS = split(_SHA3_IOTA, true);
15604
+ var SHA3_IOTA_H = IOTAS[0];
15605
+ var SHA3_IOTA_L = IOTAS[1];
15606
+ var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
15607
+ var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
15608
+ var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
15609
+ var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
15610
+ var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
15611
+ var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
15612
+ var B = /* @__PURE__ */ new Uint32Array(10);
15613
+ /**
15614
+ * `keccakf1600` internal permutation, additionally allows adjusting the round count.
15615
+ * @param s - 5x5 Keccak state encoded as 25 lanes split into 50 uint32 words
15616
+ * in this file's local little-endian lane-word order
15617
+ * @param rounds - number of rounds to execute
15618
+ * @throws On wrong argument types. {@link TypeError}
15619
+ * @throws On wrong argument ranges or values. {@link RangeError}
15620
+ * @throws If `rounds` is outside the supported `1..24` range. {@link Error}
15621
+ * @example
15622
+ * Permute a Keccak state with the default 24 rounds.
15623
+ * ```ts
15624
+ * keccakP(new Uint32Array(50));
15625
+ * ```
15626
+ */
15627
+ function keccakP(s, rounds = 24) {
15628
+ if (!(s instanceof Uint32Array)) throw new TypeError("\"s\" expected Uint32Array(50), got type=" + typeof s);
15629
+ if (s.length !== 50) throw new RangeError("\"s\" expected Uint32Array(50), got length=" + s.length);
15630
+ anumber$2(rounds, "rounds");
15631
+ if (rounds < 1 || rounds > 24) throw new Error("\"rounds\" expected integer 1..24");
15632
+ for (let round = 24 - rounds; round < 24; round++) {
15633
+ for (let x = 0; x < 10; x++) B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
15634
+ for (let x = 0; x < 10; x += 2) {
15635
+ const idx1 = (x + 8) % 10;
15636
+ const idx0 = (x + 2) % 10;
15637
+ const B0 = B[idx0];
15638
+ const B1 = B[idx0 + 1];
15639
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
15640
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
15641
+ for (let y = 0; y < 50; y += 10) {
15642
+ s[x + y] ^= Th;
15643
+ s[x + y + 1] ^= Tl;
15644
+ }
15645
+ }
15646
+ let curH = s[2];
15647
+ let curL = s[3];
15648
+ for (let t = 0; t < 24; t++) {
15649
+ const shift = SHA3_ROTL[t];
15650
+ const Th = rotlH(curH, curL, shift);
15651
+ const Tl = rotlL(curH, curL, shift);
15652
+ const PI = SHA3_PI[t];
15653
+ curH = s[PI];
15654
+ curL = s[PI + 1];
15655
+ s[PI] = Th;
15656
+ s[PI + 1] = Tl;
15657
+ }
15658
+ for (let y = 0; y < 50; y += 10) {
15659
+ const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3];
15660
+ s[y] ^= ~s[y + 2] & s[y + 4];
15661
+ s[y + 1] ^= ~s[y + 3] & s[y + 5];
15662
+ s[y + 2] ^= ~s[y + 4] & s[y + 6];
15663
+ s[y + 3] ^= ~s[y + 5] & s[y + 7];
15664
+ s[y + 4] ^= ~s[y + 6] & s[y + 8];
15665
+ s[y + 5] ^= ~s[y + 7] & s[y + 9];
15666
+ s[y + 6] ^= ~s[y + 8] & b0;
15667
+ s[y + 7] ^= ~s[y + 9] & b1;
15668
+ s[y + 8] ^= ~b0 & b2;
15669
+ s[y + 9] ^= ~b1 & b3;
15670
+ }
15671
+ s[0] ^= SHA3_IOTA_H[round];
15672
+ s[1] ^= SHA3_IOTA_L[round];
15673
+ }
15674
+ clean(B);
15675
+ }
15676
+ /**
15677
+ * Keccak sponge function.
15678
+ * @param blockLen - absorb/squeeze rate in bytes
15679
+ * @param suffix - domain separation suffix byte
15680
+ * @param outputLen - default digest length in bytes. This base sponge only
15681
+ * requires a non-negative integer; wrappers that need positive output
15682
+ * lengths must enforce that themselves.
15683
+ * @param enableXOF - whether XOF output is allowed
15684
+ * @param rounds - number of Keccak-f rounds
15685
+ * @example
15686
+ * Build a sponge state, absorb bytes, then finalize a digest.
15687
+ * ```ts
15688
+ * const hash = new Keccak(136, 0x06, 32);
15689
+ * hash.update(new Uint8Array([1, 2, 3]));
15690
+ * hash.digest();
15691
+ * ```
15692
+ */
15693
+ var Keccak = class Keccak {
15694
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
15695
+ _defineProperty(this, "state", void 0);
15696
+ _defineProperty(this, "pos", 0);
15697
+ _defineProperty(this, "posOut", 0);
15698
+ _defineProperty(this, "finished", false);
15699
+ _defineProperty(this, "state32", void 0);
15700
+ _defineProperty(this, "destroyed", false);
15701
+ _defineProperty(this, "blockLen", void 0);
15702
+ _defineProperty(this, "suffix", void 0);
15703
+ _defineProperty(this, "outputLen", void 0);
15704
+ _defineProperty(this, "canXOF", void 0);
15705
+ _defineProperty(this, "enableXOF", false);
15706
+ _defineProperty(this, "rounds", void 0);
15707
+ anumber$2(blockLen, "blockLen");
15708
+ anumber$2(suffix, "suffix");
15709
+ anumber$2(rounds, "rounds");
15710
+ abool$1(enableXOF, "enableXOF");
15711
+ this.blockLen = blockLen;
15712
+ this.suffix = suffix;
15713
+ this.outputLen = outputLen;
15714
+ this.enableXOF = enableXOF;
15715
+ this.canXOF = enableXOF;
15716
+ this.rounds = rounds;
15717
+ anumber$2(outputLen, "outputLen");
15718
+ if (!(0 < blockLen && blockLen < 200)) throw new Error("\"blockLen\" must be 1..199");
15719
+ this.state = /* @__PURE__ */ new Uint8Array(200);
15720
+ this.state32 = u32$1(this.state);
15721
+ }
15722
+ clone() {
15723
+ return this._cloneInto();
15724
+ }
15725
+ keccak() {
15726
+ swap32IfBE(this.state32);
15727
+ keccakP(this.state32, this.rounds);
15728
+ swap32IfBE(this.state32);
15729
+ this.posOut = 0;
15730
+ this.pos = 0;
15731
+ }
15732
+ update(data) {
15733
+ aexists(this);
15734
+ abytes$2(data);
15735
+ const { blockLen, state, state32 } = this;
15736
+ const len = data.length;
15737
+ const canUseU32 = blockLen % 4 === 0 && data.byteOffset % 4 === 0;
15738
+ const blockLen32 = blockLen / 4;
15739
+ const data32 = canUseU32 && len >= blockLen ? u32$1(data) : void 0;
15740
+ for (let pos = 0; pos < len;) {
15741
+ if (data32 !== void 0 && this.pos === 0 && pos % 4 === 0 && len - pos >= blockLen) {
15742
+ for (let i = 0, o = pos / 4; i < blockLen32; i++) state32[i] ^= data32[o + i];
15743
+ pos += blockLen;
15744
+ this.pos = blockLen;
15745
+ this.keccak();
15746
+ continue;
15747
+ }
15748
+ const take = Math.min(blockLen - this.pos, len - pos);
15749
+ for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++];
15750
+ if (this.pos === blockLen) this.keccak();
15751
+ }
15752
+ return this;
15753
+ }
15754
+ finish() {
15755
+ if (this.finished) return;
15756
+ this.finished = true;
15757
+ const { state, suffix, pos, blockLen } = this;
15758
+ state[pos] ^= suffix;
15759
+ if ((suffix & 128) !== 0 && pos === blockLen - 1) this.keccak();
15760
+ state[blockLen - 1] ^= 128;
15761
+ this.keccak();
15762
+ }
15763
+ writeInto(out) {
15764
+ aexists(this, false);
15765
+ abytes$2(out);
15766
+ this.finish();
15767
+ const bufferOut = this.state;
15768
+ const { blockLen } = this;
15769
+ for (let pos = 0, len = out.length; pos < len;) {
15770
+ if (this.posOut >= blockLen) this.keccak();
15771
+ const take = Math.min(blockLen - this.posOut, len - pos);
15772
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
15773
+ this.posOut += take;
15774
+ pos += take;
15775
+ }
15776
+ return out;
15777
+ }
15778
+ xofInto(out) {
15779
+ if (!this.enableXOF) throw new Error("XOF is not enabled");
15780
+ return this.writeInto(out);
15781
+ }
15782
+ xof(bytes) {
15783
+ anumber$2(bytes);
15784
+ return this.xofInto(new Uint8Array(bytes));
15785
+ }
15786
+ digestInto(out) {
15787
+ aoutput(out, this);
15788
+ if (this.finished) throw new Error("digest() was already called");
15789
+ this.writeInto(out.length === this.outputLen ? out : out.subarray(0, this.outputLen));
15790
+ this.destroy();
15791
+ }
15792
+ digest() {
15793
+ const out = new Uint8Array(this.outputLen);
15794
+ this.digestInto(out);
15795
+ return out;
15796
+ }
15797
+ destroy() {
15798
+ this.destroyed = true;
15799
+ clean(this.state);
15800
+ }
15801
+ _cloneInto(to) {
15802
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
15803
+ to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
15804
+ to.blockLen = blockLen;
15805
+ to.state32.set(this.state32);
15806
+ to.pos = this.pos;
15807
+ to.posOut = this.posOut;
15808
+ to.finished = this.finished;
15809
+ to.rounds = rounds;
15810
+ to.suffix = suffix;
15811
+ to.outputLen = outputLen;
15812
+ to.enableXOF = enableXOF;
15813
+ to.canXOF = this.canXOF;
15814
+ to.destroyed = this.destroyed;
15815
+ return to;
15816
+ }
15817
+ };
15818
+ var genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);
15819
+ /**
15820
+ * Keccak-256 hash function. Different from SHA3-256.
15821
+ * @param msg - message bytes to hash
15822
+ * @param opts - Reserved hash options.
15823
+ * @returns Digest bytes.
15824
+ * @example
15825
+ * Hash a message with Keccak-256.
15826
+ * ```ts
15827
+ * keccak_256(new Uint8Array([97, 98, 99]));
15828
+ * ```
15829
+ */
15830
+ var keccak_256 = /* @__PURE__ */ genKeccak(1, 136, 32);
15831
+ // node_modules/.bun/@qntx+siwx@0.8.0/node_modules/@qntx/siwx/dist/evm.mjs
15832
+ init_utils$2();
15833
+ init_secp256k1();
15834
+ init_utils$1();
15835
+ //! EIP-55 / EVM address + chain-id rules, matching `siwx::evm`.
15836
+ var HEX40 = /^[0-9a-fA-F]{40}$/;
15837
+ /** EIP-55 checksum spelling of a `0x`-prefixed 40-hex address. */
15838
+ function toChecksumAddress(address) {
15839
+ if (!address.startsWith("0x")) throw fieldError("address", "expected 0x + 40 hex");
15840
+ const body = address.slice(2);
15841
+ if (!HEX40.test(body)) throw fieldError("address", "expected 0x + 40 hex");
15842
+ const lower = body.toLowerCase();
15843
+ const hash = keccak_256(utf8Encode(lower));
15844
+ let out = "0x";
15845
+ for (let i = 0; i < 40; i++) {
15846
+ var _hash$Math$floor;
15847
+ const c = lower.charAt(i);
15848
+ const nibble = ((_hash$Math$floor = hash[Math.floor(i / 2)]) !== null && _hash$Math$floor !== void 0 ? _hash$Math$floor : 0) >> (i % 2 === 0 ? 4 : 0) & 15;
15849
+ out += /[a-f]/.test(c) && nibble >= 8 ? c.toUpperCase() : c;
15850
+ }
15851
+ return out;
15852
+ }
15853
+ var badAddress = () => fieldError("address", "expected 0x + 40 hex");
15854
+ /** Parse an EVM address to its 20 bytes under the canonical rule. */
15855
+ function parseEip55(address) {
15856
+ const bad = badAddress;
15857
+ if (!address.startsWith("0x")) throw bad();
15858
+ const hex = address.slice(2);
15859
+ if (!HEX40.test(hex)) throw bad();
15860
+ const hasLower = /[a-f]/.test(hex);
15861
+ const hasUpper = /[A-F]/.test(hex);
15862
+ if (hasLower && hasUpper && address !== toChecksumAddress(address)) throw fieldError("address", "bad EIP-55 checksum");
15863
+ return hexToBytes$3(hex);
15864
+ }
15865
+ /**
15866
+ * EVM `chain-id`: `[0-9]+`, no leading zero unless `"0"`, fits in `u64`.
15867
+ *
15868
+ * @throws {SiwxError} `InvalidField` `chainId`.
15869
+ */
15870
+ function parseEvmChainId(chainId) {
15871
+ if (chainId.length === 0) throw fieldError("chainId", "empty");
15872
+ if (!/^[0-9]+$/.test(chainId)) throw fieldError("chainId", "not decimal");
15873
+ if (chainId.length > 1 && chainId.startsWith("0")) throw fieldError("chainId", "leading zero");
15874
+ const value = BigInt(chainId);
15875
+ if (value > 18446744073709551615n) throw fieldError("chainId", "overflow");
15876
+ return value;
15877
+ }
15878
+ //! EIP-191 `personal_sign` verification.
15879
+ //!
15880
+ //! Decode order (cross-language contract, mirrored with Rust): length ≠
15881
+ //! 65 → `v ∉ {0,1,27,28}` → `r`/`s` equal to 0 or ≥ n → `s > n/2` (all
15882
+ //! `InvalidSignature`) → recovery failure or address mismatch →
15883
+ //! `VerificationFailed`.
15884
+ var N = secp256k1.Point.Fn.ORDER;
15885
+ var N_HALF = N / 2n;
15886
+ /** `keccak256("\x19Ethereum Signed Message:\n" + len + message)`. */
15887
+ function eip191Hash(message) {
15888
+ const prefix = utf8Encode(`\u0019Ethereum Signed Message:\n${message.length}`);
15889
+ const joined = new Uint8Array(prefix.length + message.length);
15890
+ joined.set(prefix);
15891
+ joined.set(message, prefix.length);
15892
+ return keccak_256(joined);
15893
+ }
15894
+ /** Verify a 65-byte `r‖s‖v` EIP-191 signature over `signed`. */
15895
+ function verifyEip191(message, signed, signature) {
15896
+ var _signature$;
15897
+ if (signature.length !== 65) throw new SiwxError({
15898
+ code: "InvalidSignature",
15899
+ reason: "EIP-191 signature must be 65 bytes"
15900
+ });
15901
+ const v = (_signature$ = signature[64]) !== null && _signature$ !== void 0 ? _signature$ : 0;
15902
+ if (v !== 0 && v !== 1 && v !== 27 && v !== 28) throw new SiwxError({
15903
+ code: "InvalidSignature",
15904
+ reason: "v must be 0, 1, 27 or 28"
15905
+ });
15906
+ const r = bytesToNumberBE(signature.subarray(0, 32));
15907
+ const s = bytesToNumberBE(signature.subarray(32, 64));
15908
+ if (r === 0n || r >= N || s === 0n || s >= N) throw new SiwxError({
15909
+ code: "InvalidSignature",
15910
+ reason: "r/s out of range"
15911
+ });
15912
+ if (s > N_HALF) throw new SiwxError({
15913
+ code: "InvalidSignature",
15914
+ reason: "high-s (EIP-2)"
15915
+ });
15916
+ const hash = eip191Hash(signed);
15917
+ let recovered;
15918
+ try {
15919
+ recovered = keccak_256(secp256k1.Signature.fromBytes(signature.subarray(0, 64), "compact").addRecoveryBit(v % 27).recoverPublicKey(hash).toBytes(false).subarray(1)).subarray(12);
15920
+ } catch (_unused) {
15921
+ throw new SiwxError({ code: "VerificationFailed" });
15922
+ }
15923
+ const expected = parseEip55(message.address);
15924
+ if (!equalBytes$2(recovered, expected)) throw new SiwxError({ code: "VerificationFailed" });
15925
+ }
15926
+ //! On-chain smart-account verification: the ERC-6492 universal validator via a
15927
+ //! deployless `eth_call`. Covers deployed ERC-1271 accounts, counterfactual
15928
+ //! ERC-6492 accounts and EOAs. Providers are injected; the library builds no
15929
+ //! transports and applies no timeouts — transport policy belongs to the
15930
+ //! provider owner.
15931
+ var BYTECODE = hexToBytes$2("608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572");
15932
+ /** Abi.encode(address signer, bytes32 hash, bytes signature). */
15933
+ function deploylessCalldata(signer, hash, signature) {
15934
+ const addr = hexToBytes$2(signer.slice(2));
15935
+ const word = 32;
15936
+ const out = new Uint8Array(BYTECODE.length + 96 + word + Math.ceil(signature.length / word) * word);
15937
+ const bc = BYTECODE;
15938
+ out.set(bc, 0);
15939
+ let o = bc.length;
15940
+ out.set(addr, o + (word - addr.length));
15941
+ o += word;
15942
+ out.set(hash, o);
15943
+ o += word;
15944
+ out.set(numberToBytesBE(BigInt(96), word), o);
15945
+ o += word;
15946
+ out.set(numberToBytesBE(BigInt(signature.length), word), o);
15947
+ out.set(signature, o + word);
15948
+ return out;
15949
+ }
15950
+ var malformed$1 = () => new SiwxError({
15951
+ code: "Backend",
15952
+ reason: "malformed eth_call result"
15953
+ });
15954
+ /**
15955
+ * Interpret a deployless validator `eth_call` result: `0x01` or a 32-byte word of zeros ending `01`
15956
+ * is valid; the same shapes ending `00` are `false`; anything else is malformed.
15957
+ */
15958
+ function decodeResult(hex) {
15959
+ const data = hex === "" || hex === "0x" ? /* @__PURE__ */ new Uint8Array(0) : hexToBytes$2(hex.slice(2));
15960
+ if (data.length === 1) {
15961
+ if (data[0] === 1) return true;
15962
+ if (data[0] === 0) return false;
15963
+ throw malformed$1();
15964
+ }
15965
+ if (data.length === 32) {
15966
+ for (let i = 0; i < 31; i++) if (data[i] !== 0) throw malformed$1();
15967
+ if (data[31] === 1) return true;
15968
+ if (data[31] === 0) return false;
15969
+ }
15970
+ throw malformed$1();
15971
+ }
15972
+ /** JSON-RPC code 3 (EIP-1474 execution reverted) ⇒ signature rejected. */
15973
+ var codeOf = (error) => typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
15974
+ function isRevert(error) {
15975
+ const code = codeOf(error);
15976
+ return typeof code === "number" && code === 3;
15977
+ }
15978
+ function backend$1() {
15979
+ return new SiwxError({
15980
+ code: "Backend",
15981
+ reason: "RPC request failed"
15982
+ });
15983
+ }
15984
+ var MAGIC = (() => {
15985
+ const m = /* @__PURE__ */ new Uint8Array(32);
15986
+ for (let i = 0; i < m.length; i++) m[i] = i % 2 === 0 ? 100 : 146;
15987
+ return m;
15988
+ })();
15989
+ /** True when `signature` ends with the ERC-6492 detection suffix. */
15990
+ function has6492MagicSuffix(signature) {
15991
+ if (signature.length < MAGIC.length) return false;
15992
+ for (let i = 0; i < MAGIC.length; i++) if (signature[signature.length - MAGIC.length + i] !== MAGIC[i]) return false;
15993
+ return true;
15994
+ }
15995
+ /** `eth_chainId` as a decimal number; malformed → `Backend`. */
15996
+ async function providerChainId(provider) {
15997
+ let result;
15998
+ try {
15999
+ result = await provider.request({ method: "eth_chainId" });
16000
+ } catch (_unused2) {
16001
+ throw backend$1();
16002
+ }
16003
+ if (typeof result !== "string" || !/^0x[0-9a-fA-F]+$/.test(result)) throw backend$1();
16004
+ return BigInt(result);
16005
+ }
16006
+ /**
16007
+ * Deployless `eth_call` against the vendored universal validator. `provider`'s chain id must
16008
+ * already equal the message chain id (the caller caches the binding).
16009
+ */
16010
+ async function verifyOnChain(provider, message, signed, signature) {
16011
+ parseEip55(message.address);
16012
+ const hash = eip191Hash(signed);
16013
+ const data = `0x${bytesToHex$3(deploylessCalldata(message.address, hash, signature))}`;
16014
+ let result;
16015
+ try {
16016
+ result = await provider.request({
16017
+ method: "eth_call",
16018
+ params: [{
16019
+ data,
16020
+ input: data
16021
+ }, "latest"]
16022
+ });
16023
+ } catch (error) {
16024
+ throw isRevert(error) ? new SiwxError({ code: "VerificationFailed" }) : backend$1();
16025
+ }
16026
+ if (typeof result !== "string" || !/^0x[0-9a-fA-F]*$/.test(result)) throw backend$1();
16027
+ if (!decodeResult(result)) throw new SiwxError({ code: "VerificationFailed" });
16028
+ }
16029
+ //! `@qntx/siwx/evm` — EIP-155 (`eip155`) namespace profile.
16030
+ //!
16031
+ //! `account()` emits the canonical EIP-55 checksum spelling, so
16032
+ //! lowercase / uppercase / checksummed spellings of the same address map
16033
+ //! to the same `AccountId`.
16034
+ var CHAIN_NAME = "Ethereum";
16035
+ var NAMESPACE = "eip155";
16036
+ function evmAccount(message) {
16037
+ parseEip55(message.address);
16038
+ parseEvmChainId(message.chainId);
16039
+ return createAccountId(NAMESPACE, message.chainId, toChecksumAddress(message.address));
16040
+ }
16041
+ /**
16042
+ * Ethereum (`eip155`) namespace. EIP-191 runs fully offline; a signature carrying the ERC-6492
16043
+ * magic suffix, or an EIP-191 failure on a chain with a configured provider, takes the on-chain
16044
+ * universal-validator path. Providers own all transport policy — the library applies no timeouts —
16045
+ * and `eth_chainId` is bound to the message chain id (cached per provider on success only) before
16046
+ * any `eth_call`.
16047
+ */
16048
+ function evm(options) {
16049
+ var _options$rpc;
16050
+ const rpc = (_options$rpc = options === null || options === void 0 ? void 0 : options.rpc) !== null && _options$rpc !== void 0 ? _options$rpc : {};
16051
+ const verifiedChains = /* @__PURE__ */ new Set();
16052
+ const providerFor = (chainId) => {
16053
+ const key = parseEvmChainId(chainId).toString(10);
16054
+ return rpc[key];
16055
+ };
16056
+ const onChain = async (message, signed, signature, eip191Err) => {
16057
+ const key = parseEvmChainId(message.chainId).toString(10);
16058
+ const provider = providerFor(message.chainId);
16059
+ if (provider === void 0) throw eip191Err !== null && eip191Err !== void 0 ? eip191Err : new SiwxError({
16060
+ code: "Unsupported",
16061
+ reason: "EIP-6492 requires RPC"
16062
+ });
16063
+ if (!verifiedChains.has(key)) {
16064
+ const rpcChain = await providerChainId(provider);
16065
+ if (rpcChain !== parseEvmChainId(message.chainId)) throw new SiwxError({
16066
+ code: "Mismatch",
16067
+ field: "chainId",
16068
+ expected: key,
16069
+ actual: rpcChain.toString()
16070
+ });
16071
+ verifiedChains.add(key);
16072
+ }
16073
+ await verifyOnChain(provider, message, signed, signature);
16074
+ };
16075
+ return {
16076
+ namespace: NAMESPACE,
16077
+ label: CHAIN_NAME,
16078
+ account: evmAccount,
16079
+ format(message) {
16080
+ evmAccount(message);
16081
+ return format$2(CHAIN_NAME, message);
16082
+ },
16083
+ parse(signed) {
16084
+ return parseLabeled(CHAIN_NAME, signed);
16085
+ },
16086
+ verify: async (message, signed, signature) => {
16087
+ if (has6492MagicSuffix(signature)) {
16088
+ await onChain(message, signed, signature, void 0);
16089
+ return;
16090
+ }
16091
+ try {
16092
+ verifyEip191(message, signed, signature);
16093
+ } catch (error) {
16094
+ if (error instanceof SiwxError && providerFor(message.chainId) !== void 0) {
16095
+ await onChain(message, signed, signature, error);
16096
+ return;
16097
+ }
16098
+ throw error;
16099
+ }
16100
+ }
16101
+ };
16102
+ }
16103
+ // node_modules/.bun/@qntx+siwx@0.8.0/node_modules/@qntx/siwx/dist/svm.mjs
16104
+ init_utils$1();
16105
+ init_base();
16106
+ init_objectSpread2();
16107
+ /** Solana address rules: canonical on-curve Ed25519 key in base58. */
16108
+ /**
16109
+ * Decode `address` as a base58 (Bitcoin alphabet) string of 32–44 chars that decodes to exactly 32
16110
+ * bytes.
16111
+ *
16112
+ * @throws {SiwxError} `InvalidField` `address`.
16113
+ */
16114
+ function addressBytes(address) {
16115
+ if (address.length < 32 || address.length > 44) throw fieldError("address", "expected 32–44 base58 chars");
16116
+ let bytes;
16117
+ try {
16118
+ bytes = base58.decode(address);
16119
+ } catch (_unused) {
16120
+ throw fieldError("address", "invalid base58");
16121
+ }
16122
+ if (bytes.length !== 32) throw fieldError("address", "expected 32 bytes");
16123
+ return bytes;
16124
+ }
16125
+ /**
16126
+ * The canonical, non-identity, prime-order-subgroup Ed25519 point for `bytes` (decompress →
16127
+ * recompress byte equality proves canonicity).
16128
+ *
16129
+ * @throws {SiwxError} `InvalidField` `address`.
16130
+ */
16131
+ function canonicalPoint(bytes) {
16132
+ let point;
16133
+ try {
16134
+ point = ed25519.Point.fromBytes(bytes);
16135
+ } catch (_unused2) {
16136
+ throw fieldError("address", "invalid Ed25519 pubkey");
16137
+ }
16138
+ if (point.equals(ed25519.Point.ZERO)) throw fieldError("address", "identity pubkey");
16139
+ if (!point.isTorsionFree()) throw fieldError("address", "not in the prime-order subgroup");
16140
+ if (!equalBytes$2(point.toBytes(), bytes)) throw fieldError("address", "non-canonical pubkey");
16141
+ }
16142
+ /**
16143
+ * Validate that `address` is a canonical, non-identity, prime-order-subgroup Ed25519 verifying key
16144
+ * in base58 form.
16145
+ *
16146
+ * @throws {SiwxError} `InvalidField` `address`.
16147
+ */
16148
+ function validateAddress(address) {
16149
+ canonicalPoint(addressBytes(address));
16150
+ }
16151
+ ed25519.Point.CURVE().n;
16152
+ ed25519.Point;
16153
+ /** SIWS (Sign-In-With-Solana) text layout — Phantom ABNF, LF only. */
16154
+ var siws_exports = /* @__PURE__ */ __exportAll({
16155
+ format: () => format$1,
16156
+ parse: () => parse,
16157
+ parseBytes: () => parseBytes
16158
+ });
16159
+ var LABEL = "Solana";
16160
+ /**
16161
+ * Format `message` as a SIWS signing text.
16162
+ *
16163
+ * @throws {SiwxError} `InvalidField` `scheme` (SIWS has none) or `statement` (empty).
16164
+ */
16165
+ function format$1(message) {
16166
+ if (message.scheme !== void 0) throw new SiwxError({
16167
+ code: "InvalidField",
16168
+ field: "scheme",
16169
+ reason: "not supported by SIWS"
16170
+ });
16171
+ if (message.statement !== void 0) {
16172
+ if (message.statement === "") throw new SiwxError({
16173
+ code: "InvalidField",
16174
+ field: "statement",
16175
+ reason: "empty"
16176
+ });
16177
+ if (message.statement.startsWith("URI: ")) throw new SiwxError({
16178
+ code: "InvalidField",
16179
+ field: "statement",
16180
+ reason: "ambiguous with the URI: tag"
16181
+ });
16182
+ }
16183
+ let out = `${message.domain}${MID}${LABEL}${SUFFIX}\n${message.address}`;
16184
+ if (message.statement !== void 0) out += `\n\n${message.statement}`;
16185
+ out += `\n\nURI: ${message.uri}`;
16186
+ out += `\nVersion: ${message.version}`;
16187
+ out += `\nChain ID: ${message.chainId}`;
16188
+ out += `\nNonce: ${message.nonce}`;
16189
+ out += `\nIssued At: ${message.issuedAt}`;
16190
+ if (message.expirationTime !== void 0) out += `\nExpiration Time: ${message.expirationTime}`;
16191
+ if (message.notBefore !== void 0) out += `\nNot Before: ${message.notBefore}`;
16192
+ if (message.requestId !== void 0) out += `\nRequest ID: ${message.requestId}`;
16193
+ if (message.resources !== void 0) {
16194
+ out += "\nResources:";
16195
+ for (const r of message.resources) out += `\n- ${r}`;
16196
+ }
16197
+ return out;
16198
+ }
16199
+ var missingUri = () => syntaxError("MissingField", "uri");
16200
+ /** The optional statement and the gap up to the required `URI: ` line. */
16201
+ function statementThenFields(lines, i) {
16202
+ if (i.v >= lines.length) throw missingUri();
16203
+ if (lines[i.v] !== "") throw syntaxError("ExpectedBlankLine");
16204
+ i.v++;
16205
+ const l = lines[i.v];
16206
+ if (l === void 0) throw missingUri();
16207
+ if (l === "") throw syntaxError("ExpectedBlankLine");
16208
+ if (l.startsWith("URI: ")) return;
16209
+ i.v++;
16210
+ const after = lines[i.v];
16211
+ if (after === void 0) throw missingUri();
16212
+ if (after !== "") throw syntaxError("ExpectedBlankLine");
16213
+ i.v++;
16214
+ return l;
16215
+ }
16216
+ /**
16217
+ * Parse `text` into a validated message; the preamble label must be exactly `"Solana"`.
16218
+ *
16219
+ * @throws {SiwxError} `Syntax`, `Mismatch` `label`, or `InvalidField`.
16220
+ */
16221
+ function parse(text) {
16222
+ const byteLength = utf8ByteLength(text);
16223
+ if (byteLength > 16384) throw new SiwxError({
16224
+ code: "MessageTooLarge",
16225
+ length: byteLength,
16226
+ max: MAX_MESSAGE_BYTES
16227
+ });
16228
+ if (text.includes("\r")) throw syntaxError("CarriageReturn");
16229
+ if (text.endsWith("\n")) throw syntaxError("UnexpectedTrailing");
16230
+ const lines = text.split("\n");
16231
+ const idx = { v: 0 };
16232
+ const preamble = lines[idx.v++];
16233
+ if (preamble === void 0) throw syntaxError("UnexpectedEof");
16234
+ const mid = preamble.indexOf(MID);
16235
+ if (mid === -1) throw syntaxError("MissingPreamble");
16236
+ const domain = preamble.slice(0, mid);
16237
+ const tail = preamble.slice(mid + MID.length);
16238
+ if (!tail.endsWith(" account:")) throw syntaxError("MissingAccountSuffix");
16239
+ const label = tail.slice(0, tail.length - SUFFIX.length);
16240
+ if (label !== LABEL) throw new SiwxError({
16241
+ code: "Mismatch",
16242
+ field: "label",
16243
+ expected: LABEL,
16244
+ actual: label
16245
+ });
16246
+ const address = lines[idx.v++];
16247
+ if (address === void 0) throw syntaxError("UnexpectedEof");
16248
+ const statement = statementThenFields(lines, idx);
16249
+ const take = (tag, field) => {
16250
+ const line = lines[idx.v];
16251
+ if (line === void 0 || !line.startsWith(tag)) throw syntaxError("MissingField", field);
16252
+ idx.v++;
16253
+ return line.slice(tag.length);
16254
+ };
16255
+ const uri = take("URI: ", "uri");
16256
+ const version = take("Version: ", "version");
16257
+ const chainId = take("Chain ID: ", "chainId");
16258
+ const nonce = take("Nonce: ", "nonce");
16259
+ const issuedAt = take("Issued At: ", "issuedAt");
16260
+ const tail4 = optionalTags(lines, idx.v);
16261
+ return createMessage(_objectSpread2(_objectSpread2({
16262
+ domain,
16263
+ address
16264
+ }, statement === void 0 ? {} : { statement }), {}, {
16265
+ uri,
16266
+ version,
16267
+ chainId,
16268
+ nonce,
16269
+ issuedAt
16270
+ }, tail4));
16271
+ }
16272
+ /**
16273
+ * {@link parse} over raw bytes: size check, strict UTF-8 (`InvalidUtf8`), then parse.
16274
+ *
16275
+ * @throws {SiwxError}
16276
+ */
16277
+ function parseBytes(bytes) {
16278
+ if (bytes.length > 16384) throw new SiwxError({
16279
+ code: "MessageTooLarge",
16280
+ length: bytes.length,
16281
+ max: MAX_MESSAGE_BYTES
16282
+ });
16283
+ const text = utf8Decode(bytes);
16284
+ if (text === void 0) throw syntaxError("InvalidUtf8");
16285
+ return parse(text);
16286
+ }
16287
+ new Uint8Array([255, ...utf8Encode("solana offchain")]);
16288
+ // packages/wallet-chains/dist/src-8NZeEnrW.mjs
14847
16289
  init_defineProperty();
16290
+ var PREAMBLE = " wants you to sign in with your ";
16291
+ var OPTIONAL_KEYS = [
16292
+ "scheme",
16293
+ "statement",
16294
+ "expirationTime",
16295
+ "notBefore",
16296
+ "requestId"
16297
+ ];
16298
+ var plainFields = (message) => {
16299
+ const { domain, address, uri, version, chainId, nonce, issuedAt, resources } = message;
16300
+ const fields = {
16301
+ domain,
16302
+ address,
16303
+ uri,
16304
+ version,
16305
+ chainId,
16306
+ nonce,
16307
+ issuedAt
16308
+ };
16309
+ for (const key of OPTIONAL_KEYS) {
16310
+ const value = message[key];
16311
+ if (value !== void 0) fields[key] = value;
16312
+ }
16313
+ if (resources !== void 0) fields.resources = [...resources];
16314
+ return fields;
16315
+ };
16316
+ var parseValid = (text, family) => {
16317
+ if (family === "evm") {
16318
+ const ns = evm();
16319
+ const message = ns.parse(new TextEncoder().encode(text));
16320
+ ns.account(message);
16321
+ return plainFields(message);
16322
+ }
16323
+ const message = siws_exports.parse(text);
16324
+ validateAddress(message.address);
16325
+ return plainFields(message);
16326
+ };
16327
+ /**
16328
+ * Finds a Sign-In with X message in `text` for the chain `family`. `undefined` when the text has no
16329
+ * sign-in preamble; `malformed` when it has one but is not a conforming message for the family
16330
+ * (ERC-4361: wallets should warn about that shape).
16331
+ */
16332
+ function parseSignIn(text, family) {
16333
+ try {
16334
+ return {
16335
+ status: "valid",
16336
+ fields: parseValid(text, family)
16337
+ };
16338
+ } catch (_unused) {
16339
+ return text.includes(PREAMBLE) ? { status: "malformed" } : void 0;
16340
+ }
16341
+ }
14848
16342
  var ChainError = class extends Error {
14849
16343
  constructor(code, message) {
14850
16344
  super(message);
@@ -14853,7 +16347,7 @@ zoo`.split("\n"));
14853
16347
  this.code = code;
14854
16348
  }
14855
16349
  };
14856
- // packages/wallet-chains/dist/account-ref-C2qrDbVT.mjs
16350
+ // packages/wallet-chains/dist/account-ref-D2rW_qlI.mjs
14857
16351
  var isRecord$3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
14858
16352
  var isAccountRef = (value) => {
14859
16353
  if (!isRecord$3(value) || typeof value["kind"] !== "string") return false;
@@ -14886,7 +16380,7 @@ zoo`.split("\n"));
14886
16380
  */
14887
16381
  function abigint(n, title = "value") {
14888
16382
  if (typeof n !== "bigint") throw new TypeError(`"${title}" expected bigint, got type=${typeof n}`);
14889
- if (n < _0n$4) throw new RangeError(`"${title}" expected non-negative bigint, got ${n}`);
16383
+ if (n < _0n$3) throw new RangeError(`"${title}" expected non-negative bigint, got ${n}`);
14890
16384
  return n;
14891
16385
  }
14892
16386
  function aarray(item, title, inner = () => {}) {
@@ -15094,7 +16588,7 @@ zoo`.split("\n"));
15094
16588
  }
15095
16589
  return res;
15096
16590
  }
15097
- var Point, Fn, CURVE_ORDER, _0n$4, _2n$2, hasEven, isBytes, concatBytes, equalBytes, sha256, hash160, sha256x2, pubSchnorr, pubECDSA, LOW_R_BOUND, hasLowR, signSchnorr, tagSchnorr, PubT, INTERNAL_TAPROOT_NUMS, NETWORK, TEST_NETWORK;
16591
+ var Point, Fn, CURVE_ORDER, _0n$3, _2n$1, hasEven, isBytes, concatBytes, equalBytes, sha256, hash160, sha256x2, pubSchnorr, pubECDSA, LOW_R_BOUND, hasLowR, signSchnorr, tagSchnorr, PubT, INTERNAL_TAPROOT_NUMS, NETWORK, TEST_NETWORK;
15098
16592
  var init_utils = __esmMin((() => {
15099
16593
  init_secp256k1();
15100
16594
  init_utils$1();
@@ -15105,9 +16599,9 @@ zoo`.split("\n"));
15105
16599
  Point = /* @__PURE__ */ (() => secp256k1.Point)();
15106
16600
  Fn = /* @__PURE__ */ (() => Point.Fn)();
15107
16601
  CURVE_ORDER = /* @__PURE__ */ (() => Point.Fn.ORDER)();
15108
- _0n$4 = /* @__PURE__ */ BigInt(0);
15109
- _2n$2 = /* @__PURE__ */ BigInt(2);
15110
- hasEven = (y) => y % _2n$2 === _0n$4;
16602
+ _0n$3 = /* @__PURE__ */ BigInt(0);
16603
+ _2n$1 = /* @__PURE__ */ BigInt(2);
16604
+ hasEven = (y) => y % _2n$1 === _0n$3;
15111
16605
  isBytes = /* @__PURE__ */ (() => utils.isBytes)();
15112
16606
  concatBytes = /* @__PURE__ */ (() => utils.concatBytes)();
15113
16607
  equalBytes = /* @__PURE__ */ (() => utils.equalBytes)();
@@ -15116,7 +16610,7 @@ zoo`.split("\n"));
15116
16610
  sha256x2 = (...msgs) => sha256(sha256(concatBytes(...msgs)));
15117
16611
  pubSchnorr = (priv) => schnorr.getPublicKey(priv);
15118
16612
  pubECDSA = (privateKey, isCompressed) => secp256k1.getPublicKey(privateKey, isCompressed);
15119
- LOW_R_BOUND = /* @__PURE__ */ (() => CURVE_ORDER / _2n$2)();
16613
+ LOW_R_BOUND = /* @__PURE__ */ (() => CURVE_ORDER / _2n$1)();
15120
16614
  hasLowR = (sig) => sig.r < LOW_R_BOUND;
15121
16615
  signSchnorr = (message, secretKey, auxRand) => schnorr.sign(message, secretKey, auxRand);
15122
16616
  tagSchnorr = (tag, ...messages) => schnorr.utils.taggedHash(tag, ...messages);
@@ -15156,7 +16650,7 @@ zoo`.split("\n"));
15156
16650
  function ScriptNum(bytesLimit = 6, forceMinimal = false) {
15157
16651
  return wrap({
15158
16652
  encodeStream: (w, value) => {
15159
- if (value === _0n$3) return;
16653
+ if (value === _0n$2) return;
15160
16654
  const neg = value < 0;
15161
16655
  const val = BigInt(value);
15162
16656
  const nums = [];
@@ -15168,17 +16662,17 @@ zoo`.split("\n"));
15168
16662
  decodeStream: (r) => {
15169
16663
  const len = r.leftBytes;
15170
16664
  if (len > bytesLimit) throw new Error(`ScriptNum: number (${len}) bigger than limit=${bytesLimit}`);
15171
- if (len === 0) return _0n$3;
16665
+ if (len === 0) return _0n$2;
15172
16666
  const data = r.bytes(len);
15173
16667
  if (forceMinimal) {
15174
16668
  if ((data[len - 1] & 127) === 0) {
15175
16669
  if (len <= 1 || (data[len - 2] & 128) === 0) throw new Error("Non-minimally encoded ScriptNum");
15176
16670
  }
15177
16671
  }
15178
- let res = _0n$3;
16672
+ let res = _0n$2;
15179
16673
  for (let i = 0; i < len; ++i) res |= BigInt(data[i]) << _8n * BigInt(i);
15180
16674
  if (data[len - 1] >= 128) {
15181
- res &= _2n$1 ** BigInt(len * 8) - _1n$3 >> _1n$3;
16675
+ res &= _2n ** BigInt(len * 8) - _1n$2 >> _1n$2;
15182
16676
  res = -res;
15183
16677
  }
15184
16678
  return res;
@@ -15213,13 +16707,13 @@ zoo`.split("\n"));
15213
16707
  if (tx.segwitFlag && tx.witnesses && tx.witnesses.every((w) => !w.length)) throw new Error("Segwit flag with only empty witness fields");
15214
16708
  return tx;
15215
16709
  }
15216
- var _0n$3, _1n$3, _2n$1, _8n, U8_MAX, COMPACT_DIRECT_MAX, OP, OPNames, scriptPushLen, Script, CompactSize, CompactSizeLen, _VarBytes, VarBytes, _RawWitness, RawWitness, BTCArray, RawInput, RawOutput, _RawTx, RawTx, RawOldTx;
16710
+ var _0n$2, _1n$2, _2n, _8n, U8_MAX, COMPACT_DIRECT_MAX, OP, OPNames, scriptPushLen, Script, CompactSize, CompactSizeLen, _VarBytes, VarBytes, _RawWitness, RawWitness, BTCArray, RawInput, RawOutput, _RawTx, RawTx, RawOldTx;
15217
16711
  var init_script = __esmMin((() => {
15218
16712
  init_micro_packed();
15219
16713
  init_utils();
15220
- _0n$3 = /* @__PURE__ */ BigInt(0);
15221
- _1n$3 = /* @__PURE__ */ BigInt(1);
15222
- _2n$1 = /* @__PURE__ */ BigInt(2);
16714
+ _0n$2 = /* @__PURE__ */ BigInt(0);
16715
+ _1n$2 = /* @__PURE__ */ BigInt(1);
16716
+ _2n = /* @__PURE__ */ BigInt(2);
15223
16717
  _8n = /* @__PURE__ */ BigInt(8);
15224
16718
  U8_MAX = /* @__PURE__ */ BigInt(255);
15225
16719
  COMPACT_DIRECT_MAX = /* @__PURE__ */ BigInt(252);
@@ -15431,7 +16925,7 @@ zoo`.split("\n"));
15431
16925
  return Object.freeze(wrap({
15432
16926
  encodeStream: (w, value) => {
15433
16927
  if (typeof value === "number") value = BigInt(value);
15434
- if (_0n$3 <= value && value <= COMPACT_DIRECT_MAX) return w.byte(Number(value));
16928
+ if (_0n$2 <= value && value <= COMPACT_DIRECT_MAX) return w.byte(Number(value));
15435
16929
  for (const [flag, bytes, start, stop] of limitsList) {
15436
16930
  if (start > value || value > stop) continue;
15437
16931
  w.byte(flag);
@@ -15444,7 +16938,7 @@ zoo`.split("\n"));
15444
16938
  const b0 = r.byte();
15445
16939
  if (b0 <= 252) return BigInt(b0);
15446
16940
  const [_, bytes, start] = limits[b0];
15447
- let num = _0n$3;
16941
+ let num = _0n$2;
15448
16942
  for (let i = 0; i < bytes; i++) num |= BigInt(r.byte()) << _8n * BigInt(i);
15449
16943
  if (num < start) throw r.err(`Wrong CompactSize(${8 * bytes})`);
15450
16944
  return num;
@@ -15793,7 +17287,7 @@ zoo`.split("\n"));
15793
17287
  }
15794
17288
  return mergeKeyMap(psbtEnum, _other, _current, void 0, unknown, proprietary);
15795
17289
  }
15796
- var unknowns, _0n$2, _1n$2, PubKeyECDSA, PubKeyECDSACompressed, PubKeySchnorr, SignatureSchnorr, RawWitnessWire, BIP32Der, TaprootBIP32Der, GlobalXPUB, tapScriptSigKey, _TaprootControlBlock, TaprootControlBlock, tapTree, BytesInf, ProprietaryKey, Bytes20, Bytes32, Bytes64, Bytes66, MuSig2Participants, MuSig2Key, SilentPaymentInfo, DNSSECProof, PSBTInfo, PSBTGlobal, PSBTInput, PSBTInputFinalKeys, PSBTInputSignatureKeys, PSBTOutput, PSBTOutputUnsignedKeys, PSBTKeyPair, PSBTUnknownKey, PSBTInputCoder, PSBTOutputCoder, PSBTGlobalCoder, _RawPSBTV0, _RawPSBTV2, RawPSBTV0, RawPSBTV2;
17290
+ var unknowns, _0n$1, _1n$1, PubKeyECDSA, PubKeyECDSACompressed, PubKeySchnorr, SignatureSchnorr, RawWitnessWire, BIP32Der, TaprootBIP32Der, GlobalXPUB, tapScriptSigKey, _TaprootControlBlock, TaprootControlBlock, tapTree, BytesInf, ProprietaryKey, Bytes20, Bytes32, Bytes64, Bytes66, MuSig2Participants, MuSig2Key, SilentPaymentInfo, DNSSECProof, PSBTInfo, PSBTGlobal, PSBTInput, PSBTInputFinalKeys, PSBTInputSignatureKeys, PSBTOutput, PSBTOutputUnsignedKeys, PSBTKeyPair, PSBTUnknownKey, PSBTInputCoder, PSBTOutputCoder, PSBTGlobalCoder, _RawPSBTV0, _RawPSBTV2, RawPSBTV0, RawPSBTV2;
15797
17291
  var init_psbt = __esmMin((() => {
15798
17292
  init_base();
15799
17293
  init_utils$2();
@@ -15807,8 +17301,8 @@ zoo`.split("\n"));
15807
17301
  if (mode === "ignore" || mode === "strip" || mode === "strict") return mode;
15808
17302
  throw new Error(`PSBT: invalid ${name} policy=${mode}`);
15809
17303
  };
15810
- _0n$2 = /* @__PURE__ */ BigInt(0);
15811
- _1n$2 = /* @__PURE__ */ BigInt(1);
17304
+ _0n$1 = /* @__PURE__ */ BigInt(0);
17305
+ _1n$1 = /* @__PURE__ */ BigInt(1);
15812
17306
  PubKeyECDSA = /* @__PURE__ */ (() => validate$4(createBytes(null), (pub) => validatePubkey(pub, PubT.ecdsa)))();
15813
17307
  PubKeyECDSACompressed = /* @__PURE__ */ (() => validate$4(createBytes(33), (pub) => validatePubkey(pub, PubT.ecdsa)))();
15814
17308
  PubKeySchnorr = /* @__PURE__ */ (() => validate$4(createBytes(32), (pub) => validatePubkey(pub, PubT.schnorr)))();
@@ -15870,9 +17364,9 @@ zoo`.split("\n"));
15870
17364
  while (next.length < depth) next.push(0);
15871
17365
  path = next;
15872
17366
  }
15873
- let leaves = _0n$2;
15874
- for (let i = 0; i < tree.length; i++) leaves += _1n$2 << BigInt(maxDepth - tree[i].depth);
15875
- if (leaves !== _1n$2 << BigInt(maxDepth)) throw new Error("tapTree: tuples must describe a complete binary tree");
17367
+ let leaves = _0n$1;
17368
+ for (let i = 0; i < tree.length; i++) leaves += _1n$1 << BigInt(maxDepth - tree[i].depth);
17369
+ if (leaves !== _1n$1 << BigInt(maxDepth)) throw new Error("tapTree: tuples must describe a complete binary tree");
15876
17370
  return tree;
15877
17371
  }))();
15878
17372
  BytesInf = /* @__PURE__ */ createBytes(null);
@@ -16039,7 +17533,7 @@ zoo`.split("\n"));
16039
17533
  return i;
16040
17534
  })))();
16041
17535
  PSBTOutputCoder = /* @__PURE__ */ (() => Object.freeze(validate$4(PSBTKeyMap(PSBTOutput), (o) => {
16042
- if (o.amount !== void 0 && o.amount < _0n$2) throw new Error(`validateOutput: wrong amount=${o.amount}`);
17536
+ if (o.amount !== void 0 && o.amount < _0n$1) throw new Error(`validateOutput: wrong amount=${o.amount}`);
16043
17537
  if (o.bip32Derivation) for (const [k] of o.bip32Derivation) validatePubkey(k, PubT.ecdsa);
16044
17538
  return o;
16045
17539
  })))();
@@ -17084,7 +18578,7 @@ zoo`.split("\n"));
17084
18578
  return res;
17085
18579
  }
17086
18580
  }
17087
- var _0n$1, _1n$1, U64_MAX, EMPTY32, EMPTY_OUTPUT, toVsize, stripCodeSeparator, DEFAULT_SEQUENCE, def, SignatureHash, SigHash, SigHashNames, cleanExtensions, cleanTxModifiable, TxHashIdx, sighashScope, normalizeUnknowns, LOCKTIME_THRESHOLD, inputSignatures, inputSignedKeys, Transaction;
18581
+ var _0n, _1n, U64_MAX, EMPTY32, EMPTY_OUTPUT, toVsize, stripCodeSeparator, DEFAULT_SEQUENCE, def, SignatureHash, SigHash, SigHashNames, cleanExtensions, cleanTxModifiable, TxHashIdx, sighashScope, normalizeUnknowns, LOCKTIME_THRESHOLD, inputSignatures, inputSignedKeys, Transaction;
17088
18582
  var init_transaction = __esmMin((() => {
17089
18583
  init_base();
17090
18584
  init_utils$2();
@@ -17095,8 +18589,8 @@ zoo`.split("\n"));
17095
18589
  init_utils();
17096
18590
  init_objectSpread2();
17097
18591
  init_defineProperty();
17098
- _0n$1 = /* @__PURE__ */ BigInt(0);
17099
- _1n$1 = /* @__PURE__ */ BigInt(1);
18592
+ _0n = /* @__PURE__ */ BigInt(0);
18593
+ _1n = /* @__PURE__ */ BigInt(1);
17100
18594
  U64_MAX = /* @__PURE__ */ BigInt("0xffffffffffffffff");
17101
18595
  EMPTY32 = /* @__PURE__ */ new Uint8Array(32);
17102
18596
  EMPTY_OUTPUT = {
@@ -17622,7 +19116,7 @@ zoo`.split("\n"));
17622
19116
  });
17623
19117
  }
17624
19118
  get fee() {
17625
- let res = _0n$1;
19119
+ let res = _0n;
17626
19120
  for (const i of this.inputs) {
17627
19121
  const prevOut = getPrevOut(i);
17628
19122
  if (!prevOut) throw new Error("Empty input amount");
@@ -17635,7 +19129,7 @@ zoo`.split("\n"));
17635
19129
  preimageLegacy(idx, prevOutScript, hashType) {
17636
19130
  const { isAny, isNone, isSingle } = unpackSighash(hashType);
17637
19131
  if (idx < 0 || !Number.isSafeInteger(idx)) throw new Error(`Invalid input idx=${idx}`);
17638
- if (isSingle && idx >= this.outputs.length || idx >= this.inputs.length) return U256LE.encode(_1n$1);
19132
+ if (isSingle && idx >= this.outputs.length || idx >= this.inputs.length) return U256LE.encode(_1n);
17639
19133
  prevOutScript = stripCodeSeparator(prevOutScript);
17640
19134
  let inputs = this.inputs.map(inputBeforeSign).map((input, inputIdx) => _objectSpread2(_objectSpread2({}, input), {}, { finalScriptSig: inputIdx === idx ? prevOutScript : EMPTY$1 }));
17641
19135
  if (isAny) inputs = [inputs[idx]];
@@ -17833,7 +19327,7 @@ zoo`.split("\n"));
17833
19327
  }
17834
19328
  finalizeIdx(idx) {
17835
19329
  this.checkInputIdx(idx);
17836
- if (this.fee < _0n$1) throw new Error("Outputs spends more than inputs amount");
19330
+ if (this.fee < _0n) throw new Error("Outputs spends more than inputs amount");
17837
19331
  const input = this.inputs[idx];
17838
19332
  cleanExtensions(input, this.opts.unknown, this.opts.proprietary);
17839
19333
  cleanTxModifiable(this.global.txModifiable, this.opts.unknown);
@@ -17961,7 +19455,7 @@ zoo`.split("\n"));
17961
19455
  extract() {
17962
19456
  if (!this.isFinal) throw new Error("Transaction has unfinalized inputs");
17963
19457
  if (!this.outputs.length) throw new Error("Transaction has no outputs");
17964
- if (this.fee < _0n$1) throw new Error("Outputs spends more than inputs amount");
19458
+ if (this.fee < _0n) throw new Error("Outputs spends more than inputs amount");
17965
19459
  return this.toBytes(true, true);
17966
19460
  }
17967
19461
  combine(other) {
@@ -18044,7 +19538,7 @@ zoo`.split("\n"));
18044
19538
  }
18045
19539
  };
18046
19540
  }));
18047
- // packages/wallet-chains/dist/message-Dv18g8ii.mjs
19541
+ // packages/wallet-chains/dist/message-ChhEZ0lx.mjs
18048
19542
  init_secp256k1();
18049
19543
  init_utils();
18050
19544
  init_transaction();
@@ -18104,9 +19598,9 @@ zoo`.split("\n"));
18104
19598
  * BIP-322 message signing ("simple" + legacy) built on btc-signer primitives.
18105
19599
  * https://github.com/bitcoin/bips/blob/master/bip-0322.mediawiki
18106
19600
  */
18107
- var utf8 = (s) => new TextEncoder().encode(s);
19601
+ var utf8$1 = (s) => new TextEncoder().encode(s);
18108
19602
  var BIP322_TAG = "BIP0322-signed-message";
18109
- var LEGACY_MAGIC = utf8("Bitcoin Signed Message:\n");
19603
+ var LEGACY_MAGIC = utf8$1("Bitcoin Signed Message:\n");
18110
19604
  var concat$2 = (...parts) => {
18111
19605
  const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
18112
19606
  let o = 0;
@@ -18136,8 +19630,8 @@ zoo`.split("\n"));
18136
19630
  };
18137
19631
  /** BIP340 tagged hash: sha256(sha256(tag) || sha256(tag) || m). */
18138
19632
  var bip322MessageHash = (message) => {
18139
- const tag = sha256$1(utf8(BIP322_TAG));
18140
- return sha256$1(concat$2(tag, tag, utf8(message)));
19633
+ const tag = sha256$1(utf8$1(BIP322_TAG));
19634
+ return sha256$1(concat$2(tag, tag, utf8$1(message)));
18141
19635
  };
18142
19636
  /**
18143
19637
  * Serialized to_spend tx per BIP-322: version 0, one input spending the zero prevout with the
@@ -18213,7 +19707,7 @@ zoo`.split("\n"));
18213
19707
  */
18214
19708
  var signLegacyMessage = (message, privateKey) => {
18215
19709
  var _recovered$;
18216
- const data = concat$2(pushData(LEGACY_MAGIC), pushData(utf8(message)));
19710
+ const data = concat$2(pushData(LEGACY_MAGIC), pushData(utf8$1(message)));
18217
19711
  const hash = sha256$1(sha256$1(data));
18218
19712
  const recovered = secp256k1.sign(hash, privateKey, {
18219
19713
  lowS: true,
@@ -18290,7 +19784,8 @@ zoo`.split("\n"));
18290
19784
  const { type } = getInputType(input);
18291
19785
  if ((type === "legacy" || type === "nonwitness-script") && input.nonWitnessUtxo === void 0) throw new ChainError("invalid-request", `input ${idx} is missing nonWitnessUtxo`);
18292
19786
  const sighash = input.sighashType;
18293
- if (!(sighash === void 0 || sighash === SIGHASH_ALL || isTaprootInput(input) && sighash === DEFAULT_SIGHASH)) throw new ChainError("unsupported", `input ${idx} uses a non-default sighash`);
19787
+ if (!(sighash === void 0 || sighash === SIGHASH_ALL || isTaprootInput(input) && sighash === DEFAULT_SIGHASH || sighash === 131)) throw new ChainError("unsupported", `input ${idx} uses a non-default sighash`);
19788
+ if (sighash === 131 && idx >= tx.outputsLength) throw new ChainError("unsupported", `input ${idx} uses SIGHASH_SINGLE without a same-index output`);
18294
19789
  }
18295
19790
  return {
18296
19791
  psbt: tx.toPSBT(0),
@@ -18298,7 +19793,16 @@ zoo`.split("\n"));
18298
19793
  };
18299
19794
  };
18300
19795
  var SATS = "sats";
19796
+ var SIGHASH_SINGLE_ANYONECANPAY = 131;
18301
19797
  var OP_RETURN = 106;
19798
+ /** Btc-signer's parse failures are foreign exceptions — the request is a malformed PSBT. */
19799
+ var parsePsbt = (psbt) => {
19800
+ try {
19801
+ return Transaction.fromPSBT(psbt);
19802
+ } catch (error) {
19803
+ throw error instanceof ChainError ? error : new ChainError("invalid-request", "malformed PSBT");
19804
+ }
19805
+ };
18302
19806
  var bytesToHex$2 = (bytes) => {
18303
19807
  let out = "";
18304
19808
  for (const b of bytes) out += b.toString(16).padStart(2, "0");
@@ -18324,7 +19828,7 @@ zoo`.split("\n"));
18324
19828
  * change) — not a display hint.
18325
19829
  */
18326
19830
  var decodeBitcoinPsbt = (request, ownScripts = /* @__PURE__ */ new Set()) => {
18327
- const tx = Transaction.fromPSBT(request.psbt);
19831
+ const tx = parsePsbt(request.psbt);
18328
19832
  const coder = Address(bitcoinNetwork(request.network).params);
18329
19833
  const signed = new Set(request.sign);
18330
19834
  const outflows = [];
@@ -18363,18 +19867,22 @@ zoo`.split("\n"));
18363
19867
  }
18364
19868
  const external = tx.inputsLength - signed.size > 0;
18365
19869
  const undecodable = outflows.some((o) => !o.verified);
18366
- const verifiability = external ? "opaque" : undecodable ? "partial" : "full";
19870
+ const listing = request.sign.some((i) => tx.getInput(i).sighashType === SIGHASH_SINGLE_ANYONECANPAY);
19871
+ const verifiability = external ? "opaque" : listing || undecodable ? "partial" : "full";
18367
19872
  return {
18368
19873
  family: "bitcoin",
18369
19874
  network: request.network,
18370
19875
  summary: outflows.length > 0 ? "transfer" : "contract-call",
18371
19876
  outflows,
18372
19877
  approvals: [],
18373
- fee: canFee ? { max: {
19878
+ fee: canFee && !listing ? { max: {
18374
19879
  asset: SATS,
18375
19880
  amount: (inSum - outSum).toString(10)
18376
19881
  } } : void 0,
18377
- warnings: [],
19882
+ warnings: listing ? [{
19883
+ kind: "sighash-single-anyonecanpay",
19884
+ message: "signed inputs bind only their same-index outputs; the rest of the transaction can change"
19885
+ }] : [],
18378
19886
  verifiability
18379
19887
  };
18380
19888
  };
@@ -18446,258 +19954,6 @@ zoo`.split("\n"));
18446
19954
  };
18447
19955
  /** Decodes the message `address` into the scriptPubKey the signer needs. */
18448
19956
  var decodeMessageTarget = (request) => messageTarget(request.address, request.network, request.format);
18449
- // node_modules/.bun/@noble+hashes@2.4.0/node_modules/@noble/hashes/sha3.js
18450
- init__u64();
18451
- init_utils$2();
18452
- init_defineProperty();
18453
- var _0n = BigInt(0);
18454
- var _1n = BigInt(1);
18455
- var _2n = BigInt(2);
18456
- var _7n = BigInt(7);
18457
- var _256n = BigInt(256);
18458
- var _0x71n = BigInt(113);
18459
- var SHA3_PI = [];
18460
- var SHA3_ROTL = [];
18461
- var _SHA3_IOTA = [];
18462
- for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
18463
- [x, y] = [y, (2 * x + 3 * y) % 5];
18464
- SHA3_PI.push(2 * (5 * y + x));
18465
- SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
18466
- let t = _0n;
18467
- for (let j = 0; j < 7; j++) {
18468
- R = (R << _1n ^ (R >> _7n) * _0x71n) % _256n;
18469
- if (R & _2n) t ^= _1n << (_1n << BigInt(j)) - _1n;
18470
- }
18471
- _SHA3_IOTA.push(t);
18472
- }
18473
- var IOTAS = split(_SHA3_IOTA, true);
18474
- var SHA3_IOTA_H = IOTAS[0];
18475
- var SHA3_IOTA_L = IOTAS[1];
18476
- var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
18477
- var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
18478
- var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
18479
- var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
18480
- var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
18481
- var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
18482
- var B = /* @__PURE__ */ new Uint32Array(10);
18483
- /**
18484
- * `keccakf1600` internal permutation, additionally allows adjusting the round count.
18485
- * @param s - 5x5 Keccak state encoded as 25 lanes split into 50 uint32 words
18486
- * in this file's local little-endian lane-word order
18487
- * @param rounds - number of rounds to execute
18488
- * @throws On wrong argument types. {@link TypeError}
18489
- * @throws On wrong argument ranges or values. {@link RangeError}
18490
- * @throws If `rounds` is outside the supported `1..24` range. {@link Error}
18491
- * @example
18492
- * Permute a Keccak state with the default 24 rounds.
18493
- * ```ts
18494
- * keccakP(new Uint32Array(50));
18495
- * ```
18496
- */
18497
- function keccakP(s, rounds = 24) {
18498
- if (!(s instanceof Uint32Array)) throw new TypeError("\"s\" expected Uint32Array(50), got type=" + typeof s);
18499
- if (s.length !== 50) throw new RangeError("\"s\" expected Uint32Array(50), got length=" + s.length);
18500
- anumber$2(rounds, "rounds");
18501
- if (rounds < 1 || rounds > 24) throw new Error("\"rounds\" expected integer 1..24");
18502
- for (let round = 24 - rounds; round < 24; round++) {
18503
- for (let x = 0; x < 10; x++) B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
18504
- for (let x = 0; x < 10; x += 2) {
18505
- const idx1 = (x + 8) % 10;
18506
- const idx0 = (x + 2) % 10;
18507
- const B0 = B[idx0];
18508
- const B1 = B[idx0 + 1];
18509
- const Th = rotlH(B0, B1, 1) ^ B[idx1];
18510
- const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
18511
- for (let y = 0; y < 50; y += 10) {
18512
- s[x + y] ^= Th;
18513
- s[x + y + 1] ^= Tl;
18514
- }
18515
- }
18516
- let curH = s[2];
18517
- let curL = s[3];
18518
- for (let t = 0; t < 24; t++) {
18519
- const shift = SHA3_ROTL[t];
18520
- const Th = rotlH(curH, curL, shift);
18521
- const Tl = rotlL(curH, curL, shift);
18522
- const PI = SHA3_PI[t];
18523
- curH = s[PI];
18524
- curL = s[PI + 1];
18525
- s[PI] = Th;
18526
- s[PI + 1] = Tl;
18527
- }
18528
- for (let y = 0; y < 50; y += 10) {
18529
- const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3];
18530
- s[y] ^= ~s[y + 2] & s[y + 4];
18531
- s[y + 1] ^= ~s[y + 3] & s[y + 5];
18532
- s[y + 2] ^= ~s[y + 4] & s[y + 6];
18533
- s[y + 3] ^= ~s[y + 5] & s[y + 7];
18534
- s[y + 4] ^= ~s[y + 6] & s[y + 8];
18535
- s[y + 5] ^= ~s[y + 7] & s[y + 9];
18536
- s[y + 6] ^= ~s[y + 8] & b0;
18537
- s[y + 7] ^= ~s[y + 9] & b1;
18538
- s[y + 8] ^= ~b0 & b2;
18539
- s[y + 9] ^= ~b1 & b3;
18540
- }
18541
- s[0] ^= SHA3_IOTA_H[round];
18542
- s[1] ^= SHA3_IOTA_L[round];
18543
- }
18544
- clean(B);
18545
- }
18546
- /**
18547
- * Keccak sponge function.
18548
- * @param blockLen - absorb/squeeze rate in bytes
18549
- * @param suffix - domain separation suffix byte
18550
- * @param outputLen - default digest length in bytes. This base sponge only
18551
- * requires a non-negative integer; wrappers that need positive output
18552
- * lengths must enforce that themselves.
18553
- * @param enableXOF - whether XOF output is allowed
18554
- * @param rounds - number of Keccak-f rounds
18555
- * @example
18556
- * Build a sponge state, absorb bytes, then finalize a digest.
18557
- * ```ts
18558
- * const hash = new Keccak(136, 0x06, 32);
18559
- * hash.update(new Uint8Array([1, 2, 3]));
18560
- * hash.digest();
18561
- * ```
18562
- */
18563
- var Keccak = class Keccak {
18564
- constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
18565
- _defineProperty(this, "state", void 0);
18566
- _defineProperty(this, "pos", 0);
18567
- _defineProperty(this, "posOut", 0);
18568
- _defineProperty(this, "finished", false);
18569
- _defineProperty(this, "state32", void 0);
18570
- _defineProperty(this, "destroyed", false);
18571
- _defineProperty(this, "blockLen", void 0);
18572
- _defineProperty(this, "suffix", void 0);
18573
- _defineProperty(this, "outputLen", void 0);
18574
- _defineProperty(this, "canXOF", void 0);
18575
- _defineProperty(this, "enableXOF", false);
18576
- _defineProperty(this, "rounds", void 0);
18577
- anumber$2(blockLen, "blockLen");
18578
- anumber$2(suffix, "suffix");
18579
- anumber$2(rounds, "rounds");
18580
- abool$1(enableXOF, "enableXOF");
18581
- this.blockLen = blockLen;
18582
- this.suffix = suffix;
18583
- this.outputLen = outputLen;
18584
- this.enableXOF = enableXOF;
18585
- this.canXOF = enableXOF;
18586
- this.rounds = rounds;
18587
- anumber$2(outputLen, "outputLen");
18588
- if (!(0 < blockLen && blockLen < 200)) throw new Error("\"blockLen\" must be 1..199");
18589
- this.state = /* @__PURE__ */ new Uint8Array(200);
18590
- this.state32 = u32$1(this.state);
18591
- }
18592
- clone() {
18593
- return this._cloneInto();
18594
- }
18595
- keccak() {
18596
- swap32IfBE(this.state32);
18597
- keccakP(this.state32, this.rounds);
18598
- swap32IfBE(this.state32);
18599
- this.posOut = 0;
18600
- this.pos = 0;
18601
- }
18602
- update(data) {
18603
- aexists(this);
18604
- abytes$2(data);
18605
- const { blockLen, state, state32 } = this;
18606
- const len = data.length;
18607
- const canUseU32 = blockLen % 4 === 0 && data.byteOffset % 4 === 0;
18608
- const blockLen32 = blockLen / 4;
18609
- const data32 = canUseU32 && len >= blockLen ? u32$1(data) : void 0;
18610
- for (let pos = 0; pos < len;) {
18611
- if (data32 !== void 0 && this.pos === 0 && pos % 4 === 0 && len - pos >= blockLen) {
18612
- for (let i = 0, o = pos / 4; i < blockLen32; i++) state32[i] ^= data32[o + i];
18613
- pos += blockLen;
18614
- this.pos = blockLen;
18615
- this.keccak();
18616
- continue;
18617
- }
18618
- const take = Math.min(blockLen - this.pos, len - pos);
18619
- for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++];
18620
- if (this.pos === blockLen) this.keccak();
18621
- }
18622
- return this;
18623
- }
18624
- finish() {
18625
- if (this.finished) return;
18626
- this.finished = true;
18627
- const { state, suffix, pos, blockLen } = this;
18628
- state[pos] ^= suffix;
18629
- if ((suffix & 128) !== 0 && pos === blockLen - 1) this.keccak();
18630
- state[blockLen - 1] ^= 128;
18631
- this.keccak();
18632
- }
18633
- writeInto(out) {
18634
- aexists(this, false);
18635
- abytes$2(out);
18636
- this.finish();
18637
- const bufferOut = this.state;
18638
- const { blockLen } = this;
18639
- for (let pos = 0, len = out.length; pos < len;) {
18640
- if (this.posOut >= blockLen) this.keccak();
18641
- const take = Math.min(blockLen - this.posOut, len - pos);
18642
- out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
18643
- this.posOut += take;
18644
- pos += take;
18645
- }
18646
- return out;
18647
- }
18648
- xofInto(out) {
18649
- if (!this.enableXOF) throw new Error("XOF is not enabled");
18650
- return this.writeInto(out);
18651
- }
18652
- xof(bytes) {
18653
- anumber$2(bytes);
18654
- return this.xofInto(new Uint8Array(bytes));
18655
- }
18656
- digestInto(out) {
18657
- aoutput(out, this);
18658
- if (this.finished) throw new Error("digest() was already called");
18659
- this.writeInto(out.length === this.outputLen ? out : out.subarray(0, this.outputLen));
18660
- this.destroy();
18661
- }
18662
- digest() {
18663
- const out = new Uint8Array(this.outputLen);
18664
- this.digestInto(out);
18665
- return out;
18666
- }
18667
- destroy() {
18668
- this.destroyed = true;
18669
- clean(this.state);
18670
- }
18671
- _cloneInto(to) {
18672
- const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
18673
- to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
18674
- to.blockLen = blockLen;
18675
- to.state32.set(this.state32);
18676
- to.pos = this.pos;
18677
- to.posOut = this.posOut;
18678
- to.finished = this.finished;
18679
- to.rounds = rounds;
18680
- to.suffix = suffix;
18681
- to.outputLen = outputLen;
18682
- to.enableXOF = enableXOF;
18683
- to.canXOF = this.canXOF;
18684
- to.destroyed = this.destroyed;
18685
- return to;
18686
- }
18687
- };
18688
- var genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);
18689
- /**
18690
- * Keccak-256 hash function. Different from SHA3-256.
18691
- * @param msg - message bytes to hash
18692
- * @param opts - Reserved hash options.
18693
- * @returns Digest bytes.
18694
- * @example
18695
- * Hash a message with Keccak-256.
18696
- * ```ts
18697
- * keccak_256(new Uint8Array([97, 98, 99]));
18698
- * ```
18699
- */
18700
- var keccak_256 = /* @__PURE__ */ genKeccak(1, 136, 32);
18701
19957
  // node_modules/.bun/ox@1.8.12+ff0372d108591aba/node_modules/ox/dist/core/version.js
18702
19958
  /** @internal */
18703
19959
  var version = "0.1.1";
@@ -22597,7 +23853,7 @@ zoo`.split("\n"));
22597
23853
  function validateReference(type) {
22598
23854
  if (type === "address" || type === "bool" || type === "string" || type.startsWith("bytes") || type.startsWith("uint") || type.startsWith("int")) throw new InvalidStructTypeError({ type });
22599
23855
  }
22600
- // packages/wallet-chains/dist/typed-data-Cf1g7JVv.mjs
23856
+ // packages/wallet-chains/dist/typed-data-J5g2WemC.mjs
22601
23857
  init_secp256k1();
22602
23858
  init_utils$2();
22603
23859
  init_objectSpread2();
@@ -22622,6 +23878,11 @@ zoo`.split("\n"));
22622
23878
  var isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
22623
23879
  var CANONICAL_HEX = /^0x(?:0|[1-9a-f][0-9a-f]*)$/;
22624
23880
  var canonicalHex = (value) => `0x${value.toString(16)}`;
23881
+ /** Parses a JSON-RPC quantity: `0x` and at least one hex digit — a bare `"0x"` is malformed. */
23882
+ var quantityBigInt = (value, field) => {
23883
+ if (typeof value !== "string" || !/^0x[0-9a-fA-F]+$/.test(value)) throw new ChainError("invalid-quantity", `${field} must be a 0x quantity`);
23884
+ return BigInt(value);
23885
+ };
22625
23886
  var safeInteger = (value, field) => {
22626
23887
  if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new ChainError("invalid-quantity", `${field} must be a non-negative safe integer`);
22627
23888
  return value;
@@ -22629,8 +23890,7 @@ zoo`.split("\n"));
22629
23890
  var quantity = (value, field) => {
22630
23891
  if (typeof value !== "string") throw new ChainError("invalid-quantity", `${field} must be a 0x quantity string`);
22631
23892
  if (CANONICAL_HEX.test(value)) return value;
22632
- if (/^0x[0-9a-fA-F]+$/.test(value) || value === "0x") return canonicalHex(BigInt(value === "0x" ? "0x0" : value));
22633
- throw new ChainError("invalid-quantity", `${field} must be a 0x quantity`);
23893
+ return canonicalHex(quantityBigInt(value, field));
22634
23894
  };
22635
23895
  var hexBytes$1 = (value, field) => {
22636
23896
  if (typeof value !== "string" || !/^0x(?:[0-9a-fA-F]{2})*$/.test(value)) throw new ChainError("invalid-quantity", `${field} must be 0x-prefixed bytes`);
@@ -22754,8 +24014,33 @@ zoo`.split("\n"));
22754
24014
  if (!isRecord$1(message)) return false;
22755
24015
  return Object.values(types).every((fields) => Array.isArray(fields) && fields.every(isField));
22756
24016
  };
24017
+ var isTypedDataMessage = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
24018
+ /** `value` is an array of message objects (empty allowed). */
24019
+ var typedDataMessages = (value) => Array.isArray(value) && value.every(isTypedDataMessage) ? value : void 0;
24020
+ /** The `Type field,Type field` signature of struct `name` in `types`. */
24021
+ var typedDataSignature = (types, name) => {
24022
+ var _types$name;
24023
+ return (_types$name = types[name]) === null || _types$name === void 0 ? void 0 : _types$name.map((field) => `${field.type} ${field.name}`).join(",");
24024
+ };
24025
+ /** Struct `name` has exactly `fields`, in order, no more. */
24026
+ var sameFields = (types, name, fields) => typedDataSignature(types, name) === fields.join(",");
24027
+ /** A hex `address` field value, checksummed; `undefined` when malformed. */
24028
+ var typedDataAddress = (value) => typeof value === "string" && /^0x[0-9a-fA-F]{40}$/.test(value) ? checksumEvmAddress(value) : void 0;
24029
+ /** A uint field value (safe-integer number, decimal or `0x` hex string) ≤ `max`. */
24030
+ var typedDataUint = (value, max) => {
24031
+ let parsed;
24032
+ if (typeof value === "number" && Number.isSafeInteger(value)) parsed = BigInt(value);
24033
+ else if (typeof value === "string" && /^(?:[0-9]+|0x[0-9a-fA-F]+)$/.test(value)) parsed = BigInt(value);
24034
+ else return;
24035
+ return parsed >= 0n && parsed <= max ? parsed : void 0;
24036
+ };
24037
+ /** The largest timestamp a permit/order expiry or a Safe field is allowed to carry. */
24038
+ var MAX_UINT48 = 2n ** 48n - 1n;
24039
+ var isHexBytes = (value) => typeof value === "string" && /^0x[0-9a-fA-F]*$/.test(value);
24040
+ /** A `bytes` field value: `0x`-prefixed hex of even length. */
24041
+ var typedDataBytes = (value) => isHexBytes(value) ? value : void 0;
22757
24042
  /** Parses the EIP-712 JSON source and validates its shape with ox. */
22758
- var parseTypedData = (typedData, network) => {
24043
+ var parseTypedData = (typedData) => {
22759
24044
  let json;
22760
24045
  try {
22761
24046
  json = JSON.parse(typedData);
@@ -22768,17 +24053,19 @@ zoo`.split("\n"));
22768
24053
  } catch (_unused2) {
22769
24054
  throw new ChainError("invalid-typed-data", "typedData failed EIP-712 validation");
22770
24055
  }
22771
- const { chainId } = json.domain;
22772
- const numeric = typeof chainId === "number" ? chainId : typeof chainId === "string" ? Number(chainId) : NaN;
22773
- return {
22774
- json,
22775
- chainIdMismatch: Number.isSafeInteger(numeric) && numeric !== networkChainId(network)
22776
- };
24056
+ return { json };
24057
+ };
24058
+ /**
24059
+ * `domain.chainId` as a number, when present: a safe non-negative integer given as a JSON number, a
24060
+ * decimal string or a `0x` hex string.
24061
+ */
24062
+ var domainChainId = (domain) => {
24063
+ const { chainId } = domain;
24064
+ if (chainId === void 0) return;
24065
+ const numeric = typeof chainId === "number" ? chainId : typeof chainId === "string" && /^(?:[0-9]+|0x[0-9a-fA-F]+)$/.test(chainId) ? Number(chainId) : NaN;
24066
+ if (!Number.isSafeInteger(numeric) || numeric < 0) throw new ChainError("invalid-typed-data", "typed-data domain.chainId is malformed");
24067
+ return numeric;
22777
24068
  };
22778
- var typedDataWarnings = (parsed) => parsed.chainIdMismatch ? [{
22779
- kind: "chain-id-mismatch",
22780
- message: "typed-data domain.chainId does not match the request network"
22781
- }] : [];
22782
24069
  // node_modules/.bun/ox@1.8.12+ff0372d108591aba/node_modules/ox/dist/core/internal/human-readable/formatAbiItem.js
22783
24070
  /**
22784
24071
  * Formats ABI item (e.g. error, event, function) into human-readable ABI item
@@ -25169,13 +26456,363 @@ zoo`.split("\n"));
25169
26456
  var _table$String;
25170
26457
  return (_table$String = table[String(chainId)]) === null || _table$String === void 0 ? void 0 : _table$String[address];
25171
26458
  };
26459
+ var MAX_UINT256 = 2n ** 256n - 1n;
26460
+ var MAX_UINT160 = 2n ** 160n - 1n;
26461
+ /** A fungible-token allowance; `max` is the type's maximum, which marks it unlimited. */
26462
+ var allowanceChange = (token, spender, value, change, max, chainId, table, extra = {}) => {
26463
+ const known = lookupEvmToken(table, chainId, token);
26464
+ return _objectSpread2(_objectSpread2({
26465
+ kind: "allowance",
26466
+ spender,
26467
+ amount: _objectSpread2({
26468
+ asset: token,
26469
+ amount: value.toString(10)
26470
+ }, known === void 0 ? {} : {
26471
+ symbol: known.symbol,
26472
+ decimals: known.decimals
26473
+ }),
26474
+ change,
26475
+ unlimited: change !== "decrease" && value === max
26476
+ }, extra), {}, { verified: known !== void 0 });
26477
+ };
26478
+ var isMessage$1 = isTypedDataMessage;
26479
+ var address = typedDataAddress;
26480
+ var uint = typedDataUint;
26481
+ var DETAILS = [
26482
+ "address token",
26483
+ "uint160 amount",
26484
+ "uint48 expiration",
26485
+ "uint48 nonce"
26486
+ ];
26487
+ var PERMISSIONS = ["address token", "uint256 amount"];
26488
+ var WITNESS_WARNING = {
26489
+ kind: "permit2-witness",
26490
+ message: "the permit carries a witness with further terms"
26491
+ };
26492
+ var entries = (value) => Array.isArray(value) && value.length > 0 && value.every(isMessage$1) ? value : void 0;
26493
+ var permit = (...approvals) => ({
26494
+ approvals,
26495
+ warnings: []
26496
+ });
26497
+ /**
26498
+ * The permit a typed-data document grants, or `undefined` when its shape is not exactly one of the
26499
+ * recognized ones. `chainId` is the request network's, used for the built-in token table.
26500
+ */
26501
+ function recognizePermit(json, chainId, table) {
26502
+ const { types, primaryType, message, domain } = json;
26503
+ const verifying = address(domain["verifyingContract"]);
26504
+ if (verifying === void 0) return;
26505
+ const spender = address(message["spender"]);
26506
+ if (spender === void 0) return;
26507
+ const allow = (token, value, change, max, extra = {}) => allowanceChange(token, spender, value, change, max, chainId, table, extra);
26508
+ if (primaryType === "Permit") {
26509
+ if (sameFields(types, "Permit", [
26510
+ "address owner",
26511
+ "address spender",
26512
+ "uint256 value",
26513
+ "uint256 nonce",
26514
+ "uint256 deadline"
26515
+ ])) {
26516
+ const value = uint(message["value"], MAX_UINT256);
26517
+ return value === void 0 ? void 0 : permit(allow(verifying, value, "set", MAX_UINT256));
26518
+ }
26519
+ if (sameFields(types, "Permit", [
26520
+ "address holder",
26521
+ "address spender",
26522
+ "uint256 nonce",
26523
+ "uint256 expiry",
26524
+ "bool allowed"
26525
+ ])) {
26526
+ const { allowed } = message;
26527
+ return typeof allowed === "boolean" ? permit(allow(verifying, allowed ? MAX_UINT256 : 0n, "set", MAX_UINT256)) : void 0;
26528
+ }
26529
+ return;
26530
+ }
26531
+ if (verifying.toLowerCase() !== "0x000000000022D473030F116dDEE9F6B43aC78BA3".toLowerCase()) return;
26532
+ return recognizePermit2(types, primaryType, message, allow);
26533
+ }
26534
+ var recognizePermit2 = (types, primaryType, message, allow) => {
26535
+ var _own$slice;
26536
+ const via = "permit2";
26537
+ const allowance = (details) => {
26538
+ const token = address(details["token"]);
26539
+ const amount = uint(details["amount"], MAX_UINT160);
26540
+ const expiration = uint(details["expiration"], MAX_UINT48);
26541
+ return token === void 0 || amount === void 0 || expiration === void 0 ? void 0 : allow(token, amount, "set", MAX_UINT160, {
26542
+ via,
26543
+ expiration: Number(expiration)
26544
+ });
26545
+ };
26546
+ const transfer = (permitted, deadline) => {
26547
+ const token = address(permitted["token"]);
26548
+ const amount = uint(permitted["amount"], MAX_UINT256);
26549
+ return token === void 0 || amount === void 0 ? void 0 : allow(token, amount, "transfer", MAX_UINT256, _objectSpread2({ via }, deadline <= MAX_UINT48 ? { expiration: Number(deadline) } : {}));
26550
+ };
26551
+ const all = (list, build) => {
26552
+ const built = list === null || list === void 0 ? void 0 : list.map(build);
26553
+ return built === void 0 || built.some((a) => a === void 0) ? void 0 : permit(...built.filter((a) => a !== void 0));
26554
+ };
26555
+ if (primaryType === "PermitSingle") {
26556
+ const { details } = message;
26557
+ return sameFields(types, primaryType, [
26558
+ "PermitDetails details",
26559
+ "address spender",
26560
+ "uint256 sigDeadline"
26561
+ ]) && sameFields(types, "PermitDetails", DETAILS) && isMessage$1(details) ? all([details], allowance) : void 0;
26562
+ }
26563
+ if (primaryType === "PermitBatch") return sameFields(types, primaryType, [
26564
+ "PermitDetails[] details",
26565
+ "address spender",
26566
+ "uint256 sigDeadline"
26567
+ ]) && sameFields(types, "PermitDetails", DETAILS) ? all(entries(message["details"]), allowance) : void 0;
26568
+ const witness = primaryType.includes("Witness");
26569
+ const batch = primaryType.includes("Batch");
26570
+ const expected = batch ? [
26571
+ "TokenPermissions[] permitted",
26572
+ "address spender",
26573
+ "uint256 nonce",
26574
+ "uint256 deadline"
26575
+ ] : [
26576
+ "TokenPermissions permitted",
26577
+ "address spender",
26578
+ "uint256 nonce",
26579
+ "uint256 deadline"
26580
+ ];
26581
+ if (primaryType !== `Permit${batch ? "Batch" : ""}${witness ? "Witness" : ""}TransferFrom`) return;
26582
+ const own = types[primaryType];
26583
+ const last = own === null || own === void 0 ? void 0 : own.at(-1);
26584
+ const fieldsOk = witness ? sameFields(_objectSpread2(_objectSpread2({}, types), {}, { [primaryType]: (_own$slice = own === null || own === void 0 ? void 0 : own.slice(0, -1)) !== null && _own$slice !== void 0 ? _own$slice : [] }), primaryType, expected) && (last === null || last === void 0 ? void 0 : last.name) === "witness" && types[last.type] !== void 0 : sameFields(types, primaryType, expected);
26585
+ const deadline = uint(message["deadline"], MAX_UINT256);
26586
+ if (!fieldsOk || !sameFields(types, "TokenPermissions", PERMISSIONS) || deadline === void 0) return;
26587
+ const { permitted } = message;
26588
+ const result = batch ? all(entries(permitted), (item) => transfer(item, deadline)) : isMessage$1(permitted) ? all([permitted], (item) => transfer(item, deadline)) : void 0;
26589
+ return result === void 0 || !witness ? result : {
26590
+ approvals: result.approvals,
26591
+ warnings: [WITNESS_WARNING]
26592
+ };
26593
+ };
26594
+ /**
26595
+ * Recognition of Safe `SafeTx` typed data. A document is recognized only when the primary type is
26596
+ * `SafeTx` with exactly the canonical field list and the domain names a `verifyingContract` (the
26597
+ * Safe); any other shape stays an opaque message. A `delegatecall` to a canonical MultiSendCallOnly
26598
+ * contract is unpacked into its inner calls; anything else stays a single opaque call.
26599
+ */
26600
+ /**
26601
+ * Canonical MultiSendCallOnly deployments (safe-global/safe-deployments): 1.3.0, the 1.3.0 eip155
26602
+ * variant and 1.4.1, lowercase for a checksum-insensitive compare.
26603
+ */
26604
+ var SAFE_MULTISEND_CALL_ONLY = /* @__PURE__ */ new Set([
26605
+ "0x40a2accbd92bca938b02010e17a5b8929b49130d",
26606
+ "0xa1dabef33b3b82c7814b6d82a79e50f4ac44102b",
26607
+ "0x9641d764fc13c8b624c04430c7356c1c7c8102e2"
26608
+ ]);
26609
+ var SAFE_TX = [
26610
+ "address to",
26611
+ "uint256 value",
26612
+ "bytes data",
26613
+ "uint8 operation",
26614
+ "uint256 safeTxGas",
26615
+ "uint256 baseGas",
26616
+ "uint256 gasPrice",
26617
+ "address gasToken",
26618
+ "address refundReceiver",
26619
+ "uint256 nonce"
26620
+ ];
26621
+ var MULTISEND = from$2("function multiSend(bytes transactions)");
26622
+ /**
26623
+ * Packed MultiSend entries (`uint8 operation, address to, uint256 value, uint256 dataLength, bytes
26624
+ * data` repeated). `undefined` when `data` is not a `multiSend(bytes)` call, a byte is truncated or
26625
+ * trailing, or an entry's operation is not 0 — the caller falls back to one opaque call.
26626
+ */
26627
+ var multiSendEntries = (data) => {
26628
+ if (!data.toLowerCase().startsWith("0x8d80ff0a")) return;
26629
+ let packed;
26630
+ try {
26631
+ const decoded = decodeData(MULTISEND, data);
26632
+ const first = Array.isArray(decoded) ? decoded[0] : void 0;
26633
+ if (typeof first !== "string") return;
26634
+ packed = first;
26635
+ } catch (_unused) {
26636
+ return;
26637
+ }
26638
+ if (!packed.startsWith("0x")) return;
26639
+ const hex = packed.slice(2).toLowerCase();
26640
+ const calls = [];
26641
+ let offset = 0;
26642
+ while (offset < hex.length) {
26643
+ if (hex.length - offset < 170) return;
26644
+ if (Number.parseInt(hex.slice(offset, offset + 2), 16) !== 0) return;
26645
+ const to = `0x${hex.slice(offset + 2, offset + 42)}`;
26646
+ const value = BigInt(`0x${hex.slice(offset + 42, offset + 106)}`);
26647
+ const length = BigInt(`0x${hex.slice(offset + 106, offset + 170)}`);
26648
+ offset += 170;
26649
+ if (length * 2n > BigInt(hex.length - offset)) return;
26650
+ calls.push({
26651
+ to: checksumEvmAddress(to),
26652
+ value,
26653
+ data: `0x${hex.slice(offset, offset + Number(length) * 2)}`
26654
+ });
26655
+ offset += Number(length) * 2;
26656
+ }
26657
+ return calls;
26658
+ };
26659
+ /**
26660
+ * The Safe transaction a typed-data document signs, or `undefined` when its shape is not exactly
26661
+ * the recognized one. `decode` decodes one inner call (the transaction rules without a fee); the
26662
+ * caller injects it bound to the request's network and token table.
26663
+ */
26664
+ function recognizeSafe(json, decode) {
26665
+ const { types, primaryType, message, domain } = json;
26666
+ if (primaryType !== "SafeTx" || !sameFields(types, "SafeTx", SAFE_TX)) return;
26667
+ const safe = typedDataAddress(domain["verifyingContract"]);
26668
+ const to = typedDataAddress(message["to"]);
26669
+ const value = typedDataUint(message["value"], MAX_UINT256);
26670
+ const data = typedDataBytes(message["data"]);
26671
+ const operation = typedDataUint(message["operation"], 255n);
26672
+ const safeTxGas = typedDataUint(message["safeTxGas"], MAX_UINT256);
26673
+ const baseGas = typedDataUint(message["baseGas"], MAX_UINT256);
26674
+ const gasPrice = typedDataUint(message["gasPrice"], MAX_UINT256);
26675
+ const gasToken = typedDataAddress(message["gasToken"]);
26676
+ const refundReceiver = typedDataAddress(message["refundReceiver"]);
26677
+ const nonce = typedDataUint(message["nonce"], MAX_UINT256);
26678
+ 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;
26679
+ const inner = operation === 1n && SAFE_MULTISEND_CALL_ONLY.has(to.toLowerCase()) ? multiSendEntries(data) : void 0;
26680
+ const calls = (inner !== null && inner !== void 0 ? inner : [{
26681
+ to,
26682
+ value,
26683
+ data
26684
+ }]).map(decode);
26685
+ return {
26686
+ safe: _objectSpread2({
26687
+ safe,
26688
+ nonce: nonce.toString(10),
26689
+ operation: operation === 0n ? "call" : "delegatecall",
26690
+ to,
26691
+ value: value.toString(10),
26692
+ data,
26693
+ calls
26694
+ }, gasPrice > 0n ? { refund: {
26695
+ gasPrice: gasPrice.toString(10),
26696
+ gasToken,
26697
+ refundReceiver
26698
+ } } : {}),
26699
+ multisend: inner !== void 0
26700
+ };
26701
+ }
26702
+ /** Seaport 1.5 and 1.6 deployments, lowercase for a checksum-insensitive compare. */
26703
+ var SEAPORT_CONTRACTS = /* @__PURE__ */ new Set(["0x0000000000000068f116a894984e2db1123eb395", "0x00000000000000adc04c56bf30ac9d3c0aaf14dc"]);
26704
+ /** Seaport `itemType` values 0–5; an item type outside the list is not recognized. */
26705
+ var ITEM_KINDS = [
26706
+ "native",
26707
+ "erc20",
26708
+ "erc721",
26709
+ "erc1155",
26710
+ "erc721-criteria",
26711
+ "erc1155-criteria"
26712
+ ];
26713
+ var ITEM_FIELDS = [
26714
+ "uint8 itemType",
26715
+ "address token",
26716
+ "uint256 identifierOrCriteria",
26717
+ "uint256 startAmount",
26718
+ "uint256 endAmount"
26719
+ ];
26720
+ var typesMatch = (types) => Object.keys(types).length === 3 && sameFields(types, "OrderComponents", [
26721
+ "address offerer",
26722
+ "address zone",
26723
+ "OfferItem[] offer",
26724
+ "ConsiderationItem[] consideration",
26725
+ "uint8 orderType",
26726
+ "uint256 startTime",
26727
+ "uint256 endTime",
26728
+ "bytes32 zoneHash",
26729
+ "uint256 salt",
26730
+ "bytes32 conduitKey",
26731
+ "uint256 counter"
26732
+ ]) && sameFields(types, "OfferItem", ITEM_FIELDS) && sameFields(types, "ConsiderationItem", [...ITEM_FIELDS, "address recipient"]);
26733
+ var amount = (kind, token, value, chainId, table) => {
26734
+ if (kind === "native") return {
26735
+ asset: EVM_NATIVE_ASSET,
26736
+ amount: value.toString(10),
26737
+ symbol: "ETH",
26738
+ decimals: 18
26739
+ };
26740
+ if (kind === "erc20") {
26741
+ const found = lookupEvmToken(table, chainId, token);
26742
+ return _objectSpread2({
26743
+ asset: token,
26744
+ amount: value.toString(10)
26745
+ }, found === void 0 ? {} : {
26746
+ symbol: found.symbol,
26747
+ decimals: found.decimals
26748
+ });
26749
+ }
26750
+ return {
26751
+ asset: token,
26752
+ amount: value.toString(10)
26753
+ };
26754
+ };
26755
+ var item = (message, chainId, table) => {
26756
+ const itemType = typedDataUint(message["itemType"], 255n);
26757
+ const token = typedDataAddress(message["token"]);
26758
+ const identifier = typedDataUint(message["identifierOrCriteria"], MAX_UINT256);
26759
+ const start = typedDataUint(message["startAmount"], MAX_UINT256);
26760
+ const end = typedDataUint(message["endAmount"], MAX_UINT256);
26761
+ const kind = itemType === void 0 ? void 0 : ITEM_KINDS[Number(itemType)];
26762
+ if (token === void 0 || identifier === void 0 || start === void 0 || end === void 0 || kind === void 0) return;
26763
+ return {
26764
+ kind,
26765
+ token,
26766
+ identifier: identifier.toString(10),
26767
+ startAmount: amount(kind, token, start, chainId, table),
26768
+ endAmount: amount(kind, token, end, chainId, table)
26769
+ };
26770
+ };
26771
+ var all = (list, build) => {
26772
+ const built = list === null || list === void 0 ? void 0 : list.map(build);
26773
+ return built === void 0 || built.some((entry) => entry === void 0) ? void 0 : built.filter((entry) => entry !== void 0);
26774
+ };
26775
+ /**
26776
+ * The Seaport order a typed-data document signs, or `undefined` when its shape is not exactly the
26777
+ * recognized one. `chainId` is the request network's, used for the built-in token table.
26778
+ */
26779
+ function recognizeSeaport(json, chainId, table) {
26780
+ const { types, primaryType, message, domain } = json;
26781
+ if (primaryType !== "OrderComponents" || !typesMatch(types)) return;
26782
+ const verifying = typedDataAddress(domain["verifyingContract"]);
26783
+ if (domain["name"] !== "Seaport" || verifying === void 0 || !SEAPORT_CONTRACTS.has(verifying.toLowerCase())) return;
26784
+ const offerer = typedDataAddress(message["offerer"]);
26785
+ const zone = typedDataAddress(message["zone"]);
26786
+ const startTime = typedDataUint(message["startTime"], MAX_UINT256);
26787
+ const endTime = typedDataUint(message["endTime"], MAX_UINT256);
26788
+ const offer = all(typedDataMessages(message["offer"]), (entry) => item(entry, chainId, table));
26789
+ const consideration = all(typedDataMessages(message["consideration"]), (entry) => {
26790
+ const base = item(entry, chainId, table);
26791
+ const recipient = typedDataAddress(entry["recipient"]);
26792
+ return base === void 0 || recipient === void 0 ? void 0 : _objectSpread2(_objectSpread2({}, base), {}, { recipient });
26793
+ });
26794
+ if (offerer === void 0 || zone === void 0 || startTime === void 0 || endTime === void 0 || offer === void 0 || consideration === void 0) return;
26795
+ return {
26796
+ offerer,
26797
+ zone,
26798
+ startTime: startTime <= MAX_UINT48 ? Number(startTime) : void 0,
26799
+ endTime: endTime <= MAX_UINT48 ? Number(endTime) : void 0,
26800
+ offer,
26801
+ consideration
26802
+ };
26803
+ }
25172
26804
  var ERC20_TRANSFER = from$2("function transfer(address to, uint256 amount)");
25173
26805
  var ERC20_APPROVE = from$2("function approve(address spender, uint256 amount)");
25174
26806
  var ERC20_INCREASE = from$2("function increaseAllowance(address spender, uint256 amount)");
26807
+ var ERC20_DECREASE = from$2("function decreaseAllowance(address spender, uint256 subtractedValue)");
26808
+ var SET_APPROVAL_FOR_ALL = from$2("function setApprovalForAll(address operator, bool approved)");
26809
+ var PERMIT2_APPROVE = from$2("function approve(address token, address spender, uint160 amount, uint48 expiration)");
26810
+ var PERMIT2_LOCKDOWN = from$2("function lockdown((address token, address spender)[] approvals)");
26811
+ var ERC721_SAFE_FROM_DATA = from$2("function safeTransferFrom(address from, address to, uint256 tokenId, bytes data)");
26812
+ var ERC1155_SAFE_BATCH_FROM = from$2("function safeBatchTransferFrom(address from, address to, uint256[] ids, uint256[] amounts, bytes data)");
25175
26813
  var ERC721_TRANSFER_FROM = from$2("function transferFrom(address from, address to, uint256 tokenId)");
25176
26814
  var ERC721_SAFE_FROM = from$2("function safeTransferFrom(address from, address to, uint256 tokenId)");
25177
26815
  var ERC1155_SAFE_FROM = from$2("function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes data)");
25178
- var MAX_UINT256 = 2n ** 256n - 1n;
25179
26816
  var argAddress = (args, index) => {
25180
26817
  const value = args[index];
25181
26818
  if (typeof value !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(value)) throw new ChainError("invalid-request", "decoded argument is not an address");
@@ -25199,7 +26836,7 @@ zoo`.split("\n"));
25199
26836
  const args = decodeData(fn, data);
25200
26837
  if (!Array.isArray(args)) return;
25201
26838
  return encodeData(fn, args).toLowerCase() === data.toLowerCase() ? args : void 0;
25202
- } catch (_unused) {
26839
+ } catch (_unused2) {
25203
26840
  return;
25204
26841
  }
25205
26842
  };
@@ -25207,20 +26844,19 @@ zoo`.split("\n"));
25207
26844
  asset: EVM_NATIVE_ASSET,
25208
26845
  amount: wei.toString(10)
25209
26846
  }, symbol === void 0 ? {} : { symbol }), decimals === void 0 ? {} : { decimals });
25210
- var feeWei = (tx) => BigInt(tx.gas) * (tx.type === "eip1559" ? BigInt(tx.maxFeePerGas) : BigInt(tx.gasPrice));
25211
- var nativeOutflow = (tx, to) => [{
26847
+ var feeWei = (tx) => quantityBigInt(tx.gas, "tx.gas") * (tx.type === "eip1559" ? quantityBigInt(tx.maxFeePerGas, "tx.maxFeePerGas") : quantityBigInt(tx.gasPrice, "tx.gasPrice"));
26848
+ var nativeOutflow = (value, to) => [{
25212
26849
  to,
25213
- amount: weiAmount(BigInt(tx.value)),
26850
+ amount: weiAmount(value),
25214
26851
  verified: true
25215
26852
  }];
25216
- var tokenFlow = (tx, to, amount, chainId, table) => {
25217
- var _tx$to, _tx$to2;
25218
- const token = lookupEvmToken(table, chainId, (_tx$to = tx.to) !== null && _tx$to !== void 0 ? _tx$to : "");
26853
+ var tokenFlow = (target, to, amount, chainId, table) => {
26854
+ const token = lookupEvmToken(table, chainId, target);
25219
26855
  return {
25220
26856
  flows: [{
25221
26857
  to,
25222
26858
  amount: _objectSpread2({
25223
- asset: (_tx$to2 = tx.to) !== null && _tx$to2 !== void 0 ? _tx$to2 : "",
26859
+ asset: target,
25224
26860
  amount: amount.toString(10)
25225
26861
  }, token === void 0 ? {} : {
25226
26862
  symbol: token.symbol,
@@ -25231,15 +26867,23 @@ zoo`.split("\n"));
25231
26867
  verified: token !== void 0
25232
26868
  };
25233
26869
  };
25234
- var approvalChange = (tx, spender, amount) => {
25235
- var _tx$to3;
25236
- return {
25237
- asset: (_tx$to3 = tx.to) !== null && _tx$to3 !== void 0 ? _tx$to3 : "",
25238
- spender,
25239
- amount: amount.toString(10),
25240
- unlimited: amount === MAX_UINT256,
25241
- verified: false
25242
- };
26870
+ var argBool = (args, index) => {
26871
+ const value = args[index];
26872
+ if (typeof value !== "boolean") throw new ChainError("invalid-request", "decoded argument is not a bool");
26873
+ return value;
26874
+ };
26875
+ var argList = (args, index) => {
26876
+ const value = args[index];
26877
+ if (!Array.isArray(value)) throw new ChainError("invalid-request", "decoded argument is not an array");
26878
+ return value;
26879
+ };
26880
+ var argSeconds = (args, index) => {
26881
+ const value = args[index];
26882
+ if (typeof value !== "number" && typeof value !== "bigint") throw new ChainError("invalid-request", "decoded argument is not an integer");
26883
+ return Number(value);
26884
+ };
26885
+ var pairField = (pair, key) => {
26886
+ return argAddress([typeof pair === "object" && pair !== null ? Reflect.get(pair, key) : ""], 0);
25243
26887
  };
25244
26888
  var nftFlow = (asset, to, id) => [{
25245
26889
  to,
@@ -25249,20 +26893,22 @@ zoo`.split("\n"));
25249
26893
  },
25250
26894
  verified: false
25251
26895
  }];
25252
- var decodeTransaction$1 = (request, table) => {
25253
- var _tx$to5;
25254
- const { tx } = request;
25255
- const chainId = networkChainId(request.network);
25256
- const data = tx.data.toLowerCase();
25257
- const fee = { max: weiAmount(feeWei(tx)) };
26896
+ /**
26897
+ * The call rules shared by a whole transaction and a Safe's inner calls: the same selector table
26898
+ * produces the intent; `fee` is `undefined` for a call that is not itself a transaction.
26899
+ */
26900
+ var decodeCall = (call, network, fee, table) => {
26901
+ var _call$to2;
26902
+ const chainId = networkChainId(network);
26903
+ const data = call.data.toLowerCase();
25258
26904
  const base = {
25259
26905
  family: "evm",
25260
- network: request.network,
26906
+ network,
25261
26907
  approvals: [],
25262
26908
  warnings: []
25263
26909
  };
25264
26910
  if (data === "0x") {
25265
- if (tx.to === void 0) return _objectSpread2(_objectSpread2({}, base), {}, {
26911
+ if (call.to === void 0) return _objectSpread2(_objectSpread2({}, base), {}, {
25266
26912
  summary: "contract-call",
25267
26913
  outflows: [],
25268
26914
  fee,
@@ -25270,14 +26916,15 @@ zoo`.split("\n"));
25270
26916
  });
25271
26917
  return _objectSpread2(_objectSpread2({}, base), {}, {
25272
26918
  summary: "transfer",
25273
- outflows: nativeOutflow(tx, tx.to),
26919
+ outflows: nativeOutflow(call.value, call.to),
25274
26920
  fee,
25275
26921
  verifiability: "full"
25276
26922
  });
25277
26923
  }
25278
26924
  const transferArgs = tryCall(ERC20_TRANSFER, data);
25279
26925
  if (transferArgs !== void 0) {
25280
- const { flows, verified } = tokenFlow(tx, argAddress(transferArgs, 0), argUint(transferArgs, 1), chainId, table);
26926
+ var _call$to;
26927
+ const { flows, verified } = tokenFlow((_call$to = call.to) !== null && _call$to !== void 0 ? _call$to : "", argAddress(transferArgs, 0), argUint(transferArgs, 1), chainId, table);
25281
26928
  return _objectSpread2(_objectSpread2({}, base), {}, {
25282
26929
  summary: "transfer",
25283
26930
  outflows: flows,
@@ -25285,39 +26932,63 @@ zoo`.split("\n"));
25285
26932
  verifiability: verified ? "full" : "partial"
25286
26933
  });
25287
26934
  }
25288
- const approveArgs = tryCall(ERC20_APPROVE, data);
25289
- if (approveArgs !== void 0) return _objectSpread2(_objectSpread2({}, base), {}, {
25290
- summary: "approve",
25291
- outflows: [],
25292
- approvals: [approvalChange(tx, argAddress(approveArgs, 0), argUint(approveArgs, 1))],
25293
- fee,
25294
- verifiability: "partial"
25295
- });
25296
- const increaseArgs = tryCall(ERC20_INCREASE, data);
25297
- if (increaseArgs !== void 0) return _objectSpread2(_objectSpread2({}, base), {}, {
25298
- summary: "approve",
25299
- outflows: [],
25300
- approvals: [approvalChange(tx, argAddress(increaseArgs, 0), argUint(increaseArgs, 1))],
26935
+ const partial = (summary, outflows, approvals) => _objectSpread2(_objectSpread2({}, base), {}, {
26936
+ summary,
26937
+ outflows,
26938
+ approvals,
25301
26939
  fee,
25302
26940
  verifiability: "partial"
25303
26941
  });
25304
- for (const fn of [ERC721_TRANSFER_FROM, ERC721_SAFE_FROM]) {
25305
- var _tx$to4;
26942
+ const token = (_call$to2 = call.to) !== null && _call$to2 !== void 0 ? _call$to2 : "";
26943
+ if (token.toLowerCase() === "0x000000000022D473030F116dDEE9F6B43aC78BA3".toLowerCase()) {
26944
+ const permitArgs = tryCall(PERMIT2_APPROVE, data);
26945
+ if (permitArgs !== void 0) {
26946
+ const amount = argUint(permitArgs, 2);
26947
+ return partial("approve", [], [allowanceChange(argAddress(permitArgs, 0), argAddress(permitArgs, 1), amount, "set", MAX_UINT160, chainId, table, {
26948
+ via: "permit2",
26949
+ expiration: argSeconds(permitArgs, 3)
26950
+ })]);
26951
+ }
26952
+ const lockdownArgs = tryCall(PERMIT2_LOCKDOWN, data);
26953
+ 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" })));
26954
+ }
26955
+ for (const [fn, change] of [
26956
+ [ERC20_APPROVE, "set"],
26957
+ [ERC20_INCREASE, "increase"],
26958
+ [ERC20_DECREASE, "decrease"]
26959
+ ]) {
25306
26960
  const args = tryCall(fn, data);
25307
- if (args !== void 0) return _objectSpread2(_objectSpread2({}, base), {}, {
25308
- summary: "transfer",
25309
- outflows: nftFlow((_tx$to4 = tx.to) !== null && _tx$to4 !== void 0 ? _tx$to4 : "", argAddress(args, 1), argUint(args, 2)),
25310
- fee,
25311
- verifiability: "partial"
25312
- });
26961
+ if (args !== void 0) return partial("approve", [], [allowanceChange(token, argAddress(args, 0), argUint(args, 1), change, MAX_UINT256, chainId, table)]);
26962
+ }
26963
+ const operatorArgs = tryCall(SET_APPROVAL_FOR_ALL, data);
26964
+ if (operatorArgs !== void 0) return partial("approve", [], [{
26965
+ kind: "operator",
26966
+ asset: token,
26967
+ spender: argAddress(operatorArgs, 0),
26968
+ approved: argBool(operatorArgs, 1),
26969
+ verified: false
26970
+ }]);
26971
+ const transferFromArgs = tryCall(ERC721_TRANSFER_FROM, data);
26972
+ if (transferFromArgs !== void 0) {
26973
+ const to = argAddress(transferFromArgs, 1);
26974
+ const id = argUint(transferFromArgs, 2);
26975
+ if (lookupEvmToken(table, chainId, token) !== void 0) return partial("transfer", tokenFlow(token, to, id, chainId, table).flows, []);
26976
+ return partial("transfer", nftFlow(token, to, id), []);
26977
+ }
26978
+ for (const fn of [ERC721_SAFE_FROM, ERC721_SAFE_FROM_DATA]) {
26979
+ const args = tryCall(fn, data);
26980
+ if (args !== void 0) return partial("transfer", nftFlow(token, argAddress(args, 1), argUint(args, 2)), []);
25313
26981
  }
25314
26982
  const erc1155Args = tryCall(ERC1155_SAFE_FROM, data);
25315
- if (erc1155Args !== void 0) return _objectSpread2(_objectSpread2({}, base), {}, {
25316
- summary: "transfer",
25317
- outflows: nftFlow((_tx$to5 = tx.to) !== null && _tx$to5 !== void 0 ? _tx$to5 : "", argAddress(erc1155Args, 1), argUint(erc1155Args, 2)),
25318
- fee,
25319
- verifiability: "partial"
25320
- });
26983
+ if (erc1155Args !== void 0) return partial("transfer", nftFlow(token, argAddress(erc1155Args, 1), argUint(erc1155Args, 2)), []);
26984
+ const batchArgs = tryCall(ERC1155_SAFE_BATCH_FROM, data);
26985
+ if (batchArgs !== void 0) {
26986
+ const ids = argList(batchArgs, 2);
26987
+ if (ids.length > 0 && ids.length === argList(batchArgs, 3).length) {
26988
+ const to = argAddress(batchArgs, 1);
26989
+ return partial("transfer", ids.flatMap((id) => nftFlow(token, to, argUint([id], 0))), []);
26990
+ }
26991
+ }
25321
26992
  return _objectSpread2(_objectSpread2({}, base), {}, {
25322
26993
  summary: "contract-call",
25323
26994
  outflows: [],
@@ -25325,11 +26996,46 @@ zoo`.split("\n"));
25325
26996
  verifiability: "opaque"
25326
26997
  });
25327
26998
  };
26999
+ var decodeTransaction$1 = (request, table) => {
27000
+ const { tx } = request;
27001
+ return decodeCall({
27002
+ to: tx.to,
27003
+ value: quantityBigInt(tx.value, "tx.value"),
27004
+ data: tx.data
27005
+ }, request.network, { max: weiAmount(feeWei(tx)) }, table);
27006
+ };
27007
+ /** The five EIP-712 domain fields a wallet shows; anything malformed is left out. */
27008
+ var displayDomain = (domain) => {
27009
+ const { name, version, verifyingContract, salt } = domain;
27010
+ const chainId = domainChainId(domain);
27011
+ return _objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2({}, typeof name === "string" ? { name } : {}), typeof version === "string" ? { version } : {}), chainId === void 0 ? {} : { chainId }), typeof verifyingContract === "string" && /^0x[0-9a-fA-F]{40}$/.test(verifyingContract) ? { verifyingContract: checksumEvmAddress(verifyingContract) } : {}), typeof salt === "string" ? { salt } : {});
27012
+ };
27013
+ /** Strict UTF-8 text with any sign-in recognition, else the raw bytes as hex. */
27014
+ var messageContent = (bytes) => {
27015
+ try {
27016
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
27017
+ const signIn = parseSignIn(text, "evm");
27018
+ return signIn === void 0 ? {
27019
+ kind: "text",
27020
+ text
27021
+ } : {
27022
+ kind: "text",
27023
+ text,
27024
+ signIn
27025
+ };
27026
+ } catch (_unused3) {
27027
+ return {
27028
+ kind: "bytes",
27029
+ hex: `0x${[...bytes].map((b) => b.toString(16).padStart(2, "0")).join("")}`
27030
+ };
27031
+ }
27032
+ };
25328
27033
  /**
25329
27034
  * Decodes a normalized request into a DisplayIntent. The token table parameter is for tests;
25330
27035
  * production callers use the built-in table.
25331
27036
  */
25332
27037
  var decodeEvm = (request, table = evmTokenTable) => {
27038
+ var _safe$safe$calls$0$su, _safe$safe$calls$, _permit$approvals, _permit$warnings;
25333
27039
  if (request.kind === "evm.transaction") return decodeTransaction$1(request, table);
25334
27040
  if (request.kind === "evm.personal-message") return {
25335
27041
  family: "evm",
@@ -25339,19 +27045,32 @@ zoo`.split("\n"));
25339
27045
  approvals: [],
25340
27046
  fee: void 0,
25341
27047
  warnings: [],
27048
+ message: messageContent(request.message),
25342
27049
  verifiability: "opaque"
25343
27050
  };
25344
27051
  if (request.kind !== "evm.typed-data") throw new ChainError("unsupported", `unsupported sign request kind: ${request.kind}`);
25345
- const parsed = parseTypedData(request.typedData, request.network);
27052
+ const { json } = parseTypedData(request.typedData);
27053
+ const chainId = networkChainId(request.network);
27054
+ const permit = recognizePermit(json, chainId, table);
27055
+ const seaport = permit === void 0 ? recognizeSeaport(json, chainId, table) : void 0;
27056
+ const safe = permit === void 0 && seaport === void 0 ? recognizeSafe(json, (call) => decodeCall(call, request.network, void 0, table)) : void 0;
27057
+ const message = _objectSpread2(_objectSpread2({
27058
+ kind: "typed-data",
27059
+ primaryType: json.primaryType,
27060
+ domain: displayDomain(json.domain),
27061
+ data: json.message
27062
+ }, seaport === void 0 ? {} : { seaport }), safe === void 0 ? {} : { safe: safe.safe });
27063
+ const summary = seaport === void 0 ? safe === void 0 ? permit === void 0 ? "message" : "approve" : safe.multisend ? "batch" : (_safe$safe$calls$0$su = (_safe$safe$calls$ = safe.safe.calls[0]) === null || _safe$safe$calls$ === void 0 ? void 0 : _safe$safe$calls$.summary) !== null && _safe$safe$calls$0$su !== void 0 ? _safe$safe$calls$0$su : "contract-call" : "swap";
25346
27064
  return {
25347
27065
  family: "evm",
25348
27066
  network: request.network,
25349
- summary: "message",
27067
+ summary,
25350
27068
  outflows: [],
25351
- approvals: [],
27069
+ approvals: (_permit$approvals = permit === null || permit === void 0 ? void 0 : permit.approvals) !== null && _permit$approvals !== void 0 ? _permit$approvals : [],
25352
27070
  fee: void 0,
25353
- warnings: typedDataWarnings(parsed),
25354
- verifiability: "opaque"
27071
+ warnings: (_permit$warnings = permit === null || permit === void 0 ? void 0 : permit.warnings) !== null && _permit$warnings !== void 0 ? _permit$warnings : [],
27072
+ message,
27073
+ verifiability: permit === void 0 ? "opaque" : "partial"
25355
27074
  };
25356
27075
  };
25357
27076
  /**
@@ -25385,7 +27104,9 @@ zoo`.split("\n"));
25385
27104
  if (request["kind"] === "evm.typed-data") {
25386
27105
  const { typedData } = request;
25387
27106
  if (typeof typedData !== "string") throw new ChainError("invalid-request", "typed-data payload must be the JSON source string");
25388
- parseTypedData(typedData, network);
27107
+ const { json } = parseTypedData(typedData);
27108
+ const domainChain = domainChainId(json.domain);
27109
+ if (domainChain !== void 0 && domainChain !== chainId) throw new ChainError("chain-id-mismatch", `typed-data domain.chainId ${domainChain} does not match network ${network}`);
25389
27110
  return {
25390
27111
  kind: "evm.typed-data",
25391
27112
  network,
@@ -26960,7 +28681,6 @@ zoo`.split("\n"));
26960
28681
  const outflows = [];
26961
28682
  const approvals = [];
26962
28683
  for (const call of calls) {
26963
- var _call$mint4, _call$to2, _call$amount3;
26964
28684
  if (call.kind === "system-transfer" && call.to !== void 0) {
26965
28685
  var _call$amount;
26966
28686
  const [source] = parsed.staticAccounts;
@@ -26988,13 +28708,24 @@ zoo`.split("\n"));
26988
28708
  verified: token !== void 0
26989
28709
  });
26990
28710
  }
26991
- if (call.kind === "token-approve") approvals.push({
26992
- asset: (_call$mint4 = call.mint) !== null && _call$mint4 !== void 0 ? _call$mint4 : "",
26993
- spender: (_call$to2 = call.to) !== null && _call$to2 !== void 0 ? _call$to2 : "",
26994
- amount: ((_call$amount3 = call.amount) !== null && _call$amount3 !== void 0 ? _call$amount3 : 0n).toString(10),
26995
- unlimited: false,
26996
- verified: false
26997
- });
28711
+ if (call.kind === "token-approve") {
28712
+ var _call$mint4, _call$to2, _call$mint5, _call$amount3;
28713
+ const token = lookupSolanaToken(table, request.network, (_call$mint4 = call.mint) !== null && _call$mint4 !== void 0 ? _call$mint4 : "");
28714
+ approvals.push({
28715
+ kind: "allowance",
28716
+ spender: (_call$to2 = call.to) !== null && _call$to2 !== void 0 ? _call$to2 : "",
28717
+ amount: _objectSpread2({
28718
+ asset: (_call$mint5 = call.mint) !== null && _call$mint5 !== void 0 ? _call$mint5 : "",
28719
+ amount: ((_call$amount3 = call.amount) !== null && _call$amount3 !== void 0 ? _call$amount3 : 0n).toString(10)
28720
+ }, token === void 0 ? {} : {
28721
+ symbol: token.symbol,
28722
+ decimals: token.decimals
28723
+ }),
28724
+ change: "set",
28725
+ unlimited: false,
28726
+ verified: token !== void 0
28727
+ });
28728
+ }
26998
28729
  }
26999
28730
  const fee = feeLamports(parsed, calls);
27000
28731
  return {
@@ -27091,7 +28822,8 @@ zoo`.split("\n"));
27091
28822
  const tx = Transaction.fromPSBT(psbt);
27092
28823
  for (const { index, privateKey } of inputs) {
27093
28824
  if (privateKey.length !== 32) throw new ChainError("invalid-request", `input ${index}: private key must be 32 bytes`);
27094
- if (!tx.signIdx(privateKey, index, void 0, auxRand(index))) throw new ChainError("invalid-request", `input ${index}: key cannot sign`);
28825
+ const allowed = tx.getInput(index).sighashType === SigHash.SINGLE_ANYONECANPAY ? [SigHash.SINGLE_ANYONECANPAY] : void 0;
28826
+ if (!tx.signIdx(privateKey, index, allowed, auxRand(index))) throw new ChainError("invalid-request", `input ${index}: key cannot sign`);
27095
28827
  }
27096
28828
  return tx.toPSBT(0);
27097
28829
  };
@@ -27103,6 +28835,7 @@ zoo`.split("\n"));
27103
28835
  return signBip322Simple(request.message, scriptPubKey, privateKey, auxRand);
27104
28836
  };
27105
28837
  // packages/wallet-kernel/src/modules/chains/prompt.ts
28838
+ init_objectSpread2();
27106
28839
  /** Off-chain messages carry no decodable value flow. */
27107
28840
  var MESSAGE_INTENT = {
27108
28841
  summary: "message",
@@ -27111,6 +28844,21 @@ zoo`.split("\n"));
27111
28844
  fee: void 0,
27112
28845
  verifiability: "opaque"
27113
28846
  };
28847
+ var utf8 = new TextDecoder("utf-8", { fatal: true });
28848
+ /** The prompt intent of a raw message: its UTF-8 text, or the bytes as hex for a blind sign. */
28849
+ var messageIntent = (message) => {
28850
+ try {
28851
+ return _objectSpread2(_objectSpread2({}, MESSAGE_INTENT), {}, { message: {
28852
+ kind: "text",
28853
+ text: utf8.decode(message)
28854
+ } });
28855
+ } catch (_unused) {
28856
+ return _objectSpread2(_objectSpread2({}, MESSAGE_INTENT), {}, { message: {
28857
+ kind: "bytes",
28858
+ hex: `0x${[...message].map((b) => b.toString(16).padStart(2, "0")).join("")}`
28859
+ } });
28860
+ }
28861
+ };
27114
28862
  var CATALOGS$1 = {
27115
28863
  "zh-Hans": {
27116
28864
  titles: {
@@ -27122,12 +28870,23 @@ zoo`.split("\n"));
27122
28870
  authorization: "确认账户授权",
27123
28871
  batch: "确认批量交易"
27124
28872
  },
28873
+ blindTitle: "确认盲签",
28874
+ blindDescription: "签署无法显示为文字的数据",
27125
28875
  generic: "签署来自应用的请求",
27126
28876
  otherOutflows: "可能还有其他转出",
27127
28877
  send: (amount, to) => `发送 ${amount} 到 ${to}`,
27128
28878
  allow: (spender, amount) => `授权 ${spender} 使用 ${amount}`,
27129
28879
  unlimited: (asset) => `全部 ${asset}`,
27130
- maxFee: (fee) => `最高手续费 ${fee}`
28880
+ revoke: (spender, asset) => `撤销 ${spender} 对 ${asset} 的授权`,
28881
+ increase: (spender, amount) => `授权 ${spender} 再使用 ${amount}`,
28882
+ decrease: (spender, amount) => `减少 ${spender} 的授权额度 ${amount}`,
28883
+ takeOnce: (spender, amount) => `授权 ${spender} 一次性转走 ${amount}`,
28884
+ viaPermit2: " 经 Permit2",
28885
+ until: (date) => ` 至 ${date}(UTC)`,
28886
+ operatorAllow: (spender, asset) => `授权 ${spender} 转走 ${asset} 的全部代币`,
28887
+ operatorRevoke: (spender, asset) => `撤销 ${spender} 对 ${asset} 全部代币的授权`,
28888
+ maxFee: (fee) => `最高手续费 ${fee}`,
28889
+ sighashSingle: "已签输入只绑定同序号输出,交易其余部分可被改动"
27131
28890
  },
27132
28891
  en: {
27133
28892
  titles: {
@@ -27139,12 +28898,23 @@ zoo`.split("\n"));
27139
28898
  authorization: "Confirm account authorization",
27140
28899
  batch: "Confirm batch"
27141
28900
  },
28901
+ blindTitle: "Confirm blind signing",
28902
+ blindDescription: "Sign data that cannot be shown as text",
27142
28903
  generic: "Sign a request from an app",
27143
28904
  otherOutflows: "There may be other outflows",
27144
28905
  send: (amount, to) => `Send ${amount} to ${to}`,
27145
28906
  allow: (spender, amount) => `Allow ${spender} to spend ${amount}`,
27146
28907
  unlimited: (asset) => `unlimited ${asset}`,
27147
- maxFee: (fee) => `Max fee ${fee}`
28908
+ revoke: (spender, asset) => `Revoke ${spender}'s allowance for ${asset}`,
28909
+ increase: (spender, amount) => `Allow ${spender} to spend ${amount} more`,
28910
+ decrease: (spender, amount) => `Reduce ${spender}'s allowance by ${amount}`,
28911
+ takeOnce: (spender, amount) => `Allow ${spender} to take ${amount} once`,
28912
+ viaPermit2: " via Permit2",
28913
+ until: (date) => ` until ${date} (UTC)`,
28914
+ operatorAllow: (spender, asset) => `Allow ${spender} to transfer all tokens of ${asset}`,
28915
+ operatorRevoke: (spender, asset) => `Revoke ${spender}'s access to all tokens of ${asset}`,
28916
+ maxFee: (fee) => `Max fee ${fee}`,
28917
+ sighashSingle: "Signed inputs bind only their same-index outputs; the rest of the transaction can change"
27148
28918
  }
27149
28919
  };
27150
28920
  /** `0.05 ETH` with known decimals (symbol, else the asset id); raw units and asset id otherwise. */
@@ -27152,17 +28922,52 @@ zoo`.split("\n"));
27152
28922
  var _amount$symbol;
27153
28923
  return amount.decimals === void 0 ? `${amount.amount} ${amount.asset}` : `${formatUnits(amount.amount, amount.decimals)} ${(_amount$symbol = amount.symbol) !== null && _amount$symbol !== void 0 ? _amount$symbol : amount.asset}`;
27154
28924
  }
28925
+ /** `YYYY-MM-DD` of a Unix-seconds instant in UTC (civil-from-days; no `Date` in the enclave). */
28926
+ function utcDate(seconds) {
28927
+ const z = Math.floor(seconds / 86400) + 719468;
28928
+ const era = Math.floor(z / 146097);
28929
+ const doe = z - era * 146097;
28930
+ const yoe = Math.floor((doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365);
28931
+ const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));
28932
+ const mp = Math.floor((5 * doy + 2) / 153);
28933
+ const day = doy - Math.floor((153 * mp + 2) / 5) + 1;
28934
+ const month = mp < 10 ? mp + 3 : mp - 9;
28935
+ const year = yoe + era * 400 + (month <= 2 ? 1 : 0);
28936
+ return `${String(year).padStart(4, "0")}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
28937
+ }
28938
+ function approvalLine(catalog, change) {
28939
+ var _change$amount$symbol;
28940
+ if (change.kind === "operator") return change.approved ? catalog.operatorAllow(change.spender, change.asset) : catalog.operatorRevoke(change.spender, change.asset);
28941
+ const name = (_change$amount$symbol = change.amount.symbol) !== null && _change$amount$symbol !== void 0 ? _change$amount$symbol : change.amount.asset;
28942
+ let line;
28943
+ if (change.change === "increase") line = catalog.increase(change.spender, formatAmount(change.amount));
28944
+ else if (change.change === "decrease") line = catalog.decrease(change.spender, formatAmount(change.amount));
28945
+ else if (change.change === "transfer") line = catalog.takeOnce(change.spender, change.unlimited ? catalog.unlimited(name) : formatAmount(change.amount));
28946
+ else if (change.unlimited) line = catalog.allow(change.spender, catalog.unlimited(name));
28947
+ else if (change.amount.amount === "0") line = catalog.revoke(change.spender, name);
28948
+ else line = catalog.allow(change.spender, formatAmount(change.amount));
28949
+ const via = change.via === void 0 ? "" : catalog.viaPermit2;
28950
+ const until = change.expiration === void 0 || change.expiration === 0 ? "" : catalog.until(utcDate(change.expiration));
28951
+ return `${line}${via}${until}`;
28952
+ }
27155
28953
  function chainPrompt(locale, intent) {
28954
+ var _intent$message, _intent$warnings;
27156
28955
  const catalog = CATALOGS$1[locale];
28956
+ if (((_intent$message = intent.message) === null || _intent$message === void 0 ? void 0 : _intent$message.kind) === "bytes") return {
28957
+ title: catalog.blindTitle,
28958
+ description: catalog.blindDescription
28959
+ };
27157
28960
  const title = catalog.titles[intent.summary];
28961
+ const tail = ((_intent$warnings = intent.warnings) === null || _intent$warnings === void 0 ? void 0 : _intent$warnings.some((w) => w.kind === "sighash-single-anyonecanpay")) === true ? [catalog.sighashSingle] : [];
27158
28962
  if (intent.verifiability === "opaque") return {
27159
28963
  title,
27160
- description: catalog.generic
28964
+ description: joinLines([catalog.generic, ...tail])
27161
28965
  };
27162
28966
  const lines = [
27163
28967
  ...intent.outflows.map((flow) => catalog.send(formatAmount(flow.amount), flow.to)),
27164
- ...intent.approvals.map((change) => catalog.allow(change.spender, change.unlimited ? catalog.unlimited(change.asset) : `${change.amount} ${change.asset}`)),
27165
- ...intent.fee === void 0 ? [] : [catalog.maxFee(formatAmount(intent.fee.max))]
28968
+ ...intent.approvals.map((change) => approvalLine(catalog, change)),
28969
+ ...intent.fee === void 0 ? [] : [catalog.maxFee(formatAmount(intent.fee.max))],
28970
+ ...tail
27166
28971
  ];
27167
28972
  if (intent.verifiability === "partial") return {
27168
28973
  title,
@@ -27439,7 +29244,7 @@ zoo`.split("\n"));
27439
29244
  };
27440
29245
  /** EIP-712 typed data; returns the 65-byte signature r‖s‖v with v∈{27,28}. */
27441
29246
  var signEvmTypedData = (typedData, privateKey) => {
27442
- const { json } = parseTypedData(typedData, "eip155:1");
29247
+ const { json } = parseTypedData(typedData);
27443
29248
  return rs_v(from$1(sign$1(getSignPayload$4(json), key(privateKey))));
27444
29249
  };
27445
29250
  // packages/wallet-kernel/src/modules/chains/evm.ts
@@ -27513,7 +29318,7 @@ zoo`.split("\n"));
27513
29318
  mapChainError(error);
27514
29319
  }
27515
29320
  if (!deepEqual(normalized, request)) throw new KernelError("invalid-input", "request is not normalized");
27516
- let intent = MESSAGE_INTENT;
29321
+ let intent = messageIntent(request.message);
27517
29322
  if (request.kind === "solana.transaction") try {
27518
29323
  intent = decodeSolana(request, signer);
27519
29324
  } catch (error) {
@@ -37407,7 +39212,7 @@ zoo`.split("\n"));
37407
39212
  init_errors_5xLkExNL();
37408
39213
  }));
37409
39214
  // node_modules/.bun/@qntx+spark@0.5.2/node_modules/@qntx/spark/dist/signer.mjs
37410
- var signer_exports = /* @__PURE__ */ __exportAll({
39215
+ var signer_exports = /* @__PURE__ */ __exportAll$1({
37411
39216
  EPHEMERAL_ANCHOR_SCRIPT: () => EPHEMERAL_ANCHOR_SCRIPT,
37412
39217
  bitcoinAddressScript: () => bitcoinAddressScript,
37413
39218
  createLnurlAuthSigner: () => createLnurlAuthSigner,
@@ -39256,6 +41061,22 @@ zoo`.split("\n"));
39256
41061
  for (const item of items) collectTransferables(item, out, depth + 1);
39257
41062
  return out;
39258
41063
  }
41064
+ /**
41065
+ * Opens a record at reconcile. An `entropy` record must also match its header's payload layout, so
41066
+ * an inconsistent wallet record latches the vault corrupted instead of failing at first use.
41067
+ */
41068
+ function openChecked(dek, record) {
41069
+ const plaintext = openRecord(dek, record);
41070
+ if (record.kind === "entropy") try {
41071
+ const { entropy, passphrase } = splitWalletSecret(parseEntropyHeader(record.header), plaintext);
41072
+ wipe(entropy);
41073
+ if (passphrase !== void 0) wipe(passphrase);
41074
+ } catch (error) {
41075
+ wipe(plaintext);
41076
+ throw error;
41077
+ }
41078
+ return plaintext;
41079
+ }
39259
41080
  function isMethodName(method) {
39260
41081
  return method in METHODS;
39261
41082
  }
@@ -39315,14 +41136,14 @@ zoo`.split("\n"));
39315
41136
  if (prior === void 0) opened.push({
39316
41137
  kind: record.kind,
39317
41138
  id: record.id,
39318
- plaintext: openRecord(dek, record)
41139
+ plaintext: openChecked(dek, record)
39319
41140
  });
39320
41141
  else {
39321
41142
  before.delete(`${record.kind}/${record.id}`);
39322
41143
  if (prior.header !== record.header || !equalBytes$3(prior.sealed, record.sealed)) opened.push({
39323
41144
  kind: record.kind,
39324
41145
  id: record.id,
39325
- plaintext: openRecord(dek, record)
41146
+ plaintext: openChecked(dek, record)
39326
41147
  });
39327
41148
  }
39328
41149
  }
@@ -39496,10 +41317,7 @@ zoo`.split("\n"));
39496
41317
  integrityFailure = true;
39497
41318
  setHealth("corrupted");
39498
41319
  }
39499
- const err = error instanceof KernelError ? error.retryAt === void 0 ? { code: error.code } : {
39500
- code: error.code,
39501
- retryAt: error.retryAt
39502
- } : { code: "integrity" };
41320
+ const err = error instanceof KernelError ? _objectSpread2(_objectSpread2({ code: error.code }, error.retryAt === void 0 ? {} : { retryAt: error.retryAt }), error.detail === void 0 ? {} : { detail: error.detail }) : { code: "integrity" };
39503
41321
  return {
39504
41322
  v: 2,
39505
41323
  id,
@@ -39525,21 +41343,32 @@ zoo`.split("\n"));
39525
41343
  });
39526
41344
  enqueue(reloadAndPost);
39527
41345
  }
41346
+ // packages/wallet-native/kernel/detail.ts
41347
+ /**
41348
+ * A `"<domain>:<code>"` diagnostic a platform reports alongside a failure code (e.g.
41349
+ * `"LAErrorDomain:-5"`, `"android:KeyPermanentlyInvalidatedException"`): kept only when it is a
41350
+ * short token string — anything else (oversize, free text) is dropped at this producer boundary,
41351
+ * never rejected. Never carries userInfo, localized text or input.
41352
+ */
41353
+ function detailOf(detail) {
41354
+ return detail !== void 0 && detail.length <= 80 && /^[A-Za-z0-9_.:-]+$/.test(detail) ? detail : void 0;
41355
+ }
39528
41356
  // packages/wallet-native/kernel/keystore.ts
39529
41357
  /**
39530
41358
  * Binds the native `__qntx.keystore` object to the kernel's `Keystore` contract. The C++ side
39531
- * completes each call with `(bytes, code)`; a failure code is already the kernel error code
39532
- * (`cancelled`, `factor-invalidated`, `factor-unavailable`, `unavailable`) and becomes a
41359
+ * completes each call with `(bytes, code, detail)`; a failure code is already the kernel error code
41360
+ * (`cancelled`, `factor-invalidated`, `no-device-credential`, `unavailable`) and becomes a
39533
41361
  * `KernelError` so the vault reports it verbatim instead of as an integrity failure.
39534
41362
  */
39535
- function failure$1(code) {
39536
- return code === "cancelled" || code === "factor-invalidated" || code === "factor-unavailable" || code === "unavailable" ? new KernelError(code, "the platform keystore did not complete") : new KernelError("unavailable", "the platform keystore reported no outcome");
41363
+ function failure$1(code, detail) {
41364
+ const diagnostic = detailOf(detail);
41365
+ return code === "cancelled" || code === "factor-invalidated" || code === "no-device-credential" || code === "unavailable" ? new KernelError(code, "the platform keystore did not complete", void 0, false, diagnostic) : new KernelError("unavailable", "the platform keystore reported no outcome", void 0, false, diagnostic);
39537
41366
  }
39538
41367
  async function bytesOf$1(start) {
39539
41368
  return new Promise((resolve, reject) => {
39540
- start((result, code) => {
41369
+ start((result, code, detail) => {
39541
41370
  if (result === void 0) {
39542
- reject(failure$1(code));
41371
+ reject(failure$1(code, detail));
39543
41372
  return;
39544
41373
  }
39545
41374
  resolve(result);
@@ -39548,9 +41377,9 @@ zoo`.split("\n"));
39548
41377
  }
39549
41378
  async function outcomeOf(start) {
39550
41379
  return new Promise((resolve, reject) => {
39551
- start((_result, code) => {
41380
+ start((_result, code, detail) => {
39552
41381
  if (code !== void 0) {
39553
- reject(failure$1(code));
41382
+ reject(failure$1(code, detail));
39554
41383
  return;
39555
41384
  }
39556
41385
  resolve();
@@ -41943,8 +43772,9 @@ zoo`.split("\n"));
41943
43772
  };
41944
43773
  /** Whether bit `flag` (a power of two) is set in the authenticator-data flags byte. */
41945
43774
  var hasFlag = (flags, flag) => Math.floor(flags / flag) % 2 === 1;
41946
- function failure(code) {
41947
- return code === "cancelled" || code === "factor-unavailable" || code === "unavailable" ? new KernelError(code, "the platform passkey ceremony did not complete") : new KernelError("unavailable", "the platform passkey ceremony reported no outcome");
43775
+ function failure(code, detail) {
43776
+ const diagnostic = detailOf(detail);
43777
+ return code === "cancelled" || code === "passkey-not-configured" || code === "unsupported" || code === "unavailable" ? new KernelError(code, "the platform passkey ceremony did not complete", void 0, false, diagnostic) : new KernelError("unavailable", "the platform passkey ceremony reported no outcome", void 0, false, diagnostic);
41948
43778
  }
41949
43779
  var malformed = () => new KernelError("unavailable", "the platform returned a malformed passkey response");
41950
43780
  var b64 = (bytes) => base64urlnopad.encode(bytes);
@@ -42016,7 +43846,7 @@ zoo`.split("\n"));
42016
43846
  if (!assertion && enabled === false) {
42017
43847
  first === null || first === void 0 || first.fill(0);
42018
43848
  second === null || second === void 0 || second.fill(0);
42019
- throw new KernelError("factor-unavailable", "the passkey does not support the PRF extension");
43849
+ throw new KernelError("passkey-prf-unsupported", "the passkey does not support the PRF extension");
42020
43850
  }
42021
43851
  const rawAuthData = response["authenticatorData"];
42022
43852
  let authData;
@@ -42049,9 +43879,9 @@ zoo`.split("\n"));
42049
43879
  }
42050
43880
  async function run(start, request, assertion) {
42051
43881
  return parseResponse(await new Promise((resolve, reject) => {
42052
- start(JSON.stringify(request), (responseJson, code) => {
43882
+ start(JSON.stringify(request), (responseJson, code, detail) => {
42053
43883
  if (responseJson === void 0) {
42054
- reject(failure(code));
43884
+ reject(failure(code, detail));
42055
43885
  return;
42056
43886
  }
42057
43887
  resolve(responseJson);