Created
March 1, 2023 02:57
-
-
Save liamzebedee/769d2b9077a60eee58024aa652275b33 to your computer and use it in GitHub Desktop.
Compile Solidity inside JS/TS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const solc = require('solc') | |
const solcInput = (contractName: string, content: string) => ({ | |
language: 'Solidity', | |
sources: { | |
[contractName]: { | |
content: content | |
}, | |
}, | |
settings: { | |
optimizer: { | |
enabled: true, | |
runs: 200, | |
}, | |
evmVersion: 'petersburg', | |
outputSelection: { | |
'*': { | |
'*': ['abi', 'evm.bytecode'], | |
}, | |
}, | |
}, | |
}) | |
export function compileSolidity(contractName: string, content: string) { | |
const input = solcInput(contractName, content) | |
const output = JSON.parse(solc.compile(JSON.stringify(input))) | |
let compilationFailed = false | |
if (output.errors) { | |
for (const error of output.errors) { | |
if (error.severity === 'error') { | |
console.error(error.formattedMessage) | |
compilationFailed = true | |
} else { | |
console.warn(error.formattedMessage) | |
} | |
} | |
} | |
if (compilationFailed) { | |
return undefined | |
} | |
return output | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment