-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathutils.ts
More file actions
933 lines (825 loc) · 30.7 KB
/
utils.ts
File metadata and controls
933 lines (825 loc) · 30.7 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
import assert from 'assert';
import * as hex from '@stablelib/hex';
import * as tronweb from 'tronweb';
import { protocol } from '../../resources/protobuf/tron';
import { UtilsError } from '@bitgo/sdk-core';
import { TronErc20Coin, coins } from '@bitgo/statics';
import {
TransferContract,
RawData,
AccountPermissionUpdateContract,
TransactionReceipt,
Permission,
TriggerSmartContract,
FreezeBalanceContractParameter,
VoteWitnessContractParameter,
FreezeContractDecoded,
VoteContractDecoded,
UnfreezeBalanceContractParameter,
WithdrawExpireUnfreezeContractParameter,
UnfreezeContractDecoded,
WithdrawContractDecoded,
ResourceManagementContractParameter,
ResourceManagementContractDecoded,
} from './iface';
import { ContractType, PermissionType, TronResource } from './enum';
import { AbiCoder, hexConcat } from 'ethers/lib/utils';
import { DELEGATION_TYPE_URL } from './constants';
export const TRANSACTION_MAX_EXPIRATION = 86400000; // one day
export const TRANSACTION_DEFAULT_EXPIRATION = 3600000; // one hour
const ADDRESS_PREFIX_REGEX = /^(41)/;
const ADDRESS_PREFIX = '41';
export type BytesLike = number[] | Uint8Array;
const getTronTokens = (network = 'mainnet') => {
return (
coins
.filter((coin) => coin.family === 'trx')
.filter((trx) => trx.network.type === network && trx.isToken) as unknown as TronErc20Coin[]
).map((coins) => coins.contractAddress.toString());
};
export const tokenMainnetContractAddresses = getTronTokens('mainnet');
export const tokenTestnetContractAddresses = getTronTokens('testnet');
/**
* Tron-specific helper functions
*/
export type ByteArray = number[];
export type TronBinaryLike = ByteArray | Buffer | Uint8Array | string;
export const VALID_RESOURCE_TYPES = ['ENERGY', 'BANDWIDTH'];
/**
* @param address
*/
export function isBase58Address(address: string): boolean {
return tronweb.utils.crypto.isAddressValid(address);
}
/**
* @param str
*/
export function getByteArrayFromHexAddress(str: string): ByteArray {
return tronweb.utils.code.hexStr2byteArray(str.replace('0x', ''));
}
/**
* @param arr
*/
export function getHexAddressFromByteArray(arr: ByteArray): string {
return tronweb.utils.code.byteArray2hexStr(arr);
}
/**
* @param messageToVerify
* @param base58Address
* @param sigHex
* @param useTronHeader
*/
export function verifySignature(
messageToVerify: string,
base58Address: string,
sigHex: string,
useTronHeader = true
): boolean {
if (!isValidHex(sigHex)) {
throw new UtilsError('signature is not in a valid format, needs to be hexadecimal');
}
if (!isValidHex(messageToVerify)) {
throw new UtilsError('message is not in a valid format, needs to be hexadecimal');
}
if (!isBase58Address(base58Address)) {
throw new UtilsError('address needs to be base58 encoded');
}
return tronweb.Trx.verifySignature(messageToVerify, base58Address, sigHex, useTronHeader);
}
/**
* @param base58
*/
export function getHexAddressFromBase58Address(base58: string): string {
// pulled from: https://github.com/TRON-US/tronweb/blob/dcb8efa36a5ebb65c4dab3626e90256a453f3b0d/src/utils/help.js#L17
// but they don't surface this call in index.js
const bytes = tronweb.utils.crypto.decodeBase58Address(base58);
// Ensure bytes is a ByteArray (number[])
if (Array.isArray(bytes)) {
return getHexAddressFromByteArray(bytes);
}
throw new UtilsError('Failed to decode base58 address to byte array');
}
/**
* @param privateKey
*/
export function getPubKeyFromPriKey(privateKey: TronBinaryLike): ByteArray {
return tronweb.utils.crypto.getPubKeyFromPriKey(privateKey as BytesLike);
}
/**
* @param privateKey
*/
export function getAddressFromPriKey(privateKey: TronBinaryLike): ByteArray {
return tronweb.utils.crypto.getAddressFromPriKey(privateKey as BytesLike);
}
/**
* @param address
*/
export function getBase58AddressFromByteArray(address: ByteArray): string {
return tronweb.utils.crypto.getBase58CheckAddress(address);
}
/**
* @param hex
*/
export function getBase58AddressFromHex(hex: string): string {
const arr = getByteArrayFromHexAddress(hex);
return getBase58AddressFromByteArray(arr);
}
/**
* @param privateKey
* @param transaction
*/
export function signTransaction(privateKey: string | ByteArray, transaction: TransactionReceipt): TransactionReceipt {
return tronweb.utils.crypto.signTransaction(privateKey, transaction) as TransactionReceipt;
}
/**
* @param message
* @param privateKey
* @param useTronHeader
*/
export function signString(message: string, privateKey: string | ByteArray, useTronHeader = true): string {
return tronweb.Trx.signString(message, privateKey as string, useTronHeader);
}
/**
* @param pubBytes
*/
export function getRawAddressFromPubKey(pubBytes: TronBinaryLike): ByteArray {
return tronweb.utils.crypto.computeAddress(pubBytes as BytesLike);
}
/**
* Decodes a hex encoded transaction in its protobuf representation.
*
* @param hexString raw_data_hex field from tron transactions
*/
export function decodeTransaction(hexString: string): RawData {
const rawTransaction = decodeRawTransaction(hexString);
// there should not be multiple contracts in this data
if (rawTransaction.contracts.length !== 1) {
throw new UtilsError('Number of contracts is greater than 1.');
}
let contract:
| TransferContract[]
| AccountPermissionUpdateContract[]
| TriggerSmartContract[]
| FreezeBalanceContractParameter[]
| VoteWitnessContractParameter[]
| UnfreezeBalanceContractParameter[]
| WithdrawExpireUnfreezeContractParameter[]
| ResourceManagementContractParameter[];
let contractType: ContractType;
// ensure the contract type is supported
switch (rawTransaction.contracts[0].parameter.type_url) {
case 'type.googleapis.com/protocol.TransferContract':
contractType = ContractType.Transfer;
contract = exports.decodeTransferContract(rawTransaction.contracts[0].parameter.value);
break;
case 'type.googleapis.com/protocol.AccountPermissionUpdateContract':
contractType = ContractType.AccountPermissionUpdate;
contract = exports.decodeAccountPermissionUpdateContract(rawTransaction.contracts[0].parameter.value);
break;
case 'type.googleapis.com/protocol.TriggerSmartContract':
contractType = ContractType.TriggerSmartContract;
contract = exports.decodeTriggerSmartContract(rawTransaction.contracts[0].parameter.value);
break;
case 'type.googleapis.com/protocol.FreezeBalanceV2Contract':
contractType = ContractType.FreezeBalanceV2;
contract = decodeFreezeBalanceV2Contract(rawTransaction.contracts[0].parameter.value);
break;
case 'type.googleapis.com/protocol.VoteWitnessContract':
contractType = ContractType.VoteWitness;
contract = decodeVoteWitnessContract(rawTransaction.contracts[0].parameter.value);
break;
case 'type.googleapis.com/protocol.WithdrawExpireUnfreezeContract':
contract = decodeWithdrawExpireUnfreezeContract(rawTransaction.contracts[0].parameter.value);
contractType = ContractType.WithdrawExpireUnfreeze;
break;
case 'type.googleapis.com/protocol.WithdrawBalanceContract':
contract = decodeWithdrawBalanceContract(rawTransaction.contracts[0].parameter.value);
contractType = ContractType.WithdrawBalance;
break;
case 'type.googleapis.com/protocol.UnfreezeBalanceV2Contract':
contract = decodeUnfreezeBalanceV2Contract(rawTransaction.contracts[0].parameter.value);
contractType = ContractType.UnfreezeBalanceV2;
break;
case DELEGATION_TYPE_URL:
contractType = ContractType.DelegateResourceContract;
contract = decodeDelegateResourceContract(rawTransaction.contracts[0].parameter.value);
break;
case 'type.googleapis.com/protocol.UnDelegateResourceContract':
contractType = ContractType.UnDelegateResourceContract;
contract = decodeUnDelegateResourceContract(rawTransaction.contracts[0].parameter.value);
break;
default:
throw new UtilsError('Unsupported contract type');
}
return {
contractType,
contract,
expiration: rawTransaction.expiration,
timestamp: rawTransaction.timestamp,
ref_block_bytes: rawTransaction.blockBytes,
ref_block_hash: rawTransaction.blockHash,
fee_limit: +rawTransaction.feeLimit,
};
}
/**
* Decodes a transaction's raw field from a base64 encoded string. This is a protobuf representation.
*
* @param hexString this is the raw hexadecimal encoded string. Doc found in the following link.
* @example
* @see {@link https://github.com/BitGo/bitgo-account-lib/blob/5f282588701778a4421c75fa61f42713f56e95b9/resources/protobuf/tron.proto#L319}
*/
export function decodeRawTransaction(hexString: string): {
expiration: number;
timestamp: number;
contracts: Array<any>;
blockBytes: string;
blockHash: string;
feeLimit: string;
} {
const bytes = Buffer.from(hexString, 'hex');
let raw;
try {
// we need to decode our raw_data_hex field first
raw = protocol.Transaction.raw.decode(bytes);
} catch (e) {
throw new UtilsError('There was an error decoding the initial raw_data_hex from the serialized tx.');
}
return {
expiration: Number(raw.expiration),
timestamp: Number(raw.timestamp),
contracts: raw.contract,
blockBytes: toHex(raw.refBlockBytes),
feeLimit: raw.feeLimit,
blockHash: toHex(raw.refBlockHash),
};
}
/**
* Converts a base64 encoded string to hex
*
* @param base64 - The base64 encoded string to convert
* @returns {string} - The hex representation
*/
export function getHexFromBase64(base64: string): string {
const buffer = Buffer.from(base64, 'base64');
return buffer.toString('hex');
}
/**
* Indicates whether the passed string is a safe hex string for tron's purposes.
*
* @param hex A valid hex string must be a string made of numbers and characters and has an even length.
*/
export function isValidHex(hex: string): boolean {
return /^(0x)?([0-9a-f]{2})+$/i.test(hex);
}
/** Deserialize the segment of the txHex which corresponds with the details of the transfer
*
* @param transferHex is the value property of the "parameter" field of contractList[0]
* */
export function decodeTransferContract(transferHex: string): TransferContract[] {
const contractBytes = Buffer.from(transferHex, 'base64');
let transferContract;
try {
transferContract = protocol.TransferContract.decode(contractBytes);
} catch (e) {
throw new UtilsError('There was an error decoding the transfer contract in the transaction.');
}
if (!transferContract.ownerAddress) {
throw new UtilsError('Owner address does not exist in this transfer contract.');
}
if (!transferContract.toAddress) {
throw new UtilsError('Destination address does not exist in this transfer contract.');
}
if (!transferContract.hasOwnProperty('amount')) {
throw new UtilsError('Amount does not exist in this transfer contract.');
}
// deserialize attributes
const owner_address = getBase58AddressFromByteArray(
getByteArrayFromHexAddress(Buffer.from(transferContract.ownerAddress, 'base64').toString('hex'))
);
const to_address = getBase58AddressFromByteArray(
getByteArrayFromHexAddress(Buffer.from(transferContract.toAddress, 'base64').toString('hex'))
);
const amount = transferContract.amount;
return [
{
parameter: {
value: {
amount: Number(amount),
owner_address,
to_address,
},
},
},
];
}
/**
* Deserialize the segment of the txHex corresponding with trigger smart contract
*
* @param {string} base64
* @returns {AccountPermissionUpdateContract}
*/
export function decodeTriggerSmartContract(base64: string): TriggerSmartContract[] {
let contractCallDecoded;
try {
contractCallDecoded = protocol.TriggerSmartContract.decode(Buffer.from(base64, 'base64')).toJSON();
} catch (e) {
throw new UtilsError('There was an error decoding the contract call in the transaction.');
}
if (!contractCallDecoded.ownerAddress) {
throw new UtilsError('Owner address does not exist in this contract call.');
}
if (!contractCallDecoded.contractAddress) {
throw new UtilsError('Destination contract address does not exist in this contract call.');
}
if (!contractCallDecoded.data) {
throw new UtilsError('Data does not exist in this contract call.');
}
// deserialize attributes
const owner_address = getBase58AddressFromByteArray(
getByteArrayFromHexAddress(Buffer.from(contractCallDecoded.ownerAddress, 'base64').toString('hex'))
);
const contract_address = getBase58AddressFromByteArray(
getByteArrayFromHexAddress(Buffer.from(contractCallDecoded.contractAddress, 'base64').toString('hex'))
);
const data = contractCallDecoded.data;
return [
{
parameter: {
value: {
data: data,
owner_address,
contract_address,
},
},
},
];
}
/**
* Deserialize the segment of the txHex corresponding with the details of the contract which updates
* account permission
*
* @param {string} base64
* @returns {AccountPermissionUpdateContract}
*/
export function decodeAccountPermissionUpdateContract(base64: string): AccountPermissionUpdateContract {
const accountUpdateContract = protocol.AccountPermissionUpdateContract.decode(Buffer.from(base64, 'base64')).toJSON();
assert(accountUpdateContract.ownerAddress);
assert(accountUpdateContract.owner);
assert(accountUpdateContract.hasOwnProperty('actives'));
const ownerAddress = getBase58AddressFromByteArray(
getByteArrayFromHexAddress(Buffer.from(accountUpdateContract.ownerAddress, 'base64').toString('hex'))
);
const owner: Permission = createPermission(accountUpdateContract.owner);
let witness: Permission | undefined = undefined;
if (accountUpdateContract.witness) {
witness = createPermission(accountUpdateContract.witness);
}
const activeList = accountUpdateContract.actives.map((active) => createPermission(active));
return {
ownerAddress,
owner,
witness,
actives: activeList,
};
}
/**
* Deserialize the segment of the txHex corresponding with freeze balance contract
*
* @param {string} base64 - The base64 encoded contract data
* @returns {FreezeBalanceContractParameter[]} - Array containing the decoded freeze contract
*/
export function decodeFreezeBalanceV2Contract(base64: string): FreezeBalanceContractParameter[] {
let freezeContract: FreezeContractDecoded;
try {
freezeContract = protocol.FreezeBalanceV2Contract.decode(Buffer.from(base64, 'base64')).toJSON();
} catch (e) {
throw new UtilsError('There was an error decoding the freeze contract in the transaction.');
}
if (!freezeContract.ownerAddress) {
throw new UtilsError('Owner address does not exist in this freeze contract.');
}
if (freezeContract.frozenBalance === undefined) {
throw new UtilsError('Frozen balance does not exist in this freeze contract.');
}
const owner_address = getBase58AddressFromByteArray(
getByteArrayFromHexAddress(Buffer.from(freezeContract.ownerAddress, 'base64').toString('hex'))
);
// In protobuf3, default values (BANDWIDTH = 0) may be omitted from serialization.
// If resource is undefined, default to BANDWIDTH.
const resourceValue =
freezeContract.resource === undefined || freezeContract.resource === 'BANDWIDTH'
? TronResource.BANDWIDTH
: TronResource.ENERGY;
return [
{
parameter: {
value: {
resource: resourceValue,
frozen_balance: Number(freezeContract.frozenBalance),
owner_address,
},
},
},
];
}
/**
* Deserialize the segment of the txHex corresponding with vote witness contract
*
* @param {string} base64 - The base64 encoded contract data
* @returns {VoteWitnessContractParameter[]} - Array containing the decoded vote witness contract
*/
export function decodeVoteWitnessContract(base64: string): VoteWitnessContractParameter[] {
let voteContract: VoteContractDecoded;
try {
voteContract = protocol.VoteWitnessContract.decode(Buffer.from(base64, 'base64')).toJSON();
} catch (e) {
throw new UtilsError('There was an error decoding the vote contract in the transaction.');
}
if (!voteContract.ownerAddress) {
throw new UtilsError('Owner address does not exist in this vote contract.');
}
if (!Array.isArray(voteContract.votes) || voteContract.votes.length === 0) {
throw new UtilsError('Votes do not exist or are empty in this vote contract.');
}
// deserialize attributes
const owner_address = getBase58AddressFromByteArray(
getByteArrayFromHexAddress(Buffer.from(voteContract.ownerAddress, 'base64').toString('hex'))
);
interface VoteItem {
voteAddress?: string;
voteCount?: string | number;
}
const votes = voteContract.votes.map((vote: VoteItem) => {
if (!vote.voteAddress) {
throw new UtilsError('Vote address is missing in one of the votes.');
}
return {
vote_address: getBase58AddressFromByteArray(
getByteArrayFromHexAddress(Buffer.from(vote.voteAddress, 'base64').toString('hex'))
),
vote_count: Number(vote.voteCount || 0),
};
});
return [
{
parameter: {
value: {
owner_address,
votes,
},
},
},
];
}
/**
* Deserialize the segment of the txHex corresponding with unfreeze balance contract
*
* @param {string} base64 - The base64 encoded contract data
* @returns {UnfreezeBalanceContractParameter[]} - Array containing the decoded unfreeze contract
*/
export function decodeUnfreezeBalanceV2Contract(base64: string): UnfreezeBalanceContractParameter[] {
let unfreezeContract: UnfreezeContractDecoded;
try {
unfreezeContract = protocol.UnfreezeBalanceV2Contract.decode(Buffer.from(base64, 'base64')).toJSON();
} catch (e) {
throw new UtilsError('There was an error decoding the unfreeze contract in the transaction.');
}
if (!unfreezeContract.ownerAddress) {
throw new UtilsError('Owner address does not exist in this unfreeze contract.');
}
if (unfreezeContract.unfreezeBalance === undefined) {
throw new UtilsError('Unfreeze balance does not exist in this unfreeze contract.');
}
// deserialize attributes
const owner_address = getBase58AddressFromByteArray(
getByteArrayFromHexAddress(Buffer.from(unfreezeContract.ownerAddress, 'base64').toString('hex'))
);
// In protobuf3, default values (BANDWIDTH = 0) may be omitted from serialization.
// If resource is undefined, default to BANDWIDTH.
const resourceValue = unfreezeContract.resource;
const resourceEnum =
resourceValue === undefined || resourceValue === protocol.ResourceCode.BANDWIDTH
? TronResource.BANDWIDTH
: TronResource.ENERGY;
return [
{
parameter: {
value: {
resource: resourceEnum,
unfreeze_balance: Number(unfreezeContract.unfreezeBalance),
owner_address,
},
},
},
];
}
/**
* Deserialize the segment of the txHex corresponding with withdraw balance contract
* Decoded contract is the same as withdraw expire unfreeze
*
* @param {string} base64 - The base64 encoded contract data
* @returns {WithdrawExpireUnfreezeContractParameter[]} - Array containing the decoded withdraw contract
*/
export function decodeWithdrawBalanceContract(base64: string): WithdrawExpireUnfreezeContractParameter[] {
let withdrawContract: WithdrawContractDecoded;
try {
withdrawContract = protocol.WithdrawBalanceContract.decode(Buffer.from(base64, 'base64')).toJSON();
} catch (e) {
throw new UtilsError('There was an error decoding the withdraw contract in the transaction.');
}
if (!withdrawContract.ownerAddress) {
throw new UtilsError('Owner address does not exist in this withdraw contract.');
}
// deserialize attributes
const owner_address = getBase58AddressFromByteArray(
getByteArrayFromHexAddress(Buffer.from(withdrawContract.ownerAddress, 'base64').toString('hex'))
);
return [
{
parameter: {
value: {
owner_address,
},
},
},
];
}
/**
* Deserialize the segment of the txHex corresponding with withdraw expire unfreeze contract
*
* @param {string} base64 - The base64 encoded contract data
* @returns {WithdrawExpireUnfreezeContractParameter[]} - Array containing the decoded withdraw contract
*/
export function decodeWithdrawExpireUnfreezeContract(base64: string): WithdrawExpireUnfreezeContractParameter[] {
let withdrawContract: WithdrawContractDecoded;
try {
withdrawContract = protocol.WithdrawBalanceContract.decode(Buffer.from(base64, 'base64')).toJSON();
} catch (e) {
throw new UtilsError('There was an error decoding the withdraw contract in the transaction.');
}
if (!withdrawContract.ownerAddress) {
throw new UtilsError('Owner address does not exist in this withdraw contract.');
}
// deserialize attributes
const owner_address = getBase58AddressFromByteArray(
getByteArrayFromHexAddress(Buffer.from(withdrawContract.ownerAddress, 'base64').toString('hex'))
);
return [
{
parameter: {
value: {
owner_address,
},
},
},
];
}
/**
* Deserialize the segment of the txHex corresponding with delegate resource contract
*
* @param {string} base64 - The base64 encoded contract data
* @returns {ResourceManagementContractParameter[]} - Array containing the decoded delegate resource contract
*/
export function decodeDelegateResourceContract(base64: string): ResourceManagementContractParameter[] {
let delegateResourceContract: ResourceManagementContractDecoded;
try {
delegateResourceContract = protocol.DelegateResourceContract.decode(Buffer.from(base64, 'base64')).toJSON();
} catch (e) {
throw new UtilsError('There was an error decoding the delegate resource contract in the transaction.');
}
if (!delegateResourceContract.ownerAddress) {
throw new UtilsError('Owner address does not exist in this delegate resource contract.');
}
if (!delegateResourceContract.receiverAddress) {
throw new UtilsError('Receiver address does not exist in this delegate resource contract.');
}
if (delegateResourceContract.balance === undefined) {
throw new UtilsError('Balance does not exist in this delegate resource contract.');
}
const owner_address = getBase58AddressFromByteArray(
getByteArrayFromHexAddress(Buffer.from(delegateResourceContract.ownerAddress, 'base64').toString('hex'))
);
const receiver_address = getBase58AddressFromByteArray(
getByteArrayFromHexAddress(Buffer.from(delegateResourceContract.receiverAddress, 'base64').toString('hex'))
);
// In protobuf3, default values (BANDWIDTH = 0) may be omitted from serialization.
// If resource is undefined or falsy, default to BANDWIDTH.
const resourceValue = !delegateResourceContract.resource ? TronResource.BANDWIDTH : TronResource.ENERGY;
return [
{
parameter: {
value: {
resource: resourceValue,
balance: Number(delegateResourceContract.balance),
owner_address,
receiver_address,
},
},
},
];
}
/**
* Deserialize the segment of the txHex corresponding with undelegate resource contract
*
* @param {string} base64 - The base64 encoded contract data
* @returns {ResourceManagementContractParameter[]} - Array containing the decoded undelegate resource contract
*/
export function decodeUnDelegateResourceContract(base64: string): ResourceManagementContractParameter[] {
let undelegateResourceContract: ResourceManagementContractDecoded;
try {
undelegateResourceContract = protocol.UnDelegateResourceContract.decode(Buffer.from(base64, 'base64')).toJSON();
} catch (e) {
throw new UtilsError('There was an error decoding the delegate resource contract in the transaction.');
}
if (!undelegateResourceContract.ownerAddress) {
throw new UtilsError('Owner address does not exist in this delegate resource contract.');
}
if (!undelegateResourceContract.receiverAddress) {
throw new UtilsError('Receiver address does not exist in this delegate resource contract.');
}
if (undelegateResourceContract.balance === undefined) {
throw new UtilsError('Balance does not exist in this delegate resource contract.');
}
const owner_address = getBase58AddressFromByteArray(
getByteArrayFromHexAddress(Buffer.from(undelegateResourceContract.ownerAddress, 'base64').toString('hex'))
);
const receiver_address = getBase58AddressFromByteArray(
getByteArrayFromHexAddress(Buffer.from(undelegateResourceContract.receiverAddress, 'base64').toString('hex'))
);
// In protobuf3, default values (BANDWIDTH = 0) may be omitted from serialization.
// If resource is undefined or falsy, default to BANDWIDTH.
const resourceValue = !undelegateResourceContract.resource ? TronResource.BANDWIDTH : TronResource.ENERGY;
return [
{
parameter: {
value: {
resource: resourceValue,
balance: Number(undelegateResourceContract.balance),
owner_address,
receiver_address,
},
},
},
];
}
/**
* @param raw
*/
function createPermission(raw: { permissionName: string; threshold: number }): Permission {
let permissionType: PermissionType;
const permission = raw.permissionName.toLowerCase().trim();
if (permission === 'owner') {
permissionType = PermissionType.Owner;
} else if (permission === 'witness') {
permissionType = PermissionType.Witness;
} else if (permission.substr(0, 6) === 'active') {
permissionType = PermissionType.Active;
} else {
throw new UtilsError('Permission type not parseable.');
}
return { type: permissionType, threshold: raw.threshold };
}
/**
* @param rawTransaction
*/
export function isValidTxJsonString(rawTransaction: string): boolean {
const transaction = JSON.parse(rawTransaction);
return transaction.hasOwnProperty('txID');
}
/**
* Returns whether the provided raw transaction accommodates to bitgo's preferred format
*
* @param {any} rawTransaction - The raw transaction to be checked
* @returns {boolean} the validation result
*/
export function isValidRawTransactionFormat(rawTransaction: any): boolean {
if (typeof rawTransaction === 'string' && (isValidHex(rawTransaction) || isValidTxJsonString(rawTransaction))) {
return true;
}
return false;
}
/**
* Returns an hex string of the given buffer
*
* @param {Buffer | Uint8Array} buffer - the buffer to be converted to hex
* @returns {string} - the hex value
*/
export function toHex(buffer: Buffer | Uint8Array): string {
return hex.encode(buffer, true);
}
/**
* Returns a Keccak-256 encoded string of the parameters
*
* @param types - strings describing the types of the values
* @param values - value to encode
* @param methodId - the first 4 bytes of the function selector
*/
export function encodeDataParams(types: string[], values: any[], methodId?: string): string {
types.forEach((type, index) => {
if (type == 'address') {
values[index] = values[index].replace(ADDRESS_PREFIX_REGEX, '0x');
}
});
const abiCoder = new AbiCoder();
let data;
try {
data = abiCoder.encode(types, values);
} catch (e) {
throw new UtilsError(`There was an error encoding the data params. Error = ${JSON.stringify(e)}`);
}
if (methodId) {
return hexConcat([methodId, data]).replace(/^(0x)/, '');
} else {
return data.replace(/^(0x)/, '');
}
}
/**
* Returns the decoded values according to the array of types
*
* @param types - strings describing the types of the values
* @param data - encoded string
*/
export function decodeDataParams(types: string[], data: string): any[] {
const abiCoder = new AbiCoder();
data = '0x' + data.substring(8);
return abiCoder.decode(types, data).reduce((obj, arg, index) => {
if (types[index] == 'address') arg = ADDRESS_PREFIX + arg.substr(2).toLowerCase();
obj.push(arg);
return obj;
}, []);
}
/**
* Generate raw_data_hex for a TRON transaction
*
* @param {Object} rawData - The transaction raw data object containing:
* @param {Array} rawData.contract - Array of contract objects
* @param {string} rawData.refBlockBytes - Reference block bytes
* @param {string} rawData.refBlockHash - Reference block hash
* @param {number} rawData.expiration - Transaction expiration timestamp
* @param {number} rawData.timestamp - Transaction creation timestamp
* @param {number} [rawData.feeLimit] - Optional fee limit for smart contracts
* @returns {string} The hex string representation of the encoded transaction data
*/
export function generateRawDataHex(
rawData: {
contract?: protocol.Transaction.Contract[];
refBlockBytes?: string;
refBlockHash?: string;
expiration?: number;
timestamp?: number;
feeLimit?: number;
} = {}
): string {
try {
// Process contracts to ensure proper protobuf encoding
let processedContracts = rawData.contract;
if (rawData.contract && rawData.contract.length > 0) {
processedContracts = rawData.contract.map((contract) => {
// Handle TransferContract specifically
if (contract.parameter?.type_url === 'type.googleapis.com/protocol.TransferContract') {
const contractValue = contract.parameter.value as any;
// Create the protobuf contract object
const transferContract: any = {};
// Handle owner_address (required field)
if (contractValue.owner_address) {
transferContract.ownerAddress = Buffer.from(contractValue.owner_address, 'hex');
}
// Handle to_address (required field)
if (contractValue.to_address) {
transferContract.toAddress = Buffer.from(contractValue.to_address, 'hex');
}
// Handle amount (required field)
if (contractValue.amount !== undefined) {
transferContract.amount = contractValue.amount;
}
// Encode the contract using protobuf
const encodedContract = protocol.TransferContract.encode(transferContract).finish();
const base64Value = Buffer.from(encodedContract).toString('base64');
return {
...contract,
parameter: {
...contract.parameter,
value: base64Value,
},
} as any;
}
return contract;
}) as protocol.Transaction.Contract[];
}
// Create raw transaction object matching protobuf schema
const rawTx: protocol.Transaction.Iraw = {
contract: processedContracts,
refBlockBytes: rawData.refBlockBytes ? Buffer.from(rawData.refBlockBytes, 'hex') : undefined,
refBlockHash: rawData.refBlockHash ? Buffer.from(rawData.refBlockHash, 'hex') : undefined,
expiration: rawData.expiration,
timestamp: rawData.timestamp,
feeLimit: rawData.feeLimit,
};
// Encode using protobuf and get final bytes
const encodedBytes = protocol.Transaction.raw.encode(rawTx).finish();
// Convert to hex string
return Buffer.from(encodedBytes).toString('hex');
} catch (e) {
throw new UtilsError('Failed to generate raw data hex: ' + e.message);
}
}