Load .env files in Solidity scripts/tests
Foundry recently shipped default dotenv parsing. It's in active development but soon the solenv library will no longer be needed. Yay for upstreaming!
forge install memester-xyz/solenv
Firstly, it's very important that you do not commit your .env
file. It should go without saying but make sure to add it to your .gitignore
file! This repo has committed the .env
and .env.test
files only for examples and tests.
- Add this import to your script or test:
import {Solenv} from "solenv/Solenv.sol";
- Call
.config()
somewhere. It defaults to using.env
in your project root, but you can pass another string as a parameter to load another file in instead.
// Inside a test
function setUp() public {
Solenv.config();
}
// Inside a script, load a file with a different name
function run() public {
Solenv.config(".env.prod");
// Continue with your script...
}
- You can then use the standard "env" cheatcodes in order to read your variables. e.g.
envString
,envUint
,envBool
, etc.
string memory apiKey = vm.envString("API_KEY");
uint256 retries = vm.envUint("RETRIES");
bool ouputLogs = vm.envBool("OUTPUT_LOGS");
- You must enable ffi in order to use the library. You can either pass the
--ffi
flag to any forge commands you run (e.g.forge script Script --ffi
), or you can addffi = true
to yourfoundry.toml
file.
- Comments start with
#
and must be on a newline - If you set a key twice, the last value in the file is used
- It assumes you are running on a UNIX based machine with
sh
,cast
andxxd
installed.
We have example usage for both tests and scripts.
To see the script in action, you can run:
forge script SolenvScript
Clone this repo and run:
forge install
Make sure all tests pass, add new ones if needed:
forge test
Forge scripting is becoming more popular. With solenv your scripts are even more powerful and natural to work with.
This project uses Foundry. See the book for instructions on how to install and use Foundry.