Truffle Contract Abstractions – How to Access from External JS Script

contract-invocationtruffletruffle-contract

When writing tests in truffle (v3.2.1) I can forget about things like a contract's ABI and address and just use ContractName.deployed() to interact with a contract on my testrpc chain. How can I mimic this behavior in my external Javascript code, that is, not by using truffle's built-in console or truffle test? Is there a library I need to import in my script or do I need to manually get the ABI and deployment address of the contract as if I was not using Truffle?

I'd be also fine if I could use those contract abstraction by running my JS code through truffle, but I'm not sure of how would I do that.

Thanks!

Best Answer

Not sure whether this is the intended way, but experimenting with bits and pieces of code found around the Internet resulted in something that seems to be working. Here's what I did in my javascript app:

....
const artifacts = require('../build/contracts/MyContract.json')
const contract = require('truffle-contract')
let MyContract = contract(artifacts);
MyContract.setProvider(web3.currentProvider);    
return MyContract.deployed().then(function(instance){      
  return instance.sendTransaction(param1, param2, {from: accounts[0]});
}).then(function(tx_id){
....

The json file is what was produced by truffle when migrating MyContract. Note that I had to install truffle-contract (on top of truffle) for this to work. If anyone has a more elegant way of doing this, please share!

Related Topic