Skip to content

Commit

Permalink
Update rpc (#70)
Browse files Browse the repository at this point in the history
* update rpc

* change Address.String() to return non-verbose format for unify with other sdks

* remove comments

* fix test

Co-authored-by: dayong <dayong@conflux-chain.org>
  • Loading branch information
wangdayong228 and dayong authored Apr 23, 2021
1 parent 97831af commit e1761ee
Show file tree
Hide file tree
Showing 11 changed files with 108 additions and 59 deletions.
21 changes: 14 additions & 7 deletions api.md
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,13 @@ func (client *Client) GetAccountInfo(account types.Address, epoch ...*types.Epoc
```
GetAccountInfo returns account related states of the given account

#### func (*Client) GetAccountPendingInfo

```go
func (client *Client) GetAccountPendingInfo(address types.Address) (pendignInfo *types.AccountPendingInfo, err error)
```
GetAccountPendingInfo gets transaction pending info by account address

#### func (*Client) GetAccumulateInterestRate

```go
Expand Down Expand Up @@ -715,18 +722,18 @@ WaitForTransationReceipt waits for transaction receipt valid

```go
type ClientOption struct {
KeystorePath string
RetryCount int
RetryInterval time.Duration
CallRpcLogger CallRPCLogger
BatchCallRPCLogger BatchCallRPCLogger
KeystorePath string
RetryCount int
RetryInterval time.Duration
CallRpcLog func(method string, args []interface{}, result interface{}, resultError error, duration time.Duration)
BatchCallRPCLog func(b []rpc.BatchElem, err error, duration time.Duration)
}
```

ClientOption for set keystore path and flags for retry

The simplest way to set logger is to use the types.DefaultCallRpcLogger and
types.DefaultBatchCallRPCLogger
The simplest way to set logger is to use the types.DefaultCallRpcLog and
types.DefaultBatchCallRPCLog

### type Contract

Expand Down
6 changes: 6 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -763,6 +763,12 @@ func (client *Client) GetContract(abiJSON []byte, deployedAt *types.Address) (*C
return contract, nil
}

// GetAccountPendingInfo gets transaction pending info by account address
func (client *Client) GetAccountPendingInfo(address types.Address) (pendignInfo *types.AccountPendingInfo, err error) {
err = client.wrappedCallRPC(&pendignInfo, "cfx_getAccountPendingInfo", address)
return
}

// =====Debug RPC=====

func (client *Client) GetEpochReceipts(epoch types.Epoch) (receipts [][]types.TransactionReceipt, err error) {
Expand Down
10 changes: 5 additions & 5 deletions example/context/config.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
NodeURL = "http://127.0.0.1:22537"
BlockHash = "0xbbbf51dab51c02413413edf0c5d9e03f7c2bfeb584d4154d82f0b38cd63f2e22"
TransactionHash = "0x1498b96d6e3976b8f167a49436addcb907bb8c202df6100aebb2441a55654691"
BlockHashOfNewContract = "0x2e7dd6c1896dd15729fd9f3573b5a6033464385951f557f44906e8a32d3f1307"
ERC20Address = "NET8958:TYPE.CONTRACT:ACC2PMEWZKPR34N3DEU10S2DM47SSBMXS2CUF67X96"
NodeURL = "http://127.0.0.1:12537"
BlockHash = "0x589c98650b0531883edab079acceeae4eefd892a73871ef6e8f1b4f9a82dc1bf"
TransactionHash = "0xca3c7b7b43e0290bc7ba103f42cfabd78ced8504ec5b920276891a8da67ca6b1"
BlockHashOfNewContract = "0xf7a26c4455f320ea298226635c74e87e8f1de78d7d38ba2f8beb7b97bc826b94"
ERC20Address = "NET3469801582:TYPE.CONTRACT:ACC2PMEWZKPR34N3DEU10S2DM47SSBMXS2JVY6JGXV"
18 changes: 10 additions & 8 deletions example/context/prepare.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,21 +69,23 @@ func initClient() {

// init client
var err error
option := sdk.ClientOption{
KeystorePath: path.Join(currentDir, "keystore"),
RetryCount: 10,
RetryInterval: time.Second,
// CallRpcLog: types.DefaultCallRPCLog,
// BatchCallRPCLog: types.DefaultBatchCallRPCLog,
}
client, err = sdk.NewClient(config.NodeURL, option)

keyStorePath := path.Join(currentDir, "keystore")
client, err = sdk.NewClient(config.NodeURL, sdk.ClientOption{KeystorePath: keyStorePath})
if err != nil {
panic(err)
}

config.SetClient(client)

// init retry client
option := sdk.ClientOption{
KeystorePath: keyStorePath,
RetryCount: 10,
RetryInterval: time.Second,
// CallRpcLog: types.DefaultCallRPCLog,
// BatchCallRPCLog: types.DefaultBatchCallRPCLog,
}
retryclient, err := sdk.NewClient(config.NodeURL, option)
if err != nil {
panic(err)
Expand Down
7 changes: 7 additions & 0 deletions example/example_client/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ func run(_client *sdk.Client) {
getBlockRewardInfo()
getClientVersion()
getEpochReceipts()
getAccountPendingInfo()

traceBlock()
traceFilter()
Expand Down Expand Up @@ -452,6 +453,12 @@ func getEpochReceipts() {
}
}

func getAccountPendingInfo() {
fmt.Println("default account:", *defaultAccount)
result, err := client.GetAccountPendingInfo(*defaultAccount)
printResult("GetAccountPendingInfo", []interface{}{*defaultAccount}, result, err)
}

func traceBlock() {
traces, err := client.GetBlockTraces(config.BlockHashOfNewContract)
if err != nil {
Expand Down
34 changes: 19 additions & 15 deletions generate_doc.sh
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
cd "$(dirname "$0")"

mv ./interface.go ./interface.go.tmd
mv ./interface_mock.go ./interface_mock.go.tmd

Expand All @@ -17,21 +19,23 @@ rm -f client.md
rm -f utils.md
rm -f internal_contract.md

read -r -p "The api.md will be overwritten, are you sure ? [y/n] " input
mv ./tmp.md ./api.md

# read -r -p "The api.md will be overwritten, are you sure ? [y/n] " input

case $input in
[yY][eE][sS]|[yY])
echo "Yes"
mv ./tmp.md ./api.md
;;
# case $input in
# [yY][eE][sS]|[yY])
# echo "Yes"
# mv ./tmp.md ./api.md
# ;;

[nN][oO]|[nN])
echo "No"
;;
# [nN][oO]|[nN])
# echo "No"
# ;;

*)
echo "Invalid input..."
rm ./tmp.md
exit 1
;;
esac
# *)
# echo "Invalid input..."
# rm ./tmp.md
# exit 1
# ;;
# esac
57 changes: 36 additions & 21 deletions interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,15 @@ type Contractor interface {

// ClientOperator is interface of operate actions on client
type ClientOperator interface {
GetNodeURL() string
NewAddress(base32OrHex string) (types.Address, error)
MustNewAddress(base32OrHex string) types.Address

CallRPC(result interface{}, method string, args ...interface{}) error
BatchCallRPC(b []rpc.BatchElem) error

SetAccountManager(accountManager AccountManagerOperator)

GetGasPrice() (*hexutil.Big, error)
GetNextNonce(address types.Address, epoch ...*types.Epoch) (*hexutil.Big, error)
GetStatus() (types.Status, error)
Expand All @@ -46,32 +53,18 @@ type ClientOperator interface {
GetBestBlockHash() (types.Hash, error)
GetRawBlockConfirmationRisk(blockhash types.Hash) (*hexutil.Big, error)
GetBlockConfirmationRisk(blockHash types.Hash) (*big.Float, error)
SendRawTransaction(rawData []byte) (types.Hash, error)

SendTransaction(tx types.UnsignedTransaction) (types.Hash, error)
SetAccountManager(accountManager AccountManagerOperator)
SendRawTransaction(rawData []byte) (types.Hash, error)
SignEncodedTransactionAndSend(encodedTx []byte, v byte, r, s []byte) (*types.Transaction, error)

Call(request types.CallRequest, epoch *types.Epoch) (hexutil.Bytes, error)
CallRPC(result interface{}, method string, args ...interface{}) error
BatchCallRPC(b []rpc.BatchElem) error

GetLogs(filter types.LogFilter) ([]types.Log, error)
GetTransactionByHash(txHash types.Hash) (*types.Transaction, error)
EstimateGasAndCollateral(request types.CallRequest, epoch ...*types.Epoch) (types.Estimate, error)
GetBlocksByEpoch(epoch *types.Epoch) ([]types.Hash, error)
GetTransactionReceipt(txHash types.Hash) (*types.TransactionReceipt, error)
CreateUnsignedTransaction(from types.Address, to types.Address, amount *hexutil.Big, data []byte) (types.UnsignedTransaction, error)
ApplyUnsignedTransactionDefault(tx *types.UnsignedTransaction) error
Close()
GetContract(abiJSON []byte, deployedAt *types.Address) (*Contract, error)
// DeployContract(abiJSON string, bytecode []byte, option *types.ContractDeployOption, timeout time.Duration, callback func(deployedContract Contractor, hash *types.Hash, err error)) <-chan struct{}
DeployContract(option *types.ContractDeployOption, abiJSON []byte,
bytecode []byte, constroctorParams ...interface{}) *ContractDeployResult

BatchGetTxByHashes(txhashes []types.Hash) (map[types.Hash]*types.Transaction, error)
BatchGetBlockConfirmationRisk(blockhashes []types.Hash) (map[types.Hash]*big.Float, error)
BatchGetRawBlockConfirmationRisk(blockhashes []types.Hash) (map[types.Hash]*big.Int, error)
BatchGetBlockSummarys(blockhashes []types.Hash) (map[types.Hash]*types.BlockSummary, error)
GetNodeURL() string

GetAdmin(contractAddress types.Address, epoch ...*types.Epoch) (admin *types.Address, err error)
GetSponsorInfo(contractAddress types.Address, epoch ...*types.Epoch) (sponsor types.SponsorInfo, err error)
GetStakingBalance(account types.Address, epoch ...*types.Epoch) (balance *hexutil.Big, err error)
Expand All @@ -91,14 +84,36 @@ type ClientOperator interface {
GetAccumulateInterestRate(epoch ...*types.Epoch) (intersetRate *hexutil.Big, err error)
GetBlockRewardInfo(epoch types.Epoch) (rewardInfo []types.RewardInfo, err error)
GetClientVersion() (clientVersion string, err error)
WaitForTransationBePacked(txhash types.Hash, duration time.Duration) (*types.Transaction, error)
WaitForTransationReceipt(txhash types.Hash, duration time.Duration) (*types.TransactionReceipt, error)

GetDepositList(address types.Address, epoch ...*types.Epoch) ([]types.DepositInfo, error)
GetVoteList(address types.Address, epoch ...*types.Epoch) ([]types.VoteStakeInfo, error)
GetSupplyInfo(epoch ...*types.Epoch) (info types.TokenSupplyInfo, err error)

GetBlockTraces(blockHash types.Hash) (*types.LocalizedBlockTrace, error)
FilterTraces(traceFilter types.TraceFilter) (traces []types.LocalizedTrace, err error)
GetTransactionTraces(txHash types.Hash) (traces []types.LocalizedTrace, err error)

CreateUnsignedTransaction(from types.Address, to types.Address, amount *hexutil.Big, data []byte) (types.UnsignedTransaction, error)
ApplyUnsignedTransactionDefault(tx *types.UnsignedTransaction) error

DeployContract(option *types.ContractDeployOption, abiJSON []byte,
bytecode []byte, constroctorParams ...interface{}) *ContractDeployResult
GetContract(abiJSON []byte, deployedAt *types.Address) (*Contract, error)
GetAccountPendingInfo(address types.Address) (pendignInfo *types.AccountPendingInfo, err error)
GetEpochReceipts(epoch types.Epoch) (receipts [][]types.TransactionReceipt, err error)

BatchGetTxByHashes(txhashes []types.Hash) (map[types.Hash]*types.Transaction, error)
BatchGetBlockSummarys(blockhashes []types.Hash) (map[types.Hash]*types.BlockSummary, error)
BatchGetRawBlockConfirmationRisk(blockhashes []types.Hash) (map[types.Hash]*big.Int, error)
BatchGetBlockConfirmationRisk(blockhashes []types.Hash) (map[types.Hash]*big.Float, error)

Close()

SubscribeNewHeads(channel chan types.BlockHeader) (*rpc.ClientSubscription, error)
SubscribeEpochs(channel chan types.WebsocketEpochResponse, subscriptionEpochType ...types.Epoch) (*rpc.ClientSubscription, error)
SubscribeLogs(logChannel chan types.Log, chainReorgChannel chan types.ChainReorg, filter types.LogFilter) (*rpc.ClientSubscription, error)

WaitForTransationBePacked(txhash types.Hash, duration time.Duration) (*types.Transaction, error)
WaitForTransationReceipt(txhash types.Hash, duration time.Duration) (*types.TransactionReceipt, error)
}

// AccountManagerOperator is interface of operate actions on account manager
Expand Down
4 changes: 2 additions & 2 deletions types/cfxaddress/address.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ type Address struct {

// String returns verbose base32 string of address
func (a Address) String() string {
return a.MustGetVerboseBase32Address()
return a.MustGetBase32Address()
}

// Equals reports whether a and target are equal
Expand Down Expand Up @@ -238,7 +238,7 @@ func (a *Address) ToCommon() (address common.Address, networkID uint32, err erro

// MustGetBase32Address returns base32 string of address which doesn't include address type
func (a *Address) MustGetBase32Address() string {
return fmt.Sprintf("%v:%v%v", a.networkType, a.body, a.checksum)
return strings.ToLower(fmt.Sprintf("%v:%v%v", a.networkType, a.body, a.checksum))
}

// MustGetVerboseBase32Address returns base32 string of address with address type
Expand Down
2 changes: 1 addition & 1 deletion types/cfxaddress/address_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func TestMarshalJSON(t *testing.T) {
j, e := json.Marshal(cfxAddressFromHex)
// encoding.TextMarshaler
fatalIfErr(t, e)
expect := "\"CFX:TYPE.USER:AASR8SNKYUYMSYF2XP369E8KPZUSFTJ14EC1N0VXJ1\""
expect := "\"cfx:aasr8snkyuymsyf2xp369e8kpzusftj14ec1n0vxj1\""
if string(j) != expect {
t.Fatalf("expect %#v, actual %#v", expect, string(j))
}
Expand Down
1 change: 1 addition & 0 deletions types/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ type LogFilter struct {
BlockHashes []Hash `json:"blockHashes,omitempty"`
Address []Address `json:"address,omitempty"`
Topics [][]Hash `json:"topics,omitempty"`
Offset *hexutil.Uint64 `json:"offset,omitempty"`
Limit *hexutil.Uint64 `json:"limit,omitempty"`
}

Expand Down
7 changes: 7 additions & 0 deletions types/rpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,10 @@ type TokenSupplyInfo struct {
type ChainReorg struct {
RevertTo *hexutil.Big `json:"revertTo"`
}

type AccountPendingInfo struct {
LocalNonce *hexutil.Big `json:"localNonce"`
PendingCount *hexutil.Big `json:"pendingCount"`
PendingNonce *hexutil.Big `json:"pendingNonce"`
NextPendingTx Hash `json:"nextPendingTx"`
}

0 comments on commit e1761ee

Please sign in to comment.