base.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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 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. // todo(rjl493456442) check the method is payable or not,
  158. // reject invalid transaction at the first place
  159. return c.transact(opts, &c.address, input)
  160. }
  161. // RawTransact initiates a transaction with the given raw calldata as the input.
  162. // It's usually used to initiate transactions for invoking **Fallback** function.
  163. func (c *BoundContract) RawTransact(opts *TransactOpts, calldata []byte) (*types.Transaction, error) {
  164. // todo(rjl493456442) check the method is payable or not,
  165. // reject invalid transaction at the first place
  166. return c.transact(opts, &c.address, calldata)
  167. }
  168. // Transfer initiates a plain transaction to move funds to the contract, calling
  169. // its default method if one is available.
  170. func (c *BoundContract) Transfer(opts *TransactOpts) (*types.Transaction, error) {
  171. // todo(rjl493456442) check the payable fallback or receive is defined
  172. // or not, reject invalid transaction at the first place
  173. return c.transact(opts, &c.address, nil)
  174. }
  175. // transact executes an actual transaction invocation, first deriving any missing
  176. // authorization fields, and then scheduling the transaction for execution.
  177. func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error) {
  178. var err error
  179. // Ensure a valid value field and resolve the account nonce
  180. value := opts.Value
  181. if value == nil {
  182. value = new(big.Int)
  183. }
  184. var nonce uint64
  185. if opts.Nonce == nil {
  186. nonce, err = c.transactor.PendingNonceAt(ensureContext(opts.Context), opts.From)
  187. if err != nil {
  188. return nil, fmt.Errorf("failed to retrieve account nonce: %v", err)
  189. }
  190. } else {
  191. nonce = opts.Nonce.Uint64()
  192. }
  193. // Figure out the gas allowance and gas price values
  194. gasPrice := opts.GasPrice
  195. if gasPrice == nil {
  196. gasPrice, err = c.transactor.SuggestGasPrice(ensureContext(opts.Context))
  197. if err != nil {
  198. return nil, fmt.Errorf("failed to suggest gas price: %v", err)
  199. }
  200. }
  201. gasLimit := opts.GasLimit
  202. if gasLimit == 0 {
  203. // Gas estimation cannot succeed without code for method invocations
  204. if contract != nil {
  205. if code, err := c.transactor.PendingCodeAt(ensureContext(opts.Context), c.address); err != nil {
  206. return nil, err
  207. } else if len(code) == 0 {
  208. return nil, ErrNoCode
  209. }
  210. }
  211. // If the contract surely has code (or code is not needed), estimate the transaction
  212. msg := ethereum.CallMsg{From: opts.From, To: contract, GasPrice: gasPrice, Value: value, Data: input}
  213. gasLimit, err = c.transactor.EstimateGas(ensureContext(opts.Context), msg)
  214. if err != nil {
  215. return nil, fmt.Errorf("failed to estimate gas needed: %v", err)
  216. }
  217. }
  218. // Create the transaction, sign it and schedule it for execution
  219. var rawTx *types.Transaction
  220. if contract == nil {
  221. rawTx = types.NewContractCreation(nonce, value, gasLimit, gasPrice, input)
  222. } else {
  223. rawTx = types.NewTransaction(nonce, c.address, value, gasLimit, gasPrice, input)
  224. }
  225. if opts.Signer == nil {
  226. return nil, errors.New("no signer to authorize the transaction with")
  227. }
  228. signedTx, err := opts.Signer(types.HomesteadSigner{}, opts.From, rawTx)
  229. if err != nil {
  230. return nil, err
  231. }
  232. if err := c.transactor.SendTransaction(ensureContext(opts.Context), signedTx); err != nil {
  233. return nil, err
  234. }
  235. return signedTx, nil
  236. }
  237. // FilterLogs filters contract logs for past blocks, returning the necessary
  238. // channels to construct a strongly typed bound iterator on top of them.
  239. func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
  240. // Don't crash on a lazy user
  241. if opts == nil {
  242. opts = new(FilterOpts)
  243. }
  244. // Append the event selector to the query parameters and construct the topic set
  245. query = append([][]interface{}{{c.abi.Events[name].ID}}, query...)
  246. topics, err := abi.MakeTopics(query...)
  247. if err != nil {
  248. return nil, nil, err
  249. }
  250. // Start the background filtering
  251. logs := make(chan types.Log, 128)
  252. config := ethereum.FilterQuery{
  253. Addresses: []common.Address{c.address},
  254. Topics: topics,
  255. FromBlock: new(big.Int).SetUint64(opts.Start),
  256. }
  257. if opts.End != nil {
  258. config.ToBlock = new(big.Int).SetUint64(*opts.End)
  259. }
  260. /* TODO(karalabe): Replace the rest of the method below with this when supported
  261. sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
  262. */
  263. buff, err := c.filterer.FilterLogs(ensureContext(opts.Context), config)
  264. if err != nil {
  265. return nil, nil, err
  266. }
  267. sub, err := event.NewSubscription(func(quit <-chan struct{}) error {
  268. for _, log := range buff {
  269. select {
  270. case logs <- log:
  271. case <-quit:
  272. return nil
  273. }
  274. }
  275. return nil
  276. }), nil
  277. if err != nil {
  278. return nil, nil, err
  279. }
  280. return logs, sub, nil
  281. }
  282. // WatchLogs filters subscribes to contract logs for future blocks, returning a
  283. // subscription object that can be used to tear down the watcher.
  284. func (c *BoundContract) WatchLogs(opts *WatchOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
  285. // Don't crash on a lazy user
  286. if opts == nil {
  287. opts = new(WatchOpts)
  288. }
  289. // Append the event selector to the query parameters and construct the topic set
  290. query = append([][]interface{}{{c.abi.Events[name].ID}}, query...)
  291. topics, err := abi.MakeTopics(query...)
  292. if err != nil {
  293. return nil, nil, err
  294. }
  295. // Start the background filtering
  296. logs := make(chan types.Log, 128)
  297. config := ethereum.FilterQuery{
  298. Addresses: []common.Address{c.address},
  299. Topics: topics,
  300. }
  301. if opts.Start != nil {
  302. config.FromBlock = new(big.Int).SetUint64(*opts.Start)
  303. }
  304. sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
  305. if err != nil {
  306. return nil, nil, err
  307. }
  308. return logs, sub, nil
  309. }
  310. // UnpackLog unpacks a retrieved log into the provided output structure.
  311. func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) error {
  312. if len(log.Data) > 0 {
  313. if err := c.abi.Unpack(out, event, log.Data); err != nil {
  314. return err
  315. }
  316. }
  317. var indexed abi.Arguments
  318. for _, arg := range c.abi.Events[event].Inputs {
  319. if arg.Indexed {
  320. indexed = append(indexed, arg)
  321. }
  322. }
  323. return abi.ParseTopics(out, indexed, log.Topics[1:])
  324. }
  325. // UnpackLogIntoMap unpacks a retrieved log into the provided map.
  326. func (c *BoundContract) UnpackLogIntoMap(out map[string]interface{}, event string, log types.Log) error {
  327. if len(log.Data) > 0 {
  328. if err := c.abi.UnpackIntoMap(out, event, log.Data); err != nil {
  329. return err
  330. }
  331. }
  332. var indexed abi.Arguments
  333. for _, arg := range c.abi.Events[event].Inputs {
  334. if arg.Indexed {
  335. indexed = append(indexed, arg)
  336. }
  337. }
  338. return abi.ParseTopicsIntoMap(out, indexed, log.Topics[1:])
  339. }
  340. // ensureContext is a helper method to ensure a context is not nil, even if the
  341. // user specified it as such.
  342. func ensureContext(ctx context.Context) context.Context {
  343. if ctx == nil {
  344. return context.TODO()
  345. }
  346. return ctx
  347. }