Better Programming

Advice for programmers.

Follow publication

You're unable to read via this Friend Link since it's expired. Learn more

Member-only story

Create Your First Solidity Library and Publish It on NPM

Angad Singh
Better Programming
Published in
2 min readNov 28, 2022
Photo by Shubham Dhage on Unsplash

If you have written Solidity code, chances are you have used an existing contract/library, most likely something from openzeppelin. Something like:

import "@openzeppelin/contracts/utils/Strings.sol";

Today we are going to go through how to create your own Solidity Library and publish it on NPM.

Step 1: Initializing the Repository

Before writing any Solidity code let’s first make our directory. I’m assuming you are using Mac/Linux, so then we can create our directory via:

mkdir YOUR_DIR_NAME

Assuming you have npm installed, we can now initialize an npm directory into it via:

cd YOUR_DIR_NAME
npm init -y

Step 2: Writing the Solidity Code

Once you have the repo, we can now create our first Solidity library. Libraries in Solidity require the library keyword instead of contract define.

For this tutorial, we will create a library that has only one function. This function will just concatenate two strings together. Here’s the code I came up with:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

library Concatenator {
function concatenate(string calldata _str, string calldata _str1)
public pure returns(string memory)
{
return string(abi.encodePacked(_str, _str1));
}
}

Step 3: Publish and Use the Library

Once you are done, you can now publish this library simply by running:

npm publish

If you are not logged in to an npm account in your terminal, you might need to do so by:

npm adduser

Done! Now your library is available to millions of NPM users worldwide!

Test Your Library

If you would like to test your library, you can do it by writing a basic contract such as:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "YOUR_DIR_NAME/Concatenator.sol";

contract Tester {
using Concatenator for string;
function concatenate(string calldata _str, string calldata _str1) public pure returns(string memory) {
return _str.concatenate(_str1);
}
}

If you liked this, you might like higher frequency content by me on Twitter. I’m looking forward to seeing which cool libraries you come up with!

Thanks for reading.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Angad Singh
Angad Singh

Written by Angad Singh

Talking about money, tech and how to make money from tech. https://captainkong.io

No responses yet

Write a response