1

I have the following contract (Test.sol):

contract Test {

bytes32 message = "This is a message.";

function setMessage(bytes32 _message) {
    message = _message;
}

function getMessage() constant returns (bytes32) {
    return message;
}

function stringToBytes32(string memory source) returns (bytes32 result) {
    assembly {
result := mload(add(source, 32))
    }
}}

I am trying to make an app where the user enters text and clicks a button, then the setMessage() and getMessage() functions are executed, and the message is displayed.

My index.html file (straightforward):

<input type="text" id="textbox" placeholder="enter something">
<a href="#" onclick="setMessage()" class="btn btn-primary">Submit</a>
<div id="displayedMessage"></div>

and the app.js file that index.html refers to:

  window.setMessage = function () {
  let message = $('#textbox').val()

  Test.deployed().then(function (contractInstance) {
    contractInstance.setMessage(stringToBytes32(message), { gas: 140000, from: web3.eth.accounts[0] }).then(function () {
      contractInstance.getMessage().then(function (v) {
        $('#displayedMessage').html(web3.toAscii(v))
      })
    })
  })

}

There is something wrong with the above code in app.js as the setMessage() function doesn't get called at all, though I don't know why not (I'm not getting any errors in the browser or truffle console). Or maybe it's an issue with converting the string to bytes32. The contract is deployed properly - if instead of the above, I have something like the following:

window.setMessage = function () {
Test.deployed().then(function(contractInstance) {
        contractInstance.getMessage().then(function(v) {
          $('#displayedMessage').html(web3.toAscii(v));
        })
      })

Then getMessage() gets called. But I can't seem to call setMessage()

0

The problem is that you are calling stringToBytes32(message) in line:

contractInstance.setMessage(stringToBytes32(message), { gas: 140000, from: web3.eth.accounts[0] }).then(function () {

as it was a local javascript function while it's a contract method and it should be invoked in a similar way you are invoking setMessage or be called inside the contract context.

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.