@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 "./worker-366p4fej.js";
70
+ } from "./worker-k5etevb7.js";
67
71
  var __chunkGraphs;
68
72
  var __chunkSeen;
69
73
  var __chunkNonce;
@@ -94,7 +98,7 @@ var __chunks = (base, ids, nodes, entry) => {
94
98
  __chunkSeen ||= {};
95
99
  __preload(ids[entry], 1);
96
100
  };
97
- __chunks(import.meta.url,["y76qxfny","gs57sjgx","1vpxmqwn","366p4fej","gsare3mw"],[["./kernel.worker.js",3],["./signer-gs57sjgx.js",3,4],["./browser-1vpxmqwn.js",4],["./worker-366p4fej.js"],["./worker-gsare3mw.js"]],0);
101
+ __chunks(import.meta.url,["tbfpcecm","h69ffzx5","1vpxmqwn","k5etevb7","gsare3mw"],[["./kernel.worker.js",3],["./signer-h69ffzx5.js",3,4],["./browser-1vpxmqwn.js",4],["./worker-k5etevb7.js"],["./worker-gsare3mw.js"]],0);
98
102
  // ../../node_modules/.bun/@qntx+nostr@0.15.3+ea9f70ecde856c26/node_modules/@qntx/nostr/dist/util-BcRBO6o-.mjs
