github.com/codingfuture/orig-energi3@v0.8.4/accounts/abi/bind/base.go (about) 1 // Copyright 2018 The Energi Core Authors 2 // Copyright 2015 The go-ethereum Authors 3 // This file is part of the Energi Core library. 4 // 5 // The Energi Core library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The Energi Core library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the Energi Core library. If not, see <http://www.gnu.org/licenses/>. 17 18 package bind 19 20 import ( 21 "context" 22 "errors" 23 "fmt" 24 "math/big" 25 26 "github.com/ethereum/go-ethereum" 27 "github.com/ethereum/go-ethereum/accounts/abi" 28 "github.com/ethereum/go-ethereum/common" 29 "github.com/ethereum/go-ethereum/core/types" 30 "github.com/ethereum/go-ethereum/crypto" 31 "github.com/ethereum/go-ethereum/event" 32 ) 33 34 // SignerFn is a signer function callback when a contract requires a method to 35 // sign the transaction before submission. 36 type SignerFn func(types.Signer, common.Address, *types.Transaction) (*types.Transaction, error) 37 38 // CallOpts is the collection of options to fine tune a contract call request. 39 type CallOpts struct { 40 Pending bool // Whether to operate on the pending state or the last known one 41 From common.Address // Optional the sender address, otherwise the first account is used 42 BlockNumber *big.Int // Optional the block number on which the call should be performed 43 Context context.Context // Network context to support cancellation and timeouts (nil = no timeout) 44 GasLimit uint64 // Gas limit to set for the call execution (0 = default) 45 } 46 47 // TransactOpts is the collection of authorization data required to create a 48 // valid Ethereum transaction. 49 type TransactOpts struct { 50 From common.Address // Ethereum account to send the transaction from 51 Nonce *big.Int // Nonce to use for the transaction execution (nil = use pending state) 52 Signer SignerFn // Method to use for signing the transaction (mandatory) 53 54 Value *big.Int // Funds to transfer along along the transaction (nil = 0 = no funds) 55 GasPrice *big.Int // Gas price to use for the transaction execution (nil = gas price oracle) 56 GasLimit uint64 // Gas limit to set for the transaction execution (0 = estimate) 57 58 Context context.Context // Network context to support cancellation and timeouts (nil = no timeout) 59 } 60 61 // FilterOpts is the collection of options to fine tune filtering for events 62 // within a bound contract. 63 type FilterOpts struct { 64 Start uint64 // Start of the queried range 65 End *uint64 // End of the range (nil = latest) 66 67 Context context.Context // Network context to support cancellation and timeouts (nil = no timeout) 68 } 69 70 // WatchOpts is the collection of options to fine tune subscribing for events 71 // within a bound contract. 72 type WatchOpts struct { 73 Start *uint64 // Start of the queried range (nil = latest) 74 Context context.Context // Network context to support cancellation and timeouts (nil = no timeout) 75 } 76 77 // BoundContract is the base wrapper object that reflects a contract on the 78 // Ethereum network. It contains a collection of methods that are used by the 79 // higher level contract bindings to operate. 80 type BoundContract struct { 81 address common.Address // Deployment address of the contract on the Ethereum blockchain 82 abi abi.ABI // Reflect based ABI to access the correct Ethereum methods 83 caller ContractCaller // Read interface to interact with the blockchain 84 transactor ContractTransactor // Write interface to interact with the blockchain 85 filterer ContractFilterer // Event filtering to interact with the blockchain 86 } 87 88 // NewBoundContract creates a low level contract interface through which calls 89 // and transactions may be made through. 90 func NewBoundContract(address common.Address, abi abi.ABI, caller ContractCaller, transactor ContractTransactor, filterer ContractFilterer) *BoundContract { 91 return &BoundContract{ 92 address: address, 93 abi: abi, 94 caller: caller, 95 transactor: transactor, 96 filterer: filterer, 97 } 98 } 99 100 // DeployContract deploys a contract onto the Ethereum blockchain and binds the 101 // deployment address with a Go wrapper. 102 func DeployContract(opts *TransactOpts, abi abi.ABI, bytecode []byte, backend ContractBackend, params ...interface{}) (common.Address, *types.Transaction, *BoundContract, error) { 103 // Otherwise try to deploy the contract 104 c := NewBoundContract(common.Address{}, abi, backend, backend, backend) 105 106 input, err := c.abi.Pack("", params...) 107 if err != nil { 108 return common.Address{}, nil, nil, err 109 } 110 tx, err := c.transact(opts, nil, append(bytecode, input...)) 111 if err != nil { 112 return common.Address{}, nil, nil, err 113 } 114 c.address = crypto.CreateAddress(opts.From, tx.Nonce()) 115 return c.address, tx, c, nil 116 } 117 118 // Call invokes the (constant) contract method with params as input values and 119 // sets the output to result. The result type might be a single field for simple 120 // returns, a slice of interfaces for anonymous returns and a struct for named 121 // returns. 122 func (c *BoundContract) Call(opts *CallOpts, result interface{}, method string, params ...interface{}) error { 123 // Don't crash on a lazy user 124 if opts == nil { 125 opts = new(CallOpts) 126 } 127 // Pack the input, call and unpack the results 128 input, err := c.abi.Pack(method, params...) 129 if err != nil { 130 return err 131 } 132 var ( 133 msg = ethereum.CallMsg{From: opts.From, To: &c.address, Data: input, Gas: opts.GasLimit} 134 ctx = ensureContext(opts.Context) 135 code []byte 136 output []byte 137 ) 138 if opts.Pending { 139 pb, ok := c.caller.(PendingContractCaller) 140 if !ok { 141 return ErrNoPendingState 142 } 143 output, err = pb.PendingCallContract(ctx, msg) 144 if err == nil && len(output) == 0 { 145 // Make sure we have a contract to operate on, and bail out otherwise. 146 if code, err = pb.PendingCodeAt(ctx, c.address); err != nil { 147 return err 148 } else if len(code) == 0 { 149 return ErrNoCode 150 } 151 } 152 } else { 153 output, err = c.caller.CallContract(ctx, msg, opts.BlockNumber) 154 if err == nil && len(output) == 0 { 155 // Make sure we have a contract to operate on, and bail out otherwise. 156 if code, err = c.caller.CodeAt(ctx, c.address, opts.BlockNumber); err != nil { 157 return err 158 } else if len(code) == 0 { 159 return ErrNoCode 160 } 161 } 162 } 163 if err != nil { 164 return err 165 } 166 return c.abi.Unpack(result, method, output) 167 } 168 169 // Transact invokes the (paid) contract method with params as input values. 170 func (c *BoundContract) Transact(opts *TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { 171 // Otherwise pack up the parameters and invoke the contract 172 input, err := c.abi.Pack(method, params...) 173 if err != nil { 174 return nil, err 175 } 176 return c.transact(opts, &c.address, input) 177 } 178 179 // Transfer initiates a plain transaction to move funds to the contract, calling 180 // its default method if one is available. 181 func (c *BoundContract) Transfer(opts *TransactOpts) (*types.Transaction, error) { 182 return c.transact(opts, &c.address, nil) 183 } 184 185 // transact executes an actual transaction invocation, first deriving any missing 186 // authorization fields, and then scheduling the transaction for execution. 187 func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error) { 188 var err error 189 190 // Ensure a valid value field and resolve the account nonce 191 value := opts.Value 192 if value == nil { 193 value = new(big.Int) 194 } 195 var nonce uint64 196 if opts.Nonce == nil { 197 nonce, err = c.transactor.PendingNonceAt(ensureContext(opts.Context), opts.From) 198 if err != nil { 199 return nil, fmt.Errorf("failed to retrieve account nonce: %v", err) 200 } 201 } else { 202 nonce = opts.Nonce.Uint64() 203 } 204 // Figure out the gas allowance and gas price values 205 gasPrice := opts.GasPrice 206 if gasPrice == nil { 207 gasPrice, err = c.transactor.SuggestGasPrice(ensureContext(opts.Context)) 208 if err != nil { 209 return nil, fmt.Errorf("failed to suggest gas price: %v", err) 210 } 211 } 212 gasLimit := opts.GasLimit 213 if gasLimit == 0 { 214 // Gas estimation cannot succeed without code for method invocations 215 if contract != nil { 216 if code, err := c.transactor.PendingCodeAt(ensureContext(opts.Context), c.address); err != nil { 217 return nil, err 218 } else if len(code) == 0 { 219 return nil, ErrNoCode 220 } 221 } 222 // If the contract surely has code (or code is not needed), estimate the transaction 223 msg := ethereum.CallMsg{From: opts.From, To: contract, Value: value, Data: input} 224 gasLimit, err = c.transactor.EstimateGas(ensureContext(opts.Context), msg) 225 if err != nil { 226 return nil, fmt.Errorf("failed to estimate gas needed: %v", err) 227 } 228 } 229 // Create the transaction, sign it and schedule it for execution 230 var rawTx *types.Transaction 231 if contract == nil { 232 rawTx = types.NewContractCreation(nonce, value, gasLimit, gasPrice, input) 233 } else { 234 rawTx = types.NewTransaction(nonce, c.address, value, gasLimit, gasPrice, input) 235 } 236 if opts.Signer == nil { 237 return nil, errors.New("no signer to authorize the transaction with") 238 } 239 signedTx, err := opts.Signer(types.HomesteadSigner{}, opts.From, rawTx) 240 if err != nil { 241 return nil, err 242 } 243 if err := c.transactor.SendTransaction(ensureContext(opts.Context), signedTx); err != nil { 244 return nil, err 245 } 246 return signedTx, nil 247 } 248 249 // FilterLogs filters contract logs for past blocks, returning the necessary 250 // channels to construct a strongly typed bound iterator on top of them. 251 func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) { 252 // Don't crash on a lazy user 253 if opts == nil { 254 opts = new(FilterOpts) 255 } 256 // Append the event selector to the query parameters and construct the topic set 257 query = append([][]interface{}{{c.abi.Events[name].Id()}}, query...) 258 259 topics, err := makeTopics(query...) 260 if err != nil { 261 return nil, nil, err 262 } 263 // Start the background filtering 264 logs := make(chan types.Log, 128) 265 266 config := ethereum.FilterQuery{ 267 Addresses: []common.Address{c.address}, 268 Topics: topics, 269 FromBlock: new(big.Int).SetUint64(opts.Start), 270 } 271 if opts.End != nil { 272 config.ToBlock = new(big.Int).SetUint64(*opts.End) 273 } 274 /* TODO(karalabe): Replace the rest of the method below with this when supported 275 sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs) 276 */ 277 buff, err := c.filterer.FilterLogs(ensureContext(opts.Context), config) 278 if err != nil { 279 return nil, nil, err 280 } 281 sub, err := event.NewSubscription(func(quit <-chan struct{}) error { 282 for _, log := range buff { 283 select { 284 case logs <- log: 285 case <-quit: 286 return nil 287 } 288 } 289 return nil 290 }), nil 291 292 if err != nil { 293 return nil, nil, err 294 } 295 return logs, sub, nil 296 } 297 298 // WatchLogs filters subscribes to contract logs for future blocks, returning a 299 // subscription object that can be used to tear down the watcher. 300 func (c *BoundContract) WatchLogs(opts *WatchOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) { 301 // Don't crash on a lazy user 302 if opts == nil { 303 opts = new(WatchOpts) 304 } 305 // Append the event selector to the query parameters and construct the topic set 306 query = append([][]interface{}{{c.abi.Events[name].Id()}}, query...) 307 308 topics, err := makeTopics(query...) 309 if err != nil { 310 return nil, nil, err 311 } 312 // Start the background filtering 313 logs := make(chan types.Log, 128) 314 315 config := ethereum.FilterQuery{ 316 Addresses: []common.Address{c.address}, 317 Topics: topics, 318 } 319 if opts.Start != nil { 320 config.FromBlock = new(big.Int).SetUint64(*opts.Start) 321 } 322 sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs) 323 if err != nil { 324 return nil, nil, err 325 } 326 return logs, sub, nil 327 } 328 329 // UnpackLog unpacks a retrieved log into the provided output structure. 330 func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) error { 331 if len(log.Data) > 0 { 332 if err := c.abi.Unpack(out, event, log.Data); err != nil { 333 return err 334 } 335 } 336 var indexed abi.Arguments 337 for _, arg := range c.abi.Events[event].Inputs { 338 if arg.Indexed { 339 indexed = append(indexed, arg) 340 } 341 } 342 return parseTopics(out, indexed, log.Topics[1:]) 343 } 344 345 // ensureContext is a helper method to ensure a context is not nil, even if the 346 // user specified it as such. 347 func ensureContext(ctx context.Context) context.Context { 348 if ctx == nil { 349 return context.TODO() 350 } 351 return ctx 352 }