The Difference Between Solidity Libraries With Internal Functions and Solidity Libraries With External Functions
Solidity libraries with internal functions only work very differently than Solidity libraries with external functions.
It is very common for people to mix up these two very different kinds of Solidity libraries or not to know there is a major difference. Not knowing the difference can cause endless confusion.
Solidity libraries with external functions are deployed to the blockchain as thier own seperate, independent contract on a blockchain. Contracts that use these libraries use DELEGATECALL to call the external functions in these libraries.
Solidity libraries with internal functions only are NOT deployed to a blockchain as a separate independent contract. Internal functions of Solidity libraries are added to the contracts or facets that used them. They are included in the contract or facet that is deployed. Any internal function is executed with a jump instruction, not with DELEGATECALL.
The DELEGATECALL made by an external function costs much more gas than an internal function call. So Solidity libraries that contain only internal function are very runtime gas efficient.
Solidity libraries that contain only internal functions are a great way to share functionality between different contracts while maintaining runtime gas efficiency.
Solidity Library Internal Function Example
Let’s say that you have ContractA that calls internal function funcA from Solidity library LibInternal. Here is what happens during compilation and deployment:
ContractA is compiled into bytecode.
LibInternal is compiled into bytecode.
The funcA bytecode from LibInternal bytecode is added to ContractA bytecode and is now part of ContractA bytecode.
ContractA bytecode is deployed to a blockchain to create ContractA on the blockchain.
So there is only one contract deployed, which is ContractA. And funcA is in ContractA.
Solidity Library External Function Example
Let’s say that you have ContractB that calls external function funcB from Solidity library LibExternal. Here is what happens during compilation and deployment:
ContractB is compiled into bytecode.
LibExternal is compiled into bytecode.
LibExternal is deployed as its own contract to the blockchain.
ContractB bytecode is updated with the Ethereum address of the deployed LibExternal contract so that it can make DELEGATECALLs to it.
ContractB is deployed to the blockchain.
So there are two contracts deployed, which is ContractB and LibExternal. ContractB makes DELEGATECALLs to the deployed LibExternal contract to execute the funcB external function.
What a clear explaination. I think that because ContractB uses DELEGATECALL on LIBExternal, it costs more gas. than ContractA Right?