0

I am trying to use truffle-contract and web3 to create a new instance of a contract and then get the contract address of the contract that I just created.

I have tried the following code with a few similar variations but I get an error of the form "Cannot set property 'contractInstance' of undefined"

I understand it can take a few minutes to create the contract but how do I factor this into the code?

What is the recommended way to do this, or best practice?

  createNewContract(value) {
    return new Promise((resolve, reject) => {
      const contract = require('@truffle/contract');
      const transferContract = contract(tokenAbi);
      transferContract.setProvider(that.web3);
      transferContract.new({from: account}).then(function(instance) {
        this.contractInstance = instance.address;
        return instance.address;
      }).then(function(status) {
        if (status) {
          return resolve({status: true});
        }
      }).catch(function(error) {
        console.log(error);
        return reject('new contract error');
      });
    });
  } 


Thanks

1

One possible solution could be:

// setting up web3 provider
const Web3 = require('web3')
const web3 = new Web3('ws://localhost:8545')
// import contract artifacts from build folder generated
// as a result of truffle migrate command
const sampleContractArtifact = require('./build/SampleContract')

const ContractInstance = async () => {
  //This method find the network id to retrieve the configuration from truffle-config.js file
  const networkId = await web3.eth.net.getId();
  // Retrieve the Network configuration from truffle-config.js file
  const deployedNetwork = sampleContractArtifact.networks[networkId];
  // Initializing the contract
  const SampleContract = new web3.eth.Contract(
    sampleContractArtifact.abi,
    deployedNetwork.address
  );

  return SampleContract;
};

export default ContractInstance;

The above block of code assumes you are using ganache configured to run at port 8545 in truffle.config.js. However, it will work with any network, you need to update your web3 provider accordingly.

Hope it will help.

1
  • Thanks, the async property really helped. I got things working inspired by your answer – Zakoff Aug 31 '20 at 10:58
0

I solved this by reducing it to a simply async function


  async createNewContract() {
    const that = this;

    const contract = require('@truffle/contract');
    const transferContract = contract(tokenAbi);
    transferContract.setProvider(that.web3);
    let newContract = await transferContract.new({from: that.account});
    this.contractInstance = newContract.address;
    console.log('the new contract created has an address of'+this.contractInstance);
    return this.contractInstance;
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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