Class

Server

rpc.Server(serverURL, optsopt)

Handles the network connection to a Soroban RPC instance, exposing an interface for requests to that instance.

Constructor

# new Server(serverURL, optsopt)

Parameters:
Name Type Attributes Description
serverURL string

Soroban-RPC Server URL (ex. http://localhost:8000/soroban/rpc).

opts module:rpc.Server.Options <optional>

Options object

allowHttp boolean <optional>

Allows connecting to insecure http servers (default: false). This must be set to false in production deployments! You can also use Config class to set this globally.

headers Record.<string, string> <optional>

Allows setting custom headers

See:

View Source lib/rpc/server.js, line 116

Members

URI

# serverURL

RPC Server URL (ex. http://localhost:8000/soroban/rpc).

View Source lib/rpc/server.js, line 122

number

# static constant SUBMIT_TRANSACTION_TIMEOUT

Default transaction submission timeout for RPC requests, in milliseconds

Default Value:
  • 60000

View Source lib/rpc/server.js, line 28

Methods

# async getAccount(address) → {Promise.<Account>}

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:
Name Type Description
address string

The public address of the account to load.

See:

View Source lib/rpc/server.js, line 153

A promise which resolves to the Account object with a populated sequence number

Promise.<Account>
Example
const accountId = "GBZC6Y2Y7Q3ZQ2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4";
server.getAccount(accountId).then((account) => {
  console.log("sequence:", account.sequence);
});

# async getContractData(contract, key, durabilityopt) → {Promise.<Api.LedgerEntryResult>}

Reads the current value of contract data ledger entries directly.

Allows you to directly inspect the current state of a contract. This is a backup way to access your contract data which may not be available via events or module:rpc.Server#simulateTransaction.

Parameters:
Name Type Attributes Default Description
contract string | Address | Contract

The contract ID containing the data to load as a strkey (C... form), a Contract, or an Address instance

key xdr.ScVal

The key of the contract data to load

durability module:rpc.Durability <optional>
Durability.Persistent

The "durability keyspace" that this ledger key belongs to, which is either 'temporary' or 'persistent' (the default), see module:rpc.Durability.

See:

View Source lib/rpc/server.js, line 220

The current data value

Promise.<Api.LedgerEntryResult>
Example
const contractId = "CCJZ5DGASBWQXR5MPFCJXMBI333XE5U3FSJTNQU7RIKE3P5GN2K2WYD5";
const key = xdr.ScVal.scvSymbol("counter");
server.getContractData(contractId, key, Durability.Temporary).then(data => {
  console.log("value:", data.val);
  console.log("liveUntilLedgerSeq:", data.liveUntilLedgerSeq);
  console.log("lastModified:", data.lastModifiedLedgerSeq);
  console.log("latestLedger:", data.latestLedger);
});

# async getContractWasmByContractId(contractId) → {Promise.<Buffer>}

Retrieves the WASM bytecode for a given contract.

This method allows you to fetch the WASM bytecode associated with a contract deployed on the Soroban network. The WASM bytecode represents the executable code of the contract.

Parameters:
Name Type Description
contractId string

The contract ID containing the WASM bytecode to retrieve

View Source lib/rpc/server.js, line 281

If the contract or its associated WASM bytecode cannot be found on the network.

Error

A Buffer containing the WASM bytecode

Promise.<Buffer>
Example
const contractId = "CCJZ5DGASBWQXR5MPFCJXMBI333XE5U3FSJTNQU7RIKE3P5GN2K2WYD5";
server.getContractWasmByContractId(contractId).then(wasmBuffer => {
  console.log("WASM bytecode length:", wasmBuffer.length);
  // ... do something with the WASM bytecode ...
}).catch(err => {
  console.error("Error fetching WASM bytecode:", err);
});

# async getContractWasmByHash(wasmHash) → {Promise.<Buffer>}

Retrieves the WASM bytecode for a given contract hash.

This method allows you to fetch the WASM bytecode associated with a contract deployed on the Soroban network using the contract's WASM hash. The WASM bytecode represents the executable code of the contract.

Parameters:
Name Type Description
wasmHash Buffer

The WASM hash of the contract

View Source lib/rpc/server.js, line 316

If the contract or its associated WASM bytecode cannot be found on the network.

Error

A Buffer containing the WASM bytecode

Promise.<Buffer>
Example
const wasmHash = Buffer.from("...");
server.getContractWasmByHash(wasmHash).then(wasmBuffer => {
  console.log("WASM bytecode length:", wasmBuffer.length);
  // ... do something with the WASM bytecode ...
}).catch(err => {
  console.error("Error fetching WASM bytecode:", err);
});

# async getEvents(request) → {Promise.<Api.GetEventsResponse>}

Fetch all events that match a given set of filters.

The given filters (see Api.EventFilter for detailed fields) are combined only in a logical OR fashion, and all of the fields in each filter are optional.

To page through events, use the pagingToken field on the relevant Api.EventResponse object to set the cursor parameter.

Parameters:
Name Type Description
request module:rpc.Server.GetEventsRequest

Event filters

See:

View Source lib/rpc/server.js, line 543

A paginatable set of the events matching the given event filters

Promise.<Api.GetEventsResponse>
Example
server.getEvents({
   startLedger: 1000,
   endLedger: 2000,
   filters: [
    {
     type: "contract",
     contractIds: [ "deadb33f..." ],
     topics: [[ "AAAABQAAAAh0cmFuc2Zlcg==", "AAAAAQB6Mcc=", "*" ]]
    }, {
     type: "system",
     contractIds: [ "...c4f3b4b3..." ],
     topics: [[ "*" ], [ "*", "AAAAAQB6Mcc=" ]]
    }, {
     contractIds: [ "...c4f3b4b3..." ],
     topics: [[ "AAAABQAAAAh0cmFuc2Zlcg==" ]]
    }, {
     type: "diagnostic",
     topics: [[ "AAAAAQB6Mcc=" ]]
    }
   ],
   limit: 10,
});

# async getFeeStats() → {Promise.<Api.GetFeeStatsResponse>}

Provides an analysis of the recent fee stats for regular and smart contract operations.

See:

View Source lib/rpc/server.js, line 859

the fee stats

Promise.<Api.GetFeeStatsResponse>

# async getHealth() → {Promise.<Api.GetHealthResponse>}

General node health check.

See:

View Source lib/rpc/server.js, line 184

A promise which resolves to the Api.GetHealthResponse object with the status of the server (e.g. "healthy").

Promise.<Api.GetHealthResponse>
Example
server.getHealth().then((health) => {
  console.log("status:", health.status);
});

# async getLatestLedger() → {Promise.<Api.GetLatestLedgerResponse>}

Fetch the latest ledger meta info from network which this Soroban RPC server is connected to.

See:

View Source lib/rpc/server.js, line 606

metadata about the latest ledger on the network that this RPC server is connected to

Promise.<Api.GetLatestLedgerResponse>
Example
server.getLatestLedger().then((response) => {
  console.log("hash:", response.id);
  console.log("sequence:", response.sequence);
  console.log("protocolVersion:", response.protocolVersion);
});

# async getLedgerEntries(…keys) → {Promise.<Api.GetLedgerEntriesResponse>}

Reads the current value of arbitrary ledger entries directly.

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

To fetch a contract's WASM byte-code, built the appropriate xdr.LedgerKeyContractCode ledger entry key (or see Contract.getFootprint).

Parameters:
Name Type Attributes Description
keys Array.<xdr.ScVal> <repeatable>

One or more ledger entry keys to load

See:

View Source lib/rpc/server.js, line 366

The current on-chain values for the given ledger keys

Promise.<Api.GetLedgerEntriesResponse>
Example
const contractId = "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2KM";
const key = xdr.LedgerKey.contractData(new xdr.LedgerKeyContractData({
  contractId: StrKey.decodeContract(contractId),
  key: xdr.ScVal.scvSymbol("counter"),
}));

server.getLedgerEntries([key]).then(response => {
  const ledgerData = response.entries[0];
  console.log("key:", ledgerData.key);
  console.log("value:", ledgerData.val);
  console.log("liveUntilLedgerSeq:", ledgerData.liveUntilLedgerSeq);
  console.log("lastModified:", ledgerData.lastModifiedLedgerSeq);
  console.log("latestLedger:", response.latestLedger);
});

# async getNetwork() → {Promise.<Api.GetNetworkResponse>}

Fetch metadata about the network this Soroban RPC server is connected to.

See:

View Source lib/rpc/server.js, line 585

Metadata about the current network this RPC server is connected to

Promise.<Api.GetNetworkResponse>
Example
server.getNetwork().then((network) => {
  console.log("friendbotUrl:", network.friendbotUrl);
  console.log("passphrase:", network.passphrase);
  console.log("protocolVersion:", network.protocolVersion);
});

# async getSACBalance(contractId, sac, networkPassphraseopt) → {Promise.<Api.BalanceResponse>}

Returns a contract's balance of a particular SAC asset, if any.

This is a convenience wrapper around Server.getLedgerEntries.

Parameters:
Name Type Attributes Description
contractId string

the contract ID (string C...) whose balance of sac you want to know

sac Asset

the built-in SAC token (e.g. USDC:GABC...) that you are querying from the given contract.

networkPassphrase string <optional>

optionally, the network passphrase to which this token applies. If omitted, a request about network information will be made (see getNetwork), since contract IDs for assets are specific to a network. You can refer to Networks for a list of built-in passphrases, e.g., Networks.TESTNET.

See:

View Source lib/rpc/server.js, line 913

If contractId is not a valid contract strkey (C...).

TypeError

, 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.

Promise.<Api.BalanceResponse>
Example
// assume `contractId` is some contract with an XLM balance
// assume server is an instantiated `Server` instance.
const entry = (await server.getSACBalance(
  new Address(contractId),
  Asset.native(),
  Networks.PUBLIC
));

// assumes BigInt support:
console.log(
  entry.balanceEntry ?
  BigInt(entry.balanceEntry.amount) :
  "Contract has no XLM");

# async getTransaction(hash) → {Promise.<Api.GetTransactionResponse>}

Fetch the details of a submitted transaction.

After submitting a transaction, clients should poll this to tell when the transaction has completed.

Parameters:
Name Type Description
hash string

Hex-encoded hash of the transaction to check

See:

View Source lib/rpc/server.js, line 439

The status, result, and other details about the transaction

Promise.<Api.GetTransactionResponse>
Example
const transactionHash = "c4515e3bdc0897f21cc5dbec8c82cf0a936d4741cb74a8e158eb51b9fb00411a";
server.getTransaction(transactionHash).then((tx) => {
  console.log("status:", tx.status);
  console.log("envelopeXdr:", tx.envelopeXdr);
  console.log("resultMetaXdr:", tx.resultMetaXdr);
  console.log("resultXdr:", tx.resultXdr);
});

# async getTransactions(request) → {Promise.<Api.GetTransactionsResponse>}

Fetch transactions starting from a given start ledger or a cursor. The end ledger is the latest ledger in that RPC instance.

Parameters:
Name Type Description
request Api.GetTransactionsRequest

The request parameters.

See:

View Source lib/rpc/server.js, line 483

  • A promise that resolves to the transactions response.
Promise.<Api.GetTransactionsResponse>
Example
server.getTransactions({
  startLedger: 10000,
  limit: 10,
}).then((response) => {
  console.log("Transactions:", response.transactions);
  console.log("Latest Ledger:", response.latestLedger);
  console.log("Cursor:", response.cursor);
});

# async getVersionInfo() → {Promise.<Api.GetVersionInfoResponse>}

Provides information about the current version details of the Soroban RPC and captive-core

See:

View Source lib/rpc/server.js, line 870

the version info

Promise.<Api.GetVersionInfoResponse>

# async pollTransaction(hash) → {Promise.<Api.GetTransactionsResponse>}

Poll for a particular transaction with certain parameters.

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

Parameters:
Name Type Attributes Description
hash string

the transaction you're polling for

opts.attempts number <optional>

(optional) the number of attempts to make before returning the last-seen status. By default or on invalid inputs, try 5 times.

opts.sleepStrategy SleepStrategy <optional>

(optional) the amount of time to wait for between each attempt. By default, sleep for 1 second between each attempt.

View Source lib/rpc/server.js, line 402

the response after a "found" response (which may be success or failure) or the last response obtained after polling the maximum number of specified attempts.

Promise.<Api.GetTransactionsResponse>
Example
const h = "c4515e3bdc0897f21cc5dbec8c82cf0a936d4741cb74a8e158eb51b9fb00411a";
const txStatus = await server.pollTransaction(h, {
   attempts: 100, // I'm a maniac
   sleepStrategy: rpc.LinearSleepStrategy
}); // this will take 5,050 seconds to complete

# async prepareTransaction(tx) → {Promise.<(Transaction|FeeBumpTransaction)>}

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 & 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 module:rpc.Server#simulateTransaction method directly first if you want to inspect estimated fees for a given transaction in detail first, then re-assemble it manually or via module:rpc.assembleTransaction.

Parameters:
Name Type Description
tx Transaction | FeeBumpTransaction

the transaction to prepare. It should include exactly one operation, which must be one of xdr.InvokeHostFunctionOp, xdr.ExtendFootprintTTLOp, or xdr.RestoreFootprintOp.

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.

See:

View Source lib/rpc/server.js, line 738

If simulation fails

jsonrpc.Error.<any> | Error | Api.SimulateTransactionErrorResponse

A copy of the transaction with the expected authorizations (in the case of invocation), resources, and ledger footprints added. The transaction fee will also automatically be padded with the contract's minimum resource fees discovered from the simulation.

Promise.<(Transaction|FeeBumpTransaction)>
Example
const contractId = 'CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE';
const contract = new StellarSdk.Contract(contractId);

// Right now, this is just the default fee for this example.
const fee = StellarSdk.BASE_FEE;
const transaction = new StellarSdk.TransactionBuilder(account, { fee })
  // Uncomment the following line to build transactions for the live network. Be
  // sure to also change the horizon hostname.
  //.setNetworkPassphrase(StellarSdk.Networks.PUBLIC)
  .setNetworkPassphrase(StellarSdk.Networks.FUTURENET)
  .setTimeout(30) // valid for the next 30s
  // Add an operation to call increment() on the contract
  .addOperation(contract.call("increment"))
  .build();

const preparedTransaction = await server.prepareTransaction(transaction);

// Sign this transaction with the secret key
// NOTE: signing is transaction is network specific. Test network transactions
// won't work in the public network. To switch networks, use the Network object
// as explained above (look for StellarSdk.Network).
const sourceKeypair = StellarSdk.Keypair.fromSecret(sourceSecretKey);
preparedTransaction.sign(sourceKeypair);

server.sendTransaction(transaction).then(result => {
  console.log("hash:", result.hash);
  console.log("status:", result.status);
  console.log("errorResultXdr:", result.errorResultXdr);
});

# async requestAirdrop(address, friendbotUrlopt) → {Promise.<Account>}

Fund a new account using the network's Friendbot faucet, if any.

Parameters:
Name Type Attributes Description
address string | Account

The address or account instance that we want to create and fund with Friendbot

friendbotUrl string <optional>

Optionally, an explicit address for friendbot (by default: this calls the Soroban RPC getNetwork method to try to discover this network's Friendbot url).

See:

View Source lib/rpc/server.js, line 829

If Friendbot is not configured on this network or request failure

An Account object for the created account, or the existing account if it's already funded with the populated sequence number (note that the account will not be "topped off" if it already exists)

Promise.<Account>
Example
server
   .requestAirdrop("GBZC6Y2Y7Q3ZQ2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4")
   .then((accountCreated) => {
     console.log("accountCreated:", accountCreated);
   }).catch((error) => {
     console.error("error:", error);
   });

# async sendTransaction(transaction) → {Promise.<Api.SendTransactionResponse>}

Submit a real transaction to the Stellar network.

Unlike Horizon, Soroban RPC does not wait for transaction completion. It simply validates the transaction and enqueues it. Clients should call module:rpc.Server#getTransaction to learn about transaction success/failure.

Parameters:
Name Type Description
transaction Transaction | FeeBumpTransaction

to submit

See:

View Source lib/rpc/server.js, line 791

the transaction id, status, and any error if available

Promise.<Api.SendTransactionResponse>
Example
const contractId = 'CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE';
const contract = new StellarSdk.Contract(contractId);

// Right now, this is just the default fee for this example.
const fee = StellarSdk.BASE_FEE;
const transaction = new StellarSdk.TransactionBuilder(account, { fee })
  // Uncomment the following line to build transactions for the live network. Be
  // sure to also change the horizon hostname.
  //.setNetworkPassphrase(StellarSdk.Networks.PUBLIC)
  .setNetworkPassphrase(StellarSdk.Networks.FUTURENET)
  .setTimeout(30) // valid for the next 30s
  // Add an operation to call increment() on the contract
  .addOperation(contract.call("increment"))
  .build();

// Sign this transaction with the secret key
// NOTE: signing is transaction is network specific. Test network transactions
// won't work in the public network. To switch networks, use the Network object
// as explained above (look for StellarSdk.Network).
const sourceKeypair = StellarSdk.Keypair.fromSecret(sourceSecretKey);
transaction.sign(sourceKeypair);

server.sendTransaction(transaction).then((result) => {
  console.log("hash:", result.hash);
  console.log("status:", result.status);
  console.log("errorResultXdr:", result.errorResultXdr);
});

# async simulateTransaction(tx) → {Promise.<Api.SimulateTransactionResponse>}

Submit a trial contract invocation to get back return values, expected ledger footprint, expected authorizations, and expected costs.

Parameters:
Name Type Description
tx Transaction | FeeBumpTransaction

the transaction to simulate, which should include exactly one operation (one of xdr.InvokeHostFunctionOp, xdr.ExtendFootprintTTLOp, or xdr.RestoreFootprintOp). Any provided footprint or auth information will be ignored.

See:

View Source lib/rpc/server.js, line 652

An object with the cost, footprint, result/auth requirements (if applicable), and error of the transaction

Promise.<Api.SimulateTransactionResponse>
Example
const contractId = 'CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE';
const contract = new StellarSdk.Contract(contractId);

// Right now, this is just the default fee for this example.
const fee = StellarSdk.BASE_FEE;
const transaction = new StellarSdk.TransactionBuilder(account, { fee })
  // Uncomment the following line to build transactions for the live network. Be
  // sure to also change the horizon hostname.
  //.setNetworkPassphrase(StellarSdk.Networks.PUBLIC)
  .setNetworkPassphrase(StellarSdk.Networks.FUTURENET)
  .setTimeout(30) // valid for the next 30s
  // Add an operation to call increment() on the contract
  .addOperation(contract.call("increment"))
  .build();

server.simulateTransaction(transaction).then((sim) => {
  console.log("cost:", sim.cost);
  console.log("result:", sim.result);
  console.log("error:", sim.error);
  console.log("latestLedger:", sim.latestLedger);
});

Type Definitions

object

# GetEventsRequest

Describes the complex filter combinations available for event queries.

Properties:
Name Type Attributes Default Description
filters Array.<module:rpc.Api.EventFilter>

Filters to use when querying events from the RPC server.

startLedger number <optional>

Ledger number (inclusive) to begin querying events.

cursor string <optional>

Page cursor (exclusive) to begin querying events.

limit number <optional>
100

The maximum number of events that should be returned in the RPC response.

View Source lib/rpc/server.js, line 43

object

# Options

Options for configuring connections to RPC servers.

Properties:
Name Type Attributes Default Description
allowHttp boolean <optional>
false

Allow connecting to http servers, default: false. This must be set to false in production deployments!

timeout number <optional>
0

Allow a timeout, default: 0. Allows user to avoid nasty lag. You can also use Config class to set this globally.

headers Record.<string, string> <optional>

Additional headers that should be added to any requests to the RPC server.

View Source lib/rpc/server.js, line 56

object

# ResourceLeeway

Describes additional resource leeways for transaction simulation.

Properties:
Name Type Description
cpuInstructions number

Simulate the transaction with more CPU instructions available.

View Source lib/rpc/server.js, line 51