0

I have a setup with one contract that is a singleton and is migrated to e.g. a testnet through the truffle console. This contract "creates" new contracts, which I want to access in the truffle console. Since the new contracts are not migrated via the console I want to use instance.at(address) in a command I will execute in truffle. However, it's not recognising the instance...

Contracts:
Singleton.sol → migrated via truffle ManyOfMe.sol → created via Singleton.sol

Error:

TypeError: ManyOfMe.at is not a function

Code: run.js executed through truffle console: exec ./run.js

const artifacts = require('./build/contracts/Singleton.json')
const ManyOfMe = require('./build/contracts/ManyOfMe.json')
const contract = require('truffle-contract')
const MyContract = contract(artifacts)
MyContract.setProvider(web3.currentProvider)

let Singleton
MyContract.deployed()
.then(async function(instance) {
  Singleton = instance

  let tokenAddress
  await Singleton.tokens(0).then(_ => {
    tokenAddress = _
  })
  return ManyOfMe.at(tokenAddress)
})
.then(function(instance) {
  instance.doSomething().then(_ => console.log(_))
})
.catch(function(error) {
  console.error(error)
})

PS: If I just type ManyOfMe in the truffle console, I see the at function, so I'm not sure why it won't work.

1

When you run the script with truffle exec, you'll already have the truffle context (e.g. artifacts), so you don't need to import all the stuff manually.

What you're trying to achieve is something like this here:

const Singleton = artifacts.require("Singleton");
const ManyOfMe = artifacts.require("ManyOfMe");

module.exports = function(done) {
    // code rewritten with async/await
    (async () => {
            var singleton = await Singleton.deployed();
            var manyOfMeAt0 = await ManyOfMe.at(await singleton.tokens(0));
            console.log(await manyOfMeAt0.doSomething());           

            done();
    })();
}

Moreover, if you can use async/await, then there is no need for then-chains. It improves the readability.

  • Great answer! I love the readability! Clarified a lot for me. Final question: what's the done() ? – mesqueeb Feb 27 '18 at 9:28
  • done is the signal for truffle that you've finished with your script. Since you have asnyc code here, the function returns immediatly. – ivicaa Feb 27 '18 at 9:31
  • Thanks man! Upvoting big time! You've been a real help. You're a peach. – mesqueeb Feb 27 '18 at 9:41
  • You‘re welcome. Feel free to check my other answers. ;) – ivicaa Feb 27 '18 at 13:45

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.