@qntx/wallet-native 0.8.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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-D-NCx1CQ.mjs
501
501
  init_defineProperty();
502
502
  /**
503
503
  * Strict validator combinators for the secret-area protocol. Both sides share them: the kernel
@@ -711,8 +711,11 @@
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
  });
717
+ /** A BIP-39 passphrase on the wire: raw UTF-8 bytes, never empty (the host omits "none"). */
718
+ var passphraseBytes = bytes(1, 1024);
716
719
  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
720
  var createdResult = obj({
718
721
  wallet: walletInfo$1,
@@ -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-DDz4nlYK.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}$/),
@@ -3314,7 +3328,7 @@
3314
3328
  toWords
3315
3329
  };
3316
3330
  }
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;
3331
+ 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
3332
  var init_base = __esmMin((() => {
3319
3333
  freeze = (fn) => Object.freeze(fn());
3320
3334
  powers = /* @__PURE__ */ (() => {
@@ -3544,7 +3558,7 @@
3544
3558
  return res.subarray(0, pos);
3545
3559
  }
3546
3560
  }));
3547
- utf8$1 = /* @__PURE__ */ freeze(() => {
3561
+ utf8$2 = /* @__PURE__ */ freeze(() => {
3548
3562
  let _utf8Encoder;
3549
3563
  let _utf8Decoder;
3550
3564
  const utf8Builtin = {
@@ -7463,6 +7477,7 @@
7463
7477
  return value;
7464
7478
  }
7465
7479
  // packages/wallet-kernel/src/vault/headers.ts
7480
+ init_objectSpread2();
7466
7481
  var PURPOSE_PATTERN = /^[a-z0-9-]{1,32}$/;
7467
7482
  var PASSWORD_ITERATIONS$2 = 6e5;
7468
7483
  function encodeHeader(header) {
@@ -7491,13 +7506,14 @@
7491
7506
  purpose: header.purpose,
7492
7507
  createdAt: header.createdAt
7493
7508
  });
7494
- return JSON.stringify({
7509
+ return JSON.stringify(_objectSpread2(_objectSpread2({
7495
7510
  walletId: header.walletId,
7496
7511
  origin: header.origin,
7497
- words: header.words,
7512
+ words: header.words
7513
+ }, header.passphrase === true ? { passphrase: true } : {}), {}, {
7498
7514
  backup: header.backup,
7499
7515
  createdAt: header.createdAt
7500
- });
7516
+ }));
7501
7517
  }
7502
7518
  function asEntropyOrigin(value) {
7503
7519
  if (value !== "passkey" && value !== "mnemonic") throw headerFailure();
@@ -7509,7 +7525,15 @@
7509
7525
  }
7510
7526
  function parseEntropyHeader(text) {
7511
7527
  const object = headerObject(text);
7512
- expectKeys(object, [
7528
+ const flagged = Object.hasOwn(object, "passphrase");
7529
+ expectKeys(object, flagged ? [
7530
+ "walletId",
7531
+ "origin",
7532
+ "words",
7533
+ "passphrase",
7534
+ "backup",
7535
+ "createdAt"
7536
+ ] : [
7513
7537
  "walletId",
7514
7538
  "origin",
7515
7539
  "words",
@@ -7518,13 +7542,16 @@
7518
7542
  ]);
7519
7543
  const { backup } = object;
7520
7544
  if (backup !== "none" && backup !== "passkey" && backup !== "mnemonic") throw headerFailure();
7521
- return {
7545
+ const origin = asEntropyOrigin(object["origin"]);
7546
+ if (flagged && (object["passphrase"] !== true || origin !== "mnemonic")) throw headerFailure();
7547
+ return _objectSpread2(_objectSpread2({
7522
7548
  walletId: asWalletId(object["walletId"]),
7523
- origin: asEntropyOrigin(object["origin"]),
7524
- words: asWords(object["words"]),
7549
+ origin,
7550
+ words: asWords(object["words"])
7551
+ }, flagged ? { passphrase: true } : {}), {}, {
7525
7552
  backup,
7526
7553
  createdAt: asCreatedAt(object["createdAt"])
7527
- };
7554
+ });
7528
7555
  }
7529
7556
  function parseDataKeyHeader(text) {
7530
7557
  const object = headerObject(text);
@@ -8126,6 +8153,34 @@
8126
8153
  function openRecord(dek, record) {
8127
8154
  return dek.use((bytes) => open(bytes, record.sealed, recordContext(record.kind, record.id), record.header));
8128
8155
  }
8156
+ /**
8157
+ * Splits an `entropy` record's plaintext at the header's entropy length; a payload the header does
8158
+ * not describe (a passphrase flag without bytes, bytes without the flag, more than
8159
+ * {@link MAX_PASSPHRASE_BYTES}) is `integrity`. Copies — the caller wipes `plaintext` and both
8160
+ * parts.
8161
+ */
8162
+ function splitWalletSecret(header, plaintext) {
8163
+ const entropyLength = header.words / 3 * 4;
8164
+ const extra = plaintext.length - entropyLength;
8165
+ if (!(header.passphrase === true ? extra >= 1 && extra <= 1024 : extra === 0)) throw new KernelError("integrity", "wallet record does not match its header");
8166
+ return {
8167
+ entropy: plaintext.slice(0, entropyLength),
8168
+ passphrase: header.passphrase === true ? plaintext.slice(entropyLength) : void 0
8169
+ };
8170
+ }
8171
+ /**
8172
+ * The only way to read an `entropy` record: opens it and splits it with {@link splitWalletSecret}.
8173
+ * The caller wipes both buffers.
8174
+ */
8175
+ function openWalletSecret(dek, record) {
8176
+ const header = parseEntropyHeader(record.header);
8177
+ const plaintext = openRecord(dek, record);
8178
+ try {
8179
+ return splitWalletSecret(header, plaintext);
8180
+ } finally {
8181
+ wipe(plaintext);
8182
+ }
8183
+ }
8129
8184
  function findRecord(image, kind, id) {
8130
8185
  const record = image.records.find((r) => r.kind === kind && r.id === id);
8131
8186
  if (record === void 0) throw new KernelError("not-found", "record not found");
@@ -8188,9 +8243,33 @@
8188
8243
  origin: header.origin,
8189
8244
  words: header.words,
8190
8245
  backup: header.backup,
8246
+ passphrase: header.passphrase === true,
8191
8247
  createdAt: header.createdAt
8192
8248
  };
8193
8249
  }
8250
+ // packages/wallet-kernel/src/commands/passphrase.ts
8251
+ init_utils$2();
8252
+ /**
8253
+ * A wire passphrase (raw UTF-8, wiped here) as the bytes the vault stores: NFKD-normalized, never
8254
+ * trimmed — spaces are significant in BIP-39 — and 1–1024 bytes after normalization.
8255
+ */
8256
+ function normalizePassphrase(wire) {
8257
+ const normalized = utf8ToBytes$1(decodeUtf8Secret(wire).normalize("NFKD"));
8258
+ if (normalized.length === 0 || normalized.length > 1024) {
8259
+ normalized.fill(0);
8260
+ throw new KernelError("invalid-input", "passphrase must be 1-1024 bytes");
8261
+ }
8262
+ return normalized;
8263
+ }
8264
+ /** The text `seedFromMnemonic` takes for stored passphrase bytes (`undefined` → no passphrase). */
8265
+ function passphraseText(passphrase) {
8266
+ if (passphrase === void 0) return "";
8267
+ try {
8268
+ return new TextDecoder("utf-8", { fatal: true }).decode(passphrase);
8269
+ } catch (_unused) {
8270
+ throw new KernelError("integrity", "wallet passphrase is not valid UTF-8");
8271
+ }
8272
+ }
8194
8273
  // node_modules/.bun/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/der.js
8195
8274
  var _0n$8, DERErr, _DER, DER;
8196
8275
  var init_der = __esmMin((() => {
@@ -12251,15 +12330,15 @@ zoo`.split("\n"));
12251
12330
  wipe(password, salt);
12252
12331
  }
12253
12332
  }
12254
- async function seedFromEntropy(entropy, pbkdf2) {
12255
- return seedFromMnemonic(mnemonicFromEntropy(entropy), "", pbkdf2);
12333
+ async function seedFromEntropy(entropy, passphrase, pbkdf2) {
12334
+ return seedFromMnemonic(mnemonicFromEntropy(entropy), passphrase, pbkdf2);
12256
12335
  }
12257
12336
  /**
12258
- * Derives the BIP-39 seed of `entropy`, runs `use`, wipes the seed on every path. Does not own
12259
- * `entropy`.
12337
+ * Derives the BIP-39 seed of `entropy` and `passphrase` ("" for none), runs `use`, wipes the seed
12338
+ * on every path. Does not own `entropy`.
12260
12339
  */
12261
- async function withSeed(pbkdf2, entropy, use) {
12262
- const seed = await seedFromEntropy(entropy, pbkdf2);
12340
+ async function withSeed(pbkdf2, entropy, passphrase, use) {
12341
+ const seed = await seedFromEntropy(entropy, passphrase, pbkdf2);
12263
12342
  try {
12264
12343
  return await use(seed);
12265
12344
  } finally {
@@ -12432,13 +12511,17 @@ zoo`.split("\n"));
12432
12511
  }
12433
12512
  };
12434
12513
  // packages/wallet-kernel/src/commands/vault.ts
12435
- /** Opens a wallet's sealed entropy record, then withSeed; wipes the entropy on every path. */
12514
+ /**
12515
+ * Opens a wallet's sealed entropy record, then withSeed over its entropy and passphrase; wipes both
12516
+ * on every path.
12517
+ */
12436
12518
  async function withWalletSeed(pbkdf2, dek, record, use) {
12437
- const entropy = openRecord(dek, record);
12519
+ const { entropy, passphrase } = openWalletSecret(dek, record);
12438
12520
  try {
12439
- return await withSeed(pbkdf2, entropy, use);
12521
+ return await withSeed(pbkdf2, entropy, passphraseText(passphrase), use);
12440
12522
  } finally {
12441
12523
  wipe(entropy);
12524
+ if (passphrase !== void 0) wipe(passphrase);
12442
12525
  }
12443
12526
  }
12444
12527
  var EMPTY_IMAGE$1 = {
@@ -12527,8 +12610,9 @@ zoo`.split("\n"));
12527
12610
  }
12528
12611
  // packages/wallet-kernel/src/commands/wallets.ts
12529
12612
  init_utils$2();
12530
- async function deriveWalletMaterial(platform, entropy) {
12531
- return withSeed(platform.pbkdf2, entropy, (seed) => {
12613
+ init_objectSpread2();
12614
+ async function deriveWalletMaterial(platform, entropy, passphrase) {
12615
+ return withSeed(platform.pbkdf2, entropy, passphraseText(passphrase), (seed) => {
12532
12616
  const master = masterKey(seed);
12533
12617
  return {
12534
12618
  master,
@@ -12536,13 +12620,14 @@ zoo`.split("\n"));
12536
12620
  };
12537
12621
  });
12538
12622
  }
12539
- /** Entropy → master → walletId. `entropy` is not consumed. */
12540
- async function walletMaterial(platform, entropy, origin, words) {
12541
- const { master, walletId } = await deriveWalletMaterial(platform, entropy);
12623
+ /** Entropy and passphrase → master → walletId. Neither buffer is consumed. */
12624
+ async function walletMaterial(platform, entropy, passphrase, origin, words) {
12625
+ const { master, walletId } = await deriveWalletMaterial(platform, entropy, passphrase);
12542
12626
  try {
12543
12627
  return {
12544
12628
  walletId,
12545
12629
  entropy,
12630
+ passphrase,
12546
12631
  words,
12547
12632
  origin
12548
12633
  };
@@ -12551,24 +12636,28 @@ zoo`.split("\n"));
12551
12636
  }
12552
12637
  }
12553
12638
  function walletInfoOf(material, backup, createdAt) {
12554
- return walletInfo({
12639
+ return walletInfo(_objectSpread2(_objectSpread2({
12555
12640
  walletId: material.walletId,
12556
12641
  origin: material.origin,
12557
12642
  words: material.words,
12558
- backup,
12559
- createdAt
12560
- });
12643
+ backup
12644
+ }, material.passphrase === void 0 ? {} : { passphrase: true }), {}, { createdAt }));
12645
+ }
12646
+ /** The `entropy` record payload: the entropy, then the passphrase bytes when there are any. */
12647
+ function walletSecretPlaintext(entropy, passphrase) {
12648
+ return passphrase === void 0 ? new Uint8Array(entropy) : concatBytes$3(entropy, passphrase);
12561
12649
  }
12562
12650
  /** The entropy record for a new wallet, sealed under `dek`. Consumes nothing. */
12563
12651
  function walletRecord(ctx, dek, material, backup, createdAt) {
12564
- const header = encodeHeader({
12652
+ const header = encodeHeader(_objectSpread2(_objectSpread2({
12565
12653
  walletId: material.walletId,
12566
12654
  origin: material.origin,
12567
- words: material.words,
12655
+ words: material.words
12656
+ }, material.passphrase === void 0 ? {} : { passphrase: true }), {}, {
12568
12657
  backup,
12569
12658
  createdAt
12570
- });
12571
- return sealRecord(ctx.platform, dek, "entropy", material.walletId, header, new Uint8Array(material.entropy));
12659
+ }));
12660
+ return sealRecord(ctx.platform, dek, "entropy", material.walletId, header, walletSecretPlaintext(material.entropy, material.passphrase));
12572
12661
  }
12573
12662
  /**
12574
12663
  * The dynamic gate on every "create or import" command: with an uninitialized vault `factor` is
@@ -12724,6 +12813,14 @@ zoo`.split("\n"));
12724
12813
  };
12725
12814
  }
12726
12815
  async function confirmMnemonic(ctx, params) {
12816
+ const passphrase = params.passphrase === void 0 ? void 0 : normalizePassphrase(params.passphrase);
12817
+ try {
12818
+ return await confirmWithPassphrase(ctx, params, passphrase);
12819
+ } finally {
12820
+ if (passphrase !== void 0) wipe(passphrase);
12821
+ }
12822
+ }
12823
+ async function confirmWithPassphrase(ctx, params, passphrase) {
12727
12824
  const allMatch = ctx.session.getDraft(params.draft).expected.every((expected, i) => {
12728
12825
  const answer = params.answers[i];
12729
12826
  return answer !== void 0 && answer.length === expected.length && equalBytes$3(answer, expected);
@@ -12733,7 +12830,7 @@ zoo`.split("\n"));
12733
12830
  const taken = ctx.session.takeDraft(params.draft);
12734
12831
  try {
12735
12832
  const entropy = taken.entropy.use((bytes) => new Uint8Array(bytes));
12736
- const material = await walletMaterial(ctx.platform, entropy, "mnemonic", taken.words);
12833
+ const material = await walletMaterial(ctx.platform, entropy, passphrase, "mnemonic", taken.words);
12737
12834
  try {
12738
12835
  ensureNewWallet(ctx, material);
12739
12836
  const createdAt = ctx.platform.now();
@@ -12776,9 +12873,20 @@ zoo`.split("\n"));
12776
12873
  }
12777
12874
  async function importMnemonic(ctx, params, requestSession) {
12778
12875
  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));
12876
+ let text;
12781
12877
  try {
12878
+ text = decodeUtf8Secret(params.mnemonic);
12879
+ } catch (error) {
12880
+ var _params$passphrase;
12881
+ (_params$passphrase = params.passphrase) === null || _params$passphrase === void 0 || _params$passphrase.fill(0);
12882
+ throw error;
12883
+ }
12884
+ let passphrase;
12885
+ let entropy;
12886
+ try {
12887
+ passphrase = params.passphrase === void 0 ? void 0 : normalizePassphrase(params.passphrase);
12888
+ entropy = entropyFromMnemonic(text);
12889
+ const material = await walletMaterial(ctx.platform, entropy, passphrase, "mnemonic", mnemonicWords(entropy));
12782
12890
  ensureNewWallet(ctx, material);
12783
12891
  const createdAt = ctx.platform.now();
12784
12892
  const record = walletRecord(ctx, gated.dek, material, "mnemonic", createdAt);
@@ -12788,7 +12896,8 @@ zoo`.split("\n"));
12788
12896
  session
12789
12897
  };
12790
12898
  } finally {
12791
- wipe(entropy);
12899
+ if (entropy !== void 0) wipe(entropy);
12900
+ if (passphrase !== void 0) wipe(passphrase);
12792
12901
  }
12793
12902
  }
12794
12903
  var PURPOSE_WALLET = 1;
@@ -12862,7 +12971,7 @@ zoo`.split("\n"));
12862
12971
  throw error;
12863
12972
  }
12864
12973
  const entropy = entropyFromPrf(prf.prfWallet);
12865
- const material = await walletMaterial(ctx.platform, entropy, "passkey", 12);
12974
+ const material = await walletMaterial(ctx.platform, entropy, void 0, "passkey", 12);
12866
12975
  try {
12867
12976
  ensureNewWallet(ctx, material);
12868
12977
  const createdAt = ctx.platform.now();
@@ -12893,6 +13002,7 @@ zoo`.split("\n"));
12893
13002
  init_sha2();
12894
13003
  init_utils$2();
12895
13004
  init_base();
13005
+ init_objectSpread2();
12896
13006
  var PASSWORD_ITERATIONS = 6e5;
12897
13007
  /** Payload tag byte: wallet entry. */
12898
13008
  var ORIGIN_BYTE = {
@@ -12990,26 +13100,21 @@ zoo`.split("\n"));
12990
13100
  for (const record of ctx.image.records) {
12991
13101
  if (record.kind !== "entropy") continue;
12992
13102
  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
- }
13103
+ const { entropy, passphrase } = openWalletSecret(dek, record);
13104
+ passphrase === null || passphrase === void 0 || passphrase.fill(0);
13105
+ wallets.push(_objectSpread2(_objectSpread2({
13106
+ walletId: record.id,
13107
+ origin: header.origin,
13108
+ words: header.words
13109
+ }, header.passphrase === true ? { passphrase: true } : {}), {}, { entropy }));
13005
13110
  }
13006
13111
  return {
13007
13112
  wallets,
13008
- header: JSON.stringify({ wallets: wallets.map(({ walletId, origin, words }) => ({
13113
+ header: JSON.stringify({ wallets: wallets.map(({ walletId, origin, words, passphrase }) => _objectSpread2({
13009
13114
  walletId,
13010
13115
  origin,
13011
13116
  words
13012
- })) })
13117
+ }, passphrase === true ? { passphrase } : {})) })
13013
13118
  };
13014
13119
  } catch (error) {
13015
13120
  for (const wallet of wallets) wallet.entropy.fill(0);
@@ -13214,6 +13319,21 @@ zoo`.split("\n"));
13214
13319
  * down in one commit so a torn restore can't leave half the secrets.
13215
13320
  */
13216
13321
  async function restoreBackup(ctx, params, requestSession) {
13322
+ const passphrases = /* @__PURE__ */ new Map();
13323
+ try {
13324
+ return await restoreWithPassphrases(ctx, params, requestSession, passphrases);
13325
+ } finally {
13326
+ var _params$passphrases;
13327
+ for (const passphrase of passphrases.values()) passphrase.fill(0);
13328
+ for (const entry of (_params$passphrases = params.passphrases) !== null && _params$passphrases !== void 0 ? _params$passphrases : []) entry.passphrase.fill(0);
13329
+ }
13330
+ }
13331
+ async function restoreWithPassphrases(ctx, params, requestSession, passphrases) {
13332
+ var _params$passphrases2;
13333
+ for (const entry of (_params$passphrases2 = params.passphrases) !== null && _params$passphrases2 !== void 0 ? _params$passphrases2 : []) {
13334
+ if (passphrases.has(entry.walletId)) throw new KernelError("invalid-input", `duplicate passphrase for wallet ${entry.walletId}`);
13335
+ passphrases.set(entry.walletId, normalizePassphrase(entry.passphrase));
13336
+ }
13217
13337
  const envelope = parseEnvelope(params.envelope);
13218
13338
  const credentials = envelope.factors.flatMap((f) => f.kind === "passkey" ? [b64$2.dec(f.credentialId)] : []);
13219
13339
  const bek = await bekFromFactor(ctx.platform, envelope, await backupMaterial(ctx, params.backupFactor, credentials));
@@ -13230,9 +13350,15 @@ zoo`.split("\n"));
13230
13350
  plaintext.fill(0);
13231
13351
  throw new KernelError("integrity", "backup: payload does not match header");
13232
13352
  }
13353
+ const flagged = new Set(header.wallets.filter((w) => w.passphrase === true).map((w) => w.walletId));
13354
+ for (const walletId of passphrases.keys()) if (!flagged.has(walletId)) {
13355
+ plaintext.fill(0);
13356
+ throw new KernelError("invalid-input", `wallet ${walletId} has no passphrase`);
13357
+ }
13233
13358
  const gated = gate(ctx, params.factor, requestSession);
13234
13359
  const records = [];
13235
13360
  const restored = [];
13361
+ const passphraseRequired = [];
13236
13362
  let committed = false;
13237
13363
  try {
13238
13364
  try {
@@ -13242,7 +13368,13 @@ zoo`.split("\n"));
13242
13368
  if (expected === void 0) throw new KernelError("integrity", "backup: wallet count mismatch");
13243
13369
  const words = mnemonicWords(wallet.entropy);
13244
13370
  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);
13371
+ const passphrase = passphrases.get(expected.walletId);
13372
+ if (passphrase === void 0 && expected.passphrase === true) {
13373
+ if (!ctx.image.records.some((r) => r.kind === "entropy" && r.id === expected.walletId)) passphraseRequired.push(expected.walletId);
13374
+ continue;
13375
+ }
13376
+ const material = await walletMaterial(ctx.platform, wallet.entropy, passphrase, wallet.origin, words);
13377
+ if (passphrase !== void 0 && material.walletId !== expected.walletId) throw new KernelError("invalid-input", `passphrase does not match wallet ${expected.walletId}`);
13246
13378
  if (material.walletId !== expected.walletId || material.origin !== expected.origin) throw new KernelError("integrity", "backup: derived walletId does not match header");
13247
13379
  if (ctx.image.records.some((r) => r.kind === "entropy" && r.id === material.walletId)) continue;
13248
13380
  const backup = material.origin === "passkey" ? "passkey" : "none";
@@ -13255,6 +13387,7 @@ zoo`.split("\n"));
13255
13387
  committed = true;
13256
13388
  return {
13257
13389
  wallets: restored,
13390
+ passphraseRequired,
13258
13391
  session
13259
13392
  };
13260
13393
  } catch (error) {
@@ -13272,25 +13405,29 @@ zoo`.split("\n"));
13272
13405
  // packages/wallet-kernel/src/commands/secrets.ts
13273
13406
  init_utils$2();
13274
13407
  init_objectSpread2();
13275
- /** One-shot export: the mnemonic as UTF-8 bytes (the host wraps it in a wipeable buffer). */
13408
+ /**
13409
+ * One-shot export: the mnemonic as UTF-8 bytes, plus the NFKD passphrase bytes when the wallet has
13410
+ * one (the host wraps both in wipeable buffers).
13411
+ */
13276
13412
  async function exportMnemonic(ctx, params, requestSession) {
13277
13413
  const { dek } = ctx.session.require(requestSession);
13278
13414
  await verifyFactor(ctx.platform, ctx.image, params.verify, dek, corePromptFor(ctx.platform.keystore, "export-mnemonic"));
13279
13415
  const record = findRecord(ctx.image, "entropy", params.walletId);
13280
13416
  const header = parseEntropyHeader(record.header);
13281
- const entropy = openRecord(dek, record);
13417
+ const { entropy, passphrase } = openWalletSecret(dek, record);
13282
13418
  try {
13283
13419
  const exported = utf8ToBytes$1(mnemonicFromEntropy(entropy));
13284
13420
  if (header.backup !== "mnemonic") {
13285
13421
  const updated = encodeHeader(_objectSpread2(_objectSpread2({}, header), {}, { backup: "mnemonic" }));
13286
13422
  await ctx.commit([{
13287
13423
  op: "put-record",
13288
- record: sealRecord(ctx.platform, dek, "entropy", params.walletId, updated, new Uint8Array(entropy))
13424
+ record: sealRecord(ctx.platform, dek, "entropy", params.walletId, updated, walletSecretPlaintext(entropy, passphrase))
13289
13425
  }]);
13290
13426
  }
13291
- return exported;
13427
+ return _objectSpread2({ mnemonic: exported }, passphrase === void 0 ? {} : { passphrase: new Uint8Array(passphrase) });
13292
13428
  } finally {
13293
13429
  wipe(entropy);
13430
+ if (passphrase !== void 0) wipe(passphrase);
13294
13431
  }
13295
13432
  }
13296
13433
  /**
@@ -14661,7 +14798,7 @@ zoo`.split("\n"));
14661
14798
  }
