Global

Members

(constant) AuthClawbackEnabledFlag

When set using Operation.setOptions option, then any trustlines created by this account can have a ClawbackOp operation submitted for the corresponding asset.

Source:
See:

(constant) AuthImmutableFlag

When set using Operation.setOptions option, then none of the authorization flags can be set and the account can never be deleted.

Source:
See:

(constant) AuthRequiredFlag

When set using Operation.setOptions option, requires the issuing account to give other accounts permission before they can hold the issuing account’s credit.

Source:
See:

(constant) AuthRevocableFlag

When set using Operation.setOptions option, allows the issuing account to revoke its credit held by other accounts.

Source:
See:

(constant) BASE_FEE

Minimum base fee for transactions. If this fee is below the network minimum, the transaction will fail. The more operations in the transaction, the greater the required fee. Use Server#fetchBaseFee to get an accurate value of minimum transaction fee on the network.

Source:
See:

BadResponseError

AccountRequiresMemoError is raised when a transaction is trying to submit an operation to an account which requires a memo. See SEP0029 for more information.

This error contains two attributes to help you identify the account requiring the memo and the operation where the account is the destination

console.log('The following account requires a memo ', err.accountId)
console.log('The account is used in operation: ', err.operationIndex)
Source:

(constant) DEFAULT_TIMEOUT

The default timeout for waiting for a transaction to be included in a block.

Source:

Durability

Specifies the durability namespace of contract-related ledger entries.

Source:

(constant) FastSigning

Use this flag to check if fast signing (provided by sodium-native package) is available. If your app is signing a large number of transaction or verifying a large number of signatures make sure sodium-native package is installed.

Source:

(constant) MemoHash

Type of Memo.

Source:

(constant) MemoID

Type of Memo.

Source:

(constant) MemoNone

Type of Memo.

Source:

(constant) MemoReturn

Type of Memo.

Source:

(constant) MemoText

Type of Memo.

Source:

(constant) Networks :Object

Contains passphrases for common networks:

  • Networks.PUBLIC: Public Global Stellar Network ; September 2015
  • Networks.TESTNET: Test SDF Network ; September 2015
  • Networks.FUTURENET: Test SDF Future Network ; October 2022
  • Networks.STANDALONE: Standalone Network ; February 2017
Source:
Type:
  • Object

Ok

Part of implementing Result, a minimal implementation of Rust's Result type. Used for contract methods that return Results, to maintain their distinction from methods that simply either return a value or throw.

Source:

(constant) SERVER_TIME_MAP

keep a local map of server times (export this purely for testing purposes)

each entry will map the server domain to the last-known time and the local time it was recorded, ex:

"horizon-testnet.stellar.org": {
  serverTime: 1552513039,
  localTimeRecorded: 1552513052
}
Source:

(constant) STELLAR_TOML_MAX_SIZE

the maximum size of stellar.toml file

Source:

(constant) contractErrorPattern

If contracts are implemented using the #[contracterror] macro, then the errors get included in the on-chain XDR that also describes your contract's methods. Each error will have a specific number. This Regular Expression matches these "expected error types" that a contract may throw, and helps

Source:

Methods

asciiCompare(a, b) → {number}

Compares two ASCII strings in lexographic order with uppercase precedence.

Source:
Parameters:
Name Type Description
a string

the first string to compare

b string

the second

Returns:
Type:
number

like all compare()s: -1 if a < b, 0 if a == b, and 1 if a > b

assembleTransaction(raw, simulation)

Combines the given raw transaction alongside the simulation results.

Source:
See:
  • {Server.simulateTransaction}
  • {Server.prepareTransaction}
Parameters:
Name Type Description
raw

the initial transaction, w/o simulation applied

simulation

the Soroban RPC simulation result (see Server.simulateTransaction)

Returns:

a new, cloned transaction with the proper auth and resource (fee, footprint) simulation data applied

