base.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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. "strings"
  23. "sync"
  24. "github.com/ethereum/go-ethereum"
  25. "github.com/ethereum/go-ethereum/accounts/abi"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/core/types"
  28. "github.com/ethereum/go-ethereum/crypto"
  29. "github.com/ethereum/go-ethereum/event"
  30. )
  31. // SignerFn is a signer function callback when a contract requires a method to
  32. // sign the transaction before submission.
  33. type SignerFn func(common.Address, *types.Transaction) (*types.Transaction, error)
  34. // CallOpts is the collection of options to fine tune a contract call request.
  35. type CallOpts struct {
  36. Pending bool // Whether to operate on the pending state or the last known one
  37. From common.Address // Optional the sender address, otherwise the first account is used
  38. BlockNumber *big.Int // Optional the block number on which the call should be performed
  39. Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
  40. }
  41. // TransactOpts is the collection of authorization data required to create a
  42. // valid Ethereum transaction.
  43. type TransactOpts struct {
  44. From common.Address // Ethereum account to send the transaction from
  45. Nonce *big.Int // Nonce to use for the transaction execution (nil = use pending state)
  46. Signer SignerFn // Method to use for signing the transaction (mandatory)
  47. Value *big.Int // Funds to transfer along the transaction (nil = 0 = no funds)
  48. GasPrice *big.Int // Gas price to use for the transaction execution (nil = gas price oracle)
  49. GasFeeCap *big.Int // Gas fee cap to use for the 1559 transaction execution (nil = gas price oracle)
  50. GasTipCap *big.Int // Gas priority fee cap to use for the 1559 transaction execution (nil = gas price oracle)
  51. GasLimit uint64 // Gas limit to set for the transaction execution (0 = estimate)
  52. Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
  53. NoSend bool // Do all transact steps but do not send the transaction
  54. }
  55. // FilterOpts is the collection of options to fine tune filtering for events
  56. // within a bound contract.
  57. type FilterOpts struct {
  58. Start uint64 // Start of the queried range
  59. End *uint64 // End of the range (nil = latest)
  60. Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
  61. }
  62. // WatchOpts is the collection of options to fine tune subscribing for events
  63. // within a bound contract.
  64. type WatchOpts struct {
  65. Start *uint64 // Start of the queried range (nil = latest)
  66. Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
  67. }
  68. // MetaData collects all metadata for a bound contract.
  69. type MetaData struct {
  70. mu sync.Mutex
  71. Sigs map[string]string
  72. Bin string
  73. ABI string
  74. ab *abi.ABI
  75. }
  76. func (m *MetaData) GetAbi() (*abi.ABI, error) {
  77. m.mu.Lock()
  78. defer m.mu.Unlock()
  79. if m.ab != nil {
  80. return m.ab, nil
  81. }
  82. if parsed, err := abi.JSON(strings.NewReader(m.ABI)); err != nil {
  83. return nil, err
  84. } else {
  85. m.ab = &parsed
  86. }
  87. return m.ab, nil
  88. }
  89. // BoundContract is the base wrapper object that reflects a contract on the
  90. // Ethereum network. It contains a collection of methods that are used by the
  91. // higher level contract bindings to operate.
  92. type BoundContract struct {
  93. address common.Address // Deployment address of the contract on the Ethereum blockchain
  94. abi abi.ABI // Reflect based ABI to access the correct Ethereum methods
  95. caller ContractCaller // Read interface to interact with the blockchain
  96. transactor ContractTransactor // Write interface to interact with the blockchain
  97. filterer ContractFilterer // Event filtering to interact with the blockchain
  98. }
  99. // NewBoundContract creates a low level contract interface through which calls
  100. // and transactions may be made through.
  101. func NewBoundContract(address common.Address, abi abi.ABI, caller ContractCaller, transactor ContractTransactor, filterer ContractFilterer) *BoundContract {
  102. return &BoundContract{
  103. address: address,
  104. abi: abi,
  105. caller: caller,
  106. transactor: transactor,
  107. filterer: filterer,
  108. }
  109. }
  110. // DeployContract deploys a contract onto the Ethereum blockchain and binds the
  111. // deployment address with a Go wrapper.
  112. func DeployContract(opts *TransactOpts, abi abi.ABI, bytecode []byte, backend ContractBackend, params ...interface{}) (common.Address, *types.Transaction, *BoundContract, error) {
  113. // Otherwise try to deploy the contract
  114. c := NewBoundContract(common.Address{}, abi, backend, backend, backend)
  115. input, err := c.abi.Pack("", params...)
  116. if err != nil {
  117. return common.Address{}, nil, nil, err
  118. }
  119. tx, err := c.transact(opts, nil, append(bytecode, input...))
  120. if err != nil {
  121. return common.Address{}, nil, nil, err
  122. }
  123. c.address = crypto.CreateAddress(opts.From, tx.Nonce())
  124. return c.address, tx, c, nil
  125. }
  126. // Call invokes the (constant) contract method with params as input values and
  127. // sets the output to result. The result type might be a single field for simple
  128. // returns, a slice of interfaces for anonymous returns and a struct for named
  129. // returns.
  130. func (c *BoundContract) Call(opts *CallOpts, results *[]interface{}, method string, params ...interface{}) error {
  131. // Don't crash on a lazy user
  132. if opts == nil {
  133. opts = new(CallOpts)
  134. }
  135. if results == nil {
  136. results = new([]interface{})
  137. }
  138. // Pack the input, call and unpack the results
  139. input, err := c.abi.Pack(method, params...)
  140. if err != nil {
  141. return err
  142. }
  143. var (
  144. msg = ethereum.CallMsg{From: opts.From, To: &c.address, Data: input}
  145. ctx = ensureContext(opts.Context)
  146. code []byte
  147. output []byte
  148. )
  149. if opts.Pending {
  150. pb, ok := c.caller.(PendingContractCaller)
  151. if !ok {
  152. return ErrNoPendingState
  153. }
  154. output, err = pb.PendingCallContract(ctx, msg)
  155. if err != nil {
  156. return err
  157. }
  158. if len(output) == 0 {
  159. // Make sure we have a contract to operate on, and bail out otherwise.
  160. if code, err = pb.PendingCodeAt(ctx, c.address); err != nil {
  161. return err
  162. } else if len(code) == 0 {
  163. return ErrNoCode
  164. }
  165. }
  166. } else {
  167. output, err = c.caller.CallContract(ctx, msg, opts.BlockNumber)
  168. if err != nil {
  169. return err
  170. }
  171. if len(output) == 0 {
  172. // Make sure we have a contract to operate on, and bail out otherwise.
  173. if code, err = c.caller.CodeAt(ctx, c.address, opts.BlockNumber); err != nil {
  174. return err
  175. } else if len(code) == 0 {
  176. return ErrNoCode
  177. }
  178. }
  179. }
  180. if len(*results) == 0 {
  181. res, err := c.abi.Unpack(method, output)
  182. *results = res
  183. return err
  184. }
  185. res := *results
  186. return c.abi.UnpackIntoInterface(res[0], method, output)
  187. }
  188. // Transact invokes the (paid) contract method with params as input values.
  189. func (c *BoundContract) Transact(opts *TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
  190. // Otherwise pack up the parameters and invoke the contract
  191. input, err := c.abi.Pack(method, params...)
  192. if err != nil {
  193. return nil, err
  194. }
  195. // todo(rjl493456442) check the method is payable or not,
  196. // reject invalid transaction at the first place
  197. return c.transact(opts, &c.address, input)
  198. }
  199. // RawTransact initiates a transaction with the given raw calldata as the input.
  200. // It's usually used to initiate transactions for invoking **Fallback** function.
  201. func (c *BoundContract) RawTransact(opts *TransactOpts, calldata []byte) (*types.Transaction, error) {
  202. // todo(rjl493456442) check the method is payable or not,
  203. // reject invalid transaction at the first place
  204. return c.transact(opts, &c.address, calldata)
  205. }
  206. // Transfer initiates a plain transaction to move funds to the contract, calling
  207. // its default method if one is available.
  208. func (c *BoundContract) Transfer(opts *TransactOpts) (*types.Transaction, error) {
  209. // todo(rjl493456442) check the payable fallback or receive is defined
  210. // or not, reject invalid transaction at the first place
  211. return c.transact(opts, &c.address, nil)
  212. }
  213. func (c *BoundContract) createDynamicTx(opts *TransactOpts, contract *common.Address, input []byte, head *types.Header) (*types.Transaction, error) {
  214. // Normalize value
  215. value := opts.Value
  216. if value == nil {
  217. value = new(big.Int)
  218. }
  219. // Estimate TipCap
  220. gasTipCap := opts.GasTipCap
  221. if gasTipCap == nil {
  222. tip, err := c.transactor.SuggestGasTipCap(ensureContext(opts.Context))
  223. if err != nil {
  224. return nil, err
  225. }
  226. gasTipCap = tip
  227. }
  228. // Estimate FeeCap
  229. gasFeeCap := opts.GasFeeCap
  230. if gasFeeCap == nil {
  231. gasFeeCap = new(big.Int).Add(
  232. gasTipCap,
  233. new(big.Int).Mul(head.BaseFee, big.NewInt(2)),
  234. )
  235. }
  236. if gasFeeCap.Cmp(gasTipCap) < 0 {
  237. return nil, fmt.Errorf("maxFeePerGas (%v) < maxPriorityFeePerGas (%v)", gasFeeCap, gasTipCap)
  238. }
  239. // Estimate GasLimit
  240. gasLimit := opts.GasLimit
  241. if opts.GasLimit == 0 {
  242. var err error
  243. gasLimit, err = c.estimateGasLimit(opts, contract, input, nil, gasTipCap, gasFeeCap, value)
  244. if err != nil {
  245. return nil, err
  246. }
  247. }
  248. // create the transaction
  249. nonce, err := c.getNonce(opts)
  250. if err != nil {
  251. return nil, err
  252. }
  253. baseTx := &types.DynamicFeeTx{
  254. To: contract,
  255. Nonce: nonce,
  256. GasFeeCap: gasFeeCap,
  257. GasTipCap: gasTipCap,
  258. Gas: gasLimit,
  259. Value: value,
  260. Data: input,
  261. }
  262. return types.NewTx(baseTx), nil
  263. }
  264. func (c *BoundContract) createLegacyTx(opts *TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error) {
  265. if opts.GasFeeCap != nil || opts.GasTipCap != nil {
  266. return nil, errors.New("maxFeePerGas or maxPriorityFeePerGas specified but london is not active yet")
  267. }
  268. // Normalize value
  269. value := opts.Value
  270. if value == nil {
  271. value = new(big.Int)
  272. }
  273. // Estimate GasPrice
  274. gasPrice := opts.GasPrice
  275. if gasPrice == nil {
  276. price, err := c.transactor.SuggestGasPrice(ensureContext(opts.Context))
  277. if err != nil {
  278. return nil, err
  279. }
  280. gasPrice = price
  281. }
  282. // Estimate GasLimit
  283. gasLimit := opts.GasLimit
  284. if opts.GasLimit == 0 {
  285. var err error
  286. gasLimit, err = c.estimateGasLimit(opts, contract, input, gasPrice, nil, nil, value)
  287. if err != nil {
  288. return nil, err
  289. }
  290. }
  291. // create the transaction
  292. nonce, err := c.getNonce(opts)
  293. if err != nil {
  294. return nil, err
  295. }
  296. baseTx := &types.LegacyTx{
  297. To: contract,
  298. Nonce: nonce,
  299. GasPrice: gasPrice,
  300. Gas: gasLimit,
  301. Value: value,
  302. Data: input,
  303. }
  304. return types.NewTx(baseTx), nil
  305. }
  306. func (c *BoundContract) estimateGasLimit(opts *TransactOpts, contract *common.Address, input []byte, gasPrice, gasTipCap, gasFeeCap, value *big.Int) (uint64, error) {
  307. if contract != nil {
  308. // Gas estimation cannot succeed without code for method invocations.
  309. if code, err := c.transactor.PendingCodeAt(ensureContext(opts.Context), c.address); err != nil {
  310. return 0, err
  311. } else if len(code) == 0 {
  312. return 0, ErrNoCode
  313. }
  314. }
  315. msg := ethereum.CallMsg{
  316. From: opts.From,
  317. To: contract,
  318. GasPrice: gasPrice,
  319. GasTipCap: gasTipCap,
  320. GasFeeCap: gasFeeCap,
  321. Value: value,
  322. Data: input,
  323. }
  324. return c.transactor.EstimateGas(ensureContext(opts.Context), msg)
  325. }
  326. func (c *BoundContract) getNonce(opts *TransactOpts) (uint64, error) {
  327. if opts.Nonce == nil {
  328. return c.transactor.PendingNonceAt(ensureContext(opts.Context), opts.From)
  329. } else {
  330. return opts.Nonce.Uint64(), nil
  331. }
  332. }
  333. // transact executes an actual transaction invocation, first deriving any missing
  334. // authorization fields, and then scheduling the transaction for execution.
  335. func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error) {
  336. if opts.GasPrice != nil && (opts.GasFeeCap != nil || opts.GasTipCap != nil) {
  337. return nil, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified")
  338. }
  339. // Create the transaction
  340. var (
  341. rawTx *types.Transaction
  342. err error
  343. )
  344. if opts.GasPrice != nil {
  345. rawTx, err = c.createLegacyTx(opts, contract, input)
  346. } else {
  347. // Only query for basefee if gasPrice not specified
  348. if head, errHead := c.transactor.HeaderByNumber(ensureContext(opts.Context), nil); errHead != nil {
  349. return nil, errHead
  350. } else if head.BaseFee != nil {
  351. rawTx, err = c.createDynamicTx(opts, contract, input, head)
  352. } else {
  353. // Chain is not London ready -> use legacy transaction
  354. rawTx, err = c.createLegacyTx(opts, contract, input)
  355. }
  356. }
  357. if err != nil {
  358. return nil, err
  359. }
  360. // Sign the transaction and schedule it for execution
  361. if opts.Signer == nil {
  362. return nil, errors.New("no signer to authorize the transaction with")
  363. }
  364. signedTx, err := opts.Signer(opts.From, rawTx)
  365. if err != nil {
  366. return nil, err
  367. }
  368. if opts.NoSend {
  369. return signedTx, nil
  370. }
  371. if err := c.transactor.SendTransaction(ensureContext(opts.Context), signedTx); err != nil {
  372. return nil, err
  373. }
  374. return signedTx, nil
  375. }
  376. // FilterLogs filters contract logs for past blocks, returning the necessary
  377. // channels to construct a strongly typed bound iterator on top of them.
  378. func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
  379. // Don't crash on a lazy user
  380. if opts == nil {
  381. opts = new(FilterOpts)
  382. }
  383. // Append the event selector to the query parameters and construct the topic set
  384. query = append([][]interface{}{{c.abi.Events[name].ID}}, query...)
  385. topics, err := abi.MakeTopics(query...)
  386. if err != nil {
  387. return nil, nil, err
  388. }
  389. // Start the background filtering
  390. logs := make(chan types.Log, 128)
  391. config := ethereum.FilterQuery{
  392. Addresses: []common.Address{c.address},
  393. Topics: topics,
  394. FromBlock: new(big.Int).SetUint64(opts.Start),
  395. }
  396. if opts.End != nil {
  397. config.ToBlock = new(big.Int).SetUint64(*opts.End)
  398. }
  399. /* TODO(karalabe): Replace the rest of the method below with this when supported
  400. sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
  401. */
  402. buff, err := c.filterer.FilterLogs(ensureContext(opts.Context), config)
  403. if err != nil {
  404. return nil, nil, err
  405. }
  406. sub, err := event.NewSubscription(func(quit <-chan struct{}) error {
  407. for _, log := range buff {
  408. select {
  409. case logs <- log:
  410. case <-quit:
  411. return nil
  412. }
  413. }
  414. return nil
  415. }), nil
  416. if err != nil {
  417. return nil, nil, err
  418. }
  419. return logs, sub, nil
  420. }
  421. // WatchLogs filters subscribes to contract logs for future blocks, returning a
  422. // subscription object that can be used to tear down the watcher.
  423. func (c *BoundContract) WatchLogs(opts *WatchOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
  424. // Don't crash on a lazy user
  425. if opts == nil {
  426. opts = new(WatchOpts)
  427. }
  428. // Append the event selector to the query parameters and construct the topic set
  429. query = append([][]interface{}{{c.abi.Events[name].ID}}, query...)
  430. topics, err := abi.MakeTopics(query...)
  431. if err != nil {
  432. return nil, nil, err
  433. }
  434. // Start the background filtering
  435. logs := make(chan types.Log, 128)
  436. config := ethereum.FilterQuery{
  437. Addresses: []common.Address{c.address},
  438. Topics: topics,
  439. }
  440. if opts.Start != nil {
  441. config.FromBlock = new(big.Int).SetUint64(*opts.Start)
  442. }
  443. sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
  444. if err != nil {
  445. return nil, nil, err
  446. }
  447. return logs, sub, nil
  448. }
  449. // UnpackLog unpacks a retrieved log into the provided output structure.
  450. func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) error {
  451. if log.Topics[0] != c.abi.Events[event].ID {
  452. return fmt.Errorf("event signature mismatch")
  453. }
  454. if len(log.Data) > 0 {
  455. if err := c.abi.UnpackIntoInterface(out, event, log.Data); err != nil {
  456. return err
  457. }
  458. }
  459. var indexed abi.Arguments
  460. for _, arg := range c.abi.Events[event].Inputs {
  461. if arg.Indexed {
  462. indexed = append(indexed, arg)
  463. }
  464. }
  465. return abi.ParseTopics(out, indexed, log.Topics[1:])
  466. }
  467. // UnpackLogIntoMap unpacks a retrieved log into the provided map.
  468. func (c *BoundContract) UnpackLogIntoMap(out map[string]interface{}, event string, log types.Log) error {
  469. if log.Topics[0] != c.abi.Events[event].ID {
  470. return fmt.Errorf("event signature mismatch")
  471. }
  472. if len(log.Data) > 0 {
  473. if err := c.abi.UnpackIntoMap(out, event, log.Data); err != nil {
  474. return err
  475. }
  476. }
  477. var indexed abi.Arguments
  478. for _, arg := range c.abi.Events[event].Inputs {
  479. if arg.Indexed {
  480. indexed = append(indexed, arg)
  481. }
  482. }
  483. return abi.ParseTopicsIntoMap(out, indexed, log.Topics[1:])
  484. }
  485. // ensureContext is a helper method to ensure a context is not nil, even if the
  486. // user specified it as such.
  487. func ensureContext(ctx context.Context) context.Context {
  488. if ctx == nil {
  489. return context.Background()
  490. }
  491. return ctx
  492. }