Reputation:
I am new in solidity. Now i am confused since we can write function in solidity ?
why do we need library for example. uniswap use's library to write down some of their re-usable functions.
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
.... other functions ..
}
Upvotes: -1
Views: 220
Reputation: 49361
2 main reasons.
Uniswap has too many contracts. If they need the same function in 3 different contracts, they have to implement the same function in 3 contracts. This will make each contract code look bloated and also each contract deployment would be extra expensive. Think of "library" like a singleton object in OOB, you create an object and store it in memory and every time you need that object, EVM brings it to you from the same location.
Instead of creating a library they could create a base contract and inherit from the contract but inheriting means copying the code of the base contract into the child contract so this would also cost too much gas.
Upvotes: 1