Proper use of artifacts.require?

13.7k views Asked by At

I am trying to understand how artifacts.require should be used. I've seen the standard paragraph describing it as being for migrations and testing. From this I infer that the globally scoped artifacts with its method require are automatically defined by the truffle executable tool when doing migrations or running tests. However, I am working with some code that uses artifacts.require outside the context of any migrations or tests, rather, this code just needs to do the usual at and new. However, in this context, the object artifacts is not defined.

Do I have the right picture here? Is this an appropriate use of artifacts.require? If so, what must be done to make it be defined outside of migrations and testing?

Thanks for any suggestions!

1

There are 1 answers

1
Tom Carchrae On BEST ANSWER

artifacts.require really isn't meant to be used outside of a test. this is where it is defined: https://github.com/trufflesuite/truffle-core/blob/3e96337c32aaae6885105661fd1a6792ab4494bf/lib/test.js#L240

when in production code you should load the compiled contract into your application using truffle-contract https://github.com/trufflesuite/truffle-contract

here is a short example (from http://truffleframework.com/docs/getting_started/packages-npm#within-javascript-code and see http://truffleframework.com/docs/getting_started/contracts#making-a-transaction )

var contract = require("truffle-contract");
var contractJson = require("example-truffle-library/build/contracts/SimpleNameRegistry.json");
var SimpleNameRegistry = contract(contractJson);
SimpleNameRegistry
  .deployed()
  .then(function(instance) {
     return instance.setRegistry(address);
   })
  .then(function(result) {
    // If this callback is called, the transaction was successfully processed.
    alert("Transaction successful!")
  })
  .catch(function(e) {
    // There was an error! Handle it.
  });