@ab-org/sdk-core 0.0.1 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/index.d.ts +536 -16
  2. package/dist/index.js +1776 -16
  3. package/package.json +5 -3
  4. package/dist/core/capabilities.d.ts +0 -32
  5. package/dist/core/capabilities.js +0 -88
  6. package/dist/core/chains.d.ts +0 -23
  7. package/dist/core/chains.js +0 -83
  8. package/dist/core/errors.d.ts +0 -9
  9. package/dist/core/errors.js +0 -51
  10. package/dist/core/sessionStore.d.ts +0 -26
  11. package/dist/core/sessionStore.js +0 -129
  12. package/dist/core/types.d.ts +0 -75
  13. package/dist/core/types.js +0 -1
  14. package/dist/core/walletConnector.d.ts +0 -29
  15. package/dist/core/walletConnector.js +0 -153
  16. package/dist/core/walletExecution.d.ts +0 -22
  17. package/dist/core/walletExecution.js +0 -89
  18. package/dist/hooks/useAccount.d.ts +0 -11
  19. package/dist/hooks/useAccount.js +0 -32
  20. package/dist/hooks/useWalletConnect.d.ts +0 -16
  21. package/dist/hooks/useWalletConnect.js +0 -24
  22. package/dist/providers/base.d.ts +0 -15
  23. package/dist/providers/base.js +0 -30
  24. package/dist/providers/plugin/injectedEvmProvider.d.ts +0 -112
  25. package/dist/providers/plugin/injectedEvmProvider.js +0 -326
  26. package/dist/providers/plugin/injectedWalletRegistry.d.ts +0 -9
  27. package/dist/providers/plugin/injectedWalletRegistry.js +0 -34
  28. package/dist/providers/plugin/metamaskProvider.d.ts +0 -1
  29. package/dist/providers/plugin/metamaskProvider.js +0 -1
  30. package/dist/providers/social/baseSocialProvider.d.ts +0 -21
  31. package/dist/providers/social/baseSocialProvider.js +0 -11
  32. package/dist/providers/social/cubeSignerAuth.d.ts +0 -89
  33. package/dist/providers/social/cubeSignerAuth.js +0 -128
  34. package/dist/providers/social/cubistEvmWalletProvider.d.ts +0 -9
  35. package/dist/providers/social/cubistEvmWalletProvider.js +0 -175
  36. package/dist/providers/social/cubistProvider.d.ts +0 -52
  37. package/dist/providers/social/cubistProvider.js +0 -160
