-
Notifications
You must be signed in to change notification settings - Fork 101
/
ApiWrapper.java
1468 lines (1251 loc) · 58.3 KB
/
ApiWrapper.java
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
package org.tron.trident.core;
import com.google.protobuf.InvalidProtocolBufferException;
import org.tron.trident.abi.FunctionEncoder;
import org.tron.trident.abi.datatypes.Function;
import org.tron.trident.api.GrpcAPI.BytesMessage;
import org.tron.trident.core.contract.Contract;
import org.tron.trident.core.Constant;
import org.tron.trident.api.WalletGrpc;
import org.tron.trident.api.WalletSolidityGrpc;
import org.tron.trident.core.contract.ContractFunction;
import org.tron.trident.core.exceptions.IllegalException;
import org.tron.trident.core.key.KeyPair;
import org.tron.trident.core.transaction.TransactionBuilder;
import org.tron.trident.crypto.SECP256K1;
import org.tron.trident.proto.Chain.Transaction;
import org.tron.trident.proto.Chain.Block;
import org.tron.trident.proto.Common.SmartContract;
import org.tron.trident.proto.Contract.TransferAssetContract;
import org.tron.trident.proto.Contract.UnfreezeBalanceContract;
import org.tron.trident.proto.Contract.FreezeBalanceContract;
import org.tron.trident.proto.Contract.TransferContract;
import org.tron.trident.proto.Contract.VoteWitnessContract;
import org.tron.trident.proto.Contract.TriggerSmartContract;
import org.tron.trident.proto.Contract.AccountUpdateContract;
import org.tron.trident.proto.Contract.AccountCreateContract;
import org.tron.trident.proto.Contract.AssetIssueContract;
import org.tron.trident.proto.Contract.SetAccountIdContract;
import org.tron.trident.proto.Contract.UpdateAssetContract;
import org.tron.trident.proto.Contract.UpdateBrokerageContract;
import org.tron.trident.proto.Contract.ParticipateAssetIssueContract;
import org.tron.trident.proto.Contract.UnfreezeAssetContract;
import org.tron.trident.proto.Contract.AccountPermissionUpdateContract;
import org.tron.trident.proto.Response.TransactionExtention;
import org.tron.trident.proto.Response.TransactionReturn;
import org.tron.trident.proto.Response.NodeInfo;
import org.tron.trident.proto.Response.WitnessList;
import org.tron.trident.proto.Response.BlockExtention;
import org.tron.trident.proto.Response.BlockListExtention;
import org.tron.trident.proto.Response.Proposal;
import org.tron.trident.proto.Response.Exchange;
import org.tron.trident.proto.Response.DelegatedResourceMessage;
import org.tron.trident.proto.Response.DelegatedResourceList;
import org.tron.trident.proto.Response.DelegatedResourceAccountIndex;
import org.tron.trident.api.GrpcAPI.NumberMessage;
import org.tron.trident.api.GrpcAPI.EmptyMessage;
import org.tron.trident.api.GrpcAPI.AccountAddressMessage;
import org.tron.trident.api.GrpcAPI.AccountIdMessage;
import org.tron.trident.api.GrpcAPI.BlockLimit;
import org.tron.trident.api.GrpcAPI.PaginatedMessage;
import org.tron.trident.utils.Base58Check;
import com.google.protobuf.ByteString;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.Metadata;
import io.grpc.stub.MetadataUtils;
import java.nio.ByteBuffer;
import java.util.*;
import org.tron.trident.crypto.tuwenitypes.Bytes32;
import org.bouncycastle.jcajce.provider.digest.Keccak;
import org.bouncycastle.jcajce.provider.digest.SHA256;
import org.bouncycastle.util.encoders.Hex;
import org.tron.trident.proto.Response.NodeList;
import org.tron.trident.proto.Response.TransactionInfoList;
import org.tron.trident.proto.Response.TransactionInfo;
import org.tron.trident.proto.Response.Account;
import org.tron.trident.proto.Response.AccountResourceMessage;
import org.tron.trident.proto.Response.AccountNetMessage;
import org.tron.trident.proto.Response.ChainParameters;
import org.tron.trident.proto.Response.AssetIssueList;
import org.tron.trident.proto.Response.ProposalList;
import org.tron.trident.proto.Response.ExchangeList;
import org.tron.trident.proto.Response.TransactionSignWeight;
import org.tron.trident.proto.Response.TransactionApprovedList;
import static org.tron.trident.proto.Response.TransactionReturn.response_code.SUCCESS;
/**
* A {@code ApiWrapper} object is the entry point for calling the functions.
*
*<p>A {@code ApiWrapper} object is bind with a private key and a full node.
* {@link #broadcastTransaction}, {@link #signTransaction} and other transaction related
* operations can be done via a {@code ApiWrapper} object.</p>
*
* @since java version 1.8.0_231
* @see org.tron.trident.core.contract.Contract
* @see org.tron.trident.proto.Chain.Transaction
* @see org.tron.trident.proto.Contract
*/
public class ApiWrapper {
public final WalletGrpc.WalletBlockingStub blockingStub;
public final WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity;
public final KeyPair keyPair;
public final ManagedChannel channel;
public final ManagedChannel channelSolidity;
public ApiWrapper(String grpcEndpoint, String grpcEndpointSolidity, String hexPrivateKey) {
channel = ManagedChannelBuilder.forTarget(grpcEndpoint).usePlaintext().build();
channelSolidity = ManagedChannelBuilder.forTarget(grpcEndpointSolidity).usePlaintext().build();
blockingStub = WalletGrpc.newBlockingStub(channel);
blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity);
keyPair = new KeyPair(hexPrivateKey);
}
public ApiWrapper(String grpcEndpoint, String grpcEndpointSolidity, String hexPrivateKey, String apiKey) {
channel = ManagedChannelBuilder.forTarget(grpcEndpoint).usePlaintext().build();
channelSolidity = ManagedChannelBuilder.forTarget(grpcEndpointSolidity).usePlaintext().build();
//attach api key
Metadata header = new Metadata();
Metadata.Key<String> key = Metadata.Key.of("TRON-PRO-API-KEY", Metadata.ASCII_STRING_MARSHALLER);
header.put(key, apiKey);
blockingStub = (WalletGrpc.WalletBlockingStub)MetadataUtils.attachHeaders(WalletGrpc.newBlockingStub(channel), header);
blockingStubSolidity = (WalletSolidityGrpc.WalletSolidityBlockingStub)MetadataUtils.attachHeaders(WalletSolidityGrpc.newBlockingStub(channelSolidity), header);
keyPair = new KeyPair(hexPrivateKey);
}
public void close() {
channel.shutdown();
channelSolidity.shutdown();
}
/*public ApiWrapper(Channel channel, String hexPrivateKey) {
blockingStub = WalletGrpc.newBlockingStub(channel);
blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channel);
keyPair = SECP256K1.KeyPair.create(SECP256K1.PrivateKey.create(Bytes32.fromHexString(hexPrivateKey)));
}*/
/**
* The constuctor for main net. Use TronGrid as default
* @param hexPrivateKey the binding private key. Operations require private key will all use this unless the private key is specified elsewhere.
* @param apiKey this function works with TronGrid, an API key is required.
* @return a ApiWrapper object
*/
public static ApiWrapper ofMainnet(String hexPrivateKey, String apiKey) {
return new ApiWrapper(Constant.TRONGRID_MAIN_NET, Constant.TRONGRID_MAIN_NET_SOLIDITY, hexPrivateKey, apiKey);
}
/**
* The constuctor for main net.
* @deprecated
* This method will only be available before TronGrid prohibits the use without API key
*
* @param hexPrivateKey the binding private key. Operations require private key will all use this unless the private key is specified elsewhere.
* @param apiKey this function works with TronGrid, an API key is required.
* @return a ApiWrapper object
*/
@Deprecated
public static ApiWrapper ofMainnet(String hexPrivateKey) {
return new ApiWrapper(Constant.TRONGRID_MAIN_NET, Constant.TRONGRID_MAIN_NET_SOLIDITY, hexPrivateKey);
}
/**
* The constuctor for Shasta test net. Use TronGrid as default.
* @param hexPrivateKey the binding private key. Operations require private key will all use this unless the private key is specified elsewhere.
* @param apiKey this function works with TronGrid, an API key is required.
* @return a ApiWrapper object
*/
public static ApiWrapper ofShasta(String hexPrivateKey) {
return new ApiWrapper(Constant.TRONGRID_SHASTA, Constant.TRONGRID_SHASTA_SOLIDITY, hexPrivateKey);
}
/**
* The constuctor for Nile test net.
* @param hexPrivateKey the binding private key. Operations require private key will all use this unless the private key is specified elsewhere.
* @return a ApiWrapper object
*/
public static ApiWrapper ofNile(String hexPrivateKey) {
return new ApiWrapper(Constant.FULLNODE_NILE, Constant.FULLNODE_NILE_SOLIDITY, hexPrivateKey);
}
/**
* Generate random address
* @return A list, inside are the public key and private key
*/
public static KeyPair generateAddress() {
// generate random address
return KeyPair.generate();
}
/**
* The function receives addresses in any formats.
* @param address account or contract address in any allowed formats.
* @return hex address
*/
public static ByteString parseAddress(String address) {
byte[] raw;
if (address.startsWith("T")) {
raw = Base58Check.base58ToBytes(address);
} else if (address.startsWith("41")) {
raw = Hex.decode(address);
} else if (address.startsWith("0x")) {
raw = Hex.decode(address.substring(2));
} else {
try {
raw = Hex.decode(address);
} catch (Exception e) {
throw new IllegalArgumentException("Invalid address: " + address);
}
}
return ByteString.copyFrom(raw);
}
public static byte[] calculateTransactionHash (Transaction txn) {
SHA256.Digest digest = new SHA256.Digest();
digest.update(txn.getRawData().toByteArray());
byte[] txid = digest.digest();
return txid;
}
public static ByteString parseHex(String hexString) {
byte[] raw = Hex.decode(hexString);
return ByteString.copyFrom(raw);
}
public static String toHex(byte[] raw) {
return Hex.toHexString(raw);
}
public static String toHex(ByteString raw) {
return Hex.toHexString(raw.toByteArray());
}
public Transaction signTransaction(TransactionExtention txnExt, KeyPair keyPair) {
byte[] txid = txnExt.getTxid().toByteArray();
byte[] signature = KeyPair.signTransaction(txid, keyPair);
Transaction signedTxn =
txnExt.getTransaction().toBuilder().addSignature(ByteString.copyFrom(signature)).build();
return signedTxn;
}
public Transaction signTransaction(Transaction txn, KeyPair keyPair) {
byte[] txid = calculateTransactionHash(txn);
byte[] signature = KeyPair.signTransaction(txid, keyPair);
Transaction signedTxn = txn.toBuilder().addSignature(ByteString.copyFrom(signature)).build();
return signedTxn;
}
public Transaction signTransaction(TransactionExtention txnExt) {
return signTransaction(txnExt, keyPair);
}
public Transaction signTransaction(Transaction txn) {
return signTransaction(txn, keyPair);
}
/**
* Estimate the bandwidth consumption of the transaction.
* Please note that bandwidth estimations are based on signed transactions.
* @param txn the transaction to be estimated.
*/
public long estimateBandwidth(Transaction txn) {
long byteSize = txn.toBuilder().clearRet().build().getSerializedSize() + 64;
return byteSize;
}
/**
* Resolve the result code from TransactionReturn objects.
* @param code the result code.
* @return the corresponding message.
*/
private String resolveResultCode(int code) {
String responseCode = "";
switch (code) {
case 0:
responseCode = "SUCCESS";
case 1:
responseCode = "SIGERROR";
case 2:
responseCode = "CONTRACT_VALIDATE_ERROR";
case 3:
responseCode = "CONTRACT_EXE_ERROR";
case 4:
responseCode = "BANDWITH_ERROR";
case 5:
responseCode = "DUP_TRANSACTION_ERROR";
case 6:
responseCode = "TAPOS_ERROR";
case 7:
responseCode = "TOO_BIG_TRANSACTION_ERROR";
case 8:
responseCode = "TRANSACTION_EXPIRATION_ERROR";
case 9:
responseCode = "SERVER_BUSY";
case 10:
responseCode = "NO_CONNECTION";
case 11:
responseCode = "NOT_ENOUGH_EFFECTIVE_CONNECTION";
case 20:
responseCode = "OTHER_ERROR";
}
return responseCode;
}
/**
* broadcast a transaction with the binding account.
* @param Transaction a signed transaction ready to be broadcasted
* @return a TransactionReturn object contains the broadcasting result
* @throws RuntimeException if broadcastin fails
*/
public String broadcastTransaction(Transaction txn) throws RuntimeException{
TransactionReturn ret = blockingStub.broadcastTransaction(txn);
if (!ret.getResult()) {
String message = resolveResultCode(ret.getCodeValue()) + ", " + ret.getMessage();
throw new RuntimeException(message);
} else {
byte[] txid = calculateTransactionHash(txn);
return ByteString.copyFrom(Hex.encode(txid)).toStringUtf8();
}
}
/**
* Transfer TRX. amount in SUN
* @param fromAddress owner address
* @param toAddress receive balance
* @param amount transfer amount
* @return TransactionExtention
* @throws IllegalException if fail to transfer
*/
public TransactionExtention transfer(String fromAddress, String toAddress, long amount) throws IllegalException {
ByteString rawFrom = parseAddress(fromAddress);
ByteString rawTo = parseAddress(toAddress);
TransferContract req = TransferContract.newBuilder()
.setOwnerAddress(rawFrom)
.setToAddress(rawTo)
.setAmount(amount)
.build();
TransactionExtention txnExt = blockingStub.createTransaction2(req);
if(SUCCESS != txnExt.getResult().getCode()){
throw new IllegalException(txnExt.getResult().getMessage().toStringUtf8());
}
return txnExt;
}
/**
* Transfers TRC10 Asset
* @param fromAddress owner address
* @param toAddress receive balance
* @param tokenId asset name
* @param amount transfer amount
* @return TransactionExtention
* @throws IllegalException if fail to transfer trc10
*/
public TransactionExtention transferTrc10(String fromAddress, String toAddress, int tokenId, long amount) throws IllegalException {
ByteString rawFrom = parseAddress(fromAddress);
ByteString rawTo = parseAddress(toAddress);
byte[] rawTokenId = Integer.toString(tokenId).getBytes();
TransferAssetContract req = TransferAssetContract.newBuilder()
.setOwnerAddress(rawFrom)
.setToAddress(rawTo)
.setAssetName(ByteString.copyFrom(rawTokenId))
.setAmount(amount)
.build();
TransactionExtention txnExt = blockingStub.transferAsset2(req);
if(SUCCESS != txnExt.getResult().getCode()){
throw new IllegalException(txnExt.getResult().getMessage().toStringUtf8());
}
return txnExt;
}
/**
* Freeze balance to get energy or bandwidth, for 3 days
* @param ownerAddress owner address
* @param frozenBalance frozen balance
* @param frozenDuration frozen duration
* @param resourceCode Resource type, can be 0("BANDWIDTH") or 1("ENERGY")
* @return TransactionExtention
* @throws IllegalException if fail to freeze balance
*/
public TransactionExtention freezeBalance(String ownerAddress, long frozenBalance, long frozenDuration, int resourceCode) throws IllegalException {
return freezeBalance(ownerAddress,frozenBalance,frozenDuration,resourceCode,"");
}
/**
* Freeze balance to get energy or bandwidth, for 3 days
* @param ownerAddress owner address
* @param frozenBalance frozen balance
* @param frozenDuration frozen duration
* @param resourceCode Resource type, can be 0("BANDWIDTH") or 1("ENERGY")
* @param receiveAddress the address that will receive the resource, default hexString
* @return TransactionExtention
* @throws IllegalException if fail to freeze balance
*/
public TransactionExtention freezeBalance(String ownerAddress, long frozenBalance, long frozenDuration, int resourceCode, String receiveAddress) throws IllegalException {
ByteString rawFrom = parseAddress(ownerAddress);
ByteString rawReceiveFrom = parseAddress(receiveAddress);
FreezeBalanceContract freezeBalanceContract=
FreezeBalanceContract.newBuilder()
.setOwnerAddress(rawFrom)
.setFrozenBalance(frozenBalance)
.setFrozenDuration(frozenDuration)
.setResourceValue(resourceCode)
.setReceiverAddress(rawReceiveFrom)
.build();
TransactionExtention txnExt = blockingStub.freezeBalance2(freezeBalanceContract);
if(SUCCESS != txnExt.getResult().getCode()){
throw new IllegalException(txnExt.getResult().getMessage().toStringUtf8());
}
return txnExt;
}
/**
* Unfreeze balance to get TRX back
* @param ownerAddress owner address
* @param resourceCode Resource type, can be 0("BANDWIDTH") or 1("ENERGY")
* @return TransactionExtention
* @throws IllegalException if fail to unfreeze balance
*/
public TransactionExtention unfreezeBalance(String ownerAddress, int resourceCode) throws IllegalException {
return unfreezeBalance(ownerAddress,resourceCode,"");
}
/**
* Unfreeze balance to get TRX back
* @param ownerAddress owner address
* @param resourceCode Resource type, can be 0("BANDWIDTH") or 1("ENERGY")
* @param receiveAddress the address that will lose the resource, default hexString
* @return TransactionExtention
* @throws IllegalException if fail to unfreeze balance
*/
public TransactionExtention unfreezeBalance(String ownerAddress, int resourceCode, String receiveAddress) throws IllegalException {
UnfreezeBalanceContract unfreeze =
UnfreezeBalanceContract.newBuilder()
.setOwnerAddress(parseAddress(ownerAddress))
.setResourceValue(resourceCode)
.setReceiverAddress(parseAddress(receiveAddress))
.build();
TransactionExtention txnExt = blockingStub.unfreezeBalance2(unfreeze);
if(SUCCESS != txnExt.getResult().getCode()){
throw new IllegalException(txnExt.getResult().getMessage().toStringUtf8());
}
return txnExt;
}
/**
* Vote for witnesses
* @param ownerAddress owner address
* @param votes <vote address, vote count>
* @return TransactionExtention
* IllegalNumException if fail to vote witness
*/
public TransactionExtention voteWitness(String ownerAddress, HashMap<String, String> votes) throws IllegalException {
ByteString rawFrom = parseAddress(ownerAddress);
VoteWitnessContract voteWitnessContract = createVoteWitnessContract(rawFrom, votes);
TransactionExtention txnExt = blockingStub.voteWitnessAccount2(voteWitnessContract);
if(SUCCESS != txnExt.getResult().getCode()){
throw new IllegalException(txnExt.getResult().getMessage().toStringUtf8());
}
return txnExt;
}
/**
* Create an account. Uses an already activated account to create a new account
* @param ownerAddress owner address, an activated account
* @param accountAddress the address of the new account
* @return TransactionExtention
* IllegalNumException if fail to create account
*/
public TransactionExtention createAccount(String ownerAddress, String accountAddress) throws IllegalException {
ByteString bsOwnerAddress = parseAddress(ownerAddress);
ByteString bsAccountAddress = parseAddress(accountAddress);
AccountCreateContract contract = createAccountCreateContract(bsOwnerAddress,
bsAccountAddress);
TransactionExtention transactionExtention= blockingStub.createAccount2(contract);
if(SUCCESS != transactionExtention.getResult().getCode()){
throw new IllegalException(transactionExtention.getResult().getMessage().toStringUtf8());
}
return transactionExtention;
}
/**
* Modify account name
* @param address owner address
* @param accountName the name of the account
* @return TransactionExtention
* IllegalNumException if fail to update account name
*/
//only if account.getAccountName() == null can update name
public TransactionExtention updateAccount(String address, String accountName) throws IllegalException {
ByteString bsAddress = parseAddress(address);
byte[] bytesAccountName = accountName.getBytes();
ByteString bsAccountName = ByteString.copyFrom(bytesAccountName);
AccountUpdateContract contract = createAccountUpdateContract(bsAccountName,
bsAddress);
TransactionExtention transactionExtention= blockingStub.updateAccount2(contract);
if(SUCCESS != transactionExtention.getResult().getCode()){
throw new IllegalException(transactionExtention.getResult().getMessage().toStringUtf8());
}
return transactionExtention;
}
/**
* Query the latest block information
* @return Block
* @throws IllegalException if fail to get now block
*/
public Block getNowBlock() throws IllegalException {
Block block = blockingStub.getNowBlock(EmptyMessage.newBuilder().build());
if(!block.hasBlockHeader()){
throw new IllegalException("Fail to get latest block.");
}
return block;
}
/**
* Returns the Block Object corresponding to the 'Block Height' specified (number of blocks preceding it)
* @param blockNum The block height
* @return Block
* @throws IllegalException if the parameters are not correct
*/
public Block getBlockByNum(long blockNum) throws IllegalException {
NumberMessage.Builder builder = NumberMessage.newBuilder();
builder.setNum(blockNum);
Block block = blockingStub.getBlockByNum(builder.build());
if(!block.hasBlockHeader()){
throw new IllegalException();
}
return block;
}
/**
* Get some latest blocks
* @param num Number of latest blocks
* @return BlockListExtention
* @throws IllegalException if the parameters are not correct
*/
public BlockListExtention getBlockByLatestNum(long num) throws IllegalException {
NumberMessage numberMessage = NumberMessage.newBuilder().setNum(num).build();
BlockListExtention blockListExtention = blockingStub.getBlockByLatestNum2(numberMessage);
if(blockListExtention.getBlockCount() == 0){
throw new IllegalException("The number of latest blocks must be between 1 and 99, please check it.");
}
return blockListExtention;
}
/**
* Returns the list of Block Objects included in the 'Block Height' range specified
* @param startNum Number of start block height, including this block
* @param endNum Number of end block height, excluding this block
* @return BlockListExtention
* @throws IllegalException if the parameters are not correct
*/
public BlockListExtention getBlockByLimitNext(long startNum, long endNum) throws IllegalException {
BlockLimit blockLimit = BlockLimit.newBuilder()
.setStartNum(startNum)
.setEndNum(endNum)
.build();
BlockListExtention blockListExtention = blockingStub.getBlockByLimitNext2(blockLimit);
if(endNum - startNum > 100){
throw new IllegalException("The difference between startNum and endNum cannot be greater than 100, please check it.");
}
if(blockListExtention.getBlockCount() == 0){
throw new IllegalException();
}
return blockListExtention;
}
/**
* Get current API node’ info
* @return NodeInfo
* @throws IllegalException if fail to get nodeInfo
*/
public NodeInfo getNodeInfo() throws IllegalException {
NodeInfo nodeInfo = blockingStub.getNodeInfo(EmptyMessage.newBuilder().build());
if(nodeInfo.getBlock().isEmpty()){
throw new IllegalException("Fail to get node info.");
}
return nodeInfo;
}
/**
* List all nodes that current API node is connected to
* @return NodeList
* @throws IllegalException if fail to get node list
*/
public NodeList listNodes() throws IllegalException {
NodeList nodeList = blockingStub.listNodes(EmptyMessage.newBuilder().build());
if(nodeList.getNodesCount() == 0){
throw new IllegalException("Fail to get node list.");
}
return nodeList;
}
/**
* Get transactionInfo from block number
* @param blockNum The block height
* @return TransactionInfoList
* @throws IllegalException no transactions or the blockNum is incorrect
*/
public TransactionInfoList getTransactionInfoByBlockNum(long blockNum) throws IllegalException {
NumberMessage numberMessage = NumberMessage.newBuilder().setNum(blockNum).build();
TransactionInfoList transactionInfoList = blockingStub.getTransactionInfoByBlockNum(numberMessage);
if(transactionInfoList.getTransactionInfoCount() == 0){
throw new IllegalException("no transactions or the blockNum is incorrect.");
}
return transactionInfoList;
}
/**
* Query the transaction fee, block height by transaction id
* @param txID Transaction hash, i.e. transaction id
* @return TransactionInfo
* @throws IllegalException if the parameters are not correct
*/
public TransactionInfo getTransactionInfoById(String txID) throws IllegalException {
ByteString bsTxid = parseAddress(txID);
BytesMessage request = BytesMessage.newBuilder()
.setValue(bsTxid)
.build();
TransactionInfo transactionInfo = blockingStub.getTransactionInfoById(request);
if(transactionInfo.getBlockTimeStamp() == 0){
throw new IllegalException();
}
return transactionInfo;
}
/**
* Query transaction information by transaction id
* @param txID Transaction hash, i.e. transaction id
* @return Transaction
* @throws IllegalException if the parameters are not correct
*/
public Transaction getTransactionById(String txID) throws IllegalException {
ByteString bsTxid = parseAddress(txID);
BytesMessage request = BytesMessage.newBuilder()
.setValue(bsTxid)
.build();
Transaction transaction = blockingStub.getTransactionById(request);
if(transaction.getRetCount() == 0){
throw new IllegalException();
}
return transaction;
}
/**
* Get account info by address
* @param address address, default hexString
* @return Account
*/
public Account getAccount(String address) {
ByteString bsAddress = parseAddress(address);
AccountAddressMessage accountAddressMessage = AccountAddressMessage.newBuilder()
.setAddress(bsAddress)
.build();
Account account = blockingStub.getAccount(accountAddressMessage);
return account;
}
/**
* Query the resource information of an account(bandwidth,energy,etc)
* @param address address, default hexString
* @return AccountResourceMessage
*/
public AccountResourceMessage getAccountResource(String address) {
ByteString bsAddress = parseAddress(address);
AccountAddressMessage account = AccountAddressMessage.newBuilder()
.setAddress(bsAddress)
.build();
return blockingStub.getAccountResource(account);
}
/**
* Query bandwidth information
* @param address address, default hexString
* @return AccountResourceMessage
*/
public AccountNetMessage getAccountNet(String address) {
ByteString bsAddress = parseAddress(address);
AccountAddressMessage account = AccountAddressMessage.newBuilder()
.setAddress(bsAddress)
.build();
return blockingStub.getAccountNet(account);
}
public long getAccountBalance(String address) {
Account account = getAccount(address);
long balance = account.getBalance();
return balance;
}
public Account getAccountById(String id) {
ByteString bsId = ByteString.copyFrom(id.getBytes());
AccountIdMessage accountId = AccountIdMessage.newBuilder()
.setId(bsId)
.build();
return blockingStub.getAccountById(accountId);
}
public Transaction setAccountId(String id, String address) throws IllegalException {
ByteString bsId = ByteString.copyFrom(id.getBytes());
ByteString bsAddress = parseAddress(address);
SetAccountIdContract contract = createSetAccountIdContract(bsId, bsAddress);
Transaction transaction= blockingStub.setAccountId(contract);
return transaction;
}
/**
* All parameters that the blockchain committee can set
* @return ChainParameters
* @throws IllegalException if fail to get chain parameters
*/
public ChainParameters getChainParameters() throws IllegalException {
ChainParameters chainParameters = blockingStub.getChainParameters(EmptyMessage.newBuilder().build());
if(chainParameters.getChainParameterCount() == 0){
throw new IllegalException("Fail to get chain parameters.");
}
return chainParameters;
}
/**
* Returns all resources delegations from an account to another account. The fromAddress can be retrieved from the GetDelegatedResourceAccountIndex API
* @param fromAddress energy from address,, default hexString
* @param toAddress energy delegation information, default hexString
* @return DelegatedResourceList
*/
public DelegatedResourceList getDelegatedResource(String fromAddress,
String toAddress) {
ByteString fromAddressBS = parseAddress(fromAddress);
ByteString toAddressBS = parseAddress(toAddress);
DelegatedResourceMessage request = DelegatedResourceMessage.newBuilder()
.setFromAddress(fromAddressBS)
.setToAddress(toAddressBS)
.build();
DelegatedResourceList delegatedResource = blockingStub.getDelegatedResource(request);
return delegatedResource;
}
/**
* Query the energy delegation by an account. i.e. list all addresses that have delegated resources to an account
* @param address address,, default hexString
* @return DelegatedResourceAccountIndex
*/
public DelegatedResourceAccountIndex getDelegatedResourceAccountIndex(String address) {
ByteString addressBS = parseAddress(address);
BytesMessage bytesMessage = BytesMessage.newBuilder()
.setValue(addressBS)
.build();
DelegatedResourceAccountIndex accountIndex = blockingStub.getDelegatedResourceAccountIndex(bytesMessage);
return accountIndex;
}
/**
* Query the list of all the TRC10 tokens
* @return AssetIssueList
*/
public AssetIssueList getAssetIssueList() {
AssetIssueList assetIssueList = blockingStub.getAssetIssueList(EmptyMessage.newBuilder().build());
return assetIssueList;
}
/**
* Query the list of all the tokens by pagination.
* @param offset the index of the start token
* @param limit the amount of tokens per page
* @return AssetIssueList, a list of Tokens that succeed the Token located at offset
*/
public AssetIssueList getPaginatedAssetIssueList(long offset, long limit) {
PaginatedMessage pageMessage = PaginatedMessage.newBuilder()
.setOffset(offset)
.setLimit(limit)
.build();
AssetIssueList assetIssueList = blockingStub.getPaginatedAssetIssueList(pageMessage);
return assetIssueList;
}
/**
* Query the TRC10 token information issued by an account
* @param address the Token Issuer account address
* @return AssetIssueList, a list of Tokens that succeed the Token located at offset
*/
public AssetIssueList getAssetIssueByAccount(String address) {
ByteString addressBS = parseAddress(address);
AccountAddressMessage request = AccountAddressMessage.newBuilder()
.setAddress(addressBS)
.build();
AssetIssueList assetIssueList = blockingStub.getAssetIssueByAccount(request);
return assetIssueList;
}
/**
* Query a token by token id
* @param assetId the ID of the TRC10 token
* @return AssetIssueContract, the token object, which contains the token name
*/
public AssetIssueContract getAssetIssueById(String assetId) {
ByteString assetIdBs = ByteString.copyFrom(assetId.getBytes());
BytesMessage request = BytesMessage.newBuilder()
.setValue(assetIdBs)
.build();
AssetIssueContract assetIssueContract = blockingStub.getAssetIssueById(request);
return assetIssueContract;
}
/**
* Query a token by token name
* @param name the name of the TRC10 token
* @return AssetIssueContract, the token object, which contains the token name
*/
public AssetIssueContract getAssetIssueByName(String name) {
ByteString assetNameBs = ByteString.copyFrom(name.getBytes());
BytesMessage request = BytesMessage.newBuilder()
.setValue(assetNameBs)
.build();
AssetIssueContract assetIssueContract = blockingStub.getAssetIssueByName(request);
return assetIssueContract;
}
/**
* Query the list of all the TRC10 tokens by token name
* @param name the name of the TRC10 token
* @return AssetIssueList
*/
public AssetIssueList getAssetIssueListByName(String name) {
ByteString assetNameBs = ByteString.copyFrom(name.getBytes());
BytesMessage request = BytesMessage.newBuilder()
.setValue(assetNameBs)
.build();
AssetIssueList assetIssueList = blockingStub.getAssetIssueListByName(request);
return assetIssueList;
}
/**
* Participate a token
* @param toAddress the issuer address of the token, default hexString
* @param ownerAddress the participant address, default hexString
* @param assertName token id, default hexString
* @param amount participate token amount
* @return TransactionExtention
* @throws IllegalException if fail to participate AssetIssue
*/
public TransactionExtention participateAssetIssue(String toAddress, String ownerAddress, String assertName, long amount) throws IllegalException {
ByteString bsTo = parseAddress(toAddress);
ByteString bsOwner = parseAddress(ownerAddress);
ByteString bsName = ByteString.copyFrom(assertName.getBytes());
ParticipateAssetIssueContract builder = ParticipateAssetIssueContract.newBuilder()
.setToAddress(bsTo)
.setAssetName(bsName)
.setOwnerAddress(bsOwner)
.setAmount(amount)
.build();
TransactionExtention transactionExtention = blockingStub.participateAssetIssue2(builder);
if(SUCCESS != transactionExtention.getResult().getCode()){
throw new IllegalException(transactionExtention.getResult().getMessage().toStringUtf8());
}
return transactionExtention;
}
/**
* List all proposals
* @return ProposalList
*/
public ProposalList listProposals() {
ProposalList proposalList = blockingStub.listProposals(EmptyMessage.newBuilder().build());
return proposalList;
}
/**
* Query proposal based on ID
* @param id proposal id
* @return Proposal, proposal details
* @throws IllegalException if fail to get proposal
*/
//1-17
public Proposal getProposalById(String id) throws IllegalException {
ByteString bsTxid = ByteString.copyFrom(ByteBuffer.allocate(8).putLong(Long.parseLong(id)).array());
BytesMessage request = BytesMessage.newBuilder()
.setValue(bsTxid)
.build();
Proposal proposal = blockingStub.getProposalById(request);
if(proposal.getApprovalsCount() == 0){
throw new IllegalException();
}
return proposal;
}
/**
* List all witnesses that current API node is connected to
* @return WitnessList
*/
public WitnessList listWitnesses() {
WitnessList witnessList = blockingStub
.listWitnesses(EmptyMessage.newBuilder().build());
return witnessList;
}
/**
* List all exchange pairs
* @return ExchangeList
*/
public ExchangeList listExchanges() {
ExchangeList exchangeList = blockingStub
.listExchanges(EmptyMessage.newBuilder().build());
return exchangeList;
}
/**
* Query exchange pair based on id
* @param id transaction pair id
* @return Exchange
* @throws IllegalException if fail to get exchange pair
*/
public Exchange getExchangeById(String id) throws IllegalException {
ByteString bsTxid = ByteString.copyFrom(ByteBuffer.allocate(8).putLong(Long.parseLong(id)).array());
BytesMessage request = BytesMessage.newBuilder()
.setValue(bsTxid)
.build();
Exchange exchange = blockingStub.getExchangeById(request);
if(exchange.getSerializedSize() == 0){
throw new IllegalException();
}
return exchange;
}
/**
* Issue a token
* @param ownerAddress Owner address, default hexString
* @param name Token name, default hexString
* @param abbr Token name abbreviation, default hexString
* @param totalSupply Token total supply
* @param trxNum Define the price by the ratio of trx_num/num
* @param icoNum Define the price by the ratio of trx_num/num
* @param startTime ICO start time
* @param endTime ICO end time
* @param url Token official website url, default hexString
* @param freeAssetNetLimit Token free asset net limit
* @param publicFreeAssetNetLimit Token public free asset net limit
* @param precision