상세 컨텐츠

본문 제목

Solidity - Function Selector

Programming Language/Solidity

by Yongari 2023. 1. 19. 13:09

본문

 

When a function is called, the first 4 bytes of calldata specifies which function to call.
함수가 호출될 때 호출 데이터의 처음 4바이트는 호출할 함수를 지정합니다.

This 4 bytes is called a function selector.
이 4바이트를 함수 선택기라고 합니다.

Take for example, this code below. It uses call to execute transfer on a contract at the address addr.

 - 예제코드에서 call을 사용하여 컨트랙트 주소 addr로  transfer를 실행하는걸 확인할 수 있다.

addr.call(abi.encodeWithSignature("transfer(address,uint256)", 0xSomeAddress, 123))

 

The first 4 bytes returned from abi.encodeWithSignature(....) is the function selector.
 abi.encodeWithSignature(..)의 첫번째 4 bytes가 function selector(함수 선택자) 이다.

Perhaps you can save a tiny amount of gas if you precompute and inline the function selector in your code?

코드에서 함수 선택자를 미리 계산하고 inline(인라인)화하면 적은 양의 가스를 절약할 수 있을 것이다

 

Here is how the function selector is computed.

다음은 함수 선택자를 계산하는 방법입니다.

 

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

contract FunctionSelector {
    /*
    "transfer(address,uint256)"
    0xa9059cbb
    "transferFrom(address,address,uint256)"
    0x23b872dd
    */
    function getSelector(string calldata _func) external pure returns (bytes4) {
        return bytes4(keccak256(bytes(_func)));
    }
}

Try on Remix

 

Remix - Ethereum IDE

 

remix.ethereum.org

 

'Programming Language > Solidity' 카테고리의 다른 글

스마트 컨트랙트 구조와 Solidity 변수  (0) 2023.02.07
Solidity - Calling Other Contract  (0) 2023.01.25
Solidity - Delegatecall  (0) 2023.01.18
Solidity - Call  (0) 2023.01.17
Solidity - Fallback  (0) 2023.01.13

관련글 더보기