ethclient.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // Package ethclient provides a client for the Ethereum RPC API.
  17. package ethclient
  18. import (
  19. "context"
  20. "encoding/json"
  21. "errors"
  22. "fmt"
  23. "math/big"
  24. "github.com/ethereum/go-ethereum"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/common/hexutil"
  27. "github.com/ethereum/go-ethereum/core/types"
  28. "github.com/ethereum/go-ethereum/rpc"
  29. )
  30. // Client defines typed wrappers for the Ethereum RPC API.
  31. type Client struct {
  32. c *rpc.Client
  33. }
  34. // Dial connects a client to the given URL.
  35. func Dial(rawurl string) (*Client, error) {
  36. return DialContext(context.Background(), rawurl)
  37. }
  38. func DialContext(ctx context.Context, rawurl string) (*Client, error) {
  39. c, err := rpc.DialContext(ctx, rawurl)
  40. if err != nil {
  41. return nil, err
  42. }
  43. return NewClient(c), nil
  44. }
  45. // NewClient creates a client that uses the given RPC client.
  46. func NewClient(c *rpc.Client) *Client {
  47. return &Client{c}
  48. }
  49. func (ec *Client) Close() {
  50. ec.c.Close()
  51. }
  52. // Blockchain Access
  53. // ChainId retrieves the current chain ID for transaction replay protection.
  54. func (ec *Client) ChainID(ctx context.Context) (*big.Int, error) {
  55. var result hexutil.Big
  56. err := ec.c.CallContext(ctx, &result, "eth_chainId")
  57. if err != nil {
  58. return nil, err
  59. }
  60. return (*big.Int)(&result), err
  61. }
  62. // BlockByHash returns the given full block.
  63. //
  64. // Note that loading full blocks requires two requests. Use HeaderByHash
  65. // if you don't need all transactions or uncle headers.
  66. func (ec *Client) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
  67. return ec.getBlock(ctx, "eth_getBlockByHash", hash, true)
  68. }
  69. // BlockByNumber returns a block from the current canonical chain. If number is nil, the
  70. // latest known block is returned.
  71. //
  72. // Note that loading full blocks requires two requests. Use HeaderByNumber
  73. // if you don't need all transactions or uncle headers.
  74. func (ec *Client) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) {
  75. return ec.getBlock(ctx, "eth_getBlockByNumber", toBlockNumArg(number), true)
  76. }
  77. // BlockNumber returns the most recent block number
  78. func (ec *Client) BlockNumber(ctx context.Context) (uint64, error) {
  79. var result hexutil.Uint64
  80. err := ec.c.CallContext(ctx, &result, "eth_blockNumber")
  81. return uint64(result), err
  82. }
  83. type rpcBlock struct {
  84. Hash common.Hash `json:"hash"`
  85. Transactions []rpcTransaction `json:"transactions"`
  86. UncleHashes []common.Hash `json:"uncles"`
  87. }
  88. func (ec *Client) getBlock(ctx context.Context, method string, args ...interface{}) (*types.Block, error) {
  89. var raw json.RawMessage
  90. err := ec.c.CallContext(ctx, &raw, method, args...)
  91. if err != nil {
  92. return nil, err
  93. } else if len(raw) == 0 {
  94. return nil, ethereum.NotFound
  95. }
  96. // Decode header and transactions.
  97. var head *types.Header
  98. var body rpcBlock
  99. if err := json.Unmarshal(raw, &head); err != nil {
  100. return nil, err
  101. }
  102. if err := json.Unmarshal(raw, &body); err != nil {
  103. return nil, err
  104. }
  105. // Quick-verify transaction and uncle lists. This mostly helps with debugging the server.
  106. if head.UncleHash == types.EmptyUncleHash && len(body.UncleHashes) > 0 {
  107. return nil, fmt.Errorf("server returned non-empty uncle list but block header indicates no uncles")
  108. }
  109. if head.UncleHash != types.EmptyUncleHash && len(body.UncleHashes) == 0 {
  110. return nil, fmt.Errorf("server returned empty uncle list but block header indicates uncles")
  111. }
  112. if head.TxHash == types.EmptyRootHash && len(body.Transactions) > 0 {
  113. return nil, fmt.Errorf("server returned non-empty transaction list but block header indicates no transactions")
  114. }
  115. if head.TxHash != types.EmptyRootHash && len(body.Transactions) == 0 {
  116. return nil, fmt.Errorf("server returned empty transaction list but block header indicates transactions")
  117. }
  118. // Load uncles because they are not included in the block response.
  119. var uncles []*types.Header
  120. if len(body.UncleHashes) > 0 {
  121. uncles = make([]*types.Header, len(body.UncleHashes))
  122. reqs := make([]rpc.BatchElem, len(body.UncleHashes))
  123. for i := range reqs {
  124. reqs[i] = rpc.BatchElem{
  125. Method: "eth_getUncleByBlockHashAndIndex",
  126. Args: []interface{}{body.Hash, hexutil.EncodeUint64(uint64(i))},
  127. Result: &uncles[i],
  128. }
  129. }
  130. if err := ec.c.BatchCallContext(ctx, reqs); err != nil {
  131. return nil, err
  132. }
  133. for i := range reqs {
  134. if reqs[i].Error != nil {
  135. return nil, reqs[i].Error
  136. }
  137. if uncles[i] == nil {
  138. return nil, fmt.Errorf("got null header for uncle %d of block %x", i, body.Hash[:])
  139. }
  140. }
  141. }
  142. // Fill the sender cache of transactions in the block.
  143. txs := make([]*types.Transaction, len(body.Transactions))
  144. for i, tx := range body.Transactions {
  145. if tx.From != nil {
  146. setSenderFromServer(tx.tx, *tx.From, body.Hash)
  147. }
  148. txs[i] = tx.tx
  149. }
  150. return types.NewBlockWithHeader(head).WithBody(txs, uncles), nil
  151. }
  152. // HeaderByHash returns the block header with the given hash.
  153. func (ec *Client) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) {
  154. var head *types.Header
  155. err := ec.c.CallContext(ctx, &head, "eth_getBlockByHash", hash, false)
  156. if err == nil && head == nil {
  157. err = ethereum.NotFound
  158. }
  159. return head, err
  160. }
  161. // HeaderByNumber returns a block header from the current canonical chain. If number is
  162. // nil, the latest known header is returned.
  163. func (ec *Client) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
  164. var head *types.Header
  165. err := ec.c.CallContext(ctx, &head, "eth_getBlockByNumber", toBlockNumArg(number), false)
  166. if err == nil && head == nil {
  167. err = ethereum.NotFound
  168. }
  169. return head, err
  170. }
  171. type rpcTransaction struct {
  172. tx *types.Transaction
  173. txExtraInfo
  174. }
  175. type txExtraInfo struct {
  176. BlockNumber *string `json:"blockNumber,omitempty"`
  177. BlockHash *common.Hash `json:"blockHash,omitempty"`
  178. From *common.Address `json:"from,omitempty"`
  179. }
  180. func (tx *rpcTransaction) UnmarshalJSON(msg []byte) error {
  181. if err := json.Unmarshal(msg, &tx.tx); err != nil {
  182. return err
  183. }
  184. return json.Unmarshal(msg, &tx.txExtraInfo)
  185. }
  186. // TransactionByHash returns the transaction with the given hash.
  187. func (ec *Client) TransactionByHash(ctx context.Context, hash common.Hash) (tx *types.Transaction, isPending bool, err error) {
  188. var json *rpcTransaction
  189. err = ec.c.CallContext(ctx, &json, "eth_getTransactionByHash", hash)
  190. if err != nil {
  191. return nil, false, err
  192. } else if json == nil {
  193. return nil, false, ethereum.NotFound
  194. } else if _, r, _ := json.tx.RawSignatureValues(); r == nil {
  195. return nil, false, fmt.Errorf("server returned transaction without signature")
  196. }
  197. if json.From != nil && json.BlockHash != nil {
  198. setSenderFromServer(json.tx, *json.From, *json.BlockHash)
  199. }
  200. return json.tx, json.BlockNumber == nil, nil
  201. }
  202. // TransactionSender returns the sender address of the given transaction. The transaction
  203. // must be known to the remote node and included in the blockchain at the given block and
  204. // index. The sender is the one derived by the protocol at the time of inclusion.
  205. //
  206. // There is a fast-path for transactions retrieved by TransactionByHash and
  207. // TransactionInBlock. Getting their sender address can be done without an RPC interaction.
  208. func (ec *Client) TransactionSender(ctx context.Context, tx *types.Transaction, block common.Hash, index uint) (common.Address, error) {
  209. // Try to load the address from the cache.
  210. sender, err := types.Sender(&senderFromServer{blockhash: block}, tx)
  211. if err == nil {
  212. return sender, nil
  213. }
  214. var meta struct {
  215. Hash common.Hash
  216. From common.Address
  217. }
  218. if err = ec.c.CallContext(ctx, &meta, "eth_getTransactionByBlockHashAndIndex", block, hexutil.Uint64(index)); err != nil {
  219. return common.Address{}, err
  220. }
  221. if meta.Hash == (common.Hash{}) || meta.Hash != tx.Hash() {
  222. return common.Address{}, errors.New("wrong inclusion block/index")
  223. }
  224. return meta.From, nil
  225. }
  226. // TransactionCount returns the total number of transactions in the given block.
  227. func (ec *Client) TransactionCount(ctx context.Context, blockHash common.Hash) (uint, error) {
  228. var num hexutil.Uint
  229. err := ec.c.CallContext(ctx, &num, "eth_getBlockTransactionCountByHash", blockHash)
  230. return uint(num), err
  231. }
  232. // TransactionInBlock returns a single transaction at index in the given block.
  233. func (ec *Client) TransactionInBlock(ctx context.Context, blockHash common.Hash, index uint) (*types.Transaction, error) {
  234. var json *rpcTransaction
  235. err := ec.c.CallContext(ctx, &json, "eth_getTransactionByBlockHashAndIndex", blockHash, hexutil.Uint64(index))
  236. if err != nil {
  237. return nil, err
  238. }
  239. if json == nil {
  240. return nil, ethereum.NotFound
  241. } else if _, r, _ := json.tx.RawSignatureValues(); r == nil {
  242. return nil, fmt.Errorf("server returned transaction without signature")
  243. }
  244. if json.From != nil && json.BlockHash != nil {
  245. setSenderFromServer(json.tx, *json.From, *json.BlockHash)
  246. }
  247. return json.tx, err
  248. }
  249. // TransactionInBlock returns a single transaction at index in the given block.
  250. func (ec *Client) TransactionsInBlock(ctx context.Context, number *big.Int) ([]*types.Transaction, error) {
  251. var rpcTxs []*rpcTransaction
  252. err := ec.c.CallContext(ctx, &rpcTxs, "eth_getTransactionsByBlockNumber", toBlockNumArg(number))
  253. if err != nil {
  254. return nil, err
  255. }
  256. fmt.Println(len(rpcTxs))
  257. txs := make([]*types.Transaction, 0, len(rpcTxs))
  258. for _, tx := range rpcTxs {
  259. txs = append(txs, tx.tx)
  260. }
  261. return txs, err
  262. }
  263. // TransactionInBlock returns a single transaction at index in the given block.
  264. func (ec *Client) TransactionRecipientsInBlock(ctx context.Context, number *big.Int) ([]*types.Receipt, error) {
  265. var rs []*types.Receipt
  266. err := ec.c.CallContext(ctx, &rs, "eth_getTransactionReceiptsByBlockNumber", toBlockNumArg(number))
  267. if err != nil {
  268. return nil, err
  269. }
  270. return rs, err
  271. }
  272. // TransactionDataAndReceipt returns the original data and receipt of a transaction by transaction hash.
  273. // Note that the receipt is not available for pending transactions.
  274. func (ec *Client) TransactionDataAndReceipt(ctx context.Context, txHash common.Hash) (*types.OriginalDataAndReceipt, error) {
  275. var r *types.OriginalDataAndReceipt
  276. err := ec.c.CallContext(ctx, &r, "eth_getTransactionDataAndReceipt", txHash)
  277. if err == nil {
  278. if r == nil {
  279. return nil, ethereum.NotFound
  280. }
  281. }
  282. return r, err
  283. }
  284. // TransactionReceipt returns the receipt of a transaction by transaction hash.
  285. // Note that the receipt is not available for pending transactions.
  286. func (ec *Client) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) {
  287. var r *types.Receipt
  288. err := ec.c.CallContext(ctx, &r, "eth_getTransactionReceipt", txHash)
  289. if err == nil {
  290. if r == nil {
  291. return nil, ethereum.NotFound
  292. }
  293. }
  294. return r, err
  295. }
  296. func toBlockNumArg(number *big.Int) string {
  297. if number == nil {
  298. return "latest"
  299. }
  300. pending := big.NewInt(-1)
  301. if number.Cmp(pending) == 0 {
  302. return "pending"
  303. }
  304. return hexutil.EncodeBig(number)
  305. }
  306. type rpcProgress struct {
  307. StartingBlock hexutil.Uint64
  308. CurrentBlock hexutil.Uint64
  309. HighestBlock hexutil.Uint64
  310. PulledStates hexutil.Uint64
  311. KnownStates hexutil.Uint64
  312. }
  313. // SyncProgress retrieves the current progress of the sync algorithm. If there's
  314. // no sync currently running, it returns nil.
  315. func (ec *Client) SyncProgress(ctx context.Context) (*ethereum.SyncProgress, error) {
  316. var raw json.RawMessage
  317. if err := ec.c.CallContext(ctx, &raw, "eth_syncing"); err != nil {
  318. return nil, err
  319. }
  320. // Handle the possible response types
  321. var syncing bool
  322. if err := json.Unmarshal(raw, &syncing); err == nil {
  323. return nil, nil // Not syncing (always false)
  324. }
  325. var progress *rpcProgress
  326. if err := json.Unmarshal(raw, &progress); err != nil {
  327. return nil, err
  328. }
  329. return &ethereum.SyncProgress{
  330. StartingBlock: uint64(progress.StartingBlock),
  331. CurrentBlock: uint64(progress.CurrentBlock),
  332. HighestBlock: uint64(progress.HighestBlock),
  333. PulledStates: uint64(progress.PulledStates),
  334. KnownStates: uint64(progress.KnownStates),
  335. }, nil
  336. }
  337. // SubscribeNewHead subscribes to notifications about the current blockchain head
  338. // on the given channel.
  339. func (ec *Client) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (ethereum.Subscription, error) {
  340. return ec.c.EthSubscribe(ctx, ch, "newHeads")
  341. }
  342. // State Access
  343. // NetworkID returns the network ID (also known as the chain ID) for this chain.
  344. func (ec *Client) NetworkID(ctx context.Context) (*big.Int, error) {
  345. version := new(big.Int)
  346. var ver string
  347. if err := ec.c.CallContext(ctx, &ver, "net_version"); err != nil {
  348. return nil, err
  349. }
  350. if _, ok := version.SetString(ver, 10); !ok {
  351. return nil, fmt.Errorf("invalid net_version result %q", ver)
  352. }
  353. return version, nil
  354. }
  355. // BalanceAt returns the wei balance of the given account.
  356. // The block number can be nil, in which case the balance is taken from the latest known block.
  357. func (ec *Client) BalanceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (*big.Int, error) {
  358. var result hexutil.Big
  359. err := ec.c.CallContext(ctx, &result, "eth_getBalance", account, toBlockNumArg(blockNumber))
  360. return (*big.Int)(&result), err
  361. }
  362. // StorageAt returns the value of key in the contract storage of the given account.
  363. // The block number can be nil, in which case the value is taken from the latest known block.
  364. func (ec *Client) StorageAt(ctx context.Context, account common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error) {
  365. var result hexutil.Bytes
  366. err := ec.c.CallContext(ctx, &result, "eth_getStorageAt", account, key, toBlockNumArg(blockNumber))
  367. return result, err
  368. }
  369. // CodeAt returns the contract code of the given account.
  370. // The block number can be nil, in which case the code is taken from the latest known block.
  371. func (ec *Client) CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error) {
  372. var result hexutil.Bytes
  373. err := ec.c.CallContext(ctx, &result, "eth_getCode", account, toBlockNumArg(blockNumber))
  374. return result, err
  375. }
  376. // NonceAt returns the account nonce of the given account.
  377. // The block number can be nil, in which case the nonce is taken from the latest known block.
  378. func (ec *Client) NonceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (uint64, error) {
  379. var result hexutil.Uint64
  380. err := ec.c.CallContext(ctx, &result, "eth_getTransactionCount", account, toBlockNumArg(blockNumber))
  381. return uint64(result), err
  382. }
  383. // Filters
  384. // FilterLogs executes a filter query.
  385. func (ec *Client) FilterLogs(ctx context.Context, q ethereum.FilterQuery) ([]types.Log, error) {
  386. var result []types.Log
  387. arg, err := toFilterArg(q)
  388. if err != nil {
  389. return nil, err
  390. }
  391. err = ec.c.CallContext(ctx, &result, "eth_getLogs", arg)
  392. return result, err
  393. }
  394. // SubscribeFilterLogs subscribes to the results of a streaming filter query.
  395. func (ec *Client) SubscribeFilterLogs(ctx context.Context, q ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) {
  396. arg, err := toFilterArg(q)
  397. if err != nil {
  398. return nil, err
  399. }
  400. return ec.c.EthSubscribe(ctx, ch, "logs", arg)
  401. }
  402. func toFilterArg(q ethereum.FilterQuery) (interface{}, error) {
  403. arg := map[string]interface{}{
  404. "address": q.Addresses,
  405. "topics": q.Topics,
  406. }
  407. if q.BlockHash != nil {
  408. arg["blockHash"] = *q.BlockHash
  409. if q.FromBlock != nil || q.ToBlock != nil {
  410. return nil, fmt.Errorf("cannot specify both BlockHash and FromBlock/ToBlock")
  411. }
  412. } else {
  413. if q.FromBlock == nil {
  414. arg["fromBlock"] = "0x0"
  415. } else {
  416. arg["fromBlock"] = toBlockNumArg(q.FromBlock)
  417. }
  418. arg["toBlock"] = toBlockNumArg(q.ToBlock)
  419. }
  420. return arg, nil
  421. }
  422. // Pending State
  423. // PendingBalanceAt returns the wei balance of the given account in the pending state.
  424. func (ec *Client) PendingBalanceAt(ctx context.Context, account common.Address) (*big.Int, error) {
  425. var result hexutil.Big
  426. err := ec.c.CallContext(ctx, &result, "eth_getBalance", account, "pending")
  427. return (*big.Int)(&result), err
  428. }
  429. // PendingStorageAt returns the value of key in the contract storage of the given account in the pending state.
  430. func (ec *Client) PendingStorageAt(ctx context.Context, account common.Address, key common.Hash) ([]byte, error) {
  431. var result hexutil.Bytes
  432. err := ec.c.CallContext(ctx, &result, "eth_getStorageAt", account, key, "pending")
  433. return result, err
  434. }
  435. // PendingCodeAt returns the contract code of the given account in the pending state.
  436. func (ec *Client) PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error) {
  437. var result hexutil.Bytes
  438. err := ec.c.CallContext(ctx, &result, "eth_getCode", account, "pending")
  439. return result, err
  440. }
  441. // PendingNonceAt returns the account nonce of the given account in the pending state.
  442. // This is the nonce that should be used for the next transaction.
  443. func (ec *Client) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
  444. var result hexutil.Uint64
  445. err := ec.c.CallContext(ctx, &result, "eth_getTransactionCount", account, "pending")
  446. return uint64(result), err
  447. }
  448. // PendingTransactionCount returns the total number of transactions in the pending state.
  449. func (ec *Client) PendingTransactionCount(ctx context.Context) (uint, error) {
  450. var num hexutil.Uint
  451. err := ec.c.CallContext(ctx, &num, "eth_getBlockTransactionCountByNumber", "pending")
  452. return uint(num), err
  453. }
  454. // TODO: SubscribePendingTransactions (needs server side)
  455. // Contract Calling
  456. // CallContract executes a message call transaction, which is directly executed in the VM
  457. // of the node, but never mined into the blockchain.
  458. //
  459. // blockNumber selects the block height at which the call runs. It can be nil, in which
  460. // case the code is taken from the latest known block. Note that state from very old
  461. // blocks might not be available.
  462. func (ec *Client) CallContract(ctx context.Context, msg ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
  463. var hex hexutil.Bytes
  464. err := ec.c.CallContext(ctx, &hex, "eth_call", toCallArg(msg), toBlockNumArg(blockNumber))
  465. if err != nil {
  466. return nil, err
  467. }
  468. return hex, nil
  469. }
  470. // PendingCallContract executes a message call transaction using the EVM.
  471. // The state seen by the contract call is the pending state.
  472. func (ec *Client) PendingCallContract(ctx context.Context, msg ethereum.CallMsg) ([]byte, error) {
  473. var hex hexutil.Bytes
  474. err := ec.c.CallContext(ctx, &hex, "eth_call", toCallArg(msg), "pending")
  475. if err != nil {
  476. return nil, err
  477. }
  478. return hex, nil
  479. }
  480. // SuggestGasPrice retrieves the currently suggested gas price to allow a timely
  481. // execution of a transaction.
  482. func (ec *Client) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
  483. var hex hexutil.Big
  484. if err := ec.c.CallContext(ctx, &hex, "eth_gasPrice"); err != nil {
  485. return nil, err
  486. }
  487. return (*big.Int)(&hex), nil
  488. }
  489. // EstimateGas tries to estimate the gas needed to execute a specific transaction based on
  490. // the current pending state of the backend blockchain. There is no guarantee that this is
  491. // the true gas limit requirement as other transactions may be added or removed by miners,
  492. // but it should provide a basis for setting a reasonable default.
  493. func (ec *Client) EstimateGas(ctx context.Context, msg ethereum.CallMsg) (uint64, error) {
  494. var hex hexutil.Uint64
  495. err := ec.c.CallContext(ctx, &hex, "eth_estimateGas", toCallArg(msg))
  496. if err != nil {
  497. return 0, err
  498. }
  499. return uint64(hex), nil
  500. }
  501. // SendTransaction injects a signed transaction into the pending pool for execution.
  502. //
  503. // If the transaction was a contract creation use the TransactionReceipt method to get the
  504. // contract address after the transaction has been mined.
  505. func (ec *Client) SendTransaction(ctx context.Context, tx *types.Transaction) error {
  506. data, err := tx.MarshalBinary()
  507. if err != nil {
  508. return err
  509. }
  510. return ec.c.CallContext(ctx, nil, "eth_sendRawTransaction", hexutil.Encode(data))
  511. }
  512. func toCallArg(msg ethereum.CallMsg) interface{} {
  513. arg := map[string]interface{}{
  514. "from": msg.From,
  515. "to": msg.To,
  516. }
  517. if len(msg.Data) > 0 {
  518. arg["data"] = hexutil.Bytes(msg.Data)
  519. }
  520. if msg.Value != nil {
  521. arg["value"] = (*hexutil.Big)(msg.Value)
  522. }
  523. if msg.Gas != 0 {
  524. arg["gas"] = hexutil.Uint64(msg.Gas)
  525. }
  526. if msg.GasPrice != nil {
  527. arg["gasPrice"] = (*hexutil.Big)(msg.GasPrice)
  528. }
  529. return arg
  530. }