Skip to content

Instantly share code, notes, and snippets.

@rootulp
Created June 27, 2021 18:36
Show Gist options
  • Save rootulp/05652d58dbea00a4e4857284b63af036 to your computer and use it in GitHub Desktop.
Save rootulp/05652d58dbea00a4e4857284b63af036 to your computer and use it in GitHub Desktop.
Query ERC20 token balance on Elrond
export function convertBigEndianArray(arr: Uint8Array): number {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum *= 256;
sum += arr[i];
}
return sum;
}
export async function getErc20Balance({
address,
contractAddress,
proxyProvider,
}: GetErc20BalanceInput) {
const contract = new SmartContract({
address: new Address(contractAddress),
});
const addressOfUser = new Address(address);
const response = await contract.runQuery(proxyProvider, {
func: new ContractFunction("balanceOf"),
args: [new AddressValue(addressOfUser)],
});
const encoded = response.returnData[0];
let byteArray: Uint8Array = [] as any;
protobuf.util.base64.decode(encoded, byteArray, 0);
const data = convertBigEndianArray(byteArray);
return {
data: data,
success: response.isSuccess(),
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment