Skip to content

Instantly share code, notes, and snippets.

@daverickdunn
Last active August 22, 2022 13:39
Show Gist options
  • Save daverickdunn/fc7c5190e4c588822b5c80e97ad53068 to your computer and use it in GitHub Desktop.
Save daverickdunn/fc7c5190e4c588822b5c80e97ad53068 to your computer and use it in GitHub Desktop.
Stellar JS SDK view balance.
const StellarSdk = require('stellar-sdk');
StellarSdk.Network.useTestNetwork(); // StellarSdk.Network.usePublicNetwork();
const server = new StellarSdk.Server('https://horizon-testnet.stellar.org'); // const server = new StellarSdk.Server('https://horizon.stellar.org');
// Note: this solution trusts the accounts asset codes alone.
// For general accounts you may need to verify the issuing account id: b.asset_issuer
const getBalance = (account, currency) => {
let balance = 0;
if (currency == 'XLM') {
balance = Number.parseFloat(account.balances.find(b => b.asset_type == 'native').balance);
} else {
balance = Number.parseFloat(account.balances.find(b => b.asset_code == currency).balance);
}
return balance;
}
const keypair = StellarSdk.Keypair.fromSecret('S ...')
server.loadAccount(keypair.publicKey())
.then(account => {
console.log(account.balances)
console.log(getBalance(account, 'XPORT'))
})
@Tardigrada777
Copy link

export const myBalance = async (currency = 'XLM') => {
  const _account = await server.loadAccount(wallet.publicKey());
  const _currency = currency === 'XLM' ? 'native' : currency;
  const _currencyTypeField = currency === 'XLM' ? 'asset_type' : 'asset_code';
  const _balance = _account.balances.find(b => b[_currencyTypeField] === _currency);
  return parseFloat(_balance ? _balance.balance : '0');
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment