Skip to content

Core / Soroban Primitives

Address

class Address {
constructor(address: string);
static account(buffer: Uint8Array): Address;
static claimableBalance(buffer: Uint8Array): Address;
static contract(buffer: Uint8Array): Address;
static fromScAddress(scAddress: ScAddress): Address;
static fromScVal(scVal: ScVal): Address;
static fromString(address: string): Address;
static liquidityPool(buffer: Uint8Array): Address;
static muxedAccount(buffer: Uint8Array): Address;
static muxedContract(buffer: Uint8Array): Address;
readonly type: AddressType;
toBuffer(): Uint8Array;
toScAddress(): ScAddress;
toScVal(): ScVal;
toString(): string;
}

Source: src/base/address.ts:35

new Address(address)

constructor(address: string);

Parameters

  • address — string (required) — a StrKey of the address value

Source: src/base/address.ts:42

Address.account(buffer)

Creates a new account Address object from raw bytes.

static account(buffer: Uint8Array): Address;

Parameters

  • buffer — Uint8Array (required) — The bytes of an address to parse.

Source: src/base/address.ts:80

Address.claimableBalance(buffer)

Creates a new claimable balance Address object from raw bytes.

static claimableBalance(buffer: Uint8Array): Address;

Parameters

  • buffer — Uint8Array (required) — The bytes of a claimable balance ID to parse.

Source: src/base/address.ts:98

Address.contract(buffer)

Creates a new contract Address object from raw bytes.

static contract(buffer: Uint8Array): Address;

Parameters

  • buffer — Uint8Array (required) — The bytes of an address to parse.

Source: src/base/address.ts:89

Address.fromScAddress(scAddress)

Convert this from an xdr.ScAddress type

static fromScAddress(scAddress: ScAddress): Address;

Parameters

  • scAddress — ScAddress (required) — The xdr.ScAddress type to parse

Source: src/base/address.ts:147

Address.fromScVal(scVal)

Convert this from an xdr.ScVal type.

static fromScVal(scVal: ScVal): Address;

Parameters

  • scVal — ScVal (required) — The xdr.ScVal type to parse

Source: src/base/address.ts:135

Address.fromString(address)

Parses a string and returns an Address object.

static fromString(address: string): Address;

Parameters

  • address — string (required) — The address to parse. ex. GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA

Source: src/base/address.ts:71

Address.liquidityPool(buffer)

Creates a new liquidity pool Address object from raw bytes.

static liquidityPool(buffer: Uint8Array): Address;

Parameters

  • buffer — Uint8Array (required) — The bytes of an LP ID to parse.

Source: src/base/address.ts:107

Address.muxedAccount(buffer)

Creates a new muxed account Address object from raw bytes.

static muxedAccount(buffer: Uint8Array): Address;

Parameters

  • buffer — Uint8Array (required) — The bytes of an address to parse.

Source: src/base/address.ts:116

Address.muxedContract(buffer)

Creates a new muxed contract Address object from raw bytes: the 32-byte contract ID followed by the 8-byte big-endian mux ID.

static muxedContract(buffer: Uint8Array): Address;

Parameters

  • buffer — Uint8Array (required) — The bytes of an address to parse.

Source: src/base/address.ts:126

address.type

Return the type of this address.

readonly type: AddressType;

Source: src/base/address.ts:263

address.toBuffer()

Return the raw public key bytes for this address.

toBuffer(): Uint8Array;

Source: src/base/address.ts:256

address.toScAddress()

Convert this Address to an xdr.ScAddress type.

toScAddress(): ScAddress;

Source: src/base/address.ts:217

address.toScVal()

Convert this Address to an xdr.ScVal type.

toScVal(): ScVal;

Source: src/base/address.ts:210

address.toString()

Serialize an address to string.

toString(): string;

Source: src/base/address.ts:188

Contract

Create a new Contract object.

Contract represents a single contract in the Stellar network, embodying the interface of the contract. See Contracts for more information about how contracts work in Stellar.

class Contract {
constructor(contractId: string);
address(): Address;
call(method: string, ...params: ScVal[]): Operation;
contractId(): string;
getFootprint(): LedgerKey;
toString(): string;
}

Source: src/base/contract.ts:20

new Contract(contractId)

constructor(contractId: string);

Parameters

  • contractId — string (required) — ID of the contract (ex. CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE).

Source: src/base/contract.ts:27

contract.address()

Returns the wrapped address of this contract.

address(): Address;

Source: src/base/contract.ts:57

contract.call(method, params)

Returns an operation that will invoke this contract call.

call(method: string, ...params: ScVal[]): Operation;

Parameters

  • method — string (required) — name of the method to call
  • ...params — ScVal[] (required) — arguments to pass to the method, as an array of xdr.ScVal

See also

    • Operation.invokeHostFunction
  • Operation.invokeContractFunction
  • Operation.createCustomContract
  • Operation.createStellarAssetContract
  • Operation.uploadContractWasm

Source: src/base/contract.ts:73

contract.contractId()

Returns Stellar contract ID as a strkey, ex. CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE.

contractId(): string;

Source: src/base/contract.ts:47

contract.getFootprint()