package/dist/index.js CHANGED
@@ -1,16 +1,1776 @@
1
- export * from "./core/types.js";
2
- export * from "./core/chains.js";
3
- export * from "./core/capabilities.js";
4
- export * from "./core/errors.js";
5
- export * from "./core/sessionStore.js";
6
- export * from "./core/walletConnector.js";
7
- export * from "./core/walletExecution.js";
8
- export * from "./hooks/useWalletConnect.js";
9
- export * from "./hooks/useAccount.js";
10
- export * from "./providers/base.js";
11
- export * from "./providers/plugin/injectedEvmProvider.js";
12
- export * from "./providers/plugin/injectedWalletRegistry.js";
13
- export * from "./providers/plugin/metamaskProvider.js";
14
- export * from "./providers/social/baseSocialProvider.js";
15
- export * from "./providers/social/cubeSignerAuth.js";
16
- export * from "./providers/social/cubistProvider.js";
1
+ import EventEmitter from 'eventemitter3';
2
+ import { CubeSignerClient, MemorySessionManager, envs, EvmSigner } from '@cubist-labs/cubesigner-sdk';
3
+
4
+ // src/core/chains.ts
5
+ var chainDescriptors = {
6
+ AB_CORE: {
7
+ chain: "AB_CORE",
8
+ namespace: "ab-core",
9
+ reference: "ab:core",
10
+ label: "AB Core",
11
+ rpcFamily: "custom",
12
+ supportsSmartSessions: true,
13
+ supportsAccountAbstraction: true
14
+ },
15
+ ETH: {
16
+ chain: "ETH",
17
+ namespace: "evm",
18
+ reference: "eip155:1",
19
+ label: "Ethereum",
20
+ rpcFamily: "evm",
21
+ evmChainId: 1,
22
+ supportsSmartSessions: true,
23
+ supportsAccountAbstraction: true
24
+ },
25
+ BSC: {
26
+ chain: "BSC",
27
+ namespace: "evm",
28
+ reference: "eip155:56",
29
+ label: "BNB Smart Chain",
30
+ rpcFamily: "evm",
31
+ evmChainId: 56,
32
+ supportsSmartSessions: true,
33
+ supportsAccountAbstraction: false
34
+ },
35
+ ETH_TENDERLY: {
36
+ chain: "ETH_TENDERLY",
37
+ namespace: "evm",
38
+ reference: "eip155:3030",
39
+ label: "Ethereum Tenderly",
40
+ rpcFamily: "evm",
41
+ evmChainId: 3030,
42
+ supportsSmartSessions: true,
43
+ supportsAccountAbstraction: true
44
+ },
45
+ BSC_TENDERLY: {
46
+ chain: "BSC_TENDERLY",
47
+ namespace: "evm",
48
+ reference: "eip155:3131",
49
+ label: "BNB Smart Chain Tenderly",
50
+ rpcFamily: "evm",
51
+ evmChainId: 3131,
52
+ supportsSmartSessions: true,
53
+ supportsAccountAbstraction: false
54
+ },
55
+ SOL: {
56
+ chain: "SOL",
57
+ namespace: "solana",
58
+ reference: "solana:mainnet-beta",
59
+ label: "Solana",
60
+ rpcFamily: "solana",
61
+ supportsSmartSessions: true,
62
+ supportsAccountAbstraction: false
63
+ }
64
+ };
65
+ var getChainDescriptor = (chain) => chainDescriptors[chain];
66
+ var getAllChainDescriptors = () => Object.values(chainDescriptors);
67
+ var normalizeEvmChainId = (value) => {
68
+ if (typeof value === "number") return value;
69
+ if (typeof value === "bigint") return Number(value);
70
+ return Number(BigInt(value));
71
+ };
72
+ var getSupportedChainFromEvmChainId = (value) => {
73
+ const chainId = normalizeEvmChainId(value);
74
+ const descriptor = getAllChainDescriptors().find(
75
+ (item) => item.namespace === "evm" && item.evmChainId === chainId
76
+ );
77
+ if (!descriptor) {
78
+ throw new Error(`Unsupported EVM chainId: ${chainId}`);
79
+ }
80
+ return descriptor.chain;
81
+ };
82
+ var createChainContext = (walletChain, settlementChain = walletChain) => ({
83
+ walletChain,
84
+ walletChainDescriptor: getChainDescriptor(walletChain),
85
+ settlementChain,
86
+ settlementChainDescriptor: getChainDescriptor(settlementChain)
87
+ });
88
+
89
+ // src/core/capabilities.ts
90
+ var SessionCapabilityError = class extends Error {
91
+ constructor(message) {
92
+ super(message);
93
+ this.name = "SessionCapabilityError";
94
+ }
95
+ };
96
+ var toBigIntAmount = (value) => {
97
+ if (typeof value === "bigint") return value;
98
+ if (typeof value === "number") return BigInt(value);
99
+ return BigInt(value);
100
+ };
101
+ var createSessionCapabilityPolicy = (input = {}) => ({
102
+ id: input.id ?? `cap:${Date.now()}`,
103
+ appId: input.appId,
104
+ origin: input.origin,
105
+ expiresAt: input.expiresAt,
106
+ methods: input.methods,
107
+ chains: input.chains,
108
+ tokens: input.tokens,
109
+ maxAmount: input.maxAmount,
110
+ revocable: input.revocable ?? true,
111
+ metadata: input.metadata
112
+ });
113
+ var isSessionExpired = (session, now = Date.now()) => Boolean(session?.expiresAt && session.expiresAt <= now);
114
+ var isCapabilityPolicyExpired = (policy, now = Date.now()) => Boolean(policy?.expiresAt && policy.expiresAt <= now);
115
+ var sessionSupportsCapability = (session, capability) => {
116
+ const capabilities = session?.capabilities;
117
+ if (!capabilities || capabilities.length === 0) return true;
118
+ return capabilities.includes(capability);
119
+ };
120
+ var describeSessionCapabilityPolicy = (policy) => {
121
+ if (!policy) return [];
122
+ const lines = [];
123
+ if (policy.origin) lines.push(`Origin: ${policy.origin}`);
124
+ if (policy.appId) lines.push(`App: ${policy.appId}`);
125
+ if (policy.methods?.length) lines.push(`Methods: ${policy.methods.join(", ")}`);
126
+ if (policy.chains?.length) lines.push(`Chains: ${policy.chains.join(", ")}`);
127
+ if (policy.tokens?.length) lines.push(`Tokens: ${policy.tokens.join(", ")}`);
128
+ if (policy.maxAmount) lines.push(`Max amount: ${policy.maxAmount}`);
129
+ if (policy.expiresAt) lines.push(`Expires at: ${new Date(policy.expiresAt).toISOString()}`);
130
+ return lines;
131
+ };
132
+ var assertSessionCapability = (session, check) => {
133
+ const now = check.now ?? Date.now();
134
+ if (isSessionExpired(session, now)) {
135
+ throw new SessionCapabilityError("Wallet session has expired");
136
+ }
137
+ const policy = session.capabilityPolicy;
138
+ if (isCapabilityPolicyExpired(policy, now)) {
139
+ throw new SessionCapabilityError("Capability session has expired");
140
+ }
141
+ if (!sessionSupportsCapability(session, check.capability)) {
142
+ throw new SessionCapabilityError(
143
+ `Wallet session does not support capability "${check.capability}"`
144
+ );
145
+ }
146
+ if (!policy) return;
147
+ if (policy.appId && check.appId && policy.appId !== check.appId) {
148
+ throw new SessionCapabilityError("Capability session is scoped to a different app");
149
+ }
150
+ if (policy.origin && check.origin && policy.origin !== check.origin) {
151
+ throw new SessionCapabilityError("Capability session is scoped to a different origin");
152
+ }
153
+ if (policy.methods?.length && !policy.methods.includes(check.capability)) {
154
+ throw new SessionCapabilityError(
155
+ `Capability "${check.capability}" is not allowed for this session`
156
+ );
157
+ }
158
+ if (check.chain && policy.chains?.length && !policy.chains.includes(check.chain)) {
159
+ throw new SessionCapabilityError(`Chain "${check.chain}" is not allowed for this session`);
160
+ }
161
+ if (check.token && policy.tokens?.length && !policy.tokens.includes(check.token)) {
162
+ throw new SessionCapabilityError(`Token "${check.token}" is not allowed for this session`);
163
+ }
164
+ if (policy.maxAmount && check.amount !== void 0) {
165
+ if (toBigIntAmount(check.amount) > toBigIntAmount(policy.maxAmount)) {
166
+ throw new SessionCapabilityError("Requested amount exceeds the capability session limit");
167
+ }
168
+ }
169
+ };
170
+
171
+ // src/core/errors.ts
172
+ var EVM_TRANSACTION_SIGNING_UNSUPPORTED = "EVM_TRANSACTION_SIGNING_UNSUPPORTED";
173
+ var EvmTransactionSigningUnsupportedError = class extends Error {
174
+ constructor(providerName, cause) {
175
+ super(`${providerName} does not support EVM transaction signing`);
176
+ this.providerName = providerName;
177
+ this.cause = cause;
178
+ this.code = EVM_TRANSACTION_SIGNING_UNSUPPORTED;
179
+ this.name = "EvmTransactionSigningUnsupportedError";
180
+ }
181
+ };
182
+ var getErrorCode = (error) => {
183
+ if (typeof error !== "object" || error === null || !("code" in error)) return void 0;
184
+ const { code } = error;
185
+ return typeof code === "number" || typeof code === "string" ? code : void 0;
186
+ };
187
+ var getErrorMessage = (error) => {
188
+ if (error instanceof Error) return error.message;
189
+ if (typeof error === "object" && error !== null && "message" in error) {
190
+ const { message } = error;
191
+ if (typeof message === "string") return message;
192
+ }
193
+ return String(error);
194
+ };
195
+ var isUnsupportedEvmTransactionSigningError = (error) => {
196
+ if (error instanceof EvmTransactionSigningUnsupportedError) {
197
+ return true;
198
+ }
199
+ const code = getErrorCode(error);
200
+ if (code === 4200 || code === -32601) {
201
+ return true;
202
+ }
203
+ const message = getErrorMessage(error).toLowerCase();
204
+ return message.includes("eth_signtransaction") && (message.includes("unsupported") || message.includes("not support") || message.includes("not found") || message.includes("does not exist") || message.includes("unrecognized"));
205
+ };
206
+ var normalizeEvmTransactionSigningError = (providerName, error) => {
207
+ if (error instanceof Error && !isUnsupportedEvmTransactionSigningError(error)) {
208
+ return error;
209
+ }
210
+ if (isUnsupportedEvmTransactionSigningError(error)) {
211
+ return new EvmTransactionSigningUnsupportedError(providerName, error);
212
+ }
213
+ return error instanceof Error ? error : new Error(String(error));
214
+ };
215
+ var STORAGE_KEY = "ab:wallet:session";
216
+ function getStorage() {
217
+ try {
218
+ return typeof localStorage !== "undefined" ? localStorage : null;
219
+ } catch {
220
+ return null;
221
+ }
222
+ }
223
+ function persistSession(session) {
224
+ const storage = getStorage();
225
+ if (!storage) return;
226
+ if (!session) {
227
+ storage.removeItem(STORAGE_KEY);
228
+ return;
229
+ }
230
+ const serializable = {
231
+ address: session.address,
232
+ chain: session.chain,
233
+ walletType: session.walletType,
234
+ authSource: session.authSource,
235
+ sessionId: session.sessionId,
236
+ expiresAt: session.expiresAt
237
+ };
238
+ if (session.capabilities?.length) {
239
+ serializable.capabilities = session.capabilities;
240
+ }
241
+ try {
242
+ storage.setItem(STORAGE_KEY, JSON.stringify(serializable));
243
+ } catch {
244
+ storage.removeItem(STORAGE_KEY);
245
+ }
246
+ }
247
+ function readPersistedSession() {
248
+ const storage = getStorage();
249
+ if (!storage) return null;
250
+ const raw = storage.getItem(STORAGE_KEY);
251
+ if (!raw) return null;
252
+ try {
253
+ return JSON.parse(raw);
254
+ } catch {
255
+ storage.removeItem(STORAGE_KEY);
256
+ return null;
257
+ }
258
+ }
259
+ var staleProvider = {
260
+ request() {
261
+ return Promise.reject(
262
+ new Error("Session restored from cache. Reconnect your wallet for transactions.")
263
+ );
264
+ },
265
+ disconnect() {
266
+ return Promise.resolve();
267
+ }
268
+ };
269
+ var SessionStore = class {
270
+ constructor() {
271
+ this.state = {
272
+ session: null,
273
+ balance: null,
274
+ isConnecting: false
275
+ };
276
+ this.emitter = new EventEmitter();
277
+ this.tryRehydrate();
278
+ }
279
+ getState() {
280
+ return { ...this.state };
281
+ }
282
+ setConnecting(flag) {
283
+ this.state.isConnecting = flag;
284
+ this.emitter.emit("connecting:changed", flag);
285
+ }
286
+ setSession(session) {
287
+ this.state.session = session;
288
+ persistSession(session);
289
+ this.emitter.emit("session:changed", session);
290
+ }
291
+ rehydrateSession(session) {
292
+ this.state.session = session;
293
+ persistSession(session);
294
+ this.emitter.emit("session:changed", session);
295
+ this.emitter.emit("session:rehydrated", session);
296
+ }
297
+ clearSession() {
298
+ this.state.session = null;
299
+ this.state.balance = null;
300
+ persistSession(null);
301
+ this.emitter.emit("session:changed", null);
302
+ this.emitter.emit("balance:changed", null);
303
+ }
304
+ expireSession() {
305
+ const currentSession = this.state.session;
306
+ if (!currentSession) return;
307
+ this.clearSession();
308
+ this.emitter.emit("session:expired", currentSession);
309
+ }
310
+ revokeSession() {
311
+ const currentSession = this.state.session;
312
+ if (!currentSession) return;
313
+ this.clearSession();
314
+ this.emitter.emit("session:revoked", currentSession);
315
+ }
316
+ setBalance(balance) {
317
+ this.state.balance = balance;
318
+ this.emitter.emit("balance:changed", balance);
319
+ }
320
+ on(event, listener) {
321
+ this.emitter.on(event, listener);
322
+ return () => this.emitter.off(event, listener);
323
+ }
324
+ tryRehydrate() {
325
+ const persisted = readPersistedSession();
326
+ if (!persisted) return;
327
+ if (persisted.expiresAt && persisted.expiresAt <= Date.now()) {
328
+ persistSession(null);
329
+ return;
330
+ }
331
+ this.state.session = { ...persisted, provider: staleProvider };
332
+ }
333
+ };
334
+ var sessionStore = new SessionStore();
335
+
336
+ // src/core/walletExecution.ts
337
+ var requireSession = (session) => {
338
+ const resolvedSession = session ?? sessionStore.getState().session;
339
+ if (!resolvedSession) {
340
+ throw new Error("Wallet session missing");
341
+ }
342
+ return resolvedSession;
343
+ };
344
+ var performCapabilityCheck = (session, capability, check) => {
345
+ assertSessionCapability(session, {
346
+ capability,
347
+ chain: check?.chain ?? session.chainContext?.walletChain ?? session.chain,
348
+ token: check?.token,
349
+ amount: check?.amount,
350
+ appId: check?.appId,
351
+ origin: check?.origin,
352
+ now: check?.now
353
+ });
354
+ };
355
+ var getWalletExecutionCapabilities = (session) => requireSession(session).capabilities ?? [];
356
+ var createWalletExecutionClient = (session) => {
357
+ const resolvedSession = requireSession(session);
358
+ return {
359
+ session: resolvedSession,
360
+ capabilities: resolvedSession.capabilities ?? [],
361
+ supports(capability) {
362
+ return this.capabilities.length === 0 || this.capabilities.includes(capability);
363
+ },
364
+ async sendTransaction(transaction, check) {
365
+ performCapabilityCheck(resolvedSession, "eth_sendTransaction", {
366
+ ...check,
367
+ amount: check?.amount ?? transaction.value
368
+ });
369
+ return resolvedSession.provider.request({
370
+ method: "eth_sendTransaction",
371
+ params: [{ ...transaction, from: transaction.from ?? resolvedSession.address }]
372
+ });
373
+ },
374
+ async signTransaction(transaction, check) {
375
+ performCapabilityCheck(resolvedSession, "eth_signTransaction", {
376
+ ...check,
377
+ amount: check?.amount ?? transaction.value
378
+ });
379
+ return resolvedSession.provider.request({
380
+ method: "eth_signTransaction",
381
+ params: [{ ...transaction, from: transaction.from ?? resolvedSession.address }]
382
+ });
383
+ },
384
+ async signMessage(message, check) {
385
+ performCapabilityCheck(resolvedSession, "personal_sign", check);
386
+ return resolvedSession.provider.request({
387
+ method: "personal_sign",
388
+ params: [message, resolvedSession.address]
389
+ });
390
+ },
391
+ async signTypedData(typedData, check) {
392
+ performCapabilityCheck(resolvedSession, "eth_signTypedData_v4", check);
393
+ return resolvedSession.provider.request({
394
+ method: "eth_signTypedData_v4",
395
+ params: [resolvedSession.address, JSON.stringify(typedData)]
396
+ });
397
+ }
398
+ };
399
+ };
400
+ var createWalletExecutionController = () => ({
401
+ get session() {
402
+ return sessionStore.getState().session;
403
+ },
404
+ get capabilities() {
405
+ return sessionStore.getState().session?.capabilities ?? [];
406
+ },
407
+ supports(capability) {
408
+ const session = requireSession();
409
+ return createWalletExecutionClient(session).supports(capability);
410
+ },
411
+ sendTransaction(transaction, check) {
412
+ return createWalletExecutionClient().sendTransaction(transaction, check);
413
+ },
414
+ signTransaction(transaction, check) {
415
+ return createWalletExecutionClient().signTransaction(transaction, check);
416
+ },
417
+ signMessage(message, check) {
418
+ return createWalletExecutionClient().signMessage(message, check);
419
+ },
420
+ signTypedData(typedData, check) {
421
+ return createWalletExecutionClient().signTypedData(typedData, check);
422
+ }
423
+ });
424
+
425
+ // src/core/walletConnector.ts
426
+ var ADAPTER_STORAGE_KEY = "ab:wallet:adapterId";
427
+ function getStorage2() {
428
+ try {
429
+ return typeof localStorage !== "undefined" ? localStorage : null;
430
+ } catch {
431
+ return null;
432
+ }
433
+ }
434
+ function persistAdapterId(adapterId) {
435
+ const storage = getStorage2();
436
+ if (!storage) return;
437
+ if (!adapterId) {
438
+ storage.removeItem(ADAPTER_STORAGE_KEY);
439
+ } else {
440
+ storage.setItem(ADAPTER_STORAGE_KEY, adapterId);
441
+ }
442
+ }
443
+ function readPersistedAdapterId() {
444
+ const storage = getStorage2();
445
+ if (!storage) return null;
446
+ return storage.getItem(ADAPTER_STORAGE_KEY);
447
+ }
448
+ var WalletConnector = class {
449
+ constructor(adapters) {
450
+ this.adapters = adapters;
451
+ this.currentAdapterId = null;
452
+ this.currentAdapterId = readPersistedAdapterId();
453
+ }
454
+ getAdapterById(adapterId) {
455
+ const adapter = this.adapters.find((item) => item.id === adapterId);
456
+ if (!adapter) throw new Error(`Wallet adapter ${adapterId} not registered`);
457
+ return adapter;
458
+ }
459
+ getCurrentAdapter(session = sessionStore.getState().session) {
460
+ return (this.currentAdapterId ? this.adapters.find((item) => item.id === this.currentAdapterId) : void 0) ?? this.adapters.find((item) => item.getProvider() === session?.provider);
461
+ }
462
+ clearActiveSession() {
463
+ this.currentAdapterId = null;
464
+ persistAdapterId(null);
465
+ sessionStore.clearSession();
466
+ }
467
+ requireActiveSession() {
468
+ const session = sessionStore.getState().session;
469
+ if (!session) {
470
+ throw new Error("Wallet session missing");
471
+ }
472
+ return session;
473
+ }
474
+ async connect(adapterId, args) {
475
+ const adapter = this.getAdapterById(adapterId);
476
+ const currentAdapter = this.getCurrentAdapter();
477
+ if (currentAdapter && currentAdapter.id !== adapter.id) {
478
+ await currentAdapter.disconnect();
479
+ this.clearActiveSession();
480
+ }
481
+ sessionStore.setConnecting(true);
482
+ try {
483
+ const session = await adapter.connect(args);
484
+ this.currentAdapterId = adapter.id;
485
+ persistAdapterId(adapter.id);
486
+ sessionStore.setSession(session);
487
+ sessionStore.setBalance(null);
488
+ return session;
489
+ } finally {
490
+ sessionStore.setConnecting(false);
491
+ }
492
+ }
493
+ async disconnect() {
494
+ const adapter = this.getCurrentAdapter();
495
+ if (!adapter) return;
496
+ await adapter?.disconnect();
497
+ this.clearActiveSession();
498
+ }
499
+ rehydrateSession(adapterId, session) {
500
+ this.currentAdapterId = adapterId;
501
+ persistAdapterId(adapterId);
502
+ sessionStore.rehydrateSession(session);
503
+ sessionStore.setBalance(null);
504
+ return session;
505
+ }
506
+ /**
507
+ * Attempt to silently reconnect a wallet whose session was rehydrated
508
+ * from localStorage. Uses the adapter's `reconnect()` if available,
509
+ * falling back to `connect()` for backward compatibility.
510
+ *
511
+ * Returns the restored session on success, or `null` if reconnection
512
+ * is not possible (e.g. wallet extension removed, social session expired).
513
+ */
514
+ async tryAutoReconnect() {
515
+ const state = sessionStore.getState();
516
+ if (!state.session) return null;
517
+ const adapterId = this.currentAdapterId ?? readPersistedAdapterId();
518
+ if (!adapterId) return null;
519
+ const adapter = this.adapters.find((a) => a.id === adapterId);
520
+ if (!adapter) return null;
521
+ sessionStore.setConnecting(true);
522
+ try {
523
+ const session = adapter.reconnect ? await adapter.reconnect(state.session) : null;
524
+ if (!session) return null;
525
+ this.currentAdapterId = adapterId;
526
+ persistAdapterId(adapterId);
527
+ sessionStore.rehydrateSession(session);
528
+ return session;
529
+ } catch {
530
+ return null;
531
+ } finally {
532
+ sessionStore.setConnecting(false);
533
+ }
534
+ }
535
+ supportsCapability(capability) {
536
+ const session = this.requireActiveSession();
537
+ return createWalletExecutionClient(session).supports(capability);
538
+ }
539
+ async requestCurrentProvider(payload) {
540
+ return this.requireActiveSession().provider.request(payload);
541
+ }
542
+ async sendEvmTransaction(transaction) {
543
+ const session = this.requireActiveSession();
544
+ return createWalletExecutionClient(session).sendTransaction(transaction);
545
+ }
546
+ async signEvmTransaction(transaction) {
547
+ const session = this.requireActiveSession();
548
+ return createWalletExecutionClient(session).signTransaction(transaction);
549
+ }
550
+ async signMessage(message) {
551
+ const session = this.requireActiveSession();
552
+ return createWalletExecutionClient(session).signMessage(message);
553
+ }
554
+ async signTypedData(typedData) {
555
+ const session = this.requireActiveSession();
556
+ return createWalletExecutionClient(session).signTypedData(typedData);
557
+ }
558
+ };
559
+
560
+ // src/hooks/useWalletConnect.ts
561
+ var createWalletConnectController = ({
562
+ connector,
563
+ defaultAdapterId
564
+ }) => {
565
+ return {
566
+ openModal: async (adapterId = defaultAdapterId, args) => {
567
+ if (!adapterId) throw new Error("No adapter id provided");
568
+ await connector.connect(adapterId, args);
569
+ },
570
+ disconnect: () => connector.disconnect(),
571
+ rehydrate: (adapterId, session) => connector.rehydrateSession(adapterId, session),
572
+ tryAutoReconnect: () => connector.tryAutoReconnect(),
573
+ supports(capability) {
574
+ if (!sessionStore.getState().session) return false;
575
+ return connector.supportsCapability(capability);
576
+ },
577
+ get isConnected() {
578
+ return Boolean(sessionStore.getState().session);
579
+ },
580
+ get isConnecting() {
581
+ return sessionStore.getState().isConnecting;
582
+ }
583
+ };
584
+ };
585
+
586
+ // src/hooks/useAccount.ts
587
+ var createAccountController = () => {
588
+ return {
589
+ get session() {
590
+ return sessionStore.getState().session;
591
+ },
592
+ get address() {
593
+ return sessionStore.getState().session?.address ?? null;
594
+ },
595
+ get chain() {
596
+ return sessionStore.getState().session?.chain ?? null;
597
+ },
598
+ get balance() {
599
+ return sessionStore.getState().balance;
600
+ },
601
+ get isConnected() {
602
+ return Boolean(sessionStore.getState().session);
603
+ },
604
+ get currentProvider() {
605
+ return sessionStore.getState().session?.provider ?? null;
606
+ },
607
+ get chainContext() {
608
+ return sessionStore.getState().session?.chainContext ?? null;
609
+ },
610
+ get capabilities() {
611
+ return sessionStore.getState().session?.capabilities ?? [];
612
+ },
613
+ get capabilityPolicy() {
614
+ return sessionStore.getState().session?.capabilityPolicy ?? null;
615
+ }
616
+ };
617
+ };
618
+
619
+ // src/providers/base.ts
620
+ var AbstractProvider = class {
621
+ constructor() {
622
+ this.currentSession = null;
623
+ }
624
+ async disconnect() {
625
+ this.clearSession();
626
+ }
627
+ setSession(session) {
628
+ this.currentSession = session;
629
+ return session;
630
+ }
631
+ clearSession() {
632
+ this.currentSession = null;
633
+ }
634
+ get session() {
635
+ return this.currentSession;
636
+ }
637
+ requireSession(message = `${this.title} session missing`) {
638
+ if (!this.currentSession) {
639
+ throw new Error(message);
640
+ }
641
+ return this.currentSession;
642
+ }
643
+ getProvider() {
644
+ return this.currentSession?.provider ?? null;
645
+ }
646
+ async reconnect(_persistedSession) {
647
+ return null;
648
+ }
649
+ };
650
+
651
+ // ../wallet-utils/dist/index.js
652
+ var __defProp = Object.defineProperty;
653
+ var __export = (target, all) => {
654
+ for (var name in all)
655
+ __defProp(target, name, { get: all[name], enumerable: true });
656
+ };
657
+ var cache_exports = {};
658
+ __export(cache_exports, {
659
+ clear: () => clear,
660
+ get: () => get,
661
+ remove: () => remove,
662
+ set: () => set,
663
+ setKeyNS: () => setKeyNS
664
+ });
665
+ var keyNS = "tomo-";
666
+ function get(key) {
667
+ if (typeof window === "undefined") {
668
+ return null;
669
+ }
670
+ const tempKey = keyNS + key;
671
+ if (!isKeyExist(tempKey)) {
672
+ return null;
673
+ }
674
+ let val = null;
675
+ try {
676
+ const data = window.localStorage.getItem(tempKey) || window.sessionStorage.getItem(tempKey);
677
+ val = JSON.parse(data);
678
+ } catch (err) {
679
+ console.error(err);
680
+ }
681
+ if (val !== null && Object.prototype.hasOwnProperty.call(val, "type") && Object.prototype.hasOwnProperty.call(val, "data")) {
682
+ return val["data"];
683
+ }
684
+ return null;
685
+ }
686
+ function set(key, val, isTemp) {
687
+ if (typeof window === "undefined") {
688
+ return false;
689
+ }
690
+ let store;
691
+ if (isTemp) {
692
+ store = window.sessionStorage;
693
+ } else {
694
+ store = window.localStorage;
695
+ }
696
+ const data = JSON.stringify({
697
+ data: val,
698
+ time: (/* @__PURE__ */ new Date()).getTime(),
699
+ //for manage by time limit
700
+ type: typeof val
701
+ });
702
+ try {
703
+ store.setItem(keyNS + key, data);
704
+ return true;
705
+ } catch (err) {
706
+ if (err?.name?.toUpperCase().indexOf("QUOTA") >= 0) {
707
+ window.localStorage.clear();
708
+ store.setItem(keyNS + key, data);
709
+ }
710
+ }
711
+ return false;
712
+ }
713
+ function remove(key) {
714
+ if (typeof window === "undefined") {
715
+ return;
716
+ }
717
+ const tempKey = keyNS + key;
718
+ window.localStorage.removeItem(tempKey);
719
+ window.sessionStorage.removeItem(tempKey);
720
+ }
721
+ function clear() {
722
+ if (typeof window === "undefined") {
723
+ return;
724
+ }
725
+ window?.localStorage?.clear();
726
+ window?.sessionStorage?.clear();
727
+ }
728
+ function isKeyExist(key) {
729
+ if (typeof window === "undefined") {
730
+ return false;
731
+ }
732
+ return Object.prototype.hasOwnProperty.call(window.localStorage, key) || Object.prototype.hasOwnProperty.call(window.sessionStorage, key);
733
+ }
734
+ function setKeyNS(NS) {
735
+ const isString = typeof NS === "string";
736
+ if (isString && NS !== "") {
737
+ keyNS = NS;
738
+ }
739
+ }
740
+ function pick(...candidates) {
741
+ for (const c of candidates) {
742
+ if (c != null && c !== "") return c;
743
+ }
744
+ return void 0;
745
+ }
746
+ function nextPublicProcessEnvKey(logicalKey) {
747
+ return `NEXT_PUBLIC_${logicalKey}`;
748
+ }
749
+ function readProcessEnvStatic(key) {
750
+ if (typeof process === "undefined" || !process.env) return void 0;
751
+ switch (key) {
752
+ case "STAGE":
753
+ return pick(
754
+ process.env.NEXT_PUBLIC_STAGE,
755
+ process.env.STAGE
756
+ );
757
+ case "FUNDING_CHAIN_ID":
758
+ return pick(
759
+ process.env.NEXT_PUBLIC_FUNDING_CHAIN_ID,
760
+ process.env.FUNDING_CHAIN_ID
761
+ );
762
+ /** Next.js 仅内联「静态」`process.env.NEXT_PUBLIC_*`;动态键名在客户端会为 undefined,必须逐键写出。 */
763
+ case "GOOGLE_CLIENT_ID":
764
+ return pick(
765
+ process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID,
766
+ process.env.GOOGLE_CLIENT_ID
767
+ );
768
+ case "X_CLIENT_ID":
769
+ return pick(
770
+ process.env.NEXT_PUBLIC_X_CLIENT_ID,
771
+ process.env.X_CLIENT_ID
772
+ );
773
+ case "MERCHANT_BASE_URL":
774
+ return pick(
775
+ process.env.NEXT_PUBLIC_MERCHANT_BASE_URL,
776
+ process.env.MERCHANT_BASE_URL
777
+ );
778
+ case "RELAY_ORIGIN":
779
+ return pick(
780
+ process.env.NEXT_PUBLIC_RELAY_ORIGIN,
781
+ process.env.RELAY_ORIGIN
782
+ );
783
+ case "CUBE_SIGNER_ENV":
784
+ return pick(
785
+ process.env.NEXT_PUBLIC_CUBE_SIGNER_ENV,
786
+ process.env.CUBE_SIGNER_ENV
787
+ );
788
+ case "CUBE_SIGNER_ORG_ID":
789
+ return pick(
790
+ process.env.NEXT_PUBLIC_CUBE_SIGNER_ORG_ID,
791
+ process.env.CUBE_SIGNER_ORG_ID
792
+ );
793
+ case "CUBE_REG":
794
+ return pick(
795
+ process.env.NEXT_PUBLIC_CUBE_REG,
796
+ process.env.CUBE_REG
797
+ );
798
+ case "FUNDING_TOKEN_SYMBOL":
799
+ return pick(
800
+ process.env.NEXT_PUBLIC_FUNDING_TOKEN_SYMBOL,
801
+ process.env.FUNDING_TOKEN_SYMBOL
802
+ );
803
+ case "FUNDING_TOKEN_ADDRESS":
804
+ return pick(
805
+ process.env.NEXT_PUBLIC_FUNDING_TOKEN_ADDRESS,
806
+ process.env.FUNDING_TOKEN_ADDRESS
807
+ );
808
+ default:
809
+ return pick(
810
+ process.env[`NEXT_PUBLIC_${key}`],
811
+ process.env[key]
812
+ );
813
+ }
814
+ }
815
+ function getEnv(key) {
816
+ const staticVal = readProcessEnvStatic(key);
817
+ if (staticVal != null && staticVal !== "") return staticVal;
818
+ const g = globalThis;
819
+ const env = g.process?.env;
820
+ if (env) {
821
+ const pub = nextPublicProcessEnvKey(key);
822
+ const v = env[key] ?? env[pub];
823
+ if (v != null && v !== "") return v;
824
+ }
825
+ try {
826
+ const m = import.meta.env;
827
+ if (m) {
828
+ const pub = nextPublicProcessEnvKey(key);
829
+ const v = m[key] ?? m[pub];
830
+ if (v != null && v !== "") return v;
831
+ }
832
+ } catch {
833
+ }
834
+ console.error(`${key} is not set.`);
835
+ return "";
836
+ }
837
+ var TENDERLY_BSC_3131 = {
838
+ chainId: "3131",
839
+ name: "BSC_TENDERLY",
840
+ chainName: "BSC_TENDERLY",
841
+ nativeCurrencyName: "BSC",
842
+ nativeCurrencySymbol: "BSC",
843
+ nativeCurrencyDecimals: 18,
844
+ rpcUrls: [
845
+ "https://virtual.binance.eu.rpc.tenderly.co/e643ea28-32eb-4fb9-8116-90be24f7defa"
846
+ ],
847
+ blockExplorerUrl: "https://dashboard.tenderly.co/explorer/vnet/6593bc72-f548-497d-bff9-5be061436a48",
848
+ platformType: "EVM",
849
+ icon: "https://static.tomo.inc/token/bsc_new.svg",
850
+ // Tenderly 默认资金侧合约地址(测试环境镜像):
851
+ defaultFundingTokenAddress: "0x55d398326f99059fF775485246999027B3197955"
852
+ };
853
+ var BSC_MAINNET_56 = {
854
+ chainId: "56",
855
+ name: "BSC",
856
+ chainName: "BNB Smart Chain",
857
+ nativeCurrencyName: "BNB",
858
+ nativeCurrencySymbol: "BNB",
859
+ nativeCurrencyDecimals: 18,
860
+ rpcUrls: ["https://bsc-dataseed.binance.org", "https://bsc-dataseed1.defibit.io"],
861
+ blockExplorerUrl: "https://bscscan.com",
862
+ platformType: "EVM",
863
+ icon: "https://static.tomo.inc/token/bsc_new.svg",
864
+ // 主网默认资金侧合约地址(USDT);如需覆盖请使用 FUNDING_TOKEN_ADDRESS 环境变量
865
+ defaultFundingTokenAddress: "0x55d398326f99059fF775485246999027B3197955"
866
+ };
867
+ var CHAIN_REGISTRY = {
868
+ [TENDERLY_BSC_3131.chainId]: TENDERLY_BSC_3131,
869
+ [BSC_MAINNET_56.chainId]: BSC_MAINNET_56
870
+ };
871
+ var DEFAULT_FUNDING_CHAIN_ID = getEnv("FUNDING_CHAIN_ID") || "3131";
872
+ function normalizeFundingChainId(chainId) {
873
+ if (chainId === void 0 || chainId === null) return DEFAULT_FUNDING_CHAIN_ID;
874
+ const s = String(chainId).trim();
875
+ return s === "" ? DEFAULT_FUNDING_CHAIN_ID : s;
876
+ }
877
+ function getChainInfo(chainId) {
878
+ const id = normalizeFundingChainId(chainId);
879
+ const info = CHAIN_REGISTRY[id];
880
+ if (!info) {
881
+ throw new Error(
882
+ `Unsupported funding chainId "${id}". Supported: ${Object.keys(CHAIN_REGISTRY).sort().join(", ")}`
883
+ );
884
+ }
885
+ return info;
886
+ }
887
+ function pickEnvFundingTokenAddress() {
888
+ const tryPairs = [
889
+ ["NEXT_PUBLIC_FUNDING_TOKEN_ADDRESS", "FUNDING_TOKEN_ADDRESS"]
890
+ ];
891
+ if (typeof process !== "undefined" && process.env) {
892
+ for (const [pub, priv] of tryPairs) {
893
+ const a = process.env[pub];
894
+ const b = process.env[priv];
895
+ if (a != null && a !== "") return a;
896
+ if (b != null && b !== "") return b;
897
+ }
898
+ }
899
+ try {
900
+ const m = import.meta.env;
901
+ if (m) {
902
+ for (const [pub, priv] of tryPairs) {
903
+ const a = m[pub];
904
+ const b = m[priv];
905
+ if (a != null && a !== "") return a;
906
+ if (b != null && b !== "") return b;
907
+ }
908
+ }
909
+ } catch {
910
+ }
911
+ return void 0;
912
+ }
913
+ function getFundingTokenAddress(chainId) {
914
+ const v = pickEnvFundingTokenAddress();
915
+ if (v && /^0x[0-9a-fA-F]{40}$/.test(v)) return v;
916
+ return getChainInfo(chainId).defaultFundingTokenAddress;
917
+ }
918
+ getFundingTokenAddress(DEFAULT_FUNDING_CHAIN_ID);
919
+ ({
920
+ google: getEnv("GOOGLE_CLIENT_ID"),
921
+ x: getEnv("X_CLIENT_ID")
922
+ });
923
+
924
+ // src/providers/plugin/injectedEvmProvider.ts
925
+ var injectedWalletCapabilities = [
926
+ "eth_accounts",
927
+ "eth_requestAccounts",
928
+ "eth_chainId",
929
+ "eth_signTransaction",
930
+ "eth_sendTransaction",
931
+ "personal_sign",
932
+ "eth_signTypedData_v4",
933
+ "wallet_disconnect",
934
+ "wallet_rehydrate"
935
+ ];
936
+ function unwrapProvider(candidate) {
937
+ if (!candidate) return void 0;
938
+ if ("request" in candidate) return candidate;
939
+ return candidate.ethereum;
940
+ }
941
+ function collectCandidates() {
942
+ if (typeof window === "undefined") return [];
943
+ const providers = [];
944
+ const seen = /* @__PURE__ */ new Set();
945
+ const push = (candidate) => {
946
+ const provider = unwrapProvider(candidate);
947
+ if (!provider || seen.has(provider)) return;
948
+ seen.add(provider);
949
+ providers.push(provider);
950
+ };
951
+ push(window.ethereum);
952
+ window.ethereum?.providers?.forEach(push);
953
+ push(window.okxwallet);
954
+ push(window.coinbaseWalletExtension);
955
+ push(window.trustwallet);
956
+ push(window.phantom?.ethereum);
957
+ push(window.rabby);
958
+ push(window.bitkeep);
959
+ push(window.rainbow?.ethereum);
960
+ push(window.zerionWallet);
961
+ push(unwrapProvider(window.bitget));
962
+ return providers;
963
+ }
964
+ function discoverEIP6963Providers() {
965
+ if (typeof window === "undefined") return [];
966
+ const details = [];
967
+ const seen = /* @__PURE__ */ new Set();
968
+ const onAnnounce = (event) => {
969
+ const detail = event.detail;
970
+ if (!detail?.info?.uuid || !detail.provider) return;
971
+ if (seen.has(detail.info.uuid)) return;
972
+ seen.add(detail.info.uuid);
973
+ details.push(detail);
974
+ };
975
+ window.addEventListener("eip6963:announceProvider", onAnnounce);
976
+ window.dispatchEvent(new Event("eip6963:requestProviderInfo"));
977
+ window.removeEventListener("eip6963:announceProvider", onAnnounce);
978
+ return details;
979
+ }
980
+ function getWindow() {
981
+ return typeof window === "undefined" ? void 0 : window;
982
+ }
983
+ function getKnownNonMetaMaskProviders() {
984
+ const currentWindow = getWindow();
985
+ if (!currentWindow) return [];
986
+ const providers = [
987
+ unwrapProvider(currentWindow.okxwallet),
988
+ unwrapProvider(currentWindow.coinbaseWalletExtension),
989
+ unwrapProvider(currentWindow.trustwallet),
990
+ unwrapProvider(currentWindow.phantom?.ethereum),
991
+ unwrapProvider(currentWindow.rabby),
992
+ unwrapProvider(currentWindow.bitkeep),
993
+ unwrapProvider(currentWindow.rainbow?.ethereum),
994
+ currentWindow.zerionWallet,
995
+ unwrapProvider(currentWindow.bitget)
996
+ ];
997
+ return providers.filter((provider) => Boolean(provider));
998
+ }
999
+ function findInjectedProvider(predicate) {
1000
+ return collectCandidates().find(predicate);
1001
+ }
1002
+ function findEIP6963Provider(predicate) {
1003
+ return discoverEIP6963Providers().find(predicate)?.provider;
1004
+ }
1005
+ function isMetaMaskOnly(provider) {
1006
+ const knownNonMetaMaskProviders = getKnownNonMetaMaskProviders();
1007
+ return provider.isMetaMask === true && !knownNonMetaMaskProviders.includes(provider) && provider.isCoinbaseWallet !== true && provider.isPhantom !== true && provider.isRabby !== true && provider.isOkxWallet !== true && provider.isTrust !== true && provider.isTrustWallet !== true && provider.isBitKeep !== true && provider.isRainbow !== true && provider.isZerion !== true && provider.isBraveWallet !== true && provider.isBitget !== true;
1008
+ }
1009
+ function rdnsIncludes(info, value) {
1010
+ return info.rdns.toLowerCase().includes(value.toLowerCase());
1011
+ }
1012
+ function nameIncludes(info, value) {
1013
+ return info.name.toLowerCase().includes(value.toLowerCase());
1014
+ }
1015
+ var FALLBACK_FUNDING_CHAIN = getChainInfo();
1016
+ function evmChainInfoToWalletAddEthereumChainParams(info) {
1017
+ const chainIdHex = `0x${BigInt(info.chainId).toString(16)}`;
1018
+ return {
1019
+ chainId: chainIdHex,
1020
+ chainName: info.chainName,
1021
+ nativeCurrency: {
1022
+ name: info.nativeCurrencyName,
1023
+ symbol: info.nativeCurrencySymbol,
1024
+ decimals: info.nativeCurrencyDecimals
1025
+ },
1026
+ rpcUrls: [...info.rpcUrls],
1027
+ blockExplorerUrls: [info.blockExplorerUrl]
1028
+ };
1029
+ }
1030
+ var FALLBACK_FUNDING_CHAIN_ID_HEX = `0x${BigInt(FALLBACK_FUNDING_CHAIN.chainId).toString(16)}`;
1031
+ var FALLBACK_FUNDING_CHAIN_PARAMS = evmChainInfoToWalletAddEthereumChainParams(FALLBACK_FUNDING_CHAIN);
1032
+ async function switchToFallbackFundingChain(provider) {
1033
+ const switchChain = () => provider.request({
1034
+ method: "wallet_switchEthereumChain",
1035
+ params: [{ chainId: FALLBACK_FUNDING_CHAIN_ID_HEX }]
1036
+ });
1037
+ try {
1038
+ await switchChain();
1039
+ } catch (err) {
1040
+ const code = err?.code;
1041
+ if (code === 4902) {
1042
+ await provider.request({
1043
+ method: "wallet_addEthereumChain",
1044
+ params: [FALLBACK_FUNDING_CHAIN_PARAMS]
1045
+ });
1046
+ await switchChain();
1047
+ return;
1048
+ }
1049
+ throw err;
1050
+ }
1051
+ }
1052
+ function createInjectedWalletProvider(title, provider) {
1053
+ return {
1054
+ async request(payload) {
1055
+ try {
1056
+ return await provider.request(payload);
1057
+ } catch (error) {
1058
+ if (payload.method === "eth_signTransaction") {
1059
+ throw normalizeEvmTransactionSigningError(title, error);
1060
+ }
1061
+ throw error;
1062
+ }
1063
+ },
1064
+ async disconnect() {
1065
+ await provider.disconnect();
1066
+ }
1067
+ };
1068
+ }
1069
+ var InjectedEvmProvider = class extends AbstractProvider {
1070
+ constructor(config, injected) {
1071
+ super();
1072
+ this.config = config;
1073
+ this.injected = injected;
1074
+ this.category = "plugin";
1075
+ this.id = config.id;
1076
+ this.title = config.title;
1077
+ }
1078
+ isAvailable() {
1079
+ return Boolean(this.injected ?? this.config.resolveProvider());
1080
+ }
1081
+ get client() {
1082
+ const provider = this.injected ?? this.config.resolveProvider();
1083
+ if (provider) return provider;
1084
+ throw new Error(`${this.title} provider not available`);
1085
+ }
1086
+ async connect(_args) {
1087
+ const provider = this.client;
1088
+ const walletProvider = createInjectedWalletProvider(this.title, provider);
1089
+ const [address] = await walletProvider.request({ method: "eth_requestAccounts" }) ?? [];
1090
+ if (!address) {
1091
+ throw new Error(`${this.title} did not return an account`);
1092
+ }
1093
+ await switchToFallbackFundingChain(provider);
1094
+ const chainId = await walletProvider.request({ method: "eth_chainId" });
1095
+ const chain = getSupportedChainFromEvmChainId(chainId);
1096
+ const session = {
1097
+ address,
1098
+ chain,
1099
+ provider: walletProvider,
1100
+ walletType: "injected",
1101
+ authSource: "wallet",
1102
+ sessionId: `${this.id}:${address.toLowerCase()}`,
1103
+ capabilities: injectedWalletCapabilities,
1104
+ chainContext: createChainContext(chain)
1105
+ };
1106
+ return this.setSession(session);
1107
+ }
1108
+ async reconnect(_persistedSession) {
1109
+ const provider = this.injected ?? this.config.resolveProvider();
1110
+ if (!provider) return null;
1111
+ const walletProvider = createInjectedWalletProvider(this.title, provider);
1112
+ const accounts = await provider.request({
1113
+ method: "eth_accounts",
1114
+ params: []
1115
+ });
1116
+ const [address] = accounts ?? [];
1117
+ if (!address) return null;
1118
+ let chain;
1119
+ try {
1120
+ const chainId = await walletProvider.request({ method: "eth_chainId" });
1121
+ chain = getSupportedChainFromEvmChainId(chainId);
1122
+ } catch {
1123
+ return null;
1124
+ }
1125
+ const session = {
1126
+ address,
1127
+ chain,
1128
+ provider: walletProvider,
1129
+ walletType: "injected",
1130
+ authSource: "wallet",
1131
+ sessionId: `${this.id}:${address.toLowerCase()}`,
1132
+ capabilities: injectedWalletCapabilities,
1133
+ chainContext: createChainContext(chain)
1134
+ };
1135
+ return this.setSession(session);
1136
+ }
1137
+ };
1138
+ var MetaMaskProvider = class extends InjectedEvmProvider {
1139
+ constructor(injected) {
1140
+ super(
1141
+ {
1142
+ id: "metamask",
1143
+ title: "MetaMask",
1144
+ resolveProvider: () => findEIP6963Provider(
1145
+ ({ info }) => rdnsIncludes(info, "io.metamask") || nameIncludes(info, "metamask")
1146
+ ) ?? findInjectedProvider(isMetaMaskOnly)
1147
+ },
1148
+ injected
1149
+ );
1150
+ }
1151
+ };
1152
+ var OKXProvider = class extends InjectedEvmProvider {
1153
+ constructor(injected) {
1154
+ super(
1155
+ {
1156
+ id: "okx",
1157
+ title: "OKX Wallet",
1158
+ resolveProvider: () => findEIP6963Provider(
1159
+ ({ info }) => rdnsIncludes(info, "okx") || nameIncludes(info, "okx")
1160
+ ) ?? unwrapProvider(getWindow()?.okxwallet) ?? findInjectedProvider((provider) => provider.isOkxWallet === true)
1161
+ },
1162
+ injected
1163
+ );
1164
+ }
1165
+ };
1166
+ var CoinbaseWalletProvider = class extends InjectedEvmProvider {
1167
+ constructor(injected) {
1168
+ super(
1169
+ {
1170
+ id: "coinbase",
1171
+ title: "Coinbase Wallet",
1172
+ resolveProvider: () => findEIP6963Provider(
1173
+ ({ info }) => rdnsIncludes(info, "com.coinbase.wallet") || nameIncludes(info, "coinbase")
1174
+ ) ?? unwrapProvider(getWindow()?.coinbaseWalletExtension) ?? findInjectedProvider((provider) => provider.isCoinbaseWallet === true)
1175
+ },
1176
+ injected
1177
+ );
1178
+ }
1179
+ };
1180
+ var TrustWalletProvider = class extends InjectedEvmProvider {
1181
+ constructor(injected) {
1182
+ super(
1183
+ {
1184
+ id: "trust",
1185
+ title: "Trust Wallet",
1186
+ resolveProvider: () => findEIP6963Provider(
1187
+ ({ info }) => rdnsIncludes(info, "trust") || nameIncludes(info, "trust")
1188
+ ) ?? unwrapProvider(getWindow()?.trustwallet) ?? findInjectedProvider(
1189
+ (provider) => provider.isTrust === true || provider.isTrustWallet === true
1190
+ )
1191
+ },
1192
+ injected
1193
+ );
1194
+ }
1195
+ };
1196
+ var PhantomProvider = class extends InjectedEvmProvider {
1197
+ constructor(injected) {
1198
+ super(
1199
+ {
1200
+ id: "phantom",
1201
+ title: "Phantom",
1202
+ resolveProvider: () => findEIP6963Provider(
1203
+ ({ info }) => rdnsIncludes(info, "phantom") || nameIncludes(info, "phantom")
1204
+ ) ?? unwrapProvider(getWindow()?.phantom?.ethereum) ?? findInjectedProvider((provider) => provider.isPhantom === true)
1205
+ },
1206
+ injected
1207
+ );
1208
+ }
1209
+ };
1210
+ var RabbyProvider = class extends InjectedEvmProvider {
1211
+ constructor(injected) {
1212
+ super(
1213
+ {
1214
+ id: "rabby",
1215
+ title: "Rabby",
1216
+ resolveProvider: () => findEIP6963Provider(
1217
+ ({ info }) => rdnsIncludes(info, "rabby") || nameIncludes(info, "rabby")
1218
+ ) ?? unwrapProvider(getWindow()?.rabby) ?? findInjectedProvider((provider) => provider.isRabby === true)
1219
+ },
1220
+ injected
1221
+ );
1222
+ }
1223
+ };
1224
+ var RainbowProvider = class extends InjectedEvmProvider {
1225
+ constructor(injected) {
1226
+ super(
1227
+ {
1228
+ id: "rainbow",
1229
+ title: "Rainbow",
1230
+ resolveProvider: () => findEIP6963Provider(
1231
+ ({ info }) => rdnsIncludes(info, "rainbow") || nameIncludes(info, "rainbow")
1232
+ ) ?? unwrapProvider(getWindow()?.rainbow?.ethereum) ?? findInjectedProvider((provider) => provider.isRainbow === true)
1233
+ },
1234
+ injected
1235
+ );
1236
+ }
1237
+ };
1238
+ var ZerionProvider = class extends InjectedEvmProvider {
1239
+ constructor(injected) {
1240
+ super(
1241
+ {
1242
+ id: "zerion",
1243
+ title: "Zerion",
1244
+ resolveProvider: () => findEIP6963Provider(
1245
+ ({ info }) => rdnsIncludes(info, "zerion") || nameIncludes(info, "zerion")
1246
+ ) ?? getWindow()?.zerionWallet ?? findInjectedProvider((provider) => provider.isZerion === true)
1247
+ },
1248
+ injected
1249
+ );
1250
+ }
1251
+ };
1252
+ var BraveWalletProvider = class extends InjectedEvmProvider {
1253
+ constructor(injected) {
1254
+ super(
1255
+ {
1256
+ id: "brave",
1257
+ title: "Brave Wallet",
1258
+ resolveProvider: () => findEIP6963Provider(
1259
+ ({ info }) => rdnsIncludes(info, "brave") || nameIncludes(info, "brave")
1260
+ ) ?? findInjectedProvider((provider) => provider.isBraveWallet === true)
1261
+ },
1262
+ injected
1263
+ );
1264
+ }
1265
+ };
1266
+ var BitgetProvider = class extends InjectedEvmProvider {
1267
+ constructor(injected) {
1268
+ super(
1269
+ {
1270
+ id: "bitget",
1271
+ title: "Bitget",
1272
+ resolveProvider: () => findEIP6963Provider(
1273
+ ({ info }) => rdnsIncludes(info, "bitget") || nameIncludes(info, "bitget")
1274
+ ) ?? unwrapProvider(getWindow()?.bitget) ?? findInjectedProvider((provider) => provider.isBitget === true)
1275
+ },
1276
+ injected
1277
+ );
1278
+ }
1279
+ };
1280
+
1281
+ // src/providers/plugin/injectedWalletRegistry.ts
1282
+ var installUrls = {
1283
+ metamask: "https://metamask.io/download/",
1284
+ okx: "https://www.okx.com/web3",
1285
+ coinbase: "https://www.coinbase.com/wallet/downloads",
1286
+ trust: "https://trustwallet.com/browser-extension",
1287
+ phantom: "https://phantom.com/download",
1288
+ rabby: "https://rabby.io/",
1289
+ rainbow: "https://rainbow.me/extension",
1290
+ zerion: "https://zerion.io/extension",
1291
+ brave: "https://brave.com/wallet/",
1292
+ bitget: "https://web3.bitget.com/en/wallet-download"
1293
+ };
1294
+ function createDefaultInjectedWalletRegistry() {
1295
+ const providers = [
1296
+ new MetaMaskProvider(),
1297
+ new OKXProvider(),
1298
+ new CoinbaseWalletProvider(),
1299
+ new TrustWalletProvider(),
1300
+ new PhantomProvider(),
1301
+ new RabbyProvider(),
1302
+ new RainbowProvider(),
1303
+ new ZerionProvider(),
1304
+ new BraveWalletProvider(),
1305
+ new BitgetProvider()
1306
+ ];
1307
+ return providers.map((provider) => ({
1308
+ id: provider.id,
1309
+ title: provider.title,
1310
+ installUrl: installUrls[provider.id],
1311
+ provider,
1312
+ installed: provider.isAvailable()
1313
+ }));
1314
+ }
1315
+
1316
+ // src/providers/social/baseSocialProvider.ts
1317
+ var AbstractSocialProvider = class extends AbstractProvider {
1318
+ constructor() {
1319
+ super(...arguments);
1320
+ this.category = "social";
1321
+ }
1322
+ async connect(args) {
1323
+ await this.signIn(args?.options, args?.payload);
1324
+ return this.requireSession();
1325
+ }
1326
+ };
1327
+ function resolveEnv(env) {
1328
+ return typeof env === "string" ? envs[env] : env;
1329
+ }
1330
+ var CubeSignerAuth = class {
1331
+ constructor(config) {
1332
+ this._client = null;
1333
+ this._sessionData = null;
1334
+ this.env = resolveEnv(config.env);
1335
+ this.orgId = config.orgId;
1336
+ this.scopes = config.scopes ?? ["sign:*", "manage:*"];
1337
+ this.defaultSessionPolicy = config.defaultSessionPolicy;
1338
+ this.oidcLoginHooks = config.oidcLoginHooks;
1339
+ }
1340
+ /** Currently authenticated client (null if not logged in). */
1341
+ get client() {
1342
+ return this._client;
1343
+ }
1344
+ get currentSession() {
1345
+ if (!this._client || !this._sessionData) return null;
1346
+ return {
1347
+ client: this._client,
1348
+ sessionData: this._sessionData
1349
+ };
1350
+ }
1351
+ /* ── Google ───────────────────────────────── */
1352
+ /**
1353
+ * Login with a Google ID token (JWT).
1354
+ * The token is used directly as the OIDC credential.
1355
+ */
1356
+ async loginWithGoogle(idToken) {
1357
+ return this.authenticateWithOidcToken(idToken);
1358
+ }
1359
+ /* ── Twitter / X ──────────────────────────── */
1360
+ /**
1361
+ * Login with a Twitter OAuth 2.0 authorization code.
1362
+ *
1363
+ * 1. Exchange the code for an OIDC `id_token` via CubeSigner's
1364
+ * `/v0/org/{org_id}/oauth2/twitter` endpoint.
1365
+ * 2. Create a CubeSigner session with that token.
1366
+ */
1367
+ async loginWithTwitter(params) {
1368
+ const idToken = await this.exchangeTwitterCode(params);
1369
+ return this.authenticateWithOidcToken(idToken);
1370
+ }
1371
+ /* ── Sign-out ─────────────────────────────── */
1372
+ async signOut() {
1373
+ if (this._client) {
1374
+ try {
1375
+ await this._client.revokeSession();
1376
+ } catch {
1377
+ }
1378
+ this._client = null;
1379
+ this._sessionData = null;
1380
+ }
1381
+ }
1382
+ /* ── Session restore ────────────────────── */
1383
+ /**
1384
+ * Restore a CubeSigner session from previously persisted SessionData.
1385
+ * Useful for reconnecting after page reload without re-authentication.
1386
+ */
1387
+ async restoreSession(sessionData) {
1388
+ if (this._client) {
1389
+ await this.signOut();
1390
+ }
1391
+ const client = await CubeSignerClient.create(
1392
+ new MemorySessionManager(sessionData)
1393
+ );
1394
+ this._client = client;
1395
+ this._sessionData = sessionData;
1396
+ return { client, sessionData };
1397
+ }
1398
+ /* ── Private ──────────────────────────────── */
1399
+ async authenticateWithOidcToken(oidcToken) {
1400
+ if (this._client) {
1401
+ await this.signOut();
1402
+ }
1403
+ const hooks = this.oidcLoginHooks;
1404
+ if (hooks) {
1405
+ const proof = await CubeSignerClient.proveOidcIdentity(
1406
+ this.env,
1407
+ this.orgId,
1408
+ oidcToken
1409
+ );
1410
+ if (!proof.user_info?.initialized) {
1411
+ await hooks.registerUser(oidcToken);
1412
+ }
1413
+ }
1414
+ return this.createOidcSession(oidcToken);
1415
+ }
1416
+ /**
1417
+ * Exchange a Twitter authorization code for an OIDC id_token
1418
+ * via CubeSigner's dedicated endpoint.
1419
+ *
1420
+ * `POST {SignerApiRoot}/v0/org/{org_id}/oauth2/twitter`
1421
+ */
1422
+ async exchangeTwitterCode(params) {
1423
+ const url = `${this.env.SignerApiRoot}/v0/org/${this.orgId}/oauth2/twitter`;
1424
+ const res = await fetch(url, {
1425
+ method: "POST",
1426
+ headers: { "Content-Type": "application/json" },
1427
+ body: JSON.stringify({
1428
+ code: params.code,
1429
+ code_verifier: params.codeVerifier,
1430
+ redirect_uri: params.redirectUri
1431
+ })
1432
+ });
1433
+ if (!res.ok) {
1434
+ const text = await res.text().catch(() => "");
1435
+ throw new Error(
1436
+ `Twitter code exchange failed (${res.status}): ${text}`
1437
+ );
1438
+ }
1439
+ const data = await res.json();
1440
+ if (!data.id_token) {
1441
+ throw new Error("CubeSigner twitter exchange did not return id_token");
1442
+ }
1443
+ return data.id_token;
1444
+ }
1445
+ /**
1446
+ * Create a CubeSigner OIDC session from a generic OIDC id_token.
1447
+ */
1448
+ async createOidcSession(oidcToken) {
1449
+ const resp = await CubeSignerClient.createOidcSession(
1450
+ this.env,
1451
+ this.orgId,
1452
+ oidcToken,
1453
+ this.scopes
1454
+ );
1455
+ const sessionData = resp.data();
1456
+ const client = await CubeSignerClient.create(
1457
+ new MemorySessionManager(sessionData)
1458
+ );
1459
+ this._client = client;
1460
+ this._sessionData = sessionData;
1461
+ return { client, sessionData };
1462
+ }
1463
+ };
1464
+ var evmChainIdMap = {
1465
+ ETH: 1,
1466
+ BSC: 56
1467
+ };
1468
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1469
+ var toBigIntQuantity = (value) => {
1470
+ if (typeof value === "bigint") return value;
1471
+ if (typeof value === "number") {
1472
+ if (!Number.isInteger(value) || value < 0) {
1473
+ throw new Error(`Invalid EVM quantity number: ${value}`);
1474
+ }
1475
+ return BigInt(value);
1476
+ }
1477
+ const trimmed = value.trim();
1478
+ if (!trimmed) {
1479
+ throw new Error("EVM quantity cannot be empty");
1480
+ }
1481
+ if (/^0x[0-9a-fA-F]+$/.test(trimmed) || /^\d+$/.test(trimmed)) {
1482
+ return BigInt(trimmed);
1483
+ }
1484
+ throw new Error(`Invalid EVM quantity string: ${value}`);
1485
+ };
1486
+ var toHexQuantity = (value) => {
1487
+ if (value === void 0) return void 0;
1488
+ return `0x${toBigIntQuantity(value).toString(16)}`;
1489
+ };
1490
+ var normalizeAccessList = (accessList) => {
1491
+ if (!accessList) return void 0;
1492
+ return accessList.map((item) => ({
1493
+ address: item.address,
1494
+ storageKeys: item.storageKeys
1495
+ }));
1496
+ };
1497
+ var textEncoder = new TextEncoder();
1498
+ var resolveTransactionType = (transaction) => {
1499
+ if (transaction.type !== void 0) {
1500
+ const normalized = toHexQuantity(transaction.type);
1501
+ if (normalized === "0x0" || normalized === "0x1" || normalized === "0x2") {
1502
+ return normalized;
1503
+ }
1504
+ throw new Error(`Unsupported EVM transaction type for Cubist: ${normalized}`);
1505
+ }
1506
+ if (transaction.maxFeePerGas !== void 0 || transaction.maxPriorityFeePerGas !== void 0) {
1507
+ return "0x2";
1508
+ }
1509
+ if (transaction.accessList?.length) {
1510
+ return "0x1";
1511
+ }
1512
+ return "0x0";
1513
+ };
1514
+ var toCubistSignRequest = (address, chain, transaction) => {
1515
+ const resolvedChainId = (transaction.chainId !== void 0 ? Number(toBigIntQuantity(transaction.chainId)) : void 0) ?? evmChainIdMap[chain];
1516
+ if (!resolvedChainId) {
1517
+ throw new Error("Cubist signing requires an EVM chainId");
1518
+ }
1519
+ const type = resolveTransactionType(transaction);
1520
+ const commonFields = {
1521
+ from: transaction.from ?? address,
1522
+ to: transaction.to,
1523
+ data: transaction.data,
1524
+ gas: toHexQuantity(transaction.gas),
1525
+ nonce: toHexQuantity(transaction.nonce),
1526
+ value: toHexQuantity(transaction.value)
1527
+ };
1528
+ const accessList = normalizeAccessList(transaction.accessList);
1529
+ const tx = type === "0x2" ? {
1530
+ ...commonFields,
1531
+ type,
1532
+ ...accessList ? { accessList } : {},
1533
+ maxFeePerGas: toHexQuantity(transaction.maxFeePerGas),
1534
+ maxPriorityFeePerGas: toHexQuantity(transaction.maxPriorityFeePerGas)
1535
+ } : type === "0x1" ? {
1536
+ ...commonFields,
1537
+ type,
1538
+ ...accessList ? { accessList } : {},
1539
+ gasPrice: toHexQuantity(transaction.gasPrice)
1540
+ } : {
1541
+ ...commonFields,
1542
+ type,
1543
+ gasPrice: toHexQuantity(transaction.gasPrice)
1544
+ };
1545
+ return {
1546
+ chain_id: resolvedChainId,
1547
+ tx
1548
+ };
1549
+ };
1550
+ var getTransactionParam = (params) => {
1551
+ const candidate = params?.[0];
1552
+ if (!isRecord(candidate)) {
1553
+ throw new Error("eth_signTransaction requires a transaction object");
1554
+ }
1555
+ return candidate;
1556
+ };
1557
+ var toHexBytes = (value) => {
1558
+ if (/^0x[0-9a-fA-F]*$/.test(value)) return value;
1559
+ return `0x${Array.from(textEncoder.encode(value)).map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
1560
+ };
1561
+ var getMessageParam = (address, params) => {
1562
+ const [first, second] = params ?? [];
1563
+ if (typeof second === "string" && second.toLowerCase() === address.toLowerCase()) {
1564
+ return String(first ?? "");
1565
+ }
1566
+ if (typeof first === "string" && first.toLowerCase() === address.toLowerCase()) {
1567
+ return String(second ?? "");
1568
+ }
1569
+ return String(first ?? "");
1570
+ };
1571
+ var getTypedDataParam = (address, params) => {
1572
+ const [first, second] = params ?? [];
1573
+ if (typeof first === "string" && first.toLowerCase() === address.toLowerCase()) {
1574
+ return typeof second === "string" ? JSON.parse(second) : second ?? {};
1575
+ }
1576
+ return typeof second === "string" ? JSON.parse(second) : second ?? first ?? {};
1577
+ };
1578
+ var createCubistEvmWalletProvider = ({
1579
+ session,
1580
+ address,
1581
+ chain
1582
+ }) => {
1583
+ const signer = new EvmSigner(address, session.client);
1584
+ return {
1585
+ async request(payload) {
1586
+ switch (payload.method) {
1587
+ case "eth_accounts":
1588
+ case "eth_requestAccounts":
1589
+ return [address];
1590
+ case "eth_chainId": {
1591
+ const chainId = evmChainIdMap[chain];
1592
+ return `0x${chainId.toString(16)}`;
1593
+ }
1594
+ case "eth_signTransaction": {
1595
+ const transaction = getTransactionParam(payload.params);
1596
+ const signRequest = toCubistSignRequest(address, chain, transaction);
1597
+ return await signer.signTransaction(signRequest);
1598
+ }
1599
+ case "personal_sign": {
1600
+ const message = getMessageParam(address, payload.params);
1601
+ return await signer.signEip191({
1602
+ data: toHexBytes(message)
1603
+ });
1604
+ }
1605
+ case "eth_signTypedData_v4": {
1606
+ const typedData = getTypedDataParam(address, payload.params);
1607
+ const domain = typedData.domain;
1608
+ const chainId = domain?.chainId !== void 0 ? Number(toBigIntQuantity(domain.chainId)) : evmChainIdMap[chain];
1609
+ if (!chainId) {
1610
+ throw new Error("CubistProvider: typed data signing requires an EVM chainId");
1611
+ }
1612
+ return await signer.signEip712({
1613
+ chain_id: chainId,
1614
+ typed_data: typedData
1615
+ });
1616
+ }
1617
+ default:
1618
+ throw new Error(`CubistProvider: unsupported RPC method "${payload.method}"`);
1619
+ }
1620
+ },
1621
+ async disconnect() {
1622
+ await session.client.revokeSession();
1623
+ }
1624
+ };
1625
+ };
1626
+
1627
+ // src/providers/social/cubistProvider.ts
1628
+ var defaultAdapter = {
1629
+ async resolve(session) {
1630
+ const keys = await session.client.sessionKeys();
1631
+ const evmKey = keys.find((k) => k.cached.key_type === "SecpEthAddr");
1632
+ if (!evmKey) throw new Error("No EVM key found in CubeSigner session");
1633
+ const address = evmKey.materialId;
1634
+ const chain = "ETH";
1635
+ const provider = createCubistEvmWalletProvider({
1636
+ session,
1637
+ address,
1638
+ chain
1639
+ });
1640
+ return {
1641
+ address,
1642
+ chain,
1643
+ provider,
1644
+ chainContext: createChainContext(chain)
1645
+ };
1646
+ }
1647
+ };
1648
+ var cubistCapabilities = [
1649
+ "eth_accounts",
1650
+ "eth_requestAccounts",
1651
+ "eth_chainId",
1652
+ "eth_signTransaction",
1653
+ "personal_sign",
1654
+ "eth_signTypedData_v4",
1655
+ "wallet_disconnect",
1656
+ "wallet_rehydrate"
1657
+ ];
1658
+ var CubistSocialProvider = class extends AbstractSocialProvider {
1659
+ constructor(config, adapter = defaultAdapter) {
1660
+ super();
1661
+ this.id = "cubist";
1662
+ this.title = "Cubist Social Wallet";
1663
+ this.lastCubeSignerSession = null;
1664
+ /** Stash the login method so `connect()` can auto-retry. */
1665
+ this.lastLogin = null;
1666
+ this.auth = new CubeSignerAuth(config);
1667
+ this.adapter = adapter;
1668
+ }
1669
+ async createWalletSession(method) {
1670
+ const session = method.type === "google" ? await this.auth.loginWithGoogle(method.idToken) : await this.auth.loginWithTwitter(method.params);
1671
+ this.lastCubeSignerSession = session;
1672
+ const walletSession = await this.adapter.resolve(session);
1673
+ const capabilityPolicy = this.auth.defaultSessionPolicy ? createSessionCapabilityPolicy(this.auth.defaultSessionPolicy) : void 0;
1674
+ return {
1675
+ ...walletSession,
1676
+ walletType: "social",
1677
+ authSource: method.type,
1678
+ sessionId: `${method.type}:${walletSession.address.toLowerCase()}`,
1679
+ expiresAt: capabilityPolicy?.expiresAt,
1680
+ capabilities: cubistCapabilities,
1681
+ sessionData: session.sessionData,
1682
+ chainContext: walletSession.chainContext ?? createChainContext(walletSession.chain),
1683
+ capabilityPolicy
1684
+ };
1685
+ }
1686
+ async authenticate(method) {
1687
+ const walletSession = await this.createWalletSession(method);
1688
+ this.lastLogin = method;
1689
+ this.setSession(walletSession);
1690
+ }
1691
+ getResolvedLoginMethod(payload) {
1692
+ const method = payload ?? this.lastLogin;
1693
+ if (!method) {
1694
+ throw new Error(
1695
+ "CubistSocialProvider.signIn requires a login method. Use signInWith(method) first."
1696
+ );
1697
+ }
1698
+ return method;
1699
+ }
1700
+ /**
1701
+ * Preferred explicit sign-in entrypoint.
1702
+ */
1703
+ async signInWith(method, _options) {
1704
+ await this.authenticate(method);
1705
+ }
1706
+ /**
1707
+ * Backward-compatible abstract implementation.
1708
+ *
1709
+ * - If `payload` is provided, it is treated as the login method.
1710
+ * - Otherwise reuses the previously cached login method if available.
1711
+ */
1712
+ async signIn(_options, payload) {
1713
+ await this.authenticate(this.getResolvedLoginMethod(payload));
1714
+ }
1715
+ /**
1716
+ * Explicit connect flow that both authenticates and returns the wallet session.
1717
+ */
1718
+ async connectWith(method, options) {
1719
+ return this.connect({ options, payload: method });
1720
+ }
1721
+ async connect(args) {
1722
+ if (args?.payload !== void 0 || args?.options !== void 0) {
1723
+ await this.signIn(args.options, args.payload);
1724
+ return this.requireSession("Cubist session missing after sign-in");
1725
+ }
1726
+ if (this.session) {
1727
+ return this.session;
1728
+ }
1729
+ if (!this.lastLogin) {
1730
+ throw new Error("Cubist session missing \u2014 call signInWith(method) first");
1731
+ }
1732
+ await this.signIn();
1733
+ return this.requireSession("Cubist session missing after sign-in");
1734
+ }
1735
+ async reconnect(persistedSession) {
1736
+ if (!persistedSession.sessionData) return null;
1737
+ try {
1738
+ const csSession = await this.auth.restoreSession(
1739
+ persistedSession.sessionData
1740
+ );
1741
+ this.lastCubeSignerSession = csSession;
1742
+ const walletSession = await this.adapter.resolve(csSession);
1743
+ return this.setSession({
1744
+ ...walletSession,
1745
+ walletType: persistedSession.walletType ?? "social",
1746
+ authSource: persistedSession.authSource,
1747
+ sessionId: persistedSession.sessionId,
1748
+ expiresAt: persistedSession.expiresAt,
1749
+ capabilities: cubistCapabilities,
1750
+ sessionData: csSession.sessionData,
1751
+ chainContext: walletSession.chainContext ?? createChainContext(walletSession.chain),
1752
+ capabilityPolicy: persistedSession.capabilityPolicy
1753
+ });
1754
+ } catch {
1755
+ return null;
1756
+ }
1757
+ }
1758
+ async signOut() {
1759
+ await this.auth.signOut();
1760
+ this.clearSession();
1761
+ this.lastLogin = null;
1762
+ this.lastCubeSignerSession = null;
1763
+ }
1764
+ async disconnect() {
1765
+ await this.signOut();
1766
+ }
1767
+ /** Direct access to the underlying CubeSignerAuth for advanced use-cases. */
1768
+ get cubeSignerAuth() {
1769
+ return this.auth;
1770
+ }
1771
+ get cubeSignerSession() {
1772
+ return this.lastCubeSignerSession ?? this.auth.currentSession;
1773
+ }
1774
+ };
1775
+
1776
+ export { AbstractProvider, AbstractSocialProvider, BitgetProvider, BraveWalletProvider, CoinbaseWalletProvider, CubeSignerAuth, CubistSocialProvider, EVM_TRANSACTION_SIGNING_UNSUPPORTED, EvmTransactionSigningUnsupportedError, InjectedEvmProvider, MetaMaskProvider, OKXProvider, PhantomProvider, RabbyProvider, RainbowProvider, SessionCapabilityError, SessionStore, TrustWalletProvider, WalletConnector, ZerionProvider, assertSessionCapability, createAccountController, createChainContext, createDefaultInjectedWalletRegistry, createSessionCapabilityPolicy, createWalletConnectController, createWalletExecutionClient, createWalletExecutionController, describeSessionCapabilityPolicy, discoverEIP6963Providers, findEIP6963Provider, findInjectedProvider, getAllChainDescriptors, getChainDescriptor, getSupportedChainFromEvmChainId, getWalletExecutionCapabilities, isCapabilityPolicyExpired, isSessionExpired, isUnsupportedEvmTransactionSigningError, normalizeEvmTransactionSigningError, sessionStore, sessionSupportsCapability, switchToFallbackFundingChain };