🍊Informational Vulnerability 13: Public to External functions
Introduction
Visibility in Solidity smart contracts is a pivotal concept that plays a vital role in contract design and optimization. Specifying whether functions and state variables are accessible outside of the contract influences gas costs, security, and usability. Among various visibility specifiers, public
and external
stand out as crucial in managing function accessibility. This article delves into the nuanced application of these visibility specifiers, particularly focusing on optimizing gas usage by judiciously using the external
visibility specifier.
Understanding Public and External Functions
Public Functions
Public functions are part of the contract's interface, allowing them to be called both internally and externally. They are versatile but can be less gas-efficient when called externally.
External Functions
External functions, on the other hand, are part of the contract’s interface but can only be called externally. They tend to be more gas-efficient for external calls due to the way they handle function arguments.
The Case for External Visibility
Consider a public function that is not called within the contract. Since it doesn't leverage the versatility of being callable internally, it might be more beneficial to set such a function as external.
Gas Efficiency
External functions handle input parameters more efficiently. Parameters are not copied to memory but are read directly from the call data, saving gas.
Encapsulation
Marking a function as external clearly signals its intended use case as an externally accessible endpoint, thus providing better encapsulation and contract clarity.
Implementing the Change
Changing a function’s visibility from public to external is straightforward. Consider the following Solidity function:
If myFunction
is not called inside the contract, you could optimize it by declaring it as external:
Conclusion
Visibility is a powerful tool in smart contract design, influencing how functions interact with the Ethereum Virtual Machine and other contracts. By scrutinizing function usage and thoughtfully applying the external
visibility specifier, developers can optimize gas costs, enhance encapsulation, and improve the overall efficiency and clarity of their smart contracts.
Last updated