Returns the read-only footprint entries necessary for any invocations to this contract, for convenience when manually adding it to your transaction’s overall footprint or doing bump/restore operations.

getFootprint(): LedgerKey;

Source: src/base/contract.ts:86

contract.toString()

Returns the ID as a strkey (C…).

toString(): string;

Source: src/base/contract.ts:52

Soroban

Helper class to assist with formatting and parsing token amounts.

class Soroban {
constructor();
static formatTokenAmount(amount: string, decimals: number): string;
static parseTokenAmount(value: string, decimals: number): string;
}

Source: src/base/soroban.ts:2

new Soroban()

constructor();

Soroban.formatTokenAmount(amount, decimals)

Given a whole number smart contract amount of a token and an amount of decimal places (if the token has any), it returns a “display” value.

All arithmetic inside the contract is performed on integers to avoid potential precision and consistency issues of floating-point.

static formatTokenAmount(amount: string, decimals: number): string;

Parameters

  • amount — string (required) — the token amount you want to display
  • decimals — number (required) — specify how many decimal places a token has

Throws

  • a TypeError if the given amount has a decimal point already

Example

formatTokenAmount("123000", 4) === "12.3";
formatTokenAmount("123000", 3) === "123.0";
formatTokenAmount("123", 3) === "0.123";

Source: src/base/soroban.ts:21

Soroban.parseTokenAmount(value, decimals)

Parse a token amount to use it on smart contract

This function takes the display value and its decimals (if the token has any) and returns a string that’ll be used within the smart contract.

Returns the whole number token amount represented by the display value with the decimal places shifted over.

static parseTokenAmount(value: string, decimals: number): string;

Parameters

  • value — string (required) — the token amount you want to use on a smart contract which you’ve been displaying in a UI
  • decimals — number (required) — the number of decimal places expected in the display value (different than the “actual” number, because suffix zeroes might not be present)

Example

const displayValueAmount = "123.4560"
const parsedAmtForSmartContract = parseTokenAmount(displayValueAmount, 5);
parsedAmtForSmartContract === "12345600"

Source: src/base/soroban.ts:77

SorobanDataBuilder

Supports building xdr.SorobanTransactionData structures with various items set to specific values.

This is recommended for when you are building Operation.extendFootprintTtl / Operation.restoreFootprint operations and need to TransactionBuilder.setSorobanData to avoid (re)building the entire data structure from scratch.

class SorobanDataBuilder {
constructor(sorobanData?: string | Uint8Array<ArrayBufferLike> | SorobanTransactionData);
static fromXdr(data: string | Uint8Array<ArrayBufferLike>): SorobanTransactionData;
static fromXDR(data: string | Uint8Array<ArrayBufferLike>): SorobanTransactionData;
appendFootprint(readOnly: LedgerKey[], readWrite: LedgerKey[]): SorobanDataBuilder;
build(): SorobanTransactionData;
getFootprint(): LedgerFootprint;
getReadOnly(): LedgerKey[];
getReadWrite(): LedgerKey[];
setFootprint(readOnly?: LedgerKey[] | null, readWrite?: LedgerKey[] | null): SorobanDataBuilder;
setReadOnly(readOnly?: LedgerKey[]): SorobanDataBuilder;
setReadWrite(readWrite?: LedgerKey[]): SorobanDataBuilder;
setResourceFee(fee: IntLike): SorobanDataBuilder;
setResources(cpuInstrs: number, diskReadBytes: number, writeBytes: number): SorobanDataBuilder;
}

Example

// You want to use an existing data blob but override specific parts.
const newData = new SorobanDataBuilder(existing)
.setReadOnly(someLedgerKeys)
.setResourceFee("1000")
.build();
// You want an instance from scratch
const newData = new SorobanDataBuilder()
.setFootprint([someLedgerKey], [])
.setResourceFee("1000")
.build();

Source: src/base/sorobandata_builder.ts:36

new SorobanDataBuilder(sorobanData)

constructor(sorobanData?: string | Uint8Array<ArrayBufferLike> | SorobanTransactionData);

Parameters

  • sorobanData — string | Uint8Array<ArrayBufferLike> | SorobanTransactionData (optional) — either a base64-encoded string that represents an xdr.SorobanTransactionData instance or an XDR instance itself (it will be copied); if omitted or “falsy” (e.g. an empty string), it starts with an empty instance

Source: src/base/sorobandata_builder.ts:45

SorobanDataBuilder.fromXdr(data)

Decodes and builds a xdr.SorobanTransactionData instance.

static fromXdr(data: string | Uint8Array<ArrayBufferLike>): SorobanTransactionData;

Parameters

  • data — string | Uint8Array<ArrayBufferLike> (required) — raw input to decode

Source: src/base/sorobandata_builder.ts:76

SorobanDataBuilder.fromXDR(data)

Deprecated. Use SorobanDataBuilder.fromXdr instead. Deprecated in version v17.0.0

static fromXDR(data: string | Uint8Array<ArrayBufferLike>): SorobanTransactionData;

Parameters

  • data — string | Uint8Array<ArrayBufferLike> (required)

Source: src/base/sorobandata_builder.ts:88

sorobanDataBuilder.appendFootprint(readOnly, readWrite)

Appends the given ledger keys to the existing storage access footprint.

appendFootprint(readOnly: LedgerKey[], readWrite: LedgerKey[]): SorobanDataBuilder;

Parameters

  • readOnly — LedgerKey[] (required) — read-only keys to add
  • readWrite — LedgerKey[] (required) — read-write keys to add

Source: src/base/sorobandata_builder.ts:147

sorobanDataBuilder.build()

Returns a copy of the final data structure.

build(): SorobanTransactionData;

Source: src/base/sorobandata_builder.ts:228

sorobanDataBuilder.getFootprint()

Returns the storage access pattern.

getFootprint(): LedgerFootprint;

Source: src/base/sorobandata_builder.ts:247

sorobanDataBuilder.getReadOnly()

Returns the read-only storage access pattern.

getReadOnly(): LedgerKey[];

Source: src/base/sorobandata_builder.ts:237

sorobanDataBuilder.getReadWrite()

Returns the read-write storage access pattern.

getReadWrite(): LedgerKey[];

Source: src/base/sorobandata_builder.ts:242

sorobanDataBuilder.setFootprint(readOnly, readWrite)

Sets the storage access footprint to be a certain set of ledger keys.

You can also set each field explicitly via SorobanDataBuilder.setReadOnly and SorobanDataBuilder.setReadWrite or add to the existing footprint via SorobanDataBuilder.appendFootprint.

Passing null|undefined to either parameter will IGNORE the existing values. If you want to clear them, pass [], instead.

setFootprint(readOnly?: LedgerKey[] | null, readWrite?: LedgerKey[] | null): SorobanDataBuilder;

Parameters

  • readOnly — LedgerKey[] | null (optional) — the set of ledger keys to set in the read-only portion of the transaction’s sorobanData, or null | undefined to keep the existing keys
  • readWrite — LedgerKey[] | null (optional) — the set of ledger keys to set in the read-write portion of the transaction’s sorobanData, or null | undefined to keep the existing keys

Source: src/base/sorobandata_builder.ts:171

sorobanDataBuilder.setReadOnly(readOnly)

Sets the read-only keys in the access footprint.

setReadOnly(readOnly?: LedgerKey[]): SorobanDataBuilder;

Parameters

  • readOnly — LedgerKey[] (optional) — read-only keys in the access footprint

Source: src/base/sorobandata_builder.ts:190

sorobanDataBuilder.setReadWrite(readWrite)

Sets the read-write keys in the access footprint.

setReadWrite(readWrite?: LedgerKey[]): SorobanDataBuilder;

Parameters

  • readWrite — LedgerKey[] (optional) — read-write keys in the access footprint

Source: src/base/sorobandata_builder.ts:210

sorobanDataBuilder.setResourceFee(fee)

Sets the resource fee portion of the Soroban data.

setResourceFee(fee: IntLike): SorobanDataBuilder;

Parameters

  • fee — IntLike (required) — the resource fee to set (int64)

Source: src/base/sorobandata_builder.ts:105

sorobanDataBuilder.setResources(cpuInstrs, diskReadBytes, writeBytes)

Sets up the resource metrics.

You should almost NEVER need this, as its often generated / provided to you by transaction simulation/preflight from a Soroban RPC server.

setResources(cpuInstrs: number, diskReadBytes: number, writeBytes: number): SorobanDataBuilder;

Parameters

  • cpuInstrs — number (required) — number of CPU instructions
  • diskReadBytes — number (required) — number of bytes being read from disk
  • writeBytes — number (required) — number of bytes being written to disk/memory

Source: src/base/sorobandata_builder.ts:124

authorizeEntry

Actually authorizes an existing authorization entry using the given 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 either a Keypair (or, more accurately, anything with a sign(Uint8Array): Uint8Array method) or a callback function (see SigningCallback) to handle signing the envelope hash.

When validUntilLedgerSeq differs from a non-zero stored expiration, every other node’s signature is replaced with scvVoid, because it commits to the stored expiration and would no longer verify. This includes a custom signature that does not depend on the payload. A stored 0 (as simulation returns) commits to nothing: a signature in the SDK’s ed25519 format is kept only when it verifies at validUntilLedgerSeq, and a custom signature is kept as it is. Use checkAuthEntryReadiness to find the nodes that need to sign again, or sign every node with the same validUntilLedgerSeq.

authorizeEntry(entry: SorobanAuthorizationEntry, signer: Keypair | SigningCallback, validUntilLedgerSeq: number, networkPassphrase: string, forAddress?: string): Promise<SorobanAuthorizationEntry>

