@qntx/wallet-engine 0.7.0 → 0.8.1
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.
- package/README.md +2 -0
- package/dist/connect.d.mts +45 -0
- package/dist/connect.mjs +174 -0
- package/dist/connect.mjs.map +1 -0
- package/dist/errors-CW_XXGL9.d.mts +1296 -0
- package/dist/gateway-contract.mjs +183 -1
- package/dist/gateway-contract.mjs.map +1 -0
- package/dist/index.d.mts +18 -1000
- package/dist/index.mjs +587 -939
- package/dist/index.mjs.map +1 -1
- package/dist/registry-CHiAn88k.mjs +98 -0
- package/dist/registry-CHiAn88k.mjs.map +1 -0
- package/dist/webln-CHjBMRcv.mjs +1247 -0
- package/dist/webln-CHjBMRcv.mjs.map +1 -0
- package/package.json +27 -16
- package/dist/contract-CEsgLme3.mjs +0 -277
- package/dist/contract-CEsgLme3.mjs.map +0 -1
|
@@ -0,0 +1,1247 @@
|
|
|
1
|
+
import { r as SOLANA_NETWORKS } from "./registry-CHiAn88k.mjs";
|
|
2
|
+
import { createStore } from "zustand/vanilla";
|
|
3
|
+
import { bytesToHex, hexToBytes } from "@noble/hashes/utils.js";
|
|
4
|
+
import { bitcoinAddressScript, decodeBolt11, decodeSparkAddress, parseSparkInvoice } from "@qntx/spark";
|
|
5
|
+
import { decodeLnurl, lightningAddressUrl } from "@qntx/spark/lnurl";
|
|
6
|
+
// src/controller.ts
|
|
7
|
+
/**
|
|
8
|
+
* Controller base: a zustand vanilla store plus lifecycle. `update` applies a recipe that must
|
|
9
|
+
* return a NEW state object; returning the same reference is a no-op (no set, no notification).
|
|
10
|
+
* Persistence and migrations layer on later — this package carries only what its first user needs.
|
|
11
|
+
*/
|
|
12
|
+
var Controller = class {
|
|
13
|
+
name;
|
|
14
|
+
store;
|
|
15
|
+
constructor(options) {
|
|
16
|
+
this.name = options.name;
|
|
17
|
+
this.store = createStore(options.defaultState);
|
|
18
|
+
}
|
|
19
|
+
getState() {
|
|
20
|
+
return this.store.getState();
|
|
21
|
+
}
|
|
22
|
+
update(recipe) {
|
|
23
|
+
this.store.setState((state) => recipe(state));
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
// src/connect/errors.ts
|
|
27
|
+
/** EIP-1193 / EIP-1474 / EIP-3326 error: `code` is what the page's promise rejects with. */
|
|
28
|
+
var ProviderError = class extends Error {
|
|
29
|
+
code;
|
|
30
|
+
constructor(code, message) {
|
|
31
|
+
super(message);
|
|
32
|
+
this.name = "ProviderError";
|
|
33
|
+
this.code = code;
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
const userRejectedRequest = (message = "user rejected the request") => new ProviderError(4001, message);
|
|
37
|
+
const unauthorized = (message = "not authorized") => new ProviderError(4100, message);
|
|
38
|
+
const unsupportedMethod = (method) => new ProviderError(4200, `${method} is not supported`);
|
|
39
|
+
const unrecognizedChain = (message = "unrecognized chain") => new ProviderError(4902, message);
|
|
40
|
+
const invalidParams = (message) => new ProviderError(-32602, message);
|
|
41
|
+
const requestPending = (message) => new ProviderError(-32002, message);
|
|
42
|
+
const internalError = (message) => new ProviderError(-32603, message);
|
|
43
|
+
// src/connect/controller.ts
|
|
44
|
+
const COLLECTION = "connections";
|
|
45
|
+
/** `lastUsedAt` is rewritten at most this often. */
|
|
46
|
+
const TOUCH_INTERVAL_MS = 6e4;
|
|
47
|
+
/** Granted for every network a session covers. */
|
|
48
|
+
const SESSION_METHODS = [
|
|
49
|
+
"eth_sendTransaction",
|
|
50
|
+
"personal_sign",
|
|
51
|
+
"eth_signTypedData_v4"
|
|
52
|
+
];
|
|
53
|
+
const SESSION_NOTIFICATIONS = ["accountsChanged", "chainChanged"];
|
|
54
|
+
/** The `nostr` namespace scope's granted methods — the NIP-07 surface. */
|
|
55
|
+
const NOSTR_METHODS = [
|
|
56
|
+
"getPublicKey",
|
|
57
|
+
"signEvent",
|
|
58
|
+
"nip04.encrypt",
|
|
59
|
+
"nip04.decrypt",
|
|
60
|
+
"nip44.encrypt",
|
|
61
|
+
"nip44.decrypt"
|
|
62
|
+
];
|
|
63
|
+
/** The `lightning` namespace scope's granted methods — the WebLN surface. */
|
|
64
|
+
const LIGHTNING_METHODS = [
|
|
65
|
+
"enable",
|
|
66
|
+
"getInfo",
|
|
67
|
+
"sendPayment",
|
|
68
|
+
"makeInvoice",
|
|
69
|
+
"lnurl",
|
|
70
|
+
"getBalance"
|
|
71
|
+
];
|
|
72
|
+
/** The `solana` namespace scope's granted methods — the Wallet Standard surface. */
|
|
73
|
+
const SOLANA_METHODS = [
|
|
74
|
+
"standard:connect",
|
|
75
|
+
"standard:disconnect",
|
|
76
|
+
"standard:events",
|
|
77
|
+
"solana:signTransaction",
|
|
78
|
+
"solana:signAndSendTransaction",
|
|
79
|
+
"solana:signMessage"
|
|
80
|
+
];
|
|
81
|
+
/** `eip155:1` → 1; `undefined` for anything that is not an EVM network. */
|
|
82
|
+
const evmChainId = (network) => {
|
|
83
|
+
const match = /^eip155:(\d+)$/.exec(network);
|
|
84
|
+
const id = match?.[1] === void 0 ? void 0 : Number(match[1]);
|
|
85
|
+
return id !== void 0 && Number.isSafeInteger(id) ? id : void 0;
|
|
86
|
+
};
|
|
87
|
+
const caip10 = (network, address) => `${network}:${address}`;
|
|
88
|
+
const addressOf = (account) => account.slice(account.lastIndexOf(":") + 1);
|
|
89
|
+
const isObject$2 = (v) => typeof v === "object" && v !== null;
|
|
90
|
+
const isSession = (value) => {
|
|
91
|
+
if (!isObject$2(value) || !isObject$2(value["origin"]) || !isObject$2(value["scopes"])) return false;
|
|
92
|
+
return typeof value["id"] === "string" && value["origin"]["kind"] === "browser" && typeof value["origin"]["origin"] === "string" && typeof value["currentNetwork"] === "string" && typeof value["createdAt"] === "number" && typeof value["lastUsedAt"] === "number" && (value["nostrPolicy"] === void 0 || isNostrPolicy(value["nostrPolicy"])) && (value["lightningPolicy"] === void 0 || isLightningPolicy(value["lightningPolicy"]));
|
|
93
|
+
};
|
|
94
|
+
const isLightningPolicy = (value) => isObject$2(value) && typeof value["balance"] === "boolean";
|
|
95
|
+
const isNostrPolicy = (value) => isObject$2(value) && typeof value["decrypt"] === "boolean" && (value["signing"] === "ask" || value["signing"] === "always" || isObject$2(value["signing"]) && Array.isArray(value["signing"]["kinds"]) && value["signing"]["kinds"].every((k) => typeof k === "number"));
|
|
96
|
+
var ConnectionController = class extends Controller {
|
|
97
|
+
options;
|
|
98
|
+
engineStore;
|
|
99
|
+
waiters = /* @__PURE__ */ new Map();
|
|
100
|
+
group;
|
|
101
|
+
identity;
|
|
102
|
+
constructor(options) {
|
|
103
|
+
super({
|
|
104
|
+
name: "connections",
|
|
105
|
+
defaultState: () => ({
|
|
106
|
+
sessions: {},
|
|
107
|
+
pending: {}
|
|
108
|
+
})
|
|
109
|
+
});
|
|
110
|
+
this.options = options;
|
|
111
|
+
}
|
|
112
|
+
async init() {
|
|
113
|
+
const store = await this.options.openStore();
|
|
114
|
+
this.engineStore = store;
|
|
115
|
+
this.group = void 0;
|
|
116
|
+
this.identity = void 0;
|
|
117
|
+
const collection = store.collection(COLLECTION);
|
|
118
|
+
const keys = await collection.list();
|
|
119
|
+
const rows = await Promise.all(keys.map(async (key) => collection.get(key)));
|
|
120
|
+
const now = this.options.now();
|
|
121
|
+
const sessions = {};
|
|
122
|
+
const expired = [];
|
|
123
|
+
for (const [index, raw] of rows.entries()) {
|
|
124
|
+
const key = keys[index];
|
|
125
|
+
if (raw === void 0 || key === void 0) continue;
|
|
126
|
+
const parsed = JSON.parse(new TextDecoder().decode(raw));
|
|
127
|
+
if (!isSession(parsed)) {
|
|
128
|
+
this.options.logger.warn("connection session skipped: malformed");
|
|
129
|
+
expired.push(key);
|
|
130
|
+
} else if (now - parsed.lastUsedAt > 7776e6) expired.push(key);
|
|
131
|
+
else sessions[parsed.id] = parsed;
|
|
132
|
+
}
|
|
133
|
+
await Promise.all(expired.map(async (key) => collection.delete(key)));
|
|
134
|
+
this.update(() => ({
|
|
135
|
+
sessions,
|
|
136
|
+
pending: {}
|
|
137
|
+
}));
|
|
138
|
+
}
|
|
139
|
+
async destroy() {
|
|
140
|
+
this.lock();
|
|
141
|
+
await Promise.resolve();
|
|
142
|
+
}
|
|
143
|
+
/** Locking is not consent: every pending connection is rejected. */
|
|
144
|
+
lock() {
|
|
145
|
+
this.engineStore = void 0;
|
|
146
|
+
this.group = void 0;
|
|
147
|
+
for (const waiter of this.waiters.values()) waiter.reject(userRejectedRequest("the wallet was locked"));
|
|
148
|
+
this.waiters.clear();
|
|
149
|
+
this.update(() => ({
|
|
150
|
+
sessions: {},
|
|
151
|
+
pending: {}
|
|
152
|
+
}));
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* A page navigated away (or the bridge is being disposed): the origin's pending connection
|
|
156
|
+
* requests are rejected and its unfinished pipeline requests voided — the live session survives
|
|
157
|
+
* (a refresh is not a revocation).
|
|
158
|
+
*/
|
|
159
|
+
invalidateOrigin(origin) {
|
|
160
|
+
for (const entry of this.pending()) {
|
|
161
|
+
if (entry.origin.origin !== origin) continue;
|
|
162
|
+
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
|
+
}));
|
|
168
|
+
}
|
|
169
|
+
this.options.invalidate(origin);
|
|
170
|
+
}
|
|
171
|
+
/** Throws `4100` unless `origin` is `https://host[:port]` (or localhost in development). */
|
|
172
|
+
checkOrigin(origin) {
|
|
173
|
+
let url;
|
|
174
|
+
try {
|
|
175
|
+
url = new URL(origin);
|
|
176
|
+
} catch {
|
|
177
|
+
throw unauthorized("invalid origin");
|
|
178
|
+
}
|
|
179
|
+
const localhost = url.protocol === "http:" && url.hostname === "localhost";
|
|
180
|
+
if (url.origin !== origin || url.protocol !== "https:" && !(localhost && this.options.allowLocalhost)) throw unauthorized("origin not allowed");
|
|
181
|
+
return {
|
|
182
|
+
kind: "browser",
|
|
183
|
+
origin
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
session(origin) {
|
|
187
|
+
return Object.values(this.getState().sessions).find((s) => s.origin.origin === origin);
|
|
188
|
+
}
|
|
189
|
+
pending() {
|
|
190
|
+
return Object.values(this.getState().pending);
|
|
191
|
+
}
|
|
192
|
+
/** The group sessions are bound to: the host's last `setActiveGroup`, else the app's selection. */
|
|
193
|
+
activeGroup() {
|
|
194
|
+
return this.group ?? this.options.selectedGroup();
|
|
195
|
+
}
|
|
196
|
+
/** Whether `network` is an EVM network the wallet has enabled. */
|
|
197
|
+
isEnabled(network) {
|
|
198
|
+
return this.options.enabledNetworks().includes(network);
|
|
199
|
+
}
|
|
200
|
+
/** The origin's authorized addresses on its current network; empty when not connected. */
|
|
201
|
+
accounts(origin) {
|
|
202
|
+
const session = this.session(origin);
|
|
203
|
+
return session?.scopes[session.currentNetwork]?.accounts.map(addressOf) ?? [];
|
|
204
|
+
}
|
|
205
|
+
/** Throws `4100` unless the origin's session covers `method` on `network`. */
|
|
206
|
+
authorize(origin, network, method) {
|
|
207
|
+
const session = this.session(origin);
|
|
208
|
+
const scope = session?.scopes[network];
|
|
209
|
+
if (session === void 0 || scope === void 0 || !scope.methods.includes(method)) throw unauthorized();
|
|
210
|
+
return session;
|
|
211
|
+
}
|
|
212
|
+
/** Resolves with the session once the host approves; rejects with `4001` when it refuses. */
|
|
213
|
+
async request(origin, kind, network, namespace = "eip155") {
|
|
214
|
+
if (this.engineStore === void 0) throw userRejectedRequest("the wallet is locked");
|
|
215
|
+
if (this.pending().some((p) => p.origin.origin === origin)) throw requestPending("a connection request is already pending");
|
|
216
|
+
const id = `conn-${[...this.options.random(8)].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
|
|
217
|
+
const entry = {
|
|
218
|
+
id,
|
|
219
|
+
origin: {
|
|
220
|
+
kind: "browser",
|
|
221
|
+
origin
|
|
222
|
+
},
|
|
223
|
+
kind,
|
|
224
|
+
namespace,
|
|
225
|
+
...network === void 0 ? {} : { network },
|
|
226
|
+
createdAt: this.options.now()
|
|
227
|
+
};
|
|
228
|
+
return new Promise((resolve, reject) => {
|
|
229
|
+
this.waiters.set(id, {
|
|
230
|
+
resolve,
|
|
231
|
+
reject
|
|
232
|
+
});
|
|
233
|
+
this.update((s) => ({
|
|
234
|
+
...s,
|
|
235
|
+
pending: {
|
|
236
|
+
...s.pending,
|
|
237
|
+
[id]: entry
|
|
238
|
+
}
|
|
239
|
+
}));
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* The host's approval, by id: the accounts granted (EVM addresses of the active group) and the
|
|
244
|
+
* network.
|
|
245
|
+
*/
|
|
246
|
+
async approveConnection(id, grant) {
|
|
247
|
+
const store = this.requireStore();
|
|
248
|
+
const entry = this.getState().pending[id];
|
|
249
|
+
const waiter = this.waiters.get(id);
|
|
250
|
+
if (entry === void 0 || waiter === void 0) throw new Error(`unknown connection request ${id}`);
|
|
251
|
+
if (entry.kind === "network" && entry.network !== grant.network) throw new Error(`connection request ${id} is for ${String(entry.network)}`);
|
|
252
|
+
const scopes = {};
|
|
253
|
+
if (entry.namespace === "nostr") {
|
|
254
|
+
if (grant.nostr === void 0) throw invalidParams("a nostr connection needs the identity's pubkey and policy");
|
|
255
|
+
const identity = this.activeIdentity();
|
|
256
|
+
if (identity === void 0) throw userRejectedRequest("no nostr identity is selected");
|
|
257
|
+
const identityPubkey = (await this.options.nostrPubkey(identity)).toLowerCase();
|
|
258
|
+
if (grant.nostr.pubkey.toLowerCase() !== identityPubkey) throw invalidParams("only the active identity can be granted");
|
|
259
|
+
scopes["nostr"] = {
|
|
260
|
+
accounts: [`nostr:${identityPubkey}`],
|
|
261
|
+
methods: NOSTR_METHODS,
|
|
262
|
+
notifications: []
|
|
263
|
+
};
|
|
264
|
+
} else if (entry.namespace === "solana") {
|
|
265
|
+
const group = this.activeGroup();
|
|
266
|
+
if (group === void 0) throw new Error("no account group is selected");
|
|
267
|
+
const solanaNetworks = this.options.enabledNetworks().filter((n) => n.startsWith("solana:"));
|
|
268
|
+
const solanaEntries = await Promise.all(solanaNetworks.map(async (network) => {
|
|
269
|
+
const address = await this.options.solanaAddress(group, network);
|
|
270
|
+
return [network, {
|
|
271
|
+
accounts: [caip10(network, address)],
|
|
272
|
+
methods: SOLANA_METHODS,
|
|
273
|
+
notifications: ["change"]
|
|
274
|
+
}];
|
|
275
|
+
}));
|
|
276
|
+
Object.assign(scopes, Object.fromEntries(solanaEntries));
|
|
277
|
+
} else if (entry.namespace === "lightning") {
|
|
278
|
+
if (grant.lightning === void 0) throw invalidParams("a lightning connection needs the origin's policy");
|
|
279
|
+
const group = this.activeGroup();
|
|
280
|
+
if (group === void 0) throw new Error("no account group is selected");
|
|
281
|
+
scopes["lightning"] = {
|
|
282
|
+
accounts: [`spark:${group.walletId}:${String(group.groupIndex)}`],
|
|
283
|
+
methods: LIGHTNING_METHODS,
|
|
284
|
+
notifications: []
|
|
285
|
+
};
|
|
286
|
+
} else {
|
|
287
|
+
if (evmChainId(grant.network) === void 0 || !this.options.enabledNetworks().includes(grant.network)) throw invalidParams(`${grant.network} is not an enabled EVM network`);
|
|
288
|
+
const group = this.activeGroup();
|
|
289
|
+
if (group === void 0) throw new Error("no account group is selected");
|
|
290
|
+
const own = (await this.options.evmAddress(group, grant.network)).toLowerCase();
|
|
291
|
+
if (grant.accounts.length === 0 || grant.accounts.some((a) => a.toLowerCase() !== own)) throw invalidParams("only the active group's account can be granted");
|
|
292
|
+
scopes[grant.network] = {
|
|
293
|
+
accounts: [caip10(grant.network, own)],
|
|
294
|
+
methods: SESSION_METHODS,
|
|
295
|
+
notifications: SESSION_NOTIFICATIONS
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
if (this.getState().pending[id] === void 0) throw new Error(`connection request ${id} is no longer pending`);
|
|
299
|
+
const now = this.options.now();
|
|
300
|
+
const existing = this.session(entry.origin.origin);
|
|
301
|
+
const session = {
|
|
302
|
+
id: existing?.id ?? `session-${[...this.options.random(8)].map((b) => b.toString(16).padStart(2, "0")).join("")}`,
|
|
303
|
+
origin: entry.origin,
|
|
304
|
+
scopes: {
|
|
305
|
+
...existing?.scopes,
|
|
306
|
+
...scopes
|
|
307
|
+
},
|
|
308
|
+
currentNetwork: grant.network,
|
|
309
|
+
...grant.nostr === void 0 ? {} : { nostrPolicy: grant.nostr.policy },
|
|
310
|
+
...grant.lightning === void 0 ? {} : { lightningPolicy: grant.lightning.policy },
|
|
311
|
+
createdAt: existing?.createdAt ?? now,
|
|
312
|
+
lastUsedAt: now
|
|
313
|
+
};
|
|
314
|
+
await this.persist(store, session);
|
|
315
|
+
this.dropPending(id);
|
|
316
|
+
if (existing !== void 0 && existing.currentNetwork !== grant.network) this.options.invalidate(entry.origin.origin);
|
|
317
|
+
waiter.resolve(session);
|
|
318
|
+
return session;
|
|
319
|
+
}
|
|
320
|
+
rejectConnection(id) {
|
|
321
|
+
const waiter = this.waiters.get(id);
|
|
322
|
+
if (this.getState().pending[id] === void 0 || waiter === void 0) throw new Error(`unknown connection request ${id}`);
|
|
323
|
+
this.dropPending(id);
|
|
324
|
+
waiter.reject(userRejectedRequest());
|
|
325
|
+
}
|
|
326
|
+
/** Ends the origin's session; its pending connection and unfinished requests are void. */
|
|
327
|
+
async revoke(origin) {
|
|
328
|
+
const store = this.requireStore();
|
|
329
|
+
for (const p of this.pending().filter((x) => x.origin.origin === origin)) {
|
|
330
|
+
const waiter = this.waiters.get(p.id);
|
|
331
|
+
this.dropPending(p.id);
|
|
332
|
+
waiter?.reject(userRejectedRequest("the connection was revoked"));
|
|
333
|
+
}
|
|
334
|
+
const session = this.session(origin);
|
|
335
|
+
if (session !== void 0) {
|
|
336
|
+
await store.collection(COLLECTION).delete(session.id);
|
|
337
|
+
this.update((s) => {
|
|
338
|
+
const { [session.id]: _gone, ...sessions } = s.sessions;
|
|
339
|
+
return {
|
|
340
|
+
...s,
|
|
341
|
+
sessions
|
|
342
|
+
};
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
this.options.invalidate(origin);
|
|
346
|
+
}
|
|
347
|
+
/** Switches within the session's scope; the origin's unfinished requests are void. */
|
|
348
|
+
async setCurrentNetwork(origin, network) {
|
|
349
|
+
const store = this.requireStore();
|
|
350
|
+
const session = this.session(origin);
|
|
351
|
+
if (session === void 0 || session.scopes[network] === void 0) throw unauthorized();
|
|
352
|
+
await this.persist(store, {
|
|
353
|
+
...session,
|
|
354
|
+
currentNetwork: network
|
|
355
|
+
});
|
|
356
|
+
this.options.invalidate(origin);
|
|
357
|
+
}
|
|
358
|
+
async touch(origin) {
|
|
359
|
+
const store = this.engineStore;
|
|
360
|
+
const session = this.session(origin);
|
|
361
|
+
const now = this.options.now();
|
|
362
|
+
if (store === void 0 || session === void 0 || now - session.lastUsedAt < TOUCH_INTERVAL_MS) return;
|
|
363
|
+
await this.persist(store, {
|
|
364
|
+
...session,
|
|
365
|
+
lastUsedAt: now
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* The host switched account group: every session's accounts become the new group's addresses. A
|
|
370
|
+
* session that cannot get one (no address derivable) is left with an empty list and has to be
|
|
371
|
+
* authorized again.
|
|
372
|
+
*/
|
|
373
|
+
async setActiveGroup(walletId, groupIndex) {
|
|
374
|
+
const store = this.requireStore();
|
|
375
|
+
const group = {
|
|
376
|
+
walletId,
|
|
377
|
+
groupIndex
|
|
378
|
+
};
|
|
379
|
+
this.group = group;
|
|
380
|
+
await Promise.all(Object.values(this.getState().sessions).map(async (session) => {
|
|
381
|
+
const entries = await Promise.all(Object.entries(session.scopes).map(async ([network, scope]) => {
|
|
382
|
+
if (scope.accounts.length === 0) return [network, scope];
|
|
383
|
+
try {
|
|
384
|
+
if (network === "nostr" || network === "lightning") return [network, scope];
|
|
385
|
+
if (network.startsWith("solana:")) {
|
|
386
|
+
const address = await this.options.solanaAddress(group, network);
|
|
387
|
+
return [network, {
|
|
388
|
+
...scope,
|
|
389
|
+
accounts: [caip10(network, address)]
|
|
390
|
+
}];
|
|
391
|
+
}
|
|
392
|
+
const address = await this.options.evmAddress(group, network);
|
|
393
|
+
return [network, {
|
|
394
|
+
...scope,
|
|
395
|
+
accounts: [caip10(network, address.toLowerCase())]
|
|
396
|
+
}];
|
|
397
|
+
} catch (error) {
|
|
398
|
+
this.options.logger.warn("connection account unavailable in the new group", error);
|
|
399
|
+
return [network, {
|
|
400
|
+
...scope,
|
|
401
|
+
accounts: []
|
|
402
|
+
}];
|
|
403
|
+
}
|
|
404
|
+
}));
|
|
405
|
+
await this.persist(store, {
|
|
406
|
+
...session,
|
|
407
|
+
scopes: Object.fromEntries(entries)
|
|
408
|
+
});
|
|
409
|
+
}));
|
|
410
|
+
}
|
|
411
|
+
/** The active Nostr identity — `undefined` until the host picks one. */
|
|
412
|
+
activeIdentity() {
|
|
413
|
+
return this.identity;
|
|
414
|
+
}
|
|
415
|
+
/** The origin's persisted Nostr policy — `undefined` until it is nostr-authorized. */
|
|
416
|
+
nostrPolicy(origin) {
|
|
417
|
+
return this.session(origin)?.nostrPolicy;
|
|
418
|
+
}
|
|
419
|
+
/** The origin's `nostr` namespace scope's pubkey, or `undefined` when not nostr-authorized. */
|
|
420
|
+
nostrAccount(origin) {
|
|
421
|
+
const account = this.session(origin)?.scopes["nostr"]?.accounts[0];
|
|
422
|
+
return account === void 0 ? void 0 : addressOf(account);
|
|
423
|
+
}
|
|
424
|
+
/** The origin's persisted Lightning policy — `undefined` until it is lightning-authorized. */
|
|
425
|
+
lightningPolicy(origin) {
|
|
426
|
+
return this.session(origin)?.lightningPolicy;
|
|
427
|
+
}
|
|
428
|
+
/** The origin's `solana` scope's address on `network`, or `undefined` when not authorized. */
|
|
429
|
+
solanaAccount(origin, network) {
|
|
430
|
+
const account = this.session(origin)?.scopes[network]?.accounts[0];
|
|
431
|
+
return account === void 0 ? void 0 : addressOf(account);
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* The host's Nostr identity selection: every authorized `nostr` session's account becomes the new
|
|
435
|
+
* identity's pubkey (or empties when the identity is cleared). No event — NIP-07 has none.
|
|
436
|
+
*/
|
|
437
|
+
async setActiveIdentity(ref) {
|
|
438
|
+
const store = this.requireStore();
|
|
439
|
+
this.identity = ref;
|
|
440
|
+
let pubkey;
|
|
441
|
+
if (ref !== void 0) pubkey = (await this.options.nostrPubkey(ref)).toLowerCase();
|
|
442
|
+
await Promise.all(Object.values(this.getState().sessions).map(async (session) => {
|
|
443
|
+
const scope = session.scopes["nostr"];
|
|
444
|
+
if (scope === void 0 || scope.accounts.length === 0) return;
|
|
445
|
+
await this.persist(store, {
|
|
446
|
+
...session,
|
|
447
|
+
scopes: {
|
|
448
|
+
...session.scopes,
|
|
449
|
+
nostr: {
|
|
450
|
+
...scope,
|
|
451
|
+
accounts: pubkey === void 0 ? [] : [`nostr:${pubkey}`]
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
});
|
|
455
|
+
}));
|
|
456
|
+
}
|
|
457
|
+
dropPending(id) {
|
|
458
|
+
this.waiters.delete(id);
|
|
459
|
+
this.update((s) => {
|
|
460
|
+
const { [id]: _gone, ...pending } = s.pending;
|
|
461
|
+
return {
|
|
462
|
+
...s,
|
|
463
|
+
pending
|
|
464
|
+
};
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
async persist(store, session) {
|
|
468
|
+
try {
|
|
469
|
+
await store.collection(COLLECTION).put(session.id, new TextEncoder().encode(JSON.stringify(session)));
|
|
470
|
+
} catch (error) {
|
|
471
|
+
throw internalError(error instanceof Error ? error.message : String(error));
|
|
472
|
+
}
|
|
473
|
+
this.update((s) => ({
|
|
474
|
+
...s,
|
|
475
|
+
sessions: {
|
|
476
|
+
...s.sessions,
|
|
477
|
+
[session.id]: session
|
|
478
|
+
}
|
|
479
|
+
}));
|
|
480
|
+
}
|
|
481
|
+
requireStore() {
|
|
482
|
+
if (this.engineStore === void 0) throw userRejectedRequest("the wallet is locked");
|
|
483
|
+
return this.engineStore;
|
|
484
|
+
}
|
|
485
|
+
};
|
|
486
|
+
// src/connect/nip07.ts
|
|
487
|
+
/** `signEvent` of these kinds always asks for explicit confirmation, whatever the policy allows. */
|
|
488
|
+
const FORCED_CONFIRM_KINDS = /* @__PURE__ */ new Set([
|
|
489
|
+
0,
|
|
490
|
+
3,
|
|
491
|
+
5,
|
|
492
|
+
10002
|
|
493
|
+
]);
|
|
494
|
+
const MAX_TAGS = 64;
|
|
495
|
+
const MAX_TAG_ITEMS = 32;
|
|
496
|
+
const MAX_TAG_ITEM_LENGTH = 1024;
|
|
497
|
+
const MAX_CONTENT_LENGTH = 131072;
|
|
498
|
+
const isObject$1 = (v) => typeof v === "object" && v !== null;
|
|
499
|
+
/**
|
|
500
|
+
* Strict event validation: `kind` is an integer 0–65535, `created_at` a safe integer, `tags` a
|
|
501
|
+
* bounded `string[][]`, `content` a bounded string and `pubkey` — when present — a string.
|
|
502
|
+
*/
|
|
503
|
+
function checkEvent(value) {
|
|
504
|
+
if (!isObject$1(value)) throw invalidParams("event is not an object");
|
|
505
|
+
const { kind, content, pubkey, tags, created_at: createdAt } = value;
|
|
506
|
+
if (typeof kind !== "number" || !Number.isSafeInteger(kind) || kind < 0 || kind > 65535) throw invalidParams("event.kind must be an integer 0–65535");
|
|
507
|
+
if (typeof content !== "string" || content.length > MAX_CONTENT_LENGTH) throw invalidParams("event.content must be a string");
|
|
508
|
+
if (pubkey !== void 0 && typeof pubkey !== "string") throw invalidParams("event.pubkey must be a string");
|
|
509
|
+
if (typeof createdAt !== "number" || !Number.isSafeInteger(createdAt)) throw invalidParams("event.created_at must be a safe integer");
|
|
510
|
+
if (!Array.isArray(tags) || tags.length > MAX_TAGS) throw invalidParams("event.tags must be a bounded array of string arrays");
|
|
511
|
+
const checkedTags = [];
|
|
512
|
+
for (const tag of tags) {
|
|
513
|
+
if (!Array.isArray(tag) || tag.length > MAX_TAG_ITEMS) throw invalidParams("event.tags items must be bounded string arrays");
|
|
514
|
+
const checkedTag = [];
|
|
515
|
+
for (const item of tag) {
|
|
516
|
+
if (typeof item !== "string" || item.length > MAX_TAG_ITEM_LENGTH) throw invalidParams("event.tags items must contain bounded strings");
|
|
517
|
+
checkedTag.push(item);
|
|
518
|
+
}
|
|
519
|
+
checkedTags.push(checkedTag);
|
|
520
|
+
}
|
|
521
|
+
return {
|
|
522
|
+
kind,
|
|
523
|
+
content,
|
|
524
|
+
created_at: createdAt,
|
|
525
|
+
tags: checkedTags,
|
|
526
|
+
...pubkey === void 0 ? {} : { pubkey }
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
/** NIP-04/NIP-44 encrypt/decrypt take `[peerPubkey, text]`. */
|
|
530
|
+
function peerText(params) {
|
|
531
|
+
if (!Array.isArray(params) || typeof params[0] !== "string" || typeof params[1] !== "string") throw invalidParams("expected [peerPubkey, text]");
|
|
532
|
+
return {
|
|
533
|
+
peer: params[0],
|
|
534
|
+
text: params[1]
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
var Nip07Handler = class {
|
|
538
|
+
options;
|
|
539
|
+
constructor(options) {
|
|
540
|
+
this.options = options;
|
|
541
|
+
}
|
|
542
|
+
async handle(origin, request) {
|
|
543
|
+
const { connections } = this.options;
|
|
544
|
+
connections.checkOrigin(origin);
|
|
545
|
+
const identity = connections.activeIdentity();
|
|
546
|
+
if (identity === void 0) throw unauthorized();
|
|
547
|
+
const pubkey = connections.nostrAccount(origin);
|
|
548
|
+
switch (request.method) {
|
|
549
|
+
case "getPublicKey": return this.publicKey(origin, pubkey);
|
|
550
|
+
case "signEvent": return this.signEvent(origin, pubkey, identity, request.params);
|
|
551
|
+
case "nip04.encrypt":
|
|
552
|
+
case "nip04.decrypt":
|
|
553
|
+
case "nip44.encrypt":
|
|
554
|
+
case "nip44.decrypt": {
|
|
555
|
+
connections.authorize(origin, "nostr", request.method);
|
|
556
|
+
const { peer, text } = peerText(request.params);
|
|
557
|
+
return this.crypt(origin, identity, request.method, peer, text);
|
|
558
|
+
}
|
|
559
|
+
default: throw unauthorized();
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
async publicKey(origin, pubkey) {
|
|
563
|
+
const { connections } = this.options;
|
|
564
|
+
if (pubkey === void 0) await connections.request(origin, "connect", void 0, "nostr");
|
|
565
|
+
await connections.touch(origin);
|
|
566
|
+
const granted = connections.nostrAccount(origin);
|
|
567
|
+
if (granted === void 0) throw unauthorized();
|
|
568
|
+
return granted;
|
|
569
|
+
}
|
|
570
|
+
async signEvent(origin, pubkey, identity, params) {
|
|
571
|
+
const { connections, requests, signerFor } = this.options;
|
|
572
|
+
const session = connections.authorize(origin, "nostr", "signEvent");
|
|
573
|
+
const event = checkEvent(Array.isArray(params) ? params[0] : params);
|
|
574
|
+
if (event.pubkey !== void 0 && event.pubkey !== pubkey) throw invalidParams("event.pubkey does not match the active identity");
|
|
575
|
+
if (pubkey === void 0) throw unauthorized();
|
|
576
|
+
const policy = session.nostrPolicy ?? {
|
|
577
|
+
signing: "ask",
|
|
578
|
+
decrypt: false
|
|
579
|
+
};
|
|
580
|
+
const direct = policy.signing === "always" || typeof policy.signing === "object" && policy.signing.kinds.includes(event.kind);
|
|
581
|
+
const signing = {
|
|
582
|
+
...event,
|
|
583
|
+
pubkey
|
|
584
|
+
};
|
|
585
|
+
if (direct && !FORCED_CONFIRM_KINDS.has(event.kind)) {
|
|
586
|
+
await connections.touch(origin);
|
|
587
|
+
return signerFor(identity).signEvent(signing);
|
|
588
|
+
}
|
|
589
|
+
const pending = await requests.prepare({
|
|
590
|
+
method: "nostr-sign",
|
|
591
|
+
origin: {
|
|
592
|
+
kind: "browser",
|
|
593
|
+
origin
|
|
594
|
+
},
|
|
595
|
+
ref: identity,
|
|
596
|
+
event: signing
|
|
597
|
+
});
|
|
598
|
+
const outcome = await requests.outcome(pending.id);
|
|
599
|
+
if (outcome === void 0 || !("event" in outcome)) throw unauthorized();
|
|
600
|
+
return outcome.event;
|
|
601
|
+
}
|
|
602
|
+
async crypt(origin, identity, method, peer, text) {
|
|
603
|
+
const { connections, signerFor } = this.options;
|
|
604
|
+
if (method.endsWith(".decrypt") && connections.nostrPolicy(origin)?.decrypt !== true) throw unauthorized();
|
|
605
|
+
await connections.touch(origin);
|
|
606
|
+
const signer = signerFor(identity);
|
|
607
|
+
const fn = method === "nip04.encrypt" ? signer.nip04Encrypt : method === "nip04.decrypt" ? signer.nip04Decrypt : method === "nip44.encrypt" ? signer.nip44Encrypt : signer.nip44Decrypt;
|
|
608
|
+
if (fn === void 0) throw unauthorized();
|
|
609
|
+
return fn(peer, text);
|
|
610
|
+
}
|
|
611
|
+
};
|
|
612
|
+
// src/connect/solana.ts
|
|
613
|
+
const solanaId = (name) => {
|
|
614
|
+
const entry = SOLANA_NETWORKS.find((n) => n.name === name);
|
|
615
|
+
if (entry === void 0) throw new Error(`no solana network named ${name} in the registry`);
|
|
616
|
+
return entry.id;
|
|
617
|
+
};
|
|
618
|
+
/**
|
|
619
|
+
* The Wallet Standard short chain ids to the registry's CAIP-2 genesis-hash ids, derived from the
|
|
620
|
+
* solana network registry by name.
|
|
621
|
+
*/
|
|
622
|
+
const SOLANA_CHAIN_IDS = Object.freeze({
|
|
623
|
+
"solana:mainnet": solanaId("Solana"),
|
|
624
|
+
"solana:devnet": solanaId("Solana Devnet")
|
|
625
|
+
});
|
|
626
|
+
/**
|
|
627
|
+
* The Wallet Standard handler: `standard:connect` authorizes the `solana` scope, `solana:*` sign
|
|
628
|
+
* requests go through `solana-sign`, `solanaAccountsChanged` returns the re-pointed accounts the
|
|
629
|
+
* bridge forwards as `standard:events` `change` on a group switch.
|
|
630
|
+
*/
|
|
631
|
+
var SolanaWalletHandler = class {
|
|
632
|
+
options;
|
|
633
|
+
listeners = /* @__PURE__ */ new Set();
|
|
634
|
+
unsubscribe;
|
|
635
|
+
constructor(options) {
|
|
636
|
+
this.options = options;
|
|
637
|
+
}
|
|
638
|
+
/** `standard:events` `change` per origin — derived from changes to the sessions. */
|
|
639
|
+
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
|
+
};
|
|
662
|
+
}
|
|
663
|
+
async handle(origin, request) {
|
|
664
|
+
const checked = this.options.connections.checkOrigin(origin);
|
|
665
|
+
if (request.method === "standard:connect") return this.connect(checked, request);
|
|
666
|
+
if (request.method === "standard:disconnect") {
|
|
667
|
+
await this.options.connections.revoke(origin);
|
|
668
|
+
return {};
|
|
669
|
+
}
|
|
670
|
+
if (request.method === "solana:signTransaction") return this.signTransactions(checked, request, false);
|
|
671
|
+
if (request.method === "solana:signAndSendTransaction") return this.signTransactions(checked, request, true);
|
|
672
|
+
if (request.method === "solana:signMessage") return this.signMessage(checked, request);
|
|
673
|
+
throw invalidParams(`unsupported solana method ${request.method}`);
|
|
674
|
+
}
|
|
675
|
+
async connect(checked, request) {
|
|
676
|
+
const silent = (typeof request.params === "object" && request.params !== null ? request.params : {}).silent === true;
|
|
677
|
+
const network = this.options.solanaNetwork();
|
|
678
|
+
if (this.options.connections.solanaAccount(checked.origin, network) === void 0) {
|
|
679
|
+
if (silent) throw new ProviderError(4100, "the wallet is not connected");
|
|
680
|
+
await this.options.connections.request(checked.origin, "connect", void 0, "solana");
|
|
681
|
+
} else await this.options.connections.touch(checked.origin);
|
|
682
|
+
const group = this.options.activeGroup();
|
|
683
|
+
if (group === void 0) throw new ProviderError(4100, "no account group is selected");
|
|
684
|
+
const account = await this.options.solanaAccount(group, network);
|
|
685
|
+
return { accounts: [this.walletAccount(account, network)] };
|
|
686
|
+
}
|
|
687
|
+
walletAccount(account, network) {
|
|
688
|
+
return {
|
|
689
|
+
address: account.address,
|
|
690
|
+
publicKey: account.publicKey,
|
|
691
|
+
chains: [network],
|
|
692
|
+
features: SOLANA_METHODS.filter((m) => m.startsWith("solana:"))
|
|
693
|
+
};
|
|
694
|
+
}
|
|
695
|
+
async signTransactions(checked, request, send) {
|
|
696
|
+
const network = this.options.solanaNetwork();
|
|
697
|
+
this.options.connections.authorize(checked.origin, network, request.method);
|
|
698
|
+
const address = this.options.connections.solanaAccount(checked.origin, network);
|
|
699
|
+
if (address === void 0) throw new ProviderError(4100, "no solana account for this origin");
|
|
700
|
+
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
|
+
}
|
|
717
|
+
});
|
|
718
|
+
const outcome = await this.options.requests.outcome(pending.id);
|
|
719
|
+
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 };
|
|
721
|
+
}
|
|
722
|
+
async signMessage(checked, request) {
|
|
723
|
+
const network = this.options.solanaNetwork();
|
|
724
|
+
this.options.connections.authorize(checked.origin, network, "solana:signMessage");
|
|
725
|
+
const address = this.options.connections.solanaAccount(checked.origin, network);
|
|
726
|
+
if (address === void 0) throw new ProviderError(4100, "no solana account for this origin");
|
|
727
|
+
const message = messageOf(request.params);
|
|
728
|
+
const group = this.options.activeGroup();
|
|
729
|
+
if (group === void 0) throw new ProviderError(4100, "no account group is selected");
|
|
730
|
+
const pending = await this.options.requests.prepare({
|
|
731
|
+
method: "solana-sign",
|
|
732
|
+
origin: checked,
|
|
733
|
+
account: {
|
|
734
|
+
walletId: group.walletId,
|
|
735
|
+
groupIndex: group.groupIndex,
|
|
736
|
+
address
|
|
737
|
+
},
|
|
738
|
+
network,
|
|
739
|
+
request: {
|
|
740
|
+
kind: "message",
|
|
741
|
+
message
|
|
742
|
+
}
|
|
743
|
+
});
|
|
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
|
+
};
|
|
750
|
+
}
|
|
751
|
+
/** The `setActiveGroup` re-point: the solana session's new `WalletAccount[]` for `change`. */
|
|
752
|
+
async solanaAccountsChanged(_origin) {
|
|
753
|
+
const network = this.options.solanaNetwork();
|
|
754
|
+
const group = this.options.activeGroup();
|
|
755
|
+
if (group === void 0) return [];
|
|
756
|
+
const account = await this.options.solanaAccount(group, network);
|
|
757
|
+
return [this.walletAccount(account, network)];
|
|
758
|
+
}
|
|
759
|
+
};
|
|
760
|
+
const isBytesEnvelope = (v) => typeof v === "object" && v !== null && typeof v.__bytes === "string";
|
|
761
|
+
const transactionsOf = (params) => {
|
|
762
|
+
const raw = typeof params === "object" && params !== null ? params.transactions : void 0;
|
|
763
|
+
if (!Array.isArray(raw)) throw invalidParams("solana:signTransaction needs a transactions array");
|
|
764
|
+
return raw.map((tx) => {
|
|
765
|
+
if (tx instanceof Uint8Array) return tx;
|
|
766
|
+
if (typeof tx === "string" && /^[0-9a-fA-F]+$/.test(tx)) return hexToBytes(tx);
|
|
767
|
+
if (isBytesEnvelope(tx)) return hexToBytes(tx.__bytes);
|
|
768
|
+
throw invalidParams("each transaction must be Uint8Array bytes or hex");
|
|
769
|
+
});
|
|
770
|
+
};
|
|
771
|
+
const messageOf = (params) => {
|
|
772
|
+
const message = typeof params === "object" && params !== null ? params.message : void 0;
|
|
773
|
+
if (message instanceof Uint8Array) return message;
|
|
774
|
+
if (typeof message === "string" && /^[0-9a-fA-F]+$/.test(message)) return hexToBytes(message);
|
|
775
|
+
if (isBytesEnvelope(message)) return hexToBytes(message.__bytes);
|
|
776
|
+
throw invalidParams("solana:signMessage needs Uint8Array bytes or hex");
|
|
777
|
+
};
|
|
778
|
+
const byOrigin = (sessions) => new Map(Object.values(sessions).map((s) => [s.origin.origin, s]));
|
|
779
|
+
const solanaAccounts = (session) => Object.entries(session.scopes).filter(([network]) => network.startsWith("solana:")).flatMap(([, scope]) => scope.accounts.map((a) => a.slice(a.lastIndexOf(":") + 1)));
|
|
780
|
+
function diffSessions(before, after) {
|
|
781
|
+
const events = [];
|
|
782
|
+
const prev = byOrigin(before);
|
|
783
|
+
const next = byOrigin(after);
|
|
784
|
+
for (const [origin, session] of prev) {
|
|
785
|
+
const now = next.get(origin);
|
|
786
|
+
if (solanaAccounts(session).join(",") !== (now === void 0 ? "" : solanaAccounts(now).join(","))) events.push({
|
|
787
|
+
origin,
|
|
788
|
+
accounts: now === void 0 ? [] : solanaAccounts(now)
|
|
789
|
+
});
|
|
790
|
+
}
|
|
791
|
+
for (const [origin, session] of next) if (!prev.has(origin)) {
|
|
792
|
+
const accounts = solanaAccounts(session);
|
|
793
|
+
if (accounts.length > 0) events.push({
|
|
794
|
+
origin,
|
|
795
|
+
accounts
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
return events;
|
|
799
|
+
}
|
|
800
|
+
// src/payments/parse.ts
|
|
801
|
+
/** Invoices with less than this much life left are treated as already expired. */
|
|
802
|
+
const BOLT11_EXPIRY_GRACE_MS = 6e4;
|
|
803
|
+
const invalid = (reason) => ({
|
|
804
|
+
kind: "invalid",
|
|
805
|
+
reason
|
|
806
|
+
});
|
|
807
|
+
/** BTC decimal `amount` → sats. At most 8 decimal places; must fit a safe integer. */
|
|
808
|
+
function btcAmountSats(text) {
|
|
809
|
+
const match = /^(\d+)(?:\.(\d{1,8}))?$/.exec(text);
|
|
810
|
+
if (match === null) return;
|
|
811
|
+
const [, whole] = match;
|
|
812
|
+
if (whole === void 0) return;
|
|
813
|
+
const sats = BigInt(whole) * 100000000n + BigInt((match[2] ?? "").padEnd(8, "0") || "0");
|
|
814
|
+
return sats <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(sats) : void 0;
|
|
815
|
+
}
|
|
816
|
+
/**
|
|
817
|
+
* BOLT11 → fields, network- and expiry-checked. `undefined` = not a bolt11 string; `"network"` /
|
|
818
|
+
* `"expired"` / `"malformed"` are the failure modes.
|
|
819
|
+
*/
|
|
820
|
+
function bolt11Fields(text, options) {
|
|
821
|
+
let decoded;
|
|
822
|
+
try {
|
|
823
|
+
decoded = decodeBolt11(text);
|
|
824
|
+
} catch {
|
|
825
|
+
return;
|
|
826
|
+
}
|
|
827
|
+
const network = decoded.network === "mainnet" ? "mainnet" : decoded.network === "regtest" ? "regtest" : void 0;
|
|
828
|
+
if (network === void 0) return "network";
|
|
829
|
+
if (network !== options.network) return "network";
|
|
830
|
+
const expiresAt = (decoded.timestamp + decoded.expirySeconds) * 1e3;
|
|
831
|
+
if (expiresAt <= options.now + BOLT11_EXPIRY_GRACE_MS) return "expired";
|
|
832
|
+
return {
|
|
833
|
+
...decoded.amountMsat === void 0 ? {} : { amountSats: Math.ceil(Number(decoded.amountMsat) / 1e3) },
|
|
834
|
+
paymentHash: bytesToHex(decoded.paymentHash),
|
|
835
|
+
...decoded.description === void 0 ? {} : { description: decoded.description },
|
|
836
|
+
expiresAt
|
|
837
|
+
};
|
|
838
|
+
}
|
|
839
|
+
/** Spark address or sats/token invoice → options. `null` means not a spark input. */
|
|
840
|
+
function sparkOptions(text, options) {
|
|
841
|
+
let decoded;
|
|
842
|
+
try {
|
|
843
|
+
decoded = decodeSparkAddress(text);
|
|
844
|
+
} catch {
|
|
845
|
+
return;
|
|
846
|
+
}
|
|
847
|
+
if (decoded.network !== options.network) return "network";
|
|
848
|
+
if (decoded.invoice === void 0) return [{
|
|
849
|
+
kind: "spark",
|
|
850
|
+
address: text
|
|
851
|
+
}];
|
|
852
|
+
if (decoded.invoice.expiresAt !== void 0 && decoded.invoice.expiresAt <= options.now) return "expired";
|
|
853
|
+
if (decoded.invoice.payment?.type === "tokens") return "token";
|
|
854
|
+
let parsed;
|
|
855
|
+
try {
|
|
856
|
+
parsed = parseSparkInvoice(text, {
|
|
857
|
+
network: options.network,
|
|
858
|
+
now: options.now
|
|
859
|
+
});
|
|
860
|
+
} catch {
|
|
861
|
+
return "malformed";
|
|
862
|
+
}
|
|
863
|
+
const { payment } = parsed.fields;
|
|
864
|
+
return [{
|
|
865
|
+
kind: "spark-invoice",
|
|
866
|
+
invoice: text,
|
|
867
|
+
...payment?.type === "sats" && payment.amount !== void 0 ? { amountSats: payment.amount } : {},
|
|
868
|
+
...parsed.fields.memo === void 0 ? {} : { memo: parsed.fields.memo },
|
|
869
|
+
...parsed.fields.expiresAt === void 0 ? {} : { expiresAt: parsed.fields.expiresAt }
|
|
870
|
+
}];
|
|
871
|
+
}
|
|
872
|
+
/** Does `address` decode under the other network? Used only to classify a rejection. */
|
|
873
|
+
function decodesOnOtherNetwork(address, options) {
|
|
874
|
+
try {
|
|
875
|
+
bitcoinAddressScript(address, options.network === "mainnet" ? "regtest" : "mainnet");
|
|
876
|
+
return true;
|
|
877
|
+
} catch {
|
|
878
|
+
return false;
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
/** BIP-21 URI → request. Only the `spark=` and `lightning=` payment methods are supported. */
|
|
882
|
+
function bip21Parse(text, options) {
|
|
883
|
+
const q = text.indexOf("?");
|
|
884
|
+
const address = text.slice(8, q === -1 ? void 0 : q);
|
|
885
|
+
const params = /* @__PURE__ */ new Map();
|
|
886
|
+
if (q !== -1) for (const pair of text.slice(q + 1).split("&")) {
|
|
887
|
+
const eq = pair.indexOf("=");
|
|
888
|
+
if (eq === -1) return invalid("malformed");
|
|
889
|
+
let key;
|
|
890
|
+
let value;
|
|
891
|
+
try {
|
|
892
|
+
key = decodeURIComponent(pair.slice(0, eq)).toLowerCase();
|
|
893
|
+
value = decodeURIComponent(pair.slice(eq + 1));
|
|
894
|
+
} catch {
|
|
895
|
+
return invalid("malformed");
|
|
896
|
+
}
|
|
897
|
+
if (params.has(key)) return invalid("malformed");
|
|
898
|
+
if (key.startsWith("req-") && !BIP21_KNOWN_REQ_PARAMS.has(key)) return invalid("malformed");
|
|
899
|
+
params.set(key, value);
|
|
900
|
+
}
|
|
901
|
+
const options_ = [];
|
|
902
|
+
let declaredSats;
|
|
903
|
+
const spark = params.get("spark");
|
|
904
|
+
if (spark !== void 0) {
|
|
905
|
+
const parsed = sparkOptions(spark, options);
|
|
906
|
+
if (parsed === void 0 || parsed === "malformed") return invalid("malformed");
|
|
907
|
+
if (parsed === "token") return {
|
|
908
|
+
kind: "unsupported",
|
|
909
|
+
format: "spark-token-invoice"
|
|
910
|
+
};
|
|
911
|
+
if (parsed === "network" || parsed === "expired") return invalid(parsed);
|
|
912
|
+
options_.push(...parsed);
|
|
913
|
+
const sats = parsed.find((o) => o.kind === "spark-invoice")?.amountSats;
|
|
914
|
+
if (sats !== void 0) {
|
|
915
|
+
if (declaredSats !== void 0 && declaredSats !== sats) return invalid("amount-mismatch");
|
|
916
|
+
declaredSats = sats;
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
const lightning = params.get("lightning");
|
|
920
|
+
if (lightning !== void 0) {
|
|
921
|
+
const parsed = bolt11Fields(lightning, options);
|
|
922
|
+
if (parsed === void 0 || parsed === "malformed") return invalid("malformed");
|
|
923
|
+
if (parsed === "network" || parsed === "expired") return invalid(parsed);
|
|
924
|
+
options_.push({
|
|
925
|
+
kind: "lightning",
|
|
926
|
+
invoice: lightning,
|
|
927
|
+
...parsed.amountSats === void 0 ? {} : { amountSats: parsed.amountSats },
|
|
928
|
+
paymentHash: parsed.paymentHash,
|
|
929
|
+
...parsed.description === void 0 ? {} : { description: parsed.description },
|
|
930
|
+
expiresAt: parsed.expiresAt
|
|
931
|
+
});
|
|
932
|
+
if (parsed.amountSats !== void 0) {
|
|
933
|
+
if (declaredSats !== void 0 && declaredSats !== parsed.amountSats) return invalid("amount-mismatch");
|
|
934
|
+
declaredSats = parsed.amountSats;
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
if (address.length > 0) {
|
|
938
|
+
try {
|
|
939
|
+
bitcoinAddressScript(address, options.network);
|
|
940
|
+
} catch {
|
|
941
|
+
return invalid(decodesOnOtherNetwork(address, options) ? "network" : "malformed");
|
|
942
|
+
}
|
|
943
|
+
options_.push({
|
|
944
|
+
kind: "bitcoin",
|
|
945
|
+
address
|
|
946
|
+
});
|
|
947
|
+
}
|
|
948
|
+
const declaredAmount = params.get("amount");
|
|
949
|
+
if (declaredAmount !== void 0) {
|
|
950
|
+
const sats = btcAmountSats(declaredAmount);
|
|
951
|
+
if (sats === void 0) return invalid("malformed");
|
|
952
|
+
if (declaredSats !== void 0 && declaredSats !== sats) return invalid("amount-mismatch");
|
|
953
|
+
declaredSats = sats;
|
|
954
|
+
}
|
|
955
|
+
if (options_.length === 0) {
|
|
956
|
+
if (params.has("lno")) return {
|
|
957
|
+
kind: "unsupported",
|
|
958
|
+
format: "bolt12"
|
|
959
|
+
};
|
|
960
|
+
if (params.has("sp")) return {
|
|
961
|
+
kind: "unsupported",
|
|
962
|
+
format: "silent-payment"
|
|
963
|
+
};
|
|
964
|
+
return invalid("malformed");
|
|
965
|
+
}
|
|
966
|
+
return {
|
|
967
|
+
kind: "request",
|
|
968
|
+
request: {
|
|
969
|
+
options: options_,
|
|
970
|
+
...declaredSats === void 0 ? {} : { amountSats: declaredSats },
|
|
971
|
+
...params.get("label") === void 0 ? {} : { label: params.get("label") ?? "" },
|
|
972
|
+
...params.get("message") === void 0 ? {} : { message: params.get("message") ?? "" }
|
|
973
|
+
}
|
|
974
|
+
};
|
|
975
|
+
}
|
|
976
|
+
const BIP21_KNOWN_REQ_PARAMS = /* @__PURE__ */ new Set([
|
|
977
|
+
"req-amount",
|
|
978
|
+
"req-label",
|
|
979
|
+
"req-message"
|
|
980
|
+
]);
|
|
981
|
+
/** `input` → PaymentParse. Never throws: every failure is a structured result. */
|
|
982
|
+
function parsePayment(input, options) {
|
|
983
|
+
try {
|
|
984
|
+
const text = input.trim();
|
|
985
|
+
if (/^nostr\+walletconnect:/i.test(text)) return {
|
|
986
|
+
kind: "unsupported",
|
|
987
|
+
format: "nostr-wallet-connect"
|
|
988
|
+
};
|
|
989
|
+
const stripped = text.toLowerCase().startsWith("lightning:") ? text.slice(10) : text;
|
|
990
|
+
if (/^bitcoin:/i.test(stripped)) return bip21Parse(`bitcoin:${stripped.slice(stripped.indexOf(":") + 1)}`, options);
|
|
991
|
+
const bolt11 = bolt11Fields(stripped, options);
|
|
992
|
+
if (bolt11 === "network" || bolt11 === "expired" || bolt11 === "malformed") return invalid(bolt11);
|
|
993
|
+
if (bolt11 !== void 0) return {
|
|
994
|
+
kind: "request",
|
|
995
|
+
request: {
|
|
996
|
+
options: [{
|
|
997
|
+
kind: "lightning",
|
|
998
|
+
invoice: stripped,
|
|
999
|
+
...bolt11.amountSats === void 0 ? {} : { amountSats: bolt11.amountSats },
|
|
1000
|
+
paymentHash: bolt11.paymentHash,
|
|
1001
|
+
...bolt11.description === void 0 ? {} : { description: bolt11.description },
|
|
1002
|
+
expiresAt: bolt11.expiresAt
|
|
1003
|
+
}],
|
|
1004
|
+
...bolt11.amountSats === void 0 ? {} : { amountSats: bolt11.amountSats }
|
|
1005
|
+
}
|
|
1006
|
+
};
|
|
1007
|
+
const spark = sparkOptions(stripped, options);
|
|
1008
|
+
if (spark === "token") return {
|
|
1009
|
+
kind: "unsupported",
|
|
1010
|
+
format: "spark-token-invoice"
|
|
1011
|
+
};
|
|
1012
|
+
if (spark === "network" || spark === "expired" || spark === "malformed") return invalid(spark);
|
|
1013
|
+
if (spark !== void 0) return {
|
|
1014
|
+
kind: "request",
|
|
1015
|
+
request: { options: spark }
|
|
1016
|
+
};
|
|
1017
|
+
if (/^(lnurlp|lnurlw):/i.test(stripped)) {
|
|
1018
|
+
const rest = stripped.slice(stripped.indexOf("://") + 3);
|
|
1019
|
+
const url = `${(rest.split(/[/?#]/, 1)[0] ?? "").toLowerCase().endsWith(".onion") ? "http" : "https"}://${rest}`;
|
|
1020
|
+
if (new URL(url).searchParams.get("tag") === "login") return {
|
|
1021
|
+
kind: "unsupported",
|
|
1022
|
+
format: "lnurl-auth"
|
|
1023
|
+
};
|
|
1024
|
+
return {
|
|
1025
|
+
kind: "lnurl",
|
|
1026
|
+
url
|
|
1027
|
+
};
|
|
1028
|
+
}
|
|
1029
|
+
if (/^keyauth:/i.test(stripped)) return {
|
|
1030
|
+
kind: "unsupported",
|
|
1031
|
+
format: "lnurl-auth"
|
|
1032
|
+
};
|
|
1033
|
+
if (!stripped.includes(":") && stripped.includes("@")) return {
|
|
1034
|
+
kind: "lnurl",
|
|
1035
|
+
url: lightningAddressUrl(stripped),
|
|
1036
|
+
address: stripped
|
|
1037
|
+
};
|
|
1038
|
+
if (/^lno1[02-9ac-hj-np-z]+$/i.test(stripped)) return {
|
|
1039
|
+
kind: "unsupported",
|
|
1040
|
+
format: "bolt12"
|
|
1041
|
+
};
|
|
1042
|
+
try {
|
|
1043
|
+
const url = decodeLnurl(stripped);
|
|
1044
|
+
if (new URL(url).searchParams.get("tag") === "login") return {
|
|
1045
|
+
kind: "unsupported",
|
|
1046
|
+
format: "lnurl-auth"
|
|
1047
|
+
};
|
|
1048
|
+
return {
|
|
1049
|
+
kind: "lnurl",
|
|
1050
|
+
url
|
|
1051
|
+
};
|
|
1052
|
+
} catch {}
|
|
1053
|
+
try {
|
|
1054
|
+
bitcoinAddressScript(stripped, options.network);
|
|
1055
|
+
return {
|
|
1056
|
+
kind: "request",
|
|
1057
|
+
request: { options: [{
|
|
1058
|
+
kind: "bitcoin",
|
|
1059
|
+
address: stripped
|
|
1060
|
+
}] }
|
|
1061
|
+
};
|
|
1062
|
+
} catch {
|
|
1063
|
+
if (decodesOnOtherNetwork(stripped, options)) return invalid("network");
|
|
1064
|
+
}
|
|
1065
|
+
return { kind: "unrecognized" };
|
|
1066
|
+
} catch {
|
|
1067
|
+
return invalid("malformed");
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
// src/connect/webln.ts
|
|
1071
|
+
/**
|
|
1072
|
+
* The WebLN (`window.webln`) handler — the bridge routes `provider: "webln"` messages here.
|
|
1073
|
+
* `enable` asks for a `lightning` connection approval when the origin is not yet authorized;
|
|
1074
|
+
* `sendPayment` and `lnurl` pay through the request pipeline's `pay` (a funds request with a
|
|
1075
|
+
* factor) and then poll `paymentStatus` for the settled preimage; `makeInvoice` goes through the
|
|
1076
|
+
* factor-free `webln-invoice`; `getBalance` additionally needs the session's
|
|
1077
|
+
* `lightningPolicy.balance`; `getInfo` exposes only the configured alias and methods.
|
|
1078
|
+
*/
|
|
1079
|
+
const MAX_MEMO_LENGTH = 640;
|
|
1080
|
+
const PREIMAGE_POLL_START_MS = 1e3;
|
|
1081
|
+
const PREIMAGE_POLL_MAX_MS = 8e3;
|
|
1082
|
+
const PREIMAGE_POLL_BUDGET_MS = 6e4;
|
|
1083
|
+
const isObject = (v) => typeof v === "object" && v !== null;
|
|
1084
|
+
const checkString = (value, name) => {
|
|
1085
|
+
if (typeof value !== "string" || value === "") throw invalidParams(`${name} must be a non-empty string`);
|
|
1086
|
+
return value;
|
|
1087
|
+
};
|
|
1088
|
+
const checkAmount = (value, name) => {
|
|
1089
|
+
if (value === void 0) return;
|
|
1090
|
+
const n = typeof value === "string" ? Number(value) : value;
|
|
1091
|
+
if (typeof n !== "number" || !Number.isSafeInteger(n) || n < 0) throw invalidParams(`${name} must be a non-negative safe integer`);
|
|
1092
|
+
return n;
|
|
1093
|
+
};
|
|
1094
|
+
const checkInvoiceArgs = (params) => {
|
|
1095
|
+
const args = isObject(params) ? params : {};
|
|
1096
|
+
const amount = checkAmount(args["amount"], "makeInvoice amount") ?? checkAmount(args["defaultAmount"], "makeInvoice defaultAmount");
|
|
1097
|
+
checkAmount(args["minimumAmount"], "makeInvoice minimumAmount");
|
|
1098
|
+
checkAmount(args["maximumAmount"], "makeInvoice maximumAmount");
|
|
1099
|
+
if (amount === void 0) throw invalidParams("makeInvoice needs an amount or a defaultAmount");
|
|
1100
|
+
const memo = args["defaultMemo"];
|
|
1101
|
+
if (memo !== void 0 && (typeof memo !== "string" || memo.length > MAX_MEMO_LENGTH)) throw invalidParams("makeInvoice defaultMemo must be a string at most 640 characters");
|
|
1102
|
+
return {
|
|
1103
|
+
amountSats: amount,
|
|
1104
|
+
...typeof memo === "string" ? { memo } : {}
|
|
1105
|
+
};
|
|
1106
|
+
};
|
|
1107
|
+
const checkMaxFee = (fn, amountSats) => {
|
|
1108
|
+
const maxFee = fn(amountSats);
|
|
1109
|
+
if (!Number.isSafeInteger(maxFee) || maxFee < 0) throw new ProviderError(-32603, "invalid lightning fee cap");
|
|
1110
|
+
return maxFee;
|
|
1111
|
+
};
|
|
1112
|
+
var WeblnHandler = class {
|
|
1113
|
+
options;
|
|
1114
|
+
constructor(options) {
|
|
1115
|
+
this.options = options;
|
|
1116
|
+
}
|
|
1117
|
+
ref() {
|
|
1118
|
+
const ref = this.options.sparkAccount();
|
|
1119
|
+
if (ref === void 0) throw unauthorized("no active group");
|
|
1120
|
+
return ref;
|
|
1121
|
+
}
|
|
1122
|
+
async handle(origin, request) {
|
|
1123
|
+
if (request.method === "enable") {
|
|
1124
|
+
if (this.options.connections.lightningPolicy(origin) === void 0) await this.options.connections.request(origin, "connect", void 0, "lightning");
|
|
1125
|
+
await this.options.connections.touch(origin);
|
|
1126
|
+
return true;
|
|
1127
|
+
}
|
|
1128
|
+
this.options.connections.authorize(origin, "lightning", request.method);
|
|
1129
|
+
await this.options.connections.touch(origin);
|
|
1130
|
+
const ref = this.ref();
|
|
1131
|
+
switch (request.method) {
|
|
1132
|
+
case "getInfo": return {
|
|
1133
|
+
node: { alias: this.options.alias },
|
|
1134
|
+
methods: [...LIGHTNING_METHODS]
|
|
1135
|
+
};
|
|
1136
|
+
case "sendPayment": return this.sendPayment(origin, ref, request.params);
|
|
1137
|
+
case "makeInvoice": return this.makeInvoice(origin, ref, request.params);
|
|
1138
|
+
case "lnurl": return this.lnurl(origin, ref, request.params);
|
|
1139
|
+
case "getBalance": return this.getBalance(origin);
|
|
1140
|
+
default: throw unsupportedMethod(request.method);
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
async sendPayment(origin, ref, params) {
|
|
1144
|
+
const invoice = checkString(params, "sendPayment invoice");
|
|
1145
|
+
const option = this.lightningOption(ref, invoice);
|
|
1146
|
+
if (option.amountSats === void 0) throw invalidParams("sendPayment needs a fixed-amount invoice");
|
|
1147
|
+
const maxFeeSats = checkMaxFee(this.options.lightningMaxFee, option.amountSats);
|
|
1148
|
+
const pending = await this.options.requests.prepare({
|
|
1149
|
+
method: "pay",
|
|
1150
|
+
origin: {
|
|
1151
|
+
kind: "browser",
|
|
1152
|
+
origin
|
|
1153
|
+
},
|
|
1154
|
+
account: ref,
|
|
1155
|
+
option,
|
|
1156
|
+
maxFeeSats
|
|
1157
|
+
});
|
|
1158
|
+
const outcome = await this.options.requests.outcome(pending.id);
|
|
1159
|
+
if (!("kind" in outcome) || outcome.kind !== "lightning") throw new ProviderError(-32603, "the lightning payment settled unexpectedly");
|
|
1160
|
+
return this.preimage(ref, outcome.payment);
|
|
1161
|
+
}
|
|
1162
|
+
async makeInvoice(origin, ref, params) {
|
|
1163
|
+
const { amountSats, memo } = checkInvoiceArgs(params);
|
|
1164
|
+
const pending = await this.options.requests.prepare({
|
|
1165
|
+
method: "webln-invoice",
|
|
1166
|
+
origin: {
|
|
1167
|
+
kind: "browser",
|
|
1168
|
+
origin
|
|
1169
|
+
},
|
|
1170
|
+
ref,
|
|
1171
|
+
amountSats,
|
|
1172
|
+
...memo === void 0 ? {} : { memo }
|
|
1173
|
+
});
|
|
1174
|
+
const outcome = await this.options.requests.outcome(pending.id);
|
|
1175
|
+
if (!("kind" in outcome) || outcome.kind !== "lightning.invoice") throw new ProviderError(-32603, "the invoice request settled unexpectedly");
|
|
1176
|
+
return { paymentRequest: outcome.paymentRequest };
|
|
1177
|
+
}
|
|
1178
|
+
async lnurl(origin, ref, params) {
|
|
1179
|
+
const parsed = parsePayment(checkString(params, "lnurl"), {
|
|
1180
|
+
network: ref.network,
|
|
1181
|
+
now: Date.now()
|
|
1182
|
+
});
|
|
1183
|
+
if (parsed.kind !== "request") throw invalidParams("lnurl is not an LNURL-pay request");
|
|
1184
|
+
if (parsed.request.options.some((o) => o.kind === "lnurl-withdraw")) throw unsupportedMethod("lnurl-withdraw");
|
|
1185
|
+
const option = parsed.request.options.find((o) => o.kind === "lnurl-pay");
|
|
1186
|
+
if (option === void 0 || option.kind !== "lnurl-pay") throw invalidParams("lnurl is not an LNURL-pay request");
|
|
1187
|
+
const amountSats = Math.ceil(option.request.minSendableMsat / 1e3);
|
|
1188
|
+
const maxFeeSats = checkMaxFee(this.options.lightningMaxFee, amountSats);
|
|
1189
|
+
const pending = await this.options.requests.prepare({
|
|
1190
|
+
method: "pay",
|
|
1191
|
+
origin: {
|
|
1192
|
+
kind: "browser",
|
|
1193
|
+
origin
|
|
1194
|
+
},
|
|
1195
|
+
account: ref,
|
|
1196
|
+
option,
|
|
1197
|
+
amountSats,
|
|
1198
|
+
maxFeeSats,
|
|
1199
|
+
amountFromServiceMinimum: true
|
|
1200
|
+
});
|
|
1201
|
+
const outcome = await this.options.requests.outcome(pending.id);
|
|
1202
|
+
if (!("kind" in outcome) || outcome.kind !== "lightning") throw new ProviderError(-32603, "the lnurl payment settled unexpectedly");
|
|
1203
|
+
return this.preimage(ref, outcome.payment);
|
|
1204
|
+
}
|
|
1205
|
+
async preimage(ref, payment) {
|
|
1206
|
+
let delay = PREIMAGE_POLL_START_MS;
|
|
1207
|
+
let waited = 0;
|
|
1208
|
+
while (true) {
|
|
1209
|
+
const status = await this.options.spark.paymentStatus(ref, {
|
|
1210
|
+
requestId: payment.requestId,
|
|
1211
|
+
paymentHash: payment.paymentHash
|
|
1212
|
+
});
|
|
1213
|
+
if (status.outcome === "failed" || status.outcome === "returned") throw new ProviderError(-32603, "payment failed");
|
|
1214
|
+
if (status.outcome === "succeeded") {
|
|
1215
|
+
if (status.preimage === void 0) throw new ProviderError(-32603, "the lightning payment settled without a preimage");
|
|
1216
|
+
return { preimage: bytesToHex(status.preimage) };
|
|
1217
|
+
}
|
|
1218
|
+
if (waited >= PREIMAGE_POLL_BUDGET_MS) throw new ProviderError(-32603, "the lightning payment did not settle in time");
|
|
1219
|
+
const step = Math.min(delay, PREIMAGE_POLL_MAX_MS);
|
|
1220
|
+
await this.options.sleep(step);
|
|
1221
|
+
waited += step;
|
|
1222
|
+
delay *= 2;
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
lightningOption(ref, invoice) {
|
|
1226
|
+
const parsed = parsePayment(invoice, {
|
|
1227
|
+
network: ref.network,
|
|
1228
|
+
now: Date.now()
|
|
1229
|
+
});
|
|
1230
|
+
if (parsed.kind !== "request") throw invalidParams("sendPayment invoice is not a BOLT11 invoice");
|
|
1231
|
+
const option = parsed.request.options.find((o) => o.kind === "lightning");
|
|
1232
|
+
if (option === void 0 || option.kind !== "lightning") throw invalidParams("sendPayment invoice is not a BOLT11 invoice");
|
|
1233
|
+
return option;
|
|
1234
|
+
}
|
|
1235
|
+
getBalance(origin) {
|
|
1236
|
+
if (this.options.connections.lightningPolicy(origin)?.balance !== true) throw unauthorized("balance access is not granted");
|
|
1237
|
+
const balance = this.options.spark.accountBalance(this.ref());
|
|
1238
|
+
if (balance === void 0) throw new ProviderError(-32603, "no cached balance for the active spark account");
|
|
1239
|
+
return {
|
|
1240
|
+
balance,
|
|
1241
|
+
currency: "sats"
|
|
1242
|
+
};
|
|
1243
|
+
}
|
|
1244
|
+
};
|
|
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 };
|
|
1246
|
+
|
|
1247
|
+
//# sourceMappingURL=webln-CHjBMRcv.mjs.map
|