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