Classes
The following classes are available globally.
-
The main entry point for interacting with the Stellar network via the Horizon API.
StellarSDK provides access to all Horizon API services including accounts, transactions, operations, payments, assets, and more. Create an instance configured for your target network (public, testnet, or futurenet) or connect to a custom Horizon server.
The SDK uses the Horizon REST API to query network state and submit transactions. Each instance maintains a connection to a single Horizon server and provides access to specialized service objects for different resource types.
Example:
// Connect to testnet (default) let sdk = StellarSDK() // Connect to public network let publicSdk = StellarSDK.publicNet() // Connect to futurenet let futureSdk = StellarSDK.futureNet() // Connect to custom Horizon URL let customSdk = StellarSDK(withHorizonUrl: "https://custom-horizon.example.com") // Query account information sdk.accounts.getAccountDetails(accountId: "GACCOUNT...") { response in switch response { case .success(let account): print("Balances: \(account.balances)") case .failure(let error): print("Error: \(error)") } } // Stream payment events sdk.payments.stream(for: .paymentsForAccount(account: "GACCOUNT...", cursor: nil)) .onReceive { payment in print("Payment received: \(payment)") }See also:
- [Network] for network passphrase configuration
- Stellar developer docs
- Individual service classes for specific operations
Declaration
Swift
public final class StellarSDK : Sendable -
Holds a Stellar keypair consisting of a public key and an optional private key.
KeyPair represents an Ed25519 keypair used for signing transactions and verifying signatures on the Stellar network. A keypair can be created with or without a private key:
- With private key: Used for signing transactions (full keypair)
- Without private key: Used for verification only (public key only)
The public key is encoded as a Stellar account ID starting with ‘G’ (or ‘M’ for muxed accounts). The private key (seed) is encoded as a secret seed starting with ‘S’.
Security considerations:
- Never share or expose secret seeds
- Store secret seeds securely using the iOS Keychain or equivalent secure storage
- Never commit secret seeds to version control
- Use KeyPair objects without private keys when only verification is needed
- Clear sensitive data from memory when no longer needed
Example:
// Generate a random keypair let keyPair = try KeyPair.generateRandomKeyPair() print("Account ID: \(keyPair.accountId)") print("Secret Seed: \(keyPair.secretSeed)") // Create keypair from existing secret seed let existingKeyPair = try KeyPair(secretSeed: "SXXX...") // Create public-only keypair for verification let publicOnlyKeyPair = try KeyPair(accountId: "GXXX...") // Sign data let signature = keyPair.sign(data) // Verify signature let isValid = try publicOnlyKeyPair.verify(signature: signature, message: data)See also:
See moreDeclaration
Swift
public final class KeyPair : @unchecked Sendable -
Represents a Stellar Ed25519 private key.
A private key is a 64-byte value that represents the private component of an Ed25519 keypair. The first 32 bytes are the secret scalar, and the last 32 bytes are the precomputed public key. Private keys are used to sign transactions and messages on the Stellar network.
Security considerations:
- Private keys must be kept absolutely secret and secure
- Never transmit private keys over insecure channels
- Store private keys using secure storage (iOS Keychain or equivalent)
- Never commit private keys to version control
- Use Seed class for human-readable secret seed representation
- Clear sensitive data from memory when no longer needed
Note: For most use cases, use the Seed class which provides the 32-byte seed and can be encoded as a human-readable secret seed (S-address).
See moreDeclaration
Swift
public final class PrivateKey : Sendable -
Represents a Stellar Ed25519 public key.
A public key is a 32-byte value that represents the public component of an Ed25519 keypair. Public keys are used to identify accounts on the Stellar network and to verify signatures.
Public keys are encoded as Stellar account IDs (G-addresses) using base32 encoding with version byte and checksum. This encoding makes them human-readable and helps prevent transmission errors.
Usage:
- Creating from bytes: Construct from raw 32-byte public key
- Creating from account ID: Parse from G-address string
- Signature verification: Verify transaction signatures
- XDR encoding/decoding: For network protocol operations
Security considerations:
- Public keys can be safely shared and are meant to be public
- They do not grant access to accounts on their own
- Used to verify that operations were signed by the corresponding private key
Declaration
Swift
public final class PublicKey : XDRCodable, Sendable -
Represents a Stellar Ed25519 seed used for key generation.
A seed is a 32-byte value used to generate Ed25519 keypairs for Stellar accounts. The seed is the private component from which both the private and public keys are derived.
Seeds can be:
- Generated randomly for new accounts
- Derived from BIP-39 mnemonics for hierarchical deterministic wallets
- Created from existing secret seeds (S-address format)
Security considerations:
- Seeds must be stored securely (use iOS Keychain or equivalent)
- Never expose seeds in logs, network requests, or version control
- Seeds encoded as secret seeds start with ‘S’ and are base32-encoded
Declaration
Swift
public final class Seed : Sendable -
Implements SEP-0005 - Key Derivation Methods for Stellar Accounts.
This class provides BIP-39 mnemonic generation and BIP-44 hierarchical deterministic key derivation for Stellar accounts. It allows creating multiple accounts from a single seed phrase, enabling secure wallet backups and account management.
Typical Usage
// Generate a 12-word mnemonic let mnemonic = WalletUtils.generate12WordMnemonic() // Derive first account (index 0) let keyPair0 = try WalletUtils.createKeyPair( mnemonic: mnemonic, passphrase: nil, index: 0 ) // Derive second account (index 1) let keyPair1 = try WalletUtils.createKeyPair( mnemonic: mnemonic, passphrase: nil, index: 1 )See also:
See moreDeclaration
Swift
public final class WalletUtils : Sendable -
Implements SEP-0002 - Federation Protocol.
This class provides human-readable address resolution for Stellar accounts. Instead of using long cryptographic addresses (G…), users can use addresses like “alice*example.com”. Federation makes Stellar more user-friendly by mapping memorable names to account IDs.
Typical Usage
// Resolve a Stellar address to account ID let result = await Federation.resolve( stellarAddress: "alice*testanchor.stellar.org" ) switch result { case .success(let response): print("Account ID: \(response.accountId)") if let memo = response.memo { print("Memo: \(memo)") } case .failure(let error): print("Resolution failed: \(error)") }Reverse Lookup
// Look up address from account ID let federation = Federation(federationAddress: "https://testanchor.stellar.org/federation") let result = await federation.resolve(account_id: "GACCOUNT...") if case .success(let response) = result { print("Stellar address: \(response.stellarAddress ?? "unknown")") }See also:
- SEP-0002 Specification
- [StellarToml] for discovering federation servers
Declaration
Swift
public final class Federation : @unchecked Sendable -
Data parsed from a TOML document
See moreDeclaration
Swift
public class Toml : CustomStringConvertible, SetValueProtocol, @unchecked Sendable -
Implements SEP-0024 - Hosted Deposit and Withdrawal.
This class provides an interactive flow for deposits and withdrawals where the anchor service requires user interaction through a web interface. The user completes KYC and other requirements in the anchor’s hosted web application, then the anchor handles the on/off-ramp process.
SEP-0024 enables a standardized way for wallets to integrate with anchor services for fiat on/off-ramps. The anchor hosts a web interface where users can provide additional information like KYC data, bank account details, or complete email verification.
Typical Workflow
- Initialize Service: Create InteractiveService from anchor’s domain
- Check Capabilities: Query /info endpoint to see supported assets and features
- Authenticate: Obtain JWT token using SEP-0010 WebAuthenticator
- Initiate Flow: Start deposit or withdraw, receive interactive URL
- User Interaction: Open URL in webview/browser for user to complete requirements
- Monitor Status: Poll transaction endpoint to track progress
Example: Complete Deposit Flow
// Step 1: Initialize service from domain let serviceResult = await InteractiveService.forDomain( domain: "https://testanchor.stellar.org" ) guard case .success(let service) = serviceResult else { return } // Step 2: Check what assets are supported let infoResult = await service.info() guard case .success(let info) = infoResult else { return } print("Supported assets: \(info.deposit.keys)") // Step 3: Get JWT token (using SEP-0010) let jwtToken = "..." // Obtained from WebAuthenticator // Step 4: Initiate deposit let depositRequest = Sep24DepositRequest( assetCode: "USDC", account: userAccountId, jwt: jwtToken ) let depositResult = await service.deposit(request: depositRequest) switch depositResult { case .success(let response): // Step 5: Open interactive URL in webview print("Open this URL: \(response.url)") // User completes KYC and provides deposit information // Step 6: Monitor transaction status let txRequest = Sep24TransactionRequest( id: response.id, jwt: jwtToken ) let statusResult = await service.getTransaction(request: txRequest) // Check response.transaction.status case .failure(let error): print("Deposit initiation failed: \(error)") }Example: Withdraw Flow
let withdrawRequest = Sep24WithdrawRequest( assetCode: "USDC", dest: "bank_account", account: userAccountId, jwt: jwtToken ) let result = await service.withdraw(request: withdrawRequest) switch result { case .success(let response): // Open interactive URL print("Complete withdraw at: \(response.url)") // User provides bank details and completes verification // Then sends USDC to the anchor's account case .failure(let error): print("Withdraw failed: \(error)") }Transaction Status Monitoring
// Poll for transaction status updates let txRequest = Sep24TransactionRequest( id: transactionId, jwt: jwtToken ) let result = await service.getTransaction(request: txRequest) if case .success(let response) = result { switch response.transaction.status { case "incomplete": // User needs to complete interactive flow case "pending_user_transfer_start": // Waiting for user to send funds case "pending_anchor": // Anchor is processing case "completed": // Transaction complete case "error": // Transaction failed default: break } }Fee Information
let feeRequest = Sep24FeeRequest( operation: "deposit", assetCode: "USDC", amount: "100", jwt: jwtToken ) let feeResult = await service.fee(request: feeRequest) if case .success(let feeResponse) = feeResult { print("Fee: \(feeResponse.fee)") }Error Handling
let result = await service.deposit(request: depositRequest) switch result { case .success(let response): // Handle success case .failure(let error): switch error { case .authenticationRequired: // JWT token missing or expired, re-authenticate with SEP-10 case .anchorError(let message): // Anchor-specific error (e.g., unsupported asset, amount too large) case .parsingResponseFailed(let message): // Response parsing error case .horizonError(let horizonError): // Network or HTTP error } }Integration with Other SEPs
SEP-0024 often works together with:
- SEP-0010: Required for authentication (JWT tokens)
- SEP-0012: For standalone KYC (may be handled in interactive flow)
- SEP-0038: For cross-asset swaps during deposit/withdraw
Security Considerations
- Always use HTTPS for production
- Validate JWT tokens are current
- Open interactive URLs in a secure webview
- Monitor transaction status to detect issues
- Handle user cancellations gracefully
See also:
- SEP-0024 Specification
- [WebAuthenticator] for SEP-0010 authentication
- [StellarToml] for service discovery
Declaration
Swift
public final class InteractiveService : @unchecked Sendable -
Implements SEP-0012 - KYC API.
This class provides standardized endpoints for transmitting KYC and AML information to anchors and other services. It allows customers to upload their identity information and status tracking for deposit/withdrawal operations requiring identity verification.
SEP-0012 is designed to work with SEP-6 (Deposit/Withdrawal) and SEP-24 (Interactive Deposit/Withdrawal) to enable regulated on/off-ramp operations that require customer identity verification.
Typical Workflow
- Initialize Service: Create KycService from anchor’s domain
- Authenticate: Obtain JWT token using SEP-0010 WebAuthenticator
- Get Required Fields: Query which KYC fields the anchor requires
- Upload Information: Submit customer data and supporting documents
- Check Status: Monitor KYC verification status
Example: Complete KYC Flow
// Step 1: Initialize service from domain let serviceResult = await KycService.forDomain( domain: "https://testanchor.stellar.org" ) guard case .success(let kycService) = serviceResult else { return } // Step 2: Get JWT token (using SEP-0010) let jwtToken = "..." // Obtained from WebAuthenticator // Step 3: Check what fields are required let getRequest = GetCustomerInfoRequest( account: userAccountId, jwt: jwtToken ) let getResult = await kycService.getCustomerInfo(request: getRequest) switch getResult { case .success(let response): if response.status == "NEEDS_INFO" { // Check response.fields to see what's required print("Required fields: \(response.fields?.keys ?? [])") } case .failure(let error): print("Error: \(error)") } // Step 4: Upload customer information let putRequest = PutCustomerInfoRequest(jwt: jwtToken) putRequest.account = userAccountId putRequest.firstName = "John" putRequest.lastName = "Doe" putRequest.emailAddress = "john@example.com" putRequest.birthDate = "1990-01-01" let putResult = await kycService.putCustomerInfo(request: putRequest) switch putResult { case .success(let response): print("Customer ID: \(response.id ?? "")") print("Status: \(response.status ?? "")") case .failure(let error): print("Upload failed: \(error)") }Example: Upload Documents
// Upload a file (e.g., photo ID) let photoData = ... // Image data let fileResult = await kycService.postCustomerFile( file: photoData, jwtToken: jwtToken ) switch fileResult { case .success(let response): // Use file ID in PUT /customer request let fileId = response.id let putRequest = PutCustomerInfoRequest(jwt: jwtToken) putRequest.account = userAccountId putRequest.photoIdFrontFileId = fileId let result = await kycService.putCustomerInfo(request: putRequest) case .failure(let error): print("File upload failed: \(error)") }Example: Verify Email/Phone
// Some anchors require verification of email or phone // First, submit the contact info let putRequest = PutCustomerInfoRequest(jwt: jwtToken) putRequest.account = userAccountId putRequest.emailAddress = "user@example.com" await kycService.putCustomerInfo(request: putRequest) // User receives verification code via email // Submit the verification code let verifyRequest = PutCustomerVerificationRequest( id: customerId, jwt: jwtToken ) verifyRequest.emailAddressVerification = "123456" // Code from email let result = await kycService.putCustomerVerification(request: verifyRequest)Example: Check KYC Status
let getRequest = GetCustomerInfoRequest( account: userAccountId, jwt: jwtToken ) let result = await kycService.getCustomerInfo(request: getRequest) if case .success(let response) = result { switch response.status { case "ACCEPTED": // KYC approved, can proceed with transactions case "PROCESSING": // KYC under review case "NEEDS_INFO": // Additional information required case "REJECTED": // KYC rejected default: break } }Example: Set Status Callback
// Get notified when KYC status changes let callbackRequest = PutCustomerCallbackRequest( url: "https://yourapp.com/kyc-callback", jwt: jwtToken ) let result = await kycService.putCustomerCallback(request: callbackRequest)Example: Delete Customer Data
// Delete all customer information (GDPR compliance) let result = await kycService.deleteCustomerInfo( account: userAccountId, jwt: jwtToken )Error Handling
let result = await kycService.putCustomerInfo(request: putRequest) switch result { case .success(let response): // Handle success case .failure(let error): switch error { case .badRequest(let message): // Invalid field values or missing required fields case .unauthorized(let message): // JWT token invalid or expired case .notFound(let message): // Customer not found case .payloadTooLarge(let message): // File too large case .horizonError(let horizonError): // Network or server error } }Integration with Other SEPs
SEP-0012 is typically used alongside:
- SEP-0010: Required for authentication (JWT tokens)
- SEP-6: Non-interactive deposits/withdrawals requiring KYC
- SEP-24: Interactive deposits/withdrawals (may handle KYC in UI)
- SEP-31: Cross-border payments requiring sender/receiver KYC
Data Privacy
- Customer data is sensitive and should be transmitted securely
- Use HTTPS for all requests
- Implement proper data retention policies
- Provide data deletion functionality for GDPR compliance
- Store JWT tokens securely
See also:
- SEP-0012 Specification
- [WebAuthenticator] for SEP-0010 authentication
- [TransferServerService] for SEP-6 integration
- [InteractiveService] for SEP-24 integration
Declaration
Swift
public final class KycService : @unchecked Sendable
-
Undocumented
Declaration
Swift
public final class BIntMath : Sendable -
Implements BIP-39 mnemonic code for generating deterministic keys.
This class provides functionality for generating and working with mnemonic phrases (also known as seed phrases or recovery phrases) according to the BIP-39 standard. Mnemonics are human-readable representations of cryptographic seeds that can be used to derive hierarchical deterministic wallets.
The mnemonic consists of 12 or 24 words selected from a standardized word list. These words encode entropy that can be used to generate a seed for wallet derivation.
See also:
See moreDeclaration
Swift
public final class Mnemonic : Sendable -
Implements SEP-0038 - Anchor RFQ (Request for Quote) API.
This class provides price discovery and firm quotes for asset exchanges. Anchors use this to offer indicative and firm exchange rates for converting between on-chain and off-chain assets. Essential for cross-asset deposit/withdrawal operations.
Typical Usage
let service = QuoteService(serviceAddress: "https://anchor.example.com") // Get indicative price let priceResult = await service.price( context: "sep6", sellAsset: "iso4217:USD", buyAsset: "stellar:USDC:G...", sellAmount: "100", jwt: jwtToken ) // Request firm quote let quoteRequest = Sep38PostQuoteRequest( context: "sep6", sellAsset: "iso4217:USD", buyAsset: "stellar:USDC:G...", sellAmount: "100" ) let quoteResult = await service.postQuote(request: quoteRequest, jwt: jwtToken) // Use quote in SEP-6 deposit-exchange if case .success(let quote) = quoteResult { let depositRequest = DepositExchangeRequest( destinationAsset: quote.buyAsset, sourceAsset: quote.sellAsset, amount: quote.sellAmount, quoteId: quote.id, account: accountId, jwt: jwtToken ) // Submit to TransferServerService }See also:
- SEP-0038 Specification
- [TransferServerService] for SEP-6 integration
- [InteractiveService] for SEP-24 integration
Declaration
Swift
public final class QuoteService : @unchecked Sendable -
Implements SEP-0030 - Account Recovery: Multi-Party Recovery of Stellar Accounts.
This class provides account recovery functionality allowing users to regain access to their Stellar accounts through registered identities. Multiple recovery methods can be configured as a safety net if primary authentication is lost.
Typical Usage
let service = RecoveryService(serviceAddress: "https://recovery.example.com") // Register account with recovery identities let request = Sep30Request() request.identities = [ Sep30Identity(role: "owner", authMethods: [...]) ] let result = await service.registerAccount( address: accountId, request: request, jwt: jwtToken ) // Sign transaction for recovery let signResult = await service.signTransaction( address: accountId, signingAddress: signerAddress, transaction: transactionXdr, jwt: jwtToken )See also:
- SEP-0030 Specification
- [WebAuthenticator] for SEP-10 authentication
Declaration
Swift
public final class RecoveryService : @unchecked Sendable -
Implements SEP-0008 - Regulated Assets.
This class enables issuers to validate and approve transactions involving regulated assets before they are submitted to the network. Regulated assets require issuer approval for transfers, ensuring compliance with securities regulations and KYC/AML requirements.
Typical Usage
// Initialize from domain let result = await RegulatedAssetsService.forDomain( domain: "https://issuer.example.com", network: .public ) guard case .success(let service) = result else { return } // Build transaction let transaction = try Transaction(...) let txXdr = try transaction.encodedEnvelope() // Submit for approval let approvalResult = await service.postTransaction( txB64Xdr: txXdr, apporvalServer: service.regulatedAssets[0].approvalServer ) switch approvalResult { case .success(let response): // Transaction approved, submit to network let approvedTx = try Transaction(envelopeXdr: response.tx) case .revised(let response): // Issuer revised transaction (e.g., added compliance fee) let revisedTx = try Transaction(envelopeXdr: response.tx) case .pending(let response): // Approval pending, retry later case .actionRequired(let response): // User action needed (e.g., complete KYC) case .rejected(let response): // Transaction rejected }See also:
- SEP-0008 Specification
- [StellarToml] for discovering regulated assets
Declaration
Swift
public final class RegulatedAssetsService : @unchecked Sendable -
Represents a regulated asset that requires issuer approval for transactions.
A regulated asset is defined in stellar.toml with the
See moreregulatedflag set to true and includes an approval server URL where transactions must be submitted for validation.Declaration
Swift
public class RegulatedAsset : Asset, @unchecked Sendable -
Represents a Stellar account with all its properties and balances.
Contains complete account information including balances, signers, thresholds, flags, sequence number, and sponsorship data. This is the main data structure returned when querying account details from Horizon.
Example usage:
let sdk = StellarSDK() let response = await sdk.accounts.getAccountDetails(accountId: "GACCOUNT...") switch response { case .success(let account): // Access account properties print("Account ID: \(account.accountId)") print("Sequence: \(account.sequenceNumber)") // Check balances for balance in account.balances { if balance.assetType == AssetTypeAsString.NATIVE { print("XLM Balance: \(balance.balance)") } else { print("\(balance.assetCode ?? ""): \(balance.balance)") } } // Check signers for signer in account.signers { print("Signer: \(signer.key) weight: \(signer.weight)") } // Use for transaction building let transaction = try Transaction( sourceAccount: account, operations: [/* ... */], memo: Memo.none, timeBounds: nil ) case .failure(let error): print("Error: \(error)") }See also:
- Stellar developer docs
- AccountService for querying accounts
Declaration
Swift
public class AccountResponse : Decodable, TransactionAccount, @unchecked Sendable -
Represents a claimant predicate that defines conditions for claiming a claimable balance. Predicates can be unconditional or time-based, and can be combined using logical operators. See Stellar developer docs
See moreDeclaration
Swift
public final class ClaimantPredicateResponse : Decodable, Sendable -
Represents an account creation effect. This effect occurs when a new account is created on the Stellar network through a Create Account operation. The source account must fund the new account with a minimum balance to cover the base reserve. See Stellar developer docs
See moreDeclaration
Swift
public class AccountCreatedEffectResponse : EffectResponse, @unchecked Sendable -
Represents an account credit effect. This effect occurs when an account receives a payment or other credit operation. Triggered by Payment, Path Payment, Create Claimable Balance claim, and other operations. See Stellar developer docs
See moreDeclaration
Swift
public class AccountCreditedEffectResponse : EffectResponse, @unchecked Sendable -
Represents an account debit effect. This effect occurs when an account sends a payment or other debit operation. Triggered by Payment, Path Payment, Create Claimable Balance, and other operations that reduce an account balance. See Stellar developer docs
See moreDeclaration
Swift
public class AccountDebitedEffectResponse : EffectResponse, @unchecked Sendable -
Represents an account flags update effect. This effect occurs when an account’s authorization flags are modified through a Set Options operation. Flags control asset issuer authorization requirements and account mutability. See Stellar developer docs
See moreDeclaration
Swift
public class AccountFlagsUpdatedEffectResponse : EffectResponse, @unchecked Sendable -
Represents an account home domain update effect. This effect occurs when an account’s home domain is set or changed through a Set Options operation. The home domain is used to link the account to a domain name for federation and additional account information. See Stellar developer docs
See moreDeclaration
Swift
public class AccountHomeDomainUpdatedEffectResponse : EffectResponse, @unchecked Sendable -
Represents an inflation destination update effect. This effect occurs when an account’s inflation destination is set or changed through a Set Options operation. The inflation destination specifies which account receives inflation payouts on behalf of this account. Note: Inflation is deprecated and no longer active on the Stellar network. See Stellar developer docs
Declaration
Swift
public class AccountInflationDestinationUpdatedEffectResponse : EffectResponse, @unchecked Sendable -
Represents an account removal effect. This effect occurs when an account is merged into another account through an Account Merge operation. The account’s remaining balance is transferred to the destination account, and the source account is removed from the ledger. See Stellar developer docs
Declaration
Swift
public class AccountRemovedEffectResponse : EffectResponse, @unchecked Sendable -
Represents an account sponsorship creation effect. This effect occurs when an account’s reserves begin being sponsored by another account. Sponsorship allows one account to pay the base reserve for another account’s existence. Triggered by the Begin Sponsoring Future Reserves and End Sponsoring Future Reserves operations. See Stellar developer docs
See moreDeclaration
Swift
public class AccountSponsorshipCreatedEffectResponse : EffectResponse, @unchecked Sendable -
Represents an account sponsorship removal effect. This effect occurs when sponsorship for an account’s base reserve is revoked. The account becomes responsible for paying its own base reserve. Triggered by the Revoke Sponsorship operation. See Stellar developer docs
See moreDeclaration
Swift
public class AccountSponsorshipRemovedEffectResponse : EffectResponse, @unchecked Sendable -
Represents an account sponsorship update effect. This effect occurs when the sponsoring account for an account’s base reserve changes. The sponsorship is transferred from one sponsor to another. Triggered by the Revoke Sponsorship operation. See Stellar developer docs
See moreDeclaration
Swift
public class AccountSponsorshipUpdatedEffectResponse : EffectResponse, @unchecked Sendable -
Represents an account thresholds update effect. This effect occurs when an account’s signature thresholds are modified through a Set Options operation. Thresholds determine the minimum signature weight required for different operation categories. See Stellar developer docs
See moreDeclaration
Swift
public class AccountThresholdsUpdatedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a claimable balance claimant creation effect. This effect occurs for each claimant specified when a claimable balance is created. It includes the predicate conditions that must be met for the claimant to claim the balance. Triggered by the Create Claimable Balance operation. See Stellar developer docs
See moreDeclaration
Swift
public class ClaimableBalanceClaimantCreatedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a claimable balance claimed effect. This effect occurs when a claimable balance is successfully claimed by an eligible claimant. The balance is transferred to the claimant’s account and removed from the ledger. Triggered by the Claim Claimable Balance operation. See Stellar developer docs
See moreDeclaration
Swift
public class ClaimableBalanceClaimedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a claimable balance clawback effect. This effect occurs when an asset issuer claws back a claimable balance of their asset. Clawback allows issuers to revoke assets they have issued. Triggered by the Clawback Claimable Balance operation. See Stellar developer docs
See moreDeclaration
Swift
public class ClaimableBalanceClawedBackEffectResponse : EffectResponse, @unchecked Sendable -
Represents a claimable balance creation effect. This effect occurs when a new claimable balance is created on the ledger. Claimable balances allow an account to set aside funds to be claimed by specific recipients at a later time. Triggered by the Create Claimable Balance operation. See Stellar developer docs
See moreDeclaration
Swift
public class ClaimableBalanceCreatedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a claimable balance sponsorship creation effect. This effect occurs when a claimable balance’s reserve requirement begins being sponsored by another account. Sponsorship allows one account to pay the base reserve for a claimable balance. Triggered by the Begin Sponsoring Future Reserves and End Sponsoring Future Reserves operations. See Stellar developer docs
See moreDeclaration
Swift
public class ClaimableBalanceSponsorshipCreatedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a claimable balance sponsorship removal effect. This effect occurs when sponsorship for a claimable balance’s base reserve is revoked. The claimable balance creator becomes responsible for paying the base reserve. Triggered by the Revoke Sponsorship operation. See Stellar developer docs
See moreDeclaration
Swift
public class ClaimableBalanceSponsorshipRemovedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a claimable balance sponsorship update effect. This effect occurs when the sponsoring account for a claimable balance’s base reserve changes. The sponsorship is transferred from one sponsor to another. Triggered by the Revoke Sponsorship operation. See Stellar developer docs
See moreDeclaration
Swift
public class ClaimableBalanceSponsorshipUpdatedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a contract credit effect. This effect occurs when a Soroban smart contract receives an asset transfer. Contracts can hold and manage Stellar assets as part of their execution. Triggered by Invoke Host Function operations that transfer assets to contracts. See Stellar developer docs
See moreDeclaration
Swift
public class ContractCreditedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a contract debit effect. This effect occurs when a Soroban smart contract sends an asset transfer. Contracts can hold and manage Stellar assets as part of their execution. Triggered by Invoke Host Function operations that transfer assets from contracts. See Stellar developer docs
See moreDeclaration
Swift
public class ContractDebitedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a data entry creation effect. This effect occurs when a new key-value pair is added to an account’s data entries. Account data entries allow accounts to store arbitrary data on the ledger. Triggered by the Manage Data operation. See Stellar developer docs
See moreDeclaration
Swift
public class DataCreatedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a data entry removal effect. This effect occurs when a key-value pair is deleted from an account’s data entries. Account data entries allow accounts to store arbitrary data on the ledger. Triggered by the Manage Data operation with a null value. See Stellar developer docs
See moreDeclaration
Swift
public class DataRemovedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a data entry sponsorship creation effect. This effect occurs when a data entry’s reserve requirement begins being sponsored by another account. Sponsorship allows one account to pay the base reserve for another account’s data entry. Triggered by the Begin Sponsoring Future Reserves and End Sponsoring Future Reserves operations. See Stellar developer docs
See moreDeclaration
Swift
public class DataSponsorshipCreatedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a data entry sponsorship removal effect. This effect occurs when sponsorship for a data entry’s base reserve is revoked. The account becomes responsible for paying the data entry’s base reserve. Triggered by the Revoke Sponsorship operation. See Stellar developer docs
See moreDeclaration
Swift
public class DataSponsorshipRemovedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a data entry sponsorship update effect. This effect occurs when the sponsoring account for a data entry’s base reserve changes. The sponsorship is transferred from one sponsor to another. Triggered by the Revoke Sponsorship operation. See Stellar developer docs
See moreDeclaration
Swift
public class DataSponsorshipUpdatedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a data entry update effect. This effect occurs when an existing key-value pair in an account’s data entries is modified. Account data entries allow accounts to store arbitrary data on the ledger. Triggered by the Manage Data operation. See Stellar developer docs
See moreDeclaration
Swift
public class DataUpdatedEffectResponse : EffectResponse, @unchecked Sendable -
Base class for all effect responses from the Horizon API. Effects represent specific changes that occur to the ledger as a result of operations in successfully submitted transactions. Each operation can produce multiple effects, and this class provides common properties shared by all effect types. See Stellar developer docs
See moreDeclaration
Swift
public class EffectResponse : Decodable, @unchecked Sendable -
Represents a liquidity pool creation effect. This effect occurs when a new liquidity pool is created on the Stellar network. Liquidity pools enable automated market making for asset pairs on the decentralized exchange. Triggered by the Change Trust operation with a liquidity pool asset. See Stellar developer docs
See moreDeclaration
Swift
public class LiquidityPoolCreatedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a liquidity pool deposit effect. This effect occurs when an account deposits assets into a liquidity pool. The account receives pool shares in exchange for the deposited assets. Triggered by the Liquidity Pool Deposit operation. See Stellar developer docs
See moreDeclaration
Swift
public class LiquidityPoolDepositedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a liquidity pool removal effect. This effect occurs when a liquidity pool is removed from the ledger. A pool is removed when all shares have been withdrawn and no reserves remain. Triggered by the Change Trust operation with limit set to zero. See Stellar developer docs
See moreDeclaration
Swift
public class LiquidityPoolRemovedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a liquidity pool revocation effect. This effect occurs when trustline authorization for a liquidity pool is revoked by an asset issuer. The pool shares are revoked and the reserves are returned. Triggered by the Set Trust Line Flags or Allow Trust operations. See Stellar developer docs
See moreDeclaration
Swift
public class LiquidityPoolRevokedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a liquidity pool trade effect. This effect occurs when a trade is executed against a liquidity pool. The pool automatically provides liquidity for the trade based on its constant product formula. Triggered by Path Payment operations or trades that match against the pool. See Stellar developer docs
See moreDeclaration
Swift
public class LiquidityPoolTradeEffectResponse : EffectResponse, @unchecked Sendable -
Represents a liquidity pool withdrawal effect. This effect occurs when an account withdraws assets from a liquidity pool. The account redeems pool shares in exchange for a proportional amount of the pool’s reserves. Triggered by the Liquidity Pool Withdraw operation. See Stellar developer docs
See moreDeclaration
Swift
public class LiquidityPoolWithdrewEffectResponse : EffectResponse, @unchecked Sendable -
Represents an offer creation effect. This effect occurs when a new offer to buy or sell assets is created on the Stellar decentralized exchange (DEX). Triggered by the Manage Sell Offer, Manage Buy Offer, or Create Passive Sell Offer operations. See Stellar developer docs
Declaration
Swift
public class OfferCreatedEffectResponse : EffectResponse, @unchecked Sendable -
Represents an offer removal effect. This effect occurs when an existing offer is cancelled or fully filled on the Stellar decentralized exchange (DEX). Triggered by the Manage Sell Offer or Manage Buy Offer operations, or when an offer is completely matched. See Stellar developer docs
Declaration
Swift
public class OfferRemovedEffectResponse : EffectResponse, @unchecked Sendable -
Represents an offer update effect. This effect occurs when an existing offer is modified or partially filled on the Stellar decentralized exchange (DEX). Triggered by the Manage Sell Offer or Manage Buy Offer operations, or when an offer is partially matched. See Stellar developer docs
Declaration
Swift
public class OfferUpdatedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a sequence number bump effect. This effect occurs when an account’s sequence number is manually bumped to a higher value. Triggered by the Bump Sequence operation, which can be used to invalidate future transactions or implement time bounds. See Stellar developer docs
See moreDeclaration
Swift
public class SequenceBumpedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a signer creation effect. This effect occurs when a new signer is added to an account through a Set Options operation. The new signer can be used for multi-signature authorization of transactions. See Stellar developer docs
Declaration
Swift
public class SignerCreatedEffectResponse : SignerEffectResponse, @unchecked Sendable -
Base class for signer effect responses. Represents changes to account signers, including creation, updates, and removal. Signers allow an account to be controlled by multiple keys with configurable weights. Triggered by the Set Options operation. See Stellar developer docs
See moreDeclaration
Swift
public class SignerEffectResponse : EffectResponse, @unchecked Sendable -
Represents a signer removal effect. This effect occurs when a signer is removed from an account through a Set Options operation. The removed signer can no longer authorize transactions for the account. See Stellar developer docs
Declaration
Swift
public class SignerRemovedEffectResponse : SignerEffectResponse, @unchecked Sendable -
Represents a signer sponsorship creation effect. This effect occurs when a signer’s reserve requirement begins being sponsored by another account. Sponsorship allows one account to pay the base reserve for another account’s signer. Triggered by the Begin Sponsoring Future Reserves and End Sponsoring Future Reserves operations. See Stellar developer docs
See moreDeclaration
Swift
public class SignerSponsorshipCreatedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a signer sponsorship removal effect. This effect occurs when sponsorship for a signer’s base reserve is revoked. The account becomes responsible for paying the signer’s base reserve. Triggered by the Revoke Sponsorship operation. See Stellar developer docs
See moreDeclaration
Swift
public class SignerSponsorshipRemovedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a signer sponsorship update effect. This effect occurs when the sponsoring account for a signer’s base reserve changes. The sponsorship is transferred from one sponsor to another. Triggered by the Revoke Sponsorship operation. See Stellar developer docs
See moreDeclaration
Swift
public class SignerSponsorshipUpdatedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a signer update effect. This effect occurs when an existing signer’s weight is modified through a Set Options operation. Changing a signer’s weight affects the multi-signature authorization requirements. See Stellar developer docs
Declaration
Swift
public class SignerUpdatedEffectResponse : SignerEffectResponse, @unchecked Sendable -
Represents a trade effect. This effect occurs when a trade is executed on the Stellar decentralized exchange (DEX). Triggered when offers are matched through Manage Sell Offer, Manage Buy Offer, or Path Payment operations. See Stellar developer docs
See moreDeclaration
Swift
public class TradeEffectResponse : EffectResponse, @unchecked Sendable -
Represents a trustline flags update effect. This effect occurs when an asset issuer modifies the authorization flags for a trustline through a Set Trust Line Flags operation. Flags control authorization status, liability maintenance, and clawback capabilities. See Stellar developer docs
See moreDeclaration
Swift
public class TrustLineFlagsUpdatedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a trustline authorization effect. This effect occurs when an asset issuer authorizes another account to hold its asset through an Allow Trust or Set Trust Line Flags operation. Required when the issuer has the AUTH_REQUIRED flag set. See Stellar developer docs
Declaration
Swift
public class TrustlineAuthorizedEffectResponse : TrustlineEffectResponse, @unchecked Sendable -
Represents a trustline authorized to maintain liabilities effect. This effect occurs when an asset issuer sets a trustline to maintain liabilities only through an Allow Trust or Set Trust Line Flags operation. The account can maintain existing offers and outstanding liabilities but cannot receive new assets. See Stellar developer docs
Declaration
Swift
public class TrustlineAuthorizedToMaintainLiabilitiesEffecResponse : TrustlineEffectResponse, @unchecked Sendable -
Represents a trustline creation effect. This effect occurs when an account establishes a new trustline to an asset through a Change Trust operation. Trustlines are required to hold and trade non-native assets on the Stellar network. See Stellar developer docs
Declaration
Swift
public class TrustlineCreatedEffectResponse : TrustlineEffectResponse, @unchecked Sendable -
Represents a trustline deauthorization effect. This effect occurs when an asset issuer revokes authorization for another account to hold its asset through an Allow Trust or Set Trust Line Flags operation. The account can no longer receive or send the asset. See Stellar developer docs
Declaration
Swift
public class TrustlineDeauthorizedEffectResponse : TrustlineEffectResponse, @unchecked Sendable -
Base class for trustline effect responses. Represents changes to account trustlines, which enable accounts to hold and trade non-native assets. Trustlines are established through Change Trust operations and can be authorized or modified by asset issuers. See Stellar developer docs
See moreDeclaration
Swift
public class TrustlineEffectResponse : EffectResponse, @unchecked Sendable -
Represents a trustline removal effect. This effect occurs when an account removes a trustline to an asset through a Change Trust operation with limit set to zero. The account must have a zero balance of the asset before the trustline can be removed. See Stellar developer docs
Declaration
Swift
public class TrustlineRemovedEffectResponse : TrustlineEffectResponse, @unchecked Sendable -
Represents a trustline sponsorship creation effect. This effect occurs when a trustline’s reserve requirement begins being sponsored by another account. Sponsorship allows one account to pay the base reserve for another account’s trustline. Triggered by the Begin Sponsoring Future Reserves and End Sponsoring Future Reserves operations. See Stellar developer docs
See moreDeclaration
Swift
public class TrustlineSponsorshipCreatedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a trustline sponsorship removal effect. This effect occurs when sponsorship for a trustline’s base reserve is revoked. The account becomes responsible for paying the trustline’s base reserve. Triggered by the Revoke Sponsorship operation. See Stellar developer docs
See moreDeclaration
Swift
public class TrustlineSponsorshipRemovedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a trustline sponsorship update effect. This effect occurs when the sponsoring account for a trustline’s base reserve changes. The sponsorship is transferred from one sponsor to another. Triggered by the Revoke Sponsorship operation. See Stellar developer docs
See moreDeclaration
Swift
public class TrustlineSponsorshipUpdatedEffectResponse : EffectResponse, @unchecked Sendable -
Represents a trustline update effect. This effect occurs when an existing trustline’s limit is modified through a Change Trust operation. The account can increase or decrease the maximum amount of the asset it is willing to hold. See Stellar developer docs
Declaration
Swift
public class TrustlineUpdatedEffectResponse : TrustlineEffectResponse, @unchecked Sendable -
HTTP 400 Bad Request error from Horizon indicating malformed request parameters.
This error occurs when:
- Invalid or missing required parameters
- Malformed transaction XDR
- Invalid asset codes, account IDs, or other identifiers
- Transaction validation failures before submission
Check the detail field for specific information about what was invalid.
See also:
- Stellar developer docs
- ErrorResponse for common error properties
Declaration
Swift
public class BadRequestErrorResponse : ErrorResponse, @unchecked Sendable -
HTTP 410 Before History error from Horizon indicating requested data predates available history.
This error occurs when:
- Requested ledger sequence is before Horizon’s earliest retained ledger
- Historical data has been pruned from the database
- Cursor points to data that is no longer available
Horizon servers retain limited historical data. Query more recent ledgers or use a Horizon server with longer history retention.
See also:
- Stellar developer docs
- ErrorResponse for common error properties
Declaration
Swift
public class BeforeHistoryErrorResponse : ErrorResponse, @unchecked Sendable -
HTTP 409 Duplicate error from Horizon indicating the transaction was already submitted.
This error occurs when:
- Transaction with the same hash was already submitted and processed
- Duplicate transaction submission attempt detected
- Transaction is already in the pending queue
This typically happens with async transaction submission when the same transaction is submitted multiple times. Check the transaction status rather than resubmitting.
See also:
- Stellar developer docs
- ErrorResponse for common error properties
Declaration
Swift
public class DuplicateErrorResponse : ErrorResponse, @unchecked Sendable -
Represents an error response from the Horizon API.
When a request fails, Horizon returns an error response with details about what went wrong. Error responses include HTTP status codes, error types, descriptions, and additional debugging information in the extras field.
Common error types:
- 400 Bad Request: Invalid parameters or malformed request
- 404 Not Found: Resource doesn’t exist
- 429 Rate Limit Exceeded: Too many requests
- 500 Internal Server Error: Server-side problem
Example usage:
let response = await sdk.transactions.submitTransaction(transaction: tx) switch response { case .success(let result): print("Success: \(result.hash)") case .failure(let error): if case .badRequest(_, let horizonError) = error, let errorResponse = horizonError { print("Error: \(errorResponse.title)") print("Detail: \(errorResponse.detail)") // Check for transaction-specific errors if let extras = errorResponse.extras, let resultCodes = extras.resultCodes { print("Transaction result: \(resultCodes.transaction ?? "")") print("Operation results: \(resultCodes.operations ?? [])") } } }See also:
- Stellar developer docs
- HorizonRequestError for error enum types
Declaration
Swift
public class ErrorResponse : Decodable, @unchecked Sendable -
Additional error information for transaction submission failures.
Contains transaction-specific debugging data including XDR representations and result codes from Stellar Core.
See moreDeclaration
Swift
public final class ErrorResponseExtras : Decodable, Sendable -
Result codes explaining transaction and operation failures.
Contains error codes from Stellar Core indicating why a transaction failed. Transaction result codes apply to the whole transaction, while operation result codes indicate which specific operations failed and why.
Common transaction results:
- tx_failed: One or more operations failed
- tx_bad_seq: Incorrect sequence number
- tx_insufficient_balance: Not enough XLM to pay fee
Declaration
Swift
public final class ErrorResultCodes : Decodable, Sendable -
HTTP 504 Gateway Timeout error from Horizon indicating the request took too long to process.
This error occurs when:
- Request processing exceeded Horizon’s configured timeout
- Stellar Core took too long to respond
- Database query exceeded time limits
- Network congestion or connectivity issues
Retry the request after a delay. For complex queries, consider narrowing the scope or using pagination to reduce processing time.
See also:
- Stellar developer docs
- ErrorResponse for common error properties
Declaration
Swift
public class TimeoutErrorResponse : ErrorResponse, @unchecked Sendable -
HTTP 403 Forbidden error from Horizon indicating access to the resource is denied.
This error occurs when:
- Authentication required but not provided
- Invalid or expired authentication credentials
- Insufficient permissions for the requested operation
- IP-based access restrictions
Contact the Horizon server administrator if you believe access should be granted.
See also:
- Stellar developer docs
- ErrorResponse for common error properties
Declaration
Swift
public class ForbiddenErrorResponse : ErrorResponse, @unchecked Sendable -
HTTP 500 Internal Server Error from Horizon indicating an unexpected server-side problem.
This error occurs when:
- Horizon encounters an unexpected internal error
- Database connection failures
- Stellar Core connection issues
- Unhandled exceptions on the server
These errors are typically transient. Retry the request after a delay. If errors persist, check Horizon server status or contact administrators.
See also:
- Stellar developer docs
- ErrorResponse for common error properties
Declaration
Swift
public class InternalServerErrorResponse : ErrorResponse, @unchecked Sendable -
HTTP 406 Not Acceptable error from Horizon indicating unsupported response format requested.
This error occurs when:
- Requested content type via Accept header is not supported by Horizon
- Invalid or missing Accept header
- Horizon cannot generate response in the requested format
Horizon supports JSON responses. Ensure Accept header is set to application/json or omitted.
See also:
- Stellar developer docs
- ErrorResponse for common error properties
Declaration
Swift
public class NotAcceptableErrorResponse : ErrorResponse, @unchecked Sendable -
HTTP 404 Not Found error from Horizon indicating the requested resource does not exist.
This error occurs when:
- Account ID not found on the network
- Transaction hash does not exist
- Ledger sequence not available
- Data entry key not found for account
- Invalid or non-existent resource identifier
Verify the resource identifier is correct and that the resource exists on the network.
See also:
- Stellar developer docs
- ErrorResponse for common error properties
Declaration
Swift
public class NotFoundErrorResponse : ErrorResponse, @unchecked Sendable -
HTTP 501 Not Implemented error from Horizon indicating unsupported functionality.
This error occurs when:
- Requested feature is not yet implemented in this Horizon version
- API endpoint exists but functionality is disabled
- Requested operation is not supported by the server configuration
Check Horizon version and configuration, or use an alternative approach.
See also:
- Stellar developer docs
- ErrorResponse for common error properties
Declaration
Swift
public class NotImplementedErrorResponse : ErrorResponse, @unchecked Sendable -
HTTP 413 Payload Too Large error from Horizon indicating request body exceeds size limits.
This error occurs when:
- Transaction XDR is too large
- Request body exceeds Horizon’s configured maximum size
- Batch request contains too many items
Reduce the size of the request by:
- Splitting large transactions into multiple smaller ones
- Reducing the number of operations per transaction
- Using pagination for large queries
See also:
- ErrorResponse for common error properties
Declaration
Swift
public class PayloadTooLargeErrorResponse : ErrorResponse, @unchecked Sendable -
HTTP 429 Rate Limit Exceeded error from Horizon indicating too many requests.
This error occurs when:
- Request rate exceeds the configured limit for the Horizon server
- Too many requests sent in a short time period
- Need to implement backoff and retry logic
Check response headers for rate limit information:
- X-RateLimit-Limit: Maximum requests per time window
- X-RateLimit-Remaining: Requests remaining in current window
- X-RateLimit-Reset: Time when rate limit resets
Implement exponential backoff when retrying after rate limit errors.
See also:
- Stellar developer docs
- ErrorResponse for common error properties
Declaration
Swift
public class RateLimitExceededErrorResponse : ErrorResponse, @unchecked Sendable -
HTTP 503 Stale History error from Horizon indicating the server is behind the network.
This error occurs when:
- Horizon’s database is not synced with the latest ledgers
- Ingestion from Stellar Core has fallen behind
- Server is catching up after maintenance or downtime
The Horizon server is temporarily unable to serve current data. Retry after a delay or use a different Horizon server that is in sync.
See also:
- Stellar developer docs
- ErrorResponse for common error properties
Declaration
Swift
public class StaleHistoryErrorResponse : ErrorResponse, @unchecked Sendable -
Represents an account created operation response. See Stellar developer docs
See moreDeclaration
Swift
public class AccountCreatedOperationResponse : OperationResponse, @unchecked Sendable -
Represents an account merge operation response. See Stellar developer docs
See moreDeclaration
Swift
public class AccountMergeOperationResponse : OperationResponse, @unchecked Sendable -
Represents an allow trust operation response. See Stellar developer docs
See moreDeclaration
Swift
public class AllowTrustOperationResponse : OperationResponse, @unchecked Sendable -
Represents a begin sponsoring future reserves operation response. This operation initiates sponsorship of reserves for another account, allowing the sponsor to pay for the reserve requirements of ledger entries created by the sponsored account. See Stellar developer docs
See moreDeclaration
Swift
public class BeginSponsoringFutureReservesOperationResponse : OperationResponse, @unchecked Sendable -
Represents a bump sequence operation response. This operation bumps forward the sequence number of the source account to the specified value, invalidating any lower sequence numbers for future transactions. See Stellar developer docs
See moreDeclaration
Swift
public class BumpSequenceOperationResponse : OperationResponse, @unchecked Sendable -
Represents a change trust operation response. See Stellar developer docs
See moreDeclaration
Swift
public class ChangeTrustOperationResponse : OperationResponse, @unchecked Sendable -
Represents a claim claimable balance operation response. This operation claims a claimable balance entry, transferring the asset amount to the claimant’s account. See Stellar developer docs
See moreDeclaration
Swift
public class ClaimClaimableBalanceOperationResponse : OperationResponse, @unchecked Sendable -
Represents a clawback claimable balance operation response. This operation claws back a claimable balance, returning the funds to the asset issuer. Only the asset issuer can perform this operation. See Stellar developer docs
See moreDeclaration
Swift
public class ClawbackClaimableBalanceOperationResponse : OperationResponse, @unchecked Sendable -
Represents a clawback operation response. This operation burns an amount of an asset from a holding account. The asset issuer must have the AUTH_CLAWBACK_ENABLED flag set on the asset. See Stellar developer docs
See moreDeclaration
Swift
public class ClawbackOperationResponse : OperationResponse, @unchecked Sendable -
Represents a create claimable balance operation response. This operation creates a claimable balance entry that can be claimed by specified claimants, enabling conditional payments on the Stellar network. See Stellar developer docs
See moreDeclaration
Swift
public class CreateClaimableBalanceOperationResponse : OperationResponse, @unchecked Sendable -
Represents a create passive operation response. See Stellar developer docs
See moreDeclaration
Swift
public class CreatePassiveOfferOperationResponse : OperationResponse, @unchecked Sendable -
Represents a create passive sell offer operation response. This operation creates a passive offer to sell an asset on the Stellar DEX that will only execute at or above a specified price. Passive offers will not immediately take existing offers. See Stellar developer docs
See moreDeclaration
Swift
public class CreatePassiveSellOfferOperationResponse : CreatePassiveOfferOperationResponse, @unchecked Sendable -
Represents an end sponsoring future reserves operation response. This operation terminates the current sponsorship relationship initiated by a begin sponsoring future reserves operation. See Stellar developer docs
See moreDeclaration
Swift
public class EndSponsoringFutureReservesOperationResponse : OperationResponse, @unchecked Sendable -
Represents an extend footprint TTL operation response. This Soroban operation extends the time-to-live (TTL) of ledger entries specified in the transaction’s footprint, preventing them from being archived. See Stellar developer docs
See moreDeclaration
Swift
public class ExtendFootprintTTLOperationResponse : OperationResponse, @unchecked Sendable -
Represents an inflation operation response. See Stellar developer docs
Declaration
Swift
public class InflationOperationResponse : OperationResponse, @unchecked Sendable -
Represents an invoke host function operation response. This Soroban operation invokes a smart contract function on the Stellar network. See Stellar developer docs
See moreDeclaration
Swift
public class InvokeHostFunctionOperationResponse : OperationResponse, @unchecked Sendable -
Represents a parameter passed to a Soroban contract function.
See moreDeclaration
Swift
public final class ParameterResponse : Decodable, Sendable -
Represents an asset balance change resulting from a Soroban contract invocation.
See moreDeclaration
Swift
public final class AssetBalanceChange : Decodable, Sendable -
Represents a liquidity pool deposit operation response. This operation deposits assets into a liquidity pool, providing liquidity to the pool in exchange for pool shares. See Stellar developer docs
See moreDeclaration
Swift
public class LiquidityPoolDepostOperationResponse : OperationResponse, @unchecked Sendable -
Represents a liquidity pool withdraw operation response. This operation withdraws assets from a liquidity pool by redeeming pool shares for the underlying reserve assets. See Stellar developer docs
See moreDeclaration
Swift
public class LiquidityPoolWithdrawOperationResponse : OperationResponse, @unchecked Sendable -
Represents a manage buy offer operation response. This operation creates, updates, or deletes a buy offer on the Stellar DEX, specifying the amount to buy rather than the amount to sell. See Stellar developer docs
See moreDeclaration
Swift
public class ManageBuyOfferOperationResponse : ManageOfferOperationResponse, @unchecked Sendable -
Represents a manage data operation response. See Stellar developer docs
See moreDeclaration
Swift
public class ManageDataOperationResponse : OperationResponse, @unchecked Sendable -
Represents a manage offer operation response. See Stellar developer docs
See moreDeclaration
Swift
public class ManageOfferOperationResponse : OperationResponse, @unchecked Sendable -
Represents a manage sell offer operation response. This operation creates, updates, or deletes a sell offer on the Stellar DEX, specifying the amount to sell rather than the amount to buy. See Stellar developer docs
See moreDeclaration
Swift
public class ManageSellOfferOperationResponse : ManageOfferOperationResponse, @unchecked Sendable -
Represents an operation response. Superclass for all other operation response classes. See Stellar developer docs
See moreDeclaration
Swift
public class OperationResponse : Decodable, @unchecked Sendable -
Represents a path payment operation response. See Stellar developer docs
See moreDeclaration
Swift
public class PathPaymentOperationResponse : OperationResponse, @unchecked Sendable -
Represents a path payment strict receive operation response. This operation sends a path payment where the destination amount is specified, and the source amount varies within a maximum limit. See Stellar developer docs
See moreDeclaration
Swift
public class PathPaymentStrictReceiveOperationResponse : PathPaymentOperationResponse, @unchecked Sendable -
Represents a path payment strict send operation response. This operation sends a path payment where the source amount is specified, and the destination amount varies within a minimum limit. See Stellar developer docs
See moreDeclaration
Swift
public class PathPaymentStrictSendOperationResponse : PathPaymentOperationResponse, @unchecked Sendable -
Represents a payment operation response. See Stellar developer docs
See moreDeclaration
Swift
public class PaymentOperationResponse : OperationResponse, @unchecked Sendable -
Represents a restore footprint operation response. This Soroban operation restores archived ledger entries specified in the transaction’s footprint, making them accessible again. See Stellar developer docs
See moreDeclaration
Swift
public class RestoreFootprintOperationResponse : OperationResponse, @unchecked Sendable -
Represents a revoke sponsorship operation response. This operation revokes sponsorship of a ledger entry or signer, transferring reserve responsibility back to the sponsored account. See Stellar developer docs
See moreDeclaration
Swift
public class RevokeSponsorshipOperationResponse : OperationResponse, @unchecked Sendable -
Represents a set options operation response. See Stellar developer docs
See moreDeclaration
Swift
public class SetOptionsOperationResponse : OperationResponse, @unchecked Sendable -
Represents a set trustline flags operation response. This operation allows an asset issuer to set or clear flags on a trustline, controlling authorization and clawback capabilities. See Stellar developer docs
See moreDeclaration
Swift
public class SetTrustLineFlagsOperationResponse : OperationResponse, @unchecked Sendable -
Represents an account in Stellar network with it’s sequence number.
See moreDeclaration
Swift
public class Account : TransactionAccount, @unchecked Sendable -
Represents an account merge operation. Transfers the native balance (the amount of XLM an account holds) to another account and removes the source account from the ledger. See Stellar developer docs
See moreDeclaration
Swift
public class AccountMergeOperation : Operation, @unchecked Sendable -
Represents an allow trust operation. Updates the authorized flag of an existing trustline. This can only be called by the issuer of a trustline’s asset. The issuer can only clear the authorized flag if the issuer has the AUTH_REVOCABLE_FLAG set. Otherwise, the issuer can only set the authorized flag. See Stellar developer docs
See moreDeclaration
Swift
public class AllowTrustOperation : Operation, @unchecked Sendable -
Base Asset class. See Stellar developer docs
See moreDeclaration
Swift
public class Asset : @unchecked Sendable -
Establishes the is-sponsoring-future-reserves-for relationship between the source account and sponsoredID. See Stellar developer docs.
See moreDeclaration
Swift
public class BeginSponsoringFutureReservesOperation : Operation, @unchecked Sendable -
Represents a change trust operation. Creates, updates, or deletes a trustline. See Stellar developer docs
See moreDeclaration
Swift
public class ChangeTrustOperation : Operation, @unchecked Sendable -
Represents a claim claimable balance operation. Claimable Balances can be used to “split up” a payment into two parts, which allows the sending to only depend on the sending account, and the receipt to only depend on the receiving account. See Stellar developer docs.
See moreDeclaration
Swift
public class ClaimClaimableBalanceOperation : Operation, @unchecked Sendable -
Represents a claimant authorized to claim a claimable balance with optional predicates.
See moreDeclaration
Swift
public final class Claimant : Sendable -
Represents a create account operation that creates and funds a new account.
CreateAccountOperation creates a new account on the Stellar network and funds it with an initial balance of native XLM. The new account must not already exist on the network, and the starting balance must meet the minimum account reserve requirement.
The minimum starting balance is determined by the network’s base reserve (currently 0.5 XLM) multiplied by 2 (one for the account, one for the native balance). Additional reserves are required for each trustline, offer, signer, or data entry added to the account.
The operation will fail if:
- The destination account already exists
- The starting balance is below the minimum reserve requirement
- The source account has insufficient XLM balance
- The destination account ID is invalid
Example:
// Create and fund a new account with 10 XLM let newKeyPair = try KeyPair.generateRandomKeyPair() let createAccount = CreateAccountOperation( sourceAccountId: nil, destination: newKeyPair, startBalance: 10.0 ) // Or using an existing account ID let createAccount2 = try CreateAccountOperation( sourceAccountId: nil, destinationAccountId: "GNEW...", startBalance: 10.0 )See also:
See moreDeclaration
Swift
public class CreateAccountOperation : Operation, @unchecked Sendable -
Represents a create claimable balance operation. Claimable Balances can be used to “split up” a payment into two parts, which allows the sending to only depend on the sending account, and the receipt to only depend on the receiving account. See Stellar developer docs.
See moreDeclaration
Swift
public class CreateClaimableBalanceOperation : Operation, @unchecked Sendable -
Represents a create passive offer operation. A passive offer is an offer that does not act on and take a reverse offer of equal price. Instead, they only take offers of lesser price. See Stellar developer docs
See moreDeclaration
Swift
public class CreatePassiveOfferOperation : Operation, @unchecked Sendable -
Represents a Stellar passive sell offer operation that creates offers without taking existing offers.
Declaration
Swift
public class CreatePassiveSellOfferOperation : CreatePassiveOfferOperation, @unchecked Sendable -
Terminates the current is-sponsoring-future-reserves-for relationship in which the source account is sponsored. See Stellar developer docs.
See moreDeclaration
Swift
public class EndSponsoringFutureReservesOperation : Operation, @unchecked Sendable -
Represents a Fee Bump Transaction in Stellar network. See https://github.com/stellar/stellar-protocol/blob/master/core/cap-0015.md
See moreDeclaration
Swift
public class FeeBumpTransaction : @unchecked Sendable -
Declaration
Swift
final public class LedgerBounds : Sendable -
Represents a Stellar manage buy offer operation creating or modifying offers with fixed buy amounts.
See moreDeclaration
Swift
public class ManageBuyOfferOperation : ManageOfferOperation, @unchecked Sendable -
Represents an manage data operation. Allows you to set,modify or delete a Data Entry (name/value pair) that is attached to a particular account. An account can have an arbitrary amount of DataEntries attached to it. Each DataEntry increases the minimum balance needed to be held by the account. See Stellar developer docs
See moreDeclaration
Swift
public class ManageDataOperation : Operation, @unchecked Sendable -
Represents a manage offer operation. Creates, updates, or deletes an offer. See Stellar developer docs
See moreDeclaration
Swift
public class ManageOfferOperation : Operation, @unchecked Sendable -
Represents a Stellar manage sell offer operation creating or modifying offers with fixed sell amounts.
See moreDeclaration
Swift
public class ManageSellOfferOperation : ManageOfferOperation, @unchecked Sendable -
Declaration
Swift
public class MuxedAccount : Account, @unchecked Sendable -
Base class for all Stellar operations.
Operations are the building blocks of Stellar transactions. Each operation represents a specific action on the Stellar network such as sending payments, creating accounts, or managing offers. Operations are grouped into transactions and submitted to the network.
You should never instantiate this class directly. Instead, use one of its subclasses that represent specific operation types. Each operation can optionally specify a source account that differs from the transaction’s source account.
Common operation types:
- PaymentOperation: Send assets between accounts
- CreateAccountOperation: Create and fund new accounts
- ChangeTrustOperation: Establish trustlines for assets
- ManageSellOfferOperation: Create or modify sell offers
- ManageBuyOfferOperation: Create or modify buy offers
- SetOptionsOperation: Configure account settings
- And many more…
Operation-level source accounts: When an operation specifies a source account, that account will be used as the source for that specific operation instead of the transaction’s source account. This is useful for multi-signature transactions or channel accounts.
Example:
// Payment operation using transaction source account let payment1 = try PaymentOperation( sourceAccountId: nil, destinationAccountId: "GDEST...", asset: Asset(type: AssetType.ASSET_TYPE_NATIVE), amount: 100.0 ) // Payment operation using different source account let payment2 = try PaymentOperation( sourceAccountId: "GSOURCE...", destinationAccountId: "GDEST...", asset: Asset(type: AssetType.ASSET_TYPE_NATIVE), amount: 50.0 )See also:
See moreDeclaration
Swift
public class Operation : @unchecked Sendable -
Represents a path payment operation. Sends an amount in a specific asset to a destination account through a path of offers. This allows the asset sent (e.g., 450 XLM) to be different from the asset received (e.g, 6 BTC). See Stellar developer docs
See moreDeclaration
Swift
public class PathPaymentOperation : Operation, @unchecked Sendable -
Represents a Stellar path payment operation guaranteeing exact destination amount received.
See moreDeclaration
Swift
public class PathPaymentStrictReceiveOperation : PathPaymentOperation, @unchecked Sendable -
Represents a Stellar path payment operation guaranteeing exact source amount sent.
See moreDeclaration
Swift
public class PathPaymentStrictSendOperation : PathPaymentOperation, @unchecked Sendable -
Represents a payment operation that sends an asset from one account to another.
PaymentOperation is one of the most common operations on the Stellar network. It sends a specified amount of an asset (native XLM or issued assets) from the source account to a destination account. The destination account must already exist and, for non-native assets, must have a trustline established for that asset.
The payment operation will fail if:
- The destination account does not exist
- The destination lacks a trustline for non-native assets
- The source account has insufficient balance
- The destination account would exceed asset limits
- The asset issuer has authorization controls that prevent the transfer
Example:
// Send 100 XLM let payment = try PaymentOperation( sourceAccountId: nil, destinationAccountId: "GDEST...", asset: Asset(type: AssetType.ASSET_TYPE_NATIVE), amount: 100.0 ) // Send 50 USD (issued asset) let usd = Asset(type: AssetType.ASSET_TYPE_CREDIT_ALPHANUM4, code: "USD", issuer: "GISSUER...")! let usdPayment = try PaymentOperation( sourceAccountId: nil, destinationAccountId: "GDEST...", asset: usd, amount: 50.0 )See also:
See moreDeclaration
Swift
public class PaymentOperation : Operation, @unchecked Sendable -
Represents Price. Price in Stellar is represented as a fraction.
See moreDeclaration
Swift
public final class Price : Decodable, Sendableextension Price: Equatable -
The logic of this operation depends on the state of the source account. If the source account is not sponsored or is sponsored by the owner of the specified entry or sub-entry, then attempt to revoke the sponsorship. If the source account is sponsored, the next step depends on whether the entry is sponsored or not. If it is sponsored, attempt to transfer the sponsorship to the sponsor of the source account. If the entry is not sponsored, then establish the sponsorship. See Stellar developer docs.
See moreDeclaration
Swift
public class RevokeSponsorshipOperation : Operation, @unchecked Sendable -
Represents a set options operation. This operation sets the options for an account. See Stellar developer docs
See moreDeclaration
Swift
public class SetOptionsOperation : Operation, @unchecked Sendable -
Utility class for creating signer keys used in multi-signature account configurations. Supports ED25519 public keys, SHA256 hashes, pre-authorized transactions, and signed payloads.
See moreDeclaration
Swift
public final class Signer : Sendable -
TimeBounds represents the time interval that a transaction is valid.
See moreDeclaration
Swift
final public class TimeBounds : Sendable -
Represents a Transaction in Stellar network. See Stellar developer docs
See moreDeclaration
Swift
public class Transaction : @unchecked Sendable -
Declaration
Swift
final public class TransactionPreconditions : 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:
- Stellar developer docs
- AccountResponse for the account data structure
Declaration
Swift
open class AccountService : @unchecked Sendable -
Service for querying asset information from the Stellar Horizon API.
The AssetsService provides methods to retrieve information about all assets issued on the Stellar network, including supply statistics, number of accounts, and issuer details. Can filter by asset code and issuer.
Example usage:
let sdk = StellarSDK() // Get all assets with code "USD" let response = await sdk.assets.getAssets( for: "USD", limit: 100 ) switch response { case .success(let page): for asset in page.records { print("\(asset.assetCode): \(asset.assetIssuer)") print("Accounts: \(asset.numAccounts)") print("Amount: \(asset.amount)") } case .failure(let error): print("Error: \(error)") }See also:
- Stellar developer docs
- AssetResponse for asset data structure
Declaration
Swift
public class AssetsService : @unchecked Sendable -
Service for querying claimable balances from the Stellar Horizon API.
Claimable balances allow creating asset transfers that recipients can claim later when specific conditions are met. Useful for implementing payment channels, escrow, and conditional transfers.
Example usage:
let sdk = StellarSDK() // Get claimable balance details let response = await sdk.claimableBalances.getClaimableBalanceDetails( claimableBalanceId: "00000000..." ) switch response { case .success(let balance): print("Amount: \(balance.amount)") print("Asset: \(balance.asset)") for claimant in balance.claimants { print("Claimant: \(claimant.destination)") } case .failure(let error): print("Error: \(error)") }See also:
- Stellar developer docs
- CreateClaimableBalanceOperation for creating claimable balances
Declaration
Swift
public class ClaimableBalancesService : @unchecked Sendable -
Service for querying effects from the Stellar Horizon API.
Effects represent specific changes to the ledger caused by operations. Each operation produces one or more effects. Examples include account created, account credited, trustline created, signer added, etc.
Example usage:
let sdk = StellarSDK() // Get effects for an account let response = await sdk.effects.getEffects( forAccount: "GACCOUNT...", limit: 20 ) switch response { case .success(let page): for effect in page.records { print("Effect type: \(effect.effectType)") if let credited = effect as? AccountCreditedEffectResponse { print("Credited: \(credited.amount)") } } case .failure(let error): print("Error: \(error)") }See also:
- Stellar developer docs
- EffectResponse for effect data structures
Declaration
Swift
public class EffectsService : @unchecked Sendable -
Service for querying network fee statistics from the Stellar Horizon API.
Provides current fee statistics including min, mode, and percentile fees from recent ledgers. Use this to determine appropriate fee levels for transaction submission.
Example usage:
let sdk = StellarSDK() let response = await sdk.feeStats.getFeeStats() switch response { case .success(let feeStats): print("Min fee: \(feeStats.minAcceptedFee)") print("Mode fee: \(feeStats.modeAcceptedFee)") print("P90 fee: \(feeStats.feeCharged.p90)") case .failure(let error): print("Error: \(error)") }See also:
See moreDeclaration
Swift
open class FeeStatsService : @unchecked Sendable -
Service for checking Horizon server health status.
The health endpoint provides information about the Horizon server’s operational status, including database connectivity and Stellar Core synchronization. Useful for monitoring and determining if the server is ready to handle requests.
Example usage:
let sdk = StellarSDK() let response = await sdk.health.getHealthCheck() switch response { case .success(let health): print("Status: \(health.status)") case .failure(let error): print("Health check failed: \(error)") }See also:
See moreDeclaration
Swift
open class HealthService : @unchecked Sendable -
Service for querying ledger information from the Stellar Horizon API.
Ledgers represent the state of the Stellar network at a specific point in time. Each ledger contains all transactions and operations that occurred, along with metadata like fees, transaction count, and protocol version.
Example usage:
let sdk = StellarSDK() // Get details for a specific ledger let response = await sdk.ledgers.getLedgerDetails(sequence: "12345") switch response { case .success(let ledger): print("Transaction count: \(ledger.transactionCount)") print("Closed at: \(ledger.closedAt)") case .failure(let error): print("Error: \(error)") }See also:
See moreDeclaration
Swift
public class LedgersService : @unchecked Sendable -
Service for querying liquidity pools from the Stellar Horizon API.
Liquidity pools enable automated market making (AMM) on Stellar. Each pool contains reserves of two assets and allows swapping between them at algorithmically determined prices.
Example usage:
let sdk = StellarSDK() // Get liquidity pool details let response = await sdk.liquidityPools.getLiquidityPoolDetails( liquidityPoolId: "L..." ) switch response { case .success(let pool): print("Total shares: \(pool.totalShares)") for reserve in pool.reserves { print("\(reserve.asset): \(reserve.amount)") } case .failure(let error): print("Error: \(error)") }See also:
- Stellar developer docs
- LiquidityPoolDepositOperation and LiquidityPoolWithdrawOperation
Declaration
Swift
public class LiquidityPoolsService : @unchecked Sendable -
Service for querying offer information from the Stellar Horizon API.
Offers represent open orders on the Stellar decentralized exchange (DEX). Each offer specifies an amount and price to buy or sell an asset. Can query offers by account, asset pair, or sponsor.
Example usage:
let sdk = StellarSDK() // Get all offers for an account let response = await sdk.offers.getOffers(forAccount: "GACCOUNT...") switch response { case .success(let page): for offer in page.records { print("Selling: \(offer.amount) \(offer.selling.assetCode ?? "XLM")") print("Buying: \(offer.buying.assetCode ?? "XLM")") print("Price: \(offer.price)") } case .failure(let error): print("Error: \(error)") }See also:
- Stellar developer docs
- OrderbookService for orderbook snapshots
Declaration
Swift
public class OffersService : @unchecked Sendable -
Service for querying operation history from the Stellar Horizon API.
The OperationsService provides methods to retrieve operations (individual actions within transactions) filtered by account, ledger, transaction, claimable balance, or liquidity pool. Supports pagination and streaming of real-time operation updates.
Example usage:
let sdk = StellarSDK() // Get operations for an account let response = await sdk.operations.getOperations( forAccount: "GACCOUNT...", limit: 20, order: .descending ) switch response { case .success(let page): for operation in page.records { print("Type: \(operation.operationType)") } case .failure(let error): print("Error: \(error)") }See also:
- Stellar developer docs
- OperationResponse for operation data structures
Declaration
Swift
public class OperationsService : @unchecked Sendable -
Service for querying orderbook information from the Stellar Horizon API.
The orderbook shows current bids and asks for a given asset pair on the Stellar DEX. Provides a snapshot of available offers at different price levels.
Example usage:
let sdk = StellarSDK() // Get orderbook for USD/XLM let response = await sdk.orderbook.getOrderbook( sellingAssetType: AssetTypeAsString.CREDIT_ALPHANUM4, sellingAssetCode: "USD", sellingAssetIssuer: "GISSUER...", buyingAssetType: AssetTypeAsString.NATIVE, limit: 20 ) switch response { case .success(let orderbook): print("Bids: \(orderbook.bids.count)") print("Asks: \(orderbook.asks.count)") case .failure(let error): print("Error: \(error)") }See also:
- Stellar developer docs
- OffersService for individual offers
Declaration
Swift
public class OrderbookService : @unchecked Sendable -
Service for finding payment paths on the Stellar network.
Payment paths allow sending one asset and having the recipient receive a different asset through automatic conversions on the Stellar DEX. This service finds available paths and their costs for path payment operations.
Example usage:
let sdk = StellarSDK() // Find paths to send USD and receive XLM let response = await sdk.paymentPaths.findPaymentPaths( destinationAccount: "GDEST...", destinationAssetType: AssetTypeAsString.NATIVE, destinationAmount: "100", sourceAccount: "GSOURCE..." ) switch response { case .success(let paths): for path in paths.paths { print("Source amount: \(path.sourceAmount)") print("Path length: \(path.path.count)") } case .failure(let error): print("Error: \(error)") }See also:
- Stellar developer docs
- PathPaymentOperation for executing path payments
Declaration
Swift
public class PaymentPathsService : @unchecked Sendable -
Service for querying payment operations from the Stellar Horizon API.
The PaymentsService provides methods to retrieve payment-related operations including payments, path payments, create account operations, and account merges. These are the operations that transfer value between accounts.
Example usage:
let sdk = StellarSDK() // Get payment history for an account let response = await sdk.payments.getPayments( forAccount: "GACCOUNT...", limit: 50, order: .descending ) switch response { case .success(let page): for payment in page.records { if let paymentOp = payment as? PaymentOperationResponse { print("Amount: \(paymentOp.amount) \(paymentOp.assetCode ?? "XLM")") } } case .failure(let error): print("Error: \(error)") }See also:
- Stellar developer docs
- OperationResponse for payment operation types
Declaration
Swift
public class PaymentsService : @unchecked Sendable -
Streams account data entry updates from the Horizon API using Server-Sent Events (SSE) for real-time updates.
This stream provides live updates for a specific data entry (key-value pair) on an account. Each update contains the current base64-encoded value for the specified key as it changes on the Stellar network.
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.
Example usage:
let sdk = StellarSDK() let dataStream = sdk.accounts.streamAccountData( accountId: "GACCOUNT...", key: "user_settings" ) dataStream.onReceive { response in switch response { case .open: print("Stream connection established") 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 stream when done dataStream.closeStream()See also:
- Stellar developer docs
- DataForAccountResponse for the data entry structure
- ManageDataOperation for setting account data
Declaration
Swift
public final class AccountDataStreamItem : Sendable -
Streams account data from the Horizon API using Server-Sent Events (SSE) for real-time updates.
This stream provides live updates for a single account, delivering changes as they occur on the Stellar network. Each update contains the complete current state of the account including balances, signers, thresholds, and other account properties.
Example usage:
let sdk = StellarSDK() let accountStream = sdk.accounts.streamAccount(accountId: "GACCOUNT...") accountStream.onReceive { response in switch response { case .open: print("Stream connection established") case .response(id: let id, data: let account): print("Account update received - Sequence: \(account.sequenceNumber)") for balance in account.balances { print("\(balance.assetCode ?? "XLM"): \(balance.balance)") } case .error(let error): print("Stream error: \(error)") } } // Close stream when done accountStream.closeStream()See also:
- Stellar developer docs
- AccountResponse for the account data structure
Declaration
Swift
public final class AccountStreamItem : Sendable -
Streams effect data from the Horizon API using Server-Sent Events (SSE) for real-time updates.
See moreDeclaration
Swift
public final class EffectsStreamItem : Sendable -
Streams ledger data from the Horizon API using Server-Sent Events (SSE) for real-time updates.
See moreDeclaration
Swift
public final class LedgersStreamItem : Sendable -
Streams liquidity pool trade data from the Horizon API using Server-Sent Events (SSE) for real-time updates.
This stream provides live updates for trades involving a specific liquidity pool, delivering new trade events as they occur on the Stellar network. Each update contains complete trade details including traded assets, amounts, prices, and participating accounts or liquidity pools.
Example usage:
let sdk = StellarSDK() let poolId = "L..." // Liquidity pool ID (L-address or hex format) let tradesStream = sdk.liquidityPools.streamTrades(forPoolId: poolId) tradesStream.onReceive { response in switch response { case .open: print("Stream connection established") case .response(id: let id, data: let trade): print("Trade received - Type: \(trade.tradeType)") print("Base: \(trade.baseAmount) \(trade.baseAssetCode ?? "XLM")") print("Counter: \(trade.counterAmount) \(trade.counterAssetCode ?? "XLM")") print("Price: \(trade.price.n)/\(trade.price.d)") case .error(let error): print("Stream error: \(error)") } } // Close stream when done tradesStream.closeStream()See also:
- Stellar developer docs
- TradeResponse for the trade data structure
- LiquidityPoolsService for related liquidity pool operations
Declaration
Swift
public final class LiquidityPoolTradesStreamItem : Sendable -
Streams offer data from the Horizon API using Server-Sent Events (SSE) for real-time updates.
See moreDeclaration
Swift
public final class OffersStreamItem : Sendable -
Streams operation data from the Horizon API using Server-Sent Events (SSE) for real-time updates.
See moreDeclaration
Swift
public final class OperationsStreamItem : Sendable -
Streams orderbook data from the Horizon API using Server-Sent Events (SSE) for real-time updates.
See moreDeclaration
Swift
public final class OrderbookStreamItem : Sendable -
Helper class for managing Server-Sent Events streaming from Horizon endpoints.
This class wraps the
EventSourceimplementation to provide a simplified interface for streaming data from Stellar Horizon servers. It handles the connection lifecycle, error states, and message dispatching through a unified response closure.The StreamingHelper is used internally by various SDK service classes to enable real-time streaming of ledgers, transactions, operations, effects, and other Horizon resources.
Usage Example
let helper = StreamingHelper() helper.streamFrom(requestUrl: "https://horizon.stellar.org/ledgers?cursor=now") { response in switch response { case .open: print("Stream connection opened") case .response(let id, let data): print("Received data: \(data)") // Parse JSON data case .error(let error): print("Stream error: \(error)") } } // Close when done helper.close()Response Types
The
responseClosurereceives three types of responses:.open: Connection established successfully.response(id, data): Message received with event ID and JSON data.error(error): Error occurred during streaming
Thread Safety
This class is thread-safe. The EventSource callbacks may arrive on background threads while
close()may be called from any thread. All access to mutable state is protected by an internal lock.See also:
- [EventSource] for the underlying SSE implementation
- Stellar developer docs
Declaration
Swift
public class StreamingHelper : @unchecked Sendable -
Streams trade data from the Horizon API using Server-Sent Events (SSE) for real-time updates.
See moreDeclaration
Swift
public final class TradesStreamItem : Sendable -
Streams transaction data from the Horizon API using Server-Sent Events (SSE) for real-time updates.
See moreDeclaration
Swift
public final class TransactionsStreamItem : Sendable -
Service for querying aggregated trade statistics from the Stellar Horizon API.
Trade aggregations provide OHLCV (Open, High, Low, Close, Volume) candlestick data for asset pairs over specified time intervals. Useful for charts and market analysis.
Example usage:
let sdk = StellarSDK() // Get hourly trade aggregations for the last 24 hours let oneDayAgo = Int64(Date().timeIntervalSince1970 * 1000) - (24 * 60 * 60 * 1000) let now = Int64(Date().timeIntervalSince1970 * 1000) let response = await sdk.tradeAggregations.getTradeAggregations( startTime: oneDayAgo, endTime: now, resolution: 3600000, // 1 hour in milliseconds baseAssetType: AssetTypeAsString.CREDIT_ALPHANUM4, baseAssetCode: "USD", baseAssetIssuer: "GISSUER...", counterAssetType: AssetTypeAsString.NATIVE, limit: 24 )See also:
- Stellar developer docs
- TradesService for individual trade records
Declaration
Swift
public class TradeAggregationsService : @unchecked Sendable -
Service for querying trade history from the Stellar Horizon API.
Trades represent completed exchanges between two assets on the Stellar decentralized exchange. Can filter trades by asset pair, account, offer, or liquidity pool.
Example usage:
let sdk = StellarSDK() // Get trades for a trading pair let response = await sdk.trades.getTrades( forAssetPair: (selling: Asset(canonicalForm: "USD:GISSUER...")!, buying: Asset(type: AssetType.ASSET_TYPE_NATIVE)!), limit: 50 ) switch response { case .success(let page): for trade in page.records { print("Price: \(trade.price)") print("Amount: \(trade.baseAmount)") } case .failure(let error): print("Error: \(error)") }See also:
- Stellar developer docs
- TradeAggregationsService for aggregated trade statistics
Declaration
Swift
public class TradesService : @unchecked Sendable -
Service for querying and submitting transactions on the Stellar network.
The TransactionsService provides methods to retrieve transaction history, submit new transactions to the network, and check SEP-29 memo requirements. Supports both synchronous and asynchronous transaction submission modes.
Example usage:
let sdk = StellarSDK() // Get transaction details let txResponse = await sdk.transactions.getTransactionDetails( transactionHash: "abc123..." ) // Submit a transaction let submitResponse = await sdk.transactions.submitTransaction( transaction: myTransaction ) switch submitResponse { case .success(let result): print("Transaction successful: \(result.hash)") case .destinationRequiresMemo(let accountId): print("Destination \(accountId) requires a memo (SEP-29)") case .failure(let error): print("Error: \(error)") }See also:
See moreDeclaration
Swift
public class TransactionsService : @unchecked Sendable -
Filter criteria for querying contract events.
EventFilter allows you to narrow event queries by:
- Event type (system, contract, or diagnostic)
- Specific contract IDs
- Event topic patterns
Use filters to reduce the amount of data returned and focus on events relevant to your application. Multiple filters can be combined, and events matching any filter will be included in results.
Limitations:
- Maximum 5 contract IDs per request
- Maximum 5 topic filters per request
Example:
// Filter events from specific contracts let contractFilter = EventFilter( type: "contract", contractIds: ["CCONTRACT123...", "CCONTRACT456..."] ) // Filter by event topics let topicFilter = TopicFilter(segmentMatchers: [ "transfer", // Topic 0: event name "*", // Topic 1: any value "GADDR..." // Topic 2: specific address ]) let filter = EventFilter( type: "contract", topics: [topicFilter] ) // Query events with filter let response = await server.getEvents( startLedger: 1000000, eventFilters: [contractFilter] )See also:
- [SorobanServer.getEvents] for querying events
- [TopicFilter] for topic-based filtering
- Stellar developer docs
Declaration
Swift
public final class EventFilter : Sendable -
Ledger footprint wrapper for Soroban transaction simulation.
A footprint represents the set of ledger entries that a Soroban transaction will read from or write to during execution. Footprints are returned when simulating transactions and must be included in the final transaction to ensure resource limits are properly calculated.
The footprint contains two categories of ledger keys:
- Read-only: Entries the transaction will read but not modify
- Read-write: Entries the transaction will read and potentially modify
This class provides utility methods to:
- Parse footprints from base64-encoded XDR
- Extract specific ledger keys (contract code, contract data)
- Convert footprints to XDR format for transaction submission
Example:
// Parse footprint from simulation response let footprint = try Footprint(fromBase64: simulationResponse.footprint) // Extract contract code ledger key if let codeKey = footprint.contractCodeLedgerKey { print("Contract code key: \(codeKey)") } // Create empty footprint let emptyFootprint = Footprint.empty()See also:
- [SimulateTransactionResponse] for simulation results
- SorobanTransactionDataXDR for transaction resource configuration
- Stellar developer docs
Declaration
Swift
public final class Footprint : Sendable -
Pagination settings for Soroban RPC queries that return large result sets.
Use PaginationOptions to control the number of results returned and to navigate through multiple pages of results.
Parameters:
- cursor: Continuation token from a previous response (for fetching next page)
- limit: Maximum number of results to return per request
Example:
// Fetch first page with limit let firstPageOptions = PaginationOptions(limit: 100) let response1 = await server.getEvents( startLedger: 1000000, paginationOptions: firstPageOptions ) // Fetch next page using cursor from first response if let cursor = response1.cursor { let nextPageOptions = PaginationOptions( cursor: cursor, limit: 100 ) let response2 = await server.getEvents( startLedger: 1000000, paginationOptions: nextPageOptions ) }See also:
- [SorobanServer.getEvents] for event queries
- [SorobanServer.getTransactions] for transaction queries
- [SorobanServer.getLedgers] for ledger queries
Declaration
Swift
public final class PaginationOptions : Sendable -
Configuration for Soroban transaction resource calculation during simulation.
ResourceConfig allows you to adjust the instruction budget leeway used when simulating Soroban transactions. This affects how conservatively the system estimates the CPU instructions needed for transaction execution.
The instruction leeway is added as a safety margin to the actual instruction count observed during simulation. A higher leeway provides more buffer against edge cases but increases resource fees.
Use cases:
- Increase leeway for transactions with variable execution paths
- Reduce leeway for predictable operations to minimize fees
- Adjust based on network conditions and fee tolerance
Example:
// Configure with 10% instruction leeway let resourceConfig = ResourceConfig(instructionLeeway: 1000000) // Use in transaction simulation let request = SimulateTransactionRequest( transaction: transaction, resourceConfig: resourceConfig ) let response = await server.simulateTransaction(request)See also:
- [SimulateTransactionRequest] for simulation configuration
- [SorobanServer.simulateTransaction] for running simulations
- Stellar developer docs
Declaration
Swift
public final class ResourceConfig : Sendable -
Request parameters for simulating a Soroban transaction.
SimulateTransactionRequest configures how a transaction should be simulated by the Soroban RPC server.
Parameters:
- transaction: The transaction to simulate (must contain InvokeHostFunction operation)
- resourceConfig: Optional resource budget configuration (default: 3000000 instruction leeway)
- authMode: Authorization simulation mode (protocol 23+)
Authorization modes (protocol 23+):
- “enforce”: Strict authorization checking (default)
- “record”: Record auth entries without enforcing
- “record_allow_nonroot”: Allow non-root authorization
Example:
let request = SimulateTransactionRequest( transaction: transaction, resourceConfig: ResourceConfig(instructionLeeway: 5000000) ) let response = await server.simulateTransaction(simulateTxRequest: request)See also:
- [SorobanServer.simulateTransaction] for running simulations
- [SimulateTransactionResponse] for simulation results
- [ResourceConfig] for resource configuration
Declaration
Swift
public final class SimulateTransactionRequest : @unchecked Sendable -
Parses a soroban contract byte code to get Environment Meta, Contract Spec and Contract Meta. see: Stellar developer docs
See moreDeclaration
Swift
public final class SorobanContractParser : Sendable -
Stores information parsed from a soroban contract byte code such as Environment Meta, Contract Spec Entries and Contract Meta Entries. See also: Stellar developer docs
See moreDeclaration
Swift
public final class SorobanContractInfo : Sendable -
Soroban RPC client for interacting with smart contracts on the Stellar network.
SorobanServer provides access to Soroban RPC endpoints for smart contract operations including:
- Contract invocation simulation and submission
- Reading contract state and ledger entries
- Querying contract events
- Transaction status polling
- Network and fee information
Initialize with your Soroban RPC endpoint URL. For testnet, use the public RPC endpoint or run your own RPC server. For production, always use a reliable RPC provider.
Example usage:
// Connect to testnet RPC let server = SorobanServer(endpoint: "https://soroban-testnet.stellar.org") // Get network information let networkResponse = await server.getNetwork() switch networkResponse { case .success(let network): print("Network passphrase: \(network.passphrase)") case .failure(let error): print("Error: \(error)") } // Simulate a contract invocation let simulateRequest = SimulateTransactionRequest(transaction: transaction) let simResponse = await server.simulateTransaction(simulateTxRequest: simulateRequest) switch simResponse { case .success(let simulation): print("Resource cost: \(simulation.cost)") case .failure(let error): print("Simulation failed: \(error)") }See also:
- Stellar developer docs
- [SorobanClient] for high-level contract interaction
- [AssembledTransaction] for transaction construction
Declaration
Swift
public class SorobanServer : @unchecked Sendable -
Topic-based filter for querying contract events.
TopicFilter allows filtering events by their topic values. Topics are indexed parameters emitted with contract events, typically including the event name and key parameters.
Topic matching:
- Use exact values to match specific topics (e.g., “transfer”)
- Use “*” as a wildcard to match any value at that position
Example:
// Match transfer events to a specific address let topicFilter = TopicFilter(segmentMatchers: [ "transfer", // Topic 0: event name "*", // Topic 1: any sender "GADDR..." // Topic 2: specific recipient ]) let eventFilter = EventFilter( type: "contract", topics: [topicFilter] )See also:
- [EventFilter] for complete event filtering
- [SorobanServer.getEvents] for querying events
- Stellar developer docs
Declaration
Swift
public final class TopicFilter : Sendable -
The main workhorse of
SorobanClient. This class is used to wrap a transaction-under-construction and provide high-level interfaces to the most common workflows, while still providing access to low-level stellar-sdk transaction manipulation.Most of the time, you will not construct an
AssembledTransactiondirectly, but instead receive one as the return value of aSorobanClient.buildInvokeMethodTxmethod.Let’s look at examples of how to use
AssembledTransactionfor a variety of use-cases:1. Simple read call
Since these only require simulation, you can get the
resultof the call right after constructing yourAssembledTransaction:let clientOptions = ClientOptions(sourceAccountKeyPair: sourceAccountKeyPair, contractId: "C123…", network: Network.testnet, rpcUrl: "https://…") let txOptions = AssembledTransactionOptions(clientOptions: clientOptions, methodOptions: MethodOptions(), method: "myReadMethod", arguments: args) let tx = try await AssembledTransaction.build(options: txOptions) let result = try tx.getSimulationData().returnedValueWhile that looks pretty complicated, most of the time you will use this in conjunction with
SorobanClient, which simplifies it to:let result = try await client.invokeMethod(name: "myReadMethod", args: args)2. Simple write call
For write calls that will be simulated and then sent to the network without further manipulation, only one more step is needed:
let tx = try await AssembledTransaction.build(options: txOptions) let response = try await tx.signAndSend() if response.status == GetTransactionResponse.STATUS_SUCCESS { let result = response.resultValue }If you are using it in conjunction with
SorobanClient:let result = try await client.invokeMethod(name: "myWriteMethod", args: args)3. More fine-grained control over transaction construction
If you need more control over the transaction before simulating it, you can set various
MethodOptionswhen constructing yourAssembledTransaction. With aSorobanClient, this can be passed as an argument when callinginvokeMethodorbuildInvokeMethodTx:let methodOptions = MethodOptions(fee: 10000, timeoutInSeconds: 20, simulate: false) let tx = try await client.buildInvokeMethodTx(name: "myWriteMethod", args: args, methodOptions: methodOptions)Since we’ve skipped simulation, we can now edit the
rawtransaction builder and then manually callsimulate:tx.raw?.setMemo(memo: Memo.text("Hello")) try await tx.simulate()If you need to inspect the simulation later, you can access it with
let data = try tx.getSimulationData()#### 4. Multi-auth workflows
Soroban, and Stellar in general, allows multiple parties to sign a transaction.
Let’s consider an Atomic Swap contract. Alice wants to give some of her Token A tokens to Bob for some of his Token B tokens.
let swapMethodName = "swap" let amountA = SCValXDR.i128(Int128PartsXDR(hi: 0, lo: 1000)) let minBForA = SCValXDR.i128(Int128PartsXDR(hi: 0, lo: 4500)) let amountB = SCValXDR.i128(Int128PartsXDR(hi: 0, lo: 5000)) let minAForB = SCValXDR.i128(Int128PartsXDR(hi: 0, lo: 950)) let args:[SCValXDR] = [try SCValXDR.address(SCAddressXDR(accountId: aliceId)), try SCValXDR.address(SCAddressXDR(accountId: bobId)), try SCValXDR.address(SCAddressXDR(contractId: tokenAContractId)), try SCValXDR.address(SCAddressXDR(contractId: tokenBContractId)), amountA, minBForA, amountB, minAForB]Let’s say Alice is also going to be the one signing the final transaction envelope, meaning she is the invoker. So your app, she simulates the
swapcall:let tx = try await atomicSwapClient.buildInvokeMethodTx(name: swapMethodName, args: args)But your app can’t
signAndSendthis right away, because Bob needs to sign it first. You can check this:let whoElseNeedsToSign = try tx.needsNonInvokerSigningBy()You can verify that
whoElseNeedsToSignis an array of length1, containing only Bob’s public key.If you have Bob’s secret key, you can sign it right away with:
let bobsKeyPair = try KeyPair(secretSeed: "S...") try await tx.signAuthEntries(signerKeyPair: bobsKeyPair)But if you don’t have Bob’s private key, and e.g. need to send it to another server for signing, you can provide a callback function for signing the auth entry:
let bobPublicKeyKeypair = try KeyPair(accountId: bobsAccountId) try await tx.signAuthEntries(signerKeyPair: bobPublicKeyKeypair, authorizeEntryCallback: { (entry, network) async throws in // You can send it to some other server for signing by encoding it as a base64xdr string let base64Entry = entry.xdrEncoded! // send for signing ... // and on the other server you can decode it: var entryToSign = try SorobanAuthorizationEntryXDR.init(fromBase64: base64Entry) // sign it try entryToSign.sign(signer: bobsSecretKeyPair, network: network) // encode as a base64xdr string and send it back let signedBase64Entry = entryToSign.xdrEncoded! // here you can now decode it and return it return try SorobanAuthorizationEntryXDR.init(fromBase64: signedBase64Entry) })To see an even more complicated example, where Alice swaps with Bob but the transaction is invoked by yet another party, check out in the SorobanClientTest.atomicSwapTest()
See moreDeclaration
Swift
public final class AssembledTransaction : @unchecked Sendable -
Configuration options for assembling and simulating Soroban smart contract transactions.
See moreDeclaration
Swift
public final class AssembledTransactionOptions : Sendable -
Configuration options for SorobanClient instances.
ClientOptions specifies the connection parameters and authentication details needed to interact with a deployed smart contract.
Required configuration:
- Source account keypair (public key required, private key needed for signing)
- Contract ID (the address of the deployed contract)
- Network selection (testnet, mainnet, or custom)
- RPC URL (endpoint for Soroban RPC server)
Example:
let clientOptions = ClientOptions( sourceAccountKeyPair: sourceKeyPair, contractId: "CCONTRACT123...", network: Network.testnet, rpcUrl: "https://soroban-testnet.stellar.org", enableServerLogging: false ) let client = try await SorobanClient.forClientOptions(options: clientOptions)See also:
- [SorobanClient.forClientOptions] for creating client instances
- [MethodOptions] for transaction-specific settings
Declaration
Swift
public final class ClientOptions : Sendable -
Parser and utility for Soroban contract specifications.
ContractSpec provides tools for working with contract interface definitions, including:
- Parsing contract spec entries (functions, events, types)
- Converting between native Swift types and Soroban contract values (SCVal)
- Validating function arguments against contract specifications
- Extracting contract metadata and type definitions
Contract specifications are embedded in the WebAssembly contract code and describe:
- Available contract functions with parameters and return types
- Custom data types (structs, enums, unions)
- Events that the contract can emit
- Error types the contract may return
Use this class to:
- Introspect contract interfaces
- Build type-safe contract invocations
- Parse and validate contract arguments
- Convert contract return values to Swift types
Example usage:
// Get contract spec from deployed contract let client = try await SorobanClient.forClientOptions(options: clientOptions) let spec = client.getContractSpec() // List all available functions let functions = spec.funcs() for func in functions { print("Function: \(func.name)") print("Parameters: \(func.inputs.count)") } // Get specific function details if let transferFunc = spec.getFunc(name: "transfer") { print("Transfer function inputs: \(transferFunc.inputs)") print("Transfer function outputs: \(transferFunc.outputs)") }See also:
- [SorobanClient] for high-level contract interaction
- Stellar developer docs
Declaration
Swift
public final class ContractSpec : Sendable -
Request parameters for deploying a smart contract instance.
Deploying a contract creates a new instance from previously installed WASM code. The contract receives a unique contract ID and can optionally be initialized with constructor arguments.
Prerequisites:
- Contract WASM code must be installed first (use InstallRequest)
- You need the WASM hash from the installation
Required parameters:
- Source account keypair (with private key for signing)
- WASM hash from contract installation
- Network and RPC endpoint
Optional parameters:
- Constructor arguments (if contract has an __constructor function)
- Salt for deterministic contract ID generation
- Method options for transaction customization
Example:
// After installing contract and obtaining wasmHash let constructorArgs = [ try SCValXDR.address(adminAddress), SCValXDR.u32(1000) ] let deployRequest = DeployRequest( rpcUrl: "https://soroban-testnet.stellar.org", network: Network.testnet, sourceAccountKeyPair: sourceKeyPair, wasmHash: wasmHash, constructorArgs: constructorArgs, salt: nil, // Random salt methodOptions: MethodOptions(), enableServerLogging: false ) let client = try await SorobanClient.deploy(deployRequest: deployRequest) print("Deployed at: \(client.contractId)")See also:
- [SorobanClient.deploy] for deploying contracts
- [InstallRequest] for installing contract code
Declaration
Swift
public final class DeployRequest : Sendable -
Request parameters for installing (uploading) contract WebAssembly code.
Installing a contract uploads the compiled WASM bytecode to the Stellar network, making it available for deployment. The same WASM code can be used to deploy multiple contract instances.
Required parameters:
- Source account keypair (with private key for signing)
- Contract WASM bytecode
- Network and RPC endpoint
Example:
// Load contract WASM file let wasmBytes = try Data(contentsOf: contractWasmUrl) let installRequest = InstallRequest( rpcUrl: "https://soroban-testnet.stellar.org", network: Network.testnet, sourceAccountKeyPair: sourceKeyPair, wasmBytes: wasmBytes, enableServerLogging: false ) let wasmHash = try await SorobanClient.install(installRequest: installRequest) print("Installed with hash: \(wasmHash)")See also:
- [SorobanClient.install] for installing contracts
- [DeployRequest] for deploying contract instances
Declaration
Swift
public final class InstallRequest : Sendable -
Transaction configuration options for contract method invocations.
MethodOptions allows fine-tuning of transaction behavior when invoking contract methods through SorobanClient or AssembledTransaction.
Configuration parameters:
- Fee: Base fee in stroops (default: 100)
- Timeout: Transaction validity window (default: 300 seconds)
- Simulate: Auto-simulate before submission (default: true)
- Restore: Auto-restore archived entries if needed (default: false)
Example:
// Custom method options for a high-priority transaction let methodOptions = MethodOptions( fee: 10000, // Higher fee for faster inclusion timeoutInSeconds: 60, // Shorter validity window simulate: true, // Auto-simulate restore: true // Auto-restore if needed ) let result = try await client.invokeMethod( name: "transfer", args: [from, to, amount], methodOptions: methodOptions )See also:
- [SorobanClient.invokeMethod] for using method options
- [AssembledTransaction] for transaction construction
- [ClientOptions] for client-level configuration
Declaration
Swift
public final class MethodOptions : Sendable -
This class is used in ContractSpec to represent native union values that need to be converted to XdrSCVal for Soroban contract invocation.
See moreDeclaration
Swift
public final class NativeUnionVal : @unchecked Sendable -
Result of simulating a Soroban host function invocation containing auth entries and return values.
See moreDeclaration
Swift
public final class SimulateHostFunctionResult : Sendable -
High-level client for interacting with deployed Soroban smart contracts.
SorobanClient provides a simplified interface for common contract operations:
- Installing contract WebAssembly code
- Deploying contracts with constructor arguments
- Invoking contract methods (both read-only and write operations)
- Automatic transaction construction, simulation, and submission
The client automatically handles:
- Transaction building with correct parameters
- Simulation to get resource requirements
- Distinguishing between read and write calls
- Return value extraction from transaction results
Use this class when you want a streamlined experience for contract interaction. For more control over transaction construction, use AssembledTransaction directly.
Example usage:
// Connect to an existing contract let clientOptions = ClientOptions( sourceAccountKeyPair: sourceKeyPair, contractId: "CCONTRACT123...", network: Network.testnet, rpcUrl: "https://soroban-testnet.stellar.org" ) let client = try await SorobanClient.forClientOptions(options: clientOptions) // Invoke a read-only method let balance = try await client.invokeMethod( name: "balance", args: [try SCValXDR.address(userAddress)] ) // Invoke a write method let result = try await client.invokeMethod( name: "transfer", args: [fromAddr, toAddr, amount] ) print("Transfer result: \(result)")See also:
- [AssembledTransaction] for lower-level transaction control
- [ContractSpec] for contract interface parsing
- Stellar developer docs
Declaration
Swift
public final class SorobanClient : Sendable -
Represents account and service endpoint information from a stellar.toml file.
This class parses and provides access to the account-level configuration section of a domain’s stellar.toml file. It contains service endpoints for various SEPs (Stellar Ecosystem Proposals), signing keys, and account identifiers.
Developers use this class to discover service URLs for operations such as:
- SEP-10 web authentication
- SEP-6 and SEP-24 transfer/deposit/withdrawal operations
- SEP-12 customer information transfer
- SEP-31 direct payments
- SEP-38 quotes
- Federation services
See also:
- [StellarToml] for the main stellar.toml parser
- SEP-0001
Declaration
Swift
public final class AccountInformation : Sendable -
Represents currency and asset information from a stellar.toml file.
This class parses and provides access to the CURRENCIES section of a domain’s stellar.toml file. It contains comprehensive metadata about Stellar assets including both classic assets and Soroban token contracts.
Asset information includes identification (code, issuer, contract), metadata (name, description, image), supply information, anchor details for backed assets, and regulatory information for compliant assets.
Developers use this class to discover asset properties when integrating with anchors, displaying asset information in wallets, or implementing regulatory compliance features.
See also:
- [StellarToml] for the main stellar.toml parser
- SEP-0001
- SEP-0008 for regulated assets
- SEP-0041 for Soroban token metadata
Declaration
Swift
public final class CurrencyDocumentation : Sendable -
Represents organization and issuer information from a stellar.toml file.
This class parses and provides access to the DOCUMENTATION section of a domain’s stellar.toml file. It contains organizational details about the asset issuer or service provider including legal information, contact details, and verification data.
The information in this class helps establish trust and transparency by providing verifiable details about the organization operating Stellar infrastructure or issuing assets. This includes legal names, physical addresses with attestations, social media accounts, and licensing information.
Developers use this class to display issuer information in wallets, verify organizational legitimacy, and provide users with contact details for support.
See also:
- [StellarToml] for the main stellar.toml parser
- SEP-0001
Declaration
Swift
public final class IssuerDocumentation : Sendable -
Represents point of contact information from a stellar.toml file.
This class parses and provides access to the PRINCIPALS section of a domain’s stellar.toml file. It contains information about key individuals associated with the organization, such as executives, directors, or other responsible parties.
The PRINCIPALS section helps establish accountability and trust by identifying real people behind an organization. This includes their contact information, social media accounts for verification, and cryptographic hashes of identity verification photos.
Developers use this class to display information about who is responsible for an asset or service, enabling users to verify the legitimacy of an organization through the identities of its key personnel.
See also:
- [StellarToml] for the main stellar.toml parser
- SEP-0001
Declaration
Swift
public final class PointOfContactDocumentation : Sendable -
Implements SEP-0001 - stellar.toml Discovery and Configuration.
This class parses and provides access to a domain’s stellar.toml file, which contains configuration and metadata about a Stellar integration. The stellar.toml file enables automatic discovery of services, validator nodes, asset information, and contact details.
SEP-0001 is foundational for the Stellar ecosystem, allowing wallets and applications to discover anchor services, validator information, and asset metadata from a domain.
Typical Usage
// Fetch stellar.toml from a domain let result = await StellarToml.from(domain: "testanchor.stellar.org") switch result { case .success(let toml): // Access account information if let webAuthEndpoint = toml.accountInformation.webAuthEndpoint { print("SEP-10 endpoint: \(webAuthEndpoint)") } // Access supported currencies for currency in toml.currenciesDocumentation { print("Asset: \(currency.code ?? ""), Issuer: \(currency.issuer ?? "")") } // Access transfer server if let transferServer = toml.accountInformation.transferServer { print("SEP-6 server: \(transferServer)") } case .failure(let error): print("Error: \(error)") }Available Information
- Account Information: Service endpoints (SEP-6, SEP-10, SEP-12, SEP-24, SEP-31, SEP-38)
- Issuer Documentation: Organization details, contact information
- Currencies: Supported assets with metadata and regulatory info
- Validators: Validator node information for network operators
- Points of Contact: Key personnel and support contacts
See also:
- SEP-0001 Specification
- Supported version: 2.7.0
Declaration
Swift
public final class StellarToml : Sendable -
Represents validator node information from a stellar.toml file.
This class parses and provides access to the VALIDATORS section of a domain’s stellar.toml file. It contains information about Stellar validator nodes operated by the organization, including connection details and history archive locations.
Validator information is essential for network participants who need to configure their nodes to connect to trusted validators. This includes the validator’s public key, network address, and the location of its history archive for catchup operations.
Developers use this class when building node configuration tools, validator explorers, or applications that need to discover and connect to trusted validators on the Stellar network.
See also:
- [StellarToml] for the main stellar.toml parser
- SEP-0001
- Stellar developer docs
Declaration
Swift
public final class ValidatorInformation : Sendable -
Implements SEP-0006 - Deposit and Withdrawal API.
This class provides programmatic deposit and withdrawal functionality for Stellar assets without requiring user interaction in a web interface. Unlike SEP-0024, SEP-6 is designed for automated workflows and server-to-server integrations.
Key Differences from SEP-0024
- SEP-6: Programmatic API for automation (no user web interface)
- SEP-24: Interactive flows with hosted web UI for user input
Typical Workflow
// Initialize service let result = await TransferServerService.forDomain(domain: "testanchor.stellar.org") guard case .success(let service) = result else { return } // Get info about supported assets let info = await service.info() // Deposit flow let depositRequest = DepositRequest( assetCode: "USDC", account: accountId, jwt: jwtToken ) let depositResult = await service.deposit(request: depositRequest) // Withdraw flow let withdrawRequest = WithdrawRequest( type: "bank_account", assetCode: "USDC", account: accountId, dest: "123456789", // Bank account number jwt: jwtToken ) let withdrawResult = await service.withdraw(request: withdrawRequest)Exchange Operations
SEP-6 supports asset conversion during deposit/withdrawal using SEP-38 quotes:
// Deposit with exchange (e.g., receive BRL, send USDC to Stellar) let exchangeRequest = DepositExchangeRequest( destinationAsset: "stellar:USDC:G...", sourceAsset: "iso4217:BRL", amount: "1000", account: accountId, jwt: jwtToken ) let result = await service.depositExchange(request: exchangeRequest)See also:
- SEP-0006 Specification
- [InteractiveService] for SEP-24 (interactive flows)
- [WebAuthenticator] for SEP-10 authentication
Declaration
Swift
public final class TransferServerService : @unchecked Sendable -
TxRep is a human-readable text format for Stellar transactions.
TxRep provides a readable low-level representation of Stellar transactions that can be used for debugging, auditing, or manual transaction construction. It converts between the standard base64-encoded XDR format and a human-readable key-value format.
Example:
let txEnvelopeXdr = "AAAAAC..." // Base64 XDR let txRep = try TxRep.toTxRep(transactionEnvelope: txEnvelopeXdr) // Returns human-readable format: // type: ENVELOPE_TYPE_TX // tx.sourceAccount: GBZX... // tx.fee: 100 // ... // Convert back to XDR let xdrAgain = try TxRep.fromTxRep(txRep: txRep)See: SEP-0011 for the TxRep specification.
See moreDeclaration
Swift
public final class TxRep : Sendable -
Implements SEP-0007 - URI Scheme to Facilitate Delegated Signing.
This class provides functionality for creating and processing Stellar URIs that enable transaction signing delegation. Applications can generate URIs requesting users to sign transactions or make payments, and wallets can parse these URIs to fulfill the requests.
Typical Usage
let uriScheme = URIScheme() // Generate payment URI let paymentUri = uriScheme.getPayOperationURI( destination: "GDESTINATION...", amount: 100.50, assetCode: "USDC", assetIssuer: "GISSUER..." ) // Generate transaction signing URI let transaction = try Transaction(...) let signingUri = uriScheme.getSignTransactionURI( transactionXDR: transaction.transactionXDR, callBack: "url:https://callback.example.com" )See also:
See moreDeclaration
Swift
public final class URIScheme : Sendable -
Validates and signs SEP-0007 compliant Stellar URIs.
This class provides functionality for signing URI scheme requests and verifying their authenticity by validating signatures against the origin domain’s stellar.toml file. It ensures URI requests come from legitimate sources by checking cryptographic signatures.
See: https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0007.md
See moreDeclaration
Swift
public final class URISchemeValidator : Sendable -
Implementation of the W3C Server-Sent Events (SSE) protocol for streaming data from Horizon.
This class implements a client for the Server-Sent Events protocol, which enables servers to push real-time updates to clients over HTTP. The implementation is used throughout the SDK to stream live data from Stellar Horizon servers, including ledgers, transactions, operations, effects, and account changes.
Protocol Overview
Server-Sent Events provide a unidirectional channel from server to client over HTTP. The connection remains open, and the server pushes updates as formatted text messages. Key features include:
- Automatic reconnection with configurable retry intervals
- Event identification for resuming from last received message
- Named events for routing different message types
- Long-lived connections with appropriate timeouts
Usage Example
// Stream ledger updates from Horizon let url = "https://horizon.stellar.org/ledgers?cursor=now" let eventSource = EventSource(url: url) eventSource.onOpen { response in print("Connection opened, status: \(response?.statusCode ?? 0)") } eventSource.onMessage { id, event, data in print("Received message - ID: \(id ?? "none"), Event: \(event ?? "none")") // Parse data as JSON ledger response if let ledgerData = data?.data(using: .utf8) { // Process ledger data } } eventSource.onError { error in print("Connection error: \(error?.localizedDescription ?? "unknown")") } // Close when done eventSource.close()Event Handlers
The EventSource supports three types of callbacks:
onOpen: Called when connection is establishedonMessage: Called for each message receivedonError: Called when errors occur
Additionally, named event listeners can be registered for specific event types:
eventSource.addEventListener("ledger-update") { id, event, data in // Handle ledger-specific events }Automatic Reconnection
The implementation automatically reconnects on connection failures using an exponential backoff strategy. The retry interval can be set by the server using the
retry:field in the event stream, defaulting to 3000 milliseconds.Last Event ID
To support reliable streaming, the last received event ID is persisted and sent with reconnection requests using the
Last-Event-Idheader. This allows the server to resume streaming from where it left off.See also:
- W3C Server-Sent Events Specification
- Stellar developer docs
- [StreamingHelper] for simplified Horizon streaming integration
Declaration
Swift
open class EventSource : NSObject, URLSessionDataDelegate, @unchecked Sendable -
Logging utility for Stellar SDK error messages and debugging.
This class provides static methods for logging Horizon request errors and error responses to the console. It is primarily used for debugging and troubleshooting issues with API requests.
The logger automatically formats error messages with tags for easy identification and includes detailed information about error responses, XDR data, and result codes when available.
Usage
// Log a Horizon request error StellarSDKLog.printHorizonRequestErrorMessage(tag: "MyClass", horizonRequestError: error) // Log an error response directly if let errorResponse = error.errorResponse { StellarSDKLog.printErrorResponse(tag: "MyClass", errorResponse: errorResponse) }See moreNote
All logging is done to standard output using Swift’s print function. Consider implementing custom log handlers if you need to redirect or filter output.Declaration
Swift
public final class StellarSDKLog : Sendable -
The actual binary decoder class.
See moreDeclaration
Swift
public class XDRDecoder : @unchecked Sendableextension XDRDecoder: Decoder -
The actual binary encoder class.
See moreDeclaration
Swift
public class XDREncoder : @unchecked Sendableextension XDREncoder: Encoder -
Implements SEP-0010 - Stellar Web Authentication.
This class provides functionality for authenticating users through the Stellar Web Authentication protocol, which allows clients to prove they possess the signing key for a Stellar account. The authentication flow returns a JWT token that can be used for subsequent requests to SEP-compliant services (SEP-6, SEP-12, SEP-24, SEP-31).
SEP-0010 defines a standard protocol for proving account ownership without transmitting secret keys. The server generates a challenge transaction that the client signs with their account’s signing key, proving ownership without revealing the secret key itself.
Typical Workflow
- Initialize from Domain: Create a WebAuthenticator instance using the anchor’s stellar.toml
- Get JWT Token: Request and obtain a JWT token for authentication
- Use Token: Include the JWT token in subsequent SEP service requests
Example Usage
// Step 1: Create WebAuthenticator from anchor domain let result = await WebAuthenticator.from( domain: "https://testanchor.stellar.org", network: .testnet ) switch result { case .success(let webAuth): // Step 2: Get JWT token for user account let userKeyPair = try KeyPair(secretSeed: "S...") let jwtResult = await webAuth.jwtToken( forUserAccount: userKeyPair.accountId, signers: [userKeyPair], homeDomain: "testanchor.stellar.org" ) switch jwtResult { case .success(let jwtToken): // Step 3: Use JWT token for SEP-24, SEP-6, SEP-12, etc. print("JWT Token: \(jwtToken)") case .failure(let error): print("JWT token error: \(error)") } case .failure(let error): print("WebAuth initialization error: \(error)") }Advanced Features
Multi-Signature Accounts:
// Provide multiple signers for accounts requiring multiple signatures let signers = [keyPair1, keyPair2, keyPair3] let result = await webAuth.jwtToken( forUserAccount: accountId, signers: signers )Muxed Accounts:
// For muxed accounts starting with M, provide memo let result = await webAuth.jwtToken( forUserAccount: "M...", memo: 12345, signers: [keyPair] )Client Domain Signing:
// For client domain verification (mutual authentication) let clientDomainKeyPair = try KeyPair(accountId: "G...") let result = await webAuth.jwtToken( forUserAccount: userAccountId, signers: [userKeyPair], clientDomain: "wallet.example.com", clientDomainAccountKeyPair: clientDomainKeyPair, clientDomainSigningFunction: { txXdr in // Sign on server and return signed transaction return try await signOnServer(txXdr) } )Authentication Flow Details
The SEP-0010 authentication process involves:
- Client requests a challenge transaction from the server
- Server returns a transaction with specific operations and time bounds
- Client validates the challenge transaction
- Client signs the transaction with their account key(s)
- Client submits the signed transaction to the server
- Server validates signatures and returns a JWT token
The JWT token typically expires after 24 hours and must be refreshed.
Error Handling
let result = await webAuth.jwtToken(forUserAccount: accountId, signers: signers) switch result { case .success(let token): // Use token case .failure(let error): switch error { case .requestError(let horizonError): // Network or server error case .validationErrorError(let validationError): // Challenge validation failed case .signingError: // Transaction signing failed case .parsingError(let parseError): // Response parsing failed } }Security Considerations
- Never transmit secret keys to the server
- Validate the challenge transaction before signing
- Check time bounds to prevent replay attacks
- Store JWT tokens securely
- Refresh tokens before expiration
See also:
- SEP-0010 Specification
- [StellarToml] for discovering authentication endpoints
Declaration
Swift
public final class WebAuthenticator : Sendable -
Implements SEP-45 - Stellar Web Authentication for Contract Accounts.
This class provides functionality for authenticating Soroban smart contract accounts (C… addresses) through the Stellar Web Authentication protocol. The authentication flow returns a JWT token that can be used for subsequent requests to SEP-compliant services (SEP-6, SEP-12, SEP-24, SEP-31).
SEP-45 extends the SEP-10 authentication protocol to support contract accounts, which have different authentication requirements than traditional Stellar accounts. Contract accounts can implement custom authentication logic in their __check_auth function.
Typical Workflow
- Initialize from Domain: Create a WebAuthForContracts instance using the anchor’s stellar.toml
- Get JWT Token: Request and obtain a JWT token for authentication
- Use Token: Include the JWT token in subsequent SEP service requests
Example Usage
// Step 1: Create WebAuthForContracts from anchor domain let result = await WebAuthForContracts.from( domain: "testanchor.stellar.org", network: .testnet ) switch result { case .success(let webAuth): // Step 2: Get JWT token for contract account let contractId = "CABC..." let signerKeyPair = try KeyPair(secretSeed: "S...") let jwtResult = await webAuth.jwtToken( forContractAccount: contractId, signers: [signerKeyPair] ) switch jwtResult { case .success(let jwtToken): // Step 3: Use JWT token for SEP-24, SEP-6, SEP-12, etc. print("JWT Token: \(jwtToken)") case .failure(let error): print("JWT token error: \(error)") } case .failure(let error): print("WebAuth initialization error: \(error)") }Advanced Features
Multi-Signature Contracts:
// Provide multiple signers for contracts requiring multiple signatures let signers = [keyPair1, keyPair2] let result = await webAuth.jwtToken( forContractAccount: contractId, signers: signers )Contracts Without Signature Requirements:
// For contracts whose __check_auth doesn't require signatures let result = await webAuth.jwtToken( forContractAccount: contractId, signers: [] // Empty signers array )Client Domain Signing:
// For client domain verification (mutual authentication) let clientDomainKeyPair = try KeyPair(accountId: "G...") let result = await webAuth.jwtToken( forContractAccount: contractId, signers: [contractSignerKeyPair], clientDomain: "wallet.example.com", clientDomainAccountKeyPair: clientDomainKeyPair, clientDomainSigningCallback: { entry in // Sign on server and return signed entry return try await signOnServer(entry) } )See also:
- SEP-0045 Specification
- [StellarToml] for discovering authentication endpoints
- [WebAuthenticator] for traditional account (G… and M…) authentication
Declaration
Swift
public final class WebAuthForContracts : @unchecked Sendable
View on GitHub
Install in Dash
Classes Reference