DAY 24
0
Blockchain

## 開發智能合約 - 函式庫 (Day24)

`library` 語法的使用方式類似 `contract` 語法，沒有自己的合約帳戶，所以在 library 不能使用 `payable`，也沒有 `fallback` 函式。

``````pragma solidity ^0.4.25;

library Utils {
return this;
}
}

contract MyContract {
function test() returns () {
}
}
``````

### Using For

``````using lib for type;
``````

``````pragma solidity ^0.4.25;

library MyLibrary {
function add(int num1, int num2) view returns(int result) {
return num1 + num2;
}
}

contract Number {
int num = 2;

using MyLibrary for int;

function addTwo() public {
}
}
``````

``````contract Number {
int num;

using MyLibrary for int;

function addTwo() public {
num = MyLibrary.add(40, 2);
}
}
``````

#### SafeMath.sol

``````pragma solidity ^0.4.25;

contract MyContract {
using SafeMath for uint256;
uint256 result;

function SafeAdd(uint256 a, uint256 b) {
result = 0;
}
}

library SafeMath {

/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}

uint256 c = a * b;
require(c / a == b);

return c;
}

/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold

return c;
}

/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;

return c;
}

/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);

return c;
}

/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
``````