Skip to content

Commit

Permalink
Added test-deduct-gas test
Browse files Browse the repository at this point in the history
  • Loading branch information
evgeniy-scherbina committed Feb 7, 2024
1 parent 02c4139 commit 0de25b9
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 5 deletions.
4 changes: 2 additions & 2 deletions precompile/contract/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ const (
ReadGasCostPerSlot = 5_000
)

var functionSignatureRegex = regexp.MustCompile(`\w+\((\w*|(\w+,)+\w+)\)`)
var FunctionSignatureRegex = regexp.MustCompile(`\w+\((\w*|(\w+,)+\w+)\)`)

// MustCalculateFunctionSelector returns the 4 byte function selector that results from [functionSignature]
// Ex. the function setBalance(addr address, balance uint256) should be passed in as the string:
// "setBalance(address,uint256)"
func MustCalculateFunctionSelector(functionSignature string) []byte {
if !functionSignatureRegex.MatchString(functionSignature) {
if !FunctionSignatureRegex.MatchString(functionSignature) {
panic(fmt.Errorf("invalid function signature: %q", functionSignature))
}
hash := crypto.Keccak256([]byte(functionSignature))
Expand Down
48 changes: 45 additions & 3 deletions precompile/contract/utils_test.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
// (c) 2019-2020, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.

package contract
package contract_test

import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/ethereum/go-ethereum/precompile/contract"
)

func TestFunctionSignatureRegex(t *testing.T) {
Expand Down Expand Up @@ -61,6 +63,46 @@ func TestFunctionSignatureRegex(t *testing.T) {
pass: false,
},
} {
assert.Equal(t, test.pass, functionSignatureRegex.MatchString(test.str), "unexpected result for %q", test.str)
require.Equal(t, test.pass, contract.FunctionSignatureRegex.MatchString(test.str), "unexpected result for %q", test.str)
}
}

func TestDeductGas(t *testing.T) {
for _, tc := range []struct {
desc string
suppliedGas uint64
requiredGas uint64
remainingGas uint64
err string
}{
{
desc: "not enough gas",
suppliedGas: 0,
requiredGas: 100,
err: "out of gas",
},
{
desc: "enough gas",
suppliedGas: 100,
requiredGas: 100,
remainingGas: 0,
},
{
desc: "more than enough gas",
suppliedGas: 200,
requiredGas: 100,
remainingGas: 100,
},
} {
t.Run(tc.desc, func(t *testing.T) {
remainingGas, err := contract.DeductGas(tc.suppliedGas, tc.requiredGas)
if tc.err != "" {
require.Error(t, err)
require.Contains(t, err.Error(), "out of gas")
} else {
require.NoError(t, err)
require.Equal(t, tc.remainingGas, remainingGas)
}
})
}
}

0 comments on commit 0de25b9

Please sign in to comment.