-
Notifications
You must be signed in to change notification settings - Fork 28
/
client.go
1524 lines (1280 loc) · 48.8 KB
/
client.go
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
// Copyright 2019 Conflux Foundation. All rights reserved.
// Conflux is free software and distributed under GNU General Public License.
// See http://www.gnu.org/licenses/
package sdk
import (
"context"
"fmt"
"io"
"sync/atomic"
"math/big"
"reflect"
"time"
"github.com/Conflux-Chain/go-conflux-sdk/constants"
"github.com/Conflux-Chain/go-conflux-sdk/types"
"github.com/Conflux-Chain/go-conflux-sdk/types/cfxaddress"
sdkerrors "github.com/Conflux-Chain/go-conflux-sdk/types/errors"
postypes "github.com/Conflux-Chain/go-conflux-sdk/types/pos"
"github.com/mcuadros/go-defaults"
rpc "github.com/openweb3/go-rpc-provider"
"github.com/openweb3/go-rpc-provider/interfaces"
providers "github.com/openweb3/go-rpc-provider/provider_wrapper"
"github.com/Conflux-Chain/go-conflux-sdk/utils"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/pkg/errors"
)
const errMsgApplyTxValues = "failed to apply default transaction values"
// Client represents a client to interact with Conflux blockchain.
type Client struct {
*providers.MiddlewarableProvider
AccountManager AccountManagerOperator
nodeURL string
networkID *uint32
chainID *uint32
option ClientOption
context context.Context
RpcTraceClient
rpcPosClient RpcPosClient
rpcTxpoolClient RpcTxpoolClient
rpcDebugClient RpcDebugClient
rpcFilterClient RpcFilterClient
}
// ClientOption for set keystore path and flags for retry and timeout
//
// The simplest way to set logger is to use the types.DefaultCallRpcLog and types.DefaultBatchCallRPCLog
type ClientOption struct {
KeystorePath string
// retry
RetryCount int
RetryInterval time.Duration `default:"1s"`
// timeout of request
RequestTimeout time.Duration `default:"30s"`
// Maximum number of connections may be established. The default value is 512. It's only useful for http(s) prococal
MaxConnectionPerHost int
Logger io.Writer
CircuitBreakerOption *providers.DefaultCircuitBreakerOption
}
// NewClient creates an instance of Client with specified conflux node url, it will creat account manager if option.KeystorePath not empty.
//
// client, err := sdk.NewClient("https://test.confluxrpc.com", sdk.ClientOption{
// KeystorePath: "your keystore folder path",
// RetryCount : 3,
// })
// // query rpc
// epoch, err := client.GetEpochNumber()
// if err != nil {
// panic(err)
// }
// // send transaction
// chainID, err := client.GetNetworkID()
// if err!=nil {
// panic(err)
// }
// from, err :=client.AccountManger().GetDefault()
// if err!=nil {
// panic(err)
// }
// utx, err := client.CreateUnsignedTransaction(*from, cfxaddress.MustNewFromHex("0x1cad0b19bb29d4674531d6f115237e16afce377d", chainID), types.NewBigInt(1), nil)
// if err!=nil {
// panic(err)
// }
// txhash, err := client.SendTransaction(utx)
func NewClient(nodeURL string, option ...ClientOption) (*Client, error) {
realOption := ClientOption{}
if len(option) > 0 {
realOption = option[0]
}
client, err := newClientWithOption(nodeURL, realOption)
if err != nil {
return nil, errors.Wrap(err, "failed to new client with retry")
}
return client, nil
}
// MustNewClient same to NewClient but panic if failed
func MustNewClient(nodeURL string, option ...ClientOption) *Client {
client, err := NewClient(nodeURL, option...)
if err != nil {
panic(err)
}
return client
}
// @deperacated use NewClientWithProvider instead
// NewClientWithRPCRequester creates client with specified rpcRequester
func NewClientWithRPCRequester(provider RpcRequester) (*Client, error) {
return NewClientWithProvider(provider)
}
// NewClientWithProvider creates an instance of Client with specified provider, and will wrap it to create a MiddlewarableProvider for be able to hooking CallContext/BatchCallContext/Subscribe
func NewClientWithProvider(provider interfaces.Provider) (*Client, error) {
return &Client{
MiddlewarableProvider: providers.NewMiddlewarableProvider(provider),
}, nil
}
// NewClientWithRetry creates a retryable new instance of Client with specified conflux node url and retry options.
//
// the clientOption.RetryInterval will be set to 1 second if pass 0
func newClientWithOption(nodeURL string, clientOption ClientOption) (*Client, error) {
var client Client
defaults.SetDefaults(&clientOption)
client.nodeURL = nodeURL
client.option = clientOption
client.rpcPosClient = RpcPosClient{&client}
client.rpcTxpoolClient = RpcTxpoolClient{&client}
client.rpcDebugClient = RpcDebugClient{&client}
client.rpcFilterClient = RpcFilterClient{&client}
client.RpcTraceClient = RpcTraceClient{&client}
p, err := providers.NewProviderWithOption(nodeURL, *clientOption.genProviderOption())
if err != nil {
return nil, errors.Wrap(err, "failed to new provider")
}
client.MiddlewarableProvider = p
_, err = client.GetNetworkID()
if err != nil {
return nil, errors.Wrap(err, "failed to get networkID")
}
if client.option.KeystorePath != "" {
am := NewAccountManager(client.option.KeystorePath, *client.networkID)
client.SetAccountManager(am)
}
_, err = client.GetChainID()
if err != nil {
return nil, errors.Wrap(err, "failed to get chainID")
}
return &client, nil
}
// WithContext creates a new Client with specified context
func (client *Client) WithContext(ctx context.Context) *Client {
_client := *client
_client.context = ctx
return &_client
}
func (client *Client) getContext() context.Context {
if client.context == nil {
return context.Background()
}
return client.context
}
// Provider returns the middlewarable provider
func (client *Client) Provider() *providers.MiddlewarableProvider {
return client.MiddlewarableProvider
}
// Pos returns RpcPosClient for invoke rpc with pos namespace
func (client *Client) Pos() RpcPos {
return &client.rpcPosClient
}
// TxPool returns RpcTxPoolClient for invoke rpc with txpool namespace
func (client *Client) TxPool() RpcTxpool {
return &client.rpcTxpoolClient
}
// Debug returns RpcDebugClient for invoke rpc with debug namespace
func (client *Client) Debug() RpcDebug {
return &client.rpcDebugClient
}
func (client *Client) Filter() RpcFilter {
return &client.rpcFilterClient
}
func (client *Client) Trace() RpcTrace {
return &client.RpcTraceClient
}
// GetNodeURL returns node url
func (client *Client) GetNodeURL() string {
return client.nodeURL
}
// GetAccountManager returns account manager of client
func (client *Client) GetAccountManager() AccountManagerOperator {
return client.AccountManager
}
func (client *Client) SetNetworkId(networkId uint32) {
client.networkID = &networkId
}
func (client *Client) SetChainId(chainId uint32) {
client.chainID = &chainId
}
// NewAddress create conflux address by base32 string or hex40 string, if base32OrHex is base32 and networkID is passed it will create cfx Address use networkID of current client.
func (client *Client) NewAddress(base32OrHex string) (types.Address, error) {
networkID, err := client.GetNetworkID()
if err != nil {
return types.Address{}, err
}
return cfxaddress.New(base32OrHex, networkID)
}
// MustNewAddress create conflux address by base32 string or hex40 string, if base32OrHex is base32 and networkID is passed it will create cfx Address use networkID of current client.
// it will painc if error occured.
func (client *Client) MustNewAddress(base32OrHex string) types.Address {
address, err := client.NewAddress(base32OrHex)
if err != nil {
panic(err)
}
return address
}
// CallRPC performs a JSON-RPC call with the given arguments and unmarshals into
// result if no error occurred.
//
// The result must be a pointer so that package json can unmarshal into it. You
// can also pass nil, in which case the result is ignored.
//
// You could use UseCallRpcMiddleware to add middleware for hooking CallRPC
func (client *Client) CallRPC(result interface{}, method string, args ...interface{}) error {
return client.MiddlewarableProvider.CallContext(client.getContext(), result, method, args...)
}
// BatchCallRPC sends all given requests as a single batch and waits for the server
// to return a response for all of them.
//
// In contrast to Call, BatchCall only returns I/O errors. Any error specific to
// a request is reported through the Error field of the corresponding BatchElem.
//
// Note that batch calls may not be executed atomically on the server side.
//
// You could use UseBatchCallRpcMiddleware to add middleware for hooking BatchCallRPC
func (client *Client) BatchCallRPC(b []rpc.BatchElem) error {
err := client.MiddlewarableProvider.BatchCallContext(client.getContext(), b)
if err != nil {
return err
}
for i := range b {
if rpcErr, err2 := utils.ToRpcError(b[i].Error); err2 == nil {
b[i].Error = rpcErr
}
}
return nil
}
// func (client *Client) coreBatchCallContext(ctx context.Context, b []rpc.BatchElem) error {
// err := client.rpcRequester.BatchCallContext(ctx, b)
// if err != nil {
// return err
// }
// for i := range b {
// if rpcErr, err2 := utils.ToRpcError(b[i].Error); err2 == nil {
// b[i].Error = rpcErr
// }
// }
// return nil
// }
// SetAccountManager sets account manager for sign transaction
func (client *Client) SetAccountManager(accountManager AccountManagerOperator) {
client.AccountManager = accountManager
}
// GetGasPrice returns the recent mean gas price.
func (client *Client) GetGasPrice() (gasPrice *hexutil.Big, err error) {
err = client.wrappedCallRPC(&gasPrice, "cfx_gasPrice")
return
}
// GetNextNonce returns the next transaction nonce of address
func (client *Client) GetNextNonce(address types.Address, epoch ...*types.EpochOrBlockHash) (nonce *hexutil.Big, err error) {
realEpoch := get1stEpochOrBlockhashIfy(epoch)
err = client.wrappedCallRPC(&nonce, "cfx_getNextNonce", address, realEpoch)
return
}
// GetStatus returns status of connecting conflux node
func (client *Client) GetStatus() (status types.Status, err error) {
err = client.wrappedCallRPC(&status, "cfx_getStatus")
return
}
// GetNetworkID returns networkID of connecting conflux node
func (client *Client) GetNetworkID() (uint32, error) {
if client.networkID != nil {
return *client.networkID, nil
}
status, err := client.GetStatus()
if err != nil {
return 0, errors.Wrap(err, "failed to get status")
}
client.networkID = new(uint32)
atomic.StoreUint32(client.networkID, uint32(status.NetworkID))
return *client.networkID, nil
}
// GetNetworkIDCached returns chached networkID created when new client
func (client *Client) GetNetworkIDCached() uint32 {
return *client.networkID
}
// GetNetworkID returns networkID of connecting conflux node
func (client *Client) GetChainID() (uint32, error) {
if client.chainID != nil {
return *client.chainID, nil
}
status, err := client.GetStatus()
if err != nil {
return 0, errors.Wrap(err, "failed to get status")
}
client.chainID = new(uint32)
atomic.StoreUint32(client.chainID, uint32(status.ChainID))
return *client.chainID, nil
}
// GetChainIDCached returns chached networkID created when new client
func (client *Client) GetChainIDCached() uint32 {
return *client.chainID
}
// GetEpochNumber returns the highest or specified epoch number.
func (client *Client) GetEpochNumber(epoch ...*types.Epoch) (epochNumber *hexutil.Big, err error) {
realEpoch := get1stEpochIfy(epoch)
err = client.wrappedCallRPC(&epochNumber, "cfx_epochNumber", realEpoch)
if err != nil {
epochNumber = nil
}
return
}
// GetBalance returns the balance of specified address at epoch.
func (client *Client) GetBalance(address types.Address, epoch ...*types.EpochOrBlockHash) (balance *hexutil.Big, err error) {
realEpoch := get1stEpochOrBlockhashIfy(epoch)
err = client.wrappedCallRPC(&balance, "cfx_getBalance", address, realEpoch)
if err != nil {
balance = nil
}
return
}
// GetCode returns the bytecode in HEX format of specified address at epoch.
func (client *Client) GetCode(address types.Address, epoch ...*types.EpochOrBlockHash) (code hexutil.Bytes, err error) {
realEpoch := get1stEpochOrBlockhashIfy(epoch)
err = client.wrappedCallRPC(&code, "cfx_getCode", address, realEpoch)
return
}
// GetBlockSummaryByHash returns the block summary of specified blockHash
// If the block is not found, return nil.
func (client *Client) GetBlockSummaryByHash(blockHash types.Hash) (blockSummary *types.BlockSummary, err error) {
err = client.wrappedCallRPC(&blockSummary, "cfx_getBlockByHash", blockHash, false)
return
}
// GetBlockByHash returns the block of specified blockHash
// If the block is not found, return nil.
func (client *Client) GetBlockByHash(blockHash types.Hash) (block *types.Block, err error) {
err = client.wrappedCallRPC(&block, "cfx_getBlockByHash", blockHash, true)
return
}
// GetBlockSummaryByEpoch returns the block summary of specified epoch.
// If the epoch is invalid, return the concrete error.
func (client *Client) GetBlockSummaryByEpoch(epoch *types.Epoch) (blockSummary *types.BlockSummary, err error) {
err = client.wrappedCallRPC(&blockSummary, "cfx_getBlockByEpochNumber", epoch, false)
return
}
// GetBlockByHash returns the block of specified block number
func (client *Client) GetBlockByBlockNumber(blockNumer hexutil.Uint64) (block *types.Block, err error) {
err = client.wrappedCallRPC(&block, "cfx_getBlockByBlockNumber", blockNumer, true)
return
}
// GetBlockSummaryByBlockNumber returns the block summary of specified block number.
func (client *Client) GetBlockSummaryByBlockNumber(blockNumer hexutil.Uint64) (block *types.BlockSummary, err error) {
err = client.wrappedCallRPC(&block, "cfx_getBlockByBlockNumber", blockNumer, false)
return
}
// GetBlockByEpoch returns the block of specified epoch.
// If the epoch is invalid, return the concrete error.
func (client *Client) GetBlockByEpoch(epoch *types.Epoch) (block *types.Block, err error) {
err = client.wrappedCallRPC(&block, "cfx_getBlockByEpochNumber", epoch, true)
return
}
// GetBestBlockHash returns the current best block hash.
func (client *Client) GetBestBlockHash() (hash types.Hash, err error) {
err = client.wrappedCallRPC(&hash, "cfx_getBestBlockHash")
return
}
// GetRawBlockConfirmationRisk indicates the risk coefficient that
// the pivot block of the epoch where the block is located becomes a normal block.
// It will return nil if block not exist
func (client *Client) GetRawBlockConfirmationRisk(blockhash types.Hash) (risk *hexutil.Big, err error) {
err = client.wrappedCallRPC(&risk, "cfx_getConfirmationRiskByHash", blockhash)
return
}
// GetBlockConfirmationRisk indicates the probability that
// the pivot block of the epoch where the block is located becomes a normal block.
//
// it's (raw confirmation risk coefficient/ (2^256-1))
func (client *Client) GetBlockConfirmationRisk(blockHash types.Hash) (*big.Float, error) {
risk, err := client.GetRawBlockConfirmationRisk(blockHash)
if err != nil {
return nil, errors.Wrapf(err, "failed to cfx_getConfirmationRiskByHash %v", blockHash)
}
if risk == nil {
return nil, nil
}
riskFloat := new(big.Float).SetInt(risk.ToInt())
maxUint256Float := new(big.Float).SetInt(constants.MaxUint256)
riskRate := new(big.Float).Quo(riskFloat, maxUint256Float)
return riskRate, nil
}
// SendTransaction signs and sends transaction to conflux node and returns the transaction hash.
func (client *Client) SendTransaction(tx types.UnsignedTransaction) (types.Hash, error) {
err := client.ApplyUnsignedTransactionDefault(&tx)
if err != nil {
return "", errors.Wrap(err, errMsgApplyTxValues)
}
//sign
if client.AccountManager == nil {
return "", errors.New("account manager not specified, see SetAccountManager")
}
rawData, err := client.AccountManager.SignTransaction(tx)
if err != nil {
return "", errors.Wrap(err, "failed to sign transaction")
}
//send raw tx
txhash, err := client.SendRawTransaction(rawData)
if err != nil {
return "", errors.Wrapf(err, "failed to send transaction, raw data = 0x%+x", rawData)
}
return txhash, nil
}
// SendRawTransaction sends signed transaction and returns its hash.
func (client *Client) SendRawTransaction(rawData []byte) (hash types.Hash, err error) {
tx := types.SignedTransaction{}
if e := tx.Decode(rawData, client.GetChainIDCached()); e != nil {
return "", errors.Wrap(e, "invalid raw transaction")
}
if tx.UnsignedTransaction.To != nil && tx.UnsignedTransaction.To.GetAddressType() == cfxaddress.AddressTypeUnknown {
return "", errors.New("to address with unknown type is not allowed ")
}
err = client.wrappedCallRPC(&hash, "cfx_sendRawTransaction", hexutil.Encode(rawData))
return
}
// SignEncodedTransactionAndSend signs RLP encoded transaction "encodedTx" by signature "r,s,v" and sends it to node,
// and returns responsed transaction.
func (client *Client) SignEncodedTransactionAndSend(encodedTx []byte, v byte, r, s []byte) (*types.Transaction, error) {
tx := new(types.UnsignedTransaction)
netwrokID, err := client.GetNetworkID()
if err != nil {
return nil, errors.Wrap(err, "failed to get networkID")
}
err = tx.Decode(encodedTx, netwrokID)
if err != nil {
return nil, errors.Wrap(err, "failed to decode transaction")
}
// tx.From = from
respondTx, err := client.signTransactionAndSend(tx, v, r, s)
if err != nil {
return nil, errors.Wrapf(err, "failed to sign and send transaction %+v", tx)
}
return respondTx, nil
}
func (client *Client) signTransactionAndSend(tx *types.UnsignedTransaction, v byte, r, s []byte) (*types.Transaction, error) {
rlp, err := tx.EncodeWithSignature(v, r, s)
if err != nil {
return nil, errors.Wrap(err, "failed to encode transaction with signature")
}
hash, err := client.SendRawTransaction(rlp)
if err != nil {
return nil, errors.Wrapf(err, "failed to send transaction, raw data = 0x%+x", rlp)
}
respondTx, err := client.GetTransactionByHash(hash)
if err != nil {
return nil, errors.Wrapf(err, "failed to get transaction by hash %v", hash)
}
return respondTx, nil
}
// Call executes a message call transaction "request" at specified epoch,
// which is directly executed in the VM of the node, but never mined into the block chain
// and returns the contract execution result.
func (client *Client) Call(request types.CallRequest, epoch *types.EpochOrBlockHash) (result hexutil.Bytes, err error) {
err = client.wrappedCallRPC(&result, "cfx_call", request, epoch)
if err == nil {
return
}
if rpcErr, err2 := utils.ToRpcError(err); err2 == nil {
return result, rpcErr
}
return
}
// GetLogs returns logs that matching the specified filter.
func (client *Client) GetLogs(filter types.LogFilter) (logs []types.Log, err error) {
err = client.wrappedCallRPC(&logs, "cfx_getLogs", filter)
return
}
// GetTransactionByHash returns transaction for the specified txHash.
// If the transaction is not found, return nil.
func (client *Client) GetTransactionByHash(txHash types.Hash) (tx *types.Transaction, err error) {
err = client.wrappedCallRPC(&tx, "cfx_getTransactionByHash", txHash)
return
}
// EstimateGasAndCollateral excutes a message call "request"
// and returns the amount of the gas used and storage for collateral
func (client *Client) EstimateGasAndCollateral(request types.CallRequest, epoch ...*types.Epoch) (estimat types.Estimate, err error) {
realEpoch := get1stEpochIfy(epoch)
err = client.wrappedCallRPC(&estimat, "cfx_estimateGasAndCollateral", request, realEpoch)
return
}
// GetBlocksByEpoch returns the blocks hash in the specified epoch.
func (client *Client) GetBlocksByEpoch(epoch *types.Epoch) (blockHashes []types.Hash, err error) {
err = client.wrappedCallRPC(&blockHashes, "cfx_getBlocksByEpoch", epoch)
return
}
// GetTransactionReceipt returns the receipt of specified transaction hash.
// If no receipt is found, return nil.
func (client *Client) GetTransactionReceipt(txHash types.Hash) (receipt *types.TransactionReceipt, err error) {
err = client.wrappedCallRPC(&receipt, "cfx_getTransactionReceipt", txHash)
return
}
// ===new rpc===
// GetAdmin returns admin of the given contract, it will return nil if contract not exist
func (client *Client) GetAdmin(contractAddress types.Address, epoch ...*types.Epoch) (admin *types.Address, err error) {
realEpoch := get1stEpochIfy(epoch)
err = client.wrappedCallRPC(&admin, "cfx_getAdmin", contractAddress, realEpoch)
return
}
// GetSponsorInfo returns sponsor information of the given contract
func (client *Client) GetSponsorInfo(contractAddress types.Address, epoch ...*types.Epoch) (sponsor types.SponsorInfo, err error) {
realEpoch := get1stEpochIfy(epoch)
err = client.wrappedCallRPC(&sponsor, "cfx_getSponsorInfo", contractAddress, realEpoch)
return
}
// GetStakingBalance returns balance of the given account.
func (client *Client) GetStakingBalance(account types.Address, epoch ...*types.Epoch) (balance *hexutil.Big, err error) {
realEpoch := get1stEpochIfy(epoch)
err = client.wrappedCallRPC(&balance, "cfx_getStakingBalance", account, realEpoch)
return
}
// GetCollateralForStorage returns balance of the given account.
func (client *Client) GetCollateralForStorage(account types.Address, epoch ...*types.Epoch) (storage *hexutil.Big, err error) {
realEpoch := get1stEpochIfy(epoch)
err = client.wrappedCallRPC(&storage, "cfx_getCollateralForStorage", account, realEpoch)
return
}
// GetStorageAt returns storage entries from a given contract.
func (client *Client) GetStorageAt(address types.Address, position *hexutil.Big, epoch ...*types.EpochOrBlockHash) (storageEntries hexutil.Bytes, err error) {
realEpoch := get1stEpochOrBlockhashIfy(epoch)
err = client.wrappedCallRPC(&storageEntries, "cfx_getStorageAt", address, position, realEpoch)
return
}
// GetStorageRoot returns storage root of given address
func (client *Client) GetStorageRoot(address types.Address, epoch ...*types.Epoch) (storageRoot *types.StorageRoot, err error) {
realEpoch := get1stEpochIfy(epoch)
err = client.wrappedCallRPC(&storageRoot, "cfx_getStorageRoot", address, realEpoch)
return
}
// GetBlockByHashWithPivotAssumption returns block with given hash and pivot chain assumption.
func (client *Client) GetBlockByHashWithPivotAssumption(blockHash types.Hash, pivotHash types.Hash, epoch hexutil.Uint64) (block types.Block, err error) {
err = client.wrappedCallRPC(&block, "cfx_getBlockByHashWithPivotAssumption", blockHash, pivotHash, epoch)
return
}
// CheckBalanceAgainstTransaction checks if user balance is enough for the transaction.
func (client *Client) CheckBalanceAgainstTransaction(accountAddress types.Address,
contractAddress types.Address,
gasLimit *hexutil.Big,
gasPrice *hexutil.Big,
storageLimit *hexutil.Big,
epoch ...*types.Epoch) (response types.CheckBalanceAgainstTransactionResponse, err error) {
realEpoch := get1stEpochIfy(epoch)
err = client.wrappedCallRPC(&response,
"cfx_checkBalanceAgainstTransaction", accountAddress, contractAddress,
gasLimit, gasPrice, storageLimit, realEpoch)
return
}
// GetSkippedBlocksByEpoch returns skipped block hashes of given epoch
func (client *Client) GetSkippedBlocksByEpoch(epoch *types.Epoch) (blockHashs []types.Hash, err error) {
err = client.wrappedCallRPC(&blockHashs, "cfx_getSkippedBlocksByEpoch", epoch)
return
}
// GetAccountInfo returns account related states of the given account
func (client *Client) GetAccountInfo(account types.Address, epoch ...*types.Epoch) (accountInfo types.AccountInfo, err error) {
realEpoch := get1stEpochIfy(epoch)
err = client.wrappedCallRPC(&accountInfo, "cfx_getAccount", account, realEpoch)
return
}
// GetInterestRate returns interest rate of the given epoch
func (client *Client) GetInterestRate(epoch ...*types.Epoch) (intersetRate *hexutil.Big, err error) {
realEpoch := get1stEpochIfy(epoch)
err = client.wrappedCallRPC(&intersetRate, "cfx_getInterestRate", realEpoch)
if err != nil {
intersetRate = nil
}
return
}
// GetAccumulateInterestRate returns accumulate interest rate of the given epoch
func (client *Client) GetAccumulateInterestRate(epoch ...*types.Epoch) (intersetRate *hexutil.Big, err error) {
realEpoch := get1stEpochIfy(epoch)
err = client.wrappedCallRPC(&intersetRate, "cfx_getAccumulateInterestRate", realEpoch)
if err != nil {
intersetRate = nil
}
return
}
// GetBlockRewardInfo returns block reward information in an epoch
func (client *Client) GetBlockRewardInfo(epoch types.Epoch) (rewardInfo []types.RewardInfo, err error) {
err = client.wrappedCallRPC(&rewardInfo, "cfx_getBlockRewardInfo", epoch)
return
}
// GetClientVersion returns the client version as a string
func (client *Client) GetClientVersion() (clientVersion string, err error) {
err = client.wrappedCallRPC(&clientVersion, "cfx_clientVersion")
return
}
// GetDepositList returns deposit list of the given account.
func (client *Client) GetDepositList(address types.Address, epoch ...*types.Epoch) (depositInfos []types.DepositInfo, err error) {
realEpoch := get1stEpochIfy(epoch)
err = client.wrappedCallRPC(&depositInfos, "cfx_getDepositList", address, realEpoch)
return
}
// GetVoteList returns vote list of the given account.
func (client *Client) GetVoteList(address types.Address, epoch ...*types.Epoch) (voteStakeInfos []types.VoteStakeInfo, err error) {
realEpoch := get1stEpochIfy(epoch)
err = client.wrappedCallRPC(&voteStakeInfos, "cfx_getVoteList", address, realEpoch)
return
}
// GetSupplyInfo Return information about total token supply.
func (client *Client) GetSupplyInfo(epoch ...*types.Epoch) (info types.TokenSupplyInfo, err error) {
realEpoch := get1stEpochIfy(epoch)
err = client.wrappedCallRPC(&info, "cfx_getSupplyInfo", realEpoch)
return
}
// GetPosRewardByEpoch returns pos rewarded in this epoch
func (client *Client) GetPoSRewardByEpoch(epoch types.Epoch) (reward *postypes.EpochReward, err error) {
err = client.wrappedCallRPC(&reward, "cfx_getPoSRewardByEpoch", epoch)
return
}
// GetFeeHistory returns transaction base fee per gas and effective priority fee per gas for the requested/supported epoch range.
func (client *Client) GetFeeHistory(blockCount types.HexOrDecimalUint64, lastEpoch types.Epoch, rewardPercentiles []float64) (feeHistory *types.FeeHistory, err error) {
err = client.wrappedCallRPC(&feeHistory, "cfx_feeHistory", blockCount, lastEpoch, rewardPercentiles)
return
}
func (client *Client) GetMaxPriorityFeePerGas() (maxPriorityFeePerGas *hexutil.Big, err error) {
err = client.wrappedCallRPC(&maxPriorityFeePerGas, "cfx_maxPriorityFeePerGas")
return
}
func (client *Client) GetFeeBurnt(epoch ...*types.Epoch) (info *hexutil.Big, err error) {
err = client.wrappedCallRPC(&info, "cfx_getFeeBurnt", get1stEpochIfy(epoch))
return
}
// CreateUnsignedTransaction creates an unsigned transaction by parameters,
// and the other fields will be set to values fetched from conflux node.
func (client *Client) CreateUnsignedTransaction(from types.Address, to types.Address, amount *hexutil.Big, data []byte) (types.UnsignedTransaction, error) {
tx := new(types.UnsignedTransaction)
tx.From = &from
tx.To = &to
tx.Value = amount
tx.Data = data
err := client.ApplyUnsignedTransactionDefault(tx)
if err != nil {
return types.UnsignedTransaction{}, errors.Wrap(err, errMsgApplyTxValues)
}
return *tx, nil
}
// ApplyUnsignedTransactionDefault set empty fields to value fetched from conflux node.
func (client *Client) ApplyUnsignedTransactionDefault(tx *types.UnsignedTransaction) error {
networkID, err := client.GetNetworkID()
if err != nil {
return errors.Wrap(err, "failed to get networkID")
}
chainID, err := client.GetChainID()
if err != nil {
return errors.Wrap(err, "failed to get chainID")
}
if client != nil {
if tx.From == nil {
//TODO: return error if client.AccountManager is nil?
if client.AccountManager == nil {
return errors.New("failed to get account manager")
}
if client.AccountManager != nil {
defaultAccount, err := client.AccountManager.GetDefault()
if err != nil {
return errors.Wrap(err, "failed to get default account")
}
if defaultAccount == nil {
return errors.New("no account found")
}
tx.From = defaultAccount
}
}
tx.From.CompleteByNetworkID(networkID)
tx.To.CompleteByNetworkID(networkID)
if tx.Nonce == nil {
nonce, err := client.GetNextUsableNonce(*tx.From)
if err != nil {
return errors.Wrap(err, "failed to get nonce")
}
tmp := hexutil.Big(*nonce)
tx.Nonce = &tmp
}
if tx.ChainID == nil {
chainID := hexutil.Uint(chainID)
tx.ChainID = &chainID
}
if tx.EpochHeight == nil {
epoch, err := client.GetEpochNumber(types.EpochLatestState)
if err != nil {
return errors.Wrap(err, "failed to get the latest state epoch number")
}
tx.EpochHeight = types.NewUint64(epoch.ToInt().Uint64())
}
// The gas and storage limit may be influnced by all fileds of transaction ,so set them at last step.
if tx.StorageLimit == nil || tx.Gas == nil {
callReq := new(types.CallRequest)
callReq.FillByUnsignedTx(tx)
sm, err := client.EstimateGasAndCollateral(*callReq)
if err != nil {
return errors.Wrapf(err, "failed to estimate gas and collateral, request = %+v", *callReq)
}
if tx.Gas == nil {
tx.Gas = sm.GasLimit
}
if tx.StorageLimit == nil {
tx.StorageLimit = types.NewUint64(sm.StorageCollateralized.ToInt().Uint64() * 10 / 9)
}
}
if err := client.populateTxtypeAndGasPrice(tx); err != nil {
return err
}
tx.ApplyDefault()
}
return nil
}
func (client *Client) populateTxtypeAndGasPrice(tx *types.UnsignedTransaction) error {
if tx.GasPrice != nil && (tx.MaxFeePerGas != nil || tx.MaxPriorityFeePerGas != nil) {
return errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified")
}
if tx.GasPrice != nil && (tx.Type == nil || *tx.Type == types.TRANSACTION_TYPE_LEGACY) {
tx.Type = types.TRANSACTION_TYPE_LEGACY.Ptr()
return nil
}
has1559 := tx.MaxFeePerGas != nil || tx.MaxPriorityFeePerGas != nil
gasFeeData, err := client.getFeeData()
if err != nil {
return errors.Wrap(err, "failed to get fee data")
}
// set the txtype according to feeData
// - if support1559, then set txtype to 2
// - if not support1559
// - - if has maxFeePerGas or maxPriorityFeePerGas, then return error
// - - if contains accesslist, set txtype to 1
// - - else set txtype to 0
if tx.Type == nil {
if gasFeeData.isSupport1559() {
tx.Type = types.TRANSACTION_TYPE_1559.Ptr()
} else {
if has1559 {
return errors.New("not support 1559 but (maxFeePerGas or maxPriorityFeePerGas) specified")
}
if tx.AccessList == nil {
tx.Type = types.TRANSACTION_TYPE_LEGACY.Ptr()
} else {
tx.Type = types.TRANSACTION_TYPE_2930.Ptr()
}
}
}
// if txtype is DynamicFeeTxType that means support 1559, so if gasPrice is not nil, set max... to gasPrice
if *tx.Type == types.TRANSACTION_TYPE_1559 {
if tx.GasPrice != nil {
tx.MaxFeePerGas = tx.GasPrice
tx.MaxPriorityFeePerGas = tx.GasPrice
tx.GasPrice = nil
return nil
}
if tx.MaxPriorityFeePerGas == nil {
tx.MaxPriorityFeePerGas = (*hexutil.Big)(gasFeeData.maxPriorityFeePerGas)
}
if tx.MaxFeePerGas == nil {
tx.MaxFeePerGas = (*hexutil.Big)(gasFeeData.maxFeePerGas)
}
if tx.MaxFeePerGas.ToInt().Cmp(tx.MaxPriorityFeePerGas.ToInt()) < 0 {
return fmt.Errorf("maxFeePerGas (%v) < maxPriorityFeePerGas (%v)", tx.MaxFeePerGas, tx.MaxPriorityFeePerGas)
}
return nil
}
if tx.GasPrice != nil {
return nil
}
tx.GasPrice = (*hexutil.Big)(gasFeeData.gasPrice)
return nil
}
type gasFeeData struct {
gasPrice *hexutil.Big
maxFeePerGas *hexutil.Big
maxPriorityFeePerGas *hexutil.Big
}
func (g gasFeeData) isSupport1559() bool {
return g.maxPriorityFeePerGas != nil && g.maxFeePerGas != nil
}
func (client *Client) getFeeData() (*gasFeeData, error) {
data := &gasFeeData{}
gasPrice, err := client.GetGasPrice()
if err != nil {
return nil, err
}
data.gasPrice = gasPrice
block, err := client.GetBlockByEpoch(types.EpochLatestState)
if err != nil {
return nil, err
}
basefee := block.BaseFeePerGas
if basefee == nil {
return data, nil
}
priorityFeePerGas, err := client.GetMaxPriorityFeePerGas()
if err != nil {
return nil, err
}
data.maxPriorityFeePerGas = priorityFeePerGas
maxFeePerGas := new(big.Int).Mul(basefee.ToInt(), big.NewInt(2))
maxFeePerGas = new(big.Int).Add(maxFeePerGas, data.maxPriorityFeePerGas.ToInt())
data.maxFeePerGas = types.NewBigIntByRaw(maxFeePerGas)
return data, nil
}
// DeployContract deploys a contract by abiJSON, bytecode and consturctor params.
// It returns a ContractDeployState instance which contains 3 channels for notifying when state changed.
func (client *Client) DeployContract(option *types.ContractDeployOption, abiJSON []byte,
bytecode []byte, constroctorParams ...interface{}) *ContractDeployResult {
doneChan := make(chan struct{})
result := ContractDeployResult{DoneChannel: doneChan}
go func() {
defer func() {
doneChan <- struct{}{}
close(doneChan)
}()
//generate ABI
var abi abi.ABI
err := abi.UnmarshalJSON([]byte(abiJSON))
if err != nil {
result.Error = errors.Errorf("failed to unmarshal ABI: %+v", abiJSON)
return
}
tx := new(types.UnsignedTransaction)
if option != nil {
tx.UnsignedTransactionBase = types.UnsignedTransactionBase(option.UnsignedTransactionBase)
}
//recreate contract bytecode with consturctor params
if len(constroctorParams) > 0 {
input, err := abi.Pack("", constroctorParams...)
if err != nil {
result.Error = errors.Wrapf(err, "failed to encode constructor with args %+v", constroctorParams)
return
}
bytecode = append(bytecode, input...)
}