Parameters

  • entry — SorobanAuthorizationEntry (required) — an unsigned authorization entry

  • signer — Keypair | SigningCallback (required) — either a Keypair instance or a function (see SigningCallback) which receives the xdr.HashIdPreimage input payload plus its 32-byte signing hash and returns EITHER

    (a) an object containing a `signature` of the hash of the raw payload
    bytes as a `Uint8Array` and a `publicKey` string representing who just
    created this signature,
    (b) just the naked signature of the hash of the raw payload bytes (where
    the signing key is implied to be `forAddress` when supplied,
    otherwise the entry's top-level credential address), or
    (c) an object containing a `signatureScVal` — an arbitrary, caller-built
    `xdr.ScVal` written verbatim as the credentials' signature,
    for custom account contracts (smart wallets, passkey/WebAuthn
    signers) whose `__check_auth` expects a non-Ed25519 signature shape.

    Option (b) is JUST for backwards compatibility and will be removed in the future.

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

  • networkPassphrase — string (required) — the network passphrase is incorporated into the signature (see Networks for options)

  • forAddress — string (optional) — which credential node the signature should be written to. Only relevant for SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES, where a single entry can be signed by the top-level account and/or any of its (possibly nested) delegates. Per CAP-71-01 every one of these signers signs the same payload (bound to the top-level address), so the signature produced here is written to whichever node(s) carry forAddress. When omitted, the signature is written to the top-level credentials, which preserves the behavior for SOROBAN_CREDENTIALS_ADDRESS / SOROBAN_CREDENTIALS_ADDRESS_V2 and for accounts whose signing key differs from the credential address (e.g. multisig). A bare signature is verified against this address.

Throws

  • TypeError if the entry’s address or any delegate address is muxed (M... or W...).

Example

import {
rpc,
Operation,
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:
async function signPayloadCallback(preimage, payload) {
// `payload` is hash(preimage.toXdr()) — inspect `preimage` if you want
// to display/verify what is being authorized before signing.
return signer.sign(payload);
}
async function multiPartyAuth(
server: rpc.Server,
// assume this involves multi-party auth
tx: Transaction,
) {
const sim = await server.simulateTransaction(tx);
if (!rpc.Api.isSimulationSuccess(sim)) {
throw new Error('simulation failed');
}
const invoke = tx.operations[0];
if (invoke.type !== 'invokeHostFunction') {
throw new Error('expected an invokeHostFunction operation');
}
// Simulation supplies the entries to authorize. `authorizeEntry` returns
// a signed *copy*, so collect the results rather than discarding them.
const auth = await Promise.all(
(sim.result?.auth ?? []).map((entry) =>
authorizeEntry(
entry,
signPayloadCallback,
currentLedger + 1000,
Networks.TESTNET,
),
),
);
// Replace the operation rather than mutating it: a built `Transaction`'s
// operations must not be changed. `assembleTransaction` applies the
// resources and fee from simulation, and keeps auth that is already
// present. Call `build()` once — each call consumes a sequence number.
const built = rpc.assembleTransaction(tx, sim)
.clearOperations()
.addOperation(Operation.invokeHostFunction({
source: invoke.source,
func: invoke.func,
auth,
}))
.build();
built.sign(source);
return server.sendTransaction(built);
}

See also

  • authorizeInvocation

Source: src/base/auth.ts:231

authorizeInvocation

authorizeInvocation(params: AuthorizeInvocationParams): Promise<SorobanAuthorizationEntry>

Parameters

  • params — AuthorizeInvocationParams (required)

Source: src/base/auth.ts:477

buildAuthorizationEntryPreimage

Builds the xdr.HashIdPreimage whose hash a signer must sign to authorize entry. This is the low-level signature payload used by authorizeEntry, exposed for callers that drive signing themselves — most notably for SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES, where the client (not simulation) decides which delegates sign and how.

For SOROBAN_CREDENTIALS_ADDRESS this is the legacy, non-address-bound ENVELOPE_TYPE_SOROBAN_AUTHORIZATION preimage. For SOROBAN_CREDENTIALS_ADDRESS_V2 and SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES it is the address-bound ENVELOPE_TYPE_SOROBAN_AUTHORIZATION_WITH_ADDRESS preimage (CAP-71). For the delegates variant this single payload — bound to the top-level address — is what the top-level account and every (nested) delegate each sign.

To get the raw bytes to sign, hash the XDR: hash(preimage.toXdr()).

buildAuthorizationEntryPreimage(entry: SorobanAuthorizationEntry, validUntilLedgerSeq: number, networkPassphrase: string): HashIdPreimage

Parameters

  • entry — SorobanAuthorizationEntry (required) — the authorization entry to build the payload for
  • validUntilLedgerSeq — number (required) — the expiration ledger committed into the payload (must match the signatureExpirationLedger on the credentials you submit)
  • networkPassphrase — string (required) — the network passphrase mixed into the payload

Throws

  • Error if entry carries source-account or otherwise non-address credentials

Source: src/base/auth.ts:543

buildInvocationTree

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.

buildInvocationTree(root: SorobanAuthorizedInvocation): InvocationTree

Parameters

  • root — SorobanAuthorizedInvocation (required) — 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)

Example

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

import { rpc, buildInvocationTree } from '@stellar/stellar-sdk';
const s = new rpc.Server("fill in accordingly");
s.simulateTransaction(tx).then(
(resp: rpc.Api.SimulateTransactionResponse) => {
if (rpc.Api.isSimulationSuccess(resp) && resp.result) {
// bold assumption: there's a valid result with an auth entry
const auth = resp.result.auth;
if (auth && auth.length > 0) {
alert(
"You are authorizing the following invocation:\n" +
// args decode via `scValToNative`, so wide ints arrive as `bigint`,
// which plain JSON.stringify throws on — hence the replacer.
JSON.stringify(
buildInvocationTree(auth[0].rootInvocation),
(_key, value) =>
typeof value === 'bigint' ? value.toString() : value,
2
)
);
}
}
}
);

Source: src/base/invocation.ts:154

buildWithDelegatesEntry

Builds a SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES authorization entry by wrapping the address credentials of an existing ADDRESS/ADDRESS_V2 entry (e.g. one returned by simulation) together with a caller-provided set of delegate signers.

Simulation never emits the delegates variant on its own — which accounts use delegated authentication is account-specific policy known only to the client (much like a multisig policy). This helper just assembles the wrapper XDR; you supply the delegate tree (addresses and, optionally, signatures). To produce the signatures, build the shared payload with buildAuthorizationEntryPreimage on the returned entry and sign it, or fill each node afterwards with authorizeEntry (passing the signer’s address as forAddress).

Each delegates array (the top-level set and every nestedDelegates) is sorted by address in ascending order, and duplicate addresses within an array are rejected, as the protocol requires (CAP-71-01) — otherwise the host rejects the entry.

buildWithDelegatesEntry(params: BuildWithDelegatesParams): SorobanAuthorizationEntry

Parameters

Throws

  • Error if entry is not an ADDRESS/ADDRESS_V2 entry, or if any delegates array contains a duplicate address. TypeError if the entry’s address or any delegate address is muxed (M... or W...).

Source: src/base/auth.ts:656

checkAuthEntryReadiness

Reports whether an authorization entry is ready to submit at a given ledger: fully signed and not yet expired.

Source-account entries are always ready — they carry no signature or expiration of their own and are instead covered by the transaction envelope signature.

The current ledger sequence is taken as a parameter (fetch it from a source you trust, e.g. rpc.Server.getLatestLedger) rather than looked up here, so this stays a pure decode with no network dependency.

For SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES, this conservatively requires every node (top-level and all delegates) to be signed. An account’s policy may accept an unsigned top-level node when its delegates have signed (CAP-71-01); if you support that, check inspectAuthEntry’s signers yourself.

checkAuthEntryReadiness(entry: SorobanAuthorizationEntry, currentLedgerSeq: number): AuthEntryReadiness

Parameters

  • entry — SorobanAuthorizationEntry (required) — the authorization entry to check
  • currentLedgerSeq — number (required) — the network’s current ledger sequence, compared (exclusively) against the entry’s signatureExpirationLedger

Returns

a AuthEntryReadiness: ready, expired, and which addresses are still unsignedBy

Throws

  • Error if currentLedgerSeq cannot represent a uint32 ledger sequence (non-integer, negative, or above 2^32 - 1), which would make the expiration comparison unreliable

Source: src/base/auth.ts:1161

humanizeEvents

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

Each element in the returned list has the following properties:

  • type: one of 'system', 'contract', 'diagnostic'
  • contractId: optionally, a C... encoded strkey
  • topics: a list of scValToNative invocations on the topics
  • data: a scValToNative invocation on the raw event data
humanizeEvents(events: ContractEvent[] | DiagnosticEvent[]): SorobanEvent[]

Parameters

  • events — ContractEvent[] | DiagnosticEvent[] (required) — either contract events or diagnostic events to parse into a friendly format

Source: src/base/events.ts:44

inspectAuthEntry

Decodes a xdr.SorobanAuthorizationEntry into a plain, typed summary: which credential variant it uses, which address authorizes it, its nonce and expiration ledger, and — for every node that can carry a signature (the top-level credentials plus any CAP-71 delegates) — whether it is signed and, when the payload uses the SDK’s standard ed25519 format, by which keys.

This is the read-side complement to authorizeEntry / authorizeInvocation: those fill entries with signatures, this inspects what an entry (e.g. one returned by transaction simulation, or received from a counterparty in a multi-party signing flow) requires and already carries, without reaching into raw XDR accessors.

inspectAuthEntry(entry: SorobanAuthorizationEntry): AuthEntryInfo

Parameters

  • entry — SorobanAuthorizationEntry (required) — the authorization entry to inspect

Returns

a AuthEntryInfo summary of the entry

Example

const info = inspectAuthEntry(entry);
if (!info.signed && info.address !== null) {
console.log(`${info.address} still needs to sign`, info.signers);
}

See also

  • checkAuthEntryReadiness

Source: src/base/auth.ts:1041

nativeToScVal

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)

  • Uint8Array → 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<T> → 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.

