From d9f444554bff64a85ac009a8cf6d5bf6f73d212a Mon Sep 17 00:00:00 2001 From: Austin Larson <78000745+alarso16@users.noreply.github.com> Date: Thu, 16 Oct 2025 05:59:34 -0400 Subject: [PATCH 01/19] style: Use require.ErrorIs whenever possible (#1303) --- .avalanche-golangci.yml | 10 +-- accounts/abi/abi_extra_test.go | 2 +- network/network.go | 3 +- network/network_test.go | 12 ++-- plugin/evm/config/config_test.go | 15 ++--- plugin/evm/log/log_test.go | 2 +- plugin/evm/vm_test.go | 65 +++++++------------ plugin/evm/vm_warp_test.go | 4 +- plugin/evm/wrapped_block.go | 4 +- .../allowlist/allowlisttest/test_allowlist.go | 49 +++++++------- .../allowlisttest/test_allowlist_config.go | 21 +++--- .../contracts/feemanager/config_test.go | 5 +- .../contracts/feemanager/contract_test.go | 17 ++--- .../contracts/nativeminter/config_test.go | 13 ++-- .../contracts/nativeminter/contract_test.go | 12 ++-- .../contracts/rewardmanager/config_test.go | 2 +- .../contracts/rewardmanager/contract_test.go | 18 ++--- precompile/contracts/warp/config.go | 5 +- precompile/contracts/warp/config_test.go | 7 +- precompile/contracts/warp/contract_test.go | 42 ++++++------ precompile/modules/registerer.go | 8 ++- precompile/modules/registerer_test.go | 4 +- precompile/precompiletest/test_config.go | 8 +-- precompile/precompiletest/test_precompile.go | 22 ++----- sync/client/client_test.go | 21 +++--- warp/backend.go | 6 +- warp/backend_test.go | 4 +- 27 files changed, 177 insertions(+), 204 deletions(-) diff --git a/.avalanche-golangci.yml b/.avalanche-golangci.yml index 12650b5146..f7a4de7f78 100644 --- a/.avalanche-golangci.yml +++ b/.avalanche-golangci.yml @@ -105,12 +105,12 @@ linters: forbidigo: # Forbid the following identifiers (list of regexp). forbid: - # - pattern: require\.Error$(# ErrorIs should be used instead)? - # - pattern: require\.ErrorContains$(# ErrorIs should be used instead)? - # - pattern: require\.EqualValues$(# Equal should be used instead)? - # - pattern: require\.NotEqualValues$(# NotEqual should be used instead)? + - pattern: require\.Error$(# ErrorIs should be used instead)? + - pattern: require\.ErrorContains$(# ErrorIs should be used instead)? + - pattern: require\.EqualValues$(# Equal should be used instead)? + - pattern: require\.NotEqualValues$(# NotEqual should be used instead)? - pattern: ^(t|b|tb|f)\.(Fatal|Fatalf|Error|Errorf)$(# the require library should be used instead)? - # - pattern: ^sort\.(Slice|Strings)$(# the slices package should be used instead)? + - pattern: ^sort\.(Slice|Strings)$(# the slices package should be used instead)? # Exclude godoc examples from forbidigo checks. exclude-godoc-examples: false gosec: diff --git a/accounts/abi/abi_extra_test.go b/accounts/abi/abi_extra_test.go index 37333ad02d..f8580747db 100644 --- a/accounts/abi/abi_extra_test.go +++ b/accounts/abi/abi_extra_test.go @@ -81,7 +81,7 @@ func TestUnpackInputIntoInterface(t *testing.T) { err = abi.UnpackInputIntoInterface(&v, "receive", data, test.strictMode) // skips 4 byte selector if test.expectedErrorSubstring != "" { - require.ErrorContains(t, err, test.expectedErrorSubstring) + require.ErrorContains(t, err, test.expectedErrorSubstring) //nolint:forbidigo // uses upstream code } else { require.NoError(t, err) require.Equal(t, input, v) diff --git a/network/network.go b/network/network.go index 219c8bbfa4..915d0a78bb 100644 --- a/network/network.go +++ b/network/network.go @@ -35,6 +35,7 @@ const ( var ( errAcquiringSemaphore = errors.New("error acquiring semaphore") + errEmptyNodeID = errors.New("cannot send request to empty nodeID") errExpiredRequest = errors.New("expired request") errNoPeersFound = errors.New("no peers found matching version") _ Network = (*network)(nil) @@ -191,7 +192,7 @@ func (n *network) SendAppRequestAny(ctx context.Context, minVersion *version.App // SendAppRequest sends request message bytes to specified nodeID, notifying the responseHandler on response or failure func (n *network) SendAppRequest(ctx context.Context, nodeID ids.NodeID, request []byte, responseHandler message.ResponseHandler) error { if nodeID == ids.EmptyNodeID { - return fmt.Errorf("cannot send request to empty nodeID, nodeID=%s, requestLen=%d", nodeID, len(request)) + return fmt.Errorf("%w, nodeID=%s, requestLen=%d", errEmptyNodeID, nodeID, len(request)) } // If the context was cancelled, we can skip sending this request. diff --git a/network/network_test.go b/network/network_test.go index 1608ca30ef..9ea30e9cdf 100644 --- a/network/network_test.go +++ b/network/network_test.go @@ -245,10 +245,8 @@ func TestRequestRequestsRoutingAndResponse(t *testing.T) { } // ensure empty nodeID is not allowed - require.ErrorContains(t, - net.SendAppRequest(t.Context(), ids.EmptyNodeID, []byte("hello there"), nil), - "cannot send request to empty nodeID", - ) + err = net.SendAppRequest(context.Background(), ids.EmptyNodeID, []byte("hello there"), nil) + require.ErrorIs(t, err, errEmptyNodeID) } func TestAppRequestOnShutdown(t *testing.T) { @@ -551,7 +549,8 @@ func TestNetworkPropagatesRequestHandlerError(t *testing.T) { ctx := snowtest.Context(t, snowtest.CChainID) clientNetwork, err := NewNetwork(ctx, sender, codecManager, 1, prometheus.NewRegistry()) require.NoError(t, err) - clientNetwork.SetRequestHandler(&testRequestHandler{err: errors.New("fail")}) // Return an error from the request handler + errTest := errors.New("test error") + clientNetwork.SetRequestHandler(&testRequestHandler{err: errTest}) // Return an error from the request handler require.NoError(t, clientNetwork.Connected(t.Context(), nodeID, defaultPeerVersion)) @@ -562,7 +561,8 @@ func TestNetworkPropagatesRequestHandlerError(t *testing.T) { require.NoError(t, err) // Check that if the request handler returns an error, it is propagated as a fatal error. - require.ErrorContains(t, clientNetwork.AppRequest(t.Context(), nodeID, requestID, time.Now().Add(time.Second), requestMessage), "fail") + err = clientNetwork.AppRequest(context.Background(), nodeID, requestID, time.Now().Add(time.Second), requestMessage) + require.ErrorIs(t, err, errTest) } func TestNetworkAppRequestAfterShutdown(t *testing.T) { diff --git a/plugin/evm/config/config_test.go b/plugin/evm/config/config_test.go index ac978d15da..1dc39abfb6 100644 --- a/plugin/evm/config/config_test.go +++ b/plugin/evm/config/config_test.go @@ -113,7 +113,7 @@ func TestUnmarshalConfig(t *testing.T) { var tmp Config err := json.Unmarshal(tt.givenJSON, &tmp) if tt.expectedErr { - require.Error(t, err) + require.Error(t, err) //nolint:forbidigo // uses standard library } else { require.NoError(t, err) tmp.deprecate() @@ -125,11 +125,10 @@ func TestUnmarshalConfig(t *testing.T) { func TestGetConfig(t *testing.T) { tests := []struct { - name string - configJSON []byte - networkID uint32 - expected func(*testing.T, Config) - expectError bool + name string + configJSON []byte + networkID uint32 + expected func(*testing.T, Config) }{ { name: "custom config values", @@ -164,10 +163,6 @@ func TestGetConfig(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { config, _, err := GetConfig(tt.configJSON, tt.networkID) - if tt.expectError { - require.Error(t, err) - return - } require.NoError(t, err) tt.expected(t, config) }) diff --git a/plugin/evm/log/log_test.go b/plugin/evm/log/log_test.go index 202c4fdfa6..780fe507b8 100644 --- a/plugin/evm/log/log_test.go +++ b/plugin/evm/log/log_test.go @@ -28,7 +28,7 @@ func TestInitLogger(t *testing.T) { require := require.New(t) _, err := InitLogger("alias", test.logLevel, true, os.Stderr) if test.expectedErr { - require.ErrorContains(err, "unknown level") + require.ErrorContains(err, "unknown level") //nolint:forbidigo // uses upstream code } else { require.NoError(err) } diff --git a/plugin/evm/vm_test.go b/plugin/evm/vm_test.go index 2679d4c047..c1f2213600 100644 --- a/plugin/evm/vm_test.go +++ b/plugin/evm/vm_test.go @@ -765,11 +765,10 @@ func testReorgProtection(t *testing.T, scheme string) { // with the preferred chain lower than the last finalized block) // should NEVER happen. However, the VM defends against this // just in case. - err = vm1.SetPreference(t.Context(), vm1BlkC.ID()) - require.ErrorContains(t, err, "cannot orphan finalized block", "Expected error when setting preference that would orphan finalized block") - - err = vm1BlkC.Accept(t.Context()) - require.ErrorContains(t, err, "expected accepted block to have parent", "Expected error when accepting orphaned block") + err = vm1.SetPreference(t.Context(), vm1BlkC.ID()) //nolint:forbidigo // uses upstream code + require.ErrorContains(t, err, "cannot orphan finalized block") //nolint:forbidigo // uses upstream code + err = vm1BlkC.Accept(t.Context()) //nolint:forbidigo // uses upstream code + require.ErrorContains(t, err, "expected accepted block to have parent") } // Regression test to ensure that a VM that accepts block C while preferring @@ -1088,7 +1087,8 @@ func testStickyPreference(t *testing.T, scheme string) { require.Equal(t, blkDHash, vm1.blockChain.CurrentBlock().Hash(), "expected current block to have hash %s but got %s", blkDHash.Hex(), vm1.blockChain.CurrentBlock().Hash().Hex()) // Attempt to accept out of order - require.ErrorContains(t, vm1BlkD.Accept(t.Context()), "expected accepted block to have parent", "unexpected error when accepting out of order block") + err = vm1BlkD.Accept(t.Context()) + require.ErrorContains(t, err, "expected accepted block to have parent") //nolint:forbidigo // uses upstream code // Accept in order require.NoError(t, vm1BlkC.Accept(t.Context()), "Block failed verification on VM1") @@ -2572,7 +2572,8 @@ func TestSkipChainConfigCheckCompatible(t *testing.T) { tvm.vm.ctx.Metrics = metrics.NewPrefixGatherer() // this will not be allowed - require.ErrorContains(t, reinitVM.Initialize(t.Context(), tvm.vm.ctx, tvm.db, genesisWithUpgradeBytes, []byte{}, []byte{}, []*commonEng.Fx{}, tvm.appSender), "mismatching Cancun fork timestamp in database") + err = reinitVM.Initialize(t.Context(), tvm.vm.ctx, tvm.db, genesisWithUpgradeBytes, []byte{}, []byte{}, []*commonEng.Fx{}, tvm.appSender) + require.ErrorContains(t, err, "mismatching Cancun fork timestamp in database") //nolint:forbidigo // uses upstream code // Reset metrics to allow re-initialization tvm.vm.ctx.Metrics = metrics.NewPrefixGatherer() @@ -2588,47 +2589,41 @@ func TestParentBeaconRootBlock(t *testing.T) { name string fork upgradetest.Fork beaconRoot *common.Hash - expectedError bool - errString string + expectedError error }{ { name: "non-empty parent beacon root in Durango", fork: upgradetest.Durango, beaconRoot: &common.Hash{0x01}, - expectedError: true, - // err string wont work because it will also fail with blob gas is non-empty (zeroed) + expectedError: errInvalidParentBeaconRootBeforeCancun, }, { name: "empty parent beacon root in Durango", fork: upgradetest.Durango, beaconRoot: &common.Hash{}, - expectedError: true, + expectedError: errInvalidParentBeaconRootBeforeCancun, }, { - name: "nil parent beacon root in Durango", - fork: upgradetest.Durango, - beaconRoot: nil, - expectedError: false, + name: "nil parent beacon root in Durango", + fork: upgradetest.Durango, + beaconRoot: nil, }, { name: "non-empty parent beacon root in E-Upgrade (Cancun)", fork: upgradetest.Etna, beaconRoot: &common.Hash{0x01}, - expectedError: true, - errString: "expected empty hash", + expectedError: errParentBeaconRootNonEmpty, }, { - name: "empty parent beacon root in E-Upgrade (Cancun)", - fork: upgradetest.Etna, - beaconRoot: &common.Hash{}, - expectedError: false, + name: "empty parent beacon root in E-Upgrade (Cancun)", + fork: upgradetest.Etna, + beaconRoot: &common.Hash{}, }, { name: "nil parent beacon root in E-Upgrade (Cancun)", fork: upgradetest.Etna, beaconRoot: nil, - expectedError: true, - errString: "header is missing parentBeaconRoot", + expectedError: errMissingParentBeaconRoot, }, } @@ -2667,22 +2662,10 @@ func TestParentBeaconRootBlock(t *testing.T) { parentBeaconBlock, err := wrapBlock(parentBeaconEthBlock, tvm.vm) require.NoError(t, err) - errCheck := func(err error) { - if test.expectedError { - if test.errString != "" { - require.ErrorContains(t, err, test.errString) - } else { - require.Error(t, err) - } - } else { - require.NoError(t, err) - } - } - - _, err = tvm.vm.ParseBlock(t.Context(), parentBeaconBlock.Bytes()) - errCheck(err) - err = parentBeaconBlock.Verify(t.Context()) - errCheck(err) + _, err = tvm.vm.ParseBlock(context.Background(), parentBeaconBlock.Bytes()) + require.ErrorIs(t, err, test.expectedError) + err = parentBeaconBlock.Verify(context.Background()) + require.ErrorIs(t, err, test.expectedError) }) } } @@ -3264,7 +3247,7 @@ func TestCreateHandlers(t *testing.T) { }) } require.NoError(t, client.BatchCall(batch)) - require.ErrorContains(t, batch[0].Error, "batch too large") + require.ErrorContains(t, batch[0].Error, "batch too large") //nolint:forbidigo // uses upstream code // All other elements should have an error indicating there's no response for _, elem := range batch[1:] { diff --git a/plugin/evm/vm_warp_test.go b/plugin/evm/vm_warp_test.go index 6a6d24cedf..0b269f4948 100644 --- a/plugin/evm/vm_warp_test.go +++ b/plugin/evm/vm_warp_test.go @@ -157,9 +157,9 @@ func testSendWarpMessage(t *testing.T, scheme string) { // Verify the signature cannot be fetched before the block is accepted _, err = tvm.vm.warpBackend.GetMessageSignature(t.Context(), unsignedMessage) - require.ErrorContains(err, "unknown codec version") + require.ErrorIs(err, warp.ErrVerifyWarpMessage) _, err = tvm.vm.warpBackend.GetBlockSignature(t.Context(), blk.ID()) - require.ErrorContains(err, "failed to get block") + require.ErrorIs(err, warp.ErrValidateBlock) require.NoError(tvm.vm.SetPreference(t.Context(), blk.ID())) require.NoError(blk.Accept(t.Context())) diff --git a/plugin/evm/wrapped_block.go b/plugin/evm/wrapped_block.go index 4fb4ab76de..1215c2b2a4 100644 --- a/plugin/evm/wrapped_block.go +++ b/plugin/evm/wrapped_block.go @@ -410,12 +410,12 @@ func (b *wrappedBlock) syntacticVerify() error { } } else { switch { + case ethHeader.ParentBeaconRoot != nil: + return fmt.Errorf("%w: have %x, expected nil", errInvalidParentBeaconRootBeforeCancun, *ethHeader.ParentBeaconRoot) case ethHeader.ExcessBlobGas != nil: return fmt.Errorf("%w: have %d, expected nil", errInvalidExcessBlobGasBeforeCancun, *ethHeader.ExcessBlobGas) case ethHeader.BlobGasUsed != nil: return fmt.Errorf("%w: have %d, expected nil", errInvalidBlobGasUsedBeforeCancun, *ethHeader.BlobGasUsed) - case ethHeader.ParentBeaconRoot != nil: - return fmt.Errorf("%w: have %x, expected nil", errInvalidParentBeaconRootBeforeCancun, *ethHeader.ParentBeaconRoot) } } diff --git a/precompile/allowlist/allowlisttest/test_allowlist.go b/precompile/allowlist/allowlisttest/test_allowlist.go index 6f5209af1e..b22194c71b 100644 --- a/precompile/allowlist/allowlisttest/test_allowlist.go +++ b/precompile/allowlist/allowlisttest/test_allowlist.go @@ -4,6 +4,7 @@ package allowlisttest import ( + "errors" "testing" "github.com/ava-labs/libevm/common" @@ -105,7 +106,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList.Error(), + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "no_role_set_enabled", @@ -119,7 +120,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList.Error(), + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "no_role_set_admin", @@ -133,7 +134,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList.Error(), + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "enabled_set_no_role", @@ -147,7 +148,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList.Error(), + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "enabled_set_enabled", @@ -161,7 +162,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList.Error(), + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "enabled_set_admin", @@ -175,7 +176,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList.Error(), + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "no_role_set_manager_pre_Durango", @@ -194,7 +195,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: 0, ReadOnly: false, - ExpectedErr: "invalid non-activated function selector", + ExpectedErr: errors.New("invalid non-activated function selector"), }, { Name: "no_role_set_manager", @@ -213,7 +214,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList.Error(), + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "enabled_role_set_manager_pre_Durango", @@ -232,7 +233,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: 0, ReadOnly: false, - ExpectedErr: "invalid non-activated function selector", + ExpectedErr: errors.New("invalid non-activated function selector"), }, { Name: "enabled_set_manager", @@ -251,7 +252,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList.Error(), + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "admin_set_manager_pre_Durango", @@ -270,7 +271,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: 0, ReadOnly: false, - ExpectedErr: "invalid non-activated function selector", + ExpectedErr: errors.New("invalid non-activated function selector"), }, { Name: "admin_set_manager", @@ -311,7 +312,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom SuppliedGas: allowlist.ModifyAllowListGasCost + allowlist.AllowListEventGasCost, ReadOnly: false, ExpectedRes: []byte{}, - ExpectedErr: "", + ExpectedErr: nil, AfterHook: func(t testing.TB, state *extstate.StateDB) { res := allowlist.GetAllowListStatus(state, contractAddress, TestNoRoleAddr) require.Equal(t, allowlist.NoRole, res) @@ -333,7 +334,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom SuppliedGas: allowlist.ModifyAllowListGasCost + allowlist.AllowListEventGasCost, ReadOnly: false, ExpectedRes: []byte{}, - ExpectedErr: "", + ExpectedErr: nil, AfterHook: func(t testing.TB, state *extstate.StateDB) { res := allowlist.GetAllowListStatus(state, contractAddress, TestNoRoleAddr) require.Equal(t, allowlist.EnabledRole, res) @@ -360,7 +361,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList.Error(), + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "manager_set_no_role_to_admin", @@ -374,7 +375,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList.Error(), + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "manager_set_enabled_to_admin", @@ -388,7 +389,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList.Error(), + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "manager_set_enabled_role_to_manager", @@ -407,7 +408,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList.Error(), + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "manager_set_enabled_role_to_no_role", @@ -443,7 +444,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList.Error(), + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "manager_set_admin_role_to_enabled", @@ -457,7 +458,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList.Error(), + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "manager_set_admin_to_manager", @@ -476,7 +477,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList.Error(), + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "manager_set_manager_to_no_role", @@ -490,7 +491,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList.Error(), + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "admin_set_no_role_with_readOnly_enabled", @@ -504,7 +505,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection.Error(), + ExpectedErr: vm.ErrWriteProtection, }, { Name: "admin_set_no_role_insufficient_gas", @@ -518,7 +519,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas.Error(), + ExpectedErr: vm.ErrOutOfGas, }, { Name: "no_role_read_allow_list", @@ -571,7 +572,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom return input }, SuppliedGas: allowlist.ReadAllowListGasCost - 1, ReadOnly: true, - ExpectedErr: vm.ErrOutOfGas.Error(), + ExpectedErr: vm.ErrOutOfGas, }, { Name: "initial_config_sets_admins", diff --git a/precompile/allowlist/allowlisttest/test_allowlist_config.go b/precompile/allowlist/allowlisttest/test_allowlist_config.go index 8738db0d40..c9a3a1c323 100644 --- a/precompile/allowlist/allowlisttest/test_allowlist_config.go +++ b/precompile/allowlist/allowlisttest/test_allowlist_config.go @@ -5,6 +5,7 @@ package allowlisttest import ( "encoding/json" + "errors" "testing" "github.com/ava-labs/libevm/common" @@ -57,7 +58,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: nil, EnabledAddresses: nil, }), - ExpectedError: "duplicate address in admin list", + ExpectedError: errors.New("duplicate address in admin list"), }, "invalid allow list config with duplicate enableds in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -65,7 +66,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: nil, EnabledAddresses: []common.Address{TestEnabledAddr, TestEnabledAddr}, }), - ExpectedError: "duplicate address in enabled list", + ExpectedError: errors.New("duplicate address in enabled list"), }, "invalid allow list config with duplicate managers in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -73,7 +74,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: []common.Address{TestManagerAddr, TestManagerAddr}, EnabledAddresses: nil, }), - ExpectedError: "duplicate address in manager list", + ExpectedError: errors.New("duplicate address in manager list"), }, "invalid allow list config with same admin and enabled in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -81,7 +82,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: nil, EnabledAddresses: []common.Address{TestAdminAddr}, }), - ExpectedError: "cannot set address as both admin and enabled", + ExpectedError: errors.New("cannot set address as both admin and enabled"), }, "invalid allow list config with same admin and manager in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -89,7 +90,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: []common.Address{TestAdminAddr}, EnabledAddresses: nil, }), - ExpectedError: "cannot set address as both admin and manager", + ExpectedError: errors.New("cannot set address as both admin and manager"), }, "invalid allow list config with same manager and enabled in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -97,7 +98,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: []common.Address{TestManagerAddr}, EnabledAddresses: []common.Address{TestManagerAddr}, }), - ExpectedError: "cannot set address as both enabled and manager", + ExpectedError: errors.New("cannot set address as both enabled and manager"), }, "invalid allow list config with manager role before activation": { Config: mkConfigWithUpgradeAndAllowList(module, &allowlist.AllowListConfig{ @@ -112,7 +113,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] config.EXPECT().IsDurango(gomock.Any()).Return(false) return config }(), - ExpectedError: allowlist.ErrCannotAddManagersBeforeDurango.Error(), + ExpectedError: allowlist.ErrCannotAddManagersBeforeDurango, }, "nil member allow list config in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -120,7 +121,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: nil, EnabledAddresses: nil, }), - ExpectedError: "", + ExpectedError: nil, }, "empty member allow list config in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -128,7 +129,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: []common.Address{}, EnabledAddresses: []common.Address{}, }), - ExpectedError: "", + ExpectedError: nil, }, "valid allow list config in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -136,7 +137,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: []common.Address{TestManagerAddr}, EnabledAddresses: []common.Address{TestEnabledAddr}, }), - ExpectedError: "", + ExpectedError: nil, }, } } diff --git a/precompile/contracts/feemanager/config_test.go b/precompile/contracts/feemanager/config_test.go index c0e1062dd0..cf093a968f 100644 --- a/precompile/contracts/feemanager/config_test.go +++ b/precompile/contracts/feemanager/config_test.go @@ -4,6 +4,7 @@ package feemanager import ( + "errors" "math/big" "testing" @@ -37,11 +38,11 @@ func TestVerify(t *testing.T) { tests := map[string]precompiletest.ConfigVerifyTest{ "invalid initial fee manager config": { Config: NewConfig(utils.NewUint64(3), admins, nil, nil, &invalidFeeConfig), - ExpectedError: "gasLimit = 0 cannot be less than or equal to 0", + ExpectedError: errors.New("gasLimit = 0 cannot be less than or equal to 0"), }, "nil initial fee manager config": { Config: NewConfig(utils.NewUint64(3), admins, nil, nil, &commontype.FeeConfig{}), - ExpectedError: "gasLimit cannot be nil", + ExpectedError: errors.New("fee config gasLimit cannot be nil"), }, } allowlisttest.VerifyPrecompileWithAllowListTests(t, Module, tests) diff --git a/precompile/contracts/feemanager/contract_test.go b/precompile/contracts/feemanager/contract_test.go index fe1dc67bfc..82ff4c0981 100644 --- a/precompile/contracts/feemanager/contract_test.go +++ b/precompile/contracts/feemanager/contract_test.go @@ -4,6 +4,7 @@ package feemanager import ( + "errors" "math/big" "testing" @@ -70,7 +71,7 @@ var ( }, SuppliedGas: SetFeeConfigGasCost, ReadOnly: false, - ExpectedErr: ErrCannotChangeFee.Error(), + ExpectedErr: ErrCannotChangeFee, }, { Name: "set_config_from_enabled_address_succeeds_and_emits_logs", @@ -131,7 +132,7 @@ var ( Config: &Config{ InitialFeeConfig: &testFeeConfig, }, - ExpectedErr: "cannot be greater than maxBlockGasCost", + ExpectedErr: errors.New("cannot be greater than maxBlockGasCost"), AfterHook: func(t testing.TB, state *extstate.StateDB) { feeConfig := GetStoredFeeConfig(state) require.Equal(t, testFeeConfig, feeConfig) @@ -270,7 +271,7 @@ var ( }, SuppliedGas: SetFeeConfigGasCost, ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection.Error(), + ExpectedErr: vm.ErrWriteProtection, }, { Name: "readOnly_setFeeConfig_with_allow_role_fails", @@ -284,7 +285,7 @@ var ( }, SuppliedGas: SetFeeConfigGasCost, ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection.Error(), + ExpectedErr: vm.ErrWriteProtection, }, { Name: "readOnly_setFeeConfig_with_admin_role_fails", @@ -298,7 +299,7 @@ var ( }, SuppliedGas: SetFeeConfigGasCost, ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection.Error(), + ExpectedErr: vm.ErrWriteProtection, }, { Name: "insufficient_gas_setFeeConfig_from_admin", @@ -312,7 +313,7 @@ var ( }, SuppliedGas: SetFeeConfigGasCost - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas.Error(), + ExpectedErr: vm.ErrOutOfGas, }, { Name: "set_config_with_extra_padded_bytes_should_fail_before_Durango", @@ -332,7 +333,7 @@ var ( }, SuppliedGas: SetFeeConfigGasCost, ReadOnly: false, - ExpectedErr: ErrInvalidLen.Error(), + ExpectedErr: ErrInvalidLen, SetupBlockContext: func(mbc *contract.MockBlockContext) { mbc.EXPECT().Number().Return(testBlockNumber).AnyTimes() mbc.EXPECT().Timestamp().Return(uint64(0)).AnyTimes() @@ -383,7 +384,7 @@ var ( return config }, SuppliedGas: SetFeeConfigGasCost, - ExpectedErr: ErrInvalidLen.Error(), + ExpectedErr: ErrInvalidLen, ReadOnly: false, SetupBlockContext: func(mbc *contract.MockBlockContext) { mbc.EXPECT().Number().Return(testBlockNumber).AnyTimes() diff --git a/precompile/contracts/nativeminter/config_test.go b/precompile/contracts/nativeminter/config_test.go index 649e16cc59..af7983dacc 100644 --- a/precompile/contracts/nativeminter/config_test.go +++ b/precompile/contracts/nativeminter/config_test.go @@ -4,6 +4,7 @@ package nativeminter import ( + "errors" "testing" "github.com/ava-labs/libevm/common" @@ -28,19 +29,19 @@ func TestVerify(t *testing.T) { config.EXPECT().IsDurango(gomock.Any()).Return(true).AnyTimes() return config }(), - ExpectedError: "", + ExpectedError: nil, }, "invalid allow list config in native minter allowlisttest": { Config: NewConfig(utils.NewUint64(3), admins, admins, nil, nil), - ExpectedError: "cannot set address", + ExpectedError: errors.New("cannot set address"), }, "duplicate admins in config in native minter allowlisttest": { Config: NewConfig(utils.NewUint64(3), append(admins, admins[0]), enableds, managers, nil), - ExpectedError: "duplicate address", + ExpectedError: errors.New("duplicate address"), }, "duplicate enableds in config in native minter allowlisttest": { Config: NewConfig(utils.NewUint64(3), admins, append(enableds, enableds[0]), managers, nil), - ExpectedError: "duplicate address", + ExpectedError: errors.New("duplicate address"), }, "nil amount in native minter config": { Config: NewConfig(utils.NewUint64(3), admins, nil, nil, @@ -48,7 +49,7 @@ func TestVerify(t *testing.T) { common.HexToAddress("0x01"): math.NewHexOrDecimal256(123), common.HexToAddress("0x02"): nil, }), - ExpectedError: "initial mint cannot contain nil", + ExpectedError: errors.New("initial mint cannot contain nil"), }, "negative amount in native minter config": { Config: NewConfig(utils.NewUint64(3), admins, nil, nil, @@ -56,7 +57,7 @@ func TestVerify(t *testing.T) { common.HexToAddress("0x01"): math.NewHexOrDecimal256(123), common.HexToAddress("0x02"): math.NewHexOrDecimal256(-1), }), - ExpectedError: "initial mint cannot contain invalid amount", + ExpectedError: errors.New("initial mint cannot contain invalid amount"), }, } allowlisttest.VerifyPrecompileWithAllowListTests(t, Module, tests) diff --git a/precompile/contracts/nativeminter/contract_test.go b/precompile/contracts/nativeminter/contract_test.go index beb4220d62..b48125f7e4 100644 --- a/precompile/contracts/nativeminter/contract_test.go +++ b/precompile/contracts/nativeminter/contract_test.go @@ -35,7 +35,7 @@ var tests = []precompiletest.PrecompileTest{ }, SuppliedGas: MintGasCost, ReadOnly: false, - ExpectedErr: ErrCannotMint.Error(), + ExpectedErr: ErrCannotMint, }, { Name: "calling_mintNativeCoin_from_Enabled_should_succeed", @@ -147,7 +147,7 @@ var tests = []precompiletest.PrecompileTest{ }, SuppliedGas: MintGasCost, ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection.Error(), + ExpectedErr: vm.ErrWriteProtection, }, { Name: "readOnly_mint_with_allow_role_fails", @@ -161,7 +161,7 @@ var tests = []precompiletest.PrecompileTest{ }, SuppliedGas: MintGasCost, ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection.Error(), + ExpectedErr: vm.ErrWriteProtection, }, { Name: "readOnly_mint_with_admin_role_fails", @@ -175,7 +175,7 @@ var tests = []precompiletest.PrecompileTest{ }, SuppliedGas: MintGasCost, ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection.Error(), + ExpectedErr: vm.ErrWriteProtection, }, { Name: "insufficient_gas_mint_from_admin", @@ -189,7 +189,7 @@ var tests = []precompiletest.PrecompileTest{ }, SuppliedGas: MintGasCost + NativeCoinMintedEventGasCost - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas.Error(), + ExpectedErr: vm.ErrOutOfGas, }, { Name: "mint_does_not_log_pre_Durango", @@ -234,7 +234,7 @@ var tests = []precompiletest.PrecompileTest{ }, SuppliedGas: MintGasCost, ReadOnly: false, - ExpectedErr: ErrInvalidLen.Error(), + ExpectedErr: ErrInvalidLen, }, { Name: "mint_with_extra_padded_bytes_should_succeed_with_Durango", diff --git a/precompile/contracts/rewardmanager/config_test.go b/precompile/contracts/rewardmanager/config_test.go index 7c0b8beaab..dc069aafcf 100644 --- a/precompile/contracts/rewardmanager/config_test.go +++ b/precompile/contracts/rewardmanager/config_test.go @@ -25,7 +25,7 @@ func TestVerify(t *testing.T) { AllowFeeRecipients: true, RewardAddress: common.HexToAddress("0x01"), }), - ExpectedError: ErrCannotEnableBothRewards.Error(), + ExpectedError: ErrCannotEnableBothRewards, }, } allowlisttest.VerifyPrecompileWithAllowListTests(t, Module, tests) diff --git a/precompile/contracts/rewardmanager/contract_test.go b/precompile/contracts/rewardmanager/contract_test.go index 0d932d40f6..044ce3a102 100644 --- a/precompile/contracts/rewardmanager/contract_test.go +++ b/precompile/contracts/rewardmanager/contract_test.go @@ -36,7 +36,7 @@ var ( }, SuppliedGas: AllowFeeRecipientsGasCost, ReadOnly: false, - ExpectedErr: ErrCannotAllowFeeRecipients.Error(), + ExpectedErr: ErrCannotAllowFeeRecipients, }, { Name: "set_reward_address_from_no_role_fails", @@ -50,7 +50,7 @@ var ( }, SuppliedGas: SetRewardAddressGasCost, ReadOnly: false, - ExpectedErr: ErrCannotSetRewardAddress.Error(), + ExpectedErr: ErrCannotSetRewardAddress, }, { Name: "disable_rewards_from_no_role_fails", @@ -64,7 +64,7 @@ var ( }, SuppliedGas: DisableRewardsGasCost, ReadOnly: false, - ExpectedErr: ErrCannotDisableRewards.Error(), + ExpectedErr: ErrCannotDisableRewards, }, { Name: "set_allow_fee_recipients_from_enabled_succeeds", @@ -379,7 +379,7 @@ var ( }, SuppliedGas: AllowFeeRecipientsGasCost, ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection.Error(), + ExpectedErr: vm.ErrWriteProtection, }, { Name: "readOnly_set_reward_address_with_allowed_role_fails", @@ -393,7 +393,7 @@ var ( }, SuppliedGas: SetRewardAddressGasCost, ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection.Error(), + ExpectedErr: vm.ErrWriteProtection, }, { Name: "insufficient_gas_set_reward_address_from_allowed_role", @@ -407,7 +407,7 @@ var ( }, SuppliedGas: SetRewardAddressGasCost + RewardAddressChangedEventGasCost - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas.Error(), + ExpectedErr: vm.ErrOutOfGas, }, { Name: "insufficient_gas_allow_fee_recipients_from_allowed_role", @@ -421,7 +421,7 @@ var ( }, SuppliedGas: AllowFeeRecipientsGasCost + FeeRecipientsAllowedEventGasCost - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas.Error(), + ExpectedErr: vm.ErrOutOfGas, }, { Name: "insufficient_gas_read_current_reward_address_from_allowed_role", @@ -435,7 +435,7 @@ var ( }, SuppliedGas: CurrentRewardAddressGasCost - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas.Error(), + ExpectedErr: vm.ErrOutOfGas, }, { Name: "insufficient_gas_are_fee_recipients_allowed_from_allowed_role", @@ -449,7 +449,7 @@ var ( }, SuppliedGas: AreFeeRecipientsAllowedGasCost - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas.Error(), + ExpectedErr: vm.ErrOutOfGas, }, } ) diff --git a/precompile/contracts/warp/config.go b/precompile/contracts/warp/config.go index cc0fd17885..db11bdad0e 100644 --- a/precompile/contracts/warp/config.go +++ b/precompile/contracts/warp/config.go @@ -32,6 +32,7 @@ var ( ) var ( + ErrInvalidQuorumRatio = errors.New("invalid warp quorum ratio") errOverflowSignersGasCost = errors.New("overflow calculating warp signers gas cost") errInvalidPredicateBytes = errors.New("cannot unpack predicate bytes") errInvalidWarpMsg = errors.New("cannot unpack warp message") @@ -95,11 +96,11 @@ func (c *Config) Verify(chainConfig precompileconfig.ChainConfig) error { } if c.QuorumNumerator > WarpQuorumDenominator { - return fmt.Errorf("cannot specify quorum numerator (%d) > quorum denominator (%d)", c.QuorumNumerator, WarpQuorumDenominator) + return fmt.Errorf("%w: cannot specify numerator (%d) > denominator (%d)", ErrInvalidQuorumRatio, c.QuorumNumerator, WarpQuorumDenominator) } // If a non-default quorum numerator is specified and it is less than the minimum, return an error if c.QuorumNumerator != 0 && c.QuorumNumerator < WarpQuorumNumeratorMinimum { - return fmt.Errorf("cannot specify quorum numerator (%d) < min quorum numerator (%d)", c.QuorumNumerator, WarpQuorumNumeratorMinimum) + return fmt.Errorf("%w: cannot specify numerator (%d) < min numerator (%d)", ErrInvalidQuorumRatio, c.QuorumNumerator, WarpQuorumNumeratorMinimum) } return nil } diff --git a/precompile/contracts/warp/config_test.go b/precompile/contracts/warp/config_test.go index ae6a145add..e87ba56876 100644 --- a/precompile/contracts/warp/config_test.go +++ b/precompile/contracts/warp/config_test.go @@ -4,7 +4,6 @@ package warp import ( - "fmt" "testing" "go.uber.org/mock/gomock" @@ -18,11 +17,11 @@ func TestVerify(t *testing.T) { tests := map[string]precompiletest.ConfigVerifyTest{ "quorum numerator less than minimum": { Config: NewConfig(utils.NewUint64(3), WarpQuorumNumeratorMinimum-1, false), - ExpectedError: fmt.Sprintf("cannot specify quorum numerator (%d) < min quorum numerator (%d)", WarpQuorumNumeratorMinimum-1, WarpQuorumNumeratorMinimum), + ExpectedError: ErrInvalidQuorumRatio, }, "quorum numerator greater than quorum denominator": { Config: NewConfig(utils.NewUint64(3), WarpQuorumDenominator+1, false), - ExpectedError: fmt.Sprintf("cannot specify quorum numerator (%d) > quorum denominator (%d)", WarpQuorumDenominator+1, WarpQuorumDenominator), + ExpectedError: ErrInvalidQuorumRatio, }, "default quorum numerator": { Config: NewDefaultConfig(utils.NewUint64(3)), @@ -40,7 +39,7 @@ func TestVerify(t *testing.T) { config.EXPECT().IsDurango(gomock.Any()).Return(false) return config }(), - ExpectedError: errWarpCannotBeActivated.Error(), + ExpectedError: errWarpCannotBeActivated, }, } precompiletest.RunVerifyTests(t, tests) diff --git a/precompile/contracts/warp/contract_test.go b/precompile/contracts/warp/contract_test.go index 63a163d4d9..17803abf30 100644 --- a/precompile/contracts/warp/contract_test.go +++ b/precompile/contracts/warp/contract_test.go @@ -111,7 +111,7 @@ func getBlockchainIDTests(tb testing.TB, rules extras.AvalancheRules) []precompi }, SuppliedGas: gasConfig.GetBlockchainID - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas.Error(), + ExpectedErr: vm.ErrOutOfGas, Rules: rules, }, } @@ -154,7 +154,7 @@ func sendWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []precompi InputFn: func(testing.TB) []byte { return sendWarpMessageInput }, SuppliedGas: gasConfig.SendWarpMessageCost(len(sendWarpMessageInput[4:])), ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection.Error(), + ExpectedErr: vm.ErrWriteProtection, Rules: rules, }, { @@ -163,7 +163,7 @@ func sendWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []precompi InputFn: func(testing.TB) []byte { return sendWarpMessageInput }, SuppliedGas: gasConfig.SendWarpMessageBase - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas.Error(), + ExpectedErr: vm.ErrOutOfGas, Rules: rules, }, { @@ -172,7 +172,7 @@ func sendWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []precompi InputFn: func(testing.TB) []byte { return sendWarpMessageInput }, SuppliedGas: gasConfig.SendWarpMessageCost(len(sendWarpMessageInput[4:])) - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas.Error(), + ExpectedErr: vm.ErrOutOfGas, Rules: rules, }, { @@ -183,7 +183,7 @@ func sendWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []precompi }, SuppliedGas: gasConfig.SendWarpMessageBase, ReadOnly: false, - ExpectedErr: errInvalidSendInput.Error(), + ExpectedErr: errInvalidSendInput, Rules: rules, }, { @@ -429,7 +429,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p Predicates: []predicate.Predicate{warpMessagePredicate}, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas.Error(), + ExpectedErr: vm.ErrOutOfGas, Rules: rules, }, { @@ -442,7 +442,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(warpMessagePredicate)) - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas.Error(), + ExpectedErr: vm.ErrOutOfGas, Rules: rules, }, { @@ -455,7 +455,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(invalidPackedPredicate)), ReadOnly: false, - ExpectedErr: errInvalidPredicateBytes.Error(), + ExpectedErr: errInvalidPredicateBytes, Rules: rules, }, { @@ -468,7 +468,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(invalidWarpMsgPredicate)), ReadOnly: false, - ExpectedErr: errInvalidWarpMsg.Error(), + ExpectedErr: errInvalidWarpMsg, Rules: rules, }, { @@ -481,7 +481,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(invalidAddressedPredicate)), ReadOnly: false, - ExpectedErr: errInvalidAddressedPayload.Error(), + ExpectedErr: errInvalidAddressedPayload, Rules: rules, }, { @@ -492,7 +492,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p }, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase, ReadOnly: false, - ExpectedErr: errInvalidIndexInput.Error(), + ExpectedErr: errInvalidIndexInput, Rules: rules, }, { @@ -505,7 +505,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p }, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase, ReadOnly: false, - ExpectedErr: errInvalidIndexInput.Error(), + ExpectedErr: errInvalidIndexInput, Rules: rules, }, { @@ -518,7 +518,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p }, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase, ReadOnly: false, - ExpectedErr: errInvalidIndexInput.Error(), + ExpectedErr: errInvalidIndexInput, Rules: rules, }, } @@ -719,7 +719,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ Predicates: []predicate.Predicate{warpMessagePredicate}, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas.Error(), + ExpectedErr: vm.ErrOutOfGas, Rules: rules, }, { @@ -732,7 +732,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(warpMessagePredicate)) - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas.Error(), + ExpectedErr: vm.ErrOutOfGas, Rules: rules, }, { @@ -745,7 +745,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(invalidPackedPredicate)), ReadOnly: false, - ExpectedErr: errInvalidPredicateBytes.Error(), + ExpectedErr: errInvalidPredicateBytes, Rules: rules, }, { @@ -758,7 +758,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(invalidWarpMsgPredicate)), ReadOnly: false, - ExpectedErr: errInvalidWarpMsg.Error(), + ExpectedErr: errInvalidWarpMsg, Rules: rules, }, { @@ -771,7 +771,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(invalidHashPredicate)), ReadOnly: false, - ExpectedErr: errInvalidBlockHashPayload.Error(), + ExpectedErr: errInvalidBlockHashPayload, Rules: rules, }, { @@ -782,7 +782,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ }, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase, ReadOnly: false, - ExpectedErr: errInvalidIndexInput.Error(), + ExpectedErr: errInvalidIndexInput, Rules: rules, }, { @@ -795,7 +795,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ }, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase, ReadOnly: false, - ExpectedErr: errInvalidIndexInput.Error(), + ExpectedErr: errInvalidIndexInput, Rules: rules, }, { @@ -808,7 +808,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ }, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase, ReadOnly: false, - ExpectedErr: errInvalidIndexInput.Error(), + ExpectedErr: errInvalidIndexInput, Rules: rules, }, } diff --git a/precompile/modules/registerer.go b/precompile/modules/registerer.go index b2246f0eb8..c45fc34abb 100644 --- a/precompile/modules/registerer.go +++ b/precompile/modules/registerer.go @@ -4,6 +4,7 @@ package modules import ( + "errors" "fmt" "sort" @@ -32,6 +33,9 @@ var ( End: common.HexToAddress("0x03000000000000000000000000000000000000ff"), }, } + + errBlackholeAddress = fmt.Errorf("cannot register module that overlaps with blackhole address %s", constants.BlackholeAddr) + errAddressNotInReservedRange = errors.New("address is not in a reserved range for custom precompiles") ) // ReservedAddress returns true if [addr] is in a reserved range for custom precompiles @@ -51,10 +55,10 @@ func RegisterModule(stm Module) error { key := stm.ConfigKey if address == constants.BlackholeAddr { - return fmt.Errorf("address %s overlaps with blackhole address", address) + return fmt.Errorf("%w: address %s ", errBlackholeAddress, address) } if !ReservedAddress(address) { - return fmt.Errorf("address %s not in a reserved range", address) + return fmt.Errorf("%w: address %s ", errAddressNotInReservedRange, address) } for _, registeredModule := range registeredModules { diff --git a/precompile/modules/registerer_test.go b/precompile/modules/registerer_test.go index f883c750c3..20770061fa 100644 --- a/precompile/modules/registerer_test.go +++ b/precompile/modules/registerer_test.go @@ -51,10 +51,10 @@ func TestRegisterModuleInvalidAddresses(t *testing.T) { Address: constants.BlackholeAddr, } err := RegisterModule(m) - require.ErrorContains(t, err, "overlaps with blackhole address") + require.ErrorIs(t, err, errBlackholeAddress) // Test an address outside of the reserved ranges cannot be registered m.Address = common.BigToAddress(big.NewInt(1)) err = RegisterModule(m) - require.ErrorContains(t, err, "not in a reserved range") + require.ErrorIs(t, err, errAddressNotInReservedRange) } diff --git a/precompile/precompiletest/test_config.go b/precompile/precompiletest/test_config.go index a2ff6e7fc3..875019c67d 100644 --- a/precompile/precompiletest/test_config.go +++ b/precompile/precompiletest/test_config.go @@ -17,7 +17,7 @@ import ( type ConfigVerifyTest struct { Config precompileconfig.Config ChainConfig precompileconfig.ChainConfig - ExpectedError string + ExpectedError error } // ConfigEqualTest is a test case for comparing two configs @@ -43,11 +43,7 @@ func RunVerifyTests(t *testing.T, tests map[string]ConfigVerifyTest) { chainConfig = mockChainConfig } err := test.Config.Verify(chainConfig) - if test.ExpectedError == "" { - require.NoError(err) - } else { - require.ErrorContains(err, test.ExpectedError) - } + require.ErrorIs(err, test.ExpectedError) }) } } diff --git a/precompile/precompiletest/test_precompile.go b/precompile/precompiletest/test_precompile.go index 9b35902891..77764648ae 100644 --- a/precompile/precompiletest/test_precompile.go +++ b/precompile/precompiletest/test_precompile.go @@ -55,8 +55,8 @@ type PrecompileTest struct { // ExpectedRes is the expected raw byte result returned by the precompile ExpectedRes []byte // ExpectedErr is the expected error returned by the precompile - ExpectedErr string - // ChainConfigFn returns the chain config to use for the precompile's block context + ExpectedErr error + // ChainConfig is the chain config to use for the precompile's block context // If nil, the default chain config will be used. ChainConfigFn func(*gomock.Controller) precompileconfig.ChainConfig // Rules is the rules to use for the precompile's block context. @@ -81,11 +81,7 @@ func (test PrecompileTest) Run(t *testing.T, module modules.Module) { if runParams.Input != nil { ret, remainingGas, err := module.Contract.Run(runParams.AccessibleState, runParams.Caller, runParams.ContractAddress, runParams.Input, runParams.SuppliedGas, runParams.ReadOnly) - if len(test.ExpectedErr) != 0 { - require.ErrorContains(t, err, test.ExpectedErr) - } else { - require.NoError(t, err) - } + require.ErrorIs(t, err, test.ExpectedErr) require.Equal(t, uint64(0), remainingGas) require.Equal(t, test.ExpectedRes, ret) } @@ -109,11 +105,7 @@ func (test PrecompileTest) Bench(b *testing.B, module modules.Module) { snapshot := stateDB.Snapshot() ret, remainingGas, err := module.Contract.Run(runParams.AccessibleState, runParams.Caller, runParams.ContractAddress, runParams.Input, runParams.SuppliedGas, runParams.ReadOnly) - if len(test.ExpectedErr) != 0 { - require.ErrorContains(b, err, test.ExpectedErr) - } else { - require.NoError(b, err) - } + require.ErrorIs(b, err, test.ExpectedErr) require.Equal(b, uint64(0), remainingGas) require.Equal(b, test.ExpectedRes, ret) @@ -149,11 +141,7 @@ func (test PrecompileTest) Bench(b *testing.B, module modules.Module) { // the benchmark should catch the error here. stateDB.RevertToSnapshot(snapshot) ret, remainingGas, err = module.Contract.Run(runParams.AccessibleState, runParams.Caller, runParams.ContractAddress, runParams.Input, runParams.SuppliedGas, runParams.ReadOnly) - if len(test.ExpectedErr) != 0 { - require.ErrorContains(b, err, test.ExpectedErr) - } else { - require.NoError(b, err) - } + require.ErrorIs(b, err, test.ExpectedErr) require.Equal(b, uint64(0), remainingGas) require.Equal(b, test.ExpectedRes, ret) diff --git a/sync/client/client_test.go b/sync/client/client_test.go index 2a89c7d895..db1083acaf 100644 --- a/sync/client/client_test.go +++ b/sync/client/client_test.go @@ -181,7 +181,7 @@ func TestGetBlocks(t *testing.T) { request message.BlockRequest getResponse func(t *testing.T, request message.BlockRequest) []byte assertResponse func(t *testing.T, response []*types.Block) - expectedErr string + expectedErr error }{ "normal resonse": { request: message.BlockRequest{ @@ -228,7 +228,7 @@ func TestGetBlocks(t *testing.T) { getResponse: func(_ *testing.T, _ message.BlockRequest) []byte { return []byte("gibberish") }, - expectedErr: errUnmarshalResponse.Error(), + expectedErr: errUnmarshalResponse, }, "invalid value replacing block": { request: message.BlockRequest{ @@ -249,7 +249,7 @@ func TestGetBlocks(t *testing.T) { return responseBytes }, - expectedErr: "failed to unmarshal response: rlp: expected List", + expectedErr: errUnmarshalResponse, }, "incorrect starting point": { request: message.BlockRequest{ @@ -268,7 +268,7 @@ func TestGetBlocks(t *testing.T) { return response }, - expectedErr: errHashMismatch.Error(), + expectedErr: errHashMismatch, }, "missing link in between blocks": { request: message.BlockRequest{ @@ -291,7 +291,7 @@ func TestGetBlocks(t *testing.T) { return responseBytes }, - expectedErr: errHashMismatch.Error(), + expectedErr: errHashMismatch, }, "no blocks": { request: message.BlockRequest{ @@ -308,7 +308,7 @@ func TestGetBlocks(t *testing.T) { return responseBytes }, - expectedErr: errEmptyResponse.Error(), + expectedErr: errEmptyResponse, }, "more than requested blocks": { request: message.BlockRequest{ @@ -327,7 +327,7 @@ func TestGetBlocks(t *testing.T) { return responseBytes }, - expectedErr: errTooManyBlocks.Error(), + expectedErr: errTooManyBlocks, }, } for name, test := range tests { @@ -336,7 +336,7 @@ func TestGetBlocks(t *testing.T) { defer cancel() responseBytes := test.getResponse(t, test.request) - if len(test.expectedErr) == 0 { + if test.expectedErr == nil { mockNetClient.mockResponse(1, nil, responseBytes) } else { attempted := false @@ -349,11 +349,10 @@ func TestGetBlocks(t *testing.T) { } blockResponse, err := stateSyncClient.GetBlocks(ctx, test.request.Hash, test.request.Height, test.request.Parents) - if len(test.expectedErr) != 0 { - require.ErrorContains(t, err, test.expectedErr) + require.ErrorIs(t, err, test.expectedErr) + if test.expectedErr != nil { return } - require.NoError(t, err) test.assertResponse(t, blockResponse) }) diff --git a/warp/backend.go b/warp/backend.go index 12d4fc68ed..2be5ccc7bc 100644 --- a/warp/backend.go +++ b/warp/backend.go @@ -23,6 +23,8 @@ import ( var ( _ Backend = (*backend)(nil) + ErrValidateBlock = errors.New("failed to validate block message") + ErrVerifyWarpMessage = errors.New("failed to verify warp message") errParsingOffChainMessage = errors.New("failed to parse off-chain message") messageCacheSize = 500 @@ -141,7 +143,7 @@ func (b *backend) GetMessageSignature(ctx context.Context, unsignedMessage *aval } if err := b.Verify(ctx, unsignedMessage, nil); err != nil { - return nil, fmt.Errorf("failed to validate warp message: %w", err) + return nil, fmt.Errorf("%w: %w", ErrVerifyWarpMessage, err) } return b.signMessage(unsignedMessage) } @@ -164,7 +166,7 @@ func (b *backend) GetBlockSignature(ctx context.Context, blockID ids.ID) ([]byte } if err := b.verifyBlockMessage(ctx, blockHashPayload); err != nil { - return nil, fmt.Errorf("failed to validate block message: %w", err) + return nil, fmt.Errorf("%w: %w", ErrValidateBlock, err) } sig, err := b.signMessage(unsignedMessage) diff --git a/warp/backend_test.go b/warp/backend_test.go index 11349fe46c..b6ff426bb6 100644 --- a/warp/backend_test.go +++ b/warp/backend_test.go @@ -73,7 +73,7 @@ func TestAddAndGetUnknownMessage(t *testing.T) { // Try getting a signature for a message that was not added. _, err = backend.GetMessageSignature(t.Context(), testUnsignedMessage) - require.ErrorContains(t, err, "unknown codec version") + require.ErrorIs(t, err, ErrVerifyWarpMessage) } func TestGetBlockSignature(t *testing.T) { @@ -102,7 +102,7 @@ func TestGetBlockSignature(t *testing.T) { require.Equal(expectedSig, signature) _, err = backend.GetBlockSignature(t.Context(), ids.GenerateTestID()) - require.ErrorContains(err, "failed to get block") + require.ErrorIs(err, ErrValidateBlock) } func TestZeroSizedCache(t *testing.T) { From ec2e94a242be208af7fee908931b8b701ffb23d3 Mon Sep 17 00:00:00 2001 From: Austin Larson <78000745+alarso16@users.noreply.github.com> Date: Thu, 16 Oct 2025 05:59:34 -0400 Subject: [PATCH 02/19] style: Use require.ErrorIs whenever possible (#1303) --- plugin/evm/vm_test.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/plugin/evm/vm_test.go b/plugin/evm/vm_test.go index c1f2213600..3896d1dc13 100644 --- a/plugin/evm/vm_test.go +++ b/plugin/evm/vm_test.go @@ -765,10 +765,10 @@ func testReorgProtection(t *testing.T, scheme string) { // with the preferred chain lower than the last finalized block) // should NEVER happen. However, the VM defends against this // just in case. - err = vm1.SetPreference(t.Context(), vm1BlkC.ID()) //nolint:forbidigo // uses upstream code + err = vm1.SetPreference(t.Context(), vm1BlkC.ID()) require.ErrorContains(t, err, "cannot orphan finalized block") //nolint:forbidigo // uses upstream code - err = vm1BlkC.Accept(t.Context()) //nolint:forbidigo // uses upstream code - require.ErrorContains(t, err, "expected accepted block to have parent") + err = vm1BlkC.Accept(t.Context()) + require.ErrorContains(t, err, "expected accepted block to have parent") //nolint:forbidigo // uses upstream code } // Regression test to ensure that a VM that accepts block C while preferring @@ -2662,9 +2662,9 @@ func TestParentBeaconRootBlock(t *testing.T) { parentBeaconBlock, err := wrapBlock(parentBeaconEthBlock, tvm.vm) require.NoError(t, err) - _, err = tvm.vm.ParseBlock(context.Background(), parentBeaconBlock.Bytes()) + _, err = tvm.vm.ParseBlock(t.Context(), parentBeaconBlock.Bytes()) require.ErrorIs(t, err, test.expectedError) - err = parentBeaconBlock.Verify(context.Background()) + err = parentBeaconBlock.Verify(t.Context()) require.ErrorIs(t, err, test.expectedError) }) } From 34b47934f0dd53554a0120ccb68c260ed54093c3 Mon Sep 17 00:00:00 2001 From: Jonathan Oppenheimer Date: Tue, 25 Nov 2025 01:54:13 -0500 Subject: [PATCH 03/19] test: forbidgo linter --- .../precompilebind/precompile_bind_test.go | 2 +- commontype/fee_config.go | 75 +++++++++++++------ commontype/fee_config_test.go | 65 ++++++++-------- network/network_test.go | 4 +- params/extras/config.go | 20 ++--- params/extras/config_test.go | 23 +++--- params/extras/network_upgrades.go | 8 +- params/extras/network_upgrades_test.go | 40 ++++------ params/extras/precompile_config_test.go | 41 +++++----- params/extras/precompile_upgrade.go | 16 ++-- params/extras/precompile_upgrade_test.go | 31 ++++---- params/extras/state_upgrade.go | 13 +++- params/extras/state_upgrade_test.go | 19 ++--- plugin/evm/vm.go | 3 +- plugin/evm/vm_test.go | 5 +- plugin/evm/vm_upgrade_bytes_test.go | 2 +- .../allowlisttest/test_allowlist_config.go | 21 +++--- precompile/allowlist/config.go | 22 ++++-- precompile/allowlist/unpack_pack_test.go | 4 +- .../deployerallowlisttest/simulated_test.go | 5 +- .../contracts/feemanager/config_test.go | 9 +-- .../contracts/feemanager/unpack_pack_test.go | 18 ++--- .../contracts/nativeminter/config_test.go | 19 ++--- .../nativeminter/unpack_pack_test.go | 8 +- .../contracts/rewardmanager/config_test.go | 2 +- precompile/contracts/warp/config_test.go | 10 +-- precompile/precompiletest/test_config.go | 8 +- 27 files changed, 254 insertions(+), 239 deletions(-) diff --git a/accounts/abi/bind/precompilebind/precompile_bind_test.go b/accounts/abi/bind/precompilebind/precompile_bind_test.go index 90967d6ba1..ba621c6dff 100644 --- a/accounts/abi/bind/precompilebind/precompile_bind_test.go +++ b/accounts/abi/bind/precompilebind/precompile_bind_test.go @@ -637,7 +637,7 @@ func TestPrecompileBind(t *testing.T) { // Generate the binding and create a Go source file in the workspace bindedFiles, err := PrecompileBind(types, tt.abi, []string{""}, nil, tt.name, bind.LangGo, nil, nil, "contract.abi", true) if tt.errMsg != "" { - require.ErrorContains(t, err, tt.errMsg) + require.ErrorContains(t, err, tt.errMsg) //nolint:forbidigo // uses upstream code return } require.NoError(t, err, "test %d: failed to generate binding: %v", i, err) diff --git a/commontype/fee_config.go b/commontype/fee_config.go index 75c0558635..d8e3d764e6 100644 --- a/commontype/fee_config.go +++ b/commontype/fee_config.go @@ -13,6 +13,33 @@ import ( "github.com/ava-labs/subnet-evm/utils" ) +var ( + ErrGasLimitTooLow = errors.New("gasLimit cannot be less than or equal to 0") + ErrGasLimitNil = errors.New("gasLimit cannot be nil") + errMinBaseFeeNil = errors.New("minBaseFee cannot be nil") + errTargetGasNil = errors.New("targetGas cannot be nil") + errBaseFeeChangeDenominatorNil = errors.New("baseFeeChangeDenominator cannot be nil") + errMinBlockGasCostNil = errors.New("minBlockGasCost cannot be nil") + errMaxBlockGasCostNil = errors.New("maxBlockGasCost cannot be nil") + errBlockGasCostStepNil = errors.New("blockGasCostStep cannot be nil") + errTargetBlockRateTooLow = errors.New("targetBlockRate cannot be less than or equal to 0") + errMinBaseFeeNegative = errors.New("minBaseFee cannot be less than 0") + errTargetGasTooLow = errors.New("targetGas cannot be less than or equal to 0") + errBaseFeeChangeDenominatorTooLow = errors.New("baseFeeChangeDenominator cannot be less than or equal to 0") + errMinBlockGasCostNegative = errors.New("minBlockGasCost cannot be less than 0") + errMinBlockGasCostTooHigh = errors.New("minBlockGasCost cannot be greater than maxBlockGasCost") + errBlockGasCostStepNegative = errors.New("blockGasCostStep cannot be less than 0") + errMaxBlockGasCostNotUint64 = errors.New("maxBlockGasCost is not a valid uint64") + errGasLimitExceedsHashLength = errors.New("gasLimit exceeds hash length") + errTargetBlockRateExceedsHashLength = errors.New("targetBlockRate exceeds hash length") + errMinBaseFeeExceedsHashLength = errors.New("minBaseFee exceeds hash length") + errTargetGasExceedsHashLength = errors.New("targetGas exceeds hash length") + errBaseFeeChangeDenominatorExceedsHashLength = errors.New("baseFeeChangeDenominator exceeds hash length") + errMinBlockGasCostExceedsHashLength = errors.New("minBlockGasCost exceeds hash length") + errMaxBlockGasCostExceedsHashLength = errors.New("maxBlockGasCost exceeds hash length") + errBlockGasCostStepExceedsHashLength = errors.New("blockGasCostStep exceeds hash length") +) + // FeeConfig specifies the parameters for the dynamic fee algorithm, which determines the gas limit, base fee, and block gas cost of blocks // on the network. // @@ -65,40 +92,40 @@ var EmptyFeeConfig = FeeConfig{} func (f *FeeConfig) Verify() error { switch { case f.GasLimit == nil: - return errors.New("gasLimit cannot be nil") + return ErrGasLimitNil case f.MinBaseFee == nil: - return errors.New("minBaseFee cannot be nil") + return errMinBaseFeeNil case f.TargetGas == nil: - return errors.New("targetGas cannot be nil") + return errTargetGasNil case f.BaseFeeChangeDenominator == nil: - return errors.New("baseFeeChangeDenominator cannot be nil") + return errBaseFeeChangeDenominatorNil case f.MinBlockGasCost == nil: - return errors.New("minBlockGasCost cannot be nil") + return errMinBlockGasCostNil case f.MaxBlockGasCost == nil: - return errors.New("maxBlockGasCost cannot be nil") + return errMaxBlockGasCostNil case f.BlockGasCostStep == nil: - return errors.New("blockGasCostStep cannot be nil") + return errBlockGasCostStepNil } switch { case f.GasLimit.Cmp(common.Big0) != 1: - return fmt.Errorf("gasLimit = %d cannot be less than or equal to 0", f.GasLimit) + return fmt.Errorf("%w: gasLimit = %d", ErrGasLimitTooLow, f.GasLimit) case f.TargetBlockRate <= 0: - return fmt.Errorf("targetBlockRate = %d cannot be less than or equal to 0", f.TargetBlockRate) + return fmt.Errorf("%w: targetBlockRate = %d", errTargetBlockRateTooLow, f.TargetBlockRate) case f.MinBaseFee.Cmp(common.Big0) == -1: - return fmt.Errorf("minBaseFee = %d cannot be less than 0", f.MinBaseFee) + return fmt.Errorf("%w: minBaseFee = %d", errMinBaseFeeNegative, f.MinBaseFee) case f.TargetGas.Cmp(common.Big0) != 1: - return fmt.Errorf("targetGas = %d cannot be less than or equal to 0", f.TargetGas) + return fmt.Errorf("%w: targetGas = %d", errTargetGasTooLow, f.TargetGas) case f.BaseFeeChangeDenominator.Cmp(common.Big0) != 1: - return fmt.Errorf("baseFeeChangeDenominator = %d cannot be less than or equal to 0", f.BaseFeeChangeDenominator) + return fmt.Errorf("%w: baseFeeChangeDenominator = %d", errBaseFeeChangeDenominatorTooLow, f.BaseFeeChangeDenominator) case f.MinBlockGasCost.Cmp(common.Big0) == -1: - return fmt.Errorf("minBlockGasCost = %d cannot be less than 0", f.MinBlockGasCost) + return fmt.Errorf("%w: minBlockGasCost = %d", errMinBlockGasCostNegative, f.MinBlockGasCost) case f.MinBlockGasCost.Cmp(f.MaxBlockGasCost) == 1: - return fmt.Errorf("minBlockGasCost = %d cannot be greater than maxBlockGasCost = %d", f.MinBlockGasCost, f.MaxBlockGasCost) + return fmt.Errorf("%w: minBlockGasCost = %d, maxBlockGasCost = %d", errMinBlockGasCostTooHigh, f.MinBlockGasCost, f.MaxBlockGasCost) case f.BlockGasCostStep.Cmp(common.Big0) == -1: - return fmt.Errorf("blockGasCostStep = %d cannot be less than 0", f.BlockGasCostStep) + return fmt.Errorf("%w: blockGasCostStep = %d", errBlockGasCostStepNegative, f.BlockGasCostStep) case !f.MaxBlockGasCost.IsUint64(): - return fmt.Errorf("maxBlockGasCost = %d is not a valid uint64", f.MaxBlockGasCost) + return fmt.Errorf("%w: maxBlockGasCost = %d", errMaxBlockGasCostNotUint64, f.MaxBlockGasCost) } return f.checkByteLens() } @@ -122,28 +149,28 @@ func (f *FeeConfig) Equal(other *FeeConfig) bool { // checkByteLens checks byte lengths against common.HashLen (32 bytes) and returns error func (f *FeeConfig) checkByteLens() error { if isBiggerThanHashLen(f.GasLimit) { - return fmt.Errorf("gasLimit exceeds %d bytes", common.HashLength) + return fmt.Errorf("%w: %d bytes", errGasLimitExceedsHashLength, common.HashLength) } if isBiggerThanHashLen(new(big.Int).SetUint64(f.TargetBlockRate)) { - return fmt.Errorf("targetBlockRate exceeds %d bytes", common.HashLength) + return fmt.Errorf("%w: %d bytes", errTargetBlockRateExceedsHashLength, common.HashLength) } if isBiggerThanHashLen(f.MinBaseFee) { - return fmt.Errorf("minBaseFee exceeds %d bytes", common.HashLength) + return fmt.Errorf("%w: %d bytes", errMinBaseFeeExceedsHashLength, common.HashLength) } if isBiggerThanHashLen(f.TargetGas) { - return fmt.Errorf("targetGas exceeds %d bytes", common.HashLength) + return fmt.Errorf("%w: %d bytes", errTargetGasExceedsHashLength, common.HashLength) } if isBiggerThanHashLen(f.BaseFeeChangeDenominator) { - return fmt.Errorf("baseFeeChangeDenominator exceeds %d bytes", common.HashLength) + return fmt.Errorf("%w: %d bytes", errBaseFeeChangeDenominatorExceedsHashLength, common.HashLength) } if isBiggerThanHashLen(f.MinBlockGasCost) { - return fmt.Errorf("minBlockGasCost exceeds %d bytes", common.HashLength) + return fmt.Errorf("%w: %d bytes", errMinBlockGasCostExceedsHashLength, common.HashLength) } if isBiggerThanHashLen(f.MaxBlockGasCost) { - return fmt.Errorf("maxBlockGasCost exceeds %d bytes", common.HashLength) + return fmt.Errorf("%w: %d bytes", errMaxBlockGasCostExceedsHashLength, common.HashLength) } if isBiggerThanHashLen(f.BlockGasCostStep) { - return fmt.Errorf("blockGasCostStep exceeds %d bytes", common.HashLength) + return fmt.Errorf("%w: %d bytes", errBlockGasCostStepExceedsHashLength, common.HashLength) } return nil } diff --git a/commontype/fee_config_test.go b/commontype/fee_config_test.go index ea2a3381df..cc5426b16b 100644 --- a/commontype/fee_config_test.go +++ b/commontype/fee_config_test.go @@ -12,9 +12,9 @@ import ( func TestVerify(t *testing.T) { tests := []struct { - name string - config *FeeConfig - expectedError string + name string + config *FeeConfig + wantError error }{ { name: "nil gasLimit in FeeConfig", @@ -30,42 +30,42 @@ func TestVerify(t *testing.T) { MaxBlockGasCost: big.NewInt(1_000_000), BlockGasCostStep: big.NewInt(200_000), }, - expectedError: "gasLimit cannot be nil", + wantError: ErrGasLimitNil, }, { - name: "invalid GasLimit in FeeConfig", - config: func() *FeeConfig { c := ValidTestFeeConfig; c.GasLimit = big.NewInt(0); return &c }(), - expectedError: "gasLimit = 0 cannot be less than or equal to 0", + name: "invalid GasLimit in FeeConfig", + config: func() *FeeConfig { c := ValidTestFeeConfig; c.GasLimit = big.NewInt(0); return &c }(), + wantError: ErrGasLimitTooLow, }, { - name: "invalid TargetBlockRate in FeeConfig", - config: func() *FeeConfig { c := ValidTestFeeConfig; c.TargetBlockRate = 0; return &c }(), - expectedError: "targetBlockRate = 0 cannot be less than or equal to 0", + name: "invalid TargetBlockRate in FeeConfig", + config: func() *FeeConfig { c := ValidTestFeeConfig; c.TargetBlockRate = 0; return &c }(), + wantError: errTargetBlockRateTooLow, }, { - name: "invalid MinBaseFee in FeeConfig", - config: func() *FeeConfig { c := ValidTestFeeConfig; c.MinBaseFee = big.NewInt(-1); return &c }(), - expectedError: "minBaseFee = -1 cannot be less than 0", + name: "invalid MinBaseFee in FeeConfig", + config: func() *FeeConfig { c := ValidTestFeeConfig; c.MinBaseFee = big.NewInt(-1); return &c }(), + wantError: errMinBaseFeeNegative, }, { - name: "invalid TargetGas in FeeConfig", - config: func() *FeeConfig { c := ValidTestFeeConfig; c.TargetGas = big.NewInt(0); return &c }(), - expectedError: "targetGas = 0 cannot be less than or equal to 0", + name: "invalid TargetGas in FeeConfig", + config: func() *FeeConfig { c := ValidTestFeeConfig; c.TargetGas = big.NewInt(0); return &c }(), + wantError: errTargetGasTooLow, }, { - name: "invalid BaseFeeChangeDenominator in FeeConfig", - config: func() *FeeConfig { c := ValidTestFeeConfig; c.BaseFeeChangeDenominator = big.NewInt(0); return &c }(), - expectedError: "baseFeeChangeDenominator = 0 cannot be less than or equal to 0", + name: "invalid BaseFeeChangeDenominator in FeeConfig", + config: func() *FeeConfig { c := ValidTestFeeConfig; c.BaseFeeChangeDenominator = big.NewInt(0); return &c }(), + wantError: errBaseFeeChangeDenominatorTooLow, }, { - name: "invalid MinBlockGasCost in FeeConfig", - config: func() *FeeConfig { c := ValidTestFeeConfig; c.MinBlockGasCost = big.NewInt(-1); return &c }(), - expectedError: "minBlockGasCost = -1 cannot be less than 0", + name: "invalid MinBlockGasCost in FeeConfig", + config: func() *FeeConfig { c := ValidTestFeeConfig; c.MinBlockGasCost = big.NewInt(-1); return &c }(), + wantError: errMinBlockGasCostNegative, }, { - name: "valid FeeConfig", - config: &ValidTestFeeConfig, - expectedError: "", + name: "valid FeeConfig", + config: &ValidTestFeeConfig, + wantError: nil, }, { name: "MinBlockGasCost bigger than MaxBlockGasCost in FeeConfig", @@ -75,24 +75,19 @@ func TestVerify(t *testing.T) { c.MaxBlockGasCost = big.NewInt(1) return &c }(), - expectedError: "minBlockGasCost = 2 cannot be greater than maxBlockGasCost = 1", + wantError: errMinBlockGasCostTooHigh, }, { - name: "invalid BlockGasCostStep in FeeConfig", - config: func() *FeeConfig { c := ValidTestFeeConfig; c.BlockGasCostStep = big.NewInt(-1); return &c }(), - expectedError: "blockGasCostStep = -1 cannot be less than 0", + name: "invalid BlockGasCostStep in FeeConfig", + config: func() *FeeConfig { c := ValidTestFeeConfig; c.BlockGasCostStep = big.NewInt(-1); return &c }(), + wantError: errBlockGasCostStepNegative, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { err := test.config.Verify() - if test.expectedError == "" { - require.NoError(t, err) - } else { - require.Error(t, err) - require.Contains(t, err.Error(), test.expectedError) - } + require.ErrorIs(t, err, test.wantError) }) } } diff --git a/network/network_test.go b/network/network_test.go index 9ea30e9cdf..117816f17d 100644 --- a/network/network_test.go +++ b/network/network_test.go @@ -245,7 +245,7 @@ func TestRequestRequestsRoutingAndResponse(t *testing.T) { } // ensure empty nodeID is not allowed - err = net.SendAppRequest(context.Background(), ids.EmptyNodeID, []byte("hello there"), nil) + err = net.SendAppRequest(t.Context(), ids.EmptyNodeID, []byte("hello there"), nil) require.ErrorIs(t, err, errEmptyNodeID) } @@ -561,7 +561,7 @@ func TestNetworkPropagatesRequestHandlerError(t *testing.T) { require.NoError(t, err) // Check that if the request handler returns an error, it is propagated as a fatal error. - err = clientNetwork.AppRequest(context.Background(), nodeID, requestID, time.Now().Add(time.Second), requestMessage) + err = clientNetwork.AppRequest(t.Context(), nodeID, requestID, time.Now().Add(time.Second), requestMessage) require.ErrorIs(t, err, errTest) } diff --git a/params/extras/config.go b/params/extras/config.go index 7bc9156945..bf1512afb5 100644 --- a/params/extras/config.go +++ b/params/extras/config.go @@ -276,27 +276,27 @@ func checkForks(forks []fork) error { // Non-optional forks must all be present in the chain config up to the last defined fork case lastFork.block == nil && lastFork.timestamp == nil && (cur.block != nil || cur.timestamp != nil): if cur.block != nil { - return fmt.Errorf("unsupported fork ordering: %v not enabled, but %v enabled at block %v", - lastFork.name, cur.name, cur.block) + return fmt.Errorf("%w: %v not enabled, but %v enabled at block %v", + errUnsupportedForkOrdering, lastFork.name, cur.name, cur.block) } else { - return fmt.Errorf("unsupported fork ordering: %v not enabled, but %v enabled at timestamp %v", - lastFork.name, cur.name, cur.timestamp) + return fmt.Errorf("%w: %v not enabled, but %v enabled at timestamp %v", + errUnsupportedForkOrdering, lastFork.name, cur.name, cur.timestamp) } // Fork (whether defined by block or timestamp) must follow the fork definition sequence case (lastFork.block != nil && cur.block != nil) || (lastFork.timestamp != nil && cur.timestamp != nil): if lastFork.block != nil && lastFork.block.Cmp(cur.block) > 0 { - return fmt.Errorf("unsupported fork ordering: %v enabled at block %v, but %v enabled at block %v", - lastFork.name, lastFork.block, cur.name, cur.block) + return fmt.Errorf("%w: %v enabled at block %v, but %v enabled at block %v", + errUnsupportedForkOrdering, lastFork.name, lastFork.block, cur.name, cur.block) } else if lastFork.timestamp != nil && *lastFork.timestamp > *cur.timestamp { - return fmt.Errorf("unsupported fork ordering: %v enabled at timestamp %v, but %v enabled at timestamp %v", - lastFork.name, lastFork.timestamp, cur.name, cur.timestamp) + return fmt.Errorf("%w: %v enabled at timestamp %v, but %v enabled at timestamp %v", + errUnsupportedForkOrdering, lastFork.name, lastFork.timestamp, cur.name, cur.timestamp) } // Timestamp based forks can follow block based ones, but not the other way around if lastFork.timestamp != nil && cur.block != nil { - return fmt.Errorf("unsupported fork ordering: %v used timestamp ordering, but %v reverted to block ordering", - lastFork.name, cur.name) + return fmt.Errorf("%w: %v used timestamp ordering, but %v reverted to block ordering", + errUnsupportedForkOrdering, lastFork.name, cur.name) } } } diff --git a/params/extras/config_test.go b/params/extras/config_test.go index c91508bae1..d4e9ff8d2f 100644 --- a/params/extras/config_test.go +++ b/params/extras/config_test.go @@ -11,7 +11,6 @@ import ( "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/upgrade" "github.com/ava-labs/libevm/common" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/ava-labs/subnet-evm/commontype" @@ -86,7 +85,7 @@ $`, for name, test := range tests { t.Run(name, func(t *testing.T) { got := test.config.Description() - assert.Regexp(t, test.wantRegex, got, "config description mismatch") + require.Regexp(t, test.wantRegex, got, "config description mismatch") }) } } @@ -106,8 +105,8 @@ func TestChainConfigVerify(t *testing.T) { } tests := map[string]struct { - config ChainConfig - errRegex string + config ChainConfig + wantError error }{ "invalid_feeconfig": { config: ChainConfig{ @@ -115,7 +114,7 @@ func TestChainConfigVerify(t *testing.T) { GasLimit: nil, }, }, - errRegex: "^invalid fee config: ", + wantError: commontype.ErrGasLimitNil, }, "invalid_precompile_upgrades": { // Also see precompile_config_test.go TestVerifyWithChainConfig* tests @@ -129,7 +128,7 @@ func TestChainConfigVerify(t *testing.T) { }, }, }, - errRegex: "^invalid precompile upgrades: ", + wantError: errPrecompileUpgradeInvalidDisable, }, "invalid_state_upgrades": { config: ChainConfig{ @@ -140,7 +139,7 @@ func TestChainConfigVerify(t *testing.T) { }, }, }, - errRegex: "^invalid state upgrades: ", + wantError: errStateUpgradeNilTimestamp, }, "invalid_network_upgrades": { config: ChainConfig{ @@ -150,7 +149,7 @@ func TestChainConfigVerify(t *testing.T) { }, AvalancheContext: AvalancheContext{SnowCtx: &snow.Context{}}, }, - errRegex: "^invalid network upgrades: ", + wantError: errCannotBeNil, }, "valid": { config: ChainConfig{ @@ -169,18 +168,14 @@ func TestChainConfigVerify(t *testing.T) { }, }}, }, + wantError: nil, }, } for name, test := range tests { t.Run(name, func(t *testing.T) { err := test.config.Verify() - if test.errRegex == "" { - assert.NoError(t, err) - } else { - require.Error(t, err) - assert.Regexp(t, test.errRegex, err.Error()) - } + require.ErrorIs(t, err, test.wantError) }) } } diff --git a/params/extras/network_upgrades.go b/params/extras/network_upgrades.go index d9ef14a350..4fd518d7d7 100644 --- a/params/extras/network_upgrades.go +++ b/params/extras/network_upgrades.go @@ -17,10 +17,12 @@ import ( ) var ( - errCannotBeNil = errors.New("timestamp cannot be nil") - unscheduledActivation = uint64(upgrade.UnscheduledActivationTime.Unix()) initiallyActiveTime = uint64(upgrade.InitiallyActiveTime.Unix()) + + errCannotBeNil = errors.New("timestamp cannot be nil") + errTimestampTooEarly = errors.New("provided timestamp must be greater than or equal to the default timestamp") + errUnsupportedForkOrdering = errors.New("unsupported fork ordering") ) // NetworkUpgrades contains timestamps that enable network upgrades. @@ -242,7 +244,7 @@ func verifyWithDefault(configTimestamp *uint64, defaultTimestamp *uint64) error } if *configTimestamp < *defaultTimestamp { - return fmt.Errorf("provided timestamp (%d) must be greater than or equal to the default timestamp (%d)", *configTimestamp, *defaultTimestamp) + return fmt.Errorf("%w: provided timestamp %d, default timestamp %d", errTimestampTooEarly, *configTimestamp, *defaultTimestamp) } return nil } diff --git a/params/extras/network_upgrades_test.go b/params/extras/network_upgrades_test.go index c3088ad696..3f03958743 100644 --- a/params/extras/network_upgrades_test.go +++ b/params/extras/network_upgrades_test.go @@ -206,7 +206,7 @@ func TestVerifyNetworkUpgrades(t *testing.T) { name string upgrades *NetworkUpgrades avagoUpgrades upgrade.Config - valid bool + wantError error }{ { name: "Invalid_Durango_nil_upgrade", @@ -215,7 +215,7 @@ func TestVerifyNetworkUpgrades(t *testing.T) { DurangoTimestamp: nil, }, avagoUpgrades: upgrade.Mainnet, - valid: false, + wantError: errCannotBeNil, }, { name: "Invalid_Subnet-EVM_non-zero", @@ -224,7 +224,7 @@ func TestVerifyNetworkUpgrades(t *testing.T) { DurangoTimestamp: utils.NewUint64(2), }, avagoUpgrades: upgrade.Mainnet, - valid: false, + wantError: errTimestampTooEarly, }, { name: "Invalid_Durango_before_default_upgrade", @@ -233,7 +233,7 @@ func TestVerifyNetworkUpgrades(t *testing.T) { DurangoTimestamp: utils.NewUint64(1), }, avagoUpgrades: upgrade.Mainnet, - valid: false, + wantError: errTimestampTooEarly, }, { name: "Invalid_Mainnet_Durango_reconfigured_to_Fuji", @@ -242,7 +242,7 @@ func TestVerifyNetworkUpgrades(t *testing.T) { DurangoTimestamp: utils.TimeToNewUint64(upgrade.GetConfig(constants.FujiID).DurangoTime), }, avagoUpgrades: upgrade.Mainnet, - valid: false, + wantError: errTimestampTooEarly, }, { name: "Valid_Fuji_Durango_reconfigured_to_Mainnet", @@ -251,7 +251,7 @@ func TestVerifyNetworkUpgrades(t *testing.T) { DurangoTimestamp: utils.TimeToNewUint64(upgrade.GetConfig(constants.MainnetID).DurangoTime), }, avagoUpgrades: upgrade.Fuji, - valid: false, + wantError: errCannotBeNil, // Etna is required but not specified }, { name: "Invalid_Etna_nil", @@ -261,7 +261,7 @@ func TestVerifyNetworkUpgrades(t *testing.T) { EtnaTimestamp: nil, }, avagoUpgrades: upgrade.Mainnet, - valid: false, + wantError: errCannotBeNil, }, { name: "Invalid_Etna_before_Durango", @@ -271,7 +271,7 @@ func TestVerifyNetworkUpgrades(t *testing.T) { EtnaTimestamp: utils.TimeToNewUint64(upgrade.Mainnet.DurangoTime.Add(-1)), }, avagoUpgrades: upgrade.Mainnet, - valid: false, + wantError: errTimestampTooEarly, }, { name: "Valid_Granite_After_nil_Fortuna", @@ -283,26 +283,22 @@ func TestVerifyNetworkUpgrades(t *testing.T) { GraniteTimestamp: utils.TimeToNewUint64(upgrade.Fuji.GraniteTime), }, avagoUpgrades: upgradetest.GetConfig(upgradetest.Granite), - valid: true, + wantError: nil, }, } for _, test := range testcases { t.Run(test.name, func(t *testing.T) { err := test.upgrades.verifyNetworkUpgrades(test.avagoUpgrades) - if test.valid { - require.NoError(t, err) - } else { - require.Error(t, err) - } + require.ErrorIs(t, err, test.wantError) }) } } func TestForkOrder(t *testing.T) { testcases := []struct { - name string - upgrades *NetworkUpgrades - expectedErr bool + name string + upgrades *NetworkUpgrades + wantError error }{ { name: "ValidNetworkUpgrades", @@ -310,7 +306,7 @@ func TestForkOrder(t *testing.T) { SubnetEVMTimestamp: utils.NewUint64(0), DurangoTimestamp: utils.NewUint64(2), }, - expectedErr: false, + wantError: nil, }, { name: "Invalid order", @@ -318,17 +314,13 @@ func TestForkOrder(t *testing.T) { SubnetEVMTimestamp: utils.NewUint64(1), DurangoTimestamp: utils.NewUint64(0), }, - expectedErr: true, + wantError: errUnsupportedForkOrdering, }, } for _, test := range testcases { t.Run(test.name, func(t *testing.T) { err := checkForks(test.upgrades.forkOrder()) - if test.expectedErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } + require.ErrorIs(t, err, test.wantError) }) } } diff --git a/params/extras/precompile_config_test.go b/params/extras/precompile_config_test.go index a02a20afb7..6931481362 100644 --- a/params/extras/precompile_config_test.go +++ b/params/extras/precompile_config_test.go @@ -12,6 +12,7 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/subnet-evm/commontype" + "github.com/ava-labs/subnet-evm/precompile/allowlist" "github.com/ava-labs/subnet-evm/precompile/contracts/deployerallowlist" "github.com/ava-labs/subnet-evm/precompile/contracts/feemanager" "github.com/ava-labs/subnet-evm/precompile/contracts/nativeminter" @@ -53,7 +54,7 @@ func TestVerifyWithChainConfig(t *testing.T) { }, ) err = badConfig.Verify() - require.ErrorContains(t, err, "config block timestamp (5) <= previous timestamp (5) of same key") + require.ErrorIs(t, err, errPrecompileUpgradeSameKeyTimestampNotStrictly) // cannot enable a precompile without disabling it first. badConfig = *config @@ -64,7 +65,7 @@ func TestVerifyWithChainConfig(t *testing.T) { }, ) err = badConfig.Verify() - require.ErrorContains(t, err, "disable should be [true]") + require.ErrorIs(t, err, errPrecompileUpgradeInvalidDisable) } func TestVerifyWithChainConfigAtNilTimestamp(t *testing.T) { @@ -93,7 +94,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { tests := []struct { name string upgrades []PrecompileUpgrade - expectedError string + expectedError error }{ { name: "enable and disable tx allow list", @@ -105,7 +106,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { Config: txallowlist.NewDisableConfig(utils.NewUint64(2)), }, }, - expectedError: "", + expectedError: nil, }, { name: "invalid allow list config in tx allowlist", @@ -120,7 +121,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { Config: txallowlist.NewConfig(utils.NewUint64(3), admins, admins, admins), }, }, - expectedError: "cannot set address", + expectedError: allowlist.ErrAdminAndEnabledAddress, }, { name: "invalid initial fee manager config", @@ -134,7 +135,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { }()), }, }, - expectedError: "gasLimit = -1 cannot be less than or equal to 0", + expectedError: commontype.ErrGasLimitTooLow, }, { name: "invalid initial fee manager config gas limit 0", @@ -148,7 +149,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { }()), }, }, - expectedError: "gasLimit = 0 cannot be less than or equal to 0", + expectedError: commontype.ErrGasLimitTooLow, }, { name: "different upgrades are allowed to configure same timestamp for different precompiles", @@ -160,7 +161,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { Config: feemanager.NewConfig(utils.NewUint64(1), admins, nil, nil, nil), }, }, - expectedError: "", + expectedError: nil, }, { name: "different upgrades must be monotonically increasing", @@ -172,7 +173,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { Config: feemanager.NewConfig(utils.NewUint64(1), admins, nil, nil, nil), }, }, - expectedError: "config block timestamp (1) < previous timestamp (2)", + expectedError: errPrecompileUpgradeTimestampNotMonotonic, }, { name: "upgrades with same keys are not allowed to configure same timestamp for same precompiles", @@ -184,7 +185,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { Config: txallowlist.NewDisableConfig(utils.NewUint64(1)), }, }, - expectedError: "config block timestamp (1) <= previous timestamp (1) of same key", + expectedError: errPrecompileUpgradeSameKeyTimestampNotStrictly, }, } for _, tt := range tests { @@ -196,11 +197,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { config.PrecompileUpgrades = tt.upgrades err := config.Verify() - if tt.expectedError == "" { - require.NoError(err) - } else { - require.ErrorContains(err, tt.expectedError) - } + require.ErrorIs(err, tt.expectedError) }) } } @@ -210,14 +207,14 @@ func TestVerifyPrecompiles(t *testing.T) { tests := []struct { name string precompiles Precompiles - expectedError string + expectedError error }{ { name: "invalid allow list config in tx allowlist", precompiles: Precompiles{ txallowlist.ConfigKey: txallowlist.NewConfig(utils.NewUint64(3), admins, admins, admins), }, - expectedError: "cannot set address", + expectedError: allowlist.ErrAdminAndEnabledAddress, }, { name: "invalid initial fee manager config", @@ -229,7 +226,7 @@ func TestVerifyPrecompiles(t *testing.T) { return &feeConfig }()), }, - expectedError: "gasLimit = -1 cannot be less than or equal to 0", + expectedError: commontype.ErrGasLimitTooLow, }, } for _, tt := range tests { @@ -241,11 +238,7 @@ func TestVerifyPrecompiles(t *testing.T) { config.GenesisPrecompiles = tt.precompiles err := config.Verify() - if tt.expectedError == "" { - require.NoError(err) - } else { - require.ErrorContains(err, tt.expectedError) - } + require.ErrorIs(err, tt.expectedError) }) } } @@ -269,7 +262,7 @@ func TestVerifyRequiresSortedTimestamps(t *testing.T) { // block timestamps must be monotonically increasing, so this config is invalid err := config.Verify() - require.ErrorContains(t, err, "config block timestamp (1) < previous timestamp (2)") + require.ErrorIs(t, err, errPrecompileUpgradeTimestampNotMonotonic) } func TestGetPrecompileConfig(t *testing.T) { diff --git a/params/extras/precompile_upgrade.go b/params/extras/precompile_upgrade.go index d60a86f3cd..25f1f838ef 100644 --- a/params/extras/precompile_upgrade.go +++ b/params/extras/precompile_upgrade.go @@ -17,7 +17,13 @@ import ( ethparams "github.com/ava-labs/libevm/params" ) -var errNoKey = errors.New("PrecompileUpgrade cannot be empty") +var ( + errNoKey = errors.New("PrecompileUpgrade cannot be empty") + errPrecompileUpgradeNilTimestamp = errors.New("precompile upgrade block timestamp cannot be nil") + errPrecompileUpgradeTimestampNotMonotonic = errors.New("precompile upgrade config block timestamp must be greater than or equal to previous timestamp") + errPrecompileUpgradeInvalidDisable = errors.New("precompile upgrade disable value is invalid") + errPrecompileUpgradeSameKeyTimestampNotStrictly = errors.New("precompile upgrade config block timestamp for same key must be strictly greater than previous timestamp") +) // PrecompileUpgrade is a helper struct embedded in UpgradeConfig. // It is used to unmarshal the json into the correct precompile config type @@ -118,21 +124,21 @@ func (c *ChainConfig) verifyPrecompileUpgrades() error { upgradeTimestamp := upgrade.Timestamp() if upgradeTimestamp == nil { - return fmt.Errorf("PrecompileUpgrade (%s) at [%d]: block timestamp cannot be nil ", key, i) + return fmt.Errorf("%w: PrecompileUpgrade (%s) at [%d]", errPrecompileUpgradeNilTimestamp, key, i) } // Verify specified timestamps are monotonically increasing across all precompile keys. // Note: It is OK for multiple configs of DIFFERENT keys to specify the same timestamp. if previousUpgradeTimestamp != nil && *upgradeTimestamp < *previousUpgradeTimestamp { - return fmt.Errorf("PrecompileUpgrade (%s) at [%d]: config block timestamp (%v) < previous timestamp (%v)", key, i, *upgradeTimestamp, *previousUpgradeTimestamp) + return fmt.Errorf("%w: PrecompileUpgrade (%s) at [%d] has timestamp %v, previous timestamp %v", errPrecompileUpgradeTimestampNotMonotonic, key, i, *upgradeTimestamp, *previousUpgradeTimestamp) } if disabled == upgrade.IsDisabled() { - return fmt.Errorf("PrecompileUpgrade (%s) at [%d]: disable should be [%v]", key, i, !disabled) + return fmt.Errorf("%w: PrecompileUpgrade (%s) at [%d], disable should be %v", errPrecompileUpgradeInvalidDisable, key, i, !disabled) } // Verify specified timestamps are monotonically increasing across same precompile keys. // Note: It is NOT OK for multiple configs of the SAME key to specify the same timestamp. if lastTimestamp != nil && *upgradeTimestamp <= *lastTimestamp { - return fmt.Errorf("PrecompileUpgrade (%s) at [%d]: config block timestamp (%v) <= previous timestamp (%v) of same key", key, i, *upgradeTimestamp, *lastTimestamp) + return fmt.Errorf("%w: PrecompileUpgrade (%s) at [%d] has timestamp %v, previous timestamp of same key %v", errPrecompileUpgradeSameKeyTimestampNotStrictly, key, i, *upgradeTimestamp, *lastTimestamp) } if err := upgrade.Verify(c); err != nil { diff --git a/params/extras/precompile_upgrade_test.go b/params/extras/precompile_upgrade_test.go index 8e00e75022..02f7bd84dd 100644 --- a/params/extras/precompile_upgrade_test.go +++ b/params/extras/precompile_upgrade_test.go @@ -25,13 +25,13 @@ func TestVerifyUpgradeConfig(t *testing.T) { } type test struct { - upgrades []PrecompileUpgrade - expectedErrorString string + upgrades []PrecompileUpgrade + wantError error } tests := map[string]test{ "upgrade bytes conflicts with genesis (re-enable without disable)": { - expectedErrorString: "disable should be [true]", + wantError: errPrecompileUpgradeInvalidDisable, upgrades: []PrecompileUpgrade{ { Config: txallowlist.NewConfig(utils.NewUint64(2), admins, nil, nil), @@ -39,7 +39,7 @@ func TestVerifyUpgradeConfig(t *testing.T) { }, }, "upgrade bytes conflicts with genesis (disable before enable)": { - expectedErrorString: "config block timestamp (0) <= previous timestamp (1) of same key", + wantError: errPrecompileUpgradeSameKeyTimestampNotStrictly, upgrades: []PrecompileUpgrade{ { Config: txallowlist.NewDisableConfig(utils.NewUint64(0)), @@ -47,7 +47,7 @@ func TestVerifyUpgradeConfig(t *testing.T) { }, }, "upgrade bytes conflicts with genesis (disable same time as enable)": { - expectedErrorString: "config block timestamp (1) <= previous timestamp (1) of same key", + wantError: errPrecompileUpgradeSameKeyTimestampNotStrictly, upgrades: []PrecompileUpgrade{ { Config: txallowlist.NewDisableConfig(utils.NewUint64(1)), @@ -64,16 +64,17 @@ func TestVerifyUpgradeConfig(t *testing.T) { // verify with the upgrades from the test chainConfig.UpgradeConfig.PrecompileUpgrades = tt.upgrades err := chainConfig.Verify() - - if tt.expectedErrorString != "" { - require.ErrorContains(t, err, tt.expectedErrorString) - } else { - require.NoError(t, err) - } + require.ErrorIs(t, err, tt.wantError) }) } } +type upgradeCompatibilityTest struct { + configs []*UpgradeConfig + startTimestamps []uint64 + expectedErrorString string +} + func TestCheckCompatibleUpgradeConfigs(t *testing.T) { admins := []common.Address{{1}} chainConfig := &ChainConfig{} @@ -271,12 +272,6 @@ func TestCheckCompatibleUpgradeConfigs(t *testing.T) { } } -type upgradeCompatibilityTest struct { - configs []*UpgradeConfig - startTimestamps []uint64 - expectedErrorString string -} - func (tt *upgradeCompatibilityTest) run(t *testing.T, chainConfig ChainConfig) { // apply all the upgrade bytes specified in order for i, upgrade := range tt.configs { @@ -294,7 +289,7 @@ func (tt *upgradeCompatibilityTest) run(t *testing.T, chainConfig ChainConfig) { } if tt.expectedErrorString != "" { - require.ErrorContains(t, err, tt.expectedErrorString) + require.ErrorContains(t, err, tt.expectedErrorString) //nolint:forbidigo // external libevm error } else { require.Nil(t, err, "expecting checkConfigCompatible call %d to return nil", i+1) } diff --git a/params/extras/state_upgrade.go b/params/extras/state_upgrade.go index 530e0b8046..12a23323a1 100644 --- a/params/extras/state_upgrade.go +++ b/params/extras/state_upgrade.go @@ -4,6 +4,7 @@ package extras import ( + "errors" "fmt" "reflect" @@ -14,6 +15,12 @@ import ( ethparams "github.com/ava-labs/libevm/params" ) +var ( + errStateUpgradeNilTimestamp = errors.New("state upgrade config block timestamp cannot be nil") + errStateUpgradeTimestampZero = errors.New("state upgrade config block timestamp must be greater than 0") + errStateUpgradeTimestampNotMonotonic = errors.New("state upgrade config block timestamp must be greater than previous timestamp") +) + // StateUpgrade describes the modifications to be made to the state during // a state upgrade. type StateUpgrade struct { @@ -42,16 +49,16 @@ func (c *ChainConfig) verifyStateUpgrades() error { for i, upgrade := range c.StateUpgrades { upgradeTimestamp := upgrade.BlockTimestamp if upgradeTimestamp == nil { - return fmt.Errorf("StateUpgrade[%d]: config block timestamp cannot be nil ", i) + return fmt.Errorf("%w: StateUpgrade[%d]", errStateUpgradeNilTimestamp, i) } // Verify the upgrade's timestamp is equal 0 (to avoid confusion with genesis). if *upgradeTimestamp == 0 { - return fmt.Errorf("StateUpgrade[%d]: config block timestamp (%v) must be greater than 0", i, *upgradeTimestamp) + return fmt.Errorf("%w: StateUpgrade[%d] has timestamp %v", errStateUpgradeTimestampZero, i, *upgradeTimestamp) } // Verify specified timestamps are strictly monotonically increasing. if previousUpgradeTimestamp != nil && *upgradeTimestamp <= *previousUpgradeTimestamp { - return fmt.Errorf("StateUpgrade[%d]: config block timestamp (%v) <= previous timestamp (%v)", i, *upgradeTimestamp, *previousUpgradeTimestamp) + return fmt.Errorf("%w: StateUpgrade[%d] has timestamp %v, previous timestamp %v", errStateUpgradeTimestampNotMonotonic, i, *upgradeTimestamp, *previousUpgradeTimestamp) } previousUpgradeTimestamp = upgradeTimestamp } diff --git a/params/extras/state_upgrade_test.go b/params/extras/state_upgrade_test.go index edaecebc6c..f2a3da9934 100644 --- a/params/extras/state_upgrade_test.go +++ b/params/extras/state_upgrade_test.go @@ -23,9 +23,9 @@ func TestVerifyStateUpgrades(t *testing.T) { }, } tests := []struct { - name string - upgrades []StateUpgrade - expectedError string + name string + upgrades []StateUpgrade + wantError error }{ { name: "valid upgrade", @@ -33,6 +33,7 @@ func TestVerifyStateUpgrades(t *testing.T) { {BlockTimestamp: utils.NewUint64(1), StateUpgradeAccounts: modifiedAccounts}, {BlockTimestamp: utils.NewUint64(2), StateUpgradeAccounts: modifiedAccounts}, }, + wantError: nil, }, { name: "upgrade block timestamp is not strictly increasing", @@ -40,7 +41,7 @@ func TestVerifyStateUpgrades(t *testing.T) { {BlockTimestamp: utils.NewUint64(1), StateUpgradeAccounts: modifiedAccounts}, {BlockTimestamp: utils.NewUint64(1), StateUpgradeAccounts: modifiedAccounts}, }, - expectedError: "config block timestamp (1) <= previous timestamp (1)", + wantError: errStateUpgradeTimestampNotMonotonic, }, { name: "upgrade block timestamp decreases", @@ -48,14 +49,14 @@ func TestVerifyStateUpgrades(t *testing.T) { {BlockTimestamp: utils.NewUint64(2), StateUpgradeAccounts: modifiedAccounts}, {BlockTimestamp: utils.NewUint64(1), StateUpgradeAccounts: modifiedAccounts}, }, - expectedError: "config block timestamp (1) <= previous timestamp (2)", + wantError: errStateUpgradeTimestampNotMonotonic, }, { name: "upgrade block timestamp is zero", upgrades: []StateUpgrade{ {BlockTimestamp: utils.NewUint64(0), StateUpgradeAccounts: modifiedAccounts}, }, - expectedError: "config block timestamp (0) must be greater than 0", + wantError: errStateUpgradeTimestampZero, }, } for _, tt := range tests { @@ -67,11 +68,7 @@ func TestVerifyStateUpgrades(t *testing.T) { config.StateUpgrades = tt.upgrades err := config.Verify() - if tt.expectedError == "" { - require.NoError(err) - } else { - require.ErrorContains(err, tt.expectedError) - } + require.ErrorIs(err, tt.wantError) }) } } diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index eb1bfd15b2..99e1f8c0dd 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -148,6 +148,7 @@ var ( errInitializingLogger = errors.New("failed to initialize logger") errShuttingDownVM = errors.New("shutting down VM") errPathStateUnsupported = errors.New("path state scheme is not supported") + errVerifyGenesis = errors.New("failed to verify genesis") errFirewoodSnapshotCacheDisabled = errors.New("snapshot cache must be disabled for Firewood") errFirewoodOfflinePruningUnsupported = errors.New("offline pruning is not supported for Firewood") errFirewoodStateSyncUnsupported = errors.New("state sync is not yet supported for Firewood") @@ -567,7 +568,7 @@ func parseGenesis(ctx *snow.Context, genesisBytes []byte, upgradeBytes []byte, a } if err := g.Verify(); err != nil { - return nil, fmt.Errorf("failed to verify genesis: %w", err) + return nil, fmt.Errorf("%w: %w", errVerifyGenesis, err) } // Align all the Ethereum upgrades to the Avalanche upgrades diff --git a/plugin/evm/vm_test.go b/plugin/evm/vm_test.go index 3896d1dc13..0d9874fb4a 100644 --- a/plugin/evm/vm_test.go +++ b/plugin/evm/vm_test.go @@ -3166,7 +3166,7 @@ func TestGenesisGasLimit(t *testing.T) { vm := &VM{} err = vm.Initialize(t.Context(), ctx, db, genesisBytes, []byte{}, []byte{}, []*commonEng.Fx{}, &enginetest.Sender{}) // This should fail because the gas limit is different from the fee config - require.ErrorContains(t, err, "failed to verify genesis") + require.ErrorIs(t, err, errVerifyGenesis) // This should succeed because the gas limit is the same as the fee config genesis.GasLimit = params.GetExtra(genesis.Config).FeeConfig.GasLimit.Uint64() @@ -3547,8 +3547,7 @@ func TestDelegatePrecompile_BehaviorAcrossUpgrades(t *testing.T) { // On subnet-evm, InvalidateExecution causes the transaction to be excluded from the block. // BuildBlock will create a block but it will fail verification because it's empty // and subnet-evm doesn't allow empty blocks. - require.Error(t, err, "BuildBlock should fail because it would create an empty block") - require.ErrorContains(t, err, "empty block", "Should fail with empty block error") + require.ErrorIs(t, err, errEmptyBlock) return } require.NoError(t, err) diff --git a/plugin/evm/vm_upgrade_bytes_test.go b/plugin/evm/vm_upgrade_bytes_test.go index fd656fbe3b..8d03e074a9 100644 --- a/plugin/evm/vm_upgrade_bytes_test.go +++ b/plugin/evm/vm_upgrade_bytes_test.go @@ -211,7 +211,7 @@ func TestNetworkUpgradesOverridden(t *testing.T) { upgradeJSON: newUpgradeBytesJSON, genesisJSON: tvm.config.genesisJSON, }) - require.ErrorContains(t, err, "mismatching Granite fork block timestamp") + require.ErrorContains(t, err, "mismatching Granite fork block timestamp") //nolint:forbidigo // uses upstream code } func mustMarshal(t *testing.T, v interface{}) string { diff --git a/precompile/allowlist/allowlisttest/test_allowlist_config.go b/precompile/allowlist/allowlisttest/test_allowlist_config.go index c9a3a1c323..780430863f 100644 --- a/precompile/allowlist/allowlisttest/test_allowlist_config.go +++ b/precompile/allowlist/allowlisttest/test_allowlist_config.go @@ -5,7 +5,6 @@ package allowlisttest import ( "encoding/json" - "errors" "testing" "github.com/ava-labs/libevm/common" @@ -58,7 +57,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: nil, EnabledAddresses: nil, }), - ExpectedError: errors.New("duplicate address in admin list"), + WantError: allowlist.ErrDuplicateAdminAddress, }, "invalid allow list config with duplicate enableds in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -66,7 +65,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: nil, EnabledAddresses: []common.Address{TestEnabledAddr, TestEnabledAddr}, }), - ExpectedError: errors.New("duplicate address in enabled list"), + WantError: allowlist.ErrDuplicateEnabledAddress, }, "invalid allow list config with duplicate managers in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -74,7 +73,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: []common.Address{TestManagerAddr, TestManagerAddr}, EnabledAddresses: nil, }), - ExpectedError: errors.New("duplicate address in manager list"), + WantError: allowlist.ErrDuplicateManagerAddress, }, "invalid allow list config with same admin and enabled in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -82,7 +81,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: nil, EnabledAddresses: []common.Address{TestAdminAddr}, }), - ExpectedError: errors.New("cannot set address as both admin and enabled"), + WantError: allowlist.ErrAdminAndEnabledAddress, }, "invalid allow list config with same admin and manager in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -90,7 +89,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: []common.Address{TestAdminAddr}, EnabledAddresses: nil, }), - ExpectedError: errors.New("cannot set address as both admin and manager"), + WantError: allowlist.ErrAdminAndManagerAddress, }, "invalid allow list config with same manager and enabled in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -98,7 +97,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: []common.Address{TestManagerAddr}, EnabledAddresses: []common.Address{TestManagerAddr}, }), - ExpectedError: errors.New("cannot set address as both enabled and manager"), + WantError: allowlist.ErrEnabledAndManagerAddress, }, "invalid allow list config with manager role before activation": { Config: mkConfigWithUpgradeAndAllowList(module, &allowlist.AllowListConfig{ @@ -113,7 +112,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] config.EXPECT().IsDurango(gomock.Any()).Return(false) return config }(), - ExpectedError: allowlist.ErrCannotAddManagersBeforeDurango, + WantError: allowlist.ErrCannotAddManagersBeforeDurango, }, "nil member allow list config in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -121,7 +120,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: nil, EnabledAddresses: nil, }), - ExpectedError: nil, + WantError: nil, }, "empty member allow list config in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -129,7 +128,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: []common.Address{}, EnabledAddresses: []common.Address{}, }), - ExpectedError: nil, + WantError: nil, }, "valid allow list config in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -137,7 +136,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: []common.Address{TestManagerAddr}, EnabledAddresses: []common.Address{TestEnabledAddr}, }), - ExpectedError: nil, + WantError: nil, }, } } diff --git a/precompile/allowlist/config.go b/precompile/allowlist/config.go index cb6403168d..910230624d 100644 --- a/precompile/allowlist/config.go +++ b/precompile/allowlist/config.go @@ -14,7 +14,15 @@ import ( "github.com/ava-labs/subnet-evm/precompile/precompileconfig" ) -var ErrCannotAddManagersBeforeDurango = errors.New("cannot add managers before Durango") +var ( + ErrAdminAndEnabledAddress = errors.New("cannot set address as both admin and enabled") + ErrAdminAndManagerAddress = errors.New("cannot set address as both admin and manager") + ErrCannotAddManagersBeforeDurango = errors.New("cannot add managers before Durango") + ErrDuplicateEnabledAddress = errors.New("duplicate address in enabled list") + ErrDuplicateAdminAddress = errors.New("duplicate address in admin list") + ErrDuplicateManagerAddress = errors.New("duplicate address in manager list") + ErrEnabledAndManagerAddress = errors.New("cannot set address as both enabled and manager") +) // AllowListConfig specifies the initial set of addresses with Admin or Enabled roles. type AllowListConfig struct { @@ -63,7 +71,7 @@ func (c *AllowListConfig) Verify(chainConfig precompileconfig.ChainConfig, upgra // check for duplicates in enabled list for _, enabledAddr := range c.EnabledAddresses { if _, ok := addressMap[enabledAddr]; ok { - return fmt.Errorf("duplicate address in enabled list: %s", enabledAddr) + return fmt.Errorf("%w: %s", ErrDuplicateEnabledAddress, enabledAddr) } addressMap[enabledAddr] = EnabledRole } @@ -72,9 +80,9 @@ func (c *AllowListConfig) Verify(chainConfig precompileconfig.ChainConfig, upgra for _, adminAddr := range c.AdminAddresses { if role, ok := addressMap[adminAddr]; ok { if role == AdminRole { - return fmt.Errorf("duplicate address in admin list: %s", adminAddr) + return fmt.Errorf("%w: %s", ErrDuplicateAdminAddress, adminAddr) } else { - return fmt.Errorf("cannot set address as both admin and enabled: %s", adminAddr) + return fmt.Errorf("%w: %s", ErrAdminAndEnabledAddress, adminAddr) } } addressMap[adminAddr] = AdminRole @@ -93,11 +101,11 @@ func (c *AllowListConfig) Verify(chainConfig precompileconfig.ChainConfig, upgra if role, ok := addressMap[managerAddr]; ok { switch role { case ManagerRole: - return fmt.Errorf("duplicate address in manager list: %s", managerAddr) + return fmt.Errorf("%w: %s", ErrDuplicateManagerAddress, managerAddr) case AdminRole: - return fmt.Errorf("cannot set address as both admin and manager: %s", managerAddr) + return fmt.Errorf("%w: %s", ErrAdminAndManagerAddress, managerAddr) case EnabledRole: - return fmt.Errorf("cannot set address as both enabled and manager: %s", managerAddr) + return fmt.Errorf("%w: %s", ErrEnabledAndManagerAddress, managerAddr) } } addressMap[managerAddr] = ManagerRole diff --git a/precompile/allowlist/unpack_pack_test.go b/precompile/allowlist/unpack_pack_test.go index 727e345dd7..77de0bba61 100644 --- a/precompile/allowlist/unpack_pack_test.go +++ b/precompile/allowlist/unpack_pack_test.go @@ -57,7 +57,7 @@ func FuzzPackReadAllowlistTestSkipCheck(f *testing.F) { res, err := UnpackReadAllowListInput(b, true) oldRes, oldErr := OldUnpackReadAllowList(b) if oldErr != nil { - require.ErrorContains(err, oldErr.Error()) + require.ErrorIs(err, oldErr) } else { require.NoError(err) } @@ -125,7 +125,7 @@ func FuzzPackModifyAllowlistTestSkipCheck(f *testing.F) { res, err := UnpackModifyAllowListInput(b, AdminRole, true) oldRes, oldErr := OldUnpackModifyAllowList(b, AdminRole) if oldErr != nil { - require.ErrorContains(err, oldErr.Error()) + require.ErrorIs(err, oldErr) } else { require.NoError(err) } diff --git a/precompile/contracts/deployerallowlist/deployerallowlisttest/simulated_test.go b/precompile/contracts/deployerallowlist/deployerallowlisttest/simulated_test.go index d557cb6fbf..54241ae800 100644 --- a/precompile/contracts/deployerallowlist/deployerallowlisttest/simulated_test.go +++ b/precompile/contracts/deployerallowlist/deployerallowlisttest/simulated_test.go @@ -12,7 +12,6 @@ import ( "github.com/ava-labs/libevm/common" "github.com/ava-labs/libevm/core/types" - "github.com/ava-labs/libevm/core/vm" "github.com/ava-labs/libevm/crypto" "github.com/stretchr/testify/require" @@ -153,8 +152,8 @@ func TestDeployerAllowList(t *testing.T) { // Try to deploy via unprivileged user - should fail _, err := allowListTest.DeployContract(unprivileged) - // The error returned is a JSON Error rather than the vm.ErrExecutionReverted error - require.ErrorContains(t, err, vm.ErrExecutionReverted.Error()) + // The error returned is actually a JSON Error + require.ErrorContains(t, err, "execution reverted") //nolint:forbidigo // uses upstream code }, }, { diff --git a/precompile/contracts/feemanager/config_test.go b/precompile/contracts/feemanager/config_test.go index cf093a968f..1266a0dad5 100644 --- a/precompile/contracts/feemanager/config_test.go +++ b/precompile/contracts/feemanager/config_test.go @@ -4,7 +4,6 @@ package feemanager import ( - "errors" "math/big" "testing" @@ -37,12 +36,12 @@ func TestVerify(t *testing.T) { invalidFeeConfig.GasLimit = big.NewInt(0) tests := map[string]precompiletest.ConfigVerifyTest{ "invalid initial fee manager config": { - Config: NewConfig(utils.NewUint64(3), admins, nil, nil, &invalidFeeConfig), - ExpectedError: errors.New("gasLimit = 0 cannot be less than or equal to 0"), + Config: NewConfig(utils.NewUint64(3), admins, nil, nil, &invalidFeeConfig), + WantError: commontype.ErrGasLimitTooLow, }, "nil initial fee manager config": { - Config: NewConfig(utils.NewUint64(3), admins, nil, nil, &commontype.FeeConfig{}), - ExpectedError: errors.New("fee config gasLimit cannot be nil"), + Config: NewConfig(utils.NewUint64(3), admins, nil, nil, &commontype.FeeConfig{}), + WantError: commontype.ErrGasLimitNil, }, } allowlisttest.VerifyPrecompileWithAllowListTests(t, Module, tests) diff --git a/precompile/contracts/feemanager/unpack_pack_test.go b/precompile/contracts/feemanager/unpack_pack_test.go index 2f46409624..55b856c7dc 100644 --- a/precompile/contracts/feemanager/unpack_pack_test.go +++ b/precompile/contracts/feemanager/unpack_pack_test.go @@ -122,14 +122,14 @@ func TestPackGetFeeConfigOutput(t *testing.T) { t.Run(test.name, func(t *testing.T) { unpacked, err := UnpackGetFeeConfigOutput(test.input, test.skipLenCheck) if test.expectedErr != "" { - require.ErrorContains(t, err, test.expectedErr) + require.ErrorContains(t, err, test.expectedErr) //nolint:forbidigo // uses upstream code } else { require.NoError(t, err) require.True(t, test.expectedOutput.Equal(&unpacked), "not equal: expectedOutput %v, unpacked %v", test.expectedOutput, unpacked) } oldUnpacked, oldErr := OldUnpackFeeConfig(test.input) if test.expectedOldErr != "" { - require.ErrorContains(t, oldErr, test.expectedOldErr) + require.ErrorContains(t, oldErr, test.expectedOldErr) //nolint:forbidigo // uses upstream code } else { require.NoError(t, oldErr) require.True(t, test.expectedOutput.Equal(&oldUnpacked), "not equal: expectedOutput %v, oldUnpacked %v", test.expectedOutput, oldUnpacked) @@ -293,14 +293,14 @@ func TestPackSetFeeConfigInput(t *testing.T) { t.Run(test.name, func(t *testing.T) { unpacked, err := UnpackSetFeeConfigInput(test.input, test.strictMode) if test.expectedErr != "" { - require.ErrorContains(t, err, test.expectedErr) + require.ErrorContains(t, err, test.expectedErr) //nolint:forbidigo // uses upstream code } else { require.NoError(t, err) require.True(t, test.expectedOutput.Equal(&unpacked), "not equal: expectedOutput %v, unpacked %v", test.expectedOutput, unpacked) } oldUnpacked, oldErr := OldUnpackFeeConfig(test.input) if test.expectedOldErr != "" { - require.ErrorContains(t, oldErr, test.expectedOldErr) + require.ErrorContains(t, oldErr, test.expectedOldErr) //nolint:forbidigo // uses upstream code } else { require.NoError(t, oldErr) require.True(t, test.expectedOutput.Equal(&oldUnpacked), "not equal: expectedOutput %v, oldUnpacked %v", test.expectedOutput, oldUnpacked) @@ -326,7 +326,7 @@ func testOldPackGetFeeConfigOutputEqual(t *testing.T, feeConfig commontype.FeeCo input, err := OldPackFeeConfig(feeConfig) input2, err2 := PackGetFeeConfigOutput(feeConfig) if err != nil { - require.ErrorContains(t, err2, err.Error()) + require.ErrorIs(t, err2, err) return } require.NoError(t, err2) @@ -335,7 +335,7 @@ func testOldPackGetFeeConfigOutputEqual(t *testing.T, feeConfig commontype.FeeCo config, err := OldUnpackFeeConfig(input) unpacked, err2 := UnpackGetFeeConfigOutput(input, false) if err != nil { - require.ErrorContains(t, err2, err.Error()) + require.ErrorIs(t, err2, err) return } require.NoError(t, err2) @@ -357,7 +357,7 @@ func testOldPackGetLastChangedAtOutputEqual(t *testing.T, blockNumber *big.Int, value, err := OldUnpackGetLastChangedAtOutput(input) unpacked, err2 := UnpackGetFeeConfigLastChangedAtOutput(input) if err != nil { - require.ErrorContains(t, err2, err.Error()) + require.ErrorIs(t, err2, err) return } require.NoError(t, err2) @@ -374,7 +374,7 @@ func testOldPackSetFeeConfigInputEqual(t *testing.T, feeConfig commontype.FeeCon input, err := OldPackSetFeeConfig(feeConfig) input2, err2 := PackSetFeeConfig(feeConfig) if err != nil { - require.ErrorContains(t, err2, err.Error()) + require.ErrorIs(t, err2, err) return } require.NoError(t, err2) @@ -383,7 +383,7 @@ func testOldPackSetFeeConfigInputEqual(t *testing.T, feeConfig commontype.FeeCon value, err := OldUnpackFeeConfig(input) unpacked, err2 := UnpackSetFeeConfigInput(input, true) if err != nil { - require.ErrorContains(t, err2, err.Error()) + require.ErrorIs(t, err2, err) return } require.NoError(t, err2) diff --git a/precompile/contracts/nativeminter/config_test.go b/precompile/contracts/nativeminter/config_test.go index af7983dacc..ea8d427f1d 100644 --- a/precompile/contracts/nativeminter/config_test.go +++ b/precompile/contracts/nativeminter/config_test.go @@ -11,6 +11,7 @@ import ( "github.com/ava-labs/libevm/common/math" "go.uber.org/mock/gomock" + "github.com/ava-labs/subnet-evm/precompile/allowlist" "github.com/ava-labs/subnet-evm/precompile/allowlist/allowlisttest" "github.com/ava-labs/subnet-evm/precompile/precompileconfig" "github.com/ava-labs/subnet-evm/precompile/precompiletest" @@ -29,19 +30,19 @@ func TestVerify(t *testing.T) { config.EXPECT().IsDurango(gomock.Any()).Return(true).AnyTimes() return config }(), - ExpectedError: nil, + WantError: nil, }, "invalid allow list config in native minter allowlisttest": { - Config: NewConfig(utils.NewUint64(3), admins, admins, nil, nil), - ExpectedError: errors.New("cannot set address"), + Config: NewConfig(utils.NewUint64(3), admins, admins, nil, nil), + WantError: allowlist.ErrAdminAndEnabledAddress, }, "duplicate admins in config in native minter allowlisttest": { - Config: NewConfig(utils.NewUint64(3), append(admins, admins[0]), enableds, managers, nil), - ExpectedError: errors.New("duplicate address"), + Config: NewConfig(utils.NewUint64(3), append(admins, admins[0]), enableds, managers, nil), + WantError: allowlist.ErrDuplicateAdminAddress, }, "duplicate enableds in config in native minter allowlisttest": { - Config: NewConfig(utils.NewUint64(3), admins, append(enableds, enableds[0]), managers, nil), - ExpectedError: errors.New("duplicate address"), + Config: NewConfig(utils.NewUint64(3), admins, append(enableds, enableds[0]), managers, nil), + WantError: allowlist.ErrDuplicateEnabledAddress, }, "nil amount in native minter config": { Config: NewConfig(utils.NewUint64(3), admins, nil, nil, @@ -49,7 +50,7 @@ func TestVerify(t *testing.T) { common.HexToAddress("0x01"): math.NewHexOrDecimal256(123), common.HexToAddress("0x02"): nil, }), - ExpectedError: errors.New("initial mint cannot contain nil"), + WantError: errors.New("initial mint cannot contain nil"), }, "negative amount in native minter config": { Config: NewConfig(utils.NewUint64(3), admins, nil, nil, @@ -57,7 +58,7 @@ func TestVerify(t *testing.T) { common.HexToAddress("0x01"): math.NewHexOrDecimal256(123), common.HexToAddress("0x02"): math.NewHexOrDecimal256(-1), }), - ExpectedError: errors.New("initial mint cannot contain invalid amount"), + WantError: errors.New("initial mint cannot contain invalid amount"), }, } allowlisttest.VerifyPrecompileWithAllowListTests(t, Module, tests) diff --git a/precompile/contracts/nativeminter/unpack_pack_test.go b/precompile/contracts/nativeminter/unpack_pack_test.go index 88a530815a..2bc4d8b34e 100644 --- a/precompile/contracts/nativeminter/unpack_pack_test.go +++ b/precompile/contracts/nativeminter/unpack_pack_test.go @@ -104,7 +104,7 @@ func TestUnpackMintNativeCoinInput(t *testing.T) { t.Run(test.name, func(t *testing.T) { unpackedAddress, unpackedAmount, err := UnpackMintNativeCoinInput(test.input, test.strictMode) if test.expectedErr != "" { - require.ErrorContains(t, err, test.expectedErr) + require.ErrorContains(t, err, test.expectedErr) //nolint:forbidigo // uses upstream code } else { require.NoError(t, err) require.Equal(t, test.expectedAddr, unpackedAddress) @@ -112,7 +112,7 @@ func TestUnpackMintNativeCoinInput(t *testing.T) { } oldUnpackedAddress, oldUnpackedAmount, oldErr := OldUnpackMintNativeCoinInput(test.input) if test.expectedOldErr != "" { - require.ErrorContains(t, oldErr, test.expectedOldErr) + require.ErrorContains(t, oldErr, test.expectedOldErr) //nolint:forbidigo // uses upstream code } else { require.NoError(t, oldErr) require.Equal(t, test.expectedAddr, oldUnpackedAddress) @@ -134,7 +134,7 @@ func testOldPackMintNativeCoinEqual(t *testing.T, addr common.Address, amount *b input, err := OldPackMintNativeCoinInput(addr, amount) input2, err2 := PackMintNativeCoin(addr, amount) if err != nil { - require.ErrorContains(t, err2, err.Error()) + require.ErrorIs(t, err2, err) return } require.NoError(t, err2) @@ -144,7 +144,7 @@ func testOldPackMintNativeCoinEqual(t *testing.T, addr common.Address, amount *b to, assetAmount, err := OldUnpackMintNativeCoinInput(input) unpackedAddr, unpackedAmount, err2 := UnpackMintNativeCoinInput(input, true) if err != nil { - require.ErrorContains(t, err2, err.Error()) + require.ErrorIs(t, err2, err) return } require.NoError(t, err2) diff --git a/precompile/contracts/rewardmanager/config_test.go b/precompile/contracts/rewardmanager/config_test.go index dc069aafcf..c114a3a733 100644 --- a/precompile/contracts/rewardmanager/config_test.go +++ b/precompile/contracts/rewardmanager/config_test.go @@ -25,7 +25,7 @@ func TestVerify(t *testing.T) { AllowFeeRecipients: true, RewardAddress: common.HexToAddress("0x01"), }), - ExpectedError: ErrCannotEnableBothRewards, + WantError: ErrCannotEnableBothRewards, }, } allowlisttest.VerifyPrecompileWithAllowListTests(t, Module, tests) diff --git a/precompile/contracts/warp/config_test.go b/precompile/contracts/warp/config_test.go index e87ba56876..1c875af52f 100644 --- a/precompile/contracts/warp/config_test.go +++ b/precompile/contracts/warp/config_test.go @@ -16,12 +16,12 @@ import ( func TestVerify(t *testing.T) { tests := map[string]precompiletest.ConfigVerifyTest{ "quorum numerator less than minimum": { - Config: NewConfig(utils.NewUint64(3), WarpQuorumNumeratorMinimum-1, false), - ExpectedError: ErrInvalidQuorumRatio, + Config: NewConfig(utils.NewUint64(3), WarpQuorumNumeratorMinimum-1, false), + WantError: ErrInvalidQuorumRatio, }, "quorum numerator greater than quorum denominator": { - Config: NewConfig(utils.NewUint64(3), WarpQuorumDenominator+1, false), - ExpectedError: ErrInvalidQuorumRatio, + Config: NewConfig(utils.NewUint64(3), WarpQuorumDenominator+1, false), + WantError: ErrInvalidQuorumRatio, }, "default quorum numerator": { Config: NewDefaultConfig(utils.NewUint64(3)), @@ -39,7 +39,7 @@ func TestVerify(t *testing.T) { config.EXPECT().IsDurango(gomock.Any()).Return(false) return config }(), - ExpectedError: errWarpCannotBeActivated, + WantError: errWarpCannotBeActivated, }, } precompiletest.RunVerifyTests(t, tests) diff --git a/precompile/precompiletest/test_config.go b/precompile/precompiletest/test_config.go index 875019c67d..44c537fd63 100644 --- a/precompile/precompiletest/test_config.go +++ b/precompile/precompiletest/test_config.go @@ -15,9 +15,9 @@ import ( // ConfigVerifyTest is a test case for verifying a config type ConfigVerifyTest struct { - Config precompileconfig.Config - ChainConfig precompileconfig.ChainConfig - ExpectedError error + Config precompileconfig.Config + ChainConfig precompileconfig.ChainConfig + WantError error } // ConfigEqualTest is a test case for comparing two configs @@ -43,7 +43,7 @@ func RunVerifyTests(t *testing.T, tests map[string]ConfigVerifyTest) { chainConfig = mockChainConfig } err := test.Config.Verify(chainConfig) - require.ErrorIs(err, test.ExpectedError) + require.ErrorIs(err, test.WantError) }) } } From fbc5bb6f63e91a9450c2c60491c86b6331b8e2a0 Mon Sep 17 00:00:00 2001 From: Jonathan Oppenheimer Date: Tue, 25 Nov 2025 02:04:55 -0500 Subject: [PATCH 04/19] test: define nativeminter sentinel errors --- precompile/contracts/nativeminter/config.go | 12 +++++++++--- precompile/contracts/nativeminter/config_test.go | 5 ++--- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/precompile/contracts/nativeminter/config.go b/precompile/contracts/nativeminter/config.go index be35f974a7..8ee09cd39c 100644 --- a/precompile/contracts/nativeminter/config.go +++ b/precompile/contracts/nativeminter/config.go @@ -4,6 +4,7 @@ package nativeminter import ( + "errors" "fmt" "math/big" @@ -15,7 +16,12 @@ import ( "github.com/ava-labs/subnet-evm/utils" ) -var _ precompileconfig.Config = (*Config)(nil) +var ( + _ precompileconfig.Config = (*Config)(nil) + + errInitialMintNilAmount = errors.New("initial mint cannot contain nil amount") + errInitialMintInvalidAmount = errors.New("initial mint cannot contain invalid amount") +) // Config implements the precompileconfig.Config interface while adding in the // ContractNativeMinter specific precompile config. @@ -90,11 +96,11 @@ func (c *Config) Verify(chainConfig precompileconfig.ChainConfig) error { // ensure that all of the initial mint values in the map are non-nil positive values for addr, amount := range c.InitialMint { if amount == nil { - return fmt.Errorf("initial mint cannot contain nil amount for address %s", addr) + return fmt.Errorf("%w for address %s", errInitialMintNilAmount, addr) } bigIntAmount := (*big.Int)(amount) if bigIntAmount.Sign() < 1 { - return fmt.Errorf("initial mint cannot contain invalid amount %v for address %s", bigIntAmount, addr) + return fmt.Errorf("%w: amount %v for address %s", errInitialMintInvalidAmount, bigIntAmount, addr) } } return c.AllowListConfig.Verify(chainConfig, c.Upgrade) diff --git a/precompile/contracts/nativeminter/config_test.go b/precompile/contracts/nativeminter/config_test.go index ea8d427f1d..e6f40e0ec5 100644 --- a/precompile/contracts/nativeminter/config_test.go +++ b/precompile/contracts/nativeminter/config_test.go @@ -4,7 +4,6 @@ package nativeminter import ( - "errors" "testing" "github.com/ava-labs/libevm/common" @@ -50,7 +49,7 @@ func TestVerify(t *testing.T) { common.HexToAddress("0x01"): math.NewHexOrDecimal256(123), common.HexToAddress("0x02"): nil, }), - WantError: errors.New("initial mint cannot contain nil"), + WantError: errInitialMintNilAmount, }, "negative amount in native minter config": { Config: NewConfig(utils.NewUint64(3), admins, nil, nil, @@ -58,7 +57,7 @@ func TestVerify(t *testing.T) { common.HexToAddress("0x01"): math.NewHexOrDecimal256(123), common.HexToAddress("0x02"): math.NewHexOrDecimal256(-1), }), - WantError: errors.New("initial mint cannot contain invalid amount"), + WantError: errInitialMintInvalidAmount, }, } allowlisttest.VerifyPrecompileWithAllowListTests(t, Module, tests) From 2e3a48b23984c8800491e560c92c5562afbe74cd Mon Sep 17 00:00:00 2001 From: Jonathan Oppenheimer Date: Tue, 25 Nov 2025 02:21:58 -0500 Subject: [PATCH 05/19] test: use sentinel errors --- commontype/fee_config.go | 9 +++++---- commontype/fee_config_test.go | 2 +- precompile/allowlist/allowlisttest/test_allowlist.go | 8 ++++---- precompile/contract/contract.go | 11 +++++++++-- precompile/contracts/feemanager/contract_test.go | 3 +-- precompile/contracts/feemanager/unpack_pack_test.go | 4 ++-- 6 files changed, 22 insertions(+), 15 deletions(-) diff --git a/commontype/fee_config.go b/commontype/fee_config.go index d8e3d764e6..f2ca2e552a 100644 --- a/commontype/fee_config.go +++ b/commontype/fee_config.go @@ -14,8 +14,10 @@ import ( ) var ( - ErrGasLimitTooLow = errors.New("gasLimit cannot be less than or equal to 0") - ErrGasLimitNil = errors.New("gasLimit cannot be nil") + ErrGasLimitTooLow = errors.New("gasLimit cannot be less than or equal to 0") + ErrGasLimitNil = errors.New("gasLimit cannot be nil") + ErrMinBlockGasCostTooHigh = errors.New("minBlockGasCost cannot be greater than maxBlockGasCost") + errMinBaseFeeNil = errors.New("minBaseFee cannot be nil") errTargetGasNil = errors.New("targetGas cannot be nil") errBaseFeeChangeDenominatorNil = errors.New("baseFeeChangeDenominator cannot be nil") @@ -27,7 +29,6 @@ var ( errTargetGasTooLow = errors.New("targetGas cannot be less than or equal to 0") errBaseFeeChangeDenominatorTooLow = errors.New("baseFeeChangeDenominator cannot be less than or equal to 0") errMinBlockGasCostNegative = errors.New("minBlockGasCost cannot be less than 0") - errMinBlockGasCostTooHigh = errors.New("minBlockGasCost cannot be greater than maxBlockGasCost") errBlockGasCostStepNegative = errors.New("blockGasCostStep cannot be less than 0") errMaxBlockGasCostNotUint64 = errors.New("maxBlockGasCost is not a valid uint64") errGasLimitExceedsHashLength = errors.New("gasLimit exceeds hash length") @@ -121,7 +122,7 @@ func (f *FeeConfig) Verify() error { case f.MinBlockGasCost.Cmp(common.Big0) == -1: return fmt.Errorf("%w: minBlockGasCost = %d", errMinBlockGasCostNegative, f.MinBlockGasCost) case f.MinBlockGasCost.Cmp(f.MaxBlockGasCost) == 1: - return fmt.Errorf("%w: minBlockGasCost = %d, maxBlockGasCost = %d", errMinBlockGasCostTooHigh, f.MinBlockGasCost, f.MaxBlockGasCost) + return fmt.Errorf("%w: minBlockGasCost = %d, maxBlockGasCost = %d", ErrMinBlockGasCostTooHigh, f.MinBlockGasCost, f.MaxBlockGasCost) case f.BlockGasCostStep.Cmp(common.Big0) == -1: return fmt.Errorf("%w: blockGasCostStep = %d", errBlockGasCostStepNegative, f.BlockGasCostStep) case !f.MaxBlockGasCost.IsUint64(): diff --git a/commontype/fee_config_test.go b/commontype/fee_config_test.go index cc5426b16b..a2e7959270 100644 --- a/commontype/fee_config_test.go +++ b/commontype/fee_config_test.go @@ -75,7 +75,7 @@ func TestVerify(t *testing.T) { c.MaxBlockGasCost = big.NewInt(1) return &c }(), - wantError: errMinBlockGasCostTooHigh, + wantError: ErrMinBlockGasCostTooHigh, }, { name: "invalid BlockGasCostStep in FeeConfig", diff --git a/precompile/allowlist/allowlisttest/test_allowlist.go b/precompile/allowlist/allowlisttest/test_allowlist.go index b22194c71b..241dc7ef68 100644 --- a/precompile/allowlist/allowlisttest/test_allowlist.go +++ b/precompile/allowlist/allowlisttest/test_allowlist.go @@ -4,7 +4,6 @@ package allowlisttest import ( - "errors" "testing" "github.com/ava-labs/libevm/common" @@ -14,6 +13,7 @@ import ( "github.com/ava-labs/subnet-evm/core/extstate" "github.com/ava-labs/subnet-evm/precompile/allowlist" + "github.com/ava-labs/subnet-evm/precompile/contract" "github.com/ava-labs/subnet-evm/precompile/modules" "github.com/ava-labs/subnet-evm/precompile/precompileconfig" "github.com/ava-labs/subnet-evm/precompile/precompiletest" @@ -195,7 +195,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: 0, ReadOnly: false, - ExpectedErr: errors.New("invalid non-activated function selector"), + ExpectedErr: contract.ErrInvalidNonActivatedFunctionSelector, }, { Name: "no_role_set_manager", @@ -233,7 +233,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: 0, ReadOnly: false, - ExpectedErr: errors.New("invalid non-activated function selector"), + ExpectedErr: contract.ErrInvalidNonActivatedFunctionSelector, }, { Name: "enabled_set_manager", @@ -271,7 +271,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: 0, ReadOnly: false, - ExpectedErr: errors.New("invalid non-activated function selector"), + ExpectedErr: contract.ErrInvalidNonActivatedFunctionSelector, }, { Name: "admin_set_manager", diff --git a/precompile/contract/contract.go b/precompile/contract/contract.go index dde61d0c6f..f94ad50833 100644 --- a/precompile/contract/contract.go +++ b/precompile/contract/contract.go @@ -4,6 +4,7 @@ package contract import ( + "errors" "fmt" "github.com/ava-labs/libevm/common" @@ -13,6 +14,12 @@ const ( SelectorLen = 4 ) +var ( + ErrInvalidNonActivatedFunctionSelector = errors.New("invalid non-activated function selector") + + errInvalidFunctionSelector = errors.New("invalid function selector") +) + type RunStatefulPrecompileFunc func(accessibleState AccessibleState, caller common.Address, addr common.Address, input []byte, suppliedGas uint64, readOnly bool) (ret []byte, remainingGas uint64, err error) // ActivationFunc defines a function that is used to determine if a function is active @@ -97,12 +104,12 @@ func (s *statefulPrecompileWithFunctionSelectors) Run(accessibleState Accessible functionInput := input[SelectorLen:] function, ok := s.functions[string(selector)] if !ok { - return nil, suppliedGas, fmt.Errorf("invalid function selector %#x", selector) + return nil, suppliedGas, fmt.Errorf("%w: %#x", errInvalidFunctionSelector, selector) } // Check if the function is activated if !function.IsActivated(accessibleState) { - return nil, suppliedGas, fmt.Errorf("invalid non-activated function selector %#x", selector) + return nil, suppliedGas, fmt.Errorf("%w: %#x", ErrInvalidNonActivatedFunctionSelector, selector) } return function.execute(accessibleState, caller, addr, functionInput, suppliedGas, readOnly) diff --git a/precompile/contracts/feemanager/contract_test.go b/precompile/contracts/feemanager/contract_test.go index 82ff4c0981..a439c8ef2f 100644 --- a/precompile/contracts/feemanager/contract_test.go +++ b/precompile/contracts/feemanager/contract_test.go @@ -4,7 +4,6 @@ package feemanager import ( - "errors" "math/big" "testing" @@ -132,7 +131,7 @@ var ( Config: &Config{ InitialFeeConfig: &testFeeConfig, }, - ExpectedErr: errors.New("cannot be greater than maxBlockGasCost"), + ExpectedErr: commontype.ErrMinBlockGasCostTooHigh, AfterHook: func(t testing.TB, state *extstate.StateDB) { feeConfig := GetStoredFeeConfig(state) require.Equal(t, testFeeConfig, feeConfig) diff --git a/precompile/contracts/feemanager/unpack_pack_test.go b/precompile/contracts/feemanager/unpack_pack_test.go index 55b856c7dc..d9a52a0a26 100644 --- a/precompile/contracts/feemanager/unpack_pack_test.go +++ b/precompile/contracts/feemanager/unpack_pack_test.go @@ -374,7 +374,7 @@ func testOldPackSetFeeConfigInputEqual(t *testing.T, feeConfig commontype.FeeCon input, err := OldPackSetFeeConfig(feeConfig) input2, err2 := PackSetFeeConfig(feeConfig) if err != nil { - require.ErrorIs(t, err2, err) + require.Equal(t, err.Error(), err2.Error()) return } require.NoError(t, err2) @@ -383,7 +383,7 @@ func testOldPackSetFeeConfigInputEqual(t *testing.T, feeConfig commontype.FeeCon value, err := OldUnpackFeeConfig(input) unpacked, err2 := UnpackSetFeeConfigInput(input, true) if err != nil { - require.ErrorIs(t, err2, err) + require.Equal(t, err.Error(), err2.Error()) return } require.NoError(t, err2) From 3604a8e830d23d1ff248cdbad86c8488ceac703d Mon Sep 17 00:00:00 2001 From: Jonathan Oppenheimer Date: Tue, 25 Nov 2025 02:28:04 -0500 Subject: [PATCH 06/19] test: update precompile templates --- .../precompile_config_test_template.go | 4 ++-- .../precompile_contract_test_template.go | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/accounts/abi/bind/precompilebind/precompile_config_test_template.go b/accounts/abi/bind/precompilebind/precompile_config_test_template.go index d0a443a5df..c3adcdee53 100644 --- a/accounts/abi/bind/precompilebind/precompile_config_test_template.go +++ b/accounts/abi/bind/precompilebind/precompile_config_test_template.go @@ -41,13 +41,13 @@ func TestVerify(t *testing.T) { config.EXPECT().IsDurango(gomock.Any()).Return(true).AnyTimes() return config }(), - ExpectedError: "", + WantError: nil, }, // CUSTOM CODE STARTS HERE // Add your own Verify tests here, e.g.: // "your custom test name": { // Config: NewConfig(utils.NewUint64(3), {{- if .Contract.AllowList}} admins, enableds, managers{{- end}}), - // ExpectedError: ErrYourCustomError.Error(), + // WantError: ErrYourCustomError, // }, } {{- if .Contract.AllowList}} diff --git a/accounts/abi/bind/precompilebind/precompile_contract_test_template.go b/accounts/abi/bind/precompilebind/precompile_contract_test_template.go index d47e3e25c1..4b03c82ddd 100644 --- a/accounts/abi/bind/precompilebind/precompile_contract_test_template.go +++ b/accounts/abi/bind/precompilebind/precompile_contract_test_template.go @@ -95,7 +95,7 @@ var( {{- end}} SuppliedGas: {{$func.Normalized.Name}}GasCost, ReadOnly: false, - ExpectedErr: {{if $fail}} ErrCannot{{$func.Normalized.Name}}.Error() {{- else}} "" {{- end}}, + ExpectedErr: {{if $fail}} ErrCannot{{$func.Normalized.Name}} {{- else}} nil {{- end}}, }, {{- end}} {{- end}} @@ -124,7 +124,7 @@ var( }, SuppliedGas: {{$func.Normalized.Name}}GasCost, ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection.Error(), + ExpectedErr: vm.ErrWriteProtection, }, {{- end}} { @@ -151,7 +151,7 @@ var( }, SuppliedGas: {{$func.Normalized.Name}}GasCost - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas.Error(), + ExpectedErr: vm.ErrOutOfGas, }, {{- end}} {{- if .Contract.Fallback}} @@ -161,7 +161,7 @@ var( Input: []byte{}, SuppliedGas: {{.Contract.Type}}FallbackGasCost - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas.Error(), + ExpectedErr: vm.ErrOutOfGas, }, { Name: "readOnly fallback should fail", @@ -169,7 +169,7 @@ var( Input: []byte{}, SuppliedGas: {{.Contract.Type}}FallbackGasCost, ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection.Error(), + ExpectedErr: vm.ErrWriteProtection, }, { Name: "fallback should succeed", @@ -177,7 +177,7 @@ var( Input: []byte{}, SuppliedGas: {{.Contract.Type}}FallbackGasCost, ReadOnly: false, - ExpectedErr: "", + ExpectedErr: nil, // CUSTOM CODE STARTS HERE // set expected output here ExpectedRes: []byte{}, From 5ca350c3bbfbcd82ab598dbf25f2730037e0fa8c Mon Sep 17 00:00:00 2001 From: Jonathan Oppenheimer Date: Mon, 1 Dec 2025 15:54:11 -0500 Subject: [PATCH 07/19] test: Austin suggestions --- precompile/allowlist/unpack_pack_test.go | 12 ++---------- .../contracts/deployerallowlist/simulated_test.go | 2 +- precompile/contracts/feemanager/unpack_pack_test.go | 9 +++------ precompile/contracts/nativeminter/simulated_test.go | 7 ++++--- .../contracts/nativeminter/unpack_pack_test.go | 6 ++---- 5 files changed, 12 insertions(+), 24 deletions(-) diff --git a/precompile/allowlist/unpack_pack_test.go b/precompile/allowlist/unpack_pack_test.go index 77de0bba61..65432ddaf6 100644 --- a/precompile/allowlist/unpack_pack_test.go +++ b/precompile/allowlist/unpack_pack_test.go @@ -56,11 +56,7 @@ func FuzzPackReadAllowlistTestSkipCheck(f *testing.F) { require := require.New(t) res, err := UnpackReadAllowListInput(b, true) oldRes, oldErr := OldUnpackReadAllowList(b) - if oldErr != nil { - require.ErrorIs(err, oldErr) - } else { - require.NoError(err) - } + require.ErrorIs(err, oldErr) require.Equal(oldRes, res) }) } @@ -124,11 +120,7 @@ func FuzzPackModifyAllowlistTestSkipCheck(f *testing.F) { require := require.New(t) res, err := UnpackModifyAllowListInput(b, AdminRole, true) oldRes, oldErr := OldUnpackModifyAllowList(b, AdminRole) - if oldErr != nil { - require.ErrorIs(err, oldErr) - } else { - require.NoError(err) - } + require.ErrorIs(err, oldErr) require.Equal(oldRes, res) }) } diff --git a/precompile/contracts/deployerallowlist/simulated_test.go b/precompile/contracts/deployerallowlist/simulated_test.go index 998fc2c515..e16ca7c0bd 100644 --- a/precompile/contracts/deployerallowlist/simulated_test.go +++ b/precompile/contracts/deployerallowlist/simulated_test.go @@ -118,7 +118,7 @@ func TestDeployerAllowList(t *testing.T) { // Try to deploy via unprivileged user - should fail _, err := allowListTest.DeployContract(unprivileged) - // The error returned is actually a JSON Error + // The error returned is a JSON Error rather than the vm.ErrExecutionReverted error require.ErrorContains(t, err, "execution reverted") //nolint:forbidigo // uses upstream code }, }, diff --git a/precompile/contracts/feemanager/unpack_pack_test.go b/precompile/contracts/feemanager/unpack_pack_test.go index 5fe402a4eb..cbb0d2b761 100644 --- a/precompile/contracts/feemanager/unpack_pack_test.go +++ b/precompile/contracts/feemanager/unpack_pack_test.go @@ -326,20 +326,18 @@ func testOldPackGetFeeConfigOutputEqual(t *testing.T, feeConfig commontype.FeeCo t.Run(fmt.Sprintf("TestGetFeeConfigOutput, feeConfig %v", feeConfig), func(t *testing.T) { input, err := OldPackFeeConfig(feeConfig) input2, err2 := PackGetFeeConfigOutput(feeConfig) + require.ErrorIs(t, err2, err) if err != nil { - require.ErrorIs(t, err2, err) return } - require.NoError(t, err2) require.Equal(t, input, input2) config, err := OldUnpackFeeConfig(input) unpacked, err2 := UnpackGetFeeConfigOutput(input, false) + require.ErrorIs(t, err2, err) if err != nil { - require.ErrorIs(t, err2, err) return } - require.NoError(t, err2) require.True(t, config.Equal(&unpacked), "not equal: config %v, unpacked %v", feeConfig, unpacked) if checkOutputs { require.True(t, feeConfig.Equal(&unpacked), "not equal: feeConfig %v, unpacked %v", feeConfig, unpacked) @@ -357,11 +355,10 @@ func testOldPackGetLastChangedAtOutputEqual(t *testing.T, blockNumber *big.Int, value, err := OldUnpackGetLastChangedAtOutput(input) unpacked, err2 := UnpackGetFeeConfigLastChangedAtOutput(input) + require.ErrorIs(t, err2, err) if err != nil { - require.ErrorIs(t, err2, err) return } - require.NoError(t, err2) require.Zero(t, value.Cmp(unpacked), "not equal: value %v, unpacked %v", value, unpacked) if checkOutputs { require.Zero(t, blockNumber.Cmp(unpacked), "not equal: blockNumber %v, unpacked %v", blockNumber, unpacked) diff --git a/precompile/contracts/nativeminter/simulated_test.go b/precompile/contracts/nativeminter/simulated_test.go index 5560d82e97..5685799d00 100644 --- a/precompile/contracts/nativeminter/simulated_test.go +++ b/precompile/contracts/nativeminter/simulated_test.go @@ -9,7 +9,6 @@ import ( "github.com/ava-labs/libevm/common" "github.com/ava-labs/libevm/core/types" - "github.com/ava-labs/libevm/core/vm" "github.com/ava-labs/libevm/crypto" "github.com/stretchr/testify/require" @@ -111,7 +110,8 @@ func TestNativeMinter(t *testing.T) { // Unprivileged user tries to mint - should fail _, err := nativeMinter.MintNativeCoin(unprivileged, testAddr, amount) - require.Error(t, err) + // The error returned is a JSON Error rather than the vm.ErrExecutionReverted error + require.ErrorContains(t, err, "execution reverted") //nolint:forbidigo // uses upstream code }, }, { @@ -125,7 +125,8 @@ func TestNativeMinter(t *testing.T) { // Contract tries to mint and then should revert because it's not enabled _, err := testContract.MintNativeCoin(admin, testAddr, amount) - require.ErrorContains(t, err, vm.ErrExecutionReverted.Error()) + // The error returned is a JSON Error rather than the vm.ErrExecutionReverted error + require.ErrorContains(t, err, "execution reverted") //nolint:forbidigo // uses upstream code }, }, { diff --git a/precompile/contracts/nativeminter/unpack_pack_test.go b/precompile/contracts/nativeminter/unpack_pack_test.go index 2bc4d8b34e..8506579aaf 100644 --- a/precompile/contracts/nativeminter/unpack_pack_test.go +++ b/precompile/contracts/nativeminter/unpack_pack_test.go @@ -133,21 +133,19 @@ func testOldPackMintNativeCoinEqual(t *testing.T, addr common.Address, amount *b t.Run(fmt.Sprintf("TestUnpackAndPacks, addr: %s, amount: %s", addr.String(), amount.String()), func(t *testing.T) { input, err := OldPackMintNativeCoinInput(addr, amount) input2, err2 := PackMintNativeCoin(addr, amount) + require.ErrorIs(t, err2, err) if err != nil { - require.ErrorIs(t, err2, err) return } - require.NoError(t, err2) require.Equal(t, input, input2) input = input[4:] to, assetAmount, err := OldUnpackMintNativeCoinInput(input) unpackedAddr, unpackedAmount, err2 := UnpackMintNativeCoinInput(input, true) + require.ErrorIs(t, err2, err) if err != nil { - require.ErrorIs(t, err2, err) return } - require.NoError(t, err2) require.Equal(t, to, unpackedAddr) require.Equal(t, assetAmount.Bytes(), unpackedAmount.Bytes()) if checkOutputs { From 609c644f2e137e8a2499be2b55ccb184f8d4bb33 Mon Sep 17 00:00:00 2001 From: Jonathan Oppenheimer Date: Mon, 1 Dec 2025 16:11:06 -0500 Subject: [PATCH 08/19] test: properly wrap errors --- .../deployerallowlist/simulated_test.go | 3 +- precompile/contracts/feemanager/contract.go | 6 +- .../contracts/feemanager/unpack_pack_test.go | 151 +++++++++--------- precompile/contracts/nativeminter/contract.go | 10 +- .../contracts/nativeminter/simulated_test.go | 7 +- .../nativeminter/unpack_pack_test.go | 101 ++++++------ 6 files changed, 136 insertions(+), 142 deletions(-) diff --git a/precompile/contracts/deployerallowlist/simulated_test.go b/precompile/contracts/deployerallowlist/simulated_test.go index e16ca7c0bd..957228dcb8 100644 --- a/precompile/contracts/deployerallowlist/simulated_test.go +++ b/precompile/contracts/deployerallowlist/simulated_test.go @@ -9,6 +9,7 @@ import ( "github.com/ava-labs/libevm/common" "github.com/ava-labs/libevm/core/types" + "github.com/ava-labs/libevm/core/vm" "github.com/ava-labs/libevm/crypto" "github.com/stretchr/testify/require" @@ -119,7 +120,7 @@ func TestDeployerAllowList(t *testing.T) { // Try to deploy via unprivileged user - should fail _, err := allowListTest.DeployContract(unprivileged) // The error returned is a JSON Error rather than the vm.ErrExecutionReverted error - require.ErrorContains(t, err, "execution reverted") //nolint:forbidigo // uses upstream code + require.ErrorContains(t, err, vm.ErrExecutionReverted.Error()) //nolint:forbidigo // uses upstream code }, }, { diff --git a/precompile/contracts/feemanager/contract.go b/precompile/contracts/feemanager/contract.go index 7a82a9ae35..a7dbc8e726 100644 --- a/precompile/contracts/feemanager/contract.go +++ b/precompile/contracts/feemanager/contract.go @@ -52,6 +52,8 @@ var ( ErrCannotChangeFee = errors.New("non-enabled cannot change fee config") ErrInvalidLen = errors.New("invalid input length for fee config Input") + ErrUnpackInput = errors.New("failed to unpack input") + ErrUnpackOutput = errors.New("failed to unpack output") // IFeeManagerRawABI contains the raw ABI of FeeManager contract. //go:embed contract.abi @@ -188,7 +190,7 @@ func UnpackSetFeeConfigInput(input []byte, useStrictMode bool) (commontype.FeeCo inputStruct := FeeConfigABIStruct{} err := FeeManagerABI.UnpackInputIntoInterface(&inputStruct, "setFeeConfig", input, useStrictMode) if err != nil { - return commontype.FeeConfig{}, err + return commontype.FeeConfig{}, fmt.Errorf("%w: %w", ErrUnpackInput, err) } result := commontype.FeeConfig{ @@ -301,7 +303,7 @@ func UnpackGetFeeConfigOutput(output []byte, skipLenCheck bool) (commontype.FeeC outputStruct := FeeConfigABIStruct{} err := FeeManagerABI.UnpackIntoInterface(&outputStruct, "getFeeConfig", output) if err != nil { - return commontype.FeeConfig{}, err + return commontype.FeeConfig{}, fmt.Errorf("%w: %w", ErrUnpackOutput, err) } result := commontype.FeeConfig{ diff --git a/precompile/contracts/feemanager/unpack_pack_test.go b/precompile/contracts/feemanager/unpack_pack_test.go index cbb0d2b761..f8cdb97ab4 100644 --- a/precompile/contracts/feemanager/unpack_pack_test.go +++ b/precompile/contracts/feemanager/unpack_pack_test.go @@ -71,70 +71,62 @@ func TestPackGetFeeConfigOutput(t *testing.T) { name string input []byte skipLenCheck bool - expectedErr string - expectedOldErr string + expectedErr error + expectedOldErr error expectedOutput commontype.FeeConfig }{ { name: "empty input", input: []byte{}, skipLenCheck: false, - expectedErr: ErrInvalidLen.Error(), - expectedOldErr: ErrInvalidLen.Error(), + expectedErr: ErrInvalidLen, + expectedOldErr: ErrInvalidLen, }, { name: "empty input skip len check", input: []byte{}, skipLenCheck: true, - expectedErr: "attempting to unmarshal an empty string", - expectedOldErr: ErrInvalidLen.Error(), + expectedErr: ErrUnpackOutput, + expectedOldErr: ErrInvalidLen, }, { name: "input with extra bytes", input: append(testInputBytes, make([]byte, 32)...), skipLenCheck: false, - expectedErr: ErrInvalidLen.Error(), - expectedOldErr: ErrInvalidLen.Error(), + expectedErr: ErrInvalidLen, + expectedOldErr: ErrInvalidLen, }, { name: "input with extra bytes skip len check", input: append(testInputBytes, make([]byte, 32)...), skipLenCheck: true, - expectedErr: "", - expectedOldErr: ErrInvalidLen.Error(), + expectedErr: nil, + expectedOldErr: ErrInvalidLen, expectedOutput: testFeeConfig, }, { name: "input with extra bytes (not divisible by 32)", input: append(testInputBytes, make([]byte, 33)...), skipLenCheck: false, - expectedErr: ErrInvalidLen.Error(), - expectedOldErr: ErrInvalidLen.Error(), + expectedErr: ErrInvalidLen, + expectedOldErr: ErrInvalidLen, }, { name: "input with extra bytes (not divisible by 32) skip len check", input: append(testInputBytes, make([]byte, 33)...), skipLenCheck: true, - expectedErr: "improperly formatted output", - expectedOldErr: ErrInvalidLen.Error(), + expectedErr: ErrUnpackOutput, + expectedOldErr: ErrInvalidLen, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { unpacked, err := UnpackGetFeeConfigOutput(test.input, test.skipLenCheck) - if test.expectedErr != "" { - require.ErrorContains(t, err, test.expectedErr) //nolint:forbidigo // uses upstream code - } else { - require.NoError(t, err) - require.True(t, test.expectedOutput.Equal(&unpacked), "not equal: expectedOutput %v, unpacked %v", test.expectedOutput, unpacked) - } + require.ErrorIs(t, err, test.expectedErr) + require.True(t, test.expectedOutput.Equal(&unpacked), "not equal: expectedOutput %v, unpacked %v", test.expectedOutput, unpacked) oldUnpacked, oldErr := OldUnpackFeeConfig(test.input) - if test.expectedOldErr != "" { - require.ErrorContains(t, oldErr, test.expectedOldErr) //nolint:forbidigo // uses upstream code - } else { - require.NoError(t, oldErr) - require.True(t, test.expectedOutput.Equal(&oldUnpacked), "not equal: expectedOutput %v, oldUnpacked %v", test.expectedOutput, oldUnpacked) - } + require.ErrorIs(t, oldErr, test.expectedOldErr) + require.True(t, test.expectedOutput.Equal(&oldUnpacked), "not equal: expectedOutput %v, oldUnpacked %v", test.expectedOutput, oldUnpacked) }) } } @@ -225,86 +217,87 @@ func TestPackSetFeeConfigInput(t *testing.T) { // exclude 4 bytes for function selector testInputBytes = testInputBytes[4:] tests := []struct { - name string - input []byte - strictMode bool - expectedErr string - expectedOldErr string - expectedOutput commontype.FeeConfig + name string + input []byte + strictMode bool + wantErr error + wantOldErr error + wantOutput commontype.FeeConfig }{ { - name: "empty input strict mode", - input: []byte{}, - strictMode: true, - expectedErr: ErrInvalidLen.Error(), - expectedOldErr: ErrInvalidLen.Error(), + name: "empty input strict mode", + input: []byte{}, + strictMode: true, + wantErr: ErrInvalidLen, + wantOldErr: ErrInvalidLen, }, { - name: "empty input", - input: []byte{}, - strictMode: false, - expectedErr: "attempting to unmarshal an empty string", - expectedOldErr: ErrInvalidLen.Error(), + name: "empty input", + input: []byte{}, + strictMode: false, + wantErr: ErrUnpackInput, + wantOldErr: ErrInvalidLen, }, { - name: "input with insufficient len strict mode", - input: []byte{123}, - strictMode: true, - expectedErr: ErrInvalidLen.Error(), - expectedOldErr: ErrInvalidLen.Error(), + name: "input with insufficient len strict mode", + input: []byte{123}, + strictMode: true, + wantErr: ErrInvalidLen, + wantOldErr: ErrInvalidLen, }, { - name: "input with insufficient len", - input: []byte{123}, - strictMode: false, - expectedErr: "length insufficient", - expectedOldErr: ErrInvalidLen.Error(), + name: "input with insufficient len", + input: []byte{123}, + strictMode: false, + wantErr: ErrUnpackInput, + wantOldErr: ErrInvalidLen, }, { - name: "input with extra bytes strict mode", - input: append(testInputBytes, make([]byte, 32)...), - strictMode: true, - expectedErr: ErrInvalidLen.Error(), - expectedOldErr: ErrInvalidLen.Error(), + name: "input with extra bytes strict mode", + input: append(testInputBytes, make([]byte, 32)...), + strictMode: true, + wantErr: ErrInvalidLen, + wantOldErr: ErrInvalidLen, }, { - name: "input with extra bytes", - input: append(testInputBytes, make([]byte, 32)...), - strictMode: false, - expectedErr: "", - expectedOldErr: ErrInvalidLen.Error(), - expectedOutput: testFeeConfig, + name: "input with extra bytes", + input: append(testInputBytes, make([]byte, 32)...), + strictMode: false, + wantErr: nil, + wantOldErr: ErrInvalidLen, + wantOutput: testFeeConfig, }, { - name: "input with extra bytes (not divisible by 32) strict mode", - input: append(testInputBytes, make([]byte, 33)...), - strictMode: true, - expectedErr: ErrInvalidLen.Error(), - expectedOldErr: ErrInvalidLen.Error(), + name: "input with extra bytes (not divisible by 32) strict mode", + input: append(testInputBytes, make([]byte, 33)...), + strictMode: true, + wantErr: ErrInvalidLen, + wantOldErr: ErrInvalidLen, }, { - name: "input with extra bytes (not divisible by 32)", - input: append(testInputBytes, make([]byte, 33)...), - strictMode: false, - expectedOutput: testFeeConfig, - expectedOldErr: ErrInvalidLen.Error(), + name: "input with extra bytes (not divisible by 32)", + input: append(testInputBytes, make([]byte, 33)...), + strictMode: false, + wantErr: nil, + wantOldErr: ErrInvalidLen, + wantOutput: testFeeConfig, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { unpacked, err := UnpackSetFeeConfigInput(test.input, test.strictMode) - if test.expectedErr != "" { - require.ErrorContains(t, err, test.expectedErr) //nolint:forbidigo // uses upstream code + if test.wantErr != nil { + require.ErrorIs(t, err, test.wantErr) } else { require.NoError(t, err) - require.True(t, test.expectedOutput.Equal(&unpacked), "not equal: expectedOutput %v, unpacked %v", test.expectedOutput, unpacked) + require.True(t, test.wantOutput.Equal(&unpacked), "not equal: expectedOutput %v, unpacked %v", test.wantOutput, unpacked) } oldUnpacked, oldErr := OldUnpackFeeConfig(test.input) - if test.expectedOldErr != "" { - require.ErrorContains(t, oldErr, test.expectedOldErr) //nolint:forbidigo // uses upstream code + if test.wantOldErr != nil { + require.ErrorIs(t, oldErr, test.wantOldErr) } else { require.NoError(t, oldErr) - require.True(t, test.expectedOutput.Equal(&oldUnpacked), "not equal: expectedOutput %v, oldUnpacked %v", test.expectedOutput, oldUnpacked) + require.True(t, test.wantOutput.Equal(&oldUnpacked), "not equal: expectedOutput %v, oldUnpacked %v", test.wantOutput, oldUnpacked) } }) } diff --git a/precompile/contracts/nativeminter/contract.go b/precompile/contracts/nativeminter/contract.go index 3c8f004caf..6613d37903 100644 --- a/precompile/contracts/nativeminter/contract.go +++ b/precompile/contracts/nativeminter/contract.go @@ -34,8 +34,9 @@ var ( // Singleton StatefulPrecompiledContract for minting native assets by permissioned callers. ContractNativeMinterPrecompile contract.StatefulPrecompiledContract = createNativeMinterPrecompile() - ErrCannotMint = errors.New("non-enabled cannot mint") - ErrInvalidLen = errors.New("invalid input length for minting") + ErrCannotMint = errors.New("non-enabled cannot mint") + ErrInvalidLen = errors.New("invalid input length for minting") + ErrUnpackInput = errors.New("failed to unpack input") // NativeMinterRawABI contains the raw ABI of NativeMinter contract. //go:embed contract.abi @@ -73,8 +74,11 @@ func UnpackMintNativeCoinInput(input []byte, useStrictMode bool) (common.Address } inputStruct := MintNativeCoinInput{} err := NativeMinterABI.UnpackInputIntoInterface(&inputStruct, "mintNativeCoin", input, useStrictMode) + if err != nil { + return common.Address{}, nil, fmt.Errorf("%w: %w", ErrUnpackInput, err) + } - return inputStruct.Addr, inputStruct.Amount, err + return inputStruct.Addr, inputStruct.Amount, nil } // mintNativeCoin checks if the caller is permissioned for minting operation. diff --git a/precompile/contracts/nativeminter/simulated_test.go b/precompile/contracts/nativeminter/simulated_test.go index 5685799d00..73173643c1 100644 --- a/precompile/contracts/nativeminter/simulated_test.go +++ b/precompile/contracts/nativeminter/simulated_test.go @@ -9,6 +9,7 @@ import ( "github.com/ava-labs/libevm/common" "github.com/ava-labs/libevm/core/types" + "github.com/ava-labs/libevm/core/vm" "github.com/ava-labs/libevm/crypto" "github.com/stretchr/testify/require" @@ -110,8 +111,8 @@ func TestNativeMinter(t *testing.T) { // Unprivileged user tries to mint - should fail _, err := nativeMinter.MintNativeCoin(unprivileged, testAddr, amount) - // The error returned is a JSON Error rather than the vm.ErrExecutionReverted error - require.ErrorContains(t, err, "execution reverted") //nolint:forbidigo // uses upstream code + // The error returned is a JSON Error rather than the nativeminter.ErrCannotMinterror + require.ErrorContains(t, err, nativeminter.ErrCannotMint.Error()) //nolint:forbidigo // uses upstream code }, }, { @@ -126,7 +127,7 @@ func TestNativeMinter(t *testing.T) { // Contract tries to mint and then should revert because it's not enabled _, err := testContract.MintNativeCoin(admin, testAddr, amount) // The error returned is a JSON Error rather than the vm.ErrExecutionReverted error - require.ErrorContains(t, err, "execution reverted") //nolint:forbidigo // uses upstream code + require.ErrorContains(t, err, vm.ErrExecutionReverted.Error()) //nolint:forbidigo // uses upstream code }, }, { diff --git a/precompile/contracts/nativeminter/unpack_pack_test.go b/precompile/contracts/nativeminter/unpack_pack_test.go index 8506579aaf..453123f3e8 100644 --- a/precompile/contracts/nativeminter/unpack_pack_test.go +++ b/precompile/contracts/nativeminter/unpack_pack_test.go @@ -46,78 +46,71 @@ func TestUnpackMintNativeCoinInput(t *testing.T) { // exclude 4 bytes for function selector testInputBytes = testInputBytes[4:] tests := []struct { - name string - input []byte - strictMode bool - expectedErr string - expectedOldErr string - expectedAddr common.Address - expectedAmount *big.Int + name string + input []byte + strictMode bool + wantErr error + wantOldErr error + wantAddr common.Address + wantAmount *big.Int }{ { - name: "empty input strict mode", - input: []byte{}, - strictMode: true, - expectedErr: ErrInvalidLen.Error(), - expectedOldErr: ErrInvalidLen.Error(), + name: "empty input strict mode", + input: []byte{}, + strictMode: true, + wantErr: ErrInvalidLen, + wantOldErr: ErrInvalidLen, }, { - name: "empty input", - input: []byte{}, - strictMode: false, - expectedErr: "attempting to unmarshal an empty string", - expectedOldErr: ErrInvalidLen.Error(), + name: "empty input", + input: []byte{}, + strictMode: false, + wantErr: ErrUnpackInput, + wantOldErr: ErrInvalidLen, }, { - name: "input with extra bytes strict mode", - input: append(testInputBytes, make([]byte, 32)...), - strictMode: true, - expectedErr: ErrInvalidLen.Error(), - expectedOldErr: ErrInvalidLen.Error(), + name: "input with extra bytes strict mode", + input: append(testInputBytes, make([]byte, 32)...), + strictMode: true, + wantErr: ErrInvalidLen, + wantOldErr: ErrInvalidLen, }, { - name: "input with extra bytes", - input: append(testInputBytes, make([]byte, 32)...), - strictMode: false, - expectedErr: "", - expectedOldErr: ErrInvalidLen.Error(), - expectedAddr: constants.BlackholeAddr, - expectedAmount: common.Big2, + name: "input with extra bytes", + input: append(testInputBytes, make([]byte, 32)...), + strictMode: false, + wantErr: nil, + wantOldErr: ErrInvalidLen, + wantAddr: constants.BlackholeAddr, + wantAmount: common.Big2, }, { - name: "input with extra bytes (not divisible by 32) strict mode", - input: append(testInputBytes, make([]byte, 33)...), - strictMode: true, - expectedErr: ErrInvalidLen.Error(), - expectedOldErr: ErrInvalidLen.Error(), + name: "input with extra bytes (not divisible by 32) strict mode", + input: append(testInputBytes, make([]byte, 33)...), + strictMode: true, + wantErr: ErrInvalidLen, + wantOldErr: ErrInvalidLen, }, { - name: "input with extra bytes (not divisible by 32)", - input: append(testInputBytes, make([]byte, 33)...), - strictMode: false, - expectedAddr: constants.BlackholeAddr, - expectedAmount: common.Big2, - expectedOldErr: ErrInvalidLen.Error(), + name: "input with extra bytes (not divisible by 32)", + input: append(testInputBytes, make([]byte, 33)...), + strictMode: false, + wantErr: nil, + wantOldErr: ErrInvalidLen, + wantAddr: constants.BlackholeAddr, + wantAmount: common.Big2, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { unpackedAddress, unpackedAmount, err := UnpackMintNativeCoinInput(test.input, test.strictMode) - if test.expectedErr != "" { - require.ErrorContains(t, err, test.expectedErr) //nolint:forbidigo // uses upstream code - } else { - require.NoError(t, err) - require.Equal(t, test.expectedAddr, unpackedAddress) - require.Equal(t, test.expectedAmount, unpackedAmount, "expected %s, got %s", test.expectedAmount.String(), unpackedAmount.String()) - } + require.ErrorIs(t, err, test.wantErr) + require.Equal(t, test.wantAddr, unpackedAddress) + require.Equal(t, test.wantAmount, unpackedAmount, "expected %s, got %s", test.wantAmount.String(), unpackedAmount.String()) oldUnpackedAddress, oldUnpackedAmount, oldErr := OldUnpackMintNativeCoinInput(test.input) - if test.expectedOldErr != "" { - require.ErrorContains(t, oldErr, test.expectedOldErr) //nolint:forbidigo // uses upstream code - } else { - require.NoError(t, oldErr) - require.Equal(t, test.expectedAddr, oldUnpackedAddress) - require.Equal(t, test.expectedAmount, oldUnpackedAmount, "expected %s, got %s", test.expectedAmount.String(), oldUnpackedAmount.String()) - } + require.ErrorIs(t, oldErr, test.wantOldErr) + require.Equal(t, test.wantAddr, oldUnpackedAddress) + require.Equal(t, test.wantAmount, oldUnpackedAmount, "expected %s, got %s", test.wantAmount.String(), oldUnpackedAmount.String()) }) } } From 4bfecaf2d0b46acbfda256934158a2db75425288 Mon Sep 17 00:00:00 2001 From: Jonathan Oppenheimer Date: Mon, 1 Dec 2025 16:19:51 -0500 Subject: [PATCH 09/19] test: only equal on nil --- .../contracts/feemanager/unpack_pack_test.go | 86 ++++++++++--------- .../nativeminter/unpack_pack_test.go | 12 ++- 2 files changed, 53 insertions(+), 45 deletions(-) diff --git a/precompile/contracts/feemanager/unpack_pack_test.go b/precompile/contracts/feemanager/unpack_pack_test.go index f8cdb97ab4..dfc07c5a0a 100644 --- a/precompile/contracts/feemanager/unpack_pack_test.go +++ b/precompile/contracts/feemanager/unpack_pack_test.go @@ -68,65 +68,69 @@ func TestPackGetFeeConfigOutput(t *testing.T) { testInputBytes, err := PackGetFeeConfigOutput(testFeeConfig) require.NoError(t, err) tests := []struct { - name string - input []byte - skipLenCheck bool - expectedErr error - expectedOldErr error - expectedOutput commontype.FeeConfig + name string + input []byte + skipLenCheck bool + wantErr error + wantOldErr error + wantOutput commontype.FeeConfig }{ { - name: "empty input", - input: []byte{}, - skipLenCheck: false, - expectedErr: ErrInvalidLen, - expectedOldErr: ErrInvalidLen, + name: "empty input", + input: []byte{}, + skipLenCheck: false, + wantErr: ErrInvalidLen, + wantOldErr: ErrInvalidLen, }, { - name: "empty input skip len check", - input: []byte{}, - skipLenCheck: true, - expectedErr: ErrUnpackOutput, - expectedOldErr: ErrInvalidLen, + name: "empty input skip len check", + input: []byte{}, + skipLenCheck: true, + wantErr: ErrUnpackOutput, + wantOldErr: ErrInvalidLen, }, { - name: "input with extra bytes", - input: append(testInputBytes, make([]byte, 32)...), - skipLenCheck: false, - expectedErr: ErrInvalidLen, - expectedOldErr: ErrInvalidLen, + name: "input with extra bytes", + input: append(testInputBytes, make([]byte, 32)...), + skipLenCheck: false, + wantErr: ErrInvalidLen, + wantOldErr: ErrInvalidLen, }, { - name: "input with extra bytes skip len check", - input: append(testInputBytes, make([]byte, 32)...), - skipLenCheck: true, - expectedErr: nil, - expectedOldErr: ErrInvalidLen, - expectedOutput: testFeeConfig, + name: "input with extra bytes skip len check", + input: append(testInputBytes, make([]byte, 32)...), + skipLenCheck: true, + wantErr: nil, + wantOldErr: ErrInvalidLen, + wantOutput: testFeeConfig, }, { - name: "input with extra bytes (not divisible by 32)", - input: append(testInputBytes, make([]byte, 33)...), - skipLenCheck: false, - expectedErr: ErrInvalidLen, - expectedOldErr: ErrInvalidLen, + name: "input with extra bytes (not divisible by 32)", + input: append(testInputBytes, make([]byte, 33)...), + skipLenCheck: false, + wantErr: ErrInvalidLen, + wantOldErr: ErrInvalidLen, }, { - name: "input with extra bytes (not divisible by 32) skip len check", - input: append(testInputBytes, make([]byte, 33)...), - skipLenCheck: true, - expectedErr: ErrUnpackOutput, - expectedOldErr: ErrInvalidLen, + name: "input with extra bytes (not divisible by 32) skip len check", + input: append(testInputBytes, make([]byte, 33)...), + skipLenCheck: true, + wantErr: ErrUnpackOutput, + wantOldErr: ErrInvalidLen, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { unpacked, err := UnpackGetFeeConfigOutput(test.input, test.skipLenCheck) - require.ErrorIs(t, err, test.expectedErr) - require.True(t, test.expectedOutput.Equal(&unpacked), "not equal: expectedOutput %v, unpacked %v", test.expectedOutput, unpacked) + require.ErrorIs(t, err, test.wantErr) + if test.wantErr == nil { + require.True(t, test.wantOutput.Equal(&unpacked), "not equal: expectedOutput %v, unpacked %v", test.wantOutput, unpacked) + } oldUnpacked, oldErr := OldUnpackFeeConfig(test.input) - require.ErrorIs(t, oldErr, test.expectedOldErr) - require.True(t, test.expectedOutput.Equal(&oldUnpacked), "not equal: expectedOutput %v, oldUnpacked %v", test.expectedOutput, oldUnpacked) + require.ErrorIs(t, oldErr, test.wantOldErr) + if test.wantOldErr == nil { + require.True(t, test.wantOutput.Equal(&oldUnpacked), "not equal: expectedOutput %v, oldUnpacked %v", test.wantOutput, oldUnpacked) + } }) } } diff --git a/precompile/contracts/nativeminter/unpack_pack_test.go b/precompile/contracts/nativeminter/unpack_pack_test.go index 453123f3e8..202228cee4 100644 --- a/precompile/contracts/nativeminter/unpack_pack_test.go +++ b/precompile/contracts/nativeminter/unpack_pack_test.go @@ -105,12 +105,16 @@ func TestUnpackMintNativeCoinInput(t *testing.T) { t.Run(test.name, func(t *testing.T) { unpackedAddress, unpackedAmount, err := UnpackMintNativeCoinInput(test.input, test.strictMode) require.ErrorIs(t, err, test.wantErr) - require.Equal(t, test.wantAddr, unpackedAddress) - require.Equal(t, test.wantAmount, unpackedAmount, "expected %s, got %s", test.wantAmount.String(), unpackedAmount.String()) + if test.wantErr == nil { + require.Equal(t, test.wantAddr, unpackedAddress) + require.Equal(t, test.wantAmount, unpackedAmount, "expected %s, got %s", test.wantAmount.String(), unpackedAmount.String()) + } oldUnpackedAddress, oldUnpackedAmount, oldErr := OldUnpackMintNativeCoinInput(test.input) require.ErrorIs(t, oldErr, test.wantOldErr) - require.Equal(t, test.wantAddr, oldUnpackedAddress) - require.Equal(t, test.wantAmount, oldUnpackedAmount, "expected %s, got %s", test.wantAmount.String(), oldUnpackedAmount.String()) + if test.wantOldErr == nil { + require.Equal(t, test.wantAddr, oldUnpackedAddress) + require.Equal(t, test.wantAmount, oldUnpackedAmount, "expected %s, got %s", test.wantAmount.String(), oldUnpackedAmount.String()) + } }) } } From b68b19dc77c29d384afddb34429ab4c65cae8b73 Mon Sep 17 00:00:00 2001 From: Jonathan Oppenheimer Date: Tue, 2 Dec 2025 13:44:20 -0500 Subject: [PATCH 10/19] docs: revert comment shortening --- plugin/evm/vm_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/plugin/evm/vm_test.go b/plugin/evm/vm_test.go index 0d9874fb4a..0f82088dfe 100644 --- a/plugin/evm/vm_test.go +++ b/plugin/evm/vm_test.go @@ -766,9 +766,9 @@ func testReorgProtection(t *testing.T, scheme string) { // should NEVER happen. However, the VM defends against this // just in case. err = vm1.SetPreference(t.Context(), vm1BlkC.ID()) - require.ErrorContains(t, err, "cannot orphan finalized block") //nolint:forbidigo // uses upstream code + require.ErrorContains(t, err, "cannot orphan finalized block", "Expected error when setting preference that would orphan finalized block") //nolint:forbidigo // uses upstream code err = vm1BlkC.Accept(t.Context()) - require.ErrorContains(t, err, "expected accepted block to have parent") //nolint:forbidigo // uses upstream code + require.ErrorContains(t, err, "expected accepted block to have parent", "Expected error when accepting orphaned block") //nolint:forbidigo // uses upstream code } // Regression test to ensure that a VM that accepts block C while preferring @@ -1088,7 +1088,7 @@ func testStickyPreference(t *testing.T, scheme string) { // Attempt to accept out of order err = vm1BlkD.Accept(t.Context()) - require.ErrorContains(t, err, "expected accepted block to have parent") //nolint:forbidigo // uses upstream code + require.ErrorContains(t, vm1BlkD.Accept(t.Context()), "expected accepted block to have parent", "unexpected error when accepting out of order block") //nolint:forbidigo // uses upstream code // Accept in order require.NoError(t, vm1BlkC.Accept(t.Context()), "Block failed verification on VM1") From ed6b12ed1e2beea526d1fd319172875701c16df6 Mon Sep 17 00:00:00 2001 From: Jonathan Oppenheimer Date: Wed, 3 Dec 2025 10:38:56 -0500 Subject: [PATCH 11/19] style: declare error seperately --- plugin/evm/vm_test.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/plugin/evm/vm_test.go b/plugin/evm/vm_test.go index 0f82088dfe..98e401312e 100644 --- a/plugin/evm/vm_test.go +++ b/plugin/evm/vm_test.go @@ -1087,8 +1087,7 @@ func testStickyPreference(t *testing.T, scheme string) { require.Equal(t, blkDHash, vm1.blockChain.CurrentBlock().Hash(), "expected current block to have hash %s but got %s", blkDHash.Hex(), vm1.blockChain.CurrentBlock().Hash().Hex()) // Attempt to accept out of order - err = vm1BlkD.Accept(t.Context()) - require.ErrorContains(t, vm1BlkD.Accept(t.Context()), "expected accepted block to have parent", "unexpected error when accepting out of order block") //nolint:forbidigo // uses upstream code + require.ErrorContains(t, err, "expected accepted block to have parent", "unexpected error when accepting out of order block") //nolint:forbidigo // uses upstream code // Accept in order require.NoError(t, vm1BlkC.Accept(t.Context()), "Block failed verification on VM1") From 73c5826a665dbcc2084dcadd0904ab5b3e89301d Mon Sep 17 00:00:00 2001 From: Jonathan Oppenheimer Date: Wed, 3 Dec 2025 10:42:37 -0500 Subject: [PATCH 12/19] style: consistently use want --- .../precompile_contract_test_template.go | 12 ++--- params/extras/precompile_config_test.go | 34 ++++++------- .../allowlist/allowlisttest/test_allowlist.go | 50 +++++++++---------- .../contracts/feemanager/contract_test.go | 16 +++--- .../contracts/nativeminter/contract_test.go | 12 ++--- .../contracts/rewardmanager/contract_test.go | 18 +++---- precompile/contracts/warp/contract_test.go | 42 ++++++++-------- precompile/precompiletest/test_precompile.go | 10 ++-- 8 files changed, 97 insertions(+), 97 deletions(-) diff --git a/accounts/abi/bind/precompilebind/precompile_contract_test_template.go b/accounts/abi/bind/precompilebind/precompile_contract_test_template.go index 4b03c82ddd..0709d866ee 100644 --- a/accounts/abi/bind/precompilebind/precompile_contract_test_template.go +++ b/accounts/abi/bind/precompilebind/precompile_contract_test_template.go @@ -95,7 +95,7 @@ var( {{- end}} SuppliedGas: {{$func.Normalized.Name}}GasCost, ReadOnly: false, - ExpectedErr: {{if $fail}} ErrCannot{{$func.Normalized.Name}} {{- else}} nil {{- end}}, + WantErr: {{if $fail}} ErrCannot{{$func.Normalized.Name}} {{- else}} nil {{- end}}, }, {{- end}} {{- end}} @@ -124,7 +124,7 @@ var( }, SuppliedGas: {{$func.Normalized.Name}}GasCost, ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection, + WantErr: vm.ErrWriteProtection, }, {{- end}} { @@ -151,7 +151,7 @@ var( }, SuppliedGas: {{$func.Normalized.Name}}GasCost - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas, + WantErr: vm.ErrOutOfGas, }, {{- end}} {{- if .Contract.Fallback}} @@ -161,7 +161,7 @@ var( Input: []byte{}, SuppliedGas: {{.Contract.Type}}FallbackGasCost - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas, + WantErr: vm.ErrOutOfGas, }, { Name: "readOnly fallback should fail", @@ -169,7 +169,7 @@ var( Input: []byte{}, SuppliedGas: {{.Contract.Type}}FallbackGasCost, ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection, + WantErr: vm.ErrWriteProtection, }, { Name: "fallback should succeed", @@ -177,7 +177,7 @@ var( Input: []byte{}, SuppliedGas: {{.Contract.Type}}FallbackGasCost, ReadOnly: false, - ExpectedErr: nil, + WantErr: nil, // CUSTOM CODE STARTS HERE // set expected output here ExpectedRes: []byte{}, diff --git a/params/extras/precompile_config_test.go b/params/extras/precompile_config_test.go index 6931481362..59f3e02b0d 100644 --- a/params/extras/precompile_config_test.go +++ b/params/extras/precompile_config_test.go @@ -92,9 +92,9 @@ func TestVerifyWithChainConfigAtNilTimestamp(t *testing.T) { func TestVerifyPrecompileUpgrades(t *testing.T) { admins := []common.Address{{1}} tests := []struct { - name string - upgrades []PrecompileUpgrade - expectedError error + name string + upgrades []PrecompileUpgrade + wantError error }{ { name: "enable and disable tx allow list", @@ -106,7 +106,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { Config: txallowlist.NewDisableConfig(utils.NewUint64(2)), }, }, - expectedError: nil, + wantError: nil, }, { name: "invalid allow list config in tx allowlist", @@ -121,7 +121,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { Config: txallowlist.NewConfig(utils.NewUint64(3), admins, admins, admins), }, }, - expectedError: allowlist.ErrAdminAndEnabledAddress, + wantError: allowlist.ErrAdminAndEnabledAddress, }, { name: "invalid initial fee manager config", @@ -135,7 +135,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { }()), }, }, - expectedError: commontype.ErrGasLimitTooLow, + wantError: commontype.ErrGasLimitTooLow, }, { name: "invalid initial fee manager config gas limit 0", @@ -149,7 +149,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { }()), }, }, - expectedError: commontype.ErrGasLimitTooLow, + wantError: commontype.ErrGasLimitTooLow, }, { name: "different upgrades are allowed to configure same timestamp for different precompiles", @@ -161,7 +161,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { Config: feemanager.NewConfig(utils.NewUint64(1), admins, nil, nil, nil), }, }, - expectedError: nil, + wantError: nil, }, { name: "different upgrades must be monotonically increasing", @@ -173,7 +173,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { Config: feemanager.NewConfig(utils.NewUint64(1), admins, nil, nil, nil), }, }, - expectedError: errPrecompileUpgradeTimestampNotMonotonic, + wantError: errPrecompileUpgradeTimestampNotMonotonic, }, { name: "upgrades with same keys are not allowed to configure same timestamp for same precompiles", @@ -185,7 +185,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { Config: txallowlist.NewDisableConfig(utils.NewUint64(1)), }, }, - expectedError: errPrecompileUpgradeSameKeyTimestampNotStrictly, + wantError: errPrecompileUpgradeSameKeyTimestampNotStrictly, }, } for _, tt := range tests { @@ -197,7 +197,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { config.PrecompileUpgrades = tt.upgrades err := config.Verify() - require.ErrorIs(err, tt.expectedError) + require.ErrorIs(err, tt.wantError) }) } } @@ -205,16 +205,16 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { func TestVerifyPrecompiles(t *testing.T) { admins := []common.Address{{1}} tests := []struct { - name string - precompiles Precompiles - expectedError error + name string + precompiles Precompiles + wantError error }{ { name: "invalid allow list config in tx allowlist", precompiles: Precompiles{ txallowlist.ConfigKey: txallowlist.NewConfig(utils.NewUint64(3), admins, admins, admins), }, - expectedError: allowlist.ErrAdminAndEnabledAddress, + wantError: allowlist.ErrAdminAndEnabledAddress, }, { name: "invalid initial fee manager config", @@ -226,7 +226,7 @@ func TestVerifyPrecompiles(t *testing.T) { return &feeConfig }()), }, - expectedError: commontype.ErrGasLimitTooLow, + wantError: commontype.ErrGasLimitTooLow, }, } for _, tt := range tests { @@ -238,7 +238,7 @@ func TestVerifyPrecompiles(t *testing.T) { config.GenesisPrecompiles = tt.precompiles err := config.Verify() - require.ErrorIs(err, tt.expectedError) + require.ErrorIs(err, tt.wantError) }) } } diff --git a/precompile/allowlist/allowlisttest/test_allowlist.go b/precompile/allowlist/allowlisttest/test_allowlist.go index 241dc7ef68..33ad4c2944 100644 --- a/precompile/allowlist/allowlisttest/test_allowlist.go +++ b/precompile/allowlist/allowlisttest/test_allowlist.go @@ -106,7 +106,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList, + WantErr: allowlist.ErrCannotModifyAllowList, }, { Name: "no_role_set_enabled", @@ -120,7 +120,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList, + WantErr: allowlist.ErrCannotModifyAllowList, }, { Name: "no_role_set_admin", @@ -134,7 +134,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList, + WantErr: allowlist.ErrCannotModifyAllowList, }, { Name: "enabled_set_no_role", @@ -148,7 +148,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList, + WantErr: allowlist.ErrCannotModifyAllowList, }, { Name: "enabled_set_enabled", @@ -162,7 +162,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList, + WantErr: allowlist.ErrCannotModifyAllowList, }, { Name: "enabled_set_admin", @@ -176,7 +176,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList, + WantErr: allowlist.ErrCannotModifyAllowList, }, { Name: "no_role_set_manager_pre_Durango", @@ -195,7 +195,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: 0, ReadOnly: false, - ExpectedErr: contract.ErrInvalidNonActivatedFunctionSelector, + WantErr: contract.ErrInvalidNonActivatedFunctionSelector, }, { Name: "no_role_set_manager", @@ -214,7 +214,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList, + WantErr: allowlist.ErrCannotModifyAllowList, }, { Name: "enabled_role_set_manager_pre_Durango", @@ -233,7 +233,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: 0, ReadOnly: false, - ExpectedErr: contract.ErrInvalidNonActivatedFunctionSelector, + WantErr: contract.ErrInvalidNonActivatedFunctionSelector, }, { Name: "enabled_set_manager", @@ -252,7 +252,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList, + WantErr: allowlist.ErrCannotModifyAllowList, }, { Name: "admin_set_manager_pre_Durango", @@ -271,7 +271,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: 0, ReadOnly: false, - ExpectedErr: contract.ErrInvalidNonActivatedFunctionSelector, + WantErr: contract.ErrInvalidNonActivatedFunctionSelector, }, { Name: "admin_set_manager", @@ -312,7 +312,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom SuppliedGas: allowlist.ModifyAllowListGasCost + allowlist.AllowListEventGasCost, ReadOnly: false, ExpectedRes: []byte{}, - ExpectedErr: nil, + WantErr: nil, AfterHook: func(t testing.TB, state *extstate.StateDB) { res := allowlist.GetAllowListStatus(state, contractAddress, TestNoRoleAddr) require.Equal(t, allowlist.NoRole, res) @@ -334,7 +334,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom SuppliedGas: allowlist.ModifyAllowListGasCost + allowlist.AllowListEventGasCost, ReadOnly: false, ExpectedRes: []byte{}, - ExpectedErr: nil, + WantErr: nil, AfterHook: func(t testing.TB, state *extstate.StateDB) { res := allowlist.GetAllowListStatus(state, contractAddress, TestNoRoleAddr) require.Equal(t, allowlist.EnabledRole, res) @@ -361,7 +361,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList, + WantErr: allowlist.ErrCannotModifyAllowList, }, { Name: "manager_set_no_role_to_admin", @@ -375,7 +375,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList, + WantErr: allowlist.ErrCannotModifyAllowList, }, { Name: "manager_set_enabled_to_admin", @@ -389,7 +389,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList, + WantErr: allowlist.ErrCannotModifyAllowList, }, { Name: "manager_set_enabled_role_to_manager", @@ -408,7 +408,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList, + WantErr: allowlist.ErrCannotModifyAllowList, }, { Name: "manager_set_enabled_role_to_no_role", @@ -444,7 +444,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList, + WantErr: allowlist.ErrCannotModifyAllowList, }, { Name: "manager_set_admin_role_to_enabled", @@ -458,7 +458,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList, + WantErr: allowlist.ErrCannotModifyAllowList, }, { Name: "manager_set_admin_to_manager", @@ -477,7 +477,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList, + WantErr: allowlist.ErrCannotModifyAllowList, }, { Name: "manager_set_manager_to_no_role", @@ -491,7 +491,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - ExpectedErr: allowlist.ErrCannotModifyAllowList, + WantErr: allowlist.ErrCannotModifyAllowList, }, { Name: "admin_set_no_role_with_readOnly_enabled", @@ -505,7 +505,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection, + WantErr: vm.ErrWriteProtection, }, { Name: "admin_set_no_role_insufficient_gas", @@ -519,7 +519,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas, + WantErr: vm.ErrOutOfGas, }, { Name: "no_role_read_allow_list", @@ -571,8 +571,8 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom return input }, SuppliedGas: allowlist.ReadAllowListGasCost - 1, - ReadOnly: true, - ExpectedErr: vm.ErrOutOfGas, + ReadOnly: true, + WantErr: vm.ErrOutOfGas, }, { Name: "initial_config_sets_admins", diff --git a/precompile/contracts/feemanager/contract_test.go b/precompile/contracts/feemanager/contract_test.go index dc6f4d940c..17625dc201 100644 --- a/precompile/contracts/feemanager/contract_test.go +++ b/precompile/contracts/feemanager/contract_test.go @@ -60,7 +60,7 @@ var ( }, SuppliedGas: feemanager.SetFeeConfigGasCost, ReadOnly: false, - ExpectedErr: feemanager.ErrCannotChangeFee, + WantErr: feemanager.ErrCannotChangeFee, }, { Name: "set_config_from_enabled_address_succeeds_and_emits_logs", @@ -121,7 +121,7 @@ var ( Config: &feemanager.Config{ InitialFeeConfig: &testFeeConfig, }, - ExpectedErr: commontype.ErrMinBlockGasCostTooHigh, + WantErr: commontype.ErrMinBlockGasCostTooHigh, AfterHook: func(t testing.TB, state *extstate.StateDB) { feeConfig := feemanager.GetStoredFeeConfig(state) require.Equal(t, testFeeConfig, feeConfig) @@ -260,7 +260,7 @@ var ( }, SuppliedGas: feemanager.SetFeeConfigGasCost, ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection, + WantErr: vm.ErrWriteProtection, }, { Name: "readOnly_setFeeConfig_with_allow_role_fails", @@ -274,7 +274,7 @@ var ( }, SuppliedGas: feemanager.SetFeeConfigGasCost, ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection, + WantErr: vm.ErrWriteProtection, }, { Name: "readOnly_setFeeConfig_with_admin_role_fails", @@ -288,7 +288,7 @@ var ( }, SuppliedGas: feemanager.SetFeeConfigGasCost, ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection, + WantErr: vm.ErrWriteProtection, }, { Name: "insufficient_gas_setFeeConfig_from_admin", @@ -302,7 +302,7 @@ var ( }, SuppliedGas: feemanager.SetFeeConfigGasCost - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas, + WantErr: vm.ErrOutOfGas, }, { Name: "set_config_with_extra_padded_bytes_should_fail_before_Durango", @@ -322,7 +322,7 @@ var ( }, SuppliedGas: feemanager.SetFeeConfigGasCost, ReadOnly: false, - ExpectedErr: feemanager.ErrInvalidLen, + WantErr: feemanager.ErrInvalidLen, SetupBlockContext: func(mbc *contract.MockBlockContext) { mbc.EXPECT().Number().Return(testBlockNumber).AnyTimes() mbc.EXPECT().Timestamp().Return(uint64(0)).AnyTimes() @@ -373,7 +373,7 @@ var ( return config }, SuppliedGas: feemanager.SetFeeConfigGasCost, - ExpectedErr: feemanager.ErrInvalidLen, + WantErr: feemanager.ErrInvalidLen, ReadOnly: false, SetupBlockContext: func(mbc *contract.MockBlockContext) { mbc.EXPECT().Number().Return(testBlockNumber).AnyTimes() diff --git a/precompile/contracts/nativeminter/contract_test.go b/precompile/contracts/nativeminter/contract_test.go index 0dc316ffea..464d8d7a77 100644 --- a/precompile/contracts/nativeminter/contract_test.go +++ b/precompile/contracts/nativeminter/contract_test.go @@ -36,7 +36,7 @@ var tests = []precompiletest.PrecompileTest{ }, SuppliedGas: nativeminter.MintGasCost, ReadOnly: false, - ExpectedErr: nativeminter.ErrCannotMint, + WantErr: nativeminter.ErrCannotMint, }, { Name: "calling_mintNativeCoin_from_Enabled_should_succeed", @@ -148,7 +148,7 @@ var tests = []precompiletest.PrecompileTest{ }, SuppliedGas: nativeminter.MintGasCost, ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection, + WantErr: vm.ErrWriteProtection, }, { Name: "readOnly_mint_with_allow_role_fails", @@ -162,7 +162,7 @@ var tests = []precompiletest.PrecompileTest{ }, SuppliedGas: nativeminter.MintGasCost, ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection, + WantErr: vm.ErrWriteProtection, }, { Name: "readOnly_mint_with_admin_role_fails", @@ -176,7 +176,7 @@ var tests = []precompiletest.PrecompileTest{ }, SuppliedGas: nativeminter.MintGasCost, ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection, + WantErr: vm.ErrWriteProtection, }, { Name: "insufficient_gas_mint_from_admin", @@ -190,7 +190,7 @@ var tests = []precompiletest.PrecompileTest{ }, SuppliedGas: nativeminter.MintGasCost + nativeminter.NativeCoinMintedEventGasCost - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas, + WantErr: vm.ErrOutOfGas, }, { Name: "mint_does_not_log_pre_Durango", @@ -235,7 +235,7 @@ var tests = []precompiletest.PrecompileTest{ }, SuppliedGas: nativeminter.MintGasCost, ReadOnly: false, - ExpectedErr: nativeminter.ErrInvalidLen, + WantErr: nativeminter.ErrInvalidLen, }, { Name: "mint_with_extra_padded_bytes_should_succeed_with_Durango", diff --git a/precompile/contracts/rewardmanager/contract_test.go b/precompile/contracts/rewardmanager/contract_test.go index 2d1571b8da..fb4489cd0d 100644 --- a/precompile/contracts/rewardmanager/contract_test.go +++ b/precompile/contracts/rewardmanager/contract_test.go @@ -37,7 +37,7 @@ var ( }, SuppliedGas: rewardmanager.AllowFeeRecipientsGasCost, ReadOnly: false, - ExpectedErr: rewardmanager.ErrCannotAllowFeeRecipients, + WantErr: rewardmanager.ErrCannotAllowFeeRecipients, }, { Name: "set_reward_address_from_no_role_fails", @@ -51,7 +51,7 @@ var ( }, SuppliedGas: rewardmanager.SetRewardAddressGasCost, ReadOnly: false, - ExpectedErr: rewardmanager.ErrCannotSetRewardAddress, + WantErr: rewardmanager.ErrCannotSetRewardAddress, }, { Name: "disable_rewards_from_no_role_fails", @@ -65,7 +65,7 @@ var ( }, SuppliedGas: rewardmanager.DisableRewardsGasCost, ReadOnly: false, - ExpectedErr: rewardmanager.ErrCannotDisableRewards, + WantErr: rewardmanager.ErrCannotDisableRewards, }, { Name: "set_allow_fee_recipients_from_enabled_succeeds", @@ -380,7 +380,7 @@ var ( }, SuppliedGas: rewardmanager.AllowFeeRecipientsGasCost, ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection, + WantErr: vm.ErrWriteProtection, }, { Name: "readOnly_set_reward_address_with_allowed_role_fails", @@ -394,7 +394,7 @@ var ( }, SuppliedGas: rewardmanager.SetRewardAddressGasCost, ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection, + WantErr: vm.ErrWriteProtection, }, { Name: "insufficient_gas_set_reward_address_from_allowed_role", @@ -408,7 +408,7 @@ var ( }, SuppliedGas: rewardmanager.SetRewardAddressGasCost + rewardmanager.RewardAddressChangedEventGasCost - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas, + WantErr: vm.ErrOutOfGas, }, { Name: "insufficient_gas_allow_fee_recipients_from_allowed_role", @@ -422,7 +422,7 @@ var ( }, SuppliedGas: rewardmanager.AllowFeeRecipientsGasCost + rewardmanager.FeeRecipientsAllowedEventGasCost - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas, + WantErr: vm.ErrOutOfGas, }, { Name: "insufficient_gas_read_current_reward_address_from_allowed_role", @@ -436,7 +436,7 @@ var ( }, SuppliedGas: rewardmanager.CurrentRewardAddressGasCost - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas, + WantErr: vm.ErrOutOfGas, }, { Name: "insufficient_gas_are_fee_recipients_allowed_from_allowed_role", @@ -450,7 +450,7 @@ var ( }, SuppliedGas: rewardmanager.AreFeeRecipientsAllowedGasCost - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas, + WantErr: vm.ErrOutOfGas, }, } ) diff --git a/precompile/contracts/warp/contract_test.go b/precompile/contracts/warp/contract_test.go index 17803abf30..58e11e8d67 100644 --- a/precompile/contracts/warp/contract_test.go +++ b/precompile/contracts/warp/contract_test.go @@ -111,7 +111,7 @@ func getBlockchainIDTests(tb testing.TB, rules extras.AvalancheRules) []precompi }, SuppliedGas: gasConfig.GetBlockchainID - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas, + WantErr: vm.ErrOutOfGas, Rules: rules, }, } @@ -154,7 +154,7 @@ func sendWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []precompi InputFn: func(testing.TB) []byte { return sendWarpMessageInput }, SuppliedGas: gasConfig.SendWarpMessageCost(len(sendWarpMessageInput[4:])), ReadOnly: true, - ExpectedErr: vm.ErrWriteProtection, + WantErr: vm.ErrWriteProtection, Rules: rules, }, { @@ -163,7 +163,7 @@ func sendWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []precompi InputFn: func(testing.TB) []byte { return sendWarpMessageInput }, SuppliedGas: gasConfig.SendWarpMessageBase - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas, + WantErr: vm.ErrOutOfGas, Rules: rules, }, { @@ -172,7 +172,7 @@ func sendWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []precompi InputFn: func(testing.TB) []byte { return sendWarpMessageInput }, SuppliedGas: gasConfig.SendWarpMessageCost(len(sendWarpMessageInput[4:])) - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas, + WantErr: vm.ErrOutOfGas, Rules: rules, }, { @@ -183,7 +183,7 @@ func sendWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []precompi }, SuppliedGas: gasConfig.SendWarpMessageBase, ReadOnly: false, - ExpectedErr: errInvalidSendInput, + WantErr: errInvalidSendInput, Rules: rules, }, { @@ -429,7 +429,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p Predicates: []predicate.Predicate{warpMessagePredicate}, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas, + WantErr: vm.ErrOutOfGas, Rules: rules, }, { @@ -442,7 +442,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(warpMessagePredicate)) - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas, + WantErr: vm.ErrOutOfGas, Rules: rules, }, { @@ -455,7 +455,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(invalidPackedPredicate)), ReadOnly: false, - ExpectedErr: errInvalidPredicateBytes, + WantErr: errInvalidPredicateBytes, Rules: rules, }, { @@ -468,7 +468,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(invalidWarpMsgPredicate)), ReadOnly: false, - ExpectedErr: errInvalidWarpMsg, + WantErr: errInvalidWarpMsg, Rules: rules, }, { @@ -481,7 +481,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(invalidAddressedPredicate)), ReadOnly: false, - ExpectedErr: errInvalidAddressedPayload, + WantErr: errInvalidAddressedPayload, Rules: rules, }, { @@ -492,7 +492,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p }, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase, ReadOnly: false, - ExpectedErr: errInvalidIndexInput, + WantErr: errInvalidIndexInput, Rules: rules, }, { @@ -505,7 +505,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p }, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase, ReadOnly: false, - ExpectedErr: errInvalidIndexInput, + WantErr: errInvalidIndexInput, Rules: rules, }, { @@ -518,7 +518,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p }, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase, ReadOnly: false, - ExpectedErr: errInvalidIndexInput, + WantErr: errInvalidIndexInput, Rules: rules, }, } @@ -719,7 +719,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ Predicates: []predicate.Predicate{warpMessagePredicate}, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas, + WantErr: vm.ErrOutOfGas, Rules: rules, }, { @@ -732,7 +732,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(warpMessagePredicate)) - 1, ReadOnly: false, - ExpectedErr: vm.ErrOutOfGas, + WantErr: vm.ErrOutOfGas, Rules: rules, }, { @@ -745,7 +745,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(invalidPackedPredicate)), ReadOnly: false, - ExpectedErr: errInvalidPredicateBytes, + WantErr: errInvalidPredicateBytes, Rules: rules, }, { @@ -758,7 +758,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(invalidWarpMsgPredicate)), ReadOnly: false, - ExpectedErr: errInvalidWarpMsg, + WantErr: errInvalidWarpMsg, Rules: rules, }, { @@ -771,7 +771,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(invalidHashPredicate)), ReadOnly: false, - ExpectedErr: errInvalidBlockHashPayload, + WantErr: errInvalidBlockHashPayload, Rules: rules, }, { @@ -782,7 +782,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ }, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase, ReadOnly: false, - ExpectedErr: errInvalidIndexInput, + WantErr: errInvalidIndexInput, Rules: rules, }, { @@ -795,7 +795,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ }, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase, ReadOnly: false, - ExpectedErr: errInvalidIndexInput, + WantErr: errInvalidIndexInput, Rules: rules, }, { @@ -808,7 +808,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ }, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase, ReadOnly: false, - ExpectedErr: errInvalidIndexInput, + WantErr: errInvalidIndexInput, Rules: rules, }, } diff --git a/precompile/precompiletest/test_precompile.go b/precompile/precompiletest/test_precompile.go index 77764648ae..21053ef2e8 100644 --- a/precompile/precompiletest/test_precompile.go +++ b/precompile/precompiletest/test_precompile.go @@ -54,8 +54,8 @@ type PrecompileTest struct { AfterHook func(t testing.TB, state *extstate.StateDB) // ExpectedRes is the expected raw byte result returned by the precompile ExpectedRes []byte - // ExpectedErr is the expected error returned by the precompile - ExpectedErr error + // WantErr is the expected error returned by the precompile + WantErr error // ChainConfig is the chain config to use for the precompile's block context // If nil, the default chain config will be used. ChainConfigFn func(*gomock.Controller) precompileconfig.ChainConfig @@ -81,7 +81,7 @@ func (test PrecompileTest) Run(t *testing.T, module modules.Module) { if runParams.Input != nil { ret, remainingGas, err := module.Contract.Run(runParams.AccessibleState, runParams.Caller, runParams.ContractAddress, runParams.Input, runParams.SuppliedGas, runParams.ReadOnly) - require.ErrorIs(t, err, test.ExpectedErr) + require.ErrorIs(t, err, test.WantErr) require.Equal(t, uint64(0), remainingGas) require.Equal(t, test.ExpectedRes, ret) } @@ -105,7 +105,7 @@ func (test PrecompileTest) Bench(b *testing.B, module modules.Module) { snapshot := stateDB.Snapshot() ret, remainingGas, err := module.Contract.Run(runParams.AccessibleState, runParams.Caller, runParams.ContractAddress, runParams.Input, runParams.SuppliedGas, runParams.ReadOnly) - require.ErrorIs(b, err, test.ExpectedErr) + require.ErrorIs(b, err, test.WantErr) require.Equal(b, uint64(0), remainingGas) require.Equal(b, test.ExpectedRes, ret) @@ -141,7 +141,7 @@ func (test PrecompileTest) Bench(b *testing.B, module modules.Module) { // the benchmark should catch the error here. stateDB.RevertToSnapshot(snapshot) ret, remainingGas, err = module.Contract.Run(runParams.AccessibleState, runParams.Caller, runParams.ContractAddress, runParams.Input, runParams.SuppliedGas, runParams.ReadOnly) - require.ErrorIs(b, err, test.ExpectedErr) + require.ErrorIs(b, err, test.WantErr) require.Equal(b, uint64(0), remainingGas) require.Equal(b, test.ExpectedRes, ret) From 49d7da7c5b4c0c7df5760e3c87ec72d244d5db3f Mon Sep 17 00:00:00 2001 From: Jonathan Oppenheimer Date: Wed, 3 Dec 2025 10:55:32 -0500 Subject: [PATCH 13/19] fix: revert change --- plugin/evm/vm_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin/evm/vm_test.go b/plugin/evm/vm_test.go index c0be0d8f5f..1706f568df 100644 --- a/plugin/evm/vm_test.go +++ b/plugin/evm/vm_test.go @@ -1088,7 +1088,7 @@ func testStickyPreference(t *testing.T, scheme string) { require.Equal(t, blkDHash, vm1.blockChain.CurrentBlock().Hash(), "expected current block to have hash %s but got %s", blkDHash.Hex(), vm1.blockChain.CurrentBlock().Hash().Hex()) // Attempt to accept out of order - require.ErrorContains(t, err, "expected accepted block to have parent", "unexpected error when accepting out of order block") //nolint:forbidigo // uses upstream code + require.ErrorContains(t, vm1BlkD.Accept(t.Context()), "expected accepted block to have parent", "unexpected error when accepting out of order block") //nolint:forbidigo // uses upstream code // Accept in order require.NoError(t, vm1BlkC.Accept(t.Context()), "Block failed verification on VM1") From bb3f2fab6ada9d8af5223400bd9142e8ae0d5a5f Mon Sep 17 00:00:00 2001 From: Jonathan Oppenheimer Date: Wed, 3 Dec 2025 11:53:38 -0500 Subject: [PATCH 14/19] style: revert expected -> want --- .../precompile_config_test_template.go | 4 +- .../precompile_contract_test_template.go | 12 ++--- params/extras/precompile_config_test.go | 22 ++++---- .../allowlist/allowlisttest/test_allowlist.go | 50 +++++++++---------- .../allowlisttest/test_allowlist_config.go | 20 ++++---- .../contracts/feemanager/config_test.go | 8 +-- .../contracts/feemanager/contract_test.go | 16 +++--- .../contracts/nativeminter/config_test.go | 18 +++---- .../contracts/nativeminter/contract_test.go | 12 ++--- .../contracts/rewardmanager/config_test.go | 2 +- .../contracts/rewardmanager/contract_test.go | 18 +++---- precompile/contracts/warp/config_test.go | 10 ++-- precompile/contracts/warp/contract_test.go | 42 ++++++++-------- precompile/precompiletest/test_config.go | 8 +-- precompile/precompiletest/test_precompile.go | 10 ++-- 15 files changed, 126 insertions(+), 126 deletions(-) diff --git a/accounts/abi/bind/precompilebind/precompile_config_test_template.go b/accounts/abi/bind/precompilebind/precompile_config_test_template.go index c3adcdee53..a8ef844991 100644 --- a/accounts/abi/bind/precompilebind/precompile_config_test_template.go +++ b/accounts/abi/bind/precompilebind/precompile_config_test_template.go @@ -41,13 +41,13 @@ func TestVerify(t *testing.T) { config.EXPECT().IsDurango(gomock.Any()).Return(true).AnyTimes() return config }(), - WantError: nil, + ExpectedError: nil, }, // CUSTOM CODE STARTS HERE // Add your own Verify tests here, e.g.: // "your custom test name": { // Config: NewConfig(utils.NewUint64(3), {{- if .Contract.AllowList}} admins, enableds, managers{{- end}}), - // WantError: ErrYourCustomError, + // ExpectedError: ErrYourCustomError, // }, } {{- if .Contract.AllowList}} diff --git a/accounts/abi/bind/precompilebind/precompile_contract_test_template.go b/accounts/abi/bind/precompilebind/precompile_contract_test_template.go index 0709d866ee..4b03c82ddd 100644 --- a/accounts/abi/bind/precompilebind/precompile_contract_test_template.go +++ b/accounts/abi/bind/precompilebind/precompile_contract_test_template.go @@ -95,7 +95,7 @@ var( {{- end}} SuppliedGas: {{$func.Normalized.Name}}GasCost, ReadOnly: false, - WantErr: {{if $fail}} ErrCannot{{$func.Normalized.Name}} {{- else}} nil {{- end}}, + ExpectedErr: {{if $fail}} ErrCannot{{$func.Normalized.Name}} {{- else}} nil {{- end}}, }, {{- end}} {{- end}} @@ -124,7 +124,7 @@ var( }, SuppliedGas: {{$func.Normalized.Name}}GasCost, ReadOnly: true, - WantErr: vm.ErrWriteProtection, + ExpectedErr: vm.ErrWriteProtection, }, {{- end}} { @@ -151,7 +151,7 @@ var( }, SuppliedGas: {{$func.Normalized.Name}}GasCost - 1, ReadOnly: false, - WantErr: vm.ErrOutOfGas, + ExpectedErr: vm.ErrOutOfGas, }, {{- end}} {{- if .Contract.Fallback}} @@ -161,7 +161,7 @@ var( Input: []byte{}, SuppliedGas: {{.Contract.Type}}FallbackGasCost - 1, ReadOnly: false, - WantErr: vm.ErrOutOfGas, + ExpectedErr: vm.ErrOutOfGas, }, { Name: "readOnly fallback should fail", @@ -169,7 +169,7 @@ var( Input: []byte{}, SuppliedGas: {{.Contract.Type}}FallbackGasCost, ReadOnly: true, - WantErr: vm.ErrWriteProtection, + ExpectedErr: vm.ErrWriteProtection, }, { Name: "fallback should succeed", @@ -177,7 +177,7 @@ var( Input: []byte{}, SuppliedGas: {{.Contract.Type}}FallbackGasCost, ReadOnly: false, - WantErr: nil, + ExpectedErr: nil, // CUSTOM CODE STARTS HERE // set expected output here ExpectedRes: []byte{}, diff --git a/params/extras/precompile_config_test.go b/params/extras/precompile_config_test.go index 59f3e02b0d..8be3cf675a 100644 --- a/params/extras/precompile_config_test.go +++ b/params/extras/precompile_config_test.go @@ -92,9 +92,9 @@ func TestVerifyWithChainConfigAtNilTimestamp(t *testing.T) { func TestVerifyPrecompileUpgrades(t *testing.T) { admins := []common.Address{{1}} tests := []struct { - name string - upgrades []PrecompileUpgrade - wantError error + name string + upgrades []PrecompileUpgrade + expectedError error }{ { name: "enable and disable tx allow list", @@ -106,7 +106,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { Config: txallowlist.NewDisableConfig(utils.NewUint64(2)), }, }, - wantError: nil, + expectedError: nil, }, { name: "invalid allow list config in tx allowlist", @@ -121,7 +121,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { Config: txallowlist.NewConfig(utils.NewUint64(3), admins, admins, admins), }, }, - wantError: allowlist.ErrAdminAndEnabledAddress, + expectedError: allowlist.ErrAdminAndEnabledAddress, }, { name: "invalid initial fee manager config", @@ -135,7 +135,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { }()), }, }, - wantError: commontype.ErrGasLimitTooLow, + expectedError: commontype.ErrGasLimitTooLow, }, { name: "invalid initial fee manager config gas limit 0", @@ -149,7 +149,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { }()), }, }, - wantError: commontype.ErrGasLimitTooLow, + expectedError: commontype.ErrGasLimitTooLow, }, { name: "different upgrades are allowed to configure same timestamp for different precompiles", @@ -161,7 +161,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { Config: feemanager.NewConfig(utils.NewUint64(1), admins, nil, nil, nil), }, }, - wantError: nil, + expectedError: nil, }, { name: "different upgrades must be monotonically increasing", @@ -173,7 +173,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { Config: feemanager.NewConfig(utils.NewUint64(1), admins, nil, nil, nil), }, }, - wantError: errPrecompileUpgradeTimestampNotMonotonic, + expectedError: errPrecompileUpgradeTimestampNotMonotonic, }, { name: "upgrades with same keys are not allowed to configure same timestamp for same precompiles", @@ -185,7 +185,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { Config: txallowlist.NewDisableConfig(utils.NewUint64(1)), }, }, - wantError: errPrecompileUpgradeSameKeyTimestampNotStrictly, + expectedError: errPrecompileUpgradeSameKeyTimestampNotStrictly, }, } for _, tt := range tests { @@ -197,7 +197,7 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { config.PrecompileUpgrades = tt.upgrades err := config.Verify() - require.ErrorIs(err, tt.wantError) + require.ErrorIs(err, tt.expectedError) }) } } diff --git a/precompile/allowlist/allowlisttest/test_allowlist.go b/precompile/allowlist/allowlisttest/test_allowlist.go index 33ad4c2944..241dc7ef68 100644 --- a/precompile/allowlist/allowlisttest/test_allowlist.go +++ b/precompile/allowlist/allowlisttest/test_allowlist.go @@ -106,7 +106,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - WantErr: allowlist.ErrCannotModifyAllowList, + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "no_role_set_enabled", @@ -120,7 +120,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - WantErr: allowlist.ErrCannotModifyAllowList, + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "no_role_set_admin", @@ -134,7 +134,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - WantErr: allowlist.ErrCannotModifyAllowList, + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "enabled_set_no_role", @@ -148,7 +148,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - WantErr: allowlist.ErrCannotModifyAllowList, + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "enabled_set_enabled", @@ -162,7 +162,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - WantErr: allowlist.ErrCannotModifyAllowList, + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "enabled_set_admin", @@ -176,7 +176,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - WantErr: allowlist.ErrCannotModifyAllowList, + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "no_role_set_manager_pre_Durango", @@ -195,7 +195,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: 0, ReadOnly: false, - WantErr: contract.ErrInvalidNonActivatedFunctionSelector, + ExpectedErr: contract.ErrInvalidNonActivatedFunctionSelector, }, { Name: "no_role_set_manager", @@ -214,7 +214,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - WantErr: allowlist.ErrCannotModifyAllowList, + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "enabled_role_set_manager_pre_Durango", @@ -233,7 +233,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: 0, ReadOnly: false, - WantErr: contract.ErrInvalidNonActivatedFunctionSelector, + ExpectedErr: contract.ErrInvalidNonActivatedFunctionSelector, }, { Name: "enabled_set_manager", @@ -252,7 +252,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - WantErr: allowlist.ErrCannotModifyAllowList, + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "admin_set_manager_pre_Durango", @@ -271,7 +271,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: 0, ReadOnly: false, - WantErr: contract.ErrInvalidNonActivatedFunctionSelector, + ExpectedErr: contract.ErrInvalidNonActivatedFunctionSelector, }, { Name: "admin_set_manager", @@ -312,7 +312,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom SuppliedGas: allowlist.ModifyAllowListGasCost + allowlist.AllowListEventGasCost, ReadOnly: false, ExpectedRes: []byte{}, - WantErr: nil, + ExpectedErr: nil, AfterHook: func(t testing.TB, state *extstate.StateDB) { res := allowlist.GetAllowListStatus(state, contractAddress, TestNoRoleAddr) require.Equal(t, allowlist.NoRole, res) @@ -334,7 +334,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom SuppliedGas: allowlist.ModifyAllowListGasCost + allowlist.AllowListEventGasCost, ReadOnly: false, ExpectedRes: []byte{}, - WantErr: nil, + ExpectedErr: nil, AfterHook: func(t testing.TB, state *extstate.StateDB) { res := allowlist.GetAllowListStatus(state, contractAddress, TestNoRoleAddr) require.Equal(t, allowlist.EnabledRole, res) @@ -361,7 +361,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - WantErr: allowlist.ErrCannotModifyAllowList, + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "manager_set_no_role_to_admin", @@ -375,7 +375,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - WantErr: allowlist.ErrCannotModifyAllowList, + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "manager_set_enabled_to_admin", @@ -389,7 +389,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - WantErr: allowlist.ErrCannotModifyAllowList, + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "manager_set_enabled_role_to_manager", @@ -408,7 +408,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - WantErr: allowlist.ErrCannotModifyAllowList, + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "manager_set_enabled_role_to_no_role", @@ -444,7 +444,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - WantErr: allowlist.ErrCannotModifyAllowList, + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "manager_set_admin_role_to_enabled", @@ -458,7 +458,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - WantErr: allowlist.ErrCannotModifyAllowList, + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "manager_set_admin_to_manager", @@ -477,7 +477,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - WantErr: allowlist.ErrCannotModifyAllowList, + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "manager_set_manager_to_no_role", @@ -491,7 +491,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: false, - WantErr: allowlist.ErrCannotModifyAllowList, + ExpectedErr: allowlist.ErrCannotModifyAllowList, }, { Name: "admin_set_no_role_with_readOnly_enabled", @@ -505,7 +505,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost, ReadOnly: true, - WantErr: vm.ErrWriteProtection, + ExpectedErr: vm.ErrWriteProtection, }, { Name: "admin_set_no_role_insufficient_gas", @@ -519,7 +519,7 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom }, SuppliedGas: allowlist.ModifyAllowListGasCost - 1, ReadOnly: false, - WantErr: vm.ErrOutOfGas, + ExpectedErr: vm.ErrOutOfGas, }, { Name: "no_role_read_allow_list", @@ -571,8 +571,8 @@ func AllowListTests(_ testing.TB, module modules.Module) []precompiletest.Precom return input }, SuppliedGas: allowlist.ReadAllowListGasCost - 1, - ReadOnly: true, - WantErr: vm.ErrOutOfGas, + ReadOnly: true, + ExpectedErr: vm.ErrOutOfGas, }, { Name: "initial_config_sets_admins", diff --git a/precompile/allowlist/allowlisttest/test_allowlist_config.go b/precompile/allowlist/allowlisttest/test_allowlist_config.go index 780430863f..6415a942e9 100644 --- a/precompile/allowlist/allowlisttest/test_allowlist_config.go +++ b/precompile/allowlist/allowlisttest/test_allowlist_config.go @@ -57,7 +57,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: nil, EnabledAddresses: nil, }), - WantError: allowlist.ErrDuplicateAdminAddress, + ExpectedError: allowlist.ErrDuplicateAdminAddress, }, "invalid allow list config with duplicate enableds in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -65,7 +65,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: nil, EnabledAddresses: []common.Address{TestEnabledAddr, TestEnabledAddr}, }), - WantError: allowlist.ErrDuplicateEnabledAddress, + ExpectedError: allowlist.ErrDuplicateEnabledAddress, }, "invalid allow list config with duplicate managers in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -73,7 +73,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: []common.Address{TestManagerAddr, TestManagerAddr}, EnabledAddresses: nil, }), - WantError: allowlist.ErrDuplicateManagerAddress, + ExpectedError: allowlist.ErrDuplicateManagerAddress, }, "invalid allow list config with same admin and enabled in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -81,7 +81,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: nil, EnabledAddresses: []common.Address{TestAdminAddr}, }), - WantError: allowlist.ErrAdminAndEnabledAddress, + ExpectedError: allowlist.ErrAdminAndEnabledAddress, }, "invalid allow list config with same admin and manager in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -89,7 +89,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: []common.Address{TestAdminAddr}, EnabledAddresses: nil, }), - WantError: allowlist.ErrAdminAndManagerAddress, + ExpectedError: allowlist.ErrAdminAndManagerAddress, }, "invalid allow list config with same manager and enabled in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -97,7 +97,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: []common.Address{TestManagerAddr}, EnabledAddresses: []common.Address{TestManagerAddr}, }), - WantError: allowlist.ErrEnabledAndManagerAddress, + ExpectedError: allowlist.ErrEnabledAndManagerAddress, }, "invalid allow list config with manager role before activation": { Config: mkConfigWithUpgradeAndAllowList(module, &allowlist.AllowListConfig{ @@ -112,7 +112,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] config.EXPECT().IsDurango(gomock.Any()).Return(false) return config }(), - WantError: allowlist.ErrCannotAddManagersBeforeDurango, + ExpectedError: allowlist.ErrCannotAddManagersBeforeDurango, }, "nil member allow list config in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -120,7 +120,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: nil, EnabledAddresses: nil, }), - WantError: nil, + ExpectedError: nil, }, "empty member allow list config in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -128,7 +128,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: []common.Address{}, EnabledAddresses: []common.Address{}, }), - WantError: nil, + ExpectedError: nil, }, "valid allow list config in allowlist": { Config: mkConfigWithAllowList(module, &allowlist.AllowListConfig{ @@ -136,7 +136,7 @@ func AllowListConfigVerifyTests(t testing.TB, module modules.Module) map[string] ManagerAddresses: []common.Address{TestManagerAddr}, EnabledAddresses: []common.Address{TestEnabledAddr}, }), - WantError: nil, + ExpectedError: nil, }, } } diff --git a/precompile/contracts/feemanager/config_test.go b/precompile/contracts/feemanager/config_test.go index ab7ee05d80..7569381f32 100644 --- a/precompile/contracts/feemanager/config_test.go +++ b/precompile/contracts/feemanager/config_test.go @@ -37,12 +37,12 @@ func TestVerify(t *testing.T) { invalidFeeConfig.GasLimit = big.NewInt(0) tests := map[string]precompiletest.ConfigVerifyTest{ "invalid initial fee manager config": { - Config: feemanager.NewConfig(utils.NewUint64(3), admins, nil, nil, &invalidFeeConfig), - WantError: commontype.ErrGasLimitTooLow, + Config: feemanager.NewConfig(utils.NewUint64(3), admins, nil, nil, &invalidFeeConfig), + ExpectedError: commontype.ErrGasLimitTooLow, }, "nil initial fee manager config": { - Config: feemanager.NewConfig(utils.NewUint64(3), admins, nil, nil, &commontype.FeeConfig{}), - WantError: commontype.ErrGasLimitNil, + Config: feemanager.NewConfig(utils.NewUint64(3), admins, nil, nil, &commontype.FeeConfig{}), + ExpectedError: commontype.ErrGasLimitNil, }, } allowlisttest.VerifyPrecompileWithAllowListTests(t, feemanager.Module, tests) diff --git a/precompile/contracts/feemanager/contract_test.go b/precompile/contracts/feemanager/contract_test.go index 17625dc201..dc6f4d940c 100644 --- a/precompile/contracts/feemanager/contract_test.go +++ b/precompile/contracts/feemanager/contract_test.go @@ -60,7 +60,7 @@ var ( }, SuppliedGas: feemanager.SetFeeConfigGasCost, ReadOnly: false, - WantErr: feemanager.ErrCannotChangeFee, + ExpectedErr: feemanager.ErrCannotChangeFee, }, { Name: "set_config_from_enabled_address_succeeds_and_emits_logs", @@ -121,7 +121,7 @@ var ( Config: &feemanager.Config{ InitialFeeConfig: &testFeeConfig, }, - WantErr: commontype.ErrMinBlockGasCostTooHigh, + ExpectedErr: commontype.ErrMinBlockGasCostTooHigh, AfterHook: func(t testing.TB, state *extstate.StateDB) { feeConfig := feemanager.GetStoredFeeConfig(state) require.Equal(t, testFeeConfig, feeConfig) @@ -260,7 +260,7 @@ var ( }, SuppliedGas: feemanager.SetFeeConfigGasCost, ReadOnly: true, - WantErr: vm.ErrWriteProtection, + ExpectedErr: vm.ErrWriteProtection, }, { Name: "readOnly_setFeeConfig_with_allow_role_fails", @@ -274,7 +274,7 @@ var ( }, SuppliedGas: feemanager.SetFeeConfigGasCost, ReadOnly: true, - WantErr: vm.ErrWriteProtection, + ExpectedErr: vm.ErrWriteProtection, }, { Name: "readOnly_setFeeConfig_with_admin_role_fails", @@ -288,7 +288,7 @@ var ( }, SuppliedGas: feemanager.SetFeeConfigGasCost, ReadOnly: true, - WantErr: vm.ErrWriteProtection, + ExpectedErr: vm.ErrWriteProtection, }, { Name: "insufficient_gas_setFeeConfig_from_admin", @@ -302,7 +302,7 @@ var ( }, SuppliedGas: feemanager.SetFeeConfigGasCost - 1, ReadOnly: false, - WantErr: vm.ErrOutOfGas, + ExpectedErr: vm.ErrOutOfGas, }, { Name: "set_config_with_extra_padded_bytes_should_fail_before_Durango", @@ -322,7 +322,7 @@ var ( }, SuppliedGas: feemanager.SetFeeConfigGasCost, ReadOnly: false, - WantErr: feemanager.ErrInvalidLen, + ExpectedErr: feemanager.ErrInvalidLen, SetupBlockContext: func(mbc *contract.MockBlockContext) { mbc.EXPECT().Number().Return(testBlockNumber).AnyTimes() mbc.EXPECT().Timestamp().Return(uint64(0)).AnyTimes() @@ -373,7 +373,7 @@ var ( return config }, SuppliedGas: feemanager.SetFeeConfigGasCost, - WantErr: feemanager.ErrInvalidLen, + ExpectedErr: feemanager.ErrInvalidLen, ReadOnly: false, SetupBlockContext: func(mbc *contract.MockBlockContext) { mbc.EXPECT().Number().Return(testBlockNumber).AnyTimes() diff --git a/precompile/contracts/nativeminter/config_test.go b/precompile/contracts/nativeminter/config_test.go index 56ab9e018e..acf95ad7c2 100644 --- a/precompile/contracts/nativeminter/config_test.go +++ b/precompile/contracts/nativeminter/config_test.go @@ -30,19 +30,19 @@ func TestVerify(t *testing.T) { config.EXPECT().IsDurango(gomock.Any()).Return(true).AnyTimes() return config }(), - WantError: nil, + ExpectedError: nil, }, "invalid allow list config in native minter allowlisttest": { - Config: nativeminter.NewConfig(utils.NewUint64(3), admins, admins, nil, nil), - WantError: allowlist.ErrAdminAndEnabledAddress, + Config: nativeminter.NewConfig(utils.NewUint64(3), admins, admins, nil, nil), + ExpectedError: allowlist.ErrAdminAndEnabledAddress, }, "duplicate admins in config in native minter allowlisttest": { - Config: nativeminter.NewConfig(utils.NewUint64(3), append(admins, admins[0]), enableds, managers, nil), - WantError: allowlist.ErrDuplicateAdminAddress, + Config: nativeminter.NewConfig(utils.NewUint64(3), append(admins, admins[0]), enableds, managers, nil), + ExpectedError: allowlist.ErrDuplicateAdminAddress, }, "duplicate enableds in config in native minter allowlisttest": { - Config: nativeminter.NewConfig(utils.NewUint64(3), admins, append(enableds, enableds[0]), managers, nil), - WantError: allowlist.ErrDuplicateEnabledAddress, + Config: nativeminter.NewConfig(utils.NewUint64(3), admins, append(enableds, enableds[0]), managers, nil), + ExpectedError: allowlist.ErrDuplicateEnabledAddress, }, "nil amount in native minter config": { Config: nativeminter.NewConfig(utils.NewUint64(3), admins, nil, nil, @@ -50,7 +50,7 @@ func TestVerify(t *testing.T) { common.HexToAddress("0x01"): math.NewHexOrDecimal256(123), common.HexToAddress("0x02"): nil, }), - WantError: nativeminter.ErrInitialMintNilAmount, + ExpectedError: nativeminter.ErrInitialMintNilAmount, }, "negative amount in native minter config": { Config: nativeminter.NewConfig(utils.NewUint64(3), admins, nil, nil, @@ -58,7 +58,7 @@ func TestVerify(t *testing.T) { common.HexToAddress("0x01"): math.NewHexOrDecimal256(123), common.HexToAddress("0x02"): math.NewHexOrDecimal256(-1), }), - WantError: nativeminter.ErrInitialMintInvalidAmount, + ExpectedError: nativeminter.ErrInitialMintInvalidAmount, }, } allowlisttest.VerifyPrecompileWithAllowListTests(t, nativeminter.Module, tests) diff --git a/precompile/contracts/nativeminter/contract_test.go b/precompile/contracts/nativeminter/contract_test.go index 464d8d7a77..0dc316ffea 100644 --- a/precompile/contracts/nativeminter/contract_test.go +++ b/precompile/contracts/nativeminter/contract_test.go @@ -36,7 +36,7 @@ var tests = []precompiletest.PrecompileTest{ }, SuppliedGas: nativeminter.MintGasCost, ReadOnly: false, - WantErr: nativeminter.ErrCannotMint, + ExpectedErr: nativeminter.ErrCannotMint, }, { Name: "calling_mintNativeCoin_from_Enabled_should_succeed", @@ -148,7 +148,7 @@ var tests = []precompiletest.PrecompileTest{ }, SuppliedGas: nativeminter.MintGasCost, ReadOnly: true, - WantErr: vm.ErrWriteProtection, + ExpectedErr: vm.ErrWriteProtection, }, { Name: "readOnly_mint_with_allow_role_fails", @@ -162,7 +162,7 @@ var tests = []precompiletest.PrecompileTest{ }, SuppliedGas: nativeminter.MintGasCost, ReadOnly: true, - WantErr: vm.ErrWriteProtection, + ExpectedErr: vm.ErrWriteProtection, }, { Name: "readOnly_mint_with_admin_role_fails", @@ -176,7 +176,7 @@ var tests = []precompiletest.PrecompileTest{ }, SuppliedGas: nativeminter.MintGasCost, ReadOnly: true, - WantErr: vm.ErrWriteProtection, + ExpectedErr: vm.ErrWriteProtection, }, { Name: "insufficient_gas_mint_from_admin", @@ -190,7 +190,7 @@ var tests = []precompiletest.PrecompileTest{ }, SuppliedGas: nativeminter.MintGasCost + nativeminter.NativeCoinMintedEventGasCost - 1, ReadOnly: false, - WantErr: vm.ErrOutOfGas, + ExpectedErr: vm.ErrOutOfGas, }, { Name: "mint_does_not_log_pre_Durango", @@ -235,7 +235,7 @@ var tests = []precompiletest.PrecompileTest{ }, SuppliedGas: nativeminter.MintGasCost, ReadOnly: false, - WantErr: nativeminter.ErrInvalidLen, + ExpectedErr: nativeminter.ErrInvalidLen, }, { Name: "mint_with_extra_padded_bytes_should_succeed_with_Durango", diff --git a/precompile/contracts/rewardmanager/config_test.go b/precompile/contracts/rewardmanager/config_test.go index 49f1505e0f..04476f4d04 100644 --- a/precompile/contracts/rewardmanager/config_test.go +++ b/precompile/contracts/rewardmanager/config_test.go @@ -26,7 +26,7 @@ func TestVerify(t *testing.T) { AllowFeeRecipients: true, RewardAddress: common.HexToAddress("0x01"), }), - WantError: rewardmanager.ErrCannotEnableBothRewards, + ExpectedError: rewardmanager.ErrCannotEnableBothRewards, }, } allowlisttest.VerifyPrecompileWithAllowListTests(t, rewardmanager.Module, tests) diff --git a/precompile/contracts/rewardmanager/contract_test.go b/precompile/contracts/rewardmanager/contract_test.go index fb4489cd0d..2d1571b8da 100644 --- a/precompile/contracts/rewardmanager/contract_test.go +++ b/precompile/contracts/rewardmanager/contract_test.go @@ -37,7 +37,7 @@ var ( }, SuppliedGas: rewardmanager.AllowFeeRecipientsGasCost, ReadOnly: false, - WantErr: rewardmanager.ErrCannotAllowFeeRecipients, + ExpectedErr: rewardmanager.ErrCannotAllowFeeRecipients, }, { Name: "set_reward_address_from_no_role_fails", @@ -51,7 +51,7 @@ var ( }, SuppliedGas: rewardmanager.SetRewardAddressGasCost, ReadOnly: false, - WantErr: rewardmanager.ErrCannotSetRewardAddress, + ExpectedErr: rewardmanager.ErrCannotSetRewardAddress, }, { Name: "disable_rewards_from_no_role_fails", @@ -65,7 +65,7 @@ var ( }, SuppliedGas: rewardmanager.DisableRewardsGasCost, ReadOnly: false, - WantErr: rewardmanager.ErrCannotDisableRewards, + ExpectedErr: rewardmanager.ErrCannotDisableRewards, }, { Name: "set_allow_fee_recipients_from_enabled_succeeds", @@ -380,7 +380,7 @@ var ( }, SuppliedGas: rewardmanager.AllowFeeRecipientsGasCost, ReadOnly: true, - WantErr: vm.ErrWriteProtection, + ExpectedErr: vm.ErrWriteProtection, }, { Name: "readOnly_set_reward_address_with_allowed_role_fails", @@ -394,7 +394,7 @@ var ( }, SuppliedGas: rewardmanager.SetRewardAddressGasCost, ReadOnly: true, - WantErr: vm.ErrWriteProtection, + ExpectedErr: vm.ErrWriteProtection, }, { Name: "insufficient_gas_set_reward_address_from_allowed_role", @@ -408,7 +408,7 @@ var ( }, SuppliedGas: rewardmanager.SetRewardAddressGasCost + rewardmanager.RewardAddressChangedEventGasCost - 1, ReadOnly: false, - WantErr: vm.ErrOutOfGas, + ExpectedErr: vm.ErrOutOfGas, }, { Name: "insufficient_gas_allow_fee_recipients_from_allowed_role", @@ -422,7 +422,7 @@ var ( }, SuppliedGas: rewardmanager.AllowFeeRecipientsGasCost + rewardmanager.FeeRecipientsAllowedEventGasCost - 1, ReadOnly: false, - WantErr: vm.ErrOutOfGas, + ExpectedErr: vm.ErrOutOfGas, }, { Name: "insufficient_gas_read_current_reward_address_from_allowed_role", @@ -436,7 +436,7 @@ var ( }, SuppliedGas: rewardmanager.CurrentRewardAddressGasCost - 1, ReadOnly: false, - WantErr: vm.ErrOutOfGas, + ExpectedErr: vm.ErrOutOfGas, }, { Name: "insufficient_gas_are_fee_recipients_allowed_from_allowed_role", @@ -450,7 +450,7 @@ var ( }, SuppliedGas: rewardmanager.AreFeeRecipientsAllowedGasCost - 1, ReadOnly: false, - WantErr: vm.ErrOutOfGas, + ExpectedErr: vm.ErrOutOfGas, }, } ) diff --git a/precompile/contracts/warp/config_test.go b/precompile/contracts/warp/config_test.go index 1c875af52f..e87ba56876 100644 --- a/precompile/contracts/warp/config_test.go +++ b/precompile/contracts/warp/config_test.go @@ -16,12 +16,12 @@ import ( func TestVerify(t *testing.T) { tests := map[string]precompiletest.ConfigVerifyTest{ "quorum numerator less than minimum": { - Config: NewConfig(utils.NewUint64(3), WarpQuorumNumeratorMinimum-1, false), - WantError: ErrInvalidQuorumRatio, + Config: NewConfig(utils.NewUint64(3), WarpQuorumNumeratorMinimum-1, false), + ExpectedError: ErrInvalidQuorumRatio, }, "quorum numerator greater than quorum denominator": { - Config: NewConfig(utils.NewUint64(3), WarpQuorumDenominator+1, false), - WantError: ErrInvalidQuorumRatio, + Config: NewConfig(utils.NewUint64(3), WarpQuorumDenominator+1, false), + ExpectedError: ErrInvalidQuorumRatio, }, "default quorum numerator": { Config: NewDefaultConfig(utils.NewUint64(3)), @@ -39,7 +39,7 @@ func TestVerify(t *testing.T) { config.EXPECT().IsDurango(gomock.Any()).Return(false) return config }(), - WantError: errWarpCannotBeActivated, + ExpectedError: errWarpCannotBeActivated, }, } precompiletest.RunVerifyTests(t, tests) diff --git a/precompile/contracts/warp/contract_test.go b/precompile/contracts/warp/contract_test.go index 58e11e8d67..17803abf30 100644 --- a/precompile/contracts/warp/contract_test.go +++ b/precompile/contracts/warp/contract_test.go @@ -111,7 +111,7 @@ func getBlockchainIDTests(tb testing.TB, rules extras.AvalancheRules) []precompi }, SuppliedGas: gasConfig.GetBlockchainID - 1, ReadOnly: false, - WantErr: vm.ErrOutOfGas, + ExpectedErr: vm.ErrOutOfGas, Rules: rules, }, } @@ -154,7 +154,7 @@ func sendWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []precompi InputFn: func(testing.TB) []byte { return sendWarpMessageInput }, SuppliedGas: gasConfig.SendWarpMessageCost(len(sendWarpMessageInput[4:])), ReadOnly: true, - WantErr: vm.ErrWriteProtection, + ExpectedErr: vm.ErrWriteProtection, Rules: rules, }, { @@ -163,7 +163,7 @@ func sendWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []precompi InputFn: func(testing.TB) []byte { return sendWarpMessageInput }, SuppliedGas: gasConfig.SendWarpMessageBase - 1, ReadOnly: false, - WantErr: vm.ErrOutOfGas, + ExpectedErr: vm.ErrOutOfGas, Rules: rules, }, { @@ -172,7 +172,7 @@ func sendWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []precompi InputFn: func(testing.TB) []byte { return sendWarpMessageInput }, SuppliedGas: gasConfig.SendWarpMessageCost(len(sendWarpMessageInput[4:])) - 1, ReadOnly: false, - WantErr: vm.ErrOutOfGas, + ExpectedErr: vm.ErrOutOfGas, Rules: rules, }, { @@ -183,7 +183,7 @@ func sendWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []precompi }, SuppliedGas: gasConfig.SendWarpMessageBase, ReadOnly: false, - WantErr: errInvalidSendInput, + ExpectedErr: errInvalidSendInput, Rules: rules, }, { @@ -429,7 +429,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p Predicates: []predicate.Predicate{warpMessagePredicate}, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase - 1, ReadOnly: false, - WantErr: vm.ErrOutOfGas, + ExpectedErr: vm.ErrOutOfGas, Rules: rules, }, { @@ -442,7 +442,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(warpMessagePredicate)) - 1, ReadOnly: false, - WantErr: vm.ErrOutOfGas, + ExpectedErr: vm.ErrOutOfGas, Rules: rules, }, { @@ -455,7 +455,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(invalidPackedPredicate)), ReadOnly: false, - WantErr: errInvalidPredicateBytes, + ExpectedErr: errInvalidPredicateBytes, Rules: rules, }, { @@ -468,7 +468,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(invalidWarpMsgPredicate)), ReadOnly: false, - WantErr: errInvalidWarpMsg, + ExpectedErr: errInvalidWarpMsg, Rules: rules, }, { @@ -481,7 +481,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(invalidAddressedPredicate)), ReadOnly: false, - WantErr: errInvalidAddressedPayload, + ExpectedErr: errInvalidAddressedPayload, Rules: rules, }, { @@ -492,7 +492,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p }, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase, ReadOnly: false, - WantErr: errInvalidIndexInput, + ExpectedErr: errInvalidIndexInput, Rules: rules, }, { @@ -505,7 +505,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p }, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase, ReadOnly: false, - WantErr: errInvalidIndexInput, + ExpectedErr: errInvalidIndexInput, Rules: rules, }, { @@ -518,7 +518,7 @@ func getVerifiedWarpMessageTests(tb testing.TB, rules extras.AvalancheRules) []p }, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase, ReadOnly: false, - WantErr: errInvalidIndexInput, + ExpectedErr: errInvalidIndexInput, Rules: rules, }, } @@ -719,7 +719,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ Predicates: []predicate.Predicate{warpMessagePredicate}, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase - 1, ReadOnly: false, - WantErr: vm.ErrOutOfGas, + ExpectedErr: vm.ErrOutOfGas, Rules: rules, }, { @@ -732,7 +732,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(warpMessagePredicate)) - 1, ReadOnly: false, - WantErr: vm.ErrOutOfGas, + ExpectedErr: vm.ErrOutOfGas, Rules: rules, }, { @@ -745,7 +745,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(invalidPackedPredicate)), ReadOnly: false, - WantErr: errInvalidPredicateBytes, + ExpectedErr: errInvalidPredicateBytes, Rules: rules, }, { @@ -758,7 +758,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(invalidWarpMsgPredicate)), ReadOnly: false, - WantErr: errInvalidWarpMsg, + ExpectedErr: errInvalidWarpMsg, Rules: rules, }, { @@ -771,7 +771,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ }, SuppliedGas: gasConfig.GetVerifiedWarpMessageCost(len(invalidHashPredicate)), ReadOnly: false, - WantErr: errInvalidBlockHashPayload, + ExpectedErr: errInvalidBlockHashPayload, Rules: rules, }, { @@ -782,7 +782,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ }, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase, ReadOnly: false, - WantErr: errInvalidIndexInput, + ExpectedErr: errInvalidIndexInput, Rules: rules, }, { @@ -795,7 +795,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ }, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase, ReadOnly: false, - WantErr: errInvalidIndexInput, + ExpectedErr: errInvalidIndexInput, Rules: rules, }, { @@ -808,7 +808,7 @@ func getVerifiedWarpBlockHashTests(tb testing.TB, rules extras.AvalancheRules) [ }, SuppliedGas: gasConfig.GetVerifiedWarpMessageBase, ReadOnly: false, - WantErr: errInvalidIndexInput, + ExpectedErr: errInvalidIndexInput, Rules: rules, }, } diff --git a/precompile/precompiletest/test_config.go b/precompile/precompiletest/test_config.go index 44c537fd63..875019c67d 100644 --- a/precompile/precompiletest/test_config.go +++ b/precompile/precompiletest/test_config.go @@ -15,9 +15,9 @@ import ( // ConfigVerifyTest is a test case for verifying a config type ConfigVerifyTest struct { - Config precompileconfig.Config - ChainConfig precompileconfig.ChainConfig - WantError error + Config precompileconfig.Config + ChainConfig precompileconfig.ChainConfig + ExpectedError error } // ConfigEqualTest is a test case for comparing two configs @@ -43,7 +43,7 @@ func RunVerifyTests(t *testing.T, tests map[string]ConfigVerifyTest) { chainConfig = mockChainConfig } err := test.Config.Verify(chainConfig) - require.ErrorIs(err, test.WantError) + require.ErrorIs(err, test.ExpectedError) }) } } diff --git a/precompile/precompiletest/test_precompile.go b/precompile/precompiletest/test_precompile.go index 21053ef2e8..77764648ae 100644 --- a/precompile/precompiletest/test_precompile.go +++ b/precompile/precompiletest/test_precompile.go @@ -54,8 +54,8 @@ type PrecompileTest struct { AfterHook func(t testing.TB, state *extstate.StateDB) // ExpectedRes is the expected raw byte result returned by the precompile ExpectedRes []byte - // WantErr is the expected error returned by the precompile - WantErr error + // ExpectedErr is the expected error returned by the precompile + ExpectedErr error // ChainConfig is the chain config to use for the precompile's block context // If nil, the default chain config will be used. ChainConfigFn func(*gomock.Controller) precompileconfig.ChainConfig @@ -81,7 +81,7 @@ func (test PrecompileTest) Run(t *testing.T, module modules.Module) { if runParams.Input != nil { ret, remainingGas, err := module.Contract.Run(runParams.AccessibleState, runParams.Caller, runParams.ContractAddress, runParams.Input, runParams.SuppliedGas, runParams.ReadOnly) - require.ErrorIs(t, err, test.WantErr) + require.ErrorIs(t, err, test.ExpectedErr) require.Equal(t, uint64(0), remainingGas) require.Equal(t, test.ExpectedRes, ret) } @@ -105,7 +105,7 @@ func (test PrecompileTest) Bench(b *testing.B, module modules.Module) { snapshot := stateDB.Snapshot() ret, remainingGas, err := module.Contract.Run(runParams.AccessibleState, runParams.Caller, runParams.ContractAddress, runParams.Input, runParams.SuppliedGas, runParams.ReadOnly) - require.ErrorIs(b, err, test.WantErr) + require.ErrorIs(b, err, test.ExpectedErr) require.Equal(b, uint64(0), remainingGas) require.Equal(b, test.ExpectedRes, ret) @@ -141,7 +141,7 @@ func (test PrecompileTest) Bench(b *testing.B, module modules.Module) { // the benchmark should catch the error here. stateDB.RevertToSnapshot(snapshot) ret, remainingGas, err = module.Contract.Run(runParams.AccessibleState, runParams.Caller, runParams.ContractAddress, runParams.Input, runParams.SuppliedGas, runParams.ReadOnly) - require.ErrorIs(b, err, test.WantErr) + require.ErrorIs(b, err, test.ExpectedErr) require.Equal(b, uint64(0), remainingGas) require.Equal(b, test.ExpectedRes, ret) From 811a105bb19a4b52be0d42b59b8cd06966f50818 Mon Sep 17 00:00:00 2001 From: Jonathan Oppenheimer Date: Wed, 3 Dec 2025 11:54:17 -0500 Subject: [PATCH 15/19] style: revert expected -> want --- commontype/fee_config_test.go | 60 ++++++++++++------------ params/extras/precompile_config_test.go | 12 ++--- params/extras/precompile_upgrade_test.go | 12 ++--- params/extras/state_upgrade_test.go | 16 +++---- 4 files changed, 50 insertions(+), 50 deletions(-) diff --git a/commontype/fee_config_test.go b/commontype/fee_config_test.go index a2e7959270..0f754acb97 100644 --- a/commontype/fee_config_test.go +++ b/commontype/fee_config_test.go @@ -12,9 +12,9 @@ import ( func TestVerify(t *testing.T) { tests := []struct { - name string - config *FeeConfig - wantError error + name string + config *FeeConfig + expectedError error }{ { name: "nil gasLimit in FeeConfig", @@ -30,42 +30,42 @@ func TestVerify(t *testing.T) { MaxBlockGasCost: big.NewInt(1_000_000), BlockGasCostStep: big.NewInt(200_000), }, - wantError: ErrGasLimitNil, + expectedError: ErrGasLimitNil, }, { - name: "invalid GasLimit in FeeConfig", - config: func() *FeeConfig { c := ValidTestFeeConfig; c.GasLimit = big.NewInt(0); return &c }(), - wantError: ErrGasLimitTooLow, + name: "invalid GasLimit in FeeConfig", + config: func() *FeeConfig { c := ValidTestFeeConfig; c.GasLimit = big.NewInt(0); return &c }(), + expectedError: ErrGasLimitTooLow, }, { - name: "invalid TargetBlockRate in FeeConfig", - config: func() *FeeConfig { c := ValidTestFeeConfig; c.TargetBlockRate = 0; return &c }(), - wantError: errTargetBlockRateTooLow, + name: "invalid TargetBlockRate in FeeConfig", + config: func() *FeeConfig { c := ValidTestFeeConfig; c.TargetBlockRate = 0; return &c }(), + expectedError: errTargetBlockRateTooLow, }, { - name: "invalid MinBaseFee in FeeConfig", - config: func() *FeeConfig { c := ValidTestFeeConfig; c.MinBaseFee = big.NewInt(-1); return &c }(), - wantError: errMinBaseFeeNegative, + name: "invalid MinBaseFee in FeeConfig", + config: func() *FeeConfig { c := ValidTestFeeConfig; c.MinBaseFee = big.NewInt(-1); return &c }(), + expectedError: errMinBaseFeeNegative, }, { - name: "invalid TargetGas in FeeConfig", - config: func() *FeeConfig { c := ValidTestFeeConfig; c.TargetGas = big.NewInt(0); return &c }(), - wantError: errTargetGasTooLow, + name: "invalid TargetGas in FeeConfig", + config: func() *FeeConfig { c := ValidTestFeeConfig; c.TargetGas = big.NewInt(0); return &c }(), + expectedError: errTargetGasTooLow, }, { - name: "invalid BaseFeeChangeDenominator in FeeConfig", - config: func() *FeeConfig { c := ValidTestFeeConfig; c.BaseFeeChangeDenominator = big.NewInt(0); return &c }(), - wantError: errBaseFeeChangeDenominatorTooLow, + name: "invalid BaseFeeChangeDenominator in FeeConfig", + config: func() *FeeConfig { c := ValidTestFeeConfig; c.BaseFeeChangeDenominator = big.NewInt(0); return &c }(), + expectedError: errBaseFeeChangeDenominatorTooLow, }, { - name: "invalid MinBlockGasCost in FeeConfig", - config: func() *FeeConfig { c := ValidTestFeeConfig; c.MinBlockGasCost = big.NewInt(-1); return &c }(), - wantError: errMinBlockGasCostNegative, + name: "invalid MinBlockGasCost in FeeConfig", + config: func() *FeeConfig { c := ValidTestFeeConfig; c.MinBlockGasCost = big.NewInt(-1); return &c }(), + expectedError: errMinBlockGasCostNegative, }, { - name: "valid FeeConfig", - config: &ValidTestFeeConfig, - wantError: nil, + name: "valid FeeConfig", + config: &ValidTestFeeConfig, + expectedError: nil, }, { name: "MinBlockGasCost bigger than MaxBlockGasCost in FeeConfig", @@ -75,19 +75,19 @@ func TestVerify(t *testing.T) { c.MaxBlockGasCost = big.NewInt(1) return &c }(), - wantError: ErrMinBlockGasCostTooHigh, + expectedError: ErrMinBlockGasCostTooHigh, }, { - name: "invalid BlockGasCostStep in FeeConfig", - config: func() *FeeConfig { c := ValidTestFeeConfig; c.BlockGasCostStep = big.NewInt(-1); return &c }(), - wantError: errBlockGasCostStepNegative, + name: "invalid BlockGasCostStep in FeeConfig", + config: func() *FeeConfig { c := ValidTestFeeConfig; c.BlockGasCostStep = big.NewInt(-1); return &c }(), + expectedError: errBlockGasCostStepNegative, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { err := test.config.Verify() - require.ErrorIs(t, err, test.wantError) + require.ErrorIs(t, err, test.expectedError) }) } } diff --git a/params/extras/precompile_config_test.go b/params/extras/precompile_config_test.go index 8be3cf675a..6931481362 100644 --- a/params/extras/precompile_config_test.go +++ b/params/extras/precompile_config_test.go @@ -205,16 +205,16 @@ func TestVerifyPrecompileUpgrades(t *testing.T) { func TestVerifyPrecompiles(t *testing.T) { admins := []common.Address{{1}} tests := []struct { - name string - precompiles Precompiles - wantError error + name string + precompiles Precompiles + expectedError error }{ { name: "invalid allow list config in tx allowlist", precompiles: Precompiles{ txallowlist.ConfigKey: txallowlist.NewConfig(utils.NewUint64(3), admins, admins, admins), }, - wantError: allowlist.ErrAdminAndEnabledAddress, + expectedError: allowlist.ErrAdminAndEnabledAddress, }, { name: "invalid initial fee manager config", @@ -226,7 +226,7 @@ func TestVerifyPrecompiles(t *testing.T) { return &feeConfig }()), }, - wantError: commontype.ErrGasLimitTooLow, + expectedError: commontype.ErrGasLimitTooLow, }, } for _, tt := range tests { @@ -238,7 +238,7 @@ func TestVerifyPrecompiles(t *testing.T) { config.GenesisPrecompiles = tt.precompiles err := config.Verify() - require.ErrorIs(err, tt.wantError) + require.ErrorIs(err, tt.expectedError) }) } } diff --git a/params/extras/precompile_upgrade_test.go b/params/extras/precompile_upgrade_test.go index 02f7bd84dd..b1fdd3457f 100644 --- a/params/extras/precompile_upgrade_test.go +++ b/params/extras/precompile_upgrade_test.go @@ -25,13 +25,13 @@ func TestVerifyUpgradeConfig(t *testing.T) { } type test struct { - upgrades []PrecompileUpgrade - wantError error + upgrades []PrecompileUpgrade + expectedError error } tests := map[string]test{ "upgrade bytes conflicts with genesis (re-enable without disable)": { - wantError: errPrecompileUpgradeInvalidDisable, + expectedError: errPrecompileUpgradeInvalidDisable, upgrades: []PrecompileUpgrade{ { Config: txallowlist.NewConfig(utils.NewUint64(2), admins, nil, nil), @@ -39,7 +39,7 @@ func TestVerifyUpgradeConfig(t *testing.T) { }, }, "upgrade bytes conflicts with genesis (disable before enable)": { - wantError: errPrecompileUpgradeSameKeyTimestampNotStrictly, + expectedError: errPrecompileUpgradeSameKeyTimestampNotStrictly, upgrades: []PrecompileUpgrade{ { Config: txallowlist.NewDisableConfig(utils.NewUint64(0)), @@ -47,7 +47,7 @@ func TestVerifyUpgradeConfig(t *testing.T) { }, }, "upgrade bytes conflicts with genesis (disable same time as enable)": { - wantError: errPrecompileUpgradeSameKeyTimestampNotStrictly, + expectedError: errPrecompileUpgradeSameKeyTimestampNotStrictly, upgrades: []PrecompileUpgrade{ { Config: txallowlist.NewDisableConfig(utils.NewUint64(1)), @@ -64,7 +64,7 @@ func TestVerifyUpgradeConfig(t *testing.T) { // verify with the upgrades from the test chainConfig.UpgradeConfig.PrecompileUpgrades = tt.upgrades err := chainConfig.Verify() - require.ErrorIs(t, err, tt.wantError) + require.ErrorIs(t, err, tt.expectedError) }) } } diff --git a/params/extras/state_upgrade_test.go b/params/extras/state_upgrade_test.go index f2a3da9934..14f96a88e3 100644 --- a/params/extras/state_upgrade_test.go +++ b/params/extras/state_upgrade_test.go @@ -23,9 +23,9 @@ func TestVerifyStateUpgrades(t *testing.T) { }, } tests := []struct { - name string - upgrades []StateUpgrade - wantError error + name string + upgrades []StateUpgrade + expectedError error }{ { name: "valid upgrade", @@ -33,7 +33,7 @@ func TestVerifyStateUpgrades(t *testing.T) { {BlockTimestamp: utils.NewUint64(1), StateUpgradeAccounts: modifiedAccounts}, {BlockTimestamp: utils.NewUint64(2), StateUpgradeAccounts: modifiedAccounts}, }, - wantError: nil, + expectedError: nil, }, { name: "upgrade block timestamp is not strictly increasing", @@ -41,7 +41,7 @@ func TestVerifyStateUpgrades(t *testing.T) { {BlockTimestamp: utils.NewUint64(1), StateUpgradeAccounts: modifiedAccounts}, {BlockTimestamp: utils.NewUint64(1), StateUpgradeAccounts: modifiedAccounts}, }, - wantError: errStateUpgradeTimestampNotMonotonic, + expectedError: errStateUpgradeTimestampNotMonotonic, }, { name: "upgrade block timestamp decreases", @@ -49,14 +49,14 @@ func TestVerifyStateUpgrades(t *testing.T) { {BlockTimestamp: utils.NewUint64(2), StateUpgradeAccounts: modifiedAccounts}, {BlockTimestamp: utils.NewUint64(1), StateUpgradeAccounts: modifiedAccounts}, }, - wantError: errStateUpgradeTimestampNotMonotonic, + expectedError: errStateUpgradeTimestampNotMonotonic, }, { name: "upgrade block timestamp is zero", upgrades: []StateUpgrade{ {BlockTimestamp: utils.NewUint64(0), StateUpgradeAccounts: modifiedAccounts}, }, - wantError: errStateUpgradeTimestampZero, + expectedError: errStateUpgradeTimestampZero, }, } for _, tt := range tests { @@ -68,7 +68,7 @@ func TestVerifyStateUpgrades(t *testing.T) { config.StateUpgrades = tt.upgrades err := config.Verify() - require.ErrorIs(err, tt.wantError) + require.ErrorIs(err, tt.expectedError) }) } } From 95b83cf002fbde1ab65916833840131759895d2f Mon Sep 17 00:00:00 2001 From: Jonathan Oppenheimer Date: Wed, 3 Dec 2025 11:56:52 -0500 Subject: [PATCH 16/19] style: revert expected -> want --- .../contracts/feemanager/unpack_pack_test.go | 86 ++++++++-------- .../nativeminter/unpack_pack_test.go | 98 +++++++++---------- 2 files changed, 92 insertions(+), 92 deletions(-) diff --git a/precompile/contracts/feemanager/unpack_pack_test.go b/precompile/contracts/feemanager/unpack_pack_test.go index dfc07c5a0a..f053af8cd3 100644 --- a/precompile/contracts/feemanager/unpack_pack_test.go +++ b/precompile/contracts/feemanager/unpack_pack_test.go @@ -68,68 +68,68 @@ func TestPackGetFeeConfigOutput(t *testing.T) { testInputBytes, err := PackGetFeeConfigOutput(testFeeConfig) require.NoError(t, err) tests := []struct { - name string - input []byte - skipLenCheck bool - wantErr error - wantOldErr error - wantOutput commontype.FeeConfig + name string + input []byte + skipLenCheck bool + expectedErr error + expectedOldErr error + expectedOutput commontype.FeeConfig }{ { - name: "empty input", - input: []byte{}, - skipLenCheck: false, - wantErr: ErrInvalidLen, - wantOldErr: ErrInvalidLen, + name: "empty input", + input: []byte{}, + skipLenCheck: false, + expectedErr: ErrInvalidLen, + expectedOldErr: ErrInvalidLen, }, { - name: "empty input skip len check", - input: []byte{}, - skipLenCheck: true, - wantErr: ErrUnpackOutput, - wantOldErr: ErrInvalidLen, + name: "empty input skip len check", + input: []byte{}, + skipLenCheck: true, + expectedErr: ErrUnpackOutput, + expectedOldErr: ErrInvalidLen, }, { - name: "input with extra bytes", - input: append(testInputBytes, make([]byte, 32)...), - skipLenCheck: false, - wantErr: ErrInvalidLen, - wantOldErr: ErrInvalidLen, + name: "input with extra bytes", + input: append(testInputBytes, make([]byte, 32)...), + skipLenCheck: false, + expectedErr: ErrInvalidLen, + expectedOldErr: ErrInvalidLen, }, { - name: "input with extra bytes skip len check", - input: append(testInputBytes, make([]byte, 32)...), - skipLenCheck: true, - wantErr: nil, - wantOldErr: ErrInvalidLen, - wantOutput: testFeeConfig, + name: "input with extra bytes skip len check", + input: append(testInputBytes, make([]byte, 32)...), + skipLenCheck: true, + expectedErr: nil, + expectedOldErr: ErrInvalidLen, + expectedOutput: testFeeConfig, }, { - name: "input with extra bytes (not divisible by 32)", - input: append(testInputBytes, make([]byte, 33)...), - skipLenCheck: false, - wantErr: ErrInvalidLen, - wantOldErr: ErrInvalidLen, + name: "input with extra bytes (not divisible by 32)", + input: append(testInputBytes, make([]byte, 33)...), + skipLenCheck: false, + expectedErr: ErrInvalidLen, + expectedOldErr: ErrInvalidLen, }, { - name: "input with extra bytes (not divisible by 32) skip len check", - input: append(testInputBytes, make([]byte, 33)...), - skipLenCheck: true, - wantErr: ErrUnpackOutput, - wantOldErr: ErrInvalidLen, + name: "input with extra bytes (not divisible by 32) skip len check", + input: append(testInputBytes, make([]byte, 33)...), + skipLenCheck: true, + expectedErr: ErrUnpackOutput, + expectedOldErr: ErrInvalidLen, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { unpacked, err := UnpackGetFeeConfigOutput(test.input, test.skipLenCheck) - require.ErrorIs(t, err, test.wantErr) - if test.wantErr == nil { - require.True(t, test.wantOutput.Equal(&unpacked), "not equal: expectedOutput %v, unpacked %v", test.wantOutput, unpacked) + require.ErrorIs(t, err, test.expectedErr) + if test.expectedErr == nil { + require.True(t, test.expectedOutput.Equal(&unpacked), "not equal: expectedOutput %v, unpacked %v", test.expectedOutput, unpacked) } oldUnpacked, oldErr := OldUnpackFeeConfig(test.input) - require.ErrorIs(t, oldErr, test.wantOldErr) - if test.wantOldErr == nil { - require.True(t, test.wantOutput.Equal(&oldUnpacked), "not equal: expectedOutput %v, oldUnpacked %v", test.wantOutput, oldUnpacked) + require.ErrorIs(t, oldErr, test.expectedOldErr) + if test.expectedOldErr == nil { + require.True(t, test.expectedOutput.Equal(&oldUnpacked), "not equal: expectedOutput %v, oldUnpacked %v", test.expectedOutput, oldUnpacked) } }) } diff --git a/precompile/contracts/nativeminter/unpack_pack_test.go b/precompile/contracts/nativeminter/unpack_pack_test.go index 202228cee4..8807951538 100644 --- a/precompile/contracts/nativeminter/unpack_pack_test.go +++ b/precompile/contracts/nativeminter/unpack_pack_test.go @@ -46,74 +46,74 @@ func TestUnpackMintNativeCoinInput(t *testing.T) { // exclude 4 bytes for function selector testInputBytes = testInputBytes[4:] tests := []struct { - name string - input []byte - strictMode bool - wantErr error - wantOldErr error - wantAddr common.Address - wantAmount *big.Int + name string + input []byte + strictMode bool + expectedErr error + expectedOldErr error + expectedAddr common.Address + expectedAmount *big.Int }{ { - name: "empty input strict mode", - input: []byte{}, - strictMode: true, - wantErr: ErrInvalidLen, - wantOldErr: ErrInvalidLen, + name: "empty input strict mode", + input: []byte{}, + strictMode: true, + expectedErr: ErrInvalidLen, + expectedOldErr: ErrInvalidLen, }, { - name: "empty input", - input: []byte{}, - strictMode: false, - wantErr: ErrUnpackInput, - wantOldErr: ErrInvalidLen, + name: "empty input", + input: []byte{}, + strictMode: false, + expectedErr: ErrUnpackInput, + expectedOldErr: ErrInvalidLen, }, { - name: "input with extra bytes strict mode", - input: append(testInputBytes, make([]byte, 32)...), - strictMode: true, - wantErr: ErrInvalidLen, - wantOldErr: ErrInvalidLen, + name: "input with extra bytes strict mode", + input: append(testInputBytes, make([]byte, 32)...), + strictMode: true, + expectedErr: ErrInvalidLen, + expectedOldErr: ErrInvalidLen, }, { - name: "input with extra bytes", - input: append(testInputBytes, make([]byte, 32)...), - strictMode: false, - wantErr: nil, - wantOldErr: ErrInvalidLen, - wantAddr: constants.BlackholeAddr, - wantAmount: common.Big2, + name: "input with extra bytes", + input: append(testInputBytes, make([]byte, 32)...), + strictMode: false, + expectedErr: nil, + expectedOldErr: ErrInvalidLen, + expectedAddr: constants.BlackholeAddr, + expectedAmount: common.Big2, }, { - name: "input with extra bytes (not divisible by 32) strict mode", - input: append(testInputBytes, make([]byte, 33)...), - strictMode: true, - wantErr: ErrInvalidLen, - wantOldErr: ErrInvalidLen, + name: "input with extra bytes (not divisible by 32) strict mode", + input: append(testInputBytes, make([]byte, 33)...), + strictMode: true, + expectedErr: ErrInvalidLen, + expectedOldErr: ErrInvalidLen, }, { - name: "input with extra bytes (not divisible by 32)", - input: append(testInputBytes, make([]byte, 33)...), - strictMode: false, - wantErr: nil, - wantOldErr: ErrInvalidLen, - wantAddr: constants.BlackholeAddr, - wantAmount: common.Big2, + name: "input with extra bytes (not divisible by 32)", + input: append(testInputBytes, make([]byte, 33)...), + strictMode: false, + expectedErr: nil, + expectedOldErr: ErrInvalidLen, + expectedAddr: constants.BlackholeAddr, + expectedAmount: common.Big2, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { unpackedAddress, unpackedAmount, err := UnpackMintNativeCoinInput(test.input, test.strictMode) - require.ErrorIs(t, err, test.wantErr) - if test.wantErr == nil { - require.Equal(t, test.wantAddr, unpackedAddress) - require.Equal(t, test.wantAmount, unpackedAmount, "expected %s, got %s", test.wantAmount.String(), unpackedAmount.String()) + require.ErrorIs(t, err, test.expectedErr) + if test.expectedErr == nil { + require.Equal(t, test.expectedAddr, unpackedAddress) + require.Equal(t, test.expectedAmount, unpackedAmount, "expected %s, got %s", test.expectedAmount.String(), unpackedAmount.String()) } oldUnpackedAddress, oldUnpackedAmount, oldErr := OldUnpackMintNativeCoinInput(test.input) - require.ErrorIs(t, oldErr, test.wantOldErr) - if test.wantOldErr == nil { - require.Equal(t, test.wantAddr, oldUnpackedAddress) - require.Equal(t, test.wantAmount, oldUnpackedAmount, "expected %s, got %s", test.wantAmount.String(), oldUnpackedAmount.String()) + require.ErrorIs(t, oldErr, test.expectedOldErr) + if test.expectedOldErr == nil { + require.Equal(t, test.expectedAddr, oldUnpackedAddress) + require.Equal(t, test.expectedAmount, oldUnpackedAmount, "expected %s, got %s", test.expectedAmount.String(), oldUnpackedAmount.String()) } }) } From c07a7d7ccf9cfb93e6201b56a1fe17663bfcbd27 Mon Sep 17 00:00:00 2001 From: Jonathan Oppenheimer Date: Thu, 4 Dec 2025 11:14:37 -0500 Subject: [PATCH 17/19] Update precompile/contracts/nativeminter/simulated_test.go Co-authored-by: Austin Larson <78000745+alarso16@users.noreply.github.com> Signed-off-by: Jonathan Oppenheimer <147infiniti@gmail.com> --- precompile/contracts/nativeminter/simulated_test.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/precompile/contracts/nativeminter/simulated_test.go b/precompile/contracts/nativeminter/simulated_test.go index a722064e15..803e0b6b7d 100644 --- a/precompile/contracts/nativeminter/simulated_test.go +++ b/precompile/contracts/nativeminter/simulated_test.go @@ -110,8 +110,7 @@ func TestNativeMinter(t *testing.T) { // Unprivileged user tries to mint - should fail _, err := nativeMinter.MintNativeCoin(unprivileged, testAddr, amount) - // The error returned is a JSON Error rather than the nativeminter.ErrCannotMinterror - require.ErrorContains(t, err, nativeminter.ErrCannotMint.Error()) //nolint:forbidigo // uses upstream code + require.ErrorContains(t, err, nativeminter.ErrCannotMint.Error()) //nolint:forbidigo // upstream error wrapped as string }, }, { From dc1ac3370bab9ca15fb89e753fe5be7b0e36050d Mon Sep 17 00:00:00 2001 From: Jonathan Oppenheimer Date: Thu, 4 Dec 2025 11:29:37 -0500 Subject: [PATCH 18/19] chore: Austin suggestions --- precompile/contracts/nativeminter/simulated_test.go | 3 +-- precompile/precompiletest/test_precompile.go | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/precompile/contracts/nativeminter/simulated_test.go b/precompile/contracts/nativeminter/simulated_test.go index 803e0b6b7d..3420faa747 100644 --- a/precompile/contracts/nativeminter/simulated_test.go +++ b/precompile/contracts/nativeminter/simulated_test.go @@ -124,8 +124,7 @@ func TestNativeMinter(t *testing.T) { // Contract tries to mint and then should revert because it's not enabled _, err := testContract.MintNativeCoin(admin, testAddr, amount) - // The error returned is a JSON Error rather than the vm.ErrExecutionReverted error - require.ErrorContains(t, err, vm.ErrExecutionReverted.Error()) //nolint:forbidigo // uses upstream code + require.ErrorContains(t, err, vm.ErrExecutionReverted.Error()) //nolint:forbidigo // upstream error wrapped as string }, }, { diff --git a/precompile/precompiletest/test_precompile.go b/precompile/precompiletest/test_precompile.go index 77764648ae..28091928f7 100644 --- a/precompile/precompiletest/test_precompile.go +++ b/precompile/precompiletest/test_precompile.go @@ -56,7 +56,7 @@ type PrecompileTest struct { ExpectedRes []byte // ExpectedErr is the expected error returned by the precompile ExpectedErr error - // ChainConfig is the chain config to use for the precompile's block context + // ChainConfigFn returns the chain config to use for the precompile's block context // If nil, the default chain config will be used. ChainConfigFn func(*gomock.Controller) precompileconfig.ChainConfig // Rules is the rules to use for the precompile's block context. From 4006529032c11517dca18ed619725e1be61d039e Mon Sep 17 00:00:00 2001 From: Jonathan Oppenheimer Date: Thu, 4 Dec 2025 11:37:54 -0500 Subject: [PATCH 19/19] chore: lint --- precompile/contracts/feemanager/simulated_test.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/precompile/contracts/feemanager/simulated_test.go b/precompile/contracts/feemanager/simulated_test.go index 739132351c..11546395b4 100644 --- a/precompile/contracts/feemanager/simulated_test.go +++ b/precompile/contracts/feemanager/simulated_test.go @@ -9,12 +9,14 @@ import ( "github.com/ava-labs/libevm/common" "github.com/ava-labs/libevm/core/types" + "github.com/ava-labs/libevm/core/vm" "github.com/ava-labs/libevm/crypto" "github.com/stretchr/testify/require" "github.com/ava-labs/subnet-evm/accounts/abi/bind" "github.com/ava-labs/subnet-evm/commontype" "github.com/ava-labs/subnet-evm/core" + "github.com/ava-labs/subnet-evm/core/txpool" "github.com/ava-labs/subnet-evm/params" "github.com/ava-labs/subnet-evm/params/extras" "github.com/ava-labs/subnet-evm/plugin/evm/customtypes" @@ -188,7 +190,7 @@ func TestFeeManager(t *testing.T) { // Try to change fee config from contract without being enabled - should fail during gas estimation _, err := trySetFeeConfig(testContract, admin, cchainFeeConfig) - require.ErrorContains(t, err, "execution reverted") + require.ErrorContains(t, err, vm.ErrExecutionReverted.Error()) //nolint:forbidigo // upstream error wrapped as string }, }, { @@ -247,7 +249,7 @@ func TestFeeManager(t *testing.T) { lowFeeConfig := genesisFeeConfig lowFeeConfig.MinBaseFee = originalMinBaseFee _, err = trySetFeeConfig(testContract, lowFeeAuth, lowFeeConfig) - require.ErrorContains(t, err, "underpriced") + require.ErrorContains(t, err, txpool.ErrUnderpriced.Error()) //nolint:forbidigo // upstream error wrapped as string }, }, }