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