nativeToScVal(val: unknown, opts: NativeToScValOpts = {}): ScVal

Parameters

  • val — unknown (required) — a native (or convertible) input value to wrap

  • opts — NativeToScValOpts (optional) (default: {}) — an optional set of hints around the type of conversion you’d like to see

    • type: 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 Map, this can be a [keyType, valType] pair applied to every entry, or (when all keys are strings) the same per-key spec object used for plain objects

      • 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

  • a TypeError 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).

Example

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: 'i256' }); // 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([1, '2'], { type: ['i128', 'symbol'] }); // scvVec with diff types
nativeToScVal([1, '2', 3], { type: ['i128', 'symbol'] });
// scvVec with diff types, using the default when omitted
nativeToScVal({ 'hello': 1, 'world': [ true, false ] }, {
type: {
'hello': [ 'symbol', 'i128' ],
}
})
// gives scvMap with entries: [
// [ scvSymbol, scvI128 ],
// [ scvString, scvArray<scvBool> ]
// ]

Example

import {
nativeToScVal,
scValToNative,
ScInt,
xdr
} from '@stellar/stellar-sdk';
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'],
vec: ['diff', 1, 'type', 2, 'list'],
};
// then, simply:
let scv = nativeToScVal(gigaMap); // scv.type === "scvMap"
// then...
someContract.call("method", scv);
// Similarly, the inverse should work:
scValToNative(scv) == gigaMap; // true