14662
14799
  });
14663
14800
  };
14664
- string = (len, le = false) => validate$4(apply(createBytes(len, le), utf8$1), (value) => {
14801
+ string = (len, le = false) => validate$4(apply(createBytes(len, le), utf8$2), (value) => {
14665
14802
  if (typeof value !== "string") throw new Error(`expected string, got ${typeof value}`);
14666
14803
  return value;
14667
14804
  });
@@ -14843,8 +14980,1357 @@ zoo`.split("\n"));
14843
14980
  return ed25519.verify(signature, message, this.publicKeyRaw);
14844
14981
  }
14845
14982
  };
14846
- // packages/wallet-chains/dist/index.mjs
14983
+ // node_modules/.bun/@qntx+siwx@0.8.0/node_modules/@qntx/siwx/dist/message-B6snBU4B.mjs
14984
+ init_defineProperty();
14985
+ init_objectSpread2();
14986
+ var SYNTAX_MESSAGES = {
14987
+ InvalidUtf8: "invalid UTF-8",
14988
+ CarriageReturn: "CR not allowed",
14989
+ MissingPreamble: "missing preamble marker",
14990
+ MissingAccountSuffix: "missing account suffix",
14991
+ UnexpectedEof: "unexpected end of input",
14992
+ ExpectedBlankLine: "expected blank line",
14993
+ UnexpectedTrailing: "unexpected trailing content",
14994
+ ResourceSyntax: "resource line must start with '- '",
14995
+ InvalidEnvelope: "invalid off-chain message envelope"
14996
+ };
14997
+ function describe(info) {
14998
+ if (info.code === "MessageTooLarge") return `message exceeds maximum size of ${info.max} bytes, got ${info.length}`;
14999
+ if (info.code === "Syntax") return info.syntax === "MissingField" ? `invalid message syntax: missing ${info.field}` : `invalid message syntax: ${SYNTAX_MESSAGES[info.syntax]}`;
15000
+ if (info.code === "InvalidField") return `invalid ${info.field}: ${info.reason}`;
15001
+ if (info.code === "Mismatch") return `${info.field} mismatch: expected ${info.expected}, got ${JSON.stringify(info.actual)}`;
15002
+ if (info.code === "InvalidOrigin") return "invalid origin: not a serialized web origin";
15003
+ if (info.code === "Expired") return "message expired";
15004
+ if (info.code === "NotYetValid") return "message not yet valid";
15005
+ if (info.code === "IssuedAtTooOld") return "issued-at exceeds max age";
15006
+ if (info.code === "InvalidSignature") return `invalid signature: ${info.reason}`;
15007
+ if (info.code === "VerificationFailed") return "verification failed";
15008
+ if (info.code === "Unsupported") return `unsupported: ${info.reason}`;
15009
+ return `backend error: ${info.reason}`;
15010
+ }
15011
+ /** The single error type thrown by every library failure. */
15012
+ var SiwxError = class extends Error {
15013
+ constructor(info) {
15014
+ super(describe(info));
15015
+ _defineProperty(
15016
+ this,
15017
+ /** Structured payload; `code` matches the Rust `Error::code()`. */
15018
+ "info",
15019
+ void 0
15020
+ );
15021
+ this.name = "SiwxError";
15022
+ this.info = info;
15023
+ }
15024
+ /** Stable variant name for cross-language contract tests. */
15025
+ get code() {
15026
+ return this.info.code;
15027
+ }
15028
+ };
15029
+ /** `SiwxError` constructor shorthand for layout failures. */
15030
+ function syntaxError(syntax, field) {
15031
+ if (syntax === "MissingField") {
15032
+ if (field === void 0) throw new RangeError("MissingField requires a field");
15033
+ return new SiwxError({
15034
+ code: "Syntax",
15035
+ syntax,
15036
+ field
15037
+ });
15038
+ }
15039
+ return new SiwxError({
15040
+ code: "Syntax",
15041
+ syntax
15042
+ });
15043
+ }
15044
+ /** `SiwxError` constructor shorthand for a malformed field value. */
15045
+ function fieldError(field, reason) {
15046
+ return new SiwxError({
15047
+ code: "InvalidField",
15048
+ field,
15049
+ reason
15050
+ });
15051
+ }
15052
+ /** `SiwxError` constructor shorthand for a binding mismatch. */
15053
+ function mismatchError(field, expected, actual) {
15054
+ return new SiwxError({
15055
+ code: "Mismatch",
15056
+ field,
15057
+ expected,
15058
+ actual
15059
+ });
15060
+ }
15061
+ //! CAIP-10 `account_id`: `namespace ":" reference ":" address`.
15062
+ /** Every character matches — avoids spread-on-string for Hermes-safe lint. */
15063
+ function everyChar(s, test) {
15064
+ const pred = typeof test === "function" ? test : (c) => test.test(c);
15065
+ for (const c of s) if (!pred(c)) return false;
15066
+ return true;
15067
+ }
15068
+ /**
15069
+ * Validate and build an `account_id`.
15070
+ *
15071
+ * `namespace` is CAIP-2 `[-a-z0-9]{3,8}`; `reference` is `[-_a-zA-Z0-9]{1,32}`; `address` is
15072
+ * `[-.%a-zA-Z0-9]{1,128}`.
15073
+ *
15074
+ * @throws {SiwxError} `InvalidField` `chainId` for bad namespace/reference, `address` for a bad
15075
+ * address.
15076
+ */
15077
+ function createAccountId(namespace, reference, address) {
15078
+ if (namespace.length < 3 || namespace.length > 8 || !everyChar(namespace, /[a-z0-9-]/)) throw fieldError("chainId", "bad CAIP-2 namespace");
15079
+ if (reference.length === 0 || reference.length > 32 || !everyChar(reference, /[A-Za-z0-9_-]/)) throw fieldError("chainId", "bad CAIP-2 reference");
15080
+ 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");
15081
+ return Object.freeze({
15082
+ namespace,
15083
+ reference,
15084
+ address,
15085
+ id: `${namespace}:${reference}:${address}`
15086
+ });
15087
+ }
15088
+ //! Shared pieces of the CAIP-122 text layouts (eip4361 and SIWS): the
15089
+ //! preamble infix/suffix and the optional trailing tags in fixed ABNF order.
15090
+ var MID = " wants you to sign in with your ";
15091
+ var SUFFIX = " account:";
15092
+ /**
15093
+ * Parse the optional trailing tags in fixed ABNF order: `Expiration Time`, `Not Before`, `Request
15094
+ * ID`, `Resources` (with `- ` items). Each may appear at most once and only in this order.
15095
+ */
15096
+ function optionalTags(lines, start) {
15097
+ let i = start;
15098
+ let resources;
15099
+ const take = (tag) => {
15100
+ const line = lines[i];
15101
+ if (line !== void 0 && line.startsWith(tag)) {
15102
+ i++;
15103
+ return line.slice(tag.length);
15104
+ }
15105
+ };
15106
+ const expirationTime = take("Expiration Time: ");
15107
+ const notBefore = take("Not Before: ");
15108
+ const requestId = take("Request ID: ");
15109
+ if (lines[i] === "Resources:") {
15110
+ i++;
15111
+ const list = [];
15112
+ while (i < lines.length) {
15113
+ var _lines$i;
15114
+ const r = (_lines$i = lines[i]) !== null && _lines$i !== void 0 ? _lines$i : "";
15115
+ if (r.startsWith("- ")) {
15116
+ list.push(r.slice(2));
15117
+ i++;
15118
+ } else if (r.startsWith("-")) throw syntaxError("ResourceSyntax");
15119
+ else throw syntaxError("UnexpectedTrailing");
15120
+ }
15121
+ resources = list;
15122
+ }
15123
+ if (i !== lines.length) throw syntaxError("UnexpectedTrailing");
15124
+ return {
15125
+ expirationTime,
15126
+ notBefore,
15127
+ requestId,
15128
+ resources
15129
+ };
15130
+ }
15131
+ /** Maximum accepted signing-text size in bytes. */
15132
+ var MAX_MESSAGE_BYTES = 16384;
15133
+ //! RFC 3986 URI validation, matching Rust `iri-string` exactly:
15134
+ //! `URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]`,
15135
+ //! `authority = [ userinfo "@" ] host [ ":" port ]`, strict dec-octet
15136
+ //! (no leading zeros), IPv6 / IPvFuture / pct-encoding.
15137
+ var UNRESERVED = /[A-Za-z0-9._~-]/;
15138
+ var SUB_DELIM = /[!$&'()*+,;=]/;
15139
+ var HEX$1 = /[0-9A-Fa-f]/;
15140
+ function isScheme(s) {
15141
+ if (s.length === 0 || !/[A-Za-z]/.test(s.charAt(0))) return false;
15142
+ for (const c of s) if (!/[A-Za-z0-9+.-]/.test(c)) return false;
15143
+ return true;
15144
+ }
15145
+ /** `(unreserved / pct-encoded / sub-delims / ":" / "@")*`, ASCII only. */
15146
+ function everyPct(s, allowed) {
15147
+ for (let i = 0; i < s.length; i++) {
15148
+ const c = s.charAt(i);
15149
+ if (c === "%") {
15150
+ if (i + 2 >= s.length || !HEX$1.test(s.charAt(i + 1)) || !HEX$1.test(s.charAt(i + 2))) return false;
15151
+ i += 2;
15152
+ continue;
15153
+ }
15154
+ if (!allowed(c)) return false;
15155
+ }
15156
+ return true;
15157
+ }
15158
+ function isUserinfo(s) {
15159
+ return everyPct(s, (c) => UNRESERVED.test(c) || SUB_DELIM.test(c) || c === ":");
15160
+ }
15161
+ function isRegName(s) {
15162
+ return everyPct(s, (c) => UNRESERVED.test(c) || SUB_DELIM.test(c));
15163
+ }
15164
+ function isPcharString(s) {
15165
+ return everyPct(s, (c) => UNRESERVED.test(c) || SUB_DELIM.test(c) || c === ":" || c === "@");
15166
+ }
15167
+ /** Dec-octet: 0-255, no leading zeros (RFC 3986 strict). */
15168
+ function isDecOctet(s) {
15169
+ if (s.length === 0 || s.length > 3) return false;
15170
+ if (s.length > 1 && s.startsWith("0")) return false;
15171
+ for (const c of s) if (!/[0-9]/.test(c)) return false;
15172
+ return Number(s) <= 255;
15173
+ }
15174
+ function isIPv4(s) {
15175
+ const parts = s.split(".");
15176
+ return parts.length === 4 && parts.every(isDecOctet);
15177
+ }
15178
+ function isH16(s) {
15179
+ return s.length > 0 && s.length <= 4 && s.split("").every((c) => HEX$1.test(c));
15180
+ }
15181
+ /**
15182
+ * Count h16-equivalent groups in one half of an IPv6 literal (an IPv4 tail counts as two groups and
15183
+ * must be last).
15184
+ */
15185
+ function ipv6GroupCount(part) {
15186
+ if (part === "") return 0;
15187
+ let n = 0;
15188
+ const groups = part.split(":");
15189
+ for (const g of groups) {
15190
+ if (g === "") return -1;
15191
+ if (g.includes(".")) {
15192
+ if (g !== groups.at(-1) || !isIPv4(g)) return -1;
15193
+ n += 2;
15194
+ } else if (isH16(g)) n += 1;
15195
+ else return -1;
15196
+ }
15197
+ return n;
15198
+ }
15199
+ /** IPv6address per RFC 3986, with optional IPv4 tail and `::` compression. */
15200
+ function isIPv6(s) {
15201
+ var _halves$, _halves$2, _halves$3;
15202
+ const halves = s.split("::");
15203
+ if (halves.length > 2) return false;
15204
+ if (halves.length === 1) return ipv6GroupCount((_halves$ = halves[0]) !== null && _halves$ !== void 0 ? _halves$ : "") === 8;
15205
+ const hn = ipv6GroupCount((_halves$2 = halves[0]) !== null && _halves$2 !== void 0 ? _halves$2 : "");
15206
+ const tn = ipv6GroupCount((_halves$3 = halves[1]) !== null && _halves$3 !== void 0 ? _halves$3 : "");
15207
+ if (hn === -1 || tn === -1) return false;
15208
+ return hn + tn < 8;
15209
+ }
15210
+ function isIPvFuture(s) {
15211
+ var _m$;
15212
+ const m = /^[vV]([0-9A-Fa-f]+)\.(.*)$/.exec(s);
15213
+ if (m === null) return false;
15214
+ const tail = (_m$ = m[2]) !== null && _m$ !== void 0 ? _m$ : "";
15215
+ if (tail.length === 0) return false;
15216
+ for (const c of tail) if (!(UNRESERVED.test(c) || SUB_DELIM.test(c) || c === ":")) return false;
15217
+ return true;
15218
+ }
15219
+ /** `host = IP-literal / IPv4address / reg-name` (first-match-wins). */
15220
+ function isHost(s) {
15221
+ if (s.startsWith("[")) return s.endsWith("]") && (isIPv6(s.slice(1, -1)) || isIPvFuture(s.slice(1, -1)));
15222
+ if (isIPv4(s)) return true;
15223
+ return isRegName(s);
15224
+ }
15225
+ /** `authority = [ userinfo "@" ] host [ ":" port ]`. */
15226
+ function isAuthority(s) {
15227
+ let rest = s;
15228
+ const at = rest.lastIndexOf("@");
15229
+ if (at !== -1) {
15230
+ if (rest.indexOf("@") !== at) return false;
15231
+ if (!isUserinfo(rest.slice(0, at))) return false;
15232
+ rest = rest.slice(at + 1);
15233
+ }
15234
+ let host = rest;
15235
+ let port = "";
15236
+ if (rest.startsWith("[")) {
15237
+ const end = rest.indexOf("]");
15238
+ if (end === -1) return false;
15239
+ host = rest.slice(0, end + 1);
15240
+ const after = rest.slice(end + 1);
15241
+ if (after !== "") {
15242
+ if (!after.startsWith(":")) return false;
15243
+ port = after.slice(1);
15244
+ }
15245
+ } else {
15246
+ const colon = rest.lastIndexOf(":");
15247
+ if (colon !== -1) {
15248
+ host = rest.slice(0, colon);
15249
+ port = rest.slice(colon + 1);
15250
+ if (host.includes(":")) return false;
15251
+ }
15252
+ }
15253
+ if (port !== "" && !port.split("").every((c) => /[0-9]/.test(c))) return false;
15254
+ return isHost(host);
15255
+ }
15256
+ /** `path` characters: each segment is `*pchar`. */
15257
+ function isPath$1(s) {
15258
+ for (const seg of s.split("/")) if (!isPcharString(seg)) return false;
15259
+ return true;
15260
+ }
15261
+ /** `query` / `fragment`: `*( pchar / "/" / "?" )`. */
15262
+ function isQueryOrFragment(s) {
15263
+ return everyPct(s, (c) => UNRESERVED.test(c) || SUB_DELIM.test(c) || c === ":" || c === "@" || c === "/" || c === "?");
15264
+ }
15265
+ /** RFC 3986 `URI` (absolute, with scheme). */
15266
+ function isUri(s) {
15267
+ const hash = s.indexOf("#");
15268
+ if (hash !== -1 && s.includes("#", hash + 1)) return false;
15269
+ let rest = s;
15270
+ let fragment;
15271
+ if (hash !== -1) {
15272
+ fragment = rest.slice(hash + 1);
15273
+ rest = rest.slice(0, hash);
15274
+ }
15275
+ const q = rest.indexOf("?");
15276
+ let query;
15277
+ if (q !== -1) {
15278
+ query = rest.slice(q + 1);
15279
+ rest = rest.slice(0, q);
15280
+ }
15281
+ const colon = rest.indexOf(":");
15282
+ if (colon === -1) return false;
15283
+ if (!isScheme(rest.slice(0, colon))) return false;
15284
+ let hier = rest.slice(colon + 1);
15285
+ if (hier.startsWith("//")) {
15286
+ hier = hier.slice(2);
15287
+ const slash = hier.indexOf("/");
15288
+ const authority = slash === -1 ? hier : hier.slice(0, slash);
15289
+ const path = slash === -1 ? "" : hier.slice(slash);
15290
+ if (!isAuthority(authority)) return false;
15291
+ if (!isPath$1(path)) return false;
15292
+ } else if (!isPath$1(hier)) return false;
15293
+ if (query !== void 0 && !isQueryOrFragment(query)) return false;
15294
+ if (fragment !== void 0 && !isQueryOrFragment(fragment)) return false;
15295
+ return true;
15296
+ }
15297
+ //! Lexical RFC 3339 `date-time` + instant, mirroring Rust `Timestamp`.
15298
+ var SHAPE = /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/;
15299
+ /** Days since 1970-01-01 for a proleptic-Gregorian y/m/d (Hinnant's algorithm). */
15300
+ function daysFromCivil(y, m, d) {
15301
+ const yy = m <= 2 ? y - 1 : y;
15302
+ const era = Math.floor((yy >= 0 ? yy : yy - 399) / 400);
15303
+ const yoe = yy - era * 400;
15304
+ const doy = Math.floor((153 * (m > 2 ? m - 3 : m + 9) + 2) / 5) + d - 1;
15305
+ const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;
15306
+ return era * 146097 + doe - 719468;
15307
+ }
15308
+ function daysInMonth(year, month) {
15309
+ var _ref;
15310
+ return (_ref = [
15311
+ 31,
15312
+ year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28,
15313
+ 31,
15314
+ 30,
15315
+ 31,
15316
+ 30,
15317
+ 31,
15318
+ 31,
15319
+ 30,
15320
+ 31,
15321
+ 30,
15322
+ 31
15323
+ ][month - 1]) !== null && _ref !== void 0 ? _ref : 0;
15324
+ }
15325
+ /**
15326
+ * Parse an RFC 3339 `date-time`; `undefined` when invalid.
15327
+ *
15328
+ * Requires `T`/`t` and `Z`/`z`/`±HH:MM`; optional fraction; real calendar validity (Feb 30
15329
+ * rejected); leap second `:60` rejected like Rust `time`.
15330
+ */
15331
+ function parseTimestamp(s) {
15332
+ const m = SHAPE.exec(s);
15333
+ if (m === null) return;
15334
+ const [, ys, mos, ds, hs, mis, ss, frac, tz] = m;
15335
+ const year = Number(ys);
15336
+ const month = Number(mos);
15337
+ const day = Number(ds);
15338
+ const hour = Number(hs);
15339
+ const minute = Number(mis);
15340
+ const second = Number(ss);
15341
+ if (month < 1 || month > 12) return;
15342
+ if (day < 1 || day > daysInMonth(year, month)) return;
15343
+ if (hour > 23 || minute > 59 || second > 59) return;
15344
+ let ms = daysFromCivil(year, month, day) * 864e5 + hour * 36e5 + minute * 6e4 + second * 1e3;
15345
+ if (frac !== void 0 && frac.length > 1) ms += Number(frac.slice(1, 4).padEnd(3, "0"));
15346
+ if (tz !== void 0 && tz !== "Z" && tz !== "z") {
15347
+ const oh = Number(tz.slice(1, 3));
15348
+ const om = Number(tz.slice(4, 6));
15349
+ if (oh > 23 || om > 59) return;
15350
+ const off = (oh * 60 + om) * 6e4;
15351
+ ms += tz.startsWith("+") ? -off : off;
15352
+ }
15353
+ if (!Number.isFinite(ms)) return;
15354
+ return {
15355
+ lexeme: s,
15356
+ epochMs: Math.trunc(ms)
15357
+ };
15358
+ }
15359
+ //! Strict UTF-8 helpers.
15360
+ //!
15361
+ //! `TextEncoder`/`TextDecoder` exist on every supported platform (Node,
15362
+ //! browsers, Hermes). Decoding must reject exactly what Rust
15363
+ //! `str::from_utf8` rejects — overlongs, surrogates, > U+10FFFF,
15364
+ //! truncated sequences — so `fatal: true` is used (which follows the
15365
+ //! WHATWG fatal algorithm and rejects all of those).
15366
+ var encoder$1 = new TextEncoder();
15367
+ var fatalDecoder = new TextDecoder("utf-8", { fatal: true });
15368
+ /** Encode `text` as UTF-8 bytes. */
15369
+ function utf8Encode(text) {
15370
+ return encoder$1.encode(text);
15371
+ }
15372
+ /** Decode `bytes` as strict UTF-8; `undefined` on any invalid sequence. */
15373
+ function utf8Decode(bytes) {
15374
+ try {
15375
+ return fatalDecoder.decode(bytes);
15376
+ } catch (_unused2) {
15377
+ return;
15378
+ }
15379
+ }
15380
+ /** UTF-8 byte length of `text` (JS string length counts UTF-16 code units). */
15381
+ function utf8ByteLength(text) {
15382
+ return encoder$1.encode(text).length;
15383
+ }
15384
+ //! CAIP-122 abstract data model: lexical `MessageFields` and the
15385
+ //! validated `Message` produced by `createMessage` (single validation
15386
+ //! path, same check order as Rust `Message::new`).
15387
+ var STATEMENT_CHARS = /* @__PURE__ */ new Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;= ");
15388
+ function isCaip10Address(s) {
15389
+ if (s.length === 0 || s.length > 128) return false;
15390
+ for (const c of s) if (!/[A-Za-z0-9]/.test(c) && c !== "-" && c !== "." && c !== "%") return false;
15391
+ return true;
15392
+ }
15393
+ /**
15394
+ * Validate `fields` and return a frozen [`Message`].
15395
+ *
15396
+ * Check order (as Rust `Message::new`): scheme, domain, address, statement, uri, version, chainId,
15397
+ * nonce, issuedAt, expirationTime, notBefore, requestId, resources.
15398
+ *
15399
+ * @throws {SiwxError} `InvalidField` naming the first invalid field.
15400
+ */
15401
+ function createMessage(fields) {
15402
+ if (fields.scheme !== void 0 && !isScheme(fields.scheme)) throw fieldError("scheme", "not an RFC 3986 scheme");
15403
+ if (fields.domain.length === 0) throw fieldError("domain", "empty");
15404
+ if (fields.domain.includes("@")) throw fieldError("domain", "userinfo not allowed");
15405
+ if (fields.domain.startsWith(":")) throw fieldError("domain", "empty host");
15406
+ if (!isAuthority(fields.domain)) throw fieldError("domain", "not an RFC 3986 authority");
15407
+ if (!isCaip10Address(fields.address)) throw fieldError("address", fields.address.length === 0 || fields.address.length > 128 ? "expected 1..=128 characters" : "bad CAIP-10 charset");
15408
+ if (fields.statement !== void 0) {
15409
+ if (utf8ByteLength(fields.statement) > 4096) throw fieldError("statement", "exceeds maximum size");
15410
+ for (const c of fields.statement) if (!STATEMENT_CHARS.has(c)) throw fieldError("statement", "must be RFC 3986 reserved / unreserved / SP");
15411
+ }
15412
+ checkUri(fields.uri, "uri");
15413
+ if (fields.version !== "1") throw fieldError("version", "must be \"1\"");
15414
+ if (fields.chainId.length === 0) throw fieldError("chainId", "empty");
15415
+ if (fields.chainId.length > 64) throw fieldError("chainId", "exceeds 64 characters");
15416
+ for (const c of fields.chainId) if (!/[A-Za-z0-9]/.test(c) && c !== "-" && c !== "_" && c !== ":") throw fieldError("chainId", "bad charset");
15417
+ if (fields.nonce.length < 8) throw fieldError("nonce", "too short");
15418
+ for (const c of fields.nonce) if (!/[A-Za-z0-9]/.test(c)) throw fieldError("nonce", "not ASCII alphanumeric");
15419
+ if (parseTimestamp(fields.issuedAt) === void 0) throw fieldError("issuedAt", "not an RFC 3339 date-time");
15420
+ if (fields.expirationTime !== void 0 && parseTimestamp(fields.expirationTime) === void 0) throw fieldError("expirationTime", "not an RFC 3339 date-time");
15421
+ if (fields.notBefore !== void 0 && parseTimestamp(fields.notBefore) === void 0) throw fieldError("notBefore", "not an RFC 3339 date-time");
15422
+ if (fields.requestId !== void 0) {
15423
+ if (utf8ByteLength(fields.requestId) > 128) throw fieldError("requestId", "exceeds maximum size");
15424
+ if (!isPcharString(fields.requestId)) throw fieldError("requestId", "must be RFC 3986 *pchar");
15425
+ }
15426
+ if (fields.resources !== void 0) {
15427
+ if (fields.resources.length > 32) throw fieldError("resources", "too many");
15428
+ for (const uri of fields.resources) checkUri(uri, "resources");
15429
+ }
15430
+ const out = _objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2({
15431
+ domain: fields.domain,
15432
+ address: fields.address,
15433
+ uri: fields.uri,
15434
+ version: fields.version,
15435
+ chainId: fields.chainId,
15436
+ nonce: fields.nonce,
15437
+ issuedAt: fields.issuedAt
15438
+ }, 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 });
15439
+ return Object.freeze(out);
15440
+ }
15441
+ function checkUri(uri, field) {
15442
+ if (uri.length === 0) throw fieldError(field, "empty");
15443
+ if (utf8ByteLength(uri) > 2048) throw fieldError(field, "exceeds maximum size");
15444
+ if (!isUri(uri)) throw fieldError(field, "not an RFC 3986 URI");
15445
+ }
15446
+ // node_modules/.bun/@qntx+siwx@0.8.0/node_modules/@qntx/siwx/dist/rolldown-runtime-D8jQpDG7.mjs
15447
+ var __defProp = Object.defineProperty;
15448
+ var __exportAll = (all, no_symbols) => {
15449
+ let target = {};
15450
+ for (var name in all) __defProp(target, name, {
15451
+ get: all[name],
15452
+ enumerable: true
15453
+ });
15454
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
15455
+ return target;
15456
+ };
15457
+ // node_modules/.bun/@qntx+siwx@0.8.0/node_modules/@qntx/siwx/dist/eip4361-Bf5VppSi.mjs
15458
+ init_objectSpread2();
15459
+ //! ERC-4361 signing-text layout: `format` and its strict inverse `parse`.
15460
+ //! For every accepted text `t`, `format(label, parse(t).message) === t`
15461
+ //! byte-for-byte.
15462
+ function takeTag(line, tag, field) {
15463
+ if (!line.startsWith(tag)) throw syntaxError("MissingField", field);
15464
+ return line.slice(tag.length);
15465
+ }
15466
+ /** Render `message` as an ERC-4361 signing text under `label`. */
15467
+ function format$2(label, message) {
15468
+ let out = "";
15469
+ if (message.scheme !== void 0) out += `${message.scheme}://`;
15470
+ out += `${message.domain + MID + label + SUFFIX}\n`;
15471
+ out += `${message.address}\n\n`;
15472
+ if (message.statement !== void 0) out += `${message.statement}\n`;
15473
+ out += "\n";
15474
+ out += `URI: ${message.uri}\n`;
15475
+ out += `Version: ${message.version}\n`;
15476
+ out += `Chain ID: ${message.chainId}\n`;
15477
+ out += `Nonce: ${message.nonce}\n`;
15478
+ out += `Issued At: ${message.issuedAt}`;
15479
+ if (message.expirationTime !== void 0) out += `\nExpiration Time: ${message.expirationTime}`;
15480
+ if (message.notBefore !== void 0) out += `\nNot Before: ${message.notBefore}`;
15481
+ if (message.requestId !== void 0) out += `\nRequest ID: ${message.requestId}`;
15482
+ if (message.resources !== void 0) {
15483
+ out += "\nResources:";
15484
+ for (const uri of message.resources) out += `\n- ${uri}`;
15485
+ }
15486
+ return out;
15487
+ }
15488
+ /** Parse `text` into a label + validated message. */
15489
+ function parse$1(text) {
15490
+ const byteLength = utf8ByteLength(text);
15491
+ if (byteLength > 16384) throw new SiwxError({
15492
+ code: "MessageTooLarge",
15493
+ length: byteLength,
15494
+ max: MAX_MESSAGE_BYTES
15495
+ });
15496
+ if (text.includes("\r")) throw syntaxError("CarriageReturn");
15497
+ const lines = text.split("\n");
15498
+ let i = 0;
15499
+ const next = () => {
15500
+ const l = lines[i++];
15501
+ if (l === void 0) throw syntaxError("UnexpectedEof");
15502
+ return l;
15503
+ };
15504
+ const preamble = next();
15505
+ const mid = preamble.indexOf(MID);
15506
+ if (mid === -1) throw syntaxError("MissingPreamble");
15507
+ const head = preamble.slice(0, mid);
15508
+ const tail = preamble.slice(mid + MID.length);
15509
+ if (!tail.endsWith(" account:")) throw syntaxError("MissingAccountSuffix");
15510
+ const label = tail.slice(0, -SUFFIX.length);
15511
+ if (label.length === 0) throw fieldError("label", "empty");
15512
+ let scheme;
15513
+ let domain;
15514
+ const proto = head.indexOf("://");
15515
+ if (proto === -1) domain = head;
15516
+ else {
15517
+ scheme = head.slice(0, proto);
15518
+ domain = head.slice(proto + 3);
15519
+ }
15520
+ const address = next();
15521
+ let blanks = 0;
15522
+ while (lines[i + blanks] === "") blanks++;
15523
+ let statement;
15524
+ if (blanks === 1) {
15525
+ i += 1;
15526
+ statement = next();
15527
+ if (next() !== "") throw syntaxError("ExpectedBlankLine");
15528
+ } else if (blanks === 2) i += 2;
15529
+ else if (blanks === 3) {
15530
+ i += 3;
15531
+ statement = "";
15532
+ } else throw syntaxError("ExpectedBlankLine");
15533
+ const uri = takeTag(next(), "URI: ", "uri");
15534
+ const version = takeTag(next(), "Version: ", "version");
15535
+ const chainId = takeTag(next(), "Chain ID: ", "chainId");
15536
+ const nonce = takeTag(next(), "Nonce: ", "nonce");
15537
+ const issuedAt = takeTag(next(), "Issued At: ", "issuedAt");
15538
+ const opt = optionalTags(lines, i);
15539
+ return {
15540
+ label,
15541
+ message: createMessage(_objectSpread2({
15542
+ scheme,
15543
+ domain,
15544
+ address,
15545
+ statement,
15546
+ uri,
15547
+ version,
15548
+ chainId,
15549
+ nonce,
15550
+ issuedAt
15551
+ }, opt))
15552
+ };
15553
+ }
15554
+ /** [`parseBytes`]: UTF-8 strictness then [`parse`]. */
15555
+ function parseBytes$1(bytes) {
15556
+ if (bytes.length > 16384) throw new SiwxError({
15557
+ code: "MessageTooLarge",
15558
+ length: bytes.length,
15559
+ max: MAX_MESSAGE_BYTES
15560
+ });
15561
+ const text = utf8Decode(bytes);
15562
+ if (text === void 0) throw syntaxError("InvalidUtf8");
15563
+ return parse$1(text);
15564
+ }
15565
+ /** [`parseBytes`] plus a required preamble `label`. */
15566
+ function parseLabeled(label, signed) {
15567
+ const parsed = parseBytes$1(signed);
15568
+ if (parsed.label !== label) throw mismatchError("label", label, parsed.label);
15569
+ return parsed.message;
15570
+ }
15571
+ // node_modules/.bun/@noble+hashes@2.4.0/node_modules/@noble/hashes/sha3.js
15572
+ init__u64();
15573
+ init_utils$2();
14847
15574
  init_defineProperty();
