# Introduction URL: https://docs.blux.cc/ The complete wallet infrastructure for Stellar dApps. Blux is wallet infrastructure for Stellar dApps — designed to make onboarding seamless, even for users who don't have a Stellar wallet. Users can sign in instantly with **email**, **social accounts** (Google, Apple, and more), **passkeys**, or an existing **wallet**. No friction, no setup, no barriers. ## What's Included } description="Email, social, passkeys, and wallets — all out of the box." /> } description="Transaction signing, balances, swap, history, and on/off-ramp modals." /> } description="Match your dApp's branding with a fully configurable modal." /> } description="Full type safety with clean, modern APIs." /> ## Quick Start The only required config is your **App ID** and a **network**. Everything else — appearance, login methods, language, wallets — has defaults. ```bash npm install @bluxcc/react ``` ```tsx function App() { const { login, isAuthenticated } = useBlux(); return ( ); } export default function Root() { return ( ); } ``` ```bash npm install @bluxcc/core ``` ```ts createConfig({ appId: "your-app-id", networks: [core.networks.mainnet], }); document.querySelector("#connect")?.addEventListener("click", () => { blux.login(); }); ``` Get an App ID from the [dashboard](https://dashboard.blux.cc), then follow the full setup guide for your stack: } description="For React, Next.js, Vite, and CRA projects." /> } description="For framework-agnostic or vanilla JS projects." /> Want to see Blux in action before integrating? [Try the live demo →](https://demo.blux.cc) --- # Getting Started URL: https://docs.blux.cc/getting-started From zero to a working Blux integration — the whole flow in one page. This page walks you through the full path to a working integration, from creating your app to letting users log in. Each step links to a deeper page if you want more detail. The flow looks like this: 1. **Create an app in the Dashboard** and grab your App ID. 2. **Pick a package** — React or core (vanilla JS) — and install it. 3. **Initialize Blux** with `createConfig` / `BluxProvider`, passing your App ID and a network. 4. **Customize** appearance, login methods, language, and wallets in the config. 5. **Use it** — open the built-in modals (`login`, `fundMe`, `profile`) or call the data hooks/functions. --- ## 1. Create your app & get an App ID Sign in at [dashboard.blux.cc](https://dashboard.blux.cc), create an app, and copy its **App ID**. The dashboard is also where you manage users, analytics, access rules, and which login providers are enabled. ## 2. Pick a package & install Choose based on your stack — `@bluxcc/react` for React/Next.js/Vite, or `@bluxcc/core` for any other JavaScript project. ```bash npm install @bluxcc/react ``` ```bash npm install @bluxcc/core ``` ## 3. Initialize Blux Wrap your app with `BluxProvider` (React) or call `createConfig` once at startup (vanilla JS). The only required options are `appId` and `networks`. ```tsx {children} ``` ```ts createConfig({ appId: "your-app-id", networks: [core.networks.mainnet], }); ``` ## 4. Customize the config Everything below is optional — Blux ships with sensible defaults. Add what you need to the same `config` object. - **Appearance** — match your branding (colors, fonts, radius). → [Appearance](/configuration/appearance) - **Login methods** — choose which auth options appear and in what order. → [Login Methods](/configuration/login-methods) - **Wallets** — reorder with [`orderWallets`](/configuration/order-wallets) or hide some with [`excludeWallets`](/configuration/exclude-wallets); configure [Trezor](/configuration/trezor). - **Language** — set the UI language. → [Language](/configuration/language) ### Enabling login methods Add the methods you want to the `loginMethods` array — order determines display order: ```ts createConfig({ appId: "your-app-id", networks: [core.networks.mainnet], loginMethods: ["wallet", "email", "passkey", "google", "meta"], }); ``` | Method | How to enable | |---|---| | **Wallet** | Add `"wallet"` to `loginMethods`. Connects Freighter, xBull, Trezor, Ledger, and more. | | **Email** | Add `"email"` — users get a one-time code by email. | | **SMS** | Add `"sms"` — users get a one-time code by phone. | | **Passkey** | Add `"passkey"` — passwordless sign-in via Face ID / Touch ID / security key. | | **Socials** | Add a [supported provider key](/dashboard/socials) (for example, `"google"`, `"farcaster"`, or `"github"`) **and** enable that provider in the dashboard. | Social providers must be turned on for your `appId` in the dashboard before they appear in the modal — adding them to `loginMethods` alone isn't enough. See [Socials](/dashboard/socials). ## 5. Use Blux Once initialized, you can use **built-in modals**, build a **white-label login UI**, or call **data hooks/functions**. Hosted actions and session state are exposed by `useBlux` in React and the `blux` object in vanilla JavaScript. ### Built-in modals ```tsx function App() { const { login, fundMe, profile, isAuthenticated } = useBlux(); // login() → open the auth modal // fundMe() → open the on-ramp modal // profile() → open the account modal } ``` ```ts blux.login(); // open the auth modal blux.fundMe(); // open the on-ramp modal blux.profile(); // open the account modal ``` ### Data hooks & functions When you want to build your own UI, read chain data and call contracts directly: - **Account data** — balances, transactions, payments, offers, and more. → [React hooks](/react/hooks) · [Core functions](/javascript/core) - **Soroban contracts** — read and write smart contracts. → [`useReadContracts`](/react/hooks/use-read-contracts) / [`useWriteContract`](/react/hooks/use-write-contract) (React) · [`readContracts`](/javascript/core/readContracts) / [`writeContract`](/javascript/core/writeContract) (core) That's the whole loop: configure once, then mix built-in modals with hooks/functions however your app needs. Try it all in the [live demo →](https://demo.blux.cc) --- # Configuration URL: https://docs.blux.cc/configuration Customize and configure every aspect of your Blux integration. Blux is designed to be flexible. Every aspect of the integration — from which wallets and login methods appear, to the visual style of the modal — can be configured to fit your app. All configuration is passed to `createConfig` (Vanilla JS) or `BluxProvider` (React) at initialization. The only required options are `appId` and `networks` — everything else is optional. --- {getPageTreePeers(source.getPageTree(), '/configuration').map((peer) => ( {peer.description} ))} --- # Appearance URL: https://docs.blux.cc/configuration/appearance Customize the look and feel of the Blux modal to match your dApp's branding. Blux is easy to style so it fits the look and feel of your app. You can adjust fonts, colors, borders, and backgrounds to match your design system. Every field is optional — if you leave something out, Blux uses the inherited value when available, then falls back to the default theme for that field. ## Setup Pass an `appearance` object when initializing Blux: ```tsx {children} ``` ```ts createConfig({ appName: "MyApp", networks: [core.networks.mainnet], appearance: { accentColor: "#0070f3", borderRadius: "16px", }, }); ``` ## Inherit your app's theme Use the `inherit` field to make Blux adopt the semantic theme values of your app's styling system. Set it to one of the supported adapters: `shadcn`, `radix`, `daisyui`, `chakra`, `mantine`, `mui`, `joy`, `heroui` (v3), or `bootstrap`. Blux reads the active values from the theme around its mount element and keeps them synchronized when your app switches themes. You select one adapter at a time; Blux does not try to guess which styling system your app uses. ```tsx {children} ``` ### Override inherited values Specific fields in the same `appearance` object take precedence over values supplied by `inherit`. This lets you inherit the overall theme while customizing individual parts of the Blux UI. The precedence order is: 1. Specific appearance fields 2. Values inherited from your styling system 3. Blux's default theme For example, the following configuration inherits shadcn's colors, radius, and other supported values, but always uses the supplied purple accent color: ```tsx {children} ``` The same behavior applies in Vanilla JS: ```ts createConfig({ appName: "MyApp", networks: [core.networks.mainnet], appearance: { inherit: "daisyui", background: "#ffffff", // Overrides daisyUI's --color-base-100 value }, }); ``` ### Advanced inheritance Pass an options object when the theme uses a nested scope, custom CSS-variable prefix, Chakra color palette, or your own CSS variables: ```ts createConfig({ appName: "MyApp", networks: [core.networks.mainnet], appearance: { inherit: { source: "css", scope: "#app-theme", variables: { textColor: "--app-foreground", accentColor: "--app-primary", background: "--app-dialog-surface", borderRadius: "--app-dialog-radius", }, }, borderRadius: "16px", // Overrides --app-dialog-radius }, }); ``` Use `prefix` to set a custom Chakra, MUI, Joy, or Bootstrap CSS-variable prefix. For Chakra, use `colorPalette` to choose the primary palette whose accent and focus-ring values Blux should inherit. If an inherited value is missing or invalid, Blux keeps the default for that field. ## Default Themes Blux ships with built-in light and dark defaults applied automatically based on the user's system preference. ```ts { logo: '', font: 'Manrope', textColor: '#000000', accentColor: '#0c1083', background: '#ffffff', fieldBackground: '#ffffff', borderRadius: '24px', borderColor: '#cdceee', borderWidth: '1px', outlineWidth: '1px', } ``` ```ts { logo: '', font: 'Manrope', textColor: '#ffffff', accentColor: '#ffffff', background: '#000000', fieldBackground: '#1a1a1a', borderRadius: '24px', borderColor: '#333333', borderWidth: '1px', outlineWidth: '1px', } ``` ## Properties | Property | Type | Description | |---|---|---| | `inherit` | `string \| object` | Styling-system adapter or advanced inheritance options; specific appearance fields override inherited values | | `logo` | `string` | URL of your app logo displayed in the modal | | `font` | `string` | Font family for all modal text | | `textColor` | `string` | Main text color | | `accentColor` | `string` | Primary highlight or action color | | `background` | `string` | Modal background color or image | | `fieldBackground` | `string` | Background color for input fields | | `borderRadius` | `string` | Corner radius for UI elements (e.g. `16px`) | | `borderColor` | `string` | Border color for elements | | `borderWidth` | `string` | Border width (e.g. `1px`, `0`) | | `backdropBlur` | `string` | Blur intensity behind the modal (e.g. `8px`) | | `backdropColor` | `string` | Overlay color behind the modal | | `boxShadow` | `string` | Box shadow applied to the modal | | `outlineWidth` | `string` | Outline width — falls back to `borderWidth` | | `outlineColor` | `string` | Outline color — falls back to `borderColor` | | `outlineRadius` | `string` | Outline corner radius — falls back to `borderRadius` | Want to experiment with the appearance settings visually? [Try the live demo →](https://demo.blux.cc) --- # Exclude Wallets URL: https://docs.blux.cc/configuration/exclude-wallets Control which wallets appear in the Blux login modal. The `excludeWallets` option lets you hide specific wallets from the login modal. This is useful when certain wallets don't support features your app depends on — such as `signMessage` or `getNetwork` — helping you avoid user confusion and potential runtime errors. ## Type ```ts type IWalletNames = Array< | "rabet" | "albedo" | "freighter" | "xbull" | "lobstr" | "hana" | "hot" | "klever" | "cactuslink" | "fordefi" | "trezor" | "onekey" | "bitget" | "ledger" | "walletConnect" >; ``` ## Default Behavior By default, Blux excludes `lobstr`. We recommend keeping this unless you have a specific reason to include them. **Why LOBSTR is excluded** — LOBSTR's `isAvailable()` takes ~2 seconds to respond. During that time, `blux.isReady` stays `false`, which blocks `blux.login()` from opening the modal. If you want to support LOBSTR users, use WalletConnect instead — it connects instantly without requiring the extension or affecting `isReady`. ## Usage ```ts // Default behavior — applied automatically if not specified createConfig({ excludeWallets: ["lobstr"], }); // Include all wallets with no exclusions createConfig({ excludeWallets: [], }); // Custom exclusion list createConfig({ excludeWallets: ["freighter", "albedo", "rabet"], }); ``` Including LOBSTR directly may cause delays or unreliable wallet detection. Prefer WalletConnect for LOBSTR support. --- # Explorer URL: https://docs.blux.cc/configuration/explorer Configure which Stellar block explorer Blux uses for transaction links. The `explorer` option sets which Stellar block explorer is used when a user clicks transaction links — such as "See all in explorer" on the history page, a recent transaction entry, or "See in explorer" after a successful transaction. The default is `stellarchain`. ## Type ```ts type IExplorer = "steexp" | "stellarchain" | "stellarexpert" | "lumenscan"; ``` ## Usage ```tsx {children} ``` ```ts createConfig({ explorer: "lumenscan", }); ``` --- # Language URL: https://docs.blux.cc/configuration/language Set the language used across the Blux modals and UI. The `lang` option sets the language for all Blux UI — the login, profile, send, swap, and fund modals. When omitted, Blux defaults to English. ## Type ```ts type LanguageKey = | 'en' // English | 'es' // Spanish | 'pt' // Portuguese | 'fr' // French | 'de' // German | 'ru' // Russian | 'zh' // Chinese | 'ja' // Japanese | 'ko' // Korean | 'tr'; // Turkish lang?: LanguageKey; ``` ## Usage ```tsx {children} ``` ```ts createConfig({ appName: "MyApp", lang: "es", }); ``` Want to preview the supported languages? [Try the live demo →](https://demo.blux.cc) --- # Login Methods URL: https://docs.blux.cc/configuration/login-methods Control which authentication methods are available in the Blux login modal. The `loginMethods` option defines which authentication methods are shown in the login modal. The order of the array also determines the display order — so the first item in the list will appear most prominently during onboarding. ## Type ```ts loginMethods?: Array< | 'wallet' | 'email' | 'sms' | 'passkey' | 'google' | 'farcaster' | 'tiktok' | 'linkedin' | 'twitch' | 'kick' | 'spotify' | 'instagram' | 'apple' | 'discord' | 'github' | 'meta' | 'telegram' | 'microsoft' | 'gitlab' | 'twitter' | 'steam' >; ``` ## Usage ```tsx {children} ``` ```ts createConfig({ loginMethods: ["wallet", "email", "sms", "passkey"], }); ``` ## Passkeys Add `'passkey'` to `loginMethods` to let users sign in with a **passkey** — a passwordless credential backed by their device's biometrics (Face ID, Touch ID, Windows Hello) or a hardware security key. There's no seed phrase to manage and nothing to install, which makes it one of the smoothest onboarding paths for users who are new to Stellar. ```ts createConfig({ loginMethods: ["passkey", "wallet", "email"], }); ``` ## Social login Blux supports **Google, Farcaster, TikTok, LinkedIn, Twitch, Kick, Spotify, Instagram, Apple, Discord, GitHub, Meta, Telegram, Microsoft, GitLab, X, and Steam**. Add their provider keys to `loginMethods` to show them in the modal: ```ts createConfig({ loginMethods: ["google", "farcaster", "github", "email"], }); ``` Social providers must first be **enabled for your app in the [Blux Dashboard](/dashboard)**. Each provider you add to `loginMethods` has to be turned on there for your `appId`, otherwise it won't appear in the modal. See [Socials](/dashboard/socials) for setup. ## White-label login `loginMethods` also authorizes the headless methods used by your own login UI. The core SDK exports `loginEmail`, `loginSms`, `loginOAuth`, `loginPasskey`, and `loginWallet`; the React package provides a corresponding hook for each one. Learn how to build the complete flow in [JavaScript](/javascript/usage/white-label-login) or [React](/react/usage/white-label-login). Want to see the login methods in action? [Try the live demo →](https://demo.blux.cc) --- # Networks URL: https://docs.blux.cc/configuration/networks Configure which Stellar networks your app supports. The `networks` option defines which Stellar networks your app supports. If a connected wallet is on a network not in this list, Blux will prompt the user to switch. ## Available Networks ```ts // core.networks exposes: { mainnet: 'Public Global Stellar Network ; September 2015', testnet: 'Test SDF Network ; September 2015', sandbox: 'Local Sandbox Stellar Network ; September 2022', futurenet: 'Test SDF Future Network ; October 2022', standalone: 'Standalone Network ; February 2017', } ``` ## Usage ```tsx {children} ``` ```ts createConfig({ appId: "your-app-id", networks: [core.networks.mainnet, core.networks.testnet], defaultNetwork: core.networks.mainnet, }); ``` If you only pass one network, `defaultNetwork` is optional — Blux will use the first item in the array automatically. You can change the active network later using `switchNetwork()`. Network switching prompts only appear for wallets that support `getNetwork()`, such as Rabet and Freighter. You can disable this behavior entirely by setting `promptOnWrongNetwork: false` in your config. ## Custom Networks If you need a network not in the built-in list, define it as a string and pass it to the `networks` array: ```ts const customNetwork = "Standalone Network ; February 2020"; createConfig({ appId: "your-app-id", networks: [customNetwork], }); ``` Make sure to also define a transport for any custom network. See the Transports page for details. ## Auto Sync Blux periodically checks the connected wallet's active network. By default, it keeps the app's network in sync with the wallet — as long as the wallet's network is one of the supported networks in your config. If your app calls `switchNetwork()` directly, Blux treats that as an app-controlled override and disables automatic syncing from that point on to prevent conflicts. ### Example Given this config: ```ts { networks: [networks.testnet, networks.futurenet], } ``` | Step | Event | Result | |------|-------|--------| | 1 | Alice connects Freighter on **Mainnet** | Mainnet is unsupported → Wrong Network modal shown, app stays on **Testnet** | | 2 | Alice switches Freighter to **Futurenet** | Supported → modal closes, app switches to **Futurenet** | | 3 | Alice switches Freighter to **Testnet** | Supported → app auto-syncs to **Testnet** | | 4 | App calls `switchNetwork(futurenet)` | App moves to **Futurenet**, auto-sync is now disabled | | 5 | Alice toggles between Testnet/Futurenet | Wallet changes, app stays on **Futurenet** | | 6 | Alice switches to **Mainnet** | Unsupported → Wrong Network modal, app stays on **Futurenet** | | 7 | Alice switches back to **Testnet** | Modal dismissed, but app still stays on **Futurenet** (auto-sync still off) | --- # Order Wallets URL: https://docs.blux.cc/configuration/order-wallets Control the order wallets appear in the Blux login modal. The `orderWallets` option lets you control the order in which wallets are displayed in the login modal. List the wallets in the order you want them shown — wallets you don't include keep their default position after the ones you specify. ## Type ```ts type IWalletNames = Array< | "rabet" | "albedo" | "freighter" | "xbull" | "lobstr" | "hana" | "hot" | "klever" | "cactuslink" | "fordefi" | "trezor" | "onekey" | "bitget" | "ledger" | "walletConnect" >; orderWallets?: IWalletNames | string[]; ``` ## Usage ```tsx {children} ``` ```ts createConfig({ appName: "MyApp", orderWallets: ["freighter", "xbull", "albedo"], }); ``` **Recent wallet always wins.** The wallet a user most recently logged in with is always pinned to the top of the list, regardless of `orderWallets`. Your ordering applies to all the other wallets. `orderWallets` only changes display order — to hide wallets entirely, use [Exclude Wallets](/configuration/exclude-wallets). --- # Transports URL: https://docs.blux.cc/configuration/transports Configure custom RPC endpoints for each network in your Blux app. The `transports` option lets you specify custom Horizon and Soroban RPC endpoints for each network in your config. Blux uses these as the intermediary layer for all outgoing RPC requests. If no transport is provided for a network, Blux falls back to the default public RPC endpoints. ## Type ```ts interface IServers { horizon: string; soroban: string; } type ITransports = Record; ``` ## Usage ```ts createConfig({ appName: "MyApp", networks: [core.networks.mainnet, core.networks.testnet], transports: { [core.networks.mainnet]: { horizon: "https://horizon.mydomain.org", soroban: "https://mainnetsorobanrpc.mydomain.org", }, [core.networks.testnet]: { horizon: "https://testnethorizon.mydomain.org", soroban: "https://testnetsorobanrpc.mydomain.org", }, }, }); ``` Each key in the `transports` object must match a network string from your `networks` array. Custom networks also require a transport entry — see the [Networks](/configuration/networks) page for details. --- # Trezor URL: https://docs.blux.cc/configuration/trezor Configure the Trezor hardware wallet integration. Blux supports the **Trezor** hardware wallet. Trezor requires a small manifest so its Connect service can identify your app — set it with the optional `trezor` config option. ## Type ```ts trezor?: { email: string; // a developer contact email appUrl: string; // the public URL of your app }; ``` ## Usage ```tsx {children} ``` ```ts createConfig({ appName: "MyApp", trezor: { email: "dev@myapp.com", appUrl: "https://myapp.com", }, }); ``` The `trezor` config is optional. Provide it when you offer Trezor as a wallet option so Trezor Connect can attribute requests to your app. The `email` and `appUrl` should identify a real contact and your app's public URL. --- # Wallet Connect URL: https://docs.blux.cc/configuration/walletConnect Enable WalletConnect support in your Blux app. Adding the `walletConnect` object to your config enables WalletConnect as a login option. Once configured, users will see a **Wallet Connect** option in the login modal. ## Usage ```ts createConfig({ appName: "My App", networks: [core.networks.mainnet], walletConnect: { projectId: "YOUR_PROJECT_ID", url: "https://yourapp.com", description: "A short description of your app", icons: ["https://yourapp.com/icon.png"], }, }); ``` ## Options | Option | Type | Description | |---|---|---| | `projectId` | `string` | Your WalletConnect project ID — get one from the [WalletConnect dashboard](https://cloud.walletconnect.com) | | `url` | `string` | The URL of your app, used to identify it during the connection flow | | `description` | `string` | A short description of your app shown inside the wallet | | `icons` | `string[]` | Array of image URLs used as your app icon in supported wallets | WalletConnect is the recommended way to support LOBSTR users, as it connects instantly without requiring the browser extension. See [Exclude Wallets](/configuration/exclude-wallets) for more context. --- # Dashboard URL: https://docs.blux.cc/dashboard Manage your app, users, and login settings from the Blux Dashboard. The [Blux Dashboard](https://dashboard.blux.cc) is where you manage everything about your integration that lives outside your code — your users, login providers, access rules, and analytics. Every app you build with Blux is tied to a dashboard project identified by a unique **App ID**. ## Getting started 1. Sign in at [dashboard.blux.cc](https://dashboard.blux.cc). 2. Create an app — you'll be given an **App ID**. 3. Pass that `appId` to `createConfig` (Vanilla JS) or `BluxProvider` (React). ```tsx {children} ``` ```ts createConfig({ appId: "your-app-id", networks: [core.networks.mainnet], }); ``` Once your app is wired to an `appId`, every login flows through your dashboard project — so the users, analytics, access rules, and enabled social providers you see there all apply to your live app. For backend integrations, your project also has an **App Secret**. It authenticates server-to-server requests that list or look up users and verify wallet ownership. Keep it out of browser code, mobile apps, and source control. See [Server API authentication](/api/authentication) for setup and examples. The model is similar to other auth platforms: log in, grab your App ID, drop it into your config, and manage the rest from the dashboard — no redeploy needed for most changes. ## What you can do {getPageTreePeers(source.getPageTree(), '/dashboard').map((peer) => ( {peer.description} ))} The dashboard is actively evolving — expect new controls and analytics over time. --- # Users & Analytics URL: https://docs.blux.cc/dashboard/users View, manage, and export your app's users, and track usage with analytics. The **Users** section of the dashboard gives you a complete view of everyone who has signed into your app, along with analytics about how your app is being used. ## User list Every authenticated user appears in a searchable, filterable table. For each user you can see: - **Address** — the Stellar public key associated with the account. - **Wallet** — the wallet or login method they used (e.g. passkey, Google, Freighter). - **Joined date** — when they first signed in. You can **filter by date** to focus on a specific window — for example, users who joined this week. ## Managing users From the user list you can take action on individual accounts: - **Block** a user to immediately prevent them from authenticating. - **Remove** a user from your app. ## Exporting Need the data elsewhere? Export your user list as a **CSV** or **PDF** file directly from the dashboard. ## Analytics The dashboard surfaces **charts and analytics** so you can track growth and engagement over time — sign-ins, new users, login-method breakdowns, and more. Analytics and user-management capabilities are expanding — new charts and controls are added over time. --- # Access Control URL: https://docs.blux.cc/dashboard/access-control Control who can log in and from where — allowlists, blocklists, allowed origins, and test accounts. The dashboard gives you several ways to control **who** can authenticate into your app and **where** your App ID can be used. ## Allowlist & blocklist You can gate access to your app with one of two complementary modes: - **Allowlist** — only the accounts you explicitly add can log in. Everyone else is blocked. Use this for private betas, internal tools, or invite-only apps. - **Blocklist** — everyone can log in *except* the accounts you add. Use this to ban specific bad actors while keeping the app open. ## Allowed origins By default your App ID could be used from any website. Enabling **Allowed Origins** locks it down to a list of domains you approve, so other origins can't use your `appId` to authenticate users. This protects your app from being impersonated or having its quota consumed elsewhere. Add every domain your app runs on, including local development (e.g. `http://localhost:3000`) and preview/staging URLs. ## Test accounts For development, you can create **test accounts** that use a **predefined OTP** instead of a real email/SMS code. This lets you build and test your login flow end-to-end without waiting on real verification codes. ## CAPTCHA CAPTCHA support — to add a human-verification challenge to your login flow and protect against automated abuse — is planned for a future release. Access-control features are expanding over time. Combine allowlists/blocklists with allowed origins for layered protection. --- # Social Login URL: https://docs.blux.cc/dashboard/socials Enable and configure every social login provider available for your Blux app. Blux supports **Google, Farcaster, TikTok, LinkedIn, Twitch, Kick, Spotify, Instagram, Apple, Discord, GitHub, Meta, Telegram, Microsoft, GitLab, X, and Steam**. Social providers are enabled separately for each app from its **Socials** page in the [Blux Dashboard](https://dashboard.blux.cc). ## Choose a provider in the dashboard Open your project, select **Socials**, and find the provider you want. The badge on its card tells you what is required: - **Ready to enable** or **Can be enabled without credentials** — switch it on. No credential form is required. - **Add credentials to enable** — open the provider, register the displayed redirect URI in its developer console, then enter its client ID and client secret. - **Requires your own credentials** — this provider cannot use shared Blux credentials. Complete its provider-specific form before enabling it. Steam and Farcaster never require client credentials. Apple and Telegram always require credentials owned by your project. Other OAuth providers are one-click when shared Blux credentials are available; otherwise the dashboard asks for your own. This can vary by provider and deployment, so the dashboard badge is the source of truth. | Provider | `loginMethods` key | Dashboard setup | |---|---|---| | Google | `google` | One-click when shared credentials are available; otherwise Client ID + Client Secret | | Farcaster | `farcaster` | One-click; no credentials | | TikTok | `tiktok` | Client Key + Client Secret unless shared credentials are available | | LinkedIn | `linkedin` | Client ID + Client Secret unless shared credentials are available | | Twitch | `twitch` | Client ID + Client Secret unless shared credentials are available | | Kick | `kick` | Client ID + Client Secret unless shared credentials are available | | Spotify | `spotify` | Client ID + Client Secret unless shared credentials are available | | Instagram | `instagram` | Client ID + Client Secret unless shared credentials are available | | Apple | `apple` | Your Client ID, Team ID, Key ID, and `.p8` signing key | | Discord | `discord` | Client ID + Client Secret unless shared credentials are available | | GitHub | `github` | Client ID + Client Secret unless shared credentials are available | | Meta | `meta` | App ID + App Secret unless shared credentials are available | | Telegram | `telegram` | Your Bot name + Bot token; optional Mini App login | | Microsoft | `microsoft` | Client ID + Client Secret unless shared credentials are available | | GitLab | `gitlab` | Client ID + Client Secret unless shared credentials are available | | X (Twitter) | `twitter` | Client ID + Client Secret unless shared credentials are available | | Steam | `steam` | One-click; no credentials | ## Using your own OAuth credentials Open the provider card and follow these steps: 1. Create an OAuth application in the provider's developer console. 2. Copy the **Redirect URI** shown by the Blux dashboard and register it as an authorized callback URL with the provider. Use it exactly as shown. 3. Paste the client ID and client secret into Blux, then save. Saving the credentials also enables the provider. Using your own credentials gives the provider's consent screen your application's identity. A provider backed by shared credentials can be enabled immediately, but you can still add your own credentials when you want a branded consent screen. Client secrets, bot tokens, and Apple signing keys are write-only and stored encrypted. They are never returned to the dashboard after saving and are never sent to `@bluxcc/core` or `@bluxcc/react` in the browser. Leave a saved secret field empty when updating other settings to keep its current value. ### Apple Apple requires a **Client ID**, **Team ID**, **Key ID**, and the complete `.p8` **Signing Key**, including its header and footer lines. Apple cannot use shared Blux credentials. ### Telegram Create a bot with [BotFather](https://t.me/BotFather), set its allowed domain to your application's domain, and enter the bot name and bot token in the dashboard. You can also enable login from Telegram Mini Apps. Telegram uses its on-page Login Widget rather than the usual OAuth popup. A headless integration can pass the widget payload to `loginOAuth("telegram", { telegramUser })`; a configured Mini App can use its Web App init data automatically. ## Add the provider to your app Dashboard configuration controls whether your `appId` may use a provider. Your SDK config controls whether your application offers it. You need both: ```ts createConfig({ appId: "your-app-id", appName: "My App", networks: [core.networks.mainnet], loginMethods: ["google", "farcaster", "github", "email"], }); ``` A provider works only when it is **enabled in the dashboard for your `appId`** and **present in `loginMethods`**. If either condition is missing, the built-in modal hides it and a headless `loginOAuth` call rejects. The first enabled social in `loginMethods` is featured in Blux's built-in login screen; the remaining providers appear under **Other socials**. With a white-label UI, you decide how every button is arranged. ## Start social login Use the built-in login modal or call the headless social method from your own button: ```ts // Built-in Blux login UI await blux.login(); // Your own button and UI await blux.loginOAuth("google"); ``` In React, use the matching hook: ```tsx const { loginOAuth, isPending, error } = useLoginOAuth(); ``` OAuth and passkey popups must be started directly from a user click. See [JavaScript white-label login](/javascript/usage/white-label-login) or [React white-label login](/react/usage/white-label-login) for complete examples. --- # Server API URL: https://docs.blux.cc/api Use your App Secret from a trusted backend to work with your Blux project and its users. The Blux Server API lets a trusted backend interact with a project directly. Use it to retrieve project users, search for a user, remove a user, or verify that a wallet address really belongs to someone who signed in to your project through Blux. These endpoints are independent of `@bluxcc/react` and `@bluxcc/core`. They are ordinary HTTPS endpoints and can be called from any backend language or framework. Your App Secret is a server-side credential. Never put it in frontend JavaScript, a mobile app, a public repository, a URL, or logs. A browser-visible environment variable is not secret, even if your build tool calls it an environment variable. ## Base URL ```text https://api.blux.cc ``` All requests and responses use JSON. Successful responses use either a `message` field or a `message` and `result` envelope. Errors use an `error` field. ## Quick start Copy your project's App ID and App Secret from the [Blux Dashboard](https://dashboard.blux.cc), store them in your backend's secret manager or private environment, and send them as request headers: ```bash curl --request GET \ --url 'https://api.blux.cc/server/users?limit=20' \ --header "blux-app-id: $BLUX_APP_ID" \ --header "blux-app-secret: $BLUX_APP_SECRET" ``` The same request with Node.js: ```ts const response = await fetch("https://api.blux.cc/server/users?limit=20", { headers: { "blux-app-id": process.env.BLUX_APP_ID!, "blux-app-secret": process.env.BLUX_APP_SECRET!, }, }); if (!response.ok) { const { error } = await response.json(); throw new Error(`Blux API error (${response.status}): ${error}`); } const { result } = await response.json(); console.log(result.users); ``` ## Routes | Method | Route | Purpose | |---|---|---| | `GET` | `/server/users` | List users with filters and pagination. | | `GET` | `/server/users/count` | Count users with the same optional filters. | | `GET` | `/server/users/search` | Find users by exact email or public address. | | `GET` | `/server/users/{user_id}` | Retrieve one user by ID. | | `DELETE` | `/server/users/{user_id}` | Remove one user from the project. | | `POST` | `/server/wallets/verify` | Verify wallet ownership, optionally for a specific user. | For the live machine-readable contract, see the [`server` section in Swagger](https://api.blux.cc/swagger/index.html). --- # App Secret & Authentication URL: https://docs.blux.cc/api/authentication Authenticate Server API calls without exposing your project's App Secret. Every Server API request must identify a project with its **App ID** and authenticate with that project's **App Secret**. Both values are available from your project in the [Blux Dashboard](https://dashboard.blux.cc). The App ID identifies the project and can also appear in client configuration. The App Secret grants backend access and must remain private. ## Header authentication Sending the two Blux headers is the recommended and most explicit option: ```http blux-app-id: your-app-id blux-app-secret: your-app-secret ``` ```bash curl --request GET \ --url 'https://api.blux.cc/server/users/count' \ --header "blux-app-id: $BLUX_APP_ID" \ --header "blux-app-secret: $BLUX_APP_SECRET" ``` ```ts const response = await fetch("https://api.blux.cc/server/users/count", { headers: { "blux-app-id": process.env.BLUX_APP_ID!, "blux-app-secret": process.env.BLUX_APP_SECRET!, }, }); ``` ## HTTP Basic authentication The API also accepts HTTP Basic authentication. Use the App ID as the username and the App Secret as the password: ```bash curl --request GET \ --url 'https://api.blux.cc/server/users/count' \ --user "$BLUX_APP_ID:$BLUX_APP_SECRET" ``` This sends `Authorization: Basic `. Base64 is an encoding, not encryption, so always call the API over HTTPS. ## Secret handling - Load the App Secret from a server-side secret manager or private environment variable. - Restrict access to the production secret to the services that need it. - Keep request headers out of application, proxy, and error logs. - Use separate credentials for separate Blux projects and environments. - Rotate the App Secret from the dashboard if it is exposed, then update the backend's stored value. Do not proxy arbitrary client-supplied paths or methods to the Server API. Expose narrow backend operations with your own authorization checks, especially for `DELETE /server/users/{user_id}`. ## Responses and errors Successful responses that return data have a common envelope: ```json { "message": "...", "result": {} } ``` Operations without a result return: ```json { "message": "..." } ``` Errors return: ```json { "error": "..." } ``` Handle responses by HTTP status before reading the payload: | Status | Meaning | |---|---| | `200` | The request completed. For wallet verification, inspect `result.exists`; a valid negative check is still `200`. | | `400` | A path, query, filter, or request body is invalid. | | `401` | The App ID or App Secret is missing or invalid. | | `404` | The requested user does not exist in this project. Only the single-user routes return this status. | | `500` | Blux could not complete the request. | For `500` responses, avoid automatic unbounded retries. Retry only idempotent reads with backoff; do not automatically retry a delete unless your application can confirm the desired final state. --- # Users URL: https://docs.blux.cc/api/users List, count, search, retrieve, and delete users with the Server API. The user routes operate only on users of the project identified by your Server API credentials. User responses include public account addresses but never private keys or other wallet secrets. ## User object Routes that return users use this shape: ```json { "id": 42, "auth_method": "email", "auth_value": "person@example.com", "wallet": "...", "created_at": "2026-08-01T12:00:00Z", "last_login": "2026-08-03T09:30:00Z", "login_count": 4, "accounts": [ { "id": 91, "network": "stellar", "public_key": "G..." } ] } ``` | Field | Description | |---|---| | `id` | Blux user ID within the API. Use it with the single-user and pinned verification routes. | | `auth_method` | How the user authenticated, such as `email`, `passkey`, `wallet`, or a social provider. | | `auth_value` | The identifier associated with the authentication method. | | `wallet` | Wallet value recorded for the user, when applicable. | | `created_at` | When the user was created. | | `last_login` | The user's most recent login time. | | `login_count` | Number of recorded logins. | | `accounts` | Public accounts linked to the user. Each entry contains an account `id`, `network`, and `public_key`. | ## List users ```http GET /server/users ``` Returns the project's users newest first, with optional filtering and pagination. ### Query parameters | Parameter | Type | Required | Description | |---|---|---|---| | `start_date` | string | No | Include users created on or after this date. Accepts `YYYY-MM-DD` or RFC 3339. | | `end_date` | string | No | Include users created on or before this date. Accepts `YYYY-MM-DD` or RFC 3339. | | `login_method` | string | No | Filter by `wallet`, `socials`, `passkey`, or `email`. Send comma-separated values, repeat the parameter, or combine both forms. | | `page` | integer | No | Page number. Defaults to `1`. | | `limit` | integer | No | Users per page. Defaults to `10`; maximum `100`. | ```bash curl --get 'https://api.blux.cc/server/users' \ --header "blux-app-id: $BLUX_APP_ID" \ --header "blux-app-secret: $BLUX_APP_SECRET" \ --data-urlencode 'start_date=2026-08-01' \ --data-urlencode 'login_method=email,wallet' \ --data-urlencode 'page=1' \ --data-urlencode 'limit=25' ``` The `result` contains the current page and total count: ```json { "message": "...", "result": { "page": 1, "limit": 25, "total_user": 137, "users": [] } } ``` An invalid date, login method, page, or limit returns `400`. ## Count users ```http GET /server/users/count ``` Returns a count without fetching user records. It accepts the same `start_date`, `end_date`, and `login_method` filters as the list route, which makes it useful for metrics and filtered totals. ```bash curl --get 'https://api.blux.cc/server/users/count' \ --header "blux-app-id: $BLUX_APP_ID" \ --header "blux-app-secret: $BLUX_APP_SECRET" \ --data-urlencode 'start_date=2026-08-01T00:00:00Z' \ --data-urlencode 'login_method=socials' ``` ```json { "message": "...", "result": { "total_user": 37 } } ``` ## Search users ```http GET /server/users/search ``` Search by an exact login email or by a public address. You must provide exactly one search parameter. | Parameter | Type | Required | Description | |---|---|---|---| | `email` | string | One of the two | Exact, case-insensitive login email. | | `address` | string | One of the two | Stellar `G...` or Ethereum `0x...` address. Searches Blux-provisioned custodial accounts and external wallet login addresses. | ```bash curl --get 'https://api.blux.cc/server/users/search' \ --header "blux-app-id: $BLUX_APP_ID" \ --header "blux-app-secret: $BLUX_APP_SECRET" \ --data-urlencode 'email=person@example.com' ``` ```json { "message": "...", "result": { "total_user": 1, "users": [] } } ``` The route returns every match because one email can be associated with more than one Blux user, such as separate email and social logins. No match is a successful `200` response with `total_user: 0` and an empty `users` array. Supplying both parameters or neither returns `400`. Use [wallet verification](/api/verify-wallet) when an address is a security decision, such as granting access. Search finds records; verification is explicitly designed to establish that the address came from a real Blux login for your project. ## Get one user ```http GET /server/users/{user_id} ``` Retrieves one user and their public accounts. `user_id` must be an integer and the user must belong to the authenticated project. ```bash curl --request GET \ --url 'https://api.blux.cc/server/users/42' \ --header "blux-app-id: $BLUX_APP_ID" \ --header "blux-app-secret: $BLUX_APP_SECRET" ``` The response places the [user object](#user-object) in `result`. An invalid ID returns `400`; an unknown user or a user from another project returns `404`. ## Delete one user ```http DELETE /server/users/{user_id} ``` Removes the user from the project, equivalent to the dashboard's remove-user action. ```bash curl --request DELETE \ --url 'https://api.blux.cc/server/users/42' \ --header "blux-app-id: $BLUX_APP_ID" \ --header "blux-app-secret: $BLUX_APP_SECRET" ``` ```json { "message": "..." } ``` Deleting is not banning. A deleted user can register again later. Use the dashboard's ban action when future logins from that identity must be blocked, and require your own backend authorization before exposing deletion to an operator or user. An invalid ID returns `400`; an unknown user or a user from another project returns `404`. --- # Verify a Wallet URL: https://docs.blux.cc/api/verify-wallet Confirm that a public address belongs to a user who authenticated with your Blux project. ## Verify an address ```http POST /server/wallets/verify ``` Checks whether a public address belongs to a current user of the authenticated project. The route checks both: - Custodial accounts provisioned by Blux. - An external wallet address used to log in. This protects backend operations from a caller who simply claims to own an address that never came through your project's Blux login flow. ### Request body | Field | Type | Required | Description | |---|---|---|---| | `address` | string | Yes | A Stellar account (`G...`) or Ethereum address (`0x...`). | | `user_id` | integer | No | Require the address to belong to this specific Blux user. | Verify an address anywhere in the project: ```bash curl --request POST \ --url 'https://api.blux.cc/server/wallets/verify' \ --header 'content-type: application/json' \ --header "blux-app-id: $BLUX_APP_ID" \ --header "blux-app-secret: $BLUX_APP_SECRET" \ --data '{ "address": "GBLUXDDBTGCLIC3TYAFYUJ5EO2MPXBSFMU7GHNLQ6IZWEJVXWMLBLUXX" }' ``` Pin the check to the user your application already authenticated or looked up: ```json { "address": "GBLUXDDBTGCLIC3TYAFYUJ5EO2MPXBSFMU7GHNLQ6IZWEJVXWMLBLUXX", "user_id": 42 } ``` Prefer a pinned check when your application is authorizing an action for a known user. Without `user_id`, a positive result only proves that the address belongs to some user in the project. ### Positive result The route returns `200` with `exists: true` and information about the match: ```json { "message": "...", "result": { "exists": true, "user_id": 42, "network": "stellar", "wallet_type": "custodial", "auth_method": "email" } } ``` | Field | Description | |---|---| | `exists` | Whether the address matched a non-deleted project user and, when supplied, the requested `user_id`. | | `user_id` | ID of the user who owns the matching address. | | `network` | Address network, currently `stellar` or `ethereum`. | | `wallet_type` | `custodial` for a Blux-provisioned account or `external` for the user's own login wallet. | | `auth_method` | How the matched user signs in, such as `email`, `passkey`, `wallet`, or a social provider. | ### Negative result A well-formed address that does not match is not an API error. The route returns `200` with `result.exists` set to `false`. Treat `exists` as the authoritative verification decision; do not infer success from the HTTP status alone. Malformed or missing addresses return `400`. Missing or invalid project credentials return `401`. ## Backend authorization pattern Wallet verification should be one part of your backend's authorization decision: ```ts const response = await fetch("https://api.blux.cc/server/wallets/verify", { method: "POST", headers: { "content-type": "application/json", "blux-app-id": process.env.BLUX_APP_ID!, "blux-app-secret": process.env.BLUX_APP_SECRET!, }, body: JSON.stringify({ address, user_id: bluxUserId }), }); if (!response.ok) { const { error } = await response.json(); throw new Error(`Wallet verification failed: ${error}`); } const { result } = await response.json(); if (!result.exists) { throw new Error("This wallet is not linked to the Blux user"); } // Continue with the protected operation. ``` Also authenticate the caller to your own backend and ensure they are allowed to act as `bluxUserId`. Possessing or guessing a user ID must never be enough to authorize an operation. --- # Javascript URL: https://docs.blux.cc/javascript Integrate Blux into any JavaScript project using the core SDK. The `@bluxcc/core` package is framework-agnostic — use it in any JavaScript or TypeScript project without a framework dependency. ## Installation Install the Blux core SDK using your package manager of choice: ```bash npm install @bluxcc/core ``` ```bash pnpm add @bluxcc/core ``` ```bash yarn add @bluxcc/core ``` ## Setup Call `createConfig` once at the entry point of your application to initialize Blux. Do not call it more than once. The only required options are `appId` and `networks`. ```ts import { createConfig, core } from "@bluxcc/core"; createConfig({ appId: "your-app-id", networks: [core.networks.mainnet], }); ``` ```ts const { createConfig, core } = require("@bluxcc/core"); createConfig({ appId: "your-app-id", networks: [core.networks.mainnet], }); ``` ```html ``` ## Use it After `createConfig`, open the built-in modals from the `blux` object. ```ts blux.login(); ``` {getPageTreePeers(source.getPageTree(), '/javascript').map((peer) => ( {peer.description} ))} --- # Core URL: https://docs.blux.cc/javascript/core Low-level Stellar primitives available across all Blux integrations. The `core` module provides direct access to Stellar network data and utilities — use it to read accounts, balances, transactions, offers, and more without managing Horizon connections manually. ```ts ``` --- {getPageTreePeers(source.getPageTree(), '/javascript/core').map((peer) => ( {peer.description} ))} --- # Address resolution and .xlm names URL: https://docs.blux.cc/javascript/core/address-resolution Use G, M, and C addresses, SEP-2 federation addresses, or human-readable .xlm names throughout the Blux SDK. Every Blux core parameter that represents a Stellar account or Soroban contract uses the same address resolver. You can pass: - an account address (`G…`) - a muxed account address (`M…`) where the operation supports one - a contract address (`C…`) - a standard SEP-2 federation address such as `alice*example.com` - an XLM Domains name such as `alice.xlm` or `bot.team.xlm` ```ts await core.getAccount({ address: "alice.xlm" }); await core.transfer({ to: "alice.xlm", amount: "10" }); const { values } = await core.readContracts<[string]>([ { address: "token.xlm", // may resolve to a C… contract fn: "balance", args: ["alice.xlm"], // resolved because the ABI declares Address }, ]); ``` Blux validates literal addresses locally. Names are resolved through SEP-2, and the returned record is validated again. An invalid name, an unregistered name, a record without an address, or the wrong kind of address causes the operation to reject before a transaction is built. ## Mainnet and testnet XLM Domains currently stores its registry on Stellar mainnet. Name resolution is therefore independent of the `network` passed to a Blux function: the same `.xlm` record is used for mainnet and testnet calls. The resolved address is still used on the network you selected. For example, `alice.xlm` may resolve successfully to a mainnet `G…` account that has never been funded on testnet. In that case resolution succeeds, but a testnet account lookup or transaction fails under the normal testnet rules. ## Resolve a name directly Use [`resolveXlmName`](/javascript/core/resolveXlmName) when you specifically want the normalized XLM Domains record, including its `.xlm` name, SEP-2 form, address kind, and optional memo. Use `resolveAddress` when you only need a validated address before calling another API: ```ts const account = await core.resolveAddress("alice.xlm", { expected: "account", }); account.publicKey; // base G… account account.destination; // G… or M… destination for a classic operation account.memo; // optional SEP-2 memo const contract = await core.resolveAddress("token.xlm", { expected: "contract", }); contract.contractId; // C… ``` The `expected` option prevents an address from reaching an incompatible API: | Value | Accepted result | |---|---| | `"account"` (default) | `G…` or `M…`; returns the base `G…` as `publicKey` | | `"contract"` | `C…` only | | `"soroban"` | `G…` or `C…`; muxed accounts are rejected | Standard federation connection options such as `timeout` and `allowHttp` can be passed alongside `expected`. To find a name from a `G…` account instead, use [`resolveXlmNameByAddress`](/javascript/core/resolveXlmNameByAddress). ## Where names work Account names work in `address`, `to`, `source`, `destination`, `forAccount`, `forSigner`, `forIssuer`, `claimant`, `sponsor`, and `seller` fields. Contract names work in contract-call `address` fields and token contract fields. For `readContracts` and `writeContract`, Blux also resolves strings nested in contract arguments whenever the deployed ABI declares that value as `Address`. This includes addresses inside options, vectors, tuples, maps, structs, and union cases. A string parameter that is not an ABI `Address` is left untouched, even if its text ends in `.xlm`. A `CODE:ISSUER` asset string is an asset identifier rather than an address field. Continue using the issuer's `G…` key there, for example `USDC:GA5Z…KZVN`. ## SEP-2 memos When a federation record includes a memo, `transfer` and `swap` automatically attach it to the classic transaction unless you explicitly pass your own `memo`. Soroban arguments and query filters use only the resolved address; federation memos do not apply to those fields. Learn more in the [XLM Domains integration documentation](https://www.xlm.domains/docs) and the Stellar ecosystem's [SEP-2 federation specification](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0002.md). --- # Fund Account URL: https://docs.blux.cc/javascript/core/fundAccount Fund an account with Friendbot on supported Stellar test networks. `fundAccount` requests test lumens from Friendbot for one account on one or more supported test networks. The address can be a `G…`/`M…` account, SEP-2 federation address, or `.xlm` name. ```ts const results = await core.fundAccount("alice.xlm", { network: networks.testnet, }); ``` Omit the first argument to fund the connected account: ```ts const results = await core.fundAccount(); ``` Each result reports the network, Friendbot transaction hash when available, and one of three statuses: `funded`, `already_funded`, or `failed`. `.xlm` resolution uses the mainnet XLM Domains registry even when Friendbot funds testnet. Friendbot then creates or funds the resolved `G…` account on the selected test network. See [address resolution](/javascript/core/address-resolution). Mainnet is not fundable through Friendbot. Passing an unsupported network rejects the call before any request is made. --- # Get Account URL: https://docs.blux.cc/javascript/core/getAccount Fetch details of a Stellar account using the Blux core SDK. The `getAccount` function returns the details of a single Stellar account. Omit `address` to use the connected account, and omit `network` to use the currently active network. `address` accepts `G…`, `M…`, SEP-2 federation, or `.xlm`; see [address resolution](/javascript/core/address-resolution). ## Type ```tsx type GetAccountOptions = { address?: string; // G…/M…, SEP-2 address, or .xlm name network?: string; // Omit to use the active network }; type GetAccountResult = Horizon.AccountResponse | null; ``` ## Usage ```typescript const result = await core.getAccount({ address: "alice.xlm" }); ``` --- # Get Accounts URL: https://docs.blux.cc/javascript/core/getAccounts Fetch a paginated list of Stellar accounts using the Blux core SDK. The `getAccounts` function returns a paginated list of Stellar accounts. At least one filter — `forSigner`, `forAsset`, `sponsor`, or `forLiquidityPool` — must be provided. `forSigner` and `sponsor` accept `G…`, `M…`, SEP-2 federation, or `.xlm` names; see [address resolution](/javascript/core/address-resolution). The return value contains two properties: - `response` — the account records you can use directly - `builder` — exposes `next()` and `prev()` to paginate through results ## Type ```tsx export type CallBuilderOptions = { cursor?: string; limit?: number; network?: string; order?: "asc" | "desc"; }; type GetAccountsOptionsA = { forSigner: string; // G…/M…, SEP-2 address, or .xlm name forAsset?: AssetArg; sponsor?: string; // G…/M…, SEP-2 address, or .xlm name forLiquidityPool?: string; }; type GetAccountsOptionsB = { forSigner?: string; forAsset: AssetArg; sponsor?: string; forLiquidityPool?: string; }; type GetAccountsOptionsC = { forSigner?: string; forAsset?: AssetArg; sponsor: string; forLiquidityPool?: string; }; type GetAccountsOptionsD = { forSigner?: string; forAsset?: AssetArg; sponsor?: string; forLiquidityPool: string; }; export type GetAccountsOptions = CallBuilderOptions & ( GetAccountsOptionsA | GetAccountsOptionsB | GetAccountsOptionsC | GetAccountsOptionsD ) export type GetAccountsResult = { builder: AccountCallBuilder; response: Horizon.ServerApi.CollectionPage; }; ``` ## Usage ```typescript const result = await core.getAccounts({ forSigner: "alice.xlm" }); ``` --- # Get Assets URL: https://docs.blux.cc/javascript/core/getAssets Fetch a paginated list of Stellar assets using the Blux core SDK. The `getAssets` function returns a paginated list of Stellar assets. `forIssuer` accepts a `G…`/`M…` account, SEP-2 federation address, or `.xlm` name; see [address resolution](/javascript/core/address-resolution). The return value contains two properties: - `response` — the asset records you can use directly - `builder` — exposes `next()` and `prev()` to paginate through results ## Type ```tsx export type CallBuilderOptions = { cursor?: string; limit?: number; network?: string; order?: "asc" | "desc"; }; type GetAssetsOptions = CallBuilderOptions & { forCode?: string; forIssuer?: string; // G…/M…, SEP-2 address, or .xlm name }; type GetAssetsResult = { builder: AssetsCallBuilder; response: Horizon.ServerApi.CollectionPage; }; ``` ## Usage ```typescript const result = await core.getAssets({ forCode: "USDC", forIssuer: "issuer.xlm", }); ``` --- # Get Balances URL: https://docs.blux.cc/javascript/core/getBalances Fetch the balances of a Stellar account using the Blux core SDK. The `getBalances` function returns the balances of a Stellar account. Omit `address` to use the connected account, and omit `network` to use the currently active network. `address` accepts `G…`, `M…`, SEP-2 federation, or `.xlm`; see [address resolution](/javascript/core/address-resolution). ## Type ```tsx type GetBalancesOptions = { address?: string; // G…/M…, SEP-2 address, or .xlm name network?: string; // Omit to use the active network includeZeroBalances?: boolean; }; type GetBalancesResult = Horizon.HorizonApi.BalanceLine[]; ``` ## Usage ```typescript const result = await core.getBalances({ address: "alice.xlm" }); ``` --- # Get Claimable Balances URL: https://docs.blux.cc/javascript/core/getClaimableBalances Fetch a paginated list of claimable balances using the Blux core SDK. The `getClaimableBalances` function returns a paginated list of claimable balances. Both `claimant` and `sponsor` accept `G…`, `M…`, SEP-2 federation, or `.xlm` names; see [address resolution](/javascript/core/address-resolution). The return value contains two properties: - `response` — the records you can use directly - `builder` — exposes `next()` and `prev()` to paginate through results ## Type ```tsx export type CallBuilderOptions = { cursor?: string; limit?: number; network?: string; order?: "asc" | "desc"; }; type GetClaimableBalancesOptions = CallBuilderOptions & { asset: AssetArg; sponsor?: string; // G…/M…, SEP-2 address, or .xlm name claimant: string; // G…/M…, SEP-2 address, or .xlm name }; type GetClaimableBalancesResult = { builder: ClaimableBalanceCallBuilder; response: Horizon.ServerApi.CollectionPage; }; ``` ## Usage ```typescript const result = await core.getClaimableBalances({ asset: "xlm", claimant: "alice.xlm", }); ``` --- # Get Effects URL: https://docs.blux.cc/javascript/core/getEffects Fetch a paginated list of Stellar effects using the Blux core SDK. The `getEffects` function returns a paginated list of Stellar effects. `forAccount` accepts `G…`, `M…`, SEP-2 federation, or `.xlm`; see [address resolution](/javascript/core/address-resolution). The return value contains two properties: - `response` — the records you can use directly - `builder` — exposes `next()` and `prev()` to paginate through results ## Type ```tsx export type CallBuilderOptions = { cursor?: string; limit?: number; network?: string; order?: "asc" | "desc"; }; type GetEffectsOptions = CallBuilderOptions & { forAccount?: string; // G…/M…, SEP-2 address, or .xlm name forLedger?: string | number; forTransaction?: string; forOperation?: string; forLiquidityPool?: string; }; type GetEffectsResult = { builder: EffectCallBuilder; response: Horizon.ServerApi.CollectionPage; }; ``` ## Usage ```typescript const result = await core.getEffects({ forAccount: "alice.xlm" }); ``` --- # Get Ledgers URL: https://docs.blux.cc/javascript/core/getLedgers Fetch a paginated list of Stellar ledgers using the Blux core SDK. The `getLedgers` function returns a paginated list of Stellar ledgers. The return value contains two properties: - `response` — the records you can use directly - `builder` — exposes `next()` and `prev()` to paginate through results ## Type ```tsx export type CallBuilderOptions = { cursor?: string; limit?: number; network?: string; order?: "asc" | "desc"; }; type GetLedgersOptions = CallBuilderOptions & { ledger?: number | string; }; type GetLedgersResult = { builder: LedgerCallBuilder; response: Horizon.ServerApi.CollectionPage; }; ``` ## Usage ```typescript const result = await core.getLedgers({}); ``` --- # Get Liquidity Pools URL: https://docs.blux.cc/javascript/core/getLiquidityPools Fetch a paginated list of Stellar liquidity pools using the Blux core SDK. The `getLiquidityPools` function returns a paginated list of Stellar liquidity pools. `forAccount` accepts `G…`, `M…`, SEP-2 federation, or `.xlm`; see [address resolution](/javascript/core/address-resolution). The return value contains two properties: - `response` — the records you can use directly - `builder` — exposes `next()` and `prev()` to paginate through results ## Type ```tsx export type CallBuilderOptions = { cursor?: string; limit?: number; network?: string; order?: "asc" | "desc"; }; type GetLiquidityPoolsOptions = CallBuilderOptions & { forAssets?: Array; forAccount?: string; // G…/M…, SEP-2 address, or .xlm name }; type GetLiquidityPoolsResult = { builder: LiquidityPoolCallBuilder; response: Horizon.ServerApi.CollectionPage; }; ``` ## Usage ```typescript const result = await core.getLiquidityPools({ forAccount: "alice.xlm" }); ``` --- # Get Network URL: https://docs.blux.cc/javascript/core/getNetwork Retrieve the currently active network in your Blux app. The `getNetwork` function returns the currently active network of the app. ## Usage ```typescript core.getNetwork(); ``` --- # Get Offers URL: https://docs.blux.cc/javascript/core/getOffers Fetch a paginated list of Stellar offers using the Blux core SDK. The `getOffers` function returns a paginated list of Stellar offers. `forAccount`, `sponsor`, and `seller` accept `G…`, `M…`, SEP-2 federation, or `.xlm`; see [address resolution](/javascript/core/address-resolution). The return value contains two properties: - `response` — the records you can use directly - `builder` — exposes `next()` and `prev()` to paginate through results ## Type ```tsx export type CallBuilderOptions = { cursor?: string; limit?: number; network?: string; order?: "asc" | "desc"; }; type GetOffersOptions = CallBuilderOptions & { forAccount?: string; // G…/M…, SEP-2 address, or .xlm name buying?: AssetArg; selling?: AssetArg; sponsor?: string; // G…/M…, SEP-2 address, or .xlm name seller?: string; // G…/M…, SEP-2 address, or .xlm name }; type GetOffersResult = { builder: OfferCallBuilder; response: Horizon.ServerApi.CollectionPage; }; ``` ## Usage ```typescript const result = await core.getOffers({ seller: "alice.xlm" }); ``` --- # Get Operations URL: https://docs.blux.cc/javascript/core/getOperations Fetch a paginated list of Stellar operations using the Blux core SDK. The `getOperations` function returns a paginated list of Stellar operations. `forAccount` accepts `G…`, `M…`, SEP-2 federation, or `.xlm`; see [address resolution](/javascript/core/address-resolution). The return value contains two properties: - `response` — the records you can use directly - `builder` — exposes `next()` and `prev()` to paginate through results ## Type ```tsx export type CallBuilderOptions = { cursor?: string; limit?: number; network?: string; order?: "asc" | "desc"; }; type GetOperationsOptions = CallBuilderOptions & { forAccount?: string; // G…/M…, SEP-2 address, or .xlm name forClaimableBalance?: string; forLedger?: string | number; forTransaction?: string; forLiquidityPool?: string; includeFailed?: boolean; }; type GetOperationsResult = { builder: OperationCallBuilder; response: Horizon.ServerApi.CollectionPage; }; ``` ## Usage ```typescript const result = await core.getOperations({ forAccount: "alice.xlm" }); ``` --- # Get Orderbook URL: https://docs.blux.cc/javascript/core/getOrderbook Fetch orderbook data using the Blux core SDK. The `getOrderbook` function returns orderbook data for a given asset pair. The return value contains two properties: - `response` — the orderbook record you can use directly - `builder` — exposes `next()` and `prev()` to paginate through results ## Type ```tsx export type CallBuilderOptions = { cursor?: string; limit?: number; network?: string; order?: "asc" | "desc"; }; type GetOrderbookResult = { builder: OrderbookCallBuilder; response: Horizon.ServerApi.OrderbookRecord; }; ``` ## Usage ```typescript const result = await core.getOrderbook({}); ``` --- # Get Payments URL: https://docs.blux.cc/javascript/core/getPayments Fetch a paginated list of Stellar payments using the Blux core SDK. The `getPayments` function returns a paginated list of Stellar payments. `forAccount` accepts `G…`, `M…`, SEP-2 federation, or `.xlm`; see [address resolution](/javascript/core/address-resolution). The return value contains two properties: - `response` — the records you can use directly - `builder` — exposes `next()` and `prev()` to paginate through results ## Type ```tsx export type CallBuilderOptions = { cursor?: string; limit?: number; network?: string; order?: "asc" | "desc"; }; type GetPaymentsOptions = CallBuilderOptions & { forAccount?: string; // G…/M…, SEP-2 address, or .xlm name forLedger?: string | number; forTransaction?: string; includeFailed?: boolean; }; ``` ## Usage ```typescript const result = await core.getPayments({ forAccount: "alice.xlm" }); ``` --- # Get SAC Address URL: https://docs.blux.cc/javascript/core/getSacAddress Derive the Stellar Asset Contract (SAC) id of a classic asset — locally, with no network call. `getSacAddress` returns the **Stellar Asset Contract (SAC)** id of a classic asset. Every classic asset — native XLM or a `CODE:ISSUER` pair — has a deterministic Soroban contract id derived from the asset plus the network passphrase. That contract, the SAC, is what lets Soroban contracts hold and move the asset. The id is computed **locally** from the asset and passphrase, so there is no network call and the value is returned whether or not the SAC has actually been deployed yet. The function is synchronous — there is nothing to `await`. Feed the result into [`getTokenMetadata`](/javascript/core/getTokenMetadata), [`transfer`](/javascript/core/transfer)'s `token` option, or [`readContracts`](/javascript/core/readContracts) / [`writeContract`](/javascript/core/writeContract) to treat a classic asset as a Soroban token. ## Type ```ts // 'xlm' | 'native' | a 'CODE:ISSUER' string | an Asset instance. type AssetArg = string | Asset; const getSacAddress: (asset: AssetArg, network?: string) => string; ``` | Parameter | Type | Default | Description | |---|---|---|---| | `asset` | `string \| Asset` | — | **Required.** The asset: `"xlm"`/`"native"`, a `"CODE:ISSUER"` string, or an `Asset` instance. | | `network` | `string` | active network | Network passphrase to derive against. The SAC id differs per network. | The SAC id is **network-specific** — the same asset has a different SAC on testnet and mainnet because the passphrase is part of the derivation. Omit `network` to use the active network configured by `createConfig`, or pass one explicitly. ## Usage ### Native XLM ```ts const xlmSac = core.getSacAddress("xlm"); console.log(xlmSac); // "C..." ``` ### An issued asset Pass the asset in `"CODE:ISSUER"` form: ```ts const usdcSac = core.getSacAddress( "USDC:GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN", ); ``` You can also pass an `Asset` instance: ```ts const usdc = new StellarSdk.Asset( "USDC", "GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN", ); const usdcSac = core.getSacAddress(usdc); ``` ### Derive against a specific network ```ts const usdcSacOnMainnet = core.getSacAddress( "USDC:GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN", networks.mainnet, ); ``` ### Read a classic asset's token metadata The SAC id is exactly what [`getTokenMetadata`](/javascript/core/getTokenMetadata) and the Soroban token helpers expect, so the two compose naturally: ```ts const sac = core.getSacAddress( "USDC:GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN", ); const metadata = await core.getTokenMetadata(sac); // { decimals: 7, name: "USDC:GA5Z...", symbol: "USDC" } ``` ## Errors `getSacAddress` throws synchronously with `BLUX:`-prefixed messages: | Message | Cause | |---|---| | `BLUX: getSacAddress needs a network passphrase — pass one, or call createConfig first.` | No `network` was passed and there is no active network (e.g. `createConfig` hasn't run). | It also propagates the underlying SDK error if `asset` is malformed (not `"xlm"`/`"native"`, a valid `"CODE:ISSUER"` pair, or an `Asset`). A SAC id is returned even when the contract has not been deployed on-chain yet. Deriving the id is free and offline; deploying or _using_ the SAC is what touches the network. See the Stellar **assets** skill for the full SAC interop story. --- # Get Strict Receive Paths URL: https://docs.blux.cc/javascript/core/getStrictReceivePaths Fetch strict receive payment paths using the Blux core SDK. The `getStrictReceivePaths` function returns available payment paths for a strict receive operation. When `source` is an account string, it accepts `G…`, `M…`, SEP-2 federation, or `.xlm`; see [address resolution](/javascript/core/address-resolution). The return value contains two properties: - `response` — the records you can use directly - `builder` — exposes `next()` and `prev()` to paginate through results ## Type ```tsx export type CallBuilderOptions = { cursor?: string; limit?: number; network?: string; order?: "asc" | "desc"; }; type GetPaymentPathResult = { builder: PathCallBuilder; response: Horizon.ServerApi.CollectionPage; }; ``` ## Usage ```typescript // args: [ // source: string | AssetArg[], // account address/name, or source assets // destinationAsset: AssetArg, // destinationAmount: string, // ] const result = await core.getStrictReceivePaths( ["alice.xlm", destinationAsset, destinationAmount], options, ); ``` --- # Get Strict Send Paths URL: https://docs.blux.cc/javascript/core/getStrictSendPaths Fetch strict send payment paths using the Blux core SDK. The `getStrictSendPaths` function returns available payment paths for a strict send operation. When `destination` is an account string, it accepts `G…`, `M…`, SEP-2 federation, or `.xlm`; see [address resolution](/javascript/core/address-resolution). The return value contains two properties: - `response` — the records you can use directly - `builder` — exposes `next()` and `prev()` to paginate through results ## Type ```tsx export type CallBuilderOptions = { cursor?: string; limit?: number; network?: string; order?: "asc" | "desc"; }; type GetPaymentPathResult = { builder: PathCallBuilder; response: Horizon.ServerApi.CollectionPage; }; ``` ## Usage ```typescript // args: [ // sourceAsset: AssetArg, // sourceAmount: string, // destination: string | AssetArg[], // account address/name, or destination assets // ] const result = await core.getStrictSendPaths( [sourceAsset, sourceAmount, "alice.xlm"], options, ); ``` --- # Get Token Metadata URL: https://docs.blux.cc/javascript/core/getTokenMetadata Read a SEP-41 token / Stellar Asset Contract's decimals, name, symbol, and owner by simulation — no account or fees. `getTokenMetadata` reads a token contract's metadata by simulating its read-only entrypoints. Like [`readContracts`](/javascript/core/readContracts), it simulates against a null source account — **no account, signing, or fees** — so it works for any contract id, deployed or not yet funded. `decimals`, `name`, and `symbol` come from the standard **SEP-41** token interface. `owner` is read separately and is omitted when the contract has no `owner()` function — notably **Stellar Asset Contracts**, which expose `admin()` rather than `owner()`. `getTokenMetadata` must be called after `createConfig`, but the user does **not** need to be connected — it's a read-only simulation. Pass a token contract id (`C…`) or a `.xlm`/SEP-2 name resolving to one. ## Type ```ts type GetTokenMetadataOptions = { // Network passphrase to read from. Defaults to the active network. network?: string; }; type TokenMetadata = { // Number of decimal places the token uses. decimals: number; // Human-readable token name. name: string; // Token symbol / code. symbol: string; // The token's owner, when the contract exposes an owner() function. Absent // for contracts without one — notably Stellar Asset Contracts, which expose // admin() rather than owner(). owner?: string; }; const getTokenMetadata: ( address: string, options?: GetTokenMetadataOptions, ) => Promise; ``` | Parameter | Type | Default | Description | |---|---|---|---| | `address` | `string` | — | **Required.** A token contract id (`C…`) or `.xlm`/SEP-2 name resolving to one, e.g. a SAC from [`getSacAddress`](/javascript/core/getSacAddress). | | `options.network` | `string` | active network | Network passphrase to read from. | ## Usage ### Read a token contract directly ```ts const metadata = await core.getTokenMetadata( "CB64D3G7SM2RTH6JSGG34DDTFTQ5CFDKVDZJZSODMCX4NJ2HV2KN7OG", ); console.log(metadata); // { decimals: 7, name: "USD Coin", symbol: "USDC", owner: "G..." } ``` The contract can also be addressed by name: ```ts const metadata = await core.getTokenMetadata("token.xlm"); ``` Blux rejects the call if the name is unregistered or resolves to a `G…` account instead of a `C…` contract. See [address resolution](/javascript/core/address-resolution). ### Read a classic asset's metadata through its SAC Derive the Stellar Asset Contract id with [`getSacAddress`](/javascript/core/getSacAddress), then read it. A SAC has no `owner()`, so `owner` comes back `undefined`: ```ts const sac = core.getSacAddress( "USDC:GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN", ); const metadata = await core.getTokenMetadata(sac); // { decimals: 7, name: "USDC:GA5Z...", symbol: "USDC", owner: undefined } ``` ### Read from a specific network ```ts const metadata = await core.getTokenMetadata( "CB64D3G7SM2RTH6JSGG34DDTFTQ5CFDKVDZJZSODMCX4NJ2HV2KN7OG", { network: networks.mainnet }, ); ``` ## Return value `getTokenMetadata` resolves to a `TokenMetadata` object: | Field | Type | Description | |---|---|---| | `decimals` | `number` | Number of decimal places the token uses — divide raw base-unit balances by `10 ** decimals` to display them. | | `name` | `string` | Human-readable token name. | | `symbol` | `string` | Token symbol / code. | | `owner` | `string \| undefined` | The contract owner when an `owner()` entrypoint exists; `undefined` otherwise (e.g. a SAC). | `decimals` is the key you need before showing or sending amounts: a token with 7 decimals represents `100` tokens as `1000000000` base units. Pair it with [`transfer`](/javascript/core/transfer)'s `token` option or [`readContracts`](/javascript/core/readContracts)' `balance` read. ## Errors `getTokenMetadata` rejects with `BLUX:`-prefixed messages: | Message | Cause | |---|---| | `BLUX: getTokenMetadata must be called after createConfig` | Called before `createConfig` ran. | | `BLUX: getTokenMetadata requires a token contract id or .xlm name.` | `address` was missing. | | `BLUX: "" resolves to an account address (G...), but this field requires a contract address (C...).` | The record is valid, but it points to an account rather than a token contract. | | `BLUX: getTokenMetadata could not read the token.` | The simulation returned no readable result. | A contract that is missing the standard `decimals`/`name`/`symbol` entrypoints causes the underlying simulation to fail, which propagates as an error — `getTokenMetadata` expects a SEP-41-compatible token. A missing `owner()` is **not** an error; `owner` is simply omitted. --- # Get Trade Aggregation URL: https://docs.blux.cc/javascript/core/getTradeAggregation Fetch trade aggregation data using the Blux core SDK. The `getTradeAggregation` function returns aggregated trade data for a given asset pair and time range. The return value contains two properties: - `response` — the records you can use directly - `builder` — exposes `next()` and `prev()` to paginate through results ## Type ```tsx export type CallBuilderOptions = { cursor?: string; limit?: number; network?: string; order?: "asc" | "desc"; }; ``` ## Usage ```typescript // args: [ // base: Asset, // counter: Asset, // start_time: number, // end_time: number, // resolution: number, // offset: number, // ] const result = await core.getTradeAggregation( [base, counter, start_time, end_time, resolution, offset], options, ); ``` --- # Get Trades URL: https://docs.blux.cc/javascript/core/getTrades Fetch a paginated list of Stellar trades using the Blux core SDK. The `getTrades` function returns a paginated list of Stellar trades. `forAccount` accepts `G…`, `M…`, SEP-2 federation, or `.xlm`; see [address resolution](/javascript/core/address-resolution). The return value contains two properties: - `response` — the records you can use directly - `builder` — exposes `next()` and `prev()` to paginate through results ## Type ```tsx export type CallBuilderOptions = { cursor?: string; limit?: number; network?: string; order?: "asc" | "desc"; }; type GetTradesOptions = CallBuilderOptions & { forAssetPair?: [base: AssetArg, counter: AssetArg]; forOffer?: string; forType?: Horizon.ServerApi.TradeType; forAccount?: string; // G…/M…, SEP-2 address, or .xlm name forLiquidityPool?: string; }; type GetTradesResult = { builder: TradesCallBuilder; response: Horizon.ServerApi.CollectionPage; }; ``` ## Usage ```typescript const result = await core.getTrades({ forAccount: "alice.xlm" }); ``` --- # Get Transactions URL: https://docs.blux.cc/javascript/core/getTransactions Fetch a paginated list of Stellar transactions using the Blux core SDK. The `getTransactions` function returns a paginated list of Stellar transactions. `forAccount` accepts `G…`, `M…`, SEP-2 federation, or `.xlm`; see [address resolution](/javascript/core/address-resolution). The return value contains two properties: - `response` — the records you can use directly - `builder` — exposes `next()` and `prev()` to paginate through results ## Type ```tsx export type CallBuilderOptions = { cursor?: string; limit?: number; network?: string; order?: "asc" | "desc"; }; type GetTransactionsOptions = CallBuilderOptions & { forAccount?: string; // G…/M…, SEP-2 address, or .xlm name forClaimableBalance?: string; forLedger?: string | number; forLiquidityPool?: string; includeFailed?: boolean; }; type GetTransactionsResult = { builder: TransactionCallBuilder; response: Horizon.ServerApi.CollectionPage; }; ``` ## Usage ```typescript const result = await core.getTransactions({ forAccount: "alice.xlm" }); ``` --- # Networks URL: https://docs.blux.cc/javascript/core/networks Access the list of available Stellar networks from the Blux core SDK. ## Import ```typescript core.networks; ``` ## Available Networks ```typescript export const networks = { mainnet: Networks.PUBLIC, // 'Public Global Stellar Network ; September 2015' testnet: Networks.TESTNET, // 'Test SDF Network ; September 2015' sandbox: Networks.SANDBOX, // 'Local Sandbox Stellar Network ; September 2022' futurenet: Networks.FUTURENET, // 'Test SDF Future Network ; October 2022' standalone: Networks.STANDALONE, // 'Standalone Network ; February 2017' }; ``` --- # Read Contracts URL: https://docs.blux.cc/javascript/core/readContracts Read state from Soroban smart contracts by simulating contract calls. `readContracts` is a **Soroban** helper that reads data from one or more smart contracts. It builds each call, simulates it against the network (no signature, no fee, no on-chain state change), and returns the decoded results. Use it for any read-only contract method — token balances, metadata, pool reserves, configuration, and so on. It accepts an **array of calls** and runs them in parallel, so you can batch several reads in a single request. `readContracts` simulates against a null source account, so it never spends fees or requires the user to be connected. For methods that mutate state, use [`writeContract`](/javascript/core/writeContract). ## Type ```ts type IContractCall = { address: string; // C… contract ID, SEP-2 address, or .xlm name fn: string; // function name to invoke args: unknown[]; // native values in the function's positional order }; type ReadContractsOptions = { network?: string; // Omit to use the active network }; // Returns the simulation objects and the decoded native values, // index-aligned with the calls you passed in. type ReadContractsResult = { raws: SimulateTransactionResponse[]; values: TValues; }; const readContracts: ( calls: IContractCall[], options?: ReadContractsOptions, ) => Promise>; ``` ## Native contract arguments Pass ordinary JavaScript values in the same order as the contract function's parameters. Blux loads the deployed contract spec and encodes every value as the declared Soroban type, so `args` does not require the `ToScVal` class. ```ts args: [ "alice.xlm", // resolved and encoded when the spec declares Address "1000000000", // encoded as i128 when the spec declares i128 true, // encoded as bool when the spec declares bool ] ``` Common native values include: | Soroban parameter | JavaScript value | |---|---| | Address, string, or symbol | `string` | | Boolean | `boolean` | | Integer | Safe `number`, `bigint`, or decimal `string` | | Bytes | `Uint8Array` | | Vector or tuple | `Array` | | Map | `Map` or an array of `[key, value]` entries | | Struct | An object or tuple matching the contract definition | For wide integers such as `i128`, prefer a `bigint` or decimal string so the value cannot lose precision. Argument count, order, and shape must still match the contract spec. Address-typed values accept `G…`, `C…`, SEP-2 federation addresses, and `.xlm` names. Resolution also works when an ABI `Address` is nested in an option, vector, tuple, map, struct, or union. See [address resolution](/javascript/core/address-resolution). Existing code may continue passing pre-encoded `xdr.ScVal` arguments. Native values and pre-encoded values can also be mixed, but manual encoding is no longer required. ## Usage Read a single value — for example a token's `balance`: ```ts const { values } = await core.readContracts<[string]>([ { address: "CB64D3G7SM2RTH6JSGG34DDTFTQ5CFDKVDZJZSODMCX4NJ2HV2KN7OG", fn: "balance", args: ["alice.xlm"], }, ]); console.log(values[0]); // decoded balance, e.g. "1000000000" ``` Batch several reads at once — results are index-aligned with the calls: ```ts const TOKEN = "CB64D3G7SM2RTH6JSGG34DDTFTQ5CFDKVDZJZSODMCX4NJ2HV2KN7OG"; const { values } = await core.readContracts<[string, number, string]>([ { address: TOKEN, fn: "name", args: [] }, { address: TOKEN, fn: "decimals", args: [] }, { address: TOKEN, fn: "balance", args: ["GA...USER"] }, ]); const [name, decimals, balance] = values; ``` ## Return types The deployed ABI is loaded at runtime, so TypeScript cannot infer a return type from runtime `address`, `fn`, and `network` strings. Pass one tuple generic for the batch, in the same order as the calls: ```ts const result = await core.readContracts<[string, number, string]>(calls); result.values[0]; // string result.values[1]; // number result.values[2]; // string ``` Omit the generic when the return shapes are not known; values are then `readonly unknown[]`. Include `null` in an entry's type when that function can return no value. `bigint` results are returned as strings so they're safe to serialize. The raw simulation objects are available under `raws` if you need footprint or resource details. --- # resolveXlmName URL: https://docs.blux.cc/javascript/core/resolveXlmName Resolve an XLM Domains name to a validated Stellar account or Soroban contract record. `resolveXlmName` resolves a human-readable `.xlm` name to a validated Stellar account (`G…`) or Soroban contract (`C…`). It also preserves any memo requested by the SEP-2 record. ```ts const record = await resolveXlmName("alice.xlm"); console.log(record.name); // "alice.xlm" console.log(record.address); // "G..." or "C..." console.log(record.kind); // "account" or "contract" ``` The function trims the input and converts it to lowercase. It accepts only `.xlm` notation; use [`resolveAddress`](/javascript/core/address-resolution#resolve-a-name-directly) when the input might instead be a literal Stellar address or a standard SEP-2 address such as `alice*example.com`. ## Type ```ts type XlmNameLookupOptions = { allowHttp?: boolean; timeout?: number; }; type XlmNameRecord = | { kind: "account"; name: string; federationAddress: string; address: string; publicKey: string; memo?: string; memoType?: string; } | { kind: "contract"; name: string; federationAddress: string; address: string; contractId: string; memo?: string; memoType?: string; }; function resolveXlmName( name: string, options?: XlmNameLookupOptions, ): Promise; ``` ## Account and contract records Use `kind` to narrow the returned union: ```ts const record = await resolveXlmName("token.xlm", { timeout: 5000 }); if (record.kind === "account") { console.log(record.publicKey); // G… } else { console.log(record.contractId); // C… } ``` | Field | Type | Description | |---|---|---| | `name` | `string` | Normalized `.xlm` name. | | `federationAddress` | `string` | SEP-2 form, such as `alice*xlm.domains`. | | `address` | `string` | Validated `G…` account or `C…` contract address. | | `kind` | `"account" \| "contract"` | Discriminator for the address type. | | `publicKey` | `string` | Present when `kind` is `"account"`. | | `contractId` | `string` | Present when `kind` is `"contract"`. | | `memo` | `string \| undefined` | Memo requested by the record, when present. | | `memoType` | `string \| undefined` | SEP-2 memo type, when present. | XLM Domains uses a mainnet registry, so this lookup is independent of Blux's active transaction network. If the record contains a memo, include it when constructing a payment yourself. To look up a name from a `G…` account, use [`resolveXlmNameByAddress`](/javascript/core/resolveXlmNameByAddress). ## Errors The promise rejects when the input is not a `.xlm` name, the name is unregistered, the record has no address, or the returned address is invalid. --- # resolveXlmNameByAddress URL: https://docs.blux.cc/javascript/core/resolveXlmNameByAddress Find one verified XLM Domains name associated with a Stellar account. `resolveXlmNameByAddress` accepts a classic Stellar account address (`G…`) and returns one associated `.xlm` name. Blux forward-resolves the returned name and only returns it when it points back to the requested account. ```ts const record = await resolveXlmNameByAddress("G..."); console.log(record.name); // "alice.xlm" console.log(record.publicKey); // original G… account ``` ## Type ```ts function resolveXlmNameByAddress( address: string, options?: XlmNameLookupOptions, ): Promise; ``` `XlmNameLookupOptions` supports `timeout` and `allowHttp`. The returned `XlmAccountNameRecord` has the same account fields documented for [`resolveXlmName`](/javascript/core/resolveXlmName#account-and-contract-records), with `kind: "account"` and a `publicKey`. An account can own multiple names. The XLM Domains reverse lookup chooses one record; this function does not return every name owned by the account. ## Errors The promise rejects when: - `address` is not a valid `G…` account address - the account has no reverse record - the returned record is malformed - the returned name does not resolve back to the requested account Contract addresses (`C…`) and muxed accounts (`M…`) are not supported by this lookup. --- # Swap URL: https://docs.blux.cc/javascript/core/swap Trade one asset for another through the Stellar DEX and liquidity pools — Blux finds the best path and submits it for you. `swap` trades one asset for another through the Stellar **DEX** and **liquidity pools**. You describe the trade — _sell this, buy that_ — and Blux discovers the best path payment automatically, applies a slippage guardrail, and submits the transaction through its signing flow. It builds on Stellar's two path-payment operations: - **`exactIn`** (the default) — you send an exact amount of `fromAsset` and the received amount floats. Blux quotes the route, then sets a `destMin` floor so you never receive less than your slippage tolerance allows. - **`exactOut`** — you receive an exact amount of `toAsset` and the spent amount floats. Blux sets a `sendMax` ceiling so you never spend more than your slippage tolerance allows. By default the bought asset is delivered back to the connected account (a **self-swap**); pass `to` to send it somewhere else. The connected account is always the source, and the call resolves to the same [`ISubmittedTransaction`](/javascript/usage/send-transaction#return-value) envelope returned by [`sendTransaction`](/javascript/usage/send-transaction) and [`transfer`](/javascript/core/transfer). `swap` must be called after `createConfig` and while a user is connected — the connected account is the source. Like `sendTransaction`, it shows the Blux confirmation modal before signing (unless you set `showWalletUIs: false` in `createConfig`). Wrap the call in `try/catch` to handle validation errors and user rejection. ## Type ```ts type Numberish = string | number | bigint; // 'xlm' | 'native' | a 'CODE:ISSUER' string | an Asset instance. type AssetArg = string | Asset; // Which side of the trade is fixed. type SwapType = "exactIn" | "exactOut"; type SwapOptions = { // Asset being sold. 'xlm'/'native', a 'CODE:ISSUER' string, or an Asset. fromAsset: AssetArg; // Asset being bought. Same accepted forms as fromAsset. toAsset: AssetArg; // The fixed amount, in decimal units. For 'exactIn' this is how much // fromAsset to send; for 'exactOut' it is how much toAsset to receive. // Numbers and bigints are coerced to a string. amount: Numberish; // Which side is fixed. Defaults to 'exactIn'. type?: SwapType; // Where the bought asset is delivered: G.../M..., a SEP-2 address, or .xlm // name. Defaults to the connected account (a self-swap). to?: string; // Maximum acceptable slippage as a fraction, where 0.005 = 0.5%. Defaults // to 0.005. Must be >= 0 and < 1. slippage?: number; // Optional text memo to attach to the transaction. memo?: string; // Network passphrase to swap on. Defaults to the active network. network?: string; }; const swap: (options: SwapOptions) => Promise; ``` | Parameter | Type | Default | Description | |---|---|---|---| | `fromAsset` | `string \| Asset` | — | **Required.** Asset being sold: `"xlm"`/`"native"`, `"CODE:ISSUER"`, or an `Asset`. | | `toAsset` | `string \| Asset` | — | **Required.** Asset being bought. Same accepted forms as `fromAsset`; must differ from it. | | `amount` | `string \| number \| bigint` | — | **Required.** The fixed amount in decimal units (`"100"`, not base units). Meaning depends on `type` — see below. Must be greater than zero. | | `type` | `"exactIn" \| "exactOut"` | `"exactIn"` | Which side of the trade is fixed. | | `to` | `string` | connected account | Recipient of the bought asset: `G…`/`M…`, a SEP-2 address, or `.xlm` name. Omit for a self-swap. | | `slippage` | `number` | `0.005` | Maximum slippage as a fraction (`0.005` = 0.5%). Must be `>= 0` and `< 1`. | | `memo` | `string` | — | Optional text memo. | | `network` | `string` | active network | Network passphrase to swap on — use the `networks` map (e.g. `networks.testnet`). | ## `exactIn` vs. `exactOut` `amount` always names the **fixed** side; the other side floats within your slippage tolerance. | | `exactIn` (default) | `exactOut` | |---|---|---| | `amount` is the exact… | `fromAsset` you **send** | `toAsset` you **receive** | | What floats | the amount received | the amount sent | | Slippage guardrail | `destMin` — the least you'll accept | `sendMax` — the most you'll spend | | Underlying operation | [`pathPaymentStrictSend`](/javascript/core/getStrictSendPaths) | [`pathPaymentStrictReceive`](/javascript/core/getStrictReceivePaths) | In both cases Blux discovers the best available route and embeds it in the operation, so you never assemble the path yourself. Routes of at most 3 assets (one intermediary hop) are preferred — some Horizon nodes reject path payments with longer chains — and a longer route is only used when no shorter one exists, in which case submission relies on your configured Horizon node accepting it. ## Slippage `slippage` is a fraction of the quoted price, not a percentage: `0.005` means 0.5%, `0.01` means 1%. Blux derives the on-chain guardrail from the quote and your tolerance: - `exactIn` → `destMin = quotedOut × (1 − slippage)`, rounded **down**. - `exactOut` → `sendMax = quotedIn × (1 + slippage)`, rounded **up**. The bound is always rounded so it is never tighter than you asked for. If the market moves past it before the transaction lands, the operation fails on-chain rather than executing at a worse price. A tighter `slippage` protects the price but is more likely to fail in a volatile market; a looser one is more likely to fill. ## Trustlines To receive an issued asset, the recipient needs a trustline for it. - **Self-swap into an asset you've never held** — Blux prepends the required `changeTrust` operation automatically, so a first-time buy of an issued asset just works. - **Delivering to another account (`to`)** — the recipient must already trust `toAsset`. If they don't, `swap` throws rather than silently failing on-chain. Swapping _into_ native XLM never needs a trustline. ## Usage ### Sell an exact amount (`exactIn`) The simplest case — sell exactly 100 XLM for USDC, delivered back to yourself. `exactIn` is the default, so `type` can be omitted: ```ts const result = await core.swap({ fromAsset: "xlm", toAsset: "USDC:GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN", amount: "100", // sell exactly 100 XLM }); console.log(result.hash); ``` If this is the first time the account holds USDC, the required trustline is added for you. ### Buy an exact amount (`exactOut`) Receive exactly 50 USDC, spending however much XLM the route requires (up to the slippage-bounded `sendMax`): ```ts await core.swap({ fromAsset: "xlm", toAsset: "USDC:GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN", amount: "50", type: "exactOut", // receive exactly 50 USDC }); ``` ### Deliver the bought asset to another account Pass `to` to send the proceeds elsewhere, with a tighter slippage and a memo. The destination must already trust `toAsset`: ```ts await core.swap({ fromAsset: "USDC:GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN", toAsset: "xlm", amount: "25", to: "GDESTINATION...ADDRESS", slippage: 0.01, // 1% memo: "cash out", }); ``` `to` also accepts a SEP-2 federated address (`alice*example.com`) or `.xlm` name (`alice.xlm`), which Blux resolves before building the swap. A memo from the name record is attached unless you pass `memo` yourself. See [address resolution](/javascript/core/address-resolution). ### Pass an `Asset` instance Anywhere a `"CODE:ISSUER"` string is accepted you can pass an `Asset` instead: ```ts const usdc = new StellarSdk.Asset( "USDC", "GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN", ); await core.swap({ fromAsset: "xlm", toAsset: usdc, amount: "100" }); ``` ### Swap on a specific network Omit `network` to use the active network, or pass a passphrase explicitly: ```ts await core.swap({ fromAsset: "xlm", toAsset: "USDC:GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN", amount: "100", network: networks.mainnet, }); ``` ## Return value `swap` resolves to an [`ISubmittedTransaction`](/javascript/usage/send-transaction#return-value): ```ts interface ISubmittedTransaction { hash: string; // the transaction hash returnValue: () => Promise; // null — a path payment returns no value raw: SubmitTransactionResponse | GetSuccessfulTransactionResponse; } ``` `result.hash` identifies the swap; the full Horizon response is available under `result.raw`. ## Errors `swap` rejects with `BLUX:`-prefixed messages so failures are actionable: | Message | Cause | |---|---| | `BLUX: swap must be called after createConfig` | Called before `createConfig` ran. | | `BLUX: swap requires an options object.` | Called with no options object. | | `BLUX: No account is logged in.` | No connected user to act as the source. | | `BLUX: swap requires "fromAsset" and "toAsset".` | Either asset was missing. | | `BLUX: swap requires an "amount".` | `amount` was missing. | | `BLUX: swap "type" must be "exactIn" or "exactOut".` | An invalid `type` was passed. | | `BLUX: swap "slippage" must be a fraction between 0 and 1 (e.g. 0.005 for 0.5%).` | `slippage` was out of the `[0, 1)` range. | | `BLUX: swap "amount" must be greater than zero.` | `amount` was zero or negative. | | `BLUX: "amount" could not be represented precisely; pass it as a string (e.g. "0.0000001").` | A tiny/huge `amount` rendered in exponential form — pass it as a string. | | `BLUX: "fromAsset" and "toAsset" must be different.` | Both sides resolved to the same asset. | | `BLUX: The logged-in account is not active on this network yet.` | The source account isn't funded on this network. | | `BLUX: The destination account does not exist; a swap cannot create it.` | `to` points at an account that hasn't been created. | | `BLUX: The destination has no trustline for .` | A non-self destination doesn't trust `toAsset`. | | `BLUX: No swap path found from to — the issuer could not be found on ; is it an asset from a different network?` | The issuer account does not exist on the network being queried — usually a mainnet issuer used on testnet or vice versa. | | `BLUX: No swap path found from to on — no route can fill this amount right now.` | Both assets exist, but no route (or not enough liquidity for this amount) exists between them right now. | Errors raised while signing and submitting (`BLUX: User is not authenticated.`, network busy, on-chain failure, …) propagate unchanged from [`sendTransaction`](/javascript/usage/send-transaction#errors). Want to quote a swap before committing — to show the user a rate or preview the floating side? Read the route directly with [`getStrictSendPaths`](/javascript/core/getStrictSendPaths) (`exactIn`) or [`getStrictReceivePaths`](/javascript/core/getStrictReceivePaths) (`exactOut`); they take no signature and cost nothing. --- # Switch Network URL: https://docs.blux.cc/javascript/core/switchNetwork Switch the active network in your Blux app at runtime. The `switchNetwork` function switches the app to a different network. The target network must be included in the `networks` array defined in `createConfig`. ## Usage ```typescript core.switchNetwork(core.networks.testnet); ``` --- # Transfer URL: https://docs.blux.cc/javascript/core/transfer Send XLM, issued assets, or SEP-41 tokens to any recipient — Blux picks the right operation for you. `transfer` is the high-level "send value" helper. You describe **what** you want — _send this amount of this asset to this recipient_ — and Blux figures out the **how**, building and submitting the correct transaction through its signing flow. It covers two worlds from a single function: - **Stellar (classic) transfers** — XLM and issued assets. Blux inspects the recipient and automatically chooses a `payment`, a `createAccount`, or a `createClaimableBalance` so the transfer doesn't fail on edge cases (a brand-new account, a missing trustline, …). - **Soroban (SEP-41 token) transfers** — set `token` to a contract id and value moves through the token contract's `transfer(from, to, amount)` entrypoint instead. The connected account is always the sender, and the call resolves to the same [`ISubmittedTransaction`](/javascript/usage/send-transaction#return-value) envelope returned by [`sendTransaction`](/javascript/usage/send-transaction) and [`writeContract`](/javascript/core/writeContract). `transfer` must be called after `createConfig` and while a user is connected — the connected account is the source. Like `sendTransaction`, it shows the Blux confirmation modal before signing (unless you set `showWalletUIs: false` in `createConfig`). Wrap the call in `try/catch` to handle validation errors and user rejection. ## Type ```ts type Numberish = string | number | bigint; type TransferOptions = { // Recipient: a Stellar address (G... or muxed M...), SEP-2 address, or .xlm // name. For a `token` transfer, a contract id/name is also accepted. to: string; // Amount to send (must be > 0). Numbers and bigints are coerced to a string. // Classic assets use a decimal amount ("10.5"); a `token` uses the integer // base-unit amount the contract expects. amount: Numberish; // Classic asset to send. Defaults to the native lumen. Accepts // 'xlm' | 'native' | 'CODE:ISSUER' | an Asset instance. Ignored when `token` is set. asset?: string | Asset; // Optional text memo. Ignored for `token` (Soroban) transfers. memo?: string; // When the recipient can't receive the asset directly (its account does not // exist, or it has no trustline for an issued asset), send a claimable balance // it can claim later instead of failing. Defaults to false. claimable?: boolean; // A SEP-41 token contract id (C...) or name resolving to one. When set, // value moves through the contract's transfer entrypoint. token?: string; // Network passphrase to send on. Defaults to the active network. network?: string; }; const transfer: (options: TransferOptions) => Promise; ``` | Parameter | Type | Default | Description | |---|---|---|---| | `to` | `string` | — | **Required.** Recipient. A Stellar address (`G…` or muxed `M…`), SEP-2 address, or `.xlm` name. For a `token` transfer, a contract address/name is also accepted. | | `amount` | `string \| number \| bigint` | — | **Required.** Must be greater than zero. Decimal units for a classic asset (`"10.5"`); integer base units for a `token`. | | `asset` | `string \| Asset` | `"native"` | Classic asset: `"xlm"`/`"native"`, `"CODE:ISSUER"`, or an `Asset` instance. Ignored when `token` is set. | | `memo` | `string` | — | Optional text memo. Ignored for `token` transfers. | | `claimable` | `boolean` | `false` | Fall back to a claimable balance when the recipient can't receive directly (see below). | | `token` | `string` | — | SEP-41 token contract id (`C…`) or `.xlm`/SEP-2 name resolving to one. Switches the call to the Soroban token path. | | `network` | `string` | active network | Network passphrase to send on — use the `networks` map (e.g. `networks.testnet`). | ## How the classic operation is chosen For classic assets you never pick the operation yourself — `transfer` reads the recipient's on-chain state and selects the one the network will accept: | Recipient state | `claimable` | Operation used | |---|---|---| | Exists & trusts the asset (native always qualifies) | any | `payment` | | Exists, but has **no trustline** for the issued asset | `true` | `createClaimableBalance` | | Exists, but has **no trustline** for the issued asset | `false` | ❌ throws — pass `claimable: true` | | **Doesn't exist yet**, sending **XLM** | `false` | `createAccount` (funds the new account) | | **Doesn't exist yet**, sending an issued asset | `false` | ❌ throws — send XLM, or pass `claimable: true` | | **Doesn't exist yet** | `true` | `createClaimableBalance` | A new account can only be **created** with XLM, so sending an issued asset to an address that doesn't exist yet is rejected unless you opt into `claimable: true` — the recipient then claims it once they create their account and add the trustline. ## Usage — Stellar (classic) transfers ### Send XLM The simplest case. `asset` defaults to the native lumen: ```ts const result = await core.transfer({ to: "GDESTINATION...ADDRESS", amount: "10", // 10 XLM }); console.log(result.hash); ``` If `GDESTINATION...ADDRESS` doesn't exist yet, this automatically becomes a `createAccount` that funds it with the 10 XLM. ### Send an issued asset Pass the asset in `"CODE:ISSUER"` form: ```ts await core.transfer({ to: "GDESTINATION...ADDRESS", amount: "25.5", asset: "USDC:GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN", }); ``` You can also pass an `Asset` instance instead of a string: ```ts const usdc = new StellarSdk.Asset( "USDC", "GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN", ); await core.transfer({ to: "GDESTINATION...ADDRESS", amount: "25.5", asset: usdc }); ``` ### Attach a memo Many exchanges and custodial wallets require a memo to credit your deposit: ```ts await core.transfer({ to: "GDESTINATION...ADDRESS", amount: "100", asset: "USDC:GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN", memo: "invoice-1234", }); ``` ### Send to a federated address (SEP-2) Pass a `name*domain` address and Blux resolves it against the domain's federation server — including any memo the federation record asks senders to attach: ```ts await core.transfer({ to: "alice*example.com", amount: "10" }); ``` The same call accepts an XLM Domains name. Blux resolves it, validates the record, and applies any SEP-2 memo before building the transaction: ```ts await core.transfer({ to: "alice.xlm", amount: "10" }); ``` See [address resolution and `.xlm` names](/javascript/core/address-resolution) for validation, mainnet/testnet behavior, and contract-address records. ### Fall back to a claimable balance When the recipient's account doesn't exist yet, or it hasn't added a trustline for your issued asset, a direct payment would fail. Pass `claimable: true` to send a [claimable balance](/javascript/core/getClaimableBalances) they can claim on their own schedule: ```ts await core.transfer({ to: "GNEW...RECIPIENT", amount: "100", asset: "USDC:GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN", claimable: true, }); ``` ## Usage — Soroban (SEP-41 token) transfers Set `token` to a SEP-41 token contract id or a `.xlm` name resolving to one. Blux calls the contract's `transfer(from, to, amount)` entrypoint with the connected account as `from`, simulates it, signs, submits via Soroban RPC, and waits for finalization — exactly like [`writeContract`](/javascript/core/writeContract), but you don't encode any arguments yourself. ```ts const result = await core.transfer({ token: "CB64D3G7SM2RTH6JSGG34DDTFTQ5CFDKVDZJZSODMCX4NJ2HV2KN7OG", to: "GRECIPIENT...ADDRESS", amount: "1000000000", // integer base units — see note below }); console.log(result.hash); console.log(await result.returnValue()); // null — SEP-41 transfer returns void ``` **Token amounts are integer base units, not decimals.** A token with 7 decimals represents `100` tokens as `100 * 10^7 = "1000000000"`. Passing a decimal (e.g. `"100.5"`) throws. Read the token's `decimals` with [`readContracts`](/javascript/core/readContracts) and scale before calling: ```ts const baseUnits = (100n * 10n ** 7n).toString(); // "1000000000" ``` The recipient can be an account **or another contract** — pass a contract id (`C…`) directly: ```ts await core.transfer({ token: "CB64D3G7SM2RTH6JSGG34DDTFTQ5CFDKVDZJZSODMCX4NJ2HV2KN7OG", to: "CRECIPIENT...CONTRACT", // send to a contract amount: "5000000", }); ``` `asset`, `memo`, and `claimable` are classic-only and are ignored on the token path. A token recipient may be `G…`, `C…`, SEP-2, or `.xlm`; muxed `M…` addresses are rejected because Soroban addresses cannot carry a muxed memo id. Want to bridge a classic asset (XLM or a `CODE:ISSUER` asset) into Soroban as a token? Use the asset's **Stellar Asset Contract (SAC)** id as `token`. See the Stellar **assets** skill for the SAC interop layer. ## Classic vs. token at a glance | | Classic (default) | Token (`token` set) | |---|---|---| | `amount` | decimal units — `"10.5"` | integer base units — `"10500000"` | | `asset` | `"native"` / `"CODE:ISSUER"` / `Asset` | ignored | | `memo` | supported | ignored | | `claimable` | supported | not applicable | | Recipient | `G…` / `M…` / SEP-2 / `.xlm` | `G…` / `C…` / SEP-2 / `.xlm` | | Operation | `payment` / `createAccount` / `createClaimableBalance` | SEP-41 `transfer(from, to, amount)` | | Settles via | Horizon (immediate) | Soroban RPC (waited until finalized) | ## Return value `transfer` resolves to an [`ISubmittedTransaction`](/javascript/usage/send-transaction#return-value): ```ts interface ISubmittedTransaction { hash: string; // the transaction hash returnValue: () => Promise; // null for classic & SEP-41 transfer (void) raw: SubmitTransactionResponse | GetSuccessfulTransactionResponse; } ``` `result.hash` works for both paths. Classic transfers expose Horizon fields under `result.raw`; token transfers expose the finalized Soroban RPC transaction there. ## Errors `transfer` rejects with `BLUX:`-prefixed messages so failures are actionable: | Message | Cause | |---|---| | `BLUX: transfer must be called after createConfig` | Called before `createConfig` ran. | | `BLUX: No account is logged in.` | No connected user to act as the source. | | `BLUX: transfer requires a "to" address.` | `to` was missing. | | `BLUX: transfer requires an "amount".` | `amount` was missing. | | `BLUX: transfer "amount" must be greater than zero.` | `amount` was zero or negative. | | `BLUX: "token" must be a contract id (C...).` | `token` wasn't a valid contract id. | | `BLUX: token transfers use integer base units; "amount" cannot have decimals.` | A decimal/exponential `amount` on the token path. | | `BLUX: "amount" could not be represented precisely; pass it as a string (e.g. "0.0000001").` | A tiny/huge `amount` rendered in exponential form on the classic path — pass it as a string. | | `BLUX: The logged-in account is not active on this network yet.` | The source account isn't funded on this network. | | `BLUX: The destination has no trustline for . Pass { claimable: true } to send it as a claimable balance.` | Recipient exists but doesn't trust the issued asset. | | `BLUX: The destination account does not exist, so it can only be created with XLM. Send XLM, or pass { claimable: true } to send as a claimable balance.` | Sending an issued asset to an account that doesn't exist yet. | | `BLUX: Invalid asset "…". Use "xlm", "native", or "CODE:ISSUER".` | Malformed `asset` string. | | `BLUX: Could not resolve federated address "…": …` | Federation lookup for `to` failed. | Errors raised while signing and submitting (`BLUX: User is not authenticated.`, network busy, on-chain failure, …) propagate unchanged from [`sendTransaction`](/javascript/usage/send-transaction#errors). Need lower-level control — a custom operation, batched operations, or your own fee strategy? Build the transaction yourself and submit it with [`sendTransaction`](/javascript/usage/send-transaction). `transfer` is the convenience layer for the common "send X to Y" case. --- # Write Contract URL: https://docs.blux.cc/javascript/core/writeContract Invoke a Soroban smart contract method that changes on-chain state. `writeContract` is a **Soroban** helper that invokes a state-changing contract method. It builds the call, simulates it to gather the resource fees, footprint, and authorization, assembles the final transaction, and then submits it through Blux's signing flow — so the connected user signs and the change lands on-chain. Unlike [`readContracts`](/javascript/core/readContracts), this **requires a connected user** (the source account) and produces a real, fee-paying transaction. ## Type ```ts type IContractCall = { address: string; // C… contract ID, SEP-2 address, or .xlm name fn: string; // function name to invoke args: unknown[]; // native values in the function's positional order }; type WriteContractsOptions = { network?: string; // Omit to use the active network }; const writeContract: ( call: IContractCall, options?: WriteContractsOptions, ) => Promise>; ``` ## Native contract arguments Pass ordinary JavaScript values in the order declared by the contract function. Blux reads the deployed contract spec and converts them to the required Soroban types; you do not need to wrap arguments with `ToScVal`. ```ts args: [ "GA...FROM", // Address "bob.xlm", // Address; resolved before encoding "1000000000", // i128 ] ``` Use a safe `number`, `bigint`, or decimal `string` for integers. Decimal strings and `bigint` values avoid precision loss for wide types such as `i128`. Arrays, maps, bytes, and contract-defined values must match the shape declared in the contract spec. Both the call's contract `address` and every ABI-declared `Address` argument can be a `.xlm` name or SEP-2 federation address. Nested address values are resolved inside options, vectors, tuples, maps, structs, and unions. See [address resolution](/javascript/core/address-resolution). Pre-encoded `xdr.ScVal` arguments remain supported for backward compatibility, but they are optional. ## Usage Call a token's `transfer` method. Blux prompts the user to sign before the transaction is submitted: ```ts const result = await core.writeContract({ address: "token.xlm", fn: "transfer", args: [ "GA...FROM", // from: Address "bob.xlm", // to: Address "1000000000", // amount: i128 ], }); console.log(result.hash); console.log(await result.returnValue()); ``` ## Return type The ABI is inspected at runtime, so TypeScript cannot derive the result from runtime `address`, `fn`, and `network` values. Supply the decoded function return type as the generic: ```ts const result = await core.writeContract({ address: TOKEN, fn: "mint", args: ["alice.xlm", "10000000"], }); const minted = await result.returnValue(); // bigint | null ``` `returnValue()` includes `null` because void Soroban functions and classic transactions have no decoded value. If you omit the generic, the type is `unknown | null`. `writeContract` must be called after `createConfig` and while a user is connected — the connected account is used as the transaction source. Wrap the call in a `try/catch` to handle simulation failures and user rejection. --- # Usage URL: https://docs.blux.cc/javascript/usage Everything you can do with the Blux core SDK once a user is connected. The `blux` object is your main interface for interacting with connected users. Use its built-in modals, or build your own authentication UI with the [white-label login methods](/javascript/usage/white-label-login). Once a user is authenticated, you can open the profile modal, submit transactions, sign messages, and more. ```ts ``` --- {getPageTreePeers(source.getPageTree(), '/javascript/usage').map((peer) => ( {peer.description} ))} --- # Fund Me URL: https://docs.blux.cc/javascript/usage/fund-me Let users on-ramp fiat into crypto straight to their Stellar wallet. The `blux.fundMe()` method opens the **Fund Me** modal — a built-in on-ramp flow that lets users buy crypto with fiat and have it delivered directly to their connected Stellar wallet. The modal lists supported on-ramp providers (such as **MoonPay**) so users can top up without leaving your dApp. ## Usage ```ts blux.fundMe(); ``` `fundMe()` takes no arguments — it opens the modal for the currently connected user. The user must be authenticated before opening the Fund Me modal, since funds are delivered to their connected wallet. Gate the call behind `blux.isAuthenticated`. --- # Login URL: https://docs.blux.cc/javascript/usage/login Authenticate users in your Stellar dApp with Blux's built-in login flow. The `blux.login()` method opens the Blux authentication modal, giving users a seamless way to connect with email, phone, social accounts, passkeys, or an existing wallet. Login modal ## Usage ```tsx blux.login(); // blux.logout(); console.log(blux.user); console.log(blux.isReady); console.log(blux.isAuthenticated); ``` Keep your Connect button disabled until `blux.isReady` is `true`. This ensures all wallets have reported availability before the modal opens. --- # Profile URL: https://docs.blux.cc/javascript/usage/profile Open the Blux profile modal for connected users to manage their account. The `blux.profile()` method opens a full account management modal — so you don't need to build common wallet UI yourself. Profile modal ## Usage ```tsx blux.profile(); ``` ## Pages **Receive** — Displays a QR code and the user's public Stellar address with a copy button. **Balances** — Lists all assets, NFTs, and custom tokens. Each entry shows the icon, code, name, issuer, and balance. **Send** — A form to send assets to another address. Includes fields for recipient, asset, amount, and an optional memo. Validates balance sufficiency, trustlines, and destination before submitting. Shows a confirmation screen with the transaction hash and explorer link on success. **Swap** — Swap between assets with a live price quote, slippage tolerance, route details, minimum received amount, and exchange rate. Includes a preview step before submission and a confirmation screen after. **Activity** — A list of recent transactions showing date, type (send/receive/swap), and amount. Each entry links to the full transaction in the explorer. **Logout** — Logs the user out and closes the modal. --- # Send Transaction URL: https://docs.blux.cc/javascript/usage/send-transaction Sign and submit a transaction to the Stellar network using Blux. The `blux.sendTransaction()` method **signs** a transaction with the connected wallet and **submits** it to the network. By default Blux shows a confirmation modal displaying the transaction details, estimated fee, and the submitting account before the user approves. If you only want to sign a transaction without submitting it, use [`signTransaction`](/javascript/usage/sign-transaction) instead. Send transaction modal ## Auto-detected transaction type `sendTransaction` inspects the transaction and handles each type correctly — you don't choose the path: - **Classic transactions** (payments, trustlines, offers, account operations, path payments, …) are submitted to Horizon and confirmed immediately. - **Soroban transactions** (smart-contract calls — `invokeHostFunction`, `extendFootprintTtl`, `restoreFootprint`) are submitted via Soroban RPC and then polled until the network finalizes them (typically a few seconds). The value the contract function returned is decoded and made available on the result. Because of this there is no separate `waitForTransaction`: classic transactions don't need waiting, and Soroban transactions are waited on for you. ## Type ```typescript type IOptions = { // Network passphrase to sign/submit against. Defaults to the active network. // Use the `networks` map, e.g. networks.testnet / networks.mainnet. network?: string; }; const sendTransaction: ( xdr: string, options?: IOptions, ) => Promise; ``` | Parameter | Type | Description | |---|---|---| | `xdr` | `string` | Base64-encoded XDR string of the transaction | | `options.network` | `string` | Network to submit on — omit to use the active network | ### Return value ```typescript interface ISubmittedTransaction { // The transaction hash. hash: string; // Resolves to the value the invoked contract function returned, decoded to a // native JS value. Resolves to `null` for classic transactions and for // Soroban calls whose function returns nothing (void). Always a promise. returnValue: () => Promise; // The underlying response object, for advanced use: // - classic: Horizon SubmitTransactionResponse // - soroban: the finalized Soroban RPC transaction (GetSuccessfulTransactionResponse) raw: SubmitTransactionResponse | GetSuccessfulTransactionResponse; } ``` **Migration note:** the resolved value is now the `ISubmittedTransaction` envelope. `result.hash` works for both types as before, but classic callers who previously read Horizon fields directly off the result (e.g. `result.ledger`, `result.successful`) should now read them from `result.raw`. ## Usage — classic payment ```typescript const { TransactionBuilder, Operation, Asset, BASE_FEE } = StellarSdk; // 1. Build an unsigned transaction (a 10 XLM payment). const source = await getAccount({}); // the logged-in account, on the active network if (!source) throw new Error("Account not found"); const tx = new TransactionBuilder(source, { fee: BASE_FEE, networkPassphrase: networks.testnet, }) .addOperation( Operation.payment({ destination: "GDESTINATION...ADDRESS", asset: Asset.native(), amount: "10", }), ) .setTimeout(180) .build(); // 2. Sign + submit via the connected wallet. const result = await blux.sendTransaction(tx.toXDR(), { network: networks.testnet, }); console.log(result.hash); // e.g. "a1b2c3..." console.log(await result.returnValue()); // null — classic txs have no return value console.log(result.raw.successful); // Horizon fields live under `.raw` ``` ## Usage — Soroban contract call The easiest way to call a contract is [`writeContract`](/javascript/core/writeContract), which builds, simulates, assembles, signs, submits, and waits — returning the same `ISubmittedTransaction`: ```typescript const result = await writeContract( { address: "CCONTRACT...ADDRESS", fn: "increment", args: [5], }, { network: networks.testnet }, ); console.log(result.hash); const newCount = await result.returnValue(); // the contract's return value, decoded (e.g. 5) ``` If you build and assemble the contract transaction yourself, `sendTransaction` still detects it's a Soroban transaction, submits via RPC, waits for finalization, and exposes the return value: ```typescript const result = await blux.sendTransaction(assembledContractXdr, { network: networks.testnet, }); const value = await result.returnValue(); ``` ## Errors `sendTransaction` rejects with `BLUX:`-prefixed messages: | Message | Cause | |---|---| | `BLUX: User is not authenticated.` | No user is logged in. | | `BLUX: Blux modal is open elsewhere.` | Another Blux flow is already open. | | `BLUX: Invalid XDR` | The XDR can't be parsed for the given network. | | `BLUX: Could not find the connected wallet.` | The connected wallet couldn't be resolved. | | `BLUX: Failed to submit transaction: …` | RPC rejected the transaction (`ERROR`). | | `BLUX: The network is busy, please resubmit the transaction.` | RPC returned `TRY_AGAIN_LATER`. | | `BLUX: Transaction failed on-chain.` | Submitted but failed during execution. | | `BLUX: Timed out waiting for transaction to finalize.` | Not finalized within ~30s. | To skip the confirmation modal and handle your own confirmation UI, set `showWalletUIs: false` in `createConfig`. Signing and submission then happen headlessly — the resolved value is identical either way. --- # Sign Auth Entry URL: https://docs.blux.cc/javascript/usage/sign-auth-entry Sign a Soroban authorization entry with the connected wallet using Blux. The `blux.signAuthEntry()` method asks the connected wallet to sign a single **Soroban authorization entry**. It resolves to the signed entry as a base-64 XDR string. This is a low-level building block for advanced Soroban flows — multi-party authorization, signing on behalf of a contract account, or assembling `invokeHostFunction` authorization yourself before submitting. For ordinary contract calls you don't need this: [`writeContract`](/javascript/core/writeContract) and [`sendTransaction`](/javascript/usage/send-transaction) handle authorization for you. ## Type ```typescript type IOptions = { // Network passphrase to sign against. Defaults to the active network. // Use the `networks` map, e.g. networks.testnet / networks.mainnet. network: string; }; const signAuthEntry: ( authEntry: string, options?: IOptions, ) => Promise; // the signed auth entry (base-64 XDR) ``` | Parameter | Type | Description | |---|---|---| | `authEntry` | `string` | Base64-encoded authorization entry (`HashIdPreimage`) to sign | | `options.network` | `string` | Network to sign against — omit to use the active network | ## Usage ```typescript const signEntry = async (authEntry: string) => { try { const signedAuthEntry = await blux.signAuthEntry(authEntry); // `signedAuthEntry` is the signed entry as a base-64 XDR string. // Attach it to your Soroban operation's authorization before submitting. console.log(signedAuthEntry); } catch (error) { console.error("Something went wrong!"); console.log(error); } }; ``` Sign against a specific network: ```typescript const signedAuthEntry = await blux.signAuthEntry(authEntry, { network: networks.testnet, }); ``` ## Errors `signAuthEntry` rejects (or throws) with `BLUX:`-prefixed messages: | Message | Cause | |---|---| | `BLUX: User is not authenticated.` | No user is logged in. | | `BLUX: Blux modal is open elsewhere.` | Another Blux flow is already open. | | `BLUX: Could not find the connected wallet.` | The connected wallet couldn't be resolved. | | `BLUX: Wallet does not support signAuthEntry.` | The connected wallet has no `signAuthEntry` capability. | Not every wallet supports signing auth entries. When the connected wallet lacks the capability, the call rejects with `BLUX: Wallet does not support signAuthEntry.` — handle this in your `try/catch`. To skip the confirmation modal and handle your own confirmation UI, set `showWalletUIs: false` in `createConfig`. The signed entry returned is identical either way. --- # Sign Message URL: https://docs.blux.cc/javascript/usage/sign-message Request a signed message from the connected user using Blux. The `blux.signMessage()` method prompts the connected user to sign an arbitrary message. Blux shows a confirmation modal displaying the message content and the signing account before the user approves. Sign message modal ## Type ```typescript type IOptions = { network?: string; }; const signMessage: (message: string, options?: IOptions); ``` | Parameter | Type | Description | |---|---|---| | `message` | `string` | The message string to sign | | `options.network` | `string` | Network to use — omit to use the active network | ## Usage ```typescript const sign = async () => { try { const result = await blux.signMessage("Hello"); console.log(result); } catch (error) { console.error("Something went wrong!"); console.log(error); } }; ``` To skip the confirmation modal and handle your own confirmation UI, set `showWalletUIs: false` in `createConfig`. --- # Sign Transaction URL: https://docs.blux.cc/javascript/usage/sign-transaction Sign a transaction with the connected wallet without submitting it. The `blux.signTransaction()` method signs a transaction with the connected wallet but **does not submit it**. It resolves to the signed transaction envelope (a base-64 XDR string). Use this when you want to submit it yourself, store it, send it to a backend, or pass it to a co-signer for multi-signature. If you want Blux to sign **and** submit in one step, use [`sendTransaction`](/javascript/usage/send-transaction) instead. | Method | Signs? | Submits to network? | Returns | |---|---|---|---| | `blux.sendTransaction(xdr, options?)` | ✅ | ✅ | `Promise` | | `blux.signTransaction(xdr, options?)` | ✅ | ❌ | `Promise` (signed XDR) | ## Type ```typescript type IOptions = { // Network passphrase to sign against. Defaults to the active network. // Use the `networks` map, e.g. networks.testnet / networks.mainnet. network?: string; }; const signTransaction: ( xdr: string, options?: IOptions, ) => Promise; // the signed XDR ``` | Parameter | Type | Description | |---|---|---| | `xdr` | `string` | Base64-encoded XDR string of the transaction | | `options.network` | `string` | Network to sign against — omit to use the active network | ## Usage — sign now, submit later ```typescript // Sign WITHOUT submitting. const signedXdr: string = await blux.signTransaction(unsignedXdr, { network: networks.testnet, }); // `signedXdr` is the signed envelope — it has NOT been sent to the network. // Submit it yourself whenever you want, e.g. via the Stellar SDK: const horizon = new StellarSdk.Horizon.Server("https://horizon-testnet.stellar.org"); const tx = StellarSdk.TransactionBuilder.fromXDR(signedXdr, networks.testnet); const response = await horizon.submitTransaction(tx); console.log(response.hash); ``` ## Errors `signTransaction` rejects with `BLUX:`-prefixed messages: | Message | Cause | |---|---| | `BLUX: User is not authenticated.` | No user is logged in. | | `BLUX: Blux modal is open elsewhere.` | Another Blux flow is already open. | | `BLUX: Invalid XDR` | The XDR can't be parsed for the given network. | | `BLUX: Could not find the connected wallet.` | The connected wallet couldn't be resolved. | To skip the confirmation modal and handle your own confirmation UI, set `showWalletUIs: false` in `createConfig`. The signed XDR returned is identical either way. --- # White-label Login URL: https://docs.blux.cc/javascript/usage/white-label-login Build your own authentication UI with the headless login methods in @bluxcc/core. White-label login lets you keep your own markup, styling, copy, and user flow while Blux handles authentication, account provisioning, and session state. Instead of opening the complete `blux.login()` modal, call the method for the login option the user selected. ## Available methods | Login option | Core API | Opens the full Blux login modal? | |---|---|---| | Email code | `blux.loginEmail.sendCode()` and `.loginWithCode()` | No | | SMS code | `blux.loginSms.sendCode()` and `.loginWithCode()` | No | | Social account | `blux.loginOAuth(provider)` | No; opens the provider popup | | Passkey | `blux.loginPasskey()` | No; opens the browser's passkey prompt | | Specific wallet | `blux.loginWallet(walletName)` | No; opens the wallet prompt | | Wallet picker | `blux.loginWallet()` | Yes; opens Blux's wallet-only picker | Every successful login method resolves to the authenticated `IUser` and updates `blux.user` and `blux.isAuthenticated`. The exported method names are `loginEmail`, `loginSms`, `loginOAuth`, `loginPasskey`, and `loginWallet`. Email and SMS use `loginWithCode` for the verification step. ## Configure the allowed methods Initialize Blux once, and include every method your UI can start in `loginMethods`: ```ts createConfig({ appId: "your-app-id", appName: "My App", networks: [core.networks.mainnet], loginMethods: [ "email", "sms", "google", "passkey", "wallet", ], }); ``` A headless method rejects if it is missing from `loginMethods`. Social providers must also be enabled for the same app in the [Blux Dashboard](/dashboard/socials). SMS login requires a paid Blux plan. ## Email login Email login has two steps: send a one-time code, then verify it. ```ts const email = "user@example.com"; await blux.loginEmail.sendCode(email); // Ask the user for the code sent to their inbox. const user = await blux.loginEmail.loginWithCode(email, "123456"); console.log(user.address); ``` The callable form returns the same pair of methods if it fits your component better: ```ts const { sendCode, loginWithCode } = blux.loginEmail(); await sendCode("user@example.com"); await loginWithCode("user@example.com", "123456"); ``` ## SMS login SMS follows the same two-step flow. Pass phone numbers in international [E.164](https://www.itu.int/rec/T-REC-E.164) format. ```ts const phone = "+15555555555"; await blux.loginSms.sendCode(phone); const user = await blux.loginSms.loginWithCode(phone, "123456"); ``` Adding `"sms"` to `loginMethods` is not enough on its own. The app must be on a paid plan; otherwise SMS calls reject and SMS is not offered by the built-in login modal. ## Social login Call `loginOAuth` directly from the user's click. The SDK opens the provider window immediately, completes the callback through Blux, and resolves with the authenticated user. ```ts googleButton.addEventListener("click", () => { void blux.loginOAuth("google") .then((user) => { console.log("Signed in as", user.address); }) .catch((error) => { console.error(error); }); }); ``` Do not wait for another asynchronous operation before calling `loginOAuth`; browsers may otherwise block the popup. The provider must appear in `loginMethods` and be enabled in the dashboard. See [Social Login](/dashboard/socials) for every provider key and the credential setup. ### Telegram Telegram does not use the OAuth popup. In a Telegram Mini App, Blux reads the available Web App init data when Mini App login is enabled. For a custom Telegram Login Widget, pass the signed widget payload: ```ts await blux.loginOAuth("telegram", { telegramUser: widgetUser, }); ``` If you want Blux to render the configured Telegram widget, use `blux.login()` instead. ## Passkey login `loginPasskey` registers a passkey on the first visit and authenticates with it on later visits. ```ts passkeyButton.addEventListener("click", () => { void blux.loginPasskey().then((user) => { console.log(user.address); }); }); ``` Call it directly from a click or another user gesture so the browser can show its WebAuthn prompt. ## Wallet login Pass a wallet name to skip Blux's general login modal and open that wallet directly: ```ts freighterButton.addEventListener("click", () => { void blux.loginWallet("freighter").then((user) => { console.log(user.address); }); }); ``` The wallet must be installed and available in the current browser. Call `blux.loginWallet()` without a name when you want Blux's wallet-only picker instead: ```ts await blux.loginWallet(); ``` WalletConnect is the one named-wallet exception: it still opens Blux's QR screen because there is no browser extension prompt to open. ## Readiness, errors, and the hosted fallback Keep buttons for OAuth, passkeys, and named wallets disabled until `blux.isReady` is `true`. Wrap calls in `try/catch` and show the returned `Error.message` in your own UI. ```ts async function signInWithWallet() { if (!blux.isReady) return; try { const user = await blux.loginWallet("freighter"); renderAccount(user); } catch (error) { renderError(error instanceof Error ? error.message : "Login failed"); } } ``` You can mix white-label and hosted flows. For example, render custom Google and email buttons, then offer `blux.loginWallet()` for wallet selection or `blux.login()` as an all-method fallback. `showWalletUIs` controls Blux's signing and transaction confirmation screens. It does not turn white-label login on or off; choosing a headless login method does that. --- # React URL: https://docs.blux.cc/react Integrate Blux into your React or Next.js application. The `@bluxcc/react` package provides a React-first integration with built-in hooks and components, compatible with any React-based framework including Next.js, Vite, and Create React App. **Requirements:** React 17 or higher. ## Installation Install the Blux React SDK using your package manager of choice: ```bash npm install @bluxcc/react ``` ```bash pnpm add @bluxcc/react ``` ```bash yarn add @bluxcc/react ``` ## Setup Wrap your app with `BluxProvider` to give any component access to the Blux SDK. Place it as close to the root of your application as possible. The only required options are `appId` and `networks`. ```tsx "use client"; import { networks, BluxProvider } from "@bluxcc/react"; export default function Providers({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` ```tsx import React from "react"; import ReactDOM from "react-dom/client"; import { networks, BluxProvider } from "@bluxcc/react"; import App from "./App"; const root = ReactDOM.createRoot(document.getElementById("root")!); root.render( , ); ``` ## Use it Call `useBlux` from any child of `BluxProvider` to open the built-in modals. ```tsx function ConnectButton() { const { login, isAuthenticated } = useBlux(); return ( ); } ``` {getPageTreePeers(source.getPageTree(), '/react').map((peer) => ( {peer.description} ))} --- # Hooks URL: https://docs.blux.cc/react/hooks React hooks for querying Stellar network data and managing wallet state. Blux provides hooks for **white-label authentication**, **managing wallet state** (network and transactions), and **querying Stellar network data** (accounts, balances, trades, and more). Use `useLoginEmail`, `useLoginSms`, `useLoginOAuth`, `useLoginPasskey`, and `useLoginWallet` to build your own login screen. See the [white-label login guide](/react/usage/white-label-login) for complete examples. All data-fetching hooks are built on [TanStack Query](https://tanstack.com/query/v5) and support the full suite of query options including caching, background refetching, pagination, and dependent queries. Hooks backed by a core address field accept the same `G…`, `M…`, `C…`, SEP-2, and `.xlm` values as the corresponding core function. Invalid and unregistered names surface through the query or mutation's `error`. See [address resolution and `.xlm` names](/javascript/core/address-resolution). --- {getPageTreePeers(source.getPageTree(), '/react/hooks').map((peer) => ( {peer.description} ))} --- # useAccount URL: https://docs.blux.cc/react/hooks/use-account Fetch details of a Stellar account in your React app using the Blux SDK. The `useAccount` hook returns details for a Stellar account. By default it fetches the connected account on the active network, but you can pass an explicit address and network to fetch any account. The explicit `address` accepts `G…`, `M…`, SEP-2 federation, or `.xlm`; failed resolution is exposed as the query `error`. See [address resolution](/javascript/core/address-resolution). ## Import ```tsx ``` ## Usage Called with no arguments, it returns the connected account on the current network: ```tsx function App() { const { data } = useAccount(); } ``` ```tsx root.render( ); ``` You can combine it with `useBlux` to fetch account details only when the user is authenticated: ```tsx function App() { const { user, isAuthenticated } = useBlux(); const { data } = useAccount( { address: user?.address }, { enabled: isAuthenticated } ); } ``` ```tsx root.render( ); ``` You can also pass TanStack Query options as a second argument to customize caching and refetch behavior: ```tsx function App() { const { data } = useAccount( { address: "GABK...2N7M", network: networks.mainnet }, { retry: 3, staleTime: 60000 } ); } ``` ```tsx root.render( ); ``` Always pass core parameters first, then TanStack Query options. The hook relies on this order to work correctly. ## Parameters ### `address` `string | undefined` The Stellar account ID to fetch. Omit to use the currently connected account. ### `network` `string | undefined` The network to query. Import `networks` from `@bluxcc/react` to select one. ## Query Options These are passed as the second argument and map directly to TanStack Query options. | Option | Type | Default | Description | |---|---|---|---| | `enabled` | `boolean` | `true` | Set to `false` to disable automatic fetching | | `staleTime` | `number \| Infinity` | `0` | Time in ms before data is considered stale | | `gcTime` | `number \| Infinity` | `300000` | Time in ms before inactive cache data is garbage collected | | `retry` | `boolean \| number` | `3` | How many times to retry on failure | | `retryDelay` | `number \| function` | — | Delay in ms between retry attempts | | `refetchInterval` | `number \| false \| function` | — | Continuously refetch at this interval in ms | | `refetchOnMount` | `boolean \| 'always'` | `true` | Refetch on component mount if data is stale | | `refetchOnWindowFocus` | `boolean \| 'always'` | `true` | Refetch when the window regains focus | | `refetchOnReconnect` | `boolean \| 'always'` | `true` | Refetch when network reconnects | | `refetchIntervalInBackground` | `boolean` | — | Keep refetching even when tab is in background | | `placeholderData` | `GetAccountResult \| function` | — | Placeholder data shown while query is pending (not persisted to cache) | | `initialData` | `GetAccountResult \| function` | — | Initial data for the cache (persisted) | | `initialDataUpdatedAt` | `number \| function` | — | Timestamp of when `initialData` was last updated | | `select` | `function` | — | Transform or select a subset of the returned data | | `notifyOnChangeProps` | `string[] \| 'all'` | — | Limit re-renders to specific property changes | | `structuralSharing` | `boolean \| function` | `true` | Retain references from old data for performance | | `networkMode` | `'online' \| 'always' \| 'offlineFirst'` | `'online'` | Controls when queries can run relative to network status | | `meta` | `Record` | — | Attach arbitrary metadata to the query cache entry | | `queryClient` | `QueryClient` | — | Use a custom QueryClient instead of the nearest context one | ## Return Type ### `data` `GetAccountResult | undefined` ```tsx type GetAccountResult = Horizon.AccountResponse | null; ``` ### Status Booleans | Property | Type | Description | |---|---|---| | `isPending` | `boolean` | No cached data and no completed fetch yet | | `isSuccess` | `boolean` | Query resolved successfully | | `isError` | `boolean` | Query failed | | `isLoading` | `boolean` | First fetch in-flight (`isFetching && isPending`) | | `isFetching` | `boolean` | Query function is currently executing | | `isRefetching` | `boolean` | Background refetch in progress | | `isFetched` | `boolean` | Query has been fetched at least once | | `isFetchedAfterMount` | `boolean` | Query fetched after component mounted | | `isStale` | `boolean` | Cached data is stale or older than `staleTime` | | `isPlaceholderData` | `boolean` | Currently showing placeholder data | | `isLoadingError` | `boolean` | Failed on the first fetch | | `isRefetchError` | `boolean` | Failed during a background refetch | | `isPaused` | `boolean` | Query wanted to fetch but was paused | ### Other Returns | Property | Type | Description | |---|---|---| | `status` | `'pending' \| 'success' \| 'error'` | Current query status | | `fetchStatus` | `'fetching' \| 'idle' \| 'paused'` | Current fetch status | | `error` | `null \| Error` | Error object if the query failed | | `dataUpdatedAt` | `number` | Timestamp of last successful fetch | | `errorUpdatedAt` | `number` | Timestamp of last error | | `errorUpdateCount` | `number` | Total number of errors | | `failureCount` | `number` | Failures since last success | | `failureReason` | `null \| Error` | Reason for last retry failure | | `refetch` | `function` | Manually trigger a refetch | --- # useAccounts URL: https://docs.blux.cc/react/hooks/use-accounts Fetch a filtered list of Stellar accounts in your React app using the Blux SDK. The `useAccounts` hook returns a paginated list of Stellar accounts matching the given filters. At least one filter — `forSigner`, `forAsset`, `sponsor`, or `forLiquidityPool` — must be provided. `forSigner` and `sponsor` accept `G…`, `M…`, SEP-2 federation, or `.xlm` names. See [address resolution](/javascript/core/address-resolution). ## Import ```tsx ``` ## Usage Filter by asset to fetch all accounts holding a specific token: ```tsx function App() { const { data } = useAccounts({ forAsset: new Asset("USDC", "GA5Z...KZVN") }); } ``` ```tsx root.render( ); ``` Combine with `useBlux` to fetch accounts only when the user is authenticated: ```tsx function App() { const { user, isAuthenticated } = useBlux(); const { data } = useAccounts( { forSigner: user.address }, { enabled: isAuthenticated } ); } ``` ```tsx root.render( ); ``` Pass TanStack Query options as a second argument to customize caching and refetch behavior: ```tsx function App() { const { data } = useAccounts( { forAsset: new Asset("USDC", "GA5Z...KZVN") }, { retry: 3, staleTime: 60000 } ); } ``` ```tsx root.render( ); ``` Always pass core parameters first, then TanStack Query options. The hook relies on this order to work correctly. ## Parameters ### `forSigner` `string | undefined` Filter accounts that list the given address as a signer. ### `forAsset` `Asset | undefined` Filter accounts that hold the specified asset. Import `Asset` from `@bluxcc/react`. ### `sponsor` `string | undefined` Filter accounts sponsored by the specified account ID. ### `forLiquidityPool` `string | undefined` Filter accounts related to a specific liquidity pool ID. ### `cursor` `string | undefined` Pagination cursor for fetching the next or previous page. ### `limit` `number | undefined` Number of records to return per page. ### `network` `string | undefined` The network to query. Omit to use the active network. ### `order` `'asc' | 'desc' | undefined` Sort order for the results. ## Query Options | Option | Type | Default | Description | |---|---|---|---| | `enabled` | `boolean` | `true` | Set to `false` to disable automatic fetching | | `staleTime` | `number \| Infinity` | `0` | Time in ms before data is considered stale | | `gcTime` | `number \| Infinity` | `300000` | Time in ms before inactive cache data is garbage collected | | `retry` | `boolean \| number` | `3` | How many times to retry on failure | | `retryDelay` | `number \| function` | — | Delay in ms between retry attempts | | `refetchInterval` | `number \| false \| function` | — | Continuously refetch at this interval in ms | | `refetchOnMount` | `boolean \| 'always'` | `true` | Refetch on component mount if data is stale | | `refetchOnWindowFocus` | `boolean \| 'always'` | `true` | Refetch when the window regains focus | | `refetchOnReconnect` | `boolean \| 'always'` | `true` | Refetch when network reconnects | | `refetchIntervalInBackground` | `boolean` | — | Keep refetching even when tab is in background | | `placeholderData` | `GetAccountsResult \| function` | — | Placeholder data shown while query is pending (not persisted to cache) | | `initialData` | `GetAccountsResult \| function` | — | Initial data for the cache (persisted) | | `initialDataUpdatedAt` | `number \| function` | — | Timestamp of when `initialData` was last updated | | `select` | `function` | — | Transform or select a subset of the returned data | | `notifyOnChangeProps` | `string[] \| 'all'` | — | Limit re-renders to specific property changes | | `structuralSharing` | `boolean \| function` | `true` | Retain references from old data for performance | | `networkMode` | `'online' \| 'always' \| 'offlineFirst'` | `'online'` | Controls when queries can run relative to network status | | `meta` | `Record` | — | Attach arbitrary metadata to the query cache entry | | `queryClient` | `QueryClient` | — | Use a custom QueryClient instead of the nearest context one | ## Return Type ### `data` `GetAccountsResult | undefined` ```tsx type GetAccountsResult = { builder: AccountCallBuilder; // .next() and .prev() for pagination response: Horizon.ServerApi.CollectionPage; }; ``` ### Status Booleans | Property | Type | Description | |---|---|---| | `isPending` | `boolean` | No cached data and no completed fetch yet | | `isSuccess` | `boolean` | Query resolved successfully | | `isError` | `boolean` | Query failed | | `isLoading` | `boolean` | First fetch in-flight (`isFetching && isPending`) | | `isFetching` | `boolean` | Query function is currently executing | | `isRefetching` | `boolean` | Background refetch in progress | | `isFetched` | `boolean` | Query has been fetched at least once | | `isFetchedAfterMount` | `boolean` | Query fetched after component mounted | | `isStale` | `boolean` | Cached data is stale or older than `staleTime` | | `isPlaceholderData` | `boolean` | Currently showing placeholder data | | `isLoadingError` | `boolean` | Failed on the first fetch | | `isRefetchError` | `boolean` | Failed during a background refetch | | `isPaused` | `boolean` | Query wanted to fetch but was paused | ### Other Returns | Property | Type | Description | |---|---|---| | `status` | `'pending' \| 'success' \| 'error'` | Current query status | | `fetchStatus` | `'fetching' \| 'idle' \| 'paused'` | Current fetch status | | `error` | `null \| Error` | Error object if the query failed | | `dataUpdatedAt` | `number` | Timestamp of last successful fetch | | `errorUpdatedAt` | `number` | Timestamp of last error | | `errorUpdateCount` | `number` | Total number of errors | | `failureCount` | `number` | Failures since last success | | `failureReason` | `null \| Error` | Reason for last retry failure | | `refetch` | `function` | Manually trigger a refetch | --- # useAssets URL: https://docs.blux.cc/react/hooks/use-assets Fetch a paginated list of Stellar assets in your React app using the Blux SDK. The `useAssets` hook returns a paginated list of Stellar assets. All parameters are optional — called with no arguments it returns the latest assets from the network. `forIssuer` accepts a `G…`/`M…` account, SEP-2 federation address, or `.xlm` name. See [address resolution](/javascript/core/address-resolution). ## Import ```tsx ``` ## Usage Called with no arguments: ```tsx function App() { const { data } = useAssets(); } ``` ```tsx root.render( ); ``` With filters and TanStack Query options: ```tsx function App() { const { data, isStale } = useAssets( { forCode: "USDC" }, { retry: 2, staleTime: 60000 } ); } ``` ```tsx root.render( ); ``` Always pass core parameters first, then TanStack Query options. The hook relies on this order to work correctly. ## Parameters ### `forCode` `string | undefined` Filter assets by asset code (e.g. `"USDC"`). ### `forIssuer` `string | undefined` Filter assets by issuer account ID. ### `cursor` `string | undefined` Pagination cursor for fetching the next or previous page. ### `limit` `number | undefined` Number of records to return per page. ### `network` `string | undefined` The network to query. Omit to use the active network. ### `order` `'asc' | 'desc' | undefined` Sort order for the results. ## Query Options | Option | Type | Default | Description | |---|---|---|---| | `enabled` | `boolean` | `true` | Set to `false` to disable automatic fetching | | `staleTime` | `number \| Infinity` | `0` | Time in ms before data is considered stale | | `gcTime` | `number \| Infinity` | `300000` | Time in ms before inactive cache data is garbage collected | | `retry` | `boolean \| number` | `3` | How many times to retry on failure | | `retryDelay` | `number \| function` | — | Delay in ms between retry attempts | | `refetchInterval` | `number \| false \| function` | — | Continuously refetch at this interval in ms | | `refetchOnMount` | `boolean \| 'always'` | `true` | Refetch on component mount if data is stale | | `refetchOnWindowFocus` | `boolean \| 'always'` | `true` | Refetch when the window regains focus | | `refetchOnReconnect` | `boolean \| 'always'` | `true` | Refetch when network reconnects | | `refetchIntervalInBackground` | `boolean` | — | Keep refetching even when tab is in background | | `placeholderData` | `GetAssetsResult \| function` | — | Placeholder data shown while query is pending (not persisted to cache) | | `initialData` | `GetAssetsResult \| function` | — | Initial data for the cache (persisted) | | `initialDataUpdatedAt` | `number \| function` | — | Timestamp of when `initialData` was last updated | | `select` | `function` | — | Transform or select a subset of the returned data | | `notifyOnChangeProps` | `string[] \| 'all'` | — | Limit re-renders to specific property changes | | `structuralSharing` | `boolean \| function` | `true` | Retain references from old data for performance | | `networkMode` | `'online' \| 'always' \| 'offlineFirst'` | `'online'` | Controls when queries can run relative to network status | | `meta` | `Record` | — | Attach arbitrary metadata to the query cache entry | | `queryClient` | `QueryClient` | — | Use a custom QueryClient instead of the nearest context one | ## Return Type ### `data` `GetAssetsResult | undefined` ```tsx type GetAssetsResult = { builder: AssetsCallBuilder; // .next() and .prev() for pagination response: Horizon.ServerApi.CollectionPage; }; ``` ### Status Booleans | Property | Type | Description | |---|---|---| | `isPending` | `boolean` | No cached data and no completed fetch yet | | `isSuccess` | `boolean` | Query resolved successfully | | `isError` | `boolean` | Query failed | | `isLoading` | `boolean` | First fetch in-flight (`isFetching && isPending`) | | `isFetching` | `boolean` | Query function is currently executing | | `isRefetching` | `boolean` | Background refetch in progress | | `isFetched` | `boolean` | Query has been fetched at least once | | `isFetchedAfterMount` | `boolean` | Query fetched after component mounted | | `isStale` | `boolean` | Cached data is stale or older than `staleTime` | | `isPlaceholderData` | `boolean` | Currently showing placeholder data | | `isLoadingError` | `boolean` | Failed on the first fetch | | `isRefetchError` | `boolean` | Failed during a background refetch | | `isPaused` | `boolean` | Query wanted to fetch but was paused | ### Other Returns | Property | Type | Description | |---|---|---| | `status` | `'pending' \| 'success' \| 'error'` | Current query status | | `fetchStatus` | `'fetching' \| 'idle' \| 'paused'` | Current fetch status | | `error` | `null \| Error` | Error object if the query failed | | `dataUpdatedAt` | `number` | Timestamp of last successful fetch | | `errorUpdatedAt` | `number` | Timestamp of last error | | `errorUpdateCount` | `number` | Total number of errors | | `failureCount` | `number` | Failures since last success | | `failureReason` | `null \| Error` | Reason for last retry failure | | `refetch` | `function` | Manually trigger a refetch | --- # useBalances URL: https://docs.blux.cc/react/hooks/use-balances Fetch the balances of a Stellar account in your React app using the Blux SDK. The `useBalances` hook returns the balances of a Stellar account. By default it fetches balances for the connected account on the active network, but you can pass an explicit address and network to fetch any account's balances. The explicit `address` accepts `G…`, `M…`, SEP-2 federation, or `.xlm`; failed resolution is exposed as the query `error`. See [address resolution](/javascript/core/address-resolution). ## Import ```tsx ``` ## Usage Called with no arguments: ```tsx function App() { const { data } = useBalances(); } ``` ```tsx root.render( ); ``` Combine with `useBlux` to fetch balances only when the user is authenticated: ```tsx function App() { const { user, isAuthenticated } = useBlux(); const { data } = useBalances( { address: user?.address }, { enabled: isAuthenticated } ); } ``` ```tsx root.render( ); ``` With filters and TanStack Query options: ```tsx function App() { const { data, isStale } = useBalances( { address: "GABK....2N7M", includeZeroBalances: false }, { retry: 2, staleTime: 60000 } ); } ``` ```tsx root.render( ); ``` Always pass core parameters first, then TanStack Query options. The hook relies on this order to work correctly. ## Parameters ### `address` `string | undefined` The Stellar account ID to fetch balances for. Omit to use the currently connected account. ### `network` `string | undefined` The network to query. Import `networks` from `@bluxcc/react` to select one. ### `includeZeroBalances` `boolean | undefined` When `true`, zero-balance assets are included in the result. Defaults to excluding them. ## Query Options | Option | Type | Default | Description | |---|---|---|---| | `enabled` | `boolean` | `true` | Set to `false` to disable automatic fetching | | `staleTime` | `number \| Infinity` | `0` | Time in ms before data is considered stale | | `gcTime` | `number \| Infinity` | `300000` | Time in ms before inactive cache data is garbage collected | | `retry` | `boolean \| number` | `3` | How many times to retry on failure | | `retryDelay` | `number \| function` | — | Delay in ms between retry attempts | | `refetchInterval` | `number \| false \| function` | — | Continuously refetch at this interval in ms | | `refetchOnMount` | `boolean \| 'always'` | `true` | Refetch on component mount if data is stale | | `refetchOnWindowFocus` | `boolean \| 'always'` | `true` | Refetch when the window regains focus | | `refetchOnReconnect` | `boolean \| 'always'` | `true` | Refetch when network reconnects | | `refetchIntervalInBackground` | `boolean` | — | Keep refetching even when tab is in background | | `placeholderData` | `GetBalancesResult \| function` | — | Placeholder data shown while query is pending (not persisted to cache) | | `initialData` | `GetBalancesResult \| function` | — | Initial data for the cache (persisted) | | `initialDataUpdatedAt` | `number \| function` | — | Timestamp of when `initialData` was last updated | | `select` | `function` | — | Transform or select a subset of the returned data | | `notifyOnChangeProps` | `string[] \| 'all'` | — | Limit re-renders to specific property changes | | `structuralSharing` | `boolean \| function` | `true` | Retain references from old data for performance | | `networkMode` | `'online' \| 'always' \| 'offlineFirst'` | `'online'` | Controls when queries can run relative to network status | | `meta` | `Record` | — | Attach arbitrary metadata to the query cache entry | | `queryClient` | `QueryClient` | — | Use a custom QueryClient instead of the nearest context one | ## Return Type ### `data` `GetBalancesResult | undefined` ```tsx type GetBalancesResult = Horizon.HorizonApi.BalanceLine[]; ``` ### Status Booleans | Property | Type | Description | |---|---|---| | `isPending` | `boolean` | No cached data and no completed fetch yet | | `isSuccess` | `boolean` | Query resolved successfully | | `isError` | `boolean` | Query failed | | `isLoading` | `boolean` | First fetch in-flight (`isFetching && isPending`) | | `isFetching` | `boolean` | Query function is currently executing | | `isRefetching` | `boolean` | Background refetch in progress | | `isFetched` | `boolean` | Query has been fetched at least once | | `isFetchedAfterMount` | `boolean` | Query fetched after component mounted | | `isStale` | `boolean` | Cached data is stale or older than `staleTime` | | `isPlaceholderData` | `boolean` | Currently showing placeholder data | | `isLoadingError` | `boolean` | Failed on the first fetch | | `isRefetchError` | `boolean` | Failed during a background refetch | | `isPaused` | `boolean` | Query wanted to fetch but was paused | ### Other Returns | Property | Type | Description | |---|---|---| | `status` | `'pending' \| 'success' \| 'error'` | Current query status | | `fetchStatus` | `'fetching' \| 'idle' \| 'paused'` | Current fetch status | | `error` | `null \| Error` | Error object if the query failed | | `dataUpdatedAt` | `number` | Timestamp of last successful fetch | | `errorUpdatedAt` | `number` | Timestamp of last error | | `errorUpdateCount` | `number` | Total number of errors | | `failureCount` | `number` | Failures since last success | | `failureReason` | `null \| Error` | Reason for last retry failure | | `refetch` | `function` | Manually trigger a refetch | --- # useClaimableBalances URL: https://docs.blux.cc/react/hooks/use-claimable-balances Fetch a paginated list of claimable balances in your React app using the Blux SDK. The `useClaimableBalances` hook returns a paginated list of claimable balances. Pass an `asset`; `claimant` defaults to the connected account, and `sponsor` is optional. `claimant` and `sponsor` accept `G…`, `M…`, SEP-2 federation, or `.xlm` names. See [address resolution](/javascript/core/address-resolution). ## Import ```tsx ``` ## Usage Read the connected account's claimable XLM balances: ```tsx function App() { const { data } = useClaimableBalances({ asset: "xlm" }); } ``` ```tsx root.render( ); ``` With filters and TanStack Query options: ```tsx function App() { const { data, isStale } = useClaimableBalances( { asset: Asset.native() }, { retry: 2, staleTime: 60000 } ); } ``` ```tsx root.render( ); ``` Always pass core parameters first, then TanStack Query options. The hook relies on this order to work correctly. ## Parameters ### `asset` `Asset | undefined` Filter by asset. Import `Asset` from `@bluxcc/react`. ### `sponsor` `string | undefined` Filter claimable balances sponsored by a specific account ID. ### `claimant` `string | undefined` Filter claimable balances where the specified account is listed as a claimant. ### `cursor` `string | undefined` Pagination cursor for fetching the next or previous page. ### `limit` `number | undefined` Number of records to return per page. ### `network` `string | undefined` The network to query. Omit to use the active network. ### `order` `'asc' | 'desc' | undefined` Sort order for the results. ## Query Options | Option | Type | Default | Description | |---|---|---|---| | `enabled` | `boolean` | `true` | Set to `false` to disable automatic fetching | | `staleTime` | `number \| Infinity` | `0` | Time in ms before data is considered stale | | `gcTime` | `number \| Infinity` | `300000` | Time in ms before inactive cache data is garbage collected | | `retry` | `boolean \| number` | `3` | How many times to retry on failure | | `retryDelay` | `number \| function` | — | Delay in ms between retry attempts | | `refetchInterval` | `number \| false \| function` | — | Continuously refetch at this interval in ms | | `refetchOnMount` | `boolean \| 'always'` | `true` | Refetch on component mount if data is stale | | `refetchOnWindowFocus` | `boolean \| 'always'` | `true` | Refetch when the window regains focus | | `refetchOnReconnect` | `boolean \| 'always'` | `true` | Refetch when network reconnects | | `refetchIntervalInBackground` | `boolean` | — | Keep refetching even when tab is in background | | `placeholderData` | `GetClaimableBalancesResult \| function` | — | Placeholder data shown while query is pending (not persisted to cache) | | `initialData` | `GetClaimableBalancesResult \| function` | — | Initial data for the cache (persisted) | | `initialDataUpdatedAt` | `number \| function` | — | Timestamp of when `initialData` was last updated | | `select` | `function` | — | Transform or select a subset of the returned data | | `notifyOnChangeProps` | `string[] \| 'all'` | — | Limit re-renders to specific property changes | | `structuralSharing` | `boolean \| function` | `true` | Retain references from old data for performance | | `networkMode` | `'online' \| 'always' \| 'offlineFirst'` | `'online'` | Controls when queries can run relative to network status | | `meta` | `Record` | — | Attach arbitrary metadata to the query cache entry | | `queryClient` | `QueryClient` | — | Use a custom QueryClient instead of the nearest context one | ## Return Type ### `data` `GetClaimableBalancesResult | undefined` ```tsx type GetClaimableBalancesResult = { builder: ClaimableBalanceCallBuilder; // .next() and .prev() for pagination response: Horizon.ServerApi.CollectionPage; }; ``` ### Status Booleans | Property | Type | Description | |---|---|---| | `isPending` | `boolean` | No cached data and no completed fetch yet | | `isSuccess` | `boolean` | Query resolved successfully | | `isError` | `boolean` | Query failed | | `isLoading` | `boolean` | First fetch in-flight (`isFetching && isPending`) | | `isFetching` | `boolean` | Query function is currently executing | | `isRefetching` | `boolean` | Background refetch in progress | | `isFetched` | `boolean` | Query has been fetched at least once | | `isFetchedAfterMount` | `boolean` | Query fetched after component mounted | | `isStale` | `boolean` | Cached data is stale or older than `staleTime` | | `isPlaceholderData` | `boolean` | Currently showing placeholder data | | `isLoadingError` | `boolean` | Failed on the first fetch | | `isRefetchError` | `boolean` | Failed during a background refetch | | `isPaused` | `boolean` | Query wanted to fetch but was paused | ### Other Returns | Property | Type | Description | |---|---|---| | `status` | `'pending' \| 'success' \| 'error'` | Current query status | | `fetchStatus` | `'fetching' \| 'idle' \| 'paused'` | Current fetch status | | `error` | `null \| Error` | Error object if the query failed | | `dataUpdatedAt` | `number` | Timestamp of last successful fetch | | `errorUpdatedAt` | `number` | Timestamp of last error | | `errorUpdateCount` | `number` | Total number of errors | | `failureCount` | `number` | Failures since last success | | `failureReason` | `null \| Error` | Reason for last retry failure | | `refetch` | `function` | Manually trigger a refetch | --- # useEffects URL: https://docs.blux.cc/react/hooks/use-effects Fetch a paginated list of Stellar effects in your React app using the Blux SDK. The `useEffects` hook returns a paginated list of Stellar effects. All parameters are optional — called with no arguments it returns the latest effects from the network. `forAccount` accepts `G…`, `M…`, SEP-2 federation, or `.xlm`. See [address resolution](/javascript/core/address-resolution). ## Import ```tsx ``` ## Usage Called with no arguments: ```tsx function App() { const { data } = useEffects(); } ``` ```tsx root.render( ); ``` Combine with `useBlux` to fetch effects only when the user is authenticated: ```tsx function App() { const { user, isAuthenticated } = useBlux(); const { data } = useEffects( { forAccount: user?.address }, { enabled: isAuthenticated } ); } ``` ```tsx root.render( ); ``` With filters and TanStack Query options: ```tsx function App() { const { data, isStale } = useEffects( { forLedger: 60221517 }, { retry: 2, staleTime: 60000 } ); } ``` ```tsx root.render( ); ``` Always pass core parameters first, then TanStack Query options. The hook relies on this order to work correctly. ## Parameters ### `forAccount` `string | undefined` Fetch effects for a specific Stellar account ID. ### `forLedger` `number | string | undefined` Fetch effects emitted in a specific ledger sequence. ### `forTransaction` `string | undefined` Fetch effects related to a specific transaction hash. ### `forOperation` `string | undefined` Fetch effects produced by a specific operation. ### `forLiquidityPool` `string | undefined` Fetch effects related to a specific liquidity pool. ### `cursor` `string | undefined` Pagination cursor for fetching the next or previous page. ### `limit` `number | undefined` Number of records to return per page. ### `network` `string | undefined` The network to query. Omit to use the active network. ### `order` `'asc' | 'desc' | undefined` Sort order for the results. ## Query Options | Option | Type | Default | Description | |---|---|---|---| | `enabled` | `boolean` | `true` | Set to `false` to disable automatic fetching | | `staleTime` | `number \| Infinity` | `0` | Time in ms before data is considered stale | | `gcTime` | `number \| Infinity` | `300000` | Time in ms before inactive cache data is garbage collected | | `retry` | `boolean \| number` | `3` | How many times to retry on failure | | `retryDelay` | `number \| function` | — | Delay in ms between retry attempts | | `refetchInterval` | `number \| false \| function` | — | Continuously refetch at this interval in ms | | `refetchOnMount` | `boolean \| 'always'` | `true` | Refetch on component mount if data is stale | | `refetchOnWindowFocus` | `boolean \| 'always'` | `true` | Refetch when the window regains focus | | `refetchOnReconnect` | `boolean \| 'always'` | `true` | Refetch when network reconnects | | `refetchIntervalInBackground` | `boolean` | — | Keep refetching even when tab is in background | | `placeholderData` | `GetEffectsResult \| function` | — | Placeholder data shown while query is pending (not persisted to cache) | | `initialData` | `GetEffectsResult \| function` | — | Initial data for the cache (persisted) | | `initialDataUpdatedAt` | `number \| function` | — | Timestamp of when `initialData` was last updated | | `select` | `function` | — | Transform or select a subset of the returned data | | `notifyOnChangeProps` | `string[] \| 'all'` | — | Limit re-renders to specific property changes | | `structuralSharing` | `boolean \| function` | `true` | Retain references from old data for performance | | `networkMode` | `'online' \| 'always' \| 'offlineFirst'` | `'online'` | Controls when queries can run relative to network status | | `meta` | `Record` | — | Attach arbitrary metadata to the query cache entry | | `queryClient` | `QueryClient` | — | Use a custom QueryClient instead of the nearest context one | ## Return Type ### `data` `GetEffectsResult | undefined` ```tsx type GetEffectsResult = { builder: EffectCallBuilder; // .next() and .prev() for pagination response: Horizon.ServerApi.CollectionPage; }; ``` ### Status Booleans | Property | Type | Description | |---|---|---| | `isPending` | `boolean` | No cached data and no completed fetch yet | | `isSuccess` | `boolean` | Query resolved successfully | | `isError` | `boolean` | Query failed | | `isLoading` | `boolean` | First fetch in-flight (`isFetching && isPending`) | | `isFetching` | `boolean` | Query function is currently executing | | `isRefetching` | `boolean` | Background refetch in progress | | `isFetched` | `boolean` | Query has been fetched at least once | | `isFetchedAfterMount` | `boolean` | Query fetched after component mounted | | `isStale` | `boolean` | Cached data is stale or older than `staleTime` | | `isPlaceholderData` | `boolean` | Currently showing placeholder data | | `isLoadingError` | `boolean` | Failed on the first fetch | | `isRefetchError` | `boolean` | Failed during a background refetch | | `isPaused` | `boolean` | Query wanted to fetch but was paused | ### Other Returns | Property | Type | Description | |---|---|---| | `status` | `'pending' \| 'success' \| 'error'` | Current query status | | `fetchStatus` | `'fetching' \| 'idle' \| 'paused'` | Current fetch status | | `error` | `null \| Error` | Error object if the query failed | | `dataUpdatedAt` | `number` | Timestamp of last successful fetch | | `errorUpdatedAt` | `number` | Timestamp of last error | | `errorUpdateCount` | `number` | Total number of errors | | `failureCount` | `number` | Failures since last success | | `failureReason` | `null \| Error` | Reason for last retry failure | | `refetch` | `function` | Manually trigger a refetch | --- # useLedgers URL: https://docs.blux.cc/react/hooks/use-ledgers Fetch a paginated list of Stellar ledgers in your React app using the Blux SDK. The `useLedgers` hook returns a paginated list of Stellar ledgers. All parameters are optional — called with no arguments it returns the latest ledgers from the network. ## Import ```tsx ``` ## Usage Called with no arguments: ```tsx function App() { const { data } = useLedgers(); } ``` ```tsx root.render( ); ``` With filters and TanStack Query options: ```tsx function App() { const { data, isStale } = useLedgers( { ledger: 60221517 }, { retry: 2, staleTime: 60000 } ); } ``` ```tsx root.render( ); ``` Always pass core parameters first, then TanStack Query options. The hook relies on this order to work correctly. ## Parameters ### `ledger` `number | string | undefined` Fetch data for a specific ledger sequence number. ### `cursor` `string | undefined` Pagination cursor for fetching the next or previous page. ### `limit` `number | undefined` Number of records to return per page. ### `network` `string | undefined` The network to query. Omit to use the active network. ### `order` `'asc' | 'desc' | undefined` Sort order for the results. ## Query Options | Option | Type | Default | Description | |---|---|---|---| | `enabled` | `boolean` | `true` | Set to `false` to disable automatic fetching | | `staleTime` | `number \| Infinity` | `0` | Time in ms before data is considered stale | | `gcTime` | `number \| Infinity` | `300000` | Time in ms before inactive cache data is garbage collected | | `retry` | `boolean \| number` | `3` | How many times to retry on failure | | `retryDelay` | `number \| function` | — | Delay in ms between retry attempts | | `refetchInterval` | `number \| false \| function` | — | Continuously refetch at this interval in ms | | `refetchOnMount` | `boolean \| 'always'` | `true` | Refetch on component mount if data is stale | | `refetchOnWindowFocus` | `boolean \| 'always'` | `true` | Refetch when the window regains focus | | `refetchOnReconnect` | `boolean \| 'always'` | `true` | Refetch when network reconnects | | `refetchIntervalInBackground` | `boolean` | — | Keep refetching even when tab is in background | | `placeholderData` | `GetLedgersResult \| function` | — | Placeholder data shown while query is pending (not persisted to cache) | | `initialData` | `GetLedgersResult \| function` | — | Initial data for the cache (persisted) | | `initialDataUpdatedAt` | `number \| function` | — | Timestamp of when `initialData` was last updated | | `select` | `function` | — | Transform or select a subset of the returned data | | `notifyOnChangeProps` | `string[] \| 'all'` | — | Limit re-renders to specific property changes | | `structuralSharing` | `boolean \| function` | `true` | Retain references from old data for performance | | `networkMode` | `'online' \| 'always' \| 'offlineFirst'` | `'online'` | Controls when queries can run relative to network status | | `meta` | `Record` | — | Attach arbitrary metadata to the query cache entry | | `queryClient` | `QueryClient` | — | Use a custom QueryClient instead of the nearest context one | ## Return Type ### `data` `GetLedgersResult | undefined` ```tsx type GetLedgersResult = { builder: LedgerCallBuilder; // .next() and .prev() for pagination response: Horizon.ServerApi.CollectionPage; }; ``` ### Status Booleans | Property | Type | Description | |---|---|---| | `isPending` | `boolean` | No cached data and no completed fetch yet | | `isSuccess` | `boolean` | Query resolved successfully | | `isError` | `boolean` | Query failed | | `isLoading` | `boolean` | First fetch in-flight (`isFetching && isPending`) | | `isFetching` | `boolean` | Query function is currently executing | | `isRefetching` | `boolean` | Background refetch in progress | | `isFetched` | `boolean` | Query has been fetched at least once | | `isFetchedAfterMount` | `boolean` | Query fetched after component mounted | | `isStale` | `boolean` | Cached data is stale or older than `staleTime` | | `isPlaceholderData` | `boolean` | Currently showing placeholder data | | `isLoadingError` | `boolean` | Failed on the first fetch | | `isRefetchError` | `boolean` | Failed during a background refetch | | `isPaused` | `boolean` | Query wanted to fetch but was paused | ### Other Returns | Property | Type | Description | |---|---|---| | `status` | `'pending' \| 'success' \| 'error'` | Current query status | | `fetchStatus` | `'fetching' \| 'idle' \| 'paused'` | Current fetch status | | `error` | `null \| Error` | Error object if the query failed | | `dataUpdatedAt` | `number` | Timestamp of last successful fetch | | `errorUpdatedAt` | `number` | Timestamp of last error | | `errorUpdateCount` | `number` | Total number of errors | | `failureCount` | `number` | Failures since last success | | `failureReason` | `null \| Error` | Reason for last retry failure | | `refetch` | `function` | Manually trigger a refetch | --- # useLiquidityPools URL: https://docs.blux.cc/react/hooks/use-liquidity-pools Fetch a paginated list of Stellar liquidity pools in your React app using the Blux SDK. The `useLiquidityPools` hook returns a paginated list of Stellar liquidity pools. All parameters are optional — called with no arguments it returns the latest pools from the network. `forAccount` accepts `G…`, `M…`, SEP-2 federation, or `.xlm`. See [address resolution](/javascript/core/address-resolution). ## Import ```tsx ``` ## Usage Called with no arguments: ```tsx function App() { const { data } = useLiquidityPools(); } ``` ```tsx root.render( ); ``` Combine with `useBlux` to fetch pools only when the user is authenticated: ```tsx function App() { const { user, isAuthenticated } = useBlux(); const { data } = useLiquidityPools( { forAccount: user?.address }, { enabled: isAuthenticated } ); } ``` ```tsx root.render( ); ``` With filters and TanStack Query options: ```tsx function App() { const { data, isStale } = useLiquidityPools( { forAccount: "GABK....2N7M" }, { retry: 2, staleTime: 60000 } ); } ``` ```tsx root.render( ); ``` Always pass core parameters first, then TanStack Query options. The hook relies on this order to work correctly. ## Parameters ### `forAssets` `Array | undefined` Filter pools that include any of the provided assets. Import `Asset` from `@bluxcc/react`. ### `forAccount` `string | undefined` Fetch liquidity pools associated with a specific account ID. ### `cursor` `string | undefined` Pagination cursor for fetching the next or previous page. ### `limit` `number | undefined` Number of records to return per page. ### `network` `string | undefined` The network to query. Omit to use the active network. ### `order` `'asc' | 'desc' | undefined` Sort order for the results. ## Query Options | Option | Type | Default | Description | |---|---|---|---| | `enabled` | `boolean` | `true` | Set to `false` to disable automatic fetching | | `staleTime` | `number \| Infinity` | `0` | Time in ms before data is considered stale | | `gcTime` | `number \| Infinity` | `300000` | Time in ms before inactive cache data is garbage collected | | `retry` | `boolean \| number` | `3` | How many times to retry on failure | | `retryDelay` | `number \| function` | — | Delay in ms between retry attempts | | `refetchInterval` | `number \| false \| function` | — | Continuously refetch at this interval in ms | | `refetchOnMount` | `boolean \| 'always'` | `true` | Refetch on component mount if data is stale | | `refetchOnWindowFocus` | `boolean \| 'always'` | `true` | Refetch when the window regains focus | | `refetchOnReconnect` | `boolean \| 'always'` | `true` | Refetch when network reconnects | | `refetchIntervalInBackground` | `boolean` | — | Keep refetching even when tab is in background | | `placeholderData` | `GetLiquidityPoolsResult \| function` | — | Placeholder data shown while query is pending (not persisted to cache) | | `initialData` | `GetLiquidityPoolsResult \| function` | — | Initial data for the cache (persisted) | | `initialDataUpdatedAt` | `number \| function` | — | Timestamp of when `initialData` was last updated | | `select` | `function` | — | Transform or select a subset of the returned data | | `notifyOnChangeProps` | `string[] \| 'all'` | — | Limit re-renders to specific property changes | | `structuralSharing` | `boolean \| function` | `true` | Retain references from old data for performance | | `networkMode` | `'online' \| 'always' \| 'offlineFirst'` | `'online'` | Controls when queries can run relative to network status | | `meta` | `Record` | — | Attach arbitrary metadata to the query cache entry | | `queryClient` | `QueryClient` | — | Use a custom QueryClient instead of the nearest context one | ## Return Type ### `data` `GetLiquidityPoolsResult | undefined` ```tsx type GetLiquidityPoolsResult = { builder: LiquidityPoolCallBuilder; // .next() and .prev() for pagination response: Horizon.ServerApi.CollectionPage; }; ``` ### Status Booleans | Property | Type | Description | |---|---|---| | `isPending` | `boolean` | No cached data and no completed fetch yet | | `isSuccess` | `boolean` | Query resolved successfully | | `isError` | `boolean` | Query failed | | `isLoading` | `boolean` | First fetch in-flight (`isFetching && isPending`) | | `isFetching` | `boolean` | Query function is currently executing | | `isRefetching` | `boolean` | Background refetch in progress | | `isFetched` | `boolean` | Query has been fetched at least once | | `isFetchedAfterMount` | `boolean` | Query fetched after component mounted | | `isStale` | `boolean` | Cached data is stale or older than `staleTime` | | `isPlaceholderData` | `boolean` | Currently showing placeholder data | | `isLoadingError` | `boolean` | Failed on the first fetch | | `isRefetchError` | `boolean` | Failed during a background refetch | | `isPaused` | `boolean` | Query wanted to fetch but was paused | ### Other Returns | Property | Type | Description | |---|---|---| | `status` | `'pending' \| 'success' \| 'error'` | Current query status | | `fetchStatus` | `'fetching' \| 'idle' \| 'paused'` | Current fetch status | | `error` | `null \| Error` | Error object if the query failed | | `dataUpdatedAt` | `number` | Timestamp of last successful fetch | | `errorUpdatedAt` | `number` | Timestamp of last error | | `errorUpdateCount` | `number` | Total number of errors | | `failureCount` | `number` | Failures since last success | | `failureReason` | `null \| Error` | Reason for last retry failure | | `refetch` | `function` | Manually trigger a refetch | --- # useNetwork URL: https://docs.blux.cc/react/hooks/use-network Retrieve the currently active network in your React app using the Blux SDK. The `useNetwork` hook returns the currently active network of the app. ## Import ```tsx ``` ## Usage ```tsx const Comp = () => { const network = useNetwork(); return
{network}
; }; ``` ## Return Type `string` The active network string (e.g. `'Public Global Stellar Network ; September 2015'`). Import `networks` from `@bluxcc/react` to compare against known network values. --- # useOffers URL: https://docs.blux.cc/react/hooks/use-offers Fetch a paginated list of Stellar offers in your React app using the Blux SDK. The `useOffers` hook returns a paginated list of Stellar offers. All parameters are optional — called with no arguments it returns the latest offers from the network. `forAccount`, `sponsor`, and `seller` accept `G…`, `M…`, SEP-2 federation, or `.xlm`. See [address resolution](/javascript/core/address-resolution). ## Import ```tsx ``` ## Usage Called with no arguments: ```tsx function App() { const { data } = useOffers(); } ``` ```tsx root.render( ); ``` Combine with `useBlux` to fetch offers only when the user is authenticated: ```tsx function App() { const { user, isAuthenticated } = useBlux(); const { data } = useOffers( { forAccount: user?.address }, { enabled: isAuthenticated } ); } ``` ```tsx root.render( ); ``` With filters and TanStack Query options: ```tsx function App() { const { data, isStale } = useOffers( { forAccount: "GABK....2N7M" }, { retry: 2, staleTime: 60000 } ); } ``` ```tsx root.render( ); ``` Always pass core parameters first, then TanStack Query options. The hook relies on this order to work correctly. ## Parameters ### `forAccount` `string | undefined` Fetch offers created by or affecting a specific Stellar account ID. ### `buying` `Asset | undefined` Filter offers where the buying asset matches. Import `Asset` from `@bluxcc/react`. ### `selling` `Asset | undefined` Filter offers where the selling asset matches. Import `Asset` from `@bluxcc/react`. ### `sponsor` `string | undefined` Filter offers sponsored by a specific account ID. ### `seller` `string | undefined` Filter offers created by a specific seller account ID. ### `cursor` `string | undefined` Pagination cursor for fetching the next or previous page. ### `limit` `number | undefined` Number of records to return per page. ### `network` `string | undefined` The network to query. Omit to use the active network. ### `order` `'asc' | 'desc' | undefined` Sort order for the results. ## Query Options | Option | Type | Default | Description | |---|---|---|---| | `enabled` | `boolean` | `true` | Set to `false` to disable automatic fetching | | `staleTime` | `number \| Infinity` | `0` | Time in ms before data is considered stale | | `gcTime` | `number \| Infinity` | `300000` | Time in ms before inactive cache data is garbage collected | | `retry` | `boolean \| number` | `3` | How many times to retry on failure | | `retryDelay` | `number \| function` | — | Delay in ms between retry attempts | | `refetchInterval` | `number \| false \| function` | — | Continuously refetch at this interval in ms | | `refetchOnMount` | `boolean \| 'always'` | `true` | Refetch on component mount if data is stale | | `refetchOnWindowFocus` | `boolean \| 'always'` | `true` | Refetch when the window regains focus | | `refetchOnReconnect` | `boolean \| 'always'` | `true` | Refetch when network reconnects | | `refetchIntervalInBackground` | `boolean` | — | Keep refetching even when tab is in background | | `placeholderData` | `GetOffersResult \| function` | — | Placeholder data shown while query is pending (not persisted to cache) | | `initialData` | `GetOffersResult \| function` | — | Initial data for the cache (persisted) | | `initialDataUpdatedAt` | `number \| function` | — | Timestamp of when `initialData` was last updated | | `select` | `function` | — | Transform or select a subset of the returned data | | `notifyOnChangeProps` | `string[] \| 'all'` | — | Limit re-renders to specific property changes | | `structuralSharing` | `boolean \| function` | `true` | Retain references from old data for performance | | `networkMode` | `'online' \| 'always' \| 'offlineFirst'` | `'online'` | Controls when queries can run relative to network status | | `meta` | `Record` | — | Attach arbitrary metadata to the query cache entry | | `queryClient` | `QueryClient` | — | Use a custom QueryClient instead of the nearest context one | ## Return Type ### `data` `GetOffersResult | undefined` ```tsx type GetOffersResult = { builder: OfferCallBuilder; // .next() and .prev() for pagination response: Horizon.ServerApi.CollectionPage; }; ``` ### Status Booleans | Property | Type | Description | |---|---|---| | `isPending` | `boolean` | No cached data and no completed fetch yet | | `isSuccess` | `boolean` | Query resolved successfully | | `isError` | `boolean` | Query failed | | `isLoading` | `boolean` | First fetch in-flight (`isFetching && isPending`) | | `isFetching` | `boolean` | Query function is currently executing | | `isRefetching` | `boolean` | Background refetch in progress | | `isFetched` | `boolean` | Query has been fetched at least once | | `isFetchedAfterMount` | `boolean` | Query fetched after component mounted | | `isStale` | `boolean` | Cached data is stale or older than `staleTime` | | `isPlaceholderData` | `boolean` | Currently showing placeholder data | | `isLoadingError` | `boolean` | Failed on the first fetch | | `isRefetchError` | `boolean` | Failed during a background refetch | | `isPaused` | `boolean` | Query wanted to fetch but was paused | ### Other Returns | Property | Type | Description | |---|---|---| | `status` | `'pending' \| 'success' \| 'error'` | Current query status | | `fetchStatus` | `'fetching' \| 'idle' \| 'paused'` | Current fetch status | | `error` | `null \| Error` | Error object if the query failed | | `dataUpdatedAt` | `number` | Timestamp of last successful fetch | | `errorUpdatedAt` | `number` | Timestamp of last error | | `errorUpdateCount` | `number` | Total number of errors | | `failureCount` | `number` | Failures since last success | | `failureReason` | `null \| Error` | Reason for last retry failure | | `refetch` | `function` | Manually trigger a refetch | --- # useOperations URL: https://docs.blux.cc/react/hooks/use-operations Fetch a paginated list of Stellar operations in your React app using the Blux SDK. The `useOperations` hook returns a paginated list of Stellar operations. All parameters are optional — called with no arguments it returns the latest operations from the network. `forAccount` accepts `G…`, `M…`, SEP-2 federation, or `.xlm`. See [address resolution](/javascript/core/address-resolution). ## Import ```tsx ``` ## Usage Called with no arguments: ```tsx function App() { const { data } = useOperations(); } ``` ```tsx root.render( ); ``` Combine with `useBlux` to fetch operations only when the user is authenticated: ```tsx function App() { const { user, isAuthenticated } = useBlux(); const { data } = useOperations( { forAccount: user?.address }, { enabled: isAuthenticated } ); } ``` ```tsx root.render( ); ``` With filters and TanStack Query options: ```tsx function App() { const { data, isStale } = useOperations( { forLedger: 60221517 }, { retry: 2, staleTime: 60000 } ); } ``` ```tsx root.render( ); ``` Always pass core parameters first, then TanStack Query options. The hook relies on this order to work correctly. ## Parameters ### `forAccount` `string | undefined` Fetch operations for a specific Stellar account ID. ### `forClaimableBalance` `string | undefined` Fetch operations related to a specific claimable balance ID. ### `forLedger` `number | string | undefined` Fetch operations included in a specific ledger sequence. ### `forTransaction` `string | undefined` Fetch operations related to a specific transaction hash. ### `forLiquidityPool` `string | undefined` Fetch operations related to a specific liquidity pool ID. ### `includeFailed` `boolean | undefined` When `true`, includes failed operations in the results. ### `cursor` `string | undefined` Pagination cursor for fetching the next or previous page. ### `limit` `number | undefined` Number of records to return per page. ### `network` `string | undefined` The network to query. Omit to use the active network. ### `order` `'asc' | 'desc' | undefined` Sort order for the results. ## Query Options | Option | Type | Default | Description | |---|---|---|---| | `enabled` | `boolean` | `true` | Set to `false` to disable automatic fetching | | `staleTime` | `number \| Infinity` | `0` | Time in ms before data is considered stale | | `gcTime` | `number \| Infinity` | `300000` | Time in ms before inactive cache data is garbage collected | | `retry` | `boolean \| number` | `3` | How many times to retry on failure | | `retryDelay` | `number \| function` | — | Delay in ms between retry attempts | | `refetchInterval` | `number \| false \| function` | — | Continuously refetch at this interval in ms | | `refetchOnMount` | `boolean \| 'always'` | `true` | Refetch on component mount if data is stale | | `refetchOnWindowFocus` | `boolean \| 'always'` | `true` | Refetch when the window regains focus | | `refetchOnReconnect` | `boolean \| 'always'` | `true` | Refetch when network reconnects | | `refetchIntervalInBackground` | `boolean` | — | Keep refetching even when tab is in background | | `placeholderData` | `GetOperationsResult \| function` | — | Placeholder data shown while query is pending (not persisted to cache) | | `initialData` | `GetOperationsResult \| function` | — | Initial data for the cache (persisted) | | `initialDataUpdatedAt` | `number \| function` | — | Timestamp of when `initialData` was last updated | | `select` | `function` | — | Transform or select a subset of the returned data | | `notifyOnChangeProps` | `string[] \| 'all'` | — | Limit re-renders to specific property changes | | `structuralSharing` | `boolean \| function` | `true` | Retain references from old data for performance | | `networkMode` | `'online' \| 'always' \| 'offlineFirst'` | `'online'` | Controls when queries can run relative to network status | | `meta` | `Record` | — | Attach arbitrary metadata to the query cache entry | | `queryClient` | `QueryClient` | — | Use a custom QueryClient instead of the nearest context one | ## Return Type ### `data` `GetOperationsResult | undefined` ```tsx type GetOperationsResult = { builder: OperationCallBuilder; // .next() and .prev() for pagination response: Horizon.ServerApi.CollectionPage; }; ``` ### Status Booleans | Property | Type | Description | |---|---|---| | `isPending` | `boolean` | No cached data and no completed fetch yet | | `isSuccess` | `boolean` | Query resolved successfully | | `isError` | `boolean` | Query failed | | `isLoading` | `boolean` | First fetch in-flight (`isFetching && isPending`) | | `isFetching` | `boolean` | Query function is currently executing | | `isRefetching` | `boolean` | Background refetch in progress | | `isFetched` | `boolean` | Query has been fetched at least once | | `isFetchedAfterMount` | `boolean` | Query fetched after component mounted | | `isStale` | `boolean` | Cached data is stale or older than `staleTime` | | `isPlaceholderData` | `boolean` | Currently showing placeholder data | | `isLoadingError` | `boolean` | Failed on the first fetch | | `isRefetchError` | `boolean` | Failed during a background refetch | | `isPaused` | `boolean` | Query wanted to fetch but was paused | ### Other Returns | Property | Type | Description | |---|---|---| | `status` | `'pending' \| 'success' \| 'error'` | Current query status | | `fetchStatus` | `'fetching' \| 'idle' \| 'paused'` | Current fetch status | | `error` | `null \| Error` | Error object if the query failed | | `dataUpdatedAt` | `number` | Timestamp of last successful fetch | | `errorUpdatedAt` | `number` | Timestamp of last error | | `errorUpdateCount` | `number` | Total number of errors | | `failureCount` | `number` | Failures since last success | | `failureReason` | `null \| Error` | Reason for last retry failure | | `refetch` | `function` | Manually trigger a refetch | --- # useOrderbook URL: https://docs.blux.cc/react/hooks/use-orderbook Fetch orderbook data for an asset pair in your React app using the Blux SDK. The `useOrderbook` hook returns orderbook data for a given asset pair. Both `selling` and `buying` are required — the hook will not run without them. Import `Asset` from `@bluxcc/react`. ## Import ```tsx ``` ## Usage Basic usage with required arguments: ```tsx function App() { const selling = Asset.native(); const buying = new Asset("USDC", "GA5Z....KZVN"); const { data } = useOrderbook([selling, buying]); } ``` ```tsx root.render( ); ``` With call-builder options and TanStack Query options: ```tsx function App() { const selling = Asset.native(); const buying = new Asset("USDC", "GA5Z....KZVN"); const { data, isStale } = useOrderbook( [selling, buying], // Required arguments { limit: 20, order: "asc" }, // Core parameters { retry: 3, staleTime: 5000 }, // TanStack parameters ); } ``` ```tsx root.render( ); ``` Pass required arguments first, then core call-builder options, then TanStack Query options. The hook relies on this order to work correctly. ## Parameters ### `selling` (required) `Asset` The asset being sold in the orderbook. ### `buying` (required) `Asset` The asset being bought in the orderbook. ### `limit` `number | undefined` Number of records to return. ### `network` `string | undefined` The network to query. Omit to use the active network. ### `order` `'asc' | 'desc' | undefined` Sort order for the results. ## Query Options | Option | Type | Default | Description | |---|---|---|---| | `enabled` | `boolean` | `true` | Set to `false` to disable automatic fetching | | `staleTime` | `number \| Infinity` | `0` | Time in ms before data is considered stale | | `gcTime` | `number \| Infinity` | `300000` | Time in ms before inactive cache data is garbage collected | | `retry` | `boolean \| number` | `3` | How many times to retry on failure | | `retryDelay` | `number \| function` | — | Delay in ms between retry attempts | | `refetchInterval` | `number \| false \| function` | — | Continuously refetch at this interval in ms | | `refetchOnMount` | `boolean \| 'always'` | `true` | Refetch on component mount if data is stale | | `refetchOnWindowFocus` | `boolean \| 'always'` | `true` | Refetch when the window regains focus | | `refetchOnReconnect` | `boolean \| 'always'` | `true` | Refetch when network reconnects | | `refetchIntervalInBackground` | `boolean` | — | Keep refetching even when tab is in background | | `placeholderData` | `GetOrderbookResult \| function` | — | Placeholder data shown while query is pending (not persisted to cache) | | `initialData` | `GetOrderbookResult \| function` | — | Initial data for the cache (persisted) | | `initialDataUpdatedAt` | `number \| function` | — | Timestamp of when `initialData` was last updated | | `select` | `function` | — | Transform or select a subset of the returned data | | `notifyOnChangeProps` | `string[] \| 'all'` | — | Limit re-renders to specific property changes | | `structuralSharing` | `boolean \| function` | `true` | Retain references from old data for performance | | `networkMode` | `'online' \| 'always' \| 'offlineFirst'` | `'online'` | Controls when queries can run relative to network status | | `meta` | `Record` | — | Attach arbitrary metadata to the query cache entry | | `queryClient` | `QueryClient` | — | Use a custom QueryClient instead of the nearest context one | ## Return Type ### `data` `GetOrderbookResult | undefined` ```tsx type GetOrderbookResult = { builder: OrderbookCallBuilder; response: Horizon.ServerApi.OrderbookRecord; }; ``` ### Status Booleans | Property | Type | Description | |---|---|---| | `isPending` | `boolean` | No cached data and no completed fetch yet | | `isSuccess` | `boolean` | Query resolved successfully | | `isError` | `boolean` | Query failed | | `isLoading` | `boolean` | First fetch in-flight (`isFetching && isPending`) | | `isFetching` | `boolean` | Query function is currently executing | | `isRefetching` | `boolean` | Background refetch in progress | | `isFetched` | `boolean` | Query has been fetched at least once | | `isFetchedAfterMount` | `boolean` | Query fetched after component mounted | | `isStale` | `boolean` | Cached data is stale or older than `staleTime` | | `isPlaceholderData` | `boolean` | Currently showing placeholder data | | `isLoadingError` | `boolean` | Failed on the first fetch | | `isRefetchError` | `boolean` | Failed during a background refetch | | `isPaused` | `boolean` | Query wanted to fetch but was paused | ### Other Returns | Property | Type | Description | |---|---|---| | `status` | `'pending' \| 'success' \| 'error'` | Current query status | | `fetchStatus` | `'fetching' \| 'idle' \| 'paused'` | Current fetch status | | `error` | `null \| Error` | Error object if the query failed | | `dataUpdatedAt` | `number` | Timestamp of last successful fetch | | `errorUpdatedAt` | `number` | Timestamp of last error | | `errorUpdateCount` | `number` | Total number of errors | | `failureCount` | `number` | Failures since last success | | `failureReason` | `null \| Error` | Reason for last retry failure | | `refetch` | `function` | Manually trigger a refetch | --- # usePayments URL: https://docs.blux.cc/react/hooks/use-payments Fetch a paginated list of Stellar payments in your React app using the Blux SDK. The `usePayments` hook returns a paginated list of Stellar payments. All parameters are optional — called with no arguments it returns the latest payments from the network. `forAccount` accepts `G…`, `M…`, SEP-2 federation, or `.xlm`. See [address resolution](/javascript/core/address-resolution). ## Import ```tsx ``` ## Usage Called with no arguments: ```tsx function App() { const { data } = usePayments(); } ``` ```tsx root.render( ); ``` Combine with `useBlux` to fetch payments only when the user is authenticated: ```tsx function App() { const { user, isAuthenticated } = useBlux(); const { data } = usePayments( { forAccount: user?.address }, { enabled: isAuthenticated } ); } ``` ```tsx root.render( ); ``` With filters and TanStack Query options: ```tsx function App() { const { data, isStale } = usePayments( { forLedger: 60221517 }, { retry: 2, staleTime: 60000 } ); } ``` ```tsx root.render( ); ``` Always pass core parameters first, then TanStack Query options. The hook relies on this order to work correctly. ## Parameters ### `forAccount` `string | undefined` Fetch payments for a specific Stellar account ID. ### `forLedger` `number | string | undefined` Fetch payments included in a specific ledger sequence. ### `forTransaction` `string | undefined` Fetch payments related to a specific transaction hash. ### `includeFailed` `boolean | undefined` When `true`, includes failed payments in the results. ### `cursor` `string | undefined` Pagination cursor for fetching the next or previous page. ### `limit` `number | undefined` Number of records to return per page. ### `network` `string | undefined` The network to query. Omit to use the active network. ### `order` `'asc' | 'desc' | undefined` Sort order for the results. ## Query Options | Option | Type | Default | Description | |---|---|---|---| | `enabled` | `boolean` | `true` | Set to `false` to disable automatic fetching | | `staleTime` | `number \| Infinity` | `0` | Time in ms before data is considered stale | | `gcTime` | `number \| Infinity` | `300000` | Time in ms before inactive cache data is garbage collected | | `retry` | `boolean \| number` | `3` | How many times to retry on failure | | `retryDelay` | `number \| function` | — | Delay in ms between retry attempts | | `refetchInterval` | `number \| false \| function` | — | Continuously refetch at this interval in ms | | `refetchOnMount` | `boolean \| 'always'` | `true` | Refetch on component mount if data is stale | | `refetchOnWindowFocus` | `boolean \| 'always'` | `true` | Refetch when the window regains focus | | `refetchOnReconnect` | `boolean \| 'always'` | `true` | Refetch when network reconnects | | `refetchIntervalInBackground` | `boolean` | — | Keep refetching even when tab is in background | | `placeholderData` | `GetPaymentsResult \| function` | — | Placeholder data shown while query is pending (not persisted to cache) | | `initialData` | `GetPaymentsResult \| function` | — | Initial data for the cache (persisted) | | `initialDataUpdatedAt` | `number \| function` | — | Timestamp of when `initialData` was last updated | | `select` | `function` | — | Transform or select a subset of the returned data | | `notifyOnChangeProps` | `string[] \| 'all'` | — | Limit re-renders to specific property changes | | `structuralSharing` | `boolean \| function` | `true` | Retain references from old data for performance | | `networkMode` | `'online' \| 'always' \| 'offlineFirst'` | `'online'` | Controls when queries can run relative to network status | | `meta` | `Record` | — | Attach arbitrary metadata to the query cache entry | | `queryClient` | `QueryClient` | — | Use a custom QueryClient instead of the nearest context one | ## Return Type ### `data` `GetPaymentsResult | undefined` ```tsx type GetPaymentsResult = { builder: PaymentCallBuilder; response: ServerApi.CollectionPage | ServerApi.CreateAccountOperationRecord | ServerApi.PaymentOperationRecord | ServerApi.PathPaymentOperationRecord | ServerApi.AccountMergeOperationRecord | ServerApi.PathPaymentStrictSendOperationRecord | ServerApi.InvokeHostFunctionOperationRecord >; }; ``` ### Status Booleans | Property | Type | Description | |---|---|---| | `isPending` | `boolean` | No cached data and no completed fetch yet | | `isSuccess` | `boolean` | Query resolved successfully | | `isError` | `boolean` | Query failed | | `isLoading` | `boolean` | First fetch in-flight (`isFetching && isPending`) | | `isFetching` | `boolean` | Query function is currently executing | | `isRefetching` | `boolean` | Background refetch in progress | | `isFetched` | `boolean` | Query has been fetched at least once | | `isFetchedAfterMount` | `boolean` | Query fetched after component mounted | | `isStale` | `boolean` | Cached data is stale or older than `staleTime` | | `isPlaceholderData` | `boolean` | Currently showing placeholder data | | `isLoadingError` | `boolean` | Failed on the first fetch | | `isRefetchError` | `boolean` | Failed during a background refetch | | `isPaused` | `boolean` | Query wanted to fetch but was paused | ### Other Returns | Property | Type | Description | |---|---|---| | `status` | `'pending' \| 'success' \| 'error'` | Current query status | | `fetchStatus` | `'fetching' \| 'idle' \| 'paused'` | Current fetch status | | `error` | `null \| Error` | Error object if the query failed | | `dataUpdatedAt` | `number` | Timestamp of last successful fetch | | `errorUpdatedAt` | `number` | Timestamp of last error | | `errorUpdateCount` | `number` | Total number of errors | | `failureCount` | `number` | Failures since last success | | `failureReason` | `null \| Error` | Reason for last retry failure | | `refetch` | `function` | Manually trigger a refetch | --- # useReadContracts URL: https://docs.blux.cc/react/hooks/use-read-contracts Read state from Soroban smart contracts in React, powered by TanStack Query. `useReadContracts` is the React wrapper around [`readContracts`](/javascript/core/readContracts). It reads data from one or more **Soroban** smart contracts by simulating the calls (no signature, no fee) and exposes the result as a TanStack Query, so you get caching, refetching, and loading states for free. ## Import ```tsx ``` ## Native contract arguments Pass native JavaScript values in the contract function's positional order. The hook uses the deployed contract spec to encode each value as the declared Soroban type, so `args` does not require `ToScVal`. Addresses, strings, and symbols are passed as strings; booleans as booleans; bytes as `Uint8Array`; and vectors or tuples as arrays. Integers accept safe numbers, `bigint` values, or decimal strings. Prefer `bigint` or a decimal string for wide integers such as `i128`. The contract `address` and every value whose ABI type is `Address` also accept `.xlm` names and SEP-2 federation addresses, including nested address values. See [address resolution](/javascript/core/address-resolution). Pre-encoded `xdr.ScVal` arguments remain supported, but manual encoding is optional. ## Usage Read a token's `name`, `decimals`, and a user's `balance` in one batch: ```tsx const TOKEN = "CB64D3G7SM2RTH6JSGG34DDTFTQ5CFDKVDZJZSODMCX4NJ2HV2KN7OG"; function TokenInfo({ account }: { account: string }) { const { data, isLoading } = useReadContracts<[string, number, string]>([ { address: TOKEN, fn: "name", args: [] }, { address: TOKEN, fn: "decimals", args: [] }, { address: TOKEN, fn: "balance", args: ["alice.xlm"] }, ]); if (isLoading) return

Loading…

; const [name, decimals, balance] = data?.values ?? []; return

{name}: {balance}

; } ```
```tsx root.render( ); ```
## Return types Runtime contract addresses and function names do not give TypeScript a compile-time ABI. Pass an array/tuple generic whose entries match the calls: ```tsx const query = useReadContracts<[string, number, string]>([ { address: TOKEN, fn: "name", args: [] }, { address: TOKEN, fn: "decimals", args: [] }, { address: TOKEN, fn: "balance", args: ["alice.xlm"] }, ]); query.data?.values[2]; // string ``` Omit the generic for `readonly unknown[]`, and include `null` for any call that may return no value. You can pass network options and TanStack Query options (such as `enabled`) as the second and third arguments: ```tsx const { data } = useReadContracts( calls, { network: networks.mainnet }, { enabled: isAuthenticated, staleTime: 60000 } ); ``` The hook returns the standard TanStack Query result. The contract data lives on `data` as `{ raws, values }`, index-aligned with the calls you passed in. --- # useResolveXlmNameByAddress URL: https://docs.blux.cc/react/hooks/use-resolve-xlm-name-by-address Find a verified XLM Domains name for a Stellar account in React. `useResolveXlmNameByAddress` is the React query wrapper around [`resolveXlmNameByAddress`](/javascript/core/resolveXlmNameByAddress). Give it a classic Stellar account address (`G…`) to retrieve one verified `.xlm` name. ```tsx function AccountName({ address }: { address: string }) { const { data, isLoading, error } = useResolveXlmNameByAddress(address); if (isLoading) return Finding name…; if (error) return No verified name; return {data?.name}; } ``` ## Signature ```ts useResolveXlmNameByAddress( address: string, options?: XlmNameLookupOptions, queryOptions?: QueryOptions, ): UseQueryResult; ``` | Argument | Description | |---|---| | `address` | A classic `G…` account. The query is disabled while this is empty. | | `options` | SEP-2 options: `timeout` and `allowHttp`. | | `queryOptions` | TanStack Query options such as `enabled`, `staleTime`, `retry`, and `select`. | ```tsx const result = useResolveXlmNameByAddress( accountAddress, { timeout: 5000 }, { enabled: Boolean(accountAddress), staleTime: 60_000 }, ); ``` The returned `data` includes the normalized `name`, its `federationAddress`, the verified `publicKey`, and any memo details. When an account owns multiple names, XLM Domains chooses which reverse record is returned. Only `G…` accounts are accepted. Invalid addresses, missing reverse records, and records that fail forward verification are exposed through `error`. To resolve a `.xlm` name to its address, use [`useResolveXlmName`](/react/hooks/use-resolve-xlm-name). --- # useResolveXlmName URL: https://docs.blux.cc/react/hooks/use-resolve-xlm-name Resolve an XLM Domains name in React with TanStack Query caching and status state. `useResolveXlmName` is the React query wrapper around [`resolveXlmName`](/javascript/core/resolveXlmName). It resolves a `.xlm` name to a validated account or contract record and exposes TanStack Query loading, error, caching, and refetching state. ```tsx function Recipient({ name }: { name: string }) { const { data, isLoading, error } = useResolveXlmName(name); if (isLoading) return Resolving…; if (error) return {error.message}; return {data?.address}; } ``` Use the `kind` field before reading the address-specific property: ```tsx const { data } = useResolveXlmName("token.xlm"); if (data?.kind === "account") { console.log(data.publicKey); } else if (data?.kind === "contract") { console.log(data.contractId); } ``` ## Signature ```ts useResolveXlmName( name: string, options?: XlmNameLookupOptions, queryOptions?: QueryOptions, ): UseQueryResult; ``` | Argument | Description | |---|---| | `name` | A `.xlm` name such as `alice.xlm`. The query is disabled while this is empty. | | `options` | SEP-2 options: `timeout` and `allowHttp`. | | `queryOptions` | TanStack Query options such as `enabled`, `staleTime`, `retry`, and `select`. | ```tsx const result = useResolveXlmName( "alice.xlm", { timeout: 5000 }, { staleTime: 60_000, retry: 1 }, ); ``` `data` is the same discriminated `XlmNameRecord` returned by the core function, including `name`, `federationAddress`, `address`, `kind`, optional memo fields, and either `publicKey` or `contractId`. This query does not depend on the active Blux network. XLM Domains resolves from its mainnet registry. Resolution failures are available through `error`. To resolve in the other direction, use [`useResolveXlmNameByAddress`](/react/hooks/use-resolve-xlm-name-by-address). --- # useSacAddress URL: https://docs.blux.cc/react/hooks/use-sac-address Derive the Stellar Asset Contract (SAC) id of a classic asset in React — synchronous and memoized. `useSacAddress` is the React wrapper around [`getSacAddress`](/javascript/core/getSacAddress). It returns the **Stellar Asset Contract (SAC)** id of a classic asset — native XLM or a `CODE:ISSUER` pair. Because the underlying derivation is **synchronous and local** (no network call, regardless of whether the SAC is deployed), this is **not** a TanStack Query — there's no loading state. The value is computed with `useMemo` and returned right away as `{ data, error }`. An invalid asset or missing network passphrase is captured into `error` rather than thrown during render. ## Import ```tsx ``` ## Usage Derive the SAC id of an issued asset: ```tsx function SacId() { const { data: sac, error } = useSacAddress("USDC:GA5Z....KZVN"); if (error) return

