Skip to Content

stardust-stellar/test

Every export of stardust-stellar/test, and every type it uses, from users and wallets to prompts and checks.

stardust-stellar/test is the entry your test files import. This page lists its exports and every type they use. The guide pages linked from each section explain how to use them.

import { expect, test, units, xlm } from 'stardust-stellar/test';
import type { User, UserOptions } from 'stardust-stellar/test';
Import fromNames
stardust-stellar/testtest, expect, xlm, units, and the types StardustTestOptions, UserOptions, User, UserWallet, StardustMatchers and the expectation types
stardust-stellarThe other types on this page, such as Wallet, TransactionPrompt and Landed. Use import type

Test and options

test

export const test: StardustTest;

type StardustTest = TestType<
  PlaywrightTestArgs & PlaywrightTestOptions & Fixtures,
  PlaywrightWorkerArgs & PlaywrightWorkerOptions
>;

interface Fixtures {
  stardust: StardustTestOptions;
  users: Users;
}

type Users = Readonly<Record<string, User>>;

The test function, with Stardust's stardust option and users fixture. Declare the users once per file with test.use. Every test gets fresh ones, with new keys, new balances and new tabs.

e2e/pay.spec.ts
test.use({
  stardust: {
    users: {
      payer: { wallet: 'varial', connected: true },
      friend: {},
    },
  },
});

test('sends 5 XLM to a friend', async ({ users: { payer, friend } }) => {
  await payer.page.goto('/');
  // ...
});
FixtureTypeDescription
stardustStardustTestOptionsThe option set with test.use({ stardust: { users } })
usersUsersThe test's users, by the names declared in test.use
  • test.use goes at the top of a file or inside a test.describe block. An inner test.use replaces the outer stardust object. It doesn't merge with it.
  • Reading a user the file doesn't declare throws CONFIG_INVALID.

See Users and wallet state.

StardustTestOptions

export interface StardustTestOptions {
  users: Readonly<Record<string, UserOptions>>;
}

Stardust's option for test.use. users holds the users each test in the file gets, by name. A file without test.use has no users.

UserOptions

export interface UserOptions {
  accounts?: Readonly<Record<string, AccountOptions>>;
  allowHttp?: boolean;
  connected?: boolean;
  policy?: Policy;
  strict?: boolean;
  wallet?: 'varial' | 'sep60' | 'none';
}

One user in test.use({ stardust: { users } }). Every setting is optional.

SettingTypeDefaultDescription
wallet'varial' | 'sep60' | 'none''varial'The wallet in the user's browser. 'none' means no wallet
connectedbooleanfalseStart as if the user had already connected the site, for every account
policyPolicy'approve'How the wallet answers prompts
accountsReadonly<Record<string, AccountOptions>>{ main: { fund: true } }The wallet's accounts, by name. The first is active. List at least one
allowHttpbooleantrueWhether the wallet signs on http:// pages
strictbooleantrueFail the test at its end when the app broke wallet rules. See strict mode

A wrong setting fails with CONFIG_INVALID before the test touches the network.

AccountOptions

interface AccountOptions {
  fund?: boolean | string;
}

How an account is created.

SettingTypeDefaultDescription
fundboolean | stringtrueThe starting balance: true for 100 XLM, an amount in XLM up to '1000', or false to leave the account uncreated on the network

See Accounts.

Users

User

export interface User {
  readonly account: Account;
  readonly accounts: Readonly<Record<string, Account>>;
  readonly name: string;
  readonly page: Page;
  readonly wallet: UserWallet;
}

type UserWallet = Omit<Wallet, 'attach'>;

One person in a test: a browser tab, the wallet in it, and the wallet's accounts.

FieldTypeDescription
namestringThe user's name in test.use
pagePageThe user's browser tab, a Page
walletUserWalletThe emulated wallet in the user's tab: a Wallet without attach, since Stardust puts it in the page for you
accountAccountThe account active when the test started. It doesn't change after switchAccount
accountsReadonly<Record<string, Account>>Every account in the user's wallet, by name, such as accounts.main

