I have Very Interesting cases about Libraries.
CASE 1:
I read the following in the official solidity docs:
Library functions can only be called directly (i.e. without the use of DELEGATECALL) if they do not modify the state (i.e. if they are view or pure functions), because libraries are assumed to be stateless
I am sure they mean to call libraries with the use of .call
on the address and they say this would only be possible if the function of the libraries would be pure/view
. Let me reprase in the a), b), c)
what I don't understand.
a) In the copied sentence, It says: if they do not modify the state
. I am not sure how the library changes state at all. it doesn't have its own and all it can do is change the passed variable's value.
b) I tried using it with addr.call
, but I didn't specify functions as pure/view
and it still let me do this. It's interesting why it let me since in the docs, it says it should revert.
c) Why would I ever want to call libraries with the .call
? This just defeats the whole purpose of libraries.
**D) ** It seems like if I use internal
functions on libraries, the library code ends up in the compiled version of the contract. Any reason why this is good ? if that's so, I'd have used another contract instead of library.
Case 2:
In the docs, It's really a bad example how it passes the reference type. Let's say I have a library:
// Let's say this was written by third-party and it's put on github.
library libraryContract {
function libraryTest(){
}
}
// I can import the above here.
// import "libraryContract.sol";
contract myContract {
function contractTest(){
// I call it. This will work. Now, let's say in this contract, I
// have a variable called `uint x = 0;`. and what libraryContract
// should be doing is change the value of the passed argument.
// If I pass `x` here directly, and change the argument in
//`libraryTest`, It still doesn't work since it's not passed by
//reference or something. Another case is What If I want my library
//to be changing the struct's properties, but library doesn't see
//the definiton of struct.
libraryContract.test();
}
}