typestar

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

  1. library Fruit holds internal pure functions.
  2. using Fruit for uint256 makes them methods.
  3. kg.toCrates() reads as if uint256 always had it.

Keywords and builtins used here

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.

Type this snippet

Step 4 of 4 in Composition, step 20 of 28 in Language basics.

← Previous Next →