@bitpay-labs/bitcore-client 11.5.2

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 (87) hide show
  1. package/README.md +131 -0
  2. package/bin/multi-sig/wallet-derive-address +149 -0
  3. package/bin/wallet +31 -0
  4. package/bin/wallet-balance +62 -0
  5. package/bin/wallet-balance-all +77 -0
  6. package/bin/wallet-broadcast +35 -0
  7. package/bin/wallet-bump-tx +65 -0
  8. package/bin/wallet-check +62 -0
  9. package/bin/wallet-create +46 -0
  10. package/bin/wallet-decrypt +31 -0
  11. package/bin/wallet-delete +21 -0
  12. package/bin/wallet-derive +70 -0
  13. package/bin/wallet-flags +84 -0
  14. package/bin/wallet-import +80 -0
  15. package/bin/wallet-list +31 -0
  16. package/bin/wallet-paypro +175 -0
  17. package/bin/wallet-register +29 -0
  18. package/bin/wallet-send +146 -0
  19. package/bin/wallet-sign +64 -0
  20. package/bin/wallet-sign-message +55 -0
  21. package/bin/wallet-storage +79 -0
  22. package/bin/wallet-token +73 -0
  23. package/bin/wallet-token-rm +33 -0
  24. package/bin/wallet-tx +106 -0
  25. package/bin/wallet-tx-list +92 -0
  26. package/bin/wallet-utxos +28 -0
  27. package/package.json +71 -0
  28. package/src/client.ts +271 -0
  29. package/src/encryption.ts +139 -0
  30. package/src/index.ts +21 -0
  31. package/src/storage/level.ts +171 -0
  32. package/src/storage/mongo.ts +187 -0
  33. package/src/storage/textFile.ts +250 -0
  34. package/src/storage.ts +192 -0
  35. package/src/stream-util.ts +80 -0
  36. package/src/types/index.d.ts +2 -0
  37. package/src/types/storage.d.ts +1 -0
  38. package/src/types/wallet.d.ts +36 -0
  39. package/src/utils.ts +35 -0
  40. package/src/wallet.ts +983 -0
  41. package/test/unit/wallet.test.ts +552 -0
  42. package/ts_build/src/client.d.ts +77 -0
  43. package/ts_build/src/client.d.ts.map +1 -0
  44. package/ts_build/src/client.js +280 -0
  45. package/ts_build/src/client.js.map +1 -0
  46. package/ts_build/src/encryption.d.ts +27 -0
  47. package/ts_build/src/encryption.d.ts.map +1 -0
  48. package/ts_build/src/encryption.js +130 -0
  49. package/ts_build/src/encryption.js.map +1 -0
  50. package/ts_build/src/index.d.ts +11 -0
  51. package/ts_build/src/index.d.ts.map +1 -0
  52. package/ts_build/src/index.js +55 -0
  53. package/ts_build/src/index.js.map +1 -0
  54. package/ts_build/src/storage/level.d.ts +48 -0
  55. package/ts_build/src/storage/level.d.ts.map +1 -0
  56. package/ts_build/src/storage/level.js +194 -0
  57. package/ts_build/src/storage/level.js.map +1 -0
  58. package/ts_build/src/storage/mongo.d.ts +62 -0
  59. package/ts_build/src/storage/mongo.d.ts.map +1 -0
  60. package/ts_build/src/storage/mongo.js +173 -0
  61. package/ts_build/src/storage/mongo.js.map +1 -0
  62. package/ts_build/src/storage/textFile.d.ts +53 -0
  63. package/ts_build/src/storage/textFile.d.ts.map +1 -0
  64. package/ts_build/src/storage/textFile.js +268 -0
  65. package/ts_build/src/storage/textFile.js.map +1 -0
  66. package/ts_build/src/storage.d.ts +63 -0
  67. package/ts_build/src/storage.d.ts.map +1 -0
  68. package/ts_build/src/storage.js +172 -0
  69. package/ts_build/src/storage.js.map +1 -0
  70. package/ts_build/src/stream-util.d.ts +15 -0
  71. package/ts_build/src/stream-util.d.ts.map +1 -0
  72. package/ts_build/src/stream-util.js +81 -0
  73. package/ts_build/src/stream-util.js.map +1 -0
  74. package/ts_build/src/utils.d.ts +8 -0
  75. package/ts_build/src/utils.d.ts.map +1 -0
  76. package/ts_build/src/utils.js +37 -0
  77. package/ts_build/src/utils.js.map +1 -0
  78. package/ts_build/src/wallet.d.ts +229 -0
  79. package/ts_build/src/wallet.d.ts.map +1 -0
  80. package/ts_build/src/wallet.js +806 -0
  81. package/ts_build/src/wallet.js.map +1 -0
  82. package/ts_build/test/unit/wallet.test.d.ts +2 -0
  83. package/ts_build/test/unit/wallet.test.d.ts.map +1 -0
  84. package/ts_build/test/unit/wallet.test.js +533 -0
  85. package/ts_build/test/unit/wallet.test.js.map +1 -0
  86. package/tsconfig.json +40 -0
  87. package/tsconfig.prod.json +6 -0
