getting wallet balance using BitcoinJ

756 views Asked by At

I am trying to get a wallet balance using BitcoinJ, this is the code i am trying but it always returns 0

BriefLogFormatter.init();
    NetworkParameters params ;
    String net = "testnet"; //choosing network
    if (net.equals("testnet")) {params = TestNet3Params.get();
    } else if (net.equals("regtest")) {params = RegTestParams.get();
    } else {params = MainNetParams.get();}

    String privKey = "key-here";
     BigInteger test = new BigInteger(privKey);
    ECKey key = ECKey.fromPrivate(test);//initializing key
     Wallet wallet = new Wallet(params);
     wallet.importKey(key); //puting key in wallet

     BlockStore blockStore = new MemoryBlockStore(params);
     BlockChain chain = new BlockChain(params, wallet, blockStore);
     PeerGroup peerGroup = new PeerGroup(params, chain);
     peerGroup.addWallet(wallet);
     peerGroup.startAsync(); //syncing with the blockchain

     
    System.out.println( wallet.getBalance().toString());//getting balance
2

There are 2 answers

0
TB_98 On

Use the WalletAppKit class to handle all the boiler plate:

WalletAppKit walletAppKit = WalletAppKit(params, ScriptType, FileDirectory)

walletAppKit.startAsync()
walletAppKit.awaitRunning()
walletAppKit.wallet().getBalance().toPlainString()
0
Shepherd On

You should downloadBlockChain after startAsync

peerGroup.startAsync();
peerGroup.downloadBlockChain();