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