xrpl_std/core/ledger_objects/
account.rs

1use crate::core::types::account_id::AccountID;
2use crate::core::types::keylets::account_keylet;
3use crate::{host, sfield};
4use host::Error;
5
6pub fn get_account_balance(account_id: &AccountID) -> host::Result<u64> {
7    // Construct the account keylet. This calls a host function, so propagate the error via `?`
8    let account_keylet = match account_keylet(account_id) {
9        host::Result::Ok(keylet) => keylet,
10        host::Result::Err(e) => return host::Result::Err(e),
11    };
12
13    // Try to cache the ledger object inside rippled
14    let slot = unsafe { host::cache_ledger_obj(account_keylet.as_ptr(), account_keylet.len(), 0) };
15    if slot <= 0 {
16        return host::Result::Err(Error::NoFreeSlots);
17    }
18
19    // Get the balance.
20    let mut balance = 0u64;
21    let result_code = unsafe {
22        host::get_ledger_obj_field(
23            slot,
24            sfield::Balance,
25            (&mut balance) as *mut u64 as *mut u8,
26            8,
27        )
28    };
29
30    match result_code {
31        8 => host::Result::Ok(balance), // <-- 8 bytes were written
32        code if code < 0 => host::Result::Err(Error::from_code(code)),
33        _ => host::Result::Err(Error::InternalError), // <-- Used for an unexpected result.
34    }
35}