Controlling the cost of the Ethereum transactions our users have to pay in our dApps is crucial. Since we are anyways implementing tests of our contracts, usually with Truffle, why not take advantage of those tests to display the cost of each one?

How to implements costs in your tests

At first you will need:

npm install crypto-price --save-dev

Then you can do something like this:

var myContract = artifacts.require('./contracts/MyContract.sol');
var cryptoPrice = require('crypto-price');

var ethPrice;
var cost;

contract('myContract', function(accounts) {

  before( () => {
    return cryptoPrice.getCryptoPrice('EUR', 'ETH').then( (result) => {
      ethPrice = result.price;
    });
  });

  beforeEach( () => {
    cost = 0;
  });

  it('It should do thing1', function() {
    var contract;
    return myContract.deployed().then(function(instance) {
      contract = instance;
      return contract.mySendFunction({from: accounts[0]});
    }).then(function(result) {
      cost = ((web3.fromWei((result.receipt.gasUsed) * (web3.eth.gasPrice), 'ether')) * ethPrice).toFixed(2);
    }).then(function() {
      return contract.myCallfunction.call(accounts[1]);
    }).then(function(result) {
      assert.equal(result, true, 'It did not do thing1');
    });
  });

  afterEach( () => {
    console.log('Cost: ' + cost + '€');
  });

});

Add new comment

Comment