base.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. )
  28. // SignerFn is a signer function callback when a contract requires a method to
  29. // sign the transaction before submission.
  30. type SignerFn func(types.Signer, common.Address, *types.Transaction) (*types.Transaction, error)
  31. // CallOpts is the collection of options to fine tune a contract call request.
  32. type CallOpts struct {
  33. Pending bool // Whether to operate on the pending state or the last known one
  34. From common.Address // Optional the sender address, otherwise the first account is used
  35. Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
  36. }
  37. // TransactOpts is the collection of authorization data required to create a
  38. // valid Ethereum transaction.
  39. type TransactOpts struct {
  40. From common.Address // Ethereum account to send the transaction from
  41. Nonce *big.Int // Nonce to use for the transaction execution (nil = use pending state)
  42. Signer SignerFn // Method to use for signing the transaction (mandatory)
  43. Value *big.Int // Funds to transfer along along the transaction (nil = 0 = no funds)
  44. GasPrice *big.Int // Gas price to use for the transaction execution (nil = gas price oracle)
  45. GasLimit uint64 // Gas limit to set for the transaction execution (0 = estimate)
  46. Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
  47. }
  48. // BoundContract is the base wrapper object that reflects a contract on the
  49. // Ethereum network. It contains a collection of methods that are used by the
  50. // higher level contract bindings to operate.
  51. type BoundContract struct {
  52. address common.Address // Deployment address of the contract on the Ethereum blockchain
  53. abi abi.ABI // Reflect based ABI to access the correct Ethereum methods
  54. caller ContractCaller // Read interface to interact with the blockchain
  55. transactor ContractTransactor // Write interface to interact with the blockchain
  56. }
  57. // NewBoundContract creates a low level contract interface through which calls
  58. // and transactions may be made through.
  59. func NewBoundContract(address common.Address, abi abi.ABI, caller ContractCaller, transactor ContractTransactor) *BoundContract {
  60. return &BoundContract{
  61. address: address,
  62. abi: abi,
  63. caller: caller,
  64. transactor: transactor,
  65. }
  66. }
  67. // DeployContract deploys a contract onto the Ethereum blockchain and binds the
  68. // deployment address with a Go wrapper.
  69. func DeployContract(opts *TransactOpts, abi abi.ABI, bytecode []byte, backend ContractBackend, params ...interface{}) (common.Address, *types.Transaction, *BoundContract, error) {
  70. // Otherwise try to deploy the contract
  71. c := NewBoundContract(common.Address{}, abi, backend, backend)
  72. input, err := c.abi.Pack("", params...)
  73. if err != nil {
  74. return common.Address{}, nil, nil, err
  75. }
  76. tx, err := c.transact(opts, nil, append(bytecode, input...))
  77. if err != nil {
  78. return common.Address{}, nil, nil, err
  79. }
  80. c.address = crypto.CreateAddress(opts.From, tx.Nonce())
  81. return c.address, tx, c, nil
  82. }
  83. // Call invokes the (constant) contract method with params as input values and
  84. // sets the output to result. The result type might be a single field for simple
  85. // returns, a slice of interfaces for anonymous returns and a struct for named
  86. // returns.
  87. func (c *BoundContract) Call(opts *CallOpts, result interface{}, method string, params ...interface{}) error {
  88. // Don't crash on a lazy user
  89. if opts == nil {
  90. opts = new(CallOpts)
  91. }
  92. // Pack the input, call and unpack the results
  93. input, err := c.abi.Pack(method, params...)
  94. if err != nil {
  95. return err
  96. }
  97. var (
  98. msg = ethereum.CallMsg{From: opts.From, To: &c.address, Data: input}
  99. ctx = ensureContext(opts.Context)
  100. code []byte
  101. output []byte
  102. )
  103. if opts.Pending {
  104. pb, ok := c.caller.(PendingContractCaller)
  105. if !ok {
  106. return ErrNoPendingState
  107. }
  108. output, err = pb.PendingCallContract(ctx, msg)
  109. if err == nil && len(output) == 0 {
  110. // Make sure we have a contract to operate on, and bail out otherwise.
  111. if code, err = pb.PendingCodeAt(ctx, c.address); err != nil {
  112. return err
  113. } else if len(code) == 0 {
  114. return ErrNoCode
  115. }
  116. }
  117. } else {
  118. output, err = c.caller.CallContract(ctx, msg, nil)
  119. if err == nil && len(output) == 0 {
  120. // Make sure we have a contract to operate on, and bail out otherwise.
  121. if code, err = c.caller.CodeAt(ctx, c.address, nil); err != nil {
  122. return err
  123. } else if len(code) == 0 {
  124. return ErrNoCode
  125. }
  126. }
  127. }
  128. if err != nil {
  129. return err
  130. }
  131. return c.abi.Unpack(result, method, output)
  132. }
  133. // Transact invokes the (paid) contract method with params as input values.
  134. func (c *BoundContract) Transact(opts *TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
  135. // Otherwise pack up the parameters and invoke the contract
  136. input, err := c.abi.Pack(method, params...)
  137. if err != nil {
  138. return nil, err
  139. }
  140. return c.transact(opts, &c.address, input)
  141. }
  142. // Transfer initiates a plain transaction to move funds to the contract, calling
  143. // its default method if one is available.
  144. func (c *BoundContract) Transfer(opts *TransactOpts) (*types.Transaction, error) {
  145. return c.transact(opts, &c.address, nil)
  146. }
  147. // transact executes an actual transaction invocation, first deriving any missing
  148. // authorization fields, and then scheduling the transaction for execution.
  149. func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error) {
  150. var err error
  151. // Ensure a valid value field and resolve the account nonce
  152. value := opts.Value
  153. if value == nil {
  154. value = new(big.Int)
  155. }
  156. var nonce uint64
  157. if opts.Nonce == nil {
  158. nonce, err = c.transactor.PendingNonceAt(ensureContext(opts.Context), opts.From)
  159. if err != nil {
  160. return nil, fmt.Errorf("failed to retrieve account nonce: %v", err)
  161. }
  162. } else {
  163. nonce = opts.Nonce.Uint64()
  164. }
  165. // Figure out the gas allowance and gas price values
  166. gasPrice := opts.GasPrice
  167. if gasPrice == nil {
  168. gasPrice, err = c.transactor.SuggestGasPrice(ensureContext(opts.Context))
  169. if err != nil {
  170. return nil, fmt.Errorf("failed to suggest gas price: %v", err)
  171. }
  172. }
  173. gasLimit := opts.GasLimit
  174. if gasLimit == 0 {
  175. // Gas estimation cannot succeed without code for method invocations
  176. if contract != nil {
  177. if code, err := c.transactor.PendingCodeAt(ensureContext(opts.Context), c.address); err != nil {
  178. return nil, err
  179. } else if len(code) == 0 {
  180. return nil, ErrNoCode
  181. }
  182. }
  183. // If the contract surely has code (or code is not needed), estimate the transaction
  184. msg := ethereum.CallMsg{From: opts.From, To: contract, Value: value, Data: input}
  185. gasLimit, err = c.transactor.EstimateGas(ensureContext(opts.Context), msg)
  186. if err != nil {
  187. return nil, fmt.Errorf("failed to estimate gas needed: %v", err)
  188. }
  189. }
  190. // Create the transaction, sign it and schedule it for execution
  191. var rawTx *types.Transaction
  192. if contract == nil {
  193. rawTx = types.NewContractCreation(nonce, value, gasLimit, gasPrice, input)
  194. } else {
  195. rawTx = types.NewTransaction(nonce, c.address, value, gasLimit, gasPrice, input)
  196. }
  197. if opts.Signer == nil {
  198. return nil, errors.New("no signer to authorize the transaction with")
  199. }
  200. signedTx, err := opts.Signer(types.HomesteadSigner{}, opts.From, rawTx)
  201. if err != nil {
  202. return nil, err
  203. }
  204. if err := c.transactor.SendTransaction(ensureContext(opts.Context), signedTx); err != nil {
  205. return nil, err
  206. }
  207. return signedTx, nil
  208. }
  209. func ensureContext(ctx context.Context) context.Context {
  210. if ctx == nil {
  211. return context.TODO()
  212. }
  213. return ctx
  214. }