99
103
  var NostrError = class extends Error {
100
104
  name = "NostrError";
@@ -516,7 +520,7 @@ function checkOpts2(defaults, opts) {
516
520
  const merged = Object.assign(defaults, opts);
517
521
  return merged;
518
522
  }
519
- function equalBytes(a, b) {
523
+ function equalBytes2(a, b) {
520
524
  a = abytes3(a);
521
525
  b = abytes3(b);
522
526
  if (a.length !== b.length)
@@ -1479,7 +1483,7 @@ var _poly1305_aead = (xorStream) => (key, nonce, AAD) => {
1479
1483
  const data = ciphertext.subarray(0, -tagLength);
1480
1484
  const passedTag = ciphertext.subarray(-tagLength);
1481
1485
  const tag = computeTag(xorStream, key, nonce, data, AAD);
1482
- if (!equalBytes(passedTag, tag)) {
1486
+ if (!equalBytes2(passedTag, tag)) {
1483
1487
  clean2(tag);
1484
1488
  throw new Error("invalid tag");
1485
1489
  }
@@ -1680,7 +1684,7 @@ function decrypt3(payload, conversationKey, opts) {
1680
1684
  const { nonce, ciphertext, mac } = decodePayload(payload, opts?.maxPayloadChars ?? DEFAULT_MAX_PAYLOAD_CHARS);
1681
1685
  const { chacha_key, chacha_nonce, hmac_key } = getMessageKeys(conversationKey, nonce);
1682
1686
  const calculatedMac = hmacAad(hmac_key, ciphertext, nonce);
1683
- if (!equalBytes(calculatedMac, mac))
1687
+ if (!equalBytes2(calculatedMac, mac))
1684
1688
  throw new CryptoError("invalid MAC");
1685
1689
  return unpad(chacha20(chacha_key, chacha_nonce, ciphertext));
1686
1690
  }
@@ -1853,7 +1857,7 @@ class KernelError extends Error {
1853
1857
  this.corrupted = corrupted;
1854
1858
  }
1855
1859
  }
1856
- // ../wallet/dist/core-Cq5h9X0X.mjs
1860
+ // ../wallet/dist/core-D-NCx1CQ.mjs
1857
1861
  var ValidationError = class extends Error {
1858
1862
  name = "ValidationError";
1859
1863
  };
@@ -2068,8 +2072,10 @@ var walletInfo = obj({
2068
2072
  origin: union(literal("passkey"), literal("mnemonic")),
2069
2073
  words: union(literal(12), literal(15), literal(18), literal(21), literal(24)),
2070
2074
  backup: union(literal("none"), literal("passkey"), literal("mnemonic")),
2075
+ passphrase: bool,
2071
2076
  createdAt: safeTime
2072
2077
  });
2078
+ var passphraseBytes = bytes(1, 1024);
2073
2079
  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"));
2074
2080
  var createdResult = obj({
2075
2081
  wallet: walletInfo,
@@ -2142,7 +2148,8 @@ var CORE_METHODS = {
2142
2148
  presence: true,
2143
2149
  params: obj({
2144
2150
  draft: draftId,
2145
- answers: arr(bytes(1, 64), 3, 3)
2151
+ answers: arr(bytes(1, 64), 3, 3),
2152
+ passphrase: opt(passphraseBytes)
2146
2153
  }),
2147
2154
  result: createdResult
2148
2155
  },
@@ -2179,10 +2186,15 @@ var CORE_METHODS = {
2179
2186
  params: obj({
2180
2187
  envelope: str(4000000),
2181
2188
  backupFactor: backupUnlockFactor,
2189
+ passphrases: opt(arr(obj({
2190
+ walletId,
2191
+ passphrase: passphraseBytes
2192
+ }), 1000)),
2182
2193
  factor: opt(factor)
2183
2194
  }),
2184
2195
  result: obj({
2185
2196
  wallets: arr(walletInfo, 1000),
2197
+ passphraseRequired: arr(str(128), 1000),
2186
2198
  session: sessionId
2187
2199
  })
2188
2200
  },
@@ -2191,6 +2203,7 @@ var CORE_METHODS = {
2191
2203
  presence: true,
2192
2204
  params: obj({
2193
2205
  mnemonic: bytes(1, 1024),
2206
+ passphrase: opt(passphraseBytes),
2194
2207
  factor: opt(factor)
2195
2208
  }),
2196
2209
  result: createdResult
@@ -2202,7 +2215,10 @@ var CORE_METHODS = {
2202
2215
  verify: factor,
2203
2216
  walletId
2204
2217
  }),
2205
- result: bytes(16, 1024)
2218
+ result: obj({
2219
+ mnemonic: bytes(16, 1024),
2220
+ passphrase: opt(passphraseBytes)
2221
+ })
2206
2222
  },
2207
2223
  "wallet.delete": {
2208
2224
  session: true,
@@ -2221,7 +2237,7 @@ var CORE_METHODS = {
2221
2237
  }
2222
2238
  };
2223
2239
 
2224
- // ../wallet/dist/protocol-DbpLncEB.mjs
2240
+ // ../wallet/dist/protocol-DDz4nlYK.mjs
2225
2241
  var MAX_FACTOR_CHARS = 512;
2226
2242
  var MAX_STRING_BYTES = 64000;
2227
2243
  var MAX_PAYLOAD_CHARS = 1400000;
@@ -2246,7 +2262,8 @@ var backupEnvelope = obj({
2246
2262
  var backupHeader = obj({ wallets: arr(obj({
2247
2263
  walletId: str(128),
2248
2264
  origin: union(literal("mnemonic"), literal("passkey")),
2249
- words: union(literal(12), literal(15), literal(18), literal(21), literal(24))
2265
+ words: union(literal(12), literal(15), literal(18), literal(21), literal(24)),
2266
+ passphrase: opt(literal(true))
2250
2267
  }), 1000) });
2251
2268
  var backupEnvelopeText = str(MAX_ENVELOPE_CHARS);
2252
2269
  var backupInfo = obj({
@@ -3987,6 +4004,7 @@ function encodeHeader(header) {
3987
4004
  walletId: header.walletId,
3988
4005
  origin: header.origin,
3989
4006
  words: header.words,
4007
+ ...header.passphrase === true ? { passphrase: true } : {},
3990
4008
  backup: header.backup,
3991
4009
  createdAt: header.createdAt
3992
4010
  });
@@ -4005,15 +4023,21 @@ function asWords(value) {
4005
4023
  }
4006
4024
  function parseEntropyHeader(text) {
4007
4025
  const object = headerObject(text);
4008
- expectKeys(object, ["walletId", "origin", "words", "backup", "createdAt"]);
4026
+ const flagged = Object.hasOwn(object, "passphrase");
4027
+ expectKeys(object, flagged ? ["walletId", "origin", "words", "passphrase", "backup", "createdAt"] : ["walletId", "origin", "words", "backup", "createdAt"]);
4009
4028
  const { backup } = object;
4010
4029
  if (backup !== "none" && backup !== "passkey" && backup !== "mnemonic") {
4011
4030
  throw headerFailure();
4012
4031
  }
4032
+ const origin = asEntropyOrigin(object["origin"]);
4033
+ if (flagged && (object["passphrase"] !== true || origin !== "mnemonic")) {
4034
+ throw headerFailure();
4035
+ }
4013
4036
  return {
4014
4037
  walletId: asWalletId(object["walletId"]),
4015
- origin: asEntropyOrigin(object["origin"]),
4038
+ origin,
4016
4039
  words: asWords(object["words"]),
4040
+ ...flagged ? { passphrase: true } : {},
4017
4041
  backup,
4018
4042
  createdAt: asCreatedAt(object["createdAt"])
4019
4043
  };
@@ -4149,7 +4173,7 @@ function factorBindingOk(dek, stored) {
4149
4173
  }
4150
4174
  const expected = dek.use((bytes) => factorBinding(bytes, factorContext(stored.kind, stored.id), stored.header));
4151
4175
  try {
4152
- return equalBytes(expected, sealed.subarray(33, 65));
4176
+ return equalBytes2(expected, sealed.subarray(33, 65));
4153
4177
  } finally {
4154
4178
  wipe(expected);
4155
4179
  }
@@ -4160,7 +4184,7 @@ function wrapDek(dek, factorPk, factor, random) {
4160
4184
  const ephPk = x25519.getPublicKey(eph);
4161
4185
  const shared = x25519.getSharedSecret(eph, factorPk);
4162
4186
  try {
4163
- if (equalBytes(shared, ZERO32)) {
4187
+ if (equalBytes2(shared, ZERO32)) {
4164
4188
  throw new KernelError("integrity", "weak factor public key");
4165
4189
  }
4166
4190
  const wrapKey = hkdf(sha256, shared, concatBytes(ephPk, factorPk), WRAP_INFO, 32);
@@ -4187,7 +4211,7 @@ function unwrapDek(kek, stored) {
4187
4211
  const factorSk = hkdf(sha256, kek, new Uint8Array(0), FACTOR_KEY_INFO, 32);
4188
4212
  try {
4189
4213
  const factorPk = x25519.getPublicKey(factorSk);
4190
- if (!equalBytes(factorPk, factorHeaderPublicKey(stored))) {
4214
+ if (!equalBytes2(factorPk, factorHeaderPublicKey(stored))) {
4191
4215
  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");
4192
4216
  }
4193
4217
  const { sealed } = stored;
@@ -4203,7 +4227,7 @@ function unwrapDek(kek, stored) {
4203
4227
  throw corruptError("invalid factor ephemeral key");
4204
4228
  }
4205
4229
  try {
4206
- if (equalBytes(shared, ZERO32)) {
4230
+ if (equalBytes2(shared, ZERO32)) {
4207
4231
  throw corruptError("weak factor ephemeral key");
4208
4232
  }
4209
4233
  const wrapKey = hkdf(sha256, shared, concatBytes(ephPk, factorPk), WRAP_INFO, 32);
@@ -4215,7 +4239,7 @@ function unwrapDek(kek, stored) {
4215
4239
  throw corruptError("factor wrapping failed authentication");
4216
4240
  }
4217
4241
  const expected = factorBinding(dekBytes, factorContext(stored.kind, stored.id), stored.header);
4218
- const bound = equalBytes(expected, binding);
4242
+ const bound = equalBytes2(expected, binding);
4219
4243
  wipe(expected);
4220
4244
  if (!bound) {
4221
4245
  wipe(dekBytes);
@@ -4408,7 +4432,7 @@ async function verifyFactor(platform, image, factor, dek, prompt) {
4408
4432
  try {
4409
4433
  const opened = unwrapDek(kek, stored);
4410
4434
  try {
4411
- const same = opened.use((a) => dek.use((b) => equalBytes(a, b)));
4435
+ const same = opened.use((a) => dek.use((b) => equalBytes2(a, b)));
4412
4436
  if (same) {
4413
4437
  return;
4414
4438
  }
@@ -4494,6 +4518,28 @@ function sealRecord(platform, dek, kind, id, header, plaintext) {
4494
4518
  function openRecord(dek, record) {
4495
4519
  return dek.use((bytes) => open(bytes, record.sealed, recordContext(record.kind, record.id), record.header));
4496
4520
  }
4521
+ var MAX_PASSPHRASE_BYTES = 1024;
4522
+ function splitWalletSecret(header, plaintext) {
4523
+ const entropyLength = header.words / 3 * 4;
4524
+ const extra = plaintext.length - entropyLength;
4525
+ const valid = header.passphrase === true ? extra >= 1 && extra <= MAX_PASSPHRASE_BYTES : extra === 0;
4526
+ if (!valid) {
4527
+ throw new KernelError("integrity", "wallet record does not match its header");
4528
+ }
4529
+ return {
4530
+ entropy: plaintext.slice(0, entropyLength),
4531
+ passphrase: header.passphrase === true ? plaintext.slice(entropyLength) : undefined
4532
+ };
4533
+ }
4534
+ function openWalletSecret(dek, record) {
4535
+ const header = parseEntropyHeader(record.header);
4536
+ const plaintext = openRecord(dek, record);
4537
+ try {
4538
+ return splitWalletSecret(header, plaintext);
4539
+ } finally {
4540
+ wipe(plaintext);
4541
+ }
4542
+ }
4497
4543
  function findRecord(image, kind, id) {
4498
4544
  const record = image.records.find((r) => r.kind === kind && r.id === id);
4499
4545
  if (record === undefined) {
@@ -4548,10 +4594,31 @@ function walletInfo2(header) {
4548
4594
  origin: header.origin,
4549
4595
  words: header.words,
4550
4596
  backup: header.backup,
4597
+ passphrase: header.passphrase === true,
4551
4598
  createdAt: header.createdAt
4552
4599
  };
4553
4600
  }
4554
4601
 
4602
+ // ../wallet-kernel/src/commands/passphrase.ts
4603
+ function normalizePassphrase(wire) {
4604
+ const normalized = utf8ToBytes(decodeUtf8Secret(wire).normalize("NFKD"));
4605
+ if (normalized.length === 0 || normalized.length > MAX_PASSPHRASE_BYTES) {
4606
+ normalized.fill(0);
4607
+ throw new KernelError("invalid-input", "passphrase must be 1-1024 bytes");
4608
+ }
4609
+ return normalized;
4610
+ }
4611
+ function passphraseText(passphrase) {
4612
+ if (passphrase === undefined) {
4613
+ return "";
4614
+ }
4615
+ try {
4616
+ return new TextDecoder("utf-8", { fatal: true }).decode(passphrase);
4617
+ } catch {
4618
+ throw new KernelError("integrity", "wallet passphrase is not valid UTF-8");
4619
+ }
4620
+ }
4621
+
4555
4622
  // ../wallet-kernel/src/derive/hd.ts
4556
4623
  function masterKey(seed) {
4557
4624
  return HDKey.fromMasterSeed(seed);
@@ -6862,11 +6929,11 @@ async function seedFromMnemonic(mnemonic, passphrase, pbkdf2) {
6862
6929
  wipe(password, salt);
6863
6930
  }
6864
6931
  }
6865
- async function seedFromEntropy(entropy, pbkdf2) {
6866
- return seedFromMnemonic(mnemonicFromEntropy(entropy), "", pbkdf2);
6932
+ async function seedFromEntropy(entropy, passphrase, pbkdf2) {
6933
+ return seedFromMnemonic(mnemonicFromEntropy(entropy), passphrase, pbkdf2);
6867
6934
  }
6868
- async function withSeed(pbkdf2, entropy, use) {
6869
- const seed = await seedFromEntropy(entropy, pbkdf2);
6935
+ async function withSeed(pbkdf2, entropy, passphrase, use) {
6936
+ const seed = await seedFromEntropy(entropy, passphrase, pbkdf2);
6870
6937
  try {
6871
6938
  return await use(seed);
6872
6939
  } finally {
@@ -7047,11 +7114,14 @@ class Session {
7047
7114
 
7048
7115
  // ../wallet-kernel/src/commands/vault.ts
7049
7116
  async function withWalletSeed(pbkdf2, dek, record, use) {
7050
- const entropy = openRecord(dek, record);
7117
+ const { entropy, passphrase } = openWalletSecret(dek, record);
7051
7118
  try {
7052
- return await withSeed(pbkdf2, entropy, use);
7119
+ return await withSeed(pbkdf2, entropy, passphraseText(passphrase), use);
7053
7120
  } finally {
7054
7121
  wipe(entropy);
7122
+ if (passphrase !== undefined) {
7123
+ wipe(passphrase);
7124
+ }
7055
7125
  }
7056
7126
  }
7057
7127
  var EMPTY_IMAGE = { meta: undefined, records: [], factors: [] };
@@ -7137,16 +7207,16 @@ async function removeFactor(ctx, params, requestSession) {
7137
7207
  }
7138
7208
 
7139
7209
  // ../wallet-kernel/src/commands/wallets.ts
7140
- async function deriveWalletMaterial(platform, entropy) {
7141
- return withSeed(platform.pbkdf2, entropy, (seed) => {
7210
+ async function deriveWalletMaterial(platform, entropy, passphrase) {
7211
+ return withSeed(platform.pbkdf2, entropy, passphraseText(passphrase), (seed) => {
7142
7212
  const master = masterKey(seed);
7143
7213
  return { master, walletId: walletIdOf(master) };
7144
7214
  });
7145
7215
  }
7146
- async function walletMaterial(platform, entropy, origin, words) {
7147
- const { master, walletId } = await deriveWalletMaterial(platform, entropy);
7216
+ async function walletMaterial(platform, entropy, passphrase, origin, words) {
7217
+ const { master, walletId } = await deriveWalletMaterial(platform, entropy, passphrase);
7148
7218
  try {
7149
- return { walletId, entropy, words, origin };
7219
+ return { walletId, entropy, passphrase, words, origin };
7150
7220
  } finally {
7151
7221
  master.wipePrivateData();
7152
7222
  }
@@ -7157,18 +7227,23 @@ function walletInfoOf(material, backup, createdAt) {
7157
7227
  origin: material.origin,
7158
7228
  words: material.words,
7159
7229
  backup,
7230
+ ...material.passphrase === undefined ? {} : { passphrase: true },
7160
7231
  createdAt
7161
7232
  });
7162
7233
  }
7234
+ function walletSecretPlaintext(entropy, passphrase) {
7235
+ return passphrase === undefined ? new Uint8Array(entropy) : concatBytes(entropy, passphrase);
7236
+ }
7163
7237
  function walletRecord(ctx, dek, material, backup, createdAt) {
7164
7238
  const header = encodeHeader({
7165
7239
  walletId: material.walletId,
7166
7240
  origin: material.origin,
7167
7241
  words: material.words,
7242
+ ...material.passphrase === undefined ? {} : { passphrase: true },
7168
7243
  backup,
7169
7244
  createdAt
7170
7245
  });
7171
- return sealRecord(ctx.platform, dek, "entropy", material.walletId, header, new Uint8Array(material.entropy));
7246
+ return sealRecord(ctx.platform, dek, "entropy", material.walletId, header, walletSecretPlaintext(material.entropy, material.passphrase));
7172
7247
  }
7173
7248
  function gate(ctx, factor, requestSession) {
7174
7249
  if (ctx.image.meta === undefined) {
@@ -7278,10 +7353,20 @@ async function storedFactorForPending(ctx, pending, dek) {
7278
7353
  return { kind: pending.kind, id, header, sealed };
7279
7354
  }
7280
7355
  async function confirmMnemonic(ctx, params) {
7356
+ const passphrase = params.passphrase === undefined ? undefined : normalizePassphrase(params.passphrase);
7357
+ try {
7358
+ return await confirmWithPassphrase(ctx, params, passphrase);
7359
+ } finally {
7360
+ if (passphrase !== undefined) {
7361
+ wipe(passphrase);
7362
+ }
7363
+ }
7364
+ }
7365
+ async function confirmWithPassphrase(ctx, params, passphrase) {
7281
7366
  const draft = ctx.session.getDraft(params.draft);
7282
7367
  const allMatch = draft.expected.every((expected, i) => {
7283
7368
  const answer = params.answers[i];
7284
- return answer !== undefined && answer.length === expected.length && equalBytes(answer, expected);
7369
+ return answer !== undefined && answer.length === expected.length && equalBytes2(answer, expected);
7285
7370
  });
7286
7371
  for (const answer of params.answers) {
7287
7372
  wipe(answer);
@@ -7292,7 +7377,7 @@ async function confirmMnemonic(ctx, params) {
7292
7377
  const taken = ctx.session.takeDraft(params.draft);
7293
7378
  try {
7294
7379
  const entropy = taken.entropy.use((bytes) => new Uint8Array(bytes));
7295
- const material = await walletMaterial(ctx.platform, entropy, "mnemonic", taken.words);
7380
+ const material = await walletMaterial(ctx.platform, entropy, passphrase, "mnemonic", taken.words);
7296
7381
  try {
7297
7382
  ensureNewWallet(ctx, material);
7298
7383
  const createdAt = ctx.platform.now();
@@ -7333,17 +7418,31 @@ function mnemonicWords(entropy) {
7333
7418
  }
7334
7419
  async function importMnemonic(ctx, params, requestSession) {
7335
7420
  const gated = gate(ctx, params.factor, requestSession);
7336
- const text = decodeUtf8Secret(params.mnemonic);
7337
- const entropy = entropyFromMnemonic(text);
7338
- const material = await walletMaterial(ctx.platform, entropy, "mnemonic", mnemonicWords(entropy));
7421
+ let text;
7339
7422
  try {
7423
+ text = decodeUtf8Secret(params.mnemonic);
7424
+ } catch (error) {
7425
+ params.passphrase?.fill(0);
7426
+ throw error;
7427
+ }
7428
+ let passphrase;
7429
+ let entropy;
7430
+ try {
7431
+ passphrase = params.passphrase === undefined ? undefined : normalizePassphrase(params.passphrase);
7432
+ entropy = entropyFromMnemonic(text);
7433
+ const material = await walletMaterial(ctx.platform, entropy, passphrase, "mnemonic", mnemonicWords(entropy));
7340
7434
  ensureNewWallet(ctx, material);
7341
7435
  const createdAt = ctx.platform.now();
7342
7436
  const record = walletRecord(ctx, gated.dek, material, "mnemonic", createdAt);
7343
7437
  const session = await commitRecords(ctx, gated, params.factor, [record]);
7344
7438
  return { wallet: walletInfoOf(material, "mnemonic", createdAt), session };
7345
7439
  } finally {
7346
- wipe(entropy);
7440
+ if (entropy !== undefined) {
7441
+ wipe(entropy);
7442
+ }
7443
+ if (passphrase !== undefined) {
7444
+ wipe(passphrase);
7445
+ }
7347
7446
  }
7348
7447
  }
7349
7448
  var PURPOSE_WALLET = 1;
@@ -7401,7 +7500,7 @@ async function createWithPasskey(ctx, params, requestSession) {
7401
7500
  throw error;
7402
7501
  }
7403
7502
  const entropy = entropyFromPrf(prf.prfWallet);
7404
- const material = await walletMaterial(ctx.platform, entropy, "passkey", 12);
7503
+ const material = await walletMaterial(ctx.platform, entropy, undefined, "passkey", 12);
7405
7504
  try {
7406
7505
  ensureNewWallet(ctx, material);
7407
7506
  const createdAt = ctx.platform.now();
@@ -7536,21 +7635,23 @@ function collectContents(ctx, dek) {
7536
7635
  continue;
7537
7636
  }
7538
7637
  const header = parseEntropyHeader(record.header);
7539
- const plaintext = openRecord(dek, record);
7540
- try {
7541
- wallets.push({
7542
- walletId: record.id,
7543
- origin: header.origin,
7544
- words: header.words,
7545
- entropy: plaintext
7546
- });
7547
- } catch (error) {
7548
- plaintext.fill(0);
7549
- throw error;
7550
- }
7638
+ const { entropy, passphrase } = openWalletSecret(dek, record);
7639
+ passphrase?.fill(0);
7640
+ wallets.push({
7641
+ walletId: record.id,
7642
+ origin: header.origin,
7643
+ words: header.words,
7644
+ ...header.passphrase === true ? { passphrase: true } : {},
7645
+ entropy
7646
+ });
7551
7647
  }
7552
7648
  const header = JSON.stringify({
7553
- wallets: wallets.map(({ walletId, origin, words }) => ({ walletId, origin, words }))
7649
+ wallets: wallets.map(({ walletId, origin, words, passphrase }) => ({
7650
+ walletId,
7651
+ origin,
7652
+ words,
7653
+ ...passphrase === true ? { passphrase } : {}
7654
+ }))
7554
7655
  });
7555
7656
  return { wallets, header };
7556
7657
  } catch (error) {
@@ -7744,6 +7845,25 @@ async function bekFromFactor(platform, envelope, backupFactor) {
7744
7845
  }
7745
7846
  }
7746
7847
  async function restoreBackup(ctx, params, requestSession) {
7848
+ const passphrases = new Map;
7849
+ try {
7850
+ return await restoreWithPassphrases(ctx, params, requestSession, passphrases);
7851
+ } finally {
7852
+ for (const passphrase of passphrases.values()) {
7853
+ passphrase.fill(0);
7854
+ }
7855
+ for (const entry of params.passphrases ?? []) {
7856
+ entry.passphrase.fill(0);
7857
+ }
7858
+ }
7859
+ }
7860
+ async function restoreWithPassphrases(ctx, params, requestSession, passphrases) {
7861
+ for (const entry of params.passphrases ?? []) {
7862
+ if (passphrases.has(entry.walletId)) {
7863
+ throw new KernelError("invalid-input", `duplicate passphrase for wallet ${entry.walletId}`);
7864
+ }
7865
+ passphrases.set(entry.walletId, normalizePassphrase(entry.passphrase));
7866
+ }
7747
7867
  const envelope = parseEnvelope(params.envelope);
7748
7868
  const credentials = envelope.factors.flatMap((f) => f.kind === "passkey" ? [b64.dec(f.credentialId)] : []);
7749
7869
  const bek = await bekFromFactor(ctx.platform, envelope, await backupMaterial(ctx, params.backupFactor, credentials));
@@ -7760,9 +7880,17 @@ async function restoreBackup(ctx, params, requestSession) {
7760
7880
  plaintext.fill(0);
7761
7881
  throw new KernelError("integrity", "backup: payload does not match header");
7762
7882
  }
7883
+ const flagged = new Set(header.wallets.filter((w) => w.passphrase === true).map((w) => w.walletId));
7884
+ for (const walletId of passphrases.keys()) {
7885
+ if (!flagged.has(walletId)) {
7886
+ plaintext.fill(0);
7887
+ throw new KernelError("invalid-input", `wallet ${walletId} has no passphrase`);
7888
+ }
7889
+ }
7763
7890
  const gated = gate(ctx, params.factor, requestSession);
7764
7891
  const records = [];
7765
7892
  const restored = [];
7893
+ const passphraseRequired = [];
7766
7894
  let committed = false;
7767
7895
  try {
7768
7896
  try {
@@ -7776,7 +7904,17 @@ async function restoreBackup(ctx, params, requestSession) {
7776
7904
  if (words !== expected.words) {
7777
7905
  throw new KernelError("integrity", "backup: entropy length does not match header");
7778
7906
  }
7779
- const material = await walletMaterial(ctx.platform, wallet.entropy, wallet.origin, words);
7907
+ const passphrase = passphrases.get(expected.walletId);
7908
+ if (passphrase === undefined && expected.passphrase === true) {
7909
+ if (!ctx.image.records.some((r) => r.kind === "entropy" && r.id === expected.walletId)) {
7910
+ passphraseRequired.push(expected.walletId);
7911
+ }
7912
+ continue;
7913
+ }
7914
+ const material = await walletMaterial(ctx.platform, wallet.entropy, passphrase, wallet.origin, words);
7915
+ if (passphrase !== undefined && material.walletId !== expected.walletId) {
7916
+ throw new KernelError("invalid-input", `passphrase does not match wallet ${expected.walletId}`);
7917
+ }
7780
7918
  if (material.walletId !== expected.walletId || material.origin !== expected.origin) {
7781
7919
  throw new KernelError("integrity", "backup: derived walletId does not match header");
7782
7920
  }
@@ -7793,7 +7931,7 @@ async function restoreBackup(ctx, params, requestSession) {
7793
7931
  }
7794
7932
  const session = await commitRecords(ctx, gated, params.factor, records);
7795
7933
  committed = true;
7796
- return { wallets: restored, session };
7934
+ return { wallets: restored, passphraseRequired, session };
7797
7935
  } catch (error) {
7798
7936
  if (!committed && gated.uninitialized) {
7799
7937
  gated.dek.wipe();
@@ -7817,7 +7955,7 @@ async function exportMnemonic(ctx, params, requestSession) {
7817
7955
  await verifyFactor(ctx.platform, ctx.image, params.verify, dek, corePromptFor(ctx.platform.keystore, "export-mnemonic"));
7818
7956
  const record = findRecord(ctx.image, "entropy", params.walletId);
7819
7957
  const header = parseEntropyHeader(record.header);
7820
- const entropy = openRecord(dek, record);
7958
+ const { entropy, passphrase } = openWalletSecret(dek, record);
7821
7959
  try {
7822
7960
  const exported = utf8ToBytes(mnemonicFromEntropy(entropy));
7823
7961
  if (header.backup !== "mnemonic") {
@@ -7825,13 +7963,19 @@ async function exportMnemonic(ctx, params, requestSession) {
7825
7963
  await ctx.commit([
7826
7964
  {
7827
7965
  op: "put-record",
7828
- record: sealRecord(ctx.platform, dek, "entropy", params.walletId, updated, new Uint8Array(entropy))
7966
+ record: sealRecord(ctx.platform, dek, "entropy", params.walletId, updated, walletSecretPlaintext(entropy, passphrase))
7829
7967
  }
7830
7968
  ]);
7831
7969
  }
7832
- return exported;
7970
+ return {
7971
+ mnemonic: exported,
7972
+ ...passphrase === undefined ? {} : { passphrase: new Uint8Array(passphrase) }
7973
+ };
7833
7974
  } finally {
7834
7975
  wipe(entropy);
7976
+ if (passphrase !== undefined) {
7977
+ wipe(passphrase);
7978
+ }
7835
7979
  }
7836
7980
  }
7837
7981
  async function getDataKey(ctx, params, requestSession) {
@@ -7994,632 +8138,1832 @@ class HDKey2 {
7994
8138
  }
7995
8139
  }
7996
8140
 
7997
- // ../wallet-chains/dist/index.mjs
7998
- var ChainError = class extends Error {
7999
- code;
8000
- constructor(code, message) {
8001
- super(message);
8002
- this.name = "ChainError";
8003
- this.code = code;
8141
+ // ../../node_modules/.bun/@qntx+siwx@0.8.0/node_modules/@qntx/siwx/dist/message-B6snBU4B.mjs
8142
+ var SYNTAX_MESSAGES = {
8143
+ InvalidUtf8: "invalid UTF-8",
8144
+ CarriageReturn: "CR not allowed",
8145
+ MissingPreamble: "missing preamble marker",
8146
+ MissingAccountSuffix: "missing account suffix",
8147
+ UnexpectedEof: "unexpected end of input",
8148
+ ExpectedBlankLine: "expected blank line",
8149
+ UnexpectedTrailing: "unexpected trailing content",
8150
+ ResourceSyntax: "resource line must start with '- '",
8151
+ InvalidEnvelope: "invalid off-chain message envelope"
8152
+ };
8153
+ function describe(info) {
8154
+ if (info.code === "MessageTooLarge")
8155
+ return `message exceeds maximum size of ${info.max} bytes, got ${info.length}`;
8156
+ if (info.code === "Syntax")
8157
+ return info.syntax === "MissingField" ? `invalid message syntax: missing ${info.field}` : `invalid message syntax: ${SYNTAX_MESSAGES[info.syntax]}`;
8158
+ if (info.code === "InvalidField")
8159
+ return `invalid ${info.field}: ${info.reason}`;
8160
+ if (info.code === "Mismatch")
8161
+ return `${info.field} mismatch: expected ${info.expected}, got ${JSON.stringify(info.actual)}`;
8162
+ if (info.code === "InvalidOrigin")
8163
+ return "invalid origin: not a serialized web origin";
8164
+ if (info.code === "Expired")
8165
+ return "message expired";
8166
+ if (info.code === "NotYetValid")
8167
+ return "message not yet valid";
8168
+ if (info.code === "IssuedAtTooOld")
8169
+ return "issued-at exceeds max age";
8170
+ if (info.code === "InvalidSignature")
8171
+ return `invalid signature: ${info.reason}`;
8172
+ if (info.code === "VerificationFailed")
8173
+ return "verification failed";
8174
+ if (info.code === "Unsupported")
8175
+ return `unsupported: ${info.reason}`;
8176
+ return `backend error: ${info.reason}`;
8177
+ }
8178
+ var SiwxError = class extends Error {
8179
+ info;
8180
+ constructor(info) {
8181
+ super(describe(info));
8182
+ this.name = "SiwxError";
8183
+ this.info = info;
8184
+ }
8185
+ get code() {
8186
+ return this.info.code;
8004
8187
  }
8005
8188
  };
8006
-
8007
- // ../wallet-chains/dist/account-ref-C2qrDbVT.mjs
8008
- var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8009
- var isAccountRef = (value) => {
8010
- if (!isRecord2(value) || typeof value["kind"] !== "string")
8189
+ function syntaxError(syntax, field) {
8190
+ if (syntax === "MissingField") {
8191
+ if (field === undefined)
8192
+ throw new RangeError("MissingField requires a field");
8193
+ return new SiwxError({
8194
+ code: "Syntax",
8195
+ syntax,
8196
+ field
8197
+ });
8198
+ }
8199
+ return new SiwxError({
8200
+ code: "Syntax",
8201
+ syntax
8202
+ });
8203
+ }
8204
+ function fieldError(field, reason) {
8205
+ return new SiwxError({
8206
+ code: "InvalidField",
8207
+ field,
8208
+ reason
8209
+ });
8210
+ }
8211
+ function mismatchError(field, expected, actual) {
8212
+ return new SiwxError({
8213
+ code: "Mismatch",
8214
+ field,
8215
+ expected,
8216
+ actual
8217
+ });
8218
+ }
8219
+ //! CAIP-10 `account_id`: `namespace ":" reference ":" address`.
8220
+ function everyChar(s, test) {
8221
+ const pred = typeof test === "function" ? test : (c) => test.test(c);
8222
+ for (const c of s)
8223
+ if (!pred(c))
8224
+ return false;
8225
+ return true;
8226
+ }
8227
+ function createAccountId(namespace, reference, address) {
8228
+ if (namespace.length < 3 || namespace.length > 8 || !everyChar(namespace, /[a-z0-9-]/))
8229
+ throw fieldError("chainId", "bad CAIP-2 namespace");
8230
+ if (reference.length === 0 || reference.length > 32 || !everyChar(reference, /[A-Za-z0-9_-]/))
8231
+ throw fieldError("chainId", "bad CAIP-2 reference");
8232
+ if (address.length === 0 || address.length > 128 || !everyChar(address, (c) => /[A-Za-z0-9]/.test(c) || c === "-" || c === "." || c === "%"))
8233
+ throw fieldError("address", "bad CAIP-10 address");
8234
+ return Object.freeze({
8235
+ namespace,
8236
+ reference,
8237
+ address,
8238
+ id: `${namespace}:${reference}:${address}`
8239
+ });
8240
+ }
8241
+ //! Shared pieces of the CAIP-122 text layouts (eip4361 and SIWS): the
8242
+ //! preamble infix/suffix and the optional trailing tags in fixed ABNF order.
8243
+ var MID = " wants you to sign in with your ";
8244
+ var SUFFIX = " account:";
8245
+ function optionalTags(lines, start) {
8246
+ let i = start;
8247
+ let resources;
8248
+ const take = (tag) => {
8249
+ const line = lines[i];
8250
+ if (line !== undefined && line.startsWith(tag)) {
8251
+ i++;
8252
+ return line.slice(tag.length);
8253
+ }
8254
+ };
8255
+ const expirationTime = take("Expiration Time: ");
8256
+ const notBefore = take("Not Before: ");
8257
+ const requestId = take("Request ID: ");
8258
+ if (lines[i] === "Resources:") {
8259
+ i++;
8260
+ const list = [];
8261
+ while (i < lines.length) {
8262
+ const r = lines[i] ?? "";
8263
+ if (r.startsWith("- ")) {
8264
+ list.push(r.slice(2));
8265
+ i++;
8266
+ } else if (r.startsWith("-"))
8267
+ throw syntaxError("ResourceSyntax");
8268
+ else
8269
+ throw syntaxError("UnexpectedTrailing");
8270
+ }
8271
+ resources = list;
8272
+ }
8273
+ if (i !== lines.length)
8274
+ throw syntaxError("UnexpectedTrailing");
8275
+ return {
8276
+ expirationTime,
8277
+ notBefore,
8278
+ requestId,
8279
+ resources
8280
+ };
8281
+ }
8282
+ var MAX_MESSAGE_BYTES = 16384;
8283
+ //! RFC 3986 URI validation, matching Rust `iri-string` exactly:
8284
+ //! `URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]`,
8285
+ //! `authority = [ userinfo "@" ] host [ ":" port ]`, strict dec-octet
8286
+ //! (no leading zeros), IPv6 / IPvFuture / pct-encoding.
8287
+ var UNRESERVED = /[A-Za-z0-9._~-]/;
8288
+ var SUB_DELIM = /[!$&'()*+,;=]/;
8289
+ var HEX = /[0-9A-Fa-f]/;
8290
+ function isScheme(s) {
8291
+ if (s.length === 0 || !/[A-Za-z]/.test(s.charAt(0)))
8011
8292
  return false;
8012
- if (value["kind"] === "hd")
8013
- return typeof value["walletId"] === "string" && typeof value["groupIndex"] === "number" && typeof value["template"] === "string";
8014
- return value["kind"] === "imported" && typeof value["keyId"] === "string" && typeof value["family"] === "string";
8015
- };
8016
- var requestBase = (request) => {
8017
- if (!isRecord2(request))
8018
- throw new ChainError("invalid-request", "request must be an object");
8019
- const { network, account } = request;
8020
- if (typeof network !== "string")
8021
- throw new ChainError("invalid-request", "request.network must be a string");
8022
- if (!isAccountRef(account))
8023
- throw new ChainError("invalid-request", "request.account must be an AccountRef");
8293
+ for (const c of s)
8294
+ if (!/[A-Za-z0-9+.-]/.test(c))
8295
+ return false;
8296
+ return true;
8297
+ }
8298
+ function everyPct(s, allowed) {
8299
+ for (let i = 0;i < s.length; i++) {
8300
+ const c = s.charAt(i);
8301
+ if (c === "%") {
8302
+ if (i + 2 >= s.length || !HEX.test(s.charAt(i + 1)) || !HEX.test(s.charAt(i + 2)))
8303
+ return false;
8304
+ i += 2;
8305
+ continue;
8306
+ }
8307
+ if (!allowed(c))
8308
+ return false;
8309
+ }
8310
+ return true;
8311
+ }
8312
+ function isUserinfo(s) {
8313
+ return everyPct(s, (c) => UNRESERVED.test(c) || SUB_DELIM.test(c) || c === ":");
8314
+ }
8315
+ function isRegName(s) {
8316
+ return everyPct(s, (c) => UNRESERVED.test(c) || SUB_DELIM.test(c));
8317
+ }
8318
+ function isPcharString(s) {
8319
+ return everyPct(s, (c) => UNRESERVED.test(c) || SUB_DELIM.test(c) || c === ":" || c === "@");
8320
+ }
8321
+ function isDecOctet(s) {
8322
+ if (s.length === 0 || s.length > 3)
8323
+ return false;
8324
+ if (s.length > 1 && s.startsWith("0"))
8325
+ return false;
8326
+ for (const c of s)
8327
+ if (!/[0-9]/.test(c))
8328
+ return false;
8329
+ return Number(s) <= 255;
8330
+ }
8331
+ function isIPv4(s) {
8332
+ const parts = s.split(".");
8333
+ return parts.length === 4 && parts.every(isDecOctet);
8334
+ }
8335
+ function isH16(s) {
8336
+ return s.length > 0 && s.length <= 4 && s.split("").every((c) => HEX.test(c));
8337
+ }
8338
+ function ipv6GroupCount(part) {
8339
+ if (part === "")
8340
+ return 0;
8341
+ let n = 0;
8342
+ const groups = part.split(":");
8343
+ for (const g of groups) {
8344
+ if (g === "")
8345
+ return -1;
8346
+ if (g.includes(".")) {
8347
+ if (g !== groups.at(-1) || !isIPv4(g))
8348
+ return -1;
8349
+ n += 2;
8350
+ } else if (isH16(g))
8351
+ n += 1;
8352
+ else
8353
+ return -1;
8354
+ }
8355
+ return n;
8356
+ }
8357
+ function isIPv6(s) {
8358
+ const halves = s.split("::");
8359
+ if (halves.length > 2)
8360
+ return false;
8361
+ if (halves.length === 1)
8362
+ return ipv6GroupCount(halves[0] ?? "") === 8;
8363
+ const hn = ipv6GroupCount(halves[0] ?? "");
8364
+ const tn = ipv6GroupCount(halves[1] ?? "");
8365
+ if (hn === -1 || tn === -1)
8366
+ return false;
8367
+ return hn + tn < 8;
8368
+ }
8369
+ function isIPvFuture(s) {
8370
+ const m = /^[vV]([0-9A-Fa-f]+)\.(.*)$/.exec(s);
8371
+ if (m === null)
8372
+ return false;
8373
+ const tail = m[2] ?? "";
8374
+ if (tail.length === 0)
8375
+ return false;
8376
+ for (const c of tail)
8377
+ if (!(UNRESERVED.test(c) || SUB_DELIM.test(c) || c === ":"))
8378
+ return false;
8379
+ return true;
8380
+ }
8381
+ function isHost(s) {
8382
+ if (s.startsWith("["))
8383
+ return s.endsWith("]") && (isIPv6(s.slice(1, -1)) || isIPvFuture(s.slice(1, -1)));
8384
+ if (isIPv4(s))
8385
+ return true;
8386
+ return isRegName(s);
8387
+ }
8388
+ function isAuthority(s) {
8389
+ let rest = s;
8390
+ const at = rest.lastIndexOf("@");
8391
+ if (at !== -1) {
8392
+ if (rest.indexOf("@") !== at)
8393
+ return false;
8394
+ if (!isUserinfo(rest.slice(0, at)))
8395
+ return false;
8396
+ rest = rest.slice(at + 1);
8397
+ }
8398
+ let host = rest;
8399
+ let port = "";
8400
+ if (rest.startsWith("[")) {
8401
+ const end = rest.indexOf("]");
8402
+ if (end === -1)
8403
+ return false;
8404
+ host = rest.slice(0, end + 1);
8405
+ const after = rest.slice(end + 1);
8406
+ if (after !== "") {
8407
+ if (!after.startsWith(":"))
8408
+ return false;
8409
+ port = after.slice(1);
8410
+ }
8411
+ } else {
8412
+ const colon = rest.lastIndexOf(":");
8413
+ if (colon !== -1) {
8414
+ host = rest.slice(0, colon);
8415
+ port = rest.slice(colon + 1);
8416
+ if (host.includes(":"))
8417
+ return false;
8418
+ }
8419
+ }
8420
+ if (port !== "" && !port.split("").every((c) => /[0-9]/.test(c)))
8421
+ return false;
8422
+ return isHost(host);
8423
+ }
8424
+ function isPath(s) {
8425
+ for (const seg of s.split("/"))
8426
+ if (!isPcharString(seg))
8427
+ return false;
8428
+ return true;
8429
+ }
8430
+ function isQueryOrFragment(s) {
8431
+ return everyPct(s, (c) => UNRESERVED.test(c) || SUB_DELIM.test(c) || c === ":" || c === "@" || c === "/" || c === "?");
8432
+ }
8433
+ function isUri(s) {
8434
+ const hash = s.indexOf("#");
8435
+ if (hash !== -1 && s.includes("#", hash + 1))
8436
+ return false;
8437
+ let rest = s;
8438
+ let fragment;
8439
+ if (hash !== -1) {
8440
+ fragment = rest.slice(hash + 1);
8441
+ rest = rest.slice(0, hash);
8442
+ }
8443
+ const q = rest.indexOf("?");
8444
+ let query;
8445
+ if (q !== -1) {
8446
+ query = rest.slice(q + 1);
8447
+ rest = rest.slice(0, q);
8448
+ }
8449
+ const colon = rest.indexOf(":");
8450
+ if (colon === -1)
8451
+ return false;
8452
+ if (!isScheme(rest.slice(0, colon)))
8453
+ return false;
8454
+ let hier = rest.slice(colon + 1);
8455
+ if (hier.startsWith("//")) {
8456
+ hier = hier.slice(2);
8457
+ const slash = hier.indexOf("/");
8458
+ const authority = slash === -1 ? hier : hier.slice(0, slash);
8459
+ const path = slash === -1 ? "" : hier.slice(slash);
8460
+ if (!isAuthority(authority))
8461
+ return false;
8462
+ if (!isPath(path))
8463
+ return false;
8464
+ } else if (!isPath(hier))
8465
+ return false;
8466
+ if (query !== undefined && !isQueryOrFragment(query))
8467
+ return false;
8468
+ if (fragment !== undefined && !isQueryOrFragment(fragment))
8469
+ return false;
8470
+ return true;
8471
+ }
8472
+ //! Lexical RFC 3339 `date-time` + instant, mirroring Rust `Timestamp`.
8473
+ var SHAPE = /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/;
8474
+ function daysFromCivil(y, m, d) {
8475
+ const yy = m <= 2 ? y - 1 : y;
8476
+ const era = Math.floor((yy >= 0 ? yy : yy - 399) / 400);
8477
+ const yoe = yy - era * 400;
8478
+ const doy = Math.floor((153 * (m > 2 ? m - 3 : m + 9) + 2) / 5) + d - 1;
8479
+ const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;
8480
+ return era * 146097 + doe - 719468;
8481
+ }
8482
+ function daysInMonth(year, month) {
8483
+ return [
8484
+ 31,
8485
+ year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28,
8486
+ 31,
8487
+ 30,
8488
+ 31,
8489
+ 30,
8490
+ 31,
8491
+ 31,
8492
+ 30,
8493
+ 31,
8494
+ 30,
8495
+ 31
8496
+ ][month - 1] ?? 0;
8497
+ }
8498
+ function parseTimestamp(s) {
8499
+ const m = SHAPE.exec(s);
8500
+ if (m === null)
8501
+ return;
8502
+ const [, ys, mos, ds, hs, mis, ss, frac, tz] = m;
8503
+ const year = Number(ys);
8504
+ const month = Number(mos);
8505
+ const day = Number(ds);
8506
+ const hour = Number(hs);
8507
+ const minute = Number(mis);
8508
+ const second = Number(ss);
8509
+ if (month < 1 || month > 12)
8510
+ return;
8511
+ if (day < 1 || day > daysInMonth(year, month))
8512
+ return;
8513
+ if (hour > 23 || minute > 59 || second > 59)
8514
+ return;
8515
+ let ms = daysFromCivil(year, month, day) * 86400000 + hour * 3600000 + minute * 60000 + second * 1000;
8516
+ if (frac !== undefined && frac.length > 1)
8517
+ ms += Number(frac.slice(1, 4).padEnd(3, "0"));
8518
+ if (tz !== undefined && tz !== "Z" && tz !== "z") {
8519
+ const oh = Number(tz.slice(1, 3));
8520
+ const om = Number(tz.slice(4, 6));
8521
+ if (oh > 23 || om > 59)
8522
+ return;
8523
+ const off = (oh * 60 + om) * 60000;
8524
+ ms += tz.startsWith("+") ? -off : off;
8525
+ }
8526
+ if (!Number.isFinite(ms))
8527
+ return;
8024
8528
  return {
8025
- network,
8026
- account
8529
+ lexeme: s,
8530
+ epochMs: Math.trunc(ms)
8027
8531
  };
8028
- };
8532
+ }
8533
+ //! Strict UTF-8 helpers.
8534
+ //!
8535
+ //! `TextEncoder`/`TextDecoder` exist on every supported platform (Node,
8536
+ //! browsers, Hermes). Decoding must reject exactly what Rust
8537
+ //! `str::from_utf8` rejects — overlongs, surrogates, > U+10FFFF,
8538
+ //! truncated sequences — so `fatal: true` is used (which follows the
8539
+ //! WHATWG fatal algorithm and rejects all of those).
8540
+ var encoder = new TextEncoder;
8541
+ var fatalDecoder = new TextDecoder("utf-8", { fatal: true });
8542
+ function utf8Encode(text) {
8543
+ return encoder.encode(text);
8544
+ }
8545
+ function utf8Decode(bytes) {
8546
+ try {
8547
+ return fatalDecoder.decode(bytes);
8548
+ } catch {
8549
+ return;
8550
+ }
8551
+ }
8552
+ function utf8ByteLength(text) {
8553
+ return encoder.encode(text).length;
8554
+ }
8555
+ //! CAIP-122 abstract data model: lexical `MessageFields` and the
8556
+ //! validated `Message` produced by `createMessage` (single validation
8557
+ //! path, same check order as Rust `Message::new`).
8558
+ var STATEMENT_CHARS = /* @__PURE__ */ new Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;= ");
8559
+ function isCaip10Address(s) {
8560
+ if (s.length === 0 || s.length > 128)
8561
+ return false;
8562
+ for (const c of s)
8563
+ if (!/[A-Za-z0-9]/.test(c) && c !== "-" && c !== "." && c !== "%")
8564
+ return false;
8565
+ return true;
8566
+ }
8567
+ function createMessage(fields) {
8568
+ if (fields.scheme !== undefined && !isScheme(fields.scheme))
8569
+ throw fieldError("scheme", "not an RFC 3986 scheme");
8570
+ if (fields.domain.length === 0)
8571
+ throw fieldError("domain", "empty");
8572
+ if (fields.domain.includes("@"))
8573
+ throw fieldError("domain", "userinfo not allowed");
8574
+ if (fields.domain.startsWith(":"))
8575
+ throw fieldError("domain", "empty host");
8576
+ if (!isAuthority(fields.domain))
8577
+ throw fieldError("domain", "not an RFC 3986 authority");
8578
+ if (!isCaip10Address(fields.address))
8579
+ throw fieldError("address", fields.address.length === 0 || fields.address.length > 128 ? "expected 1..=128 characters" : "bad CAIP-10 charset");
8580
+ if (fields.statement !== undefined) {
8581
+ if (utf8ByteLength(fields.statement) > 4096)
8582
+ throw fieldError("statement", "exceeds maximum size");
8583
+ for (const c of fields.statement)
8584
+ if (!STATEMENT_CHARS.has(c))
8585
+ throw fieldError("statement", "must be RFC 3986 reserved / unreserved / SP");
8586
+ }
8587
+ checkUri(fields.uri, "uri");
8588
+ if (fields.version !== "1")
8589
+ throw fieldError("version", 'must be "1"');
8590
+ if (fields.chainId.length === 0)
8591
+ throw fieldError("chainId", "empty");
8592
+ if (fields.chainId.length > 64)
8593
+ throw fieldError("chainId", "exceeds 64 characters");
8594
+ for (const c of fields.chainId)
8595
+ if (!/[A-Za-z0-9]/.test(c) && c !== "-" && c !== "_" && c !== ":")
8596
+ throw fieldError("chainId", "bad charset");
8597
+ if (fields.nonce.length < 8)
8598
+ throw fieldError("nonce", "too short");
8599
+ for (const c of fields.nonce)
8600
+ if (!/[A-Za-z0-9]/.test(c))
8601
+ throw fieldError("nonce", "not ASCII alphanumeric");
8602
+ if (parseTimestamp(fields.issuedAt) === undefined)
8603
+ throw fieldError("issuedAt", "not an RFC 3339 date-time");
8604
+ if (fields.expirationTime !== undefined && parseTimestamp(fields.expirationTime) === undefined)
8605
+ throw fieldError("expirationTime", "not an RFC 3339 date-time");
8606
+ if (fields.notBefore !== undefined && parseTimestamp(fields.notBefore) === undefined)
8607
+ throw fieldError("notBefore", "not an RFC 3339 date-time");
8608
+ if (fields.requestId !== undefined) {
8609
+ if (utf8ByteLength(fields.requestId) > 128)
8610
+ throw fieldError("requestId", "exceeds maximum size");
8611
+ if (!isPcharString(fields.requestId))
8612
+ throw fieldError("requestId", "must be RFC 3986 *pchar");
8613
+ }
8614
+ if (fields.resources !== undefined) {
8615
+ if (fields.resources.length > 32)
8616
+ throw fieldError("resources", "too many");
8617
+ for (const uri of fields.resources)
8618
+ checkUri(uri, "resources");
8619
+ }
8620
+ const out = {
8621
+ domain: fields.domain,
8622
+ address: fields.address,
8623
+ uri: fields.uri,
8624
+ version: fields.version,
8625
+ chainId: fields.chainId,
8626
+ nonce: fields.nonce,
8627
+ issuedAt: fields.issuedAt,
8628
+ ...fields.scheme === undefined ? {} : { scheme: fields.scheme },
8629
+ ...fields.statement === undefined ? {} : { statement: fields.statement },
8630
+ ...fields.expirationTime === undefined ? {} : { expirationTime: fields.expirationTime },
8631
+ ...fields.notBefore === undefined ? {} : { notBefore: fields.notBefore },
8632
+ ...fields.requestId === undefined ? {} : { requestId: fields.requestId },
8633
+ ...fields.resources === undefined ? {} : { resources: fields.resources }
8634
+ };
8635
+ return Object.freeze(out);
8636
+ }
8637
+ function checkUri(uri, field) {
8638
+ if (uri.length === 0)
8639
+ throw fieldError(field, "empty");
8640
+ if (utf8ByteLength(uri) > 2048)
8641
+ throw fieldError(field, "exceeds maximum size");
8642
+ if (!isUri(uri))
8643
+ throw fieldError(field, "not an RFC 3986 URI");
8644
+ }
8029
8645
 
8030
- // ../wallet-chains/dist/message-DuJ5KSRT.mjs
8031
- var MAINNET_BIP32 = {
8032
- public: 76067358,
8033
- private: 76066276
8034
- };
8035
- var TESTNET_BIP32 = {
8036
- public: 70617039,
8037
- private: 70615956
8038
- };
8039
- var REGTEST_NETWORK = {
8040
- ...TEST_NETWORK,
8041
- bech32: "bcrt"
8646
+ // ../../node_modules/.bun/@qntx+siwx@0.8.0/node_modules/@qntx/siwx/dist/rolldown-runtime-D8jQpDG7.mjs
8647
+ var __defProp = Object.defineProperty;
8648
+ var __exportAll = (all, no_symbols) => {
8649
+ let target = {};
8650
+ for (var name in all)
8651
+ __defProp(target, name, {
8652
+ get: all[name],
8653
+ enumerable: true
8654
+ });
8655
+ if (!no_symbols)
8656
+ __defProp(target, Symbol.toStringTag, { value: "Module" });
8657
+ return target;
8042
8658
  };
8043
- var NETWORKS = Object.freeze([
8044
- {
8045
- caip2: "bip122:000000000019d6689c085ae165831e93",
8046
- genesis: "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f",
8047
- params: NETWORK,
8048
- coinType: 0,
8049
- bip32: MAINNET_BIP32
8050
- },
8051
- {
8052
- caip2: "bip122:00000000da84f2bafbbc53dee25a72ae",
8053
- genesis: "00000000da84f2bafbbc53dee25a72ae507ff4914b867c565be350b0da8bf043",
8054
- params: TEST_NETWORK,
8055
- coinType: 1,
8056
- bip32: TESTNET_BIP32
8057
- },
8058
- {
8059
- caip2: "bip122:00000008819873e925422c1ff0f99f7c",
8060
- genesis: "00000008819873e925422c1ff0f99f7cc9bbb232af63a077a480a3633bee1ef6",
8061
- params: TEST_NETWORK,
8062
- coinType: 1,
8063
- bip32: TESTNET_BIP32
8064
- },
8065
- {
8066
- caip2: "bip122:0f9188f13cb7b2c71f2a335e3a4fc328",
8067
- genesis: "0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206",
8068
- params: REGTEST_NETWORK,
8069
- coinType: 1,
8070
- bip32: TESTNET_BIP32
8659
+
8660
+ // ../../node_modules/.bun/@qntx+siwx@0.8.0/node_modules/@qntx/siwx/dist/eip4361-Bf5VppSi.mjs
8661
+ //! ERC-4361 signing-text layout: `format` and its strict inverse `parse`.
8662
+ //! For every accepted text `t`, `format(label, parse(t).message) === t`
8663
+ //! byte-for-byte.
8664
+ function takeTag(line, tag, field) {
8665
+ if (!line.startsWith(tag))
8666
+ throw syntaxError("MissingField", field);
8667
+ return line.slice(tag.length);
8668
+ }
8669
+ function format(label, message) {
8670
+ let out = "";
8671
+ if (message.scheme !== undefined)
8672
+ out += `${message.scheme}://`;
8673
+ out += `${message.domain + MID + label + SUFFIX}
8674
+ `;
8675
+ out += `${message.address}
8676
+
8677
+ `;
8678
+ if (message.statement !== undefined)
8679
+ out += `${message.statement}
8680
+ `;
8681
+ out += `
8682
+ `;
8683
+ out += `URI: ${message.uri}
8684
+ `;
8685
+ out += `Version: ${message.version}
8686
+ `;
8687
+ out += `Chain ID: ${message.chainId}
8688
+ `;
8689
+ out += `Nonce: ${message.nonce}
8690
+ `;
8691
+ out += `Issued At: ${message.issuedAt}`;
8692
+ if (message.expirationTime !== undefined)
8693
+ out += `
8694
+ Expiration Time: ${message.expirationTime}`;
8695
+ if (message.notBefore !== undefined)
8696
+ out += `
8697
+ Not Before: ${message.notBefore}`;
8698
+ if (message.requestId !== undefined)
8699
+ out += `
8700
+ Request ID: ${message.requestId}`;
8701
+ if (message.resources !== undefined) {
8702
+ out += `
8703
+ Resources:`;
8704
+ for (const uri of message.resources)
8705
+ out += `
8706
+ - ${uri}`;
8071
8707
  }
8072
- ]);
8073
- var BITCOIN_NETWORKS = Object.freeze(Object.fromEntries(NETWORKS.map((n) => [n.caip2, n])));
8074
- var bitcoinNetwork = (caip2) => {
8075
- const net = BITCOIN_NETWORKS[caip2];
8076
- if (net === undefined)
8077
- throw new ChainError("unsupported", `unknown bitcoin network: ${caip2}`);
8078
- return net;
8079
- };
8080
- var utf8 = (s) => new TextEncoder().encode(s);
8081
- var BIP322_TAG = "BIP0322-signed-message";
8082
- var LEGACY_MAGIC = utf8(`Bitcoin Signed Message:
8708
+ return out;
8709
+ }
8710
+ function parse(text) {
8711
+ const byteLength = utf8ByteLength(text);
8712
+ if (byteLength > 16384)
8713
+ throw new SiwxError({
8714
+ code: "MessageTooLarge",
8715
+ length: byteLength,
8716
+ max: MAX_MESSAGE_BYTES
8717
+ });
8718
+ if (text.includes("\r"))
8719
+ throw syntaxError("CarriageReturn");
8720
+ const lines = text.split(`
8083
8721
  `);
8084
- var concat = (...parts) => {
8085
- const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
8086
- let o = 0;
8087
- for (const p of parts) {
8088
- out.set(p, o);
8089
- o += p.length;
8090
- }
8091
- return out;
8092
- };
8093
- var varint = (n) => Uint8Array.of(n);
8094
- var pushData = (data) => concat(varint(data.length), data);
8095
- var u32le = (n) => Uint8Array.of(n % 256, Math.floor(n / 256) % 256, Math.floor(n / 65536) % 256, Math.floor(n / 16777216) % 256);
8096
- var u64le = (n) => {
8097
- const out = /* @__PURE__ */ new Uint8Array(8);
8098
- let v = n;
8099
- for (let i = 0;i < 8; i++) {
8100
- out[i] = Number(v % 256n);
8101
- v /= 256n;
8102
- }
8103
- return out;
8104
- };
8105
- var bip322MessageHash = (message) => {
8106
- const tag = sha256(utf8(BIP322_TAG));
8107
- return sha256(concat(tag, tag, utf8(message)));
8108
- };
8109
- var toSpend = (scriptPubKey, messageHash) => {
8110
- const scriptSig = concat(Uint8Array.of(0), pushData(messageHash));
8111
- 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));
8722
+ let i = 0;
8723
+ const next = () => {
8724
+ const l = lines[i++];
8725
+ if (l === undefined)
8726
+ throw syntaxError("UnexpectedEof");
8727
+ return l;
8728
+ };
8729
+ const preamble = next();
8730
+ const mid = preamble.indexOf(MID);
8731
+ if (mid === -1)
8732
+ throw syntaxError("MissingPreamble");
8733
+ const head = preamble.slice(0, mid);
8734
+ const tail = preamble.slice(mid + MID.length);
8735
+ if (!tail.endsWith(" account:"))
8736
+ throw syntaxError("MissingAccountSuffix");
8737
+ const label = tail.slice(0, -SUFFIX.length);
8738
+ if (label.length === 0)
8739
+ throw fieldError("label", "empty");
8740
+ let scheme;
8741
+ let domain;
8742
+ const proto = head.indexOf("://");
8743
+ if (proto === -1)
8744
+ domain = head;
8745
+ else {
8746
+ scheme = head.slice(0, proto);
8747
+ domain = head.slice(proto + 3);
8748
+ }
8749
+ const address = next();
8750
+ let blanks = 0;
8751
+ while (lines[i + blanks] === "")
8752
+ blanks++;
8753
+ let statement;
8754
+ if (blanks === 1) {
8755
+ i += 1;
8756
+ statement = next();
8757
+ if (next() !== "")
8758
+ throw syntaxError("ExpectedBlankLine");
8759
+ } else if (blanks === 2)
8760
+ i += 2;
8761
+ else if (blanks === 3) {
8762
+ i += 3;
8763
+ statement = "";
8764
+ } else
8765
+ throw syntaxError("ExpectedBlankLine");
8766
+ const uri = takeTag(next(), "URI: ", "uri");
8767
+ const version = takeTag(next(), "Version: ", "version");
8768
+ const chainId = takeTag(next(), "Chain ID: ", "chainId");
8769
+ const nonce = takeTag(next(), "Nonce: ", "nonce");
8770
+ const issuedAt = takeTag(next(), "Issued At: ", "issuedAt");
8771
+ const opt = optionalTags(lines, i);
8772
+ const fields = {
8773
+ scheme,
8774
+ domain,
8775
+ address,
8776
+ statement,
8777
+ uri,
8778
+ version,
8779
+ chainId,
8780
+ nonce,
8781
+ issuedAt,
8782
+ ...opt
8783
+ };
8112
8784
  return {
8113
- txid: sha256(sha256(raw)),
8114
- raw
8785
+ label,
8786
+ message: createMessage(fields)
8115
8787
  };
8116
- };
8117
- var BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
8118
- var b642 = (i) => BASE64[i] ?? "";
8119
- var base642 = (bytes) => {
8120
- const c = b642;
8121
- let out = "";
8122
- for (let i = 0;i < bytes.length; i += 3) {
8123
- const b0 = bytes[i] ?? 0;
8124
- const b1 = bytes[i + 1] ?? 0;
8125
- const b2 = bytes[i + 2] ?? 0;
8126
- out += c(Math.floor(b0 / 4)) + c(b0 % 4 * 16 + Math.floor(b1 / 16));
8127
- out += i + 1 < bytes.length ? c(b1 % 16 * 4 + Math.floor(b2 / 64)) : "=";
8128
- out += i + 2 < bytes.length ? c(b2 % 64) : "=";
8788
+ }
8789
+ function parseBytes(bytes) {
8790
+ if (bytes.length > 16384)
8791
+ throw new SiwxError({
8792
+ code: "MessageTooLarge",
8793
+ length: bytes.length,
8794
+ max: MAX_MESSAGE_BYTES
8795
+ });
8796
+ const text = utf8Decode(bytes);
8797
+ if (text === undefined)
8798
+ throw syntaxError("InvalidUtf8");
8799
+ return parse(text);
8800
+ }
8801
+ function parseLabeled(label, signed) {
8802
+ const parsed = parseBytes(signed);
8803
+ if (parsed.label !== label)
8804
+ throw mismatchError("label", label, parsed.label);
8805
+ return parsed.message;
8806
+ }
8807
+
8808
+ // ../../node_modules/.bun/@noble+hashes@2.4.0/node_modules/@noble/hashes/sha3.js
8809
+ var _0n4 = BigInt(0);
8810
+ var _1n4 = BigInt(1);
8811
+ var _2n4 = BigInt(2);
8812
+ var _7n = BigInt(7);
8813
+ var _256n = BigInt(256);
8814
+ var _0x71n = BigInt(113);
8815
+ var SHA3_PI = [];
8816
+ var SHA3_ROTL = [];
8817
+ var _SHA3_IOTA = [];
8818
+ for (let round = 0, R = _1n4, x = 1, y = 0;round < 24; round++) {
8819
+ [x, y] = [y, (2 * x + 3 * y) % 5];
8820
+ SHA3_PI.push(2 * (5 * y + x));
8821
+ SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
8822
+ let t = _0n4;
8823
+ for (let j = 0;j < 7; j++) {
8824
+ R = (R << _1n4 ^ (R >> _7n) * _0x71n) % _256n;
8825
+ if (R & _2n4)
8826
+ t ^= _1n4 << (_1n4 << BigInt(j)) - _1n4;
8129
8827
  }
8130
- return out;
8131
- };
8132
- var signBip322Simple = (message, scriptPubKey, privateKey, auxRand) => {
8133
- const hash = bip322MessageHash(message);
8134
- const { txid } = toSpend(scriptPubKey, hash);
8135
- const tx = new Transaction({
8136
- version: 0,
8137
- lockTime: 0,
8138
- allowUnknownOutputs: true
8139
- });
8140
- const pub = secp256k1.getPublicKey(privateKey, true);
8141
- tx.addInput({
8142
- txid,
8143
- index: 0,
8144
- sequence: 0,
8145
- witnessUtxo: {
8146
- script: scriptPubKey,
8147
- amount: 0n
8148
- },
8149
- bip32Derivation: [[pub, {
8150
- fingerprint: 0,
8151
- path: []
8152
- }]],
8153
- ...scriptPubKey[0] === 81 ? { tapInternalKey: pub.slice(1) } : {}
8154
- });
8155
- tx.addOutput({
8156
- script: Uint8Array.of(106),
8157
- amount: 0n
8158
- });
8159
- const isTaproot = scriptPubKey[0] === 81;
8160
- if (!tx.signIdx(privateKey, 0, isTaproot ? [SigHash.DEFAULT, SigHash.ALL] : [SigHash.ALL], auxRand(0)))
8161
- throw new ChainError("invalid-request", "key cannot sign this BIP-322 input");
8162
- tx.finalizeIdx(0);
8163
- const witness = tx.getInput(0).finalScriptWitness;
8164
- if (witness === undefined)
8165
- throw new ChainError("invalid-request", "BIP-322 input produced no witness");
8166
- const raw = concat(varint(witness.length), ...witness.map(pushData));
8167
- return `smp${base642(raw)}`;
8168
- };
8169
- var signLegacyMessage = (message, privateKey) => {
8170
- const data = concat(pushData(LEGACY_MAGIC), pushData(utf8(message)));
8171
- const hash = sha256(sha256(data));
8172
- const recovered = secp256k1.sign(hash, privateKey, {
8173
- lowS: true,
8174
- format: "recovered"
8175
- });
8176
- const header = 27 + (recovered[0] ?? 0) + 4;
8177
- return base642(concat(Uint8Array.of(header), recovered.slice(1)));
8178
- };
8828
+ _SHA3_IOTA.push(t);
8829
+ }
8830
+ var IOTAS = split(_SHA3_IOTA, true);
8831
+ var SHA3_IOTA_H = IOTAS[0];
8832
+ var SHA3_IOTA_L = IOTAS[1];
8833
+ var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
8834
+ var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
8835
+ var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
8836
+ var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
8837
+ var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
8838
+ var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
8839
+ var B = new Uint32Array(5 * 2);
8840
+ function keccakP(s, rounds = 24) {
8841
+ if (!(s instanceof Uint32Array))
8842
+ throw new TypeError('"s" expected Uint32Array(50), got type=' + typeof s);
8843
+ if (s.length !== 50)
8844
+ throw new RangeError('"s" expected Uint32Array(50), got length=' + s.length);
8845
+ anumber(rounds, "rounds");
8846
+ if (rounds < 1 || rounds > 24)
8847
+ throw new Error('"rounds" expected integer 1..24');
8848
+ for (let round = 24 - rounds;round < 24; round++) {
8849
+ for (let x = 0;x < 10; x++)
8850
+ B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
8851
+ for (let x = 0;x < 10; x += 2) {
8852
+ const idx1 = (x + 8) % 10;
8853
+ const idx0 = (x + 2) % 10;
8854
+ const B0 = B[idx0];
8855
+ const B1 = B[idx0 + 1];
8856
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
8857
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
8858
+ for (let y = 0;y < 50; y += 10) {
8859
+ s[x + y] ^= Th;
8860
+ s[x + y + 1] ^= Tl;
8861
+ }
8862
+ }
8863
+ let curH = s[2];
8864
+ let curL = s[3];
8865
+ for (let t = 0;t < 24; t++) {
8866
+ const shift = SHA3_ROTL[t];
8867
+ const Th = rotlH(curH, curL, shift);
8868
+ const Tl = rotlL(curH, curL, shift);
8869
+ const PI = SHA3_PI[t];
8870
+ curH = s[PI];
8871
+ curL = s[PI + 1];
8872
+ s[PI] = Th;
8873
+ s[PI + 1] = Tl;
8874
+ }
8875
+ for (let y = 0;y < 50; y += 10) {
8876
+ const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3];
8877
+ s[y] ^= ~s[y + 2] & s[y + 4];
8878
+ s[y + 1] ^= ~s[y + 3] & s[y + 5];
8879
+ s[y + 2] ^= ~s[y + 4] & s[y + 6];
8880
+ s[y + 3] ^= ~s[y + 5] & s[y + 7];
8881
+ s[y + 4] ^= ~s[y + 6] & s[y + 8];
8882
+ s[y + 5] ^= ~s[y + 7] & s[y + 9];
8883
+ s[y + 6] ^= ~s[y + 8] & b0;
8884
+ s[y + 7] ^= ~s[y + 9] & b1;
8885
+ s[y + 8] ^= ~b0 & b2;
8886
+ s[y + 9] ^= ~b1 & b3;
8887
+ }
8888
+ s[0] ^= SHA3_IOTA_H[round];
8889
+ s[1] ^= SHA3_IOTA_L[round];
8890
+ }
8891
+ clean(B);
8892
+ }
8179
8893
 
8180
- // ../wallet-chains/dist/bitcoin.mjs
8181
- var isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8182
- var derivationPaths = (map) => {
8183
- const entries = map instanceof Map ? [...map.values()] : Array.isArray(map) ? map : isRecord$1(map) ? Object.values(map) : [];
8184
- const paths = [];
8185
- for (const entry of entries) {
8186
- const value = Array.isArray(entry) ? entry[1] : entry;
8187
- if (!isRecord$1(value))
8188
- continue;
8189
- const { path } = isRecord$1(value["der"]) ? value["der"] : value;
8190
- if (Array.isArray(path) && path.every((p) => typeof p === "number"))
8191
- paths.push(path);
8894
+ class Keccak {
8895
+ state;
8896
+ pos = 0;
8897
+ posOut = 0;
8898
+ finished = false;
8899
+ state32;
8900
+ destroyed = false;
8901
+ blockLen;
8902
+ suffix;
8903
+ outputLen;
8904
+ canXOF;
8905
+ enableXOF = false;
8906
+ rounds;
8907
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
8908
+ anumber(blockLen, "blockLen");
8909
+ anumber(suffix, "suffix");
8910
+ anumber(rounds, "rounds");
8911
+ abool(enableXOF, "enableXOF");
8912
+ this.blockLen = blockLen;
8913
+ this.suffix = suffix;
8914
+ this.outputLen = outputLen;
8915
+ this.enableXOF = enableXOF;
8916
+ this.canXOF = enableXOF;
8917
+ this.rounds = rounds;
8918
+ anumber(outputLen, "outputLen");
8919
+ if (!(0 < blockLen && blockLen < 200))
8920
+ throw new Error('"blockLen" must be 1..199');
8921
+ this.state = new Uint8Array(200);
8922
+ this.state32 = u32(this.state);
8923
+ }
8924
+ clone() {
8925
+ return this._cloneInto();
8926
+ }
8927
+ keccak() {
8928
+ swap32IfBE(this.state32);
8929
+ keccakP(this.state32, this.rounds);
8930
+ swap32IfBE(this.state32);
8931
+ this.posOut = 0;
8932
+ this.pos = 0;
8933
+ }
8934
+ update(data) {
8935
+ aexists(this);
8936
+ abytes(data);
8937
+ const { blockLen, state, state32 } = this;
8938
+ const len = data.length;
8939
+ const canUseU32 = blockLen % 4 === 0 && data.byteOffset % 4 === 0;
8940
+ const blockLen32 = blockLen / 4;
8941
+ const data32 = canUseU32 && len >= blockLen ? u32(data) : undefined;
8942
+ for (let pos = 0;pos < len; ) {
8943
+ if (data32 !== undefined && this.pos === 0 && pos % 4 === 0 && len - pos >= blockLen) {
8944
+ for (let i = 0, o = pos / 4;i < blockLen32; i++)
8945
+ state32[i] ^= data32[o + i];
8946
+ pos += blockLen;
8947
+ this.pos = blockLen;
8948
+ this.keccak();
8949
+ continue;
8950
+ }
8951
+ const take = Math.min(blockLen - this.pos, len - pos);
8952
+ for (let i = 0;i < take; i++)
8953
+ state[this.pos++] ^= data[pos++];
8954
+ if (this.pos === blockLen)
8955
+ this.keccak();
8956
+ }
8957
+ return this;
8958
+ }
8959
+ finish() {
8960
+ if (this.finished)
8961
+ return;
8962
+ this.finished = true;
8963
+ const { state, suffix, pos, blockLen } = this;
8964
+ state[pos] ^= suffix;
8965
+ if ((suffix & 128) !== 0 && pos === blockLen - 1)
8966
+ this.keccak();
8967
+ state[blockLen - 1] ^= 128;
8968
+ this.keccak();
8969
+ }
8970
+ writeInto(out) {
8971
+ aexists(this, false);
8972
+ abytes(out);
8973
+ this.finish();
8974
+ const bufferOut = this.state;
8975
+ const { blockLen } = this;
8976
+ for (let pos = 0, len = out.length;pos < len; ) {
8977
+ if (this.posOut >= blockLen)
8978
+ this.keccak();
8979
+ const take = Math.min(blockLen - this.posOut, len - pos);
8980
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
8981
+ this.posOut += take;
8982
+ pos += take;
8983
+ }
8984
+ return out;
8985
+ }
8986
+ xofInto(out) {
8987
+ if (!this.enableXOF)
8988
+ throw new Error("XOF is not enabled");
8989
+ return this.writeInto(out);
8990
+ }
8991
+ xof(bytes) {
8992
+ anumber(bytes);
8993
+ return this.xofInto(new Uint8Array(bytes));
8994
+ }
8995
+ digestInto(out) {
8996
+ aoutput(out, this);
8997
+ if (this.finished)
8998
+ throw new Error("digest() was already called");
8999
+ this.writeInto(out.length === this.outputLen ? out : out.subarray(0, this.outputLen));
9000
+ this.destroy();
9001
+ }
9002
+ digest() {
9003
+ const out = new Uint8Array(this.outputLen);
9004
+ this.digestInto(out);
9005
+ return out;
9006
+ }
9007
+ destroy() {
9008
+ this.destroyed = true;
9009
+ clean(this.state);
9010
+ }
9011
+ _cloneInto(to) {
9012
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
9013
+ to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);
9014
+ to.blockLen = blockLen;
9015
+ to.state32.set(this.state32);
9016
+ to.pos = this.pos;
9017
+ to.posOut = this.posOut;
9018
+ to.finished = this.finished;
9019
+ to.rounds = rounds;
9020
+ to.suffix = suffix;
9021
+ to.outputLen = outputLen;
9022
+ to.enableXOF = enableXOF;
9023
+ to.canXOF = this.canXOF;
9024
+ to.destroyed = this.destroyed;
9025
+ return to;
9026
+ }
9027
+ }
9028
+ var genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);
9029
+ var keccak_256 = /* @__PURE__ */ genKeccak(1, 136, 32);
9030
+
9031
+ // ../../node_modules/.bun/@qntx+siwx@0.8.0/node_modules/@qntx/siwx/dist/evm.mjs
9032
+ //! EIP-55 / EVM address + chain-id rules, matching `siwx::evm`.
9033
+ var HEX40 = /^[0-9a-fA-F]{40}$/;
9034
+ function toChecksumAddress(address) {
9035
+ if (!address.startsWith("0x"))
9036
+ throw fieldError("address", "expected 0x + 40 hex");
9037
+ const body = address.slice(2);
9038
+ if (!HEX40.test(body))
9039
+ throw fieldError("address", "expected 0x + 40 hex");
9040
+ const lower = body.toLowerCase();
9041
+ const hash = keccak_256(utf8Encode(lower));
9042
+ let out = "0x";
9043
+ for (let i = 0;i < 40; i++) {
9044
+ const c = lower.charAt(i);
9045
+ const nibble = (hash[Math.floor(i / 2)] ?? 0) >> (i % 2 === 0 ? 4 : 0) & 15;
9046
+ out += /[a-f]/.test(c) && nibble >= 8 ? c.toUpperCase() : c;
9047
+ }
9048
+ return out;
9049
+ }
9050
+ var badAddress = () => fieldError("address", "expected 0x + 40 hex");
9051
+ function parseEip55(address) {
9052
+ const bad = badAddress;
9053
+ if (!address.startsWith("0x"))
9054
+ throw bad();
9055
+ const hex = address.slice(2);
9056
+ if (!HEX40.test(hex))
9057
+ throw bad();
9058
+ const hasLower = /[a-f]/.test(hex);
9059
+ const hasUpper = /[A-F]/.test(hex);
9060
+ if (hasLower && hasUpper && address !== toChecksumAddress(address))
9061
+ throw fieldError("address", "bad EIP-55 checksum");
9062
+ return hexToBytes(hex);
9063
+ }
9064
+ function parseEvmChainId(chainId) {
9065
+ if (chainId.length === 0)
9066
+ throw fieldError("chainId", "empty");
9067
+ if (!/^[0-9]+$/.test(chainId))
9068
+ throw fieldError("chainId", "not decimal");
9069
+ if (chainId.length > 1 && chainId.startsWith("0"))
9070
+ throw fieldError("chainId", "leading zero");
9071
+ const value = BigInt(chainId);
9072
+ if (value > 18446744073709551615n)
9073
+ throw fieldError("chainId", "overflow");
9074
+ return value;
9075
+ }
9076
+ //! EIP-191 `personal_sign` verification.
9077
+ //!
9078
+ //! Decode order (cross-language contract, mirrored with Rust): length ≠
9079
+ //! 65 → `v ∉ {0,1,27,28}` → `r`/`s` equal to 0 or ≥ n → `s > n/2` (all
9080
+ //! `InvalidSignature`) → recovery failure or address mismatch →
9081
+ //! `VerificationFailed`.
9082
+ var N = secp256k1.Point.Fn.ORDER;
9083
+ var N_HALF = N / 2n;
9084
+ function eip191Hash(message) {
9085
+ const prefix = utf8Encode(`\x19Ethereum Signed Message:
9086
+ ${message.length}`);
9087
+ const joined = new Uint8Array(prefix.length + message.length);
9088
+ joined.set(prefix);
9089
+ joined.set(message, prefix.length);
9090
+ return keccak_256(joined);
9091
+ }
9092
+ function verifyEip191(message, signed, signature) {
9093
+ if (signature.length !== 65)
9094
+ throw new SiwxError({
9095
+ code: "InvalidSignature",
9096
+ reason: "EIP-191 signature must be 65 bytes"
9097
+ });
9098
+ const v = signature[64] ?? 0;
9099
+ if (v !== 0 && v !== 1 && v !== 27 && v !== 28)
9100
+ throw new SiwxError({
9101
+ code: "InvalidSignature",
9102
+ reason: "v must be 0, 1, 27 or 28"
9103
+ });
9104
+ const r = bytesToNumberBE(signature.subarray(0, 32));
9105
+ const s = bytesToNumberBE(signature.subarray(32, 64));
9106
+ if (r === 0n || r >= N || s === 0n || s >= N)
9107
+ throw new SiwxError({
9108
+ code: "InvalidSignature",
9109
+ reason: "r/s out of range"
9110
+ });
9111
+ if (s > N_HALF)
9112
+ throw new SiwxError({
9113
+ code: "InvalidSignature",
9114
+ reason: "high-s (EIP-2)"
9115
+ });
9116
+ const hash = eip191Hash(signed);
9117
+ let recovered;
9118
+ try {
9119
+ const uncompressed = secp256k1.Signature.fromBytes(signature.subarray(0, 64), "compact").addRecoveryBit(v % 27).recoverPublicKey(hash).toBytes(false);
9120
+ recovered = keccak_256(uncompressed.subarray(1)).subarray(12);
9121
+ } catch {
9122
+ throw new SiwxError({ code: "VerificationFailed" });
9123
+ }
9124
+ const expected = parseEip55(message.address);
9125
+ if (!equalBytes(recovered, expected))
9126
+ throw new SiwxError({ code: "VerificationFailed" });
9127
+ }
9128
+ //! On-chain smart-account verification: the ERC-6492 universal validator via a
9129
+ //! deployless `eth_call`. Covers deployed ERC-1271 accounts, counterfactual
9130
+ //! ERC-6492 accounts and EOAs. Providers are injected; the library builds no
9131
+ //! transports and applies no timeouts — transport policy belongs to the
9132
+ //! provider owner.
9133
+ var BYTECODE = hexToBytes2("608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572");
9134
+ function deploylessCalldata(signer, hash, signature) {
9135
+ const addr = hexToBytes2(signer.slice(2));
9136
+ const word = 32;
9137
+ const out = new Uint8Array(BYTECODE.length + 96 + word + Math.ceil(signature.length / word) * word);
9138
+ const bc = BYTECODE;
9139
+ out.set(bc, 0);
9140
+ let o = bc.length;
9141
+ out.set(addr, o + (word - addr.length));
9142
+ o += word;
9143
+ out.set(hash, o);
9144
+ o += word;
9145
+ out.set(numberToBytesBE(BigInt(96), word), o);
9146
+ o += word;
9147
+ out.set(numberToBytesBE(BigInt(signature.length), word), o);
9148
+ out.set(signature, o + word);
9149
+ return out;
9150
+ }
9151
+ var malformed = () => new SiwxError({
9152
+ code: "Backend",
9153
+ reason: "malformed eth_call result"
9154
+ });
9155
+ function decodeResult(hex) {
9156
+ const data = hex === "" || hex === "0x" ? /* @__PURE__ */ new Uint8Array(0) : hexToBytes2(hex.slice(2));
9157
+ if (data.length === 1) {
9158
+ if (data[0] === 1)
9159
+ return true;
9160
+ if (data[0] === 0)
9161
+ return false;
9162
+ throw malformed();
8192
9163
  }
8193
- return paths;
8194
- };
8195
- var checkPaths = (paths, where, coinType) => {
8196
- for (const path of paths)
8197
- if (path.length >= 2 && (path[1] ?? -1) - 2147483648 !== coinType)
8198
- throw new ChainError("chain-id-mismatch", `${where} derivation coin type is not this network's`);
8199
- };
8200
- var checkDerivations = (tx, coinType) => {
8201
- for (let i = 0;i < tx.inputsLength; i++) {
8202
- const input = tx.getInput(i);
8203
- checkPaths(derivationPaths(input.bip32Derivation), `input ${i}`, coinType);
8204
- checkPaths(derivationPaths(input.tapBip32Derivation), `input ${i}`, coinType);
9164
+ if (data.length === 32) {
9165
+ for (let i = 0;i < 31; i++)
9166
+ if (data[i] !== 0)
9167
+ throw malformed();
9168
+ if (data[31] === 1)
9169
+ return true;
9170
+ if (data[31] === 0)
9171
+ return false;
8205
9172
  }
8206
- for (let i = 0;i < tx.outputsLength; i++) {
8207
- const output = tx.getOutput(i);
8208
- checkPaths(derivationPaths(output.bip32Derivation), `output ${i}`, coinType);
8209
- checkPaths(derivationPaths(output.tapBip32Derivation), `output ${i}`, coinType);
9173
+ throw malformed();
9174
+ }
9175
+ var codeOf = (error) => typeof error === "object" && error !== null && ("code" in error) ? error.code : undefined;
9176
+ function isRevert(error) {
9177
+ const code = codeOf(error);
9178
+ return typeof code === "number" && code === 3;
9179
+ }
9180
+ function backend() {
9181
+ return new SiwxError({
9182
+ code: "Backend",
9183
+ reason: "RPC request failed"
9184
+ });
9185
+ }
9186
+ var MAGIC = (() => {
9187
+ const m = /* @__PURE__ */ new Uint8Array(32);
9188
+ for (let i = 0;i < m.length; i++)
9189
+ m[i] = i % 2 === 0 ? 100 : 146;
9190
+ return m;
9191
+ })();
9192
+ function has6492MagicSuffix(signature) {
9193
+ if (signature.length < MAGIC.length)
9194
+ return false;
9195
+ for (let i = 0;i < MAGIC.length; i++)
9196
+ if (signature[signature.length - MAGIC.length + i] !== MAGIC[i])
9197
+ return false;
9198
+ return true;
9199
+ }
9200
+ async function providerChainId(provider) {
9201
+ let result;
9202
+ try {
9203
+ result = await provider.request({ method: "eth_chainId" });
9204
+ } catch {
9205
+ throw backend();
8210
9206
  }
8211
- };
8212
- var DEFAULT_SIGHASH = 0;
8213
- var SIGHASH_ALL = 1;
8214
- var isTaprootInput = (input) => input.tapInternalKey !== undefined || getInputType(input).type === "taproot";
8215
- var normalizeBitcoinPsbt = (psbt, sign, network) => {
8216
- const net = bitcoinNetwork(network);
8217
- let tx;
9207
+ if (typeof result !== "string" || !/^0x[0-9a-fA-F]+$/.test(result))
9208
+ throw backend();
9209
+ return BigInt(result);
9210
+ }
9211
+ async function verifyOnChain(provider, message, signed, signature) {
9212
+ parseEip55(message.address);
9213
+ const hash = eip191Hash(signed);
9214
+ const data = `0x${bytesToHex2(deploylessCalldata(message.address, hash, signature))}`;
9215
+ let result;
8218
9216
  try {
8219
- tx = Transaction.fromPSBT(psbt, { strictPrevoutValidation: true });
9217
+ result = await provider.request({
9218
+ method: "eth_call",
9219
+ params: [{
9220
+ data,
9221
+ input: data
9222
+ }, "latest"]
9223
+ });
9224
+ } catch (error) {
9225
+ throw isRevert(error) ? new SiwxError({ code: "VerificationFailed" }) : backend();
9226
+ }
9227
+ if (typeof result !== "string" || !/^0x[0-9a-fA-F]*$/.test(result))
9228
+ throw backend();
9229
+ if (!decodeResult(result))
9230
+ throw new SiwxError({ code: "VerificationFailed" });
9231
+ }
9232
+ //! `@qntx/siwx/evm` — EIP-155 (`eip155`) namespace profile.
9233
+ //!
9234
+ //! `account()` emits the canonical EIP-55 checksum spelling, so
9235
+ //! lowercase / uppercase / checksummed spellings of the same address map
9236
+ //! to the same `AccountId`.
9237
+ var CHAIN_NAME = "Ethereum";
9238
+ var NAMESPACE = "eip155";
9239
+ function evmAccount(message) {
9240
+ parseEip55(message.address);
9241
+ parseEvmChainId(message.chainId);
9242
+ return createAccountId(NAMESPACE, message.chainId, toChecksumAddress(message.address));
9243
+ }
9244
+ function evm(options) {
9245
+ const rpc = options?.rpc ?? {};
9246
+ const verifiedChains = /* @__PURE__ */ new Set;
9247
+ const providerFor = (chainId) => {
9248
+ const key = parseEvmChainId(chainId).toString(10);
9249
+ return rpc[key];
9250
+ };
9251
+ const onChain = async (message, signed, signature, eip191Err) => {
9252
+ const key = parseEvmChainId(message.chainId).toString(10);
9253
+ const provider = providerFor(message.chainId);
9254
+ if (provider === undefined)
9255
+ throw eip191Err ?? new SiwxError({
9256
+ code: "Unsupported",
9257
+ reason: "EIP-6492 requires RPC"
9258
+ });
9259
+ if (!verifiedChains.has(key)) {
9260
+ const rpcChain = await providerChainId(provider);
9261
+ if (rpcChain !== parseEvmChainId(message.chainId))
9262
+ throw new SiwxError({
9263
+ code: "Mismatch",
9264
+ field: "chainId",
9265
+ expected: key,
9266
+ actual: rpcChain.toString()
9267
+ });
9268
+ verifiedChains.add(key);
9269
+ }
9270
+ await verifyOnChain(provider, message, signed, signature);
9271
+ };
9272
+ return {
9273
+ namespace: NAMESPACE,
9274
+ label: CHAIN_NAME,
9275
+ account: evmAccount,
9276
+ format(message) {
9277
+ evmAccount(message);
9278
+ return format(CHAIN_NAME, message);
9279
+ },
9280
+ parse(signed) {
9281
+ return parseLabeled(CHAIN_NAME, signed);
9282
+ },
9283
+ verify: async (message, signed, signature) => {
9284
+ if (has6492MagicSuffix(signature)) {
9285
+ await onChain(message, signed, signature, undefined);
9286
+ return;
9287
+ }
9288
+ try {
9289
+ verifyEip191(message, signed, signature);
9290
+ } catch (error) {
9291
+ if (error instanceof SiwxError && providerFor(message.chainId) !== undefined) {
9292
+ await onChain(message, signed, signature, error);
9293
+ return;
9294
+ }
9295
+ throw error;
9296
+ }
9297
+ }
9298
+ };
9299
+ }
9300
+
9301
+ // ../../node_modules/.bun/@qntx+siwx@0.8.0/node_modules/@qntx/siwx/dist/svm.mjs
9302
+ function addressBytes(address) {
9303
+ if (address.length < 32 || address.length > 44)
9304
+ throw fieldError("address", "expected 32–44 base58 chars");
9305
+ let bytes;
9306
+ try {
9307
+ bytes = base58.decode(address);
8220
9308
  } catch {
8221
- throw new ChainError("invalid-request", "PSBT failed to decode");
9309
+ throw fieldError("address", "invalid base58");
8222
9310
  }
8223
- if (!Array.isArray(sign) || sign.length === 0 || !sign.every((i) => Number.isSafeInteger(i) && i >= 0))
8224
- throw new ChainError("invalid-request", "sign must be a non-empty array of input indices");
8225
- const unique = [...new Set(sign.map(Number))].sort((a, b) => a - b);
8226
- const last = unique.at(-1);
8227
- if (unique.length !== sign.length || last === undefined || last >= tx.inputsLength)
8228
- throw new ChainError("invalid-request", "sign must be unique, ascending, and in range");
8229
- checkDerivations(tx, net.coinType);
8230
- for (const idx of unique) {
8231
- const input = tx.getInput(idx);
8232
- if (input.witnessUtxo === undefined && input.nonWitnessUtxo === undefined)
8233
- throw new ChainError("invalid-request", `input ${idx} carries neither witnessUtxo nor nonWitnessUtxo`);
8234
- if (input.bip32Derivation === undefined && input.tapBip32Derivation === undefined)
8235
- throw new ChainError("invalid-request", `input ${idx} is missing a bip32 derivation`);
8236
- const { type } = getInputType(input);
8237
- if ((type === "legacy" || type === "nonwitness-script") && input.nonWitnessUtxo === undefined)
8238
- throw new ChainError("invalid-request", `input ${idx} is missing nonWitnessUtxo`);
8239
- const sighash = input.sighashType;
8240
- if (!(sighash === undefined || sighash === SIGHASH_ALL || isTaprootInput(input) && sighash === DEFAULT_SIGHASH))
8241
- throw new ChainError("unsupported", `input ${idx} uses a non-default sighash`);
9311
+ if (bytes.length !== 32)
9312
+ throw fieldError("address", "expected 32 bytes");
9313
+ return bytes;
9314
+ }
9315
+ function canonicalPoint(bytes) {
9316
+ let point;
9317
+ try {
9318
+ point = ed25519.Point.fromBytes(bytes);
9319
+ } catch {
9320
+ throw fieldError("address", "invalid Ed25519 pubkey");
9321
+ }
9322
+ if (point.equals(ed25519.Point.ZERO))
9323
+ throw fieldError("address", "identity pubkey");
9324
+ if (!point.isTorsionFree())
9325
+ throw fieldError("address", "not in the prime-order subgroup");
9326
+ if (!equalBytes(point.toBytes(), bytes))
9327
+ throw fieldError("address", "non-canonical pubkey");
9328
+ }
9329
+ function validateAddress(address) {
9330
+ canonicalPoint(addressBytes(address));
9331
+ }
9332
+ var L = ed25519.Point.CURVE().n;
9333
+ var P = ed25519.Point;
9334
+ var siws_exports = /* @__PURE__ */ __exportAll({
9335
+ format: () => format2,
9336
+ parse: () => parse2,
9337
+ parseBytes: () => parseBytes2
9338
+ });
9339
+ var LABEL = "Solana";
9340
+ function format2(message) {
9341
+ if (message.scheme !== undefined)
9342
+ throw new SiwxError({
9343
+ code: "InvalidField",
9344
+ field: "scheme",
9345
+ reason: "not supported by SIWS"
9346
+ });
9347
+ if (message.statement !== undefined) {
9348
+ if (message.statement === "")
9349
+ throw new SiwxError({
9350
+ code: "InvalidField",
9351
+ field: "statement",
9352
+ reason: "empty"
9353
+ });
9354
+ if (message.statement.startsWith("URI: "))
9355
+ throw new SiwxError({
9356
+ code: "InvalidField",
9357
+ field: "statement",
9358
+ reason: "ambiguous with the URI: tag"
9359
+ });
8242
9360
  }
8243
- return {
8244
- psbt: tx.toPSBT(0),
8245
- sign: unique
9361
+ let out = `${message.domain}${MID}${LABEL}${SUFFIX}
9362
+ ${message.address}`;
9363
+ if (message.statement !== undefined)
9364
+ out += `
9365
+
9366
+ ${message.statement}`;
9367
+ out += `
9368
+
9369
+ URI: ${message.uri}`;
9370
+ out += `
9371
+ Version: ${message.version}`;
9372
+ out += `
9373
+ Chain ID: ${message.chainId}`;
9374
+ out += `
9375
+ Nonce: ${message.nonce}`;
9376
+ out += `
9377
+ Issued At: ${message.issuedAt}`;
9378
+ if (message.expirationTime !== undefined)
9379
+ out += `
9380
+ Expiration Time: ${message.expirationTime}`;
9381
+ if (message.notBefore !== undefined)
9382
+ out += `
9383
+ Not Before: ${message.notBefore}`;
9384
+ if (message.requestId !== undefined)
9385
+ out += `
9386
+ Request ID: ${message.requestId}`;
9387
+ if (message.resources !== undefined) {
9388
+ out += `
9389
+ Resources:`;
9390
+ for (const r of message.resources)
9391
+ out += `
9392
+ - ${r}`;
9393
+ }
9394
+ return out;
9395
+ }
9396
+ var missingUri = () => syntaxError("MissingField", "uri");
9397
+ function statementThenFields(lines, i) {
9398
+ if (i.v >= lines.length)
9399
+ throw missingUri();
9400
+ if (lines[i.v] !== "")
9401
+ throw syntaxError("ExpectedBlankLine");
9402
+ i.v++;
9403
+ const l = lines[i.v];
9404
+ if (l === undefined)
9405
+ throw missingUri();
9406
+ if (l === "")
9407
+ throw syntaxError("ExpectedBlankLine");
9408
+ if (l.startsWith("URI: "))
9409
+ return;
9410
+ i.v++;
9411
+ const after = lines[i.v];
9412
+ if (after === undefined)
9413
+ throw missingUri();
9414
+ if (after !== "")
9415
+ throw syntaxError("ExpectedBlankLine");
9416
+ i.v++;
9417
+ return l;
9418
+ }
9419
+ function parse2(text) {
9420
+ const byteLength = utf8ByteLength(text);
9421
+ if (byteLength > 16384)
9422
+ throw new SiwxError({
9423
+ code: "MessageTooLarge",
9424
+ length: byteLength,
9425
+ max: MAX_MESSAGE_BYTES
9426
+ });
9427
+ if (text.includes("\r"))
9428
+ throw syntaxError("CarriageReturn");
9429
+ if (text.endsWith(`
9430
+ `))
9431
+ throw syntaxError("UnexpectedTrailing");
9432
+ const lines = text.split(`
9433
+ `);
9434
+ const idx = { v: 0 };
9435
+ const preamble = lines[idx.v++];
9436
+ if (preamble === undefined)
9437
+ throw syntaxError("UnexpectedEof");
9438
+ const mid = preamble.indexOf(MID);
9439
+ if (mid === -1)
9440
+ throw syntaxError("MissingPreamble");
9441
+ const domain = preamble.slice(0, mid);
9442
+ const tail = preamble.slice(mid + MID.length);
9443
+ if (!tail.endsWith(" account:"))
9444
+ throw syntaxError("MissingAccountSuffix");
9445
+ const label = tail.slice(0, tail.length - SUFFIX.length);
9446
+ if (label !== LABEL)
9447
+ throw new SiwxError({
9448
+ code: "Mismatch",
9449
+ field: "label",
9450
+ expected: LABEL,
9451
+ actual: label
9452
+ });
9453
+ const address = lines[idx.v++];
9454
+ if (address === undefined)
9455
+ throw syntaxError("UnexpectedEof");
9456
+ const statement = statementThenFields(lines, idx);
9457
+ const take = (tag, field) => {
9458
+ const line = lines[idx.v];
9459
+ if (line === undefined || !line.startsWith(tag))
9460
+ throw syntaxError("MissingField", field);
9461
+ idx.v++;
9462
+ return line.slice(tag.length);
9463
+ };
9464
+ const uri = take("URI: ", "uri");
9465
+ const version = take("Version: ", "version");
9466
+ const chainId = take("Chain ID: ", "chainId");
9467
+ const nonce = take("Nonce: ", "nonce");
9468
+ const issuedAt = take("Issued At: ", "issuedAt");
9469
+ const tail4 = optionalTags(lines, idx.v);
9470
+ return createMessage({
9471
+ domain,
9472
+ address,
9473
+ ...statement === undefined ? {} : { statement },
9474
+ uri,
9475
+ version,
9476
+ chainId,
9477
+ nonce,
9478
+ issuedAt,
9479
+ ...tail4
9480
+ });
9481
+ }
9482
+ function parseBytes2(bytes) {
9483
+ if (bytes.length > 16384)
9484
+ throw new SiwxError({
9485
+ code: "MessageTooLarge",
9486
+ length: bytes.length,
9487
+ max: MAX_MESSAGE_BYTES
9488
+ });
9489
+ const text = utf8Decode(bytes);
9490
+ if (text === undefined)
9491
+ throw syntaxError("InvalidUtf8");
9492
+ return parse2(text);
9493
+ }
9494
+ var OFFCHAIN_DOMAIN = new Uint8Array([255, ...utf8Encode("solana offchain")]);
9495
+
9496
+ // ../wallet-chains/dist/src-8NZeEnrW.mjs
9497
+ var PREAMBLE = " wants you to sign in with your ";
9498
+ var OPTIONAL_KEYS = [
9499
+ "scheme",
9500
+ "statement",
9501
+ "expirationTime",
9502
+ "notBefore",
9503
+ "requestId"
9504
+ ];
9505
+ var plainFields = (message) => {
9506
+ const { domain, address, uri, version, chainId, nonce, issuedAt, resources } = message;
9507
+ const fields = {
9508
+ domain,
9509
+ address,
9510
+ uri,
9511
+ version,
9512
+ chainId,
9513
+ nonce,
9514
+ issuedAt
8246
9515
  };
9516
+ for (const key of OPTIONAL_KEYS) {
9517
+ const value = message[key];
9518
+ if (value !== undefined)
9519
+ fields[key] = value;
9520
+ }
9521
+ if (resources !== undefined)
9522
+ fields.resources = [...resources];
9523
+ return fields;
8247
9524
  };
8248
- var SATS = "sats";
8249
- var OP_RETURN = 106;
8250
- var bytesToHex4 = (bytes) => {
8251
- let out = "";
8252
- for (const b of bytes)
8253
- out += b.toString(16).padStart(2, "0");
8254
- return out;
9525
+ var parseValid = (text, family) => {
9526
+ if (family === "evm") {
9527
+ const ns = evm();
9528
+ const message = ns.parse(new TextEncoder().encode(text));
9529
+ ns.account(message);
9530
+ return plainFields(message);
9531
+ }
9532
+ const message = siws_exports.parse(text);
9533
+ validateAddress(message.address);
9534
+ return plainFields(message);
8255
9535
  };
8256
- var decodeOutput = (script, amount) => {
8257
- const hex = bytesToHex4(script);
8258
- if (script[0] === OP_RETURN)
9536
+ function parseSignIn(text, family) {
9537
+ try {
8259
9538
  return {
8260
- amount,
8261
- script: hex,
8262
- opReturn: true
9539
+ status: "valid",
9540
+ fields: parseValid(text, family)
8263
9541
  };
9542
+ } catch {
9543
+ return text.includes(PREAMBLE) ? { status: "malformed" } : undefined;
9544
+ }
9545
+ }
9546
+ var ChainError = class extends Error {
9547
+ code;
9548
+ constructor(code, message) {
9549
+ super(message);
9550
+ this.name = "ChainError";
9551
+ this.code = code;
9552
+ }
9553
+ };
9554
+
9555
+ // ../wallet-chains/dist/account-ref-D2rW_qlI.mjs
9556
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9557
+ var isAccountRef = (value) => {
9558
+ if (!isRecord2(value) || typeof value["kind"] !== "string")
9559
+ return false;
9560
+ if (value["kind"] === "hd")
9561
+ return typeof value["walletId"] === "string" && typeof value["groupIndex"] === "number" && typeof value["template"] === "string";
9562
+ return value["kind"] === "imported" && typeof value["keyId"] === "string" && typeof value["family"] === "string";
9563
+ };
9564
+ var requestBase = (request) => {
9565
+ if (!isRecord2(request))
9566
+ throw new ChainError("invalid-request", "request must be an object");
9567
+ const { network, account } = request;
9568
+ if (typeof network !== "string")
9569
+ throw new ChainError("invalid-request", "request.network must be a string");
9570
+ if (!isAccountRef(account))
9571
+ throw new ChainError("invalid-request", "request.account must be an AccountRef");
8264
9572
  return {
8265
- amount,
8266
- script: hex,
8267
- opReturn: false
9573
+ network,
9574
+ account
8268
9575
  };
8269
9576
  };
8270
- var decodeBitcoinPsbt = (request, ownScripts = /* @__PURE__ */ new Set) => {
8271
- const tx = Transaction.fromPSBT(request.psbt);
8272
- const coder = Address(bitcoinNetwork(request.network).params);
8273
- const signed = new Set(request.sign);
8274
- const outflows = [];
8275
- let canFee = true;
8276
- let outSum = 0n;
8277
- for (let i = 0;i < tx.outputsLength; i++) {
8278
- const output = tx.getOutput(i);
8279
- const { script } = output;
8280
- const { amount } = output;
8281
- if (script === undefined || amount === undefined)
8282
- continue;
8283
- const decoded = decodeOutput(script, amount);
8284
- outSum += amount;
8285
- if (decoded.opReturn || ownScripts.has(decoded.script))
8286
- continue;
8287
- let addr;
8288
- try {
8289
- const out = OutScript.decode(script);
8290
- addr = out === undefined ? undefined : coder.encode(out);
8291
- } catch {
8292
- addr = undefined;
8293
- }
8294
- outflows.push({
8295
- to: addr ?? decoded.script,
8296
- amount: {
8297
- asset: SATS,
8298
- amount: amount.toString(10)
8299
- },
8300
- verified: addr !== undefined
8301
- });
9577
+
9578
+ // ../wallet-chains/dist/message-ChhEZ0lx.mjs
9579
+ var MAINNET_BIP32 = {
9580
+ public: 76067358,
9581
+ private: 76066276
9582
+ };
9583
+ var TESTNET_BIP32 = {
9584
+ public: 70617039,
9585
+ private: 70615956
9586
+ };
9587
+ var REGTEST_NETWORK = {
9588
+ ...TEST_NETWORK,
9589
+ bech32: "bcrt"
9590
+ };
9591
+ var NETWORKS = Object.freeze([
9592
+ {
9593
+ caip2: "bip122:000000000019d6689c085ae165831e93",
9594
+ genesis: "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f",
9595
+ params: NETWORK,
9596
+ coinType: 0,
9597
+ bip32: MAINNET_BIP32
9598
+ },
9599
+ {
9600
+ caip2: "bip122:00000000da84f2bafbbc53dee25a72ae",
9601
+ genesis: "00000000da84f2bafbbc53dee25a72ae507ff4914b867c565be350b0da8bf043",
9602
+ params: TEST_NETWORK,
9603
+ coinType: 1,
9604
+ bip32: TESTNET_BIP32
9605
+ },
9606
+ {
9607
+ caip2: "bip122:00000008819873e925422c1ff0f99f7c",
9608
+ genesis: "00000008819873e925422c1ff0f99f7cc9bbb232af63a077a480a3633bee1ef6",
9609
+ params: TEST_NETWORK,
9610
+ coinType: 1,
9611
+ bip32: TESTNET_BIP32
9612
+ },
9613
+ {
9614
+ caip2: "bip122:0f9188f13cb7b2c71f2a335e3a4fc328",
9615
+ genesis: "0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206",
9616
+ params: REGTEST_NETWORK,
9617
+ coinType: 1,
9618
+ bip32: TESTNET_BIP32
8302
9619
  }
8303
- let inSum = 0n;
8304
- for (let i = 0;i < tx.inputsLength; i++) {
8305
- const input = tx.getInput(i);
8306
- if (input.witnessUtxo === undefined)
8307
- canFee = false;
8308
- else
8309
- inSum += input.witnessUtxo.amount;
9620
+ ]);
9621
+ var BITCOIN_NETWORKS = Object.freeze(Object.fromEntries(NETWORKS.map((n) => [n.caip2, n])));
9622
+ var bitcoinNetwork = (caip2) => {
9623
+ const net = BITCOIN_NETWORKS[caip2];
9624
+ if (net === undefined)
9625
+ throw new ChainError("unsupported", `unknown bitcoin network: ${caip2}`);
9626
+ return net;
9627
+ };
9628
+ var utf8 = (s) => new TextEncoder().encode(s);
9629
+ var BIP322_TAG = "BIP0322-signed-message";
9630
+ var LEGACY_MAGIC = utf8(`Bitcoin Signed Message:
9631
+ `);
9632
+ var concat = (...parts) => {
9633
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
9634
+ let o = 0;
9635
+ for (const p of parts) {
9636
+ out.set(p, o);
9637
+ o += p.length;
8310
9638
  }
8311
- const external = tx.inputsLength - signed.size > 0;
8312
- const undecodable = outflows.some((o) => !o.verified);
8313
- const verifiability = external ? "opaque" : undecodable ? "partial" : "full";
8314
- return {
8315
- family: "bitcoin",
8316
- network: request.network,
8317
- summary: outflows.length > 0 ? "transfer" : "contract-call",
8318
- outflows,
8319
- approvals: [],
8320
- fee: canFee ? { max: {
8321
- asset: SATS,
8322
- amount: (inSum - outSum).toString(10)
8323
- } } : undefined,
8324
- warnings: [],
8325
- verifiability
8326
- };
9639
+ return out;
8327
9640
  };
8328
- var common = (request) => {
8329
- const base = requestBase(request);
8330
- bitcoinNetwork(base.network);
8331
- return base;
9641
+ var varint = (n) => Uint8Array.of(n);
9642
+ var COMPACT_SIZE_ONE_BYTE_MAX = 252;
9643
+ var pushData = (data) => {
9644
+ if (data.length > COMPACT_SIZE_ONE_BYTE_MAX)
9645
+ throw new ChainError("invalid-request", "BIP-322 script data exceeds 252 bytes");
9646
+ return concat(varint(data.length), data);
8332
9647
  };
8333
- var messageTarget = (address, network, format) => {
8334
- if (typeof address !== "string")
8335
- throw new ChainError("invalid-request", "address must be a string");
8336
- const net = bitcoinNetwork(network);
8337
- let decoded;
8338
- try {
8339
- decoded = Address(net.params).decode(address);
8340
- } catch {
8341
- throw new ChainError("invalid-address", "address does not belong to this network");
9648
+ var u32le = (n) => Uint8Array.of(n % 256, Math.floor(n / 256) % 256, Math.floor(n / 65536) % 256, Math.floor(n / 16777216) % 256);
9649
+ var u64le = (n) => {
9650
+ const out = /* @__PURE__ */ new Uint8Array(8);
9651
+ let v = n;
9652
+ for (let i = 0;i < 8; i++) {
9653
+ out[i] = Number(v % 256n);
9654
+ v /= 256n;
8342
9655
  }
8343
- if (format === "bip322-simple") {
8344
- if (decoded.type !== "wpkh" && decoded.type !== "tr")
8345
- throw new ChainError("unsupported", "bip322-simple is only for P2WPKH/P2TR addresses");
8346
- } else if (format === "legacy") {
8347
- if (decoded.type !== "pkh")
8348
- throw new ChainError("unsupported", "legacy signing is only for P2PKH addresses");
8349
- } else
8350
- throw new ChainError("unsupported", `unsupported message format: ${String(format)}`);
8351
- const scriptPubKey = OutScript.encode(decoded);
9656
+ return out;
9657
+ };
9658
+ var bip322MessageHash = (message) => {
9659
+ const tag = sha256(utf8(BIP322_TAG));
9660
+ return sha256(concat(tag, tag, utf8(message)));
9661
+ };
9662
+ var toSpend = (scriptPubKey, messageHash) => {
9663
+ const scriptSig = concat(Uint8Array.of(0), pushData(messageHash));
9664
+ 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));
8352
9665
  return {
8353
- type: decoded.type,
8354
- address,
8355
- format,
8356
- scriptPubKey
9666
+ txid: sha256(sha256(raw)),
9667
+ raw
8357
9668
  };
8358
9669
  };
8359
- var normalizeBitcoin = (request) => {
8360
- if (!isRecord2(request) || typeof request["kind"] !== "string")
8361
- throw new ChainError("invalid-request", "request must be an object with a kind");
8362
- const { network, account } = common(request);
8363
- if (request["kind"] === "bitcoin.psbt") {
8364
- const { psbt } = request;
8365
- if (!(psbt instanceof Uint8Array))
8366
- throw new ChainError("invalid-request", "psbt must be bytes");
8367
- const normalized = normalizeBitcoinPsbt(psbt, request["sign"], network);
8368
- return {
8369
- kind: "bitcoin.psbt",
8370
- network,
8371
- account,
8372
- psbt: normalized.psbt,
8373
- sign: normalized.sign
8374
- };
8375
- }
8376
- if (request["kind"] === "bitcoin.message") {
8377
- const { format } = request;
8378
- const target = messageTarget(request["address"], network, format);
8379
- const { message, change, index } = request;
8380
- if (typeof message !== "string")
8381
- throw new ChainError("invalid-request", "message must be a string");
8382
- if (change !== 0 && change !== 1)
8383
- throw new ChainError("invalid-request", "change must be 0 or 1");
8384
- if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0 || index >= 2147483648)
8385
- throw new ChainError("invalid-request", "index must be a non-hardened path index");
8386
- return {
8387
- kind: "bitcoin.message",
8388
- network,
8389
- account,
8390
- address: target.address,
8391
- message,
8392
- format: target.format,
8393
- change,
8394
- index
8395
- };
9670
+ var BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
9671
+ var b642 = (i) => BASE64[i] ?? "";
9672
+ var base642 = (bytes) => {
9673
+ const c = b642;
9674
+ let out = "";
9675
+ for (let i = 0;i < bytes.length; i += 3) {
9676
+ const b0 = bytes[i] ?? 0;
9677
+ const b1 = bytes[i + 1] ?? 0;
9678
+ const b2 = bytes[i + 2] ?? 0;
9679
+ out += c(Math.floor(b0 / 4)) + c(b0 % 4 * 16 + Math.floor(b1 / 16));
9680
+ out += i + 1 < bytes.length ? c(b1 % 16 * 4 + Math.floor(b2 / 64)) : "=";
9681
+ out += i + 2 < bytes.length ? c(b2 % 64) : "=";
8396
9682
  }
8397
- throw new ChainError("unsupported", `unsupported sign request kind: ${request["kind"]}`);
9683
+ return out;
9684
+ };
9685
+ var signBip322Simple = (message, scriptPubKey, privateKey, auxRand) => {
9686
+ const hash = bip322MessageHash(message);
9687
+ const { txid } = toSpend(scriptPubKey, hash);
9688
+ const tx = new Transaction({
9689
+ version: 0,
9690
+ lockTime: 0,
9691
+ allowUnknownOutputs: true
9692
+ });
9693
+ const pub = secp256k1.getPublicKey(privateKey, true);
9694
+ tx.addInput({
9695
+ txid,
9696
+ index: 0,
9697
+ sequence: 0,
9698
+ witnessUtxo: {
9699
+ script: scriptPubKey,
9700
+ amount: 0n
9701
+ },
9702
+ bip32Derivation: [[pub, {
9703
+ fingerprint: 0,
9704
+ path: []
9705
+ }]],
9706
+ ...scriptPubKey[0] === 81 ? { tapInternalKey: pub.slice(1) } : {}
9707
+ });
9708
+ tx.addOutput({
9709
+ script: Uint8Array.of(106),
9710
+ amount: 0n
9711
+ });
9712
+ const isTaproot = scriptPubKey[0] === 81;
9713
+ if (!tx.signIdx(privateKey, 0, isTaproot ? [SigHash.DEFAULT, SigHash.ALL] : [SigHash.ALL], auxRand(0)))
9714
+ throw new ChainError("invalid-request", "key cannot sign this BIP-322 input");
9715
+ tx.finalizeIdx(0);
9716
+ const witness = tx.getInput(0).finalScriptWitness;
9717
+ if (witness === undefined)
9718
+ throw new ChainError("invalid-request", "BIP-322 input produced no witness");
9719
+ const raw = concat(varint(witness.length), ...witness.map(pushData));
9720
+ return `smp${base642(raw)}`;
9721
+ };
9722
+ var signLegacyMessage = (message, privateKey) => {
9723
+ const data = concat(pushData(LEGACY_MAGIC), pushData(utf8(message)));
9724
+ const hash = sha256(sha256(data));
9725
+ const recovered = secp256k1.sign(hash, privateKey, {
9726
+ lowS: true,
9727
+ format: "recovered"
9728
+ });
9729
+ const header = 27 + (recovered[0] ?? 0) + 4;
9730
+ return base642(concat(Uint8Array.of(header), recovered.slice(1)));
8398
9731
  };
8399
- var decodeMessageTarget = (request) => messageTarget(request.address, request.network, request.format);
8400
9732
 
8401
- // ../../node_modules/.bun/@noble+hashes@2.4.0/node_modules/@noble/hashes/sha3.js
8402
- var _0n4 = BigInt(0);
8403
- var _1n4 = BigInt(1);
8404
- var _2n4 = BigInt(2);
8405
- var _7n = BigInt(7);
8406
- var _256n = BigInt(256);
8407
- var _0x71n = BigInt(113);
8408
- var SHA3_PI = [];
8409
- var SHA3_ROTL = [];
8410
- var _SHA3_IOTA = [];
8411
- for (let round = 0, R = _1n4, x = 1, y = 0;round < 24; round++) {
8412
- [x, y] = [y, (2 * x + 3 * y) % 5];
8413
- SHA3_PI.push(2 * (5 * y + x));
8414
- SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
8415
- let t = _0n4;
8416
- for (let j = 0;j < 7; j++) {
8417
- R = (R << _1n4 ^ (R >> _7n) * _0x71n) % _256n;
8418
- if (R & _2n4)
8419
- t ^= _1n4 << (_1n4 << BigInt(j)) - _1n4;
8420
- }
8421
- _SHA3_IOTA.push(t);
8422
- }
8423
- var IOTAS = split(_SHA3_IOTA, true);
8424
- var SHA3_IOTA_H = IOTAS[0];
8425
- var SHA3_IOTA_L = IOTAS[1];
8426
- var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
8427
- var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
8428
- var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
8429
- var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
8430
- var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
8431
- var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
8432
- var B = new Uint32Array(5 * 2);
8433
- function keccakP(s, rounds = 24) {
8434
- if (!(s instanceof Uint32Array))
8435
- throw new TypeError('"s" expected Uint32Array(50), got type=' + typeof s);
8436
- if (s.length !== 50)
8437
- throw new RangeError('"s" expected Uint32Array(50), got length=' + s.length);
8438
- anumber(rounds, "rounds");
8439
- if (rounds < 1 || rounds > 24)
8440
- throw new Error('"rounds" expected integer 1..24');
8441
- for (let round = 24 - rounds;round < 24; round++) {
8442
- for (let x = 0;x < 10; x++)
8443
- B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
8444
- for (let x = 0;x < 10; x += 2) {
8445
- const idx1 = (x + 8) % 10;
8446
- const idx0 = (x + 2) % 10;
8447
- const B0 = B[idx0];
8448
- const B1 = B[idx0 + 1];
8449
- const Th = rotlH(B0, B1, 1) ^ B[idx1];
8450
- const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
8451
- for (let y = 0;y < 50; y += 10) {
8452
- s[x + y] ^= Th;
8453
- s[x + y + 1] ^= Tl;
8454
- }
8455
- }
8456
- let curH = s[2];
8457
- let curL = s[3];
8458
- for (let t = 0;t < 24; t++) {
8459
- const shift = SHA3_ROTL[t];
8460
- const Th = rotlH(curH, curL, shift);
8461
- const Tl = rotlL(curH, curL, shift);
8462
- const PI = SHA3_PI[t];
8463
- curH = s[PI];
8464
- curL = s[PI + 1];
8465
- s[PI] = Th;
8466
- s[PI + 1] = Tl;
8467
- }
8468
- for (let y = 0;y < 50; y += 10) {
8469
- const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3];
8470
- s[y] ^= ~s[y + 2] & s[y + 4];
8471
- s[y + 1] ^= ~s[y + 3] & s[y + 5];
8472
- s[y + 2] ^= ~s[y + 4] & s[y + 6];
8473
- s[y + 3] ^= ~s[y + 5] & s[y + 7];
8474
- s[y + 4] ^= ~s[y + 6] & s[y + 8];
8475
- s[y + 5] ^= ~s[y + 7] & s[y + 9];
8476
- s[y + 6] ^= ~s[y + 8] & b0;
8477
- s[y + 7] ^= ~s[y + 9] & b1;
8478
- s[y + 8] ^= ~b0 & b2;
8479
- s[y + 9] ^= ~b1 & b3;
8480
- }
8481
- s[0] ^= SHA3_IOTA_H[round];
8482
- s[1] ^= SHA3_IOTA_L[round];
9733
+ // ../wallet-chains/dist/bitcoin.mjs
9734
+ var isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9735
+ var derivationPaths = (map) => {
9736
+ const entries = map instanceof Map ? [...map.values()] : Array.isArray(map) ? map : isRecord$1(map) ? Object.values(map) : [];
9737
+ const paths = [];
9738
+ for (const entry of entries) {
9739
+ const value = Array.isArray(entry) ? entry[1] : entry;
9740
+ if (!isRecord$1(value))
9741
+ continue;
9742
+ const { path } = isRecord$1(value["der"]) ? value["der"] : value;
9743
+ if (Array.isArray(path) && path.every((p) => typeof p === "number"))
9744
+ paths.push(path);
8483
9745
  }
8484
- clean(B);
8485
- }
8486
-
8487
- class Keccak {
8488
- state;
8489
- pos = 0;
8490
- posOut = 0;
8491
- finished = false;
8492
- state32;
8493
- destroyed = false;
8494
- blockLen;
8495
- suffix;
8496
- outputLen;
8497
- canXOF;
8498
- enableXOF = false;
8499
- rounds;
8500
- constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
8501
- anumber(blockLen, "blockLen");
8502
- anumber(suffix, "suffix");
8503
- anumber(rounds, "rounds");
8504
- abool(enableXOF, "enableXOF");
8505
- this.blockLen = blockLen;
8506
- this.suffix = suffix;
8507
- this.outputLen = outputLen;
8508
- this.enableXOF = enableXOF;
8509
- this.canXOF = enableXOF;
8510
- this.rounds = rounds;
8511
- anumber(outputLen, "outputLen");
8512
- if (!(0 < blockLen && blockLen < 200))
8513
- throw new Error('"blockLen" must be 1..199');
8514
- this.state = new Uint8Array(200);
8515
- this.state32 = u32(this.state);
9746
+ return paths;
9747
+ };
9748
+ var checkPaths = (paths, where, coinType) => {
9749
+ for (const path of paths)
9750
+ if (path.length >= 2 && (path[1] ?? -1) - 2147483648 !== coinType)
9751
+ throw new ChainError("chain-id-mismatch", `${where} derivation coin type is not this network's`);
9752
+ };
9753
+ var checkDerivations = (tx, coinType) => {
9754
+ for (let i = 0;i < tx.inputsLength; i++) {
9755
+ const input = tx.getInput(i);
9756
+ checkPaths(derivationPaths(input.bip32Derivation), `input ${i}`, coinType);
9757
+ checkPaths(derivationPaths(input.tapBip32Derivation), `input ${i}`, coinType);
8516
9758
  }
8517
- clone() {
8518
- return this._cloneInto();
9759
+ for (let i = 0;i < tx.outputsLength; i++) {
9760
+ const output = tx.getOutput(i);
9761
+ checkPaths(derivationPaths(output.bip32Derivation), `output ${i}`, coinType);
9762
+ checkPaths(derivationPaths(output.tapBip32Derivation), `output ${i}`, coinType);
8519
9763
  }
8520
- keccak() {
8521
- swap32IfBE(this.state32);
8522
- keccakP(this.state32, this.rounds);
8523
- swap32IfBE(this.state32);
8524
- this.posOut = 0;
8525
- this.pos = 0;
9764
+ };
9765
+ var DEFAULT_SIGHASH = 0;
9766
+ var SIGHASH_ALL = 1;
9767
+ var isTaprootInput = (input) => input.tapInternalKey !== undefined || getInputType(input).type === "taproot";
9768
+ var normalizeBitcoinPsbt = (psbt, sign, network) => {
9769
+ const net = bitcoinNetwork(network);
9770
+ let tx;
9771
+ try {
9772
+ tx = Transaction.fromPSBT(psbt, { strictPrevoutValidation: true });
9773
+ } catch {
9774
+ throw new ChainError("invalid-request", "PSBT failed to decode");
8526
9775
  }
8527
- update(data) {
8528
- aexists(this);
8529
- abytes(data);
8530
- const { blockLen, state, state32 } = this;
8531
- const len = data.length;
8532
- const canUseU32 = blockLen % 4 === 0 && data.byteOffset % 4 === 0;
8533
- const blockLen32 = blockLen / 4;
8534
- const data32 = canUseU32 && len >= blockLen ? u32(data) : undefined;
8535
- for (let pos = 0;pos < len; ) {
8536
- if (data32 !== undefined && this.pos === 0 && pos % 4 === 0 && len - pos >= blockLen) {
8537
- for (let i = 0, o = pos / 4;i < blockLen32; i++)
8538
- state32[i] ^= data32[o + i];
8539
- pos += blockLen;
8540
- this.pos = blockLen;
8541
- this.keccak();
8542
- continue;
8543
- }
8544
- const take = Math.min(blockLen - this.pos, len - pos);
8545
- for (let i = 0;i < take; i++)
8546
- state[this.pos++] ^= data[pos++];
8547
- if (this.pos === blockLen)
8548
- this.keccak();
8549
- }
8550
- return this;
9776
+ if (!Array.isArray(sign) || sign.length === 0 || !sign.every((i) => Number.isSafeInteger(i) && i >= 0))
9777
+ throw new ChainError("invalid-request", "sign must be a non-empty array of input indices");
9778
+ const unique = [...new Set(sign.map(Number))].sort((a, b) => a - b);
9779
+ const last = unique.at(-1);
9780
+ if (unique.length !== sign.length || last === undefined || last >= tx.inputsLength)
9781
+ throw new ChainError("invalid-request", "sign must be unique, ascending, and in range");
9782
+ checkDerivations(tx, net.coinType);
9783
+ for (const idx of unique) {
9784
+ const input = tx.getInput(idx);
9785
+ if (input.witnessUtxo === undefined && input.nonWitnessUtxo === undefined)
9786
+ throw new ChainError("invalid-request", `input ${idx} carries neither witnessUtxo nor nonWitnessUtxo`);
9787
+ if (input.bip32Derivation === undefined && input.tapBip32Derivation === undefined)
9788
+ throw new ChainError("invalid-request", `input ${idx} is missing a bip32 derivation`);
9789
+ const { type } = getInputType(input);
9790
+ if ((type === "legacy" || type === "nonwitness-script") && input.nonWitnessUtxo === undefined)
9791
+ throw new ChainError("invalid-request", `input ${idx} is missing nonWitnessUtxo`);
9792
+ const sighash = input.sighashType;
9793
+ if (!(sighash === undefined || sighash === SIGHASH_ALL || isTaprootInput(input) && sighash === DEFAULT_SIGHASH || sighash === 131))
9794
+ throw new ChainError("unsupported", `input ${idx} uses a non-default sighash`);
9795
+ if (sighash === 131 && idx >= tx.outputsLength)
9796
+ throw new ChainError("unsupported", `input ${idx} uses SIGHASH_SINGLE without a same-index output`);
8551
9797
  }
8552
- finish() {
8553
- if (this.finished)
8554
- return;
8555
- this.finished = true;
8556
- const { state, suffix, pos, blockLen } = this;
8557
- state[pos] ^= suffix;
8558
- if ((suffix & 128) !== 0 && pos === blockLen - 1)
8559
- this.keccak();
8560
- state[blockLen - 1] ^= 128;
8561
- this.keccak();
9798
+ return {
9799
+ psbt: tx.toPSBT(0),
9800
+ sign: unique
9801
+ };
9802
+ };
9803
+ var SATS = "sats";
9804
+ var SIGHASH_SINGLE_ANYONECANPAY = 131;
9805
+ var OP_RETURN = 106;
9806
+ var parsePsbt = (psbt) => {
9807
+ try {
9808
+ return Transaction.fromPSBT(psbt);
9809
+ } catch (error) {
9810
+ throw error instanceof ChainError ? error : new ChainError("invalid-request", "malformed PSBT");
8562
9811
  }
8563
- writeInto(out) {
8564
- aexists(this, false);
8565
- abytes(out);
8566
- this.finish();
8567
- const bufferOut = this.state;
8568
- const { blockLen } = this;
8569
- for (let pos = 0, len = out.length;pos < len; ) {
8570
- if (this.posOut >= blockLen)
8571
- this.keccak();
8572
- const take = Math.min(blockLen - this.posOut, len - pos);
8573
- out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
8574
- this.posOut += take;
8575
- pos += take;
9812
+ };
9813
+ var bytesToHex4 = (bytes) => {
9814
+ let out = "";
9815
+ for (const b of bytes)
9816
+ out += b.toString(16).padStart(2, "0");
9817
+ return out;
9818
+ };
9819
+ var decodeOutput = (script, amount) => {
9820
+ const hex = bytesToHex4(script);
9821
+ if (script[0] === OP_RETURN)
9822
+ return {
9823
+ amount,
9824
+ script: hex,
9825
+ opReturn: true
9826
+ };
9827
+ return {
9828
+ amount,
9829
+ script: hex,
9830
+ opReturn: false
9831
+ };
9832
+ };
9833
+ var decodeBitcoinPsbt = (request, ownScripts = /* @__PURE__ */ new Set) => {
9834
+ const tx = parsePsbt(request.psbt);
9835
+ const coder = Address(bitcoinNetwork(request.network).params);
9836
+ const signed = new Set(request.sign);
9837
+ const outflows = [];
9838
+ let canFee = true;
9839
+ let outSum = 0n;
9840
+ for (let i = 0;i < tx.outputsLength; i++) {
9841
+ const output = tx.getOutput(i);
9842
+ const { script } = output;
9843
+ const { amount } = output;
9844
+ if (script === undefined || amount === undefined)
9845
+ continue;
9846
+ const decoded = decodeOutput(script, amount);
9847
+ outSum += amount;
9848
+ if (decoded.opReturn || ownScripts.has(decoded.script))
9849
+ continue;
9850
+ let addr;
9851
+ try {
9852
+ const out = OutScript.decode(script);
9853
+ addr = out === undefined ? undefined : coder.encode(out);
9854
+ } catch {
9855
+ addr = undefined;
8576
9856
  }
8577
- return out;
8578
- }
8579
- xofInto(out) {
8580
- if (!this.enableXOF)
8581
- throw new Error("XOF is not enabled");
8582
- return this.writeInto(out);
8583
- }
8584
- xof(bytes) {
8585
- anumber(bytes);
8586
- return this.xofInto(new Uint8Array(bytes));
9857
+ outflows.push({
9858
+ to: addr ?? decoded.script,
9859
+ amount: {
9860
+ asset: SATS,
9861
+ amount: amount.toString(10)
9862
+ },
9863
+ verified: addr !== undefined
9864
+ });
8587
9865
  }
8588
- digestInto(out) {
8589
- aoutput(out, this);
8590
- if (this.finished)
8591
- throw new Error("digest() was already called");
8592
- this.writeInto(out.length === this.outputLen ? out : out.subarray(0, this.outputLen));
8593
- this.destroy();
9866
+ let inSum = 0n;
9867
+ for (let i = 0;i < tx.inputsLength; i++) {
9868
+ const input = tx.getInput(i);
9869
+ if (input.witnessUtxo === undefined)
9870
+ canFee = false;
9871
+ else
9872
+ inSum += input.witnessUtxo.amount;
8594
9873
  }
8595
- digest() {
8596
- const out = new Uint8Array(this.outputLen);
8597
- this.digestInto(out);
8598
- return out;
9874
+ const external = tx.inputsLength - signed.size > 0;
9875
+ const undecodable = outflows.some((o) => !o.verified);
9876
+ const listing = request.sign.some((i) => tx.getInput(i).sighashType === SIGHASH_SINGLE_ANYONECANPAY);
9877
+ const verifiability = external ? "opaque" : listing || undecodable ? "partial" : "full";
9878
+ return {
9879
+ family: "bitcoin",
9880
+ network: request.network,
9881
+ summary: outflows.length > 0 ? "transfer" : "contract-call",
9882
+ outflows,
9883
+ approvals: [],
9884
+ fee: canFee && !listing ? { max: {
9885
+ asset: SATS,
9886
+ amount: (inSum - outSum).toString(10)
9887
+ } } : undefined,
9888
+ warnings: listing ? [{
9889
+ kind: "sighash-single-anyonecanpay",
9890
+ message: "signed inputs bind only their same-index outputs; the rest of the transaction can change"
9891
+ }] : [],
9892
+ verifiability
9893
+ };
9894
+ };
9895
+ var common = (request) => {
9896
+ const base = requestBase(request);
9897
+ bitcoinNetwork(base.network);
9898
+ return base;
9899
+ };
9900
+ var messageTarget = (address, network, format) => {
9901
+ if (typeof address !== "string")
9902
+ throw new ChainError("invalid-request", "address must be a string");
9903
+ const net = bitcoinNetwork(network);
9904
+ let decoded;
9905
+ try {
9906
+ decoded = Address(net.params).decode(address);
9907
+ } catch {
9908
+ throw new ChainError("invalid-address", "address does not belong to this network");
8599
9909
  }
8600
- destroy() {
8601
- this.destroyed = true;
8602
- clean(this.state);
9910
+ if (format === "bip322-simple") {
9911
+ if (decoded.type !== "wpkh" && decoded.type !== "tr")
9912
+ throw new ChainError("unsupported", "bip322-simple is only for P2WPKH/P2TR addresses");
9913
+ } else if (format === "legacy") {
9914
+ if (decoded.type !== "pkh")
9915
+ throw new ChainError("unsupported", "legacy signing is only for P2PKH addresses");
9916
+ } else
9917
+ throw new ChainError("unsupported", `unsupported message format: ${String(format)}`);
9918
+ const scriptPubKey = OutScript.encode(decoded);
9919
+ return {
9920
+ type: decoded.type,
9921
+ address,
9922
+ format,
9923
+ scriptPubKey
9924
+ };
9925
+ };
9926
+ var normalizeBitcoin = (request) => {
9927
+ if (!isRecord2(request) || typeof request["kind"] !== "string")
9928
+ throw new ChainError("invalid-request", "request must be an object with a kind");
9929
+ const { network, account } = common(request);
9930
+ if (request["kind"] === "bitcoin.psbt") {
9931
+ const { psbt } = request;
9932
+ if (!(psbt instanceof Uint8Array))
9933
+ throw new ChainError("invalid-request", "psbt must be bytes");
9934
+ const normalized = normalizeBitcoinPsbt(psbt, request["sign"], network);
9935
+ return {
9936
+ kind: "bitcoin.psbt",
9937
+ network,
9938
+ account,
9939
+ psbt: normalized.psbt,
9940
+ sign: normalized.sign
9941
+ };
8603
9942
  }
8604
- _cloneInto(to) {
8605
- const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
8606
- to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);
8607
- to.blockLen = blockLen;
8608
- to.state32.set(this.state32);
8609
- to.pos = this.pos;
8610
- to.posOut = this.posOut;
8611
- to.finished = this.finished;
8612
- to.rounds = rounds;
8613
- to.suffix = suffix;
8614
- to.outputLen = outputLen;
8615
- to.enableXOF = enableXOF;
8616
- to.canXOF = this.canXOF;
8617
- to.destroyed = this.destroyed;
8618
- return to;
9943
+ if (request["kind"] === "bitcoin.message") {
9944
+ const { format } = request;
9945
+ const target = messageTarget(request["address"], network, format);
9946
+ const { message, change, index } = request;
9947
+ if (typeof message !== "string")
9948
+ throw new ChainError("invalid-request", "message must be a string");
9949
+ if (change !== 0 && change !== 1)
9950
+ throw new ChainError("invalid-request", "change must be 0 or 1");
9951
+ if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0 || index >= 2147483648)
9952
+ throw new ChainError("invalid-request", "index must be a non-hardened path index");
9953
+ return {
9954
+ kind: "bitcoin.message",
9955
+ network,
9956
+ account,
9957
+ address: target.address,
9958
+ message,
9959
+ format: target.format,
9960
+ change,
9961
+ index
9962
+ };
8619
9963
  }
8620
- }
8621
- var genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);
8622
- var keccak_256 = /* @__PURE__ */ genKeccak(1, 136, 32);
9964
+ throw new ChainError("unsupported", `unsupported sign request kind: ${request["kind"]}`);
9965
+ };
9966
+ var decodeMessageTarget = (request) => messageTarget(request.address, request.network, request.format);
8623
9967
 
8624
9968
  // ../../node_modules/.bun/ox@1.8.12+ff0372d108591aba/node_modules/ox/dist/core/version.js
8625
9969
  var version = "0.1.1";
@@ -8924,7 +10268,7 @@ class IntegerOutOfRangeError extends BaseError {
8924
10268
  }
8925
10269
 
8926
10270
  // ../../node_modules/.bun/ox@1.8.12+ff0372d108591aba/node_modules/ox/dist/core/internal/codec/utf8.js
8927
- var encoder = /* @__PURE__ */ new TextEncoder;
10271
+ var encoder2 = /* @__PURE__ */ new TextEncoder;
8928
10272
  var decoder = /* @__PURE__ */ new TextDecoder;
8929
10273
 
8930
10274
  // ../../node_modules/.bun/ox@1.8.12+ff0372d108591aba/node_modules/ox/dist/core/Json.js
@@ -9032,7 +10376,7 @@ function fromNumber(value, options = {}) {
9032
10376
  return hex;
9033
10377
  }
9034
10378
  function fromString(value, options = {}) {
9035
- return fromBytes(encoder.encode(value), options);
10379
+ return fromBytes(encoder2.encode(value), options);
9036
10380
  }
9037
10381
  function padLeft(value, size) {
9038
10382
  return pad3(value, { dir: "left", size });
@@ -9198,7 +10542,7 @@ function fromHex(value, options = {}) {
9198
10542
  }
9199
10543
  function fromString2(value, options = {}) {
9200
10544
  const { size } = options;
9201
- const bytes = encoder.encode(value);
10545
+ const bytes = encoder2.encode(value);
9202
10546
  if (typeof size === "number") {
9203
10547
  assertSize(bytes, size);
9204
10548
  return padRight2(bytes, size);
@@ -10618,7 +11962,7 @@ function writeParameter(context, offset, parameter, value) {
10618
11962
  const value_ = normalizeString(value);
10619
11963
  const size = getUtf8Size(value_);
10620
11964
  writeWord(context, offset, size);
10621
- const { written } = encoder.encodeInto(value_, context.bytes.subarray(offset + 32, offset + 32 + size));
11965
+ const { written } = encoder2.encodeInto(value_, context.bytes.subarray(offset + 32, offset + 32 + size));
10622
11966
  if (written !== size)
10623
11967
  throw new Error("Failed to encode string.");
10624
11968
  return offset + 32 + Math.ceil(size / 32) * 32;
@@ -11348,7 +12692,7 @@ function validateReference(type) {
11348
12692
  throw new InvalidStructTypeError({ type });
11349
12693
  }
11350
12694
 
11351
- // ../wallet-chains/dist/typed-data-Cf1g7JVv.mjs
12695
+ // ../wallet-chains/dist/typed-data-J5g2WemC.mjs
11352
12696
  var isEvmAddress = (value) => /^0x[0-9a-fA-F]{40}$/.test(value);
11353
12697
  function checksumEvmAddress(address) {
11354
12698
  if (!isEvmAddress(address))
@@ -11370,6 +12714,11 @@ function assertHex(value, field) {
11370
12714
  var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
11371
12715
  var CANONICAL_HEX = /^0x(?:0|[1-9a-f][0-9a-f]*)$/;
11372
12716
  var canonicalHex = (value) => `0x${value.toString(16)}`;
12717
+ var quantityBigInt = (value, field) => {
12718
+ if (typeof value !== "string" || !/^0x[0-9a-fA-F]+$/.test(value))
12719
+ throw new ChainError("invalid-quantity", `${field} must be a 0x quantity`);
12720
+ return BigInt(value);
12721
+ };
11373
12722
  var safeInteger = (value, field) => {
11374
12723
  if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0)
11375
12724
  throw new ChainError("invalid-quantity", `${field} must be a non-negative safe integer`);
@@ -11380,9 +12729,7 @@ var quantity = (value, field) => {
11380
12729
  throw new ChainError("invalid-quantity", `${field} must be a 0x quantity string`);
11381
12730
  if (CANONICAL_HEX.test(value))
11382
12731
  return value;
11383
- if (/^0x[0-9a-fA-F]+$/.test(value) || value === "0x")
11384
- return canonicalHex(BigInt(value === "0x" ? "0x0" : value));
11385
- throw new ChainError("invalid-quantity", `${field} must be a 0x quantity`);
12732
+ return canonicalHex(quantityBigInt(value, field));
11386
12733
  };
11387
12734
  var hexBytes = (value, field) => {
11388
12735
  if (typeof value !== "string" || !/^0x(?:[0-9a-fA-F]{2})*$/.test(value))
@@ -11529,7 +12876,25 @@ var isTypedDataInput = (value) => {
11529
12876
  return false;
11530
12877
  return Object.values(types).every((fields) => Array.isArray(fields) && fields.every(isField));
11531
12878
  };
11532
- var parseTypedData = (typedData, network) => {
12879
+ var isTypedDataMessage = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12880
+ var typedDataMessages = (value) => Array.isArray(value) && value.every(isTypedDataMessage) ? value : undefined;
12881
+ var typedDataSignature = (types, name) => types[name]?.map((field) => `${field.type} ${field.name}`).join(",");
12882
+ var sameFields = (types, name, fields) => typedDataSignature(types, name) === fields.join(",");
12883
+ var typedDataAddress = (value) => typeof value === "string" && /^0x[0-9a-fA-F]{40}$/.test(value) ? checksumEvmAddress(value) : undefined;
12884
+ var typedDataUint = (value, max) => {
12885
+ let parsed;
12886
+ if (typeof value === "number" && Number.isSafeInteger(value))
12887
+ parsed = BigInt(value);
12888
+ else if (typeof value === "string" && /^(?:[0-9]+|0x[0-9a-fA-F]+)$/.test(value))
12889
+ parsed = BigInt(value);
12890
+ else
12891
+ return;
12892
+ return parsed >= 0n && parsed <= max ? parsed : undefined;
12893
+ };
12894
+ var MAX_UINT48 = 2n ** 48n - 1n;
12895
+ var isHexBytes = (value) => typeof value === "string" && /^0x[0-9a-fA-F]*$/.test(value);
12896
+ var typedDataBytes = (value) => isHexBytes(value) ? value : undefined;
12897
+ var parseTypedData = (typedData) => {
11533
12898
  let json;
11534
12899
  try {
11535
12900
  json = JSON.parse(typedData);
@@ -11543,17 +12908,17 @@ var parseTypedData = (typedData, network) => {
11543
12908
  } catch {
11544
12909
  throw new ChainError("invalid-typed-data", "typedData failed EIP-712 validation");
11545
12910
  }
11546
- const { chainId } = json.domain;
11547
- const numeric = typeof chainId === "number" ? chainId : typeof chainId === "string" ? Number(chainId) : NaN;
11548
- return {
11549
- json,
11550
- chainIdMismatch: Number.isSafeInteger(numeric) && numeric !== networkChainId(network)
11551
- };
12911
+ return { json };
12912
+ };
12913
+ var domainChainId = (domain) => {
12914
+ const { chainId } = domain;
12915
+ if (chainId === undefined)
12916
+ return;
12917
+ const numeric = typeof chainId === "number" ? chainId : typeof chainId === "string" && /^(?:[0-9]+|0x[0-9a-fA-F]+)$/.test(chainId) ? Number(chainId) : NaN;
12918
+ if (!Number.isSafeInteger(numeric) || numeric < 0)
12919
+ throw new ChainError("invalid-typed-data", "typed-data domain.chainId is malformed");
12920
+ return numeric;
11552
12921
  };
11553
- var typedDataWarnings = (parsed) => parsed.chainIdMismatch ? [{
11554
- kind: "chain-id-mismatch",
11555
- message: "typed-data domain.chainId does not match the request network"
11556
- }] : [];
11557
12922
 
11558
12923
  // ../../node_modules/.bun/ox@1.8.12+ff0372d108591aba/node_modules/ox/dist/core/internal/human-readable/formatAbiItem.js
11559
12924
  function formatAbiItem(abiItem) {
@@ -12595,7 +13960,7 @@ var exponents = {
12595
13960
  finney: 15,
12596
13961
  ether: 18
12597
13962
  };
12598
- function format(value, decimals = 0) {
13963
+ function format3(value, decimals = 0) {
12599
13964
  if (!Number.isInteger(decimals) || decimals < 0)
12600
13965
  throw new InvalidDecimalsError({ decimals });
12601
13966
  let display = value.toString();
@@ -12611,7 +13976,7 @@ function format(value, decimals = 0) {
12611
13976
  return `${negative ? "-" : ""}${integer || "0"}${fraction ? `.${fraction}` : ""}`;
12612
13977
  }
12613
13978
  function formatGwei(wei, unit = "wei") {
12614
- return format(wei, exponents.gwei - exponents[unit]);
13979
+ return format3(wei, exponents.gwei - exponents[unit]);
12615
13980
  }
12616
13981
  class InvalidDecimalsError extends BaseError {
12617
13982
  name = "Value.InvalidDecimalsError";
@@ -12703,6 +14068,7 @@ function serialize3(envelope, options = {}) {
12703
14068
  }
12704
14069
 
12705
14070
  // ../wallet-chains/dist/evm.mjs
14071
+ var EVM_NATIVE_ASSET = "native";
12706
14072
  var USDC = Object.freeze({
12707
14073
  symbol: "USDC",
12708
14074
  decimals: 6,
@@ -12729,14 +14095,364 @@ var evmTokenTable = Object.freeze({
12729
14095
  })
12730
14096
  });
12731
14097
  var lookupEvmToken = (table, chainId, address) => table[String(chainId)]?.[address];
14098
+ var MAX_UINT256 = 2n ** 256n - 1n;
14099
+ var MAX_UINT160 = 2n ** 160n - 1n;
14100
+ var allowanceChange = (token, spender, value, change, max, chainId, table, extra = {}) => {
14101
+ const known = lookupEvmToken(table, chainId, token);
14102
+ return {
14103
+ kind: "allowance",
14104
+ spender,
14105
+ amount: {
14106
+ asset: token,
14107
+ amount: value.toString(10),
14108
+ ...known === undefined ? {} : {
14109
+ symbol: known.symbol,
14110
+ decimals: known.decimals
14111
+ }
14112
+ },
14113
+ change,
14114
+ unlimited: change !== "decrease" && value === max,
14115
+ ...extra,
14116
+ verified: known !== undefined
14117
+ };
14118
+ };
14119
+ var isMessage = isTypedDataMessage;
14120
+ var address = typedDataAddress;
14121
+ var uint = typedDataUint;
14122
+ var DETAILS = [
14123
+ "address token",
14124
+ "uint160 amount",
14125
+ "uint48 expiration",
14126
+ "uint48 nonce"
14127
+ ];
14128
+ var PERMISSIONS = ["address token", "uint256 amount"];
14129
+ var WITNESS_WARNING = {
14130
+ kind: "permit2-witness",
14131
+ message: "the permit carries a witness with further terms"
14132
+ };
14133
+ var entries = (value) => Array.isArray(value) && value.length > 0 && value.every(isMessage) ? value : undefined;
14134
+ var permit = (...approvals) => ({
14135
+ approvals,
14136
+ warnings: []
14137
+ });
14138
+ function recognizePermit(json, chainId, table) {
14139
+ const { types, primaryType, message, domain } = json;
14140
+ const verifying = address(domain["verifyingContract"]);
14141
+ if (verifying === undefined)
14142
+ return;
14143
+ const spender = address(message["spender"]);
14144
+ if (spender === undefined)
14145
+ return;
14146
+ const allow = (token, value, change, max, extra = {}) => allowanceChange(token, spender, value, change, max, chainId, table, extra);
14147
+ if (primaryType === "Permit") {
14148
+ if (sameFields(types, "Permit", [
14149
+ "address owner",
14150
+ "address spender",
14151
+ "uint256 value",
14152
+ "uint256 nonce",
14153
+ "uint256 deadline"
14154
+ ])) {
14155
+ const value = uint(message["value"], MAX_UINT256);
14156
+ return value === undefined ? undefined : permit(allow(verifying, value, "set", MAX_UINT256));
14157
+ }
14158
+ if (sameFields(types, "Permit", [
14159
+ "address holder",
14160
+ "address spender",
14161
+ "uint256 nonce",
14162
+ "uint256 expiry",
14163
+ "bool allowed"
14164
+ ])) {
14165
+ const { allowed } = message;
14166
+ return typeof allowed === "boolean" ? permit(allow(verifying, allowed ? MAX_UINT256 : 0n, "set", MAX_UINT256)) : undefined;
14167
+ }
14168
+ return;
14169
+ }
14170
+ if (verifying.toLowerCase() !== "0x000000000022D473030F116dDEE9F6B43aC78BA3".toLowerCase())
14171
+ return;
14172
+ return recognizePermit2(types, primaryType, message, allow);
14173
+ }
14174
+ var recognizePermit2 = (types, primaryType, message, allow) => {
14175
+ const via = "permit2";
14176
+ const allowance = (details) => {
14177
+ const token = address(details["token"]);
14178
+ const amount = uint(details["amount"], MAX_UINT160);
14179
+ const expiration = uint(details["expiration"], MAX_UINT48);
14180
+ return token === undefined || amount === undefined || expiration === undefined ? undefined : allow(token, amount, "set", MAX_UINT160, {
14181
+ via,
14182
+ expiration: Number(expiration)
14183
+ });
14184
+ };
14185
+ const transfer = (permitted, deadline) => {
14186
+ const token = address(permitted["token"]);
14187
+ const amount = uint(permitted["amount"], MAX_UINT256);
14188
+ return token === undefined || amount === undefined ? undefined : allow(token, amount, "transfer", MAX_UINT256, {
14189
+ via,
14190
+ ...deadline <= MAX_UINT48 ? { expiration: Number(deadline) } : {}
14191
+ });
14192
+ };
14193
+ const all = (list, build) => {
14194
+ const built = list?.map(build);
14195
+ return built === undefined || built.some((a) => a === undefined) ? undefined : permit(...built.filter((a) => a !== undefined));
14196
+ };
14197
+ if (primaryType === "PermitSingle") {
14198
+ const { details } = message;
14199
+ return sameFields(types, primaryType, [
14200
+ "PermitDetails details",
14201
+ "address spender",
14202
+ "uint256 sigDeadline"
14203
+ ]) && sameFields(types, "PermitDetails", DETAILS) && isMessage(details) ? all([details], allowance) : undefined;
14204
+ }
14205
+ if (primaryType === "PermitBatch")
14206
+ return sameFields(types, primaryType, [
14207
+ "PermitDetails[] details",
14208
+ "address spender",
14209
+ "uint256 sigDeadline"
14210
+ ]) && sameFields(types, "PermitDetails", DETAILS) ? all(entries(message["details"]), allowance) : undefined;
14211
+ const witness = primaryType.includes("Witness");
14212
+ const batch = primaryType.includes("Batch");
14213
+ const expected = batch ? [
14214
+ "TokenPermissions[] permitted",
14215
+ "address spender",
14216
+ "uint256 nonce",
14217
+ "uint256 deadline"
14218
+ ] : [
14219
+ "TokenPermissions permitted",
14220
+ "address spender",
14221
+ "uint256 nonce",
14222
+ "uint256 deadline"
14223
+ ];
14224
+ if (primaryType !== `Permit${batch ? "Batch" : ""}${witness ? "Witness" : ""}TransferFrom`)
14225
+ return;
14226
+ const own = types[primaryType];
14227
+ const last = own?.at(-1);
14228
+ const fieldsOk = witness ? sameFields({
14229
+ ...types,
14230
+ [primaryType]: own?.slice(0, -1) ?? []
14231
+ }, primaryType, expected) && last?.name === "witness" && types[last.type] !== undefined : sameFields(types, primaryType, expected);
14232
+ const deadline = uint(message["deadline"], MAX_UINT256);
14233
+ if (!fieldsOk || !sameFields(types, "TokenPermissions", PERMISSIONS) || deadline === undefined)
14234
+ return;
14235
+ const { permitted } = message;
14236
+ const result = batch ? all(entries(permitted), (item) => transfer(item, deadline)) : isMessage(permitted) ? all([permitted], (item) => transfer(item, deadline)) : undefined;
14237
+ return result === undefined || !witness ? result : {
14238
+ approvals: result.approvals,
14239
+ warnings: [WITNESS_WARNING]
14240
+ };
14241
+ };
14242
+ var SAFE_MULTISEND_CALL_ONLY = /* @__PURE__ */ new Set([
14243
+ "0x40a2accbd92bca938b02010e17a5b8929b49130d",
14244
+ "0xa1dabef33b3b82c7814b6d82a79e50f4ac44102b",
14245
+ "0x9641d764fc13c8b624c04430c7356c1c7c8102e2"
14246
+ ]);
14247
+ var SAFE_TX = [
14248
+ "address to",
14249
+ "uint256 value",
14250
+ "bytes data",
14251
+ "uint8 operation",
14252
+ "uint256 safeTxGas",
14253
+ "uint256 baseGas",
14254
+ "uint256 gasPrice",
14255
+ "address gasToken",
14256
+ "address refundReceiver",
14257
+ "uint256 nonce"
14258
+ ];
14259
+ var MULTISEND = from4("function multiSend(bytes transactions)");
14260
+ var multiSendEntries = (data) => {
14261
+ if (!data.toLowerCase().startsWith("0x8d80ff0a"))
14262
+ return;
14263
+ let packed;
14264
+ try {
14265
+ const decoded = decodeData(MULTISEND, data);
14266
+ const first = Array.isArray(decoded) ? decoded[0] : undefined;
14267
+ if (typeof first !== "string")
14268
+ return;
14269
+ packed = first;
14270
+ } catch {
14271
+ return;
14272
+ }
14273
+ if (!packed.startsWith("0x"))
14274
+ return;
14275
+ const hex = packed.slice(2).toLowerCase();
14276
+ const calls = [];
14277
+ let offset = 0;
14278
+ while (offset < hex.length) {
14279
+ if (hex.length - offset < 170)
14280
+ return;
14281
+ if (Number.parseInt(hex.slice(offset, offset + 2), 16) !== 0)
14282
+ return;
14283
+ const to = `0x${hex.slice(offset + 2, offset + 42)}`;
14284
+ const value = BigInt(`0x${hex.slice(offset + 42, offset + 106)}`);
14285
+ const length = BigInt(`0x${hex.slice(offset + 106, offset + 170)}`);
14286
+ offset += 170;
14287
+ if (length * 2n > BigInt(hex.length - offset))
14288
+ return;
14289
+ calls.push({
14290
+ to: checksumEvmAddress(to),
14291
+ value,
14292
+ data: `0x${hex.slice(offset, offset + Number(length) * 2)}`
14293
+ });
14294
+ offset += Number(length) * 2;
14295
+ }
14296
+ return calls;
14297
+ };
14298
+ function recognizeSafe(json, decode) {
14299
+ const { types, primaryType, message, domain } = json;
14300
+ if (primaryType !== "SafeTx" || !sameFields(types, "SafeTx", SAFE_TX))
14301
+ return;
14302
+ const safe = typedDataAddress(domain["verifyingContract"]);
14303
+ const to = typedDataAddress(message["to"]);
14304
+ const value = typedDataUint(message["value"], MAX_UINT256);
14305
+ const data = typedDataBytes(message["data"]);
14306
+ const operation = typedDataUint(message["operation"], 255n);
14307
+ const safeTxGas = typedDataUint(message["safeTxGas"], MAX_UINT256);
14308
+ const baseGas = typedDataUint(message["baseGas"], MAX_UINT256);
14309
+ const gasPrice = typedDataUint(message["gasPrice"], MAX_UINT256);
14310
+ const gasToken = typedDataAddress(message["gasToken"]);
14311
+ const refundReceiver = typedDataAddress(message["refundReceiver"]);
14312
+ const nonce = typedDataUint(message["nonce"], MAX_UINT256);
14313
+ 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)
14314
+ return;
14315
+ const inner = operation === 1n && SAFE_MULTISEND_CALL_ONLY.has(to.toLowerCase()) ? multiSendEntries(data) : undefined;
14316
+ const calls = (inner ?? [{
14317
+ to,
14318
+ value,
14319
+ data
14320
+ }]).map(decode);
14321
+ return {
14322
+ safe: {
14323
+ safe,
14324
+ nonce: nonce.toString(10),
14325
+ operation: operation === 0n ? "call" : "delegatecall",
14326
+ to,
14327
+ value: value.toString(10),
14328
+ data,
14329
+ calls,
14330
+ ...gasPrice > 0n ? { refund: {
14331
+ gasPrice: gasPrice.toString(10),
14332
+ gasToken,
14333
+ refundReceiver
14334
+ } } : {}
14335
+ },
14336
+ multisend: inner !== undefined
14337
+ };
14338
+ }
14339
+ var SEAPORT_CONTRACTS = /* @__PURE__ */ new Set(["0x0000000000000068f116a894984e2db1123eb395", "0x00000000000000adc04c56bf30ac9d3c0aaf14dc"]);
14340
+ var ITEM_KINDS = [
14341
+ "native",
14342
+ "erc20",
14343
+ "erc721",
14344
+ "erc1155",
14345
+ "erc721-criteria",
14346
+ "erc1155-criteria"
14347
+ ];
14348
+ var ITEM_FIELDS = [
14349
+ "uint8 itemType",
14350
+ "address token",
14351
+ "uint256 identifierOrCriteria",
14352
+ "uint256 startAmount",
14353
+ "uint256 endAmount"
14354
+ ];
14355
+ var typesMatch = (types) => Object.keys(types).length === 3 && sameFields(types, "OrderComponents", [
14356
+ "address offerer",
14357
+ "address zone",
14358
+ "OfferItem[] offer",
14359
+ "ConsiderationItem[] consideration",
14360
+ "uint8 orderType",
14361
+ "uint256 startTime",
14362
+ "uint256 endTime",
14363
+ "bytes32 zoneHash",
14364
+ "uint256 salt",
14365
+ "bytes32 conduitKey",
14366
+ "uint256 counter"
14367
+ ]) && sameFields(types, "OfferItem", ITEM_FIELDS) && sameFields(types, "ConsiderationItem", [...ITEM_FIELDS, "address recipient"]);
14368
+ var amount = (kind, token, value, chainId, table) => {
14369
+ if (kind === "native")
14370
+ return {
14371
+ asset: EVM_NATIVE_ASSET,
14372
+ amount: value.toString(10),
14373
+ symbol: "ETH",
14374
+ decimals: 18
14375
+ };
14376
+ if (kind === "erc20") {
14377
+ const found = lookupEvmToken(table, chainId, token);
14378
+ return {
14379
+ asset: token,
14380
+ amount: value.toString(10),
14381
+ ...found === undefined ? {} : {
14382
+ symbol: found.symbol,
14383
+ decimals: found.decimals
14384
+ }
14385
+ };
14386
+ }
14387
+ return {
14388
+ asset: token,
14389
+ amount: value.toString(10)
14390
+ };
14391
+ };
14392
+ var item = (message, chainId, table) => {
14393
+ const itemType = typedDataUint(message["itemType"], 255n);
14394
+ const token = typedDataAddress(message["token"]);
14395
+ const identifier = typedDataUint(message["identifierOrCriteria"], MAX_UINT256);
14396
+ const start = typedDataUint(message["startAmount"], MAX_UINT256);
14397
+ const end = typedDataUint(message["endAmount"], MAX_UINT256);
14398
+ const kind = itemType === undefined ? undefined : ITEM_KINDS[Number(itemType)];
14399
+ if (token === undefined || identifier === undefined || start === undefined || end === undefined || kind === undefined)
14400
+ return;
14401
+ return {
14402
+ kind,
14403
+ token,
14404
+ identifier: identifier.toString(10),
14405
+ startAmount: amount(kind, token, start, chainId, table),
14406
+ endAmount: amount(kind, token, end, chainId, table)
14407
+ };
14408
+ };
14409
+ var all = (list, build) => {
14410
+ const built = list?.map(build);
14411
+ return built === undefined || built.some((entry) => entry === undefined) ? undefined : built.filter((entry) => entry !== undefined);
14412
+ };
14413
+ function recognizeSeaport(json, chainId, table) {
14414
+ const { types, primaryType, message, domain } = json;
14415
+ if (primaryType !== "OrderComponents" || !typesMatch(types))
14416
+ return;
14417
+ const verifying = typedDataAddress(domain["verifyingContract"]);
14418
+ if (domain["name"] !== "Seaport" || verifying === undefined || !SEAPORT_CONTRACTS.has(verifying.toLowerCase()))
14419
+ return;
14420
+ const offerer = typedDataAddress(message["offerer"]);
14421
+ const zone = typedDataAddress(message["zone"]);
14422
+ const startTime = typedDataUint(message["startTime"], MAX_UINT256);
14423
+ const endTime = typedDataUint(message["endTime"], MAX_UINT256);
14424
+ const offer = all(typedDataMessages(message["offer"]), (entry) => item(entry, chainId, table));
14425
+ const consideration = all(typedDataMessages(message["consideration"]), (entry) => {
14426
+ const base = item(entry, chainId, table);
14427
+ const recipient = typedDataAddress(entry["recipient"]);
14428
+ return base === undefined || recipient === undefined ? undefined : {
14429
+ ...base,
14430
+ recipient
14431
+ };
14432
+ });
14433
+ if (offerer === undefined || zone === undefined || startTime === undefined || endTime === undefined || offer === undefined || consideration === undefined)
14434
+ return;
14435
+ return {
14436
+ offerer,
14437
+ zone,
14438
+ startTime: startTime <= MAX_UINT48 ? Number(startTime) : undefined,
14439
+ endTime: endTime <= MAX_UINT48 ? Number(endTime) : undefined,
14440
+ offer,
14441
+ consideration
14442
+ };
14443
+ }
12732
14444
  var ERC20_TRANSFER = from4("function transfer(address to, uint256 amount)");
12733
14445
  var ERC20_APPROVE = from4("function approve(address spender, uint256 amount)");
12734
14446
  var ERC20_INCREASE = from4("function increaseAllowance(address spender, uint256 amount)");
14447
+ var ERC20_DECREASE = from4("function decreaseAllowance(address spender, uint256 subtractedValue)");
14448
+ var SET_APPROVAL_FOR_ALL = from4("function setApprovalForAll(address operator, bool approved)");
14449
+ var PERMIT2_APPROVE = from4("function approve(address token, address spender, uint160 amount, uint48 expiration)");
14450
+ var PERMIT2_LOCKDOWN = from4("function lockdown((address token, address spender)[] approvals)");
14451
+ var ERC721_SAFE_FROM_DATA = from4("function safeTransferFrom(address from, address to, uint256 tokenId, bytes data)");
14452
+ var ERC1155_SAFE_BATCH_FROM = from4("function safeBatchTransferFrom(address from, address to, uint256[] ids, uint256[] amounts, bytes data)");
12735
14453
  var ERC721_TRANSFER_FROM = from4("function transferFrom(address from, address to, uint256 tokenId)");
12736
14454
  var ERC721_SAFE_FROM = from4("function safeTransferFrom(address from, address to, uint256 tokenId)");
12737
14455
  var ERC1155_SAFE_FROM = from4("function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes data)");
12738
- var NATIVE_ASSET = "native";
12739
- var MAX_UINT256 = 2n ** 256n - 1n;
12740
14456
  var argAddress = (args, index) => {
12741
14457
  const value = args[index];
12742
14458
  if (typeof value !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(value))
@@ -12764,24 +14480,24 @@ var tryCall = (fn, data) => {
12764
14480
  }
12765
14481
  };
12766
14482
  var weiAmount = (wei, symbol, decimals) => ({
12767
- asset: NATIVE_ASSET,
14483
+ asset: EVM_NATIVE_ASSET,
12768
14484
  amount: wei.toString(10),
12769
14485
  ...symbol === undefined ? {} : { symbol },
12770
14486
  ...decimals === undefined ? {} : { decimals }
12771
14487
  });
12772
- var feeWei = (tx) => BigInt(tx.gas) * (tx.type === "eip1559" ? BigInt(tx.maxFeePerGas) : BigInt(tx.gasPrice));
12773
- var nativeOutflow = (tx, to) => [{
14488
+ var feeWei = (tx) => quantityBigInt(tx.gas, "tx.gas") * (tx.type === "eip1559" ? quantityBigInt(tx.maxFeePerGas, "tx.maxFeePerGas") : quantityBigInt(tx.gasPrice, "tx.gasPrice"));
14489
+ var nativeOutflow = (value, to) => [{
12774
14490
  to,
12775
- amount: weiAmount(BigInt(tx.value)),
14491
+ amount: weiAmount(value),
12776
14492
  verified: true
12777
14493
  }];
12778
- var tokenFlow = (tx, to, amount, chainId, table) => {
12779
- const token = lookupEvmToken(table, chainId, tx.to ?? "");
14494
+ var tokenFlow = (target, to, amount, chainId, table) => {
14495
+ const token = lookupEvmToken(table, chainId, target);
12780
14496
  return {
12781
14497
  flows: [{
12782
14498
  to,
12783
14499
  amount: {
12784
- asset: tx.to ?? "",
14500
+ asset: target,
12785
14501
  amount: amount.toString(10),
12786
14502
  ...token === undefined ? {} : {
12787
14503
  symbol: token.symbol,
@@ -12793,13 +14509,28 @@ var tokenFlow = (tx, to, amount, chainId, table) => {
12793
14509
  verified: token !== undefined
12794
14510
  };
12795
14511
  };
12796
- var approvalChange = (tx, spender, amount) => ({
12797
- asset: tx.to ?? "",
12798
- spender,
12799
- amount: amount.toString(10),
12800
- unlimited: amount === MAX_UINT256,
12801
- verified: false
12802
- });
14512
+ var argBool = (args, index) => {
14513
+ const value = args[index];
14514
+ if (typeof value !== "boolean")
14515
+ throw new ChainError("invalid-request", "decoded argument is not a bool");
14516
+ return value;
14517
+ };
14518
+ var argList = (args, index) => {
14519
+ const value = args[index];
14520
+ if (!Array.isArray(value))
14521
+ throw new ChainError("invalid-request", "decoded argument is not an array");
14522
+ return value;
14523
+ };
14524
+ var argSeconds = (args, index) => {
14525
+ const value = args[index];
14526
+ if (typeof value !== "number" && typeof value !== "bigint")
14527
+ throw new ChainError("invalid-request", "decoded argument is not an integer");
14528
+ return Number(value);
14529
+ };
14530
+ var pairField = (pair, key) => {
14531
+ const value = typeof pair === "object" && pair !== null ? Reflect.get(pair, key) : "";
14532
+ return argAddress([value], 0);
14533
+ };
12803
14534
  var nftFlow = (asset, to, id) => [{
12804
14535
  to,
12805
14536
  amount: {
@@ -12808,19 +14539,17 @@ var nftFlow = (asset, to, id) => [{
12808
14539
  },
12809
14540
  verified: false
12810
14541
  }];
12811
- var decodeTransaction = (request, table) => {
12812
- const { tx } = request;
12813
- const chainId = networkChainId(request.network);
12814
- const data = tx.data.toLowerCase();
12815
- const fee = { max: weiAmount(feeWei(tx)) };
14542
+ var decodeCall = (call, network, fee, table) => {
14543
+ const chainId = networkChainId(network);
14544
+ const data = call.data.toLowerCase();
12816
14545
  const base = {
12817
14546
  family: "evm",
12818
- network: request.network,
14547
+ network,
12819
14548
  approvals: [],
12820
14549
  warnings: []
12821
14550
  };
12822
14551
  if (data === "0x") {
12823
- if (tx.to === undefined)
14552
+ if (call.to === undefined)
12824
14553
  return {
12825
14554
  ...base,
12826
14555
  summary: "contract-call",
@@ -12831,14 +14560,14 @@ var decodeTransaction = (request, table) => {
12831
14560
  return {
12832
14561
  ...base,
12833
14562
  summary: "transfer",
12834
- outflows: nativeOutflow(tx, tx.to),
14563
+ outflows: nativeOutflow(call.value, call.to),
12835
14564
  fee,
12836
14565
  verifiability: "full"
12837
14566
  };
12838
14567
  }
12839
14568
  const transferArgs = tryCall(ERC20_TRANSFER, data);
12840
14569
  if (transferArgs !== undefined) {
12841
- const { flows, verified } = tokenFlow(tx, argAddress(transferArgs, 0), argUint(transferArgs, 1), chainId, table);
14570
+ const { flows, verified } = tokenFlow(call.to ?? "", argAddress(transferArgs, 0), argUint(transferArgs, 1), chainId, table);
12842
14571
  return {
12843
14572
  ...base,
12844
14573
  summary: "transfer",
@@ -12847,46 +14576,70 @@ var decodeTransaction = (request, table) => {
12847
14576
  verifiability: verified ? "full" : "partial"
12848
14577
  };
12849
14578
  }
12850
- const approveArgs = tryCall(ERC20_APPROVE, data);
12851
- if (approveArgs !== undefined)
12852
- return {
12853
- ...base,
12854
- summary: "approve",
12855
- outflows: [],
12856
- approvals: [approvalChange(tx, argAddress(approveArgs, 0), argUint(approveArgs, 1))],
12857
- fee,
12858
- verifiability: "partial"
12859
- };
12860
- const increaseArgs = tryCall(ERC20_INCREASE, data);
12861
- if (increaseArgs !== undefined)
12862
- return {
12863
- ...base,
12864
- summary: "approve",
12865
- outflows: [],
12866
- approvals: [approvalChange(tx, argAddress(increaseArgs, 0), argUint(increaseArgs, 1))],
12867
- fee,
12868
- verifiability: "partial"
12869
- };
12870
- for (const fn of [ERC721_TRANSFER_FROM, ERC721_SAFE_FROM]) {
14579
+ const partial = (summary, outflows, approvals) => ({
14580
+ ...base,
14581
+ summary,
14582
+ outflows,
14583
+ approvals,
14584
+ fee,
14585
+ verifiability: "partial"
14586
+ });
14587
+ const token = call.to ?? "";
14588
+ if (token.toLowerCase() === "0x000000000022D473030F116dDEE9F6B43aC78BA3".toLowerCase()) {
14589
+ const permitArgs = tryCall(PERMIT2_APPROVE, data);
14590
+ if (permitArgs !== undefined) {
14591
+ const amount = argUint(permitArgs, 2);
14592
+ return partial("approve", [], [allowanceChange(argAddress(permitArgs, 0), argAddress(permitArgs, 1), amount, "set", MAX_UINT160, chainId, table, {
14593
+ via: "permit2",
14594
+ expiration: argSeconds(permitArgs, 3)
14595
+ })]);
14596
+ }
14597
+ const lockdownArgs = tryCall(PERMIT2_LOCKDOWN, data);
14598
+ if (lockdownArgs !== undefined)
14599
+ return partial("approve", [], argList(lockdownArgs, 0).map((pair) => allowanceChange(pairField(pair, "token"), pairField(pair, "spender"), 0n, "set", MAX_UINT160, chainId, table, { via: "permit2" })));
14600
+ }
14601
+ for (const [fn, change] of [
14602
+ [ERC20_APPROVE, "set"],
14603
+ [ERC20_INCREASE, "increase"],
14604
+ [ERC20_DECREASE, "decrease"]
14605
+ ]) {
12871
14606
  const args = tryCall(fn, data);
12872
14607
  if (args !== undefined)
12873
- return {
12874
- ...base,
12875
- summary: "transfer",
12876
- outflows: nftFlow(tx.to ?? "", argAddress(args, 1), argUint(args, 2)),
12877
- fee,
12878
- verifiability: "partial"
12879
- };
14608
+ return partial("approve", [], [allowanceChange(token, argAddress(args, 0), argUint(args, 1), change, MAX_UINT256, chainId, table)]);
14609
+ }
14610
+ const operatorArgs = tryCall(SET_APPROVAL_FOR_ALL, data);
14611
+ if (operatorArgs !== undefined)
14612
+ return partial("approve", [], [{
14613
+ kind: "operator",
14614
+ asset: token,
14615
+ spender: argAddress(operatorArgs, 0),
14616
+ approved: argBool(operatorArgs, 1),
14617
+ verified: false
14618
+ }]);
14619
+ const transferFromArgs = tryCall(ERC721_TRANSFER_FROM, data);
14620
+ if (transferFromArgs !== undefined) {
14621
+ const to = argAddress(transferFromArgs, 1);
14622
+ const id = argUint(transferFromArgs, 2);
14623
+ if (lookupEvmToken(table, chainId, token) !== undefined)
14624
+ return partial("transfer", tokenFlow(token, to, id, chainId, table).flows, []);
14625
+ return partial("transfer", nftFlow(token, to, id), []);
14626
+ }
14627
+ for (const fn of [ERC721_SAFE_FROM, ERC721_SAFE_FROM_DATA]) {
14628
+ const args = tryCall(fn, data);
14629
+ if (args !== undefined)
14630
+ return partial("transfer", nftFlow(token, argAddress(args, 1), argUint(args, 2)), []);
12880
14631
  }
12881
14632
  const erc1155Args = tryCall(ERC1155_SAFE_FROM, data);
12882
14633
  if (erc1155Args !== undefined)
12883
- return {
12884
- ...base,
12885
- summary: "transfer",
12886
- outflows: nftFlow(tx.to ?? "", argAddress(erc1155Args, 1), argUint(erc1155Args, 2)),
12887
- fee,
12888
- verifiability: "partial"
12889
- };
14634
+ return partial("transfer", nftFlow(token, argAddress(erc1155Args, 1), argUint(erc1155Args, 2)), []);
14635
+ const batchArgs = tryCall(ERC1155_SAFE_BATCH_FROM, data);
14636
+ if (batchArgs !== undefined) {
14637
+ const ids = argList(batchArgs, 2);
14638
+ if (ids.length > 0 && ids.length === argList(batchArgs, 3).length) {
14639
+ const to = argAddress(batchArgs, 1);
14640
+ return partial("transfer", ids.flatMap((id) => nftFlow(token, to, argUint([id], 0))), []);
14641
+ }
14642
+ }
12890
14643
  return {
12891
14644
  ...base,
12892
14645
  summary: "contract-call",
@@ -12895,6 +14648,44 @@ var decodeTransaction = (request, table) => {
12895
14648
  verifiability: "opaque"
12896
14649
  };
12897
14650
  };
14651
+ var decodeTransaction = (request, table) => {
14652
+ const { tx } = request;
14653
+ return decodeCall({
14654
+ to: tx.to,
14655
+ value: quantityBigInt(tx.value, "tx.value"),
14656
+ data: tx.data
14657
+ }, request.network, { max: weiAmount(feeWei(tx)) }, table);
14658
+ };
14659
+ var displayDomain = (domain) => {
14660
+ const { name, version, verifyingContract, salt } = domain;
14661
+ const chainId = domainChainId(domain);
14662
+ return {
14663
+ ...typeof name === "string" ? { name } : {},
14664
+ ...typeof version === "string" ? { version } : {},
14665
+ ...chainId === undefined ? {} : { chainId },
14666
+ ...typeof verifyingContract === "string" && /^0x[0-9a-fA-F]{40}$/.test(verifyingContract) ? { verifyingContract: checksumEvmAddress(verifyingContract) } : {},
14667
+ ...typeof salt === "string" ? { salt } : {}
14668
+ };
14669
+ };
14670
+ var messageContent = (bytes) => {
14671
+ try {
14672
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
14673
+ const signIn = parseSignIn(text, "evm");
14674
+ return signIn === undefined ? {
14675
+ kind: "text",
14676
+ text
14677
+ } : {
14678
+ kind: "text",
14679
+ text,
14680
+ signIn
14681
+ };
14682
+ } catch {
14683
+ return {
14684
+ kind: "bytes",
14685
+ hex: `0x${[...bytes].map((b) => b.toString(16).padStart(2, "0")).join("")}`
14686
+ };
14687
+ }
14688
+ };
12898
14689
  var decodeEvm = (request, table = evmTokenTable) => {
12899
14690
  if (request.kind === "evm.transaction")
12900
14691
  return decodeTransaction(request, table);
@@ -12907,20 +14698,35 @@ var decodeEvm = (request, table = evmTokenTable) => {
12907
14698
  approvals: [],
12908
14699
  fee: undefined,
12909
14700
  warnings: [],
14701
+ message: messageContent(request.message),
12910
14702
  verifiability: "opaque"
12911
14703
  };
12912
14704
  if (request.kind !== "evm.typed-data")
12913
14705
  throw new ChainError("unsupported", `unsupported sign request kind: ${request.kind}`);
12914
- const parsed = parseTypedData(request.typedData, request.network);
14706
+ const { json } = parseTypedData(request.typedData);
14707
+ const chainId = networkChainId(request.network);
14708
+ const permit = recognizePermit(json, chainId, table);
14709
+ const seaport = permit === undefined ? recognizeSeaport(json, chainId, table) : undefined;
14710
+ const safe = permit === undefined && seaport === undefined ? recognizeSafe(json, (call) => decodeCall(call, request.network, undefined, table)) : undefined;
14711
+ const message = {
14712
+ kind: "typed-data",
14713
+ primaryType: json.primaryType,
14714
+ domain: displayDomain(json.domain),
14715
+ data: json.message,
14716
+ ...seaport === undefined ? {} : { seaport },
14717
+ ...safe === undefined ? {} : { safe: safe.safe }
14718
+ };
14719
+ const summary = seaport === undefined ? safe === undefined ? permit === undefined ? "message" : "approve" : safe.multisend ? "batch" : safe.safe.calls[0]?.summary ?? "contract-call" : "swap";
12915
14720
  return {
12916
14721
  family: "evm",
12917
14722
  network: request.network,
12918
- summary: "message",
14723
+ summary,
12919
14724
  outflows: [],
12920
- approvals: [],
14725
+ approvals: permit?.approvals ?? [],
12921
14726
  fee: undefined,
12922
- warnings: typedDataWarnings(parsed),
12923
- verifiability: "opaque"
14727
+ warnings: permit?.warnings ?? [],
14728
+ message,
14729
+ verifiability: permit === undefined ? "opaque" : "partial"
12924
14730
  };
12925
14731
  };
12926
14732
  var normalizeEvm = (request) => {
@@ -12954,7 +14760,10 @@ var normalizeEvm = (request) => {
12954
14760
  const { typedData } = request;
12955
14761
  if (typeof typedData !== "string")
12956
14762
  throw new ChainError("invalid-request", "typed-data payload must be the JSON source string");
12957
- parseTypedData(typedData, network);
14763
+ const { json } = parseTypedData(typedData);
14764
+ const domainChain = domainChainId(json.domain);
14765
+ if (domainChain !== undefined && domainChain !== chainId)
14766
+ throw new ChainError("chain-id-mismatch", `typed-data domain.chainId ${domainChain} does not match network ${network}`);
12958
14767
  return {
12959
14768
  kind: "evm.typed-data",
12960
14769
  network,
@@ -14435,8 +16244,11 @@ var parseCompiledMessage = (bytes) => {
14435
16244
  numRequiredSignatures: message.numSignerAccounts,
14436
16245
  staticAccounts,
14437
16246
  instructions: message.instructions,
14438
- lookupCount: lookups.length,
14439
- lookupAddresses: lookups.map((l) => l.lookupTableAddress)
16247
+ lookups: lookups.map((l) => ({
16248
+ address: l.lookupTableAddress,
16249
+ writableIndexes: l.writableIndexes,
16250
+ readonlyIndexes: l.readonlyIndexes
16251
+ }))
14440
16252
  };
14441
16253
  };
14442
16254
  var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
@@ -14501,6 +16313,7 @@ var validateLookupTables = (tables) => {
14501
16313
  if (!isSolanaAddress(table.address) || !table.addresses.every(isSolanaAddress))
14502
16314
  throw new ChainError("invalid-address", "lookup table entries must be base58 32-byte addresses");
14503
16315
  };
16316
+ var SOLANA_NATIVE_ASSET = "lamports";
14504
16317
  var USDC2 = Object.freeze({
14505
16318
  symbol: "USDC",
14506
16319
  decimals: 6,
@@ -14516,7 +16329,6 @@ var solanaTokenTable = Object.freeze({ "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"
14516
16329
  Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB: USDT2
14517
16330
  }) });
14518
16331
  var lookupSolanaToken = (table, network, mint) => table[network]?.[mint];
14519
- var LAMPORTS_ASSET = "lamports";
14520
16332
  var u323 = getU32Decoder();
14521
16333
  var u64$1 = getU64Decoder();
14522
16334
  var u32le2 = (data, offset) => u323.decode(data, offset);
@@ -14582,7 +16394,7 @@ var FULL_KINDS = /* @__PURE__ */ new Set([
14582
16394
  "ata-create-idempotent"
14583
16395
  ]);
14584
16396
  var classify2 = (parsed, calls, network, table) => {
14585
- if (parsed.lookupCount > 0)
16397
+ if (parsed.lookups.length > 0)
14586
16398
  return "partial";
14587
16399
  let allFull = true;
14588
16400
  for (const call of calls) {
@@ -14621,7 +16433,7 @@ var decodeTransaction2 = (request, signer, table) => {
14621
16433
  outflows.push({
14622
16434
  to: call.to,
14623
16435
  amount: {
14624
- asset: LAMPORTS_ASSET,
16436
+ asset: SOLANA_NATIVE_ASSET,
14625
16437
  amount: (call.amount ?? 0n).toString(10)
14626
16438
  },
14627
16439
  verified: true
@@ -14642,14 +16454,24 @@ var decodeTransaction2 = (request, signer, table) => {
14642
16454
  verified: token !== undefined
14643
16455
  });
14644
16456
  }
14645
- if (call.kind === "token-approve")
16457
+ if (call.kind === "token-approve") {
16458
+ const token = lookupSolanaToken(table, request.network, call.mint ?? "");
14646
16459
  approvals.push({
14647
- asset: call.mint ?? "",
16460
+ kind: "allowance",
14648
16461
  spender: call.to ?? "",
14649
- amount: (call.amount ?? 0n).toString(10),
16462
+ amount: {
16463
+ asset: call.mint ?? "",
16464
+ amount: (call.amount ?? 0n).toString(10),
16465
+ ...token === undefined ? {} : {
16466
+ symbol: token.symbol,
16467
+ decimals: token.decimals
16468
+ }
16469
+ },
16470
+ change: "set",
14650
16471
  unlimited: false,
14651
- verified: false
16472
+ verified: token !== undefined
14652
16473
  });
16474
+ }
14653
16475
  }
14654
16476
  const fee = feeLamports(parsed, calls);
14655
16477
  return {
@@ -14659,7 +16481,7 @@ var decodeTransaction2 = (request, signer, table) => {
14659
16481
  outflows,
14660
16482
  approvals,
14661
16483
  fee: fee === undefined ? undefined : { max: {
14662
- asset: LAMPORTS_ASSET,
16484
+ asset: SOLANA_NATIVE_ASSET,
14663
16485
  amount: fee.toString(10)
14664
16486
  } },
14665
16487
  warnings: [],
@@ -14747,7 +16569,8 @@ var signBitcoinPsbt = (psbt, inputs, auxRand) => {
14747
16569
  for (const { index, privateKey } of inputs) {
14748
16570
  if (privateKey.length !== 32)
14749
16571
  throw new ChainError("invalid-request", `input ${index}: private key must be 32 bytes`);
14750
- if (!tx.signIdx(privateKey, index, undefined, auxRand(index)))
16572
+ const allowed = tx.getInput(index).sighashType === SigHash.SINGLE_ANYONECANPAY ? [SigHash.SINGLE_ANYONECANPAY] : undefined;
16573
+ if (!tx.signIdx(privateKey, index, allowed, auxRand(index)))
14751
16574
  throw new ChainError("invalid-request", `input ${index}: key cannot sign`);
14752
16575
  }
14753
16576
  return tx.toPSBT(0);
@@ -14769,6 +16592,20 @@ var MESSAGE_INTENT = {
14769
16592
  fee: undefined,
14770
16593
  verifiability: "opaque"
14771
16594
  };
16595
+ var utf82 = new TextDecoder("utf-8", { fatal: true });
16596
+ var messageIntent = (message) => {
16597
+ try {
16598
+ return { ...MESSAGE_INTENT, message: { kind: "text", text: utf82.decode(message) } };
16599
+ } catch {
16600
+ return {
16601
+ ...MESSAGE_INTENT,
16602
+ message: {
16603
+ kind: "bytes",
16604
+ hex: `0x${[...message].map((b) => b.toString(16).padStart(2, "0")).join("")}`
16605
+ }
16606
+ };
16607
+ }
16608
+ };
14772
16609
  var CATALOGS = {
14773
16610
  "zh-Hans": {
14774
16611
  titles: {
@@ -14780,12 +16617,23 @@ var CATALOGS = {
14780
16617
  authorization: "确认账户授权",
14781
16618
  batch: "确认批量交易"
14782
16619
  },
16620
+ blindTitle: "确认盲签",
16621
+ blindDescription: "签署无法显示为文字的数据",
14783
16622
  generic: "签署来自应用的请求",
14784
16623
  otherOutflows: "可能还有其他转出",
14785
16624
  send: (amount, to) => `发送 ${amount} 到 ${to}`,
14786
16625
  allow: (spender, amount) => `授权 ${spender} 使用 ${amount}`,
14787
16626
  unlimited: (asset) => `全部 ${asset}`,
14788
- maxFee: (fee) => `最高手续费 ${fee}`
16627
+ revoke: (spender, asset) => `撤销 ${spender} 对 ${asset} 的授权`,
16628
+ increase: (spender, amount) => `授权 ${spender} 再使用 ${amount}`,
16629
+ decrease: (spender, amount) => `减少 ${spender} 的授权额度 ${amount}`,
16630
+ takeOnce: (spender, amount) => `授权 ${spender} 一次性转走 ${amount}`,
16631
+ viaPermit2: " 经 Permit2",
16632
+ until: (date) => ` 至 ${date}(UTC)`,
16633
+ operatorAllow: (spender, asset) => `授权 ${spender} 转走 ${asset} 的全部代币`,
16634
+ operatorRevoke: (spender, asset) => `撤销 ${spender} 对 ${asset} 全部代币的授权`,
16635
+ maxFee: (fee) => `最高手续费 ${fee}`,
16636
+ sighashSingle: "已签输入只绑定同序号输出,交易其余部分可被改动"
14789
16637
  },
14790
16638
  en: {
14791
16639
  titles: {
@@ -14797,34 +16645,85 @@ var CATALOGS = {
14797
16645
  authorization: "Confirm account authorization",
14798
16646
  batch: "Confirm batch"
14799
16647
  },
16648
+ blindTitle: "Confirm blind signing",
16649
+ blindDescription: "Sign data that cannot be shown as text",
14800
16650
  generic: "Sign a request from an app",
14801
16651
  otherOutflows: "There may be other outflows",
14802
16652
  send: (amount, to) => `Send ${amount} to ${to}`,
14803
16653
  allow: (spender, amount) => `Allow ${spender} to spend ${amount}`,
14804
16654
  unlimited: (asset) => `unlimited ${asset}`,
14805
- maxFee: (fee) => `Max fee ${fee}`
16655
+ revoke: (spender, asset) => `Revoke ${spender}'s allowance for ${asset}`,
16656
+ increase: (spender, amount) => `Allow ${spender} to spend ${amount} more`,
16657
+ decrease: (spender, amount) => `Reduce ${spender}'s allowance by ${amount}`,
16658
+ takeOnce: (spender, amount) => `Allow ${spender} to take ${amount} once`,
16659
+ viaPermit2: " via Permit2",
16660
+ until: (date) => ` until ${date} (UTC)`,
16661
+ operatorAllow: (spender, asset) => `Allow ${spender} to transfer all tokens of ${asset}`,
16662
+ operatorRevoke: (spender, asset) => `Revoke ${spender}'s access to all tokens of ${asset}`,
16663
+ maxFee: (fee) => `Max fee ${fee}`,
16664
+ sighashSingle: "Signed inputs bind only their same-index outputs; the rest of the transaction can change"
14806
16665
  }
14807
16666
  };
14808
16667
  function formatAmount(amount) {
14809
16668
  return amount.decimals === undefined ? `${amount.amount} ${amount.asset}` : `${formatUnits(amount.amount, amount.decimals)} ${amount.symbol ?? amount.asset}`;
14810
16669
  }
16670
+ function utcDate(seconds) {
16671
+ const z = Math.floor(seconds / 86400) + 719468;
16672
+ const era = Math.floor(z / 146097);
16673
+ const doe = z - era * 146097;
16674
+ const yoe = Math.floor((doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365);
16675
+ const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));
16676
+ const mp = Math.floor((5 * doy + 2) / 153);
16677
+ const day = doy - Math.floor((153 * mp + 2) / 5) + 1;
16678
+ const month = mp < 10 ? mp + 3 : mp - 9;
16679
+ const year = yoe + era * 400 + (month <= 2 ? 1 : 0);
16680
+ return `${String(year).padStart(4, "0")}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
16681
+ }
16682
+ function approvalLine(catalog, change) {
16683
+ if (change.kind === "operator") {
16684
+ return change.approved ? catalog.operatorAllow(change.spender, change.asset) : catalog.operatorRevoke(change.spender, change.asset);
16685
+ }
16686
+ const name = change.amount.symbol ?? change.amount.asset;
16687
+ let line;
16688
+ if (change.change === "increase") {
16689
+ line = catalog.increase(change.spender, formatAmount(change.amount));
16690
+ } else if (change.change === "decrease") {
16691
+ line = catalog.decrease(change.spender, formatAmount(change.amount));
16692
+ } else if (change.change === "transfer") {
16693
+ line = catalog.takeOnce(change.spender, change.unlimited ? catalog.unlimited(name) : formatAmount(change.amount));
16694
+ } else if (change.unlimited) {
16695
+ line = catalog.allow(change.spender, catalog.unlimited(name));
16696
+ } else if (change.amount.amount === "0") {
16697
+ line = catalog.revoke(change.spender, name);
16698
+ } else {
16699
+ line = catalog.allow(change.spender, formatAmount(change.amount));
16700
+ }
16701
+ const via = change.via === undefined ? "" : catalog.viaPermit2;
16702
+ const until = change.expiration === undefined || change.expiration === 0 ? "" : catalog.until(utcDate(change.expiration));
16703
+ return `${line}${via}${until}`;
16704
+ }
14811
16705
  function chainPrompt(locale, intent) {
14812
16706
  const catalog = CATALOGS[locale];
16707
+ if (intent.message?.kind === "bytes") {
16708
+ return { title: catalog.blindTitle, description: catalog.blindDescription };
16709
+ }
14813
16710
  const title = catalog.titles[intent.summary];
16711
+ const caution = intent.warnings?.some((w) => w.kind === "sighash-single-anyonecanpay") === true;
16712
+ const tail = caution ? [catalog.sighashSingle] : [];
14814
16713
  if (intent.verifiability === "opaque") {
14815
- return { title, description: catalog.generic };
16714
+ return { title, description: joinLines([catalog.generic, ...tail]) };
14816
16715
  }
14817
16716
  const lines = [
14818
16717
  ...intent.outflows.map((flow) => catalog.send(formatAmount(flow.amount), flow.to)),
14819
- ...intent.approvals.map((change) => catalog.allow(change.spender, change.unlimited ? catalog.unlimited(change.asset) : `${change.amount} ${change.asset}`)),
14820
- ...intent.fee === undefined ? [] : [catalog.maxFee(formatAmount(intent.fee.max))]
16718
+ ...intent.approvals.map((change) => approvalLine(catalog, change)),
16719
+ ...intent.fee === undefined ? [] : [catalog.maxFee(formatAmount(intent.fee.max))],
16720
+ ...tail
14821
16721
  ];
14822
16722
  if (intent.verifiability === "partial") {
14823
16723
  return { title, description: joinLines([catalog.otherOutflows, ...lines]) };
14824
16724
  }
14825
16725
  return { title, description: joinLines(lines.length === 0 ? [catalog.generic] : lines) };
14826
16726
  }
14827
-
14828
16727
  // ../wallet-kernel/src/modules/chains/shared.ts
14829
16728
  var BTC_PURPOSE = {
14830
16729
  "btc.bip44": 44,
@@ -14858,11 +16757,11 @@ function mapChainError(error) {
14858
16757
  }
14859
16758
 
14860
16759
  // ../wallet-kernel/src/modules/chains/bitcoin.ts
14861
- var isPath = (path) => Array.isArray(path) && path.every((p) => typeof p === "number");
16760
+ var isPath2 = (path) => Array.isArray(path) && path.every((p) => typeof p === "number");
14862
16761
  var hex = (bytes) => bytes.reduce((acc, b) => acc + b.toString(16).padStart(2, "0"), "");
14863
16762
  var derivationOf = (owner, fingerprint, purpose) => {
14864
16763
  if (purpose === 86) {
14865
- const claimed = (der) => der.fingerprint === fingerprint && isPath(der.path);
16764
+ const claimed = (der) => der.fingerprint === fingerprint && isPath2(der.path);
14866
16765
  for (const [key, value] of owner.tapBip32Derivation ?? []) {
14867
16766
  if (claimed(value.der)) {
14868
16767
  return { pubkey: key, fingerprint: value.der.fingerprint, path: value.der.path };
@@ -15119,7 +17018,7 @@ var signEvmPersonalMessage = (message, privateKey) => {
15119
17018
  return rs_v(from5(sign3(payload, key(privateKey))));
15120
17019
  };
15121
17020
  var signEvmTypedData = (typedData, privateKey) => {
15122
- const { json } = parseTypedData(typedData, "eip155:1");
17021
+ const { json } = parseTypedData(typedData);
15123
17022
  const payload = getSignPayload(json);
15124
17023
  return rs_v(from5(sign3(payload, key(privateKey))));
15125
17024
  };
@@ -15204,7 +17103,7 @@ var executeSolana = (request, account, seed, intentOnly) => {
15204
17103
  if (!deepEqual(normalized, request)) {
15205
17104
  throw new KernelError("invalid-input", "request is not normalized");
15206
17105
  }
15207
- let intent = MESSAGE_INTENT;
17106
+ let intent = messageIntent(request.message);
15208
17107
  if (request.kind === "solana.transaction") {
15209
17108
  try {
15210
17109
  intent = decodeSolana(request, signer);
@@ -16066,7 +17965,7 @@ function sparkPrompt(locale, summary) {
16066
17965
 
16067
17966
  // ../wallet-kernel/src/modules/spark/runtime.ts
16068
17967
  async function loadSparkRuntime() {
16069
- const signer = await (__preload("gs57sjgx"), import("./signer-gs57sjgx.js"));
17968
+ const signer = await (__preload("h69ffzx5"), import("./signer-h69ffzx5.js"));
16070
17969
  return {
16071
17970
  bitcoinAddressScript: signer.bitcoinAddressScript,
16072
17971
  createSparkSigner: signer.createSparkSigner,
@@ -16197,7 +18096,7 @@ var liveApprovals = (state, ctx, key) => {
16197
18096
  }
16198
18097
  return live;
16199
18098
  };
16200
- var backend = async (state, ctx) => {
18099
+ var backend2 = async (state, ctx) => {
16201
18100
  state.backendPromise ??= (async () => {
16202
18101
  try {
16203
18102
  return await ctx.platform.backends.spark();
@@ -16263,7 +18162,7 @@ var signerFor = async (state, ctx, account, requestSession) => {
16263
18162
  } catch (error) {
16264
18163
  throw mapError(state, error);
16265
18164
  }
16266
- const crypto2 = await backend(state, ctx);
18165
+ const crypto2 = await backend2(state, ctx);
16267
18166
  try {
16268
18167
  const signer = rt.createSparkSigner({
16269
18168
  crypto: crypto2,
@@ -16280,7 +18179,7 @@ var signerFor = async (state, ctx, account, requestSession) => {
16280
18179
  wipe(accountKey);
16281
18180
  }
16282
18181
  };
16283
- var transferCovered = (outflow, intent) => outflow.receivers.every((receiver) => intent.receivers.some((wanted) => equalBytes(wanted.identityPublicKey, receiver.identityPublicKey) && receiver.amountSats <= wanted.amountSats));
18182
+ var transferCovered = (outflow, intent) => outflow.receivers.every((receiver) => intent.receivers.some((wanted) => equalBytes2(wanted.identityPublicKey, receiver.identityPublicKey) && receiver.amountSats <= wanted.amountSats));
16284
18183
  var lightningCovered = async (state, rt, key, network, outflow, approval, intent) => {
16285
18184
  const signer = state.signers.get(key);
16286
18185
  const { paymentHash } = approval.decoded;
@@ -16293,7 +18192,7 @@ var lightningCovered = async (state, rt, key, network, outflow, approval, intent
16293
18192
  sspIdentityPublicKey: rt.sparkNetworkConfig(network).ssp.identityPublicKey,
16294
18193
  identityPublicKey: await signer.identityPublicKey()
16295
18194
  });
16296
- if (!equalBytes(expected, outflow.htlcOutputScript)) {
18195
+ if (!equalBytes2(expected, outflow.htlcOutputScript)) {
16297
18196
  return false;
16298
18197
  }
16299
18198
  const fresh = outflow.leaves.filter((leaf) => !approval.spentLeaves.has(bytesToHex(leaf.publicKey)));
@@ -16311,7 +18210,7 @@ var exitCovered = (outflow, approval, intent) => {
16311
18210
  if (addressScript === undefined) {
16312
18211
  return false;
16313
18212
  }
16314
- const pays = outflow.exitOutputs.some((output) => equalBytes(output.script, addressScript) && output.amountSats >= intent.amountSats);
18213
+ const pays = outflow.exitOutputs.some((output) => equalBytes2(output.script, addressScript) && output.amountSats >= intent.amountSats);
16315
18214
  if (!pays) {
16316
18215
  return false;
16317
18216
  }
@@ -16330,7 +18229,7 @@ var onchainCovered = (rt, outflow, approval, intent) => {
16330
18229
  if (addressScript === undefined) {
16331
18230
  return false;
16332
18231
  }
16333
- const every = outflow.outputs.every((output) => equalBytes(output.script, rt.EPHEMERAL_ANCHOR_SCRIPT) || equalBytes(output.script, addressScript));
18232
+ const every = outflow.outputs.every((output) => equalBytes2(output.script, rt.EPHEMERAL_ANCHOR_SCRIPT) || equalBytes2(output.script, addressScript));
16334
18233
  if (!every) {
16335
18234
  return false;
16336
18235
  }
@@ -16344,13 +18243,13 @@ var tokenCovered = async (state, key, outflow, intent) => {
16344
18243
  }
16345
18244
  const identity = await signer.identityPublicKey();
16346
18245
  return outflow.outputs.every((output) => {
16347
- if (equalBytes(output.ownerPublicKey, identity)) {
18246
+ if (equalBytes2(output.ownerPublicKey, identity)) {
16348
18247
  return true;
16349
18248
  }
16350
- if (!equalBytes(output.tokenIdentifier, intent.tokenIdentifier)) {
18249
+ if (!equalBytes2(output.tokenIdentifier, intent.tokenIdentifier)) {
16351
18250
  return false;
16352
18251
  }
16353
- return intent.receivers.some((wanted) => equalBytes(wanted.ownerPublicKey, output.ownerPublicKey) && output.amount <= BigInt(wanted.amount));
18252
+ return intent.receivers.some((wanted) => equalBytes2(wanted.ownerPublicKey, output.ownerPublicKey) && output.amount <= BigInt(wanted.amount));
16354
18253
  });
16355
18254
  };
16356
18255
  var authorizeWithCtx = async (state, ctx, account, outflow) => {
@@ -16552,6 +18451,22 @@ function collectTransferables(value, out, depth = 0) {
16552
18451
  }
16553
18452
  return out;
16554
18453
  }
18454
+ function openChecked(dek, record) {
18455
+ const plaintext = openRecord(dek, record);
18456
+ if (record.kind === "entropy") {
18457
+ try {
18458
+ const { entropy, passphrase } = splitWalletSecret(parseEntropyHeader(record.header), plaintext);
18459
+ wipe(entropy);
18460
+ if (passphrase !== undefined) {
18461
+ wipe(passphrase);
18462
+ }
18463
+ } catch (error) {
18464
+ wipe(plaintext);
18465
+ throw error;
18466
+ }
18467
+ }
18468
+ return plaintext;
18469
+ }
16555
18470
  function isMethodName(method) {
16556
18471
  return method in METHODS;
16557
18472
  }
@@ -16614,11 +18529,11 @@ function startKernel(host, port) {
16614
18529
  for (const record of next.records) {
16615
18530
  const prior = before.get(`${record.kind}/${record.id}`);
16616
18531
  if (prior === undefined) {
16617
- opened.push({ kind: record.kind, id: record.id, plaintext: openRecord(dek, record) });
18532
+ opened.push({ kind: record.kind, id: record.id, plaintext: openChecked(dek, record) });
16618
18533
  } else {
16619
18534
  before.delete(`${record.kind}/${record.id}`);
16620
- if (prior.header !== record.header || !equalBytes(prior.sealed, record.sealed)) {
16621
- opened.push({ kind: record.kind, id: record.id, plaintext: openRecord(dek, record) });
18535
+ if (prior.header !== record.header || !equalBytes2(prior.sealed, record.sealed)) {
18536
+ opened.push({ kind: record.kind, id: record.id, plaintext: openChecked(dek, record) });
16622
18537
  }
16623
18538
  }
16624
18539
  }
@@ -16640,7 +18555,7 @@ function startKernel(host, port) {
16640
18555
  const priorFactors = new Map(prev.factors.map((factor) => [factor.id, factor]));
16641
18556
  for (const factor of next.factors) {
16642
18557
  const prior = priorFactors.get(factor.id);
16643
- const changed = prior === undefined || prior.header !== factor.header || !equalBytes(prior.sealed, factor.sealed);
18558
+ const changed = prior === undefined || prior.header !== factor.header || !equalBytes2(prior.sealed, factor.sealed);
16644
18559
  if (changed && !factorBindingOk(dek, factor)) {
16645
18560
  throw new KernelError("integrity", "factor binding does not match the vault", undefined, true);
16646
18561
  }