15575
+ var _0n$4 = BigInt(0);
15576
+ var _1n$3 = BigInt(1);
15577
+ var _2n$2 = BigInt(2);
15578
+ var _7n = BigInt(7);
15579
+ var _256n = BigInt(256);
15580
+ var _0x71n = BigInt(113);
15581
+ var SHA3_PI = [];
15582
+ var SHA3_ROTL = [];
15583
+ var _SHA3_IOTA = [];
15584
+ for (let round = 0, R = _1n$3, x = 1, y = 0; round < 24; round++) {
15585
+ [x, y] = [y, (2 * x + 3 * y) % 5];
15586
+ SHA3_PI.push(2 * (5 * y + x));
15587
+ SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
15588
+ let t = _0n$4;
15589
+ for (let j = 0; j < 7; j++) {
15590
+ R = (R << _1n$3 ^ (R >> _7n) * _0x71n) % _256n;
15591
+ if (R & _2n$2) t ^= _1n$3 << (_1n$3 << BigInt(j)) - _1n$3;
15592
+ }
15593
+ _SHA3_IOTA.push(t);
15594
+ }
15595
+ var IOTAS = split(_SHA3_IOTA, true);
15596
+ var SHA3_IOTA_H = IOTAS[0];
15597
+ var SHA3_IOTA_L = IOTAS[1];
15598
+ var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
15599
+ var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
15600
+ var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
15601
+ var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
15602
+ var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
15603
+ var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
15604
+ var B = /* @__PURE__ */ new Uint32Array(10);
15605
+ /**
15606
+ * `keccakf1600` internal permutation, additionally allows adjusting the round count.
15607
+ * @param s - 5x5 Keccak state encoded as 25 lanes split into 50 uint32 words
15608
+ * in this file's local little-endian lane-word order
15609
+ * @param rounds - number of rounds to execute
15610
+ * @throws On wrong argument types. {@link TypeError}
15611
+ * @throws On wrong argument ranges or values. {@link RangeError}
15612
+ * @throws If `rounds` is outside the supported `1..24` range. {@link Error}
15613
+ * @example
15614
+ * Permute a Keccak state with the default 24 rounds.
15615
+ * ```ts
15616
+ * keccakP(new Uint32Array(50));
15617
+ * ```
15618
+ */
15619
+ function keccakP(s, rounds = 24) {
15620
+ if (!(s instanceof Uint32Array)) throw new TypeError("\"s\" expected Uint32Array(50), got type=" + typeof s);
15621
+ if (s.length !== 50) throw new RangeError("\"s\" expected Uint32Array(50), got length=" + s.length);
15622
+ anumber$2(rounds, "rounds");
15623
+ if (rounds < 1 || rounds > 24) throw new Error("\"rounds\" expected integer 1..24");
15624
+ for (let round = 24 - rounds; round < 24; round++) {
15625
+ for (let x = 0; x < 10; x++) B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
15626
+ for (let x = 0; x < 10; x += 2) {
15627
+ const idx1 = (x + 8) % 10;
15628
+ const idx0 = (x + 2) % 10;
15629
+ const B0 = B[idx0];
15630
+ const B1 = B[idx0 + 1];
15631
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
15632
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
15633
+ for (let y = 0; y < 50; y += 10) {
15634
+ s[x + y] ^= Th;
15635
+ s[x + y + 1] ^= Tl;
15636
+ }
15637
+ }
15638
+ let curH = s[2];
15639
+ let curL = s[3];
15640
+ for (let t = 0; t < 24; t++) {
15641
+ const shift = SHA3_ROTL[t];
15642
+ const Th = rotlH(curH, curL, shift);
15643
+ const Tl = rotlL(curH, curL, shift);
15644
+ const PI = SHA3_PI[t];
15645
+ curH = s[PI];
15646
+ curL = s[PI + 1];
15647
+ s[PI] = Th;
15648
+ s[PI + 1] = Tl;
15649
+ }
15650
+ for (let y = 0; y < 50; y += 10) {
15651
+ const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3];
15652
+ s[y] ^= ~s[y + 2] & s[y + 4];
15653
+ s[y + 1] ^= ~s[y + 3] & s[y + 5];
15654
+ s[y + 2] ^= ~s[y + 4] & s[y + 6];
15655
+ s[y + 3] ^= ~s[y + 5] & s[y + 7];
15656
+ s[y + 4] ^= ~s[y + 6] & s[y + 8];
15657
+ s[y + 5] ^= ~s[y + 7] & s[y + 9];
15658
+ s[y + 6] ^= ~s[y + 8] & b0;
15659
+ s[y + 7] ^= ~s[y + 9] & b1;
15660
+ s[y + 8] ^= ~b0 & b2;
15661
+ s[y + 9] ^= ~b1 & b3;
15662
+ }
15663
+ s[0] ^= SHA3_IOTA_H[round];
15664
+ s[1] ^= SHA3_IOTA_L[round];
15665
+ }
15666
+ clean(B);
15667
+ }
15668
+ /**
15669
+ * Keccak sponge function.
15670
+ * @param blockLen - absorb/squeeze rate in bytes
15671
+ * @param suffix - domain separation suffix byte
15672
+ * @param outputLen - default digest length in bytes. This base sponge only
15673
+ * requires a non-negative integer; wrappers that need positive output
15674
+ * lengths must enforce that themselves.
15675
+ * @param enableXOF - whether XOF output is allowed
15676
+ * @param rounds - number of Keccak-f rounds
15677
+ * @example
15678
+ * Build a sponge state, absorb bytes, then finalize a digest.
15679
+ * ```ts
15680
+ * const hash = new Keccak(136, 0x06, 32);
15681
+ * hash.update(new Uint8Array([1, 2, 3]));
15682
+ * hash.digest();
15683
+ * ```
15684
+ */
15685
+ var Keccak = class Keccak {
15686
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
15687
+ _defineProperty(this, "state", void 0);
15688
+ _defineProperty(this, "pos", 0);
15689
+ _defineProperty(this, "posOut", 0);
15690
+ _defineProperty(this, "finished", false);
15691
+ _defineProperty(this, "state32", void 0);
15692
+ _defineProperty(this, "destroyed", false);
15693
+ _defineProperty(this, "blockLen", void 0);
15694
+ _defineProperty(this, "suffix", void 0);
15695
+ _defineProperty(this, "outputLen", void 0);
15696
+ _defineProperty(this, "canXOF", void 0);
15697
+ _defineProperty(this, "enableXOF", false);
15698
+ _defineProperty(this, "rounds", void 0);
15699
+ anumber$2(blockLen, "blockLen");
15700
+ anumber$2(suffix, "suffix");
15701
+ anumber$2(rounds, "rounds");
15702
+ abool$1(enableXOF, "enableXOF");
15703
+ this.blockLen = blockLen;
15704
+ this.suffix = suffix;
15705
+ this.outputLen = outputLen;
15706
+ this.enableXOF = enableXOF;
15707
+ this.canXOF = enableXOF;
15708
+ this.rounds = rounds;
15709
+ anumber$2(outputLen, "outputLen");
15710
+ if (!(0 < blockLen && blockLen < 200)) throw new Error("\"blockLen\" must be 1..199");
15711
+ this.state = /* @__PURE__ */ new Uint8Array(200);
15712
+ this.state32 = u32$1(this.state);
15713
+ }
15714
+ clone() {
15715
+ return this._cloneInto();
15716
+ }
15717
+ keccak() {
15718
+ swap32IfBE(this.state32);
15719
+ keccakP(this.state32, this.rounds);
15720
+ swap32IfBE(this.state32);
15721
+ this.posOut = 0;
15722
+ this.pos = 0;
15723
+ }
15724
+ update(data) {
15725
+ aexists(this);
15726
+ abytes$2(data);
15727
+ const { blockLen, state, state32 } = this;
15728
+ const len = data.length;
15729
+ const canUseU32 = blockLen % 4 === 0 && data.byteOffset % 4 === 0;
15730
+ const blockLen32 = blockLen / 4;
15731
+ const data32 = canUseU32 && len >= blockLen ? u32$1(data) : void 0;
15732
+ for (let pos = 0; pos < len;) {
15733
+ if (data32 !== void 0 && this.pos === 0 && pos % 4 === 0 && len - pos >= blockLen) {
15734
+ for (let i = 0, o = pos / 4; i < blockLen32; i++) state32[i] ^= data32[o + i];
15735
+ pos += blockLen;
15736
+ this.pos = blockLen;
15737
+ this.keccak();
15738
+ continue;
15739
+ }
15740
+ const take = Math.min(blockLen - this.pos, len - pos);
15741
+ for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++];
15742
+ if (this.pos === blockLen) this.keccak();
15743
+ }
15744
+ return this;
15745
+ }
15746
+ finish() {
15747
+ if (this.finished) return;
15748
+ this.finished = true;
15749
+ const { state, suffix, pos, blockLen } = this;
15750
+ state[pos] ^= suffix;
15751
+ if ((suffix & 128) !== 0 && pos === blockLen - 1) this.keccak();
15752
+ state[blockLen - 1] ^= 128;
15753
+ this.keccak();
15754
+ }
15755
+ writeInto(out) {
15756
+ aexists(this, false);
15757
+ abytes$2(out);
15758
+ this.finish();
15759
+ const bufferOut = this.state;
15760
+ const { blockLen } = this;
15761
+ for (let pos = 0, len = out.length; pos < len;) {
15762
+ if (this.posOut >= blockLen) this.keccak();
15763
+ const take = Math.min(blockLen - this.posOut, len - pos);
15764
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
15765
+ this.posOut += take;
15766
+ pos += take;
15767
+ }
15768
+ return out;
15769
+ }
15770
+ xofInto(out) {
15771
+ if (!this.enableXOF) throw new Error("XOF is not enabled");
15772
+ return this.writeInto(out);
15773
+ }
15774
+ xof(bytes) {
15775
+ anumber$2(bytes);
15776
+ return this.xofInto(new Uint8Array(bytes));
15777
+ }
15778
+ digestInto(out) {
15779
+ aoutput(out, this);
15780
+ if (this.finished) throw new Error("digest() was already called");
15781
+ this.writeInto(out.length === this.outputLen ? out : out.subarray(0, this.outputLen));
15782
+ this.destroy();
15783
+ }
15784
+ digest() {
15785
+ const out = new Uint8Array(this.outputLen);
15786
+ this.digestInto(out);
15787
+ return out;
15788
+ }
15789
+ destroy() {
15790
+ this.destroyed = true;
15791
+ clean(this.state);
15792
+ }
15793
+ _cloneInto(to) {
15794
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
15795
+ to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
15796
+ to.blockLen = blockLen;
15797
+ to.state32.set(this.state32);
15798
+ to.pos = this.pos;
15799
+ to.posOut = this.posOut;
15800
+ to.finished = this.finished;
15801
+ to.rounds = rounds;
15802
+ to.suffix = suffix;
15803
+ to.outputLen = outputLen;
15804
+ to.enableXOF = enableXOF;
15805
+ to.canXOF = this.canXOF;
15806
+ to.destroyed = this.destroyed;
15807
+ return to;
15808
+ }
15809
+ };
15810
+ var genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);
15811
+ /**
15812
+ * Keccak-256 hash function. Different from SHA3-256.
15813
+ * @param msg - message bytes to hash
15814
+ * @param opts - Reserved hash options.
15815
+ * @returns Digest bytes.
15816
+ * @example
15817
+ * Hash a message with Keccak-256.
15818
+ * ```ts
15819
+ * keccak_256(new Uint8Array([97, 98, 99]));
15820
+ * ```
15821
+ */
15822
+ var keccak_256 = /* @__PURE__ */ genKeccak(1, 136, 32);
15823
+ // node_modules/.bun/@qntx+siwx@0.8.0/node_modules/@qntx/siwx/dist/evm.mjs
15824
+ init_utils$2();
15825
+ init_secp256k1();
15826
+ init_utils$1();
15827
+ //! EIP-55 / EVM address + chain-id rules, matching `siwx::evm`.
15828
+ var HEX40 = /^[0-9a-fA-F]{40}$/;
15829
+ /** EIP-55 checksum spelling of a `0x`-prefixed 40-hex address. */
15830
+ function toChecksumAddress(address) {
15831
+ if (!address.startsWith("0x")) throw fieldError("address", "expected 0x + 40 hex");
15832
+ const body = address.slice(2);
15833
+ if (!HEX40.test(body)) throw fieldError("address", "expected 0x + 40 hex");
15834
+ const lower = body.toLowerCase();
15835
+ const hash = keccak_256(utf8Encode(lower));
15836
+ let out = "0x";
15837
+ for (let i = 0; i < 40; i++) {
15838
+ var _hash$Math$floor;
15839
+ const c = lower.charAt(i);
15840
+ 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;
15841
+ out += /[a-f]/.test(c) && nibble >= 8 ? c.toUpperCase() : c;
15842
+ }
15843
+ return out;
15844
+ }
15845
+ var badAddress = () => fieldError("address", "expected 0x + 40 hex");
15846
+ /** Parse an EVM address to its 20 bytes under the canonical rule. */
15847
+ function parseEip55(address) {
15848
+ const bad = badAddress;
15849
+ if (!address.startsWith("0x")) throw bad();
15850
+ const hex = address.slice(2);
15851
+ if (!HEX40.test(hex)) throw bad();
15852
+ const hasLower = /[a-f]/.test(hex);
15853
+ const hasUpper = /[A-F]/.test(hex);
15854
+ if (hasLower && hasUpper && address !== toChecksumAddress(address)) throw fieldError("address", "bad EIP-55 checksum");
15855
+ return hexToBytes$3(hex);
15856
+ }
15857
+ /**
15858
+ * EVM `chain-id`: `[0-9]+`, no leading zero unless `"0"`, fits in `u64`.
15859
+ *
15860
+ * @throws {SiwxError} `InvalidField` `chainId`.
15861
+ */
15862
+ function parseEvmChainId(chainId) {
15863
+ if (chainId.length === 0) throw fieldError("chainId", "empty");
15864
+ if (!/^[0-9]+$/.test(chainId)) throw fieldError("chainId", "not decimal");
15865
+ if (chainId.length > 1 && chainId.startsWith("0")) throw fieldError("chainId", "leading zero");
15866
+ const value = BigInt(chainId);
15867
+ if (value > 18446744073709551615n) throw fieldError("chainId", "overflow");
15868
+ return value;
15869
+ }
15870
+ //! EIP-191 `personal_sign` verification.
15871
+ //!
15872
+ //! Decode order (cross-language contract, mirrored with Rust): length ≠
15873
+ //! 65 → `v ∉ {0,1,27,28}` → `r`/`s` equal to 0 or ≥ n → `s > n/2` (all
15874
+ //! `InvalidSignature`) → recovery failure or address mismatch →
15875
+ //! `VerificationFailed`.
15876
+ var N = secp256k1.Point.Fn.ORDER;
15877
+ var N_HALF = N / 2n;
15878
+ /** `keccak256("\x19Ethereum Signed Message:\n" + len + message)`. */
15879
+ function eip191Hash(message) {
15880
+ const prefix = utf8Encode(`\u0019Ethereum Signed Message:\n${message.length}`);
15881
+ const joined = new Uint8Array(prefix.length + message.length);
15882
+ joined.set(prefix);
15883
+ joined.set(message, prefix.length);
15884
+ return keccak_256(joined);
15885
+ }
15886
+ /** Verify a 65-byte `r‖s‖v` EIP-191 signature over `signed`. */
15887
+ function verifyEip191(message, signed, signature) {
15888
+ var _signature$;
15889
+ if (signature.length !== 65) throw new SiwxError({
15890
+ code: "InvalidSignature",
15891
+ reason: "EIP-191 signature must be 65 bytes"
15892
+ });
15893
+ const v = (_signature$ = signature[64]) !== null && _signature$ !== void 0 ? _signature$ : 0;
15894
+ if (v !== 0 && v !== 1 && v !== 27 && v !== 28) throw new SiwxError({
15895
+ code: "InvalidSignature",
15896
+ reason: "v must be 0, 1, 27 or 28"
15897
+ });
15898
+ const r = bytesToNumberBE(signature.subarray(0, 32));
15899
+ const s = bytesToNumberBE(signature.subarray(32, 64));
15900
+ if (r === 0n || r >= N || s === 0n || s >= N) throw new SiwxError({
15901
+ code: "InvalidSignature",
15902
+ reason: "r/s out of range"
15903
+ });
15904
+ if (s > N_HALF) throw new SiwxError({
15905
+ code: "InvalidSignature",
15906
+ reason: "high-s (EIP-2)"
15907
+ });
15908
+ const hash = eip191Hash(signed);
15909
+ let recovered;
15910
+ try {
15911
+ recovered = keccak_256(secp256k1.Signature.fromBytes(signature.subarray(0, 64), "compact").addRecoveryBit(v % 27).recoverPublicKey(hash).toBytes(false).subarray(1)).subarray(12);
15912
+ } catch (_unused) {
15913
+ throw new SiwxError({ code: "VerificationFailed" });
15914
+ }
15915
+ const expected = parseEip55(message.address);
15916
+ if (!equalBytes$2(recovered, expected)) throw new SiwxError({ code: "VerificationFailed" });
15917
+ }
15918
+ //! On-chain smart-account verification: the ERC-6492 universal validator via a
15919
+ //! deployless `eth_call`. Covers deployed ERC-1271 accounts, counterfactual
15920
+ //! ERC-6492 accounts and EOAs. Providers are injected; the library builds no
15921
+ //! transports and applies no timeouts — transport policy belongs to the
15922
+ //! provider owner.
15923
+ var BYTECODE = hexToBytes$2("608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572");
15924
+ /** Abi.encode(address signer, bytes32 hash, bytes signature). */
15925
+ function deploylessCalldata(signer, hash, signature) {
15926
+ const addr = hexToBytes$2(signer.slice(2));
15927
+ const word = 32;
15928
+ const out = new Uint8Array(BYTECODE.length + 96 + word + Math.ceil(signature.length / word) * word);
15929
+ const bc = BYTECODE;
15930
+ out.set(bc, 0);
15931
+ let o = bc.length;
15932
+ out.set(addr, o + (word - addr.length));
15933
+ o += word;
15934
+ out.set(hash, o);
15935
+ o += word;
15936
+ out.set(numberToBytesBE(BigInt(96), word), o);
15937
+ o += word;
15938
+ out.set(numberToBytesBE(BigInt(signature.length), word), o);
15939
+ out.set(signature, o + word);
15940
+ return out;
15941
+ }
15942
+ var malformed$1 = () => new SiwxError({
15943
+ code: "Backend",
15944
+ reason: "malformed eth_call result"
15945
+ });
15946
+ /**
15947
+ * Interpret a deployless validator `eth_call` result: `0x01` or a 32-byte word of zeros ending `01`
15948
+ * is valid; the same shapes ending `00` are `false`; anything else is malformed.
15949
+ */
15950
+ function decodeResult(hex) {
15951
+ const data = hex === "" || hex === "0x" ? /* @__PURE__ */ new Uint8Array(0) : hexToBytes$2(hex.slice(2));
15952
+ if (data.length === 1) {
15953
+ if (data[0] === 1) return true;
15954
+ if (data[0] === 0) return false;
15955
+ throw malformed$1();
15956
+ }
15957
+ if (data.length === 32) {
15958
+ for (let i = 0; i < 31; i++) if (data[i] !== 0) throw malformed$1();
15959
+ if (data[31] === 1) return true;
15960
+ if (data[31] === 0) return false;
15961
+ }
15962
+ throw malformed$1();
15963
+ }
15964
+ /** JSON-RPC code 3 (EIP-1474 execution reverted) ⇒ signature rejected. */
15965
+ var codeOf = (error) => typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
15966
+ function isRevert(error) {
15967
+ const code = codeOf(error);
15968
+ return typeof code === "number" && code === 3;
15969
+ }
15970
+ function backend$1() {
15971
+ return new SiwxError({
15972
+ code: "Backend",
15973
+ reason: "RPC request failed"
15974
+ });
15975
+ }
15976
+ var MAGIC = (() => {
15977
+ const m = /* @__PURE__ */ new Uint8Array(32);
15978
+ for (let i = 0; i < m.length; i++) m[i] = i % 2 === 0 ? 100 : 146;
15979
+ return m;
15980
+ })();
15981
+ /** True when `signature` ends with the ERC-6492 detection suffix. */
15982
+ function has6492MagicSuffix(signature) {
15983
+ if (signature.length < MAGIC.length) return false;
15984
+ for (let i = 0; i < MAGIC.length; i++) if (signature[signature.length - MAGIC.length + i] !== MAGIC[i]) return false;
15985
+ return true;
15986
+ }
15987
+ /** `eth_chainId` as a decimal number; malformed → `Backend`. */
15988
+ async function providerChainId(provider) {
15989
+ let result;
15990
+ try {
15991
+ result = await provider.request({ method: "eth_chainId" });
15992
+ } catch (_unused2) {
15993
+ throw backend$1();
15994
+ }
15995
+ if (typeof result !== "string" || !/^0x[0-9a-fA-F]+$/.test(result)) throw backend$1();
15996
+ return BigInt(result);
15997
+ }
15998
+ /**
15999
+ * Deployless `eth_call` against the vendored universal validator. `provider`'s chain id must
16000
+ * already equal the message chain id (the caller caches the binding).
16001
+ */
16002
+ async function verifyOnChain(provider, message, signed, signature) {
16003
+ parseEip55(message.address);
16004
+ const hash = eip191Hash(signed);
16005
+ const data = `0x${bytesToHex$3(deploylessCalldata(message.address, hash, signature))}`;
16006
+ let result;
16007
+ try {
16008
+ result = await provider.request({
16009
+ method: "eth_call",
16010
+ params: [{
16011
+ data,
16012
+ input: data
16013
+ }, "latest"]
16014
+ });
16015
+ } catch (error) {
16016
+ throw isRevert(error) ? new SiwxError({ code: "VerificationFailed" }) : backend$1();
16017
+ }
16018
+ if (typeof result !== "string" || !/^0x[0-9a-fA-F]*$/.test(result)) throw backend$1();
16019
+ if (!decodeResult(result)) throw new SiwxError({ code: "VerificationFailed" });
16020
+ }
16021
+ //! `@qntx/siwx/evm` — EIP-155 (`eip155`) namespace profile.
16022
+ //!
16023
+ //! `account()` emits the canonical EIP-55 checksum spelling, so
16024
+ //! lowercase / uppercase / checksummed spellings of the same address map
16025
+ //! to the same `AccountId`.
16026
+ var CHAIN_NAME = "Ethereum";
16027
+ var NAMESPACE = "eip155";
16028
+ function evmAccount(message) {
16029
+ parseEip55(message.address);
16030
+ parseEvmChainId(message.chainId);
16031
+ return createAccountId(NAMESPACE, message.chainId, toChecksumAddress(message.address));
16032
+ }
16033
+ /**
16034
+ * Ethereum (`eip155`) namespace. EIP-191 runs fully offline; a signature carrying the ERC-6492
16035
+ * magic suffix, or an EIP-191 failure on a chain with a configured provider, takes the on-chain
16036
+ * universal-validator path. Providers own all transport policy — the library applies no timeouts —
16037
+ * and `eth_chainId` is bound to the message chain id (cached per provider on success only) before
16038
+ * any `eth_call`.
16039
+ */
16040
+ function evm(options) {
16041
+ var _options$rpc;
16042
+ const rpc = (_options$rpc = options === null || options === void 0 ? void 0 : options.rpc) !== null && _options$rpc !== void 0 ? _options$rpc : {};
16043
+ const verifiedChains = /* @__PURE__ */ new Set();
16044
+ const providerFor = (chainId) => {
16045
+ const key = parseEvmChainId(chainId).toString(10);
16046
+ return rpc[key];
16047
+ };
16048
+ const onChain = async (message, signed, signature, eip191Err) => {
16049
+ const key = parseEvmChainId(message.chainId).toString(10);
16050
+ const provider = providerFor(message.chainId);
16051
+ if (provider === void 0) throw eip191Err !== null && eip191Err !== void 0 ? eip191Err : new SiwxError({
16052
+ code: "Unsupported",
16053
+ reason: "EIP-6492 requires RPC"
16054
+ });
16055
+ if (!verifiedChains.has(key)) {
16056
+ const rpcChain = await providerChainId(provider);
16057
+ if (rpcChain !== parseEvmChainId(message.chainId)) throw new SiwxError({
16058
+ code: "Mismatch",
16059
+ field: "chainId",
16060
+ expected: key,
16061
+ actual: rpcChain.toString()
16062
+ });
16063
+ verifiedChains.add(key);
16064
+ }
16065
+ await verifyOnChain(provider, message, signed, signature);
16066
+ };
16067
+ return {
16068
+ namespace: NAMESPACE,
16069
+ label: CHAIN_NAME,
16070
+ account: evmAccount,
16071
+ format(message) {
16072
+ evmAccount(message);
16073
+ return format$2(CHAIN_NAME, message);
16074
+ },
16075
+ parse(signed) {
16076
+ return parseLabeled(CHAIN_NAME, signed);
16077
+ },
16078
+ verify: async (message, signed, signature) => {
16079
+ if (has6492MagicSuffix(signature)) {
16080
+ await onChain(message, signed, signature, void 0);
16081
+ return;
16082
+ }
16083
+ try {
16084
+ verifyEip191(message, signed, signature);
16085
+ } catch (error) {
16086
+ if (error instanceof SiwxError && providerFor(message.chainId) !== void 0) {
16087
+ await onChain(message, signed, signature, error);
16088
+ return;
16089
+ }
16090
+ throw error;
16091
+ }
16092
+ }
16093
+ };
16094
+ }
16095
+ // node_modules/.bun/@qntx+siwx@0.8.0/node_modules/@qntx/siwx/dist/svm.mjs
16096
+ init_utils$1();
16097
+ init_base();
16098
+ init_objectSpread2();
16099
+ /** Solana address rules: canonical on-curve Ed25519 key in base58. */
16100
+ /**
16101
+ * Decode `address` as a base58 (Bitcoin alphabet) string of 32–44 chars that decodes to exactly 32
16102
+ * bytes.
16103
+ *
16104
+ * @throws {SiwxError} `InvalidField` `address`.
16105
+ */
16106
+ function addressBytes(address) {
16107
+ if (address.length < 32 || address.length > 44) throw fieldError("address", "expected 32–44 base58 chars");
16108
+ let bytes;
16109
+ try {
16110
+ bytes = base58.decode(address);
16111
+ } catch (_unused) {
16112
+ throw fieldError("address", "invalid base58");
16113
+ }
16114
+ if (bytes.length !== 32) throw fieldError("address", "expected 32 bytes");
16115
+ return bytes;
16116
+ }
16117
+ /**
16118
+ * The canonical, non-identity, prime-order-subgroup Ed25519 point for `bytes` (decompress →
16119
+ * recompress byte equality proves canonicity).
16120
+ *
16121
+ * @throws {SiwxError} `InvalidField` `address`.
16122
+ */
16123
+ function canonicalPoint(bytes) {
16124
+ let point;
16125
+ try {
16126
+ point = ed25519.Point.fromBytes(bytes);
16127
+ } catch (_unused2) {
16128
+ throw fieldError("address", "invalid Ed25519 pubkey");
16129
+ }
16130
+ if (point.equals(ed25519.Point.ZERO)) throw fieldError("address", "identity pubkey");
16131
+ if (!point.isTorsionFree()) throw fieldError("address", "not in the prime-order subgroup");
16132
+ if (!equalBytes$2(point.toBytes(), bytes)) throw fieldError("address", "non-canonical pubkey");
16133
+ }
16134
+ /**
16135
+ * Validate that `address` is a canonical, non-identity, prime-order-subgroup Ed25519 verifying key
16136
+ * in base58 form.
16137
+ *
16138
+ * @throws {SiwxError} `InvalidField` `address`.
16139
+ */
16140
+ function validateAddress(address) {
16141
+ canonicalPoint(addressBytes(address));
16142
+ }
16143
+ ed25519.Point.CURVE().n;
16144
+ ed25519.Point;
16145
+ /** SIWS (Sign-In-With-Solana) text layout — Phantom ABNF, LF only. */
16146
+ var siws_exports = /* @__PURE__ */ __exportAll({
16147
+ format: () => format$1,
16148
+ parse: () => parse,
16149
+ parseBytes: () => parseBytes
16150
+ });
16151
+ var LABEL = "Solana";
16152
+ /**
16153
+ * Format `message` as a SIWS signing text.
16154
+ *
16155
+ * @throws {SiwxError} `InvalidField` `scheme` (SIWS has none) or `statement` (empty).
16156
+ */
16157
+ function format$1(message) {
16158
+ if (message.scheme !== void 0) throw new SiwxError({
16159
+ code: "InvalidField",
16160
+ field: "scheme",
16161
+ reason: "not supported by SIWS"
16162
+ });
16163
+ if (message.statement !== void 0) {
16164
+ if (message.statement === "") throw new SiwxError({
16165
+ code: "InvalidField",
16166
+ field: "statement",
16167
+ reason: "empty"
16168
+ });
16169
+ if (message.statement.startsWith("URI: ")) throw new SiwxError({
16170
+ code: "InvalidField",
16171
+ field: "statement",
16172
+ reason: "ambiguous with the URI: tag"
16173
+ });
16174
+ }
16175
+ let out = `${message.domain}${MID}${LABEL}${SUFFIX}\n${message.address}`;
16176
+ if (message.statement !== void 0) out += `\n\n${message.statement}`;
16177
+ out += `\n\nURI: ${message.uri}`;
16178
+ out += `\nVersion: ${message.version}`;
16179
+ out += `\nChain ID: ${message.chainId}`;
16180
+ out += `\nNonce: ${message.nonce}`;
16181
+ out += `\nIssued At: ${message.issuedAt}`;
16182
+ if (message.expirationTime !== void 0) out += `\nExpiration Time: ${message.expirationTime}`;
16183
+ if (message.notBefore !== void 0) out += `\nNot Before: ${message.notBefore}`;
16184
+ if (message.requestId !== void 0) out += `\nRequest ID: ${message.requestId}`;
16185
+ if (message.resources !== void 0) {
16186
+ out += "\nResources:";
16187
+ for (const r of message.resources) out += `\n- ${r}`;
16188
+ }
16189
+ return out;
16190
+ }
16191
+ var missingUri = () => syntaxError("MissingField", "uri");
16192
+ /** The optional statement and the gap up to the required `URI: ` line. */
16193
+ function statementThenFields(lines, i) {
16194
+ if (i.v >= lines.length) throw missingUri();
16195
+ if (lines[i.v] !== "") throw syntaxError("ExpectedBlankLine");
16196
+ i.v++;
16197
+ const l = lines[i.v];
16198
+ if (l === void 0) throw missingUri();
16199
+ if (l === "") throw syntaxError("ExpectedBlankLine");
16200
+ if (l.startsWith("URI: ")) return;
16201
+ i.v++;
16202
+ const after = lines[i.v];
16203
+ if (after === void 0) throw missingUri();
16204
+ if (after !== "") throw syntaxError("ExpectedBlankLine");
16205
+ i.v++;
16206
+ return l;
16207
+ }
16208
+ /**
16209
+ * Parse `text` into a validated message; the preamble label must be exactly `"Solana"`.
16210
+ *
16211
+ * @throws {SiwxError} `Syntax`, `Mismatch` `label`, or `InvalidField`.
16212
+ */
16213
+ function parse(text) {
16214
+ const byteLength = utf8ByteLength(text);
16215
+ if (byteLength > 16384) throw new SiwxError({
16216
+ code: "MessageTooLarge",
16217
+ length: byteLength,
16218
+ max: MAX_MESSAGE_BYTES
16219
+ });
16220
+ if (text.includes("\r")) throw syntaxError("CarriageReturn");
16221
+ if (text.endsWith("\n")) throw syntaxError("UnexpectedTrailing");
16222
+ const lines = text.split("\n");
16223
+ const idx = { v: 0 };
16224
+ const preamble = lines[idx.v++];
16225
+ if (preamble === void 0) throw syntaxError("UnexpectedEof");
16226
+ const mid = preamble.indexOf(MID);
16227
+ if (mid === -1) throw syntaxError("MissingPreamble");
16228
+ const domain = preamble.slice(0, mid);
16229
+ const tail = preamble.slice(mid + MID.length);
16230
+ if (!tail.endsWith(" account:")) throw syntaxError("MissingAccountSuffix");
16231
+ const label = tail.slice(0, tail.length - SUFFIX.length);
16232
+ if (label !== LABEL) throw new SiwxError({
16233
+ code: "Mismatch",
16234
+ field: "label",
16235
+ expected: LABEL,
16236
+ actual: label
16237
+ });
16238
+ const address = lines[idx.v++];
16239
+ if (address === void 0) throw syntaxError("UnexpectedEof");
16240
+ const statement = statementThenFields(lines, idx);
16241
+ const take = (tag, field) => {
16242
+ const line = lines[idx.v];
16243
+ if (line === void 0 || !line.startsWith(tag)) throw syntaxError("MissingField", field);
16244
+ idx.v++;
16245
+ return line.slice(tag.length);
16246
+ };
16247
+ const uri = take("URI: ", "uri");
16248
+ const version = take("Version: ", "version");
16249
+ const chainId = take("Chain ID: ", "chainId");
16250
+ const nonce = take("Nonce: ", "nonce");
16251
+ const issuedAt = take("Issued At: ", "issuedAt");
16252
+ const tail4 = optionalTags(lines, idx.v);
16253
+ return createMessage(_objectSpread2(_objectSpread2({
16254
+ domain,
16255
+ address
16256
+ }, statement === void 0 ? {} : { statement }), {}, {
16257
+ uri,
16258
+ version,
16259
+ chainId,
16260
+ nonce,
16261
+ issuedAt
16262
+ }, tail4));
16263
+ }
16264
+ /**
16265
+ * {@link parse} over raw bytes: size check, strict UTF-8 (`InvalidUtf8`), then parse.
16266
+ *
16267
+ * @throws {SiwxError}
16268
+ */
16269
+ function parseBytes(bytes) {
16270
+ if (bytes.length > 16384) throw new SiwxError({
16271
+ code: "MessageTooLarge",
16272
+ length: bytes.length,
16273
+ max: MAX_MESSAGE_BYTES
16274
+ });
16275
+ const text = utf8Decode(bytes);
16276
+ if (text === void 0) throw syntaxError("InvalidUtf8");
16277
+ return parse(text);
16278
+ }
16279
+ new Uint8Array([255, ...utf8Encode("solana offchain")]);
16280
+ // packages/wallet-chains/dist/src-8NZeEnrW.mjs
16281
+ init_defineProperty();
16282
+ var PREAMBLE = " wants you to sign in with your ";
16283
+ var OPTIONAL_KEYS = [
16284
+ "scheme",
16285
+ "statement",
16286
+ "expirationTime",
16287
+ "notBefore",
16288
+ "requestId"
16289
+ ];
16290
+ var plainFields = (message) => {
16291
+ const { domain, address, uri, version, chainId, nonce, issuedAt, resources } = message;
16292
+ const fields = {
16293
+ domain,
16294
+ address,
16295
+ uri,
16296
+ version,
16297
+ chainId,
16298
+ nonce,
16299
+ issuedAt
16300
+ };
16301
+ for (const key of OPTIONAL_KEYS) {
16302
+ const value = message[key];
16303
+ if (value !== void 0) fields[key] = value;
16304
+ }
16305
+ if (resources !== void 0) fields.resources = [...resources];
16306
+ return fields;
16307
+ };
16308
+ var parseValid = (text, family) => {
16309
+ if (family === "evm") {
16310
+ const ns = evm();
16311
+ const message = ns.parse(new TextEncoder().encode(text));
16312
+ ns.account(message);
16313
+ return plainFields(message);
16314
+ }
16315
+ const message = siws_exports.parse(text);
16316
+ validateAddress(message.address);
16317
+ return plainFields(message);
16318
+ };
16319
+ /**
16320
+ * Finds a Sign-In with X message in `text` for the chain `family`. `undefined` when the text has no
16321
+ * sign-in preamble; `malformed` when it has one but is not a conforming message for the family
16322
+ * (ERC-4361: wallets should warn about that shape).
16323
+ */
16324
+ function parseSignIn(text, family) {
16325
+ try {
16326
+ return {
16327
+ status: "valid",
16328
+ fields: parseValid(text, family)
16329
+ };
16330
+ } catch (_unused) {
16331
+ return text.includes(PREAMBLE) ? { status: "malformed" } : void 0;
16332
+ }
16333
+ }
14848
16334
  var ChainError = class extends Error {
14849
16335
  constructor(code, message) {
14850
16336
  super(message);
@@ -14853,7 +16339,7 @@ zoo`.split("\n"));
14853
16339
  this.code = code;
14854
16340
  }
14855
16341
  };
14856
- // packages/wallet-chains/dist/account-ref-C2qrDbVT.mjs
16342
+ // packages/wallet-chains/dist/account-ref-D2rW_qlI.mjs
14857
16343
  var isRecord$3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
14858
16344
  var isAccountRef = (value) => {
14859
16345
  if (!isRecord$3(value) || typeof value["kind"] !== "string") return false;
@@ -14886,7 +16372,7 @@ zoo`.split("\n"));
14886
16372
  */
14887
16373
  function abigint(n, title = "value") {
14888
16374
  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}`);
16375
+ if (n < _0n$3) throw new RangeError(`"${title}" expected non-negative bigint, got ${n}`);
14890
16376
  return n;
14891
16377
  }
14892
16378
  function aarray(item, title, inner = () => {}) {
@@ -15094,7 +16580,7 @@ zoo`.split("\n"));
15094
16580
  }
