I want to measure the size of my compiled contract using solc.
I can dump the binary using --bin or --bin-runtime and then count how many hexadecimal digits it contains.
Is there an easier way to do it?
I want to measure the size of my compiled contract using solc.
I can dump the binary using --bin or --bin-runtime and then count how many hexadecimal digits it contains.
Is there an easier way to do it?
You can get a report of the contract byte sizes by adding the --sizes flag when building the contracts:
forge build --sizes
There is this plugin called hardhat-contract-sizer:
$ yarn add --dev hardhat-contract-sizer
You load it in the Hardhat config file:
require('hardhat-contract-sizer');
// OR
import "hardhat-contract-sizer";
And then you run it:
$ yarn hardhat size-contracts
This approach takes more leg-work, but works:
build/contracts/YourContract.json) and grab the value in deployedBytecode. It'll be easier if you use an editor (like Sublime) that lets you collapse JSON values, that you way don't need to scroll past the abi value.bytecode.hex).ls -l bytecode.hex to get the detailed file info which includes the size in bytes.EDIT: Just saw the detail that you're already dumping the binary from solc. You can always copy-paste that into a file. Real time-saver here is using ls -l rather than counting characters.
I'm not sure this kosher, but:
(1) I'm using truffle (so built-in solc)
(2) I wrote a script to compute sizes from compiled contracts. It's pretty trivial. Not sure if it's accurate, but hey, it seems to do a good job of helping me predict when my contracts aren't gonna deploy.
var fs = require('fs') ;
module.exports = async function(cb) {
const LIMIT = 1*1024 ;
function sizes (name) {
var abi = artifacts.require(name) ;
var size = (abi.bytecode.length / 2) - 1 ;
var deployedSize = (abi.deployedBytecode.length / 2) - 1 ;
return {name, size, deployedSize} ;
}
function fmt(obj) {
return ${ obj.name } ${ obj.size } ${ obj.deployedSize } ;
}
var l = fs.readdirSync("build/contracts") ;
l.forEach(function (f) {
var name = f.replace(/.json/, '') ;
var sz = sizes(name) ;
if (sz.size >= LIMIT || sz.deployedSize >= LIMIT) {
console.log(fmt(sz)) ;
}
}) ;
}
4_check_bytecode.js, then runtruffle migrate?
– deju
Feb 18 '19 at 09:14
If you want to do it through smart-contracts on-chain check out the extcodesize opcode that is available when using solidity assembly.
You can use jq to filter the ABI JSON and then wc to count the number of bytes for deployed bytecode:
$ cat artifacts/Greeter.json | jq -r '.deployedBytecode' | wc -c
1555
You can get contract size in hardhat
e.g. test.js in /scripts of hardhat project
const hre = require("hardhat")
async function test() {
// Use Hardhats provider (locally) or your own provider
const provider = ethers.provider
const bytecode = await provider.getCode(contractAddress)
const size = bytecode.length / 2
}