How to unflatten Solidity contracts

How to unflatten Solidity contracts

Useful if you fork flattened contracts and want to bring a better development experience for you and your team.


2 min read

In this article, I will show you how to easily unflatten a Solidity contract back into its organized project structure with a brand-new tool I created.

Flatten? Unflatten? What's that?

A Solidity contract is often "flattened" when being verified on a scanner. This means that all files from the project are put together in a single .sol file. Doing that will be easier to verify and share your contract, because you will have to share just a single file, instead of sharing some folders full of contracts.

But of course, that can be annoying when you get the flattened source code and want to work on it. You can simply just work on the flattened contract. It will work with no problems, but it's far from good if you want to keep basic organization and a good development experience.

Solidity Unflattener

That's why I created "solidity-unflattener". It's a very simple command you can run on your terminal. The only requirement is having node + npm installed on your machine.

Consider this file:

A flattened .sol file with lots of contracts

It's a flattened contract with hundreds of lines, joining a lot of solidity contracts in just a .sol file.

Then I can run this command:

npx @devdavi/unflatten <file_name> [<output_dir>] [--wd]


... and it will recreate the whole project structure, resulting in this:


You can notice that I used the --wd option which actually means "with dependencies". If you are using truffle, hardhat or another project structure based on NPM packages you can just yarn add @openzeppelin/... but if you are not using external dependencies from a package manager you can use the --wd option so it will also create the external dependencies files. By default, the command will ignore the external dependencies and recreate ONLY the project files.