@qntx/wallet-engine 0.8.1 → 0.9.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.
@@ -3,6 +3,7 @@ import { createStore } from "zustand/vanilla";
3
3
  import { bytesToHex, hexToBytes } from "@noble/hashes/utils.js";
4
4
  import { bitcoinAddressScript, decodeBolt11, decodeSparkAddress, parseSparkInvoice } from "@qntx/spark";
5
5
  import { decodeLnurl, lightningAddressUrl } from "@qntx/spark/lnurl";
6
+ import { base58 } from "@scure/base";
6
7
  // src/controller.ts
7
8
  /**
8
9
  * Controller base: a zustand vanilla store plus lifecycle. `update` applies a recipe that must
@@ -23,6 +24,8 @@ var Controller = class {
23
24
  this.store.setState((state) => recipe(state));
24
25
  }
25
26
  };
27
+ // src/phishing/status.ts
28
+ const PHISHING_BLOCKED_MESSAGE = "origin is on the phishing list";
26
29
  // src/connect/errors.ts
27
30
  /** EIP-1193 / EIP-1474 / EIP-3326 error: `code` is what the page's promise rejects with. */
28
31
  var ProviderError = class extends Error {
@@ -40,7 +43,8 @@ const unrecognizedChain = (message = "unrecognized chain") => new ProviderError(
40
43
  const invalidParams = (message) => new ProviderError(-32602, message);
41
44
  const requestPending = (message) => new ProviderError(-32002, message);
42
45
  const internalError = (message) => new ProviderError(-32603, message);
43
- // src/connect/controller.ts
46
+ /** A pending connection request that nobody answers is rejected after this long. */
47
+ const CONNECTION_REQUEST_TTL_MS = 6e5;
44
48
  const COLLECTION = "connections";
45
49
  /** `lastUsedAt` is rewritten at most this often. */
46
50
  const TOUCH_INTERVAL_MS = 6e4;
@@ -48,7 +52,8 @@ const TOUCH_INTERVAL_MS = 6e4;
48
52
  const SESSION_METHODS = [
49
53
  "eth_sendTransaction",
50
54
  "personal_sign",
51
- "eth_signTypedData_v4"
55
+ "eth_signTypedData_v4",
56
+ "wallet_watchAsset"
52
57
  ];
53
58
  const SESSION_NOTIFICATIONS = ["accountsChanged", "chainChanged"];
54
59
  /** The `nostr` namespace scope's granted methods — the NIP-07 surface. */
@@ -76,7 +81,8 @@ const SOLANA_METHODS = [
76
81
  "standard:events",
77
82
  "solana:signTransaction",
78
83
  "solana:signAndSendTransaction",
79
- "solana:signMessage"
84
+ "solana:signMessage",
85
+ "solana:signIn"
80
86
  ];
81
87
  /** `eip155:1` → 1; `undefined` for anything that is not an EVM network. */
82
88
  const evmChainId = (network) => {
@@ -97,6 +103,7 @@ var ConnectionController = class extends Controller {
97
103
  options;
98
104
  engineStore;
99
105
  waiters = /* @__PURE__ */ new Map();
106
+ expiries = /* @__PURE__ */ new Map();
100
107
  group;
101
108
  identity;
102
109
  constructor(options) {
@@ -146,6 +153,8 @@ var ConnectionController = class extends Controller {
146
153
  this.group = void 0;
147
154
  for (const waiter of this.waiters.values()) waiter.reject(userRejectedRequest("the wallet was locked"));
148
155
  this.waiters.clear();
156
+ for (const cancel of this.expiries.values()) cancel();
157
+ this.expiries.clear();
149
158
  this.update(() => ({
150
159
  sessions: {},
151
160
  pending: {}
@@ -160,15 +169,14 @@ var ConnectionController = class extends Controller {
160
169
  for (const entry of this.pending()) {
161
170
  if (entry.origin.origin !== origin) continue;
162
171
  this.waiters.get(entry.id)?.reject(userRejectedRequest("the page navigated away"));
163
- this.waiters.delete(entry.id);
164
- this.update((s) => ({
165
- ...s,
166
- pending: Object.fromEntries(Object.entries(s.pending).filter(([id]) => id !== entry.id))
167
- }));
172
+ this.dropPending(entry.id);
168
173
  }
169
174
  this.options.invalidate(origin);
170
175
  }
171
- /** Throws `4100` unless `origin` is `https://host[:port]` (or localhost in development). */
176
+ /**
177
+ * Throws `4100` unless `origin` is `https://host[:port]` (or localhost in development) and not on
178
+ * the phishing list.
179
+ */
172
180
  checkOrigin(origin) {
173
181
  let url;
174
182
  try {
@@ -178,6 +186,7 @@ var ConnectionController = class extends Controller {
178
186
  }
179
187
  const localhost = url.protocol === "http:" && url.hostname === "localhost";
180
188
  if (url.origin !== origin || url.protocol !== "https:" && !(localhost && this.options.allowLocalhost)) throw unauthorized("origin not allowed");
189
+ if (this.options.phishing.check(origin) === "blocked") throw unauthorized(PHISHING_BLOCKED_MESSAGE);
181
190
  return {
182
191
  kind: "browser",
183
192
  origin
@@ -210,9 +219,10 @@ var ConnectionController = class extends Controller {
210
219
  return session;
211
220
  }
212
221
  /** Resolves with the session once the host approves; rejects with `4001` when it refuses. */
213
- async request(origin, kind, network, namespace = "eip155") {
222
+ async request(origin, { kind, namespace = "eip155", network, activate = true }) {
214
223
  if (this.engineStore === void 0) throw userRejectedRequest("the wallet is locked");
215
224
  if (this.pending().some((p) => p.origin.origin === origin)) throw requestPending("a connection request is already pending");
225
+ if (this.pending().length >= 64) throw requestPending("too many pending connection requests");
216
226
  const id = `conn-${[...this.options.random(8)].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
217
227
  const entry = {
218
228
  id,
@@ -223,6 +233,7 @@ var ConnectionController = class extends Controller {
223
233
  kind,
224
234
  namespace,
225
235
  ...network === void 0 ? {} : { network },
236
+ ...activate ? {} : { activate },
226
237
  createdAt: this.options.now()
227
238
  };
228
239
  return new Promise((resolve, reject) => {
@@ -230,6 +241,10 @@ var ConnectionController = class extends Controller {
230
241
  resolve,
231
242
  reject
232
243
  });
244
+ this.expiries.set(id, this.options.setTimer(CONNECTION_REQUEST_TTL_MS, () => {
245
+ this.waiters.get(id)?.reject(userRejectedRequest("the connection request expired"));
246
+ this.dropPending(id);
247
+ }));
233
248
  this.update((s) => ({
234
249
  ...s,
235
250
  pending: {
@@ -248,6 +263,12 @@ var ConnectionController = class extends Controller {
248
263
  const entry = this.getState().pending[id];
249
264
  const waiter = this.waiters.get(id);
250
265
  if (entry === void 0 || waiter === void 0) throw new Error(`unknown connection request ${id}`);
266
+ if (this.options.phishing.check(entry.origin.origin) === "blocked") {
267
+ const blocked = unauthorized(PHISHING_BLOCKED_MESSAGE);
268
+ this.dropPending(id);
269
+ waiter.reject(blocked);
270
+ throw blocked;
271
+ }
251
272
  if (entry.kind === "network" && entry.network !== grant.network) throw new Error(`connection request ${id} is for ${String(entry.network)}`);
252
273
  const scopes = {};
253
274
  if (entry.namespace === "nostr") {
@@ -298,6 +319,7 @@ var ConnectionController = class extends Controller {
298
319
  if (this.getState().pending[id] === void 0) throw new Error(`connection request ${id} is no longer pending`);
299
320
  const now = this.options.now();
300
321
  const existing = this.session(entry.origin.origin);
322
+ const currentNetwork = entry.activate === false && existing !== void 0 ? existing.currentNetwork : grant.network;
301
323
  const session = {
302
324
  id: existing?.id ?? `session-${[...this.options.random(8)].map((b) => b.toString(16).padStart(2, "0")).join("")}`,
303
325
  origin: entry.origin,
@@ -305,7 +327,7 @@ var ConnectionController = class extends Controller {
305
327
  ...existing?.scopes,
306
328
  ...scopes
307
329
  },
308
- currentNetwork: grant.network,
330
+ currentNetwork,
309
331
  ...grant.nostr === void 0 ? {} : { nostrPolicy: grant.nostr.policy },
310
332
  ...grant.lightning === void 0 ? {} : { lightningPolicy: grant.lightning.policy },
311
333
  createdAt: existing?.createdAt ?? now,
@@ -313,7 +335,7 @@ var ConnectionController = class extends Controller {
313
335
  };
314
336
  await this.persist(store, session);
315
337
  this.dropPending(id);
316
- if (existing !== void 0 && existing.currentNetwork !== grant.network) this.options.invalidate(entry.origin.origin);
338
+ if (existing !== void 0 && existing.currentNetwork !== currentNetwork) this.options.invalidate(entry.origin.origin);
317
339
  waiter.resolve(session);
318
340
  return session;
319
341
  }
@@ -455,6 +477,8 @@ var ConnectionController = class extends Controller {
455
477
  }));
456
478
  }
457
479
  dropPending(id) {
480
+ this.expiries.get(id)?.();
481
+ this.expiries.delete(id);
458
482
  this.waiters.delete(id);
459
483
  this.update((s) => {
460
484
  const { [id]: _gone, ...pending } = s.pending;
@@ -483,6 +507,58 @@ var ConnectionController = class extends Controller {
483
507
  return this.engineStore;
484
508
  }
485
509
  };
510
+ // src/connect/text.ts
511
+ /** What a handler answers with (`4200`) for sign-message bytes that are not UTF-8 text. */
512
+ const BLIND_SIGNING_MESSAGE = "blind signing is not enabled: the message is not UTF-8 text";
513
+ const decoder = new TextDecoder("utf-8", { fatal: true });
514
+ /** The bytes as UTF-8 text, or `undefined` when they are not valid UTF-8. */
515
+ function utf8Text(bytes) {
516
+ try {
517
+ return decoder.decode(bytes);
518
+ } catch {
519
+ return;
520
+ }
521
+ }
522
+ // src/connect/subscription.ts
523
+ /**
524
+ * Fans events derived from session changes out to listeners. The store subscription is created with
525
+ * the first listener and dropped with the last; `derive` may be async (its events are then
526
+ * delivered once it settles).
527
+ */
528
+ var SessionEvents = class {
529
+ listeners = /* @__PURE__ */ new Set();
530
+ unsubscribe;
531
+ connections;
532
+ derive;
533
+ constructor(connections, derive) {
534
+ this.connections = connections;
535
+ this.derive = derive;
536
+ }
537
+ subscribe(listener) {
538
+ this.listeners.add(listener);
539
+ if (this.unsubscribe === void 0) {
540
+ let previous = this.connections.getState().sessions;
541
+ this.unsubscribe = this.connections.store.subscribe((state) => {
542
+ const events = this.derive(previous, state.sessions);
543
+ previous = state.sessions;
544
+ if (Array.isArray(events)) this.emit(events);
545
+ else (async () => {
546
+ this.emit(await events);
547
+ })();
548
+ });
549
+ }
550
+ return () => {
551
+ this.listeners.delete(listener);
552
+ if (this.listeners.size === 0) {
553
+ this.unsubscribe?.();
554
+ this.unsubscribe = void 0;
555
+ }
556
+ };
557
+ }
558
+ emit(events) {
559
+ for (const event of events) for (const listener of this.listeners) listener(event);
560
+ }
561
+ };
486
562
  // src/connect/nip07.ts
487
563
  /** `signEvent` of these kinds always asks for explicit confirmation, whatever the policy allows. */
488
564
  const FORCED_CONFIRM_KINDS = /* @__PURE__ */ new Set([
@@ -561,7 +637,10 @@ var Nip07Handler = class {
561
637
  }
562
638
  async publicKey(origin, pubkey) {
563
639
  const { connections } = this.options;
564
- if (pubkey === void 0) await connections.request(origin, "connect", void 0, "nostr");
640
+ if (pubkey === void 0) await connections.request(origin, {
641
+ kind: "connect",
642
+ namespace: "nostr"
643
+ });
565
644
  await connections.touch(origin);
566
645
  const granted = connections.nostrAccount(origin);
567
646
  if (granted === void 0) throw unauthorized();
@@ -609,6 +688,71 @@ var Nip07Handler = class {
609
688
  return fn(peer, text);
610
689
  }
611
690
  };
691
+ // src/connect/siws.ts
692
+ const STATEMENT_MAX = 1024;
693
+ const FIELD_MAX = 256;
694
+ const RESOURCES_MAX = 32;
695
+ const STRING_FIELDS = [
696
+ "domain",
697
+ "address",
698
+ "statement",
699
+ "uri",
700
+ "version",
701
+ "chainId",
702
+ "nonce",
703
+ "issuedAt",
704
+ "expirationTime",
705
+ "notBefore",
706
+ "requestId"
707
+ ];
708
+ const checkString$1 = (name, value, max) => {
709
+ if (typeof value !== "string") throw invalidParams(`${name} must be a string`);
710
+ if (value.includes("\n") || value.includes("\r")) throw invalidParams(`${name} must not contain line breaks`);
711
+ if (value.length > max) throw invalidParams(`${name} is longer than ${String(max)} characters`);
712
+ return value;
713
+ };
714
+ /** Validates a dApp's sign-in input: types, no line breaks, length caps. */
715
+ function checkSignInInput(raw) {
716
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw invalidParams("the sign-in input must be an object");
717
+ const record = new Map(Object.entries(raw));
718
+ const out = {};
719
+ for (const name of STRING_FIELDS) {
720
+ const value = record.get(name);
721
+ if (value !== void 0) out[name] = checkString$1(name, value, name === "statement" ? STATEMENT_MAX : FIELD_MAX);
722
+ }
723
+ const resources = record.get("resources");
724
+ if (resources !== void 0) {
725
+ if (!Array.isArray(resources) || resources.length > RESOURCES_MAX) throw invalidParams(`resources must be an array of at most ${String(RESOURCES_MAX)} strings`);
726
+ out["resources"] = resources.map((resource) => checkString$1("resources", resource, FIELD_MAX));
727
+ }
728
+ return out;
729
+ }
730
+ /**
731
+ * The EIP-4361-style message, byte for byte `createSignInMessageText` of
732
+ * `@solana/wallet-standard-util` 1.2.0 (an empty `resources` array still prints `Resources:`).
733
+ */
734
+ function signInMessageText(input) {
735
+ let message = `${input.domain} wants you to sign in with your Solana account:\n${input.address}`;
736
+ if (input.statement !== void 0 && input.statement !== "") message += `\n\n${input.statement}`;
737
+ const fields = [];
738
+ const optional = [
739
+ ["URI", input.uri],
740
+ ["Version", input.version],
741
+ ["Chain ID", input.chainId],
742
+ ["Nonce", input.nonce],
743
+ ["Issued At", input.issuedAt],
744
+ ["Expiration Time", input.expirationTime],
745
+ ["Not Before", input.notBefore],
746
+ ["Request ID", input.requestId]
747
+ ];
748
+ for (const [label, value] of optional) if (value !== void 0 && value !== "") fields.push(`${label}: ${value}`);
749
+ if (input.resources !== void 0) {
750
+ fields.push("Resources:");
751
+ for (const resource of input.resources) fields.push(`- ${resource}`);
752
+ }
753
+ if (fields.length > 0) message += `\n\n${fields.join("\n")}`;
754
+ return message;
755
+ }
612
756
  // src/connect/solana.ts
613
757
  const solanaId = (name) => {
614
758
  const entry = SOLANA_NETWORKS.find((n) => n.name === name);
@@ -623,6 +767,8 @@ const SOLANA_CHAIN_IDS = Object.freeze({
623
767
  "solana:mainnet": solanaId("Solana"),
624
768
  "solana:devnet": solanaId("Solana Devnet")
625
769
  });
770
+ /** The Wallet Standard short id of a registry network, or `undefined` when it has none. */
771
+ const walletStandardChain = (network) => Object.entries(SOLANA_CHAIN_IDS).find(([, id]) => id === network)?.[0];
626
772
  /**
627
773
  * The Wallet Standard handler: `standard:connect` authorizes the `solana` scope, `solana:*` sign
628
774
  * requests go through `solana-sign`, `solanaAccountsChanged` returns the re-pointed accounts the
@@ -630,35 +776,18 @@ const SOLANA_CHAIN_IDS = Object.freeze({
630
776
  */
631
777
  var SolanaWalletHandler = class {
632
778
  options;
633
- listeners = /* @__PURE__ */ new Set();
634
- unsubscribe;
779
+ events;
635
780
  constructor(options) {
636
781
  this.options = options;
782
+ this.events = new SessionEvents(options.connections, async (before, after) => Promise.all(diffSessions(before, after).map(async ({ origin }) => ({
783
+ name: "solanaAccountsChanged",
784
+ origin,
785
+ accounts: await this.solanaAccountsChanged(origin)
786
+ }))));
637
787
  }
638
788
  /** `standard:events` `change` per origin — derived from changes to the sessions. */
639
789
  subscribe(listener) {
640
- this.listeners.add(listener);
641
- if (this.unsubscribe === void 0) {
642
- let previous = this.options.connections.getState().sessions;
643
- this.unsubscribe = this.options.connections.store.subscribe((state) => {
644
- (async () => {
645
- const events = await Promise.all(diffSessions(previous, state.sessions).map(async ({ origin }) => ({
646
- name: "solanaAccountsChanged",
647
- origin,
648
- accounts: await this.solanaAccountsChanged(origin)
649
- })));
650
- for (const event of events) for (const l of this.listeners) l(event);
651
- })();
652
- previous = state.sessions;
653
- });
654
- }
655
- return () => {
656
- this.listeners.delete(listener);
657
- if (this.listeners.size === 0) {
658
- this.unsubscribe?.();
659
- this.unsubscribe = void 0;
660
- }
661
- };
790
+ return this.events.subscribe(listener);
662
791
  }
663
792
  async handle(origin, request) {
664
793
  const checked = this.options.connections.checkOrigin(origin);
@@ -670,6 +799,7 @@ var SolanaWalletHandler = class {
670
799
  if (request.method === "solana:signTransaction") return this.signTransactions(checked, request, false);
671
800
  if (request.method === "solana:signAndSendTransaction") return this.signTransactions(checked, request, true);
672
801
  if (request.method === "solana:signMessage") return this.signMessage(checked, request);
802
+ if (request.method === "solana:signIn") return this.signIn(checked, request);
673
803
  throw invalidParams(`unsupported solana method ${request.method}`);
674
804
  }
675
805
  async connect(checked, request) {
@@ -677,7 +807,10 @@ var SolanaWalletHandler = class {
677
807
  const network = this.options.solanaNetwork();
678
808
  if (this.options.connections.solanaAccount(checked.origin, network) === void 0) {
679
809
  if (silent) throw new ProviderError(4100, "the wallet is not connected");
680
- await this.options.connections.request(checked.origin, "connect", void 0, "solana");
810
+ await this.options.connections.request(checked.origin, {
811
+ kind: "connect",
812
+ namespace: "solana"
813
+ });
681
814
  } else await this.options.connections.touch(checked.origin);
682
815
  const group = this.options.activeGroup();
683
816
  if (group === void 0) throw new ProviderError(4100, "no account group is selected");
@@ -685,46 +818,98 @@ var SolanaWalletHandler = class {
685
818
  return { accounts: [this.walletAccount(account, network)] };
686
819
  }
687
820
  walletAccount(account, network) {
821
+ const chain = walletStandardChain(network);
822
+ if (chain === void 0) throw new ProviderError(-32603, `network ${network} has no Wallet Standard chain id`);
688
823
  return {
689
824
  address: account.address,
690
825
  publicKey: account.publicKey,
691
- chains: [network],
826
+ chains: [chain],
692
827
  features: SOLANA_METHODS.filter((m) => m.startsWith("solana:"))
693
828
  };
694
829
  }
695
830
  async signTransactions(checked, request, send) {
696
- const network = this.options.solanaNetwork();
831
+ const network = this.networkOf(request.params, send);
697
832
  this.options.connections.authorize(checked.origin, network, request.method);
698
833
  const address = this.options.connections.solanaAccount(checked.origin, network);
699
834
  if (address === void 0) throw new ProviderError(4100, "no solana account for this origin");
835
+ checkAccounts(request.params, address);
700
836
  const txs = transactionsOf(request.params);
701
- const group = this.options.activeGroup();
702
- if (group === void 0) throw new ProviderError(4100, "no account group is selected");
703
- const pending = await this.options.requests.prepare({
704
- method: "solana-sign",
705
- origin: checked,
706
- account: {
707
- walletId: group.walletId,
708
- groupIndex: group.groupIndex,
709
- address
710
- },
711
- network,
712
- request: {
713
- kind: "transactions",
714
- transactions: txs,
715
- send
716
- }
837
+ const outcome = await this.signRequest(checked, network, address, {
838
+ kind: "transactions",
839
+ transactions: txs,
840
+ send
717
841
  });
718
- const outcome = await this.options.requests.outcome(pending.id);
719
842
  if (!("kind" in outcome) || outcome.kind !== "solana.transactions") throw new ProviderError(-32603, "the solana-sign request settled unexpectedly");
720
- return send ? { signatures: outcome.signatures } : { signedTransactions: outcome.signedTransactions };
843
+ return send ? { signatures: (outcome.signatures ?? []).map((signature) => base58.decode(signature)) } : { signedTransactions: outcome.signedTransactions };
844
+ }
845
+ /**
846
+ * The network a transaction call targets: the wallet's default when no input names a chain,
847
+ * otherwise the one chain every input agrees on (`chain` is required for sign-and-send).
848
+ */
849
+ networkOf(params, requireChain) {
850
+ const chains = paramList(params, "chains");
851
+ if (requireChain && (chains.length === 0 || chains.some((chain) => chain === void 0))) throw invalidParams("chain is required for solana:signAndSendTransaction");
852
+ const named = new Set(chains.filter((chain) => chain !== void 0));
853
+ if (named.size === 0) return this.options.solanaNetwork();
854
+ if (named.size > 1 || chains.some((chain) => chain === void 0)) throw invalidParams("every input must use the same chain");
855
+ const [chain] = [...named];
856
+ const network = typeof chain === "string" ? SOLANA_CHAIN_IDS[chain] : void 0;
857
+ if (network === void 0) throw invalidParams("unknown chain");
858
+ return network;
721
859
  }
722
860
  async signMessage(checked, request) {
723
861
  const network = this.options.solanaNetwork();
724
862
  this.options.connections.authorize(checked.origin, network, "solana:signMessage");
725
863
  const address = this.options.connections.solanaAccount(checked.origin, network);
726
- if (address === void 0) throw new ProviderError(4100, "no solana account for this origin");
864
+ if (address !== void 0) checkAccounts(request.params, address);
727
865
  const message = messageOf(request.params);
866
+ if (utf8Text(message) === void 0) throw new ProviderError(4200, BLIND_SIGNING_MESSAGE);
867
+ return {
868
+ signature: await this.signMessageRequest(checked, network, message),
869
+ signedMessage: message
870
+ };
871
+ }
872
+ /**
873
+ * Sign In With Solana: connects first when needed, binds the message to the page's host and the
874
+ * session's account, and signs the exact text the user is shown.
875
+ */
876
+ async signIn(checked, request) {
877
+ const { input: raw } = typeof request.params === "object" && request.params !== null ? request.params : {};
878
+ const input = checkSignInInput(raw === void 0 ? {} : raw);
879
+ const { host } = new URL(checked.origin);
880
+ if (input.domain !== void 0 && input.domain !== host) throw invalidParams("domain does not match the page");
881
+ const { accounts } = await this.connect(checked, { method: "standard:connect" });
882
+ const [walletAccount] = accounts;
883
+ const network = this.options.solanaNetwork();
884
+ this.options.connections.authorize(checked.origin, network, "solana:signIn");
885
+ if (walletAccount === void 0) throw new ProviderError(4100, "no solana account for this origin");
886
+ if (input.address !== void 0 && input.address !== walletAccount.address) throw new ProviderError(4100, "address is not the connected account");
887
+ const fields = {
888
+ ...input,
889
+ domain: host,
890
+ address: walletAccount.address
891
+ };
892
+ const message = new TextEncoder().encode(signInMessageText(fields));
893
+ return [{
894
+ account: walletAccount,
895
+ signedMessage: message,
896
+ signature: await this.signMessageRequest(checked, network, message, fields),
897
+ signatureType: "ed25519"
898
+ }];
899
+ }
900
+ async signMessageRequest(checked, network, message, signIn) {
901
+ const address = this.options.connections.solanaAccount(checked.origin, network);
902
+ if (address === void 0) throw new ProviderError(4100, "no solana account for this origin");
903
+ const outcome = await this.signRequest(checked, network, address, {
904
+ kind: "message",
905
+ message,
906
+ ...signIn === void 0 ? {} : { signIn }
907
+ });
908
+ if (!("kind" in outcome) || outcome.kind !== "solana.message") throw new ProviderError(-32603, "the solana-sign request settled unexpectedly");
909
+ return outcome.signature;
910
+ }
911
+ /** One `solana-sign` request for the active group, resolved to its outcome. */
912
+ async signRequest(checked, network, address, request) {
728
913
  const group = this.options.activeGroup();
729
914
  if (group === void 0) throw new ProviderError(4100, "no account group is selected");
730
915
  const pending = await this.options.requests.prepare({
@@ -736,17 +921,9 @@ var SolanaWalletHandler = class {
736
921
  address
737
922
  },
738
923
  network,
739
- request: {
740
- kind: "message",
741
- message
742
- }
924
+ request
743
925
  });
744
- const outcome = await this.options.requests.outcome(pending.id);
745
- if (!("kind" in outcome) || outcome.kind !== "solana.message") throw new ProviderError(-32603, "the solana-sign request settled unexpectedly");
746
- return {
747
- signature: outcome.signature,
748
- signedMessage: message
749
- };
926
+ return this.options.requests.outcome(pending.id);
750
927
  }
751
928
  /** The `setActiveGroup` re-point: the solana session's new `WalletAccount[]` for `change`. */
752
929
  async solanaAccountsChanged(_origin) {
@@ -757,6 +934,16 @@ var SolanaWalletHandler = class {
757
934
  return [this.walletAccount(account, network)];
758
935
  }
759
936
  };
937
+ const paramList = (params, name) => {
938
+ const value = typeof params === "object" && params !== null ? new Map(Object.entries(params)).get(name) : void 0;
939
+ if (value === void 0) return [];
940
+ if (!Array.isArray(value)) throw invalidParams(`${name} must be an array`);
941
+ return value;
942
+ };
943
+ /** Every account the page names must be the session's Solana account. */
944
+ const checkAccounts = (params, address) => {
945
+ if (paramList(params, "accounts").some((account) => account !== address)) throw new ProviderError(4100, "account is not the connected account");
946
+ };
760
947
  const isBytesEnvelope = (v) => typeof v === "object" && v !== null && typeof v.__bytes === "string";
761
948
  const transactionsOf = (params) => {
762
949
  const raw = typeof params === "object" && params !== null ? params.transactions : void 0;
@@ -1121,7 +1308,10 @@ var WeblnHandler = class {
1121
1308
  }
1122
1309
  async handle(origin, request) {
1123
1310
  if (request.method === "enable") {
1124
- if (this.options.connections.lightningPolicy(origin) === void 0) await this.options.connections.request(origin, "connect", void 0, "lightning");
1311
+ if (this.options.connections.lightningPolicy(origin) === void 0) await this.options.connections.request(origin, {
1312
+ kind: "connect",
1313
+ namespace: "lightning"
1314
+ });
1125
1315
  await this.options.connections.touch(origin);
1126
1316
  return true;
1127
1317
  }
@@ -1178,7 +1368,7 @@ var WeblnHandler = class {
1178
1368
  async lnurl(origin, ref, params) {
1179
1369
  const parsed = parsePayment(checkString(params, "lnurl"), {
1180
1370
  network: ref.network,
1181
- now: Date.now()
1371
+ now: this.options.now()
1182
1372
  });
1183
1373
  if (parsed.kind !== "request") throw invalidParams("lnurl is not an LNURL-pay request");
1184
1374
  if (parsed.request.options.some((o) => o.kind === "lnurl-withdraw")) throw unsupportedMethod("lnurl-withdraw");
@@ -1225,7 +1415,7 @@ var WeblnHandler = class {
1225
1415
  lightningOption(ref, invoice) {
1226
1416
  const parsed = parsePayment(invoice, {
1227
1417
  network: ref.network,
1228
- now: Date.now()
1418
+ now: this.options.now()
1229
1419
  });
1230
1420
  if (parsed.kind !== "request") throw invalidParams("sendPayment invoice is not a BOLT11 invoice");
1231
1421
  const option = parsed.request.options.find((o) => o.kind === "lightning");
@@ -1242,6 +1432,6 @@ var WeblnHandler = class {
1242
1432
  };
1243
1433
  }
1244
1434
  };
1245
- export { Nip07Handler as a, ProviderError as c, unauthorized as d, unrecognizedChain as f, Controller as h, SolanaWalletHandler as i, internalError as l, userRejectedRequest as m, parsePayment as n, ConnectionController as o, unsupportedMethod as p, SOLANA_CHAIN_IDS as r, evmChainId as s, WeblnHandler as t, invalidParams as u };
1435
+ export { userRejectedRequest as _, Nip07Handler as a, utf8Text as c, ProviderError as d, internalError as f, unsupportedMethod as g, unrecognizedChain as h, SolanaWalletHandler as i, ConnectionController as l, unauthorized as m, parsePayment as n, SessionEvents as o, invalidParams as p, SOLANA_CHAIN_IDS as r, BLIND_SIGNING_MESSAGE as s, WeblnHandler as t, evmChainId as u, PHISHING_BLOCKED_MESSAGE as v, Controller as y };
1246
1436
 
1247
- //# sourceMappingURL=webln-CHjBMRcv.mjs.map
1437
+ //# sourceMappingURL=webln-DHYqdaDU.mjs.map