@injectivelabs/wallet-turnkey 1.16.38 → 1.16.39-alpha.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 (41) hide show
  1. package/dist/cjs/index.cjs +689 -0
  2. package/dist/cjs/index.d.cts +97 -0
  3. package/dist/cjs/package.json +2 -2
  4. package/dist/esm/index.d.ts +97 -3
  5. package/dist/esm/index.js +688 -3
  6. package/dist/esm/package.json +2 -2
  7. package/package.json +46 -56
  8. package/dist/cjs/index.d.ts +0 -3
  9. package/dist/cjs/index.js +0 -21
  10. package/dist/cjs/strategy/Eip1193Provider.d.ts +0 -3
  11. package/dist/cjs/strategy/Eip1193Provider.js +0 -131
  12. package/dist/cjs/strategy/consts.d.ts +0 -13
  13. package/dist/cjs/strategy/consts.js +0 -16
  14. package/dist/cjs/strategy/strategy.d.ts +0 -48
  15. package/dist/cjs/strategy/strategy.js +0 -275
  16. package/dist/cjs/strategy/turnkey/oauth.d.ts +0 -16
  17. package/dist/cjs/strategy/turnkey/oauth.js +0 -53
  18. package/dist/cjs/strategy/turnkey/otp.d.ts +0 -23
  19. package/dist/cjs/strategy/turnkey/otp.js +0 -65
  20. package/dist/cjs/strategy/turnkey/turnkey.d.ts +0 -35
  21. package/dist/cjs/strategy/turnkey/turnkey.js +0 -259
  22. package/dist/cjs/strategy/types.d.ts +0 -28
  23. package/dist/cjs/strategy/types.js +0 -6
  24. package/dist/cjs/utils.d.ts +0 -7
  25. package/dist/cjs/utils.js +0 -10
  26. package/dist/esm/strategy/Eip1193Provider.d.ts +0 -3
  27. package/dist/esm/strategy/Eip1193Provider.js +0 -127
  28. package/dist/esm/strategy/consts.d.ts +0 -13
  29. package/dist/esm/strategy/consts.js +0 -13
  30. package/dist/esm/strategy/strategy.d.ts +0 -48
  31. package/dist/esm/strategy/strategy.js +0 -271
  32. package/dist/esm/strategy/turnkey/oauth.d.ts +0 -16
  33. package/dist/esm/strategy/turnkey/oauth.js +0 -49
  34. package/dist/esm/strategy/turnkey/otp.d.ts +0 -23
  35. package/dist/esm/strategy/turnkey/otp.js +0 -61
  36. package/dist/esm/strategy/turnkey/turnkey.d.ts +0 -35
  37. package/dist/esm/strategy/turnkey/turnkey.js +0 -255
  38. package/dist/esm/strategy/types.d.ts +0 -28
  39. package/dist/esm/strategy/types.js +0 -3
  40. package/dist/esm/utils.d.ts +0 -7
  41. package/dist/esm/utils.js +0 -7
