1717package backends
1818
1919import (
20- "encoding/json"
21- "fmt"
2220 "math/big"
23- "sync"
24- "sync/atomic"
2521
2622 "github.com/ethereum/go-ethereum/accounts/abi/bind"
2723 "github.com/ethereum/go-ethereum/common"
@@ -37,183 +33,78 @@ var _ bind.ContractBackend = (*rpcBackend)(nil)
3733// rpcBackend implements bind.ContractBackend, and acts as the data provider to
3834// Ethereum contracts bound to Go structs. It uses an RPC connection to delegate
3935// all its functionality.
40- //
41- // Note: The current implementation is a blocking one. This should be replaced
42- // by a proper async version when a real RPC client is created.
4336type rpcBackend struct {
44- client rpc.Client // RPC client connection to interact with an API server
45- autoid uint32 // ID number to use for the next API request
46- lock sync.Mutex // Singleton access until we get to request multiplexing
37+ client * rpc.Client // RPC client connection to interact with an API server
4738}
4839
4940// NewRPCBackend creates a new binding backend to an RPC provider that can be
5041// used to interact with remote contracts.
51- func NewRPCBackend (client rpc.Client ) bind.ContractBackend {
52- return & rpcBackend {
53- client : client ,
54- }
55- }
56-
57- // request is a JSON RPC request package assembled internally from the client
58- // method calls.
59- type request struct {
60- JSONRPC string `json:"jsonrpc"` // Version of the JSON RPC protocol, always set to 2.0
61- ID int `json:"id"` // Auto incrementing ID number for this request
62- Method string `json:"method"` // Remote procedure name to invoke on the server
63- Params []interface {} `json:"params"` // List of parameters to pass through (keep types simple)
64- }
65-
66- // response is a JSON RPC response package sent back from the API server.
67- type response struct {
68- JSONRPC string `json:"jsonrpc"` // Version of the JSON RPC protocol, always set to 2.0
69- ID int `json:"id"` // Auto incrementing ID number for this request
70- Error * failure `json:"error"` // Any error returned by the remote side
71- Result json.RawMessage `json:"result"` // Whatever the remote side sends us in reply
72- }
73-
74- // failure is a JSON RPC response error field sent back from the API server.
75- type failure struct {
76- Code int `json:"code"` // JSON RPC error code associated with the failure
77- Message string `json:"message"` // Specific error message of the failure
78- }
79-
80- // request forwards an API request to the RPC server, and parses the response.
81- //
82- // This is currently painfully non-concurrent, but it will have to do until we
83- // find the time for niceties like this :P
84- func (b * rpcBackend ) request (ctx context.Context , method string , params []interface {}) (json.RawMessage , error ) {
85- b .lock .Lock ()
86- defer b .lock .Unlock ()
87-
88- if ctx == nil {
89- ctx = context .Background ()
90- }
91-
92- // Ugly hack to serialize an empty list properly
93- if params == nil {
94- params = []interface {}{}
95- }
96- // Assemble the request object
97- reqID := int (atomic .AddUint32 (& b .autoid , 1 ))
98- req := & request {
99- JSONRPC : "2.0" ,
100- ID : reqID ,
101- Method : method ,
102- Params : params ,
103- }
104- if err := b .client .Send (req ); err != nil {
105- return nil , err
106- }
107- res := new (response )
108- errc := make (chan error , 1 )
109- go func () {
110- errc <- b .client .Recv (res )
111- }()
112- select {
113- case err := <- errc :
114- if err != nil {
115- return nil , err
116- }
117- case <- ctx .Done ():
118- return nil , ctx .Err ()
119- }
120- if res .Error != nil {
121- if res .Error .Message == bind .ErrNoCode .Error () {
122- return nil , bind .ErrNoCode
123- }
124- return nil , fmt .Errorf ("remote error: %s" , res .Error .Message )
125- }
126- return res .Result , nil
42+ func NewRPCBackend (client * rpc.Client ) bind.ContractBackend {
43+ return & rpcBackend {client : client }
12744}
12845
12946// HasCode implements ContractVerifier.HasCode by retrieving any code associated
13047// with the contract from the remote node, and checking its size.
13148func (b * rpcBackend ) HasCode (ctx context.Context , contract common.Address , pending bool ) (bool , error ) {
132- // Execute the RPC code retrieval
13349 block := "latest"
13450 if pending {
13551 block = "pending"
13652 }
137- res , err := b .request (ctx , "eth_getCode" , []interface {}{contract .Hex (), block })
138- if err != nil {
139- return false , err
140- }
14153 var hex string
142- if err := json .Unmarshal (res , & hex ); err != nil {
54+ err := b .client .CallContext (ctx , & hex , "eth_getCode" , contract , block )
55+ if err != nil {
14356 return false , err
14457 }
145- // Convert the response back to a Go byte slice and return
14658 return len (common .FromHex (hex )) > 0 , nil
14759}
14860
14961// ContractCall implements ContractCaller.ContractCall, delegating the execution of
15062// a contract call to the remote node, returning the reply to for local processing.
15163func (b * rpcBackend ) ContractCall (ctx context.Context , contract common.Address , data []byte , pending bool ) ([]byte , error ) {
152- // Pack up the request into an RPC argument
15364 args := struct {
15465 To common.Address `json:"to"`
15566 Data string `json:"data"`
15667 }{
15768 To : contract ,
15869 Data : common .ToHex (data ),
15970 }
160- // Execute the RPC call and retrieve the response
16171 block := "latest"
16272 if pending {
16373 block = "pending"
16474 }
165- res , err := b .request (ctx , "eth_call" , []interface {}{args , block })
166- if err != nil {
167- return nil , err
168- }
16975 var hex string
170- if err := json .Unmarshal (res , & hex ); err != nil {
76+ err := b .client .CallContext (ctx , & hex , "eth_call" , args , block )
77+ if err != nil {
17178 return nil , err
17279 }
173- // Convert the response back to a Go byte slice and return
17480 return common .FromHex (hex ), nil
81+
17582}
17683
17784// PendingAccountNonce implements ContractTransactor.PendingAccountNonce, delegating
17885// the current account nonce retrieval to the remote node.
17986func (b * rpcBackend ) PendingAccountNonce (ctx context.Context , account common.Address ) (uint64 , error ) {
180- res , err := b .request (ctx , "eth_getTransactionCount" , []interface {}{account .Hex (), "pending" })
87+ var hex rpc.HexNumber
88+ err := b .client .CallContext (ctx , & hex , "eth_getTransactionCount" , account .Hex (), "pending" )
18189 if err != nil {
18290 return 0 , err
18391 }
184- var hex string
185- if err := json .Unmarshal (res , & hex ); err != nil {
186- return 0 , err
187- }
188- nonce , ok := new (big.Int ).SetString (hex , 0 )
189- if ! ok {
190- return 0 , fmt .Errorf ("invalid nonce hex: %s" , hex )
191- }
192- return nonce .Uint64 (), nil
92+ return hex .Uint64 (), nil
19393}
19494
19595// SuggestGasPrice implements ContractTransactor.SuggestGasPrice, delegating the
19696// gas price oracle request to the remote node.
19797func (b * rpcBackend ) SuggestGasPrice (ctx context.Context ) (* big.Int , error ) {
198- res , err := b .request (ctx , "eth_gasPrice" , nil )
199- if err != nil {
200- return nil , err
201- }
202- var hex string
203- if err := json .Unmarshal (res , & hex ); err != nil {
98+ var hex rpc.HexNumber
99+ if err := b .client .CallContext (ctx , & hex , "eth_gasPrice" ); err != nil {
204100 return nil , err
205101 }
206- price , ok := new (big.Int ).SetString (hex , 0 )
207- if ! ok {
208- return nil , fmt .Errorf ("invalid price hex: %s" , hex )
209- }
210- return price , nil
102+ return (* big .Int )(& hex ), nil
211103}
212104
213105// EstimateGasLimit implements ContractTransactor.EstimateGasLimit, delegating
214106// the gas estimation to the remote node.
215107func (b * rpcBackend ) EstimateGasLimit (ctx context.Context , sender common.Address , contract * common.Address , value * big.Int , data []byte ) (* big.Int , error ) {
216- // Pack up the request into an RPC argument
217108 args := struct {
218109 From common.Address `json:"from"`
219110 To * common.Address `json:"to"`
@@ -226,19 +117,12 @@ func (b *rpcBackend) EstimateGasLimit(ctx context.Context, sender common.Address
226117 Value : rpc .NewHexNumber (value ),
227118 }
228119 // Execute the RPC call and retrieve the response
229- res , err := b .request (ctx , "eth_estimateGas" , []interface {}{args })
120+ var hex rpc.HexNumber
121+ err := b .client .CallContext (ctx , & hex , "eth_estimateGas" , args )
230122 if err != nil {
231123 return nil , err
232124 }
233- var hex string
234- if err := json .Unmarshal (res , & hex ); err != nil {
235- return nil , err
236- }
237- estimate , ok := new (big.Int ).SetString (hex , 0 )
238- if ! ok {
239- return nil , fmt .Errorf ("invalid estimate hex: %s" , hex )
240- }
241- return estimate , nil
125+ return (* big .Int )(& hex ), nil
242126}
243127
244128// SendTransaction implements ContractTransactor.SendTransaction, delegating the
@@ -248,13 +132,5 @@ func (b *rpcBackend) SendTransaction(ctx context.Context, tx *types.Transaction)
248132 if err != nil {
249133 return err
250134 }
251- res , err := b .request (ctx , "eth_sendRawTransaction" , []interface {}{common .ToHex (data )})
252- if err != nil {
253- return err
254- }
255- var hex string
256- if err := json .Unmarshal (res , & hex ); err != nil {
257- return err
258- }
259- return nil
135+ return b .client .CallContext (ctx , nil , "eth_sendRawTransaction" , common .ToHex (data ))
260136}
0 commit comments