15095
16581
  return res;
15096
16582
  }
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;
16583
+ 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
16584
  var init_utils = __esmMin((() => {
15099
16585
  init_secp256k1();
15100
16586
  init_utils$1();
@@ -15105,9 +16591,9 @@ zoo`.split("\n"));
15105
16591
  Point = /* @__PURE__ */ (() => secp256k1.Point)();
15106
16592
  Fn = /* @__PURE__ */ (() => Point.Fn)();
15107
16593
  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;
16594
+ _0n$3 = /* @__PURE__ */ BigInt(0);
16595
+ _2n$1 = /* @__PURE__ */ BigInt(2);
16596
+ hasEven = (y) => y % _2n$1 === _0n$3;
15111
16597
  isBytes = /* @__PURE__ */ (() => utils.isBytes)();
15112
16598
  concatBytes = /* @__PURE__ */ (() => utils.concatBytes)();
15113
16599
  equalBytes = /* @__PURE__ */ (() => utils.equalBytes)();
@@ -15116,7 +16602,7 @@ zoo`.split("\n"));
15116
16602
  sha256x2 = (...msgs) => sha256(sha256(concatBytes(...msgs)));
15117
16603
  pubSchnorr = (priv) => schnorr.getPublicKey(priv);
15118
16604
  pubECDSA = (privateKey, isCompressed) => secp256k1.getPublicKey(privateKey, isCompressed);
15119
- LOW_R_BOUND = /* @__PURE__ */ (() => CURVE_ORDER / _2n$2)();
16605
+ LOW_R_BOUND = /* @__PURE__ */ (() => CURVE_ORDER / _2n$1)();
15120
16606
  hasLowR = (sig) => sig.r < LOW_R_BOUND;
15121
16607
  signSchnorr = (message, secretKey, auxRand) => schnorr.sign(message, secretKey, auxRand);
15122
16608
  tagSchnorr = (tag, ...messages) => schnorr.utils.taggedHash(tag, ...messages);
@@ -15156,7 +16642,7 @@ zoo`.split("\n"));
15156
16642
  function ScriptNum(bytesLimit = 6, forceMinimal = false) {
15157
16643
  return wrap({
15158
16644
  encodeStream: (w, value) => {
15159
- if (value === _0n$3) return;
16645
+ if (value === _0n$2) return;
15160
16646
  const neg = value < 0;
15161
16647
  const val = BigInt(value);
15162
16648
  const nums = [];
@@ -15168,17 +16654,17 @@ zoo`.split("\n"));
15168
16654
  decodeStream: (r) => {
15169
16655
  const len = r.leftBytes;
15170
16656
  if (len > bytesLimit) throw new Error(`ScriptNum: number (${len}) bigger than limit=${bytesLimit}`);
15171
- if (len === 0) return _0n$3;
16657
+ if (len === 0) return _0n$2;
15172
16658
  const data = r.bytes(len);
15173
16659
  if (forceMinimal) {
15174
16660
  if ((data[len - 1] & 127) === 0) {
15175
16661
  if (len <= 1 || (data[len - 2] & 128) === 0) throw new Error("Non-minimally encoded ScriptNum");
15176
16662
  }
15177
16663
  }
15178
- let res = _0n$3;
16664
+ let res = _0n$2;
15179
16665
  for (let i = 0; i < len; ++i) res |= BigInt(data[i]) << _8n * BigInt(i);
15180
16666
  if (data[len - 1] >= 128) {
15181
- res &= _2n$1 ** BigInt(len * 8) - _1n$3 >> _1n$3;
16667
+ res &= _2n ** BigInt(len * 8) - _1n$2 >> _1n$2;
15182
16668
  res = -res;
15183
16669
  }
15184
16670
  return res;
@@ -15213,13 +16699,13 @@ zoo`.split("\n"));
15213
16699
  if (tx.segwitFlag && tx.witnesses && tx.witnesses.every((w) => !w.length)) throw new Error("Segwit flag with only empty witness fields");
15214
16700
  return tx;
15215
16701
  }
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;
16702
+ 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
16703
  var init_script = __esmMin((() => {
15218
16704
  init_micro_packed();
15219
16705
  init_utils();
15220
- _0n$3 = /* @__PURE__ */ BigInt(0);
15221
- _1n$3 = /* @__PURE__ */ BigInt(1);
15222
- _2n$1 = /* @__PURE__ */ BigInt(2);
16706
+ _0n$2 = /* @__PURE__ */ BigInt(0);
16707
+ _1n$2 = /* @__PURE__ */ BigInt(1);
16708
+ _2n = /* @__PURE__ */ BigInt(2);
15223
16709
  _8n = /* @__PURE__ */ BigInt(8);
15224
16710
  U8_MAX = /* @__PURE__ */ BigInt(255);
15225
16711
  COMPACT_DIRECT_MAX = /* @__PURE__ */ BigInt(252);
@@ -15431,7 +16917,7 @@ zoo`.split("\n"));
15431
16917
  return Object.freeze(wrap({
15432
16918
  encodeStream: (w, value) => {
15433
16919
  if (typeof value === "number") value = BigInt(value);
15434
- if (_0n$3 <= value && value <= COMPACT_DIRECT_MAX) return w.byte(Number(value));
16920
+ if (_0n$2 <= value && value <= COMPACT_DIRECT_MAX) return w.byte(Number(value));
15435
16921
  for (const [flag, bytes, start, stop] of limitsList) {
15436
16922
  if (start > value || value > stop) continue;
15437
16923
  w.byte(flag);
@@ -15444,7 +16930,7 @@ zoo`.split("\n"));
15444
16930
  const b0 = r.byte();
15445
16931
  if (b0 <= 252) return BigInt(b0);
15446
16932
  const [_, bytes, start] = limits[b0];
15447
- let num = _0n$3;
16933
+ let num = _0n$2;
15448
16934
  for (let i = 0; i < bytes; i++) num |= BigInt(r.byte()) << _8n * BigInt(i);
15449
16935
  if (num < start) throw r.err(`Wrong CompactSize(${8 * bytes})`);
15450
16936
  return num;
@@ -15793,7 +17279,7 @@ zoo`.split("\n"));
15793
17279
  }
15794
17280
  return mergeKeyMap(psbtEnum, _other, _current, void 0, unknown, proprietary);
15795
17281
  }
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;
17282
+ 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
17283
  var init_psbt = __esmMin((() => {
15798
17284
  init_base();
15799
17285
  init_utils$2();
@@ -15807,8 +17293,8 @@ zoo`.split("\n"));
15807
17293
  if (mode === "ignore" || mode === "strip" || mode === "strict") return mode;
15808
17294
  throw new Error(`PSBT: invalid ${name} policy=${mode}`);
15809
17295
  };
15810
- _0n$2 = /* @__PURE__ */ BigInt(0);
15811
- _1n$2 = /* @__PURE__ */ BigInt(1);
17296
+ _0n$1 = /* @__PURE__ */ BigInt(0);
17297
+ _1n$1 = /* @__PURE__ */ BigInt(1);
15812
17298
  PubKeyECDSA = /* @__PURE__ */ (() => validate$4(createBytes(null), (pub) => validatePubkey(pub, PubT.ecdsa)))();
15813
17299
  PubKeyECDSACompressed = /* @__PURE__ */ (() => validate$4(createBytes(33), (pub) => validatePubkey(pub, PubT.ecdsa)))();
15814
17300
  PubKeySchnorr = /* @__PURE__ */ (() => validate$4(createBytes(32), (pub) => validatePubkey(pub, PubT.schnorr)))();
@@ -15870,9 +17356,9 @@ zoo`.split("\n"));
15870
17356
  while (next.length < depth) next.push(0);
15871
17357
  path = next;
15872
17358
  }
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");
17359
+ let leaves = _0n$1;
17360
+ for (let i = 0; i < tree.length; i++) leaves += _1n$1 << BigInt(maxDepth - tree[i].depth);
17361
+ if (leaves !== _1n$1 << BigInt(maxDepth)) throw new Error("tapTree: tuples must describe a complete binary tree");
15876
17362
  return tree;
15877
17363
  }))();
15878
17364
  BytesInf = /* @__PURE__ */ createBytes(null);
@@ -16039,7 +17525,7 @@ zoo`.split("\n"));
16039
17525
  return i;
16040
17526
  })))();
16041
17527
  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}`);
