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