Libraries in Solidity
Pure helpers, grafted onto a type with using-for.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
// A library holds pure helpers; using-for grafts them onto a type.
library Fruit {
function toCrates(uint256 kg) internal pure returns (uint256) {
return kg / 18;
}
function isBumper(uint256 kg) internal pure returns (bool) {
return kg > 500;
}
}
contract SeasonReport {
using Fruit for uint256;
function summarize(uint256 kg) external pure returns (uint256) {
require(kg.isBumper(), "an ordinary year");
return kg.toCrates();
}
}
How it works
library Fruitholds internal pure functions.using Fruit for uint256makes them methods.kg.toCrates()reads as if uint256 always had it.
Keywords and builtins used here
boolcontractexternalforfunctioninternallibraryrequirereturnreturnsuint256
The run, in numbers
- Lines
- 22
- Characters to type
- 492
- Tokens
- 89
- Three-star pace
- 55 tpm
At the three-star pace of 55 tokens a minute, this run takes about 97 seconds.
Step 4 of 4 in Composition, step 20 of 28 in Language basics.