diff --git a/README.md b/README.md index e7a61335d..e4a92cc9c 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ $ ./razor setConfig --provider --gasmultiplier docker ``` -docker exec -it razor-go razor setConfig --provider --alternateProvider --gasmultiplier --buffer --wait --gasprice --logLevel --gasLimit --rpcTimeout --httpTimeout --logFileMaxSize --logFileMaxBackups --logFileMaxAge +docker exec -it razor-go razor setConfig --provider --gasmultiplier --buffer --wait --gasprice --logLevel --gasLimit --rpcTimeout --httpTimeout --logFileMaxSize --logFileMaxBackups --logFileMaxAge ``` Example: @@ -190,6 +190,23 @@ Password: _Before staking on Razor Network, please ensure your account has sFUEL and RAZOR. For testnet RAZOR, please contact us on Discord._ +### Import Endpoints + +You can import the endpoints to file `$HOME/.razor/endpoints.json` on your local by using the `importEndpoints` command. +This command imports multiple providers along with the user input provider, which are then sorted according to the best performance. The best provider is thus chosen by the RPC manager and will be used to make the RPC calls. + +razor cli + +``` +$ ./razor importEndpoints +``` + +docker + +``` +docker exec -it razor-go razor importEndpoints +``` + ### Stake If you have a minimum of 1000 razors in your account, you can stake those using the addStake command. diff --git a/accounts/accounts.go b/accounts/accounts.go index 4284ed6a3..9e0a47ddb 100644 --- a/accounts/accounts.go +++ b/accounts/accounts.go @@ -13,7 +13,7 @@ import ( "strings" ) -var log = logger.NewLogger() +var log = logger.GetLogger() //This function takes path and password as input and returns new account func (am *AccountManager) CreateAccount(keystorePath string, password string) accounts.Account { diff --git a/block/block.go b/block/block.go index ea896d420..08782e45c 100644 --- a/block/block.go +++ b/block/block.go @@ -2,40 +2,112 @@ package block import ( "context" - "razor/core" "sync" "time" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" "github.com/sirupsen/logrus" + "razor/rpc" ) -var latestBlock *types.Header -var mu = sync.Mutex{} +// BlockMonitor monitors the latest block and handles stale blocks. +type BlockMonitor struct { + client *ethclient.Client + rpcManager *rpc.RPCManager + latestBlock *types.Header + mu sync.Mutex + checkInterval time.Duration + staleThreshold time.Duration +} + +// NewBlockMonitor initializes a BlockMonitor with RPC integration. +func NewBlockMonitor(client *ethclient.Client, rpcManager *rpc.RPCManager, checkInterval, staleThreshold time.Duration) *BlockMonitor { + return &BlockMonitor{ + client: client, + rpcManager: rpcManager, + checkInterval: time.Second * checkInterval, + staleThreshold: time.Second * staleThreshold, + } +} -func GetLatestBlock() *types.Header { - mu.Lock() - defer mu.Unlock() - return latestBlock +// Start begins the block monitoring process. +func (bm *BlockMonitor) Start() { + go func() { + for { + bm.updateLatestBlock() + bm.checkForStaleBlock() + time.Sleep(bm.checkInterval) + } + }() } -func SetLatestBlock(block *types.Header) { - mu.Lock() - latestBlock = block - mu.Unlock() +// GetLatestBlock retrieves the most recent block header safely. +func (bm *BlockMonitor) GetLatestBlock() *types.Header { + bm.mu.Lock() + defer bm.mu.Unlock() + return bm.latestBlock } -func CalculateLatestBlock(client *ethclient.Client) { - for { - if client != nil { - latestHeader, err := client.HeaderByNumber(context.Background(), nil) +// updateLatestBlock fetches the latest block and updates the state. +func (bm *BlockMonitor) updateLatestBlock() { + if bm.client == nil { + return + } + + header, err := bm.client.HeaderByNumber(context.Background(), nil) + if err != nil { + logrus.Errorf("Error fetching latest block: %v", err) + return + } + + bm.mu.Lock() + defer bm.mu.Unlock() + + // Update the latest block only if it changes. + if bm.latestBlock == nil || header.Number.Uint64() != bm.latestBlock.Number.Uint64() { + bm.latestBlock = header + } +} + +// checkForStaleBlock detects stale blocks and triggers appropriate actions. +func (bm *BlockMonitor) checkForStaleBlock() { + if bm.staleThreshold == 0 { + return + } + + bm.mu.Lock() + defer bm.mu.Unlock() + + if bm.latestBlock == nil || time.Since(time.Unix(int64(bm.latestBlock.Time), 0)) >= bm.staleThreshold { + logrus.Warnf("Stale block detected: Block %d is stale for %s", bm.latestBlock.Number.Uint64(), bm.staleThreshold) + + // Switch to the next best RPC endpoint if stale block detected. + if bm.rpcManager != nil { + switched, err := bm.rpcManager.SwitchToNextBestRPCClient() if err != nil { - logrus.Error("CalculateBlockNumber: Error in fetching block: ", err) + logrus.Errorf("Failed to switch RPC endpoint: %v", err) + } else if switched { + logrus.Info("Switched to the next best RPC endpoint.") + bm.updateClient() } else { - SetLatestBlock(latestHeader) + logrus.Warn("Retaining the current best RPC endpoint as no valid alternate was found.") } } - time.Sleep(time.Second * time.Duration(core.BlockNumberInterval)) } } + +// updateClient updates the Ethereum client to use the new best RPC endpoint. +func (bm *BlockMonitor) updateClient() { + if bm.rpcManager == nil { + return + } + + newClient, err := bm.rpcManager.GetBestRPCClient() + if err != nil { + return + } + + bm.client = newClient + logrus.Info("Client in logger updated with the new best RPC endpoint.") +} diff --git a/client/alternateClient.go b/client/alternateClient.go deleted file mode 100644 index 7d2394ff0..000000000 --- a/client/alternateClient.go +++ /dev/null @@ -1,63 +0,0 @@ -package client - -import ( - "github.com/ethereum/go-ethereum/ethclient" - "razor/logger" - "reflect" - "time" -) - -var ( - log = logger.NewLogger() - alternateClientStruct AlternateClientStruct -) - -type AlternateClientStruct struct { - switchToAlternateClient bool - alternateProvider string -} - -func StartTimerForAlternateClient(switchClientAfterTime uint64) { - log.Infof("StartTimerForAlternateClient: Alternate client will be switched back to primary client in %v seconds!", switchClientAfterTime) - time.Sleep(time.Duration(switchClientAfterTime) * time.Second) - log.Info("Switching back to primary RPC..") - SetSwitchToAlternateClientStatus(false) -} - -//ReplaceClientWithAlternateClient will replace the primary client(client from primary RPC) with secondary client which would be created using alternate RPC -func ReplaceClientWithAlternateClient(arguments []reflect.Value) []reflect.Value { - clientDataType := reflect.TypeOf((*ethclient.Client)(nil)).Elem() - for i := range arguments { - argument := arguments[i] - argumentDataType := reflect.TypeOf(argument.Interface()).Elem() - if argumentDataType != nil { - if argumentDataType == clientDataType { - alternateProvider := GetAlternateProvider() - alternateClient, dialErr := ethclient.Dial(alternateProvider) - if dialErr != nil { - log.Errorf("Error in connecting using alternate RPC %v: %v", alternateProvider, dialErr) - return arguments - } - arguments[i] = reflect.ValueOf(alternateClient) - return arguments - } - } - } - return arguments -} - -func GetSwitchToAlternateClientStatus() bool { - return alternateClientStruct.switchToAlternateClient -} - -func SetSwitchToAlternateClientStatus(status bool) { - alternateClientStruct.switchToAlternateClient = status -} - -func GetAlternateProvider() string { - return alternateClientStruct.alternateProvider -} - -func SetAlternateProvider(alternateProvider string) { - alternateClientStruct.alternateProvider = alternateProvider -} diff --git a/cmd/addStake.go b/cmd/addStake.go index 7092b3292..5f2c70c1c 100644 --- a/cmd/addStake.go +++ b/cmd/addStake.go @@ -2,12 +2,10 @@ package cmd import ( - "context" - "razor/accounts" "razor/core" "razor/core/types" - "razor/logger" "razor/pkg/bindings" + "razor/rpc" "razor/utils" "github.com/spf13/pflag" @@ -34,33 +32,11 @@ func initialiseStake(cmd *cobra.Command, args []string) { //This function sets the flags appropriately and executes the StakeCoins function func (*UtilsStruct) ExecuteStake(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - log.Debugf("ExecuteStake: config: %+v", config) + config, rpcParameters, account, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) - client := razorUtils.ConnectToClient(config.Provider) - - address, err := flagSetUtils.GetStringAddress(flagSet) - utils.CheckError("Error in getting address: ", err) - log.Debug("ExecuteStake: Address: ", address) - - logger.SetLoggerParameters(client, address) - log.Debug("Checking to assign log file...") - fileUtils.AssignLogFile(flagSet, config) - - log.Debug("Getting password...") - password := razorUtils.AssignPassword(flagSet) - - accountManager, err := razorUtils.AccountManagerForKeystore() - utils.CheckError("Error in getting accounts manager for keystore: ", err) - - account := accounts.InitAccountStruct(address, password, accountManager) - - err = razorUtils.CheckPassword(account) - utils.CheckError("Error in fetching private key from given password: ", err) - - balance, err := razorUtils.FetchBalance(client, address) - utils.CheckError("Error in fetching razor balance for account: "+address, err) + balance, err := razorUtils.FetchBalance(rpcParameters, account.Address) + utils.CheckError("Error in fetching razor balance for account: "+account.Address, err) log.Debug("Getting amount in wei...") valueInWei, err := cmdUtils.AssignAmountInWei(flagSet) utils.CheckError("Error in getting amount: ", err) @@ -70,13 +46,13 @@ func (*UtilsStruct) ExecuteStake(flagSet *pflag.FlagSet) { razorUtils.CheckAmountAndBalance(valueInWei, balance) log.Debug("Checking whether sFUEL balance is not 0...") - razorUtils.CheckEthBalanceIsZero(context.Background(), client, address) + razorUtils.CheckEthBalanceIsZero(rpcParameters, account.Address) - minSafeRazor, err := razorUtils.GetMinSafeRazor(context.Background(), client) + minSafeRazor, err := razorUtils.GetMinSafeRazor(rpcParameters) utils.CheckError("Error in getting minimum safe razor amount: ", err) log.Debug("ExecuteStake: Minimum razor that you can stake for first time: ", minSafeRazor) - stakerId, err := razorUtils.GetStakerId(context.Background(), client, address) + stakerId, err := razorUtils.GetStakerId(rpcParameters, account.Address) utils.CheckError("Error in getting stakerId: ", err) log.Debug("ExecuteStake: Staker Id: ", stakerId) @@ -85,7 +61,7 @@ func (*UtilsStruct) ExecuteStake(flagSet *pflag.FlagSet) { } if stakerId != 0 { - staker, err := razorUtils.GetStaker(context.Background(), client, stakerId) + staker, err := razorUtils.GetStaker(rpcParameters, stakerId) utils.CheckError("Error in getting staker: ", err) if staker.IsSlashed { @@ -94,7 +70,6 @@ func (*UtilsStruct) ExecuteStake(flagSet *pflag.FlagSet) { } txnArgs := types.TransactionOptions{ - Client: client, Amount: valueInWei, ChainId: core.ChainId, Config: config, @@ -102,25 +77,25 @@ func (*UtilsStruct) ExecuteStake(flagSet *pflag.FlagSet) { } log.Debug("ExecuteStake: Calling Approve() for amount: ", txnArgs.Amount) - approveTxnHash, err := cmdUtils.Approve(txnArgs) + approveTxnHash, err := cmdUtils.Approve(rpcParameters, txnArgs) utils.CheckError("Approve error: ", err) if approveTxnHash != core.NilHash { - err = razorUtils.WaitForBlockCompletion(txnArgs.Client, approveTxnHash.Hex()) + err = razorUtils.WaitForBlockCompletion(rpcParameters, approveTxnHash.Hex()) utils.CheckError("Error in WaitForBlockCompletion for approve: ", err) } log.Debug("ExecuteStake: Calling StakeCoins() for amount: ", txnArgs.Amount) - stakeTxnHash, err := cmdUtils.StakeCoins(txnArgs) + stakeTxnHash, err := cmdUtils.StakeCoins(rpcParameters, txnArgs) utils.CheckError("Stake error: ", err) - err = razorUtils.WaitForBlockCompletion(txnArgs.Client, stakeTxnHash.Hex()) + err = razorUtils.WaitForBlockCompletion(rpcParameters, stakeTxnHash.Hex()) utils.CheckError("Error in WaitForBlockCompletion for stake: ", err) } //This function allows the user to stake razors in the razor network and returns the hash -func (*UtilsStruct) StakeCoins(txnArgs types.TransactionOptions) (common.Hash, error) { - epoch, err := razorUtils.GetEpoch(context.Background(), txnArgs.Client) +func (*UtilsStruct) StakeCoins(rpcParameters rpc.RPCParameters, txnArgs types.TransactionOptions) (common.Hash, error) { + epoch, err := razorUtils.GetEpoch(rpcParameters) if err != nil { return core.NilHash, err } @@ -130,9 +105,15 @@ func (*UtilsStruct) StakeCoins(txnArgs types.TransactionOptions) (common.Hash, e txnArgs.MethodName = "stake" txnArgs.Parameters = []interface{}{epoch, txnArgs.Amount} txnArgs.ABI = bindings.StakeManagerMetaData.ABI - txnOpts := razorUtils.GetTxnOpts(context.Background(), txnArgs) + txnOpts := razorUtils.GetTxnOpts(rpcParameters, txnArgs) + + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return core.NilHash, err + } + log.Debugf("Executing Stake transaction with epoch = %d, amount = %d", epoch, txnArgs.Amount) - txn, err := stakeManagerUtils.Stake(txnArgs.Client, txnOpts, epoch, txnArgs.Amount) + txn, err := stakeManagerUtils.Stake(client, txnOpts, epoch, txnArgs.Amount) if err != nil { return core.NilHash, err } diff --git a/cmd/addStake_test.go b/cmd/addStake_test.go index dad161456..7b3422c76 100644 --- a/cmd/addStake_test.go +++ b/cmd/addStake_test.go @@ -84,14 +84,14 @@ func TestStakeCoins(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetEpoch", mock.Anything, mock.Anything).Return(tt.args.epoch, tt.args.getEpochErr) + utilsMock.On("GetEpoch", mock.Anything).Return(tt.args.epoch, tt.args.getEpochErr) utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(TxnOpts) transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) stakeManagerMock.On("Stake", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.stakeTxn, tt.args.stakeErr) utils := &UtilsStruct{} - got, err := utils.StakeCoins(txnArgs) + got, err := utils.StakeCoins(rpcParameters, txnArgs) if got != tt.want { t.Errorf("Txn hash for stake function, got = %v, want %v", got, tt.want) } @@ -308,14 +308,16 @@ func TestExecuteStake(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() + setupTestEndpointsEnvironment() + utilsMock.On("IsFlagPassed", mock.Anything).Return(true) fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.password) @@ -323,16 +325,16 @@ func TestExecuteStake(t *testing.T) { utilsMock.On("AccountManagerForKeystore").Return(&accounts.AccountManager{}, nil) flagSetMock.On("GetStringAddress", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.address, tt.args.addressErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) - utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) - utilsMock.On("FetchBalance", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.balance, tt.args.balanceErr) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) + utilsMock.On("FetchBalance", mock.Anything, mock.Anything).Return(tt.args.balance, tt.args.balanceErr) cmdUtilsMock.On("AssignAmountInWei", flagSet).Return(tt.args.amount, tt.args.amountErr) utilsMock.On("CheckAmountAndBalance", mock.AnythingOfType("*big.Int"), mock.AnythingOfType("*big.Int")).Return(tt.args.amount) - utilsMock.On("CheckEthBalanceIsZero", mock.Anything, mock.Anything, mock.Anything).Return() - utilsMock.On("GetMinSafeRazor", mock.Anything, mock.Anything).Return(tt.args.minSafeRazor, tt.args.minSafeRazorErr) - utilsMock.On("GetStakerId", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) - utilsMock.On("GetStaker", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.staker, tt.args.stakerErr) - cmdUtilsMock.On("Approve", mock.Anything).Return(tt.args.approveTxn, tt.args.approveErr) - cmdUtilsMock.On("StakeCoins", mock.Anything).Return(tt.args.stakeTxn, tt.args.stakeErr) + utilsMock.On("CheckEthBalanceIsZero", mock.Anything, mock.Anything).Return() + utilsMock.On("GetMinSafeRazor", mock.Anything).Return(tt.args.minSafeRazor, tt.args.minSafeRazorErr) + utilsMock.On("GetStakerId", mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) + utilsMock.On("GetStaker", mock.Anything, mock.Anything).Return(tt.args.staker, tt.args.stakerErr) + cmdUtilsMock.On("Approve", mock.Anything, mock.Anything).Return(tt.args.approveTxn, tt.args.approveErr) + cmdUtilsMock.On("StakeCoins", mock.Anything, mock.Anything).Return(tt.args.stakeTxn, tt.args.stakeErr) utils := &UtilsStruct{} fatal = false diff --git a/cmd/approve.go b/cmd/approve.go index 04872dfbe..96826d01c 100644 --- a/cmd/approve.go +++ b/cmd/approve.go @@ -2,17 +2,16 @@ package cmd import ( - "context" "github.com/ethereum/go-ethereum/common" "razor/core" "razor/core/types" "razor/pkg/bindings" + "razor/rpc" ) //This function approves the transaction if the user has sufficient balance otherwise it fails the transaction -func (*UtilsStruct) Approve(txnArgs types.TransactionOptions) (common.Hash, error) { - opts := razorUtils.GetOptions() - allowance, err := tokenManagerUtils.Allowance(txnArgs.Client, &opts, common.HexToAddress(txnArgs.Account.Address), common.HexToAddress(core.StakeManagerAddress)) +func (*UtilsStruct) Approve(rpcParameters rpc.RPCParameters, txnArgs types.TransactionOptions) (common.Hash, error) { + allowance, err := razorUtils.Allowance(rpcParameters, common.HexToAddress(txnArgs.Account.Address), common.HexToAddress(core.StakeManagerAddress)) if err != nil { return core.NilHash, err } @@ -26,9 +25,15 @@ func (*UtilsStruct) Approve(txnArgs types.TransactionOptions) (common.Hash, erro txnArgs.MethodName = "approve" txnArgs.ABI = bindings.RAZORMetaData.ABI txnArgs.Parameters = []interface{}{common.HexToAddress(core.StakeManagerAddress), txnArgs.Amount} - txnOpts := razorUtils.GetTxnOpts(context.Background(), txnArgs) + txnOpts := razorUtils.GetTxnOpts(rpcParameters, txnArgs) + + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return core.NilHash, err + } + log.Debug("Executing Approve transaction with amount: ", txnArgs.Amount) - txn, err := tokenManagerUtils.Approve(txnArgs.Client, txnOpts, common.HexToAddress(core.StakeManagerAddress), txnArgs.Amount) + txn, err := tokenManagerUtils.Approve(client, txnOpts, common.HexToAddress(core.StakeManagerAddress), txnArgs.Amount) if err != nil { return core.NilHash, err } diff --git a/cmd/approve_test.go b/cmd/approve_test.go index ddac58eff..632c45dab 100644 --- a/cmd/approve_test.go +++ b/cmd/approve_test.go @@ -123,12 +123,12 @@ func TestApprove(t *testing.T) { utilsMock.On("GetOptions").Return(tt.args.callOpts) utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(TxnOpts) transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) - tokenManagerMock.On("Allowance", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.allowanceAmount, tt.args.allowanceError) + utilsMock.On("Allowance", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.allowanceAmount, tt.args.allowanceError) tokenManagerMock.On("Approve", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.approveTxn, tt.args.approveError) utils := &UtilsStruct{} - got, err := utils.Approve(tt.args.txnArgs) + got, err := utils.Approve(rpcParameters, tt.args.txnArgs) if got != tt.want { t.Errorf("Txn hash for approve function, got = %v, want = %v", got, tt.want) } diff --git a/cmd/claimBounty.go b/cmd/claimBounty.go index d7f8bde8c..18e98bbfc 100644 --- a/cmd/claimBounty.go +++ b/cmd/claimBounty.go @@ -2,20 +2,17 @@ package cmd import ( - "context" "errors" "math/big" "os" - "razor/accounts" "razor/core" "razor/core/types" - "razor/logger" "razor/path" "razor/pkg/bindings" + "razor/rpc" "razor/utils" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/cobra" "github.com/spf13/pflag" ) @@ -37,31 +34,8 @@ func initialiseClaimBounty(cmd *cobra.Command, args []string) { //This function sets the flags appropriately and executes the ClaimBounty function func (*UtilsStruct) ExecuteClaimBounty(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - log.Debugf("ExecuteClaimBounty: config: %+v", config) - - client := razorUtils.ConnectToClient(config.Provider) - - address, err := flagSetUtils.GetStringAddress(flagSet) - utils.CheckError("Error in getting address: ", err) - log.Debug("ExecuteClaimBounty: Address: ", address) - - logger.SetLoggerParameters(client, address) - - log.Debug("Checking to assign log file...") - fileUtils.AssignLogFile(flagSet, config) - - log.Debug("Getting password...") - password := razorUtils.AssignPassword(flagSet) - - accountManager, err := razorUtils.AccountManagerForKeystore() - utils.CheckError("Error in getting accounts manager for keystore: ", err) - - account := accounts.InitAccountStruct(address, password, accountManager) - - err = razorUtils.CheckPassword(account) - utils.CheckError("Error in fetching private key from given password: ", err) + config, rpcParameters, account, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) if razorUtils.IsFlagPassed("bountyId") { bountyId, err := flagSetUtils.GetUint32BountyId(flagSet) @@ -73,23 +47,23 @@ func (*UtilsStruct) ExecuteClaimBounty(flagSet *pflag.FlagSet) { Account: account, } - txn, err := cmdUtils.ClaimBounty(config, client, redeemBountyInput) + txn, err := cmdUtils.ClaimBounty(rpcParameters, config, redeemBountyInput) utils.CheckError("ClaimBounty error: ", err) if txn != core.NilHash { - err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) + err = razorUtils.WaitForBlockCompletion(rpcParameters, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for claimBounty: ", err) } } else { log.Debug("ExecuteClaimBounty: Calling HandleClaimBounty()") - err := cmdUtils.HandleClaimBounty(client, config, account) + err := cmdUtils.HandleClaimBounty(rpcParameters, config, account) utils.CheckError("HandleClaimBounty error: ", err) } } //This function handles claimBounty by picking bountyid's from disputeData file and if there is any error it returns the error -func (*UtilsStruct) HandleClaimBounty(client *ethclient.Client, config types.Configurations, account types.Account) error { +func (*UtilsStruct) HandleClaimBounty(rpcParameters rpc.RPCParameters, config types.Configurations, account types.Account) error { disputeFilePath, err := pathUtils.GetDisputeDataFileName(account.Address) if err != nil { return err @@ -119,12 +93,12 @@ func (*UtilsStruct) HandleClaimBounty(client *ethclient.Client, config types.Con Account: account, } log.Debugf("HandleClaimBounty: Calling ClaimBounty() with arguments redeemBountyInput: %+v", redeemBountyInput) - claimBountyTxn, err := cmdUtils.ClaimBounty(config, client, redeemBountyInput) + claimBountyTxn, err := cmdUtils.ClaimBounty(rpcParameters, config, redeemBountyInput) if err != nil { return err } if claimBountyTxn != core.NilHash { - claimBountyErr := razorUtils.WaitForBlockCompletion(client, claimBountyTxn.Hex()) + claimBountyErr := razorUtils.WaitForBlockCompletion(rpcParameters, claimBountyTxn.Hex()) if claimBountyErr == nil { if len(disputeData.BountyIdQueue) > 1 { //Removing the bountyId from the queue as the bounty is being claimed @@ -145,9 +119,8 @@ func (*UtilsStruct) HandleClaimBounty(client *ethclient.Client, config types.Con } //This function allows the users who are bountyHunter to redeem their bounty in razor network -func (*UtilsStruct) ClaimBounty(config types.Configurations, client *ethclient.Client, redeemBountyInput types.RedeemBountyInput) (common.Hash, error) { +func (*UtilsStruct) ClaimBounty(rpcParameters rpc.RPCParameters, config types.Configurations, redeemBountyInput types.RedeemBountyInput) (common.Hash, error) { txnArgs := types.TransactionOptions{ - Client: client, Account: redeemBountyInput.Account, ChainId: core.ChainId, Config: config, @@ -156,15 +129,14 @@ func (*UtilsStruct) ClaimBounty(config types.Configurations, client *ethclient.C MethodName: "redeemBounty", Parameters: []interface{}{redeemBountyInput.BountyId}, } - epoch, err := razorUtils.GetEpoch(context.Background(), txnArgs.Client) + epoch, err := razorUtils.GetEpoch(rpcParameters) if err != nil { log.Error("Error in getting epoch: ", err) return core.NilHash, err } log.Debug("ClaimBounty: Epoch: ", epoch) - callOpts := razorUtils.GetOptions() - bountyLock, err := stakeManagerUtils.GetBountyLock(txnArgs.Client, &callOpts, redeemBountyInput.BountyId) + bountyLock, err := razorUtils.GetBountyLock(rpcParameters, redeemBountyInput.BountyId) if err != nil { log.Error("Error in getting bounty lock: ", err) return core.NilHash, err @@ -191,10 +163,14 @@ func (*UtilsStruct) ClaimBounty(config types.Configurations, client *ethclient.C return core.NilHash, nil } - txnOpts := razorUtils.GetTxnOpts(context.Background(), txnArgs) + txnOpts := razorUtils.GetTxnOpts(rpcParameters, txnArgs) + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return core.NilHash, err + } log.Debug("Executing RedeemBounty transaction with bountyId: ", redeemBountyInput.BountyId) - tx, err := stakeManagerUtils.RedeemBounty(txnArgs.Client, txnOpts, redeemBountyInput.BountyId) + tx, err := stakeManagerUtils.RedeemBounty(client, txnOpts, redeemBountyInput.BountyId) if err != nil { return core.NilHash, err } diff --git a/cmd/claimBounty_test.go b/cmd/claimBounty_test.go index 86531a966..acdb617e1 100644 --- a/cmd/claimBounty_test.go +++ b/cmd/claimBounty_test.go @@ -11,7 +11,6 @@ import ( utilsPkgMocks "razor/utils/mocks" "testing" - "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" Types "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" @@ -69,6 +68,7 @@ func TestExecuteClaimBounty(t *testing.T) { args: args{ config: types.Configurations{}, password: "test", + isFlagPassed: true, addressErr: errors.New("address error"), bountyId: 2, claimBountyTxn: common.BigToHash(big.NewInt(1)), @@ -113,13 +113,14 @@ func TestExecuteClaimBounty(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() + setupTestEndpointsEnvironment() fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) @@ -131,8 +132,8 @@ func TestExecuteClaimBounty(t *testing.T) { utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) utilsMock.On("IsFlagPassed", mock.Anything).Return(tt.args.isFlagPassed) cmdUtilsMock.On("HandleClaimBounty", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.handleClaimBountyErr) - cmdUtilsMock.On("ClaimBounty", mock.Anything, mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.claimBountyTxn, tt.args.claimBountyErr) - utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) + cmdUtilsMock.On("ClaimBounty", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.claimBountyTxn, tt.args.claimBountyErr) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) fatal = false utils := &UtilsStruct{} @@ -148,9 +149,7 @@ func TestExecuteClaimBounty(t *testing.T) { func TestClaimBounty(t *testing.T) { var config types.Configurations - var client *ethclient.Client var bountyInput types.RedeemBountyInput - var callOpts bind.CallOpts var blockTime int64 type args struct { @@ -264,9 +263,8 @@ func TestClaimBounty(t *testing.T) { transactionUtils = transactionUtilsMock timeUtils = timeMock - utilsMock.On("GetEpoch", mock.Anything, mock.Anything).Return(tt.args.epoch, tt.args.epochErr) - utilsMock.On("GetOptions").Return(callOpts) - stakeManagerMock.On("GetBountyLock", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.CallOpts"), mock.AnythingOfType("uint32")).Return(tt.args.bountyLock, tt.args.bountyLockErr) + utilsMock.On("GetEpoch", mock.Anything).Return(tt.args.epoch, tt.args.epochErr) + utilsMock.On("GetBountyLock", mock.Anything, mock.Anything).Return(tt.args.bountyLock, tt.args.bountyLockErr) timeMock.On("Sleep", mock.AnythingOfType("time.Duration")).Return() utilsMock.On("CalculateBlockTime", mock.AnythingOfType("*ethclient.Client")).Return(blockTime) utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(TxnOpts) @@ -275,7 +273,7 @@ func TestClaimBounty(t *testing.T) { transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.hash) utils := &UtilsStruct{} - got, err := utils.ClaimBounty(config, client, bountyInput) + got, err := utils.ClaimBounty(rpcParameters, config, bountyInput) if got != tt.want { t.Errorf("Txn hash for claimBounty function, got = %v, want = %v", got, tt.want) } @@ -294,7 +292,6 @@ func TestClaimBounty(t *testing.T) { func TestHandleClaimBounty(t *testing.T) { var ( - client *ethclient.Client config types.Configurations account types.Account fileInfo fs.FileInfo @@ -381,12 +378,12 @@ func TestHandleClaimBounty(t *testing.T) { pathMock.On("GetDisputeDataFileName", mock.AnythingOfType("string")).Return(tt.args.disputeFilePath, tt.args.disputeFilePathErr) osPathMock.On("Stat", mock.Anything).Return(fileInfo, tt.args.statErr) fileUtilsMock.On("ReadFromDisputeJsonFile", mock.Anything).Return(tt.args.disputeData, tt.args.disputeDataErr) - cmdUtilsMock.On("ClaimBounty", mock.Anything, mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.claimBountyTxn, tt.args.claimBountyTxnErr) - utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) + cmdUtilsMock.On("ClaimBounty", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.claimBountyTxn, tt.args.claimBountyTxnErr) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) fileUtilsMock.On("SaveDataToDisputeJsonFile", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.saveDataErr) ut := &UtilsStruct{} - if err := ut.HandleClaimBounty(client, config, account); (err != nil) != tt.wantErr { + if err := ut.HandleClaimBounty(rpcParameters, config, account); (err != nil) != tt.wantErr { t.Errorf("AutoClaimBounty() error = %v, wantErr %v", err, tt.wantErr) } }) diff --git a/cmd/claimCommission.go b/cmd/claimCommission.go index e16aafdb6..90e28122f 100644 --- a/cmd/claimCommission.go +++ b/cmd/claimCommission.go @@ -2,12 +2,9 @@ package cmd import ( - "context" "math/big" - "razor/accounts" "razor/core" "razor/core/types" - "razor/logger" "razor/pkg/bindings" "razor/utils" @@ -29,44 +26,19 @@ Example: //This function allows the staker to claim the rewards earned from delegator's pool share as commission func (*UtilsStruct) ClaimCommission(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - log.Debugf("ClaimCommission: Config: %+v", config) + config, rpcParameters, account, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) - client := razorUtils.ConnectToClient(config.Provider) - - address, err := flagSetUtils.GetStringAddress(flagSet) - utils.CheckError("Error in getting address: ", err) - log.Debug("ClaimCommission: Address: ", address) - - logger.SetLoggerParameters(client, address) - - log.Debug("Checking to assign log file...") - fileUtils.AssignLogFile(flagSet, config) - - log.Debug("Getting password...") - password := razorUtils.AssignPassword(flagSet) - - accountManager, err := razorUtils.AccountManagerForKeystore() - utils.CheckError("Error in getting accounts manager for keystore: ", err) - - account := accounts.InitAccountStruct(address, password, accountManager) - - err = razorUtils.CheckPassword(account) - utils.CheckError("Error in fetching private key from given password: ", err) - - stakerId, err := razorUtils.GetStakerId(context.Background(), client, address) + stakerId, err := razorUtils.GetStakerId(rpcParameters, account.Address) utils.CheckError("Error in getting stakerId: ", err) log.Debug("ClaimCommission: Staker Id: ", stakerId) - callOpts := razorUtils.GetOptions() - stakerInfo, err := stakeManagerUtils.StakerInfo(client, &callOpts, stakerId) + stakerInfo, err := razorUtils.StakerInfo(rpcParameters, stakerId) utils.CheckError("Error in getting stakerInfo: ", err) log.Debugf("ClaimCommission: Staker Info: %+v", stakerInfo) if stakerInfo.StakerReward.Cmp(big.NewInt(0)) > 0 { - txnOpts := razorUtils.GetTxnOpts(context.Background(), types.TransactionOptions{ - Client: client, + txnOpts := razorUtils.GetTxnOpts(rpcParameters, types.TransactionOptions{ ChainId: core.ChainId, Config: config, ContractAddress: core.StakeManagerAddress, @@ -78,13 +50,16 @@ func (*UtilsStruct) ClaimCommission(flagSet *pflag.FlagSet) { log.Info("Claiming commission...") + client, err := rpcParameters.RPCManager.GetBestRPCClient() + utils.CheckError("Error in getting best RPC client: ", err) + log.Debug("Executing ClaimStakeReward transaction...") txn, err := stakeManagerUtils.ClaimStakerReward(client, txnOpts) utils.CheckError("Error in claiming stake reward: ", err) txnHash := transactionUtils.Hash(txn) log.Info("Txn Hash: ", txnHash.Hex()) - err = razorUtils.WaitForBlockCompletion(client, txnHash.Hex()) + err = razorUtils.WaitForBlockCompletion(rpcParameters, txnHash.Hex()) utils.CheckError("Error in WaitForBlockCompletion for claimCommission: ", err) } else { log.Error("no commission to claim") diff --git a/cmd/claimCommission_test.go b/cmd/claimCommission_test.go index 03d2a4f45..3a8c3b630 100644 --- a/cmd/claimCommission_test.go +++ b/cmd/claimCommission_test.go @@ -189,26 +189,27 @@ func TestClaimCommission(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - fatal = false + setupTestEndpointsEnvironment() + utilsMock.On("IsFlagPassed", mock.Anything).Return(true) fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) - utilsMock.On("GetStakerId", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) + utilsMock.On("GetStakerId", mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) utilsMock.On("GetOptions").Return(callOpts) utilsMock.On("AssignPassword", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.password) utilsMock.On("CheckPassword", mock.Anything).Return(nil) utilsMock.On("AccountManagerForKeystore").Return(&accounts.AccountManager{}, nil) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(TxnOpts) - utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(nil) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) - stakeManagerMock.On("StakerInfo", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.CallOpts"), mock.AnythingOfType("uint32")).Return(tt.args.stakerInfo, tt.args.stakerInfoErr) + utilsMock.On("StakerInfo", mock.Anything, mock.AnythingOfType("uint32")).Return(tt.args.stakerInfo, tt.args.stakerInfoErr) stakeManagerMock.On("ClaimStakerReward", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.txn, tt.args.err) flagSetMock.On("GetStringAddress", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.address, tt.args.addressErr) @@ -216,6 +217,8 @@ func TestClaimCommission(t *testing.T) { transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) utils := &UtilsStruct{} + fatal = false + utils.ClaimCommission(flagSet) if fatal != tt.expectedFatal { t.Error("The executeClaimBounty function didn't execute as expected") diff --git a/cmd/cmd-utils.go b/cmd/cmd-utils.go index d034b9baf..7b3462e31 100644 --- a/cmd/cmd-utils.go +++ b/cmd/cmd-utils.go @@ -4,19 +4,24 @@ package cmd import ( "context" "errors" + "github.com/ethereum/go-ethereum/ethclient" "math/big" + "razor/accounts" + "razor/block" + "razor/core" + "razor/core/types" + "razor/logger" + "razor/rpc" "razor/utils" "strconv" "time" "github.com/spf13/pflag" - - "github.com/ethereum/go-ethereum/ethclient" ) //This function takes client as a parameter and returns the epoch and state -func (*UtilsStruct) GetEpochAndState(ctx context.Context, client *ethclient.Client) (uint32, int64, error) { - epoch, err := razorUtils.GetEpoch(ctx, client) +func (*UtilsStruct) GetEpochAndState(rpcParameter rpc.RPCParameters) (uint32, int64, error) { + epoch, err := razorUtils.GetEpoch(rpcParameter) if err != nil { return 0, 0, err } @@ -24,16 +29,16 @@ func (*UtilsStruct) GetEpochAndState(ctx context.Context, client *ethclient.Clie if err != nil { return 0, 0, err } - err = ValidateBufferPercentLimit(ctx, client, bufferPercent) + err = ValidateBufferPercentLimit(rpcParameter, bufferPercent) if err != nil { return 0, 0, err } - latestHeader, err := clientUtils.GetLatestBlockWithRetry(ctx, client) + latestHeader, err := clientUtils.GetLatestBlockWithRetry(rpcParameter) if err != nil { log.Error("Error in fetching block: ", err) return 0, 0, err } - stateBuffer, err := razorUtils.GetStateBuffer(ctx, client) + stateBuffer, err := razorUtils.GetStateBuffer(rpcParameter) if err != nil { log.Error("Error in getting state buffer: ", err) return 0, 0, err @@ -48,10 +53,10 @@ func (*UtilsStruct) GetEpochAndState(ctx context.Context, client *ethclient.Clie } //This function waits for the appropriate states which are required -func (*UtilsStruct) WaitForAppropriateState(ctx context.Context, client *ethclient.Client, action string, states ...int) (uint32, error) { +func (*UtilsStruct) WaitForAppropriateState(rpcParameter rpc.RPCParameters, action string, states ...int) (uint32, error) { statesAllowed := GetFormattedStateNames(states) for { - epoch, state, err := cmdUtils.GetEpochAndState(ctx, client) + epoch, state, err := cmdUtils.GetEpochAndState(rpcParameter) if err != nil { log.Error("Error in fetching epoch and state: ", err) return epoch, err @@ -66,9 +71,9 @@ func (*UtilsStruct) WaitForAppropriateState(ctx context.Context, client *ethclie } //This function wait if the state is commit state -func (*UtilsStruct) WaitIfCommitState(ctx context.Context, client *ethclient.Client, action string) (uint32, error) { +func (*UtilsStruct) WaitIfCommitState(rpcParameter rpc.RPCParameters, action string) (uint32, error) { for { - epoch, state, err := cmdUtils.GetEpochAndState(ctx, client) + epoch, state, err := cmdUtils.GetEpochAndState(rpcParameter) if err != nil { log.Error("Error in fetching epoch and state: ", err) return epoch, err @@ -124,3 +129,72 @@ func GetFormattedStateNames(states []int) string { } return statesAllowed } + +func InitializeCommandDependencies(flagSet *pflag.FlagSet) (types.Configurations, rpc.RPCParameters, types.Account, error) { + var ( + account types.Account + client *ethclient.Client + rpcParameters rpc.RPCParameters + blockMonitor *block.BlockMonitor + ) + + config, err := cmdUtils.GetConfigData() + if err != nil { + log.Error("Error in getting config: ", err) + return types.Configurations{}, rpc.RPCParameters{}, types.Account{}, err + } + log.Debugf("Config: %+v", config) + + if razorUtils.IsFlagPassed("address") { + address, err := flagSetUtils.GetStringAddress(flagSet) + if err != nil { + log.Error("Error in getting address: ", err) + return types.Configurations{}, rpc.RPCParameters{}, types.Account{}, err + } + log.Debugf("Address: %v", address) + + log.Debug("Getting password...") + password := razorUtils.AssignPassword(flagSet) + + accountManager, err := razorUtils.AccountManagerForKeystore() + if err != nil { + log.Error("Error in getting accounts manager for keystore: ", err) + return types.Configurations{}, rpc.RPCParameters{}, types.Account{}, err + } + + account = accounts.InitAccountStruct(address, password, accountManager) + err = razorUtils.CheckPassword(account) + if err != nil { + log.Error("Error in fetching private key from given password: ", err) + return types.Configurations{}, rpc.RPCParameters{}, types.Account{}, err + } + } + + rpcManager, err := rpc.InitializeRPCManager(config.Provider) + if err != nil { + log.Error("Error in initializing RPC Manager: ", err) + return types.Configurations{}, rpc.RPCParameters{}, types.Account{}, err + } + + rpcParameters = rpc.RPCParameters{ + RPCManager: rpcManager, + Ctx: context.Background(), + } + + client, err = rpcManager.GetBestRPCClient() + if err != nil { + log.Error("Error in getting best RPC client: ", err) + return types.Configurations{}, rpc.RPCParameters{}, types.Account{}, err + } + + // Initialize BlockMonitor with RPCManager + blockMonitor = block.NewBlockMonitor(client, rpcManager, core.BlockNumberInterval, core.StaleBlockNumberCheckInterval) + blockMonitor.Start() + log.Debug("Checking to assign log file...") + fileUtils.AssignLogFile(flagSet, config) + + // Update Logger Instance + logger.UpdateLogger(account.Address, client, blockMonitor) + + return config, rpcParameters, account, nil +} diff --git a/cmd/cmd-utils_test.go b/cmd/cmd-utils_test.go index 83e33f623..09b9ab8b3 100644 --- a/cmd/cmd-utils_test.go +++ b/cmd/cmd-utils_test.go @@ -1,10 +1,8 @@ package cmd import ( - "context" "errors" Types "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/pflag" "github.com/stretchr/testify/mock" "math/big" @@ -12,7 +10,6 @@ import ( ) func TestGetEpochAndState(t *testing.T) { - var client *ethclient.Client type args struct { epoch uint32 @@ -131,14 +128,14 @@ func TestGetEpochAndState(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetEpoch", mock.Anything, mock.Anything).Return(tt.args.epoch, tt.args.epochErr) + utilsMock.On("GetEpoch", mock.Anything).Return(tt.args.epoch, tt.args.epochErr) cmdUtilsMock.On("GetBufferPercent").Return(tt.args.bufferPercent, tt.args.bufferPercentErr) - utilsMock.On("GetStateBuffer", mock.Anything, mock.Anything).Return(tt.args.stateBuffer, tt.args.stateBufferErr) + utilsMock.On("GetStateBuffer", mock.Anything).Return(tt.args.stateBuffer, tt.args.stateBufferErr) clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything, mock.Anything).Return(tt.args.latestHeader, tt.args.latestHeaderErr) utilsMock.On("GetBufferedState", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.state, tt.args.stateErr) utils := &UtilsStruct{} - gotEpoch, gotState, err := utils.GetEpochAndState(context.Background(), client) + gotEpoch, gotState, err := utils.GetEpochAndState(rpcParameters) if gotEpoch != tt.wantEpoch { t.Errorf("GetEpochAndState() got epoch = %v, want %v", gotEpoch, tt.wantEpoch) } @@ -159,8 +156,6 @@ func TestGetEpochAndState(t *testing.T) { } func TestWaitForAppropriateState(t *testing.T) { - var client *ethclient.Client - type args struct { epoch uint32 state int64 @@ -225,7 +220,7 @@ func TestWaitForAppropriateState(t *testing.T) { cmdUtilsMock.On("GetEpochAndState", mock.Anything, mock.Anything).Return(tt.args.epoch, tt.args.state, tt.args.epochOrStateErr) timeMock.On("Sleep", mock.Anything).Return() utils := &UtilsStruct{} - got, err := utils.WaitForAppropriateState(context.Background(), client, tt.args.action, tt.args.states) + got, err := utils.WaitForAppropriateState(rpcParameters, tt.args.action, tt.args.states) if got != tt.want { t.Errorf("WaitForAppropriateState() function, got = %v, want = %v", got, tt.want) } @@ -243,7 +238,6 @@ func TestWaitForAppropriateState(t *testing.T) { } func TestWaitIfCommitState(t *testing.T) { - var client *ethclient.Client var action string type args struct { @@ -284,7 +278,7 @@ func TestWaitIfCommitState(t *testing.T) { utils := &UtilsStruct{} - got, err := utils.WaitIfCommitState(context.Background(), client, action) + got, err := utils.WaitIfCommitState(rpcParameters, action) if got != tt.want { t.Errorf("WaitIfCommitState() function, got = %v, want = %v", got, tt.want) } diff --git a/cmd/collectionList.go b/cmd/collectionList.go index f6700f866..4e94ffc4e 100644 --- a/cmd/collectionList.go +++ b/cmd/collectionList.go @@ -2,15 +2,13 @@ package cmd import ( - "context" "encoding/json" "os" - "razor/logger" + "razor/rpc" "razor/utils" "strconv" "strings" - "github.com/ethereum/go-ethereum/ethclient" "github.com/olekukonko/tablewriter" "github.com/spf13/cobra" "github.com/spf13/pflag" @@ -33,21 +31,17 @@ func initialiseCollectionList(cmd *cobra.Command, args []string) { //This function sets the flags appropriately and and executes the GetCollectionList function func (*UtilsStruct) ExecuteCollectionList(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - log.Debugf("ExecuteCollectionList: Config: %+v", config) - - client := razorUtils.ConnectToClient(config.Provider) - logger.SetLoggerParameters(client, "") + _, rpcParameters, _, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) log.Debug("Calling GetCollectionList()") - err = cmdUtils.GetCollectionList(client) + err = cmdUtils.GetCollectionList(rpcParameters) utils.CheckError("Error in getting collection list: ", err) } //This function provides the list of all collections with their name, power, ID etc. -func (*UtilsStruct) GetCollectionList(client *ethclient.Client) error { - collections, err := razorUtils.GetAllCollections(context.Background(), client) +func (*UtilsStruct) GetCollectionList(rpcParameters rpc.RPCParameters) error { + collections, err := razorUtils.GetAllCollections(rpcParameters) log.Debugf("GetCollectionList: Collections: %+v", collections) if err != nil { diff --git a/cmd/collectionList_test.go b/cmd/collectionList_test.go index 3a941c65f..2613ca61e 100644 --- a/cmd/collectionList_test.go +++ b/cmd/collectionList_test.go @@ -11,7 +11,6 @@ import ( ) func TestGetCollectionList(t *testing.T) { - var client *ethclient.Client type fields struct { razorUtils Utils } @@ -37,7 +36,6 @@ func TestGetCollectionList(t *testing.T) { } type args struct { - client *ethclient.Client collectionList []bindings.StructsCollection collectionListErr error } @@ -51,7 +49,6 @@ func TestGetCollectionList(t *testing.T) { name: "Test 1: When collectionList executes properly", fields: testUtils, args: args{ - client: client, collectionList: collectionListArray, collectionListErr: nil, }, @@ -62,7 +59,6 @@ func TestGetCollectionList(t *testing.T) { name: "Test 2: When there is a error fetching collection list ", fields: testUtils, args: args{ - client: client, collectionListErr: errors.New("error in fetching collection list"), }, wantErr: errors.New("error in fetching collection list"), @@ -72,10 +68,10 @@ func TestGetCollectionList(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetAllCollections", mock.Anything, mock.Anything).Return(tt.args.collectionList, tt.args.collectionListErr) + utilsMock.On("GetAllCollections", mock.Anything).Return(tt.args.collectionList, tt.args.collectionListErr) utils := &UtilsStruct{} - err := utils.GetCollectionList(tt.args.client) + err := utils.GetCollectionList(rpcParameters) if err == nil || tt.wantErr == nil { if err != tt.wantErr { @@ -133,18 +129,20 @@ func TestExecuteCollectionList(t *testing.T) { expectedFatal: true, }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() + setupTestEndpointsEnvironment() + utilsMock.On("IsFlagPassed", mock.Anything).Return(false) fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) - cmdUtilsMock.On("GetCollectionList", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.collectionListErr) + cmdUtilsMock.On("GetCollectionList", mock.Anything).Return(tt.args.collectionListErr) utils := &UtilsStruct{} fatal = false diff --git a/cmd/commit.go b/cmd/commit.go index 6927c9925..7ec339b60 100644 --- a/cmd/commit.go +++ b/cmd/commit.go @@ -2,7 +2,6 @@ package cmd import ( - "context" "encoding/hex" "errors" Types "github.com/ethereum/go-ethereum/core/types" @@ -10,11 +9,11 @@ import ( "razor/core" "razor/core/types" "razor/pkg/bindings" + "razor/rpc" "razor/utils" "sync" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethclient" solsha3 "github.com/miguelmota/go-solidity-sha3" ) @@ -22,28 +21,28 @@ import ( GetSalt calculates the salt on the basis of previous epoch and the medians of the previous epoch. If the previous epoch doesn't contain any medians, then the value is fetched from the smart contract. */ -func (*UtilsStruct) GetSalt(ctx context.Context, client *ethclient.Client, epoch uint32) ([32]byte, error) { +func (*UtilsStruct) GetSalt(rpcParameters rpc.RPCParameters, epoch uint32) ([32]byte, error) { previousEpoch := epoch - 1 log.Debug("GetSalt: Previous epoch: ", previousEpoch) - numProposedBlock, err := razorUtils.GetNumberOfProposedBlocks(ctx, client, previousEpoch) + numProposedBlock, err := razorUtils.GetNumberOfProposedBlocks(rpcParameters, previousEpoch) if err != nil { return [32]byte{}, err } log.Debug("GetSalt: Number of proposed blocks: ", numProposedBlock) - blockIndexToBeConfirmed, err := razorUtils.GetBlockIndexToBeConfirmed(ctx, client) + blockIndexToBeConfirmed, err := razorUtils.GetBlockIndexToBeConfirmed(rpcParameters) if err != nil { return [32]byte{}, err } log.Debug("GetSalt: Block Index to be confirmed: ", blockIndexToBeConfirmed) if numProposedBlock == 0 || (numProposedBlock > 0 && blockIndexToBeConfirmed < 0) { - return utils.VoteManagerInterface.GetSaltFromBlockchain(client) + return razorUtils.GetSaltFromBlockchain(rpcParameters) } - blockId, err := razorUtils.GetSortedProposedBlockId(ctx, client, previousEpoch, big.NewInt(int64(blockIndexToBeConfirmed))) + blockId, err := razorUtils.GetSortedProposedBlockId(rpcParameters, previousEpoch, big.NewInt(int64(blockIndexToBeConfirmed))) if err != nil { return [32]byte{}, errors.New("Error in getting blockId: " + err.Error()) } log.Debug("GetSalt: Block Id: ", blockId) - previousBlock, err := razorUtils.GetProposedBlock(ctx, client, previousEpoch, blockId) + previousBlock, err := razorUtils.GetProposedBlock(rpcParameters, previousEpoch, blockId) if err != nil { return [32]byte{}, errors.New("Error in getting previous block: " + err.Error()) } @@ -56,14 +55,14 @@ func (*UtilsStruct) GetSalt(ctx context.Context, client *ethclient.Client, epoch HandleCommitState fetches the collections assigned to the staker and creates the leaves required for the merkle tree generation. Values for only the collections assigned to the staker is fetched for others, 0 is added to the leaves of tree. */ -func (*UtilsStruct) HandleCommitState(ctx context.Context, client *ethclient.Client, epoch uint32, seed []byte, commitParams *types.CommitParams, rogueData types.Rogue) (types.CommitData, error) { - numActiveCollections, err := razorUtils.GetNumActiveCollections(ctx, client) +func (*UtilsStruct) HandleCommitState(rpcParameters rpc.RPCParameters, epoch uint32, seed []byte, commitParams *types.CommitParams, rogueData types.Rogue) (types.CommitData, error) { + numActiveCollections, err := razorUtils.GetNumActiveCollections(rpcParameters) if err != nil { return types.CommitData{}, err } log.Debug("HandleCommitState: Number of active collections: ", numActiveCollections) log.Debugf("HandleCommitState: Calling GetAssignedCollections() with arguments number of active collections = %d", numActiveCollections) - assignedCollections, seqAllottedCollections, err := razorUtils.GetAssignedCollections(ctx, client, numActiveCollections, seed) + assignedCollections, seqAllottedCollections, err := razorUtils.GetAssignedCollections(rpcParameters, numActiveCollections, seed) if err != nil { return types.CommitData{}, err } @@ -89,13 +88,13 @@ func (*UtilsStruct) HandleCommitState(ctx context.Context, client *ethclient.Cli log.Debugf("HandleCommitState: Is the collection at iterating index %v assigned: %v ", i, assignedCollections[i]) if assignedCollections[i] { - collectionId, err := razorUtils.GetCollectionIdFromIndex(ctx, client, uint16(i)) + collectionId, err := razorUtils.GetCollectionIdFromIndex(rpcParameters, uint16(i)) if err != nil { log.Error("Error in getting collection ID: ", err) errChan <- err return } - collectionData, err := razorUtils.GetAggregatedDataOfCollection(ctx, client, collectionId, epoch, commitParams) + collectionData, err := razorUtils.GetAggregatedDataOfCollection(rpcParameters, collectionId, epoch, commitParams) if err != nil { log.Error("Error in getting aggregated data of collection: ", err) errChan <- err @@ -146,14 +145,13 @@ func (*UtilsStruct) HandleCommitState(ctx context.Context, client *ethclient.Cli /* Commit finally commits the data to the smart contract. It calculates the commitment to send using the merkle tree root and the seed. */ -func (*UtilsStruct) Commit(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, latestHeader *Types.Header, stateBuffer uint64, commitmentToSend [32]byte) (common.Hash, error) { +func (*UtilsStruct) Commit(rpcParameters rpc.RPCParameters, config types.Configurations, account types.Account, epoch uint32, latestHeader *Types.Header, stateBuffer uint64, commitmentToSend [32]byte) (common.Hash, error) { if state, err := razorUtils.GetBufferedState(latestHeader, stateBuffer, config.BufferPercent); err != nil || state != 0 { log.Error("Not commit state") return core.NilHash, err } - txnOpts := razorUtils.GetTxnOpts(ctx, types.TransactionOptions{ - Client: client, + txnOpts := razorUtils.GetTxnOpts(rpcParameters, types.TransactionOptions{ ChainId: core.ChainId, Config: config, ContractAddress: core.VoteManagerAddress, @@ -164,6 +162,12 @@ func (*UtilsStruct) Commit(ctx context.Context, client *ethclient.Client, config }) log.Info("Commitment sent...") + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + log.Error(err) + return core.NilHash, err + } + log.Debugf("Executing Commit transaction with epoch = %d, commitmentToSend = %v", epoch, commitmentToSend) txn, err := voteManagerUtils.Commit(client, txnOpts, epoch, commitmentToSend) if err != nil { @@ -174,14 +178,14 @@ func (*UtilsStruct) Commit(ctx context.Context, client *ethclient.Client, config return txnHash, nil } -func CalculateSeed(ctx context.Context, client *ethclient.Client, account types.Account, keystorePath string, epoch uint32) ([]byte, error) { +func CalculateSeed(rpcParameters rpc.RPCParameters, account types.Account, keystorePath string, epoch uint32) ([]byte, error) { log.Debugf("CalculateSeed: Calling CalculateSecret() with arguments epoch = %d, keystorePath = %s, chainId = %s", epoch, keystorePath, core.ChainId) _, secret, err := cmdUtils.CalculateSecret(account, epoch, keystorePath, core.ChainId) if err != nil { return nil, err } log.Debugf("CalculateSeed: Getting Salt for current epoch %d...", epoch) - salt, err := cmdUtils.GetSalt(ctx, client, epoch) + salt, err := cmdUtils.GetSalt(rpcParameters, epoch) if err != nil { log.Error("Error in getting salt: ", err) return nil, err @@ -209,8 +213,8 @@ func CalculateCommitment(seed []byte, values []*big.Int) ([32]byte, error) { return commitmentToSend, nil } -func VerifyCommitment(ctx context.Context, client *ethclient.Client, account types.Account, commitmentFetched [32]byte) (bool, error) { - commitmentStruct, err := razorUtils.GetCommitment(ctx, client, account.Address) +func VerifyCommitment(rpcParameters rpc.RPCParameters, account types.Account, commitmentFetched [32]byte) (bool, error) { + commitmentStruct, err := razorUtils.GetCommitment(rpcParameters, account.Address) if err != nil { log.Error("Error in getting commitments: ", err) return false, err @@ -225,7 +229,7 @@ func VerifyCommitment(ctx context.Context, client *ethclient.Client, account typ return false, nil } -func GetCommittedDataForEpoch(ctx context.Context, client *ethclient.Client, account types.Account, epoch uint32, rogueData types.Rogue) (types.CommitFileData, error) { +func GetCommittedDataForEpoch(rpcParameters rpc.RPCParameters, account types.Account, epoch uint32, rogueData types.Rogue) (types.CommitFileData, error) { // Attempt to fetch global commit data from memory if epoch matches if globalCommitDataStruct.Epoch == epoch { log.Debugf("Epoch in global commit data is equal to current epoch %v. Fetching commit data from memory!", epoch) @@ -260,7 +264,7 @@ func GetCommittedDataForEpoch(ctx context.Context, client *ethclient.Client, acc // Verify the final selected commit data log.Debugf("Verifying commit data for epoch %v...", epoch) - isValid, err := VerifyCommitment(ctx, client, account, globalCommitDataStruct.Commitment) + isValid, err := VerifyCommitment(rpcParameters, account, globalCommitDataStruct.Commitment) if err != nil { return types.CommitFileData{}, err } diff --git a/cmd/commit_test.go b/cmd/commit_test.go index 1945f0aca..85f25a932 100644 --- a/cmd/commit_test.go +++ b/cmd/commit_test.go @@ -1,13 +1,11 @@ package cmd import ( - "context" "encoding/hex" "errors" "fmt" "github.com/ethereum/go-ethereum/common" Types "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethclient" "github.com/stretchr/testify/mock" "math/big" "razor/cache" @@ -21,7 +19,6 @@ import ( func TestCommit(t *testing.T) { var ( - client *ethclient.Client account types.Account config types.Configurations latestHeader *Types.Header @@ -89,7 +86,7 @@ func TestCommit(t *testing.T) { transactionMock.On("Hash", mock.AnythingOfType("*types.Transaction")).Return(tt.args.hash) utils := &UtilsStruct{} - got, err := utils.Commit(context.Background(), client, config, account, epoch, latestHeader, stateBuffer, commitment) + got, err := utils.Commit(rpcParameters, config, account, epoch, latestHeader, stateBuffer, commitment) if got != tt.want { t.Errorf("Txn hash for Commit function, got = %v, want = %v", got, tt.want) } @@ -108,9 +105,8 @@ func TestCommit(t *testing.T) { func TestHandleCommitState(t *testing.T) { var ( - client *ethclient.Client - epoch uint32 - seed []byte + epoch uint32 + seed []byte ) rogueValue := big.NewInt(1111) @@ -219,14 +215,14 @@ func TestHandleCommitState(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetNumActiveCollections", mock.Anything, mock.Anything).Return(tt.args.numActiveCollections, tt.args.numActiveCollectionsErr) - utilsMock.On("GetAssignedCollections", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.assignedCollections, tt.args.seqAllottedCollections, tt.args.assignedCollectionsErr) - utilsMock.On("GetCollectionIdFromIndex", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.collectionId, tt.args.collectionIdErr) - utilsMock.On("GetAggregatedDataOfCollection", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.collectionData, tt.args.collectionDataErr) + utilsMock.On("GetNumActiveCollections", mock.Anything).Return(tt.args.numActiveCollections, tt.args.numActiveCollectionsErr) + utilsMock.On("GetAssignedCollections", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.assignedCollections, tt.args.seqAllottedCollections, tt.args.assignedCollectionsErr) + utilsMock.On("GetCollectionIdFromIndex", mock.Anything, mock.Anything).Return(tt.args.collectionId, tt.args.collectionIdErr) + utilsMock.On("GetAggregatedDataOfCollection", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.collectionData, tt.args.collectionDataErr) utilsMock.On("GetRogueRandomValue", mock.Anything).Return(rogueValue) utils := &UtilsStruct{} - got, err := utils.HandleCommitState(context.Background(), client, epoch, seed, commitParams, tt.args.rogueData) + got, err := utils.HandleCommitState(rpcParameters, epoch, seed, commitParams, tt.args.rogueData) if !reflect.DeepEqual(got, tt.want) { t.Errorf("Data from HandleCommitState function, got = %v, want = %v", got, tt.want) } @@ -245,8 +241,6 @@ func TestHandleCommitState(t *testing.T) { } func TestGetSalt(t *testing.T) { - var client *ethclient.Client - type args struct { epoch uint32 numProposedBlocks uint8 @@ -337,15 +331,15 @@ func TestGetSalt(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetNumberOfProposedBlocks", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.numProposedBlocks, tt.args.numProposedBlocksErr) - utilsMock.On("GetBlockIndexToBeConfirmed", mock.Anything, mock.Anything).Return(tt.args.blockIndexedToBeConfirmed, tt.args.blockIndexedToBeConfirmedErr) - voteManagerUtilsMock.On("GetSaltFromBlockchain", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.saltFromBlockChain, tt.args.saltFromBlockChainErr) - utilsMock.On("GetSortedProposedBlockId", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.blockId, tt.args.blockIdErr) - utilsMock.On("GetProposedBlock", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.previousBlock, tt.args.previousBlockErr) + utilsMock.On("GetNumberOfProposedBlocks", mock.Anything, mock.Anything).Return(tt.args.numProposedBlocks, tt.args.numProposedBlocksErr) + utilsMock.On("GetBlockIndexToBeConfirmed", mock.Anything).Return(tt.args.blockIndexedToBeConfirmed, tt.args.blockIndexedToBeConfirmedErr) + utilsMock.On("GetSaltFromBlockchain", mock.Anything).Return(tt.args.saltFromBlockChain, tt.args.saltFromBlockChainErr) + utilsMock.On("GetSortedProposedBlockId", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.blockId, tt.args.blockIdErr) + utilsMock.On("GetProposedBlock", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.previousBlock, tt.args.previousBlockErr) utilsMock.On("CalculateSalt", mock.Anything, mock.Anything).Return(tt.args.salt) ut := &UtilsStruct{} - got, err := ut.GetSalt(context.Background(), client, tt.args.epoch) + got, err := ut.GetSalt(rpcParameters, tt.args.epoch) if !reflect.DeepEqual(got, tt.want) { t.Errorf("Data from GetSalt function, got = %v, want = %v", got, tt.want) } @@ -364,9 +358,8 @@ func TestGetSalt(t *testing.T) { func BenchmarkHandleCommitState(b *testing.B) { var ( - client *ethclient.Client - epoch uint32 - seed []byte + epoch uint32 + seed []byte ) rogueValue := big.NewInt(1111) @@ -389,14 +382,14 @@ func BenchmarkHandleCommitState(b *testing.B) { SetUpMockInterfaces() - utilsMock.On("GetNumActiveCollections", mock.Anything, mock.Anything).Return(v.numActiveCollections, nil) - utilsMock.On("GetAssignedCollections", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(v.assignedCollections, nil, nil) - utilsMock.On("GetCollectionIdFromIndex", mock.Anything, mock.Anything, mock.Anything).Return(uint16(1), nil) - utilsMock.On("GetAggregatedDataOfCollection", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(big.NewInt(1000), nil) + utilsMock.On("GetNumActiveCollections", mock.Anything).Return(v.numActiveCollections, nil) + utilsMock.On("GetAssignedCollections", mock.Anything, mock.Anything, mock.Anything).Return(v.assignedCollections, nil, nil) + utilsMock.On("GetCollectionIdFromIndex", mock.Anything, mock.Anything).Return(uint16(1), nil) + utilsMock.On("GetAggregatedDataOfCollection", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(big.NewInt(1000), nil) utilsMock.On("GetRogueRandomValue", mock.Anything).Return(rogueValue) ut := &UtilsStruct{} - _, err := ut.HandleCommitState(context.Background(), client, epoch, seed, commitParams, types.Rogue{IsRogue: false}) + _, err := ut.HandleCommitState(rpcParameters, epoch, seed, commitParams, types.Rogue{IsRogue: false}) if err != nil { log.Fatal(err) } @@ -477,7 +470,6 @@ func TestCalculateCommitment(t *testing.T) { func TestVerifyCommitment(t *testing.T) { var ( - client *ethclient.Client account types.Account ) type args struct { @@ -548,9 +540,9 @@ func TestVerifyCommitment(t *testing.T) { utils.MerkleInterface = &utils.MerkleTreeStruct{} merkleUtils = utils.MerkleInterface - utilsMock.On("GetCommitment", mock.Anything, mock.Anything, mock.Anything).Return(types.Commitment{CommitmentHash: commitmentHash}, tt.args.commitmentErr) + utilsMock.On("GetCommitment", mock.Anything, mock.Anything).Return(types.Commitment{CommitmentHash: commitmentHash}, tt.args.commitmentErr) - got, err := VerifyCommitment(context.Background(), client, account, commitmentFetched) + got, err := VerifyCommitment(rpcParameters, account, commitmentFetched) if (err != nil) != tt.wantErr { t.Errorf("VerifyCommitment() error = %v, wantErr %v", err, tt.wantErr) return @@ -564,7 +556,6 @@ func TestVerifyCommitment(t *testing.T) { func TestCalculateSeed(t *testing.T) { var ( - client *ethclient.Client account types.Account keystorePath string epoch uint32 @@ -633,8 +624,8 @@ func TestCalculateSeed(t *testing.T) { SetUpMockInterfaces() cmdUtilsMock.On("CalculateSecret", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil, secret, tt.args.secretErr) - cmdUtilsMock.On("GetSalt", mock.Anything, mock.Anything, mock.Anything).Return(salt, tt.args.saltErr) - got, err := CalculateSeed(context.Background(), client, account, keystorePath, epoch) + cmdUtilsMock.On("GetSalt", mock.Anything, mock.Anything).Return(salt, tt.args.saltErr) + got, err := CalculateSeed(rpcParameters, account, keystorePath, epoch) if (err != nil) != tt.wantErr { t.Errorf("CalculateSeed() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/cmd/config-utils.go b/cmd/config-utils.go index e9d9bf6b4..9335090d3 100644 --- a/cmd/config-utils.go +++ b/cmd/config-utils.go @@ -2,15 +2,13 @@ package cmd import ( - "context" "errors" - "razor/client" "razor/core" "razor/core/types" + "razor/rpc" "razor/utils" "strings" - "github.com/ethereum/go-ethereum/ethclient" "github.com/sirupsen/logrus" "github.com/spf13/viper" @@ -20,7 +18,6 @@ import ( func (*UtilsStruct) GetConfigData() (types.Configurations, error) { config := types.Configurations{ Provider: "", - AlternateProvider: "", GasMultiplier: 0, BufferPercent: 0, WaitTime: 0, @@ -37,10 +34,6 @@ func (*UtilsStruct) GetConfigData() (types.Configurations, error) { if err != nil { return config, err } - alternateProvider, err := cmdUtils.GetAlternateProvider() - if err != nil { - return config, err - } gasMultiplier, err := cmdUtils.GetMultiplier() if err != nil { return config, err @@ -90,8 +83,6 @@ func (*UtilsStruct) GetConfigData() (types.Configurations, error) { return config, err } config.Provider = provider - config.AlternateProvider = alternateProvider - client.SetAlternateProvider(alternateProvider) config.GasMultiplier = gasMultiplier config.BufferPercent = bufferPercent config.WaitTime = waitTime @@ -172,19 +163,6 @@ func (*UtilsStruct) GetProvider() (string, error) { return providerString, nil } -//This function returns the alternate provider -func (*UtilsStruct) GetAlternateProvider() (string, error) { - alternateProvider, err := getConfigValue("alternateProvider", "string", "", "alternateProvider") - if err != nil { - return "", err - } - alternateProviderString := alternateProvider.(string) - if !strings.HasPrefix(alternateProviderString, "https") { - log.Warn("You are not using a secure RPC URL. Switch to an https URL instead to be safe.") - } - return alternateProviderString, nil -} - //This function returns the multiplier func (*UtilsStruct) GetMultiplier() (float32, error) { const ( @@ -394,11 +372,9 @@ func (*UtilsStruct) GetLogFileMaxAge() (int, error) { //This function sets the log level func setLogLevel(config types.Configurations) { if config.LogLevel == "debug" { - log.SetLevel(logrus.DebugLevel) + log.SetLogLevel(logrus.DebugLevel) } - log.Debugf("Config details: %+v", config) - if razorUtils.IsFlagPassed("logFile") { log.Debugf("Log File Max Size: %d MB", config.LogFileMaxSize) log.Debugf("Log File Max Backups (max number of old log files to retain): %d", config.LogFileMaxBackups) @@ -406,8 +382,8 @@ func setLogLevel(config types.Configurations) { } } -func ValidateBufferPercentLimit(ctx context.Context, client *ethclient.Client, bufferPercent int32) error { - stateBuffer, err := razorUtils.GetStateBuffer(ctx, client) +func ValidateBufferPercentLimit(rpcParameters rpc.RPCParameters, bufferPercent int32) error { + stateBuffer, err := razorUtils.GetStateBuffer(rpcParameters) if err != nil { return err } diff --git a/cmd/config-utils_test.go b/cmd/config-utils_test.go index de2846885..92f8a70b5 100644 --- a/cmd/config-utils_test.go +++ b/cmd/config-utils_test.go @@ -1,9 +1,7 @@ package cmd import ( - "context" "errors" - "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/viper" "github.com/stretchr/testify/mock" "os" @@ -39,7 +37,6 @@ func removeTestConfig(path string) { func TestGetConfigData(t *testing.T) { nilConfig := types.Configurations{ Provider: "", - AlternateProvider: "", GasMultiplier: 0, BufferPercent: 0, WaitTime: 0, @@ -54,7 +51,6 @@ func TestGetConfigData(t *testing.T) { configData := types.Configurations{ Provider: "", - AlternateProvider: "", GasMultiplier: 1, BufferPercent: 20, WaitTime: 1, @@ -71,8 +67,6 @@ func TestGetConfigData(t *testing.T) { type args struct { provider string providerErr error - alternateProvider string - alternateProviderErr error gasMultiplier float32 gasMultiplierErr error bufferPercent int32 @@ -108,7 +102,6 @@ func TestGetConfigData(t *testing.T) { name: "Test 1: When GetConfigData function executes successfully", args: args{ provider: "", - alternateProvider: "", gasMultiplier: 1, bufferPercent: 20, waitTime: 1, @@ -196,21 +189,12 @@ func TestGetConfigData(t *testing.T) { want: nilConfig, wantErr: errors.New("httpTimeout error"), }, - { - name: "Test 11: When there is an error in getting alternate provider", - args: args{ - alternateProviderErr: errors.New("alternate provider error"), - }, - want: nilConfig, - wantErr: errors.New("alternate provider error"), - }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() cmdUtilsMock.On("GetProvider").Return(tt.args.provider, tt.args.providerErr) - cmdUtilsMock.On("GetAlternateProvider").Return(tt.args.alternateProvider, tt.args.alternateProviderErr) cmdUtilsMock.On("GetMultiplier").Return(tt.args.gasMultiplier, tt.args.gasMultiplierErr) cmdUtilsMock.On("GetWaitTime").Return(tt.args.waitTime, tt.args.waitTimeErr) cmdUtilsMock.On("GetGasPrice").Return(tt.args.gasPrice, tt.args.gasPriceErr) @@ -850,94 +834,6 @@ func TestGetProvider(t *testing.T) { } } -func TestGetAlternateProvider(t *testing.T) { - type args struct { - isFlagSet bool - alternateProvider string - alternateProviderErr error - alternateProviderInConfig string - } - tests := []struct { - name string - useDummyConfigFile bool - args args - want string - wantErr error - }{ - { - name: "Test 1: When alternateProvider is fetched from root flag", - args: args{ - isFlagSet: true, - alternateProvider: "https://polygon-mumbai.g.alchemy.com/v2/-Re1lE3oDIVTWchuKMfRIECn0I", - }, - want: "https://polygon-mumbai.g.alchemy.com/v2/-Re1lE3oDIVTWchuKMfRIECn0I", - wantErr: nil, - }, - { - name: "Test 2: When alternateProvider from root flag has prefix https", - args: args{ - isFlagSet: true, - alternateProvider: "127.0.0.1:8545", - }, - want: "127.0.0.1:8545", - wantErr: nil, - }, - { - name: "Test 3: When there is an error in fetching alternateProvider from root flag", - args: args{ - isFlagSet: true, - alternateProviderErr: errors.New("alternateProvider error"), - }, - want: "", - wantErr: errors.New("alternateProvider error"), - }, - { - name: "Test 4: When alternateProvider value is fetched from config", - useDummyConfigFile: true, - args: args{ - alternateProviderInConfig: "https://some-config-provider.com", - }, - want: "https://some-config-provider.com", - wantErr: nil, - }, - { - name: "Test 5: When alternateProvider is not passed in root nor set in config", - want: "", - wantErr: nil, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - viper.Reset() // Reset viper state - - if tt.useDummyConfigFile { - createTestConfig(t, "alternateProvider", tt.args.alternateProviderInConfig) - defer removeTestConfig(tempConfigPath) - } - - SetUpMockInterfaces() - - flagSetMock.On("FetchRootFlagInput", mock.Anything, mock.Anything).Return(tt.args.alternateProvider, tt.args.alternateProviderErr) - flagSetMock.On("Changed", mock.Anything, mock.Anything).Return(tt.args.isFlagSet) - - utils := &UtilsStruct{} - got, err := utils.GetAlternateProvider() - if got != tt.want { - t.Errorf("getAlternateProvider() got = %v, want %v", got, tt.want) - } - if err == nil || tt.wantErr == nil { - if err != tt.wantErr { - t.Errorf("Error for getAlternateProvider function, got = %v, want = %v", err, tt.wantErr) - } - } else { - if err.Error() != tt.wantErr.Error() { - t.Errorf("Error for getAlternateProvider function, got = %v, want = %v", err, tt.wantErr) - } - } - }) - } -} - func TestGetRPCTimeout(t *testing.T) { type args struct { isFlagSet bool @@ -1203,8 +1099,6 @@ func TestGetWaitTime(t *testing.T) { } func TestValidateBufferPercentLimit(t *testing.T) { - var client *ethclient.Client - type args struct { bufferPercent int32 stateBuffer uint64 @@ -1244,9 +1138,9 @@ func TestValidateBufferPercentLimit(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetStateBuffer", mock.Anything, mock.Anything).Return(tt.args.stateBuffer, tt.args.stateBufferErr) + utilsMock.On("GetStateBuffer", mock.Anything).Return(tt.args.stateBuffer, tt.args.stateBufferErr) - err := ValidateBufferPercentLimit(context.Background(), client, tt.args.bufferPercent) + err := ValidateBufferPercentLimit(rpcParameters, tt.args.bufferPercent) if err == nil || tt.wantErr == nil { if err != tt.wantErr { t.Errorf("Error for GetEpochAndState function, got = %v, want = %v", err, tt.wantErr) diff --git a/cmd/confirm.go b/cmd/confirm.go index 620c67406..22cf5c0fe 100644 --- a/cmd/confirm.go +++ b/cmd/confirm.go @@ -2,23 +2,23 @@ package cmd import ( - "context" "razor/core" "razor/core/types" + "razor/rpc" "github.com/ethereum/go-ethereum/common" ) //This function allows the user to claim the block reward and returns the hash -func (*UtilsStruct) ClaimBlockReward(ctx context.Context, options types.TransactionOptions) (common.Hash, error) { - epoch, err := razorUtils.GetEpoch(ctx, options.Client) +func (*UtilsStruct) ClaimBlockReward(rpcParameters rpc.RPCParameters, options types.TransactionOptions) (common.Hash, error) { + epoch, err := razorUtils.GetEpoch(rpcParameters) if err != nil { log.Error("Error in getting epoch: ", err) return core.NilHash, err } log.Debug("ClaimBlockReward: Epoch: ", epoch) - sortedProposedBlockIds, err := razorUtils.GetSortedProposedBlockIds(ctx, options.Client, epoch) + sortedProposedBlockIds, err := razorUtils.GetSortedProposedBlockIds(rpcParameters, epoch) if err != nil { log.Error("Error in getting sortedProposedBlockIds: ", err) return core.NilHash, err @@ -30,14 +30,14 @@ func (*UtilsStruct) ClaimBlockReward(ctx context.Context, options types.Transact return core.NilHash, nil } - stakerID, err := razorUtils.GetStakerId(ctx, options.Client, options.Account.Address) + stakerID, err := razorUtils.GetStakerId(rpcParameters, options.Account.Address) if err != nil { log.Error("Error in getting stakerId: ", err) return core.NilHash, err } log.Debug("ClaimBlockReward: Staker Id: ", stakerID) - selectedProposedBlock, err := razorUtils.GetProposedBlock(ctx, options.Client, epoch, sortedProposedBlockIds[0]) + selectedProposedBlock, err := razorUtils.GetProposedBlock(rpcParameters, epoch, sortedProposedBlockIds[0]) if err != nil { log.Error("Error in getting selectedProposedBlock: ", err) return core.NilHash, err @@ -46,9 +46,15 @@ func (*UtilsStruct) ClaimBlockReward(ctx context.Context, options types.Transact if selectedProposedBlock.ProposerId == stakerID { log.Info("Claiming block reward...") - txnOpts := razorUtils.GetTxnOpts(ctx, options) + txnOpts := razorUtils.GetTxnOpts(rpcParameters, options) + + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return core.NilHash, err + } + log.Debug("Executing ClaimBlockReward transaction...") - txn, err := blockManagerUtils.ClaimBlockReward(options.Client, txnOpts) + txn, err := blockManagerUtils.ClaimBlockReward(client, txnOpts) if err != nil { log.Error("Error in claiming block reward: ", err) return core.NilHash, err diff --git a/cmd/confirm_test.go b/cmd/confirm_test.go index dec9ba5da..c5635188e 100644 --- a/cmd/confirm_test.go +++ b/cmd/confirm_test.go @@ -1,7 +1,6 @@ package cmd import ( - "context" "errors" "github.com/stretchr/testify/mock" "math/big" @@ -130,16 +129,16 @@ func TestClaimBlockReward(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetEpoch", mock.Anything, mock.Anything).Return(tt.args.epoch, tt.args.epochErr) - utilsMock.On("GetSortedProposedBlockIds", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.sortedProposedBlockIds, tt.args.sortedProposedBlockIdsErr) - utilsMock.On("GetStakerId", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) - utilsMock.On("GetProposedBlock", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.selectedBlock, tt.args.selectedBlockErr) + utilsMock.On("GetEpoch", mock.Anything).Return(tt.args.epoch, tt.args.epochErr) + utilsMock.On("GetSortedProposedBlockIds", mock.Anything, mock.Anything).Return(tt.args.sortedProposedBlockIds, tt.args.sortedProposedBlockIdsErr) + utilsMock.On("GetStakerId", mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) + utilsMock.On("GetProposedBlock", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.selectedBlock, tt.args.selectedBlockErr) utilsMock.On("GetTxnOpts", mock.Anything, options).Return(TxnOpts) blockManagerMock.On("ClaimBlockReward", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts")).Return(tt.args.ClaimBlockRewardTxn, tt.args.ClaimBlockRewardErr) transactionMock.On("Hash", mock.AnythingOfType("*types.Transaction")).Return(tt.args.hash) utils := &UtilsStruct{} - got, err := utils.ClaimBlockReward(context.Background(), options) + got, err := utils.ClaimBlockReward(rpcParameters, options) if got != tt.want { t.Errorf("Txn hash for ClaimBlockReward function, got = %v, want = %v", got, tt.want) } diff --git a/cmd/contractAddresses.go b/cmd/contractAddresses.go index fd5cfadb1..614fae1ba 100644 --- a/cmd/contractAddresses.go +++ b/cmd/contractAddresses.go @@ -25,10 +25,9 @@ func initialiseContractAddresses(cmd *cobra.Command, args []string) { //This function sets the flag appropriatley and executes the ContractAddresses function func (*UtilsStruct) ExecuteContractAddresses(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - log.Debug("Checking to assign log file...") - fileUtils.AssignLogFile(flagSet, config) + _, _, _, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) + fmt.Println("The contract addresses are: ") cmdUtils.ContractAddresses() diff --git a/cmd/contractAddresses_test.go b/cmd/contractAddresses_test.go index 0deedd25c..7834b06e9 100644 --- a/cmd/contractAddresses_test.go +++ b/cmd/contractAddresses_test.go @@ -35,13 +35,15 @@ func TestExecuteContractAddresses(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() + setupTestEndpointsEnvironment() + utilsMock.On("IsFlagPassed", mock.Anything).Return(false) fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(types.Configurations{}, nil) cmdUtilsMock.On("ContractAddresses") diff --git a/cmd/create.go b/cmd/create.go index 71ca08a98..da9071164 100644 --- a/cmd/create.go +++ b/cmd/create.go @@ -28,10 +28,8 @@ func initialiseCreate(cmd *cobra.Command, args []string) { //This function sets the flags appropriately and executes the Create function func (*UtilsStruct) ExecuteCreate(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - log.Debug("Checking to assign log file...") - fileUtils.AssignLogFile(flagSet, config) + _, _, _, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) log.Info("The password should be of minimum 8 characters containing least 1 uppercase, lowercase, digit and special character.") password := razorUtils.AssignPassword(flagSet) log.Debug("ExecuteCreate: Calling Create() with argument as input password") diff --git a/cmd/createCollection.go b/cmd/createCollection.go index ecbcdffd9..f6a19dcfd 100644 --- a/cmd/createCollection.go +++ b/cmd/createCollection.go @@ -2,16 +2,13 @@ package cmd import ( - "context" - "razor/accounts" "razor/core" "razor/core/types" - "razor/logger" "razor/pkg/bindings" + "razor/rpc" "razor/utils" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/cobra" "github.com/spf13/pflag" ) @@ -37,29 +34,8 @@ func initialiseCreateCollection(cmd *cobra.Command, args []string) { //This function sets the flags appropriately and executes the CreateCollection function func (*UtilsStruct) ExecuteCreateCollection(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - log.Debugf("ExecuteCreateCollection: Config: %+v", config) - - client := razorUtils.ConnectToClient(config.Provider) - - address, err := flagSetUtils.GetStringAddress(flagSet) - utils.CheckError("Error in getting address: ", err) - - logger.SetLoggerParameters(client, address) - log.Debug("Checking to assign log file...") - fileUtils.AssignLogFile(flagSet, config) - - log.Debug("Getting password...") - password := razorUtils.AssignPassword(flagSet) - - accountManager, err := razorUtils.AccountManagerForKeystore() - utils.CheckError("Error in getting accounts manager for keystore: ", err) - - account := accounts.InitAccountStruct(address, password, accountManager) - - err = razorUtils.CheckPassword(account) - utils.CheckError("Error in fetching private key from given password: ", err) + config, rpcParameters, account, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) name, err := flagSetUtils.GetStringName(flagSet) utils.CheckError("Error in getting name: ", err) @@ -85,23 +61,22 @@ func (*UtilsStruct) ExecuteCreateCollection(flagSet *pflag.FlagSet) { Account: account, } - txn, err := cmdUtils.CreateCollection(client, config, collectionInput) + txn, err := cmdUtils.CreateCollection(rpcParameters, config, collectionInput) utils.CheckError("CreateCollection error: ", err) - err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) + err = razorUtils.WaitForBlockCompletion(rpcParameters, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for createCollection: ", err) } //This function allows the admin to create collction if existing jobs are present -func (*UtilsStruct) CreateCollection(client *ethclient.Client, config types.Configurations, collectionInput types.CreateCollectionInput) (common.Hash, error) { +func (*UtilsStruct) CreateCollection(rpcParameters rpc.RPCParameters, config types.Configurations, collectionInput types.CreateCollectionInput) (common.Hash, error) { jobIds := utils.ConvertUintArrayToUint16Array(collectionInput.JobIds) log.Debug("CreateCollection: Uint16 jobIds: ", jobIds) - _, err := cmdUtils.WaitForAppropriateState(context.Background(), client, "create collection", 4) + _, err := cmdUtils.WaitForAppropriateState(rpcParameters, "create collection", 4) if err != nil { log.Error("Error in fetching state") return core.NilHash, err } - txnOpts := razorUtils.GetTxnOpts(context.Background(), types.TransactionOptions{ - Client: client, + txnOpts := razorUtils.GetTxnOpts(rpcParameters, types.TransactionOptions{ ChainId: core.ChainId, Config: config, ContractAddress: core.CollectionManagerAddress, @@ -110,6 +85,12 @@ func (*UtilsStruct) CreateCollection(client *ethclient.Client, config types.Conf ABI: bindings.CollectionManagerMetaData.ABI, Account: collectionInput.Account, }) + + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return core.NilHash, err + } + log.Debugf("Executing CreateCollection transaction with tolerance: %d, power = %d , aggregation = %d, jobIds = %v, name = %s", collectionInput.Tolerance, collectionInput.Power, collectionInput.Aggregation, jobIds, collectionInput.Name) txn, err := assetManagerUtils.CreateCollection(client, txnOpts, collectionInput.Tolerance, collectionInput.Power, collectionInput.Aggregation, jobIds, collectionInput.Name) if err != nil { diff --git a/cmd/createCollection_test.go b/cmd/createCollection_test.go index f2ea4b529..b41343510 100644 --- a/cmd/createCollection_test.go +++ b/cmd/createCollection_test.go @@ -16,7 +16,6 @@ import ( ) func TestCreateCollection(t *testing.T) { - var client *ethclient.Client var WaitForDisputeOrConfirmStateStatus uint32 var config types.Configurations var collectionInput types.CreateCollectionInput @@ -73,12 +72,12 @@ func TestCreateCollection(t *testing.T) { utilsMock.On("ConvertUintArrayToUint16Array", mock.Anything).Return(tt.args.jobIdUint8) utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(TxnOpts) - cmdUtilsMock.On("WaitForAppropriateState", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(WaitForDisputeOrConfirmStateStatus, tt.args.waitForAppropriateStateErr) + cmdUtilsMock.On("WaitForAppropriateState", mock.Anything, mock.Anything, mock.Anything).Return(WaitForDisputeOrConfirmStateStatus, tt.args.waitForAppropriateStateErr) assetManagerMock.On("CreateCollection", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.createCollectionTxn, tt.args.createCollectionErr) transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) utils := &UtilsStruct{} - got, err := utils.CreateCollection(client, config, collectionInput) + got, err := utils.CreateCollection(rpcParameters, config, collectionInput) if got != tt.want { t.Errorf("Txn hash for createCollection function, got = %v, want = %v", got, tt.want) } @@ -265,14 +264,16 @@ func TestExecuteCreateCollection(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() + setupTestEndpointsEnvironment() + utilsMock.On("IsFlagPassed", mock.Anything).Return(true) fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) @@ -285,8 +286,8 @@ func TestExecuteCreateCollection(t *testing.T) { flagSetMock.On("GetInt8Power", flagSet).Return(tt.args.power, tt.args.powerErr) flagSetMock.On("GetUint32Tolerance", flagSet).Return(tt.args.tolerance, tt.args.toleranceErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) - cmdUtilsMock.On("CreateCollection", mock.AnythingOfType("*ethclient.Client"), config, mock.Anything).Return(tt.args.createCollectionHash, tt.args.createCollectionErr) - utilsMock.On("WaitForBlockCompletion", client, mock.AnythingOfType("string")).Return(nil) + cmdUtilsMock.On("CreateCollection", mock.Anything, config, mock.Anything).Return(tt.args.createCollectionHash, tt.args.createCollectionErr) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) utils := &UtilsStruct{} fatal = false diff --git a/cmd/createJob.go b/cmd/createJob.go index 1d7959a57..0cd441889 100644 --- a/cmd/createJob.go +++ b/cmd/createJob.go @@ -2,16 +2,13 @@ package cmd import ( - "context" - "razor/accounts" "razor/core" "razor/core/types" - "razor/logger" "razor/pkg/bindings" + "razor/rpc" "razor/utils" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/pflag" "github.com/spf13/cobra" @@ -38,29 +35,8 @@ func initialiseCreateJob(cmd *cobra.Command, args []string) { //This function sets the flags appropriately and executes the CreateJob function func (*UtilsStruct) ExecuteCreateJob(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - log.Debugf("ExecuteCreateJob: Config: %+v", config) - - client := razorUtils.ConnectToClient(config.Provider) - - address, err := flagSetUtils.GetStringAddress(flagSet) - utils.CheckError("Error in getting address: ", err) - - logger.SetLoggerParameters(client, address) - log.Debug("Checking to assign log file...") - fileUtils.AssignLogFile(flagSet, config) - - log.Debug("Getting password...") - password := razorUtils.AssignPassword(flagSet) - - accountManager, err := razorUtils.AccountManagerForKeystore() - utils.CheckError("Error in getting accounts manager for keystore: ", err) - - account := accounts.InitAccountStruct(address, password, accountManager) - - err = razorUtils.CheckPassword(account) - utils.CheckError("Error in fetching private key from given password: ", err) + config, rpcParameters, account, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) name, err := flagSetUtils.GetStringName(flagSet) utils.CheckError("Error in getting name: ", err) @@ -90,16 +66,15 @@ func (*UtilsStruct) ExecuteCreateJob(flagSet *pflag.FlagSet) { Account: account, } - txn, err := cmdUtils.CreateJob(client, config, jobInput) + txn, err := cmdUtils.CreateJob(rpcParameters, config, jobInput) utils.CheckError("CreateJob error: ", err) - err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) + err = razorUtils.WaitForBlockCompletion(rpcParameters, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for createJob: ", err) } //This function allows the admin to create the job -func (*UtilsStruct) CreateJob(client *ethclient.Client, config types.Configurations, jobInput types.CreateJobInput) (common.Hash, error) { +func (*UtilsStruct) CreateJob(rpcParameters rpc.RPCParameters, config types.Configurations, jobInput types.CreateJobInput) (common.Hash, error) { txnArgs := types.TransactionOptions{ - Client: client, ChainId: core.ChainId, Config: config, ContractAddress: core.CollectionManagerAddress, @@ -109,10 +84,16 @@ func (*UtilsStruct) CreateJob(client *ethclient.Client, config types.Configurati Account: jobInput.Account, } - txnOpts := razorUtils.GetTxnOpts(context.Background(), txnArgs) + txnOpts := razorUtils.GetTxnOpts(rpcParameters, txnArgs) log.Info("Creating Job...") + + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return core.NilHash, err + } + log.Debugf("CreateJob: Executing CreateJob transaction with weight = %d, power = %d, selector type = %d, name = %s, selector = %s, URl = %s", jobInput.Weight, jobInput.Power, jobInput.SelectorType, jobInput.Name, jobInput.Selector, jobInput.Url) - txn, err := assetManagerUtils.CreateJob(txnArgs.Client, txnOpts, jobInput.Weight, jobInput.Power, jobInput.SelectorType, jobInput.Name, jobInput.Selector, jobInput.Url) + txn, err := assetManagerUtils.CreateJob(client, txnOpts, jobInput.Weight, jobInput.Power, jobInput.SelectorType, jobInput.Name, jobInput.Selector, jobInput.Url) if err != nil { return core.NilHash, err } diff --git a/cmd/createJob_test.go b/cmd/createJob_test.go index d8a483625..91f0c301b 100644 --- a/cmd/createJob_test.go +++ b/cmd/createJob_test.go @@ -16,7 +16,6 @@ import ( ) func TestCreateJob(t *testing.T) { - var client *ethclient.Client var jobInput types.CreateJobInput var config types.Configurations @@ -60,7 +59,7 @@ func TestCreateJob(t *testing.T) { transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) utils := &UtilsStruct{} - got, err := utils.CreateJob(client, config, jobInput) + got, err := utils.CreateJob(rpcParameters, config, jobInput) if got != tt.want { t.Errorf("Txn hash for createJob function, got = %v, want = %v", got, tt.want) } @@ -287,14 +286,16 @@ func TestExecuteCreateJob(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() + setupTestEndpointsEnvironment() + utilsMock.On("IsFlagPassed", mock.Anything).Return(true) fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) @@ -308,8 +309,8 @@ func TestExecuteCreateJob(t *testing.T) { flagSetMock.On("GetUint8Weight", flagSet).Return(tt.args.weight, tt.args.weightErr) flagSetMock.On("GetUint8SelectorType", flagSet).Return(tt.args.selectorType, tt.args.selectorTypeErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) - cmdUtilsMock.On("CreateJob", mock.AnythingOfType("*ethclient.Client"), config, mock.Anything).Return(tt.args.createJobHash, tt.args.createJobErr) - utilsMock.On("WaitForBlockCompletion", client, mock.AnythingOfType("string")).Return(nil) + cmdUtilsMock.On("CreateJob", mock.Anything, config, mock.Anything).Return(tt.args.createJobHash, tt.args.createJobErr) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) utils := &UtilsStruct{} fatal = false diff --git a/cmd/create_test.go b/cmd/create_test.go index cb7bf36e9..dfcb40752 100644 --- a/cmd/create_test.go +++ b/cmd/create_test.go @@ -148,14 +148,16 @@ func TestExecuteCreate(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() + setupTestEndpointsEnvironment() + utilsMock.On("IsFlagPassed", mock.Anything).Return(false) fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) utilsMock.On("AssignPassword", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.password) utilsMock.On("CheckPassword", mock.Anything).Return(nil) diff --git a/cmd/delegate.go b/cmd/delegate.go index 8ebbaff6c..f5c02582b 100644 --- a/cmd/delegate.go +++ b/cmd/delegate.go @@ -2,12 +2,10 @@ package cmd import ( - "context" - "razor/accounts" "razor/core" "razor/core/types" - "razor/logger" "razor/pkg/bindings" + "razor/rpc" "razor/utils" "github.com/ethereum/go-ethereum/common" @@ -34,36 +32,14 @@ func initialiseDelegate(cmd *cobra.Command, args []string) { //This function sets the flags appropriately and executes the Delegate function func (*UtilsStruct) ExecuteDelegate(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - log.Debugf("ExecuteDelegate: Config: %+v", config) - - client := razorUtils.ConnectToClient(config.Provider) - - address, err := flagSetUtils.GetStringAddress(flagSet) - utils.CheckError("Error in getting address: ", err) - log.Debug("ExecuteDelegate: Address: ", address) - - logger.SetLoggerParameters(client, address) - log.Debug("Checking to assign log file...") - fileUtils.AssignLogFile(flagSet, config) - - log.Debug("Getting password...") - password := razorUtils.AssignPassword(flagSet) - - accountManager, err := razorUtils.AccountManagerForKeystore() - utils.CheckError("Error in getting accounts manager for keystore: ", err) - - account := accounts.InitAccountStruct(address, password, accountManager) - - err = razorUtils.CheckPassword(account) - utils.CheckError("Error in fetching private key from given password: ", err) + config, rpcParameters, account, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) stakerId, err := flagSetUtils.GetUint32StakerId(flagSet) utils.CheckError("Error in getting stakerId: ", err) log.Debug("ExecuteDelegate: Staker Id: ", stakerId) - balance, err := razorUtils.FetchBalance(client, address) - utils.CheckError("Error in fetching razor balance for account "+address+": ", err) + balance, err := razorUtils.FetchBalance(rpcParameters, account.Address) + utils.CheckError("Error in fetching razor balance for account "+account.Address+": ", err) log.Debug("ExecuteDelegate: Balance: ", balance) log.Debug("Getting amount in wei...") @@ -74,42 +50,47 @@ func (*UtilsStruct) ExecuteDelegate(flagSet *pflag.FlagSet) { razorUtils.CheckAmountAndBalance(valueInWei, balance) log.Debug("Checking whether sFUEL balance is not 0...") - razorUtils.CheckEthBalanceIsZero(context.Background(), client, address) + razorUtils.CheckEthBalanceIsZero(rpcParameters, account.Address) txnArgs := types.TransactionOptions{ - Client: client, Amount: valueInWei, ChainId: core.ChainId, Config: config, Account: account, } - approveTxnHash, err := cmdUtils.Approve(txnArgs) + approveTxnHash, err := cmdUtils.Approve(rpcParameters, txnArgs) utils.CheckError("Approve error: ", err) if approveTxnHash != core.NilHash { - err = razorUtils.WaitForBlockCompletion(txnArgs.Client, approveTxnHash.Hex()) + err = razorUtils.WaitForBlockCompletion(rpcParameters, approveTxnHash.Hex()) utils.CheckError("Error in WaitForBlockCompletion for approve: ", err) } log.Debug("ExecuteDelegate:Calling Delegate() with stakerId: ", stakerId) - delegateTxnHash, err := cmdUtils.Delegate(txnArgs, stakerId) + delegateTxnHash, err := cmdUtils.Delegate(rpcParameters, txnArgs, stakerId) utils.CheckError("Delegate error: ", err) - err = razorUtils.WaitForBlockCompletion(client, delegateTxnHash.Hex()) + err = razorUtils.WaitForBlockCompletion(rpcParameters, delegateTxnHash.Hex()) utils.CheckError("Error in WaitForBlockCompletion for delegate: ", err) } //This function allows the delegator to stake coins without setting up a node -func (*UtilsStruct) Delegate(txnArgs types.TransactionOptions, stakerId uint32) (common.Hash, error) { +func (*UtilsStruct) Delegate(rpcParameters rpc.RPCParameters, txnArgs types.TransactionOptions, stakerId uint32) (common.Hash, error) { log.Infof("Delegating %g razors to Staker %d", utils.GetAmountInDecimal(txnArgs.Amount), stakerId) txnArgs.ContractAddress = core.StakeManagerAddress txnArgs.MethodName = "delegate" txnArgs.ABI = bindings.StakeManagerMetaData.ABI txnArgs.Parameters = []interface{}{stakerId, txnArgs.Amount} - delegationTxnOpts := razorUtils.GetTxnOpts(context.Background(), txnArgs) + delegationTxnOpts := razorUtils.GetTxnOpts(rpcParameters, txnArgs) log.Info("Sending Delegate transaction...") + + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return core.NilHash, err + } + log.Debugf("Executing Delegate transaction with stakerId = %d, amount = %s", stakerId, txnArgs.Amount) - txn, err := stakeManagerUtils.Delegate(txnArgs.Client, delegationTxnOpts, stakerId, txnArgs.Amount) + txn, err := stakeManagerUtils.Delegate(client, delegationTxnOpts, stakerId, txnArgs.Amount) if err != nil { return core.NilHash, err } diff --git a/cmd/delegate_test.go b/cmd/delegate_test.go index 033bc51af..1b2cccfa5 100644 --- a/cmd/delegate_test.go +++ b/cmd/delegate_test.go @@ -63,7 +63,7 @@ func TestDelegate(t *testing.T) { utils := &UtilsStruct{} - got, err := utils.Delegate(types.TransactionOptions{ + got, err := utils.Delegate(rpcParameters, types.TransactionOptions{ Amount: tt.args.amount, }, stakerId) if got != tt.want { @@ -104,9 +104,9 @@ func TestExecuteDelegate(t *testing.T) { delegateErr error } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } tests := []struct { name string @@ -236,7 +236,9 @@ func TestExecuteDelegate(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() + setupTestEndpointsEnvironment() + utilsMock.On("IsFlagPassed", mock.Anything).Return(true) fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) @@ -245,13 +247,13 @@ func TestExecuteDelegate(t *testing.T) { flagSetMock.On("GetStringAddress", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.address, tt.args.addressErr) flagSetMock.On("GetUint32StakerId", flagSet).Return(tt.args.stakerId, tt.args.stakerIdErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) - utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) - utilsMock.On("FetchBalance", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.balance, tt.args.balanceErr) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) + utilsMock.On("FetchBalance", mock.Anything, mock.Anything).Return(tt.args.balance, tt.args.balanceErr) cmdUtilsMock.On("AssignAmountInWei", flagSet).Return(tt.args.amount, tt.args.amountErr) utilsMock.On("CheckAmountAndBalance", mock.AnythingOfType("*big.Int"), mock.AnythingOfType("*big.Int")).Return(tt.args.amount) - utilsMock.On("CheckEthBalanceIsZero", mock.Anything, mock.Anything, mock.Anything).Return() - cmdUtilsMock.On("Approve", mock.Anything).Return(tt.args.approveTxn, tt.args.approveErr) - cmdUtilsMock.On("Delegate", mock.Anything, mock.AnythingOfType("uint32")).Return(tt.args.delegateHash, tt.args.delegateErr) + utilsMock.On("CheckEthBalanceIsZero", mock.Anything, mock.Anything).Return() + cmdUtilsMock.On("Approve", mock.Anything, mock.Anything).Return(tt.args.approveTxn, tt.args.approveErr) + cmdUtilsMock.On("Delegate", mock.Anything, mock.Anything, mock.AnythingOfType("uint32")).Return(tt.args.delegateHash, tt.args.delegateErr) utils := &UtilsStruct{} fatal = false diff --git a/cmd/dispute.go b/cmd/dispute.go index 4f18c7941..61acaed44 100644 --- a/cmd/dispute.go +++ b/cmd/dispute.go @@ -2,7 +2,6 @@ package cmd import ( - "context" "errors" "math/big" "os" @@ -10,6 +9,7 @@ import ( "razor/core/types" "razor/path" "razor/pkg/bindings" + "razor/rpc" "razor/utils" "strings" @@ -17,7 +17,6 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" Types "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethclient" solsha3 "github.com/miguelmota/go-solidity-sha3" ) @@ -28,23 +27,23 @@ var ( //blockId is id of the block //This function handles the dispute and if there is any error it returns the error -func (*UtilsStruct) HandleDispute(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, blockNumber *big.Int, rogueData types.Rogue, backupNodeActionsToIgnore []string) error { +func (*UtilsStruct) HandleDispute(rpcParameters rpc.RPCParameters, config types.Configurations, account types.Account, epoch uint32, blockNumber *big.Int, rogueData types.Rogue, backupNodeActionsToIgnore []string) error { - sortedProposedBlockIds, err := razorUtils.GetSortedProposedBlockIds(ctx, client, epoch) + sortedProposedBlockIds, err := razorUtils.GetSortedProposedBlockIds(rpcParameters, epoch) if err != nil { log.Error("Error in fetching sorted proposed block id: ", err) return err } log.Debug("HandleDispute: SortedProposedBlockIds: ", sortedProposedBlockIds) - biggestStake, biggestStakerId, err := cmdUtils.GetBiggestStakeAndId(ctx, client, epoch) + biggestStake, biggestStakerId, err := cmdUtils.GetBiggestStakeAndId(rpcParameters, epoch) if err != nil { return err } log.Debugf("HandleDispute: Biggest stake: %s, Biggest staker Id: %d", biggestStake, biggestStakerId) log.Debugf("HandleDispute: Calling GetLocalMediansData() with arguments epoch = %d, blockNumber = %d, rogueData = %+v", epoch, blockNumber, rogueData) - locallyCalculatedData, err := cmdUtils.GetLocalMediansData(ctx, client, account, epoch, blockNumber, rogueData) + locallyCalculatedData, err := cmdUtils.GetLocalMediansData(rpcParameters, account, epoch, blockNumber, rogueData) if err != nil { return err } @@ -58,7 +57,6 @@ func (*UtilsStruct) HandleDispute(ctx context.Context, client *ethclient.Client, randomSortedProposedBlockIds := utils.Shuffle(sortedProposedBlockIds) //shuffles the sortedProposedBlockIds array transactionOptions := types.TransactionOptions{ - Client: client, ChainId: core.ChainId, Config: config, Account: account, @@ -67,7 +65,7 @@ func (*UtilsStruct) HandleDispute(ctx context.Context, client *ethclient.Client, log.Debug("Iterating over random sorted proposed blocks to check dispute...") for _, blockId := range randomSortedProposedBlockIds { - proposedBlock, err := razorUtils.GetProposedBlock(ctx, client, epoch, blockId) + proposedBlock, err := razorUtils.GetProposedBlock(rpcParameters, epoch, blockId) if err != nil { log.Error(err) continue @@ -87,12 +85,18 @@ func (*UtilsStruct) HandleDispute(ctx context.Context, client *ethclient.Client, log.Debug("Biggest Stake in proposed block: ", proposedBlock.BiggestStake) log.Warn("PROPOSED BIGGEST STAKE DOES NOT MATCH WITH ACTUAL BIGGEST STAKE") log.Info("Disputing BiggestStakeProposed...") - txnOpts := razorUtils.GetTxnOpts(ctx, types.TransactionOptions{ - Client: client, + txnOpts := razorUtils.GetTxnOpts(rpcParameters, types.TransactionOptions{ ChainId: core.ChainId, Config: config, Account: account, }) + + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + log.Error(err) + continue + } + log.Debugf("Executing DisputeBiggestStakeProposed transaction with arguments epoch = %d, blockIndex = %d, biggest staker Id = %d", epoch, blockIndex, biggestStakerId) disputeBiggestStakeProposedTxn, err := blockManagerUtils.DisputeBiggestStakeProposed(client, txnOpts, epoch, uint8(blockIndex), biggestStakerId) if err != nil { @@ -101,12 +105,12 @@ func (*UtilsStruct) HandleDispute(ctx context.Context, client *ethclient.Client, } disputeBiggestStakeProposedTxnHash := transactionUtils.Hash(disputeBiggestStakeProposedTxn) log.Info("Txn Hash: ", disputeBiggestStakeProposedTxnHash.Hex()) - WaitForBlockCompletionErr := razorUtils.WaitForBlockCompletion(client, disputeBiggestStakeProposedTxnHash.Hex()) + WaitForBlockCompletionErr := razorUtils.WaitForBlockCompletion(rpcParameters, disputeBiggestStakeProposedTxnHash.Hex()) //If dispute happens, then storing the bountyId into disputeData file if WaitForBlockCompletionErr == nil { log.Debug("Storing bounty Id in dispute data file....") - err = cmdUtils.StoreBountyId(ctx, client, account) + err = cmdUtils.StoreBountyId(rpcParameters, account) if err != nil { log.Error(err) } @@ -119,7 +123,7 @@ func (*UtilsStruct) HandleDispute(ctx context.Context, client *ethclient.Client, log.Debug("HandleDispute: Revealed collection ids in the block ", proposedBlock.Ids) log.Debugf("HandleDispute: Calling CheckDisputeForIds() with arguments epoch = %d, blockIndex = %d, proposed revealed Ids = %v, locally calculated revealed Ids = %v", epoch, blockIndex, proposedBlock.Ids, revealedCollectionIds) - idDisputeTxn, err := cmdUtils.CheckDisputeForIds(ctx, client, transactionOptions, epoch, uint8(blockIndex), proposedBlock.Ids, revealedCollectionIds) + idDisputeTxn, err := cmdUtils.CheckDisputeForIds(rpcParameters, transactionOptions, epoch, uint8(blockIndex), proposedBlock.Ids, revealedCollectionIds) if err != nil { log.Error("Error in disputing: ", err) continue @@ -127,12 +131,12 @@ func (*UtilsStruct) HandleDispute(ctx context.Context, client *ethclient.Client, if idDisputeTxn != nil { idDisputeTxnHash := transactionUtils.Hash(idDisputeTxn) log.Debugf("Txn Hash: %s", idDisputeTxnHash.Hex()) - WaitForBlockCompletionErr := razorUtils.WaitForBlockCompletion(client, idDisputeTxnHash.Hex()) + WaitForBlockCompletionErr := razorUtils.WaitForBlockCompletion(rpcParameters, idDisputeTxnHash.Hex()) //If dispute happens, then storing the bountyId into disputeData file if WaitForBlockCompletionErr == nil { log.Debug("Storing bounty Id in dispute data file...") - err = cmdUtils.StoreBountyId(ctx, client, account) + err = cmdUtils.StoreBountyId(rpcParameters, account) if err != nil { log.Error(err) } @@ -165,14 +169,14 @@ func (*UtilsStruct) HandleDispute(ctx context.Context, client *ethclient.Client, sortedValues := revealedDataMaps.SortedRevealedValues[collectionIdOfWrongMedian-1] log.Debug("HandleDispute: Sorted values: ", sortedValues) - leafId, err := razorUtils.GetLeafIdOfACollection(ctx, client, collectionIdOfWrongMedian) + leafId, err := razorUtils.GetLeafIdOfACollection(rpcParameters, collectionIdOfWrongMedian) if err != nil { log.Error("Error in leaf id: ", err) continue } log.Debug("HandleDispute: Leaf Id: ", leafId) log.Debugf("Calling Dispute() with arguments epoch = %d, blockIndex = %d, proposed block = %+v, leafId = %d, sortedValues = %s", epoch, uint8(blockIndex), proposedBlock, leafId, sortedValues) - disputeErr := cmdUtils.Dispute(ctx, client, config, account, epoch, uint8(blockIndex), proposedBlock, leafId, sortedValues) + disputeErr := cmdUtils.Dispute(rpcParameters, config, account, epoch, uint8(blockIndex), proposedBlock, leafId, sortedValues) if disputeErr != nil { log.Error("Error in disputing...", disputeErr) continue @@ -192,11 +196,11 @@ func (*UtilsStruct) HandleDispute(ctx context.Context, client *ethclient.Client, } //This function returns the local median data -func (*UtilsStruct) GetLocalMediansData(ctx context.Context, client *ethclient.Client, account types.Account, epoch uint32, blockNumber *big.Int, rogueData types.Rogue) (types.ProposeFileData, error) { +func (*UtilsStruct) GetLocalMediansData(rpcParameters rpc.RPCParameters, account types.Account, epoch uint32, blockNumber *big.Int, rogueData types.Rogue) (types.ProposeFileData, error) { if rogueData.IsRogue { // As the staker has proposed with incorrect medians in rogue mode so those values needs to be compared with the correct calculated medians log.Debug("Staker proposed in rogue mode, now calculating medians correctly...") - return calculateMedian(ctx, client, account, epoch, blockNumber) + return calculateMedian(rpcParameters, account, epoch, blockNumber) } // Fetching the data from file only if the node is not in rogue mode and @@ -207,18 +211,18 @@ func (*UtilsStruct) GetLocalMediansData(ctx context.Context, client *ethclient.C fileName, err := pathUtils.GetProposeDataFileName(account.Address) if err != nil { log.Error("Error in getting file name to read median data: ", err) - return calculateMedian(ctx, client, account, epoch, blockNumber) + return calculateMedian(rpcParameters, account, epoch, blockNumber) } log.Debug("GetLocalMediansData: Propose data file path: ", fileName) proposedData, err := fileUtils.ReadFromProposeJsonFile(fileName) if err != nil { log.Errorf("Error in getting propose data from file %s: %v", fileName, err) - return calculateMedian(ctx, client, account, epoch, blockNumber) + return calculateMedian(rpcParameters, account, epoch, blockNumber) } log.Debugf("GetLocalMediansData: Proposed data from file: %+v", proposedData) if proposedData.Epoch != epoch { log.Errorf("File %s doesn't contain latest median data", fileName) - return calculateMedian(ctx, client, account, epoch, blockNumber) + return calculateMedian(rpcParameters, account, epoch, blockNumber) } return proposedData, err } @@ -226,8 +230,8 @@ func (*UtilsStruct) GetLocalMediansData(ctx context.Context, client *ethclient.C return globalProposedDataStruct, nil } -func calculateMedian(ctx context.Context, client *ethclient.Client, account types.Account, epoch uint32, blockNumber *big.Int) (types.ProposeFileData, error) { - stakerId, err := razorUtils.GetStakerId(ctx, client, account.Address) +func calculateMedian(rpcParameters rpc.RPCParameters, account types.Account, epoch uint32, blockNumber *big.Int) (types.ProposeFileData, error) { + stakerId, err := razorUtils.GetStakerId(rpcParameters, account.Address) if err != nil { log.Error("Error in getting stakerId: ", err) return types.ProposeFileData{}, err @@ -236,7 +240,7 @@ func calculateMedian(ctx context.Context, client *ethclient.Client, account type log.Debug("Calculating the medians data again...") log.Debugf("GetLocalMediansData: Calling MakeBlock() with arguments blockNumber = %s, epoch = %d, rogueData = %+v", blockNumber, epoch, types.Rogue{IsRogue: false}) - medians, revealedCollectionIds, revealedDataMaps, err := cmdUtils.MakeBlock(ctx, client, blockNumber, epoch, types.Rogue{IsRogue: false}) + medians, revealedCollectionIds, revealedDataMaps, err := cmdUtils.MakeBlock(rpcParameters, blockNumber, epoch, types.Rogue{IsRogue: false}) if err != nil { log.Error("Error in calculating block medians: ", err) return types.ProposeFileData{}, err @@ -253,7 +257,7 @@ func calculateMedian(ctx context.Context, client *ethclient.Client, account type } //This function check for the dispute in different type of Id's -func (*UtilsStruct) CheckDisputeForIds(ctx context.Context, client *ethclient.Client, transactionOpts types.TransactionOptions, epoch uint32, blockIndex uint8, idsInProposedBlock []uint16, revealedCollectionIds []uint16) (*Types.Transaction, error) { +func (*UtilsStruct) CheckDisputeForIds(rpcParameters rpc.RPCParameters, transactionOpts types.TransactionOptions, epoch uint32, blockIndex uint8, idsInProposedBlock []uint16, revealedCollectionIds []uint16) (*Types.Transaction, error) { //checking for hashing whether there is any dispute or not hashIdsInProposedBlock := solsha3.SoliditySHA3([]string{"uint16[]"}, []interface{}{idsInProposedBlock}) log.Debug("CheckDisputeForIds: Hash of reveal Ids in proposed block: ", hashIdsInProposedBlock) @@ -273,7 +277,13 @@ func (*UtilsStruct) CheckDisputeForIds(ctx context.Context, client *ethclient.Cl transactionOpts.ABI = bindings.BlockManagerMetaData.ABI transactionOpts.MethodName = "disputeOnOrderOfIds" transactionOpts.Parameters = []interface{}{epoch, blockIndex, index0, index1} - txnOpts := razorUtils.GetTxnOpts(ctx, transactionOpts) + txnOpts := razorUtils.GetTxnOpts(rpcParameters, transactionOpts) + + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return nil, err + } + log.Debug("Disputing sorted order of ids!") log.Debugf("CheckDisputeForIds: Executing DisputeOnOrderOfIds transaction with arguments epoch: %d, blockIndex: %d, index0: %d, index1: %d", epoch, blockIndex, index0, index1) return blockManagerUtils.DisputeOnOrderOfIds(client, txnOpts, epoch, blockIndex, big.NewInt(int64(index0)), big.NewInt(int64(index1))) @@ -285,13 +295,19 @@ func (*UtilsStruct) CheckDisputeForIds(ctx context.Context, client *ethclient.Cl transactionOpts.ABI = bindings.BlockManagerMetaData.ABI transactionOpts.MethodName = "disputeCollectionIdShouldBePresent" transactionOpts.Parameters = []interface{}{epoch, blockIndex, missingCollectionId} - txnOpts := razorUtils.GetTxnOpts(ctx, transactionOpts) + txnOpts := razorUtils.GetTxnOpts(rpcParameters, transactionOpts) gasLimit := txnOpts.GasLimit - incrementedGasLimit, err := gasUtils.IncreaseGasLimitValue(ctx, client, gasLimit, core.DisputeGasMultiplier) + incrementedGasLimit, err := gasUtils.IncreaseGasLimitValue(rpcParameters, gasLimit, core.DisputeGasMultiplier) if err != nil { return nil, err } txnOpts.GasLimit = incrementedGasLimit + + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return nil, err + } + log.Debug("Disputing collection id should be present!") log.Debugf("CheckDisputeForIds: Executing DisputeCollectionIdShouldBePresent transaction with arguments epoch: %d, blockIndex: %d, missingCollectionId: %d", epoch, blockIndex, missingCollectionId) return blockManagerUtils.DisputeCollectionIdShouldBePresent(client, txnOpts, epoch, blockIndex, missingCollectionId) @@ -303,13 +319,19 @@ func (*UtilsStruct) CheckDisputeForIds(ctx context.Context, client *ethclient.Cl transactionOpts.ABI = bindings.BlockManagerMetaData.ABI transactionOpts.MethodName = "disputeCollectionIdShouldBeAbsent" transactionOpts.Parameters = []interface{}{epoch, blockIndex, presentCollectionId, big.NewInt(int64(positionOfPresentValue))} - txnOpts := razorUtils.GetTxnOpts(ctx, transactionOpts) + txnOpts := razorUtils.GetTxnOpts(rpcParameters, transactionOpts) gasLimit := txnOpts.GasLimit - incrementedGasLimit, err := gasUtils.IncreaseGasLimitValue(ctx, client, gasLimit, core.DisputeGasMultiplier) + incrementedGasLimit, err := gasUtils.IncreaseGasLimitValue(rpcParameters, gasLimit, core.DisputeGasMultiplier) if err != nil { return nil, err } txnOpts.GasLimit = incrementedGasLimit + + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return nil, err + } + log.Debug("Disputing collection id should be absent!") log.Debugf("CheckDisputeForIds: Executing DisputeCollectionIdShouldBeAbsent transaction with arguments epoch: %d, blockIndex: %d, presentCollectionId: %d, positionOfPresentValue: %d", epoch, blockIndex, presentCollectionId, positionOfPresentValue) return blockManagerUtils.DisputeCollectionIdShouldBeAbsent(client, txnOpts, epoch, blockIndex, presentCollectionId, big.NewInt(int64(positionOfPresentValue))) @@ -319,11 +341,8 @@ func (*UtilsStruct) CheckDisputeForIds(ctx context.Context, client *ethclient.Cl } //This function finalizes the dispute and return the error if there is any -func (*UtilsStruct) Dispute(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, blockIndex uint8, proposedBlock bindings.StructsBlock, leafId uint16, sortedValues []*big.Int) error { - blockManager := razorUtils.GetBlockManager(client) - +func (*UtilsStruct) Dispute(rpcParameters rpc.RPCParameters, config types.Configurations, account types.Account, epoch uint32, blockIndex uint8, proposedBlock bindings.StructsBlock, leafId uint16, sortedValues []*big.Int) error { txnArgs := types.TransactionOptions{ - Client: client, ChainId: core.ChainId, Config: config, Account: account, @@ -343,15 +362,15 @@ func (*UtilsStruct) Dispute(ctx context.Context, client *ethclient.Client, confi end = lenOfSortedValues } log.Debugf("Dispute: Calling GiveSorted with arguments epoch = %d, leafId = %d, sortedValues = %s", epoch, leafId, sortedValues[start:end]) - err := cmdUtils.GiveSorted(ctx, client, blockManager, txnArgs, epoch, leafId, sortedValues[start:end]) + err := cmdUtils.GiveSorted(rpcParameters, txnArgs, epoch, leafId, sortedValues[start:end]) if err != nil { if err.Error() == errors.New("gas limit reached").Error() { end = end / 2 } else { log.Error("Error in GiveSorted: ", err) - txnOpts := razorUtils.GetTxnOpts(ctx, txnArgs) + txnOpts := razorUtils.GetTxnOpts(rpcParameters, txnArgs) log.Debugf("Dispute: Calling CheckToDoResetDispute with arguments epoch = %d, sortedValues = %s", epoch, sortedValues) - cmdUtils.CheckToDoResetDispute(client, blockManager, txnOpts, epoch, sortedValues) + cmdUtils.CheckToDoResetDispute(rpcParameters, txnOpts, epoch, sortedValues) return err } } else { @@ -369,7 +388,7 @@ func (*UtilsStruct) Dispute(ctx context.Context, client *ethclient.Client, confi giveSortedLeafIds = append(giveSortedLeafIds, int(leafId)) } log.Debugf("Dispute: Calling GetCollectionIdPositionInBlock with arguments leafId = %d, proposed block = %+v", leafId, proposedBlock) - positionOfCollectionInBlock := cmdUtils.GetCollectionIdPositionInBlock(ctx, client, leafId, proposedBlock) + positionOfCollectionInBlock := cmdUtils.GetCollectionIdPositionInBlock(rpcParameters, leafId, proposedBlock) log.Debug("Dispute: Position of collection id in block: ", positionOfCollectionInBlock) log.Info("Finalizing dispute...") @@ -378,7 +397,12 @@ func (*UtilsStruct) Dispute(ctx context.Context, client *ethclient.Client, confi finalizeDisputeTxnArgs.MethodName = "finalizeDispute" finalizeDisputeTxnArgs.ABI = bindings.BlockManagerMetaData.ABI finalizeDisputeTxnArgs.Parameters = []interface{}{epoch, blockIndex, positionOfCollectionInBlock} - finalizeDisputeTxnOpts := razorUtils.GetTxnOpts(ctx, finalizeDisputeTxnArgs) + finalizeDisputeTxnOpts := razorUtils.GetTxnOpts(rpcParameters, finalizeDisputeTxnArgs) + + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return err + } log.Debugf("Executing FinalizeDispute transaction with arguments epoch = %d, blockIndex = %d, positionOfCollectionInBlock = %d", epoch, blockIndex, positionOfCollectionInBlock) finalizeTxn, err := blockManagerUtils.FinalizeDispute(client, finalizeDisputeTxnOpts, epoch, blockIndex, positionOfCollectionInBlock) @@ -392,11 +416,11 @@ func (*UtilsStruct) Dispute(ctx context.Context, client *ethclient.Client, confi finalizeTxnHash := transactionUtils.Hash(finalizeTxn) log.Info("Txn Hash: ", finalizeTxnHash.Hex()) log.Debug("Dispute: Checking mining status of FinalizeDispute transaction...") - WaitForBlockCompletionErr := razorUtils.WaitForBlockCompletion(client, finalizeTxnHash.Hex()) + WaitForBlockCompletionErr := razorUtils.WaitForBlockCompletion(rpcParameters, finalizeTxnHash.Hex()) //If dispute happens, then storing the bountyId into disputeData file if WaitForBlockCompletionErr == nil { log.Debug("Storing bounty Id in dispute data file...") - err = cmdUtils.StoreBountyId(ctx, client, account) + err = cmdUtils.StoreBountyId(rpcParameters, account) if err != nil { return err } @@ -413,21 +437,20 @@ func (*UtilsStruct) Dispute(ctx context.Context, client *ethclient.Client, confi resetDisputeTxnArgs.MethodName = "resetDispute" resetDisputeTxnArgs.ABI = bindings.BlockManagerMetaData.ABI resetDisputeTxnArgs.Parameters = []interface{}{epoch} - resetDisputeTxnOpts := razorUtils.GetTxnOpts(ctx, resetDisputeTxnArgs) + resetDisputeTxnOpts := razorUtils.GetTxnOpts(rpcParameters, resetDisputeTxnArgs) - cmdUtils.ResetDispute(client, blockManager, resetDisputeTxnOpts, epoch) + cmdUtils.ResetDispute(rpcParameters, resetDisputeTxnOpts, epoch) return nil } //This function sorts the Id's recursively -func GiveSorted(ctx context.Context, client *ethclient.Client, blockManager *bindings.BlockManager, txnArgs types.TransactionOptions, epoch uint32, leafId uint16, sortedValues []*big.Int) error { +func GiveSorted(rpcParameters rpc.RPCParameters, txnArgs types.TransactionOptions, epoch uint32, leafId uint16, sortedValues []*big.Int) error { if len(sortedValues) == 0 { return errors.New("length of sortedValues is 0") } - callOpts := razorUtils.GetOptions() - txnOpts := razorUtils.GetTxnOpts(ctx, txnArgs) - disputesMapping, err := blockManagerUtils.Disputes(client, &callOpts, epoch, common.HexToAddress(txnArgs.Account.Address)) + txnOpts := razorUtils.GetTxnOpts(rpcParameters, txnArgs) + disputesMapping, err := razorUtils.Disputes(rpcParameters, epoch, common.HexToAddress(txnArgs.Account.Address)) if err != nil { log.Error("Error in getting disputes mapping: ", disputesMapping) return err @@ -446,8 +469,14 @@ func GiveSorted(ctx context.Context, client *ethclient.Client, blockManager *bin log.Debug("GiveSorted: Is give sorted initiated: ", isGiveSortedInitiated) log.Info("Calling GiveSorted...") + + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return err + } + log.Debugf("Executing GiveSorted transaction with arguments epoch = %d, leafId = %d , sortedValues = %s", epoch, leafId, sortedValues) - txn, err := blockManagerUtils.GiveSorted(blockManager, txnOpts, epoch, leafId, sortedValues) + txn, err := blockManagerUtils.GiveSorted(client, txnOpts, epoch, leafId, sortedValues) if err != nil { return err } @@ -455,7 +484,7 @@ func GiveSorted(ctx context.Context, client *ethclient.Client, blockManager *bin txnHash := transactionUtils.Hash(txn) log.Info("Txn Hash: ", txnHash.Hex()) giveSortedLeafIds = append(giveSortedLeafIds, int(leafId)) - err = razorUtils.WaitForBlockCompletion(client, txnHash.Hex()) + err = razorUtils.WaitForBlockCompletion(rpcParameters, txnHash.Hex()) if err != nil { log.Error("Error in WaitForBlockCompletion for giveSorted: ", err) return err @@ -464,9 +493,9 @@ func GiveSorted(ctx context.Context, client *ethclient.Client, blockManager *bin } //This function returns the collection Id position in block -func (*UtilsStruct) GetCollectionIdPositionInBlock(ctx context.Context, client *ethclient.Client, leafId uint16, proposedBlock bindings.StructsBlock) *big.Int { +func (*UtilsStruct) GetCollectionIdPositionInBlock(rpcParameters rpc.RPCParameters, leafId uint16, proposedBlock bindings.StructsBlock) *big.Int { ids := proposedBlock.Ids - idToBeDisputed, err := razorUtils.GetCollectionIdFromLeafId(ctx, client, leafId) + idToBeDisputed, err := razorUtils.GetCollectionIdFromLeafId(rpcParameters, leafId) if err != nil { log.Error("Error in fetching collection id from leaf id") return nil @@ -482,7 +511,7 @@ func (*UtilsStruct) GetCollectionIdPositionInBlock(ctx context.Context, client * } //This function saves the bountyId in disputeData file and return the error if there is any -func (*UtilsStruct) StoreBountyId(ctx context.Context, client *ethclient.Client, account types.Account) error { +func (*UtilsStruct) StoreBountyId(rpcParameters rpc.RPCParameters, account types.Account) error { disputeFilePath, err := pathUtils.GetDisputeDataFileName(account.Address) if err != nil { return err @@ -491,7 +520,7 @@ func (*UtilsStruct) StoreBountyId(ctx context.Context, client *ethclient.Client, var latestBountyId uint32 - latestHeader, err := clientUtils.GetLatestBlockWithRetry(ctx, client) + latestHeader, err := clientUtils.GetLatestBlockWithRetry(rpcParameters) if err != nil { log.Error("Error in fetching block: ", err) return err @@ -499,7 +528,7 @@ func (*UtilsStruct) StoreBountyId(ctx context.Context, client *ethclient.Client, log.Debug("StoreBountyId: Latest header: ", latestHeader) log.Debugf("StoreBountyId: Calling GetBountyIdFromEvents with arguments blockNumber = %d, address = %s", latestHeader.Number, account.Address) - latestBountyId, err = cmdUtils.GetBountyIdFromEvents(ctx, client, latestHeader.Number, account.Address) + latestBountyId, err = cmdUtils.GetBountyIdFromEvents(rpcParameters, latestHeader.Number, account.Address) if err != nil { return err } @@ -528,16 +557,20 @@ func (*UtilsStruct) StoreBountyId(ctx context.Context, client *ethclient.Client, } //This function resets the dispute -func (*UtilsStruct) ResetDispute(client *ethclient.Client, blockManager *bindings.BlockManager, txnOpts *bind.TransactOpts, epoch uint32) { +func (*UtilsStruct) ResetDispute(rpcParameters rpc.RPCParameters, txnOpts *bind.TransactOpts, epoch uint32) { + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return + } log.Debug("Executing ResetDispute transaction with arguments epoch = ", epoch) - txn, err := blockManagerUtils.ResetDispute(blockManager, txnOpts, epoch) + txn, err := blockManagerUtils.ResetDispute(client, txnOpts, epoch) if err != nil { log.Error("error in resetting dispute", err) return } txnHash := transactionUtils.Hash(txn) log.Info("Txn Hash: ", txnHash.Hex()) - err = razorUtils.WaitForBlockCompletion(client, txnHash.Hex()) + err = razorUtils.WaitForBlockCompletion(rpcParameters, txnHash.Hex()) if err != nil { log.Error("Error in WaitForBlockCompletion for resetDispute: ", err) return @@ -546,8 +579,8 @@ func (*UtilsStruct) ResetDispute(client *ethclient.Client, blockManager *binding } //This function returns the bountyId from events -func (*UtilsStruct) GetBountyIdFromEvents(ctx context.Context, client *ethclient.Client, blockNumber *big.Int, bountyHunter string) (uint32, error) { - fromBlock, err := razorUtils.EstimateBlockNumberAtEpochBeginning(client, blockNumber) +func (*UtilsStruct) GetBountyIdFromEvents(rpcParameters rpc.RPCParameters, blockNumber *big.Int, bountyHunter string) (uint32, error) { + fromBlock, err := razorUtils.EstimateBlockNumberAtEpochBeginning(rpcParameters, blockNumber) if err != nil { log.Error(err) return 0, err @@ -561,7 +594,7 @@ func (*UtilsStruct) GetBountyIdFromEvents(ctx context.Context, client *ethclient }, } log.Debugf("GetBountyIdFromEvents: Query to send in filter logs: %+v", query) - logs, err := clientUtils.FilterLogsWithRetry(ctx, client, query) + logs, err := clientUtils.FilterLogsWithRetry(rpcParameters, query) if err != nil { return 0, err } @@ -589,10 +622,9 @@ func (*UtilsStruct) GetBountyIdFromEvents(ctx context.Context, client *ethclient return bountyId, nil } -func (*UtilsStruct) CheckToDoResetDispute(client *ethclient.Client, blockManager *bindings.BlockManager, txnOpts *bind.TransactOpts, epoch uint32, sortedValues []*big.Int) { +func (*UtilsStruct) CheckToDoResetDispute(rpcParameters rpc.RPCParameters, txnOpts *bind.TransactOpts, epoch uint32, sortedValues []*big.Int) { // Fetch updated dispute mapping - callOpts := razorUtils.GetOptions() - disputesMapping, err := blockManagerUtils.Disputes(client, &callOpts, epoch, txnOpts.From) + disputesMapping, err := razorUtils.Disputes(rpcParameters, epoch, txnOpts.From) if err != nil { log.Error("Error in getting disputes mapping: ", disputesMapping) return @@ -602,6 +634,6 @@ func (*UtilsStruct) CheckToDoResetDispute(client *ethclient.Client, blockManager //Checking whether LVV is equal to maximum value in sortedValues, if not equal resetting dispute if disputesMapping.LastVisitedValue.Cmp(big.NewInt(0)) != 0 && disputesMapping.LastVisitedValue.Cmp(sortedValues[len(sortedValues)-1]) != 0 { log.Debug("CheckToDoResetDispute: Calling Reset Dispute with arguments epoch = ", epoch) - cmdUtils.ResetDispute(client, blockManager, txnOpts, epoch) + cmdUtils.ResetDispute(rpcParameters, txnOpts, epoch) } } diff --git a/cmd/dispute_test.go b/cmd/dispute_test.go index 504e0dc0f..2778513d0 100644 --- a/cmd/dispute_test.go +++ b/cmd/dispute_test.go @@ -1,7 +1,6 @@ package cmd import ( - "context" "crypto/ecdsa" "crypto/rand" "errors" @@ -18,13 +17,11 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" Types "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethclient" "github.com/stretchr/testify/mock" ) func TestDispute(t *testing.T) { var ( - client *ethclient.Client config types.Configurations account types.Account epoch uint32 @@ -95,18 +92,18 @@ func TestDispute(t *testing.T) { utilsMock.On("GetBlockManager", mock.AnythingOfType("*ethclient.Client")).Return(blockManager) utilsMock.On("GetTxnOpts", mock.Anything, mock.AnythingOfType("types.TransactionOptions")).Return(TxnOpts) - cmdUtilsMock.On("GiveSorted", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil) - cmdUtilsMock.On("GetCollectionIdPositionInBlock", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.positionOfCollectionInBlock) + cmdUtilsMock.On("GiveSorted", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil) + cmdUtilsMock.On("GetCollectionIdPositionInBlock", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.positionOfCollectionInBlock) blockManagerMock.On("FinalizeDispute", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.finalizeDisputeTxn, tt.args.finalizeDisputeErr) transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) - cmdUtilsMock.On("StoreBountyId", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.storeBountyIdErr) - utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) + cmdUtilsMock.On("StoreBountyId", mock.Anything, mock.Anything).Return(tt.args.storeBountyIdErr) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) cmdUtilsMock.On("CheckToDoResetDispute", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return() - cmdUtilsMock.On("ResetDispute", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything) + cmdUtilsMock.On("ResetDispute", mock.Anything, mock.Anything, mock.Anything) utils := &UtilsStruct{} - err := utils.Dispute(context.Background(), client, config, account, epoch, blockIndex, proposedBlock, leafId, tt.args.sortedValues) + err := utils.Dispute(rpcParameters, config, account, epoch, blockIndex, proposedBlock, leafId, tt.args.sortedValues) if err == nil || tt.want == nil { if err != tt.want { t.Errorf("Error for Dispute function, got = %v, want = %v", err, tt.want) @@ -124,7 +121,6 @@ func TestHandleDispute(t *testing.T) { privateKey, _ := ecdsa.GenerateKey(crypto.S256(), rand.Reader) txnOpts, _ := bind.NewKeyedTransactorWithChainID(privateKey, big.NewInt(31337)) - var client *ethclient.Client var config types.Configurations var account types.Account var epoch uint32 @@ -525,27 +521,27 @@ func TestHandleDispute(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetSortedProposedBlockIds", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.sortedProposedBlockIds, tt.args.sortedProposedBlockIdsErr) - cmdUtilsMock.On("GetBiggestStakeAndId", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.biggestStake, tt.args.biggestStakeId, tt.args.biggestStakeErr) - cmdUtilsMock.On("GetLocalMediansData", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(types.ProposeFileData{ + utilsMock.On("GetSortedProposedBlockIds", mock.Anything, mock.Anything).Return(tt.args.sortedProposedBlockIds, tt.args.sortedProposedBlockIdsErr) + cmdUtilsMock.On("GetBiggestStakeAndId", mock.Anything, mock.Anything).Return(tt.args.biggestStake, tt.args.biggestStakeId, tt.args.biggestStakeErr) + cmdUtilsMock.On("GetLocalMediansData", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(types.ProposeFileData{ MediansData: tt.args.medians, RevealedCollectionIds: tt.args.revealedCollectionIds, RevealedDataMaps: tt.args.revealedDataMaps, }, tt.args.mediansErr) - utilsMock.On("GetProposedBlock", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.proposedBlock, tt.args.proposedBlockErr) + utilsMock.On("GetProposedBlock", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.proposedBlock, tt.args.proposedBlockErr) utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(txnOpts) blockManagerMock.On("DisputeBiggestStakeProposed", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.disputeBiggestStakeTxn, tt.args.disputeBiggestStakeErr) transactionMock.On("Hash", mock.Anything).Return(tt.args.Hash) - utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) - cmdUtilsMock.On("CheckDisputeForIds", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.idDisputeTxn, tt.args.idDisputeTxnErr) - utilsMock.On("GetLeafIdOfACollection", mock.Anything, mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.leafId, tt.args.leafIdErr) - cmdUtilsMock.On("Dispute", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.disputeErr) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) + cmdUtilsMock.On("CheckDisputeForIds", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.idDisputeTxn, tt.args.idDisputeTxnErr) + utilsMock.On("GetLeafIdOfACollection", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.leafId, tt.args.leafIdErr) + cmdUtilsMock.On("Dispute", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.disputeErr) utilsMock.On("GetBlockManager", mock.AnythingOfType("*ethclient.Client")).Return(blockManager) - cmdUtilsMock.On("StoreBountyId", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.storeBountyIdErr) - cmdUtilsMock.On("ResetDispute", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything) + cmdUtilsMock.On("StoreBountyId", mock.Anything, mock.Anything).Return(tt.args.storeBountyIdErr) + cmdUtilsMock.On("ResetDispute", mock.Anything, mock.Anything, mock.Anything) utils := &UtilsStruct{} - err := utils.HandleDispute(context.Background(), client, config, account, epoch, blockNumber, rogueData, backupNodeActionsToIgnore) + err := utils.HandleDispute(rpcParameters, config, account, epoch, blockNumber, rogueData, backupNodeActionsToIgnore) if err == nil || tt.want == nil { if err != tt.want { t.Errorf("Error for HandleDispute function, got = %v, want = %v", err, tt.want) @@ -569,8 +565,6 @@ func TestGiveSorted(t *testing.T) { AccWeight: big.NewInt(0), } - var client *ethclient.Client - var blockManager *bindings.BlockManager var txnArgs types.TransactionOptions var epoch uint32 var callOpts bind.CallOpts @@ -660,14 +654,14 @@ func TestGiveSorted(t *testing.T) { blockManagerMock.On("GiveSorted", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.giveSorted, tt.args.giveSortedErr).Once() transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) - utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.waitForBlockCompletionErr) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(tt.args.waitForBlockCompletionErr) utilsMock.On("GetOptions").Return(callOpts) - blockManagerMock.On("Disputes", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.disputesMapping, tt.args.disputesMappingErr) + utilsMock.On("Disputes", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.disputesMapping, tt.args.disputesMappingErr) utilsMock.On("GetTxnOpts", mock.Anything, mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) blockManagerMock.On("GiveSorted", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.giveSorted, nil) - cmdUtilsMock.On("ResetDispute", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything) + cmdUtilsMock.On("ResetDispute", mock.Anything, mock.Anything, mock.Anything) - err := GiveSorted(context.Background(), client, blockManager, txnArgs, epoch, tt.args.leafId, tt.args.sortedValues) + err := GiveSorted(rpcParameters, txnArgs, epoch, tt.args.leafId, tt.args.sortedValues) if (err != nil) != tt.wantErr { t.Errorf("CheckDisputeForIds() error = %v, wantErr %v", err, tt.wantErr) return @@ -678,7 +672,6 @@ func TestGiveSorted(t *testing.T) { func TestGetLocalMediansData(t *testing.T) { var ( - client *ethclient.Client account types.Account blockNumber *big.Int ) @@ -795,10 +788,10 @@ func TestGetLocalMediansData(t *testing.T) { pathMock.On("GetProposeDataFileName", mock.AnythingOfType("string")).Return(tt.args.fileName, tt.args.fileNameErr) fileUtilsMock.On("ReadFromProposeJsonFile", mock.Anything).Return(tt.args.proposedData, tt.args.proposeDataErr) - cmdUtilsMock.On("MakeBlock", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.medians, tt.args.revealedCollectionIds, tt.args.revealedDataMaps, tt.args.mediansErr) - utilsMock.On("GetStakerId", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) + cmdUtilsMock.On("MakeBlock", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.medians, tt.args.revealedCollectionIds, tt.args.revealedDataMaps, tt.args.mediansErr) + utilsMock.On("GetStakerId", mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) ut := &UtilsStruct{} - localProposedData, err := ut.GetLocalMediansData(context.Background(), client, account, tt.args.epoch, blockNumber, types.Rogue{IsRogue: tt.args.isRogue}) + localProposedData, err := ut.GetLocalMediansData(rpcParameters, account, tt.args.epoch, blockNumber, types.Rogue{IsRogue: tt.args.isRogue}) if (err != nil) != tt.wantErr { t.Errorf("GetLocalMediansData() error = %v, wantErr %v", err, tt.wantErr) return @@ -817,7 +810,6 @@ func TestGetLocalMediansData(t *testing.T) { } func TestGetCollectionIdPositionInBlock(t *testing.T) { - var client *ethclient.Client var leafId uint16 type args struct { proposedBlock bindings.StructsBlock @@ -864,9 +856,9 @@ func TestGetCollectionIdPositionInBlock(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetCollectionIdFromLeafId", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.idToBeDisputed, tt.args.idToBeDisputedErr) + utilsMock.On("GetCollectionIdFromLeafId", mock.Anything, mock.Anything).Return(tt.args.idToBeDisputed, tt.args.idToBeDisputedErr) ut := &UtilsStruct{} - if got := ut.GetCollectionIdPositionInBlock(context.Background(), client, leafId, tt.args.proposedBlock); !reflect.DeepEqual(got, tt.want) { + if got := ut.GetCollectionIdPositionInBlock(rpcParameters, leafId, tt.args.proposedBlock); !reflect.DeepEqual(got, tt.want) { t.Errorf("GetCollectionIdPositionInBlock() = %v, want %v", got, tt.want) } }) @@ -875,7 +867,6 @@ func TestGetCollectionIdPositionInBlock(t *testing.T) { func TestCheckDisputeForIds(t *testing.T) { var ( - client *ethclient.Client transactionOpts types.TransactionOptions epoch uint32 blockIndex uint8 @@ -969,12 +960,12 @@ func TestCheckDisputeForIds(t *testing.T) { utilsMock.On("GetTxnOpts", mock.Anything, mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) blockManagerMock.On("DisputeOnOrderOfIds", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.DisputeOnOrderOfIds, tt.args.DisputeOnOrderOfIdsErr) - gasUtilsMock.On("IncreaseGasLimitValue", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.incrementedGasLimit, tt.args.incrementedGasLimitErr) + gasUtilsMock.On("IncreaseGasLimitValue", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.incrementedGasLimit, tt.args.incrementedGasLimitErr) blockManagerMock.On("DisputeCollectionIdShouldBePresent", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.DisputeCollectionIdShouldBePresent, tt.args.DisputeCollectionIdShouldBePresentErr) blockManagerMock.On("DisputeCollectionIdShouldBeAbsent", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.DisputeCollectionIdShouldBeAbsent, tt.args.DisputeCollectionIdShouldBeAbsentErr) - gasUtilsMock.On("IncreaseGasLimitValue", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(uint64(2000), nil) + gasUtilsMock.On("IncreaseGasLimitValue", mock.Anything, mock.Anything, mock.Anything).Return(uint64(2000), nil) ut := &UtilsStruct{} - got, err := ut.CheckDisputeForIds(context.Background(), client, transactionOpts, epoch, blockIndex, tt.args.idsInProposedBlock, tt.args.revealedCollectionIds) + got, err := ut.CheckDisputeForIds(rpcParameters, transactionOpts, epoch, blockIndex, tt.args.idsInProposedBlock, tt.args.revealedCollectionIds) if (err != nil) != tt.wantErr { t.Errorf("CheckDisputeForIds() error = %v, wantErr %v", err, tt.wantErr) return @@ -988,7 +979,6 @@ func TestCheckDisputeForIds(t *testing.T) { func TestGetBountyIdFromEvents(t *testing.T) { var ( - client *ethclient.Client blockNumber *big.Int bountyHunter string ) @@ -1075,12 +1065,12 @@ func TestGetBountyIdFromEvents(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("EstimateBlockNumberAtEpochBeginning", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.fromBlock, tt.args.fromBlockErr) + utilsMock.On("EstimateBlockNumberAtEpochBeginning", mock.Anything, mock.Anything).Return(tt.args.fromBlock, tt.args.fromBlockErr) abiUtilsMock.On("Parse", mock.Anything).Return(tt.args.contractABI, tt.args.contractABIErr) - clientUtilsMock.On("FilterLogsWithRetry", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.logs, tt.args.logsErr) + clientUtilsMock.On("FilterLogsWithRetry", mock.Anything, mock.Anything).Return(tt.args.logs, tt.args.logsErr) abiMock.On("Unpack", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.data, tt.args.unpackErr) ut := &UtilsStruct{} - got, err := ut.GetBountyIdFromEvents(context.Background(), client, blockNumber, bountyHunter) + got, err := ut.GetBountyIdFromEvents(rpcParameters, blockNumber, bountyHunter) if (err != nil) != tt.wantErr { t.Errorf("GetBountyIdFromEvents() error = %v, wantErr %v", err, tt.wantErr) return @@ -1094,10 +1084,8 @@ func TestGetBountyIdFromEvents(t *testing.T) { func TestResetDispute(t *testing.T) { var ( - client *ethclient.Client - blockManager *bindings.BlockManager - txnOpts *bind.TransactOpts - epoch uint32 + txnOpts *bind.TransactOpts + epoch uint32 ) type args struct { ResetDisputeTxn *Types.Transaction @@ -1128,16 +1116,15 @@ func TestResetDispute(t *testing.T) { blockManagerMock.On("ResetDispute", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.ResetDisputeTxn, tt.args.ResetDisputeTxnErr) transactionMock.On("Hash", mock.AnythingOfType("*types.Transaction")).Return(tt.args.hash) - utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) ut := &UtilsStruct{} - ut.ResetDispute(client, blockManager, txnOpts, epoch) + ut.ResetDispute(rpcParameters, txnOpts, epoch) }) } } func BenchmarkGetCollectionIdPositionInBlock(b *testing.B) { - var client *ethclient.Client var leafId uint16 var table = []struct { numOfIds uint16 @@ -1155,7 +1142,7 @@ func BenchmarkGetCollectionIdPositionInBlock(b *testing.B) { utilsMock.On("GetCollectionIdFromLeafId", mock.Anything, mock.Anything, mock.Anything).Return(v.idToBeDisputed, nil) ut := &UtilsStruct{} - ut.GetCollectionIdPositionInBlock(context.Background(), client, leafId, bindings.StructsBlock{Ids: getDummyIds(v.numOfIds)}) + ut.GetCollectionIdPositionInBlock(rpcParameters, leafId, bindings.StructsBlock{Ids: getDummyIds(v.numOfIds)}) } }) } @@ -1165,7 +1152,6 @@ func BenchmarkHandleDispute(b *testing.B) { privateKey, _ := ecdsa.GenerateKey(crypto.S256(), rand.Reader) txnOpts, _ := bind.NewKeyedTransactorWithChainID(privateKey, big.NewInt(31337)) - var client *ethclient.Client var config types.Configurations var account types.Account var epoch uint32 @@ -1203,22 +1189,22 @@ func BenchmarkHandleDispute(b *testing.B) { Valid: true, BiggestStake: big.NewInt(1).Mul(big.NewInt(5356), big.NewInt(1e18))} - utilsMock.On("GetSortedProposedBlockIds", mock.Anything, mock.Anything, mock.Anything).Return(getUint32DummyIds(v.numOfSortedBlocks), nil) - cmdUtilsMock.On("GetBiggestStakeAndId", mock.Anything, mock.Anything, mock.Anything).Return(big.NewInt(1).Mul(big.NewInt(5356), big.NewInt(1e18)), uint32(2), nil) + utilsMock.On("GetSortedProposedBlockIds", mock.Anything, mock.Anything).Return(getUint32DummyIds(v.numOfSortedBlocks), nil) + cmdUtilsMock.On("GetBiggestStakeAndId", mock.Anything, mock.Anything).Return(big.NewInt(1).Mul(big.NewInt(5356), big.NewInt(1e18)), uint32(2), nil) cmdUtilsMock.On("GetLocalMediansData", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(proposedData, nil) - utilsMock.On("GetProposedBlock", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(proposedBlock, nil) + utilsMock.On("GetProposedBlock", mock.Anything, mock.Anything, mock.Anything).Return(proposedBlock, nil) utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(txnOpts) blockManagerMock.On("DisputeBiggestStakeProposed", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&Types.Transaction{}, nil) transactionMock.On("Hash", mock.Anything).Return(common.BigToHash(big.NewInt(1))) - utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) cmdUtilsMock.On("CheckDisputeForIds", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&Types.Transaction{}, nil) - utilsMock.On("GetLeafIdOfACollection", mock.Anything, mock.Anything, mock.Anything).Return(0, nil) - cmdUtilsMock.On("Dispute", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil) + utilsMock.On("GetLeafIdOfACollection", mock.Anything, mock.Anything).Return(0, nil) + cmdUtilsMock.On("Dispute", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil) utilsMock.On("GetBlockManager", mock.AnythingOfType("*ethclient.Client")).Return(blockManager) - cmdUtilsMock.On("StoreBountyId", mock.Anything, mock.Anything, mock.Anything).Return(nil) + cmdUtilsMock.On("StoreBountyId", mock.Anything, mock.Anything).Return(nil) utils := &UtilsStruct{} - err := utils.HandleDispute(context.Background(), client, config, account, epoch, blockNumber, rogueData, backupNodeActionsToIgnore) + err := utils.HandleDispute(rpcParameters, config, account, epoch, blockNumber, rogueData, backupNodeActionsToIgnore) if err != nil { log.Fatal(err) } @@ -1230,7 +1216,6 @@ func BenchmarkHandleDispute(b *testing.B) { func TestStoreBountyId(t *testing.T) { var ( - client *ethclient.Client account types.Account fileInfo fs.FileInfo ) @@ -1335,14 +1320,14 @@ func TestStoreBountyId(t *testing.T) { SetUpMockInterfaces() pathMock.On("GetDisputeDataFileName", mock.AnythingOfType("string")).Return(tt.args.disputeFilePath, tt.args.disputeFilePathErr) - clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything, mock.Anything).Return(tt.args.latestHeader, tt.args.latestHeaderErr) + clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything).Return(tt.args.latestHeader, tt.args.latestHeaderErr) cmdUtilsMock.On("GetBountyIdFromEvents", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.latestBountyId, tt.args.latestBountyIdErr) osPathMock.On("Stat", mock.Anything).Return(fileInfo, tt.args.statErr) fileUtilsMock.On("ReadFromDisputeJsonFile", mock.Anything).Return(tt.args.disputeData, tt.args.disputeDataErr) fileUtilsMock.On("SaveDataToDisputeJsonFile", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.saveDataErr) ut := &UtilsStruct{} - if err := ut.StoreBountyId(context.Background(), client, account); (err != nil) != tt.wantErr { + if err := ut.StoreBountyId(rpcParameters, account); (err != nil) != tt.wantErr { t.Errorf("AutoClaimBounty() error = %v, wantErr %v", err, tt.wantErr) } }) diff --git a/cmd/eventListeners.go b/cmd/eventListeners.go index 268e03169..0c76c07d7 100644 --- a/cmd/eventListeners.go +++ b/cmd/eventListeners.go @@ -1,23 +1,22 @@ package cmd import ( - "context" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" Types "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethclient" "math/big" "razor/cache" "razor/core" "razor/core/types" "razor/pkg/bindings" + "razor/rpc" "razor/utils" "strings" ) -func (*UtilsStruct) InitJobAndCollectionCache(ctx context.Context, client *ethclient.Client) (*cache.JobsCache, *cache.CollectionsCache, *big.Int, error) { - initAssetCacheBlock, err := clientUtils.GetLatestBlockWithRetry(ctx, client) +func (*UtilsStruct) InitJobAndCollectionCache(rpcParameters rpc.RPCParameters) (*cache.JobsCache, *cache.CollectionsCache, *big.Int, error) { + initAssetCacheBlock, err := clientUtils.GetLatestBlockWithRetry(rpcParameters) if err != nil { log.Error("Error in fetching block: ", err) return nil, nil, nil, err @@ -31,11 +30,11 @@ func (*UtilsStruct) InitJobAndCollectionCache(ctx context.Context, client *ethcl collectionsCache := cache.NewCollectionsCache() // Initialize caches - if err := utils.InitJobsCache(ctx, client, jobsCache); err != nil { + if err := utils.InitJobsCache(rpcParameters, jobsCache); err != nil { log.Error("Error in initializing jobs cache: ", err) return nil, nil, nil, err } - if err := utils.InitCollectionsCache(client, collectionsCache); err != nil { + if err := utils.InitCollectionsCache(rpcParameters, collectionsCache); err != nil { log.Error("Error in initializing collections cache: ", err) return nil, nil, nil, err } @@ -44,7 +43,7 @@ func (*UtilsStruct) InitJobAndCollectionCache(ctx context.Context, client *ethcl } // CheckForJobAndCollectionEvents checks for specific job and collections event that were emitted. -func CheckForJobAndCollectionEvents(ctx context.Context, client *ethclient.Client, commitParams *types.CommitParams) error { +func CheckForJobAndCollectionEvents(rpcParameters rpc.RPCParameters, commitParams *types.CommitParams) error { collectionManagerContractABI, err := abi.JSON(strings.NewReader(bindings.CollectionManagerMetaData.ABI)) if err != nil { log.Errorf("Error in parsing collection manager contract ABI: %v", err) @@ -54,14 +53,14 @@ func CheckForJobAndCollectionEvents(ctx context.Context, client *ethclient.Clien eventNames := []string{core.JobUpdatedEvent, core.CollectionUpdatedEvent, core.CollectionActivityStatusEvent, core.JobCreatedEvent, core.CollectionCreatedEvent} log.Debug("Checking for Job/Collection update events...") - toBlock, err := clientUtils.GetLatestBlockWithRetry(ctx, client) + toBlock, err := clientUtils.GetLatestBlockWithRetry(rpcParameters) if err != nil { log.Error("Error in getting latest block to start event listener: ", err) return err } // Process events and update the fromBlock for the next iteration - newFromBlock, err := processEvents(ctx, client, collectionManagerContractABI, commitParams.FromBlockToCheckForEvents, toBlock.Number, eventNames, commitParams.JobsCache, commitParams.CollectionsCache) + newFromBlock, err := processEvents(rpcParameters, collectionManagerContractABI, commitParams.FromBlockToCheckForEvents, toBlock.Number, eventNames, commitParams.JobsCache, commitParams.CollectionsCache) if err != nil { return err } @@ -73,8 +72,8 @@ func CheckForJobAndCollectionEvents(ctx context.Context, client *ethclient.Clien } // processEvents fetches and processes logs for multiple event types. -func processEvents(ctx context.Context, client *ethclient.Client, contractABI abi.ABI, fromBlock, toBlock *big.Int, eventNames []string, jobsCache *cache.JobsCache, collectionsCache *cache.CollectionsCache) (*big.Int, error) { - logs, err := getEventLogs(ctx, client, fromBlock, toBlock) +func processEvents(rpcParameters rpc.RPCParameters, contractABI abi.ABI, fromBlock, toBlock *big.Int, eventNames []string, jobsCache *cache.JobsCache, collectionsCache *cache.CollectionsCache) (*big.Int, error) { + logs, err := getEventLogs(rpcParameters, fromBlock, toBlock) if err != nil { log.Errorf("Failed to fetch logs: %v", err) return nil, err @@ -87,7 +86,7 @@ func processEvents(ctx context.Context, client *ethclient.Client, contractABI ab switch eventName { case core.JobUpdatedEvent, core.JobCreatedEvent: jobId := utils.ConvertHashToUint16(vLog.Topics[1]) - updatedJob, err := utils.UtilsInterface.GetActiveJob(ctx, client, jobId) + updatedJob, err := razorUtils.GetActiveJob(rpcParameters, jobId) if err != nil { log.Errorf("Error in getting job with job Id %v: %v", jobId, err) continue @@ -96,7 +95,7 @@ func processEvents(ctx context.Context, client *ethclient.Client, contractABI ab jobsCache.UpdateJob(jobId, updatedJob) case core.CollectionUpdatedEvent, core.CollectionCreatedEvent, core.CollectionActivityStatusEvent: collectionId := utils.ConvertHashToUint16(vLog.Topics[1]) - newCollection, err := utils.UtilsInterface.GetCollection(ctx, client, collectionId) + newCollection, err := razorUtils.GetCollection(rpcParameters, collectionId) if err != nil { log.Errorf("Error in getting collection with collection Id %v: %v", collectionId, err) continue @@ -113,7 +112,7 @@ func processEvents(ctx context.Context, client *ethclient.Client, contractABI ab } // getEventLogs is a utility function to fetch the event logs -func getEventLogs(ctx context.Context, client *ethclient.Client, fromBlock *big.Int, toBlock *big.Int) ([]Types.Log, error) { +func getEventLogs(rpcParameters rpc.RPCParameters, fromBlock *big.Int, toBlock *big.Int) ([]Types.Log, error) { log.Debugf("Checking for events from block %v to block %v...", fromBlock, toBlock) // Set up the query for filtering logs @@ -126,7 +125,7 @@ func getEventLogs(ctx context.Context, client *ethclient.Client, fromBlock *big. } // Retrieve the logs - logs, err := clientUtils.FilterLogsWithRetry(ctx, client, query) + logs, err := clientUtils.FilterLogsWithRetry(rpcParameters, query) if err != nil { log.Errorf("Error in filter logs: %v", err) return []Types.Log{}, err diff --git a/cmd/import.go b/cmd/import.go index 218655209..ddb722ffb 100644 --- a/cmd/import.go +++ b/cmd/import.go @@ -29,10 +29,8 @@ func initialiseImport(cmd *cobra.Command, args []string) { //This function sets the flags appropriately and executes the ImportAccount function func (*UtilsStruct) ExecuteImport(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - log.Debug("Checking to assign log file...") - fileUtils.AssignLogFile(flagSet, config) + _, _, _, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) log.Debug("Calling ImportAccount()...") account, err := cmdUtils.ImportAccount() utils.CheckError("Import error: ", err) diff --git a/cmd/importEndpoints.go b/cmd/importEndpoints.go new file mode 100644 index 000000000..040cf5375 --- /dev/null +++ b/cmd/importEndpoints.go @@ -0,0 +1,47 @@ +package cmd + +import ( + "encoding/json" + "github.com/spf13/cobra" + "os" + "path/filepath" + "razor/core" + "razor/utils" +) + +// importEndpointsCmd represents the importEndpoints command +var importEndpointsCmd = &cobra.Command{ + Use: "importEndpoints", + Short: "imports the list of endpoints locally", + Long: `Imports the list of endpoints to $HOME/.rzr directory allowing the user to access/edit it easily. +Example: + ./razor importEndpoints `, + Run: initialiseImportEndpoints, +} + +func initialiseImportEndpoints(cmd *cobra.Command, args []string) { + cmdUtils.ExecuteImportEndpoints() +} + +// ExecuteImportEndpoints imports the list of endpoints from core/endpoints.go to $HOME/.razor directory locally. +func (*UtilsStruct) ExecuteImportEndpoints() { + defaultPath, err := pathUtils.GetDefaultPath() + utils.CheckError("Error in getting default path: ", err) + + // Define the target path for endpoints.json + destFilePath := filepath.Join(defaultPath, "endpoints.json") + + // Serialize the default endpoints to JSON + endpointsData, err := json.MarshalIndent(core.DefaultEndpoints, "", " ") + utils.CheckError("Error in serializing the endpoints: %w", err) + + // Write the JSON to the destination file + err = os.WriteFile(destFilePath, endpointsData, 0644) + utils.CheckError("Error in writing endpoints.json: %w", err) + + log.Infof("Default endpoints successfully imported to %s", destFilePath) +} + +func init() { + rootCmd.AddCommand(importEndpointsCmd) +} diff --git a/cmd/importEndpoints_test.go b/cmd/importEndpoints_test.go new file mode 100644 index 000000000..6a85db8ad --- /dev/null +++ b/cmd/importEndpoints_test.go @@ -0,0 +1,52 @@ +package cmd + +import ( + "encoding/json" + "github.com/stretchr/testify/assert" + "os" + "path/filepath" + "razor/core" + "testing" +) + +func TestExecuteImportEndpoints_WithMockedPath(t *testing.T) { + // Create a temporary directory to mock the default path + tempDir, err := os.MkdirTemp("", "test_default_path") + assert.NoError(t, err, "Temporary directory should be created") + defer os.RemoveAll(tempDir) // Clean up after the test + + SetUpMockInterfaces() + + pathMock.On("GetDefaultPath").Return(tempDir, nil) + + // Call ExecuteImportEndpoints + utils := &UtilsStruct{} + utils.ExecuteImportEndpoints() + + // Verify the file was created in the mocked directory + destFilePath := filepath.Join(tempDir, "endpoints.json") + _, err = os.Stat(destFilePath) + assert.NoError(t, err, "endpoints.json should be created in the mocked directory") + + // Verify the content of the file matches core.DefaultEndpoints + data, err := os.ReadFile(destFilePath) + assert.NoError(t, err, "File should be readable") + + var importedEndpoints []string + err = json.Unmarshal(data, &importedEndpoints) + assert.NoError(t, err, "JSON should be valid") + assert.Equal(t, core.DefaultEndpoints, importedEndpoints, "Imported endpoints should match the defaults") + + // Delete the file after verification + err = os.Remove(destFilePath) + assert.NoError(t, err, "endpoints.json should be deleted successfully") + + // Verify logs + log.Infof("Default endpoints successfully imported to %s", destFilePath) + pathMock.AssertExpectations(t) + + // Confirm the file no longer exists + _, err = os.Stat(destFilePath) + assert.Error(t, err, "endpoints.json should not exist after deletion") + assert.True(t, os.IsNotExist(err), "Error should indicate file does not exist") +} diff --git a/cmd/import_test.go b/cmd/import_test.go index 89b18df31..df095d973 100644 --- a/cmd/import_test.go +++ b/cmd/import_test.go @@ -208,14 +208,16 @@ func TestExecuteImport(t *testing.T) { expectedFatal: true, }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() + setupTestEndpointsEnvironment() + utilsMock.On("IsFlagPassed", mock.Anything).Return(false) fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("ImportAccount").Return(tt.args.account, tt.args.accountErr) cmdUtilsMock.On("GetConfigData").Return(types.Configurations{}, nil) diff --git a/cmd/initTestMocks_test.go b/cmd/initTestMocks_test.go index f85f76db0..b00ecb3bb 100644 --- a/cmd/initTestMocks_test.go +++ b/cmd/initTestMocks_test.go @@ -8,12 +8,16 @@ import ( "github.com/avast/retry-go" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/ethclient" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "math/big" + "os" + "path/filepath" "razor/cmd/mocks" "razor/path" pathPkgMocks "razor/path/mocks" + "razor/rpc" "razor/utils" utilsPkgMocks "razor/utils/mocks" "strings" @@ -168,6 +172,7 @@ func SetUpMockInterfaces() { pathMock = new(pathPkgMocks.PathInterface) pathUtils = pathMock + path.PathUtilsInterface = pathMock osPathMock = new(pathPkgMocks.OSInterface) path.OSUtilsInterface = osPathMock @@ -176,6 +181,16 @@ func SetUpMockInterfaces() { var privateKey, _ = ecdsa.GenerateKey(crypto.S256(), rand.Reader) var TxnOpts, _ = bind.NewKeyedTransactorWithChainID(privateKey, big.NewInt(31000)) // Used any random big int for chain ID +var rpcManager = rpc.RPCManager{ + BestEndpoint: &rpc.RPCEndpoint{ + Client: ðclient.Client{}, + }, +} +var rpcParameters = rpc.RPCParameters{ + Ctx: context.Background(), + RPCManager: &rpcManager, +} + func TestInvokeFunctionWithRetryAttempts(t *testing.T) { tests := []struct { name string @@ -215,7 +230,12 @@ func TestInvokeFunctionWithRetryAttempts(t *testing.T) { SetUpMockInterfaces() retryUtilsMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(4)) - returnedValues, err := utils.InvokeFunctionWithRetryAttempts(ctx, dummyRPC, tt.methodName) + localRPCParameters := rpc.RPCParameters{ + Ctx: ctx, + RPCManager: &rpcManager, + } + returnedValues, err := utils.InvokeFunctionWithRetryAttempts(localRPCParameters, dummyRPC, tt.methodName) + fmt.Println("Error: ", err) if tt.expectError { assert.Error(t, err) @@ -236,14 +256,30 @@ func TestInvokeFunctionWithRetryAttempts(t *testing.T) { // Dummy interface with methods type DummyRPC struct{} -// A fast method that simulates successful execution -func (d *DummyRPC) FastMethod() error { +// A fast method that simulates successful execution, added client as the parameter because generic retry functions expects client as the first parameter +func (d *DummyRPC) FastMethod(client *ethclient.Client) error { return nil } -// A slow method that simulates a long-running process -func (d *DummyRPC) SlowMethod() error { +// A slow method that simulates a long-running process, added client as the parameter because generic retry functions expects client as the first parameter +func (d *DummyRPC) SlowMethod(client *ethclient.Client) error { fmt.Println("Sleeping...") time.Sleep(3 * time.Second) // Simulate delay to trigger timeout return nil } + +func setupTestEndpointsEnvironment() { + var testDir = "/tmp/test_rzr" + pathMock.On("GetDefaultPath").Return(testDir, nil) + err := os.MkdirAll(testDir, 0755) + if err != nil { + log.Fatalf("failed to create test directory: %s", err.Error()) + } + + mockEndpoints := `["https://testnet.skalenodes.com/v1/juicy-low-small-testnet"]` + mockFilePath := filepath.Join(testDir, "endpoints.json") + err = os.WriteFile(mockFilePath, []byte(mockEndpoints), 0644) + if err != nil { + log.Fatalf("failed to write mock endpoints.json: %s", err.Error()) + } +} diff --git a/cmd/initiateWithdraw.go b/cmd/initiateWithdraw.go index 30a426499..cf53823b5 100644 --- a/cmd/initiateWithdraw.go +++ b/cmd/initiateWithdraw.go @@ -2,19 +2,16 @@ package cmd import ( - "context" "errors" "math/big" - "razor/accounts" "razor/core" "razor/core/types" - "razor/logger" "razor/pkg/bindings" + "razor/rpc" "razor/utils" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/cobra" "github.com/spf13/pflag" ) @@ -34,49 +31,26 @@ Example: //This function sets the flags appropriately and executes the InitiateWithdraw function func (*UtilsStruct) ExecuteInitiateWithdraw(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - log.Debugf("ExecuteInitiateWithdraw: Config: %+v: ", config) + config, rpcParameters, account, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) - client := razorUtils.ConnectToClient(config.Provider) - - address, err := flagSetUtils.GetStringAddress(flagSet) - utils.CheckError("Error in getting address: ", err) - log.Debug("ExecuteInitiateWithdraw: Address: ", address) - - logger.SetLoggerParameters(client, address) - - log.Debug("Checking to assign log file...") - fileUtils.AssignLogFile(flagSet, config) - - log.Debug("Getting password...") - password := razorUtils.AssignPassword(flagSet) - - accountManager, err := razorUtils.AccountManagerForKeystore() - utils.CheckError("Error in getting accounts manager for keystore: ", err) - - account := accounts.InitAccountStruct(address, password, accountManager) - - err = razorUtils.CheckPassword(account) - utils.CheckError("Error in fetching private key from given password: ", err) - - stakerId, err := razorUtils.AssignStakerId(context.Background(), flagSet, client, address) + stakerId, err := razorUtils.AssignStakerId(rpcParameters, flagSet, account.Address) utils.CheckError("Error in fetching stakerId: ", err) log.Debug("ExecuteInitiateWithdraw: Staker Id: ", stakerId) - log.Debugf("ExecuteInitiateWithdraw: Calling HandleUnstakeLock() with arguments account address: %s, stakerId: %d", address, stakerId) - txn, err := cmdUtils.HandleUnstakeLock(context.Background(), client, account, config, stakerId) + log.Debugf("ExecuteInitiateWithdraw: Calling HandleUnstakeLock() with arguments account address: %s, stakerId: %d", account.Address, stakerId) + txn, err := cmdUtils.HandleUnstakeLock(rpcParameters, account, config, stakerId) utils.CheckError("InitiateWithdraw error: ", err) if txn != core.NilHash { - err := razorUtils.WaitForBlockCompletion(client, txn.Hex()) + err := razorUtils.WaitForBlockCompletion(rpcParameters, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for initiateWithdraw: ", err) } } //This function handles the unstake lock -func (*UtilsStruct) HandleUnstakeLock(ctx context.Context, client *ethclient.Client, account types.Account, configurations types.Configurations, stakerId uint32) (common.Hash, error) { - unstakeLock, err := razorUtils.GetLock(ctx, client, account.Address, stakerId, 0) +func (*UtilsStruct) HandleUnstakeLock(rpcParameters rpc.RPCParameters, account types.Account, configurations types.Configurations, stakerId uint32) (common.Hash, error) { + unstakeLock, err := razorUtils.GetLock(rpcParameters, account.Address, stakerId, 0) if err != nil { log.Error("Error in fetching unstakeLock") return core.NilHash, err @@ -88,7 +62,7 @@ func (*UtilsStruct) HandleUnstakeLock(ctx context.Context, client *ethclient.Cli return core.NilHash, errors.New("unstake Razors before withdrawing") } - withdrawInitiationPeriod, err := razorUtils.GetWithdrawInitiationPeriod(ctx, client) + withdrawInitiationPeriod, err := razorUtils.GetWithdrawInitiationPeriod(rpcParameters) if err != nil { log.Error("Error in fetching withdraw release period") return core.NilHash, err @@ -97,7 +71,7 @@ func (*UtilsStruct) HandleUnstakeLock(ctx context.Context, client *ethclient.Cli withdrawBefore := big.NewInt(0).Add(unstakeLock.UnlockAfter, big.NewInt(int64(withdrawInitiationPeriod))) log.Debug("HandleUnstakeLock: Withdraw before epoch: ", withdrawBefore) - epoch, err := razorUtils.GetEpoch(ctx, client) + epoch, err := razorUtils.GetEpoch(rpcParameters) if err != nil { log.Error("Error in fetching epoch") return core.NilHash, err @@ -117,14 +91,13 @@ func (*UtilsStruct) HandleUnstakeLock(ctx context.Context, client *ethclient.Cli } log.Debug("Waiting for appropriate state to initiate withdraw...") - _, err = cmdUtils.WaitForAppropriateState(ctx, client, "initiateWithdraw", 0, 1, 4) + _, err = cmdUtils.WaitForAppropriateState(rpcParameters, "initiateWithdraw", 0, 1, 4) if err != nil { log.Error("Error in fetching state: ", err) return core.NilHash, err } txnArgs := types.TransactionOptions{ - Client: client, ChainId: core.ChainId, Config: configurations, ContractAddress: core.StakeManagerAddress, @@ -133,18 +106,24 @@ func (*UtilsStruct) HandleUnstakeLock(ctx context.Context, client *ethclient.Cli Parameters: []interface{}{stakerId}, Account: account, } - txnOpts := razorUtils.GetTxnOpts(ctx, txnArgs) + txnOpts := razorUtils.GetTxnOpts(rpcParameters, txnArgs) if big.NewInt(int64(epoch)).Cmp(unstakeLock.UnlockAfter) >= 0 && big.NewInt(int64(epoch)).Cmp(withdrawBefore) <= 0 { log.Debug("Calling InitiateWithdraw() with arguments stakerId: ", stakerId) - return cmdUtils.InitiateWithdraw(client, txnOpts, stakerId) + return cmdUtils.InitiateWithdraw(rpcParameters, txnOpts, stakerId) } return core.NilHash, errors.New("unstakeLock period not over yet! Please try after some time") } //This function initiate withdraw for your razors once you've unstaked -func (*UtilsStruct) InitiateWithdraw(client *ethclient.Client, txnOpts *bind.TransactOpts, stakerId uint32) (common.Hash, error) { +func (*UtilsStruct) InitiateWithdraw(rpcParameters rpc.RPCParameters, txnOpts *bind.TransactOpts, stakerId uint32) (common.Hash, error) { log.Info("Initiating withdrawal of funds...") + + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return core.NilHash, err + } + log.Debug("Executing InitiateWithdraw transaction for stakerId = ", stakerId) txn, err := stakeManagerUtils.InitiateWithdraw(client, txnOpts, stakerId) if err != nil { diff --git a/cmd/initiateWithdraw_test.go b/cmd/initiateWithdraw_test.go index 975aa810c..76df15db9 100644 --- a/cmd/initiateWithdraw_test.go +++ b/cmd/initiateWithdraw_test.go @@ -1,7 +1,6 @@ package cmd import ( - "context" "crypto/ecdsa" "crypto/rand" "errors" @@ -21,7 +20,6 @@ import ( ) func TestHandleUnstakeLock(t *testing.T) { - var client *ethclient.Client var account types.Account var configurations types.Configurations var stakerId uint32 @@ -180,16 +178,16 @@ func TestHandleUnstakeLock(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - cmdUtilsMock.On("WaitForAppropriateState", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.state, tt.args.stateErr) - utilsMock.On("GetLock", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.lock, tt.args.lockErr) + cmdUtilsMock.On("WaitForAppropriateState", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.state, tt.args.stateErr) + utilsMock.On("GetLock", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.lock, tt.args.lockErr) utilsMock.On("GetWithdrawInitiationPeriod", mock.Anything, mock.Anything).Return(tt.args.withdrawReleasePeriod, tt.args.withdrawReleasePeriodErr) - utilsMock.On("GetEpoch", mock.Anything, mock.Anything).Return(tt.args.epoch, tt.args.epochErr) + utilsMock.On("GetEpoch", mock.Anything).Return(tt.args.epoch, tt.args.epochErr) utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(TxnOpts) cmdUtilsMock.On("InitiateWithdraw", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.withdrawHash, tt.args.withdrawErr) utilsMock.On("SecondsToReadableTime", mock.AnythingOfType("int")).Return(tt.args.time) utils := &UtilsStruct{} - got, err := utils.HandleUnstakeLock(context.Background(), client, account, configurations, stakerId) + got, err := utils.HandleUnstakeLock(rpcParameters, account, configurations, stakerId) if got != tt.want { t.Errorf("Txn hash for withdrawFunds function, got = %v, want = %v", got, tt.want) } @@ -211,7 +209,6 @@ func TestWithdraw(t *testing.T) { privateKey, _ := ecdsa.GenerateKey(crypto.S256(), rand.Reader) txnOpts, _ := bind.NewKeyedTransactorWithChainID(privateKey, big.NewInt(1)) - var client *ethclient.Client var stakerId uint32 type args struct { @@ -254,7 +251,7 @@ func TestWithdraw(t *testing.T) { transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) utils := &UtilsStruct{} - got, err := utils.InitiateWithdraw(client, txnOpts, stakerId) + got, err := utils.InitiateWithdraw(rpcParameters, txnOpts, stakerId) if got != tt.want { t.Errorf("Txn hash for withdraw function, got = %v, want = %v", got, tt.want) } @@ -354,24 +351,26 @@ func TestExecuteWithdraw(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() + setupTestEndpointsEnvironment() + utilsMock.On("IsFlagPassed", mock.Anything).Return(true) fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) utilsMock.On("CheckPassword", mock.Anything).Return(nil) utilsMock.On("AccountManagerForKeystore").Return(&accounts.AccountManager{}, nil) flagSetMock.On("GetStringAddress", flagSet).Return(tt.args.address, tt.args.addressErr) - utilsMock.On("AssignStakerId", mock.Anything, flagSet, mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) + utilsMock.On("AssignStakerId", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) - cmdUtilsMock.On("HandleUnstakeLock", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.withdrawHash, tt.args.withdrawErr) - utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) + cmdUtilsMock.On("HandleUnstakeLock", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.withdrawHash, tt.args.withdrawErr) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) utils := &UtilsStruct{} fatal = false diff --git a/cmd/interface.go b/cmd/interface.go index 3905c9ee9..f57f13a1f 100644 --- a/cmd/interface.go +++ b/cmd/interface.go @@ -2,13 +2,13 @@ package cmd import ( - "context" "crypto/ecdsa" "math/big" "razor/cache" "razor/core/types" "razor/path" "razor/pkg/bindings" + "razor/rpc" "time" "github.com/ethereum/go-ethereum/accounts" @@ -64,11 +64,6 @@ type StakeManagerInterface interface { UpdateCommission(client *ethclient.Client, opts *bind.TransactOpts, commission uint8) (*Types.Transaction, error) ApproveUnstake(client *ethclient.Client, opts *bind.TransactOpts, stakerTokenAddress common.Address, amount *big.Int) (*Types.Transaction, error) ClaimStakerReward(client *ethclient.Client, opts *bind.TransactOpts) (*Types.Transaction, error) - - //Getter methods - StakerInfo(client *ethclient.Client, opts *bind.CallOpts, stakerId uint32) (types.Staker, error) - GetMaturity(client *ethclient.Client, opts *bind.CallOpts, age uint32) (uint16, error) - GetBountyLock(client *ethclient.Client, opts *bind.CallOpts, bountyId uint32) (types.BountyLock, error) } type KeystoreInterface interface { @@ -84,9 +79,8 @@ type BlockManagerInterface interface { DisputeOnOrderOfIds(client *ethclient.Client, opts *bind.TransactOpts, epoch uint32, blockIndex uint8, index0 *big.Int, index1 *big.Int) (*Types.Transaction, error) DisputeCollectionIdShouldBeAbsent(client *ethclient.Client, opts *bind.TransactOpts, epoch uint32, blockIndex uint8, id uint16, positionOfCollectionInBlock *big.Int) (*Types.Transaction, error) DisputeCollectionIdShouldBePresent(client *ethclient.Client, opts *bind.TransactOpts, epoch uint32, blockIndex uint8, id uint16) (*Types.Transaction, error) - GiveSorted(blockManager *bindings.BlockManager, opts *bind.TransactOpts, epoch uint32, leafId uint16, sortedValues []*big.Int) (*Types.Transaction, error) - ResetDispute(blockManager *bindings.BlockManager, opts *bind.TransactOpts, epoch uint32) (*Types.Transaction, error) - Disputes(client *ethclient.Client, opts *bind.CallOpts, epoch uint32, address common.Address) (types.DisputesStruct, error) + GiveSorted(client *ethclient.Client, opts *bind.TransactOpts, epoch uint32, leafId uint16, sortedValues []*big.Int) (*Types.Transaction, error) + ResetDispute(client *ethclient.Client, opts *bind.TransactOpts, epoch uint32) (*Types.Transaction, error) } type VoteManagerInterface interface { @@ -95,7 +89,6 @@ type VoteManagerInterface interface { } type TokenManagerInterface interface { - Allowance(client *ethclient.Client, opts *bind.CallOpts, owner common.Address, spender common.Address) (*big.Int, error) Approve(client *ethclient.Client, opts *bind.TransactOpts, spender common.Address, amount *big.Int) (*Types.Transaction, error) Transfer(client *ethclient.Client, opts *bind.TransactOpts, recipient common.Address, amount *big.Int) (*Types.Transaction, error) } @@ -147,7 +140,6 @@ type FlagSetInterface interface { type UtilsCmdInterface interface { SetConfig(flagSet *pflag.FlagSet) error GetProvider() (string, error) - GetAlternateProvider() (string, error) GetMultiplier() (float32, error) GetWaitTime() (int32, error) GetGasPrice() (int32, error) @@ -162,95 +154,95 @@ type UtilsCmdInterface interface { GetLogFileMaxAge() (int, error) GetConfigData() (types.Configurations, error) ExecuteClaimBounty(flagSet *pflag.FlagSet) - ClaimBounty(config types.Configurations, client *ethclient.Client, redeemBountyInput types.RedeemBountyInput) (common.Hash, error) - ClaimBlockReward(ctx context.Context, options types.TransactionOptions) (common.Hash, error) - GetSalt(ctx context.Context, client *ethclient.Client, epoch uint32) ([32]byte, error) - HandleCommitState(ctx context.Context, client *ethclient.Client, epoch uint32, seed []byte, commitParams *types.CommitParams, rogueData types.Rogue) (types.CommitData, error) - Commit(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, latestHeader *Types.Header, stateBuffer uint64, commitment [32]byte) (common.Hash, error) + ClaimBounty(rpcParameters rpc.RPCParameters, config types.Configurations, redeemBountyInput types.RedeemBountyInput) (common.Hash, error) + ClaimBlockReward(rpcParameters rpc.RPCParameters, options types.TransactionOptions) (common.Hash, error) + GetSalt(rpcParameters rpc.RPCParameters, epoch uint32) ([32]byte, error) + HandleCommitState(rpcParameters rpc.RPCParameters, epoch uint32, seed []byte, commitParams *types.CommitParams, rogueData types.Rogue) (types.CommitData, error) + Commit(rpcParameters rpc.RPCParameters, config types.Configurations, account types.Account, epoch uint32, latestHeader *Types.Header, stateBuffer uint64, commitment [32]byte) (common.Hash, error) ListAccounts() ([]accounts.Account, error) AssignAmountInWei(flagSet *pflag.FlagSet) (*big.Int, error) ExecuteTransfer(flagSet *pflag.FlagSet) - Transfer(client *ethclient.Client, config types.Configurations, transferInput types.TransferInput) (common.Hash, error) - CheckForLastCommitted(ctx context.Context, client *ethclient.Client, staker bindings.StructsStaker, epoch uint32) error - Reveal(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, latestHeader *Types.Header, stateBuffer uint64, commitData types.CommitData, signature []byte) (common.Hash, error) + Transfer(rpcParameters rpc.RPCParameters, config types.Configurations, transferInput types.TransferInput) (common.Hash, error) + CheckForLastCommitted(rpcParameters rpc.RPCParameters, staker bindings.StructsStaker, epoch uint32) error + Reveal(rpcParameters rpc.RPCParameters, config types.Configurations, account types.Account, epoch uint32, latestHeader *Types.Header, stateBuffer uint64, commitData types.CommitData, signature []byte) (common.Hash, error) GenerateTreeRevealData(merkleTree [][][]byte, commitData types.CommitData) bindings.StructsMerkleTree - IndexRevealEventsOfCurrentEpoch(ctx context.Context, client *ethclient.Client, blockNumber *big.Int, epoch uint32) ([]types.RevealedStruct, error) + IndexRevealEventsOfCurrentEpoch(rpcParameters rpc.RPCParameters, blockNumber *big.Int, epoch uint32) ([]types.RevealedStruct, error) ExecuteCreateJob(flagSet *pflag.FlagSet) - CreateJob(client *ethclient.Client, config types.Configurations, jobInput types.CreateJobInput) (common.Hash, error) + CreateJob(rpcParameter rpc.RPCParameters, config types.Configurations, jobInput types.CreateJobInput) (common.Hash, error) ExecuteCreateCollection(flagSet *pflag.FlagSet) - CreateCollection(client *ethclient.Client, config types.Configurations, collectionInput types.CreateCollectionInput) (common.Hash, error) - GetEpochAndState(ctx context.Context, client *ethclient.Client) (uint32, int64, error) - WaitForAppropriateState(ctx context.Context, client *ethclient.Client, action string, states ...int) (uint32, error) + CreateCollection(rpcParameters rpc.RPCParameters, config types.Configurations, collectionInput types.CreateCollectionInput) (common.Hash, error) + GetEpochAndState(rpcParameter rpc.RPCParameters) (uint32, int64, error) + WaitForAppropriateState(rpcParameter rpc.RPCParameters, action string, states ...int) (uint32, error) ExecuteJobList(flagSet *pflag.FlagSet) - GetJobList(client *ethclient.Client) error + GetJobList(rpcParameters rpc.RPCParameters) error ExecuteUnstake(flagSet *pflag.FlagSet) - Unstake(ctx context.Context, config types.Configurations, client *ethclient.Client, input types.UnstakeInput) (common.Hash, error) - ApproveUnstake(client *ethclient.Client, stakerTokenAddress common.Address, txnArgs types.TransactionOptions) (common.Hash, error) + Unstake(rpcParameters rpc.RPCParameters, config types.Configurations, input types.UnstakeInput) (common.Hash, error) + ApproveUnstake(rpcParameters rpc.RPCParameters, stakerTokenAddress common.Address, txnArgs types.TransactionOptions) (common.Hash, error) ExecuteInitiateWithdraw(flagSet *pflag.FlagSet) ExecuteUnlockWithdraw(flagSet *pflag.FlagSet) - InitiateWithdraw(client *ethclient.Client, txnOpts *bind.TransactOpts, stakerId uint32) (common.Hash, error) - UnlockWithdraw(client *ethclient.Client, txnOpts *bind.TransactOpts, stakerId uint32) (common.Hash, error) - HandleUnstakeLock(ctx context.Context, client *ethclient.Client, account types.Account, configurations types.Configurations, stakerId uint32) (common.Hash, error) - HandleWithdrawLock(ctx context.Context, client *ethclient.Client, account types.Account, configurations types.Configurations, stakerId uint32) (common.Hash, error) + InitiateWithdraw(rpcParameters rpc.RPCParameters, txnOpts *bind.TransactOpts, stakerId uint32) (common.Hash, error) + UnlockWithdraw(rpcParameters rpc.RPCParameters, txnOpts *bind.TransactOpts, stakerId uint32) (common.Hash, error) + HandleUnstakeLock(rpcParameters rpc.RPCParameters, account types.Account, configurations types.Configurations, stakerId uint32) (common.Hash, error) + HandleWithdrawLock(rpcParameters rpc.RPCParameters, account types.Account, configurations types.Configurations, stakerId uint32) (common.Hash, error) ExecuteUpdateJob(flagSet *pflag.FlagSet) - UpdateJob(ctx context.Context, client *ethclient.Client, config types.Configurations, jobInput types.CreateJobInput, jobId uint16) (common.Hash, error) - WaitIfCommitState(ctx context.Context, client *ethclient.Client, action string) (uint32, error) + UpdateJob(rpcParameters rpc.RPCParameters, config types.Configurations, jobInput types.CreateJobInput, jobId uint16) (common.Hash, error) + WaitIfCommitState(rpcParameter rpc.RPCParameters, action string) (uint32, error) ExecuteCollectionList(flagSet *pflag.FlagSet) - GetCollectionList(client *ethclient.Client) error + GetCollectionList(rpcParameters rpc.RPCParameters) error ExecuteStakerinfo(flagSet *pflag.FlagSet) ExecuteSetDelegation(flagSet *pflag.FlagSet) - SetDelegation(ctx context.Context, client *ethclient.Client, config types.Configurations, delegationInput types.SetDelegationInput) (common.Hash, error) - GetStakerInfo(ctx context.Context, client *ethclient.Client, stakerId uint32) error + SetDelegation(rpcParameters rpc.RPCParameters, config types.Configurations, delegationInput types.SetDelegationInput) (common.Hash, error) + GetStakerInfo(rpcParameters rpc.RPCParameters, stakerId uint32) error ExecuteUpdateCollection(flagSet *pflag.FlagSet) - UpdateCollection(ctx context.Context, client *ethclient.Client, config types.Configurations, collectionInput types.CreateCollectionInput, collectionId uint16) (common.Hash, error) - MakeBlock(ctx context.Context, client *ethclient.Client, blockNumber *big.Int, epoch uint32, rogueData types.Rogue) ([]*big.Int, []uint16, *types.RevealedDataMaps, error) + UpdateCollection(rpcParameters rpc.RPCParameters, config types.Configurations, collectionInput types.CreateCollectionInput, collectionId uint16) (common.Hash, error) + MakeBlock(rpcParameters rpc.RPCParameters, blockNumber *big.Int, epoch uint32, rogueData types.Rogue) ([]*big.Int, []uint16, *types.RevealedDataMaps, error) IsElectedProposer(proposer types.ElectedProposer, currentStakerStake *big.Int) bool - GetSortedRevealedValues(ctx context.Context, client *ethclient.Client, blockNumber *big.Int, epoch uint32) (*types.RevealedDataMaps, error) - GetIteration(ctx context.Context, client *ethclient.Client, proposer types.ElectedProposer, bufferPercent int32) int - Propose(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, staker bindings.StructsStaker, epoch uint32, latestHeader *Types.Header, stateBuffer uint64, rogueData types.Rogue) error - GiveSorted(ctx context.Context, client *ethclient.Client, blockManager *bindings.BlockManager, txnArgs types.TransactionOptions, epoch uint32, assetId uint16, sortedStakers []*big.Int) error - GetLocalMediansData(ctx context.Context, client *ethclient.Client, account types.Account, epoch uint32, blockNumber *big.Int, rogueData types.Rogue) (types.ProposeFileData, error) - CheckDisputeForIds(ctx context.Context, client *ethclient.Client, transactionOpts types.TransactionOptions, epoch uint32, blockIndex uint8, idsInProposedBlock []uint16, revealedCollectionIds []uint16) (*Types.Transaction, error) - Dispute(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, blockIndex uint8, proposedBlock bindings.StructsBlock, leafId uint16, sortedValues []*big.Int) error - GetCollectionIdPositionInBlock(ctx context.Context, client *ethclient.Client, leafId uint16, proposedBlock bindings.StructsBlock) *big.Int - HandleDispute(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, blockNumber *big.Int, rogueData types.Rogue, backupNodeActionsToIgnore []string) error + GetSortedRevealedValues(rpcParameters rpc.RPCParameters, blockNumber *big.Int, epoch uint32) (*types.RevealedDataMaps, error) + GetIteration(rpcParameters rpc.RPCParameters, proposer types.ElectedProposer, bufferPercent int32) int + Propose(rpcParameters rpc.RPCParameters, config types.Configurations, account types.Account, staker bindings.StructsStaker, epoch uint32, latestHeader *Types.Header, stateBuffer uint64, rogueData types.Rogue) error + GiveSorted(rpcParameters rpc.RPCParameters, txnArgs types.TransactionOptions, epoch uint32, assetId uint16, sortedStakers []*big.Int) error + GetLocalMediansData(rpcParameters rpc.RPCParameters, account types.Account, epoch uint32, blockNumber *big.Int, rogueData types.Rogue) (types.ProposeFileData, error) + CheckDisputeForIds(rpcParameters rpc.RPCParameters, transactionOpts types.TransactionOptions, epoch uint32, blockIndex uint8, idsInProposedBlock []uint16, revealedCollectionIds []uint16) (*Types.Transaction, error) + Dispute(rpcParameters rpc.RPCParameters, config types.Configurations, account types.Account, epoch uint32, blockIndex uint8, proposedBlock bindings.StructsBlock, leafId uint16, sortedValues []*big.Int) error + GetCollectionIdPositionInBlock(rpcParameters rpc.RPCParameters, leafId uint16, proposedBlock bindings.StructsBlock) *big.Int + HandleDispute(rpcParameters rpc.RPCParameters, config types.Configurations, account types.Account, epoch uint32, blockNumber *big.Int, rogueData types.Rogue, backupNodeActionsToIgnore []string) error ExecuteExtendLock(flagSet *pflag.FlagSet) - ResetUnstakeLock(client *ethclient.Client, config types.Configurations, extendLockInput types.ExtendLockInput) (common.Hash, error) - CheckCurrentStatus(client *ethclient.Client, collectionId uint16) (bool, error) + ResetUnstakeLock(rpcParameters rpc.RPCParameters, config types.Configurations, extendLockInput types.ExtendLockInput) (common.Hash, error) ExecuteModifyCollectionStatus(flagSet *pflag.FlagSet) - ModifyCollectionStatus(ctx context.Context, client *ethclient.Client, config types.Configurations, modifyCollectionInput types.ModifyCollectionInput) (common.Hash, error) - Approve(txnArgs types.TransactionOptions) (common.Hash, error) + ModifyCollectionStatus(rpcParameters rpc.RPCParameters, config types.Configurations, modifyCollectionInput types.ModifyCollectionInput) (common.Hash, error) + Approve(rpcParameters rpc.RPCParameters, txnArgs types.TransactionOptions) (common.Hash, error) ExecuteDelegate(flagSet *pflag.FlagSet) - Delegate(txnArgs types.TransactionOptions, stakerId uint32) (common.Hash, error) + Delegate(rpcParameters rpc.RPCParameters, txnArgs types.TransactionOptions, stakerId uint32) (common.Hash, error) ExecuteCreate(flagSet *pflag.FlagSet) Create(password string) (accounts.Account, error) ExecuteImport(flagSet *pflag.FlagSet) ImportAccount() (accounts.Account, error) ExecuteUpdateCommission(flagSet *pflag.FlagSet) - UpdateCommission(ctx context.Context, config types.Configurations, client *ethclient.Client, updateCommissionInput types.UpdateCommissionInput) error - GetBiggestStakeAndId(ctx context.Context, client *ethclient.Client, epoch uint32) (*big.Int, uint32, error) - GetSmallestStakeAndId(ctx context.Context, client *ethclient.Client, epoch uint32) (*big.Int, uint32, error) - StakeCoins(txnArgs types.TransactionOptions) (common.Hash, error) + UpdateCommission(rpcParameters rpc.RPCParameters, config types.Configurations, updateCommissionInput types.UpdateCommissionInput) error + GetBiggestStakeAndId(rpcParameters rpc.RPCParameters, epoch uint32) (*big.Int, uint32, error) + GetSmallestStakeAndId(rpcParameters rpc.RPCParameters, epoch uint32) (*big.Int, uint32, error) + StakeCoins(rpcParameters rpc.RPCParameters, txnArgs types.TransactionOptions) (common.Hash, error) CalculateSecret(account types.Account, epoch uint32, keystorePath string, chainId *big.Int) ([]byte, []byte, error) - HandleBlock(client *ethclient.Client, account types.Account, stakerId uint32, header *Types.Header, config types.Configurations, commitParams *types.CommitParams, rogueData types.Rogue, backupNodeActionsToIgnore []string) + HandleBlock(rpcParameters rpc.RPCParameters, account types.Account, stakerId uint32, header *Types.Header, config types.Configurations, commitParams *types.CommitParams, rogueData types.Rogue, backupNodeActionsToIgnore []string) ExecuteVote(flagSet *pflag.FlagSet) - Vote(ctx context.Context, config types.Configurations, client *ethclient.Client, account types.Account, stakerId uint32, commitParams *types.CommitParams, rogueData types.Rogue, backupNodeActionsToIgnore []string) error + Vote(rpcParameters rpc.RPCParameters, config types.Configurations, account types.Account, stakerId uint32, commitParams *types.CommitParams, rogueData types.Rogue, backupNodeActionsToIgnore []string) error HandleExit() ExecuteListAccounts(flagSet *pflag.FlagSet) ClaimCommission(flagSet *pflag.FlagSet) ExecuteStake(flagSet *pflag.FlagSet) - InitiateCommit(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, stakerId uint32, latestHeader *Types.Header, commitParams *types.CommitParams, stateBuffer uint64, rogueData types.Rogue) error - InitiateReveal(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, latestHeader *Types.Header, stateBuffer uint64, rogueData types.Rogue) error - InitiatePropose(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, latestHeader *Types.Header, stateBuffer uint64, rogueData types.Rogue) error - GetBountyIdFromEvents(ctx context.Context, client *ethclient.Client, blockNumber *big.Int, bountyHunter string) (uint32, error) - HandleClaimBounty(client *ethclient.Client, config types.Configurations, account types.Account) error + InitiateCommit(rpcParameters rpc.RPCParameters, config types.Configurations, account types.Account, epoch uint32, stakerId uint32, latestHeader *Types.Header, commitParams *types.CommitParams, stateBuffer uint64, rogueData types.Rogue) error + InitiateReveal(rpcParameters rpc.RPCParameters, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, latestHeader *Types.Header, stateBuffer uint64, rogueData types.Rogue) error + InitiatePropose(rpcParameters rpc.RPCParameters, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, latestHeader *Types.Header, stateBuffer uint64, rogueData types.Rogue) error + GetBountyIdFromEvents(rpcParameters rpc.RPCParameters, blockNumber *big.Int, bountyHunter string) (uint32, error) + HandleClaimBounty(rpcParameters rpc.RPCParameters, config types.Configurations, account types.Account) error ExecuteContractAddresses(flagSet *pflag.FlagSet) ContractAddresses() - ResetDispute(client *ethclient.Client, blockManager *bindings.BlockManager, txnOpts *bind.TransactOpts, epoch uint32) - StoreBountyId(ctx context.Context, client *ethclient.Client, account types.Account) error - CheckToDoResetDispute(client *ethclient.Client, blockManager *bindings.BlockManager, txnOpts *bind.TransactOpts, epoch uint32, sortedValues []*big.Int) - InitJobAndCollectionCache(ctx context.Context, client *ethclient.Client) (*cache.JobsCache, *cache.CollectionsCache, *big.Int, error) - BatchGetStakeSnapshotCalls(client *ethclient.Client, epoch uint32, numberOfStakers uint32) ([]*big.Int, error) + ResetDispute(rpcParameters rpc.RPCParameters, txnOpts *bind.TransactOpts, epoch uint32) + StoreBountyId(rpcParameters rpc.RPCParameters, account types.Account) error + CheckToDoResetDispute(rpcParameters rpc.RPCParameters, txnOpts *bind.TransactOpts, epoch uint32, sortedValues []*big.Int) + InitJobAndCollectionCache(rpcParameters rpc.RPCParameters) (*cache.JobsCache, *cache.CollectionsCache, *big.Int, error) + BatchGetStakeSnapshotCalls(rpcParameters rpc.RPCParameters, epoch uint32, numberOfStakers uint32) ([]*big.Int, error) + ExecuteImportEndpoints() } type TransactionInterface interface { diff --git a/cmd/jobList.go b/cmd/jobList.go index c670dfe9a..ea8acc0d8 100644 --- a/cmd/jobList.go +++ b/cmd/jobList.go @@ -2,13 +2,11 @@ package cmd import ( - "context" - "github.com/ethereum/go-ethereum/ethclient" "github.com/olekukonko/tablewriter" "github.com/spf13/cobra" "github.com/spf13/pflag" "os" - "razor/logger" + "razor/rpc" "razor/utils" "strconv" ) @@ -31,21 +29,17 @@ func initialiseJobList(cmd *cobra.Command, args []string) { //This function sets the flags appropriately and executes the GetJobList function func (*UtilsStruct) ExecuteJobList(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - log.Debugf("ExecuteJobList: Config: %+v", config) - - client := razorUtils.ConnectToClient(config.Provider) - logger.SetLoggerParameters(client, "") + _, rpcParameters, _, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) log.Debug("ExecuteJobList: Calling JobList()...") - err = cmdUtils.GetJobList(client) + err = cmdUtils.GetJobList(rpcParameters) utils.CheckError("Error in getting job list: ", err) } //This function provides the list of all jobs -func (*UtilsStruct) GetJobList(client *ethclient.Client) error { - jobs, err := razorUtils.GetJobs(context.Background(), client) +func (*UtilsStruct) GetJobList(rpcParameters rpc.RPCParameters) error { + jobs, err := razorUtils.GetJobs(rpcParameters) log.Debugf("JobList: Jobs: %+v", jobs) if err != nil { return err diff --git a/cmd/jobList_test.go b/cmd/jobList_test.go index 024e90098..6bc9c64df 100644 --- a/cmd/jobList_test.go +++ b/cmd/jobList_test.go @@ -11,7 +11,6 @@ import ( ) func TestGetJobList(t *testing.T) { - var client *ethclient.Client type fields struct { razorUtils Utils } @@ -31,7 +30,6 @@ func TestGetJobList(t *testing.T) { } type args struct { - client *ethclient.Client jobList []bindings.StructsJob jobListErr error } @@ -45,7 +43,6 @@ func TestGetJobList(t *testing.T) { name: "Test 1: When jobList executes properly", fields: testUtils, args: args{ - client: client, jobList: jobListArray, jobListErr: nil, }, @@ -56,7 +53,6 @@ func TestGetJobList(t *testing.T) { name: "Test 2: When there is a error fetching job list ", fields: testUtils, args: args{ - client: client, jobListErr: errors.New("error in fetching job list"), }, wantErr: errors.New("error in fetching job list"), @@ -69,7 +65,7 @@ func TestGetJobList(t *testing.T) { utilsMock.On("GetJobs", mock.Anything, mock.Anything).Return(tt.args.jobList, tt.args.jobListErr) utils := &UtilsStruct{} - err := utils.GetJobList(tt.args.client) + err := utils.GetJobList(rpcParameters) if err == nil || tt.wantErr == nil { if err != tt.wantErr { @@ -127,18 +123,20 @@ func TestExecuteJobList(t *testing.T) { expectedFatal: true, }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() + setupTestEndpointsEnvironment() + utilsMock.On("IsFlagPassed", mock.Anything).Return(false) fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) - cmdUtilsMock.On("GetJobList", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.jobListErr) + cmdUtilsMock.On("GetJobList", mock.Anything).Return(tt.args.jobListErr) utils := &UtilsStruct{} fatal = false diff --git a/cmd/listAccounts.go b/cmd/listAccounts.go index c0505fde1..514b0c7d4 100644 --- a/cmd/listAccounts.go +++ b/cmd/listAccounts.go @@ -26,12 +26,6 @@ func initialiseListAccounts(cmd *cobra.Command, args []string) { //This function sets the flag appropriately and executes the ListAccounts function func (*UtilsStruct) ExecuteListAccounts(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - - log.Debug("Checking to assign log file...") - fileUtils.AssignLogFile(flagSet, config) - log.Debug("ExecuteListAccounts: Calling ListAccounts()...") allAccounts, err := cmdUtils.ListAccounts() utils.CheckError("ListAccounts error: ", err) diff --git a/cmd/listAccounts_test.go b/cmd/listAccounts_test.go index 9f0d74f9e..2e0ba284f 100644 --- a/cmd/listAccounts_test.go +++ b/cmd/listAccounts_test.go @@ -119,9 +119,9 @@ func TestExecuteListAccounts(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() diff --git a/cmd/mocks/abi_interface.go b/cmd/mocks/abi_interface.go index 5545d651c..9f888d8d4 100644 --- a/cmd/mocks/abi_interface.go +++ b/cmd/mocks/abi_interface.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -18,6 +18,10 @@ func (_m *AbiInterface) Unpack(_a0 abi.ABI, name string, data []byte) ([]interfa ret := _m.Called(_a0, name, data) var r0 []interface{} + var r1 error + if rf, ok := ret.Get(0).(func(abi.ABI, string, []byte) ([]interface{}, error)); ok { + return rf(_a0, name, data) + } if rf, ok := ret.Get(0).(func(abi.ABI, string, []byte) []interface{}); ok { r0 = rf(_a0, name, data) } else { @@ -26,7 +30,6 @@ func (_m *AbiInterface) Unpack(_a0 abi.ABI, name string, data []byte) ([]interfa } } - var r1 error if rf, ok := ret.Get(1).(func(abi.ABI, string, []byte) error); ok { r1 = rf(_a0, name, data) } else { @@ -36,13 +39,12 @@ func (_m *AbiInterface) Unpack(_a0 abi.ABI, name string, data []byte) ([]interfa return r0, r1 } -type mockConstructorTestingTNewAbiInterface interface { +// NewAbiInterface creates a new instance of AbiInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAbiInterface(t interface { mock.TestingT Cleanup(func()) -} - -// NewAbiInterface creates a new instance of AbiInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewAbiInterface(t mockConstructorTestingTNewAbiInterface) *AbiInterface { +}) *AbiInterface { mock := &AbiInterface{} mock.Mock.Test(t) diff --git a/cmd/mocks/asset_manager_interface.go b/cmd/mocks/asset_manager_interface.go index d4f3304fc..ea2dc6031 100644 --- a/cmd/mocks/asset_manager_interface.go +++ b/cmd/mocks/asset_manager_interface.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -22,6 +22,10 @@ func (_m *AssetManagerInterface) CreateCollection(client *ethclient.Client, opts ret := _m.Called(client, opts, tolerance, power, aggregationMethod, jobIDs, name) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, int8, uint32, []uint16, string) (*types.Transaction, error)); ok { + return rf(client, opts, tolerance, power, aggregationMethod, jobIDs, name) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, int8, uint32, []uint16, string) *types.Transaction); ok { r0 = rf(client, opts, tolerance, power, aggregationMethod, jobIDs, name) } else { @@ -30,7 +34,6 @@ func (_m *AssetManagerInterface) CreateCollection(client *ethclient.Client, opts } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint32, int8, uint32, []uint16, string) error); ok { r1 = rf(client, opts, tolerance, power, aggregationMethod, jobIDs, name) } else { @@ -45,6 +48,10 @@ func (_m *AssetManagerInterface) CreateJob(client *ethclient.Client, opts *bind. ret := _m.Called(client, opts, weight, power, selectorType, name, selector, url) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint8, int8, uint8, string, string, string) (*types.Transaction, error)); ok { + return rf(client, opts, weight, power, selectorType, name, selector, url) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint8, int8, uint8, string, string, string) *types.Transaction); ok { r0 = rf(client, opts, weight, power, selectorType, name, selector, url) } else { @@ -53,7 +60,6 @@ func (_m *AssetManagerInterface) CreateJob(client *ethclient.Client, opts *bind. } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint8, int8, uint8, string, string, string) error); ok { r1 = rf(client, opts, weight, power, selectorType, name, selector, url) } else { @@ -68,13 +74,16 @@ func (_m *AssetManagerInterface) GetActiveStatus(client *ethclient.Client, opts ret := _m.Called(client, opts, id) var r0 bool + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.CallOpts, uint16) (bool, error)); ok { + return rf(client, opts, id) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.CallOpts, uint16) bool); ok { r0 = rf(client, opts, id) } else { r0 = ret.Get(0).(bool) } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.CallOpts, uint16) error); ok { r1 = rf(client, opts, id) } else { @@ -89,6 +98,10 @@ func (_m *AssetManagerInterface) SetCollectionStatus(client *ethclient.Client, o ret := _m.Called(client, opts, assetStatus, id) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, bool, uint16) (*types.Transaction, error)); ok { + return rf(client, opts, assetStatus, id) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, bool, uint16) *types.Transaction); ok { r0 = rf(client, opts, assetStatus, id) } else { @@ -97,7 +110,6 @@ func (_m *AssetManagerInterface) SetCollectionStatus(client *ethclient.Client, o } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, bool, uint16) error); ok { r1 = rf(client, opts, assetStatus, id) } else { @@ -112,6 +124,10 @@ func (_m *AssetManagerInterface) UpdateCollection(client *ethclient.Client, opts ret := _m.Called(client, opts, collectionId, tolerance, aggregationMethod, power, jobIds) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint16, uint32, uint32, int8, []uint16) (*types.Transaction, error)); ok { + return rf(client, opts, collectionId, tolerance, aggregationMethod, power, jobIds) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint16, uint32, uint32, int8, []uint16) *types.Transaction); ok { r0 = rf(client, opts, collectionId, tolerance, aggregationMethod, power, jobIds) } else { @@ -120,7 +136,6 @@ func (_m *AssetManagerInterface) UpdateCollection(client *ethclient.Client, opts } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint16, uint32, uint32, int8, []uint16) error); ok { r1 = rf(client, opts, collectionId, tolerance, aggregationMethod, power, jobIds) } else { @@ -135,6 +150,10 @@ func (_m *AssetManagerInterface) UpdateJob(client *ethclient.Client, opts *bind. ret := _m.Called(client, opts, jobId, weight, power, selectorType, selector, url) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint16, uint8, int8, uint8, string, string) (*types.Transaction, error)); ok { + return rf(client, opts, jobId, weight, power, selectorType, selector, url) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint16, uint8, int8, uint8, string, string) *types.Transaction); ok { r0 = rf(client, opts, jobId, weight, power, selectorType, selector, url) } else { @@ -143,7 +162,6 @@ func (_m *AssetManagerInterface) UpdateJob(client *ethclient.Client, opts *bind. } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint16, uint8, int8, uint8, string, string) error); ok { r1 = rf(client, opts, jobId, weight, power, selectorType, selector, url) } else { @@ -153,13 +171,12 @@ func (_m *AssetManagerInterface) UpdateJob(client *ethclient.Client, opts *bind. return r0, r1 } -type mockConstructorTestingTNewAssetManagerInterface interface { +// NewAssetManagerInterface creates a new instance of AssetManagerInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAssetManagerInterface(t interface { mock.TestingT Cleanup(func()) -} - -// NewAssetManagerInterface creates a new instance of AssetManagerInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewAssetManagerInterface(t mockConstructorTestingTNewAssetManagerInterface) *AssetManagerInterface { +}) *AssetManagerInterface { mock := &AssetManagerInterface{} mock.Mock.Test(t) diff --git a/cmd/mocks/block_manager_interface.go b/cmd/mocks/block_manager_interface.go index 37fc600a1..cc630d8ba 100644 --- a/cmd/mocks/block_manager_interface.go +++ b/cmd/mocks/block_manager_interface.go @@ -1,17 +1,12 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks import ( big "math/big" - bindings "razor/pkg/bindings" bind "github.com/ethereum/go-ethereum/accounts/abi/bind" - common "github.com/ethereum/go-ethereum/common" - - coretypes "razor/core/types" - ethclient "github.com/ethereum/go-ethereum/ethclient" mock "github.com/stretchr/testify/mock" @@ -29,6 +24,10 @@ func (_m *BlockManagerInterface) ClaimBlockReward(client *ethclient.Client, opts ret := _m.Called(client, opts) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts) (*types.Transaction, error)); ok { + return rf(client, opts) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts) *types.Transaction); ok { r0 = rf(client, opts) } else { @@ -37,7 +36,6 @@ func (_m *BlockManagerInterface) ClaimBlockReward(client *ethclient.Client, opts } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts) error); ok { r1 = rf(client, opts) } else { @@ -52,6 +50,10 @@ func (_m *BlockManagerInterface) DisputeBiggestStakeProposed(client *ethclient.C ret := _m.Called(client, opts, epoch, blockIndex, correctBiggestStakerId) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, uint8, uint32) (*types.Transaction, error)); ok { + return rf(client, opts, epoch, blockIndex, correctBiggestStakerId) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, uint8, uint32) *types.Transaction); ok { r0 = rf(client, opts, epoch, blockIndex, correctBiggestStakerId) } else { @@ -60,7 +62,6 @@ func (_m *BlockManagerInterface) DisputeBiggestStakeProposed(client *ethclient.C } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint32, uint8, uint32) error); ok { r1 = rf(client, opts, epoch, blockIndex, correctBiggestStakerId) } else { @@ -75,6 +76,10 @@ func (_m *BlockManagerInterface) DisputeCollectionIdShouldBeAbsent(client *ethcl ret := _m.Called(client, opts, epoch, blockIndex, id, positionOfCollectionInBlock) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, uint8, uint16, *big.Int) (*types.Transaction, error)); ok { + return rf(client, opts, epoch, blockIndex, id, positionOfCollectionInBlock) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, uint8, uint16, *big.Int) *types.Transaction); ok { r0 = rf(client, opts, epoch, blockIndex, id, positionOfCollectionInBlock) } else { @@ -83,7 +88,6 @@ func (_m *BlockManagerInterface) DisputeCollectionIdShouldBeAbsent(client *ethcl } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint32, uint8, uint16, *big.Int) error); ok { r1 = rf(client, opts, epoch, blockIndex, id, positionOfCollectionInBlock) } else { @@ -98,6 +102,10 @@ func (_m *BlockManagerInterface) DisputeCollectionIdShouldBePresent(client *ethc ret := _m.Called(client, opts, epoch, blockIndex, id) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, uint8, uint16) (*types.Transaction, error)); ok { + return rf(client, opts, epoch, blockIndex, id) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, uint8, uint16) *types.Transaction); ok { r0 = rf(client, opts, epoch, blockIndex, id) } else { @@ -106,7 +114,6 @@ func (_m *BlockManagerInterface) DisputeCollectionIdShouldBePresent(client *ethc } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint32, uint8, uint16) error); ok { r1 = rf(client, opts, epoch, blockIndex, id) } else { @@ -121,6 +128,10 @@ func (_m *BlockManagerInterface) DisputeOnOrderOfIds(client *ethclient.Client, o ret := _m.Called(client, opts, epoch, blockIndex, index0, index1) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, uint8, *big.Int, *big.Int) (*types.Transaction, error)); ok { + return rf(client, opts, epoch, blockIndex, index0, index1) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, uint8, *big.Int, *big.Int) *types.Transaction); ok { r0 = rf(client, opts, epoch, blockIndex, index0, index1) } else { @@ -129,7 +140,6 @@ func (_m *BlockManagerInterface) DisputeOnOrderOfIds(client *ethclient.Client, o } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint32, uint8, *big.Int, *big.Int) error); ok { r1 = rf(client, opts, epoch, blockIndex, index0, index1) } else { @@ -139,32 +149,15 @@ func (_m *BlockManagerInterface) DisputeOnOrderOfIds(client *ethclient.Client, o return r0, r1 } -// Disputes provides a mock function with given fields: client, opts, epoch, address -func (_m *BlockManagerInterface) Disputes(client *ethclient.Client, opts *bind.CallOpts, epoch uint32, address common.Address) (coretypes.DisputesStruct, error) { - ret := _m.Called(client, opts, epoch, address) - - var r0 coretypes.DisputesStruct - if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.CallOpts, uint32, common.Address) coretypes.DisputesStruct); ok { - r0 = rf(client, opts, epoch, address) - } else { - r0 = ret.Get(0).(coretypes.DisputesStruct) - } - - var r1 error - if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.CallOpts, uint32, common.Address) error); ok { - r1 = rf(client, opts, epoch, address) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - // FinalizeDispute provides a mock function with given fields: client, opts, epoch, blockIndex, positionOfCollectionInBlock func (_m *BlockManagerInterface) FinalizeDispute(client *ethclient.Client, opts *bind.TransactOpts, epoch uint32, blockIndex uint8, positionOfCollectionInBlock *big.Int) (*types.Transaction, error) { ret := _m.Called(client, opts, epoch, blockIndex, positionOfCollectionInBlock) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, uint8, *big.Int) (*types.Transaction, error)); ok { + return rf(client, opts, epoch, blockIndex, positionOfCollectionInBlock) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, uint8, *big.Int) *types.Transaction); ok { r0 = rf(client, opts, epoch, blockIndex, positionOfCollectionInBlock) } else { @@ -173,7 +166,6 @@ func (_m *BlockManagerInterface) FinalizeDispute(client *ethclient.Client, opts } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint32, uint8, *big.Int) error); ok { r1 = rf(client, opts, epoch, blockIndex, positionOfCollectionInBlock) } else { @@ -183,22 +175,25 @@ func (_m *BlockManagerInterface) FinalizeDispute(client *ethclient.Client, opts return r0, r1 } -// GiveSorted provides a mock function with given fields: blockManager, opts, epoch, leafId, sortedValues -func (_m *BlockManagerInterface) GiveSorted(blockManager *bindings.BlockManager, opts *bind.TransactOpts, epoch uint32, leafId uint16, sortedValues []*big.Int) (*types.Transaction, error) { - ret := _m.Called(blockManager, opts, epoch, leafId, sortedValues) +// GiveSorted provides a mock function with given fields: client, opts, epoch, leafId, sortedValues +func (_m *BlockManagerInterface) GiveSorted(client *ethclient.Client, opts *bind.TransactOpts, epoch uint32, leafId uint16, sortedValues []*big.Int) (*types.Transaction, error) { + ret := _m.Called(client, opts, epoch, leafId, sortedValues) var r0 *types.Transaction - if rf, ok := ret.Get(0).(func(*bindings.BlockManager, *bind.TransactOpts, uint32, uint16, []*big.Int) *types.Transaction); ok { - r0 = rf(blockManager, opts, epoch, leafId, sortedValues) + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, uint16, []*big.Int) (*types.Transaction, error)); ok { + return rf(client, opts, epoch, leafId, sortedValues) + } + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, uint16, []*big.Int) *types.Transaction); ok { + r0 = rf(client, opts, epoch, leafId, sortedValues) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*types.Transaction) } } - var r1 error - if rf, ok := ret.Get(1).(func(*bindings.BlockManager, *bind.TransactOpts, uint32, uint16, []*big.Int) error); ok { - r1 = rf(blockManager, opts, epoch, leafId, sortedValues) + if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint32, uint16, []*big.Int) error); ok { + r1 = rf(client, opts, epoch, leafId, sortedValues) } else { r1 = ret.Error(1) } @@ -211,6 +206,10 @@ func (_m *BlockManagerInterface) Propose(client *ethclient.Client, opts *bind.Tr ret := _m.Called(client, opts, epoch, ids, medians, iteration, biggestInfluencerId) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, []uint16, []*big.Int, *big.Int, uint32) (*types.Transaction, error)); ok { + return rf(client, opts, epoch, ids, medians, iteration, biggestInfluencerId) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, []uint16, []*big.Int, *big.Int, uint32) *types.Transaction); ok { r0 = rf(client, opts, epoch, ids, medians, iteration, biggestInfluencerId) } else { @@ -219,7 +218,6 @@ func (_m *BlockManagerInterface) Propose(client *ethclient.Client, opts *bind.Tr } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint32, []uint16, []*big.Int, *big.Int, uint32) error); ok { r1 = rf(client, opts, epoch, ids, medians, iteration, biggestInfluencerId) } else { @@ -229,22 +227,25 @@ func (_m *BlockManagerInterface) Propose(client *ethclient.Client, opts *bind.Tr return r0, r1 } -// ResetDispute provides a mock function with given fields: blockManager, opts, epoch -func (_m *BlockManagerInterface) ResetDispute(blockManager *bindings.BlockManager, opts *bind.TransactOpts, epoch uint32) (*types.Transaction, error) { - ret := _m.Called(blockManager, opts, epoch) +// ResetDispute provides a mock function with given fields: client, opts, epoch +func (_m *BlockManagerInterface) ResetDispute(client *ethclient.Client, opts *bind.TransactOpts, epoch uint32) (*types.Transaction, error) { + ret := _m.Called(client, opts, epoch) var r0 *types.Transaction - if rf, ok := ret.Get(0).(func(*bindings.BlockManager, *bind.TransactOpts, uint32) *types.Transaction); ok { - r0 = rf(blockManager, opts, epoch) + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32) (*types.Transaction, error)); ok { + return rf(client, opts, epoch) + } + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32) *types.Transaction); ok { + r0 = rf(client, opts, epoch) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*types.Transaction) } } - var r1 error - if rf, ok := ret.Get(1).(func(*bindings.BlockManager, *bind.TransactOpts, uint32) error); ok { - r1 = rf(blockManager, opts, epoch) + if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint32) error); ok { + r1 = rf(client, opts, epoch) } else { r1 = ret.Error(1) } @@ -252,13 +253,12 @@ func (_m *BlockManagerInterface) ResetDispute(blockManager *bindings.BlockManage return r0, r1 } -type mockConstructorTestingTNewBlockManagerInterface interface { +// NewBlockManagerInterface creates a new instance of BlockManagerInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBlockManagerInterface(t interface { mock.TestingT Cleanup(func()) -} - -// NewBlockManagerInterface creates a new instance of BlockManagerInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewBlockManagerInterface(t mockConstructorTestingTNewBlockManagerInterface) *BlockManagerInterface { +}) *BlockManagerInterface { mock := &BlockManagerInterface{} mock.Mock.Test(t) diff --git a/cmd/mocks/crypto_interface.go b/cmd/mocks/crypto_interface.go index 386334ac0..f842d91c3 100644 --- a/cmd/mocks/crypto_interface.go +++ b/cmd/mocks/crypto_interface.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -18,6 +18,10 @@ func (_m *CryptoInterface) HexToECDSA(hexKey string) (*ecdsa.PrivateKey, error) ret := _m.Called(hexKey) var r0 *ecdsa.PrivateKey + var r1 error + if rf, ok := ret.Get(0).(func(string) (*ecdsa.PrivateKey, error)); ok { + return rf(hexKey) + } if rf, ok := ret.Get(0).(func(string) *ecdsa.PrivateKey); ok { r0 = rf(hexKey) } else { @@ -26,7 +30,6 @@ func (_m *CryptoInterface) HexToECDSA(hexKey string) (*ecdsa.PrivateKey, error) } } - var r1 error if rf, ok := ret.Get(1).(func(string) error); ok { r1 = rf(hexKey) } else { @@ -36,13 +39,12 @@ func (_m *CryptoInterface) HexToECDSA(hexKey string) (*ecdsa.PrivateKey, error) return r0, r1 } -type mockConstructorTestingTNewCryptoInterface interface { +// NewCryptoInterface creates a new instance of CryptoInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewCryptoInterface(t interface { mock.TestingT Cleanup(func()) -} - -// NewCryptoInterface creates a new instance of CryptoInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewCryptoInterface(t mockConstructorTestingTNewCryptoInterface) *CryptoInterface { +}) *CryptoInterface { mock := &CryptoInterface{} mock.Mock.Test(t) diff --git a/cmd/mocks/flag_set_interface.go b/cmd/mocks/flag_set_interface.go index e86159625..3fd59dad5 100644 --- a/cmd/mocks/flag_set_interface.go +++ b/cmd/mocks/flag_set_interface.go @@ -792,4 +792,4 @@ func NewFlagSetInterface(t interface { t.Cleanup(func() { mock.AssertExpectations(t) }) return mock -} \ No newline at end of file +} diff --git a/cmd/mocks/keystore_interface.go b/cmd/mocks/keystore_interface.go index b987385a5..8261cead9 100644 --- a/cmd/mocks/keystore_interface.go +++ b/cmd/mocks/keystore_interface.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -36,13 +36,16 @@ func (_m *KeystoreInterface) ImportECDSA(path string, priv *ecdsa.PrivateKey, pa ret := _m.Called(path, priv, passphrase) var r0 accounts.Account + var r1 error + if rf, ok := ret.Get(0).(func(string, *ecdsa.PrivateKey, string) (accounts.Account, error)); ok { + return rf(path, priv, passphrase) + } if rf, ok := ret.Get(0).(func(string, *ecdsa.PrivateKey, string) accounts.Account); ok { r0 = rf(path, priv, passphrase) } else { r0 = ret.Get(0).(accounts.Account) } - var r1 error if rf, ok := ret.Get(1).(func(string, *ecdsa.PrivateKey, string) error); ok { r1 = rf(path, priv, passphrase) } else { @@ -52,13 +55,12 @@ func (_m *KeystoreInterface) ImportECDSA(path string, priv *ecdsa.PrivateKey, pa return r0, r1 } -type mockConstructorTestingTNewKeystoreInterface interface { +// NewKeystoreInterface creates a new instance of KeystoreInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewKeystoreInterface(t interface { mock.TestingT Cleanup(func()) -} - -// NewKeystoreInterface creates a new instance of KeystoreInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewKeystoreInterface(t mockConstructorTestingTNewKeystoreInterface) *KeystoreInterface { +}) *KeystoreInterface { mock := &KeystoreInterface{} mock.Mock.Test(t) diff --git a/cmd/mocks/os_interface.go b/cmd/mocks/os_interface.go index 84b7d0913..9a013ca02 100644 --- a/cmd/mocks/os_interface.go +++ b/cmd/mocks/os_interface.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -14,13 +14,12 @@ func (_m *OSInterface) Exit(code int) { _m.Called(code) } -type mockConstructorTestingTNewOSInterface interface { +// NewOSInterface creates a new instance of OSInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewOSInterface(t interface { mock.TestingT Cleanup(func()) -} - -// NewOSInterface creates a new instance of OSInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewOSInterface(t mockConstructorTestingTNewOSInterface) *OSInterface { +}) *OSInterface { mock := &OSInterface{} mock.Mock.Test(t) diff --git a/cmd/mocks/stake_manager_interface.go b/cmd/mocks/stake_manager_interface.go index f0661906a..aaf25e318 100644 --- a/cmd/mocks/stake_manager_interface.go +++ b/cmd/mocks/stake_manager_interface.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -9,8 +9,6 @@ import ( common "github.com/ethereum/go-ethereum/common" - coretypes "razor/core/types" - ethclient "github.com/ethereum/go-ethereum/ethclient" mock "github.com/stretchr/testify/mock" @@ -28,6 +26,10 @@ func (_m *StakeManagerInterface) ApproveUnstake(client *ethclient.Client, opts * ret := _m.Called(client, opts, stakerTokenAddress, amount) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, common.Address, *big.Int) (*types.Transaction, error)); ok { + return rf(client, opts, stakerTokenAddress, amount) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, common.Address, *big.Int) *types.Transaction); ok { r0 = rf(client, opts, stakerTokenAddress, amount) } else { @@ -36,7 +38,6 @@ func (_m *StakeManagerInterface) ApproveUnstake(client *ethclient.Client, opts * } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, common.Address, *big.Int) error); ok { r1 = rf(client, opts, stakerTokenAddress, amount) } else { @@ -51,6 +52,10 @@ func (_m *StakeManagerInterface) ClaimStakerReward(client *ethclient.Client, opt ret := _m.Called(client, opts) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts) (*types.Transaction, error)); ok { + return rf(client, opts) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts) *types.Transaction); ok { r0 = rf(client, opts) } else { @@ -59,7 +64,6 @@ func (_m *StakeManagerInterface) ClaimStakerReward(client *ethclient.Client, opt } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts) error); ok { r1 = rf(client, opts) } else { @@ -74,6 +78,10 @@ func (_m *StakeManagerInterface) Delegate(client *ethclient.Client, opts *bind.T ret := _m.Called(client, opts, stakerId, amount) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, *big.Int) (*types.Transaction, error)); ok { + return rf(client, opts, stakerId, amount) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, *big.Int) *types.Transaction); ok { r0 = rf(client, opts, stakerId, amount) } else { @@ -82,7 +90,6 @@ func (_m *StakeManagerInterface) Delegate(client *ethclient.Client, opts *bind.T } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint32, *big.Int) error); ok { r1 = rf(client, opts, stakerId, amount) } else { @@ -92,53 +99,15 @@ func (_m *StakeManagerInterface) Delegate(client *ethclient.Client, opts *bind.T return r0, r1 } -// GetBountyLock provides a mock function with given fields: client, opts, bountyId -func (_m *StakeManagerInterface) GetBountyLock(client *ethclient.Client, opts *bind.CallOpts, bountyId uint32) (coretypes.BountyLock, error) { - ret := _m.Called(client, opts, bountyId) - - var r0 coretypes.BountyLock - if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.CallOpts, uint32) coretypes.BountyLock); ok { - r0 = rf(client, opts, bountyId) - } else { - r0 = ret.Get(0).(coretypes.BountyLock) - } - - var r1 error - if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.CallOpts, uint32) error); ok { - r1 = rf(client, opts, bountyId) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetMaturity provides a mock function with given fields: client, opts, age -func (_m *StakeManagerInterface) GetMaturity(client *ethclient.Client, opts *bind.CallOpts, age uint32) (uint16, error) { - ret := _m.Called(client, opts, age) - - var r0 uint16 - if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.CallOpts, uint32) uint16); ok { - r0 = rf(client, opts, age) - } else { - r0 = ret.Get(0).(uint16) - } - - var r1 error - if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.CallOpts, uint32) error); ok { - r1 = rf(client, opts, age) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - // InitiateWithdraw provides a mock function with given fields: client, opts, stakerId func (_m *StakeManagerInterface) InitiateWithdraw(client *ethclient.Client, opts *bind.TransactOpts, stakerId uint32) (*types.Transaction, error) { ret := _m.Called(client, opts, stakerId) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32) (*types.Transaction, error)); ok { + return rf(client, opts, stakerId) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32) *types.Transaction); ok { r0 = rf(client, opts, stakerId) } else { @@ -147,7 +116,6 @@ func (_m *StakeManagerInterface) InitiateWithdraw(client *ethclient.Client, opts } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint32) error); ok { r1 = rf(client, opts, stakerId) } else { @@ -162,6 +130,10 @@ func (_m *StakeManagerInterface) RedeemBounty(client *ethclient.Client, opts *bi ret := _m.Called(client, opts, bountyId) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32) (*types.Transaction, error)); ok { + return rf(client, opts, bountyId) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32) *types.Transaction); ok { r0 = rf(client, opts, bountyId) } else { @@ -170,7 +142,6 @@ func (_m *StakeManagerInterface) RedeemBounty(client *ethclient.Client, opts *bi } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint32) error); ok { r1 = rf(client, opts, bountyId) } else { @@ -185,6 +156,10 @@ func (_m *StakeManagerInterface) ResetUnstakeLock(client *ethclient.Client, opts ret := _m.Called(client, opts, stakerId) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32) (*types.Transaction, error)); ok { + return rf(client, opts, stakerId) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32) *types.Transaction); ok { r0 = rf(client, opts, stakerId) } else { @@ -193,7 +168,6 @@ func (_m *StakeManagerInterface) ResetUnstakeLock(client *ethclient.Client, opts } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint32) error); ok { r1 = rf(client, opts, stakerId) } else { @@ -208,6 +182,10 @@ func (_m *StakeManagerInterface) SetDelegationAcceptance(client *ethclient.Clien ret := _m.Called(client, opts, status) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, bool) (*types.Transaction, error)); ok { + return rf(client, opts, status) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, bool) *types.Transaction); ok { r0 = rf(client, opts, status) } else { @@ -216,7 +194,6 @@ func (_m *StakeManagerInterface) SetDelegationAcceptance(client *ethclient.Clien } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, bool) error); ok { r1 = rf(client, opts, status) } else { @@ -231,6 +208,10 @@ func (_m *StakeManagerInterface) Stake(client *ethclient.Client, txnOpts *bind.T ret := _m.Called(client, txnOpts, epoch, amount) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, *big.Int) (*types.Transaction, error)); ok { + return rf(client, txnOpts, epoch, amount) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, *big.Int) *types.Transaction); ok { r0 = rf(client, txnOpts, epoch, amount) } else { @@ -239,7 +220,6 @@ func (_m *StakeManagerInterface) Stake(client *ethclient.Client, txnOpts *bind.T } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint32, *big.Int) error); ok { r1 = rf(client, txnOpts, epoch, amount) } else { @@ -249,32 +229,15 @@ func (_m *StakeManagerInterface) Stake(client *ethclient.Client, txnOpts *bind.T return r0, r1 } -// StakerInfo provides a mock function with given fields: client, opts, stakerId -func (_m *StakeManagerInterface) StakerInfo(client *ethclient.Client, opts *bind.CallOpts, stakerId uint32) (coretypes.Staker, error) { - ret := _m.Called(client, opts, stakerId) - - var r0 coretypes.Staker - if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.CallOpts, uint32) coretypes.Staker); ok { - r0 = rf(client, opts, stakerId) - } else { - r0 = ret.Get(0).(coretypes.Staker) - } - - var r1 error - if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.CallOpts, uint32) error); ok { - r1 = rf(client, opts, stakerId) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - // UnlockWithdraw provides a mock function with given fields: client, opts, stakerId func (_m *StakeManagerInterface) UnlockWithdraw(client *ethclient.Client, opts *bind.TransactOpts, stakerId uint32) (*types.Transaction, error) { ret := _m.Called(client, opts, stakerId) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32) (*types.Transaction, error)); ok { + return rf(client, opts, stakerId) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32) *types.Transaction); ok { r0 = rf(client, opts, stakerId) } else { @@ -283,7 +246,6 @@ func (_m *StakeManagerInterface) UnlockWithdraw(client *ethclient.Client, opts * } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint32) error); ok { r1 = rf(client, opts, stakerId) } else { @@ -298,6 +260,10 @@ func (_m *StakeManagerInterface) Unstake(client *ethclient.Client, opts *bind.Tr ret := _m.Called(client, opts, stakerId, sAmount) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, *big.Int) (*types.Transaction, error)); ok { + return rf(client, opts, stakerId, sAmount) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, *big.Int) *types.Transaction); ok { r0 = rf(client, opts, stakerId, sAmount) } else { @@ -306,7 +272,6 @@ func (_m *StakeManagerInterface) Unstake(client *ethclient.Client, opts *bind.Tr } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint32, *big.Int) error); ok { r1 = rf(client, opts, stakerId, sAmount) } else { @@ -321,6 +286,10 @@ func (_m *StakeManagerInterface) UpdateCommission(client *ethclient.Client, opts ret := _m.Called(client, opts, commission) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint8) (*types.Transaction, error)); ok { + return rf(client, opts, commission) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint8) *types.Transaction); ok { r0 = rf(client, opts, commission) } else { @@ -329,7 +298,6 @@ func (_m *StakeManagerInterface) UpdateCommission(client *ethclient.Client, opts } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint8) error); ok { r1 = rf(client, opts, commission) } else { @@ -339,13 +307,12 @@ func (_m *StakeManagerInterface) UpdateCommission(client *ethclient.Client, opts return r0, r1 } -type mockConstructorTestingTNewStakeManagerInterface interface { +// NewStakeManagerInterface creates a new instance of StakeManagerInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewStakeManagerInterface(t interface { mock.TestingT Cleanup(func()) -} - -// NewStakeManagerInterface creates a new instance of StakeManagerInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewStakeManagerInterface(t mockConstructorTestingTNewStakeManagerInterface) *StakeManagerInterface { +}) *StakeManagerInterface { mock := &StakeManagerInterface{} mock.Mock.Test(t) diff --git a/cmd/mocks/string_interface.go b/cmd/mocks/string_interface.go index de733d7aa..2eb16556e 100644 --- a/cmd/mocks/string_interface.go +++ b/cmd/mocks/string_interface.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -14,13 +14,16 @@ func (_m *StringInterface) ParseBool(str string) (bool, error) { ret := _m.Called(str) var r0 bool + var r1 error + if rf, ok := ret.Get(0).(func(string) (bool, error)); ok { + return rf(str) + } if rf, ok := ret.Get(0).(func(string) bool); ok { r0 = rf(str) } else { r0 = ret.Get(0).(bool) } - var r1 error if rf, ok := ret.Get(1).(func(string) error); ok { r1 = rf(str) } else { @@ -30,13 +33,12 @@ func (_m *StringInterface) ParseBool(str string) (bool, error) { return r0, r1 } -type mockConstructorTestingTNewStringInterface interface { +// NewStringInterface creates a new instance of StringInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewStringInterface(t interface { mock.TestingT Cleanup(func()) -} - -// NewStringInterface creates a new instance of StringInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewStringInterface(t mockConstructorTestingTNewStringInterface) *StringInterface { +}) *StringInterface { mock := &StringInterface{} mock.Mock.Test(t) diff --git a/cmd/mocks/time_interface.go b/cmd/mocks/time_interface.go index 7e3a8ca96..d1b6858af 100644 --- a/cmd/mocks/time_interface.go +++ b/cmd/mocks/time_interface.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -18,13 +18,12 @@ func (_m *TimeInterface) Sleep(duration time.Duration) { _m.Called(duration) } -type mockConstructorTestingTNewTimeInterface interface { +// NewTimeInterface creates a new instance of TimeInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTimeInterface(t interface { mock.TestingT Cleanup(func()) -} - -// NewTimeInterface creates a new instance of TimeInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewTimeInterface(t mockConstructorTestingTNewTimeInterface) *TimeInterface { +}) *TimeInterface { mock := &TimeInterface{} mock.Mock.Test(t) diff --git a/cmd/mocks/token_manager_interface.go b/cmd/mocks/token_manager_interface.go index c5f946869..7bbc2ba68 100644 --- a/cmd/mocks/token_manager_interface.go +++ b/cmd/mocks/token_manager_interface.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -21,34 +21,15 @@ type TokenManagerInterface struct { mock.Mock } -// Allowance provides a mock function with given fields: client, opts, owner, spender -func (_m *TokenManagerInterface) Allowance(client *ethclient.Client, opts *bind.CallOpts, owner common.Address, spender common.Address) (*big.Int, error) { - ret := _m.Called(client, opts, owner, spender) - - var r0 *big.Int - if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.CallOpts, common.Address, common.Address) *big.Int); ok { - r0 = rf(client, opts, owner, spender) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*big.Int) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.CallOpts, common.Address, common.Address) error); ok { - r1 = rf(client, opts, owner, spender) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - // Approve provides a mock function with given fields: client, opts, spender, amount func (_m *TokenManagerInterface) Approve(client *ethclient.Client, opts *bind.TransactOpts, spender common.Address, amount *big.Int) (*types.Transaction, error) { ret := _m.Called(client, opts, spender, amount) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, common.Address, *big.Int) (*types.Transaction, error)); ok { + return rf(client, opts, spender, amount) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, common.Address, *big.Int) *types.Transaction); ok { r0 = rf(client, opts, spender, amount) } else { @@ -57,7 +38,6 @@ func (_m *TokenManagerInterface) Approve(client *ethclient.Client, opts *bind.Tr } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, common.Address, *big.Int) error); ok { r1 = rf(client, opts, spender, amount) } else { @@ -72,6 +52,10 @@ func (_m *TokenManagerInterface) Transfer(client *ethclient.Client, opts *bind.T ret := _m.Called(client, opts, recipient, amount) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, common.Address, *big.Int) (*types.Transaction, error)); ok { + return rf(client, opts, recipient, amount) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, common.Address, *big.Int) *types.Transaction); ok { r0 = rf(client, opts, recipient, amount) } else { @@ -80,7 +64,6 @@ func (_m *TokenManagerInterface) Transfer(client *ethclient.Client, opts *bind.T } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, common.Address, *big.Int) error); ok { r1 = rf(client, opts, recipient, amount) } else { @@ -90,13 +73,12 @@ func (_m *TokenManagerInterface) Transfer(client *ethclient.Client, opts *bind.T return r0, r1 } -type mockConstructorTestingTNewTokenManagerInterface interface { +// NewTokenManagerInterface creates a new instance of TokenManagerInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTokenManagerInterface(t interface { mock.TestingT Cleanup(func()) -} - -// NewTokenManagerInterface creates a new instance of TokenManagerInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewTokenManagerInterface(t mockConstructorTestingTNewTokenManagerInterface) *TokenManagerInterface { +}) *TokenManagerInterface { mock := &TokenManagerInterface{} mock.Mock.Test(t) diff --git a/cmd/mocks/transaction_interface.go b/cmd/mocks/transaction_interface.go index 9255cd7b8..c3bd72ea6 100644 --- a/cmd/mocks/transaction_interface.go +++ b/cmd/mocks/transaction_interface.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -30,13 +30,12 @@ func (_m *TransactionInterface) Hash(txn *types.Transaction) common.Hash { return r0 } -type mockConstructorTestingTNewTransactionInterface interface { +// NewTransactionInterface creates a new instance of TransactionInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTransactionInterface(t interface { mock.TestingT Cleanup(func()) -} - -// NewTransactionInterface creates a new instance of TransactionInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewTransactionInterface(t mockConstructorTestingTNewTransactionInterface) *TransactionInterface { +}) *TransactionInterface { mock := &TransactionInterface{} mock.Mock.Test(t) diff --git a/cmd/mocks/utils_cmd_interface.go b/cmd/mocks/utils_cmd_interface.go index 5827ad67f..a3841765a 100644 --- a/cmd/mocks/utils_cmd_interface.go +++ b/cmd/mocks/utils_cmd_interface.go @@ -4,6 +4,7 @@ package mocks import ( big "math/big" + RPC "razor/rpc" accounts "github.com/ethereum/go-ethereum/accounts" @@ -15,12 +16,8 @@ import ( common "github.com/ethereum/go-ethereum/common" - context "context" - coretypes "github.com/ethereum/go-ethereum/core/types" - ethclient "github.com/ethereum/go-ethereum/ethclient" - mock "github.com/stretchr/testify/mock" pflag "github.com/spf13/pflag" @@ -33,25 +30,25 @@ type UtilsCmdInterface struct { mock.Mock } -// Approve provides a mock function with given fields: txnArgs -func (_m *UtilsCmdInterface) Approve(txnArgs types.TransactionOptions) (common.Hash, error) { - ret := _m.Called(txnArgs) +// Approve provides a mock function with given fields: rpcParameters, txnArgs +func (_m *UtilsCmdInterface) Approve(rpcParameters RPC.RPCParameters, txnArgs types.TransactionOptions) (common.Hash, error) { + ret := _m.Called(rpcParameters, txnArgs) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(types.TransactionOptions) (common.Hash, error)); ok { - return rf(txnArgs) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.TransactionOptions) (common.Hash, error)); ok { + return rf(rpcParameters, txnArgs) } - if rf, ok := ret.Get(0).(func(types.TransactionOptions) common.Hash); ok { - r0 = rf(txnArgs) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.TransactionOptions) common.Hash); ok { + r0 = rf(rpcParameters, txnArgs) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(types.TransactionOptions) error); ok { - r1 = rf(txnArgs) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, types.TransactionOptions) error); ok { + r1 = rf(rpcParameters, txnArgs) } else { r1 = ret.Error(1) } @@ -59,25 +56,25 @@ func (_m *UtilsCmdInterface) Approve(txnArgs types.TransactionOptions) (common.H return r0, r1 } -// ApproveUnstake provides a mock function with given fields: client, stakerTokenAddress, txnArgs -func (_m *UtilsCmdInterface) ApproveUnstake(client *ethclient.Client, stakerTokenAddress common.Address, txnArgs types.TransactionOptions) (common.Hash, error) { - ret := _m.Called(client, stakerTokenAddress, txnArgs) +// ApproveUnstake provides a mock function with given fields: rpcParameters, stakerTokenAddress, txnArgs +func (_m *UtilsCmdInterface) ApproveUnstake(rpcParameters RPC.RPCParameters, stakerTokenAddress common.Address, txnArgs types.TransactionOptions) (common.Hash, error) { + ret := _m.Called(rpcParameters, stakerTokenAddress, txnArgs) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, common.Address, types.TransactionOptions) (common.Hash, error)); ok { - return rf(client, stakerTokenAddress, txnArgs) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, common.Address, types.TransactionOptions) (common.Hash, error)); ok { + return rf(rpcParameters, stakerTokenAddress, txnArgs) } - if rf, ok := ret.Get(0).(func(*ethclient.Client, common.Address, types.TransactionOptions) common.Hash); ok { - r0 = rf(client, stakerTokenAddress, txnArgs) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, common.Address, types.TransactionOptions) common.Hash); ok { + r0 = rf(rpcParameters, stakerTokenAddress, txnArgs) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, common.Address, types.TransactionOptions) error); ok { - r1 = rf(client, stakerTokenAddress, txnArgs) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, common.Address, types.TransactionOptions) error); ok { + r1 = rf(rpcParameters, stakerTokenAddress, txnArgs) } else { r1 = ret.Error(1) } @@ -111,25 +108,25 @@ func (_m *UtilsCmdInterface) AssignAmountInWei(flagSet *pflag.FlagSet) (*big.Int return r0, r1 } -// BatchGetStakeSnapshotCalls provides a mock function with given fields: client, epoch, numberOfStakers -func (_m *UtilsCmdInterface) BatchGetStakeSnapshotCalls(client *ethclient.Client, epoch uint32, numberOfStakers uint32) ([]*big.Int, error) { - ret := _m.Called(client, epoch, numberOfStakers) +// BatchGetStakeSnapshotCalls provides a mock function with given fields: rpcParameters, epoch, numberOfStakers +func (_m *UtilsCmdInterface) BatchGetStakeSnapshotCalls(rpcParameters RPC.RPCParameters, epoch uint32, numberOfStakers uint32) ([]*big.Int, error) { + ret := _m.Called(rpcParameters, epoch, numberOfStakers) var r0 []*big.Int var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32, uint32) ([]*big.Int, error)); ok { - return rf(client, epoch, numberOfStakers) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32, uint32) ([]*big.Int, error)); ok { + return rf(rpcParameters, epoch, numberOfStakers) } - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32, uint32) []*big.Int); ok { - r0 = rf(client, epoch, numberOfStakers) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32, uint32) []*big.Int); ok { + r0 = rf(rpcParameters, epoch, numberOfStakers) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*big.Int) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32, uint32) error); ok { - r1 = rf(client, epoch, numberOfStakers) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32, uint32) error); ok { + r1 = rf(rpcParameters, epoch, numberOfStakers) } else { r1 = ret.Error(1) } @@ -172,49 +169,25 @@ func (_m *UtilsCmdInterface) CalculateSecret(account types.Account, epoch uint32 return r0, r1, r2 } -// CheckCurrentStatus provides a mock function with given fields: client, collectionId -func (_m *UtilsCmdInterface) CheckCurrentStatus(client *ethclient.Client, collectionId uint16) (bool, error) { - ret := _m.Called(client, collectionId) - - var r0 bool - var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint16) (bool, error)); ok { - return rf(client, collectionId) - } - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint16) bool); ok { - r0 = rf(client, collectionId) - } else { - r0 = ret.Get(0).(bool) - } - - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint16) error); ok { - r1 = rf(client, collectionId) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// CheckDisputeForIds provides a mock function with given fields: ctx, client, transactionOpts, epoch, blockIndex, idsInProposedBlock, revealedCollectionIds -func (_m *UtilsCmdInterface) CheckDisputeForIds(ctx context.Context, client *ethclient.Client, transactionOpts types.TransactionOptions, epoch uint32, blockIndex uint8, idsInProposedBlock []uint16, revealedCollectionIds []uint16) (*coretypes.Transaction, error) { - ret := _m.Called(ctx, client, transactionOpts, epoch, blockIndex, idsInProposedBlock, revealedCollectionIds) +// CheckDisputeForIds provides a mock function with given fields: rpcParameters, transactionOpts, epoch, blockIndex, idsInProposedBlock, revealedCollectionIds +func (_m *UtilsCmdInterface) CheckDisputeForIds(rpcParameters RPC.RPCParameters, transactionOpts types.TransactionOptions, epoch uint32, blockIndex uint8, idsInProposedBlock []uint16, revealedCollectionIds []uint16) (*coretypes.Transaction, error) { + ret := _m.Called(rpcParameters, transactionOpts, epoch, blockIndex, idsInProposedBlock, revealedCollectionIds) var r0 *coretypes.Transaction var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.TransactionOptions, uint32, uint8, []uint16, []uint16) (*coretypes.Transaction, error)); ok { - return rf(ctx, client, transactionOpts, epoch, blockIndex, idsInProposedBlock, revealedCollectionIds) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.TransactionOptions, uint32, uint8, []uint16, []uint16) (*coretypes.Transaction, error)); ok { + return rf(rpcParameters, transactionOpts, epoch, blockIndex, idsInProposedBlock, revealedCollectionIds) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.TransactionOptions, uint32, uint8, []uint16, []uint16) *coretypes.Transaction); ok { - r0 = rf(ctx, client, transactionOpts, epoch, blockIndex, idsInProposedBlock, revealedCollectionIds) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.TransactionOptions, uint32, uint8, []uint16, []uint16) *coretypes.Transaction); ok { + r0 = rf(rpcParameters, transactionOpts, epoch, blockIndex, idsInProposedBlock, revealedCollectionIds) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*coretypes.Transaction) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, types.TransactionOptions, uint32, uint8, []uint16, []uint16) error); ok { - r1 = rf(ctx, client, transactionOpts, epoch, blockIndex, idsInProposedBlock, revealedCollectionIds) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, types.TransactionOptions, uint32, uint8, []uint16, []uint16) error); ok { + r1 = rf(rpcParameters, transactionOpts, epoch, blockIndex, idsInProposedBlock, revealedCollectionIds) } else { r1 = ret.Error(1) } @@ -222,13 +195,13 @@ func (_m *UtilsCmdInterface) CheckDisputeForIds(ctx context.Context, client *eth return r0, r1 } -// CheckForLastCommitted provides a mock function with given fields: ctx, client, staker, epoch -func (_m *UtilsCmdInterface) CheckForLastCommitted(ctx context.Context, client *ethclient.Client, staker bindings.StructsStaker, epoch uint32) error { - ret := _m.Called(ctx, client, staker, epoch) +// CheckForLastCommitted provides a mock function with given fields: rpcParameters, staker, epoch +func (_m *UtilsCmdInterface) CheckForLastCommitted(rpcParameters RPC.RPCParameters, staker bindings.StructsStaker, epoch uint32) error { + ret := _m.Called(rpcParameters, staker, epoch) var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, bindings.StructsStaker, uint32) error); ok { - r0 = rf(ctx, client, staker, epoch) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, bindings.StructsStaker, uint32) error); ok { + r0 = rf(rpcParameters, staker, epoch) } else { r0 = ret.Error(0) } @@ -236,30 +209,30 @@ func (_m *UtilsCmdInterface) CheckForLastCommitted(ctx context.Context, client * return r0 } -// CheckToDoResetDispute provides a mock function with given fields: client, blockManager, txnOpts, epoch, sortedValues -func (_m *UtilsCmdInterface) CheckToDoResetDispute(client *ethclient.Client, blockManager *bindings.BlockManager, txnOpts *bind.TransactOpts, epoch uint32, sortedValues []*big.Int) { - _m.Called(client, blockManager, txnOpts, epoch, sortedValues) +// CheckToDoResetDispute provides a mock function with given fields: rpcParameters, txnOpts, epoch, sortedValues +func (_m *UtilsCmdInterface) CheckToDoResetDispute(rpcParameters RPC.RPCParameters, txnOpts *bind.TransactOpts, epoch uint32, sortedValues []*big.Int) { + _m.Called(rpcParameters, txnOpts, epoch, sortedValues) } -// ClaimBlockReward provides a mock function with given fields: ctx, options -func (_m *UtilsCmdInterface) ClaimBlockReward(ctx context.Context, options types.TransactionOptions) (common.Hash, error) { - ret := _m.Called(ctx, options) +// ClaimBlockReward provides a mock function with given fields: rpcParameters, options +func (_m *UtilsCmdInterface) ClaimBlockReward(rpcParameters RPC.RPCParameters, options types.TransactionOptions) (common.Hash, error) { + ret := _m.Called(rpcParameters, options) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(context.Context, types.TransactionOptions) (common.Hash, error)); ok { - return rf(ctx, options) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.TransactionOptions) (common.Hash, error)); ok { + return rf(rpcParameters, options) } - if rf, ok := ret.Get(0).(func(context.Context, types.TransactionOptions) common.Hash); ok { - r0 = rf(ctx, options) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.TransactionOptions) common.Hash); ok { + r0 = rf(rpcParameters, options) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(context.Context, types.TransactionOptions) error); ok { - r1 = rf(ctx, options) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, types.TransactionOptions) error); ok { + r1 = rf(rpcParameters, options) } else { r1 = ret.Error(1) } @@ -267,25 +240,25 @@ func (_m *UtilsCmdInterface) ClaimBlockReward(ctx context.Context, options types return r0, r1 } -// ClaimBounty provides a mock function with given fields: config, client, redeemBountyInput -func (_m *UtilsCmdInterface) ClaimBounty(config types.Configurations, client *ethclient.Client, redeemBountyInput types.RedeemBountyInput) (common.Hash, error) { - ret := _m.Called(config, client, redeemBountyInput) +// ClaimBounty provides a mock function with given fields: rpcParameters, config, redeemBountyInput +func (_m *UtilsCmdInterface) ClaimBounty(rpcParameters RPC.RPCParameters, config types.Configurations, redeemBountyInput types.RedeemBountyInput) (common.Hash, error) { + ret := _m.Called(rpcParameters, config, redeemBountyInput) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(types.Configurations, *ethclient.Client, types.RedeemBountyInput) (common.Hash, error)); ok { - return rf(config, client, redeemBountyInput) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.RedeemBountyInput) (common.Hash, error)); ok { + return rf(rpcParameters, config, redeemBountyInput) } - if rf, ok := ret.Get(0).(func(types.Configurations, *ethclient.Client, types.RedeemBountyInput) common.Hash); ok { - r0 = rf(config, client, redeemBountyInput) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.RedeemBountyInput) common.Hash); ok { + r0 = rf(rpcParameters, config, redeemBountyInput) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(types.Configurations, *ethclient.Client, types.RedeemBountyInput) error); ok { - r1 = rf(config, client, redeemBountyInput) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, types.Configurations, types.RedeemBountyInput) error); ok { + r1 = rf(rpcParameters, config, redeemBountyInput) } else { r1 = ret.Error(1) } @@ -298,25 +271,25 @@ func (_m *UtilsCmdInterface) ClaimCommission(flagSet *pflag.FlagSet) { _m.Called(flagSet) } -// Commit provides a mock function with given fields: ctx, client, config, account, epoch, latestHeader, stateBuffer, commitment -func (_m *UtilsCmdInterface) Commit(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, latestHeader *coretypes.Header, stateBuffer uint64, commitment [32]byte) (common.Hash, error) { - ret := _m.Called(ctx, client, config, account, epoch, latestHeader, stateBuffer, commitment) +// Commit provides a mock function with given fields: rpcParameters, config, account, epoch, latestHeader, stateBuffer, commitment +func (_m *UtilsCmdInterface) Commit(rpcParameters RPC.RPCParameters, config types.Configurations, account types.Account, epoch uint32, latestHeader *coretypes.Header, stateBuffer uint64, commitment [32]byte) (common.Hash, error) { + ret := _m.Called(rpcParameters, config, account, epoch, latestHeader, stateBuffer, commitment) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Configurations, types.Account, uint32, *coretypes.Header, uint64, [32]byte) (common.Hash, error)); ok { - return rf(ctx, client, config, account, epoch, latestHeader, stateBuffer, commitment) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.Account, uint32, *coretypes.Header, uint64, [32]byte) (common.Hash, error)); ok { + return rf(rpcParameters, config, account, epoch, latestHeader, stateBuffer, commitment) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Configurations, types.Account, uint32, *coretypes.Header, uint64, [32]byte) common.Hash); ok { - r0 = rf(ctx, client, config, account, epoch, latestHeader, stateBuffer, commitment) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.Account, uint32, *coretypes.Header, uint64, [32]byte) common.Hash); ok { + r0 = rf(rpcParameters, config, account, epoch, latestHeader, stateBuffer, commitment) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, types.Configurations, types.Account, uint32, *coretypes.Header, uint64, [32]byte) error); ok { - r1 = rf(ctx, client, config, account, epoch, latestHeader, stateBuffer, commitment) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, types.Configurations, types.Account, uint32, *coretypes.Header, uint64, [32]byte) error); ok { + r1 = rf(rpcParameters, config, account, epoch, latestHeader, stateBuffer, commitment) } else { r1 = ret.Error(1) } @@ -353,25 +326,25 @@ func (_m *UtilsCmdInterface) Create(password string) (accounts.Account, error) { return r0, r1 } -// CreateCollection provides a mock function with given fields: client, config, collectionInput -func (_m *UtilsCmdInterface) CreateCollection(client *ethclient.Client, config types.Configurations, collectionInput types.CreateCollectionInput) (common.Hash, error) { - ret := _m.Called(client, config, collectionInput) +// CreateCollection provides a mock function with given fields: rpcParameters, config, collectionInput +func (_m *UtilsCmdInterface) CreateCollection(rpcParameters RPC.RPCParameters, config types.Configurations, collectionInput types.CreateCollectionInput) (common.Hash, error) { + ret := _m.Called(rpcParameters, config, collectionInput) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations, types.CreateCollectionInput) (common.Hash, error)); ok { - return rf(client, config, collectionInput) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.CreateCollectionInput) (common.Hash, error)); ok { + return rf(rpcParameters, config, collectionInput) } - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations, types.CreateCollectionInput) common.Hash); ok { - r0 = rf(client, config, collectionInput) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.CreateCollectionInput) common.Hash); ok { + r0 = rf(rpcParameters, config, collectionInput) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, types.Configurations, types.CreateCollectionInput) error); ok { - r1 = rf(client, config, collectionInput) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, types.Configurations, types.CreateCollectionInput) error); ok { + r1 = rf(rpcParameters, config, collectionInput) } else { r1 = ret.Error(1) } @@ -379,25 +352,25 @@ func (_m *UtilsCmdInterface) CreateCollection(client *ethclient.Client, config t return r0, r1 } -// CreateJob provides a mock function with given fields: client, config, jobInput -func (_m *UtilsCmdInterface) CreateJob(client *ethclient.Client, config types.Configurations, jobInput types.CreateJobInput) (common.Hash, error) { - ret := _m.Called(client, config, jobInput) +// CreateJob provides a mock function with given fields: rpcParameter, config, jobInput +func (_m *UtilsCmdInterface) CreateJob(rpcParameter RPC.RPCParameters, config types.Configurations, jobInput types.CreateJobInput) (common.Hash, error) { + ret := _m.Called(rpcParameter, config, jobInput) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations, types.CreateJobInput) (common.Hash, error)); ok { - return rf(client, config, jobInput) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.CreateJobInput) (common.Hash, error)); ok { + return rf(rpcParameter, config, jobInput) } - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations, types.CreateJobInput) common.Hash); ok { - r0 = rf(client, config, jobInput) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.CreateJobInput) common.Hash); ok { + r0 = rf(rpcParameter, config, jobInput) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, types.Configurations, types.CreateJobInput) error); ok { - r1 = rf(client, config, jobInput) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, types.Configurations, types.CreateJobInput) error); ok { + r1 = rf(rpcParameter, config, jobInput) } else { r1 = ret.Error(1) } @@ -405,25 +378,25 @@ func (_m *UtilsCmdInterface) CreateJob(client *ethclient.Client, config types.Co return r0, r1 } -// Delegate provides a mock function with given fields: txnArgs, stakerId -func (_m *UtilsCmdInterface) Delegate(txnArgs types.TransactionOptions, stakerId uint32) (common.Hash, error) { - ret := _m.Called(txnArgs, stakerId) +// Delegate provides a mock function with given fields: rpcParameters, txnArgs, stakerId +func (_m *UtilsCmdInterface) Delegate(rpcParameters RPC.RPCParameters, txnArgs types.TransactionOptions, stakerId uint32) (common.Hash, error) { + ret := _m.Called(rpcParameters, txnArgs, stakerId) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(types.TransactionOptions, uint32) (common.Hash, error)); ok { - return rf(txnArgs, stakerId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.TransactionOptions, uint32) (common.Hash, error)); ok { + return rf(rpcParameters, txnArgs, stakerId) } - if rf, ok := ret.Get(0).(func(types.TransactionOptions, uint32) common.Hash); ok { - r0 = rf(txnArgs, stakerId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.TransactionOptions, uint32) common.Hash); ok { + r0 = rf(rpcParameters, txnArgs, stakerId) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(types.TransactionOptions, uint32) error); ok { - r1 = rf(txnArgs, stakerId) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, types.TransactionOptions, uint32) error); ok { + r1 = rf(rpcParameters, txnArgs, stakerId) } else { r1 = ret.Error(1) } @@ -431,13 +404,13 @@ func (_m *UtilsCmdInterface) Delegate(txnArgs types.TransactionOptions, stakerId return r0, r1 } -// Dispute provides a mock function with given fields: ctx, client, config, account, epoch, blockIndex, proposedBlock, leafId, sortedValues -func (_m *UtilsCmdInterface) Dispute(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, blockIndex uint8, proposedBlock bindings.StructsBlock, leafId uint16, sortedValues []*big.Int) error { - ret := _m.Called(ctx, client, config, account, epoch, blockIndex, proposedBlock, leafId, sortedValues) +// Dispute provides a mock function with given fields: rpcParameters, config, account, epoch, blockIndex, proposedBlock, leafId, sortedValues +func (_m *UtilsCmdInterface) Dispute(rpcParameters RPC.RPCParameters, config types.Configurations, account types.Account, epoch uint32, blockIndex uint8, proposedBlock bindings.StructsBlock, leafId uint16, sortedValues []*big.Int) error { + ret := _m.Called(rpcParameters, config, account, epoch, blockIndex, proposedBlock, leafId, sortedValues) var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Configurations, types.Account, uint32, uint8, bindings.StructsBlock, uint16, []*big.Int) error); ok { - r0 = rf(ctx, client, config, account, epoch, blockIndex, proposedBlock, leafId, sortedValues) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.Account, uint32, uint8, bindings.StructsBlock, uint16, []*big.Int) error); ok { + r0 = rf(rpcParameters, config, account, epoch, blockIndex, proposedBlock, leafId, sortedValues) } else { r0 = ret.Error(0) } @@ -490,6 +463,11 @@ func (_m *UtilsCmdInterface) ExecuteImport(flagSet *pflag.FlagSet) { _m.Called(flagSet) } +// ExecuteImportEndpoints provides a mock function with given fields: +func (_m *UtilsCmdInterface) ExecuteImportEndpoints() { + _m.Called() +} + // ExecuteInitiateWithdraw provides a mock function with given fields: flagSet func (_m *UtilsCmdInterface) ExecuteInitiateWithdraw(flagSet *pflag.FlagSet) { _m.Called(flagSet) @@ -574,56 +552,32 @@ func (_m *UtilsCmdInterface) GenerateTreeRevealData(merkleTree [][][]byte, commi return r0 } -// GetAlternateProvider provides a mock function with given fields: -func (_m *UtilsCmdInterface) GetAlternateProvider() (string, error) { - ret := _m.Called() - - var r0 string - var r1 error - if rf, ok := ret.Get(0).(func() (string, error)); ok { - return rf() - } - if rf, ok := ret.Get(0).(func() string); ok { - r0 = rf() - } else { - r0 = ret.Get(0).(string) - } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetBiggestStakeAndId provides a mock function with given fields: ctx, client, epoch -func (_m *UtilsCmdInterface) GetBiggestStakeAndId(ctx context.Context, client *ethclient.Client, epoch uint32) (*big.Int, uint32, error) { - ret := _m.Called(ctx, client, epoch) +// GetBiggestStakeAndId provides a mock function with given fields: rpcParameters, epoch +func (_m *UtilsCmdInterface) GetBiggestStakeAndId(rpcParameters RPC.RPCParameters, epoch uint32) (*big.Int, uint32, error) { + ret := _m.Called(rpcParameters, epoch) var r0 *big.Int var r1 uint32 var r2 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) (*big.Int, uint32, error)); ok { - return rf(ctx, client, epoch) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) (*big.Int, uint32, error)); ok { + return rf(rpcParameters, epoch) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) *big.Int); ok { - r0 = rf(ctx, client, epoch) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) *big.Int); ok { + r0 = rf(rpcParameters, epoch) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32) uint32); ok { - r1 = rf(ctx, client, epoch) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32) uint32); ok { + r1 = rf(rpcParameters, epoch) } else { r1 = ret.Get(1).(uint32) } - if rf, ok := ret.Get(2).(func(context.Context, *ethclient.Client, uint32) error); ok { - r2 = rf(ctx, client, epoch) + if rf, ok := ret.Get(2).(func(RPC.RPCParameters, uint32) error); ok { + r2 = rf(rpcParameters, epoch) } else { r2 = ret.Error(2) } @@ -631,23 +585,23 @@ func (_m *UtilsCmdInterface) GetBiggestStakeAndId(ctx context.Context, client *e return r0, r1, r2 } -// GetBountyIdFromEvents provides a mock function with given fields: ctx, client, blockNumber, bountyHunter -func (_m *UtilsCmdInterface) GetBountyIdFromEvents(ctx context.Context, client *ethclient.Client, blockNumber *big.Int, bountyHunter string) (uint32, error) { - ret := _m.Called(ctx, client, blockNumber, bountyHunter) +// GetBountyIdFromEvents provides a mock function with given fields: rpcParameters, blockNumber, bountyHunter +func (_m *UtilsCmdInterface) GetBountyIdFromEvents(rpcParameters RPC.RPCParameters, blockNumber *big.Int, bountyHunter string) (uint32, error) { + ret := _m.Called(rpcParameters, blockNumber, bountyHunter) var r0 uint32 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, *big.Int, string) (uint32, error)); ok { - return rf(ctx, client, blockNumber, bountyHunter) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, *big.Int, string) (uint32, error)); ok { + return rf(rpcParameters, blockNumber, bountyHunter) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, *big.Int, string) uint32); ok { - r0 = rf(ctx, client, blockNumber, bountyHunter) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, *big.Int, string) uint32); ok { + r0 = rf(rpcParameters, blockNumber, bountyHunter) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, *big.Int, string) error); ok { - r1 = rf(ctx, client, blockNumber, bountyHunter) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, *big.Int, string) error); ok { + r1 = rf(rpcParameters, blockNumber, bountyHunter) } else { r1 = ret.Error(1) } @@ -679,13 +633,13 @@ func (_m *UtilsCmdInterface) GetBufferPercent() (int32, error) { return r0, r1 } -// GetCollectionIdPositionInBlock provides a mock function with given fields: ctx, client, leafId, proposedBlock -func (_m *UtilsCmdInterface) GetCollectionIdPositionInBlock(ctx context.Context, client *ethclient.Client, leafId uint16, proposedBlock bindings.StructsBlock) *big.Int { - ret := _m.Called(ctx, client, leafId, proposedBlock) +// GetCollectionIdPositionInBlock provides a mock function with given fields: rpcParameters, leafId, proposedBlock +func (_m *UtilsCmdInterface) GetCollectionIdPositionInBlock(rpcParameters RPC.RPCParameters, leafId uint16, proposedBlock bindings.StructsBlock) *big.Int { + ret := _m.Called(rpcParameters, leafId, proposedBlock) var r0 *big.Int - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint16, bindings.StructsBlock) *big.Int); ok { - r0 = rf(ctx, client, leafId, proposedBlock) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint16, bindings.StructsBlock) *big.Int); ok { + r0 = rf(rpcParameters, leafId, proposedBlock) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) @@ -695,13 +649,13 @@ func (_m *UtilsCmdInterface) GetCollectionIdPositionInBlock(ctx context.Context, return r0 } -// GetCollectionList provides a mock function with given fields: client -func (_m *UtilsCmdInterface) GetCollectionList(client *ethclient.Client) error { - ret := _m.Called(client) +// GetCollectionList provides a mock function with given fields: rpcParameters +func (_m *UtilsCmdInterface) GetCollectionList(rpcParameters RPC.RPCParameters) error { + ret := _m.Called(rpcParameters) var r0 error - if rf, ok := ret.Get(0).(func(*ethclient.Client) error); ok { - r0 = rf(client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) error); ok { + r0 = rf(rpcParameters) } else { r0 = ret.Error(0) } @@ -733,30 +687,30 @@ func (_m *UtilsCmdInterface) GetConfigData() (types.Configurations, error) { return r0, r1 } -// GetEpochAndState provides a mock function with given fields: ctx, client -func (_m *UtilsCmdInterface) GetEpochAndState(ctx context.Context, client *ethclient.Client) (uint32, int64, error) { - ret := _m.Called(ctx, client) +// GetEpochAndState provides a mock function with given fields: rpcParameter +func (_m *UtilsCmdInterface) GetEpochAndState(rpcParameter RPC.RPCParameters) (uint32, int64, error) { + ret := _m.Called(rpcParameter) var r0 uint32 var r1 int64 var r2 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) (uint32, int64, error)); ok { - return rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) (uint32, int64, error)); ok { + return rf(rpcParameter) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) uint32); ok { - r0 = rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) uint32); ok { + r0 = rf(rpcParameter) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) int64); ok { - r1 = rf(ctx, client) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters) int64); ok { + r1 = rf(rpcParameter) } else { r1 = ret.Get(1).(int64) } - if rf, ok := ret.Get(2).(func(context.Context, *ethclient.Client) error); ok { - r2 = rf(ctx, client) + if rf, ok := ret.Get(2).(func(RPC.RPCParameters) error); ok { + r2 = rf(rpcParameter) } else { r2 = ret.Error(2) } @@ -860,13 +814,13 @@ func (_m *UtilsCmdInterface) GetHTTPTimeout() (int64, error) { return r0, r1 } -// GetIteration provides a mock function with given fields: ctx, client, proposer, bufferPercent -func (_m *UtilsCmdInterface) GetIteration(ctx context.Context, client *ethclient.Client, proposer types.ElectedProposer, bufferPercent int32) int { - ret := _m.Called(ctx, client, proposer, bufferPercent) +// GetIteration provides a mock function with given fields: rpcParameters, proposer, bufferPercent +func (_m *UtilsCmdInterface) GetIteration(rpcParameters RPC.RPCParameters, proposer types.ElectedProposer, bufferPercent int32) int { + ret := _m.Called(rpcParameters, proposer, bufferPercent) var r0 int - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.ElectedProposer, int32) int); ok { - r0 = rf(ctx, client, proposer, bufferPercent) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.ElectedProposer, int32) int); ok { + r0 = rf(rpcParameters, proposer, bufferPercent) } else { r0 = ret.Get(0).(int) } @@ -874,13 +828,13 @@ func (_m *UtilsCmdInterface) GetIteration(ctx context.Context, client *ethclient return r0 } -// GetJobList provides a mock function with given fields: client -func (_m *UtilsCmdInterface) GetJobList(client *ethclient.Client) error { - ret := _m.Called(client) +// GetJobList provides a mock function with given fields: rpcParameters +func (_m *UtilsCmdInterface) GetJobList(rpcParameters RPC.RPCParameters) error { + ret := _m.Called(rpcParameters) var r0 error - if rf, ok := ret.Get(0).(func(*ethclient.Client) error); ok { - r0 = rf(client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) error); ok { + r0 = rf(rpcParameters) } else { r0 = ret.Error(0) } @@ -888,23 +842,23 @@ func (_m *UtilsCmdInterface) GetJobList(client *ethclient.Client) error { return r0 } -// GetLocalMediansData provides a mock function with given fields: ctx, client, account, epoch, blockNumber, rogueData -func (_m *UtilsCmdInterface) GetLocalMediansData(ctx context.Context, client *ethclient.Client, account types.Account, epoch uint32, blockNumber *big.Int, rogueData types.Rogue) (types.ProposeFileData, error) { - ret := _m.Called(ctx, client, account, epoch, blockNumber, rogueData) +// GetLocalMediansData provides a mock function with given fields: rpcParameters, account, epoch, blockNumber, rogueData +func (_m *UtilsCmdInterface) GetLocalMediansData(rpcParameters RPC.RPCParameters, account types.Account, epoch uint32, blockNumber *big.Int, rogueData types.Rogue) (types.ProposeFileData, error) { + ret := _m.Called(rpcParameters, account, epoch, blockNumber, rogueData) var r0 types.ProposeFileData var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Account, uint32, *big.Int, types.Rogue) (types.ProposeFileData, error)); ok { - return rf(ctx, client, account, epoch, blockNumber, rogueData) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Account, uint32, *big.Int, types.Rogue) (types.ProposeFileData, error)); ok { + return rf(rpcParameters, account, epoch, blockNumber, rogueData) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Account, uint32, *big.Int, types.Rogue) types.ProposeFileData); ok { - r0 = rf(ctx, client, account, epoch, blockNumber, rogueData) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Account, uint32, *big.Int, types.Rogue) types.ProposeFileData); ok { + r0 = rf(rpcParameters, account, epoch, blockNumber, rogueData) } else { r0 = ret.Get(0).(types.ProposeFileData) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, types.Account, uint32, *big.Int, types.Rogue) error); ok { - r1 = rf(ctx, client, account, epoch, blockNumber, rogueData) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, types.Account, uint32, *big.Int, types.Rogue) error); ok { + r1 = rf(rpcParameters, account, epoch, blockNumber, rogueData) } else { r1 = ret.Error(1) } @@ -1080,25 +1034,25 @@ func (_m *UtilsCmdInterface) GetRPCTimeout() (int64, error) { return r0, r1 } -// GetSalt provides a mock function with given fields: ctx, client, epoch -func (_m *UtilsCmdInterface) GetSalt(ctx context.Context, client *ethclient.Client, epoch uint32) ([32]byte, error) { - ret := _m.Called(ctx, client, epoch) +// GetSalt provides a mock function with given fields: rpcParameters, epoch +func (_m *UtilsCmdInterface) GetSalt(rpcParameters RPC.RPCParameters, epoch uint32) ([32]byte, error) { + ret := _m.Called(rpcParameters, epoch) var r0 [32]byte var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) ([32]byte, error)); ok { - return rf(ctx, client, epoch) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) ([32]byte, error)); ok { + return rf(rpcParameters, epoch) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) [32]byte); ok { - r0 = rf(ctx, client, epoch) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) [32]byte); ok { + r0 = rf(rpcParameters, epoch) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([32]byte) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32) error); ok { - r1 = rf(ctx, client, epoch) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32) error); ok { + r1 = rf(rpcParameters, epoch) } else { r1 = ret.Error(1) } @@ -1106,32 +1060,32 @@ func (_m *UtilsCmdInterface) GetSalt(ctx context.Context, client *ethclient.Clie return r0, r1 } -// GetSmallestStakeAndId provides a mock function with given fields: ctx, client, epoch -func (_m *UtilsCmdInterface) GetSmallestStakeAndId(ctx context.Context, client *ethclient.Client, epoch uint32) (*big.Int, uint32, error) { - ret := _m.Called(ctx, client, epoch) +// GetSmallestStakeAndId provides a mock function with given fields: rpcParameters, epoch +func (_m *UtilsCmdInterface) GetSmallestStakeAndId(rpcParameters RPC.RPCParameters, epoch uint32) (*big.Int, uint32, error) { + ret := _m.Called(rpcParameters, epoch) var r0 *big.Int var r1 uint32 var r2 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) (*big.Int, uint32, error)); ok { - return rf(ctx, client, epoch) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) (*big.Int, uint32, error)); ok { + return rf(rpcParameters, epoch) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) *big.Int); ok { - r0 = rf(ctx, client, epoch) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) *big.Int); ok { + r0 = rf(rpcParameters, epoch) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32) uint32); ok { - r1 = rf(ctx, client, epoch) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32) uint32); ok { + r1 = rf(rpcParameters, epoch) } else { r1 = ret.Get(1).(uint32) } - if rf, ok := ret.Get(2).(func(context.Context, *ethclient.Client, uint32) error); ok { - r2 = rf(ctx, client, epoch) + if rf, ok := ret.Get(2).(func(RPC.RPCParameters, uint32) error); ok { + r2 = rf(rpcParameters, epoch) } else { r2 = ret.Error(2) } @@ -1139,25 +1093,25 @@ func (_m *UtilsCmdInterface) GetSmallestStakeAndId(ctx context.Context, client * return r0, r1, r2 } -// GetSortedRevealedValues provides a mock function with given fields: ctx, client, blockNumber, epoch -func (_m *UtilsCmdInterface) GetSortedRevealedValues(ctx context.Context, client *ethclient.Client, blockNumber *big.Int, epoch uint32) (*types.RevealedDataMaps, error) { - ret := _m.Called(ctx, client, blockNumber, epoch) +// GetSortedRevealedValues provides a mock function with given fields: rpcParameters, blockNumber, epoch +func (_m *UtilsCmdInterface) GetSortedRevealedValues(rpcParameters RPC.RPCParameters, blockNumber *big.Int, epoch uint32) (*types.RevealedDataMaps, error) { + ret := _m.Called(rpcParameters, blockNumber, epoch) var r0 *types.RevealedDataMaps var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, *big.Int, uint32) (*types.RevealedDataMaps, error)); ok { - return rf(ctx, client, blockNumber, epoch) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, *big.Int, uint32) (*types.RevealedDataMaps, error)); ok { + return rf(rpcParameters, blockNumber, epoch) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, *big.Int, uint32) *types.RevealedDataMaps); ok { - r0 = rf(ctx, client, blockNumber, epoch) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, *big.Int, uint32) *types.RevealedDataMaps); ok { + r0 = rf(rpcParameters, blockNumber, epoch) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*types.RevealedDataMaps) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, *big.Int, uint32) error); ok { - r1 = rf(ctx, client, blockNumber, epoch) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, *big.Int, uint32) error); ok { + r1 = rf(rpcParameters, blockNumber, epoch) } else { r1 = ret.Error(1) } @@ -1165,13 +1119,13 @@ func (_m *UtilsCmdInterface) GetSortedRevealedValues(ctx context.Context, client return r0, r1 } -// GetStakerInfo provides a mock function with given fields: ctx, client, stakerId -func (_m *UtilsCmdInterface) GetStakerInfo(ctx context.Context, client *ethclient.Client, stakerId uint32) error { - ret := _m.Called(ctx, client, stakerId) +// GetStakerInfo provides a mock function with given fields: rpcParameters, stakerId +func (_m *UtilsCmdInterface) GetStakerInfo(rpcParameters RPC.RPCParameters, stakerId uint32) error { + ret := _m.Called(rpcParameters, stakerId) var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) error); ok { - r0 = rf(ctx, client, stakerId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) error); ok { + r0 = rf(rpcParameters, stakerId) } else { r0 = ret.Error(0) } @@ -1203,13 +1157,13 @@ func (_m *UtilsCmdInterface) GetWaitTime() (int32, error) { return r0, r1 } -// GiveSorted provides a mock function with given fields: ctx, client, blockManager, txnArgs, epoch, assetId, sortedStakers -func (_m *UtilsCmdInterface) GiveSorted(ctx context.Context, client *ethclient.Client, blockManager *bindings.BlockManager, txnArgs types.TransactionOptions, epoch uint32, assetId uint16, sortedStakers []*big.Int) error { - ret := _m.Called(ctx, client, blockManager, txnArgs, epoch, assetId, sortedStakers) +// GiveSorted provides a mock function with given fields: rpcParameters, txnArgs, epoch, assetId, sortedStakers +func (_m *UtilsCmdInterface) GiveSorted(rpcParameters RPC.RPCParameters, txnArgs types.TransactionOptions, epoch uint32, assetId uint16, sortedStakers []*big.Int) error { + ret := _m.Called(rpcParameters, txnArgs, epoch, assetId, sortedStakers) var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, *bindings.BlockManager, types.TransactionOptions, uint32, uint16, []*big.Int) error); ok { - r0 = rf(ctx, client, blockManager, txnArgs, epoch, assetId, sortedStakers) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.TransactionOptions, uint32, uint16, []*big.Int) error); ok { + r0 = rf(rpcParameters, txnArgs, epoch, assetId, sortedStakers) } else { r0 = ret.Error(0) } @@ -1217,18 +1171,18 @@ func (_m *UtilsCmdInterface) GiveSorted(ctx context.Context, client *ethclient.C return r0 } -// HandleBlock provides a mock function with given fields: client, account, stakerId, header, config, commitParams, rogueData, backupNodeActionsToIgnore -func (_m *UtilsCmdInterface) HandleBlock(client *ethclient.Client, account types.Account, stakerId uint32, header *coretypes.Header, config types.Configurations, commitParams *types.CommitParams, rogueData types.Rogue, backupNodeActionsToIgnore []string) { - _m.Called(client, account, stakerId, header, config, commitParams, rogueData, backupNodeActionsToIgnore) +// HandleBlock provides a mock function with given fields: rpcParameters, account, stakerId, header, config, commitParams, rogueData, backupNodeActionsToIgnore +func (_m *UtilsCmdInterface) HandleBlock(rpcParameters RPC.RPCParameters, account types.Account, stakerId uint32, header *coretypes.Header, config types.Configurations, commitParams *types.CommitParams, rogueData types.Rogue, backupNodeActionsToIgnore []string) { + _m.Called(rpcParameters, account, stakerId, header, config, commitParams, rogueData, backupNodeActionsToIgnore) } -// HandleClaimBounty provides a mock function with given fields: client, config, account -func (_m *UtilsCmdInterface) HandleClaimBounty(client *ethclient.Client, config types.Configurations, account types.Account) error { - ret := _m.Called(client, config, account) +// HandleClaimBounty provides a mock function with given fields: rpcParameters, config, account +func (_m *UtilsCmdInterface) HandleClaimBounty(rpcParameters RPC.RPCParameters, config types.Configurations, account types.Account) error { + ret := _m.Called(rpcParameters, config, account) var r0 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations, types.Account) error); ok { - r0 = rf(client, config, account) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.Account) error); ok { + r0 = rf(rpcParameters, config, account) } else { r0 = ret.Error(0) } @@ -1236,23 +1190,23 @@ func (_m *UtilsCmdInterface) HandleClaimBounty(client *ethclient.Client, config return r0 } -// HandleCommitState provides a mock function with given fields: ctx, client, epoch, seed, commitParams, rogueData -func (_m *UtilsCmdInterface) HandleCommitState(ctx context.Context, client *ethclient.Client, epoch uint32, seed []byte, commitParams *types.CommitParams, rogueData types.Rogue) (types.CommitData, error) { - ret := _m.Called(ctx, client, epoch, seed, commitParams, rogueData) +// HandleCommitState provides a mock function with given fields: rpcParameters, epoch, seed, commitParams, rogueData +func (_m *UtilsCmdInterface) HandleCommitState(rpcParameters RPC.RPCParameters, epoch uint32, seed []byte, commitParams *types.CommitParams, rogueData types.Rogue) (types.CommitData, error) { + ret := _m.Called(rpcParameters, epoch, seed, commitParams, rogueData) var r0 types.CommitData var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, []byte, *types.CommitParams, types.Rogue) (types.CommitData, error)); ok { - return rf(ctx, client, epoch, seed, commitParams, rogueData) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32, []byte, *types.CommitParams, types.Rogue) (types.CommitData, error)); ok { + return rf(rpcParameters, epoch, seed, commitParams, rogueData) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, []byte, *types.CommitParams, types.Rogue) types.CommitData); ok { - r0 = rf(ctx, client, epoch, seed, commitParams, rogueData) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32, []byte, *types.CommitParams, types.Rogue) types.CommitData); ok { + r0 = rf(rpcParameters, epoch, seed, commitParams, rogueData) } else { r0 = ret.Get(0).(types.CommitData) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32, []byte, *types.CommitParams, types.Rogue) error); ok { - r1 = rf(ctx, client, epoch, seed, commitParams, rogueData) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32, []byte, *types.CommitParams, types.Rogue) error); ok { + r1 = rf(rpcParameters, epoch, seed, commitParams, rogueData) } else { r1 = ret.Error(1) } @@ -1260,13 +1214,13 @@ func (_m *UtilsCmdInterface) HandleCommitState(ctx context.Context, client *ethc return r0, r1 } -// HandleDispute provides a mock function with given fields: ctx, client, config, account, epoch, blockNumber, rogueData, backupNodeActionsToIgnore -func (_m *UtilsCmdInterface) HandleDispute(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, blockNumber *big.Int, rogueData types.Rogue, backupNodeActionsToIgnore []string) error { - ret := _m.Called(ctx, client, config, account, epoch, blockNumber, rogueData, backupNodeActionsToIgnore) +// HandleDispute provides a mock function with given fields: rpcParameters, config, account, epoch, blockNumber, rogueData, backupNodeActionsToIgnore +func (_m *UtilsCmdInterface) HandleDispute(rpcParameters RPC.RPCParameters, config types.Configurations, account types.Account, epoch uint32, blockNumber *big.Int, rogueData types.Rogue, backupNodeActionsToIgnore []string) error { + ret := _m.Called(rpcParameters, config, account, epoch, blockNumber, rogueData, backupNodeActionsToIgnore) var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Configurations, types.Account, uint32, *big.Int, types.Rogue, []string) error); ok { - r0 = rf(ctx, client, config, account, epoch, blockNumber, rogueData, backupNodeActionsToIgnore) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.Account, uint32, *big.Int, types.Rogue, []string) error); ok { + r0 = rf(rpcParameters, config, account, epoch, blockNumber, rogueData, backupNodeActionsToIgnore) } else { r0 = ret.Error(0) } @@ -1279,25 +1233,25 @@ func (_m *UtilsCmdInterface) HandleExit() { _m.Called() } -// HandleUnstakeLock provides a mock function with given fields: ctx, client, account, configurations, stakerId -func (_m *UtilsCmdInterface) HandleUnstakeLock(ctx context.Context, client *ethclient.Client, account types.Account, configurations types.Configurations, stakerId uint32) (common.Hash, error) { - ret := _m.Called(ctx, client, account, configurations, stakerId) +// HandleUnstakeLock provides a mock function with given fields: rpcParameters, account, configurations, stakerId +func (_m *UtilsCmdInterface) HandleUnstakeLock(rpcParameters RPC.RPCParameters, account types.Account, configurations types.Configurations, stakerId uint32) (common.Hash, error) { + ret := _m.Called(rpcParameters, account, configurations, stakerId) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Account, types.Configurations, uint32) (common.Hash, error)); ok { - return rf(ctx, client, account, configurations, stakerId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Account, types.Configurations, uint32) (common.Hash, error)); ok { + return rf(rpcParameters, account, configurations, stakerId) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Account, types.Configurations, uint32) common.Hash); ok { - r0 = rf(ctx, client, account, configurations, stakerId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Account, types.Configurations, uint32) common.Hash); ok { + r0 = rf(rpcParameters, account, configurations, stakerId) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, types.Account, types.Configurations, uint32) error); ok { - r1 = rf(ctx, client, account, configurations, stakerId) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, types.Account, types.Configurations, uint32) error); ok { + r1 = rf(rpcParameters, account, configurations, stakerId) } else { r1 = ret.Error(1) } @@ -1305,25 +1259,25 @@ func (_m *UtilsCmdInterface) HandleUnstakeLock(ctx context.Context, client *ethc return r0, r1 } -// HandleWithdrawLock provides a mock function with given fields: ctx, client, account, configurations, stakerId -func (_m *UtilsCmdInterface) HandleWithdrawLock(ctx context.Context, client *ethclient.Client, account types.Account, configurations types.Configurations, stakerId uint32) (common.Hash, error) { - ret := _m.Called(ctx, client, account, configurations, stakerId) +// HandleWithdrawLock provides a mock function with given fields: rpcParameters, account, configurations, stakerId +func (_m *UtilsCmdInterface) HandleWithdrawLock(rpcParameters RPC.RPCParameters, account types.Account, configurations types.Configurations, stakerId uint32) (common.Hash, error) { + ret := _m.Called(rpcParameters, account, configurations, stakerId) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Account, types.Configurations, uint32) (common.Hash, error)); ok { - return rf(ctx, client, account, configurations, stakerId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Account, types.Configurations, uint32) (common.Hash, error)); ok { + return rf(rpcParameters, account, configurations, stakerId) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Account, types.Configurations, uint32) common.Hash); ok { - r0 = rf(ctx, client, account, configurations, stakerId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Account, types.Configurations, uint32) common.Hash); ok { + r0 = rf(rpcParameters, account, configurations, stakerId) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, types.Account, types.Configurations, uint32) error); ok { - r1 = rf(ctx, client, account, configurations, stakerId) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, types.Account, types.Configurations, uint32) error); ok { + r1 = rf(rpcParameters, account, configurations, stakerId) } else { r1 = ret.Error(1) } @@ -1355,25 +1309,25 @@ func (_m *UtilsCmdInterface) ImportAccount() (accounts.Account, error) { return r0, r1 } -// IndexRevealEventsOfCurrentEpoch provides a mock function with given fields: ctx, client, blockNumber, epoch -func (_m *UtilsCmdInterface) IndexRevealEventsOfCurrentEpoch(ctx context.Context, client *ethclient.Client, blockNumber *big.Int, epoch uint32) ([]types.RevealedStruct, error) { - ret := _m.Called(ctx, client, blockNumber, epoch) +// IndexRevealEventsOfCurrentEpoch provides a mock function with given fields: rpcParameters, blockNumber, epoch +func (_m *UtilsCmdInterface) IndexRevealEventsOfCurrentEpoch(rpcParameters RPC.RPCParameters, blockNumber *big.Int, epoch uint32) ([]types.RevealedStruct, error) { + ret := _m.Called(rpcParameters, blockNumber, epoch) var r0 []types.RevealedStruct var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, *big.Int, uint32) ([]types.RevealedStruct, error)); ok { - return rf(ctx, client, blockNumber, epoch) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, *big.Int, uint32) ([]types.RevealedStruct, error)); ok { + return rf(rpcParameters, blockNumber, epoch) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, *big.Int, uint32) []types.RevealedStruct); ok { - r0 = rf(ctx, client, blockNumber, epoch) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, *big.Int, uint32) []types.RevealedStruct); ok { + r0 = rf(rpcParameters, blockNumber, epoch) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]types.RevealedStruct) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, *big.Int, uint32) error); ok { - r1 = rf(ctx, client, blockNumber, epoch) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, *big.Int, uint32) error); ok { + r1 = rf(rpcParameters, blockNumber, epoch) } else { r1 = ret.Error(1) } @@ -1381,43 +1335,43 @@ func (_m *UtilsCmdInterface) IndexRevealEventsOfCurrentEpoch(ctx context.Context return r0, r1 } -// InitJobAndCollectionCache provides a mock function with given fields: ctx, client -func (_m *UtilsCmdInterface) InitJobAndCollectionCache(ctx context.Context, client *ethclient.Client) (*cache.JobsCache, *cache.CollectionsCache, *big.Int, error) { - ret := _m.Called(ctx, client) +// InitJobAndCollectionCache provides a mock function with given fields: rpcParameters +func (_m *UtilsCmdInterface) InitJobAndCollectionCache(rpcParameters RPC.RPCParameters) (*cache.JobsCache, *cache.CollectionsCache, *big.Int, error) { + ret := _m.Called(rpcParameters) var r0 *cache.JobsCache var r1 *cache.CollectionsCache var r2 *big.Int var r3 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) (*cache.JobsCache, *cache.CollectionsCache, *big.Int, error)); ok { - return rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) (*cache.JobsCache, *cache.CollectionsCache, *big.Int, error)); ok { + return rf(rpcParameters) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) *cache.JobsCache); ok { - r0 = rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) *cache.JobsCache); ok { + r0 = rf(rpcParameters) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*cache.JobsCache) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) *cache.CollectionsCache); ok { - r1 = rf(ctx, client) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters) *cache.CollectionsCache); ok { + r1 = rf(rpcParameters) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*cache.CollectionsCache) } } - if rf, ok := ret.Get(2).(func(context.Context, *ethclient.Client) *big.Int); ok { - r2 = rf(ctx, client) + if rf, ok := ret.Get(2).(func(RPC.RPCParameters) *big.Int); ok { + r2 = rf(rpcParameters) } else { if ret.Get(2) != nil { r2 = ret.Get(2).(*big.Int) } } - if rf, ok := ret.Get(3).(func(context.Context, *ethclient.Client) error); ok { - r3 = rf(ctx, client) + if rf, ok := ret.Get(3).(func(RPC.RPCParameters) error); ok { + r3 = rf(rpcParameters) } else { r3 = ret.Error(3) } @@ -1425,13 +1379,13 @@ func (_m *UtilsCmdInterface) InitJobAndCollectionCache(ctx context.Context, clie return r0, r1, r2, r3 } -// InitiateCommit provides a mock function with given fields: ctx, client, config, account, epoch, stakerId, latestHeader, commitParams, stateBuffer, rogueData -func (_m *UtilsCmdInterface) InitiateCommit(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, stakerId uint32, latestHeader *coretypes.Header, commitParams *types.CommitParams, stateBuffer uint64, rogueData types.Rogue) error { - ret := _m.Called(ctx, client, config, account, epoch, stakerId, latestHeader, commitParams, stateBuffer, rogueData) +// InitiateCommit provides a mock function with given fields: rpcParameters, config, account, epoch, stakerId, latestHeader, commitParams, stateBuffer, rogueData +func (_m *UtilsCmdInterface) InitiateCommit(rpcParameters RPC.RPCParameters, config types.Configurations, account types.Account, epoch uint32, stakerId uint32, latestHeader *coretypes.Header, commitParams *types.CommitParams, stateBuffer uint64, rogueData types.Rogue) error { + ret := _m.Called(rpcParameters, config, account, epoch, stakerId, latestHeader, commitParams, stateBuffer, rogueData) var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Configurations, types.Account, uint32, uint32, *coretypes.Header, *types.CommitParams, uint64, types.Rogue) error); ok { - r0 = rf(ctx, client, config, account, epoch, stakerId, latestHeader, commitParams, stateBuffer, rogueData) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.Account, uint32, uint32, *coretypes.Header, *types.CommitParams, uint64, types.Rogue) error); ok { + r0 = rf(rpcParameters, config, account, epoch, stakerId, latestHeader, commitParams, stateBuffer, rogueData) } else { r0 = ret.Error(0) } @@ -1439,13 +1393,13 @@ func (_m *UtilsCmdInterface) InitiateCommit(ctx context.Context, client *ethclie return r0 } -// InitiatePropose provides a mock function with given fields: ctx, client, config, account, epoch, staker, latestHeader, stateBuffer, rogueData -func (_m *UtilsCmdInterface) InitiatePropose(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, latestHeader *coretypes.Header, stateBuffer uint64, rogueData types.Rogue) error { - ret := _m.Called(ctx, client, config, account, epoch, staker, latestHeader, stateBuffer, rogueData) +// InitiatePropose provides a mock function with given fields: rpcParameters, config, account, epoch, staker, latestHeader, stateBuffer, rogueData +func (_m *UtilsCmdInterface) InitiatePropose(rpcParameters RPC.RPCParameters, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, latestHeader *coretypes.Header, stateBuffer uint64, rogueData types.Rogue) error { + ret := _m.Called(rpcParameters, config, account, epoch, staker, latestHeader, stateBuffer, rogueData) var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Configurations, types.Account, uint32, bindings.StructsStaker, *coretypes.Header, uint64, types.Rogue) error); ok { - r0 = rf(ctx, client, config, account, epoch, staker, latestHeader, stateBuffer, rogueData) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.Account, uint32, bindings.StructsStaker, *coretypes.Header, uint64, types.Rogue) error); ok { + r0 = rf(rpcParameters, config, account, epoch, staker, latestHeader, stateBuffer, rogueData) } else { r0 = ret.Error(0) } @@ -1453,13 +1407,13 @@ func (_m *UtilsCmdInterface) InitiatePropose(ctx context.Context, client *ethcli return r0 } -// InitiateReveal provides a mock function with given fields: ctx, client, config, account, epoch, staker, latestHeader, stateBuffer, rogueData -func (_m *UtilsCmdInterface) InitiateReveal(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, latestHeader *coretypes.Header, stateBuffer uint64, rogueData types.Rogue) error { - ret := _m.Called(ctx, client, config, account, epoch, staker, latestHeader, stateBuffer, rogueData) +// InitiateReveal provides a mock function with given fields: rpcParameters, config, account, epoch, staker, latestHeader, stateBuffer, rogueData +func (_m *UtilsCmdInterface) InitiateReveal(rpcParameters RPC.RPCParameters, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, latestHeader *coretypes.Header, stateBuffer uint64, rogueData types.Rogue) error { + ret := _m.Called(rpcParameters, config, account, epoch, staker, latestHeader, stateBuffer, rogueData) var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Configurations, types.Account, uint32, bindings.StructsStaker, *coretypes.Header, uint64, types.Rogue) error); ok { - r0 = rf(ctx, client, config, account, epoch, staker, latestHeader, stateBuffer, rogueData) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.Account, uint32, bindings.StructsStaker, *coretypes.Header, uint64, types.Rogue) error); ok { + r0 = rf(rpcParameters, config, account, epoch, staker, latestHeader, stateBuffer, rogueData) } else { r0 = ret.Error(0) } @@ -1467,25 +1421,25 @@ func (_m *UtilsCmdInterface) InitiateReveal(ctx context.Context, client *ethclie return r0 } -// InitiateWithdraw provides a mock function with given fields: client, txnOpts, stakerId -func (_m *UtilsCmdInterface) InitiateWithdraw(client *ethclient.Client, txnOpts *bind.TransactOpts, stakerId uint32) (common.Hash, error) { - ret := _m.Called(client, txnOpts, stakerId) +// InitiateWithdraw provides a mock function with given fields: rpcParameters, txnOpts, stakerId +func (_m *UtilsCmdInterface) InitiateWithdraw(rpcParameters RPC.RPCParameters, txnOpts *bind.TransactOpts, stakerId uint32) (common.Hash, error) { + ret := _m.Called(rpcParameters, txnOpts, stakerId) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32) (common.Hash, error)); ok { - return rf(client, txnOpts, stakerId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, *bind.TransactOpts, uint32) (common.Hash, error)); ok { + return rf(rpcParameters, txnOpts, stakerId) } - if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32) common.Hash); ok { - r0 = rf(client, txnOpts, stakerId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, *bind.TransactOpts, uint32) common.Hash); ok { + r0 = rf(rpcParameters, txnOpts, stakerId) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint32) error); ok { - r1 = rf(client, txnOpts, stakerId) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, *bind.TransactOpts, uint32) error); ok { + r1 = rf(rpcParameters, txnOpts, stakerId) } else { r1 = ret.Error(1) } @@ -1533,43 +1487,43 @@ func (_m *UtilsCmdInterface) ListAccounts() ([]accounts.Account, error) { return r0, r1 } -// MakeBlock provides a mock function with given fields: ctx, client, blockNumber, epoch, rogueData -func (_m *UtilsCmdInterface) MakeBlock(ctx context.Context, client *ethclient.Client, blockNumber *big.Int, epoch uint32, rogueData types.Rogue) ([]*big.Int, []uint16, *types.RevealedDataMaps, error) { - ret := _m.Called(ctx, client, blockNumber, epoch, rogueData) +// MakeBlock provides a mock function with given fields: rpcParameters, blockNumber, epoch, rogueData +func (_m *UtilsCmdInterface) MakeBlock(rpcParameters RPC.RPCParameters, blockNumber *big.Int, epoch uint32, rogueData types.Rogue) ([]*big.Int, []uint16, *types.RevealedDataMaps, error) { + ret := _m.Called(rpcParameters, blockNumber, epoch, rogueData) var r0 []*big.Int var r1 []uint16 var r2 *types.RevealedDataMaps var r3 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, *big.Int, uint32, types.Rogue) ([]*big.Int, []uint16, *types.RevealedDataMaps, error)); ok { - return rf(ctx, client, blockNumber, epoch, rogueData) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, *big.Int, uint32, types.Rogue) ([]*big.Int, []uint16, *types.RevealedDataMaps, error)); ok { + return rf(rpcParameters, blockNumber, epoch, rogueData) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, *big.Int, uint32, types.Rogue) []*big.Int); ok { - r0 = rf(ctx, client, blockNumber, epoch, rogueData) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, *big.Int, uint32, types.Rogue) []*big.Int); ok { + r0 = rf(rpcParameters, blockNumber, epoch, rogueData) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*big.Int) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, *big.Int, uint32, types.Rogue) []uint16); ok { - r1 = rf(ctx, client, blockNumber, epoch, rogueData) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, *big.Int, uint32, types.Rogue) []uint16); ok { + r1 = rf(rpcParameters, blockNumber, epoch, rogueData) } else { if ret.Get(1) != nil { r1 = ret.Get(1).([]uint16) } } - if rf, ok := ret.Get(2).(func(context.Context, *ethclient.Client, *big.Int, uint32, types.Rogue) *types.RevealedDataMaps); ok { - r2 = rf(ctx, client, blockNumber, epoch, rogueData) + if rf, ok := ret.Get(2).(func(RPC.RPCParameters, *big.Int, uint32, types.Rogue) *types.RevealedDataMaps); ok { + r2 = rf(rpcParameters, blockNumber, epoch, rogueData) } else { if ret.Get(2) != nil { r2 = ret.Get(2).(*types.RevealedDataMaps) } } - if rf, ok := ret.Get(3).(func(context.Context, *ethclient.Client, *big.Int, uint32, types.Rogue) error); ok { - r3 = rf(ctx, client, blockNumber, epoch, rogueData) + if rf, ok := ret.Get(3).(func(RPC.RPCParameters, *big.Int, uint32, types.Rogue) error); ok { + r3 = rf(rpcParameters, blockNumber, epoch, rogueData) } else { r3 = ret.Error(3) } @@ -1577,25 +1531,25 @@ func (_m *UtilsCmdInterface) MakeBlock(ctx context.Context, client *ethclient.Cl return r0, r1, r2, r3 } -// ModifyCollectionStatus provides a mock function with given fields: ctx, client, config, modifyCollectionInput -func (_m *UtilsCmdInterface) ModifyCollectionStatus(ctx context.Context, client *ethclient.Client, config types.Configurations, modifyCollectionInput types.ModifyCollectionInput) (common.Hash, error) { - ret := _m.Called(ctx, client, config, modifyCollectionInput) +// ModifyCollectionStatus provides a mock function with given fields: rpcParameters, config, modifyCollectionInput +func (_m *UtilsCmdInterface) ModifyCollectionStatus(rpcParameters RPC.RPCParameters, config types.Configurations, modifyCollectionInput types.ModifyCollectionInput) (common.Hash, error) { + ret := _m.Called(rpcParameters, config, modifyCollectionInput) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Configurations, types.ModifyCollectionInput) (common.Hash, error)); ok { - return rf(ctx, client, config, modifyCollectionInput) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.ModifyCollectionInput) (common.Hash, error)); ok { + return rf(rpcParameters, config, modifyCollectionInput) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Configurations, types.ModifyCollectionInput) common.Hash); ok { - r0 = rf(ctx, client, config, modifyCollectionInput) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.ModifyCollectionInput) common.Hash); ok { + r0 = rf(rpcParameters, config, modifyCollectionInput) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, types.Configurations, types.ModifyCollectionInput) error); ok { - r1 = rf(ctx, client, config, modifyCollectionInput) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, types.Configurations, types.ModifyCollectionInput) error); ok { + r1 = rf(rpcParameters, config, modifyCollectionInput) } else { r1 = ret.Error(1) } @@ -1603,13 +1557,13 @@ func (_m *UtilsCmdInterface) ModifyCollectionStatus(ctx context.Context, client return r0, r1 } -// Propose provides a mock function with given fields: ctx, client, config, account, staker, epoch, latestHeader, stateBuffer, rogueData -func (_m *UtilsCmdInterface) Propose(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, staker bindings.StructsStaker, epoch uint32, latestHeader *coretypes.Header, stateBuffer uint64, rogueData types.Rogue) error { - ret := _m.Called(ctx, client, config, account, staker, epoch, latestHeader, stateBuffer, rogueData) +// Propose provides a mock function with given fields: rpcParameters, config, account, staker, epoch, latestHeader, stateBuffer, rogueData +func (_m *UtilsCmdInterface) Propose(rpcParameters RPC.RPCParameters, config types.Configurations, account types.Account, staker bindings.StructsStaker, epoch uint32, latestHeader *coretypes.Header, stateBuffer uint64, rogueData types.Rogue) error { + ret := _m.Called(rpcParameters, config, account, staker, epoch, latestHeader, stateBuffer, rogueData) var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Configurations, types.Account, bindings.StructsStaker, uint32, *coretypes.Header, uint64, types.Rogue) error); ok { - r0 = rf(ctx, client, config, account, staker, epoch, latestHeader, stateBuffer, rogueData) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.Account, bindings.StructsStaker, uint32, *coretypes.Header, uint64, types.Rogue) error); ok { + r0 = rf(rpcParameters, config, account, staker, epoch, latestHeader, stateBuffer, rogueData) } else { r0 = ret.Error(0) } @@ -1617,30 +1571,30 @@ func (_m *UtilsCmdInterface) Propose(ctx context.Context, client *ethclient.Clie return r0 } -// ResetDispute provides a mock function with given fields: client, blockManager, txnOpts, epoch -func (_m *UtilsCmdInterface) ResetDispute(client *ethclient.Client, blockManager *bindings.BlockManager, txnOpts *bind.TransactOpts, epoch uint32) { - _m.Called(client, blockManager, txnOpts, epoch) +// ResetDispute provides a mock function with given fields: rpcParameters, txnOpts, epoch +func (_m *UtilsCmdInterface) ResetDispute(rpcParameters RPC.RPCParameters, txnOpts *bind.TransactOpts, epoch uint32) { + _m.Called(rpcParameters, txnOpts, epoch) } -// ResetUnstakeLock provides a mock function with given fields: client, config, extendLockInput -func (_m *UtilsCmdInterface) ResetUnstakeLock(client *ethclient.Client, config types.Configurations, extendLockInput types.ExtendLockInput) (common.Hash, error) { - ret := _m.Called(client, config, extendLockInput) +// ResetUnstakeLock provides a mock function with given fields: rpcParameters, config, extendLockInput +func (_m *UtilsCmdInterface) ResetUnstakeLock(rpcParameters RPC.RPCParameters, config types.Configurations, extendLockInput types.ExtendLockInput) (common.Hash, error) { + ret := _m.Called(rpcParameters, config, extendLockInput) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations, types.ExtendLockInput) (common.Hash, error)); ok { - return rf(client, config, extendLockInput) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.ExtendLockInput) (common.Hash, error)); ok { + return rf(rpcParameters, config, extendLockInput) } - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations, types.ExtendLockInput) common.Hash); ok { - r0 = rf(client, config, extendLockInput) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.ExtendLockInput) common.Hash); ok { + r0 = rf(rpcParameters, config, extendLockInput) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, types.Configurations, types.ExtendLockInput) error); ok { - r1 = rf(client, config, extendLockInput) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, types.Configurations, types.ExtendLockInput) error); ok { + r1 = rf(rpcParameters, config, extendLockInput) } else { r1 = ret.Error(1) } @@ -1648,25 +1602,25 @@ func (_m *UtilsCmdInterface) ResetUnstakeLock(client *ethclient.Client, config t return r0, r1 } -// Reveal provides a mock function with given fields: ctx, client, config, account, epoch, latestHeader, stateBuffer, commitData, signature -func (_m *UtilsCmdInterface) Reveal(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, latestHeader *coretypes.Header, stateBuffer uint64, commitData types.CommitData, signature []byte) (common.Hash, error) { - ret := _m.Called(ctx, client, config, account, epoch, latestHeader, stateBuffer, commitData, signature) +// Reveal provides a mock function with given fields: rpcParameters, config, account, epoch, latestHeader, stateBuffer, commitData, signature +func (_m *UtilsCmdInterface) Reveal(rpcParameters RPC.RPCParameters, config types.Configurations, account types.Account, epoch uint32, latestHeader *coretypes.Header, stateBuffer uint64, commitData types.CommitData, signature []byte) (common.Hash, error) { + ret := _m.Called(rpcParameters, config, account, epoch, latestHeader, stateBuffer, commitData, signature) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Configurations, types.Account, uint32, *coretypes.Header, uint64, types.CommitData, []byte) (common.Hash, error)); ok { - return rf(ctx, client, config, account, epoch, latestHeader, stateBuffer, commitData, signature) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.Account, uint32, *coretypes.Header, uint64, types.CommitData, []byte) (common.Hash, error)); ok { + return rf(rpcParameters, config, account, epoch, latestHeader, stateBuffer, commitData, signature) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Configurations, types.Account, uint32, *coretypes.Header, uint64, types.CommitData, []byte) common.Hash); ok { - r0 = rf(ctx, client, config, account, epoch, latestHeader, stateBuffer, commitData, signature) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.Account, uint32, *coretypes.Header, uint64, types.CommitData, []byte) common.Hash); ok { + r0 = rf(rpcParameters, config, account, epoch, latestHeader, stateBuffer, commitData, signature) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, types.Configurations, types.Account, uint32, *coretypes.Header, uint64, types.CommitData, []byte) error); ok { - r1 = rf(ctx, client, config, account, epoch, latestHeader, stateBuffer, commitData, signature) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, types.Configurations, types.Account, uint32, *coretypes.Header, uint64, types.CommitData, []byte) error); ok { + r1 = rf(rpcParameters, config, account, epoch, latestHeader, stateBuffer, commitData, signature) } else { r1 = ret.Error(1) } @@ -1688,25 +1642,25 @@ func (_m *UtilsCmdInterface) SetConfig(flagSet *pflag.FlagSet) error { return r0 } -// SetDelegation provides a mock function with given fields: ctx, client, config, delegationInput -func (_m *UtilsCmdInterface) SetDelegation(ctx context.Context, client *ethclient.Client, config types.Configurations, delegationInput types.SetDelegationInput) (common.Hash, error) { - ret := _m.Called(ctx, client, config, delegationInput) +// SetDelegation provides a mock function with given fields: rpcParameters, config, delegationInput +func (_m *UtilsCmdInterface) SetDelegation(rpcParameters RPC.RPCParameters, config types.Configurations, delegationInput types.SetDelegationInput) (common.Hash, error) { + ret := _m.Called(rpcParameters, config, delegationInput) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Configurations, types.SetDelegationInput) (common.Hash, error)); ok { - return rf(ctx, client, config, delegationInput) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.SetDelegationInput) (common.Hash, error)); ok { + return rf(rpcParameters, config, delegationInput) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Configurations, types.SetDelegationInput) common.Hash); ok { - r0 = rf(ctx, client, config, delegationInput) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.SetDelegationInput) common.Hash); ok { + r0 = rf(rpcParameters, config, delegationInput) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, types.Configurations, types.SetDelegationInput) error); ok { - r1 = rf(ctx, client, config, delegationInput) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, types.Configurations, types.SetDelegationInput) error); ok { + r1 = rf(rpcParameters, config, delegationInput) } else { r1 = ret.Error(1) } @@ -1714,25 +1668,25 @@ func (_m *UtilsCmdInterface) SetDelegation(ctx context.Context, client *ethclien return r0, r1 } -// StakeCoins provides a mock function with given fields: txnArgs -func (_m *UtilsCmdInterface) StakeCoins(txnArgs types.TransactionOptions) (common.Hash, error) { - ret := _m.Called(txnArgs) +// StakeCoins provides a mock function with given fields: rpcParameters, txnArgs +func (_m *UtilsCmdInterface) StakeCoins(rpcParameters RPC.RPCParameters, txnArgs types.TransactionOptions) (common.Hash, error) { + ret := _m.Called(rpcParameters, txnArgs) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(types.TransactionOptions) (common.Hash, error)); ok { - return rf(txnArgs) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.TransactionOptions) (common.Hash, error)); ok { + return rf(rpcParameters, txnArgs) } - if rf, ok := ret.Get(0).(func(types.TransactionOptions) common.Hash); ok { - r0 = rf(txnArgs) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.TransactionOptions) common.Hash); ok { + r0 = rf(rpcParameters, txnArgs) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(types.TransactionOptions) error); ok { - r1 = rf(txnArgs) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, types.TransactionOptions) error); ok { + r1 = rf(rpcParameters, txnArgs) } else { r1 = ret.Error(1) } @@ -1740,13 +1694,13 @@ func (_m *UtilsCmdInterface) StakeCoins(txnArgs types.TransactionOptions) (commo return r0, r1 } -// StoreBountyId provides a mock function with given fields: ctx, client, account -func (_m *UtilsCmdInterface) StoreBountyId(ctx context.Context, client *ethclient.Client, account types.Account) error { - ret := _m.Called(ctx, client, account) +// StoreBountyId provides a mock function with given fields: rpcParameters, account +func (_m *UtilsCmdInterface) StoreBountyId(rpcParameters RPC.RPCParameters, account types.Account) error { + ret := _m.Called(rpcParameters, account) var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Account) error); ok { - r0 = rf(ctx, client, account) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Account) error); ok { + r0 = rf(rpcParameters, account) } else { r0 = ret.Error(0) } @@ -1754,25 +1708,25 @@ func (_m *UtilsCmdInterface) StoreBountyId(ctx context.Context, client *ethclien return r0 } -// Transfer provides a mock function with given fields: client, config, transferInput -func (_m *UtilsCmdInterface) Transfer(client *ethclient.Client, config types.Configurations, transferInput types.TransferInput) (common.Hash, error) { - ret := _m.Called(client, config, transferInput) +// Transfer provides a mock function with given fields: rpcParameters, config, transferInput +func (_m *UtilsCmdInterface) Transfer(rpcParameters RPC.RPCParameters, config types.Configurations, transferInput types.TransferInput) (common.Hash, error) { + ret := _m.Called(rpcParameters, config, transferInput) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations, types.TransferInput) (common.Hash, error)); ok { - return rf(client, config, transferInput) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.TransferInput) (common.Hash, error)); ok { + return rf(rpcParameters, config, transferInput) } - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations, types.TransferInput) common.Hash); ok { - r0 = rf(client, config, transferInput) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.TransferInput) common.Hash); ok { + r0 = rf(rpcParameters, config, transferInput) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, types.Configurations, types.TransferInput) error); ok { - r1 = rf(client, config, transferInput) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, types.Configurations, types.TransferInput) error); ok { + r1 = rf(rpcParameters, config, transferInput) } else { r1 = ret.Error(1) } @@ -1780,25 +1734,25 @@ func (_m *UtilsCmdInterface) Transfer(client *ethclient.Client, config types.Con return r0, r1 } -// UnlockWithdraw provides a mock function with given fields: client, txnOpts, stakerId -func (_m *UtilsCmdInterface) UnlockWithdraw(client *ethclient.Client, txnOpts *bind.TransactOpts, stakerId uint32) (common.Hash, error) { - ret := _m.Called(client, txnOpts, stakerId) +// UnlockWithdraw provides a mock function with given fields: rpcParameters, txnOpts, stakerId +func (_m *UtilsCmdInterface) UnlockWithdraw(rpcParameters RPC.RPCParameters, txnOpts *bind.TransactOpts, stakerId uint32) (common.Hash, error) { + ret := _m.Called(rpcParameters, txnOpts, stakerId) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32) (common.Hash, error)); ok { - return rf(client, txnOpts, stakerId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, *bind.TransactOpts, uint32) (common.Hash, error)); ok { + return rf(rpcParameters, txnOpts, stakerId) } - if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32) common.Hash); ok { - r0 = rf(client, txnOpts, stakerId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, *bind.TransactOpts, uint32) common.Hash); ok { + r0 = rf(rpcParameters, txnOpts, stakerId) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint32) error); ok { - r1 = rf(client, txnOpts, stakerId) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, *bind.TransactOpts, uint32) error); ok { + r1 = rf(rpcParameters, txnOpts, stakerId) } else { r1 = ret.Error(1) } @@ -1806,25 +1760,25 @@ func (_m *UtilsCmdInterface) UnlockWithdraw(client *ethclient.Client, txnOpts *b return r0, r1 } -// Unstake provides a mock function with given fields: ctx, config, client, input -func (_m *UtilsCmdInterface) Unstake(ctx context.Context, config types.Configurations, client *ethclient.Client, input types.UnstakeInput) (common.Hash, error) { - ret := _m.Called(ctx, config, client, input) +// Unstake provides a mock function with given fields: rpcParameters, config, input +func (_m *UtilsCmdInterface) Unstake(rpcParameters RPC.RPCParameters, config types.Configurations, input types.UnstakeInput) (common.Hash, error) { + ret := _m.Called(rpcParameters, config, input) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(context.Context, types.Configurations, *ethclient.Client, types.UnstakeInput) (common.Hash, error)); ok { - return rf(ctx, config, client, input) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.UnstakeInput) (common.Hash, error)); ok { + return rf(rpcParameters, config, input) } - if rf, ok := ret.Get(0).(func(context.Context, types.Configurations, *ethclient.Client, types.UnstakeInput) common.Hash); ok { - r0 = rf(ctx, config, client, input) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.UnstakeInput) common.Hash); ok { + r0 = rf(rpcParameters, config, input) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(context.Context, types.Configurations, *ethclient.Client, types.UnstakeInput) error); ok { - r1 = rf(ctx, config, client, input) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, types.Configurations, types.UnstakeInput) error); ok { + r1 = rf(rpcParameters, config, input) } else { r1 = ret.Error(1) } @@ -1832,25 +1786,25 @@ func (_m *UtilsCmdInterface) Unstake(ctx context.Context, config types.Configura return r0, r1 } -// UpdateCollection provides a mock function with given fields: ctx, client, config, collectionInput, collectionId -func (_m *UtilsCmdInterface) UpdateCollection(ctx context.Context, client *ethclient.Client, config types.Configurations, collectionInput types.CreateCollectionInput, collectionId uint16) (common.Hash, error) { - ret := _m.Called(ctx, client, config, collectionInput, collectionId) +// UpdateCollection provides a mock function with given fields: rpcParameters, config, collectionInput, collectionId +func (_m *UtilsCmdInterface) UpdateCollection(rpcParameters RPC.RPCParameters, config types.Configurations, collectionInput types.CreateCollectionInput, collectionId uint16) (common.Hash, error) { + ret := _m.Called(rpcParameters, config, collectionInput, collectionId) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Configurations, types.CreateCollectionInput, uint16) (common.Hash, error)); ok { - return rf(ctx, client, config, collectionInput, collectionId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.CreateCollectionInput, uint16) (common.Hash, error)); ok { + return rf(rpcParameters, config, collectionInput, collectionId) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Configurations, types.CreateCollectionInput, uint16) common.Hash); ok { - r0 = rf(ctx, client, config, collectionInput, collectionId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.CreateCollectionInput, uint16) common.Hash); ok { + r0 = rf(rpcParameters, config, collectionInput, collectionId) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, types.Configurations, types.CreateCollectionInput, uint16) error); ok { - r1 = rf(ctx, client, config, collectionInput, collectionId) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, types.Configurations, types.CreateCollectionInput, uint16) error); ok { + r1 = rf(rpcParameters, config, collectionInput, collectionId) } else { r1 = ret.Error(1) } @@ -1858,13 +1812,13 @@ func (_m *UtilsCmdInterface) UpdateCollection(ctx context.Context, client *ethcl return r0, r1 } -// UpdateCommission provides a mock function with given fields: ctx, config, client, updateCommissionInput -func (_m *UtilsCmdInterface) UpdateCommission(ctx context.Context, config types.Configurations, client *ethclient.Client, updateCommissionInput types.UpdateCommissionInput) error { - ret := _m.Called(ctx, config, client, updateCommissionInput) +// UpdateCommission provides a mock function with given fields: rpcParameters, config, updateCommissionInput +func (_m *UtilsCmdInterface) UpdateCommission(rpcParameters RPC.RPCParameters, config types.Configurations, updateCommissionInput types.UpdateCommissionInput) error { + ret := _m.Called(rpcParameters, config, updateCommissionInput) var r0 error - if rf, ok := ret.Get(0).(func(context.Context, types.Configurations, *ethclient.Client, types.UpdateCommissionInput) error); ok { - r0 = rf(ctx, config, client, updateCommissionInput) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.UpdateCommissionInput) error); ok { + r0 = rf(rpcParameters, config, updateCommissionInput) } else { r0 = ret.Error(0) } @@ -1872,25 +1826,25 @@ func (_m *UtilsCmdInterface) UpdateCommission(ctx context.Context, config types. return r0 } -// UpdateJob provides a mock function with given fields: ctx, client, config, jobInput, jobId -func (_m *UtilsCmdInterface) UpdateJob(ctx context.Context, client *ethclient.Client, config types.Configurations, jobInput types.CreateJobInput, jobId uint16) (common.Hash, error) { - ret := _m.Called(ctx, client, config, jobInput, jobId) +// UpdateJob provides a mock function with given fields: rpcParameters, config, jobInput, jobId +func (_m *UtilsCmdInterface) UpdateJob(rpcParameters RPC.RPCParameters, config types.Configurations, jobInput types.CreateJobInput, jobId uint16) (common.Hash, error) { + ret := _m.Called(rpcParameters, config, jobInput, jobId) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Configurations, types.CreateJobInput, uint16) (common.Hash, error)); ok { - return rf(ctx, client, config, jobInput, jobId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.CreateJobInput, uint16) (common.Hash, error)); ok { + return rf(rpcParameters, config, jobInput, jobId) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Configurations, types.CreateJobInput, uint16) common.Hash); ok { - r0 = rf(ctx, client, config, jobInput, jobId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.CreateJobInput, uint16) common.Hash); ok { + r0 = rf(rpcParameters, config, jobInput, jobId) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, types.Configurations, types.CreateJobInput, uint16) error); ok { - r1 = rf(ctx, client, config, jobInput, jobId) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, types.Configurations, types.CreateJobInput, uint16) error); ok { + r1 = rf(rpcParameters, config, jobInput, jobId) } else { r1 = ret.Error(1) } @@ -1898,13 +1852,13 @@ func (_m *UtilsCmdInterface) UpdateJob(ctx context.Context, client *ethclient.Cl return r0, r1 } -// Vote provides a mock function with given fields: ctx, config, client, account, stakerId, commitParams, rogueData, backupNodeActionsToIgnore -func (_m *UtilsCmdInterface) Vote(ctx context.Context, config types.Configurations, client *ethclient.Client, account types.Account, stakerId uint32, commitParams *types.CommitParams, rogueData types.Rogue, backupNodeActionsToIgnore []string) error { - ret := _m.Called(ctx, config, client, account, stakerId, commitParams, rogueData, backupNodeActionsToIgnore) +// Vote provides a mock function with given fields: rpcParameters, config, account, stakerId, commitParams, rogueData, backupNodeActionsToIgnore +func (_m *UtilsCmdInterface) Vote(rpcParameters RPC.RPCParameters, config types.Configurations, account types.Account, stakerId uint32, commitParams *types.CommitParams, rogueData types.Rogue, backupNodeActionsToIgnore []string) error { + ret := _m.Called(rpcParameters, config, account, stakerId, commitParams, rogueData, backupNodeActionsToIgnore) var r0 error - if rf, ok := ret.Get(0).(func(context.Context, types.Configurations, *ethclient.Client, types.Account, uint32, *types.CommitParams, types.Rogue, []string) error); ok { - r0 = rf(ctx, config, client, account, stakerId, commitParams, rogueData, backupNodeActionsToIgnore) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations, types.Account, uint32, *types.CommitParams, types.Rogue, []string) error); ok { + r0 = rf(rpcParameters, config, account, stakerId, commitParams, rogueData, backupNodeActionsToIgnore) } else { r0 = ret.Error(0) } @@ -1912,30 +1866,30 @@ func (_m *UtilsCmdInterface) Vote(ctx context.Context, config types.Configuratio return r0 } -// WaitForAppropriateState provides a mock function with given fields: ctx, client, action, states -func (_m *UtilsCmdInterface) WaitForAppropriateState(ctx context.Context, client *ethclient.Client, action string, states ...int) (uint32, error) { +// WaitForAppropriateState provides a mock function with given fields: rpcParameter, action, states +func (_m *UtilsCmdInterface) WaitForAppropriateState(rpcParameter RPC.RPCParameters, action string, states ...int) (uint32, error) { _va := make([]interface{}, len(states)) for _i := range states { _va[_i] = states[_i] } var _ca []interface{} - _ca = append(_ca, ctx, client, action) + _ca = append(_ca, rpcParameter, action) _ca = append(_ca, _va...) ret := _m.Called(_ca...) var r0 uint32 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, string, ...int) (uint32, error)); ok { - return rf(ctx, client, action, states...) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, string, ...int) (uint32, error)); ok { + return rf(rpcParameter, action, states...) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, string, ...int) uint32); ok { - r0 = rf(ctx, client, action, states...) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, string, ...int) uint32); ok { + r0 = rf(rpcParameter, action, states...) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, string, ...int) error); ok { - r1 = rf(ctx, client, action, states...) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, string, ...int) error); ok { + r1 = rf(rpcParameter, action, states...) } else { r1 = ret.Error(1) } @@ -1943,23 +1897,23 @@ func (_m *UtilsCmdInterface) WaitForAppropriateState(ctx context.Context, client return r0, r1 } -// WaitIfCommitState provides a mock function with given fields: ctx, client, action -func (_m *UtilsCmdInterface) WaitIfCommitState(ctx context.Context, client *ethclient.Client, action string) (uint32, error) { - ret := _m.Called(ctx, client, action) +// WaitIfCommitState provides a mock function with given fields: rpcParameter, action +func (_m *UtilsCmdInterface) WaitIfCommitState(rpcParameter RPC.RPCParameters, action string) (uint32, error) { + ret := _m.Called(rpcParameter, action) var r0 uint32 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, string) (uint32, error)); ok { - return rf(ctx, client, action) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, string) (uint32, error)); ok { + return rf(rpcParameter, action) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, string) uint32); ok { - r0 = rf(ctx, client, action) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, string) uint32); ok { + r0 = rf(rpcParameter, action) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, string) error); ok { - r1 = rf(ctx, client, action) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, string) error); ok { + r1 = rf(rpcParameter, action) } else { r1 = ret.Error(1) } diff --git a/cmd/mocks/viper_interface.go b/cmd/mocks/viper_interface.go index f664ff795..ddbb6674a 100644 --- a/cmd/mocks/viper_interface.go +++ b/cmd/mocks/viper_interface.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -23,13 +23,12 @@ func (_m *ViperInterface) ViperWriteConfigAs(path string) error { return r0 } -type mockConstructorTestingTNewViperInterface interface { +// NewViperInterface creates a new instance of ViperInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewViperInterface(t interface { mock.TestingT Cleanup(func()) -} - -// NewViperInterface creates a new instance of ViperInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewViperInterface(t mockConstructorTestingTNewViperInterface) *ViperInterface { +}) *ViperInterface { mock := &ViperInterface{} mock.Mock.Test(t) diff --git a/cmd/mocks/vote_manager_interface.go b/cmd/mocks/vote_manager_interface.go index f9e96332f..8a602d25c 100644 --- a/cmd/mocks/vote_manager_interface.go +++ b/cmd/mocks/vote_manager_interface.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -24,6 +24,10 @@ func (_m *VoteManagerInterface) Commit(client *ethclient.Client, txnOpts *bind.T ret := _m.Called(client, txnOpts, epoch, commitment) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, [32]byte) (*types.Transaction, error)); ok { + return rf(client, txnOpts, epoch, commitment) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, [32]byte) *types.Transaction); ok { r0 = rf(client, txnOpts, epoch, commitment) } else { @@ -32,7 +36,6 @@ func (_m *VoteManagerInterface) Commit(client *ethclient.Client, txnOpts *bind.T } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint32, [32]byte) error); ok { r1 = rf(client, txnOpts, epoch, commitment) } else { @@ -47,6 +50,10 @@ func (_m *VoteManagerInterface) Reveal(client *ethclient.Client, txnOpts *bind.T ret := _m.Called(client, txnOpts, epoch, tree, signature) var r0 *types.Transaction + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, bindings.StructsMerkleTree, []byte) (*types.Transaction, error)); ok { + return rf(client, txnOpts, epoch, tree, signature) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, *bind.TransactOpts, uint32, bindings.StructsMerkleTree, []byte) *types.Transaction); ok { r0 = rf(client, txnOpts, epoch, tree, signature) } else { @@ -55,7 +62,6 @@ func (_m *VoteManagerInterface) Reveal(client *ethclient.Client, txnOpts *bind.T } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, *bind.TransactOpts, uint32, bindings.StructsMerkleTree, []byte) error); ok { r1 = rf(client, txnOpts, epoch, tree, signature) } else { @@ -65,13 +71,12 @@ func (_m *VoteManagerInterface) Reveal(client *ethclient.Client, txnOpts *bind.T return r0, r1 } -type mockConstructorTestingTNewVoteManagerInterface interface { +// NewVoteManagerInterface creates a new instance of VoteManagerInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewVoteManagerInterface(t interface { mock.TestingT Cleanup(func()) -} - -// NewVoteManagerInterface creates a new instance of VoteManagerInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewVoteManagerInterface(t mockConstructorTestingTNewVoteManagerInterface) *VoteManagerInterface { +}) *VoteManagerInterface { mock := &VoteManagerInterface{} mock.Mock.Test(t) diff --git a/cmd/modifyCollectionStatus.go b/cmd/modifyCollectionStatus.go index 65a928a50..ead50fcc6 100644 --- a/cmd/modifyCollectionStatus.go +++ b/cmd/modifyCollectionStatus.go @@ -2,16 +2,13 @@ package cmd import ( - "context" - "razor/accounts" "razor/core" "razor/core/types" - "razor/logger" "razor/pkg/bindings" + "razor/rpc" "razor/utils" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/cobra" "github.com/spf13/pflag" ) @@ -32,31 +29,8 @@ func initialiseModifyCollectionStatus(cmd *cobra.Command, args []string) { //This function sets the flags appropriately and executes the ModifyCollectionStatus function func (*UtilsStruct) ExecuteModifyCollectionStatus(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - log.Debugf("ExecuteModifyCollectionStatus: Config: %+v: ", config) - - client := razorUtils.ConnectToClient(config.Provider) - - address, err := flagSetUtils.GetStringAddress(flagSet) - utils.CheckError("Error in getting address: ", err) - log.Debug("ExecuteModifyCollectionStatus: Address: ", address) - - logger.SetLoggerParameters(client, address) - - log.Debug("Checking to assign log file...") - fileUtils.AssignLogFile(flagSet, config) - - log.Debug("Getting password...") - password := razorUtils.AssignPassword(flagSet) - - accountManager, err := razorUtils.AccountManagerForKeystore() - utils.CheckError("Error in getting accounts manager for keystore: ", err) - - account := accounts.InitAccountStruct(address, password, accountManager) - - err = razorUtils.CheckPassword(account) - utils.CheckError("Error in fetching private key from given password: ", err) + config, rpcParameters, account, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) collectionId, err := flagSetUtils.GetUint16CollectionId(flagSet) utils.CheckError("Error in getting collectionId: ", err) @@ -73,23 +47,17 @@ func (*UtilsStruct) ExecuteModifyCollectionStatus(flagSet *pflag.FlagSet) { Account: account, } - txn, err := cmdUtils.ModifyCollectionStatus(context.Background(), client, config, modifyCollectionInput) + txn, err := cmdUtils.ModifyCollectionStatus(rpcParameters, config, modifyCollectionInput) utils.CheckError("Error in changing collection active status: ", err) if txn != core.NilHash { - err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) + err = razorUtils.WaitForBlockCompletion(rpcParameters, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for modifyCollectionStatus: ", err) } } -//This function checks the current status of particular collectionId -func (*UtilsStruct) CheckCurrentStatus(client *ethclient.Client, collectionId uint16) (bool, error) { - callOpts := razorUtils.GetOptions() - return assetManagerUtils.GetActiveStatus(client, &callOpts, collectionId) -} - //This function allows the admin to modify the active status of collection -func (*UtilsStruct) ModifyCollectionStatus(ctx context.Context, client *ethclient.Client, config types.Configurations, modifyCollectionInput types.ModifyCollectionInput) (common.Hash, error) { - currentStatus, err := cmdUtils.CheckCurrentStatus(client, modifyCollectionInput.CollectionId) +func (*UtilsStruct) ModifyCollectionStatus(rpcParameters rpc.RPCParameters, config types.Configurations, modifyCollectionInput types.ModifyCollectionInput) (common.Hash, error) { + currentStatus, err := razorUtils.GetActiveStatus(rpcParameters, modifyCollectionInput.CollectionId) if err != nil { log.Error("Error in fetching active status") return core.NilHash, err @@ -99,13 +67,12 @@ func (*UtilsStruct) ModifyCollectionStatus(ctx context.Context, client *ethclien log.Errorf("Collection %d has the active status already set to %t", modifyCollectionInput.CollectionId, modifyCollectionInput.Status) return core.NilHash, nil } - _, err = cmdUtils.WaitForAppropriateState(ctx, client, "modify collection status", 4) + _, err = cmdUtils.WaitForAppropriateState(rpcParameters, "modify collection status", 4) if err != nil { return core.NilHash, err } txnArgs := types.TransactionOptions{ - Client: client, ChainId: core.ChainId, Config: config, ContractAddress: core.CollectionManagerAddress, @@ -115,8 +82,13 @@ func (*UtilsStruct) ModifyCollectionStatus(ctx context.Context, client *ethclien Account: modifyCollectionInput.Account, } - txnOpts := razorUtils.GetTxnOpts(ctx, txnArgs) + txnOpts := razorUtils.GetTxnOpts(rpcParameters, txnArgs) log.Infof("Changing active status of collection: %d from %t to %t", modifyCollectionInput.CollectionId, !modifyCollectionInput.Status, modifyCollectionInput.Status) + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return core.NilHash, err + } + log.Debugf("Executing SetCollectionStatus transaction with status = %v, collectionId = %d", modifyCollectionInput.Status, modifyCollectionInput.CollectionId) txn, err := assetManagerUtils.SetCollectionStatus(client, txnOpts, modifyCollectionInput.Status, modifyCollectionInput.CollectionId) if err != nil { diff --git a/cmd/modifyCollectionStatus_test.go b/cmd/modifyCollectionStatus_test.go index 028bf1db1..059798f42 100644 --- a/cmd/modifyCollectionStatus_test.go +++ b/cmd/modifyCollectionStatus_test.go @@ -1,7 +1,6 @@ package cmd import ( - "context" "errors" "math/big" "razor/accounts" @@ -9,7 +8,6 @@ import ( "razor/core/types" "testing" - "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" Types "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" @@ -17,71 +15,8 @@ import ( "github.com/stretchr/testify/mock" ) -func TestCheckCurrentStatus(t *testing.T) { - - var client *ethclient.Client - var assetId uint16 - - type args struct { - callOpts bind.CallOpts - activeStatus bool - activeStatusErr error - } - tests := []struct { - name string - args args - want bool - wantErr error - }{ - { - name: "Test 1: When CheckCurrentStatus function executes successfully", - args: args{ - callOpts: bind.CallOpts{}, - activeStatus: true, - activeStatusErr: nil, - }, - want: true, - wantErr: nil, - }, - { - name: "Test 2: When GetActiveStatus function gives an error", - args: args{ - callOpts: bind.CallOpts{}, - activeStatusErr: errors.New("activeStatus error"), - }, - want: false, - wantErr: errors.New("activeStatus error"), - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - SetUpMockInterfaces() - - utilsMock.On("GetOptions").Return(tt.args.callOpts) - assetManagerMock.On("GetActiveStatus", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.AnythingOfType("uint16")).Return(tt.args.activeStatus, tt.args.activeStatusErr) - - utils := &UtilsStruct{} - got, err := utils.CheckCurrentStatus(client, assetId) - if got != tt.want { - t.Errorf("Status from CheckCurrentStatus function, got = %v, want %v", got, tt.want) - } - if err == nil || tt.wantErr == nil { - if err != tt.wantErr { - t.Errorf("Error for CheckCurrentStatus function, got = %v, want %v", err, tt.wantErr) - } - } else { - if err.Error() != tt.wantErr.Error() { - t.Errorf("Error for CheckCurrentStatus function, got = %v, want %v", err, tt.wantErr) - } - } - - }) - } -} - func TestModifyAssetStatus(t *testing.T) { var config types.Configurations - var client *ethclient.Client type args struct { status bool @@ -161,15 +96,15 @@ func TestModifyAssetStatus(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - cmdUtilsMock.On("CheckCurrentStatus", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint16")).Return(tt.args.currentStatus, tt.args.currentStatusErr) + utilsMock.On("GetActiveStatus", mock.Anything, mock.Anything).Return(tt.args.currentStatus, tt.args.currentStatusErr) utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(TxnOpts) - cmdUtilsMock.On("WaitForAppropriateState", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.epoch, tt.args.epochErr) + cmdUtilsMock.On("WaitForAppropriateState", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.epoch, tt.args.epochErr) assetManagerMock.On("SetCollectionStatus", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.SetCollectionStatus, tt.args.SetAssetStatusErr) transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) utils := &UtilsStruct{} - got, err := utils.ModifyCollectionStatus(context.Background(), client, config, types.ModifyCollectionInput{ + got, err := utils.ModifyCollectionStatus(rpcParameters, config, types.ModifyCollectionInput{ Status: tt.args.status, }) if got != tt.want { @@ -310,13 +245,16 @@ func TestExecuteModifyAssetStatus(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() + setupTestEndpointsEnvironment() + + utilsMock.On("IsFlagPassed", mock.Anything).Return(true) fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) flagSetMock.On("GetStringAddress", flagSet).Return(tt.args.address, tt.args.addressErr) @@ -327,8 +265,8 @@ func TestExecuteModifyAssetStatus(t *testing.T) { utilsMock.On("AccountManagerForKeystore").Return(&accounts.AccountManager{}, nil) stringMock.On("ParseBool", mock.AnythingOfType("string")).Return(tt.args.parseStatus, tt.args.parseStatusErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) - cmdUtilsMock.On("ModifyCollectionStatus", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.ModifyCollectionStatusHash, tt.args.ModifyCollectionStatusErr) - utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) + cmdUtilsMock.On("ModifyCollectionStatus", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.ModifyCollectionStatusHash, tt.args.ModifyCollectionStatusErr) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) utils := &UtilsStruct{} fatal = false diff --git a/cmd/propose.go b/cmd/propose.go index 6bf71267c..f02134189 100644 --- a/cmd/propose.go +++ b/cmd/propose.go @@ -2,7 +2,6 @@ package cmd import ( - "context" "encoding/hex" "errors" "math" @@ -10,6 +9,7 @@ import ( "razor/core" "razor/core/types" "razor/pkg/bindings" + "razor/rpc" "razor/utils" "sort" "strings" @@ -17,7 +17,6 @@ import ( "time" Types "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethclient" solsha3 "github.com/miguelmota/go-solidity-sha3" ) @@ -32,12 +31,12 @@ var globalProposedDataStruct types.ProposeFileData // Find iteration using salt as seed //This functions handles the propose state -func (*UtilsStruct) Propose(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, staker bindings.StructsStaker, epoch uint32, latestHeader *Types.Header, stateBuffer uint64, rogueData types.Rogue) error { +func (*UtilsStruct) Propose(rpcParameters rpc.RPCParameters, config types.Configurations, account types.Account, staker bindings.StructsStaker, epoch uint32, latestHeader *Types.Header, stateBuffer uint64, rogueData types.Rogue) error { if state, err := razorUtils.GetBufferedState(latestHeader, stateBuffer, config.BufferPercent); err != nil || state != 2 { log.Error("Not propose state") return err } - numStakers, err := razorUtils.GetNumberOfStakers(ctx, client) + numStakers, err := razorUtils.GetNumberOfStakers(rpcParameters) if err != nil { log.Error("Error in fetching number of stakers: ", err) return err @@ -54,7 +53,7 @@ func (*UtilsStruct) Propose(ctx context.Context, client *ethclient.Client, confi if rogueData.IsRogue && utils.Contains(rogueData.RogueMode, "biggestStakerId") { log.Warn("YOU ARE PROPOSING IN ROGUE MODE, THIS CAN INCUR PENALTIES!") // If staker is going rogue with biggestStakerId than we do biggestStakerId = smallestStakerId - smallestStake, smallestStakerId, smallestStakerErr := cmdUtils.GetSmallestStakeAndId(ctx, client, epoch) + smallestStake, smallestStakerId, smallestStakerErr := cmdUtils.GetSmallestStakeAndId(rpcParameters, epoch) if smallestStakerErr != nil { log.Error("Error in calculating smallest staker: ", smallestStakerErr) return smallestStakerErr @@ -63,7 +62,7 @@ func (*UtilsStruct) Propose(ctx context.Context, client *ethclient.Client, confi biggestStakerId = smallestStakerId log.Debugf("Propose: In rogue mode, Biggest Stake: %s, Biggest Staker Id: %d", biggestStake, biggestStakerId) } else { - biggestStake, biggestStakerId, biggestStakerErr = cmdUtils.GetBiggestStakeAndId(ctx, client, epoch) + biggestStake, biggestStakerId, biggestStakerErr = cmdUtils.GetBiggestStakeAndId(rpcParameters, epoch) if biggestStakerErr != nil { log.Error("Error in calculating biggest staker: ", biggestStakerErr) return biggestStakerErr @@ -71,7 +70,7 @@ func (*UtilsStruct) Propose(ctx context.Context, client *ethclient.Client, confi } log.Debugf("Getting Salt for current epoch %d...", epoch) - salt, err := cmdUtils.GetSalt(ctx, client, epoch) + salt, err := cmdUtils.GetSalt(rpcParameters, epoch) if err != nil { return err } @@ -86,20 +85,20 @@ func (*UtilsStruct) Propose(ctx context.Context, client *ethclient.Client, confi Epoch: epoch, } log.Debugf("Propose: Calling GetIteration with arguments proposer = %+v, buffer percent = %d", proposer, config.BufferPercent) - iteration := cmdUtils.GetIteration(ctx, client, proposer, config.BufferPercent) + iteration := cmdUtils.GetIteration(rpcParameters, proposer, config.BufferPercent) log.Debug("Iteration: ", iteration) if iteration == -1 { return nil } - numOfProposedBlocks, err := razorUtils.GetNumberOfProposedBlocks(ctx, client, epoch) + numOfProposedBlocks, err := razorUtils.GetNumberOfProposedBlocks(rpcParameters, epoch) if err != nil { log.Error(err) return err } log.Debug("Propose: Number of proposed blocks: ", numOfProposedBlocks) - maxAltBlocks, err := razorUtils.GetMaxAltBlocks(ctx, client) + maxAltBlocks, err := razorUtils.GetMaxAltBlocks(rpcParameters) if err != nil { log.Error(err) return err @@ -108,7 +107,7 @@ func (*UtilsStruct) Propose(ctx context.Context, client *ethclient.Client, confi if numOfProposedBlocks >= maxAltBlocks { log.Debugf("Number of blocks proposed: %d, which is equal or greater than maximum alternative blocks allowed", numOfProposedBlocks) log.Debug("Comparing iterations...") - sortedProposedBlocks, err := razorUtils.GetSortedProposedBlockIds(ctx, client, epoch) + sortedProposedBlocks, err := razorUtils.GetSortedProposedBlockIds(rpcParameters, epoch) if err != nil { log.Error("Error in fetching sorted proposed block ids") return err @@ -116,7 +115,7 @@ func (*UtilsStruct) Propose(ctx context.Context, client *ethclient.Client, confi log.Debug("Propose: Sorted proposed blocks: ", sortedProposedBlocks) lastBlockIndex := sortedProposedBlocks[numOfProposedBlocks-1] log.Debug("Propose: Last block index: ", lastBlockIndex) - lastProposedBlockStruct, err := razorUtils.GetProposedBlock(ctx, client, epoch, lastBlockIndex) + lastProposedBlockStruct, err := razorUtils.GetProposedBlock(rpcParameters, epoch, lastBlockIndex) if err != nil { log.Error(err) return err @@ -131,7 +130,7 @@ func (*UtilsStruct) Propose(ctx context.Context, client *ethclient.Client, confi log.Info("Current iteration is less than iteration of last proposed block, can propose") } log.Debugf("Propose: Calling MakeBlock() with arguments blockNumber = %s, epoch = %d, rogueData = %+v", latestHeader.Number, epoch, rogueData) - medians, ids, revealedDataMaps, err := cmdUtils.MakeBlock(ctx, client, latestHeader.Number, epoch, rogueData) + medians, ids, revealedDataMaps, err := cmdUtils.MakeBlock(rpcParameters, latestHeader.Number, epoch, rogueData) if err != nil { log.Error(err) return err @@ -141,8 +140,7 @@ func (*UtilsStruct) Propose(ctx context.Context, client *ethclient.Client, confi log.Debugf("Propose: Iteration: %d Biggest Staker Id: %d", iteration, biggestStakerId) log.Info("Proposing block...") - txnOpts := razorUtils.GetTxnOpts(ctx, types.TransactionOptions{ - Client: client, + txnOpts := razorUtils.GetTxnOpts(rpcParameters, types.TransactionOptions{ ChainId: core.ChainId, Config: config, ContractAddress: core.BlockManagerAddress, @@ -152,6 +150,12 @@ func (*UtilsStruct) Propose(ctx context.Context, client *ethclient.Client, confi Account: account, }) + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + log.Error(err) + return err + } + log.Debugf("Executing Propose transaction with epoch = %d, Ids = %v, medians = %s, iteration = %s, biggestStakerId = %d", epoch, ids, medians, big.NewInt(int64(iteration)), biggestStakerId) txn, err := blockManagerUtils.Propose(client, txnOpts, epoch, ids, medians, big.NewInt(int64(iteration)), biggestStakerId) if err != nil { @@ -190,8 +194,8 @@ func (*UtilsStruct) Propose(ctx context.Context, client *ethclient.Client, confi } //This function returns the biggest stake and Id of it -func (*UtilsStruct) GetBiggestStakeAndId(ctx context.Context, client *ethclient.Client, epoch uint32) (*big.Int, uint32, error) { - numberOfStakers, err := razorUtils.GetNumberOfStakers(ctx, client) +func (*UtilsStruct) GetBiggestStakeAndId(rpcParameters rpc.RPCParameters, epoch uint32) (*big.Int, uint32, error) { + numberOfStakers, err := razorUtils.GetNumberOfStakers(rpcParameters) if err != nil { return nil, 0, err } @@ -202,7 +206,7 @@ func (*UtilsStruct) GetBiggestStakeAndId(ctx context.Context, client *ethclient. var biggestStakerId uint32 biggestStake := big.NewInt(0) - stakeSnapshotArray, err := cmdUtils.BatchGetStakeSnapshotCalls(client, epoch, numberOfStakers) + stakeSnapshotArray, err := cmdUtils.BatchGetStakeSnapshotCalls(rpcParameters, epoch, numberOfStakers) if err != nil { return nil, 0, err } @@ -225,20 +229,20 @@ func (*UtilsStruct) GetBiggestStakeAndId(ctx context.Context, client *ethclient. return biggestStake, biggestStakerId, nil } -func (*UtilsStruct) GetIteration(ctx context.Context, client *ethclient.Client, proposer types.ElectedProposer, bufferPercent int32) int { - stake, err := razorUtils.GetStakeSnapshot(ctx, client, proposer.StakerId, proposer.Epoch) +func (*UtilsStruct) GetIteration(rpcParameters rpc.RPCParameters, proposer types.ElectedProposer, bufferPercent int32) int { + stake, err := razorUtils.GetStakeSnapshot(rpcParameters, proposer.StakerId, proposer.Epoch) if err != nil { log.Error("Error in fetching influence of staker: ", err) return -1 } log.Debug("GetIteration: Stake: ", stake) currentStakerStake := big.NewInt(1).Mul(stake, big.NewInt(int64(math.Exp2(32)))) - stateBuffer, err := razorUtils.GetStateBuffer(ctx, client) + stateBuffer, err := razorUtils.GetStateBuffer(rpcParameters) if err != nil { log.Error("Error in getting state buffer: ", err) return -1 } - latestHeader, err := clientUtils.GetLatestBlockWithRetry(ctx, client) + latestHeader, err := clientUtils.GetLatestBlockWithRetry(rpcParameters) if err != nil { log.Error("Error in getting latest block: ", err) return -1 @@ -345,9 +349,9 @@ func pseudoRandomNumberGenerator(seed []byte, max uint32, blockHashes []byte) *b } //This function returns the sorted revealed values -func (*UtilsStruct) GetSortedRevealedValues(ctx context.Context, client *ethclient.Client, blockNumber *big.Int, epoch uint32) (*types.RevealedDataMaps, error) { +func (*UtilsStruct) GetSortedRevealedValues(rpcParameters rpc.RPCParameters, blockNumber *big.Int, epoch uint32) (*types.RevealedDataMaps, error) { log.Debugf("GetSortedRevealedValues: Calling IndexRevealEventsOfCurrentEpoch with arguments blockNumber = %s, epoch = %d", blockNumber, epoch) - assignedAsset, err := cmdUtils.IndexRevealEventsOfCurrentEpoch(ctx, client, blockNumber, epoch) + assignedAsset, err := cmdUtils.IndexRevealEventsOfCurrentEpoch(rpcParameters, blockNumber, epoch) if err != nil { return nil, err } @@ -392,15 +396,15 @@ func (*UtilsStruct) GetSortedRevealedValues(ctx context.Context, client *ethclie } //This function returns the medians, idsRevealedInThisEpoch and revealedDataMaps -func (*UtilsStruct) MakeBlock(ctx context.Context, client *ethclient.Client, blockNumber *big.Int, epoch uint32, rogueData types.Rogue) ([]*big.Int, []uint16, *types.RevealedDataMaps, error) { +func (*UtilsStruct) MakeBlock(rpcParameters rpc.RPCParameters, blockNumber *big.Int, epoch uint32, rogueData types.Rogue) ([]*big.Int, []uint16, *types.RevealedDataMaps, error) { log.Debugf("MakeBlock: Calling GetSortedRevealedValues with arguments blockNumber = %s, epoch = %d", blockNumber, epoch) - revealedDataMaps, err := cmdUtils.GetSortedRevealedValues(ctx, client, blockNumber, epoch) + revealedDataMaps, err := cmdUtils.GetSortedRevealedValues(rpcParameters, blockNumber, epoch) if err != nil { return nil, nil, nil, err } log.Debugf("MakeBlock: Revealed data map: %+v", revealedDataMaps) - activeCollections, err := razorUtils.GetActiveCollectionIds(ctx, client) + activeCollections, err := razorUtils.GetActiveCollectionIds(rpcParameters) if err != nil { return nil, nil, nil, err } @@ -452,8 +456,8 @@ func (*UtilsStruct) MakeBlock(ctx context.Context, client *ethclient.Client, blo return medians, idsRevealedInThisEpoch, revealedDataMaps, nil } -func (*UtilsStruct) GetSmallestStakeAndId(ctx context.Context, client *ethclient.Client, epoch uint32) (*big.Int, uint32, error) { - numberOfStakers, err := razorUtils.GetNumberOfStakers(ctx, client) +func (*UtilsStruct) GetSmallestStakeAndId(rpcParameters rpc.RPCParameters, epoch uint32) (*big.Int, uint32, error) { + numberOfStakers, err := razorUtils.GetNumberOfStakers(rpcParameters) if err != nil { return nil, 0, err } @@ -464,7 +468,7 @@ func (*UtilsStruct) GetSmallestStakeAndId(ctx context.Context, client *ethclient smallestStake := big.NewInt(1).Mul(big.NewInt(1e18), big.NewInt(1e18)) for i := 1; i <= int(numberOfStakers); i++ { - stake, err := razorUtils.GetStakeSnapshot(ctx, client, uint32(i), epoch) + stake, err := razorUtils.GetStakeSnapshot(rpcParameters, uint32(i), epoch) if err != nil { return nil, 0, err } @@ -476,7 +480,7 @@ func (*UtilsStruct) GetSmallestStakeAndId(ctx context.Context, client *ethclient return smallestStake, smallestStakerId, nil } -func (*UtilsStruct) BatchGetStakeSnapshotCalls(client *ethclient.Client, epoch uint32, numberOfStakers uint32) ([]*big.Int, error) { +func (*UtilsStruct) BatchGetStakeSnapshotCalls(rpcParameters rpc.RPCParameters, epoch uint32, numberOfStakers uint32) ([]*big.Int, error) { voteManagerABI, err := utils.ABIInterface.Parse(strings.NewReader(bindings.VoteManagerMetaData.ABI)) if err != nil { log.Errorf("Error in parsed voteManager ABI: %v", err) @@ -488,7 +492,7 @@ func (*UtilsStruct) BatchGetStakeSnapshotCalls(client *ethclient.Client, epoch u args[i-1] = []interface{}{epoch, i} } - results, err := clientUtils.BatchCall(client, &voteManagerABI, core.VoteManagerAddress, core.GetStakeSnapshotMethod, args) + results, err := clientUtils.BatchCall(rpcParameters, &voteManagerABI, core.VoteManagerAddress, core.GetStakeSnapshotMethod, args) if err != nil { log.Error("Error in performing getStakeSnapshot batch calls: ", err) return nil, err diff --git a/cmd/propose_test.go b/cmd/propose_test.go index 0b1fbf442..f324059f5 100644 --- a/cmd/propose_test.go +++ b/cmd/propose_test.go @@ -1,7 +1,6 @@ package cmd import ( - "context" "errors" "fmt" "github.com/ethereum/go-ethereum/accounts/abi" @@ -17,13 +16,11 @@ import ( "github.com/ethereum/go-ethereum/common" Types "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethclient" ) func TestPropose(t *testing.T) { var ( - client *ethclient.Client account types.Account config types.Configurations staker bindings.StructsStaker @@ -484,19 +481,19 @@ func TestPropose(t *testing.T) { SetUpMockInterfaces() utilsMock.On("GetBufferedState", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.state, tt.args.stateErr) - utilsMock.On("GetNumberOfStakers", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.numStakers, tt.args.numStakerErr) - cmdUtilsMock.On("GetBiggestStakeAndId", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.biggestStake, tt.args.biggestStakerId, tt.args.biggestStakerIdErr) - cmdUtilsMock.On("GetSmallestStakeAndId", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.smallestStake, tt.args.smallestStakerId, tt.args.smallestStakerIdErr) + utilsMock.On("GetNumberOfStakers", mock.Anything).Return(tt.args.numStakers, tt.args.numStakerErr) + cmdUtilsMock.On("GetBiggestStakeAndId", mock.Anything, mock.Anything).Return(tt.args.biggestStake, tt.args.biggestStakerId, tt.args.biggestStakerIdErr) + cmdUtilsMock.On("GetSmallestStakeAndId", mock.Anything, mock.Anything).Return(tt.args.smallestStake, tt.args.smallestStakerId, tt.args.smallestStakerIdErr) utilsMock.On("GetRandaoHash", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.randaoHash, tt.args.randaoHashErr) - cmdUtilsMock.On("GetIteration", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.iteration) - utilsMock.On("GetMaxAltBlocks", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.maxAltBlocks, tt.args.maxAltBlocksErr) - cmdUtilsMock.On("GetSalt", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.salt, tt.args.saltErr) cmdUtilsMock.On("GetIteration", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.iteration) - utilsMock.On("GetNumberOfProposedBlocks", mock.Anything, mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.numOfProposedBlocks, tt.args.numOfProposedBlocksErr) + utilsMock.On("GetMaxAltBlocks", mock.Anything).Return(tt.args.maxAltBlocks, tt.args.maxAltBlocksErr) + cmdUtilsMock.On("GetSalt", mock.Anything, mock.Anything).Return(tt.args.salt, tt.args.saltErr) + cmdUtilsMock.On("GetIteration", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.iteration) + utilsMock.On("GetNumberOfProposedBlocks", mock.Anything, mock.Anything).Return(tt.args.numOfProposedBlocks, tt.args.numOfProposedBlocksErr) utilsMock.On("GetSortedProposedBlockIds", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.sortedProposedBlockIds, tt.args.sortedProposedBlocksIdsErr) - utilsMock.On("GetMaxAltBlocks", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.maxAltBlocks, tt.args.maxAltBlocksErr) - utilsMock.On("GetProposedBlock", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.lastProposedBlockStruct, tt.args.lastProposedBlockStructErr) - cmdUtilsMock.On("MakeBlock", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.medians, tt.args.ids, tt.args.revealDataMaps, tt.args.mediansErr) + utilsMock.On("GetMaxAltBlocks", mock.Anything).Return(tt.args.maxAltBlocks, tt.args.maxAltBlocksErr) + utilsMock.On("GetProposedBlock", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.lastProposedBlockStruct, tt.args.lastProposedBlockStructErr) + cmdUtilsMock.On("MakeBlock", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.medians, tt.args.ids, tt.args.revealDataMaps, tt.args.mediansErr) utilsMock.On("ConvertUint32ArrayToBigIntArray", mock.Anything).Return(tt.args.mediansBigInt) pathMock.On("GetProposeDataFileName", mock.AnythingOfType("string")).Return(tt.args.fileName, tt.args.fileNameErr) fileUtilsMock.On("SaveDataToProposeJsonFile", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.saveDataErr) @@ -506,7 +503,7 @@ func TestPropose(t *testing.T) { utils := &UtilsStruct{} t.Run(tt.name, func(t *testing.T) { - err := utils.Propose(context.Background(), client, config, account, staker, epoch, latestHeader, stateBuffer, tt.args.rogueData) + err := utils.Propose(rpcParameters, config, account, staker, epoch, latestHeader, stateBuffer, tt.args.rogueData) if err == nil || tt.wantErr == nil { if err != tt.wantErr { t.Errorf("Error for Propose function, got = %v, want %v", err, tt.wantErr) @@ -521,7 +518,6 @@ func TestPropose(t *testing.T) { } func TestGetBiggestStakeAndId(t *testing.T) { - var client *ethclient.Client var epoch uint32 type args struct { @@ -590,12 +586,12 @@ func TestGetBiggestStakeAndId(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetNumberOfStakers", mock.Anything, mock.Anything).Return(tt.args.numOfStakers, tt.args.numOfStakersErr) - cmdUtilsMock.On("BatchGetStakeSnapshotCalls", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint32")).Return(tt.args.stakeArray, tt.args.stakeErr) + utilsMock.On("GetNumberOfStakers", mock.Anything).Return(tt.args.numOfStakers, tt.args.numOfStakersErr) + cmdUtilsMock.On("BatchGetStakeSnapshotCalls", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.stakeArray, tt.args.stakeErr) utils := &UtilsStruct{} - gotStake, gotId, err := utils.GetBiggestStakeAndId(context.Background(), client, epoch) + gotStake, gotId, err := utils.GetBiggestStakeAndId(rpcParameters, epoch) if err == nil || tt.wantErr == nil { if err != tt.wantErr { t.Errorf("Error for GetBiggestStakeAndId function, got = %v, want %v", err, tt.wantErr) @@ -622,7 +618,6 @@ func stakeSnapshotValue(stake string) *big.Int { } func TestGetIteration(t *testing.T) { - var client *ethclient.Client var bufferPercent int32 salt := []byte{142, 170, 157, 83, 109, 43, 34, 152, 21, 154, 159, 12, 195, 119, 50, 186, 218, 57, 39, 173, 228, 135, 20, 100, 149, 27, 169, 158, 34, 113, 66, 64} @@ -716,9 +711,9 @@ func TestGetIteration(t *testing.T) { utilsMock.On("GetStakeSnapshot", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(big.NewInt(1).Mul(tt.args.stakeSnapshot, big.NewInt(1e18)), tt.args.stakeSnapshotErr) utilsMock.On("GetRemainingTimeOfCurrentState", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.remainingTime, tt.args.remainingTimeErr) - utilsMock.On("GetStateBuffer", mock.Anything, mock.Anything).Return(tt.args.stateBuffer, tt.args.stateBufferErr) + utilsMock.On("GetStateBuffer", mock.Anything).Return(tt.args.stateBuffer, tt.args.stateBufferErr) clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything, mock.Anything).Return(tt.args.latestHeader, tt.args.latestHeaderErr) - if got := cmdUtils.GetIteration(context.Background(), client, proposer, bufferPercent); got != tt.want { + if got := cmdUtils.GetIteration(rpcParameters, proposer, bufferPercent); got != tt.want { t.Errorf("getIteration() = %v, want %v", got, tt.want) } }) @@ -882,7 +877,6 @@ func Test_pseudoRandomNumberGenerator(t *testing.T) { func TestMakeBlock(t *testing.T) { var ( - client *ethclient.Client blockNumber *big.Int epoch uint32 ) @@ -1022,7 +1016,7 @@ func TestMakeBlock(t *testing.T) { utilsMock.On("GetActiveCollectionIds", mock.Anything, mock.Anything).Return(tt.args.activeCollections, tt.args.activeCollectionsErr) utilsMock.On("GetRogueRandomValue", mock.Anything).Return(randomValue) ut := &UtilsStruct{} - got, got1, got2, err := ut.MakeBlock(context.Background(), client, blockNumber, epoch, tt.args.rogueData) + got, got1, got2, err := ut.MakeBlock(rpcParameters, blockNumber, epoch, tt.args.rogueData) if (err != nil) != tt.wantErr { t.Errorf("MakeBlock() error = %v, wantErr %v", err, tt.wantErr) return @@ -1042,7 +1036,6 @@ func TestMakeBlock(t *testing.T) { func TestGetSortedRevealedValues(t *testing.T) { var ( - client *ethclient.Client blockNumber *big.Int epoch uint32 ) @@ -1212,7 +1205,7 @@ func TestGetSortedRevealedValues(t *testing.T) { cmdUtilsMock.On("IndexRevealEventsOfCurrentEpoch", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.assignedAssets, tt.args.assignedAssetsErr) ut := &UtilsStruct{} - got, err := ut.GetSortedRevealedValues(context.Background(), client, blockNumber, epoch) + got, err := ut.GetSortedRevealedValues(rpcParameters, blockNumber, epoch) if (err != nil) != tt.wantErr { t.Errorf("GetSortedRevealedValues() error = %v, wantErr %v", err, tt.wantErr) return @@ -1225,7 +1218,6 @@ func TestGetSortedRevealedValues(t *testing.T) { } func TestGetSmallestStakeAndId(t *testing.T) { - var client *ethclient.Client var epoch uint32 type args struct { @@ -1285,12 +1277,12 @@ func TestGetSmallestStakeAndId(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetNumberOfStakers", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.numOfStakers, tt.args.numOfStakersErr) + utilsMock.On("GetNumberOfStakers", mock.Anything).Return(tt.args.numOfStakers, tt.args.numOfStakersErr) utilsMock.On("GetStakeSnapshot", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.stake, tt.args.stakeErr) utils := &UtilsStruct{} - gotStake, gotId, err := utils.GetSmallestStakeAndId(context.Background(), client, epoch) + gotStake, gotId, err := utils.GetSmallestStakeAndId(rpcParameters, epoch) if gotStake.Cmp(tt.wantStake) != 0 { t.Errorf("Smallest Stake from GetSmallestStakeAndId function, got = %v, want %v", gotStake, tt.wantStake) } @@ -1312,7 +1304,6 @@ func TestGetSmallestStakeAndId(t *testing.T) { } func TestBatchGetStakeCalls(t *testing.T) { - var client *ethclient.Client var epoch uint32 voteManagerABI, _ := abi.JSON(strings.NewReader(bindings.VoteManagerMetaData.ABI)) @@ -1364,7 +1355,7 @@ func TestBatchGetStakeCalls(t *testing.T) { clientUtilsMock.On("BatchCall", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.batchCallResults, tt.args.batchCallError) ut := &UtilsStruct{} - gotStakes, err := ut.BatchGetStakeSnapshotCalls(client, epoch, tt.args.numberOfStakers) + gotStakes, err := ut.BatchGetStakeSnapshotCalls(rpcParameters, epoch, tt.args.numberOfStakers) if err == nil || tt.wantErr == nil { assert.Equal(t, tt.wantErr, err) @@ -1378,7 +1369,6 @@ func TestBatchGetStakeCalls(t *testing.T) { } func BenchmarkGetIteration(b *testing.B) { - var client *ethclient.Client var bufferPercent int32 salt := []byte{142, 170, 157, 83, 109, 43, 34, 152, 21, 154, 159, 12, 195, 119, 50, 186, 218, 57, 39, 173, 228, 135, 20, 100, 149, 27, 169, 158, 34, 113, 66, 64} @@ -1411,17 +1401,16 @@ func BenchmarkGetIteration(b *testing.B) { utilsMock.On("GetStakeSnapshot", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(big.NewInt(1).Mul(v.stakeSnapshot, big.NewInt(1e18)), nil) utilsMock.On("GetRemainingTimeOfCurrentState", mock.Anything, mock.Anything, mock.Anything).Return(int64(100), nil) - utilsMock.On("GetStateBuffer", mock.Anything, mock.Anything).Return(uint64(5), nil) + utilsMock.On("GetStateBuffer", mock.Anything).Return(uint64(5), nil) clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything, mock.Anything).Return(&Types.Header{}, nil) - cmdUtils.GetIteration(context.Background(), client, proposer, bufferPercent) + cmdUtils.GetIteration(rpcParameters, proposer, bufferPercent) } }) } } func BenchmarkGetBiggestStakeAndId(b *testing.B) { - var client *ethclient.Client var epoch uint32 var table = []struct { @@ -1438,11 +1427,11 @@ func BenchmarkGetBiggestStakeAndId(b *testing.B) { for i := 0; i < b.N; i++ { SetUpMockInterfaces() - utilsMock.On("GetNumberOfStakers", mock.Anything, mock.Anything, mock.Anything).Return(v.numOfStakers, nil) + utilsMock.On("GetNumberOfStakers", mock.Anything).Return(v.numOfStakers, nil) cmdUtilsMock.On("BatchGetStakeSnapshotCalls", mock.Anything, mock.Anything, mock.Anything).Return(GenerateDummyStakeSnapshotArray(v.numOfStakers), nil) ut := &UtilsStruct{} - _, _, err := ut.GetBiggestStakeAndId(context.Background(), client, epoch) + _, _, err := ut.GetBiggestStakeAndId(rpcParameters, epoch) if err != nil { log.Fatal(err) } @@ -1453,7 +1442,6 @@ func BenchmarkGetBiggestStakeAndId(b *testing.B) { func BenchmarkGetSortedRevealedValues(b *testing.B) { var ( - client *ethclient.Client blockNumber *big.Int epoch uint32 ) @@ -1475,7 +1463,7 @@ func BenchmarkGetSortedRevealedValues(b *testing.B) { cmdUtilsMock.On("IndexRevealEventsOfCurrentEpoch", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(GetDummyAssignedAssets(asset, v.numOfAssignedAssets), nil) ut := &UtilsStruct{} - _, err := ut.GetSortedRevealedValues(context.Background(), client, blockNumber, epoch) + _, err := ut.GetSortedRevealedValues(rpcParameters, blockNumber, epoch) if err != nil { log.Fatal(err) } @@ -1486,7 +1474,6 @@ func BenchmarkGetSortedRevealedValues(b *testing.B) { func BenchmarkMakeBlock(b *testing.B) { var ( - client *ethclient.Client blockNumber *big.Int epoch uint32 ) @@ -1514,7 +1501,7 @@ func BenchmarkMakeBlock(b *testing.B) { }, nil) utilsMock.On("GetActiveCollectionIds", mock.Anything, mock.Anything).Return([]uint16{1}, nil) ut := &UtilsStruct{} - _, _, _, err := ut.MakeBlock(context.Background(), client, blockNumber, epoch, types.Rogue{IsRogue: false}) + _, _, _, err := ut.MakeBlock(rpcParameters, blockNumber, epoch, types.Rogue{IsRogue: false}) if err != nil { log.Fatal(err) } diff --git a/cmd/resetUnstakeLock.go b/cmd/resetUnstakeLock.go index 13efd91de..348dc4f7f 100644 --- a/cmd/resetUnstakeLock.go +++ b/cmd/resetUnstakeLock.go @@ -2,16 +2,13 @@ package cmd import ( - "context" - "razor/accounts" "razor/core" "razor/core/types" - "razor/logger" "razor/pkg/bindings" + "razor/rpc" "razor/utils" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/pflag" "github.com/spf13/cobra" @@ -35,32 +32,10 @@ func initialiseExtendLock(cmd *cobra.Command, args []string) { //This function sets the flags appropriately and executes the ResetUnstakeLock function func (*UtilsStruct) ExecuteExtendLock(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - log.Debugf("ExecuteExtendLock: Config: %+v", config) + config, rpcParameters, account, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) - client := razorUtils.ConnectToClient(config.Provider) - - address, err := flagSetUtils.GetStringAddress(flagSet) - utils.CheckError("Error in getting address: ", err) - - logger.SetLoggerParameters(client, address) - - log.Debug("Checking to assign log file...") - fileUtils.AssignLogFile(flagSet, config) - - log.Debug("Getting password...") - password := razorUtils.AssignPassword(flagSet) - - accountManager, err := razorUtils.AccountManagerForKeystore() - utils.CheckError("Error in getting accounts manager for keystore: ", err) - - account := accounts.InitAccountStruct(address, password, accountManager) - - err = razorUtils.CheckPassword(account) - utils.CheckError("Error in fetching private key from given password: ", err) - - stakerId, err := razorUtils.AssignStakerId(context.Background(), flagSet, client, address) + stakerId, err := razorUtils.AssignStakerId(rpcParameters, flagSet, account.Address) utils.CheckError("Error in getting stakerId: ", err) extendLockInput := types.ExtendLockInput{ @@ -68,16 +43,15 @@ func (*UtilsStruct) ExecuteExtendLock(flagSet *pflag.FlagSet) { Account: account, } - txn, err := cmdUtils.ResetUnstakeLock(client, config, extendLockInput) + txn, err := cmdUtils.ResetUnstakeLock(rpcParameters, config, extendLockInput) utils.CheckError("Error in extending lock: ", err) - err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) + err = razorUtils.WaitForBlockCompletion(rpcParameters, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for resetUnstakeLock: ", err) } //This function is used to reset the lock once the withdraw lock period is over -func (*UtilsStruct) ResetUnstakeLock(client *ethclient.Client, config types.Configurations, extendLockInput types.ExtendLockInput) (common.Hash, error) { - txnOpts := razorUtils.GetTxnOpts(context.Background(), types.TransactionOptions{ - Client: client, +func (*UtilsStruct) ResetUnstakeLock(rpcParameters rpc.RPCParameters, config types.Configurations, extendLockInput types.ExtendLockInput) (common.Hash, error) { + txnOpts := razorUtils.GetTxnOpts(rpcParameters, types.TransactionOptions{ ChainId: core.ChainId, Config: config, ContractAddress: core.StakeManagerAddress, @@ -88,6 +62,11 @@ func (*UtilsStruct) ResetUnstakeLock(client *ethclient.Client, config types.Conf }) log.Info("Extending lock...") + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return core.NilHash, err + } + log.Debug("Executing ResetUnstakeLock transaction with stakerId = ", extendLockInput.StakerId) txn, err := stakeManagerUtils.ResetUnstakeLock(client, txnOpts, extendLockInput.StakerId) if err != nil { diff --git a/cmd/resetUnstakeLock_test.go b/cmd/resetUnstakeLock_test.go index cfd210062..8d5b6cb09 100644 --- a/cmd/resetUnstakeLock_test.go +++ b/cmd/resetUnstakeLock_test.go @@ -18,7 +18,6 @@ import ( func TestExtendLock(t *testing.T) { var extendLockInput types.ExtendLockInput var config types.Configurations - var client *ethclient.Client type args struct { resetLockTxn *Types.Transaction @@ -62,7 +61,7 @@ func TestExtendLock(t *testing.T) { utils := &UtilsStruct{} - got, err := utils.ResetUnstakeLock(client, config, extendLockInput) + got, err := utils.ResetUnstakeLock(rpcParameters, config, extendLockInput) if got != tt.want { t.Errorf("Txn hash for resetLock function, got = %v, want = %v", got, tt.want) } @@ -162,24 +161,26 @@ func TestExecuteExtendLock(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() + setupTestEndpointsEnvironment() + utilsMock.On("IsFlagPassed", mock.Anything).Return(true) fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) utilsMock.On("CheckPassword", mock.Anything).Return(nil) utilsMock.On("AccountManagerForKeystore").Return(&accounts.AccountManager{}, nil) flagSetMock.On("GetStringAddress", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.address, tt.args.addressErr) - utilsMock.On("AssignStakerId", mock.Anything, flagSet, mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) + utilsMock.On("AssignStakerId", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) - utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) - cmdUtilsMock.On("ResetUnstakeLock", mock.AnythingOfType("*ethclient.Client"), config, mock.Anything).Return(tt.args.resetLockTxn, tt.args.resetLockErr) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) + cmdUtilsMock.On("ResetUnstakeLock", mock.Anything, config, mock.Anything).Return(tt.args.resetLockTxn, tt.args.resetLockErr) utils := &UtilsStruct{} fatal = false diff --git a/cmd/reveal.go b/cmd/reveal.go index 637f77a33..49b451efa 100644 --- a/cmd/reveal.go +++ b/cmd/reveal.go @@ -2,24 +2,23 @@ package cmd import ( - "context" "errors" "math/big" "razor/core" "razor/core/types" "razor/pkg/bindings" + "razor/rpc" "razor/utils" "strings" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" Types "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethclient" ) //This function checks for epoch last committed -func (*UtilsStruct) CheckForLastCommitted(ctx context.Context, client *ethclient.Client, staker bindings.StructsStaker, epoch uint32) error { - epochLastCommitted, err := razorUtils.GetEpochLastCommitted(ctx, client, staker.Id) +func (*UtilsStruct) CheckForLastCommitted(rpcParameters rpc.RPCParameters, staker bindings.StructsStaker, epoch uint32) error { + epochLastCommitted, err := razorUtils.GetEpochLastCommitted(rpcParameters, staker.Id) if err != nil { return err } @@ -31,7 +30,7 @@ func (*UtilsStruct) CheckForLastCommitted(ctx context.Context, client *ethclient } //This function checks if the state is reveal or not and then reveals the votes -func (*UtilsStruct) Reveal(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, latestHeader *Types.Header, stateBuffer uint64, commitData types.CommitData, signature []byte) (common.Hash, error) { +func (*UtilsStruct) Reveal(rpcParameters rpc.RPCParameters, config types.Configurations, account types.Account, epoch uint32, latestHeader *Types.Header, stateBuffer uint64, commitData types.CommitData, signature []byte) (common.Hash, error) { if state, err := razorUtils.GetBufferedState(latestHeader, stateBuffer, config.BufferPercent); err != nil || state != 1 { log.Error("Not reveal state") return core.NilHash, err @@ -56,8 +55,7 @@ func (*UtilsStruct) Reveal(ctx context.Context, client *ethclient.Client, config log.Info("Revealing votes...") - txnOpts := razorUtils.GetTxnOpts(ctx, types.TransactionOptions{ - Client: client, + txnOpts := razorUtils.GetTxnOpts(rpcParameters, types.TransactionOptions{ ChainId: core.ChainId, Config: config, ContractAddress: core.VoteManagerAddress, @@ -66,6 +64,13 @@ func (*UtilsStruct) Reveal(ctx context.Context, client *ethclient.Client, config Parameters: []interface{}{epoch, treeRevealData, signature}, Account: account, }) + + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + log.Error(err) + return core.NilHash, err + } + log.Debugf("Executing Reveal transaction wih epoch = %d, treeRevealData = %v, signature = %v", epoch, treeRevealData, signature) txn, err := voteManagerUtils.Reveal(client, txnOpts, epoch, treeRevealData, signature) if err != nil { @@ -113,9 +118,9 @@ func (*UtilsStruct) GenerateTreeRevealData(merkleTree [][][]byte, commitData typ } //This function indexes the reveal events of current epoch -func (*UtilsStruct) IndexRevealEventsOfCurrentEpoch(ctx context.Context, client *ethclient.Client, blockNumber *big.Int, epoch uint32) ([]types.RevealedStruct, error) { +func (*UtilsStruct) IndexRevealEventsOfCurrentEpoch(rpcParameters rpc.RPCParameters, blockNumber *big.Int, epoch uint32) ([]types.RevealedStruct, error) { log.Debug("Fetching reveal events of current epoch...") - fromBlock, err := razorUtils.EstimateBlockNumberAtEpochBeginning(client, blockNumber) + fromBlock, err := razorUtils.EstimateBlockNumberAtEpochBeginning(rpcParameters, blockNumber) if err != nil { return nil, errors.New("Not able to Fetch Block: " + err.Error()) } @@ -128,7 +133,7 @@ func (*UtilsStruct) IndexRevealEventsOfCurrentEpoch(ctx context.Context, client }, } log.Debugf("IndexRevealEventsOfCurrentEpoch: Query to send in filter logs: %+v", query) - logs, err := clientUtils.FilterLogsWithRetry(ctx, client, query) + logs, err := clientUtils.FilterLogsWithRetry(rpcParameters, query) if err != nil { return nil, err } diff --git a/cmd/reveal_test.go b/cmd/reveal_test.go index 0a1905f90..e592173d4 100644 --- a/cmd/reveal_test.go +++ b/cmd/reveal_test.go @@ -1,7 +1,6 @@ package cmd import ( - "context" "errors" "fmt" "math/big" @@ -14,12 +13,10 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" Types "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethclient" "github.com/stretchr/testify/mock" ) func TestCheckForLastCommitted(t *testing.T) { - var client *ethclient.Client staker := bindings.StructsStaker{ Id: 1, } @@ -66,11 +63,11 @@ func TestCheckForLastCommitted(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetEpochLastCommitted", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.epochLastCommitted, tt.args.epochLastCommittedErr) + utilsMock.On("GetEpochLastCommitted", mock.Anything, mock.Anything).Return(tt.args.epochLastCommitted, tt.args.epochLastCommittedErr) utils := &UtilsStruct{} - err := utils.CheckForLastCommitted(context.Background(), client, staker, tt.args.epoch) + err := utils.CheckForLastCommitted(rpcParameters, staker, tt.args.epoch) if err == nil || tt.want == nil { if err != tt.want { t.Errorf("Error for CheckForLastCommitted function, got = %v, want %v", err, tt.want) @@ -87,7 +84,6 @@ func TestCheckForLastCommitted(t *testing.T) { func TestReveal(t *testing.T) { var ( - client *ethclient.Client commitData types.CommitData signature []byte account types.Account @@ -171,7 +167,7 @@ func TestReveal(t *testing.T) { utils := &UtilsStruct{} - got, err := utils.Reveal(context.Background(), client, config, account, epoch, latestHeader, stateBuffer, commitData, signature) + got, err := utils.Reveal(rpcParameters, config, account, epoch, latestHeader, stateBuffer, commitData, signature) if got != tt.want { t.Errorf("Txn hash for Reveal function, got = %v, want = %v", got, tt.want) } @@ -257,7 +253,6 @@ func TestGenerateTreeRevealData(t *testing.T) { func TestIndexRevealEventsOfCurrentEpoch(t *testing.T) { var ( - client *ethclient.Client blockNumber *big.Int epoch uint32 ) @@ -321,12 +316,12 @@ func TestIndexRevealEventsOfCurrentEpoch(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("EstimateBlockNumberAtEpochBeginning", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.fromBlock, tt.args.fromBlockErr) - clientUtilsMock.On("FilterLogsWithRetry", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.logs, tt.args.logsErr) + utilsMock.On("EstimateBlockNumberAtEpochBeginning", mock.Anything, mock.Anything).Return(tt.args.fromBlock, tt.args.fromBlockErr) + clientUtilsMock.On("FilterLogsWithRetry", mock.Anything, mock.Anything).Return(tt.args.logs, tt.args.logsErr) abiUtilsMock.On("Parse", mock.Anything).Return(tt.args.contractAbi, tt.args.contractAbiErr) abiUtilsMock.On("Unpack", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.data, tt.args.unpackErr) ut := &UtilsStruct{} - got, err := ut.IndexRevealEventsOfCurrentEpoch(context.Background(), client, blockNumber, epoch) + got, err := ut.IndexRevealEventsOfCurrentEpoch(rpcParameters, blockNumber, epoch) if (err != nil) != tt.wantErr { t.Errorf("IndexRevealEventsOfCurrentEpoch() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/cmd/root.go b/cmd/root.go index 56eca6b7b..d072d3cf9 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -14,7 +14,6 @@ import ( var ( Provider string - AlternateProvider string GasMultiplier float32 BufferPercent int32 WaitTime int32 @@ -30,7 +29,7 @@ var ( LogFileMaxAge int ) -var log = logger.NewLogger() +var log = logger.GetLogger() // rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ @@ -61,7 +60,6 @@ func init() { cobra.OnInitialize(initConfig) rootCmd.PersistentFlags().StringVarP(&Provider, "provider", "p", "", "provider name") - rootCmd.PersistentFlags().StringVarP(&AlternateProvider, "alternateProvider", "", "", "alternate provider name") rootCmd.PersistentFlags().Float32VarP(&GasMultiplier, "gasmultiplier", "g", -1, "gas multiplier value") rootCmd.PersistentFlags().Int32VarP(&BufferPercent, "buffer", "b", 0, "buffer percent") rootCmd.PersistentFlags().Int32VarP(&WaitTime, "wait", "w", -1, "wait time") diff --git a/cmd/setConfig.go b/cmd/setConfig.go index 7f0ad8746..9f4b7d894 100644 --- a/cmd/setConfig.go +++ b/cmd/setConfig.go @@ -29,12 +29,11 @@ Example: // This function returns the error if there is any and sets the config func (*UtilsStruct) SetConfig(flagSet *pflag.FlagSet) error { - log.Debug("Checking to assign log file...") - fileUtils.AssignLogFile(flagSet, types.Configurations{}) + _, _, _, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) flagDetails := []types.FlagDetail{ {Name: "provider", Type: "string"}, - {Name: "alternateProvider", Type: "string"}, {Name: "gasmultiplier", Type: "float32"}, {Name: "buffer", Type: "int32"}, {Name: "wait", Type: "int32"}, @@ -62,7 +61,6 @@ func (*UtilsStruct) SetConfig(flagSet *pflag.FlagSet) error { configDetails := []types.ConfigDetail{ {FlagName: "provider", Key: "provider", DefaultValue: ""}, - {FlagName: "alternateProvider", Key: "alternateProvider", DefaultValue: ""}, {FlagName: "gasmultiplier", Key: "gasmultiplier", DefaultValue: core.DefaultGasMultiplier}, {FlagName: "buffer", Key: "buffer", DefaultValue: core.DefaultBufferPercent}, {FlagName: "wait", Key: "wait", DefaultValue: core.DefaultWaitTime}, @@ -152,7 +150,6 @@ func init() { var ( Provider string - AlternateProvider string GasMultiplier float32 BufferPercent int32 WaitTime int32 @@ -170,7 +167,6 @@ func init() { LogFileMaxAge int ) setConfig.Flags().StringVarP(&Provider, "provider", "p", "", "provider name") - setConfig.Flags().StringVarP(&AlternateProvider, "alternateProvider", "", "", "alternate provider name") setConfig.Flags().Float32VarP(&GasMultiplier, "gasmultiplier", "g", -1, "gas multiplier value") setConfig.Flags().Int32VarP(&BufferPercent, "buffer", "b", 0, "buffer percent") setConfig.Flags().Int32VarP(&WaitTime, "wait", "w", 0, "wait time (in secs)") diff --git a/cmd/setConfig_test.go b/cmd/setConfig_test.go index b25f7a858..2b88b6316 100644 --- a/cmd/setConfig_test.go +++ b/cmd/setConfig_test.go @@ -2,6 +2,7 @@ package cmd import ( "errors" + "razor/core/types" "testing" "github.com/spf13/pflag" @@ -74,7 +75,10 @@ func TestSetConfig(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() + setupTestEndpointsEnvironment() + cmdUtilsMock.On("GetConfigData").Return(types.Configurations{}, nil) + utilsMock.On("IsFlagPassed", mock.Anything).Return(false) fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) flagSetMock.On("FetchFlagInput", flagSet, mock.Anything, mock.Anything).Return(tt.args.flagInput, tt.args.flagInputErr) flagSetMock.On("Changed", mock.Anything, mock.Anything).Return(tt.args.isFlagPassed) diff --git a/cmd/setDelegation.go b/cmd/setDelegation.go index 4de0d08f4..36f28ca50 100644 --- a/cmd/setDelegation.go +++ b/cmd/setDelegation.go @@ -2,16 +2,13 @@ package cmd import ( - "context" - "razor/accounts" "razor/core" "razor/core/types" - "razor/logger" "razor/pkg/bindings" + "razor/rpc" "razor/utils" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/pflag" "github.com/spf13/cobra" @@ -35,30 +32,8 @@ func initialiseSetDelegation(cmd *cobra.Command, args []string) { //This function sets the flags appropriately and executes the SetDelegation function func (*UtilsStruct) ExecuteSetDelegation(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - log.Debugf("ExecuteSetDelegation: Config: %+v", config) - - client := razorUtils.ConnectToClient(config.Provider) - - address, err := flagSetUtils.GetStringAddress(flagSet) - utils.CheckError("Error in getting address: ", err) - - logger.SetLoggerParameters(client, address) - - log.Debug("Checking to assign log file...") - fileUtils.AssignLogFile(flagSet, config) - - log.Debug("Getting password...") - password := razorUtils.AssignPassword(flagSet) - - accountManager, err := razorUtils.AccountManagerForKeystore() - utils.CheckError("Error in getting accounts manager for keystore: ", err) - - account := accounts.InitAccountStruct(address, password, accountManager) - - err = razorUtils.CheckPassword(account) - utils.CheckError("Error in fetching private key from given password: ", err) + config, rpcParameters, account, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) statusString, err := flagSetUtils.GetStringStatus(flagSet) utils.CheckError("Error in getting status: ", err) @@ -66,7 +41,7 @@ func (*UtilsStruct) ExecuteSetDelegation(flagSet *pflag.FlagSet) { status, err := stringUtils.ParseBool(statusString) utils.CheckError("Error in parsing status to boolean: ", err) - stakerId, err := razorUtils.GetStakerId(context.Background(), client, address) + stakerId, err := razorUtils.GetStakerId(rpcParameters, account.Address) utils.CheckError("StakerId error: ", err) commission, err := flagSetUtils.GetUint8Commission(flagSet) @@ -80,17 +55,17 @@ func (*UtilsStruct) ExecuteSetDelegation(flagSet *pflag.FlagSet) { Account: account, } - txn, err := cmdUtils.SetDelegation(context.Background(), client, config, delegationInput) + txn, err := cmdUtils.SetDelegation(rpcParameters, config, delegationInput) utils.CheckError("SetDelegation error: ", err) if txn != core.NilHash { - err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) + err = razorUtils.WaitForBlockCompletion(rpcParameters, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for setDelegation: ", err) } } //This function allows the staker to start accepting/rejecting delegation requests -func (*UtilsStruct) SetDelegation(ctx context.Context, client *ethclient.Client, config types.Configurations, delegationInput types.SetDelegationInput) (common.Hash, error) { - stakerInfo, err := razorUtils.GetStaker(ctx, client, delegationInput.StakerId) +func (*UtilsStruct) SetDelegation(rpcParameters rpc.RPCParameters, config types.Configurations, delegationInput types.SetDelegationInput) (common.Hash, error) { + stakerInfo, err := razorUtils.GetStaker(rpcParameters, delegationInput.StakerId) if err != nil { return core.NilHash, err } @@ -101,14 +76,13 @@ func (*UtilsStruct) SetDelegation(ctx context.Context, client *ethclient.Client, Commission: delegationInput.Commission, Account: delegationInput.Account, } - err = cmdUtils.UpdateCommission(ctx, config, client, updateCommissionInput) + err = cmdUtils.UpdateCommission(rpcParameters, config, updateCommissionInput) if err != nil { return core.NilHash, err } } txnOpts := types.TransactionOptions{ - Client: client, ChainId: core.ChainId, Config: config, ContractAddress: core.StakeManagerAddress, @@ -123,7 +97,12 @@ func (*UtilsStruct) SetDelegation(ctx context.Context, client *ethclient.Client, return core.NilHash, nil } log.Infof("Setting delegation acceptance of Staker %d to %t", delegationInput.StakerId, delegationInput.Status) - setDelegationAcceptanceTxnOpts := razorUtils.GetTxnOpts(ctx, txnOpts) + setDelegationAcceptanceTxnOpts := razorUtils.GetTxnOpts(rpcParameters, txnOpts) + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return core.NilHash, err + } + log.Debug("Executing SetDelegationAcceptance transaction with status ", delegationInput.Status) delegationAcceptanceTxn, err := stakeManagerUtils.SetDelegationAcceptance(client, setDelegationAcceptanceTxnOpts, delegationInput.Status) if err != nil { diff --git a/cmd/setDelegation_test.go b/cmd/setDelegation_test.go index 9cb0863c7..31b2e57ef 100644 --- a/cmd/setDelegation_test.go +++ b/cmd/setDelegation_test.go @@ -1,7 +1,6 @@ package cmd import ( - "context" "errors" "math/big" "razor/accounts" @@ -18,8 +17,6 @@ import ( ) func TestSetDelegation(t *testing.T) { - - var client *ethclient.Client var config = types.Configurations{ Provider: "127.0.0.1", GasMultiplier: 1, @@ -135,14 +132,14 @@ func TestSetDelegation(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetStaker", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.staker, tt.args.stakerErr) - cmdUtilsMock.On("UpdateCommission", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.UpdateCommissionErr) + utilsMock.On("GetStaker", mock.Anything, mock.Anything).Return(tt.args.staker, tt.args.stakerErr) + cmdUtilsMock.On("UpdateCommission", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.UpdateCommissionErr) utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(TxnOpts) stakeManagerMock.On("SetDelegationAcceptance", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.AnythingOfType("bool")).Return(tt.args.setDelegationAcceptanceTxn, tt.args.setDelegationAcceptanceErr) transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) utils := &UtilsStruct{} - got, err := utils.SetDelegation(context.Background(), client, config, types.SetDelegationInput{ + got, err := utils.SetDelegation(rpcParameters, config, types.SetDelegationInput{ Status: tt.args.status, Commission: tt.args.commission, }) @@ -372,15 +369,17 @@ func TestExecuteSetDelegation(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() + setupTestEndpointsEnvironment() + utilsMock.On("IsFlagPassed", mock.Anything).Return(true) fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) @@ -391,9 +390,9 @@ func TestExecuteSetDelegation(t *testing.T) { flagSetMock.On("GetUint8Commission", flagSet).Return(tt.args.commission, tt.args.commissionErr) stringMock.On("ParseBool", mock.AnythingOfType("string")).Return(tt.args.parseStatus, tt.args.parseStatusErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) - utilsMock.On("GetStakerId", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) - cmdUtilsMock.On("SetDelegation", mock.Anything, mock.Anything, config, mock.Anything).Return(tt.args.setDelegationHash, tt.args.setDelegationErr) - utilsMock.On("WaitForBlockCompletion", client, mock.AnythingOfType("string")).Return(nil) + utilsMock.On("GetStakerId", mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) + cmdUtilsMock.On("SetDelegation", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.setDelegationHash, tt.args.setDelegationErr) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) utils := &UtilsStruct{} fatal = false diff --git a/cmd/stakerInfo.go b/cmd/stakerInfo.go index 5dc5a6631..919c2dbb8 100644 --- a/cmd/stakerInfo.go +++ b/cmd/stakerInfo.go @@ -2,13 +2,11 @@ package cmd import ( - "context" - "github.com/ethereum/go-ethereum/ethclient" "github.com/olekukonko/tablewriter" "github.com/spf13/cobra" "github.com/spf13/pflag" "os" - "razor/logger" + "razor/rpc" "razor/utils" "strconv" ) @@ -30,39 +28,34 @@ func initialiseStakerInfo(cmd *cobra.Command, args []string) { //This function sets the flag appropriately and executes the GetStakerInfo function func (*UtilsStruct) ExecuteStakerinfo(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - log.Debugf("ExecuteStakerinfo: Config: %+v", config) - - client := razorUtils.ConnectToClient(config.Provider) - logger.SetLoggerParameters(client, "") + _, rpcParameters, _, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) stakerId, err := flagSetUtils.GetUint32StakerId(flagSet) utils.CheckError("Error in getting stakerId: ", err) log.Debug("ExecuteStakerinfo: StakerId: ", stakerId) log.Debug("ExecuteStakerinfo: Calling GetStakerInfo() with argument stakerId = ", stakerId) - err = cmdUtils.GetStakerInfo(context.Background(), client, stakerId) + err = cmdUtils.GetStakerInfo(rpcParameters, stakerId) utils.CheckError("Error in getting staker info: ", err) } //This function provides the staker details like age, stake, maturity etc. -func (*UtilsStruct) GetStakerInfo(ctx context.Context, client *ethclient.Client, stakerId uint32) error { - callOpts := razorUtils.GetOptions() - stakerInfo, err := stakeManagerUtils.StakerInfo(client, &callOpts, stakerId) +func (*UtilsStruct) GetStakerInfo(rpcParameters rpc.RPCParameters, stakerId uint32) error { + stakerInfo, err := razorUtils.StakerInfo(rpcParameters, stakerId) if err != nil { return err } - maturity, err := stakeManagerUtils.GetMaturity(client, &callOpts, stakerInfo.Age) + maturity, err := razorUtils.GetMaturity(rpcParameters, stakerInfo.Age) if err != nil { return err } - epoch, err := razorUtils.GetEpoch(ctx, client) + epoch, err := razorUtils.GetEpoch(rpcParameters) if err != nil { return err } - influence, err := razorUtils.GetInfluenceSnapshot(ctx, client, stakerId, epoch) + influence, err := razorUtils.GetInfluenceSnapshot(rpcParameters, stakerId, epoch) if err != nil { return err } diff --git a/cmd/stakerInfo_test.go b/cmd/stakerInfo_test.go index db5a69e19..170b00b17 100644 --- a/cmd/stakerInfo_test.go +++ b/cmd/stakerInfo_test.go @@ -9,14 +9,11 @@ import ( "github.com/spf13/pflag" "github.com/stretchr/testify/mock" "math/big" - "razor/cmd/mocks" "razor/core/types" - utilsPkgMocks "razor/utils/mocks" "testing" ) func TestUtilsStruct_GetStakerInfo(t *testing.T) { - var client *ethclient.Client var callOpts bind.CallOpts stake, _ := new(big.Int).SetString("10000000000000000000000", 10) @@ -31,7 +28,6 @@ func TestUtilsStruct_GetStakerInfo(t *testing.T) { } type args struct { - client *ethclient.Client stakerId uint32 callOpts bind.CallOpts stakerInfo types.Staker @@ -53,7 +49,6 @@ func TestUtilsStruct_GetStakerInfo(t *testing.T) { name: "Test 1: When StakerInfo executes properly", fields: testUtils, args: args{ - client: client, stakerId: 1, callOpts: bind.CallOpts{ Pending: false, @@ -85,7 +80,6 @@ func TestUtilsStruct_GetStakerInfo(t *testing.T) { name: "Test 2: When there is error fetching staker info", fields: testUtils, args: args{ - client: client, stakerId: 1, callOpts: bind.CallOpts{ Pending: false, @@ -117,7 +111,6 @@ func TestUtilsStruct_GetStakerInfo(t *testing.T) { name: "Test 3: When there is error fetching maturity", fields: testUtils, args: args{ - client: client, stakerId: 1, callOpts: bind.CallOpts{ Pending: false, @@ -149,7 +142,6 @@ func TestUtilsStruct_GetStakerInfo(t *testing.T) { name: "Test 4: When there is error fetching influence", fields: testUtils, args: args{ - client: client, stakerId: 1, callOpts: bind.CallOpts{ Pending: false, @@ -181,7 +173,6 @@ func TestUtilsStruct_GetStakerInfo(t *testing.T) { name: "Test 5: When there is error fetching epoch", fields: testUtils, args: args{ - client: client, stakerId: 1, callOpts: bind.CallOpts{ Pending: false, @@ -216,12 +207,12 @@ func TestUtilsStruct_GetStakerInfo(t *testing.T) { SetUpMockInterfaces() utilsMock.On("GetOptions").Return(callOpts) - stakeManagerMock.On("StakerInfo", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.CallOpts"), mock.AnythingOfType("uint32")).Return(tt.args.stakerInfo, tt.args.stakerInfoErr) - stakeManagerMock.On("GetMaturity", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.CallOpts"), mock.AnythingOfType("uint32")).Return(tt.args.maturity, tt.args.maturityErr) - utilsMock.On("GetInfluenceSnapshot", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.influence, tt.args.influenceErr) - utilsMock.On("GetEpoch", mock.Anything, mock.Anything).Return(tt.args.epoch, tt.args.epochErr) + utilsMock.On("StakerInfo", mock.Anything, mock.Anything).Return(tt.args.stakerInfo, tt.args.stakerInfoErr) + utilsMock.On("GetMaturity", mock.Anything, mock.AnythingOfType("uint32")).Return(tt.args.maturity, tt.args.maturityErr) + utilsMock.On("GetInfluenceSnapshot", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.influence, tt.args.influenceErr) + utilsMock.On("GetEpoch", mock.Anything).Return(tt.args.epoch, tt.args.epochErr) utils := &UtilsStruct{} - err := utils.GetStakerInfo(context.Background(), tt.args.client, tt.args.stakerId) + err := utils.GetStakerInfo(rpcParameters, tt.args.stakerId) if err == nil || tt.wantErr == nil { if err != tt.wantErr { t.Errorf("Error for StakerInfo function, got = %v, want %v", err, tt.wantErr) @@ -297,27 +288,21 @@ func TestUtilsStruct_ExecuteStakerinfo(t *testing.T) { expectedFatal: true, }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(utilsPkgMocks.Utils) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - flagSetUtilsMock := new(mocks.FlagSetInterface) - fileUtilsMock := new(utilsPkgMocks.FileUtils) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - flagSetUtils = flagSetUtilsMock - fileUtils = fileUtilsMock + SetUpMockInterfaces() + setupTestEndpointsEnvironment() + utilsMock.On("IsFlagPassed", mock.Anything).Return(false) fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) - flagSetUtilsMock.On("GetUint32StakerId", flagSet).Return(tt.args.stakerId, tt.args.stakerIdErr) - cmdUtilsMock.On("GetStakerInfo", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.stakerInfoErr) + flagSetMock.On("GetUint32StakerId", flagSet).Return(tt.args.stakerId, tt.args.stakerIdErr) + cmdUtilsMock.On("GetStakerInfo", mock.Anything, mock.Anything).Return(tt.args.stakerInfoErr) utils := &UtilsStruct{} fatal = false diff --git a/cmd/struct-utils.go b/cmd/struct-utils.go index 0c22a71d1..febc79d30 100644 --- a/cmd/struct-utils.go +++ b/cmd/struct-utils.go @@ -2,7 +2,6 @@ package cmd import ( - "context" "crypto/ecdsa" "errors" "math/big" @@ -11,6 +10,7 @@ import ( "razor/core/types" "razor/path" "razor/pkg/bindings" + "razor/rpc" "razor/utils" "strconv" "time" @@ -195,58 +195,6 @@ func (stakeManagerUtils StakeManagerUtils) RedeemBounty(client *ethclient.Client return ExecuteTransaction(stakeManager, "RedeemBounty", opts, bountyId) } -//This function returns the staker Info -func (stakeManagerUtils StakeManagerUtils) StakerInfo(client *ethclient.Client, opts *bind.CallOpts, stakerId uint32) (types.Staker, error) { - stakeManager := razorUtils.GetStakeManager(client) - returnedValues := utils.InvokeFunctionWithTimeout(stakeManager, "Stakers", opts, stakerId) - returnedError := utils.CheckIfAnyError(returnedValues) - if returnedError != nil { - return types.Staker{}, returnedError - } - staker := returnedValues[0].Interface().(struct { - AcceptDelegation bool - IsSlashed bool - Commission uint8 - Id uint32 - Age uint32 - Address common.Address - TokenAddress common.Address - EpochFirstStakedOrLastPenalized uint32 - EpochCommissionLastUpdated uint32 - Stake *big.Int - StakerReward *big.Int - }) - return staker, nil -} - -//This function returns the maturity -func (stakeManagerUtils StakeManagerUtils) GetMaturity(client *ethclient.Client, opts *bind.CallOpts, age uint32) (uint16, error) { - stakeManager := razorUtils.GetStakeManager(client) - index := age / 10000 - returnedValues := utils.InvokeFunctionWithTimeout(stakeManager, "Maturities", opts, big.NewInt(int64(index))) - returnedError := utils.CheckIfAnyError(returnedValues) - if returnedError != nil { - return 0, returnedError - } - return returnedValues[0].Interface().(uint16), nil -} - -//This function returns the bounty lock -func (stakeManagerUtils StakeManagerUtils) GetBountyLock(client *ethclient.Client, opts *bind.CallOpts, bountyId uint32) (types.BountyLock, error) { - stakeManager := razorUtils.GetStakeManager(client) - returnedValues := utils.InvokeFunctionWithTimeout(stakeManager, "BountyLocks", opts, bountyId) - returnedError := utils.CheckIfAnyError(returnedValues) - if returnedError != nil { - return types.BountyLock{}, returnedError - } - bountyLock := returnedValues[0].Interface().(struct { - RedeemAfter uint32 - BountyHunter common.Address - Amount *big.Int - }) - return bountyLock, nil -} - //This function is used to claim the staker reward func (stakeManagerUtils StakeManagerUtils) ClaimStakerReward(client *ethclient.Client, opts *bind.TransactOpts) (*Types.Transaction, error) { stakeManager := razorUtils.GetStakeManager(client) @@ -387,30 +335,15 @@ func (blockManagerUtils BlockManagerUtils) Propose(client *ethclient.Client, opt } //This function returns the sorted Ids -func (blockManagerUtils BlockManagerUtils) GiveSorted(blockManager *bindings.BlockManager, opts *bind.TransactOpts, epoch uint32, leafId uint16, sortedValues []*big.Int) (*Types.Transaction, error) { +func (blockManagerUtils BlockManagerUtils) GiveSorted(client *ethclient.Client, opts *bind.TransactOpts, epoch uint32, leafId uint16, sortedValues []*big.Int) (*Types.Transaction, error) { + blockManager := razorUtils.GetBlockManager(client) return ExecuteTransaction(blockManager, "GiveSorted", opts, epoch, leafId, sortedValues) } //This function resets the dispute -func (blockManagerUtils BlockManagerUtils) ResetDispute(blockManager *bindings.BlockManager, opts *bind.TransactOpts, epoch uint32) (*Types.Transaction, error) { - return ExecuteTransaction(blockManager, "ResetDispute", opts, epoch) -} - -// This functiom gets Disputes mapping -func (blockManagerUtils BlockManagerUtils) Disputes(client *ethclient.Client, opts *bind.CallOpts, epoch uint32, address common.Address) (types.DisputesStruct, error) { +func (blockManagerUtils BlockManagerUtils) ResetDispute(client *ethclient.Client, opts *bind.TransactOpts, epoch uint32) (*Types.Transaction, error) { blockManager := razorUtils.GetBlockManager(client) - returnedValues := utils.InvokeFunctionWithTimeout(blockManager, "Disputes", opts, epoch, address) - returnedError := utils.CheckIfAnyError(returnedValues) - if returnedError != nil { - return types.DisputesStruct{}, returnedError - } - disputesMapping := returnedValues[0].Interface().(struct { - LeafId uint16 - LastVisitedValue *big.Int - AccWeight *big.Int - Median *big.Int - }) - return disputesMapping, nil + return ExecuteTransaction(blockManager, "ResetDispute", opts, epoch) } //This function is used to reveal the values @@ -455,17 +388,6 @@ func (voteManagerUtils VoteManagerUtils) Commit(client *ethclient.Client, opts * return txn, nil } -//This function is used to check the allowance of staker -func (tokenManagerUtils TokenManagerUtils) Allowance(client *ethclient.Client, opts *bind.CallOpts, owner common.Address, spender common.Address) (*big.Int, error) { - tokenManager := razorUtils.GetTokenManager(client) - returnedValues := utils.InvokeFunctionWithTimeout(tokenManager, "Allowance", opts, owner, spender) - returnedError := utils.CheckIfAnyError(returnedValues) - if returnedError != nil { - return nil, returnedError - } - return returnedValues[0].Interface().(*big.Int), nil -} - //This function is used to approve the transaction func (tokenManagerUtils TokenManagerUtils) Approve(client *ethclient.Client, opts *bind.TransactOpts, spender common.Address, amount *big.Int) (*Types.Transaction, error) { tokenManager := razorUtils.GetTokenManager(client) @@ -694,8 +616,8 @@ func (c CryptoUtils) HexToECDSA(hexKey string) (*ecdsa.PrivateKey, error) { } //This function is used to give the sorted Ids -func (*UtilsStruct) GiveSorted(ctx context.Context, client *ethclient.Client, blockManager *bindings.BlockManager, txnArgs types.TransactionOptions, epoch uint32, assetId uint16, sortedStakers []*big.Int) error { - return GiveSorted(ctx, client, blockManager, txnArgs, epoch, assetId, sortedStakers) +func (*UtilsStruct) GiveSorted(rpcParameters rpc.RPCParameters, txnArgs types.TransactionOptions, epoch uint32, assetId uint16, sortedStakers []*big.Int) error { + return GiveSorted(rpcParameters, txnArgs, epoch, assetId, sortedStakers) } //This function is used to write config as diff --git a/cmd/transfer.go b/cmd/transfer.go index 3a66b8f45..a24138976 100644 --- a/cmd/transfer.go +++ b/cmd/transfer.go @@ -2,16 +2,13 @@ package cmd import ( - "context" "razor/accounts" "razor/core" "razor/core/types" - "razor/logger" "razor/pkg/bindings" + "razor/rpc" "razor/utils" - "github.com/ethereum/go-ethereum/ethclient" - "github.com/spf13/pflag" "github.com/ethereum/go-ethereum/common" @@ -35,20 +32,14 @@ func initialiseTransfer(cmd *cobra.Command, args []string) { //This function sets the flag appropriately and executes the Transfer function func (*UtilsStruct) ExecuteTransfer(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - log.Debugf("ExecuteTransfer: Config: %+v", config) + config, rpcParameters, _, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) - client := razorUtils.ConnectToClient(config.Provider) + log.Debugf("ExecuteTransfer: Config: %+v", config) fromAddress, err := flagSetUtils.GetStringFrom(flagSet) utils.CheckError("Error in getting fromAddress: ", err) - logger.SetLoggerParameters(client, fromAddress) - - log.Debug("Checking to assign log file...") - fileUtils.AssignLogFile(flagSet, config) - log.Debug("Getting password...") password := razorUtils.AssignPassword(flagSet) @@ -63,7 +54,7 @@ func (*UtilsStruct) ExecuteTransfer(flagSet *pflag.FlagSet) { toAddress, err := flagSetUtils.GetStringTo(flagSet) utils.CheckError("Error in getting toAddress: ", err) - balance, err := razorUtils.FetchBalance(client, fromAddress) + balance, err := razorUtils.FetchBalance(rpcParameters, account.Address) utils.CheckError("Error in fetching razor balance: ", err) log.Debug("Getting amount in wei...") @@ -77,20 +68,19 @@ func (*UtilsStruct) ExecuteTransfer(flagSet *pflag.FlagSet) { Account: account, } - txn, err := cmdUtils.Transfer(client, config, transferInput) + txn, err := cmdUtils.Transfer(rpcParameters, config, transferInput) utils.CheckError("Transfer error: ", err) - err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) + err = razorUtils.WaitForBlockCompletion(rpcParameters, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for transfer: ", err) } //This function transfers the razors from your account to others account -func (*UtilsStruct) Transfer(client *ethclient.Client, config types.Configurations, transferInput types.TransferInput) (common.Hash, error) { +func (*UtilsStruct) Transfer(rpcParameters rpc.RPCParameters, config types.Configurations, transferInput types.TransferInput) (common.Hash, error) { log.Debug("Checking for sufficient balance...") razorUtils.CheckAmountAndBalance(transferInput.ValueInWei, transferInput.Balance) - txnOpts := razorUtils.GetTxnOpts(context.Background(), types.TransactionOptions{ - Client: client, + txnOpts := razorUtils.GetTxnOpts(rpcParameters, types.TransactionOptions{ ChainId: core.ChainId, Config: config, ContractAddress: core.RAZORAddress, @@ -100,6 +90,10 @@ func (*UtilsStruct) Transfer(client *ethclient.Client, config types.Configuratio Account: transferInput.Account, }) log.Infof("Transferring %g tokens from %s to %s", utils.GetAmountInDecimal(transferInput.ValueInWei), transferInput.Account.Address, transferInput.ToAddress) + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return core.NilHash, err + } log.Debugf("Executing Transfer transaction with toAddress: %s, amount: %s", transferInput.ToAddress, transferInput.ValueInWei) txn, err := tokenManagerUtils.Transfer(client, txnOpts, common.HexToAddress(transferInput.ToAddress), transferInput.ValueInWei) diff --git a/cmd/transfer_test.go b/cmd/transfer_test.go index 9b44ada66..4adb7aef3 100644 --- a/cmd/transfer_test.go +++ b/cmd/transfer_test.go @@ -17,7 +17,6 @@ import ( ) func TestTransfer(t *testing.T) { - var client *ethclient.Client var config types.Configurations type args struct { @@ -70,7 +69,7 @@ func TestTransfer(t *testing.T) { utils := &UtilsStruct{} - got, err := utils.Transfer(client, config, types.TransferInput{ + got, err := utils.Transfer(rpcParameters, config, types.TransferInput{ ValueInWei: big.NewInt(1).Mul(big.NewInt(1), big.NewInt(1e18)), }) if got != tt.want { @@ -235,14 +234,16 @@ func TestExecuteTransfer(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() + setupTestEndpointsEnvironment() + utilsMock.On("IsFlagPassed", mock.Anything).Return(false) fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) @@ -252,9 +253,9 @@ func TestExecuteTransfer(t *testing.T) { flagSetMock.On("GetStringTo", flagSet).Return(tt.args.to, tt.args.toErr) cmdUtilsMock.On("AssignAmountInWei", flagSet).Return(tt.args.amount, tt.args.amountErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) - utilsMock.On("FetchBalance", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.balance, tt.args.balanceErr) - cmdUtilsMock.On("Transfer", mock.AnythingOfType("*ethclient.Client"), config, mock.AnythingOfType("types.TransferInput")).Return(tt.args.transferHash, tt.args.transferErr) - utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) + utilsMock.On("FetchBalance", mock.Anything, mock.Anything).Return(tt.args.balance, tt.args.balanceErr) + cmdUtilsMock.On("Transfer", mock.Anything, config, mock.Anything).Return(tt.args.transferHash, tt.args.transferErr) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) utils := &UtilsStruct{} fatal = false diff --git a/cmd/unlockWithdraw.go b/cmd/unlockWithdraw.go index 187cd907b..e9dfd9f75 100644 --- a/cmd/unlockWithdraw.go +++ b/cmd/unlockWithdraw.go @@ -2,19 +2,16 @@ package cmd import ( - "context" "errors" "math/big" - "razor/accounts" "razor/core" "razor/core/types" - "razor/logger" "razor/pkg/bindings" + "razor/rpc" "razor/utils" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/cobra" "github.com/spf13/pflag" ) @@ -34,48 +31,25 @@ func initializeUnlockWithdraw(cmd *cobra.Command, args []string) { //This function sets the flag appropriately and executes the UnlockWithdraw function func (*UtilsStruct) ExecuteUnlockWithdraw(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - log.Debugf("ExecuteUnlockWithdraw: Config: %+v", config) + config, rpcParameters, account, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) - client := razorUtils.ConnectToClient(config.Provider) - - address, err := flagSetUtils.GetStringAddress(flagSet) - utils.CheckError("Error in getting address: ", err) - log.Debug("ExecuteUnlockWithdraw: Address: ", address) - - logger.SetLoggerParameters(client, address) - - log.Debug("Checking to assign log file...") - fileUtils.AssignLogFile(flagSet, config) - - log.Debug("Getting password...") - password := razorUtils.AssignPassword(flagSet) - - accountManager, err := razorUtils.AccountManagerForKeystore() - utils.CheckError("Error in getting accounts manager for keystore: ", err) - - account := accounts.InitAccountStruct(address, password, accountManager) - - err = razorUtils.CheckPassword(account) - utils.CheckError("Error in fetching private key from given password: ", err) - - stakerId, err := razorUtils.AssignStakerId(context.Background(), flagSet, client, address) + stakerId, err := razorUtils.AssignStakerId(rpcParameters, flagSet, account.Address) utils.CheckError("Error in fetching stakerId: ", err) log.Debug("ExecuteUnlockWithdraw: StakerId: ", stakerId) - txn, err := cmdUtils.HandleWithdrawLock(context.Background(), client, account, config, stakerId) + txn, err := cmdUtils.HandleWithdrawLock(rpcParameters, account, config, stakerId) utils.CheckError("HandleWithdrawLock error: ", err) if txn != core.NilHash { - err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) + err = razorUtils.WaitForBlockCompletion(rpcParameters, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for unlockWithdraw: ", err) } } //This function handles the Withdraw lock -func (*UtilsStruct) HandleWithdrawLock(ctx context.Context, client *ethclient.Client, account types.Account, configurations types.Configurations, stakerId uint32) (common.Hash, error) { - withdrawLock, err := razorUtils.GetLock(ctx, client, account.Address, stakerId, 1) +func (*UtilsStruct) HandleWithdrawLock(rpcParameters rpc.RPCParameters, account types.Account, configurations types.Configurations, stakerId uint32) (common.Hash, error) { + withdrawLock, err := razorUtils.GetLock(rpcParameters, account.Address, stakerId, 1) if err != nil { return core.NilHash, err } @@ -86,7 +60,7 @@ func (*UtilsStruct) HandleWithdrawLock(ctx context.Context, client *ethclient.Cl return core.NilHash, errors.New("initiate withdrawal of Razors before unlocking withdraw") } - epoch, err := razorUtils.GetEpoch(ctx, client) + epoch, err := razorUtils.GetEpoch(rpcParameters) if err != nil { log.Error("Error in fetching epoch") return core.NilHash, err @@ -102,7 +76,6 @@ func (*UtilsStruct) HandleWithdrawLock(ctx context.Context, client *ethclient.Cl if big.NewInt(int64(epoch)).Cmp(withdrawLock.UnlockAfter) >= 0 { txnArgs := types.TransactionOptions{ - Client: client, ChainId: core.ChainId, Config: configurations, ContractAddress: core.StakeManagerAddress, @@ -111,16 +84,20 @@ func (*UtilsStruct) HandleWithdrawLock(ctx context.Context, client *ethclient.Cl Parameters: []interface{}{stakerId}, Account: account, } - txnOpts := razorUtils.GetTxnOpts(ctx, txnArgs) + txnOpts := razorUtils.GetTxnOpts(rpcParameters, txnArgs) log.Debug("HandleWithdrawLock: Calling UnlockWithdraw() with arguments stakerId = ", stakerId) - return cmdUtils.UnlockWithdraw(client, txnOpts, stakerId) + return cmdUtils.UnlockWithdraw(rpcParameters, txnOpts, stakerId) } return core.NilHash, errors.New("withdrawLock period not over yet! Please try after some time") } //This function withdraws your razor once withdraw lock has passed -func (*UtilsStruct) UnlockWithdraw(client *ethclient.Client, txnOpts *bind.TransactOpts, stakerId uint32) (common.Hash, error) { +func (*UtilsStruct) UnlockWithdraw(rpcParameters rpc.RPCParameters, txnOpts *bind.TransactOpts, stakerId uint32) (common.Hash, error) { log.Info("Unlocking funds...") + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return core.NilHash, err + } log.Debug("Executing UnlockWithdraw transaction with stakerId = ", stakerId) txn, err := stakeManagerUtils.UnlockWithdraw(client, txnOpts, stakerId) diff --git a/cmd/unlockWithdraw_test.go b/cmd/unlockWithdraw_test.go index c5e44d38d..e2b078d64 100644 --- a/cmd/unlockWithdraw_test.go +++ b/cmd/unlockWithdraw_test.go @@ -1,7 +1,6 @@ package cmd import ( - "context" "errors" "math/big" "razor/accounts" @@ -87,14 +86,16 @@ func TestExecuteUnlockWithdraw(t *testing.T) { expectedFatal: true, }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() + setupTestEndpointsEnvironment() + utilsMock.On("IsFlagPassed", mock.Anything).Return(true) fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) flagSetMock.On("GetStringAddress", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.address, tt.args.addressErr) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) @@ -102,9 +103,9 @@ func TestExecuteUnlockWithdraw(t *testing.T) { utilsMock.On("CheckPassword", mock.Anything).Return(nil) utilsMock.On("AccountManagerForKeystore").Return(&accounts.AccountManager{}, nil) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) - utilsMock.On("AssignStakerId", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) - cmdUtilsMock.On("HandleWithdrawLock", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.txn, tt.args.err) - utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(nil) + utilsMock.On("AssignStakerId", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) + cmdUtilsMock.On("HandleWithdrawLock", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.txn, tt.args.err) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) utils := &UtilsStruct{} utils.ExecuteUnlockWithdraw(flagSet) if fatal != tt.expectedFatal { @@ -116,7 +117,6 @@ func TestExecuteUnlockWithdraw(t *testing.T) { func TestHandleWithdrawLock(t *testing.T) { var ( - client *ethclient.Client account types.Account configurations types.Configurations stakerId uint32 @@ -196,13 +196,13 @@ func TestHandleWithdrawLock(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetLock", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.withdrawLock, tt.args.withdrawLockErr) - utilsMock.On("GetEpoch", mock.Anything, mock.Anything).Return(tt.args.epoch, tt.args.epochErr) + utilsMock.On("GetLock", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.withdrawLock, tt.args.withdrawLockErr) + utilsMock.On("GetEpoch", mock.Anything).Return(tt.args.epoch, tt.args.epochErr) utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(TxnOpts) cmdUtilsMock.On("UnlockWithdraw", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.unlockWithdraw, tt.args.unlockWithdrawErr) utilsMock.On("SecondsToReadableTime", mock.AnythingOfType("int")).Return(tt.args.time) ut := &UtilsStruct{} - got, err := ut.HandleWithdrawLock(context.Background(), client, account, configurations, stakerId) + got, err := ut.HandleWithdrawLock(rpcParameters, account, configurations, stakerId) if (err != nil) != tt.wantErr { t.Errorf("HandleWithdrawLock() error = %v, wantErr %v", err, tt.wantErr) return @@ -216,7 +216,6 @@ func TestHandleWithdrawLock(t *testing.T) { func TestUnlockWithdraw(t *testing.T) { var ( - client *ethclient.Client txnOpts *bind.TransactOpts stakerId uint32 ) @@ -257,7 +256,7 @@ func TestUnlockWithdraw(t *testing.T) { stakeManagerMock.On("UnlockWithdraw", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.AnythingOfType("uint32")).Return(tt.args.txn, tt.args.txnErr) transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) ut := &UtilsStruct{} - got, err := ut.UnlockWithdraw(client, txnOpts, stakerId) + got, err := ut.UnlockWithdraw(rpcParameters, txnOpts, stakerId) if (err != nil) != tt.wantErr { t.Errorf("UnlockWithdraw() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/cmd/unstake.go b/cmd/unstake.go index 8d0ec8f50..11b4829ba 100644 --- a/cmd/unstake.go +++ b/cmd/unstake.go @@ -2,19 +2,16 @@ package cmd import ( - "context" "errors" "math/big" - "razor/accounts" "razor/core" "razor/core/types" - "razor/logger" "razor/pkg/bindings" + "razor/rpc" "razor/utils" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/pflag" "github.com/spf13/cobra" @@ -38,36 +35,14 @@ func initialiseUnstake(cmd *cobra.Command, args []string) { //This function sets the flag appropriately and executes the Unstake function func (*UtilsStruct) ExecuteUnstake(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - log.Debugf("ExecuteUnstake: Config: %+v", config) - - client := razorUtils.ConnectToClient(config.Provider) - - address, err := flagSetUtils.GetStringAddress(flagSet) - utils.CheckError("Error in getting address: ", err) - - logger.SetLoggerParameters(client, address) - - log.Debug("Checking to assign log file...") - fileUtils.AssignLogFile(flagSet, config) - - log.Debug("Getting password...") - password := razorUtils.AssignPassword(flagSet) - - accountManager, err := razorUtils.AccountManagerForKeystore() - utils.CheckError("Error in getting accounts manager for keystore: ", err) - - account := accounts.InitAccountStruct(address, password, accountManager) - - err = razorUtils.CheckPassword(account) - utils.CheckError("Error in fetching private key from given password: ", err) + config, rpcParameters, account, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) log.Debug("Getting amount in wei...") valueInWei, err := cmdUtils.AssignAmountInWei(flagSet) utils.CheckError("Error in getting amountInWei: ", err) - stakerId, err := razorUtils.AssignStakerId(context.Background(), flagSet, client, address) + stakerId, err := razorUtils.AssignStakerId(rpcParameters, flagSet, account.Address) utils.CheckError("StakerId error: ", err) unstakeInput := types.UnstakeInput{ @@ -76,25 +51,24 @@ func (*UtilsStruct) ExecuteUnstake(flagSet *pflag.FlagSet) { Account: account, } - txnHash, err := cmdUtils.Unstake(context.Background(), config, client, unstakeInput) + txnHash, err := cmdUtils.Unstake(rpcParameters, config, unstakeInput) utils.CheckError("Unstake Error: ", err) if txnHash != core.NilHash { - err = razorUtils.WaitForBlockCompletion(client, txnHash.Hex()) + err = razorUtils.WaitForBlockCompletion(rpcParameters, txnHash.Hex()) utils.CheckError("Error in WaitForBlockCompletion for unstake: ", err) } } //This function allows user to unstake their sRZRs in the razor network -func (*UtilsStruct) Unstake(ctx context.Context, config types.Configurations, client *ethclient.Client, input types.UnstakeInput) (common.Hash, error) { +func (*UtilsStruct) Unstake(rpcParameters rpc.RPCParameters, config types.Configurations, input types.UnstakeInput) (common.Hash, error) { txnArgs := types.TransactionOptions{ - Client: client, Amount: input.ValueInWei, ChainId: core.ChainId, Config: config, Account: input.Account, } stakerId := input.StakerId - staker, err := razorUtils.GetStaker(ctx, client, stakerId) + staker, err := razorUtils.GetStaker(rpcParameters, stakerId) if err != nil { log.Error("Error in getting staker: ", err) return core.NilHash, err @@ -102,13 +76,13 @@ func (*UtilsStruct) Unstake(ctx context.Context, config types.Configurations, cl log.Debugf("Unstake: Staker info: %+v", staker) log.Debug("Unstake: Calling ApproveUnstake()...") - approveHash, err := cmdUtils.ApproveUnstake(client, staker.TokenAddress, txnArgs) + approveHash, err := cmdUtils.ApproveUnstake(rpcParameters, staker.TokenAddress, txnArgs) if err != nil { return core.NilHash, err } if approveHash != core.NilHash { - err = razorUtils.WaitForBlockCompletion(client, approveHash.Hex()) + err = razorUtils.WaitForBlockCompletion(rpcParameters, approveHash.Hex()) if err != nil { return core.NilHash, err } @@ -120,7 +94,7 @@ func (*UtilsStruct) Unstake(ctx context.Context, config types.Configurations, cl txnArgs.MethodName = "unstake" txnArgs.ABI = bindings.StakeManagerMetaData.ABI - unstakeLock, err := razorUtils.GetLock(ctx, txnArgs.Client, txnArgs.Account.Address, stakerId, 0) + unstakeLock, err := razorUtils.GetLock(rpcParameters, txnArgs.Account.Address, stakerId, 0) if err != nil { log.Error("Error in getting unstakeLock: ", err) return core.NilHash, err @@ -134,10 +108,15 @@ func (*UtilsStruct) Unstake(ctx context.Context, config types.Configurations, cl } txnArgs.Parameters = []interface{}{stakerId, txnArgs.Amount} - txnOpts := razorUtils.GetTxnOpts(ctx, txnArgs) + txnOpts := razorUtils.GetTxnOpts(rpcParameters, txnArgs) log.Info("Unstaking coins") + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return core.NilHash, err + } + log.Debugf("Executing Unstake transaction with stakerId = %d, amount = %s", stakerId, txnArgs.Amount) - txn, err := stakeManagerUtils.Unstake(txnArgs.Client, txnOpts, stakerId, txnArgs.Amount) + txn, err := stakeManagerUtils.Unstake(client, txnOpts, stakerId, txnArgs.Amount) if err != nil { log.Error("Error in un-staking: ", err) return core.NilHash, err @@ -148,8 +127,13 @@ func (*UtilsStruct) Unstake(ctx context.Context, config types.Configurations, cl } //This function approves the unstake -func (*UtilsStruct) ApproveUnstake(client *ethclient.Client, stakerTokenAddress common.Address, txnArgs types.TransactionOptions) (common.Hash, error) { - txnOpts := razorUtils.GetTxnOpts(context.Background(), txnArgs) +func (*UtilsStruct) ApproveUnstake(rpcParameters rpc.RPCParameters, stakerTokenAddress common.Address, txnArgs types.TransactionOptions) (common.Hash, error) { + txnOpts := razorUtils.GetTxnOpts(rpcParameters, txnArgs) + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return core.NilHash, err + } + log.Infof("Approving %d amount for unstake...", txnArgs.Amount) txn, err := stakeManagerUtils.ApproveUnstake(client, txnOpts, stakerTokenAddress, txnArgs.Amount) if err != nil { diff --git a/cmd/unstake_test.go b/cmd/unstake_test.go index 3eb4a4672..7e6cece34 100644 --- a/cmd/unstake_test.go +++ b/cmd/unstake_test.go @@ -1,7 +1,6 @@ package cmd import ( - "context" "crypto/ecdsa" "crypto/rand" "errors" @@ -24,7 +23,6 @@ import ( func TestUnstake(t *testing.T) { var config types.Configurations - var client *ethclient.Client var account types.Account var stakerId uint32 @@ -123,17 +121,17 @@ func TestUnstake(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetStaker", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.staker, tt.args.stakerErr) - cmdUtilsMock.On("ApproveUnstake", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.approveHash, tt.args.approveHashErr) - utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) - utilsMock.On("GetLock", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.lock, tt.args.lockErr) - cmdUtilsMock.On("WaitForAppropriateState", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.state, tt.args.stateErr) + utilsMock.On("GetStaker", mock.Anything, mock.Anything).Return(tt.args.staker, tt.args.stakerErr) + cmdUtilsMock.On("ApproveUnstake", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.approveHash, tt.args.approveHashErr) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) + utilsMock.On("GetLock", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.lock, tt.args.lockErr) + cmdUtilsMock.On("WaitForAppropriateState", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.state, tt.args.stateErr) utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(TxnOpts) stakeManagerMock.On("Unstake", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.unstakeTxn, tt.args.unstakeErr) transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) utils := &UtilsStruct{} - _, gotErr := utils.Unstake(context.Background(), config, client, + _, gotErr := utils.Unstake(rpcParameters, config, types.UnstakeInput{ Account: account, StakerId: stakerId, @@ -284,13 +282,16 @@ func TestExecuteUnstake(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() + setupTestEndpointsEnvironment() + + utilsMock.On("IsFlagPassed", mock.Anything).Return(true) fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) @@ -300,9 +301,9 @@ func TestExecuteUnstake(t *testing.T) { utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) cmdUtilsMock.On("AssignAmountInWei", flagSet).Return(tt.args.value, tt.args.valueErr) utilsMock.On("AssignStakerId", mock.Anything, flagSet, mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) - utilsMock.On("GetLock", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string"), mock.AnythingOfType("uint32")).Return(tt.args.lock, tt.args.lockErr) - cmdUtilsMock.On("Unstake", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.unstakeHash, tt.args.unstakeErr) - utilsMock.On("WaitForBlockCompletion", client, mock.AnythingOfType("string")).Return(nil) + utilsMock.On("GetLock", mock.Anything, mock.AnythingOfType("string"), mock.AnythingOfType("uint32")).Return(tt.args.lock, tt.args.lockErr) + cmdUtilsMock.On("Unstake", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.unstakeHash, tt.args.unstakeErr) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) utils := &UtilsStruct{} fatal = false @@ -319,7 +320,6 @@ func TestExecuteUnstake(t *testing.T) { func TestApproveUnstake(t *testing.T) { var ( - client *ethclient.Client stakerTokenAddress common.Address txnArgs types.TransactionOptions ) @@ -362,7 +362,7 @@ func TestApproveUnstake(t *testing.T) { stakeManagerMock.On("ApproveUnstake", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything).Return(tt.args.txn, tt.args.txnErr) transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) ut := &UtilsStruct{} - got, err := ut.ApproveUnstake(client, stakerTokenAddress, txnArgs) + got, err := ut.ApproveUnstake(rpcParameters, stakerTokenAddress, txnArgs) if (err != nil) != tt.wantErr { t.Errorf("ApproveUnstake() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/cmd/updateCollection.go b/cmd/updateCollection.go index 0d4efc637..807f1cc15 100644 --- a/cmd/updateCollection.go +++ b/cmd/updateCollection.go @@ -2,16 +2,13 @@ package cmd import ( - "context" - "razor/accounts" "razor/core" "razor/core/types" - "razor/logger" "razor/pkg/bindings" + "razor/rpc" "razor/utils" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/cobra" "github.com/spf13/pflag" ) @@ -37,30 +34,8 @@ func initialiseUpdateCollection(cmd *cobra.Command, args []string) { //This function sets the flag appropriately and executes the UpdateCollection function func (*UtilsStruct) ExecuteUpdateCollection(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - log.Debugf("ExecuteUpdateCollection: Config : %+v", config) - - client := razorUtils.ConnectToClient(config.Provider) - - address, err := flagSetUtils.GetStringAddress(flagSet) - utils.CheckError("Error in getting address: ", err) - - logger.SetLoggerParameters(client, address) - - log.Debug("Checking to assign log file...") - fileUtils.AssignLogFile(flagSet, config) - - log.Debug("Getting password...") - password := razorUtils.AssignPassword(flagSet) - - accountManager, err := razorUtils.AccountManagerForKeystore() - utils.CheckError("Error in getting accounts manager for keystore: ", err) - - account := accounts.InitAccountStruct(address, password, accountManager) - - err = razorUtils.CheckPassword(account) - utils.CheckError("Error in fetching private key from given password: ", err) + config, rpcParameters, account, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) collectionId, err := flagSetUtils.GetUint16CollectionId(flagSet) utils.CheckError("Error in getting collectionID: ", err) @@ -84,23 +59,22 @@ func (*UtilsStruct) ExecuteUpdateCollection(flagSet *pflag.FlagSet) { Tolerance: tolerance, Account: account, } - txn, err := cmdUtils.UpdateCollection(context.Background(), client, config, collectionInput, collectionId) + txn, err := cmdUtils.UpdateCollection(rpcParameters, config, collectionInput, collectionId) utils.CheckError("Update Collection error: ", err) - err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) + err = razorUtils.WaitForBlockCompletion(rpcParameters, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for updateCollection: ", err) } //This function allows the admin to update an existing collection -func (*UtilsStruct) UpdateCollection(ctx context.Context, client *ethclient.Client, config types.Configurations, collectionInput types.CreateCollectionInput, collectionId uint16) (common.Hash, error) { +func (*UtilsStruct) UpdateCollection(rpcParameters rpc.RPCParameters, config types.Configurations, collectionInput types.CreateCollectionInput, collectionId uint16) (common.Hash, error) { jobIds := utils.ConvertUintArrayToUint16Array(collectionInput.JobIds) log.Debug("UpdateCollection: Uint16 jobIds: ", jobIds) - _, err := cmdUtils.WaitIfCommitState(ctx, client, "update collection") + _, err := cmdUtils.WaitIfCommitState(rpcParameters, "update collection") if err != nil { log.Error("Error in fetching state") return core.NilHash, err } - txnOpts := razorUtils.GetTxnOpts(ctx, types.TransactionOptions{ - Client: client, + txnOpts := razorUtils.GetTxnOpts(rpcParameters, types.TransactionOptions{ ChainId: core.ChainId, Config: config, ContractAddress: core.CollectionManagerAddress, @@ -110,6 +84,11 @@ func (*UtilsStruct) UpdateCollection(ctx context.Context, client *ethclient.Clie Account: collectionInput.Account, }) log.Info("Updating collection...") + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return core.NilHash, err + } + log.Debugf("Executing UpdateCollection transaction with collectionId = %d, tolerance = %d, aggregation method = %d, power = %d, jobIds = %v", collectionId, collectionInput.Tolerance, collectionInput.Aggregation, collectionInput.Power, jobIds) txn, err := assetManagerUtils.UpdateCollection(client, txnOpts, collectionId, collectionInput.Tolerance, collectionInput.Aggregation, collectionInput.Power, jobIds) if err != nil { diff --git a/cmd/updateCollection_test.go b/cmd/updateCollection_test.go index 5386f7246..c22a458ce 100644 --- a/cmd/updateCollection_test.go +++ b/cmd/updateCollection_test.go @@ -1,7 +1,6 @@ package cmd import ( - "context" "errors" "math/big" "razor/accounts" @@ -17,7 +16,6 @@ import ( ) func TestUpdateCollection(t *testing.T) { - var client *ethclient.Client var config types.Configurations var WaitIfCommitStateStatus uint32 var jobIdUint16 []uint16 @@ -77,12 +75,12 @@ func TestUpdateCollection(t *testing.T) { utilsMock.On("ConvertUintArrayToUint16Array", mock.Anything).Return(jobIdUint16) utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(TxnOpts) - cmdUtilsMock.On("WaitIfCommitState", mock.Anything, mock.Anything, mock.Anything).Return(WaitIfCommitStateStatus, tt.args.waitIfCommitStateErr) + cmdUtilsMock.On("WaitIfCommitState", mock.Anything, mock.Anything).Return(WaitIfCommitStateStatus, tt.args.waitIfCommitStateErr) assetManagerMock.On("UpdateCollection", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.updateCollectionTxn, tt.args.updateCollectionErr) transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) utils := &UtilsStruct{} - got, err := utils.UpdateCollection(context.Background(), client, config, collectionInput, collectionId) + got, err := utils.UpdateCollection(rpcParameters, config, collectionInput, collectionId) if got != tt.want { t.Errorf("Txn hash for updateCollection function, got = %v, want = %v", got, tt.want) @@ -267,14 +265,16 @@ func TestExecuteUpdateCollection(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() + setupTestEndpointsEnvironment() + utilsMock.On("IsFlagPassed", mock.Anything).Return(true) fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) @@ -286,8 +286,8 @@ func TestExecuteUpdateCollection(t *testing.T) { flagSetMock.On("GetUint32Aggregation", flagSet).Return(tt.args.aggregation, tt.args.aggregationErr) flagSetMock.On("GetInt8Power", flagSet).Return(tt.args.power, tt.args.powerErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) - cmdUtilsMock.On("UpdateCollection", mock.Anything, mock.Anything, config, mock.Anything, mock.Anything).Return(tt.args.updateCollectionTxn, tt.args.updateCollectionErr) - utilsMock.On("WaitForBlockCompletion", client, mock.AnythingOfType("string")).Return(nil) + cmdUtilsMock.On("UpdateCollection", mock.Anything, config, mock.Anything, mock.Anything).Return(tt.args.updateCollectionTxn, tt.args.updateCollectionErr) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) flagSetMock.On("GetUint32Tolerance", flagSet).Return(tt.args.tolerance, tt.args.toleranceErr) utils := &UtilsStruct{} diff --git a/cmd/updateCommission.go b/cmd/updateCommission.go index 5a79e17dd..63425ab4c 100644 --- a/cmd/updateCommission.go +++ b/cmd/updateCommission.go @@ -2,16 +2,13 @@ package cmd import ( - "context" "errors" - "razor/accounts" "razor/core" "razor/core/types" - "razor/logger" "razor/pkg/bindings" + "razor/rpc" "razor/utils" - "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/pflag" "github.com/spf13/cobra" @@ -34,35 +31,13 @@ func initialiseUpdateCommission(cmd *cobra.Command, args []string) { //This function sets the flag appropriately and executes the UpdateCommission function func (*UtilsStruct) ExecuteUpdateCommission(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - log.Debugf("ExecuteUpdateCommission: Config: %+v", config) - - client := razorUtils.ConnectToClient(config.Provider) - - address, err := flagSetUtils.GetStringAddress(flagSet) - utils.CheckError("Error in getting address: ", err) - - logger.SetLoggerParameters(client, address) - - log.Debug("Checking to assign log file...") - fileUtils.AssignLogFile(flagSet, config) - - log.Debug("Getting password...") - password := razorUtils.AssignPassword(flagSet) - - accountManager, err := razorUtils.AccountManagerForKeystore() - utils.CheckError("Error in getting accounts manager for keystore: ", err) - - account := accounts.InitAccountStruct(address, password, accountManager) - - err = razorUtils.CheckPassword(account) - utils.CheckError("Error in fetching private key from given password: ", err) + config, rpcParameters, account, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) commission, err := flagSetUtils.GetUint8Commission(flagSet) utils.CheckError("Error in getting commission", err) - stakerId, err := razorUtils.GetStakerId(context.Background(), client, address) + stakerId, err := razorUtils.GetStakerId(rpcParameters, account.Address) utils.CheckError("Error in getting stakerId", err) updateCommissionInput := types.UpdateCommissionInput{ @@ -71,20 +46,20 @@ func (*UtilsStruct) ExecuteUpdateCommission(flagSet *pflag.FlagSet) { Account: account, } - err = cmdUtils.UpdateCommission(context.Background(), config, client, updateCommissionInput) + err = cmdUtils.UpdateCommission(rpcParameters, config, updateCommissionInput) utils.CheckError("UpdateCommission error: ", err) } //This function allows a staker to add/update the commission value -func (*UtilsStruct) UpdateCommission(ctx context.Context, config types.Configurations, client *ethclient.Client, updateCommissionInput types.UpdateCommissionInput) error { - stakerInfo, err := razorUtils.GetStaker(ctx, client, updateCommissionInput.StakerId) +func (*UtilsStruct) UpdateCommission(rpcParameters rpc.RPCParameters, config types.Configurations, updateCommissionInput types.UpdateCommissionInput) error { + stakerInfo, err := razorUtils.GetStaker(rpcParameters, updateCommissionInput.StakerId) if err != nil { log.Error("Error in fetching staker info") return err } log.Debugf("UpdateCommission: Staker Info: %+v", stakerInfo) - maxCommission, err := razorUtils.GetMaxCommission(ctx, client) + maxCommission, err := razorUtils.GetMaxCommission(rpcParameters) if err != nil { return err } @@ -94,13 +69,13 @@ func (*UtilsStruct) UpdateCommission(ctx context.Context, config types.Configura return errors.New("commission out of range") } - epochLimitForUpdateCommission, err := razorUtils.GetEpochLimitForUpdateCommission(ctx, client) + epochLimitForUpdateCommission, err := razorUtils.GetEpochLimitForUpdateCommission(rpcParameters) if err != nil { return err } log.Debug("UpdateCommission: Epoch limit to update commission: ", epochLimitForUpdateCommission) - epoch, err := razorUtils.GetEpoch(ctx, client) + epoch, err := razorUtils.GetEpoch(rpcParameters) if err != nil { return err } @@ -118,7 +93,6 @@ func (*UtilsStruct) UpdateCommission(ctx context.Context, config types.Configura return errors.New("invalid epoch for update") } txnOpts := types.TransactionOptions{ - Client: client, ChainId: core.ChainId, Config: config, ContractAddress: core.StakeManagerAddress, @@ -127,8 +101,13 @@ func (*UtilsStruct) UpdateCommission(ctx context.Context, config types.Configura Parameters: []interface{}{updateCommissionInput.Commission}, Account: updateCommissionInput.Account, } - updateCommissionTxnOpts := razorUtils.GetTxnOpts(ctx, txnOpts) + updateCommissionTxnOpts := razorUtils.GetTxnOpts(rpcParameters, txnOpts) log.Infof("Setting the commission value of Staker %d to %d%%", updateCommissionInput.StakerId, updateCommissionInput.Commission) + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return err + } + log.Debug("Executing UpdateCommission transaction with commission = ", updateCommissionInput.Commission) txn, err := stakeManagerUtils.UpdateCommission(client, updateCommissionTxnOpts, updateCommissionInput.Commission) if err != nil { @@ -137,7 +116,7 @@ func (*UtilsStruct) UpdateCommission(ctx context.Context, config types.Configura } txnHash := transactionUtils.Hash(txn) log.Infof("Txn Hash: %s", txnHash.Hex()) - err = razorUtils.WaitForBlockCompletion(client, txnHash.Hex()) + err = razorUtils.WaitForBlockCompletion(rpcParameters, txnHash.Hex()) if err != nil { log.Error("Error in WaitForBlockCompletion for updateCommission: ", err) return err diff --git a/cmd/updateCommission_test.go b/cmd/updateCommission_test.go index df7169f41..84d93e0af 100644 --- a/cmd/updateCommission_test.go +++ b/cmd/updateCommission_test.go @@ -1,7 +1,6 @@ package cmd import ( - "context" "errors" "razor/accounts" "razor/core/types" @@ -16,7 +15,6 @@ import ( ) func TestUpdateCommission(t *testing.T) { - var client *ethclient.Client var config = types.Configurations{ Provider: "127.0.0.1", GasMultiplier: 1, @@ -191,18 +189,18 @@ func TestUpdateCommission(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetStaker", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.stakerInfo, tt.args.stakerInfoErr) + utilsMock.On("GetStaker", mock.Anything, mock.Anything).Return(tt.args.stakerInfo, tt.args.stakerInfoErr) utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(TxnOpts) - utilsMock.On("GetEpoch", mock.Anything, mock.Anything).Return(tt.args.epoch, tt.args.epochErr) + utilsMock.On("GetEpoch", mock.Anything).Return(tt.args.epoch, tt.args.epochErr) transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) - utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) utilsMock.On("GetMaxCommission", mock.Anything, mock.Anything).Return(tt.args.maxCommission, tt.args.maxCommissionErr) - utilsMock.On("GetEpochLimitForUpdateCommission", mock.Anything, mock.Anything).Return(tt.args.epochLimitForUpdateCommission, tt.args.epochLimitForUpdateCommissionErr) + utilsMock.On("GetEpochLimitForUpdateCommission", mock.Anything).Return(tt.args.epochLimitForUpdateCommission, tt.args.epochLimitForUpdateCommissionErr) utilsMock.On("SecondsToReadableTime", mock.AnythingOfType("int")).Return(tt.args.time) stakeManagerMock.On("UpdateCommission", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.UpdateCommissionTxn, tt.args.UpdateCommissionErr) utils := &UtilsStruct{} - gotErr := utils.UpdateCommission(context.Background(), config, client, types.UpdateCommissionInput{ + gotErr := utils.UpdateCommission(rpcParameters, config, types.UpdateCommissionInput{ Commission: tt.args.commission, }) if gotErr == nil || tt.wantErr == nil { @@ -324,14 +322,16 @@ func TestExecuteUpdateCommission(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() + setupTestEndpointsEnvironment() + utilsMock.On("IsFlagPassed", mock.Anything).Return(true) fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) flagSetMock.On("GetStringAddress", flagSet).Return(tt.args.address, tt.args.addressErr) @@ -339,9 +339,9 @@ func TestExecuteUpdateCommission(t *testing.T) { utilsMock.On("CheckPassword", mock.Anything).Return(nil) utilsMock.On("AccountManagerForKeystore").Return(&accounts.AccountManager{}, nil) flagSetMock.On("GetUint8Commission", flagSet).Return(tt.args.commission, tt.args.commissionErr) - utilsMock.On("GetStakerId", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) + utilsMock.On("GetStakerId", mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) - cmdUtilsMock.On("UpdateCommission", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.UpdateCommissionErr) + cmdUtilsMock.On("UpdateCommission", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.UpdateCommissionErr) utils := &UtilsStruct{} fatal = false diff --git a/cmd/updateJob.go b/cmd/updateJob.go index b0828f2d0..2954ffaa7 100644 --- a/cmd/updateJob.go +++ b/cmd/updateJob.go @@ -2,16 +2,13 @@ package cmd import ( - "context" - "razor/accounts" "razor/core" "razor/core/types" - "razor/logger" "razor/pkg/bindings" + "razor/rpc" "razor/utils" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/cobra" "github.com/spf13/pflag" ) @@ -37,30 +34,8 @@ func initialiseUpdateJob(cmd *cobra.Command, args []string) { //This function sets the flag appropriately and executes the UpdateJob function func (*UtilsStruct) ExecuteUpdateJob(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - log.Debugf("ExecuteUpdateJob: Config: %+v", config) - - client := razorUtils.ConnectToClient(config.Provider) - - address, err := flagSetUtils.GetStringAddress(flagSet) - utils.CheckError("Error in getting address: ", err) - - logger.SetLoggerParameters(client, address) - - log.Debug("Checking to assign log file...") - fileUtils.AssignLogFile(flagSet, config) - - log.Debug("Getting password...") - password := razorUtils.AssignPassword(flagSet) - - accountManager, err := razorUtils.AccountManagerForKeystore() - utils.CheckError("Error in getting accounts manager for keystore: ", err) - - account := accounts.InitAccountStruct(address, password, accountManager) - - err = razorUtils.CheckPassword(account) - utils.CheckError("Error in fetching private key from given password: ", err) + config, rpcParameters, account, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) jobId, err := flagSetUtils.GetUint16JobId(flagSet) utils.CheckError("Error in getting jobId: ", err) @@ -89,21 +64,20 @@ func (*UtilsStruct) ExecuteUpdateJob(flagSet *pflag.FlagSet) { Account: account, } - txn, err := cmdUtils.UpdateJob(context.Background(), client, config, jobInput, jobId) + txn, err := cmdUtils.UpdateJob(rpcParameters, config, jobInput, jobId) utils.CheckError("UpdateJob error: ", err) - err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) + err = razorUtils.WaitForBlockCompletion(rpcParameters, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for updateJob: ", err) } //This function allows the admin to update an existing job -func (*UtilsStruct) UpdateJob(ctx context.Context, client *ethclient.Client, config types.Configurations, jobInput types.CreateJobInput, jobId uint16) (common.Hash, error) { - _, err := cmdUtils.WaitIfCommitState(ctx, client, "update job") +func (*UtilsStruct) UpdateJob(rpcParameters rpc.RPCParameters, config types.Configurations, jobInput types.CreateJobInput, jobId uint16) (common.Hash, error) { + _, err := cmdUtils.WaitIfCommitState(rpcParameters, "update job") if err != nil { log.Error("Error in fetching state") return core.NilHash, err } - txnArgs := razorUtils.GetTxnOpts(ctx, types.TransactionOptions{ - Client: client, + txnArgs := razorUtils.GetTxnOpts(rpcParameters, types.TransactionOptions{ ChainId: core.ChainId, Config: config, ContractAddress: core.CollectionManagerAddress, @@ -113,6 +87,11 @@ func (*UtilsStruct) UpdateJob(ctx context.Context, client *ethclient.Client, con Account: jobInput.Account, }) log.Info("Updating Job...") + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return core.NilHash, err + } + log.Debugf("Executing UpdateJob transaction with arguments jobId = %d, weight = %d, power = %d, selector type = %d, selector = %s, URL = %s", jobId, jobInput.Weight, jobInput.Power, jobInput.SelectorType, jobInput.Selector, jobInput.Url) txn, err := assetManagerUtils.UpdateJob(client, txnArgs, jobId, jobInput.Weight, jobInput.Power, jobInput.SelectorType, jobInput.Selector, jobInput.Url) if err != nil { diff --git a/cmd/updateJob_test.go b/cmd/updateJob_test.go index 43c3d3b34..25933b0bc 100644 --- a/cmd/updateJob_test.go +++ b/cmd/updateJob_test.go @@ -1,7 +1,6 @@ package cmd import ( - "context" "errors" "math/big" "razor/accounts" @@ -17,8 +16,6 @@ import ( ) func TestUpdateJob(t *testing.T) { - - var client *ethclient.Client var config types.Configurations var WaitIfCommitStateStatus uint32 var jobInput types.CreateJobInput @@ -77,7 +74,7 @@ func TestUpdateJob(t *testing.T) { utils := &UtilsStruct{} - got, err := utils.UpdateJob(context.Background(), client, config, jobInput, jobId) + got, err := utils.UpdateJob(rpcParameters, config, jobInput, jobId) if got != tt.want { t.Errorf("Txn hash for updateJob function, got = %v, want = %v", got, tt.want) } @@ -314,14 +311,16 @@ func TestExecuteUpdateJob(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() + setupTestEndpointsEnvironment() + utilsMock.On("IsFlagPassed", mock.Anything).Return(true) fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) @@ -335,8 +334,8 @@ func TestExecuteUpdateJob(t *testing.T) { flagSetMock.On("GetUint8Weight", flagSet).Return(tt.args.weight, tt.args.weightErr) flagSetMock.On("GetUint8SelectorType", flagSet).Return(tt.args.selectorType, tt.args.selectorTypeErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) - cmdUtilsMock.On("UpdateJob", mock.Anything, mock.Anything, config, mock.Anything, mock.Anything).Return(tt.args.updateJobTxn, tt.args.updateJobErr) - utilsMock.On("WaitForBlockCompletion", client, mock.AnythingOfType("string")).Return(nil) + cmdUtilsMock.On("UpdateJob", mock.Anything, config, mock.Anything, mock.Anything).Return(tt.args.updateJobTxn, tt.args.updateJobErr) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) utils := &UtilsStruct{} fatal = false diff --git a/cmd/vote.go b/cmd/vote.go index 2f7b41107..f5fff9add 100644 --- a/cmd/vote.go +++ b/cmd/vote.go @@ -10,12 +10,11 @@ import ( "os" "os/signal" "path/filepath" - "razor/accounts" "razor/cache" "razor/core" "razor/core/types" - "razor/logger" "razor/pkg/bindings" + "razor/rpc" "razor/utils" "time" @@ -26,7 +25,6 @@ import ( "github.com/spf13/pflag" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethclient" solsha3 "github.com/miguelmota/go-solidity-sha3" "github.com/spf13/cobra" ) @@ -48,35 +46,12 @@ func initializeVote(cmd *cobra.Command, args []string) { //This function sets the flag appropriately and executes the Vote function func (*UtilsStruct) ExecuteVote(flagSet *pflag.FlagSet) { - config, err := cmdUtils.GetConfigData() - utils.CheckError("Error in getting config: ", err) - log.Debugf("ExecuteVote: Config: %+v", config) + config, rpcParameters, account, err := InitializeCommandDependencies(flagSet) + utils.CheckError("Error in initialising command dependencies: ", err) - client := razorUtils.ConnectToClient(config.Provider) - - err = ValidateBufferPercentLimit(context.Background(), client, config.BufferPercent) + err = ValidateBufferPercentLimit(rpcParameters, config.BufferPercent) utils.CheckError("Error in validating buffer percent: ", err) - address, err := flagSetUtils.GetStringAddress(flagSet) - utils.CheckError("Error in getting address: ", err) - log.Debug("ExecuteVote: Address: ", address) - - logger.SetLoggerParameters(client, address) - - log.Debug("Checking to assign log file...") - fileUtils.AssignLogFile(flagSet, config) - - log.Debug("Getting password...") - password := razorUtils.AssignPassword(flagSet) - - accountManager, err := razorUtils.AccountManagerForKeystore() - utils.CheckError("Error in getting accounts manager for keystore: ", err) - - account := accounts.InitAccountStruct(address, password, accountManager) - - err = razorUtils.CheckPassword(account) - utils.CheckError("Error in fetching private key from given password: ", err) - isRogue, err := flagSetUtils.GetBoolRogue(flagSet) utils.CheckError("Error in getting rogue status: ", err) log.Debug("ExecuteVote: IsRogue: ", isRogue) @@ -106,7 +81,7 @@ func (*UtilsStruct) ExecuteVote(flagSet *pflag.FlagSet) { }, } - stakerId, err := razorUtils.GetStakerId(context.Background(), client, address) + stakerId, err := razorUtils.GetStakerId(rpcParameters, account.Address) utils.CheckError("Error in getting staker id: ", err) if stakerId == 0 { @@ -115,7 +90,7 @@ func (*UtilsStruct) ExecuteVote(flagSet *pflag.FlagSet) { cmdUtils.HandleExit() - jobsCache, collectionsCache, initCacheBlockNumber, err := cmdUtils.InitJobAndCollectionCache(context.Background(), client) + jobsCache, collectionsCache, initCacheBlockNumber, err := cmdUtils.InitJobAndCollectionCache(rpcParameters) utils.CheckError("Error in initializing asset cache: ", err) commitParams := &types.CommitParams{ @@ -127,7 +102,7 @@ func (*UtilsStruct) ExecuteVote(flagSet *pflag.FlagSet) { } log.Debugf("Calling Vote() with arguments rogueData = %+v, account address = %s, backup node actions to ignore = %s", rogueData, account.Address, backupNodeActionsToIgnore) - if err := cmdUtils.Vote(context.Background(), config, client, account, stakerId, commitParams, rogueData, backupNodeActionsToIgnore); err != nil { + if err := cmdUtils.Vote(rpcParameters, config, account, stakerId, commitParams, rogueData, backupNodeActionsToIgnore); err != nil { log.Errorf("%v\n", err) osUtils.Exit(1) } @@ -158,16 +133,16 @@ func (*UtilsStruct) HandleExit() { } //This function handles all the states of voting -func (*UtilsStruct) Vote(ctx context.Context, config types.Configurations, client *ethclient.Client, account types.Account, stakerId uint32, commitParams *types.CommitParams, rogueData types.Rogue, backupNodeActionsToIgnore []string) error { - header, err := clientUtils.GetLatestBlockWithRetry(context.Background(), client) +func (*UtilsStruct) Vote(rpcParameters rpc.RPCParameters, config types.Configurations, account types.Account, stakerId uint32, commitParams *types.CommitParams, rogueData types.Rogue, backupNodeActionsToIgnore []string) error { + header, err := clientUtils.GetLatestBlockWithRetry(rpcParameters) utils.CheckError("Error in getting block: ", err) for { select { - case <-ctx.Done(): + case <-rpcParameters.Ctx.Done(): return nil default: log.Debugf("Vote: Header value: %d", header.Number) - latestHeader, err := clientUtils.GetLatestBlockWithRetry(context.Background(), client) + latestHeader, err := clientUtils.GetLatestBlockWithRetry(rpcParameters) if err != nil { log.Error("Error in fetching block: ", err) continue @@ -175,7 +150,7 @@ func (*UtilsStruct) Vote(ctx context.Context, config types.Configurations, clien log.Debugf("Vote: Latest header value: %d", latestHeader.Number) if latestHeader.Number.Cmp(header.Number) != 0 { header = latestHeader - cmdUtils.HandleBlock(client, account, stakerId, latestHeader, config, commitParams, rogueData, backupNodeActionsToIgnore) + cmdUtils.HandleBlock(rpcParameters, account, stakerId, latestHeader, config, commitParams, rogueData, backupNodeActionsToIgnore) } time.Sleep(time.Second * time.Duration(core.BlockNumberInterval)) } @@ -187,11 +162,12 @@ var ( lastVerification uint32 blockConfirmed uint32 disputeData types.DisputeFileData + lastRPCRefreshEpoch uint32 ) //This function handles the block -func (*UtilsStruct) HandleBlock(client *ethclient.Client, account types.Account, stakerId uint32, latestHeader *Types.Header, config types.Configurations, commitParams *types.CommitParams, rogueData types.Rogue, backupNodeActionsToIgnore []string) { - stateBuffer, err := razorUtils.GetStateBuffer(context.Background(), client) +func (*UtilsStruct) HandleBlock(rpcParameters rpc.RPCParameters, account types.Account, stakerId uint32, latestHeader *Types.Header, config types.Configurations, commitParams *types.CommitParams, rogueData types.Rogue, backupNodeActionsToIgnore []string) { + stateBuffer, err := razorUtils.GetStateBuffer(rpcParameters) if err != nil { log.Error("Error in getting state buffer: ", err) return @@ -207,25 +183,29 @@ func (*UtilsStruct) HandleBlock(client *ethclient.Client, account types.Account, ctx, cancel := context.WithTimeout(context.Background(), time.Duration(remainingTimeOfTheCurrentState)*time.Second) defer cancel() + + // Replacing context with the context which timeouts after remainingTimeOfTheCurrentState seconds + rpcParameters.Ctx = ctx + state, err := razorUtils.GetBufferedState(latestHeader, stateBuffer, config.BufferPercent) if err != nil { log.Error("Error in getting state: ", err) return } - epoch, err := razorUtils.GetEpoch(ctx, client) + epoch, err := razorUtils.GetEpoch(rpcParameters) if err != nil { log.Error("Error in getting epoch: ", err) return } - staker, err := razorUtils.GetStaker(ctx, client, stakerId) + staker, err := razorUtils.GetStaker(rpcParameters, stakerId) if err != nil { log.Error(err) return } stakedAmount := staker.Stake - ethBalance, err := clientUtils.BalanceAtWithRetry(ctx, client, common.HexToAddress(account.Address)) + ethBalance, err := clientUtils.BalanceAtWithRetry(rpcParameters, common.HexToAddress(account.Address)) if err != nil { log.Errorf("Error in fetching balance of the account: %s\n%v", account.Address, err) return @@ -247,7 +227,7 @@ func (*UtilsStruct) HandleBlock(client *ethclient.Client, account types.Account, return } - sRZRBalance, err := razorUtils.GetStakerSRZRBalance(ctx, client, staker) + sRZRBalance, err := razorUtils.GetStakerSRZRBalance(rpcParameters, staker) if err != nil { log.Error("Error in getting sRZR balance for staker: ", err) return @@ -274,21 +254,21 @@ func (*UtilsStruct) HandleBlock(client *ethclient.Client, account types.Account, switch state { case 0: log.Debugf("Starting commit...") - err := cmdUtils.InitiateCommit(ctx, client, config, account, epoch, stakerId, latestHeader, commitParams, stateBuffer, rogueData) + err := cmdUtils.InitiateCommit(rpcParameters, config, account, epoch, stakerId, latestHeader, commitParams, stateBuffer, rogueData) if err != nil { log.Error(err) break } case 1: log.Debugf("Starting reveal...") - err := cmdUtils.InitiateReveal(ctx, client, config, account, epoch, staker, latestHeader, stateBuffer, rogueData) + err := cmdUtils.InitiateReveal(rpcParameters, config, account, epoch, staker, latestHeader, stateBuffer, rogueData) if err != nil { log.Error(err) break } case 2: log.Debugf("Starting propose...") - err := cmdUtils.InitiatePropose(ctx, client, config, account, epoch, staker, latestHeader, stateBuffer, rogueData) + err := cmdUtils.InitiatePropose(rpcParameters, config, account, epoch, staker, latestHeader, stateBuffer, rogueData) if err != nil { log.Error(err) break @@ -301,7 +281,7 @@ func (*UtilsStruct) HandleBlock(client *ethclient.Client, account types.Account, break } - err := cmdUtils.HandleDispute(ctx, client, config, account, epoch, latestHeader.Number, rogueData, backupNodeActionsToIgnore) + err := cmdUtils.HandleDispute(rpcParameters, config, account, epoch, latestHeader.Number, rogueData, backupNodeActionsToIgnore) if err != nil { log.Error(err) break @@ -311,7 +291,7 @@ func (*UtilsStruct) HandleBlock(client *ethclient.Client, account types.Account, if razorUtils.IsFlagPassed("autoClaimBounty") { log.Debugf("Automatically claiming bounty") - err = cmdUtils.HandleClaimBounty(client, config, account) + err = cmdUtils.HandleClaimBounty(rpcParameters, config, account) if err != nil { log.Error(err) break @@ -327,7 +307,7 @@ func (*UtilsStruct) HandleBlock(client *ethclient.Client, account types.Account, break } - confirmedBlock, err := razorUtils.GetConfirmedBlocks(ctx, client, epoch) + confirmedBlock, err := razorUtils.GetConfirmedBlocks(rpcParameters, epoch) if err != nil { log.Error(err) break @@ -339,8 +319,7 @@ func (*UtilsStruct) HandleBlock(client *ethclient.Client, account types.Account, break } if (lastVerification == epoch || lastVerification == 0) && blockConfirmed < epoch { - txn, err := cmdUtils.ClaimBlockReward(ctx, types.TransactionOptions{ - Client: client, + txn, err := cmdUtils.ClaimBlockReward(rpcParameters, types.TransactionOptions{ ChainId: core.ChainId, Config: config, ContractAddress: core.BlockManagerAddress, @@ -356,6 +335,22 @@ func (*UtilsStruct) HandleBlock(client *ethclient.Client, account types.Account, if txn != core.NilHash { log.Info("Confirm Transaction Hash: ", txn) } + + if lastRPCRefreshEpoch < epoch { + err = rpcParameters.RPCManager.RefreshEndpoints() + if err != nil { + log.Error("Error in refreshing RPC endpoints: ", err) + break + } + bestEndpointURL, err := rpcParameters.RPCManager.GetBestEndpointURL() + if err != nil { + log.Error("Error in getting best RPC endpoint URL after refreshing: ", err) + break + } + log.Info("Current best RPC endpoint URL: ", bestEndpointURL) + + lastRPCRefreshEpoch = epoch + } } case -1: if config.WaitTime >= core.BufferStateSleepTime { @@ -368,8 +363,8 @@ func (*UtilsStruct) HandleBlock(client *ethclient.Client, account types.Account, } //This function initiates the commit -func (*UtilsStruct) InitiateCommit(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, stakerId uint32, latestHeader *Types.Header, commitParams *types.CommitParams, stateBuffer uint64, rogueData types.Rogue) error { - lastCommit, err := razorUtils.GetEpochLastCommitted(ctx, client, stakerId) +func (*UtilsStruct) InitiateCommit(rpcParameters rpc.RPCParameters, config types.Configurations, account types.Account, epoch uint32, stakerId uint32, latestHeader *Types.Header, commitParams *types.CommitParams, stateBuffer uint64, rogueData types.Rogue) error { + lastCommit, err := razorUtils.GetEpochLastCommitted(rpcParameters, stakerId) if err != nil { return errors.New("Error in fetching last commit: " + err.Error()) } @@ -381,20 +376,20 @@ func (*UtilsStruct) InitiateCommit(ctx context.Context, client *ethclient.Client return nil } - err = CheckForJobAndCollectionEvents(ctx, client, commitParams) + err = CheckForJobAndCollectionEvents(rpcParameters, commitParams) if err != nil { log.Error("Error in checking for asset events: ", err) return err } - staker, err := razorUtils.GetStaker(ctx, client, stakerId) + staker, err := razorUtils.GetStaker(rpcParameters, stakerId) if err != nil { log.Error(err) return err } log.Debug("InitiateCommit: Staker:", staker) stakedAmount := staker.Stake - minStakeAmount, err := razorUtils.GetMinStakeAmount(ctx, client) + minStakeAmount, err := razorUtils.GetMinStakeAmount(rpcParameters) if err != nil { log.Error("Error in getting minimum stake amount: ", err) return err @@ -412,13 +407,13 @@ func (*UtilsStruct) InitiateCommit(ctx context.Context, client *ethclient.Client keystorePath := filepath.Join(razorPath, "keystore_files") log.Debugf("InitiateCommit: Keystore file path: %s", keystorePath) log.Debugf("InitiateCommit: Calling CalculateSeed() with arguments keystorePath = %s, epoch = %d", keystorePath, epoch) - seed, err := CalculateSeed(ctx, client, account, keystorePath, epoch) + seed, err := CalculateSeed(rpcParameters, account, keystorePath, epoch) if err != nil { return errors.New("Error in getting seed: " + err.Error()) } log.Debugf("InitiateCommit: Calling HandleCommitState with arguments epoch = %d, seed = %v, rogueData = %+v", epoch, seed, rogueData) - commitData, err := cmdUtils.HandleCommitState(ctx, client, epoch, seed, commitParams, rogueData) + commitData, err := cmdUtils.HandleCommitState(rpcParameters, epoch, seed, commitParams, rogueData) if err != nil { return errors.New("Error in getting active assets: " + err.Error()) } @@ -430,7 +425,7 @@ func (*UtilsStruct) InitiateCommit(ctx context.Context, client *ethclient.Client return err } - commitTxn, err := cmdUtils.Commit(ctx, client, config, account, epoch, latestHeader, stateBuffer, commitmentToSend) + commitTxn, err := cmdUtils.Commit(rpcParameters, config, account, epoch, latestHeader, stateBuffer, commitmentToSend) if err != nil { return errors.New("Error in committing data: " + err.Error()) } @@ -457,10 +452,10 @@ func (*UtilsStruct) InitiateCommit(ctx context.Context, client *ethclient.Client } //This function initiates the reveal -func (*UtilsStruct) InitiateReveal(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, latestHeader *Types.Header, stateBuffer uint64, rogueData types.Rogue) error { +func (*UtilsStruct) InitiateReveal(rpcParameters rpc.RPCParameters, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, latestHeader *Types.Header, stateBuffer uint64, rogueData types.Rogue) error { stakedAmount := staker.Stake log.Debug("InitiateReveal: Staked Amount: ", stakedAmount) - minStakeAmount, err := razorUtils.GetMinStakeAmount(ctx, client) + minStakeAmount, err := razorUtils.GetMinStakeAmount(rpcParameters) if err != nil { log.Error("Error in getting minimum stake amount: ", err) return err @@ -470,7 +465,7 @@ func (*UtilsStruct) InitiateReveal(ctx context.Context, client *ethclient.Client log.Error("Stake is below minimum required. Kindly add stake to continue voting.") return nil } - lastReveal, err := razorUtils.GetEpochLastRevealed(ctx, client, staker.Id) + lastReveal, err := razorUtils.GetEpochLastRevealed(rpcParameters, staker.Id) if err != nil { return errors.New("Error in fetching last reveal: " + err.Error()) } @@ -482,7 +477,7 @@ func (*UtilsStruct) InitiateReveal(ctx context.Context, client *ethclient.Client } log.Debugf("InitiateReveal: Calling CheckForLastCommitted with arguments staker = %+v, epoch = %d", staker, epoch) - if err := cmdUtils.CheckForLastCommitted(ctx, client, staker, epoch); err != nil { + if err := cmdUtils.CheckForLastCommitted(rpcParameters, staker, epoch); err != nil { log.Error(err) return err } @@ -496,7 +491,7 @@ func (*UtilsStruct) InitiateReveal(ctx context.Context, client *ethclient.Client log.Debugf("InitiateReveal: Keystore file path: %s", keystorePath) // Consolidated commitment verification for commit data being fetched from memory or file - commitData, err := GetCommittedDataForEpoch(ctx, client, account, epoch, rogueData) + commitData, err := GetCommittedDataForEpoch(rpcParameters, account, epoch, rogueData) if err != nil { return err } @@ -517,7 +512,7 @@ func (*UtilsStruct) InitiateReveal(ctx context.Context, client *ethclient.Client SeqAllottedCollections: commitData.SeqAllottedCollections, } log.Debugf("InitiateReveal: Calling Reveal() with arguments epoch = %d, commitDataToSend = %+v, signature = %v", epoch, commitDataToSend, signature) - revealTxn, err := cmdUtils.Reveal(ctx, client, config, account, epoch, latestHeader, stateBuffer, commitDataToSend, signature) + revealTxn, err := cmdUtils.Reveal(rpcParameters, config, account, epoch, latestHeader, stateBuffer, commitDataToSend, signature) if err != nil { return errors.New("Reveal error: " + err.Error()) } @@ -526,10 +521,10 @@ func (*UtilsStruct) InitiateReveal(ctx context.Context, client *ethclient.Client } //This function initiates the propose -func (*UtilsStruct) InitiatePropose(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, latestHeader *Types.Header, stateBuffer uint64, rogueData types.Rogue) error { +func (*UtilsStruct) InitiatePropose(rpcParameters rpc.RPCParameters, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, latestHeader *Types.Header, stateBuffer uint64, rogueData types.Rogue) error { stakedAmount := staker.Stake log.Debug("InitiatePropose: Staked Amount: ", stakedAmount) - minStakeAmount, err := razorUtils.GetMinStakeAmount(ctx, client) + minStakeAmount, err := razorUtils.GetMinStakeAmount(rpcParameters) if err != nil { log.Error("Error in getting minimum stake amount: ", err) return err @@ -539,7 +534,7 @@ func (*UtilsStruct) InitiatePropose(ctx context.Context, client *ethclient.Clien log.Error("Stake is below minimum required. Kindly add stake to continue voting.") return nil } - lastProposal, err := razorUtils.GetEpochLastProposed(ctx, client, staker.Id) + lastProposal, err := razorUtils.GetEpochLastProposed(rpcParameters, staker.Id) if err != nil { return errors.New("Error in fetching last proposal: " + err.Error()) } @@ -548,7 +543,7 @@ func (*UtilsStruct) InitiatePropose(ctx context.Context, client *ethclient.Clien log.Debugf("Since last propose was at epoch: %d, won't propose again in epoch: %d", epoch, lastProposal) return nil } - lastReveal, err := razorUtils.GetEpochLastRevealed(ctx, client, staker.Id) + lastReveal, err := razorUtils.GetEpochLastRevealed(rpcParameters, staker.Id) if err != nil { return errors.New("Error in fetching last reveal: " + err.Error()) } @@ -559,7 +554,7 @@ func (*UtilsStruct) InitiatePropose(ctx context.Context, client *ethclient.Clien } log.Debugf("InitiatePropose: Calling Propose() with arguments staker = %+v, epoch = %d, blockNumber = %s, rogueData = %+v", staker, epoch, latestHeader.Number, rogueData) - err = cmdUtils.Propose(ctx, client, config, account, staker, epoch, latestHeader, stateBuffer, rogueData) + err = cmdUtils.Propose(rpcParameters, config, account, staker, epoch, latestHeader, stateBuffer, rogueData) if err != nil { return errors.New("Propose error: " + err.Error()) } diff --git a/cmd/vote_test.go b/cmd/vote_test.go index 023e7b388..97ce970de 100644 --- a/cmd/vote_test.go +++ b/cmd/vote_test.go @@ -12,6 +12,7 @@ import ( "razor/cache" "razor/core/types" "razor/pkg/bindings" + "razor/rpc" "razor/utils" "reflect" "testing" @@ -151,17 +152,19 @@ func TestExecuteVote(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() + setupTestEndpointsEnvironment() + utilsMock.On("IsFlagPassed", mock.Anything).Return(true) fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) - utilsMock.On("GetStateBuffer", mock.Anything, mock.Anything).Return(uint64(5), nil) + utilsMock.On("GetStateBuffer", mock.Anything).Return(uint64(5), nil) utilsMock.On("AssignPassword", flagSet).Return(tt.args.password) utilsMock.On("CheckPassword", mock.Anything).Return(nil) utilsMock.On("AccountManagerForKeystore").Return(&accounts.AccountManager{}, nil) @@ -169,11 +172,11 @@ func TestExecuteVote(t *testing.T) { flagSetMock.On("GetStringSliceBackupNode", mock.Anything).Return([]string{}, nil) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) flagSetMock.On("GetBoolRogue", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.rogueStatus, tt.args.rogueErr) - utilsMock.On("GetStakerId", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) + utilsMock.On("GetStakerId", mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) flagSetMock.On("GetStringSliceRogueMode", mock.AnythingOfType("*pflag.FlagSet")).Return(tt.args.rogueMode, tt.args.rogueModeErr) - cmdUtilsMock.On("InitJobAndCollectionCache", mock.Anything, mock.Anything).Return(&cache.JobsCache{}, &cache.CollectionsCache{}, big.NewInt(100), nil) + cmdUtilsMock.On("InitJobAndCollectionCache", mock.Anything).Return(&cache.JobsCache{}, &cache.CollectionsCache{}, big.NewInt(100), nil) cmdUtilsMock.On("HandleExit").Return() - cmdUtilsMock.On("Vote", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.voteErr) + cmdUtilsMock.On("Vote", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.voteErr) osMock.On("Exit", mock.AnythingOfType("int")).Return() utils := &UtilsStruct{} @@ -336,7 +339,6 @@ func TestCalculateSecret(t *testing.T) { func TestInitiateCommit(t *testing.T) { var ( - client *ethclient.Client config types.Configurations latestHeader *Types.Header stateBuffer uint64 @@ -553,20 +555,20 @@ func TestInitiateCommit(t *testing.T) { utils.MerkleInterface = &utils.MerkleTreeStruct{} merkleUtils = utils.MerkleInterface - utilsMock.On("GetStaker", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.staker, tt.args.stakerErr) - utilsMock.On("GetMinStakeAmount", mock.Anything, mock.Anything).Return(tt.args.minStakeAmount, tt.args.minStakeAmountErr) - utilsMock.On("GetEpochLastCommitted", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.lastCommit, tt.args.lastCommitErr) + utilsMock.On("GetStaker", mock.Anything, mock.Anything).Return(tt.args.staker, tt.args.stakerErr) + utilsMock.On("GetMinStakeAmount", mock.Anything).Return(tt.args.minStakeAmount, tt.args.minStakeAmountErr) + utilsMock.On("GetEpochLastCommitted", mock.Anything, mock.Anything).Return(tt.args.lastCommit, tt.args.lastCommitErr) cmdUtilsMock.On("CalculateSecret", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.signature, tt.args.secret, tt.args.secretErr) - cmdUtilsMock.On("GetSalt", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.salt, tt.args.saltErr) - cmdUtilsMock.On("HandleCommitState", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.commitData, tt.args.commitDataErr) + cmdUtilsMock.On("GetSalt", mock.Anything, mock.Anything).Return(tt.args.salt, tt.args.saltErr) + cmdUtilsMock.On("HandleCommitState", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.commitData, tt.args.commitDataErr) pathMock.On("GetDefaultPath").Return(tt.args.path, tt.args.pathErr) - cmdUtilsMock.On("Commit", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.commitTxn, tt.args.commitTxnErr) + cmdUtilsMock.On("Commit", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.commitTxn, tt.args.commitTxnErr) pathMock.On("GetCommitDataFileName", mock.AnythingOfType("string")).Return(tt.args.fileName, tt.args.fileNameErr) fileUtilsMock.On("SaveDataToCommitJsonFile", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.saveErr) - clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything, mock.Anything).Return(&Types.Header{Number: big.NewInt(100)}, nil) + clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything).Return(&Types.Header{Number: big.NewInt(100)}, nil) clientUtilsMock.On("FilterLogsWithRetry", mock.Anything, mock.Anything, mock.Anything).Return([]Types.Log{}, nil) ut := &UtilsStruct{} - if err := ut.InitiateCommit(context.Background(), client, config, account, tt.args.epoch, stakerId, latestHeader, commitParams, stateBuffer, rogueData); (err != nil) != tt.wantErr { + if err := ut.InitiateCommit(rpcParameters, config, account, tt.args.epoch, stakerId, latestHeader, commitParams, stateBuffer, rogueData); (err != nil) != tt.wantErr { t.Errorf("InitiateCommit() error = %v, wantErr %v", err, tt.wantErr) } }) @@ -575,7 +577,6 @@ func TestInitiateCommit(t *testing.T) { func TestInitiateReveal(t *testing.T) { var ( - client *ethclient.Client config types.Configurations account types.Account latestHeader *Types.Header @@ -780,20 +781,20 @@ func TestInitiateReveal(t *testing.T) { utils.MerkleInterface = &utils.MerkleTreeStruct{} merkleUtils = utils.MerkleInterface - utilsMock.On("GetMinStakeAmount", mock.Anything, mock.Anything).Return(tt.args.minStakeAmount, tt.args.minStakeAmountErr) - utilsMock.On("GetEpochLastRevealed", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.lastReveal, tt.args.lastRevealErr) - cmdUtilsMock.On("CheckForLastCommitted", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.revealStateErr) + utilsMock.On("GetMinStakeAmount", mock.Anything).Return(tt.args.minStakeAmount, tt.args.minStakeAmountErr) + utilsMock.On("GetEpochLastRevealed", mock.Anything, mock.Anything).Return(tt.args.lastReveal, tt.args.lastRevealErr) + cmdUtilsMock.On("CheckForLastCommitted", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.revealStateErr) pathMock.On("GetCommitDataFileName", mock.AnythingOfType("string")).Return(tt.args.fileName, tt.args.fileNameErr) fileUtilsMock.On("ReadFromCommitJsonFile", mock.Anything).Return(tt.args.committedDataFromFile, tt.args.committedDataFromFileErr) utilsMock.On("GetRogueRandomValue", mock.AnythingOfType("int")).Return(randomNum) pathMock.On("GetDefaultPath").Return(tt.args.path, tt.args.pathErr) cmdUtilsMock.On("CalculateSecret", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.signature, tt.args.secret, tt.args.secretErr) - cmdUtilsMock.On("GetSalt", mock.Anything, mock.Anything, mock.Anything).Return([32]byte{}, nil) - utilsMock.On("GetCommitment", mock.Anything, mock.Anything, mock.Anything).Return(types.Commitment{CommitmentHash: decodedCommitment32}, nil) - cmdUtilsMock.On("Reveal", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.revealTxn, tt.args.revealTxnErr) - utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) + cmdUtilsMock.On("GetSalt", mock.Anything, mock.Anything).Return([32]byte{}, nil) + utilsMock.On("GetCommitment", mock.Anything, mock.Anything).Return(types.Commitment{CommitmentHash: decodedCommitment32}, nil) + cmdUtilsMock.On("Reveal", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.revealTxn, tt.args.revealTxnErr) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) ut := &UtilsStruct{} - if err := ut.InitiateReveal(context.Background(), client, config, account, tt.args.epoch, tt.args.staker, latestHeader, stateBuffer, tt.args.rogueData); (err != nil) != tt.wantErr { + if err := ut.InitiateReveal(rpcParameters, config, account, tt.args.epoch, tt.args.staker, latestHeader, stateBuffer, tt.args.rogueData); (err != nil) != tt.wantErr { t.Errorf("InitiateReveal() error = %v, wantErr %v", err, tt.wantErr) } }) @@ -802,7 +803,6 @@ func TestInitiateReveal(t *testing.T) { func TestInitiatePropose(t *testing.T) { var ( - client *ethclient.Client config types.Configurations account types.Account rogueData types.Rogue @@ -907,13 +907,13 @@ func TestInitiatePropose(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetMinStakeAmount", mock.Anything, mock.Anything).Return(tt.args.minStakeAmount, tt.args.minStakeAmountErr) - utilsMock.On("GetEpochLastProposed", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.lastProposal, tt.args.lastProposalErr) - utilsMock.On("GetEpochLastRevealed", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.lastReveal, tt.args.lastRevealErr) - cmdUtilsMock.On("Propose", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.proposeTxnErr) - utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) + utilsMock.On("GetMinStakeAmount", mock.Anything).Return(tt.args.minStakeAmount, tt.args.minStakeAmountErr) + utilsMock.On("GetEpochLastProposed", mock.Anything, mock.Anything).Return(tt.args.lastProposal, tt.args.lastProposalErr) + utilsMock.On("GetEpochLastRevealed", mock.Anything, mock.Anything).Return(tt.args.lastReveal, tt.args.lastRevealErr) + cmdUtilsMock.On("Propose", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.proposeTxnErr) + utilsMock.On("WaitForBlockCompletion", mock.Anything, mock.Anything).Return(nil) ut := &UtilsStruct{} - if err := ut.InitiatePropose(context.Background(), client, config, account, tt.args.epoch, tt.args.staker, latestHeader, stateBuffer, rogueData); (err != nil) != tt.wantErr { + if err := ut.InitiatePropose(rpcParameters, config, account, tt.args.epoch, tt.args.staker, latestHeader, stateBuffer, rogueData); (err != nil) != tt.wantErr { t.Errorf("InitiatePropose() error = %v, wantErr %v", err, tt.wantErr) } }) @@ -922,7 +922,6 @@ func TestInitiatePropose(t *testing.T) { func TestHandleBlock(t *testing.T) { var ( - client *ethclient.Client account types.Account stakerId uint32 commitParams *types.CommitParams @@ -1268,27 +1267,27 @@ func TestHandleBlock(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetStateBuffer", mock.Anything, mock.Anything).Return(uint64(5), tt.args.stateBufferErr) + utilsMock.On("GetStateBuffer", mock.Anything).Return(uint64(5), tt.args.stateBufferErr) utilsMock.On("GetRemainingTimeOfCurrentState", mock.Anything, mock.Anything, mock.Anything).Return(int64(10), tt.args.stateRemainingTimeErr) utilsMock.On("GetBufferedState", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.state, tt.args.stateErr) - utilsMock.On("GetEpoch", mock.Anything, mock.Anything).Return(tt.args.epoch, tt.args.epochErr) - utilsMock.On("GetStaker", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.staker, tt.args.stakerErr) - clientUtilsMock.On("BalanceAtWithRetry", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.ethBalance, tt.args.ethBalanceErr) - utilsMock.On("GetStakerSRZRBalance", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.sRZRBalance, tt.args.sRZRBalanceErr) + utilsMock.On("GetEpoch", mock.Anything).Return(tt.args.epoch, tt.args.epochErr) + utilsMock.On("GetStaker", mock.Anything, mock.Anything).Return(tt.args.staker, tt.args.stakerErr) + clientUtilsMock.On("BalanceAtWithRetry", mock.Anything, mock.Anything).Return(tt.args.ethBalance, tt.args.ethBalanceErr) + utilsMock.On("GetStakerSRZRBalance", mock.Anything, mock.Anything).Return(tt.args.sRZRBalance, tt.args.sRZRBalanceErr) osMock.On("Exit", mock.AnythingOfType("int")).Return() - cmdUtilsMock.On("InitiateCommit", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.initiateCommitErr) - cmdUtilsMock.On("InitiateReveal", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.initiateRevealErr) - cmdUtilsMock.On("InitiatePropose", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.initiateProposeErr) - cmdUtilsMock.On("HandleDispute", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.handleDisputeErr) + cmdUtilsMock.On("InitiateCommit", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.initiateCommitErr) + cmdUtilsMock.On("InitiateReveal", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.initiateRevealErr) + cmdUtilsMock.On("InitiatePropose", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.initiateProposeErr) + cmdUtilsMock.On("HandleDispute", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.handleDisputeErr) utilsMock.On("IsFlagPassed", mock.AnythingOfType("string")).Return(tt.args.isFlagPassed) cmdUtilsMock.On("HandleClaimBounty", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.handleClaimBountyErr) - utilsMock.On("GetConfirmedBlocks", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.confirmedBlock, tt.args.confirmedBlockErr) + utilsMock.On("GetConfirmedBlocks", mock.Anything, mock.Anything).Return(tt.args.confirmedBlock, tt.args.confirmedBlockErr) cmdUtilsMock.On("ClaimBlockReward", mock.Anything, mock.Anything).Return(tt.args.claimBlockRewardTxn, tt.args.claimBlockRewardErr) timeMock.On("Sleep", mock.Anything).Return() utilsMock.On("WaitTillNextNSecs", mock.AnythingOfType("int32")).Return() lastVerification = tt.args.lastVerification ut := &UtilsStruct{} - ut.HandleBlock(client, account, stakerId, latestHeader, tt.args.config, commitParams, rogueData, backupNodeActionsToIgnore) + ut.HandleBlock(rpcParameters, account, stakerId, latestHeader, tt.args.config, commitParams, rogueData, backupNodeActionsToIgnore) }) } } @@ -1296,7 +1295,6 @@ func TestHandleBlock(t *testing.T) { func TestVote(t *testing.T) { var ( config types.Configurations - client *ethclient.Client rogueData types.Rogue account types.Account stakerId uint32 @@ -1328,14 +1326,19 @@ func TestVote(t *testing.T) { SetUpMockInterfaces() - clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything, mock.Anything).Return(tt.args.header, nil) + clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything).Return(tt.args.header, nil) cmdUtilsMock.On("HandleBlock", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil) + localRpcParameters := rpc.RPCParameters{ + Ctx: ctx, + RPCManager: &rpcManager, + } + ut := &UtilsStruct{} errChan := make(chan error) // Run Vote function in a goroutine go func() { - errChan <- ut.Vote(ctx, config, client, account, stakerId, commitParams, rogueData, backupNodeActionsToIgnore) + errChan <- ut.Vote(localRpcParameters, config, account, stakerId, commitParams, rogueData, backupNodeActionsToIgnore) }() // Wait for some time to allow Vote function to execute diff --git a/config.sh b/config.sh index 89ca8532e..96af7366b 100644 --- a/config.sh +++ b/config.sh @@ -11,8 +11,6 @@ then PROVIDER="http://127.0.0.1:8545" fi -read -rp "Alternate Provider: " ALTERNATE_PROVIDER - read -rp "Gas Multiplier: (1.0) " GAS_MULTIPLIER if [ -z "$GAS_MULTIPLIER" ]; then @@ -55,9 +53,4 @@ if [ -z "$MAX_AGE" ]; then MAX_AGE=60 fi -ALT_PROVIDER_OPTION="" -if [ -n "$ALTERNATE_PROVIDER" ]; then - ALT_PROVIDER_OPTION="--alternateProvider $ALTERNATE_PROVIDER" -fi - -$RAZOR setConfig -p $PROVIDER $ALT_PROVIDER_OPTION -b $BUFFER -g $GAS_MULTIPLIER -w $WAIT_TIME --gasprice $GAS_PRICE --gasLimit $GAS_LIMIT --rpcTimeout 5 --httpTimeout 5 --logFileMaxSize $MAX_SIZE --logFileMaxBackups $MAX_BACKUPS --logFileMaxAge $MAX_AGE \ No newline at end of file +$RAZOR setConfig -p $PROVIDER -b $BUFFER -g $GAS_MULTIPLIER -w $WAIT_TIME --gasprice $GAS_PRICE --gasLimit $GAS_LIMIT --rpcTimeout 5 --httpTimeout 5 --logFileMaxSize $MAX_SIZE --logFileMaxBackups $MAX_BACKUPS --logFileMaxAge $MAX_AGE \ No newline at end of file diff --git a/core/constants.go b/core/constants.go index 5570c4afb..e64548d25 100644 --- a/core/constants.go +++ b/core/constants.go @@ -69,8 +69,17 @@ const ( DefaultPathName = ".razor" ) -//BlockNumberInterval is the interval in seconds after which blockNumber needs to be calculated again -const BlockNumberInterval = 5 +const ( + //BlockNumberInterval is the interval in seconds after which blockNumber needs to be calculated again by blockMonitor + BlockNumberInterval = 5 + + // StaleBlockNumberCheckInterval specifies the duration in seconds after which the BlockMonitor + // switches to an alternate endpoint if the block number remains unchanged, indicating a potential stale endpoint. + StaleBlockNumberCheckInterval = 15 +) + +//EndpointsContextTimeout defines the maximum duration in seconds to wait for establishing a connection for an endpoint +const EndpointsContextTimeout = 5 //APIKeyRegex will be used as a regular expression to be matched in job Urls const APIKeyRegex = `\$\{(.+?)\}` @@ -81,9 +90,6 @@ const ( ProcessRequestRetryDelay int64 = 2 ) -//SwitchClientDuration is the time after which alternate client from secondary RPC will be switched back to client from primary RPC -const SwitchClientDuration = 5 * EpochLength - const ( // HexReturnType is the ReturnType for a job if that job returns a hex value HexReturnType = "hex" diff --git a/core/endpoints.go b/core/endpoints.go new file mode 100644 index 000000000..813f0f522 --- /dev/null +++ b/core/endpoints.go @@ -0,0 +1,20 @@ +package core + +var DefaultEndpoints = []string{ + "https://andromeda02.skale.prod.chorus1.net:10072", + "https://skale-figment-9.skale.figment.io:10008", + "https://skale-figment-2.skale.figment.io:10072", + "https://node03.skale.prod.chorus1.net:10072", + "https://skale.tuku.dev:10136", + "https://signia-node-8.skale.bdnodes.net:10072", + "https://skale.infstones.io:10136", + "https://skale-figment-8.skale.figment.io:10200", + "https://node05.skale.prod.chorus1.net:10136", + "https://block-node-5.skale.bdnodes.net:10008", + "https://skale-figment-11.skale.figment.io:10072", + "https://skale-jupiter-2.skale.figment.io:10072", + "https://signia-node-5.skale.bdnodes.net:10328", + "https://block-node-8.skale.bdnodes.net:10008", + "https://skale-mainnet-1a.stakin-nodes.com:10072", + "https://skale2.anonstake.com:10008", +} diff --git a/core/types/configurations.go b/core/types/configurations.go index da42176f9..2fded1d0b 100644 --- a/core/types/configurations.go +++ b/core/types/configurations.go @@ -2,7 +2,6 @@ package types type Configurations struct { Provider string - AlternateProvider string GasMultiplier float32 BufferPercent int32 WaitTime int32 diff --git a/core/types/transaction.go b/core/types/transaction.go index 75819cacf..0d7ce718b 100644 --- a/core/types/transaction.go +++ b/core/types/transaction.go @@ -1,12 +1,10 @@ package types import ( - "github.com/ethereum/go-ethereum/ethclient" "math/big" ) type TransactionOptions struct { - Client *ethclient.Client EtherValue *big.Int Amount *big.Int ChainId *big.Int diff --git a/logger/logger.go b/logger/logger.go index c640041f8..6bb8b2c21 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -18,25 +18,34 @@ import ( "gopkg.in/natefinch/lumberjack.v2" ) -type StandardLogger struct { - *logrus.Logger +// Logger encapsulates logrus and its dependencies for contextual logging. +type Logger struct { + LogrusInstance *logrus.Logger + address string + client *ethclient.Client + blockMonitor *block.BlockMonitor } -var standardLogger = &StandardLogger{logrus.New()} +// Global logger instance +var globalLogger = NewLogger("", nil, nil) -var Address string -var Epoch uint32 -var BlockNumber *big.Int -var FileName string -var Client *ethclient.Client +// GetLogger returns the global logger instance. +func GetLogger() *Logger { + return globalLogger +} + +// UpdateLogger updates the global logger instance with new parameters. +func UpdateLogger(address string, client *ethclient.Client, blockMonitor *block.BlockMonitor) { + globalLogger.address = address + globalLogger.client = client + globalLogger.blockMonitor = blockMonitor +} func init() { - path.PathUtilsInterface = &path.PathUtils{} - path.OSUtilsInterface = &path.OSUtils{} - InitializeLogger(FileName, types.Configurations{}) + InitializeLogger("", types.Configurations{}) osInfo := goInfo.GetInfo() - standardLogger.WithFields(logrus.Fields{ + globalLogger.LogrusInstance.WithFields(logrus.Fields{ "Operating System": osInfo.OS, "Core": osInfo.Core, "Platform": osInfo.Platform, @@ -47,11 +56,25 @@ func init() { } +//NewLogger initializes a Logger instance with given parameters. +func NewLogger(address string, client *ethclient.Client, blockMonitor *block.BlockMonitor) *Logger { + logger := &Logger{ + LogrusInstance: logrus.New(), + address: address, + client: client, + blockMonitor: blockMonitor, + } + + return logger +} + func InitializeLogger(fileName string, config types.Configurations) { + path.PathUtilsInterface = &path.PathUtils{} + path.OSUtilsInterface = &path.OSUtils{} if fileName != "" { logFilePath, err := path.PathUtilsInterface.GetLogFilePath(fileName) if err != nil { - standardLogger.Fatal("Error in fetching log file path: ", err) + globalLogger.Fatal("Error in fetching log file path: ", err) } lumberJackLogger := &lumberjack.Logger{ @@ -61,131 +84,160 @@ func InitializeLogger(fileName string, config types.Configurations) { MaxAge: config.LogFileMaxAge, } - out := os.Stderr - mw := io.MultiWriter(out, lumberJackLogger) - standardLogger.SetOutput(mw) + mw := io.MultiWriter(os.Stderr, lumberJackLogger) + globalLogger.LogrusInstance.SetOutput(mw) } - standardLogger.Formatter = &logrus.JSONFormatter{} + globalLogger.LogrusInstance.Formatter = &logrus.JSONFormatter{} } -func NewLogger() *StandardLogger { - return standardLogger +// Error logs a simple error message. +func (l *Logger) Error(args ...interface{}) { + epoch, blockNumber := l.updateBlockInfo() + logFields := logrus.Fields{ + "address": l.address, + "epoch": epoch, + "blockNumber": blockNumber, + "version": core.VersionWithMeta, + } + l.LogrusInstance.WithFields(logFields).Errorln(args...) } -func joinString(args ...interface{}) string { - str := "" - for index := 0; index < len(args); index++ { - msg := fmt.Sprintf("%v", args[index]) - str += " " + msg +// Info logs a simple informational message. +func (l *Logger) Info(args ...interface{}) { + epoch, blockNumber := l.updateBlockInfo() + logFields := logrus.Fields{ + "address": l.address, + "epoch": epoch, + "blockNumber": blockNumber, + "version": core.VersionWithMeta, } - return str + l.LogrusInstance.WithFields(logFields).Infoln(args...) } -func (logger *StandardLogger) Error(args ...interface{}) { - SetEpochAndBlockNumber(Client) - var logFields = logrus.Fields{ - "address": Address, - "epoch": Epoch, - "blockNumber": BlockNumber, +// Debug logs a simple debug message. +func (l *Logger) Debug(args ...interface{}) { + epoch, blockNumber := l.updateBlockInfo() + logFields := logrus.Fields{ + "address": l.address, + "epoch": epoch, + "blockNumber": blockNumber, "version": core.VersionWithMeta, } - logger.WithFields(logFields).Errorln(args...) + l.LogrusInstance.WithFields(logFields).Debugln(args...) } -func (logger *StandardLogger) Info(args ...interface{}) { - SetEpochAndBlockNumber(Client) - var logFields = logrus.Fields{ - "address": Address, - "epoch": Epoch, - "blockNumber": BlockNumber, +// Fatal logs a fatal error message and exits the application. +func (l *Logger) Fatal(args ...interface{}) { + epoch, blockNumber := l.updateBlockInfo() + logFields := logrus.Fields{ + "address": l.address, + "epoch": epoch, + "blockNumber": blockNumber, "version": core.VersionWithMeta, } - logger.WithFields(logFields).Infoln(args...) + errMsg := joinString(args) + err := errors.New(errMsg) + l.LogrusInstance.WithFields(logFields).Fatalln(err) } -func (logger *StandardLogger) Debug(args ...interface{}) { - SetEpochAndBlockNumber(Client) - var logFields = logrus.Fields{ - "address": Address, - "epoch": Epoch, - "blockNumber": BlockNumber, +// Warn logs a simple warning message. +func (l *Logger) Warn(args ...interface{}) { + epoch, blockNumber := l.updateBlockInfo() + logFields := logrus.Fields{ + "address": l.address, + "epoch": epoch, + "blockNumber": blockNumber, "version": core.VersionWithMeta, } - logger.WithFields(logFields).Debugln(args...) + l.LogrusInstance.WithFields(logFields).Warnln(args...) } -func (logger *StandardLogger) Fatal(args ...interface{}) { - SetEpochAndBlockNumber(Client) - var logFields = logrus.Fields{ - "address": Address, - "epoch": Epoch, - "blockNumber": BlockNumber, +// Errorf logs a formatted error message. +func (l *Logger) Errorf(format string, args ...interface{}) { + epoch, blockNumber := l.updateBlockInfo() + logFields := logrus.Fields{ + "address": l.address, + "epoch": epoch, + "blockNumber": blockNumber, "version": core.VersionWithMeta, } - errMsg := joinString(args) - err := errors.New(errMsg) - logger.WithFields(logFields).Fatalln(err) + l.LogrusInstance.WithFields(logFields).Errorf(format, args...) } -func (logger *StandardLogger) Errorf(format string, args ...interface{}) { - SetEpochAndBlockNumber(Client) - var logFields = logrus.Fields{ - "address": Address, - "epoch": Epoch, - "blockNumber": BlockNumber, +// Infof logs a formatted informational message. +func (l *Logger) Infof(format string, args ...interface{}) { + epoch, blockNumber := l.updateBlockInfo() + logFields := logrus.Fields{ + "address": l.address, + "epoch": epoch, + "blockNumber": blockNumber, "version": core.VersionWithMeta, } - logger.WithFields(logFields).Errorf(format, args...) + l.LogrusInstance.WithFields(logFields).Infof(format, args...) } -func (logger *StandardLogger) Infof(format string, args ...interface{}) { - SetEpochAndBlockNumber(Client) - var logFields = logrus.Fields{ - "address": Address, - "epoch": Epoch, - "blockNumber": BlockNumber, +// Debugf logs a formatted debug message. +func (l *Logger) Debugf(format string, args ...interface{}) { + epoch, blockNumber := l.updateBlockInfo() + logFields := logrus.Fields{ + "address": l.address, + "epoch": epoch, + "blockNumber": blockNumber, "version": core.VersionWithMeta, } - logger.WithFields(logFields).Infof(format, args...) + l.LogrusInstance.WithFields(logFields).Debugf(format, args...) } -func (logger *StandardLogger) Debugf(format string, args ...interface{}) { - SetEpochAndBlockNumber(Client) - var logFields = logrus.Fields{ - "address": Address, - "epoch": Epoch, - "blockNumber": BlockNumber, +// Fatalf logs a formatted fatal error message and exits the application. +func (l *Logger) Fatalf(format string, args ...interface{}) { + epoch, blockNumber := l.updateBlockInfo() + logFields := logrus.Fields{ + "address": l.address, + "epoch": epoch, + "blockNumber": blockNumber, "version": core.VersionWithMeta, } - logger.WithFields(logFields).Debugf(format, args...) + errMsg := joinString(args...) + err := errors.New(errMsg) + l.LogrusInstance.WithFields(logFields).Fatalf(format, err) } -func (logger *StandardLogger) Fatalf(format string, args ...interface{}) { - SetEpochAndBlockNumber(Client) - var logFields = logrus.Fields{ - "address": Address, - "epoch": Epoch, - "blockNumber": BlockNumber, +// Warnf logs a formatted warning message. +func (l *Logger) Warnf(format string, args ...interface{}) { + epoch, blockNumber := l.updateBlockInfo() + logFields := logrus.Fields{ + "address": l.address, + "epoch": epoch, + "blockNumber": blockNumber, "version": core.VersionWithMeta, } - errMsg := joinString(args) - err := errors.New(errMsg) - logger.WithFields(logFields).Fatalf(format, err) + l.LogrusInstance.WithFields(logFields).Warnf(format, args...) } -func SetEpochAndBlockNumber(client *ethclient.Client) { - if client != nil { - latestBlock := block.GetLatestBlock() - if latestBlock != nil { - BlockNumber = latestBlock.Number - epoch := latestBlock.Time / core.EpochLength - Epoch = uint32(epoch) - } +// joinString concatenates multiple arguments into a single string. +func joinString(args ...interface{}) string { + str := "" + for index := 0; index < len(args); index++ { + msg := fmt.Sprintf("%v", args[index]) + str += " " + msg } + return str } -func SetLoggerParameters(client *ethclient.Client, address string) { - Address = address - Client = client - go block.CalculateLatestBlock(client) +// SetLogLevel sets the log level for the logger instance. +func (l *Logger) SetLogLevel(level logrus.Level) { + l.LogrusInstance.SetLevel(level) +} + +// updateBlockInfo fetches block info from the BlockMonitor. +func (l *Logger) updateBlockInfo() (uint32, *big.Int) { + if l.blockMonitor == nil { + return 0, nil + } + latestBlock := l.blockMonitor.GetLatestBlock() + if latestBlock != nil { + epoch := uint32(latestBlock.Time / core.EpochLength) + return epoch, latestBlock.Number + } + return 0, nil } diff --git a/rpc/rpc.go b/rpc/rpc.go new file mode 100644 index 000000000..98d73cb9b --- /dev/null +++ b/rpc/rpc.go @@ -0,0 +1,242 @@ +package rpc + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "github.com/ethereum/go-ethereum/ethclient" + "github.com/ethereum/go-ethereum/log" + "github.com/sirupsen/logrus" + "os" + "path/filepath" + "razor/core" + "razor/path" + "sort" + "strings" + "sync" + "time" +) + +func (m *RPCManager) calculateMetrics(endpoint *RPCEndpoint) error { + ctx, cancel := context.WithTimeout(context.Background(), core.EndpointsContextTimeout*time.Second) + defer cancel() + + client, err := ethclient.DialContext(ctx, endpoint.URL) + if err != nil { + return fmt.Errorf("failed to connect to RPC: %w", err) + } + + start := time.Now() + blockNumber, err := m.fetchBlockNumberWithTimeout(ctx, client) + if err != nil { + if errors.Is(err, context.DeadlineExceeded) { + return fmt.Errorf("RPC call timed out: %w", err) + } + return fmt.Errorf("RPC call failed: %w", err) + } + latency := time.Since(start).Seconds() + + endpoint.BlockNumber = blockNumber + endpoint.Latency = latency + endpoint.Client = client + + return nil +} + +// updateAndSortEndpoints calculates metrics and sorts the endpoints +func (m *RPCManager) updateAndSortEndpoints() error { + if len(m.Endpoints) == 0 { + return fmt.Errorf("no endpoints available to update") + } + + var wg sync.WaitGroup + logrus.Debug("Starting concurrent metrics calculation for all endpoints...") + + for _, endpoint := range m.Endpoints { + wg.Add(1) + go func(ep *RPCEndpoint) { + defer wg.Done() + if err := m.calculateMetrics(ep); err != nil { + logrus.Errorf("Error calculating metrics for endpoint %s: %v", ep.URL, err) + } + }(endpoint) + } + wg.Wait() + + log.Debug("Concurrent metrics calculation complete. Sorting endpoints...") + + m.mutex.Lock() + defer m.mutex.Unlock() + + sort.Slice(m.Endpoints, func(i, j int) bool { + if m.Endpoints[i].BlockNumber == m.Endpoints[j].BlockNumber { + return m.Endpoints[i].Latency < m.Endpoints[j].Latency + } + return m.Endpoints[i].BlockNumber > m.Endpoints[j].BlockNumber + }) + + // Update the best RPC endpoint after sorting + m.BestEndpoint = m.Endpoints[0] + + logrus.Infof("Best RPC endpoint updated: %s (BlockNumber: %d, Latency: %.2f)", + m.BestEndpoint.URL, m.BestEndpoint.BlockNumber, m.BestEndpoint.Latency) + + return nil +} + +// RefreshEndpoints will update and sort the endpoints. +func (m *RPCManager) RefreshEndpoints() error { + if err := m.updateAndSortEndpoints(); err != nil { + return fmt.Errorf("failed to refresh endpoints: %w", err) + } + logrus.Infof("Endpoints refreshed successfully") + return nil +} + +func InitializeRPCManager(provider string) (*RPCManager, error) { + defaultPath, err := path.PathUtilsInterface.GetDefaultPath() + if err != nil { + return nil, fmt.Errorf("failed to get .razor path: %w", err) + } + + endpointsFile := filepath.Join(defaultPath, "endpoints.json") + fileData, err := os.ReadFile(endpointsFile) + if err != nil { + return nil, fmt.Errorf("failed to read endpoints.json: %w", err) + } + + // Unmarshal the JSON file into a list of RPC endpoints + var rpcEndpointsList []string + err = json.Unmarshal(fileData, &rpcEndpointsList) + if err != nil { + return nil, fmt.Errorf("failed to unmarshal endpoints.json: %w", err) + } + + // Normalize provider input and check if it's already in the list + provider = strings.TrimSpace(provider) // Trim whitespace from the input + providerFound := false + for _, endpoint := range rpcEndpointsList { + if endpoint == provider { + providerFound = true + break + } + } + + // If the provider is not found, add it to the list + if !providerFound && provider != "" { + logrus.Infof("Adding user-provided endpoint: %s", provider) + rpcEndpointsList = append(rpcEndpointsList, provider) + } + + // Initialize the RPC endpoints + rpcEndpoints := make([]*RPCEndpoint, len(rpcEndpointsList)) + for i, url := range rpcEndpointsList { + rpcEndpoints[i] = &RPCEndpoint{URL: url} + } + + rpcManager := &RPCManager{ + Endpoints: rpcEndpoints, + } + + // Pre-calculate metrics and set the best client on initialization + if err := rpcManager.updateAndSortEndpoints(); err != nil { + return nil, fmt.Errorf("failed to initialize RPC Manager: %w", err) + } + + return rpcManager, nil +} + +func (m *RPCManager) GetBestRPCClient() (*ethclient.Client, error) { + m.mutex.RLock() + defer m.mutex.RUnlock() + + if m.BestEndpoint.Client == nil { + return nil, fmt.Errorf("no best RPC client available") + } + return m.BestEndpoint.Client, nil +} + +// GetBestEndpointURL returns the URL of the best endpoint +func (m *RPCManager) GetBestEndpointURL() (string, error) { + m.mutex.RLock() + defer m.mutex.RUnlock() + + if m.BestEndpoint == nil { + return "", fmt.Errorf("no best endpoint available") + } + return m.BestEndpoint.URL, nil +} + +// SwitchToNextBestRPCClient switches to the next best available client after the current best client. +// If no valid next best client is found, it retains the current best client. +func (m *RPCManager) SwitchToNextBestRPCClient() (bool, error) { + m.mutex.Lock() + defer m.mutex.Unlock() + + // If there are fewer than 2 endpoints, there are no alternate clients to switch to. + if len(m.Endpoints) < 2 { + logrus.Warn("No alternate RPC clients available. Retaining the current best client.") + return false, nil + } + + // Find the index of the current best client + var currentIndex = -1 + for i, endpoint := range m.Endpoints { + if endpoint.Client == m.BestEndpoint.Client { + currentIndex = i + break + } + } + + // If the current client is not found (which is rare), return an error + if currentIndex == -1 { + return false, fmt.Errorf("current best client not found in the list of endpoints") + } + + // Iterate through the remaining endpoints to find a valid next best client + for i := 1; i < len(m.Endpoints); i++ { + nextIndex := (currentIndex + i) % len(m.Endpoints) + nextEndpoint := m.Endpoints[nextIndex] + + // Check if we can connect to the next endpoint + ctx, cancel := context.WithTimeout(context.Background(), core.EndpointsContextTimeout*time.Second) + cancel() + + client, err := ethclient.DialContext(ctx, nextEndpoint.URL) + if err != nil { + logrus.Errorf("Failed to connect to RPC endpoint %s: %v", nextEndpoint.URL, err) + continue + } + + // Try fetching block number to validate the endpoint + _, err = m.fetchBlockNumberWithTimeout(ctx, client) + if err != nil { + logrus.Errorf("Failed to fetch block number for endpoint %s: %v", nextEndpoint.URL, err) + continue + } + + // Successfully connected and validated, update the best client and endpoint + m.BestEndpoint.Client = client + m.BestEndpoint = nextEndpoint + + logrus.Infof("Switched to the next best RPC endpoint: %s (BlockNumber: %d, Latency: %.2f)", + m.BestEndpoint.URL, m.BestEndpoint.BlockNumber, m.BestEndpoint.Latency) + return true, nil + } + + // If no valid endpoint is found, retain the current best client + logrus.Warn("No valid next-best RPC client found. Retaining the current best client.") + return false, nil +} + +func (m *RPCManager) fetchBlockNumberWithTimeout(ctx context.Context, client *ethclient.Client) (uint64, error) { + blockNumber, err := client.BlockNumber(ctx) + if err != nil { + if errors.Is(err, context.DeadlineExceeded) { + return 0, fmt.Errorf("RPC call timed out: %w", err) + } + return 0, fmt.Errorf("RPC call failed: %w", err) + } + return blockNumber, nil +} diff --git a/rpc/rpc_struct.go b/rpc/rpc_struct.go new file mode 100644 index 000000000..6957c9d9a --- /dev/null +++ b/rpc/rpc_struct.go @@ -0,0 +1,25 @@ +package rpc + +import ( + "context" + "github.com/ethereum/go-ethereum/ethclient" + "sync" +) + +type RPCEndpoint struct { + URL string + BlockNumber uint64 + Latency float64 + Client *ethclient.Client +} + +type RPCManager struct { + Endpoints []*RPCEndpoint + mutex sync.RWMutex + BestEndpoint *RPCEndpoint // Holds the URL to current best RPC client +} + +type RPCParameters struct { + Ctx context.Context // Context with timeout for handling unresponsive RPC calls + RPCManager *RPCManager // RPC manager for client selection and contract calls +} diff --git a/utils/asset.go b/utils/asset.go index a19c47250..7c66abfb3 100644 --- a/utils/asset.go +++ b/utils/asset.go @@ -1,7 +1,6 @@ package utils import ( - "context" "encoding/hex" "encoding/json" "errors" @@ -12,6 +11,7 @@ import ( "razor/core/types" "razor/path" "razor/pkg/bindings" + "razor/rpc" "regexp" "strconv" "strings" @@ -29,22 +29,30 @@ func (*UtilsStruct) GetCollectionManagerWithOpts(client *ethclient.Client) (*bin return UtilsInterface.GetCollectionManager(client), UtilsInterface.GetOptions() } -func (*UtilsStruct) GetNumCollections(ctx context.Context, client *ethclient.Client) (uint16, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, AssetManagerInterface, "GetNumCollections", client) +func (*UtilsStruct) GetNumCollections(rpcParameters rpc.RPCParameters) (uint16, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, AssetManagerInterface, "GetNumCollections") if err != nil { return 0, err } return returnedValues[0].Interface().(uint16), nil } -func (*UtilsStruct) GetJobs(ctx context.Context, client *ethclient.Client) ([]bindings.StructsJob, error) { +func (*UtilsStruct) GetNumJobs(rpcParameters rpc.RPCParameters) (uint16, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, AssetManagerInterface, "GetNumJobs") + if err != nil { + return 0, err + } + return returnedValues[0].Interface().(uint16), nil +} + +func (*UtilsStruct) GetJobs(rpcParameters rpc.RPCParameters) ([]bindings.StructsJob, error) { var jobs []bindings.StructsJob - numJobs, err := AssetManagerInterface.GetNumJobs(client) + numJobs, err := UtilsInterface.GetNumJobs(rpcParameters) if err != nil { return nil, err } for i := 1; i <= int(numJobs); i++ { - job, err := UtilsInterface.GetActiveJob(ctx, client, uint16(i)) + job, err := UtilsInterface.GetActiveJob(rpcParameters, uint16(i)) if err != nil { return nil, err } @@ -53,22 +61,22 @@ func (*UtilsStruct) GetJobs(ctx context.Context, client *ethclient.Client) ([]bi return jobs, nil } -func (*UtilsStruct) GetNumActiveCollections(ctx context.Context, client *ethclient.Client) (uint16, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, AssetManagerInterface, "GetNumActiveCollections", client) +func (*UtilsStruct) GetNumActiveCollections(rpcParameters rpc.RPCParameters) (uint16, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, AssetManagerInterface, "GetNumActiveCollections") if err != nil { return 0, err } return returnedValues[0].Interface().(uint16), nil } -func (*UtilsStruct) GetAllCollections(ctx context.Context, client *ethclient.Client) ([]bindings.StructsCollection, error) { +func (*UtilsStruct) GetAllCollections(rpcParameters rpc.RPCParameters) ([]bindings.StructsCollection, error) { var collections []bindings.StructsCollection - numCollections, err := UtilsInterface.GetNumCollections(ctx, client) + numCollections, err := UtilsInterface.GetNumCollections(rpcParameters) if err != nil { return nil, err } for i := 1; i <= int(numCollections); i++ { - collection, err := AssetManagerInterface.GetCollection(client, uint16(i)) + collection, err := UtilsInterface.GetCollection(rpcParameters, uint16(i)) if err != nil { return nil, err } @@ -77,37 +85,45 @@ func (*UtilsStruct) GetAllCollections(ctx context.Context, client *ethclient.Cli return collections, nil } -func (*UtilsStruct) GetCollection(ctx context.Context, client *ethclient.Client, collectionId uint16) (bindings.StructsCollection, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, AssetManagerInterface, "GetCollection", client, collectionId) +func (*UtilsStruct) GetCollection(rpcParameters rpc.RPCParameters, collectionId uint16) (bindings.StructsCollection, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, AssetManagerInterface, "GetCollection", collectionId) if err != nil { return bindings.StructsCollection{}, err } return returnedValues[0].Interface().(bindings.StructsCollection), nil } -func (*UtilsStruct) GetActiveCollectionIds(ctx context.Context, client *ethclient.Client) ([]uint16, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, AssetManagerInterface, "GetActiveCollections", client) +func (*UtilsStruct) GetActiveCollectionIds(rpcParameters rpc.RPCParameters) ([]uint16, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, AssetManagerInterface, "GetActiveCollections") if err != nil { return nil, err } return returnedValues[0].Interface().([]uint16), nil } -func (*UtilsStruct) GetAggregatedDataOfCollection(ctx context.Context, client *ethclient.Client, collectionId uint16, epoch uint32, commitParams *types.CommitParams) (*big.Int, error) { +func (*UtilsStruct) GetActiveStatus(rpcParameters rpc.RPCParameters, id uint16) (bool, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, AssetManagerInterface, "GetActiveStatus", id) + if err != nil { + return false, err + } + return returnedValues[0].Interface().(bool), nil +} + +func (*UtilsStruct) GetAggregatedDataOfCollection(rpcParameters rpc.RPCParameters, collectionId uint16, epoch uint32, commitParams *types.CommitParams) (*big.Int, error) { activeCollection, err := UtilsInterface.GetActiveCollection(commitParams.CollectionsCache, collectionId) if err != nil { log.Error(err) return nil, err } //Supply previous epoch to Aggregate in case if last reported value is required. - collectionData, aggregationError := UtilsInterface.Aggregate(ctx, client, epoch-1, activeCollection, commitParams) + collectionData, aggregationError := UtilsInterface.Aggregate(rpcParameters, epoch-1, activeCollection, commitParams) if aggregationError != nil { return nil, aggregationError } return collectionData, nil } -func (*UtilsStruct) Aggregate(ctx context.Context, client *ethclient.Client, previousEpoch uint32, collection bindings.StructsCollection, commitParams *types.CommitParams) (*big.Int, error) { +func (*UtilsStruct) Aggregate(rpcParameters rpc.RPCParameters, previousEpoch uint32, collection bindings.StructsCollection, commitParams *types.CommitParams) (*big.Int, error) { var jobs []bindings.StructsJob var overriddenJobIds []uint16 @@ -136,7 +152,7 @@ func (*UtilsStruct) Aggregate(ctx context.Context, client *ethclient.Client, pre } // Overriding the jobs from contracts with official jobs present in asset.go - overrideJobs, overriddenJobIdsFromJSONfile := UtilsInterface.HandleOfficialJobsFromJSONFile(client, collection, dataString, commitParams) + overrideJobs, overriddenJobIdsFromJSONfile := UtilsInterface.HandleOfficialJobsFromJSONFile(collection, dataString, commitParams) jobs = append(jobs, overrideJobs...) overriddenJobIds = append(overriddenJobIds, overriddenJobIdsFromJSONfile...) @@ -165,7 +181,7 @@ func (*UtilsStruct) Aggregate(ctx context.Context, client *ethclient.Client, pre } dataToCommit, weight := UtilsInterface.GetDataToCommitFromJobs(jobs, commitParams) if len(dataToCommit) == 0 { - prevCommitmentData, err := UtilsInterface.FetchPreviousValue(ctx, client, previousEpoch, collection.Id) + prevCommitmentData, err := UtilsInterface.FetchPreviousValue(rpcParameters, previousEpoch, collection.Id) if err != nil { return nil, err } @@ -174,8 +190,8 @@ func (*UtilsStruct) Aggregate(ctx context.Context, client *ethclient.Client, pre return performAggregation(dataToCommit, weight, collection.AggregationMethod) } -func (*UtilsStruct) GetActiveJob(ctx context.Context, client *ethclient.Client, jobId uint16) (bindings.StructsJob, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, AssetManagerInterface, "Jobs", client, jobId) +func (*UtilsStruct) GetActiveJob(rpcParameters rpc.RPCParameters, jobId uint16) (bindings.StructsJob, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, AssetManagerInterface, "Jobs", jobId) if err != nil { return bindings.StructsJob{}, err } @@ -300,10 +316,10 @@ func (*UtilsStruct) GetDataToCommitFromJob(job bindings.StructsJob, commitParams return MultiplyWithPower(datum, job.Power), err } -func (*UtilsStruct) GetAssignedCollections(ctx context.Context, client *ethclient.Client, numActiveCollections uint16, seed []byte) (map[int]bool, []*big.Int, error) { +func (*UtilsStruct) GetAssignedCollections(rpcParameters rpc.RPCParameters, numActiveCollections uint16, seed []byte) (map[int]bool, []*big.Int, error) { assignedCollections := make(map[int]bool) var seqAllottedCollections []*big.Int - toAssign, err := UtilsInterface.ToAssign(ctx, client) + toAssign, err := UtilsInterface.ToAssign(rpcParameters) if err != nil { return nil, nil, err } @@ -315,24 +331,24 @@ func (*UtilsStruct) GetAssignedCollections(ctx context.Context, client *ethclien return assignedCollections, seqAllottedCollections, nil } -func (*UtilsStruct) GetLeafIdOfACollection(ctx context.Context, client *ethclient.Client, collectionId uint16) (uint16, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, AssetManagerInterface, "GetLeafIdOfACollection", client, collectionId) +func (*UtilsStruct) GetLeafIdOfACollection(rpcParameters rpc.RPCParameters, collectionId uint16) (uint16, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, AssetManagerInterface, "GetLeafIdOfACollection", collectionId) if err != nil { return 0, err } return returnedValues[0].Interface().(uint16), nil } -func (*UtilsStruct) GetCollectionIdFromIndex(ctx context.Context, client *ethclient.Client, medianIndex uint16) (uint16, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, AssetManagerInterface, "GetCollectionIdFromIndex", client, medianIndex) +func (*UtilsStruct) GetCollectionIdFromIndex(rpcParameters rpc.RPCParameters, medianIndex uint16) (uint16, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, AssetManagerInterface, "GetCollectionIdFromIndex", medianIndex) if err != nil { return 0, err } return returnedValues[0].Interface().(uint16), nil } -func (*UtilsStruct) GetCollectionIdFromLeafId(ctx context.Context, client *ethclient.Client, leafId uint16) (uint16, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, AssetManagerInterface, "GetCollectionIdFromLeafId", client, leafId) +func (*UtilsStruct) GetCollectionIdFromLeafId(rpcParameters rpc.RPCParameters, leafId uint16) (uint16, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, AssetManagerInterface, "GetCollectionIdFromLeafId", leafId) if err != nil { return 0, err } @@ -390,7 +406,7 @@ func ConvertCustomJobToStructJob(customJob types.CustomJob) bindings.StructsJob } } -func (*UtilsStruct) HandleOfficialJobsFromJSONFile(client *ethclient.Client, collection bindings.StructsCollection, dataString string, commitParams *types.CommitParams) ([]bindings.StructsJob, []uint16) { +func (*UtilsStruct) HandleOfficialJobsFromJSONFile(collection bindings.StructsCollection, dataString string, commitParams *types.CommitParams) ([]bindings.StructsJob, []uint16) { var overrideJobs []bindings.StructsJob var overriddenJobIds []uint16 @@ -437,7 +453,7 @@ func (*UtilsStruct) HandleOfficialJobsFromJSONFile(client *ethclient.Client, col } // InitJobsCache initializes the jobs cache with data fetched from the blockchain -func InitJobsCache(ctx context.Context, client *ethclient.Client, jobsCache *cache.JobsCache) error { +func InitJobsCache(rpcParameters rpc.RPCParameters, jobsCache *cache.JobsCache) error { jobsCache.Mu.Lock() defer jobsCache.Mu.Unlock() @@ -446,12 +462,12 @@ func InitJobsCache(ctx context.Context, client *ethclient.Client, jobsCache *cac delete(jobsCache.Jobs, k) } - numJobs, err := AssetManagerInterface.GetNumJobs(client) + numJobs, err := UtilsInterface.GetNumJobs(rpcParameters) if err != nil { return err } for i := 1; i <= int(numJobs); i++ { - job, err := UtilsInterface.GetActiveJob(ctx, client, uint16(i)) + job, err := UtilsInterface.GetActiveJob(rpcParameters, uint16(i)) if err != nil { return err } @@ -461,7 +477,7 @@ func InitJobsCache(ctx context.Context, client *ethclient.Client, jobsCache *cac } // InitCollectionsCache initializes the collections cache with data fetched from the blockchain -func InitCollectionsCache(client *ethclient.Client, collectionsCache *cache.CollectionsCache) error { +func InitCollectionsCache(rpcParameters rpc.RPCParameters, collectionsCache *cache.CollectionsCache) error { collectionsCache.Mu.Lock() defer collectionsCache.Mu.Unlock() @@ -470,12 +486,12 @@ func InitCollectionsCache(client *ethclient.Client, collectionsCache *cache.Coll delete(collectionsCache.Collections, k) } - numCollections, err := AssetManagerInterface.GetNumCollections(client) + numCollections, err := UtilsInterface.GetNumCollections(rpcParameters) if err != nil { return err } for i := 1; i <= int(numCollections); i++ { - collection, err := AssetManagerInterface.GetCollection(client, uint16(i)) + collection, err := UtilsInterface.GetCollection(rpcParameters, uint16(i)) if err != nil { return err } diff --git a/utils/asset_test.go b/utils/asset_test.go index c140857a1..65c25e198 100644 --- a/utils/asset_test.go +++ b/utils/asset_test.go @@ -14,6 +14,7 @@ import ( "razor/path" pathMocks "razor/path/mocks" "razor/pkg/bindings" + "razor/rpc" "razor/utils/mocks" "reflect" "regexp" @@ -26,9 +27,19 @@ import ( "github.com/stretchr/testify/mock" ) +var rpcManager = rpc.RPCManager{ + BestEndpoint: &rpc.RPCEndpoint{ + Client: ðclient.Client{}, + }, +} + +var rpcParameters = rpc.RPCParameters{ + Ctx: context.Background(), + RPCManager: &rpcManager, +} + func TestAggregate(t *testing.T) { var ( - client *ethclient.Client previousEpoch uint32 fileInfo fs.FileInfo ) @@ -200,14 +211,14 @@ func TestAggregate(t *testing.T) { utils := StartRazor(optionsPackageStruct) utilsMock.On("GetDataToCommitFromJobs", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.dataToCommit, tt.args.weight, tt.args.dataToCommitErr) - utilsMock.On("FetchPreviousValue", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.prevCommitmentData, tt.args.prevCommitmentDataErr) + utilsMock.On("FetchPreviousValue", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.prevCommitmentData, tt.args.prevCommitmentDataErr) pathUtilsMock.On("GetJobFilePath").Return(tt.args.assetFilePath, tt.args.assetFilePathErr) osUtilsMock.On("Stat", mock.Anything).Return(fileInfo, tt.args.statErr) osUtilsMock.On("Open", mock.Anything).Return(tt.args.jsonFile, tt.args.jsonFileErr) ioMock.On("ReadAll", mock.Anything).Return(tt.args.fileData, tt.args.fileDataErr) - utilsMock.On("HandleOfficialJobsFromJSONFile", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.overrrideJobs, tt.args.overrideJobIds) + utilsMock.On("HandleOfficialJobsFromJSONFile", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.overrrideJobs, tt.args.overrideJobIds) - got, err := utils.Aggregate(context.Background(), client, previousEpoch, tt.args.collection, commitParams) + got, err := utils.Aggregate(rpcParameters, previousEpoch, tt.args.collection, commitParams) if (err != nil) != tt.wantErr { t.Errorf("Aggregate() error = %v, wantErr %v", err, tt.wantErr) @@ -221,7 +232,6 @@ func TestAggregate(t *testing.T) { } func TestGetActiveCollectionIds(t *testing.T) { - var client *ethclient.Client var callOpts bind.CallOpts type args struct { @@ -268,7 +278,7 @@ func TestGetActiveCollectionIds(t *testing.T) { assetManagerMock.On("GetActiveCollections", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.activeAssetIds, tt.args.activeAssetIdsErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetActiveCollectionIds(context.Background(), client) + got, err := utils.GetActiveCollectionIds(rpcParameters) if (err != nil) != tt.wantErr { t.Errorf("GetActiveCollections() error = %v, wantErr %v", err, tt.wantErr) return @@ -348,7 +358,6 @@ func TestGetActiveCollection(t *testing.T) { } func TestGetActiveJob(t *testing.T) { - var client *ethclient.Client var callOpts bind.CallOpts var jobId uint16 @@ -401,7 +410,7 @@ func TestGetActiveJob(t *testing.T) { assetManagerMock.On("Jobs", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint16")).Return(tt.args.job, tt.args.jobErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetActiveJob(context.Background(), client, jobId) + got, err := utils.GetActiveJob(rpcParameters, jobId) if (err != nil) != tt.wantErr { t.Errorf("GetActiveJob() error = %v, wantErr %v", err, tt.wantErr) return @@ -414,7 +423,6 @@ func TestGetActiveJob(t *testing.T) { } func TestGetCollection(t *testing.T) { - var client *ethclient.Client var callOpts bind.CallOpts var collectionId uint16 @@ -462,7 +470,7 @@ func TestGetCollection(t *testing.T) { assetManagerMock.On("GetCollection", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint16")).Return(tt.args.asset, tt.args.assetErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetCollection(context.Background(), client, collectionId) + got, err := utils.GetCollection(rpcParameters, collectionId) if (err != nil) != tt.wantErr { t.Errorf("GetCollection() error = %v, wantErr %v", err, tt.wantErr) return @@ -475,8 +483,6 @@ func TestGetCollection(t *testing.T) { } func TestGetAllCollections(t *testing.T) { - var client *ethclient.Client - collectionListArray := []bindings.StructsCollection{ { Active: true, @@ -544,10 +550,10 @@ func TestGetAllCollections(t *testing.T) { } utils := StartRazor(optionsPackageStruct) - utilsMock.On("GetNumCollections", mock.Anything, mock.Anything).Return(tt.args.numAssets, tt.args.numAssetsErr) - assetMock.On("GetCollection", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint16")).Return(tt.args.collection, tt.args.collectionErr) + utilsMock.On("GetNumCollections", mock.Anything).Return(tt.args.numAssets, tt.args.numAssetsErr) + utilsMock.On("GetCollection", mock.Anything, mock.AnythingOfType("uint16")).Return(tt.args.collection, tt.args.collectionErr) - got, err := utils.GetAllCollections(context.Background(), client) + got, err := utils.GetAllCollections(rpcParameters) if (err != nil) != tt.wantErr { t.Errorf("GetAllCollections() error = %v, wantErr %v", err, tt.wantErr) return @@ -803,8 +809,6 @@ func TestGetDataToCommitFromJob(t *testing.T) { } func TestGetJobs(t *testing.T) { - var client *ethclient.Client - jobsArray := []bindings.StructsJob{ {Id: 1, SelectorType: 1, Weight: 100, Power: 2, Name: "ethusd_gemini", Selector: "last", @@ -813,10 +817,9 @@ func TestGetJobs(t *testing.T) { } type args struct { - numJobs uint16 - numJobsErr error - assetType uint8 - //assetTypeErr error + numJobs uint16 + numJobsErr error + assetType uint8 activeJob bindings.StructsJob activeJobErr error } @@ -868,10 +871,10 @@ func TestGetJobs(t *testing.T) { } utils := StartRazor(optionsPackageStruct) - assetMock.On("GetNumJobs", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.numJobs, tt.args.numJobsErr) - utilsMock.On("GetActiveJob", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.activeJob, tt.args.activeJobErr) + utilsMock.On("GetNumJobs", mock.Anything).Return(tt.args.numJobs, tt.args.numJobsErr) + utilsMock.On("GetActiveJob", mock.Anything, mock.Anything).Return(tt.args.activeJob, tt.args.activeJobErr) - got, err := utils.GetJobs(context.Background(), client) + got, err := utils.GetJobs(rpcParameters) if (err != nil) != tt.wantErr { t.Errorf("GetJobs() error = %v, wantErr %v", err, tt.wantErr) return @@ -884,7 +887,6 @@ func TestGetJobs(t *testing.T) { } func TestGetNumActiveCollections(t *testing.T) { - var client *ethclient.Client var callOpts bind.CallOpts type args struct { @@ -931,7 +933,7 @@ func TestGetNumActiveCollections(t *testing.T) { assetManagerMock.On("GetNumActiveCollections", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.numOfActiveAssets, tt.args.numOfActiveAssetsErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetNumActiveCollections(context.Background(), client) + got, err := utils.GetNumActiveCollections(rpcParameters) if (err != nil) != tt.wantErr { t.Errorf("GetNumActiveCollections() error = %v, wantErr %v", err, tt.wantErr) return @@ -944,7 +946,6 @@ func TestGetNumActiveCollections(t *testing.T) { } func TestGetNumCollections(t *testing.T) { - var client *ethclient.Client var callOpts bind.CallOpts type args struct { @@ -991,7 +992,7 @@ func TestGetNumCollections(t *testing.T) { assetManagerMock.On("GetNumCollections", mock.Anything, mock.Anything).Return(tt.args.numOfAssets, tt.args.numOfAssetsErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetNumCollections(context.Background(), client) + got, err := utils.GetNumCollections(rpcParameters) if (err != nil) != tt.wantErr { t.Errorf("GetNumCollections() error = %v, wantErr %v", err, tt.wantErr) return @@ -1115,7 +1116,6 @@ func TestConvertCustomJobToStructJob(t *testing.T) { } func TestHandleOfficialJobsFromJSONFile(t *testing.T) { - var client *ethclient.Client ethCollection := bindings.StructsCollection{ Active: true, Id: 7, Power: 2, AggregationMethod: 2, JobIDs: []uint16{1}, Name: "ethCollection", @@ -1226,7 +1226,7 @@ func TestHandleOfficialJobsFromJSONFile(t *testing.T) { utils := &UtilsStruct{} - gotJobs, gotOverrideJobIds := utils.HandleOfficialJobsFromJSONFile(client, tt.args.collection, tt.args.dataString, commitParams) + gotJobs, gotOverrideJobIds := utils.HandleOfficialJobsFromJSONFile(tt.args.collection, tt.args.dataString, commitParams) if !reflect.DeepEqual(gotJobs, tt.want) { t.Errorf("HandleOfficialJobsFromJSONFile() gotJobs = %v, want %v", gotJobs, tt.want) } @@ -1277,7 +1277,6 @@ var jsonDataString = `{ func TestGetAggregatedDataOfCollection(t *testing.T) { var ( - client *ethclient.Client collectionId uint16 epoch uint32 ) @@ -1331,7 +1330,7 @@ func TestGetAggregatedDataOfCollection(t *testing.T) { utilsMock.On("GetActiveCollection", mock.Anything, mock.Anything).Return(tt.args.activeCollection, tt.args.activeCollectionErr) utilsMock.On("Aggregate", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.collectionData, tt.args.aggregationErr) - got, err := utils.GetAggregatedDataOfCollection(context.Background(), client, collectionId, epoch, &types.CommitParams{HttpClient: &http.Client{}}) + got, err := utils.GetAggregatedDataOfCollection(rpcParameters, collectionId, epoch, &types.CommitParams{HttpClient: &http.Client{}}) if (err != nil) != tt.wantErr { t.Errorf("GetAggregatedDataOfCollection() error = %v, wantErr %v", err, tt.wantErr) return @@ -1345,7 +1344,6 @@ func TestGetAggregatedDataOfCollection(t *testing.T) { func TestGetAssignedCollections(t *testing.T) { var ( - client *ethclient.Client numActiveCollections uint16 seed []byte ) @@ -1389,10 +1387,10 @@ func TestGetAssignedCollections(t *testing.T) { } utils := StartRazor(optionsPackageStruct) - utilsMock.On("ToAssign", mock.Anything, mock.Anything).Return(tt.args.toAssign, tt.args.toAssignErr) + utilsMock.On("ToAssign", mock.Anything).Return(tt.args.toAssign, tt.args.toAssignErr) utilsMock.On("Prng", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.assigned) - got, got1, err := utils.GetAssignedCollections(context.Background(), client, numActiveCollections, seed) + got, got1, err := utils.GetAssignedCollections(rpcParameters, numActiveCollections, seed) if (err != nil) != tt.wantErr { t.Errorf("GetAssignedCollections() error = %v, wantErr %v", err, tt.wantErr) return @@ -1408,10 +1406,7 @@ func TestGetAssignedCollections(t *testing.T) { } func TestGetLeafIdOfACollection(t *testing.T) { - var ( - client *ethclient.Client - collectionId uint16 - ) + var collectionId uint16 type args struct { leafId uint16 leafIdErr error @@ -1452,7 +1447,7 @@ func TestGetLeafIdOfACollection(t *testing.T) { assetManagerMock.On("GetLeafIdOfACollection", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.leafId, tt.args.leafIdErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetLeafIdOfACollection(context.Background(), client, collectionId) + got, err := utils.GetLeafIdOfACollection(rpcParameters, collectionId) if (err != nil) != tt.wantErr { t.Errorf("GetLeafIdOfACollection() error = %v, wantErr %v", err, tt.wantErr) return @@ -1465,10 +1460,7 @@ func TestGetLeafIdOfACollection(t *testing.T) { } func TestGetCollectionIdFromIndex(t *testing.T) { - var ( - client *ethclient.Client - medianIndex uint16 - ) + var medianIndex uint16 type args struct { collectionId uint16 collectionIdErr error @@ -1509,7 +1501,7 @@ func TestGetCollectionIdFromIndex(t *testing.T) { assetManagerMock.On("GetCollectionIdFromIndex", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.collectionId, tt.args.collectionIdErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetCollectionIdFromIndex(context.Background(), client, medianIndex) + got, err := utils.GetCollectionIdFromIndex(rpcParameters, medianIndex) if (err != nil) != tt.wantErr { t.Errorf("GetCollectionIdFromIndex() error = %v, wantErr %v", err, tt.wantErr) return @@ -1522,10 +1514,7 @@ func TestGetCollectionIdFromIndex(t *testing.T) { } func TestGetCollectionIdFromLeafId(t *testing.T) { - var ( - client *ethclient.Client - leafId uint16 - ) + var leafId uint16 type args struct { collectionId uint16 collectionIdErr error @@ -1566,7 +1555,7 @@ func TestGetCollectionIdFromLeafId(t *testing.T) { assetManagerMock.On("GetCollectionIdFromLeafId", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.collectionId, tt.args.collectionIdErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetCollectionIdFromLeafId(context.Background(), client, leafId) + got, err := utils.GetCollectionIdFromLeafId(rpcParameters, leafId) if (err != nil) != tt.wantErr { t.Errorf("GetCollectionIdFromLeafId() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/utils/batch.go b/utils/batch.go index a7a5bfdbc..e44ec0450 100644 --- a/utils/batch.go +++ b/utils/batch.go @@ -7,22 +7,22 @@ import ( "github.com/avast/retry-go" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/ethclient" - "github.com/ethereum/go-ethereum/rpc" + RPC "github.com/ethereum/go-ethereum/rpc" "razor/core" + "razor/rpc" ) //Each batch call may require multiple arguments therefore defining args as [][]interface{} // BatchCall performs a batch call to the Ethereum client, using the provided contract ABI, address, method name, and arguments. -func (c ClientStruct) BatchCall(client *ethclient.Client, contractABI *abi.ABI, contractAddress, methodName string, args [][]interface{}) ([][]interface{}, error) { +func (c ClientStruct) BatchCall(rpcParameters rpc.RPCParameters, contractABI *abi.ABI, contractAddress, methodName string, args [][]interface{}) ([][]interface{}, error) { calls, err := ClientInterface.CreateBatchCalls(contractABI, contractAddress, methodName, args) if err != nil { log.Errorf("Error in creating batch calls: %v", err) return nil, err } - err = performBatchCallWithRetry(client, calls) + err = performBatchCallWithRetry(rpcParameters, calls) if err != nil { log.Errorf("Error in performing batch call: %v", err) return nil, err @@ -38,8 +38,8 @@ func (c ClientStruct) BatchCall(client *ethclient.Client, contractABI *abi.ABI, } // CreateBatchCalls creates a slice of rpc.BatchElem, each representing an Ethereum call, using the provided ABI, contract address, method name, and arguments. -func (c ClientStruct) CreateBatchCalls(contractABI *abi.ABI, contractAddress, methodName string, args [][]interface{}) ([]rpc.BatchElem, error) { - var calls []rpc.BatchElem +func (c ClientStruct) CreateBatchCalls(contractABI *abi.ABI, contractAddress, methodName string, args [][]interface{}) ([]RPC.BatchElem, error) { + var calls []RPC.BatchElem for _, arg := range args { data, err := contractABI.Pack(methodName, arg...) @@ -48,7 +48,7 @@ func (c ClientStruct) CreateBatchCalls(contractABI *abi.ABI, contractAddress, me return nil, err } - calls = append(calls, rpc.BatchElem{ + calls = append(calls, RPC.BatchElem{ Method: "eth_call", Args: []interface{}{ map[string]interface{}{ @@ -63,8 +63,13 @@ func (c ClientStruct) CreateBatchCalls(contractABI *abi.ABI, contractAddress, me return calls, nil } -func (c ClientStruct) PerformBatchCall(client *ethclient.Client, calls []rpc.BatchElem) error { - err := client.Client().BatchCallContext(context.Background(), calls) +func (c ClientStruct) PerformBatchCall(rpcParameters rpc.RPCParameters, calls []RPC.BatchElem) error { + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + return err + } + + err = client.Client().BatchCallContext(context.Background(), calls) if err != nil { return err } @@ -72,9 +77,9 @@ func (c ClientStruct) PerformBatchCall(client *ethclient.Client, calls []rpc.Bat } // performBatchCallWithRetry performs the batch call to the Ethereum client with retry logic. -func performBatchCallWithRetry(client *ethclient.Client, calls []rpc.BatchElem) error { +func performBatchCallWithRetry(rpcParameters rpc.RPCParameters, calls []RPC.BatchElem) error { err := retry.Do(func() error { - err := ClientInterface.PerformBatchCall(client, calls) + err := ClientInterface.PerformBatchCall(rpcParameters, calls) if err != nil { log.Errorf("Error in performing batch call, retrying: %v", err) return err @@ -97,7 +102,7 @@ func performBatchCallWithRetry(client *ethclient.Client, calls []rpc.BatchElem) } // processBatchResults processes the results of the batch call, unpacking the data using the provided ABI and method name. -func processBatchResults(contractABI *abi.ABI, methodName string, calls []rpc.BatchElem) ([][]interface{}, error) { +func processBatchResults(contractABI *abi.ABI, methodName string, calls []RPC.BatchElem) ([][]interface{}, error) { var results [][]interface{} for _, call := range calls { diff --git a/utils/batch_test.go b/utils/batch_test.go index 00cdbc40b..cfcd48637 100644 --- a/utils/batch_test.go +++ b/utils/batch_test.go @@ -3,7 +3,6 @@ package utils import ( "errors" "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/ethclient" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "math/big" @@ -16,7 +15,6 @@ import ( func TestBatchCall(t *testing.T) { //Testing Batch call scenario for getting StakeSnapshot - var client *ethclient.Client voteManagerABI, _ := abi.JSON(strings.NewReader(bindings.VoteManagerMetaData.ABI)) stakeManagerABI, _ := abi.JSON(strings.NewReader(bindings.StakeManagerMetaData.ABI)) @@ -185,7 +183,7 @@ func TestBatchCall(t *testing.T) { clientMock.On("PerformBatchCall", mock.Anything, mock.Anything).Return(tt.args.performBatchCallErr) c := ClientStruct{} - gotResults, err := c.BatchCall(client, tt.args.contractABI, tt.args.contractAddress, tt.args.methodName, arguments) + gotResults, err := c.BatchCall(rpcParameters, tt.args.contractABI, tt.args.contractAddress, tt.args.methodName, arguments) if (err != nil) != tt.wantErr { t.Errorf("BatchCall() error = %v, but wantErr bool is %v", err, tt.wantErr) return diff --git a/utils/block.go b/utils/block.go index af86f14c0..4aa739b6d 100644 --- a/utils/block.go +++ b/utils/block.go @@ -1,11 +1,12 @@ package utils import ( - "context" "errors" + "github.com/ethereum/go-ethereum/common" "math/big" Types "razor/core/types" "razor/pkg/bindings" + "razor/rpc" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/ethclient" @@ -15,24 +16,24 @@ func (*UtilsStruct) GetBlockManagerWithOpts(client *ethclient.Client) (*bindings return UtilsInterface.GetBlockManager(client), UtilsInterface.GetOptions() } -func (*UtilsStruct) GetNumberOfProposedBlocks(ctx context.Context, client *ethclient.Client, epoch uint32) (uint8, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, BlockManagerInterface, "GetNumProposedBlocks", client, epoch) +func (*UtilsStruct) GetNumberOfProposedBlocks(rpcParameters rpc.RPCParameters, epoch uint32) (uint8, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, BlockManagerInterface, "GetNumProposedBlocks", epoch) if err != nil { return 0, err } return returnedValues[0].Interface().(uint8), nil } -func (*UtilsStruct) GetProposedBlock(ctx context.Context, client *ethclient.Client, epoch uint32, proposedBlockId uint32) (bindings.StructsBlock, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, BlockManagerInterface, "GetProposedBlock", client, epoch, proposedBlockId) +func (*UtilsStruct) GetProposedBlock(rpcParameters rpc.RPCParameters, epoch uint32, proposedBlockId uint32) (bindings.StructsBlock, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, BlockManagerInterface, "GetProposedBlock", epoch, proposedBlockId) if err != nil { return bindings.StructsBlock{}, err } return returnedValues[0].Interface().(bindings.StructsBlock), nil } -func (*UtilsStruct) FetchPreviousValue(ctx context.Context, client *ethclient.Client, epoch uint32, assetId uint16) (*big.Int, error) { - block, err := UtilsInterface.GetBlock(ctx, client, epoch) +func (*UtilsStruct) FetchPreviousValue(rpcParameters rpc.RPCParameters, epoch uint32, assetId uint16) (*big.Int, error) { + block, err := UtilsInterface.GetBlock(rpcParameters, epoch) if err != nil { return big.NewInt(0), err } @@ -42,24 +43,24 @@ func (*UtilsStruct) FetchPreviousValue(ctx context.Context, client *ethclient.Cl return block.Medians[assetId-1], nil } -func (*UtilsStruct) GetBlock(ctx context.Context, client *ethclient.Client, epoch uint32) (bindings.StructsBlock, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, BlockManagerInterface, "GetBlock", client, epoch) +func (*UtilsStruct) GetBlock(rpcParameters rpc.RPCParameters, epoch uint32) (bindings.StructsBlock, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, BlockManagerInterface, "GetBlock", epoch) if err != nil { return bindings.StructsBlock{}, err } return returnedValues[0].Interface().(bindings.StructsBlock), nil } -func (*UtilsStruct) GetMinStakeAmount(ctx context.Context, client *ethclient.Client) (*big.Int, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, BlockManagerInterface, "MinStake", client) +func (*UtilsStruct) GetMinStakeAmount(rpcParameters rpc.RPCParameters) (*big.Int, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, BlockManagerInterface, "MinStake") if err != nil { return nil, err } return returnedValues[0].Interface().(*big.Int), nil } -func (*UtilsStruct) GetStateBuffer(ctx context.Context, client *ethclient.Client) (uint64, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, BlockManagerInterface, "StateBuffer", client) +func (*UtilsStruct) GetStateBuffer(rpcParameters rpc.RPCParameters) (uint64, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, BlockManagerInterface, "StateBuffer") if err != nil { return 0, err } @@ -67,31 +68,31 @@ func (*UtilsStruct) GetStateBuffer(ctx context.Context, client *ethclient.Client return uint64(stateBufferUint8), nil } -func (*UtilsStruct) GetMaxAltBlocks(ctx context.Context, client *ethclient.Client) (uint8, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, BlockManagerInterface, "MaxAltBlocks", client) +func (*UtilsStruct) GetMaxAltBlocks(rpcParameters rpc.RPCParameters) (uint8, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, BlockManagerInterface, "MaxAltBlocks") if err != nil { return 0, err } return returnedValues[0].Interface().(uint8), nil } -func (*UtilsStruct) GetSortedProposedBlockId(ctx context.Context, client *ethclient.Client, epoch uint32, index *big.Int) (uint32, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, BlockManagerInterface, "SortedProposedBlockIds", client, epoch, index) +func (*UtilsStruct) GetSortedProposedBlockId(rpcParameters rpc.RPCParameters, epoch uint32, index *big.Int) (uint32, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, BlockManagerInterface, "SortedProposedBlockIds", epoch, index) if err != nil { return 0, err } return returnedValues[0].Interface().(uint32), nil } -func (*UtilsStruct) GetSortedProposedBlockIds(ctx context.Context, client *ethclient.Client, epoch uint32) ([]uint32, error) { - numberOfProposedBlocks, err := UtilsInterface.GetNumberOfProposedBlocks(ctx, client, epoch) +func (*UtilsStruct) GetSortedProposedBlockIds(rpcParameters rpc.RPCParameters, epoch uint32) ([]uint32, error) { + numberOfProposedBlocks, err := UtilsInterface.GetNumberOfProposedBlocks(rpcParameters, epoch) if err != nil { log.Error(err) return nil, err } var sortedProposedBlockIds []uint32 for i := 0; i < int(numberOfProposedBlocks); i++ { - id, err := UtilsInterface.GetSortedProposedBlockId(ctx, client, epoch, big.NewInt(int64(i))) + id, err := UtilsInterface.GetSortedProposedBlockId(rpcParameters, epoch, big.NewInt(int64(i))) if err != nil { log.Error(err) return nil, err @@ -101,26 +102,34 @@ func (*UtilsStruct) GetSortedProposedBlockIds(ctx context.Context, client *ethcl return sortedProposedBlockIds, nil } -func (*UtilsStruct) GetBlockIndexToBeConfirmed(ctx context.Context, client *ethclient.Client) (int8, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, BlockManagerInterface, "GetBlockIndexToBeConfirmed", client) +func (*UtilsStruct) GetBlockIndexToBeConfirmed(rpcParameters rpc.RPCParameters) (int8, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, BlockManagerInterface, "GetBlockIndexToBeConfirmed") if err != nil { return 0, err } return returnedValues[0].Interface().(int8), nil } -func (*UtilsStruct) GetEpochLastProposed(ctx context.Context, client *ethclient.Client, stakerId uint32) (uint32, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, BlockManagerInterface, "GetEpochLastProposed", client, stakerId) +func (*UtilsStruct) GetEpochLastProposed(rpcParameters rpc.RPCParameters, stakerId uint32) (uint32, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, BlockManagerInterface, "GetEpochLastProposed", stakerId) if err != nil { return 0, err } return returnedValues[0].Interface().(uint32), nil } -func (*UtilsStruct) GetConfirmedBlocks(ctx context.Context, client *ethclient.Client, epoch uint32) (Types.ConfirmedBlock, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, BlockManagerInterface, "GetConfirmedBlocks", client, epoch) +func (*UtilsStruct) GetConfirmedBlocks(rpcParameters rpc.RPCParameters, epoch uint32) (Types.ConfirmedBlock, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, BlockManagerInterface, "GetConfirmedBlocks", epoch) if err != nil { return Types.ConfirmedBlock{}, err } return returnedValues[0].Interface().(Types.ConfirmedBlock), nil } + +func (*UtilsStruct) Disputes(rpcParameters rpc.RPCParameters, epoch uint32, address common.Address) (Types.DisputesStruct, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, BlockManagerInterface, "Disputes", epoch, address) + if err != nil { + return Types.DisputesStruct{}, err + } + return returnedValues[0].Interface().(Types.DisputesStruct), nil +} diff --git a/utils/block_test.go b/utils/block_test.go index 370dee4c8..53fba59ac 100644 --- a/utils/block_test.go +++ b/utils/block_test.go @@ -1,8 +1,8 @@ package utils import ( - "context" "errors" + "github.com/ethereum/go-ethereum/common" "math/big" "razor/core/types" "razor/pkg/bindings" @@ -17,7 +17,6 @@ import ( ) func TestFetchPreviousValue(t *testing.T) { - var client *ethclient.Client var epoch uint32 type args struct { @@ -68,7 +67,7 @@ func TestFetchPreviousValue(t *testing.T) { utilsMock.On("GetBlock", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.block, tt.args.blockErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.FetchPreviousValue(context.Background(), client, epoch, tt.args.assetId) + got, err := utils.FetchPreviousValue(rpcParameters, epoch, tt.args.assetId) if (err != nil) != tt.wantErr { t.Errorf("FetchPreviousValue() error = %v, wantErr %v", err, tt.wantErr) return @@ -81,7 +80,6 @@ func TestFetchPreviousValue(t *testing.T) { } func TestGetMaxAltBlocks(t *testing.T) { - var client *ethclient.Client var callOpts bind.CallOpts type args struct { @@ -128,7 +126,7 @@ func TestGetMaxAltBlocks(t *testing.T) { blockManagerMock.On("MaxAltBlocks", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.maxAltBlocks, tt.args.maxAltBlocksErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetMaxAltBlocks(context.Background(), client) + got, err := utils.GetMaxAltBlocks(rpcParameters) if (err != nil) != tt.wantErr { t.Errorf("MaxAltBlocks() error = %v, wantErr %v", err, tt.wantErr) return @@ -141,7 +139,6 @@ func TestGetMaxAltBlocks(t *testing.T) { } func TestGetMinStakeAmount(t *testing.T) { - var client *ethclient.Client var callOpts bind.CallOpts type args struct { @@ -188,7 +185,7 @@ func TestGetMinStakeAmount(t *testing.T) { blockManagerMock.On("MinStake", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.minStake, tt.args.minStakeErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetMinStakeAmount(context.Background(), client) + got, err := utils.GetMinStakeAmount(rpcParameters) if (err != nil) != tt.wantErr { t.Errorf("GetMinStakeAmount() error = %v, wantErr %v", err, tt.wantErr) return @@ -201,7 +198,6 @@ func TestGetMinStakeAmount(t *testing.T) { } func TestGetNumberOfProposedBlocks(t *testing.T) { - var client *ethclient.Client var callOpts bind.CallOpts var epoch uint32 @@ -249,7 +245,7 @@ func TestGetNumberOfProposedBlocks(t *testing.T) { blockManagerMock.On("GetNumProposedBlocks", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.numOfProposedBlocks, tt.args.numOfProposedBlocksErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetNumberOfProposedBlocks(context.Background(), client, epoch) + got, err := utils.GetNumberOfProposedBlocks(rpcParameters, epoch) if (err != nil) != tt.wantErr { t.Errorf("GetNumberOfProposedBlocks() error = %v, wantErr %v", err, tt.wantErr) return @@ -262,7 +258,6 @@ func TestGetNumberOfProposedBlocks(t *testing.T) { } func TestGetProposedBlock(t *testing.T) { - var client *ethclient.Client var epoch uint32 var proposedBlockId uint32 var callOpts bind.CallOpts @@ -315,7 +310,7 @@ func TestGetProposedBlock(t *testing.T) { blockManagerMock.On("GetProposedBlock", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint32")).Return(tt.args.block, tt.args.blockErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetProposedBlock(context.Background(), client, epoch, proposedBlockId) + got, err := utils.GetProposedBlock(rpcParameters, epoch, proposedBlockId) if (err != nil) != tt.wantErr { t.Errorf("GetProposedBlock() error = %v, wantErr %v", err, tt.wantErr) return @@ -328,7 +323,6 @@ func TestGetProposedBlock(t *testing.T) { } func TestGetSortedProposedBlockId(t *testing.T) { - var client *ethclient.Client var epoch uint32 var index *big.Int var callOpts bind.CallOpts @@ -377,7 +371,7 @@ func TestGetSortedProposedBlockId(t *testing.T) { blockManagerMock.On("SortedProposedBlockIds", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("*big.Int")).Return(tt.args.sortedProposedBlockId, tt.args.sortedProposedBlockIdErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetSortedProposedBlockId(context.Background(), client, epoch, index) + got, err := utils.GetSortedProposedBlockId(rpcParameters, epoch, index) if (err != nil) != tt.wantErr { t.Errorf("GetSortedProposedBlockId() error = %v, wantErr %v", err, tt.wantErr) return @@ -390,7 +384,6 @@ func TestGetSortedProposedBlockId(t *testing.T) { } func TestGetSortedProposedBlockIds(t *testing.T) { - var client *ethclient.Client var epoch uint32 type args struct { @@ -441,10 +434,10 @@ func TestGetSortedProposedBlockIds(t *testing.T) { } utils := StartRazor(optionsPackageStruct) - utilsMock.On("GetNumberOfProposedBlocks", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.numOfProposedBlocks, tt.args.numOfProposedBlocksErr) + utilsMock.On("GetNumberOfProposedBlocks", mock.Anything, mock.Anything).Return(tt.args.numOfProposedBlocks, tt.args.numOfProposedBlocksErr) utilsMock.On("GetSortedProposedBlockId", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.sortedProposedBlockId, tt.args.sortedProposedBlockIdErr) - got, err := utils.GetSortedProposedBlockIds(context.Background(), client, epoch) + got, err := utils.GetSortedProposedBlockIds(rpcParameters, epoch) if (err != nil) != tt.wantErr { t.Errorf("GetSortedProposedBlockIds() error = %v, wantErr %v", err, tt.wantErr) return @@ -482,10 +475,7 @@ func TestGetBlockManagerWithOpts(t *testing.T) { } func TestGetBlock(t *testing.T) { - var ( - client *ethclient.Client - epoch uint32 - ) + var epoch uint32 type args struct { block bindings.StructsBlock blockErr error @@ -527,7 +517,7 @@ func TestGetBlock(t *testing.T) { blockManagerMock.On("GetBlock", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.block, tt.args.blockErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetBlock(context.Background(), client, epoch) + got, err := utils.GetBlock(rpcParameters, epoch) if (err != nil) != tt.wantErr { t.Errorf("GetBlock() error = %v, wantErr %v", err, tt.wantErr) return @@ -540,7 +530,6 @@ func TestGetBlock(t *testing.T) { } func TestGetBlockIndexToBeConfirmed(t *testing.T) { - var client *ethclient.Client type args struct { blockIndex int8 blockIndexErr error @@ -582,7 +571,7 @@ func TestGetBlockIndexToBeConfirmed(t *testing.T) { blockManagerMock.On("GetBlockIndexToBeConfirmed", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.blockIndex, tt.args.blockIndexErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetBlockIndexToBeConfirmed(context.Background(), client) + got, err := utils.GetBlockIndexToBeConfirmed(rpcParameters) if (err != nil) != tt.wantErr { t.Errorf("GetBlockIndexToBeConfirmed() error = %v, wantErr %v", err, tt.wantErr) return @@ -595,7 +584,6 @@ func TestGetBlockIndexToBeConfirmed(t *testing.T) { } func TestGetStateBuffer(t *testing.T) { - var client *ethclient.Client type args struct { stateBuffer uint8 stateBufferErr error @@ -637,7 +625,7 @@ func TestGetStateBuffer(t *testing.T) { blockManagerMock.On("StateBuffer", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.stateBuffer, tt.args.stateBufferErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetStateBuffer(context.Background(), client) + got, err := utils.GetStateBuffer(rpcParameters) if (err != nil) != tt.wantErr { t.Errorf("GetStateBuffer() error = %v, wantErr %v", err, tt.wantErr) return @@ -650,7 +638,6 @@ func TestGetStateBuffer(t *testing.T) { } func TestGetEpochLastProposed(t *testing.T) { - var client *ethclient.Client var callOpts bind.CallOpts var stakerId uint32 @@ -698,7 +685,7 @@ func TestGetEpochLastProposed(t *testing.T) { blockManagerMock.On("GetEpochLastProposed", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.epochLastProposed, tt.args.epochLastProposedErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetEpochLastProposed(context.Background(), client, stakerId) + got, err := utils.GetEpochLastProposed(rpcParameters, stakerId) if (err != nil) != tt.wantErr { t.Errorf("GetEpochLastProposed() error = %v, wantErr %v", err, tt.wantErr) return @@ -711,7 +698,6 @@ func TestGetEpochLastProposed(t *testing.T) { } func TestGetConfirmedBlocks(t *testing.T) { - var client *ethclient.Client var callOpts bind.CallOpts var epoch uint32 @@ -763,7 +749,7 @@ func TestGetConfirmedBlocks(t *testing.T) { blockManagerMock.On("GetConfirmedBlocks", mock.Anything, mock.Anything).Return(tt.args.confirmedBlock, tt.args.confirmedBlockErr) retryMock.On("RetryAttempts", mock.Anything).Return(retry.Attempts(1)) - got, err := utils.GetConfirmedBlocks(context.Background(), client, epoch) + got, err := utils.GetConfirmedBlocks(rpcParameters, epoch) if (err != nil) != tt.wantErr { t.Errorf("GetConfirmedBlocks() error = %v, wantErr %v", err, tt.wantErr) return @@ -774,3 +760,68 @@ func TestGetConfirmedBlocks(t *testing.T) { }) } } + +func TestDisputes(t *testing.T) { + var callOpts bind.CallOpts + var epoch uint32 + var address common.Address + + type args struct { + disputes types.DisputesStruct + disputesErr error + } + tests := []struct { + name string + args args + want types.DisputesStruct + wantErr bool + }{ + { + name: "Test 1: When Disputes() executes successfully", + args: args{ + disputes: types.DisputesStruct{ + LeafId: 1, + }, + }, + want: types.DisputesStruct{ + LeafId: 1, + }, + wantErr: false, + }, + { + name: "Test 2: When there is an error in getting disputes", + args: args{ + disputesErr: errors.New("disputes error"), + }, + want: types.DisputesStruct{}, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + retryMock := new(mocks.RetryUtils) + utilsMock := new(mocks.Utils) + blockManagerMock := new(mocks.BlockManagerUtils) + + optionsPackageStruct := OptionsPackageStruct{ + RetryInterface: retryMock, + UtilsInterface: utilsMock, + BlockManagerInterface: blockManagerMock, + } + utils := StartRazor(optionsPackageStruct) + + utilsMock.On("GetOptions").Return(callOpts) + blockManagerMock.On("Disputes", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.disputes, tt.args.disputesErr) + retryMock.On("RetryAttempts", mock.Anything).Return(retry.Attempts(1)) + + got, err := utils.Disputes(rpcParameters, epoch, address) + if (err != nil) != tt.wantErr { + t.Errorf("Disputes() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("Disputes() got = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/utils/client_methods.go b/utils/client_methods.go index 9ef339898..7a7b1df4f 100644 --- a/utils/client_methods.go +++ b/utils/client_methods.go @@ -5,54 +5,62 @@ import ( "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethclient" "math/big" + "razor/rpc" ) -func (*ClientStruct) GetNonceAtWithRetry(ctx context.Context, client *ethclient.Client, accountAddress common.Address) (uint64, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, ClientInterface, "NonceAt", client, context.Background(), accountAddress) +func (*ClientStruct) GetNonceAtWithRetry(rpcParameters rpc.RPCParameters, accountAddress common.Address) (uint64, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, ClientInterface, "NonceAt", context.Background(), accountAddress) if err != nil { return 0, err } return returnedValues[0].Interface().(uint64), nil } -func (*ClientStruct) GetLatestBlockWithRetry(ctx context.Context, client *ethclient.Client) (*types.Header, error) { +func (*ClientStruct) GetLatestBlockWithRetry(rpcParameters rpc.RPCParameters) (*types.Header, error) { var blockNumberArgument *big.Int - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, ClientInterface, "HeaderByNumber", client, context.Background(), blockNumberArgument) + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, ClientInterface, "HeaderByNumber", context.Background(), blockNumberArgument) if err != nil { return nil, err } return returnedValues[0].Interface().(*types.Header), nil } -func (*ClientStruct) SuggestGasPriceWithRetry(ctx context.Context, client *ethclient.Client) (*big.Int, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, ClientInterface, "SuggestGasPrice", client, context.Background()) +func (*ClientStruct) GetBlockByNumberWithRetry(rpcParameters rpc.RPCParameters, blockNumber *big.Int) (*types.Header, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, ClientInterface, "HeaderByNumber", context.Background(), blockNumber) + if err != nil { + return nil, err + } + return returnedValues[0].Interface().(*types.Header), nil +} + +func (*ClientStruct) SuggestGasPriceWithRetry(rpcParameters rpc.RPCParameters) (*big.Int, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, ClientInterface, "SuggestGasPrice", context.Background()) if err != nil { return nil, err } return returnedValues[0].Interface().(*big.Int), nil } -func (*ClientStruct) EstimateGasWithRetry(ctx context.Context, client *ethclient.Client, message ethereum.CallMsg) (uint64, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, ClientInterface, "EstimateGas", client, context.Background(), message) +func (*ClientStruct) EstimateGasWithRetry(rpcParameters rpc.RPCParameters, message ethereum.CallMsg) (uint64, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, ClientInterface, "EstimateGas", context.Background(), message) if err != nil { return 0, err } return returnedValues[0].Interface().(uint64), nil } -func (*ClientStruct) FilterLogsWithRetry(ctx context.Context, client *ethclient.Client, query ethereum.FilterQuery) ([]types.Log, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, ClientInterface, "FilterLogs", client, context.Background(), query) +func (*ClientStruct) FilterLogsWithRetry(rpcParameters rpc.RPCParameters, query ethereum.FilterQuery) ([]types.Log, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, ClientInterface, "FilterLogs", context.Background(), query) if err != nil { return nil, err } return returnedValues[0].Interface().([]types.Log), nil } -func (*ClientStruct) BalanceAtWithRetry(ctx context.Context, client *ethclient.Client, account common.Address) (*big.Int, error) { +func (*ClientStruct) BalanceAtWithRetry(rpcParameters rpc.RPCParameters, account common.Address) (*big.Int, error) { var blockNumberArgument *big.Int - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, ClientInterface, "BalanceAt", client, context.Background(), account, blockNumberArgument) + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, ClientInterface, "BalanceAt", context.Background(), account, blockNumberArgument) if err != nil { return nil, err } diff --git a/utils/client_methods_test.go b/utils/client_methods_test.go index 79c7563bd..af59cbb87 100644 --- a/utils/client_methods_test.go +++ b/utils/client_methods_test.go @@ -12,13 +12,10 @@ import ( "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethclient" "github.com/stretchr/testify/mock" ) func TestOptionUtilsStruct_SuggestGasPriceWithRetry(t *testing.T) { - var client *ethclient.Client - type args struct { gasPrice *big.Int gasPriceErr error @@ -62,7 +59,7 @@ func TestOptionUtilsStruct_SuggestGasPriceWithRetry(t *testing.T) { retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) clientUtils := ClientStruct{} - got, err := clientUtils.SuggestGasPriceWithRetry(context.Background(), client) + got, err := clientUtils.SuggestGasPriceWithRetry(rpcParameters) if (err != nil) != tt.wantErr { t.Errorf("SuggestGasPriceWithRetry() error = %v, wantErr %v", err, tt.wantErr) return @@ -75,7 +72,6 @@ func TestOptionUtilsStruct_SuggestGasPriceWithRetry(t *testing.T) { } func TestUtilsStruct_BalanceAtWithRetry(t *testing.T) { - var client *ethclient.Client var account common.Address type args struct { @@ -120,7 +116,7 @@ func TestUtilsStruct_BalanceAtWithRetry(t *testing.T) { retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) clientUtils := ClientStruct{} - got, err := clientUtils.BalanceAtWithRetry(context.Background(), client, account) + got, err := clientUtils.BalanceAtWithRetry(rpcParameters, account) if (err != nil) != tt.wantErr { t.Errorf("BalanceAtWithRetry() error = %v, wantErr %v", err, tt.wantErr) return @@ -133,7 +129,6 @@ func TestUtilsStruct_BalanceAtWithRetry(t *testing.T) { } func TestUtilsStruct_EstimateGasWithRetry(t *testing.T) { - var client *ethclient.Client var message ethereum.CallMsg type args struct { @@ -178,7 +173,7 @@ func TestUtilsStruct_EstimateGasWithRetry(t *testing.T) { retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) clientUtils := ClientStruct{} - got, err := clientUtils.EstimateGasWithRetry(context.Background(), client, message) + got, err := clientUtils.EstimateGasWithRetry(rpcParameters, message) if (err != nil) != tt.wantErr { t.Errorf("EstimateGasWithRetry() error = %v, wantErr %v", err, tt.wantErr) return @@ -191,7 +186,6 @@ func TestUtilsStruct_EstimateGasWithRetry(t *testing.T) { } func TestUtilsStruct_FilterLogsWithRetry(t *testing.T) { - var client *ethclient.Client var query ethereum.FilterQuery type args struct { @@ -235,7 +229,7 @@ func TestUtilsStruct_FilterLogsWithRetry(t *testing.T) { retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) clientUtils := ClientStruct{} - got, err := clientUtils.FilterLogsWithRetry(context.Background(), client, query) + got, err := clientUtils.FilterLogsWithRetry(rpcParameters, query) if (err != nil) != tt.wantErr { t.Errorf("FilterLogsWithRetry() error = %v, wantErr %v", err, tt.wantErr) return @@ -248,8 +242,6 @@ func TestUtilsStruct_FilterLogsWithRetry(t *testing.T) { } func TestUtilsStruct_GetLatestBlockWithRetry(t *testing.T) { - var client *ethclient.Client - type args struct { latestHeader *types.Header latestHeaderErr error @@ -291,7 +283,7 @@ func TestUtilsStruct_GetLatestBlockWithRetry(t *testing.T) { retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) clientUtils := ClientStruct{} - got, err := clientUtils.GetLatestBlockWithRetry(context.Background(), client) + got, err := clientUtils.GetLatestBlockWithRetry(rpcParameters) if (err != nil) != tt.wantErr { t.Errorf("GetLatestBlockWithRetry() error = %v, wantErr %v", err, tt.wantErr) return @@ -304,7 +296,6 @@ func TestUtilsStruct_GetLatestBlockWithRetry(t *testing.T) { } func TestUtilsStruct_GetNonceAtWithRetry(t *testing.T) { - var client *ethclient.Client var accountAddress common.Address type args struct { @@ -348,7 +339,7 @@ func TestUtilsStruct_GetNonceAtWithRetry(t *testing.T) { retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) clientUtils := ClientStruct{} - got, err := clientUtils.GetNonceAtWithRetry(context.Background(), client, accountAddress) + got, err := clientUtils.GetNonceAtWithRetry(rpcParameters, accountAddress) if (err != nil) != tt.wantErr { t.Errorf("GetNonceAtWithRetry() error = %v, wantErr %v", err, tt.wantErr) return @@ -359,3 +350,64 @@ func TestUtilsStruct_GetNonceAtWithRetry(t *testing.T) { }) } } + +func TestClientStruct_GetBlockByNumberWithRetry(t *testing.T) { + var blockNumber *big.Int + + type args struct { + header *types.Header + headerErr error + } + + tests := []struct { + name string + args args + want *types.Header + wantErr bool + }{ + { + name: "Test 1: When GetBlockByNumberWithRetry executes successfully", + args: args{ + header: &types.Header{ + Number: big.NewInt(123), + }, + }, + want: &types.Header{ + Number: big.NewInt(123), + }, + wantErr: false, + }, + { + name: "Test 2: When there is an error in getting block header", + args: args{ + headerErr: errors.New("header error"), + }, + want: nil, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + retryMock := new(mocks.RetryUtils) + clientMock := new(mocks.ClientUtils) + optionsPackageStruct := OptionsPackageStruct{ + RetryInterface: retryMock, + ClientInterface: clientMock, + } + + StartRazor(optionsPackageStruct) + clientMock.On("HeaderByNumber", mock.AnythingOfType("*ethclient.Client"), context.Background(), blockNumber).Return(tt.args.header, tt.args.headerErr) + retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) + + clientUtils := ClientStruct{} + got, err := clientUtils.GetBlockByNumberWithRetry(rpcParameters, blockNumber) + if (err != nil) != tt.wantErr { + t.Errorf("GetBlockByNumberWithRetry() error = %v, wantErr %v", err, tt.wantErr) + return + } + if (got == nil && tt.want != nil) || (got != nil && tt.want == nil) || (got != nil && got.Number.Cmp(tt.want.Number) != 0) { + t.Errorf("GetBlockByNumberWithRetry() got = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/utils/common.go b/utils/common.go index 2f92efeaf..7d7a592a9 100644 --- a/utils/common.go +++ b/utils/common.go @@ -3,7 +3,6 @@ package utils import ( "context" "errors" - Types "github.com/ethereum/go-ethereum/core/types" "math/big" "os" "path/filepath" @@ -11,8 +10,11 @@ import ( "razor/core" "razor/core/types" "razor/logger" + "razor/rpc" "time" + Types "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" solsha3 "github.com/miguelmota/go-solidity-sha3" @@ -28,12 +30,17 @@ func (*UtilsStruct) ConnectToClient(provider string) *ethclient.Client { return client } -func (*UtilsStruct) FetchBalance(client *ethclient.Client, accountAddress string) (*big.Int, error) { +func (*UtilsStruct) FetchBalance(rpcParameters rpc.RPCParameters, accountAddress string) (*big.Int, error) { address := common.HexToAddress(accountAddress) - erc20Contract := UtilsInterface.GetTokenManager(client) - opts := UtilsInterface.GetOptions() + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, CoinInterface, "BalanceOf", address) + if err != nil { + return big.NewInt(0), err + } + return returnedValues[0].Interface().(*big.Int), nil +} - returnedValues, err := InvokeFunctionWithRetryAttempts(context.Background(), CoinInterface, "BalanceOf", erc20Contract, &opts, address) +func (*UtilsStruct) Allowance(rpcParameters rpc.RPCParameters, owner common.Address, spender common.Address) (*big.Int, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, CoinInterface, "Allowance", owner, spender) if err != nil { return big.NewInt(0), err } @@ -50,16 +57,18 @@ func (*UtilsStruct) GetBufferedState(header *Types.Header, stateBuffer uint64, b return int64(state % core.NumberOfStates), nil } -func (*UtilsStruct) CheckTransactionReceipt(client *ethclient.Client, _txHash string) int { +func (*UtilsStruct) CheckTransactionReceipt(rpcParameters rpc.RPCParameters, _txHash string) int { txHash := common.HexToHash(_txHash) - tx, err := ClientInterface.TransactionReceipt(client, context.Background(), txHash) + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, ClientInterface, "TransactionReceipt", rpcParameters.Ctx, txHash) if err != nil { return -1 } - return int(tx.Status) + + txnReceipt := returnedValues[0].Interface().(*Types.Receipt) + return int(txnReceipt.Status) } -func (*UtilsStruct) WaitForBlockCompletion(client *ethclient.Client, hashToRead string) error { +func (*UtilsStruct) WaitForBlockCompletion(rpcParameters rpc.RPCParameters, hashToRead string) error { ctx, cancel := context.WithTimeout(context.Background(), core.BlockCompletionTimeout*time.Second) defer cancel() @@ -70,7 +79,7 @@ func (*UtilsStruct) WaitForBlockCompletion(client *ethclient.Client, hashToRead return errors.New("timeout exceeded for transaction mining") default: log.Debug("Checking if transaction is mined....") - transactionStatus := UtilsInterface.CheckTransactionReceipt(client, hashToRead) + transactionStatus := UtilsInterface.CheckTransactionReceipt(rpcParameters, hashToRead) if transactionStatus == 0 { err := errors.New("transaction mining unsuccessful") @@ -127,8 +136,8 @@ func (*UtilsStruct) IsFlagPassed(name string) bool { return found } -func (*UtilsStruct) CheckEthBalanceIsZero(ctx context.Context, client *ethclient.Client, address string) { - ethBalance, err := ClientInterface.BalanceAtWithRetry(ctx, client, common.HexToAddress(address)) +func (*UtilsStruct) CheckEthBalanceIsZero(rpcParameters rpc.RPCParameters, address string) { + ethBalance, err := ClientInterface.BalanceAtWithRetry(rpcParameters, common.HexToAddress(address)) if err != nil { log.Fatalf("Error in fetching sFUEL balance of the account: %s\n%s", address, err) } @@ -156,15 +165,15 @@ func GetStateName(stateNumber int64) string { return stateName } -func (*UtilsStruct) AssignStakerId(ctx context.Context, flagSet *pflag.FlagSet, client *ethclient.Client, address string) (uint32, error) { +func (*UtilsStruct) AssignStakerId(rpcParameters rpc.RPCParameters, flagSet *pflag.FlagSet, address string) (uint32, error) { if UtilsInterface.IsFlagPassed("stakerId") { return UtilsInterface.GetUint32(flagSet, "stakerId") } - return UtilsInterface.GetStakerId(ctx, client, address) + return UtilsInterface.GetStakerId(rpcParameters, address) } -func (*UtilsStruct) GetEpoch(ctx context.Context, client *ethclient.Client) (uint32, error) { - latestHeader, err := ClientInterface.GetLatestBlockWithRetry(ctx, client) +func (*UtilsStruct) GetEpoch(rpcParameters rpc.RPCParameters) (uint32, error) { + latestHeader, err := ClientInterface.GetLatestBlockWithRetry(rpcParameters) if err != nil { log.Error("Error in fetching block: ", err) return 0, err @@ -173,13 +182,13 @@ func (*UtilsStruct) GetEpoch(ctx context.Context, client *ethclient.Client) (uin return uint32(epoch), nil } -func (*UtilsStruct) CalculateBlockTime(ctx context.Context, client *ethclient.Client) int64 { - latestBlock, err := ClientInterface.GetLatestBlockWithRetry(ctx, client) +func (*UtilsStruct) CalculateBlockTime(rpcParameters rpc.RPCParameters) int64 { + latestBlock, err := ClientInterface.GetLatestBlockWithRetry(rpcParameters) if err != nil { log.Fatalf("Error in fetching latest Block: %s", err) } latestBlockNumber := latestBlock.Number - lastSecondBlock, err := ClientInterface.HeaderByNumber(client, context.Background(), big.NewInt(1).Sub(latestBlockNumber, big.NewInt(1))) + lastSecondBlock, err := ClientInterface.GetBlockByNumberWithRetry(rpcParameters, big.NewInt(1).Sub(latestBlockNumber, big.NewInt(1))) if err != nil { log.Fatalf("Error in fetching last second Block: %s", err) } @@ -206,8 +215,8 @@ func (*UtilsStruct) Prng(max uint32, prngHashes []byte) *big.Int { return sum.Mod(sum, maxBigInt) } -func (*UtilsStruct) EstimateBlockNumberAtEpochBeginning(client *ethclient.Client, currentBlockNumber *big.Int) (*big.Int, error) { - block, err := ClientInterface.HeaderByNumber(client, context.Background(), currentBlockNumber) +func (*UtilsStruct) EstimateBlockNumberAtEpochBeginning(rpcParameters rpc.RPCParameters, currentBlockNumber *big.Int) (*big.Int, error) { + block, err := ClientInterface.GetBlockByNumberWithRetry(rpcParameters, currentBlockNumber) if err != nil { log.Error("Error in fetching block: ", err) return nil, err @@ -215,7 +224,7 @@ func (*UtilsStruct) EstimateBlockNumberAtEpochBeginning(client *ethclient.Client currentEpoch := block.Time / core.EpochLength previousBlockNumber := block.Number.Uint64() - core.StateLength - previousBlock, err := ClientInterface.HeaderByNumber(client, context.Background(), big.NewInt(int64(previousBlockNumber))) + previousBlock, err := ClientInterface.GetBlockByNumberWithRetry(rpcParameters, big.NewInt(int64(previousBlockNumber))) if err != nil { log.Error("Err in fetching Previous block: ", err) return nil, err @@ -224,7 +233,7 @@ func (*UtilsStruct) EstimateBlockNumberAtEpochBeginning(client *ethclient.Client previousBlockAssumedTimestamp := block.Time - core.EpochLength previousEpoch := previousBlockActualTimestamp / core.EpochLength if previousBlockActualTimestamp > previousBlockAssumedTimestamp && previousEpoch != currentEpoch-1 { - return UtilsInterface.EstimateBlockNumberAtEpochBeginning(client, big.NewInt(int64(previousBlockNumber))) + return UtilsInterface.EstimateBlockNumberAtEpochBeginning(rpcParameters, big.NewInt(int64(previousBlockNumber))) } return big.NewInt(int64(previousBlockNumber)), nil diff --git a/utils/common_test.go b/utils/common_test.go index 3cc05fd02..8aef3d599 100644 --- a/utils/common_test.go +++ b/utils/common_test.go @@ -1,7 +1,6 @@ package utils import ( - "context" "errors" "math/big" "os" @@ -13,7 +12,6 @@ import ( "testing" "github.com/avast/retry-go" - "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/pflag" @@ -44,8 +42,6 @@ func TestCheckError(t *testing.T) { } func TestCalculateBlockTime(t *testing.T) { - var client *ethclient.Client - type args struct { latestBlock *types.Header latestBlockErr error @@ -100,9 +96,9 @@ func TestCalculateBlockTime(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -113,12 +109,12 @@ func TestCalculateBlockTime(t *testing.T) { } utils := StartRazor(optionsPackageStruct) - clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything, mock.Anything).Return(tt.args.latestBlock, tt.args.latestBlockErr) - clientUtilsMock.On("HeaderByNumber", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.lastSecondBlock, tt.args.lastSecondBlockErr) + clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything).Return(tt.args.latestBlock, tt.args.latestBlockErr) + clientUtilsMock.On("GetBlockByNumberWithRetry", mock.Anything, mock.Anything).Return(tt.args.lastSecondBlock, tt.args.lastSecondBlockErr) fatal = false - utils.CalculateBlockTime(context.Background(), client) + utils.CalculateBlockTime(rpcParameters) if fatal != tt.expectedFatal { t.Error("The CalculateBlockTime function didn't execute as expected") } @@ -127,7 +123,6 @@ func TestCalculateBlockTime(t *testing.T) { } func TestCheckEthBalanceIsZero(t *testing.T) { - var client *ethclient.Client var address string type args struct { @@ -163,9 +158,9 @@ func TestCheckEthBalanceIsZero(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -176,11 +171,11 @@ func TestCheckEthBalanceIsZero(t *testing.T) { } utils := StartRazor(optionsPackageStruct) - clientMock.On("BalanceAtWithRetry", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.ethBalance, tt.args.ethBalanceErr) + clientMock.On("BalanceAtWithRetry", mock.Anything, mock.Anything).Return(tt.args.ethBalance, tt.args.ethBalanceErr) fatal = false - utils.CheckEthBalanceIsZero(context.Background(), client, address) + utils.CheckEthBalanceIsZero(rpcParameters, address) if fatal != tt.expectedFatal { t.Error("The CheckEthBalanceIsZero function didn't execute as expected") } @@ -189,7 +184,6 @@ func TestCheckEthBalanceIsZero(t *testing.T) { } func TestCheckTransactionReceipt(t *testing.T) { - var client *ethclient.Client var txHash string type args struct { @@ -220,24 +214,27 @@ func TestCheckTransactionReceipt(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { clientMock := new(mocks.ClientUtils) + retryMock := new(mocks.RetryUtils) optionsPackageStruct := OptionsPackageStruct{ ClientInterface: clientMock, + RetryInterface: retryMock, } utils := StartRazor(optionsPackageStruct) - clientMock.On("TransactionReceipt", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.tx, tt.args.txErr) + clientMock.On("TransactionReceipt", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.tx, tt.args.txErr) + retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) fatal = false - utils.CheckTransactionReceipt(client, txHash) + utils.CheckTransactionReceipt(rpcParameters, txHash) if fatal != tt.expectedFatal { t.Error("The CheckTransactionReceipt function didn't execute as expected") } @@ -272,9 +269,9 @@ func TestConnectToClient(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -298,9 +295,7 @@ func TestConnectToClient(t *testing.T) { } func TestFetchBalance(t *testing.T) { - var client *ethclient.Client var accountAddress string - var callOpts bind.CallOpts type args struct { erc20Contract *bindings.RAZOR @@ -345,12 +340,10 @@ func TestFetchBalance(t *testing.T) { } utils := StartRazor(optionsPackageStruct) - utilsMock.On("GetTokenManager", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.erc20Contract) - utilsMock.On("GetOptions").Return(callOpts) erc20Mock.On("BalanceOf", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.balance, tt.args.balanceErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.FetchBalance(client, accountAddress) + got, err := utils.FetchBalance(rpcParameters, accountAddress) if (err != nil) != tt.wantErr { t.Errorf("FetchBalance() error = %v, wantErr %v", err, tt.wantErr) return @@ -430,8 +423,6 @@ func TestGetBufferedState(t *testing.T) { } func TestGetEpoch(t *testing.T) { - var client *ethclient.Client - type args struct { latestHeader *types.Header latestHeaderErr error @@ -473,9 +464,9 @@ func TestGetEpoch(t *testing.T) { } utils := StartRazor(optionsPackageStruct) - clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything, mock.Anything).Return(tt.args.latestHeader, tt.args.latestHeaderErr) + clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything).Return(tt.args.latestHeader, tt.args.latestHeaderErr) - got, err := utils.GetEpoch(context.Background(), client) + got, err := utils.GetEpoch(rpcParameters) if (err != nil) != tt.wantErr { t.Errorf("GetEpoch() error = %v, wantErr %v", err, tt.wantErr) return @@ -549,7 +540,6 @@ func TestGetStateName(t *testing.T) { } func TestWaitForBlockCompletion(t *testing.T) { - var client *ethclient.Client var hashToRead string type args struct { @@ -593,17 +583,17 @@ func TestWaitForBlockCompletion(t *testing.T) { } utils := StartRazor(optionsPackageStruct) - utilsMock.On("CheckTransactionReceipt", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.transactionStatus) + utilsMock.On("CheckTransactionReceipt", mock.Anything, mock.Anything).Return(tt.args.transactionStatus) timeMock.On("Sleep", mock.Anything).Return() - gotErr := utils.WaitForBlockCompletion(client, hashToRead) + gotErr := utils.WaitForBlockCompletion(rpcParameters, hashToRead) if gotErr == nil || tt.want == nil { if gotErr != tt.want { - t.Errorf("Error for stake function, got = %v, want %v", gotErr, tt.want) + t.Errorf("Error for WaitForBlockCompletion function, got = %v, want %v", gotErr, tt.want) } } else { if gotErr.Error() != tt.want.Error() { - t.Errorf("Error for stake function, got = %v, want %v", gotErr, tt.want) + t.Errorf("Error for WaitForBlockCompletion function, got = %v, want %v", gotErr, tt.want) } } }) @@ -770,7 +760,6 @@ func TestIsValidateAddress(t *testing.T) { func TestAssignStakerId(t *testing.T) { var flagSet *pflag.FlagSet - var client *ethclient.Client var address string type args struct { @@ -815,9 +804,9 @@ func TestAssignStakerId(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -830,11 +819,11 @@ func TestAssignStakerId(t *testing.T) { utilsMock.On("IsFlagPassed", mock.AnythingOfType("string")).Return(tt.args.flagPassed) utilsMock.On("GetUint32", mock.Anything, mock.AnythingOfType("string")).Return(tt.args.flagSetStakerId, tt.args.flagSetStakerIdErr) - utilsMock.On("GetStakerId", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) + utilsMock.On("GetStakerId", mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) fatal = false - _, err := utils.AssignStakerId(context.Background(), flagSet, client, address) + _, err := utils.AssignStakerId(rpcParameters, flagSet, address) if fatal != tt.expectedFatal { t.Error("The AssignStakerId function didn't execute as expected") } @@ -882,9 +871,9 @@ func TestAssignLogFile(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -1006,10 +995,7 @@ func TestPrng(t *testing.T) { } func TestEstimateBlockNumberAtEpochBeginning(t *testing.T) { - var ( - client *ethclient.Client - currentBlockNumber *big.Int - ) + var currentBlockNumber *big.Int type args struct { block *types.Header blockErr error @@ -1051,9 +1037,9 @@ func TestEstimateBlockNumberAtEpochBeginning(t *testing.T) { } utils := StartRazor(optionsPackageStruct) - clientMock.On("HeaderByNumber", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.block, tt.args.blockErr) - clientMock.On("HeaderByNumber", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.previousBlock, tt.args.previousBlockErr) - got, err := utils.EstimateBlockNumberAtEpochBeginning(client, currentBlockNumber) + clientMock.On("GetBlockByNumberWithRetry", mock.Anything, mock.Anything).Return(tt.args.block, tt.args.blockErr) + clientMock.On("GetBlockByNumberWithRetry", mock.Anything, mock.Anything).Return(tt.args.previousBlock, tt.args.previousBlockErr) + got, err := utils.EstimateBlockNumberAtEpochBeginning(rpcParameters, currentBlockNumber) if (err != nil) != tt.wantErr { t.Errorf("EstimateBlockNumberAtEpochBeginning() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/utils/contract-manager_test.go b/utils/contract-manager_test.go index 08ddc0b3f..da989aa57 100644 --- a/utils/contract-manager_test.go +++ b/utils/contract-manager_test.go @@ -38,9 +38,9 @@ func TestGetStakeManager(t *testing.T) { expectedFatal: true, }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -91,9 +91,9 @@ func TestGetStakedToken(t *testing.T) { expectedFatal: true, }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -143,9 +143,9 @@ func TestGetTokenManager(t *testing.T) { expectedFatal: true, }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -195,9 +195,9 @@ func TestGetAssetManager(t *testing.T) { expectedFatal: true, }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -247,9 +247,9 @@ func TestGetBlockManager(t *testing.T) { expectedFatal: true, }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -299,9 +299,9 @@ func TestGetVoteManager(t *testing.T) { expectedFatal: true, }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/utils/interface.go b/utils/interface.go index f90001279..4f250c2f4 100644 --- a/utils/interface.go +++ b/utils/interface.go @@ -10,9 +10,10 @@ import ( "razor/cache" "razor/core/types" "razor/pkg/bindings" + "razor/rpc" "time" - "github.com/ethereum/go-ethereum/rpc" + RPC "github.com/ethereum/go-ethereum/rpc" "github.com/avast/retry-go" "github.com/ethereum/go-ethereum" @@ -72,67 +73,74 @@ var GasInterface GasUtils type Utils interface { MultiplyFloatAndBigInt(bigIntVal *big.Int, floatingVal float64) *big.Int - GetTxnOpts(ctx context.Context, transactionData types.TransactionOptions) *bind.TransactOpts + GetTxnOpts(rpcParameters rpc.RPCParameters, transactionData types.TransactionOptions) *bind.TransactOpts GetBlockManager(client *ethclient.Client) *bindings.BlockManager GetOptions() bind.CallOpts - GetNumberOfProposedBlocks(ctx context.Context, client *ethclient.Client, epoch uint32) (uint8, error) - GetSortedProposedBlockId(ctx context.Context, client *ethclient.Client, epoch uint32, index *big.Int) (uint32, error) - FetchPreviousValue(ctx context.Context, client *ethclient.Client, epoch uint32, assetId uint16) (*big.Int, error) - GetBlock(ctx context.Context, client *ethclient.Client, epoch uint32) (bindings.StructsBlock, error) - GetMaxAltBlocks(ctx context.Context, client *ethclient.Client) (uint8, error) - GetMinSafeRazor(ctx context.Context, client *ethclient.Client) (*big.Int, error) - GetMinStakeAmount(ctx context.Context, client *ethclient.Client) (*big.Int, error) - GetStateBuffer(ctx context.Context, client *ethclient.Client) (uint64, error) - GetProposedBlock(ctx context.Context, client *ethclient.Client, epoch uint32, proposedBlockId uint32) (bindings.StructsBlock, error) - GetSortedProposedBlockIds(ctx context.Context, client *ethclient.Client, epoch uint32) ([]uint32, error) - GetBlockIndexToBeConfirmed(ctx context.Context, client *ethclient.Client) (int8, error) + GetNumberOfProposedBlocks(rpcParameters rpc.RPCParameters, epoch uint32) (uint8, error) + GetSortedProposedBlockId(rpcParameters rpc.RPCParameters, epoch uint32, index *big.Int) (uint32, error) + FetchPreviousValue(rpcParameters rpc.RPCParameters, epoch uint32, assetId uint16) (*big.Int, error) + GetBlock(rpcParameters rpc.RPCParameters, epoch uint32) (bindings.StructsBlock, error) + GetMaxAltBlocks(rpcParameters rpc.RPCParameters) (uint8, error) + GetMinSafeRazor(rpcParameters rpc.RPCParameters) (*big.Int, error) + GetMinStakeAmount(rpcParameters rpc.RPCParameters) (*big.Int, error) + GetStateBuffer(rpcParameters rpc.RPCParameters) (uint64, error) + GetProposedBlock(rpcParameters rpc.RPCParameters, epoch uint32, proposedBlockId uint32) (bindings.StructsBlock, error) + GetSortedProposedBlockIds(rpcParameters rpc.RPCParameters, epoch uint32) ([]uint32, error) + GetBlockIndexToBeConfirmed(rpcParameters rpc.RPCParameters) (int8, error) GetBlockManagerWithOpts(client *ethclient.Client) (*bindings.BlockManager, bind.CallOpts) GetStakeManager(client *ethclient.Client) *bindings.StakeManager GetStakeManagerWithOpts(client *ethclient.Client) (*bindings.StakeManager, bind.CallOpts) - GetStaker(ctx context.Context, client *ethclient.Client, stakerId uint32) (bindings.StructsStaker, error) - GetStake(ctx context.Context, client *ethclient.Client, stakerId uint32) (*big.Int, error) - GetStakerId(ctx context.Context, client *ethclient.Client, address string) (uint32, error) - GetNumberOfStakers(ctx context.Context, client *ethclient.Client) (uint32, error) - GetLock(ctx context.Context, client *ethclient.Client, address string, stakerId uint32, lockType uint8) (types.Locks, error) - GetWithdrawInitiationPeriod(ctx context.Context, client *ethclient.Client) (uint16, error) - GetMaxCommission(ctx context.Context, client *ethclient.Client) (uint8, error) - GetEpochLimitForUpdateCommission(ctx context.Context, client *ethclient.Client) (uint16, error) + GetStaker(rpcParameters rpc.RPCParameters, stakerId uint32) (bindings.StructsStaker, error) + GetStake(rpcParameters rpc.RPCParameters, stakerId uint32) (*big.Int, error) + GetStakerId(rpcParameters rpc.RPCParameters, address string) (uint32, error) + GetNumberOfStakers(rpcParameters rpc.RPCParameters) (uint32, error) + GetLock(rpcParameters rpc.RPCParameters, address string, stakerId uint32, lockType uint8) (types.Locks, error) + GetWithdrawInitiationPeriod(rpcParameters rpc.RPCParameters) (uint16, error) + GetMaxCommission(rpcParameters rpc.RPCParameters) (uint8, error) + GetEpochLimitForUpdateCommission(rpcParameters rpc.RPCParameters) (uint16, error) + StakerInfo(rpcParameters rpc.RPCParameters, stakerId uint32) (types.Staker, error) + GetMaturity(rpcParameters rpc.RPCParameters, age uint32) (uint16, error) + GetBountyLock(rpcParameters rpc.RPCParameters, bountyId uint32) (types.BountyLock, error) GetVoteManagerWithOpts(client *ethclient.Client) (*bindings.VoteManager, bind.CallOpts) - GetCommitment(ctx context.Context, client *ethclient.Client, address string) (types.Commitment, error) - GetVoteValue(ctx context.Context, client *ethclient.Client, epoch uint32, stakerId uint32, medianIndex uint16) (*big.Int, error) - GetInfluenceSnapshot(ctx context.Context, client *ethclient.Client, stakerId uint32, epoch uint32) (*big.Int, error) - GetStakeSnapshot(ctx context.Context, client *ethclient.Client, stakerId uint32, epoch uint32) (*big.Int, error) - GetTotalInfluenceRevealed(ctx context.Context, client *ethclient.Client, epoch uint32, medianIndex uint16) (*big.Int, error) - GetEpochLastCommitted(ctx context.Context, client *ethclient.Client, stakerId uint32) (uint32, error) - GetEpochLastRevealed(ctx context.Context, client *ethclient.Client, stakerId uint32) (uint32, error) + GetCommitment(rpcParameters rpc.RPCParameters, address string) (types.Commitment, error) + GetVoteValue(rpcParameters rpc.RPCParameters, epoch uint32, stakerId uint32, medianIndex uint16) (*big.Int, error) + GetInfluenceSnapshot(rpcParameters rpc.RPCParameters, stakerId uint32, epoch uint32) (*big.Int, error) + GetStakeSnapshot(rpcParameters rpc.RPCParameters, stakerId uint32, epoch uint32) (*big.Int, error) + GetTotalInfluenceRevealed(rpcParameters rpc.RPCParameters, epoch uint32, medianIndex uint16) (*big.Int, error) + GetEpochLastCommitted(rpcParameters rpc.RPCParameters, stakerId uint32) (uint32, error) + GetEpochLastRevealed(rpcParameters rpc.RPCParameters, stakerId uint32) (uint32, error) GetVoteManager(client *ethclient.Client) *bindings.VoteManager GetCollectionManager(client *ethclient.Client) *bindings.CollectionManager GetCollectionManagerWithOpts(client *ethclient.Client) (*bindings.CollectionManager, bind.CallOpts) - GetNumCollections(ctx context.Context, client *ethclient.Client) (uint16, error) - GetActiveJob(ctx context.Context, client *ethclient.Client, jobId uint16) (bindings.StructsJob, error) - GetCollection(ctx context.Context, client *ethclient.Client, collectionId uint16) (bindings.StructsCollection, error) + GetNumCollections(rpcParameters rpc.RPCParameters) (uint16, error) + GetNumJobs(rpcParameters rpc.RPCParameters) (uint16, error) + GetActiveJob(rpcParameters rpc.RPCParameters, jobId uint16) (bindings.StructsJob, error) + GetCollection(rpcParameters rpc.RPCParameters, collectionId uint16) (bindings.StructsCollection, error) GetActiveCollection(collectionsCache *cache.CollectionsCache, collectionId uint16) (bindings.StructsCollection, error) - Aggregate(ctx context.Context, client *ethclient.Client, previousEpoch uint32, collection bindings.StructsCollection, commitParams *types.CommitParams) (*big.Int, error) + Aggregate(rpcParameters rpc.RPCParameters, previousEpoch uint32, collection bindings.StructsCollection, commitParams *types.CommitParams) (*big.Int, error) GetDataToCommitFromJobs(jobs []bindings.StructsJob, commitParams *types.CommitParams) ([]*big.Int, []uint8) GetDataToCommitFromJob(job bindings.StructsJob, commitParams *types.CommitParams) (*big.Int, error) - GetAssignedCollections(ctx context.Context, client *ethclient.Client, numActiveCollections uint16, seed []byte) (map[int]bool, []*big.Int, error) - GetLeafIdOfACollection(ctx context.Context, client *ethclient.Client, collectionId uint16) (uint16, error) - GetCollectionIdFromIndex(ctx context.Context, client *ethclient.Client, medianIndex uint16) (uint16, error) - GetCollectionIdFromLeafId(ctx context.Context, client *ethclient.Client, leafId uint16) (uint16, error) - GetNumActiveCollections(ctx context.Context, client *ethclient.Client) (uint16, error) - GetAggregatedDataOfCollection(ctx context.Context, client *ethclient.Client, collectionId uint16, epoch uint32, commitParams *types.CommitParams) (*big.Int, error) - GetJobs(ctx context.Context, client *ethclient.Client) ([]bindings.StructsJob, error) - GetAllCollections(ctx context.Context, client *ethclient.Client) ([]bindings.StructsCollection, error) - GetActiveCollectionIds(ctx context.Context, client *ethclient.Client) ([]uint16, error) - HandleOfficialJobsFromJSONFile(client *ethclient.Client, collection bindings.StructsCollection, dataString string, commitParams *types.CommitParams) ([]bindings.StructsJob, []uint16) + GetAssignedCollections(rpcParameters rpc.RPCParameters, numActiveCollections uint16, seed []byte) (map[int]bool, []*big.Int, error) + GetLeafIdOfACollection(rpcParameters rpc.RPCParameters, collectionId uint16) (uint16, error) + GetSaltFromBlockchain(rpcParameters rpc.RPCParameters) ([32]byte, error) + GetCollectionIdFromIndex(rpcParameters rpc.RPCParameters, medianIndex uint16) (uint16, error) + GetCollectionIdFromLeafId(rpcParameters rpc.RPCParameters, leafId uint16) (uint16, error) + GetNumActiveCollections(rpcParameters rpc.RPCParameters) (uint16, error) + GetAggregatedDataOfCollection(rpcParameters rpc.RPCParameters, collectionId uint16, epoch uint32, commitParams *types.CommitParams) (*big.Int, error) + GetJobs(rpcParameters rpc.RPCParameters) ([]bindings.StructsJob, error) + GetAllCollections(rpcParameters rpc.RPCParameters) ([]bindings.StructsCollection, error) + GetActiveCollectionIds(rpcParameters rpc.RPCParameters) ([]uint16, error) + GetActiveStatus(rpcParameters rpc.RPCParameters, id uint16) (bool, error) + HandleOfficialJobsFromJSONFile(collection bindings.StructsCollection, dataString string, commitParams *types.CommitParams) ([]bindings.StructsJob, []uint16) ConnectToClient(provider string) *ethclient.Client - FetchBalance(client *ethclient.Client, accountAddress string) (*big.Int, error) + FetchBalance(rpcParameters rpc.RPCParameters, accountAddress string) (*big.Int, error) + Allowance(rpcParameters rpc.RPCParameters, owner common.Address, spender common.Address) (*big.Int, error) GetBufferedState(header *Types.Header, stateBuffer uint64, buffer int32) (int64, error) - WaitForBlockCompletion(client *ethclient.Client, hashToRead string) error - CheckEthBalanceIsZero(ctx context.Context, client *ethclient.Client, address string) - AssignStakerId(ctx context.Context, flagSet *pflag.FlagSet, client *ethclient.Client, address string) (uint32, error) - GetEpoch(ctx context.Context, client *ethclient.Client) (uint32, error) - CalculateBlockTime(ctx context.Context, client *ethclient.Client) int64 + WaitForBlockCompletion(rpcManager rpc.RPCParameters, hashToRead string) error + CheckEthBalanceIsZero(rpcParameters rpc.RPCParameters, address string) + AssignStakerId(rpcParameters rpc.RPCParameters, flagSet *pflag.FlagSet, address string) (uint32, error) + GetEpoch(rpcParameters rpc.RPCParameters) (uint32, error) + CalculateBlockTime(rpcParameters rpc.RPCParameters) int64 IsFlagPassed(name string) bool GetTokenManager(client *ethclient.Client) *bindings.RAZOR GetStakedToken(client *ethclient.Client, tokenAddress common.Address) *bindings.StakedToken @@ -142,22 +150,23 @@ type Utils interface { WriteDataToJSON(fileName string, data map[string]*types.StructsJob) error DeleteJobFromJSON(fileName string, jobId string) error AddJobToJSON(fileName string, job *types.StructsJob) error - CheckTransactionReceipt(client *ethclient.Client, _txHash string) int + CheckTransactionReceipt(rpcManager rpc.RPCParameters, _txHash string) int CalculateSalt(epoch uint32, medians []*big.Int) [32]byte - ToAssign(ctx context.Context, client *ethclient.Client) (uint16, error) + ToAssign(rpcParameters rpc.RPCParameters) (uint16, error) Prng(max uint32, prngHashes []byte) *big.Int GetRemainingTimeOfCurrentState(block *Types.Header, stateBuffer uint64, bufferPercent int32) (int64, error) SecondsToReadableTime(input int) string - EstimateBlockNumberAtEpochBeginning(client *ethclient.Client, currentBlockNumber *big.Int) (*big.Int, error) - GetEpochLastProposed(ctx context.Context, client *ethclient.Client, stakerId uint32) (uint32, error) - GetConfirmedBlocks(ctx context.Context, client *ethclient.Client, epoch uint32) (types.ConfirmedBlock, error) + EstimateBlockNumberAtEpochBeginning(rpcParameters rpc.RPCParameters, currentBlockNumber *big.Int) (*big.Int, error) + GetEpochLastProposed(rpcParameters rpc.RPCParameters, stakerId uint32) (uint32, error) + GetConfirmedBlocks(rpcParameters rpc.RPCParameters, epoch uint32) (types.ConfirmedBlock, error) + Disputes(rpcParameters rpc.RPCParameters, epoch uint32, address common.Address) (types.DisputesStruct, error) CheckAmountAndBalance(amountInWei *big.Int, balance *big.Int) *big.Int PasswordPrompt() string AssignPassword(flagSet *pflag.FlagSet) string PrivateKeyPrompt() string GetRogueRandomValue(value int) *big.Int GetStakedTokenManagerWithOpts(client *ethclient.Client, tokenAddress common.Address) (*bindings.StakedToken, bind.CallOpts) - GetStakerSRZRBalance(ctx context.Context, client *ethclient.Client, staker bindings.StructsStaker) (*big.Int, error) + GetStakerSRZRBalance(rpcParameters rpc.RPCParameters, staker bindings.StructsStaker) (*big.Int, error) CheckPassword(account types.Account) error AccountManagerForKeystore() (types.AccountManagerInterface, error) } @@ -174,15 +183,16 @@ type ClientUtils interface { SuggestGasPrice(client *ethclient.Client, ctx context.Context) (*big.Int, error) EstimateGas(client *ethclient.Client, ctx context.Context, msg ethereum.CallMsg) (uint64, error) FilterLogs(client *ethclient.Client, ctx context.Context, q ethereum.FilterQuery) ([]Types.Log, error) - SuggestGasPriceWithRetry(ctx context.Context, client *ethclient.Client) (*big.Int, error) - EstimateGasWithRetry(ctx context.Context, client *ethclient.Client, message ethereum.CallMsg) (uint64, error) - GetLatestBlockWithRetry(ctx context.Context, client *ethclient.Client) (*Types.Header, error) - FilterLogsWithRetry(ctx context.Context, client *ethclient.Client, query ethereum.FilterQuery) ([]Types.Log, error) - BalanceAtWithRetry(ctx context.Context, client *ethclient.Client, account common.Address) (*big.Int, error) - GetNonceAtWithRetry(ctx context.Context, client *ethclient.Client, accountAddress common.Address) (uint64, error) - PerformBatchCall(client *ethclient.Client, calls []rpc.BatchElem) error - CreateBatchCalls(contractABI *abi.ABI, contractAddress, methodName string, args [][]interface{}) ([]rpc.BatchElem, error) - BatchCall(client *ethclient.Client, contractABI *abi.ABI, contractAddress, methodName string, args [][]interface{}) ([][]interface{}, error) + SuggestGasPriceWithRetry(rpcParameters rpc.RPCParameters) (*big.Int, error) + EstimateGasWithRetry(rpcParameters rpc.RPCParameters, message ethereum.CallMsg) (uint64, error) + GetLatestBlockWithRetry(rpcParameters rpc.RPCParameters) (*Types.Header, error) + GetBlockByNumberWithRetry(rpcParameters rpc.RPCParameters, blockNumber *big.Int) (*Types.Header, error) + FilterLogsWithRetry(rpcParameters rpc.RPCParameters, query ethereum.FilterQuery) ([]Types.Log, error) + BalanceAtWithRetry(rpcParameters rpc.RPCParameters, account common.Address) (*big.Int, error) + GetNonceAtWithRetry(rpcParameters rpc.RPCParameters, accountAddress common.Address) (uint64, error) + PerformBatchCall(rpcParameters rpc.RPCParameters, calls []RPC.BatchElem) error + CreateBatchCalls(contractABI *abi.ABI, contractAddress, methodName string, args [][]interface{}) ([]RPC.BatchElem, error) + BatchCall(rpcParameters rpc.RPCParameters, contractABI *abi.ABI, contractAddress, methodName string, args [][]interface{}) ([][]interface{}, error) } type TimeUtils interface { @@ -197,7 +207,8 @@ type OSUtils interface { } type CoinUtils interface { - BalanceOf(erc20Contract *bindings.RAZOR, opts *bind.CallOpts, account common.Address) (*big.Int, error) + BalanceOf(client *ethclient.Client, account common.Address) (*big.Int, error) + Allowance(client *ethclient.Client, owner common.Address, spender common.Address) (*big.Int, error) } type MerkleTreeInterface interface { @@ -234,6 +245,7 @@ type BlockManagerUtils interface { GetBlockIndexToBeConfirmed(client *ethclient.Client) (int8, error) GetEpochLastProposed(client *ethclient.Client, stakerId uint32) (uint32, error) GetConfirmedBlocks(client *ethclient.Client, epoch uint32) (types.ConfirmedBlock, error) + Disputes(client *ethclient.Client, epoch uint32, address common.Address) (types.DisputesStruct, error) } type StakeManagerUtils interface { @@ -245,6 +257,9 @@ type StakeManagerUtils interface { MaxCommission(client *ethclient.Client) (uint8, error) EpochLimitForUpdateCommission(client *ethclient.Client) (uint16, error) WithdrawInitiationPeriod(client *ethclient.Client) (uint16, error) + StakerInfo(client *ethclient.Client, stakerId uint32) (types.Staker, error) + GetMaturity(client *ethclient.Client, age uint32) (uint16, error) + GetBountyLock(client *ethclient.Client, bountyId uint32) (types.BountyLock, error) } type AssetManagerUtils interface { @@ -254,6 +269,7 @@ type AssetManagerUtils interface { GetJob(client *ethclient.Client, id uint16) (bindings.StructsJob, error) GetCollection(client *ethclient.Client, id uint16) (bindings.StructsCollection, error) GetActiveCollections(client *ethclient.Client) ([]uint16, error) + GetActiveStatus(client *ethclient.Client, id uint16) (bool, error) Jobs(client *ethclient.Client, id uint16) (bindings.StructsJob, error) GetCollectionIdFromIndex(client *ethclient.Client, index uint16) (uint16, error) GetCollectionIdFromLeafId(client *ethclient.Client, leafId uint16) (uint16, error) @@ -309,9 +325,9 @@ type FileUtils interface { } type GasUtils interface { - GetGasPrice(ctx context.Context, client *ethclient.Client, config types.Configurations) *big.Int - GetGasLimit(ctx context.Context, transactionData types.TransactionOptions, txnOpts *bind.TransactOpts) (uint64, error) - IncreaseGasLimitValue(ctx context.Context, client *ethclient.Client, gasLimit uint64, gasLimitMultiplier float32) (uint64, error) + GetGasPrice(rpcParameters rpc.RPCParameters, config types.Configurations) *big.Int + GetGasLimit(rpcParameters rpc.RPCParameters, transactionData types.TransactionOptions, txnOpts *bind.TransactOpts) (uint64, error) + IncreaseGasLimitValue(rpcParameters rpc.RPCParameters, gasLimit uint64, gasLimitMultiplier float32) (uint64, error) } type UtilsStruct struct{} diff --git a/utils/log.go b/utils/log.go index 8f2dabb3f..5e21da50f 100644 --- a/utils/log.go +++ b/utils/log.go @@ -1,5 +1,7 @@ package utils -import "razor/logger" +import ( + "razor/logger" +) -var log = logger.NewLogger() +var log = logger.GetLogger() diff --git a/utils/math_test.go b/utils/math_test.go index 0772dad53..a3727b0f8 100644 --- a/utils/math_test.go +++ b/utils/math_test.go @@ -258,9 +258,9 @@ func TestCheckAmountAndBalance(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/utils/mocks/abi_utils.go b/utils/mocks/abi_utils.go index fe7e64709..263ca9798 100644 --- a/utils/mocks/abi_utils.go +++ b/utils/mocks/abi_utils.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -23,6 +23,10 @@ func (_m *ABIUtils) Pack(parsedData abi.ABI, name string, args ...interface{}) ( ret := _m.Called(_ca...) var r0 []byte + var r1 error + if rf, ok := ret.Get(0).(func(abi.ABI, string, ...interface{}) ([]byte, error)); ok { + return rf(parsedData, name, args...) + } if rf, ok := ret.Get(0).(func(abi.ABI, string, ...interface{}) []byte); ok { r0 = rf(parsedData, name, args...) } else { @@ -31,7 +35,6 @@ func (_m *ABIUtils) Pack(parsedData abi.ABI, name string, args ...interface{}) ( } } - var r1 error if rf, ok := ret.Get(1).(func(abi.ABI, string, ...interface{}) error); ok { r1 = rf(parsedData, name, args...) } else { @@ -46,13 +49,16 @@ func (_m *ABIUtils) Parse(reader io.Reader) (abi.ABI, error) { ret := _m.Called(reader) var r0 abi.ABI + var r1 error + if rf, ok := ret.Get(0).(func(io.Reader) (abi.ABI, error)); ok { + return rf(reader) + } if rf, ok := ret.Get(0).(func(io.Reader) abi.ABI); ok { r0 = rf(reader) } else { r0 = ret.Get(0).(abi.ABI) } - var r1 error if rf, ok := ret.Get(1).(func(io.Reader) error); ok { r1 = rf(reader) } else { @@ -62,13 +68,12 @@ func (_m *ABIUtils) Parse(reader io.Reader) (abi.ABI, error) { return r0, r1 } -type mockConstructorTestingTNewABIUtils interface { +// NewABIUtils creates a new instance of ABIUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewABIUtils(t interface { mock.TestingT Cleanup(func()) -} - -// NewABIUtils creates a new instance of ABIUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewABIUtils(t mockConstructorTestingTNewABIUtils) *ABIUtils { +}) *ABIUtils { mock := &ABIUtils{} mock.Mock.Test(t) diff --git a/utils/mocks/asset_manager_utils.go b/utils/mocks/asset_manager_utils.go index 09faa71e6..6714520fa 100644 --- a/utils/mocks/asset_manager_utils.go +++ b/utils/mocks/asset_manager_utils.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -19,6 +19,10 @@ func (_m *AssetManagerUtils) GetActiveCollections(client *ethclient.Client) ([]u ret := _m.Called(client) var r0 []uint16 + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client) ([]uint16, error)); ok { + return rf(client) + } if rf, ok := ret.Get(0).(func(*ethclient.Client) []uint16); ok { r0 = rf(client) } else { @@ -27,7 +31,6 @@ func (_m *AssetManagerUtils) GetActiveCollections(client *ethclient.Client) ([]u } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { r1 = rf(client) } else { @@ -37,18 +40,45 @@ func (_m *AssetManagerUtils) GetActiveCollections(client *ethclient.Client) ([]u return r0, r1 } +// GetActiveStatus provides a mock function with given fields: client, id +func (_m *AssetManagerUtils) GetActiveStatus(client *ethclient.Client, id uint16) (bool, error) { + ret := _m.Called(client, id) + + var r0 bool + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, uint16) (bool, error)); ok { + return rf(client, id) + } + if rf, ok := ret.Get(0).(func(*ethclient.Client, uint16) bool); ok { + r0 = rf(client, id) + } else { + r0 = ret.Get(0).(bool) + } + + if rf, ok := ret.Get(1).(func(*ethclient.Client, uint16) error); ok { + r1 = rf(client, id) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // GetCollection provides a mock function with given fields: client, id func (_m *AssetManagerUtils) GetCollection(client *ethclient.Client, id uint16) (bindings.StructsCollection, error) { ret := _m.Called(client, id) var r0 bindings.StructsCollection + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, uint16) (bindings.StructsCollection, error)); ok { + return rf(client, id) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, uint16) bindings.StructsCollection); ok { r0 = rf(client, id) } else { r0 = ret.Get(0).(bindings.StructsCollection) } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, uint16) error); ok { r1 = rf(client, id) } else { @@ -63,13 +93,16 @@ func (_m *AssetManagerUtils) GetCollectionIdFromIndex(client *ethclient.Client, ret := _m.Called(client, index) var r0 uint16 + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, uint16) (uint16, error)); ok { + return rf(client, index) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, uint16) uint16); ok { r0 = rf(client, index) } else { r0 = ret.Get(0).(uint16) } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, uint16) error); ok { r1 = rf(client, index) } else { @@ -84,13 +117,16 @@ func (_m *AssetManagerUtils) GetCollectionIdFromLeafId(client *ethclient.Client, ret := _m.Called(client, leafId) var r0 uint16 + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, uint16) (uint16, error)); ok { + return rf(client, leafId) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, uint16) uint16); ok { r0 = rf(client, leafId) } else { r0 = ret.Get(0).(uint16) } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, uint16) error); ok { r1 = rf(client, leafId) } else { @@ -105,13 +141,16 @@ func (_m *AssetManagerUtils) GetJob(client *ethclient.Client, id uint16) (bindin ret := _m.Called(client, id) var r0 bindings.StructsJob + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, uint16) (bindings.StructsJob, error)); ok { + return rf(client, id) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, uint16) bindings.StructsJob); ok { r0 = rf(client, id) } else { r0 = ret.Get(0).(bindings.StructsJob) } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, uint16) error); ok { r1 = rf(client, id) } else { @@ -126,13 +165,16 @@ func (_m *AssetManagerUtils) GetLeafIdOfACollection(client *ethclient.Client, co ret := _m.Called(client, collectionId) var r0 uint16 + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, uint16) (uint16, error)); ok { + return rf(client, collectionId) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, uint16) uint16); ok { r0 = rf(client, collectionId) } else { r0 = ret.Get(0).(uint16) } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, uint16) error); ok { r1 = rf(client, collectionId) } else { @@ -147,13 +189,16 @@ func (_m *AssetManagerUtils) GetNumActiveCollections(client *ethclient.Client) ( ret := _m.Called(client) var r0 uint16 + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client) (uint16, error)); ok { + return rf(client) + } if rf, ok := ret.Get(0).(func(*ethclient.Client) uint16); ok { r0 = rf(client) } else { r0 = ret.Get(0).(uint16) } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { r1 = rf(client) } else { @@ -168,13 +213,16 @@ func (_m *AssetManagerUtils) GetNumCollections(client *ethclient.Client) (uint16 ret := _m.Called(client) var r0 uint16 + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client) (uint16, error)); ok { + return rf(client) + } if rf, ok := ret.Get(0).(func(*ethclient.Client) uint16); ok { r0 = rf(client) } else { r0 = ret.Get(0).(uint16) } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { r1 = rf(client) } else { @@ -189,13 +237,16 @@ func (_m *AssetManagerUtils) GetNumJobs(client *ethclient.Client) (uint16, error ret := _m.Called(client) var r0 uint16 + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client) (uint16, error)); ok { + return rf(client) + } if rf, ok := ret.Get(0).(func(*ethclient.Client) uint16); ok { r0 = rf(client) } else { r0 = ret.Get(0).(uint16) } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { r1 = rf(client) } else { @@ -210,13 +261,16 @@ func (_m *AssetManagerUtils) Jobs(client *ethclient.Client, id uint16) (bindings ret := _m.Called(client, id) var r0 bindings.StructsJob + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, uint16) (bindings.StructsJob, error)); ok { + return rf(client, id) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, uint16) bindings.StructsJob); ok { r0 = rf(client, id) } else { r0 = ret.Get(0).(bindings.StructsJob) } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, uint16) error); ok { r1 = rf(client, id) } else { @@ -226,13 +280,12 @@ func (_m *AssetManagerUtils) Jobs(client *ethclient.Client, id uint16) (bindings return r0, r1 } -type mockConstructorTestingTNewAssetManagerUtils interface { +// NewAssetManagerUtils creates a new instance of AssetManagerUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAssetManagerUtils(t interface { mock.TestingT Cleanup(func()) -} - -// NewAssetManagerUtils creates a new instance of AssetManagerUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewAssetManagerUtils(t mockConstructorTestingTNewAssetManagerUtils) *AssetManagerUtils { +}) *AssetManagerUtils { mock := &AssetManagerUtils{} mock.Mock.Test(t) diff --git a/utils/mocks/bind_utils.go b/utils/mocks/bind_utils.go index 170527afc..408a36720 100644 --- a/utils/mocks/bind_utils.go +++ b/utils/mocks/bind_utils.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -21,6 +21,10 @@ func (_m *BindUtils) NewKeyedTransactorWithChainID(key *ecdsa.PrivateKey, chainI ret := _m.Called(key, chainID) var r0 *bind.TransactOpts + var r1 error + if rf, ok := ret.Get(0).(func(*ecdsa.PrivateKey, *big.Int) (*bind.TransactOpts, error)); ok { + return rf(key, chainID) + } if rf, ok := ret.Get(0).(func(*ecdsa.PrivateKey, *big.Int) *bind.TransactOpts); ok { r0 = rf(key, chainID) } else { @@ -29,7 +33,6 @@ func (_m *BindUtils) NewKeyedTransactorWithChainID(key *ecdsa.PrivateKey, chainI } } - var r1 error if rf, ok := ret.Get(1).(func(*ecdsa.PrivateKey, *big.Int) error); ok { r1 = rf(key, chainID) } else { @@ -39,13 +42,12 @@ func (_m *BindUtils) NewKeyedTransactorWithChainID(key *ecdsa.PrivateKey, chainI return r0, r1 } -type mockConstructorTestingTNewBindUtils interface { +// NewBindUtils creates a new instance of BindUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBindUtils(t interface { mock.TestingT Cleanup(func()) -} - -// NewBindUtils creates a new instance of BindUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewBindUtils(t mockConstructorTestingTNewBindUtils) *BindUtils { +}) *BindUtils { mock := &BindUtils{} mock.Mock.Test(t) diff --git a/utils/mocks/bindings_utils.go b/utils/mocks/bindings_utils.go index 63e9e0132..bbdfca74d 100644 --- a/utils/mocks/bindings_utils.go +++ b/utils/mocks/bindings_utils.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -21,6 +21,10 @@ func (_m *BindingsUtils) NewBlockManager(address common.Address, client *ethclie ret := _m.Called(address, client) var r0 *bindings.BlockManager + var r1 error + if rf, ok := ret.Get(0).(func(common.Address, *ethclient.Client) (*bindings.BlockManager, error)); ok { + return rf(address, client) + } if rf, ok := ret.Get(0).(func(common.Address, *ethclient.Client) *bindings.BlockManager); ok { r0 = rf(address, client) } else { @@ -29,7 +33,6 @@ func (_m *BindingsUtils) NewBlockManager(address common.Address, client *ethclie } } - var r1 error if rf, ok := ret.Get(1).(func(common.Address, *ethclient.Client) error); ok { r1 = rf(address, client) } else { @@ -44,6 +47,10 @@ func (_m *BindingsUtils) NewCollectionManager(address common.Address, client *et ret := _m.Called(address, client) var r0 *bindings.CollectionManager + var r1 error + if rf, ok := ret.Get(0).(func(common.Address, *ethclient.Client) (*bindings.CollectionManager, error)); ok { + return rf(address, client) + } if rf, ok := ret.Get(0).(func(common.Address, *ethclient.Client) *bindings.CollectionManager); ok { r0 = rf(address, client) } else { @@ -52,7 +59,6 @@ func (_m *BindingsUtils) NewCollectionManager(address common.Address, client *et } } - var r1 error if rf, ok := ret.Get(1).(func(common.Address, *ethclient.Client) error); ok { r1 = rf(address, client) } else { @@ -67,6 +73,10 @@ func (_m *BindingsUtils) NewRAZOR(address common.Address, client *ethclient.Clie ret := _m.Called(address, client) var r0 *bindings.RAZOR + var r1 error + if rf, ok := ret.Get(0).(func(common.Address, *ethclient.Client) (*bindings.RAZOR, error)); ok { + return rf(address, client) + } if rf, ok := ret.Get(0).(func(common.Address, *ethclient.Client) *bindings.RAZOR); ok { r0 = rf(address, client) } else { @@ -75,7 +85,6 @@ func (_m *BindingsUtils) NewRAZOR(address common.Address, client *ethclient.Clie } } - var r1 error if rf, ok := ret.Get(1).(func(common.Address, *ethclient.Client) error); ok { r1 = rf(address, client) } else { @@ -90,6 +99,10 @@ func (_m *BindingsUtils) NewStakeManager(address common.Address, client *ethclie ret := _m.Called(address, client) var r0 *bindings.StakeManager + var r1 error + if rf, ok := ret.Get(0).(func(common.Address, *ethclient.Client) (*bindings.StakeManager, error)); ok { + return rf(address, client) + } if rf, ok := ret.Get(0).(func(common.Address, *ethclient.Client) *bindings.StakeManager); ok { r0 = rf(address, client) } else { @@ -98,7 +111,6 @@ func (_m *BindingsUtils) NewStakeManager(address common.Address, client *ethclie } } - var r1 error if rf, ok := ret.Get(1).(func(common.Address, *ethclient.Client) error); ok { r1 = rf(address, client) } else { @@ -113,6 +125,10 @@ func (_m *BindingsUtils) NewStakedToken(address common.Address, client *ethclien ret := _m.Called(address, client) var r0 *bindings.StakedToken + var r1 error + if rf, ok := ret.Get(0).(func(common.Address, *ethclient.Client) (*bindings.StakedToken, error)); ok { + return rf(address, client) + } if rf, ok := ret.Get(0).(func(common.Address, *ethclient.Client) *bindings.StakedToken); ok { r0 = rf(address, client) } else { @@ -121,7 +137,6 @@ func (_m *BindingsUtils) NewStakedToken(address common.Address, client *ethclien } } - var r1 error if rf, ok := ret.Get(1).(func(common.Address, *ethclient.Client) error); ok { r1 = rf(address, client) } else { @@ -136,6 +151,10 @@ func (_m *BindingsUtils) NewVoteManager(address common.Address, client *ethclien ret := _m.Called(address, client) var r0 *bindings.VoteManager + var r1 error + if rf, ok := ret.Get(0).(func(common.Address, *ethclient.Client) (*bindings.VoteManager, error)); ok { + return rf(address, client) + } if rf, ok := ret.Get(0).(func(common.Address, *ethclient.Client) *bindings.VoteManager); ok { r0 = rf(address, client) } else { @@ -144,7 +163,6 @@ func (_m *BindingsUtils) NewVoteManager(address common.Address, client *ethclien } } - var r1 error if rf, ok := ret.Get(1).(func(common.Address, *ethclient.Client) error); ok { r1 = rf(address, client) } else { @@ -154,13 +172,12 @@ func (_m *BindingsUtils) NewVoteManager(address common.Address, client *ethclien return r0, r1 } -type mockConstructorTestingTNewBindingsUtils interface { +// NewBindingsUtils creates a new instance of BindingsUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewBindingsUtils(t interface { mock.TestingT Cleanup(func()) -} - -// NewBindingsUtils creates a new instance of BindingsUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewBindingsUtils(t mockConstructorTestingTNewBindingsUtils) *BindingsUtils { +}) *BindingsUtils { mock := &BindingsUtils{} mock.Mock.Test(t) diff --git a/utils/mocks/block_manager_utils.go b/utils/mocks/block_manager_utils.go index d61b0c566..50f70386c 100644 --- a/utils/mocks/block_manager_utils.go +++ b/utils/mocks/block_manager_utils.go @@ -6,6 +6,8 @@ import ( big "math/big" bindings "razor/pkg/bindings" + common "github.com/ethereum/go-ethereum/common" + ethclient "github.com/ethereum/go-ethereum/ethclient" mock "github.com/stretchr/testify/mock" @@ -18,6 +20,30 @@ type BlockManagerUtils struct { mock.Mock } +// Disputes provides a mock function with given fields: client, epoch, address +func (_m *BlockManagerUtils) Disputes(client *ethclient.Client, epoch uint32, address common.Address) (types.DisputesStruct, error) { + ret := _m.Called(client, epoch, address) + + var r0 types.DisputesStruct + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32, common.Address) (types.DisputesStruct, error)); ok { + return rf(client, epoch, address) + } + if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32, common.Address) types.DisputesStruct); ok { + r0 = rf(client, epoch, address) + } else { + r0 = ret.Get(0).(types.DisputesStruct) + } + + if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32, common.Address) error); ok { + r1 = rf(client, epoch, address) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // GetBlock provides a mock function with given fields: client, epoch func (_m *BlockManagerUtils) GetBlock(client *ethclient.Client, epoch uint32) (bindings.StructsBlock, error) { ret := _m.Called(client, epoch) diff --git a/utils/mocks/client_utils.go b/utils/mocks/client_utils.go index 819cc74b4..ecde0c240 100644 --- a/utils/mocks/client_utils.go +++ b/utils/mocks/client_utils.go @@ -4,6 +4,7 @@ package mocks import ( big "math/big" + RPC "razor/rpc" abi "github.com/ethereum/go-ethereum/accounts/abi" @@ -53,25 +54,25 @@ func (_m *ClientUtils) BalanceAt(client *ethclient.Client, ctx context.Context, return r0, r1 } -// BalanceAtWithRetry provides a mock function with given fields: ctx, client, account -func (_m *ClientUtils) BalanceAtWithRetry(ctx context.Context, client *ethclient.Client, account common.Address) (*big.Int, error) { - ret := _m.Called(ctx, client, account) +// BalanceAtWithRetry provides a mock function with given fields: rpcParameters, account +func (_m *ClientUtils) BalanceAtWithRetry(rpcParameters RPC.RPCParameters, account common.Address) (*big.Int, error) { + ret := _m.Called(rpcParameters, account) var r0 *big.Int var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, common.Address) (*big.Int, error)); ok { - return rf(ctx, client, account) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, common.Address) (*big.Int, error)); ok { + return rf(rpcParameters, account) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, common.Address) *big.Int); ok { - r0 = rf(ctx, client, account) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, common.Address) *big.Int); ok { + r0 = rf(rpcParameters, account) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, common.Address) error); ok { - r1 = rf(ctx, client, account) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, common.Address) error); ok { + r1 = rf(rpcParameters, account) } else { r1 = ret.Error(1) } @@ -79,25 +80,25 @@ func (_m *ClientUtils) BalanceAtWithRetry(ctx context.Context, client *ethclient return r0, r1 } -// BatchCall provides a mock function with given fields: client, contractABI, contractAddress, methodName, args -func (_m *ClientUtils) BatchCall(client *ethclient.Client, contractABI *abi.ABI, contractAddress string, methodName string, args [][]interface{}) ([][]interface{}, error) { - ret := _m.Called(client, contractABI, contractAddress, methodName, args) +// BatchCall provides a mock function with given fields: rpcParameters, contractABI, contractAddress, methodName, args +func (_m *ClientUtils) BatchCall(rpcParameters RPC.RPCParameters, contractABI *abi.ABI, contractAddress string, methodName string, args [][]interface{}) ([][]interface{}, error) { + ret := _m.Called(rpcParameters, contractABI, contractAddress, methodName, args) var r0 [][]interface{} var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, *abi.ABI, string, string, [][]interface{}) ([][]interface{}, error)); ok { - return rf(client, contractABI, contractAddress, methodName, args) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, *abi.ABI, string, string, [][]interface{}) ([][]interface{}, error)); ok { + return rf(rpcParameters, contractABI, contractAddress, methodName, args) } - if rf, ok := ret.Get(0).(func(*ethclient.Client, *abi.ABI, string, string, [][]interface{}) [][]interface{}); ok { - r0 = rf(client, contractABI, contractAddress, methodName, args) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, *abi.ABI, string, string, [][]interface{}) [][]interface{}); ok { + r0 = rf(rpcParameters, contractABI, contractAddress, methodName, args) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([][]interface{}) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, *abi.ABI, string, string, [][]interface{}) error); ok { - r1 = rf(client, contractABI, contractAddress, methodName, args) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, *abi.ABI, string, string, [][]interface{}) error); ok { + r1 = rf(rpcParameters, contractABI, contractAddress, methodName, args) } else { r1 = ret.Error(1) } @@ -155,23 +156,23 @@ func (_m *ClientUtils) EstimateGas(client *ethclient.Client, ctx context.Context return r0, r1 } -// EstimateGasWithRetry provides a mock function with given fields: ctx, client, message -func (_m *ClientUtils) EstimateGasWithRetry(ctx context.Context, client *ethclient.Client, message ethereum.CallMsg) (uint64, error) { - ret := _m.Called(ctx, client, message) +// EstimateGasWithRetry provides a mock function with given fields: rpcParameters, message +func (_m *ClientUtils) EstimateGasWithRetry(rpcParameters RPC.RPCParameters, message ethereum.CallMsg) (uint64, error) { + ret := _m.Called(rpcParameters, message) var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, ethereum.CallMsg) (uint64, error)); ok { - return rf(ctx, client, message) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, ethereum.CallMsg) (uint64, error)); ok { + return rf(rpcParameters, message) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, ethereum.CallMsg) uint64); ok { - r0 = rf(ctx, client, message) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, ethereum.CallMsg) uint64); ok { + r0 = rf(rpcParameters, message) } else { r0 = ret.Get(0).(uint64) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, ethereum.CallMsg) error); ok { - r1 = rf(ctx, client, message) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, ethereum.CallMsg) error); ok { + r1 = rf(rpcParameters, message) } else { r1 = ret.Error(1) } @@ -205,25 +206,25 @@ func (_m *ClientUtils) FilterLogs(client *ethclient.Client, ctx context.Context, return r0, r1 } -// FilterLogsWithRetry provides a mock function with given fields: ctx, client, query -func (_m *ClientUtils) FilterLogsWithRetry(ctx context.Context, client *ethclient.Client, query ethereum.FilterQuery) ([]types.Log, error) { - ret := _m.Called(ctx, client, query) +// FilterLogsWithRetry provides a mock function with given fields: rpcParameters, query +func (_m *ClientUtils) FilterLogsWithRetry(rpcParameters RPC.RPCParameters, query ethereum.FilterQuery) ([]types.Log, error) { + ret := _m.Called(rpcParameters, query) var r0 []types.Log var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, ethereum.FilterQuery) ([]types.Log, error)); ok { - return rf(ctx, client, query) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, ethereum.FilterQuery) ([]types.Log, error)); ok { + return rf(rpcParameters, query) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, ethereum.FilterQuery) []types.Log); ok { - r0 = rf(ctx, client, query) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, ethereum.FilterQuery) []types.Log); ok { + r0 = rf(rpcParameters, query) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]types.Log) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, ethereum.FilterQuery) error); ok { - r1 = rf(ctx, client, query) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, ethereum.FilterQuery) error); ok { + r1 = rf(rpcParameters, query) } else { r1 = ret.Error(1) } @@ -231,25 +232,25 @@ func (_m *ClientUtils) FilterLogsWithRetry(ctx context.Context, client *ethclien return r0, r1 } -// GetLatestBlockWithRetry provides a mock function with given fields: ctx, client -func (_m *ClientUtils) GetLatestBlockWithRetry(ctx context.Context, client *ethclient.Client) (*types.Header, error) { - ret := _m.Called(ctx, client) +// GetBlockByNumberWithRetry provides a mock function with given fields: rpcParameters, blockNumber +func (_m *ClientUtils) GetBlockByNumberWithRetry(rpcParameters RPC.RPCParameters, blockNumber *big.Int) (*types.Header, error) { + ret := _m.Called(rpcParameters, blockNumber) var r0 *types.Header var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) (*types.Header, error)); ok { - return rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, *big.Int) (*types.Header, error)); ok { + return rf(rpcParameters, blockNumber) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) *types.Header); ok { - r0 = rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, *big.Int) *types.Header); ok { + r0 = rf(rpcParameters, blockNumber) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*types.Header) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { - r1 = rf(ctx, client) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, *big.Int) error); ok { + r1 = rf(rpcParameters, blockNumber) } else { r1 = ret.Error(1) } @@ -257,23 +258,49 @@ func (_m *ClientUtils) GetLatestBlockWithRetry(ctx context.Context, client *ethc return r0, r1 } -// GetNonceAtWithRetry provides a mock function with given fields: ctx, client, accountAddress -func (_m *ClientUtils) GetNonceAtWithRetry(ctx context.Context, client *ethclient.Client, accountAddress common.Address) (uint64, error) { - ret := _m.Called(ctx, client, accountAddress) +// GetLatestBlockWithRetry provides a mock function with given fields: rpcParameters +func (_m *ClientUtils) GetLatestBlockWithRetry(rpcParameters RPC.RPCParameters) (*types.Header, error) { + ret := _m.Called(rpcParameters) + + var r0 *types.Header + var r1 error + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) (*types.Header, error)); ok { + return rf(rpcParameters) + } + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) *types.Header); ok { + r0 = rf(rpcParameters) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*types.Header) + } + } + + if rf, ok := ret.Get(1).(func(RPC.RPCParameters) error); ok { + r1 = rf(rpcParameters) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetNonceAtWithRetry provides a mock function with given fields: rpcParameters, accountAddress +func (_m *ClientUtils) GetNonceAtWithRetry(rpcParameters RPC.RPCParameters, accountAddress common.Address) (uint64, error) { + ret := _m.Called(rpcParameters, accountAddress) var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, common.Address) (uint64, error)); ok { - return rf(ctx, client, accountAddress) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, common.Address) (uint64, error)); ok { + return rf(rpcParameters, accountAddress) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, common.Address) uint64); ok { - r0 = rf(ctx, client, accountAddress) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, common.Address) uint64); ok { + r0 = rf(rpcParameters, accountAddress) } else { r0 = ret.Get(0).(uint64) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, common.Address) error); ok { - r1 = rf(ctx, client, accountAddress) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, common.Address) error); ok { + r1 = rf(rpcParameters, accountAddress) } else { r1 = ret.Error(1) } @@ -331,13 +358,13 @@ func (_m *ClientUtils) NonceAt(client *ethclient.Client, ctx context.Context, ac return r0, r1 } -// PerformBatchCall provides a mock function with given fields: client, calls -func (_m *ClientUtils) PerformBatchCall(client *ethclient.Client, calls []rpc.BatchElem) error { - ret := _m.Called(client, calls) +// PerformBatchCall provides a mock function with given fields: rpcParameters, calls +func (_m *ClientUtils) PerformBatchCall(rpcParameters RPC.RPCParameters, calls []rpc.BatchElem) error { + ret := _m.Called(rpcParameters, calls) var r0 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, []rpc.BatchElem) error); ok { - r0 = rf(client, calls) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, []rpc.BatchElem) error); ok { + r0 = rf(rpcParameters, calls) } else { r0 = ret.Error(0) } @@ -371,25 +398,25 @@ func (_m *ClientUtils) SuggestGasPrice(client *ethclient.Client, ctx context.Con return r0, r1 } -// SuggestGasPriceWithRetry provides a mock function with given fields: ctx, client -func (_m *ClientUtils) SuggestGasPriceWithRetry(ctx context.Context, client *ethclient.Client) (*big.Int, error) { - ret := _m.Called(ctx, client) +// SuggestGasPriceWithRetry provides a mock function with given fields: rpcParameters +func (_m *ClientUtils) SuggestGasPriceWithRetry(rpcParameters RPC.RPCParameters) (*big.Int, error) { + ret := _m.Called(rpcParameters) var r0 *big.Int var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) (*big.Int, error)); ok { - return rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) (*big.Int, error)); ok { + return rf(rpcParameters) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) *big.Int); ok { - r0 = rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) *big.Int); ok { + r0 = rf(rpcParameters) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { - r1 = rf(ctx, client) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters) error); ok { + r1 = rf(rpcParameters) } else { r1 = ret.Error(1) } diff --git a/utils/mocks/coin_utils.go b/utils/mocks/coin_utils.go index b885937b7..08b05174d 100644 --- a/utils/mocks/coin_utils.go +++ b/utils/mocks/coin_utils.go @@ -1,14 +1,12 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks import ( big "math/big" - bindings "razor/pkg/bindings" - - bind "github.com/ethereum/go-ethereum/accounts/abi/bind" common "github.com/ethereum/go-ethereum/common" + ethclient "github.com/ethereum/go-ethereum/ethclient" mock "github.com/stretchr/testify/mock" ) @@ -18,22 +16,25 @@ type CoinUtils struct { mock.Mock } -// BalanceOf provides a mock function with given fields: erc20Contract, opts, account -func (_m *CoinUtils) BalanceOf(erc20Contract *bindings.RAZOR, opts *bind.CallOpts, account common.Address) (*big.Int, error) { - ret := _m.Called(erc20Contract, opts, account) +// Allowance provides a mock function with given fields: client, owner, spender +func (_m *CoinUtils) Allowance(client *ethclient.Client, owner common.Address, spender common.Address) (*big.Int, error) { + ret := _m.Called(client, owner, spender) var r0 *big.Int - if rf, ok := ret.Get(0).(func(*bindings.RAZOR, *bind.CallOpts, common.Address) *big.Int); ok { - r0 = rf(erc20Contract, opts, account) + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, common.Address, common.Address) (*big.Int, error)); ok { + return rf(client, owner, spender) + } + if rf, ok := ret.Get(0).(func(*ethclient.Client, common.Address, common.Address) *big.Int); ok { + r0 = rf(client, owner, spender) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - var r1 error - if rf, ok := ret.Get(1).(func(*bindings.RAZOR, *bind.CallOpts, common.Address) error); ok { - r1 = rf(erc20Contract, opts, account) + if rf, ok := ret.Get(1).(func(*ethclient.Client, common.Address, common.Address) error); ok { + r1 = rf(client, owner, spender) } else { r1 = ret.Error(1) } @@ -41,13 +42,38 @@ func (_m *CoinUtils) BalanceOf(erc20Contract *bindings.RAZOR, opts *bind.CallOpt return r0, r1 } -type mockConstructorTestingTNewCoinUtils interface { - mock.TestingT - Cleanup(func()) +// BalanceOf provides a mock function with given fields: client, account +func (_m *CoinUtils) BalanceOf(client *ethclient.Client, account common.Address) (*big.Int, error) { + ret := _m.Called(client, account) + + var r0 *big.Int + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, common.Address) (*big.Int, error)); ok { + return rf(client, account) + } + if rf, ok := ret.Get(0).(func(*ethclient.Client, common.Address) *big.Int); ok { + r0 = rf(client, account) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*big.Int) + } + } + + if rf, ok := ret.Get(1).(func(*ethclient.Client, common.Address) error); ok { + r1 = rf(client, account) + } else { + r1 = ret.Error(1) + } + + return r0, r1 } // NewCoinUtils creates a new instance of CoinUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewCoinUtils(t mockConstructorTestingTNewCoinUtils) *CoinUtils { +// The first argument is typically a *testing.T value. +func NewCoinUtils(t interface { + mock.TestingT + Cleanup(func()) +}) *CoinUtils { mock := &CoinUtils{} mock.Mock.Test(t) diff --git a/utils/mocks/eth_client_utils.go b/utils/mocks/eth_client_utils.go index 3ca9afc90..d1d0dfb19 100644 --- a/utils/mocks/eth_client_utils.go +++ b/utils/mocks/eth_client_utils.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -17,6 +17,10 @@ func (_m *EthClientUtils) Dial(rawurl string) (*ethclient.Client, error) { ret := _m.Called(rawurl) var r0 *ethclient.Client + var r1 error + if rf, ok := ret.Get(0).(func(string) (*ethclient.Client, error)); ok { + return rf(rawurl) + } if rf, ok := ret.Get(0).(func(string) *ethclient.Client); ok { r0 = rf(rawurl) } else { @@ -25,7 +29,6 @@ func (_m *EthClientUtils) Dial(rawurl string) (*ethclient.Client, error) { } } - var r1 error if rf, ok := ret.Get(1).(func(string) error); ok { r1 = rf(rawurl) } else { @@ -35,13 +38,12 @@ func (_m *EthClientUtils) Dial(rawurl string) (*ethclient.Client, error) { return r0, r1 } -type mockConstructorTestingTNewEthClientUtils interface { +// NewEthClientUtils creates a new instance of EthClientUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEthClientUtils(t interface { mock.TestingT Cleanup(func()) -} - -// NewEthClientUtils creates a new instance of EthClientUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewEthClientUtils(t mockConstructorTestingTNewEthClientUtils) *EthClientUtils { +}) *EthClientUtils { mock := &EthClientUtils{} mock.Mock.Test(t) diff --git a/utils/mocks/flag_set_utils.go b/utils/mocks/flag_set_utils.go index 1887c99aa..796caec4b 100644 --- a/utils/mocks/flag_set_utils.go +++ b/utils/mocks/flag_set_utils.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -17,13 +17,16 @@ func (_m *FlagSetUtils) GetLogFileName(flagSet *pflag.FlagSet) (string, error) { ret := _m.Called(flagSet) var r0 string + var r1 error + if rf, ok := ret.Get(0).(func(*pflag.FlagSet) (string, error)); ok { + return rf(flagSet) + } if rf, ok := ret.Get(0).(func(*pflag.FlagSet) string); ok { r0 = rf(flagSet) } else { r0 = ret.Get(0).(string) } - var r1 error if rf, ok := ret.Get(1).(func(*pflag.FlagSet) error); ok { r1 = rf(flagSet) } else { @@ -33,13 +36,12 @@ func (_m *FlagSetUtils) GetLogFileName(flagSet *pflag.FlagSet) (string, error) { return r0, r1 } -type mockConstructorTestingTNewFlagSetUtils interface { +// NewFlagSetUtils creates a new instance of FlagSetUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewFlagSetUtils(t interface { mock.TestingT Cleanup(func()) -} - -// NewFlagSetUtils creates a new instance of FlagSetUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewFlagSetUtils(t mockConstructorTestingTNewFlagSetUtils) *FlagSetUtils { +}) *FlagSetUtils { mock := &FlagSetUtils{} mock.Mock.Test(t) diff --git a/utils/mocks/gas_utils.go b/utils/mocks/gas_utils.go index b0d357dc5..b3085c7db 100644 --- a/utils/mocks/gas_utils.go +++ b/utils/mocks/gas_utils.go @@ -3,13 +3,10 @@ package mocks import ( - context "context" big "math/big" + RPC "razor/rpc" bind "github.com/ethereum/go-ethereum/accounts/abi/bind" - - ethclient "github.com/ethereum/go-ethereum/ethclient" - mock "github.com/stretchr/testify/mock" types "razor/core/types" @@ -20,23 +17,23 @@ type GasUtils struct { mock.Mock } -// GetGasLimit provides a mock function with given fields: ctx, transactionData, txnOpts -func (_m *GasUtils) GetGasLimit(ctx context.Context, transactionData types.TransactionOptions, txnOpts *bind.TransactOpts) (uint64, error) { - ret := _m.Called(ctx, transactionData, txnOpts) +// GetGasLimit provides a mock function with given fields: rpcParameters, transactionData, txnOpts +func (_m *GasUtils) GetGasLimit(rpcParameters RPC.RPCParameters, transactionData types.TransactionOptions, txnOpts *bind.TransactOpts) (uint64, error) { + ret := _m.Called(rpcParameters, transactionData, txnOpts) var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, types.TransactionOptions, *bind.TransactOpts) (uint64, error)); ok { - return rf(ctx, transactionData, txnOpts) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.TransactionOptions, *bind.TransactOpts) (uint64, error)); ok { + return rf(rpcParameters, transactionData, txnOpts) } - if rf, ok := ret.Get(0).(func(context.Context, types.TransactionOptions, *bind.TransactOpts) uint64); ok { - r0 = rf(ctx, transactionData, txnOpts) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.TransactionOptions, *bind.TransactOpts) uint64); ok { + r0 = rf(rpcParameters, transactionData, txnOpts) } else { r0 = ret.Get(0).(uint64) } - if rf, ok := ret.Get(1).(func(context.Context, types.TransactionOptions, *bind.TransactOpts) error); ok { - r1 = rf(ctx, transactionData, txnOpts) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, types.TransactionOptions, *bind.TransactOpts) error); ok { + r1 = rf(rpcParameters, transactionData, txnOpts) } else { r1 = ret.Error(1) } @@ -44,13 +41,13 @@ func (_m *GasUtils) GetGasLimit(ctx context.Context, transactionData types.Trans return r0, r1 } -// GetGasPrice provides a mock function with given fields: ctx, client, config -func (_m *GasUtils) GetGasPrice(ctx context.Context, client *ethclient.Client, config types.Configurations) *big.Int { - ret := _m.Called(ctx, client, config) +// GetGasPrice provides a mock function with given fields: rpcParameters, config +func (_m *GasUtils) GetGasPrice(rpcParameters RPC.RPCParameters, config types.Configurations) *big.Int { + ret := _m.Called(rpcParameters, config) var r0 *big.Int - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Configurations) *big.Int); ok { - r0 = rf(ctx, client, config) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.Configurations) *big.Int); ok { + r0 = rf(rpcParameters, config) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) @@ -60,23 +57,23 @@ func (_m *GasUtils) GetGasPrice(ctx context.Context, client *ethclient.Client, c return r0 } -// IncreaseGasLimitValue provides a mock function with given fields: ctx, client, gasLimit, gasLimitMultiplier -func (_m *GasUtils) IncreaseGasLimitValue(ctx context.Context, client *ethclient.Client, gasLimit uint64, gasLimitMultiplier float32) (uint64, error) { - ret := _m.Called(ctx, client, gasLimit, gasLimitMultiplier) +// IncreaseGasLimitValue provides a mock function with given fields: rpcParameters, gasLimit, gasLimitMultiplier +func (_m *GasUtils) IncreaseGasLimitValue(rpcParameters RPC.RPCParameters, gasLimit uint64, gasLimitMultiplier float32) (uint64, error) { + ret := _m.Called(rpcParameters, gasLimit, gasLimitMultiplier) var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint64, float32) (uint64, error)); ok { - return rf(ctx, client, gasLimit, gasLimitMultiplier) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint64, float32) (uint64, error)); ok { + return rf(rpcParameters, gasLimit, gasLimitMultiplier) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint64, float32) uint64); ok { - r0 = rf(ctx, client, gasLimit, gasLimitMultiplier) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint64, float32) uint64); ok { + r0 = rf(rpcParameters, gasLimit, gasLimitMultiplier) } else { r0 = ret.Get(0).(uint64) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint64, float32) error); ok { - r1 = rf(ctx, client, gasLimit, gasLimitMultiplier) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint64, float32) error); ok { + r1 = rf(rpcParameters, gasLimit, gasLimitMultiplier) } else { r1 = ret.Error(1) } diff --git a/utils/mocks/io_utils.go b/utils/mocks/io_utils.go index 0515dfe46..53abf8243 100644 --- a/utils/mocks/io_utils.go +++ b/utils/mocks/io_utils.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -18,6 +18,10 @@ func (_m *IOUtils) ReadAll(body io.ReadCloser) ([]byte, error) { ret := _m.Called(body) var r0 []byte + var r1 error + if rf, ok := ret.Get(0).(func(io.ReadCloser) ([]byte, error)); ok { + return rf(body) + } if rf, ok := ret.Get(0).(func(io.ReadCloser) []byte); ok { r0 = rf(body) } else { @@ -26,7 +30,6 @@ func (_m *IOUtils) ReadAll(body io.ReadCloser) ([]byte, error) { } } - var r1 error if rf, ok := ret.Get(1).(func(io.ReadCloser) error); ok { r1 = rf(body) } else { @@ -36,13 +39,12 @@ func (_m *IOUtils) ReadAll(body io.ReadCloser) ([]byte, error) { return r0, r1 } -type mockConstructorTestingTNewIOUtils interface { +// NewIOUtils creates a new instance of IOUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewIOUtils(t interface { mock.TestingT Cleanup(func()) -} - -// NewIOUtils creates a new instance of IOUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewIOUtils(t mockConstructorTestingTNewIOUtils) *IOUtils { +}) *IOUtils { mock := &IOUtils{} mock.Mock.Test(t) diff --git a/utils/mocks/json_utils.go b/utils/mocks/json_utils.go index d679371cf..0ed546611 100644 --- a/utils/mocks/json_utils.go +++ b/utils/mocks/json_utils.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -14,6 +14,10 @@ func (_m *JsonUtils) Marshal(v interface{}) ([]byte, error) { ret := _m.Called(v) var r0 []byte + var r1 error + if rf, ok := ret.Get(0).(func(interface{}) ([]byte, error)); ok { + return rf(v) + } if rf, ok := ret.Get(0).(func(interface{}) []byte); ok { r0 = rf(v) } else { @@ -22,7 +26,6 @@ func (_m *JsonUtils) Marshal(v interface{}) ([]byte, error) { } } - var r1 error if rf, ok := ret.Get(1).(func(interface{}) error); ok { r1 = rf(v) } else { @@ -46,13 +49,12 @@ func (_m *JsonUtils) Unmarshal(data []byte, v interface{}) error { return r0 } -type mockConstructorTestingTNewJsonUtils interface { +// NewJsonUtils creates a new instance of JsonUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewJsonUtils(t interface { mock.TestingT Cleanup(func()) -} - -// NewJsonUtils creates a new instance of JsonUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewJsonUtils(t mockConstructorTestingTNewJsonUtils) *JsonUtils { +}) *JsonUtils { mock := &JsonUtils{} mock.Mock.Test(t) diff --git a/utils/mocks/merkle_tree_interface.go b/utils/mocks/merkle_tree_interface.go index 60b8654f8..04793ec8b 100644 --- a/utils/mocks/merkle_tree_interface.go +++ b/utils/mocks/merkle_tree_interface.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -18,6 +18,10 @@ func (_m *MerkleTreeInterface) CreateMerkle(values []*big.Int) ([][][]byte, erro ret := _m.Called(values) var r0 [][][]byte + var r1 error + if rf, ok := ret.Get(0).(func([]*big.Int) ([][][]byte, error)); ok { + return rf(values) + } if rf, ok := ret.Get(0).(func([]*big.Int) [][][]byte); ok { r0 = rf(values) } else { @@ -26,7 +30,6 @@ func (_m *MerkleTreeInterface) CreateMerkle(values []*big.Int) ([][][]byte, erro } } - var r1 error if rf, ok := ret.Get(1).(func([]*big.Int) error); ok { r1 = rf(values) } else { @@ -41,6 +44,10 @@ func (_m *MerkleTreeInterface) GetMerkleRoot(tree [][][]byte) ([32]byte, error) ret := _m.Called(tree) var r0 [32]byte + var r1 error + if rf, ok := ret.Get(0).(func([][][]byte) ([32]byte, error)); ok { + return rf(tree) + } if rf, ok := ret.Get(0).(func([][][]byte) [32]byte); ok { r0 = rf(tree) } else { @@ -49,7 +56,6 @@ func (_m *MerkleTreeInterface) GetMerkleRoot(tree [][][]byte) ([32]byte, error) } } - var r1 error if rf, ok := ret.Get(1).(func([][][]byte) error); ok { r1 = rf(tree) } else { @@ -75,13 +81,12 @@ func (_m *MerkleTreeInterface) GetProofPath(tree [][][]byte, assetId uint16) [][ return r0 } -type mockConstructorTestingTNewMerkleTreeInterface interface { +// NewMerkleTreeInterface creates a new instance of MerkleTreeInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewMerkleTreeInterface(t interface { mock.TestingT Cleanup(func()) -} - -// NewMerkleTreeInterface creates a new instance of MerkleTreeInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewMerkleTreeInterface(t mockConstructorTestingTNewMerkleTreeInterface) *MerkleTreeInterface { +}) *MerkleTreeInterface { mock := &MerkleTreeInterface{} mock.Mock.Test(t) diff --git a/utils/mocks/os_utils.go b/utils/mocks/os_utils.go index 4d1e4fe49..d9a0da04f 100644 --- a/utils/mocks/os_utils.go +++ b/utils/mocks/os_utils.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -19,6 +19,10 @@ func (_m *OSUtils) Open(name string) (*os.File, error) { ret := _m.Called(name) var r0 *os.File + var r1 error + if rf, ok := ret.Get(0).(func(string) (*os.File, error)); ok { + return rf(name) + } if rf, ok := ret.Get(0).(func(string) *os.File); ok { r0 = rf(name) } else { @@ -27,7 +31,6 @@ func (_m *OSUtils) Open(name string) (*os.File, error) { } } - var r1 error if rf, ok := ret.Get(1).(func(string) error); ok { r1 = rf(name) } else { @@ -42,6 +45,10 @@ func (_m *OSUtils) OpenFile(name string, flag int, perm fs.FileMode) (*os.File, ret := _m.Called(name, flag, perm) var r0 *os.File + var r1 error + if rf, ok := ret.Get(0).(func(string, int, fs.FileMode) (*os.File, error)); ok { + return rf(name, flag, perm) + } if rf, ok := ret.Get(0).(func(string, int, fs.FileMode) *os.File); ok { r0 = rf(name, flag, perm) } else { @@ -50,7 +57,6 @@ func (_m *OSUtils) OpenFile(name string, flag int, perm fs.FileMode) (*os.File, } } - var r1 error if rf, ok := ret.Get(1).(func(string, int, fs.FileMode) error); ok { r1 = rf(name, flag, perm) } else { @@ -65,6 +71,10 @@ func (_m *OSUtils) ReadFile(filename string) ([]byte, error) { ret := _m.Called(filename) var r0 []byte + var r1 error + if rf, ok := ret.Get(0).(func(string) ([]byte, error)); ok { + return rf(filename) + } if rf, ok := ret.Get(0).(func(string) []byte); ok { r0 = rf(filename) } else { @@ -73,7 +83,6 @@ func (_m *OSUtils) ReadFile(filename string) ([]byte, error) { } } - var r1 error if rf, ok := ret.Get(1).(func(string) error); ok { r1 = rf(filename) } else { @@ -97,13 +106,12 @@ func (_m *OSUtils) WriteFile(name string, data []byte, perm fs.FileMode) error { return r0 } -type mockConstructorTestingTNewOSUtils interface { +// NewOSUtils creates a new instance of OSUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewOSUtils(t interface { mock.TestingT Cleanup(func()) -} - -// NewOSUtils creates a new instance of OSUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewOSUtils(t mockConstructorTestingTNewOSUtils) *OSUtils { +}) *OSUtils { mock := &OSUtils{} mock.Mock.Test(t) diff --git a/utils/mocks/path_utils.go b/utils/mocks/path_utils.go index a08d4489d..876a3bcac 100644 --- a/utils/mocks/path_utils.go +++ b/utils/mocks/path_utils.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -14,13 +14,16 @@ func (_m *PathUtils) GetDefaultPath() (string, error) { ret := _m.Called() var r0 string + var r1 error + if rf, ok := ret.Get(0).(func() (string, error)); ok { + return rf() + } if rf, ok := ret.Get(0).(func() string); ok { r0 = rf() } else { r0 = ret.Get(0).(string) } - var r1 error if rf, ok := ret.Get(1).(func() error); ok { r1 = rf() } else { @@ -35,13 +38,16 @@ func (_m *PathUtils) GetJobFilePath() (string, error) { ret := _m.Called() var r0 string + var r1 error + if rf, ok := ret.Get(0).(func() (string, error)); ok { + return rf() + } if rf, ok := ret.Get(0).(func() string); ok { r0 = rf() } else { r0 = ret.Get(0).(string) } - var r1 error if rf, ok := ret.Get(1).(func() error); ok { r1 = rf() } else { @@ -51,13 +57,12 @@ func (_m *PathUtils) GetJobFilePath() (string, error) { return r0, r1 } -type mockConstructorTestingTNewPathUtils interface { +// NewPathUtils creates a new instance of PathUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewPathUtils(t interface { mock.TestingT Cleanup(func()) -} - -// NewPathUtils creates a new instance of PathUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewPathUtils(t mockConstructorTestingTNewPathUtils) *PathUtils { +}) *PathUtils { mock := &PathUtils{} mock.Mock.Test(t) diff --git a/utils/mocks/retry_utils.go b/utils/mocks/retry_utils.go index aa02f7b82..956abb7ac 100644 --- a/utils/mocks/retry_utils.go +++ b/utils/mocks/retry_utils.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -28,13 +28,12 @@ func (_m *RetryUtils) RetryAttempts(numberOfAttempts uint) retry.Option { return r0 } -type mockConstructorTestingTNewRetryUtils interface { +// NewRetryUtils creates a new instance of RetryUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewRetryUtils(t interface { mock.TestingT Cleanup(func()) -} - -// NewRetryUtils creates a new instance of RetryUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewRetryUtils(t mockConstructorTestingTNewRetryUtils) *RetryUtils { +}) *RetryUtils { mock := &RetryUtils{} mock.Mock.Test(t) diff --git a/utils/mocks/stake_manager_utils.go b/utils/mocks/stake_manager_utils.go index 57a42b7e4..ac9530288 100644 --- a/utils/mocks/stake_manager_utils.go +++ b/utils/mocks/stake_manager_utils.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -25,13 +25,16 @@ func (_m *StakeManagerUtils) EpochLimitForUpdateCommission(client *ethclient.Cli ret := _m.Called(client) var r0 uint16 + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client) (uint16, error)); ok { + return rf(client) + } if rf, ok := ret.Get(0).(func(*ethclient.Client) uint16); ok { r0 = rf(client) } else { r0 = ret.Get(0).(uint16) } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { r1 = rf(client) } else { @@ -41,18 +44,69 @@ func (_m *StakeManagerUtils) EpochLimitForUpdateCommission(client *ethclient.Cli return r0, r1 } +// GetBountyLock provides a mock function with given fields: client, bountyId +func (_m *StakeManagerUtils) GetBountyLock(client *ethclient.Client, bountyId uint32) (types.BountyLock, error) { + ret := _m.Called(client, bountyId) + + var r0 types.BountyLock + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32) (types.BountyLock, error)); ok { + return rf(client, bountyId) + } + if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32) types.BountyLock); ok { + r0 = rf(client, bountyId) + } else { + r0 = ret.Get(0).(types.BountyLock) + } + + if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32) error); ok { + r1 = rf(client, bountyId) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetMaturity provides a mock function with given fields: client, age +func (_m *StakeManagerUtils) GetMaturity(client *ethclient.Client, age uint32) (uint16, error) { + ret := _m.Called(client, age) + + var r0 uint16 + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32) (uint16, error)); ok { + return rf(client, age) + } + if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32) uint16); ok { + r0 = rf(client, age) + } else { + r0 = ret.Get(0).(uint16) + } + + if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32) error); ok { + r1 = rf(client, age) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // GetNumStakers provides a mock function with given fields: client func (_m *StakeManagerUtils) GetNumStakers(client *ethclient.Client) (uint32, error) { ret := _m.Called(client) var r0 uint32 + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client) (uint32, error)); ok { + return rf(client) + } if rf, ok := ret.Get(0).(func(*ethclient.Client) uint32); ok { r0 = rf(client) } else { r0 = ret.Get(0).(uint32) } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { r1 = rf(client) } else { @@ -67,13 +121,16 @@ func (_m *StakeManagerUtils) GetStaker(client *ethclient.Client, stakerId uint32 ret := _m.Called(client, stakerId) var r0 bindings.StructsStaker + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32) (bindings.StructsStaker, error)); ok { + return rf(client, stakerId) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32) bindings.StructsStaker); ok { r0 = rf(client, stakerId) } else { r0 = ret.Get(0).(bindings.StructsStaker) } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32) error); ok { r1 = rf(client, stakerId) } else { @@ -88,13 +145,16 @@ func (_m *StakeManagerUtils) GetStakerId(client *ethclient.Client, address commo ret := _m.Called(client, address) var r0 uint32 + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, common.Address) (uint32, error)); ok { + return rf(client, address) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, common.Address) uint32); ok { r0 = rf(client, address) } else { r0 = ret.Get(0).(uint32) } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, common.Address) error); ok { r1 = rf(client, address) } else { @@ -109,13 +169,16 @@ func (_m *StakeManagerUtils) Locks(client *ethclient.Client, address common.Addr ret := _m.Called(client, address, address1, lockType) var r0 types.Locks + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, common.Address, common.Address, uint8) (types.Locks, error)); ok { + return rf(client, address, address1, lockType) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, common.Address, common.Address, uint8) types.Locks); ok { r0 = rf(client, address, address1, lockType) } else { r0 = ret.Get(0).(types.Locks) } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, common.Address, common.Address, uint8) error); ok { r1 = rf(client, address, address1, lockType) } else { @@ -130,13 +193,16 @@ func (_m *StakeManagerUtils) MaxCommission(client *ethclient.Client) (uint8, err ret := _m.Called(client) var r0 uint8 + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client) (uint8, error)); ok { + return rf(client) + } if rf, ok := ret.Get(0).(func(*ethclient.Client) uint8); ok { r0 = rf(client) } else { r0 = ret.Get(0).(uint8) } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { r1 = rf(client) } else { @@ -151,6 +217,10 @@ func (_m *StakeManagerUtils) MinSafeRazor(client *ethclient.Client) (*big.Int, e ret := _m.Called(client) var r0 *big.Int + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client) (*big.Int, error)); ok { + return rf(client) + } if rf, ok := ret.Get(0).(func(*ethclient.Client) *big.Int); ok { r0 = rf(client) } else { @@ -159,7 +229,6 @@ func (_m *StakeManagerUtils) MinSafeRazor(client *ethclient.Client) (*big.Int, e } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { r1 = rf(client) } else { @@ -169,18 +238,45 @@ func (_m *StakeManagerUtils) MinSafeRazor(client *ethclient.Client) (*big.Int, e return r0, r1 } +// StakerInfo provides a mock function with given fields: client, stakerId +func (_m *StakeManagerUtils) StakerInfo(client *ethclient.Client, stakerId uint32) (types.Staker, error) { + ret := _m.Called(client, stakerId) + + var r0 types.Staker + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32) (types.Staker, error)); ok { + return rf(client, stakerId) + } + if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32) types.Staker); ok { + r0 = rf(client, stakerId) + } else { + r0 = ret.Get(0).(types.Staker) + } + + if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32) error); ok { + r1 = rf(client, stakerId) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // WithdrawInitiationPeriod provides a mock function with given fields: client func (_m *StakeManagerUtils) WithdrawInitiationPeriod(client *ethclient.Client) (uint16, error) { ret := _m.Called(client) var r0 uint16 + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client) (uint16, error)); ok { + return rf(client) + } if rf, ok := ret.Get(0).(func(*ethclient.Client) uint16); ok { r0 = rf(client) } else { r0 = ret.Get(0).(uint16) } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { r1 = rf(client) } else { @@ -190,13 +286,12 @@ func (_m *StakeManagerUtils) WithdrawInitiationPeriod(client *ethclient.Client) return r0, r1 } -type mockConstructorTestingTNewStakeManagerUtils interface { +// NewStakeManagerUtils creates a new instance of StakeManagerUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewStakeManagerUtils(t interface { mock.TestingT Cleanup(func()) -} - -// NewStakeManagerUtils creates a new instance of StakeManagerUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewStakeManagerUtils(t mockConstructorTestingTNewStakeManagerUtils) *StakeManagerUtils { +}) *StakeManagerUtils { mock := &StakeManagerUtils{} mock.Mock.Test(t) diff --git a/utils/mocks/staked_token_utils.go b/utils/mocks/staked_token_utils.go index a502ee966..6acdb5a67 100644 --- a/utils/mocks/staked_token_utils.go +++ b/utils/mocks/staked_token_utils.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -21,6 +21,10 @@ func (_m *StakedTokenUtils) BalanceOf(client *ethclient.Client, tokenAddress com ret := _m.Called(client, tokenAddress, address) var r0 *big.Int + var r1 error + if rf, ok := ret.Get(0).(func(*ethclient.Client, common.Address, common.Address) (*big.Int, error)); ok { + return rf(client, tokenAddress, address) + } if rf, ok := ret.Get(0).(func(*ethclient.Client, common.Address, common.Address) *big.Int); ok { r0 = rf(client, tokenAddress, address) } else { @@ -29,7 +33,6 @@ func (_m *StakedTokenUtils) BalanceOf(client *ethclient.Client, tokenAddress com } } - var r1 error if rf, ok := ret.Get(1).(func(*ethclient.Client, common.Address, common.Address) error); ok { r1 = rf(client, tokenAddress, address) } else { @@ -39,13 +42,12 @@ func (_m *StakedTokenUtils) BalanceOf(client *ethclient.Client, tokenAddress com return r0, r1 } -type mockConstructorTestingTNewStakedTokenUtils interface { +// NewStakedTokenUtils creates a new instance of StakedTokenUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewStakedTokenUtils(t interface { mock.TestingT Cleanup(func()) -} - -// NewStakedTokenUtils creates a new instance of StakedTokenUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewStakedTokenUtils(t mockConstructorTestingTNewStakedTokenUtils) *StakedTokenUtils { +}) *StakedTokenUtils { mock := &StakedTokenUtils{} mock.Mock.Test(t) diff --git a/utils/mocks/time_utils.go b/utils/mocks/time_utils.go index 118542bef..ef3af8cba 100644 --- a/utils/mocks/time_utils.go +++ b/utils/mocks/time_utils.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks @@ -18,13 +18,12 @@ func (_m *TimeUtils) Sleep(duration time.Duration) { _m.Called(duration) } -type mockConstructorTestingTNewTimeUtils interface { +// NewTimeUtils creates a new instance of TimeUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTimeUtils(t interface { mock.TestingT Cleanup(func()) -} - -// NewTimeUtils creates a new instance of TimeUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewTimeUtils(t mockConstructorTestingTNewTimeUtils) *TimeUtils { +}) *TimeUtils { mock := &TimeUtils{} mock.Mock.Test(t) diff --git a/utils/mocks/utils.go b/utils/mocks/utils.go index 51e0457c3..b3190e723 100644 --- a/utils/mocks/utils.go +++ b/utils/mocks/utils.go @@ -4,6 +4,8 @@ package mocks import ( big "math/big" + RPC "razor/rpc" + bindings "razor/pkg/bindings" bind "github.com/ethereum/go-ethereum/accounts/abi/bind" @@ -12,8 +14,6 @@ import ( common "github.com/ethereum/go-ethereum/common" - context "context" - coretypes "github.com/ethereum/go-ethereum/core/types" ethclient "github.com/ethereum/go-ethereum/ethclient" @@ -70,25 +70,51 @@ func (_m *Utils) AddJobToJSON(fileName string, job *types.StructsJob) error { return r0 } -// Aggregate provides a mock function with given fields: ctx, client, previousEpoch, collection, commitParams -func (_m *Utils) Aggregate(ctx context.Context, client *ethclient.Client, previousEpoch uint32, collection bindings.StructsCollection, commitParams *types.CommitParams) (*big.Int, error) { - ret := _m.Called(ctx, client, previousEpoch, collection, commitParams) +// Aggregate provides a mock function with given fields: rpcParameters, previousEpoch, collection, commitParams +func (_m *Utils) Aggregate(rpcParameters RPC.RPCParameters, previousEpoch uint32, collection bindings.StructsCollection, commitParams *types.CommitParams) (*big.Int, error) { + ret := _m.Called(rpcParameters, previousEpoch, collection, commitParams) + + var r0 *big.Int + var r1 error + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32, bindings.StructsCollection, *types.CommitParams) (*big.Int, error)); ok { + return rf(rpcParameters, previousEpoch, collection, commitParams) + } + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32, bindings.StructsCollection, *types.CommitParams) *big.Int); ok { + r0 = rf(rpcParameters, previousEpoch, collection, commitParams) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*big.Int) + } + } + + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32, bindings.StructsCollection, *types.CommitParams) error); ok { + r1 = rf(rpcParameters, previousEpoch, collection, commitParams) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Allowance provides a mock function with given fields: rpcParameters, owner, spender +func (_m *Utils) Allowance(rpcParameters RPC.RPCParameters, owner common.Address, spender common.Address) (*big.Int, error) { + ret := _m.Called(rpcParameters, owner, spender) var r0 *big.Int var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, bindings.StructsCollection, *types.CommitParams) (*big.Int, error)); ok { - return rf(ctx, client, previousEpoch, collection, commitParams) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, common.Address, common.Address) (*big.Int, error)); ok { + return rf(rpcParameters, owner, spender) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, bindings.StructsCollection, *types.CommitParams) *big.Int); ok { - r0 = rf(ctx, client, previousEpoch, collection, commitParams) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, common.Address, common.Address) *big.Int); ok { + r0 = rf(rpcParameters, owner, spender) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32, bindings.StructsCollection, *types.CommitParams) error); ok { - r1 = rf(ctx, client, previousEpoch, collection, commitParams) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, common.Address, common.Address) error); ok { + r1 = rf(rpcParameters, owner, spender) } else { r1 = ret.Error(1) } @@ -110,23 +136,23 @@ func (_m *Utils) AssignPassword(flagSet *pflag.FlagSet) string { return r0 } -// AssignStakerId provides a mock function with given fields: ctx, flagSet, client, address -func (_m *Utils) AssignStakerId(ctx context.Context, flagSet *pflag.FlagSet, client *ethclient.Client, address string) (uint32, error) { - ret := _m.Called(ctx, flagSet, client, address) +// AssignStakerId provides a mock function with given fields: rpcParameters, flagSet, address +func (_m *Utils) AssignStakerId(rpcParameters RPC.RPCParameters, flagSet *pflag.FlagSet, address string) (uint32, error) { + ret := _m.Called(rpcParameters, flagSet, address) var r0 uint32 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *pflag.FlagSet, *ethclient.Client, string) (uint32, error)); ok { - return rf(ctx, flagSet, client, address) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, *pflag.FlagSet, string) (uint32, error)); ok { + return rf(rpcParameters, flagSet, address) } - if rf, ok := ret.Get(0).(func(context.Context, *pflag.FlagSet, *ethclient.Client, string) uint32); ok { - r0 = rf(ctx, flagSet, client, address) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, *pflag.FlagSet, string) uint32); ok { + r0 = rf(rpcParameters, flagSet, address) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(context.Context, *pflag.FlagSet, *ethclient.Client, string) error); ok { - r1 = rf(ctx, flagSet, client, address) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, *pflag.FlagSet, string) error); ok { + r1 = rf(rpcParameters, flagSet, address) } else { r1 = ret.Error(1) } @@ -134,13 +160,13 @@ func (_m *Utils) AssignStakerId(ctx context.Context, flagSet *pflag.FlagSet, cli return r0, r1 } -// CalculateBlockTime provides a mock function with given fields: ctx, client -func (_m *Utils) CalculateBlockTime(ctx context.Context, client *ethclient.Client) int64 { - ret := _m.Called(ctx, client) +// CalculateBlockTime provides a mock function with given fields: rpcParameters +func (_m *Utils) CalculateBlockTime(rpcParameters RPC.RPCParameters) int64 { + ret := _m.Called(rpcParameters) var r0 int64 - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) int64); ok { - r0 = rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) int64); ok { + r0 = rf(rpcParameters) } else { r0 = ret.Get(0).(int64) } @@ -180,9 +206,9 @@ func (_m *Utils) CheckAmountAndBalance(amountInWei *big.Int, balance *big.Int) * return r0 } -// CheckEthBalanceIsZero provides a mock function with given fields: ctx, client, address -func (_m *Utils) CheckEthBalanceIsZero(ctx context.Context, client *ethclient.Client, address string) { - _m.Called(ctx, client, address) +// CheckEthBalanceIsZero provides a mock function with given fields: rpcParameters, address +func (_m *Utils) CheckEthBalanceIsZero(rpcParameters RPC.RPCParameters, address string) { + _m.Called(rpcParameters, address) } // CheckPassword provides a mock function with given fields: account @@ -199,13 +225,13 @@ func (_m *Utils) CheckPassword(account types.Account) error { return r0 } -// CheckTransactionReceipt provides a mock function with given fields: client, _txHash -func (_m *Utils) CheckTransactionReceipt(client *ethclient.Client, _txHash string) int { - ret := _m.Called(client, _txHash) +// CheckTransactionReceipt provides a mock function with given fields: rpcManager, _txHash +func (_m *Utils) CheckTransactionReceipt(rpcManager RPC.RPCParameters, _txHash string) int { + ret := _m.Called(rpcManager, _txHash) var r0 int - if rf, ok := ret.Get(0).(func(*ethclient.Client, string) int); ok { - r0 = rf(client, _txHash) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, string) int); ok { + r0 = rf(rpcManager, _txHash) } else { r0 = ret.Get(0).(int) } @@ -243,25 +269,49 @@ func (_m *Utils) DeleteJobFromJSON(fileName string, jobId string) error { return r0 } -// EstimateBlockNumberAtEpochBeginning provides a mock function with given fields: client, currentBlockNumber -func (_m *Utils) EstimateBlockNumberAtEpochBeginning(client *ethclient.Client, currentBlockNumber *big.Int) (*big.Int, error) { - ret := _m.Called(client, currentBlockNumber) +// Disputes provides a mock function with given fields: rpcParameters, epoch, address +func (_m *Utils) Disputes(rpcParameters RPC.RPCParameters, epoch uint32, address common.Address) (types.DisputesStruct, error) { + ret := _m.Called(rpcParameters, epoch, address) + + var r0 types.DisputesStruct + var r1 error + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32, common.Address) (types.DisputesStruct, error)); ok { + return rf(rpcParameters, epoch, address) + } + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32, common.Address) types.DisputesStruct); ok { + r0 = rf(rpcParameters, epoch, address) + } else { + r0 = ret.Get(0).(types.DisputesStruct) + } + + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32, common.Address) error); ok { + r1 = rf(rpcParameters, epoch, address) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// EstimateBlockNumberAtEpochBeginning provides a mock function with given fields: rpcParameters, currentBlockNumber +func (_m *Utils) EstimateBlockNumberAtEpochBeginning(rpcParameters RPC.RPCParameters, currentBlockNumber *big.Int) (*big.Int, error) { + ret := _m.Called(rpcParameters, currentBlockNumber) var r0 *big.Int var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, *big.Int) (*big.Int, error)); ok { - return rf(client, currentBlockNumber) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, *big.Int) (*big.Int, error)); ok { + return rf(rpcParameters, currentBlockNumber) } - if rf, ok := ret.Get(0).(func(*ethclient.Client, *big.Int) *big.Int); ok { - r0 = rf(client, currentBlockNumber) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, *big.Int) *big.Int); ok { + r0 = rf(rpcParameters, currentBlockNumber) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, *big.Int) error); ok { - r1 = rf(client, currentBlockNumber) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, *big.Int) error); ok { + r1 = rf(rpcParameters, currentBlockNumber) } else { r1 = ret.Error(1) } @@ -269,25 +319,25 @@ func (_m *Utils) EstimateBlockNumberAtEpochBeginning(client *ethclient.Client, c return r0, r1 } -// FetchBalance provides a mock function with given fields: client, accountAddress -func (_m *Utils) FetchBalance(client *ethclient.Client, accountAddress string) (*big.Int, error) { - ret := _m.Called(client, accountAddress) +// FetchBalance provides a mock function with given fields: rpcParameters, accountAddress +func (_m *Utils) FetchBalance(rpcParameters RPC.RPCParameters, accountAddress string) (*big.Int, error) { + ret := _m.Called(rpcParameters, accountAddress) var r0 *big.Int var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, string) (*big.Int, error)); ok { - return rf(client, accountAddress) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, string) (*big.Int, error)); ok { + return rf(rpcParameters, accountAddress) } - if rf, ok := ret.Get(0).(func(*ethclient.Client, string) *big.Int); ok { - r0 = rf(client, accountAddress) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, string) *big.Int); ok { + r0 = rf(rpcParameters, accountAddress) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, string) error); ok { - r1 = rf(client, accountAddress) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, string) error); ok { + r1 = rf(rpcParameters, accountAddress) } else { r1 = ret.Error(1) } @@ -295,25 +345,25 @@ func (_m *Utils) FetchBalance(client *ethclient.Client, accountAddress string) ( return r0, r1 } -// FetchPreviousValue provides a mock function with given fields: ctx, client, epoch, assetId -func (_m *Utils) FetchPreviousValue(ctx context.Context, client *ethclient.Client, epoch uint32, assetId uint16) (*big.Int, error) { - ret := _m.Called(ctx, client, epoch, assetId) +// FetchPreviousValue provides a mock function with given fields: rpcParameters, epoch, assetId +func (_m *Utils) FetchPreviousValue(rpcParameters RPC.RPCParameters, epoch uint32, assetId uint16) (*big.Int, error) { + ret := _m.Called(rpcParameters, epoch, assetId) var r0 *big.Int var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, uint16) (*big.Int, error)); ok { - return rf(ctx, client, epoch, assetId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32, uint16) (*big.Int, error)); ok { + return rf(rpcParameters, epoch, assetId) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, uint16) *big.Int); ok { - r0 = rf(ctx, client, epoch, assetId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32, uint16) *big.Int); ok { + r0 = rf(rpcParameters, epoch, assetId) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32, uint16) error); ok { - r1 = rf(ctx, client, epoch, assetId) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32, uint16) error); ok { + r1 = rf(rpcParameters, epoch, assetId) } else { r1 = ret.Error(1) } @@ -345,25 +395,25 @@ func (_m *Utils) GetActiveCollection(collectionsCache *cache.CollectionsCache, c return r0, r1 } -// GetActiveCollectionIds provides a mock function with given fields: ctx, client -func (_m *Utils) GetActiveCollectionIds(ctx context.Context, client *ethclient.Client) ([]uint16, error) { - ret := _m.Called(ctx, client) +// GetActiveCollectionIds provides a mock function with given fields: rpcParameters +func (_m *Utils) GetActiveCollectionIds(rpcParameters RPC.RPCParameters) ([]uint16, error) { + ret := _m.Called(rpcParameters) var r0 []uint16 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) ([]uint16, error)); ok { - return rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) ([]uint16, error)); ok { + return rf(rpcParameters) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) []uint16); ok { - r0 = rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) []uint16); ok { + r0 = rf(rpcParameters) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]uint16) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { - r1 = rf(ctx, client) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters) error); ok { + r1 = rf(rpcParameters) } else { r1 = ret.Error(1) } @@ -371,23 +421,47 @@ func (_m *Utils) GetActiveCollectionIds(ctx context.Context, client *ethclient.C return r0, r1 } -// GetActiveJob provides a mock function with given fields: ctx, client, jobId -func (_m *Utils) GetActiveJob(ctx context.Context, client *ethclient.Client, jobId uint16) (bindings.StructsJob, error) { - ret := _m.Called(ctx, client, jobId) +// GetActiveJob provides a mock function with given fields: rpcParameters, jobId +func (_m *Utils) GetActiveJob(rpcParameters RPC.RPCParameters, jobId uint16) (bindings.StructsJob, error) { + ret := _m.Called(rpcParameters, jobId) var r0 bindings.StructsJob var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint16) (bindings.StructsJob, error)); ok { - return rf(ctx, client, jobId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint16) (bindings.StructsJob, error)); ok { + return rf(rpcParameters, jobId) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint16) bindings.StructsJob); ok { - r0 = rf(ctx, client, jobId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint16) bindings.StructsJob); ok { + r0 = rf(rpcParameters, jobId) } else { r0 = ret.Get(0).(bindings.StructsJob) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint16) error); ok { - r1 = rf(ctx, client, jobId) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint16) error); ok { + r1 = rf(rpcParameters, jobId) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetActiveStatus provides a mock function with given fields: rpcParameters, id +func (_m *Utils) GetActiveStatus(rpcParameters RPC.RPCParameters, id uint16) (bool, error) { + ret := _m.Called(rpcParameters, id) + + var r0 bool + var r1 error + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint16) (bool, error)); ok { + return rf(rpcParameters, id) + } + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint16) bool); ok { + r0 = rf(rpcParameters, id) + } else { + r0 = ret.Get(0).(bool) + } + + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint16) error); ok { + r1 = rf(rpcParameters, id) } else { r1 = ret.Error(1) } @@ -395,25 +469,25 @@ func (_m *Utils) GetActiveJob(ctx context.Context, client *ethclient.Client, job return r0, r1 } -// GetAggregatedDataOfCollection provides a mock function with given fields: ctx, client, collectionId, epoch, commitParams -func (_m *Utils) GetAggregatedDataOfCollection(ctx context.Context, client *ethclient.Client, collectionId uint16, epoch uint32, commitParams *types.CommitParams) (*big.Int, error) { - ret := _m.Called(ctx, client, collectionId, epoch, commitParams) +// GetAggregatedDataOfCollection provides a mock function with given fields: rpcParameters, collectionId, epoch, commitParams +func (_m *Utils) GetAggregatedDataOfCollection(rpcParameters RPC.RPCParameters, collectionId uint16, epoch uint32, commitParams *types.CommitParams) (*big.Int, error) { + ret := _m.Called(rpcParameters, collectionId, epoch, commitParams) var r0 *big.Int var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint16, uint32, *types.CommitParams) (*big.Int, error)); ok { - return rf(ctx, client, collectionId, epoch, commitParams) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint16, uint32, *types.CommitParams) (*big.Int, error)); ok { + return rf(rpcParameters, collectionId, epoch, commitParams) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint16, uint32, *types.CommitParams) *big.Int); ok { - r0 = rf(ctx, client, collectionId, epoch, commitParams) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint16, uint32, *types.CommitParams) *big.Int); ok { + r0 = rf(rpcParameters, collectionId, epoch, commitParams) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint16, uint32, *types.CommitParams) error); ok { - r1 = rf(ctx, client, collectionId, epoch, commitParams) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint16, uint32, *types.CommitParams) error); ok { + r1 = rf(rpcParameters, collectionId, epoch, commitParams) } else { r1 = ret.Error(1) } @@ -421,25 +495,25 @@ func (_m *Utils) GetAggregatedDataOfCollection(ctx context.Context, client *ethc return r0, r1 } -// GetAllCollections provides a mock function with given fields: ctx, client -func (_m *Utils) GetAllCollections(ctx context.Context, client *ethclient.Client) ([]bindings.StructsCollection, error) { - ret := _m.Called(ctx, client) +// GetAllCollections provides a mock function with given fields: rpcParameters +func (_m *Utils) GetAllCollections(rpcParameters RPC.RPCParameters) ([]bindings.StructsCollection, error) { + ret := _m.Called(rpcParameters) var r0 []bindings.StructsCollection var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) ([]bindings.StructsCollection, error)); ok { - return rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) ([]bindings.StructsCollection, error)); ok { + return rf(rpcParameters) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) []bindings.StructsCollection); ok { - r0 = rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) []bindings.StructsCollection); ok { + r0 = rf(rpcParameters) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]bindings.StructsCollection) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { - r1 = rf(ctx, client) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters) error); ok { + r1 = rf(rpcParameters) } else { r1 = ret.Error(1) } @@ -447,34 +521,34 @@ func (_m *Utils) GetAllCollections(ctx context.Context, client *ethclient.Client return r0, r1 } -// GetAssignedCollections provides a mock function with given fields: ctx, client, numActiveCollections, seed -func (_m *Utils) GetAssignedCollections(ctx context.Context, client *ethclient.Client, numActiveCollections uint16, seed []byte) (map[int]bool, []*big.Int, error) { - ret := _m.Called(ctx, client, numActiveCollections, seed) +// GetAssignedCollections provides a mock function with given fields: rpcParameters, numActiveCollections, seed +func (_m *Utils) GetAssignedCollections(rpcParameters RPC.RPCParameters, numActiveCollections uint16, seed []byte) (map[int]bool, []*big.Int, error) { + ret := _m.Called(rpcParameters, numActiveCollections, seed) var r0 map[int]bool var r1 []*big.Int var r2 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint16, []byte) (map[int]bool, []*big.Int, error)); ok { - return rf(ctx, client, numActiveCollections, seed) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint16, []byte) (map[int]bool, []*big.Int, error)); ok { + return rf(rpcParameters, numActiveCollections, seed) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint16, []byte) map[int]bool); ok { - r0 = rf(ctx, client, numActiveCollections, seed) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint16, []byte) map[int]bool); ok { + r0 = rf(rpcParameters, numActiveCollections, seed) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(map[int]bool) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint16, []byte) []*big.Int); ok { - r1 = rf(ctx, client, numActiveCollections, seed) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint16, []byte) []*big.Int); ok { + r1 = rf(rpcParameters, numActiveCollections, seed) } else { if ret.Get(1) != nil { r1 = ret.Get(1).([]*big.Int) } } - if rf, ok := ret.Get(2).(func(context.Context, *ethclient.Client, uint16, []byte) error); ok { - r2 = rf(ctx, client, numActiveCollections, seed) + if rf, ok := ret.Get(2).(func(RPC.RPCParameters, uint16, []byte) error); ok { + r2 = rf(rpcParameters, numActiveCollections, seed) } else { r2 = ret.Error(2) } @@ -482,23 +556,23 @@ func (_m *Utils) GetAssignedCollections(ctx context.Context, client *ethclient.C return r0, r1, r2 } -// GetBlock provides a mock function with given fields: ctx, client, epoch -func (_m *Utils) GetBlock(ctx context.Context, client *ethclient.Client, epoch uint32) (bindings.StructsBlock, error) { - ret := _m.Called(ctx, client, epoch) +// GetBlock provides a mock function with given fields: rpcParameters, epoch +func (_m *Utils) GetBlock(rpcParameters RPC.RPCParameters, epoch uint32) (bindings.StructsBlock, error) { + ret := _m.Called(rpcParameters, epoch) var r0 bindings.StructsBlock var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) (bindings.StructsBlock, error)); ok { - return rf(ctx, client, epoch) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) (bindings.StructsBlock, error)); ok { + return rf(rpcParameters, epoch) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) bindings.StructsBlock); ok { - r0 = rf(ctx, client, epoch) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) bindings.StructsBlock); ok { + r0 = rf(rpcParameters, epoch) } else { r0 = ret.Get(0).(bindings.StructsBlock) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32) error); ok { - r1 = rf(ctx, client, epoch) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32) error); ok { + r1 = rf(rpcParameters, epoch) } else { r1 = ret.Error(1) } @@ -506,23 +580,23 @@ func (_m *Utils) GetBlock(ctx context.Context, client *ethclient.Client, epoch u return r0, r1 } -// GetBlockIndexToBeConfirmed provides a mock function with given fields: ctx, client -func (_m *Utils) GetBlockIndexToBeConfirmed(ctx context.Context, client *ethclient.Client) (int8, error) { - ret := _m.Called(ctx, client) +// GetBlockIndexToBeConfirmed provides a mock function with given fields: rpcParameters +func (_m *Utils) GetBlockIndexToBeConfirmed(rpcParameters RPC.RPCParameters) (int8, error) { + ret := _m.Called(rpcParameters) var r0 int8 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) (int8, error)); ok { - return rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) (int8, error)); ok { + return rf(rpcParameters) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) int8); ok { - r0 = rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) int8); ok { + r0 = rf(rpcParameters) } else { r0 = ret.Get(0).(int8) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { - r1 = rf(ctx, client) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters) error); ok { + r1 = rf(rpcParameters) } else { r1 = ret.Error(1) } @@ -572,6 +646,30 @@ func (_m *Utils) GetBlockManagerWithOpts(client *ethclient.Client) (*bindings.Bl return r0, r1 } +// GetBountyLock provides a mock function with given fields: rpcParameters, bountyId +func (_m *Utils) GetBountyLock(rpcParameters RPC.RPCParameters, bountyId uint32) (types.BountyLock, error) { + ret := _m.Called(rpcParameters, bountyId) + + var r0 types.BountyLock + var r1 error + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) (types.BountyLock, error)); ok { + return rf(rpcParameters, bountyId) + } + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) types.BountyLock); ok { + r0 = rf(rpcParameters, bountyId) + } else { + r0 = ret.Get(0).(types.BountyLock) + } + + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32) error); ok { + r1 = rf(rpcParameters, bountyId) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + // GetBufferedState provides a mock function with given fields: header, stateBuffer, buffer func (_m *Utils) GetBufferedState(header *coretypes.Header, stateBuffer uint64, buffer int32) (int64, error) { ret := _m.Called(header, stateBuffer, buffer) @@ -596,23 +694,23 @@ func (_m *Utils) GetBufferedState(header *coretypes.Header, stateBuffer uint64, return r0, r1 } -// GetCollection provides a mock function with given fields: ctx, client, collectionId -func (_m *Utils) GetCollection(ctx context.Context, client *ethclient.Client, collectionId uint16) (bindings.StructsCollection, error) { - ret := _m.Called(ctx, client, collectionId) +// GetCollection provides a mock function with given fields: rpcParameters, collectionId +func (_m *Utils) GetCollection(rpcParameters RPC.RPCParameters, collectionId uint16) (bindings.StructsCollection, error) { + ret := _m.Called(rpcParameters, collectionId) var r0 bindings.StructsCollection var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint16) (bindings.StructsCollection, error)); ok { - return rf(ctx, client, collectionId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint16) (bindings.StructsCollection, error)); ok { + return rf(rpcParameters, collectionId) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint16) bindings.StructsCollection); ok { - r0 = rf(ctx, client, collectionId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint16) bindings.StructsCollection); ok { + r0 = rf(rpcParameters, collectionId) } else { r0 = ret.Get(0).(bindings.StructsCollection) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint16) error); ok { - r1 = rf(ctx, client, collectionId) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint16) error); ok { + r1 = rf(rpcParameters, collectionId) } else { r1 = ret.Error(1) } @@ -620,23 +718,23 @@ func (_m *Utils) GetCollection(ctx context.Context, client *ethclient.Client, co return r0, r1 } -// GetCollectionIdFromIndex provides a mock function with given fields: ctx, client, medianIndex -func (_m *Utils) GetCollectionIdFromIndex(ctx context.Context, client *ethclient.Client, medianIndex uint16) (uint16, error) { - ret := _m.Called(ctx, client, medianIndex) +// GetCollectionIdFromIndex provides a mock function with given fields: rpcParameters, medianIndex +func (_m *Utils) GetCollectionIdFromIndex(rpcParameters RPC.RPCParameters, medianIndex uint16) (uint16, error) { + ret := _m.Called(rpcParameters, medianIndex) var r0 uint16 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint16) (uint16, error)); ok { - return rf(ctx, client, medianIndex) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint16) (uint16, error)); ok { + return rf(rpcParameters, medianIndex) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint16) uint16); ok { - r0 = rf(ctx, client, medianIndex) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint16) uint16); ok { + r0 = rf(rpcParameters, medianIndex) } else { r0 = ret.Get(0).(uint16) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint16) error); ok { - r1 = rf(ctx, client, medianIndex) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint16) error); ok { + r1 = rf(rpcParameters, medianIndex) } else { r1 = ret.Error(1) } @@ -644,23 +742,23 @@ func (_m *Utils) GetCollectionIdFromIndex(ctx context.Context, client *ethclient return r0, r1 } -// GetCollectionIdFromLeafId provides a mock function with given fields: ctx, client, leafId -func (_m *Utils) GetCollectionIdFromLeafId(ctx context.Context, client *ethclient.Client, leafId uint16) (uint16, error) { - ret := _m.Called(ctx, client, leafId) +// GetCollectionIdFromLeafId provides a mock function with given fields: rpcParameters, leafId +func (_m *Utils) GetCollectionIdFromLeafId(rpcParameters RPC.RPCParameters, leafId uint16) (uint16, error) { + ret := _m.Called(rpcParameters, leafId) var r0 uint16 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint16) (uint16, error)); ok { - return rf(ctx, client, leafId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint16) (uint16, error)); ok { + return rf(rpcParameters, leafId) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint16) uint16); ok { - r0 = rf(ctx, client, leafId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint16) uint16); ok { + r0 = rf(rpcParameters, leafId) } else { r0 = ret.Get(0).(uint16) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint16) error); ok { - r1 = rf(ctx, client, leafId) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint16) error); ok { + r1 = rf(rpcParameters, leafId) } else { r1 = ret.Error(1) } @@ -710,23 +808,23 @@ func (_m *Utils) GetCollectionManagerWithOpts(client *ethclient.Client) (*bindin return r0, r1 } -// GetCommitment provides a mock function with given fields: ctx, client, address -func (_m *Utils) GetCommitment(ctx context.Context, client *ethclient.Client, address string) (types.Commitment, error) { - ret := _m.Called(ctx, client, address) +// GetCommitment provides a mock function with given fields: rpcParameters, address +func (_m *Utils) GetCommitment(rpcParameters RPC.RPCParameters, address string) (types.Commitment, error) { + ret := _m.Called(rpcParameters, address) var r0 types.Commitment var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, string) (types.Commitment, error)); ok { - return rf(ctx, client, address) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, string) (types.Commitment, error)); ok { + return rf(rpcParameters, address) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, string) types.Commitment); ok { - r0 = rf(ctx, client, address) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, string) types.Commitment); ok { + r0 = rf(rpcParameters, address) } else { r0 = ret.Get(0).(types.Commitment) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, string) error); ok { - r1 = rf(ctx, client, address) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, string) error); ok { + r1 = rf(rpcParameters, address) } else { r1 = ret.Error(1) } @@ -734,23 +832,23 @@ func (_m *Utils) GetCommitment(ctx context.Context, client *ethclient.Client, ad return r0, r1 } -// GetConfirmedBlocks provides a mock function with given fields: ctx, client, epoch -func (_m *Utils) GetConfirmedBlocks(ctx context.Context, client *ethclient.Client, epoch uint32) (types.ConfirmedBlock, error) { - ret := _m.Called(ctx, client, epoch) +// GetConfirmedBlocks provides a mock function with given fields: rpcParameters, epoch +func (_m *Utils) GetConfirmedBlocks(rpcParameters RPC.RPCParameters, epoch uint32) (types.ConfirmedBlock, error) { + ret := _m.Called(rpcParameters, epoch) var r0 types.ConfirmedBlock var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) (types.ConfirmedBlock, error)); ok { - return rf(ctx, client, epoch) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) (types.ConfirmedBlock, error)); ok { + return rf(rpcParameters, epoch) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) types.ConfirmedBlock); ok { - r0 = rf(ctx, client, epoch) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) types.ConfirmedBlock); ok { + r0 = rf(rpcParameters, epoch) } else { r0 = ret.Get(0).(types.ConfirmedBlock) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32) error); ok { - r1 = rf(ctx, client, epoch) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32) error); ok { + r1 = rf(rpcParameters, epoch) } else { r1 = ret.Error(1) } @@ -812,23 +910,23 @@ func (_m *Utils) GetDataToCommitFromJobs(jobs []bindings.StructsJob, commitParam return r0, r1 } -// GetEpoch provides a mock function with given fields: ctx, client -func (_m *Utils) GetEpoch(ctx context.Context, client *ethclient.Client) (uint32, error) { - ret := _m.Called(ctx, client) +// GetEpoch provides a mock function with given fields: rpcParameters +func (_m *Utils) GetEpoch(rpcParameters RPC.RPCParameters) (uint32, error) { + ret := _m.Called(rpcParameters) var r0 uint32 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) (uint32, error)); ok { - return rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) (uint32, error)); ok { + return rf(rpcParameters) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) uint32); ok { - r0 = rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) uint32); ok { + r0 = rf(rpcParameters) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { - r1 = rf(ctx, client) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters) error); ok { + r1 = rf(rpcParameters) } else { r1 = ret.Error(1) } @@ -836,23 +934,23 @@ func (_m *Utils) GetEpoch(ctx context.Context, client *ethclient.Client) (uint32 return r0, r1 } -// GetEpochLastCommitted provides a mock function with given fields: ctx, client, stakerId -func (_m *Utils) GetEpochLastCommitted(ctx context.Context, client *ethclient.Client, stakerId uint32) (uint32, error) { - ret := _m.Called(ctx, client, stakerId) +// GetEpochLastCommitted provides a mock function with given fields: rpcParameters, stakerId +func (_m *Utils) GetEpochLastCommitted(rpcParameters RPC.RPCParameters, stakerId uint32) (uint32, error) { + ret := _m.Called(rpcParameters, stakerId) var r0 uint32 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) (uint32, error)); ok { - return rf(ctx, client, stakerId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) (uint32, error)); ok { + return rf(rpcParameters, stakerId) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) uint32); ok { - r0 = rf(ctx, client, stakerId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) uint32); ok { + r0 = rf(rpcParameters, stakerId) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32) error); ok { - r1 = rf(ctx, client, stakerId) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32) error); ok { + r1 = rf(rpcParameters, stakerId) } else { r1 = ret.Error(1) } @@ -860,23 +958,23 @@ func (_m *Utils) GetEpochLastCommitted(ctx context.Context, client *ethclient.Cl return r0, r1 } -// GetEpochLastProposed provides a mock function with given fields: ctx, client, stakerId -func (_m *Utils) GetEpochLastProposed(ctx context.Context, client *ethclient.Client, stakerId uint32) (uint32, error) { - ret := _m.Called(ctx, client, stakerId) +// GetEpochLastProposed provides a mock function with given fields: rpcParameters, stakerId +func (_m *Utils) GetEpochLastProposed(rpcParameters RPC.RPCParameters, stakerId uint32) (uint32, error) { + ret := _m.Called(rpcParameters, stakerId) var r0 uint32 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) (uint32, error)); ok { - return rf(ctx, client, stakerId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) (uint32, error)); ok { + return rf(rpcParameters, stakerId) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) uint32); ok { - r0 = rf(ctx, client, stakerId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) uint32); ok { + r0 = rf(rpcParameters, stakerId) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32) error); ok { - r1 = rf(ctx, client, stakerId) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32) error); ok { + r1 = rf(rpcParameters, stakerId) } else { r1 = ret.Error(1) } @@ -884,23 +982,23 @@ func (_m *Utils) GetEpochLastProposed(ctx context.Context, client *ethclient.Cli return r0, r1 } -// GetEpochLastRevealed provides a mock function with given fields: ctx, client, stakerId -func (_m *Utils) GetEpochLastRevealed(ctx context.Context, client *ethclient.Client, stakerId uint32) (uint32, error) { - ret := _m.Called(ctx, client, stakerId) +// GetEpochLastRevealed provides a mock function with given fields: rpcParameters, stakerId +func (_m *Utils) GetEpochLastRevealed(rpcParameters RPC.RPCParameters, stakerId uint32) (uint32, error) { + ret := _m.Called(rpcParameters, stakerId) var r0 uint32 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) (uint32, error)); ok { - return rf(ctx, client, stakerId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) (uint32, error)); ok { + return rf(rpcParameters, stakerId) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) uint32); ok { - r0 = rf(ctx, client, stakerId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) uint32); ok { + r0 = rf(rpcParameters, stakerId) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32) error); ok { - r1 = rf(ctx, client, stakerId) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32) error); ok { + r1 = rf(rpcParameters, stakerId) } else { r1 = ret.Error(1) } @@ -908,23 +1006,23 @@ func (_m *Utils) GetEpochLastRevealed(ctx context.Context, client *ethclient.Cli return r0, r1 } -// GetEpochLimitForUpdateCommission provides a mock function with given fields: ctx, client -func (_m *Utils) GetEpochLimitForUpdateCommission(ctx context.Context, client *ethclient.Client) (uint16, error) { - ret := _m.Called(ctx, client) +// GetEpochLimitForUpdateCommission provides a mock function with given fields: rpcParameters +func (_m *Utils) GetEpochLimitForUpdateCommission(rpcParameters RPC.RPCParameters) (uint16, error) { + ret := _m.Called(rpcParameters) var r0 uint16 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) (uint16, error)); ok { - return rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) (uint16, error)); ok { + return rf(rpcParameters) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) uint16); ok { - r0 = rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) uint16); ok { + r0 = rf(rpcParameters) } else { r0 = ret.Get(0).(uint16) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { - r1 = rf(ctx, client) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters) error); ok { + r1 = rf(rpcParameters) } else { r1 = ret.Error(1) } @@ -932,25 +1030,25 @@ func (_m *Utils) GetEpochLimitForUpdateCommission(ctx context.Context, client *e return r0, r1 } -// GetInfluenceSnapshot provides a mock function with given fields: ctx, client, stakerId, epoch -func (_m *Utils) GetInfluenceSnapshot(ctx context.Context, client *ethclient.Client, stakerId uint32, epoch uint32) (*big.Int, error) { - ret := _m.Called(ctx, client, stakerId, epoch) +// GetInfluenceSnapshot provides a mock function with given fields: rpcParameters, stakerId, epoch +func (_m *Utils) GetInfluenceSnapshot(rpcParameters RPC.RPCParameters, stakerId uint32, epoch uint32) (*big.Int, error) { + ret := _m.Called(rpcParameters, stakerId, epoch) var r0 *big.Int var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, uint32) (*big.Int, error)); ok { - return rf(ctx, client, stakerId, epoch) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32, uint32) (*big.Int, error)); ok { + return rf(rpcParameters, stakerId, epoch) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, uint32) *big.Int); ok { - r0 = rf(ctx, client, stakerId, epoch) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32, uint32) *big.Int); ok { + r0 = rf(rpcParameters, stakerId, epoch) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32, uint32) error); ok { - r1 = rf(ctx, client, stakerId, epoch) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32, uint32) error); ok { + r1 = rf(rpcParameters, stakerId, epoch) } else { r1 = ret.Error(1) } @@ -958,25 +1056,25 @@ func (_m *Utils) GetInfluenceSnapshot(ctx context.Context, client *ethclient.Cli return r0, r1 } -// GetJobs provides a mock function with given fields: ctx, client -func (_m *Utils) GetJobs(ctx context.Context, client *ethclient.Client) ([]bindings.StructsJob, error) { - ret := _m.Called(ctx, client) +// GetJobs provides a mock function with given fields: rpcParameters +func (_m *Utils) GetJobs(rpcParameters RPC.RPCParameters) ([]bindings.StructsJob, error) { + ret := _m.Called(rpcParameters) var r0 []bindings.StructsJob var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) ([]bindings.StructsJob, error)); ok { - return rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) ([]bindings.StructsJob, error)); ok { + return rf(rpcParameters) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) []bindings.StructsJob); ok { - r0 = rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) []bindings.StructsJob); ok { + r0 = rf(rpcParameters) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]bindings.StructsJob) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { - r1 = rf(ctx, client) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters) error); ok { + r1 = rf(rpcParameters) } else { r1 = ret.Error(1) } @@ -984,23 +1082,23 @@ func (_m *Utils) GetJobs(ctx context.Context, client *ethclient.Client) ([]bindi return r0, r1 } -// GetLeafIdOfACollection provides a mock function with given fields: ctx, client, collectionId -func (_m *Utils) GetLeafIdOfACollection(ctx context.Context, client *ethclient.Client, collectionId uint16) (uint16, error) { - ret := _m.Called(ctx, client, collectionId) +// GetLeafIdOfACollection provides a mock function with given fields: rpcParameters, collectionId +func (_m *Utils) GetLeafIdOfACollection(rpcParameters RPC.RPCParameters, collectionId uint16) (uint16, error) { + ret := _m.Called(rpcParameters, collectionId) var r0 uint16 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint16) (uint16, error)); ok { - return rf(ctx, client, collectionId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint16) (uint16, error)); ok { + return rf(rpcParameters, collectionId) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint16) uint16); ok { - r0 = rf(ctx, client, collectionId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint16) uint16); ok { + r0 = rf(rpcParameters, collectionId) } else { r0 = ret.Get(0).(uint16) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint16) error); ok { - r1 = rf(ctx, client, collectionId) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint16) error); ok { + r1 = rf(rpcParameters, collectionId) } else { r1 = ret.Error(1) } @@ -1008,23 +1106,23 @@ func (_m *Utils) GetLeafIdOfACollection(ctx context.Context, client *ethclient.C return r0, r1 } -// GetLock provides a mock function with given fields: ctx, client, address, stakerId, lockType -func (_m *Utils) GetLock(ctx context.Context, client *ethclient.Client, address string, stakerId uint32, lockType uint8) (types.Locks, error) { - ret := _m.Called(ctx, client, address, stakerId, lockType) +// GetLock provides a mock function with given fields: rpcParameters, address, stakerId, lockType +func (_m *Utils) GetLock(rpcParameters RPC.RPCParameters, address string, stakerId uint32, lockType uint8) (types.Locks, error) { + ret := _m.Called(rpcParameters, address, stakerId, lockType) var r0 types.Locks var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, string, uint32, uint8) (types.Locks, error)); ok { - return rf(ctx, client, address, stakerId, lockType) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, string, uint32, uint8) (types.Locks, error)); ok { + return rf(rpcParameters, address, stakerId, lockType) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, string, uint32, uint8) types.Locks); ok { - r0 = rf(ctx, client, address, stakerId, lockType) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, string, uint32, uint8) types.Locks); ok { + r0 = rf(rpcParameters, address, stakerId, lockType) } else { r0 = ret.Get(0).(types.Locks) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, string, uint32, uint8) error); ok { - r1 = rf(ctx, client, address, stakerId, lockType) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, string, uint32, uint8) error); ok { + r1 = rf(rpcParameters, address, stakerId, lockType) } else { r1 = ret.Error(1) } @@ -1032,23 +1130,47 @@ func (_m *Utils) GetLock(ctx context.Context, client *ethclient.Client, address return r0, r1 } -// GetMaxAltBlocks provides a mock function with given fields: ctx, client -func (_m *Utils) GetMaxAltBlocks(ctx context.Context, client *ethclient.Client) (uint8, error) { - ret := _m.Called(ctx, client) +// GetMaturity provides a mock function with given fields: rpcParameters, age +func (_m *Utils) GetMaturity(rpcParameters RPC.RPCParameters, age uint32) (uint16, error) { + ret := _m.Called(rpcParameters, age) + + var r0 uint16 + var r1 error + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) (uint16, error)); ok { + return rf(rpcParameters, age) + } + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) uint16); ok { + r0 = rf(rpcParameters, age) + } else { + r0 = ret.Get(0).(uint16) + } + + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32) error); ok { + r1 = rf(rpcParameters, age) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetMaxAltBlocks provides a mock function with given fields: rpcParameters +func (_m *Utils) GetMaxAltBlocks(rpcParameters RPC.RPCParameters) (uint8, error) { + ret := _m.Called(rpcParameters) var r0 uint8 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) (uint8, error)); ok { - return rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) (uint8, error)); ok { + return rf(rpcParameters) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) uint8); ok { - r0 = rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) uint8); ok { + r0 = rf(rpcParameters) } else { r0 = ret.Get(0).(uint8) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { - r1 = rf(ctx, client) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters) error); ok { + r1 = rf(rpcParameters) } else { r1 = ret.Error(1) } @@ -1056,23 +1178,23 @@ func (_m *Utils) GetMaxAltBlocks(ctx context.Context, client *ethclient.Client) return r0, r1 } -// GetMaxCommission provides a mock function with given fields: ctx, client -func (_m *Utils) GetMaxCommission(ctx context.Context, client *ethclient.Client) (uint8, error) { - ret := _m.Called(ctx, client) +// GetMaxCommission provides a mock function with given fields: rpcParameters +func (_m *Utils) GetMaxCommission(rpcParameters RPC.RPCParameters) (uint8, error) { + ret := _m.Called(rpcParameters) var r0 uint8 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) (uint8, error)); ok { - return rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) (uint8, error)); ok { + return rf(rpcParameters) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) uint8); ok { - r0 = rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) uint8); ok { + r0 = rf(rpcParameters) } else { r0 = ret.Get(0).(uint8) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { - r1 = rf(ctx, client) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters) error); ok { + r1 = rf(rpcParameters) } else { r1 = ret.Error(1) } @@ -1080,25 +1202,25 @@ func (_m *Utils) GetMaxCommission(ctx context.Context, client *ethclient.Client) return r0, r1 } -// GetMinSafeRazor provides a mock function with given fields: ctx, client -func (_m *Utils) GetMinSafeRazor(ctx context.Context, client *ethclient.Client) (*big.Int, error) { - ret := _m.Called(ctx, client) +// GetMinSafeRazor provides a mock function with given fields: rpcParameters +func (_m *Utils) GetMinSafeRazor(rpcParameters RPC.RPCParameters) (*big.Int, error) { + ret := _m.Called(rpcParameters) var r0 *big.Int var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) (*big.Int, error)); ok { - return rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) (*big.Int, error)); ok { + return rf(rpcParameters) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) *big.Int); ok { - r0 = rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) *big.Int); ok { + r0 = rf(rpcParameters) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { - r1 = rf(ctx, client) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters) error); ok { + r1 = rf(rpcParameters) } else { r1 = ret.Error(1) } @@ -1106,25 +1228,49 @@ func (_m *Utils) GetMinSafeRazor(ctx context.Context, client *ethclient.Client) return r0, r1 } -// GetMinStakeAmount provides a mock function with given fields: ctx, client -func (_m *Utils) GetMinStakeAmount(ctx context.Context, client *ethclient.Client) (*big.Int, error) { - ret := _m.Called(ctx, client) +// GetMinStakeAmount provides a mock function with given fields: rpcParameters +func (_m *Utils) GetMinStakeAmount(rpcParameters RPC.RPCParameters) (*big.Int, error) { + ret := _m.Called(rpcParameters) var r0 *big.Int var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) (*big.Int, error)); ok { - return rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) (*big.Int, error)); ok { + return rf(rpcParameters) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) *big.Int); ok { - r0 = rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) *big.Int); ok { + r0 = rf(rpcParameters) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { - r1 = rf(ctx, client) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters) error); ok { + r1 = rf(rpcParameters) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetNumActiveCollections provides a mock function with given fields: rpcParameters +func (_m *Utils) GetNumActiveCollections(rpcParameters RPC.RPCParameters) (uint16, error) { + ret := _m.Called(rpcParameters) + + var r0 uint16 + var r1 error + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) (uint16, error)); ok { + return rf(rpcParameters) + } + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) uint16); ok { + r0 = rf(rpcParameters) + } else { + r0 = ret.Get(0).(uint16) + } + + if rf, ok := ret.Get(1).(func(RPC.RPCParameters) error); ok { + r1 = rf(rpcParameters) } else { r1 = ret.Error(1) } @@ -1132,23 +1278,23 @@ func (_m *Utils) GetMinStakeAmount(ctx context.Context, client *ethclient.Client return r0, r1 } -// GetNumActiveCollections provides a mock function with given fields: ctx, client -func (_m *Utils) GetNumActiveCollections(ctx context.Context, client *ethclient.Client) (uint16, error) { - ret := _m.Called(ctx, client) +// GetNumCollections provides a mock function with given fields: rpcParameters +func (_m *Utils) GetNumCollections(rpcParameters RPC.RPCParameters) (uint16, error) { + ret := _m.Called(rpcParameters) var r0 uint16 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) (uint16, error)); ok { - return rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) (uint16, error)); ok { + return rf(rpcParameters) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) uint16); ok { - r0 = rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) uint16); ok { + r0 = rf(rpcParameters) } else { r0 = ret.Get(0).(uint16) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { - r1 = rf(ctx, client) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters) error); ok { + r1 = rf(rpcParameters) } else { r1 = ret.Error(1) } @@ -1156,23 +1302,23 @@ func (_m *Utils) GetNumActiveCollections(ctx context.Context, client *ethclient. return r0, r1 } -// GetNumCollections provides a mock function with given fields: ctx, client -func (_m *Utils) GetNumCollections(ctx context.Context, client *ethclient.Client) (uint16, error) { - ret := _m.Called(ctx, client) +// GetNumJobs provides a mock function with given fields: rpcParameters +func (_m *Utils) GetNumJobs(rpcParameters RPC.RPCParameters) (uint16, error) { + ret := _m.Called(rpcParameters) var r0 uint16 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) (uint16, error)); ok { - return rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) (uint16, error)); ok { + return rf(rpcParameters) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) uint16); ok { - r0 = rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) uint16); ok { + r0 = rf(rpcParameters) } else { r0 = ret.Get(0).(uint16) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { - r1 = rf(ctx, client) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters) error); ok { + r1 = rf(rpcParameters) } else { r1 = ret.Error(1) } @@ -1180,23 +1326,23 @@ func (_m *Utils) GetNumCollections(ctx context.Context, client *ethclient.Client return r0, r1 } -// GetNumberOfProposedBlocks provides a mock function with given fields: ctx, client, epoch -func (_m *Utils) GetNumberOfProposedBlocks(ctx context.Context, client *ethclient.Client, epoch uint32) (uint8, error) { - ret := _m.Called(ctx, client, epoch) +// GetNumberOfProposedBlocks provides a mock function with given fields: rpcParameters, epoch +func (_m *Utils) GetNumberOfProposedBlocks(rpcParameters RPC.RPCParameters, epoch uint32) (uint8, error) { + ret := _m.Called(rpcParameters, epoch) var r0 uint8 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) (uint8, error)); ok { - return rf(ctx, client, epoch) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) (uint8, error)); ok { + return rf(rpcParameters, epoch) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) uint8); ok { - r0 = rf(ctx, client, epoch) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) uint8); ok { + r0 = rf(rpcParameters, epoch) } else { r0 = ret.Get(0).(uint8) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32) error); ok { - r1 = rf(ctx, client, epoch) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32) error); ok { + r1 = rf(rpcParameters, epoch) } else { r1 = ret.Error(1) } @@ -1204,23 +1350,23 @@ func (_m *Utils) GetNumberOfProposedBlocks(ctx context.Context, client *ethclien return r0, r1 } -// GetNumberOfStakers provides a mock function with given fields: ctx, client -func (_m *Utils) GetNumberOfStakers(ctx context.Context, client *ethclient.Client) (uint32, error) { - ret := _m.Called(ctx, client) +// GetNumberOfStakers provides a mock function with given fields: rpcParameters +func (_m *Utils) GetNumberOfStakers(rpcParameters RPC.RPCParameters) (uint32, error) { + ret := _m.Called(rpcParameters) var r0 uint32 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) (uint32, error)); ok { - return rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) (uint32, error)); ok { + return rf(rpcParameters) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) uint32); ok { - r0 = rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) uint32); ok { + r0 = rf(rpcParameters) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { - r1 = rf(ctx, client) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters) error); ok { + r1 = rf(rpcParameters) } else { r1 = ret.Error(1) } @@ -1242,23 +1388,23 @@ func (_m *Utils) GetOptions() bind.CallOpts { return r0 } -// GetProposedBlock provides a mock function with given fields: ctx, client, epoch, proposedBlockId -func (_m *Utils) GetProposedBlock(ctx context.Context, client *ethclient.Client, epoch uint32, proposedBlockId uint32) (bindings.StructsBlock, error) { - ret := _m.Called(ctx, client, epoch, proposedBlockId) +// GetProposedBlock provides a mock function with given fields: rpcParameters, epoch, proposedBlockId +func (_m *Utils) GetProposedBlock(rpcParameters RPC.RPCParameters, epoch uint32, proposedBlockId uint32) (bindings.StructsBlock, error) { + ret := _m.Called(rpcParameters, epoch, proposedBlockId) var r0 bindings.StructsBlock var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, uint32) (bindings.StructsBlock, error)); ok { - return rf(ctx, client, epoch, proposedBlockId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32, uint32) (bindings.StructsBlock, error)); ok { + return rf(rpcParameters, epoch, proposedBlockId) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, uint32) bindings.StructsBlock); ok { - r0 = rf(ctx, client, epoch, proposedBlockId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32, uint32) bindings.StructsBlock); ok { + r0 = rf(rpcParameters, epoch, proposedBlockId) } else { r0 = ret.Get(0).(bindings.StructsBlock) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32, uint32) error); ok { - r1 = rf(ctx, client, epoch, proposedBlockId) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32, uint32) error); ok { + r1 = rf(rpcParameters, epoch, proposedBlockId) } else { r1 = ret.Error(1) } @@ -1306,23 +1452,49 @@ func (_m *Utils) GetRogueRandomValue(value int) *big.Int { return r0 } -// GetSortedProposedBlockId provides a mock function with given fields: ctx, client, epoch, index -func (_m *Utils) GetSortedProposedBlockId(ctx context.Context, client *ethclient.Client, epoch uint32, index *big.Int) (uint32, error) { - ret := _m.Called(ctx, client, epoch, index) +// GetSaltFromBlockchain provides a mock function with given fields: rpcParameters +func (_m *Utils) GetSaltFromBlockchain(rpcParameters RPC.RPCParameters) ([32]byte, error) { + ret := _m.Called(rpcParameters) + + var r0 [32]byte + var r1 error + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) ([32]byte, error)); ok { + return rf(rpcParameters) + } + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) [32]byte); ok { + r0 = rf(rpcParameters) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([32]byte) + } + } + + if rf, ok := ret.Get(1).(func(RPC.RPCParameters) error); ok { + r1 = rf(rpcParameters) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// GetSortedProposedBlockId provides a mock function with given fields: rpcParameters, epoch, index +func (_m *Utils) GetSortedProposedBlockId(rpcParameters RPC.RPCParameters, epoch uint32, index *big.Int) (uint32, error) { + ret := _m.Called(rpcParameters, epoch, index) var r0 uint32 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, *big.Int) (uint32, error)); ok { - return rf(ctx, client, epoch, index) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32, *big.Int) (uint32, error)); ok { + return rf(rpcParameters, epoch, index) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, *big.Int) uint32); ok { - r0 = rf(ctx, client, epoch, index) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32, *big.Int) uint32); ok { + r0 = rf(rpcParameters, epoch, index) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32, *big.Int) error); ok { - r1 = rf(ctx, client, epoch, index) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32, *big.Int) error); ok { + r1 = rf(rpcParameters, epoch, index) } else { r1 = ret.Error(1) } @@ -1330,25 +1502,25 @@ func (_m *Utils) GetSortedProposedBlockId(ctx context.Context, client *ethclient return r0, r1 } -// GetSortedProposedBlockIds provides a mock function with given fields: ctx, client, epoch -func (_m *Utils) GetSortedProposedBlockIds(ctx context.Context, client *ethclient.Client, epoch uint32) ([]uint32, error) { - ret := _m.Called(ctx, client, epoch) +// GetSortedProposedBlockIds provides a mock function with given fields: rpcParameters, epoch +func (_m *Utils) GetSortedProposedBlockIds(rpcParameters RPC.RPCParameters, epoch uint32) ([]uint32, error) { + ret := _m.Called(rpcParameters, epoch) var r0 []uint32 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) ([]uint32, error)); ok { - return rf(ctx, client, epoch) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) ([]uint32, error)); ok { + return rf(rpcParameters, epoch) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) []uint32); ok { - r0 = rf(ctx, client, epoch) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) []uint32); ok { + r0 = rf(rpcParameters, epoch) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]uint32) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32) error); ok { - r1 = rf(ctx, client, epoch) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32) error); ok { + r1 = rf(rpcParameters, epoch) } else { r1 = ret.Error(1) } @@ -1356,25 +1528,25 @@ func (_m *Utils) GetSortedProposedBlockIds(ctx context.Context, client *ethclien return r0, r1 } -// GetStake provides a mock function with given fields: ctx, client, stakerId -func (_m *Utils) GetStake(ctx context.Context, client *ethclient.Client, stakerId uint32) (*big.Int, error) { - ret := _m.Called(ctx, client, stakerId) +// GetStake provides a mock function with given fields: rpcParameters, stakerId +func (_m *Utils) GetStake(rpcParameters RPC.RPCParameters, stakerId uint32) (*big.Int, error) { + ret := _m.Called(rpcParameters, stakerId) var r0 *big.Int var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) (*big.Int, error)); ok { - return rf(ctx, client, stakerId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) (*big.Int, error)); ok { + return rf(rpcParameters, stakerId) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) *big.Int); ok { - r0 = rf(ctx, client, stakerId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) *big.Int); ok { + r0 = rf(rpcParameters, stakerId) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32) error); ok { - r1 = rf(ctx, client, stakerId) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32) error); ok { + r1 = rf(rpcParameters, stakerId) } else { r1 = ret.Error(1) } @@ -1424,25 +1596,25 @@ func (_m *Utils) GetStakeManagerWithOpts(client *ethclient.Client) (*bindings.St return r0, r1 } -// GetStakeSnapshot provides a mock function with given fields: ctx, client, stakerId, epoch -func (_m *Utils) GetStakeSnapshot(ctx context.Context, client *ethclient.Client, stakerId uint32, epoch uint32) (*big.Int, error) { - ret := _m.Called(ctx, client, stakerId, epoch) +// GetStakeSnapshot provides a mock function with given fields: rpcParameters, stakerId, epoch +func (_m *Utils) GetStakeSnapshot(rpcParameters RPC.RPCParameters, stakerId uint32, epoch uint32) (*big.Int, error) { + ret := _m.Called(rpcParameters, stakerId, epoch) var r0 *big.Int var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, uint32) (*big.Int, error)); ok { - return rf(ctx, client, stakerId, epoch) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32, uint32) (*big.Int, error)); ok { + return rf(rpcParameters, stakerId, epoch) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, uint32) *big.Int); ok { - r0 = rf(ctx, client, stakerId, epoch) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32, uint32) *big.Int); ok { + r0 = rf(rpcParameters, stakerId, epoch) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32, uint32) error); ok { - r1 = rf(ctx, client, stakerId, epoch) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32, uint32) error); ok { + r1 = rf(rpcParameters, stakerId, epoch) } else { r1 = ret.Error(1) } @@ -1492,23 +1664,23 @@ func (_m *Utils) GetStakedTokenManagerWithOpts(client *ethclient.Client, tokenAd return r0, r1 } -// GetStaker provides a mock function with given fields: ctx, client, stakerId -func (_m *Utils) GetStaker(ctx context.Context, client *ethclient.Client, stakerId uint32) (bindings.StructsStaker, error) { - ret := _m.Called(ctx, client, stakerId) +// GetStaker provides a mock function with given fields: rpcParameters, stakerId +func (_m *Utils) GetStaker(rpcParameters RPC.RPCParameters, stakerId uint32) (bindings.StructsStaker, error) { + ret := _m.Called(rpcParameters, stakerId) var r0 bindings.StructsStaker var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) (bindings.StructsStaker, error)); ok { - return rf(ctx, client, stakerId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) (bindings.StructsStaker, error)); ok { + return rf(rpcParameters, stakerId) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) bindings.StructsStaker); ok { - r0 = rf(ctx, client, stakerId) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) bindings.StructsStaker); ok { + r0 = rf(rpcParameters, stakerId) } else { r0 = ret.Get(0).(bindings.StructsStaker) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32) error); ok { - r1 = rf(ctx, client, stakerId) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32) error); ok { + r1 = rf(rpcParameters, stakerId) } else { r1 = ret.Error(1) } @@ -1516,23 +1688,23 @@ func (_m *Utils) GetStaker(ctx context.Context, client *ethclient.Client, staker return r0, r1 } -// GetStakerId provides a mock function with given fields: ctx, client, address -func (_m *Utils) GetStakerId(ctx context.Context, client *ethclient.Client, address string) (uint32, error) { - ret := _m.Called(ctx, client, address) +// GetStakerId provides a mock function with given fields: rpcParameters, address +func (_m *Utils) GetStakerId(rpcParameters RPC.RPCParameters, address string) (uint32, error) { + ret := _m.Called(rpcParameters, address) var r0 uint32 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, string) (uint32, error)); ok { - return rf(ctx, client, address) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, string) (uint32, error)); ok { + return rf(rpcParameters, address) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, string) uint32); ok { - r0 = rf(ctx, client, address) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, string) uint32); ok { + r0 = rf(rpcParameters, address) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, string) error); ok { - r1 = rf(ctx, client, address) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, string) error); ok { + r1 = rf(rpcParameters, address) } else { r1 = ret.Error(1) } @@ -1540,25 +1712,25 @@ func (_m *Utils) GetStakerId(ctx context.Context, client *ethclient.Client, addr return r0, r1 } -// GetStakerSRZRBalance provides a mock function with given fields: ctx, client, staker -func (_m *Utils) GetStakerSRZRBalance(ctx context.Context, client *ethclient.Client, staker bindings.StructsStaker) (*big.Int, error) { - ret := _m.Called(ctx, client, staker) +// GetStakerSRZRBalance provides a mock function with given fields: rpcParameters, staker +func (_m *Utils) GetStakerSRZRBalance(rpcParameters RPC.RPCParameters, staker bindings.StructsStaker) (*big.Int, error) { + ret := _m.Called(rpcParameters, staker) var r0 *big.Int var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, bindings.StructsStaker) (*big.Int, error)); ok { - return rf(ctx, client, staker) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, bindings.StructsStaker) (*big.Int, error)); ok { + return rf(rpcParameters, staker) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, bindings.StructsStaker) *big.Int); ok { - r0 = rf(ctx, client, staker) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, bindings.StructsStaker) *big.Int); ok { + r0 = rf(rpcParameters, staker) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, bindings.StructsStaker) error); ok { - r1 = rf(ctx, client, staker) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, bindings.StructsStaker) error); ok { + r1 = rf(rpcParameters, staker) } else { r1 = ret.Error(1) } @@ -1566,23 +1738,23 @@ func (_m *Utils) GetStakerSRZRBalance(ctx context.Context, client *ethclient.Cli return r0, r1 } -// GetStateBuffer provides a mock function with given fields: ctx, client -func (_m *Utils) GetStateBuffer(ctx context.Context, client *ethclient.Client) (uint64, error) { - ret := _m.Called(ctx, client) +// GetStateBuffer provides a mock function with given fields: rpcParameters +func (_m *Utils) GetStateBuffer(rpcParameters RPC.RPCParameters) (uint64, error) { + ret := _m.Called(rpcParameters) var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) (uint64, error)); ok { - return rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) (uint64, error)); ok { + return rf(rpcParameters) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) uint64); ok { - r0 = rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) uint64); ok { + r0 = rf(rpcParameters) } else { r0 = ret.Get(0).(uint64) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { - r1 = rf(ctx, client) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters) error); ok { + r1 = rf(rpcParameters) } else { r1 = ret.Error(1) } @@ -1606,25 +1778,25 @@ func (_m *Utils) GetTokenManager(client *ethclient.Client) *bindings.RAZOR { return r0 } -// GetTotalInfluenceRevealed provides a mock function with given fields: ctx, client, epoch, medianIndex -func (_m *Utils) GetTotalInfluenceRevealed(ctx context.Context, client *ethclient.Client, epoch uint32, medianIndex uint16) (*big.Int, error) { - ret := _m.Called(ctx, client, epoch, medianIndex) +// GetTotalInfluenceRevealed provides a mock function with given fields: rpcParameters, epoch, medianIndex +func (_m *Utils) GetTotalInfluenceRevealed(rpcParameters RPC.RPCParameters, epoch uint32, medianIndex uint16) (*big.Int, error) { + ret := _m.Called(rpcParameters, epoch, medianIndex) var r0 *big.Int var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, uint16) (*big.Int, error)); ok { - return rf(ctx, client, epoch, medianIndex) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32, uint16) (*big.Int, error)); ok { + return rf(rpcParameters, epoch, medianIndex) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, uint16) *big.Int); ok { - r0 = rf(ctx, client, epoch, medianIndex) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32, uint16) *big.Int); ok { + r0 = rf(rpcParameters, epoch, medianIndex) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32, uint16) error); ok { - r1 = rf(ctx, client, epoch, medianIndex) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32, uint16) error); ok { + r1 = rf(rpcParameters, epoch, medianIndex) } else { r1 = ret.Error(1) } @@ -1632,13 +1804,13 @@ func (_m *Utils) GetTotalInfluenceRevealed(ctx context.Context, client *ethclien return r0, r1 } -// GetTxnOpts provides a mock function with given fields: ctx, transactionData -func (_m *Utils) GetTxnOpts(ctx context.Context, transactionData types.TransactionOptions) *bind.TransactOpts { - ret := _m.Called(ctx, transactionData) +// GetTxnOpts provides a mock function with given fields: rpcParameters, transactionData +func (_m *Utils) GetTxnOpts(rpcParameters RPC.RPCParameters, transactionData types.TransactionOptions) *bind.TransactOpts { + ret := _m.Called(rpcParameters, transactionData) var r0 *bind.TransactOpts - if rf, ok := ret.Get(0).(func(context.Context, types.TransactionOptions) *bind.TransactOpts); ok { - r0 = rf(ctx, transactionData) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, types.TransactionOptions) *bind.TransactOpts); ok { + r0 = rf(rpcParameters, transactionData) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*bind.TransactOpts) @@ -1714,25 +1886,25 @@ func (_m *Utils) GetVoteManagerWithOpts(client *ethclient.Client) (*bindings.Vot return r0, r1 } -// GetVoteValue provides a mock function with given fields: ctx, client, epoch, stakerId, medianIndex -func (_m *Utils) GetVoteValue(ctx context.Context, client *ethclient.Client, epoch uint32, stakerId uint32, medianIndex uint16) (*big.Int, error) { - ret := _m.Called(ctx, client, epoch, stakerId, medianIndex) +// GetVoteValue provides a mock function with given fields: rpcParameters, epoch, stakerId, medianIndex +func (_m *Utils) GetVoteValue(rpcParameters RPC.RPCParameters, epoch uint32, stakerId uint32, medianIndex uint16) (*big.Int, error) { + ret := _m.Called(rpcParameters, epoch, stakerId, medianIndex) var r0 *big.Int var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, uint32, uint16) (*big.Int, error)); ok { - return rf(ctx, client, epoch, stakerId, medianIndex) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32, uint32, uint16) (*big.Int, error)); ok { + return rf(rpcParameters, epoch, stakerId, medianIndex) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, uint32, uint16) *big.Int); ok { - r0 = rf(ctx, client, epoch, stakerId, medianIndex) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32, uint32, uint16) *big.Int); ok { + r0 = rf(rpcParameters, epoch, stakerId, medianIndex) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32, uint32, uint16) error); ok { - r1 = rf(ctx, client, epoch, stakerId, medianIndex) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32, uint32, uint16) error); ok { + r1 = rf(rpcParameters, epoch, stakerId, medianIndex) } else { r1 = ret.Error(1) } @@ -1740,23 +1912,23 @@ func (_m *Utils) GetVoteValue(ctx context.Context, client *ethclient.Client, epo return r0, r1 } -// GetWithdrawInitiationPeriod provides a mock function with given fields: ctx, client -func (_m *Utils) GetWithdrawInitiationPeriod(ctx context.Context, client *ethclient.Client) (uint16, error) { - ret := _m.Called(ctx, client) +// GetWithdrawInitiationPeriod provides a mock function with given fields: rpcParameters +func (_m *Utils) GetWithdrawInitiationPeriod(rpcParameters RPC.RPCParameters) (uint16, error) { + ret := _m.Called(rpcParameters) var r0 uint16 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) (uint16, error)); ok { - return rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) (uint16, error)); ok { + return rf(rpcParameters) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) uint16); ok { - r0 = rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) uint16); ok { + r0 = rf(rpcParameters) } else { r0 = ret.Get(0).(uint16) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { - r1 = rf(ctx, client) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters) error); ok { + r1 = rf(rpcParameters) } else { r1 = ret.Error(1) } @@ -1764,25 +1936,25 @@ func (_m *Utils) GetWithdrawInitiationPeriod(ctx context.Context, client *ethcli return r0, r1 } -// HandleOfficialJobsFromJSONFile provides a mock function with given fields: client, collection, dataString, commitParams -func (_m *Utils) HandleOfficialJobsFromJSONFile(client *ethclient.Client, collection bindings.StructsCollection, dataString string, commitParams *types.CommitParams) ([]bindings.StructsJob, []uint16) { - ret := _m.Called(client, collection, dataString, commitParams) +// HandleOfficialJobsFromJSONFile provides a mock function with given fields: collection, dataString, commitParams +func (_m *Utils) HandleOfficialJobsFromJSONFile(collection bindings.StructsCollection, dataString string, commitParams *types.CommitParams) ([]bindings.StructsJob, []uint16) { + ret := _m.Called(collection, dataString, commitParams) var r0 []bindings.StructsJob var r1 []uint16 - if rf, ok := ret.Get(0).(func(*ethclient.Client, bindings.StructsCollection, string, *types.CommitParams) ([]bindings.StructsJob, []uint16)); ok { - return rf(client, collection, dataString, commitParams) + if rf, ok := ret.Get(0).(func(bindings.StructsCollection, string, *types.CommitParams) ([]bindings.StructsJob, []uint16)); ok { + return rf(collection, dataString, commitParams) } - if rf, ok := ret.Get(0).(func(*ethclient.Client, bindings.StructsCollection, string, *types.CommitParams) []bindings.StructsJob); ok { - r0 = rf(client, collection, dataString, commitParams) + if rf, ok := ret.Get(0).(func(bindings.StructsCollection, string, *types.CommitParams) []bindings.StructsJob); ok { + r0 = rf(collection, dataString, commitParams) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]bindings.StructsJob) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, bindings.StructsCollection, string, *types.CommitParams) []uint16); ok { - r1 = rf(client, collection, dataString, commitParams) + if rf, ok := ret.Get(1).(func(bindings.StructsCollection, string, *types.CommitParams) []uint16); ok { + r1 = rf(collection, dataString, commitParams) } else { if ret.Get(1) != nil { r1 = ret.Get(1).([]uint16) @@ -1906,23 +2078,47 @@ func (_m *Utils) SecondsToReadableTime(input int) string { return r0 } -// ToAssign provides a mock function with given fields: ctx, client -func (_m *Utils) ToAssign(ctx context.Context, client *ethclient.Client) (uint16, error) { - ret := _m.Called(ctx, client) +// StakerInfo provides a mock function with given fields: rpcParameters, stakerId +func (_m *Utils) StakerInfo(rpcParameters RPC.RPCParameters, stakerId uint32) (types.Staker, error) { + ret := _m.Called(rpcParameters, stakerId) + + var r0 types.Staker + var r1 error + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) (types.Staker, error)); ok { + return rf(rpcParameters, stakerId) + } + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, uint32) types.Staker); ok { + r0 = rf(rpcParameters, stakerId) + } else { + r0 = ret.Get(0).(types.Staker) + } + + if rf, ok := ret.Get(1).(func(RPC.RPCParameters, uint32) error); ok { + r1 = rf(rpcParameters, stakerId) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// ToAssign provides a mock function with given fields: rpcParameters +func (_m *Utils) ToAssign(rpcParameters RPC.RPCParameters) (uint16, error) { + ret := _m.Called(rpcParameters) var r0 uint16 var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) (uint16, error)); ok { - return rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) (uint16, error)); ok { + return rf(rpcParameters) } - if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) uint16); ok { - r0 = rf(ctx, client) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters) uint16); ok { + r0 = rf(rpcParameters) } else { r0 = ret.Get(0).(uint16) } - if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { - r1 = rf(ctx, client) + if rf, ok := ret.Get(1).(func(RPC.RPCParameters) error); ok { + r1 = rf(rpcParameters) } else { r1 = ret.Error(1) } @@ -1930,13 +2126,13 @@ func (_m *Utils) ToAssign(ctx context.Context, client *ethclient.Client) (uint16 return r0, r1 } -// WaitForBlockCompletion provides a mock function with given fields: client, hashToRead -func (_m *Utils) WaitForBlockCompletion(client *ethclient.Client, hashToRead string) error { - ret := _m.Called(client, hashToRead) +// WaitForBlockCompletion provides a mock function with given fields: rpcManager, hashToRead +func (_m *Utils) WaitForBlockCompletion(rpcManager RPC.RPCParameters, hashToRead string) error { + ret := _m.Called(rpcManager, hashToRead) var r0 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, string) error); ok { - r0 = rf(client, hashToRead) + if rf, ok := ret.Get(0).(func(RPC.RPCParameters, string) error); ok { + r0 = rf(rpcManager, hashToRead) } else { r0 = ret.Error(0) } diff --git a/utils/options.go b/utils/options.go index f7fe75367..246c6aaf6 100644 --- a/utils/options.go +++ b/utils/options.go @@ -4,12 +4,11 @@ import ( "context" "errors" "razor/core/types" + "razor/rpc" "strings" "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/ethclient" - "math/big" "github.com/ethereum/go-ethereum/accounts/abi/bind" @@ -25,7 +24,7 @@ func (*UtilsStruct) GetOptions() bind.CallOpts { } } -func (*UtilsStruct) GetTxnOpts(ctx context.Context, transactionData types.TransactionOptions) *bind.TransactOpts { +func (*UtilsStruct) GetTxnOpts(rpcParameters rpc.RPCParameters, transactionData types.TransactionOptions) *bind.TransactOpts { log.Debug("Getting transaction options...") account := transactionData.Account if account.AccountManager == nil { @@ -34,21 +33,21 @@ func (*UtilsStruct) GetTxnOpts(ctx context.Context, transactionData types.Transa privateKey, err := account.AccountManager.GetPrivateKey(account.Address, account.Password) CheckError("Error in fetching private key: ", err) - nonce, err := ClientInterface.GetNonceAtWithRetry(ctx, transactionData.Client, common.HexToAddress(account.Address)) + nonce, err := ClientInterface.GetNonceAtWithRetry(rpcParameters, common.HexToAddress(account.Address)) CheckError("Error in fetching nonce: ", err) - gasPrice := GasInterface.GetGasPrice(ctx, transactionData.Client, transactionData.Config) + gasPrice := GasInterface.GetGasPrice(rpcParameters, transactionData.Config) txnOpts, err := BindInterface.NewKeyedTransactorWithChainID(privateKey, transactionData.ChainId) CheckError("Error in getting transactor: ", err) txnOpts.Nonce = big.NewInt(int64(nonce)) txnOpts.GasPrice = gasPrice txnOpts.Value = transactionData.EtherValue - gasLimit, err := GasInterface.GetGasLimit(ctx, transactionData, txnOpts) + gasLimit, err := GasInterface.GetGasLimit(rpcParameters, transactionData, txnOpts) if err != nil { errString := err.Error() if ContainsStringFromArray(errString, []string{"500", "501", "502", "503", "504"}) || errString == errors.New("intrinsic gas too low").Error() { - latestBlock, err := ClientInterface.GetLatestBlockWithRetry(ctx, transactionData.Client) + latestBlock, err := ClientInterface.GetLatestBlockWithRetry(rpcParameters) CheckError("Error in fetching block: ", err) txnOpts.GasLimit = latestBlock.GasLimit @@ -63,7 +62,7 @@ func (*UtilsStruct) GetTxnOpts(ctx context.Context, transactionData types.Transa return txnOpts } -func (*GasStruct) GetGasPrice(ctx context.Context, client *ethclient.Client, config types.Configurations) *big.Int { +func (*GasStruct) GetGasPrice(rpcParameters rpc.RPCParameters, config types.Configurations) *big.Int { var gas *big.Int if config.GasPrice != 0 { gas = big.NewInt(1).Mul(big.NewInt(int64(config.GasPrice)), big.NewInt(1e9)) @@ -71,7 +70,7 @@ func (*GasStruct) GetGasPrice(ctx context.Context, client *ethclient.Client, con gas = big.NewInt(0) } var err error - suggestedGasPrice, err := ClientInterface.SuggestGasPriceWithRetry(ctx, client) + suggestedGasPrice, err := ClientInterface.SuggestGasPriceWithRetry(rpcParameters) if err != nil { log.Error(err) return UtilsInterface.MultiplyFloatAndBigInt(gas, float64(config.GasMultiplier)) @@ -86,7 +85,7 @@ func (*GasStruct) GetGasPrice(ctx context.Context, client *ethclient.Client, con return gasPrice } -func (*GasStruct) GetGasLimit(ctx context.Context, transactionData types.TransactionOptions, txnOpts *bind.TransactOpts) (uint64, error) { +func (*GasStruct) GetGasLimit(rpcParameters rpc.RPCParameters, transactionData types.TransactionOptions, txnOpts *bind.TransactOpts) (uint64, error) { if transactionData.MethodName == "" { return 0, nil } @@ -110,14 +109,14 @@ func (*GasStruct) GetGasLimit(ctx context.Context, transactionData types.Transac } var gasLimit uint64 if transactionData.MethodName == "reveal" { - gasLimit, err = getGasLimitForReveal(ctx, transactionData.Client) + gasLimit, err = getGasLimitForReveal(rpcParameters) if err != nil { log.Error("GetGasLimit: Error in getting gasLimit for reveal transaction: ", err) return transactionData.Config.GasLimitOverride, err } log.Debug("Calculated gas limit for reveal: ", gasLimit) } else { - gasLimit, err = ClientInterface.EstimateGasWithRetry(ctx, transactionData.Client, msg) + gasLimit, err = ClientInterface.EstimateGasWithRetry(rpcParameters, msg) if err != nil { log.Error("GetGasLimit: Error in getting gasLimit: ", err) //If estimateGas throws an error for a transaction than gasLimit should be picked up from the config @@ -126,17 +125,17 @@ func (*GasStruct) GetGasLimit(ctx context.Context, transactionData types.Transac } log.Debug("Estimated Gas: ", gasLimit) } - return GasInterface.IncreaseGasLimitValue(ctx, transactionData.Client, gasLimit, transactionData.Config.GasLimitMultiplier) + return GasInterface.IncreaseGasLimitValue(rpcParameters, gasLimit, transactionData.Config.GasLimitMultiplier) } -func (*GasStruct) IncreaseGasLimitValue(ctx context.Context, client *ethclient.Client, gasLimit uint64, gasLimitMultiplier float32) (uint64, error) { +func (*GasStruct) IncreaseGasLimitValue(rpcParameters rpc.RPCParameters, gasLimit uint64, gasLimitMultiplier float32) (uint64, error) { if gasLimit == 0 || gasLimitMultiplier <= 0 { return gasLimit, nil } gasLimitIncremented := float64(gasLimitMultiplier) * float64(gasLimit) gasLimit = uint64(gasLimitIncremented) - latestBlock, err := ClientInterface.GetLatestBlockWithRetry(ctx, client) + latestBlock, err := ClientInterface.GetLatestBlockWithRetry(rpcParameters) if err != nil { log.Error("Error in fetching block: ", err) return 0, err @@ -149,8 +148,8 @@ func (*GasStruct) IncreaseGasLimitValue(ctx context.Context, client *ethclient.C return gasLimit, nil } -func getGasLimitForReveal(ctx context.Context, client *ethclient.Client) (uint64, error) { - toAssign, err := UtilsInterface.ToAssign(ctx, client) +func getGasLimitForReveal(rpcParameters rpc.RPCParameters) (uint64, error) { + toAssign, err := UtilsInterface.ToAssign(rpcParameters) if err != nil { return 0, err } diff --git a/utils/options_test.go b/utils/options_test.go index 7e530e451..7099d4c6d 100644 --- a/utils/options_test.go +++ b/utils/options_test.go @@ -17,13 +17,10 @@ import ( "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/accounts/abi/bind" Types "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethclient" "github.com/stretchr/testify/mock" ) func Test_getGasPrice(t *testing.T) { - var client *ethclient.Client - type args struct { suggestedGasPrice *big.Int suggestedGasPriceErr error @@ -103,16 +100,16 @@ func Test_getGasPrice(t *testing.T) { }, } - defer func() { log.ExitFunc = nil }() + defer func() { log.LogrusInstance.ExitFunc = nil }() var fatal bool - log.ExitFunc = func(int) { fatal = true } + log.LogrusInstance.ExitFunc = func(int) { fatal = true } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { UtilsMock := new(mocks.Utils) clientUtilsMock := new(mocks.ClientUtils) - clientUtilsMock.On("SuggestGasPriceWithRetry", mock.Anything, mock.Anything).Return(tt.args.suggestedGasPrice, tt.args.suggestedGasPriceErr) + clientUtilsMock.On("SuggestGasPriceWithRetry", mock.Anything).Return(tt.args.suggestedGasPrice, tt.args.suggestedGasPriceErr) UtilsMock.On("MultiplyFloatAndBigInt", mock.AnythingOfType("*big.Int"), mock.AnythingOfType("float64")).Return(tt.args.multipliedGasPrice) fatal = false @@ -123,7 +120,7 @@ func Test_getGasPrice(t *testing.T) { } StartRazor(optionsPackageStruct) gasUtils := GasStruct{} - got := gasUtils.GetGasPrice(context.Background(), client, tt.args.config) + got := gasUtils.GetGasPrice(rpcParameters, tt.args.config) if fatal != tt.expectedFatal { if got.Cmp(tt.want) != 0 { t.Errorf("getGasPrice() = %v, want %v", got, tt.want) @@ -255,15 +252,15 @@ func Test_utils_GetTxnOpts(t *testing.T) { }, } - originalExitFunc := log.ExitFunc // Preserve the original ExitFunc - defer func() { log.ExitFunc = originalExitFunc }() // Ensure it's reset after tests + originalExitFunc := log.LogrusInstance.ExitFunc // Preserve the original ExitFunc + defer func() { log.LogrusInstance.ExitFunc = originalExitFunc }() // Ensure it's reset after tests for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { fatalOccurred := false // Override log.ExitFunc to induce a panic for testing the fatal scenario - log.ExitFunc = func(int) { panic("log.Fatal called") } + log.LogrusInstance.ExitFunc = func(int) { panic("log.Fatal called") } var account types.Account accountManager := accounts.NewAccountManager("test_accounts") @@ -291,12 +288,12 @@ func Test_utils_GetTxnOpts(t *testing.T) { utils := StartRazor(optionsPackageStruct) - clientMock.On("GetNonceAtWithRetry", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.nonce, tt.args.nonceErr) - gasMock.On("GetGasPrice", mock.Anything, mock.Anything, mock.Anything).Return(gasPrice) + clientMock.On("GetNonceAtWithRetry", mock.Anything, mock.Anything).Return(tt.args.nonce, tt.args.nonceErr) + gasMock.On("GetGasPrice", mock.Anything, mock.Anything).Return(gasPrice) bindMock.On("NewKeyedTransactorWithChainID", mock.AnythingOfType("*ecdsa.PrivateKey"), mock.AnythingOfType("*big.Int")).Return(tt.args.txnOpts, tt.args.txnOptsErr) gasMock.On("GetGasLimit", mock.Anything, transactionData, txnOpts).Return(tt.args.gasLimit, tt.args.gasLimitErr) utilsMock.On("MultiplyFloatAndBigInt", mock.AnythingOfType("*big.Int"), mock.AnythingOfType("float64")).Return(big.NewInt(1)) - clientMock.On("GetLatestBlockWithRetry", mock.Anything, mock.Anything).Return(tt.args.latestHeader, tt.args.latestHeaderErr) + clientMock.On("GetLatestBlockWithRetry", mock.Anything).Return(tt.args.latestHeader, tt.args.latestHeaderErr) // Defer a function to recover from the panic and check if it matches the expectedFatal condition defer func() { @@ -318,7 +315,7 @@ func Test_utils_GetTxnOpts(t *testing.T) { } }() - got := utils.GetTxnOpts(context.Background(), transactionData) + got := utils.GetTxnOpts(rpcParameters, transactionData) if !tt.expectedFatal && fatalOccurred { t.Fatalf("Test exited due to an unexpected fatal condition") } @@ -479,12 +476,12 @@ func TestUtilsStruct_GetGasLimit(t *testing.T) { abiMock.On("Parse", reader).Return(tt.args.parsedData, tt.args.parseErr) abiMock.On("Pack", parsedData, mock.AnythingOfType("string"), mock.Anything).Return(tt.args.inputData, tt.args.packErr) - clientUtilsMock.On("EstimateGasWithRetry", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.gasLimit, tt.args.gasLimitErr) - gasUtilsMock.On("IncreaseGasLimitValue", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.increaseGasLimit, tt.args.increaseGasLimitErr) - utilsMock.On("ToAssign", mock.Anything, mock.Anything).Return(tt.args.toAssign, tt.args.toAssignErr) + clientUtilsMock.On("EstimateGasWithRetry", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.gasLimit, tt.args.gasLimitErr) + gasUtilsMock.On("IncreaseGasLimitValue", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.increaseGasLimit, tt.args.increaseGasLimitErr) + utilsMock.On("ToAssign", mock.Anything).Return(tt.args.toAssign, tt.args.toAssignErr) gasUtils := GasStruct{} - got, err := gasUtils.GetGasLimit(context.Background(), tt.args.transactionData, txnOpts) + got, err := gasUtils.GetGasLimit(rpcParameters, tt.args.transactionData, txnOpts) if got != tt.want { t.Errorf("getGasLimit() got = %v, want %v", got, tt.want) } @@ -502,8 +499,6 @@ func TestUtilsStruct_GetGasLimit(t *testing.T) { } func TestUtilsStruct_IncreaseGasLimitValue(t *testing.T) { - var client *ethclient.Client - type args struct { gasLimit uint64 gasLimitMultiplier float32 @@ -582,7 +577,7 @@ func TestUtilsStruct_IncreaseGasLimitValue(t *testing.T) { clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything, mock.Anything).Return(tt.args.latestBlock, tt.args.blockErr) gasUtils := GasStruct{} - got, err := gasUtils.IncreaseGasLimitValue(context.Background(), client, tt.args.gasLimit, tt.args.gasLimitMultiplier) + got, err := gasUtils.IncreaseGasLimitValue(rpcParameters, tt.args.gasLimit, tt.args.gasLimitMultiplier) if got != tt.want { t.Errorf("increaseGasLimitValue() got = %v, want %v", got, tt.want) } diff --git a/utils/stake.go b/utils/stake.go index c11a55a21..4cb499b6b 100644 --- a/utils/stake.go +++ b/utils/stake.go @@ -1,10 +1,10 @@ package utils import ( - "context" "math/big" "razor/core/types" "razor/pkg/bindings" + "razor/rpc" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" @@ -15,16 +15,16 @@ func (*UtilsStruct) GetStakeManagerWithOpts(client *ethclient.Client) (*bindings return UtilsInterface.GetStakeManager(client), UtilsInterface.GetOptions() } -func (*UtilsStruct) GetStakerId(ctx context.Context, client *ethclient.Client, address string) (uint32, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, StakeManagerInterface, "GetStakerId", client, common.HexToAddress(address)) +func (*UtilsStruct) GetStakerId(rpcParameters rpc.RPCParameters, address string) (uint32, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, StakeManagerInterface, "GetStakerId", common.HexToAddress(address)) if err != nil { return 0, err } return returnedValues[0].Interface().(uint32), nil } -func (*UtilsStruct) GetStake(ctx context.Context, client *ethclient.Client, stakerId uint32) (*big.Int, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, StakeManagerInterface, "GetStaker", client, stakerId) +func (*UtilsStruct) GetStake(rpcParameters rpc.RPCParameters, stakerId uint32) (*big.Int, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, StakeManagerInterface, "GetStaker", stakerId) if err != nil { return nil, err } @@ -32,62 +32,86 @@ func (*UtilsStruct) GetStake(ctx context.Context, client *ethclient.Client, stak return staker.Stake, nil } -func (*UtilsStruct) GetStaker(ctx context.Context, client *ethclient.Client, stakerId uint32) (bindings.StructsStaker, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, StakeManagerInterface, "GetStaker", client, stakerId) +func (*UtilsStruct) GetStaker(rpcParameters rpc.RPCParameters, stakerId uint32) (bindings.StructsStaker, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, StakeManagerInterface, "GetStaker", stakerId) if err != nil { return bindings.StructsStaker{}, err } return returnedValues[0].Interface().(bindings.StructsStaker), nil } -func (*UtilsStruct) GetNumberOfStakers(ctx context.Context, client *ethclient.Client) (uint32, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, StakeManagerInterface, "GetNumStakers", client) +func (*UtilsStruct) GetNumberOfStakers(rpcParameters rpc.RPCParameters) (uint32, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, StakeManagerInterface, "GetNumStakers") if err != nil { return 0, err } return returnedValues[0].Interface().(uint32), nil } -func (*UtilsStruct) GetLock(ctx context.Context, client *ethclient.Client, address string, stakerId uint32, lockType uint8) (types.Locks, error) { - staker, err := UtilsInterface.GetStaker(ctx, client, stakerId) +func (*UtilsStruct) GetLock(rpcParameters rpc.RPCParameters, address string, stakerId uint32, lockType uint8) (types.Locks, error) { + staker, err := UtilsInterface.GetStaker(rpcParameters, stakerId) if err != nil { return types.Locks{}, err } - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, StakeManagerInterface, "Locks", client, common.HexToAddress(address), staker.TokenAddress, lockType) + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, StakeManagerInterface, "Locks", common.HexToAddress(address), staker.TokenAddress, lockType) if err != nil { return types.Locks{}, err } return returnedValues[0].Interface().(types.Locks), nil } -func (*UtilsStruct) GetWithdrawInitiationPeriod(ctx context.Context, client *ethclient.Client) (uint16, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, StakeManagerInterface, "WithdrawInitiationPeriod", client) +func (*UtilsStruct) GetWithdrawInitiationPeriod(rpcParameters rpc.RPCParameters) (uint16, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, StakeManagerInterface, "WithdrawInitiationPeriod") if err != nil { return 0, err } return returnedValues[0].Interface().(uint16), nil } -func (*UtilsStruct) GetMaxCommission(ctx context.Context, client *ethclient.Client) (uint8, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, StakeManagerInterface, "MaxCommission", client) +func (*UtilsStruct) GetMaxCommission(rpcParameters rpc.RPCParameters) (uint8, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, StakeManagerInterface, "MaxCommission") if err != nil { return 0, err } return returnedValues[0].Interface().(uint8), nil } -func (*UtilsStruct) GetEpochLimitForUpdateCommission(ctx context.Context, client *ethclient.Client) (uint16, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, StakeManagerInterface, "EpochLimitForUpdateCommission", client) +func (*UtilsStruct) GetEpochLimitForUpdateCommission(rpcParameters rpc.RPCParameters) (uint16, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, StakeManagerInterface, "EpochLimitForUpdateCommission") if err != nil { return 0, err } return returnedValues[0].Interface().(uint16), nil } -func (*UtilsStruct) GetMinSafeRazor(ctx context.Context, client *ethclient.Client) (*big.Int, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, StakeManagerInterface, "MinSafeRazor", client) +func (*UtilsStruct) GetMinSafeRazor(rpcParameters rpc.RPCParameters) (*big.Int, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, StakeManagerInterface, "MinSafeRazor") if err != nil { return nil, err } return returnedValues[0].Interface().(*big.Int), nil } + +func (*UtilsStruct) StakerInfo(rpcParameters rpc.RPCParameters, stakerId uint32) (types.Staker, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, StakeManagerInterface, "StakerInfo", stakerId) + if err != nil { + return types.Staker{}, err + } + return returnedValues[0].Interface().(types.Staker), nil +} + +func (*UtilsStruct) GetMaturity(rpcParameters rpc.RPCParameters, age uint32) (uint16, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, StakeManagerInterface, "GetMaturity", age) + if err != nil { + return 0, err + } + return returnedValues[0].Interface().(uint16), nil +} + +func (*UtilsStruct) GetBountyLock(rpcParameters rpc.RPCParameters, bountyId uint32) (types.BountyLock, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, StakeManagerInterface, "GetBountyLock", bountyId) + if err != nil { + return types.BountyLock{}, err + } + return returnedValues[0].Interface().(types.BountyLock), nil +} diff --git a/utils/stake_test.go b/utils/stake_test.go index a78f12276..6f02cae73 100644 --- a/utils/stake_test.go +++ b/utils/stake_test.go @@ -1,8 +1,8 @@ package utils import ( - "context" "errors" + "github.com/ethereum/go-ethereum/common" "math/big" "razor/core/types" "razor/pkg/bindings" @@ -17,7 +17,6 @@ import ( ) func TestGetEpochLimitForUpdateCommission(t *testing.T) { - var client *ethclient.Client var callOpts bind.CallOpts type args struct { @@ -64,7 +63,7 @@ func TestGetEpochLimitForUpdateCommission(t *testing.T) { stakeManagerMock.On("EpochLimitForUpdateCommission", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.epochLimitForUpdateCommission, tt.args.epochLimitForUpdateCommissionErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetEpochLimitForUpdateCommission(context.Background(), client) + got, err := utils.GetEpochLimitForUpdateCommission(rpcParameters) if (err != nil) != tt.wantErr { t.Errorf("GetEpochLimitForUpdateCommission() error = %v, wantErr %v", err, tt.wantErr) return @@ -78,7 +77,6 @@ func TestGetEpochLimitForUpdateCommission(t *testing.T) { func TestGetLock(t *testing.T) { var ( - client *ethclient.Client address string stakerId uint32 lockType uint8 @@ -136,11 +134,11 @@ func TestGetLock(t *testing.T) { } utils := StartRazor(optionsPackageStruct) - utilsMock.On("GetStaker", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.staker, tt.args.stakerErr) + utilsMock.On("GetStaker", mock.Anything, mock.Anything).Return(tt.args.staker, tt.args.stakerErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) stakeManagerMock.On("Locks", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.AnythingOfType("uint8")).Return(tt.args.locks, tt.args.locksErr) - got, err := utils.GetLock(context.Background(), client, address, stakerId, lockType) + got, err := utils.GetLock(rpcParameters, address, stakerId, lockType) if (err != nil) != tt.wantErr { t.Errorf("GetLock() error = %v, wantErr %v", err, tt.wantErr) return @@ -153,8 +151,6 @@ func TestGetLock(t *testing.T) { } func TestGetMaxCommission(t *testing.T) { - var client *ethclient.Client - type args struct { maxCommission uint8 maxCommissionErr error @@ -198,7 +194,7 @@ func TestGetMaxCommission(t *testing.T) { stakeManagerMock.On("MaxCommission", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.maxCommission, tt.args.maxCommissionErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetMaxCommission(context.Background(), client) + got, err := utils.GetMaxCommission(rpcParameters) if (err != nil) != tt.wantErr { t.Errorf("GetMaxCommission() error = %v, wantErr %v", err, tt.wantErr) return @@ -211,8 +207,6 @@ func TestGetMaxCommission(t *testing.T) { } func TestGetNumberOfStakers(t *testing.T) { - var client *ethclient.Client - type args struct { numStakers uint32 numStakersErr error @@ -256,7 +250,7 @@ func TestGetNumberOfStakers(t *testing.T) { stakeManagerMock.On("GetNumStakers", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.numStakers, tt.args.numStakersErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetNumberOfStakers(context.Background(), client) + got, err := utils.GetNumberOfStakers(rpcParameters) if (err != nil) != tt.wantErr { t.Errorf("GetNumberOfStakers() error = %v, wantErr %v", err, tt.wantErr) return @@ -269,7 +263,6 @@ func TestGetNumberOfStakers(t *testing.T) { } func TestGetStake(t *testing.T) { - var client *ethclient.Client var stakerId uint32 type args struct { @@ -315,7 +308,7 @@ func TestGetStake(t *testing.T) { stakeManagerMock.On("GetStaker", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.staker, tt.args.stakerErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetStake(context.Background(), client, stakerId) + got, err := utils.GetStake(rpcParameters, stakerId) if (err != nil) != tt.wantErr { t.Errorf("GetStake() error = %v, wantErr %v", err, tt.wantErr) return @@ -328,7 +321,6 @@ func TestGetStake(t *testing.T) { } func TestGetStaker(t *testing.T) { - var client *ethclient.Client var stakerId uint32 type args struct { @@ -374,7 +366,7 @@ func TestGetStaker(t *testing.T) { stakeManagerMock.On("GetStaker", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.staker, tt.args.stakerErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetStaker(context.Background(), client, stakerId) + got, err := utils.GetStaker(rpcParameters, stakerId) if (err != nil) != tt.wantErr { t.Errorf("GetStaker() error = %v, wantErr %v", err, tt.wantErr) return @@ -387,7 +379,6 @@ func TestGetStaker(t *testing.T) { } func TestGetStakerId(t *testing.T) { - var client *ethclient.Client var account string type args struct { @@ -433,7 +424,7 @@ func TestGetStakerId(t *testing.T) { stakeManagerMock.On("GetStakerId", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetStakerId(context.Background(), client, account) + got, err := utils.GetStakerId(rpcParameters, account) if (err != nil) != tt.wantErr { t.Errorf("GetStakerId() error = %v, wantErr %v", err, tt.wantErr) return @@ -446,8 +437,6 @@ func TestGetStakerId(t *testing.T) { } func TestGetWithdrawReleasePeriod(t *testing.T) { - var client *ethclient.Client - type args struct { withdrawReleasePeriod uint16 withdrawReleasePeriodErr error @@ -491,7 +480,7 @@ func TestGetWithdrawReleasePeriod(t *testing.T) { stakeManagerMock.On("WithdrawInitiationPeriod", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.withdrawReleasePeriod, tt.args.withdrawReleasePeriodErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetWithdrawInitiationPeriod(context.Background(), client) + got, err := utils.GetWithdrawInitiationPeriod(rpcParameters) if (err != nil) != tt.wantErr { t.Errorf("GetWithdrawInitiationPeriod() error = %v, wantErr %v", err, tt.wantErr) return @@ -528,7 +517,6 @@ func TestGetStakeManagerWithOpts(t *testing.T) { } func TestGetMinSafeRazor(t *testing.T) { - var client *ethclient.Client type args struct { minSafeRazor *big.Int minSafeRazorErr error @@ -570,7 +558,7 @@ func TestGetMinSafeRazor(t *testing.T) { stakeManagerMock.On("MinSafeRazor", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.minSafeRazor, tt.args.minSafeRazorErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetMinSafeRazor(context.Background(), client) + got, err := utils.GetMinSafeRazor(rpcParameters) if (err != nil) != tt.wantErr { t.Errorf("GetMinSafeRazor() error = %v, wantErr %v", err, tt.wantErr) return @@ -581,3 +569,173 @@ func TestGetMinSafeRazor(t *testing.T) { }) } } + +func TestStakerInfo(t *testing.T) { + type args struct { + staker types.Staker + stakerErr error + } + tests := []struct { + name string + args args + want types.Staker + wantErr bool + }{ + { + name: "Test 1: When StakerInfo() executes successfully", + args: args{ + staker: types.Staker{ + Id: 1, + }, + }, + want: types.Staker{ + Id: 1, + }, + wantErr: false, + }, + { + name: "Test 2: When there is an error in getting staker info", + args: args{ + stakerErr: errors.New("staker info error"), + }, + want: types.Staker{}, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + retryMock := new(mocks.RetryUtils) + stakeManagerMock := new(mocks.StakeManagerUtils) + + optionsPackageStruct := OptionsPackageStruct{ + RetryInterface: retryMock, + StakeManagerInterface: stakeManagerMock, + } + utils := StartRazor(optionsPackageStruct) + + stakeManagerMock.On("StakerInfo", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.staker, tt.args.stakerErr) + retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) + + got, err := utils.StakerInfo(rpcParameters, 1) + if (err != nil) != tt.wantErr { + t.Errorf("StakerInfo() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("StakerInfo() got = %v, want %v", got, tt.want) + } + }) + } +} + +func TestGetMaturity(t *testing.T) { + type args struct { + maturity uint16 + maturityErr error + } + tests := []struct { + name string + args args + want uint16 + wantErr bool + }{ + { + name: "Test 1: When GetMaturity() executes successfully", + args: args{ + maturity: 100, + }, + want: 100, + wantErr: false, + }, + { + name: "Test 2: When there is an error in getting maturity", + args: args{ + maturityErr: errors.New("maturity error"), + }, + want: 0, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + retryMock := new(mocks.RetryUtils) + stakeManagerMock := new(mocks.StakeManagerUtils) + + optionsPackageStruct := OptionsPackageStruct{ + RetryInterface: retryMock, + StakeManagerInterface: stakeManagerMock, + } + utils := StartRazor(optionsPackageStruct) + + stakeManagerMock.On("GetMaturity", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.maturity, tt.args.maturityErr) + retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) + + got, err := utils.GetMaturity(rpcParameters, 10) + if (err != nil) != tt.wantErr { + t.Errorf("GetMaturity() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("GetMaturity() got = %v, want %v", got, tt.want) + } + }) + } +} + +func TestGetBountyLock(t *testing.T) { + type args struct { + bountyLock types.BountyLock + bountyLockErr error + } + tests := []struct { + name string + args args + want types.BountyLock + wantErr bool + }{ + { + name: "Test 1: When GetBountyLock() executes successfully", + args: args{ + bountyLock: types.BountyLock{ + BountyHunter: common.HexToAddress("0xaA"), + }, + }, + want: types.BountyLock{ + BountyHunter: common.HexToAddress("0xaA"), + }, + wantErr: false, + }, + { + name: "Test 2: When there is an error in getting bounty lock", + args: args{ + bountyLockErr: errors.New("bounty lock error"), + }, + want: types.BountyLock{}, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + retryMock := new(mocks.RetryUtils) + stakeManagerMock := new(mocks.StakeManagerUtils) + + optionsPackageStruct := OptionsPackageStruct{ + RetryInterface: retryMock, + StakeManagerInterface: stakeManagerMock, + } + utils := StartRazor(optionsPackageStruct) + + stakeManagerMock.On("GetBountyLock", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.bountyLock, tt.args.bountyLockErr) + retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) + + got, err := utils.GetBountyLock(rpcParameters, 1) + if (err != nil) != tt.wantErr { + t.Errorf("GetBountyLock() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBountyLock() got = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/utils/stakedToken.go b/utils/stakedToken.go index dabdab283..3546c15a8 100644 --- a/utils/stakedToken.go +++ b/utils/stakedToken.go @@ -1,20 +1,20 @@ package utils import ( - "context" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" "math/big" "razor/pkg/bindings" + "razor/rpc" ) func (*UtilsStruct) GetStakedTokenManagerWithOpts(client *ethclient.Client, tokenAddress common.Address) (*bindings.StakedToken, bind.CallOpts) { return UtilsInterface.GetStakedToken(client, tokenAddress), UtilsInterface.GetOptions() } -func (*UtilsStruct) GetStakerSRZRBalance(ctx context.Context, client *ethclient.Client, staker bindings.StructsStaker) (*big.Int, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, StakedTokenInterface, "BalanceOf", client, staker.TokenAddress, staker.Address) +func (*UtilsStruct) GetStakerSRZRBalance(rpcParameters rpc.RPCParameters, staker bindings.StructsStaker) (*big.Int, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, StakedTokenInterface, "BalanceOf", staker.TokenAddress, staker.Address) if err != nil { log.Error("Error in getting sRZRBalance: ", err) return nil, err diff --git a/utils/stakedToken_test.go b/utils/stakedToken_test.go index caa0e7fd4..5fe5d9842 100644 --- a/utils/stakedToken_test.go +++ b/utils/stakedToken_test.go @@ -1,10 +1,8 @@ package utils import ( - "context" "errors" "github.com/avast/retry-go" - "github.com/ethereum/go-ethereum/ethclient" "github.com/stretchr/testify/mock" "math/big" "razor/pkg/bindings" @@ -14,11 +12,7 @@ import ( ) func TestGetStakerSRZRBalance(t *testing.T) { - var ( - client *ethclient.Client - staker bindings.StructsStaker - ) - + var staker bindings.StructsStaker type args struct { sRZR *big.Int sRZRErr error @@ -62,7 +56,7 @@ func TestGetStakerSRZRBalance(t *testing.T) { stakedTokenMock.On("BalanceOf", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.sRZR, tt.args.sRZRErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetStakerSRZRBalance(context.Background(), client, staker) + got, err := utils.GetStakerSRZRBalance(rpcParameters, staker) if (err != nil) != tt.wantErr { t.Errorf("GetStakerSRZRBalance() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/utils/struct-utils.go b/utils/struct-utils.go index 216e85114..839e78554 100644 --- a/utils/struct-utils.go +++ b/utils/struct-utils.go @@ -9,12 +9,13 @@ import ( "io/fs" "math/big" "os" - "razor/client" "razor/core" coretypes "razor/core/types" "razor/path" "razor/pkg/bindings" + "razor/rpc" "reflect" + "strings" "time" "github.com/avast/retry-go" @@ -110,30 +111,37 @@ func CheckIfAnyError(result []reflect.Value) error { return nil } -func InvokeFunctionWithRetryAttempts(ctx context.Context, interfaceName interface{}, methodName string, args ...interface{}) ([]reflect.Value, error) { +func InvokeFunctionWithRetryAttempts(rpcParameters rpc.RPCParameters, interfaceName interface{}, methodName string, args ...interface{}) ([]reflect.Value, error) { var returnedValues []reflect.Value var err error var contextError bool - inputs := make([]reflect.Value, len(args)) - for i := range args { - inputs[i] = reflect.ValueOf(args[i]) + + // Ensure inputs has space for the client and any additional arguments + inputs := make([]reflect.Value, len(args)+1) + + // Always use the current best client for each retry + client, err := rpcParameters.RPCManager.GetBestRPCClient() + if err != nil { + log.Errorf("Failed to get current best client: %v", err) + return returnedValues, err } - alternateProvider := client.GetAlternateProvider() - switchToAlternateClient := client.GetSwitchToAlternateClientStatus() - if switchToAlternateClient && alternateProvider != "" { - // Changing client argument to alternate client - log.Debug("Making this RPC call using alternate RPC provider!") - inputs = client.ReplaceClientWithAlternateClient(inputs) + + // Set the client as the first argument + inputs[0] = reflect.ValueOf(client) + // Add the rest of the args to inputs starting from index 1 + for i := 0; i < len(args); i++ { + inputs[i+1] = reflect.ValueOf(args[i]) } + err = retry.Do( func() error { // Check if the context has been cancelled or timed out select { - case <-ctx.Done(): + case <-rpcParameters.Ctx.Done(): // If context is done, return the context error timeout log.Debugf("Context timed out for method: %s", methodName) contextError = true - return retry.Unrecoverable(ctx.Err()) + return retry.Unrecoverable(rpcParameters.Ctx.Err()) default: // Proceed with the RPC call returnedValues = reflect.ValueOf(interfaceName).MethodByName(methodName).Call(inputs) @@ -148,20 +156,67 @@ func InvokeFunctionWithRetryAttempts(ctx context.Context, interfaceName interfac }, RetryInterface.RetryAttempts(core.MaxRetries), retry.Delay(time.Second*time.Duration(core.RetryDelayDuration)), retry.DelayType(retry.FixedDelay)) if err != nil { if contextError { - // Skip the alternate client switch when the error is context-related - log.Warnf("Skipping alternate client switch due to context error: %v", err) + // If context error, we don't switch the client + log.Warnf("Skipping switching to the next best client due to context error: %v", err) return returnedValues, err } - if !switchToAlternateClient && alternateProvider != "" { + + // Only switch to the next best client if the error is identified as an RPC error + if isRPCError(err) { log.Errorf("%v error after retries: %v", methodName, err) - log.Info("Switching RPC to alternate RPC") - client.SetSwitchToAlternateClientStatus(true) - go client.StartTimerForAlternateClient(core.SwitchClientDuration) + log.Info("Attempting to switch to a new best RPC endpoint...") + + switched, switchErr := rpcParameters.RPCManager.SwitchToNextBestRPCClient() + if switchErr != nil { + log.Errorf("Failed to switch to the next best client: %v", switchErr) + return returnedValues, switchErr + } + + if switched { + log.Infof("Successfully switched to a new RPC endpoint after RPC error.") + } else { + log.Warnf("No switch occurred. Retaining the current RPC client.") + } } } + return returnedValues, err } +func isRPCError(err error) bool { + // Check for common RPC error patterns + if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) { + return true + } + + // Add other checks based on specific RPC errors (timeouts, connection issues, etc.) + if strings.Contains(err.Error(), "connection refused") || + strings.Contains(err.Error(), "connection reset by peer") || + strings.Contains(err.Error(), "EOF") || + strings.Contains(err.Error(), "dial") || + strings.Contains(err.Error(), "no such host") || + strings.Contains(err.Error(), "i/o timeout") { + return true + } + + // Check for HTTP 500–504 errors + if strings.Contains(err.Error(), "500") || + strings.Contains(err.Error(), "501") || + strings.Contains(err.Error(), "502") || + strings.Contains(err.Error(), "503") || + strings.Contains(err.Error(), "504") { + return true + } + + // Check for the custom RPC timeout error + if strings.Contains(err.Error(), "RPC timeout error") { + return true + } + + // If it's not an RPC error, return false + return false +} + func (b BlockManagerStruct) GetBlockIndexToBeConfirmed(client *ethclient.Client) (int8, error) { blockManager, opts := UtilsInterface.GetBlockManagerWithOpts(client) returnedValues := InvokeFunctionWithTimeout(blockManager, "BlockIndexToBeConfirmed", &opts) @@ -357,6 +412,22 @@ func (b BlockManagerStruct) GetConfirmedBlocks(client *ethclient.Client, epoch u }), nil } +func (b BlockManagerStruct) Disputes(client *ethclient.Client, epoch uint32, address common.Address) (coretypes.DisputesStruct, error) { + blockManager, opts := UtilsInterface.GetBlockManagerWithOpts(client) + returnedValues := InvokeFunctionWithTimeout(blockManager, "Disputes", &opts, epoch, address) + returnedError := CheckIfAnyError(returnedValues) + if returnedError != nil { + return coretypes.DisputesStruct{}, returnedError + } + disputesMapping := returnedValues[0].Interface().(struct { + LeafId uint16 + LastVisitedValue *big.Int + AccWeight *big.Int + Median *big.Int + }) + return disputesMapping, nil +} + func (s StakeManagerStruct) GetStakerId(client *ethclient.Client, address common.Address) (uint32, error) { stakeManager, opts := UtilsInterface.GetStakeManagerWithOpts(client) returnedValues := InvokeFunctionWithTimeout(stakeManager, "GetStakerId", &opts, address) @@ -431,6 +502,55 @@ func (s StakeManagerStruct) GetStaker(client *ethclient.Client, stakerId uint32) return returnedValues[0].Interface().(bindings.StructsStaker), nil } +func (s StakeManagerStruct) StakerInfo(client *ethclient.Client, stakerId uint32) (coretypes.Staker, error) { + stakeManager, opts := UtilsInterface.GetStakeManagerWithOpts(client) + returnedValues := InvokeFunctionWithTimeout(stakeManager, "Stakers", &opts, stakerId) + returnedError := CheckIfAnyError(returnedValues) + if returnedError != nil { + return coretypes.Staker{}, returnedError + } + staker := returnedValues[0].Interface().(struct { + AcceptDelegation bool + IsSlashed bool + Commission uint8 + Id uint32 + Age uint32 + Address common.Address + TokenAddress common.Address + EpochFirstStakedOrLastPenalized uint32 + EpochCommissionLastUpdated uint32 + Stake *big.Int + StakerReward *big.Int + }) + return staker, nil +} + +func (s StakeManagerStruct) GetMaturity(client *ethclient.Client, age uint32) (uint16, error) { + stakeManager, opts := UtilsInterface.GetStakeManagerWithOpts(client) + index := age / 10000 + returnedValues := InvokeFunctionWithTimeout(stakeManager, "Maturities", opts, big.NewInt(int64(index))) + returnedError := CheckIfAnyError(returnedValues) + if returnedError != nil { + return 0, returnedError + } + return returnedValues[0].Interface().(uint16), nil +} + +func (s StakeManagerStruct) GetBountyLock(client *ethclient.Client, bountyId uint32) (coretypes.BountyLock, error) { + stakeManager, opts := UtilsInterface.GetStakeManagerWithOpts(client) + returnedValues := InvokeFunctionWithTimeout(stakeManager, "BountyLocks", &opts, bountyId) + returnedError := CheckIfAnyError(returnedValues) + if returnedError != nil { + return coretypes.BountyLock{}, returnedError + } + bountyLock := returnedValues[0].Interface().(struct { + RedeemAfter uint32 + BountyHunter common.Address + Amount *big.Int + }) + return bountyLock, nil +} + func (a AssetManagerStruct) GetNumCollections(client *ethclient.Client) (uint16, error) { collectionManager, opts := UtilsInterface.GetCollectionManagerWithOpts(client) returnedValues := InvokeFunctionWithTimeout(collectionManager, "GetNumCollections", &opts) @@ -461,6 +581,16 @@ func (a AssetManagerStruct) GetActiveCollections(client *ethclient.Client) ([]ui return returnedValues[0].Interface().([]uint16), nil } +func (a AssetManagerStruct) GetActiveStatus(client *ethclient.Client, id uint16) (bool, error) { + collectionManager, opts := UtilsInterface.GetCollectionManagerWithOpts(client) + returnedValues := InvokeFunctionWithTimeout(collectionManager, "GetCollectionStatus", &opts, id) + returnedError := CheckIfAnyError(returnedValues) + if returnedError != nil { + return false, returnedError + } + return returnedValues[0].Interface().(bool), nil +} + func (a AssetManagerStruct) Jobs(client *ethclient.Client, id uint16) (bindings.StructsJob, error) { collectionManager, opts := UtilsInterface.GetCollectionManagerWithOpts(client) returnedValues := InvokeFunctionWithTimeout(collectionManager, "Jobs", &opts, id) @@ -692,8 +822,22 @@ func (c ClientStruct) FilterLogs(client *ethclient.Client, ctx context.Context, return returnedValues[0].Interface().([]types.Log), nil } -func (c CoinStruct) BalanceOf(erc20Contract *bindings.RAZOR, opts *bind.CallOpts, account common.Address) (*big.Int, error) { - returnedValues := InvokeFunctionWithTimeout(erc20Contract, "BalanceOf", opts, account) +func (c CoinStruct) BalanceOf(client *ethclient.Client, account common.Address) (*big.Int, error) { + tokenManager := UtilsInterface.GetTokenManager(client) + opts := UtilsInterface.GetOptions() + returnedValues := InvokeFunctionWithTimeout(tokenManager, "BalanceOf", &opts, account) + returnedError := CheckIfAnyError(returnedValues) + if returnedError != nil { + return nil, returnedError + } + return returnedValues[0].Interface().(*big.Int), nil +} + +//This function is used to check the allowance of staker +func (c CoinStruct) Allowance(client *ethclient.Client, owner common.Address, spender common.Address) (*big.Int, error) { + tokenManager := UtilsInterface.GetTokenManager(client) + opts := UtilsInterface.GetOptions() + returnedValues := InvokeFunctionWithTimeout(tokenManager, "Allowance", &opts, owner, spender) returnedError := CheckIfAnyError(returnedValues) if returnedError != nil { return nil, returnedError diff --git a/utils/vote.go b/utils/vote.go index 7fb1531f8..dd7594686 100644 --- a/utils/vote.go +++ b/utils/vote.go @@ -1,10 +1,10 @@ package utils import ( - "context" "math/big" "razor/core/types" "razor/pkg/bindings" + "razor/rpc" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/ethclient" @@ -14,12 +14,12 @@ func (*UtilsStruct) GetVoteManagerWithOpts(client *ethclient.Client) (*bindings. return UtilsInterface.GetVoteManager(client), UtilsInterface.GetOptions() } -func (*UtilsStruct) GetCommitment(ctx context.Context, client *ethclient.Client, address string) (types.Commitment, error) { - stakerId, err := UtilsInterface.GetStakerId(ctx, client, address) +func (*UtilsStruct) GetCommitment(rpcParameters rpc.RPCParameters, address string) (types.Commitment, error) { + stakerId, err := UtilsInterface.GetStakerId(rpcParameters, address) if err != nil { return types.Commitment{}, err } - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, VoteManagerInterface, "GetCommitment", client, stakerId) + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, VoteManagerInterface, "GetCommitment", stakerId) if err != nil { return types.Commitment{}, err } @@ -27,58 +27,66 @@ func (*UtilsStruct) GetCommitment(ctx context.Context, client *ethclient.Client, return commitment, nil } -func (*UtilsStruct) GetVoteValue(ctx context.Context, client *ethclient.Client, epoch uint32, stakerId uint32, medianIndex uint16) (*big.Int, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, VoteManagerInterface, "GetVoteValue", client, epoch, stakerId, medianIndex) +func (*UtilsStruct) GetVoteValue(rpcParameters rpc.RPCParameters, epoch uint32, stakerId uint32, medianIndex uint16) (*big.Int, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, VoteManagerInterface, "GetVoteValue", epoch, stakerId, medianIndex) if err != nil { return big.NewInt(0), err } return returnedValues[0].Interface().(*big.Int), nil } -func (*UtilsStruct) GetInfluenceSnapshot(ctx context.Context, client *ethclient.Client, stakerId uint32, epoch uint32) (*big.Int, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, VoteManagerInterface, "GetInfluenceSnapshot", client, epoch, stakerId) +func (*UtilsStruct) GetInfluenceSnapshot(rpcParameters rpc.RPCParameters, stakerId uint32, epoch uint32) (*big.Int, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, VoteManagerInterface, "GetInfluenceSnapshot", epoch, stakerId) if err != nil { return nil, err } return returnedValues[0].Interface().(*big.Int), nil } -func (*UtilsStruct) GetStakeSnapshot(ctx context.Context, client *ethclient.Client, stakerId uint32, epoch uint32) (*big.Int, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, VoteManagerInterface, "GetStakeSnapshot", client, epoch, stakerId) +func (*UtilsStruct) GetStakeSnapshot(rpcParameters rpc.RPCParameters, stakerId uint32, epoch uint32) (*big.Int, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, VoteManagerInterface, "GetStakeSnapshot", epoch, stakerId) if err != nil { return nil, err } return returnedValues[0].Interface().(*big.Int), nil } -func (*UtilsStruct) GetTotalInfluenceRevealed(ctx context.Context, client *ethclient.Client, epoch uint32, medianIndex uint16) (*big.Int, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, VoteManagerInterface, "GetTotalInfluenceRevealed", client, epoch, medianIndex) +func (*UtilsStruct) GetTotalInfluenceRevealed(rpcParameters rpc.RPCParameters, epoch uint32, medianIndex uint16) (*big.Int, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, VoteManagerInterface, "GetTotalInfluenceRevealed", epoch, medianIndex) if err != nil { return nil, err } return returnedValues[0].Interface().(*big.Int), nil } -func (*UtilsStruct) GetEpochLastCommitted(ctx context.Context, client *ethclient.Client, stakerId uint32) (uint32, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, VoteManagerInterface, "GetEpochLastCommitted", client, stakerId) +func (*UtilsStruct) GetEpochLastCommitted(rpcParameters rpc.RPCParameters, stakerId uint32) (uint32, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, VoteManagerInterface, "GetEpochLastCommitted", stakerId) if err != nil { return 0, err } return returnedValues[0].Interface().(uint32), nil } -func (*UtilsStruct) GetEpochLastRevealed(ctx context.Context, client *ethclient.Client, stakerId uint32) (uint32, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, VoteManagerInterface, "GetEpochLastRevealed", client, stakerId) +func (*UtilsStruct) GetEpochLastRevealed(rpcParameters rpc.RPCParameters, stakerId uint32) (uint32, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, VoteManagerInterface, "GetEpochLastRevealed", stakerId) if err != nil { return 0, err } return returnedValues[0].Interface().(uint32), nil } -func (*UtilsStruct) ToAssign(ctx context.Context, client *ethclient.Client) (uint16, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, VoteManagerInterface, "ToAssign", client) +func (*UtilsStruct) ToAssign(rpcParameters rpc.RPCParameters) (uint16, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, VoteManagerInterface, "ToAssign") if err != nil { return 0, err } return returnedValues[0].Interface().(uint16), nil } + +func (*UtilsStruct) GetSaltFromBlockchain(rpcParameters rpc.RPCParameters) ([32]byte, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(rpcParameters, VoteManagerInterface, "GetSaltFromBlockchain") + if err != nil { + return [32]byte{}, err + } + return returnedValues[0].Interface().([32]byte), nil +} diff --git a/utils/vote_test.go b/utils/vote_test.go index 600bfe741..fdc2f9318 100644 --- a/utils/vote_test.go +++ b/utils/vote_test.go @@ -1,7 +1,6 @@ package utils import ( - "context" "errors" "math/big" "razor/core/types" @@ -17,7 +16,6 @@ import ( ) func TestGetCommitments(t *testing.T) { - var client *ethclient.Client var callOpts bind.CallOpts var address string @@ -79,7 +77,7 @@ func TestGetCommitments(t *testing.T) { voteManagerMock.On("GetCommitment", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.commitments, tt.args.commitmentErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetCommitment(context.Background(), client, address) + got, err := utils.GetCommitment(rpcParameters, address) if (err != nil) != tt.wantErr { t.Errorf("GetCommitment() error = %v, wantErr %v", err, tt.wantErr) return @@ -92,7 +90,6 @@ func TestGetCommitments(t *testing.T) { } func TestGetEpochLastCommitted(t *testing.T) { - var client *ethclient.Client var callOpts bind.CallOpts var stakerId uint32 @@ -140,7 +137,7 @@ func TestGetEpochLastCommitted(t *testing.T) { voteManagerMock.On("GetEpochLastCommitted", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.epochLastCommitted, tt.args.epochLastCommittedErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetEpochLastCommitted(context.Background(), client, stakerId) + got, err := utils.GetEpochLastCommitted(rpcParameters, stakerId) if (err != nil) != tt.wantErr { t.Errorf("GetEpochLastCommitted() error = %v, wantErr %v", err, tt.wantErr) return @@ -153,7 +150,6 @@ func TestGetEpochLastCommitted(t *testing.T) { } func TestGetEpochLastRevealed(t *testing.T) { - var client *ethclient.Client var stakerId uint32 type args struct { @@ -199,7 +195,7 @@ func TestGetEpochLastRevealed(t *testing.T) { voteManagerMock.On("GetEpochLastRevealed", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.epochLastRevealed, tt.args.epochLastRevealedErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetEpochLastRevealed(context.Background(), client, stakerId) + got, err := utils.GetEpochLastRevealed(rpcParameters, stakerId) if (err != nil) != tt.wantErr { t.Errorf("GetEpochLastRevealed() error = %v, wantErr %v", err, tt.wantErr) return @@ -212,7 +208,6 @@ func TestGetEpochLastRevealed(t *testing.T) { } func TestGetInfluenceSnapshot(t *testing.T) { - var client *ethclient.Client var callOpts bind.CallOpts var stakerId uint32 var epoch uint32 @@ -261,7 +256,7 @@ func TestGetInfluenceSnapshot(t *testing.T) { voteManagerMock.On("GetInfluenceSnapshot", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint32")).Return(tt.args.influenceSnapshot, tt.args.influenceErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetInfluenceSnapshot(context.Background(), client, stakerId, epoch) + got, err := utils.GetInfluenceSnapshot(rpcParameters, stakerId, epoch) if (err != nil) != tt.wantErr { t.Errorf("GetInfluenceSnapshot() error = %v, wantErr %v", err, tt.wantErr) return @@ -274,7 +269,6 @@ func TestGetInfluenceSnapshot(t *testing.T) { } func TestGetStakeSnapshot(t *testing.T) { - var client *ethclient.Client var callOpts bind.CallOpts var stakerId uint32 var epoch uint32 @@ -323,7 +317,7 @@ func TestGetStakeSnapshot(t *testing.T) { voteManagerMock.On("GetStakeSnapshot", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint32")).Return(tt.args.stakeSnapshot, tt.args.snapshotErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetStakeSnapshot(context.Background(), client, stakerId, epoch) + got, err := utils.GetStakeSnapshot(rpcParameters, stakerId, epoch) if (err != nil) != tt.wantErr { t.Errorf("GetStakeSnapshot() error = %v, wantErr %v", err, tt.wantErr) return @@ -337,7 +331,6 @@ func TestGetStakeSnapshot(t *testing.T) { func TestGetTotalInfluenceRevealed(t *testing.T) { var ( - client *ethclient.Client callOpts bind.CallOpts epoch uint32 medianIndex uint16 @@ -387,7 +380,7 @@ func TestGetTotalInfluenceRevealed(t *testing.T) { voteManagerMock.On("GetTotalInfluenceRevealed", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint16")).Return(tt.args.totalInfluenceRevealed, tt.args.influenceErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetTotalInfluenceRevealed(context.Background(), client, epoch, medianIndex) + got, err := utils.GetTotalInfluenceRevealed(rpcParameters, epoch, medianIndex) if (err != nil) != tt.wantErr { t.Errorf("GetTotalInfluenceRevealed() error = %v, wantErr %v", err, tt.wantErr) return @@ -401,7 +394,6 @@ func TestGetTotalInfluenceRevealed(t *testing.T) { func TestGetVoteValue(t *testing.T) { var ( - client *ethclient.Client callOpts bind.CallOpts medianIndex uint16 stakerId uint32 @@ -452,7 +444,7 @@ func TestGetVoteValue(t *testing.T) { voteManagerMock.On("GetVoteValue", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint16")).Return(tt.args.voteValue, tt.args.voteValueErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.GetVoteValue(context.Background(), client, epoch, stakerId, medianIndex) + got, err := utils.GetVoteValue(rpcParameters, epoch, stakerId, medianIndex) if (err != nil) != tt.wantErr { t.Errorf("GetVoteValue() error = %v, wantErr %v", err, tt.wantErr) return @@ -489,7 +481,6 @@ func TestGetVoteManagerWithOpts(t *testing.T) { } func TestToAssign(t *testing.T) { - var client *ethclient.Client type args struct { toAssign uint16 toAssignErr error @@ -531,7 +522,7 @@ func TestToAssign(t *testing.T) { voteManagerMock.On("ToAssign", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.toAssign, tt.args.toAssignErr) retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) - got, err := utils.ToAssign(context.Background(), client) + got, err := utils.ToAssign(rpcParameters) if (err != nil) != tt.wantErr { t.Errorf("ToAssign() error = %v, wantErr %v", err, tt.wantErr) return