5

I'm having trouble to pass bytes32 to a solidity function from javascript. It's converting to an incorrect bytes32 in solidity. The javascript is a test, running with truffle v3.3.1 on testRPC v3.0.5.

MyContract {


  event myEvent(bytes32 id);
  function myTran(bytes32 arg) {
     myEvent(arg);
  }
}

When I pass it a string it works (and myEvent emits a correct hex):

myContract.myTran( "0x2a1acd26847576a128e3dba3aa984feafffdf81f7c7b23bdf51e7bec1c15944c");

this works too:

var x = "0x2a1acd26847576a128e3dba3aa984feafffdf81f7c7b23bdf51e7bec1c15944c";
return myContract.myTran(x);

This works but I i receive a different hex value from the myEvent than the passed hex:

 ... tx executed before  ...
    var x = new String( tx.logs[0].args.id );
    console.log(typeof x, x); // output: string 0x2a1acd26847576a128e3dba3aa984feafffdf81f7c7b23bdf51e7bec1c15944c
    return myContract.myTran(x); // executes but the bytes32 in the event is different
3

Have you tried passing in the string primitive?

var x = new String(tx.logs[0].args.id);
return myContract.myTran(x.valueOf()); 
  • thanks for the tip. with x.valueOf() I get: Error: VM Exception while processing transaction: invalid opcode as well – szerte Jul 6 '17 at 7:46
  • I notice that you aren't indexing q in your event myEvent(bytes32 q); And then you are accessing a formatted event result, specifying id with tx.logs[0].args.id. Could you be reading the wrong argument? – Max Jul 6 '17 at 9:33
3

I've created a independent test case and it turned out the invalid opcodes were caused by something else.

Anyways, the outcome from my tests is that it fails only if I pass as a String object (it accepts it but converts the 0x0.. string into its ascii values).

Passed as String object .valueOf():

var testFoo = "0x341f85f5eca6304166fcfb6f591d49f6019f23fa39be0615e6417da06bf747ce";
var testFooObj = new String(testFoo);
return instance.sendFoo(testFooObj.valueOf());
// returns correct:
// "0x341f85f5eca6304166fcfb6f591d49f6019f23fa39be0615e6417da06bf747ce"

Passed as object:

var testFooObj = new String(testFoo);
return instance.sendFoo(testFooObj);
// returns incorrectly converted:
// "0x2230783334316638356635656361363330343136366663666236663539316434"

Contract:

pragma solidity ^0.4.11;

contract Bytes32Test {
    bytes32[] public fooStore;

    function getFooStoreLength() constant returns (uint len) {
        return fooStore.length;
    }

    event logFoo(bytes32 foo);
    function sendFoo(bytes32 foo) {
        fooStore.push(foo);
        logFoo(foo);
    }

}
  • Excellent! Well done. Good luck with the rest of your dev cycle. – Max Jul 6 '17 at 11:52

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.