-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathutils.ts
More file actions
1062 lines (984 loc) · 37.1 KB
/
utils.ts
File metadata and controls
1062 lines (984 loc) · 37.1 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
import { Buffer } from 'buffer';
import request from 'superagent';
import assert from 'assert';
import {
addHexPrefix,
bufferToHex,
bufferToInt,
generateAddress,
isValidAddress,
setLengthLeft,
stripHexPrefix,
toBuffer,
generateAddress2,
padToEven,
} from 'ethereumjs-util';
import { BaseCoin, BaseNetwork, coins, ContractAddressDefinedToken, EthereumNetwork } from '@bitgo/statics';
import EthereumAbi from 'ethereumjs-abi';
import EthereumCommon from '@ethereumjs/common';
import BN from 'bn.js';
import BigNumber from 'bignumber.js';
import {
ActivateMethodId,
BuildTransactionError,
LockMethodId,
SigningError,
TransactionType,
UnlockMethodId,
UnvoteMethodId,
VoteMethodId,
WithdrawMethodId,
} from '@bitgo/sdk-core';
import {
ERC1155TransferData,
ERC721TransferData,
FlushTokensData,
NativeTransferData,
SignatureParts,
TokenTransferData,
TransferData,
TxData,
WalletInitializationData,
ForwarderInitializationData,
} from './iface';
import { KeyPair } from './keyPair';
import {
createForwarderMethodId,
ERC1155BatchTransferTypeMethodId,
ERC1155BatchTransferTypes,
ERC1155SafeTransferTypeMethodId,
ERC1155SafeTransferTypes,
ERC721SafeTransferTypeMethodId,
ERC721SafeTransferTypes,
flushCoinsMethodId,
flushCoinsTypes,
flushForwarderTokensMethodId,
flushTokensTypes,
flushERC721ForwarderTokensMethodId,
flushERC721ForwarderTokensMethodIdV4,
flushERC721TokensTypes,
flushERC721TokensTypesv4,
flushERC1155ForwarderTokensMethodId,
flushERC1155ForwarderTokensMethodIdV4,
flushERC1155TokensTypes,
flushERC1155TokensTypesv4,
sendMultisigMethodId,
sendMultisigTokenMethodId,
sendMultiSigTokenTypes,
sendMultiSigTypes,
walletInitializationFirstBytes,
v1CreateForwarderMethodId,
walletSimpleConstructor,
createV1WalletTypes,
v1CreateWalletMethodId,
createV1ForwarderTypes,
recoveryWalletInitializationFirstBytes,
defaultForwarderVersion,
createV4ForwarderTypes,
v4CreateForwarderMethodId,
flushTokensTypesv4,
flushForwarderTokensMethodIdV4,
sendMultiSigTokenTypesFirstSigner,
sendMultiSigTypesFirstSigner,
} from './walletUtil';
import { EthTransactionData } from './types';
/**
* @param network
*/
export function getCommon(network: EthereumNetwork): EthereumCommon {
return EthereumCommon.forCustomChain(
// use the mainnet config as a base, override chain ids and network name
'mainnet',
{
name: network.type,
networkId: network.chainId,
chainId: network.chainId,
},
'london'
);
}
/**
* Signs the transaction using the appropriate algorithm
* and the provided common for the blockchain
*
* @param {TxData} transactionData the transaction data to sign
* @param {KeyPair} keyPair the signer's keypair
* @param {EthereumCommon} customCommon the network's custom common
* @returns {string} the transaction signed and encoded
*/
export async function signInternal(
transactionData: TxData,
keyPair: KeyPair,
customCommon: EthereumCommon
): Promise<string> {
if (!keyPair.getKeys().prv) {
throw new SigningError('Missing private key');
}
const ethTx = EthTransactionData.fromJson(transactionData, customCommon);
ethTx.sign(keyPair);
return ethTx.toSerialized();
}
/**
* Signs the transaction using the appropriate algorithm
*
* @param {TxData} transactionData the transaction data to sign
* @param {KeyPair} keyPair the signer's keypair
* @returns {string} the transaction signed and encoded
*/
export async function sign(transactionData: TxData, keyPair: KeyPair): Promise<string> {
return signInternal(transactionData, keyPair, getCommon(coins.get('teth').network as EthereumNetwork));
}
/**
* Returns the contract method encoded data
*
* @param {string} to destination address
* @param {number} value Amount to tranfer
* @param {string} data aditional method call data
* @param {number} expireTime expiration time for the transaction in seconds
* @param {number} sequenceId sequence id
* @param {string} signature signature of the call
* @returns {string} -- the contract method encoded data
*/
export function sendMultiSigData(
to: string,
value: string,
data: string,
expireTime: number,
sequenceId: number,
signature: string
): string {
const params = [to, value, toBuffer(data), expireTime, sequenceId, toBuffer(signature)];
const method = EthereumAbi.methodID('sendMultiSig', sendMultiSigTypes);
const args = EthereumAbi.rawEncode(sendMultiSigTypes, params);
return addHexPrefix(Buffer.concat([method, args]).toString('hex'));
}
/**
* Returns the contract method encoded data
*
* @param {string} to destination address
* @param {number} value Amount to tranfer
* @param {string} tokenContractAddress the address of the erc20 token contract
* @param {number} expireTime expiration time for the transaction in seconds
* @param {number} sequenceId sequence id
* @param {string} signature signature of the call
* @returns {string} -- the contract method encoded data
*/
export function sendMultiSigTokenData(
to: string,
value: string,
tokenContractAddress: string,
expireTime: number,
sequenceId: number,
signature: string
): string {
const params = [to, value, tokenContractAddress, expireTime, sequenceId, toBuffer(signature)];
const method = EthereumAbi.methodID('sendMultiSigToken', sendMultiSigTokenTypes);
const args = EthereumAbi.rawEncode(sendMultiSigTokenTypes, params);
return addHexPrefix(Buffer.concat([method, args]).toString('hex'));
}
/**
* Get the data required to make a flush tokens contract call
*
* @param forwarderAddress The forwarder address to flush
* @param tokenAddress The token address to flush from
*/
export function flushTokensData(forwarderAddress: string, tokenAddress: string, forwarderVersion: number): string {
let params: string[];
let method: Uint8Array;
let args: Uint8Array;
if (forwarderVersion >= 4) {
params = [tokenAddress];
method = EthereumAbi.methodID('flushTokens', flushTokensTypesv4);
args = EthereumAbi.rawEncode(flushTokensTypesv4, params);
} else {
params = [forwarderAddress, tokenAddress];
method = EthereumAbi.methodID('flushForwarderTokens', flushTokensTypes);
args = EthereumAbi.rawEncode(flushTokensTypes, params);
}
return addHexPrefix(Buffer.concat([method, args]).toString('hex'));
}
/**
* Get the data required to make a flush native coins contract call
*/
export function flushCoinsData(): string {
const params = [];
const method = EthereumAbi.methodID('flush', flushCoinsTypes);
const args = EthereumAbi.rawEncode(flushCoinsTypes, params);
return addHexPrefix(Buffer.concat([method, args]).toString('hex'));
}
/**
* Get the data required to make a flush ERC721 tokens contract call
* @param forwarderAddress - The forwarder address (for v0-v3)
* @param tokenAddress - The ERC721 token contract address
* @param tokenId - The token ID to flush
* @param forwarderVersion - The forwarder version
*/
export function flushERC721TokensData(
forwarderAddress: string,
tokenAddress: string,
tokenId: string,
forwarderVersion: number
): string {
let params: (string | Buffer)[];
let method: Uint8Array;
let args: Uint8Array;
if (forwarderVersion >= 4) {
params = [tokenAddress, tokenId];
method = EthereumAbi.methodID('flushERC721Token', flushERC721TokensTypesv4);
args = EthereumAbi.rawEncode(flushERC721TokensTypesv4, params);
} else {
params = [forwarderAddress, tokenAddress, tokenId];
method = EthereumAbi.methodID('flushERC721ForwarderTokens', flushERC721TokensTypes);
args = EthereumAbi.rawEncode(flushERC721TokensTypes, params);
}
return addHexPrefix(Buffer.concat([method, args]).toString('hex'));
}
/**
* Decode the given ABI-encoded flush ERC721 tokens data
* @param data The data to decode
* @param to The to address (contract address for v4+)
* @returns parsed flush data with forwarderAddress, tokenAddress, tokenId and forwarderVersion
*/
export function decodeFlushERC721TokensData(
data: string,
to?: string
): {
forwarderAddress: string;
tokenAddress: string;
tokenId: string;
forwarderVersion?: number;
} {
if (data.startsWith(flushERC721ForwarderTokensMethodIdV4)) {
if (!to) {
throw new BuildTransactionError(`Missing to address: ${to}`);
}
const [tokenAddress, tokenId] = getRawDecoded(
flushERC721TokensTypesv4,
getBufferedByteCode(flushERC721ForwarderTokensMethodIdV4, data)
);
return {
forwarderAddress: to,
tokenAddress: addHexPrefix(tokenAddress as string),
tokenId: new BigNumber(bufferToHex(tokenId as Buffer)).toFixed(),
forwarderVersion: 4,
};
} else if (data.startsWith(flushERC721ForwarderTokensMethodId)) {
const [forwarderAddress, tokenAddress, tokenId] = getRawDecoded(
flushERC721TokensTypes,
getBufferedByteCode(flushERC721ForwarderTokensMethodId, data)
);
return {
forwarderAddress: addHexPrefix(forwarderAddress as string),
tokenAddress: addHexPrefix(tokenAddress as string),
tokenId: new BigNumber(bufferToHex(tokenId as Buffer)).toFixed(),
};
}
throw new BuildTransactionError(`Invalid flush ERC721 bytecode: ${data}`);
}
/**
* Get the data required to make a flush ERC1155 tokens contract call
* @param forwarderAddress - The forwarder address (for v0-v3)
* @param tokenAddress - The ERC1155 token contract address
* @param tokenId - The token ID to flush
* @param forwarderVersion - The forwarder version
*/
export function flushERC1155TokensData(
forwarderAddress: string,
tokenAddress: string,
tokenId: string,
forwarderVersion: number
): string {
let params: (string | Buffer)[];
let method: Uint8Array;
let args: Uint8Array;
if (forwarderVersion >= 4) {
params = [tokenAddress, tokenId];
method = EthereumAbi.methodID('flushERC1155Tokens', flushERC1155TokensTypesv4);
args = EthereumAbi.rawEncode(flushERC1155TokensTypesv4, params);
} else {
params = [forwarderAddress, tokenAddress, tokenId];
method = EthereumAbi.methodID('flushERC1155ForwarderTokens', flushERC1155TokensTypes);
args = EthereumAbi.rawEncode(flushERC1155TokensTypes, params);
}
return addHexPrefix(Buffer.concat([method, args]).toString('hex'));
}
/**
* Decode the given ABI-encoded flush ERC1155 tokens data
* @param data The data to decode
* @param to The to address (contract address for v4+)
* @returns parsed flush data with forwarderAddress, tokenAddress, tokenId and forwarderVersion
*/
export function decodeFlushERC1155TokensData(
data: string,
to?: string
): {
forwarderAddress: string;
tokenAddress: string;
tokenId: string;
forwarderVersion?: number;
} {
if (data.startsWith(flushERC1155ForwarderTokensMethodIdV4)) {
if (!to) {
throw new BuildTransactionError(`Missing to address: ${to}`);
}
const [tokenAddress, tokenId] = getRawDecoded(
flushERC1155TokensTypesv4,
getBufferedByteCode(flushERC1155ForwarderTokensMethodIdV4, data)
);
return {
forwarderAddress: to,
tokenAddress: addHexPrefix(tokenAddress as string),
tokenId: new BigNumber(bufferToHex(tokenId as Buffer)).toFixed(),
forwarderVersion: 4,
};
} else if (data.startsWith(flushERC1155ForwarderTokensMethodId)) {
const [forwarderAddress, tokenAddress, tokenId] = getRawDecoded(
flushERC1155TokensTypes,
getBufferedByteCode(flushERC1155ForwarderTokensMethodId, data)
);
return {
forwarderAddress: addHexPrefix(forwarderAddress as string),
tokenAddress: addHexPrefix(tokenAddress as string),
tokenId: new BigNumber(bufferToHex(tokenId as Buffer)).toFixed(),
};
}
throw new BuildTransactionError(`Invalid flush ERC1155 bytecode: ${data}`);
}
/**
* Returns the create forwarder method calling data
*
* @returns {string} - the createForwarder method encoded
*/
export function getAddressInitializationData(): string {
return createForwarderMethodId;
}
/**
* Returns whether or not the string is a valid Eth address
*
* @param {string} address - the tx hash to validate
* @returns {boolean} - the validation result
*/
export function isValidEthAddress(address: string): boolean {
return isValidAddress(address);
}
/**
* Returns whether or not the string is a valid amount number
*
* @param {string} amount - the string to validate
* @returns {boolean} - the validation result
*/
export function isValidAmount(amount: string): boolean {
const bigNumberAmount = new BigNumber(amount);
return bigNumberAmount.isInteger() && bigNumberAmount.isGreaterThanOrEqualTo(0);
}
/**
* Returns the smart contract encoded data
*
* @param {string} data The wallet creation data to decode
* @returns {string[]} - The list of signer addresses
*/
export function decodeWalletCreationData(data: string): WalletInitializationData {
if (!(data.startsWith(walletInitializationFirstBytes) || data.startsWith(v1CreateWalletMethodId))) {
throw new BuildTransactionError(`Invalid wallet bytecode: ${data}`);
}
if (data.startsWith(walletInitializationFirstBytes)) {
const dataBuffer = Buffer.from(data.slice(2), 'hex');
// the last 160 bytes contain the serialized address array
const serializedSigners = dataBuffer.slice(-160);
const resultEncodedParameters = EthereumAbi.rawDecode(walletSimpleConstructor, serializedSigners);
if (resultEncodedParameters.length !== 1) {
throw new BuildTransactionError(`Could not decode wallet constructor bytecode: ${resultEncodedParameters}`);
}
const addresses: BN[] = resultEncodedParameters[0];
if (addresses.length !== 3) {
throw new BuildTransactionError(`invalid number of addresses in parsed constructor: ${addresses}`);
}
// sometimes ethereumjs-abi removes 0 padding at the start of addresses,
// so we should pad until they are the standard 20 bytes
const paddedAddresses = addresses.map((address) => stripHexPrefix(address.toString('hex')).padStart(40, '0'));
return { owners: paddedAddresses.map((address) => addHexPrefix(address)) };
} else {
const decodedDataForWalletCreation = getRawDecoded(
createV1WalletTypes,
getBufferedByteCode(v1CreateWalletMethodId, data)
);
const addresses = decodedDataForWalletCreation[0] as string[];
const saltBuffer = decodedDataForWalletCreation[1];
const salt = bufferToHex(saltBuffer as Buffer);
const paddedAddresses = addresses.map((address) => stripHexPrefix(address.toString()).padStart(40, '0'));
const owners = paddedAddresses.map((address) => addHexPrefix(address));
return {
owners,
salt,
};
}
}
/**
* Decode the given ABI-encoded transfer data and return parsed fields
*
* @param data The data to decode
* @param isFirstSigner whether transaction is being built for a first signer
* @returns parsed transfer data
*/
export function decodeTransferData(data: string, isFirstSigner?: boolean): TransferData {
if (data.startsWith(sendMultisigMethodId)) {
return decodeNativeTransferData(data, isFirstSigner);
} else if (data.startsWith(sendMultisigTokenMethodId)) {
return decodeTokenTransferData(data, isFirstSigner);
} else {
throw new BuildTransactionError(`Invalid transfer bytecode: ${data}`);
}
}
/**
* Decode the given ABI-encoded transfer data for the sendMultisigToken function and return parsed fields
*
* @param data The data to decode
* @param isFirstSigner whether transaction is being built for a first signer
* @returns parsed token transfer data
*/
export function decodeTokenTransferData(data: string, isFirstSigner?: boolean): TokenTransferData {
if (!data.startsWith(sendMultisigTokenMethodId)) {
throw new BuildTransactionError(`Invalid transfer bytecode: ${data}`);
}
let to: RecursiveBufferOrString | undefined;
let amount: RecursiveBufferOrString | undefined;
let tokenContractAddress: RecursiveBufferOrString | undefined;
let expireTime: RecursiveBufferOrString | undefined;
let sequenceId: RecursiveBufferOrString | undefined;
let signature: RecursiveBufferOrString | undefined;
let prefix: RecursiveBufferOrString | undefined;
if (!isFirstSigner) {
[to, amount, tokenContractAddress, expireTime, sequenceId, signature] = getRawDecoded(
sendMultiSigTokenTypes,
getBufferedByteCode(sendMultisigTokenMethodId, data)
);
} else {
[prefix, to, amount, tokenContractAddress, expireTime, sequenceId] = getRawDecoded(
sendMultiSigTokenTypesFirstSigner,
getBufferedByteCode(sendMultisigTokenMethodId, data)
);
}
return {
operationHashPrefix: isFirstSigner ? (prefix as string) : undefined,
to: addHexPrefix(to as string),
amount: new BigNumber(bufferToHex(amount as Buffer)).toFixed(),
expireTime: bufferToInt(expireTime as Buffer),
sequenceId: bufferToInt(sequenceId as Buffer),
signature: bufferToHex(signature as Buffer),
tokenContractAddress: addHexPrefix(tokenContractAddress as string),
};
}
export function decodeERC721TransferData(data: string): ERC721TransferData {
if (!data.startsWith(sendMultisigMethodId)) {
throw new BuildTransactionError(`Invalid transfer bytecode: ${data}`);
}
const [to, amount, internalData, expireTime, sequenceId, signature] = getRawDecoded(
sendMultiSigTypes,
getBufferedByteCode(sendMultisigMethodId, data)
);
const internalDataHex = bufferToHex(internalData as Buffer);
if (!internalDataHex.startsWith(ERC721SafeTransferTypeMethodId)) {
throw new BuildTransactionError(`Invalid transfer bytecode: ${data}`);
}
const [from, receiver, tokenId, userSentData] = getRawDecoded(
ERC721SafeTransferTypes,
getBufferedByteCode(ERC721SafeTransferTypeMethodId, internalDataHex)
);
return {
to: addHexPrefix(receiver as string),
from: addHexPrefix(from as string),
expireTime: bufferToInt(expireTime as Buffer),
amount: new BigNumber(bufferToHex(amount as Buffer)).toFixed(),
tokenId: new BigNumber(bufferToHex(tokenId as Buffer)).toFixed(),
sequenceId: bufferToInt(sequenceId as Buffer),
signature: bufferToHex(signature as Buffer),
tokenContractAddress: addHexPrefix(to as string),
userData: bufferToHex(userSentData as Buffer),
};
}
export function decodeERC1155TransferData(data: string): ERC1155TransferData {
let from, receiver, userSentData;
let tokenIds: string[];
let values: string[];
if (!data.startsWith(sendMultisigMethodId)) {
throw new BuildTransactionError(`Invalid transfer bytecode: ${data}`);
}
const [to, amount, internalData, expireTime, sequenceId, signature] = getRawDecoded(
sendMultiSigTypes,
getBufferedByteCode(sendMultisigMethodId, data)
);
const internalDataHex = bufferToHex(internalData as Buffer);
if (internalDataHex.startsWith(ERC1155SafeTransferTypeMethodId)) {
let tokenId;
let value;
[from, receiver, tokenId, value, userSentData] = getRawDecoded(
ERC1155SafeTransferTypes,
getBufferedByteCode(ERC1155SafeTransferTypeMethodId, internalDataHex)
);
tokenIds = [new BigNumber(bufferToHex(tokenId)).toFixed()];
values = [new BigNumber(bufferToHex(value)).toFixed()];
} else if (bufferToHex(internalData as Buffer).startsWith(ERC1155BatchTransferTypeMethodId)) {
let tempTokenIds, tempValues;
[from, receiver, tempTokenIds, tempValues, userSentData] = getRawDecoded(
ERC1155BatchTransferTypes,
getBufferedByteCode(ERC1155BatchTransferTypeMethodId, internalDataHex)
);
tokenIds = tempTokenIds.map((x) => new BigNumber(bufferToHex(x)).toFixed());
values = tempValues.map((x) => new BigNumber(bufferToHex(x)).toFixed());
} else {
throw new BuildTransactionError(`Invalid transfer bytecode: ${data}`);
}
return {
to: addHexPrefix(receiver),
from: addHexPrefix(from),
expireTime: bufferToInt(expireTime as Buffer),
amount: new BigNumber(bufferToHex(amount as Buffer)).toFixed(),
tokenIds,
values,
sequenceId: bufferToInt(sequenceId as Buffer),
signature: bufferToHex(signature as Buffer),
tokenContractAddress: addHexPrefix(to as string),
userData: userSentData,
};
}
/**
* Decode the given ABI-encoded transfer data for the sendMultisig function and return parsed fields
*
* @param data The data to decode
* @param isFirstSigner whether transaction is being built for a first signer
* @returns parsed transfer data
*/
export function decodeNativeTransferData(data: string, isFirstSigner?: boolean): NativeTransferData {
if (!data.startsWith(sendMultisigMethodId)) {
throw new BuildTransactionError(`Invalid transfer bytecode: ${data}`);
}
let to: RecursiveBufferOrString | undefined;
let amount: RecursiveBufferOrString | undefined;
let internalData: RecursiveBufferOrString | undefined;
let expireTime: RecursiveBufferOrString | undefined;
let sequenceId: RecursiveBufferOrString | undefined;
let signature: RecursiveBufferOrString | undefined;
let prefix: RecursiveBufferOrString | undefined;
if (!isFirstSigner) {
[to, amount, internalData, expireTime, sequenceId, signature] = getRawDecoded(
sendMultiSigTypes,
getBufferedByteCode(sendMultisigMethodId, data)
);
} else {
[prefix, to, amount, internalData, expireTime, sequenceId] = getRawDecoded(
sendMultiSigTypesFirstSigner,
getBufferedByteCode(sendMultisigMethodId, data)
);
}
return {
operationHashPrefix: isFirstSigner ? (prefix as string) : undefined,
to: addHexPrefix(to as string),
amount: new BigNumber(bufferToHex(amount as Buffer)).toFixed(),
expireTime: bufferToInt(expireTime as Buffer),
sequenceId: bufferToInt(sequenceId as Buffer),
signature: bufferToHex(signature as Buffer),
data: bufferToHex(internalData as Buffer),
};
}
/**
* Decode the given ABI-encoded flush tokens data and return parsed fields
*
* @param data The data to decode
* @param to Optional to parameter of tx
* @returns parsed transfer data
*/
export function decodeFlushTokensData(data: string, to?: string): FlushTokensData {
if (data.startsWith(flushForwarderTokensMethodId)) {
const [forwarderAddress, tokenAddress] = getRawDecoded(
flushTokensTypes,
getBufferedByteCode(flushForwarderTokensMethodId, data)
);
return {
forwarderAddress: addHexPrefix(forwarderAddress as string),
tokenAddress: addHexPrefix(tokenAddress as string),
};
} else if (data.startsWith(flushForwarderTokensMethodIdV4)) {
const [tokenAddress] = getRawDecoded(flushTokensTypesv4, getBufferedByteCode(flushForwarderTokensMethodIdV4, data));
if (!to) {
throw new BuildTransactionError(`Missing to address: ${to}`);
}
return {
forwarderAddress: to,
tokenAddress: addHexPrefix(tokenAddress as string),
forwarderVersion: 4,
};
} else {
throw new BuildTransactionError(`Invalid transfer bytecode: ${data}`);
}
}
/**
* Classify the given transaction data based as a transaction type.
* ETH transactions are defined by the first 8 bytes of the transaction data, also known as the method id
*
* @param {string} data The data to classify the transaction with
* @returns {TransactionType} The classified transaction type
*/
export function classifyTransaction(data: string, coinName?: string): TransactionType {
if (data.length < 10) {
// contract calls must have at least 4 bytes (method id) and '0x'
// if it doesn't have enough data to be a contract call it must be a single sig send
return TransactionType.SingleSigSend;
}
// TODO(STLX-1970): validate if we are going to constraint to some methods allowed
const methodId = data.slice(0, 10).toLowerCase();
const isCeloStaking =
CELO_STAKING_METHOD_IDS.has(methodId) && coinName && (coinName === 'celo' || coinName === 'tcelo');
let transactionType = transactionTypesMap[methodId];
if ((!isCeloStaking && CELO_STAKING_METHOD_IDS.has(methodId)) || transactionType === undefined) {
transactionType = TransactionType.ContractCall;
}
return transactionType;
}
const CELO_STAKING_METHOD_IDS = new Set([
LockMethodId,
VoteMethodId,
ActivateMethodId,
UnvoteMethodId,
UnlockMethodId,
WithdrawMethodId,
]);
/**
* A transaction types map according to the starting part of the encoded data
*/
const transactionTypesMap = {
[walletInitializationFirstBytes]: TransactionType.WalletInitialization,
[recoveryWalletInitializationFirstBytes]: TransactionType.RecoveryWalletDeployment,
[v1CreateWalletMethodId]: TransactionType.WalletInitialization,
[createForwarderMethodId]: TransactionType.AddressInitialization,
[v1CreateForwarderMethodId]: TransactionType.AddressInitialization,
[v4CreateForwarderMethodId]: TransactionType.AddressInitialization,
[sendMultisigMethodId]: TransactionType.Send,
[flushForwarderTokensMethodId]: TransactionType.FlushTokens,
[flushForwarderTokensMethodIdV4]: TransactionType.FlushTokens,
[flushCoinsMethodId]: TransactionType.FlushCoins,
[flushERC721ForwarderTokensMethodId]: TransactionType.FlushERC721,
[flushERC721ForwarderTokensMethodIdV4]: TransactionType.FlushERC721,
[flushERC1155ForwarderTokensMethodId]: TransactionType.FlushERC1155,
[flushERC1155ForwarderTokensMethodIdV4]: TransactionType.FlushERC1155,
[sendMultisigTokenMethodId]: TransactionType.Send,
[LockMethodId]: TransactionType.StakingLock,
[VoteMethodId]: TransactionType.StakingVote,
[ActivateMethodId]: TransactionType.StakingActivate,
[UnvoteMethodId]: TransactionType.StakingUnvote,
[UnlockMethodId]: TransactionType.StakingUnlock,
[WithdrawMethodId]: TransactionType.StakingWithdraw,
};
/**
*
* @param {number} num number to be converted to hex
* @returns {string} the hex number
*/
export function numberToHexString(num: number): string {
const hex = num.toString(16);
return hex.length % 2 === 0 ? '0x' + hex : '0x0' + hex;
}
/**
*
* @param {string} hex The hex string to be converted
* @returns {number} the resulting number
*/
export function hexStringToNumber(hex: string): number {
return parseInt(hex.slice(2), 16);
}
/**
* Generates an address of the forwarder address to be deployed
*
* @param {string} contractAddress the address which is creating this new address
* @param {number} contractCounter the nonce of the contract address
* @returns {string} the calculated forwarder contract address
*/
export function calculateForwarderAddress(contractAddress: string, contractCounter: number): string {
const forwarderAddress = generateAddress(
Buffer.from(stripHexPrefix(contractAddress), 'hex'),
Buffer.from(padToEven(stripHexPrefix(numberToHexString(contractCounter))), 'hex')
);
return addHexPrefix(forwarderAddress.toString('hex'));
}
/**
* Calculate the forwarder v1 address that will be generated if `creatorAddress` creates it with salt `salt`
* and initcode `inicode using the create2 opcode
* @param {string} creatorAddress The address that is sending the tx to create a new address, hex string
* @param {string} salt The salt to create the address with using create2, hex string
* @param {string} initcode The initcode that will be deployed to the address, hex string
* @return {string} The calculated address
*/
export function calculateForwarderV1Address(creatorAddress: string, salt: string, initcode: string): string {
const forwarderV1Address = generateAddress2(
Buffer.from(stripHexPrefix(creatorAddress), 'hex'),
Buffer.from(stripHexPrefix(salt), 'hex'),
Buffer.from(padToEven(stripHexPrefix(initcode)), 'hex')
);
return addHexPrefix(forwarderV1Address.toString('hex'));
}
/**
* Take the implementation address for the proxy contract, and get the binary initcode for the associated proxy
* @param {string} implementationAddress The address of the implementation contract for the proxy
* @return {string} Binary hex string of the proxy
*/
export function getProxyInitcode(implementationAddress: string): string {
const target = stripHexPrefix(implementationAddress.toLowerCase()).padStart(40, '0');
// bytecode of the proxy, from:
// https://github.com/BitGo/eth-multisig-v4/blob/d546a937f90f93e83b3423a5bf933d1d77c677c3/contracts/CloneFactory.sol#L42-L56
return `0x3d602d80600a3d3981f3363d3d373d3d3d363d73${target}5af43d82803e903d91602b57fd5bf3`;
}
/**
* Convert the given signature parts to a string representation
*
* @param {SignatureParts} sig The signature to convert to string
* @returns {string} String representation of the signature
*/
export function toStringSig(sig: SignatureParts): string {
return bufferToHex(
Buffer.concat([
setLengthLeft(Buffer.from(stripHexPrefix(sig.r), 'hex'), 32),
setLengthLeft(Buffer.from(stripHexPrefix(sig.s), 'hex'), 32),
toBuffer(sig.v),
])
);
}
/**
* Return whether or not the given tx data has a signature
*
* @param {TxData} txData The transaction data to check for signature
* @returns {boolean} true if the tx has a signature, else false
*/
export function hasSignature(txData: TxData): boolean {
return (
txData.v !== undefined &&
txData.r !== undefined &&
txData.s !== undefined &&
txData.v.length > 0 &&
txData.r.length > 0 &&
txData.s.length > 0
);
}
type RecursiveBufferOrString = string | Buffer | BN | RecursiveBufferOrString[];
/**
* Get the raw data decoded for some types
*
* @param {string[]} types ABI types definition
* @param {Buffer} serializedArgs encoded args
* @returns {Buffer[]} the decoded raw
*/
export function getRawDecoded(types: string[], serializedArgs: Buffer): RecursiveBufferOrString[] {
function normalize(v: unknown, i: number): unknown {
if (BN.isBN(v)) {
return v;
} else if (typeof v === 'string' || Buffer.isBuffer(v)) {
return v;
} else if (Array.isArray(v)) {
return v.map(normalize);
} else {
throw new Error(`For ${types}[${i}] got ${typeof v}`);
}
}
return EthereumAbi.rawDecode(types, serializedArgs).map(normalize);
}
/**
* Get the buffered bytecode from rawData using a methodId as delimiter
*
* @param {string} methodId the hex encoded method Id
* @param {string} rawData the hex encoded raw data
* @returns {Buffer} data buffered bytecode
*/
export function getBufferedByteCode(methodId: string, rawData: string): Buffer {
const splitBytecode = rawData.split(methodId);
if (splitBytecode.length !== 2) {
throw new BuildTransactionError(`Invalid send bytecode: ${rawData}`);
}
if (splitBytecode[1].length % 2 !== 0) {
throw new BuildTransactionError(`Invalid send bytecode: ${rawData} (wrong lenght)`);
}
return Buffer.from(splitBytecode[1], 'hex');
}
/**
* Get the statics coin object matching a given contract address if it exists
*
* @param tokenContractAddress The contract address to match against
* @param network - the coin network
* @param family - the coin family
* @returns statics BaseCoin object for the matching token
*/
export function getToken(
tokenContractAddress: string,
network: BaseNetwork,
family: string
): Readonly<BaseCoin> | undefined {
// filter the coins array to find the token with the matching contract address, network and coin family
// coin family is needed to avoid causing issues when a token has same contract address on two different chains
const tokens = coins.filter((coin) => {
if (coin instanceof ContractAddressDefinedToken) {
return (
coin.network.type === network.type &&
coin.family === family &&
coin.contractAddress.toLowerCase() === tokenContractAddress.toLowerCase()
);
}
return false;
});
// if length of tokens is 1, return the first, else return undefined
// Can't directly index into tokens, or call `length`, so we use map to get an array
const tokensArray = tokens.map((token) => token);
if (tokensArray.length >= 1) {
// there should never be two tokens with the same contract address, so we assert that here
assert(tokensArray.length === 1);
return tokensArray[0];
}
return undefined;
}
/**
* Returns the create wallet method calling data for v1 wallets
*
* @param {string[]} walletOwners - wallet owner addresses for wallet initialization transactions
* @param {string} salt - The salt for wallet initialization transactions
* @returns {string} - the createWallet method encoded
*/
export function getV1WalletInitializationData(walletOwners: string[], salt: string): string {
const saltBuffer = setLengthLeft(toBuffer(salt), 32);
const params = [walletOwners, saltBuffer];
const method = EthereumAbi.methodID('createWallet', createV1WalletTypes);
const args = EthereumAbi.rawEncode(createV1WalletTypes, params);
return addHexPrefix(Buffer.concat([method, args]).toString('hex'));
}
/**
* Returns the create address method calling data for v1, v2, v4 forwarders
*
* @param {string} baseAddress - The address of the wallet contract
* @param {string} salt - The salt for address initialization transactions
* @param {string} feeAddress - The fee address for the enterprise
* @returns {string} - the createForwarder method encoded
*/
export function getV1AddressInitializationData(baseAddress: string, salt: string, feeAddress?: string): string {
const saltBuffer = setLengthLeft(toBuffer(salt), 32);
const { createForwarderParams, createForwarderTypes } = getCreateForwarderParamsAndTypes(
baseAddress,
saltBuffer,
feeAddress
);
const method = EthereumAbi.methodID('createForwarder', createForwarderTypes);
const args = EthereumAbi.rawEncode(createForwarderTypes, createForwarderParams);
return addHexPrefix(Buffer.concat([method, args]).toString('hex'));
}
/**
* Returns the create address method calling data for all forwarder versions
*
* @param {number} forwarderVersion - The version of the forwarder to create
* @param {string} baseAddress - The address of the wallet contract
* @param {string} salt - The salt for address initialization transactions
* @param {string} feeAddress - The fee address for the enterprise
* @returns {string} - the createForwarder method encoded
*
*/
export function getAddressInitDataAllForwarderVersions(
forwarderVersion: number,
baseAddress: string,
salt: string,
feeAddress?: string
): string {
if (forwarderVersion === defaultForwarderVersion) {
return getAddressInitializationData();
} else {
return getV1AddressInitializationData(baseAddress, salt, feeAddress);
}
}
/**
* Returns the createForwarderTypes and createForwarderParams for all forwarder versions
*
* @param {string} baseAddress - The address of the wallet contract
* @param {Buffer} saltBuffer - The salt for address initialization transaction
* @param {string} feeAddress - The fee address for the enterprise
* @returns {createForwarderParams: (string | Buffer)[], createForwarderTypes: string[]}
*/
export function getCreateForwarderParamsAndTypes(
baseAddress: string,
saltBuffer: Buffer,
feeAddress?: string
): { createForwarderParams: (string | Buffer)[]; createForwarderTypes: string[] } {
let createForwarderParams = [baseAddress, saltBuffer];
let createForwarderTypes = createV1ForwarderTypes;
if (feeAddress) {
createForwarderParams = [baseAddress, feeAddress, saltBuffer];
createForwarderTypes = createV4ForwarderTypes;
}
return { createForwarderParams, createForwarderTypes };
}
/**
* Decode the given ABI-encoded create forwarder data and return parsed fields
*
* @param data The data to decode
* @returns parsed transfer data
*/
export function decodeForwarderCreationData(data: string): ForwarderInitializationData {
if (
!(
data.startsWith(v4CreateForwarderMethodId) ||
data.startsWith(v1CreateForwarderMethodId) ||
data.startsWith(createForwarderMethodId)
)
) {
throw new BuildTransactionError(`Invalid address bytecode: ${data}`);
}
if (data.startsWith(createForwarderMethodId)) {
return {
baseAddress: undefined,