1

I have a simple smart contract that is supposed to record input strings on the blockchain using events:

pragma solidity 0.4.19;

contract Recorder{
  event Record(
    address _from,
    string _message,
    uint _cash
  );

  function record(string message) public payable {
    Record(msg.sender,message,msg.value);
  }

  function () public payable {} 
}

I have deployed it on my testrpc network and it works fine. I have this external javascript code that I execute view truffle console:

module.exports = function(callback) {
const Recorder = artifacts.require('Recorder');
//const artifacts = require('./build/contracts/Recorder.json');


recorder = Recorder.at(Recorder.address);


recorder.record.sendTransaction("123",{from: web3.eth.accounts[0],value: 70}).then(console.log(web3.eth.getBalance(Recorder.address)));

console.log(web3.eth.getBalance(Recorder.address));

}

It works fine, but the account balance doesn't update in the script. The console.log portion shows a balance of 0 at the address.

If I console.log the account balance in the truffle console after running this external script it shows the correct balance.

If I run the external script again it shows a non-updated account balance. If I run the script once it shows a balance of 0. The second time I run the console.log portion only shows 70, etc.

The truffle console is always up to date, but the external script is always one run behind. It isn't a big issue, I just want to expand my understanding of what is going on in the background.

1 Answer 1

0

Try this to execute the log after the transaction was mined

module.exports = function(callback) {
  const Recorder = artifacts.require('Recorder');
  const recorder = Recorder.at(Recorder.address);

  recorder.record("123",{from: web3.eth.accounts[0],value: 70}).then(function () {
    console.log(web3.eth.getBalance(Recorder.address)); 
  });
}

In truffle you have this posibilities

  • myContract.method(params) will wait until the transaction was added to the blockchain.

  • myContract.method.sendTransaction(params) will return immediately with the transaction hash without waiting.

  • myContract.method.call(params) will execute the function no changes will be done to the contract (ie like it was a getter).

  • myContract.method.estimateGas(params) will estimate how much gas will consume.

1
  • Thank You so much. This makes a lot of sense and fixed my problem.
    – Donely
    Feb 21, 2018 at 8:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.