See also

  • scValToNative

Source: src/base/scval.ts:174

scValToNative

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, timepoint, duration → 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.

scValToNative(scv: ScVal): any

Parameters

  • scv — ScVal (required) — the input smart contract value

Throws

  • TypeError if two keys of a map convert to the same object property, such as u32 1 and symbol "1"

See also

  • nativeToScVal

Source: src/base/scval.ts:429

scvSortedMap

Build a sorted ScVal map from unsorted entries, sorted by key in the order the Soroban host requires.

scvSortedMap(items: ScMapEntry[]): ScVal

Parameters

  • items — ScMapEntry[] (required) — the unsorted map entries

Source: src/base/scval.ts:542

walkInvocationTree

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.

walkInvocationTree(root: SorobanAuthorizedInvocation, callback: InvocationWalker): void

Parameters

  • root — SorobanAuthorizedInvocation (required) — the tree to explore
  • callback — InvocationWalker (required) — the callback to execute for each node

Source: src/base/invocation.ts:261

Types

AuthEntryCredentialType

The credential arm of a xdr.SorobanAuthorizationEntry.

type AuthEntryCredentialType = "sourceAccount" | "address" | "addressV2" | "addressWithDelegates"

Source: src/base/auth.ts:924

AuthEntryInfo

A structured, read-only view of a xdr.SorobanAuthorizationEntry, returned by inspectAuthEntry.

interface AuthEntryInfo {
address: string | null;
credentialType: AuthEntryCredentialType;
invocation: SorobanAuthorizedInvocation;
nonce: bigint | null;
signatureExpirationLedger: number | null;
signed: boolean;
signers: AuthEntrySigner[];
}

Source: src/base/auth.ts:971

authEntryInfo.address

the authorizing address, or null for source-account credentials.

address: string | null;

Source: src/base/auth.ts:974

authEntryInfo.credentialType

credentialType: AuthEntryCredentialType;

Source: src/base/auth.ts:972

authEntryInfo.invocation

the invocation tree this entry authorizes.

invocation: SorobanAuthorizedInvocation;

Source: src/base/auth.ts:1000

authEntryInfo.nonce

the credential nonce, or null for source-account credentials.

nonce: bigint | null;

Source: src/base/auth.ts:976

authEntryInfo.signatureExpirationLedger

the (exclusive) ledger sequence until which the signature is valid, or null for source-account credentials. Note that unsigned entries commonly carry a placeholder (often 0) until authorizeEntry sets it.

signatureExpirationLedger: number | null;

Source: src/base/auth.ts:982

authEntryInfo.signed

whether every signer node carries a signature payload. Always false for source-account credentials (which have no signature nodes — they are instead covered by the transaction envelope signature; use checkAuthEntryReadiness for a submit check). For the delegates variant note that an account’s policy may accept an unsigned top-level node when its delegates have signed (CAP-71-01) — consult signers if you support that.

signed: boolean;

Source: src/base/auth.ts:998

authEntryInfo.signers

every node that can carry a signature: the top-level credentials first, then (for the delegates variant) each delegate, depth-first. Empty for source-account credentials.

signers: AuthEntrySigner[];

Source: src/base/auth.ts:988

AuthEntryReadiness

The result of checkAuthEntryReadiness.

interface AuthEntryReadiness {
expired: boolean;
ready: boolean;
unsignedBy: string[];
}

Source: src/base/auth.ts:1004

authEntryReadiness.expired

true when currentLedgerSeq >= signatureExpirationLedger (expiration is exclusive). Always false for source-account credentials.

expired: boolean;

Source: src/base/auth.ts:1011

authEntryReadiness.ready

true when the entry is fully signed and not expired.

ready: boolean;

Source: src/base/auth.ts:1006

authEntryReadiness.unsignedBy

addresses of signer nodes that carry no signature payload.

unsignedBy: string[];

Source: src/base/auth.ts:1013

AuthEntrySignature

A single ed25519 signature parsed out of a credential node’s signature value, in the map format written by authorizeEntry.

interface AuthEntrySignature {
publicKey: string;
signature: Uint8Array;
}

Source: src/base/auth.ts:931

authEntrySignature.publicKey

the signer’s public key, as a G… strkey.

