base.go 14 KB

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