@qntx/wallet-engine 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.
- package/dist/connect.d.mts +3 -2
- package/dist/connect.mjs +16 -5
- package/dist/connect.mjs.map +1 -1
- package/dist/{errors-CP1G6KCc.d.mts → errors-Bglz0VYn.d.mts} +518 -318
- package/dist/gateway-contract.d.mts +1 -1
- package/dist/gateway-contract.mjs +2 -2
- package/dist/index.d.mts +37 -4
- package/dist/index.mjs +4123 -5077
- package/dist/index.mjs.map +1 -1
- package/dist/{registry-LcFSPrE1.d.mts → registry-Deo5WQe1.d.mts} +3 -1
- package/dist/{registry-CHiAn88k.mjs → registry-wYrcuFNc.mjs} +8 -7
- package/dist/registry-wYrcuFNc.mjs.map +1 -0
- package/dist/webln-BGKm12wd.mjs +3638 -0
- package/dist/webln-BGKm12wd.mjs.map +1 -0
- package/package.json +9 -6
- package/dist/registry-CHiAn88k.mjs.map +0 -1
- package/dist/webln-DHYqdaDU.mjs +0 -1437
- package/dist/webln-DHYqdaDU.mjs.map +0 -1
|
@@ -0,0 +1,3638 @@
|
|
|
1
|
+
import { r as SOLANA_NETWORKS, t as BITCOIN_NETWORKS$1 } from "./registry-wYrcuFNc.mjs";
|
|
2
|
+
import { createStore } from "zustand/vanilla";
|
|
3
|
+
import { bytesToHex, hexToBytes } from "@noble/hashes/utils.js";
|
|
4
|
+
import { ChainError, parseSignIn } from "@qntx/wallet-chains";
|
|
5
|
+
import { WalletError } from "@qntx/wallet";
|
|
6
|
+
import { BITCOIN_NETWORKS, decodeBitcoinPsbt } from "@qntx/wallet-chains/bitcoin";
|
|
7
|
+
import { SAFE_MULTISEND_CALL_ONLY, checksumEvmAddress, evmTokenTable, isEvmAddress, lookupEvmToken } from "@qntx/wallet-chains/evm";
|
|
8
|
+
import { SOLANA_NATIVE_ASSET, decodeSolana, isSolanaAddress, normalizeSolana } from "@qntx/wallet-chains/solana";
|
|
9
|
+
import { Address, Transaction } from "@scure/btc-signer";
|
|
10
|
+
import { SparkInputError, bitcoinAddressScript, decodeBolt11, decodeSparkAddress, encodeSparkAddress, parseSparkInvoice } from "@qntx/spark";
|
|
11
|
+
import { decodeLnurl, encodeLnurl, lightningAddressUrl, requestInvoice, resolveLnurl, submitWithdraw } from "@qntx/spark/lnurl";
|
|
12
|
+
import { signedMatchesUnsigned } from "@qntx/nostr";
|
|
13
|
+
import { makeZapRequest } from "@qntx/nostr/nips/nip57";
|
|
14
|
+
import { SiwxError, checkOrigin, createMessage, parseTimestamp } from "@qntx/siwx";
|
|
15
|
+
import { base58, base64, hex } from "@scure/base";
|
|
16
|
+
import { p2wpkh } from "@scure/btc-signer/payment.js";
|
|
17
|
+
import { selectUTXO } from "@scure/btc-signer/utxo.js";
|
|
18
|
+
// src/controller.ts
|
|
19
|
+
/**
|
|
20
|
+
* Controller base: a zustand vanilla store plus lifecycle. `update` applies a recipe that must
|
|
21
|
+
* return a NEW state object; returning the same reference is a no-op (no set, no notification).
|
|
22
|
+
* Persistence and migrations layer on later — this package carries only what its first user needs.
|
|
23
|
+
*/
|
|
24
|
+
var Controller = class {
|
|
25
|
+
name;
|
|
26
|
+
store;
|
|
27
|
+
constructor(options) {
|
|
28
|
+
this.name = options.name;
|
|
29
|
+
this.store = createStore(options.defaultState);
|
|
30
|
+
}
|
|
31
|
+
getState() {
|
|
32
|
+
return this.store.getState();
|
|
33
|
+
}
|
|
34
|
+
update(recipe) {
|
|
35
|
+
this.store.setState((state) => recipe(state));
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
// src/errors.ts
|
|
39
|
+
/** Typed engine errors: store codes are `closed` and `integrity` (decrypt or bind failure). */
|
|
40
|
+
var EngineStoreError = class extends Error {
|
|
41
|
+
code;
|
|
42
|
+
constructor(code, message) {
|
|
43
|
+
super(message);
|
|
44
|
+
this.name = "EngineStoreError";
|
|
45
|
+
this.code = code;
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
const errorMessage = (error) => error instanceof Error ? error.message : String(error);
|
|
49
|
+
// src/phishing/status.ts
|
|
50
|
+
const PHISHING_BLOCKED_MESSAGE = "origin is on the phishing list";
|
|
51
|
+
// src/connect/errors.ts
|
|
52
|
+
/** EIP-1193 / EIP-1474 / EIP-3326 error: `code` is what the page's promise rejects with. */
|
|
53
|
+
var ProviderError = class extends Error {
|
|
54
|
+
code;
|
|
55
|
+
constructor(code, message) {
|
|
56
|
+
super(message);
|
|
57
|
+
this.name = "ProviderError";
|
|
58
|
+
this.code = code;
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
const userRejectedRequest = (message = "user rejected the request") => new ProviderError(4001, message);
|
|
62
|
+
const unauthorized = (message = "not authorized") => new ProviderError(4100, message);
|
|
63
|
+
const unsupportedMethod = (method) => new ProviderError(4200, `${method} is not supported`);
|
|
64
|
+
const unrecognizedChain = (message = "unrecognized chain") => new ProviderError(4902, message);
|
|
65
|
+
const invalidParams = (message) => new ProviderError(-32602, message);
|
|
66
|
+
const requestPending = (message) => new ProviderError(-32002, message);
|
|
67
|
+
const internalError = (message) => new ProviderError(-32603, message);
|
|
68
|
+
/** A pending connection request that nobody answers is rejected after this long. */
|
|
69
|
+
const CONNECTION_REQUEST_TTL_MS = 6e5;
|
|
70
|
+
const COLLECTION$1 = "connections";
|
|
71
|
+
/** `lastUsedAt` is rewritten at most this often. */
|
|
72
|
+
const TOUCH_INTERVAL_MS = 6e4;
|
|
73
|
+
/** Granted for every network a session covers. */
|
|
74
|
+
const SESSION_METHODS = [
|
|
75
|
+
"eth_sendTransaction",
|
|
76
|
+
"personal_sign",
|
|
77
|
+
"eth_signTypedData_v4",
|
|
78
|
+
"wallet_watchAsset"
|
|
79
|
+
];
|
|
80
|
+
const SESSION_NOTIFICATIONS = ["accountsChanged", "chainChanged"];
|
|
81
|
+
/** The `nostr` namespace scope's granted methods — the NIP-07 surface. */
|
|
82
|
+
const NOSTR_METHODS = [
|
|
83
|
+
"getPublicKey",
|
|
84
|
+
"signEvent",
|
|
85
|
+
"nip04.encrypt",
|
|
86
|
+
"nip04.decrypt",
|
|
87
|
+
"nip44.encrypt",
|
|
88
|
+
"nip44.decrypt"
|
|
89
|
+
];
|
|
90
|
+
/** The `lightning` namespace scope's granted methods — the WebLN surface. */
|
|
91
|
+
const LIGHTNING_METHODS = [
|
|
92
|
+
"enable",
|
|
93
|
+
"getInfo",
|
|
94
|
+
"sendPayment",
|
|
95
|
+
"makeInvoice",
|
|
96
|
+
"lnurl",
|
|
97
|
+
"getBalance"
|
|
98
|
+
];
|
|
99
|
+
/** The `solana` namespace scope's granted methods — the Wallet Standard surface. */
|
|
100
|
+
const SOLANA_METHODS = [
|
|
101
|
+
"standard:connect",
|
|
102
|
+
"standard:disconnect",
|
|
103
|
+
"standard:events",
|
|
104
|
+
"solana:signTransaction",
|
|
105
|
+
"solana:signAndSendTransaction",
|
|
106
|
+
"solana:signMessage",
|
|
107
|
+
"solana:signIn"
|
|
108
|
+
];
|
|
109
|
+
/** The `bip122` namespace scope's granted methods — the Bitcoin Wallet Standard surface. */
|
|
110
|
+
const BITCOIN_METHODS = [
|
|
111
|
+
"bitcoin:connect",
|
|
112
|
+
"standard:disconnect",
|
|
113
|
+
"bitcoin:events",
|
|
114
|
+
"bitcoin:signMessage",
|
|
115
|
+
"bitcoin:signTransaction",
|
|
116
|
+
"bitcoin:signAndSendTransaction"
|
|
117
|
+
];
|
|
118
|
+
/** The order of a `bip122` scope's two accounts. */
|
|
119
|
+
const BITCOIN_PURPOSES = ["payment", "ordinals"];
|
|
120
|
+
/** `eip155:1` → 1; `undefined` for anything that is not an EVM network. */
|
|
121
|
+
const evmChainId = (network) => {
|
|
122
|
+
const match = /^eip155:(\d+)$/.exec(network);
|
|
123
|
+
const id = match?.[1] === void 0 ? void 0 : Number(match[1]);
|
|
124
|
+
return id !== void 0 && Number.isSafeInteger(id) ? id : void 0;
|
|
125
|
+
};
|
|
126
|
+
const caip10 = (network, address) => `${network}:${address}`;
|
|
127
|
+
const addressOf = (account) => account.slice(account.lastIndexOf(":") + 1);
|
|
128
|
+
const isObject$4 = (v) => typeof v === "object" && v !== null;
|
|
129
|
+
const isSession = (value) => {
|
|
130
|
+
if (!isObject$4(value) || !isObject$4(value["origin"]) || !isObject$4(value["scopes"])) return false;
|
|
131
|
+
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"]));
|
|
132
|
+
};
|
|
133
|
+
const isLightningPolicy = (value) => isObject$4(value) && typeof value["balance"] === "boolean";
|
|
134
|
+
const isNostrPolicy = (value) => isObject$4(value) && typeof value["decrypt"] === "boolean" && (value["signing"] === "ask" || value["signing"] === "always" || isObject$4(value["signing"]) && Array.isArray(value["signing"]["kinds"]) && value["signing"]["kinds"].every((k) => typeof k === "number"));
|
|
135
|
+
var ConnectionController = class extends Controller {
|
|
136
|
+
options;
|
|
137
|
+
engineStore;
|
|
138
|
+
waiters = /* @__PURE__ */ new Map();
|
|
139
|
+
expiries = /* @__PURE__ */ new Map();
|
|
140
|
+
group;
|
|
141
|
+
identity;
|
|
142
|
+
constructor(options) {
|
|
143
|
+
super({
|
|
144
|
+
name: "connections",
|
|
145
|
+
defaultState: () => ({
|
|
146
|
+
sessions: {},
|
|
147
|
+
pending: {}
|
|
148
|
+
})
|
|
149
|
+
});
|
|
150
|
+
this.options = options;
|
|
151
|
+
}
|
|
152
|
+
async init() {
|
|
153
|
+
const store = await this.options.openStore();
|
|
154
|
+
this.engineStore = store;
|
|
155
|
+
this.group = void 0;
|
|
156
|
+
this.identity = void 0;
|
|
157
|
+
const collection = store.collection(COLLECTION$1);
|
|
158
|
+
const keys = await collection.list();
|
|
159
|
+
const rows = await Promise.all(keys.map(async (key) => collection.get(key)));
|
|
160
|
+
const now = this.options.now();
|
|
161
|
+
const sessions = {};
|
|
162
|
+
const expired = [];
|
|
163
|
+
for (const [index, raw] of rows.entries()) {
|
|
164
|
+
const key = keys[index];
|
|
165
|
+
if (raw === void 0 || key === void 0) continue;
|
|
166
|
+
const parsed = JSON.parse(new TextDecoder().decode(raw));
|
|
167
|
+
if (!isSession(parsed)) {
|
|
168
|
+
this.options.logger.warn("connection session skipped: malformed");
|
|
169
|
+
expired.push(key);
|
|
170
|
+
} else if (now - parsed.lastUsedAt > 7776e6) expired.push(key);
|
|
171
|
+
else sessions[parsed.id] = parsed;
|
|
172
|
+
}
|
|
173
|
+
await Promise.all(expired.map(async (key) => collection.delete(key)));
|
|
174
|
+
this.update(() => ({
|
|
175
|
+
sessions,
|
|
176
|
+
pending: {}
|
|
177
|
+
}));
|
|
178
|
+
}
|
|
179
|
+
async destroy() {
|
|
180
|
+
this.lock();
|
|
181
|
+
await Promise.resolve();
|
|
182
|
+
}
|
|
183
|
+
/** Locking is not consent: every pending connection is rejected. */
|
|
184
|
+
lock() {
|
|
185
|
+
this.engineStore = void 0;
|
|
186
|
+
this.group = void 0;
|
|
187
|
+
for (const waiter of this.waiters.values()) waiter.reject(userRejectedRequest("the wallet was locked"));
|
|
188
|
+
this.waiters.clear();
|
|
189
|
+
for (const cancel of this.expiries.values()) cancel();
|
|
190
|
+
this.expiries.clear();
|
|
191
|
+
this.update(() => ({
|
|
192
|
+
sessions: {},
|
|
193
|
+
pending: {}
|
|
194
|
+
}));
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* A page navigated away (or the bridge is being disposed): the origin's pending connection
|
|
198
|
+
* requests are rejected and its unfinished pipeline requests voided — the live session survives
|
|
199
|
+
* (a refresh is not a revocation).
|
|
200
|
+
*/
|
|
201
|
+
invalidateOrigin(origin) {
|
|
202
|
+
for (const entry of this.pending()) {
|
|
203
|
+
if (entry.origin.origin !== origin) continue;
|
|
204
|
+
this.waiters.get(entry.id)?.reject(userRejectedRequest("the page navigated away"));
|
|
205
|
+
this.dropPending(entry.id);
|
|
206
|
+
}
|
|
207
|
+
this.options.invalidate(origin);
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Throws `4100` unless `origin` is `https://host[:port]` (or localhost in development) and not on
|
|
211
|
+
* the phishing list.
|
|
212
|
+
*/
|
|
213
|
+
checkOrigin(origin) {
|
|
214
|
+
let url;
|
|
215
|
+
try {
|
|
216
|
+
url = new URL(origin);
|
|
217
|
+
} catch {
|
|
218
|
+
throw unauthorized("invalid origin");
|
|
219
|
+
}
|
|
220
|
+
const localhost = url.protocol === "http:" && url.hostname === "localhost";
|
|
221
|
+
if (url.origin !== origin || url.protocol !== "https:" && !(localhost && this.options.allowLocalhost)) throw unauthorized("origin not allowed");
|
|
222
|
+
if (this.options.phishing.check(origin) === "blocked") throw unauthorized(PHISHING_BLOCKED_MESSAGE);
|
|
223
|
+
return {
|
|
224
|
+
kind: "browser",
|
|
225
|
+
origin
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
session(origin) {
|
|
229
|
+
return Object.values(this.getState().sessions).find((s) => s.origin.origin === origin);
|
|
230
|
+
}
|
|
231
|
+
pending() {
|
|
232
|
+
return Object.values(this.getState().pending);
|
|
233
|
+
}
|
|
234
|
+
/** The group sessions are bound to: the host's last `setActiveGroup`, else the app's selection. */
|
|
235
|
+
activeGroup() {
|
|
236
|
+
return this.group ?? this.options.selectedGroup();
|
|
237
|
+
}
|
|
238
|
+
/** Whether `network` is an EVM network the wallet has enabled. */
|
|
239
|
+
isEnabled(network) {
|
|
240
|
+
return this.options.enabledNetworks().includes(network);
|
|
241
|
+
}
|
|
242
|
+
/** The origin's authorized addresses on its current network; empty when not connected. */
|
|
243
|
+
accounts(origin) {
|
|
244
|
+
const session = this.session(origin);
|
|
245
|
+
return session?.scopes[session.currentNetwork]?.accounts.map(addressOf) ?? [];
|
|
246
|
+
}
|
|
247
|
+
/** Throws `4100` unless the origin's session covers `method` on `network`. */
|
|
248
|
+
authorize(origin, network, method) {
|
|
249
|
+
const session = this.session(origin);
|
|
250
|
+
const scope = session?.scopes[network];
|
|
251
|
+
if (session === void 0 || scope === void 0 || !scope.methods.includes(method)) throw unauthorized();
|
|
252
|
+
return session;
|
|
253
|
+
}
|
|
254
|
+
/** Resolves with the session once the host approves; rejects with `4001` when it refuses. */
|
|
255
|
+
async request(origin, { kind, namespace = "eip155", network, activate = true }) {
|
|
256
|
+
if (this.engineStore === void 0) throw userRejectedRequest("the wallet is locked");
|
|
257
|
+
if (this.pending().some((p) => p.origin.origin === origin)) throw requestPending("a connection request is already pending");
|
|
258
|
+
if (this.pending().length >= 64) throw requestPending("too many pending connection requests");
|
|
259
|
+
const id = `conn-${[...this.options.random(8)].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
|
|
260
|
+
const entry = {
|
|
261
|
+
id,
|
|
262
|
+
origin: {
|
|
263
|
+
kind: "browser",
|
|
264
|
+
origin
|
|
265
|
+
},
|
|
266
|
+
kind,
|
|
267
|
+
namespace,
|
|
268
|
+
...network === void 0 ? {} : { network },
|
|
269
|
+
...activate ? {} : { activate },
|
|
270
|
+
createdAt: this.options.now()
|
|
271
|
+
};
|
|
272
|
+
return new Promise((resolve, reject) => {
|
|
273
|
+
this.waiters.set(id, {
|
|
274
|
+
resolve,
|
|
275
|
+
reject
|
|
276
|
+
});
|
|
277
|
+
this.expiries.set(id, this.options.setTimer(CONNECTION_REQUEST_TTL_MS, () => {
|
|
278
|
+
this.waiters.get(id)?.reject(userRejectedRequest("the connection request expired"));
|
|
279
|
+
this.dropPending(id);
|
|
280
|
+
}));
|
|
281
|
+
this.update((s) => ({
|
|
282
|
+
...s,
|
|
283
|
+
pending: {
|
|
284
|
+
...s.pending,
|
|
285
|
+
[id]: entry
|
|
286
|
+
}
|
|
287
|
+
}));
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* The host's approval, by id: the accounts granted (EVM addresses of the active group) and the
|
|
292
|
+
* network.
|
|
293
|
+
*/
|
|
294
|
+
async approveConnection(id, grant) {
|
|
295
|
+
const store = this.requireStore();
|
|
296
|
+
const entry = this.getState().pending[id];
|
|
297
|
+
const waiter = this.waiters.get(id);
|
|
298
|
+
if (entry === void 0 || waiter === void 0) throw new Error(`unknown connection request ${id}`);
|
|
299
|
+
if (this.options.phishing.check(entry.origin.origin) === "blocked") {
|
|
300
|
+
const blocked = unauthorized(PHISHING_BLOCKED_MESSAGE);
|
|
301
|
+
this.dropPending(id);
|
|
302
|
+
waiter.reject(blocked);
|
|
303
|
+
throw blocked;
|
|
304
|
+
}
|
|
305
|
+
if (entry.kind === "network" && entry.network !== grant.network) throw new Error(`connection request ${id} is for ${String(entry.network)}`);
|
|
306
|
+
const scopes = {};
|
|
307
|
+
if (entry.namespace === "nostr") {
|
|
308
|
+
if (grant.nostr === void 0) throw invalidParams("a nostr connection needs the identity's pubkey and policy");
|
|
309
|
+
const identity = this.activeIdentity();
|
|
310
|
+
if (identity === void 0) throw userRejectedRequest("no nostr identity is selected");
|
|
311
|
+
const identityPubkey = (await this.options.nostrPubkey(identity)).toLowerCase();
|
|
312
|
+
if (grant.nostr.pubkey.toLowerCase() !== identityPubkey) throw invalidParams("only the active identity can be granted");
|
|
313
|
+
scopes["nostr"] = {
|
|
314
|
+
accounts: [`nostr:${identityPubkey}`],
|
|
315
|
+
methods: NOSTR_METHODS,
|
|
316
|
+
notifications: []
|
|
317
|
+
};
|
|
318
|
+
} else if (entry.namespace === "solana") {
|
|
319
|
+
const group = this.activeGroup();
|
|
320
|
+
if (group === void 0) throw new Error("no account group is selected");
|
|
321
|
+
const solanaNetworks = this.options.enabledNetworks().filter((n) => n.startsWith("solana:"));
|
|
322
|
+
const solanaEntries = await Promise.all(solanaNetworks.map(async (network) => {
|
|
323
|
+
const address = await this.options.solanaAddress(group, network);
|
|
324
|
+
return [network, {
|
|
325
|
+
accounts: [caip10(network, address)],
|
|
326
|
+
methods: SOLANA_METHODS,
|
|
327
|
+
notifications: ["change"]
|
|
328
|
+
}];
|
|
329
|
+
}));
|
|
330
|
+
Object.assign(scopes, Object.fromEntries(solanaEntries));
|
|
331
|
+
} else if (entry.namespace === "bip122") {
|
|
332
|
+
const group = this.activeGroup();
|
|
333
|
+
if (group === void 0) throw new Error("no account group is selected");
|
|
334
|
+
const bitcoinNetworks = this.options.enabledNetworks().filter((n) => n.startsWith("bip122:"));
|
|
335
|
+
const bitcoinEntries = await Promise.all(bitcoinNetworks.map(async (network) => [network, await this.bitcoinScope(group, network)]));
|
|
336
|
+
Object.assign(scopes, Object.fromEntries(bitcoinEntries));
|
|
337
|
+
} else if (entry.namespace === "lightning") {
|
|
338
|
+
if (grant.lightning === void 0) throw invalidParams("a lightning connection needs the origin's policy");
|
|
339
|
+
const group = this.activeGroup();
|
|
340
|
+
if (group === void 0) throw new Error("no account group is selected");
|
|
341
|
+
scopes["lightning"] = {
|
|
342
|
+
accounts: [`spark:${group.walletId}:${String(group.groupIndex)}`],
|
|
343
|
+
methods: LIGHTNING_METHODS,
|
|
344
|
+
notifications: []
|
|
345
|
+
};
|
|
346
|
+
} else {
|
|
347
|
+
if (evmChainId(grant.network) === void 0 || !this.options.enabledNetworks().includes(grant.network)) throw invalidParams(`${grant.network} is not an enabled EVM network`);
|
|
348
|
+
const group = this.activeGroup();
|
|
349
|
+
if (group === void 0) throw new Error("no account group is selected");
|
|
350
|
+
const own = (await this.options.evmAddress(group, grant.network)).toLowerCase();
|
|
351
|
+
if (grant.accounts.length === 0 || grant.accounts.some((a) => a.toLowerCase() !== own)) throw invalidParams("only the active group's account can be granted");
|
|
352
|
+
scopes[grant.network] = {
|
|
353
|
+
accounts: [caip10(grant.network, own)],
|
|
354
|
+
methods: SESSION_METHODS,
|
|
355
|
+
notifications: SESSION_NOTIFICATIONS
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
if (this.getState().pending[id] === void 0) throw new Error(`connection request ${id} is no longer pending`);
|
|
359
|
+
const now = this.options.now();
|
|
360
|
+
const existing = this.session(entry.origin.origin);
|
|
361
|
+
const currentNetwork = entry.activate === false && existing !== void 0 ? existing.currentNetwork : grant.network;
|
|
362
|
+
const session = {
|
|
363
|
+
id: existing?.id ?? `session-${[...this.options.random(8)].map((b) => b.toString(16).padStart(2, "0")).join("")}`,
|
|
364
|
+
origin: entry.origin,
|
|
365
|
+
scopes: {
|
|
366
|
+
...existing?.scopes,
|
|
367
|
+
...scopes
|
|
368
|
+
},
|
|
369
|
+
currentNetwork,
|
|
370
|
+
...grant.nostr === void 0 ? {} : { nostrPolicy: grant.nostr.policy },
|
|
371
|
+
...grant.lightning === void 0 ? {} : { lightningPolicy: grant.lightning.policy },
|
|
372
|
+
createdAt: existing?.createdAt ?? now,
|
|
373
|
+
lastUsedAt: now
|
|
374
|
+
};
|
|
375
|
+
await this.persist(store, session);
|
|
376
|
+
this.dropPending(id);
|
|
377
|
+
if (existing !== void 0 && existing.currentNetwork !== currentNetwork) this.options.invalidate(entry.origin.origin);
|
|
378
|
+
waiter.resolve(session);
|
|
379
|
+
return session;
|
|
380
|
+
}
|
|
381
|
+
rejectConnection(id) {
|
|
382
|
+
const waiter = this.waiters.get(id);
|
|
383
|
+
if (this.getState().pending[id] === void 0 || waiter === void 0) throw new Error(`unknown connection request ${id}`);
|
|
384
|
+
this.dropPending(id);
|
|
385
|
+
waiter.reject(userRejectedRequest());
|
|
386
|
+
}
|
|
387
|
+
/** Ends the origin's session; its pending connection and unfinished requests are void. */
|
|
388
|
+
async revoke(origin) {
|
|
389
|
+
const store = this.requireStore();
|
|
390
|
+
for (const p of this.pending().filter((x) => x.origin.origin === origin)) {
|
|
391
|
+
const waiter = this.waiters.get(p.id);
|
|
392
|
+
this.dropPending(p.id);
|
|
393
|
+
waiter?.reject(userRejectedRequest("the connection was revoked"));
|
|
394
|
+
}
|
|
395
|
+
const session = this.session(origin);
|
|
396
|
+
if (session !== void 0) {
|
|
397
|
+
await store.collection(COLLECTION$1).delete(session.id);
|
|
398
|
+
this.update((s) => {
|
|
399
|
+
const { [session.id]: _gone, ...sessions } = s.sessions;
|
|
400
|
+
return {
|
|
401
|
+
...s,
|
|
402
|
+
sessions
|
|
403
|
+
};
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
this.options.invalidate(origin);
|
|
407
|
+
}
|
|
408
|
+
/** Switches within the session's scope; the origin's unfinished requests are void. */
|
|
409
|
+
async setCurrentNetwork(origin, network) {
|
|
410
|
+
const store = this.requireStore();
|
|
411
|
+
const session = this.session(origin);
|
|
412
|
+
if (session === void 0 || session.scopes[network] === void 0) throw unauthorized();
|
|
413
|
+
await this.persist(store, {
|
|
414
|
+
...session,
|
|
415
|
+
currentNetwork: network
|
|
416
|
+
});
|
|
417
|
+
this.options.invalidate(origin);
|
|
418
|
+
}
|
|
419
|
+
async touch(origin) {
|
|
420
|
+
const store = this.engineStore;
|
|
421
|
+
const session = this.session(origin);
|
|
422
|
+
const now = this.options.now();
|
|
423
|
+
if (store === void 0 || session === void 0 || now - session.lastUsedAt < TOUCH_INTERVAL_MS) return;
|
|
424
|
+
await this.persist(store, {
|
|
425
|
+
...session,
|
|
426
|
+
lastUsedAt: now
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* The host switched account group: every session's accounts become the new group's addresses. A
|
|
431
|
+
* session that cannot get one (no address derivable) is left with an empty list and has to be
|
|
432
|
+
* authorized again.
|
|
433
|
+
*/
|
|
434
|
+
async setActiveGroup(walletId, groupIndex) {
|
|
435
|
+
const store = this.requireStore();
|
|
436
|
+
const group = {
|
|
437
|
+
walletId,
|
|
438
|
+
groupIndex
|
|
439
|
+
};
|
|
440
|
+
this.group = group;
|
|
441
|
+
await Promise.all(Object.values(this.getState().sessions).map(async (session) => {
|
|
442
|
+
const entries = await Promise.all(Object.entries(session.scopes).map(async ([network, scope]) => {
|
|
443
|
+
if (scope.accounts.length === 0) return [network, scope];
|
|
444
|
+
try {
|
|
445
|
+
if (network === "nostr" || network === "lightning") return [network, scope];
|
|
446
|
+
if (network.startsWith("bip122:")) return [network, await this.bitcoinScope(group, network)];
|
|
447
|
+
if (network.startsWith("solana:")) {
|
|
448
|
+
const address = await this.options.solanaAddress(group, network);
|
|
449
|
+
return [network, {
|
|
450
|
+
...scope,
|
|
451
|
+
accounts: [caip10(network, address)]
|
|
452
|
+
}];
|
|
453
|
+
}
|
|
454
|
+
const address = await this.options.evmAddress(group, network);
|
|
455
|
+
return [network, {
|
|
456
|
+
...scope,
|
|
457
|
+
accounts: [caip10(network, address.toLowerCase())]
|
|
458
|
+
}];
|
|
459
|
+
} catch (error) {
|
|
460
|
+
this.options.logger.warn("connection account unavailable in the new group", error);
|
|
461
|
+
return [network, {
|
|
462
|
+
...scope,
|
|
463
|
+
accounts: []
|
|
464
|
+
}];
|
|
465
|
+
}
|
|
466
|
+
}));
|
|
467
|
+
await this.persist(store, {
|
|
468
|
+
...session,
|
|
469
|
+
scopes: Object.fromEntries(entries)
|
|
470
|
+
});
|
|
471
|
+
}));
|
|
472
|
+
}
|
|
473
|
+
/** The active Nostr identity — `undefined` until the host picks one. */
|
|
474
|
+
activeIdentity() {
|
|
475
|
+
return this.identity;
|
|
476
|
+
}
|
|
477
|
+
/** The origin's persisted Nostr policy — `undefined` until it is nostr-authorized. */
|
|
478
|
+
nostrPolicy(origin) {
|
|
479
|
+
return this.session(origin)?.nostrPolicy;
|
|
480
|
+
}
|
|
481
|
+
/** The origin's `nostr` namespace scope's pubkey, or `undefined` when not nostr-authorized. */
|
|
482
|
+
nostrAccount(origin) {
|
|
483
|
+
const account = this.session(origin)?.scopes["nostr"]?.accounts[0];
|
|
484
|
+
return account === void 0 ? void 0 : addressOf(account);
|
|
485
|
+
}
|
|
486
|
+
/** The origin's persisted Lightning policy — `undefined` until it is lightning-authorized. */
|
|
487
|
+
lightningPolicy(origin) {
|
|
488
|
+
return this.session(origin)?.lightningPolicy;
|
|
489
|
+
}
|
|
490
|
+
/** The origin's `solana` scope's address on `network`, or `undefined` when not authorized. */
|
|
491
|
+
solanaAccount(origin, network) {
|
|
492
|
+
const account = this.session(origin)?.scopes[network]?.accounts[0];
|
|
493
|
+
return account === void 0 ? void 0 : addressOf(account);
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* The origin's `bip122` scope accounts on `network`, in `BITCOIN_PURPOSES` order, or `undefined`
|
|
497
|
+
* when not authorized.
|
|
498
|
+
*/
|
|
499
|
+
bitcoinAccounts(origin, network) {
|
|
500
|
+
const [payment, ordinals] = this.session(origin)?.scopes[network]?.accounts ?? [];
|
|
501
|
+
return payment === void 0 || ordinals === void 0 ? void 0 : {
|
|
502
|
+
payment: addressOf(payment),
|
|
503
|
+
ordinals: addressOf(ordinals)
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
async bitcoinScope(group, network) {
|
|
507
|
+
return {
|
|
508
|
+
accounts: (await Promise.all(BITCOIN_PURPOSES.map(async (purpose) => this.options.bitcoinAddress(group, network, purpose)))).map((address) => caip10(network, address)),
|
|
509
|
+
methods: BITCOIN_METHODS,
|
|
510
|
+
notifications: ["change"]
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* The host's Nostr identity selection: every authorized `nostr` session's account becomes the new
|
|
515
|
+
* identity's pubkey (or empties when the identity is cleared). No event — NIP-07 has none.
|
|
516
|
+
*/
|
|
517
|
+
async setActiveIdentity(ref) {
|
|
518
|
+
const store = this.requireStore();
|
|
519
|
+
this.identity = ref;
|
|
520
|
+
let pubkey;
|
|
521
|
+
if (ref !== void 0) pubkey = (await this.options.nostrPubkey(ref)).toLowerCase();
|
|
522
|
+
await Promise.all(Object.values(this.getState().sessions).map(async (session) => {
|
|
523
|
+
const scope = session.scopes["nostr"];
|
|
524
|
+
if (scope === void 0 || scope.accounts.length === 0) return;
|
|
525
|
+
await this.persist(store, {
|
|
526
|
+
...session,
|
|
527
|
+
scopes: {
|
|
528
|
+
...session.scopes,
|
|
529
|
+
nostr: {
|
|
530
|
+
...scope,
|
|
531
|
+
accounts: pubkey === void 0 ? [] : [`nostr:${pubkey}`]
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
});
|
|
535
|
+
}));
|
|
536
|
+
}
|
|
537
|
+
dropPending(id) {
|
|
538
|
+
this.expiries.get(id)?.();
|
|
539
|
+
this.expiries.delete(id);
|
|
540
|
+
this.waiters.delete(id);
|
|
541
|
+
this.update((s) => {
|
|
542
|
+
const { [id]: _gone, ...pending } = s.pending;
|
|
543
|
+
return {
|
|
544
|
+
...s,
|
|
545
|
+
pending
|
|
546
|
+
};
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
async persist(store, session) {
|
|
550
|
+
try {
|
|
551
|
+
await store.collection(COLLECTION$1).put(session.id, new TextEncoder().encode(JSON.stringify(session)));
|
|
552
|
+
} catch (error) {
|
|
553
|
+
throw internalError(error instanceof Error ? error.message : String(error));
|
|
554
|
+
}
|
|
555
|
+
this.update((s) => ({
|
|
556
|
+
...s,
|
|
557
|
+
sessions: {
|
|
558
|
+
...s.sessions,
|
|
559
|
+
[session.id]: session
|
|
560
|
+
}
|
|
561
|
+
}));
|
|
562
|
+
}
|
|
563
|
+
requireStore() {
|
|
564
|
+
if (this.engineStore === void 0) throw userRejectedRequest("the wallet is locked");
|
|
565
|
+
return this.engineStore;
|
|
566
|
+
}
|
|
567
|
+
};
|
|
568
|
+
// src/addresses/normalize.ts
|
|
569
|
+
/**
|
|
570
|
+
* The canonical form of `address` for its family — EIP-55 for EVM, the re-encoded form for bitcoin
|
|
571
|
+
* (accepted on any known bitcoin network, since a contact is not tied to the wallet's network) and
|
|
572
|
+
* Spark (identity key only, no invoice fields) — or `undefined` when it is not a valid address.
|
|
573
|
+
*/
|
|
574
|
+
function normalizeAddress(family, address) {
|
|
575
|
+
try {
|
|
576
|
+
if (family === "evm") return isEvmAddress(address) ? checksumEvmAddress(address) : void 0;
|
|
577
|
+
if (family === "solana") return isSolanaAddress(address) ? address : void 0;
|
|
578
|
+
if (family === "spark") {
|
|
579
|
+
const decoded = decodeSparkAddress(address);
|
|
580
|
+
return encodeSparkAddress({
|
|
581
|
+
network: decoded.network,
|
|
582
|
+
identityPublicKey: decoded.identityPublicKey
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
for (const network of Object.values(BITCOIN_NETWORKS)) try {
|
|
586
|
+
const codec = Address(network.params);
|
|
587
|
+
return codec.encode(codec.decode(address));
|
|
588
|
+
} catch {}
|
|
589
|
+
return;
|
|
590
|
+
} catch {
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
// src/connect/text.ts
|
|
595
|
+
/** What a handler answers with (`4200`) for sign-message bytes that are not UTF-8 text. */
|
|
596
|
+
const BLIND_SIGNING_MESSAGE = "blind signing is not enabled: the message is not UTF-8 text";
|
|
597
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
598
|
+
/** The bytes as UTF-8 text, or `undefined` when they are not valid UTF-8. */
|
|
599
|
+
function utf8Text(bytes) {
|
|
600
|
+
try {
|
|
601
|
+
return decoder.decode(bytes);
|
|
602
|
+
} catch {
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
const UNSAFE_RANGES = [
|
|
607
|
+
[0, 31],
|
|
608
|
+
[127, 159],
|
|
609
|
+
[1564, 1564],
|
|
610
|
+
[8203, 8207],
|
|
611
|
+
[8234, 8238],
|
|
612
|
+
[8288, 8288],
|
|
613
|
+
[8294, 8297],
|
|
614
|
+
[65279, 65279]
|
|
615
|
+
];
|
|
616
|
+
const isUnsafe = (codePoint) => UNSAFE_RANGES.some(([low, high]) => codePoint >= low && codePoint <= high);
|
|
617
|
+
/**
|
|
618
|
+
* Untrusted contract text (a token symbol) as safe-to-show text: trimmed, non-empty, at most `max`
|
|
619
|
+
* code points, with no control, bidi-control or zero-width characters. `undefined` otherwise.
|
|
620
|
+
*/
|
|
621
|
+
function safeDisplayText(raw, max) {
|
|
622
|
+
const text = raw.trim();
|
|
623
|
+
let count = 0;
|
|
624
|
+
for (const char of text) {
|
|
625
|
+
count += 1;
|
|
626
|
+
if (count > max || isUnsafe(char.codePointAt(0) ?? 0)) return;
|
|
627
|
+
}
|
|
628
|
+
return count === 0 ? void 0 : text;
|
|
629
|
+
}
|
|
630
|
+
function isAscii(text) {
|
|
631
|
+
for (const char of text) {
|
|
632
|
+
const code = char.codePointAt(0) ?? 0;
|
|
633
|
+
if (code < 32 || code > 126) return false;
|
|
634
|
+
}
|
|
635
|
+
return true;
|
|
636
|
+
}
|
|
637
|
+
/** A token's `decimals` as an integer within `0..TOKEN_DECIMALS_MAX`, else `undefined`. */
|
|
638
|
+
const safeDecimals = (value) => Number.isInteger(value) && value >= 0 && value <= 36 ? value : void 0;
|
|
639
|
+
// src/spark/errors.ts
|
|
640
|
+
var SparkControllerError = class extends Error {
|
|
641
|
+
category;
|
|
642
|
+
constructor(category, message, cause) {
|
|
643
|
+
super(message, { cause });
|
|
644
|
+
this.name = "SparkControllerError";
|
|
645
|
+
this.category = category;
|
|
646
|
+
}
|
|
647
|
+
};
|
|
648
|
+
/** Maps a thrown client/kernel error into a category without leaking payloads. */
|
|
649
|
+
function categorize(error) {
|
|
650
|
+
const name = error instanceof Error ? error.name : "";
|
|
651
|
+
const message = error instanceof Error ? error.message : "";
|
|
652
|
+
if (/approval|denied|rejected/i.test(message)) return /required/i.test(message) ? "approval-required" : "rejected";
|
|
653
|
+
if (/insufficient|not enough|balance/i.test(message)) return "insufficient-funds";
|
|
654
|
+
if (name === "SparkRequestError" || /fetch|network|timeout|unavailable|closed/i.test(message)) return "network";
|
|
655
|
+
return "internal";
|
|
656
|
+
}
|
|
657
|
+
const feeCheck = (amountSats, maxFeeSats) => maxFeeSats !== void 0 && maxFeeSats >= amountSats ? ["fee-exceeds-amount"] : [];
|
|
658
|
+
// src/payments/errors.ts
|
|
659
|
+
var PaymentError = class extends Error {
|
|
660
|
+
category;
|
|
661
|
+
constructor(category, message, cause) {
|
|
662
|
+
super(message, { cause });
|
|
663
|
+
this.name = "PaymentError";
|
|
664
|
+
this.category = category;
|
|
665
|
+
}
|
|
666
|
+
};
|
|
667
|
+
// src/payments/pay.ts
|
|
668
|
+
const lightningDetails = (invoice) => {
|
|
669
|
+
const decoded = decodeBolt11(invoice);
|
|
670
|
+
return {
|
|
671
|
+
payee: bytesToHex(decoded.payee),
|
|
672
|
+
expiresAt: (decoded.timestamp + decoded.expirySeconds) * 1e3
|
|
673
|
+
};
|
|
674
|
+
};
|
|
675
|
+
/**
|
|
676
|
+
* Validates one parsed payment option and fixes everything the approval needs — including the
|
|
677
|
+
* LNURL-pay invoice, fetched here exactly once. Every input validation happens before the approval
|
|
678
|
+
* round, so a `PaymentError` here never consumed a verification. `lnurl-withdraw` receives funds
|
|
679
|
+
* and has its own entry, {@link withdrawLnurl}.
|
|
680
|
+
*/
|
|
681
|
+
async function preparePay(context, params) {
|
|
682
|
+
const ref = params.account;
|
|
683
|
+
const { network } = ref;
|
|
684
|
+
if (params.option.kind === "lnurl-withdraw") throw new PaymentError("invalid-input", "lnurl-withdraw receives funds: use payments.withdrawLnurl");
|
|
685
|
+
switch (params.option.kind) {
|
|
686
|
+
case "spark": {
|
|
687
|
+
if (params.amountSats === void 0) throw new PaymentError("invalid-input", "spark payment: amountSats is required");
|
|
688
|
+
const { address } = params.option;
|
|
689
|
+
const { amountSats } = params;
|
|
690
|
+
return {
|
|
691
|
+
display: {
|
|
692
|
+
family: "spark",
|
|
693
|
+
network,
|
|
694
|
+
kind: "transfer",
|
|
695
|
+
amountSats,
|
|
696
|
+
receiver: address
|
|
697
|
+
},
|
|
698
|
+
checks: [],
|
|
699
|
+
staleReason: () => void 0,
|
|
700
|
+
execute: async (spark, verify) => ({
|
|
701
|
+
kind: "spark",
|
|
702
|
+
transfer: await spark.send(ref, {
|
|
703
|
+
receiver: address,
|
|
704
|
+
amountSats,
|
|
705
|
+
verify
|
|
706
|
+
})
|
|
707
|
+
})
|
|
708
|
+
};
|
|
709
|
+
}
|
|
710
|
+
case "spark-invoice": {
|
|
711
|
+
const { option } = params;
|
|
712
|
+
if (option.expiresAt !== void 0 && option.expiresAt <= context.now()) throw new PaymentError("rejected", "spark invoice expired");
|
|
713
|
+
if (option.amountSats !== void 0 && params.amountSats !== void 0 && params.amountSats !== option.amountSats) throw new PaymentError("invalid-input", "spark invoice: amountSats conflicts with the invoice amount");
|
|
714
|
+
const amountSats = option.amountSats ?? params.amountSats;
|
|
715
|
+
if (amountSats === void 0) throw new PaymentError("invalid-input", "spark invoice: amountless invoice requires amountSats");
|
|
716
|
+
const openAmount = option.amountSats === void 0 ? params.amountSats : void 0;
|
|
717
|
+
const parsed = parseSparkInvoice(option.invoice, {
|
|
718
|
+
network,
|
|
719
|
+
now: context.now()
|
|
720
|
+
});
|
|
721
|
+
const { expiresAt } = option;
|
|
722
|
+
return {
|
|
723
|
+
display: {
|
|
724
|
+
family: "spark",
|
|
725
|
+
network,
|
|
726
|
+
kind: "transfer",
|
|
727
|
+
amountSats,
|
|
728
|
+
receiver: encodeSparkAddress({
|
|
729
|
+
network,
|
|
730
|
+
identityPublicKey: parsed.receiverIdentityPublicKey
|
|
731
|
+
}),
|
|
732
|
+
...option.memo === void 0 ? {} : { description: option.memo }
|
|
733
|
+
},
|
|
734
|
+
checks: [],
|
|
735
|
+
staleReason: (now) => expiresAt !== void 0 && expiresAt <= now ? "spark invoice expired" : void 0,
|
|
736
|
+
execute: async (spark, verify) => ({
|
|
737
|
+
kind: "spark",
|
|
738
|
+
transfer: await spark.paySparkInvoice(ref, {
|
|
739
|
+
invoice: option.invoice,
|
|
740
|
+
...openAmount === void 0 ? {} : { amountSats: openAmount },
|
|
741
|
+
verify
|
|
742
|
+
})
|
|
743
|
+
})
|
|
744
|
+
};
|
|
745
|
+
}
|
|
746
|
+
case "lightning": {
|
|
747
|
+
const { option } = params;
|
|
748
|
+
if (option.amountSats === void 0 && params.amountSats === void 0) throw new PaymentError("invalid-input", "amountless invoice: amountSats is required");
|
|
749
|
+
if (params.maxFeeSats === void 0) throw new PaymentError("invalid-input", "lightning payment: maxFeeSats is required");
|
|
750
|
+
if (option.expiresAt <= context.now() + 6e4) throw new PaymentError("rejected", "lightning invoice expired");
|
|
751
|
+
if (option.amountSats !== void 0 && params.amountSats !== void 0 && params.amountSats !== option.amountSats) throw new PaymentError("invalid-input", "amountSats conflicts with the invoice amount");
|
|
752
|
+
const { maxFeeSats } = params;
|
|
753
|
+
const openAmount = option.amountSats === void 0 ? params.amountSats : void 0;
|
|
754
|
+
const amountSats = option.amountSats ?? params.amountSats ?? 0;
|
|
755
|
+
const { payee } = lightningDetails(option.invoice);
|
|
756
|
+
const { expiresAt } = option;
|
|
757
|
+
return {
|
|
758
|
+
display: {
|
|
759
|
+
family: "spark",
|
|
760
|
+
network,
|
|
761
|
+
kind: "lightning",
|
|
762
|
+
amountSats,
|
|
763
|
+
maxFeeSats,
|
|
764
|
+
...params.amountFromServiceMinimum === true ? { amountFromServiceMinimum: true } : {},
|
|
765
|
+
receiver: payee,
|
|
766
|
+
...option.description === void 0 ? {} : { description: option.description }
|
|
767
|
+
},
|
|
768
|
+
checks: feeCheck(amountSats, maxFeeSats),
|
|
769
|
+
staleReason: (now) => expiresAt <= now + 6e4 ? "lightning invoice expired" : void 0,
|
|
770
|
+
execute: async (spark, verify) => ({
|
|
771
|
+
kind: "lightning",
|
|
772
|
+
payment: await spark.payInvoice(ref, {
|
|
773
|
+
invoice: option.invoice,
|
|
774
|
+
maxFeeSats,
|
|
775
|
+
...openAmount === void 0 ? {} : { amountSats: openAmount },
|
|
776
|
+
verify
|
|
777
|
+
})
|
|
778
|
+
})
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
case "lnurl-pay": {
|
|
782
|
+
const { request } = params.option;
|
|
783
|
+
if (params.amountSats === void 0) throw new PaymentError("invalid-input", "lnurl-pay: amountSats is required");
|
|
784
|
+
if (params.maxFeeSats === void 0) throw new PaymentError("invalid-input", "lnurl-pay: maxFeeSats is required");
|
|
785
|
+
const { amountSats, maxFeeSats } = params;
|
|
786
|
+
const amountMsat = amountSats * 1e3;
|
|
787
|
+
if (amountMsat < request.minSendableMsat || amountMsat > request.maxSendableMsat) throw new PaymentError("rejected", "lnurl-pay: amount outside the service's range");
|
|
788
|
+
if (request.commentAllowed === 0 && params.comment !== void 0) throw new PaymentError("rejected", "lnurl-pay: comments not accepted by this service");
|
|
789
|
+
if (params.comment !== void 0 && params.comment.length > request.commentAllowed) throw new PaymentError("rejected", "lnurl-pay: comment exceeds the service's limit");
|
|
790
|
+
let requested;
|
|
791
|
+
try {
|
|
792
|
+
requested = await requestInvoice(request, {
|
|
793
|
+
fetch: context.fetch,
|
|
794
|
+
network,
|
|
795
|
+
amountMsat,
|
|
796
|
+
...params.comment === void 0 ? {} : { comment: params.comment }
|
|
797
|
+
});
|
|
798
|
+
} catch (error) {
|
|
799
|
+
if (error instanceof PaymentError || error instanceof SparkControllerError) throw error;
|
|
800
|
+
throw new PaymentError("network", "lnurl-pay: invoice request failed", error);
|
|
801
|
+
}
|
|
802
|
+
const { invoice } = requested;
|
|
803
|
+
const { payee, expiresAt } = lightningDetails(invoice);
|
|
804
|
+
return {
|
|
805
|
+
display: {
|
|
806
|
+
family: "spark",
|
|
807
|
+
network,
|
|
808
|
+
kind: "lightning",
|
|
809
|
+
amountSats,
|
|
810
|
+
maxFeeSats,
|
|
811
|
+
...params.amountFromServiceMinimum === true ? { amountFromServiceMinimum: true } : {},
|
|
812
|
+
receiver: payee,
|
|
813
|
+
description: request.description
|
|
814
|
+
},
|
|
815
|
+
checks: feeCheck(amountSats, maxFeeSats),
|
|
816
|
+
staleReason: (now) => expiresAt <= now + 6e4 ? "lightning invoice expired" : void 0,
|
|
817
|
+
execute: async (spark, verify) => ({
|
|
818
|
+
kind: "lightning",
|
|
819
|
+
payment: await spark.payInvoice(ref, {
|
|
820
|
+
invoice,
|
|
821
|
+
maxFeeSats,
|
|
822
|
+
verify
|
|
823
|
+
})
|
|
824
|
+
})
|
|
825
|
+
};
|
|
826
|
+
}
|
|
827
|
+
default: {
|
|
828
|
+
if (params.amountSats === void 0) throw new PaymentError("invalid-input", "bitcoin payment: amountSats is required");
|
|
829
|
+
const { address } = params.option;
|
|
830
|
+
const { amountSats, maxFeeSats } = params;
|
|
831
|
+
const speed = params.speed ?? "MEDIUM";
|
|
832
|
+
return {
|
|
833
|
+
display: {
|
|
834
|
+
family: "spark",
|
|
835
|
+
network,
|
|
836
|
+
kind: "exit",
|
|
837
|
+
amountSats,
|
|
838
|
+
...maxFeeSats === void 0 ? {} : { maxFeeSats },
|
|
839
|
+
receiver: address
|
|
840
|
+
},
|
|
841
|
+
checks: feeCheck(amountSats, maxFeeSats),
|
|
842
|
+
staleReason: () => void 0,
|
|
843
|
+
execute: async (spark, verify) => ({
|
|
844
|
+
kind: "withdraw",
|
|
845
|
+
exit: await spark.withdraw(ref, {
|
|
846
|
+
address,
|
|
847
|
+
speed,
|
|
848
|
+
verify,
|
|
849
|
+
amountSats,
|
|
850
|
+
...maxFeeSats === void 0 ? {} : { maxFeeSats }
|
|
851
|
+
})
|
|
852
|
+
})
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
/**
|
|
858
|
+
* LNURL-withdraw: asks the service to pay an invoice this wallet creates. It receives funds, so it
|
|
859
|
+
* needs no verification factor and does not go through the request pipeline.
|
|
860
|
+
*/
|
|
861
|
+
async function withdrawLnurl(context, params) {
|
|
862
|
+
const { request } = params.option;
|
|
863
|
+
const amountMsat = params.amountSats * 1e3;
|
|
864
|
+
if (amountMsat < request.minWithdrawableMsat || amountMsat > request.maxWithdrawableMsat) throw new PaymentError("rejected", "lnurl-withdraw: amount outside the service's range");
|
|
865
|
+
const invoice = await context.spark.createInvoice(params.account, {
|
|
866
|
+
amountSats: params.amountSats,
|
|
867
|
+
memo: request.defaultDescription
|
|
868
|
+
});
|
|
869
|
+
try {
|
|
870
|
+
await submitWithdraw(request, {
|
|
871
|
+
fetch: context.fetch,
|
|
872
|
+
invoice: invoice.invoice
|
|
873
|
+
});
|
|
874
|
+
} catch (error) {
|
|
875
|
+
if (error instanceof PaymentError || error instanceof SparkControllerError) throw error;
|
|
876
|
+
throw new PaymentError("network", "lnurl-withdraw: submission failed", error);
|
|
877
|
+
}
|
|
878
|
+
return {
|
|
879
|
+
kind: "lnurl-withdraw",
|
|
880
|
+
invoice
|
|
881
|
+
};
|
|
882
|
+
}
|
|
883
|
+
// src/payments/zap.ts
|
|
884
|
+
/** Everything up to payment: resolve LNURL, sign the 9734, request the invoice. */
|
|
885
|
+
async function prepareZap(params, context) {
|
|
886
|
+
const amountMsat = params.amountSats * 1e3;
|
|
887
|
+
if (!Number.isSafeInteger(params.amountSats) || params.amountSats <= 0 || !Number.isSafeInteger(amountMsat)) throw new PaymentError("invalid-input", "zap amount is not a positive safe integer");
|
|
888
|
+
try {
|
|
889
|
+
const resolved = await resolveLnurl(params.recipient.lightning, { fetch: context.fetch });
|
|
890
|
+
if (resolved.tag !== "payRequest") throw new PaymentError("rejected", "recipient is not an LNURL-pay endpoint");
|
|
891
|
+
if (!resolved.allowsNostr || resolved.nostrPubkey === void 0) throw new PaymentError("rejected", "LNURL service does not accept nostr zaps");
|
|
892
|
+
if (amountMsat < resolved.minSendableMsat || amountMsat > resolved.maxSendableMsat) throw new PaymentError("rejected", "zap amount outside the service's bounds");
|
|
893
|
+
if (params.comment !== void 0) {
|
|
894
|
+
if (resolved.commentAllowed === 0) throw new PaymentError("rejected", "the service does not accept comments");
|
|
895
|
+
if (params.comment.length > resolved.commentAllowed) throw new PaymentError("rejected", "comment exceeds the service's limit");
|
|
896
|
+
}
|
|
897
|
+
const lnurl = params.recipient.lightning.toLowerCase().startsWith("lnurl1") ? params.recipient.lightning.toLowerCase() : encodeLnurl(lightningAddressUrl(params.recipient.lightning));
|
|
898
|
+
const base = {
|
|
899
|
+
amount: amountMsat,
|
|
900
|
+
relays: [...params.relays],
|
|
901
|
+
comment: params.comment,
|
|
902
|
+
lnurl
|
|
903
|
+
};
|
|
904
|
+
const unsigned = {
|
|
905
|
+
..."event" in params.recipient ? makeZapRequest({
|
|
906
|
+
event: params.recipient.event,
|
|
907
|
+
...base
|
|
908
|
+
}) : makeZapRequest({
|
|
909
|
+
pubkey: params.recipient.pubkey,
|
|
910
|
+
...base
|
|
911
|
+
}),
|
|
912
|
+
pubkey: await params.signer.getPublicKey()
|
|
913
|
+
};
|
|
914
|
+
const zapRequest = await params.signer.signEvent(unsigned);
|
|
915
|
+
if (!context.verifyEvent(zapRequest) || !signedMatchesUnsigned(zapRequest, unsigned)) throw new PaymentError("rejected", "signer returned a zap request that does not match");
|
|
916
|
+
const { invoice } = await requestInvoice(resolved, {
|
|
917
|
+
fetch: context.fetch,
|
|
918
|
+
network: params.network,
|
|
919
|
+
amountMsat,
|
|
920
|
+
...params.comment === void 0 ? {} : { comment: params.comment },
|
|
921
|
+
zapRequest: JSON.stringify(zapRequest)
|
|
922
|
+
});
|
|
923
|
+
const decoded = decodeBolt11(invoice);
|
|
924
|
+
const expiresAt = (decoded.timestamp + decoded.expirySeconds) * 1e3;
|
|
925
|
+
if (expiresAt <= context.now() + 6e4) throw new PaymentError("rejected", "zap invoice expires too soon");
|
|
926
|
+
const eventId = "event" in params.recipient ? params.recipient.event.id : void 0;
|
|
927
|
+
return {
|
|
928
|
+
zapRequest,
|
|
929
|
+
invoice,
|
|
930
|
+
paymentHash: bytesToHex(decoded.paymentHash),
|
|
931
|
+
expiresAt,
|
|
932
|
+
amountSats: params.amountSats,
|
|
933
|
+
receiptPubkey: bytesToHex(resolved.nostrPubkey),
|
|
934
|
+
recipientPubkey: "event" in params.recipient ? params.recipient.event.pubkey : params.recipient.pubkey,
|
|
935
|
+
...eventId === void 0 ? {} : { eventId },
|
|
936
|
+
...params.comment === void 0 ? {} : { comment: params.comment },
|
|
937
|
+
lightning: params.recipient.lightning
|
|
938
|
+
};
|
|
939
|
+
} catch (error) {
|
|
940
|
+
if (error instanceof PaymentError) throw error;
|
|
941
|
+
if (error instanceof SparkInputError || error instanceof Error && error.cause instanceof SparkInputError) throw new PaymentError("rejected", "zap failed invoice validation");
|
|
942
|
+
throw new PaymentError(categorizePayment(error), "zap failed");
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
/**
|
|
946
|
+
* Fixes a prepared zap for approval: the invoice (fetched by {@link prepareZap}) is paid as-is, and
|
|
947
|
+
* the zap note is written under the payment's transfer id afterwards. A nearly-expired invoice is
|
|
948
|
+
* refused here and again at approval — the user may sit on the confirm screen.
|
|
949
|
+
*/
|
|
950
|
+
function prepareZapAction(account, prepared, options) {
|
|
951
|
+
if (prepared.expiresAt <= options.now() + 6e4) throw new PaymentError("rejected", "zap invoice expired");
|
|
952
|
+
const { maxFeeSats } = options;
|
|
953
|
+
const { payee } = lightningInvoiceDetails(prepared.invoice);
|
|
954
|
+
return {
|
|
955
|
+
display: {
|
|
956
|
+
family: "spark",
|
|
957
|
+
network: account.network,
|
|
958
|
+
kind: "lightning",
|
|
959
|
+
amountSats: prepared.amountSats,
|
|
960
|
+
maxFeeSats,
|
|
961
|
+
receiver: payee,
|
|
962
|
+
...prepared.comment === void 0 ? {} : { description: prepared.comment }
|
|
963
|
+
},
|
|
964
|
+
checks: feeCheck(prepared.amountSats, maxFeeSats),
|
|
965
|
+
staleReason: (now) => prepared.expiresAt <= now + 6e4 ? "zap invoice expired" : void 0,
|
|
966
|
+
execute: async (spark, verify) => ({
|
|
967
|
+
kind: "lightning",
|
|
968
|
+
payment: await spark.payInvoice(account, {
|
|
969
|
+
invoice: prepared.invoice,
|
|
970
|
+
maxFeeSats,
|
|
971
|
+
verify,
|
|
972
|
+
note: {
|
|
973
|
+
kind: "zap",
|
|
974
|
+
recipientPubkey: prepared.recipientPubkey,
|
|
975
|
+
...prepared.eventId === void 0 ? {} : { eventId: prepared.eventId },
|
|
976
|
+
...prepared.comment === void 0 ? {} : { comment: prepared.comment },
|
|
977
|
+
lightning: prepared.lightning
|
|
978
|
+
}
|
|
979
|
+
})
|
|
980
|
+
})
|
|
981
|
+
};
|
|
982
|
+
}
|
|
983
|
+
const lightningInvoiceDetails = (invoice) => ({ payee: bytesToHex(decodeBolt11(invoice).payee) });
|
|
984
|
+
function categorizePayment(error) {
|
|
985
|
+
return categorize(error) === "network" ? "network" : "rejected";
|
|
986
|
+
}
|
|
987
|
+
// src/spark/l1.ts
|
|
988
|
+
/** The bitcoin network each Spark network settles on; deposits and exits must agree with it. */
|
|
989
|
+
const SPARK_L1_NETWORK = {
|
|
990
|
+
mainnet: "bip122:000000000019d6689c085ae165831e93",
|
|
991
|
+
regtest: "bip122:0f9188f13cb7b2c71f2a335e3a4fc328"
|
|
992
|
+
};
|
|
993
|
+
// src/transactions/route.ts
|
|
994
|
+
const hexId = (prefix, random) => `${prefix}-${[...random(8)].map((b) => b.toString(16).padStart(2, "0")).join("")}`;
|
|
995
|
+
const newId = (random) => hexId("tx", random);
|
|
996
|
+
const newRequestId = (random) => hexId("req", random);
|
|
997
|
+
const LIVE_REPLACEMENT_STATES = /* @__PURE__ */ new Set([
|
|
998
|
+
"draft",
|
|
999
|
+
"signed",
|
|
1000
|
+
"submitted",
|
|
1001
|
+
"pending"
|
|
1002
|
+
]);
|
|
1003
|
+
/**
|
|
1004
|
+
* Approval-time check for a replacement: the original must still be unconfirmed and no other
|
|
1005
|
+
* replacement of it may already be on its way.
|
|
1006
|
+
*/
|
|
1007
|
+
const replacementStaleReason = (ctx, originalId) => {
|
|
1008
|
+
const txs = ctx.txs();
|
|
1009
|
+
const original = txs[originalId];
|
|
1010
|
+
if (original?.state !== "submitted" && original?.state !== "pending") return "original transaction already finished — nothing to replace";
|
|
1011
|
+
return Object.values(txs).some((t) => t.replaces === originalId && LIVE_REPLACEMENT_STATES.has(t.state)) ? "original transaction was already replaced — start over" : void 0;
|
|
1012
|
+
};
|
|
1013
|
+
const submitTx = async (ctx, tx, hash) => {
|
|
1014
|
+
const tracked = await ctx.transition(tx, {
|
|
1015
|
+
state: "submitted",
|
|
1016
|
+
hash,
|
|
1017
|
+
submittedAt: ctx.options.now()
|
|
1018
|
+
});
|
|
1019
|
+
ctx.track(tracked.id, hash);
|
|
1020
|
+
return tracked;
|
|
1021
|
+
};
|
|
1022
|
+
const failTx = async (ctx, tx, error) => {
|
|
1023
|
+
const failed = tx.state === "signed" ? "failed" : "rejected";
|
|
1024
|
+
await ctx.transition(tx, {
|
|
1025
|
+
state: failed,
|
|
1026
|
+
error: errorMessage(error)
|
|
1027
|
+
});
|
|
1028
|
+
};
|
|
1029
|
+
// src/requests/checks.ts
|
|
1030
|
+
/** Two reads of one fee differ by more than this share of the smaller one. */
|
|
1031
|
+
const FEE_MISMATCH_PERCENT = 25n;
|
|
1032
|
+
/** A fee ceiling above this multiple of the independent estimate is flagged. */
|
|
1033
|
+
const FEE_CAP_MULTIPLIER = 2n;
|
|
1034
|
+
/**
|
|
1035
|
+
* `|a − b| / min(a, b)` is strictly above {@link FEE_MISMATCH_PERCENT}; a zero against a non-zero
|
|
1036
|
+
* always is.
|
|
1037
|
+
*/
|
|
1038
|
+
const feesDiffer = (a, b) => {
|
|
1039
|
+
const low = a < b ? a : b;
|
|
1040
|
+
return ((a < b ? b : a) - low) * 100n > low * FEE_MISMATCH_PERCENT;
|
|
1041
|
+
};
|
|
1042
|
+
/**
|
|
1043
|
+
* The final ceiling exceeds {@link FEE_CAP_MULTIPLIER} times the independent estimate of the same
|
|
1044
|
+
* tier.
|
|
1045
|
+
*/
|
|
1046
|
+
const exceedsNetworkCap = (final, independent) => final > independent * FEE_CAP_MULTIPLIER;
|
|
1047
|
+
/** The worst-case fee is not below the amount sent (native-asset sends only). */
|
|
1048
|
+
const feeReachesAmount = (maxFee, amount) => maxFee >= amount;
|
|
1049
|
+
const min = (a, b) => a < b ? a : b;
|
|
1050
|
+
const max = (a, b) => a > b ? a : b;
|
|
1051
|
+
/** EIP-1559 quotes are `maxFee = baseFee × 2 + priority`; this recovers the base fee. */
|
|
1052
|
+
const baseFeeOf = (quote) => (quote.maxFeePerGas - (quote.maxPriorityFeePerGas ?? 0n)) / 2n;
|
|
1053
|
+
/**
|
|
1054
|
+
* EIP-1559: priority fee is the lower of the two, `maxFeePerGas = max(baseFee) × 2 + priority` (a
|
|
1055
|
+
* high ceiling only prevents a stuck transaction, the base fee actually paid is the chain's).
|
|
1056
|
+
* Legacy: the lower gas price. Two different shapes cannot be merged — the independent quote wins.
|
|
1057
|
+
*/
|
|
1058
|
+
const mergeEvmQuote = (primary, independent) => {
|
|
1059
|
+
const a = primary.maxPriorityFeePerGas;
|
|
1060
|
+
const b = independent.maxPriorityFeePerGas;
|
|
1061
|
+
if (a !== void 0 && b !== void 0) {
|
|
1062
|
+
const priority = min(a, b);
|
|
1063
|
+
const maxFeePerGas = max(baseFeeOf(primary), baseFeeOf(independent)) * 2n + priority;
|
|
1064
|
+
return {
|
|
1065
|
+
quote: {
|
|
1066
|
+
tier: primary.tier,
|
|
1067
|
+
wei: maxFeePerGas,
|
|
1068
|
+
maxFeePerGas,
|
|
1069
|
+
maxPriorityFeePerGas: priority
|
|
1070
|
+
},
|
|
1071
|
+
mismatch: feesDiffer(a, b) || feesDiffer(baseFeeOf(primary), baseFeeOf(independent))
|
|
1072
|
+
};
|
|
1073
|
+
}
|
|
1074
|
+
if (a === void 0 && b === void 0) {
|
|
1075
|
+
const price = min(primary.maxFeePerGas, independent.maxFeePerGas);
|
|
1076
|
+
return {
|
|
1077
|
+
quote: {
|
|
1078
|
+
tier: primary.tier,
|
|
1079
|
+
wei: price,
|
|
1080
|
+
maxFeePerGas: price,
|
|
1081
|
+
maxPriorityFeePerGas: void 0
|
|
1082
|
+
},
|
|
1083
|
+
mismatch: feesDiffer(primary.maxFeePerGas, independent.maxFeePerGas)
|
|
1084
|
+
};
|
|
1085
|
+
}
|
|
1086
|
+
return {
|
|
1087
|
+
quote: independent,
|
|
1088
|
+
mismatch: true
|
|
1089
|
+
};
|
|
1090
|
+
};
|
|
1091
|
+
const mergeSolanaQuote = (primary, independent) => ({
|
|
1092
|
+
quote: {
|
|
1093
|
+
tier: primary.tier,
|
|
1094
|
+
microLamportsPerCu: min(primary.microLamportsPerCu, independent.microLamportsPerCu)
|
|
1095
|
+
},
|
|
1096
|
+
mismatch: feesDiffer(primary.microLamportsPerCu, independent.microLamportsPerCu)
|
|
1097
|
+
});
|
|
1098
|
+
/** Bitcoin fee rates (sat/vB) per confirmation target. */
|
|
1099
|
+
const mergeSatPerByte = (primary, independent) => ({
|
|
1100
|
+
rate: Math.min(primary, independent),
|
|
1101
|
+
mismatch: feesDiffer(BigInt(Math.ceil(primary)), BigInt(Math.ceil(independent)))
|
|
1102
|
+
});
|
|
1103
|
+
/** The checks a prepared build carries, in a stable order and without duplicates. */
|
|
1104
|
+
const collectChecks = (flags) => [...new Set(flags.filter((f) => f !== void 0))];
|
|
1105
|
+
// src/timer.ts
|
|
1106
|
+
/**
|
|
1107
|
+
* An `AbortSignal` that fires after `ms` on the injected timer — the platform timeout signal is not
|
|
1108
|
+
* available in every runtime this package runs in. Call `cancel` once the work is done, or `abort`
|
|
1109
|
+
* to stop it early.
|
|
1110
|
+
*/
|
|
1111
|
+
function timeoutSignal(ms, setTimer) {
|
|
1112
|
+
const controller = new AbortController();
|
|
1113
|
+
const cancel = setTimer(ms, () => {
|
|
1114
|
+
controller.abort();
|
|
1115
|
+
});
|
|
1116
|
+
return {
|
|
1117
|
+
signal: controller.signal,
|
|
1118
|
+
cancel,
|
|
1119
|
+
abort: () => {
|
|
1120
|
+
controller.abort();
|
|
1121
|
+
}
|
|
1122
|
+
};
|
|
1123
|
+
}
|
|
1124
|
+
// src/chains/bitcoin.ts
|
|
1125
|
+
const DUST = {
|
|
1126
|
+
p2wpkh: 294,
|
|
1127
|
+
p2tr: 330,
|
|
1128
|
+
p2pkh: 546
|
|
1129
|
+
};
|
|
1130
|
+
const FROZEN_AMOUNTS = /* @__PURE__ */ new Set([546, 330]);
|
|
1131
|
+
const isObject$3 = (v) => typeof v === "object" && v !== null;
|
|
1132
|
+
var EsploraError = class extends Error {
|
|
1133
|
+
/** True for request timeout/abort, network failure, 429-after-retries and 5xx — safe to retry. */
|
|
1134
|
+
transient;
|
|
1135
|
+
constructor(message, transient) {
|
|
1136
|
+
super(message);
|
|
1137
|
+
this.name = "EsploraError";
|
|
1138
|
+
this.transient = transient;
|
|
1139
|
+
}
|
|
1140
|
+
};
|
|
1141
|
+
const MAX_IN_FLIGHT = 4;
|
|
1142
|
+
const MAX_RETRIES = 3;
|
|
1143
|
+
const MAX_BACKOFF_MS = 2e3;
|
|
1144
|
+
const REQUEST_TIMEOUT_MS = 1e4;
|
|
1145
|
+
/** Bounded-concurrency + 429-aware ordered failover over the endpoint list. */
|
|
1146
|
+
const esplora = (endpoints, fetchFn, deps, timeoutMs = REQUEST_TIMEOUT_MS) => {
|
|
1147
|
+
const { setTimer, random } = deps;
|
|
1148
|
+
const sleep = async (ms) => new Promise((resolve) => {
|
|
1149
|
+
setTimer(ms, resolve);
|
|
1150
|
+
});
|
|
1151
|
+
let inFlight = 0;
|
|
1152
|
+
const waiters = [];
|
|
1153
|
+
const acquire = async () => {
|
|
1154
|
+
if (inFlight >= MAX_IN_FLIGHT) await new Promise((resolve) => {
|
|
1155
|
+
waiters.push(resolve);
|
|
1156
|
+
});
|
|
1157
|
+
inFlight += 1;
|
|
1158
|
+
};
|
|
1159
|
+
const release = () => {
|
|
1160
|
+
inFlight -= 1;
|
|
1161
|
+
waiters.shift()?.();
|
|
1162
|
+
};
|
|
1163
|
+
const backoff = async (headers, retry) => {
|
|
1164
|
+
const ra = headers.get("retry-after");
|
|
1165
|
+
const retryAfterMs = ra !== null && ra !== "" && !Number.isNaN(Number(ra)) ? Number(ra) * 1e3 : void 0;
|
|
1166
|
+
const jitter = (random(1)[0] ?? 0) % 100;
|
|
1167
|
+
await sleep(retryAfterMs ?? Math.min(100 * 2 ** retry + jitter, MAX_BACKOFF_MS));
|
|
1168
|
+
};
|
|
1169
|
+
const request = async (base, path, body) => {
|
|
1170
|
+
await acquire();
|
|
1171
|
+
const bound = timeoutSignal(timeoutMs, setTimer);
|
|
1172
|
+
try {
|
|
1173
|
+
let res;
|
|
1174
|
+
try {
|
|
1175
|
+
res = await fetchFn(`${base.replace(/\/$/, "")}${path}`, {
|
|
1176
|
+
...body === void 0 ? { method: "GET" } : {
|
|
1177
|
+
method: "POST",
|
|
1178
|
+
headers: { "content-type": "text/plain" },
|
|
1179
|
+
body
|
|
1180
|
+
},
|
|
1181
|
+
signal: bound.signal
|
|
1182
|
+
});
|
|
1183
|
+
} catch (error) {
|
|
1184
|
+
throw new EsploraError(`esplora ${base}${path}: request failed (${error instanceof Error ? error.name : "unknown"})`, true);
|
|
1185
|
+
}
|
|
1186
|
+
if (res.status === 429) return { throttled: res.headers };
|
|
1187
|
+
if (!res.ok) throw new EsploraError(`esplora ${base}${path}: ${res.status}`, res.status >= 500);
|
|
1188
|
+
const text = await res.text();
|
|
1189
|
+
try {
|
|
1190
|
+
return { value: JSON.parse(text) };
|
|
1191
|
+
} catch {
|
|
1192
|
+
return { value: text };
|
|
1193
|
+
}
|
|
1194
|
+
} finally {
|
|
1195
|
+
bound.cancel();
|
|
1196
|
+
release();
|
|
1197
|
+
}
|
|
1198
|
+
};
|
|
1199
|
+
const call = async (base, path, body, retry) => {
|
|
1200
|
+
const outcome = await request(base, path, body);
|
|
1201
|
+
if ("value" in outcome) return outcome.value;
|
|
1202
|
+
if (retry >= MAX_RETRIES) throw new EsploraError(`esplora ${base}${path}: 429 after ${MAX_RETRIES} retries`, true);
|
|
1203
|
+
await backoff(outcome.throttled, retry);
|
|
1204
|
+
return call(base, path, body, retry + 1);
|
|
1205
|
+
};
|
|
1206
|
+
const attempt = async (rest, path, body, last) => {
|
|
1207
|
+
const [base, ...next] = rest;
|
|
1208
|
+
if (base === void 0) throw last instanceof Error ? last : /* @__PURE__ */ new Error("all esplora endpoints failed");
|
|
1209
|
+
try {
|
|
1210
|
+
return await call(base, path, body, 0);
|
|
1211
|
+
} catch (error) {
|
|
1212
|
+
return attempt(next, path, body, error);
|
|
1213
|
+
}
|
|
1214
|
+
};
|
|
1215
|
+
return {
|
|
1216
|
+
get: async (path) => attempt(endpoints, path, void 0, void 0),
|
|
1217
|
+
post: async (path, body) => attempt(endpoints, path, body, void 0)
|
|
1218
|
+
};
|
|
1219
|
+
};
|
|
1220
|
+
const feeTiers = async (es) => {
|
|
1221
|
+
const res = await es.get("/fee-estimates");
|
|
1222
|
+
const estimates = isObject$3(res) ? res : {};
|
|
1223
|
+
const pick = (target) => Math.max(1, Math.ceil(Number(estimates[target] ?? 1)));
|
|
1224
|
+
return [
|
|
1225
|
+
{
|
|
1226
|
+
tier: "fast",
|
|
1227
|
+
satPerByte: pick("1")
|
|
1228
|
+
},
|
|
1229
|
+
{
|
|
1230
|
+
tier: "normal",
|
|
1231
|
+
satPerByte: pick("3")
|
|
1232
|
+
},
|
|
1233
|
+
{
|
|
1234
|
+
tier: "slow",
|
|
1235
|
+
satPerByte: pick("6")
|
|
1236
|
+
},
|
|
1237
|
+
{
|
|
1238
|
+
tier: "economy",
|
|
1239
|
+
satPerByte: pick("144")
|
|
1240
|
+
}
|
|
1241
|
+
];
|
|
1242
|
+
};
|
|
1243
|
+
const dustFor = (scriptType) => DUST[scriptType] ?? 546;
|
|
1244
|
+
const isFrozen = (value) => FROZEN_AMOUNTS.has(value);
|
|
1245
|
+
var BitcoinChainAdapter = class {
|
|
1246
|
+
/** Inputs for selectUTXO — the same TransactionInputUpdate objects added to the PSBT. */
|
|
1247
|
+
toInputs(utxos, fingerprint, pathOf, pubkeyOf, scriptOf, template, rawTxOf) {
|
|
1248
|
+
return utxos.filter((u) => u.status === "confirmed" && !isFrozen(u.value)).map((u) => {
|
|
1249
|
+
const pub = pubkeyOf(u);
|
|
1250
|
+
const entry = {
|
|
1251
|
+
txid: u.txid,
|
|
1252
|
+
index: u.vout,
|
|
1253
|
+
sequence: 4294967293
|
|
1254
|
+
};
|
|
1255
|
+
if (template !== "btc.bip44") entry.witnessUtxo = {
|
|
1256
|
+
amount: BigInt(u.value),
|
|
1257
|
+
script: scriptOf(u)
|
|
1258
|
+
};
|
|
1259
|
+
if (template === "btc.bip44") {
|
|
1260
|
+
const raw = rawTxOf === void 0 ? void 0 : rawTxOf(u);
|
|
1261
|
+
if (raw === void 0) throw new Error(`no raw transaction for bip44 input ${u.txid}`);
|
|
1262
|
+
entry.nonWitnessUtxo = raw;
|
|
1263
|
+
}
|
|
1264
|
+
if (template === "btc.bip86") {
|
|
1265
|
+
entry.tapInternalKey = pub;
|
|
1266
|
+
entry.tapBip32Derivation = [[pub, {
|
|
1267
|
+
hashes: [],
|
|
1268
|
+
der: {
|
|
1269
|
+
fingerprint,
|
|
1270
|
+
path: pathOf(u)
|
|
1271
|
+
}
|
|
1272
|
+
}]];
|
|
1273
|
+
} else {
|
|
1274
|
+
entry.bip32Derivation = [[pub, {
|
|
1275
|
+
fingerprint,
|
|
1276
|
+
path: pathOf(u)
|
|
1277
|
+
}]];
|
|
1278
|
+
if (template === "btc.bip49") entry.redeemScript = p2wpkh(pub).script;
|
|
1279
|
+
}
|
|
1280
|
+
return entry;
|
|
1281
|
+
});
|
|
1282
|
+
}
|
|
1283
|
+
buildPsbt(inputs, to, amount, feePerByte, changeAddress, network) {
|
|
1284
|
+
const selection = selectUTXO([...inputs], [{
|
|
1285
|
+
address: to,
|
|
1286
|
+
amount
|
|
1287
|
+
}], "default", {
|
|
1288
|
+
feePerByte,
|
|
1289
|
+
changeAddress,
|
|
1290
|
+
bip69: true,
|
|
1291
|
+
dust: BigInt(dustFor("p2wpkh")),
|
|
1292
|
+
network,
|
|
1293
|
+
createTx: true
|
|
1294
|
+
});
|
|
1295
|
+
if (selection === void 0 || selection.tx === void 0) throw new Error("insufficient confirmed utxo for the amount + fee");
|
|
1296
|
+
const wanted = new Set((selection.inputs ?? []).flatMap((sel) => {
|
|
1297
|
+
const raw = sel.txid;
|
|
1298
|
+
if (!(raw instanceof Uint8Array)) return [];
|
|
1299
|
+
const forward = hex.encode(raw);
|
|
1300
|
+
const reverse = hex.encode(Uint8Array.from(raw).reverse());
|
|
1301
|
+
return [`${forward}:${String(sel.index ?? -1)}`, `${reverse}:${String(sel.index ?? -1)}`];
|
|
1302
|
+
}));
|
|
1303
|
+
const chosen = inputs.filter((i) => wanted.has(`${String(i.txid)}:${String(i.index)}`));
|
|
1304
|
+
return {
|
|
1305
|
+
psbt: selection.tx.toPSBT(),
|
|
1306
|
+
inputs: chosen
|
|
1307
|
+
};
|
|
1308
|
+
}
|
|
1309
|
+
/** Fixed-input/output PSBT — the RBF/CPFP path, which chooses nothing itself. */
|
|
1310
|
+
buildExactPsbt(inputs, outputs, network) {
|
|
1311
|
+
const tx = new Transaction();
|
|
1312
|
+
for (const input of inputs) tx.addInput(input);
|
|
1313
|
+
for (const out of outputs) tx.addOutputAddress(out.address, out.amount, network);
|
|
1314
|
+
const tap = inputs.every((i) => i.tapInternalKey !== void 0);
|
|
1315
|
+
const vsize = Math.ceil(10.5 + inputs.length * (tap ? 57.5 : 68) + outputs.length * (tap ? 43 : 31));
|
|
1316
|
+
return {
|
|
1317
|
+
psbt: tx.toPSBT(),
|
|
1318
|
+
vsize
|
|
1319
|
+
};
|
|
1320
|
+
}
|
|
1321
|
+
};
|
|
1322
|
+
// src/requests/simulation.ts
|
|
1323
|
+
const SIMULATION_TIMEOUT_MS = 1e4;
|
|
1324
|
+
/** Asset ids compare by string, case-insensitively for EVM `0x` addresses. */
|
|
1325
|
+
const sameAsset = (a, b) => a === b || a.startsWith("0x") && a.toLowerCase() === b.toLowerCase();
|
|
1326
|
+
/** An asset amount that moved by more than this share of the old one is a changed simulation. */
|
|
1327
|
+
const SIMULATION_CHANGE_PERCENT = 5n;
|
|
1328
|
+
const covers = (changes, other) => changes.every((c) => other.some((o) => sameAsset(o.asset, c.asset)));
|
|
1329
|
+
const total = (changes, asset) => changes.filter((c) => sameAsset(c.asset, asset)).reduce((sum, c) => sum + BigInt(c.amount), 0n);
|
|
1330
|
+
/**
|
|
1331
|
+
* Whether a re-simulation differs enough from the first outcome to be shown again: a different
|
|
1332
|
+
* status, an asset appearing or disappearing, or an amount that moved by more than
|
|
1333
|
+
* {@link SIMULATION_CHANGE_PERCENT} percent of the old one. Two outcomes failing or missing the
|
|
1334
|
+
* same way count as unchanged.
|
|
1335
|
+
*/
|
|
1336
|
+
function simulationChanged(before, after) {
|
|
1337
|
+
if (before.status !== after.status) return true;
|
|
1338
|
+
if (before.status !== "success" || after.status !== "success") return false;
|
|
1339
|
+
if (!covers(before.changes, after.changes) || !covers(after.changes, before.changes)) return true;
|
|
1340
|
+
return before.changes.some(({ asset }) => {
|
|
1341
|
+
const prior = total(before.changes, asset);
|
|
1342
|
+
const next = total(after.changes, asset);
|
|
1343
|
+
const diff = prior > next ? prior - next : next - prior;
|
|
1344
|
+
const base = prior < 0n ? -prior : prior;
|
|
1345
|
+
return diff * 100n > base * SIMULATION_CHANGE_PERCENT;
|
|
1346
|
+
});
|
|
1347
|
+
}
|
|
1348
|
+
const noop = () => void 0;
|
|
1349
|
+
/**
|
|
1350
|
+
* Runs a simulation under the 10 s bound of the injected timer. A throw from `run` and the timeout
|
|
1351
|
+
* are `unavailable`; the timer is always cancelled.
|
|
1352
|
+
*/
|
|
1353
|
+
async function boundedSimulation(run, setTimer) {
|
|
1354
|
+
const stopTimer = { cancel: noop };
|
|
1355
|
+
const timeout = new Promise((resolve) => {
|
|
1356
|
+
stopTimer.cancel = setTimer(SIMULATION_TIMEOUT_MS, () => {
|
|
1357
|
+
resolve({
|
|
1358
|
+
status: "unavailable",
|
|
1359
|
+
error: "timeout"
|
|
1360
|
+
});
|
|
1361
|
+
});
|
|
1362
|
+
});
|
|
1363
|
+
const bounded = async () => {
|
|
1364
|
+
try {
|
|
1365
|
+
return await run();
|
|
1366
|
+
} catch (error) {
|
|
1367
|
+
return {
|
|
1368
|
+
status: "unavailable",
|
|
1369
|
+
error: errorMessage(error)
|
|
1370
|
+
};
|
|
1371
|
+
}
|
|
1372
|
+
};
|
|
1373
|
+
try {
|
|
1374
|
+
return await Promise.race([bounded(), timeout]);
|
|
1375
|
+
} finally {
|
|
1376
|
+
stopTimer.cancel();
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
// src/requests/risk.ts
|
|
1380
|
+
const byDanger = (findings) => [...findings].sort((a, b) => Number(b.level === "danger") - Number(a.level === "danger"));
|
|
1381
|
+
/** The finding for a browser origin's phishing status, if any; `blocked` never reaches a request. */
|
|
1382
|
+
function originRisk(status) {
|
|
1383
|
+
if (status === "trusted") return [{
|
|
1384
|
+
code: "phishing-origin",
|
|
1385
|
+
level: "danger"
|
|
1386
|
+
}];
|
|
1387
|
+
return status === "unchecked" ? [{
|
|
1388
|
+
code: "phishing-unchecked",
|
|
1389
|
+
level: "warning"
|
|
1390
|
+
}] : [];
|
|
1391
|
+
}
|
|
1392
|
+
/** `findings` plus `extra`, deduplicated by code, `danger` first. */
|
|
1393
|
+
function mergeRisk(findings, extra) {
|
|
1394
|
+
const byCode = /* @__PURE__ */ new Map();
|
|
1395
|
+
for (const finding of [...findings, ...extra]) byCode.set(finding.code, finding);
|
|
1396
|
+
return byDanger([...byCode.values()]);
|
|
1397
|
+
}
|
|
1398
|
+
/**
|
|
1399
|
+
* Findings for the approvals a transaction grants: an operator approved for a whole collection is a
|
|
1400
|
+
* `danger`; a granted unlimited allowance is a `warning`. Revocations and reductions raise
|
|
1401
|
+
* nothing.
|
|
1402
|
+
*/
|
|
1403
|
+
function assessApprovals(intent) {
|
|
1404
|
+
const found = /* @__PURE__ */ new Map();
|
|
1405
|
+
for (const change of intent.approvals) if (change.kind === "operator") {
|
|
1406
|
+
if (change.approved) found.set("collection-approval", {
|
|
1407
|
+
code: "collection-approval",
|
|
1408
|
+
level: "danger"
|
|
1409
|
+
});
|
|
1410
|
+
} else if (change.change !== "decrease" && change.unlimited) found.set("unlimited-approval", {
|
|
1411
|
+
code: "unlimited-approval",
|
|
1412
|
+
level: "warning"
|
|
1413
|
+
});
|
|
1414
|
+
return byDanger([...found.values()]);
|
|
1415
|
+
}
|
|
1416
|
+
const PERMIT_MAX_LIFETIME_MS = 2592e6;
|
|
1417
|
+
/**
|
|
1418
|
+
* Findings for what a signed permit grants: any non-revoking allowance is a `warning`, an unlimited
|
|
1419
|
+
* one a `danger`, and a Permit2 allowance that lasts more than 30 days from `now` a `danger`.
|
|
1420
|
+
*/
|
|
1421
|
+
function assessPermits(intent, now) {
|
|
1422
|
+
const found = /* @__PURE__ */ new Map();
|
|
1423
|
+
for (const change of intent.approvals) {
|
|
1424
|
+
if (change.kind !== "allowance" || change.amount.amount === "0") continue;
|
|
1425
|
+
found.set("permit-approval", {
|
|
1426
|
+
code: "permit-approval",
|
|
1427
|
+
level: "warning"
|
|
1428
|
+
});
|
|
1429
|
+
if (change.unlimited) found.set("permit-unlimited", {
|
|
1430
|
+
code: "permit-unlimited",
|
|
1431
|
+
level: "danger"
|
|
1432
|
+
});
|
|
1433
|
+
if (change.via === "permit2" && change.change === "set" && change.expiration !== void 0 && change.expiration * 1e3 > now + PERMIT_MAX_LIFETIME_MS) found.set("permit-long-lived", {
|
|
1434
|
+
code: "permit-long-lived",
|
|
1435
|
+
level: "danger"
|
|
1436
|
+
});
|
|
1437
|
+
}
|
|
1438
|
+
return byDanger([...found.values()]);
|
|
1439
|
+
}
|
|
1440
|
+
/**
|
|
1441
|
+
* Findings for a recognized Seaport order: an order whose `offer` gives up items without any
|
|
1442
|
+
* consideration paying the offerer is the zero-price-listing phishing shape (`danger`), and an
|
|
1443
|
+
* `offerer` other than the signing account is a `warning`.
|
|
1444
|
+
*/
|
|
1445
|
+
function assessSeaport(order, signer) {
|
|
1446
|
+
if (order === void 0) return [];
|
|
1447
|
+
const found = /* @__PURE__ */ new Map();
|
|
1448
|
+
const paid = order.consideration.some((item) => item.recipient.toLowerCase() === order.offerer.toLowerCase() && (BigInt(item.startAmount.amount) > 0n || BigInt(item.endAmount.amount) > 0n));
|
|
1449
|
+
if (order.offer.length > 0 && !paid) found.set("order-receives-nothing", {
|
|
1450
|
+
code: "order-receives-nothing",
|
|
1451
|
+
level: "danger"
|
|
1452
|
+
});
|
|
1453
|
+
if (order.offerer.toLowerCase() !== signer.toLowerCase()) found.set("order-offerer-mismatch", {
|
|
1454
|
+
code: "order-offerer-mismatch",
|
|
1455
|
+
level: "warning"
|
|
1456
|
+
});
|
|
1457
|
+
return byDanger([...found.values()]);
|
|
1458
|
+
}
|
|
1459
|
+
/**
|
|
1460
|
+
* Findings for a recognized Safe transaction: a `delegatecall` into a contract that is not a
|
|
1461
|
+
* canonical MultiSendCallOnly is the multisig-hijack phishing shape (`danger`), a non-zero gas
|
|
1462
|
+
* refund is a `warning`, and every decoded inner call's approvals are assessed too.
|
|
1463
|
+
*/
|
|
1464
|
+
function assessSafe(safe) {
|
|
1465
|
+
if (safe === void 0) return [];
|
|
1466
|
+
const found = /* @__PURE__ */ new Map();
|
|
1467
|
+
for (const finding of safe.calls.flatMap((call) => assessApprovals(call))) found.set(finding.code, finding);
|
|
1468
|
+
if (safe.operation === "delegatecall" && !SAFE_MULTISEND_CALL_ONLY.has(safe.to.toLowerCase())) found.set("safe-delegatecall", {
|
|
1469
|
+
code: "safe-delegatecall",
|
|
1470
|
+
level: "danger"
|
|
1471
|
+
});
|
|
1472
|
+
if (safe.refund !== void 0) found.set("safe-gas-refund", {
|
|
1473
|
+
code: "safe-gas-refund",
|
|
1474
|
+
level: "warning"
|
|
1475
|
+
});
|
|
1476
|
+
return byDanger([...found.values()]);
|
|
1477
|
+
}
|
|
1478
|
+
/**
|
|
1479
|
+
* Findings for the inputs a dApp PSBT asks the wallet to sign. A `SINGLE|ANYONECANPAY` input binds
|
|
1480
|
+
* only its same-index output, so anyone can change the rest of the transaction: `danger`. Until
|
|
1481
|
+
* inscription data exists the heuristic is the coin-selection freeze rule (546 and 330 sat
|
|
1482
|
+
* outputs): such an input is a `warning` when it is signed as a listing (the sighash that fits
|
|
1483
|
+
* selling it) and a `danger` otherwise.
|
|
1484
|
+
*/
|
|
1485
|
+
function assessBitcoinPsbts(inputs) {
|
|
1486
|
+
const found = /* @__PURE__ */ new Map();
|
|
1487
|
+
if (inputs.some((i) => i.sigHash === "SINGLE|ANYONECANPAY")) found.set("bitcoin-sighash-single", {
|
|
1488
|
+
code: "bitcoin-sighash-single",
|
|
1489
|
+
level: "danger"
|
|
1490
|
+
});
|
|
1491
|
+
const postage = inputs.filter((i) => isFrozen(i.value));
|
|
1492
|
+
if (postage.length > 0) found.set("bitcoin-inscription-input", {
|
|
1493
|
+
code: "bitcoin-inscription-input",
|
|
1494
|
+
level: postage.some((i) => i.sigHash !== "SINGLE|ANYONECANPAY") ? "danger" : "warning"
|
|
1495
|
+
});
|
|
1496
|
+
return byDanger([...found.values()]);
|
|
1497
|
+
}
|
|
1498
|
+
const LOCAL_HOSTS = /* @__PURE__ */ new Set([
|
|
1499
|
+
"localhost",
|
|
1500
|
+
"127.0.0.1",
|
|
1501
|
+
"[::1]"
|
|
1502
|
+
]);
|
|
1503
|
+
/** `scheme`, `host` (IPv6 keeps its brackets) of a `scheme://host[:port]` origin. */
|
|
1504
|
+
const originParts = (origin) => {
|
|
1505
|
+
const sep = origin.indexOf("://");
|
|
1506
|
+
const rest = origin.slice(sep + 3);
|
|
1507
|
+
const end = rest.startsWith("[") ? rest.indexOf("]") + 1 : rest.lastIndexOf(":");
|
|
1508
|
+
return {
|
|
1509
|
+
scheme: sep === -1 ? "" : origin.slice(0, sep).toLowerCase(),
|
|
1510
|
+
host: (end > 0 ? rest.slice(0, end) : rest).toLowerCase()
|
|
1511
|
+
};
|
|
1512
|
+
};
|
|
1513
|
+
const isLocalHost = (host) => LOCAL_HOSTS.has(host) || host.endsWith(".localhost");
|
|
1514
|
+
/**
|
|
1515
|
+
* What a Sign-In with Ethereum/Solana message adds to a request from `origin`: a message for
|
|
1516
|
+
* another domain is refused (`reject`) in production and a `danger` on a local development page;
|
|
1517
|
+
* the signing address must be the signer; an expired or not-yet-valid window and a text that only
|
|
1518
|
+
* resembles a sign-in message are warnings.
|
|
1519
|
+
*/
|
|
1520
|
+
function assessSignIn(input) {
|
|
1521
|
+
const { signIn, origin, signer, family, now } = input;
|
|
1522
|
+
if (signIn.status === "malformed") return { risk: [{
|
|
1523
|
+
code: "sign-in-malformed",
|
|
1524
|
+
level: "warning"
|
|
1525
|
+
}] };
|
|
1526
|
+
const { fields } = signIn;
|
|
1527
|
+
const { scheme, host } = originParts(origin);
|
|
1528
|
+
const developer = isLocalHost(host);
|
|
1529
|
+
let findings;
|
|
1530
|
+
try {
|
|
1531
|
+
findings = checkOrigin(createMessage(fields), origin, developer ? {
|
|
1532
|
+
allowedSchemes: ["https", "http"],
|
|
1533
|
+
defaultScheme: scheme,
|
|
1534
|
+
developerMode: true
|
|
1535
|
+
} : {});
|
|
1536
|
+
} catch (error) {
|
|
1537
|
+
if (error instanceof SiwxError && error.code === "InvalidOrigin") return {
|
|
1538
|
+
reject: "the page origin is not a valid web origin",
|
|
1539
|
+
risk: []
|
|
1540
|
+
};
|
|
1541
|
+
throw error;
|
|
1542
|
+
}
|
|
1543
|
+
if (findings.some((f) => f.severity === "reject")) return {
|
|
1544
|
+
reject: `the sign-in message is for ${fields.domain}, not this page`,
|
|
1545
|
+
risk: []
|
|
1546
|
+
};
|
|
1547
|
+
const found = /* @__PURE__ */ new Map();
|
|
1548
|
+
const add = (code, level) => {
|
|
1549
|
+
found.set(code, {
|
|
1550
|
+
code,
|
|
1551
|
+
level
|
|
1552
|
+
});
|
|
1553
|
+
};
|
|
1554
|
+
for (const finding of findings) if (finding.code === "PortMismatch") add("sign-in-port-mismatch", "warning");
|
|
1555
|
+
else add("sign-in-domain-mismatch", "danger");
|
|
1556
|
+
if (!(family === "evm" ? fields.address.toLowerCase() === signer.toLowerCase() : fields.address === signer)) add("sign-in-address-mismatch", "danger");
|
|
1557
|
+
const expires = fields.expirationTime === void 0 ? void 0 : parseTimestamp(fields.expirationTime);
|
|
1558
|
+
if (expires !== void 0 && expires.epochMs < now) add("sign-in-expired", "warning");
|
|
1559
|
+
const notBefore = fields.notBefore === void 0 ? void 0 : parseTimestamp(fields.notBefore);
|
|
1560
|
+
if (notBefore !== void 0 && notBefore.epochMs > now) add("sign-in-not-yet-valid", "warning");
|
|
1561
|
+
return { risk: byDanger([...found.values()]) };
|
|
1562
|
+
}
|
|
1563
|
+
/** EVM addresses compare without the `0x` prefix and case-insensitively. */
|
|
1564
|
+
const comparable = (family, address) => family === "evm" ? address.replace(/^0x/i, "").toLowerCase() : address;
|
|
1565
|
+
const looksLike = (a, b) => a !== b && a.length >= 8 && b.length >= 8 && a.slice(0, 4) === b.slice(0, 4) && a.slice(-4) === b.slice(-4);
|
|
1566
|
+
/** Findings for every recipient of one request, deduplicated, `danger` first. */
|
|
1567
|
+
function assessRecipients(family, recipients, known) {
|
|
1568
|
+
const knownSet = new Set(known.map((a) => comparable(family, a)));
|
|
1569
|
+
const found = /* @__PURE__ */ new Map();
|
|
1570
|
+
for (const recipient of recipients) {
|
|
1571
|
+
const candidate = comparable(family, recipient);
|
|
1572
|
+
if (knownSet.has(candidate)) continue;
|
|
1573
|
+
found.set("first-recipient", {
|
|
1574
|
+
code: "first-recipient",
|
|
1575
|
+
level: "warning"
|
|
1576
|
+
});
|
|
1577
|
+
if ([...knownSet].some((k) => looksLike(candidate, k))) found.set("address-poisoning", {
|
|
1578
|
+
code: "address-poisoning",
|
|
1579
|
+
level: "danger"
|
|
1580
|
+
});
|
|
1581
|
+
}
|
|
1582
|
+
return byDanger([...found.values()]);
|
|
1583
|
+
}
|
|
1584
|
+
const declaredOutflow = (intent, asset) => intent.outflows.filter((flow) => sameAsset(flow.amount.asset, asset)).reduce((sum, flow) => sum + BigInt(flow.amount.amount), 0n);
|
|
1585
|
+
/**
|
|
1586
|
+
* What a simulation adds to a request. `unavailable` blocks silent approval; `reverted` is a
|
|
1587
|
+
* danger; an outflow above what the decode declares for that asset is a danger too — but only
|
|
1588
|
+
* against a decode that is not `opaque`, and never for Solana lamports (fees and rent always exceed
|
|
1589
|
+
* the declared amount).
|
|
1590
|
+
*/
|
|
1591
|
+
function assessSimulation(intent, outcome) {
|
|
1592
|
+
if (outcome === void 0) return {
|
|
1593
|
+
checks: [],
|
|
1594
|
+
risk: []
|
|
1595
|
+
};
|
|
1596
|
+
if (outcome.status === "unavailable") return {
|
|
1597
|
+
checks: ["simulation-unavailable"],
|
|
1598
|
+
risk: []
|
|
1599
|
+
};
|
|
1600
|
+
if (outcome.status === "reverted") return {
|
|
1601
|
+
checks: [],
|
|
1602
|
+
risk: [{
|
|
1603
|
+
code: "simulation-reverted",
|
|
1604
|
+
level: "danger"
|
|
1605
|
+
}]
|
|
1606
|
+
};
|
|
1607
|
+
return {
|
|
1608
|
+
checks: [],
|
|
1609
|
+
risk: intent.verifiability !== "opaque" && outcome.changes.some((change) => {
|
|
1610
|
+
const amount = BigInt(change.amount);
|
|
1611
|
+
return amount < 0n && change.asset !== SOLANA_NATIVE_ASSET && -amount > declaredOutflow(intent, change.asset);
|
|
1612
|
+
}) ? [{
|
|
1613
|
+
code: "simulation-mismatch",
|
|
1614
|
+
level: "danger"
|
|
1615
|
+
}] : []
|
|
1616
|
+
};
|
|
1617
|
+
}
|
|
1618
|
+
/**
|
|
1619
|
+
* A token on `chainId` that reports the symbol of a different, built-in token of the same chain —
|
|
1620
|
+
* the shape of a lookalike token. Symbols compare case-insensitively.
|
|
1621
|
+
*/
|
|
1622
|
+
function impersonatesBuiltIn(chainId, address, symbol) {
|
|
1623
|
+
const wanted = symbol.toLowerCase();
|
|
1624
|
+
return Object.entries(evmTokenTable[String(chainId)] ?? {}).some(([known, token]) => known.toLowerCase() !== address.toLowerCase() && token.symbol.toLowerCase() === wanted);
|
|
1625
|
+
}
|
|
1626
|
+
// src/requests/sign-log.ts
|
|
1627
|
+
const SIGN_LOG_LIMIT = 1e3;
|
|
1628
|
+
const COLLECTION = "sign-log";
|
|
1629
|
+
const isObject$2 = (v) => typeof v === "object" && v !== null;
|
|
1630
|
+
const METHODS = /* @__PURE__ */ new Set([
|
|
1631
|
+
"send",
|
|
1632
|
+
"speed-up",
|
|
1633
|
+
"cancel",
|
|
1634
|
+
"cpfp",
|
|
1635
|
+
"pay",
|
|
1636
|
+
"zap",
|
|
1637
|
+
"evm-sign",
|
|
1638
|
+
"nostr-sign",
|
|
1639
|
+
"webln-invoice",
|
|
1640
|
+
"watch-asset",
|
|
1641
|
+
"solana-sign",
|
|
1642
|
+
"bitcoin-sign",
|
|
1643
|
+
"spark-deposit",
|
|
1644
|
+
"spark-exit"
|
|
1645
|
+
]);
|
|
1646
|
+
const OUTCOMES = /* @__PURE__ */ new Set([
|
|
1647
|
+
"submitted",
|
|
1648
|
+
"rejected",
|
|
1649
|
+
"failed",
|
|
1650
|
+
"expired",
|
|
1651
|
+
"invalidated"
|
|
1652
|
+
]);
|
|
1653
|
+
const FAMILIES = /* @__PURE__ */ new Set([
|
|
1654
|
+
"evm",
|
|
1655
|
+
"solana",
|
|
1656
|
+
"bitcoin"
|
|
1657
|
+
]);
|
|
1658
|
+
const isAccount = (value) => {
|
|
1659
|
+
if (!isObject$2(value)) return false;
|
|
1660
|
+
if (value["kind"] === "hd") return typeof value["walletId"] === "string" && typeof value["groupIndex"] === "number" && typeof value["template"] === "string";
|
|
1661
|
+
if (value["kind"] === "imported") return typeof value["keyId"] === "string" && FAMILIES.has(value["family"]);
|
|
1662
|
+
if (value["kind"] === "derived") return typeof value["walletId"] === "string" && typeof value["index"] === "number";
|
|
1663
|
+
if (value["kind"] === void 0 && typeof value["walletId"] === "string" && typeof value["groupIndex"] === "number" && typeof value["address"] === "string") return true;
|
|
1664
|
+
return value["kind"] === void 0 && typeof value["walletId"] === "string" && typeof value["groupIndex"] === "number" && typeof value["network"] === "string";
|
|
1665
|
+
};
|
|
1666
|
+
const isOrigin = (value) => isObject$2(value) && (value["kind"] === "internal" || value["kind"] === "browser" && typeof value["origin"] === "string");
|
|
1667
|
+
const isEntry = (value) => isObject$2(value) && typeof value["id"] === "string" && typeof value["at"] === "number" && isOrigin(value["origin"]) && METHODS.has(value["method"]) && OUTCOMES.has(value["outcome"]) && isAccount(value["account"]);
|
|
1668
|
+
/** Sortable key: time first, request id as the tiebreak. */
|
|
1669
|
+
const keyOf = (entry) => `${String(entry.at).padStart(16, "0")}-${entry.id}`;
|
|
1670
|
+
function createSignLog(logger) {
|
|
1671
|
+
let store;
|
|
1672
|
+
return {
|
|
1673
|
+
open: (next) => {
|
|
1674
|
+
store = next;
|
|
1675
|
+
},
|
|
1676
|
+
close: () => {
|
|
1677
|
+
store = void 0;
|
|
1678
|
+
},
|
|
1679
|
+
append: async (entry) => {
|
|
1680
|
+
const current = store;
|
|
1681
|
+
if (current === void 0) {
|
|
1682
|
+
logger.warn(`sign log entry for request ${entry.id} (${entry.outcome}) not written: vault locked`);
|
|
1683
|
+
return;
|
|
1684
|
+
}
|
|
1685
|
+
const collection = current.collection(COLLECTION);
|
|
1686
|
+
await collection.put(keyOf(entry), new TextEncoder().encode(JSON.stringify(entry)));
|
|
1687
|
+
const keys = [...await collection.list()].sort();
|
|
1688
|
+
await Promise.all(keys.slice(0, Math.max(0, keys.length - SIGN_LOG_LIMIT)).map(async (k) => collection.delete(k)));
|
|
1689
|
+
},
|
|
1690
|
+
list: async () => {
|
|
1691
|
+
if (store === void 0) return [];
|
|
1692
|
+
const collection = store.collection(COLLECTION);
|
|
1693
|
+
const keys = [...await collection.list()].sort();
|
|
1694
|
+
const rows = await Promise.all(keys.map(async (k) => collection.get(k)));
|
|
1695
|
+
const entries = [];
|
|
1696
|
+
for (const raw of rows) {
|
|
1697
|
+
if (raw === void 0) continue;
|
|
1698
|
+
const parsed = JSON.parse(new TextDecoder().decode(raw));
|
|
1699
|
+
if (isEntry(parsed)) entries.push(parsed);
|
|
1700
|
+
}
|
|
1701
|
+
return entries.reverse();
|
|
1702
|
+
},
|
|
1703
|
+
clear: async () => {
|
|
1704
|
+
if (store === void 0) return;
|
|
1705
|
+
const collection = store.collection(COLLECTION);
|
|
1706
|
+
const keys = [...await collection.list()].sort();
|
|
1707
|
+
await Promise.all(keys.map(async (k) => collection.delete(k)));
|
|
1708
|
+
}
|
|
1709
|
+
};
|
|
1710
|
+
}
|
|
1711
|
+
// src/requests/controller.ts
|
|
1712
|
+
/** A token the page asked to watch whose on-chain metadata cannot be shown; the dApp's bad input. */
|
|
1713
|
+
var InvalidTokenError = class extends Error {
|
|
1714
|
+
constructor(message) {
|
|
1715
|
+
super(message);
|
|
1716
|
+
this.name = "InvalidTokenError";
|
|
1717
|
+
}
|
|
1718
|
+
};
|
|
1719
|
+
/** A Sign-In with X message for another domain than the page that asked for the signature. */
|
|
1720
|
+
var SignInOriginError = class extends Error {
|
|
1721
|
+
constructor(message) {
|
|
1722
|
+
super(message);
|
|
1723
|
+
this.name = "SignInOriginError";
|
|
1724
|
+
}
|
|
1725
|
+
};
|
|
1726
|
+
/** Message bytes that cannot be shown as text for a group that did not opt in to blind signing. */
|
|
1727
|
+
var BlindSigningDisabledError = class extends Error {
|
|
1728
|
+
constructor() {
|
|
1729
|
+
super(BLIND_SIGNING_MESSAGE);
|
|
1730
|
+
this.name = "BlindSigningDisabledError";
|
|
1731
|
+
}
|
|
1732
|
+
};
|
|
1733
|
+
/**
|
|
1734
|
+
* The approval-time re-simulation differs from the prepared outcome; the request went back to
|
|
1735
|
+
* `awaiting-approval` with the fresh result and stays approvable.
|
|
1736
|
+
*/
|
|
1737
|
+
var SimulationChangedError = class extends Error {
|
|
1738
|
+
constructor() {
|
|
1739
|
+
super("the simulation changed while the request waited — review it again");
|
|
1740
|
+
this.name = "SimulationChangedError";
|
|
1741
|
+
}
|
|
1742
|
+
};
|
|
1743
|
+
/** A request that ended without a result: `stage` says how, `message` is the failure if any. */
|
|
1744
|
+
var RequestEndedError = class extends Error {
|
|
1745
|
+
stage;
|
|
1746
|
+
constructor(stage, message) {
|
|
1747
|
+
super(message ?? `request ${stage}`);
|
|
1748
|
+
this.name = "RequestEndedError";
|
|
1749
|
+
this.stage = stage;
|
|
1750
|
+
}
|
|
1751
|
+
};
|
|
1752
|
+
/** The origin already has a request in flight; a dApp gets one at a time. */
|
|
1753
|
+
var OriginBusyError = class extends Error {
|
|
1754
|
+
constructor(origin) {
|
|
1755
|
+
super(`${origin} already has an unfinished request`);
|
|
1756
|
+
this.name = "OriginBusyError";
|
|
1757
|
+
}
|
|
1758
|
+
};
|
|
1759
|
+
/** Requests expire this long after creation. */
|
|
1760
|
+
const REQUEST_TTL_MS = 6e5;
|
|
1761
|
+
/** A simulation older than this is re-run at approval before any signing. */
|
|
1762
|
+
const RESIMULATE_AFTER_MS = 6e4;
|
|
1763
|
+
const originKey = (origin) => `origin:${origin.origin}`;
|
|
1764
|
+
/** A message request's content: its UTF-8 text with any sign-in parse, else the raw bytes. */
|
|
1765
|
+
const messageContent = (message, signIn) => {
|
|
1766
|
+
const text = utf8Text(message);
|
|
1767
|
+
if (text === void 0) return {
|
|
1768
|
+
kind: "bytes",
|
|
1769
|
+
hex: `0x${bytesToHex(message)}`
|
|
1770
|
+
};
|
|
1771
|
+
return signIn === void 0 ? {
|
|
1772
|
+
kind: "text",
|
|
1773
|
+
text
|
|
1774
|
+
} : {
|
|
1775
|
+
kind: "text",
|
|
1776
|
+
text,
|
|
1777
|
+
signIn
|
|
1778
|
+
};
|
|
1779
|
+
};
|
|
1780
|
+
const solanaIntent = (account, network, message) => {
|
|
1781
|
+
try {
|
|
1782
|
+
const request = normalizeSolana({
|
|
1783
|
+
kind: "solana.transaction",
|
|
1784
|
+
network,
|
|
1785
|
+
account: {
|
|
1786
|
+
kind: "hd",
|
|
1787
|
+
walletId: account.walletId,
|
|
1788
|
+
groupIndex: account.groupIndex,
|
|
1789
|
+
template: "solana.bip44-change"
|
|
1790
|
+
},
|
|
1791
|
+
message
|
|
1792
|
+
}, account.address);
|
|
1793
|
+
return request.kind === "solana.transaction" ? decodeSolana(request, account.address, void 0) : { error: "not a transaction" };
|
|
1794
|
+
} catch (error) {
|
|
1795
|
+
return { error: errorMessage(error) };
|
|
1796
|
+
}
|
|
1797
|
+
};
|
|
1798
|
+
/** Nothing declared and nothing checkable: what a transaction that did not decode counts as. */
|
|
1799
|
+
const OPAQUE_INTENT = {
|
|
1800
|
+
outflows: [],
|
|
1801
|
+
verifiability: "opaque"
|
|
1802
|
+
};
|
|
1803
|
+
/**
|
|
1804
|
+
* Merges a simulation's assessment into a built request and keeps the pre-simulation checks, risk
|
|
1805
|
+
* and intent on `resimulation`, so an approval-time re-run assesses the same way.
|
|
1806
|
+
*/
|
|
1807
|
+
const withSimulation = (built, intent, simulation, resimulate) => {
|
|
1808
|
+
if (simulation === void 0) return built;
|
|
1809
|
+
const assessed = assessSimulation(intent, simulation);
|
|
1810
|
+
return {
|
|
1811
|
+
...built,
|
|
1812
|
+
checks: collectChecks([...built.checks, ...assessed.checks]),
|
|
1813
|
+
risk: mergeRisk(built.risk, assessed.risk),
|
|
1814
|
+
simulation,
|
|
1815
|
+
...resimulate === void 0 ? {} : { resimulation: {
|
|
1816
|
+
intent,
|
|
1817
|
+
checks: built.checks,
|
|
1818
|
+
risk: built.risk,
|
|
1819
|
+
run: resimulate
|
|
1820
|
+
} }
|
|
1821
|
+
};
|
|
1822
|
+
};
|
|
1823
|
+
/** The input's browser origin, when it carries one (`evm-sign`/`nostr-sign`/`webln-invoice`/`pay`). */
|
|
1824
|
+
const browserOriginOf = (input) => "origin" in input ? input.origin : void 0;
|
|
1825
|
+
const LIVE = /* @__PURE__ */ new Set(["awaiting-approval", "signing"]);
|
|
1826
|
+
var RequestController = class extends Controller {
|
|
1827
|
+
options;
|
|
1828
|
+
entries = /* @__PURE__ */ new Map();
|
|
1829
|
+
log;
|
|
1830
|
+
settlers = /* @__PURE__ */ new Map();
|
|
1831
|
+
/** Original transaction id → the unfinished request replacing or accelerating it. */
|
|
1832
|
+
targets = /* @__PURE__ */ new Map();
|
|
1833
|
+
locked = true;
|
|
1834
|
+
/** Bumped on every unlock and lock so work that outlives a session never touches the next one. */
|
|
1835
|
+
session = 0;
|
|
1836
|
+
constructor(options) {
|
|
1837
|
+
super({
|
|
1838
|
+
name: "requests",
|
|
1839
|
+
defaultState: () => ({ requests: {} })
|
|
1840
|
+
});
|
|
1841
|
+
this.options = options;
|
|
1842
|
+
this.log = createSignLog(options.logger);
|
|
1843
|
+
}
|
|
1844
|
+
async init() {
|
|
1845
|
+
this.session += 1;
|
|
1846
|
+
this.locked = false;
|
|
1847
|
+
this.entries.clear();
|
|
1848
|
+
this.targets.clear();
|
|
1849
|
+
this.settlers.clear();
|
|
1850
|
+
this.update(() => ({ requests: {} }));
|
|
1851
|
+
this.log.open(await this.options.openStore());
|
|
1852
|
+
}
|
|
1853
|
+
async destroy() {
|
|
1854
|
+
this.lock();
|
|
1855
|
+
await Promise.resolve();
|
|
1856
|
+
}
|
|
1857
|
+
/** Locking is not consent: every unfinished request becomes `invalidated` and frees its resources. */
|
|
1858
|
+
lock() {
|
|
1859
|
+
this.session += 1;
|
|
1860
|
+
this.locked = true;
|
|
1861
|
+
for (const [id, request] of Object.entries(this.getState().requests)) if (LIVE.has(request.stage)) this.finish(id, "invalidated");
|
|
1862
|
+
this.log.close();
|
|
1863
|
+
}
|
|
1864
|
+
/** A page navigated away, was revoked or changed network: its unfinished requests are void. */
|
|
1865
|
+
invalidateOrigin(origin) {
|
|
1866
|
+
for (const [id, request] of Object.entries(this.getState().requests)) if (LIVE.has(request.stage) && request.origin.kind === "browser" && request.origin.origin === origin) this.finish(id, "invalidated");
|
|
1867
|
+
}
|
|
1868
|
+
/** The signature record, newest first. */
|
|
1869
|
+
async signLog() {
|
|
1870
|
+
return this.log.list();
|
|
1871
|
+
}
|
|
1872
|
+
async clearSignLog() {
|
|
1873
|
+
await this.log.clear();
|
|
1874
|
+
}
|
|
1875
|
+
async prepare(input) {
|
|
1876
|
+
if (this.locked) throw new Error("requests require an unlocked vault");
|
|
1877
|
+
const { session } = this;
|
|
1878
|
+
const id = newRequestId(this.options.random);
|
|
1879
|
+
const target = "txId" in input ? input.txId : void 0;
|
|
1880
|
+
const browserOrigin = browserOriginOf(input);
|
|
1881
|
+
const originStatus = browserOrigin === void 0 ? "clear" : this.options.phishing.check(browserOrigin.origin);
|
|
1882
|
+
if (originStatus === "blocked") throw new Error(PHISHING_BLOCKED_MESSAGE);
|
|
1883
|
+
if (browserOrigin !== void 0) {
|
|
1884
|
+
const key = originKey(browserOrigin);
|
|
1885
|
+
if (this.targets.has(key)) throw new OriginBusyError(browserOrigin.origin);
|
|
1886
|
+
this.targets.set(key, id);
|
|
1887
|
+
}
|
|
1888
|
+
if (target !== void 0) {
|
|
1889
|
+
if (this.targets.has(target)) throw new Error(`transaction ${target} already has an unfinished replacement request`);
|
|
1890
|
+
this.targets.set(target, id);
|
|
1891
|
+
}
|
|
1892
|
+
let built;
|
|
1893
|
+
try {
|
|
1894
|
+
built = await this.build(input, id);
|
|
1895
|
+
} catch (error) {
|
|
1896
|
+
this.unclaim(id);
|
|
1897
|
+
throw error;
|
|
1898
|
+
}
|
|
1899
|
+
if (session !== this.session) {
|
|
1900
|
+
built.run.release();
|
|
1901
|
+
this.unclaim(id);
|
|
1902
|
+
throw new Error("the vault was locked while the request was being prepared");
|
|
1903
|
+
}
|
|
1904
|
+
const { checks } = built;
|
|
1905
|
+
const createdAt = this.options.now();
|
|
1906
|
+
const request = {
|
|
1907
|
+
id,
|
|
1908
|
+
origin: browserOrigin ?? { kind: "internal" },
|
|
1909
|
+
method: input.method,
|
|
1910
|
+
account: built.account,
|
|
1911
|
+
network: built.network,
|
|
1912
|
+
...target === void 0 ? {} : { target },
|
|
1913
|
+
stage: "awaiting-approval",
|
|
1914
|
+
display: built.display,
|
|
1915
|
+
verification: checks.length > 0 ? "unverifiable" : "verified",
|
|
1916
|
+
checks,
|
|
1917
|
+
risk: mergeRisk(built.risk, originRisk(originStatus)),
|
|
1918
|
+
...built.simulation === void 0 ? {} : {
|
|
1919
|
+
simulation: built.simulation,
|
|
1920
|
+
simulatedAt: createdAt
|
|
1921
|
+
},
|
|
1922
|
+
createdAt,
|
|
1923
|
+
expiresAt: createdAt + REQUEST_TTL_MS
|
|
1924
|
+
};
|
|
1925
|
+
const stopTimer = this.options.setTimer(REQUEST_TTL_MS, () => {
|
|
1926
|
+
if (this.getState().requests[id]?.stage === "awaiting-approval") this.finish(id, "expired");
|
|
1927
|
+
});
|
|
1928
|
+
const resimulation = built.resimulation === void 0 ? void 0 : {
|
|
1929
|
+
...built.resimulation,
|
|
1930
|
+
risk: mergeRisk(built.resimulation.risk, originRisk(originStatus))
|
|
1931
|
+
};
|
|
1932
|
+
this.entries.set(id, {
|
|
1933
|
+
prepared: built.run,
|
|
1934
|
+
stopTimer,
|
|
1935
|
+
...resimulation === void 0 ? {} : { resimulation }
|
|
1936
|
+
});
|
|
1937
|
+
this.put(request);
|
|
1938
|
+
this.openSettler(id);
|
|
1939
|
+
return request;
|
|
1940
|
+
}
|
|
1941
|
+
/**
|
|
1942
|
+
* Resolves with what `approve` returned, or rejects with `RequestEndedError` when the request
|
|
1943
|
+
* ends any other way — how a dApp's pending call learns the outcome.
|
|
1944
|
+
*/
|
|
1945
|
+
async outcome(id) {
|
|
1946
|
+
const settler = this.settlers.get(id);
|
|
1947
|
+
if (settler === void 0) throw new Error(`unknown request ${id}`);
|
|
1948
|
+
return settler.promise;
|
|
1949
|
+
}
|
|
1950
|
+
openSettler(id) {
|
|
1951
|
+
const holder = {};
|
|
1952
|
+
const promise = new Promise((resolve, reject) => {
|
|
1953
|
+
holder.resolve = resolve;
|
|
1954
|
+
holder.reject = reject;
|
|
1955
|
+
});
|
|
1956
|
+
Promise.allSettled([promise]);
|
|
1957
|
+
this.settlers.set(id, {
|
|
1958
|
+
promise,
|
|
1959
|
+
resolve: (value) => holder.resolve?.(value),
|
|
1960
|
+
reject: (error) => holder.reject?.(error)
|
|
1961
|
+
});
|
|
1962
|
+
}
|
|
1963
|
+
settle(id, result) {
|
|
1964
|
+
const settler = this.settlers.get(id);
|
|
1965
|
+
if (settler === void 0) return;
|
|
1966
|
+
if (result instanceof Error) settler.reject(result);
|
|
1967
|
+
else settler.resolve(result);
|
|
1968
|
+
}
|
|
1969
|
+
/** The bitcoin network `account`'s Spark network settles on; any other pairing is refused. */
|
|
1970
|
+
l1Network(account) {
|
|
1971
|
+
const network = SPARK_L1_NETWORK[account.network];
|
|
1972
|
+
if (network === void 0) throw new Error(`unknown Spark network ${account.network}`);
|
|
1973
|
+
return network;
|
|
1974
|
+
}
|
|
1975
|
+
sparkBuilt(account, action) {
|
|
1976
|
+
return {
|
|
1977
|
+
account,
|
|
1978
|
+
network: action.display.network,
|
|
1979
|
+
display: action.display,
|
|
1980
|
+
checks: collectChecks(action.checks),
|
|
1981
|
+
risk: this.sparkRisk(action.display),
|
|
1982
|
+
run: {
|
|
1983
|
+
factor: "required",
|
|
1984
|
+
staleReason: () => action.staleReason(this.options.now()),
|
|
1985
|
+
submit: async (verify) => action.execute(this.options.spark, verify),
|
|
1986
|
+
release: () => void 0
|
|
1987
|
+
}
|
|
1988
|
+
};
|
|
1989
|
+
}
|
|
1990
|
+
async simulateOne(account, network, message) {
|
|
1991
|
+
try {
|
|
1992
|
+
return await this.options.simulateSolana(account, network, message);
|
|
1993
|
+
} catch (error) {
|
|
1994
|
+
return {
|
|
1995
|
+
status: "unavailable",
|
|
1996
|
+
error: errorMessage(error)
|
|
1997
|
+
};
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
async build(input, id) {
|
|
2001
|
+
if (input.method === "pay" || input.method === "zap") {
|
|
2002
|
+
const action = input.method === "pay" ? await preparePay({
|
|
2003
|
+
fetch: this.options.fetch,
|
|
2004
|
+
now: this.options.now
|
|
2005
|
+
}, input) : prepareZapAction(input.account, input.zap, {
|
|
2006
|
+
maxFeeSats: input.maxFeeSats,
|
|
2007
|
+
now: this.options.now
|
|
2008
|
+
});
|
|
2009
|
+
return this.sparkBuilt(input.account, action);
|
|
2010
|
+
}
|
|
2011
|
+
if (input.method === "spark-deposit") {
|
|
2012
|
+
const l1 = this.l1Network(input.account);
|
|
2013
|
+
if (input.from.kind !== "hd" || input.from.walletId !== input.account.walletId) throw new Error("a Spark deposit must come from the same wallet");
|
|
2014
|
+
const to = await this.options.spark.newDepositAddress(input.account);
|
|
2015
|
+
const prepared = await this.options.transactions.prepareSend({
|
|
2016
|
+
account: input.from,
|
|
2017
|
+
network: l1,
|
|
2018
|
+
to,
|
|
2019
|
+
amount: BigInt(input.amountSats),
|
|
2020
|
+
fee: input.fee
|
|
2021
|
+
}, id, {
|
|
2022
|
+
walletId: input.account.walletId,
|
|
2023
|
+
groupIndex: input.account.groupIndex,
|
|
2024
|
+
network: input.account.network
|
|
2025
|
+
});
|
|
2026
|
+
return {
|
|
2027
|
+
account: prepared.account,
|
|
2028
|
+
network: prepared.network,
|
|
2029
|
+
display: prepared.intent,
|
|
2030
|
+
checks: collectChecks([prepared.intent.verifiability === "full" ? void 0 : "decode-partial", ...prepared.checks]),
|
|
2031
|
+
risk: [],
|
|
2032
|
+
run: {
|
|
2033
|
+
...prepared,
|
|
2034
|
+
factor: "required"
|
|
2035
|
+
}
|
|
2036
|
+
};
|
|
2037
|
+
}
|
|
2038
|
+
if (input.method === "spark-exit") {
|
|
2039
|
+
const l1 = this.l1Network(input.account);
|
|
2040
|
+
const address = await this.options.transactions.nextReceiveAddress(input.account.walletId, input.account.groupIndex, l1);
|
|
2041
|
+
const action = await preparePay({
|
|
2042
|
+
fetch: this.options.fetch,
|
|
2043
|
+
now: this.options.now
|
|
2044
|
+
}, {
|
|
2045
|
+
account: input.account,
|
|
2046
|
+
option: {
|
|
2047
|
+
kind: "bitcoin",
|
|
2048
|
+
address
|
|
2049
|
+
},
|
|
2050
|
+
amountSats: input.amountSats,
|
|
2051
|
+
maxFeeSats: input.maxFeeSats,
|
|
2052
|
+
...input.speed === void 0 ? {} : { speed: input.speed }
|
|
2053
|
+
});
|
|
2054
|
+
return this.sparkBuilt(input.account, action);
|
|
2055
|
+
}
|
|
2056
|
+
if (input.method === "evm-sign") {
|
|
2057
|
+
const prepared = await this.options.transactions.prepareDapp(input.account, input.request);
|
|
2058
|
+
const isTransaction = input.request.kind === "evm.transaction";
|
|
2059
|
+
const signInRisk = "signer" in prepared && prepared.intent.message?.kind === "text" ? this.signInRisk(prepared.intent.message.signIn, input.origin, prepared.signer, "evm") : [];
|
|
2060
|
+
const blindRisk = prepared.intent.message?.kind === "bytes" ? this.blindRisk(input.account) : [];
|
|
2061
|
+
const { message } = prepared.intent;
|
|
2062
|
+
if (message?.kind === "typed-data" && "signer" in prepared && message.domain.verifyingContract?.toLowerCase() === prepared.signer.toLowerCase()) throw new ChainError("invalid-request", "typed data addressed to your own account is refused");
|
|
2063
|
+
const permitRisk = message?.kind === "typed-data" ? assessPermits(prepared.intent, this.options.now()) : [];
|
|
2064
|
+
const orderRisk = message?.kind === "typed-data" && "signer" in prepared ? [...assessSeaport(message.seaport, prepared.signer), ...assessSafe(message.safe)] : [];
|
|
2065
|
+
const built = {
|
|
2066
|
+
account: prepared.account,
|
|
2067
|
+
network: prepared.network,
|
|
2068
|
+
display: prepared.intent,
|
|
2069
|
+
checks: collectChecks([isTransaction && prepared.intent.verifiability !== "full" ? "decode-partial" : void 0, ...prepared.checks]),
|
|
2070
|
+
risk: isTransaction ? this.chainRisk(prepared.intent) : mergeRisk(mergeRisk(mergeRisk(signInRisk, permitRisk), orderRisk), blindRisk),
|
|
2071
|
+
run: {
|
|
2072
|
+
...prepared,
|
|
2073
|
+
factor: "required"
|
|
2074
|
+
}
|
|
2075
|
+
};
|
|
2076
|
+
return isTransaction ? withSimulation(built, prepared.intent, prepared.simulation, prepared.resimulate) : built;
|
|
2077
|
+
}
|
|
2078
|
+
if (input.method === "solana-sign") {
|
|
2079
|
+
const txs = input.request.kind === "transactions" ? input.request.transactions : [];
|
|
2080
|
+
const [only] = txs;
|
|
2081
|
+
const intents = txs.map((tx) => solanaIntent(input.account, input.network, tx));
|
|
2082
|
+
const [decoded] = intents;
|
|
2083
|
+
const signIn = input.request.kind === "message" && input.request.signIn === void 0 ? parseSignIn(utf8Text(input.request.message) ?? "", "solana") : void 0;
|
|
2084
|
+
const message = input.request.kind === "message" ? messageContent(input.request.message, signIn) : void 0;
|
|
2085
|
+
const built = {
|
|
2086
|
+
account: input.account,
|
|
2087
|
+
network: input.network,
|
|
2088
|
+
display: {
|
|
2089
|
+
kind: "solana.sign",
|
|
2090
|
+
send: input.request.kind === "transactions" ? input.request.send : false,
|
|
2091
|
+
count: txs.length === 0 ? 1 : txs.length,
|
|
2092
|
+
transactions: intents,
|
|
2093
|
+
...message === void 0 ? {} : { message },
|
|
2094
|
+
...input.request.kind === "message" && input.request.signIn !== void 0 ? { signIn: input.request.signIn } : {}
|
|
2095
|
+
},
|
|
2096
|
+
checks: [],
|
|
2097
|
+
risk: mergeRisk(this.signInRisk(signIn, input.origin, input.account.address, "solana"), message?.kind === "bytes" ? this.blindRisk(input.account) : []),
|
|
2098
|
+
run: {
|
|
2099
|
+
factor: "required",
|
|
2100
|
+
staleReason: () => void 0,
|
|
2101
|
+
submit: async (verify) => this.options.solanaSign(input.account, input.network, input.request, verify),
|
|
2102
|
+
release: () => void 0
|
|
2103
|
+
}
|
|
2104
|
+
};
|
|
2105
|
+
if (only === void 0) return built;
|
|
2106
|
+
const single = txs.length === 1;
|
|
2107
|
+
const simulation = single ? await this.simulateOne(input.account, input.network, only) : {
|
|
2108
|
+
status: "unavailable",
|
|
2109
|
+
error: "batch"
|
|
2110
|
+
};
|
|
2111
|
+
return withSimulation(built, decoded !== void 0 && "verifiability" in decoded ? decoded : OPAQUE_INTENT, simulation, single ? async () => this.simulateOne(input.account, input.network, only) : void 0);
|
|
2112
|
+
}
|
|
2113
|
+
if (input.method === "bitcoin-sign" && input.request.kind === "psbt") {
|
|
2114
|
+
const { psbts, send } = input.request;
|
|
2115
|
+
const prepared = await this.options.bitcoinPrepare(input.account, input.network, psbts);
|
|
2116
|
+
const intents = prepared.map(({ request, ownScripts }) => decodeBitcoinPsbt(request, ownScripts));
|
|
2117
|
+
return {
|
|
2118
|
+
account: input.account,
|
|
2119
|
+
network: input.network,
|
|
2120
|
+
display: {
|
|
2121
|
+
kind: "bitcoin.sign",
|
|
2122
|
+
psbts: intents,
|
|
2123
|
+
send
|
|
2124
|
+
},
|
|
2125
|
+
checks: collectChecks(intents.some((i) => i.verifiability !== "full") ? ["decode-partial"] : []),
|
|
2126
|
+
risk: assessBitcoinPsbts(prepared.flatMap((p) => p.inputs)),
|
|
2127
|
+
run: {
|
|
2128
|
+
factor: "required",
|
|
2129
|
+
staleReason: () => void 0,
|
|
2130
|
+
submit: async (verify) => this.options.bitcoinSignPsbts(input.account, input.network, prepared, send, verify),
|
|
2131
|
+
release: () => void 0
|
|
2132
|
+
}
|
|
2133
|
+
};
|
|
2134
|
+
}
|
|
2135
|
+
if (input.method === "bitcoin-sign") {
|
|
2136
|
+
if (input.request.kind !== "message") throw new Error("unreachable bitcoin-sign request");
|
|
2137
|
+
const { request } = input;
|
|
2138
|
+
return {
|
|
2139
|
+
account: input.account,
|
|
2140
|
+
network: input.network,
|
|
2141
|
+
display: {
|
|
2142
|
+
kind: "bitcoin.sign",
|
|
2143
|
+
message: {
|
|
2144
|
+
kind: "text",
|
|
2145
|
+
text: request.message
|
|
2146
|
+
}
|
|
2147
|
+
},
|
|
2148
|
+
checks: [],
|
|
2149
|
+
risk: [],
|
|
2150
|
+
run: {
|
|
2151
|
+
factor: "required",
|
|
2152
|
+
staleReason: () => void 0,
|
|
2153
|
+
submit: async (verify) => this.options.bitcoinSign(input.account, input.network, request, verify),
|
|
2154
|
+
release: () => void 0
|
|
2155
|
+
}
|
|
2156
|
+
};
|
|
2157
|
+
}
|
|
2158
|
+
if (input.method === "webln-invoice") return {
|
|
2159
|
+
account: input.ref,
|
|
2160
|
+
network: "",
|
|
2161
|
+
display: {
|
|
2162
|
+
kind: "lightning.invoice",
|
|
2163
|
+
amountSats: input.amountSats,
|
|
2164
|
+
...input.memo === void 0 ? {} : { memo: input.memo }
|
|
2165
|
+
},
|
|
2166
|
+
checks: [],
|
|
2167
|
+
risk: [],
|
|
2168
|
+
run: {
|
|
2169
|
+
factor: "none",
|
|
2170
|
+
staleReason: () => void 0,
|
|
2171
|
+
submit: async () => {
|
|
2172
|
+
return {
|
|
2173
|
+
kind: "lightning.invoice",
|
|
2174
|
+
paymentRequest: (await this.options.spark.createInvoice(input.ref, {
|
|
2175
|
+
amountSats: input.amountSats,
|
|
2176
|
+
...input.memo === void 0 ? {} : { memo: input.memo }
|
|
2177
|
+
})).invoice
|
|
2178
|
+
};
|
|
2179
|
+
},
|
|
2180
|
+
release: () => void 0
|
|
2181
|
+
}
|
|
2182
|
+
};
|
|
2183
|
+
if (input.method === "watch-asset") {
|
|
2184
|
+
const address = checksumEvmAddress(input.address);
|
|
2185
|
+
const metadata = await this.options.tokens.metadata(input.network, address);
|
|
2186
|
+
const symbol = safeDisplayText(metadata.symbol, 32);
|
|
2187
|
+
const decimals = safeDecimals(metadata.decimals);
|
|
2188
|
+
if (symbol === void 0) throw new InvalidTokenError("the token symbol cannot be displayed safely");
|
|
2189
|
+
if (decimals === void 0) throw new InvalidTokenError("the token decimals are out of range");
|
|
2190
|
+
const chainId = Number(input.network.slice(7));
|
|
2191
|
+
return {
|
|
2192
|
+
account: input.account,
|
|
2193
|
+
network: input.network,
|
|
2194
|
+
display: {
|
|
2195
|
+
kind: "token.watch",
|
|
2196
|
+
network: input.network,
|
|
2197
|
+
address,
|
|
2198
|
+
symbol,
|
|
2199
|
+
decimals,
|
|
2200
|
+
verified: lookupEvmToken(evmTokenTable, chainId, address) !== void 0
|
|
2201
|
+
},
|
|
2202
|
+
checks: [],
|
|
2203
|
+
risk: [...impersonatesBuiltIn(chainId, address, symbol) ? [{
|
|
2204
|
+
code: "token-impersonation",
|
|
2205
|
+
level: "danger"
|
|
2206
|
+
}] : [], ...isAscii(symbol) ? [] : [{
|
|
2207
|
+
code: "token-symbol-unicode",
|
|
2208
|
+
level: "warning"
|
|
2209
|
+
}]],
|
|
2210
|
+
run: {
|
|
2211
|
+
factor: "none",
|
|
2212
|
+
staleReason: () => void 0,
|
|
2213
|
+
submit: async () => {
|
|
2214
|
+
await this.options.tokens.add(input.network, address);
|
|
2215
|
+
return { kind: "token.watch" };
|
|
2216
|
+
},
|
|
2217
|
+
release: () => void 0
|
|
2218
|
+
}
|
|
2219
|
+
};
|
|
2220
|
+
}
|
|
2221
|
+
if (input.method === "nostr-sign") return {
|
|
2222
|
+
account: input.ref,
|
|
2223
|
+
network: "",
|
|
2224
|
+
display: {
|
|
2225
|
+
kind: "nostr.event",
|
|
2226
|
+
eventKind: input.event.kind,
|
|
2227
|
+
preview: input.event.content.slice(0, 280),
|
|
2228
|
+
tagCount: input.event.tags.length
|
|
2229
|
+
},
|
|
2230
|
+
checks: [],
|
|
2231
|
+
risk: [],
|
|
2232
|
+
run: {
|
|
2233
|
+
factor: "none",
|
|
2234
|
+
staleReason: () => void 0,
|
|
2235
|
+
submit: async () => ({
|
|
2236
|
+
kind: "nostr.event",
|
|
2237
|
+
event: await this.options.nostrSign(input.ref, input.event)
|
|
2238
|
+
}),
|
|
2239
|
+
release: () => void 0
|
|
2240
|
+
}
|
|
2241
|
+
};
|
|
2242
|
+
const prepared = input.method === "send" ? await this.options.transactions.prepareSend(input, id) : await this.options.transactions.prepareReplacement(input, id);
|
|
2243
|
+
const built = {
|
|
2244
|
+
account: prepared.account,
|
|
2245
|
+
network: prepared.network,
|
|
2246
|
+
display: prepared.intent,
|
|
2247
|
+
checks: collectChecks([prepared.intent.verifiability === "full" ? void 0 : "decode-partial", ...prepared.checks]),
|
|
2248
|
+
risk: input.method === "send" ? this.chainRisk(prepared.intent) : [],
|
|
2249
|
+
run: {
|
|
2250
|
+
...prepared,
|
|
2251
|
+
factor: "required"
|
|
2252
|
+
}
|
|
2253
|
+
};
|
|
2254
|
+
return input.method === "send" ? withSimulation(built, prepared.intent, prepared.simulation, prepared.resimulate) : built;
|
|
2255
|
+
}
|
|
2256
|
+
async approve(id, method, verify) {
|
|
2257
|
+
const request = this.getState().requests[id];
|
|
2258
|
+
if (request === void 0) throw new Error(`unknown request ${id}`);
|
|
2259
|
+
if (request.method !== method) throw new Error(`request ${id} is a ${request.method} request, not ${method}`);
|
|
2260
|
+
const entry = this.entries.get(id);
|
|
2261
|
+
if (request.stage !== "awaiting-approval" || entry === void 0) throw new Error(`request ${id} is ${request.stage}, not awaiting approval`);
|
|
2262
|
+
if (this.options.now() >= request.expiresAt) {
|
|
2263
|
+
this.finish(id, "expired");
|
|
2264
|
+
throw new Error(`request ${id} expired`);
|
|
2265
|
+
}
|
|
2266
|
+
if (request.origin.kind === "browser" && this.options.phishing.check(request.origin.origin) === "blocked") {
|
|
2267
|
+
this.finish(id, "failed", PHISHING_BLOCKED_MESSAGE);
|
|
2268
|
+
throw new Error(PHISHING_BLOCKED_MESSAGE);
|
|
2269
|
+
}
|
|
2270
|
+
const { session } = this;
|
|
2271
|
+
this.put({
|
|
2272
|
+
...request,
|
|
2273
|
+
stage: "signing"
|
|
2274
|
+
});
|
|
2275
|
+
let stale;
|
|
2276
|
+
try {
|
|
2277
|
+
stale = await entry.prepared.staleReason();
|
|
2278
|
+
} catch (error) {
|
|
2279
|
+
stale = errorMessage(error);
|
|
2280
|
+
}
|
|
2281
|
+
if (session !== this.session) throw new Error(`request ${id} was invalidated`);
|
|
2282
|
+
if (stale !== void 0) {
|
|
2283
|
+
this.finish(id, "failed", stale);
|
|
2284
|
+
throw new Error(stale);
|
|
2285
|
+
}
|
|
2286
|
+
const { resimulation } = entry;
|
|
2287
|
+
if (resimulation !== void 0 && request.simulatedAt !== void 0 && this.options.now() - request.simulatedAt >= 6e4) {
|
|
2288
|
+
let outcome;
|
|
2289
|
+
try {
|
|
2290
|
+
outcome = await resimulation.run();
|
|
2291
|
+
} catch (error) {
|
|
2292
|
+
outcome = {
|
|
2293
|
+
status: "unavailable",
|
|
2294
|
+
error: errorMessage(error)
|
|
2295
|
+
};
|
|
2296
|
+
}
|
|
2297
|
+
if (session !== this.session) throw new Error(`request ${id} was invalidated`);
|
|
2298
|
+
const assessed = assessSimulation(resimulation.intent, outcome);
|
|
2299
|
+
const checks = collectChecks([...resimulation.checks, ...assessed.checks]);
|
|
2300
|
+
const refreshed = {
|
|
2301
|
+
...this.requireRequest(id),
|
|
2302
|
+
simulation: outcome,
|
|
2303
|
+
simulatedAt: this.options.now(),
|
|
2304
|
+
verification: checks.length > 0 ? "unverifiable" : "verified",
|
|
2305
|
+
checks,
|
|
2306
|
+
risk: mergeRisk(resimulation.risk, assessed.risk)
|
|
2307
|
+
};
|
|
2308
|
+
if (request.simulation !== void 0 && simulationChanged(request.simulation, outcome)) {
|
|
2309
|
+
this.put({
|
|
2310
|
+
...refreshed,
|
|
2311
|
+
stage: "awaiting-approval"
|
|
2312
|
+
});
|
|
2313
|
+
throw new SimulationChangedError();
|
|
2314
|
+
}
|
|
2315
|
+
this.put(refreshed);
|
|
2316
|
+
}
|
|
2317
|
+
try {
|
|
2318
|
+
const result = entry.prepared.factor === "none" ? await entry.prepared.submit() : await entry.prepared.submit(this.requireVerify(verify));
|
|
2319
|
+
if (session === this.session) {
|
|
2320
|
+
entry.stopTimer();
|
|
2321
|
+
this.entries.delete(id);
|
|
2322
|
+
this.unclaim(id);
|
|
2323
|
+
const done = {
|
|
2324
|
+
...this.requireRequest(id),
|
|
2325
|
+
stage: "submitted",
|
|
2326
|
+
..."id" in result ? { txId: result.id } : {}
|
|
2327
|
+
};
|
|
2328
|
+
this.put(done);
|
|
2329
|
+
this.record(done, "submitted", void 0, result);
|
|
2330
|
+
} else this.record(request, "submitted");
|
|
2331
|
+
this.settle(id, result);
|
|
2332
|
+
return result;
|
|
2333
|
+
} catch (error) {
|
|
2334
|
+
if (session === this.session) this.finish(id, this.failureStage(entry.prepared, error), errorMessage(error));
|
|
2335
|
+
else this.record(request, "failed", errorMessage(error));
|
|
2336
|
+
throw error;
|
|
2337
|
+
}
|
|
2338
|
+
}
|
|
2339
|
+
/**
|
|
2340
|
+
* A cancelled or refused verification is `rejected`; anything after it is `failed`. Chain
|
|
2341
|
+
* requests record which step failed on the tracked transaction; for Spark, the approval round is
|
|
2342
|
+
* the only source of `WalletError`.
|
|
2343
|
+
*/
|
|
2344
|
+
failureStage(run, error) {
|
|
2345
|
+
if (run.txId === void 0) return error instanceof WalletError ? "rejected" : "failed";
|
|
2346
|
+
return this.options.transactions.getState().txs[run.txId]?.state === "rejected" ? "rejected" : "failed";
|
|
2347
|
+
}
|
|
2348
|
+
reject(id) {
|
|
2349
|
+
const request = this.getState().requests[id];
|
|
2350
|
+
if (request === void 0) throw new Error(`unknown request ${id}`);
|
|
2351
|
+
if (request.stage !== "awaiting-approval") throw new Error(`request ${id} is ${request.stage}, not awaiting approval`);
|
|
2352
|
+
this.finish(id, "rejected");
|
|
2353
|
+
}
|
|
2354
|
+
/** `approve` for a factor-required run: a missing factor is invalid input. */
|
|
2355
|
+
requireVerify(verify) {
|
|
2356
|
+
if (verify === void 0) throw new WalletError("invalid-input", "a verification factor is required");
|
|
2357
|
+
return verify;
|
|
2358
|
+
}
|
|
2359
|
+
requireRequest(id) {
|
|
2360
|
+
const request = this.getState().requests[id];
|
|
2361
|
+
if (request === void 0) throw new Error(`unknown request ${id}`);
|
|
2362
|
+
return request;
|
|
2363
|
+
}
|
|
2364
|
+
put(request) {
|
|
2365
|
+
this.update((s) => ({
|
|
2366
|
+
...s,
|
|
2367
|
+
requests: {
|
|
2368
|
+
...s.requests,
|
|
2369
|
+
[request.id]: request
|
|
2370
|
+
}
|
|
2371
|
+
}));
|
|
2372
|
+
}
|
|
2373
|
+
unclaim(requestId) {
|
|
2374
|
+
for (const [target, holder] of this.targets) if (holder === requestId) this.targets.delete(target);
|
|
2375
|
+
}
|
|
2376
|
+
/** Ends a request in a terminal stage and frees what it reserved. */
|
|
2377
|
+
finish(id, stage, error) {
|
|
2378
|
+
this.unclaim(id);
|
|
2379
|
+
const entry = this.entries.get(id);
|
|
2380
|
+
if (entry !== void 0) {
|
|
2381
|
+
entry.stopTimer();
|
|
2382
|
+
this.entries.delete(id);
|
|
2383
|
+
try {
|
|
2384
|
+
entry.prepared.release();
|
|
2385
|
+
} catch (releaseError) {
|
|
2386
|
+
this.options.logger.warn("request release failed", releaseError);
|
|
2387
|
+
}
|
|
2388
|
+
}
|
|
2389
|
+
const request = this.getState().requests[id];
|
|
2390
|
+
if (request !== void 0) {
|
|
2391
|
+
const ended = {
|
|
2392
|
+
...request,
|
|
2393
|
+
stage,
|
|
2394
|
+
...error === void 0 ? {} : { error }
|
|
2395
|
+
};
|
|
2396
|
+
this.put(ended);
|
|
2397
|
+
this.record(ended, stage, error);
|
|
2398
|
+
this.settle(id, new RequestEndedError(stage, error));
|
|
2399
|
+
}
|
|
2400
|
+
}
|
|
2401
|
+
/** Appends the final stage to the signature record; a failed write is a warning, not an error. */
|
|
2402
|
+
record(request, outcome, error, result) {
|
|
2403
|
+
const { display } = request;
|
|
2404
|
+
const eventId = result !== void 0 && "kind" in result && result.kind === "nostr.event" ? result.event.id : void 0;
|
|
2405
|
+
const summary = "kind" in display && display.kind === "nostr.event" ? `nostr kind ${display.eventKind}${eventId === void 0 ? "" : ` ${eventId}`}` : "kind" in display && display.kind === "token.watch" ? `watch token ${display.symbol}` : "kind" in display && display.kind === "lightning.invoice" ? `lightning invoice ${display.amountSats} sats` : "kind" in display && display.kind === "bitcoin.sign" ? display.psbts === void 0 ? "bitcoin message" : display.send === true ? "bitcoin send" : `bitcoin psbt ${String(display.psbts.length)}` : "kind" in display && display.kind === "solana.sign" ? display.signIn === void 0 ? display.transactions.length === 0 ? display.message?.kind === "bytes" ? "blind message" : display.message?.kind === "text" && display.message.signIn?.status === "valid" ? `sign-in ${display.message.signIn.fields.domain}` : "solana message" : `solana ${display.send ? "send" : "sign"} ${String(display.count)} tx` : `solana sign-in ${display.signIn.domain}` : "summary" in display ? display.message?.kind === "bytes" ? "blind message" : display.message?.kind === "text" && display.message.signIn?.status === "valid" ? `sign-in ${display.message.signIn.fields.domain}` : display.message?.kind === "typed-data" && display.message.seaport !== void 0 ? "seaport order" : display.message?.kind === "typed-data" && display.message.safe !== void 0 ? `safe tx ${display.message.safe.nonce}` : display.message?.kind === "typed-data" && display.approvals[0]?.kind === "allowance" ? `permit ${display.approvals[0].amount.symbol ?? display.approvals[0].amount.asset}` : display.summary : `${display.kind} ${display.amountSats}`;
|
|
2406
|
+
const entry = {
|
|
2407
|
+
id: request.id,
|
|
2408
|
+
at: this.options.now(),
|
|
2409
|
+
origin: request.origin,
|
|
2410
|
+
method: request.method,
|
|
2411
|
+
account: request.account,
|
|
2412
|
+
network: request.network,
|
|
2413
|
+
summary,
|
|
2414
|
+
verification: request.verification,
|
|
2415
|
+
checks: request.checks,
|
|
2416
|
+
risk: request.risk,
|
|
2417
|
+
outcome,
|
|
2418
|
+
...error === void 0 ? {} : { error }
|
|
2419
|
+
};
|
|
2420
|
+
this.appendLog(entry);
|
|
2421
|
+
}
|
|
2422
|
+
async appendLog(entry) {
|
|
2423
|
+
try {
|
|
2424
|
+
await this.log.append(entry);
|
|
2425
|
+
} catch (error) {
|
|
2426
|
+
this.options.logger.warn("sign log write failed", error);
|
|
2427
|
+
}
|
|
2428
|
+
}
|
|
2429
|
+
/**
|
|
2430
|
+
* Addresses the wallet already knows for a family: contacts, plus recipients of tracked chain
|
|
2431
|
+
* sends (Spark payments are not tracked).
|
|
2432
|
+
*/
|
|
2433
|
+
knownAddresses(family) {
|
|
2434
|
+
const contacts = Object.values(this.options.addressBook.getState().entries).filter((e) => e.family === family).map((e) => e.address);
|
|
2435
|
+
if (family === "spark") return contacts;
|
|
2436
|
+
const paid = Object.values(this.options.transactions.getState().txs).filter((tx) => tx.family === family && (tx.state === "submitted" || tx.state === "pending" || tx.state === "confirmed")).flatMap((tx) => tx.intent?.outflows.map((o) => o.to) ?? []);
|
|
2437
|
+
return [...contacts, ...paid];
|
|
2438
|
+
}
|
|
2439
|
+
/** A blind-sign request carries one danger; a group that did not opt in refuses it outright. */
|
|
2440
|
+
blindRisk(account) {
|
|
2441
|
+
if (!("groupIndex" in account && "walletId" in account ? this.options.blindSigning(account.walletId, account.groupIndex) : false)) throw new BlindSigningDisabledError();
|
|
2442
|
+
return [{
|
|
2443
|
+
code: "blind-signing",
|
|
2444
|
+
level: "danger"
|
|
2445
|
+
}];
|
|
2446
|
+
}
|
|
2447
|
+
/** Risk of a Sign-In with X message; a message for another domain throws `SignInOriginError`. */
|
|
2448
|
+
signInRisk(signIn, origin, signer, family) {
|
|
2449
|
+
if (signIn === void 0) return [];
|
|
2450
|
+
const assessed = assessSignIn({
|
|
2451
|
+
signIn,
|
|
2452
|
+
origin: origin.origin,
|
|
2453
|
+
signer,
|
|
2454
|
+
family,
|
|
2455
|
+
now: this.options.now()
|
|
2456
|
+
});
|
|
2457
|
+
if (assessed.reject !== void 0) throw new SignInOriginError(assessed.reject);
|
|
2458
|
+
return assessed.risk;
|
|
2459
|
+
}
|
|
2460
|
+
chainRisk(intent) {
|
|
2461
|
+
return mergeRisk(assessRecipients(intent.family, intent.outflows.map((o) => o.to), this.knownAddresses(intent.family)), assessApprovals(intent));
|
|
2462
|
+
}
|
|
2463
|
+
/** Only a Spark transfer has a recipient to check; Lightning and exits are not assessed. */
|
|
2464
|
+
sparkRisk(display) {
|
|
2465
|
+
if (display.kind !== "transfer") return [];
|
|
2466
|
+
return assessRecipients("spark", [normalizeAddress("spark", display.receiver) ?? display.receiver], this.knownAddresses("spark"));
|
|
2467
|
+
}
|
|
2468
|
+
};
|
|
2469
|
+
// src/connect/subscription.ts
|
|
2470
|
+
/**
|
|
2471
|
+
* Fans events derived from session changes out to listeners. The store subscription is created with
|
|
2472
|
+
* the first listener and dropped with the last; `derive` may be async (its events are then
|
|
2473
|
+
* delivered once it settles).
|
|
2474
|
+
*/
|
|
2475
|
+
var SessionEvents = class {
|
|
2476
|
+
listeners = /* @__PURE__ */ new Set();
|
|
2477
|
+
unsubscribe;
|
|
2478
|
+
connections;
|
|
2479
|
+
derive;
|
|
2480
|
+
constructor(connections, derive) {
|
|
2481
|
+
this.connections = connections;
|
|
2482
|
+
this.derive = derive;
|
|
2483
|
+
}
|
|
2484
|
+
subscribe(listener) {
|
|
2485
|
+
this.listeners.add(listener);
|
|
2486
|
+
if (this.unsubscribe === void 0) {
|
|
2487
|
+
let previous = this.connections.getState().sessions;
|
|
2488
|
+
this.unsubscribe = this.connections.store.subscribe((state) => {
|
|
2489
|
+
const events = this.derive(previous, state.sessions);
|
|
2490
|
+
previous = state.sessions;
|
|
2491
|
+
if (Array.isArray(events)) this.emit(events);
|
|
2492
|
+
else (async () => {
|
|
2493
|
+
this.emit(await events);
|
|
2494
|
+
})();
|
|
2495
|
+
});
|
|
2496
|
+
}
|
|
2497
|
+
return () => {
|
|
2498
|
+
this.listeners.delete(listener);
|
|
2499
|
+
if (this.listeners.size === 0) {
|
|
2500
|
+
this.unsubscribe?.();
|
|
2501
|
+
this.unsubscribe = void 0;
|
|
2502
|
+
}
|
|
2503
|
+
};
|
|
2504
|
+
}
|
|
2505
|
+
emit(events) {
|
|
2506
|
+
for (const event of events) for (const listener of this.listeners) listener(event);
|
|
2507
|
+
}
|
|
2508
|
+
};
|
|
2509
|
+
// src/connect/bitcoin.ts
|
|
2510
|
+
const bitcoinId = (name) => {
|
|
2511
|
+
const entry = BITCOIN_NETWORKS$1.find((n) => n.name === name);
|
|
2512
|
+
if (entry === void 0) throw new Error(`no bitcoin network named ${name} in the registry`);
|
|
2513
|
+
return entry.id;
|
|
2514
|
+
};
|
|
2515
|
+
/**
|
|
2516
|
+
* The Bitcoin Wallet Standard chain ids to the registry's CAIP-2 ids: `bitcoin:testnet` is the
|
|
2517
|
+
* registry's default test network (Testnet4 — the registry has no Testnet3).
|
|
2518
|
+
*/
|
|
2519
|
+
const BITCOIN_CHAIN_IDS = Object.freeze({
|
|
2520
|
+
"bitcoin:mainnet": bitcoinId("Bitcoin"),
|
|
2521
|
+
"bitcoin:testnet": bitcoinId("Bitcoin Testnet4")
|
|
2522
|
+
});
|
|
2523
|
+
/** The Wallet Standard chain id of a registry network, or `undefined` when it has none. */
|
|
2524
|
+
const bitcoinStandardChain = (network) => Object.entries(BITCOIN_CHAIN_IDS).find(([, id]) => id === network)?.[0];
|
|
2525
|
+
/** The kernel tags a BIP-322 simple signature `smp` + base64 of the witness. */
|
|
2526
|
+
const SIMPLE_PREFIX = "smp";
|
|
2527
|
+
const TEMPLATES = {
|
|
2528
|
+
payment: "btc.bip84",
|
|
2529
|
+
ordinals: "btc.bip86"
|
|
2530
|
+
};
|
|
2531
|
+
/**
|
|
2532
|
+
* The Bitcoin Wallet Standard handler: `bitcoin:connect` authorizes the `bip122` scope (both the
|
|
2533
|
+
* `payment` and the `ordinals` account) and returns the requested purposes in order;
|
|
2534
|
+
* `bitcoin:signMessage` goes through `bitcoin-sign` (BIP-322 simple); `bitcoinAccountsChanged`
|
|
2535
|
+
* carries the re-pointed accounts the bridge forwards as `bitcoin:events` `change` on a group
|
|
2536
|
+
* switch.
|
|
2537
|
+
*/
|
|
2538
|
+
var BitcoinWalletHandler = class {
|
|
2539
|
+
options;
|
|
2540
|
+
events;
|
|
2541
|
+
constructor(options) {
|
|
2542
|
+
this.options = options;
|
|
2543
|
+
this.events = new SessionEvents(options.connections, async (before, after) => Promise.all(diffSessions$1(before, after).map(async ({ origin }) => ({
|
|
2544
|
+
name: "bitcoinAccountsChanged",
|
|
2545
|
+
origin,
|
|
2546
|
+
accounts: await this.bitcoinAccountsChanged()
|
|
2547
|
+
}))));
|
|
2548
|
+
}
|
|
2549
|
+
subscribe(listener) {
|
|
2550
|
+
return this.events.subscribe(listener);
|
|
2551
|
+
}
|
|
2552
|
+
async handle(origin, request) {
|
|
2553
|
+
const checked = this.options.connections.checkOrigin(origin);
|
|
2554
|
+
if (request.method === "bitcoin:connect") return this.connect(checked, request);
|
|
2555
|
+
if (request.method === "standard:disconnect") {
|
|
2556
|
+
await this.options.connections.revoke(origin);
|
|
2557
|
+
return {};
|
|
2558
|
+
}
|
|
2559
|
+
if (request.method === "bitcoin:signMessage") return this.signMessage(checked, request);
|
|
2560
|
+
if (request.method === "bitcoin:signTransaction") return this.signTransactions(checked, request, false);
|
|
2561
|
+
if (request.method === "bitcoin:signAndSendTransaction") return this.signTransactions(checked, request, true);
|
|
2562
|
+
throw invalidParams(`unsupported bitcoin method ${request.method}`);
|
|
2563
|
+
}
|
|
2564
|
+
async connect(checked, request) {
|
|
2565
|
+
const purposes = purposesOf(request.params);
|
|
2566
|
+
const network = this.options.bitcoinNetwork();
|
|
2567
|
+
await (this.options.connections.bitcoinAccounts(checked.origin, network) !== void 0 ? this.options.connections.touch(checked.origin) : this.options.connections.request(checked.origin, {
|
|
2568
|
+
kind: "connect",
|
|
2569
|
+
namespace: "bip122"
|
|
2570
|
+
}));
|
|
2571
|
+
const group = this.options.activeGroup();
|
|
2572
|
+
if (group === void 0) throw new ProviderError(4100, "no account group is selected");
|
|
2573
|
+
return { accounts: await Promise.all(purposes.map(async (purpose) => this.walletAccount(group, network, purpose))) };
|
|
2574
|
+
}
|
|
2575
|
+
async walletAccount(group, network, purpose) {
|
|
2576
|
+
const chain = bitcoinStandardChain(network);
|
|
2577
|
+
if (chain === void 0) throw new ProviderError(-32603, `network ${network} has no Wallet Standard chain id`);
|
|
2578
|
+
const account = await this.options.bitcoinAccount(group, network, purpose);
|
|
2579
|
+
return {
|
|
2580
|
+
address: account.address,
|
|
2581
|
+
publicKey: account.publicKey,
|
|
2582
|
+
chains: [chain],
|
|
2583
|
+
features: BITCOIN_METHODS.filter((m) => m.startsWith("bitcoin:"))
|
|
2584
|
+
};
|
|
2585
|
+
}
|
|
2586
|
+
/**
|
|
2587
|
+
* Signs `message` (UTF-8 text only — `bitcoin.message` takes text, so there is no blind path) for
|
|
2588
|
+
* one of the session's accounts. The signature is the BIP-322 simple witness serialization
|
|
2589
|
+
* (witness item count, then each item length-prefixed) — the kernel's `smp` + base64 string
|
|
2590
|
+
* decoded to bytes, which is what MetaMask's Bitcoin Wallet Standard wallet hands out.
|
|
2591
|
+
*/
|
|
2592
|
+
async signMessage(checked, request) {
|
|
2593
|
+
const network = this.options.bitcoinNetwork();
|
|
2594
|
+
this.options.connections.authorize(checked.origin, network, "bitcoin:signMessage");
|
|
2595
|
+
const accounts = this.options.connections.bitcoinAccounts(checked.origin, network);
|
|
2596
|
+
if (accounts === void 0) throw new ProviderError(4100, "no bitcoin account for this origin");
|
|
2597
|
+
const { address, message } = signMessageParams(request.params);
|
|
2598
|
+
const purpose = BITCOIN_PURPOSES.find((p) => accounts[p] === address);
|
|
2599
|
+
if (purpose === void 0) throw new ProviderError(4100, "account is not a connected account");
|
|
2600
|
+
const text = utf8Text(message);
|
|
2601
|
+
if (text === void 0) throw new ProviderError(4200, BLIND_SIGNING_MESSAGE);
|
|
2602
|
+
const group = this.options.activeGroup();
|
|
2603
|
+
if (group === void 0) throw new ProviderError(4100, "no account group is selected");
|
|
2604
|
+
const account = {
|
|
2605
|
+
...group,
|
|
2606
|
+
address,
|
|
2607
|
+
template: TEMPLATES[purpose]
|
|
2608
|
+
};
|
|
2609
|
+
const pending = await this.options.requests.prepare({
|
|
2610
|
+
method: "bitcoin-sign",
|
|
2611
|
+
origin: checked,
|
|
2612
|
+
account,
|
|
2613
|
+
network,
|
|
2614
|
+
request: {
|
|
2615
|
+
kind: "message",
|
|
2616
|
+
message: text
|
|
2617
|
+
}
|
|
2618
|
+
});
|
|
2619
|
+
const outcome = await this.options.requests.outcome(pending.id);
|
|
2620
|
+
if (!("kind" in outcome) || outcome.kind !== "bitcoin.message") throw new ProviderError(-32603, "the bitcoin-sign request settled unexpectedly");
|
|
2621
|
+
if (!outcome.signature.startsWith(SIMPLE_PREFIX)) throw new ProviderError(-32603, "the kernel returned an unrecognized signature encoding");
|
|
2622
|
+
return {
|
|
2623
|
+
signedMessage: message,
|
|
2624
|
+
signature: base64.decode(outcome.signature.slice(3))
|
|
2625
|
+
};
|
|
2626
|
+
}
|
|
2627
|
+
/**
|
|
2628
|
+
* Signs (and with `send` broadcasts) a batch of dApp PSBTs under one approval. Every account
|
|
2629
|
+
* named must be a session account of one purpose — a PSBT spending both payment and ordinals
|
|
2630
|
+
* inputs is not supported yet — and `chain`, when given, must be the session's network.
|
|
2631
|
+
*/
|
|
2632
|
+
async signTransactions(checked, request, send) {
|
|
2633
|
+
const network = this.options.bitcoinNetwork();
|
|
2634
|
+
this.options.connections.authorize(checked.origin, network, request.method);
|
|
2635
|
+
const accounts = this.options.connections.bitcoinAccounts(checked.origin, network);
|
|
2636
|
+
if (accounts === void 0) throw new ProviderError(4100, "no bitcoin account for this origin");
|
|
2637
|
+
const inputs = transactionInputs(request.params);
|
|
2638
|
+
if (send && inputs.some((input) => input.chain === void 0)) throw invalidParams("chain is required for bitcoin:signAndSendTransaction");
|
|
2639
|
+
if (inputs.some((input) => input.chain !== void 0 && BITCOIN_CHAIN_IDS[input.chain] !== network)) throw invalidParams("chain is not the connected network");
|
|
2640
|
+
const purposes = /* @__PURE__ */ new Set();
|
|
2641
|
+
for (const { address } of inputs.flatMap((input) => input.inputsToSign)) {
|
|
2642
|
+
const purpose = BITCOIN_PURPOSES.find((p) => accounts[p] === address);
|
|
2643
|
+
if (purpose === void 0) throw new ProviderError(4100, "account is not a connected account");
|
|
2644
|
+
purposes.add(purpose);
|
|
2645
|
+
}
|
|
2646
|
+
const [purpose, ...rest] = purposes;
|
|
2647
|
+
if (purpose === void 0) throw invalidParams("inputsToSign names no account");
|
|
2648
|
+
if (rest.length > 0) throw invalidParams("mixed payment and ordinals inputs are not supported yet");
|
|
2649
|
+
const group = this.options.activeGroup();
|
|
2650
|
+
if (group === void 0) throw new ProviderError(4100, "no account group is selected");
|
|
2651
|
+
const account = {
|
|
2652
|
+
...group,
|
|
2653
|
+
address: accounts[purpose],
|
|
2654
|
+
template: TEMPLATES[purpose]
|
|
2655
|
+
};
|
|
2656
|
+
let outcome;
|
|
2657
|
+
try {
|
|
2658
|
+
const pending = await this.options.requests.prepare({
|
|
2659
|
+
method: "bitcoin-sign",
|
|
2660
|
+
origin: checked,
|
|
2661
|
+
account,
|
|
2662
|
+
network,
|
|
2663
|
+
request: {
|
|
2664
|
+
kind: "psbt",
|
|
2665
|
+
psbts: inputs.map(({ psbt, inputsToSign }) => ({
|
|
2666
|
+
psbt,
|
|
2667
|
+
sign: inputsToSign.flatMap(({ signingIndexes, sigHash }) => signingIndexes.map((index) => ({
|
|
2668
|
+
index,
|
|
2669
|
+
sigHash
|
|
2670
|
+
})))
|
|
2671
|
+
})),
|
|
2672
|
+
send
|
|
2673
|
+
}
|
|
2674
|
+
});
|
|
2675
|
+
outcome = await this.options.requests.outcome(pending.id);
|
|
2676
|
+
} catch (error) {
|
|
2677
|
+
throw error instanceof ChainError ? invalidParams(error.message) : error;
|
|
2678
|
+
}
|
|
2679
|
+
if (!("kind" in outcome) || outcome.kind !== "bitcoin.psbts") throw new ProviderError(-32603, "the bitcoin-sign request settled unexpectedly");
|
|
2680
|
+
return send ? outcome.txids.map((txId) => ({ txId })) : outcome.signedPsbts.map((signedPsbt) => ({ signedPsbt }));
|
|
2681
|
+
}
|
|
2682
|
+
/** The `setActiveGroup` re-point: the bitcoin session's new accounts, `payment` then `ordinals`. */
|
|
2683
|
+
async bitcoinAccountsChanged() {
|
|
2684
|
+
const network = this.options.bitcoinNetwork();
|
|
2685
|
+
const group = this.options.activeGroup();
|
|
2686
|
+
if (group === void 0) return [];
|
|
2687
|
+
return Promise.all(BITCOIN_PURPOSES.map(async (purpose) => this.walletAccount(group, network, purpose)));
|
|
2688
|
+
}
|
|
2689
|
+
};
|
|
2690
|
+
const isBytesEnvelope$1 = (v) => typeof v === "object" && v !== null && typeof v.__bytes === "string";
|
|
2691
|
+
const purposesOf = (params) => {
|
|
2692
|
+
const raw = typeof params === "object" && params !== null ? params.purposes : void 0;
|
|
2693
|
+
if (!Array.isArray(raw) || raw.length === 0) throw invalidParams("bitcoin:connect needs a non-empty purposes array");
|
|
2694
|
+
return raw.map((purpose) => {
|
|
2695
|
+
const found = BITCOIN_PURPOSES.find((p) => p === purpose);
|
|
2696
|
+
if (found === void 0) throw invalidParams("unknown purpose");
|
|
2697
|
+
return found;
|
|
2698
|
+
});
|
|
2699
|
+
};
|
|
2700
|
+
const signMessageParams = (params) => {
|
|
2701
|
+
const { account, message } = typeof params === "object" && params !== null ? params : {};
|
|
2702
|
+
if (typeof account !== "string") throw invalidParams("bitcoin:signMessage needs the account address");
|
|
2703
|
+
if (message instanceof Uint8Array) return {
|
|
2704
|
+
address: account,
|
|
2705
|
+
message
|
|
2706
|
+
};
|
|
2707
|
+
if (isBytesEnvelope$1(message) && /^(?:[0-9a-fA-F]{2})*$/.test(message.__bytes)) return {
|
|
2708
|
+
address: account,
|
|
2709
|
+
message: hexToBytes(message.__bytes)
|
|
2710
|
+
};
|
|
2711
|
+
throw invalidParams("bitcoin:signMessage needs Uint8Array message bytes");
|
|
2712
|
+
};
|
|
2713
|
+
const bytesOf = (value) => {
|
|
2714
|
+
if (value instanceof Uint8Array) return value;
|
|
2715
|
+
return isBytesEnvelope$1(value) && /^(?:[0-9a-fA-F]{2})*$/.test(value.__bytes) ? hexToBytes(value.__bytes) : void 0;
|
|
2716
|
+
};
|
|
2717
|
+
const sigHashOf = (value) => {
|
|
2718
|
+
if (value === void 0 || value === "ALL") return "ALL";
|
|
2719
|
+
if (value === "SINGLE|ANYONECANPAY") return value;
|
|
2720
|
+
throw invalidParams("sigHash must be ALL or SINGLE|ANYONECANPAY");
|
|
2721
|
+
};
|
|
2722
|
+
/** The wire shape of `bitcoin:signTransaction` inputs: accounts arrive as their addresses. */
|
|
2723
|
+
const transactionInputs = (params) => {
|
|
2724
|
+
const raw = typeof params === "object" && params !== null ? params.inputs : void 0;
|
|
2725
|
+
if (!Array.isArray(raw) || raw.length === 0) throw invalidParams("a bitcoin transaction call needs a non-empty inputs array");
|
|
2726
|
+
return raw.map((entry) => {
|
|
2727
|
+
const { psbt, chain, inputsToSign } = typeof entry === "object" && entry !== null ? entry : {};
|
|
2728
|
+
const bytes = bytesOf(psbt);
|
|
2729
|
+
if (bytes === void 0 || !Array.isArray(inputsToSign) || inputsToSign.length === 0) throw invalidParams("each input needs psbt bytes and inputsToSign");
|
|
2730
|
+
if (chain !== void 0 && typeof chain !== "string") throw invalidParams("chain must be a string");
|
|
2731
|
+
return {
|
|
2732
|
+
psbt: bytes,
|
|
2733
|
+
chain,
|
|
2734
|
+
inputsToSign: inputsToSign.map((item) => {
|
|
2735
|
+
const { address, signingIndexes, sigHash } = typeof item === "object" && item !== null ? item : {};
|
|
2736
|
+
if (typeof address !== "string" || !Array.isArray(signingIndexes) || signingIndexes.length === 0 || !signingIndexes.every((i) => Number.isSafeInteger(i) && i >= 0)) throw invalidParams("inputsToSign needs an account and signing indexes");
|
|
2737
|
+
return {
|
|
2738
|
+
address,
|
|
2739
|
+
signingIndexes: signingIndexes.map(Number),
|
|
2740
|
+
sigHash: sigHashOf(sigHash)
|
|
2741
|
+
};
|
|
2742
|
+
})
|
|
2743
|
+
};
|
|
2744
|
+
});
|
|
2745
|
+
};
|
|
2746
|
+
const byOrigin$1 = (sessions) => new Map(Object.values(sessions).map((s) => [s.origin.origin, s]));
|
|
2747
|
+
const bitcoinAccountList = (session) => Object.entries(session.scopes).filter(([network]) => network.startsWith("bip122:")).flatMap(([, scope]) => scope.accounts.map((a) => a.slice(a.lastIndexOf(":") + 1)));
|
|
2748
|
+
function diffSessions$1(before, after) {
|
|
2749
|
+
const events = [];
|
|
2750
|
+
const prev = byOrigin$1(before);
|
|
2751
|
+
const next = byOrigin$1(after);
|
|
2752
|
+
for (const [origin, session] of prev) {
|
|
2753
|
+
const now = next.get(origin);
|
|
2754
|
+
if (bitcoinAccountList(session).join(",") !== (now === void 0 ? "" : bitcoinAccountList(now).join(","))) events.push({ origin });
|
|
2755
|
+
}
|
|
2756
|
+
for (const [origin, session] of next) if (!prev.has(origin) && bitcoinAccountList(session).length > 0) events.push({ origin });
|
|
2757
|
+
return events;
|
|
2758
|
+
}
|
|
2759
|
+
// src/connect/nip07.ts
|
|
2760
|
+
/** `signEvent` of these kinds always asks for explicit confirmation, whatever the policy allows. */
|
|
2761
|
+
const FORCED_CONFIRM_KINDS = /* @__PURE__ */ new Set([
|
|
2762
|
+
0,
|
|
2763
|
+
3,
|
|
2764
|
+
5,
|
|
2765
|
+
10002
|
|
2766
|
+
]);
|
|
2767
|
+
const MAX_TAGS = 64;
|
|
2768
|
+
const MAX_TAG_ITEMS = 32;
|
|
2769
|
+
const MAX_TAG_ITEM_LENGTH = 1024;
|
|
2770
|
+
const MAX_CONTENT_LENGTH = 131072;
|
|
2771
|
+
const isObject$1 = (v) => typeof v === "object" && v !== null;
|
|
2772
|
+
/**
|
|
2773
|
+
* Strict event validation: `kind` is an integer 0–65535, `created_at` a safe integer, `tags` a
|
|
2774
|
+
* bounded `string[][]`, `content` a bounded string and `pubkey` — when present — a string.
|
|
2775
|
+
*/
|
|
2776
|
+
function checkEvent(value) {
|
|
2777
|
+
if (!isObject$1(value)) throw invalidParams("event is not an object");
|
|
2778
|
+
const { kind, content, pubkey, tags, created_at: createdAt } = value;
|
|
2779
|
+
if (typeof kind !== "number" || !Number.isSafeInteger(kind) || kind < 0 || kind > 65535) throw invalidParams("event.kind must be an integer 0–65535");
|
|
2780
|
+
if (typeof content !== "string" || content.length > MAX_CONTENT_LENGTH) throw invalidParams("event.content must be a string");
|
|
2781
|
+
if (pubkey !== void 0 && typeof pubkey !== "string") throw invalidParams("event.pubkey must be a string");
|
|
2782
|
+
if (typeof createdAt !== "number" || !Number.isSafeInteger(createdAt)) throw invalidParams("event.created_at must be a safe integer");
|
|
2783
|
+
if (!Array.isArray(tags) || tags.length > MAX_TAGS) throw invalidParams("event.tags must be a bounded array of string arrays");
|
|
2784
|
+
const checkedTags = [];
|
|
2785
|
+
for (const tag of tags) {
|
|
2786
|
+
if (!Array.isArray(tag) || tag.length > MAX_TAG_ITEMS) throw invalidParams("event.tags items must be bounded string arrays");
|
|
2787
|
+
const checkedTag = [];
|
|
2788
|
+
for (const item of tag) {
|
|
2789
|
+
if (typeof item !== "string" || item.length > MAX_TAG_ITEM_LENGTH) throw invalidParams("event.tags items must contain bounded strings");
|
|
2790
|
+
checkedTag.push(item);
|
|
2791
|
+
}
|
|
2792
|
+
checkedTags.push(checkedTag);
|
|
2793
|
+
}
|
|
2794
|
+
return {
|
|
2795
|
+
kind,
|
|
2796
|
+
content,
|
|
2797
|
+
created_at: createdAt,
|
|
2798
|
+
tags: checkedTags,
|
|
2799
|
+
...pubkey === void 0 ? {} : { pubkey }
|
|
2800
|
+
};
|
|
2801
|
+
}
|
|
2802
|
+
/** NIP-04/NIP-44 encrypt/decrypt take `[peerPubkey, text]`. */
|
|
2803
|
+
function peerText(params) {
|
|
2804
|
+
if (!Array.isArray(params) || typeof params[0] !== "string" || typeof params[1] !== "string") throw invalidParams("expected [peerPubkey, text]");
|
|
2805
|
+
return {
|
|
2806
|
+
peer: params[0],
|
|
2807
|
+
text: params[1]
|
|
2808
|
+
};
|
|
2809
|
+
}
|
|
2810
|
+
var Nip07Handler = class {
|
|
2811
|
+
options;
|
|
2812
|
+
constructor(options) {
|
|
2813
|
+
this.options = options;
|
|
2814
|
+
}
|
|
2815
|
+
async handle(origin, request) {
|
|
2816
|
+
const { connections } = this.options;
|
|
2817
|
+
connections.checkOrigin(origin);
|
|
2818
|
+
const identity = connections.activeIdentity();
|
|
2819
|
+
if (identity === void 0) throw unauthorized();
|
|
2820
|
+
const pubkey = connections.nostrAccount(origin);
|
|
2821
|
+
switch (request.method) {
|
|
2822
|
+
case "getPublicKey": return this.publicKey(origin, pubkey);
|
|
2823
|
+
case "signEvent": return this.signEvent(origin, pubkey, identity, request.params);
|
|
2824
|
+
case "nip04.encrypt":
|
|
2825
|
+
case "nip04.decrypt":
|
|
2826
|
+
case "nip44.encrypt":
|
|
2827
|
+
case "nip44.decrypt": {
|
|
2828
|
+
connections.authorize(origin, "nostr", request.method);
|
|
2829
|
+
const { peer, text } = peerText(request.params);
|
|
2830
|
+
return this.crypt(origin, identity, request.method, peer, text);
|
|
2831
|
+
}
|
|
2832
|
+
default: throw unauthorized();
|
|
2833
|
+
}
|
|
2834
|
+
}
|
|
2835
|
+
async publicKey(origin, pubkey) {
|
|
2836
|
+
const { connections } = this.options;
|
|
2837
|
+
if (pubkey === void 0) await connections.request(origin, {
|
|
2838
|
+
kind: "connect",
|
|
2839
|
+
namespace: "nostr"
|
|
2840
|
+
});
|
|
2841
|
+
await connections.touch(origin);
|
|
2842
|
+
const granted = connections.nostrAccount(origin);
|
|
2843
|
+
if (granted === void 0) throw unauthorized();
|
|
2844
|
+
return granted;
|
|
2845
|
+
}
|
|
2846
|
+
async signEvent(origin, pubkey, identity, params) {
|
|
2847
|
+
const { connections, requests, signerFor } = this.options;
|
|
2848
|
+
const session = connections.authorize(origin, "nostr", "signEvent");
|
|
2849
|
+
const event = checkEvent(Array.isArray(params) ? params[0] : params);
|
|
2850
|
+
if (event.pubkey !== void 0 && event.pubkey !== pubkey) throw invalidParams("event.pubkey does not match the active identity");
|
|
2851
|
+
if (pubkey === void 0) throw unauthorized();
|
|
2852
|
+
const policy = session.nostrPolicy ?? {
|
|
2853
|
+
signing: "ask",
|
|
2854
|
+
decrypt: false
|
|
2855
|
+
};
|
|
2856
|
+
const direct = policy.signing === "always" || typeof policy.signing === "object" && policy.signing.kinds.includes(event.kind);
|
|
2857
|
+
const signing = {
|
|
2858
|
+
...event,
|
|
2859
|
+
pubkey
|
|
2860
|
+
};
|
|
2861
|
+
if (direct && !FORCED_CONFIRM_KINDS.has(event.kind)) {
|
|
2862
|
+
await connections.touch(origin);
|
|
2863
|
+
return signerFor(identity).signEvent(signing);
|
|
2864
|
+
}
|
|
2865
|
+
const pending = await requests.prepare({
|
|
2866
|
+
method: "nostr-sign",
|
|
2867
|
+
origin: {
|
|
2868
|
+
kind: "browser",
|
|
2869
|
+
origin
|
|
2870
|
+
},
|
|
2871
|
+
ref: identity,
|
|
2872
|
+
event: signing
|
|
2873
|
+
});
|
|
2874
|
+
const outcome = await requests.outcome(pending.id);
|
|
2875
|
+
if (outcome === void 0 || !("event" in outcome)) throw unauthorized();
|
|
2876
|
+
return outcome.event;
|
|
2877
|
+
}
|
|
2878
|
+
async crypt(origin, identity, method, peer, text) {
|
|
2879
|
+
const { connections, signerFor } = this.options;
|
|
2880
|
+
if (method.endsWith(".decrypt") && connections.nostrPolicy(origin)?.decrypt !== true) throw unauthorized();
|
|
2881
|
+
await connections.touch(origin);
|
|
2882
|
+
const signer = signerFor(identity);
|
|
2883
|
+
const fn = method === "nip04.encrypt" ? signer.nip04Encrypt : method === "nip04.decrypt" ? signer.nip04Decrypt : method === "nip44.encrypt" ? signer.nip44Encrypt : signer.nip44Decrypt;
|
|
2884
|
+
if (fn === void 0) throw unauthorized();
|
|
2885
|
+
return fn(peer, text);
|
|
2886
|
+
}
|
|
2887
|
+
};
|
|
2888
|
+
// src/connect/siws.ts
|
|
2889
|
+
const STATEMENT_MAX = 1024;
|
|
2890
|
+
const FIELD_MAX = 256;
|
|
2891
|
+
const RESOURCES_MAX = 32;
|
|
2892
|
+
const STRING_FIELDS = [
|
|
2893
|
+
"domain",
|
|
2894
|
+
"address",
|
|
2895
|
+
"statement",
|
|
2896
|
+
"uri",
|
|
2897
|
+
"version",
|
|
2898
|
+
"chainId",
|
|
2899
|
+
"nonce",
|
|
2900
|
+
"issuedAt",
|
|
2901
|
+
"expirationTime",
|
|
2902
|
+
"notBefore",
|
|
2903
|
+
"requestId"
|
|
2904
|
+
];
|
|
2905
|
+
const checkString$1 = (name, value, max) => {
|
|
2906
|
+
if (typeof value !== "string") throw invalidParams(`${name} must be a string`);
|
|
2907
|
+
if (value.includes("\n") || value.includes("\r")) throw invalidParams(`${name} must not contain line breaks`);
|
|
2908
|
+
if (value.length > max) throw invalidParams(`${name} is longer than ${String(max)} characters`);
|
|
2909
|
+
return value;
|
|
2910
|
+
};
|
|
2911
|
+
/** Validates a dApp's sign-in input: types, no line breaks, length caps. */
|
|
2912
|
+
function checkSignInInput(raw) {
|
|
2913
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw invalidParams("the sign-in input must be an object");
|
|
2914
|
+
const record = new Map(Object.entries(raw));
|
|
2915
|
+
const out = {};
|
|
2916
|
+
for (const name of STRING_FIELDS) {
|
|
2917
|
+
const value = record.get(name);
|
|
2918
|
+
if (value !== void 0) out[name] = checkString$1(name, value, name === "statement" ? STATEMENT_MAX : FIELD_MAX);
|
|
2919
|
+
}
|
|
2920
|
+
const resources = record.get("resources");
|
|
2921
|
+
if (resources !== void 0) {
|
|
2922
|
+
if (!Array.isArray(resources) || resources.length > RESOURCES_MAX) throw invalidParams(`resources must be an array of at most ${String(RESOURCES_MAX)} strings`);
|
|
2923
|
+
out["resources"] = resources.map((resource) => checkString$1("resources", resource, FIELD_MAX));
|
|
2924
|
+
}
|
|
2925
|
+
return out;
|
|
2926
|
+
}
|
|
2927
|
+
/**
|
|
2928
|
+
* The EIP-4361-style message, byte for byte `createSignInMessageText` of
|
|
2929
|
+
* `@solana/wallet-standard-util` 1.2.0 (an empty `resources` array still prints `Resources:`).
|
|
2930
|
+
*/
|
|
2931
|
+
function signInMessageText(input) {
|
|
2932
|
+
let message = `${input.domain} wants you to sign in with your Solana account:\n${input.address}`;
|
|
2933
|
+
if (input.statement !== void 0 && input.statement !== "") message += `\n\n${input.statement}`;
|
|
2934
|
+
const fields = [];
|
|
2935
|
+
const optional = [
|
|
2936
|
+
["URI", input.uri],
|
|
2937
|
+
["Version", input.version],
|
|
2938
|
+
["Chain ID", input.chainId],
|
|
2939
|
+
["Nonce", input.nonce],
|
|
2940
|
+
["Issued At", input.issuedAt],
|
|
2941
|
+
["Expiration Time", input.expirationTime],
|
|
2942
|
+
["Not Before", input.notBefore],
|
|
2943
|
+
["Request ID", input.requestId]
|
|
2944
|
+
];
|
|
2945
|
+
for (const [label, value] of optional) if (value !== void 0 && value !== "") fields.push(`${label}: ${value}`);
|
|
2946
|
+
if (input.resources !== void 0) {
|
|
2947
|
+
fields.push("Resources:");
|
|
2948
|
+
for (const resource of input.resources) fields.push(`- ${resource}`);
|
|
2949
|
+
}
|
|
2950
|
+
if (fields.length > 0) message += `\n\n${fields.join("\n")}`;
|
|
2951
|
+
return message;
|
|
2952
|
+
}
|
|
2953
|
+
// src/connect/solana.ts
|
|
2954
|
+
const solanaId = (name) => {
|
|
2955
|
+
const entry = SOLANA_NETWORKS.find((n) => n.name === name);
|
|
2956
|
+
if (entry === void 0) throw new Error(`no solana network named ${name} in the registry`);
|
|
2957
|
+
return entry.id;
|
|
2958
|
+
};
|
|
2959
|
+
/**
|
|
2960
|
+
* The Wallet Standard short chain ids to the registry's CAIP-2 genesis-hash ids, derived from the
|
|
2961
|
+
* solana network registry by name.
|
|
2962
|
+
*/
|
|
2963
|
+
const SOLANA_CHAIN_IDS = Object.freeze({
|
|
2964
|
+
"solana:mainnet": solanaId("Solana"),
|
|
2965
|
+
"solana:devnet": solanaId("Solana Devnet")
|
|
2966
|
+
});
|
|
2967
|
+
/** The Wallet Standard short id of a registry network, or `undefined` when it has none. */
|
|
2968
|
+
const walletStandardChain = (network) => Object.entries(SOLANA_CHAIN_IDS).find(([, id]) => id === network)?.[0];
|
|
2969
|
+
/**
|
|
2970
|
+
* The Wallet Standard handler: `standard:connect` authorizes the `solana` scope, `solana:*` sign
|
|
2971
|
+
* requests go through `solana-sign`, `solanaAccountsChanged` returns the re-pointed accounts the
|
|
2972
|
+
* bridge forwards as `standard:events` `change` on a group switch.
|
|
2973
|
+
*/
|
|
2974
|
+
var SolanaWalletHandler = class {
|
|
2975
|
+
options;
|
|
2976
|
+
events;
|
|
2977
|
+
constructor(options) {
|
|
2978
|
+
this.options = options;
|
|
2979
|
+
this.events = new SessionEvents(options.connections, async (before, after) => Promise.all(diffSessions(before, after).map(async ({ origin }) => ({
|
|
2980
|
+
name: "solanaAccountsChanged",
|
|
2981
|
+
origin,
|
|
2982
|
+
accounts: await this.solanaAccountsChanged(origin)
|
|
2983
|
+
}))));
|
|
2984
|
+
}
|
|
2985
|
+
/** `standard:events` `change` per origin — derived from changes to the sessions. */
|
|
2986
|
+
subscribe(listener) {
|
|
2987
|
+
return this.events.subscribe(listener);
|
|
2988
|
+
}
|
|
2989
|
+
async handle(origin, request) {
|
|
2990
|
+
const checked = this.options.connections.checkOrigin(origin);
|
|
2991
|
+
if (request.method === "standard:connect") return this.connect(checked, request);
|
|
2992
|
+
if (request.method === "standard:disconnect") {
|
|
2993
|
+
await this.options.connections.revoke(origin);
|
|
2994
|
+
return {};
|
|
2995
|
+
}
|
|
2996
|
+
if (request.method === "solana:signTransaction") return this.signTransactions(checked, request, false);
|
|
2997
|
+
if (request.method === "solana:signAndSendTransaction") return this.signTransactions(checked, request, true);
|
|
2998
|
+
if (request.method === "solana:signMessage") return this.signMessage(checked, request);
|
|
2999
|
+
if (request.method === "solana:signIn") return this.signIn(checked, request);
|
|
3000
|
+
throw invalidParams(`unsupported solana method ${request.method}`);
|
|
3001
|
+
}
|
|
3002
|
+
async connect(checked, request) {
|
|
3003
|
+
const silent = (typeof request.params === "object" && request.params !== null ? request.params : {}).silent === true;
|
|
3004
|
+
const network = this.options.solanaNetwork();
|
|
3005
|
+
if (this.options.connections.solanaAccount(checked.origin, network) === void 0) {
|
|
3006
|
+
if (silent) throw new ProviderError(4100, "the wallet is not connected");
|
|
3007
|
+
await this.options.connections.request(checked.origin, {
|
|
3008
|
+
kind: "connect",
|
|
3009
|
+
namespace: "solana"
|
|
3010
|
+
});
|
|
3011
|
+
} else await this.options.connections.touch(checked.origin);
|
|
3012
|
+
const group = this.options.activeGroup();
|
|
3013
|
+
if (group === void 0) throw new ProviderError(4100, "no account group is selected");
|
|
3014
|
+
const account = await this.options.solanaAccount(group, network);
|
|
3015
|
+
return { accounts: [this.walletAccount(account, network)] };
|
|
3016
|
+
}
|
|
3017
|
+
walletAccount(account, network) {
|
|
3018
|
+
const chain = walletStandardChain(network);
|
|
3019
|
+
if (chain === void 0) throw new ProviderError(-32603, `network ${network} has no Wallet Standard chain id`);
|
|
3020
|
+
return {
|
|
3021
|
+
address: account.address,
|
|
3022
|
+
publicKey: account.publicKey,
|
|
3023
|
+
chains: [chain],
|
|
3024
|
+
features: SOLANA_METHODS.filter((m) => m.startsWith("solana:"))
|
|
3025
|
+
};
|
|
3026
|
+
}
|
|
3027
|
+
async signTransactions(checked, request, send) {
|
|
3028
|
+
const network = this.networkOf(request.params, send);
|
|
3029
|
+
this.options.connections.authorize(checked.origin, network, request.method);
|
|
3030
|
+
const address = this.options.connections.solanaAccount(checked.origin, network);
|
|
3031
|
+
if (address === void 0) throw new ProviderError(4100, "no solana account for this origin");
|
|
3032
|
+
checkAccounts(request.params, address);
|
|
3033
|
+
const txs = transactionsOf(request.params);
|
|
3034
|
+
const outcome = await this.signRequest(checked, network, address, {
|
|
3035
|
+
kind: "transactions",
|
|
3036
|
+
transactions: txs,
|
|
3037
|
+
send
|
|
3038
|
+
});
|
|
3039
|
+
if (!("kind" in outcome) || outcome.kind !== "solana.transactions") throw new ProviderError(-32603, "the solana-sign request settled unexpectedly");
|
|
3040
|
+
return send ? { signatures: (outcome.signatures ?? []).map((signature) => base58.decode(signature)) } : { signedTransactions: outcome.signedTransactions };
|
|
3041
|
+
}
|
|
3042
|
+
/**
|
|
3043
|
+
* The network a transaction call targets: the wallet's default when no input names a chain,
|
|
3044
|
+
* otherwise the one chain every input agrees on (`chain` is required for sign-and-send).
|
|
3045
|
+
*/
|
|
3046
|
+
networkOf(params, requireChain) {
|
|
3047
|
+
const chains = paramList(params, "chains");
|
|
3048
|
+
if (requireChain && (chains.length === 0 || chains.some((chain) => chain === void 0))) throw invalidParams("chain is required for solana:signAndSendTransaction");
|
|
3049
|
+
const named = new Set(chains.filter((chain) => chain !== void 0));
|
|
3050
|
+
if (named.size === 0) return this.options.solanaNetwork();
|
|
3051
|
+
if (named.size > 1 || chains.some((chain) => chain === void 0)) throw invalidParams("every input must use the same chain");
|
|
3052
|
+
const [chain] = [...named];
|
|
3053
|
+
const network = typeof chain === "string" ? SOLANA_CHAIN_IDS[chain] : void 0;
|
|
3054
|
+
if (network === void 0) throw invalidParams("unknown chain");
|
|
3055
|
+
return network;
|
|
3056
|
+
}
|
|
3057
|
+
async signMessage(checked, request) {
|
|
3058
|
+
const network = this.options.solanaNetwork();
|
|
3059
|
+
this.options.connections.authorize(checked.origin, network, "solana:signMessage");
|
|
3060
|
+
const address = this.options.connections.solanaAccount(checked.origin, network);
|
|
3061
|
+
if (address !== void 0) checkAccounts(request.params, address);
|
|
3062
|
+
const message = messageOf(request.params);
|
|
3063
|
+
return {
|
|
3064
|
+
signature: await this.signMessageRequest(checked, network, message),
|
|
3065
|
+
signedMessage: message
|
|
3066
|
+
};
|
|
3067
|
+
}
|
|
3068
|
+
/**
|
|
3069
|
+
* Sign In With Solana: connects first when needed, binds the message to the page's host and the
|
|
3070
|
+
* session's account, and signs the exact text the user is shown.
|
|
3071
|
+
*/
|
|
3072
|
+
async signIn(checked, request) {
|
|
3073
|
+
const { input: raw } = typeof request.params === "object" && request.params !== null ? request.params : {};
|
|
3074
|
+
const input = checkSignInInput(raw === void 0 ? {} : raw);
|
|
3075
|
+
const { host } = new URL(checked.origin);
|
|
3076
|
+
if (input.domain !== void 0 && input.domain !== host) throw invalidParams("domain does not match the page");
|
|
3077
|
+
const { accounts } = await this.connect(checked, { method: "standard:connect" });
|
|
3078
|
+
const [walletAccount] = accounts;
|
|
3079
|
+
const network = this.options.solanaNetwork();
|
|
3080
|
+
this.options.connections.authorize(checked.origin, network, "solana:signIn");
|
|
3081
|
+
if (walletAccount === void 0) throw new ProviderError(4100, "no solana account for this origin");
|
|
3082
|
+
if (input.address !== void 0 && input.address !== walletAccount.address) throw new ProviderError(4100, "address is not the connected account");
|
|
3083
|
+
const fields = {
|
|
3084
|
+
...input,
|
|
3085
|
+
domain: host,
|
|
3086
|
+
address: walletAccount.address
|
|
3087
|
+
};
|
|
3088
|
+
const message = new TextEncoder().encode(signInMessageText(fields));
|
|
3089
|
+
return [{
|
|
3090
|
+
account: walletAccount,
|
|
3091
|
+
signedMessage: message,
|
|
3092
|
+
signature: await this.signMessageRequest(checked, network, message, fields),
|
|
3093
|
+
signatureType: "ed25519"
|
|
3094
|
+
}];
|
|
3095
|
+
}
|
|
3096
|
+
async signMessageRequest(checked, network, message, signIn) {
|
|
3097
|
+
const address = this.options.connections.solanaAccount(checked.origin, network);
|
|
3098
|
+
if (address === void 0) throw new ProviderError(4100, "no solana account for this origin");
|
|
3099
|
+
const outcome = await this.signRequest(checked, network, address, {
|
|
3100
|
+
kind: "message",
|
|
3101
|
+
message,
|
|
3102
|
+
...signIn === void 0 ? {} : { signIn }
|
|
3103
|
+
});
|
|
3104
|
+
if (!("kind" in outcome) || outcome.kind !== "solana.message") throw new ProviderError(-32603, "the solana-sign request settled unexpectedly");
|
|
3105
|
+
return outcome.signature;
|
|
3106
|
+
}
|
|
3107
|
+
/** One `solana-sign` request for the active group, resolved to its outcome. */
|
|
3108
|
+
async signRequest(checked, network, address, request) {
|
|
3109
|
+
const group = this.options.activeGroup();
|
|
3110
|
+
if (group === void 0) throw new ProviderError(4100, "no account group is selected");
|
|
3111
|
+
try {
|
|
3112
|
+
const pending = await this.options.requests.prepare({
|
|
3113
|
+
method: "solana-sign",
|
|
3114
|
+
origin: checked,
|
|
3115
|
+
account: {
|
|
3116
|
+
walletId: group.walletId,
|
|
3117
|
+
groupIndex: group.groupIndex,
|
|
3118
|
+
address
|
|
3119
|
+
},
|
|
3120
|
+
network,
|
|
3121
|
+
request
|
|
3122
|
+
});
|
|
3123
|
+
return await this.options.requests.outcome(pending.id);
|
|
3124
|
+
} catch (error) {
|
|
3125
|
+
if (error instanceof BlindSigningDisabledError) throw new ProviderError(4200, error.message);
|
|
3126
|
+
throw error instanceof SignInOriginError ? invalidParams(error.message) : error;
|
|
3127
|
+
}
|
|
3128
|
+
}
|
|
3129
|
+
/** The `setActiveGroup` re-point: the solana session's new `WalletAccount[]` for `change`. */
|
|
3130
|
+
async solanaAccountsChanged(_origin) {
|
|
3131
|
+
const network = this.options.solanaNetwork();
|
|
3132
|
+
const group = this.options.activeGroup();
|
|
3133
|
+
if (group === void 0) return [];
|
|
3134
|
+
const account = await this.options.solanaAccount(group, network);
|
|
3135
|
+
return [this.walletAccount(account, network)];
|
|
3136
|
+
}
|
|
3137
|
+
};
|
|
3138
|
+
const paramList = (params, name) => {
|
|
3139
|
+
const value = typeof params === "object" && params !== null ? new Map(Object.entries(params)).get(name) : void 0;
|
|
3140
|
+
if (value === void 0) return [];
|
|
3141
|
+
if (!Array.isArray(value)) throw invalidParams(`${name} must be an array`);
|
|
3142
|
+
return value;
|
|
3143
|
+
};
|
|
3144
|
+
/** Every account the page names must be the session's Solana account. */
|
|
3145
|
+
const checkAccounts = (params, address) => {
|
|
3146
|
+
if (paramList(params, "accounts").some((account) => account !== address)) throw new ProviderError(4100, "account is not the connected account");
|
|
3147
|
+
};
|
|
3148
|
+
const isBytesEnvelope = (v) => typeof v === "object" && v !== null && typeof v.__bytes === "string";
|
|
3149
|
+
const transactionsOf = (params) => {
|
|
3150
|
+
const raw = typeof params === "object" && params !== null ? params.transactions : void 0;
|
|
3151
|
+
if (!Array.isArray(raw)) throw invalidParams("solana:signTransaction needs a transactions array");
|
|
3152
|
+
return raw.map((tx) => {
|
|
3153
|
+
if (tx instanceof Uint8Array) return tx;
|
|
3154
|
+
if (typeof tx === "string" && /^[0-9a-fA-F]+$/.test(tx)) return hexToBytes(tx);
|
|
3155
|
+
if (isBytesEnvelope(tx)) return hexToBytes(tx.__bytes);
|
|
3156
|
+
throw invalidParams("each transaction must be Uint8Array bytes or hex");
|
|
3157
|
+
});
|
|
3158
|
+
};
|
|
3159
|
+
const messageOf = (params) => {
|
|
3160
|
+
const message = typeof params === "object" && params !== null ? params.message : void 0;
|
|
3161
|
+
if (message instanceof Uint8Array) return message;
|
|
3162
|
+
if (typeof message === "string" && /^[0-9a-fA-F]+$/.test(message)) return hexToBytes(message);
|
|
3163
|
+
if (isBytesEnvelope(message)) return hexToBytes(message.__bytes);
|
|
3164
|
+
throw invalidParams("solana:signMessage needs Uint8Array bytes or hex");
|
|
3165
|
+
};
|
|
3166
|
+
const byOrigin = (sessions) => new Map(Object.values(sessions).map((s) => [s.origin.origin, s]));
|
|
3167
|
+
const solanaAccounts = (session) => Object.entries(session.scopes).filter(([network]) => network.startsWith("solana:")).flatMap(([, scope]) => scope.accounts.map((a) => a.slice(a.lastIndexOf(":") + 1)));
|
|
3168
|
+
function diffSessions(before, after) {
|
|
3169
|
+
const events = [];
|
|
3170
|
+
const prev = byOrigin(before);
|
|
3171
|
+
const next = byOrigin(after);
|
|
3172
|
+
for (const [origin, session] of prev) {
|
|
3173
|
+
const now = next.get(origin);
|
|
3174
|
+
if (solanaAccounts(session).join(",") !== (now === void 0 ? "" : solanaAccounts(now).join(","))) events.push({
|
|
3175
|
+
origin,
|
|
3176
|
+
accounts: now === void 0 ? [] : solanaAccounts(now)
|
|
3177
|
+
});
|
|
3178
|
+
}
|
|
3179
|
+
for (const [origin, session] of next) if (!prev.has(origin)) {
|
|
3180
|
+
const accounts = solanaAccounts(session);
|
|
3181
|
+
if (accounts.length > 0) events.push({
|
|
3182
|
+
origin,
|
|
3183
|
+
accounts
|
|
3184
|
+
});
|
|
3185
|
+
}
|
|
3186
|
+
return events;
|
|
3187
|
+
}
|
|
3188
|
+
// src/payments/parse.ts
|
|
3189
|
+
/** Invoices with less than this much life left are treated as already expired. */
|
|
3190
|
+
const BOLT11_EXPIRY_GRACE_MS = 6e4;
|
|
3191
|
+
const invalid = (reason) => ({
|
|
3192
|
+
kind: "invalid",
|
|
3193
|
+
reason
|
|
3194
|
+
});
|
|
3195
|
+
/** BTC decimal `amount` → sats. At most 8 decimal places; must fit a safe integer. */
|
|
3196
|
+
function btcAmountSats(text) {
|
|
3197
|
+
const match = /^(\d+)(?:\.(\d{1,8}))?$/.exec(text);
|
|
3198
|
+
if (match === null) return;
|
|
3199
|
+
const [, whole] = match;
|
|
3200
|
+
if (whole === void 0) return;
|
|
3201
|
+
const sats = BigInt(whole) * 100000000n + BigInt((match[2] ?? "").padEnd(8, "0") || "0");
|
|
3202
|
+
return sats <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(sats) : void 0;
|
|
3203
|
+
}
|
|
3204
|
+
/**
|
|
3205
|
+
* BOLT11 → fields, network- and expiry-checked. `undefined` = not a bolt11 string; `"network"` /
|
|
3206
|
+
* `"expired"` / `"malformed"` are the failure modes.
|
|
3207
|
+
*/
|
|
3208
|
+
function bolt11Fields(text, options) {
|
|
3209
|
+
let decoded;
|
|
3210
|
+
try {
|
|
3211
|
+
decoded = decodeBolt11(text);
|
|
3212
|
+
} catch {
|
|
3213
|
+
return;
|
|
3214
|
+
}
|
|
3215
|
+
const network = decoded.network === "mainnet" ? "mainnet" : decoded.network === "regtest" ? "regtest" : void 0;
|
|
3216
|
+
if (network === void 0) return "network";
|
|
3217
|
+
if (network !== options.network) return "network";
|
|
3218
|
+
const expiresAt = (decoded.timestamp + decoded.expirySeconds) * 1e3;
|
|
3219
|
+
if (expiresAt <= options.now + BOLT11_EXPIRY_GRACE_MS) return "expired";
|
|
3220
|
+
return {
|
|
3221
|
+
...decoded.amountMsat === void 0 ? {} : { amountSats: Math.ceil(Number(decoded.amountMsat) / 1e3) },
|
|
3222
|
+
paymentHash: bytesToHex(decoded.paymentHash),
|
|
3223
|
+
...decoded.description === void 0 ? {} : { description: decoded.description },
|
|
3224
|
+
expiresAt
|
|
3225
|
+
};
|
|
3226
|
+
}
|
|
3227
|
+
/** Spark address or sats/token invoice → options. `null` means not a spark input. */
|
|
3228
|
+
function sparkOptions(text, options) {
|
|
3229
|
+
let decoded;
|
|
3230
|
+
try {
|
|
3231
|
+
decoded = decodeSparkAddress(text);
|
|
3232
|
+
} catch {
|
|
3233
|
+
return;
|
|
3234
|
+
}
|
|
3235
|
+
if (decoded.network !== options.network) return "network";
|
|
3236
|
+
if (decoded.invoice === void 0) return [{
|
|
3237
|
+
kind: "spark",
|
|
3238
|
+
address: text
|
|
3239
|
+
}];
|
|
3240
|
+
if (decoded.invoice.expiresAt !== void 0 && decoded.invoice.expiresAt <= options.now) return "expired";
|
|
3241
|
+
if (decoded.invoice.payment?.type === "tokens") return "token";
|
|
3242
|
+
let parsed;
|
|
3243
|
+
try {
|
|
3244
|
+
parsed = parseSparkInvoice(text, {
|
|
3245
|
+
network: options.network,
|
|
3246
|
+
now: options.now
|
|
3247
|
+
});
|
|
3248
|
+
} catch {
|
|
3249
|
+
return "malformed";
|
|
3250
|
+
}
|
|
3251
|
+
const { payment } = parsed.fields;
|
|
3252
|
+
return [{
|
|
3253
|
+
kind: "spark-invoice",
|
|
3254
|
+
invoice: text,
|
|
3255
|
+
...payment?.type === "sats" && payment.amount !== void 0 ? { amountSats: payment.amount } : {},
|
|
3256
|
+
...parsed.fields.memo === void 0 ? {} : { memo: parsed.fields.memo },
|
|
3257
|
+
...parsed.fields.expiresAt === void 0 ? {} : { expiresAt: parsed.fields.expiresAt }
|
|
3258
|
+
}];
|
|
3259
|
+
}
|
|
3260
|
+
/** Does `address` decode under the other network? Used only to classify a rejection. */
|
|
3261
|
+
function decodesOnOtherNetwork(address, options) {
|
|
3262
|
+
try {
|
|
3263
|
+
bitcoinAddressScript(address, options.network === "mainnet" ? "regtest" : "mainnet");
|
|
3264
|
+
return true;
|
|
3265
|
+
} catch {
|
|
3266
|
+
return false;
|
|
3267
|
+
}
|
|
3268
|
+
}
|
|
3269
|
+
/** BIP-21 URI → request. Only the `spark=` and `lightning=` payment methods are supported. */
|
|
3270
|
+
function bip21Parse(text, options) {
|
|
3271
|
+
const q = text.indexOf("?");
|
|
3272
|
+
const address = text.slice(8, q === -1 ? void 0 : q);
|
|
3273
|
+
const params = /* @__PURE__ */ new Map();
|
|
3274
|
+
if (q !== -1) for (const pair of text.slice(q + 1).split("&")) {
|
|
3275
|
+
const eq = pair.indexOf("=");
|
|
3276
|
+
if (eq === -1) return invalid("malformed");
|
|
3277
|
+
let key;
|
|
3278
|
+
let value;
|
|
3279
|
+
try {
|
|
3280
|
+
key = decodeURIComponent(pair.slice(0, eq)).toLowerCase();
|
|
3281
|
+
value = decodeURIComponent(pair.slice(eq + 1));
|
|
3282
|
+
} catch {
|
|
3283
|
+
return invalid("malformed");
|
|
3284
|
+
}
|
|
3285
|
+
if (params.has(key)) return invalid("malformed");
|
|
3286
|
+
if (key.startsWith("req-") && !BIP21_KNOWN_REQ_PARAMS.has(key)) return invalid("malformed");
|
|
3287
|
+
params.set(key, value);
|
|
3288
|
+
}
|
|
3289
|
+
const options_ = [];
|
|
3290
|
+
let declaredSats;
|
|
3291
|
+
const spark = params.get("spark");
|
|
3292
|
+
if (spark !== void 0) {
|
|
3293
|
+
const parsed = sparkOptions(spark, options);
|
|
3294
|
+
if (parsed === void 0 || parsed === "malformed") return invalid("malformed");
|
|
3295
|
+
if (parsed === "token") return {
|
|
3296
|
+
kind: "unsupported",
|
|
3297
|
+
format: "spark-token-invoice"
|
|
3298
|
+
};
|
|
3299
|
+
if (parsed === "network" || parsed === "expired") return invalid(parsed);
|
|
3300
|
+
options_.push(...parsed);
|
|
3301
|
+
const sats = parsed.find((o) => o.kind === "spark-invoice")?.amountSats;
|
|
3302
|
+
if (sats !== void 0) {
|
|
3303
|
+
if (declaredSats !== void 0 && declaredSats !== sats) return invalid("amount-mismatch");
|
|
3304
|
+
declaredSats = sats;
|
|
3305
|
+
}
|
|
3306
|
+
}
|
|
3307
|
+
const lightning = params.get("lightning");
|
|
3308
|
+
if (lightning !== void 0) {
|
|
3309
|
+
const parsed = bolt11Fields(lightning, options);
|
|
3310
|
+
if (parsed === void 0 || parsed === "malformed") return invalid("malformed");
|
|
3311
|
+
if (parsed === "network" || parsed === "expired") return invalid(parsed);
|
|
3312
|
+
options_.push({
|
|
3313
|
+
kind: "lightning",
|
|
3314
|
+
invoice: lightning,
|
|
3315
|
+
...parsed.amountSats === void 0 ? {} : { amountSats: parsed.amountSats },
|
|
3316
|
+
paymentHash: parsed.paymentHash,
|
|
3317
|
+
...parsed.description === void 0 ? {} : { description: parsed.description },
|
|
3318
|
+
expiresAt: parsed.expiresAt
|
|
3319
|
+
});
|
|
3320
|
+
if (parsed.amountSats !== void 0) {
|
|
3321
|
+
if (declaredSats !== void 0 && declaredSats !== parsed.amountSats) return invalid("amount-mismatch");
|
|
3322
|
+
declaredSats = parsed.amountSats;
|
|
3323
|
+
}
|
|
3324
|
+
}
|
|
3325
|
+
if (address.length > 0) {
|
|
3326
|
+
try {
|
|
3327
|
+
bitcoinAddressScript(address, options.network);
|
|
3328
|
+
} catch {
|
|
3329
|
+
return invalid(decodesOnOtherNetwork(address, options) ? "network" : "malformed");
|
|
3330
|
+
}
|
|
3331
|
+
options_.push({
|
|
3332
|
+
kind: "bitcoin",
|
|
3333
|
+
address
|
|
3334
|
+
});
|
|
3335
|
+
}
|
|
3336
|
+
const declaredAmount = params.get("amount");
|
|
3337
|
+
if (declaredAmount !== void 0) {
|
|
3338
|
+
const sats = btcAmountSats(declaredAmount);
|
|
3339
|
+
if (sats === void 0) return invalid("malformed");
|
|
3340
|
+
if (declaredSats !== void 0 && declaredSats !== sats) return invalid("amount-mismatch");
|
|
3341
|
+
declaredSats = sats;
|
|
3342
|
+
}
|
|
3343
|
+
if (options_.length === 0) {
|
|
3344
|
+
if (params.has("lno")) return {
|
|
3345
|
+
kind: "unsupported",
|
|
3346
|
+
format: "bolt12"
|
|
3347
|
+
};
|
|
3348
|
+
if (params.has("sp")) return {
|
|
3349
|
+
kind: "unsupported",
|
|
3350
|
+
format: "silent-payment"
|
|
3351
|
+
};
|
|
3352
|
+
return invalid("malformed");
|
|
3353
|
+
}
|
|
3354
|
+
return {
|
|
3355
|
+
kind: "request",
|
|
3356
|
+
request: {
|
|
3357
|
+
options: options_,
|
|
3358
|
+
...declaredSats === void 0 ? {} : { amountSats: declaredSats },
|
|
3359
|
+
...params.get("label") === void 0 ? {} : { label: params.get("label") ?? "" },
|
|
3360
|
+
...params.get("message") === void 0 ? {} : { message: params.get("message") ?? "" }
|
|
3361
|
+
}
|
|
3362
|
+
};
|
|
3363
|
+
}
|
|
3364
|
+
const BIP21_KNOWN_REQ_PARAMS = /* @__PURE__ */ new Set([
|
|
3365
|
+
"req-amount",
|
|
3366
|
+
"req-label",
|
|
3367
|
+
"req-message"
|
|
3368
|
+
]);
|
|
3369
|
+
/** `input` → PaymentParse. Never throws: every failure is a structured result. */
|
|
3370
|
+
function parsePayment(input, options) {
|
|
3371
|
+
try {
|
|
3372
|
+
const text = input.trim();
|
|
3373
|
+
if (/^nostr\+walletconnect:/i.test(text)) return {
|
|
3374
|
+
kind: "unsupported",
|
|
3375
|
+
format: "nostr-wallet-connect"
|
|
3376
|
+
};
|
|
3377
|
+
const stripped = text.toLowerCase().startsWith("lightning:") ? text.slice(10) : text;
|
|
3378
|
+
if (/^bitcoin:/i.test(stripped)) return bip21Parse(`bitcoin:${stripped.slice(stripped.indexOf(":") + 1)}`, options);
|
|
3379
|
+
const bolt11 = bolt11Fields(stripped, options);
|
|
3380
|
+
if (bolt11 === "network" || bolt11 === "expired" || bolt11 === "malformed") return invalid(bolt11);
|
|
3381
|
+
if (bolt11 !== void 0) return {
|
|
3382
|
+
kind: "request",
|
|
3383
|
+
request: {
|
|
3384
|
+
options: [{
|
|
3385
|
+
kind: "lightning",
|
|
3386
|
+
invoice: stripped,
|
|
3387
|
+
...bolt11.amountSats === void 0 ? {} : { amountSats: bolt11.amountSats },
|
|
3388
|
+
paymentHash: bolt11.paymentHash,
|
|
3389
|
+
...bolt11.description === void 0 ? {} : { description: bolt11.description },
|
|
3390
|
+
expiresAt: bolt11.expiresAt
|
|
3391
|
+
}],
|
|
3392
|
+
...bolt11.amountSats === void 0 ? {} : { amountSats: bolt11.amountSats }
|
|
3393
|
+
}
|
|
3394
|
+
};
|
|
3395
|
+
const spark = sparkOptions(stripped, options);
|
|
3396
|
+
if (spark === "token") return {
|
|
3397
|
+
kind: "unsupported",
|
|
3398
|
+
format: "spark-token-invoice"
|
|
3399
|
+
};
|
|
3400
|
+
if (spark === "network" || spark === "expired" || spark === "malformed") return invalid(spark);
|
|
3401
|
+
if (spark !== void 0) return {
|
|
3402
|
+
kind: "request",
|
|
3403
|
+
request: { options: spark }
|
|
3404
|
+
};
|
|
3405
|
+
if (/^(lnurlp|lnurlw):/i.test(stripped)) {
|
|
3406
|
+
const rest = stripped.slice(stripped.indexOf("://") + 3);
|
|
3407
|
+
const url = `${(rest.split(/[/?#]/, 1)[0] ?? "").toLowerCase().endsWith(".onion") ? "http" : "https"}://${rest}`;
|
|
3408
|
+
if (new URL(url).searchParams.get("tag") === "login") return {
|
|
3409
|
+
kind: "unsupported",
|
|
3410
|
+
format: "lnurl-auth"
|
|
3411
|
+
};
|
|
3412
|
+
return {
|
|
3413
|
+
kind: "lnurl",
|
|
3414
|
+
url
|
|
3415
|
+
};
|
|
3416
|
+
}
|
|
3417
|
+
if (/^keyauth:/i.test(stripped)) return {
|
|
3418
|
+
kind: "unsupported",
|
|
3419
|
+
format: "lnurl-auth"
|
|
3420
|
+
};
|
|
3421
|
+
if (!stripped.includes(":") && stripped.includes("@")) return {
|
|
3422
|
+
kind: "lnurl",
|
|
3423
|
+
url: lightningAddressUrl(stripped),
|
|
3424
|
+
address: stripped
|
|
3425
|
+
};
|
|
3426
|
+
if (/^lno1[02-9ac-hj-np-z]+$/i.test(stripped)) return {
|
|
3427
|
+
kind: "unsupported",
|
|
3428
|
+
format: "bolt12"
|
|
3429
|
+
};
|
|
3430
|
+
try {
|
|
3431
|
+
const url = decodeLnurl(stripped);
|
|
3432
|
+
if (new URL(url).searchParams.get("tag") === "login") return {
|
|
3433
|
+
kind: "unsupported",
|
|
3434
|
+
format: "lnurl-auth"
|
|
3435
|
+
};
|
|
3436
|
+
return {
|
|
3437
|
+
kind: "lnurl",
|
|
3438
|
+
url
|
|
3439
|
+
};
|
|
3440
|
+
} catch {}
|
|
3441
|
+
try {
|
|
3442
|
+
bitcoinAddressScript(stripped, options.network);
|
|
3443
|
+
return {
|
|
3444
|
+
kind: "request",
|
|
3445
|
+
request: { options: [{
|
|
3446
|
+
kind: "bitcoin",
|
|
3447
|
+
address: stripped
|
|
3448
|
+
}] }
|
|
3449
|
+
};
|
|
3450
|
+
} catch {
|
|
3451
|
+
if (decodesOnOtherNetwork(stripped, options)) return invalid("network");
|
|
3452
|
+
}
|
|
3453
|
+
return { kind: "unrecognized" };
|
|
3454
|
+
} catch {
|
|
3455
|
+
return invalid("malformed");
|
|
3456
|
+
}
|
|
3457
|
+
}
|
|
3458
|
+
// src/connect/webln.ts
|
|
3459
|
+
/**
|
|
3460
|
+
* The WebLN (`window.webln`) handler — the bridge routes `provider: "webln"` messages here.
|
|
3461
|
+
* `enable` asks for a `lightning` connection approval when the origin is not yet authorized;
|
|
3462
|
+
* `sendPayment` and `lnurl` pay through the request pipeline's `pay` (a funds request with a
|
|
3463
|
+
* factor) and then poll `paymentStatus` for the settled preimage; `makeInvoice` goes through the
|
|
3464
|
+
* factor-free `webln-invoice`; `getBalance` additionally needs the session's
|
|
3465
|
+
* `lightningPolicy.balance`; `getInfo` exposes only the configured alias and methods.
|
|
3466
|
+
*/
|
|
3467
|
+
const MAX_MEMO_LENGTH = 640;
|
|
3468
|
+
const PREIMAGE_POLL_START_MS = 1e3;
|
|
3469
|
+
const PREIMAGE_POLL_MAX_MS = 8e3;
|
|
3470
|
+
const PREIMAGE_POLL_BUDGET_MS = 6e4;
|
|
3471
|
+
const isObject = (v) => typeof v === "object" && v !== null;
|
|
3472
|
+
const checkString = (value, name) => {
|
|
3473
|
+
if (typeof value !== "string" || value === "") throw invalidParams(`${name} must be a non-empty string`);
|
|
3474
|
+
return value;
|
|
3475
|
+
};
|
|
3476
|
+
const checkAmount = (value, name) => {
|
|
3477
|
+
if (value === void 0) return;
|
|
3478
|
+
const n = typeof value === "string" ? Number(value) : value;
|
|
3479
|
+
if (typeof n !== "number" || !Number.isSafeInteger(n) || n < 0) throw invalidParams(`${name} must be a non-negative safe integer`);
|
|
3480
|
+
return n;
|
|
3481
|
+
};
|
|
3482
|
+
const checkInvoiceArgs = (params) => {
|
|
3483
|
+
const args = isObject(params) ? params : {};
|
|
3484
|
+
const amount = checkAmount(args["amount"], "makeInvoice amount") ?? checkAmount(args["defaultAmount"], "makeInvoice defaultAmount");
|
|
3485
|
+
checkAmount(args["minimumAmount"], "makeInvoice minimumAmount");
|
|
3486
|
+
checkAmount(args["maximumAmount"], "makeInvoice maximumAmount");
|
|
3487
|
+
if (amount === void 0) throw invalidParams("makeInvoice needs an amount or a defaultAmount");
|
|
3488
|
+
const memo = args["defaultMemo"];
|
|
3489
|
+
if (memo !== void 0 && (typeof memo !== "string" || memo.length > MAX_MEMO_LENGTH)) throw invalidParams("makeInvoice defaultMemo must be a string at most 640 characters");
|
|
3490
|
+
return {
|
|
3491
|
+
amountSats: amount,
|
|
3492
|
+
...typeof memo === "string" ? { memo } : {}
|
|
3493
|
+
};
|
|
3494
|
+
};
|
|
3495
|
+
const checkMaxFee = (fn, amountSats) => {
|
|
3496
|
+
const maxFee = fn(amountSats);
|
|
3497
|
+
if (!Number.isSafeInteger(maxFee) || maxFee < 0) throw new ProviderError(-32603, "invalid lightning fee cap");
|
|
3498
|
+
return maxFee;
|
|
3499
|
+
};
|
|
3500
|
+
var WeblnHandler = class {
|
|
3501
|
+
options;
|
|
3502
|
+
constructor(options) {
|
|
3503
|
+
this.options = options;
|
|
3504
|
+
}
|
|
3505
|
+
ref() {
|
|
3506
|
+
const ref = this.options.sparkAccount();
|
|
3507
|
+
if (ref === void 0) throw unauthorized("no active group");
|
|
3508
|
+
return ref;
|
|
3509
|
+
}
|
|
3510
|
+
async handle(origin, request) {
|
|
3511
|
+
if (request.method === "enable") {
|
|
3512
|
+
if (this.options.connections.lightningPolicy(origin) === void 0) await this.options.connections.request(origin, {
|
|
3513
|
+
kind: "connect",
|
|
3514
|
+
namespace: "lightning"
|
|
3515
|
+
});
|
|
3516
|
+
await this.options.connections.touch(origin);
|
|
3517
|
+
return true;
|
|
3518
|
+
}
|
|
3519
|
+
this.options.connections.authorize(origin, "lightning", request.method);
|
|
3520
|
+
await this.options.connections.touch(origin);
|
|
3521
|
+
const ref = this.ref();
|
|
3522
|
+
switch (request.method) {
|
|
3523
|
+
case "getInfo": return {
|
|
3524
|
+
node: { alias: this.options.alias },
|
|
3525
|
+
methods: [...LIGHTNING_METHODS]
|
|
3526
|
+
};
|
|
3527
|
+
case "sendPayment": return this.sendPayment(origin, ref, request.params);
|
|
3528
|
+
case "makeInvoice": return this.makeInvoice(origin, ref, request.params);
|
|
3529
|
+
case "lnurl": return this.lnurl(origin, ref, request.params);
|
|
3530
|
+
case "getBalance": return this.getBalance(origin);
|
|
3531
|
+
default: throw unsupportedMethod(request.method);
|
|
3532
|
+
}
|
|
3533
|
+
}
|
|
3534
|
+
async sendPayment(origin, ref, params) {
|
|
3535
|
+
const invoice = checkString(params, "sendPayment invoice");
|
|
3536
|
+
const option = this.lightningOption(ref, invoice);
|
|
3537
|
+
if (option.amountSats === void 0) throw invalidParams("sendPayment needs a fixed-amount invoice");
|
|
3538
|
+
const maxFeeSats = checkMaxFee(this.options.lightningMaxFee, option.amountSats);
|
|
3539
|
+
const pending = await this.options.requests.prepare({
|
|
3540
|
+
method: "pay",
|
|
3541
|
+
origin: {
|
|
3542
|
+
kind: "browser",
|
|
3543
|
+
origin
|
|
3544
|
+
},
|
|
3545
|
+
account: ref,
|
|
3546
|
+
option,
|
|
3547
|
+
maxFeeSats
|
|
3548
|
+
});
|
|
3549
|
+
const outcome = await this.options.requests.outcome(pending.id);
|
|
3550
|
+
if (!("kind" in outcome) || outcome.kind !== "lightning") throw new ProviderError(-32603, "the lightning payment settled unexpectedly");
|
|
3551
|
+
return this.preimage(ref, outcome.payment);
|
|
3552
|
+
}
|
|
3553
|
+
async makeInvoice(origin, ref, params) {
|
|
3554
|
+
const { amountSats, memo } = checkInvoiceArgs(params);
|
|
3555
|
+
const pending = await this.options.requests.prepare({
|
|
3556
|
+
method: "webln-invoice",
|
|
3557
|
+
origin: {
|
|
3558
|
+
kind: "browser",
|
|
3559
|
+
origin
|
|
3560
|
+
},
|
|
3561
|
+
ref,
|
|
3562
|
+
amountSats,
|
|
3563
|
+
...memo === void 0 ? {} : { memo }
|
|
3564
|
+
});
|
|
3565
|
+
const outcome = await this.options.requests.outcome(pending.id);
|
|
3566
|
+
if (!("kind" in outcome) || outcome.kind !== "lightning.invoice") throw new ProviderError(-32603, "the invoice request settled unexpectedly");
|
|
3567
|
+
return { paymentRequest: outcome.paymentRequest };
|
|
3568
|
+
}
|
|
3569
|
+
async lnurl(origin, ref, params) {
|
|
3570
|
+
const parsed = parsePayment(checkString(params, "lnurl"), {
|
|
3571
|
+
network: ref.network,
|
|
3572
|
+
now: this.options.now()
|
|
3573
|
+
});
|
|
3574
|
+
if (parsed.kind !== "request") throw invalidParams("lnurl is not an LNURL-pay request");
|
|
3575
|
+
if (parsed.request.options.some((o) => o.kind === "lnurl-withdraw")) throw unsupportedMethod("lnurl-withdraw");
|
|
3576
|
+
const option = parsed.request.options.find((o) => o.kind === "lnurl-pay");
|
|
3577
|
+
if (option === void 0 || option.kind !== "lnurl-pay") throw invalidParams("lnurl is not an LNURL-pay request");
|
|
3578
|
+
const amountSats = Math.ceil(option.request.minSendableMsat / 1e3);
|
|
3579
|
+
const maxFeeSats = checkMaxFee(this.options.lightningMaxFee, amountSats);
|
|
3580
|
+
const pending = await this.options.requests.prepare({
|
|
3581
|
+
method: "pay",
|
|
3582
|
+
origin: {
|
|
3583
|
+
kind: "browser",
|
|
3584
|
+
origin
|
|
3585
|
+
},
|
|
3586
|
+
account: ref,
|
|
3587
|
+
option,
|
|
3588
|
+
amountSats,
|
|
3589
|
+
maxFeeSats,
|
|
3590
|
+
amountFromServiceMinimum: true
|
|
3591
|
+
});
|
|
3592
|
+
const outcome = await this.options.requests.outcome(pending.id);
|
|
3593
|
+
if (!("kind" in outcome) || outcome.kind !== "lightning") throw new ProviderError(-32603, "the lnurl payment settled unexpectedly");
|
|
3594
|
+
return this.preimage(ref, outcome.payment);
|
|
3595
|
+
}
|
|
3596
|
+
async preimage(ref, payment) {
|
|
3597
|
+
let delay = PREIMAGE_POLL_START_MS;
|
|
3598
|
+
let waited = 0;
|
|
3599
|
+
while (true) {
|
|
3600
|
+
const status = await this.options.spark.paymentStatus(ref, {
|
|
3601
|
+
requestId: payment.requestId,
|
|
3602
|
+
paymentHash: payment.paymentHash
|
|
3603
|
+
});
|
|
3604
|
+
if (status.outcome === "failed" || status.outcome === "returned") throw new ProviderError(-32603, "payment failed");
|
|
3605
|
+
if (status.outcome === "succeeded") {
|
|
3606
|
+
if (status.preimage === void 0) throw new ProviderError(-32603, "the lightning payment settled without a preimage");
|
|
3607
|
+
return { preimage: bytesToHex(status.preimage) };
|
|
3608
|
+
}
|
|
3609
|
+
if (waited >= PREIMAGE_POLL_BUDGET_MS) throw new ProviderError(-32603, "the lightning payment did not settle in time");
|
|
3610
|
+
const step = Math.min(delay, PREIMAGE_POLL_MAX_MS);
|
|
3611
|
+
await this.options.sleep(step);
|
|
3612
|
+
waited += step;
|
|
3613
|
+
delay *= 2;
|
|
3614
|
+
}
|
|
3615
|
+
}
|
|
3616
|
+
lightningOption(ref, invoice) {
|
|
3617
|
+
const parsed = parsePayment(invoice, {
|
|
3618
|
+
network: ref.network,
|
|
3619
|
+
now: this.options.now()
|
|
3620
|
+
});
|
|
3621
|
+
if (parsed.kind !== "request") throw invalidParams("sendPayment invoice is not a BOLT11 invoice");
|
|
3622
|
+
const option = parsed.request.options.find((o) => o.kind === "lightning");
|
|
3623
|
+
if (option === void 0 || option.kind !== "lightning") throw invalidParams("sendPayment invoice is not a BOLT11 invoice");
|
|
3624
|
+
return option;
|
|
3625
|
+
}
|
|
3626
|
+
getBalance(origin) {
|
|
3627
|
+
if (this.options.connections.lightningPolicy(origin)?.balance !== true) throw unauthorized("balance access is not granted");
|
|
3628
|
+
const balance = this.options.spark.accountBalance(this.ref());
|
|
3629
|
+
if (balance === void 0) throw new ProviderError(-32603, "no cached balance for the active spark account");
|
|
3630
|
+
return {
|
|
3631
|
+
balance,
|
|
3632
|
+
currency: "sats"
|
|
3633
|
+
};
|
|
3634
|
+
}
|
|
3635
|
+
};
|
|
3636
|
+
export { newId as A, normalizeAddress as B, exceedsNetworkCap as C, mergeSatPerByte as D, mergeEvmQuote as E, PaymentError as F, invalidParams as G, evmChainId as H, SparkControllerError as I, unsupportedMethod as J, unauthorized as K, categorize as L, submitTx as M, prepareZap as N, mergeSolanaQuote as O, withdrawLnurl as P, Controller as Q, safeDecimals as R, collectChecks as S, feesDiffer as T, ProviderError as U, ConnectionController as V, internalError as W, EngineStoreError as X, userRejectedRequest as Y, errorMessage as Z, boundedSimulation as _, Nip07Handler as a, feeTiers as b, SessionEvents as c, OriginBusyError as d, REQUEST_TTL_MS as f, SignInOriginError as g, RequestEndedError as h, SolanaWalletHandler as i, replacementStaleReason as j, failTx as k, BlindSigningDisabledError as l, RequestController as m, parsePayment as n, BITCOIN_CHAIN_IDS as o, RESIMULATE_AFTER_MS as p, unrecognizedChain as q, SOLANA_CHAIN_IDS as r, BitcoinWalletHandler as s, WeblnHandler as t, InvalidTokenError as u, BitcoinChainAdapter as v, feeReachesAmount as w, timeoutSignal as x, esplora as y, safeDisplayText as z };
|
|
3637
|
+
|
|
3638
|
+
//# sourceMappingURL=webln-BGKm12wd.mjs.map
|