package/src/wallet.ts ADDED
@@ -0,0 +1,983 @@
1
+ import 'source-map-support/register';
2
+ import Mnemonic from '@bitpay-labs/bitcore-mnemonic';
3
+ import {
4
+ BitcoreLib,
5
+ BitcoreLibCash,
6
+ BitcoreLibDoge,
7
+ BitcoreLibLtc,
8
+ Constants,
9
+ Deriver,
10
+ SolKit,
11
+ SolanaProgram,
12
+ Transactions,
13
+ Web3,
14
+ ethers,
15
+ xrpl
16
+ } from '@bitpay-labs/crypto-wallet-core';
17
+ import * as Bcrypt from 'bcrypt';
18
+ import { Client } from './client';
19
+ import { Encryption } from './encryption';
20
+ import { Storage } from './storage';
21
+ import { ParseApiStream } from './stream-util';
22
+ import { StorageType } from './types/storage';
23
+ import { BumpTxFeeType, IWallet, KeyImport } from './types/wallet';
24
+
25
+ const { PrivateKey, HDPrivateKey } = BitcoreLib;
26
+ const chainLibs = {
27
+ BTC: BitcoreLib,
28
+ BCH: BitcoreLibCash,
29
+ DOGE: BitcoreLibDoge,
30
+ LTC: BitcoreLibLtc,
31
+ ETH: { Web3, ethers },
32
+ MATIC: { Web3, ethers },
33
+ ARB: { Web3, ethers },
34
+ BASE: { Web3, ethers },
35
+ OP: { Web3, ethers },
36
+ XRP: xrpl,
37
+ SOL: { SolKit, SolanaProgram }
38
+ };
39
+
40
+ export interface IWalletExt extends IWallet {
41
+ storage?: Storage;
42
+ }
43
+
44
+ export class Wallet {
45
+ masterKey?: any;
46
+ baseUrl: string;
47
+ chain: string;
48
+ network: string;
49
+ client: Client;
50
+ storage: Storage;
51
+ storageType: string;
52
+ unlocked?: { encryptionKey: string; masterKey: string };
53
+ password: string;
54
+ encryptionKey: string;
55
+ authPubKey: string;
56
+ pubKey?: string;
57
+ xPubKey: string;
58
+ name: string;
59
+ path: string;
60
+ addressIndex?: number;
61
+ authKey: string;
62
+ derivationPath: string;
63
+ tokens?: Array<any>;
64
+ lite: boolean;
65
+ addressType: string;
66
+ addressZero: string;
67
+
68
+ static XrpAccountFlags = xrpl.AccountSetTfFlags;
69
+
70
+ constructor(params: Wallet | IWalletExt) {
71
+ Object.assign(this, params);
72
+ if (!this.baseUrl) {
73
+ this.baseUrl = 'https://api.bitcore.io/api';
74
+ }
75
+ this.client = new Client({
76
+ apiUrl: this.getApiUrl(),
77
+ authKey: this.getAuthSigningKey()
78
+ });
79
+ this.addressIndex = this.addressIndex || 0;
80
+ this.addressType = AddressTypes[this.chain]?.[this.addressType] || 'pubkeyhash';
81
+ if (params.lite) {
82
+ delete this.masterKey;
83
+ delete this.pubKey;
84
+ this.lite = true;
85
+ }
86
+ }
87
+
88
+ getApiUrl() {
89
+ return `${this.baseUrl}/${this.chain}/${this.network}`;
90
+ }
91
+
92
+ getLib() {
93
+ return chainLibs[this.chain.toUpperCase()];
94
+ }
95
+
96
+ saveWallet() {
97
+ const walletInstance = Object.assign({}, this);
98
+ delete walletInstance.unlocked;
99
+ if (walletInstance.masterKey) {
100
+ walletInstance.lite = false;
101
+ }
102
+ return this.storage.saveWallet({ wallet: walletInstance });
103
+ }
104
+
105
+ toObject(lite: boolean = this.lite) {
106
+ return {
107
+ name: this.name,
108
+ chain: this.chain,
109
+ network: this.network,
110
+ path: this.path,
111
+ baseUrl: this.baseUrl,
112
+ encryptionKey: this.encryptionKey,
113
+ authKey: this.authKey,
114
+ authPubKey: this.authPubKey,
115
+ masterKey: lite ? undefined : this.masterKey,
116
+ password: Bcrypt.hashSync(this.password, 10),
117
+ xPubKey: this.xPubKey,
118
+ pubKey: lite ? undefined : this.pubKey,
119
+ tokens: this.tokens,
120
+ storageType: this.storageType,
121
+ lite,
122
+ addressType: this.addressType,
123
+ addressZero: this.addressZero
124
+ };
125
+ }
126
+
127
+ static async deleteWallet(params: { name: string; path?: string; storage?: Storage; storageType?: StorageType }) {
128
+ const { name, path, storageType } = params;
129
+ let { storage } = params;
130
+ storage = storage || new Storage({ errorIfExists: false, createIfMissing: false, path, storageType });
131
+ await storage.deleteWallet({ name });
132
+ }
133
+
134
+ static async create(params: Partial<IWalletExt>) {
135
+ const { network, name, phrase, xpriv, password, path, lite, baseUrl } = params;
136
+ let { chain, storageType, storage, addressType } = params;
137
+ if (phrase && xpriv) {
138
+ throw new Error('You can only provide either a phrase or a xpriv, not both');
139
+ }
140
+ if (!chain || !network || !name) {
141
+ throw new Error('Missing required parameter');
142
+ }
143
+ chain = chain.toUpperCase();
144
+ if (addressType && AddressTypes[chain] && !AddressTypes[chain]?.[addressType]) {
145
+ throw new Error(`Invalid --addressType for chain. Valid address types are: ${Object.keys(AddressTypes[chain]).join(' | ')}`);
146
+ }
147
+ addressType = AddressTypes[chain]?.[addressType] || 'pubkeyhash';
148
+
149
+ // Generate wallet private keys
150
+ let hdPrivKey;
151
+ let mnemonic;
152
+ if (xpriv) {
153
+ hdPrivKey = new HDPrivateKey(xpriv, network);
154
+ } else {
155
+ mnemonic = new Mnemonic(phrase);
156
+ const algo = Constants.ALGOS_BY_CHAIN[chain] || Constants.ALGOS_BY_CHAIN['default'];
157
+ const keyType = Constants.ALGO_TO_KEY_TYPE[algo];
158
+ hdPrivKey = mnemonic.toHDPrivateKey('', network).derive(Deriver.pathFor(chain, network), keyType);
159
+ }
160
+ const privKeyObj = hdPrivKey.toObject();
161
+
162
+ // Generate authentication keys
163
+ const authKey = new PrivateKey();
164
+ const authPubKey = authKey.toPublicKey().toString();
165
+
166
+ // Generate public keys
167
+ // bip44 compatible pubKey
168
+ const pubKey = hdPrivKey.publicKey.toString();
169
+
170
+ // Generate and encrypt the encryption key and private key
171
+ const walletEncryptionKey = Encryption.generateEncryptionKey();
172
+ const encryptionKey = Encryption.encryptEncryptionKey(walletEncryptionKey, password);
173
+ const encPrivateKey = Encryption.encryptPrivateKey(JSON.stringify(privKeyObj), pubKey, walletEncryptionKey);
174
+
175
+ storageType = storageType ? storageType : 'Level';
176
+ storage =
177
+ storage ||
178
+ new Storage({
179
+ path,
180
+ errorIfExists: false,
181
+ createIfMissing: true,
182
+ storageType
183
+ });
184
+
185
+ let alreadyExists;
186
+ try {
187
+ alreadyExists = await this.loadWallet({ storage, name, storageType });
188
+ } catch { /* ignore */ }
189
+ if (alreadyExists) {
190
+ throw new Error('Wallet already exists');
191
+ }
192
+ const wallet = new Wallet({
193
+ name,
194
+ chain,
195
+ network,
196
+ path,
197
+ baseUrl,
198
+ encryptionKey,
199
+ authKey,
200
+ authPubKey,
201
+ masterKey: encPrivateKey,
202
+ password,
203
+ xPubKey: hdPrivKey.xpubkey,
204
+ pubKey,
205
+ tokens: [],
206
+ storage,
207
+ storageType,
208
+ lite,
209
+ addressType,
210
+ addressZero: null
211
+ } as IWalletExt);
212
+
213
+ // save wallet to storage and then bitcore-node
214
+ await storage.saveWallet({ wallet: wallet.toObject(lite) });
215
+ const loadedWallet = await this.loadWallet({
216
+ storage,
217
+ name,
218
+ storageType
219
+ });
220
+
221
+ if (!xpriv) {
222
+ console.log(mnemonic.toString());
223
+ } else {
224
+ console.log(hdPrivKey.toString());
225
+ }
226
+
227
+ await loadedWallet.register().catch(e => {
228
+ console.debug(e);
229
+ console.error('Failed to register wallet with bitcore-node.');
230
+ });
231
+
232
+ return loadedWallet;
233
+ }
234
+
235
+ static async exists(params: { name: string; path?: string; storage?: Storage }) {
236
+ const { storage, name } = params;
237
+ let alreadyExists;
238
+ try {
239
+ alreadyExists = await Wallet.loadWallet({
240
+ storage,
241
+ name
242
+ });
243
+ } catch (err) {
244
+ console.log(err);
245
+ }
246
+ return alreadyExists != undefined && alreadyExists.length && alreadyExists.length != 0;
247
+ }
248
+
249
+ static async loadWallet(params: { name: string; path?: string; storage?: Storage; storageType?: StorageType }) {
250
+ const { name, path, storageType } = params;
251
+ let { storage } = params;
252
+ storage = storage || new Storage({ errorIfExists: false, createIfMissing: false, path, storageType });
253
+ const loadedWallet = await storage.loadWallet({ name });
254
+ if (loadedWallet) {
255
+ return new Wallet(Object.assign(loadedWallet, { storage }));
256
+ } else {
257
+ throw new Error('No wallet could be found');
258
+ }
259
+ }
260
+
261
+ /**
262
+ * Does this wallet use UTXOs?
263
+ * @returns {Boolean}
264
+ */
265
+ isUtxoChain() {
266
+ // the toUpperCase() should not be necessary, but it's here just in case.
267
+ return ['BTC', 'BCH', 'DOGE', 'LTC'].includes(this.chain?.toUpperCase() || 'BTC');
268
+ }
269
+
270
+ /**
271
+ * Is this wallet EVM compatible?
272
+ * @returns {Boolean}
273
+ */
274
+ isEvmChain() {
275
+ return ['ETH', 'MATIC', 'ARB', 'OP', 'BASE'].includes(this.chain?.toUpperCase());
276
+ }
277
+
278
+ isSolanaChain() {
279
+ return ['SOL'].includes(this.chain?.toUpperCase());
280
+ }
281
+
282
+ lock() {
283
+ this.unlocked = undefined;
284
+ return this;
285
+ }
286
+
287
+ async unlock(password) {
288
+ const validPass = await Bcrypt.compare(password, this.password).catch(() => false);
289
+ if (!validPass) {
290
+ throw new Error('Incorrect Password');
291
+ }
292
+ const encryptionKey = await Encryption.decryptEncryptionKey(this.encryptionKey, password);
293
+ let masterKey;
294
+ if (!this.lite) {
295
+ const encMasterKey = this.masterKey;
296
+ const masterKeyStr = await Encryption.decryptPrivateKey(encMasterKey, this.pubKey, encryptionKey);
297
+ masterKey = JSON.parse(masterKeyStr);
298
+ }
299
+ this.unlocked = {
300
+ encryptionKey,
301
+ masterKey
302
+ };
303
+ return this;
304
+ }
305
+
306
+ async register(params: { baseUrl?: string } = {}) {
307
+ const { baseUrl } = params;
308
+ if (baseUrl) {
309
+ // save the new url without chain and network
310
+ // then use the new url with chain and network below
311
+ this.baseUrl = baseUrl;
312
+ await this.saveWallet();
313
+ }
314
+ const payload = {
315
+ name: this.name,
316
+ pubKey: this.authPubKey,
317
+ path: this.derivationPath,
318
+ network: this.network,
319
+ chain: this.chain,
320
+ apiUrl: this.getApiUrl()
321
+ };
322
+ return this.client.register({ payload });
323
+ }
324
+
325
+ getAuthSigningKey() {
326
+ return new PrivateKey(this.authKey);
327
+ }
328
+
329
+ /**
330
+ * Get balance for the wallet
331
+ * @param params
332
+ * @param params.time Get balance at point in time
333
+ * @param params.token DEPRECATED: Token to get by ticker symbol. WARNING: there could be multiple tokens with the same symbol
334
+ * @param params.tokenName Token to get by tokenName (Recommended over `token`)
335
+ * @param params.address EVM Account address to get the balance for
336
+ * @param params.hex Return the balance in hex
337
+ * @returns
338
+ */
339
+ getBalance(params: { time?: string; token?: string; tokenName?: string; address?: string; hex?: boolean } = {}) {
340
+ const { time, token, tokenName, address, hex } = params;
341
+ let payload;
342
+ if (token || tokenName) {
343
+ const tokenObj = this.getTokenObj({ token, tokenName });
344
+ payload = {
345
+ tokenContractAddress: tokenObj.address
346
+ };
347
+ }
348
+ return this.client.getBalance({ payload, pubKey: this.authPubKey, time, address, hex });
349
+ }
350
+
351
+ getNetworkFee(params: { target?: number; txType?: number } = {}) {
352
+ const target = params.target || 2;
353
+ const txType = params.txType;
354
+ return this.client.getFee({ target, txType });
355
+ }
356
+
357
+ getNetworkPriorityFee(params: { percentile?: number } = {}) {
358
+ const percentile = params.percentile;
359
+ return this.client.getPriorityFee({ percentile });
360
+ }
361
+
362
+ getUtxos(params: { includeSpent?: boolean } = {}) {
363
+ const { includeSpent = false } = params;
364
+ return this.client.getCoins({
365
+ pubKey: this.authPubKey,
366
+ includeSpent
367
+ });
368
+ }
369
+
370
+ getUtxosArray(params: { includeSpent?: boolean } = {}) {
371
+ return new Promise((resolve, reject) => {
372
+ const utxoArray = [];
373
+ const { includeSpent = false } = params;
374
+ const utxoRequest = this.client.getCoins({
375
+ pubKey: this.authPubKey,
376
+ includeSpent
377
+ });
378
+ utxoRequest
379
+ .pipe(new ParseApiStream())
380
+ .on('data', utxo => utxoArray.push(utxo))
381
+ .on('end', () => resolve(utxoArray))
382
+ .on('err', err => reject(err));
383
+ });
384
+ }
385
+
386
+ /**
387
+ * Backwards compatible method for getting the token object
388
+ *
389
+ * `token` and `tokenName` are separate parameters because there are legacy token objects
390
+ * without a `name` but modern implementations try to use the tokenName.
391
+ * e.g.:
392
+ * tokens = [
393
+ * { token: 'USDC', address: '0x123...', decimals: '6' } // USDC.e
394
+ * { token: 'USDC', address: '0xabc...', decimals: '6', name: 'USDCn_m' } // native USDC
395
+ * ]
396
+ * params1 = { token: 'USDC', tokenName: 'USDC_m' } => returns tokens[0]
397
+ * params2 = { token: 'USDC', tokenName: 'USDCn_m' } => returns tokens[1]
398
+ *
399
+ *
400
+ * @param tokenName The `name` field on the token object
401
+ * @param token The `symbol` field on the token object (deprecated)
402
+ */
403
+ getTokenObj(params: { tokenName?: string; token?: string }) {
404
+ const { tokenName, token } = params || {};
405
+ if (!tokenName && !token) {
406
+ return null;
407
+ }
408
+ // If tokenName was given, find the token by name (e.g. USDC_m)
409
+ let tokenObj = tokenName && this.tokens.find(tok => tok.name === tokenName);
410
+ // If not found by name AND token was given, find the token by symbol (e.g. USDC)
411
+ // NOTE: we don't want to
412
+ tokenObj = tokenObj || (token && this.tokens.find(tok => tok.symbol === token && [token, undefined].includes(tok.name)));
413
+ if (!tokenObj) {
414
+ throw new Error(`${tokenName || token} not found on wallet ${this.name}`);
415
+ }
416
+ return tokenObj;
417
+ }
418
+
419
+ listTransactions(params) {
420
+ const { token, tokenName } = params;
421
+ if (token || tokenName) {
422
+ const tokenObj = this.getTokenObj({ token, tokenName });
423
+ params.tokenContractAddress = tokenObj.address;
424
+ }
425
+ return this.client.listTransactions({
426
+ ...params,
427
+ pubKey: this.authPubKey
428
+ });
429
+ }
430
+
431
+ async getToken(contractAddress) {
432
+ if (this.isSolanaChain()) {
433
+ const addresses = await this.client.getSolanaTokens(this.addressZero);
434
+ return addresses.find(addr => addr.mintAddress === contractAddress);
435
+ }
436
+ return this.client.getToken(contractAddress);
437
+ }
438
+
439
+ async addToken(params) {
440
+ if (!this.tokens) {
441
+ this.tokens = [];
442
+ }
443
+ this.tokens.push({
444
+ symbol: params.symbol,
445
+ address: params.address,
446
+ decimals: params.decimals,
447
+ name: params.name,
448
+ ataAddress: params.ataAddress
449
+ });
450
+ await this.saveWallet();
451
+ }
452
+
453
+ async rmToken({ tokenName }) {
454
+ if (!this.tokens) {
455
+ return;
456
+ }
457
+ this.tokens = this.tokens.filter(tok =>
458
+ (tok.name && tok.name !== tokenName) ||
459
+ /* legacy object */ (!tok.name && tok.symbol !== tokenName)
460
+ );
461
+ await this.saveWallet();
462
+ }
463
+
464
+ async newTx(params: {
465
+ utxos?: any[];
466
+ recipients: { address: string; amount: number }[];
467
+ from?: string;
468
+ change?: string; // 'miner' to have any change go to the miner (i.e. no change).
469
+ invoiceID?: string;
470
+ memo?: string;
471
+ fee?: number;
472
+ feeRate?: number;
473
+ nonce?: number;
474
+ tag?: number;
475
+ data?: string;
476
+ token?: string; // deprecated. tokenName is better, but old token objects don't have the `name` field.
477
+ tokenName?: string;
478
+ gasLimit?: number;
479
+ gasPrice?: number;
480
+ contractAddress?: string;
481
+ chainId?: number;
482
+ replaceByFee?: boolean;
483
+ lockUntilBlock?: number;
484
+ lockUntilDate?: Date;
485
+ isSweep?: boolean;
486
+ type?: string;
487
+ flags?: number;
488
+ blockHash?: string;
489
+ blockHeight?: number;
490
+ }) {
491
+ let chain = this.chain;
492
+ let tokenContractAddress;
493
+ let decimals;
494
+ let fromAta;
495
+ if (params.token || params.tokenName) {
496
+ chain = this.isSolanaChain() ? this.chain + 'SPL' : this.chain + 'ERC20';
497
+ const tokenObj = this.getTokenObj(params);
498
+ tokenContractAddress = tokenObj.address;
499
+ decimals = tokenObj.decimals;
500
+ fromAta = tokenObj.ataAddress;
501
+ }
502
+ let change = params.change;
503
+ if (change === 'miner') {
504
+ change = undefined; // no change
505
+ } else if (!change) {
506
+ change = await this._getChangeAddress();
507
+ }
508
+ let blockHash = params.blockHash;
509
+ let blockHeight = params.blockHeight;
510
+ if (this.isSolanaChain() && (!blockHash || !blockHeight)) {
511
+ const tip = await this.client.getBlockTip();
512
+ blockHash = tip.hash;
513
+ blockHeight = tip.height;
514
+ }
515
+ const payload = {
516
+ network: this.network,
517
+ chain,
518
+ recipients: params.recipients,
519
+ from: params.from,
520
+ change,
521
+ invoiceID: params.invoiceID,
522
+ memo: params.memo,
523
+ fee: params.fee,
524
+ feeRate: params.feeRate,
525
+ utxos: params.utxos,
526
+ nonce: params.nonce,
527
+ tag: params.tag,
528
+ gasPrice: params.gasPrice || params.feeRate || params.fee,
529
+ gasLimit: params.gasLimit || 200000,
530
+ data: params.data,
531
+ tokenAddress: tokenContractAddress,
532
+ contractAddress: params.contractAddress,
533
+ chainId: params.chainId,
534
+ replaceByFee: params.replaceByFee,
535
+ lockUntilBlock: params.lockUntilBlock,
536
+ lockUntilDate: params.lockUntilDate,
537
+ isSweep: params.isSweep,
538
+ type: params.type,
539
+ flags: params.flags,
540
+ blockHash,
541
+ blockHeight,
542
+ decimals,
543
+ fromAta
544
+ };
545
+ return Transactions.create(payload);
546
+ }
547
+
548
+ async createAtaAccount(mintAddress) {
549
+ if (!this.isSolanaChain()) {
550
+ throw new Error('createAtaAccount is only supported for Solana wallets');
551
+ }
552
+ const owner = SolKit.address(this.addressZero);
553
+ if (!mintAddress) {
554
+ throw new Error('mintAddress is required to create an associated token account');
555
+ }
556
+ const [newAccount] = await SolanaProgram.Token.findAssociatedTokenPda({
557
+ owner,
558
+ tokenProgram: SolanaProgram.Token.TOKEN_PROGRAM_ADDRESS,
559
+ mint: SolKit.address(mintAddress),
560
+ });
561
+ const tip = await this.client.getBlockTip();
562
+ const blockHash = tip.hash;
563
+ const blockHeight = tip.height;
564
+ const privateKey = await this.derivePrivateKey(null, 0);
565
+ const privKeyBytes = SolKit.getBase58Encoder().encode(privateKey.privKey);
566
+ const keyPair = await SolKit.createKeyPairSignerFromPrivateKeyBytes(privKeyBytes);
567
+ const tx = Transactions.create({
568
+ network: this.network,
569
+ chain: this.chain,
570
+ category: 'createata',
571
+ fromKeyPair: keyPair,
572
+ from: this.addressZero,
573
+ ataAddress: newAccount,
574
+ blockHash,
575
+ blockHeight,
576
+ mint: mintAddress,
577
+ });
578
+ const sig = await this.signTx({ tx });
579
+ await this.broadcast({ tx: sig });
580
+ return sig;
581
+ }
582
+
583
+ async broadcast(params: { tx: string }) {
584
+ const { tx } = params;
585
+ const payload = {
586
+ network: this.network,
587
+ chain: this.chain,
588
+ rawTx: tx
589
+ };
590
+ return this.client.broadcast({ payload });
591
+ }
592
+
593
+ async getTransactionByTxid(params: { txid: string; populated?: boolean }) {
594
+ const { txid, populated } = params;
595
+ return this.client.getTransaction({ txid, populated });
596
+ }
597
+
598
+ async importKeys(params: { keys: KeyImport[]; rederiveAddys?: boolean }) {
599
+ const { encryptionKey } = this.unlocked;
600
+ const { rederiveAddys } = params;
601
+ let { keys } = params;
602
+ let keysToSave = keys.filter(key => typeof key.privKey === 'string');
603
+
604
+ if (rederiveAddys) {
605
+ keysToSave = keysToSave.map(key => ({
606
+ ...key,
607
+ address: key.pubKey ? Deriver.getAddress(this.chain, this.network, key.pubKey, this.addressType) : key.address
608
+ }) as KeyImport);
609
+ keys = keys.map(key => ({
610
+ ...key,
611
+ address: key.pubKey ? Deriver.getAddress(this.chain, this.network, key.pubKey, this.addressType) : key.address
612
+ }) as KeyImport);
613
+ }
614
+
615
+ if (keysToSave.length) {
616
+ await this.storage.addKeys({
617
+ keys: keysToSave,
618
+ encryptionKey,
619
+ name: this.name
620
+ });
621
+ }
622
+ const addedAddresses = keys.map(key => {
623
+ return { address: key.address };
624
+ });
625
+ return this.client.importAddresses({
626
+ pubKey: this.authPubKey,
627
+ payload: addedAddresses
628
+ });
629
+ }
630
+
631
+ async signTx(params) {
632
+ const { tx, keys, passphrase, signingKeys, changeAddressIdx } = params;
633
+ const utxos = params.utxos || [];
634
+ if (!utxos.length) {
635
+ await new Promise<void>((resolve, reject) => {
636
+ this.getUtxos()
637
+ .pipe(new ParseApiStream())
638
+ .on('data', utxo => utxos.push(utxo))
639
+ .on('end', () => resolve())
640
+ .on('err', err => reject(err));
641
+ });
642
+ }
643
+ let addresses = [];
644
+ let decryptedKeys;
645
+ if (!keys && !signingKeys) {
646
+ for (const utxo of utxos) {
647
+ addresses.push(utxo.address);
648
+ }
649
+ addresses = addresses.length > 0 ? addresses : await this.getAddresses();
650
+ decryptedKeys = await this.storage.getKeys({
651
+ addresses,
652
+ name: this.name,
653
+ encryptionKey: this.unlocked.encryptionKey
654
+ });
655
+ } else if (!signingKeys) {
656
+ addresses.push(keys[0]);
657
+ for (const element of utxos) {
658
+ const keyToDecrypt = keys.find(key => key.address === element.address);
659
+ addresses.push(keyToDecrypt);
660
+ }
661
+ const decryptedParams = Encryption.bitcoinCoreDecrypt(addresses, passphrase);
662
+ decryptedKeys = [...decryptedParams.jsonlDecrypted];
663
+ }
664
+ if (this.isUtxoChain()) {
665
+ // If changeAddressIdx == null, then save the change key at the current addressIndex (just in case)
666
+ const changeKey = await this.derivePrivateKey(true, changeAddressIdx == null ? this.addressIndex : changeAddressIdx);
667
+ await this.importKeys({ keys: [changeKey] });
668
+ }
669
+
670
+ const payload = {
671
+ chain: this.chain,
672
+ network: this.network,
673
+ tx,
674
+ keys: signingKeys || decryptedKeys,
675
+ key: signingKeys ? signingKeys[0] : decryptedKeys[0],
676
+ utxos
677
+ };
678
+ return Transactions.sign({ ...payload });
679
+ }
680
+
681
+ async checkWallet() {
682
+ return this.client.checkWallet({
683
+ pubKey: this.authPubKey
684
+ });
685
+ }
686
+
687
+ async syncAddresses(withChangeAddress = false) {
688
+ const addresses = new Array<string>();
689
+ if (this.addressIndex !== undefined) {
690
+ for (let i = 0; i < this.addressIndex; i++) {
691
+ addresses.push(this.deriveAddress(i, false));
692
+ if (withChangeAddress) {
693
+ addresses.push(this.deriveAddress(i, true));
694
+ }
695
+ }
696
+ }
697
+ return this.client.importAddresses({
698
+ pubKey: this.authPubKey,
699
+ payload: addresses.map(a => ({ address: a }))
700
+ });
701
+ }
702
+
703
+ async getAddresses() {
704
+ const walletAddresses = await this.client.getAddresses({
705
+ pubKey: this.authPubKey
706
+ });
707
+ return walletAddresses.map(walletAddress => walletAddress.address);
708
+ }
709
+
710
+ async getLocalAddress(address) {
711
+ return this.storage.getAddress({ name: this.name, address });
712
+ }
713
+
714
+ async getLocalAddresses(limit?: number, skip?: number) {
715
+ return this.storage.getAddresses({ name: this.name, limit, skip });
716
+ }
717
+
718
+ async checkAddressOnServer(address) {
719
+ const walletAddresses = await this.getAddresses();
720
+ return !!walletAddresses.find(a => a === address);
721
+ }
722
+
723
+ deriveAddress(addressIndex, isChange) {
724
+ if (addressIndex === 0 && this.addressZero) {
725
+ return this.addressZero;
726
+ }
727
+ const address = Deriver.deriveAddress(this.chain, this.network, this.xPubKey, addressIndex, isChange, this.addressType);
728
+ return address;
729
+ }
730
+
731
+ async solSignMessage(privateKey, message) {
732
+ const privKeyBytes = SolKit.getBase58Encoder().encode(privateKey);
733
+ const keypair = await SolKit.createKeyPairFromPrivateKeyBytes(privKeyBytes);
734
+ const encodedMessage = SolKit.getUtf8Encoder().encode(message);
735
+ const signedBytes = await SolKit.signBytes(keypair.privateKey, encodedMessage);
736
+ return SolKit.getBase58Decoder().decode(signedBytes);
737
+ }
738
+
739
+ async getBlockTip() {
740
+ return this.client.getBlockTip();
741
+ }
742
+
743
+ async derivePrivateKey(isChange, addressIndex = this.addressIndex) {
744
+ const keyToImport = await Deriver.derivePrivateKey(
745
+ this.chain,
746
+ this.network,
747
+ this.unlocked.masterKey,
748
+ addressIndex || 0,
749
+ isChange,
750
+ this.addressType
751
+ );
752
+ return keyToImport;
753
+ }
754
+
755
+ async nextAddressPair(withChangeAddress?: boolean) {
756
+ return this.generateAddressPair(this.addressIndex, withChangeAddress);
757
+ }
758
+
759
+ async generateAddressPair(addressIndex: number, withChangeAddress?: boolean) {
760
+ if (this.lite) {
761
+ return this.nextAddressPairLite(withChangeAddress);
762
+ }
763
+ addressIndex = addressIndex || 0;
764
+ const newPrivateKey = await this.derivePrivateKey(false, addressIndex);
765
+ const keys = [newPrivateKey];
766
+ if (withChangeAddress) {
767
+ const newChangePrivateKey = await this.derivePrivateKey(true, addressIndex);
768
+ keys.push(newChangePrivateKey);
769
+ }
770
+ if (addressIndex === this.addressIndex) {
771
+ this.addressIndex++;
772
+ }
773
+ await this.importKeys({ keys });
774
+ if (addressIndex === 0) {
775
+ this.addressZero = newPrivateKey.address.toString();
776
+ }
777
+ await this.saveWallet();
778
+ return keys.map(key => key.address.toString());
779
+ }
780
+
781
+ async nextAddressPairLite(withChangeAddress?: boolean) {
782
+ return this.generateAddressPairLite(this.addressIndex, withChangeAddress);
783
+ }
784
+
785
+ async generateAddressPairLite(addressIndex: number, withChangeAddress?: boolean) {
786
+ addressIndex = addressIndex || 0;
787
+ const addresses = [];
788
+ addresses.push(this.deriveAddress(this.addressIndex, false));
789
+ if (withChangeAddress) {
790
+ addresses.push(this.deriveAddress(this.addressIndex, true));
791
+ }
792
+ if (addressIndex === this.addressIndex) {
793
+ this.addressIndex++;
794
+ }
795
+ await this.client.importAddresses({
796
+ pubKey: this.authPubKey,
797
+ payload: addresses
798
+ });
799
+ await this.saveWallet();
800
+ return addresses;
801
+ }
802
+
803
+ async getNonce(_addressIndex: number = 0, isChange?: boolean) {
804
+ const address = this.deriveAddress(0, isChange);
805
+ const count = await this.client.getNonce({ address });
806
+ if (!count || typeof count.nonce !== 'number') {
807
+ throw new Error('Unable to get nonce');
808
+ }
809
+ return count.nonce;
810
+ }
811
+
812
+ private async _getChangeAddress() {
813
+ if (!this.isUtxoChain()) {
814
+ return;
815
+ }
816
+ const key = await this.derivePrivateKey(true, this.addressIndex);
817
+ await this.importKeys({ keys: [key] });
818
+ return key.address;
819
+ }
820
+
821
+ async bumpTxFee({ txid, rawTx, changeIdx, feeRate, feeTarget, feePriority, noRbf, isSweep } = {} as BumpTxFeeType) {
822
+ if (changeIdx == null && this.isUtxoChain()) {
823
+ throw new Error('Must provide changeIdx for UTXO chains');
824
+ }
825
+
826
+ const lib = this.getLib();
827
+ let existingTx;
828
+ if (rawTx) {
829
+ if (lib.ethers) {
830
+ existingTx = lib.ethers.utils.parseTransaction(rawTx);
831
+ } else {
832
+ const tx = new lib.Transaction(rawTx);
833
+ txid = tx.id;
834
+ }
835
+ }
836
+ if (txid) {
837
+ existingTx = await this.getTransactionByTxid({ txid, populated: this.isUtxoChain() });
838
+ } else if (!existingTx) {
839
+ throw new Error('Must provide either rawTx or txid');
840
+ }
841
+
842
+ const params: any = {};
843
+
844
+ if (this.isUtxoChain()) {
845
+ const { coins: { inputs, outputs }, locktime } = existingTx;
846
+
847
+ params.utxos = inputs;
848
+ params.change = outputs.find(o => o.mintIndex == changeIdx).address;
849
+ params.recipients = outputs.filter(o => o.mintIndex != changeIdx).map(o => ({ address: o.address, amount: o.value }));
850
+ params.lockUntilBlock = locktime > 0 ? locktime : undefined;
851
+ params.replaceByFee = !noRbf;
852
+ params.isSweep = isSweep ?? outputs.length === 1;
853
+ if (feeRate) {
854
+ params.feeRate = feeRate;
855
+ } else {
856
+ const scale = 1e5; // convert from sat/kb to sat/byte
857
+ params.feeRate = Math.ceil((await this.getNetworkFee({ target: feeTarget })).feerate * scale);
858
+ console.log(`Bumping fee rate to ${params.feeRate} sats/byte`);
859
+ }
860
+
861
+ // EVM chains
862
+ } else {
863
+ const { nonce, gasLimit, gasPrice, to, data, value, chainId, type } = existingTx;
864
+ // converting gasLimit and value with toString avoids a bigNumber warning
865
+ params.nonce = nonce;
866
+ params.gasLimit = gasLimit?.toString();
867
+ params.gasPrice = gasPrice;
868
+ params.data = data;
869
+ params.chainId = chainId;
870
+ params.type = type;
871
+ params.recipients = [{ address: to, amount: value.toString() }];
872
+
873
+ // TODO fix type2 support
874
+ // eslint-disable-next-line no-constant-condition, no-constant-binary-expression
875
+ if (false && existingTx.type === 2) {
876
+ if (feeRate) {
877
+ params.maxGasFee = Web3.utils.toWei(feeRate.toString(), 'gwei');
878
+ } else {
879
+ // TODO placeholder until for type2 support is merged in another PR
880
+ // params.maxGasFee = (await wallet.getNetworkFee({ target: feeTarget })).feerate;
881
+ // console.log(`Bumping max gas price to ${Web3.utils.fromWei(params.maxGasFee.toString(), 'gwei')} gwei`);
882
+ }
883
+ if (feePriority) {
884
+ params.maxPriorityFee = Web3.utils.toWei(feePriority.toString(), 'gwei');
885
+ } else {
886
+ // TODO placeholder until for type2 support is merged in another PR
887
+ // params.maxPriorityFee = existingTx.maxPriorityFeePerGas;
888
+ // console.log(`Bumping max priority fee to ${Web3.utils.fromWei(params.maxPriorityFee.toString(), 'gwei')} gwei`);
889
+ }
890
+
891
+ // type 0
892
+ } else {
893
+ if (feeRate) {
894
+ params.gasPrice = Web3.utils.toWei(feeRate.toString(), 'gwei');
895
+ } else {
896
+ params.gasPrice = (await this.getNetworkFee({ target: feeTarget })).feerate;
897
+ console.log(`Bumping gas price to ${Web3.utils.fromWei(params.gasPrice.toString(), 'gwei')} gwei`);
898
+ }
899
+ }
900
+
901
+ }
902
+
903
+ const tx: string = await this.newTx(params);
904
+ return { tx, params };
905
+ }
906
+
907
+ async getAccountFlags({ index }) {
908
+ const account = this.deriveAddress(index ?? 0, false);
909
+ return this.client.getAccountFlags({ address: account });
910
+ }
911
+
912
+
913
+ async estimateGas(params: { to: string; from: string; data: string; value: string }) {
914
+ return this.client.estimateGas(params);
915
+ }
916
+
917
+ async getL1Fee(rawTx) {
918
+ try {
919
+ return this.client.getL1Fee({ rawTx });
920
+ } catch {
921
+ return 0;
922
+ }
923
+ }
924
+
925
+ isMainnet() {
926
+ return this.network === 'mainnet' || this.network === 'livenet';
927
+ }
928
+
929
+ isUnlocked() {
930
+ return !!this.unlocked;
931
+ }
932
+ }
933
+
934
+ export const AddressTypes = {
935
+ BTC: {
936
+ // pubkeyhash
937
+ pubkeyhash: 'pubkeyhash',
938
+ p2pkh: 'pubkeyhash',
939
+
940
+ // scripthash
941
+ scripthash: 'scripthash',
942
+ p2sh: 'scripthash',
943
+
944
+ // witnesspubkeyhash
945
+ witnesspubkeyhash: 'witnesspubkeyhash',
946
+ p2wpkh: 'witnesspubkeyhash',
947
+
948
+ // taproot
949
+ taproot: 'taproot',
950
+ p2tr: 'taproot'
951
+ },
952
+ BCH: {
953
+ // pubkeyhash
954
+ pubkeyhash: 'pubkeyhash',
955
+ p2pkh: 'pubkeyhash',
956
+
957
+ // scripthash
958
+ scripthash: 'scripthash',
959
+ p2sh: 'scripthash'
960
+ },
961
+ LTC: {
962
+ // pubkeyhash
963
+ pubkeyhash: 'pubkeyhash',
964
+ p2pkh: 'pubkeyhash',
965
+
966
+ // scripthash
967
+ scripthash: 'scripthash',
968
+ p2sh: 'scripthash',
969
+
970
+ // witnesspubkeyhash
971
+ witnesspubkeyhash: 'witnesspubkeyhash',
972
+ p2wpkh: 'witnesspubkeyhash',
973
+ },
974
+ DOGE: {
975
+ // pubkeyhash
976
+ pubkeyhash: 'pubkeyhash',
977
+ p2pkh: 'pubkeyhash',
978
+
979
+ // scripthash
980
+ scripthash: 'scripthash',
981
+ p2sh: 'scripthash'
982
+ }
983
+ };