0

I have create a basic truffle project and i am writing automated tests.

There is 2 ways to instantiate the smartcontract to test and i want to understand the difference between this 2 ways:

const SimpleStorage = artifacts.require("./SimpleStorage.sol");
contract("SimpleStorage", accounts => {
  
  beforeEach( async () => {
     // Way 1:
     this.instance = await SimpleStorage.new({ from: accounts[0] });

     // Way 2:
     this.instance = await SimpleStorage.deployed();
  });

It works in both cases but i want to understand the differences between new and deployed

Thanks

1 Answer 1

1

.new() instructs it to deploy an instance of the contract.

.deployed() returns the deployed contract on the active network, with a twist. You can use that in a UI or nodejs app that wants the deployed contract, but truffle test uses a sandbox that is meant to prevent tests from scribbling on production contracts. So, test goes ahead and deploys a new one, just like new(), and it pretends that was the deployed contract.

Personally, my habit is to use new() so I know it is a new instance without reliance on the sleight-of-hand always working as expected. That method strikes me as more explicit and less vulnerable to future breaking changes or bugs in Truffle itself.

There is a good reason for the behavior. Developers might form the habit of using deployed() everywhere. In tests, it could lead to trouble, so the sandbox idea keeps them out of trouble. I treat this interception like an emergency circuit-breaker that shouldn't be the primary means or sole means of preventing a disaster, so new(), because that's what I actually want.

In practice, both work and the result is mostly the same. Maybe a kind soul will chime in with subtle differences if any exist.

Hope it helps.

4
  • Thanks a lot. What do you mean by "twist" ?
    – Bob5421
    Commented Jan 31, 2021 at 13:02
  • 1
    "plot twist" - it isn't always the current latest deployed instance. Sometimes they do the old switcheroo. Commented Jan 31, 2021 at 21:04
  • twist is not a specific blockchain term ?
    – Bob5421
    Commented Feb 1, 2021 at 7:05
  • 1
    No. Colloquial. :-) Commented Feb 1, 2021 at 17:27

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.