Solidity – How to Pass Arbitrary Bytes to a Function

bytessoliditytruffle

I'm trying to implement a contract which will store bytes blob, a dynamic bytes array.

For example I have following struct:

Sign {
    address signer;
    bytes16 signType;
    bytes   sign;
}

plus an event:

event Signed(
    bytes16 signType,
    bytes sign
);

and trying to set it:

function addSignature(byte16 signType, bytes sign) {
    // ... store data
    ... = Sign(msg.sender, signType, sign) 
    // raise event
    Sign(signType, sign);
}

The problem that I can't find a way to pass bytes to the function from Javascript.

I'm using Truffle, and tried following Javascript code:

var type = web3.fromAscii('test', 16);
var sign = [0x12, 0x34]; //also tried web3.toBigNumber('0x1234');
contract.addSignature(type, sign, {from: myAccount, gas: 2000000});

it makes a transaction, but I don't see correct value stored into my contact. For example by listening to Signed event I see that there're an empty array. If I try to read data, I got zeros (actually it's more weird, I get signType padded with long array of zeroes).

What is a proper way to use arbitrary bytes array? hot to send to contract, how to read?

PS I'm using Truffle with TestRPC.

Best Answer

EDIT: See How to pass arbitrary bytes to a function in Remix

The behavior in Remix was changed so see above; the following was for an older version of Remix / browser-solidity.

To pass bytes to a function, pass the bytes as a hex string.

Example in Solidity Browser:

contract SimpleStorage {
    bytes storedData;
    function set(bytes x) {
        storedData = x;
    }
    function get() constant returns (bytes retVal) {
        return storedData;
    }
}

Click "Create", then in "Set" enter "0x1234" or any arbitrary hex string.

Click "Set", then "Get" and you will see your data, encoded according to the ABI.

Related Topic