Skip to content

Instantly share code, notes, and snippets.

@liamzebedee
Created March 1, 2023 02:57
Show Gist options
  • Save liamzebedee/769d2b9077a60eee58024aa652275b33 to your computer and use it in GitHub Desktop.
Save liamzebedee/769d2b9077a60eee58024aa652275b33 to your computer and use it in GitHub Desktop.
Compile Solidity inside JS/TS
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