Solidity: Using X for Y

When auditing smart contracts, this is a syntax you will encounter every day.

The "using" syntax is a great feature that enables developers to write more maintainable and readable code, especially when working with libraries.
A prime example of this syntax in action is seen with SafeMath or EnumerableSet libraries.

Understanding the using Syntax in Solidity

At its core, the using statement in Solidity attaches a library to a specific data type, enabling the library's functions to be called on that data type as if they were methods belonging to the type itself.
This syntax enriches the native type with additional functionality without the need for inheritance or the complexities of contract composition.

Syntax and Use Cases

The syntax for employing a library in your Solidity code is straightforward:

When applied, this allows you to use the library's functions as though they were part of the type you're attaching them to. The SafeMath library is a textbook example:

This line tells the Solidity compiler to treat all uint256 variables as if they have the SafeMath library's functions attached to them.
Consider the conventional approach without the using syntax:

Here, sub is a function from the SafeMath library that subtracts one unsigned integer from another, checking for underflow. The function explicitly takes two uint256 arguments: x and y.
With the using SafeMath for uint256 directive, the syntax becomes more intuitive:

This adjustment might seem minor, but it significantly enhances code readability and maintainability. Instead of always having to refer to the library and its static functions, developers can call functions directly on the variable as if it were a method of uint256.