Server

Server

Server handles the network connection to a Horizon instance and exposes an interface for requests to that instance.

Constructor

new Server(serverURL, optsopt)

serverURL Horizon Server URL (ex. https://horizon-testnet.stellar.org).

TODO: Solve URI(this.serverURL as any).

Source:
Parameters:
Name Type Attributes Description
serverURL string

Horizon Server URL (ex. https://horizon-testnet.stellar.org).

opts object <optional>

Options object

Name Type Attributes Description
allowHttp boolean <optional>

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

appName string <optional>

Allow set custom header X-App-Name, default: undefined.

appVersion string <optional>

Allow set custom header X-App-Version, default: undefined.

authToken string <optional>

Allow set custom header X-Auth-Token, default: undefined.

Methods

accounts() → {AccountCallBuilder}

Source:
Returns:
Type:
AccountCallBuilder

New AccountCallBuilder object configured by a current Horizon server configuration.

assets() → {AssetsCallBuilder}

Get a new AssetsCallBuilder instance configured with the current Horizon server configuration.

Source:
Returns:
Type:
AssetsCallBuilder

New AssetsCallBuilder instance

(async) checkMemoRequired(transaction) → {Promise.<void, Error>}

Check if any of the destination accounts requires a memo.

This function implements a memo required check as defined in SEP-29. It will load each account which is the destination and check if it has the data field config.memo_required set to "MQ==".

Each account is checked sequentially instead of loading multiple accounts at the same time from Horizon.

Source:
See:
Parameters:
Name Type Description
transaction Transaction

The transaction to check.

Returns:
Type:
Promise.<void, Error>

claimableBalances() → {ClaimableBalanceCallBuilder}

Source:
Returns:
Type:
ClaimableBalanceCallBuilder

New ClaimableBalanceCallBuilder object configured by a current Horizon server configuration.

effects() → {EffectCallBuilder}

Source:
Returns:
Type:
EffectCallBuilder

New EffectCallBuilder instance configured with the current Horizon server configuration

(async) feeStats() → {Promise.<HorizonApi.FeeStatsResponse>}

Fetch the fee stats endpoint.

Source:
See:
Returns:
Type:
Promise.<HorizonApi.FeeStatsResponse>

Promise that resolves to the fee stats returned by Horizon.

(async) fetchBaseFee() → {Promise.<number>}

Fetch the base fee. Since this hits the server, if the server call fails, you might get an error. You should be prepared to use a default value if that happens!

Source:
Returns:
Type:
Promise.<number>

Promise that resolves to the base fee.

(async) fetchTimebounds(seconds, _isRetryopt) → {Promise.<Timebounds>}

Get timebounds for N seconds from now, when you're creating a transaction with TransactionBuilder.

By default, TransactionBuilder uses the current local time, but your machine's local time could be different from Horizon's. This gives you more assurance that your timebounds will reflect what you want.

Note that this will generate your timebounds when you init the transaction, not when you build or submit the transaction! So give yourself enough time to get the transaction built and signed before submitting.

Example:

const transaction = new StellarSdk.TransactionBuilder(accountId, {
 fee: await StellarSdk.Server.fetchBaseFee(),
 timebounds: await StellarSdk.Server.fetchTimebounds(100)
})
 .addOperation(operation)
 // normally we would need to call setTimeout here, but setting timebounds
 // earlier does the trick!
 .build();
Source:
Parameters:
Name Type Attributes Default Description
seconds number

Number of seconds past the current time to wait.

_isRetry bool <optional>
false

True if this is a retry. Only set this internally! This is to avoid a scenario where Horizon is horking up the wrong date.

Returns:
Type:
Promise.<Timebounds>

Promise that resolves a timebounds object (with the shape { minTime: 0, maxTime: N }) that you can set the timebounds option to.

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

Source:
See:
Parameters:
Name Type Description
address string

The public address of the account to load.

Returns:
Type:
Promise.<Account>

a promise to the Account object with a populated sequence number

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 Server.simulateTransaction.

Source:
See:
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 Durability <optional>
Durability.Persistent

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

Returns:
Type:
Promise.<Api.LedgerEntryResult>

the current data value

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.

Source:
Parameters:
Name Type Description
contractId string

the contract ID containing the WASM bytecode to retrieve

Throws:

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

Type
Error
Returns:
Type:
Promise.<Buffer>

a Buffer containing the WASM bytecode

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.

Source:
Parameters:
Name Type Description
wasmHash Buffer

the WASM hash of the contract

Throws:

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

Type
Error
Returns:
Type:
Promise.<Buffer>

a Buffer containing the WASM bytecode

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.

Source:
See:
Parameters:
Name Type Description
request Server.GetEventsRequest

event filters

Returns:
Type:
Promise.<Api.GetEventsResponse>

a paginatable set of the events matching the given event filters

Example
server.getEvents({
   startLedger: 1000,
   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) getHealth() → {Promise.<Api.GetHealthResponse>}

General node health check.

Source:
See:
Returns:
Type:
Promise.<Api.GetHealthResponse>

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

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.

Source:
See:
Returns:
Type:
Promise.<Api.GetLatestLedgerResponse>

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

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

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

one or more ledger entry keys to load

Returns:
Type:
Promise.<Api.GetLedgerEntriesResponse>

the current on-chain values for the given ledger keys

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.

Source:
See:
Returns:
Type:
Promise.<Api.GetNetworkResponse>

metadata about the current network this RPC server is connected to

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

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

Source:
See:
Parameters:
Name Type Description
hash string

hex-encoded hash of the transaction to check

Returns:
Type:
Promise.<Api.GetTransactionResponse>

the status, result, and other details about the transaction

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);
});

