@0xsequence/dapp-client 0.0.0-20250910142613

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 (43) hide show
  1. package/.turbo/turbo-build.log +5 -0
  2. package/CHANGELOG.md +11 -0
  3. package/LICENSE +202 -0
  4. package/README.md +238 -0
  5. package/dist/ChainSessionManager.d.ts +203 -0
  6. package/dist/ChainSessionManager.d.ts.map +1 -0
  7. package/dist/ChainSessionManager.js +742 -0
  8. package/dist/DappClient.d.ts +409 -0
  9. package/dist/DappClient.d.ts.map +1 -0
  10. package/dist/DappClient.js +667 -0
  11. package/dist/DappTransport.d.ts +47 -0
  12. package/dist/DappTransport.d.ts.map +1 -0
  13. package/dist/DappTransport.js +443 -0
  14. package/dist/index.d.ts +11 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +7 -0
  17. package/dist/types/index.d.ts +168 -0
  18. package/dist/types/index.d.ts.map +1 -0
  19. package/dist/types/index.js +25 -0
  20. package/dist/utils/constants.d.ts +6 -0
  21. package/dist/utils/constants.d.ts.map +1 -0
  22. package/dist/utils/constants.js +5 -0
  23. package/dist/utils/errors.d.ts +28 -0
  24. package/dist/utils/errors.d.ts.map +1 -0
  25. package/dist/utils/errors.js +54 -0
  26. package/dist/utils/index.d.ts +11 -0
  27. package/dist/utils/index.d.ts.map +1 -0
  28. package/dist/utils/index.js +135 -0
  29. package/dist/utils/storage.d.ts +64 -0
  30. package/dist/utils/storage.d.ts.map +1 -0
  31. package/dist/utils/storage.js +196 -0
  32. package/eslint.config.mjs +4 -0
  33. package/package.json +38 -0
  34. package/src/ChainSessionManager.ts +978 -0
  35. package/src/DappClient.ts +801 -0
  36. package/src/DappTransport.ts +518 -0
  37. package/src/index.ts +47 -0
  38. package/src/types/index.ts +218 -0
  39. package/src/utils/constants.ts +5 -0
  40. package/src/utils/errors.ts +62 -0
  41. package/src/utils/index.ts +158 -0
  42. package/src/utils/storage.ts +272 -0
  43. package/tsconfig.json +10 -0