authorizeEntry(entry, signer, validUntilLedgerSeq, networkPassphraseopt) → {Promise.<xdr.SorobanAuthorizationEntry>}

Actually authorizes an existing authorization entry using the given the credentials and expiration details, returning a signed copy.

This "fills out" the authorization entry with a signature, indicating to the Operation.invokeHostFunction its attached to that:

  • a particular identity (i.e. signing Keypair or other signer)
  • approving the execution of an invocation tree (i.e. a simulation-acquired xdr.SorobanAuthorizedInvocation or otherwise built)
  • on a particular network (uniquely identified by its passphrase, see Networks)
  • until a particular ledger sequence is reached.

This one lets you pass a either a Keypair (or, more accurately, anything with a sign(Buffer): Buffer method) or a callback function (see SigningCallback) to handle signing the envelope hash.

Source:
See:
Parameters:
Name Type Attributes Description
entry xdr.SorobanAuthorizationEntry

an unsigned authorization entr

signer Keypair | SigningCallback

either a Keypair instance or a function which takes a payload (a xdr.HashIdPreimageSorobanAuthorization instance) input and returns the signature of the hash of the raw payload bytes (where the signing key should correspond to the address in the entry)

validUntilLedgerSeq number

the (exclusive) future ledger sequence number until which this authorization entry should be valid (if currentLedgerSeq==validUntil, this is expired))

networkPassphrase string <optional>

the network passphrase is incorprated into the signature (see Networks for options)

Returns:
Type:
Promise.<xdr.SorobanAuthorizationEntry>

a promise for an authorization entry that you can pass along to Operation.invokeHostFunction

Example
import {
  SorobanRpc,
  Transaction,
  Networks,
  authorizeEntry
} from '@stellar/stellar-sdk';

// Assume signPayloadCallback is a well-formed signing callback.
//
// It might, for example, pop up a modal from a browser extension, send the
// transaction to a third-party service for signing, or just do simple
// signing via Keypair like it does here:
function signPayloadCallback(payload) {
   return signer.sign(hash(payload.toXDR());
}

function multiPartyAuth(
   server: SorobanRpc.Server,
   // assume this involves multi-party auth
   tx: Transaction,
) {
   return server
     .simulateTransaction(tx)
     .then((simResult) => {
         tx.operations[0].auth.map(entry =>
           authorizeEntry(
             entry,
             signPayloadCallback,
             currentLedger + 1000,
             Networks.TESTNET);
         ));

         return server.prepareTransaction(tx, simResult);
     })
     .then((preppedTx) => {
       preppedTx.sign(source);
       return server.sendTransaction(preppedTx);
     });
}

authorizeInvocation(signer, validUntilLedgerSeq, invocation, publicKeyopt, networkPassphraseopt) → {Promise.<xdr.SorobanAuthorizationEntry>}

This builds an entry from scratch, allowing you to express authorization as a function of:

  • a particular identity (i.e. signing Keypair or other signer)
  • approving the execution of an invocation tree (i.e. a simulation-acquired xdr.SorobanAuthorizedInvocation or otherwise built)
  • on a particular network (uniquely identified by its passphrase, see Networks)
  • until a particular ledger sequence is reached.

This is in contrast to authorizeEntry, which signs an existing entry.

Source:
See:
Parameters:
Name Type Attributes Description
signer Keypair | SigningCallback

either a Keypair instance (or anything with a .sign(buf): Buffer-like method) or a function which takes a payload (a xdr.HashIdPreimageSorobanAuthorization instance) input and returns the signature of the hash of the raw payload bytes (where the signing key should correspond to the address in the entry)

validUntilLedgerSeq number

the (exclusive) future ledger sequence number until which this authorization entry should be valid (if currentLedgerSeq==validUntilLedgerSeq, this is expired))

invocation xdr.SorobanAuthorizedInvocation

the invocation tree that we're authorizing (likely, this comes from transaction simulation)

publicKey string <optional>

the public identity of the signer (when providing a Keypair to signer, this can be omitted, as it just uses Keypair.publicKey)

