0

I am trying to fetch the latest block from the Avalanche network's public RPC server. I have succeeded in sending JSON-RPC calls to their server and I get a response. The problem is how to decode the response and make meaning out of the data returned.

Here are my attempts

 <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

    <script>

      jQuery.ajax({
    url: "https://api.avax.network/ext/bc/C/rpc",
    type: "post",
    data: JSON.stringify({
    "jsonrpc": "2.0",
    "id": 65,
    "method": "eth_getBlockByNumber",
    "params": ["latest", false]
  }),
    contentType: "application/json; charset=utf-8",
    dataType   : "json",
    success    : function (data) {
      console.log((data.result.gasUsed))
            console.log(data);
        },
    error      : function (xhr, status, errorThrown) {
        console.log(xhr);
    }
});
</script>

My issue now is that each time I try to decode each value from the response object, it fails. I've tried using hexcode to string converter, but it doesn't work. Here is the code snippet I've tried:

function hex2a(hex) {
var str = '';
for (var i = 0; i < hex.length; i += 2) {
    var v = parseInt(hex.substr(i, 2), 16);
    if (v) str += String.fromCharCode(v);
}
return str;

}

This does not return a readable string. And I am stuck on a side project. Can someone help me out?

Andyke
  • 39
  • 7

1 Answers1

2

You can use the native parseInt() function to convert hex numbers to their decimal form.

Example: parseInt(0x1c6500) returns 1860864.

Petr Hejda
  • 40,554
  • 8
  • 72
  • 100
  • Wow! You just saved my entire life..... Thank you so much for this. I have spent the last two days on this very issue. This is a very beautiful new year gift. – Andyke Jan 01 '22 at 13:28