2

How do we call contracts with msg.value? For example, below is my basic contract, but couldn't find anyway to write test cases in truffle. So how do I write test cases for below methods? deposit(), deposit(unit amount), deposit(address adr) ??

pragma solidity ^0.4.18;

import "./ConvertLib.sol";

contract MetaCoin {
    mapping (address => uint) balances;

    event Transfer(address _from, address _to, uint256 _value);

    function MetaCoin() public {
        balances[tx.origin] = 10000;
    }

    function getBalance(address addr) public view returns(uint) {
        return balances[addr];
    }

    function getBalanceInEth(address addr) public view returns(uint) {
        return ConvertLib.convert(getBalance(addr), 2);
    }   

    function deposit() payable {
        balances[msg.sender] += msg.value;
    }

    function deposit(uint amount) payable {
        balances[msg.sender] += amount;
    }

    function deposit(address addr) payable {
        balances[addr] += msg.value;
    }               
}

Truffle Test

var MetaCoin = artifacts.require("./MetaCoin.sol");

contract('MetaCoin', function(accounts) {
  it("should put 10000 MetaCoin in the first account", function() {
    return MetaCoin.deployed().then(function(instance) {
      return instance.getBalance.call(accounts[0]);
    }).then(function(balance) {
      assert.equal(balance.valueOf(), 10000, "10000 wasn't in the first account");
    });
  });
  it("should return 20000 Eth in the first account", function() {
    return MetaCoin.deployed().then(function(instance) {
      return instance.getBalanceInEth.call(accounts[0]);
    }).then(function(balance) {
      assert.equal(balance.valueOf(), 20000, "10000 wasn't in the first account");
    });
  });  
});
1

You can do it like this:

instance.deposit(accounts[0], {from: someAccount, value: someValueInWei});
1

This is currently not supported. In the near future it should be via the following syntax

See pull request #94

You can use the payable and value options.

instance.methods['deposit()']

or

instance.methods['deposit(address)']

etc...

  • 1
    Ok, I have changed my method signatures. So no overloading for now. – Jimson Kannanthara James Mar 2 '18 at 14:49

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.