17528
+ if (o.amount !== void 0 && o.amount < _0n$1) throw new Error(`validateOutput: wrong amount=${o.amount}`);
16043
17529
  if (o.bip32Derivation) for (const [k] of o.bip32Derivation) validatePubkey(k, PubT.ecdsa);
16044
17530
  return o;
16045
17531
  })))();
@@ -17084,7 +18570,7 @@ zoo`.split("\n"));
17084
18570
  return res;
17085
18571
  }
17086
18572
  }
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;
18573
+ 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
18574
  var init_transaction = __esmMin((() => {
17089
18575
  init_base();
17090
18576
  init_utils$2();
@@ -17095,8 +18581,8 @@ zoo`.split("\n"));
17095
18581
  init_utils();
17096
18582
  init_objectSpread2();
17097
18583
  init_defineProperty();
17098
- _0n$1 = /* @__PURE__ */ BigInt(0);
17099
- _1n$1 = /* @__PURE__ */ BigInt(1);
18584
+ _0n = /* @__PURE__ */ BigInt(0);
18585
+ _1n = /* @__PURE__ */ BigInt(1);
17100
18586
  U64_MAX = /* @__PURE__ */ BigInt("0xffffffffffffffff");
17101
18587
  EMPTY32 = /* @__PURE__ */ new Uint8Array(32);
17102
18588
  EMPTY_OUTPUT = {
@@ -17622,7 +19108,7 @@ zoo`.split("\n"));
17622
19108
  });
17623
19109
  }
17624
19110
  get fee() {
17625
- let res = _0n$1;
19111
+ let res = _0n;
17626
19112
  for (const i of this.inputs) {
17627
19113
  const prevOut = getPrevOut(i);
17628
19114
  if (!prevOut) throw new Error("Empty input amount");
@@ -17635,7 +19121,7 @@ zoo`.split("\n"));
17635
19121
  preimageLegacy(idx, prevOutScript, hashType) {
17636
19122
  const { isAny, isNone, isSingle } = unpackSighash(hashType);
17637
19123
  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);
19124
+ if (isSingle && idx >= this.outputs.length || idx >= this.inputs.length) return U256LE.encode(_1n);
17639
19125
  prevOutScript = stripCodeSeparator(prevOutScript);
17640
19126
  let inputs = this.inputs.map(inputBeforeSign).map((input, inputIdx) => _objectSpread2(_objectSpread2({}, input), {}, { finalScriptSig: inputIdx === idx ? prevOutScript : EMPTY$1 }));
17641
19127
  if (isAny) inputs = [inputs[idx]];
@@ -17833,7 +19319,7 @@ zoo`.split("\n"));
17833
19319
  }
17834
19320
  finalizeIdx(idx) {
17835
19321
  this.checkInputIdx(idx);
17836
- if (this.fee < _0n$1) throw new Error("Outputs spends more than inputs amount");
19322
+ if (this.fee < _0n) throw new Error("Outputs spends more than inputs amount");
17837
19323
  const input = this.inputs[idx];
17838
19324
  cleanExtensions(input, this.opts.unknown, this.opts.proprietary);
17839
19325
  cleanTxModifiable(this.global.txModifiable, this.opts.unknown);
@@ -17961,7 +19447,7 @@ zoo`.split("\n"));
17961
19447
  extract() {
17962
19448
  if (!this.isFinal) throw new Error("Transaction has unfinalized inputs");
17963
19449
  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");
19450
+ if (this.fee < _0n) throw new Error("Outputs spends more than inputs amount");
17965
19451
  return this.toBytes(true, true);
17966
19452
  }
17967
19453
  combine(other) {
@@ -18044,7 +19530,7 @@ zoo`.split("\n"));
18044
19530
  }
18045
19531
  };
18046
19532
  }));
18047
- // packages/wallet-chains/dist/message-DuJ5KSRT.mjs
19533
+ // packages/wallet-chains/dist/message-ChhEZ0lx.mjs
18048
19534
  init_secp256k1();
18049
19535
  init_utils();
18050
19536
  init_transaction();
@@ -18104,9 +19590,9 @@ zoo`.split("\n"));
18104
19590
  * BIP-322 message signing ("simple" + legacy) built on btc-signer primitives.
18105
19591
  * https://github.com/bitcoin/bips/blob/master/bip-0322.mediawiki
18106
19592
  */
18107
- var utf8 = (s) => new TextEncoder().encode(s);
19593
+ var utf8$1 = (s) => new TextEncoder().encode(s);
18108
19594
  var BIP322_TAG = "BIP0322-signed-message";
18109
- var LEGACY_MAGIC = utf8("Bitcoin Signed Message:\n");
19595
+ var LEGACY_MAGIC = utf8$1("Bitcoin Signed Message:\n");
18110
19596
  var concat$2 = (...parts) => {
18111
19597
  const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
18112
19598
  let o = 0;
@@ -18116,9 +19602,14 @@ zoo`.split("\n"));
18116
19602
  }
18117
19603
  return out;
18118
19604
  };
18119
- /** CompactSize length prefix (values here are always < 253). */
19605
+ /** CompactSize length prefix for the one-byte form. */
18120
19606
  var varint = (n) => Uint8Array.of(n);
18121
- var pushData = (data) => concat$2(varint(data.length), data);
19607
+ var COMPACT_SIZE_ONE_BYTE_MAX = 252;
19608
+ /** A length-prefixed push; longer data would need a multi-byte CompactSize this code never emits. */
19609
+ var pushData = (data) => {
19610
+ if (data.length > COMPACT_SIZE_ONE_BYTE_MAX) throw new ChainError("invalid-request", "BIP-322 script data exceeds 252 bytes");
19611
+ return concat$2(varint(data.length), data);
19612
+ };
18122
19613
  var u32le$1 = (n) => Uint8Array.of(n % 256, Math.floor(n / 256) % 256, Math.floor(n / 65536) % 256, Math.floor(n / 16777216) % 256);
18123
19614
  var u64le$1 = (n) => {
18124
19615
  const out = /* @__PURE__ */ new Uint8Array(8);
@@ -18131,8 +19622,8 @@ zoo`.split("\n"));
18131
19622
  };
18132
19623
  /** BIP340 tagged hash: sha256(sha256(tag) || sha256(tag) || m). */
18133
19624
  var bip322MessageHash = (message) => {
18134
- const tag = sha256$1(utf8(BIP322_TAG));
18135
- return sha256$1(concat$2(tag, tag, utf8(message)));
19625
+ const tag = sha256$1(utf8$1(BIP322_TAG));
19626
+ return sha256$1(concat$2(tag, tag, utf8$1(message)));
18136
19627
  };
18137
19628
  /**
18138
19629
  * Serialized to_spend tx per BIP-322: version 0, one input spending the zero prevout with the
@@ -18208,7 +19699,7 @@ zoo`.split("\n"));
18208
19699
  */
18209
19700
  var signLegacyMessage = (message, privateKey) => {
18210
19701
  var _recovered$;
18211
- const data = concat$2(pushData(LEGACY_MAGIC), pushData(utf8(message)));
19702
+ const data = concat$2(pushData(LEGACY_MAGIC), pushData(utf8$1(message)));
18212
19703
  const hash = sha256$1(sha256$1(data));
18213
19704
  const recovered = secp256k1.sign(hash, privateKey, {
18214
19705
  lowS: true,
@@ -18285,7 +19776,8 @@ zoo`.split("\n"));
18285
19776
  const { type } = getInputType(input);
18286
19777
  if ((type === "legacy" || type === "nonwitness-script") && input.nonWitnessUtxo === void 0) throw new ChainError("invalid-request", `input ${idx} is missing nonWitnessUtxo`);
18287
19778
  const sighash = input.sighashType;
18288
- if (!(sighash === void 0 || sighash === SIGHASH_ALL || isTaprootInput(input) && sighash === DEFAULT_SIGHASH)) throw new ChainError("unsupported", `input ${idx} uses a non-default sighash`);
19779
+ 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`);
19780
+ if (sighash === 131 && idx >= tx.outputsLength) throw new ChainError("unsupported", `input ${idx} uses SIGHASH_SINGLE without a same-index output`);
18289
19781
  }
18290
19782
  return {
18291
19783
  psbt: tx.toPSBT(0),
@@ -18293,7 +19785,16 @@ zoo`.split("\n"));
18293
19785
  };
18294
19786
  };
18295
19787
  var SATS = "sats";
19788
+ var SIGHASH_SINGLE_ANYONECANPAY = 131;
18296
19789
  var OP_RETURN = 106;
19790
+ /** Btc-signer's parse failures are foreign exceptions — the request is a malformed PSBT. */
19791
+ var parsePsbt = (psbt) => {
19792
+ try {
19793
+ return Transaction.fromPSBT(psbt);
19794
+ } catch (error) {
19795
+ throw error instanceof ChainError ? error : new ChainError("invalid-request", "malformed PSBT");
19796
+ }
19797
+ };
18297
19798
  var bytesToHex$2 = (bytes) => {
18298
19799
  let out = "";
18299
19800
  for (const b of bytes) out += b.toString(16).padStart(2, "0");
@@ -18319,7 +19820,7 @@ zoo`.split("\n"));
18319
19820
  * change) — not a display hint.
18320
19821
  */
18321
19822
  var decodeBitcoinPsbt = (request, ownScripts = /* @__PURE__ */ new Set()) => {
18322
- const tx = Transaction.fromPSBT(request.psbt);
19823
+ const tx = parsePsbt(request.psbt);
18323
19824
  const coder = Address(bitcoinNetwork(request.network).params);
18324
19825
  const signed = new Set(request.sign);
18325
19826
  const outflows = [];
@@ -18358,18 +19859,22 @@ zoo`.split("\n"));
18358
19859
  }
18359
19860
  const external = tx.inputsLength - signed.size > 0;
18360
19861
  const undecodable = outflows.some((o) => !o.verified);
18361
- const verifiability = external ? "opaque" : undecodable ? "partial" : "full";
19862
+ const listing = request.sign.some((i) => tx.getInput(i).sighashType === SIGHASH_SINGLE_ANYONECANPAY);
19863
+ const verifiability = external ? "opaque" : listing || undecodable ? "partial" : "full";
18362
19864
  return {
18363
19865
  family: "bitcoin",
18364
19866
  network: request.network,
18365
19867
  summary: outflows.length > 0 ? "transfer" : "contract-call",
18366
19868
  outflows,
18367
19869
  approvals: [],
18368
- fee: canFee ? { max: {
19870
+ fee: canFee && !listing ? { max: {
18369
19871
  asset: SATS,
18370
19872
  amount: (inSum - outSum).toString(10)
18371
19873
  } } : void 0,
18372
- warnings: [],
19874
+ warnings: listing ? [{
19875
+ kind: "sighash-single-anyonecanpay",
19876
+ message: "signed inputs bind only their same-index outputs; the rest of the transaction can change"
19877
+ }] : [],
18373
19878
  verifiability
18374
19879
  };
18375
19880
  };
@@ -18441,258 +19946,6 @@ zoo`.split("\n"));
18441
19946
  };
18442
19947
  /** Decodes the message `address` into the scriptPubKey the signer needs. */
18443
19948
  var decodeMessageTarget = (request) => messageTarget(request.address, request.network, request.format);