ledgers() → {LedgerCallBuilder}

Source:
Returns:
Type:
LedgerCallBuilder

New LedgerCallBuilder object configured by a current Horizon server configuration.

liquidityPools() → {LiquidityPoolCallBuilder}

Source:
Returns:
Type:
LiquidityPoolCallBuilder

New LiquidityPoolCallBuilder object configured to the current Horizon server settings.

(async) loadAccount(accountId) → {Promise}

Fetches an account's most current state in the ledger, then creates and returns an AccountResponse object.

Source:
Parameters:
Name Type Description
accountId string

The account to load.

Returns:
Type:
Promise

Returns a promise to the AccountResponse object with populated sequence number.

offers() → {OfferCallBuilder}

People on the Stellar network can make offers to buy or sell assets. This endpoint represents all the offers on the DEX.

You can query all offers for account using the function .accountId:

server.offers()
 .forAccount(accountId).call()
 .then(function(offers) {
   console.log(offers);
 });
Source:
Returns:
Type:
OfferCallBuilder

New OfferCallBuilder object

operations() → {OperationCallBuilder}

Source:
Returns:
Type:
OperationCallBuilder

New OperationCallBuilder object configured by a current Horizon server configuration.

orderbook(selling, buying) → {OrderbookCallBuilder}

Source:
Parameters:
Name Type Description
selling Asset

Asset being sold

buying Asset

Asset being bought

Returns:
Type:
OrderbookCallBuilder

New OrderbookCallBuilder object configured by a current Horizon server configuration.

payments() → {PaymentCallBuilder}

Source:
Returns:
Type:
PaymentCallBuilder

New PaymentCallBuilder instance configured with the current Horizon server configuration.

(async) prepareTransaction(transaction) → {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 adviseable 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 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 assembleTransaction.

Source:
See:
Parameters:
Name Type Description
transaction 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.

Throws:

if simulation fails

Type
jsonrpc.Error.<any> | Error | Api.SimulateTransactionErrorResponse
Returns:
Type:
Promise.<(Transaction|FeeBumpTransaction)>

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.

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.

Source:
See:
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 Server.getNetwork method to try to discover this network's Friendbot url).

Throws:

if Friendbot is not configured on this network or request failure

Returns:
Type:
Promise.<Account>

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)

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 Server.getTransactionStatus to learn about transaction success/failure.

Source:
See:
Parameters:
Name Type Description
transaction Transaction | FeeBumpTransaction

