@injectivelabs/wallet-trezor 1.16.25-alpha.2 → 1.16.25-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/cjs/index.d.ts +3 -0
  2. package/dist/cjs/index.js +22 -0
  3. package/dist/cjs/package.json +2 -2
  4. package/dist/cjs/strategy/Base.d.ts +44 -0
  5. package/dist/cjs/strategy/Base.js +307 -0
  6. package/dist/cjs/strategy/TrezorBip32.d.ts +5 -0
  7. package/dist/cjs/strategy/TrezorBip32.js +17 -0
  8. package/dist/cjs/strategy/TrezorBip44.d.ts +5 -0
  9. package/dist/cjs/strategy/TrezorBip44.js +17 -0
  10. package/dist/cjs/strategy/hw/AccountManager.d.ts +20 -0
  11. package/dist/cjs/strategy/hw/AccountManager.js +104 -0
  12. package/dist/cjs/strategy/hw/index.d.ts +3 -0
  13. package/dist/cjs/strategy/hw/index.js +10 -0
  14. package/dist/cjs/strategy/hw/transport/base.d.ts +6 -0
  15. package/dist/cjs/strategy/hw/transport/base.js +37 -0
  16. package/dist/cjs/strategy/hw/transport/transport-no-init.d.ts +4 -0
  17. package/dist/cjs/strategy/hw/transport/transport-no-init.js +12 -0
  18. package/dist/cjs/strategy/lib.d.ts +41 -0
  19. package/dist/cjs/strategy/lib.js +44 -0
  20. package/dist/cjs/types.d.ts +15 -0
  21. package/dist/cjs/types.js +8 -0
  22. package/dist/cjs/utils.d.ts +16 -0
  23. package/dist/cjs/utils.js +36 -0
  24. package/dist/esm/index.d.ts +3 -72
  25. package/dist/esm/index.js +3 -479
  26. package/dist/esm/package.json +2 -2
  27. package/dist/esm/strategy/Base.d.ts +44 -0
  28. package/dist/esm/strategy/Base.js +304 -0
  29. package/dist/esm/strategy/TrezorBip32.d.ts +5 -0
  30. package/dist/esm/strategy/TrezorBip32.js +10 -0
  31. package/dist/esm/strategy/TrezorBip44.d.ts +5 -0
  32. package/dist/esm/strategy/TrezorBip44.js +10 -0
  33. package/dist/esm/strategy/hw/AccountManager.d.ts +20 -0
  34. package/dist/esm/strategy/hw/AccountManager.js +101 -0
  35. package/dist/esm/strategy/hw/index.d.ts +3 -0
  36. package/dist/esm/strategy/hw/index.js +3 -0
  37. package/dist/esm/strategy/hw/transport/base.d.ts +6 -0
  38. package/dist/esm/strategy/hw/transport/base.js +31 -0
  39. package/dist/esm/strategy/hw/transport/transport-no-init.d.ts +4 -0
  40. package/dist/esm/strategy/hw/transport/transport-no-init.js +6 -0
  41. package/dist/esm/strategy/lib.d.ts +41 -0
  42. package/dist/esm/strategy/lib.js +8 -0
  43. package/dist/esm/types.d.ts +15 -0
  44. package/dist/esm/types.js +5 -0
  45. package/dist/esm/utils.d.ts +16 -0
  46. package/dist/esm/utils.js +32 -0
  47. package/package.json +17 -17
  48. package/dist/cjs/index.cjs +0 -481
  49. package/dist/cjs/index.d.cts +0 -72