With wallet: 'none', user.wallet exists but isn't in the page, so the app sees no wallet.

Use User to type helper functions:

async function connect(user: User) {
  await user.page.getByRole('button', { name: 'Connect wallet' }).click();
}

Account

interface Account {
  readonly address: string;
  readonly keypair: Keypair;
}

A throwaway testnet account Stardust created for one test.

FieldTypeDescription
addressstringThe account's public address, G...
keypairKeypairThe account's key, from @stellar/stellar-sdk. It stays in Node and never enters the page

Wallet and policies

Wallet

interface Wallet {
  readonly address: string;
  attach(
    host: PageHost,
    options: {
      wallet: 'varial' | 'sep60';
    },
  ): Promise<void>;
  disconnect(): Promise<void>;
  lock(): Promise<void>;
  readonly network: NetworkInfo;
  nextPrompt<K extends PromptKind = PromptKind>(
    kind?: K,
    options?: WaitOptions,
  ): Promise<PromptOf<K>>;
  prompts<K extends PromptKind = PromptKind>(kind?: K): readonly PromptOf<K>[];
  setPolicy(policy: Policy): void;
  subscribe(listener: (prompt: Prompt) => void): () => void;
  switchAccount(account: Account): Promise<void>;
  switchNetwork(network: 'testnet' | 'futurenet' | 'mainnet'): Promise<void>;
  unlock(): Promise<void>;
  violations(): readonly Violation[];
}

The emulated wallet in a user's page. It answers the app as the real wallet does, and records every prompt.

MemberDescription
addressThe active account's address, as the wallet reports it to the app
networkThe network the wallet reports to the app, a NetworkInfo
nextPrompt(kind?, options?)Returns the oldest prompt of kind, or of any kind, that it hasn't returned yet, waiting for one if needed. Throws NO_PROMPT when none arrives in time (10 s)
prompts(kind?)Every prompt so far in this test, or only those of kind, in arrival order
setPolicy(policy)Changes how the wallet answers prompts from now on
violations()The wallet rules the app has broken so far
subscribe(listener)Calls listener when a prompt arrives and again when it's answered. Returns a function that stops the calls
switchAccount(account)Makes another of the wallet's accounts active. Throws UNKNOWN_ACCOUNT for an account that isn't in this wallet
switchNetwork(network)Makes the wallet report another network. On 'mainnet', nothing is signed
lock()Locks the wallet. Prompts wait until unlock()
unlock()Unlocks the wallet. Waiting prompts go ahead under the policy
disconnect()Removes the site from the wallet's connected sites
attach(host, options)Puts the wallet in a page. Only on wallets from a custom setup; a user's wallet doesn't have it

nextPrompt and prompts return a prompt once it's decoded. Under 'manual' the test answers it. Under the other policies it's already answered, and the test inspects it.

See Prompts and Wallet actions.

NetworkInfo

interface NetworkInfo {
  readonly friendbotUrl: string | null;
  readonly name: 'testnet' | 'futurenet' | 'mainnet' | 'custom';
  readonly networkPassphrase: string;
  readonly protocolVersion: number;
  readonly rpcUrl: string;
}

A network, as Stardust read it from its RPC.

FieldTypeDescription
name'testnet' | 'futurenet' | 'mainnet' | 'custom'The network's name, from its passphrase. 'mainnet' appears only on wallet.network, after switchNetwork('mainnet')
rpcUrlstringThe RPC URL
networkPassphrasestringThe network passphrase
friendbotUrlstring | nullThe network's Friendbot, or null when it has none
protocolVersionnumberThe protocol version the RPC reports

WaitOptions

interface WaitOptions {
  signal?: AbortSignal;
  timeoutMs?: number;
}

How long to wait, for nextPrompt, landed() and the checks that wait.

