toFunctionSelector
Returns the 4-byte function selector for a given function definition
toFunctionSelector
Returns the 4-byte function selector for a given function definition. The selector is the first 4 bytes of the keccak256 hash of the function signature.
Import
import "github.com/ChefBingbong/viem-go/utils/hash"Usage
import "github.com/ChefBingbong/viem-go/utils/hash"
// Get function selectorselector, _ := hash.ToFunctionSelector("function ownerOf(uint256 tokenId)")// "0x6352211e"
selector, _ = hash.ToFunctionSelector("function transfer(address to, uint256 amount)")// "0xa9059cbb"
// Get selector as bytesselectorBytes, _ := hash.ToFunctionSelectorBytes("function transfer(address,uint256)")// []byte{0xa9, 0x05, 0x9c, 0xbb}Returns
- Type:
(string, error)forToFunctionSelector,([]byte, error)forToFunctionSelectorBytes
The 4-byte function selector. ToFunctionSelector returns a hex string with 0x prefix, ToFunctionSelectorBytes returns raw bytes.
Parameters
function (required)
- Type:
string
The function definition string. Can include the function keyword or just the signature.
// With function keywordselector, _ := hash.ToFunctionSelector("function ownerOf(uint256 tokenId)")// "0x6352211e"
// Without function keywordselector, _ = hash.ToFunctionSelector("transfer(address,uint256)")// "0xa9059cbb"Functions
ToFunctionSelector
Returns the selector as a hex string:
selector, _ := hash.ToFunctionSelector("function transfer(address,uint256)")
// "0xa9059cbb"
ToFunctionSelectorBytes
Returns the selector as raw 4 bytes:
selectorBytes, _ := hash.ToFunctionSelectorBytes("function transfer(address,uint256)")
// []byte{0xa9, 0x05, 0x9c, 0xbb}
Notes
- The function signature is normalized (spaces removed, parameter names removed) before hashing
- Only the first 4 bytes of the keccak256 hash are used
- Function selectors are used to identify which function to call in contract interactions