networkPassphrase string <optional>

the network passphrase is incorprated into the signature (see Networks for options, default: Networks.FUTURENET)

Returns:
Type:
Promise.<xdr.SorobanAuthorizationEntry>

a promise for an authorization entry that you can pass along to Operation.invokeHostFunction

basicNodeSigner()

For use with ContractClient and AssembledTransaction. Implements signTransaction and signAuthEntry with signatures expected by those classes. This is useful for testing and maybe some simple Node applications. Feel free to use this as a starting point for your own Wallet/TransactionSigner implementation.

Source:

buildInvocationTree(root) → {InvocationTree}

Turns a raw invocation tree into a human-readable format.

This is designed to make the invocation tree easier to understand in order to inform users about the side-effects of their contract calls. This will help make informed decisions about whether or not a particular invocation will result in what you expect it to.

Source:
Parameters:
Name Type Description
root xdr.SorobanAuthorizedInvocation

the raw XDR of the invocation, likely acquired from transaction simulation. this is either from the Operation.invokeHostFunction itself (the func field), or from the authorization entries (xdr.SorobanAuthorizationEntry, the rootInvocation field)

Returns:
Type:
InvocationTree

a human-readable version of the invocation tree

Example
Here, we show a browser modal after simulating an arbitrary transaction,
`tx`, which we assume has an `Operation.invokeHostFunction` inside of it:

```typescript
import { Server, buildInvocationTree } from '@stellar/stellar-sdk';

const s = new Server("fill in accordingly");

s.simulateTransaction(tx).then(
 (resp: SorobanRpc.SimulateTransactionResponse) => {
   if (SorobanRpc.isSuccessfulSim(resp) && ) {
     // bold assumption: there's a valid result with an auth entry
     alert(
       "You are authorizing the following invocation:\n" +
       JSON.stringify(
         buildInvocationTree(resp.result!.auth[0].rootInvocation()),
         null,
         2
       )
     );
   }
 }
);
```

decodeAddressToMuxedAccount(address) → {xdr.MuxedAccount}

Converts a Stellar address (in G... or M... form) to an xdr.MuxedAccount structure, using the ed25519 representation when possible.

This supports full muxed accounts, where an M... address will resolve to both its underlying G... address and an integer ID.

Source:
Parameters:
Name Type Description
address string

G... or M... address to encode into XDR

Returns:
Type:
xdr.MuxedAccount

a muxed account object for this address string

encodeMuxedAccount(address, id) → {xdr.MuxedAccount}

Transform a Stellar address (G...) and an ID into its XDR representation.

Source:
Parameters:
Name Type Description
address string

a Stellar G... address

id string

a Uint64 ID represented as a string

Returns:
Type:
xdr.MuxedAccount
  • XDR representation of the above muxed account

encodeMuxedAccountToAddress(muxedAccount) → {string}

Converts an xdr.MuxedAccount to its StrKey representation.

This returns its "M..." string representation if there is a muxing ID within the object and returns the "G..." representation otherwise.

Source:
See:
Parameters:
Name Type Description
muxedAccount xdr.MuxedAccount

Raw account to stringify

Returns:
Type:
string

Stringified G... (corresponding to the underlying pubkey) or M... address (corresponding to both the key and the muxed ID)

extractBaseAddress(address) → {string}

Extracts the underlying base (G...) address from an M-address.

Source:
Parameters:
Name Type Description
address string

an account address (either M... or G...)

Returns:
Type:
string

a Stellar public key address (G...)

getCurrentServerTime(hostname) → {number}

Given a hostname, get the current time of that server (i.e., use the last- recorded server time and offset it by the time since then.) If there IS no recorded server time, or it's been 5 minutes since the last, return null.

Source:
Parameters:
Name Type Description
hostname string

Hostname of a Horizon server.

Returns:
Type:
number

The UNIX timestamp (in seconds, not milliseconds) representing the current time on that server, or null if we don't have a record of that time.

