|
| 1 | +# Flattening your contracts |
| 2 | + |
| 3 | +Hardhat comes with a built-in `flatten` task that lets you combine the source code of multiple Solidity files. |
| 4 | + |
| 5 | +## Flattening all your files |
| 6 | + |
| 7 | +If you use the `flatten` task without passing any other arguments, all the Solidity files in your project will be combined: |
| 8 | + |
| 9 | +``` |
| 10 | +$ npx hardhat flatten |
| 11 | +// Sources flattened with hardhat v2.12.3 https://hardhat.org |
| 12 | +
|
| 13 | +// File contracts/Bar.sol |
| 14 | +
|
| 15 | +// SPDX-License-Identifier: MIT |
| 16 | +pragma solidity ^0.8.0; |
| 17 | +
|
| 18 | +contract Bar {} |
| 19 | +
|
| 20 | +// File contracts/Qux.sol |
| 21 | +
|
| 22 | +... |
| 23 | +``` |
| 24 | + |
| 25 | +The result will be printed to stdout. You can create a file with the flattened sources using the `>` redirection operator: |
| 26 | + |
| 27 | +``` |
| 28 | +$ npx hardhat flatten > Flattened.sol |
| 29 | +
|
| 30 | +$ cat Flattened.sol |
| 31 | +// Sources flattened with hardhat v2.12.3 https://hardhat.org |
| 32 | +
|
| 33 | +// File contracts/Bar.sol |
| 34 | +
|
| 35 | +... |
| 36 | +``` |
| 37 | + |
| 38 | +## Flattening specific files |
| 39 | + |
| 40 | +The `flatten` task can receive a path to the file you want to flatten: |
| 41 | + |
| 42 | +``` |
| 43 | +npx hardhat flatten contracts/Foo.sol |
| 44 | +``` |
| 45 | + |
| 46 | +In this case, the result will contain the source code of `Foo.sol` and all its transitive dependencies (the files that it imports, and the files that those files import, and so on). |
| 47 | + |
| 48 | +You can also use multiple files: |
| 49 | + |
| 50 | +``` |
| 51 | +npx hardhat flatten contracts/Foo.sol contracts/Bar.sol |
| 52 | +``` |
| 53 | + |
| 54 | +But if `Bar.sol` is a dependency of `Foo.sol`, then the result will be the same as in the previous example. |
| 55 | + |
| 56 | +As explained in the previous section, you can redirect the output to some file: |
| 57 | + |
| 58 | +``` |
| 59 | +npx hardhat flatten contracts/Foo.sol > Flattened.sol |
| 60 | +``` |
| 61 | + |
| 62 | +## Circular dependencies |
| 63 | + |
| 64 | +Projects with circular dependencies cannot be flattened at the moment. If this is something you need, please upvote or comment [this issue](https://github.com/NomicFoundation/hardhat/issues/1486). |
0 commit comments