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