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