@qntx/wallet-worker 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.
@@ -30,8 +30,11 @@ import {
30
30
  randomBytes2,
31
31
  abool2,
32
32
  asafenumber,
33
+ bytesToNumberBE,
33
34
  bytesToNumberLE,
35
+ numberToBytesBE,
34
36
  numberToBytesLE,
37
+ equalBytes,
35
38
  copyBytes,
36
39
  aInRange,
37
40
  validateObject,
@@ -49,6 +52,7 @@ import {
49
52
  schnorr,
50
53
  base64,
51
54
  base64urlnopad,
55
+ base58,
52
56
  bech32,
53
57
  ripemd160,
54
58
  HDKey,
@@ -63,7 +67,7 @@ import {
63
67
  SigHash,
64
68
  getInputType,
65
69
  Transaction
66
- } from "./node-366p4fej.js";
70
+ } from "./node-k5etevb7.js";
67
71
 
68
72
  // src/worker/node.ts
69
73
  import { readFile } from "node:fs/promises";
@@ -489,7 +493,7 @@ function checkOpts2(defaults, opts) {
489
493
  const merged = Object.assign(defaults, opts);
490
494
  return merged;
491
495
  }
492
- function equalBytes(a, b) {
496
+ function equalBytes2(a, b) {
493
497
  a = abytes3(a);
494
498
  b = abytes3(b);
495
499
  if (a.length !== b.length)
@@ -1452,7 +1456,7 @@ var _poly1305_aead = (xorStream) => (key, nonce, AAD) => {
1452
1456
  const data = ciphertext.subarray(0, -tagLength);
1453
1457
  const passedTag = ciphertext.subarray(-tagLength);
1454
1458
  const tag = computeTag(xorStream, key, nonce, data, AAD);
1455
- if (!equalBytes(passedTag, tag)) {
1459
+ if (!equalBytes2(passedTag, tag)) {
1456
1460
  clean2(tag);
1457
1461
  throw new Error("invalid tag");
1458
1462
  }
@@ -1653,7 +1657,7 @@ function decrypt3(payload, conversationKey, opts) {
1653
1657
  const { nonce, ciphertext, mac } = decodePayload(payload, opts?.maxPayloadChars ?? DEFAULT_MAX_PAYLOAD_CHARS);
1654
1658
  const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce);
1655
1659
  const calculatedMac = hmacAad(hmac_key, ciphertext, nonce);
1656
- if (!equalBytes(calculatedMac, mac))
1660
+ if (!equalBytes2(calculatedMac, mac))
1657
1661
  throw new CryptoError("invalid MAC");
1658
1662
  return unpad(chacha20(chacha_key, chacha_nonce, ciphertext));
1659
1663
  }
@@ -1826,7 +1830,7 @@ class KernelError extends Error {
1826
1830
  this.corrupted = corrupted;
1827
1831
  }
1828
1832
  }
1829
- // ../wallet/dist/core-Cq5h9X0X.mjs
1833
+ // ../wallet/dist/core-D-NCx1CQ.mjs
1830
1834
  var ValidationError = class extends Error {
1831
1835
  name = "ValidationError";
1832
1836
  };
@@ -2041,8 +2045,10 @@ var walletInfo = obj({
2041
2045
  origin: union(literal("passkey"), literal("mnemonic")),
2042
2046
  words: union(literal(12), literal(15), literal(18), literal(21), literal(24)),
2043
2047
  backup: union(literal("none"), literal("passkey"), literal("mnemonic")),
2048
+ passphrase: bool,
2044
2049
  createdAt: safeTime
2045
2050
  });
2051
+ var passphraseBytes = bytes(1, 1024);
2046
2052
  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"));
2047
2053
  var createdResult = obj({
2048
2054
  wallet: walletInfo,
@@ -2115,7 +2121,8 @@ var CORE_METHODS = {
2115
2121
  presence: true,
2116
2122
  params: obj({
2117
2123
  draft: draftId,
2118
- answers: arr(bytes(1, 64), 3, 3)
2124
+ answers: arr(bytes(1, 64), 3, 3),
2125
+ passphrase: opt(passphraseBytes)
2119
2126
  }),
2120
2127
  result: createdResult
2121
2128
  },
@@ -2152,10 +2159,15 @@ var CORE_METHODS = {
2152
2159
  params: obj({
2153
2160
  envelope: str(4000000),
2154
2161
  backupFactor: backupUnlockFactor,
2162
+ passphrases: opt(arr(obj({
2163
+ walletId,
2164
+ passphrase: passphraseBytes
2165
+ }), 1000)),
2155
2166
  factor: opt(factor)
2156
2167
  }),
2157
2168
  result: obj({
2158
2169
  wallets: arr(walletInfo, 1000),
2170
+ passphraseRequired: arr(str(128), 1000),
2159
2171
  session: sessionId
2160
2172
  })
2161
2173
  },
@@ -2164,6 +2176,7 @@ var CORE_METHODS = {
2164
2176
  presence: true,
2165
2177
  params: obj({
2166
2178
  mnemonic: bytes(1, 1024),
2179
+ passphrase: opt(passphraseBytes),
2167
2180
  factor: opt(factor)
2168
2181
  }),
2169
2182
  result: createdResult
@@ -2175,7 +2188,10 @@ var CORE_METHODS = {
2175
2188
  verify: factor,
2176
2189
  walletId
2177
2190
  }),
2178
- result: bytes(16, 1024)
2191
+ result: obj({
2192
+ mnemonic: bytes(16, 1024),
2193
+ passphrase: opt(passphraseBytes)
2194
+ })
2179
2195
  },
2180
2196
  "wallet.delete": {
2181
2197
  session: true,
@@ -2194,7 +2210,7 @@ var CORE_METHODS = {
2194
2210
  }
2195
2211
  };
2196
2212
 
2197
- // ../wallet/dist/protocol-DbpLncEB.mjs
2213
+ // ../wallet/dist/protocol-DDz4nlYK.mjs
2198
2214
  var MAX_FACTOR_CHARS = 512;
2199
2215
  var MAX_STRING_BYTES = 64000;
2200
2216
  var MAX_PAYLOAD_CHARS = 1400000;
@@ -2219,7 +2235,8 @@ var backupEnvelope = obj({
2219
2235
  var backupHeader = obj({ wallets: arr(obj({
2220
2236
  walletId: str(128),
2221
2237
  origin: union(literal("mnemonic"), literal("passkey")),
2222
- words: union(literal(12), literal(15), literal(18), literal(21), literal(24))
2238
+ words: union(literal(12), literal(15), literal(18), literal(21), literal(24)),
2239
+ passphrase: opt(literal(true))
2223
2240
  }), 1000) });
2224
2241
  var backupEnvelopeText = str(MAX_ENVELOPE_CHARS);
2225
2242
  var backupInfo = obj({
@@ -3960,6 +3977,7 @@ function encodeHeader(header) {
3960
3977
  walletId: header.walletId,
3961
3978
  origin: header.origin,
3962
3979
  words: header.words,
3980
+ ...header.passphrase === true ? { passphrase: true } : {},
3963
3981
  backup: header.backup,
3964
3982
  createdAt: header.createdAt
3965
3983
  });
@@ -3978,15 +3996,21 @@ function asWords(value) {
3978
3996
  }
3979
3997
  function parseEntropyHeader(text) {
3980
3998
  const object = headerObject(text);
3981
- expectKeys(object, ["walletId", "origin", "words", "backup", "createdAt"]);
3999
+ const flagged = Object.hasOwn(object, "passphrase");
4000
+ expectKeys(object, flagged ? ["walletId", "origin", "words", "passphrase", "backup", "createdAt"] : ["walletId", "origin", "words", "backup", "createdAt"]);
3982
4001
  const { backup } = object;
3983
4002
  if (backup !== "none" && backup !== "passkey" && backup !== "mnemonic") {
3984
4003
  throw headerFailure();
3985
4004
  }
4005
+ const origin = asEntropyOrigin(object["origin"]);
4006
+ if (flagged && (object["passphrase"] !== true || origin !== "mnemonic")) {
4007
+ throw headerFailure();
4008
+ }
3986
4009
  return {
3987
4010
  walletId: asWalletId(object["walletId"]),
3988
- origin: asEntropyOrigin(object["origin"]),
4011
+ origin,
3989
4012
  words: asWords(object["words"]),
4013
+ ...flagged ? { passphrase: true } : {},
3990
4014
  backup,
3991
4015
  createdAt: asCreatedAt(object["createdAt"])
3992
4016
  };
@@ -4122,7 +4146,7 @@ function factorBindingOk(dek, stored) {
4122
4146
  }
4123
4147
  const expected = dek.use((bytes) => factorBinding(bytes, factorContext(stored.kind, stored.id), stored.header));
4124
4148
  try {
4125
- return equalBytes(expected, sealed.subarray(33, 65));
4149
+ return equalBytes2(expected, sealed.subarray(33, 65));
4126
4150
  } finally {
4127
4151
  wipe(expected);
4128
4152
  }
@@ -4133,7 +4157,7 @@ function wrapDek(dek, factorPk, factor, random) {
4133
4157
  const ephPk = x25519.getPublicKey(eph);
4134
4158
  const shared = x25519.getSharedSecret(eph, factorPk);
4135
4159
  try {
4136
- if (equalBytes(shared, ZERO32)) {
4160
+ if (equalBytes2(shared, ZERO32)) {
4137
4161
  throw new KernelError("integrity", "weak factor public key");
4138
4162
  }
4139
4163
  const wrapKey = hkdf(sha256, shared, concatBytes(ephPk, factorPk), WRAP_INFO, 32);
@@ -4160,7 +4184,7 @@ function unwrapDek(kek, stored) {
4160
4184
  const factorSk = hkdf(sha256, kek, new Uint8Array(0), FACTOR_KEY_INFO, 32);
4161
4185
  try {
4162
4186
  const factorPk = x25519.getPublicKey(factorSk);
4163
- if (!equalBytes(factorPk, factorHeaderPublicKey(stored))) {
4187
+ if (!equalBytes2(factorPk, factorHeaderPublicKey(stored))) {
4164
4188
  throw stored.kind === "password" ? new KernelError("wrong-password", "password did not open the vault") : stored.kind === "hardware" ? corruptError("hardware factor returned a key that does not match its header") : new KernelError("wrong-passkey", "passkey does not match the factor");
4165
4189
  }
4166
4190
  const { sealed } = stored;
@@ -4176,7 +4200,7 @@ function unwrapDek(kek, stored) {
4176
4200
  throw corruptError("invalid factor ephemeral key");
4177
4201
  }
4178
4202
  try {
4179
- if (equalBytes(shared, ZERO32)) {
4203
+ if (equalBytes2(shared, ZERO32)) {
4180
4204
  throw corruptError("weak factor ephemeral key");
4181
4205
  }
4182
4206
  const wrapKey = hkdf(sha256, shared, concatBytes(ephPk, factorPk), WRAP_INFO, 32);
@@ -4188,7 +4212,7 @@ function unwrapDek(kek, stored) {
4188
4212
  throw corruptError("factor wrapping failed authentication");
4189
4213
  }
4190
4214
  const expected = factorBinding(dekBytes, factorContext(stored.kind, stored.id), stored.header);
4191
- const bound = equalBytes(expected, binding);
4215
+ const bound = equalBytes2(expected, binding);
4192
4216
  wipe(expected);
4193
4217
  if (!bound) {
4194
4218
  wipe(dekBytes);
@@ -4381,7 +4405,7 @@ async function verifyFactor(platform, image, factor, dek, prompt) {
4381
4405
  try {
4382
4406
  const opened = unwrapDek(kek, stored);
4383
4407
  try {
4384
- const same = opened.use((a) => dek.use((b) => equalBytes(a, b)));
4408
+ const same = opened.use((a) => dek.use((b) => equalBytes2(a, b)));
4385
4409
  if (same) {
4386
4410
  return;
4387
4411
  }
@@ -4467,6 +4491,28 @@ function sealRecord(platform, dek, kind, id, header, plaintext) {
4467
4491
  function openRecord(dek, record) {
4468
4492
  return dek.use((bytes) => open(bytes, record.sealed, recordContext(record.kind, record.id), record.header));
4469
4493
  }
4494
+ var MAX_PASSPHRASE_BYTES = 1024;
4495
+ function splitWalletSecret(header, plaintext) {
4496
+ const entropyLength = header.words / 3 * 4;
4497
+ const extra = plaintext.length - entropyLength;
4498
+ const valid = header.passphrase === true ? extra >= 1 && extra <= MAX_PASSPHRASE_BYTES : extra === 0;
4499
+ if (!valid) {
4500
+ throw new KernelError("integrity", "wallet record does not match its header");
4501
+ }
4502
+ return {
4503
+ entropy: plaintext.slice(0, entropyLength),
4504
+ passphrase: header.passphrase === true ? plaintext.slice(entropyLength) : undefined
4505
+ };
4506
+ }
4507
+ function openWalletSecret(dek, record) {
4508
+ const header = parseEntropyHeader(record.header);
4509
+ const plaintext = openRecord(dek, record);
4510
+ try {
4511
+ return splitWalletSecret(header, plaintext);
4512
+ } finally {
4513
+ wipe(plaintext);
4514
+ }
4515
+ }
4470
4516
  function findRecord(image, kind, id) {
4471
4517
  const record = image.records.find((r) => r.kind === kind && r.id === id);
4472
4518
  if (record === undefined) {
@@ -4521,10 +4567,31 @@ function walletInfo2(header) {
4521
4567
  origin: header.origin,
4522
4568
  words: header.words,
4523
4569
  backup: header.backup,
4570
+ passphrase: header.passphrase === true,
4524
4571
  createdAt: header.createdAt
4525
4572
  };
4526
4573
  }
4527
4574
 
4575
+ // ../wallet-kernel/src/commands/passphrase.ts
4576
+ function normalizePassphrase(wire) {
4577
+ const normalized = utf8ToBytes(decodeUtf8Secret(wire).normalize("NFKD"));
4578
+ if (normalized.length === 0 || normalized.length > MAX_PASSPHRASE_BYTES) {
4579
+ normalized.fill(0);
4580
+ throw new KernelError("invalid-input", "passphrase must be 1-1024 bytes");
4581
+ }
4582
+ return normalized;
4583
+ }
4584
+ function passphraseText(passphrase) {
4585
+ if (passphrase === undefined) {
4586
+ return "";
4587
+ }
4588
+ try {
4589
+ return new TextDecoder("utf-8", { fatal: true }).decode(passphrase);
4590
+ } catch {
4591
+ throw new KernelError("integrity", "wallet passphrase is not valid UTF-8");
4592
+ }
4593
+ }
4594
+
4528
4595
  // ../wallet-kernel/src/derive/hd.ts
4529
4596
  function masterKey(seed) {
4530
4597
  return HDKey.fromMasterSeed(seed);
@@ -6835,11 +6902,11 @@ async function seedFromMnemonic(mnemonic, passphrase, pbkdf2) {
6835
6902
  wipe(password, salt);
6836
6903
  }
6837
6904
  }
6838
- async function seedFromEntropy(entropy, pbkdf2) {
6839
- return seedFromMnemonic(mnemonicFromEntropy(entropy), "", pbkdf2);
6905
+ async function seedFromEntropy(entropy, passphrase, pbkdf2) {
6906
+ return seedFromMnemonic(mnemonicFromEntropy(entropy), passphrase, pbkdf2);
6840
6907
  }
6841
- async function withSeed(pbkdf2, entropy, use) {
6842
- const seed = await seedFromEntropy(entropy, pbkdf2);
6908
+ async function withSeed(pbkdf2, entropy, passphrase, use) {
6909
+ const seed = await seedFromEntropy(entropy, passphrase, pbkdf2);
6843
6910
  try {
6844
6911
  return await use(seed);
6845
6912
  } finally {
@@ -7020,11 +7087,14 @@ class Session {
7020
7087
 
7021
7088
  // ../wallet-kernel/src/commands/vault.ts
7022
7089
  async function withWalletSeed(pbkdf2, dek, record, use) {
7023
- const entropy = openRecord(dek, record);
7090
+ const { entropy, passphrase } = openWalletSecret(dek, record);
7024
7091
  try {
7025
- return await withSeed(pbkdf2, entropy, use);
7092
+ return await withSeed(pbkdf2, entropy, passphraseText(passphrase), use);
7026
7093
  } finally {
7027
7094
  wipe(entropy);
7095
+ if (passphrase !== undefined) {
7096
+ wipe(passphrase);
7097
+ }
7028
7098
  }
7029
7099
  }
7030
7100
  var EMPTY_IMAGE = { meta: undefined, records: [], factors: [] };
@@ -7110,16 +7180,16 @@ async function removeFactor(ctx, params, requestSession) {
7110
7180
  }
7111
7181
 
7112
7182
  // ../wallet-kernel/src/commands/wallets.ts
7113
- async function deriveWalletMaterial(platform, entropy) {
7114
- return withSeed(platform.pbkdf2, entropy, (seed) => {
7183
+ async function deriveWalletMaterial(platform, entropy, passphrase) {
7184
+ return withSeed(platform.pbkdf2, entropy, passphraseText(passphrase), (seed) => {
7115
7185
  const master = masterKey(seed);
7116
7186
  return { master, walletId: walletIdOf(master) };
7117
7187
  });
7118
7188
  }
7119
- async function walletMaterial(platform, entropy, origin, words) {
7120
- const { master, walletId } = await deriveWalletMaterial(platform, entropy);
7189
+ async function walletMaterial(platform, entropy, passphrase, origin, words) {
7190
+ const { master, walletId } = await deriveWalletMaterial(platform, entropy, passphrase);
7121
7191
  try {
7122
- return { walletId, entropy, words, origin };
7192
+ return { walletId, entropy, passphrase, words, origin };
7123
7193
  } finally {
7124
7194
  master.wipePrivateData();
7125
7195
  }
@@ -7130,18 +7200,23 @@ function walletInfoOf(material, backup, createdAt) {
7130
7200
  origin: material.origin,
7131
7201
  words: material.words,
7132
7202
  backup,
7203
+ ...material.passphrase === undefined ? {} : { passphrase: true },
7133
7204
  createdAt
7134
7205
  });
7135
7206
  }
7207
+ function walletSecretPlaintext(entropy, passphrase) {
7208
+ return passphrase === undefined ? new Uint8Array(entropy) : concatBytes(entropy, passphrase);
7209
+ }
7136
7210
  function walletRecord(ctx, dek, material, backup, createdAt) {
7137
7211
  const header = encodeHeader({
7138
7212
  walletId: material.walletId,
7139
7213
  origin: material.origin,
7140
7214
  words: material.words,
7215
+ ...material.passphrase === undefined ? {} : { passphrase: true },
7141
7216
  backup,
7142
7217
  createdAt
7143
7218
  });
7144
- return sealRecord(ctx.platform, dek, "entropy", material.walletId, header, new Uint8Array(material.entropy));
7219
+ return sealRecord(ctx.platform, dek, "entropy", material.walletId, header, walletSecretPlaintext(material.entropy, material.passphrase));
7145
7220
  }
7146
7221
  function gate(ctx, factor, requestSession) {
7147
7222
  if (ctx.image.meta === undefined) {
@@ -7251,10 +7326,20 @@ async function storedFactorForPending(ctx, pending, dek) {
7251
7326
  return { kind: pending.kind, id, header, sealed };
7252
7327
  }
7253
7328
  async function confirmMnemonic(ctx, params) {
7329
+ const passphrase = params.passphrase === undefined ? undefined : normalizePassphrase(params.passphrase);
7330
+ try {
7331
+ return await confirmWithPassphrase(ctx, params, passphrase);
7332
+ } finally {
7333
+ if (passphrase !== undefined) {
7334
+ wipe(passphrase);
7335
+ }
7336
+ }
7337
+ }
7338
+ async function confirmWithPassphrase(ctx, params, passphrase) {
7254
7339
  const draft = ctx.session.getDraft(params.draft);
7255
7340
  const allMatch = draft.expected.every((expected, i) => {
7256
7341
  const answer = params.answers[i];
7257
- return answer !== undefined && answer.length === expected.length && equalBytes(answer, expected);
7342
+ return answer !== undefined && answer.length === expected.length && equalBytes2(answer, expected);
7258
7343
  });
7259
7344
  for (const answer of params.answers) {
7260
7345
  wipe(answer);
@@ -7265,7 +7350,7 @@ async function confirmMnemonic(ctx, params) {
7265
7350
  const taken = ctx.session.takeDraft(params.draft);
7266
7351
  try {
7267
7352
  const entropy = taken.entropy.use((bytes) => new Uint8Array(bytes));
7268
- const material = await walletMaterial(ctx.platform, entropy, "mnemonic", taken.words);
7353
+ const material = await walletMaterial(ctx.platform, entropy, passphrase, "mnemonic", taken.words);
7269
7354
  try {
7270
7355
  ensureNewWallet(ctx, material);
7271
7356
  const createdAt = ctx.platform.now();
@@ -7306,17 +7391,31 @@ function mnemonicWords(entropy) {
7306
7391
  }
7307
7392
  async function importMnemonic(ctx, params, requestSession) {
7308
7393
  const gated = gate(ctx, params.factor, requestSession);
7309
- const text = decodeUtf8Secret(params.mnemonic);
7310
- const entropy = entropyFromMnemonic(text);
7311
- const material = await walletMaterial(ctx.platform, entropy, "mnemonic", mnemonicWords(entropy));
7394
+ let text;
7312
7395
  try {
7396
+ text = decodeUtf8Secret(params.mnemonic);
7397
+ } catch (error) {
7398
+ params.passphrase?.fill(0);
7399
+ throw error;
7400
+ }
7401
+ let passphrase;
7402
+ let entropy;
7403
+ try {
7404
+ passphrase = params.passphrase === undefined ? undefined : normalizePassphrase(params.passphrase);
7405
+ entropy = entropyFromMnemonic(text);
7406
+ const material = await walletMaterial(ctx.platform, entropy, passphrase, "mnemonic", mnemonicWords(entropy));
7313
7407
  ensureNewWallet(ctx, material);
7314
7408
  const createdAt = ctx.platform.now();
7315
7409
  const record = walletRecord(ctx, gated.dek, material, "mnemonic", createdAt);
7316
7410
  const session = await commitRecords(ctx, gated, params.factor, [record]);
7317
7411
  return { wallet: walletInfoOf(material, "mnemonic", createdAt), session };
7318
7412
  } finally {
7319
- wipe(entropy);
7413
+ if (entropy !== undefined) {
7414
+ wipe(entropy);
7415
+ }
7416
+ if (passphrase !== undefined) {
7417
+ wipe(passphrase);
7418
+ }
7320
7419
  }
7321
7420
  }
7322
7421
  var PURPOSE_WALLET = 1;
@@ -7374,7 +7473,7 @@ async function createWithPasskey(ctx, params, requestSession) {
7374
7473
  throw error;
7375
7474
  }
7376
7475
  const entropy = entropyFromPrf(prf.prfWallet);
7377
- const material = await walletMaterial(ctx.platform, entropy, "passkey", 12);
7476
+ const material = await walletMaterial(ctx.platform, entropy, undefined, "passkey", 12);
7378
7477
  try {
7379
7478
  ensureNewWallet(ctx, material);
7380
7479
  const createdAt = ctx.platform.now();
@@ -7509,21 +7608,23 @@ function collectContents(ctx, dek) {
7509
7608
  continue;
7510
7609
  }
7511
7610
  const header = parseEntropyHeader(record.header);
7512
- const plaintext = openRecord(dek, record);
7513
- try {
7514
- wallets.push({
7515
- walletId: record.id,
7516
- origin: header.origin,
7517
- words: header.words,
7518
- entropy: plaintext
7519
- });
7520
- } catch (error) {
7521
- plaintext.fill(0);
7522
- throw error;
7523
- }
7611
+ const { entropy, passphrase } = openWalletSecret(dek, record);
7612
+ passphrase?.fill(0);
7613
+ wallets.push({
7614
+ walletId: record.id,
7615
+ origin: header.origin,
7616
+ words: header.words,
7617
+ ...header.passphrase === true ? { passphrase: true } : {},
7618
+ entropy
7619
+ });
7524
7620
  }
7525
7621
  const header = JSON.stringify({
7526
- wallets: wallets.map(({ walletId, origin, words }) => ({ walletId, origin, words }))
7622
+ wallets: wallets.map(({ walletId, origin, words, passphrase }) => ({
7623
+ walletId,
7624
+ origin,
7625
+ words,
7626
+ ...passphrase === true ? { passphrase } : {}
7627
+ }))
7527
7628
  });
7528
7629
  return { wallets, header };
7529
7630
  } catch (error) {
@@ -7717,6 +7818,25 @@ async function bekFromFactor(platform, envelope, backupFactor) {
7717
7818
  }
7718
7819
  }
7719
7820
  async function restoreBackup(ctx, params, requestSession) {
7821
+ const passphrases = new Map;
7822
+ try {
7823
+ return await restoreWithPassphrases(ctx, params, requestSession, passphrases);
7824
+ } finally {
7825
+ for (const passphrase of passphrases.values()) {
7826
+ passphrase.fill(0);
7827
+ }
7828
+ for (const entry of params.passphrases ?? []) {
7829
+ entry.passphrase.fill(0);
7830
+ }
7831
+ }
7832
+ }
7833
+ async function restoreWithPassphrases(ctx, params, requestSession, passphrases) {
7834
+ for (const entry of params.passphrases ?? []) {
7835
+ if (passphrases.has(entry.walletId)) {
7836
+ throw new KernelError("invalid-input", `duplicate passphrase for wallet ${entry.walletId}`);
7837
+ }
7838
+ passphrases.set(entry.walletId, normalizePassphrase(entry.passphrase));
7839
+ }
7720
7840
  const envelope = parseEnvelope(params.envelope);
7721
7841
  const credentials = envelope.factors.flatMap((f) => f.kind === "passkey" ? [b64.dec(f.credentialId)] : []);
7722
7842
  const bek = await bekFromFactor(ctx.platform, envelope, await backupMaterial(ctx, params.backupFactor, credentials));
@@ -7733,9 +7853,17 @@ async function restoreBackup(ctx, params, requestSession) {
7733
7853
  plaintext.fill(0);
7734
7854
  throw new KernelError("integrity", "backup: payload does not match header");
7735
7855
  }
7856
+ const flagged = new Set(header.wallets.filter((w) => w.passphrase === true).map((w) => w.walletId));
7857
+ for (const walletId of passphrases.keys()) {
7858
+ if (!flagged.has(walletId)) {
7859
+ plaintext.fill(0);
7860
+ throw new KernelError("invalid-input", `wallet ${walletId} has no passphrase`);
7861
+ }
7862
+ }
7736
7863
  const gated = gate(ctx, params.factor, requestSession);
7737
7864
  const records = [];
7738
7865
  const restored = [];
7866
+ const passphraseRequired = [];
7739
7867
  let committed = false;
7740
7868
  try {
7741
7869
  try {
@@ -7749,7 +7877,17 @@ async function restoreBackup(ctx, params, requestSession) {
7749
7877
  if (words !== expected.words) {
7750
7878
  throw new KernelError("integrity", "backup: entropy length does not match header");
7751
7879
  }
7752
- const material = await walletMaterial(ctx.platform, wallet.entropy, wallet.origin, words);
7880
+ const passphrase = passphrases.get(expected.walletId);
7881
+ if (passphrase === undefined && expected.passphrase === true) {
7882
+ if (!ctx.image.records.some((r) => r.kind === "entropy" && r.id === expected.walletId)) {
7883
+ passphraseRequired.push(expected.walletId);
7884
+ }
7885
+ continue;
7886
+ }
7887
+ const material = await walletMaterial(ctx.platform, wallet.entropy, passphrase, wallet.origin, words);
7888
+ if (passphrase !== undefined && material.walletId !== expected.walletId) {
7889
+ throw new KernelError("invalid-input", `passphrase does not match wallet ${expected.walletId}`);
7890
+ }
7753
7891
  if (material.walletId !== expected.walletId || material.origin !== expected.origin) {
7754
7892
  throw new KernelError("integrity", "backup: derived walletId does not match header");
7755
7893
  }
@@ -7766,7 +7904,7 @@ async function restoreBackup(ctx, params, requestSession) {
7766
7904
  }
7767
7905
  const session = await commitRecords(ctx, gated, params.factor, records);
7768
7906
  committed = true;
7769
- return { wallets: restored, session };
7907
+ return { wallets: restored, passphraseRequired, session };
7770
7908
  } catch (error) {
7771
7909
  if (!committed && gated.uninitialized) {
7772
7910
  gated.dek.wipe();
@@ -7790,7 +7928,7 @@ async function exportMnemonic(ctx, params, requestSession) {
7790
7928
  await verifyFactor(ctx.platform, ctx.image, params.verify, dek, corePromptFor(ctx.platform.keystore, "export-mnemonic"));
7791
7929
  const record = findRecord(ctx.image, "entropy", params.walletId);
7792
7930
  const header = parseEntropyHeader(record.header);
7793
- const entropy = openRecord(dek, record);
7931
+ const { entropy, passphrase } = openWalletSecret(dek, record);
7794
7932
  try {
7795
7933
  const exported = utf8ToBytes(mnemonicFromEntropy(entropy));
7796
7934
  if (header.backup !== "mnemonic") {
@@ -7798,13 +7936,19 @@ async function exportMnemonic(ctx, params, requestSession) {
7798
7936
  await ctx.commit([
7799
7937
  {
7800
7938
  op: "put-record",
7801
- record: sealRecord(ctx.platform, dek, "entropy", params.walletId, updated, new Uint8Array(entropy))
7939
+ record: sealRecord(ctx.platform, dek, "entropy", params.walletId, updated, walletSecretPlaintext(entropy, passphrase))
7802
7940
  }
7803
7941
  ]);
7804
7942
  }
7805
- return exported;
7943
+ return {
7944
+ mnemonic: exported,
7945
+ ...passphrase === undefined ? {} : { passphrase: new Uint8Array(passphrase) }
7946
+ };
7806
7947
  } finally {
7807
7948
  wipe(entropy);
7949
+ if (passphrase !== undefined) {
7950
+ wipe(passphrase);
7951
+ }
7808
7952
  }
7809
7953
  }
7810
7954
  async function getDataKey(ctx, params, requestSession) {
@@ -7967,632 +8111,1832 @@ class HDKey2 {
7967
8111
  }
7968
8112
  }
7969
8113
 
7970
- // ../wallet-chains/dist/index.mjs
7971
- var ChainError = class extends Error {
7972
- code;
7973
- constructor(code, message) {
7974
- super(message);
7975
- this.name = "ChainError";
7976
- this.code = code;
8114
+ // ../../node_modules/.bun/@qntx+siwx@0.8.0/node_modules/@qntx/siwx/dist/message-B6snBU4B.mjs
8115
+ var SYNTAX_MESSAGES = {
8116
+ InvalidUtf8: "invalid UTF-8",
8117
+ CarriageReturn: "CR not allowed",
8118
+ MissingPreamble: "missing preamble marker",
8119
+ MissingAccountSuffix: "missing account suffix",
8120
+ UnexpectedEof: "unexpected end of input",
8121
+ ExpectedBlankLine: "expected blank line",
8122
+ UnexpectedTrailing: "unexpected trailing content",
8123
+ ResourceSyntax: "resource line must start with '- '",
8124
+ InvalidEnvelope: "invalid off-chain message envelope"
8125
+ };
8126
+ function describe(info) {
8127
+ if (info.code === "MessageTooLarge")
8128
+ return `message exceeds maximum size of ${info.max} bytes, got ${info.length}`;
8129
+ if (info.code === "Syntax")
8130
+ return info.syntax === "MissingField" ? `invalid message syntax: missing ${info.field}` : `invalid message syntax: ${SYNTAX_MESSAGES[info.syntax]}`;
8131
+ if (info.code === "InvalidField")
8132
+ return `invalid ${info.field}: ${info.reason}`;
8133
+ if (info.code === "Mismatch")
8134
+ return `${info.field} mismatch: expected ${info.expected}, got ${JSON.stringify(info.actual)}`;
8135
+ if (info.code === "InvalidOrigin")
8136
+ return "invalid origin: not a serialized web origin";
8137
+ if (info.code === "Expired")
8138
+ return "message expired";
8139
+ if (info.code === "NotYetValid")
8140
+ return "message not yet valid";
8141
+ if (info.code === "IssuedAtTooOld")
8142
+ return "issued-at exceeds max age";
8143
+ if (info.code === "InvalidSignature")
8144
+ return `invalid signature: ${info.reason}`;
8145
+ if (info.code === "VerificationFailed")
8146
+ return "verification failed";
8147
+ if (info.code === "Unsupported")
8148
+ return `unsupported: ${info.reason}`;
8149
+ return `backend error: ${info.reason}`;
8150
+ }
8151
+ var SiwxError = class extends Error {
8152
+ info;
8153
+ constructor(info) {
8154
+ super(describe(info));
8155
+ this.name = "SiwxError";
8156
+ this.info = info;
8157
+ }
8158
+ get code() {
8159
+ return this.info.code;
7977
8160
  }
7978
8161
  };
7979
-
7980
- // ../wallet-chains/dist/account-ref-C2qrDbVT.mjs
7981
- var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
7982
- var isAccountRef = (value) => {
7983
- if (!isRecord2(value) || typeof value["kind"] !== "string")
8162
+ function syntaxError(syntax, field) {
8163
+ if (syntax === "MissingField") {
8164
+ if (field === undefined)
8165
+ throw new RangeError("MissingField requires a field");
8166
+ return new SiwxError({
8167
+ code: "Syntax",
8168
+ syntax,
8169
+ field
8170
+ });
8171
+ }
8172
+ return new SiwxError({
8173
+ code: "Syntax",
8174
+ syntax
8175
+ });
8176
+ }
8177
+ function fieldError(field, reason) {
8178
+ return new SiwxError({
8179
+ code: "InvalidField",
8180
+ field,
8181
+ reason
8182
+ });
8183
+ }
8184
+ function mismatchError(field, expected, actual) {
8185
+ return new SiwxError({
8186
+ code: "Mismatch",
8187
+ field,
8188
+ expected,
8189
+ actual
8190
+ });
8191
+ }
8192
+ //! CAIP-10 `account_id`: `namespace ":" reference ":" address`.
8193
+ function everyChar(s, test) {
8194
+ const pred = typeof test === "function" ? test : (c) => test.test(c);
8195
+ for (const c of s)
8196
+ if (!pred(c))
8197
+ return false;
8198
+ return true;
8199
+ }
8200
+ function createAccountId(namespace, reference, address) {
8201
+ if (namespace.length < 3 || namespace.length > 8 || !everyChar(namespace, /[a-z0-9-]/))
8202
+ throw fieldError("chainId", "bad CAIP-2 namespace");
8203
+ if (reference.length === 0 || reference.length > 32 || !everyChar(reference, /[A-Za-z0-9_-]/))
8204
+ throw fieldError("chainId", "bad CAIP-2 reference");
8205
+ if (address.length === 0 || address.length > 128 || !everyChar(address, (c) => /[A-Za-z0-9]/.test(c) || c === "-" || c === "." || c === "%"))
8206
+ throw fieldError("address", "bad CAIP-10 address");
8207
+ return Object.freeze({
8208
+ namespace,
8209
+ reference,
8210
+ address,
8211
+ id: `${namespace}:${reference}:${address}`
8212
+ });
8213
+ }
8214
+ //! Shared pieces of the CAIP-122 text layouts (eip4361 and SIWS): the
8215
+ //! preamble infix/suffix and the optional trailing tags in fixed ABNF order.
8216
+ var MID = " wants you to sign in with your ";
8217
+ var SUFFIX = " account:";
8218
+ function optionalTags(lines, start) {
8219
+ let i = start;
8220
+ let resources;
8221
+ const take = (tag) => {
8222
+ const line = lines[i];
8223
+ if (line !== undefined && line.startsWith(tag)) {
8224
+ i++;
8225
+ return line.slice(tag.length);
8226
+ }
8227
+ };
8228
+ const expirationTime = take("Expiration Time: ");
8229
+ const notBefore = take("Not Before: ");
8230
+ const requestId = take("Request ID: ");
8231
+ if (lines[i] === "Resources:") {
8232
+ i++;
8233
+ const list = [];
8234
+ while (i < lines.length) {
8235
+ const r = lines[i] ?? "";
8236
+ if (r.startsWith("- ")) {
8237
+ list.push(r.slice(2));
8238
+ i++;
8239
+ } else if (r.startsWith("-"))
8240
+ throw syntaxError("ResourceSyntax");
8241
+ else
8242
+ throw syntaxError("UnexpectedTrailing");
8243
+ }
8244
+ resources = list;
8245
+ }
8246
+ if (i !== lines.length)
8247
+ throw syntaxError("UnexpectedTrailing");
8248
+ return {
8249
+ expirationTime,
8250
+ notBefore,
8251
+ requestId,
8252
+ resources
8253
+ };
8254
+ }
8255
+ var MAX_MESSAGE_BYTES = 16384;
8256
+ //! RFC 3986 URI validation, matching Rust `iri-string` exactly:
8257
+ //! `URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]`,
8258
+ //! `authority = [ userinfo "@" ] host [ ":" port ]`, strict dec-octet
8259
+ //! (no leading zeros), IPv6 / IPvFuture / pct-encoding.
8260
+ var UNRESERVED = /[A-Za-z0-9._~-]/;
8261
+ var SUB_DELIM = /[!$&'()*+,;=]/;
8262
+ var HEX = /[0-9A-Fa-f]/;
8263
+ function isScheme(s) {
8264
+ if (s.length === 0 || !/[A-Za-z]/.test(s.charAt(0)))
7984
8265
  return false;
7985
- if (value["kind"] === "hd")
7986
- return typeof value["walletId"] === "string" && typeof value["groupIndex"] === "number" && typeof value["template"] === "string";
7987
- return value["kind"] === "imported" && typeof value["keyId"] === "string" && typeof value["family"] === "string";
7988
- };
7989
- var requestBase = (request) => {
7990
- if (!isRecord2(request))
7991
- throw new ChainError("invalid-request", "request must be an object");
7992
- const { network, account } = request;
7993
- if (typeof network !== "string")
7994
- throw new ChainError("invalid-request", "request.network must be a string");
7995
- if (!isAccountRef(account))
7996
- throw new ChainError("invalid-request", "request.account must be an AccountRef");
8266
+ for (const c of s)
8267
+ if (!/[A-Za-z0-9+.-]/.test(c))
8268
+ return false;
8269
+ return true;
8270
+ }
8271
+ function everyPct(s, allowed) {
8272
+ for (let i = 0;i < s.length; i++) {
8273
+ const c = s.charAt(i);
8274
+ if (c === "%") {
8275
+ if (i + 2 >= s.length || !HEX.test(s.charAt(i + 1)) || !HEX.test(s.charAt(i + 2)))
8276
+ return false;
8277
+ i += 2;
8278
+ continue;
8279
+ }
8280
+ if (!allowed(c))
8281
+ return false;
8282
+ }
8283
+ return true;
8284
+ }
8285
+ function isUserinfo(s) {
8286
+ return everyPct(s, (c) => UNRESERVED.test(c) || SUB_DELIM.test(c) || c === ":");
8287
+ }
8288
+ function isRegName(s) {
8289
+ return everyPct(s, (c) => UNRESERVED.test(c) || SUB_DELIM.test(c));
8290
+ }
8291
+ function isPcharString(s) {
8292
+ return everyPct(s, (c) => UNRESERVED.test(c) || SUB_DELIM.test(c) || c === ":" || c === "@");
8293
+ }
8294
+ function isDecOctet(s) {
8295
+ if (s.length === 0 || s.length > 3)
8296
+ return false;
8297
+ if (s.length > 1 && s.startsWith("0"))
8298
+ return false;
8299
+ for (const c of s)
8300
+ if (!/[0-9]/.test(c))
8301
+ return false;
8302
+ return Number(s) <= 255;
8303
+ }
8304
+ function isIPv4(s) {
8305
+ const parts = s.split(".");
8306
+ return parts.length === 4 && parts.every(isDecOctet);
8307
+ }
8308
+ function isH16(s) {
8309
+ return s.length > 0 && s.length <= 4 && s.split("").every((c) => HEX.test(c));
8310
+ }
8311
+ function ipv6GroupCount(part) {
8312
+ if (part === "")
8313
+ return 0;
8314
+ let n = 0;
8315
+ const groups = part.split(":");
8316
+ for (const g of groups) {
8317
+ if (g === "")
8318
+ return -1;
8319
+ if (g.includes(".")) {
8320
+ if (g !== groups.at(-1) || !isIPv4(g))
8321
+ return -1;
8322
+ n += 2;
8323
+ } else if (isH16(g))
8324
+ n += 1;
8325
+ else
8326
+ return -1;
8327
+ }
8328
+ return n;
8329
+ }
8330
+ function isIPv6(s) {
8331
+ const halves = s.split("::");
8332
+ if (halves.length > 2)
8333
+ return false;
8334
+ if (halves.length === 1)
8335
+ return ipv6GroupCount(halves[0] ?? "") === 8;
8336
+ const hn = ipv6GroupCount(halves[0] ?? "");
8337
+ const tn = ipv6GroupCount(halves[1] ?? "");
8338
+ if (hn === -1 || tn === -1)
8339
+ return false;
8340
+ return hn + tn < 8;
8341
+ }
8342
+ function isIPvFuture(s) {
8343
+ const m = /^[vV]([0-9A-Fa-f]+)\.(.*)$/.exec(s);
8344
+ if (m === null)
8345
+ return false;
8346
+ const tail = m[2] ?? "";
8347
+ if (tail.length === 0)
8348
+ return false;
8349
+ for (const c of tail)
8350
+ if (!(UNRESERVED.test(c) || SUB_DELIM.test(c) || c === ":"))
8351
+ return false;
8352
+ return true;
8353
+ }
8354
+ function isHost(s) {
8355
+ if (s.startsWith("["))
8356
+ return s.endsWith("]") && (isIPv6(s.slice(1, -1)) || isIPvFuture(s.slice(1, -1)));
8357
+ if (isIPv4(s))
8358
+ return true;
8359
+ return isRegName(s);
8360
+ }
8361
+ function isAuthority(s) {
8362
+ let rest = s;
8363
+ const at = rest.lastIndexOf("@");
8364
+ if (at !== -1) {
8365
+ if (rest.indexOf("@") !== at)
8366
+ return false;
8367
+ if (!isUserinfo(rest.slice(0, at)))
8368
+ return false;
8369
+ rest = rest.slice(at + 1);
8370
+ }
8371
+ let host = rest;
8372
+ let port = "";
8373
+ if (rest.startsWith("[")) {
8374
+ const end = rest.indexOf("]");
8375
+ if (end === -1)
8376
+ return false;
8377
+ host = rest.slice(0, end + 1);
8378
+ const after = rest.slice(end + 1);
8379
+ if (after !== "") {
8380
+ if (!after.startsWith(":"))
8381
+ return false;
8382
+ port = after.slice(1);
8383
+ }
8384
+ } else {
8385
+ const colon = rest.lastIndexOf(":");
8386
+ if (colon !== -1) {
8387
+ host = rest.slice(0, colon);
8388
+ port = rest.slice(colon + 1);
8389
+ if (host.includes(":"))
8390
+ return false;
8391
+ }
8392
+ }
8393
+ if (port !== "" && !port.split("").every((c) => /[0-9]/.test(c)))
8394
+ return false;
8395
+ return isHost(host);
8396
+ }
8397
+ function isPath(s) {
8398
+ for (const seg of s.split("/"))
8399
+ if (!isPcharString(seg))
8400
+ return false;
8401
+ return true;
8402
+ }
8403
+ function isQueryOrFragment(s) {
8404
+ return everyPct(s, (c) => UNRESERVED.test(c) || SUB_DELIM.test(c) || c === ":" || c === "@" || c === "/" || c === "?");
8405
+ }
8406
+ function isUri(s) {
8407
+ const hash = s.indexOf("#");
8408
+ if (hash !== -1 && s.includes("#", hash + 1))
8409
+ return false;
8410
+ let rest = s;
8411
+ let fragment;
8412
+ if (hash !== -1) {
8413
+ fragment = rest.slice(hash + 1);
8414
+ rest = rest.slice(0, hash);
8415
+ }
8416
+ const q = rest.indexOf("?");
8417
+ let query;
8418
+ if (q !== -1) {
8419
+ query = rest.slice(q + 1);
8420
+ rest = rest.slice(0, q);
8421
+ }
8422
+ const colon = rest.indexOf(":");
8423
+ if (colon === -1)
8424
+ return false;
8425
+ if (!isScheme(rest.slice(0, colon)))
8426
+ return false;
8427
+ let hier = rest.slice(colon + 1);
8428
+ if (hier.startsWith("//")) {
8429
+ hier = hier.slice(2);
8430
+ const slash = hier.indexOf("/");
8431
+ const authority = slash === -1 ? hier : hier.slice(0, slash);
8432
+ const path = slash === -1 ? "" : hier.slice(slash);
8433
+ if (!isAuthority(authority))
8434
+ return false;
8435
+ if (!isPath(path))
8436
+ return false;
8437
+ } else if (!isPath(hier))
8438
+ return false;
8439
+ if (query !== undefined && !isQueryOrFragment(query))
8440
+ return false;
8441
+ if (fragment !== undefined && !isQueryOrFragment(fragment))
8442
+ return false;
8443
+ return true;
8444
+ }
8445
+ //! Lexical RFC 3339 `date-time` + instant, mirroring Rust `Timestamp`.
8446
+ var SHAPE = /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/;
8447
+ function daysFromCivil(y, m, d) {
8448
+ const yy = m <= 2 ? y - 1 : y;
8449
+ const era = Math.floor((yy >= 0 ? yy : yy - 399) / 400);
8450
+ const yoe = yy - era * 400;
8451
+ const doy = Math.floor((153 * (m > 2 ? m - 3 : m + 9) + 2) / 5) + d - 1;
8452
+ const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;
8453
+ return era * 146097 + doe - 719468;
8454
+ }
8455
+ function daysInMonth(year, month) {
8456
+ return [
8457
+ 31,
8458
+ year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28,
8459
+ 31,
8460
+ 30,
8461
+ 31,
8462
+ 30,
8463
+ 31,
8464
+ 31,
8465
+ 30,
8466
+ 31,
8467
+ 30,
8468
+ 31
8469
+ ][month - 1] ?? 0;
8470
+ }
8471
+ function parseTimestamp(s) {
8472
+ const m = SHAPE.exec(s);
8473
+ if (m === null)
8474
+ return;
8475
+ const [, ys, mos, ds, hs, mis, ss, frac, tz] = m;
8476
+ const year = Number(ys);
8477
+ const month = Number(mos);
8478
+ const day = Number(ds);
8479
+ const hour = Number(hs);
8480
+ const minute = Number(mis);
8481
+ const second = Number(ss);
8482
+ if (month < 1 || month > 12)
8483
+ return;
8484
+ if (day < 1 || day > daysInMonth(year, month))
8485
+ return;
8486
+ if (hour > 23 || minute > 59 || second > 59)
8487
+ return;
8488
+ let ms = daysFromCivil(year, month, day) * 86400000 + hour * 3600000 + minute * 60000 + second * 1000;
8489
+ if (frac !== undefined && frac.length > 1)
8490
+ ms += Number(frac.slice(1, 4).padEnd(3, "0"));
8491
+ if (tz !== undefined && tz !== "Z" && tz !== "z") {
8492
+ const oh = Number(tz.slice(1, 3));
8493
+ const om = Number(tz.slice(4, 6));
8494
+ if (oh > 23 || om > 59)
8495
+ return;
8496
+ const off = (oh * 60 + om) * 60000;
8497
+ ms += tz.startsWith("+") ? -off : off;
8498
+ }
8499
+ if (!Number.isFinite(ms))
8500
+ return;
7997
8501
  return {
7998
- network,
7999
- account
8502
+ lexeme: s,
8503
+ epochMs: Math.trunc(ms)
8000
8504
  };
8001
- };
8505
+ }
8506
+ //! Strict UTF-8 helpers.
8507
+ //!
8508
+ //! `TextEncoder`/`TextDecoder` exist on every supported platform (Node,
8509
+ //! browsers, Hermes). Decoding must reject exactly what Rust
8510
+ //! `str::from_utf8` rejects — overlongs, surrogates, > U+10FFFF,
8511
+ //! truncated sequences — so `fatal: true` is used (which follows the
8512
+ //! WHATWG fatal algorithm and rejects all of those).
8513
+ var encoder = new TextEncoder;
8514
+ var fatalDecoder = new TextDecoder("utf-8", { fatal: true });
8515
+ function utf8Encode(text) {
8516
+ return encoder.encode(text);
8517
+ }
8518
+ function utf8Decode(bytes) {
8519
+ try {
8520
+ return fatalDecoder.decode(bytes);
8521
+ } catch {
8522
+ return;
8523
+ }
8524
+ }
8525
+ function utf8ByteLength(text) {
8526
+ return encoder.encode(text).length;
8527
+ }
8528
+ //! CAIP-122 abstract data model: lexical `MessageFields` and the
8529
+ //! validated `Message` produced by `createMessage` (single validation
8530
+ //! path, same check order as Rust `Message::new`).
8531
+ var STATEMENT_CHARS = /* @__PURE__ */ new Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;= ");
8532
+ function isCaip10Address(s) {
8533
+ if (s.length === 0 || s.length > 128)
8534
+ return false;
8535
+ for (const c of s)
8536
+ if (!/[A-Za-z0-9]/.test(c) && c !== "-" && c !== "." && c !== "%")
8537
+ return false;
8538
+ return true;
8539
+ }
8540
+ function createMessage(fields) {
8541
+ if (fields.scheme !== undefined && !isScheme(fields.scheme))
8542
+ throw fieldError("scheme", "not an RFC 3986 scheme");
8543
+ if (fields.domain.length === 0)
8544
+ throw fieldError("domain", "empty");
8545
+ if (fields.domain.includes("@"))
8546
+ throw fieldError("domain", "userinfo not allowed");
8547
+ if (fields.domain.startsWith(":"))
8548
+ throw fieldError("domain", "empty host");
8549
+ if (!isAuthority(fields.domain))
8550
+ throw fieldError("domain", "not an RFC 3986 authority");
8551
+ if (!isCaip10Address(fields.address))
8552
+ throw fieldError("address", fields.address.length === 0 || fields.address.length > 128 ? "expected 1..=128 characters" : "bad CAIP-10 charset");
8553
+ if (fields.statement !== undefined) {
8554
+ if (utf8ByteLength(fields.statement) > 4096)
8555
+ throw fieldError("statement", "exceeds maximum size");
8556
+ for (const c of fields.statement)
8557
+ if (!STATEMENT_CHARS.has(c))
8558
+ throw fieldError("statement", "must be RFC 3986 reserved / unreserved / SP");
8559
+ }
8560
+ checkUri(fields.uri, "uri");
8561
+ if (fields.version !== "1")
8562
+ throw fieldError("version", 'must be "1"');
8563
+ if (fields.chainId.length === 0)
8564
+ throw fieldError("chainId", "empty");
8565
+ if (fields.chainId.length > 64)
8566
+ throw fieldError("chainId", "exceeds 64 characters");
8567
+ for (const c of fields.chainId)
8568
+ if (!/[A-Za-z0-9]/.test(c) && c !== "-" && c !== "_" && c !== ":")
8569
+ throw fieldError("chainId", "bad charset");
8570
+ if (fields.nonce.length < 8)
8571
+ throw fieldError("nonce", "too short");
8572
+ for (const c of fields.nonce)
8573
+ if (!/[A-Za-z0-9]/.test(c))
8574
+ throw fieldError("nonce", "not ASCII alphanumeric");
8575
+ if (parseTimestamp(fields.issuedAt) === undefined)
8576
+ throw fieldError("issuedAt", "not an RFC 3339 date-time");
8577
+ if (fields.expirationTime !== undefined && parseTimestamp(fields.expirationTime) === undefined)
8578
+ throw fieldError("expirationTime", "not an RFC 3339 date-time");
8579
+ if (fields.notBefore !== undefined && parseTimestamp(fields.notBefore) === undefined)
8580
+ throw fieldError("notBefore", "not an RFC 3339 date-time");
8581
+ if (fields.requestId !== undefined) {
8582
+ if (utf8ByteLength(fields.requestId) > 128)
8583
+ throw fieldError("requestId", "exceeds maximum size");
8584
+ if (!isPcharString(fields.requestId))
8585
+ throw fieldError("requestId", "must be RFC 3986 *pchar");
8586
+ }
8587
+ if (fields.resources !== undefined) {
8588
+ if (fields.resources.length > 32)
8589
+ throw fieldError("resources", "too many");
8590
+ for (const uri of fields.resources)
8591
+ checkUri(uri, "resources");
8592
+ }
8593
+ const out = {
8594
+ domain: fields.domain,
8595
+ address: fields.address,
8596
+ uri: fields.uri,
8597
+ version: fields.version,
8598
+ chainId: fields.chainId,
8599
+ nonce: fields.nonce,
8600
+ issuedAt: fields.issuedAt,
8601
+ ...fields.scheme === undefined ? {} : { scheme: fields.scheme },
8602
+ ...fields.statement === undefined ? {} : { statement: fields.statement },
8603
+ ...fields.expirationTime === undefined ? {} : { expirationTime: fields.expirationTime },
8604
+ ...fields.notBefore === undefined ? {} : { notBefore: fields.notBefore },
8605
+ ...fields.requestId === undefined ? {} : { requestId: fields.requestId },
8606
+ ...fields.resources === undefined ? {} : { resources: fields.resources }
8607
+ };
8608
+ return Object.freeze(out);
8609
+ }
8610
+ function checkUri(uri, field) {
8611
+ if (uri.length === 0)
8612
+ throw fieldError(field, "empty");
8613
+ if (utf8ByteLength(uri) > 2048)
8614
+ throw fieldError(field, "exceeds maximum size");
8615
+ if (!isUri(uri))
8616
+ throw fieldError(field, "not an RFC 3986 URI");
8617
+ }
8002
8618
 
8003
- // ../wallet-chains/dist/message-DuJ5KSRT.mjs
8004
- var MAINNET_BIP32 = {
8005
- public: 76067358,
8006
- private: 76066276
8007
- };
8008
- var TESTNET_BIP32 = {
8009
- public: 70617039,
8010
- private: 70615956
8011
- };
8012
- var REGTEST_NETWORK = {
8013
- ...TEST_NETWORK,
8014
- bech32: "bcrt"
8619
+ // ../../node_modules/.bun/@qntx+siwx@0.8.0/node_modules/@qntx/siwx/dist/rolldown-runtime-D8jQpDG7.mjs
8620
+ var __defProp = Object.defineProperty;
8621
+ var __exportAll = (all, no_symbols) => {
8622
+ let target = {};
8623
+ for (var name in all)
8624
+ __defProp(target, name, {
8625
+ get: all[name],
8626
+ enumerable: true
8627
+ });
8628
+ if (!no_symbols)
8629
+ __defProp(target, Symbol.toStringTag, { value: "Module" });
8630
+ return target;
8015
8631
  };
8016
- var NETWORKS = Object.freeze([
8017
- {
8018
- caip2: "bip122:000000000019d6689c085ae165831e93",
8019
- genesis: "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f",
8020
- params: NETWORK,
8021
- coinType: 0,
8022
- bip32: MAINNET_BIP32
8023
- },
8024
- {
8025
- caip2: "bip122:00000000da84f2bafbbc53dee25a72ae",
8026
- genesis: "00000000da84f2bafbbc53dee25a72ae507ff4914b867c565be350b0da8bf043",
8027
- params: TEST_NETWORK,
8028
- coinType: 1,
8029
- bip32: TESTNET_BIP32
8030
- },
8031
- {
8032
- caip2: "bip122:00000008819873e925422c1ff0f99f7c",
8033
- genesis: "00000008819873e925422c1ff0f99f7cc9bbb232af63a077a480a3633bee1ef6",
8034
- params: TEST_NETWORK,
8035
- coinType: 1,
8036
- bip32: TESTNET_BIP32
8037
- },
8038
- {
8039
- caip2: "bip122:0f9188f13cb7b2c71f2a335e3a4fc328",
8040
- genesis: "0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206",
8041
- params: REGTEST_NETWORK,
8042
- coinType: 1,
8043
- bip32: TESTNET_BIP32
8632
+
8633
+ // ../../node_modules/.bun/@qntx+siwx@0.8.0/node_modules/@qntx/siwx/dist/eip4361-Bf5VppSi.mjs
8634
+ //! ERC-4361 signing-text layout: `format` and its strict inverse `parse`.
8635
+ //! For every accepted text `t`, `format(label, parse(t).message) === t`
8636
+ //! byte-for-byte.
8637
+ function takeTag(line, tag, field) {
8638
+ if (!line.startsWith(tag))
8639
+ throw syntaxError("MissingField", field);
8640
+ return line.slice(tag.length);
8641
+ }
8642
+ function format(label, message) {
8643
+ let out = "";
8644
+ if (message.scheme !== undefined)
8645
+ out += `${message.scheme}://`;
8646
+ out += `${message.domain + MID + label + SUFFIX}
8647
+ `;
8648
+ out += `${message.address}
8649
+
8650
+ `;
8651
+ if (message.statement !== undefined)
8652
+ out += `${message.statement}
8653
+ `;
8654
+ out += `
8655
+ `;
8656
+ out += `URI: ${message.uri}
8657
+ `;
8658
+ out += `Version: ${message.version}
8659
+ `;
8660
+ out += `Chain ID: ${message.chainId}
8661
+ `;
8662
+ out += `Nonce: ${message.nonce}
8663
+ `;
8664
+ out += `Issued At: ${message.issuedAt}`;
8665
+ if (message.expirationTime !== undefined)
8666
+ out += `
8667
+ Expiration Time: ${message.expirationTime}`;
8668
+ if (message.notBefore !== undefined)
8669
+ out += `
8670
+ Not Before: ${message.notBefore}`;
8671
+ if (message.requestId !== undefined)
8672
+ out += `
8673
+ Request ID: ${message.requestId}`;
8674
+ if (message.resources !== undefined) {
8675
+ out += `
8676
+ Resources:`;
8677
+ for (const uri of message.resources)
8678
+ out += `
8679
+ - ${uri}`;
8044
8680
  }
8045
- ]);
8046
- var BITCOIN_NETWORKS = Object.freeze(Object.fromEntries(NETWORKS.map((n) => [n.caip2, n])));
8047
- var bitcoinNetwork = (caip2) => {
8048
- const net = BITCOIN_NETWORKS[caip2];
8049
- if (net === undefined)
8050
- throw new ChainError("unsupported", `unknown bitcoin network: ${caip2}`);
8051
- return net;
8052
- };
8053
- var utf8 = (s) => new TextEncoder().encode(s);
8054
- var BIP322_TAG = "BIP0322-signed-message";
8055
- var LEGACY_MAGIC = utf8(`Bitcoin Signed Message:
8681
+ return out;
8682
+ }
8683
+ function parse(text) {
8684
+ const byteLength = utf8ByteLength(text);
8685
+ if (byteLength > 16384)
8686
+ throw new SiwxError({
8687
+ code: "MessageTooLarge",
8688
+ length: byteLength,
8689
+ max: MAX_MESSAGE_BYTES
8690
+ });
8691
+ if (text.includes("\r"))
8692
+ throw syntaxError("CarriageReturn");
8693
+ const lines = text.split(`
8056
8694
  `);
8057
- var concat = (...parts) => {
8058
- const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
8059
- let o = 0;
8060
- for (const p of parts) {
8061
- out.set(p, o);
8062
- o += p.length;
8063
- }
8064
- return out;
8065
- };
8066
- var varint = (n) => Uint8Array.of(n);
8067
- var pushData = (data) => concat(varint(data.length), data);
8068
- var u32le = (n) => Uint8Array.of(n % 256, Math.floor(n / 256) % 256, Math.floor(n / 65536) % 256, Math.floor(n / 16777216) % 256);
8069
- var u64le = (n) => {
8070
- const out = /* @__PURE__ */ new Uint8Array(8);
8071
- let v = n;
8072
- for (let i = 0;i < 8; i++) {
8073
- out[i] = Number(v % 256n);
8074
- v /= 256n;
8075
- }
8076
- return out;
8077
- };
8078
- var bip322MessageHash = (message) => {
8079
- const tag = sha256(utf8(BIP322_TAG));
8080
- return sha256(concat(tag, tag, utf8(message)));
8081
- };
8082
- var toSpend = (scriptPubKey, messageHash) => {
8083
- const scriptSig = concat(Uint8Array.of(0), pushData(messageHash));
8084
- const raw = concat(u32le(0), varint(1), /* @__PURE__ */ new Uint8Array(32), u32le(4294967295), pushData(scriptSig), u32le(0), varint(1), u64le(0n), pushData(scriptPubKey), u32le(0));
8695
+ let i = 0;
8696
+ const next = () => {
8697
+ const l = lines[i++];
8698
+ if (l === undefined)
8699
+ throw syntaxError("UnexpectedEof");
8700
+ return l;
8701
+ };
8702
+ const preamble = next();
8703
+ const mid = preamble.indexOf(MID);
8704
+ if (mid === -1)
8705
+ throw syntaxError("MissingPreamble");
8706
+ const head = preamble.slice(0, mid);
8707
+ const tail = preamble.slice(mid + MID.length);
8708
+ if (!tail.endsWith(" account:"))
8709
+ throw syntaxError("MissingAccountSuffix");
8710
+ const label = tail.slice(0, -SUFFIX.length);
8711
+ if (label.length === 0)
8712
+ throw fieldError("label", "empty");
8713
+ let scheme;
8714
+ let domain;
8715
+ const proto = head.indexOf("://");
8716
+ if (proto === -1)
8717
+ domain = head;
8718
+ else {
8719
+ scheme = head.slice(0, proto);
8720
+ domain = head.slice(proto + 3);
8721
+ }
8722
+ const address = next();
8723
+ let blanks = 0;
8724
+ while (lines[i + blanks] === "")
8725
+ blanks++;
8726
+ let statement;
8727
+ if (blanks === 1) {
8728
+ i += 1;
8729
+ statement = next();
8730
+ if (next() !== "")
8731
+ throw syntaxError("ExpectedBlankLine");
8732
+ } else if (blanks === 2)
8733
+ i += 2;
8734
+ else if (blanks === 3) {
8735
+ i += 3;
8736
+ statement = "";
8737
+ } else
8738
+ throw syntaxError("ExpectedBlankLine");
8739
+ const uri = takeTag(next(), "URI: ", "uri");
8740
+ const version = takeTag(next(), "Version: ", "version");
8741
+ const chainId = takeTag(next(), "Chain ID: ", "chainId");
8742
+ const nonce = takeTag(next(), "Nonce: ", "nonce");
8743
+ const issuedAt = takeTag(next(), "Issued At: ", "issuedAt");
8744
+ const opt = optionalTags(lines, i);
8745
+ const fields = {
8746
+ scheme,
8747
+ domain,
8748
+ address,
8749
+ statement,
8750
+ uri,
8751
+ version,
8752
+ chainId,
8753
+ nonce,
8754
+ issuedAt,
8755
+ ...opt
8756
+ };
8085
8757
  return {
8086
- txid: sha256(sha256(raw)),
8087
- raw
8758
+ label,
8759
+ message: createMessage(fields)
8088
8760
  };
8089
- };
8090
- var BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
8091
- var b642 = (i) => BASE64[i] ?? "";
8092
- var base642 = (bytes) => {
8093
- const c = b642;
8094
- let out = "";
8095
- for (let i = 0;i < bytes.length; i += 3) {
8096
- const b0 = bytes[i] ?? 0;
8097
- const b1 = bytes[i + 1] ?? 0;
8098
- const b2 = bytes[i + 2] ?? 0;
8099
- out += c(Math.floor(b0 / 4)) + c(b0 % 4 * 16 + Math.floor(b1 / 16));
8100
- out += i + 1 < bytes.length ? c(b1 % 16 * 4 + Math.floor(b2 / 64)) : "=";
8101
- out += i + 2 < bytes.length ? c(b2 % 64) : "=";
8761
+ }
8762
+ function parseBytes(bytes) {
8763
+ if (bytes.length > 16384)
8764
+ throw new SiwxError({
8765
+ code: "MessageTooLarge",
8766
+ length: bytes.length,
8767
+ max: MAX_MESSAGE_BYTES
8768
+ });
8769
+ const text = utf8Decode(bytes);
8770
+ if (text === undefined)
8771
+ throw syntaxError("InvalidUtf8");
8772
+ return parse(text);
8773
+ }
8774
+ function parseLabeled(label, signed) {
8775
+ const parsed = parseBytes(signed);
8776
+ if (parsed.label !== label)
8777
+ throw mismatchError("label", label, parsed.label);
8778
+ return parsed.message;
8779
+ }
8780
+
8781
+ // ../../node_modules/.bun/@noble+hashes@2.4.0/node_modules/@noble/hashes/sha3.js
8782
+ var _0n4 = BigInt(0);
8783
+ var _1n4 = BigInt(1);
8784
+ var _2n4 = BigInt(2);
8785
+ var _7n = BigInt(7);
8786
+ var _256n = BigInt(256);
8787
+ var _0x71n = BigInt(113);
8788
+ var SHA3_PI = [];
8789
+ var SHA3_ROTL = [];
8790
+ var _SHA3_IOTA = [];
8791
+ for (let round = 0, R = _1n4, x = 1, y = 0;round < 24; round++) {
8792
+ [x, y] = [y, (2 * x + 3 * y) % 5];
8793
+ SHA3_PI.push(2 * (5 * y + x));
8794
+ SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
8795
+ let t = _0n4;
8796
+ for (let j = 0;j < 7; j++) {
8797
+ R = (R << _1n4 ^ (R >> _7n) * _0x71n) % _256n;
8798
+ if (R & _2n4)
8799
+ t ^= _1n4 << (_1n4 << BigInt(j)) - _1n4;
8102
8800
  }
8103
- return out;
8104
- };
8105
- var signBip322Simple = (message, scriptPubKey, privateKey, auxRand) => {
8106
- const hash = bip322MessageHash(message);
8107
- const { txid } = toSpend(scriptPubKey, hash);
8108
- const tx = new Transaction({
8109
- version: 0,
8110
- lockTime: 0,
8111
- allowUnknownOutputs: true
8112
- });
8113
- const pub = secp256k1.getPublicKey(privateKey, true);
8114
- tx.addInput({
8115
- txid,
8116
- index: 0,
8117
- sequence: 0,
8118
- witnessUtxo: {
8119
- script: scriptPubKey,
8120
- amount: 0n
8121
- },
8122
- bip32Derivation: [[pub, {
8123
- fingerprint: 0,
8124
- path: []
8125
- }]],
8126
- ...scriptPubKey[0] === 81 ? { tapInternalKey: pub.slice(1) } : {}
8127
- });
8128
- tx.addOutput({
8129
- script: Uint8Array.of(106),
8130
- amount: 0n
8131
- });
8132
- const isTaproot = scriptPubKey[0] === 81;
8133
- if (!tx.signIdx(privateKey, 0, isTaproot ? [SigHash.DEFAULT, SigHash.ALL] : [SigHash.ALL], auxRand(0)))
8134
- throw new ChainError("invalid-request", "key cannot sign this BIP-322 input");
8135
- tx.finalizeIdx(0);
8136
- const witness = tx.getInput(0).finalScriptWitness;
8137
- if (witness === undefined)
8138
- throw new ChainError("invalid-request", "BIP-322 input produced no witness");
8139
- const raw = concat(varint(witness.length), ...witness.map(pushData));
8140
- return `smp${base642(raw)}`;
8141
- };
8142
- var signLegacyMessage = (message, privateKey) => {
8143
- const data = concat(pushData(LEGACY_MAGIC), pushData(utf8(message)));
8144
- const hash = sha256(sha256(data));
8145
- const recovered = secp256k1.sign(hash, privateKey, {
8146
- lowS: true,
8147
- format: "recovered"
8148
- });
8149
- const header = 27 + (recovered[0] ?? 0) + 4;
8150
- return base642(concat(Uint8Array.of(header), recovered.slice(1)));
8151
- };
8801
+ _SHA3_IOTA.push(t);
8802
+ }
8803
+ var IOTAS = split(_SHA3_IOTA, true);
8804
+ var SHA3_IOTA_H = IOTAS[0];
8805
+ var SHA3_IOTA_L = IOTAS[1];
8806
+ var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
8807
+ var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
8808
+ var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
8809
+ var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
8810
+ var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
8811
+ var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
8812
+ var B = new Uint32Array(5 * 2);
8813
+ function keccakP(s, rounds = 24) {
8814
+ if (!(s instanceof Uint32Array))
8815
+ throw new TypeError('"s" expected Uint32Array(50), got type=' + typeof s);
8816
+ if (s.length !== 50)
8817
+ throw new RangeError('"s" expected Uint32Array(50), got length=' + s.length);
8818
+ anumber(rounds, "rounds");
8819
+ if (rounds < 1 || rounds > 24)
8820
+ throw new Error('"rounds" expected integer 1..24');
8821
+ for (let round = 24 - rounds;round < 24; round++) {
8822
+ for (let x = 0;x < 10; x++)
8823
+ B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
8824
+ for (let x = 0;x < 10; x += 2) {
8825
+ const idx1 = (x + 8) % 10;
8826
+ const idx0 = (x + 2) % 10;
8827
+ const B0 = B[idx0];
8828
+ const B1 = B[idx0 + 1];
8829
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
8830
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
8831
+ for (let y = 0;y < 50; y += 10) {
8832
+ s[x + y] ^= Th;
8833
+ s[x + y + 1] ^= Tl;
8834
+ }
8835
+ }
8836
+ let curH = s[2];
8837
+ let curL = s[3];
8838
+ for (let t = 0;t < 24; t++) {
8839
+ const shift = SHA3_ROTL[t];
8840
+ const Th = rotlH(curH, curL, shift);
8841
+ const Tl = rotlL(curH, curL, shift);
8842
+ const PI = SHA3_PI[t];
8843
+ curH = s[PI];
8844
+ curL = s[PI + 1];
8845
+ s[PI] = Th;
8846
+ s[PI + 1] = Tl;
8847
+ }
8848
+ for (let y = 0;y < 50; y += 10) {
8849
+ const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3];
8850
+ s[y] ^= ~s[y + 2] & s[y + 4];
8851
+ s[y + 1] ^= ~s[y + 3] & s[y + 5];
8852
+ s[y + 2] ^= ~s[y + 4] & s[y + 6];
8853
+ s[y + 3] ^= ~s[y + 5] & s[y + 7];
8854
+ s[y + 4] ^= ~s[y + 6] & s[y + 8];
8855
+ s[y + 5] ^= ~s[y + 7] & s[y + 9];
8856
+ s[y + 6] ^= ~s[y + 8] & b0;
8857
+ s[y + 7] ^= ~s[y + 9] & b1;
8858
+ s[y + 8] ^= ~b0 & b2;
8859
+ s[y + 9] ^= ~b1 & b3;
8860
+ }
8861
+ s[0] ^= SHA3_IOTA_H[round];
8862
+ s[1] ^= SHA3_IOTA_L[round];
8863
+ }
8864
+ clean(B);
8865
+ }
8152
8866
 
8153
- // ../wallet-chains/dist/bitcoin.mjs
8154
- var isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8155
- var derivationPaths = (map) => {
8156
- const entries = map instanceof Map ? [...map.values()] : Array.isArray(map) ? map : isRecord$1(map) ? Object.values(map) : [];
8157
- const paths = [];
8158
- for (const entry of entries) {
8159
- const value = Array.isArray(entry) ? entry[1] : entry;
8160
- if (!isRecord$1(value))
8161
- continue;
8162
- const { path } = isRecord$1(value["der"]) ? value["der"] : value;
8163
- if (Array.isArray(path) && path.every((p) => typeof p === "number"))
8164
- paths.push(path);
8867
+ class Keccak {
8868
+ state;
8869
+ pos = 0;
8870
+ posOut = 0;
8871
+ finished = false;
8872
+ state32;
8873
+ destroyed = false;
8874
+ blockLen;
8875
+ suffix;
8876
+ outputLen;
8877
+ canXOF;
8878
+ enableXOF = false;
8879
+ rounds;
8880
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
8881
+ anumber(blockLen, "blockLen");
8882
+ anumber(suffix, "suffix");
8883
+ anumber(rounds, "rounds");
8884
+ abool(enableXOF, "enableXOF");
8885
+ this.blockLen = blockLen;
8886
+ this.suffix = suffix;
8887
+ this.outputLen = outputLen;
8888
+ this.enableXOF = enableXOF;
8889
+ this.canXOF = enableXOF;
8890
+ this.rounds = rounds;
8891
+ anumber(outputLen, "outputLen");
8892
+ if (!(0 < blockLen && blockLen < 200))
8893
+ throw new Error('"blockLen" must be 1..199');
8894
+ this.state = new Uint8Array(200);
8895
+ this.state32 = u32(this.state);
8896
+ }
8897
+ clone() {
8898
+ return this._cloneInto();
8899
+ }
8900
+ keccak() {
8901
+ swap32IfBE(this.state32);
8902
+ keccakP(this.state32, this.rounds);
8903
+ swap32IfBE(this.state32);
8904
+ this.posOut = 0;
8905
+ this.pos = 0;
8906
+ }
8907
+ update(data) {
8908
+ aexists(this);
8909
+ abytes(data);
8910
+ const { blockLen, state, state32 } = this;
8911
+ const len = data.length;
8912
+ const canUseU32 = blockLen % 4 === 0 && data.byteOffset % 4 === 0;
8913
+ const blockLen32 = blockLen / 4;
8914
+ const data32 = canUseU32 && len >= blockLen ? u32(data) : undefined;
8915
+ for (let pos = 0;pos < len; ) {
8916
+ if (data32 !== undefined && this.pos === 0 && pos % 4 === 0 && len - pos >= blockLen) {
8917
+ for (let i = 0, o = pos / 4;i < blockLen32; i++)
8918
+ state32[i] ^= data32[o + i];
8919
+ pos += blockLen;
8920
+ this.pos = blockLen;
8921
+ this.keccak();
8922
+ continue;
8923
+ }
8924
+ const take = Math.min(blockLen - this.pos, len - pos);
8925
+ for (let i = 0;i < take; i++)
8926
+ state[this.pos++] ^= data[pos++];
8927
+ if (this.pos === blockLen)
8928
+ this.keccak();
8929
+ }
8930
+ return this;
8931
+ }
8932
+ finish() {
8933
+ if (this.finished)
8934
+ return;
8935
+ this.finished = true;
8936
+ const { state, suffix, pos, blockLen } = this;
8937
+ state[pos] ^= suffix;
8938
+ if ((suffix & 128) !== 0 && pos === blockLen - 1)
8939
+ this.keccak();
8940
+ state[blockLen - 1] ^= 128;
8941
+ this.keccak();
8942
+ }
8943
+ writeInto(out) {
8944
+ aexists(this, false);
8945
+ abytes(out);
8946
+ this.finish();
8947
+ const bufferOut = this.state;
8948
+ const { blockLen } = this;
8949
+ for (let pos = 0, len = out.length;pos < len; ) {
8950
+ if (this.posOut >= blockLen)
8951
+ this.keccak();
8952
+ const take = Math.min(blockLen - this.posOut, len - pos);
8953
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
8954
+ this.posOut += take;
8955
+ pos += take;
8956
+ }
8957
+ return out;
8958
+ }
8959
+ xofInto(out) {
8960
+ if (!this.enableXOF)
8961
+ throw new Error("XOF is not enabled");
8962
+ return this.writeInto(out);
8963
+ }
8964
+ xof(bytes) {
8965
+ anumber(bytes);
8966
+ return this.xofInto(new Uint8Array(bytes));
8967
+ }
8968
+ digestInto(out) {
8969
+ aoutput(out, this);
8970
+ if (this.finished)
8971
+ throw new Error("digest() was already called");
8972
+ this.writeInto(out.length === this.outputLen ? out : out.subarray(0, this.outputLen));
8973
+ this.destroy();
8974
+ }
8975
+ digest() {
8976
+ const out = new Uint8Array(this.outputLen);
8977
+ this.digestInto(out);
8978
+ return out;
8979
+ }
8980
+ destroy() {
8981
+ this.destroyed = true;
8982
+ clean(this.state);
8983
+ }
8984
+ _cloneInto(to) {
8985
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
8986
+ to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);
8987
+ to.blockLen = blockLen;
8988
+ to.state32.set(this.state32);
8989
+ to.pos = this.pos;
8990
+ to.posOut = this.posOut;
8991
+ to.finished = this.finished;
8992
+ to.rounds = rounds;
8993
+ to.suffix = suffix;
8994
+ to.outputLen = outputLen;
8995
+ to.enableXOF = enableXOF;
8996
+ to.canXOF = this.canXOF;
8997
+ to.destroyed = this.destroyed;
8998
+ return to;
8999
+ }
9000
+ }
9001
+ var genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);
9002
+ var keccak_256 = /* @__PURE__ */ genKeccak(1, 136, 32);
9003
+
9004
+ // ../../node_modules/.bun/@qntx+siwx@0.8.0/node_modules/@qntx/siwx/dist/evm.mjs
9005
+ //! EIP-55 / EVM address + chain-id rules, matching `siwx::evm`.
9006
+ var HEX40 = /^[0-9a-fA-F]{40}$/;
9007
+ function toChecksumAddress(address) {
9008
+ if (!address.startsWith("0x"))
9009
+ throw fieldError("address", "expected 0x + 40 hex");
9010
+ const body = address.slice(2);
9011
+ if (!HEX40.test(body))
9012
+ throw fieldError("address", "expected 0x + 40 hex");
9013
+ const lower = body.toLowerCase();
9014
+ const hash = keccak_256(utf8Encode(lower));
9015
+ let out = "0x";
9016
+ for (let i = 0;i < 40; i++) {
9017
+ const c = lower.charAt(i);
9018
+ const nibble = (hash[Math.floor(i / 2)] ?? 0) >> (i % 2 === 0 ? 4 : 0) & 15;
9019
+ out += /[a-f]/.test(c) && nibble >= 8 ? c.toUpperCase() : c;
9020
+ }
9021
+ return out;
9022
+ }
9023
+ var badAddress = () => fieldError("address", "expected 0x + 40 hex");
9024
+ function parseEip55(address) {
9025
+ const bad = badAddress;
9026
+ if (!address.startsWith("0x"))
9027
+ throw bad();
9028
+ const hex = address.slice(2);
9029
+ if (!HEX40.test(hex))
9030
+ throw bad();
9031
+ const hasLower = /[a-f]/.test(hex);
9032
+ const hasUpper = /[A-F]/.test(hex);
9033
+ if (hasLower && hasUpper && address !== toChecksumAddress(address))
9034
+ throw fieldError("address", "bad EIP-55 checksum");
9035
+ return hexToBytes(hex);
9036
+ }
9037
+ function parseEvmChainId(chainId) {
9038
+ if (chainId.length === 0)
9039
+ throw fieldError("chainId", "empty");
9040
+ if (!/^[0-9]+$/.test(chainId))
9041
+ throw fieldError("chainId", "not decimal");
9042
+ if (chainId.length > 1 && chainId.startsWith("0"))
9043
+ throw fieldError("chainId", "leading zero");
9044
+ const value = BigInt(chainId);
9045
+ if (value > 18446744073709551615n)
9046
+ throw fieldError("chainId", "overflow");
9047
+ return value;
9048
+ }
9049
+ //! EIP-191 `personal_sign` verification.
9050
+ //!
9051
+ //! Decode order (cross-language contract, mirrored with Rust): length ≠
9052
+ //! 65 → `v ∉ {0,1,27,28}` → `r`/`s` equal to 0 or ≥ n → `s > n/2` (all
9053
+ //! `InvalidSignature`) → recovery failure or address mismatch →
9054
+ //! `VerificationFailed`.
9055
+ var N = secp256k1.Point.Fn.ORDER;
9056
+ var N_HALF = N / 2n;
9057
+ function eip191Hash(message) {
9058
+ const prefix = utf8Encode(`\x19Ethereum Signed Message:
9059
+ ${message.length}`);
9060
+ const joined = new Uint8Array(prefix.length + message.length);
9061
+ joined.set(prefix);
9062
+ joined.set(message, prefix.length);
9063
+ return keccak_256(joined);
9064
+ }
9065
+ function verifyEip191(message, signed, signature) {
9066
+ if (signature.length !== 65)
9067
+ throw new SiwxError({
9068
+ code: "InvalidSignature",
9069
+ reason: "EIP-191 signature must be 65 bytes"
9070
+ });
9071
+ const v = signature[64] ?? 0;
9072
+ if (v !== 0 && v !== 1 && v !== 27 && v !== 28)
9073
+ throw new SiwxError({
9074
+ code: "InvalidSignature",
9075
+ reason: "v must be 0, 1, 27 or 28"
9076
+ });
9077
+ const r = bytesToNumberBE(signature.subarray(0, 32));
9078
+ const s = bytesToNumberBE(signature.subarray(32, 64));
9079
+ if (r === 0n || r >= N || s === 0n || s >= N)
9080
+ throw new SiwxError({
9081
+ code: "InvalidSignature",
9082
+ reason: "r/s out of range"
9083
+ });
9084
+ if (s > N_HALF)
9085
+ throw new SiwxError({
9086
+ code: "InvalidSignature",
9087
+ reason: "high-s (EIP-2)"
9088
+ });
9089
+ const hash = eip191Hash(signed);
9090
+ let recovered;
9091
+ try {
9092
+ const uncompressed = secp256k1.Signature.fromBytes(signature.subarray(0, 64), "compact").addRecoveryBit(v % 27).recoverPublicKey(hash).toBytes(false);
9093
+ recovered = keccak_256(uncompressed.subarray(1)).subarray(12);
9094
+ } catch {
9095
+ throw new SiwxError({ code: "VerificationFailed" });
9096
+ }
9097
+ const expected = parseEip55(message.address);
9098
+ if (!equalBytes(recovered, expected))
9099
+ throw new SiwxError({ code: "VerificationFailed" });
9100
+ }
9101
+ //! On-chain smart-account verification: the ERC-6492 universal validator via a
9102
+ //! deployless `eth_call`. Covers deployed ERC-1271 accounts, counterfactual
9103
+ //! ERC-6492 accounts and EOAs. Providers are injected; the library builds no
9104
+ //! transports and applies no timeouts — transport policy belongs to the
9105
+ //! provider owner.
9106
+ var BYTECODE = hexToBytes2("608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572");
9107
+ function deploylessCalldata(signer, hash, signature) {
9108
+ const addr = hexToBytes2(signer.slice(2));
9109
+ const word = 32;
9110
+ const out = new Uint8Array(BYTECODE.length + 96 + word + Math.ceil(signature.length / word) * word);
9111
+ const bc = BYTECODE;
9112
+ out.set(bc, 0);
9113
+ let o = bc.length;
9114
+ out.set(addr, o + (word - addr.length));
9115
+ o += word;
9116
+ out.set(hash, o);
9117
+ o += word;
9118
+ out.set(numberToBytesBE(BigInt(96), word), o);
9119
+ o += word;
9120
+ out.set(numberToBytesBE(BigInt(signature.length), word), o);
9121
+ out.set(signature, o + word);
9122
+ return out;
9123
+ }
9124
+ var malformed = () => new SiwxError({
9125
+ code: "Backend",
9126
+ reason: "malformed eth_call result"
9127
+ });
9128
+ function decodeResult(hex) {
9129
+ const data = hex === "" || hex === "0x" ? /* @__PURE__ */ new Uint8Array(0) : hexToBytes2(hex.slice(2));
9130
+ if (data.length === 1) {
9131
+ if (data[0] === 1)
9132
+ return true;
9133
+ if (data[0] === 0)
9134
+ return false;
9135
+ throw malformed();
8165
9136
  }
8166
- return paths;
8167
- };
8168
- var checkPaths = (paths, where, coinType) => {
8169
- for (const path of paths)
8170
- if (path.length >= 2 && (path[1] ?? -1) - 2147483648 !== coinType)
8171
- throw new ChainError("chain-id-mismatch", `${where} derivation coin type is not this network's`);
8172
- };
8173
- var checkDerivations = (tx, coinType) => {
8174
- for (let i = 0;i < tx.inputsLength; i++) {
8175
- const input = tx.getInput(i);
8176
- checkPaths(derivationPaths(input.bip32Derivation), `input ${i}`, coinType);
8177
- checkPaths(derivationPaths(input.tapBip32Derivation), `input ${i}`, coinType);
9137
+ if (data.length === 32) {
9138
+ for (let i = 0;i < 31; i++)
9139
+ if (data[i] !== 0)
9140
+ throw malformed();
9141
+ if (data[31] === 1)
9142
+ return true;
9143
+ if (data[31] === 0)
9144
+ return false;
8178
9145
  }
8179
- for (let i = 0;i < tx.outputsLength; i++) {
8180
- const output = tx.getOutput(i);
8181
- checkPaths(derivationPaths(output.bip32Derivation), `output ${i}`, coinType);
8182
- checkPaths(derivationPaths(output.tapBip32Derivation), `output ${i}`, coinType);
9146
+ throw malformed();
9147
+ }
9148
+ var codeOf = (error) => typeof error === "object" && error !== null && ("code" in error) ? error.code : undefined;
9149
+ function isRevert(error) {
9150
+ const code = codeOf(error);
9151
+ return typeof code === "number" && code === 3;
9152
+ }
9153
+ function backend() {
9154
+ return new SiwxError({
9155
+ code: "Backend",
9156
+ reason: "RPC request failed"
9157
+ });
9158
+ }
9159
+ var MAGIC = (() => {
9160
+ const m = /* @__PURE__ */ new Uint8Array(32);
9161
+ for (let i = 0;i < m.length; i++)
9162
+ m[i] = i % 2 === 0 ? 100 : 146;
9163
+ return m;
9164
+ })();
9165
+ function has6492MagicSuffix(signature) {
9166
+ if (signature.length < MAGIC.length)
9167
+ return false;
9168
+ for (let i = 0;i < MAGIC.length; i++)
9169
+ if (signature[signature.length - MAGIC.length + i] !== MAGIC[i])
9170
+ return false;
9171
+ return true;
9172
+ }
9173
+ async function providerChainId(provider) {
9174
+ let result;
9175
+ try {
9176
+ result = await provider.request({ method: "eth_chainId" });
9177
+ } catch {
9178
+ throw backend();
8183
9179
  }
8184
- };
8185
- var DEFAULT_SIGHASH = 0;
8186
- var SIGHASH_ALL = 1;
8187
- var isTaprootInput = (input) => input.tapInternalKey !== undefined || getInputType(input).type === "taproot";
8188
- var normalizeBitcoinPsbt = (psbt, sign, network) => {
8189
- const net = bitcoinNetwork(network);
8190
- let tx;
9180
+ if (typeof result !== "string" || !/^0x[0-9a-fA-F]+$/.test(result))
9181
+ throw backend();
9182
+ return BigInt(result);
9183
+ }
9184
+ async function verifyOnChain(provider, message, signed, signature) {
9185
+ parseEip55(message.address);
9186
+ const hash = eip191Hash(signed);
9187
+ const data = `0x${bytesToHex2(deploylessCalldata(message.address, hash, signature))}`;
9188
+ let result;
8191
9189
  try {
8192
- tx = Transaction.fromPSBT(psbt, { strictPrevoutValidation: true });
9190
+ result = await provider.request({
9191
+ method: "eth_call",
9192
+ params: [{
9193
+ data,
9194
+ input: data
9195
+ }, "latest"]
9196
+ });
9197
+ } catch (error) {
9198
+ throw isRevert(error) ? new SiwxError({ code: "VerificationFailed" }) : backend();
9199
+ }
9200
+ if (typeof result !== "string" || !/^0x[0-9a-fA-F]*$/.test(result))
9201
+ throw backend();
9202
+ if (!decodeResult(result))
9203
+ throw new SiwxError({ code: "VerificationFailed" });
9204
+ }
9205
+ //! `@qntx/siwx/evm` — EIP-155 (`eip155`) namespace profile.
9206
+ //!
9207
+ //! `account()` emits the canonical EIP-55 checksum spelling, so
9208
+ //! lowercase / uppercase / checksummed spellings of the same address map
9209
+ //! to the same `AccountId`.
9210
+ var CHAIN_NAME = "Ethereum";
9211
+ var NAMESPACE = "eip155";
9212
+ function evmAccount(message) {
9213
+ parseEip55(message.address);
9214
+ parseEvmChainId(message.chainId);
9215
+ return createAccountId(NAMESPACE, message.chainId, toChecksumAddress(message.address));
9216
+ }
9217
+ function evm(options) {
9218
+ const rpc = options?.rpc ?? {};
9219
+ const verifiedChains = /* @__PURE__ */ new Set;
9220
+ const providerFor = (chainId) => {
9221
+ const key = parseEvmChainId(chainId).toString(10);
9222
+ return rpc[key];
9223
+ };
9224
+ const onChain = async (message, signed, signature, eip191Err) => {
9225
+ const key = parseEvmChainId(message.chainId).toString(10);
9226
+ const provider = providerFor(message.chainId);
9227
+ if (provider === undefined)
9228
+ throw eip191Err ?? new SiwxError({
9229
+ code: "Unsupported",
9230
+ reason: "EIP-6492 requires RPC"
9231
+ });
9232
+ if (!verifiedChains.has(key)) {
9233
+ const rpcChain = await providerChainId(provider);
9234
+ if (rpcChain !== parseEvmChainId(message.chainId))
9235
+ throw new SiwxError({
9236
+ code: "Mismatch",
9237
+ field: "chainId",
9238
+ expected: key,
9239
+ actual: rpcChain.toString()
9240
+ });
9241
+ verifiedChains.add(key);
9242
+ }
9243
+ await verifyOnChain(provider, message, signed, signature);
9244
+ };
9245
+ return {
9246
+ namespace: NAMESPACE,
9247
+ label: CHAIN_NAME,
9248
+ account: evmAccount,
9249
+ format(message) {
9250
+ evmAccount(message);
9251
+ return format(CHAIN_NAME, message);
9252
+ },
9253
+ parse(signed) {
9254
+ return parseLabeled(CHAIN_NAME, signed);
9255
+ },
9256
+ verify: async (message, signed, signature) => {
9257
+ if (has6492MagicSuffix(signature)) {
9258
+ await onChain(message, signed, signature, undefined);
9259
+ return;
9260
+ }
9261
+ try {
9262
+ verifyEip191(message, signed, signature);
9263
+ } catch (error) {
9264
+ if (error instanceof SiwxError && providerFor(message.chainId) !== undefined) {
9265
+ await onChain(message, signed, signature, error);
9266
+ return;
9267
+ }
9268
+ throw error;
9269
+ }
9270
+ }
9271
+ };
9272
+ }
9273
+
9274
+ // ../../node_modules/.bun/@qntx+siwx@0.8.0/node_modules/@qntx/siwx/dist/svm.mjs
9275
+ function addressBytes(address) {
9276
+ if (address.length < 32 || address.length > 44)
9277
+ throw fieldError("address", "expected 32–44 base58 chars");
9278
+ let bytes;
9279
+ try {
9280
+ bytes = base58.decode(address);
8193
9281
  } catch {
8194
- throw new ChainError("invalid-request", "PSBT failed to decode");
9282
+ throw fieldError("address", "invalid base58");
8195
9283
  }
8196
- if (!Array.isArray(sign) || sign.length === 0 || !sign.every((i) => Number.isSafeInteger(i) && i >= 0))
8197
- throw new ChainError("invalid-request", "sign must be a non-empty array of input indices");
8198
- const unique = [...new Set(sign.map(Number))].sort((a, b) => a - b);
8199
- const last = unique.at(-1);
8200
- if (unique.length !== sign.length || last === undefined || last >= tx.inputsLength)
8201
- throw new ChainError("invalid-request", "sign must be unique, ascending, and in range");
8202
- checkDerivations(tx, net.coinType);
8203
- for (const idx of unique) {
8204
- const input = tx.getInput(idx);
8205
- if (input.witnessUtxo === undefined && input.nonWitnessUtxo === undefined)
8206
- throw new ChainError("invalid-request", `input ${idx} carries neither witnessUtxo nor nonWitnessUtxo`);
8207
- if (input.bip32Derivation === undefined && input.tapBip32Derivation === undefined)
8208
- throw new ChainError("invalid-request", `input ${idx} is missing a bip32 derivation`);
8209
- const { type } = getInputType(input);
8210
- if ((type === "legacy" || type === "nonwitness-script") && input.nonWitnessUtxo === undefined)
8211
- throw new ChainError("invalid-request", `input ${idx} is missing nonWitnessUtxo`);
8212
- const sighash = input.sighashType;
8213
- if (!(sighash === undefined || sighash === SIGHASH_ALL || isTaprootInput(input) && sighash === DEFAULT_SIGHASH))
8214
- throw new ChainError("unsupported", `input ${idx} uses a non-default sighash`);
9284
+ if (bytes.length !== 32)
9285
+ throw fieldError("address", "expected 32 bytes");
9286
+ return bytes;
9287
+ }
9288
+ function canonicalPoint(bytes) {
9289
+ let point;
9290
+ try {
9291
+ point = ed25519.Point.fromBytes(bytes);
9292
+ } catch {
9293
+ throw fieldError("address", "invalid Ed25519 pubkey");
9294
+ }
9295
+ if (point.equals(ed25519.Point.ZERO))
9296
+ throw fieldError("address", "identity pubkey");
9297
+ if (!point.isTorsionFree())
9298
+ throw fieldError("address", "not in the prime-order subgroup");
9299
+ if (!equalBytes(point.toBytes(), bytes))
9300
+ throw fieldError("address", "non-canonical pubkey");
9301
+ }
9302
+ function validateAddress(address) {
9303
+ canonicalPoint(addressBytes(address));
9304
+ }
9305
+ var L = ed25519.Point.CURVE().n;
9306
+ var P = ed25519.Point;
9307
+ var siws_exports = /* @__PURE__ */ __exportAll({
9308
+ format: () => format2,
9309
+ parse: () => parse2,
9310
+ parseBytes: () => parseBytes2
9311
+ });
9312
+ var LABEL = "Solana";
9313
+ function format2(message) {
9314
+ if (message.scheme !== undefined)
9315
+ throw new SiwxError({
9316
+ code: "InvalidField",
9317
+ field: "scheme",
9318
+ reason: "not supported by SIWS"
9319
+ });
9320
+ if (message.statement !== undefined) {
9321
+ if (message.statement === "")
9322
+ throw new SiwxError({
9323
+ code: "InvalidField",
9324
+ field: "statement",
9325
+ reason: "empty"
9326
+ });
9327
+ if (message.statement.startsWith("URI: "))
9328
+ throw new SiwxError({
9329
+ code: "InvalidField",
9330
+ field: "statement",
9331
+ reason: "ambiguous with the URI: tag"
9332
+ });
8215
9333
  }
8216
- return {
8217
- psbt: tx.toPSBT(0),
8218
- sign: unique
9334
+ let out = `${message.domain}${MID}${LABEL}${SUFFIX}
9335
+ ${message.address}`;
9336
+ if (message.statement !== undefined)
9337
+ out += `
9338
+
9339
+ ${message.statement}`;
9340
+ out += `
9341
+
9342
+ URI: ${message.uri}`;
9343
+ out += `
9344
+ Version: ${message.version}`;
9345
+ out += `
9346
+ Chain ID: ${message.chainId}`;
9347
+ out += `
9348
+ Nonce: ${message.nonce}`;
9349
+ out += `
9350
+ Issued At: ${message.issuedAt}`;
9351
+ if (message.expirationTime !== undefined)
9352
+ out += `
9353
+ Expiration Time: ${message.expirationTime}`;
9354
+ if (message.notBefore !== undefined)
9355
+ out += `
9356
+ Not Before: ${message.notBefore}`;
9357
+ if (message.requestId !== undefined)
9358
+ out += `
9359
+ Request ID: ${message.requestId}`;
9360
+ if (message.resources !== undefined) {
9361
+ out += `
9362
+ Resources:`;
9363
+ for (const r of message.resources)
9364
+ out += `
9365
+ - ${r}`;
9366
+ }
9367
+ return out;
9368
+ }
9369
+ var missingUri = () => syntaxError("MissingField", "uri");
9370
+ function statementThenFields(lines, i) {
9371
+ if (i.v >= lines.length)
9372
+ throw missingUri();
9373
+ if (lines[i.v] !== "")
9374
+ throw syntaxError("ExpectedBlankLine");
9375
+ i.v++;
9376
+ const l = lines[i.v];
9377
+ if (l === undefined)
9378
+ throw missingUri();
9379
+ if (l === "")
9380
+ throw syntaxError("ExpectedBlankLine");
9381
+ if (l.startsWith("URI: "))
9382
+ return;
9383
+ i.v++;
9384
+ const after = lines[i.v];
9385
+ if (after === undefined)
9386
+ throw missingUri();
9387
+ if (after !== "")
9388
+ throw syntaxError("ExpectedBlankLine");
9389
+ i.v++;
9390
+ return l;
9391
+ }
9392
+ function parse2(text) {
9393
+ const byteLength = utf8ByteLength(text);
9394
+ if (byteLength > 16384)
9395
+ throw new SiwxError({
9396
+ code: "MessageTooLarge",
9397
+ length: byteLength,
9398
+ max: MAX_MESSAGE_BYTES
9399
+ });
9400
+ if (text.includes("\r"))
9401
+ throw syntaxError("CarriageReturn");
9402
+ if (text.endsWith(`
9403
+ `))
9404
+ throw syntaxError("UnexpectedTrailing");
9405
+ const lines = text.split(`
9406
+ `);
9407
+ const idx = { v: 0 };
9408
+ const preamble = lines[idx.v++];
9409
+ if (preamble === undefined)
9410
+ throw syntaxError("UnexpectedEof");
9411
+ const mid = preamble.indexOf(MID);
9412
+ if (mid === -1)
9413
+ throw syntaxError("MissingPreamble");
9414
+ const domain = preamble.slice(0, mid);
9415
+ const tail = preamble.slice(mid + MID.length);
9416
+ if (!tail.endsWith(" account:"))
9417
+ throw syntaxError("MissingAccountSuffix");
9418
+ const label = tail.slice(0, tail.length - SUFFIX.length);
9419
+ if (label !== LABEL)
9420
+ throw new SiwxError({
9421
+ code: "Mismatch",
9422
+ field: "label",
9423
+ expected: LABEL,
9424
+ actual: label
9425
+ });
9426
+ const address = lines[idx.v++];
9427
+ if (address === undefined)
9428
+ throw syntaxError("UnexpectedEof");
9429
+ const statement = statementThenFields(lines, idx);
9430
+ const take = (tag, field) => {
9431
+ const line = lines[idx.v];
9432
+ if (line === undefined || !line.startsWith(tag))
9433
+ throw syntaxError("MissingField", field);
9434
+ idx.v++;
9435
+ return line.slice(tag.length);
9436
+ };
9437
+ const uri = take("URI: ", "uri");
9438
+ const version = take("Version: ", "version");
9439
+ const chainId = take("Chain ID: ", "chainId");
9440
+ const nonce = take("Nonce: ", "nonce");
9441
+ const issuedAt = take("Issued At: ", "issuedAt");
9442
+ const tail4 = optionalTags(lines, idx.v);
9443
+ return createMessage({
9444
+ domain,
9445
+ address,
9446
+ ...statement === undefined ? {} : { statement },
9447
+ uri,
9448
+ version,
9449
+ chainId,
9450
+ nonce,
9451
+ issuedAt,
9452
+ ...tail4
9453
+ });
9454
+ }
9455
+ function parseBytes2(bytes) {
9456
+ if (bytes.length > 16384)
9457
+ throw new SiwxError({
9458
+ code: "MessageTooLarge",
9459
+ length: bytes.length,
9460
+ max: MAX_MESSAGE_BYTES
9461
+ });
9462
+ const text = utf8Decode(bytes);
9463
+ if (text === undefined)
9464
+ throw syntaxError("InvalidUtf8");
9465
+ return parse2(text);
9466
+ }
9467
+ var OFFCHAIN_DOMAIN = new Uint8Array([255, ...utf8Encode("solana offchain")]);
9468
+
9469
+ // ../wallet-chains/dist/src-8NZeEnrW.mjs
9470
+ var PREAMBLE = " wants you to sign in with your ";
9471
+ var OPTIONAL_KEYS = [
9472
+ "scheme",
9473
+ "statement",
9474
+ "expirationTime",
9475
+ "notBefore",
9476
+ "requestId"
9477
+ ];
9478
+ var plainFields = (message) => {
9479
+ const { domain, address, uri, version, chainId, nonce, issuedAt, resources } = message;
9480
+ const fields = {
9481
+ domain,
9482
+ address,
9483
+ uri,
9484
+ version,
9485
+ chainId,
9486
+ nonce,
9487
+ issuedAt
8219
9488
  };
9489
+ for (const key of OPTIONAL_KEYS) {
9490
+ const value = message[key];
9491
+ if (value !== undefined)
9492
+ fields[key] = value;
9493
+ }
9494
+ if (resources !== undefined)
9495
+ fields.resources = [...resources];
9496
+ return fields;
8220
9497
  };
8221
- var SATS = "sats";
8222
- var OP_RETURN = 106;
8223
- var bytesToHex4 = (bytes) => {
8224
- let out = "";
8225
- for (const b of bytes)
8226
- out += b.toString(16).padStart(2, "0");
8227
- return out;
9498
+ var parseValid = (text, family) => {
9499
+ if (family === "evm") {
9500
+ const ns = evm();
9501
+ const message = ns.parse(new TextEncoder().encode(text));
9502
+ ns.account(message);
9503
+ return plainFields(message);
9504
+ }
9505
+ const message = siws_exports.parse(text);
9506
+ validateAddress(message.address);
9507
+ return plainFields(message);
8228
9508
  };
8229
- var decodeOutput = (script, amount) => {
8230
- const hex = bytesToHex4(script);
8231
- if (script[0] === OP_RETURN)
9509
+ function parseSignIn(text, family) {
9510
+ try {
8232
9511
  return {
8233
- amount,
8234
- script: hex,
8235
- opReturn: true
9512
+ status: "valid",
9513
+ fields: parseValid(text, family)
8236
9514
  };
9515
+ } catch {
9516
+ return text.includes(PREAMBLE) ? { status: "malformed" } : undefined;
9517
+ }
9518
+ }
9519
+ var ChainError = class extends Error {
9520
+ code;
9521
+ constructor(code, message) {
9522
+ super(message);
9523
+ this.name = "ChainError";
9524
+ this.code = code;
9525
+ }
9526
+ };
9527
+
9528
+ // ../wallet-chains/dist/account-ref-D2rW_qlI.mjs
9529
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9530
+ var isAccountRef = (value) => {
9531
+ if (!isRecord2(value) || typeof value["kind"] !== "string")
9532
+ return false;
9533
+ if (value["kind"] === "hd")
9534
+ return typeof value["walletId"] === "string" && typeof value["groupIndex"] === "number" && typeof value["template"] === "string";
9535
+ return value["kind"] === "imported" && typeof value["keyId"] === "string" && typeof value["family"] === "string";
9536
+ };
9537
+ var requestBase = (request) => {
9538
+ if (!isRecord2(request))
9539
+ throw new ChainError("invalid-request", "request must be an object");
9540
+ const { network, account } = request;
9541
+ if (typeof network !== "string")
9542
+ throw new ChainError("invalid-request", "request.network must be a string");
9543
+ if (!isAccountRef(account))
9544
+ throw new ChainError("invalid-request", "request.account must be an AccountRef");
8237
9545
  return {
8238
- amount,
8239
- script: hex,
8240
- opReturn: false
9546
+ network,
9547
+ account
8241
9548
  };
8242
9549
  };
8243
- var decodeBitcoinPsbt = (request, ownScripts = /* @__PURE__ */ new Set) => {
8244
- const tx = Transaction.fromPSBT(request.psbt);
8245
- const coder = Address(bitcoinNetwork(request.network).params);
8246
- const signed = new Set(request.sign);
8247
- const outflows = [];
8248
- let canFee = true;
8249
- let outSum = 0n;
8250
- for (let i = 0;i < tx.outputsLength; i++) {
8251
- const output = tx.getOutput(i);
8252
- const { script } = output;
8253
- const { amount } = output;
8254
- if (script === undefined || amount === undefined)
8255
- continue;
8256
- const decoded = decodeOutput(script, amount);
8257
- outSum += amount;
8258
- if (decoded.opReturn || ownScripts.has(decoded.script))
8259
- continue;
8260
- let addr;
8261
- try {
8262
- const out = OutScript.decode(script);
8263
- addr = out === undefined ? undefined : coder.encode(out);
8264
- } catch {
8265
- addr = undefined;
8266
- }
8267
- outflows.push({
8268
- to: addr ?? decoded.script,
8269
- amount: {
8270
- asset: SATS,
8271
- amount: amount.toString(10)
8272
- },
8273
- verified: addr !== undefined
8274
- });
9550
+
9551
+ // ../wallet-chains/dist/message-ChhEZ0lx.mjs
9552
+ var MAINNET_BIP32 = {
9553
+ public: 76067358,
9554
+ private: 76066276
9555
+ };
9556
+ var TESTNET_BIP32 = {
9557
+ public: 70617039,
9558
+ private: 70615956
9559
+ };
9560
+ var REGTEST_NETWORK = {
9561
+ ...TEST_NETWORK,
9562
+ bech32: "bcrt"
9563
+ };
9564
+ var NETWORKS = Object.freeze([
9565
+ {
9566
+ caip2: "bip122:000000000019d6689c085ae165831e93",
9567
+ genesis: "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f",
9568
+ params: NETWORK,
9569
+ coinType: 0,
9570
+ bip32: MAINNET_BIP32
9571
+ },
9572
+ {
9573
+ caip2: "bip122:00000000da84f2bafbbc53dee25a72ae",
9574
+ genesis: "00000000da84f2bafbbc53dee25a72ae507ff4914b867c565be350b0da8bf043",
9575
+ params: TEST_NETWORK,
9576
+ coinType: 1,
9577
+ bip32: TESTNET_BIP32
9578
+ },
9579
+ {
9580
+ caip2: "bip122:00000008819873e925422c1ff0f99f7c",
9581
+ genesis: "00000008819873e925422c1ff0f99f7cc9bbb232af63a077a480a3633bee1ef6",
9582
+ params: TEST_NETWORK,
9583
+ coinType: 1,
9584
+ bip32: TESTNET_BIP32
9585
+ },
9586
+ {
9587
+ caip2: "bip122:0f9188f13cb7b2c71f2a335e3a4fc328",
9588
+ genesis: "0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206",
9589
+ params: REGTEST_NETWORK,
9590
+ coinType: 1,
9591
+ bip32: TESTNET_BIP32
8275
9592
  }
8276
- let inSum = 0n;
8277
- for (let i = 0;i < tx.inputsLength; i++) {
8278
- const input = tx.getInput(i);
8279
- if (input.witnessUtxo === undefined)
8280
- canFee = false;
8281
- else
8282
- inSum += input.witnessUtxo.amount;
9593
+ ]);
9594
+ var BITCOIN_NETWORKS = Object.freeze(Object.fromEntries(NETWORKS.map((n) => [n.caip2, n])));
9595
+ var bitcoinNetwork = (caip2) => {
9596
+ const net = BITCOIN_NETWORKS[caip2];
9597
+ if (net === undefined)
9598
+ throw new ChainError("unsupported", `unknown bitcoin network: ${caip2}`);
9599
+ return net;
9600
+ };
9601
+ var utf8 = (s) => new TextEncoder().encode(s);
9602
+ var BIP322_TAG = "BIP0322-signed-message";
9603
+ var LEGACY_MAGIC = utf8(`Bitcoin Signed Message:
9604
+ `);
9605
+ var concat = (...parts) => {
9606
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
9607
+ let o = 0;
9608
+ for (const p of parts) {
9609
+ out.set(p, o);
9610
+ o += p.length;
8283
9611
  }
8284
- const external = tx.inputsLength - signed.size > 0;
8285
- const undecodable = outflows.some((o) => !o.verified);
8286
- const verifiability = external ? "opaque" : undecodable ? "partial" : "full";
8287
- return {
8288
- family: "bitcoin",
8289
- network: request.network,
8290
- summary: outflows.length > 0 ? "transfer" : "contract-call",
8291
- outflows,
8292
- approvals: [],
8293
- fee: canFee ? { max: {
8294
- asset: SATS,
8295
- amount: (inSum - outSum).toString(10)
8296
- } } : undefined,
8297
- warnings: [],
8298
- verifiability
8299
- };
9612
+ return out;
8300
9613
  };
8301
- var common = (request) => {
8302
- const base = requestBase(request);
8303
- bitcoinNetwork(base.network);
8304
- return base;
9614
+ var varint = (n) => Uint8Array.of(n);
9615
+ var COMPACT_SIZE_ONE_BYTE_MAX = 252;
9616
+ var pushData = (data) => {
9617
+ if (data.length > COMPACT_SIZE_ONE_BYTE_MAX)
9618
+ throw new ChainError("invalid-request", "BIP-322 script data exceeds 252 bytes");
9619
+ return concat(varint(data.length), data);
8305
9620
  };
8306
- var messageTarget = (address, network, format) => {
8307
- if (typeof address !== "string")
8308
- throw new ChainError("invalid-request", "address must be a string");
8309
- const net = bitcoinNetwork(network);
8310
- let decoded;
8311
- try {
8312
- decoded = Address(net.params).decode(address);
8313
- } catch {
8314
- throw new ChainError("invalid-address", "address does not belong to this network");
9621
+ var u32le = (n) => Uint8Array.of(n % 256, Math.floor(n / 256) % 256, Math.floor(n / 65536) % 256, Math.floor(n / 16777216) % 256);
9622
+ var u64le = (n) => {
9623
+ const out = /* @__PURE__ */ new Uint8Array(8);
9624
+ let v = n;
9625
+ for (let i = 0;i < 8; i++) {
9626
+ out[i] = Number(v % 256n);
9627
+ v /= 256n;
8315
9628
  }
8316
- if (format === "bip322-simple") {
8317
- if (decoded.type !== "wpkh" && decoded.type !== "tr")
8318
- throw new ChainError("unsupported", "bip322-simple is only for P2WPKH/P2TR addresses");
8319
- } else if (format === "legacy") {
8320
- if (decoded.type !== "pkh")
8321
- throw new ChainError("unsupported", "legacy signing is only for P2PKH addresses");
8322
- } else
8323
- throw new ChainError("unsupported", `unsupported message format: ${String(format)}`);
8324
- const scriptPubKey = OutScript.encode(decoded);
9629
+ return out;
9630
+ };
9631
+ var bip322MessageHash = (message) => {
9632
+ const tag = sha256(utf8(BIP322_TAG));
9633
+ return sha256(concat(tag, tag, utf8(message)));
9634
+ };
9635
+ var toSpend = (scriptPubKey, messageHash) => {
9636
+ const scriptSig = concat(Uint8Array.of(0), pushData(messageHash));
9637
+ const raw = concat(u32le(0), varint(1), /* @__PURE__ */ new Uint8Array(32), u32le(4294967295), pushData(scriptSig), u32le(0), varint(1), u64le(0n), pushData(scriptPubKey), u32le(0));
8325
9638
  return {
8326
- type: decoded.type,
8327
- address,
8328
- format,
8329
- scriptPubKey
9639
+ txid: sha256(sha256(raw)),
9640
+ raw
8330
9641
  };
8331
9642
  };
8332
- var normalizeBitcoin = (request) => {
8333
- if (!isRecord2(request) || typeof request["kind"] !== "string")
8334
- throw new ChainError("invalid-request", "request must be an object with a kind");
8335
- const { network, account } = common(request);
8336
- if (request["kind"] === "bitcoin.psbt") {
8337
- const { psbt } = request;
8338
- if (!(psbt instanceof Uint8Array))
8339
- throw new ChainError("invalid-request", "psbt must be bytes");
8340
- const normalized = normalizeBitcoinPsbt(psbt, request["sign"], network);
8341
- return {
8342
- kind: "bitcoin.psbt",
8343
- network,
8344
- account,
8345
- psbt: normalized.psbt,
8346
- sign: normalized.sign
8347
- };
8348
- }
8349
- if (request["kind"] === "bitcoin.message") {
8350
- const { format } = request;
8351
- const target = messageTarget(request["address"], network, format);
8352
- const { message, change, index } = request;
8353
- if (typeof message !== "string")
8354
- throw new ChainError("invalid-request", "message must be a string");
8355
- if (change !== 0 && change !== 1)
8356
- throw new ChainError("invalid-request", "change must be 0 or 1");
8357
- if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0 || index >= 2147483648)
8358
- throw new ChainError("invalid-request", "index must be a non-hardened path index");
8359
- return {
8360
- kind: "bitcoin.message",
8361
- network,
8362
- account,
8363
- address: target.address,
8364
- message,
8365
- format: target.format,
8366
- change,
8367
- index
8368
- };
9643
+ var BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
9644
+ var b642 = (i) => BASE64[i] ?? "";
9645
+ var base642 = (bytes) => {
9646
+ const c = b642;
9647
+ let out = "";
9648
+ for (let i = 0;i < bytes.length; i += 3) {
9649
+ const b0 = bytes[i] ?? 0;
9650
+ const b1 = bytes[i + 1] ?? 0;
9651
+ const b2 = bytes[i + 2] ?? 0;
9652
+ out += c(Math.floor(b0 / 4)) + c(b0 % 4 * 16 + Math.floor(b1 / 16));
9653
+ out += i + 1 < bytes.length ? c(b1 % 16 * 4 + Math.floor(b2 / 64)) : "=";
9654
+ out += i + 2 < bytes.length ? c(b2 % 64) : "=";
8369
9655
  }
8370
- throw new ChainError("unsupported", `unsupported sign request kind: ${request["kind"]}`);
9656
+ return out;
9657
+ };
9658
+ var signBip322Simple = (message, scriptPubKey, privateKey, auxRand) => {
9659
+ const hash = bip322MessageHash(message);
9660
+ const { txid } = toSpend(scriptPubKey, hash);
9661
+ const tx = new Transaction({
9662
+ version: 0,
9663
+ lockTime: 0,
9664
+ allowUnknownOutputs: true
9665
+ });
9666
+ const pub = secp256k1.getPublicKey(privateKey, true);
9667
+ tx.addInput({
9668
+ txid,
9669
+ index: 0,
9670
+ sequence: 0,
9671
+ witnessUtxo: {
9672
+ script: scriptPubKey,
9673
+ amount: 0n
9674
+ },
9675
+ bip32Derivation: [[pub, {
9676
+ fingerprint: 0,
9677
+ path: []
9678
+ }]],
9679
+ ...scriptPubKey[0] === 81 ? { tapInternalKey: pub.slice(1) } : {}
9680
+ });
9681
+ tx.addOutput({
9682
+ script: Uint8Array.of(106),
9683
+ amount: 0n
9684
+ });
9685
+ const isTaproot = scriptPubKey[0] === 81;
9686
+ if (!tx.signIdx(privateKey, 0, isTaproot ? [SigHash.DEFAULT, SigHash.ALL] : [SigHash.ALL], auxRand(0)))
9687
+ throw new ChainError("invalid-request", "key cannot sign this BIP-322 input");
9688
+ tx.finalizeIdx(0);
9689
+ const witness = tx.getInput(0).finalScriptWitness;
9690
+ if (witness === undefined)
9691
+ throw new ChainError("invalid-request", "BIP-322 input produced no witness");
9692
+ const raw = concat(varint(witness.length), ...witness.map(pushData));
9693
+ return `smp${base642(raw)}`;
9694
+ };
9695
+ var signLegacyMessage = (message, privateKey) => {
9696
+ const data = concat(pushData(LEGACY_MAGIC), pushData(utf8(message)));
9697
+ const hash = sha256(sha256(data));
9698
+ const recovered = secp256k1.sign(hash, privateKey, {
9699
+ lowS: true,
9700
+ format: "recovered"
9701
+ });
9702
+ const header = 27 + (recovered[0] ?? 0) + 4;
9703
+ return base642(concat(Uint8Array.of(header), recovered.slice(1)));
8371
9704
  };
8372
- var decodeMessageTarget = (request) => messageTarget(request.address, request.network, request.format);
8373
9705
 
8374
- // ../../node_modules/.bun/@noble+hashes@2.4.0/node_modules/@noble/hashes/sha3.js
8375
- var _0n4 = BigInt(0);
8376
- var _1n4 = BigInt(1);
8377
- var _2n4 = BigInt(2);
8378
- var _7n = BigInt(7);
8379
- var _256n = BigInt(256);
8380
- var _0x71n = BigInt(113);
8381
- var SHA3_PI = [];
8382
- var SHA3_ROTL = [];
8383
- var _SHA3_IOTA = [];
8384
- for (let round = 0, R = _1n4, x = 1, y = 0;round < 24; round++) {
8385
- [x, y] = [y, (2 * x + 3 * y) % 5];
8386
- SHA3_PI.push(2 * (5 * y + x));
8387
- SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
8388
- let t = _0n4;
8389
- for (let j = 0;j < 7; j++) {
8390
- R = (R << _1n4 ^ (R >> _7n) * _0x71n) % _256n;
8391
- if (R & _2n4)
8392
- t ^= _1n4 << (_1n4 << BigInt(j)) - _1n4;
8393
- }
8394
- _SHA3_IOTA.push(t);
8395
- }
8396
- var IOTAS = split(_SHA3_IOTA, true);
8397
- var SHA3_IOTA_H = IOTAS[0];
8398
- var SHA3_IOTA_L = IOTAS[1];
8399
- var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
8400
- var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
8401
- var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
8402
- var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
8403
- var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
8404
- var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
8405
- var B = new Uint32Array(5 * 2);
8406
- function keccakP(s, rounds = 24) {
8407
- if (!(s instanceof Uint32Array))
8408
- throw new TypeError('"s" expected Uint32Array(50), got type=' + typeof s);
8409
- if (s.length !== 50)
8410
- throw new RangeError('"s" expected Uint32Array(50), got length=' + s.length);
8411
- anumber(rounds, "rounds");
8412
- if (rounds < 1 || rounds > 24)
8413
- throw new Error('"rounds" expected integer 1..24');
8414
- for (let round = 24 - rounds;round < 24; round++) {
8415
- for (let x = 0;x < 10; x++)
8416
- B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
8417
- for (let x = 0;x < 10; x += 2) {
8418
- const idx1 = (x + 8) % 10;
8419
- const idx0 = (x + 2) % 10;
8420
- const B0 = B[idx0];
8421
- const B1 = B[idx0 + 1];
8422
- const Th = rotlH(B0, B1, 1) ^ B[idx1];
8423
- const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
8424
- for (let y = 0;y < 50; y += 10) {
8425
- s[x + y] ^= Th;
8426
- s[x + y + 1] ^= Tl;
8427
- }
8428
- }
8429
- let curH = s[2];
8430
- let curL = s[3];
8431
- for (let t = 0;t < 24; t++) {
8432
- const shift = SHA3_ROTL[t];
8433
- const Th = rotlH(curH, curL, shift);
8434
- const Tl = rotlL(curH, curL, shift);
8435
- const PI = SHA3_PI[t];
8436
- curH = s[PI];
8437
- curL = s[PI + 1];
8438
- s[PI] = Th;
8439
- s[PI + 1] = Tl;
8440
- }
8441
- for (let y = 0;y < 50; y += 10) {
8442
- const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3];
8443
- s[y] ^= ~s[y + 2] & s[y + 4];
8444
- s[y + 1] ^= ~s[y + 3] & s[y + 5];
8445
- s[y + 2] ^= ~s[y + 4] & s[y + 6];
8446
- s[y + 3] ^= ~s[y + 5] & s[y + 7];
8447
- s[y + 4] ^= ~s[y + 6] & s[y + 8];
8448
- s[y + 5] ^= ~s[y + 7] & s[y + 9];
8449
- s[y + 6] ^= ~s[y + 8] & b0;
8450
- s[y + 7] ^= ~s[y + 9] & b1;
8451
- s[y + 8] ^= ~b0 & b2;
8452
- s[y + 9] ^= ~b1 & b3;
8453
- }
8454
- s[0] ^= SHA3_IOTA_H[round];
8455
- s[1] ^= SHA3_IOTA_L[round];
9706
+ // ../wallet-chains/dist/bitcoin.mjs
9707
+ var isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9708
+ var derivationPaths = (map) => {
9709
+ const entries = map instanceof Map ? [...map.values()] : Array.isArray(map) ? map : isRecord$1(map) ? Object.values(map) : [];
9710
+ const paths = [];
9711
+ for (const entry of entries) {
9712
+ const value = Array.isArray(entry) ? entry[1] : entry;
9713
+ if (!isRecord$1(value))
9714
+ continue;
9715
+ const { path } = isRecord$1(value["der"]) ? value["der"] : value;
9716
+ if (Array.isArray(path) && path.every((p) => typeof p === "number"))
9717
+ paths.push(path);
8456
9718
  }
8457
- clean(B);
8458
- }
8459
-
8460
- class Keccak {
8461
- state;
8462
- pos = 0;
8463
- posOut = 0;
8464
- finished = false;
8465
- state32;
8466
- destroyed = false;
8467
- blockLen;
8468
- suffix;
8469
- outputLen;
8470
- canXOF;
8471
- enableXOF = false;
8472
- rounds;
8473
- constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
8474
- anumber(blockLen, "blockLen");
8475
- anumber(suffix, "suffix");
8476
- anumber(rounds, "rounds");
8477
- abool(enableXOF, "enableXOF");
8478
- this.blockLen = blockLen;
8479
- this.suffix = suffix;
8480
- this.outputLen = outputLen;
8481
- this.enableXOF = enableXOF;
8482
- this.canXOF = enableXOF;
8483
- this.rounds = rounds;
8484
- anumber(outputLen, "outputLen");
8485
- if (!(0 < blockLen && blockLen < 200))
8486
- throw new Error('"blockLen" must be 1..199');
8487
- this.state = new Uint8Array(200);
8488
- this.state32 = u32(this.state);
9719
+ return paths;
9720
+ };
9721
+ var checkPaths = (paths, where, coinType) => {
9722
+ for (const path of paths)
9723
+ if (path.length >= 2 && (path[1] ?? -1) - 2147483648 !== coinType)
9724
+ throw new ChainError("chain-id-mismatch", `${where} derivation coin type is not this network's`);
9725
+ };
9726
+ var checkDerivations = (tx, coinType) => {
9727
+ for (let i = 0;i < tx.inputsLength; i++) {
9728
+ const input = tx.getInput(i);
9729
+ checkPaths(derivationPaths(input.bip32Derivation), `input ${i}`, coinType);
9730
+ checkPaths(derivationPaths(input.tapBip32Derivation), `input ${i}`, coinType);
8489
9731
  }
8490
- clone() {
8491
- return this._cloneInto();
9732
+ for (let i = 0;i < tx.outputsLength; i++) {
9733
+ const output = tx.getOutput(i);
9734
+ checkPaths(derivationPaths(output.bip32Derivation), `output ${i}`, coinType);
9735
+ checkPaths(derivationPaths(output.tapBip32Derivation), `output ${i}`, coinType);
8492
9736
  }
8493
- keccak() {
8494
- swap32IfBE(this.state32);
8495
- keccakP(this.state32, this.rounds);
8496
- swap32IfBE(this.state32);
8497
- this.posOut = 0;
8498
- this.pos = 0;
9737
+ };
9738
+ var DEFAULT_SIGHASH = 0;
9739
+ var SIGHASH_ALL = 1;
9740
+ var isTaprootInput = (input) => input.tapInternalKey !== undefined || getInputType(input).type === "taproot";
9741
+ var normalizeBitcoinPsbt = (psbt, sign, network) => {
9742
+ const net = bitcoinNetwork(network);
9743
+ let tx;
9744
+ try {
9745
+ tx = Transaction.fromPSBT(psbt, { strictPrevoutValidation: true });
9746
+ } catch {
9747
+ throw new ChainError("invalid-request", "PSBT failed to decode");
8499
9748
  }
8500
- update(data) {
8501
- aexists(this);
8502
- abytes(data);
8503
- const { blockLen, state, state32 } = this;
8504
- const len = data.length;
8505
- const canUseU32 = blockLen % 4 === 0 && data.byteOffset % 4 === 0;
8506
- const blockLen32 = blockLen / 4;
8507
- const data32 = canUseU32 && len >= blockLen ? u32(data) : undefined;
8508
- for (let pos = 0;pos < len; ) {
8509
- if (data32 !== undefined && this.pos === 0 && pos % 4 === 0 && len - pos >= blockLen) {
8510
- for (let i = 0, o = pos / 4;i < blockLen32; i++)
8511
- state32[i] ^= data32[o + i];
8512
- pos += blockLen;
8513
- this.pos = blockLen;
8514
- this.keccak();
8515
- continue;
8516
- }
8517
- const take = Math.min(blockLen - this.pos, len - pos);
8518
- for (let i = 0;i < take; i++)
8519
- state[this.pos++] ^= data[pos++];
8520
- if (this.pos === blockLen)
8521
- this.keccak();
8522
- }
8523
- return this;
9749
+ if (!Array.isArray(sign) || sign.length === 0 || !sign.every((i) => Number.isSafeInteger(i) && i >= 0))
9750
+ throw new ChainError("invalid-request", "sign must be a non-empty array of input indices");
9751
+ const unique = [...new Set(sign.map(Number))].sort((a, b) => a - b);
9752
+ const last = unique.at(-1);
9753
+ if (unique.length !== sign.length || last === undefined || last >= tx.inputsLength)
9754
+ throw new ChainError("invalid-request", "sign must be unique, ascending, and in range");
9755
+ checkDerivations(tx, net.coinType);
9756
+ for (const idx of unique) {
9757
+ const input = tx.getInput(idx);
9758
+ if (input.witnessUtxo === undefined && input.nonWitnessUtxo === undefined)
9759
+ throw new ChainError("invalid-request", `input ${idx} carries neither witnessUtxo nor nonWitnessUtxo`);
9760
+ if (input.bip32Derivation === undefined && input.tapBip32Derivation === undefined)
9761
+ throw new ChainError("invalid-request", `input ${idx} is missing a bip32 derivation`);
9762
+ const { type } = getInputType(input);
9763
+ if ((type === "legacy" || type === "nonwitness-script") && input.nonWitnessUtxo === undefined)
9764
+ throw new ChainError("invalid-request", `input ${idx} is missing nonWitnessUtxo`);
9765
+ const sighash = input.sighashType;
9766
+ if (!(sighash === undefined || sighash === SIGHASH_ALL || isTaprootInput(input) && sighash === DEFAULT_SIGHASH || sighash === 131))
9767
+ throw new ChainError("unsupported", `input ${idx} uses a non-default sighash`);
9768
+ if (sighash === 131 && idx >= tx.outputsLength)
9769
+ throw new ChainError("unsupported", `input ${idx} uses SIGHASH_SINGLE without a same-index output`);
8524
9770
  }
8525
- finish() {
8526
- if (this.finished)
8527
- return;
8528
- this.finished = true;
8529
- const { state, suffix, pos, blockLen } = this;
8530
- state[pos] ^= suffix;
8531
- if ((suffix & 128) !== 0 && pos === blockLen - 1)
8532
- this.keccak();
8533
- state[blockLen - 1] ^= 128;
8534
- this.keccak();
9771
+ return {
9772
+ psbt: tx.toPSBT(0),
9773
+ sign: unique
9774
+ };
9775
+ };
9776
+ var SATS = "sats";
9777
+ var SIGHASH_SINGLE_ANYONECANPAY = 131;
9778
+ var OP_RETURN = 106;
9779
+ var parsePsbt = (psbt) => {
9780
+ try {
9781
+ return Transaction.fromPSBT(psbt);
9782
+ } catch (error) {
9783
+ throw error instanceof ChainError ? error : new ChainError("invalid-request", "malformed PSBT");
8535
9784
  }
8536
- writeInto(out) {
8537
- aexists(this, false);
8538
- abytes(out);
8539
- this.finish();
8540
- const bufferOut = this.state;
8541
- const { blockLen } = this;
8542
- for (let pos = 0, len = out.length;pos < len; ) {
8543
- if (this.posOut >= blockLen)
8544
- this.keccak();
8545
- const take = Math.min(blockLen - this.posOut, len - pos);
8546
- out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
8547
- this.posOut += take;
8548
- pos += take;
9785
+ };
9786
+ var bytesToHex4 = (bytes) => {
9787
+ let out = "";
9788
+ for (const b of bytes)
9789
+ out += b.toString(16).padStart(2, "0");
9790
+ return out;
9791
+ };
9792
+ var decodeOutput = (script, amount) => {
9793
+ const hex = bytesToHex4(script);
9794
+ if (script[0] === OP_RETURN)
9795
+ return {
9796
+ amount,
9797
+ script: hex,
9798
+ opReturn: true
9799
+ };
9800
+ return {
9801
+ amount,
9802
+ script: hex,
9803
+ opReturn: false
9804
+ };
9805
+ };
9806
+ var decodeBitcoinPsbt = (request, ownScripts = /* @__PURE__ */ new Set) => {
9807
+ const tx = parsePsbt(request.psbt);
9808
+ const coder = Address(bitcoinNetwork(request.network).params);
9809
+ const signed = new Set(request.sign);
9810
+ const outflows = [];
9811
+ let canFee = true;
9812
+ let outSum = 0n;
9813
+ for (let i = 0;i < tx.outputsLength; i++) {
9814
+ const output = tx.getOutput(i);
9815
+ const { script } = output;
9816
+ const { amount } = output;
9817
+ if (script === undefined || amount === undefined)
9818
+ continue;
9819
+ const decoded = decodeOutput(script, amount);
9820
+ outSum += amount;
9821
+ if (decoded.opReturn || ownScripts.has(decoded.script))
9822
+ continue;
9823
+ let addr;
9824
+ try {
9825
+ const out = OutScript.decode(script);
9826
+ addr = out === undefined ? undefined : coder.encode(out);
9827
+ } catch {
9828
+ addr = undefined;
8549
9829
  }
8550
- return out;
8551
- }
8552
- xofInto(out) {
8553
- if (!this.enableXOF)
8554
- throw new Error("XOF is not enabled");
8555
- return this.writeInto(out);
8556
- }
8557
- xof(bytes) {
8558
- anumber(bytes);
8559
- return this.xofInto(new Uint8Array(bytes));
9830
+ outflows.push({
9831
+ to: addr ?? decoded.script,
9832
+ amount: {
9833
+ asset: SATS,
9834
+ amount: amount.toString(10)
9835
+ },
9836
+ verified: addr !== undefined
9837
+ });
8560
9838
  }
8561
- digestInto(out) {
8562
- aoutput(out, this);
8563
- if (this.finished)
8564
- throw new Error("digest() was already called");
8565
- this.writeInto(out.length === this.outputLen ? out : out.subarray(0, this.outputLen));
8566
- this.destroy();
9839
+ let inSum = 0n;
9840
+ for (let i = 0;i < tx.inputsLength; i++) {
9841
+ const input = tx.getInput(i);
9842
+ if (input.witnessUtxo === undefined)
9843
+ canFee = false;
9844
+ else
9845
+ inSum += input.witnessUtxo.amount;
8567
9846
  }
8568
- digest() {
8569
- const out = new Uint8Array(this.outputLen);
8570
- this.digestInto(out);
8571
- return out;
9847
+ const external = tx.inputsLength - signed.size > 0;
9848
+ const undecodable = outflows.some((o) => !o.verified);
9849
+ const listing = request.sign.some((i) => tx.getInput(i).sighashType === SIGHASH_SINGLE_ANYONECANPAY);
9850
+ const verifiability = external ? "opaque" : listing || undecodable ? "partial" : "full";
9851
+ return {
9852
+ family: "bitcoin",
9853
+ network: request.network,
9854
+ summary: outflows.length > 0 ? "transfer" : "contract-call",
9855
+ outflows,
9856
+ approvals: [],
9857
+ fee: canFee && !listing ? { max: {
9858
+ asset: SATS,
9859
+ amount: (inSum - outSum).toString(10)
9860
+ } } : undefined,
9861
+ warnings: listing ? [{
9862
+ kind: "sighash-single-anyonecanpay",
9863
+ message: "signed inputs bind only their same-index outputs; the rest of the transaction can change"
9864
+ }] : [],
9865
+ verifiability
9866
+ };
9867
+ };
9868
+ var common = (request) => {
9869
+ const base = requestBase(request);
9870
+ bitcoinNetwork(base.network);
9871
+ return base;
9872
+ };
9873
+ var messageTarget = (address, network, format) => {
9874
+ if (typeof address !== "string")
9875
+ throw new ChainError("invalid-request", "address must be a string");
9876
+ const net = bitcoinNetwork(network);
9877
+ let decoded;
9878
+ try {
9879
+ decoded = Address(net.params).decode(address);
9880
+ } catch {
9881
+ throw new ChainError("invalid-address", "address does not belong to this network");
8572
9882
  }
8573
- destroy() {
8574
- this.destroyed = true;
8575
- clean(this.state);
9883
+ if (format === "bip322-simple") {
9884
+ if (decoded.type !== "wpkh" && decoded.type !== "tr")
9885
+ throw new ChainError("unsupported", "bip322-simple is only for P2WPKH/P2TR addresses");
9886
+ } else if (format === "legacy") {
9887
+ if (decoded.type !== "pkh")
9888
+ throw new ChainError("unsupported", "legacy signing is only for P2PKH addresses");
9889
+ } else
9890
+ throw new ChainError("unsupported", `unsupported message format: ${String(format)}`);
9891
+ const scriptPubKey = OutScript.encode(decoded);
9892
+ return {
9893
+ type: decoded.type,
9894
+ address,
9895
+ format,
9896
+ scriptPubKey
9897
+ };
9898
+ };
9899
+ var normalizeBitcoin = (request) => {
9900
+ if (!isRecord2(request) || typeof request["kind"] !== "string")
9901
+ throw new ChainError("invalid-request", "request must be an object with a kind");
9902
+ const { network, account } = common(request);
9903
+ if (request["kind"] === "bitcoin.psbt") {
9904
+ const { psbt } = request;
9905
+ if (!(psbt instanceof Uint8Array))
9906
+ throw new ChainError("invalid-request", "psbt must be bytes");
9907
+ const normalized = normalizeBitcoinPsbt(psbt, request["sign"], network);
9908
+ return {
9909
+ kind: "bitcoin.psbt",
9910
+ network,
9911
+ account,
9912
+ psbt: normalized.psbt,
9913
+ sign: normalized.sign
9914
+ };
8576
9915
  }
8577
- _cloneInto(to) {
8578
- const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
8579
- to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);
8580
- to.blockLen = blockLen;
8581
- to.state32.set(this.state32);
8582
- to.pos = this.pos;
8583
- to.posOut = this.posOut;
8584
- to.finished = this.finished;
8585
- to.rounds = rounds;
8586
- to.suffix = suffix;
8587
- to.outputLen = outputLen;
8588
- to.enableXOF = enableXOF;
8589
- to.canXOF = this.canXOF;
8590
- to.destroyed = this.destroyed;
8591
- return to;
9916
+ if (request["kind"] === "bitcoin.message") {
9917
+ const { format } = request;
9918
+ const target = messageTarget(request["address"], network, format);
9919
+ const { message, change, index } = request;
9920
+ if (typeof message !== "string")
9921
+ throw new ChainError("invalid-request", "message must be a string");
9922
+ if (change !== 0 && change !== 1)
9923
+ throw new ChainError("invalid-request", "change must be 0 or 1");
9924
+ if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0 || index >= 2147483648)
9925
+ throw new ChainError("invalid-request", "index must be a non-hardened path index");
9926
+ return {
9927
+ kind: "bitcoin.message",
9928
+ network,
9929
+ account,
9930
+ address: target.address,
9931
+ message,
9932
+ format: target.format,
9933
+ change,
9934
+ index
9935
+ };
8592
9936
  }
8593
- }
8594
- var genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);
8595
- var keccak_256 = /* @__PURE__ */ genKeccak(1, 136, 32);
9937
+ throw new ChainError("unsupported", `unsupported sign request kind: ${request["kind"]}`);
9938
+ };
9939
+ var decodeMessageTarget = (request) => messageTarget(request.address, request.network, request.format);
8596
9940
 
8597
9941
  // ../../node_modules/.bun/ox@1.8.12+ff0372d108591aba/node_modules/ox/dist/core/version.js
8598
9942
  var version = "0.1.1";
@@ -8897,7 +10241,7 @@ class IntegerOutOfRangeError extends BaseError {
8897
10241
  }
8898
10242
 
8899
10243
  // ../../node_modules/.bun/ox@1.8.12+ff0372d108591aba/node_modules/ox/dist/core/internal/codec/utf8.js
8900
- var encoder = /* @__PURE__ */ new TextEncoder;
10244
+ var encoder2 = /* @__PURE__ */ new TextEncoder;
8901
10245
  var decoder = /* @__PURE__ */ new TextDecoder;
8902
10246
 
8903
10247
  // ../../node_modules/.bun/ox@1.8.12+ff0372d108591aba/node_modules/ox/dist/core/Json.js
@@ -9005,7 +10349,7 @@ function fromNumber(value, options = {}) {
9005
10349
  return hex;
9006
10350
  }
9007
10351
  function fromString(value, options = {}) {
9008
- return fromBytes(encoder.encode(value), options);
10352
+ return fromBytes(encoder2.encode(value), options);
9009
10353
  }
9010
10354
  function padLeft(value, size) {
9011
10355
  return pad3(value, { dir: "left", size });
@@ -9171,7 +10515,7 @@ function fromHex(value, options = {}) {
9171
10515
  }
9172
10516
  function fromString2(value, options = {}) {
9173
10517
  const { size } = options;
9174
- const bytes = encoder.encode(value);
10518
+ const bytes = encoder2.encode(value);
9175
10519
  if (typeof size === "number") {
9176
10520
  assertSize(bytes, size);
9177
10521
  return padRight2(bytes, size);
@@ -10591,7 +11935,7 @@ function writeParameter(context, offset, parameter, value) {
10591
11935
  const value_ = normalizeString(value);
10592
11936
  const size = getUtf8Size(value_);
10593
11937
  writeWord(context, offset, size);
10594
- const { written } = encoder.encodeInto(value_, context.bytes.subarray(offset + 32, offset + 32 + size));
11938
+ const { written } = encoder2.encodeInto(value_, context.bytes.subarray(offset + 32, offset + 32 + size));
10595
11939
  if (written !== size)
10596
11940
  throw new Error("Failed to encode string.");
10597
11941
  return offset + 32 + Math.ceil(size / 32) * 32;
@@ -11321,7 +12665,7 @@ function validateReference(type) {
11321
12665
  throw new InvalidStructTypeError({ type });
11322
12666
  }
11323
12667
 
11324
- // ../wallet-chains/dist/typed-data-Cf1g7JVv.mjs
12668
+ // ../wallet-chains/dist/typed-data-J5g2WemC.mjs
11325
12669
  var isEvmAddress = (value) => /^0x[0-9a-fA-F]{40}$/.test(value);
11326
12670
  function checksumEvmAddress(address) {
11327
12671
  if (!isEvmAddress(address))
@@ -11343,6 +12687,11 @@ function assertHex(value, field) {
11343
12687
  var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
11344
12688
  var CANONICAL_HEX = /^0x(?:0|[1-9a-f][0-9a-f]*)$/;
11345
12689
  var canonicalHex = (value) => `0x${value.toString(16)}`;
12690
+ var quantityBigInt = (value, field) => {
12691
+ if (typeof value !== "string" || !/^0x[0-9a-fA-F]+$/.test(value))
12692
+ throw new ChainError("invalid-quantity", `${field} must be a 0x quantity`);
12693
+ return BigInt(value);
12694
+ };
11346
12695
  var safeInteger = (value, field) => {
11347
12696
  if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0)
11348
12697
  throw new ChainError("invalid-quantity", `${field} must be a non-negative safe integer`);
@@ -11353,9 +12702,7 @@ var quantity = (value, field) => {
11353
12702
  throw new ChainError("invalid-quantity", `${field} must be a 0x quantity string`);
11354
12703
  if (CANONICAL_HEX.test(value))
11355
12704
  return value;
11356
- if (/^0x[0-9a-fA-F]+$/.test(value) || value === "0x")
11357
- return canonicalHex(BigInt(value === "0x" ? "0x0" : value));
11358
- throw new ChainError("invalid-quantity", `${field} must be a 0x quantity`);
12705
+ return canonicalHex(quantityBigInt(value, field));
11359
12706
  };
11360
12707
  var hexBytes = (value, field) => {
11361
12708
  if (typeof value !== "string" || !/^0x(?:[0-9a-fA-F]{2})*$/.test(value))
@@ -11502,7 +12849,25 @@ var isTypedDataInput = (value) => {
11502
12849
  return false;
11503
12850
  return Object.values(types).every((fields) => Array.isArray(fields) && fields.every(isField));
11504
12851
  };
11505
- var parseTypedData = (typedData, network) => {
12852
+ var isTypedDataMessage = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12853
+ var typedDataMessages = (value) => Array.isArray(value) && value.every(isTypedDataMessage) ? value : undefined;
12854
+ var typedDataSignature = (types, name) => types[name]?.map((field) => `${field.type} ${field.name}`).join(",");
12855
+ var sameFields = (types, name, fields) => typedDataSignature(types, name) === fields.join(",");
12856
+ var typedDataAddress = (value) => typeof value === "string" && /^0x[0-9a-fA-F]{40}$/.test(value) ? checksumEvmAddress(value) : undefined;
12857
+ var typedDataUint = (value, max) => {
12858
+ let parsed;
12859
+ if (typeof value === "number" && Number.isSafeInteger(value))
12860
+ parsed = BigInt(value);
12861
+ else if (typeof value === "string" && /^(?:[0-9]+|0x[0-9a-fA-F]+)$/.test(value))
12862
+ parsed = BigInt(value);
12863
+ else
12864
+ return;
12865
+ return parsed >= 0n && parsed <= max ? parsed : undefined;
12866
+ };
12867
+ var MAX_UINT48 = 2n ** 48n - 1n;
12868
+ var isHexBytes = (value) => typeof value === "string" && /^0x[0-9a-fA-F]*$/.test(value);
12869
+ var typedDataBytes = (value) => isHexBytes(value) ? value : undefined;
12870
+ var parseTypedData = (typedData) => {
11506
12871
  let json;
11507
12872
  try {
11508
12873
  json = JSON.parse(typedData);
@@ -11516,17 +12881,17 @@ var parseTypedData = (typedData, network) => {
11516
12881
  } catch {
11517
12882
  throw new ChainError("invalid-typed-data", "typedData failed EIP-712 validation");
11518
12883
  }
11519
- const { chainId } = json.domain;
11520
- const numeric = typeof chainId === "number" ? chainId : typeof chainId === "string" ? Number(chainId) : NaN;
11521
- return {
11522
- json,
11523
- chainIdMismatch: Number.isSafeInteger(numeric) && numeric !== networkChainId(network)
11524
- };
12884
+ return { json };
12885
+ };
12886
+ var domainChainId = (domain) => {
12887
+ const { chainId } = domain;
12888
+ if (chainId === undefined)
12889
+ return;
12890
+ const numeric = typeof chainId === "number" ? chainId : typeof chainId === "string" && /^(?:[0-9]+|0x[0-9a-fA-F]+)$/.test(chainId) ? Number(chainId) : NaN;
12891
+ if (!Number.isSafeInteger(numeric) || numeric < 0)
12892
+ throw new ChainError("invalid-typed-data", "typed-data domain.chainId is malformed");
12893
+ return numeric;
11525
12894
  };
11526
- var typedDataWarnings = (parsed) => parsed.chainIdMismatch ? [{
11527
- kind: "chain-id-mismatch",
11528
- message: "typed-data domain.chainId does not match the request network"
11529
- }] : [];
11530
12895
 
11531
12896
  // ../../node_modules/.bun/ox@1.8.12+ff0372d108591aba/node_modules/ox/dist/core/internal/human-readable/formatAbiItem.js
11532
12897
  function formatAbiItem(abiItem) {
@@ -12568,7 +13933,7 @@ var exponents = {
12568
13933
  finney: 15,
12569
13934
  ether: 18
12570
13935
  };
12571
- function format(value, decimals = 0) {
13936
+ function format3(value, decimals = 0) {
12572
13937
  if (!Number.isInteger(decimals) || decimals < 0)
12573
13938
  throw new InvalidDecimalsError({ decimals });
12574
13939
  let display = value.toString();
@@ -12584,7 +13949,7 @@ function format(value, decimals = 0) {
12584
13949
  return `${negative ? "-" : ""}${integer || "0"}${fraction ? `.${fraction}` : ""}`;
12585
13950
  }
12586
13951
  function formatGwei(wei, unit = "wei") {
12587
- return format(wei, exponents.gwei - exponents[unit]);
13952
+ return format3(wei, exponents.gwei - exponents[unit]);
12588
13953
  }
12589
13954
  class InvalidDecimalsError extends BaseError {
12590
13955
  name = "Value.InvalidDecimalsError";
@@ -12676,6 +14041,7 @@ function serialize3(envelope, options = {}) {
12676
14041
  }
12677
14042
 
12678
14043
  // ../wallet-chains/dist/evm.mjs
14044
+ var EVM_NATIVE_ASSET = "native";
12679
14045
  var USDC = Object.freeze({
12680
14046
  symbol: "USDC",
12681
14047
  decimals: 6,
@@ -12702,14 +14068,364 @@ var evmTokenTable = Object.freeze({
12702
14068
  })
12703
14069
  });
12704
14070
  var lookupEvmToken = (table, chainId, address) => table[String(chainId)]?.[address];
14071
+ var MAX_UINT256 = 2n ** 256n - 1n;
14072
+ var MAX_UINT160 = 2n ** 160n - 1n;
14073
+ var allowanceChange = (token, spender, value, change, max, chainId, table, extra = {}) => {
14074
+ const known = lookupEvmToken(table, chainId, token);
14075
+ return {
14076
+ kind: "allowance",
14077
+ spender,
14078
+ amount: {
14079
+ asset: token,
14080
+ amount: value.toString(10),
14081
+ ...known === undefined ? {} : {
14082
+ symbol: known.symbol,
14083
+ decimals: known.decimals
14084
+ }
14085
+ },
14086
+ change,
14087
+ unlimited: change !== "decrease" && value === max,
14088
+ ...extra,
14089
+ verified: known !== undefined
14090
+ };
14091
+ };
14092
+ var isMessage = isTypedDataMessage;
14093
+ var address = typedDataAddress;
14094
+ var uint = typedDataUint;
14095
+ var DETAILS = [
14096
+ "address token",
14097
+ "uint160 amount",
14098
+ "uint48 expiration",
14099
+ "uint48 nonce"
14100
+ ];
14101
+ var PERMISSIONS = ["address token", "uint256 amount"];
14102
+ var WITNESS_WARNING = {
14103
+ kind: "permit2-witness",
14104
+ message: "the permit carries a witness with further terms"
14105
+ };
14106
+ var entries = (value) => Array.isArray(value) && value.length > 0 && value.every(isMessage) ? value : undefined;
14107
+ var permit = (...approvals) => ({
14108
+ approvals,
14109
+ warnings: []
14110
+ });
14111
+ function recognizePermit(json, chainId, table) {
14112
+ const { types, primaryType, message, domain } = json;
14113
+ const verifying = address(domain["verifyingContract"]);
14114
+ if (verifying === undefined)
14115
+ return;
14116
+ const spender = address(message["spender"]);
14117
+ if (spender === undefined)
14118
+ return;
14119
+ const allow = (token, value, change, max, extra = {}) => allowanceChange(token, spender, value, change, max, chainId, table, extra);
14120
+ if (primaryType === "Permit") {
14121
+ if (sameFields(types, "Permit", [
14122
+ "address owner",
14123
+ "address spender",
14124
+ "uint256 value",
14125
+ "uint256 nonce",
14126
+ "uint256 deadline"
14127
+ ])) {
14128
+ const value = uint(message["value"], MAX_UINT256);
14129
+ return value === undefined ? undefined : permit(allow(verifying, value, "set", MAX_UINT256));
14130
+ }
14131
+ if (sameFields(types, "Permit", [
14132
+ "address holder",
14133
+ "address spender",
14134
+ "uint256 nonce",
14135
+ "uint256 expiry",
14136
+ "bool allowed"
14137
+ ])) {
14138
+ const { allowed } = message;
14139
+ return typeof allowed === "boolean" ? permit(allow(verifying, allowed ? MAX_UINT256 : 0n, "set", MAX_UINT256)) : undefined;
14140
+ }
14141
+ return;
14142
+ }
14143
+ if (verifying.toLowerCase() !== "0x000000000022D473030F116dDEE9F6B43aC78BA3".toLowerCase())
14144
+ return;
14145
+ return recognizePermit2(types, primaryType, message, allow);
14146
+ }
14147
+ var recognizePermit2 = (types, primaryType, message, allow) => {
14148
+ const via = "permit2";
14149
+ const allowance = (details) => {
14150
+ const token = address(details["token"]);
14151
+ const amount = uint(details["amount"], MAX_UINT160);
14152
+ const expiration = uint(details["expiration"], MAX_UINT48);
14153
+ return token === undefined || amount === undefined || expiration === undefined ? undefined : allow(token, amount, "set", MAX_UINT160, {
14154
+ via,
14155
+ expiration: Number(expiration)
14156
+ });
14157
+ };
14158
+ const transfer = (permitted, deadline) => {
14159
+ const token = address(permitted["token"]);
14160
+ const amount = uint(permitted["amount"], MAX_UINT256);
14161
+ return token === undefined || amount === undefined ? undefined : allow(token, amount, "transfer", MAX_UINT256, {
14162
+ via,
14163
+ ...deadline <= MAX_UINT48 ? { expiration: Number(deadline) } : {}
14164
+ });
14165
+ };
14166
+ const all = (list, build) => {
14167
+ const built = list?.map(build);
14168
+ return built === undefined || built.some((a) => a === undefined) ? undefined : permit(...built.filter((a) => a !== undefined));
14169
+ };
14170
+ if (primaryType === "PermitSingle") {
14171
+ const { details } = message;
14172
+ return sameFields(types, primaryType, [
14173
+ "PermitDetails details",
14174
+ "address spender",
14175
+ "uint256 sigDeadline"
14176
+ ]) && sameFields(types, "PermitDetails", DETAILS) && isMessage(details) ? all([details], allowance) : undefined;
14177
+ }
14178
+ if (primaryType === "PermitBatch")
14179
+ return sameFields(types, primaryType, [
14180
+ "PermitDetails[] details",
14181
+ "address spender",
14182
+ "uint256 sigDeadline"
14183
+ ]) && sameFields(types, "PermitDetails", DETAILS) ? all(entries(message["details"]), allowance) : undefined;
14184
+ const witness = primaryType.includes("Witness");
14185
+ const batch = primaryType.includes("Batch");
14186
+ const expected = batch ? [
14187
+ "TokenPermissions[] permitted",
14188
+ "address spender",
14189
+ "uint256 nonce",
14190
+ "uint256 deadline"
14191
+ ] : [
14192
+ "TokenPermissions permitted",
14193
+ "address spender",
14194
+ "uint256 nonce",
14195
+ "uint256 deadline"
14196
+ ];
14197
+ if (primaryType !== `Permit${batch ? "Batch" : ""}${witness ? "Witness" : ""}TransferFrom`)
14198
+ return;
14199
+ const own = types[primaryType];
14200
+ const last = own?.at(-1);
14201
+ const fieldsOk = witness ? sameFields({
14202
+ ...types,
14203
+ [primaryType]: own?.slice(0, -1) ?? []
14204
+ }, primaryType, expected) && last?.name === "witness" && types[last.type] !== undefined : sameFields(types, primaryType, expected);
14205
+ const deadline = uint(message["deadline"], MAX_UINT256);
14206
+ if (!fieldsOk || !sameFields(types, "TokenPermissions", PERMISSIONS) || deadline === undefined)
14207
+ return;
14208
+ const { permitted } = message;
14209
+ const result = batch ? all(entries(permitted), (item) => transfer(item, deadline)) : isMessage(permitted) ? all([permitted], (item) => transfer(item, deadline)) : undefined;
14210
+ return result === undefined || !witness ? result : {
14211
+ approvals: result.approvals,
14212
+ warnings: [WITNESS_WARNING]
14213
+ };
14214
+ };
14215
+ var SAFE_MULTISEND_CALL_ONLY = /* @__PURE__ */ new Set([
14216
+ "0x40a2accbd92bca938b02010e17a5b8929b49130d",
14217
+ "0xa1dabef33b3b82c7814b6d82a79e50f4ac44102b",
14218
+ "0x9641d764fc13c8b624c04430c7356c1c7c8102e2"
14219
+ ]);
14220
+ var SAFE_TX = [
14221
+ "address to",
14222
+ "uint256 value",
14223
+ "bytes data",
14224
+ "uint8 operation",
14225
+ "uint256 safeTxGas",
14226
+ "uint256 baseGas",
14227
+ "uint256 gasPrice",
14228
+ "address gasToken",
14229
+ "address refundReceiver",
14230
+ "uint256 nonce"
14231
+ ];
14232
+ var MULTISEND = from4("function multiSend(bytes transactions)");
14233
+ var multiSendEntries = (data) => {
14234
+ if (!data.toLowerCase().startsWith("0x8d80ff0a"))
14235
+ return;
14236
+ let packed;
14237
+ try {
14238
+ const decoded = decodeData(MULTISEND, data);
14239
+ const first = Array.isArray(decoded) ? decoded[0] : undefined;
14240
+ if (typeof first !== "string")
14241
+ return;
14242
+ packed = first;
14243
+ } catch {
14244
+ return;
14245
+ }
14246
+ if (!packed.startsWith("0x"))
14247
+ return;
14248
+ const hex = packed.slice(2).toLowerCase();
14249
+ const calls = [];
14250
+ let offset = 0;
14251
+ while (offset < hex.length) {
14252
+ if (hex.length - offset < 170)
14253
+ return;
14254
+ if (Number.parseInt(hex.slice(offset, offset + 2), 16) !== 0)
14255
+ return;
14256
+ const to = `0x${hex.slice(offset + 2, offset + 42)}`;
14257
+ const value = BigInt(`0x${hex.slice(offset + 42, offset + 106)}`);
14258
+ const length = BigInt(`0x${hex.slice(offset + 106, offset + 170)}`);
14259
+ offset += 170;
14260
+ if (length * 2n > BigInt(hex.length - offset))
14261
+ return;
14262
+ calls.push({
14263
+ to: checksumEvmAddress(to),
14264
+ value,
14265
+ data: `0x${hex.slice(offset, offset + Number(length) * 2)}`
14266
+ });
14267
+ offset += Number(length) * 2;
14268
+ }
14269
+ return calls;
14270
+ };
14271
+ function recognizeSafe(json, decode) {
14272
+ const { types, primaryType, message, domain } = json;
14273
+ if (primaryType !== "SafeTx" || !sameFields(types, "SafeTx", SAFE_TX))
14274
+ return;
14275
+ const safe = typedDataAddress(domain["verifyingContract"]);
14276
+ const to = typedDataAddress(message["to"]);
14277
+ const value = typedDataUint(message["value"], MAX_UINT256);
14278
+ const data = typedDataBytes(message["data"]);
14279
+ const operation = typedDataUint(message["operation"], 255n);
14280
+ const safeTxGas = typedDataUint(message["safeTxGas"], MAX_UINT256);
14281
+ const baseGas = typedDataUint(message["baseGas"], MAX_UINT256);
14282
+ const gasPrice = typedDataUint(message["gasPrice"], MAX_UINT256);
14283
+ const gasToken = typedDataAddress(message["gasToken"]);
14284
+ const refundReceiver = typedDataAddress(message["refundReceiver"]);
14285
+ const nonce = typedDataUint(message["nonce"], MAX_UINT256);
14286
+ if (safe === undefined || to === undefined || value === undefined || data === undefined || operation === undefined || operation > 1n || safeTxGas === undefined || baseGas === undefined || gasPrice === undefined || gasToken === undefined || refundReceiver === undefined || nonce === undefined)
14287
+ return;
14288
+ const inner = operation === 1n && SAFE_MULTISEND_CALL_ONLY.has(to.toLowerCase()) ? multiSendEntries(data) : undefined;
14289
+ const calls = (inner ?? [{
14290
+ to,
14291
+ value,
14292
+ data
14293
+ }]).map(decode);
14294
+ return {
14295
+ safe: {
14296
+ safe,
14297
+ nonce: nonce.toString(10),
14298
+ operation: operation === 0n ? "call" : "delegatecall",
14299
+ to,
14300
+ value: value.toString(10),
14301
+ data,
14302
+ calls,
14303
+ ...gasPrice > 0n ? { refund: {
14304
+ gasPrice: gasPrice.toString(10),
14305
+ gasToken,
14306
+ refundReceiver
14307
+ } } : {}
14308
+ },
14309
+ multisend: inner !== undefined
14310
+ };
14311
+ }
14312
+ var SEAPORT_CONTRACTS = /* @__PURE__ */ new Set(["0x0000000000000068f116a894984e2db1123eb395", "0x00000000000000adc04c56bf30ac9d3c0aaf14dc"]);
14313
+ var ITEM_KINDS = [
14314
+ "native",
14315
+ "erc20",
14316
+ "erc721",
14317
+ "erc1155",
14318
+ "erc721-criteria",
14319
+ "erc1155-criteria"
14320
+ ];
14321
+ var ITEM_FIELDS = [
14322
+ "uint8 itemType",
14323
+ "address token",
14324
+ "uint256 identifierOrCriteria",
14325
+ "uint256 startAmount",
14326
+ "uint256 endAmount"
14327
+ ];
14328
+ var typesMatch = (types) => Object.keys(types).length === 3 && sameFields(types, "OrderComponents", [
14329
+ "address offerer",
14330
+ "address zone",
14331
+ "OfferItem[] offer",
14332
+ "ConsiderationItem[] consideration",
14333
+ "uint8 orderType",
14334
+ "uint256 startTime",
14335
+ "uint256 endTime",
14336
+ "bytes32 zoneHash",
14337
+ "uint256 salt",
14338
+ "bytes32 conduitKey",
14339
+ "uint256 counter"
14340
+ ]) && sameFields(types, "OfferItem", ITEM_FIELDS) && sameFields(types, "ConsiderationItem", [...ITEM_FIELDS, "address recipient"]);
14341
+ var amount = (kind, token, value, chainId, table) => {
14342
+ if (kind === "native")
14343
+ return {
14344
+ asset: EVM_NATIVE_ASSET,
14345
+ amount: value.toString(10),
14346
+ symbol: "ETH",
14347
+ decimals: 18
14348
+ };
14349
+ if (kind === "erc20") {
14350
+ const found = lookupEvmToken(table, chainId, token);
14351
+ return {
14352
+ asset: token,
14353
+ amount: value.toString(10),
14354
+ ...found === undefined ? {} : {
14355
+ symbol: found.symbol,
14356
+ decimals: found.decimals
14357
+ }
14358
+ };
14359
+ }
14360
+ return {
14361
+ asset: token,
14362
+ amount: value.toString(10)
14363
+ };
14364
+ };
14365
+ var item = (message, chainId, table) => {
14366
+ const itemType = typedDataUint(message["itemType"], 255n);
14367
+ const token = typedDataAddress(message["token"]);
14368
+ const identifier = typedDataUint(message["identifierOrCriteria"], MAX_UINT256);
14369
+ const start = typedDataUint(message["startAmount"], MAX_UINT256);
14370
+ const end = typedDataUint(message["endAmount"], MAX_UINT256);
14371
+ const kind = itemType === undefined ? undefined : ITEM_KINDS[Number(itemType)];
14372
+ if (token === undefined || identifier === undefined || start === undefined || end === undefined || kind === undefined)
14373
+ return;
14374
+ return {
14375
+ kind,
14376
+ token,
14377
+ identifier: identifier.toString(10),
14378
+ startAmount: amount(kind, token, start, chainId, table),
14379
+ endAmount: amount(kind, token, end, chainId, table)
14380
+ };
14381
+ };
14382
+ var all = (list, build) => {
14383
+ const built = list?.map(build);
14384
+ return built === undefined || built.some((entry) => entry === undefined) ? undefined : built.filter((entry) => entry !== undefined);
14385
+ };
14386
+ function recognizeSeaport(json, chainId, table) {
14387
+ const { types, primaryType, message, domain } = json;
14388
+ if (primaryType !== "OrderComponents" || !typesMatch(types))
14389
+ return;
14390
+ const verifying = typedDataAddress(domain["verifyingContract"]);
14391
+ if (domain["name"] !== "Seaport" || verifying === undefined || !SEAPORT_CONTRACTS.has(verifying.toLowerCase()))
14392
+ return;
14393
+ const offerer = typedDataAddress(message["offerer"]);
14394
+ const zone = typedDataAddress(message["zone"]);
14395
+ const startTime = typedDataUint(message["startTime"], MAX_UINT256);
14396
+ const endTime = typedDataUint(message["endTime"], MAX_UINT256);
14397
+ const offer = all(typedDataMessages(message["offer"]), (entry) => item(entry, chainId, table));
14398
+ const consideration = all(typedDataMessages(message["consideration"]), (entry) => {
14399
+ const base = item(entry, chainId, table);
14400
+ const recipient = typedDataAddress(entry["recipient"]);
14401
+ return base === undefined || recipient === undefined ? undefined : {
14402
+ ...base,
14403
+ recipient
14404
+ };
14405
+ });
14406
+ if (offerer === undefined || zone === undefined || startTime === undefined || endTime === undefined || offer === undefined || consideration === undefined)
14407
+ return;
14408
+ return {
14409
+ offerer,
14410
+ zone,
14411
+ startTime: startTime <= MAX_UINT48 ? Number(startTime) : undefined,
14412
+ endTime: endTime <= MAX_UINT48 ? Number(endTime) : undefined,
14413
+ offer,
14414
+ consideration
14415
+ };
14416
+ }
12705
14417
  var ERC20_TRANSFER = from4("function transfer(address to, uint256 amount)");
12706
14418
  var ERC20_APPROVE = from4("function approve(address spender, uint256 amount)");
12707
14419
  var ERC20_INCREASE = from4("function increaseAllowance(address spender, uint256 amount)");
14420
+ var ERC20_DECREASE = from4("function decreaseAllowance(address spender, uint256 subtractedValue)");
14421
+ var SET_APPROVAL_FOR_ALL = from4("function setApprovalForAll(address operator, bool approved)");
14422
+ var PERMIT2_APPROVE = from4("function approve(address token, address spender, uint160 amount, uint48 expiration)");
14423
+ var PERMIT2_LOCKDOWN = from4("function lockdown((address token, address spender)[] approvals)");
14424
+ var ERC721_SAFE_FROM_DATA = from4("function safeTransferFrom(address from, address to, uint256 tokenId, bytes data)");
14425
+ var ERC1155_SAFE_BATCH_FROM = from4("function safeBatchTransferFrom(address from, address to, uint256[] ids, uint256[] amounts, bytes data)");
12708
14426
  var ERC721_TRANSFER_FROM = from4("function transferFrom(address from, address to, uint256 tokenId)");
12709
14427
  var ERC721_SAFE_FROM = from4("function safeTransferFrom(address from, address to, uint256 tokenId)");
12710
14428
  var ERC1155_SAFE_FROM = from4("function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes data)");
12711
- var NATIVE_ASSET = "native";
12712
- var MAX_UINT256 = 2n ** 256n - 1n;
12713
14429
  var argAddress = (args, index) => {
12714
14430
  const value = args[index];
12715
14431
  if (typeof value !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(value))
@@ -12737,24 +14453,24 @@ var tryCall = (fn, data) => {
12737
14453
  }
12738
14454
  };
12739
14455
  var weiAmount = (wei, symbol, decimals) => ({
12740
- asset: NATIVE_ASSET,
14456
+ asset: EVM_NATIVE_ASSET,
12741
14457
  amount: wei.toString(10),
12742
14458
  ...symbol === undefined ? {} : { symbol },
12743
14459
  ...decimals === undefined ? {} : { decimals }
12744
14460
  });
12745
- var feeWei = (tx) => BigInt(tx.gas) * (tx.type === "eip1559" ? BigInt(tx.maxFeePerGas) : BigInt(tx.gasPrice));
12746
- var nativeOutflow = (tx, to) => [{
14461
+ var feeWei = (tx) => quantityBigInt(tx.gas, "tx.gas") * (tx.type === "eip1559" ? quantityBigInt(tx.maxFeePerGas, "tx.maxFeePerGas") : quantityBigInt(tx.gasPrice, "tx.gasPrice"));
14462
+ var nativeOutflow = (value, to) => [{
12747
14463
  to,
12748
- amount: weiAmount(BigInt(tx.value)),
14464
+ amount: weiAmount(value),
12749
14465
  verified: true
12750
14466
  }];
12751
- var tokenFlow = (tx, to, amount, chainId, table) => {
12752
- const token = lookupEvmToken(table, chainId, tx.to ?? "");
14467
+ var tokenFlow = (target, to, amount, chainId, table) => {
14468
+ const token = lookupEvmToken(table, chainId, target);
12753
14469
  return {
12754
14470
  flows: [{
12755
14471
  to,
12756
14472
  amount: {
12757
- asset: tx.to ?? "",
14473
+ asset: target,
12758
14474
  amount: amount.toString(10),
12759
14475
  ...token === undefined ? {} : {
12760
14476
  symbol: token.symbol,
@@ -12766,13 +14482,28 @@ var tokenFlow = (tx, to, amount, chainId, table) => {
12766
14482
  verified: token !== undefined
12767
14483
  };
12768
14484
  };
12769
- var approvalChange = (tx, spender, amount) => ({
12770
- asset: tx.to ?? "",
12771
- spender,
12772
- amount: amount.toString(10),
12773
- unlimited: amount === MAX_UINT256,
12774
- verified: false
12775
- });
14485
+ var argBool = (args, index) => {
14486
+ const value = args[index];
14487
+ if (typeof value !== "boolean")
14488
+ throw new ChainError("invalid-request", "decoded argument is not a bool");
14489
+ return value;
14490
+ };
14491
+ var argList = (args, index) => {
14492
+ const value = args[index];
14493
+ if (!Array.isArray(value))
14494
+ throw new ChainError("invalid-request", "decoded argument is not an array");
14495
+ return value;
14496
+ };
14497
+ var argSeconds = (args, index) => {
14498
+ const value = args[index];
14499
+ if (typeof value !== "number" && typeof value !== "bigint")
14500
+ throw new ChainError("invalid-request", "decoded argument is not an integer");
14501
+ return Number(value);
14502
+ };
14503
+ var pairField = (pair, key) => {
14504
+ const value = typeof pair === "object" && pair !== null ? Reflect.get(pair, key) : "";
14505
+ return argAddress([value], 0);
14506
+ };
12776
14507
  var nftFlow = (asset, to, id) => [{
12777
14508
  to,
12778
14509
  amount: {
@@ -12781,19 +14512,17 @@ var nftFlow = (asset, to, id) => [{
12781
14512
  },
12782
14513
  verified: false
12783
14514
  }];
12784
- var decodeTransaction = (request, table) => {
12785
- const { tx } = request;
12786
- const chainId = networkChainId(request.network);
12787
- const data = tx.data.toLowerCase();
12788
- const fee = { max: weiAmount(feeWei(tx)) };
14515
+ var decodeCall = (call, network, fee, table) => {
14516
+ const chainId = networkChainId(network);
14517
+ const data = call.data.toLowerCase();
12789
14518
  const base = {
12790
14519
  family: "evm",
12791
- network: request.network,
14520
+ network,
12792
14521
  approvals: [],
12793
14522
  warnings: []
12794
14523
  };
12795
14524
  if (data === "0x") {
12796
- if (tx.to === undefined)
14525
+ if (call.to === undefined)
12797
14526
  return {
12798
14527
  ...base,
12799
14528
  summary: "contract-call",
@@ -12804,14 +14533,14 @@ var decodeTransaction = (request, table) => {
12804
14533
  return {
12805
14534
  ...base,
12806
14535
  summary: "transfer",
12807
- outflows: nativeOutflow(tx, tx.to),
14536
+ outflows: nativeOutflow(call.value, call.to),
12808
14537
  fee,
12809
14538
  verifiability: "full"
12810
14539
  };
12811
14540
  }
12812
14541
  const transferArgs = tryCall(ERC20_TRANSFER, data);
12813
14542
  if (transferArgs !== undefined) {
12814
- const { flows, verified } = tokenFlow(tx, argAddress(transferArgs, 0), argUint(transferArgs, 1), chainId, table);
14543
+ const { flows, verified } = tokenFlow(call.to ?? "", argAddress(transferArgs, 0), argUint(transferArgs, 1), chainId, table);
12815
14544
  return {
12816
14545
  ...base,
12817
14546
  summary: "transfer",
@@ -12820,46 +14549,70 @@ var decodeTransaction = (request, table) => {
12820
14549
  verifiability: verified ? "full" : "partial"
12821
14550
  };
12822
14551
  }
12823
- const approveArgs = tryCall(ERC20_APPROVE, data);
12824
- if (approveArgs !== undefined)
12825
- return {
12826
- ...base,
12827
- summary: "approve",
12828
- outflows: [],
12829
- approvals: [approvalChange(tx, argAddress(approveArgs, 0), argUint(approveArgs, 1))],
12830
- fee,
12831
- verifiability: "partial"
12832
- };
12833
- const increaseArgs = tryCall(ERC20_INCREASE, data);
12834
- if (increaseArgs !== undefined)
12835
- return {
12836
- ...base,
12837
- summary: "approve",
12838
- outflows: [],
12839
- approvals: [approvalChange(tx, argAddress(increaseArgs, 0), argUint(increaseArgs, 1))],
12840
- fee,
12841
- verifiability: "partial"
12842
- };
12843
- for (const fn of [ERC721_TRANSFER_FROM, ERC721_SAFE_FROM]) {
14552
+ const partial = (summary, outflows, approvals) => ({
14553
+ ...base,
14554
+ summary,
14555
+ outflows,
14556
+ approvals,
14557
+ fee,
14558
+ verifiability: "partial"
14559
+ });
14560
+ const token = call.to ?? "";
14561
+ if (token.toLowerCase() === "0x000000000022D473030F116dDEE9F6B43aC78BA3".toLowerCase()) {
14562
+ const permitArgs = tryCall(PERMIT2_APPROVE, data);
14563
+ if (permitArgs !== undefined) {
14564
+ const amount = argUint(permitArgs, 2);
14565
+ return partial("approve", [], [allowanceChange(argAddress(permitArgs, 0), argAddress(permitArgs, 1), amount, "set", MAX_UINT160, chainId, table, {
14566
+ via: "permit2",
14567
+ expiration: argSeconds(permitArgs, 3)
14568
+ })]);
14569
+ }
14570
+ const lockdownArgs = tryCall(PERMIT2_LOCKDOWN, data);
14571
+ if (lockdownArgs !== undefined)
14572
+ return partial("approve", [], argList(lockdownArgs, 0).map((pair) => allowanceChange(pairField(pair, "token"), pairField(pair, "spender"), 0n, "set", MAX_UINT160, chainId, table, { via: "permit2" })));
14573
+ }
14574
+ for (const [fn, change] of [
14575
+ [ERC20_APPROVE, "set"],
14576
+ [ERC20_INCREASE, "increase"],
14577
+ [ERC20_DECREASE, "decrease"]
14578
+ ]) {
12844
14579
  const args = tryCall(fn, data);
12845
14580
  if (args !== undefined)
12846
- return {
12847
- ...base,
12848
- summary: "transfer",
12849
- outflows: nftFlow(tx.to ?? "", argAddress(args, 1), argUint(args, 2)),
12850
- fee,
12851
- verifiability: "partial"
12852
- };
14581
+ return partial("approve", [], [allowanceChange(token, argAddress(args, 0), argUint(args, 1), change, MAX_UINT256, chainId, table)]);
14582
+ }
14583
+ const operatorArgs = tryCall(SET_APPROVAL_FOR_ALL, data);
14584
+ if (operatorArgs !== undefined)
14585
+ return partial("approve", [], [{
14586
+ kind: "operator",
14587
+ asset: token,
14588
+ spender: argAddress(operatorArgs, 0),
14589
+ approved: argBool(operatorArgs, 1),
14590
+ verified: false
14591
+ }]);
14592
+ const transferFromArgs = tryCall(ERC721_TRANSFER_FROM, data);
14593
+ if (transferFromArgs !== undefined) {
14594
+ const to = argAddress(transferFromArgs, 1);
14595
+ const id = argUint(transferFromArgs, 2);
14596
+ if (lookupEvmToken(table, chainId, token) !== undefined)
14597
+ return partial("transfer", tokenFlow(token, to, id, chainId, table).flows, []);
14598
+ return partial("transfer", nftFlow(token, to, id), []);
14599
+ }
14600
+ for (const fn of [ERC721_SAFE_FROM, ERC721_SAFE_FROM_DATA]) {
14601
+ const args = tryCall(fn, data);
14602
+ if (args !== undefined)
14603
+ return partial("transfer", nftFlow(token, argAddress(args, 1), argUint(args, 2)), []);
12853
14604
  }
12854
14605
  const erc1155Args = tryCall(ERC1155_SAFE_FROM, data);
12855
14606
  if (erc1155Args !== undefined)
12856
- return {
12857
- ...base,
12858
- summary: "transfer",
12859
- outflows: nftFlow(tx.to ?? "", argAddress(erc1155Args, 1), argUint(erc1155Args, 2)),
12860
- fee,
12861
- verifiability: "partial"
12862
- };
14607
+ return partial("transfer", nftFlow(token, argAddress(erc1155Args, 1), argUint(erc1155Args, 2)), []);
14608
+ const batchArgs = tryCall(ERC1155_SAFE_BATCH_FROM, data);
14609
+ if (batchArgs !== undefined) {
14610
+ const ids = argList(batchArgs, 2);
14611
+ if (ids.length > 0 && ids.length === argList(batchArgs, 3).length) {
14612
+ const to = argAddress(batchArgs, 1);
14613
+ return partial("transfer", ids.flatMap((id) => nftFlow(token, to, argUint([id], 0))), []);
14614
+ }
14615
+ }
12863
14616
  return {
12864
14617
  ...base,
12865
14618
  summary: "contract-call",
@@ -12868,6 +14621,44 @@ var decodeTransaction = (request, table) => {
12868
14621
  verifiability: "opaque"
12869
14622
  };
12870
14623
  };
14624
+ var decodeTransaction = (request, table) => {
14625
+ const { tx } = request;
14626
+ return decodeCall({
14627
+ to: tx.to,
14628
+ value: quantityBigInt(tx.value, "tx.value"),
14629
+ data: tx.data
14630
+ }, request.network, { max: weiAmount(feeWei(tx)) }, table);
14631
+ };
14632
+ var displayDomain = (domain) => {
14633
+ const { name, version, verifyingContract, salt } = domain;
14634
+ const chainId = domainChainId(domain);
14635
+ return {
14636
+ ...typeof name === "string" ? { name } : {},
14637
+ ...typeof version === "string" ? { version } : {},
14638
+ ...chainId === undefined ? {} : { chainId },
14639
+ ...typeof verifyingContract === "string" && /^0x[0-9a-fA-F]{40}$/.test(verifyingContract) ? { verifyingContract: checksumEvmAddress(verifyingContract) } : {},
14640
+ ...typeof salt === "string" ? { salt } : {}
14641
+ };
14642
+ };
14643
+ var messageContent = (bytes) => {
14644
+ try {
14645
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
14646
+ const signIn = parseSignIn(text, "evm");
14647
+ return signIn === undefined ? {
14648
+ kind: "text",
14649
+ text
14650
+ } : {
14651
+ kind: "text",
14652
+ text,
14653
+ signIn
14654
+ };
14655
+ } catch {
14656
+ return {
14657
+ kind: "bytes",
14658
+ hex: `0x${[...bytes].map((b) => b.toString(16).padStart(2, "0")).join("")}`
14659
+ };
14660
+ }
14661
+ };
12871
14662
  var decodeEvm = (request, table = evmTokenTable) => {
12872
14663
  if (request.kind === "evm.transaction")
12873
14664
  return decodeTransaction(request, table);
@@ -12880,20 +14671,35 @@ var decodeEvm = (request, table = evmTokenTable) => {
12880
14671
  approvals: [],
12881
14672
  fee: undefined,
12882
14673
  warnings: [],
14674
+ message: messageContent(request.message),
12883
14675
  verifiability: "opaque"
12884
14676
  };
12885
14677
  if (request.kind !== "evm.typed-data")
12886
14678
  throw new ChainError("unsupported", `unsupported sign request kind: ${request.kind}`);
12887
- const parsed = parseTypedData(request.typedData, request.network);
14679
+ const { json } = parseTypedData(request.typedData);
14680
+ const chainId = networkChainId(request.network);
14681
+ const permit = recognizePermit(json, chainId, table);
14682
+ const seaport = permit === undefined ? recognizeSeaport(json, chainId, table) : undefined;
14683
+ const safe = permit === undefined && seaport === undefined ? recognizeSafe(json, (call) => decodeCall(call, request.network, undefined, table)) : undefined;
14684
+ const message = {
14685
+ kind: "typed-data",
14686
+ primaryType: json.primaryType,
14687
+ domain: displayDomain(json.domain),
14688
+ data: json.message,
14689
+ ...seaport === undefined ? {} : { seaport },
14690
+ ...safe === undefined ? {} : { safe: safe.safe }
14691
+ };
14692
+ const summary = seaport === undefined ? safe === undefined ? permit === undefined ? "message" : "approve" : safe.multisend ? "batch" : safe.safe.calls[0]?.summary ?? "contract-call" : "swap";
12888
14693
  return {
12889
14694
  family: "evm",
12890
14695
  network: request.network,
12891
- summary: "message",
14696
+ summary,
12892
14697
  outflows: [],
12893
- approvals: [],
14698
+ approvals: permit?.approvals ?? [],
12894
14699
  fee: undefined,
12895
- warnings: typedDataWarnings(parsed),
12896
- verifiability: "opaque"
14700
+ warnings: permit?.warnings ?? [],
14701
+ message,
14702
+ verifiability: permit === undefined ? "opaque" : "partial"
12897
14703
  };
12898
14704
  };
12899
14705
  var normalizeEvm = (request) => {
@@ -12927,7 +14733,10 @@ var normalizeEvm = (request) => {
12927
14733
  const { typedData } = request;
12928
14734
  if (typeof typedData !== "string")
12929
14735
  throw new ChainError("invalid-request", "typed-data payload must be the JSON source string");
12930
- parseTypedData(typedData, network);
14736
+ const { json } = parseTypedData(typedData);
14737
+ const domainChain = domainChainId(json.domain);
14738
+ if (domainChain !== undefined && domainChain !== chainId)
14739
+ throw new ChainError("chain-id-mismatch", `typed-data domain.chainId ${domainChain} does not match network ${network}`);
12931
14740
  return {
12932
14741
  kind: "evm.typed-data",
12933
14742
  network,
@@ -14408,8 +16217,11 @@ var parseCompiledMessage = (bytes) => {
14408
16217
  numRequiredSignatures: message.numSignerAccounts,
14409
16218
  staticAccounts,
14410
16219
  instructions: message.instructions,
14411
- lookupCount: lookups.length,
14412
- lookupAddresses: lookups.map((l) => l.lookupTableAddress)
16220
+ lookups: lookups.map((l) => ({
16221
+ address: l.lookupTableAddress,
16222
+ writableIndexes: l.writableIndexes,
16223
+ readonlyIndexes: l.readonlyIndexes
16224
+ }))
14413
16225
  };
14414
16226
  };
14415
16227
  var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
@@ -14474,6 +16286,7 @@ var validateLookupTables = (tables) => {
14474
16286
  if (!isSolanaAddress(table.address) || !table.addresses.every(isSolanaAddress))
14475
16287
  throw new ChainError("invalid-address", "lookup table entries must be base58 32-byte addresses");
14476
16288
  };
16289
+ var SOLANA_NATIVE_ASSET = "lamports";
14477
16290
  var USDC2 = Object.freeze({
14478
16291
  symbol: "USDC",
14479
16292
  decimals: 6,
@@ -14489,7 +16302,6 @@ var solanaTokenTable = Object.freeze({ "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"
14489
16302
  Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB: USDT2
14490
16303
  }) });
14491
16304
  var lookupSolanaToken = (table, network, mint) => table[network]?.[mint];
14492
- var LAMPORTS_ASSET = "lamports";
14493
16305
  var u323 = getU32Decoder();
14494
16306
  var u64$1 = getU64Decoder();
14495
16307
  var u32le2 = (data, offset) => u323.decode(data, offset);
@@ -14555,7 +16367,7 @@ var FULL_KINDS = /* @__PURE__ */ new Set([
14555
16367
  "ata-create-idempotent"
14556
16368
  ]);
14557
16369
  var classify2 = (parsed, calls, network, table) => {
14558
- if (parsed.lookupCount > 0)
16370
+ if (parsed.lookups.length > 0)
14559
16371
  return "partial";
14560
16372
  let allFull = true;
14561
16373
  for (const call of calls) {
@@ -14594,7 +16406,7 @@ var decodeTransaction2 = (request, signer, table) => {
14594
16406
  outflows.push({
14595
16407
  to: call.to,
14596
16408
  amount: {
14597
- asset: LAMPORTS_ASSET,
16409
+ asset: SOLANA_NATIVE_ASSET,
14598
16410
  amount: (call.amount ?? 0n).toString(10)
14599
16411
  },
14600
16412
  verified: true
@@ -14615,14 +16427,24 @@ var decodeTransaction2 = (request, signer, table) => {
14615
16427
  verified: token !== undefined
14616
16428
  });
14617
16429
  }
14618
- if (call.kind === "token-approve")
16430
+ if (call.kind === "token-approve") {
16431
+ const token = lookupSolanaToken(table, request.network, call.mint ?? "");
14619
16432
  approvals.push({
14620
- asset: call.mint ?? "",
16433
+ kind: "allowance",
14621
16434
  spender: call.to ?? "",
14622
- amount: (call.amount ?? 0n).toString(10),
16435
+ amount: {
16436
+ asset: call.mint ?? "",
16437
+ amount: (call.amount ?? 0n).toString(10),
16438
+ ...token === undefined ? {} : {
16439
+ symbol: token.symbol,
16440
+ decimals: token.decimals
16441
+ }
16442
+ },
16443
+ change: "set",
14623
16444
  unlimited: false,
14624
- verified: false
16445
+ verified: token !== undefined
14625
16446
  });
16447
+ }
14626
16448
  }
14627
16449
  const fee = feeLamports(parsed, calls);
14628
16450
  return {
@@ -14632,7 +16454,7 @@ var decodeTransaction2 = (request, signer, table) => {
14632
16454
  outflows,
14633
16455
  approvals,
14634
16456
  fee: fee === undefined ? undefined : { max: {
14635
- asset: LAMPORTS_ASSET,
16457
+ asset: SOLANA_NATIVE_ASSET,
14636
16458
  amount: fee.toString(10)
14637
16459
  } },
14638
16460
  warnings: [],
@@ -14720,7 +16542,8 @@ var signBitcoinPsbt = (psbt, inputs, auxRand) => {
14720
16542
  for (const { index, privateKey } of inputs) {
14721
16543
  if (privateKey.length !== 32)
14722
16544
  throw new ChainError("invalid-request", `input ${index}: private key must be 32 bytes`);
14723
- if (!tx.signIdx(privateKey, index, undefined, auxRand(index)))
16545
+ const allowed = tx.getInput(index).sighashType === SigHash.SINGLE_ANYONECANPAY ? [SigHash.SINGLE_ANYONECANPAY] : undefined;
16546
+ if (!tx.signIdx(privateKey, index, allowed, auxRand(index)))
14724
16547
  throw new ChainError("invalid-request", `input ${index}: key cannot sign`);
14725
16548
  }
14726
16549
  return tx.toPSBT(0);
@@ -14742,6 +16565,20 @@ var MESSAGE_INTENT = {
14742
16565
  fee: undefined,
14743
16566
  verifiability: "opaque"
14744
16567
  };
16568
+ var utf82 = new TextDecoder("utf-8", { fatal: true });
16569
+ var messageIntent = (message) => {
16570
+ try {
16571
+ return { ...MESSAGE_INTENT, message: { kind: "text", text: utf82.decode(message) } };
16572
+ } catch {
16573
+ return {
16574
+ ...MESSAGE_INTENT,
16575
+ message: {
16576
+ kind: "bytes",
16577
+ hex: `0x${[...message].map((b) => b.toString(16).padStart(2, "0")).join("")}`
16578
+ }
16579
+ };
16580
+ }
16581
+ };
14745
16582
  var CATALOGS = {
14746
16583
  "zh-Hans": {
14747
16584
  titles: {
@@ -14753,12 +16590,23 @@ var CATALOGS = {
14753
16590
  authorization: "确认账户授权",
14754
16591
  batch: "确认批量交易"
14755
16592
  },
16593
+ blindTitle: "确认盲签",
16594
+ blindDescription: "签署无法显示为文字的数据",
14756
16595
  generic: "签署来自应用的请求",
14757
16596
  otherOutflows: "可能还有其他转出",
14758
16597
  send: (amount, to) => `发送 ${amount} 到 ${to}`,
14759
16598
  allow: (spender, amount) => `授权 ${spender} 使用 ${amount}`,
14760
16599
  unlimited: (asset) => `全部 ${asset}`,
14761
- maxFee: (fee) => `最高手续费 ${fee}`
16600
+ revoke: (spender, asset) => `撤销 ${spender} 对 ${asset} 的授权`,
16601
+ increase: (spender, amount) => `授权 ${spender} 再使用 ${amount}`,
16602
+ decrease: (spender, amount) => `减少 ${spender} 的授权额度 ${amount}`,
16603
+ takeOnce: (spender, amount) => `授权 ${spender} 一次性转走 ${amount}`,
16604
+ viaPermit2: " 经 Permit2",
16605
+ until: (date) => ` 至 ${date}(UTC)`,
16606
+ operatorAllow: (spender, asset) => `授权 ${spender} 转走 ${asset} 的全部代币`,
16607
+ operatorRevoke: (spender, asset) => `撤销 ${spender} 对 ${asset} 全部代币的授权`,
16608
+ maxFee: (fee) => `最高手续费 ${fee}`,
16609
+ sighashSingle: "已签输入只绑定同序号输出,交易其余部分可被改动"
14762
16610
  },
14763
16611
  en: {
14764
16612
  titles: {
@@ -14770,34 +16618,85 @@ var CATALOGS = {
14770
16618
  authorization: "Confirm account authorization",
14771
16619
  batch: "Confirm batch"
14772
16620
  },
16621
+ blindTitle: "Confirm blind signing",
16622
+ blindDescription: "Sign data that cannot be shown as text",
14773
16623
  generic: "Sign a request from an app",
14774
16624
  otherOutflows: "There may be other outflows",
14775
16625
  send: (amount, to) => `Send ${amount} to ${to}`,
14776
16626
  allow: (spender, amount) => `Allow ${spender} to spend ${amount}`,
14777
16627
  unlimited: (asset) => `unlimited ${asset}`,
14778
- maxFee: (fee) => `Max fee ${fee}`
16628
+ revoke: (spender, asset) => `Revoke ${spender}'s allowance for ${asset}`,
16629
+ increase: (spender, amount) => `Allow ${spender} to spend ${amount} more`,
16630
+ decrease: (spender, amount) => `Reduce ${spender}'s allowance by ${amount}`,
16631
+ takeOnce: (spender, amount) => `Allow ${spender} to take ${amount} once`,
16632
+ viaPermit2: " via Permit2",
16633
+ until: (date) => ` until ${date} (UTC)`,
16634
+ operatorAllow: (spender, asset) => `Allow ${spender} to transfer all tokens of ${asset}`,
16635
+ operatorRevoke: (spender, asset) => `Revoke ${spender}'s access to all tokens of ${asset}`,
16636
+ maxFee: (fee) => `Max fee ${fee}`,
16637
+ sighashSingle: "Signed inputs bind only their same-index outputs; the rest of the transaction can change"
14779
16638
  }
14780
16639
  };
14781
16640
  function formatAmount(amount) {
14782
16641
  return amount.decimals === undefined ? `${amount.amount} ${amount.asset}` : `${formatUnits(amount.amount, amount.decimals)} ${amount.symbol ?? amount.asset}`;
14783
16642
  }
16643
+ function utcDate(seconds) {
16644
+ const z = Math.floor(seconds / 86400) + 719468;
16645
+ const era = Math.floor(z / 146097);
16646
+ const doe = z - era * 146097;
16647
+ const yoe = Math.floor((doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365);
16648
+ const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));
16649
+ const mp = Math.floor((5 * doy + 2) / 153);
16650
+ const day = doy - Math.floor((153 * mp + 2) / 5) + 1;
16651
+ const month = mp < 10 ? mp + 3 : mp - 9;
16652
+ const year = yoe + era * 400 + (month <= 2 ? 1 : 0);
16653
+ return `${String(year).padStart(4, "0")}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
16654
+ }
16655
+ function approvalLine(catalog, change) {
16656
+ if (change.kind === "operator") {
16657
+ return change.approved ? catalog.operatorAllow(change.spender, change.asset) : catalog.operatorRevoke(change.spender, change.asset);
16658
+ }
16659
+ const name = change.amount.symbol ?? change.amount.asset;
16660
+ let line;
16661
+ if (change.change === "increase") {
16662
+ line = catalog.increase(change.spender, formatAmount(change.amount));
16663
+ } else if (change.change === "decrease") {
16664
+ line = catalog.decrease(change.spender, formatAmount(change.amount));
16665
+ } else if (change.change === "transfer") {
16666
+ line = catalog.takeOnce(change.spender, change.unlimited ? catalog.unlimited(name) : formatAmount(change.amount));
16667
+ } else if (change.unlimited) {
16668
+ line = catalog.allow(change.spender, catalog.unlimited(name));
16669
+ } else if (change.amount.amount === "0") {
16670
+ line = catalog.revoke(change.spender, name);
16671
+ } else {
16672
+ line = catalog.allow(change.spender, formatAmount(change.amount));
16673
+ }
16674
+ const via = change.via === undefined ? "" : catalog.viaPermit2;
16675
+ const until = change.expiration === undefined || change.expiration === 0 ? "" : catalog.until(utcDate(change.expiration));
16676
+ return `${line}${via}${until}`;
16677
+ }
14784
16678
  function chainPrompt(locale, intent) {
14785
16679
  const catalog = CATALOGS[locale];
16680
+ if (intent.message?.kind === "bytes") {
16681
+ return { title: catalog.blindTitle, description: catalog.blindDescription };
16682
+ }
14786
16683
  const title = catalog.titles[intent.summary];
16684
+ const caution = intent.warnings?.some((w) => w.kind === "sighash-single-anyonecanpay") === true;
16685
+ const tail = caution ? [catalog.sighashSingle] : [];
14787
16686
  if (intent.verifiability === "opaque") {
14788
- return { title, description: catalog.generic };
16687
+ return { title, description: joinLines([catalog.generic, ...tail]) };
14789
16688
  }
14790
16689
  const lines = [
14791
16690
  ...intent.outflows.map((flow) => catalog.send(formatAmount(flow.amount), flow.to)),
14792
- ...intent.approvals.map((change) => catalog.allow(change.spender, change.unlimited ? catalog.unlimited(change.asset) : `${change.amount} ${change.asset}`)),
14793
- ...intent.fee === undefined ? [] : [catalog.maxFee(formatAmount(intent.fee.max))]
16691
+ ...intent.approvals.map((change) => approvalLine(catalog, change)),
16692
+ ...intent.fee === undefined ? [] : [catalog.maxFee(formatAmount(intent.fee.max))],
16693
+ ...tail
14794
16694
  ];
14795
16695
  if (intent.verifiability === "partial") {
14796
16696
  return { title, description: joinLines([catalog.otherOutflows, ...lines]) };
14797
16697
  }
14798
16698
  return { title, description: joinLines(lines.length === 0 ? [catalog.generic] : lines) };
14799
16699
  }
14800
-
14801
16700
  // ../wallet-kernel/src/modules/chains/shared.ts
14802
16701
  var BTC_PURPOSE = {
14803
16702
  "btc.bip44": 44,
@@ -14831,11 +16730,11 @@ function mapChainError(error) {
14831
16730
  }
14832
16731
 
14833
16732
  // ../wallet-kernel/src/modules/chains/bitcoin.ts
14834
- var isPath = (path) => Array.isArray(path) && path.every((p) => typeof p === "number");
16733
+ var isPath2 = (path) => Array.isArray(path) && path.every((p) => typeof p === "number");
14835
16734
  var hex = (bytes) => bytes.reduce((acc, b) => acc + b.toString(16).padStart(2, "0"), "");
14836
16735
  var derivationOf = (owner, fingerprint, purpose) => {
14837
16736
  if (purpose === 86) {
14838
- const claimed = (der) => der.fingerprint === fingerprint && isPath(der.path);
16737
+ const claimed = (der) => der.fingerprint === fingerprint && isPath2(der.path);
14839
16738
  for (const [key, value] of owner.tapBip32Derivation ?? []) {
14840
16739
  if (claimed(value.der)) {
14841
16740
  return { pubkey: key, fingerprint: value.der.fingerprint, path: value.der.path };
@@ -15092,7 +16991,7 @@ var signEvmPersonalMessage = (message, privateKey) => {
15092
16991
  return rs_v(from5(sign3(payload, key(privateKey))));
15093
16992
  };
15094
16993
  var signEvmTypedData = (typedData, privateKey) => {
15095
- const { json } = parseTypedData(typedData, "eip155:1");
16994
+ const { json } = parseTypedData(typedData);
15096
16995
  const payload = getSignPayload(json);
15097
16996
  return rs_v(from5(sign3(payload, key(privateKey))));
15098
16997
  };
@@ -15177,7 +17076,7 @@ var executeSolana = (request, account, seed, intentOnly) => {
15177
17076
  if (!deepEqual(normalized, request)) {
15178
17077
  throw new KernelError("invalid-input", "request is not normalized");
15179
17078
  }
15180
- let intent = MESSAGE_INTENT;
17079
+ let intent = messageIntent(request.message);
15181
17080
  if (request.kind === "solana.transaction") {
15182
17081
  try {
15183
17082
  intent = decodeSolana(request, signer);
@@ -16039,7 +17938,7 @@ function sparkPrompt(locale, summary) {
16039
17938
 
16040
17939
  // ../wallet-kernel/src/modules/spark/runtime.ts
16041
17940
  async function loadSparkRuntime() {
16042
- const signer = await import("./signer-gs57sjgx.js");
17941
+ const signer = await import("./signer-h69ffzx5.js");
16043
17942
  return {
16044
17943
  bitcoinAddressScript: signer.bitcoinAddressScript,
16045
17944
  createSparkSigner: signer.createSparkSigner,
@@ -16170,7 +18069,7 @@ var liveApprovals = (state, ctx, key) => {
16170
18069
  }
16171
18070
  return live;
16172
18071
  };
16173
- var backend = async (state, ctx) => {
18072
+ var backend2 = async (state, ctx) => {
16174
18073
  state.backendPromise ??= (async () => {
16175
18074
  try {
16176
18075
  return await ctx.platform.backends.spark();
@@ -16236,7 +18135,7 @@ var signerFor = async (state, ctx, account, requestSession) => {
16236
18135
  } catch (error) {
16237
18136
  throw mapError(state, error);
16238
18137
  }
16239
- const crypto2 = await backend(state, ctx);
18138
+ const crypto2 = await backend2(state, ctx);
16240
18139
  try {
16241
18140
  const signer = rt.createSparkSigner({
16242
18141
  crypto: crypto2,
@@ -16253,7 +18152,7 @@ var signerFor = async (state, ctx, account, requestSession) => {
16253
18152
  wipe(accountKey);
16254
18153
  }
16255
18154
  };
16256
- var transferCovered = (outflow, intent) => outflow.receivers.every((receiver) => intent.receivers.some((wanted) => equalBytes(wanted.identityPublicKey, receiver.identityPublicKey) && receiver.amountSats <= wanted.amountSats));
18155
+ var transferCovered = (outflow, intent) => outflow.receivers.every((receiver) => intent.receivers.some((wanted) => equalBytes2(wanted.identityPublicKey, receiver.identityPublicKey) && receiver.amountSats <= wanted.amountSats));
16257
18156
  var lightningCovered = async (state, rt, key, network, outflow, approval, intent) => {
16258
18157
  const signer = state.signers.get(key);
16259
18158
  const { paymentHash } = approval.decoded;
@@ -16266,7 +18165,7 @@ var lightningCovered = async (state, rt, key, network, outflow, approval, intent
16266
18165
  sspIdentityPublicKey: rt.sparkNetworkConfig(network).ssp.identityPublicKey,
16267
18166
  identityPublicKey: await signer.identityPublicKey()
16268
18167
  });
16269
- if (!equalBytes(expected, outflow.htlcOutputScript)) {
18168
+ if (!equalBytes2(expected, outflow.htlcOutputScript)) {
16270
18169
  return false;
16271
18170
  }
16272
18171
  const fresh = outflow.leaves.filter((leaf) => !approval.spentLeaves.has(bytesToHex(leaf.publicKey)));
@@ -16284,7 +18183,7 @@ var exitCovered = (outflow, approval, intent) => {
16284
18183
  if (addressScript === undefined) {
16285
18184
  return false;
16286
18185
  }
16287
- const pays = outflow.exitOutputs.some((output) => equalBytes(output.script, addressScript) && output.amountSats >= intent.amountSats);
18186
+ const pays = outflow.exitOutputs.some((output) => equalBytes2(output.script, addressScript) && output.amountSats >= intent.amountSats);
16288
18187
  if (!pays) {
16289
18188
  return false;
16290
18189
  }
@@ -16303,7 +18202,7 @@ var onchainCovered = (rt, outflow, approval, intent) => {
16303
18202
  if (addressScript === undefined) {
16304
18203
  return false;
16305
18204
  }
16306
- const every = outflow.outputs.every((output) => equalBytes(output.script, rt.EPHEMERAL_ANCHOR_SCRIPT) || equalBytes(output.script, addressScript));
18205
+ const every = outflow.outputs.every((output) => equalBytes2(output.script, rt.EPHEMERAL_ANCHOR_SCRIPT) || equalBytes2(output.script, addressScript));
16307
18206
  if (!every) {
16308
18207
  return false;
16309
18208
  }
@@ -16317,13 +18216,13 @@ var tokenCovered = async (state, key, outflow, intent) => {
16317
18216
  }
16318
18217
  const identity = await signer.identityPublicKey();
16319
18218
  return outflow.outputs.every((output) => {
16320
- if (equalBytes(output.ownerPublicKey, identity)) {
18219
+ if (equalBytes2(output.ownerPublicKey, identity)) {
16321
18220
  return true;
16322
18221
  }
16323
- if (!equalBytes(output.tokenIdentifier, intent.tokenIdentifier)) {
18222
+ if (!equalBytes2(output.tokenIdentifier, intent.tokenIdentifier)) {
16324
18223
  return false;
16325
18224
  }
16326
- return intent.receivers.some((wanted) => equalBytes(wanted.ownerPublicKey, output.ownerPublicKey) && output.amount <= BigInt(wanted.amount));
18225
+ return intent.receivers.some((wanted) => equalBytes2(wanted.ownerPublicKey, output.ownerPublicKey) && output.amount <= BigInt(wanted.amount));
16327
18226
  });
16328
18227
  };
16329
18228
  var authorizeWithCtx = async (state, ctx, account, outflow) => {
@@ -16525,6 +18424,22 @@ function collectTransferables(value, out, depth = 0) {
16525
18424
  }
16526
18425
  return out;
16527
18426
  }
18427
+ function openChecked(dek, record) {
18428
+ const plaintext = openRecord(dek, record);
18429
+ if (record.kind === "entropy") {
18430
+ try {
18431
+ const { entropy, passphrase } = splitWalletSecret(parseEntropyHeader(record.header), plaintext);
18432
+ wipe(entropy);
18433
+ if (passphrase !== undefined) {
18434
+ wipe(passphrase);
18435
+ }
18436
+ } catch (error) {
18437
+ wipe(plaintext);
18438
+ throw error;
18439
+ }
18440
+ }
18441
+ return plaintext;
18442
+ }
16528
18443
  function isMethodName(method) {
16529
18444
  return method in METHODS;
16530
18445
  }
@@ -16587,11 +18502,11 @@ function startKernel(host, port) {
16587
18502
  for (const record of next.records) {
16588
18503
  const prior = before.get(`${record.kind}/${record.id}`);
16589
18504
  if (prior === undefined) {
16590
- opened.push({ kind: record.kind, id: record.id, plaintext: openRecord(dek, record) });
18505
+ opened.push({ kind: record.kind, id: record.id, plaintext: openChecked(dek, record) });
16591
18506
  } else {
16592
18507
  before.delete(`${record.kind}/${record.id}`);
16593
- if (prior.header !== record.header || !equalBytes(prior.sealed, record.sealed)) {
16594
- opened.push({ kind: record.kind, id: record.id, plaintext: openRecord(dek, record) });
18508
+ if (prior.header !== record.header || !equalBytes2(prior.sealed, record.sealed)) {
18509
+ opened.push({ kind: record.kind, id: record.id, plaintext: openChecked(dek, record) });
16595
18510
  }
16596
18511
  }
16597
18512
  }
@@ -16613,7 +18528,7 @@ function startKernel(host, port) {
16613
18528
  const priorFactors = new Map(prev.factors.map((factor) => [factor.id, factor]));
16614
18529
  for (const factor of next.factors) {
16615
18530
  const prior = priorFactors.get(factor.id);
16616
- const changed = prior === undefined || prior.header !== factor.header || !equalBytes(prior.sealed, factor.sealed);
18531
+ const changed = prior === undefined || prior.header !== factor.header || !equalBytes2(prior.sealed, factor.sealed);
16617
18532
  if (changed && !factorBindingOk(dek, factor)) {
16618
18533
  throw new KernelError("integrity", "factor binding does not match the vault", undefined, true);
16619
18534
  }