publicKey: string;

Source: src/base/auth.ts:933

authEntrySignature.signature

the raw 64-byte ed25519 signature.

signature: Uint8Array;

Source: src/base/auth.ts:935

AuthEntrySigner

One node of an authorization entry that can carry a signature: the top-level address credentials and, for SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES, each (possibly nested) delegate.

interface AuthEntrySigner {
address: string;
rawSignature: ScVal;
signatures: AuthEntrySignature[] | null;
signed: boolean;
}

Source: src/base/auth.ts:943

authEntrySigner.address

the node’s address (G… account or C… contract).

address: string;

Source: src/base/auth.ts:945

authEntrySigner.rawSignature

the raw signature value, whatever its shape.

rawSignature: ScVal;

Source: src/base/auth.ts:964

authEntrySigner.signatures

the signature payload parsed as the SDK’s standard ed25519 format (a vec of {public_key, signature} maps, see authorizeEntry), or null when the payload has some other, signer-defined shape (as custom accounts such as WebAuthn/passkey wallets use). Of the two unsigned placeholder forms, an empty scvVec parses as [] while scvVoid (not a vec at all) parses as null — check signed rather than this field to tell whether a node is unsigned.

signatures: AuthEntrySignature[] | null;

Source: src/base/auth.ts:962

authEntrySigner.signed

whether a signature payload is present on this node (i.e. its signature is neither scvVoid nor an empty scvVec). For contract (C…) addresses this only means something is attached — whether it satisfies the contract’s __check_auth cannot be verified client-side.

signed: boolean;

Source: src/base/auth.ts:952

AuthorizeInvocationParams

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.

interface AuthorizeInvocationParams {
authV2?: boolean;
invocation: SorobanAuthorizedInvocation;
networkPassphrase: string;
publicKey?: string;
signer: Keypair | SigningCallback;
validUntilLedgerSeq: number;
}

See also

  • authorizeEntry

Source: src/base/auth.ts:462

authorizeInvocationParams.authV2

Build SOROBAN_CREDENTIALS_ADDRESS_V2 (CAP-71) credentials instead of the legacy SOROBAN_CREDENTIALS_ADDRESS. V2 credentials bind the address into the signed payload.

authV2?: boolean;

Source: src/base/auth.ts:474

authorizeInvocationParams.invocation

invocation: SorobanAuthorizedInvocation;

Source: src/base/auth.ts:465

authorizeInvocationParams.networkPassphrase

networkPassphrase: string;

Source: src/base/auth.ts:466

authorizeInvocationParams.publicKey

publicKey?: string;

Source: src/base/auth.ts:467

authorizeInvocationParams.signer

signer: Keypair | SigningCallback;

Source: src/base/auth.ts:463

authorizeInvocationParams.validUntilLedgerSeq

validUntilLedgerSeq: number;

Source: src/base/auth.ts:464

BuildWithDelegatesParams

Parameters for buildWithDelegatesEntry.

interface BuildWithDelegatesParams {
delegates: DelegateSignature[];
entry: SorobanAuthorizationEntry;
signature?: ScVal;
validUntilLedgerSeq: number;
}

Source: src/base/auth.ts:608

buildWithDelegatesParams.delegates

the delegate signers to attach.

delegates: DelegateSignature[];

Source: src/base/auth.ts:623

buildWithDelegatesParams.entry

an existing SOROBAN_CREDENTIALS_ADDRESS or SOROBAN_CREDENTIALS_ADDRESS_V2 entry — typically one returned by simulation — whose address credentials should be wrapped.

entry: SorobanAuthorizationEntry;

Source: src/base/auth.ts:614

buildWithDelegatesParams.signature

the top-level account’s signature. Defaults to scvVoid, which is valid for accounts that authorize purely via delegated signers (CAP-71-01).

signature?: ScVal;

Source: src/base/auth.ts:628

buildWithDelegatesParams.validUntilLedgerSeq

the expiration ledger sequence stored on the top-level credentials. Every signature commits to it, so pass the value the signatures were made for. With 0 (as simulation returns), authorizeEntry keeps an ed25519 signature only when it verifies at the expiration it is given.

validUntilLedgerSeq: number;

Source: src/base/auth.ts:621

CreateInvocation

Details about a contract creation invocation.

  • type indicates if this creation was a custom contract ('wasm'), a wrapping of an existing Stellar asset ('sac'), or a reference to an external executable ('external', see CAP-85)
  • asset is set when type=='sac', containing the canonical Asset being wrapped by this Stellar Asset Contract
  • wasm is set when type=='wasm', containing additional creation parameters
  • external is set when type=='external', containing the referenced executable and the creation parameters
interface CreateInvocation {
asset?: string;
external?: ExternalRefCreateDetails;
type: "wasm" | "sac" | "external";
wasm?: WasmCreateDetails;
}

Source: src/base/invocation.ts:53

createInvocation.asset

asset?: string;

Source: src/base/invocation.ts:55

createInvocation.external

external?: ExternalRefCreateDetails;

Source: src/base/invocation.ts:57

createInvocation.type

type: "wasm" | "sac" | "external";

Source: src/base/invocation.ts:54

