@partylayer/sdk 0.18.2 → 0.20.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 +70 -226
- package/dist/index.d.mts +132 -91
- package/dist/index.d.ts +132 -91
- package/dist/index.js +1232 -147
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1227 -151
- package/dist/index.mjs.map +1 -1
- package/package.json +20 -10
package/dist/index.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { toWalletId, toPartyId, isRecognizedNetwork,
|
|
2
|
-
export { AdapterNotRegisteredError, PartyLayerError as CantonConnectError, CapabilityNotSupportedError, ENABLEMENT_METRICS, ERROR_METRICS, InternalError, METRICS, OriginNotAllowedError, PartyLayerError, REGISTRY_METRICS, RegistryFetchFailedError, RegistrySchemaInvalidError, RegistryVerificationFailedError, SessionExpiredError, TimeoutError, TransportError, UserRejectedError, WalletNotFoundError, WalletNotInstalledError, errorMetricName, isOfficialAdapterFactory, isOfficialProviderAdapter } from '@partylayer/core';
|
|
1
|
+
import { toWalletId, toPartyId, isRecognizedNetwork, detectNetworkMismatch, ledgerApiBodyToObject, normalizeLedgerMethodLower, hashForPrivacy, createMetricsPayload, isOfficialAdapterFactory, isOfficialProviderAdapter, mapUnknownErrorToPartyLayerError, findMatchingWalletInfo, NetworkMismatchError, METRICS, WalletNotFoundError, AdapterNotRegisteredError, capabilityGuard, installGuard, toSessionId, CapabilityNotSupportedError, toTransferIntent, errorMetricName, TransportError, toSignature, toTransactionHash, toCAIP2Network } from '@partylayer/core';
|
|
2
|
+
export { AdapterNotRegisteredError, PartyLayerError as CantonConnectError, CapabilityNotSupportedError, ENABLEMENT_METRICS, ERROR_METRICS, InternalError, METRICS, OriginNotAllowedError, PartyLayerError, REGISTRY_METRICS, RegistryFetchFailedError, RegistrySchemaInvalidError, RegistryVerificationFailedError, SessionExpiredError, TRANSFER_INTENT_FIELDS, TimeoutError, TransportError, UserRejectedError, WalletNotFoundError, WalletNotInstalledError, errorMetricName, isOfficialAdapterFactory, isOfficialProviderAdapter, toTransferIntent } from '@partylayer/core';
|
|
3
3
|
import { RegistryClient } from '@partylayer/registry-client';
|
|
4
4
|
export { deriveGenericWalletName, findMatchingWallet, findMatchingWalletInfo, isCip0103Native, matchesProviderDetection } from '@partylayer/registry-client';
|
|
5
|
-
import { subscribeAnnouncedProviders, createExtensionChannelProvider, discoverProviders, createProviderBridge } from '@partylayer/provider';
|
|
5
|
+
import { subscribeAnnouncedProviders, createExtensionChannelProvider, discoverProviders, createProviderBridge, CIP0103EventBus, toProviderRpcError } from '@partylayer/provider';
|
|
6
6
|
export { CANTON_NETWORKS, CIP0103EventBus, CIP0103_EVENTS, CIP0103_MANDATORY_METHODS, CIP0103_METHODS, JSON_RPC_ERRORS, PartyLayerProvider, ProviderRpcError, RPC_ERRORS, createProviderBridge, discoverInjectedProviders, fromCAIP2Network, isCIP0103Provider, isValidCAIP2, toCAIP2Network, waitForProvider } from '@partylayer/provider';
|
|
7
7
|
export { ConsoleAdapter } from '@partylayer/adapter-console';
|
|
8
8
|
import { LoopAdapter } from '@partylayer/adapter-loop';
|
|
@@ -14,7 +14,583 @@ export { NightlyAdapter } from '@partylayer/adapter-nightly';
|
|
|
14
14
|
export { SendAdapter } from '@partylayer/adapter-send';
|
|
15
15
|
export { BronAdapter } from '@partylayer/adapter-bron';
|
|
16
16
|
|
|
17
|
-
// src/
|
|
17
|
+
// src/default-wallets.ts
|
|
18
|
+
var loaders = {
|
|
19
|
+
walley: async () => {
|
|
20
|
+
const { WalleyAdapter } = await import('@k2flabs/walley-dapp-sdk');
|
|
21
|
+
return { providerId: "walley", create: (host) => new WalleyAdapter({ host }) };
|
|
22
|
+
},
|
|
23
|
+
cauri: async () => {
|
|
24
|
+
const { cauriAdapterFactory } = await import('@lithiumdigital/cauri-dapp-sdk');
|
|
25
|
+
return cauriAdapterFactory;
|
|
26
|
+
},
|
|
27
|
+
oneswap: async (network) => {
|
|
28
|
+
const { createOneSwapProviderAdapter } = await import('@oneswap/wallet-cip0103-adapter');
|
|
29
|
+
return {
|
|
30
|
+
providerId: "oneswap",
|
|
31
|
+
create: (host) => createOneSwapProviderAdapter({
|
|
32
|
+
walletUrl: host,
|
|
33
|
+
networkId: toCAIP2Network(network).networkId
|
|
34
|
+
})
|
|
35
|
+
};
|
|
36
|
+
},
|
|
37
|
+
vala: async () => {
|
|
38
|
+
const { valaAdapterFactory } = await import('@vala-wallet/dapp-sdk');
|
|
39
|
+
return valaAdapterFactory;
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
async function loadDefaultWallet(id, config, origin) {
|
|
43
|
+
if (id === "walletconnect" && config.walletConnect?.projectId.trim()) {
|
|
44
|
+
const { WalletConnectAdapter } = await import('@partylayer/adapter-walletconnect');
|
|
45
|
+
return new WalletConnectAdapter({
|
|
46
|
+
...config.walletConnect,
|
|
47
|
+
metadata: config.walletConnect.metadata ?? {
|
|
48
|
+
name: config.app.name,
|
|
49
|
+
description: config.app.name,
|
|
50
|
+
url: origin === "unknown" ? "" : origin,
|
|
51
|
+
icons: []
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
if (id === "bron" && config.bron) {
|
|
56
|
+
const { BronAdapter: BronAdapter2 } = await import('@partylayer/adapter-bron');
|
|
57
|
+
return new BronAdapter2(config.bron);
|
|
58
|
+
}
|
|
59
|
+
return Object.prototype.hasOwnProperty.call(loaders, id) ? loaders[id](config.network) : void 0;
|
|
60
|
+
}
|
|
61
|
+
var UNSUPPORTED_METHOD = 4200;
|
|
62
|
+
var METHOD_NOT_FOUND = -32601;
|
|
63
|
+
function isUnsupportedMethod(err) {
|
|
64
|
+
const code = err?.code;
|
|
65
|
+
return code === UNSUPPORTED_METHOD || code === METHOD_NOT_FOUND;
|
|
66
|
+
}
|
|
67
|
+
function assertExecuteCorrelation(result, request) {
|
|
68
|
+
const expected = request?.commandId;
|
|
69
|
+
if (typeof expected !== "string" || !expected) return;
|
|
70
|
+
const value = result;
|
|
71
|
+
for (const actual of [value?.commandId, value?.tx?.commandId]) {
|
|
72
|
+
if (typeof actual === "string" && actual && actual !== expected) {
|
|
73
|
+
throw new TransportError("Wallet returned a different commandId; transaction outcome is unknown. Reconcile before retrying.");
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function receiptFromExecutedTx(result) {
|
|
78
|
+
const tx = result?.tx;
|
|
79
|
+
const updateId = tx?.payload?.updateId;
|
|
80
|
+
if (typeof updateId !== "string" || updateId.length === 0) return null;
|
|
81
|
+
return {
|
|
82
|
+
transactionHash: toTransactionHash(updateId),
|
|
83
|
+
submittedAt: Date.now(),
|
|
84
|
+
commandId: typeof tx?.commandId === "string" ? tx.commandId : void 0,
|
|
85
|
+
updateId,
|
|
86
|
+
...validOffset(tx?.payload?.completionOffset) ? { completionOffset: tx.payload.completionOffset } : {}
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
function normalizeReceipt(result, request) {
|
|
90
|
+
assertExecuteCorrelation(result, request);
|
|
91
|
+
const executed = receiptFromExecutedTx(result);
|
|
92
|
+
if (executed) return executed;
|
|
93
|
+
const value = result && typeof result === "object" ? result : {};
|
|
94
|
+
const timestamp = typeof value.submittedAt === "number" ? value.submittedAt : typeof value.submittedAt === "string" ? Date.parse(value.submittedAt) : NaN;
|
|
95
|
+
const tx = value.tx && typeof value.tx === "object" ? value.tx : {};
|
|
96
|
+
const commandId = typeof value.commandId === "string" ? value.commandId : typeof tx.commandId === "string" ? tx.commandId : typeof request.commandId === "string" ? request.commandId : void 0;
|
|
97
|
+
return {
|
|
98
|
+
submittedAt: Number.isFinite(timestamp) ? timestamp : Date.now(),
|
|
99
|
+
...typeof value.transactionHash === "string" && value.transactionHash.length > 0 ? { transactionHash: toTransactionHash(value.transactionHash) } : {},
|
|
100
|
+
...typeof value.updateId === "string" && value.updateId.length > 0 ? { updateId: value.updateId } : {},
|
|
101
|
+
...validOffset(value.completionOffset) ? { completionOffset: value.completionOffset } : {},
|
|
102
|
+
...commandId ? { commandId } : {}
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
function validOffset(value) {
|
|
106
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
107
|
+
}
|
|
108
|
+
function reportOnce(state, walletId, detail, logger) {
|
|
109
|
+
if (state.logged) return;
|
|
110
|
+
state.logged = true;
|
|
111
|
+
logger?.warn(
|
|
112
|
+
`[PartyLayer] ${walletId}: ${detail} Confirm ledger completion only when the receipt contains a real updateId.`
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
async function submitViaPrepareExecute(provider, params, opts) {
|
|
116
|
+
const payload = Object.prototype.hasOwnProperty.call(params, "signedTx") ? params.signedTx : params;
|
|
117
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
118
|
+
throw new TransportError("CIP-0103 submission requires a command payload object as signedTx");
|
|
119
|
+
}
|
|
120
|
+
const rpcParams = payload;
|
|
121
|
+
const { walletId, state, logger } = opts;
|
|
122
|
+
if (state.verb !== "plain") {
|
|
123
|
+
try {
|
|
124
|
+
const result2 = await provider.request({
|
|
125
|
+
method: "prepareExecuteAndWait",
|
|
126
|
+
params: rpcParams
|
|
127
|
+
});
|
|
128
|
+
state.verb = "awaited";
|
|
129
|
+
const receipt = normalizeReceipt(result2, rpcParams);
|
|
130
|
+
if (receipt.updateId) return receipt;
|
|
131
|
+
reportOnce(
|
|
132
|
+
state,
|
|
133
|
+
walletId,
|
|
134
|
+
"prepareExecuteAndWait returned no updateId.",
|
|
135
|
+
logger
|
|
136
|
+
);
|
|
137
|
+
return receipt;
|
|
138
|
+
} catch (err) {
|
|
139
|
+
if (!isUnsupportedMethod(err)) throw err;
|
|
140
|
+
state.verb = "plain";
|
|
141
|
+
reportOnce(
|
|
142
|
+
state,
|
|
143
|
+
walletId,
|
|
144
|
+
"has no prepareExecuteAndWait; using prepareExecute, which the CIP-0103 types return as null.",
|
|
145
|
+
logger
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const result = await provider.request({ method: "prepareExecute", params: rpcParams });
|
|
150
|
+
return normalizeReceipt(result, rpcParams);
|
|
151
|
+
}
|
|
152
|
+
function normalizeSignedMessage(response, session, params) {
|
|
153
|
+
const signature = typeof response === "string" ? response : response?.signature;
|
|
154
|
+
if (typeof signature !== "string" || signature.trim().length === 0) {
|
|
155
|
+
throw new TransportError("The wallet returned an invalid message signature");
|
|
156
|
+
}
|
|
157
|
+
const reportedParty = response && typeof response === "object" ? response.partyId : void 0;
|
|
158
|
+
if (reportedParty !== void 0 && reportedParty !== session.partyId) {
|
|
159
|
+
throw new TransportError("The wallet account changed while signing; reconnect before retrying");
|
|
160
|
+
}
|
|
161
|
+
const reportedMessage = response && typeof response === "object" ? response.message : void 0;
|
|
162
|
+
if (reportedMessage !== void 0 && reportedMessage !== params.message) {
|
|
163
|
+
throw new TransportError("Wallet signed an unexpected message");
|
|
164
|
+
}
|
|
165
|
+
return {
|
|
166
|
+
signature: toSignature(signature),
|
|
167
|
+
partyId: session.partyId,
|
|
168
|
+
message: params.message,
|
|
169
|
+
nonce: params.nonce,
|
|
170
|
+
domain: params.domain
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
function assertConnectionAccepted(result) {
|
|
174
|
+
if (result === false || result && typeof result === "object" && result.isConnected === false) {
|
|
175
|
+
throw new TransportError("The wallet did not establish a connection");
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
function assertPrimaryParty(account) {
|
|
179
|
+
if (typeof account?.partyId !== "string" || !account.partyId.trim()) throw new TransportError("The wallet did not return a primary party");
|
|
180
|
+
}
|
|
181
|
+
var SILENT_PROBE_TIMEOUT_MS = 1e4;
|
|
182
|
+
function disconnected() {
|
|
183
|
+
return new Error("Native wallet connection is no longer active");
|
|
184
|
+
}
|
|
185
|
+
function teardown(source) {
|
|
186
|
+
try {
|
|
187
|
+
source?.teardown?.();
|
|
188
|
+
} catch {
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
function abortable(promise, signal) {
|
|
192
|
+
return new Promise((resolve, reject) => {
|
|
193
|
+
const abort = () => reject(disconnected());
|
|
194
|
+
if (signal.aborted) {
|
|
195
|
+
reject(disconnected());
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
199
|
+
promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
async function readIdentity(provider, registration, signal) {
|
|
203
|
+
const account = await abortable(
|
|
204
|
+
provider.request({ method: "getPrimaryAccount" }),
|
|
205
|
+
signal
|
|
206
|
+
);
|
|
207
|
+
assertPrimaryParty(account);
|
|
208
|
+
let status;
|
|
209
|
+
try {
|
|
210
|
+
status = await abortable(provider.request({ method: "status" }), signal);
|
|
211
|
+
} catch (error) {
|
|
212
|
+
if (signal.aborted) throw error;
|
|
213
|
+
}
|
|
214
|
+
if (status?.isConnected === false || status?.connection?.isConnected === false)
|
|
215
|
+
throw disconnected();
|
|
216
|
+
const network = [status?.network?.networkId, account.networkId, registration.network].find(
|
|
217
|
+
(value) => typeof value === "string" && isRecognizedNetwork(value)
|
|
218
|
+
) ?? registration.network;
|
|
219
|
+
if (registration.expected && (account.partyId !== registration.expected.partyId || detectNetworkMismatch(registration.expected.network, network)))
|
|
220
|
+
throw disconnected();
|
|
221
|
+
if (signal.aborted) throw disconnected();
|
|
222
|
+
return { account, network, status };
|
|
223
|
+
}
|
|
224
|
+
var NativeConnectionOwner = class {
|
|
225
|
+
constructor(changed = () => {
|
|
226
|
+
}) {
|
|
227
|
+
this.changed = changed;
|
|
228
|
+
}
|
|
229
|
+
client = null;
|
|
230
|
+
initialization = null;
|
|
231
|
+
registrations = /* @__PURE__ */ new Map();
|
|
232
|
+
operation = null;
|
|
233
|
+
pending = null;
|
|
234
|
+
closing = null;
|
|
235
|
+
projection = null;
|
|
236
|
+
unsubscribers = [];
|
|
237
|
+
disposed = false;
|
|
238
|
+
refreshRevision = 0;
|
|
239
|
+
identityRefreshing = false;
|
|
240
|
+
probes = /* @__PURE__ */ new Set();
|
|
241
|
+
get busy() {
|
|
242
|
+
return this.operation !== null || this.closing !== null;
|
|
243
|
+
}
|
|
244
|
+
assertAvailable() {
|
|
245
|
+
if (this.disposed) throw disconnected();
|
|
246
|
+
if (this.busy) throw new Error("A native wallet operation is already in progress");
|
|
247
|
+
}
|
|
248
|
+
/** Run during picker preparation, never between a click and provider.connect. */
|
|
249
|
+
async prepare(id, source, network) {
|
|
250
|
+
if (this.disposed) throw disconnected();
|
|
251
|
+
this.registrations.set(id, { id, source, network });
|
|
252
|
+
if (!this.initialization) {
|
|
253
|
+
this.initialization = (async () => {
|
|
254
|
+
const { DiscoveryClient } = await import('@canton-network/core-wallet-discovery');
|
|
255
|
+
const client = await DiscoveryClient.create({ adapters: [] });
|
|
256
|
+
if (this.disposed) {
|
|
257
|
+
client.destroy();
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
this.client = client;
|
|
261
|
+
})();
|
|
262
|
+
}
|
|
263
|
+
await this.initialization;
|
|
264
|
+
if (this.disposed || !this.client) throw disconnected();
|
|
265
|
+
for (const registration of this.registrations.values())
|
|
266
|
+
this.client.registerAdapter(this.wrap(registration));
|
|
267
|
+
}
|
|
268
|
+
wrap(registration) {
|
|
269
|
+
const source = registration.source;
|
|
270
|
+
return {
|
|
271
|
+
providerId: registration.id,
|
|
272
|
+
name: source.name,
|
|
273
|
+
type: source.type === "desktop" || source.type === "mobile" || source.type === "remote" ? source.type : "browser",
|
|
274
|
+
icon: source.icon,
|
|
275
|
+
getInfo: () => ({
|
|
276
|
+
providerId: registration.id,
|
|
277
|
+
name: source.name,
|
|
278
|
+
type: "browser",
|
|
279
|
+
icon: source.icon
|
|
280
|
+
}),
|
|
281
|
+
detect: () => source.detect(),
|
|
282
|
+
provider: () => this.guard(source.provider(), registration),
|
|
283
|
+
teardown: () => teardown(source),
|
|
284
|
+
restore: async () => {
|
|
285
|
+
const operation = this.operation;
|
|
286
|
+
if (!operation) throw disconnected();
|
|
287
|
+
try {
|
|
288
|
+
const raw = source.restore ? await abortable(source.restore(), operation.abort.signal) : source.provider();
|
|
289
|
+
if (!raw) return null;
|
|
290
|
+
const provider = raw;
|
|
291
|
+
operation.identity = await readIdentity(provider, registration, operation.abort.signal);
|
|
292
|
+
return this.guard(provider, registration);
|
|
293
|
+
} catch (error) {
|
|
294
|
+
teardown(source);
|
|
295
|
+
throw error;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
guard(raw, registration) {
|
|
301
|
+
const provider = {
|
|
302
|
+
request: async (args) => {
|
|
303
|
+
if (this.disposed) throw disconnected();
|
|
304
|
+
if (args.method !== "connect") {
|
|
305
|
+
if (this.client?.getActiveSession()?.provider !== provider) throw disconnected();
|
|
306
|
+
if (!this.projection && args.method !== "disconnect") throw disconnected();
|
|
307
|
+
if (this.identityRefreshing && ![
|
|
308
|
+
"status",
|
|
309
|
+
"getPrimaryAccount",
|
|
310
|
+
"listAccounts",
|
|
311
|
+
"getActiveNetwork",
|
|
312
|
+
"isConnected"
|
|
313
|
+
].includes(args.method)) {
|
|
314
|
+
throw new Error("Native wallet identity is being refreshed");
|
|
315
|
+
}
|
|
316
|
+
const result = await (args.method === "disconnect" && this.operation ? abortable(raw.request(args), this.operation.abort.signal) : raw.request(args));
|
|
317
|
+
if (args.method === "status") {
|
|
318
|
+
const status = result;
|
|
319
|
+
if (status?.isConnected === false || status?.connection?.isConnected === false) {
|
|
320
|
+
this.invalidate(registration.id);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
return result;
|
|
324
|
+
}
|
|
325
|
+
const operation = this.operation;
|
|
326
|
+
if (!operation || operation.abort.signal.aborted) throw disconnected();
|
|
327
|
+
const response = await abortable(raw.request(args), operation.abort.signal);
|
|
328
|
+
assertConnectionAccepted(response);
|
|
329
|
+
operation.identity = await readIdentity(raw, registration, operation.abort.signal);
|
|
330
|
+
return response;
|
|
331
|
+
},
|
|
332
|
+
on: (event, listener) => {
|
|
333
|
+
raw.on(event, listener);
|
|
334
|
+
return provider;
|
|
335
|
+
},
|
|
336
|
+
emit: (event, ...args) => raw.emit(event, ...args),
|
|
337
|
+
removeListener: (event, listener) => {
|
|
338
|
+
raw.removeListener(event, listener);
|
|
339
|
+
return provider;
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
return provider;
|
|
343
|
+
}
|
|
344
|
+
/** No await precedes the official client's connect call. */
|
|
345
|
+
connect(id, signal) {
|
|
346
|
+
this.assertAvailable();
|
|
347
|
+
if (!this.client || !this.registrations.has(id))
|
|
348
|
+
return Promise.reject(new Error("Native wallet was not prepared"));
|
|
349
|
+
const operation = { abort: new AbortController(), id };
|
|
350
|
+
this.operation = operation;
|
|
351
|
+
this.detach();
|
|
352
|
+
const previous = this.client.getActiveSession();
|
|
353
|
+
teardown(previous?.adapter);
|
|
354
|
+
const previousId = this.projection?.id;
|
|
355
|
+
this.projection = null;
|
|
356
|
+
if (previousId) this.changed(previousId, null);
|
|
357
|
+
const abort = () => operation.abort.abort();
|
|
358
|
+
if (signal?.aborted) abort();
|
|
359
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
360
|
+
const task = (async () => {
|
|
361
|
+
try {
|
|
362
|
+
await this.client.connect(id);
|
|
363
|
+
if (operation.abort.signal.aborted || this.disposed || !operation.identity)
|
|
364
|
+
throw disconnected();
|
|
365
|
+
this.projection = { id, identity: operation.identity };
|
|
366
|
+
this.attach(id);
|
|
367
|
+
return operation.identity;
|
|
368
|
+
} catch (error) {
|
|
369
|
+
this.client?.destroy();
|
|
370
|
+
this.client = null;
|
|
371
|
+
this.initialization = null;
|
|
372
|
+
teardown(this.registrations.get(id)?.source);
|
|
373
|
+
throw error;
|
|
374
|
+
} finally {
|
|
375
|
+
signal?.removeEventListener("abort", abort);
|
|
376
|
+
if (this.operation === operation) this.operation = null;
|
|
377
|
+
}
|
|
378
|
+
})();
|
|
379
|
+
this.pending = task;
|
|
380
|
+
void task.then(
|
|
381
|
+
() => {
|
|
382
|
+
if (this.pending === task) this.pending = null;
|
|
383
|
+
},
|
|
384
|
+
() => {
|
|
385
|
+
if (this.pending === task) this.pending = null;
|
|
386
|
+
}
|
|
387
|
+
);
|
|
388
|
+
return task;
|
|
389
|
+
}
|
|
390
|
+
async restore(expected) {
|
|
391
|
+
if (!this.client || this.projection || this.busy || this.disposed) return this.getSession();
|
|
392
|
+
const registration = expected && this.registrations.get(expected.id);
|
|
393
|
+
if (registration) registration.expected = expected;
|
|
394
|
+
const operation = { abort: new AbortController() };
|
|
395
|
+
this.operation = operation;
|
|
396
|
+
const timeout = setTimeout(() => operation.abort.abort(), SILENT_PROBE_TIMEOUT_MS);
|
|
397
|
+
const task = (async () => {
|
|
398
|
+
try {
|
|
399
|
+
await this.client.restorePersistedSessionIfNeeded();
|
|
400
|
+
const active = this.client?.getActiveSession();
|
|
401
|
+
if (!active || !operation.identity || operation.abort.signal.aborted || this.disposed)
|
|
402
|
+
return null;
|
|
403
|
+
if (expected && active.providerId !== expected.id) {
|
|
404
|
+
teardown(active.adapter);
|
|
405
|
+
this.client.destroy();
|
|
406
|
+
this.client = null;
|
|
407
|
+
this.initialization = null;
|
|
408
|
+
return null;
|
|
409
|
+
}
|
|
410
|
+
const id = String(active.providerId);
|
|
411
|
+
this.projection = { id, identity: operation.identity };
|
|
412
|
+
this.attach(id);
|
|
413
|
+
return this.getSession();
|
|
414
|
+
} finally {
|
|
415
|
+
clearTimeout(timeout);
|
|
416
|
+
if (registration) delete registration.expected;
|
|
417
|
+
if (this.operation === operation) this.operation = null;
|
|
418
|
+
}
|
|
419
|
+
})();
|
|
420
|
+
this.pending = task;
|
|
421
|
+
try {
|
|
422
|
+
return await task;
|
|
423
|
+
} finally {
|
|
424
|
+
if (this.pending === task) this.pending = null;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
getSession() {
|
|
428
|
+
if (this.disposed || !this.client?.getActiveSession() || !this.projection) return null;
|
|
429
|
+
return this.projection;
|
|
430
|
+
}
|
|
431
|
+
getProvider(id) {
|
|
432
|
+
if (!this.getSession() || id && this.projection?.id !== id) throw disconnected();
|
|
433
|
+
return this.client.getProvider();
|
|
434
|
+
}
|
|
435
|
+
/** A bare signature must not be attributed to an old, eventless primary party. */
|
|
436
|
+
async validateIdentity(id, partyId, network) {
|
|
437
|
+
const provider = this.getProvider(id);
|
|
438
|
+
const revision = ++this.refreshRevision;
|
|
439
|
+
this.identityRefreshing = true;
|
|
440
|
+
let verified = false;
|
|
441
|
+
try {
|
|
442
|
+
const identity = await this.probe(provider, this.registrations.get(id));
|
|
443
|
+
if (revision !== this.refreshRevision || this.getProvider(id) !== provider)
|
|
444
|
+
throw disconnected();
|
|
445
|
+
verified = true;
|
|
446
|
+
this.projection = { id, identity };
|
|
447
|
+
if (identity.account.partyId !== partyId || detectNetworkMismatch(network, identity.network)) {
|
|
448
|
+
this.changed(id, identity);
|
|
449
|
+
throw new Error("Wallet identity changed during message signing");
|
|
450
|
+
}
|
|
451
|
+
} catch (error) {
|
|
452
|
+
if (!verified && revision === this.refreshRevision) this.invalidate(id);
|
|
453
|
+
throw error;
|
|
454
|
+
} finally {
|
|
455
|
+
if (revision === this.refreshRevision) this.identityRefreshing = false;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
async probe(provider, registration) {
|
|
459
|
+
const abort = new AbortController();
|
|
460
|
+
this.probes.add(abort);
|
|
461
|
+
const timeout = setTimeout(() => abort.abort(), SILENT_PROBE_TIMEOUT_MS);
|
|
462
|
+
try {
|
|
463
|
+
return await readIdentity(provider, registration, abort.signal);
|
|
464
|
+
} finally {
|
|
465
|
+
clearTimeout(timeout);
|
|
466
|
+
this.probes.delete(abort);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
detach() {
|
|
470
|
+
++this.refreshRevision;
|
|
471
|
+
this.identityRefreshing = false;
|
|
472
|
+
for (const probe of this.probes) probe.abort();
|
|
473
|
+
this.probes.clear();
|
|
474
|
+
this.unsubscribers.splice(0).forEach((unsubscribe) => {
|
|
475
|
+
try {
|
|
476
|
+
unsubscribe();
|
|
477
|
+
} catch {
|
|
478
|
+
}
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
attach(id) {
|
|
482
|
+
const provider = this.getProvider(id);
|
|
483
|
+
const update = (payload) => {
|
|
484
|
+
const status = payload;
|
|
485
|
+
if (status?.connection?.isConnected === false || status?.isConnected === false || Array.isArray(payload) && payload.length === 0) {
|
|
486
|
+
this.invalidate(id);
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
const revision = ++this.refreshRevision;
|
|
490
|
+
this.identityRefreshing = true;
|
|
491
|
+
const registration = this.registrations.get(id);
|
|
492
|
+
void this.probe(provider, registration).then(
|
|
493
|
+
(identity) => {
|
|
494
|
+
if (revision !== this.refreshRevision || this.projection?.id !== id || this.disposed)
|
|
495
|
+
return;
|
|
496
|
+
this.identityRefreshing = false;
|
|
497
|
+
this.projection = { id, identity };
|
|
498
|
+
this.changed(id, identity);
|
|
499
|
+
},
|
|
500
|
+
() => {
|
|
501
|
+
if (revision === this.refreshRevision) this.invalidate(id);
|
|
502
|
+
}
|
|
503
|
+
);
|
|
504
|
+
};
|
|
505
|
+
for (const event of ["accountsChanged", "statusChanged"]) {
|
|
506
|
+
provider.on(event, update);
|
|
507
|
+
this.unsubscribers.push(() => provider.removeListener(event, update));
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
invalidate(id) {
|
|
511
|
+
if (this.projection?.id !== id) return;
|
|
512
|
+
this.detach();
|
|
513
|
+
this.projection = null;
|
|
514
|
+
teardown(this.client?.getActiveSession()?.adapter);
|
|
515
|
+
this.client?.destroy();
|
|
516
|
+
this.client = null;
|
|
517
|
+
this.initialization = null;
|
|
518
|
+
this.changed(id, null);
|
|
519
|
+
}
|
|
520
|
+
/** Local transport cleanup when switching to a proprietary integration. */
|
|
521
|
+
release() {
|
|
522
|
+
this.assertAvailable();
|
|
523
|
+
const id = this.projection?.id;
|
|
524
|
+
this.detach();
|
|
525
|
+
this.projection = null;
|
|
526
|
+
teardown(this.client?.getActiveSession()?.adapter);
|
|
527
|
+
this.client?.destroy();
|
|
528
|
+
this.client = null;
|
|
529
|
+
this.initialization = null;
|
|
530
|
+
if (id) this.changed(id, null);
|
|
531
|
+
}
|
|
532
|
+
disconnect() {
|
|
533
|
+
if (this.closing) return this.closing;
|
|
534
|
+
this.operation?.abort.abort();
|
|
535
|
+
const task = (async () => {
|
|
536
|
+
await this.pending?.catch(() => {
|
|
537
|
+
});
|
|
538
|
+
this.detach();
|
|
539
|
+
const id = this.projection?.id;
|
|
540
|
+
this.projection = null;
|
|
541
|
+
const operation = { abort: new AbortController() };
|
|
542
|
+
this.operation = operation;
|
|
543
|
+
const timeout = setTimeout(() => operation.abort.abort(), SILENT_PROBE_TIMEOUT_MS);
|
|
544
|
+
try {
|
|
545
|
+
await this.client?.disconnect();
|
|
546
|
+
} finally {
|
|
547
|
+
clearTimeout(timeout);
|
|
548
|
+
if (this.client?.getActiveSession()) {
|
|
549
|
+
this.client.destroy();
|
|
550
|
+
this.client = null;
|
|
551
|
+
this.initialization = null;
|
|
552
|
+
}
|
|
553
|
+
this.operation = null;
|
|
554
|
+
if (id) this.changed(id, null);
|
|
555
|
+
}
|
|
556
|
+
})();
|
|
557
|
+
this.closing = task;
|
|
558
|
+
void task.then(
|
|
559
|
+
() => {
|
|
560
|
+
if (this.closing === task) this.closing = null;
|
|
561
|
+
},
|
|
562
|
+
() => {
|
|
563
|
+
if (this.closing === task) this.closing = null;
|
|
564
|
+
}
|
|
565
|
+
);
|
|
566
|
+
return task;
|
|
567
|
+
}
|
|
568
|
+
destroy() {
|
|
569
|
+
if (this.disposed) return;
|
|
570
|
+
this.disposed = true;
|
|
571
|
+
this.operation?.abort.abort();
|
|
572
|
+
this.detach();
|
|
573
|
+
this.projection = null;
|
|
574
|
+
teardown(this.client?.getActiveSession()?.adapter);
|
|
575
|
+
if (!this.client?.getActiveSession() && this.operation?.id)
|
|
576
|
+
teardown(this.registrations.get(this.operation.id)?.source);
|
|
577
|
+
this.client?.destroy();
|
|
578
|
+
this.client = null;
|
|
579
|
+
}
|
|
580
|
+
};
|
|
581
|
+
var nativeOwnerBindings = /* @__PURE__ */ new WeakMap();
|
|
582
|
+
var nativeAdapterCopies = /* @__PURE__ */ new WeakMap();
|
|
583
|
+
|
|
584
|
+
// src/announce-adapter.ts
|
|
585
|
+
function getAnnounceCapabilities(config = {}) {
|
|
586
|
+
const caps = ["connect"];
|
|
587
|
+
if (config.signMessage !== false) caps.push("signMessage");
|
|
588
|
+
caps.push("submitTransaction");
|
|
589
|
+
if (config.restore) caps.push("restore");
|
|
590
|
+
if (config.ledgerApi) caps.push("ledgerApi");
|
|
591
|
+
if (config.events) caps.push("events");
|
|
592
|
+
return caps;
|
|
593
|
+
}
|
|
18
594
|
var ANNOUNCED_WALLET_ID_PREFIX = "browser:ext:";
|
|
19
595
|
function announcedWalletId(announceId) {
|
|
20
596
|
return toWalletId(`${ANNOUNCED_WALLET_ID_PREFIX}${announceId}`);
|
|
@@ -38,16 +614,21 @@ function toBase64Message(message) {
|
|
|
38
614
|
for (const b of bytes) binary += String.fromCharCode(b);
|
|
39
615
|
return btoa(binary);
|
|
40
616
|
}
|
|
41
|
-
var GenericAnnounceAdapter = class {
|
|
617
|
+
var GenericAnnounceAdapter = class _GenericAnnounceAdapter {
|
|
42
618
|
walletId;
|
|
43
619
|
name;
|
|
44
620
|
/** Icon surfaced to the picker (announce detail). */
|
|
45
621
|
icon;
|
|
46
|
-
|
|
622
|
+
rawProvider;
|
|
47
623
|
metadataEnabled;
|
|
48
624
|
staticMetadata;
|
|
49
625
|
mapError;
|
|
50
626
|
signMessageBase64;
|
|
627
|
+
/**
|
|
628
|
+
* Which execute verb this wallet turned out to support. Resolved on the first
|
|
629
|
+
* submit and reused, so the wallet is asked at most once.
|
|
630
|
+
*/
|
|
631
|
+
executeVerb = {};
|
|
51
632
|
// Optional WalletAdapter surface — assigned in the ctor ONLY when configured,
|
|
52
633
|
// so `getCapabilities()` and `'x' in adapter` feature-detection stay honest.
|
|
53
634
|
restore;
|
|
@@ -57,10 +638,15 @@ var GenericAnnounceAdapter = class {
|
|
|
57
638
|
// declares support, so a wallet that cannot sign is not advertised as able to.
|
|
58
639
|
signMessage;
|
|
59
640
|
constructor(args) {
|
|
641
|
+
const configuration = { ...args, config: args.config && {
|
|
642
|
+
...args.config,
|
|
643
|
+
staticMetadata: args.config.staticMetadata && { ...args.config.staticMetadata }
|
|
644
|
+
} };
|
|
645
|
+
nativeAdapterCopies.set(this, () => new _GenericAnnounceAdapter(configuration));
|
|
60
646
|
this.walletId = args.walletId ?? announcedWalletId(args.announceId);
|
|
61
647
|
this.name = args.name && args.name.length > 0 ? args.name : `Canton Wallet (${args.announceId.slice(0, 6)}\u2026)`;
|
|
62
648
|
this.icon = args.icon;
|
|
63
|
-
this.
|
|
649
|
+
this.rawProvider = args.provider;
|
|
64
650
|
const config = args.config;
|
|
65
651
|
this.metadataEnabled = config?.metadata === true;
|
|
66
652
|
this.staticMetadata = config?.staticMetadata;
|
|
@@ -71,6 +657,22 @@ var GenericAnnounceAdapter = class {
|
|
|
71
657
|
if (config?.ledgerApi) this.ledgerApi = this.makeLedgerApi();
|
|
72
658
|
if (config?.signMessage !== false) this.signMessage = this.signMessageImpl.bind(this);
|
|
73
659
|
}
|
|
660
|
+
get provider() {
|
|
661
|
+
return nativeOwnerBindings.get(this)?.getProvider(String(this.walletId)) ?? this.rawProvider;
|
|
662
|
+
}
|
|
663
|
+
/** @internal Register the discovered transport with the one official owner. */
|
|
664
|
+
async prepareNativeConnection(network) {
|
|
665
|
+
const owner = nativeOwnerBindings.get(this);
|
|
666
|
+
if (!owner) return;
|
|
667
|
+
await owner.prepare(String(this.walletId), {
|
|
668
|
+
providerId: String(this.walletId),
|
|
669
|
+
name: this.name,
|
|
670
|
+
type: "browser",
|
|
671
|
+
icon: this.icon,
|
|
672
|
+
provider: () => this.rawProvider,
|
|
673
|
+
detect: async () => true
|
|
674
|
+
}, network);
|
|
675
|
+
}
|
|
74
676
|
/**
|
|
75
677
|
* Capabilities derived from actual presence: connect and submitTransaction are
|
|
76
678
|
* always present; signMessage, restore, ledgerApi, and events are each included
|
|
@@ -78,30 +680,40 @@ var GenericAnnounceAdapter = class {
|
|
|
78
680
|
* beyond what the adapter can do.
|
|
79
681
|
*/
|
|
80
682
|
getCapabilities() {
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
return caps;
|
|
683
|
+
return getAnnounceCapabilities({
|
|
684
|
+
signMessage: !!this.signMessage,
|
|
685
|
+
restore: !!this.restore,
|
|
686
|
+
ledgerApi: !!this.ledgerApi,
|
|
687
|
+
events: !!this.on
|
|
688
|
+
});
|
|
88
689
|
}
|
|
89
690
|
/**
|
|
90
691
|
* The adapter is only ever constructed for a wallet that just announced, so
|
|
91
692
|
* its presence is established by the announce handshake itself.
|
|
92
693
|
*/
|
|
93
694
|
async detectInstalled() {
|
|
94
|
-
return {
|
|
695
|
+
return {
|
|
696
|
+
installed: true,
|
|
697
|
+
// Presence by CONSTRUCTION: this adapter only exists because an announce
|
|
698
|
+
// arrived on the wallet's own target channel. There is no probe to be
|
|
699
|
+
// wrong about, which is why this is the one path that cannot report a
|
|
700
|
+
// wallet that is not there.
|
|
701
|
+
availability: { kind: "installed" },
|
|
702
|
+
reason: "Announced via canton:announceProvider"
|
|
703
|
+
};
|
|
95
704
|
}
|
|
96
|
-
async connect(ctx) {
|
|
705
|
+
async connect(ctx, options) {
|
|
97
706
|
return this.guarded(async () => {
|
|
98
|
-
|
|
99
|
-
const
|
|
707
|
+
const owner = nativeOwnerBindings.get(this);
|
|
708
|
+
const native = owner ? await owner.connect(String(this.walletId), options?.signal) : void 0;
|
|
709
|
+
if (!owner) assertConnectionAccepted(await this.provider.request({ method: "connect" }));
|
|
710
|
+
const account = native?.account ?? await this.provider.request({
|
|
100
711
|
method: "getPrimaryAccount"
|
|
101
712
|
});
|
|
713
|
+
assertPrimaryParty(account);
|
|
102
714
|
let status;
|
|
103
715
|
try {
|
|
104
|
-
status = await this.provider.request({ method: "status" });
|
|
716
|
+
status = native?.status ?? await this.provider.request({ method: "status" });
|
|
105
717
|
} catch {
|
|
106
718
|
}
|
|
107
719
|
const reportedNetwork = status?.network?.networkId;
|
|
@@ -121,6 +733,11 @@ var GenericAnnounceAdapter = class {
|
|
|
121
733
|
});
|
|
122
734
|
}
|
|
123
735
|
async disconnect() {
|
|
736
|
+
const owner = nativeOwnerBindings.get(this);
|
|
737
|
+
if (owner) {
|
|
738
|
+
await owner.disconnect();
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
124
741
|
try {
|
|
125
742
|
await this.provider.request({ method: "disconnect" });
|
|
126
743
|
} catch {
|
|
@@ -133,21 +750,15 @@ var GenericAnnounceAdapter = class {
|
|
|
133
750
|
return this.guarded(async () => {
|
|
134
751
|
const rpcParams = this.signMessageBase64 ? { message: toBase64Message(params.message) } : { message: params.message };
|
|
135
752
|
const res = await this.provider.request({ method: "signMessage", params: rpcParams });
|
|
136
|
-
|
|
137
|
-
return {
|
|
138
|
-
signature: toSignature(String(sig)),
|
|
139
|
-
partyId: session.partyId,
|
|
140
|
-
message: params.message,
|
|
141
|
-
nonce: params.nonce,
|
|
142
|
-
domain: params.domain
|
|
143
|
-
};
|
|
753
|
+
return normalizeSignedMessage(res, session, params);
|
|
144
754
|
});
|
|
145
755
|
}
|
|
146
|
-
async submitTransaction(
|
|
756
|
+
async submitTransaction(ctx, _session, params) {
|
|
147
757
|
return this.guarded(
|
|
148
|
-
() => this.provider
|
|
149
|
-
|
|
150
|
-
|
|
758
|
+
() => submitViaPrepareExecute(this.provider, params, {
|
|
759
|
+
walletId: String(this.walletId),
|
|
760
|
+
state: this.executeVerb,
|
|
761
|
+
logger: ctx.logger
|
|
151
762
|
})
|
|
152
763
|
);
|
|
153
764
|
}
|
|
@@ -174,6 +785,12 @@ var GenericAnnounceAdapter = class {
|
|
|
174
785
|
/** restore: silent status()/getPrimaryAccount() probe + expiry + party-match. */
|
|
175
786
|
makeRestore() {
|
|
176
787
|
return (_ctx, persisted) => this.guarded(async () => {
|
|
788
|
+
const owner = nativeOwnerBindings.get(this);
|
|
789
|
+
if (owner) {
|
|
790
|
+
await this.prepareNativeConnection(_ctx.network);
|
|
791
|
+
const restored = await owner.restore({ id: String(this.walletId), partyId: persisted.partyId, network: persisted.network });
|
|
792
|
+
return restored?.id === String(this.walletId) ? { ...persisted, capabilitiesSnapshot: this.getCapabilities() } : null;
|
|
793
|
+
}
|
|
177
794
|
if (persisted.expiresAt && Date.now() >= persisted.expiresAt) return null;
|
|
178
795
|
let status;
|
|
179
796
|
try {
|
|
@@ -186,6 +803,10 @@ var GenericAnnounceAdapter = class {
|
|
|
186
803
|
method: "getPrimaryAccount"
|
|
187
804
|
});
|
|
188
805
|
if (account.partyId !== persisted.partyId) return null;
|
|
806
|
+
const network = [status?.network?.networkId, account.networkId].find(
|
|
807
|
+
(value) => typeof value === "string" && isRecognizedNetwork(value)
|
|
808
|
+
);
|
|
809
|
+
if (network && detectNetworkMismatch(persisted.network, network)) return null;
|
|
189
810
|
return {
|
|
190
811
|
...persisted,
|
|
191
812
|
walletId: this.walletId,
|
|
@@ -244,7 +865,14 @@ function buildMetadata(status, account) {
|
|
|
244
865
|
put("userId", status?.session?.userId);
|
|
245
866
|
return meta;
|
|
246
867
|
}
|
|
247
|
-
|
|
868
|
+
function getDiscoveryCapabilities(declared) {
|
|
869
|
+
const capabilities = ["connect", "disconnect"];
|
|
870
|
+
if (declared?.signMessage !== false) capabilities.push("signMessage");
|
|
871
|
+
if (declared?.submitTransaction !== false) capabilities.push("submitTransaction");
|
|
872
|
+
if (declared?.ledgerApi) capabilities.push("ledgerApi");
|
|
873
|
+
return capabilities;
|
|
874
|
+
}
|
|
875
|
+
var GenericDiscoveryAdapter = class _GenericDiscoveryAdapter {
|
|
248
876
|
walletId;
|
|
249
877
|
name;
|
|
250
878
|
icon;
|
|
@@ -260,7 +888,33 @@ var GenericDiscoveryAdapter = class {
|
|
|
260
888
|
networkHosts;
|
|
261
889
|
/** Lazily resolved from `official.provider()` — NOT at construction (SSR-safe). */
|
|
262
890
|
providerInstance = null;
|
|
891
|
+
/**
|
|
892
|
+
* Which execute verb this wallet turned out to support. Resolved on the first
|
|
893
|
+
* submit and reused, so the wallet is asked at most once.
|
|
894
|
+
*/
|
|
895
|
+
executeVerb = {};
|
|
896
|
+
capabilities;
|
|
897
|
+
ledgerApi;
|
|
263
898
|
constructor(args) {
|
|
899
|
+
const configuration = { ...args, capabilities: args.capabilities && { ...args.capabilities } };
|
|
900
|
+
nativeAdapterCopies.set(this, () => new _GenericDiscoveryAdapter({
|
|
901
|
+
...configuration,
|
|
902
|
+
networkHosts: { ...this.networkHosts }
|
|
903
|
+
}));
|
|
904
|
+
this.capabilities = getDiscoveryCapabilities(args.capabilities);
|
|
905
|
+
if (args.capabilities?.ledgerApi) {
|
|
906
|
+
this.ledgerApi = async (_ctx, _session, params) => {
|
|
907
|
+
const result = await this.provider.request({
|
|
908
|
+
method: "ledgerApi",
|
|
909
|
+
params: {
|
|
910
|
+
requestMethod: normalizeLedgerMethodLower(params.requestMethod),
|
|
911
|
+
resource: params.resource,
|
|
912
|
+
body: ledgerApiBodyToObject(params.body)
|
|
913
|
+
}
|
|
914
|
+
});
|
|
915
|
+
return { response: typeof result?.response === "string" ? result.response : JSON.stringify(result ?? null) };
|
|
916
|
+
};
|
|
917
|
+
}
|
|
264
918
|
if (args.official) {
|
|
265
919
|
this.official = args.official;
|
|
266
920
|
this.factory = null;
|
|
@@ -313,11 +967,20 @@ var GenericDiscoveryAdapter = class {
|
|
|
313
967
|
}
|
|
314
968
|
this.official = this.factory.create(host);
|
|
315
969
|
}
|
|
970
|
+
/** @internal Prepare the official owner before a popup-opening click. */
|
|
971
|
+
async prepareNativeConnection(network) {
|
|
972
|
+
const owner = nativeOwnerBindings.get(this);
|
|
973
|
+
if (!owner) return;
|
|
974
|
+
this.resolveOfficial(network);
|
|
975
|
+
await owner.prepare(String(this.walletId), this.official, network);
|
|
976
|
+
}
|
|
316
977
|
/** Lazily obtain (and cache) the official provider — deferred off the init/SSR path.
|
|
317
978
|
* `official.provider()` is typed `OfficialProvider` (loose `request` so real
|
|
318
979
|
* official adapters are assignable); it is call-compatible with CIP0103Provider
|
|
319
980
|
* (the bridge only ever calls `request({ method, params })`). */
|
|
320
981
|
get provider() {
|
|
982
|
+
const owner = nativeOwnerBindings.get(this);
|
|
983
|
+
if (owner) return owner.getProvider(String(this.walletId));
|
|
321
984
|
if (this.providerInstance === null) {
|
|
322
985
|
if (!this.official) {
|
|
323
986
|
throw new Error(
|
|
@@ -328,37 +991,55 @@ var GenericDiscoveryAdapter = class {
|
|
|
328
991
|
}
|
|
329
992
|
return this.providerInstance;
|
|
330
993
|
}
|
|
331
|
-
/**
|
|
332
|
-
* Baseline CIP-0103 capabilities. NEVER includes `'events'`: popup/remote
|
|
333
|
-
* wallets expose the event surface but do not emit (truthfulness doctrine).
|
|
334
|
-
*/
|
|
994
|
+
/** Implemented, registry-declared capabilities; popup event listeners are never claimed. */
|
|
335
995
|
getCapabilities() {
|
|
336
|
-
return [
|
|
996
|
+
return [...this.capabilities];
|
|
337
997
|
}
|
|
338
|
-
/**
|
|
998
|
+
/**
|
|
999
|
+
* THE SINGLE PLACE THE discovery-adapter RULE IS APPLIED.
|
|
1000
|
+
*
|
|
1001
|
+
* **A `discovery-adapter` transport implies there is no local install.** Every
|
|
1002
|
+
* wallet on that transport is a hosted popup or remote gateway reached with
|
|
1003
|
+
* `window.open` — Walley, Cauri and OneSwap today. There is no extension, no
|
|
1004
|
+
* injected global, nothing on the machine to probe. The honest answer is
|
|
1005
|
+
* `no-local-install`, and it follows from the registry entry alone.
|
|
1006
|
+
*
|
|
1007
|
+
* SO THE VENDOR'S `detect()` IS NOT CALLED, and reinstating that call would be
|
|
1008
|
+
* a regression however much it looks like rigour. Read from their shipped
|
|
1009
|
+
* source, all three are constants:
|
|
1010
|
+
*
|
|
1011
|
+
* walley: typeof window < "u" && typeof window.open == "function"
|
|
1012
|
+
* cauri: Promise.resolve(true)
|
|
1013
|
+
* oneswap: typeof window !== 'undefined'
|
|
1014
|
+
*
|
|
1015
|
+
* Each returns true in any browser. Awaiting them bought a value carrying no
|
|
1016
|
+
* information, at the cost of an async hop on the picker's render path and a
|
|
1017
|
+
* dependency on three third parties independently choosing to answer
|
|
1018
|
+
* honestly. The registry already knows, it is signed, and it cannot drift.
|
|
1019
|
+
*
|
|
1020
|
+
* `installed: false` is deliberate and is NOT "not available": there is no
|
|
1021
|
+
* local install, so the only truthful value for a field that asks about one
|
|
1022
|
+
* is false. A picker must read `availability`, which says why.
|
|
1023
|
+
*/
|
|
339
1024
|
async detectInstalled() {
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
return {
|
|
346
|
-
installed,
|
|
347
|
-
reason: installed ? void 0 : "Wallet reported not available"
|
|
348
|
-
};
|
|
349
|
-
} catch {
|
|
350
|
-
return { installed: false, reason: "Detection failed" };
|
|
351
|
-
}
|
|
1025
|
+
return {
|
|
1026
|
+
installed: false,
|
|
1027
|
+
availability: { kind: "no-local-install" },
|
|
1028
|
+
reason: "Hosted popup wallet \u2014 opens in a window; nothing is installed locally"
|
|
1029
|
+
};
|
|
352
1030
|
}
|
|
353
|
-
async connect(ctx) {
|
|
1031
|
+
async connect(ctx, options) {
|
|
354
1032
|
this.resolveOfficial(ctx.network);
|
|
355
|
-
|
|
356
|
-
const
|
|
1033
|
+
const owner = nativeOwnerBindings.get(this);
|
|
1034
|
+
const native = owner ? await owner.connect(String(this.walletId), options?.signal) : void 0;
|
|
1035
|
+
if (!owner) assertConnectionAccepted(await this.provider.request({ method: "connect" }));
|
|
1036
|
+
const account = native?.account ?? await this.provider.request({
|
|
357
1037
|
method: "getPrimaryAccount"
|
|
358
1038
|
});
|
|
1039
|
+
assertPrimaryParty(account);
|
|
359
1040
|
let reportedNetwork;
|
|
360
1041
|
try {
|
|
361
|
-
const status = await this.provider.request({
|
|
1042
|
+
const status = native?.status ?? await this.provider.request({
|
|
362
1043
|
method: "status"
|
|
363
1044
|
});
|
|
364
1045
|
reportedNetwork = status?.network?.networkId;
|
|
@@ -375,65 +1056,167 @@ var GenericDiscoveryAdapter = class {
|
|
|
375
1056
|
};
|
|
376
1057
|
return { partyId, session, capabilities: this.getCapabilities() };
|
|
377
1058
|
}
|
|
378
|
-
/**
|
|
379
|
-
* Restore a persisted session by delegating to the official adapter's own `restore`.
|
|
380
|
-
*
|
|
381
|
-
* The official `ProviderAdapter` shape carries an optional `restore()` that reinstates a
|
|
382
|
-
* session (for example from the wallet's own storage) and returns a LIVE provider.
|
|
383
|
-
* Without this method the SDK revived the persisted record as-is and then built a fresh,
|
|
384
|
-
* SESSION-LESS provider from `provider()`, so a wallet that restores in `restore` looked
|
|
385
|
-
* connected after a reload but its first real request threw. This forwards to the
|
|
386
|
-
* official `restore` and, when it yields a provider, adopts it as the cached provider so
|
|
387
|
-
* the very next request uses the restored session.
|
|
388
|
-
*
|
|
389
|
-
* Popup-safe: this runs on the SDK's init/restore path, never inside a user gesture, so a
|
|
390
|
-
* popup could not open here even if an adapter tried (the browser would block it). Per
|
|
391
|
-
* the official contract `restore` is storage-based and gesture-free. If the official
|
|
392
|
-
* adapter has no `restore`, it returns null, or host resolution is not ready, this falls
|
|
393
|
-
* through to the previous behavior: the persisted session is returned and the provider is
|
|
394
|
-
* built lazily on first use, exactly as before.
|
|
395
|
-
*/
|
|
1059
|
+
/** Restore silently and validate the live party before exposing a connected session. */
|
|
396
1060
|
async restore(ctx, persisted) {
|
|
397
|
-
const asIs = { ...persisted, walletId: this.walletId };
|
|
398
1061
|
try {
|
|
1062
|
+
if (persisted.expiresAt && Date.now() >= persisted.expiresAt) return null;
|
|
399
1063
|
this.resolveOfficial(ctx.network);
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
restored = null;
|
|
1064
|
+
const owner = nativeOwnerBindings.get(this);
|
|
1065
|
+
if (owner) {
|
|
1066
|
+
await this.prepareNativeConnection(ctx.network);
|
|
1067
|
+
const restored = await owner.restore({
|
|
1068
|
+
id: String(this.walletId),
|
|
1069
|
+
partyId: persisted.partyId,
|
|
1070
|
+
network: persisted.network
|
|
1071
|
+
});
|
|
1072
|
+
return restored?.id === String(this.walletId) ? { ...persisted, walletId: this.walletId, capabilitiesSnapshot: this.getCapabilities() } : null;
|
|
410
1073
|
}
|
|
411
|
-
if (
|
|
1074
|
+
if (this.official?.restore) {
|
|
1075
|
+
const restored = await this.official.restore();
|
|
1076
|
+
if (!restored) return null;
|
|
412
1077
|
this.providerInstance = restored;
|
|
413
|
-
return asIs;
|
|
414
1078
|
}
|
|
1079
|
+
const account = await this.provider.request({ method: "getPrimaryAccount" });
|
|
1080
|
+
if (account.partyId !== persisted.partyId) return null;
|
|
1081
|
+
let status;
|
|
1082
|
+
try {
|
|
1083
|
+
status = await this.provider.request({ method: "status" });
|
|
1084
|
+
} catch {
|
|
1085
|
+
}
|
|
1086
|
+
if (status?.connection?.isConnected === false) return null;
|
|
1087
|
+
const network = [status?.network?.networkId, account.networkId].find(
|
|
1088
|
+
(value) => typeof value === "string" && isRecognizedNetwork(value)
|
|
1089
|
+
);
|
|
1090
|
+
if (network && detectNetworkMismatch(persisted.network, network)) return null;
|
|
1091
|
+
return { ...persisted, walletId: this.walletId, capabilitiesSnapshot: this.getCapabilities() };
|
|
1092
|
+
} catch {
|
|
1093
|
+
return null;
|
|
415
1094
|
}
|
|
416
|
-
return asIs;
|
|
417
1095
|
}
|
|
418
1096
|
async disconnect() {
|
|
1097
|
+
const owner = nativeOwnerBindings.get(this);
|
|
1098
|
+
if (owner) {
|
|
1099
|
+
await owner.disconnect();
|
|
1100
|
+
return;
|
|
1101
|
+
}
|
|
419
1102
|
try {
|
|
420
1103
|
await this.provider.request({ method: "disconnect" });
|
|
421
1104
|
} catch {
|
|
422
1105
|
}
|
|
423
1106
|
}
|
|
424
|
-
async signMessage(_ctx,
|
|
425
|
-
|
|
1107
|
+
async signMessage(_ctx, session, params) {
|
|
1108
|
+
const response = await this.provider.request({
|
|
426
1109
|
method: "signMessage",
|
|
427
1110
|
params: { message: params.message }
|
|
428
1111
|
});
|
|
1112
|
+
return normalizeSignedMessage(response, session, params);
|
|
429
1113
|
}
|
|
430
|
-
async submitTransaction(
|
|
431
|
-
return this.provider
|
|
432
|
-
|
|
433
|
-
|
|
1114
|
+
async submitTransaction(ctx, _session, params) {
|
|
1115
|
+
return submitViaPrepareExecute(this.provider, params, {
|
|
1116
|
+
walletId: String(this.walletId),
|
|
1117
|
+
state: this.executeVerb,
|
|
1118
|
+
logger: ctx.logger
|
|
434
1119
|
});
|
|
435
1120
|
}
|
|
436
1121
|
};
|
|
1122
|
+
function createSessionProvider(options) {
|
|
1123
|
+
const events = new CIP0103EventBus();
|
|
1124
|
+
let current = null;
|
|
1125
|
+
let disposed = false;
|
|
1126
|
+
let revision = 0;
|
|
1127
|
+
const nativeSubscriptions = [];
|
|
1128
|
+
const bridgeSubscriptions = [];
|
|
1129
|
+
const provider = {
|
|
1130
|
+
request: async (args) => {
|
|
1131
|
+
try {
|
|
1132
|
+
if (disposed) throw new Error("PartyLayer client was destroyed");
|
|
1133
|
+
if (args.method === "connect" || args.method === "disconnect" || args.method === "signMessage") {
|
|
1134
|
+
return options.bridge.request(args);
|
|
1135
|
+
}
|
|
1136
|
+
await options.ensureSession();
|
|
1137
|
+
const native = options.native();
|
|
1138
|
+
if (!native) return options.bridge.request(args);
|
|
1139
|
+
if ([
|
|
1140
|
+
"prepareExecute",
|
|
1141
|
+
"prepareExecuteAndWait",
|
|
1142
|
+
"prepareTransaction",
|
|
1143
|
+
"executeTransaction",
|
|
1144
|
+
"signTransaction",
|
|
1145
|
+
"ledgerApi"
|
|
1146
|
+
].includes(args.method))
|
|
1147
|
+
options.guardNetwork();
|
|
1148
|
+
const result = await native.request(args);
|
|
1149
|
+
if (args.method === "prepareExecute" || args.method === "prepareExecuteAndWait")
|
|
1150
|
+
assertExecuteCorrelation(result, args.params);
|
|
1151
|
+
return result;
|
|
1152
|
+
} catch (error) {
|
|
1153
|
+
throw toProviderRpcError(error);
|
|
1154
|
+
}
|
|
1155
|
+
},
|
|
1156
|
+
on: (event, listener) => {
|
|
1157
|
+
events.on(event, listener);
|
|
1158
|
+
return provider;
|
|
1159
|
+
},
|
|
1160
|
+
emit: (event, ...args) => events.emit(event, ...args),
|
|
1161
|
+
removeListener: (event, listener) => {
|
|
1162
|
+
events.removeListener(event, listener);
|
|
1163
|
+
return provider;
|
|
1164
|
+
}
|
|
1165
|
+
};
|
|
1166
|
+
events.setOwner(provider);
|
|
1167
|
+
const refresh = () => {
|
|
1168
|
+
const next = options.native();
|
|
1169
|
+
if (next === current) return;
|
|
1170
|
+
++revision;
|
|
1171
|
+
nativeSubscriptions.splice(0).forEach((unsubscribe2) => unsubscribe2());
|
|
1172
|
+
current = next;
|
|
1173
|
+
if (!next || disposed) return;
|
|
1174
|
+
const captured = revision;
|
|
1175
|
+
for (const name of ["statusChanged", "accountsChanged", "txChanged", "connected"]) {
|
|
1176
|
+
const listener = (...args) => {
|
|
1177
|
+
if (!disposed && next === options.native()) events.emit(name, ...args);
|
|
1178
|
+
};
|
|
1179
|
+
next.on(name, listener);
|
|
1180
|
+
nativeSubscriptions.push(() => next.removeListener(name, listener));
|
|
1181
|
+
}
|
|
1182
|
+
for (const [method, event] of [
|
|
1183
|
+
["status", "statusChanged"],
|
|
1184
|
+
["listAccounts", "accountsChanged"]
|
|
1185
|
+
]) {
|
|
1186
|
+
void next.request({ method }).then(
|
|
1187
|
+
(value) => {
|
|
1188
|
+
if (!disposed && captured === revision && next === options.native())
|
|
1189
|
+
events.emit(event, value);
|
|
1190
|
+
},
|
|
1191
|
+
() => {
|
|
1192
|
+
}
|
|
1193
|
+
);
|
|
1194
|
+
}
|
|
1195
|
+
events.emit("connected", { isConnected: true });
|
|
1196
|
+
};
|
|
1197
|
+
for (const name of ["statusChanged", "accountsChanged", "txChanged", "connected"]) {
|
|
1198
|
+
const listener = (...args) => {
|
|
1199
|
+
if (!options.native() && !disposed) events.emit(name, ...args);
|
|
1200
|
+
};
|
|
1201
|
+
options.bridge.on(name, listener);
|
|
1202
|
+
bridgeSubscriptions.push(() => options.bridge.removeListener(name, listener));
|
|
1203
|
+
}
|
|
1204
|
+
const unsubscribe = options.subscribe(refresh);
|
|
1205
|
+
refresh();
|
|
1206
|
+
return {
|
|
1207
|
+
provider,
|
|
1208
|
+
destroy: () => {
|
|
1209
|
+
if (disposed) return;
|
|
1210
|
+
disposed = true;
|
|
1211
|
+
++revision;
|
|
1212
|
+
unsubscribe();
|
|
1213
|
+
nativeSubscriptions.splice(0).forEach((remove) => remove());
|
|
1214
|
+
bridgeSubscriptions.splice(0).forEach((remove) => remove());
|
|
1215
|
+
current = null;
|
|
1216
|
+
events.removeAllListeners();
|
|
1217
|
+
}
|
|
1218
|
+
};
|
|
1219
|
+
}
|
|
437
1220
|
|
|
438
1221
|
// src/config.ts
|
|
439
1222
|
var DEFAULT_REGISTRY_URL = "https://registry.partylayer.xyz";
|
|
@@ -878,9 +1661,20 @@ function deriveAnnounceConfig(entry) {
|
|
|
878
1661
|
}
|
|
879
1662
|
return config;
|
|
880
1663
|
}
|
|
1664
|
+
function matchKnownByIdentity(providerId, base) {
|
|
1665
|
+
return base.find((w) => {
|
|
1666
|
+
const k = w.installHints?.injectedKey;
|
|
1667
|
+
return providerId === String(w.walletId) || !!k && (providerId === k || providerId.startsWith(`${k}.`));
|
|
1668
|
+
});
|
|
1669
|
+
}
|
|
1670
|
+
var DEFAULT_CONNECT_TIMEOUT_MS = 12e4;
|
|
881
1671
|
var PartyLayerClient = class {
|
|
882
1672
|
config;
|
|
883
1673
|
adapters = /* @__PURE__ */ new Map();
|
|
1674
|
+
destroyed = false;
|
|
1675
|
+
initialized = false;
|
|
1676
|
+
defaultLoads = /* @__PURE__ */ new Map();
|
|
1677
|
+
registryDefaultIds = /* @__PURE__ */ new Set();
|
|
884
1678
|
/**
|
|
885
1679
|
* Pre-resolved connect plans for popup/remote (GenericDiscoveryAdapter)
|
|
886
1680
|
* wallets, warmed on `listWallets()` (which the modal calls on open) so a
|
|
@@ -890,6 +1684,11 @@ var PartyLayerClient = class {
|
|
|
890
1684
|
warmPlans = /* @__PURE__ */ new Map();
|
|
891
1685
|
eventHandlers = /* @__PURE__ */ new Map();
|
|
892
1686
|
activeSession = null;
|
|
1687
|
+
sessionRevision = 0;
|
|
1688
|
+
connectionAttempt = 0;
|
|
1689
|
+
restoreTask = null;
|
|
1690
|
+
restorationBlocked = false;
|
|
1691
|
+
sessionStorageQueue = Promise.resolve();
|
|
893
1692
|
/**
|
|
894
1693
|
* True when `activeSession` was revived AS-IS (no live `status()` probe) because
|
|
895
1694
|
* its adapter wasn't registered yet at restore time (the lazy configured-announce
|
|
@@ -912,10 +1711,13 @@ var PartyLayerClient = class {
|
|
|
912
1711
|
// captured (not just a one-shot window). Read by aggregateAnnouncedWallets;
|
|
913
1712
|
// torn down in destroy(). Empty → listWallets() output is byte-identical.
|
|
914
1713
|
announceRegistry = /* @__PURE__ */ new Map();
|
|
1714
|
+
announceChannels = /* @__PURE__ */ new Map();
|
|
915
1715
|
announceUnsubscribe = null;
|
|
916
1716
|
/** Pending debounced `wallets:changed` emit (coalesces an announce burst). */
|
|
917
1717
|
walletsChangedTimer = null;
|
|
918
1718
|
origin;
|
|
1719
|
+
nativeOwner;
|
|
1720
|
+
sessionProvider;
|
|
919
1721
|
constructor(config) {
|
|
920
1722
|
this.config = config;
|
|
921
1723
|
if (config.app.origin) {
|
|
@@ -929,9 +1731,13 @@ var PartyLayerClient = class {
|
|
|
929
1731
|
this.logLevel = config.logLevel ?? "info";
|
|
930
1732
|
this.crypto = config.crypto || new DefaultCrypto();
|
|
931
1733
|
this.storage = config.storage || new DefaultStorage();
|
|
1734
|
+
if (typeof window !== "undefined") {
|
|
1735
|
+
this.nativeOwner = new NativeConnectionOwner((id, identity) => this.onNativeIdentityChanged(id, identity));
|
|
1736
|
+
}
|
|
932
1737
|
const telemetryAdapter = createTelemetryAdapter(config.telemetry);
|
|
933
1738
|
this.telemetry = telemetryAdapter || new DefaultTelemetry();
|
|
934
|
-
const
|
|
1739
|
+
const defaults = config.adapters ?? getBuiltinAdapters();
|
|
1740
|
+
const adaptersToRegister = [...defaults, ...config.additionalAdapters ?? []];
|
|
935
1741
|
for (const adapterOrClass of adaptersToRegister) {
|
|
936
1742
|
let adapter;
|
|
937
1743
|
if (typeof adapterOrClass === "function") {
|
|
@@ -943,7 +1749,7 @@ var PartyLayerClient = class {
|
|
|
943
1749
|
} else {
|
|
944
1750
|
adapter = adapterOrClass;
|
|
945
1751
|
}
|
|
946
|
-
this.
|
|
1752
|
+
this.registerAdapter(adapter);
|
|
947
1753
|
this.log("debug", "adapter:registered", "Registered wallet adapter", {
|
|
948
1754
|
walletId: adapter.walletId,
|
|
949
1755
|
name: adapter.name,
|
|
@@ -957,10 +1763,16 @@ var PartyLayerClient = class {
|
|
|
957
1763
|
storage: this.storage
|
|
958
1764
|
});
|
|
959
1765
|
this.updateRegistryStatus();
|
|
1766
|
+
if (!config.deferInitialization) this.initialize();
|
|
1767
|
+
}
|
|
1768
|
+
/** Start browser discovery/restoration once; safe for framework effect replay. */
|
|
1769
|
+
initialize() {
|
|
1770
|
+
if (this.initialized || this.destroyed) return;
|
|
1771
|
+
this.initialized = true;
|
|
960
1772
|
if (this.announceEnabled) {
|
|
961
1773
|
this.announceUnsubscribe = subscribeAnnouncedProviders(
|
|
962
1774
|
(p) => this.onAnnounceAccumulated(p),
|
|
963
|
-
{ createProvider: (a) =>
|
|
1775
|
+
{ createProvider: (a) => this.announceChannel(a.target ?? a.id) }
|
|
964
1776
|
);
|
|
965
1777
|
}
|
|
966
1778
|
this.restoreSession().catch((err) => {
|
|
@@ -972,6 +1784,15 @@ var PartyLayerClient = class {
|
|
|
972
1784
|
});
|
|
973
1785
|
});
|
|
974
1786
|
}
|
|
1787
|
+
announceChannel(target) {
|
|
1788
|
+
if (this.destroyed) throw new Error("PartyLayer client was destroyed");
|
|
1789
|
+
let provider = this.announceChannels.get(target);
|
|
1790
|
+
if (!provider) {
|
|
1791
|
+
provider = createExtensionChannelProvider({ target });
|
|
1792
|
+
this.announceChannels.set(target, provider);
|
|
1793
|
+
}
|
|
1794
|
+
return provider;
|
|
1795
|
+
}
|
|
975
1796
|
/**
|
|
976
1797
|
* Register a wallet adapter
|
|
977
1798
|
*
|
|
@@ -980,7 +1801,34 @@ var PartyLayerClient = class {
|
|
|
980
1801
|
* In production, adapters would be auto-registered via registry.
|
|
981
1802
|
*/
|
|
982
1803
|
registerAdapter(adapter) {
|
|
1804
|
+
const boundOwner = nativeOwnerBindings.get(adapter);
|
|
1805
|
+
if (this.nativeOwner && boundOwner && boundOwner !== this.nativeOwner) {
|
|
1806
|
+
adapter = nativeAdapterCopies.get(adapter)();
|
|
1807
|
+
}
|
|
983
1808
|
this.adapters.set(adapter.walletId, adapter);
|
|
1809
|
+
if (this.nativeOwner && (adapter instanceof GenericDiscoveryAdapter || adapter instanceof GenericAnnounceAdapter)) {
|
|
1810
|
+
nativeOwnerBindings.set(adapter, this.nativeOwner);
|
|
1811
|
+
}
|
|
1812
|
+
}
|
|
1813
|
+
onNativeIdentityChanged(id, identity) {
|
|
1814
|
+
const active = this.activeSession;
|
|
1815
|
+
if (this.destroyed || !active || String(active.walletId) !== id) return;
|
|
1816
|
+
++this.sessionRevision;
|
|
1817
|
+
if (!identity) {
|
|
1818
|
+
this.restorationBlocked = true;
|
|
1819
|
+
this.warmPlans.clear();
|
|
1820
|
+
this.activeSession = null;
|
|
1821
|
+
void this.removeSession(active.sessionId);
|
|
1822
|
+
this.emit("session:disconnected", { type: "session:disconnected", sessionId: active.sessionId });
|
|
1823
|
+
return;
|
|
1824
|
+
}
|
|
1825
|
+
const session = { ...active, partyId: identity.account.partyId, network: identity.network };
|
|
1826
|
+
const mismatch = this.networkMismatch(session);
|
|
1827
|
+
if (mismatch) session.networkMismatch = mismatch;
|
|
1828
|
+
else delete session.networkMismatch;
|
|
1829
|
+
this.activeSession = session;
|
|
1830
|
+
void this.persistSession(session);
|
|
1831
|
+
this.emit("session:connected", { type: "session:connected", session });
|
|
984
1832
|
}
|
|
985
1833
|
/**
|
|
986
1834
|
* Look up a registered adapter by wallet id.
|
|
@@ -1004,6 +1852,7 @@ var PartyLayerClient = class {
|
|
|
1004
1852
|
* List available wallets
|
|
1005
1853
|
*/
|
|
1006
1854
|
async listWallets(filter) {
|
|
1855
|
+
this.initialize();
|
|
1007
1856
|
let registryWallets;
|
|
1008
1857
|
try {
|
|
1009
1858
|
registryWallets = await this.registryClient.getWallets();
|
|
@@ -1015,9 +1864,10 @@ var PartyLayerClient = class {
|
|
|
1015
1864
|
});
|
|
1016
1865
|
registryWallets = [];
|
|
1017
1866
|
}
|
|
1867
|
+
await this.ensureDefaultWallets();
|
|
1018
1868
|
const registryIds = new Set(registryWallets.map((w) => String(w.walletId)));
|
|
1019
1869
|
for (const [, adapter] of this.adapters) {
|
|
1020
|
-
if (registryIds.has(String(adapter.walletId))) continue;
|
|
1870
|
+
if (registryIds.has(String(adapter.walletId)) || this.registryDefaultIds.has(adapter.walletId)) continue;
|
|
1021
1871
|
registryWallets.push({
|
|
1022
1872
|
walletId: adapter.walletId,
|
|
1023
1873
|
name: adapter.name,
|
|
@@ -1027,24 +1877,62 @@ var PartyLayerClient = class {
|
|
|
1027
1877
|
adapter: { packageName: "builtin", versionRange: "*" },
|
|
1028
1878
|
docs: [],
|
|
1029
1879
|
networks: [this.config.network || "devnet"],
|
|
1030
|
-
channel: "stable"
|
|
1880
|
+
channel: this.config.channel || "stable"
|
|
1031
1881
|
});
|
|
1032
1882
|
}
|
|
1033
1883
|
registryWallets = await this.gateUnconnectableEntries(registryWallets);
|
|
1034
1884
|
registryWallets = await this.aggregateAnnouncedWallets(registryWallets);
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
return
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
}
|
|
1043
|
-
if (!filter?.includeExperimental) {
|
|
1044
|
-
return registryWallets.filter((walletInfo) => walletInfo.channel === "stable");
|
|
1045
|
-
}
|
|
1885
|
+
registryWallets = registryWallets.map((wallet) => {
|
|
1886
|
+
const adapter = this.adapters.get(wallet.walletId);
|
|
1887
|
+
return adapter ? { ...wallet, capabilities: adapter.getCapabilities() } : wallet;
|
|
1888
|
+
}).filter(
|
|
1889
|
+
(wallet) => wallet.networks.includes(this.config.network) && (filter?.includeExperimental || wallet.channel === (this.config.channel || "stable")) && (!filter?.requiredCapabilities || filter.requiredCapabilities.every((cap) => wallet.capabilities.includes(cap)))
|
|
1890
|
+
);
|
|
1891
|
+
await this.warmDiscoveryPlans(registryWallets);
|
|
1046
1892
|
return registryWallets;
|
|
1047
1893
|
}
|
|
1894
|
+
/** Resolve only reviewed default SDKs present in the active registry. */
|
|
1895
|
+
async ensureDefaultWallets() {
|
|
1896
|
+
if (this.config.adapters !== void 0) return;
|
|
1897
|
+
let registry;
|
|
1898
|
+
try {
|
|
1899
|
+
registry = await this.registryClient.getRegistry();
|
|
1900
|
+
} catch {
|
|
1901
|
+
return;
|
|
1902
|
+
}
|
|
1903
|
+
await Promise.all(registry.wallets.map(async (entry) => {
|
|
1904
|
+
const id = toWalletId(entry.id);
|
|
1905
|
+
if (this.adapters.has(id) || !entry.supportedNetworks.includes(this.config.network) || entry.adapter?.transport === "discovery-adapter" && !entry.adapter.networkHosts?.[this.config.network]) return;
|
|
1906
|
+
let pending = this.defaultLoads.get(entry.id);
|
|
1907
|
+
if (!pending) {
|
|
1908
|
+
pending = (async () => {
|
|
1909
|
+
try {
|
|
1910
|
+
const entryAdapter = await loadDefaultWallet(entry.id, this.config, this.origin);
|
|
1911
|
+
if (!entryAdapter || this.destroyed) return;
|
|
1912
|
+
const adapter = isOfficialAdapterFactory(entryAdapter) ? new GenericDiscoveryAdapter({
|
|
1913
|
+
factory: entryAdapter,
|
|
1914
|
+
name: entry.name,
|
|
1915
|
+
networkHosts: entry.adapter?.networkHosts,
|
|
1916
|
+
capabilities: entry.capabilities
|
|
1917
|
+
}) : entryAdapter;
|
|
1918
|
+
if (typeof window !== "undefined" && adapter instanceof GenericDiscoveryAdapter) {
|
|
1919
|
+
adapter.resolveOfficial(this.config.network);
|
|
1920
|
+
}
|
|
1921
|
+
this.registerAdapter(adapter);
|
|
1922
|
+
this.registryDefaultIds.add(id);
|
|
1923
|
+
} catch (error) {
|
|
1924
|
+
this.defaultLoads.delete(entry.id);
|
|
1925
|
+
this.log("warn", "wallet:load_failed", "Official wallet SDK could not load", {
|
|
1926
|
+
walletId: entry.id,
|
|
1927
|
+
error: String(error)
|
|
1928
|
+
});
|
|
1929
|
+
}
|
|
1930
|
+
})();
|
|
1931
|
+
this.defaultLoads.set(entry.id, pending);
|
|
1932
|
+
}
|
|
1933
|
+
await pending;
|
|
1934
|
+
}));
|
|
1935
|
+
}
|
|
1048
1936
|
/**
|
|
1049
1937
|
* Hide registry entries whose wallet needs an app-registered adapter that is
|
|
1050
1938
|
* NOT registered. This is the library default (RainbowKit-style): never show a
|
|
@@ -1067,10 +1955,14 @@ var PartyLayerClient = class {
|
|
|
1067
1955
|
*/
|
|
1068
1956
|
async gateUnconnectableEntries(wallets) {
|
|
1069
1957
|
let hidden = null;
|
|
1958
|
+
const announceCapabilities = /* @__PURE__ */ new Map();
|
|
1070
1959
|
try {
|
|
1071
1960
|
const registry = await this.registryClient.getRegistry();
|
|
1072
1961
|
for (const entry of registry.wallets) {
|
|
1073
|
-
if (entry.adapter?.transport === "announce")
|
|
1962
|
+
if (entry.adapter?.transport === "announce") {
|
|
1963
|
+
announceCapabilities.set(entry.id, getAnnounceCapabilities(deriveAnnounceConfig(entry)));
|
|
1964
|
+
continue;
|
|
1965
|
+
}
|
|
1074
1966
|
const walletId = toWalletId(entry.id);
|
|
1075
1967
|
if (!this.adapters.has(walletId)) {
|
|
1076
1968
|
(hidden ??= /* @__PURE__ */ new Set()).add(String(walletId));
|
|
@@ -1079,8 +1971,10 @@ var PartyLayerClient = class {
|
|
|
1079
1971
|
} catch {
|
|
1080
1972
|
return wallets;
|
|
1081
1973
|
}
|
|
1082
|
-
|
|
1083
|
-
|
|
1974
|
+
return wallets.filter((w) => !hidden?.has(String(w.walletId))).map((w) => {
|
|
1975
|
+
const capabilities = announceCapabilities.get(String(w.walletId));
|
|
1976
|
+
return capabilities ? { ...w, capabilities } : w;
|
|
1977
|
+
});
|
|
1084
1978
|
}
|
|
1085
1979
|
/**
|
|
1086
1980
|
* If `walletId` maps to a registry entry with `transport: 'discovery-adapter'`,
|
|
@@ -1171,7 +2065,7 @@ var PartyLayerClient = class {
|
|
|
1171
2065
|
injectionPaths,
|
|
1172
2066
|
// Working provider over the announce target channel; G4 (provider.md):
|
|
1173
2067
|
// target defaults to id when omitted — never a shared slot.
|
|
1174
|
-
createProvider: (a) =>
|
|
2068
|
+
createProvider: (a) => this.announceChannel(a.target ?? a.id)
|
|
1175
2069
|
});
|
|
1176
2070
|
const byId = /* @__PURE__ */ new Map();
|
|
1177
2071
|
for (const d of snapshot) byId.set(d.id, d);
|
|
@@ -1184,7 +2078,7 @@ var PartyLayerClient = class {
|
|
|
1184
2078
|
const known = findMatchingWalletInfo(
|
|
1185
2079
|
{ provider: { id: d.id } },
|
|
1186
2080
|
base
|
|
1187
|
-
);
|
|
2081
|
+
) ?? matchKnownByIdentity(d.id, base);
|
|
1188
2082
|
if (known) {
|
|
1189
2083
|
if (this.adapters.has(known.walletId)) continue;
|
|
1190
2084
|
try {
|
|
@@ -1198,21 +2092,25 @@ var PartyLayerClient = class {
|
|
|
1198
2092
|
provider: d.provider,
|
|
1199
2093
|
config: deriveAnnounceConfig(entry)
|
|
1200
2094
|
});
|
|
1201
|
-
this.
|
|
2095
|
+
this.registerAdapter(configured);
|
|
1202
2096
|
const active = this.activeSession;
|
|
1203
2097
|
if (active && this.activeSessionNeedsProbe && active.walletId === configured.walletId && configured.restore) {
|
|
2098
|
+
const revision = this.sessionRevision;
|
|
1204
2099
|
try {
|
|
1205
2100
|
const reprobed = await configured.restore(this.createAdapterContext(), {
|
|
1206
2101
|
...active,
|
|
1207
2102
|
encrypted: ""
|
|
1208
2103
|
});
|
|
2104
|
+
if (this.destroyed || revision !== this.sessionRevision || this.activeSession !== active) continue;
|
|
1209
2105
|
if (reprobed) {
|
|
1210
2106
|
this.activeSession = reprobed;
|
|
1211
2107
|
this.activeSessionNeedsProbe = false;
|
|
1212
2108
|
await this.persistSession(reprobed);
|
|
2109
|
+
if (this.destroyed || revision !== this.sessionRevision || this.activeSession !== reprobed) continue;
|
|
1213
2110
|
this.emit("session:connected", { type: "session:connected", session: reprobed });
|
|
1214
2111
|
} else {
|
|
1215
2112
|
await this.removeSession(active.sessionId);
|
|
2113
|
+
if (this.destroyed || revision !== this.sessionRevision || this.activeSession !== active) continue;
|
|
1216
2114
|
this.activeSession = null;
|
|
1217
2115
|
this.activeSessionNeedsProbe = false;
|
|
1218
2116
|
this.emit("session:expired", { type: "session:expired", sessionId: active.sessionId });
|
|
@@ -1234,7 +2132,7 @@ var PartyLayerClient = class {
|
|
|
1234
2132
|
icon: d.icon,
|
|
1235
2133
|
provider: d.provider
|
|
1236
2134
|
});
|
|
1237
|
-
this.
|
|
2135
|
+
this.registerAdapter(adapter);
|
|
1238
2136
|
entries.push({
|
|
1239
2137
|
walletId: adapter.walletId,
|
|
1240
2138
|
name: adapter.name,
|
|
@@ -1286,16 +2184,22 @@ var PartyLayerClient = class {
|
|
|
1286
2184
|
* Connect to a wallet
|
|
1287
2185
|
*/
|
|
1288
2186
|
async connect(options) {
|
|
2187
|
+
this.initialize();
|
|
2188
|
+
this.nativeOwner?.assertAvailable();
|
|
2189
|
+
this.restorationBlocked = true;
|
|
2190
|
+
const attempt = ++this.connectionAttempt;
|
|
2191
|
+
++this.sessionRevision;
|
|
1289
2192
|
this.telemetry?.increment?.(METRICS.WALLET_CONNECT_ATTEMPTS);
|
|
1290
2193
|
const correlationId = newCorrelationId();
|
|
1291
2194
|
this.log("debug", "connect:start", "connect", {}, correlationId);
|
|
1292
2195
|
try {
|
|
1293
|
-
const fast = this.tryFastConnect(options, correlationId);
|
|
2196
|
+
const fast = this.tryFastConnect(options, correlationId, attempt);
|
|
1294
2197
|
if (fast) return await fast;
|
|
1295
2198
|
const plan = await this.resolveConnectPlan(options);
|
|
1296
|
-
return await this.completeConnect(plan, options, correlationId);
|
|
2199
|
+
return await this.completeConnect(plan, options, correlationId, attempt);
|
|
1297
2200
|
} catch (err) {
|
|
1298
|
-
|
|
2201
|
+
this.warmPlans.clear();
|
|
2202
|
+
const timeoutMs = options?.timeoutMs || DEFAULT_CONNECT_TIMEOUT_MS;
|
|
1299
2203
|
const error = mapUnknownErrorToPartyLayerError(err, {
|
|
1300
2204
|
phase: "connect",
|
|
1301
2205
|
walletId: options?.walletId ? String(options.walletId) : void 0,
|
|
@@ -1333,6 +2237,10 @@ var PartyLayerClient = class {
|
|
|
1333
2237
|
} else {
|
|
1334
2238
|
const nativeAdapter = this.adapters.get(options.walletId);
|
|
1335
2239
|
if (nativeAdapter) {
|
|
2240
|
+
const entry = await this.registryClient.getWalletEntry(String(options.walletId)).catch(() => null);
|
|
2241
|
+
if (entry?.supportedNetworks?.length && !entry.supportedNetworks.includes(this.config.network)) {
|
|
2242
|
+
throw new WalletNotFoundError(`${String(options.walletId)} is unavailable on ${this.config.network}`);
|
|
2243
|
+
}
|
|
1336
2244
|
isNativeWallet = true;
|
|
1337
2245
|
selectedWallet = {
|
|
1338
2246
|
walletId: options.walletId,
|
|
@@ -1398,6 +2306,9 @@ var PartyLayerClient = class {
|
|
|
1398
2306
|
adapter.setNetworkHosts(networkHosts);
|
|
1399
2307
|
adapter.resolveOfficial(ctx.network);
|
|
1400
2308
|
}
|
|
2309
|
+
if (adapter instanceof GenericDiscoveryAdapter || adapter instanceof GenericAnnounceAdapter) {
|
|
2310
|
+
await adapter.prepareNativeConnection(ctx.network);
|
|
2311
|
+
}
|
|
1401
2312
|
return { selectedWallet, adapter, ctx, isNativeWallet };
|
|
1402
2313
|
}
|
|
1403
2314
|
/**
|
|
@@ -1405,21 +2316,37 @@ var PartyLayerClient = class {
|
|
|
1405
2316
|
* build / persist / emit the session. Separated from plan resolution so the
|
|
1406
2317
|
* popup-safe fast-path can call it gesture-synchronously.
|
|
1407
2318
|
*/
|
|
1408
|
-
async completeConnect(plan, options, correlationId = newCorrelationId()) {
|
|
2319
|
+
async completeConnect(plan, options, correlationId = newCorrelationId(), attempt) {
|
|
2320
|
+
this.nativeOwner?.assertAvailable();
|
|
2321
|
+
this.restorationBlocked = true;
|
|
2322
|
+
const currentAttempt = attempt ?? ++this.connectionAttempt;
|
|
2323
|
+
if (attempt === void 0) ++this.sessionRevision;
|
|
2324
|
+
if (this.destroyed || currentAttempt !== this.connectionAttempt) throw new Error("Wallet connection was superseded");
|
|
1409
2325
|
const { selectedWallet, adapter, ctx } = plan;
|
|
1410
|
-
|
|
2326
|
+
if (!nativeOwnerBindings.has(adapter) && this.nativeOwner?.getSession()) this.nativeOwner.release();
|
|
2327
|
+
const timeoutMs = options?.timeoutMs || DEFAULT_CONNECT_TIMEOUT_MS;
|
|
2328
|
+
const abort = new AbortController();
|
|
1411
2329
|
const connectPromise = adapter.connect(ctx, {
|
|
1412
2330
|
timeoutMs,
|
|
2331
|
+
signal: abort.signal,
|
|
1413
2332
|
partyId: void 0,
|
|
1414
2333
|
preferInstalled: options?.preferInstalled,
|
|
1415
2334
|
onDisplayUri: options?.onDisplayUri
|
|
1416
2335
|
});
|
|
2336
|
+
let timeoutHandle;
|
|
1417
2337
|
const timeoutPromise = new Promise((_, reject) => {
|
|
1418
|
-
setTimeout(() => {
|
|
2338
|
+
timeoutHandle = setTimeout(() => {
|
|
2339
|
+
abort.abort();
|
|
1419
2340
|
reject(new Error(`Connection timed out after ${timeoutMs}ms - user did not complete wallet connection`));
|
|
1420
2341
|
}, timeoutMs);
|
|
1421
2342
|
});
|
|
1422
|
-
|
|
2343
|
+
let result;
|
|
2344
|
+
try {
|
|
2345
|
+
result = await Promise.race([connectPromise, timeoutPromise]);
|
|
2346
|
+
} finally {
|
|
2347
|
+
if (timeoutHandle !== void 0) clearTimeout(timeoutHandle);
|
|
2348
|
+
}
|
|
2349
|
+
if (this.destroyed || currentAttempt !== this.connectionAttempt) throw new Error("Wallet connection was superseded");
|
|
1423
2350
|
const session = {
|
|
1424
2351
|
sessionId: toSessionId(`session_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`),
|
|
1425
2352
|
walletId: selectedWallet.walletId,
|
|
@@ -1450,12 +2377,18 @@ var PartyLayerClient = class {
|
|
|
1450
2377
|
enforced: this.enforcement !== "off"
|
|
1451
2378
|
}, correlationId);
|
|
1452
2379
|
if (this.enforcement === "strict") {
|
|
2380
|
+
if (nativeOwnerBindings.has(adapter)) await this.nativeOwner?.disconnect();
|
|
1453
2381
|
throw new NetworkMismatchError(mismatch.expected, mismatch.actual);
|
|
1454
2382
|
}
|
|
1455
2383
|
}
|
|
1456
|
-
|
|
2384
|
+
++this.sessionRevision;
|
|
1457
2385
|
this.activeSession = session;
|
|
2386
|
+
this.restorationBlocked = false;
|
|
1458
2387
|
this.activeSessionNeedsProbe = false;
|
|
2388
|
+
await this.persistSession(session);
|
|
2389
|
+
if (this.destroyed || currentAttempt !== this.connectionAttempt || this.activeSession !== session) {
|
|
2390
|
+
throw new Error("Wallet connection was superseded");
|
|
2391
|
+
}
|
|
1459
2392
|
this.updateRegistryStatus();
|
|
1460
2393
|
this.telemetry?.increment?.(METRICS.WALLET_CONNECT_SUCCESS);
|
|
1461
2394
|
this.telemetry?.increment?.(METRICS.SESSIONS_CREATED);
|
|
@@ -1486,7 +2419,7 @@ var PartyLayerClient = class {
|
|
|
1486
2419
|
*/
|
|
1487
2420
|
async warmDiscoveryPlans(wallets) {
|
|
1488
2421
|
for (const [walletId, adapter] of this.adapters) {
|
|
1489
|
-
if (!(adapter instanceof GenericDiscoveryAdapter)) continue;
|
|
2422
|
+
if (!(adapter instanceof GenericDiscoveryAdapter || adapter instanceof GenericAnnounceAdapter)) continue;
|
|
1490
2423
|
if (this.warmPlans.has(walletId)) continue;
|
|
1491
2424
|
try {
|
|
1492
2425
|
const plan = await this.resolveConnectPlan({ walletId }, wallets);
|
|
@@ -1502,30 +2435,39 @@ var PartyLayerClient = class {
|
|
|
1502
2435
|
* Returns the in-flight Session promise, or null to fall back to the normal
|
|
1503
2436
|
* path (e.g. cold cache, or a non-discovery wallet).
|
|
1504
2437
|
*/
|
|
1505
|
-
tryFastConnect(options, correlationId) {
|
|
2438
|
+
tryFastConnect(options, correlationId, attempt) {
|
|
1506
2439
|
const walletId = options?.walletId;
|
|
1507
2440
|
if (!walletId) return null;
|
|
1508
2441
|
if (options?.requiredCapabilities || options?.allowWallets) return null;
|
|
1509
2442
|
const plan = this.warmPlans.get(walletId);
|
|
1510
2443
|
if (!plan) return null;
|
|
1511
2444
|
this.warmPlans.delete(walletId);
|
|
1512
|
-
return this.completeConnect(plan, options, correlationId);
|
|
2445
|
+
return this.completeConnect(plan, options, correlationId, attempt);
|
|
1513
2446
|
}
|
|
1514
2447
|
/**
|
|
1515
2448
|
* Disconnect from wallet
|
|
1516
2449
|
*/
|
|
1517
2450
|
async disconnect() {
|
|
1518
|
-
|
|
2451
|
+
this.restorationBlocked = true;
|
|
2452
|
+
this.warmPlans.clear();
|
|
2453
|
+
const revision = ++this.sessionRevision;
|
|
2454
|
+
++this.connectionAttempt;
|
|
2455
|
+
const session = this.activeSession;
|
|
2456
|
+
if (!session) {
|
|
2457
|
+
if (this.nativeOwner?.busy) await this.nativeOwner.disconnect();
|
|
2458
|
+
await this.removeSession();
|
|
1519
2459
|
return;
|
|
1520
2460
|
}
|
|
1521
2461
|
try {
|
|
1522
|
-
const adapter = this.adapters.get(
|
|
2462
|
+
const adapter = this.adapters.get(session.walletId);
|
|
1523
2463
|
if (adapter) {
|
|
1524
2464
|
const ctx = this.createAdapterContext();
|
|
1525
|
-
await adapter.disconnect(ctx,
|
|
2465
|
+
await adapter.disconnect(ctx, session);
|
|
1526
2466
|
}
|
|
1527
|
-
|
|
2467
|
+
if (revision !== this.sessionRevision || this.activeSession !== session) return;
|
|
2468
|
+
const sessionId = session.sessionId;
|
|
1528
2469
|
await this.removeSession(sessionId);
|
|
2470
|
+
if (revision !== this.sessionRevision || this.activeSession !== session) return;
|
|
1529
2471
|
this.activeSession = null;
|
|
1530
2472
|
this.warmPlans.clear();
|
|
1531
2473
|
this.emit("session:disconnected", {
|
|
@@ -1545,12 +2487,20 @@ var PartyLayerClient = class {
|
|
|
1545
2487
|
* Get active session
|
|
1546
2488
|
*/
|
|
1547
2489
|
async getActiveSession() {
|
|
2490
|
+
if (this.destroyed) return null;
|
|
2491
|
+
this.initialize();
|
|
1548
2492
|
if (this.activeSession) {
|
|
2493
|
+
const adapter = this.adapters.get(this.activeSession.walletId);
|
|
2494
|
+
if (adapter && nativeOwnerBindings.has(adapter) && this.nativeOwner?.getSession()?.id !== String(this.activeSession.walletId)) {
|
|
2495
|
+
this.onNativeIdentityChanged(String(this.activeSession.walletId), null);
|
|
2496
|
+
return null;
|
|
2497
|
+
}
|
|
1549
2498
|
if (this.activeSession.expiresAt && Date.now() >= this.activeSession.expiresAt) {
|
|
2499
|
+
const sessionId = this.activeSession.sessionId;
|
|
1550
2500
|
await this.disconnect();
|
|
1551
2501
|
this.emit("session:expired", {
|
|
1552
2502
|
type: "session:expired",
|
|
1553
|
-
sessionId
|
|
2503
|
+
sessionId
|
|
1554
2504
|
});
|
|
1555
2505
|
return null;
|
|
1556
2506
|
}
|
|
@@ -1576,7 +2526,11 @@ var PartyLayerClient = class {
|
|
|
1576
2526
|
try {
|
|
1577
2527
|
this.assertNetworkOk(session);
|
|
1578
2528
|
const ctx = this.createAdapterContext();
|
|
1579
|
-
|
|
2529
|
+
const result = await adapter.signMessage(ctx, session, params);
|
|
2530
|
+
if (nativeOwnerBindings.has(adapter)) {
|
|
2531
|
+
await this.nativeOwner.validateIdentity(String(session.walletId), session.partyId, session.network);
|
|
2532
|
+
}
|
|
2533
|
+
return normalizeSignedMessage(result, session, params);
|
|
1580
2534
|
} catch (err) {
|
|
1581
2535
|
const error = mapUnknownErrorToPartyLayerError(err, {
|
|
1582
2536
|
phase: "signMessage",
|
|
@@ -1690,6 +2644,55 @@ var PartyLayerClient = class {
|
|
|
1690
2644
|
throw error;
|
|
1691
2645
|
}
|
|
1692
2646
|
}
|
|
2647
|
+
/**
|
|
2648
|
+
* Request a typed transfer. The application says what it wants; the wallet
|
|
2649
|
+
* builds the command, shows the user what they are authorising, obtains their
|
|
2650
|
+
* approval, signs, executes, and returns the real update id.
|
|
2651
|
+
*
|
|
2652
|
+
* The acting party comes from the active session, never from the caller, and
|
|
2653
|
+
* the intent is narrowed to the allowlisted fields before any adapter sees it,
|
|
2654
|
+
* so no caller-supplied option can reach the wallet.
|
|
2655
|
+
*
|
|
2656
|
+
* Throws `CapabilityNotSupportedError` when the active wallet does not
|
|
2657
|
+
* implement it. Ask first with `session.capabilitiesSnapshot.includes('transfer')`,
|
|
2658
|
+
* or require it at connect with `connect({ requiredCapabilities: ['transfer'] })`.
|
|
2659
|
+
*/
|
|
2660
|
+
async requestTransfer(intent) {
|
|
2661
|
+
const session = await this.getActiveSession();
|
|
2662
|
+
if (!session) {
|
|
2663
|
+
throw new Error("No active session");
|
|
2664
|
+
}
|
|
2665
|
+
const adapter = this.adapters.get(session.walletId);
|
|
2666
|
+
if (!adapter || !adapter.requestTransfer) {
|
|
2667
|
+
throw new CapabilityNotSupportedError(
|
|
2668
|
+
session.walletId,
|
|
2669
|
+
"transfer"
|
|
2670
|
+
);
|
|
2671
|
+
}
|
|
2672
|
+
const safeIntent = toTransferIntent(intent);
|
|
2673
|
+
const correlationId = newCorrelationId();
|
|
2674
|
+
this.log("debug", "requestTransfer:start", "requestTransfer", {}, correlationId);
|
|
2675
|
+
try {
|
|
2676
|
+
this.assertNetworkOk(session);
|
|
2677
|
+
const ctx = this.createAdapterContext();
|
|
2678
|
+
const result = await adapter.requestTransfer(ctx, session, safeIntent);
|
|
2679
|
+
this.emit("tx:status", {
|
|
2680
|
+
type: "tx:status",
|
|
2681
|
+
sessionId: session.sessionId,
|
|
2682
|
+
txId: result.updateId,
|
|
2683
|
+
status: "committed",
|
|
2684
|
+
raw: result
|
|
2685
|
+
}, correlationId);
|
|
2686
|
+
return result;
|
|
2687
|
+
} catch (err) {
|
|
2688
|
+
const error = mapUnknownErrorToPartyLayerError(err, {
|
|
2689
|
+
phase: "requestTransfer",
|
|
2690
|
+
walletId: String(session.walletId)
|
|
2691
|
+
});
|
|
2692
|
+
this.emit("error", { type: "error", error }, correlationId);
|
|
2693
|
+
throw error;
|
|
2694
|
+
}
|
|
2695
|
+
}
|
|
1693
2696
|
/**
|
|
1694
2697
|
* Subscribe to events
|
|
1695
2698
|
*/
|
|
@@ -1712,28 +2715,55 @@ var PartyLayerClient = class {
|
|
|
1712
2715
|
}
|
|
1713
2716
|
}
|
|
1714
2717
|
/**
|
|
1715
|
-
* Get
|
|
1716
|
-
*
|
|
1717
|
-
* This bridge routes all request() calls through the existing
|
|
1718
|
-
* PartyLayerClient methods and maps events to CIP-0103 format.
|
|
2718
|
+
* Get the stable provider facade for this client.
|
|
1719
2719
|
*
|
|
1720
|
-
*
|
|
1721
|
-
*
|
|
1722
|
-
*
|
|
1723
|
-
*
|
|
2720
|
+
* Browser-native connections expose the official owner's actual accounts,
|
|
2721
|
+
* network, execution/events and raw Ledger API response, including standard
|
|
2722
|
+
* path/query/header request fields. Signing keeps the reviewed encoding policy.
|
|
2723
|
+
* Existing proprietary/custom integrations retain their compatibility bridge.
|
|
2724
|
+
* `createProviderBridge(client)` remains available explicitly for legacy callers.
|
|
2725
|
+
* Full async server user-URL orchestration needs a verified direct provider path.
|
|
1724
2726
|
*
|
|
1725
|
-
*
|
|
1726
|
-
* bridge. For async wallet support, use `PartyLayerProvider` directly.
|
|
1727
|
-
*
|
|
1728
|
-
* @returns CIP-0103 compliant Provider
|
|
2727
|
+
* @returns Stable CIP-0103 provider facade
|
|
1729
2728
|
*/
|
|
1730
2729
|
asProvider() {
|
|
1731
|
-
|
|
2730
|
+
if (!this.sessionProvider) {
|
|
2731
|
+
this.sessionProvider = createSessionProvider({
|
|
2732
|
+
bridge: createProviderBridge(this),
|
|
2733
|
+
native: () => {
|
|
2734
|
+
const session = this.activeSession;
|
|
2735
|
+
const adapter = session && this.adapters.get(session.walletId);
|
|
2736
|
+
if (!adapter || !nativeOwnerBindings.has(adapter) || !this.nativeOwner?.getSession()) return null;
|
|
2737
|
+
return this.nativeOwner.getProvider(String(session.walletId));
|
|
2738
|
+
},
|
|
2739
|
+
ensureSession: () => this.getActiveSession(),
|
|
2740
|
+
guardNetwork: () => {
|
|
2741
|
+
if (this.activeSession) this.assertNetworkOk(this.activeSession);
|
|
2742
|
+
},
|
|
2743
|
+
subscribe: (changed) => {
|
|
2744
|
+
const connected = this.on("session:connected", changed);
|
|
2745
|
+
const disconnected2 = this.on("session:disconnected", changed);
|
|
2746
|
+
const expired = this.on("session:expired", changed);
|
|
2747
|
+
return () => {
|
|
2748
|
+
connected();
|
|
2749
|
+
disconnected2();
|
|
2750
|
+
expired();
|
|
2751
|
+
};
|
|
2752
|
+
}
|
|
2753
|
+
});
|
|
2754
|
+
}
|
|
2755
|
+
return this.sessionProvider.provider;
|
|
1732
2756
|
}
|
|
1733
2757
|
/**
|
|
1734
2758
|
* Destroy client and cleanup
|
|
1735
2759
|
*/
|
|
1736
2760
|
destroy() {
|
|
2761
|
+
if (this.destroyed) return;
|
|
2762
|
+
++this.sessionRevision;
|
|
2763
|
+
++this.connectionAttempt;
|
|
2764
|
+
this.destroyed = true;
|
|
2765
|
+
this.sessionProvider?.destroy();
|
|
2766
|
+
this.nativeOwner?.destroy();
|
|
1737
2767
|
if (this.telemetry && "destroy" in this.telemetry && typeof this.telemetry.destroy === "function") {
|
|
1738
2768
|
this.telemetry.destroy();
|
|
1739
2769
|
} else if (this.telemetry?.flush) {
|
|
@@ -1743,6 +2773,8 @@ var PartyLayerClient = class {
|
|
|
1743
2773
|
this.announceUnsubscribe?.();
|
|
1744
2774
|
this.announceUnsubscribe = null;
|
|
1745
2775
|
this.announceRegistry.clear();
|
|
2776
|
+
for (const channel of this.announceChannels.values()) channel.destroy();
|
|
2777
|
+
this.announceChannels.clear();
|
|
1746
2778
|
if (this.walletsChangedTimer !== null) {
|
|
1747
2779
|
clearTimeout(this.walletsChangedTimer);
|
|
1748
2780
|
this.walletsChangedTimer = null;
|
|
@@ -1778,10 +2810,16 @@ var PartyLayerClient = class {
|
|
|
1778
2810
|
* Persist session to storage
|
|
1779
2811
|
*/
|
|
1780
2812
|
async persistSession(session) {
|
|
2813
|
+
const revision = this.sessionRevision;
|
|
1781
2814
|
try {
|
|
1782
2815
|
const data = JSON.stringify(session);
|
|
1783
2816
|
const encrypted = await this.crypto.encrypt(data, this.origin);
|
|
1784
|
-
|
|
2817
|
+
const write = this.sessionStorageQueue.then(async () => {
|
|
2818
|
+
if (!this.destroyed && revision === this.sessionRevision) await this.storage.set(SESSION_STORAGE_KEY, encrypted);
|
|
2819
|
+
});
|
|
2820
|
+
this.sessionStorageQueue = write.catch(() => {
|
|
2821
|
+
});
|
|
2822
|
+
await write;
|
|
1785
2823
|
} catch (err) {
|
|
1786
2824
|
this.log("warn", "session:persist_failed", "Failed to persist session", {
|
|
1787
2825
|
error: err instanceof Error ? err.message : String(err)
|
|
@@ -1795,8 +2833,14 @@ var PartyLayerClient = class {
|
|
|
1795
2833
|
* active session we always remove the single SESSION_STORAGE_KEY.
|
|
1796
2834
|
*/
|
|
1797
2835
|
async removeSession(_sessionId) {
|
|
2836
|
+
const revision = this.sessionRevision;
|
|
1798
2837
|
try {
|
|
1799
|
-
|
|
2838
|
+
const remove = this.sessionStorageQueue.then(async () => {
|
|
2839
|
+
if (!this.destroyed && revision === this.sessionRevision) await this.storage.remove(SESSION_STORAGE_KEY);
|
|
2840
|
+
});
|
|
2841
|
+
this.sessionStorageQueue = remove.catch(() => {
|
|
2842
|
+
});
|
|
2843
|
+
await remove;
|
|
1800
2844
|
} catch (err) {
|
|
1801
2845
|
this.log("warn", "session:remove_failed", "Failed to remove session", {
|
|
1802
2846
|
error: err instanceof Error ? err.message : String(err)
|
|
@@ -1806,16 +2850,31 @@ var PartyLayerClient = class {
|
|
|
1806
2850
|
/**
|
|
1807
2851
|
* Restore session from storage
|
|
1808
2852
|
*/
|
|
1809
|
-
|
|
2853
|
+
restoreSession() {
|
|
2854
|
+
if (this.destroyed || this.restorationBlocked) return Promise.resolve(null);
|
|
2855
|
+
if (this.restoreTask) return this.restoreTask;
|
|
2856
|
+
const task = this.restoreSessionOnce();
|
|
2857
|
+
this.restoreTask = task;
|
|
2858
|
+
const clear = () => {
|
|
2859
|
+
if (this.restoreTask === task) this.restoreTask = null;
|
|
2860
|
+
};
|
|
2861
|
+
void task.then(clear, clear);
|
|
2862
|
+
return task;
|
|
2863
|
+
}
|
|
2864
|
+
async restoreSessionOnce() {
|
|
2865
|
+
const revision = this.sessionRevision;
|
|
2866
|
+
const current = () => !this.destroyed && !this.restorationBlocked && revision === this.sessionRevision;
|
|
1810
2867
|
this.telemetry?.increment?.(METRICS.RESTORE_ATTEMPTS);
|
|
1811
2868
|
const correlationId = newCorrelationId();
|
|
1812
2869
|
this.log("debug", "session:restore_start", "restoreSession", {}, correlationId);
|
|
1813
2870
|
try {
|
|
1814
2871
|
const encrypted = await this.storage.get(SESSION_STORAGE_KEY);
|
|
2872
|
+
if (!current()) return this.activeSession;
|
|
1815
2873
|
if (!encrypted) {
|
|
1816
2874
|
return null;
|
|
1817
2875
|
}
|
|
1818
2876
|
const decrypted = await this.crypto.decrypt(encrypted, this.origin);
|
|
2877
|
+
if (!current()) return this.activeSession;
|
|
1819
2878
|
const session = JSON.parse(decrypted);
|
|
1820
2879
|
if (session.expiresAt && Date.now() >= session.expiresAt) {
|
|
1821
2880
|
await this.removeSession(session.sessionId);
|
|
@@ -1847,7 +2906,17 @@ var PartyLayerClient = class {
|
|
|
1847
2906
|
}
|
|
1848
2907
|
session.networkMismatch = mismatch;
|
|
1849
2908
|
}
|
|
1850
|
-
|
|
2909
|
+
await this.ensureDefaultWallets();
|
|
2910
|
+
if (!current()) return this.activeSession;
|
|
2911
|
+
let adapter = this.adapters.get(session.walletId);
|
|
2912
|
+
if (this.nativeOwner && !adapter) {
|
|
2913
|
+
try {
|
|
2914
|
+
await this.aggregateAnnouncedWallets(await this.registryClient.getWallets());
|
|
2915
|
+
} catch {
|
|
2916
|
+
}
|
|
2917
|
+
if (!current()) return this.activeSession;
|
|
2918
|
+
adapter = this.adapters.get(session.walletId);
|
|
2919
|
+
}
|
|
1851
2920
|
if (adapter?.restore) {
|
|
1852
2921
|
const ctx = this.createAdapterContext();
|
|
1853
2922
|
if (adapter instanceof GenericDiscoveryAdapter && adapter.usesFactory()) {
|
|
@@ -1867,10 +2936,12 @@ var PartyLayerClient = class {
|
|
|
1867
2936
|
...session,
|
|
1868
2937
|
encrypted
|
|
1869
2938
|
});
|
|
1870
|
-
if (
|
|
2939
|
+
if (!current()) return this.activeSession;
|
|
2940
|
+
if (restored && restored.partyId === session.partyId && !detectNetworkMismatch(session.network, restored.network)) {
|
|
1871
2941
|
this.activeSession = restored;
|
|
1872
2942
|
this.activeSessionNeedsProbe = false;
|
|
1873
2943
|
await this.persistSession(restored);
|
|
2944
|
+
if (!current()) return this.activeSession;
|
|
1874
2945
|
this.telemetry?.increment?.(METRICS.SESSIONS_RESTORED);
|
|
1875
2946
|
this.telemetry?.increment?.(METRICS.WALLET_CONNECT_SUCCESS);
|
|
1876
2947
|
this.emit("session:connected", {
|
|
@@ -1887,6 +2958,11 @@ var PartyLayerClient = class {
|
|
|
1887
2958
|
return null;
|
|
1888
2959
|
}
|
|
1889
2960
|
}
|
|
2961
|
+
if (this.nativeOwner && (!adapter || nativeOwnerBindings.has(adapter))) {
|
|
2962
|
+
await this.removeSession(session.sessionId);
|
|
2963
|
+
this.emit("session:expired", { type: "session:expired", sessionId: session.sessionId }, correlationId);
|
|
2964
|
+
return null;
|
|
2965
|
+
}
|
|
1890
2966
|
this.activeSession = session;
|
|
1891
2967
|
this.activeSessionNeedsProbe = true;
|
|
1892
2968
|
return session;
|
|
@@ -1994,6 +3070,6 @@ function createPartyLayer(config) {
|
|
|
1994
3070
|
return new PartyLayerClient(config);
|
|
1995
3071
|
}
|
|
1996
3072
|
|
|
1997
|
-
export { ANNOUNCED_WALLET_ID_PREFIX, PartyLayerClient as CantonConnectClient, DEFAULT_REGISTRY_URL, GenericAnnounceAdapter, GenericDiscoveryAdapter, MetricsTelemetryAdapter, PartyLayerClient, announcedWalletId, createPartyLayer as createCantonConnect, createPartyLayer, createTelemetryAdapter, getBuiltinAdapters, isTelemetryConfig };
|
|
3073
|
+
export { ANNOUNCED_WALLET_ID_PREFIX, PartyLayerClient as CantonConnectClient, DEFAULT_REGISTRY_URL, GenericAnnounceAdapter, GenericDiscoveryAdapter, MetricsTelemetryAdapter, PartyLayerClient, announcedWalletId, createPartyLayer as createCantonConnect, createPartyLayer, createTelemetryAdapter, getBuiltinAdapters, getDiscoveryCapabilities, isTelemetryConfig };
|
|
1998
3074
|
//# sourceMappingURL=index.mjs.map
|
|
1999
3075
|
//# sourceMappingURL=index.mjs.map
|