github.com/0xPolygon/supernets2-node@v0.0.0-20230711153321-2fe574524eaa/etherman/etherman.go (about) 1 package etherman 2 3 import ( 4 "context" 5 "crypto/ecdsa" 6 "encoding/json" 7 "errors" 8 "fmt" 9 "math" 10 "math/big" 11 "os" 12 "path/filepath" 13 "strings" 14 "time" 15 16 "github.com/0xPolygon/supernets2-node/encoding" 17 "github.com/0xPolygon/supernets2-node/etherman/etherscan" 18 "github.com/0xPolygon/supernets2-node/etherman/ethgasstation" 19 "github.com/0xPolygon/supernets2-node/etherman/smartcontracts/matic" 20 "github.com/0xPolygon/supernets2-node/etherman/smartcontracts/polygonzkevmglobalexitroot" 21 "github.com/0xPolygon/supernets2-node/etherman/smartcontracts/supernets2" 22 "github.com/0xPolygon/supernets2-node/etherman/smartcontracts/supernets2datacommittee" 23 ethmanTypes "github.com/0xPolygon/supernets2-node/etherman/types" 24 "github.com/0xPolygon/supernets2-node/log" 25 "github.com/0xPolygon/supernets2-node/state" 26 "github.com/0xPolygon/supernets2-node/test/operations" 27 "github.com/ethereum/go-ethereum" 28 "github.com/ethereum/go-ethereum/accounts/abi" 29 "github.com/ethereum/go-ethereum/accounts/abi/bind" 30 "github.com/ethereum/go-ethereum/accounts/keystore" 31 "github.com/ethereum/go-ethereum/common" 32 "github.com/ethereum/go-ethereum/core" 33 "github.com/ethereum/go-ethereum/core/types" 34 "github.com/ethereum/go-ethereum/crypto" 35 "github.com/ethereum/go-ethereum/ethclient" 36 "golang.org/x/crypto/sha3" 37 ) 38 39 var ( 40 updateGlobalExitRootSignatureHash = crypto.Keccak256Hash([]byte("UpdateGlobalExitRoot(bytes32,bytes32)")) 41 forcedBatchSignatureHash = crypto.Keccak256Hash([]byte("ForceBatch(uint64,bytes32,address,bytes)")) 42 sequencedBatchesEventSignatureHash = crypto.Keccak256Hash([]byte("SequenceBatches(uint64)")) 43 forceSequencedBatchesSignatureHash = crypto.Keccak256Hash([]byte("SequenceForceBatches(uint64)")) 44 verifyBatchesSignatureHash = crypto.Keccak256Hash([]byte("VerifyBatches(uint64,bytes32,address)")) 45 verifyBatchesTrustedAggregatorSignatureHash = crypto.Keccak256Hash([]byte("VerifyBatchesTrustedAggregator(uint64,bytes32,address)")) 46 setTrustedSequencerURLSignatureHash = crypto.Keccak256Hash([]byte("SetTrustedSequencerURL(string)")) 47 setTrustedSequencerSignatureHash = crypto.Keccak256Hash([]byte("SetTrustedSequencer(address)")) 48 transferOwnershipSignatureHash = crypto.Keccak256Hash([]byte("OwnershipTransferred(address,address)")) 49 emergencyStateActivatedSignatureHash = crypto.Keccak256Hash([]byte("EmergencyStateActivated()")) 50 emergencyStateDeactivatedSignatureHash = crypto.Keccak256Hash([]byte("EmergencyStateDeactivated()")) 51 updateZkEVMVersionSignatureHash = crypto.Keccak256Hash([]byte("UpdateSupernets2Version(uint64,uint64,string)")) 52 consolidatePendingStateSignatureHash = crypto.Keccak256Hash([]byte("ConsolidatePendingState(uint64,bytes32,uint64)")) 53 setTrustedAggregatorTimeoutSignatureHash = crypto.Keccak256Hash([]byte("SetTrustedAggregatorTimeout(uint64)")) 54 setTrustedAggregatorSignatureHash = crypto.Keccak256Hash([]byte("SetTrustedAggregator(address)")) 55 setPendingStateTimeoutSignatureHash = crypto.Keccak256Hash([]byte("SetPendingStateTimeout(uint64)")) 56 setMultiplierBatchFeeSignatureHash = crypto.Keccak256Hash([]byte("SetMultiplierBatchFee(uint16)")) 57 setVerifyBatchTimeTargetSignatureHash = crypto.Keccak256Hash([]byte("SetVerifyBatchTimeTarget(uint64)")) 58 setForceBatchTimeoutSignatureHash = crypto.Keccak256Hash([]byte("SetForceBatchTimeout(uint64)")) 59 activateForceBatchesSignatureHash = crypto.Keccak256Hash([]byte("ActivateForceBatches()")) 60 transferAdminRoleSignatureHash = crypto.Keccak256Hash([]byte("TransferAdminRole(address)")) 61 acceptAdminRoleSignatureHash = crypto.Keccak256Hash([]byte("AcceptAdminRole(address)")) 62 proveNonDeterministicPendingStateSignatureHash = crypto.Keccak256Hash([]byte("ProveNonDeterministicPendingState(bytes32,bytes32)")) 63 overridePendingStateSignatureHash = crypto.Keccak256Hash([]byte("OverridePendingState(uint64,bytes32,address)")) 64 65 // Proxy events 66 initializedSignatureHash = crypto.Keccak256Hash([]byte("Initialized(uint8)")) 67 adminChangedSignatureHash = crypto.Keccak256Hash([]byte("AdminChanged(address,address)")) 68 beaconUpgradedSignatureHash = crypto.Keccak256Hash([]byte("BeaconUpgraded(address)")) 69 upgradedSignatureHash = crypto.Keccak256Hash([]byte("Upgraded(address)")) 70 71 // ErrNotFound is used when the object is not found 72 ErrNotFound = errors.New("not found") 73 // ErrIsReadOnlyMode is used when the EtherMan client is in read-only mode. 74 ErrIsReadOnlyMode = errors.New("etherman client in read-only mode: no account configured to send transactions to L1. " + 75 "please check the [Etherman] PrivateKeyPath and PrivateKeyPassword configuration") 76 // ErrPrivateKeyNotFound used when the provided sender does not have a private key registered to be used 77 ErrPrivateKeyNotFound = errors.New("can't find sender private key to sign tx") 78 ) 79 80 // SequencedBatchesSigHash returns the hash for the `SequenceBatches` event. 81 func SequencedBatchesSigHash() common.Hash { return sequencedBatchesEventSignatureHash } 82 83 // TrustedVerifyBatchesSigHash returns the hash for the `TrustedVerifyBatches` event. 84 func TrustedVerifyBatchesSigHash() common.Hash { return verifyBatchesTrustedAggregatorSignatureHash } 85 86 // EventOrder is the the type used to identify the events order 87 type EventOrder string 88 89 const ( 90 // GlobalExitRootsOrder identifies a GlobalExitRoot event 91 GlobalExitRootsOrder EventOrder = "GlobalExitRoots" 92 // SequenceBatchesOrder identifies a VerifyBatch event 93 SequenceBatchesOrder EventOrder = "SequenceBatches" 94 // ForcedBatchesOrder identifies a ForcedBatches event 95 ForcedBatchesOrder EventOrder = "ForcedBatches" 96 // TrustedVerifyBatchOrder identifies a TrustedVerifyBatch event 97 TrustedVerifyBatchOrder EventOrder = "TrustedVerifyBatch" 98 // SequenceForceBatchesOrder identifies a SequenceForceBatches event 99 SequenceForceBatchesOrder EventOrder = "SequenceForceBatches" 100 // ForkIDsOrder identifies an updateZkevmVersion event 101 ForkIDsOrder EventOrder = "forkIDs" 102 ) 103 104 type ethereumClient interface { 105 ethereum.ChainReader 106 ethereum.ChainStateReader 107 ethereum.ContractCaller 108 ethereum.GasEstimator 109 ethereum.GasPricer 110 ethereum.LogFilterer 111 ethereum.TransactionReader 112 ethereum.TransactionSender 113 114 bind.DeployBackend 115 } 116 117 // L1Config represents the configuration of the network used in L1 118 type L1Config struct { 119 L1ChainID uint64 `json:"chainId"` 120 Supernets2Addr common.Address `json:"supernets2Address"` 121 MaticAddr common.Address `json:"maticTokenAddress"` 122 GlobalExitRootManagerAddr common.Address `json:"supernets2GlobalExitRootAddress"` 123 DataCommitteeAddr common.Address `json:"supernets2DataCommitteeContract"` 124 } 125 126 type externalGasProviders struct { 127 MultiGasProvider bool 128 Providers []ethereum.GasPricer 129 } 130 131 // Client is a simple implementation of EtherMan. 132 type Client struct { 133 EthClient ethereumClient 134 Supernets2 *supernets2.Supernets2 135 GlobalExitRootManager *polygonzkevmglobalexitroot.Polygonzkevmglobalexitroot 136 Matic *matic.Matic 137 DataCommittee *supernets2datacommittee.Supernets2datacommittee 138 SCAddresses []common.Address 139 140 GasProviders externalGasProviders 141 142 l1Cfg L1Config 143 auth map[common.Address]bind.TransactOpts // empty in case of read-only client 144 } 145 146 // NewClient creates a new etherman. 147 func NewClient(cfg Config, l1Config L1Config) (*Client, error) { 148 // Connect to ethereum node 149 ethClient, err := ethclient.Dial(cfg.URL) 150 if err != nil { 151 log.Errorf("error connecting to %s: %+v", cfg.URL, err) 152 return nil, err 153 } 154 // Create smc clients 155 poe, err := supernets2.NewSupernets2(l1Config.Supernets2Addr, ethClient) 156 if err != nil { 157 return nil, err 158 } 159 globalExitRoot, err := polygonzkevmglobalexitroot.NewPolygonzkevmglobalexitroot(l1Config.GlobalExitRootManagerAddr, ethClient) 160 if err != nil { 161 return nil, err 162 } 163 matic, err := matic.NewMatic(l1Config.MaticAddr, ethClient) 164 if err != nil { 165 return nil, err 166 } 167 dataCommittee, err := supernets2datacommittee.NewSupernets2datacommittee(l1Config.DataCommitteeAddr, ethClient) 168 if err != nil { 169 return nil, err 170 } 171 var scAddresses []common.Address 172 scAddresses = append(scAddresses, l1Config.Supernets2Addr, l1Config.GlobalExitRootManagerAddr) 173 174 gProviders := []ethereum.GasPricer{ethClient} 175 if cfg.MultiGasProvider { 176 if cfg.Etherscan.ApiKey == "" { 177 log.Info("No ApiKey provided for etherscan. Ignoring provider...") 178 } else { 179 log.Info("ApiKey detected for etherscan") 180 gProviders = append(gProviders, etherscan.NewEtherscanService(cfg.Etherscan.ApiKey)) 181 } 182 gProviders = append(gProviders, ethgasstation.NewEthGasStationService()) 183 } 184 185 return &Client{ 186 EthClient: ethClient, 187 Supernets2: poe, 188 Matic: matic, 189 GlobalExitRootManager: globalExitRoot, 190 DataCommittee: dataCommittee, 191 SCAddresses: scAddresses, 192 GasProviders: externalGasProviders{ 193 MultiGasProvider: cfg.MultiGasProvider, 194 Providers: gProviders, 195 }, 196 l1Cfg: l1Config, 197 auth: map[common.Address]bind.TransactOpts{}, 198 }, nil 199 } 200 201 // VerifyGenBlockNumber verifies if the genesis Block Number is valid 202 func (etherMan *Client) VerifyGenBlockNumber(ctx context.Context, genBlockNumber uint64) (bool, error) { 203 log.Info("Verifying genesis blockNumber: ", genBlockNumber) 204 // Filter query 205 genBlock := new(big.Int).SetUint64(genBlockNumber) 206 query := ethereum.FilterQuery{ 207 FromBlock: genBlock, 208 ToBlock: genBlock, 209 Addresses: etherMan.SCAddresses, 210 Topics: [][]common.Hash{{updateZkEVMVersionSignatureHash}}, 211 } 212 logs, err := etherMan.EthClient.FilterLogs(ctx, query) 213 if err != nil { 214 return false, err 215 } 216 if len(logs) == 0 { 217 return false, fmt.Errorf("the specified genBlockNumber in config file does not contain any forkID event. Please use the proper blockNumber.") 218 } 219 zkevmVersion, err := etherMan.Supernets2.ParseUpdateSupernets2Version(logs[0]) 220 if err != nil { 221 log.Error("error parsing the forkID event") 222 return false, err 223 } 224 if zkevmVersion.NumBatch != 0 { 225 return false, fmt.Errorf("the specified genBlockNumber in config file does not contain the initial forkID event (BatchNum: %d). Please use the proper blockNumber.", zkevmVersion.NumBatch) 226 } 227 return true, nil 228 } 229 230 // GetForks returns fork information 231 func (etherMan *Client) GetForks(ctx context.Context, genBlockNumber uint64) ([]state.ForkIDInterval, error) { 232 log.Debug("Getting forkIDs from blockNumber: ", genBlockNumber) 233 // Filter query 234 query := ethereum.FilterQuery{ 235 FromBlock: new(big.Int).SetUint64(genBlockNumber), 236 Addresses: etherMan.SCAddresses, 237 Topics: [][]common.Hash{{updateZkEVMVersionSignatureHash}}, 238 } 239 logs, err := etherMan.EthClient.FilterLogs(ctx, query) 240 if err != nil { 241 return []state.ForkIDInterval{}, err 242 } 243 var forks []state.ForkIDInterval 244 for i, l := range logs { 245 zkevmVersion, err := etherMan.Supernets2.ParseUpdateSupernets2Version(l) 246 if err != nil { 247 return []state.ForkIDInterval{}, err 248 } 249 var fork state.ForkIDInterval 250 if i == 0 { 251 fork = state.ForkIDInterval{ 252 FromBatchNumber: zkevmVersion.NumBatch + 1, 253 ToBatchNumber: math.MaxUint64, 254 ForkId: zkevmVersion.ForkID, 255 Version: zkevmVersion.Version, 256 } 257 } else { 258 forks[len(forks)-1].ToBatchNumber = zkevmVersion.NumBatch 259 fork = state.ForkIDInterval{ 260 FromBatchNumber: zkevmVersion.NumBatch + 1, 261 ToBatchNumber: math.MaxUint64, 262 ForkId: zkevmVersion.ForkID, 263 Version: zkevmVersion.Version, 264 } 265 } 266 forks = append(forks, fork) 267 } 268 log.Debugf("Forks decoded: %+v", forks) 269 return forks, nil 270 } 271 272 // GetRollupInfoByBlockRange function retrieves the Rollup information that are included in all this ethereum blocks 273 // from block x to block y. 274 func (etherMan *Client) GetRollupInfoByBlockRange(ctx context.Context, fromBlock uint64, toBlock *uint64) ([]Block, map[common.Hash][]Order, error) { 275 // Filter query 276 query := ethereum.FilterQuery{ 277 FromBlock: new(big.Int).SetUint64(fromBlock), 278 Addresses: etherMan.SCAddresses, 279 } 280 if toBlock != nil { 281 query.ToBlock = new(big.Int).SetUint64(*toBlock) 282 } 283 blocks, blocksOrder, err := etherMan.readEvents(ctx, query) 284 if err != nil { 285 return nil, nil, err 286 } 287 return blocks, blocksOrder, nil 288 } 289 290 // Order contains the event order to let the synchronizer store the information following this order. 291 type Order struct { 292 Name EventOrder 293 Pos int 294 } 295 296 func (etherMan *Client) readEvents(ctx context.Context, query ethereum.FilterQuery) ([]Block, map[common.Hash][]Order, error) { 297 logs, err := etherMan.EthClient.FilterLogs(ctx, query) 298 if err != nil { 299 return nil, nil, err 300 } 301 var blocks []Block 302 blocksOrder := make(map[common.Hash][]Order) 303 for _, vLog := range logs { 304 err := etherMan.processEvent(ctx, vLog, &blocks, &blocksOrder) 305 if err != nil { 306 log.Warnf("error processing event. Retrying... Error: %s. vLog: %+v", err.Error(), vLog) 307 return nil, nil, err 308 } 309 } 310 return blocks, blocksOrder, nil 311 } 312 313 func (etherMan *Client) processEvent(ctx context.Context, vLog types.Log, blocks *[]Block, blocksOrder *map[common.Hash][]Order) error { 314 switch vLog.Topics[0] { 315 case sequencedBatchesEventSignatureHash: 316 return etherMan.sequencedBatchesEvent(ctx, vLog, blocks, blocksOrder) 317 case updateGlobalExitRootSignatureHash: 318 return etherMan.updateGlobalExitRootEvent(ctx, vLog, blocks, blocksOrder) 319 case forcedBatchSignatureHash: 320 return etherMan.forcedBatchEvent(ctx, vLog, blocks, blocksOrder) 321 case verifyBatchesTrustedAggregatorSignatureHash: 322 return etherMan.verifyBatchesTrustedAggregatorEvent(ctx, vLog, blocks, blocksOrder) 323 case verifyBatchesSignatureHash: 324 log.Warn("VerifyBatches event not implemented yet") 325 return nil 326 case forceSequencedBatchesSignatureHash: 327 return etherMan.forceSequencedBatchesEvent(ctx, vLog, blocks, blocksOrder) 328 case setTrustedSequencerURLSignatureHash: 329 log.Debug("SetTrustedSequencerURL event detected") 330 return nil 331 case setTrustedSequencerSignatureHash: 332 log.Debug("SetTrustedSequencer event detected") 333 return nil 334 case initializedSignatureHash: 335 log.Debug("Initialized event detected") 336 return nil 337 case adminChangedSignatureHash: 338 log.Debug("AdminChanged event detected") 339 return nil 340 case beaconUpgradedSignatureHash: 341 log.Debug("BeaconUpgraded event detected") 342 return nil 343 case upgradedSignatureHash: 344 log.Debug("Upgraded event detected") 345 return nil 346 case transferOwnershipSignatureHash: 347 log.Debug("TransferOwnership event detected") 348 return nil 349 case emergencyStateActivatedSignatureHash: 350 log.Debug("EmergencyStateActivated event detected") 351 return nil 352 case emergencyStateDeactivatedSignatureHash: 353 log.Debug("EmergencyStateDeactivated event detected") 354 return nil 355 case updateZkEVMVersionSignatureHash: 356 return etherMan.updateZkevmVersion(ctx, vLog, blocks, blocksOrder) 357 case consolidatePendingStateSignatureHash: 358 log.Debug("ConsolidatePendingState event detected") 359 return nil 360 case setTrustedAggregatorTimeoutSignatureHash: 361 log.Debug("SetTrustedAggregatorTimeout event detected") 362 return nil 363 case setTrustedAggregatorSignatureHash: 364 log.Debug("setTrustedAggregator event detected") 365 return nil 366 case setPendingStateTimeoutSignatureHash: 367 log.Debug("SetPendingStateTimeout event detected") 368 return nil 369 case setMultiplierBatchFeeSignatureHash: 370 log.Debug("SetMultiplierBatchFee event detected") 371 return nil 372 case setVerifyBatchTimeTargetSignatureHash: 373 log.Debug("SetVerifyBatchTimeTarget event detected") 374 return nil 375 case setForceBatchTimeoutSignatureHash: 376 log.Debug("SetForceBatchTimeout event detected") 377 return nil 378 case activateForceBatchesSignatureHash: 379 log.Debug("ActivateForceBatches event detected") 380 return nil 381 case transferAdminRoleSignatureHash: 382 log.Debug("TransferAdminRole event detected") 383 return nil 384 case acceptAdminRoleSignatureHash: 385 log.Debug("AcceptAdminRole event detected") 386 return nil 387 case proveNonDeterministicPendingStateSignatureHash: 388 log.Debug("ProveNonDeterministicPendingState event detected") 389 return nil 390 case overridePendingStateSignatureHash: 391 log.Debug("OverridePendingState event detected") 392 return nil 393 } 394 log.Warn("Event not registered: ", vLog) 395 return nil 396 } 397 398 func (etherMan *Client) updateZkevmVersion(ctx context.Context, vLog types.Log, blocks *[]Block, blocksOrder *map[common.Hash][]Order) error { 399 log.Debug("UpdateZkEVMVersion event detected") 400 zkevmVersion, err := etherMan.Supernets2.ParseUpdateSupernets2Version(vLog) 401 if err != nil { 402 log.Error("error parsing UpdateZkEVMVersion event. Error: ", err) 403 return err 404 } 405 fork := ForkID{ 406 BatchNumber: zkevmVersion.NumBatch, 407 ForkID: zkevmVersion.ForkID, 408 Version: zkevmVersion.Version, 409 } 410 if len(*blocks) == 0 || ((*blocks)[len(*blocks)-1].BlockHash != vLog.BlockHash || (*blocks)[len(*blocks)-1].BlockNumber != vLog.BlockNumber) { 411 fullBlock, err := etherMan.EthClient.BlockByHash(ctx, vLog.BlockHash) 412 if err != nil { 413 return fmt.Errorf("error getting hashParent. BlockNumber: %d. Error: %w", vLog.BlockNumber, err) 414 } 415 t := time.Unix(int64(fullBlock.Time()), 0) 416 block := prepareBlock(vLog, t, fullBlock) 417 block.ForkIDs = append(block.ForkIDs, fork) 418 *blocks = append(*blocks, block) 419 } else if (*blocks)[len(*blocks)-1].BlockHash == vLog.BlockHash && (*blocks)[len(*blocks)-1].BlockNumber == vLog.BlockNumber { 420 (*blocks)[len(*blocks)-1].ForkIDs = append((*blocks)[len(*blocks)-1].ForkIDs, fork) 421 } else { 422 log.Error("Error processing updateZkevmVersion event. BlockHash:", vLog.BlockHash, ". BlockNumber: ", vLog.BlockNumber) 423 return fmt.Errorf("error processing updateZkevmVersion event") 424 } 425 or := Order{ 426 Name: ForkIDsOrder, 427 Pos: len((*blocks)[len(*blocks)-1].ForkIDs) - 1, 428 } 429 (*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash] = append((*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash], or) 430 return nil 431 } 432 433 func (etherMan *Client) updateGlobalExitRootEvent(ctx context.Context, vLog types.Log, blocks *[]Block, blocksOrder *map[common.Hash][]Order) error { 434 log.Debug("UpdateGlobalExitRoot event detected") 435 globalExitRoot, err := etherMan.GlobalExitRootManager.ParseUpdateGlobalExitRoot(vLog) 436 if err != nil { 437 return err 438 } 439 var gExitRoot GlobalExitRoot 440 gExitRoot.MainnetExitRoot = common.BytesToHash(globalExitRoot.MainnetExitRoot[:]) 441 gExitRoot.RollupExitRoot = common.BytesToHash(globalExitRoot.RollupExitRoot[:]) 442 gExitRoot.BlockNumber = vLog.BlockNumber 443 gExitRoot.GlobalExitRoot = hash(globalExitRoot.MainnetExitRoot, globalExitRoot.RollupExitRoot) 444 445 if len(*blocks) == 0 || ((*blocks)[len(*blocks)-1].BlockHash != vLog.BlockHash || (*blocks)[len(*blocks)-1].BlockNumber != vLog.BlockNumber) { 446 fullBlock, err := etherMan.EthClient.BlockByHash(ctx, vLog.BlockHash) 447 if err != nil { 448 return fmt.Errorf("error getting hashParent. BlockNumber: %d. Error: %w", vLog.BlockNumber, err) 449 } 450 t := time.Unix(int64(fullBlock.Time()), 0) 451 block := prepareBlock(vLog, t, fullBlock) 452 block.GlobalExitRoots = append(block.GlobalExitRoots, gExitRoot) 453 *blocks = append(*blocks, block) 454 } else if (*blocks)[len(*blocks)-1].BlockHash == vLog.BlockHash && (*blocks)[len(*blocks)-1].BlockNumber == vLog.BlockNumber { 455 (*blocks)[len(*blocks)-1].GlobalExitRoots = append((*blocks)[len(*blocks)-1].GlobalExitRoots, gExitRoot) 456 } else { 457 log.Error("Error processing UpdateGlobalExitRoot event. BlockHash:", vLog.BlockHash, ". BlockNumber: ", vLog.BlockNumber) 458 return fmt.Errorf("error processing UpdateGlobalExitRoot event") 459 } 460 or := Order{ 461 Name: GlobalExitRootsOrder, 462 Pos: len((*blocks)[len(*blocks)-1].GlobalExitRoots) - 1, 463 } 464 (*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash] = append((*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash], or) 465 return nil 466 } 467 468 // WaitTxToBeMined waits for an L1 tx to be mined. It will return error if the tx is reverted or timeout is exceeded 469 func (etherMan *Client) WaitTxToBeMined(ctx context.Context, tx *types.Transaction, timeout time.Duration) (bool, error) { 470 err := operations.WaitTxToBeMined(ctx, etherMan.EthClient, tx, timeout) 471 if errors.Is(err, context.DeadlineExceeded) { 472 return false, nil 473 } 474 if err != nil { 475 return false, err 476 } 477 return true, nil 478 } 479 480 // EstimateGasSequenceBatches estimates gas for sending batches 481 func (etherMan *Client) EstimateGasSequenceBatches( 482 sender common.Address, 483 sequences []ethmanTypes.Sequence, 484 committeeSignaturesAndAddrs []byte, 485 ) (*types.Transaction, error) { 486 opts, err := etherMan.getAuthByAddress(sender) 487 if err == ErrNotFound { 488 return nil, ErrPrivateKeyNotFound 489 } 490 opts.NoSend = true 491 492 tx, err := etherMan.sequenceBatches(opts, sequences, committeeSignaturesAndAddrs) 493 if err != nil { 494 return nil, err 495 } 496 497 return tx, nil 498 } 499 500 // BuildSequenceBatchesTxData builds a []bytes to be sent to the PoE SC method SequenceBatches. 501 func (etherMan *Client) BuildSequenceBatchesTxData( 502 sender common.Address, 503 sequences []ethmanTypes.Sequence, 504 committeeSignaturesAndAddrs []byte, 505 ) (to *common.Address, data []byte, err error) { 506 opts, err := etherMan.getAuthByAddress(sender) 507 if err == ErrNotFound { 508 return nil, nil, fmt.Errorf("failed to build sequence batches, err: %w", ErrPrivateKeyNotFound) 509 } 510 opts.NoSend = true 511 // force nonce, gas limit and gas price to avoid querying it from the chain 512 opts.Nonce = big.NewInt(1) 513 opts.GasLimit = uint64(1) 514 opts.GasPrice = big.NewInt(1) 515 516 tx, err := etherMan.sequenceBatches(opts, sequences, committeeSignaturesAndAddrs) 517 if err != nil { 518 return nil, nil, err 519 } 520 521 return tx.To(), tx.Data(), nil 522 } 523 524 func (etherMan *Client) sequenceBatches( 525 opts bind.TransactOpts, 526 sequences []ethmanTypes.Sequence, 527 committeeSignaturesAndAddrs []byte, 528 ) (*types.Transaction, error) { 529 var batches []supernets2.Supernets2BatchData 530 for _, seq := range sequences { 531 batch := supernets2.Supernets2BatchData{ 532 TransactionsHash: crypto.Keccak256Hash(seq.BatchL2Data), 533 GlobalExitRoot: seq.GlobalExitRoot, 534 Timestamp: uint64(seq.Timestamp), 535 MinForcedTimestamp: uint64(seq.ForcedBatchTimestamp), 536 } 537 538 batches = append(batches, batch) 539 } 540 541 tx, err := etherMan.Supernets2.SequenceBatches(&opts, batches, opts.From, committeeSignaturesAndAddrs) 542 if err != nil { 543 if parsedErr, ok := tryParseError(err); ok { 544 err = parsedErr 545 } 546 err = fmt.Errorf( 547 "error sequencing batches: %w, committeeSignaturesAndAddrs %s", 548 err, common.Bytes2Hex(committeeSignaturesAndAddrs), 549 ) 550 } 551 552 return tx, err 553 } 554 555 // BuildTrustedVerifyBatchesTxData builds a []bytes to be sent to the PoE SC method TrustedVerifyBatches. 556 func (etherMan *Client) BuildTrustedVerifyBatchesTxData(lastVerifiedBatch, newVerifiedBatch uint64, inputs *ethmanTypes.FinalProofInputs) (to *common.Address, data []byte, err error) { 557 opts, err := etherMan.generateRandomAuth() 558 if err != nil { 559 return nil, nil, fmt.Errorf("failed to build trusted verify batches, err: %w", err) 560 } 561 opts.NoSend = true 562 // force nonce, gas limit and gas price to avoid querying it from the chain 563 opts.Nonce = big.NewInt(1) 564 opts.GasLimit = uint64(1) 565 opts.GasPrice = big.NewInt(1) 566 567 var newLocalExitRoot [32]byte 568 copy(newLocalExitRoot[:], inputs.NewLocalExitRoot) 569 570 var newStateRoot [32]byte 571 copy(newStateRoot[:], inputs.NewStateRoot) 572 573 proof, err := encoding.DecodeBytes(&inputs.FinalProof.Proof) 574 if err != nil { 575 return nil, nil, fmt.Errorf("failed to decode proof, err: %w", err) 576 } 577 578 const pendStateNum = 0 // TODO hardcoded for now until we implement the pending state feature 579 580 tx, err := etherMan.Supernets2.VerifyBatchesTrustedAggregator( 581 &opts, 582 pendStateNum, 583 lastVerifiedBatch, 584 newVerifiedBatch, 585 newLocalExitRoot, 586 newStateRoot, 587 proof, 588 ) 589 if err != nil { 590 if parsedErr, ok := tryParseError(err); ok { 591 err = parsedErr 592 } 593 return nil, nil, err 594 } 595 596 return tx.To(), tx.Data(), nil 597 } 598 599 // GetSendSequenceFee get super/trusted sequencer fee 600 func (etherMan *Client) GetSendSequenceFee(numBatches uint64) (*big.Int, error) { 601 f, err := etherMan.Supernets2.BatchFee(&bind.CallOpts{Pending: false}) 602 if err != nil { 603 return nil, err 604 } 605 fee := new(big.Int).Mul(f, new(big.Int).SetUint64(numBatches)) 606 return fee, nil 607 } 608 609 // TrustedSequencer gets trusted sequencer address 610 func (etherMan *Client) TrustedSequencer() (common.Address, error) { 611 return etherMan.Supernets2.TrustedSequencer(&bind.CallOpts{Pending: false}) 612 } 613 614 func (etherMan *Client) forcedBatchEvent(ctx context.Context, vLog types.Log, blocks *[]Block, blocksOrder *map[common.Hash][]Order) error { 615 log.Debug("ForceBatch event detected") 616 fb, err := etherMan.Supernets2.ParseForceBatch(vLog) 617 if err != nil { 618 return err 619 } 620 var forcedBatch ForcedBatch 621 forcedBatch.BlockNumber = vLog.BlockNumber 622 forcedBatch.ForcedBatchNumber = fb.ForceBatchNum 623 forcedBatch.GlobalExitRoot = fb.LastGlobalExitRoot 624 // Read the tx for this batch. 625 tx, isPending, err := etherMan.EthClient.TransactionByHash(ctx, vLog.TxHash) 626 if err != nil { 627 return err 628 } else if isPending { 629 return fmt.Errorf("error: tx is still pending. TxHash: %s", tx.Hash().String()) 630 } 631 msg, err := core.TransactionToMessage(tx, types.NewLondonSigner(tx.ChainId()), big.NewInt(0)) 632 if err != nil { 633 return err 634 } 635 if fb.Sequencer == msg.From { 636 txData := tx.Data() 637 // Extract coded txs. 638 // Load contract ABI 639 abi, err := abi.JSON(strings.NewReader(supernets2.Supernets2ABI)) 640 if err != nil { 641 return err 642 } 643 644 // Recover Method from signature and ABI 645 method, err := abi.MethodById(txData[:4]) 646 if err != nil { 647 return err 648 } 649 650 // Unpack method inputs 651 data, err := method.Inputs.Unpack(txData[4:]) 652 if err != nil { 653 return err 654 } 655 bytedata := data[0].([]byte) 656 forcedBatch.RawTxsData = bytedata 657 } else { 658 forcedBatch.RawTxsData = fb.Transactions 659 } 660 forcedBatch.Sequencer = fb.Sequencer 661 fullBlock, err := etherMan.EthClient.BlockByHash(ctx, vLog.BlockHash) 662 if err != nil { 663 return fmt.Errorf("error getting hashParent. BlockNumber: %d. Error: %w", vLog.BlockNumber, err) 664 } 665 t := time.Unix(int64(fullBlock.Time()), 0) 666 forcedBatch.ForcedAt = t 667 if len(*blocks) == 0 || ((*blocks)[len(*blocks)-1].BlockHash != vLog.BlockHash || (*blocks)[len(*blocks)-1].BlockNumber != vLog.BlockNumber) { 668 block := prepareBlock(vLog, t, fullBlock) 669 block.ForcedBatches = append(block.ForcedBatches, forcedBatch) 670 *blocks = append(*blocks, block) 671 } else if (*blocks)[len(*blocks)-1].BlockHash == vLog.BlockHash && (*blocks)[len(*blocks)-1].BlockNumber == vLog.BlockNumber { 672 (*blocks)[len(*blocks)-1].ForcedBatches = append((*blocks)[len(*blocks)-1].ForcedBatches, forcedBatch) 673 } else { 674 log.Error("Error processing ForceBatch event. BlockHash:", vLog.BlockHash, ". BlockNumber: ", vLog.BlockNumber) 675 return fmt.Errorf("error processing ForceBatch event") 676 } 677 or := Order{ 678 Name: ForcedBatchesOrder, 679 Pos: len((*blocks)[len(*blocks)-1].ForcedBatches) - 1, 680 } 681 (*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash] = append((*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash], or) 682 return nil 683 } 684 685 func (etherMan *Client) sequencedBatchesEvent(ctx context.Context, vLog types.Log, blocks *[]Block, blocksOrder *map[common.Hash][]Order) error { 686 log.Debug("SequenceBatches event detected") 687 sb, err := etherMan.Supernets2.ParseSequenceBatches(vLog) 688 if err != nil { 689 return err 690 } 691 // Read the tx for this event. 692 tx, isPending, err := etherMan.EthClient.TransactionByHash(ctx, vLog.TxHash) 693 if err != nil { 694 return err 695 } else if isPending { 696 return fmt.Errorf("error tx is still pending. TxHash: %s", tx.Hash().String()) 697 } 698 msg, err := core.TransactionToMessage(tx, types.NewLondonSigner(tx.ChainId()), big.NewInt(0)) 699 if err != nil { 700 return err 701 } 702 sequences, err := decodeSequences(tx.Data(), sb.NumBatch, msg.From, vLog.TxHash, msg.Nonce) 703 if err != nil { 704 return fmt.Errorf("error decoding the sequences: %v", err) 705 } 706 707 if len(*blocks) == 0 || ((*blocks)[len(*blocks)-1].BlockHash != vLog.BlockHash || (*blocks)[len(*blocks)-1].BlockNumber != vLog.BlockNumber) { 708 fullBlock, err := etherMan.EthClient.BlockByHash(ctx, vLog.BlockHash) 709 if err != nil { 710 return fmt.Errorf("error getting hashParent. BlockNumber: %d. Error: %w", vLog.BlockNumber, err) 711 } 712 block := prepareBlock(vLog, time.Unix(int64(fullBlock.Time()), 0), fullBlock) 713 block.SequencedBatches = append(block.SequencedBatches, sequences) 714 *blocks = append(*blocks, block) 715 } else if (*blocks)[len(*blocks)-1].BlockHash == vLog.BlockHash && (*blocks)[len(*blocks)-1].BlockNumber == vLog.BlockNumber { 716 (*blocks)[len(*blocks)-1].SequencedBatches = append((*blocks)[len(*blocks)-1].SequencedBatches, sequences) 717 } else { 718 log.Error("Error processing SequencedBatches event. BlockHash:", vLog.BlockHash, ". BlockNumber: ", vLog.BlockNumber) 719 return fmt.Errorf("error processing SequencedBatches event") 720 } 721 or := Order{ 722 Name: SequenceBatchesOrder, 723 Pos: len((*blocks)[len(*blocks)-1].SequencedBatches) - 1, 724 } 725 (*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash] = append((*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash], or) 726 return nil 727 } 728 729 func decodeSequences(txData []byte, lastBatchNumber uint64, sequencer common.Address, txHash common.Hash, nonce uint64) ([]SequencedBatch, error) { 730 // Extract coded txs. 731 // Load contract ABI 732 abi, err := abi.JSON(strings.NewReader(supernets2.Supernets2ABI)) 733 if err != nil { 734 return nil, err 735 } 736 737 // Recover Method from signature and ABI 738 method, err := abi.MethodById(txData[:4]) 739 if err != nil { 740 return nil, err 741 } 742 743 // Unpack method inputs 744 data, err := method.Inputs.Unpack(txData[4:]) 745 if err != nil { 746 return nil, err 747 } 748 var sequences []supernets2.Supernets2BatchData 749 bytedata, err := json.Marshal(data[0]) 750 if err != nil { 751 return nil, err 752 } 753 err = json.Unmarshal(bytedata, &sequences) 754 if err != nil { 755 return nil, err 756 } 757 coinbase := (data[1]).(common.Address) 758 sequencedBatches := make([]SequencedBatch, len(sequences)) 759 for i, seq := range sequences { 760 bn := lastBatchNumber - uint64(len(sequences)-(i+1)) 761 sequencedBatches[i] = SequencedBatch{ 762 BatchNumber: bn, 763 SequencerAddr: sequencer, 764 TxHash: txHash, 765 Nonce: nonce, 766 Coinbase: coinbase, 767 Supernets2BatchData: seq, 768 } 769 } 770 771 return sequencedBatches, nil 772 } 773 774 func (etherMan *Client) verifyBatchesTrustedAggregatorEvent(ctx context.Context, vLog types.Log, blocks *[]Block, blocksOrder *map[common.Hash][]Order) error { 775 log.Debug("TrustedVerifyBatches event detected") 776 vb, err := etherMan.Supernets2.ParseVerifyBatchesTrustedAggregator(vLog) 777 if err != nil { 778 return err 779 } 780 var trustedVerifyBatch VerifiedBatch 781 trustedVerifyBatch.BlockNumber = vLog.BlockNumber 782 trustedVerifyBatch.BatchNumber = vb.NumBatch 783 trustedVerifyBatch.TxHash = vLog.TxHash 784 trustedVerifyBatch.StateRoot = vb.StateRoot 785 trustedVerifyBatch.Aggregator = vb.Aggregator 786 787 if len(*blocks) == 0 || ((*blocks)[len(*blocks)-1].BlockHash != vLog.BlockHash || (*blocks)[len(*blocks)-1].BlockNumber != vLog.BlockNumber) { 788 fullBlock, err := etherMan.EthClient.BlockByHash(ctx, vLog.BlockHash) 789 if err != nil { 790 return fmt.Errorf("error getting hashParent. BlockNumber: %d. Error: %w", vLog.BlockNumber, err) 791 } 792 block := prepareBlock(vLog, time.Unix(int64(fullBlock.Time()), 0), fullBlock) 793 block.VerifiedBatches = append(block.VerifiedBatches, trustedVerifyBatch) 794 *blocks = append(*blocks, block) 795 } else if (*blocks)[len(*blocks)-1].BlockHash == vLog.BlockHash && (*blocks)[len(*blocks)-1].BlockNumber == vLog.BlockNumber { 796 (*blocks)[len(*blocks)-1].VerifiedBatches = append((*blocks)[len(*blocks)-1].VerifiedBatches, trustedVerifyBatch) 797 } else { 798 log.Error("Error processing trustedVerifyBatch event. BlockHash:", vLog.BlockHash, ". BlockNumber: ", vLog.BlockNumber) 799 return fmt.Errorf("error processing trustedVerifyBatch event") 800 } 801 or := Order{ 802 Name: TrustedVerifyBatchOrder, 803 Pos: len((*blocks)[len(*blocks)-1].VerifiedBatches) - 1, 804 } 805 (*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash] = append((*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash], or) 806 return nil 807 } 808 809 func (etherMan *Client) forceSequencedBatchesEvent(ctx context.Context, vLog types.Log, blocks *[]Block, blocksOrder *map[common.Hash][]Order) error { 810 log.Debug("SequenceForceBatches event detect") 811 fsb, err := etherMan.Supernets2.ParseSequenceForceBatches(vLog) 812 if err != nil { 813 return err 814 } 815 816 // Read the tx for this batch. 817 tx, isPending, err := etherMan.EthClient.TransactionByHash(ctx, vLog.TxHash) 818 if err != nil { 819 return err 820 } else if isPending { 821 return fmt.Errorf("error: tx is still pending. TxHash: %s", tx.Hash().String()) 822 } 823 msg, err := core.TransactionToMessage(tx, types.NewLondonSigner(tx.ChainId()), big.NewInt(0)) 824 if err != nil { 825 return err 826 } 827 fullBlock, err := etherMan.EthClient.BlockByHash(ctx, vLog.BlockHash) 828 if err != nil { 829 return fmt.Errorf("error getting hashParent. BlockNumber: %d. Error: %w", vLog.BlockNumber, err) 830 } 831 sequencedForceBatch, err := decodeSequencedForceBatches(tx.Data(), fsb.NumBatch, msg.From, vLog.TxHash, fullBlock, msg.Nonce) 832 if err != nil { 833 return err 834 } 835 836 if len(*blocks) == 0 || ((*blocks)[len(*blocks)-1].BlockHash != vLog.BlockHash || (*blocks)[len(*blocks)-1].BlockNumber != vLog.BlockNumber) { 837 block := prepareBlock(vLog, time.Unix(int64(fullBlock.Time()), 0), fullBlock) 838 block.SequencedForceBatches = append(block.SequencedForceBatches, sequencedForceBatch) 839 *blocks = append(*blocks, block) 840 } else if (*blocks)[len(*blocks)-1].BlockHash == vLog.BlockHash && (*blocks)[len(*blocks)-1].BlockNumber == vLog.BlockNumber { 841 (*blocks)[len(*blocks)-1].SequencedForceBatches = append((*blocks)[len(*blocks)-1].SequencedForceBatches, sequencedForceBatch) 842 } else { 843 log.Error("Error processing ForceSequencedBatches event. BlockHash:", vLog.BlockHash, ". BlockNumber: ", vLog.BlockNumber) 844 return fmt.Errorf("error processing ForceSequencedBatches event") 845 } 846 or := Order{ 847 Name: SequenceForceBatchesOrder, 848 Pos: len((*blocks)[len(*blocks)-1].SequencedForceBatches) - 1, 849 } 850 (*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash] = append((*blocksOrder)[(*blocks)[len(*blocks)-1].BlockHash], or) 851 852 return nil 853 } 854 855 func decodeSequencedForceBatches(txData []byte, lastBatchNumber uint64, sequencer common.Address, txHash common.Hash, block *types.Block, nonce uint64) ([]SequencedForceBatch, error) { 856 // Extract coded txs. 857 // Load contract ABI 858 abi, err := abi.JSON(strings.NewReader(supernets2.Supernets2ABI)) 859 if err != nil { 860 return nil, err 861 } 862 863 // Recover Method from signature and ABI 864 method, err := abi.MethodById(txData[:4]) 865 if err != nil { 866 return nil, err 867 } 868 869 // Unpack method inputs 870 data, err := method.Inputs.Unpack(txData[4:]) 871 if err != nil { 872 return nil, err 873 } 874 875 var forceBatches []supernets2.Supernets2ForcedBatchData 876 bytedata, err := json.Marshal(data[0]) 877 if err != nil { 878 return nil, err 879 } 880 err = json.Unmarshal(bytedata, &forceBatches) 881 if err != nil { 882 return nil, err 883 } 884 885 sequencedForcedBatches := make([]SequencedForceBatch, len(forceBatches)) 886 for i, force := range forceBatches { 887 bn := lastBatchNumber - uint64(len(forceBatches)-(i+1)) 888 sequencedForcedBatches[i] = SequencedForceBatch{ 889 BatchNumber: bn, 890 Coinbase: sequencer, 891 TxHash: txHash, 892 Timestamp: time.Unix(int64(block.Time()), 0), 893 Nonce: nonce, 894 Supernets2ForcedBatchData: force, 895 } 896 } 897 return sequencedForcedBatches, nil 898 } 899 900 func prepareBlock(vLog types.Log, t time.Time, fullBlock *types.Block) Block { 901 var block Block 902 block.BlockNumber = vLog.BlockNumber 903 block.BlockHash = vLog.BlockHash 904 block.ParentHash = fullBlock.ParentHash() 905 block.ReceivedAt = t 906 return block 907 } 908 909 func hash(data ...[32]byte) [32]byte { 910 var res [32]byte 911 hash := sha3.NewLegacyKeccak256() 912 for _, d := range data { 913 hash.Write(d[:]) //nolint:errcheck,gosec 914 } 915 copy(res[:], hash.Sum(nil)) 916 return res 917 } 918 919 // HeaderByNumber returns a block header from the current canonical chain. If number is 920 // nil, the latest known header is returned. 921 func (etherMan *Client) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) { 922 return etherMan.EthClient.HeaderByNumber(ctx, number) 923 } 924 925 // EthBlockByNumber function retrieves the ethereum block information by ethereum block number. 926 func (etherMan *Client) EthBlockByNumber(ctx context.Context, blockNumber uint64) (*types.Block, error) { 927 block, err := etherMan.EthClient.BlockByNumber(ctx, new(big.Int).SetUint64(blockNumber)) 928 if err != nil { 929 if errors.Is(err, ethereum.NotFound) || err.Error() == "block does not exist in blockchain" { 930 return nil, ErrNotFound 931 } 932 return nil, err 933 } 934 return block, nil 935 } 936 937 // GetLastBatchTimestamp function allows to retrieve the lastTimestamp value in the smc 938 func (etherMan *Client) GetLastBatchTimestamp() (uint64, error) { 939 return etherMan.Supernets2.LastTimestamp(&bind.CallOpts{Pending: false}) 940 } 941 942 // GetLatestBatchNumber function allows to retrieve the latest proposed batch in the smc 943 func (etherMan *Client) GetLatestBatchNumber() (uint64, error) { 944 return etherMan.Supernets2.LastBatchSequenced(&bind.CallOpts{Pending: false}) 945 } 946 947 // GetLatestBlockNumber gets the latest block number from the ethereum 948 func (etherMan *Client) GetLatestBlockNumber(ctx context.Context) (uint64, error) { 949 header, err := etherMan.EthClient.HeaderByNumber(ctx, nil) 950 if err != nil || header == nil { 951 return 0, err 952 } 953 return header.Number.Uint64(), nil 954 } 955 956 // GetLatestBlockTimestamp gets the latest block timestamp from the ethereum 957 func (etherMan *Client) GetLatestBlockTimestamp(ctx context.Context) (uint64, error) { 958 header, err := etherMan.EthClient.HeaderByNumber(ctx, nil) 959 if err != nil || header == nil { 960 return 0, err 961 } 962 return header.Time, nil 963 } 964 965 // GetLatestVerifiedBatchNum gets latest verified batch from ethereum 966 func (etherMan *Client) GetLatestVerifiedBatchNum() (uint64, error) { 967 return etherMan.Supernets2.LastVerifiedBatch(&bind.CallOpts{Pending: false}) 968 } 969 970 // GetTx function get ethereum tx 971 func (etherMan *Client) GetTx(ctx context.Context, txHash common.Hash) (*types.Transaction, bool, error) { 972 return etherMan.EthClient.TransactionByHash(ctx, txHash) 973 } 974 975 // GetTxReceipt function gets ethereum tx receipt 976 func (etherMan *Client) GetTxReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) { 977 return etherMan.EthClient.TransactionReceipt(ctx, txHash) 978 } 979 980 // ApproveMatic function allow to approve tokens in matic smc 981 func (etherMan *Client) ApproveMatic(ctx context.Context, account common.Address, maticAmount *big.Int, to common.Address) (*types.Transaction, error) { 982 opts, err := etherMan.getAuthByAddress(account) 983 if err == ErrNotFound { 984 return nil, errors.New("can't find account private key to sign tx") 985 } 986 if etherMan.GasProviders.MultiGasProvider { 987 opts.GasPrice = etherMan.GetL1GasPrice(ctx) 988 } 989 tx, err := etherMan.Matic.Approve(&opts, etherMan.l1Cfg.Supernets2Addr, maticAmount) 990 if err != nil { 991 if parsedErr, ok := tryParseError(err); ok { 992 err = parsedErr 993 } 994 return nil, fmt.Errorf("error approving balance to send the batch. Error: %w", err) 995 } 996 997 return tx, nil 998 } 999 1000 // GetTrustedSequencerURL Gets the trusted sequencer url from rollup smc 1001 func (etherMan *Client) GetTrustedSequencerURL() (string, error) { 1002 return etherMan.Supernets2.TrustedSequencerURL(&bind.CallOpts{Pending: false}) 1003 } 1004 1005 // GetL2ChainID returns L2 Chain ID 1006 func (etherMan *Client) GetL2ChainID() (uint64, error) { 1007 return etherMan.Supernets2.ChainID(&bind.CallOpts{Pending: false}) 1008 } 1009 1010 // GetL2ForkID returns current L2 Fork ID 1011 func (etherMan *Client) GetL2ForkID() (uint64, error) { 1012 // TODO: implement this 1013 return 1, nil 1014 } 1015 1016 // GetL2ForkIDIntervals return L2 Fork ID intervals 1017 func (etherMan *Client) GetL2ForkIDIntervals() ([]state.ForkIDInterval, error) { 1018 // TODO: implement this 1019 return []state.ForkIDInterval{{FromBatchNumber: 0, ToBatchNumber: math.MaxUint64, ForkId: 1}}, nil 1020 } 1021 1022 // GetL1GasPrice gets the l1 gas price 1023 func (etherMan *Client) GetL1GasPrice(ctx context.Context) *big.Int { 1024 // Get gasPrice from providers 1025 gasPrice := big.NewInt(0) 1026 for i, prov := range etherMan.GasProviders.Providers { 1027 gp, err := prov.SuggestGasPrice(ctx) 1028 if err != nil { 1029 log.Warnf("error getting gas price from provider %d. Error: %s", i+1, err.Error()) 1030 } else if gasPrice.Cmp(gp) == -1 { // gasPrice < gp 1031 gasPrice = gp 1032 } 1033 } 1034 log.Debug("gasPrice chose: ", gasPrice) 1035 return gasPrice 1036 } 1037 1038 // SendTx sends a tx to L1 1039 func (etherMan *Client) SendTx(ctx context.Context, tx *types.Transaction) error { 1040 return etherMan.EthClient.SendTransaction(ctx, tx) 1041 } 1042 1043 // CurrentNonce returns the current nonce for the provided account 1044 func (etherMan *Client) CurrentNonce(ctx context.Context, account common.Address) (uint64, error) { 1045 return etherMan.EthClient.NonceAt(ctx, account, nil) 1046 } 1047 1048 // SuggestedGasPrice returns the suggest nonce for the network at the moment 1049 func (etherMan *Client) SuggestedGasPrice(ctx context.Context) (*big.Int, error) { 1050 suggestedGasPrice := etherMan.GetL1GasPrice(ctx) 1051 if suggestedGasPrice.Cmp(big.NewInt(0)) == 0 { 1052 return nil, errors.New("failed to get the suggested gas price") 1053 } 1054 return suggestedGasPrice, nil 1055 } 1056 1057 // EstimateGas returns the estimated gas for the tx 1058 func (etherMan *Client) EstimateGas(ctx context.Context, from common.Address, to *common.Address, value *big.Int, data []byte) (uint64, error) { 1059 return etherMan.EthClient.EstimateGas(ctx, ethereum.CallMsg{ 1060 From: from, 1061 To: to, 1062 Value: value, 1063 Data: data, 1064 }) 1065 } 1066 1067 // CheckTxWasMined check if a tx was already mined 1068 func (etherMan *Client) CheckTxWasMined(ctx context.Context, txHash common.Hash) (bool, *types.Receipt, error) { 1069 receipt, err := etherMan.EthClient.TransactionReceipt(ctx, txHash) 1070 if errors.Is(err, ethereum.NotFound) { 1071 return false, nil, nil 1072 } else if err != nil { 1073 return false, nil, err 1074 } 1075 1076 return true, receipt, nil 1077 } 1078 1079 // SignTx tries to sign a transaction accordingly to the provided sender 1080 func (etherMan *Client) SignTx(ctx context.Context, sender common.Address, tx *types.Transaction) (*types.Transaction, error) { 1081 auth, err := etherMan.getAuthByAddress(sender) 1082 if err == ErrNotFound { 1083 return nil, ErrPrivateKeyNotFound 1084 } 1085 signedTx, err := auth.Signer(auth.From, tx) 1086 if err != nil { 1087 return nil, err 1088 } 1089 return signedTx, nil 1090 } 1091 1092 // GetRevertMessage tries to get a revert message of a transaction 1093 func (etherMan *Client) GetRevertMessage(ctx context.Context, tx *types.Transaction) (string, error) { 1094 if tx == nil { 1095 return "", nil 1096 } 1097 1098 receipt, err := etherMan.GetTxReceipt(ctx, tx.Hash()) 1099 if err != nil { 1100 return "", err 1101 } 1102 1103 if receipt.Status == types.ReceiptStatusFailed { 1104 revertMessage, err := operations.RevertReason(ctx, etherMan.EthClient, tx, receipt.BlockNumber) 1105 if err != nil { 1106 return "", err 1107 } 1108 return revertMessage, nil 1109 } 1110 return "", nil 1111 } 1112 1113 // AddOrReplaceAuth adds an authorization or replace an existent one to the same account 1114 func (etherMan *Client) AddOrReplaceAuth(auth bind.TransactOpts) error { 1115 log.Infof("added or replaced authorization for address: %v", auth.From.String()) 1116 etherMan.auth[auth.From] = auth 1117 return nil 1118 } 1119 1120 // LoadAuthFromKeyStore loads an authorization from a key store file 1121 func (etherMan *Client) LoadAuthFromKeyStore(path, password string) (*bind.TransactOpts, *ecdsa.PrivateKey, error) { 1122 auth, pk, err := newAuthFromKeystore(path, password, etherMan.l1Cfg.L1ChainID) 1123 if err != nil { 1124 return nil, nil, err 1125 } 1126 1127 log.Infof("loaded authorization for address: %v", auth.From.String()) 1128 etherMan.auth[auth.From] = auth 1129 return &auth, pk, nil 1130 } 1131 1132 // newKeyFromKeystore creates an instance of a keystore key from a keystore file 1133 func newKeyFromKeystore(path, password string) (*keystore.Key, error) { 1134 if path == "" && password == "" { 1135 return nil, nil 1136 } 1137 keystoreEncrypted, err := os.ReadFile(filepath.Clean(path)) 1138 if err != nil { 1139 return nil, err 1140 } 1141 log.Infof("decrypting key from: %v", path) 1142 key, err := keystore.DecryptKey(keystoreEncrypted, password) 1143 if err != nil { 1144 return nil, err 1145 } 1146 return key, nil 1147 } 1148 1149 // newAuthFromKeystore an authorization instance from a keystore file 1150 func newAuthFromKeystore(path, password string, chainID uint64) (bind.TransactOpts, *ecdsa.PrivateKey, error) { 1151 log.Infof("reading key from: %v", path) 1152 key, err := newKeyFromKeystore(path, password) 1153 if err != nil { 1154 return bind.TransactOpts{}, nil, err 1155 } 1156 if key == nil { 1157 return bind.TransactOpts{}, nil, nil 1158 } 1159 auth, err := bind.NewKeyedTransactorWithChainID(key.PrivateKey, new(big.Int).SetUint64(chainID)) 1160 if err != nil { 1161 return bind.TransactOpts{}, nil, err 1162 } 1163 return *auth, key.PrivateKey, nil 1164 } 1165 1166 // getAuthByAddress tries to get an authorization from the authorizations map 1167 func (etherMan *Client) getAuthByAddress(addr common.Address) (bind.TransactOpts, error) { 1168 auth, found := etherMan.auth[addr] 1169 if !found { 1170 return bind.TransactOpts{}, ErrNotFound 1171 } 1172 return auth, nil 1173 } 1174 1175 // generateRandomAuth generates an authorization instance from a 1176 // randomly generated private key to be used to estimate gas for PoE 1177 // operations NOT restricted to the Trusted Sequencer 1178 func (etherMan *Client) generateRandomAuth() (bind.TransactOpts, error) { 1179 privateKey, err := crypto.GenerateKey() 1180 if err != nil { 1181 return bind.TransactOpts{}, errors.New("failed to generate a private key to estimate L1 txs") 1182 } 1183 chainID := big.NewInt(0).SetUint64(etherMan.l1Cfg.L1ChainID) 1184 auth, err := bind.NewKeyedTransactorWithChainID(privateKey, chainID) 1185 if err != nil { 1186 return bind.TransactOpts{}, errors.New("failed to generate a fake authorization to estimate L1 txs") 1187 } 1188 1189 return *auth, nil 1190 }