FieldTypeDefaultDescription
timeoutMsnumber10 s for nextPrompt, 30 s for a transactionHow long to wait, in milliseconds
signalAbortSignalnoneStops the wait early

Policy

type Policy =
  | PolicyMode
  | Partial<Record<PromptKind, PolicyMode>>
  | ((prompt: Prompt) => Decision | Promise<Decision>);

type PolicyMode = 'approve' | 'reject' | 'manual';

How the wallet answers prompts.

PolicyBehaviour
'approve'Every prompt is approved as it arrives. The default
'reject'Every prompt is rejected as it arrives, including connect
'manual'Prompts wait until the test answers them
{ signTransaction: 'manual' }One PolicyMode per prompt kind. Kinds left out are approved
(prompt) => DecisionA function that returns a Decision for each prompt, or a promise of one
trader.wallet.setPolicy({ signTransaction: 'manual' });
trader.wallet.setPolicy((prompt) =>
  prompt.kind === 'signMessage' ? { action: 'reject' } : { action: 'approve' },
);

When a policy approves a blocked prompt, the wallet rejects it instead, as a real user could only reject it. After switchNetwork('mainnet'), it does the same for every prompt except connect. A locked wallet's prompts wait under every policy. See Policies.

Decision

type Decision =
  | {
      action: 'approve';
    }
  | {
      action: 'reject';
    }
  | {
      action: 'fail';
      code: -1 | -2 | -3;
      message?: string;
    }
  | {
      action: 'hang';
    };

How a policy function answers a prompt.

DecisionWhat the app receives
{ action: 'approve' }The real result: signed transaction, signature or address
{ action: 'reject' }Error -4, The user rejected this request.
{ action: 'fail', code, message? }A wallet error, as with fail()
{ action: 'hang' }Nothing, ever

A function that returns anything else fails the test with CONFIG_INVALID.

Violation

interface Violation {
  readonly detail: string;
  readonly kind: ViolationKind;
  readonly promptId: string | null;
}

type ViolationKind =
  | 'missingNetworkPassphrase'
  | 'networkMismatch'
  | 'invalidXdr'
  | 'signerMismatch'
  | 'unknownMessage';

A wallet rule the app broke. With strict: true, each one fails the test at its end.

FieldDescription
promptIdThe prompt it happened on, such as 'p2', or null when it wasn't on a prompt
kindWhich rule the app broke
detailWhat the app did, in a sentence
KindWhen
missingNetworkPassphrasesignTransaction or addToken without a network passphrase. Real Varial (formerly Freighter) then assumes mainnet. Varial only
networkMismatchThe app asked to sign for a different network than the wallet's
invalidXdrThe app sent something that isn't valid XDR
signerMismatchThe app named a signer that isn't the wallet's account
unknownMessageThe app sent a message type Varial doesn't recognize. Varial only

See Strict mode.

Prompts

Prompt

type Prompt =
  | ConnectPrompt
  | TransactionPrompt
  | AuthEntryPrompt
  | MessagePrompt
  | AddTokenPrompt;

type PromptOf<K extends PromptKind> = Extract<
  Prompt,
  {
    kind: K;
  }
>;

Anything a real wallet shows the user as a popup. Narrow it by kind. PromptOf<'signTransaction'> is TransactionPrompt, which is what nextPrompt('signTransaction') returns.

PromptKind

type PromptKind =
  'connect' | 'signTransaction' | 'signAuthEntry' | 'signMessage' | 'addToken';
KindThe app asks forPrompt type
connectThe address, on a site that isn't connectedConnectPrompt
signTransactionA whole transaction to be signedTransactionPrompt
signAuthEntryOne contract call to be authorized, while someone else sends the transactionAuthEntryPrompt
signMessageA message to be signed, as proof of owning the addressMessagePrompt
addTokenA token to be added. 'varial' onlyAddTokenPrompt

PromptStatus

type PromptStatus = 'pending' | 'approved' | 'rejected' | 'failed' | 'hung';