createInvocation.wasm

wasm?: WasmCreateDetails;

Source: src/base/invocation.ts:56

DelegateSignature

A delegate signer to attach to a SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES entry via buildWithDelegatesEntry.

interface DelegateSignature {
address: string;
nestedDelegates?: DelegateSignature[];
signature?: ScVal;
}

Source: src/base/auth.ts:594

delegateSignature.address

the delegate’s address (G… account or C… contract).

address: string;

Source: src/base/auth.ts:596

delegateSignature.nestedDelegates

signers this delegate in turn delegates to (recursive).

nestedDelegates?: DelegateSignature[];

Source: src/base/auth.ts:604

delegateSignature.signature

the delegate’s signature value. Defaults to a scvVoid placeholder, which you can fill afterwards with authorizeEntry (passing this address as forAddress) or by editing the entry directly.

signature?: ScVal;

Source: src/base/auth.ts:602

ExecuteInvocation

Details about a contract function execution invocation.

  • source is the strkey of the contract (C...) being invoked
  • function is the name of the function being invoked
  • args are the natively-represented parameters to the function invocation (see scValToNative for rules on how they’re represented as JS types)
interface ExecuteInvocation {
args: any[];
function: string;
source: string;
}

Source: src/base/invocation.ts:68

executeInvocation.args

args: any[];

Source: src/base/invocation.ts:72

executeInvocation.function

function: string;

Source: src/base/invocation.ts:70

executeInvocation.source

source: string;

Source: src/base/invocation.ts:69

ExternalRefCreateDetails

Details about a contract creation from an external executable (CAP-85).

  • owner is the strkey of the account or contract that owns the external executable being referenced
  • tag is the owner-scoped name of that executable. It is an unbounded SCString, so it is not always text: a lenient UTF-8 decode would render two distinct tags identically, and the tag is half of what identifies the code being deployed. Binary tags come back as raw bytes, matching scValToNative
  • address is the strkey of the deployer and salt its hex-encoded salt, which together derive the new contract’s ID
interface ExternalRefCreateDetails {
address: string;
constructorArgs?: any[];
owner: string;
salt: string;
tag: string | Uint8Array<ArrayBufferLike>;
}

Source: src/base/invocation.ts:32

externalRefCreateDetails.address

address: string;

Source: src/base/invocation.ts:35

externalRefCreateDetails.constructorArgs

constructorArgs?: any[];

Source: src/base/invocation.ts:38

externalRefCreateDetails.owner

owner: string;

Source: src/base/invocation.ts:33

externalRefCreateDetails.salt

salt: string;

Source: src/base/invocation.ts:36

externalRefCreateDetails.tag

tag: string | Uint8Array<ArrayBufferLike>;

Source: src/base/invocation.ts:34

IntLike

type IntLike = bigint | number | string

Source: src/base/sorobandata_builder.ts:10

InvocationTree

A node in the invocation tree.

  • type is the type of invocation occurring, either contract creation or host function execution
  • args are the parameters to the invocation, depending on the type
  • invocations are any sub-invocations that may occur as a result of this invocation (i.e. a tree of call stacks)
interface InvocationTree {
args: CreateInvocation | ExecuteInvocation;
invocations: InvocationTree[];
type: "create" | "execute";
}

Source: src/base/invocation.ts:84

invocationTree.args

args: CreateInvocation | ExecuteInvocation;

Source: src/base/invocation.ts:86

invocationTree.invocations

invocations: InvocationTree[];

Source: src/base/invocation.ts:87

invocationTree.type

type: "create" | "execute";

Source: src/base/invocation.ts:85

InvocationWalker

A callback used when walking an invocation tree.

Returning exactly false is a hint to stop exploring deeper from this node; other return values are ignored.

type InvocationWalker = (node: SorobanAuthorizedInvocation, depth: number, parent?: SorobanAuthorizedInvocation) => boolean | null | void

Source: src/base/invocation.ts:102

NativeToScValOpts

interface NativeToScValOpts {
type?: ScValType | ScValMapTypeSpec | ScValType | null[];
}

Source: src/base/scval.ts:27

nativeToScValOpts.type

type?: ScValType | ScValMapTypeSpec | ScValType | null[];

Source: src/base/scval.ts:28

SigningCallback

A callback for signing an XDR structure representing all of the details necessary to authorize an invocation tree.

type SigningCallback = (preimage: HashIdPreimage, payload: Uint8Array) => Promise<Uint8Array | { publicKey: string; signature: Uint8Array } | { address?: string; signatureScVal: ScVal }>

Source: src/base/auth.ts:62

WasmCreateDetails

interface WasmCreateDetails {
address: string;
constructorArgs?: any[];
hash: string;
salt: string;
}

Source: src/base/invocation.ts:11

wasmCreateDetails.address

address: string;

Source: src/base/invocation.ts:13

wasmCreateDetails.constructorArgs

constructorArgs?: any[];

Source: src/base/invocation.ts:16

wasmCreateDetails.hash

hash: string;

Source: src/base/invocation.ts:12

wasmCreateDetails.salt

salt: string;

Source: src/base/invocation.ts:14