Solidity – How to Convert Hexadecimal Values into Readable Format Using JavaScript

ethjseventsjavascriptsolidityweb3js

I'm using etherscan API to fetch the event logs:

http://api-ropsten.etherscan.io/api?module=logs&action=getLogs&fromBlock=3147081&toBlock=latest&address=0x8685ab734df053d736164f5c07e22335ba7dda29&topic0=0xcded53d631ce4a38a1f90d59e5f2f9c023cd28c64aa66488e9462cc4a64a032f&apikey=YourApiKeyToken

The result is a Object with hexadecimal values:

{
  "status": "1",
  "message": "OK",
  "result": [
    {
      "address": "0x8685ab734df053d736164f5c07e22335ba7dda29",
      "topics": [
        "0xcded53d631ce4a38a1f90d59e5f2f9c023cd28c64aa66488e9462cc4a64a032f"
      ],
      "data": "0x0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000b579d4f1546d51980499aa96a2e411be3e449197000000000000000000000000000000000000000000000000016345785d8a00000000000000000000000000000000000000000000000000000000000000000001",
      "blockNumber": "0x30054a",
      "timeStamp": "0x5ae8016c",
      "gasPrice": "0x12a05f200",
      "gasUsed": "0x23aea",
      "logIndex": "0x8",
      "transactionHash": "0xb010aa74f66b00a9827044a3bfe4720bb1e057f243e5cae52307bafe2c2bb5d8",
      "transactionIndex": "0xf"
    }
  ]
}

I'm calling API from my NodeJS server and tried web3.toAscii(), ethjs.toAscii() and ethjs.toUtf8() to convert the hexadecimals values into readable format- none of them working.

Only thing I can convert is hexadecimal numbers into readable numbers like blocknumber using parseInt()

Here's a basic structure of my contract code:

contract EtherBlock {
    uint256 public nonce;
    event eOpenPosition(uint256 indexed PositionKey, address indexed Opener, uint256 EtherTossed, uint8 OddEven);
    function OpenPosition (uint8 OddEven) public {
        emit eOpenPosition(nonce, msg.sender, msg.value, OddEven);
    }
}

Where am I lacking? How can I convert the event data logs into readable format? What is the 'decode' function in Javascript?

Best Answer

Try this:

let EVENT = [
    {name: "PositionKey", size: 256, indexed: true },
    {name: "Opener"     , size: 160, indexed: true },
    {name: "EtherTossed", size: 256, indexed: false},
    {name: "OddEven"    , size:   8, indexed: false},
];

function decode(data) {
    let event = {};
    let index = "0x".length;
    for (let i = 0; i < EVENT.length; i++) {
        if (!EVENT[i].indexed) {
            let name = EVENT[i].name;
            let size = Math.floor(EVENT[i].size / 4);
            event[name] = web3.toBigNumber("0x" + data.substr(index, size));
            index += size;
        }
    }
    return event;
}
Related Topic