Where a prompt is in its life: 'pending' until it's answered, then the answer. approve() gives 'approved', reject() gives 'rejected', fail() gives 'failed' and hang() gives 'hung'.

BlockedReason

type BlockedReason =
  | 'notConnected'
  | 'networkMismatch'
  | 'insecureOrigin'
  | 'alreadyAdded'
  | 'locked';

Why the real wallet would refuse a prompt.

ReasonMeaning
notConnectedThe site isn't connected
networkMismatchThe app asked for another network than the wallet's
insecureOriginThe page isn't https and allowHttp is false
alreadyAddedThe token is already added
lockedThe wallet is locked

approve() on a blocked prompt throws PROMPT_BLOCKED, or WALLET_LOCKED for 'locked'. reject() always works.

BasePrompt

interface BasePrompt<K extends PromptKind> {
  approve(): Promise<void>;
  readonly blocked: BlockedReason | null;
  fail(error: Failure): Promise<void>;
  hang(): void;
  readonly id: string;
  readonly kind: K;
  readonly networkPassphrase: string | null;
  readonly origin: string;
  reject(): Promise<void>;
  readonly status: PromptStatus;
}

interface Failure {
  code: -1 | -2 | -3;
  message?: string;
}

What every prompt has. Each prompt is answered exactly once. A second answer throws ALREADY_ANSWERED.

MemberDescription
id'p1', 'p2', … in arrival order within a test
kindThe prompt kind
originThe site that sent it, taken from the browser, never from the page's message
networkPassphraseThe network passphrase the app asked for, or null when it sent none
statusA PromptStatus, 'pending' until the prompt is answered
blockedA BlockedReason, or null when the real wallet wouldn't refuse it
approve()Approves the prompt. The app receives the real result. Resolves once the reply has reached the page. Throws PROMPT_BLOCKED when blocked, WALLET_LOCKED while locked, and MAINNET_REFUSED on every kind but connect while the wallet is on mainnet
reject()Rejects the prompt. The app receives error -4, The user rejected this request.
fail(error)Answers with a wallet error
hang()Never answers. The app's call waits forever, as when a user ignores the popup
Failure fieldDescription
code-1 for an internal error, -2 for an external service, -3 for an invalid request
messageThe error message. Default: Varial's internal-error text for -1, Stardust: simulated wallet error (code N) otherwise

ConnectPrompt

type ConnectPrompt = BasePrompt<'connect'>;

The app asks for the user's address, on a site that isn't connected. It has no fields beyond BasePrompt.

TransactionPrompt

interface TransactionPrompt extends BasePrompt<'signTransaction'> {
  landed(options?: WaitOptions): Promise<Landed>;
  readonly transaction: DecodedTransaction;
}

The app asks for a whole transaction to be signed.

MemberDescription
transactionThe transaction, decoded, a DecodedTransaction
landed(options?)Waits for the signed transaction to land and returns its outcome. Throws OUTCOME_UNKNOWN when it doesn't appear in time (30 s)

On a pending prompt, landed() first waits for the answer, within the same timeout. On a rejected, failed or hung prompt, it throws UNSUPPORTED, because nothing was signed.

AuthEntryPrompt

interface AuthEntryPrompt extends BasePrompt<'signAuthEntry'> {
  landed(options?: WaitOptions): Promise<Landed>;
  readonly preimage: DecodedAuthPreimage;
}

The app asks for one contract call to be authorized, while someone else sends the transaction.

MemberDescription
preimageThe authorization entry preimage, decoded, a DecodedAuthPreimage
landed(options?)Waits for a transaction that uses this authorization to land, and returns its outcome. Throws OUTCOME_UNKNOWN when none appears in time (30 s)

landed() handles pending, rejected, failed and hung prompts as on TransactionPrompt.

MessagePrompt

interface MessagePrompt extends BasePrompt<'signMessage'> {
  readonly message: string;
}

