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