Using keyword in Solidity

Using keyword in Solidity.

I was recently asked to explain the meaning of the term “Using for” in Solidity. As I tried to provide a clear explanation, I realized that it can be a complex topic to understand. Therefore, I am here to attempt to clarify it further.

Using is used to include a library within a contract in solidity.

Library

A library in Solidity is a standalone entity that is similar to a contract but is not a contract. It contains view-only functions that can be called by other contracts thereby helping to seperate and re-use code logic.

1
2
3
4
5
library Math{
function add(uint256 a, uint256 b) internal pure returns(uint256){
return a > b ? b : a;
}
}

The library above takes 2 inputs of type uint and returns the smallest of both numbers.
Let us create a function and use the library in it.

1
2
3
4
5
6
//contract to get the minimum of two numbers
contract Example{
function minExample(uint a, uint b) external pure returns (uint256) {
return Math.add(a,b);
}
}

This is the standard implementation of libraries but we can make it shorter and better to enhance data types.

Using SomeLibrary for SomeDataType

1
2
3
4
5
6
7
//contract to get the minimum of two numbers
contract Example{
using Math for uint;
function minExample(uint a, uint b) external pure returns (uint256) {
return a.add(b);
}
}

By using the using Math for uint keyword in this Solidity contract, we can assign all the functions in the Math library to the uint data type. This allows us to call the functions from the library directly on the uint type within the contract, without having to explicitly reference the library.

In this way, we can use expressions like a.add(b) within a function in the contract, where a and b are uint variables. Essentially, using using Math for uint is a convenient way of writing Math.add(a,b) in the contract code.

Using SomeLibrary for * (All Data Types)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
library MathBool {
function multiply(uint a, uint b) internal pure returns (uint256){
return a * b;
}
function reverse (bool a) internal pure returns (bool){
return a ? true : false;
}
}

contract Example {
using MathBool for * ;
function multiplyExample (uint a) external pure returns (uint256){
return a.multiply(9);
}
function reverseExample (bool a) external pure returns (bool){
return a.reverse();
}
}

The line using MathBool for * is a Solidity keyword that imports and makes all functions in the MathBool library available for use within the Example contract on all data types.

The for * part in using MathBool for * indicates that all functions in the MathBool library can be called on any data type. This means that the functions are not limited to a specific data type, unlike before when we specified a particular type, such as “for uint256”. With the for * syntax, all types in the Example contract can use the functions defined in the MathBool library.