The app asks for a message to be signed, as proof of owning the address. Nothing moves on chain. message is the message as the app sent it.

AddTokenPrompt

interface AddTokenPrompt extends BasePrompt<'addToken'> {
  readonly contractId: string;
}

The app asks the wallet to add a token, 'varial' only. contractId is the token contract, C.... See Varial.

Decoded data

DecodedTransaction

interface DecodedTransaction {
  readonly authEntries: readonly DecodedAuthEntry[];
  readonly fee: bigint;
  readonly hash: string;
  readonly invocations: readonly Invocation[];
  readonly memo: {
    type: 'none' | 'text' | 'id' | 'hash' | 'return';
    value: string | null;
  };
  readonly operations: readonly DecodedOperation[];
  readonly sequence: bigint;
  readonly source: string;
  readonly xdr: string;
}

A transaction the app asked the wallet to sign, decoded.

FieldTypeDescription
xdrstringThe transaction envelope as the app sent it, base64 XDR
hashstringThe transaction hash, hex. For a fee bump, the fee bump's hash
sourcestringThe source account. For a fee bump, the account paying the fee
feebigintThe declared maximum fee, in stroops
sequencebigintThe sequence number
memo{ type, value }The memo. value is null for 'none', and hex for 'hash' and 'return'
operationsreadonly DecodedOperation[]The operations, in order
invocationsreadonly Invocation[]The contract call and every sub-call it authorizes, flattened in order. Empty for a classic transaction
authEntriesreadonly DecodedAuthEntry[]The authorization entries attached to the contract call

DecodedOperation

interface DecodedOperation {
  readonly body: Readonly<Record<string, unknown>>;
  readonly source: string | null;
  readonly type: string;
}

One operation of a transaction.

FieldTypeDescription
typestringThe operation type, as the Stellar SDK names it, such as 'payment' or 'invokeHostFunction'
sourcestring | nullThe operation's own source account, or null when it uses the transaction's
bodyReadonly<Record<string, unknown>>The operation's fields, named as in the Stellar SDK. Assets are 'native' or 'CODE:ISSUER', amounts are bigint stroops

Invocation

interface Invocation {
  readonly args: readonly unknown[];
  readonly contract: string;
  readonly depth: number;
  readonly fn: string;
  readonly namedArgs: Readonly<Record<string, unknown>> | null;
}

A contract call.

FieldTypeDescription
contractstringThe contract called, C...
fnstringThe function name
argsreadonly unknown[]The arguments in order, converted from XDR. Integers are bigint, addresses are strings
namedArgsReadonly<Record<string, unknown>> | nullThe arguments by name, from the contract's spec, or null when the spec can't be read
depthnumberHow deep the call is: 0 for the top-level call

DecodedAuthEntry

interface DecodedAuthEntry {
  readonly address: string;
  readonly expirationLedger: number;
  readonly invocations: readonly Invocation[];
  readonly xdr: string;
}

An authorization entry attached to a transaction, decoded.

FieldTypeDescription
xdrstringThe entry, base64 XDR
addressstringWho must authorize it
expirationLedgernumberThe last ledger in which the authorization is valid
invocationsreadonly Invocation[]The calls it authorizes, flattened in order

DecodedAuthPreimage

interface DecodedAuthPreimage {
  readonly expirationLedger: number;
  readonly invocations: readonly Invocation[];
  readonly networkPassphrase: string | null;
  readonly nonce: bigint;
  readonly xdr: string;
}

An authorization entry preimage the app asked the wallet to sign, decoded.

FieldTypeDescription
xdrstringThe preimage as the app sent it, base64 XDR
networkPassphrasestring | nullThe network the preimage is for, matched from its network ID, or null when it's not a known network
noncebigintThe authorization's nonce
expirationLedgernumberThe last ledger in which the authorization is valid
invocationsreadonly Invocation[]The calls it authorizes, flattened in order

Outcome

Landed

