How can I generate the ABI of my smart contract locally with foundry/forge?
Asked Answered
A

2

5

I have a project with multiple smart contracts locally and I want to generate the ABI of my sc.sol smart contract. I do wish to perform this locally using forge or foundry. I know it is possible to do it on Remix or to use solc but I do not have these and wishes to use foundry/forge only.

Ankle answered 21/9, 2023 at 10:39 Comment(0)
Z
6

forge build generates the contract artifacts in the out folder (by default).

You can parse the JSON artifact and read the abi section.

For example using the jq bash command:

forge build --silent && jq '.abi' ./out/MyContract.sol/MyContract.json

src/MyContract.sol:

pragma solidity ^0.8.21;

contract MyContract {
    function foo() external {}
}

Output of the above command:

[
  {
    "inputs": [],
    "name": "foo",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  }
]
Zins answered 21/9, 2023 at 10:57 Comment(4)
Okay. But those files have lots of other data within them...but no deployed addressesCorissa
@Corissa forge build only compiles the contract, i.e. translates the human-readable Solidity code into machine-readable bytecode (and generates the ABI as a side-step to that). But it doesn't deploy the contract... In order to deploy a contract to a new address, you can use the forge create command. What it does in the background, it sends a transaction from your deployer address (signed by the deployer private key), containing the bytecode. And then the EVM node that produces a new blocks stores the contract bytecode and assigns it a new address.Zins
Thank you. I will trim those file down to only ABIs and add deployment addresses.. for frontend usageCorissa
you could also use a compiler option to create separate abi files and skip the jq part: --extra-output-files abiMediaeval
P
1

You can use

forge inspect <YOUR_CONTRACT> abi

and if you want to generate a file with it use

forge inspect <YOUR_CONTRACT> > <OUTPUT_FILE>

for example

forge inspect src/MyContract.sol:MyContract > myContractAbi.json

And if you add the flag --pretty and the output is a .sol file it will write you the contract interface. Like

forge inspect src/MyContract.sol:MyContract --pretty > MyContractInterface.sol
Prefatory answered 4/8 at 11:38 Comment(1)
you missed abi before > in your example :)Corissa

© 2022 - 2024 — McMap. All rights reserved.