From bb75173cc022063e9a8c335f9b2301bb537762a8 Mon Sep 17 00:00:00 2001 From: Yashk767 <76935991+Yashk767@users.noreply.github.com> Date: Wed, 9 Oct 2024 15:54:33 +0530 Subject: [PATCH] refactor: added context with timeout to retry mechanism (#1235) * chore: updated config variable default and limits for 5 min epoch (#1232) * feat: added timeout to retry mechanism using context * refactor: called stateBuffer once and used in other functions * refactor: added context to RPC calls used in vote function * refactor: added context instance to all the dependent functions * refactor: fixed tests for cmd package * refactor: fixed tests for utils package * refactor: fixed additional tests in cmd package * refactor: fixed benchmarks in cmd package * refactor: reduced number of retry attempts * refactor: added tests for context deadline exceeded for retry case * refactor: rebased retry params with current main branch v2.0.0 release --- cmd/addStake.go | 13 +- cmd/addStake_test.go | 12 +- cmd/approve.go | 3 +- cmd/approve_test.go | 2 +- cmd/claimBounty.go | 5 +- cmd/claimBounty_test.go | 4 +- cmd/claimCommission.go | 5 +- cmd/claimCommission_test.go | 4 +- cmd/cmd-utils.go | 24 +- cmd/cmd-utils_test.go | 17 +- cmd/commit.go | 33 +- cmd/commit_test.go | 40 +- cmd/config-utils.go | 10 +- cmd/config-utils_test.go | 5 +- cmd/confirm.go | 13 +- cmd/confirm_test.go | 13 +- cmd/createCollection.go | 5 +- cmd/createCollection_test.go | 4 +- cmd/createJob.go | 3 +- cmd/createJob_test.go | 2 +- cmd/delegate.go | 5 +- cmd/delegate_test.go | 4 +- cmd/dispute.go | 75 ++-- cmd/dispute_test.go | 77 ++-- cmd/eventListeners.go | 19 +- cmd/initTestMocks_test.go | 80 ++++ cmd/initiateWithdraw.go | 17 +- cmd/initiateWithdraw_test.go | 17 +- cmd/interface.go | 72 +-- cmd/mocks/utils_cmd_interface.go | 580 ++++++++++++------------ cmd/modifyCollectionStatus.go | 9 +- cmd/modifyCollectionStatus_test.go | 9 +- cmd/propose.go | 61 +-- cmd/propose_test.go | 118 +++-- cmd/resetUnstakeLock.go | 5 +- cmd/resetUnstakeLock_test.go | 4 +- cmd/reveal.go | 15 +- cmd/reveal_test.go | 14 +- cmd/setDelegation.go | 13 +- cmd/setDelegation_test.go | 49 +-- cmd/stakerInfo.go | 9 +- cmd/stakerInfo_test.go | 14 +- cmd/struct-utils.go | 5 +- cmd/transfer.go | 3 +- cmd/transfer_test.go | 2 +- cmd/unlockWithdraw.go | 13 +- cmd/unlockWithdraw_test.go | 13 +- cmd/unstake.go | 15 +- cmd/unstake_test.go | 15 +- cmd/updateCollection.go | 9 +- cmd/updateCollection_test.go | 9 +- cmd/updateCommission.go | 17 +- cmd/updateCommission_test.go | 17 +- cmd/updateJob.go | 9 +- cmd/updateJob_test.go | 9 +- cmd/vote.go | 84 ++-- cmd/vote_test.go | 149 ++++--- utils/asset.go | 13 +- utils/asset_test.go | 13 +- utils/block.go | 47 +- utils/block_test.go | 29 +- utils/client_methods.go | 16 +- utils/client_methods_test.go | 8 +- utils/common.go | 32 +- utils/common_test.go | 96 +--- utils/interface.go | 90 ++-- utils/mocks/client_utils.go | 72 +-- utils/mocks/gas_utils.go | 51 ++- utils/mocks/utils.go | 680 +++++++++++++++-------------- utils/options.go | 22 +- utils/options_test.go | 20 +- utils/stake.go | 39 +- utils/stake_test.go | 21 +- utils/stakedToken.go | 5 +- utils/stakedToken_test.go | 3 +- utils/struct-utils.go | 32 +- utils/vote.go | 35 +- utils/vote_test.go | 19 +- 78 files changed, 1669 insertions(+), 1526 deletions(-) diff --git a/cmd/addStake.go b/cmd/addStake.go index b8765442d..128c1a38d 100644 --- a/cmd/addStake.go +++ b/cmd/addStake.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "razor/accounts" "razor/core" "razor/core/types" @@ -69,13 +70,13 @@ func (*UtilsStruct) ExecuteStake(flagSet *pflag.FlagSet) { razorUtils.CheckAmountAndBalance(valueInWei, balance) log.Debug("Checking whether sFuel balance is not 0...") - razorUtils.CheckEthBalanceIsZero(client, address) + razorUtils.CheckEthBalanceIsZero(context.Background(), client, address) - minSafeRazor, err := razorUtils.GetMinSafeRazor(client) + minSafeRazor, err := razorUtils.GetMinSafeRazor(context.Background(), client) 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(client, address) + stakerId, err := razorUtils.GetStakerId(context.Background(), client, address) utils.CheckError("Error in getting stakerId: ", err) log.Debug("ExecuteStake: Staker Id: ", stakerId) @@ -84,7 +85,7 @@ func (*UtilsStruct) ExecuteStake(flagSet *pflag.FlagSet) { } if stakerId != 0 { - staker, err := razorUtils.GetStaker(client, stakerId) + staker, err := razorUtils.GetStaker(context.Background(), client, stakerId) utils.CheckError("Error in getting staker: ", err) if staker.IsSlashed { @@ -119,7 +120,7 @@ func (*UtilsStruct) ExecuteStake(flagSet *pflag.FlagSet) { //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(txnArgs.Client) + epoch, err := razorUtils.GetEpoch(context.Background(), txnArgs.Client) if err != nil { return core.NilHash, err } @@ -129,7 +130,7 @@ 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(txnArgs) + txnOpts := razorUtils.GetTxnOpts(context.Background(), txnArgs) log.Debugf("Executing Stake transaction with epoch = %d, amount = %d", epoch, txnArgs.Amount) txn, err := stakeManagerUtils.Stake(txnArgs.Client, txnOpts, epoch, txnArgs.Amount) if err != nil { diff --git a/cmd/addStake_test.go b/cmd/addStake_test.go index df21fd316..dad161456 100644 --- a/cmd/addStake_test.go +++ b/cmd/addStake_test.go @@ -84,8 +84,8 @@ func TestStakeCoins(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetEpoch", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.epoch, tt.args.getEpochErr) - utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(TxnOpts) + utilsMock.On("GetEpoch", mock.Anything, 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) @@ -327,10 +327,10 @@ func TestExecuteStake(t *testing.T) { utilsMock.On("FetchBalance", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).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.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return() - utilsMock.On("GetMinSafeRazor", mock.AnythingOfType("*ethclient.Client")).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) + 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) diff --git a/cmd/approve.go b/cmd/approve.go index 76f5e991f..04872dfbe 100644 --- a/cmd/approve.go +++ b/cmd/approve.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "github.com/ethereum/go-ethereum/common" "razor/core" "razor/core/types" @@ -25,7 +26,7 @@ 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(txnArgs) + txnOpts := razorUtils.GetTxnOpts(context.Background(), txnArgs) log.Debug("Executing Approve transaction with amount: ", txnArgs.Amount) txn, err := tokenManagerUtils.Approve(txnArgs.Client, txnOpts, common.HexToAddress(core.StakeManagerAddress), txnArgs.Amount) if err != nil { diff --git a/cmd/approve_test.go b/cmd/approve_test.go index 218c9bae4..ddac58eff 100644 --- a/cmd/approve_test.go +++ b/cmd/approve_test.go @@ -121,7 +121,7 @@ func TestApprove(t *testing.T) { SetUpMockInterfaces() utilsMock.On("GetOptions").Return(tt.args.callOpts) - utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(TxnOpts) + 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) tokenManagerMock.On("Approve", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.approveTxn, tt.args.approveError) diff --git a/cmd/claimBounty.go b/cmd/claimBounty.go index 0e91572bd..d7f8bde8c 100644 --- a/cmd/claimBounty.go +++ b/cmd/claimBounty.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "errors" "math/big" "os" @@ -155,7 +156,7 @@ func (*UtilsStruct) ClaimBounty(config types.Configurations, client *ethclient.C MethodName: "redeemBounty", Parameters: []interface{}{redeemBountyInput.BountyId}, } - epoch, err := razorUtils.GetEpoch(txnArgs.Client) + epoch, err := razorUtils.GetEpoch(context.Background(), txnArgs.Client) if err != nil { log.Error("Error in getting epoch: ", err) return core.NilHash, err @@ -190,7 +191,7 @@ func (*UtilsStruct) ClaimBounty(config types.Configurations, client *ethclient.C return core.NilHash, nil } - txnOpts := razorUtils.GetTxnOpts(txnArgs) + txnOpts := razorUtils.GetTxnOpts(context.Background(), txnArgs) log.Debug("Executing RedeemBounty transaction with bountyId: ", redeemBountyInput.BountyId) tx, err := stakeManagerUtils.RedeemBounty(txnArgs.Client, txnOpts, redeemBountyInput.BountyId) diff --git a/cmd/claimBounty_test.go b/cmd/claimBounty_test.go index 848540833..86531a966 100644 --- a/cmd/claimBounty_test.go +++ b/cmd/claimBounty_test.go @@ -264,12 +264,12 @@ func TestClaimBounty(t *testing.T) { transactionUtils = transactionUtilsMock timeUtils = timeMock - utilsMock.On("GetEpoch", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.epoch, tt.args.epochErr) + 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) timeMock.On("Sleep", mock.AnythingOfType("time.Duration")).Return() utilsMock.On("CalculateBlockTime", mock.AnythingOfType("*ethclient.Client")).Return(blockTime) - utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(TxnOpts) + utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(TxnOpts) stakeManagerMock.On("RedeemBounty", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.AnythingOfType("uint32")).Return(tt.args.redeemBountyTxn, tt.args.redeemBountyErr) utilsMock.On("SecondsToReadableTime", mock.AnythingOfType("int")).Return(tt.args.time) transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.hash) diff --git a/cmd/claimCommission.go b/cmd/claimCommission.go index 6de6853df..e16aafdb6 100644 --- a/cmd/claimCommission.go +++ b/cmd/claimCommission.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "math/big" "razor/accounts" "razor/core" @@ -54,7 +55,7 @@ func (*UtilsStruct) ClaimCommission(flagSet *pflag.FlagSet) { err = razorUtils.CheckPassword(account) utils.CheckError("Error in fetching private key from given password: ", err) - stakerId, err := razorUtils.GetStakerId(client, address) + stakerId, err := razorUtils.GetStakerId(context.Background(), client, address) utils.CheckError("Error in getting stakerId: ", err) log.Debug("ClaimCommission: Staker Id: ", stakerId) callOpts := razorUtils.GetOptions() @@ -64,7 +65,7 @@ func (*UtilsStruct) ClaimCommission(flagSet *pflag.FlagSet) { log.Debugf("ClaimCommission: Staker Info: %+v", stakerInfo) if stakerInfo.StakerReward.Cmp(big.NewInt(0)) > 0 { - txnOpts := razorUtils.GetTxnOpts(types.TransactionOptions{ + txnOpts := razorUtils.GetTxnOpts(context.Background(), types.TransactionOptions{ Client: client, ChainId: core.ChainId, Config: config, diff --git a/cmd/claimCommission_test.go b/cmd/claimCommission_test.go index 50a252130..03d2a4f45 100644 --- a/cmd/claimCommission_test.go +++ b/cmd/claimCommission_test.go @@ -199,13 +199,13 @@ func TestClaimCommission(t *testing.T) { fatal = false fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) - utilsMock.On("GetStakerId", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.stakerId, tt.args.stakerIdErr) + utilsMock.On("GetStakerId", mock.Anything, 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.AnythingOfType("types.TransactionOptions")).Return(TxnOpts) + utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(TxnOpts) utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), 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) diff --git a/cmd/cmd-utils.go b/cmd/cmd-utils.go index 7786ac766..d034b9baf 100644 --- a/cmd/cmd-utils.go +++ b/cmd/cmd-utils.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "errors" "math/big" "razor/utils" @@ -14,8 +15,8 @@ import ( ) //This function takes client as a parameter and returns the epoch and state -func (*UtilsStruct) GetEpochAndState(client *ethclient.Client) (uint32, int64, error) { - epoch, err := razorUtils.GetEpoch(client) +func (*UtilsStruct) GetEpochAndState(ctx context.Context, client *ethclient.Client) (uint32, int64, error) { + epoch, err := razorUtils.GetEpoch(ctx, client) if err != nil { return 0, 0, err } @@ -23,16 +24,21 @@ func (*UtilsStruct) GetEpochAndState(client *ethclient.Client) (uint32, int64, e if err != nil { return 0, 0, err } - err = ValidateBufferPercentLimit(client, bufferPercent) + err = ValidateBufferPercentLimit(ctx, client, bufferPercent) if err != nil { return 0, 0, err } - latestHeader, err := clientUtils.GetLatestBlockWithRetry(client) + latestHeader, err := clientUtils.GetLatestBlockWithRetry(ctx, client) if err != nil { log.Error("Error in fetching block: ", err) return 0, 0, err } - state, err := razorUtils.GetBufferedState(client, latestHeader, bufferPercent) + stateBuffer, err := razorUtils.GetStateBuffer(ctx, client) + if err != nil { + log.Error("Error in getting state buffer: ", err) + return 0, 0, err + } + state, err := razorUtils.GetBufferedState(latestHeader, stateBuffer, bufferPercent) if err != nil { return 0, 0, err } @@ -42,10 +48,10 @@ func (*UtilsStruct) GetEpochAndState(client *ethclient.Client) (uint32, int64, e } //This function waits for the appropriate states which are required -func (*UtilsStruct) WaitForAppropriateState(client *ethclient.Client, action string, states ...int) (uint32, error) { +func (*UtilsStruct) WaitForAppropriateState(ctx context.Context, client *ethclient.Client, action string, states ...int) (uint32, error) { statesAllowed := GetFormattedStateNames(states) for { - epoch, state, err := cmdUtils.GetEpochAndState(client) + epoch, state, err := cmdUtils.GetEpochAndState(ctx, client) if err != nil { log.Error("Error in fetching epoch and state: ", err) return epoch, err @@ -60,9 +66,9 @@ func (*UtilsStruct) WaitForAppropriateState(client *ethclient.Client, action str } //This function wait if the state is commit state -func (*UtilsStruct) WaitIfCommitState(client *ethclient.Client, action string) (uint32, error) { +func (*UtilsStruct) WaitIfCommitState(ctx context.Context, client *ethclient.Client, action string) (uint32, error) { for { - epoch, state, err := cmdUtils.GetEpochAndState(client) + epoch, state, err := cmdUtils.GetEpochAndState(ctx, client) if err != nil { log.Error("Error in fetching epoch and state: ", err) return epoch, err diff --git a/cmd/cmd-utils_test.go b/cmd/cmd-utils_test.go index f91d14522..83e33f623 100644 --- a/cmd/cmd-utils_test.go +++ b/cmd/cmd-utils_test.go @@ -1,6 +1,7 @@ package cmd import ( + "context" "errors" Types "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" @@ -130,14 +131,14 @@ func TestGetEpochAndState(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetEpoch", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.epoch, tt.args.epochErr) + utilsMock.On("GetEpoch", mock.Anything, mock.Anything).Return(tt.args.epoch, tt.args.epochErr) cmdUtilsMock.On("GetBufferPercent").Return(tt.args.bufferPercent, tt.args.bufferPercentErr) - utilsMock.On("GetStateBuffer", mock.Anything).Return(tt.args.stateBuffer, tt.args.stateBufferErr) - clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything).Return(tt.args.latestHeader, tt.args.latestHeaderErr) + utilsMock.On("GetStateBuffer", mock.Anything, 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(client) + gotEpoch, gotState, err := utils.GetEpochAndState(context.Background(), client) if gotEpoch != tt.wantEpoch { t.Errorf("GetEpochAndState() got epoch = %v, want %v", gotEpoch, tt.wantEpoch) } @@ -221,10 +222,10 @@ func TestWaitForAppropriateState(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - cmdUtilsMock.On("GetEpochAndState", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.epoch, tt.args.state, tt.args.epochOrStateErr) + 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(client, tt.args.action, tt.args.states) + got, err := utils.WaitForAppropriateState(context.Background(), client, tt.args.action, tt.args.states) if got != tt.want { t.Errorf("WaitForAppropriateState() function, got = %v, want = %v", got, tt.want) } @@ -278,12 +279,12 @@ func TestWaitIfCommitState(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - cmdUtilsMock.On("GetEpochAndState", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.epoch, tt.args.state, tt.args.epochOrStateErr) + 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.WaitIfCommitState(client, action) + got, err := utils.WaitIfCommitState(context.Background(), client, action) if got != tt.want { t.Errorf("WaitIfCommitState() function, got = %v, want = %v", got, tt.want) } diff --git a/cmd/commit.go b/cmd/commit.go index 0e2a68763..5524e1d51 100644 --- a/cmd/commit.go +++ b/cmd/commit.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "encoding/hex" "errors" Types "github.com/ethereum/go-ethereum/core/types" @@ -21,15 +22,15 @@ 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(client *ethclient.Client, epoch uint32) ([32]byte, error) { +func (*UtilsStruct) GetSalt(ctx context.Context, client *ethclient.Client, epoch uint32) ([32]byte, error) { previousEpoch := epoch - 1 log.Debug("GetSalt: Previous epoch: ", previousEpoch) - numProposedBlock, err := razorUtils.GetNumberOfProposedBlocks(client, previousEpoch) + numProposedBlock, err := razorUtils.GetNumberOfProposedBlocks(ctx, client, previousEpoch) if err != nil { return [32]byte{}, err } log.Debug("GetSalt: Number of proposed blocks: ", numProposedBlock) - blockIndexToBeConfirmed, err := razorUtils.GetBlockIndexToBeConfirmed(client) + blockIndexToBeConfirmed, err := razorUtils.GetBlockIndexToBeConfirmed(ctx, client) if err != nil { return [32]byte{}, err } @@ -37,12 +38,12 @@ func (*UtilsStruct) GetSalt(client *ethclient.Client, epoch uint32) ([32]byte, e if numProposedBlock == 0 || (numProposedBlock > 0 && blockIndexToBeConfirmed < 0) { return utils.VoteManagerInterface.GetSaltFromBlockchain(client) } - blockId, err := razorUtils.GetSortedProposedBlockId(client, previousEpoch, big.NewInt(int64(blockIndexToBeConfirmed))) + blockId, err := razorUtils.GetSortedProposedBlockId(ctx, client, 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(client, previousEpoch, blockId) + previousBlock, err := razorUtils.GetProposedBlock(ctx, client, previousEpoch, blockId) if err != nil { return [32]byte{}, errors.New("Error in getting previous block: " + err.Error()) } @@ -55,14 +56,14 @@ func (*UtilsStruct) GetSalt(client *ethclient.Client, epoch uint32) ([32]byte, e 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(client *ethclient.Client, epoch uint32, seed []byte, commitParams *types.CommitParams, rogueData types.Rogue) (types.CommitData, error) { +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(client) 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(client, numActiveCollections, seed) + assignedCollections, seqAllottedCollections, err := razorUtils.GetAssignedCollections(ctx, client, numActiveCollections, seed) if err != nil { return types.CommitData{}, err } @@ -94,7 +95,7 @@ func (*UtilsStruct) HandleCommitState(client *ethclient.Client, epoch uint32, se errChan <- err return } - collectionData, err := razorUtils.GetAggregatedDataOfCollection(client, collectionId, epoch, commitParams) + collectionData, err := razorUtils.GetAggregatedDataOfCollection(ctx, client, collectionId, epoch, commitParams) if err != nil { log.Error("Error in getting aggregated data of collection: ", err) errChan <- err @@ -145,8 +146,8 @@ func (*UtilsStruct) HandleCommitState(client *ethclient.Client, epoch uint32, se /* 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(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, latestHeader *Types.Header, seed []byte, values []*big.Int) (common.Hash, error) { - if state, err := razorUtils.GetBufferedState(client, latestHeader, config.BufferPercent); err != nil || state != 0 { +func (*UtilsStruct) Commit(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, latestHeader *Types.Header, stateBuffer uint64, seed []byte, values []*big.Int) (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 } @@ -157,7 +158,7 @@ func (*UtilsStruct) Commit(client *ethclient.Client, config types.Configurations return core.NilHash, err } - txnOpts := razorUtils.GetTxnOpts(types.TransactionOptions{ + txnOpts := razorUtils.GetTxnOpts(ctx, types.TransactionOptions{ Client: client, ChainId: core.ChainId, Config: config, @@ -179,14 +180,14 @@ func (*UtilsStruct) Commit(client *ethclient.Client, config types.Configurations return txnHash, nil } -func CalculateSeed(client *ethclient.Client, account types.Account, keystorePath string, epoch uint32) ([]byte, error) { +func CalculateSeed(ctx context.Context, client *ethclient.Client, 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(client, epoch) + salt, err := cmdUtils.GetSalt(ctx, client, epoch) if err != nil { log.Error("Error in getting salt: ", err) return nil, err @@ -214,15 +215,15 @@ func CalculateCommitment(seed []byte, values []*big.Int) ([32]byte, error) { return commitmentToSend, nil } -func VerifyCommitment(client *ethclient.Client, account types.Account, keystorePath string, epoch uint32, values []*big.Int) (bool, error) { - commitmentStruct, err := razorUtils.GetCommitment(client, account.Address) +func VerifyCommitment(ctx context.Context, client *ethclient.Client, account types.Account, keystorePath string, epoch uint32, values []*big.Int) (bool, error) { + commitmentStruct, err := razorUtils.GetCommitment(ctx, client, account.Address) if err != nil { log.Error("Error in getting commitments: ", err) return false, err } log.Debugf("VerifyCommitment: CommitmentStruct: %+v", commitmentStruct) - seed, err := CalculateSeed(client, account, keystorePath, epoch) + seed, err := CalculateSeed(ctx, client, account, keystorePath, epoch) if err != nil { log.Error("Error in calculating seed: ", err) return false, err diff --git a/cmd/commit_test.go b/cmd/commit_test.go index a998ec22d..6cfa81aad 100644 --- a/cmd/commit_test.go +++ b/cmd/commit_test.go @@ -1,6 +1,7 @@ package cmd import ( + "context" "encoding/hex" "errors" "fmt" @@ -24,6 +25,7 @@ func TestCommit(t *testing.T) { account types.Account config types.Configurations latestHeader *Types.Header + stateBuffer uint64 seed []byte epoch uint32 ) @@ -96,13 +98,13 @@ func TestCommit(t *testing.T) { utils.MerkleInterface = &utils.MerkleTreeStruct{} merkleUtils = utils.MerkleInterface - utilsMock.On("GetBufferedState", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.state, tt.args.stateErr) - utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(TxnOpts) + utilsMock.On("GetBufferedState", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.state, tt.args.stateErr) + utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(TxnOpts) voteManagerMock.On("Commit", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.AnythingOfType("uint32"), mock.Anything).Return(tt.args.commitTxn, tt.args.commitErr) transactionMock.On("Hash", mock.AnythingOfType("*types.Transaction")).Return(tt.args.hash) utils := &UtilsStruct{} - got, err := utils.Commit(client, config, account, epoch, latestHeader, seed, tt.args.values) + got, err := utils.Commit(context.Background(), client, config, account, epoch, latestHeader, stateBuffer, seed, tt.args.values) if got != tt.want { t.Errorf("Txn hash for Commit function, got = %v, want = %v", got, tt.want) } @@ -233,13 +235,13 @@ func TestHandleCommitState(t *testing.T) { SetUpMockInterfaces() utilsMock.On("GetNumActiveCollections", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.numActiveCollections, tt.args.numActiveCollectionsErr) - utilsMock.On("GetAssignedCollections", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.assignedCollections, tt.args.seqAllottedCollections, tt.args.assignedCollectionsErr) + 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.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.collectionId, tt.args.collectionIdErr) - utilsMock.On("GetAggregatedDataOfCollection", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.collectionData, tt.args.collectionDataErr) + utilsMock.On("GetAggregatedDataOfCollection", mock.Anything, 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(client, epoch, seed, commitParams, tt.args.rogueData) + got, err := utils.HandleCommitState(context.Background(), client, 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) } @@ -350,15 +352,15 @@ func TestGetSalt(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetNumberOfProposedBlocks", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.numProposedBlocks, tt.args.numProposedBlocksErr) - utilsMock.On("GetBlockIndexToBeConfirmed", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.blockIndexedToBeConfirmed, tt.args.blockIndexedToBeConfirmedErr) + 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.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.blockId, tt.args.blockIdErr) - utilsMock.On("GetProposedBlock", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(tt.args.previousBlock, tt.args.previousBlockErr) + 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("CalculateSalt", mock.Anything, mock.Anything).Return(tt.args.salt) ut := &UtilsStruct{} - got, err := ut.GetSalt(client, tt.args.epoch) + got, err := ut.GetSalt(context.Background(), client, tt.args.epoch) if !reflect.DeepEqual(got, tt.want) { t.Errorf("Data from GetSalt function, got = %v, want = %v", got, tt.want) } @@ -403,13 +405,13 @@ func BenchmarkHandleCommitState(b *testing.B) { SetUpMockInterfaces() utilsMock.On("GetNumActiveCollections", mock.AnythingOfType("*ethclient.Client")).Return(v.numActiveCollections, nil) - utilsMock.On("GetAssignedCollections", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything).Return(v.assignedCollections, nil, nil) + utilsMock.On("GetAssignedCollections", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(v.assignedCollections, nil, nil) utilsMock.On("GetCollectionIdFromIndex", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(uint16(1), nil) - utilsMock.On("GetAggregatedDataOfCollection", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(big.NewInt(1000), nil) + utilsMock.On("GetAggregatedDataOfCollection", mock.Anything, 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(client, epoch, seed, commitParams, types.Rogue{IsRogue: false}) + _, err := ut.HandleCommitState(context.Background(), client, epoch, seed, commitParams, types.Rogue{IsRogue: false}) if err != nil { log.Fatal(err) } @@ -595,10 +597,10 @@ func TestVerifyCommitment(t *testing.T) { utils.MerkleInterface = &utils.MerkleTreeStruct{} merkleUtils = utils.MerkleInterface - utilsMock.On("GetCommitment", mock.Anything, mock.Anything).Return(types.Commitment{CommitmentHash: commitmentHash}, tt.args.commitmentErr) - cmdUtilsMock.On("GetSalt", mock.Anything, mock.Anything).Return(salt, nil) + utilsMock.On("GetCommitment", mock.Anything, mock.Anything, mock.Anything).Return(types.Commitment{CommitmentHash: commitmentHash}, tt.args.commitmentErr) + cmdUtilsMock.On("GetSalt", mock.Anything, mock.Anything, mock.Anything).Return(salt, nil) cmdUtilsMock.On("CalculateSecret", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil, secret, tt.args.secretErr) - got, err := VerifyCommitment(client, account, keystorePath, epoch, tt.args.values) + got, err := VerifyCommitment(context.Background(), client, account, keystorePath, epoch, tt.args.values) if (err != nil) != tt.wantErr { t.Errorf("VerifyCommitment() error = %v, wantErr %v", err, tt.wantErr) return @@ -681,8 +683,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).Return(salt, tt.args.saltErr) - got, err := CalculateSeed(client, account, keystorePath, epoch) + cmdUtilsMock.On("GetSalt", mock.Anything, mock.Anything, mock.Anything).Return(salt, tt.args.saltErr) + got, err := CalculateSeed(context.Background(), client, 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 2220e8bcf..b236ce514 100644 --- a/cmd/config-utils.go +++ b/cmd/config-utils.go @@ -2,15 +2,17 @@ package cmd import ( + "context" "errors" - "github.com/ethereum/go-ethereum/ethclient" - "github.com/sirupsen/logrus" "razor/client" "razor/core" "razor/core/types" "razor/utils" "strings" + "github.com/ethereum/go-ethereum/ethclient" + "github.com/sirupsen/logrus" + "github.com/spf13/viper" ) @@ -404,8 +406,8 @@ func setLogLevel(config types.Configurations) { } } -func ValidateBufferPercentLimit(client *ethclient.Client, bufferPercent int32) error { - stateBuffer, err := razorUtils.GetStateBuffer(client) +func ValidateBufferPercentLimit(ctx context.Context, client *ethclient.Client, bufferPercent int32) error { + stateBuffer, err := razorUtils.GetStateBuffer(ctx, client) if err != nil { return err } diff --git a/cmd/config-utils_test.go b/cmd/config-utils_test.go index 6bea01ba7..de2846885 100644 --- a/cmd/config-utils_test.go +++ b/cmd/config-utils_test.go @@ -1,6 +1,7 @@ package cmd import ( + "context" "errors" "github.com/ethereum/go-ethereum/ethclient" "github.com/spf13/viper" @@ -1243,9 +1244,9 @@ func TestValidateBufferPercentLimit(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetStateBuffer", mock.Anything).Return(tt.args.stateBuffer, tt.args.stateBufferErr) + utilsMock.On("GetStateBuffer", mock.Anything, mock.Anything).Return(tt.args.stateBuffer, tt.args.stateBufferErr) - err := ValidateBufferPercentLimit(client, tt.args.bufferPercent) + err := ValidateBufferPercentLimit(context.Background(), client, 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 e9d308b04..620c67406 100644 --- a/cmd/confirm.go +++ b/cmd/confirm.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "razor/core" "razor/core/types" @@ -9,15 +10,15 @@ import ( ) //This function allows the user to claim the block reward and returns the hash -func (*UtilsStruct) ClaimBlockReward(options types.TransactionOptions) (common.Hash, error) { - epoch, err := razorUtils.GetEpoch(options.Client) +func (*UtilsStruct) ClaimBlockReward(ctx context.Context, options types.TransactionOptions) (common.Hash, error) { + epoch, err := razorUtils.GetEpoch(ctx, options.Client) if err != nil { log.Error("Error in getting epoch: ", err) return core.NilHash, err } log.Debug("ClaimBlockReward: Epoch: ", epoch) - sortedProposedBlockIds, err := razorUtils.GetSortedProposedBlockIds(options.Client, epoch) + sortedProposedBlockIds, err := razorUtils.GetSortedProposedBlockIds(ctx, options.Client, epoch) if err != nil { log.Error("Error in getting sortedProposedBlockIds: ", err) return core.NilHash, err @@ -29,14 +30,14 @@ func (*UtilsStruct) ClaimBlockReward(options types.TransactionOptions) (common.H return core.NilHash, nil } - stakerID, err := razorUtils.GetStakerId(options.Client, options.Account.Address) + stakerID, err := razorUtils.GetStakerId(ctx, options.Client, 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(options.Client, epoch, sortedProposedBlockIds[0]) + selectedProposedBlock, err := razorUtils.GetProposedBlock(ctx, options.Client, epoch, sortedProposedBlockIds[0]) if err != nil { log.Error("Error in getting selectedProposedBlock: ", err) return core.NilHash, err @@ -45,7 +46,7 @@ func (*UtilsStruct) ClaimBlockReward(options types.TransactionOptions) (common.H if selectedProposedBlock.ProposerId == stakerID { log.Info("Claiming block reward...") - txnOpts := razorUtils.GetTxnOpts(options) + txnOpts := razorUtils.GetTxnOpts(ctx, options) log.Debug("Executing ClaimBlockReward transaction...") txn, err := blockManagerUtils.ClaimBlockReward(options.Client, txnOpts) if err != nil { diff --git a/cmd/confirm_test.go b/cmd/confirm_test.go index cd7977f1a..dec9ba5da 100644 --- a/cmd/confirm_test.go +++ b/cmd/confirm_test.go @@ -1,6 +1,7 @@ package cmd import ( + "context" "errors" "github.com/stretchr/testify/mock" "math/big" @@ -129,16 +130,16 @@ func TestClaimBlockReward(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetEpoch", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.epoch, tt.args.epochErr) - utilsMock.On("GetSortedProposedBlockIds", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.sortedProposedBlockIds, tt.args.sortedProposedBlockIdsErr) - utilsMock.On("GetStakerId", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.stakerId, tt.args.stakerIdErr) - utilsMock.On("GetProposedBlock", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint32")).Return(tt.args.selectedBlock, tt.args.selectedBlockErr) - utilsMock.On("GetTxnOpts", options).Return(TxnOpts) + 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("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(options) + got, err := utils.ClaimBlockReward(context.Background(), options) if got != tt.want { t.Errorf("Txn hash for ClaimBlockReward function, got = %v, want = %v", got, tt.want) } diff --git a/cmd/createCollection.go b/cmd/createCollection.go index d6c44cd93..ecbcdffd9 100644 --- a/cmd/createCollection.go +++ b/cmd/createCollection.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "razor/accounts" "razor/core" "razor/core/types" @@ -94,12 +95,12 @@ func (*UtilsStruct) ExecuteCreateCollection(flagSet *pflag.FlagSet) { func (*UtilsStruct) CreateCollection(client *ethclient.Client, config types.Configurations, collectionInput types.CreateCollectionInput) (common.Hash, error) { jobIds := utils.ConvertUintArrayToUint16Array(collectionInput.JobIds) log.Debug("CreateCollection: Uint16 jobIds: ", jobIds) - _, err := cmdUtils.WaitForAppropriateState(client, "create collection", 4) + _, err := cmdUtils.WaitForAppropriateState(context.Background(), client, "create collection", 4) if err != nil { log.Error("Error in fetching state") return core.NilHash, err } - txnOpts := razorUtils.GetTxnOpts(types.TransactionOptions{ + txnOpts := razorUtils.GetTxnOpts(context.Background(), types.TransactionOptions{ Client: client, ChainId: core.ChainId, Config: config, diff --git a/cmd/createCollection_test.go b/cmd/createCollection_test.go index cb8cfcc08..f2ea4b529 100644 --- a/cmd/createCollection_test.go +++ b/cmd/createCollection_test.go @@ -72,8 +72,8 @@ func TestCreateCollection(t *testing.T) { SetUpMockInterfaces() utilsMock.On("ConvertUintArrayToUint16Array", mock.Anything).Return(tt.args.jobIdUint8) - utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(TxnOpts) - cmdUtilsMock.On("WaitForAppropriateState", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string"), mock.Anything).Return(WaitForDisputeOrConfirmStateStatus, tt.args.waitForAppropriateStateErr) + 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) 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) diff --git a/cmd/createJob.go b/cmd/createJob.go index df93330cf..1d7959a57 100644 --- a/cmd/createJob.go +++ b/cmd/createJob.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "razor/accounts" "razor/core" "razor/core/types" @@ -108,7 +109,7 @@ func (*UtilsStruct) CreateJob(client *ethclient.Client, config types.Configurati Account: jobInput.Account, } - txnOpts := razorUtils.GetTxnOpts(txnArgs) + txnOpts := razorUtils.GetTxnOpts(context.Background(), txnArgs) log.Info("Creating Job...") 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) diff --git a/cmd/createJob_test.go b/cmd/createJob_test.go index 81bb56119..d8a483625 100644 --- a/cmd/createJob_test.go +++ b/cmd/createJob_test.go @@ -55,7 +55,7 @@ func TestCreateJob(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(TxnOpts) + utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(TxnOpts) assetManagerMock.On("CreateJob", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.createJobTxn, tt.args.createJobErr) transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) diff --git a/cmd/delegate.go b/cmd/delegate.go index f14ac0b6d..5311156fe 100644 --- a/cmd/delegate.go +++ b/cmd/delegate.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "razor/accounts" "razor/core" "razor/core/types" @@ -73,7 +74,7 @@ func (*UtilsStruct) ExecuteDelegate(flagSet *pflag.FlagSet) { razorUtils.CheckAmountAndBalance(valueInWei, balance) log.Debug("Checking whether sFuel balance is not 0...") - razorUtils.CheckEthBalanceIsZero(client, address) + razorUtils.CheckEthBalanceIsZero(context.Background(), client, address) txnArgs := types.TransactionOptions{ Client: client, @@ -105,7 +106,7 @@ func (*UtilsStruct) Delegate(txnArgs types.TransactionOptions, stakerId uint32) txnArgs.MethodName = "delegate" txnArgs.ABI = bindings.StakeManagerMetaData.ABI txnArgs.Parameters = []interface{}{stakerId, txnArgs.Amount} - delegationTxnOpts := razorUtils.GetTxnOpts(txnArgs) + delegationTxnOpts := razorUtils.GetTxnOpts(context.Background(), txnArgs) log.Info("Sending Delegate transaction...") log.Debugf("Executing Delegate transaction with stakerId = %d, amount = %s", stakerId, txnArgs.Amount) txn, err := stakeManagerUtils.Delegate(txnArgs.Client, delegationTxnOpts, stakerId, txnArgs.Amount) diff --git a/cmd/delegate_test.go b/cmd/delegate_test.go index fe6ac8811..033bc51af 100644 --- a/cmd/delegate_test.go +++ b/cmd/delegate_test.go @@ -57,7 +57,7 @@ func TestDelegate(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(TxnOpts) + utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(TxnOpts) stakeManagerMock.On("Delegate", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.delegateTxn, tt.args.delegateErr) transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) @@ -249,7 +249,7 @@ func TestExecuteDelegate(t *testing.T) { utilsMock.On("FetchBalance", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).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.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return() + 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) diff --git a/cmd/dispute.go b/cmd/dispute.go index 516cef698..0b8e6536e 100644 --- a/cmd/dispute.go +++ b/cmd/dispute.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "errors" "math/big" "os" @@ -27,23 +28,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(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, blockNumber *big.Int, rogueData types.Rogue, backupNodeActionsToIgnore []string) 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 { - sortedProposedBlockIds, err := razorUtils.GetSortedProposedBlockIds(client, epoch) + sortedProposedBlockIds, err := razorUtils.GetSortedProposedBlockIds(ctx, client, 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(client, epoch) + biggestStake, biggestStakerId, err := cmdUtils.GetBiggestStakeAndId(ctx, client, 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(client, account, epoch, blockNumber, rogueData) + locallyCalculatedData, err := cmdUtils.GetLocalMediansData(ctx, client, account, epoch, blockNumber, rogueData) if err != nil { return err } @@ -66,7 +67,7 @@ func (*UtilsStruct) HandleDispute(client *ethclient.Client, config types.Configu log.Debug("Iterating over random sorted proposed blocks to check dispute...") for _, blockId := range randomSortedProposedBlockIds { - proposedBlock, err := razorUtils.GetProposedBlock(client, epoch, blockId) + proposedBlock, err := razorUtils.GetProposedBlock(ctx, client, epoch, blockId) if err != nil { log.Error(err) continue @@ -86,7 +87,7 @@ func (*UtilsStruct) HandleDispute(client *ethclient.Client, config types.Configu 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(types.TransactionOptions{ + txnOpts := razorUtils.GetTxnOpts(ctx, types.TransactionOptions{ Client: client, ChainId: core.ChainId, Config: config, @@ -105,7 +106,7 @@ func (*UtilsStruct) HandleDispute(client *ethclient.Client, config types.Configu //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(client, account) + err = cmdUtils.StoreBountyId(ctx, client, account) if err != nil { log.Error(err) } @@ -118,7 +119,7 @@ func (*UtilsStruct) HandleDispute(client *ethclient.Client, config types.Configu 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(client, transactionOptions, epoch, uint8(blockIndex), proposedBlock.Ids, revealedCollectionIds) + idDisputeTxn, err := cmdUtils.CheckDisputeForIds(ctx, client, transactionOptions, epoch, uint8(blockIndex), proposedBlock.Ids, revealedCollectionIds) if err != nil { log.Error("Error in disputing: ", err) continue @@ -131,7 +132,7 @@ func (*UtilsStruct) HandleDispute(client *ethclient.Client, config types.Configu //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(client, account) + err = cmdUtils.StoreBountyId(ctx, client, account) if err != nil { log.Error(err) } @@ -171,7 +172,7 @@ func (*UtilsStruct) HandleDispute(client *ethclient.Client, config types.Configu } 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(client, config, account, epoch, uint8(blockIndex), proposedBlock, leafId, sortedValues) + disputeErr := cmdUtils.Dispute(ctx, client, config, account, epoch, uint8(blockIndex), proposedBlock, leafId, sortedValues) if disputeErr != nil { log.Error("Error in disputing...", disputeErr) continue @@ -191,11 +192,11 @@ func (*UtilsStruct) HandleDispute(client *ethclient.Client, config types.Configu } //This function returns the local median data -func (*UtilsStruct) GetLocalMediansData(client *ethclient.Client, account types.Account, epoch uint32, blockNumber *big.Int, rogueData types.Rogue) (types.ProposeFileData, error) { +func (*UtilsStruct) GetLocalMediansData(ctx context.Context, client *ethclient.Client, 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(client, account, epoch, blockNumber) + return calculateMedian(ctx, client, account, epoch, blockNumber) } // Fetching the data from file only if the node is not in rogue mode and @@ -206,18 +207,18 @@ func (*UtilsStruct) GetLocalMediansData(client *ethclient.Client, account types. fileName, err := pathUtils.GetProposeDataFileName(account.Address) if err != nil { log.Error("Error in getting file name to read median data: ", err) - return calculateMedian(client, account, epoch, blockNumber) + return calculateMedian(ctx, client, 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(client, account, epoch, blockNumber) + return calculateMedian(ctx, client, 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(client, account, epoch, blockNumber) + return calculateMedian(ctx, client, account, epoch, blockNumber) } return proposedData, err } @@ -225,8 +226,8 @@ func (*UtilsStruct) GetLocalMediansData(client *ethclient.Client, account types. return globalProposedDataStruct, nil } -func calculateMedian(client *ethclient.Client, account types.Account, epoch uint32, blockNumber *big.Int) (types.ProposeFileData, error) { - stakerId, err := razorUtils.GetStakerId(client, account.Address) +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) if err != nil { log.Error("Error in getting stakerId: ", err) return types.ProposeFileData{}, err @@ -235,7 +236,7 @@ func calculateMedian(client *ethclient.Client, account types.Account, epoch uint 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(client, blockNumber, epoch, types.Rogue{IsRogue: false}) + medians, revealedCollectionIds, revealedDataMaps, err := cmdUtils.MakeBlock(ctx, client, blockNumber, epoch, types.Rogue{IsRogue: false}) if err != nil { log.Error("Error in calculating block medians: ", err) return types.ProposeFileData{}, err @@ -252,7 +253,7 @@ func calculateMedian(client *ethclient.Client, account types.Account, epoch uint } //This function check for the dispute in different type of Id's -func (*UtilsStruct) CheckDisputeForIds(client *ethclient.Client, transactionOpts types.TransactionOptions, epoch uint32, blockIndex uint8, idsInProposedBlock []uint16, revealedCollectionIds []uint16) (*Types.Transaction, error) { +func (*UtilsStruct) CheckDisputeForIds(ctx context.Context, client *ethclient.Client, 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) @@ -272,7 +273,7 @@ func (*UtilsStruct) CheckDisputeForIds(client *ethclient.Client, transactionOpts transactionOpts.ABI = bindings.BlockManagerMetaData.ABI transactionOpts.MethodName = "disputeOnOrderOfIds" transactionOpts.Parameters = []interface{}{epoch, blockIndex, index0, index1} - txnOpts := razorUtils.GetTxnOpts(transactionOpts) + txnOpts := razorUtils.GetTxnOpts(ctx, transactionOpts) 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))) @@ -284,9 +285,9 @@ func (*UtilsStruct) CheckDisputeForIds(client *ethclient.Client, transactionOpts transactionOpts.ABI = bindings.BlockManagerMetaData.ABI transactionOpts.MethodName = "disputeCollectionIdShouldBePresent" transactionOpts.Parameters = []interface{}{epoch, blockIndex, missingCollectionId} - txnOpts := razorUtils.GetTxnOpts(transactionOpts) + txnOpts := razorUtils.GetTxnOpts(ctx, transactionOpts) gasLimit := txnOpts.GasLimit - incrementedGasLimit, err := gasUtils.IncreaseGasLimitValue(client, gasLimit, core.DisputeGasMultiplier) + incrementedGasLimit, err := gasUtils.IncreaseGasLimitValue(ctx, client, gasLimit, core.DisputeGasMultiplier) if err != nil { return nil, err } @@ -302,9 +303,9 @@ func (*UtilsStruct) CheckDisputeForIds(client *ethclient.Client, transactionOpts transactionOpts.ABI = bindings.BlockManagerMetaData.ABI transactionOpts.MethodName = "disputeCollectionIdShouldBeAbsent" transactionOpts.Parameters = []interface{}{epoch, blockIndex, presentCollectionId, big.NewInt(int64(positionOfPresentValue))} - txnOpts := razorUtils.GetTxnOpts(transactionOpts) + txnOpts := razorUtils.GetTxnOpts(ctx, transactionOpts) gasLimit := txnOpts.GasLimit - incrementedGasLimit, err := gasUtils.IncreaseGasLimitValue(client, gasLimit, core.DisputeGasMultiplier) + incrementedGasLimit, err := gasUtils.IncreaseGasLimitValue(ctx, client, gasLimit, core.DisputeGasMultiplier) if err != nil { return nil, err } @@ -318,7 +319,7 @@ func (*UtilsStruct) CheckDisputeForIds(client *ethclient.Client, transactionOpts } //This function finalizes the dispute and return the error if there is any -func (*UtilsStruct) Dispute(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, blockIndex uint8, proposedBlock bindings.StructsBlock, leafId uint16, sortedValues []*big.Int) error { +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) txnArgs := types.TransactionOptions{ @@ -342,13 +343,13 @@ func (*UtilsStruct) Dispute(client *ethclient.Client, config types.Configuration end = lenOfSortedValues } log.Debugf("Dispute: Calling GiveSorted with arguments epoch = %d, leafId = %d, sortedValues = %s", epoch, leafId, sortedValues[start:end]) - err := cmdUtils.GiveSorted(client, blockManager, txnArgs, epoch, leafId, sortedValues[start:end]) + err := cmdUtils.GiveSorted(ctx, client, blockManager, 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(txnArgs) + txnOpts := razorUtils.GetTxnOpts(ctx, txnArgs) log.Debugf("Dispute: Calling CheckToDoResetDispute with arguments epoch = %d, sortedValues = %s", epoch, sortedValues) cmdUtils.CheckToDoResetDispute(client, blockManager, txnOpts, epoch, sortedValues) return err @@ -377,7 +378,7 @@ func (*UtilsStruct) Dispute(client *ethclient.Client, config types.Configuration finalizeDisputeTxnArgs.MethodName = "finalizeDispute" finalizeDisputeTxnArgs.ABI = bindings.BlockManagerMetaData.ABI finalizeDisputeTxnArgs.Parameters = []interface{}{epoch, blockIndex, positionOfCollectionInBlock} - finalizeDisputeTxnOpts := razorUtils.GetTxnOpts(finalizeDisputeTxnArgs) + finalizeDisputeTxnOpts := razorUtils.GetTxnOpts(ctx, finalizeDisputeTxnArgs) 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) @@ -395,7 +396,7 @@ func (*UtilsStruct) Dispute(client *ethclient.Client, config types.Configuration //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(client, account) + err = cmdUtils.StoreBountyId(ctx, client, account) if err != nil { return err } @@ -412,7 +413,7 @@ func (*UtilsStruct) Dispute(client *ethclient.Client, config types.Configuration resetDisputeTxnArgs.MethodName = "resetDispute" resetDisputeTxnArgs.ABI = bindings.BlockManagerMetaData.ABI resetDisputeTxnArgs.Parameters = []interface{}{epoch} - resetDisputeTxnOpts := razorUtils.GetTxnOpts(resetDisputeTxnArgs) + resetDisputeTxnOpts := razorUtils.GetTxnOpts(ctx, resetDisputeTxnArgs) cmdUtils.ResetDispute(client, blockManager, resetDisputeTxnOpts, epoch) @@ -420,12 +421,12 @@ func (*UtilsStruct) Dispute(client *ethclient.Client, config types.Configuration } //This function sorts the Id's recursively -func GiveSorted(client *ethclient.Client, blockManager *bindings.BlockManager, txnArgs types.TransactionOptions, epoch uint32, leafId uint16, sortedValues []*big.Int) error { +func GiveSorted(ctx context.Context, client *ethclient.Client, blockManager *bindings.BlockManager, 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(txnArgs) + txnOpts := razorUtils.GetTxnOpts(ctx, txnArgs) disputesMapping, err := blockManagerUtils.Disputes(client, &callOpts, epoch, common.HexToAddress(txnArgs.Account.Address)) if err != nil { log.Error("Error in getting disputes mapping: ", disputesMapping) @@ -481,7 +482,7 @@ func (*UtilsStruct) GetCollectionIdPositionInBlock(client *ethclient.Client, lea } //This function saves the bountyId in disputeData file and return the error if there is any -func (*UtilsStruct) StoreBountyId(client *ethclient.Client, account types.Account) error { +func (*UtilsStruct) StoreBountyId(ctx context.Context, client *ethclient.Client, account types.Account) error { disputeFilePath, err := pathUtils.GetDisputeDataFileName(account.Address) if err != nil { return err @@ -490,7 +491,7 @@ func (*UtilsStruct) StoreBountyId(client *ethclient.Client, account types.Accoun var latestBountyId uint32 - latestHeader, err := clientUtils.GetLatestBlockWithRetry(client) + latestHeader, err := clientUtils.GetLatestBlockWithRetry(ctx, client) if err != nil { log.Error("Error in fetching block: ", err) return err @@ -498,7 +499,7 @@ func (*UtilsStruct) StoreBountyId(client *ethclient.Client, account types.Accoun 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(client, latestHeader.Number, account.Address) + latestBountyId, err = cmdUtils.GetBountyIdFromEvents(ctx, client, latestHeader.Number, account.Address) if err != nil { return err } @@ -545,7 +546,7 @@ func (*UtilsStruct) ResetDispute(client *ethclient.Client, blockManager *binding } //This function returns the bountyId from events -func (*UtilsStruct) GetBountyIdFromEvents(client *ethclient.Client, blockNumber *big.Int, bountyHunter string) (uint32, error) { +func (*UtilsStruct) GetBountyIdFromEvents(ctx context.Context, client *ethclient.Client, blockNumber *big.Int, bountyHunter string) (uint32, error) { fromBlock, err := razorUtils.EstimateBlockNumberAtEpochBeginning(client, blockNumber) if err != nil { log.Error(err) @@ -560,7 +561,7 @@ func (*UtilsStruct) GetBountyIdFromEvents(client *ethclient.Client, blockNumber }, } log.Debugf("GetBountyIdFromEvents: Query to send in filter logs: %+v", query) - logs, err := clientUtils.FilterLogsWithRetry(client, query) + logs, err := clientUtils.FilterLogsWithRetry(ctx, client, query) if err != nil { return 0, err } diff --git a/cmd/dispute_test.go b/cmd/dispute_test.go index 2a473f238..4f7fb43a2 100644 --- a/cmd/dispute_test.go +++ b/cmd/dispute_test.go @@ -1,6 +1,7 @@ package cmd import ( + "context" "crypto/ecdsa" "crypto/rand" "errors" @@ -93,19 +94,19 @@ func TestDispute(t *testing.T) { SetUpMockInterfaces() utilsMock.On("GetBlockManager", mock.AnythingOfType("*ethclient.Client")).Return(blockManager) - utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(TxnOpts) - cmdUtilsMock.On("GiveSorted", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil) + 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).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).Return(tt.args.storeBountyIdErr) + 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("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) utils := &UtilsStruct{} - err := utils.Dispute(client, config, account, epoch, blockIndex, proposedBlock, leafId, tt.args.sortedValues) + err := utils.Dispute(context.Background(), client, 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) @@ -524,27 +525,27 @@ func TestHandleDispute(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetSortedProposedBlockIds", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.sortedProposedBlockIds, tt.args.sortedProposedBlockIdsErr) - cmdUtilsMock.On("GetBiggestStakeAndId", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.biggestStake, tt.args.biggestStakeId, tt.args.biggestStakeErr) - cmdUtilsMock.On("GetLocalMediansData", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(types.ProposeFileData{ + 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{ MediansData: tt.args.medians, RevealedCollectionIds: tt.args.revealedCollectionIds, RevealedDataMaps: tt.args.revealedDataMaps, }, tt.args.mediansErr) - utilsMock.On("GetProposedBlock", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint32")).Return(tt.args.proposedBlock, tt.args.proposedBlockErr) - utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) + utilsMock.On("GetProposedBlock", mock.Anything, 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.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.idDisputeTxn, tt.args.idDisputeTxnErr) + 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.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) + 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("GetBlockManager", mock.AnythingOfType("*ethclient.Client")).Return(blockManager) - cmdUtilsMock.On("StoreBountyId", mock.Anything, mock.Anything).Return(tt.args.storeBountyIdErr) + 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) utils := &UtilsStruct{} - err := utils.HandleDispute(client, config, account, epoch, blockNumber, rogueData, backupNodeActionsToIgnore) + err := utils.HandleDispute(context.Background(), client, 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) @@ -657,16 +658,16 @@ func TestGiveSorted(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - blockManagerMock.On("GiveSorted", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.giveSorted, tt.args.giveSortedErr).Once() + 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("GetOptions").Return(callOpts) blockManagerMock.On("Disputes", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.disputesMapping, tt.args.disputesMappingErr) - utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) - blockManagerMock.On("GiveSorted", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.giveSorted, nil) + 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) - err := GiveSorted(client, blockManager, txnArgs, epoch, tt.args.leafId, tt.args.sortedValues) + err := GiveSorted(context.Background(), client, blockManager, txnArgs, epoch, tt.args.leafId, tt.args.sortedValues) if (err != nil) != tt.wantErr { t.Errorf("CheckDisputeForIds() error = %v, wantErr %v", err, tt.wantErr) return @@ -794,10 +795,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.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything).Return(tt.args.medians, tt.args.revealedCollectionIds, tt.args.revealedDataMaps, tt.args.mediansErr) - utilsMock.On("GetStakerId", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.stakerId, tt.args.stakerIdErr) + 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) ut := &UtilsStruct{} - localProposedData, err := ut.GetLocalMediansData(client, account, tt.args.epoch, blockNumber, types.Rogue{IsRogue: tt.args.isRogue}) + localProposedData, err := ut.GetLocalMediansData(context.Background(), client, 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 @@ -966,14 +967,14 @@ func TestCheckDisputeForIds(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) + 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).Return(tt.args.incrementedGasLimit, tt.args.incrementedGasLimitErr) + gasUtilsMock.On("IncreaseGasLimitValue", mock.Anything, 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).Return(uint64(2000), nil) + gasUtilsMock.On("IncreaseGasLimitValue", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(uint64(2000), nil) ut := &UtilsStruct{} - got, err := ut.CheckDisputeForIds(client, transactionOpts, epoch, blockIndex, tt.args.idsInProposedBlock, tt.args.revealedCollectionIds) + got, err := ut.CheckDisputeForIds(context.Background(), client, 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 @@ -1076,10 +1077,10 @@ func TestGetBountyIdFromEvents(t *testing.T) { utilsMock.On("EstimateBlockNumberAtEpochBeginning", mock.AnythingOfType("*ethclient.Client"), 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.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("ethereum.FilterQuery")).Return(tt.args.logs, tt.args.logsErr) + clientUtilsMock.On("FilterLogsWithRetry", mock.Anything, 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(client, blockNumber, bountyHunter) + got, err := ut.GetBountyIdFromEvents(context.Background(), client, blockNumber, bountyHunter) if (err != nil) != tt.wantErr { t.Errorf("GetBountyIdFromEvents() error = %v, wantErr %v", err, tt.wantErr) return @@ -1202,22 +1203,22 @@ func BenchmarkHandleDispute(b *testing.B) { Valid: true, BiggestStake: big.NewInt(1).Mul(big.NewInt(5356), big.NewInt(1e18))} - utilsMock.On("GetSortedProposedBlockIds", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(getUint32DummyIds(v.numOfSortedBlocks), nil) - cmdUtilsMock.On("GetBiggestStakeAndId", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(big.NewInt(1).Mul(big.NewInt(5356), big.NewInt(1e18)), uint32(2), nil) - cmdUtilsMock.On("GetLocalMediansData", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(proposedData, nil) - utilsMock.On("GetProposedBlock", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint32")).Return(proposedBlock, nil) - utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) + 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) + 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("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) - cmdUtilsMock.On("CheckDisputeForIds", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&Types.Transaction{}, nil) - utilsMock.On("GetLeafIdOfACollection", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(0, 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("GetBlockManager", mock.AnythingOfType("*ethclient.Client")).Return(blockManager) - cmdUtilsMock.On("StoreBountyId", mock.Anything, mock.Anything).Return(nil) + cmdUtilsMock.On("StoreBountyId", mock.Anything, mock.Anything, mock.Anything).Return(nil) utils := &UtilsStruct{} - err := utils.HandleDispute(client, config, account, epoch, blockNumber, rogueData, backupNodeActionsToIgnore) + err := utils.HandleDispute(context.Background(), client, config, account, epoch, blockNumber, rogueData, backupNodeActionsToIgnore) if err != nil { log.Fatal(err) } @@ -1334,14 +1335,14 @@ func TestStoreBountyId(t *testing.T) { SetUpMockInterfaces() pathMock.On("GetDisputeDataFileName", mock.AnythingOfType("string")).Return(tt.args.disputeFilePath, tt.args.disputeFilePathErr) - clientUtilsMock.On("GetLatestBlockWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.latestHeader, tt.args.latestHeaderErr) - cmdUtilsMock.On("GetBountyIdFromEvents", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.latestBountyId, tt.args.latestBountyIdErr) + clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything, 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(client, account); (err != nil) != tt.wantErr { + if err := ut.StoreBountyId(context.Background(), client, 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 7b8d876fa..f213c03fa 100644 --- a/cmd/eventListeners.go +++ b/cmd/eventListeners.go @@ -1,6 +1,7 @@ package cmd import ( + "context" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" @@ -15,8 +16,8 @@ import ( "strings" ) -func (*UtilsStruct) InitJobAndCollectionCache(client *ethclient.Client) (*cache.JobsCache, *cache.CollectionsCache, *big.Int, error) { - initAssetCacheBlock, err := clientUtils.GetLatestBlockWithRetry(client) +func (*UtilsStruct) InitJobAndCollectionCache(ctx context.Context, client *ethclient.Client) (*cache.JobsCache, *cache.CollectionsCache, *big.Int, error) { + initAssetCacheBlock, err := clientUtils.GetLatestBlockWithRetry(ctx, client) if err != nil { log.Error("Error in fetching block: ", err) return nil, nil, nil, err @@ -43,7 +44,7 @@ func (*UtilsStruct) InitJobAndCollectionCache(client *ethclient.Client) (*cache. } // CheckForJobAndCollectionEvents checks for specific job and collections event that were emitted. -func CheckForJobAndCollectionEvents(client *ethclient.Client, commitParams *types.CommitParams) error { +func CheckForJobAndCollectionEvents(ctx context.Context, client *ethclient.Client, 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) @@ -53,14 +54,14 @@ func CheckForJobAndCollectionEvents(client *ethclient.Client, commitParams *type eventNames := []string{core.JobUpdatedEvent, core.CollectionUpdatedEvent, core.CollectionActivityStatusEvent, core.JobCreatedEvent, core.CollectionCreatedEvent} log.Debug("Checking for Job/Collection update events...") - toBlock, err := clientUtils.GetLatestBlockWithRetry(client) + toBlock, err := clientUtils.GetLatestBlockWithRetry(ctx, client) 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(client, collectionManagerContractABI, commitParams.FromBlockToCheckForEvents, toBlock.Number, eventNames, commitParams.JobsCache, commitParams.CollectionsCache) + newFromBlock, err := processEvents(ctx, client, collectionManagerContractABI, commitParams.FromBlockToCheckForEvents, toBlock.Number, eventNames, commitParams.JobsCache, commitParams.CollectionsCache) if err != nil { return err } @@ -72,8 +73,8 @@ func CheckForJobAndCollectionEvents(client *ethclient.Client, commitParams *type } // processEvents fetches and processes logs for multiple event types. -func processEvents(client *ethclient.Client, contractABI abi.ABI, fromBlock, toBlock *big.Int, eventNames []string, jobsCache *cache.JobsCache, collectionsCache *cache.CollectionsCache) (*big.Int, error) { - logs, err := getEventLogs(client, fromBlock, toBlock) +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) if err != nil { log.Errorf("Failed to fetch logs: %v", err) return nil, err @@ -112,7 +113,7 @@ func processEvents(client *ethclient.Client, contractABI abi.ABI, fromBlock, toB } // getEventLogs is a utility function to fetch the event logs -func getEventLogs(client *ethclient.Client, fromBlock *big.Int, toBlock *big.Int) ([]Types.Log, error) { +func getEventLogs(ctx context.Context, client *ethclient.Client, 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 @@ -125,7 +126,7 @@ func getEventLogs(client *ethclient.Client, fromBlock *big.Int, toBlock *big.Int } // Retrieve the logs - logs, err := clientUtils.FilterLogsWithRetry(client, query) + logs, err := clientUtils.FilterLogsWithRetry(ctx, client, query) if err != nil { log.Errorf("Error in filter logs: %v", err) return []Types.Log{}, err diff --git a/cmd/initTestMocks_test.go b/cmd/initTestMocks_test.go index f410e24a3..f85f76db0 100644 --- a/cmd/initTestMocks_test.go +++ b/cmd/initTestMocks_test.go @@ -1,16 +1,24 @@ package cmd import ( + "context" "crypto/ecdsa" "crypto/rand" + "fmt" + "github.com/avast/retry-go" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/crypto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" "math/big" "razor/cmd/mocks" "razor/path" pathPkgMocks "razor/path/mocks" "razor/utils" utilsPkgMocks "razor/utils/mocks" + "strings" + "testing" + "time" ) var ( @@ -167,3 +175,75 @@ 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 + +func TestInvokeFunctionWithRetryAttempts(t *testing.T) { + tests := []struct { + name string + methodName string + timeout time.Duration + expectError bool + expectedErr string + expectedVals bool + }{ + { + name: "Normal Case - Fast Method", + methodName: "FastMethod", + timeout: 5 * time.Second, + expectError: false, + expectedErr: "", + expectedVals: true, + }, + { + name: "Timeout Case - Slow Method", + methodName: "SlowMethod", + timeout: 0 * time.Second, + expectError: true, + expectedErr: "context deadline exceeded", + expectedVals: false, + }, + } + + // Dummy RPC struct + dummyRPC := &DummyRPC{} + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Set up context with timeout for each test case + ctx, cancel := context.WithTimeout(context.Background(), tt.timeout) + defer cancel() + + SetUpMockInterfaces() + retryUtilsMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(4)) + + returnedValues, err := utils.InvokeFunctionWithRetryAttempts(ctx, dummyRPC, tt.methodName) + + if tt.expectError { + assert.Error(t, err) + assert.True(t, strings.Contains(err.Error(), tt.expectedErr), "Expected error to contain: %v, but got: %v", tt.expectedErr, err.Error()) + } else { + assert.NoError(t, err) + } + + if tt.expectedVals { + assert.NotNil(t, returnedValues) + } else { + assert.Nil(t, returnedValues) + } + }) + } +} + +// Dummy interface with methods +type DummyRPC struct{} + +// A fast method that simulates successful execution +func (d *DummyRPC) FastMethod() error { + return nil +} + +// A slow method that simulates a long-running process +func (d *DummyRPC) SlowMethod() error { + fmt.Println("Sleeping...") + time.Sleep(3 * time.Second) // Simulate delay to trigger timeout + return nil +} diff --git a/cmd/initiateWithdraw.go b/cmd/initiateWithdraw.go index f1393c452..30a426499 100644 --- a/cmd/initiateWithdraw.go +++ b/cmd/initiateWithdraw.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "errors" "math/big" "razor/accounts" @@ -59,12 +60,12 @@ func (*UtilsStruct) ExecuteInitiateWithdraw(flagSet *pflag.FlagSet) { err = razorUtils.CheckPassword(account) utils.CheckError("Error in fetching private key from given password: ", err) - stakerId, err := razorUtils.AssignStakerId(flagSet, client, address) + stakerId, err := razorUtils.AssignStakerId(context.Background(), flagSet, client, 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(client, account, config, stakerId) + txn, err := cmdUtils.HandleUnstakeLock(context.Background(), client, account, config, stakerId) utils.CheckError("InitiateWithdraw error: ", err) if txn != core.NilHash { @@ -74,8 +75,8 @@ func (*UtilsStruct) ExecuteInitiateWithdraw(flagSet *pflag.FlagSet) { } //This function handles the unstake lock -func (*UtilsStruct) HandleUnstakeLock(client *ethclient.Client, account types.Account, configurations types.Configurations, stakerId uint32) (common.Hash, error) { - unstakeLock, err := razorUtils.GetLock(client, account.Address, stakerId, 0) +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) if err != nil { log.Error("Error in fetching unstakeLock") return core.NilHash, err @@ -87,7 +88,7 @@ func (*UtilsStruct) HandleUnstakeLock(client *ethclient.Client, account types.Ac return core.NilHash, errors.New("unstake Razors before withdrawing") } - withdrawInitiationPeriod, err := razorUtils.GetWithdrawInitiationPeriod(client) + withdrawInitiationPeriod, err := razorUtils.GetWithdrawInitiationPeriod(ctx, client) if err != nil { log.Error("Error in fetching withdraw release period") return core.NilHash, err @@ -96,7 +97,7 @@ func (*UtilsStruct) HandleUnstakeLock(client *ethclient.Client, account types.Ac withdrawBefore := big.NewInt(0).Add(unstakeLock.UnlockAfter, big.NewInt(int64(withdrawInitiationPeriod))) log.Debug("HandleUnstakeLock: Withdraw before epoch: ", withdrawBefore) - epoch, err := razorUtils.GetEpoch(client) + epoch, err := razorUtils.GetEpoch(ctx, client) if err != nil { log.Error("Error in fetching epoch") return core.NilHash, err @@ -116,7 +117,7 @@ func (*UtilsStruct) HandleUnstakeLock(client *ethclient.Client, account types.Ac } log.Debug("Waiting for appropriate state to initiate withdraw...") - _, err = cmdUtils.WaitForAppropriateState(client, "initiateWithdraw", 0, 1, 4) + _, err = cmdUtils.WaitForAppropriateState(ctx, client, "initiateWithdraw", 0, 1, 4) if err != nil { log.Error("Error in fetching state: ", err) return core.NilHash, err @@ -132,7 +133,7 @@ func (*UtilsStruct) HandleUnstakeLock(client *ethclient.Client, account types.Ac Parameters: []interface{}{stakerId}, Account: account, } - txnOpts := razorUtils.GetTxnOpts(txnArgs) + txnOpts := razorUtils.GetTxnOpts(ctx, 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) diff --git a/cmd/initiateWithdraw_test.go b/cmd/initiateWithdraw_test.go index ac827497f..975aa810c 100644 --- a/cmd/initiateWithdraw_test.go +++ b/cmd/initiateWithdraw_test.go @@ -1,6 +1,7 @@ package cmd import ( + "context" "crypto/ecdsa" "crypto/rand" "errors" @@ -179,16 +180,16 @@ func TestHandleUnstakeLock(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - cmdUtilsMock.On("WaitForAppropriateState", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.state, tt.args.stateErr) - utilsMock.On("GetLock", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string"), mock.AnythingOfType("uint32"), mock.Anything).Return(tt.args.lock, tt.args.lockErr) - utilsMock.On("GetWithdrawInitiationPeriod", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.withdrawReleasePeriod, tt.args.withdrawReleasePeriodErr) - utilsMock.On("GetEpoch", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.epoch, tt.args.epochErr) - utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(TxnOpts) + 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) + 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("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(client, account, configurations, stakerId) + got, err := utils.HandleUnstakeLock(context.Background(), client, account, configurations, stakerId) if got != tt.want { t.Errorf("Txn hash for withdrawFunds function, got = %v, want = %v", got, tt.want) } @@ -367,9 +368,9 @@ func TestExecuteWithdraw(t *testing.T) { 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", flagSet, mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) + utilsMock.On("AssignStakerId", mock.Anything, flagSet, 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).Return(tt.args.withdrawHash, tt.args.withdrawErr) + 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) utils := &UtilsStruct{} diff --git a/cmd/interface.go b/cmd/interface.go index 51a1e127d..fd3f3b8d1 100644 --- a/cmd/interface.go +++ b/cmd/interface.go @@ -163,62 +163,62 @@ type UtilsCmdInterface interface { GetConfigData() (types.Configurations, error) ExecuteClaimBounty(flagSet *pflag.FlagSet) ClaimBounty(config types.Configurations, client *ethclient.Client, redeemBountyInput types.RedeemBountyInput) (common.Hash, error) - ClaimBlockReward(options types.TransactionOptions) (common.Hash, error) - GetSalt(client *ethclient.Client, epoch uint32) ([32]byte, error) - HandleCommitState(client *ethclient.Client, epoch uint32, seed []byte, commitParams *types.CommitParams, rogueData types.Rogue) (types.CommitData, error) - Commit(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, latestHeader *Types.Header, seed []byte, values []*big.Int) (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, seed []byte, values []*big.Int) (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(client *ethclient.Client, staker bindings.StructsStaker, epoch uint32) error - Reveal(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, latestHeader *Types.Header, commitData types.CommitData, signature []byte) (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) GenerateTreeRevealData(merkleTree [][][]byte, commitData types.CommitData) bindings.StructsMerkleTree - IndexRevealEventsOfCurrentEpoch(client *ethclient.Client, blockNumber *big.Int, epoch uint32) ([]types.RevealedStruct, error) + IndexRevealEventsOfCurrentEpoch(ctx context.Context, client *ethclient.Client, 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) ExecuteCreateCollection(flagSet *pflag.FlagSet) CreateCollection(client *ethclient.Client, config types.Configurations, collectionInput types.CreateCollectionInput) (common.Hash, error) - GetEpochAndState(client *ethclient.Client) (uint32, int64, error) - WaitForAppropriateState(client *ethclient.Client, action string, states ...int) (uint32, error) + GetEpochAndState(ctx context.Context, client *ethclient.Client) (uint32, int64, error) + WaitForAppropriateState(ctx context.Context, client *ethclient.Client, action string, states ...int) (uint32, error) ExecuteJobList(flagSet *pflag.FlagSet) GetJobList(client *ethclient.Client) error ExecuteUnstake(flagSet *pflag.FlagSet) - Unstake(config types.Configurations, client *ethclient.Client, input types.UnstakeInput) (common.Hash, error) + 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) 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(client *ethclient.Client, account types.Account, configurations types.Configurations, stakerId uint32) (common.Hash, error) - HandleWithdrawLock(client *ethclient.Client, account types.Account, configurations types.Configurations, 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) ExecuteUpdateJob(flagSet *pflag.FlagSet) - UpdateJob(client *ethclient.Client, config types.Configurations, jobInput types.CreateJobInput, jobId uint16) (common.Hash, error) - WaitIfCommitState(client *ethclient.Client, action string) (uint32, error) + 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) ExecuteCollectionList(flagSet *pflag.FlagSet) GetCollectionList(client *ethclient.Client) error ExecuteStakerinfo(flagSet *pflag.FlagSet) ExecuteSetDelegation(flagSet *pflag.FlagSet) - SetDelegation(client *ethclient.Client, config types.Configurations, delegationInput types.SetDelegationInput) (common.Hash, error) - GetStakerInfo(client *ethclient.Client, stakerId uint32) error + 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 ExecuteUpdateCollection(flagSet *pflag.FlagSet) - UpdateCollection(client *ethclient.Client, config types.Configurations, collectionInput types.CreateCollectionInput, collectionId uint16) (common.Hash, error) - MakeBlock(client *ethclient.Client, blockNumber *big.Int, epoch uint32, rogueData types.Rogue) ([]*big.Int, []uint16, *types.RevealedDataMaps, error) + 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) IsElectedProposer(proposer types.ElectedProposer, currentStakerStake *big.Int) bool - GetSortedRevealedValues(client *ethclient.Client, blockNumber *big.Int, epoch uint32) (*types.RevealedDataMaps, error) - GetIteration(client *ethclient.Client, proposer types.ElectedProposer, bufferPercent int32) int - Propose(client *ethclient.Client, config types.Configurations, account types.Account, staker bindings.StructsStaker, epoch uint32, latestHeader *Types.Header, rogueData types.Rogue) error - GiveSorted(client *ethclient.Client, blockManager *bindings.BlockManager, txnArgs types.TransactionOptions, epoch uint32, assetId uint16, sortedStakers []*big.Int) error - GetLocalMediansData(client *ethclient.Client, account types.Account, epoch uint32, blockNumber *big.Int, rogueData types.Rogue) (types.ProposeFileData, error) - CheckDisputeForIds(client *ethclient.Client, transactionOpts types.TransactionOptions, epoch uint32, blockIndex uint8, idsInProposedBlock []uint16, revealedCollectionIds []uint16) (*Types.Transaction, error) - Dispute(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, blockIndex uint8, proposedBlock bindings.StructsBlock, leafId uint16, sortedValues []*big.Int) error + 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(client *ethclient.Client, leafId uint16, proposedBlock bindings.StructsBlock) *big.Int - HandleDispute(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, blockNumber *big.Int, rogueData types.Rogue, backupNodeActionsToIgnore []string) error + HandleDispute(ctx context.Context, client *ethclient.Client, 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) ExecuteModifyCollectionStatus(flagSet *pflag.FlagSet) - ModifyCollectionStatus(client *ethclient.Client, config types.Configurations, modifyCollectionInput types.ModifyCollectionInput) (common.Hash, error) + ModifyCollectionStatus(ctx context.Context, client *ethclient.Client, config types.Configurations, modifyCollectionInput types.ModifyCollectionInput) (common.Hash, error) Approve(txnArgs types.TransactionOptions) (common.Hash, error) ExecuteDelegate(flagSet *pflag.FlagSet) Delegate(txnArgs types.TransactionOptions, stakerId uint32) (common.Hash, error) @@ -227,9 +227,9 @@ type UtilsCmdInterface interface { ExecuteImport(flagSet *pflag.FlagSet) ImportAccount() (accounts.Account, error) ExecuteUpdateCommission(flagSet *pflag.FlagSet) - UpdateCommission(config types.Configurations, client *ethclient.Client, updateCommissionInput types.UpdateCommissionInput) error - GetBiggestStakeAndId(client *ethclient.Client, epoch uint32) (*big.Int, uint32, error) - GetSmallestStakeAndId(client *ethclient.Client, epoch uint32) (*big.Int, uint32, error) + 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) 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) @@ -239,17 +239,17 @@ type UtilsCmdInterface interface { ExecuteListAccounts(flagSet *pflag.FlagSet) ClaimCommission(flagSet *pflag.FlagSet) ExecuteStake(flagSet *pflag.FlagSet) - InitiateCommit(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, stakerId uint32, latestHeader *Types.Header, commitParams *types.CommitParams, rogueData types.Rogue) error - InitiateReveal(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, latestHeader *Types.Header, rogueData types.Rogue) error - InitiatePropose(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, latestHeader *Types.Header, rogueData types.Rogue) error - GetBountyIdFromEvents(client *ethclient.Client, blockNumber *big.Int, bountyHunter string) (uint32, error) + 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 ExecuteContractAddresses(flagSet *pflag.FlagSet) ContractAddresses() ResetDispute(client *ethclient.Client, blockManager *bindings.BlockManager, txnOpts *bind.TransactOpts, epoch uint32) - StoreBountyId(client *ethclient.Client, account types.Account) error + 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(client *ethclient.Client) (*cache.JobsCache, *cache.CollectionsCache, *big.Int, error) + 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) } diff --git a/cmd/mocks/utils_cmd_interface.go b/cmd/mocks/utils_cmd_interface.go index b957be0e5..4a71651c0 100644 --- a/cmd/mocks/utils_cmd_interface.go +++ b/cmd/mocks/utils_cmd_interface.go @@ -196,25 +196,25 @@ func (_m *UtilsCmdInterface) CheckCurrentStatus(client *ethclient.Client, collec return r0, r1 } -// CheckDisputeForIds provides a mock function with given fields: client, transactionOpts, epoch, blockIndex, idsInProposedBlock, revealedCollectionIds -func (_m *UtilsCmdInterface) CheckDisputeForIds(client *ethclient.Client, transactionOpts types.TransactionOptions, epoch uint32, blockIndex uint8, idsInProposedBlock []uint16, revealedCollectionIds []uint16) (*coretypes.Transaction, error) { - ret := _m.Called(client, transactionOpts, epoch, blockIndex, idsInProposedBlock, revealedCollectionIds) +// 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) var r0 *coretypes.Transaction var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.TransactionOptions, uint32, uint8, []uint16, []uint16) (*coretypes.Transaction, error)); ok { - return rf(client, transactionOpts, epoch, blockIndex, idsInProposedBlock, revealedCollectionIds) + 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(*ethclient.Client, types.TransactionOptions, uint32, uint8, []uint16, []uint16) *coretypes.Transaction); ok { - r0 = rf(client, 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) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*coretypes.Transaction) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, types.TransactionOptions, uint32, uint8, []uint16, []uint16) error); ok { - r1 = rf(client, transactionOpts, epoch, blockIndex, idsInProposedBlock, revealedCollectionIds) + 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) } else { r1 = ret.Error(1) } @@ -222,13 +222,13 @@ func (_m *UtilsCmdInterface) CheckDisputeForIds(client *ethclient.Client, transa return r0, r1 } -// CheckForLastCommitted provides a mock function with given fields: client, staker, epoch -func (_m *UtilsCmdInterface) CheckForLastCommitted(client *ethclient.Client, staker bindings.StructsStaker, epoch uint32) error { - ret := _m.Called(client, staker, epoch) +// 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) var r0 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, bindings.StructsStaker, uint32) error); ok { - r0 = rf(client, staker, epoch) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, bindings.StructsStaker, uint32) error); ok { + r0 = rf(ctx, client, staker, epoch) } else { r0 = ret.Error(0) } @@ -241,25 +241,25 @@ func (_m *UtilsCmdInterface) CheckToDoResetDispute(client *ethclient.Client, blo _m.Called(client, blockManager, txnOpts, epoch, sortedValues) } -// ClaimBlockReward provides a mock function with given fields: options -func (_m *UtilsCmdInterface) ClaimBlockReward(options types.TransactionOptions) (common.Hash, error) { - ret := _m.Called(options) +// 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) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(types.TransactionOptions) (common.Hash, error)); ok { - return rf(options) + 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(types.TransactionOptions) common.Hash); ok { - r0 = rf(options) + if rf, ok := ret.Get(0).(func(context.Context, types.TransactionOptions) common.Hash); ok { + r0 = rf(ctx, options) } 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(options) + if rf, ok := ret.Get(1).(func(context.Context, types.TransactionOptions) error); ok { + r1 = rf(ctx, options) } else { r1 = ret.Error(1) } @@ -298,25 +298,25 @@ func (_m *UtilsCmdInterface) ClaimCommission(flagSet *pflag.FlagSet) { _m.Called(flagSet) } -// Commit provides a mock function with given fields: client, config, account, epoch, latestHeader, seed, values -func (_m *UtilsCmdInterface) Commit(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, latestHeader *coretypes.Header, seed []byte, values []*big.Int) (common.Hash, error) { - ret := _m.Called(client, config, account, epoch, latestHeader, seed, values) +// Commit provides a mock function with given fields: ctx, client, config, account, epoch, latestHeader, stateBuffer, seed, values +func (_m *UtilsCmdInterface) Commit(ctx context.Context, client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, latestHeader *coretypes.Header, stateBuffer uint64, seed []byte, values []*big.Int) (common.Hash, error) { + ret := _m.Called(ctx, client, config, account, epoch, latestHeader, stateBuffer, seed, values) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations, types.Account, uint32, *coretypes.Header, []byte, []*big.Int) (common.Hash, error)); ok { - return rf(client, config, account, epoch, latestHeader, seed, values) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Configurations, types.Account, uint32, *coretypes.Header, uint64, []byte, []*big.Int) (common.Hash, error)); ok { + return rf(ctx, client, config, account, epoch, latestHeader, stateBuffer, seed, values) } - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations, types.Account, uint32, *coretypes.Header, []byte, []*big.Int) common.Hash); ok { - r0 = rf(client, config, account, epoch, latestHeader, seed, values) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Configurations, types.Account, uint32, *coretypes.Header, uint64, []byte, []*big.Int) common.Hash); ok { + r0 = rf(ctx, client, config, account, epoch, latestHeader, stateBuffer, seed, values) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, types.Configurations, types.Account, uint32, *coretypes.Header, []byte, []*big.Int) error); ok { - r1 = rf(client, config, account, epoch, latestHeader, seed, values) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, types.Configurations, types.Account, uint32, *coretypes.Header, uint64, []byte, []*big.Int) error); ok { + r1 = rf(ctx, client, config, account, epoch, latestHeader, stateBuffer, seed, values) } else { r1 = ret.Error(1) } @@ -431,13 +431,13 @@ func (_m *UtilsCmdInterface) Delegate(txnArgs types.TransactionOptions, stakerId return r0, r1 } -// Dispute provides a mock function with given fields: client, config, account, epoch, blockIndex, proposedBlock, leafId, sortedValues -func (_m *UtilsCmdInterface) Dispute(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(client, config, account, epoch, blockIndex, proposedBlock, leafId, sortedValues) +// 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) var r0 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations, types.Account, uint32, uint8, bindings.StructsBlock, uint16, []*big.Int) error); ok { - r0 = rf(client, config, account, epoch, blockIndex, proposedBlock, leafId, sortedValues) + 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) } else { r0 = ret.Error(0) } @@ -598,32 +598,32 @@ func (_m *UtilsCmdInterface) GetAlternateProvider() (string, error) { return r0, r1 } -// GetBiggestStakeAndId provides a mock function with given fields: client, epoch -func (_m *UtilsCmdInterface) GetBiggestStakeAndId(client *ethclient.Client, epoch uint32) (*big.Int, uint32, error) { - ret := _m.Called(client, epoch) +// 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) var r0 *big.Int var r1 uint32 var r2 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32) (*big.Int, uint32, error)); ok { - return rf(client, epoch) + 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(*ethclient.Client, uint32) *big.Int); ok { - r0 = rf(client, epoch) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) *big.Int); ok { + r0 = rf(ctx, client, epoch) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32) uint32); ok { - r1 = rf(client, epoch) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32) uint32); ok { + r1 = rf(ctx, client, epoch) } else { r1 = ret.Get(1).(uint32) } - if rf, ok := ret.Get(2).(func(*ethclient.Client, uint32) error); ok { - r2 = rf(client, epoch) + if rf, ok := ret.Get(2).(func(context.Context, *ethclient.Client, uint32) error); ok { + r2 = rf(ctx, client, epoch) } else { r2 = ret.Error(2) } @@ -631,23 +631,23 @@ func (_m *UtilsCmdInterface) GetBiggestStakeAndId(client *ethclient.Client, epoc return r0, r1, r2 } -// GetBountyIdFromEvents provides a mock function with given fields: client, blockNumber, bountyHunter -func (_m *UtilsCmdInterface) GetBountyIdFromEvents(client *ethclient.Client, blockNumber *big.Int, bountyHunter string) (uint32, error) { - ret := _m.Called(client, blockNumber, bountyHunter) +// 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) var r0 uint32 var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, *big.Int, string) (uint32, error)); ok { - return rf(client, blockNumber, bountyHunter) + 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(*ethclient.Client, *big.Int, string) uint32); ok { - r0 = rf(client, blockNumber, bountyHunter) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, *big.Int, string) uint32); ok { + r0 = rf(ctx, client, blockNumber, bountyHunter) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(*ethclient.Client, *big.Int, string) error); ok { - r1 = rf(client, blockNumber, bountyHunter) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, *big.Int, string) error); ok { + r1 = rf(ctx, client, blockNumber, bountyHunter) } else { r1 = ret.Error(1) } @@ -733,30 +733,30 @@ func (_m *UtilsCmdInterface) GetConfigData() (types.Configurations, error) { return r0, r1 } -// GetEpochAndState provides a mock function with given fields: client -func (_m *UtilsCmdInterface) GetEpochAndState(client *ethclient.Client) (uint32, int64, error) { - ret := _m.Called(client) +// 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) var r0 uint32 var r1 int64 var r2 error - if rf, ok := ret.Get(0).(func(*ethclient.Client) (uint32, int64, error)); ok { - return rf(client) + 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(*ethclient.Client) uint32); ok { - r0 = rf(client) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) uint32); ok { + r0 = rf(ctx, client) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(*ethclient.Client) int64); ok { - r1 = rf(client) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) int64); ok { + r1 = rf(ctx, client) } else { r1 = ret.Get(1).(int64) } - if rf, ok := ret.Get(2).(func(*ethclient.Client) error); ok { - r2 = rf(client) + if rf, ok := ret.Get(2).(func(context.Context, *ethclient.Client) error); ok { + r2 = rf(ctx, client) } else { r2 = ret.Error(2) } @@ -860,13 +860,13 @@ func (_m *UtilsCmdInterface) GetHTTPTimeout() (int64, error) { return r0, r1 } -// GetIteration provides a mock function with given fields: client, proposer, bufferPercent -func (_m *UtilsCmdInterface) GetIteration(client *ethclient.Client, proposer types.ElectedProposer, bufferPercent int32) int { - ret := _m.Called(client, proposer, bufferPercent) +// 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) var r0 int - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.ElectedProposer, int32) int); ok { - r0 = rf(client, proposer, bufferPercent) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.ElectedProposer, int32) int); ok { + r0 = rf(ctx, client, proposer, bufferPercent) } else { r0 = ret.Get(0).(int) } @@ -888,23 +888,23 @@ func (_m *UtilsCmdInterface) GetJobList(client *ethclient.Client) error { return r0 } -// GetLocalMediansData provides a mock function with given fields: client, account, epoch, blockNumber, rogueData -func (_m *UtilsCmdInterface) GetLocalMediansData(client *ethclient.Client, account types.Account, epoch uint32, blockNumber *big.Int, rogueData types.Rogue) (types.ProposeFileData, error) { - ret := _m.Called(client, account, epoch, blockNumber, rogueData) +// 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) var r0 types.ProposeFileData var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Account, uint32, *big.Int, types.Rogue) (types.ProposeFileData, error)); ok { - return rf(client, account, epoch, blockNumber, rogueData) + 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(*ethclient.Client, types.Account, uint32, *big.Int, types.Rogue) types.ProposeFileData); ok { - r0 = rf(client, 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) } else { r0 = ret.Get(0).(types.ProposeFileData) } - if rf, ok := ret.Get(1).(func(*ethclient.Client, types.Account, uint32, *big.Int, types.Rogue) error); ok { - r1 = rf(client, account, epoch, blockNumber, rogueData) + 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) } else { r1 = ret.Error(1) } @@ -1080,25 +1080,25 @@ func (_m *UtilsCmdInterface) GetRPCTimeout() (int64, error) { return r0, r1 } -// GetSalt provides a mock function with given fields: client, epoch -func (_m *UtilsCmdInterface) GetSalt(client *ethclient.Client, epoch uint32) ([32]byte, error) { - ret := _m.Called(client, epoch) +// 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) var r0 [32]byte var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32) ([32]byte, error)); ok { - return rf(client, epoch) + 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(*ethclient.Client, uint32) [32]byte); ok { - r0 = rf(client, epoch) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) [32]byte); ok { + r0 = rf(ctx, client, epoch) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([32]byte) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32) error); ok { - r1 = rf(client, epoch) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32) error); ok { + r1 = rf(ctx, client, epoch) } else { r1 = ret.Error(1) } @@ -1106,32 +1106,32 @@ func (_m *UtilsCmdInterface) GetSalt(client *ethclient.Client, epoch uint32) ([3 return r0, r1 } -// GetSmallestStakeAndId provides a mock function with given fields: client, epoch -func (_m *UtilsCmdInterface) GetSmallestStakeAndId(client *ethclient.Client, epoch uint32) (*big.Int, uint32, error) { - ret := _m.Called(client, epoch) +// 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) var r0 *big.Int var r1 uint32 var r2 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32) (*big.Int, uint32, error)); ok { - return rf(client, epoch) + 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(*ethclient.Client, uint32) *big.Int); ok { - r0 = rf(client, epoch) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) *big.Int); ok { + r0 = rf(ctx, client, epoch) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32) uint32); ok { - r1 = rf(client, epoch) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32) uint32); ok { + r1 = rf(ctx, client, epoch) } else { r1 = ret.Get(1).(uint32) } - if rf, ok := ret.Get(2).(func(*ethclient.Client, uint32) error); ok { - r2 = rf(client, epoch) + if rf, ok := ret.Get(2).(func(context.Context, *ethclient.Client, uint32) error); ok { + r2 = rf(ctx, client, epoch) } else { r2 = ret.Error(2) } @@ -1139,25 +1139,25 @@ func (_m *UtilsCmdInterface) GetSmallestStakeAndId(client *ethclient.Client, epo return r0, r1, r2 } -// GetSortedRevealedValues provides a mock function with given fields: client, blockNumber, epoch -func (_m *UtilsCmdInterface) GetSortedRevealedValues(client *ethclient.Client, blockNumber *big.Int, epoch uint32) (*types.RevealedDataMaps, error) { - ret := _m.Called(client, blockNumber, epoch) +// 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) var r0 *types.RevealedDataMaps var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, *big.Int, uint32) (*types.RevealedDataMaps, error)); ok { - return rf(client, blockNumber, epoch) + 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(*ethclient.Client, *big.Int, uint32) *types.RevealedDataMaps); ok { - r0 = rf(client, 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) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*types.RevealedDataMaps) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, *big.Int, uint32) error); ok { - r1 = rf(client, blockNumber, epoch) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, *big.Int, uint32) error); ok { + r1 = rf(ctx, client, blockNumber, epoch) } else { r1 = ret.Error(1) } @@ -1165,13 +1165,13 @@ func (_m *UtilsCmdInterface) GetSortedRevealedValues(client *ethclient.Client, b return r0, r1 } -// GetStakerInfo provides a mock function with given fields: client, stakerId -func (_m *UtilsCmdInterface) GetStakerInfo(client *ethclient.Client, stakerId uint32) error { - ret := _m.Called(client, stakerId) +// 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) var r0 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32) error); ok { - r0 = rf(client, stakerId) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) error); ok { + r0 = rf(ctx, client, stakerId) } else { r0 = ret.Error(0) } @@ -1203,13 +1203,13 @@ func (_m *UtilsCmdInterface) GetWaitTime() (int32, error) { return r0, r1 } -// GiveSorted provides a mock function with given fields: client, blockManager, txnArgs, epoch, assetId, sortedStakers -func (_m *UtilsCmdInterface) GiveSorted(client *ethclient.Client, blockManager *bindings.BlockManager, txnArgs types.TransactionOptions, epoch uint32, assetId uint16, sortedStakers []*big.Int) error { - ret := _m.Called(client, blockManager, txnArgs, epoch, assetId, sortedStakers) +// 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) var r0 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, *bindings.BlockManager, types.TransactionOptions, uint32, uint16, []*big.Int) error); ok { - r0 = rf(client, blockManager, txnArgs, epoch, assetId, sortedStakers) + 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) } else { r0 = ret.Error(0) } @@ -1236,23 +1236,23 @@ func (_m *UtilsCmdInterface) HandleClaimBounty(client *ethclient.Client, config return r0 } -// HandleCommitState provides a mock function with given fields: client, epoch, seed, commitParams, rogueData -func (_m *UtilsCmdInterface) HandleCommitState(client *ethclient.Client, epoch uint32, seed []byte, commitParams *types.CommitParams, rogueData types.Rogue) (types.CommitData, error) { - ret := _m.Called(client, epoch, seed, commitParams, rogueData) +// 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) var r0 types.CommitData var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32, []byte, *types.CommitParams, types.Rogue) (types.CommitData, error)); ok { - return rf(client, epoch, seed, commitParams, rogueData) + 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(*ethclient.Client, uint32, []byte, *types.CommitParams, types.Rogue) types.CommitData); ok { - r0 = rf(client, 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) } else { r0 = ret.Get(0).(types.CommitData) } - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32, []byte, *types.CommitParams, types.Rogue) error); ok { - r1 = rf(client, epoch, seed, commitParams, rogueData) + 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) } else { r1 = ret.Error(1) } @@ -1260,13 +1260,13 @@ func (_m *UtilsCmdInterface) HandleCommitState(client *ethclient.Client, epoch u return r0, r1 } -// HandleDispute provides a mock function with given fields: client, config, account, epoch, blockNumber, rogueData, backupNodeActionsToIgnore -func (_m *UtilsCmdInterface) HandleDispute(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, blockNumber *big.Int, rogueData types.Rogue, backupNodeActionsToIgnore []string) error { - ret := _m.Called(client, config, account, epoch, blockNumber, rogueData, backupNodeActionsToIgnore) +// 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) var r0 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations, types.Account, uint32, *big.Int, types.Rogue, []string) error); ok { - r0 = rf(client, config, account, epoch, blockNumber, rogueData, backupNodeActionsToIgnore) + 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) } else { r0 = ret.Error(0) } @@ -1279,25 +1279,25 @@ func (_m *UtilsCmdInterface) HandleExit() { _m.Called() } -// HandleUnstakeLock provides a mock function with given fields: client, account, configurations, stakerId -func (_m *UtilsCmdInterface) HandleUnstakeLock(client *ethclient.Client, account types.Account, configurations types.Configurations, stakerId uint32) (common.Hash, error) { - ret := _m.Called(client, account, configurations, stakerId) +// 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) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Account, types.Configurations, uint32) (common.Hash, error)); ok { - return rf(client, account, configurations, stakerId) + 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(*ethclient.Client, types.Account, types.Configurations, uint32) common.Hash); ok { - r0 = rf(client, 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) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, types.Account, types.Configurations, uint32) error); ok { - r1 = rf(client, account, configurations, stakerId) + 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) } else { r1 = ret.Error(1) } @@ -1305,25 +1305,25 @@ func (_m *UtilsCmdInterface) HandleUnstakeLock(client *ethclient.Client, account return r0, r1 } -// HandleWithdrawLock provides a mock function with given fields: client, account, configurations, stakerId -func (_m *UtilsCmdInterface) HandleWithdrawLock(client *ethclient.Client, account types.Account, configurations types.Configurations, stakerId uint32) (common.Hash, error) { - ret := _m.Called(client, account, configurations, stakerId) +// 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) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Account, types.Configurations, uint32) (common.Hash, error)); ok { - return rf(client, account, configurations, stakerId) + 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(*ethclient.Client, types.Account, types.Configurations, uint32) common.Hash); ok { - r0 = rf(client, 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) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, types.Account, types.Configurations, uint32) error); ok { - r1 = rf(client, account, configurations, stakerId) + 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) } else { r1 = ret.Error(1) } @@ -1355,25 +1355,25 @@ func (_m *UtilsCmdInterface) ImportAccount() (accounts.Account, error) { return r0, r1 } -// IndexRevealEventsOfCurrentEpoch provides a mock function with given fields: client, blockNumber, epoch -func (_m *UtilsCmdInterface) IndexRevealEventsOfCurrentEpoch(client *ethclient.Client, blockNumber *big.Int, epoch uint32) ([]types.RevealedStruct, error) { - ret := _m.Called(client, blockNumber, epoch) +// 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) var r0 []types.RevealedStruct var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, *big.Int, uint32) ([]types.RevealedStruct, error)); ok { - return rf(client, blockNumber, epoch) + 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(*ethclient.Client, *big.Int, uint32) []types.RevealedStruct); ok { - r0 = rf(client, 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) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]types.RevealedStruct) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, *big.Int, uint32) error); ok { - r1 = rf(client, blockNumber, epoch) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, *big.Int, uint32) error); ok { + r1 = rf(ctx, client, blockNumber, epoch) } else { r1 = ret.Error(1) } @@ -1381,43 +1381,43 @@ func (_m *UtilsCmdInterface) IndexRevealEventsOfCurrentEpoch(client *ethclient.C return r0, r1 } -// InitJobAndCollectionCache provides a mock function with given fields: client -func (_m *UtilsCmdInterface) InitJobAndCollectionCache(client *ethclient.Client) (*cache.JobsCache, *cache.CollectionsCache, *big.Int, error) { - ret := _m.Called(client) +// 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) var r0 *cache.JobsCache var r1 *cache.CollectionsCache var r2 *big.Int var r3 error - if rf, ok := ret.Get(0).(func(*ethclient.Client) (*cache.JobsCache, *cache.CollectionsCache, *big.Int, error)); ok { - return rf(client) + 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(*ethclient.Client) *cache.JobsCache); ok { - r0 = rf(client) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) *cache.JobsCache); ok { + r0 = rf(ctx, client) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*cache.JobsCache) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client) *cache.CollectionsCache); ok { - r1 = rf(client) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) *cache.CollectionsCache); ok { + r1 = rf(ctx, client) } else { if ret.Get(1) != nil { r1 = ret.Get(1).(*cache.CollectionsCache) } } - if rf, ok := ret.Get(2).(func(*ethclient.Client) *big.Int); ok { - r2 = rf(client) + if rf, ok := ret.Get(2).(func(context.Context, *ethclient.Client) *big.Int); ok { + r2 = rf(ctx, client) } else { if ret.Get(2) != nil { r2 = ret.Get(2).(*big.Int) } } - if rf, ok := ret.Get(3).(func(*ethclient.Client) error); ok { - r3 = rf(client) + if rf, ok := ret.Get(3).(func(context.Context, *ethclient.Client) error); ok { + r3 = rf(ctx, client) } else { r3 = ret.Error(3) } @@ -1425,13 +1425,13 @@ func (_m *UtilsCmdInterface) InitJobAndCollectionCache(client *ethclient.Client) return r0, r1, r2, r3 } -// InitiateCommit provides a mock function with given fields: client, config, account, epoch, stakerId, latestHeader, commitParams, rogueData -func (_m *UtilsCmdInterface) InitiateCommit(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, stakerId uint32, latestHeader *coretypes.Header, commitParams *types.CommitParams, rogueData types.Rogue) error { - ret := _m.Called(client, config, account, epoch, stakerId, latestHeader, commitParams, rogueData) +// 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) var r0 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations, types.Account, uint32, uint32, *coretypes.Header, *types.CommitParams, types.Rogue) error); ok { - r0 = rf(client, config, account, epoch, stakerId, latestHeader, commitParams, rogueData) + 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) } else { r0 = ret.Error(0) } @@ -1439,13 +1439,13 @@ func (_m *UtilsCmdInterface) InitiateCommit(client *ethclient.Client, config typ return r0 } -// InitiatePropose provides a mock function with given fields: client, config, account, epoch, staker, latestHeader, rogueData -func (_m *UtilsCmdInterface) InitiatePropose(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, latestHeader *coretypes.Header, rogueData types.Rogue) error { - ret := _m.Called(client, config, account, epoch, staker, latestHeader, rogueData) +// 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) var r0 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations, types.Account, uint32, bindings.StructsStaker, *coretypes.Header, types.Rogue) error); ok { - r0 = rf(client, config, account, epoch, staker, latestHeader, rogueData) + 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) } else { r0 = ret.Error(0) } @@ -1453,13 +1453,13 @@ func (_m *UtilsCmdInterface) InitiatePropose(client *ethclient.Client, config ty return r0 } -// InitiateReveal provides a mock function with given fields: client, config, account, epoch, staker, latestHeader, rogueData -func (_m *UtilsCmdInterface) InitiateReveal(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, latestHeader *coretypes.Header, rogueData types.Rogue) error { - ret := _m.Called(client, config, account, epoch, staker, latestHeader, rogueData) +// 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) var r0 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations, types.Account, uint32, bindings.StructsStaker, *coretypes.Header, types.Rogue) error); ok { - r0 = rf(client, config, account, epoch, staker, latestHeader, rogueData) + 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) } else { r0 = ret.Error(0) } @@ -1533,43 +1533,43 @@ func (_m *UtilsCmdInterface) ListAccounts() ([]accounts.Account, error) { return r0, r1 } -// MakeBlock provides a mock function with given fields: client, blockNumber, epoch, rogueData -func (_m *UtilsCmdInterface) MakeBlock(client *ethclient.Client, blockNumber *big.Int, epoch uint32, rogueData types.Rogue) ([]*big.Int, []uint16, *types.RevealedDataMaps, error) { - ret := _m.Called(client, blockNumber, epoch, rogueData) +// 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) var r0 []*big.Int var r1 []uint16 var r2 *types.RevealedDataMaps var r3 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, *big.Int, uint32, types.Rogue) ([]*big.Int, []uint16, *types.RevealedDataMaps, error)); ok { - return rf(client, blockNumber, epoch, rogueData) + 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(*ethclient.Client, *big.Int, uint32, types.Rogue) []*big.Int); ok { - r0 = rf(client, 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) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]*big.Int) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, *big.Int, uint32, types.Rogue) []uint16); ok { - r1 = rf(client, blockNumber, epoch, rogueData) + 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) } else { if ret.Get(1) != nil { r1 = ret.Get(1).([]uint16) } } - if rf, ok := ret.Get(2).(func(*ethclient.Client, *big.Int, uint32, types.Rogue) *types.RevealedDataMaps); ok { - r2 = rf(client, blockNumber, epoch, rogueData) + 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) } else { if ret.Get(2) != nil { r2 = ret.Get(2).(*types.RevealedDataMaps) } } - if rf, ok := ret.Get(3).(func(*ethclient.Client, *big.Int, uint32, types.Rogue) error); ok { - r3 = rf(client, blockNumber, epoch, rogueData) + 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) } else { r3 = ret.Error(3) } @@ -1577,25 +1577,25 @@ func (_m *UtilsCmdInterface) MakeBlock(client *ethclient.Client, blockNumber *bi return r0, r1, r2, r3 } -// ModifyCollectionStatus provides a mock function with given fields: client, config, modifyCollectionInput -func (_m *UtilsCmdInterface) ModifyCollectionStatus(client *ethclient.Client, config types.Configurations, modifyCollectionInput types.ModifyCollectionInput) (common.Hash, error) { - ret := _m.Called(client, config, modifyCollectionInput) +// 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) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations, types.ModifyCollectionInput) (common.Hash, error)); ok { - return rf(client, config, modifyCollectionInput) + 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(*ethclient.Client, types.Configurations, types.ModifyCollectionInput) common.Hash); ok { - r0 = rf(client, 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) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, types.Configurations, types.ModifyCollectionInput) error); ok { - r1 = rf(client, config, modifyCollectionInput) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, types.Configurations, types.ModifyCollectionInput) error); ok { + r1 = rf(ctx, client, config, modifyCollectionInput) } else { r1 = ret.Error(1) } @@ -1603,13 +1603,13 @@ func (_m *UtilsCmdInterface) ModifyCollectionStatus(client *ethclient.Client, co return r0, r1 } -// Propose provides a mock function with given fields: client, config, account, staker, epoch, latestHeader, rogueData -func (_m *UtilsCmdInterface) Propose(client *ethclient.Client, config types.Configurations, account types.Account, staker bindings.StructsStaker, epoch uint32, latestHeader *coretypes.Header, rogueData types.Rogue) error { - ret := _m.Called(client, config, account, staker, epoch, latestHeader, rogueData) +// 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) var r0 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations, types.Account, bindings.StructsStaker, uint32, *coretypes.Header, types.Rogue) error); ok { - r0 = rf(client, config, account, staker, epoch, latestHeader, rogueData) + 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) } else { r0 = ret.Error(0) } @@ -1648,25 +1648,25 @@ func (_m *UtilsCmdInterface) ResetUnstakeLock(client *ethclient.Client, config t return r0, r1 } -// Reveal provides a mock function with given fields: client, config, account, epoch, latestHeader, commitData, signature -func (_m *UtilsCmdInterface) Reveal(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, latestHeader *coretypes.Header, commitData types.CommitData, signature []byte) (common.Hash, error) { - ret := _m.Called(client, config, account, epoch, latestHeader, commitData, signature) +// 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) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations, types.Account, uint32, *coretypes.Header, types.CommitData, []byte) (common.Hash, error)); ok { - return rf(client, config, account, epoch, latestHeader, 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, error)); ok { + return rf(ctx, client, config, account, epoch, latestHeader, stateBuffer, commitData, signature) } - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations, types.Account, uint32, *coretypes.Header, types.CommitData, []byte) common.Hash); ok { - r0 = rf(client, config, account, epoch, latestHeader, 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) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, types.Configurations, types.Account, uint32, *coretypes.Header, types.CommitData, []byte) error); ok { - r1 = rf(client, config, account, epoch, latestHeader, commitData, signature) + 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) } else { r1 = ret.Error(1) } @@ -1688,25 +1688,25 @@ func (_m *UtilsCmdInterface) SetConfig(flagSet *pflag.FlagSet) error { return r0 } -// SetDelegation provides a mock function with given fields: client, config, delegationInput -func (_m *UtilsCmdInterface) SetDelegation(client *ethclient.Client, config types.Configurations, delegationInput types.SetDelegationInput) (common.Hash, error) { - ret := _m.Called(client, config, delegationInput) +// 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) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations, types.SetDelegationInput) (common.Hash, error)); ok { - return rf(client, config, delegationInput) + 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(*ethclient.Client, types.Configurations, types.SetDelegationInput) common.Hash); ok { - r0 = rf(client, 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) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, types.Configurations, types.SetDelegationInput) error); ok { - r1 = rf(client, config, delegationInput) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, types.Configurations, types.SetDelegationInput) error); ok { + r1 = rf(ctx, client, config, delegationInput) } else { r1 = ret.Error(1) } @@ -1740,13 +1740,13 @@ func (_m *UtilsCmdInterface) StakeCoins(txnArgs types.TransactionOptions) (commo return r0, r1 } -// StoreBountyId provides a mock function with given fields: client, account -func (_m *UtilsCmdInterface) StoreBountyId(client *ethclient.Client, account types.Account) error { - ret := _m.Called(client, account) +// 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) var r0 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Account) error); ok { - r0 = rf(client, account) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, types.Account) error); ok { + r0 = rf(ctx, client, account) } else { r0 = ret.Error(0) } @@ -1806,25 +1806,25 @@ func (_m *UtilsCmdInterface) UnlockWithdraw(client *ethclient.Client, txnOpts *b return r0, r1 } -// Unstake provides a mock function with given fields: config, client, input -func (_m *UtilsCmdInterface) Unstake(config types.Configurations, client *ethclient.Client, input types.UnstakeInput) (common.Hash, error) { - ret := _m.Called(config, client, input) +// 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) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(types.Configurations, *ethclient.Client, types.UnstakeInput) (common.Hash, error)); ok { - return rf(config, client, input) + 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(types.Configurations, *ethclient.Client, types.UnstakeInput) common.Hash); ok { - r0 = rf(config, client, 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) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(common.Hash) } } - if rf, ok := ret.Get(1).(func(types.Configurations, *ethclient.Client, types.UnstakeInput) error); ok { - r1 = rf(config, client, input) + if rf, ok := ret.Get(1).(func(context.Context, types.Configurations, *ethclient.Client, types.UnstakeInput) error); ok { + r1 = rf(ctx, config, client, input) } else { r1 = ret.Error(1) } @@ -1832,25 +1832,25 @@ func (_m *UtilsCmdInterface) Unstake(config types.Configurations, client *ethcli return r0, r1 } -// UpdateCollection provides a mock function with given fields: client, config, collectionInput, collectionId -func (_m *UtilsCmdInterface) UpdateCollection(client *ethclient.Client, config types.Configurations, collectionInput types.CreateCollectionInput, collectionId uint16) (common.Hash, error) { - ret := _m.Called(client, config, collectionInput, collectionId) +// 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) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations, types.CreateCollectionInput, uint16) (common.Hash, error)); ok { - return rf(client, config, collectionInput, collectionId) + 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(*ethclient.Client, types.Configurations, types.CreateCollectionInput, uint16) common.Hash); ok { - r0 = rf(client, 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) } 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, uint16) error); ok { - r1 = rf(client, config, collectionInput, collectionId) + 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) } else { r1 = ret.Error(1) } @@ -1858,13 +1858,13 @@ func (_m *UtilsCmdInterface) UpdateCollection(client *ethclient.Client, config t return r0, r1 } -// UpdateCommission provides a mock function with given fields: config, client, updateCommissionInput -func (_m *UtilsCmdInterface) UpdateCommission(config types.Configurations, client *ethclient.Client, updateCommissionInput types.UpdateCommissionInput) error { - ret := _m.Called(config, client, updateCommissionInput) +// 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) var r0 error - if rf, ok := ret.Get(0).(func(types.Configurations, *ethclient.Client, types.UpdateCommissionInput) error); ok { - r0 = rf(config, client, updateCommissionInput) + if rf, ok := ret.Get(0).(func(context.Context, types.Configurations, *ethclient.Client, types.UpdateCommissionInput) error); ok { + r0 = rf(ctx, config, client, updateCommissionInput) } else { r0 = ret.Error(0) } @@ -1872,25 +1872,25 @@ func (_m *UtilsCmdInterface) UpdateCommission(config types.Configurations, clien return r0 } -// UpdateJob provides a mock function with given fields: client, config, jobInput, jobId -func (_m *UtilsCmdInterface) UpdateJob(client *ethclient.Client, config types.Configurations, jobInput types.CreateJobInput, jobId uint16) (common.Hash, error) { - ret := _m.Called(client, config, jobInput, jobId) +// 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) var r0 common.Hash var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, types.Configurations, types.CreateJobInput, uint16) (common.Hash, error)); ok { - return rf(client, config, jobInput, jobId) + 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(*ethclient.Client, types.Configurations, types.CreateJobInput, uint16) common.Hash); ok { - r0 = rf(client, 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) } 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, uint16) error); ok { - r1 = rf(client, config, jobInput, jobId) + 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) } else { r1 = ret.Error(1) } @@ -1912,30 +1912,30 @@ func (_m *UtilsCmdInterface) Vote(ctx context.Context, config types.Configuratio return r0 } -// WaitForAppropriateState provides a mock function with given fields: client, action, states -func (_m *UtilsCmdInterface) WaitForAppropriateState(client *ethclient.Client, action string, states ...int) (uint32, error) { +// 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) { _va := make([]interface{}, len(states)) for _i := range states { _va[_i] = states[_i] } var _ca []interface{} - _ca = append(_ca, client, action) + _ca = append(_ca, ctx, client, action) _ca = append(_ca, _va...) ret := _m.Called(_ca...) var r0 uint32 var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, string, ...int) (uint32, error)); ok { - return rf(client, action, states...) + 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(*ethclient.Client, string, ...int) uint32); ok { - r0 = rf(client, action, states...) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, string, ...int) uint32); ok { + r0 = rf(ctx, client, action, states...) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(*ethclient.Client, string, ...int) error); ok { - r1 = rf(client, action, states...) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, string, ...int) error); ok { + r1 = rf(ctx, client, action, states...) } else { r1 = ret.Error(1) } @@ -1943,23 +1943,23 @@ func (_m *UtilsCmdInterface) WaitForAppropriateState(client *ethclient.Client, a return r0, r1 } -// WaitIfCommitState provides a mock function with given fields: client, action -func (_m *UtilsCmdInterface) WaitIfCommitState(client *ethclient.Client, action string) (uint32, error) { - ret := _m.Called(client, action) +// 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) var r0 uint32 var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, string) (uint32, error)); ok { - return rf(client, action) + 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(*ethclient.Client, string) uint32); ok { - r0 = rf(client, action) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, string) uint32); ok { + r0 = rf(ctx, client, action) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(*ethclient.Client, string) error); ok { - r1 = rf(client, action) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, string) error); ok { + r1 = rf(ctx, client, action) } else { r1 = ret.Error(1) } diff --git a/cmd/modifyCollectionStatus.go b/cmd/modifyCollectionStatus.go index 7f16efad6..65a928a50 100644 --- a/cmd/modifyCollectionStatus.go +++ b/cmd/modifyCollectionStatus.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "razor/accounts" "razor/core" "razor/core/types" @@ -72,7 +73,7 @@ func (*UtilsStruct) ExecuteModifyCollectionStatus(flagSet *pflag.FlagSet) { Account: account, } - txn, err := cmdUtils.ModifyCollectionStatus(client, config, modifyCollectionInput) + txn, err := cmdUtils.ModifyCollectionStatus(context.Background(), client, config, modifyCollectionInput) utils.CheckError("Error in changing collection active status: ", err) if txn != core.NilHash { err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) @@ -87,7 +88,7 @@ func (*UtilsStruct) CheckCurrentStatus(client *ethclient.Client, collectionId ui } //This function allows the admin to modify the active status of collection -func (*UtilsStruct) ModifyCollectionStatus(client *ethclient.Client, config types.Configurations, modifyCollectionInput types.ModifyCollectionInput) (common.Hash, error) { +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) if err != nil { log.Error("Error in fetching active status") @@ -98,7 +99,7 @@ func (*UtilsStruct) ModifyCollectionStatus(client *ethclient.Client, config type log.Errorf("Collection %d has the active status already set to %t", modifyCollectionInput.CollectionId, modifyCollectionInput.Status) return core.NilHash, nil } - _, err = cmdUtils.WaitForAppropriateState(client, "modify collection status", 4) + _, err = cmdUtils.WaitForAppropriateState(ctx, client, "modify collection status", 4) if err != nil { return core.NilHash, err } @@ -114,7 +115,7 @@ func (*UtilsStruct) ModifyCollectionStatus(client *ethclient.Client, config type Account: modifyCollectionInput.Account, } - txnOpts := razorUtils.GetTxnOpts(txnArgs) + txnOpts := razorUtils.GetTxnOpts(ctx, txnArgs) log.Infof("Changing active status of collection: %d from %t to %t", modifyCollectionInput.CollectionId, !modifyCollectionInput.Status, modifyCollectionInput.Status) log.Debugf("Executing SetCollectionStatus transaction with status = %v, collectionId = %d", modifyCollectionInput.Status, modifyCollectionInput.CollectionId) txn, err := assetManagerUtils.SetCollectionStatus(client, txnOpts, modifyCollectionInput.Status, modifyCollectionInput.CollectionId) diff --git a/cmd/modifyCollectionStatus_test.go b/cmd/modifyCollectionStatus_test.go index f6fb0d750..028bf1db1 100644 --- a/cmd/modifyCollectionStatus_test.go +++ b/cmd/modifyCollectionStatus_test.go @@ -1,6 +1,7 @@ package cmd import ( + "context" "errors" "math/big" "razor/accounts" @@ -161,14 +162,14 @@ func TestModifyAssetStatus(t *testing.T) { SetUpMockInterfaces() cmdUtilsMock.On("CheckCurrentStatus", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint16")).Return(tt.args.currentStatus, tt.args.currentStatusErr) - utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(TxnOpts) - cmdUtilsMock.On("WaitForAppropriateState", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string"), mock.Anything).Return(tt.args.epoch, tt.args.epochErr) + 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) 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(client, config, types.ModifyCollectionInput{ + got, err := utils.ModifyCollectionStatus(context.Background(), client, config, types.ModifyCollectionInput{ Status: tt.args.status, }) if got != tt.want { @@ -326,7 +327,7 @@ 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).Return(tt.args.ModifyCollectionStatusHash, tt.args.ModifyCollectionStatusErr) + 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) utils := &UtilsStruct{} diff --git a/cmd/propose.go b/cmd/propose.go index 43aa82655..1a760e239 100644 --- a/cmd/propose.go +++ b/cmd/propose.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "encoding/hex" "errors" "math" @@ -31,12 +32,12 @@ var globalProposedDataStruct types.ProposeFileData // Find iteration using salt as seed //This functions handles the propose state -func (*UtilsStruct) Propose(client *ethclient.Client, config types.Configurations, account types.Account, staker bindings.StructsStaker, epoch uint32, latestHeader *Types.Header, rogueData types.Rogue) error { - if state, err := razorUtils.GetBufferedState(client, latestHeader, config.BufferPercent); err != nil || state != 2 { +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 { + if state, err := razorUtils.GetBufferedState(latestHeader, stateBuffer, config.BufferPercent); err != nil || state != 2 { log.Error("Not propose state") return err } - numStakers, err := razorUtils.GetNumberOfStakers(client) + numStakers, err := razorUtils.GetNumberOfStakers(ctx, client) if err != nil { log.Error("Error in fetching number of stakers: ", err) return err @@ -53,7 +54,7 @@ func (*UtilsStruct) Propose(client *ethclient.Client, config types.Configuration 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(client, epoch) + smallestStake, smallestStakerId, smallestStakerErr := cmdUtils.GetSmallestStakeAndId(ctx, client, epoch) if smallestStakerErr != nil { log.Error("Error in calculating smallest staker: ", smallestStakerErr) return smallestStakerErr @@ -62,7 +63,7 @@ func (*UtilsStruct) Propose(client *ethclient.Client, config types.Configuration biggestStakerId = smallestStakerId log.Debugf("Propose: In rogue mode, Biggest Stake: %s, Biggest Staker Id: %d", biggestStake, biggestStakerId) } else { - biggestStake, biggestStakerId, biggestStakerErr = cmdUtils.GetBiggestStakeAndId(client, epoch) + biggestStake, biggestStakerId, biggestStakerErr = cmdUtils.GetBiggestStakeAndId(ctx, client, epoch) if biggestStakerErr != nil { log.Error("Error in calculating biggest staker: ", biggestStakerErr) return biggestStakerErr @@ -70,7 +71,7 @@ func (*UtilsStruct) Propose(client *ethclient.Client, config types.Configuration } log.Debugf("Getting Salt for current epoch %d...", epoch) - salt, err := cmdUtils.GetSalt(client, epoch) + salt, err := cmdUtils.GetSalt(ctx, client, epoch) if err != nil { return err } @@ -85,20 +86,20 @@ func (*UtilsStruct) Propose(client *ethclient.Client, config types.Configuration Epoch: epoch, } log.Debugf("Propose: Calling GetIteration with arguments proposer = %+v, buffer percent = %d", proposer, config.BufferPercent) - iteration := cmdUtils.GetIteration(client, proposer, config.BufferPercent) + iteration := cmdUtils.GetIteration(ctx, client, proposer, config.BufferPercent) log.Debug("Iteration: ", iteration) if iteration == -1 { return nil } - numOfProposedBlocks, err := razorUtils.GetNumberOfProposedBlocks(client, epoch) + numOfProposedBlocks, err := razorUtils.GetNumberOfProposedBlocks(ctx, client, epoch) if err != nil { log.Error(err) return err } log.Debug("Propose: Number of proposed blocks: ", numOfProposedBlocks) - maxAltBlocks, err := razorUtils.GetMaxAltBlocks(client) + maxAltBlocks, err := razorUtils.GetMaxAltBlocks(ctx, client) if err != nil { log.Error(err) return err @@ -107,7 +108,7 @@ func (*UtilsStruct) Propose(client *ethclient.Client, config types.Configuration 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(client, epoch) + sortedProposedBlocks, err := razorUtils.GetSortedProposedBlockIds(ctx, client, epoch) if err != nil { log.Error("Error in fetching sorted proposed block ids") return err @@ -115,7 +116,7 @@ func (*UtilsStruct) Propose(client *ethclient.Client, config types.Configuration log.Debug("Propose: Sorted proposed blocks: ", sortedProposedBlocks) lastBlockIndex := sortedProposedBlocks[numOfProposedBlocks-1] log.Debug("Propose: Last block index: ", lastBlockIndex) - lastProposedBlockStruct, err := razorUtils.GetProposedBlock(client, epoch, lastBlockIndex) + lastProposedBlockStruct, err := razorUtils.GetProposedBlock(ctx, client, epoch, lastBlockIndex) if err != nil { log.Error(err) return err @@ -130,7 +131,7 @@ func (*UtilsStruct) Propose(client *ethclient.Client, config types.Configuration 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(client, latestHeader.Number, epoch, rogueData) + medians, ids, revealedDataMaps, err := cmdUtils.MakeBlock(ctx, client, latestHeader.Number, epoch, rogueData) if err != nil { log.Error(err) return err @@ -140,7 +141,7 @@ func (*UtilsStruct) Propose(client *ethclient.Client, config types.Configuration log.Debugf("Propose: Iteration: %d Biggest Staker Id: %d", iteration, biggestStakerId) log.Info("Proposing block...") - txnOpts := razorUtils.GetTxnOpts(types.TransactionOptions{ + txnOpts := razorUtils.GetTxnOpts(ctx, types.TransactionOptions{ Client: client, ChainId: core.ChainId, Config: config, @@ -195,8 +196,8 @@ func (*UtilsStruct) Propose(client *ethclient.Client, config types.Configuration } //This function returns the biggest stake and Id of it -func (*UtilsStruct) GetBiggestStakeAndId(client *ethclient.Client, epoch uint32) (*big.Int, uint32, error) { - numberOfStakers, err := razorUtils.GetNumberOfStakers(client) +func (*UtilsStruct) GetBiggestStakeAndId(ctx context.Context, client *ethclient.Client, epoch uint32) (*big.Int, uint32, error) { + numberOfStakers, err := razorUtils.GetNumberOfStakers(ctx, client) if err != nil { return nil, 0, err } @@ -230,15 +231,25 @@ func (*UtilsStruct) GetBiggestStakeAndId(client *ethclient.Client, epoch uint32) return biggestStake, biggestStakerId, nil } -func (*UtilsStruct) GetIteration(client *ethclient.Client, proposer types.ElectedProposer, bufferPercent int32) int { - stake, err := razorUtils.GetStakeSnapshot(client, proposer.StakerId, proposer.Epoch) +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) 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)))) - stateRemainingTime, err := razorUtils.GetRemainingTimeOfCurrentState(client, bufferPercent) + stateBuffer, err := razorUtils.GetStateBuffer(ctx, client) + if err != nil { + log.Error("Error in getting state buffer: ", err) + return -1 + } + latestHeader, err := clientUtils.GetLatestBlockWithRetry(ctx, client) + if err != nil { + log.Error("Error in getting latest block: ", err) + return -1 + } + stateRemainingTime, err := razorUtils.GetRemainingTimeOfCurrentState(latestHeader, stateBuffer, bufferPercent) if err != nil { return -1 } @@ -340,9 +351,9 @@ func pseudoRandomNumberGenerator(seed []byte, max uint32, blockHashes []byte) *b } //This function returns the sorted revealed values -func (*UtilsStruct) GetSortedRevealedValues(client *ethclient.Client, blockNumber *big.Int, epoch uint32) (*types.RevealedDataMaps, error) { +func (*UtilsStruct) GetSortedRevealedValues(ctx context.Context, client *ethclient.Client, 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(client, blockNumber, epoch) + assignedAsset, err := cmdUtils.IndexRevealEventsOfCurrentEpoch(ctx, client, blockNumber, epoch) if err != nil { return nil, err } @@ -387,9 +398,9 @@ func (*UtilsStruct) GetSortedRevealedValues(client *ethclient.Client, blockNumbe } //This function returns the medians, idsRevealedInThisEpoch and revealedDataMaps -func (*UtilsStruct) MakeBlock(client *ethclient.Client, blockNumber *big.Int, epoch uint32, rogueData types.Rogue) ([]*big.Int, []uint16, *types.RevealedDataMaps, error) { +func (*UtilsStruct) MakeBlock(ctx context.Context, client *ethclient.Client, 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(client, blockNumber, epoch) + revealedDataMaps, err := cmdUtils.GetSortedRevealedValues(ctx, client, blockNumber, epoch) if err != nil { return nil, nil, nil, err } @@ -447,8 +458,8 @@ func (*UtilsStruct) MakeBlock(client *ethclient.Client, blockNumber *big.Int, ep return medians, idsRevealedInThisEpoch, revealedDataMaps, nil } -func (*UtilsStruct) GetSmallestStakeAndId(client *ethclient.Client, epoch uint32) (*big.Int, uint32, error) { - numberOfStakers, err := razorUtils.GetNumberOfStakers(client) +func (*UtilsStruct) GetSmallestStakeAndId(ctx context.Context, client *ethclient.Client, epoch uint32) (*big.Int, uint32, error) { + numberOfStakers, err := razorUtils.GetNumberOfStakers(ctx, client) if err != nil { return nil, 0, err } @@ -459,7 +470,7 @@ func (*UtilsStruct) GetSmallestStakeAndId(client *ethclient.Client, epoch uint32 smallestStake := big.NewInt(1).Mul(big.NewInt(1e18), big.NewInt(1e18)) for i := 1; i <= int(numberOfStakers); i++ { - stake, err := razorUtils.GetStakeSnapshot(client, uint32(i), epoch) + stake, err := razorUtils.GetStakeSnapshot(ctx, client, uint32(i), epoch) if err != nil { return nil, 0, err } diff --git a/cmd/propose_test.go b/cmd/propose_test.go index 6ab69727a..2d8b3f772 100644 --- a/cmd/propose_test.go +++ b/cmd/propose_test.go @@ -1,6 +1,7 @@ package cmd import ( + "context" "errors" "fmt" "github.com/ethereum/go-ethereum/accounts/abi" @@ -8,7 +9,6 @@ import ( "math/big" "razor/core/types" "razor/pkg/bindings" - utilsPkgMocks "razor/utils/mocks" "reflect" "strings" "testing" @@ -23,11 +23,12 @@ import ( func TestPropose(t *testing.T) { var ( - client *ethclient.Client - account types.Account - config types.Configurations - staker bindings.StructsStaker - epoch uint32 + client *ethclient.Client + account types.Account + config types.Configurations + staker bindings.StructsStaker + epoch uint32 + stateBuffer uint64 ) 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} @@ -506,30 +507,30 @@ 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.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.numStakers, tt.args.numStakerErr) - cmdUtilsMock.On("GetBiggestStakeAndId", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).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("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("GetRandaoHash", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.randaoHash, tt.args.randaoHashErr) - cmdUtilsMock.On("GetIteration", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.iteration) + 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.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.salt, tt.args.saltErr) - cmdUtilsMock.On("GetIteration", mock.Anything, mock.Anything).Return(tt.args.iteration) - utilsMock.On("GetNumberOfProposedBlocks", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.numOfProposedBlocks, tt.args.numOfProposedBlocksErr) - utilsMock.On("GetSortedProposedBlockIds", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.sortedProposedBlockIds, tt.args.sortedProposedBlocksIdsErr) - utilsMock.On("GetMaxAltBlocks", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.maxAltBlocks, tt.args.maxAltBlocksErr) - utilsMock.On("GetProposedBlock", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint32")).Return(tt.args.lastProposedBlockStruct, tt.args.lastProposedBlockStructErr) - cmdUtilsMock.On("MakeBlock", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything).Return(tt.args.medians, tt.args.ids, tt.args.revealDataMaps, tt.args.mediansErr) + 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("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("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) - utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(TxnOpts) + utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(TxnOpts) blockManagerMock.On("Propose", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.proposeTxn, tt.args.proposeErr) transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.waitForBlockCompletionErr) utils := &UtilsStruct{} t.Run(tt.name, func(t *testing.T) { - err := utils.Propose(client, config, account, staker, epoch, latestHeader, tt.args.rogueData) + err := utils.Propose(context.Background(), client, 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) @@ -613,12 +614,12 @@ func TestGetBiggestStakeAndId(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetNumberOfStakers", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.numOfStakers, tt.args.numOfStakersErr) + 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) utils := &UtilsStruct{} - gotStake, gotId, err := utils.GetBiggestStakeAndId(client, epoch) + gotStake, gotId, err := utils.GetBiggestStakeAndId(context.Background(), client, epoch) if err == nil || tt.wantErr == nil { if err != tt.wantErr { t.Errorf("Error for GetBiggestStakeAndId function, got = %v, want %v", err, tt.wantErr) @@ -662,6 +663,10 @@ func TestGetIteration(t *testing.T) { type args struct { stakeSnapshot *big.Int stakeSnapshotErr error + stateBuffer uint64 + stateBufferErr error + latestHeader *Types.Header + latestHeaderErr error remainingTime int64 remainingTimeErr error } @@ -674,6 +679,8 @@ func TestGetIteration(t *testing.T) { name: "Test 1: When getIteration returns a valid iteration", args: args{ stakeSnapshot: big.NewInt(1000), + stateBuffer: 5, + latestHeader: &Types.Header{}, remainingTime: 10, }, want: 70183, @@ -682,6 +689,7 @@ func TestGetIteration(t *testing.T) { name: "Test 2: When there is an error in getting stakeSnapshotValue", args: args{ stakeSnapshot: big.NewInt(0), + latestHeader: &Types.Header{}, stakeSnapshotErr: errors.New("error in getting stakeSnapshotValue"), }, want: -1, @@ -690,6 +698,8 @@ func TestGetIteration(t *testing.T) { name: "Test 3: When getIteration returns an invalid iteration", args: args{ stakeSnapshot: big.NewInt(1), + stateBuffer: 5, + latestHeader: &Types.Header{}, remainingTime: 2, }, want: -1, @@ -698,23 +708,41 @@ func TestGetIteration(t *testing.T) { name: "Test 4: When there is an error in getting remaining time for the state", args: args{ stakeSnapshot: stakeSnapshotValue("2592145500000000000000000"), + stateBuffer: 5, + latestHeader: &Types.Header{}, remainingTimeErr: errors.New("remaining time error"), }, want: -1, }, + { + name: "Test 5: When there is an error in getting state buffer", + args: args{ + stakeSnapshot: big.NewInt(1000), + stateBufferErr: errors.New("state buffer error"), + }, + want: -1, + }, + { + name: "Test 6: When there is an error in getting latest header", + args: args{ + stakeSnapshot: big.NewInt(1000), + stateBuffer: 5, + latestHeaderErr: errors.New("latest header error"), + }, + want: -1, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock = new(utilsPkgMocks.Utils) - razorUtils = utilsMock - + SetUpMockInterfaces() cmdUtils = &UtilsStruct{} - utilsMock.On("GetStakeSnapshot", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint32")).Return(big.NewInt(1).Mul(tt.args.stakeSnapshot, big.NewInt(1e18)), tt.args.stakeSnapshotErr) - utilsMock.On("GetRemainingTimeOfCurrentState", mock.Anything, mock.Anything).Return(tt.args.remainingTime, tt.args.remainingTimeErr) - - if got := cmdUtils.GetIteration(client, proposer, bufferPercent); got != tt.want { + 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) + 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 { t.Errorf("getIteration() = %v, want %v", got, tt.want) } }) @@ -1014,11 +1042,11 @@ func TestMakeBlock(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - cmdUtilsMock.On("GetSortedRevealedValues", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.revealedDataMaps, tt.args.revealedDataMapsErr) + cmdUtilsMock.On("GetSortedRevealedValues", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.revealedDataMaps, tt.args.revealedDataMapsErr) utilsMock.On("GetActiveCollectionIds", mock.Anything).Return(tt.args.activeCollections, tt.args.activeCollectionsErr) utilsMock.On("GetRogueRandomValue", mock.Anything).Return(randomValue) ut := &UtilsStruct{} - got, got1, got2, err := ut.MakeBlock(client, blockNumber, epoch, tt.args.rogueData) + got, got1, got2, err := ut.MakeBlock(context.Background(), client, blockNumber, epoch, tt.args.rogueData) if (err != nil) != tt.wantErr { t.Errorf("MakeBlock() error = %v, wantErr %v", err, tt.wantErr) return @@ -1206,9 +1234,9 @@ func TestGetSortedRevealedValues(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - cmdUtilsMock.On("IndexRevealEventsOfCurrentEpoch", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.assignedAssets, tt.args.assignedAssetsErr) + cmdUtilsMock.On("IndexRevealEventsOfCurrentEpoch", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.assignedAssets, tt.args.assignedAssetsErr) ut := &UtilsStruct{} - got, err := ut.GetSortedRevealedValues(client, blockNumber, epoch) + got, err := ut.GetSortedRevealedValues(context.Background(), client, blockNumber, epoch) if (err != nil) != tt.wantErr { t.Errorf("GetSortedRevealedValues() error = %v, wantErr %v", err, tt.wantErr) return @@ -1281,12 +1309,12 @@ func TestGetSmallestStakeAndId(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetNumberOfStakers", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.numOfStakers, tt.args.numOfStakersErr) - utilsMock.On("GetStakeSnapshot", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint32")).Return(tt.args.stake, tt.args.stakeErr) + utilsMock.On("GetNumberOfStakers", mock.Anything, mock.Anything, 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(client, epoch) + gotStake, gotId, err := utils.GetSmallestStakeAndId(context.Background(), client, epoch) if gotStake.Cmp(tt.wantStake) != 0 { t.Errorf("Smallest Stake from GetSmallestStakeAndId function, got = %v, want %v", gotStake, tt.wantStake) } @@ -1405,10 +1433,12 @@ func BenchmarkGetIteration(b *testing.B) { cmdUtils = &UtilsStruct{} - utilsMock.On("GetStakeSnapshot", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint32")).Return(big.NewInt(1).Mul(v.stakeSnapshot, big.NewInt(1e18)), nil) - utilsMock.On("GetRemainingTimeOfCurrentState", mock.Anything, mock.Anything).Return(int64(100), nil) + 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) + clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything, mock.Anything).Return(&Types.Header{}, nil) - cmdUtils.GetIteration(client, proposer, bufferPercent) + cmdUtils.GetIteration(context.Background(), client, proposer, bufferPercent) } }) } @@ -1432,11 +1462,11 @@ func BenchmarkGetBiggestStakeAndId(b *testing.B) { for i := 0; i < b.N; i++ { SetUpMockInterfaces() - utilsMock.On("GetNumberOfStakers", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(v.numOfStakers, nil) + utilsMock.On("GetNumberOfStakers", mock.Anything, mock.Anything, 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(client, epoch) + _, _, err := ut.GetBiggestStakeAndId(context.Background(), client, epoch) if err != nil { log.Fatal(err) } @@ -1467,9 +1497,9 @@ func BenchmarkGetSortedRevealedValues(b *testing.B) { asset := GetDummyRevealedValues(v.numOfRevealedValues) - cmdUtilsMock.On("IndexRevealEventsOfCurrentEpoch", mock.Anything, mock.Anything, mock.Anything).Return(GetDummyAssignedAssets(asset, v.numOfAssignedAssets), nil) + cmdUtilsMock.On("IndexRevealEventsOfCurrentEpoch", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(GetDummyAssignedAssets(asset, v.numOfAssignedAssets), nil) ut := &UtilsStruct{} - _, err := ut.GetSortedRevealedValues(client, blockNumber, epoch) + _, err := ut.GetSortedRevealedValues(context.Background(), client, blockNumber, epoch) if err != nil { log.Fatal(err) } @@ -1501,14 +1531,14 @@ func BenchmarkMakeBlock(b *testing.B) { votes := GetDummyVotes(v.numOfVotes) - cmdUtilsMock.On("GetSortedRevealedValues", mock.Anything, mock.Anything, mock.Anything).Return(&types.RevealedDataMaps{ + cmdUtilsMock.On("GetSortedRevealedValues", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(&types.RevealedDataMaps{ SortedRevealedValues: map[uint16][]*big.Int{0: votes}, VoteWeights: map[string]*big.Int{(big.NewInt(1).Mul(big.NewInt(697718000), big.NewInt(1e18))).String(): big.NewInt(100)}, InfluenceSum: map[uint16]*big.Int{0: big.NewInt(100)}, }, nil) utilsMock.On("GetActiveCollectionIds", mock.Anything).Return([]uint16{1}, nil) ut := &UtilsStruct{} - _, _, _, err := ut.MakeBlock(client, blockNumber, epoch, types.Rogue{IsRogue: false}) + _, _, _, err := ut.MakeBlock(context.Background(), client, blockNumber, epoch, types.Rogue{IsRogue: false}) if err != nil { log.Fatal(err) } diff --git a/cmd/resetUnstakeLock.go b/cmd/resetUnstakeLock.go index 3f4d5d474..13efd91de 100644 --- a/cmd/resetUnstakeLock.go +++ b/cmd/resetUnstakeLock.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "razor/accounts" "razor/core" "razor/core/types" @@ -59,7 +60,7 @@ func (*UtilsStruct) ExecuteExtendLock(flagSet *pflag.FlagSet) { err = razorUtils.CheckPassword(account) utils.CheckError("Error in fetching private key from given password: ", err) - stakerId, err := razorUtils.AssignStakerId(flagSet, client, address) + stakerId, err := razorUtils.AssignStakerId(context.Background(), flagSet, client, address) utils.CheckError("Error in getting stakerId: ", err) extendLockInput := types.ExtendLockInput{ @@ -75,7 +76,7 @@ func (*UtilsStruct) ExecuteExtendLock(flagSet *pflag.FlagSet) { //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(types.TransactionOptions{ + txnOpts := razorUtils.GetTxnOpts(context.Background(), types.TransactionOptions{ Client: client, ChainId: core.ChainId, Config: config, diff --git a/cmd/resetUnstakeLock_test.go b/cmd/resetUnstakeLock_test.go index 1d598abdc..cfd210062 100644 --- a/cmd/resetUnstakeLock_test.go +++ b/cmd/resetUnstakeLock_test.go @@ -56,7 +56,7 @@ func TestExtendLock(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(TxnOpts) + utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(TxnOpts) stakeManagerMock.On("ResetUnstakeLock", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.AnythingOfType("uint32")).Return(tt.args.resetLockTxn, tt.args.resetLockErr) transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) @@ -176,7 +176,7 @@ func TestExecuteExtendLock(t *testing.T) { 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", flagSet, mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) + utilsMock.On("AssignStakerId", mock.Anything, flagSet, 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) diff --git a/cmd/reveal.go b/cmd/reveal.go index 0667c6666..637f77a33 100644 --- a/cmd/reveal.go +++ b/cmd/reveal.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "errors" "math/big" "razor/core" @@ -17,8 +18,8 @@ import ( ) //This function checks for epoch last committed -func (*UtilsStruct) CheckForLastCommitted(client *ethclient.Client, staker bindings.StructsStaker, epoch uint32) error { - epochLastCommitted, err := razorUtils.GetEpochLastCommitted(client, staker.Id) +func (*UtilsStruct) CheckForLastCommitted(ctx context.Context, client *ethclient.Client, staker bindings.StructsStaker, epoch uint32) error { + epochLastCommitted, err := razorUtils.GetEpochLastCommitted(ctx, client, staker.Id) if err != nil { return err } @@ -30,8 +31,8 @@ func (*UtilsStruct) CheckForLastCommitted(client *ethclient.Client, staker bindi } //This function checks if the state is reveal or not and then reveals the votes -func (*UtilsStruct) Reveal(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, latestHeader *Types.Header, commitData types.CommitData, signature []byte) (common.Hash, error) { - if state, err := razorUtils.GetBufferedState(client, latestHeader, config.BufferPercent); err != nil || state != 1 { +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) { + if state, err := razorUtils.GetBufferedState(latestHeader, stateBuffer, config.BufferPercent); err != nil || state != 1 { log.Error("Not reveal state") return core.NilHash, err } @@ -55,7 +56,7 @@ func (*UtilsStruct) Reveal(client *ethclient.Client, config types.Configurations log.Info("Revealing votes...") - txnOpts := razorUtils.GetTxnOpts(types.TransactionOptions{ + txnOpts := razorUtils.GetTxnOpts(ctx, types.TransactionOptions{ Client: client, ChainId: core.ChainId, Config: config, @@ -112,7 +113,7 @@ func (*UtilsStruct) GenerateTreeRevealData(merkleTree [][][]byte, commitData typ } //This function indexes the reveal events of current epoch -func (*UtilsStruct) IndexRevealEventsOfCurrentEpoch(client *ethclient.Client, blockNumber *big.Int, epoch uint32) ([]types.RevealedStruct, error) { +func (*UtilsStruct) IndexRevealEventsOfCurrentEpoch(ctx context.Context, client *ethclient.Client, blockNumber *big.Int, epoch uint32) ([]types.RevealedStruct, error) { log.Debug("Fetching reveal events of current epoch...") fromBlock, err := razorUtils.EstimateBlockNumberAtEpochBeginning(client, blockNumber) if err != nil { @@ -127,7 +128,7 @@ func (*UtilsStruct) IndexRevealEventsOfCurrentEpoch(client *ethclient.Client, bl }, } log.Debugf("IndexRevealEventsOfCurrentEpoch: Query to send in filter logs: %+v", query) - logs, err := clientUtils.FilterLogsWithRetry(client, query) + logs, err := clientUtils.FilterLogsWithRetry(ctx, client, query) if err != nil { return nil, err } diff --git a/cmd/reveal_test.go b/cmd/reveal_test.go index c276ade07..0a1905f90 100644 --- a/cmd/reveal_test.go +++ b/cmd/reveal_test.go @@ -1,6 +1,7 @@ package cmd import ( + "context" "errors" "fmt" "math/big" @@ -65,11 +66,11 @@ func TestCheckForLastCommitted(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetEpochLastCommitted", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.epochLastCommitted, tt.args.epochLastCommittedErr) + utilsMock.On("GetEpochLastCommitted", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.epochLastCommitted, tt.args.epochLastCommittedErr) utils := &UtilsStruct{} - err := utils.CheckForLastCommitted(client, staker, tt.args.epoch) + err := utils.CheckForLastCommitted(context.Background(), client, 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) @@ -93,6 +94,7 @@ func TestReveal(t *testing.T) { config types.Configurations epoch uint32 latestHeader *Types.Header + stateBuffer uint64 ) type args struct { @@ -163,13 +165,13 @@ func TestReveal(t *testing.T) { utilsMock.On("GetBufferedState", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.state, tt.args.stateErr) merkleUtilsMock.On("CreateMerkle", mock.Anything).Return(tt.args.merkleTree, tt.args.merkleTreeErr) cmdUtilsMock.On("GenerateTreeRevealData", mock.Anything, mock.Anything).Return(tt.args.treeRevealData) - utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(TxnOpts) + utilsMock.On("GetTxnOpts", mock.Anything, mock.AnythingOfType("types.TransactionOptions")).Return(TxnOpts) voteManagerMock.On("Reveal", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.AnythingOfType("uint32"), mock.Anything, mock.Anything).Return(tt.args.revealTxn, tt.args.revealErr) transactionMock.On("Hash", mock.AnythingOfType("*types.Transaction")).Return(tt.args.hash) utils := &UtilsStruct{} - got, err := utils.Reveal(client, config, account, epoch, latestHeader, commitData, signature) + got, err := utils.Reveal(context.Background(), client, 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) } @@ -320,11 +322,11 @@ func TestIndexRevealEventsOfCurrentEpoch(t *testing.T) { SetUpMockInterfaces() utilsMock.On("EstimateBlockNumberAtEpochBeginning", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.fromBlock, tt.args.fromBlockErr) - clientUtilsMock.On("FilterLogsWithRetry", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("ethereum.FilterQuery")).Return(tt.args.logs, tt.args.logsErr) + clientUtilsMock.On("FilterLogsWithRetry", mock.Anything, 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(client, blockNumber, epoch) + got, err := ut.IndexRevealEventsOfCurrentEpoch(context.Background(), client, blockNumber, epoch) if (err != nil) != tt.wantErr { t.Errorf("IndexRevealEventsOfCurrentEpoch() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/cmd/setDelegation.go b/cmd/setDelegation.go index f28ca97d3..4de0d08f4 100644 --- a/cmd/setDelegation.go +++ b/cmd/setDelegation.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "razor/accounts" "razor/core" "razor/core/types" @@ -65,7 +66,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(client, address) + stakerId, err := razorUtils.GetStakerId(context.Background(), client, address) utils.CheckError("StakerId error: ", err) commission, err := flagSetUtils.GetUint8Commission(flagSet) @@ -79,7 +80,7 @@ func (*UtilsStruct) ExecuteSetDelegation(flagSet *pflag.FlagSet) { Account: account, } - txn, err := cmdUtils.SetDelegation(client, config, delegationInput) + txn, err := cmdUtils.SetDelegation(context.Background(), client, config, delegationInput) utils.CheckError("SetDelegation error: ", err) if txn != core.NilHash { err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) @@ -88,8 +89,8 @@ func (*UtilsStruct) ExecuteSetDelegation(flagSet *pflag.FlagSet) { } //This function allows the staker to start accepting/rejecting delegation requests -func (*UtilsStruct) SetDelegation(client *ethclient.Client, config types.Configurations, delegationInput types.SetDelegationInput) (common.Hash, error) { - stakerInfo, err := razorUtils.GetStaker(client, delegationInput.StakerId) +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) if err != nil { return core.NilHash, err } @@ -100,7 +101,7 @@ func (*UtilsStruct) SetDelegation(client *ethclient.Client, config types.Configu Commission: delegationInput.Commission, Account: delegationInput.Account, } - err = cmdUtils.UpdateCommission(config, client, updateCommissionInput) + err = cmdUtils.UpdateCommission(ctx, config, client, updateCommissionInput) if err != nil { return core.NilHash, err } @@ -122,7 +123,7 @@ func (*UtilsStruct) SetDelegation(client *ethclient.Client, config types.Configu return core.NilHash, nil } log.Infof("Setting delegation acceptance of Staker %d to %t", delegationInput.StakerId, delegationInput.Status) - setDelegationAcceptanceTxnOpts := razorUtils.GetTxnOpts(txnOpts) + setDelegationAcceptanceTxnOpts := razorUtils.GetTxnOpts(ctx, txnOpts) 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 e9cc4b2b1..9cb0863c7 100644 --- a/cmd/setDelegation_test.go +++ b/cmd/setDelegation_test.go @@ -1,14 +1,13 @@ package cmd import ( + "context" "errors" "math/big" "razor/accounts" - "razor/cmd/mocks" "razor/core" "razor/core/types" "razor/pkg/bindings" - utilsPkgMocks "razor/utils/mocks" "testing" "github.com/ethereum/go-ethereum/common" @@ -134,24 +133,16 @@ func TestSetDelegation(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(utilsPkgMocks.Utils) - stakeManagerUtilsMock := new(mocks.StakeManagerInterface) - transactionUtilsMock := new(mocks.TransactionInterface) - cmdUtilsMock := new(mocks.UtilsCmdInterface) + SetUpMockInterfaces() - razorUtils = utilsMock - stakeManagerUtils = stakeManagerUtilsMock - transactionUtils = transactionUtilsMock - cmdUtils = cmdUtilsMock - - utilsMock.On("GetStaker", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.staker, tt.args.stakerErr) - cmdUtilsMock.On("UpdateCommission", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.UpdateCommissionErr) - utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(TxnOpts) - stakeManagerUtilsMock.On("SetDelegationAcceptance", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.AnythingOfType("bool")).Return(tt.args.setDelegationAcceptanceTxn, tt.args.setDelegationAcceptanceErr) - transactionUtilsMock.On("Hash", mock.Anything).Return(tt.args.hash) + 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("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(client, config, types.SetDelegationInput{ + got, err := utils.SetDelegation(context.Background(), client, config, types.SetDelegationInput{ Status: tt.args.status, Commission: tt.args.commission, }) @@ -388,32 +379,20 @@ func TestExecuteSetDelegation(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(utilsPkgMocks.Utils) - cmdUtilsMock := new(mocks.UtilsCmdInterface) - flagSetUtilsMock := new(mocks.FlagSetInterface) - stakeManagerUtilsMock := new(mocks.StakeManagerInterface) - stringMock := new(mocks.StringInterface) - fileUtilsMock := new(utilsPkgMocks.FileUtils) - - razorUtils = utilsMock - cmdUtils = cmdUtilsMock - flagSetUtils = flagSetUtilsMock - stakeManagerUtils = stakeManagerUtilsMock - stringUtils = stringMock - fileUtils = fileUtilsMock + SetUpMockInterfaces() 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) - flagSetUtilsMock.On("GetStringAddress", flagSet).Return(tt.args.address, tt.args.addressErr) - flagSetUtilsMock.On("GetStringStatus", flagSet).Return(tt.args.status, tt.args.statusErr) - flagSetUtilsMock.On("GetUint8Commission", flagSet).Return(tt.args.commission, tt.args.commissionErr) + flagSetMock.On("GetStringAddress", flagSet).Return(tt.args.address, tt.args.addressErr) + flagSetMock.On("GetStringStatus", flagSet).Return(tt.args.status, tt.args.statusErr) + 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.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.stakerId, tt.args.stakerIdErr) - cmdUtilsMock.On("SetDelegation", mock.AnythingOfType("*ethclient.Client"), config, mock.Anything).Return(tt.args.setDelegationHash, tt.args.setDelegationErr) + 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) utils := &UtilsStruct{} diff --git a/cmd/stakerInfo.go b/cmd/stakerInfo.go index 0778117ef..5dc5a6631 100644 --- a/cmd/stakerInfo.go +++ b/cmd/stakerInfo.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "github.com/ethereum/go-ethereum/ethclient" "github.com/olekukonko/tablewriter" "github.com/spf13/cobra" @@ -41,13 +42,13 @@ func (*UtilsStruct) ExecuteStakerinfo(flagSet *pflag.FlagSet) { log.Debug("ExecuteStakerinfo: StakerId: ", stakerId) log.Debug("ExecuteStakerinfo: Calling GetStakerInfo() with argument stakerId = ", stakerId) - err = cmdUtils.GetStakerInfo(client, stakerId) + err = cmdUtils.GetStakerInfo(context.Background(), client, stakerId) utils.CheckError("Error in getting staker info: ", err) } //This function provides the staker details like age, stake, maturity etc. -func (*UtilsStruct) GetStakerInfo(client *ethclient.Client, stakerId uint32) error { +func (*UtilsStruct) GetStakerInfo(ctx context.Context, client *ethclient.Client, stakerId uint32) error { callOpts := razorUtils.GetOptions() stakerInfo, err := stakeManagerUtils.StakerInfo(client, &callOpts, stakerId) if err != nil { @@ -57,11 +58,11 @@ func (*UtilsStruct) GetStakerInfo(client *ethclient.Client, stakerId uint32) err if err != nil { return err } - epoch, err := razorUtils.GetEpoch(client) + epoch, err := razorUtils.GetEpoch(ctx, client) if err != nil { return err } - influence, err := razorUtils.GetInfluenceSnapshot(client, stakerId, epoch) + influence, err := razorUtils.GetInfluenceSnapshot(ctx, client, stakerId, epoch) if err != nil { return err } diff --git a/cmd/stakerInfo_test.go b/cmd/stakerInfo_test.go index c73676722..db5a69e19 100644 --- a/cmd/stakerInfo_test.go +++ b/cmd/stakerInfo_test.go @@ -213,19 +213,15 @@ func TestUtilsStruct_GetStakerInfo(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(utilsPkgMocks.Utils) - stakeManagerMock := new(mocks.StakeManagerInterface) - - razorUtils = utilsMock - stakeManagerUtils = stakeManagerMock + 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.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint32")).Return(tt.args.influence, tt.args.influenceErr) - utilsMock.On("GetEpoch", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.epoch, tt.args.epochErr) + 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) utils := &UtilsStruct{} - err := utils.GetStakerInfo(tt.args.client, tt.args.stakerId) + err := utils.GetStakerInfo(context.Background(), tt.args.client, 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) @@ -321,7 +317,7 @@ func TestUtilsStruct_ExecuteStakerinfo(t *testing.T) { 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.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.stakerInfoErr) + cmdUtilsMock.On("GetStakerInfo", mock.Anything, 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 eebc2712f..0c22a71d1 100644 --- a/cmd/struct-utils.go +++ b/cmd/struct-utils.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "crypto/ecdsa" "errors" "math/big" @@ -693,8 +694,8 @@ func (c CryptoUtils) HexToECDSA(hexKey string) (*ecdsa.PrivateKey, error) { } //This function is used to give the sorted Ids -func (*UtilsStruct) GiveSorted(client *ethclient.Client, blockManager *bindings.BlockManager, txnArgs types.TransactionOptions, epoch uint32, assetId uint16, sortedStakers []*big.Int) error { - return GiveSorted(client, blockManager, txnArgs, epoch, assetId, sortedStakers) +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) } //This function is used to write config as diff --git a/cmd/transfer.go b/cmd/transfer.go index bbb7517b1..3a66b8f45 100644 --- a/cmd/transfer.go +++ b/cmd/transfer.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "razor/accounts" "razor/core" "razor/core/types" @@ -88,7 +89,7 @@ func (*UtilsStruct) Transfer(client *ethclient.Client, config types.Configuratio log.Debug("Checking for sufficient balance...") razorUtils.CheckAmountAndBalance(transferInput.ValueInWei, transferInput.Balance) - txnOpts := razorUtils.GetTxnOpts(types.TransactionOptions{ + txnOpts := razorUtils.GetTxnOpts(context.Background(), types.TransactionOptions{ Client: client, ChainId: core.ChainId, Config: config, diff --git a/cmd/transfer_test.go b/cmd/transfer_test.go index d0e04e651..9b44ada66 100644 --- a/cmd/transfer_test.go +++ b/cmd/transfer_test.go @@ -63,7 +63,7 @@ func TestTransfer(t *testing.T) { SetUpMockInterfaces() utilsMock.On("CheckAmountAndBalance", mock.AnythingOfType("*big.Int"), mock.AnythingOfType("*big.Int")).Return(tt.args.amount) - utilsMock.On("GetTxnOpts", mock.Anything).Return(TxnOpts) + utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(TxnOpts) utilsMock.On("GetAmountInDecimal", mock.AnythingOfType("*big.Int")).Return(tt.args.decimalAmount) tokenManagerMock.On("Transfer", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.AnythingOfType("common.Address"), mock.AnythingOfType("*big.Int")).Return(tt.args.transferTxn, tt.args.transferErr) transactionMock.On("Hash", mock.Anything).Return(tt.args.transferHash) diff --git a/cmd/unlockWithdraw.go b/cmd/unlockWithdraw.go index 5edd33c91..187cd907b 100644 --- a/cmd/unlockWithdraw.go +++ b/cmd/unlockWithdraw.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "errors" "math/big" "razor/accounts" @@ -59,11 +60,11 @@ func (*UtilsStruct) ExecuteUnlockWithdraw(flagSet *pflag.FlagSet) { err = razorUtils.CheckPassword(account) utils.CheckError("Error in fetching private key from given password: ", err) - stakerId, err := razorUtils.AssignStakerId(flagSet, client, address) + stakerId, err := razorUtils.AssignStakerId(context.Background(), flagSet, client, address) utils.CheckError("Error in fetching stakerId: ", err) log.Debug("ExecuteUnlockWithdraw: StakerId: ", stakerId) - txn, err := cmdUtils.HandleWithdrawLock(client, account, config, stakerId) + txn, err := cmdUtils.HandleWithdrawLock(context.Background(), client, account, config, stakerId) utils.CheckError("HandleWithdrawLock error: ", err) if txn != core.NilHash { @@ -73,8 +74,8 @@ func (*UtilsStruct) ExecuteUnlockWithdraw(flagSet *pflag.FlagSet) { } //This function handles the Withdraw lock -func (*UtilsStruct) HandleWithdrawLock(client *ethclient.Client, account types.Account, configurations types.Configurations, stakerId uint32) (common.Hash, error) { - withdrawLock, err := razorUtils.GetLock(client, account.Address, stakerId, 1) +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) if err != nil { return core.NilHash, err } @@ -85,7 +86,7 @@ func (*UtilsStruct) HandleWithdrawLock(client *ethclient.Client, account types.A return core.NilHash, errors.New("initiate withdrawal of Razors before unlocking withdraw") } - epoch, err := razorUtils.GetEpoch(client) + epoch, err := razorUtils.GetEpoch(ctx, client) if err != nil { log.Error("Error in fetching epoch") return core.NilHash, err @@ -110,7 +111,7 @@ func (*UtilsStruct) HandleWithdrawLock(client *ethclient.Client, account types.A Parameters: []interface{}{stakerId}, Account: account, } - txnOpts := razorUtils.GetTxnOpts(txnArgs) + txnOpts := razorUtils.GetTxnOpts(ctx, txnArgs) log.Debug("HandleWithdrawLock: Calling UnlockWithdraw() with arguments stakerId = ", stakerId) return cmdUtils.UnlockWithdraw(client, txnOpts, stakerId) } diff --git a/cmd/unlockWithdraw_test.go b/cmd/unlockWithdraw_test.go index 210613e20..c5e44d38d 100644 --- a/cmd/unlockWithdraw_test.go +++ b/cmd/unlockWithdraw_test.go @@ -1,6 +1,7 @@ package cmd import ( + "context" "errors" "math/big" "razor/accounts" @@ -101,8 +102,8 @@ 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).Return(tt.args.stakerId, tt.args.stakerIdErr) - cmdUtilsMock.On("HandleWithdrawLock", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.Anything, mock.Anything).Return(tt.args.txn, tt.args.err) + 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) utils := &UtilsStruct{} utils.ExecuteUnlockWithdraw(flagSet) @@ -195,13 +196,13 @@ func TestHandleWithdrawLock(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetLock", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string"), mock.AnythingOfType("uint32"), mock.Anything).Return(tt.args.withdrawLock, tt.args.withdrawLockErr) - utilsMock.On("GetEpoch", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.epoch, tt.args.epochErr) - utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(TxnOpts) + 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("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(client, account, configurations, stakerId) + got, err := ut.HandleWithdrawLock(context.Background(), client, account, configurations, stakerId) if (err != nil) != tt.wantErr { t.Errorf("HandleWithdrawLock() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/cmd/unstake.go b/cmd/unstake.go index af79f2591..8d0ec8f50 100644 --- a/cmd/unstake.go +++ b/cmd/unstake.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "errors" "math/big" "razor/accounts" @@ -66,7 +67,7 @@ func (*UtilsStruct) ExecuteUnstake(flagSet *pflag.FlagSet) { valueInWei, err := cmdUtils.AssignAmountInWei(flagSet) utils.CheckError("Error in getting amountInWei: ", err) - stakerId, err := razorUtils.AssignStakerId(flagSet, client, address) + stakerId, err := razorUtils.AssignStakerId(context.Background(), flagSet, client, address) utils.CheckError("StakerId error: ", err) unstakeInput := types.UnstakeInput{ @@ -75,7 +76,7 @@ func (*UtilsStruct) ExecuteUnstake(flagSet *pflag.FlagSet) { Account: account, } - txnHash, err := cmdUtils.Unstake(config, client, unstakeInput) + txnHash, err := cmdUtils.Unstake(context.Background(), config, client, unstakeInput) utils.CheckError("Unstake Error: ", err) if txnHash != core.NilHash { err = razorUtils.WaitForBlockCompletion(client, txnHash.Hex()) @@ -84,7 +85,7 @@ func (*UtilsStruct) ExecuteUnstake(flagSet *pflag.FlagSet) { } //This function allows user to unstake their sRZRs in the razor network -func (*UtilsStruct) Unstake(config types.Configurations, client *ethclient.Client, input types.UnstakeInput) (common.Hash, error) { +func (*UtilsStruct) Unstake(ctx context.Context, config types.Configurations, client *ethclient.Client, input types.UnstakeInput) (common.Hash, error) { txnArgs := types.TransactionOptions{ Client: client, Amount: input.ValueInWei, @@ -93,7 +94,7 @@ func (*UtilsStruct) Unstake(config types.Configurations, client *ethclient.Clien Account: input.Account, } stakerId := input.StakerId - staker, err := razorUtils.GetStaker(client, stakerId) + staker, err := razorUtils.GetStaker(ctx, client, stakerId) if err != nil { log.Error("Error in getting staker: ", err) return core.NilHash, err @@ -119,7 +120,7 @@ func (*UtilsStruct) Unstake(config types.Configurations, client *ethclient.Clien txnArgs.MethodName = "unstake" txnArgs.ABI = bindings.StakeManagerMetaData.ABI - unstakeLock, err := razorUtils.GetLock(txnArgs.Client, txnArgs.Account.Address, stakerId, 0) + unstakeLock, err := razorUtils.GetLock(ctx, txnArgs.Client, txnArgs.Account.Address, stakerId, 0) if err != nil { log.Error("Error in getting unstakeLock: ", err) return core.NilHash, err @@ -133,7 +134,7 @@ func (*UtilsStruct) Unstake(config types.Configurations, client *ethclient.Clien } txnArgs.Parameters = []interface{}{stakerId, txnArgs.Amount} - txnOpts := razorUtils.GetTxnOpts(txnArgs) + txnOpts := razorUtils.GetTxnOpts(ctx, txnArgs) log.Info("Unstaking coins") log.Debugf("Executing Unstake transaction with stakerId = %d, amount = %s", stakerId, txnArgs.Amount) txn, err := stakeManagerUtils.Unstake(txnArgs.Client, txnOpts, stakerId, txnArgs.Amount) @@ -148,7 +149,7 @@ func (*UtilsStruct) Unstake(config types.Configurations, client *ethclient.Clien //This function approves the unstake func (*UtilsStruct) ApproveUnstake(client *ethclient.Client, stakerTokenAddress common.Address, txnArgs types.TransactionOptions) (common.Hash, error) { - txnOpts := razorUtils.GetTxnOpts(txnArgs) + txnOpts := razorUtils.GetTxnOpts(context.Background(), txnArgs) 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 3f8008dfe..3eb4a4672 100644 --- a/cmd/unstake_test.go +++ b/cmd/unstake_test.go @@ -1,6 +1,7 @@ package cmd import ( + "context" "crypto/ecdsa" "crypto/rand" "errors" @@ -122,17 +123,17 @@ func TestUnstake(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetStaker", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.staker, tt.args.stakerErr) + 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.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string"), mock.AnythingOfType("uint32"), mock.Anything).Return(tt.args.lock, tt.args.lockErr) + 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("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(TxnOpts) + 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(config, client, + _, gotErr := utils.Unstake(context.Background(), config, client, types.UnstakeInput{ Account: account, StakerId: stakerId, @@ -298,9 +299,9 @@ func TestExecuteUnstake(t *testing.T) { flagSetMock.On("GetStringAddress", flagSet).Return(tt.args.address, tt.args.addressErr) utilsMock.On("ConnectToClient", mock.AnythingOfType("string")).Return(client) cmdUtilsMock.On("AssignAmountInWei", flagSet).Return(tt.args.value, tt.args.valueErr) - utilsMock.On("AssignStakerId", flagSet, mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.stakerId, tt.args.stakerIdErr) + 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).Return(tt.args.unstakeHash, tt.args.unstakeErr) + 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) utils := &UtilsStruct{} @@ -357,7 +358,7 @@ func TestApproveUnstake(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(txnOpts) + utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(txnOpts) 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{} diff --git a/cmd/updateCollection.go b/cmd/updateCollection.go index 10b249064..0d4efc637 100644 --- a/cmd/updateCollection.go +++ b/cmd/updateCollection.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "razor/accounts" "razor/core" "razor/core/types" @@ -83,22 +84,22 @@ func (*UtilsStruct) ExecuteUpdateCollection(flagSet *pflag.FlagSet) { Tolerance: tolerance, Account: account, } - txn, err := cmdUtils.UpdateCollection(client, config, collectionInput, collectionId) + txn, err := cmdUtils.UpdateCollection(context.Background(), client, config, collectionInput, collectionId) utils.CheckError("Update Collection error: ", err) err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for updateCollection: ", err) } //This function allows the admin to update an existing collection -func (*UtilsStruct) UpdateCollection(client *ethclient.Client, config types.Configurations, collectionInput types.CreateCollectionInput, collectionId uint16) (common.Hash, error) { +func (*UtilsStruct) UpdateCollection(ctx context.Context, client *ethclient.Client, 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(client, "update collection") + _, err := cmdUtils.WaitIfCommitState(ctx, client, "update collection") if err != nil { log.Error("Error in fetching state") return core.NilHash, err } - txnOpts := razorUtils.GetTxnOpts(types.TransactionOptions{ + txnOpts := razorUtils.GetTxnOpts(ctx, types.TransactionOptions{ Client: client, ChainId: core.ChainId, Config: config, diff --git a/cmd/updateCollection_test.go b/cmd/updateCollection_test.go index f473a212d..5386f7246 100644 --- a/cmd/updateCollection_test.go +++ b/cmd/updateCollection_test.go @@ -1,6 +1,7 @@ package cmd import ( + "context" "errors" "math/big" "razor/accounts" @@ -75,13 +76,13 @@ func TestUpdateCollection(t *testing.T) { SetUpMockInterfaces() utilsMock.On("ConvertUintArrayToUint16Array", mock.Anything).Return(jobIdUint16) - utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(TxnOpts) - cmdUtilsMock.On("WaitIfCommitState", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(WaitIfCommitStateStatus, tt.args.waitIfCommitStateErr) + utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(TxnOpts) + cmdUtilsMock.On("WaitIfCommitState", mock.Anything, 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(client, config, collectionInput, collectionId) + got, err := utils.UpdateCollection(context.Background(), client, config, collectionInput, collectionId) if got != tt.want { t.Errorf("Txn hash for updateCollection function, got = %v, want = %v", got, tt.want) @@ -285,7 +286,7 @@ 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.AnythingOfType("*ethclient.Client"), config, mock.Anything, mock.Anything).Return(tt.args.updateCollectionTxn, tt.args.updateCollectionErr) + 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) flagSetMock.On("GetUint32Tolerance", flagSet).Return(tt.args.tolerance, tt.args.toleranceErr) diff --git a/cmd/updateCommission.go b/cmd/updateCommission.go index 5c59f15ab..5a79e17dd 100644 --- a/cmd/updateCommission.go +++ b/cmd/updateCommission.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "errors" "razor/accounts" "razor/core" @@ -61,7 +62,7 @@ func (*UtilsStruct) ExecuteUpdateCommission(flagSet *pflag.FlagSet) { commission, err := flagSetUtils.GetUint8Commission(flagSet) utils.CheckError("Error in getting commission", err) - stakerId, err := razorUtils.GetStakerId(client, address) + stakerId, err := razorUtils.GetStakerId(context.Background(), client, address) utils.CheckError("Error in getting stakerId", err) updateCommissionInput := types.UpdateCommissionInput{ @@ -70,20 +71,20 @@ func (*UtilsStruct) ExecuteUpdateCommission(flagSet *pflag.FlagSet) { Account: account, } - err = cmdUtils.UpdateCommission(config, client, updateCommissionInput) + err = cmdUtils.UpdateCommission(context.Background(), config, client, updateCommissionInput) utils.CheckError("UpdateCommission error: ", err) } //This function allows a staker to add/update the commission value -func (*UtilsStruct) UpdateCommission(config types.Configurations, client *ethclient.Client, updateCommissionInput types.UpdateCommissionInput) error { - stakerInfo, err := razorUtils.GetStaker(client, updateCommissionInput.StakerId) +func (*UtilsStruct) UpdateCommission(ctx context.Context, config types.Configurations, client *ethclient.Client, updateCommissionInput types.UpdateCommissionInput) error { + stakerInfo, err := razorUtils.GetStaker(ctx, client, 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(client) + maxCommission, err := razorUtils.GetMaxCommission(ctx, client) if err != nil { return err } @@ -93,13 +94,13 @@ func (*UtilsStruct) UpdateCommission(config types.Configurations, client *ethcli return errors.New("commission out of range") } - epochLimitForUpdateCommission, err := razorUtils.GetEpochLimitForUpdateCommission(client) + epochLimitForUpdateCommission, err := razorUtils.GetEpochLimitForUpdateCommission(ctx, client) if err != nil { return err } log.Debug("UpdateCommission: Epoch limit to update commission: ", epochLimitForUpdateCommission) - epoch, err := razorUtils.GetEpoch(client) + epoch, err := razorUtils.GetEpoch(ctx, client) if err != nil { return err } @@ -126,7 +127,7 @@ func (*UtilsStruct) UpdateCommission(config types.Configurations, client *ethcli Parameters: []interface{}{updateCommissionInput.Commission}, Account: updateCommissionInput.Account, } - updateCommissionTxnOpts := razorUtils.GetTxnOpts(txnOpts) + updateCommissionTxnOpts := razorUtils.GetTxnOpts(ctx, txnOpts) log.Infof("Setting the commission value of Staker %d to %d%%", updateCommissionInput.StakerId, updateCommissionInput.Commission) log.Debug("Executing UpdateCommission transaction with commission = ", updateCommissionInput.Commission) txn, err := stakeManagerUtils.UpdateCommission(client, updateCommissionTxnOpts, updateCommissionInput.Commission) diff --git a/cmd/updateCommission_test.go b/cmd/updateCommission_test.go index 79dbeecd7..df7169f41 100644 --- a/cmd/updateCommission_test.go +++ b/cmd/updateCommission_test.go @@ -1,6 +1,7 @@ package cmd import ( + "context" "errors" "razor/accounts" "razor/core/types" @@ -190,18 +191,18 @@ func TestUpdateCommission(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetStaker", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.stakerInfo, tt.args.stakerInfoErr) - utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(TxnOpts) - utilsMock.On("GetEpoch", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.epoch, tt.args.epochErr) + utilsMock.On("GetStaker", mock.Anything, 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) transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(nil) - utilsMock.On("GetMaxCommission", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.maxCommission, tt.args.maxCommissionErr) - utilsMock.On("GetEpochLimitForUpdateCommission", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.epochLimitForUpdateCommission, tt.args.epochLimitForUpdateCommissionErr) + 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("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(config, client, types.UpdateCommissionInput{ + gotErr := utils.UpdateCommission(context.Background(), config, client, types.UpdateCommissionInput{ Commission: tt.args.commission, }) if gotErr == nil || tt.wantErr == nil { @@ -338,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.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.stakerId, tt.args.stakerIdErr) + utilsMock.On("GetStakerId", mock.Anything, 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).Return(tt.args.UpdateCommissionErr) + cmdUtilsMock.On("UpdateCommission", mock.Anything, 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 a1cbe352d..b0828f2d0 100644 --- a/cmd/updateJob.go +++ b/cmd/updateJob.go @@ -2,6 +2,7 @@ package cmd import ( + "context" "razor/accounts" "razor/core" "razor/core/types" @@ -88,20 +89,20 @@ func (*UtilsStruct) ExecuteUpdateJob(flagSet *pflag.FlagSet) { Account: account, } - txn, err := cmdUtils.UpdateJob(client, config, jobInput, jobId) + txn, err := cmdUtils.UpdateJob(context.Background(), client, config, jobInput, jobId) utils.CheckError("UpdateJob error: ", err) err = razorUtils.WaitForBlockCompletion(client, txn.Hex()) utils.CheckError("Error in WaitForBlockCompletion for updateJob: ", err) } //This function allows the admin to update an existing job -func (*UtilsStruct) UpdateJob(client *ethclient.Client, config types.Configurations, jobInput types.CreateJobInput, jobId uint16) (common.Hash, error) { - _, err := cmdUtils.WaitIfCommitState(client, "update 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") if err != nil { log.Error("Error in fetching state") return core.NilHash, err } - txnArgs := razorUtils.GetTxnOpts(types.TransactionOptions{ + txnArgs := razorUtils.GetTxnOpts(ctx, types.TransactionOptions{ Client: client, ChainId: core.ChainId, Config: config, diff --git a/cmd/updateJob_test.go b/cmd/updateJob_test.go index 0d2da59a7..43c3d3b34 100644 --- a/cmd/updateJob_test.go +++ b/cmd/updateJob_test.go @@ -1,6 +1,7 @@ package cmd import ( + "context" "errors" "math/big" "razor/accounts" @@ -69,14 +70,14 @@ func TestUpdateJob(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetTxnOpts", mock.AnythingOfType("types.TransactionOptions")).Return(TxnOpts) - cmdUtilsMock.On("WaitIfCommitState", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(WaitIfCommitStateStatus, tt.args.waitIfCommitStateErr) + utilsMock.On("GetTxnOpts", mock.Anything, mock.Anything).Return(TxnOpts) + cmdUtilsMock.On("WaitIfCommitState", mock.Anything, mock.Anything, mock.Anything).Return(WaitIfCommitStateStatus, tt.args.waitIfCommitStateErr) assetManagerMock.On("UpdateJob", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("*bind.TransactOpts"), mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.updateJobTxn, tt.args.updateJobErr) transactionMock.On("Hash", mock.Anything).Return(tt.args.hash) utils := &UtilsStruct{} - got, err := utils.UpdateJob(client, config, jobInput, jobId) + got, err := utils.UpdateJob(context.Background(), client, config, jobInput, jobId) if got != tt.want { t.Errorf("Txn hash for updateJob function, got = %v, want = %v", got, tt.want) } @@ -334,7 +335,7 @@ 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.AnythingOfType("*ethclient.Client"), config, mock.Anything, mock.Anything).Return(tt.args.updateJobTxn, tt.args.updateJobErr) + 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) utils := &UtilsStruct{} diff --git a/cmd/vote.go b/cmd/vote.go index 0dd69073a..e7d11dc05 100644 --- a/cmd/vote.go +++ b/cmd/vote.go @@ -54,7 +54,7 @@ func (*UtilsStruct) ExecuteVote(flagSet *pflag.FlagSet) { client := razorUtils.ConnectToClient(config.Provider) - err = ValidateBufferPercentLimit(client, config.BufferPercent) + err = ValidateBufferPercentLimit(context.Background(), client, config.BufferPercent) utils.CheckError("Error in validating buffer percent: ", err) address, err := flagSetUtils.GetStringAddress(flagSet) @@ -106,7 +106,7 @@ func (*UtilsStruct) ExecuteVote(flagSet *pflag.FlagSet) { }, } - stakerId, err := razorUtils.GetStakerId(client, address) + stakerId, err := razorUtils.GetStakerId(context.Background(), client, address) utils.CheckError("Error in getting staker id: ", err) if stakerId == 0 { @@ -115,7 +115,7 @@ func (*UtilsStruct) ExecuteVote(flagSet *pflag.FlagSet) { cmdUtils.HandleExit() - jobsCache, collectionsCache, initCacheBlockNumber, err := cmdUtils.InitJobAndCollectionCache(client) + jobsCache, collectionsCache, initCacheBlockNumber, err := cmdUtils.InitJobAndCollectionCache(context.Background(), client) utils.CheckError("Error in initializing asset cache: ", err) commitParams := &types.CommitParams{ @@ -159,7 +159,7 @@ 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(client) + header, err := clientUtils.GetLatestBlockWithRetry(context.Background(), client) utils.CheckError("Error in getting block: ", err) for { select { @@ -167,7 +167,7 @@ func (*UtilsStruct) Vote(ctx context.Context, config types.Configurations, clien return nil default: log.Debugf("Vote: Header value: %d", header.Number) - latestHeader, err := clientUtils.GetLatestBlockWithRetry(client) + latestHeader, err := clientUtils.GetLatestBlockWithRetry(context.Background(), client) if err != nil { log.Error("Error in fetching block: ", err) continue @@ -191,25 +191,41 @@ var ( //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) { - state, err := razorUtils.GetBufferedState(client, latestHeader, config.BufferPercent) + stateBuffer, err := razorUtils.GetStateBuffer(context.Background(), client) + if err != nil { + log.Error("Error in getting state buffer: ", err) + return + } + remainingTimeOfTheCurrentState, err := razorUtils.GetRemainingTimeOfCurrentState(latestHeader, stateBuffer, config.BufferPercent) + if err != nil { + log.Error("Error in getting remaining time of the current state: ", err) + return + } + if remainingTimeOfTheCurrentState <= 0 { + return + } + + ctx, cancel := context.WithTimeout(context.Background(), time.Duration(remainingTimeOfTheCurrentState)*time.Second) + defer cancel() + state, err := razorUtils.GetBufferedState(latestHeader, stateBuffer, config.BufferPercent) if err != nil { log.Error("Error in getting state: ", err) return } - epoch, err := razorUtils.GetEpoch(client) + epoch, err := razorUtils.GetEpoch(ctx, client) if err != nil { log.Error("Error in getting epoch: ", err) return } - staker, err := razorUtils.GetStaker(client, stakerId) + staker, err := razorUtils.GetStaker(ctx, client, stakerId) if err != nil { log.Error(err) return } stakedAmount := staker.Stake - ethBalance, err := clientUtils.BalanceAtWithRetry(client, common.HexToAddress(account.Address)) + ethBalance, err := clientUtils.BalanceAtWithRetry(ctx, client, common.HexToAddress(account.Address)) if err != nil { log.Errorf("Error in fetching balance of the account: %s\n%v", account.Address, err) return @@ -231,7 +247,7 @@ func (*UtilsStruct) HandleBlock(client *ethclient.Client, account types.Account, return } - sRZRBalance, err := razorUtils.GetStakerSRZRBalance(client, staker) + sRZRBalance, err := razorUtils.GetStakerSRZRBalance(ctx, client, staker) if err != nil { log.Error("Error in getting sRZR balance for staker: ", err) return @@ -258,21 +274,21 @@ func (*UtilsStruct) HandleBlock(client *ethclient.Client, account types.Account, switch state { case 0: log.Debugf("Starting commit...") - err := cmdUtils.InitiateCommit(client, config, account, epoch, stakerId, latestHeader, commitParams, rogueData) + err := cmdUtils.InitiateCommit(ctx, client, config, account, epoch, stakerId, latestHeader, commitParams, stateBuffer, rogueData) if err != nil { log.Error(err) break } case 1: log.Debugf("Starting reveal...") - err := cmdUtils.InitiateReveal(client, config, account, epoch, staker, latestHeader, rogueData) + err := cmdUtils.InitiateReveal(ctx, client, config, account, epoch, staker, latestHeader, stateBuffer, rogueData) if err != nil { log.Error(err) break } case 2: log.Debugf("Starting propose...") - err := cmdUtils.InitiatePropose(client, config, account, epoch, staker, latestHeader, rogueData) + err := cmdUtils.InitiatePropose(ctx, client, config, account, epoch, staker, latestHeader, stateBuffer, rogueData) if err != nil { log.Error(err) break @@ -285,7 +301,7 @@ func (*UtilsStruct) HandleBlock(client *ethclient.Client, account types.Account, break } - err := cmdUtils.HandleDispute(client, config, account, epoch, latestHeader.Number, rogueData, backupNodeActionsToIgnore) + err := cmdUtils.HandleDispute(ctx, client, config, account, epoch, latestHeader.Number, rogueData, backupNodeActionsToIgnore) if err != nil { log.Error(err) break @@ -306,7 +322,7 @@ func (*UtilsStruct) HandleBlock(client *ethclient.Client, account types.Account, log.Debugf("Last verification: %d", lastVerification) log.Debugf("Block confirmed: %d", blockConfirmed) if lastVerification == epoch && blockConfirmed < epoch { - txn, err := cmdUtils.ClaimBlockReward(types.TransactionOptions{ + txn, err := cmdUtils.ClaimBlockReward(ctx, types.TransactionOptions{ Client: client, ChainId: core.ChainId, Config: config, @@ -340,8 +356,8 @@ func (*UtilsStruct) HandleBlock(client *ethclient.Client, account types.Account, } //This function initiates the commit -func (*UtilsStruct) InitiateCommit(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, stakerId uint32, latestHeader *Types.Header, commitParams *types.CommitParams, rogueData types.Rogue) error { - lastCommit, err := razorUtils.GetEpochLastCommitted(client, stakerId) +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) if err != nil { return errors.New("Error in fetching last commit: " + err.Error()) } @@ -352,20 +368,20 @@ func (*UtilsStruct) InitiateCommit(client *ethclient.Client, config types.Config return nil } - err = CheckForJobAndCollectionEvents(client, commitParams) + err = CheckForJobAndCollectionEvents(ctx, client, commitParams) if err != nil { log.Error("Error in checking for asset events: ", err) return err } - staker, err := razorUtils.GetStaker(client, stakerId) + staker, err := razorUtils.GetStaker(ctx, client, stakerId) if err != nil { log.Error(err) return err } log.Debug("InitiateCommit: Staker:", staker) stakedAmount := staker.Stake - minStakeAmount, err := razorUtils.GetMinStakeAmount(client) + minStakeAmount, err := razorUtils.GetMinStakeAmount(ctx, client) if err != nil { log.Error("Error in getting minimum stake amount: ", err) return err @@ -383,19 +399,19 @@ func (*UtilsStruct) InitiateCommit(client *ethclient.Client, config types.Config 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(client, account, keystorePath, epoch) + seed, err := CalculateSeed(ctx, client, 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(client, epoch, seed, commitParams, rogueData) + commitData, err := cmdUtils.HandleCommitState(ctx, client, epoch, seed, commitParams, rogueData) if err != nil { return errors.New("Error in getting active assets: " + err.Error()) } log.Debug("InitiateCommit: Commit Data: ", commitData) - commitTxn, err := cmdUtils.Commit(client, config, account, epoch, latestHeader, seed, commitData.Leaves) + commitTxn, err := cmdUtils.Commit(ctx, client, config, account, epoch, latestHeader, stateBuffer, seed, commitData.Leaves) if err != nil { return errors.New("Error in committing data: " + err.Error()) } @@ -431,10 +447,10 @@ func (*UtilsStruct) InitiateCommit(client *ethclient.Client, config types.Config } //This function initiates the reveal -func (*UtilsStruct) InitiateReveal(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, latestHeader *Types.Header, rogueData types.Rogue) error { +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 { stakedAmount := staker.Stake log.Debug("InitiateReveal: Staked Amount: ", stakedAmount) - minStakeAmount, err := razorUtils.GetMinStakeAmount(client) + minStakeAmount, err := razorUtils.GetMinStakeAmount(ctx, client) if err != nil { log.Error("Error in getting minimum stake amount: ", err) return err @@ -444,7 +460,7 @@ func (*UtilsStruct) InitiateReveal(client *ethclient.Client, config types.Config log.Error("Stake is below minimum required. Kindly add stake to continue voting.") return nil } - lastReveal, err := razorUtils.GetEpochLastRevealed(client, staker.Id) + lastReveal, err := razorUtils.GetEpochLastRevealed(ctx, client, staker.Id) if err != nil { return errors.New("Error in fetching last reveal: " + err.Error()) } @@ -456,7 +472,7 @@ func (*UtilsStruct) InitiateReveal(client *ethclient.Client, config types.Config } log.Debugf("InitiateReveal: Calling CheckForLastCommitted with arguments staker = %+v, epoch = %d", staker, epoch) - if err := cmdUtils.CheckForLastCommitted(client, staker, epoch); err != nil { + if err := cmdUtils.CheckForLastCommitted(ctx, client, staker, epoch); err != nil { log.Error(err) return err } @@ -490,7 +506,7 @@ func (*UtilsStruct) InitiateReveal(client *ethclient.Client, config types.Config log.Debugf("InitiateReveal: Keystore file path: %s", keystorePath) log.Debugf("InitiateReveal: Calling VerifyCommitment() for address %v with arguments epoch = %v, values = %v", account.Address, epoch, committedDataFromFile.Leaves) - isCommittedDataFromFileValid, err := VerifyCommitment(client, account, keystorePath, epoch, committedDataFromFile.Leaves) + isCommittedDataFromFileValid, err := VerifyCommitment(ctx, client, account, keystorePath, epoch, committedDataFromFile.Leaves) if err != nil { log.Error("Error in verifying commitment for commit data from file: ", err) return err @@ -542,7 +558,7 @@ func (*UtilsStruct) InitiateReveal(client *ethclient.Client, config types.Config SeqAllottedCollections: globalCommitDataStruct.SeqAllottedCollections, } log.Debugf("InitiateReveal: Calling Reveal() with arguments epoch = %d, commitDataToSend = %+v, signature = %v", epoch, commitDataToSend, signature) - revealTxn, err := cmdUtils.Reveal(client, config, account, epoch, latestHeader, commitDataToSend, signature) + revealTxn, err := cmdUtils.Reveal(ctx, client, config, account, epoch, latestHeader, stateBuffer, commitDataToSend, signature) if err != nil { return errors.New("Reveal error: " + err.Error()) } @@ -561,10 +577,10 @@ func (*UtilsStruct) InitiateReveal(client *ethclient.Client, config types.Config } //This function initiates the propose -func (*UtilsStruct) InitiatePropose(client *ethclient.Client, config types.Configurations, account types.Account, epoch uint32, staker bindings.StructsStaker, latestHeader *Types.Header, rogueData types.Rogue) error { +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 { stakedAmount := staker.Stake log.Debug("InitiatePropose: Staked Amount: ", stakedAmount) - minStakeAmount, err := razorUtils.GetMinStakeAmount(client) + minStakeAmount, err := razorUtils.GetMinStakeAmount(ctx, client) if err != nil { log.Error("Error in getting minimum stake amount: ", err) return err @@ -574,7 +590,7 @@ func (*UtilsStruct) InitiatePropose(client *ethclient.Client, config types.Confi log.Error("Stake is below minimum required. Kindly add stake to continue voting.") return nil } - lastProposal, err := razorUtils.GetEpochLastProposed(client, staker.Id) + lastProposal, err := razorUtils.GetEpochLastProposed(ctx, client, staker.Id) if err != nil { return errors.New("Error in fetching last proposal: " + err.Error()) } @@ -583,7 +599,7 @@ func (*UtilsStruct) InitiatePropose(client *ethclient.Client, config types.Confi log.Debugf("Since last propose was at epoch: %d, won't propose again in epoch: %d", epoch, lastProposal) return nil } - lastReveal, err := razorUtils.GetEpochLastRevealed(client, staker.Id) + lastReveal, err := razorUtils.GetEpochLastRevealed(ctx, client, staker.Id) if err != nil { return errors.New("Error in fetching last reveal: " + err.Error()) } @@ -594,7 +610,7 @@ func (*UtilsStruct) InitiatePropose(client *ethclient.Client, config types.Confi } log.Debugf("InitiatePropose: Calling Propose() with arguments staker = %+v, epoch = %d, blockNumber = %s, rogueData = %+v", staker, epoch, latestHeader.Number, rogueData) - err = cmdUtils.Propose(client, config, account, staker, epoch, latestHeader, rogueData) + err = cmdUtils.Propose(ctx, client, 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 4809a8ad6..07549319b 100644 --- a/cmd/vote_test.go +++ b/cmd/vote_test.go @@ -161,7 +161,7 @@ func TestExecuteVote(t *testing.T) { fileUtilsMock.On("AssignLogFile", mock.AnythingOfType("*pflag.FlagSet"), mock.Anything) cmdUtilsMock.On("GetConfigData").Return(tt.args.config, tt.args.configErr) - utilsMock.On("GetStateBuffer", mock.Anything).Return(uint64(5), nil) + utilsMock.On("GetStateBuffer", mock.Anything, 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,9 +169,9 @@ 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.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.stakerId, tt.args.stakerIdErr) + utilsMock.On("GetStakerId", mock.Anything, 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).Return(&cache.JobsCache{}, &cache.CollectionsCache{}, big.NewInt(100), nil) + cmdUtilsMock.On("InitJobAndCollectionCache", mock.Anything, 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) osMock.On("Exit", mock.AnythingOfType("int")).Return() @@ -339,6 +339,7 @@ func TestInitiateCommit(t *testing.T) { client *ethclient.Client config types.Configurations latestHeader *Types.Header + stateBuffer uint64 account types.Account stakerId uint32 rogueData types.Rogue @@ -549,21 +550,21 @@ func TestInitiateCommit(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetStaker", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.staker, tt.args.stakerErr) - utilsMock.On("GetMinStakeAmount", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.minStakeAmount, tt.args.minStakeAmountErr) - utilsMock.On("GetEpochLastCommitted", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.lastCommit, tt.args.lastCommitErr) - cmdUtilsMock.On("CalculateSecret", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(tt.args.signature, tt.args.secret, tt.args.secretErr) - cmdUtilsMock.On("GetSalt", mock.AnythingOfType("*ethclient.Client"), 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) + 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) + 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) 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).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, mock.Anything).Return(tt.args.commitTxn, tt.args.commitTxnErr) utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.waitForBlockCompletionErr) pathMock.On("GetCommitDataFileName", mock.AnythingOfType("string")).Return(tt.args.fileName, tt.args.fileNameErr) fileUtilsMock.On("SaveDataToCommitJsonFile", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.saveErr) - clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything).Return(&Types.Header{Number: big.NewInt(100)}, nil) - clientUtilsMock.On("FilterLogsWithRetry", mock.Anything, mock.Anything).Return([]Types.Log{}, nil) + clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything, 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(client, config, account, tt.args.epoch, stakerId, latestHeader, commitParams, rogueData); (err != nil) != tt.wantErr { + if err := ut.InitiateCommit(context.Background(), client, config, account, tt.args.epoch, stakerId, latestHeader, commitParams, stateBuffer, rogueData); (err != nil) != tt.wantErr { t.Errorf("InitiateCommit() error = %v, wantErr %v", err, tt.wantErr) } }) @@ -576,6 +577,7 @@ func TestInitiateReveal(t *testing.T) { config types.Configurations account types.Account latestHeader *Types.Header + stateBuffer uint64 ) randomNum := big.NewInt(1111) @@ -771,20 +773,20 @@ func TestInitiateReveal(t *testing.T) { utils.MerkleInterface = &utils.MerkleTreeStruct{} merkleUtils = utils.MerkleInterface - utilsMock.On("GetMinStakeAmount", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.minStakeAmount, tt.args.minStakeAmountErr) - utilsMock.On("GetEpochLastRevealed", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.lastReveal, tt.args.lastRevealErr) - cmdUtilsMock.On("CheckForLastCommitted", mock.AnythingOfType("*ethclient.Client"), mock.Anything, mock.AnythingOfType("uint32")).Return(tt.args.revealStateErr) + 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) 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).Return(tt.args.signature, tt.args.secret, tt.args.secretErr) - cmdUtilsMock.On("GetSalt", mock.Anything, mock.Anything).Return([32]byte{}, nil) - utilsMock.On("GetCommitment", mock.Anything, mock.Anything).Return(types.Commitment{}, 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) + 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{}, 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) ut := &UtilsStruct{} - if err := ut.InitiateReveal(client, config, account, tt.args.epoch, tt.args.staker, latestHeader, tt.args.rogueData); (err != nil) != tt.wantErr { + if err := ut.InitiateReveal(context.Background(), client, 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) } }) @@ -793,10 +795,11 @@ func TestInitiateReveal(t *testing.T) { func TestInitiatePropose(t *testing.T) { var ( - client *ethclient.Client - config types.Configurations - account types.Account - rogueData types.Rogue + client *ethclient.Client + config types.Configurations + account types.Account + rogueData types.Rogue + stateBuffer uint64 ) type args struct { staker bindings.StructsStaker @@ -897,13 +900,13 @@ func TestInitiatePropose(t *testing.T) { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() - utilsMock.On("GetMinStakeAmount", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.minStakeAmount, tt.args.minStakeAmountErr) - utilsMock.On("GetEpochLastProposed", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.lastProposal, tt.args.lastProposalErr) - utilsMock.On("GetEpochLastRevealed", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).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("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) ut := &UtilsStruct{} - if err := ut.InitiatePropose(client, config, account, tt.args.epoch, tt.args.staker, latestHeader, rogueData); (err != nil) != tt.wantErr { + if err := ut.InitiatePropose(context.Background(), client, 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) } }) @@ -924,31 +927,33 @@ func TestHandleBlock(t *testing.T) { Number: big.NewInt(1001), } type args struct { - config types.Configurations - state int64 - stateErr error - epoch uint32 - epochErr error - stateName string - staker bindings.StructsStaker - stakerErr error - ethBalance *big.Int - ethBalanceErr error - actualStake *big.Float - actualStakeErr error - actualBalance *big.Float - sRZRBalance *big.Int - sRZRBalanceErr error - sRZRInEth *big.Float - initiateCommitErr error - initiateRevealErr error - initiateProposeErr error - handleDisputeErr error - claimBlockRewardTxn common.Hash - claimBlockRewardErr error - lastVerification uint32 - isFlagPassed bool - handleClaimBountyErr error + config types.Configurations + stateBufferErr error + stateRemainingTimeErr error + state int64 + stateErr error + epoch uint32 + epochErr error + stateName string + staker bindings.StructsStaker + stakerErr error + ethBalance *big.Int + ethBalanceErr error + actualStake *big.Float + actualStakeErr error + actualBalance *big.Float + sRZRBalance *big.Int + sRZRBalanceErr error + sRZRInEth *big.Float + initiateCommitErr error + initiateRevealErr error + initiateProposeErr error + handleDisputeErr error + claimBlockRewardTxn common.Hash + claimBlockRewardErr error + lastVerification uint32 + isFlagPassed bool + handleClaimBountyErr error } tests := []struct { name string @@ -1222,24 +1227,38 @@ func TestHandleBlock(t *testing.T) { config: types.Configurations{WaitTime: 6}, }, }, + { + name: "Test 23: When there is an error in getting stateBuffer", + args: args{ + stateBufferErr: errors.New("state buffer error"), + }, + }, + { + name: "Test 24: When there is an error in getting state remaining time", + args: args{ + stateRemainingTimeErr: errors.New("state remaining time error"), + }, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { SetUpMockInterfaces() + utilsMock.On("GetStateBuffer", mock.Anything, 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.AnythingOfType("*ethclient.Client")).Return(tt.args.epoch, tt.args.epochErr) - utilsMock.On("GetStaker", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.staker, tt.args.stakerErr) - clientUtilsMock.On("BalanceAtWithRetry", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(tt.args.ethBalance, tt.args.ethBalanceErr) - utilsMock.On("GetStakerSRZRBalance", mock.Anything, mock.Anything).Return(tt.args.sRZRBalance, tt.args.sRZRBalanceErr) + 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) 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).Return(tt.args.initiateCommitErr) - cmdUtilsMock.On("InitiateReveal", 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).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) + 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) utilsMock.On("IsFlagPassed", mock.AnythingOfType("string")).Return(tt.args.isFlagPassed) cmdUtilsMock.On("HandleClaimBounty", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.handleClaimBountyErr) - cmdUtilsMock.On("ClaimBlockReward", mock.Anything).Return(tt.args.claimBlockRewardTxn, tt.args.claimBlockRewardErr) + cmdUtilsMock.On("ClaimBlockReward", mock.Anything, mock.Anything).Return(tt.args.claimBlockRewardTxn, tt.args.claimBlockRewardErr) utilsMock.On("WaitForBlockCompletion", mock.AnythingOfType("*ethclient.Client"), mock.Anything).Return(nil) timeMock.On("Sleep", mock.Anything).Return() utilsMock.On("WaitTillNextNSecs", mock.AnythingOfType("int32")).Return() @@ -1285,7 +1304,7 @@ func TestVote(t *testing.T) { SetUpMockInterfaces() - clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything).Return(tt.args.header, nil) + clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything, 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) ut := &UtilsStruct{} diff --git a/utils/asset.go b/utils/asset.go index 7f3602a41..6750d8e9e 100644 --- a/utils/asset.go +++ b/utils/asset.go @@ -1,6 +1,7 @@ package utils import ( + "context" "encoding/hex" "encoding/json" "errors" @@ -141,21 +142,21 @@ func (*UtilsStruct) GetActiveCollectionIds(client *ethclient.Client) ([]uint16, return activeCollectionIds, nil } -func (*UtilsStruct) GetAggregatedDataOfCollection(client *ethclient.Client, collectionId uint16, epoch uint32, commitParams *types.CommitParams) (*big.Int, error) { +func (*UtilsStruct) GetAggregatedDataOfCollection(ctx context.Context, client *ethclient.Client, 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(client, epoch-1, activeCollection, commitParams) + collectionData, aggregationError := UtilsInterface.Aggregate(ctx, client, epoch-1, activeCollection, commitParams) if aggregationError != nil { return nil, aggregationError } return collectionData, nil } -func (*UtilsStruct) Aggregate(client *ethclient.Client, previousEpoch uint32, collection bindings.StructsCollection, commitParams *types.CommitParams) (*big.Int, error) { +func (*UtilsStruct) Aggregate(ctx context.Context, client *ethclient.Client, previousEpoch uint32, collection bindings.StructsCollection, commitParams *types.CommitParams) (*big.Int, error) { var jobs []bindings.StructsJob var overriddenJobIds []uint16 @@ -213,7 +214,7 @@ func (*UtilsStruct) Aggregate(client *ethclient.Client, previousEpoch uint32, co } dataToCommit, weight := UtilsInterface.GetDataToCommitFromJobs(jobs, commitParams) if len(dataToCommit) == 0 { - prevCommitmentData, err := UtilsInterface.FetchPreviousValue(client, previousEpoch, collection.Id) + prevCommitmentData, err := UtilsInterface.FetchPreviousValue(ctx, client, previousEpoch, collection.Id) if err != nil { return nil, err } @@ -360,10 +361,10 @@ func (*UtilsStruct) GetDataToCommitFromJob(job bindings.StructsJob, commitParams return MultiplyWithPower(datum, job.Power), err } -func (*UtilsStruct) GetAssignedCollections(client *ethclient.Client, numActiveCollections uint16, seed []byte) (map[int]bool, []*big.Int, error) { +func (*UtilsStruct) GetAssignedCollections(ctx context.Context, client *ethclient.Client, numActiveCollections uint16, seed []byte) (map[int]bool, []*big.Int, error) { assignedCollections := make(map[int]bool) var seqAllottedCollections []*big.Int - toAssign, err := UtilsInterface.ToAssign(client) + toAssign, err := UtilsInterface.ToAssign(ctx, client) if err != nil { return nil, nil, err } diff --git a/utils/asset_test.go b/utils/asset_test.go index cf4dfa740..a95c0ae83 100644 --- a/utils/asset_test.go +++ b/utils/asset_test.go @@ -1,6 +1,7 @@ package utils import ( + "context" "errors" "fmt" "io/fs" @@ -199,14 +200,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.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("uint16")).Return(tt.args.prevCommitmentData, tt.args.prevCommitmentDataErr) + utilsMock.On("FetchPreviousValue", mock.Anything, 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) - got, err := utils.Aggregate(client, previousEpoch, tt.args.collection, commitParams) + got, err := utils.Aggregate(context.Background(), client, previousEpoch, tt.args.collection, commitParams) if (err != nil) != tt.wantErr { t.Errorf("Aggregate() error = %v, wantErr %v", err, tt.wantErr) @@ -1328,9 +1329,9 @@ func TestGetAggregatedDataOfCollection(t *testing.T) { utils := StartRazor(optionsPackageStruct) 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).Return(tt.args.collectionData, tt.args.aggregationErr) + 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(client, collectionId, epoch, &types.CommitParams{HttpClient: &http.Client{}}) + got, err := utils.GetAggregatedDataOfCollection(context.Background(), client, collectionId, epoch, &types.CommitParams{HttpClient: &http.Client{}}) if (err != nil) != tt.wantErr { t.Errorf("GetAggregatedDataOfCollection() error = %v, wantErr %v", err, tt.wantErr) return @@ -1388,10 +1389,10 @@ func TestGetAssignedCollections(t *testing.T) { } utils := StartRazor(optionsPackageStruct) - utilsMock.On("ToAssign", mock.Anything).Return(tt.args.toAssign, tt.args.toAssignErr) + utilsMock.On("ToAssign", mock.Anything, 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(client, numActiveCollections, seed) + got, got1, err := utils.GetAssignedCollections(context.Background(), client, numActiveCollections, seed) if (err != nil) != tt.wantErr { t.Errorf("GetAssignedCollections() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/utils/block.go b/utils/block.go index 80f303421..53544e78b 100644 --- a/utils/block.go +++ b/utils/block.go @@ -1,6 +1,7 @@ package utils import ( + "context" "errors" "math/big" "razor/pkg/bindings" @@ -13,24 +14,24 @@ func (*UtilsStruct) GetBlockManagerWithOpts(client *ethclient.Client) (*bindings return UtilsInterface.GetBlockManager(client), UtilsInterface.GetOptions() } -func (*UtilsStruct) GetNumberOfProposedBlocks(client *ethclient.Client, epoch uint32) (uint8, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(BlockManagerInterface, "GetNumProposedBlocks", client, epoch) +func (*UtilsStruct) GetNumberOfProposedBlocks(ctx context.Context, client *ethclient.Client, epoch uint32) (uint8, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, BlockManagerInterface, "GetNumProposedBlocks", client, epoch) if err != nil { return 0, err } return returnedValues[0].Interface().(uint8), nil } -func (*UtilsStruct) GetProposedBlock(client *ethclient.Client, epoch uint32, proposedBlockId uint32) (bindings.StructsBlock, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(BlockManagerInterface, "GetProposedBlock", client, epoch, proposedBlockId) +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) if err != nil { return bindings.StructsBlock{}, err } return returnedValues[0].Interface().(bindings.StructsBlock), nil } -func (*UtilsStruct) FetchPreviousValue(client *ethclient.Client, epoch uint32, assetId uint16) (*big.Int, error) { - block, err := UtilsInterface.GetBlock(client, epoch) +func (*UtilsStruct) FetchPreviousValue(ctx context.Context, client *ethclient.Client, epoch uint32, assetId uint16) (*big.Int, error) { + block, err := UtilsInterface.GetBlock(ctx, client, epoch) if err != nil { return big.NewInt(0), err } @@ -40,24 +41,24 @@ func (*UtilsStruct) FetchPreviousValue(client *ethclient.Client, epoch uint32, a return block.Medians[assetId-1], nil } -func (*UtilsStruct) GetBlock(client *ethclient.Client, epoch uint32) (bindings.StructsBlock, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(BlockManagerInterface, "GetBlock", client, epoch) +func (*UtilsStruct) GetBlock(ctx context.Context, client *ethclient.Client, epoch uint32) (bindings.StructsBlock, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, BlockManagerInterface, "GetBlock", client, epoch) if err != nil { return bindings.StructsBlock{}, err } return returnedValues[0].Interface().(bindings.StructsBlock), nil } -func (*UtilsStruct) GetMinStakeAmount(client *ethclient.Client) (*big.Int, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(BlockManagerInterface, "MinStake", client) +func (*UtilsStruct) GetMinStakeAmount(ctx context.Context, client *ethclient.Client) (*big.Int, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, BlockManagerInterface, "MinStake", client) if err != nil { return nil, err } return returnedValues[0].Interface().(*big.Int), nil } -func (*UtilsStruct) GetStateBuffer(client *ethclient.Client) (uint64, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(BlockManagerInterface, "StateBuffer", client) +func (*UtilsStruct) GetStateBuffer(ctx context.Context, client *ethclient.Client) (uint64, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, BlockManagerInterface, "StateBuffer", client) if err != nil { return 0, err } @@ -65,31 +66,31 @@ func (*UtilsStruct) GetStateBuffer(client *ethclient.Client) (uint64, error) { return uint64(stateBufferUint8), nil } -func (*UtilsStruct) GetMaxAltBlocks(client *ethclient.Client) (uint8, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(BlockManagerInterface, "MaxAltBlocks", client) +func (*UtilsStruct) GetMaxAltBlocks(ctx context.Context, client *ethclient.Client) (uint8, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, BlockManagerInterface, "MaxAltBlocks", client) if err != nil { return 0, err } return returnedValues[0].Interface().(uint8), nil } -func (*UtilsStruct) GetSortedProposedBlockId(client *ethclient.Client, epoch uint32, index *big.Int) (uint32, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(BlockManagerInterface, "SortedProposedBlockIds", client, epoch, index) +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) if err != nil { return 0, err } return returnedValues[0].Interface().(uint32), nil } -func (*UtilsStruct) GetSortedProposedBlockIds(client *ethclient.Client, epoch uint32) ([]uint32, error) { - numberOfProposedBlocks, err := UtilsInterface.GetNumberOfProposedBlocks(client, epoch) +func (*UtilsStruct) GetSortedProposedBlockIds(ctx context.Context, client *ethclient.Client, epoch uint32) ([]uint32, error) { + numberOfProposedBlocks, err := UtilsInterface.GetNumberOfProposedBlocks(ctx, client, epoch) if err != nil { log.Error(err) return nil, err } var sortedProposedBlockIds []uint32 for i := 0; i < int(numberOfProposedBlocks); i++ { - id, err := UtilsInterface.GetSortedProposedBlockId(client, epoch, big.NewInt(int64(i))) + id, err := UtilsInterface.GetSortedProposedBlockId(ctx, client, epoch, big.NewInt(int64(i))) if err != nil { log.Error(err) return nil, err @@ -99,16 +100,16 @@ func (*UtilsStruct) GetSortedProposedBlockIds(client *ethclient.Client, epoch ui return sortedProposedBlockIds, nil } -func (*UtilsStruct) GetBlockIndexToBeConfirmed(client *ethclient.Client) (int8, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(BlockManagerInterface, "GetBlockIndexToBeConfirmed", client) +func (*UtilsStruct) GetBlockIndexToBeConfirmed(ctx context.Context, client *ethclient.Client) (int8, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, BlockManagerInterface, "GetBlockIndexToBeConfirmed", client) if err != nil { return 0, err } return returnedValues[0].Interface().(int8), nil } -func (*UtilsStruct) GetEpochLastProposed(client *ethclient.Client, stakerId uint32) (uint32, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(BlockManagerInterface, "GetEpochLastProposed", client, stakerId) +func (*UtilsStruct) GetEpochLastProposed(ctx context.Context, client *ethclient.Client, stakerId uint32) (uint32, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, BlockManagerInterface, "GetEpochLastProposed", client, stakerId) if err != nil { return 0, err } diff --git a/utils/block_test.go b/utils/block_test.go index 54d8ec738..ba1d2c73b 100644 --- a/utils/block_test.go +++ b/utils/block_test.go @@ -1,6 +1,7 @@ package utils import ( + "context" "errors" "math/big" "razor/pkg/bindings" @@ -63,10 +64,10 @@ func TestFetchPreviousValue(t *testing.T) { } utils := StartRazor(optionsPackageStruct) - utilsMock.On("GetBlock", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.block, tt.args.blockErr) + 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(client, epoch, tt.args.assetId) + got, err := utils.FetchPreviousValue(context.Background(), client, epoch, tt.args.assetId) if (err != nil) != tt.wantErr { t.Errorf("FetchPreviousValue() error = %v, wantErr %v", err, tt.wantErr) return @@ -126,7 +127,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(client) + got, err := utils.GetMaxAltBlocks(context.Background(), client) if (err != nil) != tt.wantErr { t.Errorf("MaxAltBlocks() error = %v, wantErr %v", err, tt.wantErr) return @@ -186,7 +187,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(client) + got, err := utils.GetMinStakeAmount(context.Background(), client) if (err != nil) != tt.wantErr { t.Errorf("GetMinStakeAmount() error = %v, wantErr %v", err, tt.wantErr) return @@ -247,7 +248,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(client, epoch) + got, err := utils.GetNumberOfProposedBlocks(context.Background(), client, epoch) if (err != nil) != tt.wantErr { t.Errorf("GetNumberOfProposedBlocks() error = %v, wantErr %v", err, tt.wantErr) return @@ -313,7 +314,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(client, epoch, proposedBlockId) + got, err := utils.GetProposedBlock(context.Background(), client, epoch, proposedBlockId) if (err != nil) != tt.wantErr { t.Errorf("GetProposedBlock() error = %v, wantErr %v", err, tt.wantErr) return @@ -375,7 +376,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(client, epoch, index) + got, err := utils.GetSortedProposedBlockId(context.Background(), client, epoch, index) if (err != nil) != tt.wantErr { t.Errorf("GetSortedProposedBlockId() error = %v, wantErr %v", err, tt.wantErr) return @@ -439,10 +440,10 @@ func TestGetSortedProposedBlockIds(t *testing.T) { } utils := StartRazor(optionsPackageStruct) - utilsMock.On("GetNumberOfProposedBlocks", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.numOfProposedBlocks, tt.args.numOfProposedBlocksErr) - utilsMock.On("GetSortedProposedBlockId", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32"), mock.AnythingOfType("*big.Int")).Return(tt.args.sortedProposedBlockId, tt.args.sortedProposedBlockIdErr) + utilsMock.On("GetNumberOfProposedBlocks", mock.Anything, 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(client, epoch) + got, err := utils.GetSortedProposedBlockIds(context.Background(), client, epoch) if (err != nil) != tt.wantErr { t.Errorf("GetSortedProposedBlockIds() error = %v, wantErr %v", err, tt.wantErr) return @@ -525,7 +526,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(client, epoch) + got, err := utils.GetBlock(context.Background(), client, epoch) if (err != nil) != tt.wantErr { t.Errorf("GetBlock() error = %v, wantErr %v", err, tt.wantErr) return @@ -580,7 +581,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(client) + got, err := utils.GetBlockIndexToBeConfirmed(context.Background(), client) if (err != nil) != tt.wantErr { t.Errorf("GetBlockIndexToBeConfirmed() error = %v, wantErr %v", err, tt.wantErr) return @@ -635,7 +636,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(client) + got, err := utils.GetStateBuffer(context.Background(), client) if (err != nil) != tt.wantErr { t.Errorf("GetStateBuffer() error = %v, wantErr %v", err, tt.wantErr) return @@ -696,7 +697,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(client, stakerId) + got, err := utils.GetEpochLastProposed(context.Background(), client, stakerId) if (err != nil) != tt.wantErr { t.Errorf("GetEpochLastProposed() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/utils/client_methods.go b/utils/client_methods.go index e4b492501..b3537e322 100644 --- a/utils/client_methods.go +++ b/utils/client_methods.go @@ -11,17 +11,17 @@ import ( "razor/core" ) -func (*ClientStruct) GetNonceAtWithRetry(client *ethclient.Client, accountAddress common.Address) (uint64, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ClientInterface, "NonceAt", client, context.Background(), accountAddress) +func (*ClientStruct) GetNonceAtWithRetry(ctx context.Context, client *ethclient.Client, accountAddress common.Address) (uint64, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, ClientInterface, "NonceAt", client, context.Background(), accountAddress) if err != nil { return 0, err } return returnedValues[0].Interface().(uint64), nil } -func (*ClientStruct) GetLatestBlockWithRetry(client *ethclient.Client) (*types.Header, error) { +func (*ClientStruct) GetLatestBlockWithRetry(ctx context.Context, client *ethclient.Client) (*types.Header, error) { var blockNumberArgument *big.Int - returnedValues, err := InvokeFunctionWithRetryAttempts(ClientInterface, "HeaderByNumber", client, context.Background(), blockNumberArgument) + returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, ClientInterface, "HeaderByNumber", client, context.Background(), blockNumberArgument) if err != nil { return nil, err } @@ -68,17 +68,17 @@ func (*ClientStruct) EstimateGasWithRetry(client *ethclient.Client, message ethe return gasLimit, nil } -func (*ClientStruct) FilterLogsWithRetry(client *ethclient.Client, query ethereum.FilterQuery) ([]types.Log, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(ClientInterface, "FilterLogs", client, context.Background(), query) +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) if err != nil { return nil, err } return returnedValues[0].Interface().([]types.Log), nil } -func (*ClientStruct) BalanceAtWithRetry(client *ethclient.Client, account common.Address) (*big.Int, error) { +func (*ClientStruct) BalanceAtWithRetry(ctx context.Context, client *ethclient.Client, account common.Address) (*big.Int, error) { var blockNumberArgument *big.Int - returnedValues, err := InvokeFunctionWithRetryAttempts(ClientInterface, "BalanceAt", client, context.Background(), account, blockNumberArgument) + returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, ClientInterface, "BalanceAt", client, 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 ac879bb2d..352267b9e 100644 --- a/utils/client_methods_test.go +++ b/utils/client_methods_test.go @@ -120,7 +120,7 @@ func TestUtilsStruct_BalanceAtWithRetry(t *testing.T) { retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) clientUtils := ClientStruct{} - got, err := clientUtils.BalanceAtWithRetry(client, account) + got, err := clientUtils.BalanceAtWithRetry(context.Background(), client, account) if (err != nil) != tt.wantErr { t.Errorf("BalanceAtWithRetry() error = %v, wantErr %v", err, tt.wantErr) return @@ -235,7 +235,7 @@ func TestUtilsStruct_FilterLogsWithRetry(t *testing.T) { retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) clientUtils := ClientStruct{} - got, err := clientUtils.FilterLogsWithRetry(client, query) + got, err := clientUtils.FilterLogsWithRetry(context.Background(), client, query) if (err != nil) != tt.wantErr { t.Errorf("FilterLogsWithRetry() error = %v, wantErr %v", err, tt.wantErr) return @@ -291,7 +291,7 @@ func TestUtilsStruct_GetLatestBlockWithRetry(t *testing.T) { retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) clientUtils := ClientStruct{} - got, err := clientUtils.GetLatestBlockWithRetry(client) + got, err := clientUtils.GetLatestBlockWithRetry(context.Background(), client) if (err != nil) != tt.wantErr { t.Errorf("GetLatestBlockWithRetry() error = %v, wantErr %v", err, tt.wantErr) return @@ -348,7 +348,7 @@ func TestUtilsStruct_GetNonceAtWithRetry(t *testing.T) { retryMock.On("RetryAttempts", mock.AnythingOfType("uint")).Return(retry.Attempts(1)) clientUtils := ClientStruct{} - got, err := clientUtils.GetNonceAtWithRetry(client, accountAddress) + got, err := clientUtils.GetNonceAtWithRetry(context.Background(), client, accountAddress) if (err != nil) != tt.wantErr { t.Errorf("GetNonceAtWithRetry() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/utils/common.go b/utils/common.go index d329aac31..4a1e210b2 100644 --- a/utils/common.go +++ b/utils/common.go @@ -53,11 +53,7 @@ func (*UtilsStruct) FetchBalance(client *ethclient.Client, accountAddress string return balance, nil } -func (*UtilsStruct) GetBufferedState(client *ethclient.Client, header *Types.Header, buffer int32) (int64, error) { - stateBuffer, err := UtilsInterface.GetStateBuffer(client) - if err != nil { - return -1, err - } +func (*UtilsStruct) GetBufferedState(header *Types.Header, stateBuffer uint64, buffer int32) (int64, error) { lowerLimit := (core.StateLength * uint64(buffer)) / 100 upperLimit := core.StateLength - (core.StateLength*uint64(buffer))/100 if header.Time%(core.StateLength) > upperLimit-stateBuffer || header.Time%(core.StateLength) < lowerLimit+stateBuffer { @@ -132,8 +128,8 @@ func (*UtilsStruct) IsFlagPassed(name string) bool { return found } -func (*UtilsStruct) CheckEthBalanceIsZero(client *ethclient.Client, address string) { - ethBalance, err := ClientInterface.BalanceAtWithRetry(client, common.HexToAddress(address)) +func (*UtilsStruct) CheckEthBalanceIsZero(ctx context.Context, client *ethclient.Client, address string) { + ethBalance, err := ClientInterface.BalanceAtWithRetry(ctx, client, common.HexToAddress(address)) if err != nil { log.Fatalf("Error in fetching sFuel balance of the account: %s\n%s", address, err) } @@ -161,15 +157,15 @@ func GetStateName(stateNumber int64) string { return stateName } -func (*UtilsStruct) AssignStakerId(flagSet *pflag.FlagSet, client *ethclient.Client, address string) (uint32, error) { +func (*UtilsStruct) AssignStakerId(ctx context.Context, flagSet *pflag.FlagSet, client *ethclient.Client, address string) (uint32, error) { if UtilsInterface.IsFlagPassed("stakerId") { return UtilsInterface.GetUint32(flagSet, "stakerId") } - return UtilsInterface.GetStakerId(client, address) + return UtilsInterface.GetStakerId(ctx, client, address) } -func (*UtilsStruct) GetEpoch(client *ethclient.Client) (uint32, error) { - latestHeader, err := ClientInterface.GetLatestBlockWithRetry(client) +func (*UtilsStruct) GetEpoch(ctx context.Context, client *ethclient.Client) (uint32, error) { + latestHeader, err := ClientInterface.GetLatestBlockWithRetry(ctx, client) if err != nil { log.Error("Error in fetching block: ", err) return 0, err @@ -178,8 +174,8 @@ func (*UtilsStruct) GetEpoch(client *ethclient.Client) (uint32, error) { return uint32(epoch), nil } -func (*UtilsStruct) CalculateBlockTime(client *ethclient.Client) int64 { - latestBlock, err := ClientInterface.GetLatestBlockWithRetry(client) +func (*UtilsStruct) CalculateBlockTime(ctx context.Context, client *ethclient.Client) int64 { + latestBlock, err := ClientInterface.GetLatestBlockWithRetry(ctx, client) if err != nil { log.Fatalf("Error in fetching latest Block: %s", err) } @@ -191,15 +187,7 @@ func (*UtilsStruct) CalculateBlockTime(client *ethclient.Client) int64 { return int64(latestBlock.Time - lastSecondBlock.Time) } -func (*UtilsStruct) GetRemainingTimeOfCurrentState(client *ethclient.Client, bufferPercent int32) (int64, error) { - block, err := ClientInterface.GetLatestBlockWithRetry(client) - if err != nil { - return 0, err - } - stateBuffer, err := UtilsInterface.GetStateBuffer(client) - if err != nil { - return 0, err - } +func (*UtilsStruct) GetRemainingTimeOfCurrentState(block *Types.Header, stateBuffer uint64, bufferPercent int32) (int64, error) { timeRemaining := core.StateLength - (block.Time % core.StateLength) upperLimit := ((core.StateLength * uint64(bufferPercent)) / 100) + stateBuffer diff --git a/utils/common_test.go b/utils/common_test.go index ea5065190..ba01a3feb 100644 --- a/utils/common_test.go +++ b/utils/common_test.go @@ -1,6 +1,7 @@ package utils import ( + "context" "errors" "math/big" "os" @@ -112,12 +113,12 @@ func TestCalculateBlockTime(t *testing.T) { } utils := StartRazor(optionsPackageStruct) - clientUtilsMock.On("GetLatestBlockWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.latestBlock, tt.args.latestBlockErr) + 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) fatal = false - utils.CalculateBlockTime(client) + utils.CalculateBlockTime(context.Background(), client) if fatal != tt.expectedFatal { t.Error("The CalculateBlockTime function didn't execute as expected") } @@ -175,11 +176,11 @@ func TestCheckEthBalanceIsZero(t *testing.T) { } utils := StartRazor(optionsPackageStruct) - clientMock.On("BalanceAtWithRetry", mock.Anything, mock.Anything).Return(tt.args.ethBalance, tt.args.ethBalanceErr) + clientMock.On("BalanceAtWithRetry", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.ethBalance, tt.args.ethBalanceErr) fatal = false - utils.CheckEthBalanceIsZero(client, address) + utils.CheckEthBalanceIsZero(context.Background(), client, address) if fatal != tt.expectedFatal { t.Error("The CheckEthBalanceIsZero function didn't execute as expected") } @@ -362,13 +363,10 @@ func TestFetchBalance(t *testing.T) { } func TestGetBufferedState(t *testing.T) { - var client *ethclient.Client - type args struct { - block *types.Header - buffer int32 - stateBuffer uint64 - stateBufferErr error + block *types.Header + buffer int32 + stateBuffer uint64 } tests := []struct { name string @@ -414,36 +412,12 @@ func TestGetBufferedState(t *testing.T) { want: -1, wantErr: false, }, - { - name: "Test 4: When there is an error in getting stateBuffer", - args: args{ - block: &types.Header{ - Time: 100, - }, - buffer: 2, - stateBufferErr: errors.New("error in getting stateBuffer"), - }, - - want: -1, - wantErr: true, - }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + utils := StartRazor(OptionsPackageStruct{}) - utilsMock := new(mocks.Utils) - clientUtilsMock := new(mocks.ClientUtils) - - optionsPackageStruct := OptionsPackageStruct{ - UtilsInterface: utilsMock, - ClientInterface: clientUtilsMock, - } - - utils := StartRazor(optionsPackageStruct) - - utilsMock.On("GetStateBuffer", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.stateBuffer, tt.args.stateBufferErr) - - got, err := utils.GetBufferedState(client, tt.args.block, tt.args.buffer) + got, err := utils.GetBufferedState(tt.args.block, tt.args.stateBuffer, tt.args.buffer) if (err != nil) != tt.wantErr { t.Errorf("GetBufferedState() error = %v, wantErr %v", err, tt.wantErr) return @@ -499,9 +473,9 @@ func TestGetEpoch(t *testing.T) { } utils := StartRazor(optionsPackageStruct) - clientUtilsMock.On("GetLatestBlockWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.latestHeader, tt.args.latestHeaderErr) + clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything, mock.Anything).Return(tt.args.latestHeader, tt.args.latestHeaderErr) - got, err := utils.GetEpoch(client) + got, err := utils.GetEpoch(context.Background(), client) if (err != nil) != tt.wantErr { t.Errorf("GetEpoch() error = %v, wantErr %v", err, tt.wantErr) return @@ -856,11 +830,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.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.stakerId, tt.args.stakerIdErr) + utilsMock.On("GetStakerId", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) fatal = false - _, err := utils.AssignStakerId(flagSet, client, address) + _, err := utils.AssignStakerId(context.Background(), flagSet, client, address) if fatal != tt.expectedFatal { t.Error("The AssignStakerId function didn't execute as expected") } @@ -937,15 +911,10 @@ func TestAssignLogFile(t *testing.T) { } func TestGetRemainingTimeOfCurrentState(t *testing.T) { - var ( - client *ethclient.Client - bufferPercent int32 - ) type args struct { - block *types.Header - blockErr error - stateBuffer uint64 - stateBufferErr error + block *types.Header + stateBuffer uint64 + bufferPercent int32 } tests := []struct { name string @@ -962,38 +931,11 @@ func TestGetRemainingTimeOfCurrentState(t *testing.T) { want: 85, wantErr: false, }, - { - name: "Test 2: When there is an error in getting stateBuffer", - args: args{ - block: &types.Header{}, - stateBufferErr: errors.New("error in getting stateBuffer"), - }, - want: 0, - wantErr: true, - }, - { - name: "Test 3: When there is an error in getting block", - args: args{ - blockErr: errors.New("error in getting block"), - }, - want: 0, - wantErr: true, - }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - utilsMock := new(mocks.Utils) - clientUtilsMock := new(mocks.ClientUtils) - - optionsPackageStruct := OptionsPackageStruct{ - UtilsInterface: utilsMock, - ClientInterface: clientUtilsMock, - } - utils := StartRazor(optionsPackageStruct) - - utilsMock.On("GetStateBuffer", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.stateBuffer, tt.args.stateBufferErr) - clientUtilsMock.On("GetLatestBlockWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.block, tt.args.blockErr) - got, err := utils.GetRemainingTimeOfCurrentState(client, bufferPercent) + utils := StartRazor(OptionsPackageStruct{}) + got, err := utils.GetRemainingTimeOfCurrentState(tt.args.block, tt.args.stateBuffer, tt.args.bufferPercent) if (err != nil) != tt.wantErr { t.Errorf("GetRemainingTimeOfCurrentState() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/utils/interface.go b/utils/interface.go index cc7ee2274..2aa3177de 100644 --- a/utils/interface.go +++ b/utils/interface.go @@ -71,39 +71,39 @@ var GasInterface GasUtils type Utils interface { MultiplyFloatAndBigInt(bigIntVal *big.Int, floatingVal float64) *big.Int - GetTxnOpts(transactionData types.TransactionOptions) *bind.TransactOpts + GetTxnOpts(ctx context.Context, transactionData types.TransactionOptions) *bind.TransactOpts GetBlockManager(client *ethclient.Client) *bindings.BlockManager GetOptions() bind.CallOpts - GetNumberOfProposedBlocks(client *ethclient.Client, epoch uint32) (uint8, error) - GetSortedProposedBlockId(client *ethclient.Client, epoch uint32, index *big.Int) (uint32, error) - FetchPreviousValue(client *ethclient.Client, epoch uint32, assetId uint16) (*big.Int, error) - GetBlock(client *ethclient.Client, epoch uint32) (bindings.StructsBlock, error) - GetMaxAltBlocks(client *ethclient.Client) (uint8, error) - GetMinSafeRazor(client *ethclient.Client) (*big.Int, error) - GetMinStakeAmount(client *ethclient.Client) (*big.Int, error) - GetStateBuffer(client *ethclient.Client) (uint64, error) - GetProposedBlock(client *ethclient.Client, epoch uint32, proposedBlockId uint32) (bindings.StructsBlock, error) - GetSortedProposedBlockIds(client *ethclient.Client, epoch uint32) ([]uint32, error) - GetBlockIndexToBeConfirmed(client *ethclient.Client) (int8, error) + 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) GetBlockManagerWithOpts(client *ethclient.Client) (*bindings.BlockManager, bind.CallOpts) GetStakeManager(client *ethclient.Client) *bindings.StakeManager GetStakeManagerWithOpts(client *ethclient.Client) (*bindings.StakeManager, bind.CallOpts) - GetStaker(client *ethclient.Client, stakerId uint32) (bindings.StructsStaker, error) - GetStake(client *ethclient.Client, stakerId uint32) (*big.Int, error) - GetStakerId(client *ethclient.Client, address string) (uint32, error) - GetNumberOfStakers(client *ethclient.Client) (uint32, error) - GetLock(client *ethclient.Client, address string, stakerId uint32, lockType uint8) (types.Locks, error) - GetWithdrawInitiationPeriod(client *ethclient.Client) (uint16, error) - GetMaxCommission(client *ethclient.Client) (uint8, error) - GetEpochLimitForUpdateCommission(client *ethclient.Client) (uint16, error) + 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) GetVoteManagerWithOpts(client *ethclient.Client) (*bindings.VoteManager, bind.CallOpts) - GetCommitment(client *ethclient.Client, address string) (types.Commitment, error) - GetVoteValue(client *ethclient.Client, epoch uint32, stakerId uint32, medianIndex uint16) (*big.Int, error) - GetInfluenceSnapshot(client *ethclient.Client, stakerId uint32, epoch uint32) (*big.Int, error) - GetStakeSnapshot(client *ethclient.Client, stakerId uint32, epoch uint32) (*big.Int, error) - GetTotalInfluenceRevealed(client *ethclient.Client, epoch uint32, medianIndex uint16) (*big.Int, error) - GetEpochLastCommitted(client *ethclient.Client, stakerId uint32) (uint32, error) - GetEpochLastRevealed(client *ethclient.Client, stakerId uint32) (uint32, error) + 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) GetVoteManager(client *ethclient.Client) *bindings.VoteManager GetCollectionManager(client *ethclient.Client) *bindings.CollectionManager GetCollectionManagerWithOpts(client *ethclient.Client) (*bindings.CollectionManager, bind.CallOpts) @@ -111,27 +111,27 @@ type Utils interface { GetActiveJob(client *ethclient.Client, jobId uint16) (bindings.StructsJob, error) GetCollection(client *ethclient.Client, collectionId uint16) (bindings.StructsCollection, error) GetActiveCollection(collectionsCache *cache.CollectionsCache, collectionId uint16) (bindings.StructsCollection, error) - Aggregate(client *ethclient.Client, previousEpoch uint32, collection bindings.StructsCollection, commitParams *types.CommitParams) (*big.Int, error) + Aggregate(ctx context.Context, client *ethclient.Client, 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(client *ethclient.Client, numActiveCollections uint16, seed []byte) (map[int]bool, []*big.Int, error) + GetAssignedCollections(ctx context.Context, client *ethclient.Client, numActiveCollections uint16, seed []byte) (map[int]bool, []*big.Int, error) GetLeafIdOfACollection(client *ethclient.Client, collectionId uint16) (uint16, error) GetCollectionIdFromIndex(client *ethclient.Client, medianIndex uint16) (uint16, error) GetCollectionIdFromLeafId(client *ethclient.Client, leafId uint16) (uint16, error) GetNumActiveCollections(client *ethclient.Client) (uint16, error) - GetAggregatedDataOfCollection(client *ethclient.Client, collectionId uint16, epoch uint32, commitParams *types.CommitParams) (*big.Int, error) + GetAggregatedDataOfCollection(ctx context.Context, client *ethclient.Client, collectionId uint16, epoch uint32, commitParams *types.CommitParams) (*big.Int, error) GetJobs(client *ethclient.Client) ([]bindings.StructsJob, error) GetAllCollections(client *ethclient.Client) ([]bindings.StructsCollection, error) GetActiveCollectionIds(client *ethclient.Client) ([]uint16, error) HandleOfficialJobsFromJSONFile(client *ethclient.Client, 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) - GetBufferedState(client *ethclient.Client, header *Types.Header, buffer int32) (int64, error) + GetBufferedState(header *Types.Header, stateBuffer uint64, buffer int32) (int64, error) WaitForBlockCompletion(client *ethclient.Client, hashToRead string) error - CheckEthBalanceIsZero(client *ethclient.Client, address string) - AssignStakerId(flagSet *pflag.FlagSet, client *ethclient.Client, address string) (uint32, error) - GetEpoch(client *ethclient.Client) (uint32, error) - CalculateBlockTime(client *ethclient.Client) int64 + 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 IsFlagPassed(name string) bool GetTokenManager(client *ethclient.Client) *bindings.RAZOR GetStakedToken(client *ethclient.Client, tokenAddress common.Address) *bindings.StakedToken @@ -143,19 +143,19 @@ type Utils interface { AddJobToJSON(fileName string, job *types.StructsJob) error CheckTransactionReceipt(client *ethclient.Client, _txHash string) int CalculateSalt(epoch uint32, medians []*big.Int) [32]byte - ToAssign(client *ethclient.Client) (uint16, error) + ToAssign(ctx context.Context, client *ethclient.Client) (uint16, error) Prng(max uint32, prngHashes []byte) *big.Int - GetRemainingTimeOfCurrentState(client *ethclient.Client, bufferPercent int32) (int64, error) + 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(client *ethclient.Client, stakerId uint32) (uint32, error) + GetEpochLastProposed(ctx context.Context, client *ethclient.Client, stakerId uint32) (uint32, 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(client *ethclient.Client, staker bindings.StructsStaker) (*big.Int, error) + GetStakerSRZRBalance(ctx context.Context, client *ethclient.Client, staker bindings.StructsStaker) (*big.Int, error) CheckPassword(account types.Account) error AccountManagerForKeystore() (types.AccountManagerInterface, error) } @@ -174,10 +174,10 @@ type ClientUtils interface { FilterLogs(client *ethclient.Client, ctx context.Context, q ethereum.FilterQuery) ([]Types.Log, error) SuggestGasPriceWithRetry(client *ethclient.Client) (*big.Int, error) EstimateGasWithRetry(client *ethclient.Client, message ethereum.CallMsg) (uint64, error) - GetLatestBlockWithRetry(client *ethclient.Client) (*Types.Header, error) - FilterLogsWithRetry(client *ethclient.Client, query ethereum.FilterQuery) ([]Types.Log, error) - BalanceAtWithRetry(client *ethclient.Client, account common.Address) (*big.Int, error) - GetNonceAtWithRetry(client *ethclient.Client, accountAddress common.Address) (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) @@ -307,8 +307,8 @@ type FileUtils interface { type GasUtils interface { GetGasPrice(client *ethclient.Client, config types.Configurations) *big.Int - GetGasLimit(transactionData types.TransactionOptions, txnOpts *bind.TransactOpts) (uint64, error) - IncreaseGasLimitValue(client *ethclient.Client, gasLimit uint64, gasLimitMultiplier float32) (uint64, error) + 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) } type UtilsStruct struct{} diff --git a/utils/mocks/client_utils.go b/utils/mocks/client_utils.go index 73cdfe6ac..8d8d79081 100644 --- a/utils/mocks/client_utils.go +++ b/utils/mocks/client_utils.go @@ -53,25 +53,25 @@ func (_m *ClientUtils) BalanceAt(client *ethclient.Client, ctx context.Context, return r0, r1 } -// BalanceAtWithRetry provides a mock function with given fields: client, account -func (_m *ClientUtils) BalanceAtWithRetry(client *ethclient.Client, account common.Address) (*big.Int, error) { - ret := _m.Called(client, account) +// 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) 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(context.Context, *ethclient.Client, common.Address) (*big.Int, error)); ok { + return rf(ctx, client, account) } - if rf, ok := ret.Get(0).(func(*ethclient.Client, common.Address) *big.Int); ok { - r0 = rf(client, account) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, common.Address) *big.Int); ok { + r0 = rf(ctx, 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) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, common.Address) error); ok { + r1 = rf(ctx, client, account) } else { r1 = ret.Error(1) } @@ -205,25 +205,25 @@ func (_m *ClientUtils) FilterLogs(client *ethclient.Client, ctx context.Context, return r0, r1 } -// FilterLogsWithRetry provides a mock function with given fields: client, query -func (_m *ClientUtils) FilterLogsWithRetry(client *ethclient.Client, query ethereum.FilterQuery) ([]types.Log, error) { - ret := _m.Called(client, query) +// 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) var r0 []types.Log var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, ethereum.FilterQuery) ([]types.Log, error)); ok { - return rf(client, query) + 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(*ethclient.Client, ethereum.FilterQuery) []types.Log); ok { - r0 = rf(client, query) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, ethereum.FilterQuery) []types.Log); ok { + r0 = rf(ctx, client, query) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]types.Log) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, ethereum.FilterQuery) error); ok { - r1 = rf(client, query) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, ethereum.FilterQuery) error); ok { + r1 = rf(ctx, client, query) } else { r1 = ret.Error(1) } @@ -231,25 +231,25 @@ func (_m *ClientUtils) FilterLogsWithRetry(client *ethclient.Client, query ether return r0, r1 } -// GetLatestBlockWithRetry provides a mock function with given fields: client -func (_m *ClientUtils) GetLatestBlockWithRetry(client *ethclient.Client) (*types.Header, error) { - ret := _m.Called(client) +// 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) var r0 *types.Header var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client) (*types.Header, error)); ok { - return rf(client) + 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(*ethclient.Client) *types.Header); ok { - r0 = rf(client) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) *types.Header); ok { + r0 = rf(ctx, client) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*types.Header) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { - r1 = rf(client) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { + r1 = rf(ctx, client) } else { r1 = ret.Error(1) } @@ -257,23 +257,23 @@ func (_m *ClientUtils) GetLatestBlockWithRetry(client *ethclient.Client) (*types return r0, r1 } -// GetNonceAtWithRetry provides a mock function with given fields: client, accountAddress -func (_m *ClientUtils) GetNonceAtWithRetry(client *ethclient.Client, accountAddress common.Address) (uint64, error) { - ret := _m.Called(client, accountAddress) +// 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) var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, common.Address) (uint64, error)); ok { - return rf(client, accountAddress) + 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(*ethclient.Client, common.Address) uint64); ok { - r0 = rf(client, accountAddress) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, common.Address) uint64); ok { + r0 = rf(ctx, client, accountAddress) } else { r0 = ret.Get(0).(uint64) } - if rf, ok := ret.Get(1).(func(*ethclient.Client, common.Address) error); ok { - r1 = rf(client, accountAddress) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, common.Address) error); ok { + r1 = rf(ctx, client, accountAddress) } else { r1 = ret.Error(1) } diff --git a/utils/mocks/gas_utils.go b/utils/mocks/gas_utils.go index 59351797c..71803e058 100644 --- a/utils/mocks/gas_utils.go +++ b/utils/mocks/gas_utils.go @@ -1,11 +1,13 @@ -// Code generated by mockery v2.14.0. DO NOT EDIT. +// Code generated by mockery v2.30.1. DO NOT EDIT. package mocks import ( + context "context" big "math/big" bind "github.com/ethereum/go-ethereum/accounts/abi/bind" + ethclient "github.com/ethereum/go-ethereum/ethclient" mock "github.com/stretchr/testify/mock" @@ -18,20 +20,23 @@ type GasUtils struct { mock.Mock } -// GetGasLimit provides a mock function with given fields: transactionData, txnOpts -func (_m *GasUtils) GetGasLimit(transactionData types.TransactionOptions, txnOpts *bind.TransactOpts) (uint64, error) { - ret := _m.Called(transactionData, txnOpts) +// 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) var r0 uint64 - if rf, ok := ret.Get(0).(func(types.TransactionOptions, *bind.TransactOpts) uint64); ok { - r0 = rf(transactionData, txnOpts) + 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(context.Context, types.TransactionOptions, *bind.TransactOpts) uint64); ok { + r0 = rf(ctx, transactionData, txnOpts) } else { r0 = ret.Get(0).(uint64) } - var r1 error - if rf, ok := ret.Get(1).(func(types.TransactionOptions, *bind.TransactOpts) error); ok { - r1 = rf(transactionData, txnOpts) + if rf, ok := ret.Get(1).(func(context.Context, types.TransactionOptions, *bind.TransactOpts) error); ok { + r1 = rf(ctx, transactionData, txnOpts) } else { r1 = ret.Error(1) } @@ -55,20 +60,23 @@ func (_m *GasUtils) GetGasPrice(client *ethclient.Client, config types.Configura return r0 } -// IncreaseGasLimitValue provides a mock function with given fields: client, gasLimit, gasLimitMultiplier -func (_m *GasUtils) IncreaseGasLimitValue(client *ethclient.Client, gasLimit uint64, gasLimitMultiplier float32) (uint64, error) { - ret := _m.Called(client, gasLimit, gasLimitMultiplier) +// 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) var r0 uint64 - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint64, float32) uint64); ok { - r0 = rf(client, gasLimit, gasLimitMultiplier) + 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(context.Context, *ethclient.Client, uint64, float32) uint64); ok { + r0 = rf(ctx, client, gasLimit, gasLimitMultiplier) } else { r0 = ret.Get(0).(uint64) } - var r1 error - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint64, float32) error); ok { - r1 = rf(client, gasLimit, gasLimitMultiplier) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint64, float32) error); ok { + r1 = rf(ctx, client, gasLimit, gasLimitMultiplier) } else { r1 = ret.Error(1) } @@ -76,13 +84,12 @@ func (_m *GasUtils) IncreaseGasLimitValue(client *ethclient.Client, gasLimit uin return r0, r1 } -type mockConstructorTestingTNewGasUtils interface { +// NewGasUtils creates a new instance of GasUtils. 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 NewGasUtils(t interface { mock.TestingT Cleanup(func()) -} - -// NewGasUtils creates a new instance of GasUtils. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewGasUtils(t mockConstructorTestingTNewGasUtils) *GasUtils { +}) *GasUtils { mock := &GasUtils{} mock.Mock.Test(t) diff --git a/utils/mocks/utils.go b/utils/mocks/utils.go index 869a2fbcb..5b1455791 100644 --- a/utils/mocks/utils.go +++ b/utils/mocks/utils.go @@ -12,6 +12,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" @@ -68,25 +70,25 @@ func (_m *Utils) AddJobToJSON(fileName string, job *types.StructsJob) error { return r0 } -// Aggregate provides a mock function with given fields: client, previousEpoch, collection, commitParams -func (_m *Utils) Aggregate(client *ethclient.Client, previousEpoch uint32, collection bindings.StructsCollection, commitParams *types.CommitParams) (*big.Int, error) { - ret := _m.Called(client, previousEpoch, collection, commitParams) +// 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) var r0 *big.Int var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32, bindings.StructsCollection, *types.CommitParams) (*big.Int, error)); ok { - return rf(client, previousEpoch, collection, commitParams) + 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(*ethclient.Client, uint32, bindings.StructsCollection, *types.CommitParams) *big.Int); ok { - r0 = rf(client, previousEpoch, collection, commitParams) + 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) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32, bindings.StructsCollection, *types.CommitParams) error); ok { - r1 = rf(client, previousEpoch, collection, commitParams) + 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) } else { r1 = ret.Error(1) } @@ -108,23 +110,23 @@ func (_m *Utils) AssignPassword(flagSet *pflag.FlagSet) string { return r0 } -// AssignStakerId provides a mock function with given fields: flagSet, client, address -func (_m *Utils) AssignStakerId(flagSet *pflag.FlagSet, client *ethclient.Client, address string) (uint32, error) { - ret := _m.Called(flagSet, client, address) +// 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) var r0 uint32 var r1 error - if rf, ok := ret.Get(0).(func(*pflag.FlagSet, *ethclient.Client, string) (uint32, error)); ok { - return rf(flagSet, client, address) + 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(*pflag.FlagSet, *ethclient.Client, string) uint32); ok { - r0 = rf(flagSet, client, address) + if rf, ok := ret.Get(0).(func(context.Context, *pflag.FlagSet, *ethclient.Client, string) uint32); ok { + r0 = rf(ctx, flagSet, client, address) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(*pflag.FlagSet, *ethclient.Client, string) error); ok { - r1 = rf(flagSet, client, address) + if rf, ok := ret.Get(1).(func(context.Context, *pflag.FlagSet, *ethclient.Client, string) error); ok { + r1 = rf(ctx, flagSet, client, address) } else { r1 = ret.Error(1) } @@ -132,13 +134,13 @@ func (_m *Utils) AssignStakerId(flagSet *pflag.FlagSet, client *ethclient.Client return r0, r1 } -// CalculateBlockTime provides a mock function with given fields: client -func (_m *Utils) CalculateBlockTime(client *ethclient.Client) int64 { - ret := _m.Called(client) +// 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) var r0 int64 - if rf, ok := ret.Get(0).(func(*ethclient.Client) int64); ok { - r0 = rf(client) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) int64); ok { + r0 = rf(ctx, client) } else { r0 = ret.Get(0).(int64) } @@ -178,9 +180,9 @@ func (_m *Utils) CheckAmountAndBalance(amountInWei *big.Int, balance *big.Int) * return r0 } -// CheckEthBalanceIsZero provides a mock function with given fields: client, address -func (_m *Utils) CheckEthBalanceIsZero(client *ethclient.Client, address string) { - _m.Called(client, address) +// 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) } // CheckPassword provides a mock function with given fields: account @@ -293,25 +295,25 @@ func (_m *Utils) FetchBalance(client *ethclient.Client, accountAddress string) ( return r0, r1 } -// FetchPreviousValue provides a mock function with given fields: client, epoch, assetId -func (_m *Utils) FetchPreviousValue(client *ethclient.Client, epoch uint32, assetId uint16) (*big.Int, error) { - ret := _m.Called(client, epoch, assetId) +// 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) var r0 *big.Int var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32, uint16) (*big.Int, error)); ok { - return rf(client, epoch, assetId) + 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(*ethclient.Client, uint32, uint16) *big.Int); ok { - r0 = rf(client, epoch, assetId) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, uint16) *big.Int); ok { + r0 = rf(ctx, client, epoch, assetId) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32, uint16) error); ok { - r1 = rf(client, epoch, assetId) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32, uint16) error); ok { + r1 = rf(ctx, client, epoch, assetId) } else { r1 = ret.Error(1) } @@ -393,25 +395,25 @@ func (_m *Utils) GetActiveJob(client *ethclient.Client, jobId uint16) (bindings. return r0, r1 } -// GetAggregatedDataOfCollection provides a mock function with given fields: client, collectionId, epoch, commitParams -func (_m *Utils) GetAggregatedDataOfCollection(client *ethclient.Client, collectionId uint16, epoch uint32, commitParams *types.CommitParams) (*big.Int, error) { - ret := _m.Called(client, collectionId, epoch, commitParams) +// 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) var r0 *big.Int var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint16, uint32, *types.CommitParams) (*big.Int, error)); ok { - return rf(client, collectionId, epoch, commitParams) + 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(*ethclient.Client, uint16, uint32, *types.CommitParams) *big.Int); ok { - r0 = rf(client, 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) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint16, uint32, *types.CommitParams) error); ok { - r1 = rf(client, collectionId, epoch, commitParams) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint16, uint32, *types.CommitParams) error); ok { + r1 = rf(ctx, client, collectionId, epoch, commitParams) } else { r1 = ret.Error(1) } @@ -445,34 +447,34 @@ func (_m *Utils) GetAllCollections(client *ethclient.Client) ([]bindings.Structs return r0, r1 } -// GetAssignedCollections provides a mock function with given fields: client, numActiveCollections, seed -func (_m *Utils) GetAssignedCollections(client *ethclient.Client, numActiveCollections uint16, seed []byte) (map[int]bool, []*big.Int, error) { - ret := _m.Called(client, numActiveCollections, seed) +// 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) var r0 map[int]bool var r1 []*big.Int var r2 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint16, []byte) (map[int]bool, []*big.Int, error)); ok { - return rf(client, numActiveCollections, seed) + 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(*ethclient.Client, uint16, []byte) map[int]bool); ok { - r0 = rf(client, 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) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(map[int]bool) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint16, []byte) []*big.Int); ok { - r1 = rf(client, numActiveCollections, seed) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint16, []byte) []*big.Int); ok { + r1 = rf(ctx, client, numActiveCollections, seed) } else { if ret.Get(1) != nil { r1 = ret.Get(1).([]*big.Int) } } - if rf, ok := ret.Get(2).(func(*ethclient.Client, uint16, []byte) error); ok { - r2 = rf(client, numActiveCollections, seed) + if rf, ok := ret.Get(2).(func(context.Context, *ethclient.Client, uint16, []byte) error); ok { + r2 = rf(ctx, client, numActiveCollections, seed) } else { r2 = ret.Error(2) } @@ -480,23 +482,23 @@ func (_m *Utils) GetAssignedCollections(client *ethclient.Client, numActiveColle return r0, r1, r2 } -// GetBlock provides a mock function with given fields: client, epoch -func (_m *Utils) GetBlock(client *ethclient.Client, epoch uint32) (bindings.StructsBlock, error) { - ret := _m.Called(client, epoch) +// 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) var r0 bindings.StructsBlock var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32) (bindings.StructsBlock, error)); ok { - return rf(client, epoch) + 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(*ethclient.Client, uint32) bindings.StructsBlock); ok { - r0 = rf(client, epoch) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) bindings.StructsBlock); ok { + r0 = rf(ctx, client, epoch) } else { r0 = ret.Get(0).(bindings.StructsBlock) } - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32) error); ok { - r1 = rf(client, epoch) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32) error); ok { + r1 = rf(ctx, client, epoch) } else { r1 = ret.Error(1) } @@ -504,23 +506,23 @@ func (_m *Utils) GetBlock(client *ethclient.Client, epoch uint32) (bindings.Stru return r0, r1 } -// GetBlockIndexToBeConfirmed provides a mock function with given fields: client -func (_m *Utils) GetBlockIndexToBeConfirmed(client *ethclient.Client) (int8, error) { - ret := _m.Called(client) +// 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) var r0 int8 var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client) (int8, error)); ok { - return rf(client) + 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(*ethclient.Client) int8); ok { - r0 = rf(client) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) int8); ok { + r0 = rf(ctx, client) } else { r0 = ret.Get(0).(int8) } - if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { - r1 = rf(client) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { + r1 = rf(ctx, client) } else { r1 = ret.Error(1) } @@ -570,23 +572,23 @@ func (_m *Utils) GetBlockManagerWithOpts(client *ethclient.Client) (*bindings.Bl return r0, r1 } -// GetBufferedState provides a mock function with given fields: client, header, buffer -func (_m *Utils) GetBufferedState(client *ethclient.Client, header *coretypes.Header, buffer int32) (int64, error) { - ret := _m.Called(client, header, buffer) +// 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) var r0 int64 var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, *coretypes.Header, int32) (int64, error)); ok { - return rf(client, header, buffer) + if rf, ok := ret.Get(0).(func(*coretypes.Header, uint64, int32) (int64, error)); ok { + return rf(header, stateBuffer, buffer) } - if rf, ok := ret.Get(0).(func(*ethclient.Client, *coretypes.Header, int32) int64); ok { - r0 = rf(client, header, buffer) + if rf, ok := ret.Get(0).(func(*coretypes.Header, uint64, int32) int64); ok { + r0 = rf(header, stateBuffer, buffer) } else { r0 = ret.Get(0).(int64) } - if rf, ok := ret.Get(1).(func(*ethclient.Client, *coretypes.Header, int32) error); ok { - r1 = rf(client, header, buffer) + if rf, ok := ret.Get(1).(func(*coretypes.Header, uint64, int32) error); ok { + r1 = rf(header, stateBuffer, buffer) } else { r1 = ret.Error(1) } @@ -708,23 +710,23 @@ func (_m *Utils) GetCollectionManagerWithOpts(client *ethclient.Client) (*bindin return r0, r1 } -// GetCommitment provides a mock function with given fields: client, address -func (_m *Utils) GetCommitment(client *ethclient.Client, address string) (types.Commitment, error) { - ret := _m.Called(client, address) +// 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) var r0 types.Commitment var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, string) (types.Commitment, error)); ok { - return rf(client, address) + 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(*ethclient.Client, string) types.Commitment); ok { - r0 = rf(client, address) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, string) types.Commitment); ok { + r0 = rf(ctx, client, address) } else { r0 = ret.Get(0).(types.Commitment) } - if rf, ok := ret.Get(1).(func(*ethclient.Client, string) error); ok { - r1 = rf(client, address) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, string) error); ok { + r1 = rf(ctx, client, address) } else { r1 = ret.Error(1) } @@ -786,23 +788,23 @@ func (_m *Utils) GetDataToCommitFromJobs(jobs []bindings.StructsJob, commitParam return r0, r1 } -// GetEpoch provides a mock function with given fields: client -func (_m *Utils) GetEpoch(client *ethclient.Client) (uint32, error) { - ret := _m.Called(client) +// 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) 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(context.Context, *ethclient.Client) (uint32, error)); ok { + return rf(ctx, client) } - if rf, ok := ret.Get(0).(func(*ethclient.Client) uint32); ok { - r0 = rf(client) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) uint32); ok { + r0 = rf(ctx, client) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { - r1 = rf(client) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { + r1 = rf(ctx, client) } else { r1 = ret.Error(1) } @@ -810,23 +812,23 @@ func (_m *Utils) GetEpoch(client *ethclient.Client) (uint32, error) { return r0, r1 } -// GetEpochLastCommitted provides a mock function with given fields: client, stakerId -func (_m *Utils) GetEpochLastCommitted(client *ethclient.Client, stakerId uint32) (uint32, error) { - ret := _m.Called(client, stakerId) +// 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) var r0 uint32 var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32) (uint32, error)); ok { - return rf(client, stakerId) + 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(*ethclient.Client, uint32) uint32); ok { - r0 = rf(client, stakerId) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) uint32); ok { + r0 = rf(ctx, client, stakerId) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32) error); ok { - r1 = rf(client, stakerId) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32) error); ok { + r1 = rf(ctx, client, stakerId) } else { r1 = ret.Error(1) } @@ -834,23 +836,23 @@ func (_m *Utils) GetEpochLastCommitted(client *ethclient.Client, stakerId uint32 return r0, r1 } -// GetEpochLastProposed provides a mock function with given fields: client, stakerId -func (_m *Utils) GetEpochLastProposed(client *ethclient.Client, stakerId uint32) (uint32, error) { - ret := _m.Called(client, stakerId) +// 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) var r0 uint32 var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32) (uint32, error)); ok { - return rf(client, stakerId) + 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(*ethclient.Client, uint32) uint32); ok { - r0 = rf(client, stakerId) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) uint32); ok { + r0 = rf(ctx, client, stakerId) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32) error); ok { - r1 = rf(client, stakerId) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32) error); ok { + r1 = rf(ctx, client, stakerId) } else { r1 = ret.Error(1) } @@ -858,23 +860,23 @@ func (_m *Utils) GetEpochLastProposed(client *ethclient.Client, stakerId uint32) return r0, r1 } -// GetEpochLastRevealed provides a mock function with given fields: client, stakerId -func (_m *Utils) GetEpochLastRevealed(client *ethclient.Client, stakerId uint32) (uint32, error) { - ret := _m.Called(client, stakerId) +// 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) var r0 uint32 var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32) (uint32, error)); ok { - return rf(client, stakerId) + 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(*ethclient.Client, uint32) uint32); ok { - r0 = rf(client, stakerId) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) uint32); ok { + r0 = rf(ctx, client, stakerId) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32) error); ok { - r1 = rf(client, stakerId) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32) error); ok { + r1 = rf(ctx, client, stakerId) } else { r1 = ret.Error(1) } @@ -882,23 +884,23 @@ func (_m *Utils) GetEpochLastRevealed(client *ethclient.Client, stakerId uint32) return r0, r1 } -// GetEpochLimitForUpdateCommission provides a mock function with given fields: client -func (_m *Utils) GetEpochLimitForUpdateCommission(client *ethclient.Client) (uint16, error) { - ret := _m.Called(client) +// 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) 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(context.Context, *ethclient.Client) (uint16, error)); ok { + return rf(ctx, client) } - if rf, ok := ret.Get(0).(func(*ethclient.Client) uint16); ok { - r0 = rf(client) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) uint16); ok { + r0 = rf(ctx, client) } else { r0 = ret.Get(0).(uint16) } - if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { - r1 = rf(client) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { + r1 = rf(ctx, client) } else { r1 = ret.Error(1) } @@ -906,25 +908,25 @@ func (_m *Utils) GetEpochLimitForUpdateCommission(client *ethclient.Client) (uin return r0, r1 } -// GetInfluenceSnapshot provides a mock function with given fields: client, stakerId, epoch -func (_m *Utils) GetInfluenceSnapshot(client *ethclient.Client, stakerId uint32, epoch uint32) (*big.Int, error) { - ret := _m.Called(client, stakerId, epoch) +// 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) 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, stakerId, epoch) + 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(*ethclient.Client, uint32, uint32) *big.Int); ok { - r0 = rf(client, stakerId, epoch) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, uint32) *big.Int); ok { + r0 = rf(ctx, client, stakerId, epoch) } 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, stakerId, epoch) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32, uint32) error); ok { + r1 = rf(ctx, client, stakerId, epoch) } else { r1 = ret.Error(1) } @@ -982,23 +984,23 @@ func (_m *Utils) GetLeafIdOfACollection(client *ethclient.Client, collectionId u return r0, r1 } -// GetLock provides a mock function with given fields: client, address, stakerId, lockType -func (_m *Utils) GetLock(client *ethclient.Client, address string, stakerId uint32, lockType uint8) (types.Locks, error) { - ret := _m.Called(client, address, stakerId, lockType) +// 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) var r0 types.Locks var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, string, uint32, uint8) (types.Locks, error)); ok { - return rf(client, address, stakerId, lockType) + 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(*ethclient.Client, string, uint32, uint8) types.Locks); ok { - r0 = rf(client, 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) } else { r0 = ret.Get(0).(types.Locks) } - if rf, ok := ret.Get(1).(func(*ethclient.Client, string, uint32, uint8) error); ok { - r1 = rf(client, address, stakerId, lockType) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, string, uint32, uint8) error); ok { + r1 = rf(ctx, client, address, stakerId, lockType) } else { r1 = ret.Error(1) } @@ -1006,23 +1008,23 @@ func (_m *Utils) GetLock(client *ethclient.Client, address string, stakerId uint return r0, r1 } -// GetMaxAltBlocks provides a mock function with given fields: client -func (_m *Utils) GetMaxAltBlocks(client *ethclient.Client) (uint8, error) { - ret := _m.Called(client) +// 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) 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(context.Context, *ethclient.Client) (uint8, error)); ok { + return rf(ctx, client) } - if rf, ok := ret.Get(0).(func(*ethclient.Client) uint8); ok { - r0 = rf(client) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) uint8); ok { + r0 = rf(ctx, client) } else { r0 = ret.Get(0).(uint8) } - if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { - r1 = rf(client) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { + r1 = rf(ctx, client) } else { r1 = ret.Error(1) } @@ -1030,23 +1032,23 @@ func (_m *Utils) GetMaxAltBlocks(client *ethclient.Client) (uint8, error) { return r0, r1 } -// GetMaxCommission provides a mock function with given fields: client -func (_m *Utils) GetMaxCommission(client *ethclient.Client) (uint8, error) { - ret := _m.Called(client) +// 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) 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(context.Context, *ethclient.Client) (uint8, error)); ok { + return rf(ctx, client) } - if rf, ok := ret.Get(0).(func(*ethclient.Client) uint8); ok { - r0 = rf(client) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) uint8); ok { + r0 = rf(ctx, client) } else { r0 = ret.Get(0).(uint8) } - if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { - r1 = rf(client) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { + r1 = rf(ctx, client) } else { r1 = ret.Error(1) } @@ -1054,25 +1056,25 @@ func (_m *Utils) GetMaxCommission(client *ethclient.Client) (uint8, error) { return r0, r1 } -// GetMinSafeRazor provides a mock function with given fields: client -func (_m *Utils) GetMinSafeRazor(client *ethclient.Client) (*big.Int, error) { - ret := _m.Called(client) +// 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) 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(context.Context, *ethclient.Client) (*big.Int, error)); ok { + return rf(ctx, client) } - if rf, ok := ret.Get(0).(func(*ethclient.Client) *big.Int); ok { - r0 = rf(client) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) *big.Int); ok { + r0 = rf(ctx, client) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { - r1 = rf(client) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { + r1 = rf(ctx, client) } else { r1 = ret.Error(1) } @@ -1080,25 +1082,25 @@ func (_m *Utils) GetMinSafeRazor(client *ethclient.Client) (*big.Int, error) { return r0, r1 } -// GetMinStakeAmount provides a mock function with given fields: client -func (_m *Utils) GetMinStakeAmount(client *ethclient.Client) (*big.Int, error) { - ret := _m.Called(client) +// 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) 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(context.Context, *ethclient.Client) (*big.Int, error)); ok { + return rf(ctx, client) } - if rf, ok := ret.Get(0).(func(*ethclient.Client) *big.Int); ok { - r0 = rf(client) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) *big.Int); ok { + r0 = rf(ctx, client) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { - r1 = rf(client) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { + r1 = rf(ctx, client) } else { r1 = ret.Error(1) } @@ -1154,23 +1156,23 @@ func (_m *Utils) GetNumCollections(client *ethclient.Client) (uint16, error) { return r0, r1 } -// GetNumberOfProposedBlocks provides a mock function with given fields: client, epoch -func (_m *Utils) GetNumberOfProposedBlocks(client *ethclient.Client, epoch uint32) (uint8, error) { - ret := _m.Called(client, epoch) +// 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) var r0 uint8 var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32) (uint8, error)); ok { - return rf(client, epoch) + 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(*ethclient.Client, uint32) uint8); ok { - r0 = rf(client, epoch) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) uint8); ok { + r0 = rf(ctx, client, epoch) } else { r0 = ret.Get(0).(uint8) } - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32) error); ok { - r1 = rf(client, epoch) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32) error); ok { + r1 = rf(ctx, client, epoch) } else { r1 = ret.Error(1) } @@ -1178,23 +1180,23 @@ func (_m *Utils) GetNumberOfProposedBlocks(client *ethclient.Client, epoch uint3 return r0, r1 } -// GetNumberOfStakers provides a mock function with given fields: client -func (_m *Utils) GetNumberOfStakers(client *ethclient.Client) (uint32, error) { - ret := _m.Called(client) +// 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) 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(context.Context, *ethclient.Client) (uint32, error)); ok { + return rf(ctx, client) } - if rf, ok := ret.Get(0).(func(*ethclient.Client) uint32); ok { - r0 = rf(client) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) uint32); ok { + r0 = rf(ctx, client) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { - r1 = rf(client) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { + r1 = rf(ctx, client) } else { r1 = ret.Error(1) } @@ -1216,23 +1218,23 @@ func (_m *Utils) GetOptions() bind.CallOpts { return r0 } -// GetProposedBlock provides a mock function with given fields: client, epoch, proposedBlockId -func (_m *Utils) GetProposedBlock(client *ethclient.Client, epoch uint32, proposedBlockId uint32) (bindings.StructsBlock, error) { - ret := _m.Called(client, epoch, proposedBlockId) +// 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) var r0 bindings.StructsBlock var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32, uint32) (bindings.StructsBlock, error)); ok { - return rf(client, epoch, proposedBlockId) + 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(*ethclient.Client, uint32, uint32) bindings.StructsBlock); ok { - r0 = rf(client, epoch, proposedBlockId) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, uint32) bindings.StructsBlock); ok { + r0 = rf(ctx, client, epoch, proposedBlockId) } else { r0 = ret.Get(0).(bindings.StructsBlock) } - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32, uint32) error); ok { - r1 = rf(client, epoch, proposedBlockId) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32, uint32) error); ok { + r1 = rf(ctx, client, epoch, proposedBlockId) } else { r1 = ret.Error(1) } @@ -1240,23 +1242,23 @@ func (_m *Utils) GetProposedBlock(client *ethclient.Client, epoch uint32, propos return r0, r1 } -// GetRemainingTimeOfCurrentState provides a mock function with given fields: client, bufferPercent -func (_m *Utils) GetRemainingTimeOfCurrentState(client *ethclient.Client, bufferPercent int32) (int64, error) { - ret := _m.Called(client, bufferPercent) +// GetRemainingTimeOfCurrentState provides a mock function with given fields: block, stateBuffer, bufferPercent +func (_m *Utils) GetRemainingTimeOfCurrentState(block *coretypes.Header, stateBuffer uint64, bufferPercent int32) (int64, error) { + ret := _m.Called(block, stateBuffer, bufferPercent) var r0 int64 var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, int32) (int64, error)); ok { - return rf(client, bufferPercent) + if rf, ok := ret.Get(0).(func(*coretypes.Header, uint64, int32) (int64, error)); ok { + return rf(block, stateBuffer, bufferPercent) } - if rf, ok := ret.Get(0).(func(*ethclient.Client, int32) int64); ok { - r0 = rf(client, bufferPercent) + if rf, ok := ret.Get(0).(func(*coretypes.Header, uint64, int32) int64); ok { + r0 = rf(block, stateBuffer, bufferPercent) } else { r0 = ret.Get(0).(int64) } - if rf, ok := ret.Get(1).(func(*ethclient.Client, int32) error); ok { - r1 = rf(client, bufferPercent) + if rf, ok := ret.Get(1).(func(*coretypes.Header, uint64, int32) error); ok { + r1 = rf(block, stateBuffer, bufferPercent) } else { r1 = ret.Error(1) } @@ -1280,23 +1282,23 @@ func (_m *Utils) GetRogueRandomValue(value int) *big.Int { return r0 } -// GetSortedProposedBlockId provides a mock function with given fields: client, epoch, index -func (_m *Utils) GetSortedProposedBlockId(client *ethclient.Client, epoch uint32, index *big.Int) (uint32, error) { - ret := _m.Called(client, epoch, index) +// 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) var r0 uint32 var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32, *big.Int) (uint32, error)); ok { - return rf(client, epoch, index) + 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(*ethclient.Client, uint32, *big.Int) uint32); ok { - r0 = rf(client, epoch, index) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, *big.Int) uint32); ok { + r0 = rf(ctx, client, epoch, index) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32, *big.Int) error); ok { - r1 = rf(client, epoch, index) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32, *big.Int) error); ok { + r1 = rf(ctx, client, epoch, index) } else { r1 = ret.Error(1) } @@ -1304,25 +1306,25 @@ func (_m *Utils) GetSortedProposedBlockId(client *ethclient.Client, epoch uint32 return r0, r1 } -// GetSortedProposedBlockIds provides a mock function with given fields: client, epoch -func (_m *Utils) GetSortedProposedBlockIds(client *ethclient.Client, epoch uint32) ([]uint32, error) { - ret := _m.Called(client, epoch) +// 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) var r0 []uint32 var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32) ([]uint32, error)); ok { - return rf(client, epoch) + 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(*ethclient.Client, uint32) []uint32); ok { - r0 = rf(client, epoch) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) []uint32); ok { + r0 = rf(ctx, client, epoch) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]uint32) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32) error); ok { - r1 = rf(client, epoch) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32) error); ok { + r1 = rf(ctx, client, epoch) } else { r1 = ret.Error(1) } @@ -1330,25 +1332,25 @@ func (_m *Utils) GetSortedProposedBlockIds(client *ethclient.Client, epoch uint3 return r0, r1 } -// GetStake provides a mock function with given fields: client, stakerId -func (_m *Utils) GetStake(client *ethclient.Client, stakerId uint32) (*big.Int, error) { - ret := _m.Called(client, stakerId) +// 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) var r0 *big.Int var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32) (*big.Int, error)); ok { - return rf(client, stakerId) + 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(*ethclient.Client, uint32) *big.Int); ok { - r0 = rf(client, stakerId) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) *big.Int); ok { + r0 = rf(ctx, client, stakerId) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32) error); ok { - r1 = rf(client, stakerId) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32) error); ok { + r1 = rf(ctx, client, stakerId) } else { r1 = ret.Error(1) } @@ -1398,25 +1400,25 @@ func (_m *Utils) GetStakeManagerWithOpts(client *ethclient.Client) (*bindings.St return r0, r1 } -// GetStakeSnapshot provides a mock function with given fields: client, stakerId, epoch -func (_m *Utils) GetStakeSnapshot(client *ethclient.Client, stakerId uint32, epoch uint32) (*big.Int, error) { - ret := _m.Called(client, stakerId, epoch) +// 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) 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, stakerId, epoch) + 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(*ethclient.Client, uint32, uint32) *big.Int); ok { - r0 = rf(client, stakerId, epoch) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, uint32) *big.Int); ok { + r0 = rf(ctx, client, stakerId, epoch) } 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, stakerId, epoch) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32, uint32) error); ok { + r1 = rf(ctx, client, stakerId, epoch) } else { r1 = ret.Error(1) } @@ -1466,23 +1468,23 @@ func (_m *Utils) GetStakedTokenManagerWithOpts(client *ethclient.Client, tokenAd return r0, r1 } -// GetStaker provides a mock function with given fields: client, stakerId -func (_m *Utils) GetStaker(client *ethclient.Client, stakerId uint32) (bindings.StructsStaker, error) { - ret := _m.Called(client, stakerId) +// 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) 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(context.Context, *ethclient.Client, uint32) (bindings.StructsStaker, error)); ok { + return rf(ctx, client, stakerId) } - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32) bindings.StructsStaker); ok { - r0 = rf(client, stakerId) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32) bindings.StructsStaker); ok { + r0 = rf(ctx, client, stakerId) } else { r0 = ret.Get(0).(bindings.StructsStaker) } - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32) error); ok { - r1 = rf(client, stakerId) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32) error); ok { + r1 = rf(ctx, client, stakerId) } else { r1 = ret.Error(1) } @@ -1490,23 +1492,23 @@ func (_m *Utils) GetStaker(client *ethclient.Client, stakerId uint32) (bindings. return r0, r1 } -// GetStakerId provides a mock function with given fields: client, address -func (_m *Utils) GetStakerId(client *ethclient.Client, address string) (uint32, error) { - ret := _m.Called(client, address) +// 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) var r0 uint32 var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, string) (uint32, error)); ok { - return rf(client, address) + 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(*ethclient.Client, string) uint32); ok { - r0 = rf(client, address) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, string) uint32); ok { + r0 = rf(ctx, client, address) } else { r0 = ret.Get(0).(uint32) } - if rf, ok := ret.Get(1).(func(*ethclient.Client, string) error); ok { - r1 = rf(client, address) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, string) error); ok { + r1 = rf(ctx, client, address) } else { r1 = ret.Error(1) } @@ -1514,25 +1516,25 @@ func (_m *Utils) GetStakerId(client *ethclient.Client, address string) (uint32, return r0, r1 } -// GetStakerSRZRBalance provides a mock function with given fields: client, staker -func (_m *Utils) GetStakerSRZRBalance(client *ethclient.Client, staker bindings.StructsStaker) (*big.Int, error) { - ret := _m.Called(client, staker) +// 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) var r0 *big.Int var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, bindings.StructsStaker) (*big.Int, error)); ok { - return rf(client, staker) + 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(*ethclient.Client, bindings.StructsStaker) *big.Int); ok { - r0 = rf(client, staker) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, bindings.StructsStaker) *big.Int); ok { + r0 = rf(ctx, client, staker) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, bindings.StructsStaker) error); ok { - r1 = rf(client, staker) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, bindings.StructsStaker) error); ok { + r1 = rf(ctx, client, staker) } else { r1 = ret.Error(1) } @@ -1540,23 +1542,23 @@ func (_m *Utils) GetStakerSRZRBalance(client *ethclient.Client, staker bindings. return r0, r1 } -// GetStateBuffer provides a mock function with given fields: client -func (_m *Utils) GetStateBuffer(client *ethclient.Client) (uint64, error) { - ret := _m.Called(client) +// 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) var r0 uint64 var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client) (uint64, error)); ok { - return rf(client) + 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(*ethclient.Client) uint64); ok { - r0 = rf(client) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) uint64); ok { + r0 = rf(ctx, client) } else { r0 = ret.Get(0).(uint64) } - if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { - r1 = rf(client) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { + r1 = rf(ctx, client) } else { r1 = ret.Error(1) } @@ -1580,25 +1582,25 @@ func (_m *Utils) GetTokenManager(client *ethclient.Client) *bindings.RAZOR { return r0 } -// GetTotalInfluenceRevealed provides a mock function with given fields: client, epoch, medianIndex -func (_m *Utils) GetTotalInfluenceRevealed(client *ethclient.Client, epoch uint32, medianIndex uint16) (*big.Int, error) { - ret := _m.Called(client, epoch, medianIndex) +// 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) var r0 *big.Int var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32, uint16) (*big.Int, error)); ok { - return rf(client, epoch, medianIndex) + 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(*ethclient.Client, uint32, uint16) *big.Int); ok { - r0 = rf(client, epoch, medianIndex) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client, uint32, uint16) *big.Int); ok { + r0 = rf(ctx, client, epoch, medianIndex) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32, uint16) error); ok { - r1 = rf(client, epoch, medianIndex) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32, uint16) error); ok { + r1 = rf(ctx, client, epoch, medianIndex) } else { r1 = ret.Error(1) } @@ -1606,13 +1608,13 @@ func (_m *Utils) GetTotalInfluenceRevealed(client *ethclient.Client, epoch uint3 return r0, r1 } -// GetTxnOpts provides a mock function with given fields: transactionData -func (_m *Utils) GetTxnOpts(transactionData types.TransactionOptions) *bind.TransactOpts { - ret := _m.Called(transactionData) +// 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) var r0 *bind.TransactOpts - if rf, ok := ret.Get(0).(func(types.TransactionOptions) *bind.TransactOpts); ok { - r0 = rf(transactionData) + if rf, ok := ret.Get(0).(func(context.Context, types.TransactionOptions) *bind.TransactOpts); ok { + r0 = rf(ctx, transactionData) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*bind.TransactOpts) @@ -1688,25 +1690,25 @@ func (_m *Utils) GetVoteManagerWithOpts(client *ethclient.Client) (*bindings.Vot return r0, r1 } -// GetVoteValue provides a mock function with given fields: client, epoch, stakerId, medianIndex -func (_m *Utils) GetVoteValue(client *ethclient.Client, epoch uint32, stakerId uint32, medianIndex uint16) (*big.Int, error) { - ret := _m.Called(client, epoch, stakerId, medianIndex) +// 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) var r0 *big.Int var r1 error - if rf, ok := ret.Get(0).(func(*ethclient.Client, uint32, uint32, uint16) (*big.Int, error)); ok { - return rf(client, epoch, stakerId, medianIndex) + 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(*ethclient.Client, uint32, uint32, uint16) *big.Int); ok { - r0 = rf(client, 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) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*big.Int) } } - if rf, ok := ret.Get(1).(func(*ethclient.Client, uint32, uint32, uint16) error); ok { - r1 = rf(client, epoch, stakerId, medianIndex) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client, uint32, uint32, uint16) error); ok { + r1 = rf(ctx, client, epoch, stakerId, medianIndex) } else { r1 = ret.Error(1) } @@ -1714,23 +1716,23 @@ func (_m *Utils) GetVoteValue(client *ethclient.Client, epoch uint32, stakerId u return r0, r1 } -// GetWithdrawInitiationPeriod provides a mock function with given fields: client -func (_m *Utils) GetWithdrawInitiationPeriod(client *ethclient.Client) (uint16, error) { - ret := _m.Called(client) +// 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) 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(context.Context, *ethclient.Client) (uint16, error)); ok { + return rf(ctx, client) } - if rf, ok := ret.Get(0).(func(*ethclient.Client) uint16); ok { - r0 = rf(client) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) uint16); ok { + r0 = rf(ctx, client) } else { r0 = ret.Get(0).(uint16) } - if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { - r1 = rf(client) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { + r1 = rf(ctx, client) } else { r1 = ret.Error(1) } @@ -1880,23 +1882,23 @@ func (_m *Utils) SecondsToReadableTime(input int) string { return r0 } -// ToAssign provides a mock function with given fields: client -func (_m *Utils) ToAssign(client *ethclient.Client) (uint16, error) { - ret := _m.Called(client) +// 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) 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(context.Context, *ethclient.Client) (uint16, error)); ok { + return rf(ctx, client) } - if rf, ok := ret.Get(0).(func(*ethclient.Client) uint16); ok { - r0 = rf(client) + if rf, ok := ret.Get(0).(func(context.Context, *ethclient.Client) uint16); ok { + r0 = rf(ctx, client) } else { r0 = ret.Get(0).(uint16) } - if rf, ok := ret.Get(1).(func(*ethclient.Client) error); ok { - r1 = rf(client) + if rf, ok := ret.Get(1).(func(context.Context, *ethclient.Client) error); ok { + r1 = rf(ctx, client) } else { r1 = ret.Error(1) } diff --git a/utils/options.go b/utils/options.go index a92398895..90c7c466a 100644 --- a/utils/options.go +++ b/utils/options.go @@ -25,7 +25,7 @@ func (*UtilsStruct) GetOptions() bind.CallOpts { } } -func (*UtilsStruct) GetTxnOpts(transactionData types.TransactionOptions) *bind.TransactOpts { +func (*UtilsStruct) GetTxnOpts(ctx context.Context, transactionData types.TransactionOptions) *bind.TransactOpts { log.Debug("Getting transaction options...") account := transactionData.Account if account.AccountManager == nil { @@ -34,7 +34,7 @@ func (*UtilsStruct) GetTxnOpts(transactionData types.TransactionOptions) *bind.T privateKey, err := account.AccountManager.GetPrivateKey(account.Address, account.Password) CheckError("Error in fetching private key: ", err) - nonce, err := ClientInterface.GetNonceAtWithRetry(transactionData.Client, common.HexToAddress(account.Address)) + nonce, err := ClientInterface.GetNonceAtWithRetry(ctx, transactionData.Client, common.HexToAddress(account.Address)) CheckError("Error in fetching nonce: ", err) gasPrice := GasInterface.GetGasPrice(transactionData.Client, transactionData.Config) @@ -44,11 +44,11 @@ func (*UtilsStruct) GetTxnOpts(transactionData types.TransactionOptions) *bind.T txnOpts.GasPrice = gasPrice txnOpts.Value = transactionData.EtherValue - gasLimit, err := GasInterface.GetGasLimit(transactionData, txnOpts) + gasLimit, err := GasInterface.GetGasLimit(ctx, 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(transactionData.Client) + latestBlock, err := ClientInterface.GetLatestBlockWithRetry(ctx, transactionData.Client) CheckError("Error in fetching block: ", err) txnOpts.GasLimit = latestBlock.GasLimit @@ -86,7 +86,7 @@ func (*GasStruct) GetGasPrice(client *ethclient.Client, config types.Configurati return gasPrice } -func (*GasStruct) GetGasLimit(transactionData types.TransactionOptions, txnOpts *bind.TransactOpts) (uint64, error) { +func (*GasStruct) GetGasLimit(ctx context.Context, transactionData types.TransactionOptions, txnOpts *bind.TransactOpts) (uint64, error) { if transactionData.MethodName == "" { return 0, nil } @@ -110,7 +110,7 @@ func (*GasStruct) GetGasLimit(transactionData types.TransactionOptions, txnOpts } var gasLimit uint64 if transactionData.MethodName == "reveal" { - gasLimit, err = getGasLimitForReveal(transactionData.Client) + gasLimit, err = getGasLimitForReveal(ctx, transactionData.Client) if err != nil { log.Error("GetGasLimit: Error in getting gasLimit for reveal transaction: ", err) return transactionData.Config.GasLimitOverride, err @@ -126,17 +126,17 @@ func (*GasStruct) GetGasLimit(transactionData types.TransactionOptions, txnOpts } log.Debug("Estimated Gas: ", gasLimit) } - return GasInterface.IncreaseGasLimitValue(transactionData.Client, gasLimit, transactionData.Config.GasLimitMultiplier) + return GasInterface.IncreaseGasLimitValue(ctx, transactionData.Client, gasLimit, transactionData.Config.GasLimitMultiplier) } -func (*GasStruct) IncreaseGasLimitValue(client *ethclient.Client, gasLimit uint64, gasLimitMultiplier float32) (uint64, error) { +func (*GasStruct) IncreaseGasLimitValue(ctx context.Context, client *ethclient.Client, 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(client) + latestBlock, err := ClientInterface.GetLatestBlockWithRetry(ctx, client) if err != nil { log.Error("Error in fetching block: ", err) return 0, err @@ -149,8 +149,8 @@ func (*GasStruct) IncreaseGasLimitValue(client *ethclient.Client, gasLimit uint6 return gasLimit, nil } -func getGasLimitForReveal(client *ethclient.Client) (uint64, error) { - toAssign, err := UtilsInterface.ToAssign(client) +func getGasLimitForReveal(ctx context.Context, client *ethclient.Client) (uint64, error) { + toAssign, err := UtilsInterface.ToAssign(ctx, client) if err != nil { return 0, err } diff --git a/utils/options_test.go b/utils/options_test.go index 71628fbdd..babcdcd9a 100644 --- a/utils/options_test.go +++ b/utils/options_test.go @@ -291,13 +291,13 @@ func Test_utils_GetTxnOpts(t *testing.T) { utils := StartRazor(optionsPackageStruct) - clientMock.On("GetNonceAtWithRetry", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("common.Address")).Return(tt.args.nonce, tt.args.nonceErr) + clientMock.On("GetNonceAtWithRetry", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.nonce, tt.args.nonceErr) gasMock.On("GetGasPrice", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("types.Configurations")).Return(gasPrice) bindMock.On("NewKeyedTransactorWithChainID", mock.AnythingOfType("*ecdsa.PrivateKey"), mock.AnythingOfType("*big.Int")).Return(tt.args.txnOpts, tt.args.txnOptsErr) - gasMock.On("GetGasLimit", transactionData, txnOpts).Return(tt.args.gasLimit, tt.args.gasLimitErr) + gasMock.On("GetGasLimit", mock.Anything, transactionData, txnOpts).Return(tt.args.gasLimit, tt.args.gasLimitErr) clientMock.On("SuggestGasPriceWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(big.NewInt(1), nil) utilsMock.On("MultiplyFloatAndBigInt", mock.AnythingOfType("*big.Int"), mock.AnythingOfType("float64")).Return(big.NewInt(1)) - clientMock.On("GetLatestBlockWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.latestHeader, tt.args.latestHeaderErr) + clientMock.On("GetLatestBlockWithRetry", mock.Anything, 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() { @@ -319,7 +319,7 @@ func Test_utils_GetTxnOpts(t *testing.T) { } }() - got := utils.GetTxnOpts(transactionData) + got := utils.GetTxnOpts(context.Background(), transactionData) if !tt.expectedFatal && fatalOccurred { t.Fatalf("Test exited due to an unexpected fatal condition") } @@ -480,12 +480,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.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("ethereum.CallMsg")).Return(tt.args.gasLimit, tt.args.gasLimitErr) - gasUtilsMock.On("IncreaseGasLimitValue", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint64"), mock.AnythingOfType("float32")).Return(tt.args.increaseGasLimit, tt.args.increaseGasLimitErr) - utilsMock.On("ToAssign", 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, mock.Anything).Return(tt.args.increaseGasLimit, tt.args.increaseGasLimitErr) + utilsMock.On("ToAssign", mock.Anything, mock.Anything).Return(tt.args.toAssign, tt.args.toAssignErr) gasUtils := GasStruct{} - got, err := gasUtils.GetGasLimit(tt.args.transactionData, txnOpts) + got, err := gasUtils.GetGasLimit(context.Background(), tt.args.transactionData, txnOpts) if got != tt.want { t.Errorf("getGasLimit() got = %v, want %v", got, tt.want) } @@ -580,10 +580,10 @@ func TestUtilsStruct_IncreaseGasLimitValue(t *testing.T) { StartRazor(optionsPackageStruct) - clientUtilsMock.On("GetLatestBlockWithRetry", mock.AnythingOfType("*ethclient.Client")).Return(tt.args.latestBlock, tt.args.blockErr) + clientUtilsMock.On("GetLatestBlockWithRetry", mock.Anything, mock.Anything).Return(tt.args.latestBlock, tt.args.blockErr) gasUtils := GasStruct{} - got, err := gasUtils.IncreaseGasLimitValue(client, tt.args.gasLimit, tt.args.gasLimitMultiplier) + got, err := gasUtils.IncreaseGasLimitValue(context.Background(), client, 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 2e31ded35..c11a55a21 100644 --- a/utils/stake.go +++ b/utils/stake.go @@ -1,6 +1,7 @@ package utils import ( + "context" "math/big" "razor/core/types" "razor/pkg/bindings" @@ -14,16 +15,16 @@ func (*UtilsStruct) GetStakeManagerWithOpts(client *ethclient.Client) (*bindings return UtilsInterface.GetStakeManager(client), UtilsInterface.GetOptions() } -func (*UtilsStruct) GetStakerId(client *ethclient.Client, address string) (uint32, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(StakeManagerInterface, "GetStakerId", client, common.HexToAddress(address)) +func (*UtilsStruct) GetStakerId(ctx context.Context, client *ethclient.Client, address string) (uint32, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, StakeManagerInterface, "GetStakerId", client, common.HexToAddress(address)) if err != nil { return 0, err } return returnedValues[0].Interface().(uint32), nil } -func (*UtilsStruct) GetStake(client *ethclient.Client, stakerId uint32) (*big.Int, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(StakeManagerInterface, "GetStaker", client, stakerId) +func (*UtilsStruct) GetStake(ctx context.Context, client *ethclient.Client, stakerId uint32) (*big.Int, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, StakeManagerInterface, "GetStaker", client, stakerId) if err != nil { return nil, err } @@ -31,60 +32,60 @@ func (*UtilsStruct) GetStake(client *ethclient.Client, stakerId uint32) (*big.In return staker.Stake, nil } -func (*UtilsStruct) GetStaker(client *ethclient.Client, stakerId uint32) (bindings.StructsStaker, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(StakeManagerInterface, "GetStaker", client, stakerId) +func (*UtilsStruct) GetStaker(ctx context.Context, client *ethclient.Client, stakerId uint32) (bindings.StructsStaker, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, StakeManagerInterface, "GetStaker", client, stakerId) if err != nil { return bindings.StructsStaker{}, err } return returnedValues[0].Interface().(bindings.StructsStaker), nil } -func (*UtilsStruct) GetNumberOfStakers(client *ethclient.Client) (uint32, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(StakeManagerInterface, "GetNumStakers", client) +func (*UtilsStruct) GetNumberOfStakers(ctx context.Context, client *ethclient.Client) (uint32, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, StakeManagerInterface, "GetNumStakers", client) if err != nil { return 0, err } return returnedValues[0].Interface().(uint32), nil } -func (*UtilsStruct) GetLock(client *ethclient.Client, address string, stakerId uint32, lockType uint8) (types.Locks, error) { - staker, err := UtilsInterface.GetStaker(client, stakerId) +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) if err != nil { return types.Locks{}, err } - returnedValues, err := InvokeFunctionWithRetryAttempts(StakeManagerInterface, "Locks", client, common.HexToAddress(address), staker.TokenAddress, lockType) + returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, StakeManagerInterface, "Locks", client, common.HexToAddress(address), staker.TokenAddress, lockType) if err != nil { return types.Locks{}, err } return returnedValues[0].Interface().(types.Locks), nil } -func (*UtilsStruct) GetWithdrawInitiationPeriod(client *ethclient.Client) (uint16, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(StakeManagerInterface, "WithdrawInitiationPeriod", client) +func (*UtilsStruct) GetWithdrawInitiationPeriod(ctx context.Context, client *ethclient.Client) (uint16, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, StakeManagerInterface, "WithdrawInitiationPeriod", client) if err != nil { return 0, err } return returnedValues[0].Interface().(uint16), nil } -func (*UtilsStruct) GetMaxCommission(client *ethclient.Client) (uint8, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(StakeManagerInterface, "MaxCommission", client) +func (*UtilsStruct) GetMaxCommission(ctx context.Context, client *ethclient.Client) (uint8, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, StakeManagerInterface, "MaxCommission", client) if err != nil { return 0, err } return returnedValues[0].Interface().(uint8), nil } -func (*UtilsStruct) GetEpochLimitForUpdateCommission(client *ethclient.Client) (uint16, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(StakeManagerInterface, "EpochLimitForUpdateCommission", client) +func (*UtilsStruct) GetEpochLimitForUpdateCommission(ctx context.Context, client *ethclient.Client) (uint16, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, StakeManagerInterface, "EpochLimitForUpdateCommission", client) if err != nil { return 0, err } return returnedValues[0].Interface().(uint16), nil } -func (*UtilsStruct) GetMinSafeRazor(client *ethclient.Client) (*big.Int, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(StakeManagerInterface, "MinSafeRazor", client) +func (*UtilsStruct) GetMinSafeRazor(ctx context.Context, client *ethclient.Client) (*big.Int, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, StakeManagerInterface, "MinSafeRazor", client) if err != nil { return nil, err } diff --git a/utils/stake_test.go b/utils/stake_test.go index 142fde453..a78f12276 100644 --- a/utils/stake_test.go +++ b/utils/stake_test.go @@ -1,6 +1,7 @@ package utils import ( + "context" "errors" "math/big" "razor/core/types" @@ -63,7 +64,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(client) + got, err := utils.GetEpochLimitForUpdateCommission(context.Background(), client) if (err != nil) != tt.wantErr { t.Errorf("GetEpochLimitForUpdateCommission() error = %v, wantErr %v", err, tt.wantErr) return @@ -135,11 +136,11 @@ func TestGetLock(t *testing.T) { } utils := StartRazor(optionsPackageStruct) - utilsMock.On("GetStaker", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("uint32")).Return(tt.args.staker, tt.args.stakerErr) + utilsMock.On("GetStaker", mock.Anything, 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(client, address, stakerId, lockType) + got, err := utils.GetLock(context.Background(), client, address, stakerId, lockType) if (err != nil) != tt.wantErr { t.Errorf("GetLock() error = %v, wantErr %v", err, tt.wantErr) return @@ -197,7 +198,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(client) + got, err := utils.GetMaxCommission(context.Background(), client) if (err != nil) != tt.wantErr { t.Errorf("GetMaxCommission() error = %v, wantErr %v", err, tt.wantErr) return @@ -255,7 +256,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(client) + got, err := utils.GetNumberOfStakers(context.Background(), client) if (err != nil) != tt.wantErr { t.Errorf("GetNumberOfStakers() error = %v, wantErr %v", err, tt.wantErr) return @@ -314,7 +315,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(client, stakerId) + got, err := utils.GetStake(context.Background(), client, stakerId) if (err != nil) != tt.wantErr { t.Errorf("GetStake() error = %v, wantErr %v", err, tt.wantErr) return @@ -373,7 +374,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(client, stakerId) + got, err := utils.GetStaker(context.Background(), client, stakerId) if (err != nil) != tt.wantErr { t.Errorf("GetStaker() error = %v, wantErr %v", err, tt.wantErr) return @@ -432,7 +433,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(client, account) + got, err := utils.GetStakerId(context.Background(), client, account) if (err != nil) != tt.wantErr { t.Errorf("GetStakerId() error = %v, wantErr %v", err, tt.wantErr) return @@ -490,7 +491,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(client) + got, err := utils.GetWithdrawInitiationPeriod(context.Background(), client) if (err != nil) != tt.wantErr { t.Errorf("GetWithdrawInitiationPeriod() error = %v, wantErr %v", err, tt.wantErr) return @@ -569,7 +570,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(client) + got, err := utils.GetMinSafeRazor(context.Background(), client) if (err != nil) != tt.wantErr { t.Errorf("GetMinSafeRazor() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/utils/stakedToken.go b/utils/stakedToken.go index 9b0b69088..dabdab283 100644 --- a/utils/stakedToken.go +++ b/utils/stakedToken.go @@ -1,6 +1,7 @@ package utils import ( + "context" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" @@ -12,8 +13,8 @@ func (*UtilsStruct) GetStakedTokenManagerWithOpts(client *ethclient.Client, toke return UtilsInterface.GetStakedToken(client, tokenAddress), UtilsInterface.GetOptions() } -func (*UtilsStruct) GetStakerSRZRBalance(client *ethclient.Client, staker bindings.StructsStaker) (*big.Int, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(StakedTokenInterface, "BalanceOf", client, staker.TokenAddress, staker.Address) +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) 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 4440e9d0d..caa0e7fd4 100644 --- a/utils/stakedToken_test.go +++ b/utils/stakedToken_test.go @@ -1,6 +1,7 @@ package utils import ( + "context" "errors" "github.com/avast/retry-go" "github.com/ethereum/go-ethereum/ethclient" @@ -61,7 +62,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(client, staker) + got, err := utils.GetStakerSRZRBalance(context.Background(), client, 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 654bca816..5b25dc2f7 100644 --- a/utils/struct-utils.go +++ b/utils/struct-utils.go @@ -110,9 +110,10 @@ func CheckIfAnyError(result []reflect.Value) error { return nil } -func InvokeFunctionWithRetryAttempts(interfaceName interface{}, methodName string, args ...interface{}) ([]reflect.Value, error) { +func InvokeFunctionWithRetryAttempts(ctx context.Context, 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]) @@ -126,16 +127,31 @@ func InvokeFunctionWithRetryAttempts(interfaceName interface{}, methodName strin } err = retry.Do( func() error { - returnedValues = reflect.ValueOf(interfaceName).MethodByName(methodName).Call(inputs) - err = CheckIfAnyError(returnedValues) - if err != nil { - log.Debug("Function to retry: ", methodName) - log.Errorf("Error in %v....Retrying", methodName) - return err + // Check if the context has been cancelled or timed out + select { + case <-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()) + default: + // Proceed with the RPC call + returnedValues = reflect.ValueOf(interfaceName).MethodByName(methodName).Call(inputs) + err = CheckIfAnyError(returnedValues) + if err != nil { + log.Debug("Function to retry: ", methodName) + log.Errorf("Error in %v....Retrying", methodName) + return err + } + return nil } - return nil }, 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) + return returnedValues, err + } if !switchToAlternateClient && alternateProvider != "" { log.Errorf("%v error after retries: %v", methodName, err) log.Info("Switching RPC to alternate RPC") diff --git a/utils/vote.go b/utils/vote.go index b5d2f0616..7fb1531f8 100644 --- a/utils/vote.go +++ b/utils/vote.go @@ -1,6 +1,7 @@ package utils import ( + "context" "math/big" "razor/core/types" "razor/pkg/bindings" @@ -13,12 +14,12 @@ func (*UtilsStruct) GetVoteManagerWithOpts(client *ethclient.Client) (*bindings. return UtilsInterface.GetVoteManager(client), UtilsInterface.GetOptions() } -func (*UtilsStruct) GetCommitment(client *ethclient.Client, address string) (types.Commitment, error) { - stakerId, err := UtilsInterface.GetStakerId(client, address) +func (*UtilsStruct) GetCommitment(ctx context.Context, client *ethclient.Client, address string) (types.Commitment, error) { + stakerId, err := UtilsInterface.GetStakerId(ctx, client, address) if err != nil { return types.Commitment{}, err } - returnedValues, err := InvokeFunctionWithRetryAttempts(VoteManagerInterface, "GetCommitment", client, stakerId) + returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, VoteManagerInterface, "GetCommitment", client, stakerId) if err != nil { return types.Commitment{}, err } @@ -26,56 +27,56 @@ func (*UtilsStruct) GetCommitment(client *ethclient.Client, address string) (typ return commitment, nil } -func (*UtilsStruct) GetVoteValue(client *ethclient.Client, epoch uint32, stakerId uint32, medianIndex uint16) (*big.Int, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(VoteManagerInterface, "GetVoteValue", client, epoch, stakerId, medianIndex) +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) if err != nil { return big.NewInt(0), err } return returnedValues[0].Interface().(*big.Int), nil } -func (*UtilsStruct) GetInfluenceSnapshot(client *ethclient.Client, stakerId uint32, epoch uint32) (*big.Int, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(VoteManagerInterface, "GetInfluenceSnapshot", client, epoch, stakerId) +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) if err != nil { return nil, err } return returnedValues[0].Interface().(*big.Int), nil } -func (*UtilsStruct) GetStakeSnapshot(client *ethclient.Client, stakerId uint32, epoch uint32) (*big.Int, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(VoteManagerInterface, "GetStakeSnapshot", client, epoch, stakerId) +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) if err != nil { return nil, err } return returnedValues[0].Interface().(*big.Int), nil } -func (*UtilsStruct) GetTotalInfluenceRevealed(client *ethclient.Client, epoch uint32, medianIndex uint16) (*big.Int, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(VoteManagerInterface, "GetTotalInfluenceRevealed", client, epoch, medianIndex) +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) if err != nil { return nil, err } return returnedValues[0].Interface().(*big.Int), nil } -func (*UtilsStruct) GetEpochLastCommitted(client *ethclient.Client, stakerId uint32) (uint32, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(VoteManagerInterface, "GetEpochLastCommitted", client, stakerId) +func (*UtilsStruct) GetEpochLastCommitted(ctx context.Context, client *ethclient.Client, stakerId uint32) (uint32, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, VoteManagerInterface, "GetEpochLastCommitted", client, stakerId) if err != nil { return 0, err } return returnedValues[0].Interface().(uint32), nil } -func (*UtilsStruct) GetEpochLastRevealed(client *ethclient.Client, stakerId uint32) (uint32, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(VoteManagerInterface, "GetEpochLastRevealed", client, stakerId) +func (*UtilsStruct) GetEpochLastRevealed(ctx context.Context, client *ethclient.Client, stakerId uint32) (uint32, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, VoteManagerInterface, "GetEpochLastRevealed", client, stakerId) if err != nil { return 0, err } return returnedValues[0].Interface().(uint32), nil } -func (*UtilsStruct) ToAssign(client *ethclient.Client) (uint16, error) { - returnedValues, err := InvokeFunctionWithRetryAttempts(VoteManagerInterface, "ToAssign", client) +func (*UtilsStruct) ToAssign(ctx context.Context, client *ethclient.Client) (uint16, error) { + returnedValues, err := InvokeFunctionWithRetryAttempts(ctx, VoteManagerInterface, "ToAssign", client) if err != nil { return 0, err } diff --git a/utils/vote_test.go b/utils/vote_test.go index df90c568b..600bfe741 100644 --- a/utils/vote_test.go +++ b/utils/vote_test.go @@ -1,6 +1,7 @@ package utils import ( + "context" "errors" "math/big" "razor/core/types" @@ -74,11 +75,11 @@ func TestGetCommitments(t *testing.T) { utils := StartRazor(optionsPackageStruct) utilsMock.On("GetOptions").Return(callOpts) - utilsMock.On("GetStakerId", mock.AnythingOfType("*ethclient.Client"), mock.AnythingOfType("string")).Return(tt.args.stakerId, tt.args.stakerIdErr) + utilsMock.On("GetStakerId", mock.Anything, mock.Anything, mock.Anything).Return(tt.args.stakerId, tt.args.stakerIdErr) 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(client, address) + got, err := utils.GetCommitment(context.Background(), client, address) if (err != nil) != tt.wantErr { t.Errorf("GetCommitment() error = %v, wantErr %v", err, tt.wantErr) return @@ -139,7 +140,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(client, stakerId) + got, err := utils.GetEpochLastCommitted(context.Background(), client, stakerId) if (err != nil) != tt.wantErr { t.Errorf("GetEpochLastCommitted() error = %v, wantErr %v", err, tt.wantErr) return @@ -198,7 +199,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(client, stakerId) + got, err := utils.GetEpochLastRevealed(context.Background(), client, stakerId) if (err != nil) != tt.wantErr { t.Errorf("GetEpochLastRevealed() error = %v, wantErr %v", err, tt.wantErr) return @@ -260,7 +261,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(client, stakerId, epoch) + got, err := utils.GetInfluenceSnapshot(context.Background(), client, stakerId, epoch) if (err != nil) != tt.wantErr { t.Errorf("GetInfluenceSnapshot() error = %v, wantErr %v", err, tt.wantErr) return @@ -322,7 +323,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(client, stakerId, epoch) + got, err := utils.GetStakeSnapshot(context.Background(), client, stakerId, epoch) if (err != nil) != tt.wantErr { t.Errorf("GetStakeSnapshot() error = %v, wantErr %v", err, tt.wantErr) return @@ -386,7 +387,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(client, epoch, medianIndex) + got, err := utils.GetTotalInfluenceRevealed(context.Background(), client, epoch, medianIndex) if (err != nil) != tt.wantErr { t.Errorf("GetTotalInfluenceRevealed() error = %v, wantErr %v", err, tt.wantErr) return @@ -451,7 +452,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(client, epoch, stakerId, medianIndex) + got, err := utils.GetVoteValue(context.Background(), client, epoch, stakerId, medianIndex) if (err != nil) != tt.wantErr { t.Errorf("GetVoteValue() error = %v, wantErr %v", err, tt.wantErr) return @@ -530,7 +531,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(client) + got, err := utils.ToAssign(context.Background(), client) if (err != nil) != tt.wantErr { t.Errorf("ToAssign() error = %v, wantErr %v", err, tt.wantErr) return