github.com/0xsequence/ethkit@v1.25.0/go-ethereum/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/0xsequence/ethkit/go-ethereum" 28 "github.com/0xsequence/ethkit/go-ethereum/accounts/abi" 29 "github.com/0xsequence/ethkit/go-ethereum/common" 30 "github.com/0xsequence/ethkit/go-ethereum/core/types" 31 "github.com/0xsequence/ethkit/go-ethereum/crypto" 32 "github.com/0xsequence/ethkit/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 { 175 return err 176 } 177 if len(output) == 0 { 178 // Make sure we have a contract to operate on, and bail out otherwise. 179 if code, err = pb.PendingCodeAt(ctx, c.address); err != nil { 180 return err 181 } else if len(code) == 0 { 182 return ErrNoCode 183 } 184 } 185 } else { 186 output, err = c.caller.CallContract(ctx, msg, opts.BlockNumber) 187 if err != nil { 188 return err 189 } 190 if len(output) == 0 { 191 // Make sure we have a contract to operate on, and bail out otherwise. 192 if code, err = c.caller.CodeAt(ctx, c.address, opts.BlockNumber); err != nil { 193 return err 194 } else if len(code) == 0 { 195 return ErrNoCode 196 } 197 } 198 } 199 200 if len(*results) == 0 { 201 res, err := c.abi.Unpack(method, output) 202 *results = res 203 return err 204 } 205 res := *results 206 return c.abi.UnpackIntoInterface(res[0], method, output) 207 } 208 209 // Transact invokes the (paid) contract method with params as input values. 210 func (c *BoundContract) Transact(opts *TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { 211 // Otherwise pack up the parameters and invoke the contract 212 input, err := c.abi.Pack(method, params...) 213 if err != nil { 214 return nil, err 215 } 216 // todo(rjl493456442) check the method is payable or not, 217 // reject invalid transaction at the first place 218 return c.transact(opts, &c.address, input) 219 } 220 221 // RawTransact initiates a transaction with the given raw calldata as the input. 222 // It's usually used to initiate transactions for invoking **Fallback** function. 223 func (c *BoundContract) RawTransact(opts *TransactOpts, calldata []byte) (*types.Transaction, error) { 224 // todo(rjl493456442) check the method is payable or not, 225 // reject invalid transaction at the first place 226 return c.transact(opts, &c.address, calldata) 227 } 228 229 // Transfer initiates a plain transaction to move funds to the contract, calling 230 // its default method if one is available. 231 func (c *BoundContract) Transfer(opts *TransactOpts) (*types.Transaction, error) { 232 // todo(rjl493456442) check the payable fallback or receive is defined 233 // or not, reject invalid transaction at the first place 234 return c.transact(opts, &c.address, nil) 235 } 236 237 func (c *BoundContract) createDynamicTx(opts *TransactOpts, contract *common.Address, input []byte, head *types.Header) (*types.Transaction, error) { 238 // Normalize value 239 value := opts.Value 240 if value == nil { 241 value = new(big.Int) 242 } 243 // Estimate TipCap 244 gasTipCap := opts.GasTipCap 245 if gasTipCap == nil { 246 tip, err := c.transactor.SuggestGasTipCap(ensureContext(opts.Context)) 247 if err != nil { 248 return nil, err 249 } 250 gasTipCap = tip 251 } 252 // Estimate FeeCap 253 gasFeeCap := opts.GasFeeCap 254 if gasFeeCap == nil { 255 gasFeeCap = new(big.Int).Add( 256 gasTipCap, 257 new(big.Int).Mul(head.BaseFee, big.NewInt(2)), 258 ) 259 } 260 if gasFeeCap.Cmp(gasTipCap) < 0 { 261 return nil, fmt.Errorf("maxFeePerGas (%v) < maxPriorityFeePerGas (%v)", gasFeeCap, gasTipCap) 262 } 263 // Estimate GasLimit 264 gasLimit := opts.GasLimit 265 if opts.GasLimit == 0 { 266 var err error 267 gasLimit, err = c.estimateGasLimit(opts, contract, input, nil, gasTipCap, gasFeeCap, value) 268 if err != nil { 269 return nil, err 270 } 271 } 272 // create the transaction 273 nonce, err := c.getNonce(opts) 274 if err != nil { 275 return nil, err 276 } 277 baseTx := &types.DynamicFeeTx{ 278 To: contract, 279 Nonce: nonce, 280 GasFeeCap: gasFeeCap, 281 GasTipCap: gasTipCap, 282 Gas: gasLimit, 283 Value: value, 284 Data: input, 285 } 286 return types.NewTx(baseTx), nil 287 } 288 289 func (c *BoundContract) createLegacyTx(opts *TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error) { 290 if opts.GasFeeCap != nil || opts.GasTipCap != nil { 291 return nil, errors.New("maxFeePerGas or maxPriorityFeePerGas specified but london is not active yet") 292 } 293 // Normalize value 294 value := opts.Value 295 if value == nil { 296 value = new(big.Int) 297 } 298 // Estimate GasPrice 299 gasPrice := opts.GasPrice 300 if gasPrice == nil { 301 price, err := c.transactor.SuggestGasPrice(ensureContext(opts.Context)) 302 if err != nil { 303 return nil, err 304 } 305 gasPrice = price 306 } 307 // Estimate GasLimit 308 gasLimit := opts.GasLimit 309 if opts.GasLimit == 0 { 310 var err error 311 gasLimit, err = c.estimateGasLimit(opts, contract, input, gasPrice, nil, nil, value) 312 if err != nil { 313 return nil, err 314 } 315 } 316 // create the transaction 317 nonce, err := c.getNonce(opts) 318 if err != nil { 319 return nil, err 320 } 321 baseTx := &types.LegacyTx{ 322 To: contract, 323 Nonce: nonce, 324 GasPrice: gasPrice, 325 Gas: gasLimit, 326 Value: value, 327 Data: input, 328 } 329 return types.NewTx(baseTx), nil 330 } 331 332 func (c *BoundContract) estimateGasLimit(opts *TransactOpts, contract *common.Address, input []byte, gasPrice, gasTipCap, gasFeeCap, value *big.Int) (uint64, error) { 333 if contract != nil { 334 // Gas estimation cannot succeed without code for method invocations. 335 if code, err := c.transactor.PendingCodeAt(ensureContext(opts.Context), c.address); err != nil { 336 return 0, err 337 } else if len(code) == 0 { 338 return 0, ErrNoCode 339 } 340 } 341 msg := ethereum.CallMsg{ 342 From: opts.From, 343 To: contract, 344 GasPrice: gasPrice, 345 GasTipCap: gasTipCap, 346 GasFeeCap: gasFeeCap, 347 Value: value, 348 Data: input, 349 } 350 return c.transactor.EstimateGas(ensureContext(opts.Context), msg) 351 } 352 353 func (c *BoundContract) getNonce(opts *TransactOpts) (uint64, error) { 354 if opts.Nonce == nil { 355 return c.transactor.PendingNonceAt(ensureContext(opts.Context), opts.From) 356 } else { 357 return opts.Nonce.Uint64(), nil 358 } 359 } 360 361 // transact executes an actual transaction invocation, first deriving any missing 362 // authorization fields, and then scheduling the transaction for execution. 363 func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error) { 364 if opts.GasPrice != nil && (opts.GasFeeCap != nil || opts.GasTipCap != nil) { 365 return nil, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified") 366 } 367 // Create the transaction 368 var ( 369 rawTx *types.Transaction 370 err error 371 ) 372 if opts.GasPrice != nil { 373 rawTx, err = c.createLegacyTx(opts, contract, input) 374 } else { 375 // Only query for basefee if gasPrice not specified 376 if head, errHead := c.transactor.HeaderByNumber(ensureContext(opts.Context), nil); errHead != nil { 377 return nil, errHead 378 } else if head.BaseFee != nil { 379 rawTx, err = c.createDynamicTx(opts, contract, input, head) 380 } else { 381 // Chain is not London ready -> use legacy transaction 382 rawTx, err = c.createLegacyTx(opts, contract, input) 383 } 384 } 385 if err != nil { 386 return nil, err 387 } 388 // Sign the transaction and schedule it for execution 389 if opts.Signer == nil { 390 return nil, errors.New("no signer to authorize the transaction with") 391 } 392 signedTx, err := opts.Signer(opts.From, rawTx) 393 if err != nil { 394 return nil, err 395 } 396 if opts.NoSend { 397 return signedTx, nil 398 } 399 if err := c.transactor.SendTransaction(ensureContext(opts.Context), signedTx); err != nil { 400 return nil, err 401 } 402 return signedTx, nil 403 } 404 405 // FilterLogs filters contract logs for past blocks, returning the necessary 406 // channels to construct a strongly typed bound iterator on top of them. 407 func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) { 408 // Don't crash on a lazy user 409 if opts == nil { 410 opts = new(FilterOpts) 411 } 412 // Append the event selector to the query parameters and construct the topic set 413 query = append([][]interface{}{{c.abi.Events[name].ID}}, query...) 414 415 topics, err := abi.MakeTopics(query...) 416 if err != nil { 417 return nil, nil, err 418 } 419 // Start the background filtering 420 logs := make(chan types.Log, 128) 421 422 config := ethereum.FilterQuery{ 423 Addresses: []common.Address{c.address}, 424 Topics: topics, 425 FromBlock: new(big.Int).SetUint64(opts.Start), 426 } 427 if opts.End != nil { 428 config.ToBlock = new(big.Int).SetUint64(*opts.End) 429 } 430 /* TODO(karalabe): Replace the rest of the method below with this when supported 431 sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs) 432 */ 433 buff, err := c.filterer.FilterLogs(ensureContext(opts.Context), config) 434 if err != nil { 435 return nil, nil, err 436 } 437 sub, err := event.NewSubscription(func(quit <-chan struct{}) error { 438 for _, log := range buff { 439 select { 440 case logs <- log: 441 case <-quit: 442 return nil 443 } 444 } 445 return nil 446 }), nil 447 448 if err != nil { 449 return nil, nil, err 450 } 451 return logs, sub, nil 452 } 453 454 // WatchLogs filters subscribes to contract logs for future blocks, returning a 455 // subscription object that can be used to tear down the watcher. 456 func (c *BoundContract) WatchLogs(opts *WatchOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) { 457 // Don't crash on a lazy user 458 if opts == nil { 459 opts = new(WatchOpts) 460 } 461 // Append the event selector to the query parameters and construct the topic set 462 query = append([][]interface{}{{c.abi.Events[name].ID}}, query...) 463 464 topics, err := abi.MakeTopics(query...) 465 if err != nil { 466 return nil, nil, err 467 } 468 // Start the background filtering 469 logs := make(chan types.Log, 128) 470 471 config := ethereum.FilterQuery{ 472 Addresses: []common.Address{c.address}, 473 Topics: topics, 474 } 475 if opts.Start != nil { 476 config.FromBlock = new(big.Int).SetUint64(*opts.Start) 477 } 478 sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs) 479 if err != nil { 480 return nil, nil, err 481 } 482 return logs, sub, nil 483 } 484 485 // UnpackLog unpacks a retrieved log into the provided output structure. 486 func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) error { 487 if log.Topics[0] != c.abi.Events[event].ID { 488 return fmt.Errorf("event signature mismatch") 489 } 490 if len(log.Data) > 0 { 491 if err := c.abi.UnpackIntoInterface(out, event, log.Data); err != nil { 492 return err 493 } 494 } 495 var indexed abi.Arguments 496 for _, arg := range c.abi.Events[event].Inputs { 497 if arg.Indexed { 498 indexed = append(indexed, arg) 499 } 500 } 501 return abi.ParseTopics(out, indexed, log.Topics[1:]) 502 } 503 504 // UnpackLogIntoMap unpacks a retrieved log into the provided map. 505 func (c *BoundContract) UnpackLogIntoMap(out map[string]interface{}, event string, log types.Log) error { 506 if log.Topics[0] != c.abi.Events[event].ID { 507 return fmt.Errorf("event signature mismatch") 508 } 509 if len(log.Data) > 0 { 510 if err := c.abi.UnpackIntoMap(out, event, log.Data); err != nil { 511 return err 512 } 513 } 514 var indexed abi.Arguments 515 for _, arg := range c.abi.Events[event].Inputs { 516 if arg.Indexed { 517 indexed = append(indexed, arg) 518 } 519 } 520 return abi.ParseTopicsIntoMap(out, indexed, log.Topics[1:]) 521 } 522 523 // ensureContext is a helper method to ensure a context is not nil, even if the 524 // user specified it as such. 525 func ensureContext(ctx context.Context) context.Context { 526 if ctx == nil { 527 return context.Background() 528 } 529 return ctx 530 }