Solidity Tutorial: all about Libraries – Jean Cvllr

If we call add() function of the Math library from our contract, the address of MyContract will be returned and not the library address. The add() function is compiled as an external call ( DELEGATECALL ) but if we check the address from the address(this) (the contract address), we will see our contract address (not the library contract’s address). The same applies for all other msg properties ( msg.value, msg.data and msg.gas).
Furthermore, internalfunctions of libraries are visible in all contracts, just as if the library were a base contract. What ??? Yes that sounds strange. Let’s unpack the process of calling an internal library function, to understand what happen exactly is the following :
- Contract A calls internal function B from library L.
- At compile time, the EVM pulls internal function B into contract A. It would be like if function B was hardcoded in contract A.
- A regular
JUMPcall will be used instead of aDELEGATECALL.
Calls to internal functions use the same internal calling convention :
- all internal types can be passed.
- types stored in memory will be passed by reference and not copied.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Despite the fact libraries do not have storage, they can modify their linked contract’s storage, by passing a storage argument to their function parameters. Hence any modification made by the library does via its function will be saved in the contract’s own storage.
Therefore, the keyword this will point to the calling contract, and refers to the storage of the calling contract to be precise.
Since a library is an isolated piece of code, it can only access state variables of from the storage of the calling contract if they are explicitly supplied. In fact, it would have no way to name them, otherwise. Let’s have a look at a simple example.
// Some code here
We want to use a library function !
Ok enough theory, let’s look at some practical examples ! ?
To use a library function, we select the variable we want to apply the library function to and add a . followed by the library function name we want to use. Type variable = variable.libraryFunction(Type argument).
Here is an example below.
pragma solidity ^0.5.0;contract MyContract library MathLib}
Published at Thu, 01 Aug 2019 13:48:48 +0000
{flickr|100|campaign}