to submit

Returns:
Type:
Promise.<Api.SendTransactionResponse>

the transaction id, status, and any error if available

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(transaction) → {Promise.<Api.SimulateTransactionResponse>}

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

Source:
See:
Parameters:
Name Type Description
transaction 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.

Returns:
Type:
Promise.<Api.SimulateTransactionResponse>

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

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);
});

strictReceivePaths(source, destinationAsset, destinationAmount) → {StrictReceivePathCallBuilder}

The Stellar Network allows payments to be made between assets through path payments. A strict receive path payment specifies a series of assets to route a payment through, from source asset (the asset debited from the payer) to destination asset (the asset credited to the payee).

A strict receive path search is specified using:

  • The destination address.
  • The source address or source assets.
  • The asset and amount that the destination account should receive.

As part of the search, horizon will load a list of assets available to the source address and will find any payment paths from those source assets to the desired destination asset. The search's amount parameter will be used to determine if there a given path can satisfy a payment of the desired amount.

If a list of assets is passed as the source, horizon will find any payment paths from those source assets to the desired destination asset.

Source:
Parameters:
Name Type Description
source string | Array.<Asset>

The sender's account ID or a list of assets. Any returned path will use a source that the sender can hold.

destinationAsset Asset

The destination asset.

destinationAmount string

The amount, denominated in the destination asset, that any returned path should be able to satisfy.

Returns:
Type:
StrictReceivePathCallBuilder

New StrictReceivePathCallBuilder object configured with the current Horizon server configuration.

strictSendPaths(sourceAsset, sourceAmount, destination) → {StrictSendPathCallBuilder}

The Stellar Network allows payments to be made between assets through path payments. A strict send path payment specifies a series of assets to route a payment through, from source asset (the asset debited from the payer) to destination asset (the asset credited to the payee).

A strict send path search is specified using:

The asset and amount that is being sent. The destination account or the destination assets.

Source:
Parameters:
Name Type Description
sourceAsset Asset

The asset to be sent.

sourceAmount string

The amount, denominated in the source asset, that any returned path should be able to satisfy.

destination string | Array.<Asset>

The destination account or the destination assets.

Returns:
Type:
StrictSendPathCallBuilder

New StrictSendPathCallBuilder object configured with the current Horizon server configuration.

(async) submitTransaction(transaction, optsopt) → {Promise}

Submits a transaction to the network.

By default this function calls Server#checkMemoRequired, you can skip this check by setting the option skipMemoRequiredCheck to true.

If you submit any number of manageOffer operations, this will add an attribute to the response that will help you analyze what happened with your offers.

Ex:

const res = {
  ...response,
  offerResults: [
    {
      // Exact ordered list of offers that executed, with the exception
      // that the last one may not have executed entirely.
      offersClaimed: [
        sellerId: String,
        offerId: String,
        assetSold: {
          type: 'native|credit_alphanum4|credit_alphanum12',

          // these are only present if the asset is not native
          assetCode: String,
          issuer: String,
        },

        // same shape as assetSold
        assetBought: {}
      ],

      // What effect your manageOffer op had
      effect: "manageOfferCreated|manageOfferUpdated|manageOfferDeleted",

      // Whether your offer immediately got matched and filled
      wasImmediatelyFilled: Boolean,

      // Whether your offer immediately got deleted, if for example the order was too small
      wasImmediatelyDeleted: Boolean,

      // Whether the offer was partially, but not completely, filled
      wasPartiallyFilled: Boolean,

      // The full requested amount of the offer is open for matching
      isFullyOpen: Boolean,

      // The total amount of tokens bought / sold during transaction execution
      amountBought: Number,
      amountSold: Number,

      // if the offer was created, updated, or partially filled, this is
      // the outstanding offer
      currentOffer: {
        offerId: String,
        amount: String,
        price: {
          n: String,
          d: String,
        },

        selling: {
          type: 'native|credit_alphanum4|credit_alphanum12',

          // these are only present if the asset is not native
          assetCode: String,
          issuer: String,
        },

        // same as `selling`
        buying: {},
      },

      // the index of this particular operation in the op stack
      operationIndex: Number
    }
  ]
}

