AccountService

open class AccountService : @unchecked Sendable

Service for querying account information from the Stellar Horizon API.

The AccountService provides methods to retrieve account details, query account data fields, filter accounts by various criteria, and create test accounts on testnet and futurenet.

Example usage:

let sdk = StellarSDK()

// Get account details
let accountResponse = await sdk.accounts.getAccountDetails(accountId: "GACCOUNT...")
switch accountResponse {
case .success(let account):
    print("Sequence: \(account.sequenceNumber)")
    print("Balances: \(account.balances)")
case .failure(let error):
    print("Error: \(error)")
}

// Query accounts holding a specific asset
let assetAccounts = await sdk.accounts.getAccounts(
    asset: "USD:GISSUER...",
    limit: 20
)

See also:

  • Retrieves detailed information about a single Stellar account.

    Returns account data including balances, signers, thresholds, flags, sequence number, and other account properties. Supports both regular accounts (G-addresses) and muxed accounts (M-addresses).

    Example:

    let response = await sdk.accounts.getAccountDetails(accountId: "GACCOUNT...")
    switch response {
    case .success(let account):
        print("Sequence: \(account.sequenceNumber)")
        for balance in account.balances {
            print("\(balance.assetCode): \(balance.balance)")
        }
    case .failure(let error):
        print("Error: \(error)")
    }
    

    See also:

    Declaration

    Swift

    open func getAccountDetails(accountId: String) async -> AccountResponseEnum

    Parameters

    accountId

    The Stellar account ID (public key). Accepts G-addresses for regular accounts or M-addresses for muxed accounts. For muxed accounts, the underlying ed25519 account is queried automatically.

    Return Value

    AccountResponseEnum with account details on success or error on failure

  • Retrieves a specific data entry from an account’s key-value store.

    Each Stellar account can store arbitrary key-value pairs using the ManageDataOperation. This method retrieves the base64-encoded value for a given key. Returns 404 if the account doesn’t exist or the key is not found.

    Example:

    let response = await sdk.accounts.getDataForAccount(
        accountId: "GACCOUNT...",
        key: "user_email"
    )
    switch response {
    case .success(let data):
        // Decode base64 value
        if let decoded = Data(base64Encoded: data.value) {
            print("Value: \(String(data: decoded, encoding: .utf8) ?? "")")
        }
    case .failure(let error):
        print("Error: \(error)")
    }
    

    See also:

    Declaration

    Swift

    open func getDataForAccount(accountId: String, key: String) async -> DataForAccountResponseEnum

    Parameters

    accountId

    The Stellar account ID containing the data entry

    key

    The name of the data field to retrieve

    Return Value

    DataForAccountResponseEnum with the base64-encoded value on success or error on failure

  • Creates and funds a test account on Stellar’s testnet using Friendbot.

    Friendbot is a service that creates and funds new accounts on testnet with 10,000 XLM. This is useful for testing and development. Only works on testnet, not on the public network.

    Example:

    // Generate a new keypair
    let keyPair = try KeyPair.generateRandomKeyPair()
    let accountId = keyPair.accountId
    
    // Create and fund the account on testnet
    let response = await sdk.accounts.createTestAccount(accountId: accountId)
    switch response {
    case .success:
        print("Test account created: \(accountId)")
    case .failure(let error):
        print("Error: \(error)")
    }
    

    See also:

    Declaration

    Swift

    open func createTestAccount(accountId: String) async -> CreateTestAccountResponseEnum

    Parameters

    accountId

    A Stellar account ID (public key starting with G). Generate using KeyPair.generateRandomKeyPair().accountId

    Return Value

    CreateTestAccountResponseEnum with success or error

  • Creates and funds a test account on Stellar’s futurenet using Friendbot.

    Futurenet is used for testing upcoming protocol features before they reach testnet. This method creates and funds new accounts on futurenet for early testing.

    Example:

    let keyPair = try KeyPair.generateRandomKeyPair()
    let response = await sdk.accounts.createFutureNetTestAccount(accountId: keyPair.accountId)
    switch response {
    case .success:
        print("Futurenet account created")
    case .failure(let error):
        print("Error: \(error)")
    }
    

    See also:

    • createTestAccount for creating accounts on testnet

    Declaration

    Swift

    open func createFutureNetTestAccount(accountId: String) async -> CreateTestAccountResponseEnum

    Parameters

    accountId

    A Stellar account ID (public key starting with G). Generate using KeyPair.generateRandomKeyPair().accountId

    Return Value

    CreateTestAccountResponseEnum with success or error

  • Queries accounts with optional filtering by signer, asset, sponsor, or liquidity pool.

    This endpoint allows you to search for accounts that match specific criteria. All filter parameters are optional - use them individually or in combination to narrow your search. Results are returned as a paginated list.

    Example:

    // Find accounts holding a specific asset
    let response = await sdk.accounts.getAccounts(
        asset: "USDC:GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN",
        limit: 50
    )
    switch response {
    case .success(let page):
        for account in page.records {
            print("Account: \(account.accountId)")
        }
        // Load next page if available
        if page.hasNextPage() {
            let nextPage = await page.getNextPage()
        }
    case .failure(let error):
        print("Error: \(error)")
    }
    
    // Find accounts with a specific signer
    let signerAccounts = await sdk.accounts.getAccounts(
        signer: "GSIGNER...",
        order: .descending
    )
    

    See also:

    Declaration

    Swift

    open func getAccounts(signer: String? = nil, asset: String? = nil, sponsor: String? = nil, liquidityPoolId: String? = nil, cursor: String? = nil, order: Order? = nil, limit: Int? = nil) async -> PageResponse<AccountResponse>.ResponseEnum

    Parameters

    signer

    Filter accounts that have this account as a signer

    asset

    Filter accounts with trustlines to this asset. Use canonical form “CODE:ISSUER” (e.g., “USD:GISSUER…”) or “native” for XLM. See SEP-0011 for asset representation.

    sponsor

    Filter accounts sponsored by this account ID

    liquidityPoolId

    Filter accounts participating in this liquidity pool (L-address or hex)

    cursor

    Pagination cursor to start from. Use nil to start from the beginning.

    order

    Sort order - .ascending or .descending. Default is ascending.

    limit

    Maximum number of records per page. Default is 10, maximum is 200.

    Return Value

    PageResponse containing matching accounts or error

  • Loads accounts from a specific URL.

    Used internally for pagination. Can be called directly with URLs from PageResponse links (e.g., next, prev) to navigate paginated results.

    Example:

    // Manual pagination using URL
    if let nextUrl = accountsPage.links.next?.href {
        let nextPage = await sdk.accounts.getAccountsFromUrl(url: nextUrl)
    }
    

    See also:

    • PageResponse.getNextPage for automatic pagination

    Declaration

    Swift

    open func getAccountsFromUrl(url: String) async -> PageResponse<AccountResponse>.ResponseEnum

    Parameters

    url

    The complete URL to fetch accounts from. Typically obtained from PageResponse.links.next.href or PageResponse.links.prev.href

    Return Value

    PageResponse containing accounts or error

  • Streams real-time updates for a single Stellar account using Server-Sent Events (SSE).

    Creates a persistent connection to Horizon that delivers account state changes as they occur on the Stellar network. Each update contains the complete current state of the account including balances, signers, thresholds, sequence number, and other properties.

    The stream automatically reconnects if the connection is lost. Use the returned AccountStreamItem to receive updates via the onReceive callback and close the stream when finished.

    Example:

    let accountStream = sdk.accounts.streamAccount(accountId: "GACCOUNT...")
    
    accountStream.onReceive { response in
        switch response {
        case .open:
            print("Stream connected")
        case .response(id: let id, data: let account):
            print("Account update - Sequence: \(account.sequenceNumber)")
            for balance in account.balances {
                print("\(balance.assetCode ?? "XLM"): \(balance.balance)")
            }
        case .error(let error):
            print("Stream error: \(error)")
        }
    }
    
    // Close when done
    accountStream.closeStream()
    

    See also:

    • Stellar developer docs
    • AccountStreamItem for stream control methods
    • AccountResponse for the account data structure

    Declaration

    Swift

    open func streamAccount(accountId: String) -> AccountStreamItem

    Parameters

    accountId

    The Stellar account ID (public key). Accepts G-addresses for regular accounts or M-addresses for muxed accounts. For muxed accounts, the underlying ed25519 account is streamed automatically.

    Return Value

    AccountStreamItem for receiving account updates and controlling the stream

  • Streams real-time updates for a specific data entry on a Stellar account using Server-Sent Events (SSE).

    Creates a persistent connection to Horizon that delivers updates whenever the specified data entry changes on the Stellar network. Each update contains the current base64-encoded value for the key.

    Accounts can store arbitrary key-value pairs (up to 64 bytes per value) using the ManageDataOperation. This stream allows you to monitor changes to a specific key in real-time.

    The stream automatically reconnects if the connection is lost. Use the returned AccountDataStreamItem to receive updates via the onReceive callback and close the stream when finished.

    Example:

    let dataStream = sdk.accounts.streamAccountData(
        accountId: "GACCOUNT...",
        key: "user_settings"
    )
    
    dataStream.onReceive { response in
        switch response {
        case .open:
            print("Stream connected")
        case .response(id: let id, data: let dataEntry):
            // Decode base64 value
            if let decoded = Data(base64Encoded: dataEntry.value) {
                let value = String(data: decoded, encoding: .utf8) ?? ""
                print("Data updated - Value: \(value)")
            }
        case .error(let error):
            print("Stream error: \(error)")
        }
    }
    
    // Close when done
    dataStream.closeStream()
    

    See also:

    • Stellar developer docs
    • AccountDataStreamItem for stream control methods
    • DataForAccountResponse for the data entry structure
    • ManageDataOperation for setting account data

    Declaration

    Swift

    open func streamAccountData(accountId: String, key: String) -> AccountDataStreamItem

    Parameters

    accountId

    The Stellar account ID containing the data entry

    key

    The name of the data field to stream

    Return Value

    AccountDataStreamItem for receiving data updates and controlling the stream