I've fired up my testrpc
and deployed a simple HelloWorld contract using truffle
. I send a simple transaction to my contract and I log my account balance before and after the transaction. Unfortunately, this does not add up to the gasUsed parameter I see in the transaction.
contract HelloWorld {
uint public x;
function HelloWorld() {
x = 5;
}
function set_x(uint _x) returns(uint x) {
x = _x;
return x;
}
}
And my javascript
var HelloWorld = artifacts.require("./HelloWorld.sol");
module.exports = function(callback) {}
from_wei = web3._extend.utils.fromWei
var account1 = web3.eth.accounts[0];
var start_balance = web3.eth.getBalance(account1).toNumber();
HelloWorld.deployed().then(function(instance) {
return instance.set_x(500)
}).then(function(tx) {
console.log(tx)
var new_balance = web3.eth.getBalance(account1).toNumber();
console.log(start_balance + " initial balance");
console.log(new_balance + " balance after transaction");
console.log((start_balance - new_balance) + " difference");
console.log(from_wei(start_balance - new_balance) + " difference (from_wei) ?");
console.log(web3.eth.gasPrice.toNumber() + " gas price")
})
Outputs something like this:
{ tx: '0x1a2876b330618c75c7e264becbee75c491b47b5a17a0f9f9fe7fb124f0e93113',
receipt:
{ transactionHash: '0x1a2876b330618c75c7e264becbee75c491b47b5a17a0f9f9fe7fb124f0e93113',
transactionIndex: 0,
blockHash: '0xf30134cac3be167d6053a21953b87010ce7145ccb36775e76d38458dddfa81b9',
blockNumber: 16,
gasUsed: 21736,
cumulativeGasUsed: 21736,
contractAddress: null,
logs: [] },
logs: [] }
99939363900000000000 initial balance
99937190300000000000 balance after transaction
2173600000000000 difference
0.0021736 difference (from_wei) ?
20000000000 gas price
It looks like the difference in my account balance IS the same as the gas used, just a different magnitude. So I'm confused? Are these numbers expressed in wei? I thought I needed to multiply by the gas price to see how much the transaction would affect my account balance...? How can I get GasUsed to equal the difference in my account balance?
1
eth.getTransaction
) will show the actual gas price used.toNumber()
at all cost.