Class SorobanServer

java.lang.Object
org.stellar.sdk.SorobanServer
All Implemented Interfaces:
Closeable, AutoCloseable

public class SorobanServer extends Object implements Closeable
Main class used to connect to the Stellar RPC (formerly Soroban-RPC) instance and exposes an interface for requests to that instance.
  • Constructor Details

    • SorobanServer

      public SorobanServer(String serverURI)
      Creates a new SorobanServer instance.
      Parameters:
      serverURI - The URI of the Stellar RPC instance to connect to.
    • SorobanServer

      public SorobanServer(String serverURI, okhttp3.OkHttpClient httpClient)
      Creates a new SorobanServer instance.
      Parameters:
      serverURI - The URI of the Stellar RPC instance to connect to.
      httpClient - The OkHttpClient instance to use for requests.
  • Method Details

    • getAccount

      public TransactionBuilderAccount getAccount(String address)
      Fetch 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 with TransactionBuilder.
      Parameters:
      address - The address of the account to load, muxed accounts are supported.
      Returns:
      An Account object containing the sequence number and current state of the account.
      Throws:
      NetworkException - All the exceptions below are subclasses of NetworkException
      AccountNotFoundException - If the account does not exist on the network. You may need to fund it first.
      SorobanRpcException - If the Stellar RPC instance returns an error response.
      RequestTimeoutException - If the request timed out.
      ConnectionErrorException - When the request cannot be executed due to cancellation or connectivity problems, etc.
    • getHealth

      public GetHealthResponse getHealth()
      General node health check.
      Returns:
      A GetHealthResponse object containing the health check result.
      Throws:
      NetworkException - All the exceptions below are subclasses of NetworkException
      SorobanRpcException - If the Stellar RPC instance returns an error response.
      RequestTimeoutException - If the request timed out.
      ConnectionErrorException - When the request cannot be executed due to cancellation or connectivity problems, etc.
      See Also:
    • getFeeStats

      public GetFeeStatsResponse getFeeStats()
      Get statistics for charged inclusion fees.
      Returns:
      A GetFeeStatsResponse object containing the fee stats.
      Throws:
      NetworkException - All the exceptions below are subclasses of NetworkException
      SorobanRpcException - If the Stellar RPC instance returns an error response.
      RequestTimeoutException - If the request timed out.
      ConnectionErrorException - When the request cannot be executed due to cancellation or connectivity problems, etc.
      See Also:
    • getContractData

      public Optional<GetLedgerEntriesResponse.LedgerEntryResult> getContractData(String contractId, SCVal key, SorobanServer.Durability durability)
      Reads the current value of contract data ledger entries directly.
      Parameters:
      contractId - The contract ID containing the data to load.
      key - The key of the contract data to load.
      durability - The "durability keyspace" that this ledger key belongs to, which is either SorobanServer.Durability.TEMPORARY or SorobanServer.Durability.PERSISTENT.
      Returns:
      A GetLedgerEntriesResponse.LedgerEntryResult object containing the ledger entry result.
      Throws:
      NetworkException - All the exceptions below are subclasses of NetworkException
      SorobanRpcException - If the Stellar RPC instance returns an error response.
      RequestTimeoutException - If the request timed out.
      ConnectionErrorException - When the request cannot be executed due to cancellation or connectivity problems, etc.
    • getLedgerEntries

      public GetLedgerEntriesResponse getLedgerEntries(Collection<LedgerKey> keys)
      Reads the current value of ledger entries directly.

      Allows you to directly inspect the current state of contracts, contract's code, or any other ledger entries.

      Parameters:
      keys - The key of the contract data to load, at least one key must be provided.
      Returns:
      A GetLedgerEntriesResponse object containing the current values.
      Throws:
      IllegalArgumentException - If the keys collection is empty or invalid.
      NetworkException - All the exceptions below are subclasses of NetworkException
      SorobanRpcException - If the Stellar RPC instance returns an error response.
      RequestTimeoutException - If the request timed out.
      ConnectionErrorException - When the request cannot be executed due to cancellation or connectivity problems, etc.
      See Also:
    • getTransaction

      public GetTransactionResponse getTransaction(String hash)
      Fetch the details of a submitted transaction.

      When submitting a transaction, client should poll this to tell when the transaction has completed.

      Parameters:
      hash - The hash of the transaction to check. Encoded as a hex string.
      Returns:
      A GetTransactionResponse object containing the transaction status, result, and other details.
      Throws:
      NetworkException - All the exceptions below are subclasses of NetworkException
      SorobanRpcException - If the Stellar RPC instance returns an error response.
      RequestTimeoutException - If the request timed out.
      ConnectionErrorException - When the request cannot be executed due to cancellation or connectivity problems, etc.
      See Also:
    • pollTransaction

      public GetTransactionResponse pollTransaction(String hash) throws InterruptedException
      An alias for pollTransaction(String, int, SleepStrategy) with default parameters, which maxAttempts is set to 30, and the sleep strategy is set to a default strategy that sleeps for 1 second between attempts.
      Parameters:
      hash - The hash of the transaction to poll for.
      Returns:
      A GetTransactionResponse object after a "found" response, (which may be success or failure) or the last response obtained after polling the maximum number of specified attempts.
      Throws:
      InterruptedException - If the thread is interrupted while sleeping between attempts.
    • pollTransaction

      public GetTransactionResponse pollTransaction(String hash, int maxAttempts, SorobanServer.SleepStrategy sleepStrategy) throws InterruptedException
      Polls the transaction status until it is completed or the maximum number of attempts is reached.

      After submitting a transaction, clients can use this to poll for transaction completion and return a definitive state of success or failure.

      Parameters:
      hash - The hash of the transaction to poll for.
      maxAttempts - The number of attempts to make before returning the last-seen status.
      sleepStrategy - A strategy to determine the sleep duration between attempts. It should take the current attempt number and return the sleep duration in milliseconds.
      Returns:
      A GetTransactionResponse object after a "found" response, (which may be success or failure) or the last response obtained after polling the maximum number of specified attempts.
      Throws:
      IllegalArgumentException - If maxAttempts is less than or equal to 0.
      InterruptedException - If the thread is interrupted while sleeping between attempts.
    • getTransactions

      public GetTransactionsResponse getTransactions(GetTransactionsRequest getTransactionsRequest)
      Gets 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.
      Parameters:
      getTransactionsRequest - The GetTransactionsRequest to use for the request.
      Returns:
      A GetTransactionsResponse object containing the transactions that match the request.
      Throws:
      NetworkException - All the exceptions below are subclasses of NetworkException
      SorobanRpcException - If the Stellar RPC instance returns an error response.
      RequestTimeoutException - If the request timed out.
      ConnectionErrorException - When the request cannot be executed due to cancellation or connectivity problems, etc.
      See Also:
    • getLedgers

      public GetLedgersResponse getLedgers(GetLedgersRequest getLedgersRequest)
      Gets 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.
      Parameters:
      getLedgersRequest - The GetLedgersRequest to use for the request.
      Returns:
      A GetLedgersResponse object containing the ledgers that match the request.
      Throws:
      NetworkException - All the exceptions below are subclasses of NetworkException
      SorobanRpcException - If the Stellar RPC instance returns an error response.
      RequestTimeoutException - If the request timed out.
      ConnectionErrorException - When the request cannot be executed due to cancellation or connectivity problems, etc.
      See Also:
    • getEvents

      public GetEventsResponse getEvents(GetEventsRequest getEventsRequest)
      Fetches all events that match the given GetEventsRequest.
      Parameters:
      getEventsRequest - The GetEventsRequest to use for the request.
      Returns:
      A GetEventsResponse object containing the events that match the request.
      Throws:
      NetworkException - All the exceptions below are subclasses of NetworkException
      SorobanRpcException - If the Stellar RPC instance returns an error response.
      RequestTimeoutException - If the request timed out.
      ConnectionErrorException - When the request cannot be executed due to cancellation or connectivity problems, etc.
      See Also:
    • getVersionInfo

      public GetVersionInfoResponse getVersionInfo()
      Fetches version information about the RPC and Captive core.
      Returns:
      A GetVersionInfoResponse object containing the version information.
      Throws:
      NetworkException - All the exceptions below are subclasses of NetworkException
      SorobanRpcException - If the Stellar RPC instance returns an error response.
      RequestTimeoutException - If the request timed out.
      ConnectionErrorException - When the request cannot be executed due to cancellation or connectivity problems, etc.
      See Also:
    • getNetwork

      public GetNetworkResponse getNetwork()
      Fetches metadata about the network which Stellar RPC is connected to.
      Returns:
      A GetNetworkResponse object containing the network metadata.
      Throws:
      NetworkException - All the exceptions below are subclasses of NetworkException
      SorobanRpcException - If the Stellar RPC instance returns an error response.
      RequestTimeoutException - If the request timed out.
      ConnectionErrorException - When the request cannot be executed due to cancellation or connectivity problems, etc.
      See Also:
    • getLatestLedger

      public GetLatestLedgerResponse getLatestLedger()
      Fetches the latest ledger meta info from network which Stellar RPC is connected to.
      Returns:
      A GetLatestLedgerResponse object containing the latest ledger meta info.
      Throws:
      NetworkException - All the exceptions below are subclasses of NetworkException
      SorobanRpcException - If the Stellar RPC instance returns an error response.
      RequestTimeoutException - If the request timed out.
      ConnectionErrorException - When the request cannot be executed due to cancellation or connectivity problems, etc.
      See Also:
    • simulateTransaction

      public SimulateTransactionResponse simulateTransaction(Transaction transaction, @Nullable SimulateTransactionRequest.ResourceConfig resourceConfig, @Nullable SimulateTransactionRequest.AuthMode authMode, boolean useUpgradedAuth)
      Submit a trial contract invocation to get back return values, expected ledger footprint, expected authorizations, and expected costs.
      Parameters:
      transaction - The transaction to simulate. It should include exactly one operation, which must be one of InvokeHostFunctionOperation, ExtendFootprintTTLOperation, or RestoreFootprintOperation. Any provided footprint will be ignored.
      resourceConfig - Additional resource include in the simulation.
      authMode - Explicitly allows users to opt-in to non-root authorization in recording mode.
      useUpgradedAuth - Whether simulation records ADDRESS_V2 ("upgraded") authorization credentials (CAP-71) instead of the legacy ADDRESS credentials. Defaults to true in the shorter overloads; pass false to ask for the legacy format. It only affects the recording auth modes. Maps to the useUpgradedAuth flag introduced in Stellar RPC v27.1.0; older RPC servers silently ignore it. This flag is transitional: once the network returns ADDRESS_V2 credentials by default (protocol 28), it becomes a no-op — do not rely on passing false to keep receiving the legacy format.
      Returns:
      A SimulateTransactionResponse object containing the cost, footprint, result/auth requirements (if applicable), and error of the transaction.
      Throws:
      NetworkException - All the exceptions below are subclasses of NetworkException
      SorobanRpcException - If the Stellar RPC instance returns an error response.
      RequestTimeoutException - If the request timed out.
      ConnectionErrorException - When the request cannot be executed due to cancellation or connectivity problems, etc.
      See Also:
    • simulateTransaction

      public SimulateTransactionResponse simulateTransaction(Transaction transaction, @Nullable SimulateTransactionRequest.ResourceConfig resourceConfig, @Nullable SimulateTransactionRequest.AuthMode authMode)
      An alias for simulateTransaction(Transaction, SimulateTransactionRequest.ResourceConfig, SimulateTransactionRequest.AuthMode, boolean) with useUpgradedAuth enabled, so simulation records ADDRESS_V2 (CAP-71) credentials.
      Parameters:
      transaction - The transaction to simulate.
      resourceConfig - Additional resource include in the simulation.
      authMode - Explicitly allows users to opt-in to non-root authorization in recording mode.
      Returns:
      A SimulateTransactionResponse object containing the simulation result.
    • simulateTransaction

      public SimulateTransactionResponse simulateTransaction(Transaction transaction)
      Parameters:
      transaction - The transaction to simulate.
      Returns:
      A SimulateTransactionResponse object containing the simulation result.
    • prepareTransaction

      public Transaction prepareTransaction(Transaction transaction)
      Submit a trial contract invocation, first run a simulation of the contract invocation as defined on the incoming transaction, and apply the results to a new copy of the transaction which is then returned. Setting the ledger footprint and authorization, so the resulting transaction is ready for signing and sending.

      The returned transaction will also have an updated fee that is the sum of fee set on incoming transaction with the contract resource fees estimated from simulation. It is advisable to check the fee on returned transaction and validate or take appropriate measures for interaction with user to confirm it is acceptable.

      You can call the simulateTransaction(org.stellar.sdk.Transaction, org.stellar.sdk.requests.sorobanrpc.SimulateTransactionRequest.ResourceConfig, org.stellar.sdk.requests.sorobanrpc.SimulateTransactionRequest.AuthMode, boolean) method directly first if you want to inspect estimated fees for a given transaction in detail first, if that is of importance.

      The underlying simulation records ADDRESS_V2 (CAP-71) authorization credentials; use prepareTransaction(Transaction, boolean) to ask for the legacy ADDRESS credentials.

      Parameters:
      transaction - The transaction to prepare. It should include exactly one operation, which must be one of InvokeHostFunctionOperation, ExtendFootprintTTLOperation, or RestoreFootprintOperation. Any provided footprint will be ignored. You can use Transaction.isSorobanTransaction() to check if a transaction is a Soroban transaction. Any provided footprint will be overwritten. However, if your operation has existing auth entries, they will be preferred over ALL auth entries from the simulation. In other words, if you include auth entries, you don't care about the auth returned from the simulation. Other fields (footprint, etc.) will be filled as normal.
      Returns:
      Returns a copy of the Transaction, with the expected authorizations (in the case of invocation) and ledger footprint added. The transaction fee will also automatically be padded with the contract's minimum resource fees discovered from the simulation.
      Throws:
      PrepareTransactionException - If preparing the transaction fails.
      NetworkException - All the exceptions below are subclasses of NetworkException
      SorobanRpcException - If the Stellar RPC instance returns an error response.
      RequestTimeoutException - If the request timed out.
      ConnectionErrorException - When the request cannot be executed due to cancellation or connectivity problems, etc.
    • prepareTransaction

      public Transaction prepareTransaction(Transaction transaction, boolean useUpgradedAuth)
      Submit a trial contract invocation, first run a simulation of the contract invocation as defined on the incoming transaction, and apply the results to a new copy of the transaction which is then returned.

      Same as prepareTransaction(Transaction), but lets you choose the authorization credential format recorded by the underlying simulation.

      Parameters:
      transaction - The transaction to prepare, see prepareTransaction(Transaction).
      useUpgradedAuth - Whether the underlying simulation records ADDRESS_V2 ("upgraded") authorization credentials (CAP-71) instead of the legacy ADDRESS credentials. Pass false to ask for the legacy format. It only affects the recording auth modes. This flag is transitional: once the network returns ADDRESS_V2 credentials by default (protocol 28), it becomes a no-op.
      Returns:
      Returns a copy of the Transaction, with the expected authorizations (in the case of invocation) and ledger footprint added. The transaction fee will also automatically be padded with the contract's minimum resource fees discovered from the simulation.
      Throws:
      PrepareTransactionException - If preparing the transaction fails.
      NetworkException - All the exceptions below are subclasses of NetworkException
      SorobanRpcException - If the Stellar RPC instance returns an error response.
      RequestTimeoutException - If the request timed out.
      ConnectionErrorException - When the request cannot be executed due to cancellation or connectivity problems, etc.
    • prepareTransaction

      public Transaction prepareTransaction(Transaction transaction, SimulateTransactionResponse simulateTransactionResponse)
      Prepare the transaction using the simulateTransaction obtained by the user in advance, apply the simulateTransaction results to a new copy of the transaction which is then returned. Setting the ledger footprint and authorization, so the resulting transaction is ready for signing and sending.

      The returned transaction will also have an updated fee that is the sum of fee set on incoming transaction with the contract resource fees estimated from simulation. It is advisable to check the fee on returned transaction and validate or take appropriate measures for interaction with user to confirm it is acceptable.

      Parameters:
      transaction - The transaction to prepare. It should include exactly one operation, which must be one of InvokeHostFunctionOperation, ExtendFootprintTTLOperation, or RestoreFootprintOperation. Any provided footprint will be ignored. You can use Transaction.isSorobanTransaction() to check if a transaction is a Soroban transaction. Any provided footprint will be overwritten. However, if your operation has existing auth entries, they will be preferred over ALL auth entries from the simulation. In other words, if you include auth entries, you don't care about the auth returned from the simulation. Other fields (footprint, etc.) will be filled as normal.
      simulateTransactionResponse - The SimulateTransactionResponse to use for preparing the transaction.
      Returns:
      Returns a copy of the Transaction, with the expected authorizations (in the case of invocation) and ledger footprint added. The transaction fee will also automatically be padded with the contract's minimum resource fees discovered from the simulation.
      Throws:
      PrepareTransactionException - If preparing the transaction fails.
    • sendTransaction

      public SendTransactionResponse sendTransaction(Transaction transaction)
      Submit a real transaction to the Stellar network. This is the only way to make changes "on-chain". Unlike Horizon, Stellar RPC does not wait for transaction completion. It simply validates the transaction and enqueues it. Clients should call getTransaction(java.lang.String) to learn about transaction's status.
      Parameters:
      transaction - The transaction to submit.
      Returns:
      A SendTransactionResponse object containing some details about the transaction that was submitted.
      Throws:
      NetworkException - All the exceptions below are subclasses of NetworkException
      SorobanRpcException - If the Stellar RPC instance returns an error response.
      RequestTimeoutException - If the request timed out.
      ConnectionErrorException - When the request cannot be executed due to cancellation or connectivity problems, etc.
      See Also:
    • getSACBalance

      public GetSACBalanceResponse getSACBalance(String contractId, Asset asset, Network network)
      Fetches the balance of a specific asset for a contract. This is useful for checking the balance of a contract in a specific asset.
      Parameters:
      contractId - The contract ID containing the asset balance. Encoded as Stellar Contract Address. e.g. CAB...
      asset - The asset to check the balance for. This should be a valid asset object.
      network - The network to use for the asset.
      Returns:
      A GetSACBalanceResponse which will contain the balance entry details if and only if the request returned a valid balance ledger entry. If it doesn't, the balanceEntry field will not exist.
      See Also:
    • getExternalRefWasmHash

      public byte[] getExternalRefWasmHash(ContractExecutableExternalRef externalRef)
      Resolves a CAP-85 external executable reference to the Wasm hash it names.

      A contract created from an external reference does not carry its own Wasm hash. Instead the reference names an owner contract and a tag, and the owner holds a persistent contract data entry keyed by that tag whose value is the 32-byte hash of an existing Wasm. This performs exactly that lookup; the owner contract is not invoked.

      Example:

      
       ContractExecutable executable = instance.getExecutable();
       if (executable.getDiscriminant() == ContractExecutableType.CONTRACT_EXECUTABLE_EXTERNAL_REF) {
         byte[] wasmHash = server.getExternalRefWasmHash(executable.getExternal_ref());
         byte[] wasm = server.getContractWasmByHash(wasmHash);
       }
       
      Parameters:
      externalRef - The external executable reference, for example the external_ref arm of a contract instance's executable.
      Returns:
      The 32-byte Wasm hash the reference resolves to.
      Throws:
      IllegalArgumentException - If externalRef is null or structurally incomplete, or its owner is not a contract and so cannot hold the tag entry that names the Wasm.
      ExternalRefNotFoundException - If the tag entry does not exist or has been archived.
      ContractWasmRetrievalException - If the tag entry does not hold a 32-byte Wasm hash, or the RPC response contains unexpected ledger entry data.
      NetworkException - The following three exceptions are subclasses of NetworkException, thrown on RPC or transport failures.
      SorobanRpcException - If the Stellar RPC instance returns an error response.
      RequestTimeoutException - If the request timed out.
      ConnectionErrorException - When the request cannot be executed due to cancellation or connectivity problems, etc.
    • getContractWasm

      public byte[] getContractWasm(String contractId)
      Fetches the Wasm bytecode of a deployed contract by its contract ID.

      This first reads the contract instance ledger entry to discover the executable, then fetches the CONTRACT_CODE ledger entry referenced by the instance.

      A contract created from a CAP-85 external executable reference carries no Wasm hash of its own, so its reference is resolved to one first (see getExternalRefWasmHash(ContractExecutableExternalRef)) at the cost of one extra request.

      Parameters:
      contractId - The contract ID. Encoded as a Stellar Contract Address.
      Returns:
      The contract Wasm bytecode.
      Throws:
      IllegalArgumentException - If the contract ID is not a valid contract strkey.
      ContractInstanceNotFoundException - If the contract instance ledger entry does not exist.
      StellarAssetContractHasNoWasmException - If the contract is a Stellar Asset Contract, which has no Wasm.
      ExternalRefNotFoundException - If the contract follows an external executable reference whose tag entry does not exist or has been archived.
      ContractCodeNotFoundException - If the contract code ledger entry does not exist or has been archived.
      ContractWasmRetrievalException - If the RPC response contains unexpected ledger entry data, including an external executable reference the instance holds that cannot be resolved, such as one whose owner is not a contract.
      NetworkException - The following three exceptions are subclasses of NetworkException, thrown on RPC or transport failures.
      SorobanRpcException - If the Stellar RPC instance returns an error response.
      RequestTimeoutException - If the request timed out.
      ConnectionErrorException - When the request cannot be executed due to cancellation or connectivity problems, etc.
    • getContractWasmByHash

      public byte[] getContractWasmByHash(byte[] wasmHash)
      Fetches the Wasm bytecode of a deployed contract by its Wasm hash.
      Parameters:
      wasmHash - The 32-byte Wasm hash.
      Returns:
      The contract Wasm bytecode.
      Throws:
      IllegalArgumentException - If wasmHash is null or not 32 bytes.
      ContractCodeNotFoundException - If the contract code ledger entry does not exist or has been archived.
      ContractWasmRetrievalException - If the RPC response contains unexpected ledger entry data.
      NetworkException - The following three exceptions are subclasses of NetworkException, thrown on RPC or transport failures.
      SorobanRpcException - If the Stellar RPC instance returns an error response.
      RequestTimeoutException - If the request timed out.
      ConnectionErrorException - When the request cannot be executed due to cancellation or connectivity problems, etc.
    • getContractMeta

      public ContractMeta getContractMeta(String contractId)
      Fetches and parses the SEP-0046 metadata of a deployed contract.

      This method fetches the contract Wasm and parses it locally. When you need more than one introspection view from the same contract, prefer getContractInfo(String) to avoid fetching the Wasm multiple times.

      Parameters:
      contractId - The contract ID, encoded as a Stellar Contract Address.
      Returns:
      The parsed ContractMeta.
      See Also:
    • getContractSpec

      public ContractSpec getContractSpec(String contractId)
      Fetches and parses the SEP-0048 interface specification of a deployed contract.

      This method fetches the contract Wasm and parses it locally. When you need more than one introspection view from the same contract, prefer getContractInfo(String) to avoid fetching the Wasm multiple times.

      Parameters:
      contractId - The contract ID, encoded as a Stellar Contract Address.
      Returns:
      The parsed ContractSpec.
      See Also:
    • getContractInfo

      public ContractInfo getContractInfo(String contractId)
      Fetches and parses the SEP-0046 metadata, SEP-0048 specification, and environment metadata of a deployed contract.

      This method issues two RPC requests (one for the contract instance ledger entry, one for the contract code ledger entry) and parses the Wasm a single time. Prefer this over calling getContractMeta(java.lang.String) and getContractSpec(java.lang.String) separately when more than one view is needed.

      Parameters:
      contractId - The contract ID, encoded as a Stellar Contract Address.
      Returns:
      The parsed ContractInfo.
      See Also:
    • assembleTransaction

      public static Transaction assembleTransaction(Transaction transaction, SimulateTransactionResponse simulateTransactionResponse)
    • close

      public void close() throws IOException
      Specified by:
      close in interface AutoCloseable
      Specified by:
      close in interface Closeable
      Throws:
      IOException