{error.message}

; return {sac}; // "C..." } ```
```tsx root.render( ); ```
It also accepts `"xlm"`/`"native"` or an `Asset` instance, and an optional network passphrase as the second argument: ```tsx // Native XLM on a specific network. const { data } = useSacAddress("xlm", networks.mainnet); ``` ### Chain into a metadata read A common flow is deriving the SAC, then reading its on-chain metadata with [`useTokenMetadata`](/react/hooks/use-token-metadata) once the id is known: ```tsx function AssetCard() { const { data: sac } = useSacAddress("USDC:GA5Z....KZVN"); const { data: meta } = useTokenMetadata(sac ?? "", undefined, { enabled: Boolean(sac), }); return

{meta?.symbol} · {meta?.decimals} decimals

; } ```
```tsx root.render( ); ```
Pass a **stable** `asset` — a string, or a memoized `Asset` instance — so the memo doesn't recompute on every render. A fresh `new Asset(...)` created inline in the component body changes identity each render. ## Parameters ### `asset` (required) `string | Asset` The asset: `"xlm"`/`"native"`, a `"CODE:ISSUER"` string, or an `Asset` instance. ### `network` `string | undefined` Network passphrase to derive against. Import `networks` from `@bluxcc/react` to select one. The SAC id is network-specific; omit to use the active network. ## Return Type `useSacAddress` returns a plain object — **not** a TanStack Query result: ```tsx type UseSacAddressResult = { // The SAC contract id (C…), or undefined when it can't be derived. data: string | undefined; // The error thrown while deriving, or null on success. error: Error | null; }; ``` | Property | Type | Description | |---|---|---| | `data` | `string \| undefined` | The SAC contract id (`C…`) on success, or `undefined` when derivation failed. | | `error` | `Error \| null` | The captured error (invalid asset, or no network passphrase available), or `null` on success. | There is no `isLoading` / `isSuccess` here — the result is available synchronously on first render. If you need to read the SAC's on-chain metadata, that read **is** async; feed `data` into [`useTokenMetadata`](/react/hooks/use-token-metadata). --- # useStrictReceivePaths URL: https://docs.blux.cc/react/hooks/use-strict-receive-paths Fetch strict receive payment paths in your React app using the Blux SDK. The `useStrictReceivePaths` hook returns available payment paths for a strict receive operation. `source`, `destinationAsset`, and `destinationAmount` are all required — the hook will not run without them. Import `Asset` from `@bluxcc/react`. When `source` is an account string, it accepts `G…`, `M…`, SEP-2 federation, or `.xlm`. See [address resolution](/javascript/core/address-resolution). ## Import ```tsx ``` ## Usage Basic usage with required arguments: ```tsx function App() { const source = "alice.xlm"; const destinationAsset = new Asset("USDC", "GA5Z....KZVN"); const destinationAmount = "10"; const { data } = useStrictReceivePaths([source, destinationAsset, destinationAmount]); } ``` ```tsx root.render( ); ``` With call-builder options and TanStack Query options: ```tsx function App() { const source = "GAUZ....NOWM"; const destinationAsset = new Asset("USDC", "GA5Z....KZVN"); const destinationAmount = "10"; const { data, refetch } = useStrictReceivePaths( [source, destinationAsset, destinationAmount], // Required arguments { limit: 20, order: "asc" }, // Core parameters { retry: 3, staleTime: 5000 }, // TanStack parameters ); } ``` ```tsx root.render( ); ``` Pass required arguments first, then core call-builder options, then TanStack Query options. The hook relies on this order to work correctly. ## Parameters ### `source` (required) `string | AssetArg[]` Either a source account ID or an array of assets to use as possible payment sources. ### `destinationAsset` (required) `Asset` The asset the destination account should receive. ### `destinationAmount` (required) `string` The exact amount the destination must receive, as a decimal string (e.g. `"100.00"`). ### `limit` `number | undefined` Number of records to return. ### `network` `string | undefined` The network to query. Omit to use the active network. ### `order` `'asc' | 'desc' | undefined` Sort order for the results. ## Query Options | Option | Type | Default | Description | |---|---|---|---| | `enabled` | `boolean` | `true` | Set to `false` to disable automatic fetching | | `staleTime` | `number \| Infinity` | `0` | Time in ms before data is considered stale | | `gcTime` | `number \| Infinity` | `300000` | Time in ms before inactive cache data is garbage collected | | `retry` | `boolean \| number` | `3` | How many times to retry on failure | | `retryDelay` | `number \| function` | — | Delay in ms between retry attempts | | `refetchInterval` | `number \| false \| function` | — | Continuously refetch at this interval in ms | | `refetchOnMount` | `boolean \| 'always'` | `true` | Refetch on component mount if data is stale | | `refetchOnWindowFocus` | `boolean \| 'always'` | `true` | Refetch when the window regains focus | | `refetchOnReconnect` | `boolean \| 'always'` | `true` | Refetch when network reconnects | | `refetchIntervalInBackground` | `boolean` | — | Keep refetching even when tab is in background | | `placeholderData` | `GetPaymentPathResult \| function` | — | Placeholder data shown while query is pending (not persisted to cache) | | `initialData` | `GetPaymentPathResult \| function` | — | Initial data for the cache (persisted) | | `initialDataUpdatedAt` | `number \| function` | — | Timestamp of when `initialData` was last updated | | `select` | `function` | — | Transform or select a subset of the returned data | | `notifyOnChangeProps` | `string[] \| 'all'` | — | Limit re-renders to specific property changes | | `structuralSharing` | `boolean \| function` | `true` | Retain references from old data for performance | | `networkMode` | `'online' \| 'always' \| 'offlineFirst'` | `'online'` | Controls when queries can run relative to network status | | `meta` | `Record` | — | Attach arbitrary metadata to the query cache entry | | `queryClient` | `QueryClient` | — | Use a custom QueryClient instead of the nearest context one | ## Return Type ### `data` `GetPaymentPathResult | undefined` ```tsx type GetPaymentPathResult = { builder: PathCallBuilder; // .next() and .prev() for pagination response: Horizon.ServerApi.CollectionPage; }; ``` ### Status Booleans | Property | Type | Description | |---|---|---| | `isPending` | `boolean` | No cached data and no completed fetch yet | | `isSuccess` | `boolean` | Query resolved successfully | | `isError` | `boolean` | Query failed | | `isLoading` | `boolean` | First fetch in-flight (`isFetching && isPending`) | | `isFetching` | `boolean` | Query function is currently executing | | `isRefetching` | `boolean` | Background refetch in progress | | `isFetched` | `boolean` | Query has been fetched at least once | | `isFetchedAfterMount` | `boolean` | Query fetched after component mounted | | `isStale` | `boolean` | Cached data is stale or older than `staleTime` | | `isPlaceholderData` | `boolean` | Currently showing placeholder data | | `isLoadingError` | `boolean` | Failed on the first fetch | | `isRefetchError` | `boolean` | Failed during a background refetch | | `isPaused` | `boolean` | Query wanted to fetch but was paused | ### Other Returns | Property | Type | Description | |---|---|---| | `status` | `'pending' \| 'success' \| 'error'` | Current query status | | `fetchStatus` | `'fetching' \| 'idle' \| 'paused'` | Current fetch status | | `error` | `null \| Error` | Error object if the query failed | | `dataUpdatedAt` | `number` | Timestamp of last successful fetch | | `errorUpdatedAt` | `number` | Timestamp of last error | | `errorUpdateCount` | `number` | Total number of errors | | `failureCount` | `number` | Failures since last success | | `failureReason` | `null \| Error` | Reason for last retry failure | | `refetch` | `function` | Manually trigger a refetch | --- # useStrictSendPaths URL: https://docs.blux.cc/react/hooks/use-strict-send-paths Fetch strict send payment paths in your React app using the Blux SDK. The `useStrictSendPaths` hook returns available payment paths for a strict send operation. `sourceAsset`, `sourceAmount`, and `destination` are all required — the hook will not run without them. Import `Asset` from `@bluxcc/react`. When `destination` is an account string, it accepts `G…`, `M…`, SEP-2 federation, or `.xlm`. See [address resolution](/javascript/core/address-resolution). ## Import ```tsx ``` ## Usage Basic usage with required arguments: ```tsx function App() { const sourceAsset = new Asset("USDC", "GA5Z....KZVN"); const sourceAmount = "100.00"; const destination = "alice.xlm"; const { data } = useStrictSendPaths([sourceAsset, sourceAmount, destination]); } ``` ```tsx root.render( ); ``` With call-builder options and TanStack Query options: ```tsx function App() { const sourceAsset = new Asset("USDC", "GA5Z....KZVN"); const sourceAmount = "100.00"; const destination = "GAUZ....NOWM"; const { data, refetch } = useStrictSendPaths( [sourceAsset, sourceAmount, destination], // Required arguments { limit: 20, order: "asc" }, // Core parameters { retry: 3, staleTime: 5000 }, // TanStack parameters ); } ``` ```tsx root.render( ); ``` Pass required arguments first, then core call-builder options, then TanStack Query options. The hook relies on this order to work correctly. ## Parameters ### `sourceAsset` (required) `Asset` The asset to send from the source account. ### `sourceAmount` (required) `string` The exact amount to send, as a decimal string (e.g. `"100.00"`). ### `destination` (required) `string | AssetArg[]` Either a destination account ID or an array of assets representing acceptable destination assets. ### `limit` `number | undefined` Number of records to return. ### `network` `string | undefined` The network to query. Omit to use the active network. ### `order` `'asc' | 'desc' | undefined` Sort order for the results. ## Query Options | Option | Type | Default | Description | |---|---|---|---| | `enabled` | `boolean` | `true` | Set to `false` to disable automatic fetching | | `staleTime` | `number \| Infinity` | `0` | Time in ms before data is considered stale | | `gcTime` | `number \| Infinity` | `300000` | Time in ms before inactive cache data is garbage collected | | `retry` | `boolean \| number` | `3` | How many times to retry on failure | | `retryDelay` | `number \| function` | — | Delay in ms between retry attempts | | `refetchInterval` | `number \| false \| function` | — | Continuously refetch at this interval in ms | | `refetchOnMount` | `boolean \| 'always'` | `true` | Refetch on component mount if data is stale | | `refetchOnWindowFocus` | `boolean \| 'always'` | `true` | Refetch when the window regains focus | | `refetchOnReconnect` | `boolean \| 'always'` | `true` | Refetch when network reconnects | | `refetchIntervalInBackground` | `boolean` | — | Keep refetching even when tab is in background | | `placeholderData` | `GetPaymentPathResult \| function` | — | Placeholder data shown while query is pending (not persisted to cache) | | `initialData` | `GetPaymentPathResult \| function` | — | Initial data for the cache (persisted) | | `initialDataUpdatedAt` | `number \| function` | — | Timestamp of when `initialData` was last updated | | `select` | `function` | — | Transform or select a subset of the returned data | | `notifyOnChangeProps` | `string[] \| 'all'` | — | Limit re-renders to specific property changes | | `structuralSharing` | `boolean \| function` | `true` | Retain references from old data for performance | | `networkMode` | `'online' \| 'always' \| 'offlineFirst'` | `'online'` | Controls when queries can run relative to network status | | `meta` | `Record` | — | Attach arbitrary metadata to the query cache entry | | `queryClient` | `QueryClient` | — | Use a custom QueryClient instead of the nearest context one | ## Return Type ### `data` `GetPaymentPathResult | undefined` ```tsx type GetPaymentPathResult = { builder: PathCallBuilder; // .next() and .prev() for pagination response: Horizon.ServerApi.CollectionPage; }; ``` ### Status Booleans | Property | Type | Description | |---|---|---| | `isPending` | `boolean` | No cached data and no completed fetch yet | | `isSuccess` | `boolean` | Query resolved successfully | | `isError` | `boolean` | Query failed | | `isLoading` | `boolean` | First fetch in-flight (`isFetching && isPending`) | | `isFetching` | `boolean` | Query function is currently executing | | `isRefetching` | `boolean` | Background refetch in progress | | `isFetched` | `boolean` | Query has been fetched at least once | | `isFetchedAfterMount` | `boolean` | Query fetched after component mounted | | `isStale` | `boolean` | Cached data is stale or older than `staleTime` | | `isPlaceholderData` | `boolean` | Currently showing placeholder data | | `isLoadingError` | `boolean` | Failed on the first fetch | | `isRefetchError` | `boolean` | Failed during a background refetch | | `isPaused` | `boolean` | Query wanted to fetch but was paused | ### Other Returns | Property | Type | Description | |---|---|---| | `status` | `'pending' \| 'success' \| 'error'` | Current query status | | `fetchStatus` | `'fetching' \| 'idle' \| 'paused'` | Current fetch status | | `error` | `null \| Error` | Error object if the query failed | | `dataUpdatedAt` | `number` | Timestamp of last successful fetch | | `errorUpdatedAt` | `number` | Timestamp of last error | | `errorUpdateCount` | `number` | Total number of errors | | `failureCount` | `number` | Failures since last success | | `failureReason` | `null \| Error` | Reason for last retry failure | | `refetch` | `function` | Manually trigger a refetch | --- # useSwap URL: https://docs.blux.cc/react/hooks/use-swap Swap one asset for another from React, powered by a TanStack Query mutation. `useSwap` is the React wrapper around [`swap`](/javascript/core/swap). It trades one asset for another through the Stellar **DEX** and **liquidity pools** — discovering the best path payment and applying a slippage guardrail for you — and exposes the call as a TanStack Query **mutation**. Named after wagmi's mutation hooks, it returns `swap` (fire-and-forget, an alias of `mutate`) and `swapAsync` (returns a promise, an alias of `mutateAsync`), alongside the usual `isPending`, `isSuccess`, `error`, and `data` state. A user must be connected — the connected account is the source. The optional `to` field accepts `G…`, `M…`, SEP-2 federation, or `.xlm`. A memo from a resolved record is applied unless you pass `memo` yourself. See [address resolution](/javascript/core/address-resolution). ## Import ```tsx ``` ## Usage Sell exactly 100 XLM for USDC when the user clicks a button. `exactIn` is the default, so you only describe the trade: ```tsx const USDC = "USDC:GA5Z....KZVN"; function SwapButton() { const { swap, isPending, error } = useSwap(); return ( <> {error &&

{error.message}

} ); } ```
```tsx root.render( ); ```
The mutation variables are the core [`SwapOptions`](/javascript/core/swap#type) verbatim, so every knob is just a field on the object you pass — `type` (`exactIn`/`exactOut`), `slippage`, `to`, `memo`, and `network`. ### Buy an exact amount Pass `type: "exactOut"` to fix the **received** side and let the spent amount float: ```tsx const { swap } = useSwap(); // Receive exactly 50 USDC, spending up to a slippage-bounded amount of XLM. swap({ fromAsset: "xlm", toAsset: "USDC:GA5Z....KZVN", amount: "50", type: "exactOut" }); ``` ### Await the result with `swapAsync` Use `swapAsync` when you want to `await` the submitted transaction — for example to deliver the proceeds to another account with tighter slippage and a memo: ```tsx const { swapAsync } = useSwap(); const tx = await swapAsync({ fromAsset: "USDC:GA5Z....KZVN", toAsset: "xlm", amount: "25", to: "GB...DEST", slippage: 0.01, // 1% memo: "cash out", }); console.log(tx.hash); ``` ### Refresh balances on success Pass any TanStack Mutation options (`onSuccess`, `onError`, `onSettled`, …). A common pattern is refetching [`useBalances`](/react/hooks/use-balances) once the swap lands: ```tsx function SwapPanel() { const { refetch } = useBalances(); const { swap, isPending } = useSwap({ onSuccess: () => refetch(), // pull fresh balances after the swap onError: (error) => console.error(error.message), }); return ( ); } ``` ```tsx root.render( ); ``` ## Parameters `useSwap` takes an optional TanStack **Mutation options** object (`onSuccess`, `onError`, `onSettled`, `retry`, …). The `mutationFn` is provided by the hook — you don't supply it. The mutation **variables** — what you pass to `swap(...)` / `swapAsync(...)` — are the core [`SwapOptions`](/javascript/core/swap#type): | Field | Type | Default | Description | |---|---|---|---| | `fromAsset` | `string \| Asset` | — | **Required.** Asset being sold. | | `toAsset` | `string \| Asset` | — | **Required.** Asset being bought; must differ from `fromAsset`. | | `amount` | `string \| number \| bigint` | — | **Required.** Fixed amount in decimal units; meaning depends on `type`. | | `type` | `"exactIn" \| "exactOut"` | `"exactIn"` | Which side of the trade is fixed. | | `to` | `string` | connected account | Recipient of the bought asset: `G…`/`M…`, SEP-2 address, or `.xlm` name. Omit for a self-swap. | | `slippage` | `number` | `0.005` | Max slippage as a fraction (`0.005` = 0.5%). | | `memo` | `string` | — | Optional text memo. | | `network` | `string` | active network | Network passphrase to swap on. | ## Return Type The full TanStack mutation result, plus the two wagmi-style aliases: | Property | Type | Description | |---|---|---| | `swap` | `function` | Fire-and-forget alias of `mutate`. Call `swap({ … })`. | | `swapAsync` | `function` | Promise-returning alias of `mutateAsync`. `await swapAsync({ … })`. | | `mutate` / `mutateAsync` | `function` | The underlying TanStack mutators. | | `data` | `ISubmittedTransaction \| undefined` | The [submitted transaction](/javascript/usage/send-transaction#return-value) on success. | | `isPending` | `boolean` | A swap is in flight (building, signing, or submitting). | | `isSuccess` | `boolean` | The most recent swap succeeded. | | `isError` | `boolean` | The most recent swap failed. | | `error` | `Error \| null` | The error from the last failed swap. | | `reset` | `function` | Clear the mutation back to its idle state. | A user must be connected before calling `swap` / `swapAsync` — the connected account is the source. Like every Blux write, it shows the confirmation modal before signing; handle rejection and validation failures via `onError` or a `try/catch` around `swapAsync`. See [`swap`](/javascript/core/swap#errors) for the full list of `BLUX:` errors. --- # useSwitchNetwork URL: https://docs.blux.cc/react/hooks/use-switch-network Change the active network in your React app using the Blux SDK. The `useSwitchNetwork` hook returns a `switchNetwork` function for changing the currently active network. Switching the active network affects components like the profile modal and hooks such as `useBalance`, `useAccount`, and `useTransactions` when no explicit `network` parameter is provided to them. ## Import ```tsx ``` ## Usage ```tsx const Comp = () => { const { switchNetwork } = useSwitchNetwork(); const changeNetwork = () => { switchNetwork(networks.mainnet); }; return (
); }; ``` ## Return Type ### `switchNetwork` `(network: string) => void` Call with a network value from the `networks` object to update the active network across your app. --- # useTokenMetadata URL: https://docs.blux.cc/react/hooks/use-token-metadata Read a SEP-41 token / Stellar Asset Contract's metadata in React, powered by TanStack Query. `useTokenMetadata` is the React wrapper around [`getTokenMetadata`](/javascript/core/getTokenMetadata). It reads a SEP-41 token / Stellar Asset Contract's `decimals`, `name`, `symbol`, and `owner` by simulating the contract's read-only entrypoints — **no account, signing, or fees** — and exposes the result as a TanStack Query, so you get caching, refetching, and loading states for free. The read works for a `C…` contract id or `.xlm`/SEP-2 name resolving to one. `owner` is `undefined` for contracts without an `owner()` function (notably Stellar Asset Contracts, which expose `admin()` instead). The query stays **disabled until a non-empty `address`** is provided, which makes it easy to chain after [`useSacAddress`](/react/hooks/use-sac-address). Invalid or unregistered names surface through `error`; see [address resolution](/javascript/core/address-resolution). ## Import ```tsx ``` ## Usage Read a token contract directly: ```tsx function TokenInfo() { const { data, isLoading, error } = useTokenMetadata( "token.xlm", ); if (isLoading) return

Loading…

; if (error) return

{error.message}

; // data → { decimals: 7, name: "USD Coin", symbol: "USDC", owner?: "G…" } return

{data?.name} ({data?.symbol})

; } ```
```tsx root.render( ); ```
### Derive a classic asset's SAC, then read it Pair it with [`useSacAddress`](/react/hooks/use-sac-address) to read a classic asset's metadata. Keep the query disabled until the SAC id is known: ```tsx function ClassicAsset() { const { data: sac } = useSacAddress("USDC:GA5Z....KZVN"); const { data: meta } = useTokenMetadata(sac ?? "", undefined, { enabled: Boolean(sac), }); return

{meta?.symbol} · {meta?.decimals} decimals

; } ```
```tsx root.render( ); ```
You can pass core options (currently just `network`) and TanStack Query options as the second and third arguments: ```tsx const { data } = useTokenMetadata( "CB64...N7OG", { network: networks.mainnet }, // core options { enabled: true, staleTime: 60000 }, // TanStack options ); ``` Always pass the address first, then core options, then TanStack Query options. The hook relies on this order to work correctly. ## Parameters ### `address` (required) `string` The token contract id (`C…`), e.g. a SAC from [`useSacAddress`](/react/hooks/use-sac-address) / [`getSacAddress`](/javascript/core/getSacAddress). The query is disabled while this is empty. ### `network` `string | undefined` Passed as `{ network }` in the second argument. The network to read from. Import `networks` from `@bluxcc/react` to select one. Omit to use the active network. ## Query Options These are passed as the third argument and map directly to TanStack Query options. | Option | Type | Default | Description | |---|---|---|---| | `enabled` | `boolean` | `true` | Set to `false` to disable automatic fetching. Also auto-disabled while `address` is empty. | | `staleTime` | `number \| Infinity` | `0` | Time in ms before data is considered stale | | `gcTime` | `number \| Infinity` | `300000` | Time in ms before inactive cache data is garbage collected | | `retry` | `boolean \| number` | `3` | How many times to retry on failure | | `retryDelay` | `number \| function` | — | Delay in ms between retry attempts | | `refetchInterval` | `number \| false \| function` | — | Continuously refetch at this interval in ms | | `refetchOnMount` | `boolean \| 'always'` | `true` | Refetch on component mount if data is stale | | `refetchOnWindowFocus` | `boolean \| 'always'` | `true` | Refetch when the window regains focus | | `refetchOnReconnect` | `boolean \| 'always'` | `true` | Refetch when network reconnects | | `refetchIntervalInBackground` | `boolean` | — | Keep refetching even when tab is in background | | `placeholderData` | `TokenMetadata \| function` | — | Placeholder data shown while query is pending (not persisted to cache) | | `initialData` | `TokenMetadata \| function` | — | Initial data for the cache (persisted) | | `initialDataUpdatedAt` | `number \| function` | — | Timestamp of when `initialData` was last updated | | `select` | `function` | — | Transform or select a subset of the returned data | | `notifyOnChangeProps` | `string[] \| 'all'` | — | Limit re-renders to specific property changes | | `structuralSharing` | `boolean \| function` | `true` | Retain references from old data for performance | | `networkMode` | `'online' \| 'always' \| 'offlineFirst'` | `'online'` | Controls when queries can run relative to network status | | `meta` | `Record` | — | Attach arbitrary metadata to the query cache entry | | `queryClient` | `QueryClient` | — | Use a custom QueryClient instead of the nearest context one | ## Return Type ### `data` `TokenMetadata | undefined` ```tsx type TokenMetadata = { decimals: number; // number of decimal places the token uses name: string; // human-readable token name symbol: string; // token symbol / code owner?: string; // owner() when present; undefined for a SAC }; ``` ### Status Booleans | Property | Type | Description | |---|---|---| | `isPending` | `boolean` | No cached data and no completed fetch yet | | `isSuccess` | `boolean` | Query resolved successfully | | `isError` | `boolean` | Query failed | | `isLoading` | `boolean` | First fetch in-flight (`isFetching && isPending`) | | `isFetching` | `boolean` | Query function is currently executing | | `isRefetching` | `boolean` | Background refetch in progress | | `isFetched` | `boolean` | Query has been fetched at least once | | `isFetchedAfterMount` | `boolean` | Query fetched after component mounted | | `isStale` | `boolean` | Cached data is stale or older than `staleTime` | | `isPlaceholderData` | `boolean` | Currently showing placeholder data | | `isLoadingError` | `boolean` | Failed on the first fetch | | `isRefetchError` | `boolean` | Failed during a background refetch | | `isPaused` | `boolean` | Query wanted to fetch but was paused | ### Other Returns | Property | Type | Description | |---|---|---| | `status` | `'pending' \| 'success' \| 'error'` | Current query status | | `fetchStatus` | `'fetching' \| 'idle' \| 'paused'` | Current fetch status | | `error` | `null \| Error` | Error object if the query failed | | `dataUpdatedAt` | `number` | Timestamp of last successful fetch | | `errorUpdatedAt` | `number` | Timestamp of last error | | `errorUpdateCount` | `number` | Total number of errors | | `failureCount` | `number` | Failures since last success | | `failureReason` | `null \| Error` | Reason for last retry failure | | `refetch` | `function` | Manually trigger a refetch | This is a read-only simulation, so the user does not need to be connected. See [`getTokenMetadata`](/javascript/core/getTokenMetadata#errors) for the `BLUX:` errors that surface on `error`. --- # useTradeAggregation URL: https://docs.blux.cc/react/hooks/use-trade-aggregation Fetch aggregated trade data for an asset pair in your React app using the Blux SDK. The `useTradeAggregation` hook returns aggregated trade data for a base/counter asset pair over a configurable time window. All six arguments are required — the hook will not run without them. Import `Asset` from `@bluxcc/react`. ## Import ```tsx ``` ## Usage Basic usage with required arguments: ```tsx function App() { const base = new Asset("USDC", "GA5Z....4KZVN"); const counter = Asset.native(); const start_time = 1622505600000; // ms const end_time = 1622592000000; // ms const resolution = 3600000; // 1 hour in ms const offset = 0; const { data } = useTradeAggregation([base, counter, start_time, end_time, resolution, offset]); } ``` ```tsx root.render( ); ``` With call-builder options and TanStack Query options: ```tsx function App() { const { data, refetch } = useTradeAggregation( [ // Required arguments new Asset("USDC", "GA5Z....KZVN"), new Asset("EURT", "GAP5....ZPBR"), 1622505600000, 1622592000000, 3600000, 0, ], { cursor: "9876543210", limit: 200, order: "asc" }, // Core parameters { retry: 1, staleTime: 60000 }, // TanStack parameters ); } ``` ```tsx root.render( ); ``` Pass required arguments first, then core call-builder options, then TanStack Query options. The hook relies on this order to work correctly. ## Parameters ### `base` (required) `Asset` The base asset for the aggregation. ### `counter` (required) `Asset` The counter asset for the aggregation. ### `start_time` (required) `number` Unix timestamp in milliseconds for the start of the aggregation window. ### `end_time` (required) `number` Unix timestamp in milliseconds for the end of the aggregation window. ### `resolution` (required) `number` Bucket size in milliseconds for each aggregation point (e.g. `3600000` for 1 hour). ### `offset` (required) `number` Offset in milliseconds added to the aggregation window start, used to align buckets. Pass `0` for no offset. ### `cursor` `string | undefined` Pagination cursor for fetching the next or previous page. ### `limit` `number | undefined` Number of records to return per page. ### `network` `string | undefined` The network to query. Omit to use the active network. ### `order` `'asc' | 'desc' | undefined` Sort order for the results. ## Query Options | Option | Type | Default | Description | |---|---|---|---| | `enabled` | `boolean` | `true` | Set to `false` to disable automatic fetching | | `staleTime` | `number \| Infinity` | `0` | Time in ms before data is considered stale | | `gcTime` | `number \| Infinity` | `300000` | Time in ms before inactive cache data is garbage collected | | `retry` | `boolean \| number` | `3` | How many times to retry on failure | | `retryDelay` | `number \| function` | — | Delay in ms between retry attempts | | `refetchInterval` | `number \| false \| function` | — | Continuously refetch at this interval in ms | | `refetchOnMount` | `boolean \| 'always'` | `true` | Refetch on component mount if data is stale | | `refetchOnWindowFocus` | `boolean \| 'always'` | `true` | Refetch when the window regains focus | | `refetchOnReconnect` | `boolean \| 'always'` | `true` | Refetch when network reconnects | | `refetchIntervalInBackground` | `boolean` | — | Keep refetching even when tab is in background | | `placeholderData` | `GetTradeAggregationResult \| function` | — | Placeholder data shown while query is pending (not persisted to cache) | | `initialData` | `GetTradeAggregationResult \| function` | — | Initial data for the cache (persisted) | | `initialDataUpdatedAt` | `number \| function` | — | Timestamp of when `initialData` was last updated | | `select` | `function` | — | Transform or select a subset of the returned data | | `notifyOnChangeProps` | `string[] \| 'all'` | — | Limit re-renders to specific property changes | | `structuralSharing` | `boolean \| function` | `true` | Retain references from old data for performance | | `networkMode` | `'online' \| 'always' \| 'offlineFirst'` | `'online'` | Controls when queries can run relative to network status | | `meta` | `Record` | — | Attach arbitrary metadata to the query cache entry | | `queryClient` | `QueryClient` | — | Use a custom QueryClient instead of the nearest context one | ## Return Type ### `data` `GetTradeAggregationResult | undefined` ```tsx type GetTradeAggregationResult = any; ``` ### Status Booleans | Property | Type | Description | |---|---|---| | `isPending` | `boolean` | No cached data and no completed fetch yet | | `isSuccess` | `boolean` | Query resolved successfully | | `isError` | `boolean` | Query failed | | `isLoading` | `boolean` | First fetch in-flight (`isFetching && isPending`) | | `isFetching` | `boolean` | Query function is currently executing | | `isRefetching` | `boolean` | Background refetch in progress | | `isFetched` | `boolean` | Query has been fetched at least once | | `isFetchedAfterMount` | `boolean` | Query fetched after component mounted | | `isStale` | `boolean` | Cached data is stale or older than `staleTime` | | `isPlaceholderData` | `boolean` | Currently showing placeholder data | | `isLoadingError` | `boolean` | Failed on the first fetch | | `isRefetchError` | `boolean` | Failed during a background refetch | | `isPaused` | `boolean` | Query wanted to fetch but was paused | ### Other Returns | Property | Type | Description | |---|---|---| | `status` | `'pending' \| 'success' \| 'error'` | Current query status | | `fetchStatus` | `'fetching' \| 'idle' \| 'paused'` | Current fetch status | | `error` | `null \| Error` | Error object if the query failed | | `dataUpdatedAt` | `number` | Timestamp of last successful fetch | | `errorUpdatedAt` | `number` | Timestamp of last error | | `errorUpdateCount` | `number` | Total number of errors | | `failureCount` | `number` | Failures since last success | | `failureReason` | `null \| Error` | Reason for last retry failure | | `refetch` | `function` | Manually trigger a refetch | --- # useTrades URL: https://docs.blux.cc/react/hooks/use-trades Fetch a paginated list of Stellar trades in your React app using the Blux SDK. The `useTrades` hook returns a paginated list of Stellar trades. All parameters are optional — called with no arguments it returns the latest trades from the network. `forAccount` accepts `G…`, `M…`, SEP-2 federation, or `.xlm`. See [address resolution](/javascript/core/address-resolution). ## Import ```tsx ``` ## Usage Called with no arguments: ```tsx function App() { const { data } = useTrades(); } ``` ```tsx root.render( ); ``` Combine with `useBlux` to fetch trades only when the user is authenticated: ```tsx function App() { const { user, isAuthenticated } = useBlux(); const { data } = useTrades( { forAccount: user?.address }, { enabled: isAuthenticated } ); } ``` ```tsx root.render( ); ``` With filters and TanStack Query options: ```tsx function App() { const { data, isStale } = useTrades( { forOffer: "1234567890123456" }, { retry: 2, staleTime: 60000 } ); } ``` ```tsx root.render( ); ``` Always pass core parameters first, then TanStack Query options. The hook relies on this order to work correctly. ## Parameters ### `forAssetPair` `[base: AssetArg, counter: AssetArg] | undefined` Filter trades for a specific asset pair. Import `Asset` from `@bluxcc/react`. ### `forOffer` `string | undefined` Filter trades created by a specific offer ID. ### `forType` `Horizon.ServerApi.TradeType | undefined` Filter trades by type (e.g. `"buy"` or `"sell"`). ### `forLiquidityPool` `string | undefined` Filter trades that occurred on a specific liquidity pool. ### `forAccount` `string | undefined` Fetch trades for a specific Stellar account ID. ### `cursor` `string | undefined` Pagination cursor for fetching the next or previous page. ### `limit` `number | undefined` Number of records to return per page. ### `network` `string | undefined` The network to query. Omit to use the active network. ### `order` `'asc' | 'desc' | undefined` Sort order for the results. ## Query Options | Option | Type | Default | Description | |---|---|---|---| | `enabled` | `boolean` | `true` | Set to `false` to disable automatic fetching | | `staleTime` | `number \| Infinity` | `0` | Time in ms before data is considered stale | | `gcTime` | `number \| Infinity` | `300000` | Time in ms before inactive cache data is garbage collected | | `retry` | `boolean \| number` | `3` | How many times to retry on failure | | `retryDelay` | `number \| function` | — | Delay in ms between retry attempts | | `refetchInterval` | `number \| false \| function` | — | Continuously refetch at this interval in ms | | `refetchOnMount` | `boolean \| 'always'` | `true` | Refetch on component mount if data is stale | | `refetchOnWindowFocus` | `boolean \| 'always'` | `true` | Refetch when the window regains focus | | `refetchOnReconnect` | `boolean \| 'always'` | `true` | Refetch when network reconnects | | `refetchIntervalInBackground` | `boolean` | — | Keep refetching even when tab is in background | | `placeholderData` | `GetTradesResult \| function` | — | Placeholder data shown while query is pending (not persisted to cache) | | `initialData` | `GetTradesResult \| function` | — | Initial data for the cache (persisted) | | `initialDataUpdatedAt` | `number \| function` | — | Timestamp of when `initialData` was last updated | | `select` | `function` | — | Transform or select a subset of the returned data | | `notifyOnChangeProps` | `string[] \| 'all'` | — | Limit re-renders to specific property changes | | `structuralSharing` | `boolean \| function` | `true` | Retain references from old data for performance | | `networkMode` | `'online' \| 'always' \| 'offlineFirst'` | `'online'` | Controls when queries can run relative to network status | | `meta` | `Record` | — | Attach arbitrary metadata to the query cache entry | | `queryClient` | `QueryClient` | — | Use a custom QueryClient instead of the nearest context one | ## Return Type ### `data` `GetTradesResult | undefined` ```tsx type GetTradesResult = { builder: TradesCallBuilder; // .next() and .prev() for pagination response: Horizon.ServerApi.CollectionPage; }; ``` ### Status Booleans | Property | Type | Description | |---|---|---| | `isPending` | `boolean` | No cached data and no completed fetch yet | | `isSuccess` | `boolean` | Query resolved successfully | | `isError` | `boolean` | Query failed | | `isLoading` | `boolean` | First fetch in-flight (`isFetching && isPending`) | | `isFetching` | `boolean` | Query function is currently executing | | `isRefetching` | `boolean` | Background refetch in progress | | `isFetched` | `boolean` | Query has been fetched at least once | | `isFetchedAfterMount` | `boolean` | Query fetched after component mounted | | `isStale` | `boolean` | Cached data is stale or older than `staleTime` | | `isPlaceholderData` | `boolean` | Currently showing placeholder data | | `isLoadingError` | `boolean` | Failed on the first fetch | | `isRefetchError` | `boolean` | Failed during a background refetch | | `isPaused` | `boolean` | Query wanted to fetch but was paused | ### Other Returns | Property | Type | Description | |---|---|---| | `status` | `'pending' \| 'success' \| 'error'` | Current query status | | `fetchStatus` | `'fetching' \| 'idle' \| 'paused'` | Current fetch status | | `error` | `null \| Error` | Error object if the query failed | | `dataUpdatedAt` | `number` | Timestamp of last successful fetch | | `errorUpdatedAt` | `number` | Timestamp of last error | | `errorUpdateCount` | `number` | Total number of errors | | `failureCount` | `number` | Failures since last success | | `failureReason` | `null \| Error` | Reason for last retry failure | | `refetch` | `function` | Manually trigger a refetch | --- # useTransactions URL: https://docs.blux.cc/react/hooks/use-transactions Fetch a paginated list of Stellar transactions in your React app using the Blux SDK. The `useTransactions` hook returns a paginated list of Stellar transactions. All parameters are optional — called with no arguments it returns the latest transactions from the network. `forAccount` accepts `G…`, `M…`, SEP-2 federation, or `.xlm`. See [address resolution](/javascript/core/address-resolution). ## Import ```tsx ``` ## Usage Called with no arguments: ```tsx function App() { const { data } = useTransactions(); } ``` ```tsx root.render( ); ``` Combine with `useBlux` to fetch transactions only when the user is authenticated: ```tsx function App() { const { user, isAuthenticated } = useBlux(); const { data } = useTransactions( { forAccount: user?.address }, { enabled: isAuthenticated } ); } ``` ```tsx root.render( ); ``` With filters and TanStack Query options: ```tsx function App() { const { data, isStale } = useTransactions( { forLedger: 60221517 }, { retry: 2, staleTime: 60000 } ); } ``` ```tsx root.render( ); ``` Always pass core parameters first, then TanStack Query options. The hook relies on this order to work correctly. ## Parameters ### `forAccount` `string | undefined` Fetch transactions for a specific Stellar account ID. ### `forClaimableBalance` `string | undefined` Fetch transactions related to a specific claimable balance ID. ### `forLedger` `number | string | undefined` Fetch transactions included in a specific ledger sequence. ### `forLiquidityPool` `string | undefined` Fetch transactions related to a specific liquidity pool ID. ### `includeFailed` `boolean | undefined` When `true`, includes failed transactions in the results. ### `cursor` `string | undefined` Pagination cursor for fetching the next or previous page. ### `limit` `number | undefined` Number of records to return per page. ### `network` `string | undefined` The network to query. Omit to use the active network. ### `order` `'asc' | 'desc' | undefined` Sort order for the results. ## Query Options | Option | Type | Default | Description | |---|---|---|---| | `enabled` | `boolean` | `true` | Set to `false` to disable automatic fetching | | `staleTime` | `number \| Infinity` | `0` | Time in ms before data is considered stale | | `gcTime` | `number \| Infinity` | `300000` | Time in ms before inactive cache data is garbage collected | | `retry` | `boolean \| number` | `3` | How many times to retry on failure | | `retryDelay` | `number \| function` | — | Delay in ms between retry attempts | | `refetchInterval` | `number \| false \| function` | — | Continuously refetch at this interval in ms | | `refetchOnMount` | `boolean \| 'always'` | `true` | Refetch on component mount if data is stale | | `refetchOnWindowFocus` | `boolean \| 'always'` | `true` | Refetch when the window regains focus | | `refetchOnReconnect` | `boolean \| 'always'` | `true` | Refetch when network reconnects | | `refetchIntervalInBackground` | `boolean` | — | Keep refetching even when tab is in background | | `placeholderData` | `GetTransactionsResult \| function` | — | Placeholder data shown while query is pending (not persisted to cache) | | `initialData` | `GetTransactionsResult \| function` | — | Initial data for the cache (persisted) | | `initialDataUpdatedAt` | `number \| function` | — | Timestamp of when `initialData` was last updated | | `select` | `function` | — | Transform or select a subset of the returned data | | `notifyOnChangeProps` | `string[] \| 'all'` | — | Limit re-renders to specific property changes | | `structuralSharing` | `boolean \| function` | `true` | Retain references from old data for performance | | `networkMode` | `'online' \| 'always' \| 'offlineFirst'` | `'online'` | Controls when queries can run relative to network status | | `meta` | `Record` | — | Attach arbitrary metadata to the query cache entry | | `queryClient` | `QueryClient` | — | Use a custom QueryClient instead of the nearest context one | ## Return Type ### `data` `GetTransactionsResult | undefined` ```tsx type GetTransactionsResult = { builder: TransactionCallBuilder; // .next() and .prev() for pagination response: Horizon.ServerApi.CollectionPage; }; ``` ### Status Booleans | Property | Type | Description | |---|---|---| | `isPending` | `boolean` | No cached data and no completed fetch yet | | `isSuccess` | `boolean` | Query resolved successfully | | `isError` | `boolean` | Query failed | | `isLoading` | `boolean` | First fetch in-flight (`isFetching && isPending`) | | `isFetching` | `boolean` | Query function is currently executing | | `isRefetching` | `boolean` | Background refetch in progress | | `isFetched` | `boolean` | Query has been fetched at least once | | `isFetchedAfterMount` | `boolean` | Query fetched after component mounted | | `isStale` | `boolean` | Cached data is stale or older than `staleTime` | | `isPlaceholderData` | `boolean` | Currently showing placeholder data | | `isLoadingError` | `boolean` | Failed on the first fetch | | `isRefetchError` | `boolean` | Failed during a background refetch | | `isPaused` | `boolean` | Query wanted to fetch but was paused | ### Other Returns | Property | Type | Description | |---|---|---| | `status` | `'pending' \| 'success' \| 'error'` | Current query status | | `fetchStatus` | `'fetching' \| 'idle' \| 'paused'` | Current fetch status | | `error` | `null \| Error` | Error object if the query failed | | `dataUpdatedAt` | `number` | Timestamp of last successful fetch | | `errorUpdatedAt` | `number` | Timestamp of last error | | `errorUpdateCount` | `number` | Total number of errors | | `failureCount` | `number` | Failures since last success | | `failureReason` | `null \| Error` | Reason for last retry failure | | `refetch` | `function` | Manually trigger a refetch | --- # useTransfer URL: https://docs.blux.cc/react/hooks/use-transfer Send XLM, issued assets, or SEP-41 tokens from React. `useTransfer` wraps [`transfer`](/javascript/core/transfer) in a TanStack mutation. It exposes `transfer` for fire-and-forget calls and `transferAsync` when you need to await the submitted transaction. ```tsx function SendButton() { const { transfer, isPending, error } = useTransfer(); return ( <> {error &&

{error.message}

} ); } ``` For classic assets, `to` accepts `G…`, `M…`, SEP-2 federation, or `.xlm`. On the SEP-41 token path it accepts `G…`, `C…`, SEP-2, or `.xlm`; muxed `M…` addresses are not Soroban addresses. The `token` field accepts a `C…` id or name resolving to one: ```tsx const { transferAsync } = useTransfer(); const transaction = await transferAsync({ token: "token.xlm", to: "alice.xlm", amount: "10000000", // integer token base units }); ``` Invalid or unregistered names are returned through the mutation's `error` or reject `transferAsync`. See [address resolution](/javascript/core/address-resolution) for mainnet/testnet behavior and SEP-2 memos. All classic-asset, claimable-balance, memo, and network options are identical to the core [`TransferOptions`](/javascript/core/transfer#type). --- # useWriteContract URL: https://docs.blux.cc/react/hooks/use-write-contract Invoke state-changing Soroban contract methods from React, powered by TanStack Query. `useWriteContract` is the React wrapper around [`writeContract`](/javascript/core/writeContract). It invokes a state-changing **Soroban** contract method, prompting the connected user to sign, and exposes the call as a TanStack Query **mutation** — giving you `mutate`/`mutateAsync`, plus `isPending`, `isSuccess`, and `error` states. ## Import ```tsx ``` ## Native contract arguments Pass ordinary JavaScript values in the same order as the contract function's parameters. Blux reads the deployed contract spec and encodes each value as the expected Soroban type, so `args` does not require `ToScVal`. Use strings for addresses, strings, and symbols; booleans for `bool`; `Uint8Array` for bytes; and arrays for vectors or tuples. Integers accept safe numbers, `bigint` values, or decimal strings. Prefer `bigint` or a decimal string for wide integers such as `i128`. The contract `address` and every ABI-declared `Address` argument accept `.xlm` names and SEP-2 federation addresses, including address values nested in contract-defined structures. See [address resolution](/javascript/core/address-resolution). Pre-encoded `xdr.ScVal` arguments remain supported for existing integrations, but manual encoding is optional. ## Usage Call a token's `transfer` method when the user clicks a button: ```tsx const TOKEN = "CB64D3G7SM2RTH6JSGG34DDTFTQ5CFDKVDZJZSODMCX4NJ2HV2KN7OG"; function TransferButton() { const { user } = useBlux(); const { mutate, isPending } = useWriteContract(); const transfer = () => { if (!user) return; mutate({ call: { address: TOKEN, fn: "transfer", args: [ user.address, // from: Address "bob.xlm", // to: Address "1000000000", // amount: i128 ], }, }); }; return ( ); } ``` ```tsx root.render( ); ``` The mutation variables are `{ call, options }`, where `call` is the contract call and `options` can carry a `network`. Use `mutateAsync` if you prefer to `await` the result. Pass the decoded contract return type as the hook generic: ```tsx const { mutateAsync } = useWriteContract(); const result = await mutateAsync({ call: { address: TOKEN, fn: "mint", args: ["alice.xlm", "1000000000"], }, options: { network: networks.mainnet }, }); const minted = await result.returnValue(); // bigint | null ``` Because the ABI is discovered at runtime, TypeScript cannot infer this value from `address`, `fn`, and `network` strings. Without a generic, `returnValue()` is `unknown | null`; it is `null` for a void function. A user must be connected before calling the mutation — the connected account is the transaction source. Handle rejection and simulation failures via the mutation's `onError` callback or a `try/catch` around `mutateAsync`. --- # Usage URL: https://docs.blux.cc/react/usage Learn how to authenticate users, manage profiles, and submit transactions with Blux. Blux provides ready-made UI flows through `useBlux` and dedicated [white-label login hooks](/react/usage/white-label-login) for custom authentication screens. Both require the `BluxProvider`. ## Quick Example ```tsx function App() { const { login, logout, sendTransaction, isAuthenticated, user } = useBlux(); } ``` Use `useBlux` for the hosted login modal and authenticated session state. For custom login controls, import `useLoginEmail`, `useLoginSms`, `useLoginOAuth`, `useLoginPasskey`, or `useLoginWallet`. --- {getPageTreePeers(source.getPageTree(), '/react/usage').map((peer) => ( {peer.description} ))} --- # Fund Me URL: https://docs.blux.cc/react/usage/fund-me Let users on-ramp fiat into crypto straight to their Stellar wallet from React. Blux ships with a built-in **Fund Me** modal — an on-ramp flow that lets users buy crypto with fiat and have it delivered directly to their connected Stellar wallet. The modal lists supported on-ramp providers (such as **MoonPay**). Open it by calling `fundMe()` from the `useBlux` hook. ## Import ```tsx ``` ## Usage ```tsx function FundButton() { const { fundMe, isAuthenticated } = useBlux(); return ( ); } ``` `fundMe` takes no arguments — it opens the modal for the currently connected user. The user must be authenticated before opening the Fund Me modal, since funds are delivered to their connected wallet. Gate the call behind `isAuthenticated`. --- # Login URL: https://docs.blux.cc/react/usage/login Authenticate users in your app with Blux's built-in login modal. Blux provides an out-of-the-box login modal so you can onboard users without building your own auth UI. Call `login()` from the `useBlux` hook to trigger it. ## Import ```tsx ``` ## Usage ```tsx function LoginButton() { const { login, isReady, isAuthenticated } = useBlux(); const disableLogin = !isReady || (isReady && isAuthenticated); return ( ); } ``` Keep the login button disabled until `isReady` is `true` to avoid triggering the modal before Blux has finished detecting available wallets. ## Key Fields The `useBlux` hook provides these fields for managing authentication state: | Field | Type | Description | |---|---|---| | `isReady` | `boolean` | `false` until Blux has finished checking for available wallets, then `true` | | `isAuthenticated` | `boolean` | `true` after a successful login, resets to `false` on logout | | `user` | `object \| null` | User info (address, connection method) after login; `null` otherwise | | `login` | `() => void` | Opens the wallet selection modal | | `logout` | `() => void` | Signs the user out, resetting `isAuthenticated` and `user` | ## Screenshots ![Login modal](/img/Login.png) --- # Profile URL: https://docs.blux.cc/react/usage/profile Display and manage the connected user's profile using the Blux SDK. Blux provides a built-in profile modal that displays account information for the connected user. Open it by calling `profile()` from the `useBlux` hook. ## Import ```tsx ``` ## Usage ```tsx function ProfileButton() { const { profile, isAuthenticated } = useBlux(); return ( ); } ``` ## Screenshots ![Profile modal](/img/Profile.png) --- # Send Transaction URL: https://docs.blux.cc/react/usage/send-transaction Sign and submit Stellar transactions from your React app using the Blux SDK. Use the `sendTransaction` function from the `useBlux` hook to **sign** a transaction with the connected wallet and **submit** it to the network. By default Blux shows a confirmation modal displaying the transaction details, estimated fee, and submitting account before the user approves. If you only want to sign a transaction without submitting it, use [`signTransaction`](/react/usage/sign-transaction) instead. ## Import ```tsx ``` ## Auto-detected transaction type `sendTransaction` inspects the transaction and handles each type correctly — you don't choose the path: - **Classic transactions** (payments, trustlines, offers, account operations, path payments, …) are submitted to Horizon and confirmed immediately. - **Soroban transactions** (smart-contract calls) are submitted via Soroban RPC and then polled until the network finalizes them (typically a few seconds). The value the contract function returned is decoded and made available on the result. There is no separate `waitForTransaction`: classic transactions don't need waiting, and Soroban transactions are waited on for you. ## Type ```tsx type IOptions = { // Network passphrase to sign/submit against. Defaults to the active network. network?: string; }; const sendTransaction: ( xdr: string, options?: IOptions, ) => Promise; ``` | Parameter | Type | Description | |---|---|---| | `xdr` | `string` | Base64-encoded XDR string of the transaction | | `options.network` | `string` | Network to submit on — omit to use the active network | ### Return value ```tsx interface ISubmittedTransaction { // The transaction hash. hash: string; // Resolves to the value the invoked contract function returned, decoded to a // native JS value. Resolves to `null` for classic transactions and for // Soroban calls whose function returns nothing (void). Always a promise. returnValue: () => Promise; // The underlying response object, for advanced use: // - classic: Horizon SubmitTransactionResponse // - soroban: the finalized Soroban RPC transaction (GetSuccessfulTransactionResponse) raw: SubmitTransactionResponse | GetSuccessfulTransactionResponse; } ``` **Migration note:** the resolved value is now the `ISubmittedTransaction` envelope, and the `isSoroban` option has been removed — the type is detected for you. `result.hash` works for both types; classic callers who previously read Horizon fields directly off the result (e.g. `result.ledger`, `result.successful`) should now read them from `result.raw`. ## Usage ```tsx function SendButton({ xdr }: { xdr: string }) { const { sendTransaction } = useBlux(); const sendTx = async () => { try { const result = await sendTransaction(xdr); console.log(result.hash); console.log(await result.returnValue()); // null for classic txs } catch (error) { console.error("Something went wrong!", error); } }; return ; } ``` For Soroban contract calls, prefer the [`useWriteContract`](/react/hooks/use-write-contract) hook, which builds, simulates, assembles, signs, submits, and waits — resolving to the same `ISubmittedTransaction`. ## Errors `sendTransaction` rejects with `BLUX:`-prefixed messages: | Message | Cause | |---|---| | `BLUX: User is not authenticated.` | No user is logged in. | | `BLUX: Blux modal is open elsewhere.` | Another Blux flow is already open. | | `BLUX: Invalid XDR` | The XDR can't be parsed for the given network. | | `BLUX: Could not find the connected wallet.` | The connected wallet couldn't be resolved. | | `BLUX: Failed to submit transaction: …` | RPC rejected the transaction (`ERROR`). | | `BLUX: The network is busy, please resubmit the transaction.` | RPC returned `TRY_AGAIN_LATER`. | | `BLUX: Transaction failed on-chain.` | Submitted but failed during execution. | | `BLUX: Timed out waiting for transaction to finalize.` | Not finalized within ~30s. | To skip the confirmation modal and build your own flow, set `showWalletUIs: false` in your `BluxProvider` configuration. The resolved value is identical either way. ## Screenshots ![Send Transaction modal](/img/SendTransaction.png) --- # Sign Auth Entry URL: https://docs.blux.cc/react/usage/sign-auth-entry Sign a Soroban authorization entry from your React app using the Blux SDK. Use the `signAuthEntry` function from the `useBlux` hook to ask the connected wallet to sign a single **Soroban authorization entry**. It resolves to the signed entry as a base-64 XDR string. This is a low-level building block for advanced Soroban flows — multi-party authorization, signing on behalf of a contract account, or assembling `invokeHostFunction` authorization yourself before submitting. For ordinary contract calls you don't need this: [`useWriteContract`](/react/hooks/use-write-contract) and [`sendTransaction`](/react/usage/send-transaction) handle authorization for you. ## Import ```tsx ``` ## Type ```tsx type IOptions = { // Network passphrase to sign against. Defaults to the active network. network: string; }; const signAuthEntry: ( authEntry: string, options?: IOptions, ) => Promise; // the signed auth entry (base-64 XDR) ``` | Parameter | Type | Description | |---|---|---| | `authEntry` | `string` | Base64-encoded authorization entry (`HashIdPreimage`) to sign | | `options.network` | `string` | Network to sign against — omit to use the active network | ## Usage ```tsx function SignAuthEntryButton({ authEntry }: { authEntry: string }) { const { signAuthEntry } = useBlux(); const handleSign = async () => { try { const signedAuthEntry = await signAuthEntry(authEntry); // `signedAuthEntry` is the signed entry as a base-64 XDR string. // Attach it to your Soroban operation's authorization before submitting. console.log(signedAuthEntry); } catch (error) { console.error("Signing failed:", error); } }; return ; } ``` ## Errors `signAuthEntry` rejects with `BLUX:`-prefixed messages: | Message | Cause | |---|---| | `BLUX: User is not authenticated.` | No user is logged in. | | `BLUX: Blux modal is open elsewhere.` | Another Blux flow is already open. | | `BLUX: Could not find the connected wallet.` | The connected wallet couldn't be resolved. | | `BLUX: Wallet does not support signAuthEntry.` | The connected wallet has no `signAuthEntry` capability. | Not every wallet supports signing auth entries. When the connected wallet lacks the capability, the call rejects with `BLUX: Wallet does not support signAuthEntry.` — handle this in your `try/catch`. To skip the confirmation modal and build your own flow, set `showWalletUIs: false` in your `BluxProvider` configuration. The signed entry returned is identical either way. --- # Sign Message URL: https://docs.blux.cc/react/usage/sign-message Request a signed message from the user's wallet using the Blux SDK. Use `signMessage` from the `useBlux` hook to request a message signature from the connected user's wallet. This is useful for verifying ownership of an account without submitting a transaction. ## Import ```tsx ``` ## Usage ```tsx function SignButton() { const { signMessage } = useBlux(); const handleSign = async () => { try { const signature = await signMessage("Hello from Blux!"); console.log("Signature:", signature); } catch (error) { console.error("Signing failed:", error); } }; return ; } ``` ## Screenshots ![Sign Message modal](/img/SignMessage.png) --- # Sign Transaction URL: https://docs.blux.cc/react/usage/sign-transaction Sign a transaction in your React app without submitting it, using the Blux SDK. Use the `signTransaction` function from the `useBlux` hook to sign a transaction with the connected wallet **without submitting it**. It resolves to the signed transaction envelope (a base-64 XDR string). Use this when you want to submit it yourself, store it, send it to a backend, or pass it to a co-signer for multi-signature. If you want Blux to sign **and** submit in one step, use [`sendTransaction`](/react/usage/send-transaction) instead. | Method | Signs? | Submits to network? | Returns | |---|---|---|---| | `sendTransaction(xdr, options?)` | ✅ | ✅ | `Promise` | | `signTransaction(xdr, options?)` | ✅ | ❌ | `Promise` (signed XDR) | ## Import ```tsx ``` ## Type ```tsx type IOptions = { // Network passphrase to sign against. Defaults to the active network. network?: string; }; const signTransaction: ( xdr: string, options?: IOptions, ) => Promise; // the signed XDR ``` | Parameter | Type | Description | |---|---|---| | `xdr` | `string` | Base64-encoded XDR string of the transaction | | `options.network` | `string` | Network to sign against — omit to use the active network | ## Usage ```tsx function SignButton({ xdr }: { xdr: string }) { const { signTransaction } = useBlux(); const handleSign = async () => { try { const signedXdr = await signTransaction(xdr); // `signedXdr` is the signed envelope — it has NOT been sent to the network. // Submit it yourself, send it to a backend, or pass it to a co-signer. console.log("Signed XDR:", signedXdr); } catch (error) { console.error("Signing failed:", error); } }; return ; } ``` ## Errors `signTransaction` rejects with `BLUX:`-prefixed messages: | Message | Cause | |---|---| | `BLUX: User is not authenticated.` | No user is logged in. | | `BLUX: Blux modal is open elsewhere.` | Another Blux flow is already open. | | `BLUX: Invalid XDR` | The XDR can't be parsed for the given network. | | `BLUX: Could not find the connected wallet.` | The connected wallet couldn't be resolved. | To skip the confirmation modal and handle your own confirmation UI, set `showWalletUIs: false` in your `BluxProvider` configuration. The signed XDR returned is identical either way. --- # White-label Login URL: https://docs.blux.cc/react/usage/white-label-login Build a custom authentication UI with Blux's React login hooks. The React package exposes one hook for each headless login method. You render the inputs and buttons; the hooks call Blux, track pending and error state, and update the authenticated user exposed by `useBlux`. ## Available hooks | Hook | Actions | Use it for | |---|---|---| | `useLoginEmail` | `sendCode`, `loginWithCode` | Custom email and OTP forms | | `useLoginSms` | `sendCode`, `loginWithCode` | Custom phone and OTP forms | | `useLoginOAuth` | `loginOAuth` | Custom social-login buttons | | `useLoginPasskey` | `loginPasskey` | A custom passkey button | | `useLoginWallet` | `loginWallet` | A custom wallet list or Blux's wallet-only picker | Each action has a fire-and-forget form for event handlers and an async form that returns the authenticated user—for example, `loginOAuth` and `loginOAuthAsync`. ## Configure the provider Add each method your UI uses to the `BluxProvider` config: ```tsx export function Providers({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` All login hooks must be rendered below `BluxProvider`. Social providers must also be enabled for the same app in the [Blux Dashboard](/dashboard/socials), and SMS requires a paid plan. ## Email example The email hook tracks sending and verification independently: ```tsx export function EmailLogin() { const [email, setEmail] = useState(""); const [code, setCode] = useState(""); const { sendCode, loginWithCode, isCodeSent, isSendingCode, isLoggingIn, error, } = useLoginEmail(); function submit(event: FormEvent) { event.preventDefault(); if (isCodeSent) { loginWithCode(email, code); } else { sendCode(email); } } return (
setEmail(event.target.value)} disabled={isCodeSent} required /> {isCodeSent && ( setCode(event.target.value)} required /> )} {error &&

{error.message}

}
); } ``` Use `sendCodeAsync` and `loginWithCodeAsync` when subsequent code needs the result: ```tsx const { sendCodeAsync, loginWithCodeAsync } = useLoginEmail(); await sendCodeAsync("user@example.com"); const user = await loginWithCodeAsync("user@example.com", "123456"); ``` ## SMS example `useLoginSms` has the same return value as `useLoginEmail`. Use an international E.164 phone number: ```tsx const { sendCode, loginWithCode, isCodeSent, isPending, error, } = useLoginSms(); // First screen: send the code. function sendPhoneCode() { sendCode("+15555555555"); } // Second screen: verify the code the user entered. function verifyPhoneCode() { loginWithCode("+15555555555", "123456"); } ``` SMS login is available only on paid Blux plans. If the app is not entitled to SMS, the action returns an error even when `"sms"` appears in `loginMethods`. ## Social example Render any provider however you like and call `loginOAuth` directly from its click handler: ```tsx export function SocialLogin() { const { isReady } = useBlux(); const { loginOAuth, isPending, error } = useLoginOAuth({ onSuccess: (user) => console.log("Signed in", user.address), }); return ( <> {error &&

