-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathabstractEthLikeNewCoins.ts
More file actions
3192 lines (2883 loc) · 113 KB
/
abstractEthLikeNewCoins.ts
File metadata and controls
3192 lines (2883 loc) · 113 KB
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 {
AddressCoinSpecific,
BitGoBase,
BuildNftTransferDataOptions,
common,
Ecdsa,
ECDSAMethodTypes,
ECDSAUtils,
EthereumLibraryUnavailableError,
FeeEstimateOptions,
FullySignedTransaction,
getIsUnsignedSweep,
HalfSignedTransaction,
InvalidAddressError,
InvalidAddressVerificationObjectPropertyError,
IWallet,
KeyPair,
MPCSweepRecoveryOptions,
MPCSweepTxs,
MPCTx,
MPCTxs,
ParsedTransaction,
ParseTransactionOptions,
PrebuildTransactionResult,
PresignTransactionOptions as BasePresignTransactionOptions,
Recipient,
SignTransactionOptions as BaseSignTransactionOptions,
TxIntentMismatchError,
TxIntentMismatchRecipientError,
TransactionParams,
TransactionPrebuild as BaseTransactionPrebuild,
TransactionRecipient,
TypedData,
UnexpectedAddressError,
UnsignedTransactionTss,
Util,
VerifyAddressOptions as BaseVerifyAddressOptions,
VerifyTransactionOptions,
Wallet,
} from '@bitgo/sdk-core';
import { getDerivationPath } from '@bitgo/sdk-lib-mpc';
import { bip32 } from '@bitgo/secp256k1';
import {
BaseCoin as StaticsBaseCoin,
CoinFeature,
CoinMap,
coins,
EthereumNetwork as EthLikeNetwork,
ethGasConfigs,
} from '@bitgo/statics';
import type * as EthLikeCommon from '@ethereumjs/common';
import type * as EthLikeTxLib from '@ethereumjs/tx';
import { FeeMarketEIP1559Transaction, Transaction as LegacyTransaction } from '@ethereumjs/tx';
import { RLP } from '@ethereumjs/rlp';
import { SignTypedDataVersion, TypedDataUtils, TypedMessage } from '@metamask/eth-sig-util';
import { BigNumber } from 'bignumber.js';
import BN from 'bn.js';
import { randomBytes } from 'crypto';
import debugLib from 'debug';
import { addHexPrefix, bufArrToArr, stripHexPrefix, bufferToHex, setLengthLeft, toBuffer } from 'ethereumjs-util';
import Keccak from 'keccak';
import _ from 'lodash';
import secp256k1 from 'secp256k1';
import { AbstractEthLikeCoin } from './abstractEthLikeCoin';
import { EthLikeToken } from './ethLikeToken';
import {
calculateForwarderV1Address,
decodeTransferData,
ERC1155TransferBuilder,
ERC721TransferBuilder,
getBufferedByteCode,
getCommon,
getCreateForwarderParamsAndTypes,
getProxyInitcode,
getRawDecoded,
getToken,
KeyPair as KeyPairLib,
TransactionBuilder,
TransferBuilder,
} from './lib';
import { SendCrossChainRecoveryOptions } from './types';
/**
* The prebuilt hop transaction returned from the HSM
*/
interface HopPrebuild {
tx: string;
id: string;
signature: string;
paymentId: string;
gasPrice: number;
gasLimit: number;
amount: number;
recipient: string;
nonce: number;
userReqSig: string;
gasPriceMax: number;
}
/**
* The extra parameters to send to platform build route for hop transactions
*/
interface HopParams {
hopParams: {
gasPriceMax: number;
userReqSig: string;
paymentId: string;
gasLimit: number;
};
}
export interface EIP1559 {
maxPriorityFeePerGas: number;
maxFeePerGas: number;
}
export interface ReplayProtectionOptions {
chain: string | number;
hardfork: string;
}
export interface TransactionPrebuild extends BaseTransactionPrebuild {
hopTransaction?: HopPrebuild;
buildParams: {
recipients: Recipient[];
};
recipients: TransactionRecipient[];
nextContractSequenceId: number;
gasPrice: number;
gasLimit: number;
isBatch: boolean;
coin: string;
token?: string;
}
export interface SignFinalOptions {
txPrebuild: {
eip1559?: EIP1559;
replayProtectionOptions?: ReplayProtectionOptions;
gasPrice?: string;
gasLimit?: string;
recipients?: Recipient[];
halfSigned?: {
expireTime: number;
contractSequenceId: number;
backupKeyNonce?: number;
signature: string;
txHex?: string;
};
nextContractSequenceId?: number;
hopTransaction?: string;
backupKeyNonce?: number;
isBatch?: boolean;
txHex?: string;
expireTime?: number;
};
signingKeyNonce?: number;
walletContractAddress?: string;
prv: string;
recipients?: Recipient[];
common?: EthLikeCommon.default;
}
export interface SignTransactionOptions extends BaseSignTransactionOptions, SignFinalOptions {
isLastSignature?: boolean;
expireTime?: number;
sequenceId?: number;
gasLimit?: number;
gasPrice?: number;
custodianTransactionId?: string;
common?: EthLikeCommon.default;
walletVersion?: number;
}
export type SignedTransaction = HalfSignedTransaction | FullySignedTransaction;
export interface FeesUsed {
gasPrice: number;
gasLimit: number;
}
interface PrecreateBitGoOptions {
enterprise?: string;
newFeeAddress?: string;
}
export interface OfflineVaultTxInfo {
nextContractSequenceId?: string;
contractSequenceId?: string;
tx?: string;
txHex?: string;
userKey?: string;
backupKey?: string;
coin: string;
gasPrice: number;
gasLimit: number;
recipients: Recipient[];
walletContractAddress: string;
amount: string;
backupKeyNonce: number;
// For Eth Specific Coins
eip1559?: EIP1559;
replayProtectionOptions?: ReplayProtectionOptions;
// For Hot Wallet EvmBasedCrossChainRecovery Specific
halfSigned?: HalfSignedTransaction;
feesUsed?: FeesUsed;
isEvmBasedCrossChainRecovery?: boolean;
walletVersion?: number;
}
interface UnformattedTxInfo {
recipient: Recipient;
}
export type UnsignedSweepTxMPCv2 = {
txRequests: {
transactions: [
{
unsignedTx: UnsignedTransactionTss;
nonce: number;
signatureShares: [];
}
];
walletCoin: string;
}[];
};
export type UnsignedBuilConsolidation = {
transactions: MPCSweepTxs[] | UnsignedSweepTxMPCv2[] | RecoveryInfo[] | OfflineVaultTxInfo[];
lastScanIndex: number;
};
export type RecoverOptionsWithBytes = {
isTss: true;
/**
* @deprecated this is no longer used
*/
openSSLBytes?: Uint8Array;
};
export type NonTSSRecoverOptions = {
isTss?: false | undefined;
};
export type TSSRecoverOptions = RecoverOptionsWithBytes | NonTSSRecoverOptions;
export type RecoverOptions = {
userKey: string;
backupKey: string;
walletPassphrase?: string;
walletContractAddress: string; // use this as walletBaseAddress for TSS
recoveryDestination: string;
krsProvider?: string;
gasPrice?: number;
gasLimit?: number;
eip1559?: EIP1559;
replayProtectionOptions?: ReplayProtectionOptions;
bitgoFeeAddress?: string;
bitgoDestinationAddress?: string;
tokenContractAddress?: string;
intendedChain?: string;
common?: EthLikeCommon.default;
derivationSeed?: string;
apiKey?: string; // optional API key to use instead of the one from the environment
isUnsignedSweep?: boolean; // specify if this is an unsigned recovery
} & TSSRecoverOptions;
export type GetBatchExecutionInfoRT = {
values: [string[], string[]];
totalAmount: string;
};
export interface BuildTransactionParams {
to: string;
nonce?: number;
value: number;
data?: Buffer;
gasPrice?: number;
gasLimit?: number;
eip1559?: EIP1559;
replayProtectionOptions?: ReplayProtectionOptions;
}
export interface RecoveryInfo {
id: string;
tx: string;
backupKey?: string;
coin?: string;
}
export interface RecoverTokenTransaction {
halfSigned: {
recipient: Recipient;
expireTime: number;
contractSequenceId: number;
operationHash: string;
signature: string;
gasLimit: number;
gasPrice: number;
tokenContractAddress: string;
walletId: string;
};
}
export interface RecoverTokenOptions {
tokenContractAddress: string;
wallet: Wallet;
recipient: string;
broadcast?: boolean;
walletPassphrase?: string;
prv?: string;
}
export interface GetSendMethodArgsOptions {
recipient: Recipient;
expireTime: number;
contractSequenceId: number;
signature: string;
}
export interface SendMethodArgs {
name: string;
type: string;
value: any;
}
interface HopTransactionBuildOptions {
wallet: Wallet;
recipients: Recipient[];
walletPassphrase: string;
}
export interface BuildOptions {
hop?: boolean;
wallet?: Wallet;
recipients?: Recipient[];
walletPassphrase?: string;
[index: string]: unknown;
}
interface FeeEstimate {
gasLimitEstimate: number;
feeEstimate: number;
}
// TODO: This interface will need to be updated for the new fee model introduced in the London Hard Fork
interface EthTransactionParams extends TransactionParams {
gasPrice?: number;
gasLimit?: number;
hopParams?: HopParams;
hop?: boolean;
prebuildTx?: PrebuildTransactionResult;
tokenName?: string;
}
export interface VerifyEthTransactionOptions extends VerifyTransactionOptions {
txPrebuild: TransactionPrebuild;
txParams: EthTransactionParams;
}
interface PresignTransactionOptions extends TransactionPrebuild, BasePresignTransactionOptions {
wallet: Wallet;
}
interface EthAddressCoinSpecifics extends AddressCoinSpecific {
forwarderVersion: number;
salt?: string;
}
export const DEFAULT_SCAN_FACTOR = 20;
export interface EthConsolidationRecoveryOptions {
coinName?: string;
walletContractAddress?: string;
apiKey?: string;
isTss?: boolean;
userKey?: string;
backupKey?: string;
walletPassphrase?: string;
recoveryDestination?: string;
krsProvider?: string;
gasPrice?: number;
gasLimit?: number;
eip1559?: EIP1559;
replayProtectionOptions?: ReplayProtectionOptions;
bitgoFeeAddress?: string;
bitgoDestinationAddress?: string;
tokenContractAddress?: string;
intendedChain?: string;
common?: EthLikeCommon.default;
derivationSeed?: string;
bitgoKey?: string;
startingScanIndex?: number;
endingScanIndex?: number;
ignoreAddressTypes?: unknown;
}
export interface VerifyEthAddressOptions extends BaseVerifyAddressOptions {
baseAddress: string;
coinSpecific: EthAddressCoinSpecifics;
forwarderVersion: number;
}
const debug = debugLib('bitgo:v2:ethlike');
export const optionalDeps = {
get ethAbi() {
try {
return require('ethereumjs-abi');
} catch (e) {
debug('unable to load ethereumjs-abi:');
debug(e.stack);
throw new EthereumLibraryUnavailableError(`ethereumjs-abi`);
}
},
get ethUtil() {
try {
return require('ethereumjs-util');
} catch (e) {
debug('unable to load ethereumjs-util:');
debug(e.stack);
throw new EthereumLibraryUnavailableError(`ethereumjs-util`);
}
},
get EthTx(): typeof EthLikeTxLib {
try {
return require('@ethereumjs/tx');
} catch (e) {
debug('unable to load @ethereumjs/tx');
debug(e.stack);
throw new EthereumLibraryUnavailableError(`@ethereumjs/tx`);
}
},
get EthCommon(): typeof EthLikeCommon {
try {
return require('@ethereumjs/common');
} catch (e) {
debug('unable to load @ethereumjs/common:');
debug(e.stack);
throw new EthereumLibraryUnavailableError(`@ethereumjs/common`);
}
},
};
export abstract class AbstractEthLikeNewCoins extends AbstractEthLikeCoin {
static hopTransactionSalt = 'bitgoHopAddressRequestSalt';
protected readonly sendMethodName: 'sendMultiSig' | 'sendMultiSigToken';
readonly staticsCoin?: Readonly<StaticsBaseCoin>;
protected constructor(bitgo: BitGoBase, staticsCoin?: Readonly<StaticsBaseCoin>) {
super(bitgo, staticsCoin);
if (!staticsCoin) {
throw new Error('missing required constructor parameter staticsCoin');
}
this.staticsCoin = staticsCoin;
this.sendMethodName = 'sendMultiSig';
}
/**
* Method to return the coin's network object
* @returns {EthLikeNetwork | undefined}
*/
getNetwork(): EthLikeNetwork | undefined {
return this.staticsCoin?.network as EthLikeNetwork;
}
/**
* Evaluates whether an address string is valid for this coin
* @param {string} address
* @returns {boolean} True if address is the valid ethlike adderss
*/
isValidAddress(address: string): boolean {
return optionalDeps.ethUtil.isValidAddress(optionalDeps.ethUtil.addHexPrefix(address));
}
/**
* Flag for sending data along with transactions
* @returns {boolean} True if okay to send tx data (ETH), false otherwise
*/
transactionDataAllowed() {
return true;
}
/**
* Default expire time for a contract call (1 week)
* @returns {number} Time in seconds
*/
getDefaultExpireTime(): number {
return Math.floor(new Date().getTime() / 1000) + 60 * 60 * 24 * 7;
}
/**
* Method to get the custom chain common object based on params from recovery
* @param {number} chainId - the chain id of the custom chain
* @returns {EthLikeCommon.default}
*/
static getCustomChainCommon(chainId: number): EthLikeCommon.default {
const coinName = CoinMap.coinNameFromChainId(chainId);
const coin = coins.get(coinName);
const ethLikeCommon = getCommon(coin.network as EthLikeNetwork);
return ethLikeCommon;
}
/**
* Gets correct Eth Common object based on params from either recovery or tx building
* @param {EIP1559} eip1559 - configs that specify whether we should construct an eip1559 tx
* @param {ReplayProtectionOptions} replayProtectionOptions - check if chain id supports replay protection
* @returns {EthLikeCommon.default}
*/
private static getEthLikeCommon(
eip1559?: EIP1559,
replayProtectionOptions?: ReplayProtectionOptions
): EthLikeCommon.default {
// if eip1559 params are specified, default to london hardfork, otherwise,
// default to petersburg to avoid replay protection issues
const defaultHardfork = !!eip1559 ? 'london' : optionalDeps.EthCommon.Hardfork.Petersburg;
const ethLikeCommon = AbstractEthLikeNewCoins.getCustomChainCommon(replayProtectionOptions?.chain as number);
ethLikeCommon.setHardfork(replayProtectionOptions?.hardfork ?? defaultHardfork);
return ethLikeCommon;
}
/**
* Method to build the tx object
* @param {BuildTransactionParams} params - params to build transaction
* @returns {EthLikeTxLib.FeeMarketEIP1559Transaction | EthLikeTxLib.Transaction}
*/
static buildTransaction(
params: BuildTransactionParams
): EthLikeTxLib.FeeMarketEIP1559Transaction | EthLikeTxLib.Transaction {
// if eip1559 params are specified, default to london hardfork, otherwise,
// default to tangerine whistle to avoid replay protection issues
const ethLikeCommon = AbstractEthLikeNewCoins.getEthLikeCommon(params.eip1559, params.replayProtectionOptions);
const baseParams = {
to: params.to,
nonce: params.nonce,
value: params.value,
data: params.data,
gasLimit: new optionalDeps.ethUtil.BN(params.gasLimit),
};
const unsignedEthTx = !!params.eip1559
? optionalDeps.EthTx.FeeMarketEIP1559Transaction.fromTxData(
{
...baseParams,
maxFeePerGas: new optionalDeps.ethUtil.BN(params.eip1559.maxFeePerGas),
maxPriorityFeePerGas: new optionalDeps.ethUtil.BN(params.eip1559.maxPriorityFeePerGas),
},
{ common: ethLikeCommon }
)
: optionalDeps.EthTx.Transaction.fromTxData(
{
...baseParams,
gasPrice: new optionalDeps.ethUtil.BN(params.gasPrice),
},
{ common: ethLikeCommon }
);
return unsignedEthTx;
}
/**
* Query explorer for the balance of an address
* @param {String} address - the ETHLike address
* @param {String} apiKey - optional API key to use instead of the one from the environment
* @returns {BigNumber} address balance
*/
async queryAddressBalance(address: string, apiKey?: string): Promise<any> {
const result = await this.recoveryBlockchainExplorerQuery(
{
chainid: this.getChainId().toString(),
module: 'account',
action: 'balance',
address: address,
},
apiKey
);
// throw if the result does not exist or the result is not a valid number
if (!result || !result.result || isNaN(result.result)) {
throw new Error(`Could not obtain address balance for ${address} from the explorer, got: ${result.result}`);
}
return new optionalDeps.ethUtil.BN(result.result, 10);
}
/**
* @param {Recipient[]} recipients - the recipients of the transaction
* @param {number} expireTime - the expire time of the transaction
* @param {number} contractSequenceId - the contract sequence id of the transaction
* @returns {string}
*/
getOperationSha3ForExecuteAndConfirm(
recipients: Recipient[],
expireTime: number,
contractSequenceId: number
): string {
if (!recipients || !Array.isArray(recipients)) {
throw new Error('expecting array of recipients');
}
// Right now we only support 1 recipient
if (recipients.length !== 1) {
throw new Error('must send to exactly 1 recipient');
}
if (!_.isNumber(expireTime)) {
throw new Error('expireTime must be number of seconds since epoch');
}
if (!_.isNumber(contractSequenceId)) {
throw new Error('contractSequenceId must be number');
}
// Check inputs
recipients.forEach(function (recipient) {
if (
!_.isString(recipient.address) ||
!optionalDeps.ethUtil.isValidAddress(optionalDeps.ethUtil.addHexPrefix(recipient.address))
) {
throw new Error('Invalid address: ' + recipient.address);
}
let amount: BigNumber;
try {
amount = new BigNumber(recipient.amount);
} catch (e) {
throw new Error('Invalid amount for: ' + recipient.address + ' - should be numeric');
}
recipient.amount = amount.toFixed(0);
if (recipient.data && !_.isString(recipient.data)) {
throw new Error('Data for recipient ' + recipient.address + ' - should be of type hex string');
}
});
const recipient = recipients[0];
return optionalDeps.ethUtil.bufferToHex(
optionalDeps.ethAbi.soliditySHA3(...this.getOperation(recipient, expireTime, contractSequenceId))
);
}
/**
* Get transfer operation for coin
* @param {Recipient} recipient - recipient info
* @param {number} expireTime - expiry time
* @param {number} contractSequenceId - sequence id
* @returns {Array} operation array
*/
getOperation(recipient: Recipient, expireTime: number, contractSequenceId: number): (string | Buffer)[][] {
const network = this.getNetwork() as EthLikeNetwork;
return [
['string', 'address', 'uint', 'bytes', 'uint', 'uint'],
[
network.nativeCoinOperationHashPrefix,
new optionalDeps.ethUtil.BN(optionalDeps.ethUtil.stripHexPrefix(recipient.address), 16),
recipient.amount,
Buffer.from(optionalDeps.ethUtil.stripHexPrefix(optionalDeps.ethUtil.padToEven(recipient.data || '')), 'hex'),
expireTime,
contractSequenceId,
],
];
}
/**
* Queries the contract (via explorer API) for the next sequence ID
* @param {String} address - address of the contract
* @param {String} apiKey - optional API key to use instead of the one from the environment
* @returns {Promise<Number>} sequence ID
*/
async querySequenceId(address: string, apiKey?: string): Promise<number> {
// Get sequence ID using contract call
const sequenceIdMethodSignature = optionalDeps.ethAbi.methodID('getNextSequenceId', []);
const sequenceIdArgs = optionalDeps.ethAbi.rawEncode([], []);
const sequenceIdData = Buffer.concat([sequenceIdMethodSignature, sequenceIdArgs]).toString('hex');
const result = await this.recoveryBlockchainExplorerQuery(
{
chainid: this.getChainId().toString(),
module: 'proxy',
action: 'eth_call',
to: address,
data: sequenceIdData,
tag: 'latest',
},
apiKey
);
if (!result || !result.result) {
throw new Error('Could not obtain sequence ID from explorer, got: ' + result.result);
}
const sequenceIdHex = result.result;
return new optionalDeps.ethUtil.BN(sequenceIdHex.slice(2), 16).toNumber();
}
/**
* Recover an unsupported token from a BitGo multisig wallet
* This builds a half-signed transaction, for which there will be an admin route to co-sign and broadcast. Optionally
* the user can set params.broadcast = true and the half-signed tx will be sent to BitGo for cosigning and broadcasting
* @param {RecoverTokenOptions} params
* @param {Wallet} params.wallet - the wallet to recover the token from
* @param {string} params.tokenContractAddress - the contract address of the unsupported token
* @param {string} params.recipient - the destination address recovered tokens should be sent to
* @param {string} params.walletPassphrase - the wallet passphrase
* @param {string} params.prv - the xprv
* @param {boolean} params.broadcast - if true, we will automatically submit the half-signed tx to BitGo for cosigning and broadcasting
* @returns {Promise<RecoverTokenTransaction>}
*/
async recoverToken(params: RecoverTokenOptions): Promise<RecoverTokenTransaction> {
const network = this.getNetwork() as EthLikeNetwork;
if (!_.isObject(params)) {
throw new Error(`recoverToken must be passed a params object. Got ${params} (type ${typeof params})`);
}
if (_.isUndefined(params.tokenContractAddress) || !_.isString(params.tokenContractAddress)) {
throw new Error(
`tokenContractAddress must be a string, got ${
params.tokenContractAddress
} (type ${typeof params.tokenContractAddress})`
);
}
if (!this.isValidAddress(params.tokenContractAddress)) {
throw new Error('tokenContractAddress not a valid address');
}
if (_.isUndefined(params.wallet) || !(params.wallet instanceof Wallet)) {
throw new Error(`wallet must be a wallet instance, got ${params.wallet} (type ${typeof params.wallet})`);
}
if (_.isUndefined(params.recipient) || !_.isString(params.recipient)) {
throw new Error(`recipient must be a string, got ${params.recipient} (type ${typeof params.recipient})`);
}
if (!this.isValidAddress(params.recipient)) {
throw new Error('recipient not a valid address');
}
if (!optionalDeps.ethUtil.bufferToHex || !optionalDeps.ethAbi.soliditySHA3) {
throw new Error('ethereum not fully supported in this environment');
}
// Get token balance from external API
const coinSpecific = params.wallet.coinSpecific();
if (!coinSpecific || !_.isString(coinSpecific.baseAddress)) {
throw new Error('missing required coin specific property baseAddress');
}
const recoveryAmount = await this.queryAddressTokenBalance(params.tokenContractAddress, coinSpecific.baseAddress);
if (params.broadcast) {
// We're going to create a normal ETH transaction that sends an amount of 0 ETH to the
// tokenContractAddress and encode the unsupported-token-send data in the data field
// #tricksy
const sendMethodArgs = [
{
name: '_to',
type: 'address',
value: params.recipient,
},
{
name: '_value',
type: 'uint256',
value: recoveryAmount.toString(10),
},
];
const methodSignature = optionalDeps.ethAbi.methodID('transfer', _.map(sendMethodArgs, 'type'));
const encodedArgs = optionalDeps.ethAbi.rawEncode(_.map(sendMethodArgs, 'type'), _.map(sendMethodArgs, 'value'));
const sendData = Buffer.concat([methodSignature, encodedArgs]);
const broadcastParams: any = {
address: params.tokenContractAddress,
amount: '0',
data: sendData.toString('hex'),
};
if (params.walletPassphrase) {
broadcastParams.walletPassphrase = params.walletPassphrase;
} else if (params.prv) {
broadcastParams.prv = params.prv;
}
return await params.wallet.send(broadcastParams);
}
const recipient = {
address: params.recipient,
amount: recoveryAmount.toString(10),
};
// This signature will be valid for one week
const expireTime = Math.floor(new Date().getTime() / 1000) + 60 * 60 * 24 * 7;
// Get sequence ID. We do this by building a 'fake' eth transaction, so the platform will increment and return us the new sequence id
// This _does_ require the user to have a non-zero wallet balance
const { nextContractSequenceId, gasPrice, gasLimit } = (await params.wallet.prebuildTransaction({
recipients: [
{
address: params.recipient,
amount: '1',
},
],
})) as any;
// these recoveries need to be processed by support, but if the customer sends any transactions before recovery is
// complete the sequence ID will be invalid. artificially inflate the sequence ID to allow more time for processing
const safeSequenceId = nextContractSequenceId + 1000;
// Build sendData for ethereum tx
const operationTypes = ['string', 'address', 'uint', 'address', 'uint', 'uint'];
const operationArgs = [
// Token operation has prefix has been added here so that ether operation hashes, signatures cannot be re-used for tokenSending
network.tokenOperationHashPrefix,
new optionalDeps.ethUtil.BN(optionalDeps.ethUtil.stripHexPrefix(recipient.address), 16),
recipient.amount,
new optionalDeps.ethUtil.BN(optionalDeps.ethUtil.stripHexPrefix(params.tokenContractAddress), 16),
expireTime,
safeSequenceId,
];
const operationHash = optionalDeps.ethUtil.bufferToHex(
optionalDeps.ethAbi.soliditySHA3(operationTypes, operationArgs)
);
const userPrv = await params.wallet.getPrv({
prv: params.prv,
walletPassphrase: params.walletPassphrase,
});
const signature = Util.ethSignMsgHash(operationHash, Util.xprvToEthPrivateKey(userPrv));
return {
halfSigned: {
recipient: recipient,
expireTime: expireTime,
contractSequenceId: safeSequenceId,
operationHash: operationHash,
signature: signature,
gasLimit: gasLimit,
gasPrice: gasPrice,
tokenContractAddress: params.tokenContractAddress,
walletId: params.wallet.id(),
},
};
}
/**
* Ensure either enterprise or newFeeAddress is passed, to know whether to create new key or use enterprise key
* @param {PrecreateBitGoOptions} params
* @param {string} params.enterprise {String} the enterprise id to associate with this key
* @param {string} params.newFeeAddress {Boolean} create a new fee address (enterprise not needed in this case)
* @returns {void}
*/
preCreateBitGo(params: PrecreateBitGoOptions): void {
// We always need params object, since either enterprise or newFeeAddress is required
if (!_.isObject(params)) {
throw new Error(`preCreateBitGo must be passed a params object. Got ${params} (type ${typeof params})`);
}
if (_.isUndefined(params.enterprise) && _.isUndefined(params.newFeeAddress)) {
throw new Error(
'expecting enterprise when adding BitGo key. If you want to create a new ETH bitgo key, set the newFeeAddress parameter to true.'
);
}
// Check whether key should be an enterprise key or a BitGo key for a new fee address
if (!_.isUndefined(params.enterprise) && !_.isUndefined(params.newFeeAddress)) {
throw new Error(`Incompatible arguments - cannot pass both enterprise and newFeeAddress parameter.`);
}
if (!_.isUndefined(params.enterprise) && !_.isString(params.enterprise)) {
throw new Error(`enterprise should be a string - got ${params.enterprise} (type ${typeof params.enterprise})`);
}
if (!_.isUndefined(params.newFeeAddress) && !_.isBoolean(params.newFeeAddress)) {
throw new Error(
`newFeeAddress should be a boolean - got ${params.newFeeAddress} (type ${typeof params.newFeeAddress})`
);
}
}
/**
* Queries public block explorer to get the next ETHLike coin's nonce that should be used for the given ETH address
* @param {string} address
* @param {string} apiKey - optional API key to use instead of the one from the environment
* @returns {Promise<number>}
*/
async getAddressNonce(address: string, apiKey?: string): Promise<number> {
// Get nonce for backup key (should be 0)
let nonce = 0;
const result = await this.recoveryBlockchainExplorerQuery(
{
chainid: this.getChainId().toString(),
module: 'account',
action: 'txlist',
address,
},
apiKey
);
if (result && typeof result?.nonce === 'number') {
return Number(result.nonce);
}
if (!result || !Array.isArray(result.result)) {
throw new Error('Unable to find next nonce from Etherscan, got: ' + JSON.stringify(result));
}
const backupKeyTxList = result.result;
if (backupKeyTxList.length > 0) {
// Calculate last nonce used
const outgoingTxs = backupKeyTxList.filter((tx) => tx.from === address);
nonce = outgoingTxs.length;
}
return nonce;
}
/**
* Helper function for recover()
* This transforms the unsigned transaction information into a format the BitGo offline vault expects
* @param {UnformattedTxInfo} txInfo - tx info
* @param {EthLikeTxLib.Transaction | EthLikeTxLib.FeeMarketEIP1559Transaction} ethTx - the ethereumjs tx object
* @param {string} userKey - the user's key
* @param {string} backupKey - the backup key
* @param {Buffer} gasPrice - gas price for the tx
* @param {number} gasLimit - gas limit for the tx
* @param {EIP1559} eip1559 - eip1559 params
* @param {ReplayProtectionOptions} replayProtectionOptions - replay protection options
* @param {apiKey} apiKey - optional apiKey to use when retrieving block chain data
* @returns {Promise<OfflineVaultTxInfo>}
*/
async formatForOfflineVault(
txInfo: UnformattedTxInfo,
ethTx: EthLikeTxLib.Transaction | EthLikeTxLib.FeeMarketEIP1559Transaction,
userKey: string,
backupKey: string,
gasPrice: Buffer,
gasLimit: number,
eip1559?: EIP1559,
replayProtectionOptions?: ReplayProtectionOptions,
apiKey?: string
): Promise<OfflineVaultTxInfo> {
if (!ethTx.to) {
throw new Error('Eth tx must have a `to` address');
}
const backupHDNode = bip32.fromBase58(backupKey);
const backupSigningKey = backupHDNode.publicKey;
const response: OfflineVaultTxInfo = {
tx: ethTx.serialize().toString('hex'),
userKey,
backupKey,
coin: this.getChain(),
gasPrice: optionalDeps.ethUtil.bufferToInt(gasPrice).toFixed(),
gasLimit,
recipients: [txInfo.recipient],
walletContractAddress: ethTx.to.toString(),
amount: txInfo.recipient.amount as string,
backupKeyNonce: await this.getAddressNonce(
`0x${optionalDeps.ethUtil.publicToAddress(backupSigningKey, true).toString('hex')}`,
apiKey
),
eip1559,
replayProtectionOptions,
};
_.extend(response, txInfo);
response.nextContractSequenceId = response.contractSequenceId;
return response;
}
/**
* Helper function for recover()
* This transforms the unsigned transaction information into a format the BitGo offline vault expects
* @param {UnformattedTxInfo} txInfo - tx info
* @param {EthLikeTxLib.Transaction | EthLikeTxLib.FeeMarketEIP1559Transaction} ethTx - the ethereumjs tx object
* @param {string} userKey - the user's key
* @param {string} backupKey - the backup key
* @param {Buffer} gasPrice - gas price for the tx
* @param {number} gasLimit - gas limit for the tx
* @param {number} backupKeyNonce - the nonce of the backup key address
* @param {EIP1559} eip1559 - eip1559 params
* @param {ReplayProtectionOptions} replayProtectionOptions - replay protection options
* @returns {Promise<OfflineVaultTxInfo>}
*/
formatForOfflineVaultTSS(
txInfo: UnformattedTxInfo,
ethTx: EthLikeTxLib.Transaction | EthLikeTxLib.FeeMarketEIP1559Transaction,
userKey: string,
backupKey: string,
gasPrice: Buffer,
gasLimit: number,
backupKeyNonce: number,
eip1559?: EIP1559,
replayProtectionOptions?: ReplayProtectionOptions
): OfflineVaultTxInfo {
if (!ethTx.to) {
throw new Error('Eth tx must have a `to` address');