Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot unmarshal hex string without 0x prefix #2333

Closed
MisaZ10 opened this issue Feb 6, 2019 · 3 comments
Closed

Cannot unmarshal hex string without 0x prefix #2333

MisaZ10 opened this issue Feb 6, 2019 · 3 comments
Labels
Bug Addressing a bug

Comments

@MisaZ10
Copy link

MisaZ10 commented Feb 6, 2019

Expected behavior

pragma solidity ^0.4.11;

contract Voting {
    mapping (bytes32 => uint8) public votesReceived;
    bytes32[] public candidateList;

    function Voting(bytes32[] candidateNames) {
        candidateList = candidateNames;
    }

    function totalVotesFor(bytes32 candidate) returns (uint8) {
        if (validCandidate(candidate) == false) throw;
        return votesReceived[candidate];
    }

    function voteForCandidate(bytes32 candidate) {
        if (validCandidate(candidate) == false) throw;
        votesReceived[candidate] += 1;
    }

    function validCandidate(bytes32 candidate) returns (bool) {
        for(uint i = 0; i < candidateList.length; i++) {
            if (candidateList[i] == candidate) {
                return true;
            }
        }
        return false;
    }
}
const Web3 = require('web3');
const solc = require('solc');
const fs = require('fs');

const provider = new Web3.providers.HttpProvider("http://localhost:8545")
const web3 = new Web3(provider);
const asciiToHex = Web3.utils.fromAscii;

const candidates = ['Rama', 'Nick', 'Jose'];

web3.eth.getAccounts()
.then((accounts) => {
  const code = fs.readFileSync('./voting.sol').toString();
  const compiledCode = solc.compile(code);
  const errors = [];
  const warnings = [];
  (compiledCode.errors || []).forEach((err) => {
    if (/\:\s*Warning\:/.test(err)) {
      warnings.push(err);
    } else {
      errors.push(err);
    }
  });

  if (errors.length) {
    throw new Error('solc.compile: ' + errors.join('\n'));
  }
  if (warnings.length) {
    console.warn('solc.compile: ' + warnings.join('\n'));
  }
  const byteCode = compiledCode.contracts[':Voting'].bytecode;
  const abiDefinition = JSON.parse(compiledCode.contracts[':Voting'].interface);

  const VotingContract = new web3.eth.Contract(abiDefinition,
    {data: byteCode, from: accounts[0], gas: 47}
  );

  let deployedContract = null;
  const votingHex = candidates.map(asciiToHex) // votingHex [ '0x52616d61', '0x4e69636b', '0x4a6f7365']
  VotingContract.deploy({
    data: byteCode,
    arguments: [votingHex]
  })
  .send(function (error, transactionHash) {
    if (error) new Error(error); // here return error
    console.log('transactionHash', transactionHash);
  })
  .catch((e) => {
    console.error(e)
    process.exit(1)
  })
});

This is a small example of a contract.
I want to deploy a smart contract and vote for candidate.

Actual behavior

I want to deploy a smart contract but in deploy function return error.

I am using Web3.js 1.0.0-beta.37 because with the version 1.0.0-beta.41 I have this issue
#2256

Steps to reproduce the behavior

  1. Connect to private blockchain
  2. Compile contract
  3. Try to deploy contract with arguments (array to bytes32)

Error Logs

Error: Returned error: invalid argument 0: json: cannot unmarshal hex string without 0x prefix into Go struct field SendTxArgs.data of type hexutil.Bytes

Extra data

I created a private test blockchain with this genesis.json

{
  "config": {
    "chainId": 3,
    "homesteadBlock": 1,
    "eip150Block": 2,
    "eip150Hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "eip155Block": 3,
    "eip158Block": 3,
    "byzantiumBlock": 4,
    "clique": {
      "period": 5,
      "epoch": 30000
    }
  },
  "nonce": "0x0",
  "timestamp": "0x5a8efd25",
  "extraData": "0x00000000000000000000000000000000000000000000000000000000000000003590aca93338b0721966a8d0c96ebf2c4c87c5448cc5a1a0802db41db826c2fcb72423744338dcb00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
  "gasLimit": "0xf42400",
  "difficulty": "0x1",
  "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
  "coinbase": "0x0000000000000000000000000000000000000000",
  "alloc": {
    "3590aca93338b0721966a8d0c96ebf2c4c87c544": {
      "balance": "0x200000000000000000000000000000000000000000000000000000000000000"
    },
    "8cc5a1a0802db41db826c2fcb72423744338dcb0": {
      "balance": "0x200000000000000000000000000000000000000000000000000000000000000"
    }
  },
  "number": "0x0",
  "gasUsed": "0x0",
  "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000"
}

Versions

NPM 6.4.0
Node v8.11.1
Web3.js 1.0.0-beta.37
OS Ubuntu 18.04

@nivida nivida added the Bug Addressing a bug label Feb 6, 2019
@nivida
Copy link
Contributor

nivida commented Feb 8, 2019

Does this error still occur in the latest version (beta.44)? I've fixed issue #2256.

@MisaZ10
Copy link
Author

MisaZ10 commented Feb 11, 2019

With 1.0.0-beta.46 I have this result:

Error: invalid bytes32 value (arg="candidateNames", coderType="bytes32", value="0x52616d61", version=4.0.24)

@nivida
Copy link
Contributor

nivida commented Feb 18, 2019

Yes, this error happens because ethers.js added a strict validation for bytes* values.

Just change this line:

const votingHex = candidates.map(asciiToHex);

To:

const votingHex = candidates.map((value) => {
  return asciiToHex(value);
});

This is required because asciiToHex does have a default property for defining the bytes length the returned string should have. The default length is 32 bytes please check out the documentation for further details: web3.utils.asciiToHex.

Btw.: You could use the web3.utils.asciiToHex method directly instead of using the fromAscii alias.

@nivida nivida closed this as completed Feb 18, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Addressing a bug
Projects
None yet
Development

No branches or pull requests

2 participants