0

I used solc compiler in react app but browser is not compatible with it and gives an error after using that code;

const createContract = async () => {
    const contract = erc1155.print();
    console.log(contract);

    compileSmartContract(contract);
  };

  function compileSmartContract(sourceCode: string): CompilationOutput {
    const input = {
      language: "Solidity",
      sources: {
        "MyContract.sol": {
          content: sourceCode,
        },
      },
      settings: {
        outputSelection: {
          "*": {
            "*": ["abi", "evm.bytecode"],
          },
        },
      },
    };

    const output = JSON.parse(solc.compile(JSON.stringify(input)));

    if (!output.contracts["MyContract.sol"]) {
      throw new Error("Compilation failed");
    }

    const contract = output.contracts["MyContract.sol"].MyContract;
    const abi = JSON.stringify(contract.abi);
    const bytecode = contract.evm.bytecode.object;

    return { abi, bytecode };
  }

error

Also I tried remix API and truffle compilers to compile smart contract and get bytecode and abi of it. Is there any proper way to compile given contract ?

0

1 Answer 1

0

Try to use a backend(Node JS). Send your smart contract to the backend, store your smart contract, and spawn a child process to run the smart contract using the truffle command. Get the output and send it to the API response. The way now you are doing is like beating around the bush. Try this way, It worked for me.

var fs = require('fs');
var exec = require('child_process').exec;

async function copyabi(Name){
  fs.copyFile('./artifacts/contracts/'+Name+'.sol/'+Name+'.json', './ABI/'+Name+'.json', function (err, file) {
    if (err) throw err;
    console.log('Contract ByteCode Recorded Successfully...');
});
}

 async function deploy(Name){
    return exec("npx hardhat run --network ropsten scripts/Deploy2.js", function(err, stdout, stderr) {
      if (err) {
        console.log(err);        
      }
      console.log(stdout);
      copyabi(Name);
    });
  }

fs.watchFile('./JSON/data.json', {bigint: false, persistent: true, interval: 2000}, function (curr, prev) {
  console.log("File Changed");
  fs.readFile('./JSON/data.json', 'utf8', function (err, data) {
    if (err) throw err;
      var obj = JSON.parse(data);
    if(obj.TxHash != ""){
      console.log("Contract Deployed", obj.TxHash);
      return resolve({
        status: 200,
        message: "New Contract Created and deployed successfully...",
        result: obj
      });
    }
  });
});

So whenever the contract gets compiled and gives the JSON abi. It'll be deployed to the network. If you want you can the functionalities by handling errors and all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.