xclud / web3dart

Ethereum library, written in Dart.
https://pub.dev/packages/web3dart
MIT License
170 stars 94 forks source link

Add token and get balance #130

Open irfandi-fm opened 7 months ago

irfandi-fm commented 7 months ago

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?

xclud commented 7 months ago

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

irfandi-fm commented 7 months ago

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?

reasje commented 4 months ago

@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);