@@ -0,0 +1,3 @@
1
+ export { TrezorBip32 as TrezorBip32Strategy } from './strategy/TrezorBip32.js';
2
+ export { TrezorBip44 as TrezorBip44Strategy } from './strategy/TrezorBip44.js';
3
+ export * from './types.js';
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.TrezorBip44Strategy = exports.TrezorBip32Strategy = void 0;
18
+ var TrezorBip32_js_1 = require("./strategy/TrezorBip32.js");
19
+ Object.defineProperty(exports, "TrezorBip32Strategy", { enumerable: true, get: function () { return TrezorBip32_js_1.TrezorBip32; } });
20
+ var TrezorBip44_js_1 = require("./strategy/TrezorBip44.js");
21
+ Object.defineProperty(exports, "TrezorBip44Strategy", { enumerable: true, get: function () { return TrezorBip44_js_1.TrezorBip44; } });
22
+ __exportStar(require("./types.js"), exports);
@@ -1,3 +1,3 @@
1
1
  {
2
- "type": "commonjs"
3
- }
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1,44 @@
1
+ import { EvmChainId } from '@injectivelabs/ts-types';
2
+ import { WalletDeviceType, BaseConcreteStrategy } from '@injectivelabs/wallet-base';
3
+ import type { TrezorDerivationPathType } from '../types.js';
4
+ import type { AccountAddress, EvmChainId as EvmChainIdType } from '@injectivelabs/ts-types';
5
+ import type { TxRaw, TxResponse, AminoSignResponse, DirectSignResponse } from '@injectivelabs/sdk-ts';
6
+ import type { StdSignDoc, SendTransactionOptions, ConcreteWalletStrategy, ConcreteEvmWalletStrategyArgs } from '@injectivelabs/wallet-base';
7
+ export default class TrezorBase extends BaseConcreteStrategy implements ConcreteWalletStrategy {
8
+ private baseDerivationPath;
9
+ private trezor;
10
+ private evmOptions;
11
+ private alchemy;
12
+ private derivationPathType;
13
+ constructor(args: ConcreteEvmWalletStrategyArgs & {
14
+ derivationPathType: TrezorDerivationPathType;
15
+ });
16
+ getWalletDeviceType(): Promise<WalletDeviceType>;
17
+ enable(): Promise<boolean>;
18
+ disconnect(): Promise<void>;
19
+ getAddresses(): Promise<string[]>;
20
+ getSessionOrConfirm(address: AccountAddress): Promise<string>;
21
+ sendEvmTransaction(txData: any, args: {
22
+ address: string;
23
+ evmChainId: EvmChainIdType;
24
+ }): Promise<string>;
25
+ sendTransaction(transaction: TxRaw, options: SendTransactionOptions): Promise<TxResponse>;
26
+ signEip712TypedData(eip712json: string, address: AccountAddress): Promise<string>;
27
+ signAminoCosmosTransaction(_transaction: {
28
+ address: string;
29
+ signDoc: StdSignDoc;
30
+ }): Promise<AminoSignResponse>;
31
+ signCosmosTransaction(_transaction: {
32
+ txRaw: TxRaw;
33
+ accountNumber: number;
34
+ chainId: string;
35
+ address: string;
36
+ }): Promise<DirectSignResponse>;
37
+ signArbitrary(signer: AccountAddress, data: string | Uint8Array): Promise<string>;
38
+ getEthereumChainId(): Promise<string>;
39
+ getEvmTransactionReceipt(txHash: string, evmChainId?: EvmChainId): Promise<string>;
40
+ getPubKey(): Promise<string>;
41
+ private signEvmTransaction;
42
+ private getWalletForAddress;
43
+ private getAlchemy;
44
+ }
@@ -0,0 +1,307 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const utils_1 = require("@injectivelabs/utils");
4
+ const viem_1 = require("viem");
5
+ const ts_types_1 = require("@injectivelabs/ts-types");
6
+ const sdk_ts_1 = require("@injectivelabs/sdk-ts");
7
+ const alchemy_sdk_1 = require("alchemy-sdk");
8
+ const exceptions_1 = require("@injectivelabs/exceptions");
9
+ const wallet_base_1 = require("@injectivelabs/wallet-base");
10
+ const lib_js_1 = require("./lib.js");
11
+ const utils_js_1 = require("../utils.js");
12
+ const index_js_1 = require("./hw/index.js");
13
+ class TrezorBase extends wallet_base_1.BaseConcreteStrategy {
14
+ baseDerivationPath;
15
+ trezor;
16
+ evmOptions;
17
+ alchemy;
18
+ derivationPathType;
19
+ constructor(args) {
20
+ super(args);
21
+ this.evmOptions = args.evmOptions;
22
+ this.trezor = new index_js_1.BaseTrezorTransport();
23
+ this.derivationPathType = args.derivationPathType;
24
+ this.baseDerivationPath = wallet_base_1.DEFAULT_BASE_DERIVATION_PATH;
25
+ }
26
+ async getWalletDeviceType() {
27
+ return Promise.resolve(wallet_base_1.WalletDeviceType.Hardware);
28
+ }
29
+ async enable() {
30
+ return Promise.resolve(true);
31
+ }
32
+ async disconnect() {
33
+ return Promise.resolve();
34
+ }
35
+ async getAddresses() {
36
+ const { baseDerivationPath, derivationPathType } = this;
37
+ try {
38
+ await this.trezor.connect();
39
+ const accountManager = await this.trezor.getAccountManager();
40
+ const wallets = await accountManager.getWallets(baseDerivationPath, derivationPathType);
41
+ return wallets.map((k) => k.address);
42
+ }
43
+ catch (e) {
44
+ throw new exceptions_1.TrezorException(new Error(e.message), {
45
+ code: exceptions_1.UnspecifiedErrorCode,
46
+ type: exceptions_1.ErrorType.WalletError,
47
+ contextModule: wallet_base_1.WalletAction.GetAccounts,
48
+ });
49
+ }
50
+ }
51
+ async getSessionOrConfirm(address) {
52
+ return Promise.resolve(`0x${Buffer.from(`Confirmation for ${address} at time: ${Date.now()}`).toString('hex')}`);
53
+ }
54
+ async sendEvmTransaction(txData, args) {
55
+ const signedTransaction = await this.signEvmTransaction(txData, args);
56
+ try {
57
+ const alchemy = await this.getAlchemy(args.evmChainId);
58
+ const provider = await alchemy.config.getProvider();
59
+ const txHash = await provider.send('eth_sendRawTransaction', [
60
+ signedTransaction,
61
+ ]);
62
+ return txHash;
63
+ }
64
+ catch (e) {
65
+ throw new exceptions_1.TrezorException(new Error(e.message), {
66
+ code: exceptions_1.UnspecifiedErrorCode,
67
+ type: exceptions_1.ErrorType.WalletError,
68
+ contextModule: wallet_base_1.WalletAction.SendEvmTransaction,
69
+ });
70
+ }
71
+ }
72
+ async sendTransaction(transaction, options) {
73
+ const { endpoints, txTimeout } = options;
74
+ if (!endpoints) {
75
+ throw new exceptions_1.WalletException(new Error('You have to pass endpoints.grpc within the options for using Ethereum native wallets'));
76
+ }
77
+ const txApi = new sdk_ts_1.TxGrpcApi(endpoints.grpc);
78
+ const response = await txApi.broadcast(transaction, { txTimeout });
79
+ if (response.code !== 0) {
80
+ throw new exceptions_1.TransactionException(new Error(response.rawLog), {
81
+ code: exceptions_1.UnspecifiedErrorCode,
82
+ contextCode: response.code,
83
+ contextModule: response.codespace,
84
+ });
85
+ }
86
+ return response;
87
+ }
88
+ async signEip712TypedData(eip712json, address) {
89
+ const TrezorConnect = await (0, lib_js_1.loadTrezorConnect)();
90
+ console.log('🪵Address:', address);
91
+ const object = JSON.parse(eip712json);
92
+ const compatibleObject = {
93
+ ...object,
94
+ domain: {
95
+ ...object.domain,
96
+ chainId: object.domain.chainId,
97
+ salt: '0',
98
+ },
99
+ };
100
+ const dataWithHashes = (0, utils_js_1.transformTypedData)(compatibleObject);
101
+ const { types: { EIP712Domain = [], ...otherTypes } = {}, message = {}, domain = {}, primaryType, domain_separator_hash, message_hash, } = dataWithHashes;
102
+ try {
103
+ console.log('🪵Signing EIP-712 typed data with Trezor...');
104
+ await this.trezor.connect();
105
+ console.log('🪵Connected to Trezor...');
106
+ // const { derivationPath } = await this.getWalletForAddress(address)
107
+ // Hardcoded for testint purposes, otherwise use above
108
+ const derivationPath = "m/44'/60'/0'/0/0";
109
+ console.log('🪵Derivation path:', derivationPath);
110
+ console.log('Signing EIP-712 typed data with Trezor...');
111
+ const response = await TrezorConnect.ethereumSignTypedData({
112
+ path: derivationPath,
113
+ data: {
114
+ types: { EIP712Domain, ...otherTypes },
115
+ message,
116
+ domain,
117
+ primaryType,
118
+ },
119
+ message_hash,
120
+ domain_separator_hash,
121
+ metamask_v4_compat: true,
122
+ });
123
+ console.log('🪵response', response);
124
+ if (!response.success) {
125
+ // noinspection ExceptionCaughtLocallyJS
126
+ throw new Error((response.payload && response.payload.error) || 'Unknown error');
127
+ }
128
+ return response.payload.signature;
129
+ }
130
+ catch (e) {
131
+ throw new exceptions_1.TrezorException(new Error(e.message), {
132
+ code: exceptions_1.UnspecifiedErrorCode,
133
+ type: exceptions_1.ErrorType.WalletError,
134
+ contextModule: wallet_base_1.WalletAction.SignTransaction,
135
+ });
136
+ }
137
+ }
138
+ async signAminoCosmosTransaction(_transaction) {
139
+ throw new exceptions_1.WalletException(new Error('This wallet does not support signing Cosmos transactions'), {
140
+ code: exceptions_1.UnspecifiedErrorCode,
141
+ type: exceptions_1.ErrorType.WalletError,
142
+ contextModule: wallet_base_1.WalletAction.SendTransaction,
143
+ });
144
+ }
145
+ async signCosmosTransaction(_transaction) {
146
+ throw new exceptions_1.WalletException(new Error('This wallet does not support signing Cosmos transactions'), {
147
+ code: exceptions_1.UnspecifiedErrorCode,
148
+ type: exceptions_1.ErrorType.WalletError,
149
+ contextModule: wallet_base_1.WalletAction.SendTransaction,
150
+ });
151
+ }
152
+ async signArbitrary(signer, data) {
153
+ const TrezorConnect = await (0, lib_js_1.loadTrezorConnect)();
154
+ try {
155
+ await this.trezor.connect();
156
+ const { derivationPath } = await this.getWalletForAddress(signer);
157
+ const response = await TrezorConnect.ethereumSignMessage({
158
+ path: derivationPath,
159
+ message: (0, sdk_ts_1.toUtf8)(data),
160
+ });
161
+ if (!response.success) {
162
+ throw new Error((response.payload && response.payload.error) || 'Unknown error');
163
+ }
164
+ return response.payload.signature;
165
+ }
166
+ catch (e) {
167
+ throw new exceptions_1.TrezorException(new Error(e.message), {
168
+ code: exceptions_1.UnspecifiedErrorCode,
169
+ type: exceptions_1.ErrorType.WalletError,
170
+ contextModule: wallet_base_1.WalletAction.SignTransaction,
171
+ });
172
+ }
173
+ }
174
+ async getEthereumChainId() {
175
+ const alchemy = await this.getAlchemy();
176
+ const alchemyProvider = await alchemy.config.getProvider();
177
+ return alchemyProvider.network.chainId.toString();
178
+ }
179
+ async getEvmTransactionReceipt(txHash, evmChainId) {
180
+ const alchemy = await this.getAlchemy(evmChainId);
181
+ const provider = await alchemy.config.getProvider();
182
+ const interval = 3000;
183
+ const maxAttempts = 10;
184
+ let attempts = 0;
185
+ while (attempts < maxAttempts) {
186
+ attempts++;
187
+ await (0, utils_1.sleep)(interval);
188
+ try {
189
+ const receipt = await provider.send('eth_getTransactionReceipt', [
190
+ txHash,
191
+ ]);
192
+ if (receipt) {
193
+ return txHash;
194
+ }
195
+ }
196
+ catch { }
197
+ }
198
+ throw new Error(`Failed to retrieve transaction receipt for txHash: ${txHash}`);
199
+ }
200
+ async getPubKey() {
201
+ throw new exceptions_1.WalletException(new Error('You can only fetch PubKey from Cosmos native wallets'));
202
+ }
203
+ async signEvmTransaction(txData, args) {
204
+ const TrezorConnect = await (0, lib_js_1.loadTrezorConnect)();
205
+ const chainId = parseInt(args.evmChainId.toString(), 10);
206
+ const alchemy = await this.getAlchemy(args.evmChainId);
207
+ const nonce = await alchemy.core.getTransactionCount(args.address);
208
+ // Handle hex string values properly (with or without 0x prefix)
209
+ const parseHexValue = (value) => {
210
+ if (typeof value === 'string') {
211
+ const hexValue = value.startsWith('0x') ? value : `0x${value}`;
212
+ return BigInt(hexValue);
213
+ }
214
+ return BigInt(value);
215
+ };
216
+ // Convert to BigInt first, then to hex for Trezor
217
+ const valueBigInt = parseHexValue(txData.value || '0x0');
218
+ const gasBigInt = parseHexValue(txData.gas);
219
+ const maxFeePerGasBigInt = parseHexValue(txData.maxFeePerGas);
220
+ const maxPriorityFeePerGasBigInt = parseHexValue(txData.maxPriorityFeePerGas);
221
+ // Create transaction data for Trezor API (needs hex strings)
222
+ const trezorTxData = {
223
+ to: txData.to,
224
+ value: (0, viem_1.toHex)(valueBigInt),
225
+ gasLimit: (0, viem_1.toHex)(gasBigInt),
226
+ nonce: (0, viem_1.toHex)(nonce),
227
+ data: txData.data || '0x',
228
+ chainId,
229
+ maxFeePerGas: (0, viem_1.toHex)(maxFeePerGasBigInt),
230
+ maxPriorityFeePerGas: (0, viem_1.toHex)(maxPriorityFeePerGasBigInt),
231
+ };
232
+ try {
233
+ await this.trezor.connect();
234
+ const { derivationPath } = await this.getWalletForAddress(args.address);
235
+ const response = await TrezorConnect.ethereumSignTransaction({
236
+ path: derivationPath,
237
+ transaction: trezorTxData,
238
+ });
239
+ if (!response.success) {
240
+ throw new exceptions_1.TrezorException(new Error((response.payload && response.payload.error) ||
241
+ 'Something happened while signing with Trezor'), {
242
+ code: exceptions_1.UnspecifiedErrorCode,
243
+ type: exceptions_1.ErrorType.WalletError,
244
+ contextModule: wallet_base_1.WalletAction.SignEvmTransaction,
245
+ });
246
+ }
247
+ // Create viem-compatible transaction data for serialization
248
+ const viemTxData = {
249
+ type: 'eip1559',
250
+ chainId,
251
+ nonce,
252
+ to: txData.to,
253
+ value: valueBigInt,
254
+ data: (txData.data || '0x'),
255
+ gas: gasBigInt,
256
+ maxFeePerGas: maxFeePerGasBigInt,
257
+ maxPriorityFeePerGas: maxPriorityFeePerGasBigInt,
258
+ v: BigInt(response.payload.v),
259
+ r: response.payload.r,
260
+ s: response.payload.s,
261
+ };
262
+ return (0, viem_1.serializeTransaction)(viemTxData);
263
+ }
264
+ catch (e) {
265
+ if (e instanceof exceptions_1.TrezorException) {
266
+ throw e;
267
+ }
268
+ throw new exceptions_1.TrezorException(new Error(e.message), {
269
+ code: exceptions_1.UnspecifiedErrorCode,
270
+ type: exceptions_1.ErrorType.WalletError,
271
+ contextModule: wallet_base_1.WalletAction.SignEvmTransaction,
272
+ });
273
+ }
274
+ }
275
+ async getWalletForAddress(address) {
276
+ const { baseDerivationPath, derivationPathType } = this;
277
+ const accountManager = await this.trezor.getAccountManager();
278
+ if (!accountManager.hasWalletForAddress(address)) {
279
+ for (let i = 0; i < wallet_base_1.DEFAULT_ADDRESS_SEARCH_LIMIT / wallet_base_1.DEFAULT_NUM_ADDRESSES_TO_FETCH; i += 1) {
280
+ await accountManager.getWallets(baseDerivationPath, derivationPathType);
281
+ if (accountManager.hasWalletForAddress(address)) {
282
+ return (await accountManager.getWalletForAddress(address));
283
+ }
284
+ }
285
+ }
286
+ return (await accountManager.getWalletForAddress(address));
287
+ }
288
+ async getAlchemy(evmChainId) {
289
+ if (this.alchemy) {
290
+ return this.alchemy;
291
+ }
292
+ const options = this.evmOptions;
293
+ const chainId = evmChainId || options.evmChainId;
294
+ const url = options.rpcUrl || options.rpcUrls?.[chainId];
295
+ if (!url) {
296
+ throw new exceptions_1.GeneralException(new Error('Please pass rpcUrl within the ethereumOptions'));
297
+ }
298
+ this.alchemy = new alchemy_sdk_1.Alchemy({
299
+ apiKey: (0, wallet_base_1.getKeyFromRpcUrl)(url),
300
+ network: chainId === ts_types_1.EvmChainId.Mainnet
301
+ ? alchemy_sdk_1.Network.ETH_MAINNET
302
+ : alchemy_sdk_1.Network.ETH_SEPOLIA,
303
+ });
304
+ return this.alchemy;
305
+ }
306
+ }
307
+ exports.default = TrezorBase;
@@ -0,0 +1,5 @@
1
+ import TrezorBase from './Base.js';
2
+ import type { ConcreteEvmWalletStrategyArgs } from '@injectivelabs/wallet-base';
3
+ export declare class TrezorBip32 extends TrezorBase {
4
+ constructor(args: ConcreteEvmWalletStrategyArgs);
5
+ }
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.TrezorBip32 = void 0;
7
+ const Base_js_1 = __importDefault(require("./Base.js"));
8
+ const types_js_1 = require("../types.js");
9
+ class TrezorBip32 extends Base_js_1.default {
10
+ constructor(args) {
11
+ super({
12
+ ...args,
13
+ derivationPathType: types_js_1.TrezorDerivationPathType.Bip32,
14
+ });
15
+ }
16
+ }
17
+ exports.TrezorBip32 = TrezorBip32;
@@ -0,0 +1,5 @@
1
+ import TrezorBase from './Base.js';
2
+ import type { ConcreteEvmWalletStrategyArgs } from '@injectivelabs/wallet-base';
3
+ export declare class TrezorBip44 extends TrezorBase {
4
+ constructor(args: ConcreteEvmWalletStrategyArgs);
5
+ }
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.TrezorBip44 = void 0;
7
+ const Base_js_1 = __importDefault(require("./Base.js"));
8
+ const types_js_1 = require("../types.js");
9
+ class TrezorBip44 extends Base_js_1.default {
10
+ constructor(args) {
11
+ super({
12
+ ...args,
13
+ derivationPathType: types_js_1.TrezorDerivationPathType.Bip44,
14
+ });
15
+ }
16
+ }
17
+ exports.TrezorBip44 = TrezorBip44;
@@ -0,0 +1,20 @@
1
+ import { TrezorDerivationPathType } from '../../types.js';
2
+ import type { AccountAddress } from '@injectivelabs/ts-types';
3
+ import type { TrezorWalletInfo } from '../../types.js';
4
+ export default class AccountManager {
5
+ private wallets;
6
+ constructor();
7
+ getWallets(baseDerivationPath: string, derivationPathType: TrezorDerivationPathType): Promise<TrezorWalletInfo[]>;
8
+ getTrezorDerivationPathBasedOnType: ({ fullBaseDerivationPath, derivationPathType, index, }: {
9
+ fullBaseDerivationPath: string;
10
+ derivationPathType: TrezorDerivationPathType;
11
+ index: number;
12
+ }) => string;
13
+ private getWalletsBasedOnIndex;
14
+ private hasWallets;
15
+ private hasWalletsInOffset;
16
+ private getOffset;
17
+ hasWalletForAddress(address: AccountAddress): boolean;
18
+ getWalletForAddress(address: AccountAddress): Promise<TrezorWalletInfo | undefined>;
19
+ reset(): void;
20
+ }
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const exceptions_1 = require("@injectivelabs/exceptions");
4
+ const sdk_ts_1 = require("@injectivelabs/sdk-ts");
5
+ const wallet_base_1 = require("@injectivelabs/wallet-base");
6
+ const lib_js_1 = require("../lib.js");
7
+ const types_js_1 = require("../../types.js");
8
+ const addressOfHDKey = (hdKey) => {
9
+ const shouldSanitizePublicKey = true;
10
+ const derivedPublicKey = hdKey.publicKey;
11
+ const ethereumAddressWithoutPrefix = Buffer.from((0, sdk_ts_1.publicKeyToAddress)(derivedPublicKey, shouldSanitizePublicKey)).toString('hex');
12
+ const address = (0, sdk_ts_1.addHexPrefix)(ethereumAddressWithoutPrefix);
13
+ return address;
14
+ };
15
+ class AccountManager {
16
+ wallets = [];
17
+ constructor() {
18
+ this.wallets = [];
19
+ }
20
+ async getWallets(baseDerivationPath, derivationPathType) {
21
+ const { start, end } = this.getOffset();
22
+ /**
23
+ * 1. Wallets are not yet fetched at all,
24
+ * 2. Wallets are not yet fetched for that offset
25
+ */
26
+ if (!this.hasWallets() || !this.hasWalletsInOffset(start)) {
27
+ await this.getWalletsBasedOnIndex({
28
+ start,
29
+ end,
30
+ baseDerivationPath,
31
+ derivationPathType,
32
+ });
33
+ }
34
+ return this.wallets.slice(start, end);
35
+ }
36
+ getTrezorDerivationPathBasedOnType = ({ fullBaseDerivationPath, derivationPathType, index, }) => {
37
+ if (derivationPathType === types_js_1.TrezorDerivationPathType.Bip44) {
38
+ return `${fullBaseDerivationPath}/${index}'/0/0`;
39
+ }
40
+ if (derivationPathType === types_js_1.TrezorDerivationPathType.Legacy) {
41
+ return `m/${index}`;
42
+ }
43
+ return `${fullBaseDerivationPath}/0'/0/${index}`;
44
+ };
45
+ async getWalletsBasedOnIndex({ start, end, baseDerivationPath, derivationPathType, }) {
46
+ const TrezorConnect = await (0, lib_js_1.loadTrezorConnect)();
47
+ const pathsToFetch = [];
48
+ for (let index = start; index < end; index += 1) {
49
+ const path = this.getTrezorDerivationPathBasedOnType({
50
+ fullBaseDerivationPath: baseDerivationPath,
51
+ derivationPathType,
52
+ index,
53
+ });
54
+ pathsToFetch.push({
55
+ path,
56
+ showOnTrezor: false,
57
+ });
58
+ }
59
+ const result = await TrezorConnect.ethereumGetPublicKey({
60
+ bundle: pathsToFetch,
61
+ });
62
+ if (!result.success) {
63
+ throw new exceptions_1.TrezorException(new Error((result.payload && result.payload.error) ||
64
+ 'Please make sure your Trezor is connected and unlocked'));
65
+ }
66
+ for (const item of result.payload) {
67
+ const hdKey = {
68
+ publicKey: Buffer.from(item.publicKey, 'hex'),
69
+ chainCode: Buffer.from(item.chainCode, 'hex'),
70
+ };
71
+ const address = addressOfHDKey(hdKey);
72
+ this.wallets.push({
73
+ hdKey,
74
+ derivationPath: item.serializedPath,
75
+ address: address.toLowerCase(),
76
+ });
77
+ }
78
+ }
79
+ hasWallets() {
80
+ return this.wallets.length > 0;
81
+ }
82
+ hasWalletsInOffset(offset) {
83
+ return this.wallets.length > offset;
84
+ }
85
+ getOffset() {
86
+ const totalWallets = this.wallets.length;
87
+ const nextBatchStart = totalWallets;
88
+ const nextBatchEnd = totalWallets + wallet_base_1.DEFAULT_NUM_ADDRESSES_TO_FETCH;
89
+ return {
90
+ start: nextBatchStart,
91
+ end: nextBatchEnd,
92
+ };
93
+ }
94
+ hasWalletForAddress(address) {
95
+ return (this.wallets.find((wallet) => wallet.address.toLowerCase() === address.toLowerCase()) !== undefined);
96
+ }
97
+ async getWalletForAddress(address) {
98
+ return this.wallets.find((wallet) => wallet.address.toLowerCase() === address.toLowerCase());
99
+ }
100
+ reset() {
101
+ this.wallets = [];
102
+ }
103
+ }
104
+ exports.default = AccountManager;
@@ -0,0 +1,3 @@
1
+ import BaseTrezorTransport from './transport/base.js';
2
+ import TrezorTransportNoInit from './transport/transport-no-init.js';
3
+ export { TrezorTransportNoInit, BaseTrezorTransport };
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.BaseTrezorTransport = exports.TrezorTransportNoInit = void 0;
7
+ const base_js_1 = __importDefault(require("./transport/base.js"));
8
+ exports.BaseTrezorTransport = base_js_1.default;
9
+ const transport_no_init_js_1 = __importDefault(require("./transport/transport-no-init.js"));
10
+ exports.TrezorTransportNoInit = transport_no_init_js_1.default;
@@ -0,0 +1,6 @@
1
+ import AccountManager from '../AccountManager.js';
2
+ export default class BaseTrezorTransport {
3
+ private accountManager;
4
+ connect(): Promise<void>;
5
+ getAccountManager(): Promise<AccountManager>;
6
+ }
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const AccountManager_js_1 = __importDefault(require("../AccountManager.js"));
7
+ const lib_js_1 = require("../../lib.js");
8
+ const TREZOR_CONNECT_MANIFEST = {
9
+ email: 'contact@injectivelabs.org',
10
+ appUrl: 'https://injectivelabs.org',
11
+ appName: 'Injective Labs',
12
+ };
13
+ class BaseTrezorTransport {
14
+ accountManager = null;
15
+ async connect() {
16
+ const TrezorConnect = await (0, lib_js_1.loadTrezorConnect)();
17
+ const settings = await TrezorConnect.getSettings();
18
+ if (!settings.success) {
19
+ console.log('🪵Initializing TrezorConnect...');
20
+ await TrezorConnect.init({
21
+ lazyLoad: true,
22
+ manifest: TREZOR_CONNECT_MANIFEST,
23
+ debug: true,
24
+ // 'auto', 'popup', 'iframe'
25
+ coreMode: 'popup',
26
+ });
27
+ }
28
+ return Promise.resolve();
29
+ }
30
+ async getAccountManager() {
31
+ if (!this.accountManager) {
32
+ this.accountManager = new AccountManager_js_1.default();
33
+ }
34
+ return this.accountManager;
35
+ }
36
+ }
37
+ exports.default = BaseTrezorTransport;
@@ -0,0 +1,4 @@
1
+ import BaseTrezorTransport from './base.js';
2
+ export default class TrezorTransportNoInit extends BaseTrezorTransport {
3
+ constructor();
4
+ }
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const base_js_1 = __importDefault(require("./base.js"));
7
+ class TrezorTransportNoInit extends base_js_1.default {
8
+ constructor() {
9
+ super();
10
+ }
11
+ }
12
+ exports.default = TrezorTransportNoInit;