@taquito/wallet-connect 24.2.0 → 24.3.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,728 +1,660 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@walletconnect/sign-client'), require('@walletconnect/modal'), require('@taquito/taquito'), require('@walletconnect/utils')) :
3
- typeof define === 'function' && define.amd ? define(['exports', '@walletconnect/sign-client', '@walletconnect/modal', '@taquito/taquito', '@walletconnect/utils'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.taquitoWalletConnect = {}, global.walletconnectSignClient, global.walletconnectModal, global.taquito, global.walletconnectUtils));
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@walletconnect/sign-client'), require('@walletconnect/modal'), require('@taquito/taquito'), require('@walletconnect/utils')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', '@walletconnect/sign-client', '@walletconnect/modal', '@taquito/taquito', '@walletconnect/utils'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.taquitoWalletConnect = {}, global.walletconnectSignClient, global.walletconnectModal, global.taquito, global.walletconnectUtils));
5
5
  })(this, (function (exports, Client, modal, taquito, utils) { 'use strict';
6
6
 
7
- /******************************************************************************
8
- Copyright (c) Microsoft Corporation.
9
-
10
- Permission to use, copy, modify, and/or distribute this software for any
11
- purpose with or without fee is hereby granted.
12
-
13
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
14
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
15
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
16
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
17
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
18
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
19
- PERFORMANCE OF THIS SOFTWARE.
20
- ***************************************************************************** */
21
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
22
-
23
-
24
- function __awaiter(thisArg, _arguments, P, generator) {
25
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
26
- return new (P || (P = Promise))(function (resolve, reject) {
27
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
28
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
29
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
30
- step((generator = generator.apply(thisArg, _arguments || [])).next());
31
- });
32
- }
33
-
34
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
35
- var e = new Error(message);
36
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
37
- };
7
+ exports.NetworkType = void 0;
8
+ (function (NetworkType) {
9
+ NetworkType["MAINNET"] = "mainnet";
10
+ NetworkType["GHOSTNET"] = "ghostnet";
11
+ NetworkType["SHADOWNET"] = "shadownet";
12
+ NetworkType["WEEKLYNET"] = "weeklynet";
13
+ NetworkType["TEZLINK_SHADOWNET"] = "tezlink_shadownet";
14
+ NetworkType["TALLINNNET"] = "tallinnnet";
15
+ NetworkType["CUSTOM"] = "custom";
16
+ })(exports.NetworkType || (exports.NetworkType = {}));
17
+ exports.PermissionScopeMethods = void 0;
18
+ (function (PermissionScopeMethods) {
19
+ PermissionScopeMethods["TEZOS_GET_ACCOUNTS"] = "tezos_getAccounts";
20
+ PermissionScopeMethods["TEZOS_SEND"] = "tezos_send";
21
+ PermissionScopeMethods["TEZOS_SIGN"] = "tezos_sign";
22
+ })(exports.PermissionScopeMethods || (exports.PermissionScopeMethods = {}));
23
+ exports.PermissionScopeEvents = void 0;
24
+ (function (PermissionScopeEvents) {
25
+ PermissionScopeEvents["CHAIN_CHANGED"] = "chainChanged";
26
+ PermissionScopeEvents["ACCOUNTS_CHANGED"] = "accountsChanged";
27
+ })(exports.PermissionScopeEvents || (exports.PermissionScopeEvents = {}));
28
+ exports.SigningType = void 0;
29
+ (function (SigningType) {
30
+ SigningType["RAW"] = "raw";
31
+ SigningType["OPERATION"] = "operation";
32
+ SigningType["MICHELINE"] = "micheline";
33
+ })(exports.SigningType || (exports.SigningType = {}));
38
34
 
39
- exports.NetworkType = void 0;
40
- (function (NetworkType) {
41
- NetworkType["MAINNET"] = "mainnet";
42
- NetworkType["GHOSTNET"] = "ghostnet";
43
- NetworkType["SHADOWNET"] = "shadownet";
44
- NetworkType["WEEKLYNET"] = "weeklynet";
45
- NetworkType["TEZLINK_SHADOWNET"] = "tezlink_shadownet";
46
- NetworkType["TALLINNNET"] = "tallinnnet";
47
- NetworkType["CUSTOM"] = "custom";
48
- })(exports.NetworkType || (exports.NetworkType = {}));
49
- exports.PermissionScopeMethods = void 0;
50
- (function (PermissionScopeMethods) {
51
- PermissionScopeMethods["TEZOS_GET_ACCOUNTS"] = "tezos_getAccounts";
52
- PermissionScopeMethods["TEZOS_SEND"] = "tezos_send";
53
- PermissionScopeMethods["TEZOS_SIGN"] = "tezos_sign";
54
- })(exports.PermissionScopeMethods || (exports.PermissionScopeMethods = {}));
55
- exports.PermissionScopeEvents = void 0;
56
- (function (PermissionScopeEvents) {
57
- PermissionScopeEvents["CHAIN_CHANGED"] = "chainChanged";
58
- PermissionScopeEvents["ACCOUNTS_CHANGED"] = "accountsChanged";
59
- })(exports.PermissionScopeEvents || (exports.PermissionScopeEvents = {}));
60
- exports.SigningType = void 0;
61
- (function (SigningType) {
62
- SigningType["RAW"] = "raw";
63
- SigningType["OPERATION"] = "operation";
64
- SigningType["MICHELINE"] = "micheline";
65
- })(exports.SigningType || (exports.SigningType = {}));
35
+ /**
36
+ * @category Error
37
+ * Error that indicates missing required permission scopes
38
+ */
39
+ class MissingRequiredScope extends Error {
40
+ constructor(requiredScopes) {
41
+ super(`Required permission scope were not granted for "${requiredScopes}"`);
42
+ this.requiredScopes = requiredScopes;
43
+ this.name = 'MissingRequiredScope';
44
+ }
45
+ }
46
+ /**
47
+ * @category Error
48
+ * Error that indicates the wallet returned an invalid namespace
49
+ */
50
+ class InvalidReceivedSessionNamespace extends Error {
51
+ constructor(messageWc, codeWc, type, data) {
52
+ super();
53
+ this.messageWc = messageWc;
54
+ this.codeWc = codeWc;
55
+ this.data = data;
56
+ this.name = 'InvalidReceivedSessionNamespace';
57
+ const baseMessage = `${codeWc}: ${messageWc}.`;
58
+ this.message = data
59
+ ? type === 'incomplete'
60
+ ? ` ${baseMessage} "${data}" is missing in the session namespace.`
61
+ : ` ${baseMessage} "${data}" is invalid.`
62
+ : baseMessage;
63
+ }
64
+ }
65
+ /**
66
+ * @category Error
67
+ * Error that indicates an invalid session key being passed
68
+ */
69
+ class InvalidSessionKey extends Error {
70
+ constructor(key) {
71
+ super(`Invalid session key "${key}"`);
72
+ this.key = key;
73
+ this.name = 'InvalidSessionKey';
74
+ }
75
+ }
76
+ /**
77
+ * @category Error
78
+ * Error that indicates the pkh is not part of the active accounts in the session
79
+ */
80
+ class InvalidAccount extends Error {
81
+ constructor(pkh) {
82
+ super(`Invalid pkh "${pkh}"`);
83
+ this.pkh = pkh;
84
+ this.name = 'InvalidAccount';
85
+ }
86
+ }
87
+ /**
88
+ * @category Error
89
+ * Error that indicates the network is not part of the active networks in the session
90
+ */
91
+ class InvalidNetwork extends Error {
92
+ constructor(network) {
93
+ super(`Invalid network "${network}"`);
94
+ this.network = network;
95
+ this.name = 'InvalidNetwork';
96
+ }
97
+ }
98
+ /**
99
+ * @category Error
100
+ * Error that indicates the combinaison pkh-network is not part of the active session
101
+ */
102
+ class InvalidNetworkOrAccount extends Error {
103
+ constructor(network, pkh) {
104
+ super(`No permission. The combinaison "${network}" and "${pkh}" is not part of the active session.`);
105
+ this.network = network;
106
+ this.pkh = pkh;
107
+ this.name = 'InvalidNetworkOrAccount';
108
+ }
109
+ }
110
+ /**
111
+ * @category Error
112
+ * Error that indicates the connection could not be established
113
+ */
114
+ class ConnectionFailed extends Error {
115
+ constructor(originalError) {
116
+ super(`Unable to connect`);
117
+ this.originalError = originalError;
118
+ this.name = 'ConnectionFailed';
119
+ }
120
+ }
121
+ /**
122
+ * @category Error
123
+ * Error that indicates there is no active session
124
+ */
125
+ class NotConnected extends Error {
126
+ constructor() {
127
+ super('Not connected, no active session');
128
+ this.name = 'NotConnected';
129
+ }
130
+ }
131
+ /**
132
+ * @category Error
133
+ * Error that indicates the active account is not specified
134
+ */
135
+ class ActiveAccountUnspecified extends Error {
136
+ constructor() {
137
+ super('Please specify the active account using the "setActiveAccount" method.');
138
+ this.name = 'ActiveAccountUnspecified';
139
+ }
140
+ }
141
+ /**
142
+ * @category Error
143
+ * Error that indicates the active network is not specified
144
+ */
145
+ class ActiveNetworkUnspecified extends Error {
146
+ constructor() {
147
+ super('Please specify the active network using the "setActiveNetwork" method.');
148
+ this.name = 'ActiveNetworkUnspecified';
149
+ }
150
+ }
151
+ /**
152
+ * @category Error
153
+ * Error that indicates the session is invalid
154
+ */
155
+ class InvalidSession extends Error {
156
+ constructor(message) {
157
+ super(message);
158
+ this.name = 'InvalidSession';
159
+ }
160
+ }
161
+ class PublicKeyRetrievalError extends Error {
162
+ constructor() {
163
+ super(`Unable to retrieve public key`);
164
+ this.name = 'PublicKeyRetrievalError';
165
+ }
166
+ }
66
167
 
67
- /**
68
- * @category Error
69
- * @description Error that indicates missing required permission scopes
70
- */
71
- class MissingRequiredScope extends Error {
72
- constructor(requiredScopes) {
73
- super(`Required permission scope were not granted for "${requiredScopes}"`);
74
- this.requiredScopes = requiredScopes;
75
- this.name = 'MissingRequiredScope';
76
- }
77
- }
78
- /**
79
- * @category Error
80
- * @description Error that indicates the wallet returned an invalid namespace
81
- */
82
- class InvalidReceivedSessionNamespace extends Error {
83
- constructor(messageWc, codeWc, type, data) {
84
- super();
85
- this.messageWc = messageWc;
86
- this.codeWc = codeWc;
87
- this.data = data;
88
- this.name = 'InvalidReceivedSessionNamespace';
89
- const baseMessage = `${codeWc}: ${messageWc}.`;
90
- this.message = data
91
- ? type === 'incomplete'
92
- ? ` ${baseMessage} "${data}" is missing in the session namespace.`
93
- : ` ${baseMessage} "${data}" is invalid.`
94
- : baseMessage;
95
- }
96
- }
97
- /**
98
- * @category Error
99
- * @description Error that indicates an invalid session key being passed
100
- */
101
- class InvalidSessionKey extends Error {
102
- constructor(key) {
103
- super(`Invalid session key "${key}"`);
104
- this.key = key;
105
- this.name = 'InvalidSessionKey';
106
- }
107
- }
108
- /**
109
- * @category Error
110
- * @description Error that indicates the pkh is not part of the active accounts in the session
111
- */
112
- class InvalidAccount extends Error {
113
- constructor(pkh) {
114
- super(`Invalid pkh "${pkh}"`);
115
- this.pkh = pkh;
116
- this.name = 'InvalidAccount';
117
- }
118
- }
119
- /**
120
- * @category Error
121
- * @description Error that indicates the network is not part of the active networks in the session
122
- */
123
- class InvalidNetwork extends Error {
124
- constructor(network) {
125
- super(`Invalid network "${network}"`);
126
- this.network = network;
127
- this.name = 'InvalidNetwork';
128
- }
129
- }
130
- /**
131
- * @category Error
132
- * @description Error that indicates the combinaison pkh-network is not part of the active session
133
- */
134
- class InvalidNetworkOrAccount extends Error {
135
- constructor(network, pkh) {
136
- super(`No permission. The combinaison "${network}" and "${pkh}" is not part of the active session.`);
137
- this.network = network;
138
- this.pkh = pkh;
139
- this.name = 'InvalidNetworkOrAccount';
140
- }
141
- }
142
- /**
143
- * @category Error
144
- * @description Error that indicates the connection could not be established
145
- */
146
- class ConnectionFailed extends Error {
147
- constructor(originalError) {
148
- super(`Unable to connect`);
149
- this.originalError = originalError;
150
- this.name = 'ConnectionFailed';
151
- }
152
- }
153
- /**
154
- * @category Error
155
- * @description Error that indicates there is no active session
156
- */
157
- class NotConnected extends Error {
158
- constructor() {
159
- super('Not connected, no active session');
160
- this.name = 'NotConnected';
161
- }
162
- }
163
- /**
164
- * @category Error
165
- * @description Error that indicates the active account is not specified
166
- */
167
- class ActiveAccountUnspecified extends Error {
168
- constructor() {
169
- super('Please specify the active account using the "setActiveAccount" method.');
170
- this.name = 'ActiveAccountUnspecified';
171
- }
172
- }
173
- /**
174
- * @category Error
175
- * @description Error that indicates the active network is not specified
176
- */
177
- class ActiveNetworkUnspecified extends Error {
178
- constructor() {
179
- super('Please specify the active network using the "setActiveNetwork" method.');
180
- this.name = 'ActiveNetworkUnspecified';
181
- }
182
- }
183
- /**
184
- * @category Error
185
- * @description Error that indicates the session is invalid
186
- */
187
- class InvalidSession extends Error {
188
- constructor(message) {
189
- super(message);
190
- this.name = 'InvalidSession';
191
- }
192
- }
193
- class PublicKeyRetrievalError extends Error {
194
- constructor() {
195
- super(`Unable to retrieve public key`);
196
- this.name = 'PublicKeyRetrievalError';
197
- }
198
- }
168
+ /**
169
+ * @packageDocumentation
170
+ * @module @taquito/wallet-connect
171
+ */
172
+ const TEZOS_PLACEHOLDER = 'tezos';
173
+ /**
174
+ * The `WalletConnect` class implements the `WalletProvider` interface, providing an alternative to `BeaconWallet`.
175
+ * This package enables dapps built with Taquito to connect to wallets via the WalletConnect/Reown protocol.
176
+ \* @remarks Currently, a QR code is displayed to establish a connection with a wallet. As more Tezos wallets integrate with WalletConnect,
177
+ * we plan showing a list of available wallets alongside the QR code.
178
+ */
179
+ class WalletConnect {
180
+ constructor(signClient, WalletConnectModal) {
181
+ this.signClient = signClient;
182
+ this.walletConnectModal = WalletConnectModal;
183
+ this.signClient.on('session_delete', ({ topic }) => {
184
+ if (this.session?.topic === topic) {
185
+ this.session = undefined;
186
+ }
187
+ });
188
+ this.signClient.on('session_expire', ({ topic }) => {
189
+ if (this.session?.topic === topic) {
190
+ this.session = undefined;
191
+ }
192
+ });
193
+ this.signClient.on('session_update', ({ params, topic }) => {
194
+ if (this.session?.topic === topic) {
195
+ this.session.namespaces = params.namespaces;
196
+ // TODO determine if we need validation on the namespace here
197
+ }
198
+ });
199
+ this.signClient.on('session_event', () => {
200
+ // TODO Do we need to handle other session events, such as "chainChanged", "accountsChanged", etc.
201
+ });
202
+ }
203
+ /**
204
+ * Initialize a WalletConnect provider
205
+ * (Initialize a WalletConnect client with persisted storage and a network connection)
206
+ *
207
+ * @example
208
+ * ```
209
+ * await WalletConnect.init({
210
+ * projectId: "YOUR_PROJECT_ID", // can get YOUR_PROJECT_ID from [Reown Cloud](https://cloud.reown.com)
211
+ * metadata: {
212
+ * name: "YOUR_DAPP_NAME",
213
+ * description: "YOUR_DAPP_DESCRIPTION",
214
+ * icons: ["ICON_URL"],
215
+ * url: "DAPP_URL",
216
+ * },
217
+ * });
218
+ * ```
219
+ */
220
+ static async init(initParams) {
221
+ if (!initParams.projectId) {
222
+ throw new Error('projectId is required');
223
+ }
224
+ const client = await Client.init(initParams);
225
+ const walletConnectModal = new modal.WalletConnectModal({
226
+ projectId: initParams.projectId,
227
+ });
228
+ return new WalletConnect(client, walletConnectModal);
229
+ }
230
+ /**
231
+ * Request permission for a new session and establish a connection.
232
+ *
233
+ * @param connectParams.permissionScope The networks, methods, and events that will be granted permission
234
+ * @param connectParams.pairingTopic Option to connect to an existing active pairing. If pairingTopic is defined, a prompt will appear in the corresponding wallet to accept or decline the session proposal. If no pairingTopic, a QR code modal will open in the dapp, allowing to connect to a wallet.
235
+ * @param connectParams.registryUrl Optional registry of wallet deep links to show in the Modal
236
+ \* @throws ConnectionFailed is thrown if no connection can be established with a wallet
237
+ */
238
+ async requestPermissions(connectParams) {
239
+ // TODO when Tezos wallets will officially support wallet connect, we need to provide a default value for registryUrl
240
+ try {
241
+ const chains = connectParams.permissionScope.networks.map((network) => `${TEZOS_PLACEHOLDER}:${network}`);
242
+ const { uri, approval } = await this.signClient.connect({
243
+ requiredNamespaces: {
244
+ [TEZOS_PLACEHOLDER]: {
245
+ chains,
246
+ methods: connectParams.permissionScope.methods,
247
+ events: connectParams.permissionScope.events ?? [],
248
+ },
249
+ },
250
+ pairingTopic: connectParams.pairingTopic,
251
+ });
252
+ if (uri) {
253
+ this.walletConnectModal.openModal({
254
+ uri,
255
+ chains,
256
+ });
257
+ }
258
+ this.session = await approval();
259
+ }
260
+ catch (error) {
261
+ throw new ConnectionFailed(error);
262
+ }
263
+ finally {
264
+ this.walletConnectModal.closeModal();
265
+ }
266
+ this.validateReceivedNamespace(connectParams.permissionScope, this.session.namespaces);
267
+ this.setDefaultAccountAndNetwork();
268
+ }
269
+ /**
270
+ * Access all existing active pairings
271
+ */
272
+ getAvailablePairing() {
273
+ return this.signClient.pairing.getAll({ active: true });
274
+ }
275
+ /**
276
+ * Access all existing sessions
277
+ * @return an array of strings which represent the session keys
278
+ */
279
+ getAllExistingSessionKeys() {
280
+ return this.signClient.session.keys;
281
+ }
282
+ /**
283
+ * Configure the Client with an existing session.
284
+ * The session is immediately restored without a prompt on the wallet to accept/decline it.
285
+ \* @throws InvalidSessionKey is thrown if the provided session key doesn't exist
286
+ */
287
+ configureWithExistingSessionKey(key) {
288
+ const sessions = this.getAllExistingSessionKeys();
289
+ if (!sessions.includes(key)) {
290
+ throw new InvalidSessionKey(key);
291
+ }
292
+ this.session = this.signClient.session.get(key);
293
+ this.setDefaultAccountAndNetwork();
294
+ }
295
+ async disconnect() {
296
+ if (this.session) {
297
+ await this.signClient.disconnect({
298
+ topic: this.session.topic,
299
+ reason: utils.getSdkError('USER_DISCONNECTED'),
300
+ });
301
+ this.clearState();
302
+ }
303
+ }
304
+ getPeerMetadata() {
305
+ return this.getSession().peer.metadata;
306
+ }
307
+ /**
308
+ * Once the session is establish, send Tezos operations to be approved, signed and inject by the wallet.
309
+ \* @throws MissingRequiredScope is thrown if permission to send operation was not granted
310
+ */
311
+ async sendOperations(params) {
312
+ const session = this.getSession();
313
+ if (!this.getPermittedMethods().includes(exports.PermissionScopeMethods.TEZOS_SEND)) {
314
+ throw new MissingRequiredScope(exports.PermissionScopeMethods.TEZOS_SEND);
315
+ }
316
+ const network = this.getActiveNetwork();
317
+ const account = await this.getPKH();
318
+ this.validateNetworkAndAccount(network, account);
319
+ const { operationHash } = await this.signClient.request({
320
+ topic: session.topic,
321
+ chainId: `${TEZOS_PLACEHOLDER}:${network}`,
322
+ request: {
323
+ method: exports.PermissionScopeMethods.TEZOS_SEND,
324
+ params: {
325
+ account,
326
+ operations: params,
327
+ },
328
+ },
329
+ });
330
+ return operationHash;
331
+ }
332
+ /**
333
+ * Once the session is establish, send payload to be signed by the wallet.
334
+ \* @throws MissingRequiredScope is thrown if permission to sign payload was not granted
335
+ */
336
+ async sign(bytes, watermark) {
337
+ const session = this.getSession();
338
+ if (!this.getPermittedMethods().includes(exports.PermissionScopeMethods.TEZOS_SIGN)) {
339
+ throw new MissingRequiredScope(exports.PermissionScopeMethods.TEZOS_SIGN);
340
+ }
341
+ const network = this.getActiveNetwork();
342
+ const account = await this.getPKH();
343
+ this.validateNetworkAndAccount(network, account);
344
+ let expression = bytes;
345
+ if (watermark) {
346
+ expression =
347
+ Array.from(watermark, (byte) => byte.toString(16).padStart(2, '0')).join('') + expression;
348
+ }
349
+ const { signature } = await this.signClient.request({
350
+ topic: session.topic,
351
+ chainId: `${TEZOS_PLACEHOLDER}:${network}`,
352
+ request: {
353
+ method: exports.PermissionScopeMethods.TEZOS_SIGN,
354
+ params: {
355
+ account: await this.getPKH(),
356
+ payload: expression,
357
+ },
358
+ },
359
+ });
360
+ return signature;
361
+ }
362
+ /**
363
+ * Return all connected accounts from the active session
364
+ \* @throws NotConnected if no active session
365
+ */
366
+ getAccounts() {
367
+ return this.getTezosNamespace().accounts.map((account) => account.split(':')[2]);
368
+ }
369
+ /**
370
+ * Set the active account.
371
+ * Must be called if there are multiple accounts in the session and every time the active account is switched
372
+ * @param pkh public key hash of the selected account
373
+ \* @throws InvalidAccount thrown if the pkh is not part of the active accounts in the session
374
+ */
375
+ setActiveAccount(pkh) {
376
+ if (!this.getAccounts().includes(pkh)) {
377
+ throw new InvalidAccount(pkh);
378
+ }
379
+ this.activeAccount = pkh;
380
+ }
381
+ /**
382
+ * Access the public key hash of the active account
383
+ \* @throws ActiveAccountUnspecified thrown when there are multiple Tezos account in the session and none is set as the active one
384
+ */
385
+ async getPKH() {
386
+ if (!this.activeAccount) {
387
+ this.getSession();
388
+ throw new ActiveAccountUnspecified();
389
+ }
390
+ return this.activeAccount;
391
+ }
392
+ /**
393
+ * Access the public key of the active account
394
+ \* @throws ActiveAccountUnspecified thrown when there are multiple Tezos account in the session and none is set as the active one
395
+ \* @throws MissingRequiredScope is thrown if permission to get accounts was not granted
396
+ \* @throws PublicKeyRetrievalError is thrown if the public key is not found
397
+ */
398
+ async getPK() {
399
+ const session = this.getSession();
400
+ if (!this.getPermittedMethods().includes(exports.PermissionScopeMethods.TEZOS_GET_ACCOUNTS)) {
401
+ throw new MissingRequiredScope(exports.PermissionScopeMethods.TEZOS_GET_ACCOUNTS);
402
+ }
403
+ const network = this.getActiveNetwork();
404
+ const account = await this.getPKH();
405
+ const accounts = await this.signClient.request({
406
+ topic: session.topic,
407
+ chainId: `${TEZOS_PLACEHOLDER}:${network}`,
408
+ request: {
409
+ method: exports.PermissionScopeMethods.TEZOS_GET_ACCOUNTS,
410
+ params: {},
411
+ },
412
+ });
413
+ const selectedAccount = accounts.find((acc) => acc.address === account);
414
+ if (!selectedAccount) {
415
+ throw new PublicKeyRetrievalError();
416
+ }
417
+ return selectedAccount.pubkey;
418
+ }
419
+ /**
420
+ * Return all networks from the namespace of the active session
421
+ \* @throws NotConnected if no active session
422
+ */
423
+ getNetworks() {
424
+ return this.getPermittedNetwork();
425
+ }
426
+ /**
427
+ * Set the active network.
428
+ * Must be called if there are multiple network in the session and every time the active network is switched
429
+ * @param network selected network
430
+ \* @throws InvalidNetwork thrown if the network is not part of the active networks in the session
431
+ */
432
+ setActiveNetwork(network) {
433
+ if (!this.getNetworks().includes(network)) {
434
+ throw new InvalidNetwork(network);
435
+ }
436
+ this.activeNetwork = network;
437
+ }
438
+ /**
439
+ * Access the active network
440
+ \* @throws ActiveNetworkUnspecified thorwn when there are multiple Tezos netwroks in the session and none is set as the active one
441
+ */
442
+ getActiveNetwork() {
443
+ if (!this.activeNetwork) {
444
+ this.getSession();
445
+ throw new ActiveNetworkUnspecified();
446
+ }
447
+ return this.activeNetwork;
448
+ }
449
+ setDefaultAccountAndNetwork() {
450
+ const activeAccount = this.getAccounts();
451
+ if (activeAccount.length === 1) {
452
+ this.activeAccount = activeAccount[0];
453
+ }
454
+ const activeNetwork = this.getNetworks();
455
+ if (activeNetwork.length === 1) {
456
+ this.activeNetwork = activeNetwork[0];
457
+ }
458
+ }
459
+ clearState() {
460
+ this.session = undefined;
461
+ this.activeAccount = undefined;
462
+ this.activeNetwork = undefined;
463
+ }
464
+ getSession() {
465
+ if (!this.session) {
466
+ throw new NotConnected();
467
+ }
468
+ return this.session;
469
+ }
470
+ isActiveSession() {
471
+ return this.session ? true : false;
472
+ }
473
+ ping() {
474
+ this.signClient.ping({ topic: this.getSession().topic });
475
+ }
476
+ // https://docs.reown.com/api/sign/wallet-usage#namespaces
477
+ // TODO: add validations related to Namespaces extensions and related unit tests:
478
+ validateReceivedNamespace(scope, receivedNamespaces) {
479
+ if (receivedNamespaces[TEZOS_PLACEHOLDER]) {
480
+ this.validateMethods(scope.methods, receivedNamespaces[TEZOS_PLACEHOLDER].methods);
481
+ if (scope.events) {
482
+ this.validateEvents(scope.events, receivedNamespaces['tezos'].events);
483
+ }
484
+ this.validateAccounts(scope.networks, receivedNamespaces[TEZOS_PLACEHOLDER].accounts);
485
+ }
486
+ else {
487
+ this.clearState();
488
+ throw new InvalidReceivedSessionNamespace('All namespaces must be approved', utils.getSdkError('USER_REJECTED').code, 'incomplete', 'tezos');
489
+ }
490
+ }
491
+ validateMethods(requiredMethods, receivedMethods) {
492
+ const missingMethods = [];
493
+ requiredMethods.forEach((method) => {
494
+ if (!receivedMethods.includes(method)) {
495
+ missingMethods.push(method);
496
+ }
497
+ });
498
+ if (missingMethods.length > 0) {
499
+ this.clearState();
500
+ throw new InvalidReceivedSessionNamespace('All methods must be approved', utils.getSdkError('USER_REJECTED_METHODS').code, 'incomplete', missingMethods);
501
+ }
502
+ }
503
+ validateEvents(requiredEvents, receivedEvents) {
504
+ const missingEvents = [];
505
+ requiredEvents.forEach((method) => {
506
+ if (!receivedEvents.includes(method)) {
507
+ missingEvents.push(method);
508
+ }
509
+ });
510
+ if (missingEvents.length > 0) {
511
+ this.clearState();
512
+ throw new InvalidReceivedSessionNamespace('All events must be approved', utils.getSdkError('USER_REJECTED_EVENTS').code, 'incomplete', missingEvents);
513
+ }
514
+ }
515
+ validateAccounts(requiredNetwork, receivedAccounts) {
516
+ if (receivedAccounts.length === 0) {
517
+ this.clearState();
518
+ throw new InvalidReceivedSessionNamespace('Accounts must not be empty', utils.getSdkError('USER_REJECTED_CHAINS').code, 'incomplete');
519
+ }
520
+ const receivedChains = [];
521
+ const invalidChains = [];
522
+ const missingChains = [];
523
+ const invalidChainsNamespace = [];
524
+ receivedAccounts.forEach((chain) => {
525
+ const accountId = chain.split(':');
526
+ if (accountId.length !== 3) {
527
+ invalidChains.push(chain);
528
+ }
529
+ if (accountId[0] !== TEZOS_PLACEHOLDER) {
530
+ invalidChainsNamespace.push(chain);
531
+ }
532
+ const network = accountId[1];
533
+ if (!receivedChains.includes(network)) {
534
+ receivedChains.push(network);
535
+ }
536
+ });
537
+ if (invalidChains.length > 0) {
538
+ this.clearState();
539
+ throw new InvalidReceivedSessionNamespace('Accounts must be CAIP-10 compliant', utils.getSdkError('USER_REJECTED_CHAINS').code, 'invalid', invalidChains);
540
+ }
541
+ if (invalidChainsNamespace.length > 0) {
542
+ this.clearState();
543
+ throw new InvalidReceivedSessionNamespace('Accounts must be defined in matching namespace', utils.getSdkError('UNSUPPORTED_ACCOUNTS').code, 'invalid', invalidChainsNamespace);
544
+ }
545
+ requiredNetwork.forEach((network) => {
546
+ if (!receivedChains.includes(network)) {
547
+ missingChains.push(network);
548
+ }
549
+ });
550
+ if (missingChains.length > 0) {
551
+ this.clearState();
552
+ throw new InvalidReceivedSessionNamespace('All chains must have at least one account', utils.getSdkError('USER_REJECTED_CHAINS').code, 'incomplete', missingChains);
553
+ }
554
+ }
555
+ getTezosNamespace() {
556
+ if (TEZOS_PLACEHOLDER in this.getSession().namespaces) {
557
+ return this.getSession().namespaces[TEZOS_PLACEHOLDER];
558
+ }
559
+ else {
560
+ throw new InvalidSession('Tezos not found in namespaces');
561
+ }
562
+ }
563
+ getTezosRequiredNamespace() {
564
+ if (TEZOS_PLACEHOLDER in this.getSession().requiredNamespaces) {
565
+ return this.getSession().requiredNamespaces[TEZOS_PLACEHOLDER];
566
+ }
567
+ else {
568
+ throw new InvalidSession('Tezos not found in requiredNamespaces');
569
+ }
570
+ }
571
+ validateNetworkAndAccount(network, account) {
572
+ if (!this.getTezosNamespace().accounts.includes(`${TEZOS_PLACEHOLDER}:${network}:${account}`)) {
573
+ throw new InvalidNetworkOrAccount(network, account);
574
+ }
575
+ }
576
+ getPermittedMethods() {
577
+ return this.getTezosRequiredNamespace().methods;
578
+ }
579
+ getPermittedNetwork() {
580
+ return this.getTezosRequiredNamespace().chains.map((chain) => chain.split(':')[1]);
581
+ }
582
+ formatParameters(params) {
583
+ const formatedParams = params;
584
+ if (typeof params.fee !== 'undefined') {
585
+ formatedParams.fee = params.fee.toString();
586
+ }
587
+ if (typeof params.storageLimit !== 'undefined') {
588
+ formatedParams.storageLimit = params.storageLimit.toString();
589
+ }
590
+ if (typeof params.gasLimit !== 'undefined') {
591
+ formatedParams.gasLimit = params.gasLimit.toString();
592
+ }
593
+ return formatedParams;
594
+ }
595
+ removeDefaultLimits(params, operatedParams) {
596
+ if (typeof params.fee === 'undefined') {
597
+ delete operatedParams.fee;
598
+ }
599
+ if (typeof params.storageLimit === 'undefined') {
600
+ delete operatedParams.storage_limit;
601
+ }
602
+ if (typeof params.gasLimit === 'undefined') {
603
+ delete operatedParams.gas_limit;
604
+ }
605
+ return operatedParams;
606
+ }
607
+ async mapTransferParamsToWalletParams(params) {
608
+ const walletParams = await params();
609
+ return this.removeDefaultLimits(walletParams, await taquito.createTransferOperation(this.formatParameters(walletParams)));
610
+ }
611
+ async mapTransferTicketParamsToWalletParams(params) {
612
+ const walletParams = await params();
613
+ return this.removeDefaultLimits(walletParams, await taquito.createTransferTicketOperation(this.formatParameters(walletParams)));
614
+ }
615
+ async mapStakeParamsToWalletParams(params) {
616
+ const walletParams = await params();
617
+ return this.removeDefaultLimits(walletParams, await taquito.createTransferOperation(this.formatParameters(walletParams)));
618
+ }
619
+ async mapUnstakeParamsToWalletParams(params) {
620
+ const walletParams = await params();
621
+ return this.removeDefaultLimits(walletParams, await taquito.createTransferOperation(this.formatParameters(walletParams)));
622
+ }
623
+ async mapFinalizeUnstakeParamsToWalletParams(params) {
624
+ const walletParams = await params();
625
+ return this.removeDefaultLimits(walletParams, await taquito.createTransferOperation(this.formatParameters(walletParams)));
626
+ }
627
+ async mapOriginateParamsToWalletParams(params) {
628
+ const walletParams = await params();
629
+ return this.removeDefaultLimits(walletParams, await taquito.createOriginationOperation(this.formatParameters(walletParams)));
630
+ }
631
+ async mapDelegateParamsToWalletParams(params) {
632
+ const walletParams = await params();
633
+ return this.removeDefaultLimits(walletParams, await taquito.createSetDelegateOperation(this.formatParameters(walletParams)));
634
+ }
635
+ async mapIncreasePaidStorageWalletParams(params) {
636
+ const walletParams = await params();
637
+ return this.removeDefaultLimits(walletParams, await taquito.createIncreasePaidStorageOperation(this.formatParameters(walletParams)));
638
+ }
639
+ async mapRegisterGlobalConstantParamsToWalletParams(params) {
640
+ const walletParams = await params();
641
+ return this.removeDefaultLimits(walletParams, await taquito.createRegisterGlobalConstantOperation(this.formatParameters(walletParams)));
642
+ }
643
+ }
199
644
 
200
- /**
201
- * @packageDocumentation
202
- * @module @taquito/wallet-connect
203
- */
204
- const TEZOS_PLACEHOLDER = 'tezos';
205
- /**
206
- * @description The `WalletConnect` class implements the `WalletProvider` interface, providing an alternative to `BeaconWallet`.
207
- * This package enables dapps built with Taquito to connect to wallets via the WalletConnect/Reown protocol.
208
- * @note Currently, a QR code is displayed to establish a connection with a wallet. As more Tezos wallets integrate with WalletConnect,
209
- * we plan showing a list of available wallets alongside the QR code.
210
- */
211
- class WalletConnect {
212
- constructor(signClient, WalletConnectModal) {
213
- this.signClient = signClient;
214
- this.walletConnectModal = WalletConnectModal;
215
- this.signClient.on('session_delete', ({ topic }) => {
216
- var _a;
217
- if (((_a = this.session) === null || _a === void 0 ? void 0 : _a.topic) === topic) {
218
- this.session = undefined;
219
- }
220
- });
221
- this.signClient.on('session_expire', ({ topic }) => {
222
- var _a;
223
- if (((_a = this.session) === null || _a === void 0 ? void 0 : _a.topic) === topic) {
224
- this.session = undefined;
225
- }
226
- });
227
- this.signClient.on('session_update', ({ params, topic }) => {
228
- var _a;
229
- if (((_a = this.session) === null || _a === void 0 ? void 0 : _a.topic) === topic) {
230
- this.session.namespaces = params.namespaces;
231
- // TODO determine if we need validation on the namespace here
232
- }
233
- });
234
- this.signClient.on('session_event', () => {
235
- // TODO Do we need to handle other session events, such as "chainChanged", "accountsChanged", etc.
236
- });
237
- }
238
- /**
239
- * @description Initialize a WalletConnect provider
240
- * (Initialize a WalletConnect client with persisted storage and a network connection)
241
- *
242
- * @example
243
- * ```
244
- * await WalletConnect.init({
245
- * projectId: "YOUR_PROJECT_ID", // can get YOUR_PROJECT_ID from [Reown Cloud](https://cloud.reown.com)
246
- * metadata: {
247
- * name: "YOUR_DAPP_NAME",
248
- * description: "YOUR_DAPP_DESCRIPTION",
249
- * icons: ["ICON_URL"],
250
- * url: "DAPP_URL",
251
- * },
252
- * });
253
- * ```
254
- */
255
- static init(initParams) {
256
- return __awaiter(this, void 0, void 0, function* () {
257
- if (!initParams.projectId) {
258
- throw new Error('projectId is required');
259
- }
260
- const client = yield Client.init(initParams);
261
- const walletConnectModal = new modal.WalletConnectModal({
262
- projectId: initParams.projectId,
263
- });
264
- return new WalletConnect(client, walletConnectModal);
265
- });
266
- }
267
- /**
268
- * @description Request permission for a new session and establish a connection.
269
- *
270
- * @param connectParams.permissionScope The networks, methods, and events that will be granted permission
271
- * @param connectParams.pairingTopic Option to connect to an existing active pairing. If pairingTopic is defined, a prompt will appear in the corresponding wallet to accept or decline the session proposal. If no pairingTopic, a QR code modal will open in the dapp, allowing to connect to a wallet.
272
- * @param connectParams.registryUrl Optional registry of wallet deep links to show in the Modal
273
- * @error ConnectionFailed is thrown if no connection can be established with a wallet
274
- */
275
- requestPermissions(connectParams) {
276
- return __awaiter(this, void 0, void 0, function* () {
277
- var _a;
278
- // TODO when Tezos wallets will officially support wallet connect, we need to provide a default value for registryUrl
279
- try {
280
- const chains = connectParams.permissionScope.networks.map((network) => `${TEZOS_PLACEHOLDER}:${network}`);
281
- const { uri, approval } = yield this.signClient.connect({
282
- requiredNamespaces: {
283
- [TEZOS_PLACEHOLDER]: {
284
- chains,
285
- methods: connectParams.permissionScope.methods,
286
- events: (_a = connectParams.permissionScope.events) !== null && _a !== void 0 ? _a : [],
287
- },
288
- },
289
- pairingTopic: connectParams.pairingTopic,
290
- });
291
- if (uri) {
292
- this.walletConnectModal.openModal({
293
- uri,
294
- chains,
295
- });
296
- }
297
- this.session = yield approval();
298
- }
299
- catch (error) {
300
- throw new ConnectionFailed(error);
301
- }
302
- finally {
303
- this.walletConnectModal.closeModal();
304
- }
305
- this.validateReceivedNamespace(connectParams.permissionScope, this.session.namespaces);
306
- this.setDefaultAccountAndNetwork();
307
- });
308
- }
309
- /**
310
- * @description Access all existing active pairings
311
- */
312
- getAvailablePairing() {
313
- return this.signClient.pairing.getAll({ active: true });
314
- }
315
- /**
316
- * @description Access all existing sessions
317
- * @return an array of strings which represent the session keys
318
- */
319
- getAllExistingSessionKeys() {
320
- return this.signClient.session.keys;
321
- }
322
- /**
323
- * @description Configure the Client with an existing session.
324
- * The session is immediately restored without a prompt on the wallet to accept/decline it.
325
- * @error InvalidSessionKey is thrown if the provided session key doesn't exist
326
- */
327
- configureWithExistingSessionKey(key) {
328
- const sessions = this.getAllExistingSessionKeys();
329
- if (!sessions.includes(key)) {
330
- throw new InvalidSessionKey(key);
331
- }
332
- this.session = this.signClient.session.get(key);
333
- this.setDefaultAccountAndNetwork();
334
- }
335
- disconnect() {
336
- return __awaiter(this, void 0, void 0, function* () {
337
- if (this.session) {
338
- yield this.signClient.disconnect({
339
- topic: this.session.topic,
340
- reason: utils.getSdkError('USER_DISCONNECTED'),
341
- });
342
- this.clearState();
343
- }
344
- });
345
- }
346
- getPeerMetadata() {
347
- return this.getSession().peer.metadata;
348
- }
349
- /**
350
- * @description Once the session is establish, send Tezos operations to be approved, signed and inject by the wallet.
351
- * @error MissingRequiredScope is thrown if permission to send operation was not granted
352
- */
353
- sendOperations(params) {
354
- return __awaiter(this, void 0, void 0, function* () {
355
- const session = this.getSession();
356
- if (!this.getPermittedMethods().includes(exports.PermissionScopeMethods.TEZOS_SEND)) {
357
- throw new MissingRequiredScope(exports.PermissionScopeMethods.TEZOS_SEND);
358
- }
359
- const network = this.getActiveNetwork();
360
- const account = yield this.getPKH();
361
- this.validateNetworkAndAccount(network, account);
362
- const { operationHash } = yield this.signClient.request({
363
- topic: session.topic,
364
- chainId: `${TEZOS_PLACEHOLDER}:${network}`,
365
- request: {
366
- method: exports.PermissionScopeMethods.TEZOS_SEND,
367
- params: {
368
- account,
369
- operations: params,
370
- },
371
- },
372
- });
373
- return operationHash;
374
- });
375
- }
376
- /**
377
- * @description Once the session is establish, send payload to be signed by the wallet.
378
- * @error MissingRequiredScope is thrown if permission to sign payload was not granted
379
- */
380
- sign(bytes, watermark) {
381
- return __awaiter(this, void 0, void 0, function* () {
382
- const session = this.getSession();
383
- if (!this.getPermittedMethods().includes(exports.PermissionScopeMethods.TEZOS_SIGN)) {
384
- throw new MissingRequiredScope(exports.PermissionScopeMethods.TEZOS_SIGN);
385
- }
386
- const network = this.getActiveNetwork();
387
- const account = yield this.getPKH();
388
- this.validateNetworkAndAccount(network, account);
389
- let expression = bytes;
390
- if (watermark) {
391
- expression =
392
- Array.from(watermark, (byte) => byte.toString(16).padStart(2, '0')).join('') + expression;
393
- }
394
- const { signature } = yield this.signClient.request({
395
- topic: session.topic,
396
- chainId: `${TEZOS_PLACEHOLDER}:${network}`,
397
- request: {
398
- method: exports.PermissionScopeMethods.TEZOS_SIGN,
399
- params: {
400
- account: yield this.getPKH(),
401
- payload: expression,
402
- },
403
- },
404
- });
405
- return signature;
406
- });
407
- }
408
- /**
409
- * @description Return all connected accounts from the active session
410
- * @error NotConnected if no active session
411
- */
412
- getAccounts() {
413
- return this.getTezosNamespace().accounts.map((account) => account.split(':')[2]);
414
- }
415
- /**
416
- * @description Set the active account.
417
- * Must be called if there are multiple accounts in the session and every time the active account is switched
418
- * @param pkh public key hash of the selected account
419
- * @error InvalidAccount thrown if the pkh is not part of the active accounts in the session
420
- */
421
- setActiveAccount(pkh) {
422
- if (!this.getAccounts().includes(pkh)) {
423
- throw new InvalidAccount(pkh);
424
- }
425
- this.activeAccount = pkh;
426
- }
427
- /**
428
- * @description Access the public key hash of the active account
429
- * @error ActiveAccountUnspecified thrown when there are multiple Tezos account in the session and none is set as the active one
430
- */
431
- getPKH() {
432
- return __awaiter(this, void 0, void 0, function* () {
433
- if (!this.activeAccount) {
434
- this.getSession();
435
- throw new ActiveAccountUnspecified();
436
- }
437
- return this.activeAccount;
438
- });
439
- }
440
- /**
441
- * @description Access the public key of the active account
442
- * @error ActiveAccountUnspecified thrown when there are multiple Tezos account in the session and none is set as the active one
443
- * @error MissingRequiredScope is thrown if permission to get accounts was not granted
444
- * @error PublicKeyRetrievalError is thrown if the public key is not found
445
- */
446
- getPK() {
447
- return __awaiter(this, void 0, void 0, function* () {
448
- const session = this.getSession();
449
- if (!this.getPermittedMethods().includes(exports.PermissionScopeMethods.TEZOS_GET_ACCOUNTS)) {
450
- throw new MissingRequiredScope(exports.PermissionScopeMethods.TEZOS_GET_ACCOUNTS);
451
- }
452
- const network = this.getActiveNetwork();
453
- const account = yield this.getPKH();
454
- const accounts = yield this.signClient.request({
455
- topic: session.topic,
456
- chainId: `${TEZOS_PLACEHOLDER}:${network}`,
457
- request: {
458
- method: exports.PermissionScopeMethods.TEZOS_GET_ACCOUNTS,
459
- params: {},
460
- },
461
- });
462
- const selectedAccount = accounts.find((acc) => acc.address === account);
463
- if (!selectedAccount) {
464
- throw new PublicKeyRetrievalError();
465
- }
466
- return selectedAccount.pubkey;
467
- });
468
- }
469
- /**
470
- * @description Return all networks from the namespace of the active session
471
- * @error NotConnected if no active session
472
- */
473
- getNetworks() {
474
- return this.getPermittedNetwork();
475
- }
476
- /**
477
- * @description Set the active network.
478
- * Must be called if there are multiple network in the session and every time the active network is switched
479
- * @param network selected network
480
- * @error InvalidNetwork thrown if the network is not part of the active networks in the session
481
- */
482
- setActiveNetwork(network) {
483
- if (!this.getNetworks().includes(network)) {
484
- throw new InvalidNetwork(network);
485
- }
486
- this.activeNetwork = network;
487
- }
488
- /**
489
- * @description Access the active network
490
- * @error ActiveNetworkUnspecified thorwn when there are multiple Tezos netwroks in the session and none is set as the active one
491
- */
492
- getActiveNetwork() {
493
- if (!this.activeNetwork) {
494
- this.getSession();
495
- throw new ActiveNetworkUnspecified();
496
- }
497
- return this.activeNetwork;
498
- }
499
- setDefaultAccountAndNetwork() {
500
- const activeAccount = this.getAccounts();
501
- if (activeAccount.length === 1) {
502
- this.activeAccount = activeAccount[0];
503
- }
504
- const activeNetwork = this.getNetworks();
505
- if (activeNetwork.length === 1) {
506
- this.activeNetwork = activeNetwork[0];
507
- }
508
- }
509
- clearState() {
510
- this.session = undefined;
511
- this.activeAccount = undefined;
512
- this.activeNetwork = undefined;
513
- }
514
- getSession() {
515
- if (!this.session) {
516
- throw new NotConnected();
517
- }
518
- return this.session;
519
- }
520
- isActiveSession() {
521
- return this.session ? true : false;
522
- }
523
- ping() {
524
- this.signClient.ping({ topic: this.getSession().topic });
525
- }
526
- // https://docs.reown.com/api/sign/wallet-usage#namespaces
527
- // TODO: add validations related to Namespaces extensions and related unit tests:
528
- validateReceivedNamespace(scope, receivedNamespaces) {
529
- if (receivedNamespaces[TEZOS_PLACEHOLDER]) {
530
- this.validateMethods(scope.methods, receivedNamespaces[TEZOS_PLACEHOLDER].methods);
531
- if (scope.events) {
532
- this.validateEvents(scope.events, receivedNamespaces['tezos'].events);
533
- }
534
- this.validateAccounts(scope.networks, receivedNamespaces[TEZOS_PLACEHOLDER].accounts);
535
- }
536
- else {
537
- this.clearState();
538
- throw new InvalidReceivedSessionNamespace('All namespaces must be approved', utils.getSdkError('USER_REJECTED').code, 'incomplete', 'tezos');
539
- }
540
- }
541
- validateMethods(requiredMethods, receivedMethods) {
542
- const missingMethods = [];
543
- requiredMethods.forEach((method) => {
544
- if (!receivedMethods.includes(method)) {
545
- missingMethods.push(method);
546
- }
547
- });
548
- if (missingMethods.length > 0) {
549
- this.clearState();
550
- throw new InvalidReceivedSessionNamespace('All methods must be approved', utils.getSdkError('USER_REJECTED_METHODS').code, 'incomplete', missingMethods);
551
- }
552
- }
553
- validateEvents(requiredEvents, receivedEvents) {
554
- const missingEvents = [];
555
- requiredEvents.forEach((method) => {
556
- if (!receivedEvents.includes(method)) {
557
- missingEvents.push(method);
558
- }
559
- });
560
- if (missingEvents.length > 0) {
561
- this.clearState();
562
- throw new InvalidReceivedSessionNamespace('All events must be approved', utils.getSdkError('USER_REJECTED_EVENTS').code, 'incomplete', missingEvents);
563
- }
564
- }
565
- validateAccounts(requiredNetwork, receivedAccounts) {
566
- if (receivedAccounts.length === 0) {
567
- this.clearState();
568
- throw new InvalidReceivedSessionNamespace('Accounts must not be empty', utils.getSdkError('USER_REJECTED_CHAINS').code, 'incomplete');
569
- }
570
- const receivedChains = [];
571
- const invalidChains = [];
572
- const missingChains = [];
573
- const invalidChainsNamespace = [];
574
- receivedAccounts.forEach((chain) => {
575
- const accountId = chain.split(':');
576
- if (accountId.length !== 3) {
577
- invalidChains.push(chain);
578
- }
579
- if (accountId[0] !== TEZOS_PLACEHOLDER) {
580
- invalidChainsNamespace.push(chain);
581
- }
582
- const network = accountId[1];
583
- if (!receivedChains.includes(network)) {
584
- receivedChains.push(network);
585
- }
586
- });
587
- if (invalidChains.length > 0) {
588
- this.clearState();
589
- throw new InvalidReceivedSessionNamespace('Accounts must be CAIP-10 compliant', utils.getSdkError('USER_REJECTED_CHAINS').code, 'invalid', invalidChains);
590
- }
591
- if (invalidChainsNamespace.length > 0) {
592
- this.clearState();
593
- throw new InvalidReceivedSessionNamespace('Accounts must be defined in matching namespace', utils.getSdkError('UNSUPPORTED_ACCOUNTS').code, 'invalid', invalidChainsNamespace);
594
- }
595
- requiredNetwork.forEach((network) => {
596
- if (!receivedChains.includes(network)) {
597
- missingChains.push(network);
598
- }
599
- });
600
- if (missingChains.length > 0) {
601
- this.clearState();
602
- throw new InvalidReceivedSessionNamespace('All chains must have at least one account', utils.getSdkError('USER_REJECTED_CHAINS').code, 'incomplete', missingChains);
603
- }
604
- }
605
- getTezosNamespace() {
606
- if (TEZOS_PLACEHOLDER in this.getSession().namespaces) {
607
- return this.getSession().namespaces[TEZOS_PLACEHOLDER];
608
- }
609
- else {
610
- throw new InvalidSession('Tezos not found in namespaces');
611
- }
612
- }
613
- getTezosRequiredNamespace() {
614
- if (TEZOS_PLACEHOLDER in this.getSession().requiredNamespaces) {
615
- return this.getSession().requiredNamespaces[TEZOS_PLACEHOLDER];
616
- }
617
- else {
618
- throw new InvalidSession('Tezos not found in requiredNamespaces');
619
- }
620
- }
621
- validateNetworkAndAccount(network, account) {
622
- if (!this.getTezosNamespace().accounts.includes(`${TEZOS_PLACEHOLDER}:${network}:${account}`)) {
623
- throw new InvalidNetworkOrAccount(network, account);
624
- }
625
- }
626
- getPermittedMethods() {
627
- return this.getTezosRequiredNamespace().methods;
628
- }
629
- getPermittedNetwork() {
630
- return this.getTezosRequiredNamespace().chains.map((chain) => chain.split(':')[1]);
631
- }
632
- formatParameters(params) {
633
- const formatedParams = params;
634
- if (typeof params.fee !== 'undefined') {
635
- formatedParams.fee = params.fee.toString();
636
- }
637
- if (typeof params.storageLimit !== 'undefined') {
638
- formatedParams.storageLimit = params.storageLimit.toString();
639
- }
640
- if (typeof params.gasLimit !== 'undefined') {
641
- formatedParams.gasLimit = params.gasLimit.toString();
642
- }
643
- return formatedParams;
644
- }
645
- removeDefaultLimits(params, operatedParams) {
646
- if (typeof params.fee === 'undefined') {
647
- delete operatedParams.fee;
648
- }
649
- if (typeof params.storageLimit === 'undefined') {
650
- delete operatedParams.storage_limit;
651
- }
652
- if (typeof params.gasLimit === 'undefined') {
653
- delete operatedParams.gas_limit;
654
- }
655
- return operatedParams;
656
- }
657
- mapTransferParamsToWalletParams(params) {
658
- return __awaiter(this, void 0, void 0, function* () {
659
- const walletParams = yield params();
660
- return this.removeDefaultLimits(walletParams, yield taquito.createTransferOperation(this.formatParameters(walletParams)));
661
- });
662
- }
663
- mapTransferTicketParamsToWalletParams(params) {
664
- return __awaiter(this, void 0, void 0, function* () {
665
- const walletParams = yield params();
666
- return this.removeDefaultLimits(walletParams, yield taquito.createTransferTicketOperation(this.formatParameters(walletParams)));
667
- });
668
- }
669
- mapStakeParamsToWalletParams(params) {
670
- return __awaiter(this, void 0, void 0, function* () {
671
- const walletParams = yield params();
672
- return this.removeDefaultLimits(walletParams, yield taquito.createTransferOperation(this.formatParameters(walletParams)));
673
- });
674
- }
675
- mapUnstakeParamsToWalletParams(params) {
676
- return __awaiter(this, void 0, void 0, function* () {
677
- const walletParams = yield params();
678
- return this.removeDefaultLimits(walletParams, yield taquito.createTransferOperation(this.formatParameters(walletParams)));
679
- });
680
- }
681
- mapFinalizeUnstakeParamsToWalletParams(params) {
682
- return __awaiter(this, void 0, void 0, function* () {
683
- const walletParams = yield params();
684
- return this.removeDefaultLimits(walletParams, yield taquito.createTransferOperation(this.formatParameters(walletParams)));
685
- });
686
- }
687
- mapOriginateParamsToWalletParams(params) {
688
- return __awaiter(this, void 0, void 0, function* () {
689
- const walletParams = yield params();
690
- return this.removeDefaultLimits(walletParams, yield taquito.createOriginationOperation(this.formatParameters(walletParams)));
691
- });
692
- }
693
- mapDelegateParamsToWalletParams(params) {
694
- return __awaiter(this, void 0, void 0, function* () {
695
- const walletParams = yield params();
696
- return this.removeDefaultLimits(walletParams, yield taquito.createSetDelegateOperation(this.formatParameters(walletParams)));
697
- });
698
- }
699
- mapIncreasePaidStorageWalletParams(params) {
700
- return __awaiter(this, void 0, void 0, function* () {
701
- const walletParams = yield params();
702
- return this.removeDefaultLimits(walletParams, yield taquito.createIncreasePaidStorageOperation(this.formatParameters(walletParams)));
703
- });
704
- }
705
- mapRegisterGlobalConstantParamsToWalletParams(params) {
706
- return __awaiter(this, void 0, void 0, function* () {
707
- const walletParams = yield params();
708
- return this.removeDefaultLimits(walletParams, yield taquito.createRegisterGlobalConstantOperation(this.formatParameters(walletParams)));
709
- });
710
- }
711
- }
712
-
713
- exports.ActiveAccountUnspecified = ActiveAccountUnspecified;
714
- exports.ActiveNetworkUnspecified = ActiveNetworkUnspecified;
715
- exports.ConnectionFailed = ConnectionFailed;
716
- exports.InvalidAccount = InvalidAccount;
717
- exports.InvalidNetwork = InvalidNetwork;
718
- exports.InvalidNetworkOrAccount = InvalidNetworkOrAccount;
719
- exports.InvalidReceivedSessionNamespace = InvalidReceivedSessionNamespace;
720
- exports.InvalidSession = InvalidSession;
721
- exports.InvalidSessionKey = InvalidSessionKey;
722
- exports.MissingRequiredScope = MissingRequiredScope;
723
- exports.NotConnected = NotConnected;
724
- exports.PublicKeyRetrievalError = PublicKeyRetrievalError;
725
- exports.WalletConnect = WalletConnect;
645
+ exports.ActiveAccountUnspecified = ActiveAccountUnspecified;
646
+ exports.ActiveNetworkUnspecified = ActiveNetworkUnspecified;
647
+ exports.ConnectionFailed = ConnectionFailed;
648
+ exports.InvalidAccount = InvalidAccount;
649
+ exports.InvalidNetwork = InvalidNetwork;
650
+ exports.InvalidNetworkOrAccount = InvalidNetworkOrAccount;
651
+ exports.InvalidReceivedSessionNamespace = InvalidReceivedSessionNamespace;
652
+ exports.InvalidSession = InvalidSession;
653
+ exports.InvalidSessionKey = InvalidSessionKey;
654
+ exports.MissingRequiredScope = MissingRequiredScope;
655
+ exports.NotConnected = NotConnected;
656
+ exports.PublicKeyRetrievalError = PublicKeyRetrievalError;
657
+ exports.WalletConnect = WalletConnect;
726
658
 
727
659
  }));
728
660
  //# sourceMappingURL=taquito-wallet-connect.umd.js.map