# Stellar (/docs/stellar)



Stellar is a **classic `G…` account**, the same address format wallets,
exchanges, and every Stellar tool already understand. The `G…` is HKDF of the
same **MasterDEK** as Solana (`cavos-ed25519-stellar-v1`). A new device
unwraps the DEK; the account has one spend key. This is the Stellar
adapter for the Cavos [embedded wallet](https://cavos.xyz/embedded-wallet)
([embedded wallets](https://cavos.xyz/embedded-wallet),
[embedded wallet SDK](https://cavos.xyz/embedded-wallet),
[stellar embedded wallet](https://cavos.xyz/embedded-stellar-wallet)). The
same account model is described for a product audience on the
[Stellar embedded wallet](https://cavos.xyz/embedded-stellar-wallet) page.

It's a native Stellar account (not a Soroban contract), so it interoperates with
the whole ecosystem, and it can still **sign Soroban contract invocations**, so
the same `G…` acts as a `require_auth` role in on-chain apps like
[escrows](#soroban-contracts--escrows). Gas and account reserves are sponsored
by the Cavos relayer.

To see the whole flow running, clone the
[Stellar wallet starter](https://github.com/cavos-labs/cavos-stellar-by-example/tree/main/stellar-wallet-starter): a Next.js app on testnet with sign-in,
`create()`, XLM and USDC balances, a sponsored trustline, and payments.

## Sign in with Google or email (React) [#sign-in-with-google-or-email-react]

The shortest path from a Google or email sign-in to a Stellar `G…` address is the
React provider. The Cavos modal handles sign-in (Google, Apple, or an emailed
code; GitHub and Telegram are optional providers), and every signed-in user gets
a classic Stellar account derived from their identity. No seed phrase, no
browser extension.

```tsx title="app/providers.tsx"
"use client";
import { CavosProvider } from "@cavos/kit/react";

export function Providers({ children }: { children: React.ReactNode }) {
  return (
    <CavosProvider
      config={{
        appId: process.env.NEXT_PUBLIC_CAVOS_APP_ID,
        chains: ["stellar"],
        network: "testnet",                 // "testnet" | "mainnet"
        appSalt: "my-app",                  // never change it after users connect
        socialRecovery: true,
        deviceApproval: "enclave",
      }}
      modal={{ appName: "My App", theme: "light" }}
    >
      {children}
    </CavosProvider>
  );
}
```

```tsx title="components/stellar-wallet.tsx"
"use client";
import { useCavos } from "@cavos/kit/react";

export function StellarWallet() {
  const { isAuthenticated, isLoading, login, openModal, wallet } = useCavos();
  if (isLoading) return null;
  if (!isAuthenticated) {
    return (
      <>
        <button onClick={() => login("google")}>Continue with Google</button>
        <button onClick={openModal}>Use email</button>
      </>
    );
  }
  if (wallet?.chain !== "stellar") return null;
  return <p>{wallet.address}</p>;     // G… address
}
```

The address exists as soon as the user signs in; the account is created on-chain
with [`create()`](#create-the-account) or the first `execute`. Every hook is in
[React](/docs/react) and every sign-in option in [Authentication](/docs/auth).
The [Stellar wallet starter](https://github.com/cavos-labs/cavos-stellar-by-example/tree/main/stellar-wallet-starter)
is this flow as a runnable Next.js app. Without React, use `Cavos.connect` below.

## Connect [#connect]

Use the unified `Cavos.connect`, passing `chains: ["stellar"]`. An `appId`
activates the gasless relayer (it sponsors the account's XLM reserves and pays
fees). **Connect never creates the account**: create it with `create()`, or let
the first `execute` create it.

```ts title="TypeScript"
import { Cavos } from "@cavos/kit";

const session = await Cavos.connect({
  chains: ["stellar"],
  defaultChain: "stellar",
  network: "testnet",                   // "testnet" | "mainnet"
  appSalt: "my-app",                    // HKDF salt, never change it
  identity: {                           // from your login (see Authentication)
    userId: user.id,
    email: user.email,
  },
  appId: process.env.NEXT_PUBLIC_CAVOS_APP_ID, // activates the gasless relayer
});

const wallet = session.wallet("stellar");
if (wallet.chain !== "stellar") throw new Error("expected a Stellar wallet");
console.log(wallet.address);            // G… address
console.log(wallet.status);             // "undeployed" | "ready" | "needs-device-approval"
```

`network: "testnet"` resolves to `stellar-testnet`; `"mainnet"` resolves to
`stellar-mainnet`. `session.wallet()` returns the `CavosWallet` union; the `wallet.chain` check
narrows it, so the snippets below can call Stellar methods directly.

<Callout type="info">
  `connect` unwraps (or mints) the MasterDEK and
  imports the Ed25519 control key as a non-extractable WebCrypto key, inside the
  [Cavos vault](/docs/vault) on the web (the default in the React provider with
  an `appId`; opt-in with `Cavos.connect`). The `G…`
  is that key's public address. A returning device with a local wrap is `ready`
  with no prompt. This MasterDEK path is the browser path: on React Native and
  Node, the Stellar adapter does not use the device unwrap key yet.
</Callout>

## Status values [#status-values]

| Status                  | Meaning                                                   | Can execute?                                                   |
| ----------------------- | --------------------------------------------------------- | -------------------------------------------------------------- |
| `undeployed`            | Address resolved, no on-chain account yet                 | Yes: `create()` or the first `execute` creates the account     |
| `ready`                 | Account exists and this device can sign                   | Yes                                                            |
| `needs-device-approval` | The registry has an address, but this device holds no key | No: restore with enclave login or `approveDeviceWithPasskey()` |

<Callout type="info">
  **Lazy deploy**: An `undeployed` wallet can sign messages and execute. The
  first `execute` creates the account, then performs the operation. After that,
  status becomes `ready`.
</Callout>

## Create the account [#create-the-account]

`create()` creates the account on-chain and sends nothing. With an `appId` the
relayer sponsors it, so the account holds **0 XLM** and the user locks no XLM.
It does nothing when the account is already `ready`. Call it before
`addTrustline` or `invokeContract` on a new account (requires `@cavos/kit` 0.5.3).

```ts title="TypeScript"
if (wallet.chain === "stellar") {
  await wallet.create();                 // status becomes "ready"
  await wallet.addTrustline({ code: "USDC", issuer: "GA...ISSUER" });
}
```

## Execute a transfer [#execute-a-transfer]

On Stellar, `execute(amount, destination)` moves `amount` **stroops** of native
XLM out of the account to `destination`. Both `undeployed` and `ready` wallets
can execute: on an `undeployed` wallet it creates the account first.

```ts title="TypeScript"
if (wallet.chain === "stellar" && wallet.status !== "needs-device-approval") {
  const hash = await wallet.execute(
    10_000_000n,                         // 1 XLM, in stroops
    "GDESTINATION...ADDRESS",            // recipient G… address
  );
  console.log(hash);                     // Horizon transaction hash
}
```

When the account is `undeployed`, this call creates the account first, then
sends the payment in a second transaction. A sponsored account starts with
0 XLM, so that payment fails with `op_underfunded` unless XLM reached the account
first. The account is created either way, and status becomes `ready`.

`amount` is a `bigint` of stroops (`1 XLM = 10_000_000 stroops`). Pass
`{ fee: 'self' }` to submit directly: the account pays its own (tiny) fee
from its XLM balance instead of the relayer.

Read the native balance with `wallet.balance()` (stroops):

```ts title="TypeScript"
const stroops = await wallet.balance();  // bigint, native XLM
```

## Soroban contracts & escrows [#soroban-contracts--escrows]

Beyond native XLM transfers, the account can **invoke Soroban contracts**. Because
the control key is a real Stellar signer, it can satisfy a contract's
`require_auth` for this account's address, so your `G…` account participates in
on-chain apps (escrows, marketplaces, DeFi) as a first-class signer, still silent
and still gasless.

`invokeContract` builds and simulates the call, re-signs **only** the Soroban auth
entry belonging to this account with the control key (other roles' entries are
untouched), and submits it, sponsored by the relayer by default:

```ts title="TypeScript"
if (wallet.chain === "stellar" && wallet.status === "ready") {
  const hash = await wallet.invokeContract({
    contractId: "C...ESCROW",             // the Soroban contract
    method: "approve_milestone",
    args: [0, wallet.address],            // ScVals, or JS values auto-converted
  });
}
```

<Callout type="warn">
  **Soroban invocations require a deployed account.** `invokeContract` and
  `addTrustline` require `status === "ready"`. Call `create()` first on a new
  account.
</Callout>

To hold or receive a classic asset (e.g. USDC, needed to fund a USDC escrow),
open a trustline first. A trustline adds a subentry (reserve); sponsored by the
relayer by default:

```ts title="TypeScript"
await wallet.addTrustline({ code: "USDC", issuer: "GA...ISSUER" });
const bal = await wallet.tokenBalance({ code: "USDC", issuer: "GA...ISSUER" }); // "0" if none
```

When your backend (or a platform's REST API) builds the transaction and hands
you an **unsigned XDR**, use `signXdr` instead. It mirrors a classic wallet's
`signTransaction(unsignedXdr) → signedXdr`, so a Cavos account drops into any
flow that already expects one: it does **not** submit:

```ts title="TypeScript"
const signedXdr = await wallet.signXdr(unsignedXdr); // your backend submits it
```

It handles both auth models: Soroban auth entries naming **this** account are
re-signed (`authorizeEntry`), source-account auth and classic transactions are
satisfied by this device's ed25519 signature. Entries authorizing other
addresses are left untouched.

### Trustless Work escrows [#trustless-work-escrows]

`@cavos/kit` ships a first-class wrapper for [Trustless Work](https://www.trustlesswork.com/)
milestone escrows: a Soroban platform where auth is spread across six roles
(`approver`, `service_provider`, `platform`, `release_signer`, `dispute_resolver`,
`receiver`), each an address that signs contract calls. A Cavos account can hold
any of these roles: the wrapper passes this account's `G…` as the role argument and
its control key signs the matching auth entry.

Deploy a fresh escrow through the Trustless Work factory, signed by a Cavos
account:

```ts title="TypeScript"
import { deployEscrow, StellarAdapter } from "@cavos/kit";

const adapter = new StellarAdapter({ network: "stellar-testnet" });

const { escrowId } = await deployEscrow(wallet, {
  factoryId: "C...FACTORY",
  wasmHash: "96e4eb6a...",                // the escrow contract's wasm hash
  adapter,
  escrow: {
    engagementId: "job-42",
    title: "Landing page",
    description: "Design + build",
    amount: 2_000_000n,                    // total, in the token's base units (7-dp)
    platformFeeBps: 100,                   // 1%
    roles: {
      approver: client.address,
      serviceProvider: freelancer.address,
      platform: client.address,
      releaseSigner: client.address,
      disputeResolver: client.address,
      receiver: freelancer.address,
    },
    milestones: [{ description: "Ship v1" }],
    trustline: "C...USDC",                 // the token SAC (native XLM SAC needs no trustline)
  },
});
```

Then drive the lifecycle. Each method acts as the role it maps to, so it must be
called by the account holding that role:

```ts title="TypeScript"
import { TrustlessWorkEscrow, buildEscrowScVal } from "@cavos/kit";

const escrow = new TrustlessWorkEscrow(wallet, escrowId);

// Client funds the escrow (fund BEFORE any milestone change; the expected
// struct must match stored state; rebuild it from the same EscrowInput):
await escrow.fundEscrow(buildEscrowScVal(escrowInput), 2_000_000n);

// Service provider marks work delivered:
await escrow.changeMilestoneStatus(0, "delivered");

// Client approves:
await escrow.approveMilestone(0);

// Once every milestone is approved and the escrow is funded, release funds:
// pays the receiver, minus the Trustless Work + platform fees:
await escrow.releaseFunds("G...TRUSTLESS_WORK");

// Read live on-chain state at any time:
const state = await escrow.getEscrow(adapter);
console.log(state.flags.released, state.milestones[0].approved);
```

`disputeEscrow()` and `resolveDispute(...)` cover the dispute path. Every method is
gasless by default; pass `{ fee: 'self' }` to have the account pay its own fee.

<Callout type="info">
  **Gasless by default.** `invokeContract` and escrow methods are sponsored: the
  relayer signs the fee-bump (`kind: "soroban"`) and pays the inclusion fee and
  the resource fee. Pass `{ fee: 'self' }` for the account to pay the fee
  itself.
</Callout>

## Sign messages [#sign-messages]

Sign arbitrary messages off-chain with the control key. Works on both
`undeployed` and `ready` wallets, because the control key is derived from the MasterDEK at connect time:

```ts title="TypeScript"
const sig = await wallet.signMessage("Hello, Cavos!");
// sig.signature: Uint8Array
// sig.publicKey: "G..." (control key's G address)
// sig.curve: "ed25519"
```

A verifier calls `Keypair.fromPublicKey(controlAddress).verify(messageBytes,
signature)`: standard ed25519 math. The message is prefixed with the Cavos
domain prefix before signing.

## Unlock factors & silent signing [#unlock-factors--silent-signing]

One spend key, restored by an enclave unwrap or a passkey's encrypted copy.
Signing in again with the enrolled Google, Apple, GitHub, Telegram, or email identity
**does** restore the account.

| Factor      | Role                                        |
| ----------- | ------------------------------------------- |
| **Device**  | Ed25519 key imported from the DEK           |
| **Passkey** | Encrypted copy of the MasterDEK (can spend) |
| **Enclave** | Seals / unwraps the DEK                     |

On a returning device with a local wrap, `connect` is `ready` with no prompt.
On a new device with no wrap, the vault asks for the passkey if one was added;
otherwise status is `needs-device-approval` until enclave login or
`approveDeviceWithPasskey()`.

## Add a passkey (recommended) [#add-a-passkey-recommended]

Signing up never asks for a passkey. After connect, call `enrollPasskeyDefault()`.
The passkey stores an **encrypted copy of the MasterDEK**: anyone with that
synced passkey can open the wallet. It is *not* 2FA and does not add a signer
to the account. See [Passkeys](/docs/passkeys) for how the copy is protected.

<Callout type="warn">
  Use the enclave if you want Google/Apple/GitHub/Telegram/email restore without giving a synced
  credential spending power by itself. `deviceApproval: "passkey"` is one chain.
</Callout>

```ts title="TypeScript"
const { enrollPasskeyDefault, approveDeviceWithPasskey, walletStatus } = useCavos();

await enrollPasskeyDefault(); // from a device that holds the wallet

// A new device is asked on sign-in. If the user dismissed it:
if (walletStatus.needsDeviceApproval && walletStatus.hasPasskey) {
  await approveDeviceWithPasskey();
}
```

## Approve a new device [#approve-a-new-device]

A fresh device lands on the same `G…` with
`status: "needs-device-approval"` until it unwraps the MasterDEK (enclave login
or `approveDeviceWithPasskey()`). No signer is added to the account.

See [Multi-device](/docs/multi-device) and [Passkeys](/docs/passkeys).

## Recovery [#recovery]

[Hardware-isolated recovery](/docs/hardware-isolated-recovery) seals the
MasterDEK. Sign in again on the new device, or use
`approveDeviceWithPasskey()`.

## Manage devices [#manage-devices]

One spend key, restored from the MasterDEK on every device. There is no
per-device list to manage, the same as Starknet and Solana.

## Pay reserves and fees in a token [#pay-reserves-and-fees-in-a-token]

The kit relayer (`appId`) sponsors **XLM** so the user never holds lumens;
Cavos pays. That is the default for `execute`, trustlines, fee-bumps, and `invokeContract`.

If the user should pay those same costs in USDC (or another allowlisted
asset), use [`@cavos/reserve`](/docs/reserve) and sign with
`wallet.signXdr`. Do not also call `wallet.execute` to create the account:
that would take the relayer path instead.

```ts title="TypeScript"
import { Reserve } from "@cavos/reserve";

const reserve = await Reserve.connect("testnet");

if (wallet.chain === "stellar") {
  await reserve.pay(
    {
      source: wallet.address,
      destination,
      amount: "10",
      token: "USDC:GCKUFD5KAAM6DRSLODK55OVECMB5IJ5NSFQYFTBZRPOTJASUKTBZXGS2",
      maxSend: "0.05",
    },
    (xdr) => wallet.signXdr(xdr),
  );
}
```

Reserve is wallet-agnostic (Freighter works the same way) and does not need
a Cavos `appId`. Classic operations only: no Soroban. See
[Reserve](/docs/reserve) for activate-from-a-claimable (a `G…` that holds
0 XLM), verification, and the token allowlist.

## Gasless vs self-funded [#gasless-vs-self-funded]

| Path                           | When                                           | Who pays                                                                               |
| ------------------------------ | ---------------------------------------------- | -------------------------------------------------------------------------------------- |
| **Relayer (gasless, default)** | `appId` is set                                 | The Cavos relayer is the tx source + fee payer and **sponsors the account's reserves** |
| **Self-funded fallback**       | no `appId`, a `stellarSourceKeypair` is passed | Your funded keypair funds reserves + pays fees                                         |

Every Stellar account locks XLM **reserves** (a base reserve plus \~0.5 XLM per
subentry, such as data entries and trustlines). With the relayer, those reserves
and all fees are sponsored, so the user locks no XLM. The relayer is **only** a
fee payer + reserve sponsor, never a custodian or identity authority; a bad or
absent relayer can cost fees but can never move funds or squat an address.

## Limits and errors [#limits-and-errors]

What the relayer sponsors, and what a failed call looks like:

| Situation                                | What happens                                                                                                                                                                                     |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Testnet**                              | Sponsorship is free and unmetered.                                                                                                                                                               |
| **Mainnet**                              | Sponsorship spends your organization's prepaid XLM gas. Deposit it in the dashboard under **Gas**.                                                                                               |
| **Mainnet gas runs out**                 | The relayer answers `402 insufficient_gas` and the call throws `kit/stellar: relay failed (402)`. Nothing is submitted. Deposit XLM and retry.                                                   |
| **Too many requests**                    | The relayer answers `429` with a `Retry-After` header.                                                                                                                                           |
| **Transaction not eligible**             | The relayer only sponsors account creation, Cavos data entries, trustlines, fee-bumps of the account's own transactions, and Soroban calls. Anything else is rejected with `400` and a `reason`. |
| **`create()` fails**                     | Status stays `undeployed`. Calling `create()` again is safe: it checks whether the account already exists on-chain.                                                                              |
| **First XLM `execute` on a new account** | The account is created, then the payment fails with `op_underfunded` because a sponsored account starts with 0 XLM. Fund it first.                                                               |

The relayer pays fees and sponsors reserves. It never holds the spend key, so
it cannot move funds. When sponsorship is unavailable, an account that holds
XLM can still pay its own fee with `{ fee: 'self' }`.

## Address resolution [#address-resolution]

On Stellar, the `G…` address is resolved via the **registry-first** model (see
[Concepts](/docs/concepts)). When you call `connect`:

1. **Registry lookup**: `(userId, appId, chain, network)`.
2. **If found**: that `G…` is returned. The device unwraps the MasterDEK or lands on
   `needs-device-approval`.
3. **If not found**: the SDK mints a random MasterDEK and claims the
   HKDF `G…`. The first device to register wins.

The address is available before the account exists on-chain. The on-chain
account is created by `create()` or the first `execute`.

```ts title="TypeScript"
const wallet = session.wallet("stellar");
if (wallet.chain !== "stellar") throw new Error("expected a Stellar wallet");
console.log(wallet.address);  // G… address
console.log(wallet.status);   // "undeployed" until create() or the first execute
```

## Networks & constants [#networks--constants]

```ts title="TypeScript"
import { STELLAR_NETWORKS, HORIZON_URL, XLM_DECIMALS } from "@cavos/kit";

STELLAR_NETWORKS["stellar-testnet"];     // network config
HORIZON_URL["stellar-mainnet"];          // https://horizon.stellar.org
XLM_DECIMALS;                            // 7 (1 XLM = 10^7 stroops)
```

Networks: `"stellar-testnet"`, `"stellar-mainnet"`.

## What's available [#whats-available]

* ✅ Classic `G…` account. Native MasterDEK path shares the DEK with Solana.
* ✅ **Create on demand**: `create()` creates the sponsored account and sends nothing; the first `execute` also creates it.
* ✅ Silent signing via a non-extractable ed25519 control key, held by the
  [Cavos vault](/docs/vault) within your app's limits.
* ✅ &#x2A;*Sign messages off-chain while undeployed.**
* ✅ Gasless create + execute via the Cavos relayer (reserves sponsored).
* ✅ Native XLM transfer (`execute(amount, destination)`) + `balance()`.
* ✅ **Soroban contract invocation** (`invokeContract`): the account signs its own
  `require_auth` entry, so it acts as a role in on-chain apps, plus USDC-style
  trustlines (`addTrustline` / `tokenBalance`).
* ✅ **Trustless Work escrows** out of the box: `deployEscrow` (via factory) and
  the `TrustlessWorkEscrow` wrapper (fund → deliver → approve → release, plus
  disputes) with `getEscrow` live state reads.
* ✅ **Enclave DEK wrap** and **passkey** restore on the native path.
* ✅ **Pay in a token** via [`@cavos/reserve`](/docs/reserve) (`wallet.signXdr`).

For the cross-chain model and how this compares to the other chains, see
[Chains](/docs/chains) and [Concepts](/docs/concepts). A React install lives in
[how to add an embedded wallet](https://cavos.xyz/blog/how-to-add-an-embedded-wallet).
If users currently sign in Freighter, read
[embedded wallet vs browser extension](https://cavos.xyz/blog/embedded-wallet-vs-browser-extension).