18444
- // node_modules/.bun/@noble+hashes@2.4.0/node_modules/@noble/hashes/sha3.js
18445
- init__u64();
18446
- init_utils$2();
18447
- init_defineProperty();
18448
- var _0n = BigInt(0);
18449
- var _1n = BigInt(1);
18450
- var _2n = BigInt(2);
18451
- var _7n = BigInt(7);
18452
- var _256n = BigInt(256);
18453
- var _0x71n = BigInt(113);
18454
- var SHA3_PI = [];
18455
- var SHA3_ROTL = [];
18456
- var _SHA3_IOTA = [];
18457
- for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
18458
- [x, y] = [y, (2 * x + 3 * y) % 5];
18459
- SHA3_PI.push(2 * (5 * y + x));
18460
- SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
18461
- let t = _0n;
18462
- for (let j = 0; j < 7; j++) {
18463
- R = (R << _1n ^ (R >> _7n) * _0x71n) % _256n;
18464
- if (R & _2n) t ^= _1n << (_1n << BigInt(j)) - _1n;
18465
- }
18466
- _SHA3_IOTA.push(t);
18467
- }
18468
- var IOTAS = split(_SHA3_IOTA, true);
18469
- var SHA3_IOTA_H = IOTAS[0];
18470
- var SHA3_IOTA_L = IOTAS[1];
18471
- var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
18472
- var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
18473
- var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
18474
- var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
18475
- var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
18476
- var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
18477
- var B = /* @__PURE__ */ new Uint32Array(10);
18478
- /**
18479
- * `keccakf1600` internal permutation, additionally allows adjusting the round count.
18480
- * @param s - 5x5 Keccak state encoded as 25 lanes split into 50 uint32 words
18481
- * in this file's local little-endian lane-word order
18482
- * @param rounds - number of rounds to execute
18483
- * @throws On wrong argument types. {@link TypeError}
18484
- * @throws On wrong argument ranges or values. {@link RangeError}
18485
- * @throws If `rounds` is outside the supported `1..24` range. {@link Error}
18486
- * @example
18487
- * Permute a Keccak state with the default 24 rounds.
18488
- * ```ts
18489
- * keccakP(new Uint32Array(50));
18490
- * ```
18491
- */
18492
- function keccakP(s, rounds = 24) {
18493
- if (!(s instanceof Uint32Array)) throw new TypeError("\"s\" expected Uint32Array(50), got type=" + typeof s);
18494
- if (s.length !== 50) throw new RangeError("\"s\" expected Uint32Array(50), got length=" + s.length);
18495
- anumber$2(rounds, "rounds");
18496
- if (rounds < 1 || rounds > 24) throw new Error("\"rounds\" expected integer 1..24");
18497
- for (let round = 24 - rounds; round < 24; round++) {
18498
- for (let x = 0; x < 10; x++) B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
18499
- for (let x = 0; x < 10; x += 2) {
18500
- const idx1 = (x + 8) % 10;
18501
- const idx0 = (x + 2) % 10;
18502
- const B0 = B[idx0];
18503
- const B1 = B[idx0 + 1];
18504
- const Th = rotlH(B0, B1, 1) ^ B[idx1];
18505
- const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
18506
- for (let y = 0; y < 50; y += 10) {
18507
- s[x + y] ^= Th;
18508
- s[x + y + 1] ^= Tl;
18509
- }
18510
- }
18511
- let curH = s[2];
18512
- let curL = s[3];
18513
- for (let t = 0; t < 24; t++) {
18514
- const shift = SHA3_ROTL[t];
18515
- const Th = rotlH(curH, curL, shift);
18516
- const Tl = rotlL(curH, curL, shift);
18517
- const PI = SHA3_PI[t];
18518
- curH = s[PI];
18519
- curL = s[PI + 1];
18520
- s[PI] = Th;
18521
- s[PI + 1] = Tl;
18522
- }
18523
- for (let y = 0; y < 50; y += 10) {
18524
- const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3];
18525
- s[y] ^= ~s[y + 2] & s[y + 4];
18526
- s[y + 1] ^= ~s[y + 3] & s[y + 5];
18527
- s[y + 2] ^= ~s[y + 4] & s[y + 6];
18528
- s[y + 3] ^= ~s[y + 5] & s[y + 7];
18529
- s[y + 4] ^= ~s[y + 6] & s[y + 8];
18530
- s[y + 5] ^= ~s[y + 7] & s[y + 9];
18531
- s[y + 6] ^= ~s[y + 8] & b0;
18532
- s[y + 7] ^= ~s[y + 9] & b1;
18533
- s[y + 8] ^= ~b0 & b2;
18534
- s[y + 9] ^= ~b1 & b3;
18535
- }
18536
- s[0] ^= SHA3_IOTA_H[round];
18537
- s[1] ^= SHA3_IOTA_L[round];
18538
- }
18539
- clean(B);
18540
- }
18541
- /**
18542
- * Keccak sponge function.
18543
- * @param blockLen - absorb/squeeze rate in bytes
18544
- * @param suffix - domain separation suffix byte
18545
- * @param outputLen - default digest length in bytes. This base sponge only
18546
- * requires a non-negative integer; wrappers that need positive output
18547
- * lengths must enforce that themselves.
18548
- * @param enableXOF - whether XOF output is allowed
18549
- * @param rounds - number of Keccak-f rounds
18550
- * @example
18551
- * Build a sponge state, absorb bytes, then finalize a digest.
18552
- * ```ts
18553
- * const hash = new Keccak(136, 0x06, 32);
18554
- * hash.update(new Uint8Array([1, 2, 3]));
18555
- * hash.digest();
18556
- * ```
18557
- */
18558
- var Keccak = class Keccak {
18559
- constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
18560
- _defineProperty(this, "state", void 0);
18561
- _defineProperty(this, "pos", 0);
18562
- _defineProperty(this, "posOut", 0);
18563
- _defineProperty(this, "finished", false);
18564
- _defineProperty(this, "state32", void 0);
18565
- _defineProperty(this, "destroyed", false);
18566
- _defineProperty(this, "blockLen", void 0);
18567
- _defineProperty(this, "suffix", void 0);
18568
- _defineProperty(this, "outputLen", void 0);
18569
- _defineProperty(this, "canXOF", void 0);
18570
- _defineProperty(this, "enableXOF", false);
18571
- _defineProperty(this, "rounds", void 0);
18572
- anumber$2(blockLen, "blockLen");
18573
- anumber$2(suffix, "suffix");
18574
- anumber$2(rounds, "rounds");
18575
- abool$1(enableXOF, "enableXOF");
18576
- this.blockLen = blockLen;
18577
- this.suffix = suffix;
18578
- this.outputLen = outputLen;
18579
- this.enableXOF = enableXOF;
18580
- this.canXOF = enableXOF;
18581
- this.rounds = rounds;
18582
- anumber$2(outputLen, "outputLen");
18583
- if (!(0 < blockLen && blockLen < 200)) throw new Error("\"blockLen\" must be 1..199");
18584
- this.state = /* @__PURE__ */ new Uint8Array(200);
18585
- this.state32 = u32$1(this.state);
18586
- }
18587
- clone() {
18588
- return this._cloneInto();
18589
- }
18590
- keccak() {
18591
- swap32IfBE(this.state32);
18592
- keccakP(this.state32, this.rounds);
18593
- swap32IfBE(this.state32);
18594
- this.posOut = 0;
18595
- this.pos = 0;
18596
- }
18597
- update(data) {
18598
- aexists(this);
18599
- abytes$2(data);
18600
- const { blockLen, state, state32 } = this;
18601
- const len = data.length;
18602
- const canUseU32 = blockLen % 4 === 0 && data.byteOffset % 4 === 0;
18603
- const blockLen32 = blockLen / 4;
18604
- const data32 = canUseU32 && len >= blockLen ? u32$1(data) : void 0;
18605
- for (let pos = 0; pos < len;) {
18606
- if (data32 !== void 0 && this.pos === 0 && pos % 4 === 0 && len - pos >= blockLen) {
18607
- for (let i = 0, o = pos / 4; i < blockLen32; i++) state32[i] ^= data32[o + i];
18608
- pos += blockLen;
18609
- this.pos = blockLen;
18610
- this.keccak();
18611
- continue;
18612
- }
18613
- const take = Math.min(blockLen - this.pos, len - pos);
18614
- for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++];
18615
- if (this.pos === blockLen) this.keccak();
18616
- }
18617
- return this;
18618
- }
18619
- finish() {
18620
- if (this.finished) return;
18621
- this.finished = true;
18622
- const { state, suffix, pos, blockLen } = this;
18623
- state[pos] ^= suffix;
18624
- if ((suffix & 128) !== 0 && pos === blockLen - 1) this.keccak();
18625
- state[blockLen - 1] ^= 128;
18626
- this.keccak();
18627
- }
18628
- writeInto(out) {
18629
- aexists(this, false);
18630
- abytes$2(out);
18631
- this.finish();
18632
- const bufferOut = this.state;
18633
- const { blockLen } = this;
18634
- for (let pos = 0, len = out.length; pos < len;) {
18635
- if (this.posOut >= blockLen) this.keccak();
18636
- const take = Math.min(blockLen - this.posOut, len - pos);
18637
- out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
18638
- this.posOut += take;
18639
- pos += take;
18640
- }
18641
- return out;
18642
- }
18643
- xofInto(out) {
18644
- if (!this.enableXOF) throw new Error("XOF is not enabled");
18645
- return this.writeInto(out);
18646
- }
18647
- xof(bytes) {
18648
- anumber$2(bytes);
18649
- return this.xofInto(new Uint8Array(bytes));
18650
- }
18651
- digestInto(out) {
18652
- aoutput(out, this);
18653
- if (this.finished) throw new Error("digest() was already called");
18654
- this.writeInto(out.length === this.outputLen ? out : out.subarray(0, this.outputLen));
18655
- this.destroy();
18656
- }
18657
- digest() {
18658
- const out = new Uint8Array(this.outputLen);
18659
- this.digestInto(out);
18660
- return out;
18661
- }
18662
- destroy() {
18663
- this.destroyed = true;
18664
- clean(this.state);
18665
- }
18666
- _cloneInto(to) {
18667
- const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
18668
- to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
18669
- to.blockLen = blockLen;
18670
- to.state32.set(this.state32);
18671
- to.pos = this.pos;
18672
- to.posOut = this.posOut;
18673
- to.finished = this.finished;
18674
- to.rounds = rounds;
18675
- to.suffix = suffix;
18676
- to.outputLen = outputLen;
18677
- to.enableXOF = enableXOF;
18678
- to.canXOF = this.canXOF;
18679
- to.destroyed = this.destroyed;
18680
- return to;
18681
- }
18682
- };
18683
- var genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);
18684
- /**
18685
- * Keccak-256 hash function. Different from SHA3-256.
18686
- * @param msg - message bytes to hash
18687
- * @param opts - Reserved hash options.
18688
- * @returns Digest bytes.
18689
- * @example
18690
- * Hash a message with Keccak-256.
18691
- * ```ts
18692
- * keccak_256(new Uint8Array([97, 98, 99]));
18693
- * ```
18694
- */
18695
- var keccak_256 = /* @__PURE__ */ genKeccak(1, 136, 32);
18696
19949
  // node_modules/.bun/ox@1.8.12+ff0372d108591aba/node_modules/ox/dist/core/version.js
18697
19950
  /** @internal */
18698
19951
  var version = "0.1.1";
@@ -22592,7 +23845,7 @@ zoo`.split("\n"));
22592
23845
  function validateReference(type) {
22593
23846
  if (type === "address" || type === "bool" || type === "string" || type.startsWith("bytes") || type.startsWith("uint") || type.startsWith("int")) throw new InvalidStructTypeError({ type });
22594
23847
  }
22595
- // packages/wallet-chains/dist/typed-data-Cf1g7JVv.mjs
23848
+ // packages/wallet-chains/dist/typed-data-J5g2WemC.mjs
22596
23849
  init_secp256k1();
22597
23850
  init_utils$2();
22598
23851
  init_objectSpread2();
@@ -22617,6 +23870,11 @@ zoo`.split("\n"));
22617
23870
  var isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
22618
23871
  var CANONICAL_HEX = /^0x(?:0|[1-9a-f][0-9a-f]*)$/;
22619
23872
  var canonicalHex = (value) => `0x${value.toString(16)}`;
23873
+ /** Parses a JSON-RPC quantity: `0x` and at least one hex digit — a bare `"0x"` is malformed. */
23874
+ var quantityBigInt = (value, field) => {
23875
+ if (typeof value !== "string" || !/^0x[0-9a-fA-F]+$/.test(value)) throw new ChainError("invalid-quantity", `${field} must be a 0x quantity`);
23876
+ return BigInt(value);
23877
+ };
22620
23878
  var safeInteger = (value, field) => {
22621
23879
  if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new ChainError("invalid-quantity", `${field} must be a non-negative safe integer`);
22622
23880
  return value;
@@ -22624,8 +23882,7 @@ zoo`.split("\n"));
22624
23882
  var quantity = (value, field) => {
22625
23883
  if (typeof value !== "string") throw new ChainError("invalid-quantity", `${field} must be a 0x quantity string`);
22626
23884
  if (CANONICAL_HEX.test(value)) return value;
22627
- if (/^0x[0-9a-fA-F]+$/.test(value) || value === "0x") return canonicalHex(BigInt(value === "0x" ? "0x0" : value));
22628
- throw new ChainError("invalid-quantity", `${field} must be a 0x quantity`);
23885
+ return canonicalHex(quantityBigInt(value, field));
22629
23886
  };
22630
23887
  var hexBytes$1 = (value, field) => {
22631
23888
  if (typeof value !== "string" || !/^0x(?:[0-9a-fA-F]{2})*$/.test(value)) throw new ChainError("invalid-quantity", `${field} must be 0x-prefixed bytes`);
@@ -22749,8 +24006,33 @@ zoo`.split("\n"));
22749
24006
  if (!isRecord$1(message)) return false;
22750
24007
  return Object.values(types).every((fields) => Array.isArray(fields) && fields.every(isField));
22751
24008
  };
24009
+ var isTypedDataMessage = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
24010
+ /** `value` is an array of message objects (empty allowed). */
24011
+ var typedDataMessages = (value) => Array.isArray(value) && value.every(isTypedDataMessage) ? value : void 0;
24012
+ /** The `Type field,Type field` signature of struct `name` in `types`. */
24013
+ var typedDataSignature = (types, name) => {
24014
+ var _types$name;
24015
+ return (_types$name = types[name]) === null || _types$name === void 0 ? void 0 : _types$name.map((field) => `${field.type} ${field.name}`).join(",");
24016
+ };
24017
+ /** Struct `name` has exactly `fields`, in order, no more. */
24018
+ var sameFields = (types, name, fields) => typedDataSignature(types, name) === fields.join(",");
24019
+ /** A hex `address` field value, checksummed; `undefined` when malformed. */
24020
+ var typedDataAddress = (value) => typeof value === "string" && /^0x[0-9a-fA-F]{40}$/.test(value) ? checksumEvmAddress(value) : void 0;
24021
+ /** A uint field value (safe-integer number, decimal or `0x` hex string) ≤ `max`. */
24022
+ var typedDataUint = (value, max) => {
24023
+ let parsed;
24024
+ if (typeof value === "number" && Number.isSafeInteger(value)) parsed = BigInt(value);
24025
+ else if (typeof value === "string" && /^(?:[0-9]+|0x[0-9a-fA-F]+)$/.test(value)) parsed = BigInt(value);
24026
+ else return;
24027
+ return parsed >= 0n && parsed <= max ? parsed : void 0;
24028
+ };
24029
+ /** The largest timestamp a permit/order expiry or a Safe field is allowed to carry. */
24030
+ var MAX_UINT48 = 2n ** 48n - 1n;
24031
+ var isHexBytes = (value) => typeof value === "string" && /^0x[0-9a-fA-F]*$/.test(value);
24032
+ /** A `bytes` field value: `0x`-prefixed hex of even length. */
24033
+ var typedDataBytes = (value) => isHexBytes(value) ? value : void 0;
22752
24034
  /** Parses the EIP-712 JSON source and validates its shape with ox. */
22753
- var parseTypedData = (typedData, network) => {
24035
+ var parseTypedData = (typedData) => {
22754
24036
  let json;
22755
24037
  try {
22756
24038
  json = JSON.parse(typedData);
@@ -22763,17 +24045,19 @@ zoo`.split("\n"));
22763
24045
  } catch (_unused2) {
22764
24046
  throw new ChainError("invalid-typed-data", "typedData failed EIP-712 validation");
22765
24047
  }
22766
- const { chainId } = json.domain;
22767
- const numeric = typeof chainId === "number" ? chainId : typeof chainId === "string" ? Number(chainId) : NaN;
22768
- return {
22769
- json,
22770
- chainIdMismatch: Number.isSafeInteger(numeric) && numeric !== networkChainId(network)
22771
- };
24048
+ return { json };
24049
+ };
24050
+ /**
24051
+ * `domain.chainId` as a number, when present: a safe non-negative integer given as a JSON number, a
24052
+ * decimal string or a `0x` hex string.
24053
+ */
24054
+ var domainChainId = (domain) => {
24055
+ const { chainId } = domain;
24056
+ if (chainId === void 0) return;
24057
+ const numeric = typeof chainId === "number" ? chainId : typeof chainId === "string" && /^(?:[0-9]+|0x[0-9a-fA-F]+)$/.test(chainId) ? Number(chainId) : NaN;
24058
+ if (!Number.isSafeInteger(numeric) || numeric < 0) throw new ChainError("invalid-typed-data", "typed-data domain.chainId is malformed");
24059
+ return numeric;
22772
24060
  };
22773
- var typedDataWarnings = (parsed) => parsed.chainIdMismatch ? [{
22774
- kind: "chain-id-mismatch",
22775
- message: "typed-data domain.chainId does not match the request network"
22776
- }] : [];
22777
24061
  // node_modules/.bun/ox@1.8.12+ff0372d108591aba/node_modules/ox/dist/core/internal/human-readable/formatAbiItem.js
22778
24062
  /**
22779
24063
  * Formats ABI item (e.g. error, event, function) into human-readable ABI item
@@ -25132,6 +26416,8 @@ zoo`.split("\n"));
25132
26416
  }
25133
26417
  // packages/wallet-chains/dist/evm.mjs
25134
26418
  init_objectSpread2();
26419
+ /** The native asset id in `AssetFlow` and simulated asset changes. */
26420
+ var EVM_NATIVE_ASSET = "native";
25135
26421
  var USDC$1 = Object.freeze({
25136
26422
  symbol: "USDC",
25137
26423
  decimals: 6,
@@ -25162,14 +26448,363 @@ zoo`.split("\n"));
25162
26448
  var _table$String;
25163
26449
  return (_table$String = table[String(chainId)]) === null || _table$String === void 0 ? void 0 : _table$String[address];
25164
26450
  };
26451
+ var MAX_UINT256 = 2n ** 256n - 1n;
26452
+ var MAX_UINT160 = 2n ** 160n - 1n;
26453
+ /** A fungible-token allowance; `max` is the type's maximum, which marks it unlimited. */
26454
+ var allowanceChange = (token, spender, value, change, max, chainId, table, extra = {}) => {
26455
+ const known = lookupEvmToken(table, chainId, token);
26456
+ return _objectSpread2(_objectSpread2({
26457
+ kind: "allowance",
26458
+ spender,
26459
+ amount: _objectSpread2({
26460
+ asset: token,
26461
+ amount: value.toString(10)
26462
+ }, known === void 0 ? {} : {
26463
+ symbol: known.symbol,
26464
+ decimals: known.decimals
26465
+ }),
26466
+ change,
26467
+ unlimited: change !== "decrease" && value === max
26468
+ }, extra), {}, { verified: known !== void 0 });
26469
+ };
26470
+ var isMessage$1 = isTypedDataMessage;
26471
+ var address = typedDataAddress;
26472
+ var uint = typedDataUint;
26473
+ var DETAILS = [
26474
+ "address token",
26475
+ "uint160 amount",
26476
+ "uint48 expiration",
26477
+ "uint48 nonce"
26478
+ ];
26479
+ var PERMISSIONS = ["address token", "uint256 amount"];
26480
+ var WITNESS_WARNING = {
26481
+ kind: "permit2-witness",
26482
+ message: "the permit carries a witness with further terms"
26483
+ };
26484
+ var entries = (value) => Array.isArray(value) && value.length > 0 && value.every(isMessage$1) ? value : void 0;
26485
+ var permit = (...approvals) => ({
26486
+ approvals,
26487
+ warnings: []
26488
+ });
26489
+ /**
26490
+ * The permit a typed-data document grants, or `undefined` when its shape is not exactly one of the
26491
+ * recognized ones. `chainId` is the request network's, used for the built-in token table.
26492
+ */
26493
+ function recognizePermit(json, chainId, table) {
26494
+ const { types, primaryType, message, domain } = json;
26495
+ const verifying = address(domain["verifyingContract"]);
26496
+ if (verifying === void 0) return;
26497
+ const spender = address(message["spender"]);
26498
+ if (spender === void 0) return;
26499
+ const allow = (token, value, change, max, extra = {}) => allowanceChange(token, spender, value, change, max, chainId, table, extra);
26500
+ if (primaryType === "Permit") {
26501
+ if (sameFields(types, "Permit", [
26502
+ "address owner",
26503
+ "address spender",
26504
+ "uint256 value",
26505
+ "uint256 nonce",
26506
+ "uint256 deadline"
26507
+ ])) {
26508
+ const value = uint(message["value"], MAX_UINT256);
26509
+ return value === void 0 ? void 0 : permit(allow(verifying, value, "set", MAX_UINT256));
26510
+ }
26511
+ if (sameFields(types, "Permit", [
26512
+ "address holder",
26513
+ "address spender",
26514
+ "uint256 nonce",
26515
+ "uint256 expiry",
26516
+ "bool allowed"
26517
+ ])) {
26518
+ const { allowed } = message;
26519
+ return typeof allowed === "boolean" ? permit(allow(verifying, allowed ? MAX_UINT256 : 0n, "set", MAX_UINT256)) : void 0;
26520
+ }
26521
+ return;
26522
+ }
26523
+ if (verifying.toLowerCase() !== "0x000000000022D473030F116dDEE9F6B43aC78BA3".toLowerCase()) return;
26524
+ return recognizePermit2(types, primaryType, message, allow);
26525
+ }
26526
+ var recognizePermit2 = (types, primaryType, message, allow) => {
26527
+ var _own$slice;
26528
+ const via = "permit2";
26529
+ const allowance = (details) => {
26530
+ const token = address(details["token"]);
26531
+ const amount = uint(details["amount"], MAX_UINT160);
26532
+ const expiration = uint(details["expiration"], MAX_UINT48);
26533
+ return token === void 0 || amount === void 0 || expiration === void 0 ? void 0 : allow(token, amount, "set", MAX_UINT160, {
26534
+ via,
26535
+ expiration: Number(expiration)
26536
+ });
26537
+ };
26538
+ const transfer = (permitted, deadline) => {
26539
+ const token = address(permitted["token"]);
26540
+ const amount = uint(permitted["amount"], MAX_UINT256);
26541
+ return token === void 0 || amount === void 0 ? void 0 : allow(token, amount, "transfer", MAX_UINT256, _objectSpread2({ via }, deadline <= MAX_UINT48 ? { expiration: Number(deadline) } : {}));
26542
+ };
26543
+ const all = (list, build) => {
26544
+ const built = list === null || list === void 0 ? void 0 : list.map(build);
26545
+ return built === void 0 || built.some((a) => a === void 0) ? void 0 : permit(...built.filter((a) => a !== void 0));
26546
+ };
26547
+ if (primaryType === "PermitSingle") {
26548
+ const { details } = message;
26549
+ return sameFields(types, primaryType, [
26550
+ "PermitDetails details",
26551
+ "address spender",
26552
+ "uint256 sigDeadline"
26553
+ ]) && sameFields(types, "PermitDetails", DETAILS) && isMessage$1(details) ? all([details], allowance) : void 0;
26554
+ }
26555
+ if (primaryType === "PermitBatch") return sameFields(types, primaryType, [
26556
+ "PermitDetails[] details",
26557
+ "address spender",
26558
+ "uint256 sigDeadline"
26559
+ ]) && sameFields(types, "PermitDetails", DETAILS) ? all(entries(message["details"]), allowance) : void 0;
26560
+ const witness = primaryType.includes("Witness");
26561
+ const batch = primaryType.includes("Batch");
26562
+ const expected = batch ? [
26563
+ "TokenPermissions[] permitted",
26564
+ "address spender",
26565
+ "uint256 nonce",
26566
+ "uint256 deadline"
26567
+ ] : [
26568
+ "TokenPermissions permitted",
26569
+ "address spender",
26570
+ "uint256 nonce",
26571
+ "uint256 deadline"
26572
+ ];
26573
+ if (primaryType !== `Permit${batch ? "Batch" : ""}${witness ? "Witness" : ""}TransferFrom`) return;
26574
+ const own = types[primaryType];
26575
+ const last = own === null || own === void 0 ? void 0 : own.at(-1);
26576
+ 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);
26577
+ const deadline = uint(message["deadline"], MAX_UINT256);
26578
+ if (!fieldsOk || !sameFields(types, "TokenPermissions", PERMISSIONS) || deadline === void 0) return;
26579
+ const { permitted } = message;
26580
+ const result = batch ? all(entries(permitted), (item) => transfer(item, deadline)) : isMessage$1(permitted) ? all([permitted], (item) => transfer(item, deadline)) : void 0;
26581
+ return result === void 0 || !witness ? result : {
26582
+ approvals: result.approvals,
26583
+ warnings: [WITNESS_WARNING]
26584
+ };
26585
+ };
26586
+ /**
26587
+ * Recognition of Safe `SafeTx` typed data. A document is recognized only when the primary type is
26588
+ * `SafeTx` with exactly the canonical field list and the domain names a `verifyingContract` (the
26589
+ * Safe); any other shape stays an opaque message. A `delegatecall` to a canonical MultiSendCallOnly
26590
+ * contract is unpacked into its inner calls; anything else stays a single opaque call.
26591
+ */
26592
+ /**
26593
+ * Canonical MultiSendCallOnly deployments (safe-global/safe-deployments): 1.3.0, the 1.3.0 eip155
26594
+ * variant and 1.4.1, lowercase for a checksum-insensitive compare.
26595
+ */
26596
+ var SAFE_MULTISEND_CALL_ONLY = /* @__PURE__ */ new Set([
26597
+ "0x40a2accbd92bca938b02010e17a5b8929b49130d",
26598
+ "0xa1dabef33b3b82c7814b6d82a79e50f4ac44102b",
26599
+ "0x9641d764fc13c8b624c04430c7356c1c7c8102e2"
26600
+ ]);
26601
+ var SAFE_TX = [
26602
+ "address to",
26603
+ "uint256 value",
26604
+ "bytes data",
26605
+ "uint8 operation",
26606
+ "uint256 safeTxGas",
26607
+ "uint256 baseGas",
26608
+ "uint256 gasPrice",
26609
+ "address gasToken",
26610
+ "address refundReceiver",
26611
+ "uint256 nonce"
26612
+ ];
26613
+ var MULTISEND = from$2("function multiSend(bytes transactions)");
26614
+ /**
26615
+ * Packed MultiSend entries (`uint8 operation, address to, uint256 value, uint256 dataLength, bytes
26616
+ * data` repeated). `undefined` when `data` is not a `multiSend(bytes)` call, a byte is truncated or
26617
+ * trailing, or an entry's operation is not 0 — the caller falls back to one opaque call.
26618
+ */
26619
+ var multiSendEntries = (data) => {
26620
+ if (!data.toLowerCase().startsWith("0x8d80ff0a")) return;
26621
+ let packed;
26622
+ try {
26623
+ const decoded = decodeData(MULTISEND, data);
26624
+ const first = Array.isArray(decoded) ? decoded[0] : void 0;
26625
+ if (typeof first !== "string") return;
26626
+ packed = first;
26627
+ } catch (_unused) {
26628
+ return;
26629
+ }
26630
+ if (!packed.startsWith("0x")) return;
26631
+ const hex = packed.slice(2).toLowerCase();
26632
+ const calls = [];
26633
+ let offset = 0;
26634
+ while (offset < hex.length) {
26635
+ if (hex.length - offset < 170) return;
26636
+ if (Number.parseInt(hex.slice(offset, offset + 2), 16) !== 0) return;
26637
+ const to = `0x${hex.slice(offset + 2, offset + 42)}`;
26638
+ const value = BigInt(`0x${hex.slice(offset + 42, offset + 106)}`);
26639
+ const length = BigInt(`0x${hex.slice(offset + 106, offset + 170)}`);
26640
+ offset += 170;
26641
+ if (length * 2n > BigInt(hex.length - offset)) return;
26642
+ calls.push({
26643
+ to: checksumEvmAddress(to),
26644
+ value,
26645
+ data: `0x${hex.slice(offset, offset + Number(length) * 2)}`
26646
+ });
26647
+ offset += Number(length) * 2;
26648
+ }
26649
+ return calls;
26650
+ };
26651
+ /**
26652
+ * The Safe transaction a typed-data document signs, or `undefined` when its shape is not exactly
26653
+ * the recognized one. `decode` decodes one inner call (the transaction rules without a fee); the
26654
+ * caller injects it bound to the request's network and token table.
26655
+ */
26656
+ function recognizeSafe(json, decode) {
26657
+ const { types, primaryType, message, domain } = json;
26658
+ if (primaryType !== "SafeTx" || !sameFields(types, "SafeTx", SAFE_TX)) return;
26659
+ const safe = typedDataAddress(domain["verifyingContract"]);
26660
+ const to = typedDataAddress(message["to"]);
26661
+ const value = typedDataUint(message["value"], MAX_UINT256);
26662
+ const data = typedDataBytes(message["data"]);
26663
+ const operation = typedDataUint(message["operation"], 255n);
26664
+ const safeTxGas = typedDataUint(message["safeTxGas"], MAX_UINT256);
26665
+ const baseGas = typedDataUint(message["baseGas"], MAX_UINT256);
26666
+ const gasPrice = typedDataUint(message["gasPrice"], MAX_UINT256);
26667
+ const gasToken = typedDataAddress(message["gasToken"]);
26668
+ const refundReceiver = typedDataAddress(message["refundReceiver"]);
26669
+ const nonce = typedDataUint(message["nonce"], MAX_UINT256);
26670
+ 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;
26671
+ const inner = operation === 1n && SAFE_MULTISEND_CALL_ONLY.has(to.toLowerCase()) ? multiSendEntries(data) : void 0;
26672
+ const calls = (inner !== null && inner !== void 0 ? inner : [{
26673
+ to,
26674
+ value,
26675
+ data
26676
+ }]).map(decode);
26677
+ return {
26678
+ safe: _objectSpread2({
26679
+ safe,
26680
+ nonce: nonce.toString(10),
26681
+ operation: operation === 0n ? "call" : "delegatecall",
26682
+ to,
26683
+ value: value.toString(10),
26684
+ data,
26685
+ calls
26686
+ }, gasPrice > 0n ? { refund: {
26687
+ gasPrice: gasPrice.toString(10),
26688
+ gasToken,
26689
+ refundReceiver
26690
+ } } : {}),
26691
+ multisend: inner !== void 0
26692
+ };
26693
+ }
26694
+ /** Seaport 1.5 and 1.6 deployments, lowercase for a checksum-insensitive compare. */
26695
+ var SEAPORT_CONTRACTS = /* @__PURE__ */ new Set(["0x0000000000000068f116a894984e2db1123eb395", "0x00000000000000adc04c56bf30ac9d3c0aaf14dc"]);
26696
+ /** Seaport `itemType` values 0–5; an item type outside the list is not recognized. */
26697
+ var ITEM_KINDS = [
26698
+ "native",
26699
+ "erc20",
26700
+ "erc721",
26701
+ "erc1155",
26702
+ "erc721-criteria",
26703
+ "erc1155-criteria"
26704
+ ];
26705
+ var ITEM_FIELDS = [
26706
+ "uint8 itemType",
26707
+ "address token",
26708
+ "uint256 identifierOrCriteria",
26709
+ "uint256 startAmount",
26710
+ "uint256 endAmount"
26711
+ ];
26712
+ var typesMatch = (types) => Object.keys(types).length === 3 && sameFields(types, "OrderComponents", [
26713
+ "address offerer",
26714
+ "address zone",
26715
+ "OfferItem[] offer",
26716
+ "ConsiderationItem[] consideration",
26717
+ "uint8 orderType",
26718
+ "uint256 startTime",
26719
+ "uint256 endTime",
26720
+ "bytes32 zoneHash",
26721
+ "uint256 salt",
26722
+ "bytes32 conduitKey",
26723
+ "uint256 counter"
26724
+ ]) && sameFields(types, "OfferItem", ITEM_FIELDS) && sameFields(types, "ConsiderationItem", [...ITEM_FIELDS, "address recipient"]);
26725
+ var amount = (kind, token, value, chainId, table) => {
26726
+ if (kind === "native") return {
26727
+ asset: EVM_NATIVE_ASSET,
26728
+ amount: value.toString(10),
26729
+ symbol: "ETH",
26730
+ decimals: 18
26731
+ };
26732
+ if (kind === "erc20") {
26733
+ const found = lookupEvmToken(table, chainId, token);
26734
+ return _objectSpread2({
26735
+ asset: token,
26736
+ amount: value.toString(10)
26737
+ }, found === void 0 ? {} : {
26738
+ symbol: found.symbol,
26739
+ decimals: found.decimals
26740
+ });
26741
+ }
26742
+ return {
26743
+ asset: token,
26744
+ amount: value.toString(10)
26745
+ };
26746
+ };
26747
+ var item = (message, chainId, table) => {
26748
+ const itemType = typedDataUint(message["itemType"], 255n);
26749
+ const token = typedDataAddress(message["token"]);
26750
+ const identifier = typedDataUint(message["identifierOrCriteria"], MAX_UINT256);
26751
+ const start = typedDataUint(message["startAmount"], MAX_UINT256);
26752
+ const end = typedDataUint(message["endAmount"], MAX_UINT256);
26753
+ const kind = itemType === void 0 ? void 0 : ITEM_KINDS[Number(itemType)];
26754
+ if (token === void 0 || identifier === void 0 || start === void 0 || end === void 0 || kind === void 0) return;
26755
+ return {
26756
+ kind,
26757
+ token,
26758
+ identifier: identifier.toString(10),
26759
+ startAmount: amount(kind, token, start, chainId, table),
26760
+ endAmount: amount(kind, token, end, chainId, table)
26761
+ };
26762
+ };
26763
+ var all = (list, build) => {
26764
+ const built = list === null || list === void 0 ? void 0 : list.map(build);
26765
+ return built === void 0 || built.some((entry) => entry === void 0) ? void 0 : built.filter((entry) => entry !== void 0);
26766
+ };
26767
+ /**
26768
+ * The Seaport order a typed-data document signs, or `undefined` when its shape is not exactly the
26769
+ * recognized one. `chainId` is the request network's, used for the built-in token table.
26770
+ */
26771
+ function recognizeSeaport(json, chainId, table) {
26772
+ const { types, primaryType, message, domain } = json;
26773
+ if (primaryType !== "OrderComponents" || !typesMatch(types)) return;
26774
+ const verifying = typedDataAddress(domain["verifyingContract"]);
26775
+ if (domain["name"] !== "Seaport" || verifying === void 0 || !SEAPORT_CONTRACTS.has(verifying.toLowerCase())) return;
26776
+ const offerer = typedDataAddress(message["offerer"]);
26777
+ const zone = typedDataAddress(message["zone"]);
26778
+ const startTime = typedDataUint(message["startTime"], MAX_UINT256);
26779
+ const endTime = typedDataUint(message["endTime"], MAX_UINT256);
26780
+ const offer = all(typedDataMessages(message["offer"]), (entry) => item(entry, chainId, table));
26781
+ const consideration = all(typedDataMessages(message["consideration"]), (entry) => {
26782
+ const base = item(entry, chainId, table);
26783
+ const recipient = typedDataAddress(entry["recipient"]);
26784
+ return base === void 0 || recipient === void 0 ? void 0 : _objectSpread2(_objectSpread2({}, base), {}, { recipient });
26785
+ });
26786
+ if (offerer === void 0 || zone === void 0 || startTime === void 0 || endTime === void 0 || offer === void 0 || consideration === void 0) return;
26787
+ return {
26788
+ offerer,
26789
+ zone,
26790
+ startTime: startTime <= MAX_UINT48 ? Number(startTime) : void 0,
26791
+ endTime: endTime <= MAX_UINT48 ? Number(endTime) : void 0,
26792
+ offer,
26793
+ consideration
26794
+ };
26795
+ }
25165
26796
  var ERC20_TRANSFER = from$2("function transfer(address to, uint256 amount)");
25166
26797
  var ERC20_APPROVE = from$2("function approve(address spender, uint256 amount)");
25167
26798
  var ERC20_INCREASE = from$2("function increaseAllowance(address spender, uint256 amount)");
26799
+ var ERC20_DECREASE = from$2("function decreaseAllowance(address spender, uint256 subtractedValue)");
26800
+ var SET_APPROVAL_FOR_ALL = from$2("function setApprovalForAll(address operator, bool approved)");
26801
+ var PERMIT2_APPROVE = from$2("function approve(address token, address spender, uint160 amount, uint48 expiration)");
26802
+ var PERMIT2_LOCKDOWN = from$2("function lockdown((address token, address spender)[] approvals)");
26803
+ var ERC721_SAFE_FROM_DATA = from$2("function safeTransferFrom(address from, address to, uint256 tokenId, bytes data)");
26804
+ var ERC1155_SAFE_BATCH_FROM = from$2("function safeBatchTransferFrom(address from, address to, uint256[] ids, uint256[] amounts, bytes data)");
25168
26805
  var ERC721_TRANSFER_FROM = from$2("function transferFrom(address from, address to, uint256 tokenId)");
25169
26806
  var ERC721_SAFE_FROM = from$2("function safeTransferFrom(address from, address to, uint256 tokenId)");
25170
26807
  var ERC1155_SAFE_FROM = from$2("function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes data)");
25171
- var NATIVE_ASSET = "native";
25172
- var MAX_UINT256 = 2n ** 256n - 1n;
25173
26808
  var argAddress = (args, index) => {
25174
26809
  const value = args[index];
25175
26810
  if (typeof value !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(value)) throw new ChainError("invalid-request", "decoded argument is not an address");
@@ -25193,28 +26828,27 @@ zoo`.split("\n"));
25193
26828
  const args = decodeData(fn, data);
25194
26829
  if (!Array.isArray(args)) return;
25195
26830
  return encodeData(fn, args).toLowerCase() === data.toLowerCase() ? args : void 0;
25196
- } catch (_unused) {
26831
+ } catch (_unused2) {
25197
26832
  return;
25198
26833
  }
25199
26834
  };
