Libraries in Solidity

Libraries in Solidity

Solidity is right now under development and we may expect couple of improvement and new features going forward  but libraries is one of the concept and feature we have in solidity that helps in re-using the piece of code.

What is Library In Solidity ?

A library is a different type of contract, that doesn't have any storage and cannot hold ether. This is helpful when we want to re-use some piece of code. This does not have payable and fallback function so libraries do not hold ether and do not have any storage. Library function deployed only at one specific address and these functions are called in context of calling contract. This is explained more in detail in video.

pragma solidity ^ 0.4.20;
library math{
function add(uint _fValue, uint _sValue) public returns(uint){
return _fValue + _sValue;
}
}
contract salary{
function salarywithBouns(uint _salary, uint _bonus) public returns(uint){
return math.add(_salary,_bonus);
}
}

Usage of "using" and "for" keyword

We can attach library function to any data type by using "using" and "for" keywords. This is explained more in detail in video.

pragma solidity ^ 0.4.20;
library math{
function add(uint _fValue, uint _sValue) public returns(uint){
return _fValue + _sValue;
}
}
contract salary{
using math for uint;
function salarywithBouns(uint _salary, uint _bonus) public
returns(uint){
return _salary.add(_bonus);
}
}

I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

No Comments

Post a Reply

Inquire Now
close slider