-
Notifications
You must be signed in to change notification settings - Fork 293
/
Copy pathwallet.ts
3724 lines (3333 loc) · 136 KB
/
wallet.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @prettier
*/
import * as t from 'io-ts';
import assert from 'assert';
import { BigNumber } from 'bignumber.js';
import * as _ from 'lodash';
import * as common from '../../common';
import {
IBaseCoin,
NFTTransferOptions,
SignedMessage,
SignedTransaction,
SignedTransactionRequest,
TransactionPrebuild,
VerifyAddressOptions,
} from '../baseCoin';
import { makeRandomKey } from '../bitcoin';
import { BitGoBase } from '../bitgoBase';
import { getSharedSecret } from '../ecdh';
import { AddressGenerationError, MethodNotImplementedError, MissingEncryptedKeychainError } from '../errors';
import * as internal from '../internal/internal';
import { drawKeycard } from '../internal';
import { decryptKeychainPrivateKey, Keychain, KeychainWithEncryptedPrv } from '../keychain';
import { IPendingApproval, PendingApproval, PendingApprovals } from '../pendingApproval';
import { TradingAccount } from '../trading';
import {
inferAddressType,
RequestTracer,
TxRequest,
EddsaUnsignedTransaction,
IntentOptionsForMessage,
IntentOptionsForTypedData,
RequestType,
} from '../utils';
import {
AccelerateTransactionOptions,
AddressesOptions,
BuildConsolidationTransactionOptions,
BuildTokenEnablementOptions,
ChangeFeeOptions,
ConsolidateUnspentsOptions,
CreateAddressOptions,
CreatePolicyRuleOptions,
CreateShareOptions,
BulkCreateShareOption,
BulkWalletShareOptions,
CrossChainUTXO,
DeployForwardersOptions,
DownloadKeycardOptions,
FanoutUnspentsOptions,
FetchCrossChainUTXOsOptions,
FlushForwarderTokenOptions,
ForwarderBalance,
ForwarderBalanceOptions,
FreezeOptions,
FundForwardersOptions,
GetAddressOptions,
GetPrvOptions,
GetTransactionOptions,
GetTransferOptions,
GetUserPrvOptions,
IWallet,
MaximumSpendable,
MaximumSpendableOptions,
ModifyWebhookOptions,
NftBalance,
PaginationOptions,
PrebuildAndSignTransactionOptions,
PrebuildTransactionOptions,
PrebuildTransactionResult,
RecoverTokenOptions,
RemovePolicyRuleOptions,
RemoveUserOptions,
SendManyOptions,
SendNFTOptions,
SendNFTResult,
SendOptions,
ShareWalletOptions,
SimulateWebhookOptions,
SubmitTransactionOptions,
SubWalletType,
SweepOptions,
TransferBySequenceIdOptions,
TransferCommentOptions,
TransfersOptions,
UnspentsOptions,
UpdateAddressOptions,
UpdateBuildDefaultOptions,
WalletCoinSpecific,
WalletData,
WalletEcdsaChallenges,
WalletSignMessageOptions,
WalletSignTransactionOptions,
WalletSignTypedDataOptions,
WalletType,
CreateBulkWalletShareListResponse,
SharedKeyChain,
BulkWalletShareKeychain,
ManageUnspentReservationOptions,
SignAndSendTxRequestOptions,
} from './iWallet';
import { StakingWallet } from '../staking';
import { Lightning } from '../lightning/custodial';
import EddsaUtils from '../utils/tss/eddsa';
import { EcdsaMPCv2Utils, EcdsaUtils } from '../utils/tss/ecdsa';
import { getTxRequest } from '../tss';
import { buildParamKeys, BuildParams } from './BuildParams';
import { postWithCodec } from '../utils/postWithCodec';
import { TxSendBody } from '@bitgo/public-types';
import { AddressBook, IAddressBook } from '../address-book';
import { IRequestTracer } from '../../api';
import { getTxRequestApiVersion, validateTxRequestApiVersion } from '../utils/txRequest';
const debug = require('debug')('bitgo:v2:wallet');
type ManageUnspents = 'consolidate' | 'fanout';
const whitelistedSendParams = TxSendBody.type.types.flatMap((t) => Object.keys(t.props));
export enum ManageUnspentsOptions {
BUILD_ONLY,
BUILD_SIGN_SEND,
}
function isPrebuildTransactionResult(
prebuildTx: string | PrebuildTransactionResult | undefined
): prebuildTx is PrebuildTransactionResult {
if (!prebuildTx || typeof prebuildTx === 'string') {
return false;
}
return (prebuildTx as PrebuildTransactionResult).walletId !== undefined;
}
export class Wallet implements IWallet {
public readonly bitgo: BitGoBase;
public readonly baseCoin: IBaseCoin;
public _wallet: WalletData;
private readonly tssUtils: EcdsaUtils | EcdsaMPCv2Utils | EddsaUtils | undefined;
private readonly _permissions?: string[];
constructor(bitgo: BitGoBase, baseCoin: IBaseCoin, walletData: any) {
this.bitgo = bitgo;
this.baseCoin = baseCoin;
this._wallet = walletData;
const userId = _.get(bitgo, '_user.id');
if (_.isString(userId)) {
const userDetails = _.find(walletData.users, { user: userId });
this._permissions = _.get(userDetails, 'permissions');
}
if (baseCoin?.supportsTss() && this._wallet.multisigType === 'tss') {
switch (baseCoin.getMPCAlgorithm()) {
case 'ecdsa':
if (walletData.multisigTypeVersion === 'MPCv2') {
this.tssUtils = new EcdsaMPCv2Utils(bitgo, baseCoin, this);
} else {
this.tssUtils = new EcdsaUtils(bitgo, baseCoin, this);
}
break;
case 'eddsa':
this.tssUtils = new EddsaUtils(bitgo, baseCoin, this);
break;
default:
this.tssUtils = undefined;
}
}
}
/**
* Build a URL using this wallet's id which can be used for BitGo API operations
* @param extra API specific string to append to the wallet id
*/
url(extra = ''): string {
return this.baseCoin.url('/wallet/' + this.id() + extra);
}
/**
* Get this wallet's id
*/
id(): string {
return this._wallet.id;
}
/**
* Get the number of approvals required for spending funds from this wallet
*/
approvalsRequired(): number {
return this._wallet.approvalsRequired;
}
/**
* Get the current balance of this wallet
*/
balance(): number {
return this._wallet.balance;
}
/** @deprecated use codec instead: t.exact(BuildParams).encode(v) */
prebuildWhitelistedParams(): string[] {
return buildParamKeys;
}
/**
* This is a strict sub-set of prebuildWhitelistedParams
*/
prebuildConsolidateAccountParams(): string[] {
return [
'consolidateAddresses',
'feeRate',
'maxFeeRate',
'memo',
'validFromBlock',
'validToBlock',
'preview',
'keepAlive',
'apiVersion',
];
}
/**
* Get the confirmed balance of this wallet
*/
confirmedBalance(): number {
return this._wallet.confirmedBalance;
}
/**
* Get the spendable balance of this wallet
*/
spendableBalance(): number {
return this._wallet.spendableBalance;
}
/**
* Get a string representation of the balance of this wallet
*
* This is useful when balances have the potential to overflow standard javascript numbers
*/
balanceString(): string {
return this._wallet.balanceString;
}
/**
* Get a string representation of the confirmed balance of this wallet
*
* This is useful when balances have the potential to overflow standard javascript numbers
*/
confirmedBalanceString(): string {
return this._wallet.confirmedBalanceString;
}
/**
* Get a string representation of the spendable balance of this wallet
*
* This is useful when balances have the potential to overflow standard javascript numbers
*/
spendableBalanceString(): string {
return this._wallet.spendableBalanceString;
}
/**
* Get the coin identifier for the type of coin this wallet holds
*/
coin(): string {
return this._wallet.coin;
}
type(): WalletType {
return this._wallet.type || 'hot';
}
multisigType(): 'onchain' | 'tss' {
return this._wallet.multisigType;
}
multisigTypeVersion(): 'MPCv2' | undefined {
return this._wallet.multisigTypeVersion;
}
subType(): SubWalletType | undefined {
return this._wallet.subType;
}
/**
* Get the label (name) for this wallet
*/
public label(): string {
return this._wallet.label;
}
public flags(): { name: string; value: string }[] {
return this._wallet.walletFlags ?? [];
}
public flag(name: string): string | undefined {
return this.flags().find((flag) => flag.name === name)?.value;
}
/**
* Get the public object ids for the keychains on this wallet.
*/
public keyIds(): string[] {
return this._wallet.keys;
}
/**
* Get a receive address for this wallet
*/
public receiveAddress(): string | undefined {
return this._wallet.receiveAddress?.address;
}
/**
* Get the wallet id of the wallet that this wallet was migrated from.
*
* For example, if this is a BCH wallet that was created from a BTC wallet,
* the BCH wallet migrated from field would have the BTC wallet id.
*/
public migratedFrom(): string | undefined {
return this._wallet.migratedFrom;
}
/**
* Return the token flush thresholds for this wallet
* @return {*|Object} pairs of { [tokenName]: thresholds } base units
*/
tokenFlushThresholds(): any {
if (this.baseCoin.getFamily() !== 'eth') {
throw new Error('not supported for this wallet');
}
return this._wallet.coinSpecific.tokenFlushThresholds;
}
/**
* Get wallet properties which are specific to certain coin implementations
*/
coinSpecific(): WalletCoinSpecific | undefined {
return this._wallet.coinSpecific;
}
/**
* Get all pending approvals on this wallet
*/
pendingApprovals(): IPendingApproval[] {
return this._wallet.pendingApprovals.map((currentApproval) => {
return new PendingApproval(this.bitgo, this.baseCoin, currentApproval, this);
});
}
/**
* Refresh the wallet object by syncing with the back-end
* @param params
* @returns {Wallet}
*/
async refresh(params: Record<string, never> = {}): Promise<Wallet> {
this._wallet = await this.bitgo.get(this.url()).result();
return this;
}
/**
* List the transactions for a given wallet
* @param params
* @returns {*}
*/
async transactions(params: PaginationOptions = {}): Promise<any> {
const query: PaginationOptions = {};
if (params.prevId) {
if (!_.isString(params.prevId)) {
throw new Error('invalid prevId argument, expecting string');
}
query.prevId = params.prevId;
}
if (params.limit) {
if (!_.isNumber(params.limit)) {
throw new Error('invalid limit argument, expecting number');
}
query.limit = params.limit;
}
return await this.bitgo
.get(this.baseCoin.url('/wallet/' + this._wallet.id + '/tx'))
.query(query)
.result();
}
/**
* Return a list of nft tokens for this wallet. Will always return undefined if the wallet
* was not initialized with the allTokens flag.
*
* @returns {NftBalance[] | undefined}
*/
nftBalances(): NftBalance[] | undefined {
if (this._wallet.nfts) {
return Object.values(this._wallet.nfts).map((nftData) => nftData);
}
return undefined;
}
/**
* Return a list of unsupported nft tokens for this wallet. Will always return undefined if the wallet
* was not initialized with the allTokens flag.
*
* @returns {NftBalance[] | undefined}
*/
unsupportedNftBalances(): NftBalance[] | undefined {
if (this._wallet.unsupportedNfts) {
return Object.values(this._wallet.unsupportedNfts).map((nftData) => nftData);
}
return undefined;
}
/**
* Returns a list of the wallets nft & unsupported nfts.
*
* @returns {NftBalance[]}
*/
async getNftBalances(): Promise<NftBalance[]> {
const walletData: Partial<WalletData> = await this.bitgo.get(this.url()).query({ allTokens: true }).result();
const supportedNfts = walletData?.nfts ? Object.values(walletData.nfts).map((balance) => balance) : [];
const unsupportedNfts = walletData?.unsupportedNfts
? Object.values(walletData.unsupportedNfts).map((balance) => balance)
: [];
return [...supportedNfts, ...unsupportedNfts];
}
/**
* List the transactions for a given wallet
* @param params
* - txHash the transaction hash to search for
* @returns {*}
*/
async getTransaction(params: GetTransactionOptions = {}): Promise<any> {
common.validateParams(params, ['txHash'], []);
const paginatedOptions: PaginationOptions = {};
if (!_.isUndefined(params.prevId)) {
if (!_.isString(params.prevId)) {
throw new Error('invalid prevId argument, expecting string');
}
paginatedOptions.prevId = params.prevId;
}
if (!_.isUndefined(params.limit)) {
if (!_.isInteger(params.limit) || params.limit < 1) {
throw new Error('invalid limit argument, expecting positive integer');
}
paginatedOptions.limit = params.limit;
}
const query = paginatedOptions;
if (params.includeRbf) {
query['includeRbf'] = params.includeRbf;
}
return await this.bitgo
.get(this.url('/tx/' + params.txHash))
.query(query)
.result();
}
/**
* List the transfers for a given wallet
* @param params
* @returns {*}
*/
async transfers(params: TransfersOptions = {}): Promise<any> {
const query: TransfersOptions = {};
if (params.prevId) {
if (!_.isString(params.prevId)) {
throw new Error('invalid prevId argument, expecting string');
}
query.prevId = params.prevId;
}
if (params.limit) {
if (!_.isNumber(params.limit)) {
throw new Error('invalid limit argument, expecting number');
}
query.limit = params.limit;
}
if (params.allTokens) {
if (!_.isBoolean(params.allTokens)) {
throw new Error('invalid allTokens argument, expecting boolean');
}
query.allTokens = params.allTokens;
}
if (params.searchLabel) {
if (!_.isString(params.searchLabel)) {
throw new Error('invalid searchLabel argument, expecting string');
}
query.searchLabel = params.searchLabel;
}
if (params.address) {
if (!_.isArray(params.address) && !_.isString(params.address)) {
throw new Error('invalid address argument, expecting string or array');
}
if (_.isArray(params.address)) {
params.address.forEach((address) => {
if (!_.isString(address)) {
throw new Error('invalid address argument, expecting array of address strings');
}
});
}
query.address = params.address;
}
if (params.dateGte) {
if (!_.isString(params.dateGte)) {
throw new Error('invalid dateGte argument, expecting string');
}
query.dateGte = params.dateGte;
}
if (params.dateLt) {
if (!_.isString(params.dateLt)) {
throw new Error('invalid dateLt argument, expecting string');
}
query.dateLt = params.dateLt;
}
if (!_.isNil(params.valueGte)) {
if (!_.isNumber(params.valueGte)) {
throw new Error('invalid valueGte argument, expecting number');
}
query.valueGte = params.valueGte;
}
if (!_.isNil(params.valueLt)) {
if (!_.isNumber(params.valueLt)) {
throw new Error('invalid valueLt argument, expecting number');
}
query.valueLt = params.valueLt;
}
if (!_.isNil(params.includeHex)) {
if (!_.isBoolean(params.includeHex)) {
throw new Error('invalid includeHex argument, expecting boolean');
}
query.includeHex = params.includeHex;
}
if (!_.isNil(params.state)) {
if (!Array.isArray(params.state) && !_.isString(params.state)) {
throw new Error('invalid state argument, expecting string or array');
}
if (Array.isArray(params.state)) {
params.state.forEach((state) => {
if (!_.isString(state)) {
throw new Error('invalid state argument, expecting array of state strings');
}
});
}
query.state = params.state;
}
if (!_.isNil(params.type)) {
if (!_.isString(params.type)) {
throw new Error('invalid type argument, expecting string');
}
query.type = params.type;
}
return await this.bitgo.get(this.url('/transfer')).query(query).result();
}
/**
* Get transfers on this wallet
* @param params
*/
async getTransfer(params: GetTransferOptions = {}): Promise<any> {
common.validateParams(params, ['id'], []);
return await this.bitgo.get(this.url('/transfer/' + params.id)).result();
}
/**
* Get a transaction by sequence id for a given wallet
* @param params
*/
async transferBySequenceId(params: TransferBySequenceIdOptions = {}): Promise<any> {
common.validateParams(params, ['sequenceId'], []);
return await this.bitgo.get(this.url('/transfer/sequenceId/' + params.sequenceId)).result();
}
/**
* Get the maximum amount you can spend in a single transaction
*
* @param {Object} params - parameters object
* @param {Number} params.limit - maximum number of selectable unspents
* @param {Number | String} params.minValue - the minimum value of unspents to use in satoshis
* @param {Number | String} params.maxValue - the maximum value of unspents to use in satoshis
* @param {Number} params.minHeight - the minimum height of unspents on the block chain to use
* @param {Number} params.minConfirms - all selected unspents will have at least this many confirmations
* @param {Boolean} params.enforceMinConfirmsForChange - Enforces minConfirms on change inputs
* @param {Number} params.feeRate - fee rate to use in calculation of maximum spendable in satoshis/kB
* @param {Number} params.maxFeeRate - upper limit for feeRate in satoshis/kB
* @param {String} params.recipientAddress - recipient addresses for a more accurate calculation of the maximum available to send
* @returns {{maximumSpendable: Number, coin: String}}
* NOTE : feeTxConfirmTarget omitted on purpose because gauging the maximum spendable amount with dynamic fees does not make sense
*/
async maximumSpendable(params: MaximumSpendableOptions = {}): Promise<MaximumSpendable> {
const filteredParams = _.pick(params, [
'enforceMinConfirmsForChange',
'feeRate',
'limit',
'maxFeeRate',
'maxValue',
'minConfirms',
'minHeight',
'minValue',
'plainTarget',
'recipientAddress',
'target',
]);
return await this.bitgo.get(this.url('/maximumSpendable')).query(filteredParams).result();
}
/**
* List the unspents for a given wallet
* @param params
* @returns {*}
*/
async unspents(params: UnspentsOptions = {}): Promise<any> {
const query = _.pick(params, [
'chains',
'limit',
'maxValue',
'minConfirms',
'minHeight',
'minValue',
'prevId',
'segwit',
'target',
]);
return this.bitgo.get(this.url('/unspents')).query(query).result();
}
/**
* Consolidate or fanout unspents on a wallet
*
* @param {String} routeName - either `consolidate` or `fanout`
*
* @param {Object} params - parameters object
*
* Wallet parameters:
* @param {String} params.walletPassphrase - the users wallet passphrase
* @param {String} params.xprv - the private key in string form if the walletPassphrase is not available
*
* Fee parameters:
* @param {Number} params.feeRate - The fee rate to use for the consolidation in satoshis/kB
* @param {Number} params.maxFeeRate - upper limit for feeRate in satoshis/kB
* @param {Number} params.maxFeePercentage - the maximum relative portion that you're willing to spend towards fees
* @param {Number} params.feeTxConfirmTarget - estimate the fees to aim for first confirmation with this number of blocks
*
* Input parameters:
* @param {Number | String} params.minValue - the minimum value of unspents to use in satoshis
* @param {Number | String} params.maxValue - the maximum value of unspents to use in satoshis
* @param {Number} params.minHeight - the minimum height of unspents on the block chain to use
* @param {Number} params.minConfirms - all selected unspents will have at least this many confirmations
* @param {Boolean} params.enforceMinConfirmsForChange - if true, minConfirms also applies to change outputs
* @param {Number} params.limit for routeName === 'consolidate'
* params.maxNumInputsToUse for routeName === 'fanout'
* - maximum number of unspents you want to use in the transaction
* Output parameters:
* @param {Number} params.numUnspentsToMake - the number of new unspents to make
* @param {Boolean} params.bulk - if set to True, this enables the consolidation of large number of unspents by creating multiple transactions,
* with each transaction composed of 200 unspents, except for the last transaction which may have fewer unspents.
*/
private async manageUnspents(
routeName: ManageUnspents,
params: ConsolidateUnspentsOptions | FanoutUnspentsOptions = {},
option = ManageUnspentsOptions.BUILD_SIGN_SEND
): Promise<unknown> {
common.validateParams(params, [], ['walletPassphrase', 'xprv']);
const reqId = new RequestTracer();
const fanoutInputFormat = params.maxNumInputsToUse ? 'maxNumInputsToUse' : 'unspents';
const filteredParams = _.pick(params, [
'feeRate',
'maxFeeRate',
'maxFeePercentage',
'feeTxConfirmTarget',
'minValue',
'maxValue',
'minHeight',
'minConfirms',
'enforceMinConfirmsForChange',
'targetAddress',
'txFormat',
'bulk',
routeName === 'consolidate' ? 'limit' : fanoutInputFormat,
'numUnspentsToMake',
]);
this.bitgo.setRequestTracer(reqId);
const buildResponse: TransactionPrebuild | TransactionPrebuild[] = await this.bitgo
.post(this.url(`/${routeName}Unspents`))
.send(filteredParams)
.result();
if (option === ManageUnspentsOptions.BUILD_ONLY) {
return buildResponse;
}
const keychains = (await this.baseCoin
.keychains()
.getKeysForSigning({ wallet: this, reqId })) as unknown as Keychain[];
const transactionParams = {
...params,
keychain: keychains[0],
pubs: keychains.map((k) => {
assert(k.pub);
return k.pub;
}),
// Building PSBTs with the bulk flag does not include the previous transaction for non-segwit inputs.
// Manually override the signing and validating to not fail.
allowNonSegwitSigningWithoutPrevTx: !!params.bulk,
};
const txPrebuilds = Array.isArray(buildResponse) ? buildResponse : [buildResponse];
const selectParams = _.pick(params, ['comment', 'otp', 'bulk']);
const response = await Promise.all(
txPrebuilds.map(async (txPrebuild) => {
const signedTransaction = await this.signTransaction({ ...transactionParams, txPrebuild });
const finalTxParams = _.extend({}, signedTransaction, selectParams, { type: routeName });
this.bitgo.setRequestTracer(reqId);
return this.sendTransaction(finalTxParams, reqId);
})
);
return Array.isArray(buildResponse) ? response : response[0];
}
/**
* Manage the unspent reservations on the wallet
*
* @param params.create - create a new reservation
* @param params.modify - modify an existing reservation
* @param params.delete - delete an existing reservation
*/
async manageUnspentReservations(
params: ManageUnspentReservationOptions
): Promise<{ unspents: { id: string; walletId: string; expireTime: string; userId?: string }[] }> {
const filteredParams = _.pick(params, ['create', 'modify', 'delete']);
this.bitgo.setRequestTracer(new RequestTracer());
// The URL cannot contain the coinName, so we remove it from the URL
const url = this.url(`/reservedunspents`).replace(`/${this.baseCoin.getChain()}`, '');
if (filteredParams.create) {
const filteredCreateParams = _.pick(params.create, ['unspentIds', 'expireTime']);
return this.bitgo.post(url).send(filteredCreateParams).result();
} else if (filteredParams.modify) {
const filteredModifyParams = _.pick(params.modify, ['unspentIds', 'changes']);
return this.bitgo.put(url).send(filteredModifyParams).result();
} else if (filteredParams.delete) {
const filteredDeleteParams = _.pick(params.delete, ['id']);
return this.bitgo.del(url).query(filteredDeleteParams).result();
} else {
throw new Error('Did not detect a creation, modification, or deletion request.');
}
}
/**
* Consolidate unspents on a wallet
*
* @param {Object} params - parameters object
* @param {String} params.walletPassphrase - the users wallet passphrase
* @param {String} params.xprv - the private key in string form if the walletPassphrase is not available
* @param {Number} params.feeRate - The fee rate to use for the consolidation in satoshis/kB
* @param {Number} params.maxFeeRate - upper limit for feeRate in satoshis/kB
* @param {Number} params.maxFeePercentage - the maximum relative portion that you're willing to spend towards fees
* @param {Number} params.feeTxConfirmTarget - estimate the fees to aim for first confirmation with this number of blocks
* @param {Number | String} params.minValue - the minimum value of unspents to use in satoshis
* @param {Number | String} params.maxValue - the maximum value of unspents to use in satoshis
* @param {Number} params.minHeight - the minimum height of unspents on the block chain to use
* @param {Number} params.minConfirms - all selected unspents will have at least this many confirmations
* @param {Boolean} params.enforceMinConfirmsForChange - if true, minConfirms also applies to change outputs
* @param {Number} params.limit for routeName === 'consolidate'
* params.maxNumInputsToUse for routeName === 'fanout'
* - maximum number of unspents you want to use in the transaction
* @param {Number} params.numUnspentsToMake - the number of new unspents to make. It is not applicable for if bulk consolidate.
* @param {Boolean} params.bulk - if set to True, this enables the consolidation of large number of unspents by creating multiple transactions,
* with each transaction composed of 200 unspents, except for the last transaction which may have fewer unspents.
*/
async consolidateUnspents(
params: ConsolidateUnspentsOptions = {},
option = ManageUnspentsOptions.BUILD_SIGN_SEND
): Promise<unknown> {
return this.manageUnspents('consolidate', params, option);
}
/**
* Fanout unspents on a wallet
*
* @param {Object} params - parameters object
* @param {String} params.walletPassphrase - the users wallet passphrase
* @param {String} params.xprv - the private key in string form if the walletPassphrase is not available
* @param {Number | String} params.minValue - the minimum value of unspents to use
* @param {Number | String} params.maxValue - the maximum value of unspents to use
* @param {Number} params.minHeight - the minimum height of unspents on the block chain to use
* @param {Number} params.minConfirms - all selected unspents will have at least this many confirmations
* @param {Number} params.maxFeePercentage - the maximum proportion of an unspent you are willing to lose to fees
* @param {Number} params.feeTxConfirmTarget - estimate the fees to aim for first confirmation with this number of blocks
* @param {Number} params.feeRate - The desired fee rate for the transaction in satoshis/kB
* @param {Number} params.maxFeeRate - The max limit for a fee rate in satoshis/kB
* @param {Number} params.maxNumInputsToUse - the number of unspents you want to use in the transaction
* @param {Number} params.numUnspentsToMake - the number of new unspents to make
*
* @param {ManageUnspentsOptions} option - flag to toggle build and send or build only
*/
async fanoutUnspents(
params: FanoutUnspentsOptions = {},
option = ManageUnspentsOptions.BUILD_SIGN_SEND
): Promise<unknown> {
return this.manageUnspents('fanout', params, option);
}
/**
* Set the token flush thresholds for the wallet. Updates the wallet.
* Tokens will only be flushed from forwarder contracts if the balance is greater than the threshold defined here.
* @param thresholds {Object} - pairs of { [tokenName]: threshold } (base units)
*/
async updateTokenFlushThresholds(thresholds: any = {}): Promise<any> {
if (this.baseCoin.getFamily() !== 'eth') {
throw new Error('not supported for this wallet');
}
this._wallet = await this.bitgo
.put(this.url())
.send({
tokenFlushThresholds: thresholds,
})
.result();
}
/**
* Updates the wallet. Sets flags for deployForwardersManually and flushForwardersManually of the wallet.
* @param forwarderFlags {Object} - {
"coinSpecific": {
[coinName]: {
"deployForwardersManually": {Boolean},
"flushForwardersManually": {Boolean}
}
}
}
*/
async updateForwarders(forwarderFlags: any = {}): Promise<any> {
if (this.baseCoin.getFamily() !== 'eth') {
throw new Error('not supported for this wallet');
}
this._wallet = await this.bitgo.put(this.url()).send(forwarderFlags).result();
}
/**
* To manually deploy an ETH address
*
* @param {Object} params - parameters object
* @param {String} [params.address] - addressId
* @param {String} [params.id] - addressId could be received also as id
* @returns {Object} Http response
*/
async deployForwarders(params: DeployForwardersOptions): Promise<any> {
if (_.isUndefined(params.address) && _.isUndefined(params.id)) {
throw new Error('address or id of address required');
}
let query;
if (params.address) {
query = params.address;
} else {
query = params.id;
}
const url = this.url(`/address/${encodeURIComponent(query)}/deployment`);
this._wallet = await this.bitgo.post(url).send(params).result();
return this._wallet;
}
/**
* To manually forward tokens from an ETH or CELO address
*
* @param {Object} params - parameters object
* @param {String} params.tokenName - Name of token that needs to be forwarded from the address
* @param {String} [params.address] -
* @param {String} [params.address] - addressId
* @param {String} [params.id] - addressId could be received also as id
* @param {String} [params.gasPrice] - Explicit gas price to use when forwarding token from the forwarder contract (ETH and Celo only). If not given, defaults to the current estimated network gas price.
* @param {String} [params.eip1559] - Specify eip1559 fee parameters in token forwarding transaction.
* @returns {Object} Http response
*/
async flushForwarderToken(params: FlushForwarderTokenOptions): Promise<any> {
if (_.isUndefined(params.address) && _.isUndefined(params.id)) {
throw new Error('address or id of address required');
}
let query;
if (params.address) {
query = params.address;
} else {
query = params.id;
}
const url = this.url(`/address/${encodeURIComponent(query)}/tokenforward`);
this._wallet = await this.bitgo.post(url).send(params).result();
return this._wallet;
}
/**
* Sweep funds for a wallet
*
* @param {Object} params - parameters object
* @param {String} params.address - The address to send all the funds in the wallet to
* @param {String} params.walletPassphrase - the users wallet passphrase
* @param {String} params.xprv - the private key in string form if the walletPassphrase is not available
* @param {String} params.otp - Two factor auth code to enable sending the transaction
* @param {Number} params.feeTxConfirmTarget - Estimate the fees to aim for first confirmation within this number of blocks
* @param {Number} params.feeRate - The desired fee rate for the transaction in satoshis/kB
* @param {Number} [params.maxFeeRate] - upper limit for feeRate in satoshis/kB
* @param {Boolean} [params.allowPartialSweep] - allows sweeping 200 unspents when the wallet has more than that
* @returns txHex {String} the txHex of the signed transaction
*/
async sweep(params: SweepOptions = {}): Promise<any> {
params = params || {};
common.validateParams(params, ['address'], ['walletPassphrase', 'xprv', 'otp']);
// The sweep API endpoint is only available to utxo-based coins
if (!this.baseCoin.sweepWithSendMany()) {
if (this.confirmedBalanceString() !== this.balanceString()) {
throw new Error(
'cannot sweep when unconfirmed funds exist on the wallet, please wait until all inbound transactions confirm'
);
}
const value = await this.bitgo.get(this.url('/maximumSpendable')).result();
const maximumSpendable = new BigNumber(value.maximumSpendable);
if (value === undefined || maximumSpendable.isZero()) {
throw new Error('no funds to sweep');
}
const sendManyParams: SendManyOptions = {
...params,
recipients: [
{
address: params.address || '', // Ensure address is always a string
amount: maximumSpendable.toString(),
},
],
};
return this.sendMany(sendManyParams);
}
// the following flow works for all UTXO coins
const reqId = new RequestTracer();
const filteredParams = _.pick(params, [
'address',
'feeRate',
'maxFeeRate',
'feeTxConfirmTarget',
'allowPartialSweep',
'txFormat',
]);
this.bitgo.setRequestTracer(reqId);
const response = await this.bitgo.post(this.url('/sweepWallet')).send(filteredParams).result();
const transaction = await this.baseCoin.explainTransaction(response);
if (transaction?.outputs.length) {
const invalidOutputAddress = transaction.outputs.find((output) => output.address !== params.address);
if (invalidOutputAddress) {
throw new Error(`invalid sweep destination ${invalidOutputAddress.address}, specified ${params.address}`);
}
} else {
throw new Error('invalid transaction, no destination address');
}
const keychains = (await this.baseCoin.keychains().getKeysForSigning({ wallet: this, reqId })) as any;
const transactionParams = {
...params,
txPrebuild: response,
keychain: keychains[0],
userKeychain: keychains[0],
backupKeychain: keychains.length > 1 ? keychains[1] : null,
bitgoKeychain: keychains.length > 2 ? keychains[2] : null,
prv: params.xprv,
};
const signedTransaction = await this.signTransaction(transactionParams);
const selectParams = _.pick(params, ['otp']);
const finalTxParams = _.extend({}, signedTransaction, selectParams);
this.bitgo.setRequestTracer(reqId);
return this.sendTransaction(finalTxParams, reqId);
}