xek-sdk
Version:
SDK for katana blockchain
83 lines (68 loc) • 1.96 kB
JavaScript
;
const BigNumber = require('bignumber.js');
const {SUBDIVISION} = require('../constant');
function validateAddress(address) {
return /^[0-9a-fA-F]{40}$/.test(address);
}
function validateBlock(height) {
return /[0-9]/.test(height);
}
function validateTxHash(hash) {
return /^[0-9a-fA-F]{64}$/.test(hash);
}
const isUint = (n) => {
n = Number(n);
return !Number.isNaN(n) && Number.isInteger(n) && n >= 0;
};
const fromXek = (xek) => {
const value = new BigNumber(xek);
return value.multipliedBy(new BigNumber(SUBDIVISION)).toNumber();
};
const toXek = (subdivision) => {
const value = new BigNumber(subdivision);
return value.dividedBy(new BigNumber(SUBDIVISION)).toString(10);
};
const subtraction = (a, b) => {
return new BigNumber(a).minus(b);
};
const bigNumToString = (val, base) => {
return new BigNumber(val).toString(base);
};
const encodeUtf8 = (text) => {
const code = encodeURIComponent(text);
const bytes = [];
const len = code.length;
for (let i = 0; i < len; i++) {
const c = code.charAt(i);
if (c === '%') {
const hex = code.charAt(i + 1) + code.charAt(i + 2);
const hexVal = parseInt(hex, 16);
bytes.push(hexVal);
i += 2;
} else {
bytes.push(c.charCodeAt(0));
}
}
return bytes;
};
const decode = (buf) => {
let unit8Arr = new Uint8Array(buf);
let encodedString = String.fromCharCode.apply(null, unit8Arr);
return decodeURIComponent(escape((encodedString)));
};
const compare = (a,b) => {
return new BigNumber(a).comparedTo(b);
}
module.exports = {
isTxHash: validateTxHash,
isBlockHeight: validateBlock,
isAddress: validateAddress,
isUint: isUint,
toXek: toXek,
fromXek: fromXek,
encode: encodeUtf8,
decode: decode,
subtraction: subtraction,
bigNumToString: bigNumToString,
compare: compare
};