Stellar JS SDK

repository·main·Indexed 20 days ago

https://github.com/stellar/js-stellar-sdk

A JavaScript library for interacting with the Stellar network, providing tools for building and signing transactions, querying network history, and communicating with Horizon (REST) and Soroban RPC (JSON-RPC) servers. Supports Node.js, browser, and mobile environments, and includes a CLI tool for generating TypeScript bindings from Stellar smart contracts.

Tokens
150.9K
Snippets
506
Records
640
Agent score
72%

What's inside @stellar/stellar-sdk

  1. Use the Contracts Client for Soroban smart contracts

    main
    The Contracts Client is a high-level interface designed for interacting with Soroban smart contracts. It provides a streamlined workflow to assemble transaction payloads, simulate them to predict outcomes, sign them, and finally submit them to the network. This abstraction manages the complexities of constructing the specific transaction types required for contract invocations.
  2. Understand SimulateTransactionResponse types

    main

    The rpc.Api.SimulateTransactionResponse is a union type that simplifies the raw simulation response into three distinct interfaces based on the outcome of the simulation. This allows you to handle different scenarios (success, restoration needed, or error) using type guards or checking for specific fields.

    • SimulateTransactionSuccessResponse: Returned when the simulation succeeds. Includes minResourceFee, transactionData, and optionally result (if an invocation was simulated) and stateChanges.
    • SimulateTransactionRestoreResponse: Returned when an expiration error occurs, indicating that a restoration is necessary before submission. It includes a restorePreamble containing the minResourceFee and transactionData required to make the simulation succeed.
    • SimulateTransactionErrorResponse: Returned for all other errors. Includes the error string and events.
  3. How Horizon's CallFunction and CallCollectionFunction work

    main

    The Horizon ServerApi uses two primary patterns for retrieving data from the network:

    1. CallFunction<T>: Used to fetch a single resource of type T. It returns a Promise<T>.
    2. CallCollectionFunction<T>: Used to fetch a paginated collection of resources of type T. It returns a Promise<CollectionPage<T>>.

    When calling a collection function, you can pass CallFunctionTemplateOptions to control the results.

    // Example of using CallFunctionTemplateOptions with a collection
    const collection = await horizonApi.someCollection({ 
      cursor: 'some_token', 
      limit: 10, 
      order: 'desc' 
    });
  4. Understand the InvocationTree structure

    main

    An InvocationTree represents the call stack of Soroban operations. Each node in the tree has a type of either create or execute.

    • create type: Uses CreateInvocation details. This can be a custom contract (type: 'wasm') or a Stellar Asset Contract (type: 'sac').
      • For wasm: Requires WasmCreateDetails (address, hash, salt, and optional constructor arguments).
      • For sac: Requires an asset string.
    • execute type: Uses ExecuteInvocation details, specifying the contract source, the function name, and the args array.

    Each node can contain a list of invocations (sub-invocations) that occur as a result of that node's execution, forming a tree structure.

  5. Use the Signer interface for identity-aware signing

    main

    A Signer bundles a signing function with a specific identity (address). This is preferred over bare signing callbacks because it ensures the SDK knows which address is performing the signature. The address can be a G... account address or a C... contract address for smart accounts.

    An interface implementing Signer must provide:

    • address: The string address of the signer.
    • signTransaction: A function to sign a transaction envelope (matches SEP-43/Freighter shape).
    • signAuthEntry (optional): A function to sign an authorization entry preimage (required for multi-party auth).
    interface Signer {
      readonly address: string;
      signAuthEntry?: SignAuthEntry;
      signTransaction: SignTransaction;
    }
  6. Understand the role of AssembledTransaction

    main

    The AssembledTransaction class is the primary tool for managing transactions under construction in the Client. It wraps a transaction and provides high-level interfaces for common workflows (like reading or writing to a contract) while allowing low-level access to the underlying stellar-sdk transaction via the .raw property.

    Most developers interact with AssembledTransaction indirectly by calling methods on a Client instance, which returns an AssembledTransaction automatically.

  7. Protocol 27: Use AddressV2 for Soroban Authorization

    main

    Protocol 27 introduces AddressV2 and AddressWithDelegates. While the SDK is forward-compatible, you can opt-in to ADDRESS_V2 credentials by passing authV2: true to authorizeInvocation.

    // Opt-in to AddressV2
    const entry = await authorizeInvocation({
      signer,
      validUntilLedgerSeq,
      invocation,
      networkPassphrase,
      authV2: true,
    })
    
    // Read the V2 address
    const addr = entry.credentials().addressV2()
  8. Understand Horizon TradeRecord types

    main

    A TradeRecord in the Horizon API represents a trading pair and can be one of two types:

    1. Orderbook: A traditional order book for a trading pair.
    2. LiquidityPool: A liquidity pool record used in Stellar's Automated Market Maker (AMM) functionality.
    type TradeRecord = TradeRecord.Orderbook | TradeRecord.LiquidityPool
  9. Difference between Envelope and Authorization signatures

    main

    An invoke transaction involves two distinct types of signatures:

    FeatureEnvelope signatureAuthorization-entry signature
    PurposeAuthorizes the source to submit the transaction and pay fees.Authorizes specific contract calls via require_auth().
    Who signsThe transaction source (and classic multisig signers).Each address required by the contract (if not the source).
    What it signsThe entire transaction hash.A specific invocation payload per address.
    SDK APItx.sign / signTransactionsignAuthEntries, authorizeEntry
    AddressV2 ImpactUnchanged.Payload becomes address-bound.

    Note: If the account being authorized is the transaction source, the envelope signature already covers it, and no separate authorization signature is required.

  10. Understand FeeBump and InnerTransaction responses

    main

    The Horizon API uses specific response shapes for transaction-related operations:

    • FeeBumpTransactionResponse: Returned when bumping a transaction fee. It contains the transaction hash and an array of signatures.
    • InnerTransactionResponse: Used for inner transactions, containing the hash, max_fee, and signatures.
    interface FeeBumpTransactionResponse {
      hash: string;
      signatures: string[];
    }
    
    interface InnerTransactionResponse {
      hash: string;
      max_fee: string;
      signatures: string[];
    }
  11. How the Keypair class works

    main

    The Keypair class represents the public and (optionally) secret keys of a Stellar account. It is currently used for ed25519 signature systems. A Keypair can either be a public-only key (used for verification) or a full keypair containing a secret key (used for signing).

    Key capabilities include:

    • Generation: Creating new keys via random(), fromSecret(), or fromPublicKey().
    • Signing: Generating signatures for raw data, decorated signatures for transaction envelopes, or SEP-53 compliant messages.
    • Verification: Verifying signatures against data using the public key.
    • Encoding: Exporting keys to Stellar strkey format, raw Buffer bytes, or XDR representations.
    // Example of creating a random keypair and getting its public key
    const keypair = Keypair.random();
    console.log(keypair.publicKey()); // e.g., 'GB3KJ...'
    
    // Example of signing data (requires a secret key)
    if (keypair.canSign()) {
      const signature = keypair.sign(Buffer.from('some data'));
    }
  12. Use Horizon.AccountResponse to retrieve account information

    main

    The Horizon.AccountResponse class provides detailed information and links for a single Stellar account. It includes balances (including trust lines), account flags, thresholds, and sequence numbers. It also implements the TransactionSource interface, meaning it can be passed directly to a TransactionBuilder to use its data as a source for new transactions.

    Important: Do not instantiate this class directly using new AccountResponse(). Instead, use Horizon.Server#loadAccount to retrieve an instance.

    // Correct way to get an AccountResponse
    const account = await server.loadAccount(accountId);
    
    // Use it in a transaction builder
    const transaction = new TransactionBuilder(account, network)
      .addOperation(operation)
      .build();