getLiquidityPoolId(liquidityPoolType, liquidityPoolParameters) → {Buffer}

getLiquidityPoolId computes the Pool ID for the given assets, fee and pool type.

Source:
See:
Parameters:
Name Type Description
liquidityPoolType string

– A string representing the liquidity pool type.

liquidityPoolParameters object

– The liquidity pool parameters.

Name Type Description
assetA Asset

– The first asset in the Pool, it must respect the rule assetA < assetB.

assetB Asset

– The second asset in the Pool, it must respect the rule assetA < assetB.

fee number

– The liquidity pool fee. For now the only fee supported is 30.

Returns:
Type:
Buffer

the raw Pool ID buffer, which can be stringfied with toString('hex')

getSalty() → {Buffer}

Source:
Returns:
Type:
Buffer

a random 256-bit "salt" value.

humanizeEvents(events) → {Array.<SorobanEvent>}

Converts raw diagnostic or contract events into something with a flatter, human-readable, and understandable structure.

Source:
Parameters:
Name Type Description
events Array.<xdr.DiagnosticEvent> | Array.<xdr.ContractEvent>

either contract events or diagnostic events to parse into a friendly format

Returns:
Type:
Array.<SorobanEvent>

a list of human-readable event structures, where each element has the following properties:

  • type: a string of one of 'system', 'contract', 'diagnostic
  • contractId?: optionally, a C... encoded strkey
  • topics: a list of scValToNative invocations on the topics
  • data: similarly, a scValToNative invocation on the raw event data

implementsToString()

A TypeScript type guard that checks if an object has a toString method.

Source:

isValid(versionByteName, encoded) → {Boolean}

Sanity-checks whether or not a strkey appears valid.

Source:
Parameters:
Name Type Description
versionByteName string

the type of strkey to expect in encoded

encoded string

the strkey to validate

Returns:
Type:
Boolean

whether or not the encoded strkey appears valid for the versionByteName strkey type (see versionBytes, above).

isValidDate(d) → {boolean}

Checks whether a provided object is a valid Date.

Source:
Parameters:
Name Type Description
d Date

date object

Returns:
Type:
boolean

nativeToScVal(val, optsopt) → {xdr.ScVal}

Attempts to convert native types into smart contract values (xdr.ScVal).

Provides conversions from smart contract XDR values (xdr.ScVal) to native JavaScript types.

The conversions are as follows:

  • xdr.ScVal -> passthrough

  • null/undefined -> scvVoid

  • string -> scvString (a copy is made)

  • UintArray8 -> scvBytes (a copy is made)

  • boolean -> scvBool

  • number/bigint -> the smallest possible XDR integer type that will fit the input value (if you want a specific type, use ScInt)

  • Address or Contract -> scvAddress (for contracts and public keys)

  • Array -> scvVec after attempting to convert each item of type T to an xdr.ScVal (recursively). note that all values must be the same type!

  • object -> scvMap after attempting to convert each key and value to an xdr.ScVal (recursively). note that there is no restriction on types matching anywhere (unlike arrays)

When passing an integer-like native value, you can also optionally specify a type which will force a particular interpretation of that value.

Note that not all type specifications are compatible with all ScVals, e.g. toScVal("a string", {type: "i256"}) will throw.

Source:
See:
Parameters:
Name Type Attributes Description
val any

a native (or convertible) input value to wrap

opts object <optional>

an optional set of hints around the type of conversion you'd like to see

Name Type Attributes Description
type string <optional>

there is different behavior for different input types for val:

- when `val` is an integer-like type (i.e. number|bigint), this will be
  forwarded to ScInt or forced to be u32/i32.

- when `val` is an array type, this is forwarded to the recursion

- when `val` is an object type (key-value entries), this should be an
  object in which each key has a pair of types (to represent forced types
  for the key and the value), where `null` (or a missing entry) indicates
  the default interpretation(s) (refer to the examples, below)