25200
26835
  var weiAmount = (wei, symbol, decimals) => _objectSpread2(_objectSpread2({
25201
- asset: NATIVE_ASSET,
26836
+ asset: EVM_NATIVE_ASSET,
25202
26837
  amount: wei.toString(10)
25203
26838
  }, symbol === void 0 ? {} : { symbol }), decimals === void 0 ? {} : { decimals });
25204
- var feeWei = (tx) => BigInt(tx.gas) * (tx.type === "eip1559" ? BigInt(tx.maxFeePerGas) : BigInt(tx.gasPrice));
25205
- var nativeOutflow = (tx, to) => [{
26839
+ var feeWei = (tx) => quantityBigInt(tx.gas, "tx.gas") * (tx.type === "eip1559" ? quantityBigInt(tx.maxFeePerGas, "tx.maxFeePerGas") : quantityBigInt(tx.gasPrice, "tx.gasPrice"));
26840
+ var nativeOutflow = (value, to) => [{
25206
26841
  to,
25207
- amount: weiAmount(BigInt(tx.value)),
26842
+ amount: weiAmount(value),
25208
26843
  verified: true
25209
26844
  }];
25210
- var tokenFlow = (tx, to, amount, chainId, table) => {
25211
- var _tx$to, _tx$to2;
25212
- const token = lookupEvmToken(table, chainId, (_tx$to = tx.to) !== null && _tx$to !== void 0 ? _tx$to : "");
26845
+ var tokenFlow = (target, to, amount, chainId, table) => {
26846
+ const token = lookupEvmToken(table, chainId, target);
25213
26847
  return {
25214
26848
  flows: [{
25215
26849
  to,
25216
26850
  amount: _objectSpread2({
25217
- asset: (_tx$to2 = tx.to) !== null && _tx$to2 !== void 0 ? _tx$to2 : "",
26851
+ asset: target,
25218
26852
  amount: amount.toString(10)
25219
26853
  }, token === void 0 ? {} : {
25220
26854
  symbol: token.symbol,
@@ -25225,15 +26859,23 @@ zoo`.split("\n"));
25225
26859
  verified: token !== void 0
25226
26860
  };
25227
26861
  };
25228
- var approvalChange = (tx, spender, amount) => {
25229
- var _tx$to3;
25230
- return {
25231
- asset: (_tx$to3 = tx.to) !== null && _tx$to3 !== void 0 ? _tx$to3 : "",
25232
- spender,
25233
- amount: amount.toString(10),
25234
- unlimited: amount === MAX_UINT256,
25235
- verified: false
25236
- };
26862
+ var argBool = (args, index) => {
26863
+ const value = args[index];
26864
+ if (typeof value !== "boolean") throw new ChainError("invalid-request", "decoded argument is not a bool");
26865
+ return value;
26866
+ };
26867
+ var argList = (args, index) => {
26868
+ const value = args[index];
26869
+ if (!Array.isArray(value)) throw new ChainError("invalid-request", "decoded argument is not an array");
26870
+ return value;
26871
+ };
26872
+ var argSeconds = (args, index) => {
26873
+ const value = args[index];
26874
+ if (typeof value !== "number" && typeof value !== "bigint") throw new ChainError("invalid-request", "decoded argument is not an integer");
26875
+ return Number(value);
26876
+ };
26877
+ var pairField = (pair, key) => {
26878
+ return argAddress([typeof pair === "object" && pair !== null ? Reflect.get(pair, key) : ""], 0);
25237
26879
  };
25238
26880
  var nftFlow = (asset, to, id) => [{
25239
26881
  to,
@@ -25243,20 +26885,22 @@ zoo`.split("\n"));
25243
26885
  },
25244
26886
  verified: false
25245
26887
  }];
25246
- var decodeTransaction$1 = (request, table) => {
25247
- var _tx$to5;
25248
- const { tx } = request;
25249
- const chainId = networkChainId(request.network);
25250
- const data = tx.data.toLowerCase();
25251
- const fee = { max: weiAmount(feeWei(tx)) };
26888
+ /**
26889
+ * The call rules shared by a whole transaction and a Safe's inner calls: the same selector table
26890
+ * produces the intent; `fee` is `undefined` for a call that is not itself a transaction.
26891
+ */
26892
+ var decodeCall = (call, network, fee, table) => {
26893
+ var _call$to2;
26894
+ const chainId = networkChainId(network);
26895
+ const data = call.data.toLowerCase();
25252
26896
  const base = {
25253
26897
  family: "evm",
25254
- network: request.network,
26898
+ network,
25255
26899
  approvals: [],
25256
26900
  warnings: []
25257
26901
  };
25258
26902
  if (data === "0x") {
25259
- if (tx.to === void 0) return _objectSpread2(_objectSpread2({}, base), {}, {
26903
+ if (call.to === void 0) return _objectSpread2(_objectSpread2({}, base), {}, {
25260
26904
  summary: "contract-call",
25261
26905
  outflows: [],
25262
26906
  fee,
@@ -25264,14 +26908,15 @@ zoo`.split("\n"));
25264
26908
  });
25265
26909
  return _objectSpread2(_objectSpread2({}, base), {}, {
25266
26910
  summary: "transfer",
25267
- outflows: nativeOutflow(tx, tx.to),
26911
+ outflows: nativeOutflow(call.value, call.to),
25268
26912
  fee,
25269
26913
  verifiability: "full"
25270
26914
  });
25271
26915
  }
25272
26916
  const transferArgs = tryCall(ERC20_TRANSFER, data);
25273
26917
  if (transferArgs !== void 0) {
25274
- const { flows, verified } = tokenFlow(tx, argAddress(transferArgs, 0), argUint(transferArgs, 1), chainId, table);
26918
+ var _call$to;
26919
+ const { flows, verified } = tokenFlow((_call$to = call.to) !== null && _call$to !== void 0 ? _call$to : "", argAddress(transferArgs, 0), argUint(transferArgs, 1), chainId, table);
25275
26920
  return _objectSpread2(_objectSpread2({}, base), {}, {
25276
26921
  summary: "transfer",
25277
26922
  outflows: flows,
@@ -25279,39 +26924,63 @@ zoo`.split("\n"));
25279
26924
  verifiability: verified ? "full" : "partial"
25280
26925
  });
25281
26926
  }
25282
- const approveArgs = tryCall(ERC20_APPROVE, data);
25283
- if (approveArgs !== void 0) return _objectSpread2(_objectSpread2({}, base), {}, {
25284
- summary: "approve",
25285
- outflows: [],
25286
- approvals: [approvalChange(tx, argAddress(approveArgs, 0), argUint(approveArgs, 1))],
25287
- fee,
25288
- verifiability: "partial"
25289
- });
25290
- const increaseArgs = tryCall(ERC20_INCREASE, data);
25291
- if (increaseArgs !== void 0) return _objectSpread2(_objectSpread2({}, base), {}, {
25292
- summary: "approve",
25293
- outflows: [],
25294
- approvals: [approvalChange(tx, argAddress(increaseArgs, 0), argUint(increaseArgs, 1))],
26927
+ const partial = (summary, outflows, approvals) => _objectSpread2(_objectSpread2({}, base), {}, {
26928
+ summary,
26929
+ outflows,
26930
+ approvals,
25295
26931
  fee,
25296
26932
  verifiability: "partial"
25297
26933
  });
25298
- for (const fn of [ERC721_TRANSFER_FROM, ERC721_SAFE_FROM]) {
25299
- var _tx$to4;
26934
+ const token = (_call$to2 = call.to) !== null && _call$to2 !== void 0 ? _call$to2 : "";
26935
+ if (token.toLowerCase() === "0x000000000022D473030F116dDEE9F6B43aC78BA3".toLowerCase()) {
26936
+ const permitArgs = tryCall(PERMIT2_APPROVE, data);
26937
+ if (permitArgs !== void 0) {
26938
+ const amount = argUint(permitArgs, 2);
26939
+ return partial("approve", [], [allowanceChange(argAddress(permitArgs, 0), argAddress(permitArgs, 1), amount, "set", MAX_UINT160, chainId, table, {
26940
+ via: "permit2",
26941
+ expiration: argSeconds(permitArgs, 3)
26942
+ })]);
26943
+ }
26944
+ const lockdownArgs = tryCall(PERMIT2_LOCKDOWN, data);
26945
+ 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" })));
26946
+ }
26947
+ for (const [fn, change] of [
26948
+ [ERC20_APPROVE, "set"],
26949
+ [ERC20_INCREASE, "increase"],
26950
+ [ERC20_DECREASE, "decrease"]
26951
+ ]) {
25300
26952
  const args = tryCall(fn, data);
25301
- if (args !== void 0) return _objectSpread2(_objectSpread2({}, base), {}, {
25302
- summary: "transfer",
25303
- outflows: nftFlow((_tx$to4 = tx.to) !== null && _tx$to4 !== void 0 ? _tx$to4 : "", argAddress(args, 1), argUint(args, 2)),
25304
- fee,
25305
- verifiability: "partial"
25306
- });
26953
+ if (args !== void 0) return partial("approve", [], [allowanceChange(token, argAddress(args, 0), argUint(args, 1), change, MAX_UINT256, chainId, table)]);
26954
+ }
26955
+ const operatorArgs = tryCall(SET_APPROVAL_FOR_ALL, data);
26956
+ if (operatorArgs !== void 0) return partial("approve", [], [{
26957
+ kind: "operator",
26958
+ asset: token,
26959
+ spender: argAddress(operatorArgs, 0),
26960
+ approved: argBool(operatorArgs, 1),
26961
+ verified: false
26962
+ }]);
26963
+ const transferFromArgs = tryCall(ERC721_TRANSFER_FROM, data);
26964
+ if (transferFromArgs !== void 0) {
26965
+ const to = argAddress(transferFromArgs, 1);
26966
+ const id = argUint(transferFromArgs, 2);
26967
+ if (lookupEvmToken(table, chainId, token) !== void 0) return partial("transfer", tokenFlow(token, to, id, chainId, table).flows, []);
26968
+ return partial("transfer", nftFlow(token, to, id), []);
26969
+ }
26970
+ for (const fn of [ERC721_SAFE_FROM, ERC721_SAFE_FROM_DATA]) {
26971
+ const args = tryCall(fn, data);
26972
+ if (args !== void 0) return partial("transfer", nftFlow(token, argAddress(args, 1), argUint(args, 2)), []);
25307
26973
  }
25308
26974
  const erc1155Args = tryCall(ERC1155_SAFE_FROM, data);
25309
- if (erc1155Args !== void 0) return _objectSpread2(_objectSpread2({}, base), {}, {
25310
- summary: "transfer",
25311
- outflows: nftFlow((_tx$to5 = tx.to) !== null && _tx$to5 !== void 0 ? _tx$to5 : "", argAddress(erc1155Args, 1), argUint(erc1155Args, 2)),
25312
- fee,
25313
- verifiability: "partial"
25314
- });
26975
+ if (erc1155Args !== void 0) return partial("transfer", nftFlow(token, argAddress(erc1155Args, 1), argUint(erc1155Args, 2)), []);
26976
+ const batchArgs = tryCall(ERC1155_SAFE_BATCH_FROM, data);
26977
+ if (batchArgs !== void 0) {
26978
+ const ids = argList(batchArgs, 2);
26979
+ if (ids.length > 0 && ids.length === argList(batchArgs, 3).length) {
26980
+ const to = argAddress(batchArgs, 1);
26981
+ return partial("transfer", ids.flatMap((id) => nftFlow(token, to, argUint([id], 0))), []);
26982
+ }
26983
+ }
25315
26984
  return _objectSpread2(_objectSpread2({}, base), {}, {
25316
26985
  summary: "contract-call",
25317
26986
  outflows: [],
@@ -25319,11 +26988,46 @@ zoo`.split("\n"));
25319
26988
  verifiability: "opaque"
25320
26989
  });
25321
26990
  };
26991
+ var decodeTransaction$1 = (request, table) => {
26992
+ const { tx } = request;
26993
+ return decodeCall({
26994
+ to: tx.to,
26995
+ value: quantityBigInt(tx.value, "tx.value"),
26996
+ data: tx.data
26997
+ }, request.network, { max: weiAmount(feeWei(tx)) }, table);
26998
+ };
26999
+ /** The five EIP-712 domain fields a wallet shows; anything malformed is left out. */
27000
+ var displayDomain = (domain) => {
27001
+ const { name, version, verifyingContract, salt } = domain;
27002
+ const chainId = domainChainId(domain);
27003
+ 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 } : {});
27004
+ };
27005
+ /** Strict UTF-8 text with any sign-in recognition, else the raw bytes as hex. */
27006
+ var messageContent = (bytes) => {
27007
+ try {
27008
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
27009
+ const signIn = parseSignIn(text, "evm");
27010
+ return signIn === void 0 ? {
27011
+ kind: "text",
27012
+ text
27013
+ } : {
27014
+ kind: "text",
27015
+ text,
27016
+ signIn
27017
+ };
27018
+ } catch (_unused3) {
27019
+ return {
27020
+ kind: "bytes",
27021
+ hex: `0x${[...bytes].map((b) => b.toString(16).padStart(2, "0")).join("")}`
27022
+ };
27023
+ }
27024
+ };
25322
27025
  /**
25323
27026
  * Decodes a normalized request into a DisplayIntent. The token table parameter is for tests;
25324
27027
  * production callers use the built-in table.
25325
27028
  */
25326
27029
  var decodeEvm = (request, table = evmTokenTable) => {
27030
+ var _safe$safe$calls$0$su, _safe$safe$calls$, _permit$approvals, _permit$warnings;
25327
27031
  if (request.kind === "evm.transaction") return decodeTransaction$1(request, table);
25328
27032
  if (request.kind === "evm.personal-message") return {
25329
27033
  family: "evm",
@@ -25333,19 +27037,32 @@ zoo`.split("\n"));
25333
27037
  approvals: [],
25334
27038
  fee: void 0,
25335
27039
  warnings: [],
27040
+ message: messageContent(request.message),
25336
27041
  verifiability: "opaque"
25337
27042
  };
25338
27043
  if (request.kind !== "evm.typed-data") throw new ChainError("unsupported", `unsupported sign request kind: ${request.kind}`);
25339
- const parsed = parseTypedData(request.typedData, request.network);
27044
+ const { json } = parseTypedData(request.typedData);
27045
+ const chainId = networkChainId(request.network);
27046
+ const permit = recognizePermit(json, chainId, table);
27047
+ const seaport = permit === void 0 ? recognizeSeaport(json, chainId, table) : void 0;
27048
+ const safe = permit === void 0 && seaport === void 0 ? recognizeSafe(json, (call) => decodeCall(call, request.network, void 0, table)) : void 0;
27049
+ const message = _objectSpread2(_objectSpread2({
27050
+ kind: "typed-data",
27051
+ primaryType: json.primaryType,
27052
+ domain: displayDomain(json.domain),
27053
+ data: json.message
27054
+ }, seaport === void 0 ? {} : { seaport }), safe === void 0 ? {} : { safe: safe.safe });
27055
+ 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";
25340
27056
  return {
25341
27057
  family: "evm",
25342
27058
  network: request.network,
25343
- summary: "message",
27059
+ summary,
25344
27060
  outflows: [],
25345
- approvals: [],
27061
+ approvals: (_permit$approvals = permit === null || permit === void 0 ? void 0 : permit.approvals) !== null && _permit$approvals !== void 0 ? _permit$approvals : [],
25346
27062
  fee: void 0,
25347
- warnings: typedDataWarnings(parsed),
25348
- verifiability: "opaque"
27063
+ warnings: (_permit$warnings = permit === null || permit === void 0 ? void 0 : permit.warnings) !== null && _permit$warnings !== void 0 ? _permit$warnings : [],
27064
+ message,
27065
+ verifiability: permit === void 0 ? "opaque" : "partial"
25349
27066
  };
25350
27067
  };
25351
27068
  /**
@@ -25379,7 +27096,9 @@ zoo`.split("\n"));
25379
27096
  if (request["kind"] === "evm.typed-data") {
25380
27097
  const { typedData } = request;
25381
27098
  if (typeof typedData !== "string") throw new ChainError("invalid-request", "typed-data payload must be the JSON source string");
25382
- parseTypedData(typedData, network);
27099
+ const { json } = parseTypedData(typedData);
27100
+ const domainChain = domainChainId(json.domain);
27101
+ if (domainChain !== void 0 && domainChain !== chainId) throw new ChainError("chain-id-mismatch", `typed-data domain.chainId ${domainChain} does not match network ${network}`);
25383
27102
  return {
25384
27103
  kind: "evm.typed-data",
25385
27104
  network,
@@ -26777,8 +28496,11 @@ zoo`.split("\n"));
26777
28496
  numRequiredSignatures: message.numSignerAccounts,
26778
28497
  staticAccounts,
26779
28498
  instructions: message.instructions,
26780
- lookupCount: lookups.length,
26781
- lookupAddresses: lookups.map((l) => l.lookupTableAddress)
28499
+ lookups: lookups.map((l) => ({
28500
+ address: l.lookupTableAddress,
28501
+ writableIndexes: l.writableIndexes,
28502
+ readonlyIndexes: l.readonlyIndexes
28503
+ }))
26782
28504
  };
26783
28505
  };
26784
28506
  var isRecord$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
@@ -26838,6 +28560,8 @@ zoo`.split("\n"));
26838
28560
  if (tables === void 0) return;
26839
28561
  for (const table of tables) if (!isSolanaAddress(table.address) || !table.addresses.every(isSolanaAddress)) throw new ChainError("invalid-address", "lookup table entries must be base58 32-byte addresses");
26840
28562
  };
28563
+ /** The native asset id in `AssetFlow` and simulated asset changes. */
28564
+ var SOLANA_NATIVE_ASSET = "lamports";
26841
28565
  var USDC = Object.freeze({
26842
28566
  symbol: "USDC",
26843
28567
  decimals: 6,
@@ -26856,7 +28580,6 @@ zoo`.split("\n"));
26856
28580
  var _table$network;
26857
28581
  return (_table$network = table[network]) === null || _table$network === void 0 ? void 0 : _table$network[mint];
26858
28582
  };
26859
- var LAMPORTS_ASSET = "lamports";
26860
28583
  var u32 = getU32Decoder();
26861
28584
  var u64$1 = getU64Decoder();
26862
28585
  var u32le = (data, offset) => u32.decode(data, offset);
@@ -26920,7 +28643,7 @@ zoo`.split("\n"));
26920
28643
  "ata-create-idempotent"
26921
28644
  ]);
26922
28645
  var classify$1 = (parsed, calls, network, table) => {
26923
- if (parsed.lookupCount > 0) return "partial";
28646
+ if (parsed.lookups.length > 0) return "partial";
26924
28647
  let allFull = true;
26925
28648
  for (const call of calls) {
26926
28649
  var _call$mint;
@@ -26950,14 +28673,13 @@ zoo`.split("\n"));
26950
28673
  const outflows = [];
26951
28674
  const approvals = [];
26952
28675
  for (const call of calls) {
26953
- var _call$mint4, _call$to2, _call$amount3;
26954
28676
  if (call.kind === "system-transfer" && call.to !== void 0) {
26955
28677
  var _call$amount;
26956
28678
  const [source] = parsed.staticAccounts;
26957
28679
  if (source === signer) outflows.push({
26958
28680
  to: call.to,
26959
28681
  amount: {
26960
- asset: LAMPORTS_ASSET,
28682
+ asset: SOLANA_NATIVE_ASSET,
26961
28683
  amount: ((_call$amount = call.amount) !== null && _call$amount !== void 0 ? _call$amount : 0n).toString(10)
26962
28684
  },
26963
28685
  verified: true
@@ -26978,13 +28700,24 @@ zoo`.split("\n"));
26978
28700
  verified: token !== void 0
26979
28701
  });
26980
28702
  }
26981
- if (call.kind === "token-approve") approvals.push({
26982
- asset: (_call$mint4 = call.mint) !== null && _call$mint4 !== void 0 ? _call$mint4 : "",
26983
- spender: (_call$to2 = call.to) !== null && _call$to2 !== void 0 ? _call$to2 : "",
26984
- amount: ((_call$amount3 = call.amount) !== null && _call$amount3 !== void 0 ? _call$amount3 : 0n).toString(10),
26985
- unlimited: false,
26986
- verified: false
26987
- });
28703
+ if (call.kind === "token-approve") {
28704
+ var _call$mint4, _call$to2, _call$mint5, _call$amount3;
28705
+ const token = lookupSolanaToken(table, request.network, (_call$mint4 = call.mint) !== null && _call$mint4 !== void 0 ? _call$mint4 : "");
28706
+ approvals.push({
28707
+ kind: "allowance",
28708
+ spender: (_call$to2 = call.to) !== null && _call$to2 !== void 0 ? _call$to2 : "",
28709
+ amount: _objectSpread2({
28710
+ asset: (_call$mint5 = call.mint) !== null && _call$mint5 !== void 0 ? _call$mint5 : "",
28711
+ amount: ((_call$amount3 = call.amount) !== null && _call$amount3 !== void 0 ? _call$amount3 : 0n).toString(10)
28712
+ }, token === void 0 ? {} : {
28713
+ symbol: token.symbol,
28714
+ decimals: token.decimals
28715
+ }),
28716
+ change: "set",
28717
+ unlimited: false,
28718
+ verified: token !== void 0
28719
+ });
28720
+ }
26988
28721
  }
26989
28722
  const fee = feeLamports(parsed, calls);
26990
28723
  return {
@@ -26994,7 +28727,7 @@ zoo`.split("\n"));
26994
28727
  outflows,
26995
28728
  approvals,
26996
28729
  fee: fee === void 0 ? void 0 : { max: {
26997
- asset: LAMPORTS_ASSET,
28730
+ asset: SOLANA_NATIVE_ASSET,
26998
28731
  amount: fee.toString(10)
26999
28732
  } },
27000
28733
  warnings: [],
@@ -27081,7 +28814,8 @@ zoo`.split("\n"));
27081
28814
  const tx = Transaction.fromPSBT(psbt);
27082
28815
  for (const { index, privateKey } of inputs) {
27083
28816
  if (privateKey.length !== 32) throw new ChainError("invalid-request", `input ${index}: private key must be 32 bytes`);
27084
- if (!tx.signIdx(privateKey, index, void 0, auxRand(index))) throw new ChainError("invalid-request", `input ${index}: key cannot sign`);
28817
+ const allowed = tx.getInput(index).sighashType === SigHash.SINGLE_ANYONECANPAY ? [SigHash.SINGLE_ANYONECANPAY] : void 0;
28818
+ if (!tx.signIdx(privateKey, index, allowed, auxRand(index))) throw new ChainError("invalid-request", `input ${index}: key cannot sign`);
27085
28819
  }
27086
28820
  return tx.toPSBT(0);
27087
28821
  };
@@ -27093,6 +28827,7 @@ zoo`.split("\n"));
27093
28827
  return signBip322Simple(request.message, scriptPubKey, privateKey, auxRand);
27094
28828
  };
27095
28829
  // packages/wallet-kernel/src/modules/chains/prompt.ts
28830
+ init_objectSpread2();
27096
28831
  /** Off-chain messages carry no decodable value flow. */
27097
28832
  var MESSAGE_INTENT = {
27098
28833
  summary: "message",
@@ -27101,6 +28836,21 @@ zoo`.split("\n"));
27101
28836
  fee: void 0,
27102
28837
  verifiability: "opaque"
27103
28838
  };
28839
+ var utf8 = new TextDecoder("utf-8", { fatal: true });
28840
+ /** The prompt intent of a raw message: its UTF-8 text, or the bytes as hex for a blind sign. */
28841
+ var messageIntent = (message) => {
28842
+ try {
28843
+ return _objectSpread2(_objectSpread2({}, MESSAGE_INTENT), {}, { message: {
28844
+ kind: "text",
28845
+ text: utf8.decode(message)
28846
+ } });
28847
+ } catch (_unused) {
28848
+ return _objectSpread2(_objectSpread2({}, MESSAGE_INTENT), {}, { message: {
28849
+ kind: "bytes",
28850
+ hex: `0x${[...message].map((b) => b.toString(16).padStart(2, "0")).join("")}`
28851
+ } });
28852
+ }
28853
+ };
27104
28854
  var CATALOGS$1 = {
27105
28855
  "zh-Hans": {
27106
28856
  titles: {
@@ -27112,12 +28862,23 @@ zoo`.split("\n"));
27112
28862
  authorization: "确认账户授权",
27113
28863
  batch: "确认批量交易"
27114
28864
  },
28865
+ blindTitle: "确认盲签",
28866
+ blindDescription: "签署无法显示为文字的数据",
27115
28867
  generic: "签署来自应用的请求",
27116
28868
  otherOutflows: "可能还有其他转出",
27117
28869
  send: (amount, to) => `发送 ${amount} 到 ${to}`,
27118
28870
  allow: (spender, amount) => `授权 ${spender} 使用 ${amount}`,
27119
28871
  unlimited: (asset) => `全部 ${asset}`,
27120
- maxFee: (fee) => `最高手续费 ${fee}`
28872
+ revoke: (spender, asset) => `撤销 ${spender} 对 ${asset} 的授权`,
28873
+ increase: (spender, amount) => `授权 ${spender} 再使用 ${amount}`,
28874
+ decrease: (spender, amount) => `减少 ${spender} 的授权额度 ${amount}`,
28875
+ takeOnce: (spender, amount) => `授权 ${spender} 一次性转走 ${amount}`,
28876
+ viaPermit2: " 经 Permit2",
28877
+ until: (date) => ` 至 ${date}(UTC)`,
28878
+ operatorAllow: (spender, asset) => `授权 ${spender} 转走 ${asset} 的全部代币`,
28879
+ operatorRevoke: (spender, asset) => `撤销 ${spender} 对 ${asset} 全部代币的授权`,
28880
+ maxFee: (fee) => `最高手续费 ${fee}`,
28881
+ sighashSingle: "已签输入只绑定同序号输出,交易其余部分可被改动"
27121
28882
  },
27122
28883
  en: {
27123
28884
  titles: {
@@ -27129,12 +28890,23 @@ zoo`.split("\n"));
27129
28890
  authorization: "Confirm account authorization",
27130
28891
  batch: "Confirm batch"
27131
28892
  },
28893
+ blindTitle: "Confirm blind signing",
28894
+ blindDescription: "Sign data that cannot be shown as text",
27132
28895
  generic: "Sign a request from an app",
27133
28896
  otherOutflows: "There may be other outflows",
27134
28897
  send: (amount, to) => `Send ${amount} to ${to}`,
27135
28898
  allow: (spender, amount) => `Allow ${spender} to spend ${amount}`,
27136
28899
  unlimited: (asset) => `unlimited ${asset}`,
27137
- maxFee: (fee) => `Max fee ${fee}`
28900
+ revoke: (spender, asset) => `Revoke ${spender}'s allowance for ${asset}`,
28901
+ increase: (spender, amount) => `Allow ${spender} to spend ${amount} more`,
28902
+ decrease: (spender, amount) => `Reduce ${spender}'s allowance by ${amount}`,
28903
+ takeOnce: (spender, amount) => `Allow ${spender} to take ${amount} once`,
28904
+ viaPermit2: " via Permit2",
28905
+ until: (date) => ` until ${date} (UTC)`,
28906
+ operatorAllow: (spender, asset) => `Allow ${spender} to transfer all tokens of ${asset}`,
28907
+ operatorRevoke: (spender, asset) => `Revoke ${spender}'s access to all tokens of ${asset}`,
28908
+ maxFee: (fee) => `Max fee ${fee}`,
28909
+ sighashSingle: "Signed inputs bind only their same-index outputs; the rest of the transaction can change"
27138
28910
  }
27139
28911
  };
27140
28912
  /** `0.05 ETH` with known decimals (symbol, else the asset id); raw units and asset id otherwise. */
@@ -27142,17 +28914,52 @@ zoo`.split("\n"));
27142
28914
  var _amount$symbol;
27143
28915
  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}`;
27144
28916
  }
28917
+ /** `YYYY-MM-DD` of a Unix-seconds instant in UTC (civil-from-days; no `Date` in the enclave). */
28918
+ function utcDate(seconds) {
28919
+ const z = Math.floor(seconds / 86400) + 719468;
28920
+ const era = Math.floor(z / 146097);
28921
+ const doe = z - era * 146097;
28922
+ const yoe = Math.floor((doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365);
28923
+ const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));
28924
+ const mp = Math.floor((5 * doy + 2) / 153);
28925
+ const day = doy - Math.floor((153 * mp + 2) / 5) + 1;
28926
+ const month = mp < 10 ? mp + 3 : mp - 9;
28927
+ const year = yoe + era * 400 + (month <= 2 ? 1 : 0);
28928
+ return `${String(year).padStart(4, "0")}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
28929
+ }
28930
+ function approvalLine(catalog, change) {
28931
+ var _change$amount$symbol;
28932
+ if (change.kind === "operator") return change.approved ? catalog.operatorAllow(change.spender, change.asset) : catalog.operatorRevoke(change.spender, change.asset);
28933
+ const name = (_change$amount$symbol = change.amount.symbol) !== null && _change$amount$symbol !== void 0 ? _change$amount$symbol : change.amount.asset;
28934
+ let line;
28935
+ if (change.change === "increase") line = catalog.increase(change.spender, formatAmount(change.amount));
28936
+ else if (change.change === "decrease") line = catalog.decrease(change.spender, formatAmount(change.amount));
28937
+ else if (change.change === "transfer") line = catalog.takeOnce(change.spender, change.unlimited ? catalog.unlimited(name) : formatAmount(change.amount));
28938
+ else if (change.unlimited) line = catalog.allow(change.spender, catalog.unlimited(name));
28939
+ else if (change.amount.amount === "0") line = catalog.revoke(change.spender, name);
28940
+ else line = catalog.allow(change.spender, formatAmount(change.amount));
28941
+ const via = change.via === void 0 ? "" : catalog.viaPermit2;
28942
+ const until = change.expiration === void 0 || change.expiration === 0 ? "" : catalog.until(utcDate(change.expiration));
28943
+ return `${line}${via}${until}`;
28944
+ }
27145
28945
  function chainPrompt(locale, intent) {
28946
+ var _intent$message, _intent$warnings;
27146
28947
  const catalog = CATALOGS$1[locale];
28948
+ if (((_intent$message = intent.message) === null || _intent$message === void 0 ? void 0 : _intent$message.kind) === "bytes") return {
28949
+ title: catalog.blindTitle,
28950
+ description: catalog.blindDescription
28951
+ };
27147
28952
  const title = catalog.titles[intent.summary];
28953
+ 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] : [];
27148
28954
  if (intent.verifiability === "opaque") return {
27149
28955
  title,
27150
- description: catalog.generic
28956
+ description: joinLines([catalog.generic, ...tail])
27151
28957
  };
27152
28958
  const lines = [
27153
28959
  ...intent.outflows.map((flow) => catalog.send(formatAmount(flow.amount), flow.to)),
27154
- ...intent.approvals.map((change) => catalog.allow(change.spender, change.unlimited ? catalog.unlimited(change.asset) : `${change.amount} ${change.asset}`)),
27155
- ...intent.fee === void 0 ? [] : [catalog.maxFee(formatAmount(intent.fee.max))]
28960
+ ...intent.approvals.map((change) => approvalLine(catalog, change)),
28961
+ ...intent.fee === void 0 ? [] : [catalog.maxFee(formatAmount(intent.fee.max))],
28962
+ ...tail
27156
28963
  ];
27157
28964
  if (intent.verifiability === "partial") return {
27158
28965
  title,
@@ -27429,7 +29236,7 @@ zoo`.split("\n"));
27429
29236
  };
