web3dart icon indicating copy to clipboard operation
web3dart copied to clipboard

Add token and get balance

Open irfandi-fm opened this issue 1 year ago • 3 comments

Hi! I'm new to the blockchain technology, and I'm currently building a simple wallet using flutter. I can get the balance of my wallet with below code.

  Future<EtherAmount> getBalance(
      {required String privateKey, required String rpcUrl}) async {
    final client = Web3Client(rpcUrl, Client());
    final credentials = EthPrivateKey.fromHex(privateKey);
    final address = credentials.address;
    final balance = await client.getBalance(address);
    debugPrint(balance.toString());

    return balance;
  }

Next, I want to implement the add token just like in metamask. How do do that? I see that we need to supply the contract address. Then how do we get the balance of that token?

irfandi-fm avatar Nov 20 '23 03:11 irfandi-fm

Hi, all you need is to have the contract address. You get balance of the contract address.

xclud avatar Nov 20 '23 04:11 xclud

Hi, all you need is to have the contract address. You get balance of the contract address.

Can you give me an example code? Because the parameter to get the balance is only the wallet address. Where to supply the contract address?

irfandi-fm avatar Nov 20 '23 07:11 irfandi-fm

@irfandi-fm I did these to get token balance :

  1. Generate dart class from contract ABI (There are descriptions about how to do that in the readme of this repo HERE)
  2. Make an instance of that class with It's contract address
  3. call balanceOf func of that instance and get the balance
final ercToken =
    contracts.ErcToken(client: _web3Client, address: data);

final tokenBalanceResponse = await ercToken.balanceOf(address);

reasje avatar Feb 14 '24 10:02 reasje