@@ -0,0 +1,689 @@
1
+ let viem = require("viem");
2
+ let __injectivelabs_utils = require("@injectivelabs/utils");
3
+ let __injectivelabs_sdk_ts_core_tx = require("@injectivelabs/sdk-ts/core/tx");
4
+ let __injectivelabs_sdk_ts_utils = require("@injectivelabs/sdk-ts/utils");
5
+ let __injectivelabs_exceptions = require("@injectivelabs/exceptions");
6
+ let __injectivelabs_wallet_base = require("@injectivelabs/wallet-base");
7
+ let __turnkey_viem = require("@turnkey/viem");
8
+ let __turnkey_sdk_browser = require("@turnkey/sdk-browser");
9
+
10
+ //#region src/strategy/types.ts
11
+ const TurnkeyErrorCodes = { UserLoggedOut: 7 };
12
+
13
+ //#endregion
14
+ //#region src/strategy/consts.ts
15
+ const TURNKEY_OAUTH_PATH = "turnkey/oauth";
16
+ const TURNKEY_OTP_PATH = "turnkey/otp";
17
+ const TURNKEY_OTP_INIT_PATH = `${TURNKEY_OTP_PATH}/init`;
18
+ const TURNKEY_OTP_VERIFY_PATH = `${TURNKEY_OTP_PATH}/verify`;
19
+ const DEFAULT_TURNKEY_REFRESH_SECONDS = "86400";
20
+
21
+ //#endregion
22
+ //#region src/strategy/turnkey/otp.ts
23
+ var TurnkeyOtpWallet = class {
24
+ static async initEmailOTP(args) {
25
+ const { client, indexedDbClient, expirationSeconds } = args;
26
+ try {
27
+ await indexedDbClient.resetKeyPair();
28
+ let publicKey = await indexedDbClient.getPublicKey();
29
+ if (!publicKey) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Public key not found"));
30
+ const response = await client.post(args.otpInitPath || TURNKEY_OTP_INIT_PATH, {
31
+ targetPublicKey: publicKey,
32
+ email: args.email,
33
+ suborgId: args.subOrgId,
34
+ invalidateExistingSessions: args.invalidateExistingSessions,
35
+ isUsingIndexedDB: true,
36
+ expirationSeconds: expirationSeconds || DEFAULT_TURNKEY_REFRESH_SECONDS
37
+ });
38
+ return response === null || response === void 0 ? void 0 : response.data;
39
+ } catch (e) {
40
+ throw new __injectivelabs_exceptions.WalletException(new Error(e.message), {
41
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
42
+ type: __injectivelabs_exceptions.ErrorType.WalletError,
43
+ contextModule: "turnkey-init-email-otp"
44
+ });
45
+ }
46
+ }
47
+ static async confirmEmailOTP(args) {
48
+ const { client, expirationSeconds, targetPublicKey } = args;
49
+ try {
50
+ var _ref;
51
+ const organizationId = args.organizationId;
52
+ const emailOTPId = args.emailOTPId;
53
+ const otpVerifyPath = args.otpVerifyPath || TURNKEY_OTP_VERIFY_PATH;
54
+ if (!emailOTPId) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Email OTP ID is required"));
55
+ if (!organizationId) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Organization ID is required"));
56
+ const response = await client.post(otpVerifyPath, {
57
+ isUsingIndexedDB: true,
58
+ targetPublicKey,
59
+ otpId: emailOTPId,
60
+ otpCode: args.otpCode,
61
+ suborgID: organizationId,
62
+ expirationSeconds: (_ref = expirationSeconds || DEFAULT_TURNKEY_REFRESH_SECONDS) === null || _ref === void 0 ? void 0 : _ref.toString()
63
+ });
64
+ return response === null || response === void 0 ? void 0 : response.data;
65
+ } catch (e) {
66
+ throw new __injectivelabs_exceptions.WalletException(new Error(e.message), {
67
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
68
+ type: __injectivelabs_exceptions.ErrorType.WalletError,
69
+ contextModule: "turnkey-confirm-email-otp"
70
+ });
71
+ }
72
+ }
73
+ };
74
+
75
+ //#endregion
76
+ //#region src/strategy/turnkey/oauth.ts
77
+ var TurnkeyOauthWallet = class {
78
+ static async generateOAuthNonce(indexedDbClient) {
79
+ try {
80
+ await indexedDbClient.resetKeyPair();
81
+ const targetPublicKey = await indexedDbClient.getPublicKey();
82
+ if (!targetPublicKey) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Target public key not found"));
83
+ return Array.from((0, __injectivelabs_sdk_ts_utils.sha256)(new TextEncoder().encode(targetPublicKey))).map((b) => b.toString(16).padStart(2, "0")).join("");
84
+ } catch (e) {
85
+ throw new __injectivelabs_exceptions.WalletException(new Error(e.message), {
86
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
87
+ type: __injectivelabs_exceptions.ErrorType.WalletError,
88
+ contextModule: "turnkey-generate-oauth-nonce"
89
+ });
90
+ }
91
+ }
92
+ static async oauthLogin(args) {
93
+ const { client, indexedDbClient, expirationSeconds } = args;
94
+ const path = args.oauthLoginPath || TURNKEY_OAUTH_PATH;
95
+ try {
96
+ var _ref;
97
+ const targetPublicKey = await indexedDbClient.getPublicKey();
98
+ if (!targetPublicKey) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Target public key not found"));
99
+ return (await client.post(path, {
100
+ targetPublicKey,
101
+ oidcToken: args.oidcToken,
102
+ providerName: args.providerName,
103
+ expirationSeconds: (_ref = expirationSeconds || DEFAULT_TURNKEY_REFRESH_SECONDS) === null || _ref === void 0 ? void 0 : _ref.toString()
104
+ })).data;
105
+ } catch (e) {
106
+ throw new __injectivelabs_exceptions.WalletException(new Error(e.message), {
107
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
108
+ type: __injectivelabs_exceptions.ErrorType.WalletError,
109
+ contextModule: "turnkey-oauth-login"
110
+ });
111
+ }
112
+ }
113
+ };
114
+
115
+ //#endregion
116
+ //#region src/utils.ts
117
+ function generateGoogleUrl({ nonce, clientId, redirectUri, scope = "openid profile email", prompt = "consent" }) {
118
+ if (!clientId) throw new Error("Google client ID not found");
119
+ return `https://accounts.google.com/o/oauth2/v2/auth?prompt=${prompt}&client_id=${clientId}&redirect_uri=${redirectUri}&response_type=id_token&scope=${scope}&nonce=${nonce}`;
120
+ }
121
+
122
+ //#endregion
123
+ //#region \0@oxc-project+runtime@0.98.0/helpers/typeof.js
124
+ function _typeof(o) {
125
+ "@babel/helpers - typeof";
126
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o$1) {
127
+ return typeof o$1;
128
+ } : function(o$1) {
129
+ return o$1 && "function" == typeof Symbol && o$1.constructor === Symbol && o$1 !== Symbol.prototype ? "symbol" : typeof o$1;
130
+ }, _typeof(o);
131
+ }
132
+
133
+ //#endregion
134
+ //#region \0@oxc-project+runtime@0.98.0/helpers/toPrimitive.js
135
+ function toPrimitive(t, r) {
136
+ if ("object" != _typeof(t) || !t) return t;
137
+ var e = t[Symbol.toPrimitive];
138
+ if (void 0 !== e) {
139
+ var i = e.call(t, r || "default");
140
+ if ("object" != _typeof(i)) return i;
141
+ throw new TypeError("@@toPrimitive must return a primitive value.");
142
+ }
143
+ return ("string" === r ? String : Number)(t);
144
+ }
145
+
146
+ //#endregion
147
+ //#region \0@oxc-project+runtime@0.98.0/helpers/toPropertyKey.js
148
+ function toPropertyKey(t) {
149
+ var i = toPrimitive(t, "string");
150
+ return "symbol" == _typeof(i) ? i : i + "";
151
+ }
152
+
153
+ //#endregion
154
+ //#region \0@oxc-project+runtime@0.98.0/helpers/defineProperty.js
155
+ function _defineProperty(e, r, t) {
156
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
157
+ value: t,
158
+ enumerable: !0,
159
+ configurable: !0,
160
+ writable: !0
161
+ }) : e[r] = t, e;
162
+ }
163
+
164
+ //#endregion
165
+ //#region src/strategy/turnkey/turnkey.ts
166
+ var TurnkeyWallet = class {
167
+ setMetadata(metadata) {
168
+ this.metadata = {
169
+ ...this.metadata,
170
+ ...metadata
171
+ };
172
+ }
173
+ constructor(metadata) {
174
+ _defineProperty(this, "otpId", void 0);
175
+ _defineProperty(this, "turnkey", void 0);
176
+ _defineProperty(this, "userOrganizationId", void 0);
177
+ _defineProperty(this, "client", void 0);
178
+ _defineProperty(this, "metadata", void 0);
179
+ _defineProperty(this, "indexedDbClient", void 0);
180
+ _defineProperty(this, "accountMap", {});
181
+ this.metadata = metadata;
182
+ this.client = new __injectivelabs_utils.HttpRestClient(metadata.apiServerEndpoint);
183
+ }
184
+ static async getTurnkeyInstance(metadata) {
185
+ const { turnkey, indexedDbClient } = await createTurnkeyClient(metadata);
186
+ return {
187
+ turnkey,
188
+ indexedDbClient
189
+ };
190
+ }
191
+ async getTurnkey() {
192
+ if (!this.indexedDbClient) await this.initClient();
193
+ if (!this.turnkey) this.turnkey = new __turnkey_sdk_browser.Turnkey(this.metadata);
194
+ return this.turnkey;
195
+ }
196
+ async getIndexedDbClient() {
197
+ if (!this.indexedDbClient) await this.initClient();
198
+ if (!this.indexedDbClient) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Indexed DB client not initialized"));
199
+ return this.indexedDbClient;
200
+ }
201
+ async getSession(existingCredentialBundle) {
202
+ try {
203
+ const { metadata } = this;
204
+ const indexedDbClient = await this.getIndexedDbClient();
205
+ const session = await (await this.getTurnkey()).getSession();
206
+ const organizationId = (session === null || session === void 0 ? void 0 : session.organizationId) || metadata.defaultOrganizationId;
207
+ if (!(existingCredentialBundle || (session === null || session === void 0 ? void 0 : session.token))) return {
208
+ session: void 0,
209
+ organizationId
210
+ };
211
+ const user = await indexedDbClient.getWhoami();
212
+ const actualOrganizationId = (user === null || user === void 0 ? void 0 : user.organizationId) || (session === null || session === void 0 ? void 0 : session.organizationId) || organizationId;
213
+ if (!user) return {
214
+ session: void 0,
215
+ organizationId: actualOrganizationId
216
+ };
217
+ this.userOrganizationId = actualOrganizationId;
218
+ return {
219
+ session,
220
+ organizationId: actualOrganizationId
221
+ };
222
+ } catch (_unused) {
223
+ throw new __injectivelabs_exceptions.TurnkeyWalletSessionException(/* @__PURE__ */ new Error("Session expired. Please login again."));
224
+ }
225
+ }
226
+ async getAccounts() {
227
+ const indexedDbClient = await this.getIndexedDbClient();
228
+ if (!this.userOrganizationId) return [];
229
+ try {
230
+ const response = await indexedDbClient.getWallets({ organizationId: this.userOrganizationId });
231
+ return (await Promise.allSettled(response.wallets.map((wallet) => indexedDbClient.getWalletAccounts({
232
+ walletId: wallet.walletId,
233
+ organizationId: this.userOrganizationId
234
+ })))).filter((account) => account.status === "fulfilled").flatMap((result) => {
235
+ var _result$value;
236
+ return (_result$value = result.value) === null || _result$value === void 0 ? void 0 : _result$value.accounts;
237
+ }).filter((wa) => !!wa && wa.addressFormat === "ADDRESS_FORMAT_ETHEREUM" && !!wa.address).map((account) => (0, __injectivelabs_sdk_ts_utils.getInjectiveAddress)(account.address));
238
+ } catch (e) {
239
+ if (e.code === TurnkeyErrorCodes.UserLoggedOut) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("User is not logged in"), {
240
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
241
+ type: __injectivelabs_exceptions.ErrorType.WalletError,
242
+ contextModule: __injectivelabs_wallet_base.WalletAction.GetAccounts,
243
+ contextCode: TurnkeyErrorCodes.UserLoggedOut
244
+ });
245
+ throw new __injectivelabs_exceptions.WalletException(new Error(e.message), {
246
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
247
+ type: __injectivelabs_exceptions.ErrorType.WalletError,
248
+ contextModule: "turnkey-wallet-get-accounts"
249
+ });
250
+ }
251
+ }
252
+ async getOrCreateAndGetAccount(address) {
253
+ const { accountMap } = this;
254
+ const indexedDbClient = await this.getIndexedDbClient();
255
+ const organizationId = this.userOrganizationId;
256
+ if (accountMap[address] || accountMap[address.toLowerCase()]) return accountMap[address] || accountMap[address.toLowerCase()];
257
+ if (!organizationId) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Organization ID is required"));
258
+ indexedDbClient.config.organizationId = organizationId;
259
+ if (!address) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Account address not found"));
260
+ const turnkeyAccount = await (0, __turnkey_viem.createAccount)({
261
+ organizationId,
262
+ signWith: address,
263
+ client: indexedDbClient
264
+ });
265
+ this.accountMap[address] = turnkeyAccount;
266
+ return turnkeyAccount;
267
+ }
268
+ async initOTP(email) {
269
+ const indexedDbClient = await this.getIndexedDbClient();
270
+ const result = await TurnkeyOtpWallet.initEmailOTP({
271
+ client: this.client,
272
+ indexedDbClient,
273
+ email,
274
+ otpInitPath: this.metadata.otpInitPath || TURNKEY_OTP_INIT_PATH
275
+ });
276
+ if (!result || !result.otpId) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Failed to initialize OTP"));
277
+ if (result === null || result === void 0 ? void 0 : result.organizationId) this.userOrganizationId = result.organizationId;
278
+ if (result === null || result === void 0 ? void 0 : result.otpId) this.otpId = result.otpId;
279
+ return result;
280
+ }
281
+ async confirmOTP(otpCode) {
282
+ const indexedDbClient = await this.getIndexedDbClient();
283
+ const targetPublicKey = await indexedDbClient.getPublicKey();
284
+ if (!this.otpId) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("OTP ID is required"));
285
+ if (!targetPublicKey) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Target public key not found"));
286
+ if (!this.userOrganizationId) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Organization ID is required"));
287
+ const result = await TurnkeyOtpWallet.confirmEmailOTP({
288
+ otpCode,
289
+ client: this.client,
290
+ emailOTPId: this.otpId,
291
+ organizationId: this.userOrganizationId,
292
+ targetPublicKey,
293
+ otpVerifyPath: this.metadata.otpVerifyPath || TURNKEY_OTP_VERIFY_PATH
294
+ });
295
+ if (!result || !result.session) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Failed to confirm OTP"));
296
+ await indexedDbClient.loginWithSession(result.session);
297
+ this.userOrganizationId = result.organizationId;
298
+ return result;
299
+ }
300
+ async initOAuth(provider) {
301
+ var _this$metadata, _this$metadata2;
302
+ if (provider === __injectivelabs_wallet_base.TurnkeyProvider.Apple) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Apple sign in option is currently not supported"));
303
+ const indexedDbClient = await this.getIndexedDbClient();
304
+ const nonce = await TurnkeyOauthWallet.generateOAuthNonce(indexedDbClient);
305
+ if (!((_this$metadata = this.metadata) === null || _this$metadata === void 0 ? void 0 : _this$metadata.googleClientId) || !((_this$metadata2 = this.metadata) === null || _this$metadata2 === void 0 ? void 0 : _this$metadata2.googleRedirectUri)) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("googleClientId and googleRedirectUri are required"));
306
+ return generateGoogleUrl({
307
+ nonce,
308
+ clientId: this.metadata.googleClientId,
309
+ redirectUri: this.metadata.googleRedirectUri
310
+ });
311
+ }
312
+ async confirmOAuth(provider, oidcToken) {
313
+ if (provider === __injectivelabs_wallet_base.TurnkeyProvider.Apple) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Apple sign in option is currently not supported"));
314
+ const indexedDbClient = await this.getIndexedDbClient();
315
+ const oauthResult = await TurnkeyOauthWallet.oauthLogin({
316
+ oidcToken,
317
+ indexedDbClient,
318
+ client: this.client,
319
+ providerName: provider.toString(),
320
+ oauthLoginPath: this.metadata.oauthLoginPath || TURNKEY_OAUTH_PATH
321
+ });
322
+ if (!oauthResult || !oauthResult.credentialBundle) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Unexpected OAuth result"));
323
+ await indexedDbClient.loginWithSession(oauthResult.credentialBundle);
324
+ this.userOrganizationId = oauthResult.organizationId;
325
+ return oauthResult.credentialBundle;
326
+ }
327
+ async refreshSession() {
328
+ var _session$session;
329
+ const session = await this.getSession();
330
+ const indexedDbClient = await this.getIndexedDbClient();
331
+ if ((_session$session = session.session) === null || _session$session === void 0 ? void 0 : _session$session.token) {
332
+ await indexedDbClient.refreshSession({
333
+ sessionType: __turnkey_sdk_browser.SessionType.READ_WRITE,
334
+ expirationSeconds: this.metadata.expirationSeconds
335
+ });
336
+ this.userOrganizationId = session.organizationId;
337
+ return session.session.token;
338
+ }
339
+ throw new __injectivelabs_exceptions.TurnkeyWalletSessionException(/* @__PURE__ */ new Error("Session expired. Please login again."));
340
+ }
341
+ async initClient() {
342
+ const { metadata } = this;
343
+ const { turnkey, indexedDbClient } = await createTurnkeyClient(metadata);
344
+ this.turnkey = turnkey;
345
+ this.indexedDbClient = indexedDbClient;
346
+ return {
347
+ turnkey,
348
+ indexedDbClient
349
+ };
350
+ }
351
+ };
352
+ async function createTurnkeyClient(metadata) {
353
+ const turnkey = new __turnkey_sdk_browser.Turnkey(metadata);
354
+ const indexedDbClient = await turnkey.indexedDbClient();
355
+ await indexedDbClient.init();
356
+ if (!turnkey) throw new __injectivelabs_exceptions.GeneralException(/* @__PURE__ */ new Error("Turnkey is not initialized"));
357
+ return {
358
+ turnkey,
359
+ indexedDbClient
360
+ };
361
+ }
362
+
363
+ //#endregion
364
+ //#region src/strategy/Eip1193Provider.ts
365
+ const getEip1193ProviderForTurnkey = async (account, chainId) => {
366
+ return new CustomEip1193Provider({
367
+ chainId: parseInt(chainId, 16),
368
+ signTypedData: account.signTypedData.bind(account),
369
+ signMessage: account.signMessage.bind(account),
370
+ signTransaction: account.signTransaction.bind(account),
371
+ account,
372
+ address: account.address
373
+ });
374
+ };
375
+ var CustomEip1193Provider = class {
376
+ constructor(args) {
377
+ var _args$chainId;
378
+ _defineProperty(this, "chainId", void 0);
379
+ _defineProperty(this, "signTypedData", void 0);
380
+ _defineProperty(this, "signMessage", void 0);
381
+ _defineProperty(this, "signTransaction", void 0);
382
+ _defineProperty(this, "account", void 0);
383
+ _defineProperty(this, "address", void 0);
384
+ this.chainId = (_args$chainId = args.chainId) !== null && _args$chainId !== void 0 ? _args$chainId : 1;
385
+ this.signTypedData = args.signTypedData;
386
+ this.signMessage = args.signMessage;
387
+ this.account = args.account;
388
+ this.address = args.address;
389
+ this.signTransaction = args.signTransaction;
390
+ }
391
+ async requestAccounts() {
392
+ return [this.address];
393
+ }
394
+ getClient() {
395
+ return (0, __injectivelabs_wallet_base.getViemWalletClient)({
396
+ chainId: this.chainId,
397
+ account: this.account
398
+ });
399
+ }
400
+ getChain() {
401
+ return (0, __injectivelabs_wallet_base.getEvmChainConfig)(this.chainId);
402
+ }
403
+ on(_event, _listener) {
404
+ throw new Error("Not implemented");
405
+ }
406
+ removeListener(..._args) {
407
+ throw new Error("Not implemented!");
408
+ }
409
+ async request(args) {
410
+ if (args.method === "eth_requestAccounts") return this.requestAccounts();
411
+ if (args.method === "eth_signTypedData") {
412
+ if (!args.params) throw new Error("params is required");
413
+ return this.signTypedData(args.params[0]);
414
+ }
415
+ if (args.method === "eth_signMessage") {
416
+ if (!args.params) throw new Error("params is required");
417
+ return this.signMessage(args.params[0]);
418
+ }
419
+ if (args.method === "eth_chainId") return this.chainId;
420
+ if (args.method === "wallet_switchEthereumChain") {
421
+ if (!args.params) throw new Error("params is required");
422
+ const chainId = String(args.params[0].chainId).replace("0x", "");
423
+ this.chainId = parseInt(chainId, 16);
424
+ return true;
425
+ }
426
+ if (args.method === "eth_sendTransaction") {
427
+ if (!args.params) throw new Error("params is required");
428
+ const accountClient = (0, __injectivelabs_wallet_base.getViemWalletClient)({
429
+ chainId: this.chainId,
430
+ account: this.account
431
+ });
432
+ const client = this.getClient();
433
+ const parseHexValue = (value) => {
434
+ if (typeof value === "string") {
435
+ const hexValue = value.startsWith("0x") ? value : `0x${value}`;
436
+ return BigInt(hexValue);
437
+ }
438
+ return BigInt(value);
439
+ };
440
+ const processedTransaction = { ...args.params[0] };
441
+ for (const field of [
442
+ "value",
443
+ "gas",
444
+ "gasLimit",
445
+ "gasPrice",
446
+ "maxFeePerGas",
447
+ "maxPriorityFeePerGas"
448
+ ]) if (processedTransaction[field] !== void 0) processedTransaction[field] = parseHexValue(processedTransaction[field]);
449
+ const preparedTransaction = await accountClient.prepareTransactionRequest(processedTransaction);
450
+ const signedTransaction = await this.signTransaction(preparedTransaction);
451
+ return await client.sendRawTransaction({ serializedTransaction: signedTransaction });
452
+ }
453
+ if (args.method === "eth_getTransactionCount") {
454
+ if (!args.params) throw new Error("params is required");
455
+ return `0x${(await (0, __injectivelabs_wallet_base.getViemPublicClient)(this.chainId).getTransactionCount({
456
+ address: this.address,
457
+ blockTag: "pending"
458
+ })).toString(16)}`;
459
+ }
460
+ return this.getClient().request({
461
+ method: args.method,
462
+ params: args.params
463
+ });
464
+ }
465
+ };
466
+
467
+ //#endregion
468
+ //#region src/strategy/strategy.ts
469
+ var TurnkeyWalletStrategy = class extends __injectivelabs_wallet_base.BaseConcreteStrategy {
470
+ constructor(args) {
471
+ var _this$metadata;
472
+ super(args);
473
+ _defineProperty(this, "turnkeyWallet", void 0);
474
+ _defineProperty(this, "evmOptions", void 0);
475
+ _defineProperty(this, "client", void 0);
476
+ const endpoint = args.apiServerEndpoint || ((_this$metadata = this.metadata) === null || _this$metadata === void 0 || (_this$metadata = _this$metadata.turnkey) === null || _this$metadata === void 0 ? void 0 : _this$metadata.apiServerEndpoint);
477
+ if (!endpoint) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("apiServerEndpoint is required"));
478
+ this.client = new __injectivelabs_utils.HttpRestClient(endpoint);
479
+ this.evmOptions = args.evmOptions;
480
+ }
481
+ async getWalletDeviceType() {
482
+ return Promise.resolve(__injectivelabs_wallet_base.WalletDeviceType.Browser);
483
+ }
484
+ setMetadata(metadata) {
485
+ if (metadata === null || metadata === void 0 ? void 0 : metadata.turnkey) {
486
+ var _this$metadata2, _this$turnkeyWallet, _this$metadata3;
487
+ this.metadata = {
488
+ ...this.metadata,
489
+ turnkey: {
490
+ ...(_this$metadata2 = this.metadata) === null || _this$metadata2 === void 0 ? void 0 : _this$metadata2.turnkey,
491
+ ...metadata.turnkey
492
+ }
493
+ };
494
+ (_this$turnkeyWallet = this.turnkeyWallet) === null || _this$turnkeyWallet === void 0 || _this$turnkeyWallet.setMetadata((_this$metadata3 = this.metadata) === null || _this$metadata3 === void 0 ? void 0 : _this$metadata3.turnkey);
495
+ }
496
+ }
497
+ async enable() {
498
+ const turnkeyWallet = await this.getTurnkeyWallet();
499
+ try {
500
+ const session = await turnkeyWallet.getSession();
501
+ if (session.session) {
502
+ var _this$metadata4;
503
+ if ((_this$metadata4 = this.metadata) === null || _this$metadata4 === void 0 ? void 0 : _this$metadata4.turnkey) this.metadata.turnkey.session = session.session;
504
+ return true;
505
+ }
506
+ return !!await turnkeyWallet.getIndexedDbClient();
507
+ } catch (_unused) {
508
+ return false;
509
+ }
510
+ }
511
+ async disconnect() {
512
+ const turnkeyWallet = await this.getTurnkeyWallet();
513
+ const turnkey = await turnkeyWallet.getTurnkey();
514
+ const indexedDbClient = await turnkeyWallet.getIndexedDbClient();
515
+ if (!await turnkey.getSession()) return;
516
+ await Promise.allSettled([turnkey.logout(), indexedDbClient.clear()]);
517
+ }
518
+ async getAddresses() {
519
+ const turnkeyWallet = await this.getTurnkeyWallet();
520
+ try {
521
+ return await turnkeyWallet.getAccounts();
522
+ } catch (e) {
523
+ if (e.contextCode === TurnkeyErrorCodes.UserLoggedOut) {
524
+ await this.disconnect();
525
+ throw e;
526
+ }
527
+ throw new __injectivelabs_exceptions.WalletException(new Error(e.message), {
528
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
529
+ type: __injectivelabs_exceptions.ErrorType.WalletError,
530
+ contextModule: __injectivelabs_wallet_base.WalletAction.GetAccounts
531
+ });
532
+ }
533
+ }
534
+ async getAddressesInfo() {
535
+ throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("getAddressesInfo is not implemented"), {
536
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
537
+ type: __injectivelabs_exceptions.ErrorType.WalletError,
538
+ contextModule: __injectivelabs_wallet_base.WalletAction.GetAccounts
539
+ });
540
+ }
541
+ async getSessionOrConfirm(_address) {
542
+ return await (await this.getTurnkeyWallet()).refreshSession();
543
+ }
544
+ async getWalletClient() {
545
+ return await this.getTurnkeyWallet();
546
+ }
547
+ async sendEvmTransaction(transaction, args) {
548
+ try {
549
+ var _options$rpcUrls;
550
+ const options = this.evmOptions;
551
+ const turnkeyWallet = await this.getTurnkeyWallet();
552
+ const chainId = args.evmChainId || options.evmChainId;
553
+ const url = options.rpcUrl || ((_options$rpcUrls = options.rpcUrls) === null || _options$rpcUrls === void 0 ? void 0 : _options$rpcUrls[args.evmChainId]);
554
+ if (!url) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Please pass rpcUrl within the evmOptions"), {
555
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
556
+ context: __injectivelabs_wallet_base.WalletAction.SendEvmTransaction
557
+ });
558
+ const accountClient = (0, __injectivelabs_wallet_base.getViemWalletClient)({
559
+ chainId,
560
+ account: await turnkeyWallet.getOrCreateAndGetAccount((0, viem.getAddress)(args.address)),
561
+ rpcUrl: url
562
+ });
563
+ const parseHexValue = (value) => {
564
+ if (typeof value === "string") {
565
+ const hexValue = value.startsWith("0x") ? value : `0x${value}`;
566
+ return BigInt(hexValue);
567
+ }
568
+ return BigInt(value);
569
+ };
570
+ const processedTransaction = { ...transaction };
571
+ for (const field of [
572
+ "value",
573
+ "gas",
574
+ "gasLimit",
575
+ "gasPrice",
576
+ "maxFeePerGas",
577
+ "maxPriorityFeePerGas"
578
+ ]) if (processedTransaction[field] !== void 0) processedTransaction[field] = parseHexValue(processedTransaction[field]);
579
+ const { account: _, ...transactionToSign } = await accountClient.prepareTransactionRequest(processedTransaction);
580
+ const signedTransaction = await accountClient.signTransaction(transactionToSign);
581
+ return await accountClient.sendRawTransaction({ serializedTransaction: signedTransaction });
582
+ } catch (e) {
583
+ throw new __injectivelabs_exceptions.WalletException(e, {
584
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
585
+ context: __injectivelabs_wallet_base.WalletAction.SendEvmTransaction
586
+ });
587
+ }
588
+ }
589
+ async sendTransaction(transaction, options) {
590
+ const { endpoints, txTimeout } = options;
591
+ if (!endpoints) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("You have to pass endpoints.grpc within the options for using Turnkey wallet"));
592
+ const response = await new __injectivelabs_sdk_ts_core_tx.TxGrpcApi(endpoints.grpc).broadcast(transaction, { txTimeout });
593
+ if (response.code !== 0) throw new __injectivelabs_exceptions.TransactionException(new Error(response.rawLog), {
594
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
595
+ contextCode: response.code,
596
+ contextModule: response.codespace
597
+ });
598
+ return response;
599
+ }
600
+ async signEip712TypedData(eip712json, address) {
601
+ const turnkeyWallet = await this.getTurnkeyWallet();
602
+ const checksumAddress = (0, viem.getAddress)(address);
603
+ const account = await turnkeyWallet.getOrCreateAndGetAccount(checksumAddress);
604
+ if (!account) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Turnkey account not found"));
605
+ let parsedData;
606
+ try {
607
+ parsedData = JSON.parse(eip712json);
608
+ } catch (_unused2) {
609
+ throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Failed to parse EIP-712 data: Invalid JSON format"), {
610
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
611
+ type: __injectivelabs_exceptions.ErrorType.WalletError,
612
+ contextModule: __injectivelabs_wallet_base.WalletAction.SignTransaction
613
+ });
614
+ }
615
+ return await account.signTypedData(parsedData);
616
+ }
617
+ async signCosmosTransaction(_transaction) {
618
+ throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("This wallet does not support signing Cosmos transactions"), {
619
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
620
+ type: __injectivelabs_exceptions.ErrorType.WalletError,
621
+ contextModule: __injectivelabs_wallet_base.WalletAction.SignTransaction
622
+ });
623
+ }
624
+ async signAminoCosmosTransaction(_transaction) {
625
+ throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("This wallet does not support signAminoCosmosTransaction"), {
626
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
627
+ type: __injectivelabs_exceptions.ErrorType.WalletError,
628
+ contextModule: __injectivelabs_wallet_base.WalletAction.SignTransaction
629
+ });
630
+ }
631
+ async signArbitrary(_signer, _data) {
632
+ throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("This wallet does not support signArbitrary"), {
633
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
634
+ type: __injectivelabs_exceptions.ErrorType.WalletError,
635
+ contextModule: __injectivelabs_wallet_base.WalletAction.SignTransaction
636
+ });
637
+ }
638
+ async getEthereumChainId() {
639
+ throw new __injectivelabs_exceptions.CosmosWalletException(/* @__PURE__ */ new Error("getEthereumChainId is not supported on Turnkey wallet"), {
640
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
641
+ context: __injectivelabs_wallet_base.WalletAction.GetChainId
642
+ });
643
+ }
644
+ async getEvmTransactionReceipt(txHash, evmChainId) {
645
+ var _options$rpcUrls2;
646
+ const options = this.evmOptions;
647
+ const chainId = evmChainId || options.evmChainId;
648
+ const url = options.rpcUrl || ((_options$rpcUrls2 = options.rpcUrls) === null || _options$rpcUrls2 === void 0 ? void 0 : _options$rpcUrls2[chainId]);
649
+ if (!url) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Please pass rpcUrl within the evmOptions"), {
650
+ code: __injectivelabs_exceptions.UnspecifiedErrorCode,
651
+ context: __injectivelabs_wallet_base.WalletAction.GetEvmTransactionReceipt
652
+ });
653
+ const publicClient = (0, __injectivelabs_wallet_base.getViemPublicClient)(chainId, url);
654
+ try {
655
+ return await publicClient.waitForTransactionReceipt({
656
+ hash: txHash,
657
+ timeout: 3e4,
658
+ pollingInterval: 3e3
659
+ });
660
+ } catch (_unused3) {
661
+ throw new Error(`Failed to retrieve transaction receipt for txHash: ${txHash}`);
662
+ }
663
+ }
664
+ async getPubKey() {
665
+ throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("You can only fetch PubKey from Cosmos native wallets"));
666
+ }
667
+ async getIndexedDbClient() {
668
+ return await (await this.getTurnkeyWallet()).getIndexedDbClient();
669
+ }
670
+ async getTurnkeyWallet() {
671
+ const { metadata } = this;
672
+ if (!this.turnkeyWallet) {
673
+ if (!(metadata === null || metadata === void 0 ? void 0 : metadata.turnkey)) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Turnkey metadata is required"));
674
+ if (!metadata.turnkey.apiBaseUrl) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Turnkey apiBaseUrl is required"));
675
+ if (!metadata.turnkey.apiServerEndpoint) throw new __injectivelabs_exceptions.WalletException(/* @__PURE__ */ new Error("Turnkey apiServerEndpoint is required"));
676
+ this.turnkeyWallet = new TurnkeyWallet(metadata.turnkey);
677
+ }
678
+ return this.turnkeyWallet;
679
+ }
680
+ async getEip1193Provider() {
681
+ const turnkeyWallet = await this.getTurnkeyWallet();
682
+ const checksumAddress = (0, viem.getAddress)((0, __injectivelabs_sdk_ts_utils.getEthereumAddress)((await turnkeyWallet.getAccounts())[0]));
683
+ return await getEip1193ProviderForTurnkey(await turnkeyWallet.getOrCreateAndGetAccount(checksumAddress), String(this.evmOptions.evmChainId));
684
+ }
685
+ };
686
+
687
+ //#endregion
688
+ exports.TurnkeyWallet = TurnkeyWallet;
689
+ exports.TurnkeyWalletStrategy = TurnkeyWalletStrategy;