2

I have a simple contract which logs an error if the input is less than 9 characters/bytes. It works fine with remix, but not in truffle js test and truffle console. Am I doing something wrong by passing the bytes32 input as "123456789"?

Contract:

pragma solidity ^0.4.11;

contract TestLength {

    event Error(string message, bytes32 input);
    bytes32[] allInputs;

    function test(bytes32 input) {

        if (!validateLength(input, 9 , 9)) {
            Error("minimum 9 characters", input);
        }

        allInputs.push(input);
    }

    function validateLength(bytes32 b, uint minLength, uint maxLength) 
    constant internal returns (bool) {

      for (uint i = 0; i < 32; i++) {
        if (i < minLength) {
          if(b[i] == 0) return false;
        }
        if (i > maxLength - 1) {
          if(b[i] != 0) return false;  
        }
      }

      return true;
    }
}

Truffle JS test:

var TestLength = artifacts.require("./test/TestLength.sol");

contract('TestLength', function(accounts) {
  it("should not throw an error when passing 9 characters", function() {

    var testLength;

    return TestLength.deployed().then(function(instance) {
      testLength = instance;
      return testLength.test("123456789",{from: accounts[0]});
    }).then(function(instance) {
      console.log("test: " + JSON.stringify(instance));
      assert.equal(instance.logs.length,0,"no event should be triggered.");
    });

  });

});
4

The issue was with how remix and JS console differs on how it accepts string arguments.

The solution was to change the input from "123456789" to web3.fromUtf8("123456789")

web3.fromAscii also works.

With web3 version 1.0 (currently in beta). These functions have moved under "utils". https://web3js.readthedocs.io/en/1.0/web3-utils.html?highlight=fromUtf8#asciitohex

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.