base.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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(types.Signer, 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 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, result interface{}, method string, params ...interface{}) error {
  105. // Don't crash on a lazy user
  106. if opts == nil {
  107. opts = new(CallOpts)
  108. }
  109. // Pack the input, call and unpack the results
  110. input, err := c.abi.Pack(method, params...)
  111. if err != nil {
  112. return err
  113. }
  114. var (
  115. msg = ethereum.CallMsg{From: opts.From, To: &c.address, Data: input}
  116. ctx = ensureContext(opts.Context)
  117. code []byte
  118. output []byte
  119. )
  120. if opts.Pending {
  121. pb, ok := c.caller.(PendingContractCaller)
  122. if !ok {
  123. return ErrNoPendingState
  124. }
  125. output, err = pb.PendingCallContract(ctx, msg)
  126. if err == nil && len(output) == 0 {
  127. // Make sure we have a contract to operate on, and bail out otherwise.
  128. if code, err = pb.PendingCodeAt(ctx, c.address); err != nil {
  129. return err
  130. } else if len(code) == 0 {
  131. return ErrNoCode
  132. }
  133. }
  134. } else {
  135. output, err = c.caller.CallContract(ctx, msg, opts.BlockNumber)
  136. if err == nil && len(output) == 0 {
  137. // Make sure we have a contract to operate on, and bail out otherwise.
  138. if code, err = c.caller.CodeAt(ctx, c.address, opts.BlockNumber); err != nil {
  139. return err
  140. } else if len(code) == 0 {
  141. return ErrNoCode
  142. }
  143. }
  144. }
  145. if err != nil {
  146. return err
  147. }
  148. return c.abi.Unpack(result, method, output)
  149. }
  150. // Transact invokes the (paid) contract method with params as input values.
  151. func (c *BoundContract) Transact(opts *TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
  152. // Otherwise pack up the parameters and invoke the contract
  153. input, err := c.abi.Pack(method, params...)
  154. if err != nil {
  155. return nil, err
  156. }
  157. return c.transact(opts, &c.address, input)
  158. }
  159. // Transfer initiates a plain transaction to move funds to the contract, calling
  160. // its default method if one is available.
  161. func (c *BoundContract) Transfer(opts *TransactOpts) (*types.Transaction, error) {
  162. return c.transact(opts, &c.address, nil)
  163. }
  164. // transact executes an actual transaction invocation, first deriving any missing
  165. // authorization fields, and then scheduling the transaction for execution.
  166. func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error) {
  167. var err error
  168. // Ensure a valid value field and resolve the account nonce
  169. value := opts.Value
  170. if value == nil {
  171. value = new(big.Int)
  172. }
  173. var nonce uint64
  174. if opts.Nonce == nil {
  175. nonce, err = c.transactor.PendingNonceAt(ensureContext(opts.Context), opts.From)
  176. if err != nil {
  177. return nil, fmt.Errorf("failed to retrieve account nonce: %v", err)
  178. }
  179. } else {
  180. nonce = opts.Nonce.Uint64()
  181. }
  182. // Figure out the gas allowance and gas price values
  183. gasPrice := opts.GasPrice
  184. if gasPrice == nil {
  185. gasPrice, err = c.transactor.SuggestGasPrice(ensureContext(opts.Context))
  186. if err != nil {
  187. return nil, fmt.Errorf("failed to suggest gas price: %v", err)
  188. }
  189. }
  190. gasLimit := opts.GasLimit
  191. if gasLimit == 0 {
  192. // Gas estimation cannot succeed without code for method invocations
  193. if contract != nil {
  194. if code, err := c.transactor.PendingCodeAt(ensureContext(opts.Context), c.address); err != nil {
  195. return nil, err
  196. } else if len(code) == 0 {
  197. return nil, ErrNoCode
  198. }
  199. }
  200. // If the contract surely has code (or code is not needed), estimate the transaction
  201. msg := ethereum.CallMsg{From: opts.From, To: contract, Value: value, Data: input}
  202. gasLimit, err = c.transactor.EstimateGas(ensureContext(opts.Context), msg)
  203. if err != nil {
  204. return nil, fmt.Errorf("failed to estimate gas needed: %v", err)
  205. }
  206. }
  207. // Create the transaction, sign it and schedule it for execution
  208. var rawTx *types.Transaction
  209. if contract == nil {
  210. rawTx = types.NewContractCreation(nonce, value, gasLimit, gasPrice, input)
  211. } else {
  212. rawTx = types.NewTransaction(nonce, c.address, value, gasLimit, gasPrice, input)
  213. }
  214. if opts.Signer == nil {
  215. return nil, errors.New("no signer to authorize the transaction with")
  216. }
  217. signedTx, err := opts.Signer(types.HomesteadSigner{}, opts.From, rawTx)
  218. if err != nil {
  219. return nil, err
  220. }
  221. if err := c.transactor.SendTransaction(ensureContext(opts.Context), signedTx); err != nil {
  222. return nil, err
  223. }
  224. return signedTx, nil
  225. }
  226. // FilterLogs filters contract logs for past blocks, returning the necessary
  227. // channels to construct a strongly typed bound iterator on top of them.
  228. func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
  229. // Don't crash on a lazy user
  230. if opts == nil {
  231. opts = new(FilterOpts)
  232. }
  233. // Append the event selector to the query parameters and construct the topic set
  234. query = append([][]interface{}{{c.abi.Events[name].ID()}}, query...)
  235. topics, err := makeTopics(query...)
  236. if err != nil {
  237. return nil, nil, err
  238. }
  239. // Start the background filtering
  240. logs := make(chan types.Log, 128)
  241. config := ethereum.FilterQuery{
  242. Addresses: []common.Address{c.address},
  243. Topics: topics,
  244. FromBlock: new(big.Int).SetUint64(opts.Start),
  245. }
  246. if opts.End != nil {
  247. config.ToBlock = new(big.Int).SetUint64(*opts.End)
  248. }
  249. /* TODO(karalabe): Replace the rest of the method below with this when supported
  250. sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
  251. */
  252. buff, err := c.filterer.FilterLogs(ensureContext(opts.Context), config)
  253. if err != nil {
  254. return nil, nil, err
  255. }
  256. sub, err := event.NewSubscription(func(quit <-chan struct{}) error {
  257. for _, log := range buff {
  258. select {
  259. case logs <- log:
  260. case <-quit:
  261. return nil
  262. }
  263. }
  264. return nil
  265. }), nil
  266. if err != nil {
  267. return nil, nil, err
  268. }
  269. return logs, sub, nil
  270. }
  271. // WatchLogs filters subscribes to contract logs for future blocks, returning a
  272. // subscription object that can be used to tear down the watcher.
  273. func (c *BoundContract) WatchLogs(opts *WatchOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
  274. // Don't crash on a lazy user
  275. if opts == nil {
  276. opts = new(WatchOpts)
  277. }
  278. // Append the event selector to the query parameters and construct the topic set
  279. query = append([][]interface{}{{c.abi.Events[name].ID()}}, query...)
  280. topics, err := makeTopics(query...)
  281. if err != nil {
  282. return nil, nil, err
  283. }
  284. // Start the background filtering
  285. logs := make(chan types.Log, 128)
  286. config := ethereum.FilterQuery{
  287. Addresses: []common.Address{c.address},
  288. Topics: topics,
  289. }
  290. if opts.Start != nil {
  291. config.FromBlock = new(big.Int).SetUint64(*opts.Start)
  292. }
  293. sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
  294. if err != nil {
  295. return nil, nil, err
  296. }
  297. return logs, sub, nil
  298. }
  299. // UnpackLog unpacks a retrieved log into the provided output structure.
  300. func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) error {
  301. if len(log.Data) > 0 {
  302. if err := c.abi.Unpack(out, event, log.Data); err != nil {
  303. return err
  304. }
  305. }
  306. var indexed abi.Arguments
  307. for _, arg := range c.abi.Events[event].Inputs {
  308. if arg.Indexed {
  309. indexed = append(indexed, arg)
  310. }
  311. }
  312. return parseTopics(out, indexed, log.Topics[1:])
  313. }
  314. // UnpackLogIntoMap unpacks a retrieved log into the provided map.
  315. func (c *BoundContract) UnpackLogIntoMap(out map[string]interface{}, event string, log types.Log) error {
  316. if len(log.Data) > 0 {
  317. if err := c.abi.UnpackIntoMap(out, event, log.Data); err != nil {
  318. return err
  319. }
  320. }
  321. var indexed abi.Arguments
  322. for _, arg := range c.abi.Events[event].Inputs {
  323. if arg.Indexed {
  324. indexed = append(indexed, arg)
  325. }
  326. }
  327. return parseTopicsIntoMap(out, indexed, log.Topics[1:])
  328. }
  329. // ensureContext is a helper method to ensure a context is not nil, even if the
  330. // user specified it as such.
  331. func ensureContext(ctx context.Context) context.Context {
  332. if ctx == nil {
  333. return context.TODO()
  334. }
  335. return ctx
  336. }