I've set up a Truffle sample project, which contains the following contract with the last method added for demonstration purposes (see logs below):
pragma solidity ^0.4.4;
import "./ConvertLib.sol";
// This is just a simple example of a coin-like contract.
// It is not standards compatible and cannot be expected to talk to other
// coin/token contracts. If you want to create a standards-compliant
// token, see: https://github.com/ConsenSys/Tokens. Cheers!
contract MetaCoin {
mapping (address => uint) balances;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
function MetaCoin() {
balances[tx.origin] = 10000;
}
function sendCoin(address receiver, uint amount) returns(bool sufficient) {
if (balances[msg.sender] < amount) return false;
balances[msg.sender] -= amount;
balances[receiver] += amount;
Transfer(msg.sender, receiver, amount);
return true;
}
function getBalanceInEth(address addr) returns(uint){
return ConvertLib.convert(getBalance(addr),2);
}
function getBalance(address addr) returns(uint) {
return balances[addr];
}
function getBalanceWithConstant(address addr) constant returns(uint) {
return balances[addr];
}
}
The getBalance()
function only return a value and doesn't alter the state of the network. Why was there no constant
used for this function in the Truffle sample code? From what I can tell looking at the logs, in its current form, it needs mining and costs gas when being called.
Update
Here's the log.
First I call the function with the constant, which just returns the value:
Home:truffle migu$ truffle console
truffle(development)> var meta;
undefined
truffle(development)> MetaCoin.deployed().then(function(instance) { meta = instance;})
undefined
truffle(development)> address = '0xf27c14a83851210c6e26502433fd8193733ace90'
'0xf27c14a83851210c6e26502433fd8193733ace90'
truffle(development)> var tx = meta.getBalanceWithConstant(address);
undefined
truffle(development)> tx
{ [String: '10000'] s: 1, e: 4, c: [ 10000 ] }
Also, the testrpc logs don't show any mining:
eth_call
Then I call the function without a constant:
truffle(development)> var tx1 = meta.getBalance(address);
undefined
truffle(development)> tx1
{ tx: '0xc671857f5fdfb1e7f487cebd32d74a1dfd99a3d54d8201f4435e4595753400be',
receipt:
{ transactionHash: '0xc671857f5fdfb1e7f487cebd32d74a1dfd99a3d54d8201f4435e4595753400be',
transactionIndex: 0,
blockHash: '0xe12fce4f8e2b3dd8fc0ca840ab5a63e60a8c94e22ab6c5b157fc654ddf4c2f48',
blockNumber: 6,
gasUsed: 23146,
cumulativeGasUsed: 23146,
contractAddress: null,
logs: [] },
logs: [] }
And the testrpc logs show mining activities:
eth_sendTransaction
Transaction: 0xc671857f5fdfb1e7f487cebd32d74a1dfd99a3d54d8201f4435e4595753400be
Gas usage: 0x5a6a
Block Number: 0x06
Block Time: Sun Mar 12 2017 08:07:27 GMT+1100 (AEDT)
eth_getTransactionReceipt