For example, you'll want to examine offerResults to add affordances like these to your app:

  • If wasImmediatelyFilled is true, then no offer was created. So if you normally watch the Server.offers endpoint for offer updates, you instead need to check Server.trades to find the result of this filled offer.
  • If wasImmediatelyDeleted is true, then the offer you submitted was deleted without reaching the orderbook or being matched (possibly because your amounts were rounded down to zero). So treat the just-submitted offer request as if it never happened.
  • If wasPartiallyFilled is true, you can tell the user that amountBought or amountSold have already been transferred.
Source:
See:
Parameters:
Name Type Attributes Description
transaction Transaction | FeeBumpTransaction

The transaction to submit.

opts object <optional>

Options object

Name Type Attributes Description
skipMemoRequiredCheck boolean <optional>

Allow skipping memo required check, default: false. See SEP0029.

Returns:
Type:
Promise

Promise that resolves or rejects with response from horizon.

tradeAggregation(base, counter, start_time, end_time, resolution, offset) → {TradeAggregationCallBuilder}

Source:
Parameters:
Name Type Description
base Asset

base asset

counter Asset

counter asset

start_time long

lower time boundary represented as millis since epoch

end_time long

upper time boundary represented as millis since epoch

resolution long

segment duration as millis since epoch. *Supported values are 5 minutes (300000), 15 minutes (900000), 1 hour (3600000), 1 day (86400000) and 1 week (604800000).

offset long

segments can be offset using this parameter. Expressed in milliseconds. *Can only be used if the resolution is greater than 1 hour. Value must be in whole hours, less than the provided resolution, and less than 24 hours. Returns new TradeAggregationCallBuilder object configured with the current Horizon server configuration.

Returns:
Type:
TradeAggregationCallBuilder

New TradeAggregationCallBuilder instance

trades() → {TradesCallBuilder}

Returns

Source:
Returns:
Type:
TradesCallBuilder

New TradesCallBuilder object configured by a current Horizon server configuration.

transactions() → {TransactionCallBuilder}

Source:
Returns:
Type:
TransactionCallBuilder

New TransactionCallBuilder object configured by a current Horizon server configuration.

Server

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

Constructor

new Server(serverURL, optsopt)

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

Source:
See:
Parameters:
Name Type Attributes Description
serverURL string

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

opts object <optional>

Options object

Name Type Attributes Description
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

Methods

accounts() → {AccountCallBuilder}

Source:
Returns:
Type:
AccountCallBuilder

New AccountCallBuilder object configured by a current Horizon server configuration.

assets() → {AssetsCallBuilder}

Get a new AssetsCallBuilder instance configured with the current Horizon server configuration.

Source:
Returns:
Type:
AssetsCallBuilder

New AssetsCallBuilder instance

(async) checkMemoRequired(transaction) → {Promise.<void, Error>}

Check if any of the destination accounts requires a memo.

This function implements a memo required check as defined in SEP-29. It will load each account which is the destination and check if it has the data field config.memo_required set to "MQ==".

Each account is checked sequentially instead of loading multiple accounts at the same time from Horizon.

Source:
See:
Parameters:
Name Type Description
transaction Transaction

The transaction to check.

Returns:
Type:
Promise.<void, Error>

claimableBalances() → {ClaimableBalanceCallBuilder}

Source:
Returns:
Type:
ClaimableBalanceCallBuilder

New ClaimableBalanceCallBuilder object configured by a current Horizon server configuration.

effects() → {EffectCallBuilder}

Source:
Returns:
Type:
EffectCallBuilder

New EffectCallBuilder instance configured with the current Horizon server configuration

(async) feeStats() → {Promise.<HorizonApi.FeeStatsResponse>}

Fetch the fee stats endpoint.

Source:
See:
Returns:
Type:
Promise.<HorizonApi.FeeStatsResponse>

Promise that resolves to the fee stats returned by Horizon.