- when `val` is a string type, this can be 'string' or 'symbol' to force
  a particular interpretation of `val`.

- when `val` is a bytes-like type, this can be 'string', 'symbol', or
  'bytes' to force a particular interpretation

As a simple example, nativeToScVal("hello", {type: 'symbol'}) will return an scvSymbol, whereas without the type it would have been an scvString.

Throws:

if...

  • there are arrays with more than one type in them
  • there are values that do not have a sensible conversion (e.g. random XDR types, custom classes)
  • the type of the input object (or some inner value of said object) cannot be determined (via typeof)
  • the type you specified (via opts.type) is incompatible with the value you passed in (val), e.g. nativeToScVal("a string", { type: 'i128' }), though this does not apply for types that ignore opts (e.g. addresses).
Type
TypeError
Returns:
Type:
xdr.ScVal

a wrapped, smart, XDR version of the input value

Examples
nativeToScVal(1000);                   // gives ScValType === scvU64
nativeToScVal(1000n);                  // gives ScValType === scvU64
nativeToScVal(1n << 100n);             // gives ScValType === scvU128
nativeToScVal(1000, { type: 'u32' });  // gives ScValType === scvU32
nativeToScVal(1000, { type: 'i125' }); // gives ScValType === scvI256
nativeToScVal("a string");                     // gives ScValType === scvString
nativeToScVal("a string", { type: 'symbol' }); // gives scvSymbol
nativeToScVal(new Uint8Array(5));                      // scvBytes
nativeToScVal(new Uint8Array(5), { type: 'symbol' });  // scvSymbol
nativeToScVal(null); // scvVoid
nativeToScVal(true); // scvBool
nativeToScVal([1, 2, 3]);                    // gives scvVec with each element as scvU64
nativeToScVal([1, 2, 3], { type: 'i128' });  // scvVec<scvI128>
nativeToScVal({ 'hello': 1, 'world': [ true, false ] }, {
  type: {
    'hello': [ 'symbol', 'i128' ],
  }
})
// gives scvMap with entries: [
//     [ scvSymbol, scvI128 ],
//     [ scvString, scvArray<scvBool> ]
// ]
import {
  nativeToScVal,
  scValToNative,
  ScInt,
  xdr
} from '@stellar/stellar-base';

let gigaMap = {
  bool: true,
  void: null,
  u32: xdr.ScVal.scvU32(1),
  i32: xdr.ScVal.scvI32(1),
  u64: 1n,
  i64: -1n,
  u128: new ScInt(1).toU128(),
  i128: new ScInt(1).toI128(),
  u256: new ScInt(1).toU256(),
  i256: new ScInt(1).toI256(),
  map: {
    arbitrary: 1n,
    nested: 'values',
    etc: false
  },
  vec: ['same', 'type', 'list'],
};

// then, simply:
let scv = nativeToScVal(gigaMap);    // scv.switch() == xdr.ScValType.scvMap()

// then...
someContract.call("method", scv);

// Similarly, the inverse should work:
scValToNative(scv) == gigaMap;       // true

parseRawSimulation(raw)

Converts a raw response schema into one with parsed XDR fields and a simplified interface.

Source:
Parameters:
Name Type Description
raw

the raw response schema (parsed ones are allowed, best-effort detected, and returned untouched)

Returns:

the original parameter (if already parsed), parsed otherwise

(async) postObject()

Sends the jsonrpc 'params' as a single 'param' object (no array support).

Source:

scValToBigInt(scv) → {bigint}

Transforms an opaque xdr.ScVal into a native bigint, if possible.

If you then want to use this in the abstractions provided by this module, you can pass it to the constructor of XdrLargeInt.

Source:
Parameters:
Name Type Description
scv xdr.ScVal

the raw XDR value to parse into an integer

Throws:

if the scv input value doesn't represent an integer

Type
TypeError
Returns:
Type:
bigint

the native value of this input value

