Solidity

如何將十六進制值轉換為可讀格式?

  • May 2, 2018

我正在使用 etherscan API 來獲取事件日誌:

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

結果是一個具有十六進制值的對象:

{
 "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"
   }
 ]
}

我正在從我的 NodeJS 伺服器呼叫 API 並嘗試將web3.toAscii()十六進制值轉換為可讀格式 - 它們都不起作用。ethjs.toAscii()``ethjs.toUtf8()

我唯一可以將十六進制數字轉換為可讀數字,例如使用 blocknumberparseInt()

這是我的契約程式碼的基本結構:

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);
   }
}

我缺什麼地方?如何將事件數據日誌轉換為可讀格式?Javascript中的“解碼”功能是什麼?

試試這個:

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;
}

引用自:https://ethereum.stackexchange.com/questions/47303