(async) fetchBaseFee() → {Promise.<number>}

Fetch the base fee. Since this hits the server, if the server call fails, you might get an error. You should be prepared to use a default value if that happens!

Source:
Returns:
Type:
Promise.<number>

Promise that resolves to the base fee.

(async) fetchTimebounds(seconds, _isRetryopt) → {Promise.<Timebounds>}

Get timebounds for N seconds from now, when you're creating a transaction with TransactionBuilder.

By default, TransactionBuilder uses the current local time, but your machine's local time could be different from Horizon's. This gives you more assurance that your timebounds will reflect what you want.

Note that this will generate your timebounds when you init the transaction, not when you build or submit the transaction! So give yourself enough time to get the transaction built and signed before submitting.

Example:

const transaction = new StellarSdk.TransactionBuilder(accountId, {
 fee: await StellarSdk.Server.fetchBaseFee(),
 timebounds: await StellarSdk.Server.fetchTimebounds(100)
})
 .addOperation(operation)
 // normally we would need to call setTimeout here, but setting timebounds
 // earlier does the trick!
 .build();
Source:
Parameters:
Name Type Attributes Default Description
seconds number

Number of seconds past the current time to wait.

_isRetry bool <optional>
false

True if this is a retry. Only set this internally! This is to avoid a scenario where Horizon is horking up the wrong date.

Returns:
Type:
Promise.<Timebounds>

Promise that resolves a timebounds object (with the shape { minTime: 0, maxTime: N }) that you can set the timebounds option to.

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

Source:
See:
Parameters:
Name Type Description
address string

The public address of the account to load.

Returns:
Type:
Promise.<Account>

a promise to the Account object with a populated sequence number

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 Server.simulateTransaction.

Source:
See:
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 Durability <optional>
Durability.Persistent

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

Returns:
Type:
Promise.<Api.LedgerEntryResult>

the current data value

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.

Source:
Parameters:
Name Type Description
contractId string

the contract ID containing the WASM bytecode to retrieve

Throws:

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

Type
Error
Returns:
Type:
Promise.<Buffer>

a Buffer containing the WASM bytecode

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.

Source:
Parameters:
Name Type Description
wasmHash Buffer

the WASM hash of the contract

Throws:

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

Type
Error
Returns:
Type:
Promise.<Buffer>

a Buffer containing the WASM bytecode

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.

Source:
See:
Parameters:
Name Type Description
request Server.GetEventsRequest

event filters

Returns:
Type:
Promise.<Api.GetEventsResponse>

a paginatable set of the events matching the given event filters

Example
server.getEvents({
   startLedger: 1000,
   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) getHealth() → {Promise.<Api.GetHealthResponse>}

General node health check.

Source:
See:
Returns:
Type:
Promise.<Api.GetHealthResponse>

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

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.

Source:
See:
Returns:
Type:
Promise.<Api.GetLatestLedgerResponse>

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

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

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

one or more ledger entry keys to load

Returns:
Type:
Promise.<Api.GetLedgerEntriesResponse>

the current on-chain values for the given ledger keys

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.

Source:
See:
Returns:
Type:
Promise.<Api.GetNetworkResponse>

metadata about the current network this RPC server is connected to

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

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

Source:
See:
Parameters:
Name Type Description
hash string

hex-encoded hash of the transaction to check

Returns:
Type:
Promise.<Api.GetTransactionResponse>

the status, result, and other details about the transaction

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);
});

ledgers() → {LedgerCallBuilder}

Source:
Returns:
Type:
LedgerCallBuilder

New LedgerCallBuilder object configured by a current Horizon server configuration.

liquidityPools() → {LiquidityPoolCallBuilder}

Source:
Returns:
Type:
LiquidityPoolCallBuilder

New LiquidityPoolCallBuilder object configured to the current Horizon server settings.

(async) loadAccount(accountId) → {Promise}

Fetches an account's most current state in the ledger, then creates and returns an AccountResponse object.

Source:
Parameters:
Name Type Description
accountId string

The account to load.

Returns:
Type:
Promise

