github.com/bcskill/bcschain/v3@v3.4.9-beta2/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 25 "github.com/bcskill/bcschain/v3" 26 "github.com/bcskill/bcschain/v3/accounts/abi" 27 "github.com/bcskill/bcschain/v3/common" 28 "github.com/bcskill/bcschain/v3/core/types" 29 "github.com/bcskill/bcschain/v3/crypto" 30 "github.com/bcskill/bcschain/v3/event" 31 ) 32 33 // SignerFn is a signer function callback when a contract requires a method to 34 // sign the transaction before submission. 35 type SignerFn func(common.Address, *types.Transaction) (*types.Transaction, error) 36 37 // CallOpts is the collection of options to fine tune a contract call request. 38 type CallOpts struct { 39 Pending bool // Whether to operate on the pending state or the last known one 40 From common.Address // Optional the sender address, otherwise the first account is used 41 BlockNumber *big.Int // Optional the block number on which the call should be performed 42 Context context.Context // Network context to support cancellation and timeouts (nil = no timeout) 43 } 44 45 // TransactOpts is the collection of authorization data required to create a 46 // valid Ethereum transaction. 47 type TransactOpts struct { 48 From common.Address // Ethereum account to send the transaction from 49 Nonce *big.Int // Nonce to use for the transaction execution (nil = use pending state) 50 Signer SignerFn // Method to use for signing the transaction (mandatory) 51 52 Value *big.Int // Funds to transfer along the transaction (nil = 0 = no funds) 53 GasPrice *big.Int // Gas price to use for the transaction execution (nil = gas price oracle) 54 GasLimit uint64 // Gas limit to set for the transaction execution (0 = estimate) 55 56 Context context.Context // Network context to support cancellation and timeouts (nil = no timeout) 57 58 NoSend bool // Do all transact steps but do not send the transaction 59 } 60 61 // FilterOpts is the collection of options to fine tune filtering for events 62 // within a bound contract. 63 type FilterOpts struct { 64 Start uint64 // Start of the queried range 65 End *uint64 // End of the range (nil = latest) 66 67 Context context.Context // Network context to support cancellation and timeouts (nil = no timeout) 68 } 69 70 // WatchOpts is the collection of options to fine tune subscribing for events 71 // within a bound contract. 72 type WatchOpts struct { 73 Start *uint64 // Start of the queried range (nil = latest) 74 Context context.Context // Network context to support cancellation and timeouts (nil = no timeout) 75 } 76 77 // BoundContract is the base wrapper object that reflects a contract on the 78 // Ethereum network. It contains a collection of methods that are used by the 79 // higher level contract bindings to operate. 80 type BoundContract struct { 81 address common.Address // Deployment address of the contract on the Ethereum blockchain 82 abi abi.ABI // Reflect based ABI to access the correct Ethereum methods 83 caller ContractCaller // Read interface to interact with the blockchain 84 transactor ContractTransactor // Write interface to interact with the blockchain 85 filterer ContractFilterer // Event filtering to interact with the blockchain 86 } 87 88 // NewBoundContract creates a low level contract interface through which calls 89 // and transactions may be made through. 90 func NewBoundContract(address common.Address, abi abi.ABI, caller ContractCaller, transactor ContractTransactor, filterer ContractFilterer) *BoundContract { 91 return &BoundContract{ 92 address: address, 93 abi: abi, 94 caller: caller, 95 transactor: transactor, 96 filterer: filterer, 97 } 98 } 99 100 // DeployContract deploys a contract onto the Ethereum blockchain and binds the 101 // deployment address with a Go wrapper. 102 func DeployContract(opts *TransactOpts, abi abi.ABI, bytecode []byte, backend ContractBackend, params ...interface{}) (common.Address, *types.Transaction, *BoundContract, error) { 103 // Otherwise try to deploy the contract 104 c := NewBoundContract(common.Address{}, abi, backend, backend, backend) 105 106 input, err := c.abi.Pack("", params...) 107 if err != nil { 108 return common.Address{}, nil, nil, err 109 } 110 tx, err := c.transact(opts, nil, append(bytecode, input...)) 111 if err != nil { 112 return common.Address{}, nil, nil, err 113 } 114 c.address = crypto.CreateAddress(opts.From, tx.Nonce()) 115 return c.address, tx, c, nil 116 } 117 118 // Call invokes the (constant) contract method with params as input values and 119 // sets the output to result. The result type might be a single field for simple 120 // returns, a slice of interfaces for anonymous returns and a struct for named 121 // returns. 122 func (c *BoundContract) Call(opts *CallOpts, results *[]interface{}, method string, params ...interface{}) error { 123 // Don't crash on a lazy user 124 if opts == nil { 125 opts = new(CallOpts) 126 } 127 if results == nil { 128 results = new([]interface{}) 129 } 130 // Pack the input, call and unpack the results 131 input, err := c.abi.Pack(method, params...) 132 if err != nil { 133 return err 134 } 135 var ( 136 msg = gochain.CallMsg{From: opts.From, To: &c.address, Data: input} 137 ctx = ensureContext(opts.Context) 138 code []byte 139 output []byte 140 ) 141 if opts.Pending { 142 pb, ok := c.caller.(PendingContractCaller) 143 if !ok { 144 return ErrNoPendingState 145 } 146 output, err = pb.PendingCallContract(ctx, msg) 147 if err == nil && len(output) == 0 { 148 // Make sure we have a contract to operate on, and bail out otherwise. 149 if code, err = pb.PendingCodeAt(ctx, c.address); err != nil { 150 return err 151 } else if len(code) == 0 { 152 return ErrNoCode 153 } 154 } 155 } else { 156 output, err = c.caller.CallContract(ctx, msg, opts.BlockNumber) 157 if err != nil { 158 return err 159 } 160 if len(output) == 0 { 161 // Make sure we have a contract to operate on, and bail out otherwise. 162 if code, err = c.caller.CodeAt(ctx, c.address, opts.BlockNumber); err != nil { 163 return err 164 } else if len(code) == 0 { 165 return ErrNoCode 166 } 167 } 168 } 169 170 if len(*results) == 0 { 171 res, err := c.abi.Unpack(method, output) 172 *results = res 173 return err 174 } 175 res := *results 176 return c.abi.UnpackIntoInterface(res[0], method, output) 177 } 178 179 // Transact invokes the (paid) contract method with params as input values. 180 func (c *BoundContract) Transact(opts *TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { 181 // Otherwise pack up the parameters and invoke the contract 182 input, err := c.abi.Pack(method, params...) 183 if err != nil { 184 return nil, err 185 } 186 // todo(rjl493456442) check the method is payable or not, 187 // reject invalid transaction at the first place 188 return c.transact(opts, &c.address, input) 189 } 190 191 // RawTransact initiates a transaction with the given raw calldata as the input. 192 // It's usually used to initiate transactions for invoking **Fallback** function. 193 func (c *BoundContract) RawTransact(opts *TransactOpts, calldata []byte) (*types.Transaction, error) { 194 // todo(rjl493456442) check the method is payable or not, 195 // reject invalid transaction at the first place 196 return c.transact(opts, &c.address, calldata) 197 } 198 199 // Transfer initiates a plain transaction to move funds to the contract, calling 200 // its default method if one is available. 201 func (c *BoundContract) Transfer(opts *TransactOpts) (*types.Transaction, error) { 202 // todo(rjl493456442) check the payable fallback or receive is defined 203 // or not, reject invalid transaction at the first place 204 return c.transact(opts, &c.address, nil) 205 } 206 207 // transact executes an actual transaction invocation, first deriving any missing 208 // authorization fields, and then scheduling the transaction for execution. 209 func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error) { 210 var err error 211 212 // Ensure a valid value field and resolve the account nonce 213 value := opts.Value 214 if value == nil { 215 value = new(big.Int) 216 } 217 var nonce uint64 218 if opts.Nonce == nil { 219 nonce, err = c.transactor.PendingNonceAt(ensureContext(opts.Context), opts.From) 220 if err != nil { 221 return nil, fmt.Errorf("failed to retrieve account nonce: %v", err) 222 } 223 } else { 224 nonce = opts.Nonce.Uint64() 225 } 226 // Figure out the gas allowance and gas price values 227 gasPrice := opts.GasPrice 228 if gasPrice == nil { 229 gasPrice, err = c.transactor.SuggestGasPrice(ensureContext(opts.Context)) 230 if err != nil { 231 return nil, fmt.Errorf("failed to suggest gas price: %v", err) 232 } 233 } 234 gasLimit := opts.GasLimit 235 if gasLimit == 0 { 236 // Gas estimation cannot succeed without code for method invocations 237 if contract != nil { 238 if code, err := c.transactor.PendingCodeAt(ensureContext(opts.Context), c.address); err != nil { 239 return nil, err 240 } else if len(code) == 0 { 241 return nil, ErrNoCode 242 } 243 } 244 // If the contract surely has code (or code is not needed), estimate the transaction 245 msg := gochain.CallMsg{From: opts.From, To: contract, GasPrice: gasPrice, Value: value, Data: input} 246 gasLimit, err = c.transactor.EstimateGas(ensureContext(opts.Context), msg) 247 if err != nil { 248 return nil, fmt.Errorf("failed to estimate gas needed: %v", err) 249 } 250 } 251 // Create the transaction, sign it and schedule it for execution 252 var rawTx *types.Transaction 253 if contract == nil { 254 rawTx = types.NewContractCreation(nonce, value, gasLimit, gasPrice, input) 255 } else { 256 rawTx = types.NewTransaction(nonce, c.address, value, gasLimit, gasPrice, input) 257 } 258 if opts.Signer == nil { 259 return nil, errors.New("no signer to authorize the transaction with") 260 } 261 signedTx, err := opts.Signer(opts.From, rawTx) 262 if err != nil { 263 return nil, err 264 } 265 if opts.NoSend { 266 return signedTx, nil 267 } 268 if err := c.transactor.SendTransaction(ensureContext(opts.Context), signedTx); err != nil { 269 return nil, err 270 } 271 return signedTx, nil 272 } 273 274 // FilterLogs filters contract logs for past blocks, returning the necessary 275 // channels to construct a strongly typed bound iterator on top of them. 276 func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) { 277 // Don't crash on a lazy user 278 if opts == nil { 279 opts = new(FilterOpts) 280 } 281 // Append the event selector to the query parameters and construct the topic set 282 query = append([][]interface{}{{c.abi.Events[name].ID}}, query...) 283 284 topics, err := abi.MakeTopics(query...) 285 if err != nil { 286 return nil, nil, err 287 } 288 // Start the background filtering 289 logs := make(chan types.Log, 128) 290 291 config := gochain.FilterQuery{ 292 Addresses: []common.Address{c.address}, 293 Topics: topics, 294 FromBlock: new(big.Int).SetUint64(opts.Start), 295 } 296 if opts.End != nil { 297 config.ToBlock = new(big.Int).SetUint64(*opts.End) 298 } 299 /* TODO(karalabe): Replace the rest of the method below with this when supported 300 sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs) 301 */ 302 buff, err := c.filterer.FilterLogs(ensureContext(opts.Context), config) 303 if err != nil { 304 return nil, nil, err 305 } 306 sub, err := event.NewSubscription(func(quit <-chan struct{}) error { 307 for _, log := range buff { 308 select { 309 case logs <- log: 310 case <-quit: 311 return nil 312 } 313 } 314 return nil 315 }), nil 316 317 if err != nil { 318 return nil, nil, err 319 } 320 return logs, sub, nil 321 } 322 323 // WatchLogs filters subscribes to contract logs for future blocks, returning a 324 // subscription object that can be used to tear down the watcher. 325 func (c *BoundContract) WatchLogs(opts *WatchOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) { 326 // Don't crash on a lazy user 327 if opts == nil { 328 opts = new(WatchOpts) 329 } 330 // Append the event selector to the query parameters and construct the topic set 331 query = append([][]interface{}{{c.abi.Events[name].ID}}, query...) 332 333 topics, err := abi.MakeTopics(query...) 334 if err != nil { 335 return nil, nil, err 336 } 337 // Start the background filtering 338 logs := make(chan types.Log, 128) 339 340 config := gochain.FilterQuery{ 341 Addresses: []common.Address{c.address}, 342 Topics: topics, 343 } 344 if opts.Start != nil { 345 config.FromBlock = new(big.Int).SetUint64(*opts.Start) 346 } 347 sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs) 348 if err != nil { 349 return nil, nil, err 350 } 351 return logs, sub, nil 352 } 353 354 // UnpackLog unpacks a retrieved log into the provided output structure. 355 func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) error { 356 if len(log.Data) > 0 { 357 if err := c.abi.UnpackIntoInterface(out, event, log.Data); err != nil { 358 return err 359 } 360 } 361 var indexed abi.Arguments 362 for _, arg := range c.abi.Events[event].Inputs { 363 if arg.Indexed { 364 indexed = append(indexed, arg) 365 } 366 } 367 return abi.ParseTopics(out, indexed, log.Topics[1:]) 368 } 369 370 // UnpackLogIntoMap unpacks a retrieved log into the provided map. 371 func (c *BoundContract) UnpackLogIntoMap(out map[string]interface{}, event string, log types.Log) error { 372 if len(log.Data) > 0 { 373 if err := c.abi.UnpackIntoMap(out, event, log.Data); err != nil { 374 return err 375 } 376 } 377 var indexed abi.Arguments 378 for _, arg := range c.abi.Events[event].Inputs { 379 if arg.Indexed { 380 indexed = append(indexed, arg) 381 } 382 } 383 return abi.ParseTopicsIntoMap(out, indexed, log.Topics[1:]) 384 } 385 386 // ensureContext is a helper method to ensure a context is not nil, even if the 387 // user specified it as such. 388 func ensureContext(ctx context.Context) context.Context { 389 if ctx == nil { 390 return context.TODO() 391 } 392 return ctx 393 }