SorobanServer
public class SorobanServer : @unchecked 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
-
Enable detailed request/response logging for debugging. Default: false.
Declaration
Swift
public var enableLogging: Bool -
Creates a new Soroban RPC client instance.
Declaration
Swift
public init(endpoint: String)Parameters
endpointURL of the Soroban RPC server to connect to
-
getHealth()AsynchronousGeneral node health check request. See: https://soroban.stellar.org/api/methods/getHealth
Declaration
Swift
public func getHealth() async -> GetHealthResponseEnum -
getNetwork()AsynchronousGeneral info about the currently configured network. See: https://soroban.stellar.org/api/methods/getNetwork
Declaration
Swift
public func getNetwork() async -> GetNetworkResponseEnum -
getFeeStats()AsynchronousStatistics for charged inclusion fees. The inclusion fee statistics are calculated from the inclusion fees that were paid for the transactions to be included onto the ledger. For Soroban transactions and Stellar transactions, they each have their own inclusion fees and own surge pricing. Inclusion fees are used to prevent spam and prioritize transactions during network traffic surge.
Declaration
Swift
public func getFeeStats() async -> GetFeeStatsResponseEnumReturn Value
Fee statistics for both Soroban and classic transactions
-
getVersionInfo()AsynchronousVersion information about the RPC and Captive core. RPC manages its own, pared-down version of Stellar Core optimized for its own subset of needs.
Declaration
Swift
public func getVersionInfo() async -> GetVersionInfoResponseEnumReturn Value
Version details for RPC server and its embedded Stellar Core instance
-
getLedgerEntries(base64EncodedKeys:Asynchronous) For reading the current value of ledger entries directly. Allows you to directly inspect the current state of a contract, a contract’s code, or any other ledger entry. This is a backup way to access your contract data which may not be available via events or simulateTransaction. To fetch contract wasm byte-code, use the ContractCode ledger entry key.
See: https://soroban.stellar.org/api/methods/getLedgerEntries
Declaration
Swift
public func getLedgerEntries(base64EncodedKeys: [String]) async -> GetLedgerEntriesResponseEnumParameters
base64EncodedKeysArray of base64-encoded LedgerKey XDR values
Return Value
Current values of the requested ledger entries
-
getLatestLedger()AsynchronousFor finding out the current latest known ledger of this node. This is a subset of the ledger info from Horizon.
See: https://soroban.stellar.org/api/methods/getLatestLedger
Declaration
Swift
public func getLatestLedger() async -> GetLatestLedgerResponseEnumReturn Value
Latest ledger sequence number and hash
-
getLedgers(startLedger:AsynchronouspaginationOptions: format: ) Retrieve a list of ledgers starting from the specified starting point. The getLedgers method return a detailed list of ledgers starting from the user specified starting point that you can paginate as long as the pages fall within the history retention of their corresponding RPC provider.
Declaration
Swift
public func getLedgers(startLedger: UInt32, paginationOptions: PaginationOptions? = nil, format: String? = nil) async -> GetLedgersResponseEnumParameters
startLedgerStarting ledger sequence number
paginationOptionsPagination settings (limit, cursor)
formatXDR encoding format preference
Return Value
List of ledger details within the requested range
-
getContractCodeForWasmId(wasmId:Asynchronous) Loads the contract code (wasm binary) for the given wasmId.
Declaration
Swift
public func getContractCodeForWasmId(wasmId: String) async -> GetContractCodeResponseEnumParameters
wasmIdHex-encoded hash of the contract WASM
Return Value
Contract code entry containing the WASM bytecode
-
getContractCodeForContractId(contractId:Asynchronous) Loads the contract code (wasm binary) for the given contractId.
Declaration
Swift
public func getContractCodeForContractId(contractId: String) async -> GetContractCodeResponseEnumParameters
contractIdStellar contract address (C…)
Return Value
Contract code entry containing the WASM bytecode
-
getContractInfoForContractId(contractId:Asynchronous) Loads contract source byte code for the given contractId and extracts the information (Environment Meta, Contract Spec, Contract Meta).
Declaration
Swift
public func getContractInfoForContractId(contractId: String) async -> GetContractInfoEnumParameters
contractIdStellar contract address (C…)
Return Value
Parsed contract information including spec entries
-
getContractInfoForWasmId(wasmId:Asynchronous) Loads contract source byte code for the given wasm id and extracts the information (Environment Meta, Contract Spec, Contract Meta).
Declaration
Swift
public func getContractInfoForWasmId(wasmId: String) async -> GetContractInfoEnumParameters
wasmIdHex-encoded hash of the contract WASM
Return Value
Parsed contract information including spec entries
-
getAccount(accountId:Asynchronous) Fetches a minimal set of current info about a Stellar account. Needed to get the current sequence number for the account, so you can build a successful transaction. Fails if the account was not found or accountId is invalid.
Declaration
Swift
public func getAccount(accountId: String) async -> GetAccountResponseEnumParameters
accountIdStellar account address (G…)
Return Value
Account object with current sequence number
-
getContractData(contractId:Asynchronouskey: durability: ) Reads the current value of contract data ledger entries directly.
Declaration
Swift
public func getContractData(contractId: String, key: SCValXDR, durability: ContractDataDurability) async -> GetContractDataResponseEnumParameters
contractIdStellar contract address (C…)
keyStorage key as SCVal
durabilityStorage durability type (persistent or temporary)
Return Value
Current value of the contract data entry
-
simulateTransaction(simulateTxRequest:Asynchronous) Simulates a contract invocation without submitting to the network.
Transaction simulation is essential for Soroban contract interactions. It provides:
- Return values from read-only contract calls
- Resource consumption estimates (CPU instructions, memory, ledger I/O)
- Required ledger footprint for the transaction
- Authorization requirements for multi-party transactions
Always simulate before submitting write transactions to ensure they will succeed and to obtain the correct resource limits and footprint.
Example:
let request = SimulateTransactionRequest(transaction: transaction) let response = await server.simulateTransaction(simulateTxRequest: request) switch response { case .success(let simulation): if let result = simulation.results?.first { print("Contract returned: \(result.returnValue)") } print("Cost: \(simulation.cost)") case .failure(let error): print("Simulation error: \(error)") }See also:
Declaration
Swift
public func simulateTransaction(simulateTxRequest: SimulateTransactionRequest) async -> SimulateTransactionResponseEnumParameters
simulateTxRequestThe simulation request containing the transaction to simulate
Return Value
SimulateTransactionResponseEnum with simulation results or error
-
sendTransaction(transaction:Asynchronous) Submits a transaction to the Stellar network for execution.
This is the only way to make on-chain changes with smart contracts. Before calling this:
- Simulate the transaction with simulateTransaction
- Add the resource limits and footprint from simulation
- Sign the transaction with all required signers
Important: Unlike Horizon, this method does not wait for transaction completion. It validates and enqueues the transaction, then returns immediately. Use getTransaction to poll for completion status.
Example:
// After simulation and signing let response = await server.sendTransaction(transaction: signedTransaction) switch response { case .success(let result): print("Transaction hash: \(result.hash)") print("Status: \(result.status)") // Poll for completion case .failure(let error): print("Submission failed: \(error)") }See also:
- Stellar developer docs
- getTransaction(transactionHash:) for status polling
Declaration
Swift
public func sendTransaction(transaction: Transaction) async -> SendTransactionResponseEnumParameters
transactionThe signed transaction to submit
Return Value
SendTransactionResponseEnum with submission result or error
-
getTransaction(transactionHash:Asynchronous) Polls for transaction completion status.
After submitting a transaction with sendTransaction, use this method to check if the transaction has been included in a ledger and whether it succeeded or failed.
Transaction lifecycle:
- PENDING: Transaction received but not yet in a ledger
- SUCCESS: Transaction successfully executed
- FAILED: Transaction failed during execution
- NOT_FOUND: Transaction not found (may have expired)
Poll this endpoint until status is SUCCESS or FAILED. Typical polling interval is 1-2 seconds.
Example:
func pollTransaction(hash: String) async { let response = await server.getTransaction(transactionHash: hash) switch response { case .success(let txInfo): switch txInfo.status { case GetTransactionResponse.STATUS_SUCCESS: print("Transaction succeeded!") if let result = txInfo.resultValue { print("Return value: \(result)") } case GetTransactionResponse.STATUS_FAILED: print("Transaction failed: \(txInfo.resultXdr ?? "")") default: // Still pending, poll again try? await Task.sleep(nanoseconds: 1_000_000_000) await pollTransaction(hash: hash) } case .failure(let error): print("Error: \(error)") } }See also:
Declaration
Swift
public func getTransaction(transactionHash: String) async -> GetTransactionResponseEnumParameters
transactionHashThe transaction hash returned from sendTransaction
Return Value
GetTransactionResponseEnum with transaction status or error
-
getTransactions(startLedger:AsynchronouspaginationOptions: ) The getTransactions method return a detailed list of transactions starting from the user specified starting point that you can paginate as long as the pages fall within the history retention of their corresponding RPC provider.
Declaration
Swift
public func getTransactions(startLedger: Int? = nil, paginationOptions: PaginationOptions? = nil) async -> GetTransactionsResponseEnumParameters
startLedgerStarting ledger sequence number
paginationOptionsPagination settings (limit, cursor)
Return Value
List of transactions within the requested range
-
Queries contract events emitted within a specified ledger range.
Contract events provide a way for smart contracts to emit structured data that can be queried by off-chain applications. Use this method to:
- Monitor contract state changes
- Track token transfers in custom assets
- Build event-driven applications
- Populate application databases with on-chain data
Important notes:
- By default, Soroban RPC retains only the most recent 24 hours of events
- Deduplicate events by their unique ID to prevent double-processing
Use filters to narrow results to specific contracts or event types
Example:
// Query all events from a specific contract let filter = EventFilter( type: "contract", contractIds: ["CCONTRACT123..."] ) let response = await server.getEvents( startLedger: 1000000, eventFilters: [filter], paginationOptions: PaginationOptions(limit: 100) ) switch response { case .success(let eventsResponse): for event in eventsResponse.events { print("Event ID: \(event.id)") print("Topics: \(event.topic)") print("Value: \(event.value)") } case .failure(let error): print("Error: \(error)") }See also:
Declaration
Swift
public func getEvents(startLedger: Int? = nil, endLedger: Int? = nil, eventFilters: [EventFilter]? = nil, paginationOptions: PaginationOptions? = nil) async -> GetEventsResponseEnumParameters
startLedgerStarting ledger sequence number (optional)
endLedgerEnding ledger sequence number (optional)
eventFiltersFilters to narrow event results by contract ID or topics
paginationOptionsPagination settings for large result sets
Return Value
GetEventsResponseEnum with events or error
View on GitHub
Install in Dash