@@ -0,0 +1,5 @@
1
+
2
+ 
3
+ > @0xsequence/dapp-client@0.0.0-20250910142613 build /Users/taylan/Development/Horizon/sequence.js/packages/wallet/dapp-client
4
+ > tsc
5
+
package/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # @0xsequence/dapp-client
2
+
3
+ ## 0.0.0-20250910142613
4
+
5
+ ### Patch Changes
6
+
7
+ - v3 beta snapshot
8
+ - Updated dependencies
9
+ - @0xsequence/guard@0.0.0-20250910142613
10
+ - @0xsequence/wallet-core@0.0.0-20250910142613
11
+ - @0xsequence/wallet-primitives@0.0.0-20250910142613
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,238 @@
1
+ # @0xsequence/dapp-client
2
+
3
+ ## 1. Overview
4
+
5
+ The `DappClient` is the main entry point for interacting with the Sequence Wallet from any decentralized application (dapp). It provides a high-level, developer-friendly API to manage user sessions across multiple blockchains.
6
+
7
+ This client simplifies complex wallet interactions such as connecting a user, sending transactions, and signing messages, while handling different communication methods (popup vs. redirect) and session types (implicit vs. explicit) under the hood.
8
+
9
+ ### Core Concepts
10
+
11
+ - **Multichain by Design:** A single client instance manages connections to multiple blockchains simultaneously.
12
+ - **Implicit vs. Explicit Sessions:**
13
+ - **Implicit Session:** The primary session tied to a user's main login (e.g., social or email). It is designed for interacting with specific, pre-approved contracts within your dapp for a seamless UX.
14
+ - **Explicit Session:** A temporary, permissioned session key. Your dapp can request specific permissions (e.g., "allow this key to spend 10 USDC"), and once approved by the user, can perform those actions without further popups.
15
+ - **Event-Driven:** Asynchronous operations like signing are handled via an event emitter, creating a single, consistent API for both popup and redirect flows.
16
+
17
+ ## 2. Getting Started
18
+
19
+ ### Installation
20
+
21
+ ```bash
22
+ pnpm install @0xsequence/dapp-client
23
+ ```
24
+
25
+ ### Basic Usage
26
+
27
+ It is recommended to create and manage a single, singleton instance of the `DappClient` throughout your application.
28
+
29
+ ```typescript
30
+ import { DappClient } from '@0xsequence/dapp-client'
31
+
32
+ // 1. Create a single client instance for your app
33
+ const dappClient = new DappClient('https://my-wallet-url.com')
34
+
35
+ // 2. Initialize the client when your application loads
36
+ async function initializeClient() {
37
+ try {
38
+ // The initialize method loads any existing session from storage
39
+ // and handles any pending redirect responses.
40
+ await dappClient.initialize()
41
+ console.log('Client initialized. User is connected:', dappClient.isInitialized)
42
+ } catch (error) {
43
+ console.error('Failed to initialize client:', error)
44
+ }
45
+ }
46
+
47
+ initializeClient()
48
+ ```
49
+
50
+ ## 3. Class: `DappClient`
51
+
52
+ The main entry point for interacting with the Wallet. This client manages user sessions across multiple chains, handles connection and disconnection, and provides methods for signing and sending transactions.
53
+
54
+ ### Constructor
55
+
56
+ **`new DappClient(walletUrl, options?)`**
57
+
58
+ Initializes a new instance of the DappClient.
59
+
60
+ | Parameter | Type | Description |
61
+ | :------------------------------- | :-------------------------- | :------------------------------------------------------------------------------------------- |
62
+ | `walletUrl` | `string` | **(Required)** The URL of the Ecosystem Wallet Webapp. |
63
+ | `origin` | `string` | **(Required)** The origin of the dapp. |
64
+ | `options` | `object` | (Optional) An object containing configuration options for the client. |
65
+ | `options.transportMode` | `'popup' \| 'redirect'` | The communication mode to use with the wallet. Defaults to `'popup'`. |
66
+ | `options.keymachineUrl` | `string` | The URL of the key management service. Defaults to the production Sequence Key Machine. |
67
+ | `options.redirectPath` | `string` | The path to redirect back to after a redirect-based flow. Used as origin+path. |
68
+ | `options.sequenceStorage` | `SequenceStorage` | An object for persistent session data storage. Defaults to `WebStorage` (using IndexedDB). |
69
+ | `options.sequenceSessionStorage` | `SequenceSessionStorage` | An object for temporary data storage (e.g., pending requests). Defaults to `sessionStorage`. |
70
+ | `options.randomPrivateKeyFn` | `() => Hex \| Promise<Hex>` | A function to generate random private keys for new sessions. |
71
+ | `options.redirectActionHandler` | `(url: string) => void` | A handler to manually control navigation for redirect flows. |
72
+ | `options.canUseIndexedDb` | `boolean` | A flag to enable or disable the use of IndexedDB for caching. Defaults to `true`. |
73
+
74
+ ---
75
+
76
+ ## 4. API Reference
77
+
78
+ ### Properties
79
+
80
+ | Property | Type | Description |
81
+ | :-------------- | :--------------- | :------------------------------------------------------------------------ |
82
+ | `isInitialized` | `boolean` | `true` if the client has an active and loaded session, `false` otherwise. |
83
+ | `loginMethod` | `string \| null` | The login method used for the current session (e.g., 'google', 'email'). |
84
+ | `userEmail` | `string \| null` | The email address associated with the session, if available. |
85
+ | `transportMode` | `TransportMode` | (Read-only) The transport mode the client was configured with. |
86
+
87
+ ### Methods
88
+
89
+ #### **initialize()**
90
+
91
+ Initializes the client by loading any existing session from storage. This should be called once when your application loads.
92
+
93
+ - **Returns:** `Promise<void>`
94
+ - **Throws:** `InitializationError` if the process fails.
95
+
96
+ ---
97
+
98
+ #### **connect()**
99
+
100
+ Creates and initializes a new user session for a given chain.
101
+
102
+ - **Parameters:**
103
+ - `chainId`: `ChainId` - The primary chain ID for the new session.
104
+ - `permissions?`: `Signers.Session.ExplicitParams` - (Optional) Permissions to request the user to approve for the new session (Unrestricted permissions if not provided).
105
+ - `options?`: `{ preferredLoginMethod?, email? }` - (Optional) Options for the new session.
106
+ - **Returns:** `Promise<void>`
107
+ - **Throws:** `ConnectionError`, `InitializationError`
108
+
109
+ ---
110
+
111
+ #### **disconnect()**
112
+
113
+ Disconnects the client and clears all session data from browser storage. Note: this does not revoke the sessions on-chain.
114
+
115
+ - **Returns:** `Promise<void>`
116
+
117
+ ---
118
+
119
+ #### **getWalletAddress()**
120
+
121
+ Returns the wallet address of the current session.
122
+
123
+ - **Returns:** `Address.Address | null`
124
+
125
+ ---
126
+
127
+ #### **getAllSessions()**
128
+
129
+ Returns an array of all active session keys (both implicit and explicit).
130
+
131
+ - **Returns:** `Session[]`
132
+
133
+ ---
134
+
135
+ #### **addExplicitSession()**
136
+
137
+ Creates and initializes a new explicit session for a given chain.
138
+
139
+ - **Parameters:**
140
+ - `chainId`: `ChainId` - The chain ID for the new session.
141
+ - `permissions`: `Signers.Session.ExplicitParams` - The permissions to request.
142
+ - **Returns:** `Promise<void>`
143
+ - **Throws:** `AddExplicitSessionError`, `InitializationError`
144
+ - **Example:**
145
+ ```typescript
146
+ // Allow this session to transfer 1 USDC on Polygon
147
+ const USDC_ADDRESS = '0x...'
148
+ const permissions = {
149
+ permissions: [Utils.ERC20PermissionBuilder.buildTransfer(USDC_ADDRESS, '1000000')],
150
+ }
151
+ await dappClient.addExplicitSession(137, permissions)
152
+ ```
153
+
154
+ ---
155
+
156
+ #### **sendTransaction()**
157
+
158
+ Signs and sends a transaction using an active session signer.
159
+
160
+ - **Parameters:**
161
+ - `chainId`: `ChainId` - The chain ID for the transaction.
162
+ - `transactions`: `Transaction[]` - An array of transactions to execute.
163
+ - `feeOption?`: `Relayer.FeeOption` - (Optional) A gas fee option for (ex: User could pay the gas in USDC).
164
+ - **Returns:** `Promise<string>` - The transaction hash.
165
+ - **Throws:** `TransactionError`, `InitializationError`
166
+
167
+ ---
168
+
169
+ #### **getFeeOptions()**
170
+
171
+ Gets available gas fee options for a transaction.
172
+
173
+ - **Parameters:**
174
+ - `chainId`: `ChainId` - The chain ID for the transaction.
175
+ - `transactions`: `Transaction[]` - The transactions to get fee options for.
176
+ - **Returns:** `Promise<Relayer.FeeOption[]>`
177
+ - **Throws:** `FeeOptionError`, `InitializationError`
178
+
179
+ ---
180
+
181
+ #### **signMessage()**
182
+
183
+ Signs a standard EIP-191 message. The signature is delivered via the `signatureResponse` event.
184
+
185
+ - **Parameters:**
186
+ - `chainId`: `ChainId` - The chain ID for signing.
187
+ - `message`: `string` - The message to sign.
188
+ - **Returns:** `Promise<void>`
189
+ - **Throws:** `SigningError`, `InitializationError`
190
+
191
+ ---
192
+
193
+ #### **signTypedData()**
194
+
195
+ Signs an EIP-712 typed data object. The signature is delivered via the `signatureResponse` event.
196
+
197
+ - **Parameters:**
198
+ - `chainId`: `ChainId` - The chain ID for signing.
199
+ - `typedData`: `unknown` - The typed data object to sign.
200
+ - **Returns:** `Promise<void>`
201
+ - **Throws:** `SigningError`, `InitializationError`
202
+
203
+ ---
204
+
205
+ #### **on()**
206
+
207
+ Registers an event listener for client-side events.
208
+
209
+ - **Parameters:**
210
+ - `event`: `'sessionsUpdated' | 'signatureResponse'` - The event to listen for.
211
+ - `listener`: `DappClientEventListener` - The callback function.
212
+ - **Returns:** `() => void` - A function to unsubscribe the listener.
213
+ - **Example:**
214
+
215
+ ```typescript
216
+ // The listener for `signatureResponse` receives the signing result.
217
+ dappClient.on('signatureResponse', (data) => {
218
+ // The `data` object includes the chainId where the signing occurred.
219
+ console.log('Signature response from chain:', data.chainId)
220
+
221
+ if (data.error) {
222
+ console.error('Signing failed:', data.error)
223
+ return
224
+ }
225
+
226
+ // The `data.response` object contains the signature and other details.
227
+ console.log('Action:', data.action) // 'signMessage' or 'signTypedData'
228
+ console.log('Signature:', data.response.signature)
229
+ console.log('Signed by wallet:', data.response.walletAddress)
230
+ })
231
+
232
+ // The listener for `sessionsUpdated` is useful for syncing UI state.
233
+ dappClient.on('sessionsUpdated', () => {
234
+ console.log('Sessions updated!')
235
+ console.log('Is initialized:', dappClient.isInitialized)
236
+ console.log('Wallet address:', dappClient.getWalletAddress())
237
+ })
238
+ ```
@@ -0,0 +1,203 @@
1
+ import { Relayer, Signers } from '@0xsequence/wallet-core';
2
+ import { Address, Hex } from 'ox';
3
+ import { DappTransport } from './DappTransport.js';
4
+ import { SequenceStorage } from './utils/storage.js';
5
+ import { ExplicitSessionEventListener, LoginMethod, RandomPrivateKeyFn, Session, Transaction, GuardConfig } from './types/index.js';
6
+ interface ChainSessionManagerEventMap {
7
+ explicitSessionResponse: ExplicitSessionEventListener;
8
+ }
9
+ /**
10
+ * Manages sessions and wallet interactions for a single blockchain.
11
+ * This class is used internally by the DappClient to handle chain-specific logic.
12
+ */
13
+ export declare class ChainSessionManager {
14
+ private readonly instanceId;
15
+ private stateProvider;
16
+ private readonly redirectUrl;
17
+ private readonly randomPrivateKeyFn;
18
+ private eventListeners;
19
+ private sessions;
20
+ private walletAddress;
21
+ private sessionManager;
22
+ private wallet;
23
+ private provider;
24
+ private relayer;
25
+ private readonly chainId;
26
+ transport: DappTransport | null;
27
+ private sequenceStorage;
28
+ isInitialized: boolean;
29
+ private isInitializing;
30
+ loginMethod: LoginMethod | null;
31
+ userEmail: string | null;
32
+ private guard?;
33
+ /**
34
+ * @param chainId The ID of the chain this manager is responsible for.
35
+ * @param keyMachineUrl The URL of the key management service.
36
+ * @param transport The transport mechanism for communicating with the wallet.
37
+ * @param sequenceStorage The storage implementation for persistent session data.
38
+ * @param redirectUrl (Optional) The URL to redirect back to after a redirect-based flow.
39
+ * @param guard (Optional) The guard config to use for the session.
40
+ * @param randomPrivateKeyFn (Optional) A function to generate random private keys.
41
+ * @param canUseIndexedDb (Optional) A flag to enable or disable IndexedDB for caching.
42
+ */
43
+ constructor(chainId: number, transport: DappTransport, projectAccessKey: string, keyMachineUrl: string, nodesUrl: string, relayerUrl: string, sequenceStorage: SequenceStorage, redirectUrl: string, guard?: GuardConfig, randomPrivateKeyFn?: RandomPrivateKeyFn, canUseIndexedDb?: boolean);
44
+ /**
45
+ * Registers an event listener for a specific event within this chain manager.
46
+ * @param event The event to listen for ChainSessionManagerEvent events.
47
+ * @param listener The function to call when the event occurs.
48
+ * @returns A function to unsubscribe the listener.
49
+ */
50
+ on<K extends keyof ChainSessionManagerEventMap>(event: K, listener: ChainSessionManagerEventMap[K]): () => void;
51
+ /**
52
+ * @private Emits an event to all registered listeners for this chain manager.
53
+ * @param event The event to emit.
54
+ * @param data The data to pass to the listener.
55
+ */
56
+ private emit;
57
+ /**
58
+ * Initializes the manager by loading sessions from storage for this specific chain.
59
+ * @returns A promise resolving to the login method and email if an implicit session is found, or void.
60
+ * @throws {InitializationError} If initialization fails.
61
+ */
62
+ initialize(): Promise<{
63
+ loginMethod: string | null;
64
+ userEmail: string | null;
65
+ } | void>;
66
+ /**
67
+ * Initializes the manager with a known wallet address, without loading sessions from storage.
68
+ * This is used when a wallet address is known but the session manager for this chain hasn't been instantiated yet.
69
+ * @param walletAddress The address of the wallet to initialize with.
70
+ */
71
+ initializeWithWallet(walletAddress: Address.Address): void;
72
+ /**
73
+ * @private Loads implicit and explicit sessions from storage for the current wallet address.
74
+ * @param walletAddress The walletAddress for all sessions.
75
+ */
76
+ private _loadSessionFromStorage;
77
+ /**
78
+ * Initiates the creation of a new session by sending a request to the wallet.
79
+ * @param permissions (Optional) Permissions for an initial explicit session.
80
+ * @param options (Optional) Additional options like preferred login method.
81
+ * @throws {InitializationError} If a session already exists or the transport fails to initialize.
82
+ */
83
+ createNewSession(origin: string, permissions?: Signers.Session.ExplicitParams, options?: {
84
+ preferredLoginMethod?: LoginMethod;
85
+ email?: string;
86
+ includeImplicitSession?: boolean;
87
+ }): Promise<void>;
88
+ /**
89
+ * Initiates the addition of a new explicit session by sending a request to the wallet.
90
+ * @param permissions The permissions for the new explicit session.
91
+ * @throws {InitializationError} If the manager is not initialized.
92
+ * @throws {AddExplicitSessionError} If adding the session fails.
93
+ */
94
+ addExplicitSession(permissions: Signers.Session.ExplicitParams): Promise<void>;
95
+ /**
96
+ * Initiates the modification of an existing explicit session by sending a request to the wallet.
97
+ * @param sessionAddress The address of the explicit session to modify.
98
+ * @param newPermissions The new permissions for the session.
99
+ * @throws {InitializationError} If the manager is not initialized.
100
+ * @throws {ModifyExplicitSessionError} If modifying the session fails.
101
+ */
102
+ modifyExplicitSession(sessionAddress: Address.Address, newPermissions: Signers.Session.ExplicitParams): Promise<void>;
103
+ /**
104
+ * @private Handles the connection-related part of a redirect response, initializing sessions.
105
+ * @param response The response payload from the redirect.
106
+ * @returns A promise resolving to true on success.
107
+ */
108
+ private _handleRedirectConnectionResponse;
109
+ /**
110
+ * Resets the manager state and clears all credentials from storage.
111
+ */
112
+ disconnect(): Promise<void>;
113
+ /**
114
+ * @private Initializes an implicit session signer and adds it to the session manager.
115
+ * @param pk The private key of the session.
116
+ * @param address The wallet address.
117
+ * @param attestation The attestation from the wallet.
118
+ * @param identitySignature The identity signature from the wallet.
119
+ * @param saveSession Whether to persist the session in storage.
120
+ * @param loginMethod The login method used.
121
+ * @param userEmail The email associated with the session.
122
+ * @param guard The guard configuration.
123
+ */
124
+ private _initializeImplicitSessionInternal;
125
+ /**
126
+ * @private Initializes an explicit session signer and adds it to the session manager.
127
+ * It retries fetching permissions from the network if allowed.
128
+ * @param pk The private key of the session.
129
+ * @param loginMethod The login method used for the session.
130
+ * @param userEmail The email associated with the session.
131
+ * @param allowRetries Whether to retry fetching permissions on failure.
132
+ */
133
+ private _initializeExplicitSessionInternal;
134
+ /**
135
+ * Checks if the current session has permission to execute a set of transactions.
136
+ * @param transactions The transactions to check permissions for.
137
+ * @returns A promise that resolves to true if the session has permission, false otherwise.
138
+ */
139
+ hasPermission(transactions: Transaction[]): Promise<boolean>;
140
+ /**
141
+ * Fetches fee options for a set of transactions.
142
+ * @param calls The transactions to estimate fees for.
143
+ * @returns A promise that resolves with an array of fee options.
144
+ * @throws {FeeOptionError} If fetching fee options fails.
145
+ */
146
+ getFeeOptions(calls: Transaction[]): Promise<Relayer.FeeOption[]>;
147
+ /**
148
+ * Builds, signs, and sends a batch of transactions.
149
+ * @param transactions The transactions to be sent.
150
+ * @param feeOption (Optional) The fee option to use for sponsoring the transaction. If provided, a token transfer call will be prepended.
151
+ * @returns A promise that resolves with the transaction hash.
152
+ * @throws {InitializationError} If the session is not initialized.
153
+ * @throws {TransactionError} If the transaction fails at any stage.
154
+ */
155
+ buildSignAndSendTransactions(transactions: Transaction[], feeOption?: Relayer.FeeOption): Promise<Hex.Hex>;
156
+ /**
157
+ * Handles a redirect response from the wallet for this specific chain.
158
+ * @param response The pre-parsed response from the transport.
159
+ * @returns A promise that resolves to true if the response was handled successfully.
160
+ * @throws {WalletRedirectError} If the response is invalid or causes an error.
161
+ * @throws {InitializationError} If the session cannot be initialized from the response.
162
+ */
163
+ handleRedirectResponse(response: {
164
+ payload: any;
165
+ action: string;
166
+ } | {
167
+ error: any;
168
+ action: string;
169
+ }): Promise<boolean>;
170
+ /**
171
+ * Gets the wallet address associated with this manager.
172
+ * @returns The wallet address, or null if not initialized.
173
+ */
174
+ getWalletAddress(): Address.Address | null;
175
+ /**
176
+ * Gets the sessions (signers) managed by this instance.
177
+ * @returns An array of session objects.
178
+ */
179
+ getSessions(): Session[];
180
+ /**
181
+ * @private Prepares, signs, and builds a transaction envelope.
182
+ * @param calls The payload calls to include in the transaction.
183
+ * @returns The signed transaction data ready for relaying.
184
+ */
185
+ private _buildAndSignCalls;
186
+ /**
187
+ * @private Polls the relayer for the status of a transaction until it is confirmed or fails.
188
+ * @param opHash The operation hash of the relayed transaction.
189
+ * @param chainId The chain ID of the transaction.
190
+ * @returns The final status of the transaction.
191
+ */
192
+ private _waitForTransactionReceipt;
193
+ /**
194
+ * @private Resets the internal state of the manager without clearing stored credentials.
195
+ */
196
+ private _resetState;
197
+ /**
198
+ * @private Resets the internal state and clears all persisted session data from storage.
199
+ */
200
+ private _resetStateAndClearCredentials;
201
+ }
202
+ export {};
203
+ //# sourceMappingURL=ChainSessionManager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ChainSessionManager.d.ts","sourceRoot":"","sources":["../src/ChainSessionManager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,OAAO,EAAE,OAAO,EAAiB,MAAM,yBAAyB,CAAA;AAGnF,OAAO,EAAe,OAAO,EAAE,GAAG,EAAqC,MAAM,IAAI,CAAA;AAEjF,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAWlD,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AAGpD,OAAO,EAIL,4BAA4B,EAG5B,WAAW,EACX,kBAAkB,EAElB,OAAO,EACP,WAAW,EAEX,WAAW,EACZ,MAAM,kBAAkB,CAAA;AAGzB,UAAU,2BAA2B;IACnC,uBAAuB,EAAE,4BAA4B,CAA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