27430
29237
  /** EIP-712 typed data; returns the 65-byte signature r‖s‖v with v∈{27,28}. */
27431
29238
  var signEvmTypedData = (typedData, privateKey) => {
27432
- const { json } = parseTypedData(typedData, "eip155:1");
29239
+ const { json } = parseTypedData(typedData);
27433
29240
  return rs_v(from$1(sign$1(getSignPayload$4(json), key(privateKey))));
27434
29241
  };
27435
29242
  // packages/wallet-kernel/src/modules/chains/evm.ts
@@ -27503,7 +29310,7 @@ zoo`.split("\n"));
27503
29310
  mapChainError(error);
27504
29311
  }
27505
29312
  if (!deepEqual(normalized, request)) throw new KernelError("invalid-input", "request is not normalized");
27506
- let intent = MESSAGE_INTENT;
29313
+ let intent = messageIntent(request.message);
27507
29314
  if (request.kind === "solana.transaction") try {
27508
29315
  intent = decodeSolana(request, signer);
27509
29316
  } catch (error) {
@@ -29022,8 +30829,9 @@ zoo`.split("\n"));
29022
30829
  /**
29023
30830
  * Export `ncryptsec` at logN 16 with key security byte 0x02 ("the client does not track this" in
29024
30831
  * NIP-49's terms): the kernel does not track a key's handling history and any key can be exported
29025
- * as plaintext nsec, so 0x01 would never be honest. Salt and nonce come from the library's RNG
29026
- * (noble randomBytes); not injectable in 0.14.
30832
+ * as plaintext nsec, so 0x01 would never be honest. `nip49Encrypt` draws its salt and nonce from
30833
+ * `crypto.getRandomValues`, which the kernel runtime installs natively (the same source as
30834
+ * `__qntx.random`; in a Web Worker, the platform CSPRNG), so no API-level injection is needed.
29027
30835
  */
29028
30836
  async function ncryptsecFromSecretKey(secretKey, password) {
29029
30837
  const encoded = await encrypt(secretKey, decodeUtf8Secret(password), {
@@ -37396,7 +39204,7 @@ zoo`.split("\n"));
37396
39204
  init_errors_5xLkExNL();
37397
39205
  }));
37398
39206
  // node_modules/.bun/@qntx+spark@0.5.2/node_modules/@qntx/spark/dist/signer.mjs
37399
- var signer_exports = /* @__PURE__ */ __exportAll({
39207
+ var signer_exports = /* @__PURE__ */ __exportAll$1({
37400
39208
  EPHEMERAL_ANCHOR_SCRIPT: () => EPHEMERAL_ANCHOR_SCRIPT,
37401
39209
  bitcoinAddressScript: () => bitcoinAddressScript,
37402
39210
  createLnurlAuthSigner: () => createLnurlAuthSigner,
@@ -39245,6 +41053,22 @@ zoo`.split("\n"));
39245
41053
  for (const item of items) collectTransferables(item, out, depth + 1);
39246
41054
  return out;
39247
41055
  }
41056
+ /**
41057
+ * Opens a record at reconcile. An `entropy` record must also match its header's payload layout, so
41058
+ * an inconsistent wallet record latches the vault corrupted instead of failing at first use.
41059
+ */
41060
+ function openChecked(dek, record) {
41061
+ const plaintext = openRecord(dek, record);
41062
+ if (record.kind === "entropy") try {
41063
+ const { entropy, passphrase } = splitWalletSecret(parseEntropyHeader(record.header), plaintext);
41064
+ wipe(entropy);
41065
+ if (passphrase !== void 0) wipe(passphrase);
41066
+ } catch (error) {
41067
+ wipe(plaintext);
41068
+ throw error;
41069
+ }
41070
+ return plaintext;
41071
+ }
39248
41072
  function isMethodName(method) {
39249
41073
  return method in METHODS;
39250
41074
  }
@@ -39304,14 +41128,14 @@ zoo`.split("\n"));
39304
41128
  if (prior === void 0) opened.push({
39305
41129
  kind: record.kind,
39306
41130
  id: record.id,
39307
- plaintext: openRecord(dek, record)
41131
+ plaintext: openChecked(dek, record)
39308
41132
  });
39309
41133
  else {
39310
41134
  before.delete(`${record.kind}/${record.id}`);
39311
41135
  if (prior.header !== record.header || !equalBytes$3(prior.sealed, record.sealed)) opened.push({
39312
41136
  kind: record.kind,
39313
41137
  id: record.id,
39314
- plaintext: openRecord(dek, record)
41138
+ plaintext: openChecked(dek, record)
39315
41139
  });
39316
41140
  }
39317
41141
  }