Returns a promise to the AccountResponse object with populated sequence number.

offers() → {OfferCallBuilder}

People on the Stellar network can make offers to buy or sell assets. This endpoint represents all the offers on the DEX.

You can query all offers for account using the function .accountId:

server.offers()
 .forAccount(accountId).call()
 .then(function(offers) {
   console.log(offers);
 });
Source:
Returns:
Type:
OfferCallBuilder

New OfferCallBuilder object

operations() → {OperationCallBuilder}

Source:
Returns:
Type:
OperationCallBuilder

New OperationCallBuilder object configured by a current Horizon server configuration.

orderbook(selling, buying) → {OrderbookCallBuilder}

Source:
Parameters:
Name Type Description
selling Asset

Asset being sold

buying Asset

Asset being bought

Returns:
Type:
OrderbookCallBuilder

New OrderbookCallBuilder object configured by a current Horizon server configuration.

payments() → {PaymentCallBuilder}

Source:
Returns:
Type:
PaymentCallBuilder

New PaymentCallBuilder instance configured with the current Horizon server configuration.

(async) prepareTransaction(transaction) → {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 adviseable 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 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 assembleTransaction.

Source:
See:
Parameters:
Name Type Description
transaction 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.

Throws:

if simulation fails

Type
jsonrpc.Error.<any> | Error | Api.SimulateTransactionErrorResponse
Returns:
Type:
Promise.<(Transaction|FeeBumpTransaction)>

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.

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.

Source:
See:
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 Server.getNetwork method to try to discover this network's Friendbot url).

Throws:

if Friendbot is not configured on this network or request failure

Returns:
Type:
Promise.<Account>

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)

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 Server.getTransactionStatus to learn about transaction success/failure.

Source:
See:
Parameters:
Name Type Description
transaction Transaction | FeeBumpTransaction

to submit

Returns:
Type:
Promise.<Api.SendTransactionResponse>

the transaction id, status, and any error if available

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(transaction) → {Promise.<Api.SimulateTransactionResponse>}

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

Source:
See:
Parameters:
Name Type Description
transaction 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.

Returns:
Type:
Promise.<Api.SimulateTransactionResponse>

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

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);
});

strictReceivePaths(source, destinationAsset, destinationAmount) → {StrictReceivePathCallBuilder}

The Stellar Network allows payments to be made between assets through path payments. A strict receive path payment specifies a series of assets to route a payment through, from source asset (the asset debited from the payer) to destination asset (the asset credited to the payee).

A strict receive path search is specified using:

  • The destination address.
  • The source address or source assets.
  • The asset and amount that the destination account should receive.

As part of the search, horizon will load a list of assets available to the source address and will find any payment paths from those source assets to the desired destination asset. The search's amount parameter will be used to determine if there a given path can satisfy a payment of the desired amount.

If a list of assets is passed as the source, horizon will find any payment paths from those source assets to the desired destination asset.

Source:
Parameters:
Name Type Description
source string | Array.<Asset>

The sender's account ID or a list of assets. Any returned path will use a source that the sender can hold.

destinationAsset Asset

The destination asset.

destinationAmount string

The amount, denominated in the destination asset, that any returned path should be able to satisfy.

Returns:
Type:
StrictReceivePathCallBuilder

New StrictReceivePathCallBuilder object configured with the current Horizon server configuration.

strictSendPaths(sourceAsset, sourceAmount, destination) → {StrictSendPathCallBuilder}

The Stellar Network allows payments to be made between assets through path payments. A strict send path payment specifies a series of assets to route a payment through, from source asset (the asset debited from the payer) to destination asset (the asset credited to the payee).

A strict send path search is specified using:

The asset and amount that is being sent. The destination account or the destination assets.

Source:
Parameters:
Name Type Description
sourceAsset Asset

The asset to be sent.

sourceAmount string

The amount, denominated in the source asset, that any returned path should be able to satisfy.

destination string | Array.<Asset>

The destination account or the destination assets.

Returns:
Type:
StrictSendPathCallBuilder

New StrictSendPathCallBuilder object configured with the current Horizon server configuration.

