Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
const res = await rpc.Query.invokeScript(sb.str).execute(url);
const tokenList = {} as { [symbol: string]: u.Fixed8 };
if (
!res ||
!res.result ||
!res.result.stack ||
res.result.stack.length !== 3 * scriptHashArray.length
) {
throw new Error("Stack returned was invalid");
}
try {
for (let i = 0; i < res.result.stack.length; i += 3) {
try {
const symbol = rpc.StringParser(res.result.stack[i]);
const decimals = rpc.IntegerParser(res.result.stack[i + 1]);
tokenList[symbol] = rpc
.Fixed8Parser(res.result.stack[i + 2])
.mul(Math.pow(10, 8 - decimals));
} catch (e) {
log.error(`single call in getTokenBalances failed with : ${e.message}`);
throw e;
}
}
return tokenList;
} catch (err) {
log.error(`getTokenBalances failed with : ${err.message}`);
throw err;
}
}
export async function getTokenBalance(
url: string,
scriptHash: string,
address: string
): Promise {
const sb = new sc.ScriptBuilder();
abi.decimals(scriptHash)(sb);
abi.balanceOf(scriptHash, address)(sb);
const script = sb.str;
try {
const res = await rpc.Query.invokeScript(script).execute(url);
const decimals = rpc.IntegerParser(res.result.stack[0]);
return rpc
.Fixed8Parser(res.result.stack[1])
.mul(Math.pow(10, 8 - decimals));
} catch (err) {
log.error(`getTokenBalance failed with : ${err.message}`);
throw err;
}
}
} else {
sb.emitAppCall(scriptHash, "name")
.emitAppCall(scriptHash, "symbol")
.emitAppCall(scriptHash, "decimals")
.emitAppCall(scriptHash, "totalSupply");
}
});
const res = await rpc.Query.invokeScript(sb.str).execute(url);
const result: TokenInfo[] = [];
const step = address ? 5 : 4;
for (let i = 0; i < res.result.stack.length; i += step) {
const name = rpc.StringParser(res.result.stack[i]);
const symbol = rpc.StringParser(res.result.stack[i + 1]);
const decimals = rpc.IntegerParser(res.result.stack[i + 2]);
const totalSupply = rpc
.Fixed8Parser(res.result.stack[i + 3])
.dividedBy(
Math.pow(10, decimals - rpc.IntegerParser(res.result.stack[i + 2]))
)
.toNumber();
const balance = address
? rpc
.Fixed8Parser(res.result.stack[i + 4])
.dividedBy(
Math.pow(
10,
decimals - rpc.IntegerParser(res.result.stack[i + 2])
)
)
: undefined;
const name = rpc.StringParser(res.result.stack[i]);
const symbol = rpc.StringParser(res.result.stack[i + 1]);
const decimals = rpc.IntegerParser(res.result.stack[i + 2]);
const totalSupply = rpc
.Fixed8Parser(res.result.stack[i + 3])
.dividedBy(
Math.pow(10, decimals - rpc.IntegerParser(res.result.stack[i + 2]))
)
.toNumber();
const balance = address
? rpc
.Fixed8Parser(res.result.stack[i + 4])
.dividedBy(
Math.pow(
10,
decimals - rpc.IntegerParser(res.result.stack[i + 2])
)
)
: undefined;
const obj = {
name,
symbol,
decimals,
totalSupply,
balance
};
if (!obj.balance) {
delete obj.balance;
}