### Start Local Stellar Network with Quickstart Source: https://developers.stellar.org/docs/tools/lab/quickstart-with-lab This command initiates a local Stellar network environment using the Stellar CLI. It bundles Stellar Core, Horizon, RPC, Friendbot, and PostgreSQL databases. Ensure you have Stellar CLI and Docker installed before running. ```bash stellar network container start testnet ``` -------------------------------- ### Initialize and run dbt environment Source: https://developers.stellar.org/docs/data/analytics/hubble/developer-guide/data-curation/getting-started Commands to clone the repository, install dependencies, and execute dbt build operations for data models. ```bash git clone https://github.com/stellar/stellar-dbt-public pip install --upgrade pip && pip install -r requirements.txt dbt deps dbt build --full-refresh dbt build dbt build --select ``` -------------------------------- ### Example Horizon Startup Log Source: https://developers.stellar.org/docs/data/apis/horizon/admin-guide/running This is an example log output indicating that the Horizon process has started successfully and is ready to serve client requests on port 8000. ```log INFO[...] Starting horizon on :8000 pid=29013 ``` -------------------------------- ### Initialize and Start Anchor Platform Source: https://developers.stellar.org/docs/platforms/anchor-platform/admin-guide/getting-started Commands to clone the repository, navigate to the quick-run directory, and launch the platform services using the provided shell script. ```bash git clone https://github.com/stellar/anchor-platform cd anchor-platform/quick-run ./ap_start.sh ``` -------------------------------- ### Build and Setup Commands Source: https://developers.stellar.org/docs/build/smart-contracts/example-contracts/simple-account Essential shell commands for cloning the examples repository, running tests, and building the contract into a Wasm executable. ```bash git clone -b v23.0.0 https://github.com/stellar/soroban-examples cd simple_account cargo test stellar contract build ``` -------------------------------- ### Install Stellar SDK and Dependencies Source: https://developers.stellar.org/docs/build/guides/dapps/frontend-guide Install the official Stellar SDK, Freighter wallet API, and BigNumber library for blockchain interactions. ```bash npm install stellar-sdk @stellar/freighter-api bignumber.js ``` -------------------------------- ### Clone Soroban Examples Repository Source: https://developers.stellar.org/docs/build/guides/dapps/initialization Clones the Stellar Soroban examples repository from GitHub. This is the first step to get the necessary smart contract code. ```bash git clone https://github.com/stellar/soroban-examples.git ``` -------------------------------- ### Implement Rust Modules, Macros, Structs, and Traits Source: https://developers.stellar.org/docs/learn/migrate/evm/solidity-and-rust-basics Provides basic implementation examples for core Rust language features including module namespacing, declarative macros, custom structs, and trait-based behavior definition. ```rust // Modules mod my_module { pub fn my_function() { println!("Hello from my_module!"); } } // Macros macro_rules! my_macro { () => { println!("Hello from my_macro!"); }; } // Structs struct MyStruct { field1: i32, field2: String } // Traits trait MyTrait { fn my_method(&self); } impl MyTrait for MyStruct { fn my_method(&self) { println!("Hello from MyTrait's my_method!"); } } ``` -------------------------------- ### Node.js Backend Setup Source: https://developers.stellar.org/docs/platforms/anchor-platform/sep-guide/sep24/example Commands to initialize a Node.js project and install necessary dependencies for handling JWT authentication. ```bash yarn init -y yarn add express jsonwebtoken touch server.js ``` -------------------------------- ### Install py-stellar-base SDK Source: https://developers.stellar.org/docs/learn/fundamentals/contract-development/contract-interactions/stellar-transaction This snippet shows the command to install the stellar-sdk package, which provides support for interacting with Soroban smart contracts. It is a prerequisite for using the SDK. ```bash pip install stellar-sdk ``` -------------------------------- ### Install Stellar TypeScript Wallet SDK Source: https://developers.stellar.org/docs/build/apps/wallet/intro Adds the Stellar TypeScript Wallet SDK dependency to your project using Yarn. ```bash yarn add @stellar/typescript-wallet-sdk ``` -------------------------------- ### Configure dbt profiles and project settings Source: https://developers.stellar.org/docs/data/analytics/hubble/developer-guide/data-curation/getting-started Example configuration for profiles.yml and dbt_project.yml to include stellar-dbt-public settings and define model materialization strategies. ```yaml new_project: target: test outputs: test: project: dataset: stellar_dbt_public: target: test outputs: test: project: dataset: ``` ```yaml name: 'stellar_dbt' version: '1.0.0' config-version: 2 profile: 'new_project' models: new_project: staging: +materialized: view stellar_dbt_public: staging: +materialized: ephemeral ``` -------------------------------- ### Run Local Stellar RPC Node with Docker Source: https://developers.stellar.org/docs/data/apis/rpc/admin-guide/development Starts a standalone Stellar network instance using the official Quickstart Docker image with RPC enabled. The container is automatically removed upon termination. ```bash docker run --rm -it \ -p 8000:8000 \ --name stellar \ stellar/quickstart:testing \ --local \ --enable-stellar-rpc ``` -------------------------------- ### Verify Node.js and npm Installation Source: https://developers.stellar.org/docs/build/guides/dapps/frontend-guide Commands to check the installed versions of Node.js and npm to ensure the development environment is ready. ```bash node --version npm --version ``` -------------------------------- ### Initialize SolidJS Project Source: https://developers.stellar.org/docs/build/apps/dapp-frontend Commands to scaffold a new SolidJS project using degit, install dependencies, and start the development server. ```shell npx degit solidjs/templates/vanilla/bare soroban-template-solid cd soroban-template-solid npm install npm run dev ``` -------------------------------- ### Setup Stellar Accounts and Assets (Python) Source: https://developers.stellar.org/docs/learn/fundamentals/liquidity-on-stellar-sdex-liquidity-pools Initializes Stellar SDK, defines helper functions for transaction building, asset ordering, and account loading. It sets up test accounts and assets for liquidity pool examples. ```python from decimal import Decimal from typing import List, Any, Dict from stellar_sdk import * server = Server("https://horizon-testnet.stellar.org") # Preamble def new_tx_builder(source: str) -> TransactionBuilder: network_passphrase = Network.TESTNET_NETWORK_PASSPHRASE base_fee = 100 source_account = server.load_account(source) builder = TransactionBuilder( source_account=source_account, network_passphrase=network_passphrase, base_fee=base_fee ).set_timeout(30) return builder # Returns the given asset pair in "protocol order." def order_asset(a: Asset, b: Asset) -> List[Asset]: return [a, b] if LiquidityPoolAsset.is_valid_lexicographic_order(a, b) else [b, a] secrets = [ "SBGCD73TK2PTW2DQNWUYZSTCTHHVJPL4GZF3GVZMCDL6GYETYNAYOADN", "SAAQFHI2FMSIC6OFPWZ3PDIIX3OF64RS3EB52VLYYZBX6GYB54TW3Q4U", "SCJWYFTBDMDPAABHVJZE3DRMBRTEH4AIC5YUM54QGW57NUBM2XX6433P", ] kps = [Keypair.from_secret(secret=secret) for secret in secrets] ``` -------------------------------- ### Install JavaScript Stellar SDK Source: https://developers.stellar.org/docs/learn/fundamentals/contract-development/contract-interactions/stellar-transaction Installs the @stellar/stellar-sdk package using npm. This is the first step to using the SDK in a JavaScript project. ```bash npm install --save @stellar/stellar-sdk ``` -------------------------------- ### Install Node Dependencies for Scaffold Stellar Source: https://developers.stellar.org/docs/build/smart-contracts/getting-started/hello-world-frontend Installs frontend dependencies for a Scaffold Stellar project and copies the example environment variable file. Assumes Node.js is installed. ```bash cd npm install cp .env.example .env ``` -------------------------------- ### Setup Stellar Accounts and Assets (JavaScript) Source: https://developers.stellar.org/docs/learn/fundamentals/liquidity-on-stellar-sdex-liquidity-pools Initializes Stellar SDK, defines helper functions for transaction building, asset ordering, account loading, and asset distribution. It sets up test accounts and assets for liquidity pool examples. ```javascript const sdk = require("stellar-sdk"); const BigNumber = require("bignumber.js"); let server = new sdk.Server("https://horizon-testnet.stellar.org"); /// Helps simplify creating & signing a transaction. function buildTx(source, signer, ...ops) { let tx = new sdk.TransactionBuilder(source, { fee: sdk.BASE_FEE, networkPassphrase: sdk.Networks.TESTNET, }); ops.forEach((op) => tx.addOperation(op)); tx = tx.setTimeout(30).build(); tx.sign(signer); return tx; } /// Returns the given asset pair in "protocol order." function orderAssets(A, B) { return sdk.Asset.compare(A, B) <= 0 ? [A, B] : [B, A]; } /// Returns all of the accounts we'll be using. function getAccounts() { return Promise.all(kps.map((kp) => server.loadAccount(kp.publicKey()))); } const kps = [ "SBGCD73TK2PTW2DQNWUYZSTCTHHVJPL4GZF3GVZMCDL6GYETYNAYOADN", "SAAQFHI2FMSIC6OFPWZ3PDIIX3OF64RS3EB52VLYYZBX6GYB54TW3Q4U", "SCJWYFTBDMDPAABHVJZE3DRMBRTEH4AIC5YUM54QGW57NUBM2XX6433P", ].map((s) => sdk.Keypair.fromSecret(s)); // kp0 issues the assets const kp0 = kps[0]; const [A, B] = orderAssets( ...[new sdk.Asset("A", kp0.publicKey()), new sdk.Asset("B", kp0.publicKey())], ); /// Establishes trustlines and funds `recipientKps` for all `assets`. function distributeAssets(issuerKp, recipientKps, ...assets) { return server.loadAccount(issuerKp.publicKey()).then((issuer) => { const ops = recipientKps .map((recipientKp) => assets.map((asset) => [ sdk.Operation.changeTrust({ source: recipientKp.publicKey(), limit: "100000", asset: asset, }), sdk.Operation.payment({ source: issuerKp.publicKey(), destination: recipientKp.publicKey(), amount: "100000", asset: asset, }), ]), ) .flat(2); let tx = buildTx(issuer, issuerKp, ...ops); tx.sign(...recipientKps); return server.submitTransaction(tx); }); } function preamble() { return distributeAssets(kp0, [kps[1], kps[2]], A, B); } ``` -------------------------------- ### Execute JSON-RPC Request via Bash Source: https://developers.stellar.org/docs/platforms/anchor-platform/sep-guide/sep24/integration A command-line example demonstrating how to execute a JSON-RPC request by passing a configuration file to a shell script. ```bash ./call-json-rpc.sh request-offchain-funds.json ``` -------------------------------- ### Example Initialization Script Source: https://developers.stellar.org/docs/build/guides/dapps/initialization A bash script designed to automate the initialization process of a Soroban Dapp. It handles network setup, identity generation, funding, contract building, deployment, and initialization. ```bash #!/bin/bash set -e NETWORK="$1" # If stellar-cli is called inside the soroban-preview docker container, ``` -------------------------------- ### Initialize a new Soroban project Source: https://developers.stellar.org/docs/build/smart-contracts/getting-started/hello-world Uses the Stellar CLI to scaffold a new Soroban smart contract project with a standard Rust workspace structure. ```shell stellar contract init soroban-hello-world ``` -------------------------------- ### Create New Rust Library for Stellar Contract Source: https://developers.stellar.org/docs/learn/migrate/evm/solidity-and-rust-basics This command initializes a new Rust library project, which will serve as the foundation for your Stellar smart contract. It sets up the basic file structure and configuration needed for a Rust project. ```bash cargo new --lib increment ``` -------------------------------- ### Install Stellar SDK Go Module Source: https://developers.stellar.org/docs/data/indexers/build-your-own/ingest-sdk/examples Installs the latest version of the Stellar Go SDK and tidies up the go.mod file. This is a prerequisite for using the SDK in your Go project. ```go go get github.com/stellar/go-stellar-sdk@latest go mod tidy ``` -------------------------------- ### Rust: Basic Hello World Program Source: https://developers.stellar.org/docs/learn/migrate/evm/solidity-and-rust-basics A simple 'Hello, world!' program written in Rust. This is a standard entry point for demonstrating Rust syntax and the basic structure of a Rust executable. It utilizes the `println!` macro for output. ```rust fn main() { println!("Hello, world!"); } ``` -------------------------------- ### Setup Stellar Network and Accounts Source: https://developers.stellar.org/docs/tools/cli/cookbook/tx-new-create-claimable-balance Initializes the Stellar testnet and generates funded accounts for Alice, Bob, and Charlie. These accounts are necessary for subsequent transaction examples. ```bash stellar network use testnet stellar keys generate --fund alice stellar keys generate bob --fund stellar keys generate charlie --fund ``` -------------------------------- ### Run Development Server Source: https://developers.stellar.org/docs/build/apps/example-application-tutorial/overview Starts the SvelteKit development server using the preferred package manager. ```bash npm run dev ``` ```bash yarn dev ``` ```bash pnpm run dev ``` ```bash bun run dev ``` -------------------------------- ### Solidity: Data Types Example Source: https://developers.stellar.org/docs/learn/migrate/evm/solidity-and-rust-basics Demonstrates various data types available in Solidity, including booleans, integers, addresses, strings, bytes, arrays, structs, enums, and mappings. Each type is shown with an example implementation within a contract. ```solidity pragma solidity ^0.8.0; contract DataTypesExample { // Boolean bool public isCompleted = false; // Integer (signed and unsigned) int256 public signedInteger = -10; uint256 public unsignedInteger = 10; // Address address public userAddress = 0x742d35Cc6634C0532925a3b844Bc454e4438f44e; // String string public greeting = "Hello, World!"; // Bytes (dynamic-size and fixed-size) bytes public dynamicBytes = "hello, solidity"; bytes32 public fixedBytes = "hello, solidity"; // Arrays (dynamic-size and fixed-size) uint[] public dynamicArray = [1, 2, 3]; uint[5] public fixedArray = [1, 2, 3, 4, 5]; address[] public dynamicAddressArray = [0xd41d1744871f42Bb724D777A2d0Bf53FB43a0040, 0x1f514ae9834aEAF6c2c3eb6D20E27e865F419010]; address[3] public fixedAddressArray = [0xC90cd0D820D6dc447B3cD9545185B046873786A6, 0x401997E856CE51e0D4A8f26ce64952313BEA0E25, 0x221d3b9821f3Cc49B42E7dd487E2a6d1b3ed0E05]; bool[] public dynamicBoolArray = [true, false, true]; bool[2] public fixedBoolArray = [true, false]; // Struct struct Person { string name; uint age; } Person public person = Person("Alice", 30); // Enums enum Status { Open, Closed, Pending } Status public currentStatus = Status.Open; Status public nextStatus = Status.Closed; Status public previousStatus = Status.Pending; // Mapping mapping(address => uint) public balances; constructor() { balances[msg.sender] = 100; } } ``` -------------------------------- ### Unit Testing Soroban Contracts Source: https://developers.stellar.org/docs/build/smart-contracts/getting-started/hello-world Shows how to write unit tests for Soroban contracts using the test attribute, environment initialization, contract registration, and the generated contract client. ```rust #![cfg(test)] use super::*; use soroban_sdk::{vec, Env, String}; #[test] fn test() { let env = Env::default(); let contract_id = env.register(Contract, ()); let client = ContractClient::new(&env, &contract_id); let words = client.hello(&String::from_str(&env, "Dev")); assert_eq!( words, vec![ &env, String::from_str(&env, "Hello"), String::from_str(&env, "Dev"), ] ); } ``` -------------------------------- ### Horizon Database Migration Log Entries Source: https://developers.stellar.org/docs/data/apis/horizon/admin-guide/upgrading Example log entries indicating the start and successful completion of database migrations during a Stellar Horizon upgrade. These logs help in diagnosing upgrade-related issues. ```log 2023/09/22 18:27:01 Applying DB migrations... 2023/09/22 18:27:01 successfully applied 5 Horizon migrations ``` -------------------------------- ### Configure Environment Variables Source: https://developers.stellar.org/docs/build/apps/guestbook/overview Commands to initialize the .env file from the example template and define necessary Stellar network credentials for Testnet deployment. ```bash cp .env.example .env # Example .env content: PUBLIC_STELLAR_ACCOUNT=stroopy PRIVATE_FUNDER_SECRET_KEY=S...ECRET PUBLIC_FUNDER_PUBLIC_KEY=G...ADDRESS ``` -------------------------------- ### Rust Smart Contract Structure Example Source: https://developers.stellar.org/docs/learn/migrate/evm/solidity-and-rust-basics This is a placeholder for the Rust code of your smart contract. The `#[contractimpl]` attribute marks the implementation block for your contract's functions. Replace the `...` with your actual contract logic. ```rust // Remember to replace your lib.rs file with the code example above. // This is just a reference to point you in the right direction. #[contractimpl] impl IncrementContract {...} ``` -------------------------------- ### Implementing a Counter Contract in Solidity Source: https://developers.stellar.org/docs/learn/migrate/evm/solidity-and-rust-basics A basic smart contract example in Solidity that manages a private unsigned integer state. It includes public functions to retrieve the current count and increment the state variable. ```Solidity // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; contract Counter { uint256 private _count; function getCount() public view returns (uint256) { return _count; } function increment() public { _count += 1; } } ``` -------------------------------- ### Create and Initialize a Node.js Project for Deployment Source: https://developers.stellar.org/docs/build/guides/transactions/install-deploy-contract-with-code Creates a new directory for the Node.js deployment project, navigates into it, initializes a new Node.js project, and installs the necessary Stellar SDK and file system modules. ```bash mkdir deploy-contract cd deploy-contract npm init -y npm install @stellar/stellar-sdk fs ``` -------------------------------- ### Initialize and Build a Sample Rust Contract Source: https://developers.stellar.org/docs/build/guides/transactions/install-deploy-contract-with-code Initializes a new Soroban smart contract project, navigates into its directory, and builds the contract. This process generates a .wasm file required for deployment. ```bash stellar contract init hello-world cd hello-world stellar contract build ``` -------------------------------- ### Solidity: Hello World Smart Contract Source: https://developers.stellar.org/docs/learn/migrate/evm/solidity-and-rust-basics A basic 'Hello, World!' smart contract written in Solidity. It defines a simple function that returns a string. This demonstrates the fundamental structure of a Solidity contract. ```solidity pragma solidity ^0.8.0; contract HelloWorld { function sayHello() public pure returns (string memory) { return "Hello, World!"; } } ``` -------------------------------- ### Invoke Stellar Contract Function Source: https://developers.stellar.org/docs/learn/migrate/evm/solidity-and-rust-basics This command invokes a specific function within your Stellar smart contract. You need to provide the path to the compiled Wasm file, the contract ID, and the function name. This example shows how to invoke the 'increment' function. ```bash stellar contract invoke \ --wasm target/wasm32v1-none/release/increment.wasm \ --id 1 \ -- \ increment ``` -------------------------------- ### HTTP GET Request Example in C# Source: https://developers.stellar.org/docs/platforms/stellar-disbursement-platform/api-reference/retrieve-a-receiver Provides a C# code example using HttpClient to make a GET request to retrieve a receiver's data. It demonstrates how to set the 'Accept' and 'Authorization' headers and handle the response. ```csharp var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, "/receivers/:id"); request.Headers.Add("Accept", "application/json"); request.Headers.Add("Authorization", ""); var response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` -------------------------------- ### Configure Environment Variables Source: https://developers.stellar.org/docs/build/guides/dapps/soroban-contract-init-template Copies the example environment file to a local .env file for project configuration. ```bash cp .env.example .env ``` -------------------------------- ### Upgrade and Start Single Horizon Instance (Helm Kubernetes) Source: https://developers.stellar.org/docs/data/apis/horizon/admin-guide/upgrading Upgrades a Helm installation of Stellar Horizon on Kubernetes to a new release tag and starts a single ingest instance. It also configures the instance to apply database migrations automatically. ```bash helm upgrade my-horizon \ --namespace my-horizon-namespace-on-cluster \ --set global.image.horizon.tag=new_horizon_release_number \ --set ingest.horizonConfig.applyMigrations=True \ --set ingest.replicaCount=1 ``` -------------------------------- ### Setup Stellar SDK and Transaction Builder (JavaScript) Source: https://developers.stellar.org/docs/build/guides/dapps/frontend-guide This snippet demonstrates how to initialize the Stellar SDK, create a server instance for the test network, and set up a transaction builder. It highlights the use of network passphrases and base fees for transaction construction. ```javascript import * as StellarSdk from "@stellar/stellar-sdk"; import { rpc as StellarRpc } from "@stellar/stellar-sdk"; export const server = new StellarRpc.Server("https://soroban-testnet.stellar.org"); // soroban testnet server const transaction = new StellarSdk.TransactionBuilder(account, { fee: StellarSdk.BASE_FEE, networkPassphrase: StellarSdk.Networks.TESTNET, // Use appropriate network }) ``` -------------------------------- ### Initialize Stellar Wallet for Testnet Source: https://developers.stellar.org/docs/build/apps/wallet/intro Creates a wallet instance with default configuration connected to Stellar's Testnet. This is the primary class for accessing SDK functionality. ```kotlin val wallet = Wallet(StellarConfiguration.Testnet) ``` ```typescript let wallet = walletSdk.Wallet.TestNet(); ``` ```dart var wallet = Wallet.testNet; ``` ```swift let wallet = Wallet.testNet ``` -------------------------------- ### Install Stellar SDKs and Polyfills Source: https://developers.stellar.org/docs/build/apps/example-application-tutorial/overview Installs the Stellar SDK and necessary node polyfills to ensure compatibility with client-side environments. ```bash # Stellar SDKs npm install --save-dev stellar-sdk @stellar/wallet-sdk # We will need some polyfills to make things available client-side npm install --save-dev @esbuild-plugins/node-globals-polyfill @esbuild-plugins/node-modules-polyfill path @rollup/plugin-inject buffer svelte-local-storage-store uuid ``` ```bash # Stellar SDKs yarn add --dev stellar-sdk @stellar/wallet-sdk # We will need some polyfills to make things available client-side yarn add --dev @esbuild-plugins/node-globals-polyfill @esbuild-plugins/node-modules-polyfill path @rollup/plugin-inject buffer svelte-local-storage-store uuid ``` ```bash # Stellar SDKs pnpm add --save-dev stellar-sdk @stellar/wallet-sdk ``` -------------------------------- ### Run Stellar Development Environment Source: https://developers.stellar.org/docs/build/guides/dapps/soroban-contract-init-template Starts the local Stellar network container and launches the development server. ```bash stellar network container start local npm run dev ``` -------------------------------- ### Get Stellar Account Payments using Python (Requests) Source: https://developers.stellar.org/docs/data/apis/horizon/api-reference/get-payments-by-account-id This Python code snippet demonstrates fetching payment operations for a Stellar account using the `requests` library. It sends a GET request to the Horizon API and prints the JSON response. Ensure you have the `requests` library installed (`pip install requests`). ```python import requests def get_account_payments(account_id): url = f"https://horizon-testnet.stellar.org/accounts/{account_id}/payments" headers = { "Accept": "application/json" } try: response = requests.get(url, headers=headers) response.raise_for_status() # Raise an exception for bad status codes print(response.json()) except requests.exceptions.RequestException as e: print(f"Error fetching account payments: {e}") # Example usage: # get_account_payments(':account_id') ``` -------------------------------- ### Get Stellar Account Payments using Node.js (Axios) Source: https://developers.stellar.org/docs/data/apis/horizon/api-reference/get-payments-by-account-id This Node.js code snippet demonstrates fetching payment operations for a Stellar account using the Axios library. It sends a GET request to the Horizon API and logs the JSON response. Make sure to install Axios (`npm install axios`) before running. ```javascript const axios = require('axios'); async function getAccountPayments(accountId) { const url = `https://horizon-testnet.stellar.org/accounts/${accountId}/payments`; try { const response = await axios.get(url, { headers: { 'Accept': 'application/json', }, }); console.log(response.data); } catch (error) { console.error('Error fetching account payments:', error.message); } } // Example usage: // getAccountPayments(':account_id'); ``` -------------------------------- ### Setup CSS and Layout Source: https://developers.stellar.org/docs/build/apps/example-application-tutorial/overview Defines the global CSS directives and imports them into the SvelteKit layout. Also configures the layout to be client-side only. ```css @tailwind base; @tailwind components; @tailwind utilities; ``` ```html ``` ```javascript // Disable pre-rendering of pages during build-time export const prerender = false; // Disable server-side rendering export const ssr = false; ``` -------------------------------- ### Rust Contract Test Setup and Execution Source: https://developers.stellar.org/docs/build/smart-contracts/example-contracts/custom-types This Rust code demonstrates how to set up and execute a test for a Stellar smart contract. It initializes the environment, registers the contract, creates a client, and asserts the outcomes of contract function calls. ```rust #[test] fn test() { let env = Env::default(); let contract_id = env.register(IncrementContract, ()); let client = IncrementContractClient::new(&env, &contract_id); assert_eq!(client.increment(&1), 1); assert_eq!(client.increment(&10), 11); assert_eq!( client.get_state(), State { count: 11, last_incr: 10 } ); } ``` -------------------------------- ### Install Stellar SDKs and Polyfills with bun Source: https://developers.stellar.org/docs/build/apps/example-application-tutorial/overview Installs the Stellar SDK and necessary polyfills for client-side development using bun. This command adds `stellar-sdk`, `@stellar/wallet-sdk`, and various polyfill packages. ```bash bun add --dev stellar-sdk @stellar/wallet-sdk bun add --dev @esbuild-plugins/node-globals-polyfill @esbuild-plugins/node-modules-polyfill \ path @rollup/plugin-inject buffer svelte-local-storage-store uuid ``` -------------------------------- ### Get Account Offers - HTTP Source: https://developers.stellar.org/docs/data/apis/horizon/api-reference/get-offers-by-account-id Example of making an HTTP GET request to retrieve offers for a Stellar account. This snippet demonstrates the request structure and headers required for the Stellar Horizon API. ```http GET https://horizon-testnet.stellar.org/accounts/:account_id/offers Accept: application/json ``` -------------------------------- ### Get Stellar Horizon Instance Source: https://developers.stellar.org/docs/build/apps/wallet/intro Retrieves the Stellar Horizon instance from the configured wallet object. This instance is used for direct interaction with the Stellar network. ```kotlin val stellar = wallet.stellar() ``` ```typescript const stellar = wallet.stellar(); ``` ```dart var stellar = wallet.stellar(); ``` ```swift let stellar = wallet.stellar ``` -------------------------------- ### Install Project Dependencies Source: https://developers.stellar.org/docs/build/apps/dapp-frontend Installs essential utility packages required for environment variable management, file globbing, and asynchronous command execution. ```shell npm install dotenv glob util ``` -------------------------------- ### Get Receivers Request Example (C#) Source: https://developers.stellar.org/docs/platforms/stellar-disbursement-platform/api-reference/list-all-receivers This C# code snippet demonstrates how to make a GET request to the '/receivers' endpoint using HttpClient. It includes setting the 'Accept' and 'Authorization' headers and handling the response. ```csharp var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, "/receivers"); request.Headers.Add("Accept", "application/json"); request.Headers.Add("Authorization", ""); var response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` -------------------------------- ### Clone and Test Soroban Deployer Example Source: https://developers.stellar.org/docs/build/smart-contracts/example-contracts/deployer Commands to retrieve the example repository and execute the test suite for the deployer contract. ```bash git clone -b v23.0.0 https://github.com/stellar/soroban-examples cd deployer/deployer cargo test ``` -------------------------------- ### Rust: Get Count Function Signature Source: https://developers.stellar.org/docs/learn/migrate/evm/solidity-and-rust-basics Defines the public `get_count` function for the smart contract. It takes an `Env` object and returns the current counter value as a `u32`. ```rust pub fn get_count(env: Env) -> u32 {} ``` -------------------------------- ### Initialize SvelteKit Project Source: https://developers.stellar.org/docs/build/apps/example-application-tutorial/overview Creates a new SvelteKit project using the latest template. This command initiates an interactive setup process to configure TypeScript, ESLint, and Prettier. ```bash npm create svelte@latest my-basic-payment-app ``` -------------------------------- ### Manage Services Source: https://developers.stellar.org/docs/platforms/anchor-platform/admin-guide/getting-started Commands to stop all services or restart them after configuration changes. ```bash docker-compose down docker-compose restart ``` -------------------------------- ### GET /contract/fetch Source: https://developers.stellar.org/docs/tools/cli/stellar-cli Fetches a contract's WASM binary from the network. ```APIDOC ## GET /contract/fetch ### Description Retrieves the Wasm binary for a specific contract ID or Wasm hash. ### Method GET ### Parameters #### Query Parameters - **id** (string) - Optional - Contract ID to fetch. - **wasm-hash** (string) - Optional - Wasm hash to fetch. - **out-file** (string) - Optional - File path to write the binary. ### Request Example { "id": "CA..." } ### Response #### Success Response (200) - **binary** (blob) - The raw Wasm binary data. ``` -------------------------------- ### Export DATABASE_URL and Initialize Horizon Database Source: https://developers.stellar.org/docs/data/apis/horizon/admin-guide/configuring This example shows how to export the DATABASE_URL environment variable, which specifies the connection details for the PostgreSQL database, and then execute the 'stellar-horizon db init' command to initialize the database schema. This prepares the database for Horizon's use. ```bash export DATABASE_URL="dbname=horizon user=horizon password= host=" stellar-horizon db init ``` -------------------------------- ### Get Strict Receive Paths (C#) Source: https://developers.stellar.org/docs/data/apis/horizon/api-reference/list-strict-receive-payment-paths Retrieves strict receive payment paths using the Stellar Horizon API with HttpClient. This example demonstrates making a GET request to the /paths/strict-receive endpoint and handling the JSON response. ```csharp var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, "https://horizon-testnet.stellar.org/paths/strict-receive"); request.Headers.Add("Accept", "application/json"); var response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); Console.WriteLine(await response.Content.ReadAsStringAsync()); ``` -------------------------------- ### Initialize Stellar SDK Client Source: https://developers.stellar.org/docs/build/guides/transactions/claimable-balances Basic setup for the Stellar SDK in a JavaScript environment to interact with the network. ```javascript import * as StellarSdk from "@stellar/stellar-sdk"; // Replace with your actual Claimable Balance ID ``` -------------------------------- ### Rust: Disable Standard Library for Soroban Source: https://developers.stellar.org/docs/learn/migrate/evm/solidity-and-rust-basics This Rust attribute `#![no_std]` prevents the linking of the Rust standard library, creating a leaner, 'barebones' starting point for Soroban applications by including only essential components. ```rust #![no_std] ``` -------------------------------- ### Retrieve Verification Types (JavaScript) Source: https://developers.stellar.org/docs/platforms/stellar-disbursement-platform/api-reference/list-receiver-verification-types Example code in JavaScript using the fetch API to get receiver verification types. It shows how to configure the GET request with appropriate headers for content negotiation and authorization. ```javascript fetch('/receivers/verification-types', { method: 'GET', headers: { 'Accept': 'application/json', 'Authorization': '' } }) .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(data => { console.log(data); }) .catch(error => { console.error('There was a problem with the fetch operation:', error); }); ``` -------------------------------- ### GET /stellar events Source: https://developers.stellar.org/docs/tools/cli/stellar-cli Watch the network for contract events. ```APIDOC ## GET stellar events ### Description Subscribes to and monitors the network for events emitted by smart contracts. ### Method GET ### Endpoint stellar events ### Parameters #### Query Parameters - **rpc-url** (string) - Optional - RPC server endpoint to monitor. ### Response #### Success Response (200) - **event** (object) - The emitted contract event data. #### Response Example { "event": { "type": "contract", "data": "..." } } ``` -------------------------------- ### stellar contract upload Source: https://developers.stellar.org/docs/tools/developer-tools/cli/stellar-cli Installs a WASM file to the ledger without creating a contract instance. Allows adding key-value metadata to the contract. ```APIDOC ## POST /contract/upload ### Description Install a WASM file to the ledger without creating a contract instance. Allows adding key-value metadata to the contract. ### Method POST ### Endpoint /contract/upload ### Parameters #### Query Parameters - **source-account** (string) - Required - The Stellar account that will be used to upload the WASM. - **package** (string) - Optional - Package to build when `--wasm` is not provided. - **meta** (object) - Optional - Add key-value pairs to contract meta (adds the meta to the `contractmetav0` custom section). - **key** (string) - The metadata key. - **value** (string) - The metadata value. #### Request Body - **wasm** (file) - The WASM file to upload. ### Request Example ```bash stellar contract upload --source-account GABCDEFG... --meta key1=value1 --meta key2=value2 < ./my_contract.wasm ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the upload operation. - **contract_id** (string) - The ID of the uploaded contract WASM. #### Response Example ```json { "status": "success", "contract_id": "CABCDEFG..." } ``` ``` -------------------------------- ### GET /getLedgers Source: https://developers.stellar.org/docs/data/apis/rpc/api-reference/methods/getLedgers Retrieves a detailed list of ledgers starting from a specified sequence number. Supports pagination and different response formats. ```APIDOC ## POST /getLedgers ### Description The `getLedgers` method returns a detailed list of ledgers starting from the user specified starting point that you can paginate as long as the pages fall within the history retention of their corresponding RPC provider. ### Method POST ### Endpoint https://soroban-testnet.stellar.org ### Parameters #### Request Body - **jsonrpc** (string) - Required - Specifies the JSON-RPC protocol version. - **id** (number) - Required - A unique identifier for the request. - **method** (string) - Required - The name of the method to be called, which is 'getLedgers'. - **params** (object) - Required - An object containing the parameters for the getLedgers method. - **startLedger** (number) - Optional - Ledger sequence number to start fetching responses from (inclusive). Must be omitted if a cursor is included. - **pagination** (object) - Optional - An object for controlling pagination. - **cursor** (string) - Optional - An opaque string which acts as a paging token. To obtain the next page of results occurring after a given response set this value to the `cursor` field of the response. - **limit** (number) - Optional - The maximum number of records returned. Defaults to 100. Maximum is 10000. - **xdrFormat** (string) - Optional - Specifies whether XDR should be encoded as Base64 ('base64') or JSON ('json'). Defaults to 'base64'. ### Request Example ```json { "jsonrpc": "2.0", "id": 8675309, "method": "getLedgers", "params": { "startLedger": 36233, "pagination": { "limit": 2 } } } ``` ### Response #### Success Response (200) - **jsonrpc** (string) - The JSON-RPC protocol version. - **id** (number) - The ID of the request. - **result** (object) - The result of the getLedgers method. - **ledgers** (array[object]) - An array of ledger objects. - **hash** (string) - The hash of the ledger header. - **sequence** (number) - The sequence number of the ledger. - **ledgerCloseTime** (string) - The timestamp at which the ledger was closed. - **headerXdr** (string) - The LedgerHeader structure for this ledger (base64-encoded string). - **metadataXdr** (string) - The LedgerCloseMeta union for this ledger (base64-encoded string). - **latestLedger** (number) - The sequence number of the latest ledger known to Stellar RPC. - **latestLedgerCloseTime** (number) - The unix timestamp of the close time of the latest ledger. - **oldestLedger** (number) - The sequence number of the oldest ledger ingested by Stellar RPC. - **oldestLedgerCloseTime** (number) - The unix timestamp of the close time of the oldest ledger. - **cursor** (string) - A token for obtaining the next page of results. #### Response Example ```json { "jsonrpc": "2.0", "id": 8675309, "result": { "ledgers": [ { "hash": "0000000000000000000000000000000000000000000000000000000000000000", "sequence": 36233, "ledgerCloseTime": "2023-01-01T00:00:00Z", "headerXdr": "AAAA...", "metadataXdr": "AAAA..." } ], "latestLedger": 100000, "latestLedgerCloseTime": 1672531200, "oldestLedger": 1, "oldestLedgerCloseTime": 1437536000, "cursor": "now" } } ``` ``` -------------------------------- ### Clone and Build Soroban Deployer Example Source: https://developers.stellar.org/docs/build/guides/conventions/deploy-contract Commands to set up the development environment by cloning the repository and building the contract binaries. ```bash git clone -b v22.0.1 https://github.com/stellar/soroban-examples cd soroban-examples/deployer/deployer stellar contract build ``` -------------------------------- ### Create Stellar Identity on Local Network Source: https://developers.stellar.org/docs/tools/quickstart/getting-started/deploy-smart-contract Generates a new Stellar identity (key pair) on the local network and optionally funds it. This identity is required as the 'source-account' for deploying and invoking contracts. The command uses the 'stellar' CLI tool. ```bash stellar keys generate --global bob --network local --fund ``` -------------------------------- ### Configure dbt project dependencies Source: https://developers.stellar.org/docs/data/analytics/hubble/developer-guide/data-curation/getting-started Defines the stellar-dbt-public package dependency in a packages.yml file to allow integration into an existing dbt project. ```yaml packages: - git: "https://github.com/stellar/stellar-dbt-public.git" revision: v0.0.28 ``` -------------------------------- ### GET /stellar doctor Source: https://developers.stellar.org/docs/tools/cli/stellar-cli Diagnose and troubleshoot CLI and network connectivity issues. ```APIDOC ## GET stellar doctor ### Description Runs a diagnostic suite to identify configuration or network issues affecting the Stellar CLI. ### Method GET ### Endpoint stellar doctor ### Parameters #### Query Parameters - **config-dir** (string) - Optional - Custom path to the configuration directory. ### Response #### Success Response (200) - **status** (string) - Diagnostic report summary. - **issues** (array) - List of detected issues or empty if healthy. #### Response Example { "status": "healthy", "issues": [] } ``` -------------------------------- ### Get Stellar Contract Counter Value Source: https://developers.stellar.org/docs/learn/migrate/evm/solidity-and-rust-basics This command retrieves the current value of the counter from your Stellar smart contract. It uses the `stellar contract invoke` command with the `get_count` function. The output will be the current integer value stored in the contract's storage. ```bash stellar contract invoke \ --wasm target/wasm32v1-none/release/increment.wasm \ --id 1 \ -- \ get_count ``` -------------------------------- ### Initialize Fuzzing Project Source: https://developers.stellar.org/docs/build/smart-contracts/example-contracts/fuzzing Command to initialize a new fuzzing project within a Soroban contract directory. ```bash cargo fuzz init ``` -------------------------------- ### Prometheus Configuration Example for SDP Metrics Source: https://developers.stellar.org/docs/platforms/stellar-disbursement-platform/admin-guide/monitoring This is an example of a Prometheus configuration snippet that targets the SDP metrics endpoints. It shows how to define scrape jobs for both the Dashboard API and the TSS. Adjust the 'host.docker.internal' and port numbers if your setup differs. ```yaml scrape_configs: - job_name: 'sdp-dashboard-api' static_configs: - targets: ['host.docker.internal:8002'] - job_name: 'sdp-tss' static_configs: - targets: ['host.docker.internal:9002'] ``` -------------------------------- ### GET /contract/read Source: https://developers.stellar.org/docs/tools/developer-tools/cli/stellar-cli Retrieves the current value of a contract-data ledger entry from the Stellar network. ```APIDOC ## GET /contract/read ### Description Prints the current value of a specific contract-data ledger entry. Supports output formatting as string, JSON, or XDR. ### Method GET ### Endpoint stellar contract read ### Parameters #### Query Parameters - **id** (string) - Required - Contract ID owning the data entries - **key** (string) - Optional - Storage key (symbols only) - **key-xdr** (string) - Optional - Storage key (base64-encoded XDR) - **output** (string) - Optional - Format of the output (string, json, xdr). Default: string - **durability** (string) - Optional - Storage entry durability (persistent, temporary). Default: persistent ### Response #### Success Response (200) - **data** (any) - The value of the requested ledger entry ### Response Example { "data": "example_value", "format": "json" } ``` -------------------------------- ### Install Stellar SDKs and Polyfills with pnpm Source: https://developers.stellar.org/docs/build/apps/example-application-tutorial/overview Installs the Stellar SDK and essential polyfills for client-side use with pnpm. This includes packages like `@esbuild-plugins/node-globals-polyfill`, `@esbuild-plugins/node-modules-polyfill`, `path`, `@rollup/plugin-inject`, `buffer`, `svelte-local-storage-store`, and `uuid`. ```bash pnpm add --save-dev @esbuild-plugins/node-globals-polyfill @esbuild-plugins/node-modules-polyfill \ path @rollup/plugin-inject buffer svelte-local-storage-store uuid ``` -------------------------------- ### Running Soroban Contract Tests Source: https://developers.stellar.org/docs/build/smart-contracts/example-contracts/auth This command navigates to the `auth` directory within the cloned `soroban-examples` repository and executes the contract tests using Cargo. It verifies the functionality of the authentication contract. ```bash cd auth cargo test ``` -------------------------------- ### Verify Platform Status Source: https://developers.stellar.org/docs/platforms/anchor-platform/admin-guide/getting-started Commands to verify the platform is responding via HTTP and to check the status of running Docker containers. ```bash curl http://localhost:8080/.well-known/stellar.toml docker-compose ps ``` -------------------------------- ### GET /wallet-registration/start Source: https://developers.stellar.org/docs/platforms/stellar-disbursement-platform/api-reference/start-wallet-registration Serves the SEP-24 interactive registration UI. This endpoint is used to start the wallet registration process and requires authorization tokens. ```APIDOC ## GET /wallet-registration/start ### Description Serves the SEP-24 interactive registration UI. This endpoint is used to start the wallet registration process and requires authorization tokens. ### Method GET ### Endpoint /wallet-registration/start ### Parameters #### Query Parameters - **token** (string) - Required - SEP-24 token for authorization. - **transaction_id** (string) - Required - SEP-24 transaction ID. - **lang** (string) - Optional - Optional language override for the webview. ### Request Example ``` GET /wallet-registration/start?token=&transaction_id=&lang= ``` ### Response #### Success Response (200) - **text/html** - HTML webview for receiver registration. #### Response Example (200) ```html Wallet Registration

