0

I can't understand the advantage of function selector. Following link What is a function selctor?

uses function selector to invoke a function of another contract but it uses the statements:

   bytes4 selector = contract1.func.selector;
   bytes memory data = abi.encodeWithSelector(selector, uint256(789), uint8(123));

This means for the function selector we must know both the function name and the arguments of the function which we want to invoke.

Now consider another linkerror-member-func-not-found-or-not-visible-after-argument-dependent-lookup-in

It also calls the function 'func' of contract1 without using the function selector. But it also uses name of the function and the argument list.

(uint32 arg1, uint32 arg2) = contract1.func(uint256(789), uint8(123));

So in both the cases with or without function selector, we must know the function name and the argumnet list. So what is the advantage of using function selector?

1

In both your code examples, a function selector is used to tell the target contract what function you're calling. In the second case, Solidity is generating the code that uses the function selector for you. This is generally a better approach. (No need for you to deal with function selectors directly if the compiler can do it for you.)

That said, you do need to deal with function selectors yourself if you're writing code in a non-Solidity language or don't know the function signature in advance (e.g. a general purpose multisig wallet). In those cases, you have to do a bit of work yourself to craft the right transaction data.

  • Can you give an example in Solidity where we invoke a function, whose signature we don't know and we invoke the function using function selector? – zak100 Jul 2 at 23:09
  • programtheblockchain.com/posts/2018/08/02/… is such an example. The client will need to use the function selector to construct the data passed to the execute function. – user19510 Jul 2 at 23:28
0

Function selectors have other uses beside being used to invoke a function

I've seen it used in a variety of circumstances:

  • Log function calls
  • Verify signed messages that target a specific function
  • Generate IDs
  • Function level access control

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.