@qntx/wallet-worker 0.9.0 → 0.11.0

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