type Landed =
  | {
      readonly status: 'success';
      readonly hash: string;
      readonly ledger: number;
      readonly feeCharged: bigint;
      readonly feeBump: boolean;
      readonly returnValue: unknown;
      readonly events: readonly ContractEvent[];
      readonly balanceChanges: readonly BalanceChange[];
    }
  | {
      readonly status: 'failed';
      readonly hash: string;
      readonly ledger: number;
      readonly resultCode: string;
      readonly contractError: ContractError | null;
    };

A transaction's outcome once it's in a ledger, from prompt.landed(). Check status before reading the other fields. A transaction that doesn't appear in time throws OUTCOME_UNKNOWN instead.

FieldStatusDescription
statusboth'success' or 'failed'
hashbothThe transaction hash, hex
ledgerbothThe ledger the transaction is in
feeChargedsuccessThe fee charged, in stroops
feeBumpsuccessWhether the transaction landed inside a fee bump
returnValuesuccessA contract call's return value, converted from XDR, or undefined
eventssuccessThe contract events the transaction emitted
balanceChangessuccessEvery balance the transaction changed, read from its events. Fees aren't included
resultCodefailedThe transaction's result code, such as 'txFAILED'
contractErrorfailedThe contract error that made it fail, or null

BalanceChange

interface BalanceChange {
  readonly address: string;
  readonly asset: Asset;
  readonly change: bigint;
}

How much one address's balance of one asset changed.

FieldTypeDescription
addressstringThe account or contract whose balance changed
assetAssetThe asset. In Landed.balanceChanges, it's the token contract, C..., for XLM and classic assets too
changebigintThe change in the asset's smallest units: stroops for XLM. Negative when the balance went down

Asset

type Asset = 'native' | `${string}:${string}` | `C${string}`;

An asset: 'native' for XLM, 'CODE:ISSUER' for a classic asset, or a token contract's address, C....

ContractEvent

interface ContractEvent {
  readonly contract: string;
  readonly data: unknown;
  readonly topics: readonly unknown[];
}

An event a contract emitted.

FieldTypeDescription
contractstringThe contract that emitted the event, C...
topicsreadonly unknown[]The event's topics, converted from XDR. The first is usually its name, such as 'transfer'
dataunknownThe event's data, converted from XDR

ContractError

interface ContractError {
  readonly code: number;
  readonly contract: string;
  readonly name: string | null;
}

An error a contract returned.

FieldTypeDescription
contractstringThe contract that returned the error, C...
codenumberThe error number
namestring | nullThe error's name from the contract's spec, or null when the spec can't be read

Checks

expect

export const expect: Expect<StardustMatchers>;

expect, with Stardust's checks on prompts added. Checks on the page, such as toBeVisible(), work as usual.

CheckPrompt kindsWaitsPasses when
toInvoke(expected)signTransaction, signAuthEntryNoThe contract call, or a sub-call it authorizes, matches
toHaveOperation(expected)signTransactionNoThe transaction contains this classic operation
toLand(options?)signTransaction, signAuthEntryYesThe transaction lands with status SUCCESS
toFail(expected?, options?)signTransaction, signAuthEntryYesThe transaction lands with status FAILED, with this error if one is given
toChangeBalance(address, asset, change, options?)signTransaction, signAuthEntryYesThe transaction changed address's balance of asset by change, fees excluded
toEmit(expected, options?)signTransaction, signAuthEntryYesThe contract emitted an event with this first topic
  • Checks that wait take WaitOptions last, 30 s by default. To pass only options to toFail, give {} first.
  • On a rejected, failed or hung prompt, a check that waits fails at once and names the status. On a pending prompt, it waits for the answer within the same timeout.
  • .not works only on checks that don't wait. On the others it throws UNSUPPORTED. Use toFail instead of .not.toLand().
  • toInvoke with args throws UNSUPPORTED when the contract's spec can't be read.
  • asset in toChangeBalance is 'native', 'CODE:ISSUER' or a token contract, C....
