2

Lets say I have many contracts that are already deployed and I don't want to re-deploy them (using testrpc), can I still test them with truffle?

  • or some other mocha based testing tool. – viknek Oct 17 '17 at 0:23
1

If you have the source code of the contract you should be good to go, start normally, but instead of using .deployed() replace with .at(<address>) (drop the source in contracts/ and compile to create the artifacts needed).

const ContractA = artifacts.require("./ContractA.sol");

const addressA = '0x12341234...';

contract('Contract A', function(accounts) => {
  let instanceA;
  before(async () => {
    instanceA = await ContractA.at(addressA);
  });
  it('Test ', () => {
    assert.ok(instanceA, 'Contract should be deployed');
  });
});

If you do not have the contract but have the ABI you can use truffle-contract to access the instance, and it should work inside your tests.

0

You can do something like this:

const Web3 = require('web3');
const contract = require('truffle-contract');
const fs = require('fs');
const fileContent = fs.readFileSync('./build/contracts/SampleContract.json', 'utf8');
const sampleContractArtifact = JSON.parse(fileContent);
const sampleContract = contract(sampleContractArtifact);
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));

sampleContract.setProvider(web3.currentProvider);

describe('Sample Contact', () => {
    //call deployed().then(function) and get the instance. You can test with the instance object.
});
0

Yes, you can access deployed contracts in your testing scenarios. This is particularly helpful to run test scenarios that touch live contract data (user accounts, Oracles, other deployed helper contracts, contracts and callbacks outside your control).

The technique is simple and powerful:

  1. Write a smart contract that performs inspection and testing
  2. Get the deployment transaction byte code for that contract
  3. Run ESTIMATEGAS on that transaction

This allows you to perform any action as any account in your test scenarios.

The technique is fully documented at https://fulldecent.blogspot.com/2019/04/testing-deployed-ethereum-contracts.html

This is based on my presentation at NIFTY 2018 / Hong Kong and I have demonstrated with 0xcert many flaws in deployed ERC-721 contracts using this technique. Yes, you can tool this to work with Truffle as well.

This approach is limited to testing which can be done with byte code (in Solidity). You cannot test events using this approach. If you would like to test events on deployed smart contracts then please see these additional two questions:

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.