@qntx/wallet-engine 0.12.0 → 0.14.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/README.md +1057 -20
- package/dist/apps-fiat24.d.mts +202 -0
- package/dist/apps-fiat24.mjs +1378 -0
- package/dist/apps-fiat24.mjs.map +1 -0
- package/dist/apps-hyperliquid.d.mts +549 -0
- package/dist/apps-hyperliquid.mjs +2742 -0
- package/dist/apps-hyperliquid.mjs.map +1 -0
- package/dist/apps-polymarket.d.mts +729 -0
- package/dist/apps-polymarket.mjs +3786 -0
- package/dist/apps-polymarket.mjs.map +1 -0
- package/dist/apps.d.mts +136 -0
- package/dist/apps.mjs +535 -0
- package/dist/apps.mjs.map +1 -0
- package/dist/connect-BY1C5ZRI.mjs +210 -0
- package/dist/connect-BY1C5ZRI.mjs.map +1 -0
- package/dist/connect.d.mts +17 -9
- package/dist/connect.mjs +3 -185
- package/dist/controller-DpNVHVsj.d.mts +2295 -0
- package/dist/controller-rMnaxKAH.mjs +46 -0
- package/dist/controller-rMnaxKAH.mjs.map +1 -0
- package/dist/decimal-COJ4g8qy.mjs +38 -0
- package/dist/decimal-COJ4g8qy.mjs.map +1 -0
- package/dist/eligibility-BfM9ybYZ.mjs +48 -0
- package/dist/eligibility-BfM9ybYZ.mjs.map +1 -0
- package/dist/engine-Dic_kkEr.d.mts +1829 -0
- package/dist/errors-B8W-hoYW.d.mts +7 -0
- package/dist/errors-horUy5k1.mjs +24 -0
- package/dist/errors-horUy5k1.mjs.map +1 -0
- package/dist/gateway-contract.d.mts +3 -362
- package/dist/gateway-contract.mjs +1531 -81
- package/dist/gateway-contract.mjs.map +1 -1
- package/dist/idb.d.mts +5 -0
- package/dist/idb.mjs +122 -46
- package/dist/idb.mjs.map +1 -1
- package/dist/index-vBgfOFIh.d.mts +2227 -0
- package/dist/index.d.mts +58 -515
- package/dist/index.mjs +22314 -4901
- package/dist/index.mjs.map +1 -1
- package/dist/json-BDwV38cj.mjs +15 -0
- package/dist/json-BDwV38cj.mjs.map +1 -0
- package/dist/link-Ceq8Dggp.mjs +139 -0
- package/dist/link-Ceq8Dggp.mjs.map +1 -0
- package/dist/primitives-DbSHLZKq.mjs +31 -0
- package/dist/primitives-DbSHLZKq.mjs.map +1 -0
- package/dist/push-message-AQuzoNFY.d.mts +84 -0
- package/dist/push-message-kbnH1A5w.mjs +142 -0
- package/dist/push-message-kbnH1A5w.mjs.map +1 -0
- package/dist/push.d.mts +13 -0
- package/dist/push.mjs +70 -0
- package/dist/push.mjs.map +1 -0
- package/dist/qr.d.mts +292 -0
- package/dist/qr.mjs +1725 -0
- package/dist/qr.mjs.map +1 -0
- package/dist/registry-CbtwcxkX.mjs +374 -0
- package/dist/registry-CbtwcxkX.mjs.map +1 -0
- package/dist/risk-DyABgg4W.mjs +757 -0
- package/dist/risk-DyABgg4W.mjs.map +1 -0
- package/dist/session-CNJFLarP.mjs +18 -0
- package/dist/session-CNJFLarP.mjs.map +1 -0
- package/dist/socket-ChG9JRT_.mjs +110 -0
- package/dist/socket-ChG9JRT_.mjs.map +1 -0
- package/dist/spi-BrTw5s98.d.mts +3 -0
- package/dist/timer-Cdk5rGM2.mjs +43 -0
- package/dist/timer-Cdk5rGM2.mjs.map +1 -0
- package/dist/types-BpvioFGo.d.mts +258 -0
- package/dist/types-DbftVZ3I.mjs +90 -0
- package/dist/types-DbftVZ3I.mjs.map +1 -0
- package/dist/walletconnect.d.mts +86 -0
- package/dist/walletconnect.mjs +1507 -0
- package/dist/walletconnect.mjs.map +1 -0
- package/dist/webln-BgrtPXpG.mjs +2593 -0
- package/dist/webln-BgrtPXpG.mjs.map +1 -0
- package/dist/webln-Bllk_xJ2.d.mts +666 -0
- package/package.json +94 -19
- package/dist/connect.mjs.map +0 -1
- package/dist/errors-DpkJneDe.d.mts +0 -1696
- package/dist/registry-Deo5WQe1.d.mts +0 -25
- package/dist/registry-wYrcuFNc.mjs +0 -99
- package/dist/registry-wYrcuFNc.mjs.map +0 -1
- package/dist/webln-DzsI7jVb.mjs +0 -3629
- package/dist/webln-DzsI7jVb.mjs.map +0 -1
|
@@ -0,0 +1,1507 @@
|
|
|
1
|
+
import { t as Controller } from "./controller-rMnaxKAH.mjs";
|
|
2
|
+
import { A as evmChainId, F as toProviderError, M as internalError, N as invalidParams, j as ProviderError, o as walletStandardChain, u as bitcoinStandardChain } from "./webln-BgrtPXpG.mjs";
|
|
3
|
+
import { c as parseWith } from "./eligibility-BfM9ybYZ.mjs";
|
|
4
|
+
import { d as walletConnectKey } from "./types-DbftVZ3I.mjs";
|
|
5
|
+
import { _ as verifyRisk, g as originRisk, h as mergeRisk } from "./risk-DyABgg4W.mjs";
|
|
6
|
+
import { tokenName } from "./gateway-contract.mjs";
|
|
7
|
+
import "./connect-BY1C5ZRI.mjs";
|
|
8
|
+
import { getAddress } from "viem";
|
|
9
|
+
import { bytesToHex as bytesToHex$1, utf8ToBytes } from "@noble/hashes/utils.js";
|
|
10
|
+
import { address, getTransactionDecoder } from "@solana/kit";
|
|
11
|
+
import { base58, base64 } from "@scure/base";
|
|
12
|
+
import { WalletKit } from "@reown/walletkit";
|
|
13
|
+
import { Core } from "@walletconnect/core";
|
|
14
|
+
import { buildAuthObject, getChainsFromRecap, getMethodsFromRecap, getRecapFromResources, getSdkError, normalizeNamespaces, parseUri, populateAuthPayload } from "@walletconnect/utils";
|
|
15
|
+
/**
|
|
16
|
+
* The eip155 namespace: every WalletConnect method is the EIP-1193 method of the same name, so
|
|
17
|
+
* dispatch is a straight pass-through into the injected-provider handler with the request's CAIP-2
|
|
18
|
+
* chain as its network.
|
|
19
|
+
*/
|
|
20
|
+
const eip155Row = {
|
|
21
|
+
namespace: "eip155",
|
|
22
|
+
methods: Object.fromEntries([
|
|
23
|
+
"personal_sign",
|
|
24
|
+
"eth_signTypedData_v4",
|
|
25
|
+
"eth_sendTransaction",
|
|
26
|
+
"wallet_sendCalls",
|
|
27
|
+
"wallet_getCallsStatus",
|
|
28
|
+
"wallet_showCallsStatus",
|
|
29
|
+
"wallet_getCapabilities",
|
|
30
|
+
"wallet_watchAsset",
|
|
31
|
+
"wallet_switchEthereumChain",
|
|
32
|
+
"wallet_addEthereumChain"
|
|
33
|
+
].map((method) => [method, [method]])),
|
|
34
|
+
events: ["accountsChanged", "chainChanged"],
|
|
35
|
+
serves: (network) => evmChainId(network) !== void 0,
|
|
36
|
+
accounts: (scope) => scope.accounts,
|
|
37
|
+
dispatch: async (call, engine) => engine.eip1193.handle(call.origin, {
|
|
38
|
+
method: call.method,
|
|
39
|
+
params: call.params,
|
|
40
|
+
network: call.network
|
|
41
|
+
})
|
|
42
|
+
};
|
|
43
|
+
// src/walletconnect/namespaces.ts
|
|
44
|
+
const unique = (items) => [...new Set(items)];
|
|
45
|
+
/**
|
|
46
|
+
* The namespaces the wallet can offer a proposal: every required namespace, chain, method and event
|
|
47
|
+
* must be servable and enabled; optional entries that are not are dropped. `ok: false` carries the
|
|
48
|
+
* `getSdkError` reason the peer is rejected with.
|
|
49
|
+
*/
|
|
50
|
+
const offerNamespaces = (required, optional, rows, isEnabled) => {
|
|
51
|
+
const namespaces = {};
|
|
52
|
+
for (const [key, request] of Object.entries(required)) {
|
|
53
|
+
const row = rows[key];
|
|
54
|
+
if (row === void 0) return {
|
|
55
|
+
ok: false,
|
|
56
|
+
error: getSdkError("UNSUPPORTED_NAMESPACE_KEY", key)
|
|
57
|
+
};
|
|
58
|
+
const chains = [...request.chains ?? []];
|
|
59
|
+
if (chains.length === 0 || !chains.every((chain) => row.serves(chain) && isEnabled(chain))) return {
|
|
60
|
+
ok: false,
|
|
61
|
+
error: getSdkError("UNSUPPORTED_CHAINS")
|
|
62
|
+
};
|
|
63
|
+
if (!request.methods.every((method) => row.methods[method] !== void 0)) return {
|
|
64
|
+
ok: false,
|
|
65
|
+
error: getSdkError("UNSUPPORTED_METHODS")
|
|
66
|
+
};
|
|
67
|
+
if (!request.events.every((event) => row.events.includes(event))) return {
|
|
68
|
+
ok: false,
|
|
69
|
+
error: getSdkError("UNSUPPORTED_EVENTS")
|
|
70
|
+
};
|
|
71
|
+
namespaces[key] = {
|
|
72
|
+
chains,
|
|
73
|
+
required: chains,
|
|
74
|
+
methods: unique([...request.methods, ...optional[key]?.methods ?? []]).filter((method) => row.methods[method] !== void 0),
|
|
75
|
+
events: unique([...request.events, ...optional[key]?.events ?? []]).filter((event) => row.events.includes(event))
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
for (const [key, request] of Object.entries(optional)) {
|
|
79
|
+
const row = rows[key];
|
|
80
|
+
if (row === void 0) continue;
|
|
81
|
+
const offered = namespaces[key] ?? (namespaces[key] = {
|
|
82
|
+
chains: [],
|
|
83
|
+
required: [],
|
|
84
|
+
methods: unique(request.methods).filter((method) => row.methods[method] !== void 0),
|
|
85
|
+
events: unique(request.events).filter((event) => row.events.includes(event))
|
|
86
|
+
});
|
|
87
|
+
const chains = [...offered.chains];
|
|
88
|
+
for (const chain of request.chains ?? []) if (!chains.includes(chain) && row.serves(chain) && isEnabled(chain)) chains.push(chain);
|
|
89
|
+
namespaces[key] = {
|
|
90
|
+
...offered,
|
|
91
|
+
chains
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
const granted = Object.values(namespaces);
|
|
95
|
+
const networks = granted.flatMap((offered) => [...offered.chains]);
|
|
96
|
+
if (networks.length === 0) return {
|
|
97
|
+
ok: false,
|
|
98
|
+
error: getSdkError("UNSUPPORTED_CHAINS")
|
|
99
|
+
};
|
|
100
|
+
return {
|
|
101
|
+
ok: true,
|
|
102
|
+
namespaces,
|
|
103
|
+
networks,
|
|
104
|
+
required: granted.flatMap((o) => o.required)
|
|
105
|
+
};
|
|
106
|
+
};
|
|
107
|
+
/**
|
|
108
|
+
* The session namespaces to advertise after the session's scopes changed: chains and accounts are
|
|
109
|
+
* recomputed from the scopes (namespaces the WalletKit session lacks are never added), methods and
|
|
110
|
+
* events keep what the session negotiated. `undefined` when a chain can no longer produce an
|
|
111
|
+
* account — the session is unrecoverable and must be dropped.
|
|
112
|
+
*/
|
|
113
|
+
const sessionNamespaces = (scopes, namespaces, rows) => {
|
|
114
|
+
const out = {};
|
|
115
|
+
for (const [key, live] of Object.entries(namespaces)) {
|
|
116
|
+
const row = rows[key];
|
|
117
|
+
if (row === void 0) {
|
|
118
|
+
out[key] = {
|
|
119
|
+
...live,
|
|
120
|
+
accounts: [...live.accounts],
|
|
121
|
+
methods: [...live.methods],
|
|
122
|
+
events: [...live.events]
|
|
123
|
+
};
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
const chains = Object.keys(scopes).filter((network) => network.startsWith(`${key}:`));
|
|
127
|
+
const accounts = [];
|
|
128
|
+
for (const chain of chains) {
|
|
129
|
+
const scope = scopes[chain];
|
|
130
|
+
const bound = scope === void 0 ? [] : row.accounts(scope);
|
|
131
|
+
if (bound.length === 0) return;
|
|
132
|
+
accounts.push(...bound);
|
|
133
|
+
}
|
|
134
|
+
out[key] = {
|
|
135
|
+
chains,
|
|
136
|
+
accounts,
|
|
137
|
+
methods: [...live.methods],
|
|
138
|
+
events: [...live.events]
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
return out;
|
|
142
|
+
};
|
|
143
|
+
const sameSet = (a, b) => a.length === b.length && a.every((item) => b.includes(item));
|
|
144
|
+
/** Order-insensitive comparison of the parts reconcile can change: chains and accounts. */
|
|
145
|
+
const sameNamespaces = (a, b) => {
|
|
146
|
+
for (const key of /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])) {
|
|
147
|
+
const x = a[key];
|
|
148
|
+
const y = b[key];
|
|
149
|
+
if (x === void 0 || y === void 0) return false;
|
|
150
|
+
if (!sameSet(x.chains ?? [], y.chains ?? []) || !sameSet(x.accounts, y.accounts)) return false;
|
|
151
|
+
}
|
|
152
|
+
return true;
|
|
153
|
+
};
|
|
154
|
+
// src/walletconnect/proposals.ts
|
|
155
|
+
/** `metadata.url` reduced to its origin, or `undefined` when it is not an http(s) URL. */
|
|
156
|
+
const metadataOrigin = (url) => {
|
|
157
|
+
if (typeof url !== "string") return;
|
|
158
|
+
try {
|
|
159
|
+
const parsed = new URL(url);
|
|
160
|
+
return parsed.protocol === "https:" || parsed.protocol === "http:" ? parsed.origin : void 0;
|
|
161
|
+
} catch {
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
/** The peer's self-declared metadata, sanitized for display — never a verified identity. */
|
|
166
|
+
const sanitizePeer = (metadata, url) => ({
|
|
167
|
+
name: parseWith(tokenName, metadata.name) ?? new URL(url).host,
|
|
168
|
+
url,
|
|
169
|
+
description: typeof metadata.description === "string" && metadata.description.length <= 256 ? metadata.description : "",
|
|
170
|
+
icons: Array.isArray(metadata.icons) ? metadata.icons.filter((icon) => typeof icon === "string" && icon.startsWith("https://")).slice(0, 4) : []
|
|
171
|
+
});
|
|
172
|
+
/** A proposal or request's Verify context reduced to our verdict — display-only too. */
|
|
173
|
+
const verifyOf = (verified) => ({
|
|
174
|
+
validation: verified.validation === "VALID" || verified.validation === "INVALID" || verified.validation === "UNKNOWN" ? verified.validation : "UNKNOWN",
|
|
175
|
+
isScam: verified.isScam === true
|
|
176
|
+
});
|
|
177
|
+
/**
|
|
178
|
+
* Validates a proposal end to end — peer URL, phishing list, namespace offer — without any SDK
|
|
179
|
+
* call, so a live `session_proposal` and a recovered pending proposal take the same path.
|
|
180
|
+
*/
|
|
181
|
+
const judgeProposal = (proposal, verify, deps) => {
|
|
182
|
+
const url = metadataOrigin(proposal.proposer.metadata.url);
|
|
183
|
+
if (url === void 0) return {
|
|
184
|
+
ok: false,
|
|
185
|
+
error: {
|
|
186
|
+
...deps.userRejected(),
|
|
187
|
+
message: "the peer metadata url is not an http(s) origin"
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
const status = deps.phishing(url);
|
|
191
|
+
if (status === "blocked") return {
|
|
192
|
+
ok: false,
|
|
193
|
+
error: deps.userRejected()
|
|
194
|
+
};
|
|
195
|
+
const offer = offerNamespaces(normalizeNamespaces(proposal.requiredNamespaces), normalizeNamespaces(proposal.optionalNamespaces), deps.rows, deps.isEnabled);
|
|
196
|
+
if (!offer.ok) return {
|
|
197
|
+
ok: false,
|
|
198
|
+
error: offer.error
|
|
199
|
+
};
|
|
200
|
+
return {
|
|
201
|
+
ok: true,
|
|
202
|
+
proposal: {
|
|
203
|
+
peer: sanitizePeer(proposal.proposer.metadata, url),
|
|
204
|
+
verify,
|
|
205
|
+
risk: mergeRisk(originRisk(status), verifyRisk(verify)),
|
|
206
|
+
offer,
|
|
207
|
+
expiresAt: proposal.expiryTimestamp * 1e3
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
};
|
|
211
|
+
// src/walletconnect/authenticate.ts
|
|
212
|
+
/**
|
|
213
|
+
* One `session_authenticate` end to end: validate the CAIP-222 request against the peer it claims
|
|
214
|
+
* to be, sign the populated SIWE message through the ordinary `evm-sign` pipeline, build the Cacao
|
|
215
|
+
* and settle — a session when the recap carries methods, an auth-only answer otherwise. Every
|
|
216
|
+
* failure answers `rejectSessionAuthenticate`; nothing is held or requeued.
|
|
217
|
+
*/
|
|
218
|
+
const handleAuthenticate = async (event, deps) => {
|
|
219
|
+
const { kit, engine } = deps;
|
|
220
|
+
const reject = async (message) => {
|
|
221
|
+
try {
|
|
222
|
+
await kit.rejectSessionAuthenticate({
|
|
223
|
+
id: event.id,
|
|
224
|
+
reason: getSdkError("USER_REJECTED", message)
|
|
225
|
+
});
|
|
226
|
+
} catch (error) {
|
|
227
|
+
deps.warn("walletconnect auth rejection failed", error);
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
const { authPayload, requester, expiryTimestamp } = event.params;
|
|
231
|
+
if (expiryTimestamp * 1e3 <= deps.now()) return reject("the authenticate request expired");
|
|
232
|
+
const url = metadataOrigin(requester.metadata.url);
|
|
233
|
+
if (url === void 0) return reject("the peer metadata url is not an http(s) origin");
|
|
234
|
+
if (engine.phishing.check(url) === "blocked") return reject("the peer is on the phishing list");
|
|
235
|
+
if (authPayload.domain !== new URL(url).host) return reject("the auth domain is not the peer's host");
|
|
236
|
+
const aud = authPayload.aud ?? ("uri" in authPayload ? authPayload.uri : void 0);
|
|
237
|
+
let audOrigin;
|
|
238
|
+
try {
|
|
239
|
+
audOrigin = typeof aud === "string" ? new URL(aud).origin : void 0;
|
|
240
|
+
} catch {
|
|
241
|
+
audOrigin = void 0;
|
|
242
|
+
}
|
|
243
|
+
if (audOrigin !== url) return reject("the auth URI is not the peer's origin");
|
|
244
|
+
const network = authPayload.chains.find((chain) => eip155Row.serves(chain) && engine.connections.isEnabled(chain));
|
|
245
|
+
if (network === void 0) return reject("no requested chain is served and enabled");
|
|
246
|
+
let populated;
|
|
247
|
+
try {
|
|
248
|
+
populated = populateAuthPayload({
|
|
249
|
+
authPayload,
|
|
250
|
+
chains: [network],
|
|
251
|
+
methods: Object.keys(eip155Row.methods)
|
|
252
|
+
});
|
|
253
|
+
} catch {
|
|
254
|
+
return reject("the requested methods are not supported");
|
|
255
|
+
}
|
|
256
|
+
let recap;
|
|
257
|
+
try {
|
|
258
|
+
recap = getRecapFromResources(populated.resources);
|
|
259
|
+
if (recap !== void 0 && !getChainsFromRecap(recap).every((chain) => chain === network)) {
|
|
260
|
+
await reject("the recap authorizes other chains");
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
} catch {
|
|
264
|
+
return reject("the recap resource is malformed");
|
|
265
|
+
}
|
|
266
|
+
const preview = await engine.connections.previewAccounts(network);
|
|
267
|
+
const address = preview?.addresses[0];
|
|
268
|
+
if (preview === void 0 || address === void 0) return reject("no account is available for the network");
|
|
269
|
+
const iss = `${network}:${getAddress(address)}`;
|
|
270
|
+
const account = {
|
|
271
|
+
kind: "hd",
|
|
272
|
+
walletId: preview.group.walletId,
|
|
273
|
+
groupIndex: preview.group.groupIndex,
|
|
274
|
+
template: "evm.bip44"
|
|
275
|
+
};
|
|
276
|
+
const origin = {
|
|
277
|
+
kind: "walletconnect",
|
|
278
|
+
origin: walletConnectKey(event.topic),
|
|
279
|
+
topic: event.topic,
|
|
280
|
+
url,
|
|
281
|
+
name: sanitizePeer(requester.metadata, url).name,
|
|
282
|
+
verify: verifyOf(event.verifyContext.verified)
|
|
283
|
+
};
|
|
284
|
+
let signature;
|
|
285
|
+
try {
|
|
286
|
+
const pending = await engine.requests.prepare({
|
|
287
|
+
method: "evm-sign",
|
|
288
|
+
origin,
|
|
289
|
+
account,
|
|
290
|
+
network,
|
|
291
|
+
request: {
|
|
292
|
+
kind: "evm.personal-message",
|
|
293
|
+
network,
|
|
294
|
+
account,
|
|
295
|
+
message: utf8ToBytes(kit.formatAuthMessage({
|
|
296
|
+
request: populated,
|
|
297
|
+
iss
|
|
298
|
+
}))
|
|
299
|
+
}
|
|
300
|
+
});
|
|
301
|
+
const outcome = await engine.requests.outcome(pending.id);
|
|
302
|
+
if (!("signature" in outcome) || !(outcome.signature instanceof Uint8Array)) throw internalError("the sign request has no signature");
|
|
303
|
+
signature = `0x${bytesToHex$1(outcome.signature)}`;
|
|
304
|
+
} catch {
|
|
305
|
+
return reject("the signature request did not complete");
|
|
306
|
+
}
|
|
307
|
+
const auth = buildAuthObject(populated, {
|
|
308
|
+
t: "eip191",
|
|
309
|
+
s: signature
|
|
310
|
+
}, iss);
|
|
311
|
+
const recapMethods = recap === void 0 ? [] : getMethodsFromRecap(recap).flatMap((method) => eip155Row.methods[typeof method === "string" ? method : ""] ?? []);
|
|
312
|
+
if (recapMethods.length === 0) {
|
|
313
|
+
await kit.approveSessionAuthenticate({
|
|
314
|
+
id: event.id,
|
|
315
|
+
auths: [auth]
|
|
316
|
+
});
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
try {
|
|
320
|
+
await deps.establish(async () => {
|
|
321
|
+
await engine.connections.establishWalletConnect({ [network]: {
|
|
322
|
+
methods: [...new Set(recapMethods)],
|
|
323
|
+
notifications: ["accountsChanged", "chainChanged"]
|
|
324
|
+
} }, async (bound) => {
|
|
325
|
+
const [caip10] = bound[network]?.accounts ?? [];
|
|
326
|
+
if ((caip10?.slice(caip10.lastIndexOf(":") + 1))?.toLowerCase() !== address.toLowerCase()) throw internalError("the bound account changed between signing and settling");
|
|
327
|
+
const { session } = await kit.approveSessionAuthenticate({
|
|
328
|
+
id: event.id,
|
|
329
|
+
auths: [auth]
|
|
330
|
+
});
|
|
331
|
+
if (session === void 0) throw internalError("the authenticated session did not settle");
|
|
332
|
+
return {
|
|
333
|
+
kind: "walletconnect",
|
|
334
|
+
origin: walletConnectKey(session.topic),
|
|
335
|
+
topic: session.topic,
|
|
336
|
+
url,
|
|
337
|
+
name: origin.name,
|
|
338
|
+
verify: origin.verify
|
|
339
|
+
};
|
|
340
|
+
});
|
|
341
|
+
});
|
|
342
|
+
} catch {
|
|
343
|
+
return reject("the session did not settle");
|
|
344
|
+
}
|
|
345
|
+
};
|
|
346
|
+
// src/walletconnect/results.ts
|
|
347
|
+
/**
|
|
348
|
+
* Field extraction for the shared handlers' results — `handle` returns `unknown`, and an unexpected
|
|
349
|
+
* shape is the engine's contract broken, not bad dApp input: -32603, not -32602.
|
|
350
|
+
*/
|
|
351
|
+
const isRecord = (value) => typeof value === "object" && value !== null;
|
|
352
|
+
/** One bytes field of a handler result — a signature, a signed transaction. */
|
|
353
|
+
const bytesField = (result, key) => {
|
|
354
|
+
const value = isRecord(result) ? result[key] : void 0;
|
|
355
|
+
if (!(value instanceof Uint8Array)) throw internalError(`the handler returned no ${key}`);
|
|
356
|
+
return value;
|
|
357
|
+
};
|
|
358
|
+
/** A bytes-array field of a handler result — `signedTransactions`, `signatures`. */
|
|
359
|
+
const bytesListField = (result, key) => {
|
|
360
|
+
const value = isRecord(result) ? result[key] : void 0;
|
|
361
|
+
if (!Array.isArray(value) || !value.every((item) => item instanceof Uint8Array)) throw internalError(`the handler returned no ${key}`);
|
|
362
|
+
return value;
|
|
363
|
+
};
|
|
364
|
+
/** A handler result that is itself a list of records — `bitcoin:signTransaction`. */
|
|
365
|
+
const recordsList = (result) => {
|
|
366
|
+
if (!Array.isArray(result) || !result.every(isRecord)) throw internalError("the handler returned no result list");
|
|
367
|
+
return result;
|
|
368
|
+
};
|
|
369
|
+
/** A list-of-records field of a handler result — `bitcoin:connect`'s `accounts`. */
|
|
370
|
+
const recordsListField = (result, key) => {
|
|
371
|
+
const value = isRecord(result) ? result[key] : void 0;
|
|
372
|
+
if (!Array.isArray(value) || !value.every(isRecord)) throw internalError(`the handler returned no ${key}`);
|
|
373
|
+
return value;
|
|
374
|
+
};
|
|
375
|
+
// src/walletconnect/bip122.ts
|
|
376
|
+
const isParams$1 = (params) => typeof params === "object" && params !== null;
|
|
377
|
+
const base64Of$1 = (value, name) => {
|
|
378
|
+
if (typeof value !== "string") throw invalidParams(`${name} must be a base64 string`);
|
|
379
|
+
try {
|
|
380
|
+
return base64.decode(value);
|
|
381
|
+
} catch {
|
|
382
|
+
throw invalidParams(`${name} is not valid base64`);
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
/**
|
|
386
|
+
* The session's Bitcoin binding — every bip122 method needs it up front: falling through to a
|
|
387
|
+
* handler would open a connect prompt the WalletConnect flow must never raise.
|
|
388
|
+
*/
|
|
389
|
+
const requireBinding = (call, engine) => {
|
|
390
|
+
const binding = engine.connections.sessionAccounts(call.origin.origin, call.network);
|
|
391
|
+
if (binding === void 0) throw new ProviderError(4100, "no bitcoin account for this origin");
|
|
392
|
+
return binding;
|
|
393
|
+
};
|
|
394
|
+
/**
|
|
395
|
+
* `params.account` names the session's WalletConnect account — the payment (BIP-84) address, the
|
|
396
|
+
* only address the namespace advertises.
|
|
397
|
+
*/
|
|
398
|
+
const requireAccount = (params, binding) => {
|
|
399
|
+
const [payment] = binding.addresses;
|
|
400
|
+
if (params["account"] !== payment || payment === void 0) throw new ProviderError(4100, "account is not the connected account");
|
|
401
|
+
return payment;
|
|
402
|
+
};
|
|
403
|
+
/** `bitcoin:connect` for the given purposes — the session is bound, so no prompt can open. */
|
|
404
|
+
const addressesFor = async (engine, origin, network, purposes) => {
|
|
405
|
+
const result = await engine.bitcoinWallet.handle(origin, {
|
|
406
|
+
method: "bitcoin:connect",
|
|
407
|
+
params: { purposes: [...purposes] },
|
|
408
|
+
network
|
|
409
|
+
});
|
|
410
|
+
return recordsListField(result, "accounts").map((account, index) => {
|
|
411
|
+
if (typeof account["address"] !== "string" || !(account["publicKey"] instanceof Uint8Array)) throw internalError("the connect result has no account address and key");
|
|
412
|
+
return {
|
|
413
|
+
address: account["address"],
|
|
414
|
+
publicKey: bytesToHex$1(account["publicKey"]),
|
|
415
|
+
intention: purposes[index] === "ordinals" ? "ordinal" : "payment"
|
|
416
|
+
};
|
|
417
|
+
});
|
|
418
|
+
};
|
|
419
|
+
/** The `bip122_addressesChanged` payload — the getAccountAddresses result for both purposes. */
|
|
420
|
+
const bip122Addresses = async (engine, origin, network) => addressesFor(engine, origin, network, ["payment", "ordinals"]);
|
|
421
|
+
const INTENTION_PURPOSES = {
|
|
422
|
+
payment: "payment",
|
|
423
|
+
ordinal: "ordinals"
|
|
424
|
+
};
|
|
425
|
+
const getAccountAddresses = async (call, engine, params) => {
|
|
426
|
+
const binding = requireBinding(call, engine);
|
|
427
|
+
requireAccount(params, binding);
|
|
428
|
+
const raw = params["intentions"];
|
|
429
|
+
if (raw !== void 0 && !Array.isArray(raw)) throw invalidParams("intentions must be an array of payment/ordinal");
|
|
430
|
+
const purposes = raw === void 0 || raw.length === 0 ? ["payment", "ordinals"] : raw.map((intention) => {
|
|
431
|
+
const purpose = INTENTION_PURPOSES[String(intention)];
|
|
432
|
+
if (purpose === void 0) throw invalidParams(`unknown intention ${String(intention)}`);
|
|
433
|
+
return purpose;
|
|
434
|
+
});
|
|
435
|
+
return addressesFor(engine, call.origin, call.network, purposes);
|
|
436
|
+
};
|
|
437
|
+
const signMessage$1 = async (call, engine, params) => {
|
|
438
|
+
const binding = requireBinding(call, engine);
|
|
439
|
+
requireAccount(params, binding);
|
|
440
|
+
if (params["protocol"] !== "bip322") throw new ProviderError(4200, "only BIP-322 message signatures are supported");
|
|
441
|
+
const { address: named, message } = params;
|
|
442
|
+
if (named !== void 0 && typeof named !== "string") throw invalidParams("address must be a string");
|
|
443
|
+
if (typeof message !== "string") throw invalidParams("signMessage needs a message string");
|
|
444
|
+
const address = named ?? requireAccount(params, binding);
|
|
445
|
+
const result = await engine.bitcoinWallet.handle(call.origin, {
|
|
446
|
+
method: "bitcoin:signMessage",
|
|
447
|
+
params: {
|
|
448
|
+
account: address,
|
|
449
|
+
message: utf8ToBytes(message)
|
|
450
|
+
},
|
|
451
|
+
network: call.network
|
|
452
|
+
});
|
|
453
|
+
return {
|
|
454
|
+
address,
|
|
455
|
+
signature: bytesToHex$1(bytesField(result, "signature"))
|
|
456
|
+
};
|
|
457
|
+
};
|
|
458
|
+
const sigHashOf = (value) => {
|
|
459
|
+
if (value === void 0) return "ALL";
|
|
460
|
+
if (!Array.isArray(value)) throw invalidParams("sighashTypes must be an array of sighash bytes");
|
|
461
|
+
if (value.length === 1 && value[0] === 1) return "ALL";
|
|
462
|
+
if (value.length === 1 && value[0] === 131) return "SINGLE|ANYONECANPAY";
|
|
463
|
+
throw invalidParams("sighashTypes must be exactly [1] or [131]");
|
|
464
|
+
};
|
|
465
|
+
const signPsbt = async (call, engine, params) => {
|
|
466
|
+
const binding = requireBinding(call, engine);
|
|
467
|
+
requireAccount(params, binding);
|
|
468
|
+
const { broadcast } = params;
|
|
469
|
+
if (broadcast !== void 0 && typeof broadcast !== "boolean") throw invalidParams("broadcast must be a boolean");
|
|
470
|
+
const raw = params["signInputs"];
|
|
471
|
+
if (!Array.isArray(raw) || raw.length === 0) throw invalidParams("signPsbt needs a non-empty signInputs array");
|
|
472
|
+
const groups = /* @__PURE__ */ new Map();
|
|
473
|
+
for (const entry of raw) {
|
|
474
|
+
const { address, index, sighashTypes } = isParams$1(entry) ? entry : {};
|
|
475
|
+
if (typeof address !== "string" || typeof index !== "number" || !Number.isSafeInteger(index) || index < 0) throw invalidParams("each signInput needs an address and a non-negative index");
|
|
476
|
+
const sigHash = sigHashOf(sighashTypes);
|
|
477
|
+
const key = `${address} ${sigHash}`;
|
|
478
|
+
const group = groups.get(key) ?? {
|
|
479
|
+
address,
|
|
480
|
+
signingIndexes: [],
|
|
481
|
+
sigHash
|
|
482
|
+
};
|
|
483
|
+
group.signingIndexes.push(index);
|
|
484
|
+
groups.set(key, group);
|
|
485
|
+
}
|
|
486
|
+
const chain = bitcoinStandardChain(call.network);
|
|
487
|
+
if (chain === void 0) throw internalError(`network ${call.network} has no Bitcoin Wallet Standard chain id`);
|
|
488
|
+
const result = await engine.bitcoinWallet.handle(call.origin, {
|
|
489
|
+
method: broadcast === true ? "bitcoin:signAndSendTransaction" : "bitcoin:signTransaction",
|
|
490
|
+
params: { inputs: [{
|
|
491
|
+
psbt: base64Of$1(params["psbt"], "psbt"),
|
|
492
|
+
chain,
|
|
493
|
+
inputsToSign: [...groups.values()]
|
|
494
|
+
}] },
|
|
495
|
+
network: call.network
|
|
496
|
+
});
|
|
497
|
+
const [first] = recordsList(result);
|
|
498
|
+
if (first === void 0) throw internalError("the sign request returned no PSBT");
|
|
499
|
+
const txid = first["txId"];
|
|
500
|
+
if (txid !== void 0 && typeof txid !== "string") throw internalError("the sign request returned a non-string txid");
|
|
501
|
+
return txid === void 0 ? { psbt: base64.encode(bytesField(first, "signedPsbt")) } : {
|
|
502
|
+
psbt: base64.encode(bytesField(first, "signedPsbt")),
|
|
503
|
+
txid
|
|
504
|
+
};
|
|
505
|
+
};
|
|
506
|
+
const MAX_SATS = 0x775f05a074000;
|
|
507
|
+
const sendTransfer = async (call, engine, params) => {
|
|
508
|
+
const binding = requireBinding(call, engine);
|
|
509
|
+
requireAccount(params, binding);
|
|
510
|
+
const { memo, recipientAddress, amount, changeAddress } = params;
|
|
511
|
+
if (typeof memo === "string" && memo !== "") throw new ProviderError(4200, "OP_RETURN memos are not supported");
|
|
512
|
+
if (typeof amount !== "string" || !/^[1-9][0-9]*$/.test(amount) || BigInt(amount) > MAX_SATS) throw invalidParams("amount must be a positive satoshi count");
|
|
513
|
+
if (typeof recipientAddress !== "string") throw invalidParams("recipientAddress must be a string");
|
|
514
|
+
if (changeAddress !== void 0 && !(typeof changeAddress === "string" && binding.addresses.includes(changeAddress))) throw invalidParams("changeAddress is not one of the session's addresses");
|
|
515
|
+
engine.connections.authorize(call.origin.origin, call.network, "sendTransfer");
|
|
516
|
+
let tx;
|
|
517
|
+
try {
|
|
518
|
+
const pending = await engine.requests.prepare({
|
|
519
|
+
method: "send",
|
|
520
|
+
origin: call.origin,
|
|
521
|
+
account: {
|
|
522
|
+
kind: "hd",
|
|
523
|
+
walletId: binding.group.walletId,
|
|
524
|
+
groupIndex: binding.group.groupIndex,
|
|
525
|
+
template: "btc.bip84"
|
|
526
|
+
},
|
|
527
|
+
network: call.network,
|
|
528
|
+
to: recipientAddress,
|
|
529
|
+
amount: BigInt(amount),
|
|
530
|
+
fee: "normal"
|
|
531
|
+
});
|
|
532
|
+
const outcome = await engine.requests.outcome(pending.id);
|
|
533
|
+
if (!("hash" in outcome)) throw internalError("the send request settled unexpectedly");
|
|
534
|
+
tx = outcome;
|
|
535
|
+
} catch (error) {
|
|
536
|
+
throw toProviderError(error);
|
|
537
|
+
}
|
|
538
|
+
if (tx.hash === void 0) throw internalError("the broadcast has no transaction id");
|
|
539
|
+
await engine.connections.touch(call.origin.origin);
|
|
540
|
+
return { txid: tx.hash };
|
|
541
|
+
};
|
|
542
|
+
const dispatch$1 = async (call, engine) => {
|
|
543
|
+
const params = isParams$1(call.params) ? call.params : {};
|
|
544
|
+
switch (call.method) {
|
|
545
|
+
case "getAccountAddresses": return getAccountAddresses(call, engine, params);
|
|
546
|
+
case "signMessage": return signMessage$1(call, engine, params);
|
|
547
|
+
case "signPsbt": return signPsbt(call, engine, params);
|
|
548
|
+
case "sendTransfer": return sendTransfer(call, engine, params);
|
|
549
|
+
default: throw new ProviderError(-32601, `unsupported bip122 method ${call.method}`);
|
|
550
|
+
}
|
|
551
|
+
};
|
|
552
|
+
/**
|
|
553
|
+
* The bip122 namespace: requests translate into `bitcoin:*` Wallet Standard calls (or the shared
|
|
554
|
+
* `send` pipeline for sendTransfer) with the request's CAIP-2 chain as its network. The session
|
|
555
|
+
* advertises only the payment address — WalletConnect's Bitcoin spec has dApps display the first
|
|
556
|
+
* external address; ordinals stays reachable through getAccountAddresses.
|
|
557
|
+
*/
|
|
558
|
+
const bip122Row = {
|
|
559
|
+
namespace: "bip122",
|
|
560
|
+
methods: {
|
|
561
|
+
getAccountAddresses: ["bitcoin:connect"],
|
|
562
|
+
signMessage: ["bitcoin:signMessage"],
|
|
563
|
+
signPsbt: ["bitcoin:signTransaction", "bitcoin:signAndSendTransaction"],
|
|
564
|
+
sendTransfer: ["sendTransfer"]
|
|
565
|
+
},
|
|
566
|
+
events: [
|
|
567
|
+
"accountsChanged",
|
|
568
|
+
"chainChanged",
|
|
569
|
+
"bip122_addressesChanged"
|
|
570
|
+
],
|
|
571
|
+
serves: (network) => bitcoinStandardChain(network) !== void 0,
|
|
572
|
+
accounts: (scope) => scope.accounts.slice(0, 1),
|
|
573
|
+
dispatch: dispatch$1
|
|
574
|
+
};
|
|
575
|
+
// src/walletconnect/errors.ts
|
|
576
|
+
/** A `createWalletConnect` misuse or a refused pairing/proposal/grant; `code` says which. */
|
|
577
|
+
var WalletConnectError = class extends Error {
|
|
578
|
+
code;
|
|
579
|
+
constructor(code, message) {
|
|
580
|
+
super(message);
|
|
581
|
+
this.name = "WalletConnectError";
|
|
582
|
+
this.code = code;
|
|
583
|
+
}
|
|
584
|
+
};
|
|
585
|
+
/**
|
|
586
|
+
* The JSON-RPC error a `session_request` answer carries: a user rejection is the protocol's `5000
|
|
587
|
+
* "User rejected."`, other provider errors keep their code, anything else is opaque.
|
|
588
|
+
*/
|
|
589
|
+
const requestError = (error) => {
|
|
590
|
+
if (error instanceof ProviderError) return error.code === 4001 ? {
|
|
591
|
+
code: 5e3,
|
|
592
|
+
message: "User rejected."
|
|
593
|
+
} : {
|
|
594
|
+
code: error.code,
|
|
595
|
+
message: error.message
|
|
596
|
+
};
|
|
597
|
+
return {
|
|
598
|
+
code: -32603,
|
|
599
|
+
message: "internal error"
|
|
600
|
+
};
|
|
601
|
+
};
|
|
602
|
+
// src/walletconnect/queue.ts
|
|
603
|
+
/** How many recently seen request ids dedup keeps. */
|
|
604
|
+
const MAX_SEEN = 500;
|
|
605
|
+
/**
|
|
606
|
+
* Per-topic FIFO queues: requests of one session serialize (an approval must not race the next
|
|
607
|
+
* call) while different sessions run concurrently. Requests queue while the vault is locked and
|
|
608
|
+
* drain when it unlocks; ids already queued, in flight or recently done are dropped so the relay's
|
|
609
|
+
* at-least-once delivery and a restarted recovery never reach the pipeline twice.
|
|
610
|
+
*/
|
|
611
|
+
var SessionRequestQueue = class {
|
|
612
|
+
pending = /* @__PURE__ */ new Map();
|
|
613
|
+
running = /* @__PURE__ */ new Map();
|
|
614
|
+
expired = /* @__PURE__ */ new Set();
|
|
615
|
+
seen = /* @__PURE__ */ new Set();
|
|
616
|
+
seenOrder = [];
|
|
617
|
+
ready = false;
|
|
618
|
+
handler;
|
|
619
|
+
constructor(handler) {
|
|
620
|
+
this.handler = handler;
|
|
621
|
+
}
|
|
622
|
+
/** The vault opened or locked: queued items drain only while ready. */
|
|
623
|
+
setReady(ready) {
|
|
624
|
+
this.ready = ready;
|
|
625
|
+
if (ready) for (const topic of this.pending.keys()) this.drain(topic);
|
|
626
|
+
}
|
|
627
|
+
has(id) {
|
|
628
|
+
return this.seen.has(id);
|
|
629
|
+
}
|
|
630
|
+
enqueue(item) {
|
|
631
|
+
if (this.seen.has(item.id)) return;
|
|
632
|
+
this.seen.add(item.id);
|
|
633
|
+
this.seenOrder.push(item.id);
|
|
634
|
+
if (this.seenOrder.length > MAX_SEEN) {
|
|
635
|
+
const oldest = this.seenOrder.shift();
|
|
636
|
+
if (oldest !== void 0) this.seen.delete(oldest);
|
|
637
|
+
}
|
|
638
|
+
const queue = this.pending.get(item.topic) ?? [];
|
|
639
|
+
queue.push(item);
|
|
640
|
+
this.pending.set(item.topic, queue);
|
|
641
|
+
if (this.ready) this.drain(item.topic);
|
|
642
|
+
}
|
|
643
|
+
/** Back at the head of its queue — a dispatch that failed while the vault was locked. */
|
|
644
|
+
requeue(item) {
|
|
645
|
+
const queue = this.pending.get(item.topic) ?? [];
|
|
646
|
+
queue.unshift(item);
|
|
647
|
+
this.pending.set(item.topic, queue);
|
|
648
|
+
if (this.ready) this.drain(item.topic);
|
|
649
|
+
}
|
|
650
|
+
/** The session went away: its queued requests are never answered. */
|
|
651
|
+
drop(topic) {
|
|
652
|
+
this.pending.delete(topic);
|
|
653
|
+
}
|
|
654
|
+
/**
|
|
655
|
+
* `session_request_expire`: a queued item is dropped; an in-flight one is marked so no response
|
|
656
|
+
* is sent and its pipeline request is voided.
|
|
657
|
+
*/
|
|
658
|
+
expire(id) {
|
|
659
|
+
this.expired.add(id);
|
|
660
|
+
for (const [topic, queue] of this.pending) {
|
|
661
|
+
const index = queue.findIndex((item) => item.id === id);
|
|
662
|
+
if (index !== -1) {
|
|
663
|
+
queue.splice(index, 1);
|
|
664
|
+
if (queue.length === 0) this.pending.delete(topic);
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
for (const [topic, item] of this.running) if (item.id === id) {
|
|
669
|
+
this.handler.invalidate(topic);
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
/** `session_request_expire` marked this id — the answer would fail, so none is sent. */
|
|
674
|
+
wasExpired(id) {
|
|
675
|
+
return this.expired.has(id);
|
|
676
|
+
}
|
|
677
|
+
async drain(topic) {
|
|
678
|
+
if (this.running.has(topic)) return;
|
|
679
|
+
for (;;) {
|
|
680
|
+
if (!this.ready) return;
|
|
681
|
+
const item = this.pending.get(topic)?.shift();
|
|
682
|
+
if (item === void 0) {
|
|
683
|
+
this.pending.delete(topic);
|
|
684
|
+
return;
|
|
685
|
+
}
|
|
686
|
+
this.running.set(topic, item);
|
|
687
|
+
try {
|
|
688
|
+
await this.handler.run(item);
|
|
689
|
+
} catch (error) {
|
|
690
|
+
this.handler.warn(error);
|
|
691
|
+
} finally {
|
|
692
|
+
this.running.delete(topic);
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
};
|
|
697
|
+
// src/walletconnect/solana.ts
|
|
698
|
+
const isParams = (params) => typeof params === "object" && params !== null;
|
|
699
|
+
const pubkeyOf = (params) => {
|
|
700
|
+
const { pubkey } = params;
|
|
701
|
+
if (pubkey !== void 0 && typeof pubkey !== "string") throw invalidParams("pubkey must be a base58 address");
|
|
702
|
+
return pubkey;
|
|
703
|
+
};
|
|
704
|
+
const base58Of = (value, name) => {
|
|
705
|
+
if (typeof value !== "string") throw invalidParams(`${name} must be a base58 string`);
|
|
706
|
+
try {
|
|
707
|
+
return base58.decode(value);
|
|
708
|
+
} catch {
|
|
709
|
+
throw invalidParams(`${name} is not valid base58`);
|
|
710
|
+
}
|
|
711
|
+
};
|
|
712
|
+
const base64Of = (value, name) => {
|
|
713
|
+
if (typeof value !== "string") throw invalidParams(`${name} must be a base64 string`);
|
|
714
|
+
try {
|
|
715
|
+
return base64.decode(value);
|
|
716
|
+
} catch {
|
|
717
|
+
throw invalidParams(`${name} is not valid base64`);
|
|
718
|
+
}
|
|
719
|
+
};
|
|
720
|
+
/** The session's Solana address — the signer whose slot the returned signature is read from. */
|
|
721
|
+
const sessionAddress = (call, engine) => {
|
|
722
|
+
const [bound] = engine.connections.sessionAccounts(call.origin.origin, call.network)?.addresses ?? [];
|
|
723
|
+
if (bound === void 0) throw new ProviderError(4100, "no solana account for this origin");
|
|
724
|
+
return bound;
|
|
725
|
+
};
|
|
726
|
+
const signMessage = async (call, engine, params) => {
|
|
727
|
+
const pubkey = pubkeyOf(params);
|
|
728
|
+
if (pubkey === void 0) throw invalidParams("solana_signMessage needs the signing pubkey");
|
|
729
|
+
const result = await engine.solanaWallet.handle(call.origin, {
|
|
730
|
+
method: "solana:signMessage",
|
|
731
|
+
params: {
|
|
732
|
+
message: base58Of(params["message"], "message"),
|
|
733
|
+
accounts: [pubkey]
|
|
734
|
+
},
|
|
735
|
+
network: call.network
|
|
736
|
+
});
|
|
737
|
+
return { signature: base58.encode(bytesField(result, "signature")) };
|
|
738
|
+
};
|
|
739
|
+
const signTransaction = async (call, engine, params) => {
|
|
740
|
+
const pubkey = pubkeyOf(params);
|
|
741
|
+
const chain = walletStandardChain(call.network);
|
|
742
|
+
if (chain === void 0) throw internalError(`network ${call.network} has no Wallet Standard chain id`);
|
|
743
|
+
const result = await engine.solanaWallet.handle(call.origin, {
|
|
744
|
+
method: "solana:signTransaction",
|
|
745
|
+
params: {
|
|
746
|
+
transactions: [base64Of(params["transaction"], "transaction")],
|
|
747
|
+
accounts: pubkey === void 0 ? [] : [pubkey],
|
|
748
|
+
chains: [chain]
|
|
749
|
+
},
|
|
750
|
+
network: call.network
|
|
751
|
+
});
|
|
752
|
+
const [signed] = bytesListField(result, "signedTransactions");
|
|
753
|
+
if (signed === void 0) throw internalError("the sign request returned no transaction");
|
|
754
|
+
const signature = getTransactionDecoder().decode(signed).signatures[address(sessionAddress(call, engine))];
|
|
755
|
+
if (signature === null || signature === void 0) throw internalError("the signed transaction has no signature for the session account");
|
|
756
|
+
return {
|
|
757
|
+
signature: base58.encode(new Uint8Array(signature)),
|
|
758
|
+
transaction: base64.encode(signed)
|
|
759
|
+
};
|
|
760
|
+
};
|
|
761
|
+
const signAllTransactions = async (call, engine, params) => {
|
|
762
|
+
const raw = params["transactions"];
|
|
763
|
+
if (!Array.isArray(raw) || raw.length === 0) throw invalidParams("solana_signAllTransactions needs a non-empty transactions array");
|
|
764
|
+
const chain = walletStandardChain(call.network);
|
|
765
|
+
if (chain === void 0) throw internalError(`network ${call.network} has no Wallet Standard chain id`);
|
|
766
|
+
const result = await engine.solanaWallet.handle(call.origin, {
|
|
767
|
+
method: "solana:signTransaction",
|
|
768
|
+
params: {
|
|
769
|
+
transactions: raw.map((tx) => base64Of(tx, "each transaction")),
|
|
770
|
+
chains: raw.map(() => chain)
|
|
771
|
+
},
|
|
772
|
+
network: call.network
|
|
773
|
+
});
|
|
774
|
+
return { transactions: bytesListField(result, "signedTransactions").map((tx) => base64.encode(tx)) };
|
|
775
|
+
};
|
|
776
|
+
const signAndSend = async (call, engine, params) => {
|
|
777
|
+
const pubkey = pubkeyOf(params);
|
|
778
|
+
const chain = walletStandardChain(call.network);
|
|
779
|
+
if (chain === void 0) throw internalError(`network ${call.network} has no Wallet Standard chain id`);
|
|
780
|
+
const result = await engine.solanaWallet.handle(call.origin, {
|
|
781
|
+
method: "solana:signAndSendTransaction",
|
|
782
|
+
params: {
|
|
783
|
+
transactions: [base64Of(params["transaction"], "transaction")],
|
|
784
|
+
accounts: pubkey === void 0 ? [] : [pubkey],
|
|
785
|
+
chains: [chain]
|
|
786
|
+
},
|
|
787
|
+
network: call.network
|
|
788
|
+
});
|
|
789
|
+
const [signature] = bytesListField(result, "signatures");
|
|
790
|
+
if (signature === void 0) throw internalError("the broadcast returned no signature");
|
|
791
|
+
return { signature: base58.encode(signature) };
|
|
792
|
+
};
|
|
793
|
+
const dispatch = async (call, engine) => {
|
|
794
|
+
const params = isParams(call.params) ? call.params : {};
|
|
795
|
+
switch (call.method) {
|
|
796
|
+
case "solana_signMessage": return signMessage(call, engine, params);
|
|
797
|
+
case "solana_signTransaction": return signTransaction(call, engine, params);
|
|
798
|
+
case "solana_signAllTransactions": return signAllTransactions(call, engine, params);
|
|
799
|
+
case "solana_signAndSendTransaction": return signAndSend(call, engine, params);
|
|
800
|
+
default: throw new ProviderError(-32601, `unsupported solana method ${call.method}`);
|
|
801
|
+
}
|
|
802
|
+
};
|
|
803
|
+
// src/walletconnect/client.ts
|
|
804
|
+
/** One row per CAIP namespace the wallet serves. */
|
|
805
|
+
const ROWS = {
|
|
806
|
+
eip155: eip155Row,
|
|
807
|
+
solana: {
|
|
808
|
+
namespace: "solana",
|
|
809
|
+
methods: {
|
|
810
|
+
solana_signMessage: ["solana:signMessage"],
|
|
811
|
+
solana_signTransaction: ["solana:signTransaction"],
|
|
812
|
+
solana_signAllTransactions: ["solana:signTransaction"],
|
|
813
|
+
solana_signAndSendTransaction: ["solana:signAndSendTransaction"]
|
|
814
|
+
},
|
|
815
|
+
events: ["accountsChanged", "chainChanged"],
|
|
816
|
+
serves: (network) => walletStandardChain(network) !== void 0,
|
|
817
|
+
accounts: (scope) => scope.accounts,
|
|
818
|
+
dispatch
|
|
819
|
+
},
|
|
820
|
+
bip122: bip122Row
|
|
821
|
+
};
|
|
822
|
+
/** A session within this much of its expiry is extended on every reconcile. */
|
|
823
|
+
const EXTEND_WITHIN_MS = 5184e5;
|
|
824
|
+
var WalletConnectController = class extends Controller {
|
|
825
|
+
queue;
|
|
826
|
+
judged = /* @__PURE__ */ new Map();
|
|
827
|
+
held = /* @__PURE__ */ new Map();
|
|
828
|
+
heldAuths = /* @__PURE__ */ new Map();
|
|
829
|
+
lastNetwork = /* @__PURE__ */ new Map();
|
|
830
|
+
gone = /* @__PURE__ */ new Set();
|
|
831
|
+
chain = Promise.resolve();
|
|
832
|
+
reconcileScheduled = false;
|
|
833
|
+
establishing = 0;
|
|
834
|
+
disposed = false;
|
|
835
|
+
walletIds = /* @__PURE__ */ new Set();
|
|
836
|
+
off = [];
|
|
837
|
+
options;
|
|
838
|
+
core;
|
|
839
|
+
kit;
|
|
840
|
+
constructor(options, core, kit) {
|
|
841
|
+
super({
|
|
842
|
+
name: "walletconnect",
|
|
843
|
+
defaultState: () => ({ proposals: {} })
|
|
844
|
+
});
|
|
845
|
+
this.options = options;
|
|
846
|
+
this.core = core;
|
|
847
|
+
this.kit = kit;
|
|
848
|
+
this.queue = new SessionRequestQueue({
|
|
849
|
+
run: async (item) => this.runRequest(item),
|
|
850
|
+
invalidate: (topic) => {
|
|
851
|
+
this.options.engine.connections.invalidateOrigin(walletConnectKey(topic));
|
|
852
|
+
},
|
|
853
|
+
warn: (error) => this.options.logger.warn("walletconnect request failed", error)
|
|
854
|
+
});
|
|
855
|
+
}
|
|
856
|
+
async init() {
|
|
857
|
+
const { engine, wallet } = this.options;
|
|
858
|
+
this.walletIds = new Set(wallet.getSnapshot().wallets.map((w) => w.walletId));
|
|
859
|
+
this.kit.on("session_proposal", this.onProposal);
|
|
860
|
+
this.kit.on("proposal_expire", this.onProposalExpire);
|
|
861
|
+
this.kit.on("session_request", this.onSessionRequest);
|
|
862
|
+
this.kit.on("session_request_expire", this.onRequestExpire);
|
|
863
|
+
this.kit.on("session_delete", this.onSessionDelete);
|
|
864
|
+
this.kit.on("session_authenticate", this.onSessionAuthenticate);
|
|
865
|
+
const { signClient } = this.kit.engine;
|
|
866
|
+
signClient.events.on("session_expire", this.onSessionExpire);
|
|
867
|
+
this.off.push(() => {
|
|
868
|
+
this.kit.off("session_proposal", this.onProposal);
|
|
869
|
+
this.kit.off("proposal_expire", this.onProposalExpire);
|
|
870
|
+
this.kit.off("session_request", this.onSessionRequest);
|
|
871
|
+
this.kit.off("session_request_expire", this.onRequestExpire);
|
|
872
|
+
this.kit.off("session_delete", this.onSessionDelete);
|
|
873
|
+
this.kit.off("session_authenticate", this.onSessionAuthenticate);
|
|
874
|
+
signClient.events.off("session_expire", this.onSessionExpire);
|
|
875
|
+
}, engine.connections.store.subscribe((state, previous) => this.onConnections(state.ready, previous.ready)), wallet.subscribe(() => this.onWallet()));
|
|
876
|
+
for (const proposal of Object.values(this.kit.getPendingSessionProposals())) await this.offerProposal(proposal, async () => this.recoverVerify(proposal));
|
|
877
|
+
for (const pending of this.kit.getPendingSessionRequests()) this.enqueue(pending);
|
|
878
|
+
for (const pending of signClient.auth.requests.getAll()) await this.offerAuth({
|
|
879
|
+
id: pending.id,
|
|
880
|
+
topic: pending.pairingTopic,
|
|
881
|
+
params: {
|
|
882
|
+
requester: pending.requester,
|
|
883
|
+
authPayload: pending.authPayload,
|
|
884
|
+
expiryTimestamp: pending.expiryTimestamp
|
|
885
|
+
},
|
|
886
|
+
verifyContext: pending.verifyContext
|
|
887
|
+
});
|
|
888
|
+
this.syncReady();
|
|
889
|
+
this.scheduleReconcile();
|
|
890
|
+
}
|
|
891
|
+
async destroy() {
|
|
892
|
+
await this.dispose();
|
|
893
|
+
}
|
|
894
|
+
/** Tears the transport down: unsubscribes, closes the relay connection, clears state. */
|
|
895
|
+
async dispose() {
|
|
896
|
+
if (this.disposed) return;
|
|
897
|
+
this.disposed = true;
|
|
898
|
+
for (const off of this.off) off();
|
|
899
|
+
this.off.length = 0;
|
|
900
|
+
try {
|
|
901
|
+
await this.core.relayer.transportClose();
|
|
902
|
+
} catch (error) {
|
|
903
|
+
this.options.logger.warn("walletconnect transport close failed", error);
|
|
904
|
+
}
|
|
905
|
+
this.judged.clear();
|
|
906
|
+
this.held.clear();
|
|
907
|
+
this.heldAuths.clear();
|
|
908
|
+
this.update(() => ({ proposals: {} }));
|
|
909
|
+
}
|
|
910
|
+
/** `wc:` pairing URI → an active pairing the dApp's proposal arrives on. */
|
|
911
|
+
async pair(uri) {
|
|
912
|
+
let parsed;
|
|
913
|
+
try {
|
|
914
|
+
parsed = parseUri(uri);
|
|
915
|
+
} catch {
|
|
916
|
+
throw new WalletConnectError("invalid-uri", "not a WalletConnect pairing URI");
|
|
917
|
+
}
|
|
918
|
+
if (parsed.version !== 2 || !/^[0-9a-f]{64}$/i.test(parsed.topic) || typeof parsed.symKey !== "string" || parsed.symKey === "" || parsed.relay?.protocol === void 0) throw new WalletConnectError("invalid-uri", "not a v2 WalletConnect pairing URI");
|
|
919
|
+
if (parsed.expiryTimestamp !== void 0 && parsed.expiryTimestamp * 1e3 <= this.options.now()) throw new WalletConnectError("expired-uri", "the pairing URI has expired");
|
|
920
|
+
if (this.core.pairing.getPairings().some((pairing) => pairing.topic === parsed.topic)) throw new WalletConnectError("duplicate-pairing", "this pairing URI is already in use");
|
|
921
|
+
try {
|
|
922
|
+
await this.kit.pair({ uri });
|
|
923
|
+
} catch (error) {
|
|
924
|
+
if (error instanceof Error && error.message.includes("Pairing already exists")) throw new WalletConnectError("duplicate-pairing", "this pairing URI is already active");
|
|
925
|
+
throw error;
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
/**
|
|
929
|
+
* Grants `grant.networks` to the proposal: the session is settled on the relay inside the
|
|
930
|
+
* connection store's write queue, then persisted under `walletconnect:<topic>`.
|
|
931
|
+
*/
|
|
932
|
+
async approve(id, grant) {
|
|
933
|
+
const proposal = this.getState().proposals[id];
|
|
934
|
+
const judged = this.judged.get(id);
|
|
935
|
+
if (proposal === void 0 || judged === void 0) throw new WalletConnectError("unknown-proposal", `unknown proposal ${id}`);
|
|
936
|
+
if (this.options.now() >= proposal.expiresAt) {
|
|
937
|
+
this.removeProposal(id);
|
|
938
|
+
throw new WalletConnectError("expired", "the proposal has expired");
|
|
939
|
+
}
|
|
940
|
+
if (!this.ready()) throw new WalletConnectError("locked", "the wallet is locked");
|
|
941
|
+
if (this.options.engine.phishing.check(proposal.peer.url) === "blocked") {
|
|
942
|
+
await this.rejectProposal(id);
|
|
943
|
+
throw new WalletConnectError("blocked", "the peer url is on the phishing list");
|
|
944
|
+
}
|
|
945
|
+
const acknowledged = new Set(grant.acknowledged);
|
|
946
|
+
if (!proposal.risk.filter((finding) => finding.level === "danger").every((finding) => acknowledged.has(finding.code))) throw new WalletConnectError("unacknowledged", "danger findings must be acknowledged");
|
|
947
|
+
const granted = new Set(grant.networks);
|
|
948
|
+
if (grant.networks.length === 0 || !proposal.required.every((network) => granted.has(network)) || grant.networks.some((network) => !proposal.networks.includes(network))) throw new WalletConnectError("invalid-grant", "the granted networks are not in the offer");
|
|
949
|
+
const scopes = {};
|
|
950
|
+
for (const network of grant.networks) {
|
|
951
|
+
const key = network.split(":")[0] ?? "";
|
|
952
|
+
const offered = judged.offer.namespaces[key];
|
|
953
|
+
const row = ROWS[key];
|
|
954
|
+
if (offered === void 0 || row === void 0) throw new WalletConnectError("invalid-grant", "the granted networks are not in the offer");
|
|
955
|
+
const methods = /* @__PURE__ */ new Set();
|
|
956
|
+
for (const method of offered.methods) for (const providerMethod of row.methods[method] ?? []) methods.add(providerMethod);
|
|
957
|
+
scopes[network] = {
|
|
958
|
+
methods: [...methods],
|
|
959
|
+
notifications: [...offered.events]
|
|
960
|
+
};
|
|
961
|
+
}
|
|
962
|
+
this.establishing += 1;
|
|
963
|
+
try {
|
|
964
|
+
const session = await this.options.engine.connections.establishWalletConnect(scopes, async (bound) => this.settle(id, proposal, judged, bound));
|
|
965
|
+
if (session.origin.kind === "walletconnect" && judged.offer.namespaces["bip122"]?.events.includes("bip122_addressesChanged") === true) for (const network of grant.networks.filter((n) => n.startsWith("bip122:"))) await this.emitBip122Addresses(session.origin, session.origin.topic, network);
|
|
966
|
+
this.removeProposal(id);
|
|
967
|
+
return session;
|
|
968
|
+
} finally {
|
|
969
|
+
this.establishing -= 1;
|
|
970
|
+
this.scheduleReconcile();
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
/** One `bip122_addressesChanged` — failures are logged, never thrown. */
|
|
974
|
+
async emitBip122Addresses(origin, topic, chainId) {
|
|
975
|
+
try {
|
|
976
|
+
const data = await bip122Addresses(this.options.engine, origin, chainId);
|
|
977
|
+
await this.kit.emitSessionEvent({
|
|
978
|
+
topic,
|
|
979
|
+
event: {
|
|
980
|
+
name: "bip122_addressesChanged",
|
|
981
|
+
data
|
|
982
|
+
},
|
|
983
|
+
chainId
|
|
984
|
+
});
|
|
985
|
+
} catch (error) {
|
|
986
|
+
this.options.logger.warn("walletconnect event failed", error);
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
/** Turns the proposal down; the peer learns the rejection. */
|
|
990
|
+
async reject(id) {
|
|
991
|
+
if (this.getState().proposals[id] === void 0) throw new WalletConnectError("unknown-proposal", `unknown proposal ${id}`);
|
|
992
|
+
await this.rejectProposal(id);
|
|
993
|
+
}
|
|
994
|
+
/** Settles the session on the relay and hands the controller its walletconnect origin. */
|
|
995
|
+
async settle(id, proposal, judged, bound) {
|
|
996
|
+
const namespaces = {};
|
|
997
|
+
for (const [key, offered] of Object.entries(judged.offer.namespaces)) {
|
|
998
|
+
const row = ROWS[key];
|
|
999
|
+
const chains = offered.chains.filter((chain) => bound[chain] !== void 0);
|
|
1000
|
+
if (row === void 0 || chains.length === 0) continue;
|
|
1001
|
+
namespaces[key] = {
|
|
1002
|
+
chains,
|
|
1003
|
+
accounts: chains.flatMap((chain) => {
|
|
1004
|
+
const scope = bound[chain];
|
|
1005
|
+
return scope === void 0 ? [] : row.accounts(scope);
|
|
1006
|
+
}),
|
|
1007
|
+
methods: [...offered.methods],
|
|
1008
|
+
events: [...offered.events]
|
|
1009
|
+
};
|
|
1010
|
+
}
|
|
1011
|
+
const session = await this.kit.approveSession({
|
|
1012
|
+
id,
|
|
1013
|
+
namespaces
|
|
1014
|
+
});
|
|
1015
|
+
return {
|
|
1016
|
+
kind: "walletconnect",
|
|
1017
|
+
origin: walletConnectKey(session.topic),
|
|
1018
|
+
topic: session.topic,
|
|
1019
|
+
url: proposal.peer.url,
|
|
1020
|
+
name: proposal.peer.name,
|
|
1021
|
+
verify: proposal.verify
|
|
1022
|
+
};
|
|
1023
|
+
}
|
|
1024
|
+
ready() {
|
|
1025
|
+
return this.options.engine.connections.getState().ready;
|
|
1026
|
+
}
|
|
1027
|
+
removeProposal(id) {
|
|
1028
|
+
this.judged.delete(id);
|
|
1029
|
+
this.update((state) => {
|
|
1030
|
+
const { [id]: _gone, ...proposals } = state.proposals;
|
|
1031
|
+
return { proposals };
|
|
1032
|
+
});
|
|
1033
|
+
}
|
|
1034
|
+
async rejectProposal(id) {
|
|
1035
|
+
this.removeProposal(id);
|
|
1036
|
+
try {
|
|
1037
|
+
await this.kit.rejectSession({
|
|
1038
|
+
id,
|
|
1039
|
+
reason: getSdkError("USER_REJECTED")
|
|
1040
|
+
});
|
|
1041
|
+
} catch (error) {
|
|
1042
|
+
this.options.logger.warn("walletconnect proposal rejection failed", error);
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
/**
|
|
1046
|
+
* A proposal — live event or recovered from the store — judged end to end; rejected ones are
|
|
1047
|
+
* answered at once, servable ones enter the state until approved, rejected or expired.
|
|
1048
|
+
*/
|
|
1049
|
+
async offerProposal(proposal, resolveVerify) {
|
|
1050
|
+
const { engine } = this.options;
|
|
1051
|
+
if (!this.ready()) {
|
|
1052
|
+
this.held.set(proposal.id, {
|
|
1053
|
+
proposal,
|
|
1054
|
+
verify: Promise.resolve(resolveVerify())
|
|
1055
|
+
});
|
|
1056
|
+
return;
|
|
1057
|
+
}
|
|
1058
|
+
const verify = await resolveVerify();
|
|
1059
|
+
const verdict = judgeProposal(proposal, verify, {
|
|
1060
|
+
phishing: (url) => engine.phishing.check(url),
|
|
1061
|
+
isEnabled: (network) => engine.connections.isEnabled(network),
|
|
1062
|
+
rows: ROWS,
|
|
1063
|
+
userRejected: () => getSdkError("USER_REJECTED")
|
|
1064
|
+
});
|
|
1065
|
+
if (!verdict.ok) {
|
|
1066
|
+
try {
|
|
1067
|
+
await this.kit.rejectSession({
|
|
1068
|
+
id: proposal.id,
|
|
1069
|
+
reason: verdict.error
|
|
1070
|
+
});
|
|
1071
|
+
} catch (error) {
|
|
1072
|
+
this.options.logger.warn("walletconnect proposal rejection failed", error);
|
|
1073
|
+
}
|
|
1074
|
+
return;
|
|
1075
|
+
}
|
|
1076
|
+
const judged = verdict.proposal;
|
|
1077
|
+
this.judged.set(proposal.id, judged);
|
|
1078
|
+
this.update((state) => ({ proposals: {
|
|
1079
|
+
...state.proposals,
|
|
1080
|
+
[proposal.id]: {
|
|
1081
|
+
id: proposal.id,
|
|
1082
|
+
peer: judged.peer,
|
|
1083
|
+
verify: judged.verify,
|
|
1084
|
+
risk: judged.risk,
|
|
1085
|
+
networks: judged.offer.networks,
|
|
1086
|
+
required: judged.offer.required,
|
|
1087
|
+
methods: Object.fromEntries(Object.entries(judged.offer.namespaces).map(([key, offered]) => [key, offered.methods])),
|
|
1088
|
+
expiresAt: judged.expiresAt
|
|
1089
|
+
}
|
|
1090
|
+
} }));
|
|
1091
|
+
}
|
|
1092
|
+
/** A recovered proposal re-resolves its attestation; a failed resolution stays UNKNOWN. */
|
|
1093
|
+
async recoverVerify(proposal) {
|
|
1094
|
+
try {
|
|
1095
|
+
const { origin, isScam } = await this.core.verify.resolve({
|
|
1096
|
+
...proposal.attestation === void 0 ? {} : { attestationId: proposal.attestation },
|
|
1097
|
+
...proposal.encryptedId === void 0 ? {} : { encryptedId: proposal.encryptedId },
|
|
1098
|
+
...proposal.proposer.metadata.verifyUrl === void 0 ? {} : { verifyUrl: proposal.proposer.metadata.verifyUrl }
|
|
1099
|
+
});
|
|
1100
|
+
const url = metadataOrigin(proposal.proposer.metadata.url);
|
|
1101
|
+
return {
|
|
1102
|
+
validation: url !== void 0 && origin === url ? "VALID" : typeof origin === "string" && origin.length > 0 ? "INVALID" : "UNKNOWN",
|
|
1103
|
+
isScam: isScam === true
|
|
1104
|
+
};
|
|
1105
|
+
} catch {
|
|
1106
|
+
return {
|
|
1107
|
+
validation: "UNKNOWN",
|
|
1108
|
+
isScam: false
|
|
1109
|
+
};
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
enqueue(request) {
|
|
1113
|
+
this.queue.enqueue({
|
|
1114
|
+
id: request.id,
|
|
1115
|
+
topic: request.topic,
|
|
1116
|
+
chainId: request.params.chainId,
|
|
1117
|
+
method: request.params.request.method,
|
|
1118
|
+
params: request.params.request.params,
|
|
1119
|
+
expiryTimestamp: request.params.request.expiryTimestamp,
|
|
1120
|
+
verify: verifyOf(request.verifyContext.verified)
|
|
1121
|
+
});
|
|
1122
|
+
}
|
|
1123
|
+
/** One queued request: validate, dispatch through the shared handler, answer. */
|
|
1124
|
+
async runRequest(item) {
|
|
1125
|
+
const { engine } = this.options;
|
|
1126
|
+
if (!this.ready()) {
|
|
1127
|
+
this.queue.requeue(item);
|
|
1128
|
+
return;
|
|
1129
|
+
}
|
|
1130
|
+
if (item.expiryTimestamp !== void 0 && item.expiryTimestamp * 1e3 <= this.options.now()) {
|
|
1131
|
+
await this.respond(item, {
|
|
1132
|
+
id: item.id,
|
|
1133
|
+
jsonrpc: "2.0",
|
|
1134
|
+
error: {
|
|
1135
|
+
code: 4100,
|
|
1136
|
+
message: "Request expired"
|
|
1137
|
+
}
|
|
1138
|
+
});
|
|
1139
|
+
return;
|
|
1140
|
+
}
|
|
1141
|
+
if (utf8ToBytes(JSON.stringify(item.params)).length > 131072) {
|
|
1142
|
+
await this.respond(item, {
|
|
1143
|
+
id: item.id,
|
|
1144
|
+
jsonrpc: "2.0",
|
|
1145
|
+
error: {
|
|
1146
|
+
code: -32005,
|
|
1147
|
+
message: "request params exceed the message size limit"
|
|
1148
|
+
}
|
|
1149
|
+
});
|
|
1150
|
+
return;
|
|
1151
|
+
}
|
|
1152
|
+
const session = engine.connections.session(walletConnectKey(item.topic));
|
|
1153
|
+
if (session === void 0 || session.origin.kind !== "walletconnect") {
|
|
1154
|
+
await this.respond(item, {
|
|
1155
|
+
id: item.id,
|
|
1156
|
+
jsonrpc: "2.0",
|
|
1157
|
+
error: {
|
|
1158
|
+
code: 4100,
|
|
1159
|
+
message: "not authorized"
|
|
1160
|
+
}
|
|
1161
|
+
});
|
|
1162
|
+
return;
|
|
1163
|
+
}
|
|
1164
|
+
const row = ROWS[item.chainId.split(":")[0] ?? ""];
|
|
1165
|
+
if (row === void 0) {
|
|
1166
|
+
await this.respond(item, {
|
|
1167
|
+
id: item.id,
|
|
1168
|
+
jsonrpc: "2.0",
|
|
1169
|
+
error: {
|
|
1170
|
+
code: -32601,
|
|
1171
|
+
message: "unsupported namespace"
|
|
1172
|
+
}
|
|
1173
|
+
});
|
|
1174
|
+
return;
|
|
1175
|
+
}
|
|
1176
|
+
const origin = {
|
|
1177
|
+
...session.origin,
|
|
1178
|
+
verify: item.verify
|
|
1179
|
+
};
|
|
1180
|
+
try {
|
|
1181
|
+
const result = await row.dispatch({
|
|
1182
|
+
origin,
|
|
1183
|
+
network: item.chainId,
|
|
1184
|
+
method: item.method,
|
|
1185
|
+
params: item.params
|
|
1186
|
+
}, engine);
|
|
1187
|
+
await this.respond(item, {
|
|
1188
|
+
id: item.id,
|
|
1189
|
+
jsonrpc: "2.0",
|
|
1190
|
+
result
|
|
1191
|
+
});
|
|
1192
|
+
} catch (error) {
|
|
1193
|
+
if (this.queue.wasExpired(item.id)) return;
|
|
1194
|
+
if (!this.ready()) {
|
|
1195
|
+
this.queue.requeue(item);
|
|
1196
|
+
return;
|
|
1197
|
+
}
|
|
1198
|
+
await this.respond(item, {
|
|
1199
|
+
id: item.id,
|
|
1200
|
+
jsonrpc: "2.0",
|
|
1201
|
+
error: requestError(error)
|
|
1202
|
+
});
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
/** The peer gets its answer unless the request expired while it ran — then none is sent. */
|
|
1206
|
+
async respond(item, answer) {
|
|
1207
|
+
if (this.queue.wasExpired(item.id)) return;
|
|
1208
|
+
try {
|
|
1209
|
+
await this.kit.respondSessionRequest({
|
|
1210
|
+
topic: item.topic,
|
|
1211
|
+
response: answer
|
|
1212
|
+
});
|
|
1213
|
+
} catch (error) {
|
|
1214
|
+
this.options.logger.warn("walletconnect response failed", error);
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
onProposal = (event) => {
|
|
1218
|
+
this.serialized(async () => {
|
|
1219
|
+
try {
|
|
1220
|
+
await this.offerProposal(event.params, () => verifyOf(event.verifyContext.verified));
|
|
1221
|
+
} catch (error) {
|
|
1222
|
+
this.options.logger.warn("walletconnect proposal failed", error);
|
|
1223
|
+
}
|
|
1224
|
+
});
|
|
1225
|
+
};
|
|
1226
|
+
onProposalExpire = (event) => {
|
|
1227
|
+
this.held.delete(event.id);
|
|
1228
|
+
this.removeProposal(event.id);
|
|
1229
|
+
};
|
|
1230
|
+
onSessionRequest = (event) => {
|
|
1231
|
+
this.enqueue(event);
|
|
1232
|
+
};
|
|
1233
|
+
onRequestExpire = (event) => {
|
|
1234
|
+
this.queue.expire(event.id);
|
|
1235
|
+
};
|
|
1236
|
+
onSessionDelete = (event) => {
|
|
1237
|
+
this.sessionEnded(event.topic);
|
|
1238
|
+
};
|
|
1239
|
+
onSessionExpire = (event) => {
|
|
1240
|
+
this.sessionEnded(event.topic);
|
|
1241
|
+
};
|
|
1242
|
+
/** The peer or the expirer ended the session: drop its queue; the next reconcile revokes it. */
|
|
1243
|
+
sessionEnded(topic) {
|
|
1244
|
+
this.queue.drop(topic);
|
|
1245
|
+
this.lastNetwork.delete(topic);
|
|
1246
|
+
this.scheduleReconcile();
|
|
1247
|
+
}
|
|
1248
|
+
syncReady() {
|
|
1249
|
+
this.queue.setReady(this.ready());
|
|
1250
|
+
}
|
|
1251
|
+
onConnections(ready, wasReady) {
|
|
1252
|
+
if (!ready) {
|
|
1253
|
+
this.queue.setReady(false);
|
|
1254
|
+
return;
|
|
1255
|
+
}
|
|
1256
|
+
if (!wasReady) {
|
|
1257
|
+
this.queue.setReady(true);
|
|
1258
|
+
this.drainHeld();
|
|
1259
|
+
}
|
|
1260
|
+
this.scheduleReconcile();
|
|
1261
|
+
}
|
|
1262
|
+
/** Proposals and auths held while locked get judged now, in arrival order. */
|
|
1263
|
+
drainHeld() {
|
|
1264
|
+
for (const [id, held] of this.held) {
|
|
1265
|
+
this.held.delete(id);
|
|
1266
|
+
this.serialized(async () => this.offerProposal(held.proposal, async () => held.verify));
|
|
1267
|
+
}
|
|
1268
|
+
for (const [id, auth] of this.heldAuths) {
|
|
1269
|
+
this.heldAuths.delete(id);
|
|
1270
|
+
this.serialized(async () => this.offerAuth(auth));
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
/**
|
|
1274
|
+
* A `session_authenticate` — live event or recovered from the auth store — handled end to end.
|
|
1275
|
+
* While locked it is held raw (the enabled set is empty); when ready it validates, signs the SIWE
|
|
1276
|
+
* through the pipeline and settles. Auth requests are short-lived, so a held one is never
|
|
1277
|
+
* re-emitted and an expired one is simply refused when it finally runs.
|
|
1278
|
+
*/
|
|
1279
|
+
async offerAuth(event) {
|
|
1280
|
+
if (!this.ready()) {
|
|
1281
|
+
this.heldAuths.set(event.id, event);
|
|
1282
|
+
return;
|
|
1283
|
+
}
|
|
1284
|
+
await handleAuthenticate(event, {
|
|
1285
|
+
kit: this.kit,
|
|
1286
|
+
engine: this.options.engine,
|
|
1287
|
+
now: this.options.now,
|
|
1288
|
+
warn: (message, error) => this.options.logger.warn(message, error),
|
|
1289
|
+
establish: async (work) => {
|
|
1290
|
+
this.establishing += 1;
|
|
1291
|
+
try {
|
|
1292
|
+
return await work();
|
|
1293
|
+
} finally {
|
|
1294
|
+
this.establishing -= 1;
|
|
1295
|
+
this.scheduleReconcile();
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
});
|
|
1299
|
+
}
|
|
1300
|
+
onSessionAuthenticate = (event) => {
|
|
1301
|
+
this.serialized(async () => {
|
|
1302
|
+
try {
|
|
1303
|
+
await this.offerAuth(event);
|
|
1304
|
+
} catch (error) {
|
|
1305
|
+
this.options.logger.warn("walletconnect authenticate failed", error);
|
|
1306
|
+
}
|
|
1307
|
+
});
|
|
1308
|
+
};
|
|
1309
|
+
/** Async lifecycle work runs strictly serial so repoints and deletions never interleave. */
|
|
1310
|
+
serialized(work) {
|
|
1311
|
+
const previous = this.chain;
|
|
1312
|
+
this.chain = (async () => {
|
|
1313
|
+
await previous;
|
|
1314
|
+
try {
|
|
1315
|
+
await work();
|
|
1316
|
+
} catch (error) {
|
|
1317
|
+
this.options.logger.warn("walletconnect lifecycle failed", error);
|
|
1318
|
+
}
|
|
1319
|
+
})();
|
|
1320
|
+
}
|
|
1321
|
+
scheduleReconcile() {
|
|
1322
|
+
if (this.disposed || !this.ready()) return;
|
|
1323
|
+
if (this.reconcileScheduled) return;
|
|
1324
|
+
this.reconcileScheduled = true;
|
|
1325
|
+
this.serialized(async () => {
|
|
1326
|
+
this.reconcileScheduled = false;
|
|
1327
|
+
await this.reconcile();
|
|
1328
|
+
});
|
|
1329
|
+
}
|
|
1330
|
+
/**
|
|
1331
|
+
* Aligns the WalletKit session set with the controller's `walletconnect:` sessions — a session
|
|
1332
|
+
* only the peer still holds is disconnected, one only the wallet holds is revoked, and a session
|
|
1333
|
+
* both hold is re-pointed at the selected group's accounts and the session's current network.
|
|
1334
|
+
*/
|
|
1335
|
+
async reconcile() {
|
|
1336
|
+
const { engine } = this.options;
|
|
1337
|
+
if (!this.ready()) return;
|
|
1338
|
+
const active = this.kit.getActiveSessions();
|
|
1339
|
+
const ours = /* @__PURE__ */ new Map();
|
|
1340
|
+
for (const session of Object.values(engine.connections.getState().sessions)) if (session.origin.kind === "walletconnect") ours.set(session.origin.topic, session);
|
|
1341
|
+
if (this.establishing === 0) {
|
|
1342
|
+
for (const topic of Object.keys(active)) if (!ours.has(topic) && !this.gone.has(topic)) await this.kit.disconnectSession({
|
|
1343
|
+
topic,
|
|
1344
|
+
reason: getSdkError("USER_DISCONNECTED")
|
|
1345
|
+
}).catch((error) => {
|
|
1346
|
+
this.options.logger.warn("walletconnect disconnect failed", error);
|
|
1347
|
+
});
|
|
1348
|
+
}
|
|
1349
|
+
for (const [topic, session] of ours) {
|
|
1350
|
+
if (this.gone.has(topic)) continue;
|
|
1351
|
+
const live = active[topic];
|
|
1352
|
+
if (live === void 0) {
|
|
1353
|
+
await engine.connections.revoke(session.origin.origin).catch((error) => {
|
|
1354
|
+
this.options.logger.warn("walletconnect revoke failed", error);
|
|
1355
|
+
});
|
|
1356
|
+
continue;
|
|
1357
|
+
}
|
|
1358
|
+
await this.repoint(topic, live, session);
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
/** One live session: re-advertise scopes, push account/chain changes, keep its expiry alive. */
|
|
1362
|
+
async repoint(topic, live, session) {
|
|
1363
|
+
const recomputed = sessionNamespaces(session.scopes, live.namespaces, ROWS);
|
|
1364
|
+
if (recomputed === void 0) {
|
|
1365
|
+
await this.kit.disconnectSession({
|
|
1366
|
+
topic,
|
|
1367
|
+
reason: getSdkError("USER_DISCONNECTED")
|
|
1368
|
+
}).catch((error) => {
|
|
1369
|
+
this.options.logger.warn("walletconnect disconnect failed", error);
|
|
1370
|
+
});
|
|
1371
|
+
await this.options.engine.connections.revoke(session.origin.origin).catch((error) => {
|
|
1372
|
+
this.options.logger.warn("walletconnect revoke failed", error);
|
|
1373
|
+
});
|
|
1374
|
+
return;
|
|
1375
|
+
}
|
|
1376
|
+
if (!sameNamespaces(live.namespaces, recomputed)) {
|
|
1377
|
+
const changed = changedAccounts(live.namespaces, recomputed);
|
|
1378
|
+
try {
|
|
1379
|
+
await this.kit.updateSession({
|
|
1380
|
+
topic,
|
|
1381
|
+
namespaces: recomputed
|
|
1382
|
+
});
|
|
1383
|
+
} catch (error) {
|
|
1384
|
+
this.options.logger.warn("walletconnect session update failed", error);
|
|
1385
|
+
}
|
|
1386
|
+
for (const [chainId, accounts] of changed) {
|
|
1387
|
+
const offered = recomputed[chainId.split(":")[0] ?? ""];
|
|
1388
|
+
if (offered !== void 0 && offered.events.includes("accountsChanged")) await this.kit.emitSessionEvent({
|
|
1389
|
+
topic,
|
|
1390
|
+
event: {
|
|
1391
|
+
name: "accountsChanged",
|
|
1392
|
+
data: [...accounts]
|
|
1393
|
+
},
|
|
1394
|
+
chainId
|
|
1395
|
+
}).catch((error) => {
|
|
1396
|
+
this.options.logger.warn("walletconnect event failed", error);
|
|
1397
|
+
});
|
|
1398
|
+
if (session.origin.kind === "walletconnect" && chainId.startsWith("bip122:") && offered !== void 0 && offered.events.includes("bip122_addressesChanged")) await this.emitBip122Addresses(session.origin, topic, chainId);
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
const previous = this.lastNetwork.get(topic);
|
|
1402
|
+
this.lastNetwork.set(topic, session.currentNetwork);
|
|
1403
|
+
const chainId = evmChainId(session.currentNetwork);
|
|
1404
|
+
const evm = recomputed["eip155"];
|
|
1405
|
+
if (previous !== void 0 && previous !== session.currentNetwork && chainId !== void 0 && evm !== void 0 && evm.events.includes("chainChanged") && (evm.chains ?? []).includes(session.currentNetwork)) await this.kit.emitSessionEvent({
|
|
1406
|
+
topic,
|
|
1407
|
+
event: {
|
|
1408
|
+
name: "chainChanged",
|
|
1409
|
+
data: chainId
|
|
1410
|
+
},
|
|
1411
|
+
chainId: session.currentNetwork
|
|
1412
|
+
}).catch((error) => {
|
|
1413
|
+
this.options.logger.warn("walletconnect event failed", error);
|
|
1414
|
+
});
|
|
1415
|
+
if (live.expiry * 1e3 - this.options.now() < EXTEND_WITHIN_MS) await this.kit.extendSession({ topic }).catch((error) => {
|
|
1416
|
+
this.options.logger.warn("walletconnect extend failed", error);
|
|
1417
|
+
});
|
|
1418
|
+
}
|
|
1419
|
+
/** A deleted wallet's sessions die at once — before a repoint could serve another wallet's. */
|
|
1420
|
+
onWallet() {
|
|
1421
|
+
const snapshot = this.options.wallet.getSnapshot();
|
|
1422
|
+
if (snapshot.vault !== "unlocked") return;
|
|
1423
|
+
const ids = new Set(snapshot.wallets.map((w) => w.walletId));
|
|
1424
|
+
const removed = [...this.walletIds].filter((id) => !ids.has(id));
|
|
1425
|
+
this.walletIds = ids;
|
|
1426
|
+
if (removed.length === 0) return;
|
|
1427
|
+
this.serialized(async () => {
|
|
1428
|
+
const active = this.kit.getActiveSessions();
|
|
1429
|
+
for (const session of Object.values(this.options.engine.connections.getState().sessions)) {
|
|
1430
|
+
if (session.origin.kind !== "walletconnect" || session.group === void 0 || !removed.includes(session.group.walletId)) continue;
|
|
1431
|
+
const { topic } = session.origin;
|
|
1432
|
+
this.gone.add(topic);
|
|
1433
|
+
const live = active[topic];
|
|
1434
|
+
if (live !== void 0) {
|
|
1435
|
+
await this.kit.disconnectSession({
|
|
1436
|
+
topic,
|
|
1437
|
+
reason: getSdkError("USER_DISCONNECTED")
|
|
1438
|
+
}).catch((error) => {
|
|
1439
|
+
this.options.logger.warn("walletconnect disconnect failed", error);
|
|
1440
|
+
});
|
|
1441
|
+
await this.core.pairing.disconnect({ topic: live.pairingTopic }).catch((error) => {
|
|
1442
|
+
this.options.logger.warn("walletconnect pairing disconnect failed", error);
|
|
1443
|
+
});
|
|
1444
|
+
}
|
|
1445
|
+
await this.options.engine.connections.revoke(session.origin.origin).catch((error) => {
|
|
1446
|
+
this.options.logger.warn("walletconnect revoke failed", error);
|
|
1447
|
+
});
|
|
1448
|
+
}
|
|
1449
|
+
});
|
|
1450
|
+
}
|
|
1451
|
+
};
|
|
1452
|
+
/** The chains whose advertised accounts differ between two namespace sets. */
|
|
1453
|
+
const changedAccounts = (before, after) => {
|
|
1454
|
+
const changed = [];
|
|
1455
|
+
for (const [key, next] of Object.entries(after)) {
|
|
1456
|
+
const previous = before[key];
|
|
1457
|
+
if (previous === void 0) continue;
|
|
1458
|
+
for (const chain of next.chains ?? []) {
|
|
1459
|
+
const now = next.accounts.filter((account) => account.startsWith(`${chain}:`));
|
|
1460
|
+
const then = previous.accounts.filter((account) => account.startsWith(`${chain}:`));
|
|
1461
|
+
if (now.length !== then.length || now.some((account) => !then.includes(account))) changed.push([chain, now]);
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
return changed;
|
|
1465
|
+
};
|
|
1466
|
+
/**
|
|
1467
|
+
* The handles a test reaches for the SDK internals the public entry hides — emitting engine-side
|
|
1468
|
+
* events or inspecting the pairing store. The entry itself only exports `createWalletConnect`.
|
|
1469
|
+
*/
|
|
1470
|
+
const createWalletConnectClient = async (options) => {
|
|
1471
|
+
const core = new Core({
|
|
1472
|
+
projectId: options.projectId,
|
|
1473
|
+
...options.relayUrl === void 0 ? {} : { relayUrl: options.relayUrl },
|
|
1474
|
+
telemetryEnabled: false,
|
|
1475
|
+
logger: "silent",
|
|
1476
|
+
storage: {
|
|
1477
|
+
getKeys: async () => options.storage.getKeys(),
|
|
1478
|
+
getEntries: async () => options.storage.getEntries(),
|
|
1479
|
+
getItem: async (key) => options.storage.getItem(key),
|
|
1480
|
+
setItem: async (key, value) => options.storage.setItem(key, value),
|
|
1481
|
+
removeItem: async (key) => options.storage.removeItem(key)
|
|
1482
|
+
}
|
|
1483
|
+
});
|
|
1484
|
+
const kit = await WalletKit.init({
|
|
1485
|
+
core,
|
|
1486
|
+
metadata: {
|
|
1487
|
+
...options.metadata,
|
|
1488
|
+
icons: [...options.metadata.icons]
|
|
1489
|
+
},
|
|
1490
|
+
signConfig: { disableRequestQueue: true }
|
|
1491
|
+
});
|
|
1492
|
+
const controller = new WalletConnectController(options, core, kit);
|
|
1493
|
+
await controller.init();
|
|
1494
|
+
return {
|
|
1495
|
+
walletConnect: controller,
|
|
1496
|
+
core,
|
|
1497
|
+
kit
|
|
1498
|
+
};
|
|
1499
|
+
};
|
|
1500
|
+
/** The `Core`/`WalletKit` pair plus the controller that drives them — one entry, one instance. */
|
|
1501
|
+
const createWalletConnect = async (options) => {
|
|
1502
|
+
const { walletConnect } = await createWalletConnectClient(options);
|
|
1503
|
+
return walletConnect;
|
|
1504
|
+
};
|
|
1505
|
+
export { WalletConnectError, createWalletConnect };
|
|
1506
|
+
|
|
1507
|
+
//# sourceMappingURL=walletconnect.mjs.map
|