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