Compiling contract code in tests #6164
-
Hi there, I want to compile a smart contract code (which has a couple of dependencies) in a test. The reason for this is that the contract code is a template. So I would like to do something like this: it('works', async () => {
const CompiledContract = await compile(getSource(variables));
const instance = await CompiledContract.new();
// ..
}) Any pointers? |
Beta Was this translation helpful? Give feedback.
Answered by
0xGh
Aug 21, 2023
Replies: 1 comment 3 replies
-
Came up with this solution: const path = require('path');
const fs = require('fs');
const TruffleCompile = require('@truffle/workflow-compile').default;
const TruffleConfig = require('@truffle/config');
const TruffleContract = require('@truffle/contract');
const MyContractSource = require('fs').readFileSync('./contracts/MyContract.sol', 'utf-8');
let truffleConfig = null;
async function compile(source, fileName = 'TestContract') {
const config = truffleConfig || TruffleConfig.detect();
if (!truffleConfig) {
truffleConfig = config;
}
const outFile = path.join('contracts', 'mocks', fileName + '.sol');
fs.writeFileSync(outFile, source);
if (config._ && config._.length > 0) {
config.paths = config._.map(specifiedPath => {
const absolutePath = path.resolve(config.working_directory, specifiedPath);
if (fs.existsSync(absolutePath)) {
return absolutePath;
} else {
return specifiedPath;
}
});
}
const compilationOutput = await TruffleCompile.compile(config);
fs.unlinkSync(outFile);
const contractArtifact = compilationOutput.compilations[0].contracts.find(
({ contractName }) => contractName == fileName,
);
if (contractArtifact == null) {
throw new Error('Contract compiled but not found');
}
const contract = TruffleContract(
contractArtifact.bytecode == 'string'
? contractArtifact
: require('@truffle/compile-common').Shims.NewToLegacy.forContract(contractArtifact),
);
contract.setProvider(web3.currentProvider);
return contract;
} Probably this solution is not the best because it saves the contract on disk but I am sure it can be improved further later on. |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
gnidan
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Came up with this solution: