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