{error.message}

} ); } ``` The call must begin in the click handler so browsers do not block the provider popup. Configure each provider in both `loginMethods` and the dashboard; see [Social Login](/dashboard/socials). For a custom Telegram Login Widget, pass its signed payload as the second argument: ```tsx loginOAuth("telegram", { telegramUser: widgetUser }); ``` Inside a configured Telegram Mini App, the hook can use the available Web App init data automatically. Use `useBlux().login()` if you want Blux to render its Telegram widget instead. ## Passkey example ```tsx export function PasskeyLogin() { const { isReady } = useBlux(); const { loginPasskey, isPending, error } = useLoginPasskey(); return ( <> {error &&

{error.message}

} ); } ``` Passkey and OAuth actions should run directly from a user gesture. The hooks preserve that call timing before updating their async status. ## Wallet example Pass a wallet name to open that wallet directly, or omit the name to open Blux's wallet-only picker: ```tsx export function WalletLogin() { const { isReady } = useBlux(); const { loginWallet, isPending, error } = useLoginWallet(); return ( <> {error &&

{error.message}

} ); } ``` A named wallet must be available in the browser. WalletConnect still opens Blux's QR screen even when selected by name. ## Status and callbacks All five hooks expose `data`, `error`, `status`, `isIdle`, `isPending`, `isSuccess`, `isError`, and `reset`. Email and SMS additionally expose `isCodeSent`, `isSendingCode`, and `isLoggingIn`. ```tsx const login = useLoginOAuth({ onSuccess: (user) => navigate(`/account/${user.address}`), onError: (error) => reportError(error), onSettled: (user, error) => console.log({ user, error }), }); ``` `useLoginEmail` and `useLoginSms` also accept `onCodeSent`. You can freely mix these hooks with the hosted flow from `useBlux().login()`. White-label login is independent of `showWalletUIs`, which controls Blux's later signing and transaction confirmation screens. --- # Changelog URL: https://docs.blux.cc/changelog Release notes for @bluxcc/core and @bluxcc/react. Both packages ship at the same version. `@bluxcc/core` and `@bluxcc/react` are released together. Every version below applies to both packages — pick the one that matches your stack. Newest releases are at the top. --- ## v0.3.7 September 13, 2026 · [GitHub (core)](https://github.com/bluxcc/core/releases/tag/v0.3.7) · [GitHub (react)](https://github.com/bluxcc/react/releases/tag/v0.3.7) ```bash npm i @bluxcc/react@^0.3.7 ``` ```bash npm i @bluxcc/core@^0.3.7 ``` ### Updates - Added `resolveXlmName()`. - Added support for XLM names instead of `G...` addresses across all hooks and helpers. - `useReactContracts` and `useWriteContract` now accept standard values, such as numbers, and automatically convert them to the required contract type, such as `i128` and `u64`. - Direct `ScVal` inputs remain supported. --- ## v0.3.4 September 4, 2026 · [GitHub (core)](https://github.com/bluxcc/core/releases/tag/v0.3.4) · [GitHub (react)](https://github.com/bluxcc/react/releases/tag/v0.3.4) ```bash npm i @bluxcc/react@^0.3.4 ``` ```bash npm i @bluxcc/core@^0.3.4 ``` ### Updates - Added on/off ramping directly to the profile modal, with the same functionality as fundMe(). --- --- ## v0.3.3 September 2, 2026 · [GitHub (core)](https://github.com/bluxcc/core/releases/tag/v0.3.3) · [GitHub (react)](https://github.com/bluxcc/react/releases/tag/v0.3.3) ```bash npm i @bluxcc/react@^0.3.3 ``` ```bash npm i @bluxcc/core@^0.3.3 ``` ### Updates - Added support for more social login providers. - Added white-label support for email, SMS, OAuth, and wallet login flows. - Simplified the onboarding page by reducing the number of buttons. - Added testnet USDC to the profile modal. --- ## v0.3.1 August 29, 2026 · [GitHub (core)](https://github.com/bluxcc/core/releases/tag/v0.3.1) · [GitHub (react)](https://github.com/bluxcc/react/releases/tag/v0.3.1) ```bash npm i @bluxcc/react@^0.3.1 ``` ```bash npm i @bluxcc/core@^0.3.1 ``` ### Updates - Added off-ramping through MoneyGram and MoonPay in the `fundMe()` modal. - Added SMS login support for users in the US and Canada. - User activity is now retrieved only when the Activity page is opened. - Fixed the modal logo display. --- ## v0.3.0 August 27, 2026 · [GitHub (core)](https://github.com/bluxcc/core/releases/tag/v0.3.0) · [GitHub (react)](https://github.com/bluxcc/react/releases/tag/v0.3.0) ```bash npm i @bluxcc/react@^0.3.0 ``` ```bash npm i @bluxcc/core@^0.3.0 ``` ### Added - Added Turkish language support. ### Changed - Replaced SEP-10 transaction signing with message signing for wallet authentication. - Updated the login flow for Freighter, Rabet, Albedo, Bitget, Hana, HOT, OneKey, and xBull. ### Fixed - Fixed Freighter’s inactive-account warning during authentication. - Fixed login failures related to rejecting the Privacy Policy or Terms and Conditions. - Fixed modals disappearing when users scroll down.