Example
let scv = contract.call("add", x, y); // assume it returns an xdr.ScVal
let bigi = scValToBigInt(scv);

new ScInt(bigi);               // if you don't care about types, and
new XdrLargeInt('i128', bigi); // if you do

scValToNative(scv) → {any}

Given a smart contract value, attempt to convert it to a native type. Possible conversions include:

  • void -> null
  • u32, i32 -> number
  • u64, i64, u128, i128, u256, i256 -> bigint
  • vec -> Array of any of the above (via recursion)
  • map -> key-value object of any of the above (via recursion)
  • bool -> boolean
  • bytes -> Uint8Array
  • symbol -> string
  • string -> string IF the underlying buffer can be decoded as ascii/utf8, Uint8Array of the raw contents in any error case

If no viable conversion can be determined, this just "unwraps" the smart value to return its underlying XDR value.

Source:
See:
Parameters:
Name Type Description
scv xdr.ScVal

the input smart contract value

Returns:
Type:
any

typeRef(typeDef) → {JSONSchema7}

Source:
Parameters:
Name Type Description
typeDef

type to convert to json schema reference

Returns:
Type:
JSONSchema7

a schema describing the type

walkInvocationTree(root, callback) → {void}

Executes a callback function on each node in the tree until stopped.

Nodes are walked in a depth-first order. Returning false from the callback stops further depth exploration at that node, but it does not stop the walk in a "global" view.

Source:
Parameters:
Name Type Description
root xdr.SorobanAuthorizedInvocation

the tree to explore

callback InvocationWalker

the callback to execute for each node

Returns:
Type:
void

(async) withExponentialBackoff()

Keep calling a fn for timeoutInSeconds seconds, if keepWaitingIf is true. Returns an array of all attempts to call the function.

Source:

Type Definitions

CreateInvocation

Properties:
Properties
Name Type Attributes Description
type 'wasm' | 'sac'

a type indicating if this creation was a custom contract or a wrapping of an existing Stellar asset

token string <optional>

when type=='sac', the canonical Asset that is being wrapped by this Stellar Asset Contract

wasm object <optional>

when type=='wasm', add'l creation parameters

Name Type Description
hash string

hex hash of WASM bytecode backing this contract

address string

contract address of this deployment

salt string

hex salt that the user consumed when creating this contract (encoded in the resulting address)

Source:

ExecuteInvocation

Properties:
Name Type Description
source string

the strkey of the contract (C...) being invoked

function string

the name of the function being invoked

args Array.<any>

the natively-represented parameters to the function invocation (see scValToNative) for rules on how they're represented a JS types

Source:

InvocationTree

Properties:
Name Type Description
type 'execute' | 'create'

the type of invocation occurring, either contract creation or host function execution

args CreateInvocation | ExecuteInvocation

the parameters to the invocation, depending on the type

invocations Array.<InvocationTree>

any sub-invocations that (may) occur as a result of this invocation (i.e. a tree of call stacks)

Source:

InvocationWalker(node, depth, parentopt) → (nullable) {boolean}

Source:
Parameters:
Name Type Attributes Description
node xdr.SorobanAuthorizedInvocation

the currently explored node

depth number

the depth of the tree this node is occurring at (the root starts at a depth of 1)

parent xdr.SorobanAuthorizedInvocation <optional>

this nodes parent node, if any (i.e. this doesn't exist at the root)

Returns:
Type:
boolean

returning false is a hint to stop exploring

(async) SigningCallback(preimage) → {Promise.<Uint8Array>}

Source:
Parameters:
Name Type Description
preimage xdr.HashIdPreimage

the entire authorization envelope whose hash you should sign, so that you can inspect the entire structure if necessary (rather than blindly signing a hash)

Returns:
Type:
Promise.<Uint8Array>

the signature of the raw payload (which is the sha256 hash of the preimage bytes, so hash(preimage.toXDR())) signed by the key corresponding to the public key in the entry you pass to authorizeEntry (decipherable from its credentials().address().address())