base.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. // Copyright 2015 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 bind
  17. import (
  18. "context"
  19. "errors"
  20. "fmt"
  21. "math/big"
  22. "github.com/ethereum/go-ethereum"
  23. "github.com/ethereum/go-ethereum/accounts/abi"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/core/types"
  26. "github.com/ethereum/go-ethereum/crypto"
  27. "github.com/ethereum/go-ethereum/event"
  28. )
  29. // SignerFn is a signer function callback when a contract requires a method to
  30. // sign the transaction before submission.
  31. type SignerFn func(common.Address, *types.Transaction) (*types.Transaction, error)
  32. // CallOpts is the collection of options to fine tune a contract call request.
  33. type CallOpts struct {
  34. Pending bool // Whether to operate on the pending state or the last known one
  35. From common.Address // Optional the sender address, otherwise the first account is used
  36. BlockNumber *big.Int // Optional the block number on which the call should be performed
  37. Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
  38. }
  39. // TransactOpts is the collection of authorization data required to create a
  40. // valid Ethereum transaction.
  41. type TransactOpts struct {
  42. From common.Address // Ethereum account to send the transaction from
  43. Nonce *big.Int // Nonce to use for the transaction execution (nil = use pending state)
  44. Signer SignerFn // Method to use for signing the transaction (mandatory)
  45. Value *big.Int // Funds to transfer along the transaction (nil = 0 = no funds)
  46. GasPrice *big.Int // Gas price to use for the transaction execution (nil = gas price oracle)
  47. GasLimit uint64 // Gas limit to set for the transaction execution (0 = estimate)
  48. Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
  49. NoSend bool // Do all transact steps but do not send the transaction
  50. }
  51. // FilterOpts is the collection of options to fine tune filtering for events
  52. // within a bound contract.
  53. type FilterOpts struct {
  54. Start uint64 // Start of the queried range
  55. End *uint64 // End of the range (nil = latest)
  56. Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
  57. }
  58. // WatchOpts is the collection of options to fine tune subscribing for events
  59. // within a bound contract.
  60. type WatchOpts struct {
  61. Start *uint64 // Start of the queried range (nil = latest)
  62. Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
  63. }
  64. // BoundContract is the base wrapper object that reflects a contract on the
  65. // Ethereum network. It contains a collection of methods that are used by the
  66. // higher level contract bindings to operate.
  67. type BoundContract struct {
  68. address common.Address // Deployment address of the contract on the Ethereum blockchain
  69. abi abi.ABI // Reflect based ABI to access the correct Ethereum methods
  70. caller ContractCaller // Read interface to interact with the blockchain
  71. transactor ContractTransactor // Write interface to interact with the blockchain
  72. filterer ContractFilterer // Event filtering to interact with the blockchain
  73. }
  74. // NewBoundContract creates a low level contract interface through which calls
  75. // and transactions may be made through.
  76. func NewBoundContract(address common.Address, abi abi.ABI, caller ContractCaller, transactor ContractTransactor, filterer ContractFilterer) *BoundContract {
  77. return &BoundContract{
  78. address: address,
  79. abi: abi,
  80. caller: caller,
  81. transactor: transactor,
  82. filterer: filterer,
  83. }
  84. }
  85. // DeployContract deploys a contract onto the Ethereum blockchain and binds the
  86. // deployment address with a Go wrapper.
  87. func DeployContract(opts *TransactOpts, abi abi.ABI, bytecode []byte, backend ContractBackend, params ...interface{}) (common.Address, *types.Transaction, *BoundContract, error) {
  88. // Otherwise try to deploy the contract
  89. c := NewBoundContract(common.Address{}, abi, backend, backend, backend)
  90. input, err := c.abi.Pack("", params...)
  91. if err != nil {
  92. return common.Address{}, nil, nil, err
  93. }
  94. tx, err := c.transact(opts, nil, append(bytecode, input...))
  95. if err != nil {
  96. return common.Address{}, nil, nil, err
  97. }
  98. c.address = crypto.CreateAddress(opts.From, tx.Nonce())
  99. return c.address, tx, c, nil
  100. }
  101. // Call invokes the (constant) contract method with params as input values and
  102. // sets the output to result. The result type might be a single field for simple
  103. // returns, a slice of interfaces for anonymous returns and a struct for named
  104. // returns.
  105. func (c *BoundContract) Call(opts *CallOpts, results *[]interface{}, method string, params ...interface{}) error {
  106. // Don't crash on a lazy user
  107. if opts == nil {
  108. opts = new(CallOpts)
  109. }
  110. if results == nil {
  111. results = new([]interface{})
  112. }
  113. // Pack the input, call and unpack the results
  114. input, err := c.abi.Pack(method, params...)
  115. if err != nil {
  116. return err
  117. }
  118. var (
  119. msg = ethereum.CallMsg{From: opts.From, To: &c.address, Data: input}
  120. ctx = ensureContext(opts.Context)
  121. code []byte
  122. output []byte
  123. )
  124. if opts.Pending {
  125. pb, ok := c.caller.(PendingContractCaller)
  126. if !ok {
  127. return ErrNoPendingState
  128. }
  129. output, err = pb.PendingCallContract(ctx, msg)
  130. if err == nil && len(output) == 0 {
  131. // Make sure we have a contract to operate on, and bail out otherwise.
  132. if code, err = pb.PendingCodeAt(ctx, c.address); err != nil {
  133. return err
  134. } else if len(code) == 0 {
  135. return ErrNoCode
  136. }
  137. }
  138. } else {
  139. output, err = c.caller.CallContract(ctx, msg, opts.BlockNumber)
  140. if err != nil {
  141. return err
  142. }
  143. if len(output) == 0 {
  144. // Make sure we have a contract to operate on, and bail out otherwise.
  145. if code, err = c.caller.CodeAt(ctx, c.address, opts.BlockNumber); err != nil {
  146. return err
  147. } else if len(code) == 0 {
  148. return ErrNoCode
  149. }
  150. }
  151. }
  152. if len(*results) == 0 {
  153. res, err := c.abi.Unpack(method, output)
  154. *results = res
  155. return err
  156. }
  157. res := *results
  158. return c.abi.UnpackIntoInterface(res[0], method, output)
  159. }
  160. // Transact invokes the (paid) contract method with params as input values.
  161. func (c *BoundContract) Transact(opts *TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
  162. // Otherwise pack up the parameters and invoke the contract
  163. input, err := c.abi.Pack(method, params...)
  164. if err != nil {
  165. return nil, err
  166. }
  167. // todo(rjl493456442) check the method is payable or not,
  168. // reject invalid transaction at the first place
  169. return c.transact(opts, &c.address, input)
  170. }
  171. // RawTransact initiates a transaction with the given raw calldata as the input.
  172. // It's usually used to initiate transactions for invoking **Fallback** function.
  173. func (c *BoundContract) RawTransact(opts *TransactOpts, calldata []byte) (*types.Transaction, error) {
  174. // todo(rjl493456442) check the method is payable or not,
  175. // reject invalid transaction at the first place
  176. return c.transact(opts, &c.address, calldata)
  177. }
  178. // Transfer initiates a plain transaction to move funds to the contract, calling
  179. // its default method if one is available.
  180. func (c *BoundContract) Transfer(opts *TransactOpts) (*types.Transaction, error) {
  181. // todo(rjl493456442) check the payable fallback or receive is defined
  182. // or not, reject invalid transaction at the first place
  183. return c.transact(opts, &c.address, nil)
  184. }
  185. // transact executes an actual transaction invocation, first deriving any missing
  186. // authorization fields, and then scheduling the transaction for execution.
  187. func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error) {
  188. var err error
  189. // Ensure a valid value field and resolve the account nonce
  190. value := opts.Value
  191. if value == nil {
  192. value = new(big.Int)
  193. }
  194. var nonce uint64
  195. if opts.Nonce == nil {
  196. nonce, err = c.transactor.PendingNonceAt(ensureContext(opts.Context), opts.From)
  197. if err != nil {
  198. return nil, fmt.Errorf("failed to retrieve account nonce: %v", err)
  199. }
  200. } else {
  201. nonce = opts.Nonce.Uint64()
  202. }
  203. // Figure out the gas allowance and gas price values
  204. gasPrice := opts.GasPrice
  205. if gasPrice == nil {
  206. gasPrice, err = c.transactor.SuggestGasPrice(ensureContext(opts.Context))
  207. if err != nil {
  208. return nil, fmt.Errorf("failed to suggest gas price: %v", err)
  209. }
  210. }
  211. gasLimit := opts.GasLimit
  212. if gasLimit == 0 {
  213. // Gas estimation cannot succeed without code for method invocations
  214. if contract != nil {
  215. if code, err := c.transactor.PendingCodeAt(ensureContext(opts.Context), c.address); err != nil {
  216. return nil, err
  217. } else if len(code) == 0 {
  218. return nil, ErrNoCode
  219. }
  220. }
  221. // If the contract surely has code (or code is not needed), estimate the transaction
  222. msg := ethereum.CallMsg{From: opts.From, To: contract, GasPrice: gasPrice, Value: value, Data: input}
  223. gasLimit, err = c.transactor.EstimateGas(ensureContext(opts.Context), msg)
  224. if err != nil {
  225. return nil, fmt.Errorf("failed to estimate gas needed: %v", err)
  226. }
  227. }
  228. // Create the transaction, sign it and schedule it for execution
  229. var rawTx *types.Transaction
  230. if contract == nil {
  231. rawTx = types.NewContractCreation(nonce, value, gasLimit, gasPrice, input)
  232. } else {
  233. rawTx = types.NewTransaction(nonce, c.address, value, gasLimit, gasPrice, input)
  234. }
  235. if opts.Signer == nil {
  236. return nil, errors.New("no signer to authorize the transaction with")
  237. }
  238. signedTx, err := opts.Signer(opts.From, rawTx)
  239. if err != nil {
  240. return nil, err
  241. }
  242. if opts.NoSend {
  243. return signedTx, nil
  244. }
  245. if err := c.transactor.SendTransaction(ensureContext(opts.Context), signedTx); err != nil {
  246. return nil, err
  247. }
  248. return signedTx, nil
  249. }
  250. // FilterLogs filters contract logs for past blocks, returning the necessary
  251. // channels to construct a strongly typed bound iterator on top of them.
  252. func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
  253. // Don't crash on a lazy user
  254. if opts == nil {
  255. opts = new(FilterOpts)
  256. }
  257. // Append the event selector to the query parameters and construct the topic set
  258. query = append([][]interface{}{{c.abi.Events[name].ID}}, query...)
  259. topics, err := abi.MakeTopics(query...)
  260. if err != nil {
  261. return nil, nil, err
  262. }
  263. // Start the background filtering
  264. logs := make(chan types.Log, 128)
  265. config := ethereum.FilterQuery{
  266. Addresses: []common.Address{c.address},
  267. Topics: topics,
  268. FromBlock: new(big.Int).SetUint64(opts.Start),
  269. }
  270. if opts.End != nil {
  271. config.ToBlock = new(big.Int).SetUint64(*opts.End)
  272. }
  273. /* TODO(karalabe): Replace the rest of the method below with this when supported
  274. sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
  275. */
  276. buff, err := c.filterer.FilterLogs(ensureContext(opts.Context), config)
  277. if err != nil {
  278. return nil, nil, err
  279. }
  280. sub, err := event.NewSubscription(func(quit <-chan struct{}) error {
  281. for _, log := range buff {
  282. select {
  283. case logs <- log:
  284. case <-quit:
  285. return nil
  286. }
  287. }
  288. return nil
  289. }), nil
  290. if err != nil {
  291. return nil, nil, err
  292. }
  293. return logs, sub, nil
  294. }
  295. // WatchLogs filters subscribes to contract logs for future blocks, returning a
  296. // subscription object that can be used to tear down the watcher.
  297. func (c *BoundContract) WatchLogs(opts *WatchOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
  298. // Don't crash on a lazy user
  299. if opts == nil {
  300. opts = new(WatchOpts)
  301. }
  302. // Append the event selector to the query parameters and construct the topic set
  303. query = append([][]interface{}{{c.abi.Events[name].ID}}, query...)
  304. topics, err := abi.MakeTopics(query...)
  305. if err != nil {
  306. return nil, nil, err
  307. }
  308. // Start the background filtering
  309. logs := make(chan types.Log, 128)
  310. config := ethereum.FilterQuery{
  311. Addresses: []common.Address{c.address},
  312. Topics: topics,
  313. }
  314. if opts.Start != nil {
  315. config.FromBlock = new(big.Int).SetUint64(*opts.Start)
  316. }
  317. sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
  318. if err != nil {
  319. return nil, nil, err
  320. }
  321. return logs, sub, nil
  322. }
  323. // UnpackLog unpacks a retrieved log into the provided output structure.
  324. func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) error {
  325. if len(log.Data) > 0 {
  326. if err := c.abi.UnpackIntoInterface(out, event, log.Data); err != nil {
  327. return err
  328. }
  329. }
  330. var indexed abi.Arguments
  331. for _, arg := range c.abi.Events[event].Inputs {
  332. if arg.Indexed {
  333. indexed = append(indexed, arg)
  334. }
  335. }
  336. return abi.ParseTopics(out, indexed, log.Topics[1:])
  337. }
  338. // UnpackLogIntoMap unpacks a retrieved log into the provided map.
  339. func (c *BoundContract) UnpackLogIntoMap(out map[string]interface{}, event string, log types.Log) error {
  340. if len(log.Data) > 0 {
  341. if err := c.abi.UnpackIntoMap(out, event, log.Data); err != nil {
  342. return err
  343. }
  344. }
  345. var indexed abi.Arguments
  346. for _, arg := range c.abi.Events[event].Inputs {
  347. if arg.Indexed {
  348. indexed = append(indexed, arg)
  349. }
  350. }
  351. return abi.ParseTopicsIntoMap(out, indexed, log.Topics[1:])
  352. }
  353. // ensureContext is a helper method to ensure a context is not nil, even if the
  354. // user specified it as such.
  355. func ensureContext(ctx context.Context) context.Context {
  356. if ctx == nil {
  357. return context.TODO()
  358. }
  359. return ctx
  360. }