Seems that isHex is missing on the JS library.
re2005 opened this issue · 4 comments
Describe the bug
isHex is not present on the utils
To Reproduce
Check the available apis:
https://github.com/Zilliqa/Zilliqa-JavaScript-Library/tree/dev/packages/zilliqa-js-util
Trying to use isHex
and it's not exported.
Hi @re2005 , isHex
is part of the bytes package.
If you are checking whether the given hex string is a legitimate Base16 address, I recommend you to use isAddress
as it contains additional checks to ensure the length is valid. isHex
is a more generic hex string check.
Some examples:
const { bytes, validation } = require('@zilliqa-js/util');
function test() {
const hexStr1 = "0x1234567890abcdef";
const hexStr2 = "0x43D459eC504C7432959c086B0ac7F7855E984306";
const bech32 = "zil1g029nmzsf36r99vupp4s43lhs40fsscx3jjpuy";
const testHex = bytes.isHex(hexStr1);
const testHex2 = bytes.isHex(hexStr2);
const testAddr = validation.isAddress(hexStr2);
const testBech32 = validation.isAddress(bech32);
console.log("%o is hex: %o", hexStr1, testHex);
console.log("%o is hex: %o", hexStr2, testHex2);
console.log("%o is address: %o", hexStr2, testAddr);
console.log("%o is address: %o", bech32, testBech32);
}
test();
Response:
'0x1234567890abcdef' is hex: true
'0x43D459eC504C7432959c086B0ac7F7855E984306' is hex: true
'0x43D459eC504C7432959c086B0ac7F7855E984306' is address: true
'zil1g029nmzsf36r99vupp4s43lhs40fsscx3jjpuy' is address: false
Hi @teye thanks for the explanation and examples. I'm looking to validate a transaction hash.
0xc9e623374ca81a854cb5d05b0df10b0155aedf8768c7190ffe5927d11905c50e
isHex will validate it, but not sure about the length. Any recommendation ?
Thanks!
you may want to check out GetTransaction
:
const { Zilliqa } = require('@zilliqa-js/zilliqa');
const zilliqa = new Zilliqa('https://dev-api.zilliqa.com'); <-- adjust this according to mainnet or testnet url
async function test2() {
try {
const tx = await zilliqa.blockchain.getTransaction('c9e623374ca81a854cb5d05b0df10b0155aedf8768c7190ffe5927d11905c50e');
console.log(tx.getReceipt());
} catch (e) {
console.log(e);
}
}
test2();
Response:
{ code: -20, data: null, message: 'Txn Hash not Present' }
The GetTransaction returns the details of the transaction if present. If the transaction hash is invalid, i,e not in hex form, it will return { code: -1, data: null, message: 'Unable to Process' }
See https://dev.zilliqa.com/docs/apis/api-transaction-get-tx for more info.
Alternatively...If you don't need to know whether the transaction is on the blockchain or just want a quick simple validation, you can also use isHex
and check the length to ensure it has 64 characters. Note: this "simple check" does not validate if the transaction has encountered errors while processing on the blockchain.