1

I am just adding 2 strings into one string but getting below error:

transact to TestStrings.testCOntract errored: Error encoding arguments: SyntaxError: Unexpected token e in JSON at position 2

Below is my contract code:

pragma solidity ^0.5.1;

library Strings {

    function concat(string memory _base, string memory _value) internal returns (string memory) {

        bytes memory _baseBytes = bytes(_base);
        bytes memory _valueBytes = bytes(_value);

        string memory _tmpValue = new string(_baseBytes.length + _valueBytes.length);
        bytes memory _newValue = bytes(_tmpValue);

        uint i;
        uint j;

        for(i = 0;i<_baseBytes.length;i++) {
            _newValue[j++] = _baseBytes[i];
        }

        for(i = 0;i<_valueBytes.length;i++) {
            _newValue[j++] = _baseBytes[i];
        }
        return string(_newValue);
    }
}

contract TestStrings {

    using Strings for string;

    function testCOntract(string memory _base) public returns(string memory) {
        return _base.concat("_suffix");
    }
}

I have tried THIS accepted answer and it's working fine. But I am not sure what I am missing with my code.

Dharmesh Kheni
  • 169
  • 2
  • 7

1 Answers1

1

You Error is in the second for, it should be _valueBytes[i], and use pure in your function

pragma solidity ^0.5.1;

library Strings {

    function concat(string memory _base, string memory _value) internal pure returns (string memory) {

        bytes memory _baseBytes = bytes(_base);
        bytes memory _valueBytes = bytes(_value);

        string memory _tmpValue = new string(_baseBytes.length + _valueBytes.length);
        bytes memory _newValue = bytes(_tmpValue);

        uint i;
        uint j;

        for(i = 0;i<_baseBytes.length;i++) {
            _newValue[j++] = _baseBytes[i];
        }

        for(i = 0;i<_valueBytes.length;i++) {
            _newValue[j++] = _valueBytes[i];
        }
        return string(_newValue);
    }
}

contract TestStrings {

    using Strings for string;

    function testCOntract(string memory _base) public pure returns(string memory) {
        return _base.concat("_suffix");
    }
}

enter image description here

Majd TL
  • 3,217
  • 3
  • 17
  • 36