Utilizing the Casper Python SDK, pycspr
, you can set up a script to query the balance of an ERC-20 contract.
Currently, the python SDK requires the account-hash of a wallet instead of permitting only the public_key_hex. When calling the below script, you can send the output of the casper-client account-address
command directly to the script for execution.
from pycspr.types import CL_Key
from pycspr import NodeClient
from pycspr import NodeConnection
from pycspr.types import DictionaryID_ContractNamedKey
import base64
import argparse
_NODE_ADDRESS = "localhost"
def main(args):
# step1 create dictionary_item_key
# public key -> 0125a6336791eba195c472a8b7dbcd256a6ecddf8863e586a3dfefe2581a5d672c
account_key=CL_Key.from_string(args.account_hash)
itemKey = base64.b64encode(b'\x00' + account_key.identifier) # b'\x00' for account; b'\x01' for contract package
print("itemKey",itemKey.decode("utf-8"))
client = NodeClient(NodeConnection(host=_NODE_ADDRESS,port_rpc=7777))
# step2 get rpc
# Set dictionary item identifier.
dictionary_id = DictionaryID_ContractNamedKey(
dictionary_name="balances",
dictionary_item_key=itemKey.decode("utf-8"),
contract_key=args.contract_hash
)
# Set node JSON-RPC query response.
response = client.get_dictionary_item(dictionary_id)
# get balance
balance = response["stored_value"]["CLValue"]["parsed"]
# set decimal places (add 1 for 0-indexing)
decs = int(args.decimals + 1)
decs = "1".ljust(decs,"0")
print(f"ERC-20 balance => {int(balance) / int(decs):,}")
if__name__ == "__main__":
try:
parser = argparse.ArgumentParser(
prog='Casper ERC Balance Checker',
description='Queries a public key for the ERC-20 token balance of a given ERC-20 name.',
epilog='Casper Support Engineering Tooling')
parser.add_argument('--account-hash', '-a', dest='account_hash',
required=True,
help='The wallet\'s account-hash, which can be obtained from the casper-client account-address command.')
parser.add_argument('--contract-hash', '-c', dest='contract_hash',
required=True,
help='The ERC-20 contract\'s hash.')
parser.add_argument('--decimals', '-d', dest='decimals',
required=True,
type=int,
help="The number of decimal places the ERC-20 contract has.")
args = parser.parse_args()
main(args)
except Exception as err:
print(f"API ERROR @ NODE {_NODE_ADDRESS} :: {err}")
You can execute this script with a command similar to:
python erc20.py --account-hash $(casper-client account-address --public-key 0125a6336791eba195c472a8b7dbcd256a6ecddf8863e586a3dfefe2581a5d672c) --contract-hash 4120116565bd608fae6a45078055f320a2f429f426c86797b072b4efd15b186a --decimals 11
If you have any concerns, questions, or issues, please submit a request to our support team here:
https://support.casperlabs.io/hc/en-gb/requests/new
Comments
0 comments
Please sign in to leave a comment.