await expect(prompt).toLand({ timeoutMs: 60_000 });
await expect(prompt).toFail({}, { timeoutMs: 60_000 });

See Transactions and Balances and events.

StardustMatchers

type StardustMatchers = {
  toInvoke(
    this: MatcherState,
    prompt: TransactionPrompt | AuthEntryPrompt,
    expected: InvokeExpectation,
  ): MatcherResult;
  toHaveOperation(
    this: MatcherState,
    prompt: TransactionPrompt,
    expected: OperationExpectation,
  ): MatcherResult;
  toLand(
    this: MatcherState,
    prompt: TransactionPrompt | AuthEntryPrompt,
    options?: WaitOptions,
  ): Promise<MatcherResult>;
  toFail(
    this: MatcherState,
    prompt: TransactionPrompt | AuthEntryPrompt,
    expected?: FailExpectation,
    options?: WaitOptions,
  ): Promise<MatcherResult>;
  toChangeBalance(
    this: MatcherState,
    prompt: TransactionPrompt | AuthEntryPrompt,
    address: string,
    asset: string,
    change: BalanceExpectation,
    options?: WaitOptions,
  ): Promise<MatcherResult>;
  toEmit(
    this: MatcherState,
    prompt: TransactionPrompt | AuthEntryPrompt,
    expected: EmitExpectation,
    options?: WaitOptions,
  ): Promise<MatcherResult>;
};

Stardust's checks, as expect receives them. In a test, prompt is the value you pass to expect, and the other parameters are the check's arguments.

Expectations

interface InvokeExpectation {
  readonly args?: Readonly<Record<string, unknown>>;
  readonly contract: string;
  readonly fn: string;
}

interface OperationExpectation {
  readonly [field: string]: unknown;
  readonly type: string;
}

interface FailExpectation {
  readonly contractError?: string | number;
  readonly resultCode?: string;
}

type BalanceExpectation =
  | bigint
  | {
      readonly min?: bigint;
      readonly max?: bigint;
    };

interface EmitExpectation {
  readonly contract: string;
  readonly topic: string;
}

What each check compares.

TypeFieldDescription
InvokeExpectationcontractThe contract, C...
fnThe function name
argsArguments by name, from the contract's spec. Only listed arguments are compared
OperationExpectationtypeThe operation type, such as 'payment' or 'changeTrust'
any otherA field to compare, named as in the Stellar SDK. Assets are 'native' or 'CODE:ISSUER', amounts are bigint stroops. Only listed fields are compared
FailExpectationresultCodeThe result code, such as 'txFAILED'
contractErrorThe contract error, by name from the contract's spec or by number. Leave both fields out to accept any failure
BalanceExpectationAn exact change in the asset's smallest units, or { min?, max? } when the exact amount can't be known
EmitExpectationcontractThe contract that emits the event, C...
topicThe event's name, compared with its first topic, such as 'transfer'

MatcherState and MatcherResult

interface MatcherState {
  readonly isNot: boolean;
}

interface MatcherResult {
  readonly message: () => string;
  readonly pass: boolean;
}

What expect passes to a check and reads back. isNot is true when the check was called through .not. Tests don't use these types.

Helpers

xlm

export function xlm(amount: string): bigint;

Converts an XLM amount, written as a decimal string, to stroops. xlm('10') is 100_000_000n. Throws a RangeError when amount isn't a decimal amount or has more than 7 decimal places.

units

export function units(amount: string, decimals: number): bigint;

Converts a token amount, written as a decimal string, to the token's smallest units. units('9.8', 7) is 98_000_000n. Throws a RangeError when amount isn't a decimal amount or has more decimal places than decimals, and when decimals isn't a whole number of 0 or more.

Both helpers take amounts of 0 or more. For a decrease, negate the result:

await expect(prompt).toChangeBalance(address, 'native', -xlm('10'));

On this page