Please complete your registration

``` #### Error Response (400) - **application/json** - Details about the error. #### Response Example (400) ```json { "error": "Bad Request: Missing required parameter.", "extras": {} } ``` #### Error Response (401) - **application/json** - Details about the error. #### Response Example (401) ```json { "error": "Unauthorized", "extras": { "status": 401, "message": "Authentication failed." } } ``` ``` -------------------------------- ### Edit Stellar Transaction Envelope from Stdin Source: https://developers.stellar.org/docs/tools/cli/stellar-cli Edits a Stellar transaction envelope provided via standard input. This command respects environment variables like STELLAR_EDITOR, EDITOR, and VISUAL to determine the preferred editor. It can be used to start a new editing session or to pipe an existing transaction envelope (e.g., from `stellar tx new`) into the editor. ```bash # Start a new edit session stellar tx edit # Pipe an XDR transaction envelope into the editor stellar tx new manage-data --data-name hello --build-only | stellar tx edit ``` -------------------------------- ### Initialize Go Module for Token Transfer Processor Source: https://developers.stellar.org/docs/data/indexers/build-your-own/processors/token-transfer-processor/examples Initializes a new Go module in the current directory for the Token Transfer Processor example. This is a prerequisite for setting up the project. ```bash go mod init example/ttp_processor ``` -------------------------------- ### Configure Business Callback Server Source: https://developers.stellar.org/docs/platforms/anchor-platform/admin-guide/getting-started Commands to stop the default reference server to allow for the integration of a custom business callback implementation. ```bash docker-compose stop reference-server ``` -------------------------------- ### GET /stellar/tx/hash Source: https://developers.stellar.org/docs/tools/cli/stellar-cli Calculates the cryptographic hash of a provided transaction envelope. ```APIDOC ## GET stellar tx hash ### Description Calculate the hash of a transaction envelope provided via argument or stdin. ### Method CLI Command ### Endpoint stellar tx hash [OPTIONS] [TX_XDR] ### Parameters #### Arguments - **TX_XDR** (string) - Optional - Base-64 transaction envelope XDR or file containing XDR. #### Query Parameters - **--rpc-url** (string) - Optional - RPC server endpoint. - **--network** (string) - Optional - Name of network to use from config. ### Response #### Success Response (200) - **hash** (string) - The calculated transaction hash. ``` -------------------------------- ### Configure contract-specific Cargo.toml Source: https://developers.stellar.org/docs/build/smart-contracts/getting-started/hello-world Sets up the package metadata, crate type for WASM compilation, and contract-specific dependencies for an individual smart contract. ```toml [package] name = "hello-world" version = "0.0.0" edition = "2021" publish = false [lib] crate-type = ["cdylib"] doctest = false [dependencies] soroban-sdk = { workspace = true } [dev-dependencies] soroban-sdk = { workspace = true, features = ["testutils"] } ```