base.go 8.4 KB

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