(async) submitTransaction(transaction, optsopt) → {Promise}

Submits a transaction to the network.

By default this function calls Server#checkMemoRequired, you can skip this check by setting the option skipMemoRequiredCheck to true.

If you submit any number of manageOffer operations, this will add an attribute to the response that will help you analyze what happened with your offers.

Ex:

const res = {
  ...response,
  offerResults: [
    {
      // Exact ordered list of offers that executed, with the exception
      // that the last one may not have executed entirely.
      offersClaimed: [
        sellerId: String,
        offerId: String,
        assetSold: {
          type: 'native|credit_alphanum4|credit_alphanum12',

          // these are only present if the asset is not native
          assetCode: String,
          issuer: String,
        },

        // same shape as assetSold
        assetBought: {}
      ],

      // What effect your manageOffer op had
      effect: "manageOfferCreated|manageOfferUpdated|manageOfferDeleted",

      // Whether your offer immediately got matched and filled
      wasImmediatelyFilled: Boolean,

      // Whether your offer immediately got deleted, if for example the order was too small
      wasImmediatelyDeleted: Boolean,

      // Whether the offer was partially, but not completely, filled
      wasPartiallyFilled: Boolean,

      // The full requested amount of the offer is open for matching
      isFullyOpen: Boolean,

      // The total amount of tokens bought / sold during transaction execution
      amountBought: Number,
      amountSold: Number,

      // if the offer was created, updated, or partially filled, this is
      // the outstanding offer
      currentOffer: {
        offerId: String,
        amount: String,
        price: {
          n: String,
          d: String,
        },

        selling: {
          type: 'native|credit_alphanum4|credit_alphanum12',

          // these are only present if the asset is not native
          assetCode: String,
          issuer: String,
        },

        // same as `selling`
        buying: {},
      },

      // the index of this particular operation in the op stack
      operationIndex: Number
    }
  ]
}

For example, you'll want to examine offerResults to add affordances like these to your app:

  • If wasImmediatelyFilled is true, then no offer was created. So if you normally watch the Server.offers endpoint for offer updates, you instead need to check Server.trades to find the result of this filled offer.
  • If wasImmediatelyDeleted is true, then the offer you submitted was deleted without reaching the orderbook or being matched (possibly because your amounts were rounded down to zero). So treat the just-submitted offer request as if it never happened.
  • If wasPartiallyFilled is true, you can tell the user that amountBought or amountSold have already been transferred.
Source:
See:
Parameters:
Name Type Attributes Description
transaction Transaction | FeeBumpTransaction

The transaction to submit.

opts object <optional>

Options object

Name Type Attributes Description
skipMemoRequiredCheck boolean <optional>

Allow skipping memo required check, default: false. See SEP0029.

Returns:
Type:
Promise

Promise that resolves or rejects with response from horizon.

tradeAggregation(base, counter, start_time, end_time, resolution, offset) → {TradeAggregationCallBuilder}

Source:
Parameters:
Name Type Description
base Asset

base asset

counter Asset

counter asset

start_time long

lower time boundary represented as millis since epoch

end_time long

upper time boundary represented as millis since epoch

resolution long

segment duration as millis since epoch. *Supported values are 5 minutes (300000), 15 minutes (900000), 1 hour (3600000), 1 day (86400000) and 1 week (604800000).

offset long

segments can be offset using this parameter. Expressed in milliseconds. *Can only be used if the resolution is greater than 1 hour. Value must be in whole hours, less than the provided resolution, and less than 24 hours. Returns new TradeAggregationCallBuilder object configured with the current Horizon server configuration.

Returns:
Type:
TradeAggregationCallBuilder

New TradeAggregationCallBuilder instance

trades() → {TradesCallBuilder}

Returns

Source:
Returns:
Type:
TradesCallBuilder

New TradesCallBuilder object configured by a current Horizon server configuration.

transactions() → {TransactionCallBuilder}

Source:
Returns:
Type:
TransactionCallBuilder

New TransactionCallBuilder object configured by a current Horizon server configuration.