# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
This site has an agentic ask interface you may use to query the documentation dynamically by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.varialwallet.com/index.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

---

# Introduction

{% hint style="info" %}
**Freighter is now Varial.** Same wallet, new name. Existing integrations keep working unchanged — dapps on `@stellar/freighter-api` and the WalletConnect methods are unaffected. New integrations should use [`@stellar/varial-sdk`](/extension-varial-sdk/installation), the extension SDK's new name.
{% endhint %}

Varial (formerly Freighter) is a non-custodial wallet for the Stellar network, available as a browser extension and a mobile app. Non-custodial means your users hold their own keys — your dapp never sees or stores private keys. This guide walks you through integrating Varial so your users can connect their wallets, sign transactions, and interact with Soroban smart contracts.

## What You Can Build

With Varial, your dapp can connect a user's wallet with a single call — no signup form, no password, just a familiar wallet popup and an immediate public key. From there you can read their active network, hand off transactions for signing, and submit to the network.

For dapps that integrate with smart contracts, Varial also handles authorization entry signing for smart contract calls and arbitrary message signing for account verification.

## How It Works

The integration model is simple: your dapp talks to the wallet, and the wallet talks to the user.

For **desktop browsers**, you integrate with the Varial browser extension through a lightweight JavaScript library. It injects itself into the page, and your dapp calls methods like "is the wallet connected?", "what's the user's address?", and "please sign this transaction."

For **mobile**, the integration works over WalletConnect v2. When a user opens your dapp in a mobile browser, WalletConnect presents a modal where they select Varial as their wallet and approve the connection. On desktop, the same flow can display a QR code for the user to scan. Either way, a secure relay session is established and signing requests flow through the same pattern — your dapp proposes, the user reviews and approves in the wallet.

Both paths produce the same output: signed transactions you can submit to the Stellar network. So your backend and submission logic stay the same regardless of whether your user connected from a laptop or a phone.

If you want to support multiple Stellar wallets — not just Varial — take a look at [Stellar Wallets Kit](https://stellarwalletskit.dev/). It provides a unified interface across Stellar wallets, including browser extensions and WalletConnect-based mobile wallets, so your users can connect with whichever wallet they prefer.

> **Note:** Stellar Wallets Kit's WalletConnect module supports all four methods the Varial mobile app exposes — `stellar_signXDR`, `stellar_signAndSubmitXDR`, `stellar_signMessage`, and `stellar_signAuthEntry` — from v2.3.0. Older versions only expose the first two; upgrade the kit, or integrate WalletConnect directly, if you need message or auth entry signing.

## Why Varial

**Built and maintained by SDF.** Varial is developed by the Stellar Development Foundation, the same team behind the core Stellar protocol and SDKs.

**Complete Stellar support.** Transaction signing, Soroban authorization entry signing with contract invocation inspection, SEP-53 message signing, contract token management, and Blockaid transaction scanning.

**Desktop and mobile.** Browser extension for desktop, WalletConnect for mobile. Both paths produce the same signed output, so your dapp supports both with minimal branching.

## Get Started

**Desktop** — integrate with the Varial browser extension using `@stellar/varial-sdk`. See the [Extension Guide](/extension-varial-sdk/installation).

**Mobile** — connect to the Varial mobile app over WalletConnect v2. See the [Mobile Guide](/mobile-walletconnect/mobile).

**Both** — if your dapp needs to support desktop and mobile users, use both integration paths. Both produce the same output (signed XDR), so your submission logic stays the same regardless of how the user connected.

## Quick links

| I want to...       | Extension                                                  | Mobile                                             |
| ------------------ | ---------------------------------------------------------- | -------------------------------------------------- |
| Install / set up   | [Installation](/extension-varial-sdk/installation)         | [Installation](/mobile-walletconnect/installation) |
| Connect to Varial  | [Connecting](/extension-varial-sdk/connecting)             | [Connecting](/mobile-walletconnect/connecting)     |
| Sign a transaction | [Signing](/extension-varial-sdk/signing)                   | [Signing](/mobile-walletconnect/signing)           |
| Add a token        | [Token Management](/extension-varial-sdk/token-management) | —                                                  |
| Try it out         | [Playground ↗](https://play.varialwallet.com)              | [Playground ↗](https://play.varialwallet.com)      |

## Resources

* [GitHub — Varial Extension](https://github.com/stellar/freighter)
* [GitHub — Varial Mobile App](https://github.com/stellar/freighter-mobile)
* [Varial on Chrome Web Store](https://chromewebstore.google.com/detail/freighter/bcacfldlkkdogcmkkibnjlakofdplcbk)
* [Varial on Firefox Add-ons](https://addons.mozilla.org/en-US/firefox/addon/freighter/)
* [Stellar Developer Docs](https://developers.stellar.org)
* [WalletConnect v2 Docs](https://docs.walletconnect.network/app-sdk/overview)


# What's New

Highlights from Freighter browser extension releases 5.31.0 through 5.37.0. For later releases, see the [Freighter changelog](https://freighter.app/changelog).

## Release 5.37.0

### Collectibles

You can now add SEP-50 collectibles to your Freighter wallet on Mainnet, Testnet, and Futurenet. If your account is the owner of a collectible, click `Collectibles` in the Account view. Once you're in the Collectibles view, click the options icon on the right side of the screen. This will show you a dropdown with the option to `Add manually`. Clicking that will take you to a screen to input your collectible's contract address, as well as its token id. Once you've successfully done that, if your account is the owner of the collectible, you will now see it in your `Collectibles` view. You'll also be able to send it to another user, just as you would any payment, using the `Send` button.

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-45edbcccaeb79dac622b86fe4427b71ef71a4c5d%2Fadd_collectibles.png?alt=media" alt="Add Collectibles" width="300"><figcaption></figcaption></figure>

### Memo checks

Freighter's Send flow now has enhanced memo requirement checking. If your destination needs a memo, we'll remind you to make sure your payment gets to where it's supposed to go. This is especially useful when you're sending payment to exchanges, which often require memos.

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-20b7739ae3eff300201883302d1b64972bc9190c%2Fmemo_required.png?alt=media" alt="Memo Required" width="300"><figcaption></figcaption></figure>

### Additional bugfixes and stability fixes

[Full changelog](https://github.com/stellar/freighter/releases/tag/5.37.0)

## Release 5.36.0

### Performance Improvements

We heard your feedback and in Release 5.36.0, we've made improvements to make Freighter faster and smoother than ever! We've made some updates to lazy load API requests and we've added even more caching to speed up your Freighter experience.

Side by side comparison of v5.35.0 and v5.36.0:

{% file src="/files/vkIHNtb15zxlSipDhxZE" %}

### Send and Swap Update

We've also updated the UX for the Send and Swap flows in Freighter to streamline the process. This means fewer clicks to send a payment or swap to a different asset.

### Copy Your Address

For your convenience, we now include a button to copy your address from your options dropdown.

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-38efa1cfff427bb770492e5c9853790198e51c61%2Fcopy_address.png?alt=media" alt="Copy Address" width="300"><figcaption></figcaption></figure>

### Additional bugfixes and stability fixes

[Full changelog](https://github.com/stellar/freighter/releases/tag/5.36.0)

## Release 5.34.0

### App-Wide Design system Update

For this release, we've freshened up the design system, removed the nav bar at the bottom, and reorganized certain buttons.

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-39a47ce1a00d6f517859749ca97fd902ae83d69b%2FOld_Homescreen_5.34.png?alt=media" alt="Old Homescreen" width="300"><figcaption><p>Old Homescreen</p></figcaption></figure>

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-8614b0e2eeeeac2e4d5842beee61cf0539821fa3%2FNew_Homescreen_5.34.png?alt=media" alt="New Homescreen" width="300"><figcaption><p>New Homescreen</p></figcaption></figure>

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-befd441fe3397d85c8efc15d4ba8a60b51a6a670%2FOld_History_5.34.png?alt=media" alt="Old History Page" width="300"><figcaption><p>Old History Page</p></figcaption></figure>

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-3b0892d9c4bf673bbed7894606edde6f79e1b26e%2FNew_History_5.34.png?alt=media" alt="New History Page" width="300"><figcaption><p>New History Page</p></figcaption></figure>

### Settings is now under the top left dropdown navigation

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-1d3ca546edfe9713822a568cb854096f49acf966%2FOld_settings_button_Location_5.34.png?alt=media" alt="Old Settings Button Location" width="300"><figcaption><p>Old Settings Location</p></figcaption></figure>

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-aca40fc7cd365945919b520d370cbc1821e505c4%2FNew_settings_button_Location_5.34.png?alt=media" alt="New Settings Button Location" width="300"><figcaption><p>New Settings Location</p></figcaption></figure>

### Secondary navigation is now in the top left dropdown

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-710980fdd26a86a37009cb9b40be8b480625fb8c%2FOld_Settings_Dropdown_5.34.png?alt=media" alt="Old Secondary Nav Location" width="300"><figcaption><p>Old Secondary Nav Location</p></figcaption></figure>

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-3e9832f5a3caaa5ec597f7034374f6e36c688842%2FNew_Settings_Dropdown_5.34.png?alt=media" alt="New Secondary Nav Location" width="300"><figcaption><p>New Secondary Nav Location</p></figcaption></figure>

### Implements SEP-53 handling for sign-message API

Learn more about SEP-53 message signing [here](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0053.md).

[Full changelog](https://github.com/stellar/freighter/releases/tag/5.34.0)

## Release 5.33.0

### Discover

You can now find dapps to connect your Freighter wallet to from the `Discover` screen. Here, you'll find dapps that provide different services, like lending, DEXs, and bridging.

To access, simply click the `Discover` button on the home screen.

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-2cd218c73460329a2c885516954c6d65cf4eb035%2Fdiscover-button.png?alt=media" alt="Discover Button" width="300"><figcaption></figcaption></figure>

From here, you can click the `Open` button next to any protocol to navigate to the dapp.

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-d5d7c335382c0a483530abf6e0e4ac132b5a2090%2Fdiscover-screen.png?alt=media" alt="Discover Screen" width="300"><figcaption></figcaption></figure>

### Filtering claimable balances

Many users have reported their Stellar accounts receive a good deal of claimable balance "spam" in their account history - claimable balances they have no intention of claiming. These often present themselves as a transaction containing many `create claimable balance` operations.

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-3bfdb55c966046b5ae4256809885a9668c9ad6bb%2Fcreate-claimable-spam.png?alt=media" alt="Create Claimable Balance Spam" width="300"><figcaption></figcaption></figure>

To filter out this noise and provide a better experience for users, Freighter now automatically hides these types of transactions for you. If you do want to engage with any of these, they still exist on your account. You can find them by visiting a block explorer like [stellar.expert](https://stellar.expert).

### Additional bugfixes and stability fixes

[Full changelog](https://github.com/stellar/freighter/releases/tag/5.33.0)

## Release 5.32.0

### Add Asset Unification

The "Add Asset" flow is now unified so that users do not have to select "Add Manually" in order to add custom tokens. You can now use the single search bar in order to search for issuers, domains, and contract IDs when looking for an asset to add to your balances screen.

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-2031645685a4192b9bb762099c201f31aa368822%2Fasset-unification.png?alt=media" alt="Add Assets" width="300"><figcaption></figcaption></figure>

### Improved Support for Asset Icons

Traditionally, you have only been able to see an asset's icon if it was correctly defined in [the asset's toml file](https://developers.stellar.org/docs/tokens/publishing-asset-info#sample-stellartoml) hosted on the asset's home domain.

Custom tokens have no corresponding toml file or home domain which meant there was no support for displaying a custom token's asset icon. We've expanded icon support by including icons defined in any [SEP 42 Stellar Asset List](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0042.md) that is active in your wallet. This change will allow more asset icons to be available for Freighter assets and include custom tokens that are vetted by the community and added to the maintained asset lists.

### Failed Transaction in History

Your history previously only included transactions that were successful and included in the ledger. We've updated our history data to include failed transactions in order to give users a better view of the actions they attempt to take.

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-d009674447df7b0042fb85fbc88fac83c18133b6%2Ffailed-history-row.png?alt=media" alt="Failed History Row" width="300"><figcaption></figcaption></figure>

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-c6175ff3407273a2169c8edee20129cb3c7041ed%2Ffailed-history-item.png?alt=media" alt="Failed History Item" width="300"><figcaption></figcaption></figure>

### Additional bugfixes and stability fixes

[Full changelog](https://github.com/stellar/freighter/releases/tag/5.32.0)

## Release 5.31.0

### Coinbase Onramp

You can now fund your wallet directly from Freighter. To do so, first, make sure you are on Mainnet. Then, click on the `...` dropdown on the Account screen. You'll see a button labeled `Add funds`. This will bring you to a screen with a button labeled `Buy With Coinbase`. This button takes you to Coinbase where you can select any asset Coinbase offers. At checkout, you will find your Freighter address prefilled. Completing checkout will send the asset to your Freighter wallet.

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-849ea517ea5efda2490f75a9865c995fb0e75ed7%2Fcoinbase_account.png?alt=media" alt="Account" width="300"><figcaption></figcaption></figure>

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-081c2de5394b611cc336ecdf6b98cfe4e2b699ea%2Fcoinbase_add_funds.png?alt=media" alt="Add funds" width="300"><figcaption></figcaption></figure>

If your account is unfunded, you can simply click the `Add XLM` button on the Account screen. This will take you to a screen where you can `Buy XLM With Coinbase`. This button will take you to Coinbase where `XLM` will be preselected for you and your Freighter address will be prefilled as the destination.

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-849ea517ea5efda2490f75a9865c995fb0e75ed7%2Fcoinbase_account.png?alt=media" alt="Account" width="300"><figcaption></figcaption></figure>

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-5d7590382fa98cc94947b3f1dd810eabcd037884%2Fcoinbase_add_xlm.png?alt=media" alt="Add XLM" width="300"><figcaption></figcaption></figure>

### Hide Assets

You can now choose to hide assets you own. Click the `...` dropdown and click `Manage assets` (when your account is funded). Here you will see a button in the top right corner where you can toggle assets. This is useful if you have many assets but only want to see a few that you care about.

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-76ce5ca3177dd37b651deddc417b7dc7bf6a663f%2Fhide_assets.png?alt=media" alt="Hide assets" width="300"><figcaption></figcaption></figure>

### Paste Mnemonic Phrase

During onboarding, if you choose to import an account by mnemonic phrase, you can now paste your mnemonic phrase. If you paste the complete phrase into the first input, it will populate the rest of the inputs with each word.

Please note that when you do so, we will automatically clear your clipboard after successful paste. This is because keeping your mnemonic phrase (or secret key) in your clipboard is a vulnerable place that hackers may have access to. Because of that, we generally encourage users to never store sensitive information in their clipboard.

For more information:

* [Demonic vulnerability](https://www.halborn.com/disclosures/demonic-vulnerability)
* [StilachiRAT vulnerability](https://www.microsoft.com/en-us/security/blog/2025/03/17/stilachirat-analysis-from-system-reconnaissance-to-cryptocurrency-theft/)

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-2cac3538abde09614485ec02123ac93942134d06%2Frecover_paste.png?alt=media" alt="Paste recovery phrase" width="300"><figcaption></figcaption></figure>

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-9ca7fec459096c59d5912b2d1d42b9a2f61aa8fc%2Frecover_pasted.png?alt=media" alt="Pasted recovery phrase" width="300"><figcaption></figcaption></figure>

### Security Improvements

We've made some changes to how users deal with connected apps in Freighter.

Previously, if you tried to sign a transaction/message/auth entry for a dapp that was NOT on your connected apps list, Freighter would present a warning message but still allow you to continue signing if you so choose. This design made sense from the perspective of reducing user friction and allowing people to sign things quickly.

As the ecosystem continues to evolve and grow, the Freighter team feels it would be best to start giving you a bit more security in this flow. Starting in this release, Freighter will automatically block you from signing a transaction/message/auth entry if the app is not on your connected apps list. The only way for you to sign for a dapp is to first go through the "connection flow" that the dapp should offer. Behind the scenes, the dapp will be using the `@stellar/freighter-api` methods `setAllowed` or `requestAccess` to do so. The goal here is to keep users from accidentally signing for a dapp that they do not intend to.

Also, previously, if you went through the aforementioned "connection flow", it would connect all of your Freighter addresses across ALL networks to an app. Again, this design made sense from the perspective of reducing user friction and allowing people to sign quickly.

Going forward, when you connect to a dapp, only the active keypair on the currently selected network will be connected to the app. If you want to sign using another one of your Freighter accounts, you will need to go through the connection flow for that address.

<figure><img src="https://4265215729-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGjPrm2NFBxEHS8Vvs68a%2Fuploads%2Fgit-blob-f732c1794406e5bc5a924a88dd79d123c9bc03fa%2Fsign_unconnected.png?alt=media" alt="Sign for unconnected apps" width="300"><figcaption></figcaption></figure>

### Additional bugfixes and stability fixes

[Full changelog](https://github.com/stellar/freighter/releases/tag/5.31.0)


# Installation

Get up and running with Varial by installing the browser extension and choosing the right integration method for your app.

## Prerequisites

1. Install the Varial browser extension from the [Chrome Web Store](https://chromewebstore.google.com/detail/freighter/bcacfldlkkdogcmkkibnjlakofdplcbk) or [Firefox Add-ons](https://addons.mozilla.org/en-US/firefox/addon/freighter/).
2. Choose an integration method below based on your project setup.

## Choose Your Integration

### npm / yarn

Use this when building with a bundler (Webpack, Vite, etc.) in a React, Next.js, or other modern JS framework.

**Ideal for:**

* React, Vue, Svelte, or Angular applications
* Server-side rendered apps (Next.js, Nuxt)
* Any project using a JavaScript bundler

```bash
npm install @stellar/varial-sdk
```

```bash
yarn add @stellar/varial-sdk
```

Then import in your code. You can import the entire library:

```javascript
import varialSdk from "@stellar/varial-sdk";
```

Or import only what you need:

```javascript
import {
  isConnected,
  getAddress,
  signAuthEntry,
  signTransaction,
  signMessage,
  addToken,
} from "@stellar/varial-sdk";
```

{% hint style="info" %}
**Upgrading from `@stellar/freighter-api`?** `@stellar/varial-sdk` is the same SDK under its new name, continuing from version 7.0.0. Swap the package and change the import path — method names, parameters and return types are the same. `@stellar/freighter-api` stays at 6.0.1 with no new releases: dapps already using it keep working, but new methods such as `disconnect()` are only in `@stellar/varial-sdk`.
{% endhint %}

> See the [Extension Integration](/extension-varial-sdk/extension) for the full API reference.

### CDN (script tag)

Use this for plain HTML pages or projects without a build step. The library is loaded directly in the browser.

**Ideal for:**

* Static HTML sites
* Prototypes and quick experiments
* Projects without a bundler

Add to your `<head>`:

```html
<script src="https://unpkg.com/@stellar/varial-sdk/build/index.min.js"></script>
```

This always loads the latest version automatically. To pin a specific version:

```html
<script src="https://unpkg.com/@stellar/varial-sdk@7.0.0/build/index.min.js"></script>
```

Then access the API via `window.freighterApi` (the global keeps its previous name):

```javascript
const { address } = await window.freighterApi.requestAccess();
```

## Next steps

| I want to...             | Go to                                                      |
| ------------------------ | ---------------------------------------------------------- |
| Connect my app to Varial | [Connecting](/extension-varial-sdk/connecting)             |
| Sign a transaction       | [Signing](/extension-varial-sdk/signing)                   |
| Add a token              | [Token Management](/extension-varial-sdk/token-management) |


# Overview

Integrate Varial into your web application using `@stellar/varial-sdk`. This library lets you send and receive data from a user's Varial extension.

{% hint style="info" %}
`@stellar/varial-sdk` is the new name of `@stellar/freighter-api`. The old package stays at 6.0.1 with no new releases. Dapps using it keep working with every method on these pages except ones added after 6.0.1, such as `disconnect()`.
{% endhint %}

`@stellar/varial-sdk` adheres to the [SEP-43](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0043.md) standard for wallet interfaces on Stellar, and also offers additional methods beyond the spec such as `getNetworkDetails`, `addToken`, and `WatchWalletChanges`.

## Error Type

All methods return an optional `error` field of type `FreighterApiError` (the type keeps its previous name):

```typescript
interface FreighterApiError {
  code: number;
  message: string;
  ext?: string[];
}
```

## API Reference

| Category                                                   | Description                                                  |
| ---------------------------------------------------------- | ------------------------------------------------------------ |
| [Connecting](/extension-varial-sdk/connecting)             | Detect Varial, check permissions, request access, disconnect |
| [Reading Data](/extension-varial-sdk/reading-data)         | Get the user's address and network configuration             |
| [Signing](/extension-varial-sdk/signing)                   | Sign transactions, auth entries, and messages                |
| [Token Management](/extension-varial-sdk/token-management) | Add contract tokens to the user's wallet                     |
| [Watching Changes](/extension-varial-sdk/watching-changes) | Monitor wallet state changes in real time                    |


# Connecting

Detect whether a user has Varial installed, check if your app is authorized, request access to the user's public key, and disconnect.

## Detecting Varial

### `isConnected()`

Check if the user has Varial installed in their browser.

**Returns:** `Promise<{ isConnected: boolean } & { error?: FreighterApiError }>`

```typescript
import { isConnected } from "@stellar/varial-sdk";

const result = await isConnected();

if (result.isConnected) {
  console.log("Varial is installed");
}
```

{% hint style="info" %}
`isConnected()` checks whether the Varial extension is installed. Note that it returns `false` for any user without the extension — not just mobile users. To detect the Varial mobile app's in-app browser specifically, check for `window.stellar?.platform === "mobile"`. The injected `window.stellar.provider` value is still `"freighter"`, the app's old name — it was kept unchanged so existing wallet detection keeps working.
{% endhint %}

## Checking Authorization

### `isAllowed()`

Check if the user has previously authorized your app to receive data from Varial.

**Returns:** `Promise<{ isAllowed: boolean } & { error?: FreighterApiError }>`

```typescript
import { isAllowed } from "@stellar/varial-sdk";

const result = await isAllowed();

if (result.isAllowed) {
  console.log("App is on the Allow List");
}
```

## Requesting Authorization

### `setAllowed()`

Prompt the user to authorize your app and add it to Varial's **Allow List**. Once approved, the extension can provide user data without additional prompts.

**Returns:** `Promise<{ isAllowed: boolean } & { error?: FreighterApiError }>`

```typescript
import { setAllowed } from "@stellar/varial-sdk";

const result = await setAllowed();

if (result.isAllowed) {
  console.log("App added to Allow List");
}
```

{% hint style="info" %}
If the user has already authorized your app, `setAllowed()` resolves immediately with `{ isAllowed: true }`.
{% endhint %}

## Requesting Access

### `requestAccess()`

Prompt the user to add your dapp to Varial's Allow List and return their public key in one call. This is the recommended way to connect — it combines authorization and data retrieval in a single step.

**Returns:** `Promise<{ address: string } & { error?: FreighterApiError }>`

If the user has previously authorized your app, the public key is returned immediately without a popup.

```typescript
import { isConnected, requestAccess } from "@stellar/varial-sdk";

// Always check isConnected first
const connectResult = await isConnected();
if (!connectResult.isConnected) {
  console.error("Varial is not installed");
  return;
}

const accessResult = await requestAccess();
if (accessResult.error) {
  console.error("Access denied:", accessResult.error.message);
} else {
  console.log("Public key:", accessResult.address);
}
```

{% hint style="warning" %}
Always check `isConnected()` before calling `requestAccess()` to ensure the extension is available.
{% endhint %}

## Disconnecting

### `disconnect()`

Revoke your app's access to the user's public key, for example from a "Disconnect" button in your app. Varial removes your app from the Allow List without asking the user to confirm, so the next call to `requestAccess()` or `setAllowed()` prompts the user again.

`disconnect()` is available in `@stellar/varial-sdk` 7.0.0 and later. `@stellar/freighter-api` 6.0.1 doesn't include it.

**Returns:** `Promise<{ error?: FreighterApiError }>`

```typescript
import { disconnect } from "@stellar/varial-sdk";

const result = await disconnect();

if (result.error) {
  console.error("Disconnect failed:", result.error.message);
} else {
  console.log("App removed from Allow List");
}
```

Calling `disconnect()` when your app isn't on the Allow List succeeds without changing anything. It returns an error if the user locked Varial manually or hasn't unlocked it since the browser started (an automatic lock after inactivity doesn't block it), or if the user's extension is a version that doesn't support `disconnect()`. The method was added in version 5.50.0 of the extension (the first Varial release), so earlier versions return an error.

{% hint style="warning" %}
Varial authorizes apps per account and per network, and `disconnect()` only revokes access for the account and network that are active when you call it. If the user previously authorized your app on another account or network, your app will have access to that public key again, without a prompt, when the user switches to it.
{% endhint %}

## Next steps

Once connected, you can [read the user's address and network](/extension-varial-sdk/reading-data) or [sign transactions](/extension-varial-sdk/signing).


# Reading Data

Retrieve the user's public key and network configuration from Varial.

{% hint style="info" %}
These methods require that the user has previously authorized your app via [`requestAccess()`](/extension-varial-sdk/connecting#requesting-access) or [`setAllowed()`](/extension-varial-sdk/connecting#requesting-authorization).
{% endhint %}

## Getting the User's Address

### `getAddress()`

A lightweight way to retrieve the user's public key. Unlike `requestAccess()`, this will **not** prompt the user — it returns an empty string if the app isn't authorized or Varial isn't connected.

**Returns:** `Promise<{ address: string } & { error?: FreighterApiError }>`

```typescript
import { getAddress } from "@stellar/varial-sdk";

const { address, error } = await getAddress();

if (error) {
  console.error(error.message);
} else {
  console.log("Public key:", address);
}
```

## Getting the Network

### `getNetwork()`

Get the name and passphrase of the network the user has selected in Varial.

**Returns:** `Promise<{ network: string; networkPassphrase: string } & { error?: FreighterApiError }>`

Possible `network` values: `PUBLIC`, `TESTNET`, `FUTURENET`, or `STANDALONE` (custom networks).

```typescript
import { getNetwork } from "@stellar/varial-sdk";

const { network, networkPassphrase, error } = await getNetwork();

if (!error) {
  console.log("Network:", network);           // e.g., "TESTNET"
  console.log("Passphrase:", networkPassphrase);
}
```

### `getNetworkDetails()`

Get comprehensive network configuration including the Horizon URL, passphrase, and Soroban RPC URL.

**Returns:** `Promise<{ network: string; networkUrl: string; networkPassphrase: string; sorobanRpcUrl?: string } & { error?: FreighterApiError }>`

```typescript
import { getNetworkDetails } from "@stellar/varial-sdk";

const details = await getNetworkDetails();

if (!details.error) {
  console.log("Network:", details.network);            // e.g., "TESTNET"
  console.log("Horizon:", details.networkUrl);          // e.g., "https://horizon-testnet.stellar.org"
  console.log("Passphrase:", details.networkPassphrase);
  console.log("Soroban RPC:", details.sorobanRpcUrl);   // e.g., "https://soroban-testnet.stellar.org"
}
```

{% hint style="info" %}
Use `getNetworkDetails()` instead of `getNetwork()` when working with Soroban smart contracts or when you need specific network endpoints.
{% endhint %}


# Signing

Sign transactions, authorization entries, and arbitrary messages using the user's Varial wallet.

## Signing a Transaction

### `signTransaction()`

Pass a transaction XDR string to Varial for the user to review and sign.

```
signTransaction(xdr: string, opts?: {
  network?: string,
  networkPassphrase?: string,
  address?: string
}) -> Promise<{ signedTxXdr: string; signerAddress: string } & { error?: FreighterApiError }>
```

The user will review the transaction details before signing.

**Parameters**

| Parameter                | Type     | Description                                                                              |
| ------------------------ | -------- | ---------------------------------------------------------------------------------------- |
| `xdr`                    | `string` | **Required.** Base64-encoded transaction XDR.                                            |
| `opts.network`           | `string` | Network name (maps to `Networks` enum in `@stellar/stellar-sdk`).                        |
| `opts.networkPassphrase` | `string` | Custom passphrase. Ignored if `network` is also provided.                                |
| `opts.address`           | `string` | Request a specific account's signature. Varial will switch to that account if available. |

{% hint style="info" %}
Passing `network` or `networkPassphrase` lets Varial warn the user if their wallet is configured to the wrong network.
{% endhint %}

**Example**

```typescript
import { signTransaction } from "@stellar/varial-sdk";

const { signedTxXdr, signerAddress, error } = await signTransaction(xdr, {
  network: "TESTNET",
  address: "G...", // optional: request a specific account
});

if (error) {
  console.error("Signing failed:", error.message);
} else {
  console.log("Signed by:", signerAddress);
  console.log("Signed XDR:", signedTxXdr);
}
```

**Errors**

| Condition               | Error message                                |
| ----------------------- | -------------------------------------------- |
| User rejected           | `"The user rejected this request."`          |
| Extension not installed | `"The wallet encountered an internal error"` |

## Signing an Auth Entry

### `signAuthEntry()`

Sign an [authorization entry preimage](https://github.com/stellar/js-stellar-base/blob/a9567e5843760bfb6a8b786592046aee4c9d38b2/types/next.d.ts#L6895) and receive the signed hash back as a base64 string. Used for [Soroban contract authorization](https://developers.stellar.org/docs/smart-contracts/guides/auth/authorization) flows.

```
signAuthEntry(entryXdr: string, opts: {
  address: string
}) -> Promise<{ signedAuthEntry: string | null; signerAddress: string } & { error?: FreighterApiError }>
```

See the [`authorizeEntry` helper](https://github.com/stellar/js-stellar-base/blob/e3d6fc3351e7d242b374c7c6057668366364a279/src/auth.js#L97) in `js-stellar-base` for how signed auth entries are used, or the [Soroban development documentation](https://developers.stellar.org/docs/smart-contracts) for wallet-side patterns.

**Example**

```typescript
import { signAuthEntry } from "@stellar/varial-sdk";

const { signedAuthEntry, signerAddress, error } = await signAuthEntry(entryXdr, {
  address: "G...",
});

if (error) {
  console.error("Auth entry signing failed:", error.message);
} else {
  console.log("Signed auth entry:", signedAuthEntry);
}
```

**Errors**

| Condition     | Error message                       |
| ------------- | ----------------------------------- |
| User rejected | `"The user rejected this request."` |

## Signing a Message

### `signMessage()`

Sign an arbitrary string and receive a base64-encoded Ed25519 signature. Follows [SEP-53](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0053.md).

```
signMessage(message: string, opts: {
  address: string
}) -> Promise<{ signedMessage: string | null; signerAddress: string } & { error?: FreighterApiError }>
```

**Example**

```typescript
import { signMessage } from "@stellar/varial-sdk";

const { signedMessage, signerAddress, error } = await signMessage(
  "Verify account ownership",
  { address: "G..." },
);

if (error) {
  console.error("Message signing failed:", error.message);
} else {
  console.log("Signature:", signedMessage);
}
```

**Errors**

| Condition     | Error message                       |
| ------------- | ----------------------------------- |
| User rejected | `"The user rejected this request."` |

## Full Example: Connect, Sign, and Submit

A complete flow from connection to Horizon submission:

```typescript
import { isConnected, requestAccess, signTransaction } from "@stellar/varial-sdk";
import { Server, TransactionBuilder } from "@stellar/stellar-sdk";

// 1. Check Varial is installed
const connectResult = await isConnected();
if (!connectResult.isConnected) {
  throw new Error("Varial not found");
}

// 2. Request the user's public key
const accessResult = await requestAccess();
if (accessResult.error) {
  throw new Error(accessResult.error.message);
}

// 3. Sign the transaction
const xdr = "AAAAAgAAAAA..."; // your assembled transaction XDR
const signResult = await signTransaction(xdr, {
  network: "TESTNET",
  address: accessResult.address,
});
if (signResult.error) {
  throw new Error(signResult.error.message);
}

// 4. Submit to Horizon
const server = new Server("https://horizon-testnet.stellar.org");
const tx = TransactionBuilder.fromXDR(
  signResult.signedTxXdr,
  "Test SDF Network ; September 2015",
);
const response = await server.submitTransaction(tx);
console.log("Transaction submitted:", response.hash);
```


# Token Management

Unlike Stellar assets, contract tokens a user owns are not automatically displayed in Varial — they must be explicitly added. This method lets your dapp prompt users to add a contract token directly, without the user having to find and add it in Varial manually.

{% hint style="info" %}
In a future release, Varial will auto-detect token transfers and display them automatically. Once that ships, `addToken()` will become a no-op.
{% endhint %}

## Adding a Token

### `addToken()`

Trigger an "add token" flow that displays token details in a modal for the user to review and approve.

```
addToken({ contractId: string, networkPassphrase?: string })
  -> Promise<{ contractId: string } & { error?: FreighterApiError }>
```

When called, Varial loads the token's **symbol**, **name**, **decimals**, and **balance** from the contract and displays them for the user to verify before adding.

### Parameters

| Parameter           | Type     | Description                                           |
| ------------------- | -------- | ----------------------------------------------------- |
| `contractId`        | `string` | **Required.** The contract token ID (`C...` address). |
| `networkPassphrase` | `string` | Defaults to Mainnet passphrase if omitted.            |

### Example

```typescript
import { isConnected, addToken } from "@stellar/varial-sdk";

const { isConnected: connected } = await isConnected();
if (!connected) return;

const result = await addToken({
  contractId: "CC...ABCD",
  networkPassphrase: "Test SDF Network ; September 2015", // optional
});

if (result.error) {
  console.error(result.error.message);
} else {
  console.log(`Token added: ${result.contractId}`);
}
```

{% hint style="info" %}
After the user approves, Varial will automatically track the token's balance and display it alongside other account balances.
{% endhint %}


# Watching Changes

Monitor the user's Varial wallet for address and network changes in real time.

## WatchWalletChanges

### `new WatchWalletChanges(timeout?: number)`

Creates a watcher that polls Varial for changes at a configurable interval.

| Parameter | Type     | Default | Description                       |
| --------- | -------- | ------- | --------------------------------- |
| `timeout` | `number` | `3000`  | Polling interval in milliseconds. |

### `watch(callback)`

Start polling. The callback fires only when something has changed (address, network, or passphrase).

```
watch(callback: ({ address: string; network: string; networkPassphrase: string }) => void)
```

### `stop()`

Stop polling for changes.

### Example

```typescript
import { WatchWalletChanges } from "@stellar/varial-sdk";

const watcher = new WatchWalletChanges(1000); // poll every second

watcher.watch((changes) => {
  console.log("Address:", changes.address);
  console.log("Network:", changes.network);
  console.log("Passphrase:", changes.networkPassphrase);
});

// Stop after 30 seconds
setTimeout(() => watcher.stop(), 30000);
```

{% hint style="info" %}
The callback only fires when a value actually changes — it won't emit duplicate events.
{% endhint %}


# Installation

Get up and running with WalletConnect so your dapp can connect to the Varial mobile app.

## Prerequisites

1. Sign up at [WalletConnect Dashboard](https://dashboard.walletconnect.com/) and create a project to get your **Project ID**.
2. Choose an installation method below.

## npm / yarn

```bash
npm install @walletconnect/universal-provider @reown/appkit
```

```bash
yarn add @walletconnect/universal-provider @reown/appkit
```

Then initialize the provider and modal:

```typescript
import { UniversalProvider } from "@walletconnect/universal-provider";
import { createAppKit } from "@reown/appkit/core";
import { mainnet } from "@reown/appkit/networks";

const projectId = "YOUR_PROJECT_ID";

// Provider — handles the WalletConnect protocol
const provider = await UniversalProvider.init({
  projectId,
  metadata: {
    name: "My Stellar Dapp",
    description: "A dapp that integrates with Varial",
    url: "https://my-dapp.com",
    icons: ["https://my-dapp.com/icon.png"],
  },
});

// Modal — displays the QR code and wallet list.
// AppKit requires at least one network. Stellar is not built-in,
// so we pass a placeholder. With manualWCControl the modal won't
// use it for chain switching.
const modal = createAppKit({
  projectId,
  networks: [mainnet],
  universalProvider: provider,
  manualWCControl: true,
});
```

## Next steps

| I want to...                        | Go to                                                         |
| ----------------------------------- | ------------------------------------------------------------- |
| Connect to the Varial mobile app    | [Connecting](/mobile-walletconnect/connecting)                |
| Sign a transaction                  | [Signing](/mobile-walletconnect/signing)                      |
| Feature Varial upfront in the modal | [Featuring Varial](/mobile-walletconnect/featuring-freighter) |

## Alternatives

[Stellar Wallets Kit](https://stellarwalletskit.dev/) provides a multi-wallet interface that includes WalletConnect support. From v2.3.0, its `WalletConnectModule` supports all four Varial methods:

| Stellar Wallets Kit method   | WalletConnect RPC method   |
| ---------------------------- | -------------------------- |
| `signTransaction()`          | `stellar_signXDR`          |
| `signAndSubmitTransaction()` | `stellar_signAndSubmitXDR` |
| `signMessage()`              | `stellar_signMessage`      |
| `signAuthEntry()`            | `stellar_signAuthEntry`    |

Use the kit if your dapp supports several Stellar wallets. Integrate WalletConnect directly, as shown in this guide, if you want full control over the session and the modal. Kit versions before v2.3.0 only support `stellar_signXDR` and `stellar_signAndSubmitXDR`.

{% hint style="warning" %}
The kit sends `stellar:pubnet` only for the Mainnet passphrase (`Networks.PUBLIC`) and `stellar:testnet` for anything else. It uses the `networkPassphrase` you pass on the call, or else the kit's network, which is Mainnet unless you set it with `init({ network })` or `setNetwork()`. Keep it in line with the network active in the Varial mobile app, or the request is rejected.
{% endhint %}

{% hint style="info" %}
Older examples may use `@walletconnect/sign-client` directly. That approach still works, but `@walletconnect/universal-provider` is the actively documented package. For more details, see the [UniversalProvider docs](https://docs.reown.com/advanced/providers/universal) and the [AppKit modal migration guide](https://docs.reown.com/appkit/upgrade/wcm).
{% endhint %}


# Overview

Connect your dapp to the Varial mobile app using the [WalletConnect v2](https://docs.walletconnect.network/app-sdk/overview) protocol. All methods follow the standard JSON-RPC 2.0 request/response format over a WalletConnect session.

## Supported Chains

| Network          | Chain ID          |
| ---------------- | ----------------- |
| Mainnet (PUBLIC) | `stellar:pubnet`  |
| Testnet          | `stellar:testnet` |

## API Reference

| Method                                                                               | Description                                                                                                                                         |
| ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`stellar_signXDR`](/mobile-walletconnect/signing#stellar_signxdr)                   | Sign a transaction and return the signed XDR                                                                                                        |
| [`stellar_signAndSubmitXDR`](/mobile-walletconnect/signing#stellar_signandsubmitxdr) | Sign and submit a transaction to Horizon                                                                                                            |
| [`stellar_signMessage`](/mobile-walletconnect/signing#stellar_signmessage)           | Sign an arbitrary UTF-8 message ([SEP-53](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0053.md))                           |
| [`stellar_signAuthEntry`](/mobile-walletconnect/signing#stellar_signauthentry)       | Sign a Soroban authorization entry preimage (as defined in [SEP-43](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0043.md)) |

## Error Handling

All error responses use JSON-RPC 2.0 format with code `5000`:

```json
{
  "id": 1234567890,
  "jsonrpc": "2.0",
  "error": {
    "code": 5000,
    "message": "User rejected the request"
  }
}
```

{% hint style="warning" %}
The Varial mobile app validates that the `chainId` in the request matches the wallet's active network. If the user is on the wrong network, the request is rejected. Always specify `chainId` as a separate argument to `provider.request()`, not inside `params`.
{% endhint %}

## Security

The Varial mobile app uses **Blockaid** scanning to protect users:

| Scan type            | When it runs                                                  |
| -------------------- | ------------------------------------------------------------- |
| **Site scan**        | Once during WalletConnect session connection                  |
| **Transaction scan** | For `stellar_signXDR` and `stellar_signAndSubmitXDR` requests |

`stellar_signMessage` and `stellar_signAuthEntry` do not trigger additional scans — the site was already scanned during connection.

## See also

* [WalletConnect v2 Docs](https://docs.walletconnect.network/app-sdk/overview)
* [Stellar Smart Contracts Auth](https://developers.stellar.org/docs/smart-contracts/guides/auth/authorization)
* [SEP-53: Message Signing](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0053.md)
* [SEP-43: Auth Entry Signing](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0043.md)


# Connecting

Establish a WalletConnect session with the Varial mobile app, handle session lifecycle events, and disconnect.

Assumes `provider` and `modal` are initialized as shown in [Installation](/mobile-walletconnect/installation).

## Creating a Session

Call `modal.open()` to show the wallet selection modal, then `provider.connect()` to start the pairing. The modal displays a QR code and a list of wallets — when the user selects Varial or scans the QR code, the connection is established automatically. `connect()` resolves once the wallet approves.

```typescript
// Open the modal (shows a spinner, then the QR code and wallet list)
modal.open();

// Connect — resolves when the wallet approves
const session = await provider.connect({
  namespaces: {
    stellar: {
      methods: [
        "stellar_signXDR",
        "stellar_signAndSubmitXDR",
        "stellar_signMessage",
        "stellar_signAuthEntry",
      ],
      chains: ["stellar:pubnet"],
      events: ["accountsChanged"],
    },
  },
});

if (!session) {
  throw new Error("Connection failed");
}

modal.close();
console.log("Connected! Session topic:", session.topic);
```

The connected session is also accessible at any time via `provider.session`.

Accounts are stored in `session.namespaces.stellar.accounts` as `"stellar:pubnet:G..."` strings — split on `:` to extract the public key:

```typescript
const publicKey = session.namespaces.stellar.accounts[0].split(":")[2];
```

{% hint style="info" %}
Use `namespaces` for methods your dapp needs to function. Use `optionalNamespaces` for methods that enhance the experience but aren't essential.

**Note:** `UniversalProvider` treats `namespaces` as optional at the protocol level on the first connection. After the wallet approves, the approved namespaces are persisted and become required on subsequent connections. To be safe, always verify the approved methods after connecting:

```typescript
const methods = session.namespaces.stellar?.methods || [];
if (!methods.includes("stellar_signXDR")) {
  throw new Error("Wallet does not support required methods");
}
```

{% endhint %}

## Handling Events

Listen for session lifecycle events to keep your UI in sync:

```typescript
// Session was disconnected by the wallet
provider.on("session_delete", ({ topic }) => {
  console.log("Session deleted:", topic);
});

// Session expired
provider.on("session_expire", ({ topic }) => {
  console.log("Session expired:", topic);
});
```

## Disconnecting

When the user wants to disconnect:

```typescript
await provider.disconnect();
```

## Next steps

Once connected, you can [sign transactions, messages, and auth entries](/mobile-walletconnect/signing).


# Signing

Sign transactions, messages, and Soroban authorization entries via WalletConnect.

Assumes `provider` and `modal` are initialized as shown in [Installation](/mobile-walletconnect/installation).

{% hint style="info" %}
The WalletConnect RPC methods use different response field names than the extension API. For example, `stellar_signXDR` returns `signedXDR` while the extension's `signTransaction()` returns `signedTxXdr`. See the response tables below for each method's exact fields.
{% endhint %}

## Signing a Transaction

### `stellar_signXDR`

Sign a transaction and return the signed XDR. The transaction is **not** submitted to the network — your dapp is responsible for submission.

**Parameters**

| Parameter | Type     | Description                                                                             |
| --------- | -------- | --------------------------------------------------------------------------------------- |
| `xdr`     | `string` | **Required.** Base64-encoded `TransactionEnvelope` or `FeeBumpTransactionEnvelope` XDR. |

**Response**

| Field       | Type     | Description                            |
| ----------- | -------- | -------------------------------------- |
| `signedXDR` | `string` | Base64-encoded signed transaction XDR. |

```typescript
const result = await provider.request(
  {
    method: "stellar_signXDR",
    params: { xdr: "AAAAAgAAAAA..." },
  },
  "stellar:pubnet",
);

console.log("Signed XDR:", result.signedXDR);
```

**Errors**

| Condition            | Error message                                                                                                                            |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| Chain not supported  | `"The chain <chainId> is not supported. Please make sure the transaction you are trying to sign was built on a supported Stellar chain"` |
| Wrong active network | `"Please switch to <network> in Varial Settings and try again"`                                                                          |
| XDR parse failure    | `"Failed to sign transaction"`                                                                                                           |
| User rejected        | `"User rejected the request"`                                                                                                            |

***

### `stellar_signAndSubmitXDR`

Sign a transaction **and** submit it to Horizon in one step.

**Parameters**

| Parameter | Type     | Description                                                                             |
| --------- | -------- | --------------------------------------------------------------------------------------- |
| `xdr`     | `string` | **Required.** Base64-encoded `TransactionEnvelope` or `FeeBumpTransactionEnvelope` XDR. |

**Response**

| Field    | Type     | Description                                               |
| -------- | -------- | --------------------------------------------------------- |
| `status` | `string` | `"success"` when the transaction is signed and submitted. |

```typescript
const result = await provider.request(
  {
    method: "stellar_signAndSubmitXDR",
    params: { xdr: "AAAAAgAAAAA..." },
  },
  "stellar:pubnet",
);

console.log("Status:", result.status); // "success"
```

**Errors**

| Condition                  | Error message                                                                                                                            |
| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| Chain not supported        | `"The chain <chainId> is not supported. Please make sure the transaction you are trying to sign was built on a supported Stellar chain"` |
| Wrong active network       | `"Please switch to <network> in Varial Settings and try again"`                                                                          |
| XDR parse / sign failure   | `"Failed to sign transaction"`                                                                                                           |
| Horizon submission failure | `"Failed to submit transaction"`                                                                                                         |
| User rejected              | `"User rejected the request"`                                                                                                            |

{% hint style="info" %}
Use **`stellar_signXDR`** when you need to inspect or modify the signed transaction before submission. Use **`stellar_signAndSubmitXDR`** for a simpler flow where Varial handles everything.
{% endhint %}

***

## Signing a Message

### `stellar_signMessage`

Sign an arbitrary UTF-8 text message with the wallet's active key, following [SEP-53](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0053.md).

**Parameters**

| Parameter | Type     | Constraints                     | Description                    |
| --------- | -------- | ------------------------------- | ------------------------------ |
| `message` | `string` | Non-empty, max 1024 UTF-8 bytes | The plaintext message to sign. |

**Response**

| Field       | Type     | Description                                    |
| ----------- | -------- | ---------------------------------------------- |
| `signature` | `string` | Base64-encoded Ed25519 signature (per SEP-53). |

```typescript
const result = await provider.request(
  {
    method: "stellar_signMessage",
    params: { message: "Please sign to verify account ownership" },
  },
  "stellar:pubnet",
);

console.log("Signature:", result.signature);
```

**Errors**

| Condition                     | Error message                  |
| ----------------------------- | ------------------------------ |
| Missing or non-string message | `"Invalid message"`            |
| Empty message                 | `"Cannot sign empty message"`  |
| Message exceeds 1 KB          | `"Message too long (max 1KB)"` |
| Signing failed                | `"Failed to sign message"`     |
| User rejected                 | `"User rejected the request"`  |

***

## Signing an Auth Entry

### `stellar_signAuthEntry`

Sign a Soroban authorization entry preimage for multi-auth and custom-account smart contract workflows. Follows [SEP-43](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0043.md).

Your dapp constructs the `HashIdPreimage` (network ID + nonce + expiry + invocation), and Varial hashes it with SHA-256 and signs the digest.

{% hint style="warning" %}
The Varial mobile app performs a **Blockaid site scan** during the initial WalletConnect session connection — no additional scan runs at auth-entry signing time. Review the contract address, function name, and subinvocations displayed in the UI before confirming.
{% endhint %}

**Parameters**

| Parameter  | Type     | Constraints               | Description                                                                                                                                                         |
| ---------- | -------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `entryXdr` | `string` | Non-empty, non-whitespace | Base64-encoded `HashIdPreimage` XDR (envelope type `envelopeTypeSorobanAuthorization`). Build from the `SorobanAuthorizationEntry` returned by contract simulation. |

**Response**

| Field             | Description                                                                |
| ----------------- | -------------------------------------------------------------------------- |
| `signedAuthEntry` | Base64-encoded 64-byte Ed25519 signature over `SHA-256(preimage)`.         |
| `signerAddress`   | Stellar public key (G-address) of the account that produced the signature. |

```typescript
const result = await provider.request(
  {
    method: "stellar_signAuthEntry",
    params: { entryXdr: "AAAAAQ..." },
  },
  "stellar:pubnet",
);

console.log("Signature:", result.signedAuthEntry);
console.log("Signer:", result.signerAddress);
```

**Errors**

| Condition                                          | Error message                                      |
| -------------------------------------------------- | -------------------------------------------------- |
| Missing, non-string, or whitespace-only `entryXdr` | `"Invalid authorization entry"`                    |
| XDR parse failure                                  | `"Failed to process auth entry"`                   |
| `networkId` doesn't match active network           | `"Authorization entry is for a different network"` |
| User rejected                                      | `"User rejected the request"`                      |

## Full Example: Connect, Sign, and Submit

A complete flow from connection to transaction signing. The AppKit modal displays both a QR code and a list of wallets. When a user opens your dapp in the Varial mobile app's in-app browser, they select Varial from the wallet list to deep-link into the connection approval — no QR code scanning needed. From an external browser, the user scans the QR code with their phone instead.

```typescript
import { UniversalProvider } from "@walletconnect/universal-provider";
import { createAppKit } from "@reown/appkit/core";
import { mainnet } from "@reown/appkit/networks";

const projectId = "YOUR_PROJECT_ID";

// 1. Initialize provider and modal
const provider = await UniversalProvider.init({
  projectId,
  metadata: {
    name: "My Stellar Dapp",
    description: "A dapp that integrates with Varial",
    url: "https://my-dapp.com",
    icons: ["https://my-dapp.com/icon.png"],
  },
});

// AppKit requires at least one network. Stellar is not built-in,
// so we pass a placeholder. With manualWCControl the modal won't
// use it for chain switching.
const modal = createAppKit({
  projectId,
  networks: [mainnet],
  universalProvider: provider,
  manualWCControl: true,
});

// 2. Open the modal and connect
modal.open();

const session = await provider.connect({
  namespaces: {
    stellar: {
      methods: ["stellar_signXDR", "stellar_signAndSubmitXDR", "stellar_signMessage", "stellar_signAuthEntry"],
      chains: ["stellar:pubnet"],
      events: ["accountsChanged"],
    },
  },
});

if (!session) {
  throw new Error("Connection failed");
}

modal.close();

// 3. Sign a transaction
const xdr = "AAAAAgAAAAA..."; // your assembled transaction XDR
const result = await provider.request(
  {
    method: "stellar_signXDR",
    params: { xdr },
  },
  "stellar:pubnet",
);

console.log("Signed XDR:", result.signedXDR);
```


# Featuring Varial

When a user opens the WalletConnect / Reown modal in your dapp, wallets in the **featured row** are shown first — most users pick from there without scrolling or using the search bar. If your dapp is built for Stellar, featuring Varial makes it discoverable upfront and improves conversion for Stellar users.

## Varial's WalletConnect Explorer ID

```
997a355c8f682468706a76cff1b004a7115f505fb962dac54b6e9b442dd1c380
```

This is the **public** identifier of Varial's listing in the [WalletGuide Explorer](https://walletguide.walletconnect.network/) (a.k.a. Reown Explorer). It is not the same as your dapp's WalletConnect **Project ID** — Project IDs identify the dapp/wallet account on the WalletConnect relay, while Explorer IDs identify a public wallet listing in the directory.

This ID did not change when Freighter became Varial, so existing `featuredWalletIds` configs keep working. The Explorer ID can change if Varial's listing is rotated (e.g. after a security key rotation on our end). If Varial ever stops appearing in the featured row, look up the current ID using one of the following:

* **UI:** Open [WalletGuide](https://walletguide.walletconnect.network/) → search "Varial" → click the card → copy the `Wallet ID` field from the detail view. The listing is being renamed from Freighter, so if "Varial" doesn't find it yet, search "Freighter" instead.
* **API:** `curl "https://explorer-api.walletconnect.com/v3/wallets?projectId=<your-wc-project-id>&search=varial"` and read `id` from the Varial entry in the response (or use `search=freighter` if the listing still shows the old name). Use your own WalletConnect **Project ID** here — the one you got from the [WalletConnect Dashboard](https://dashboard.walletconnect.com/) during [Installation](/mobile-walletconnect/installation). The `projectId` param is just used for rate-limiting and must be a valid registered project ID, but it does not filter results — every valid project ID returns the same global wallet directory, so Varial will appear in the response regardless of which valid ID you use.

## Option A — Direct WalletConnect / Reown integration

If you set up the modal directly with `@reown/appkit` (as in [Installation](/mobile-walletconnect/installation)), pass `featuredWalletIds` to `createAppKit`:

```typescript
import { createAppKit } from "@reown/appkit/core";
import { mainnet } from "@reown/appkit/networks";

const modal = createAppKit({
  projectId,
  networks: [mainnet],
  universalProvider: provider,
  manualWCControl: true,
  featuredWalletIds: [
    "997a355c8f682468706a76cff1b004a7115f505fb962dac54b6e9b442dd1c380", // Varial
  ],
});
```

You can include other wallet IDs in the same array — they appear in the featured row in the order you list them.

## Option B — Stellar Wallets Kit

[Stellar Wallets Kit](https://stellarwalletskit.dev/) (SWK) includes Varial in `featuredWalletIds` by default for its `WalletConnectModule`, so on recent versions of the kit you get featured placement automatically — no extra config needed.

If you're on an older kit version (or the kit's default has gone stale), you can override the value via `appKitOptions.featuredWalletIds`:

```typescript
import { WalletConnectModule } from "@creit-tech/stellar-wallets-kit/modules/wallet-connect";

const wc = new WalletConnectModule({
  // ...your usual config (projectId, allowedChains, ...)
  appKitOptions: {
    featuredWalletIds: [
      "997a355c8f682468706a76cff1b004a7115f505fb962dac54b6e9b442dd1c380", // Varial
    ],
  } as unknown as ConstructorParameters<typeof WalletConnectModule>[0]["appKitOptions"],
});
```

The cast is needed because `appKitOptions` is typed as the full `CreateAppKit` shape, but the kit only forwards a subset of those options to the underlying modal — so passing just `featuredWalletIds` is correct at runtime but doesn't satisfy the static type. Prefer the narrow `as unknown as ConstructorParameters<...>` cast over `as any`: the runtime behavior is identical, but the assertion stays scoped to this property value rather than erasing type-checking everywhere `appKitOptions` is consumed.


# Third-Party Integrations

Varial connects to third-party services to provide a better user experience. As an open source project, we document these integrations so other wallet developers can adopt similar patterns.

## Multi-Wallet Support

If your dapp needs to support multiple Stellar wallets beyond Varial, [Stellar Wallets Kit](https://stellarwalletskit.dev/) provides a unified interface for connecting to any Stellar wallet. It handles wallet detection, connection, and signing through a single API, so your users can choose whichever wallet they prefer.

## Available Integrations

| Integration                                                                                                   | Description                                      |
| ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ |
| [Stellar Wallets Kit](https://stellarwalletskit.dev/)                                                         | Unified multi-wallet interface for Stellar dapps |
| [Soroswap](https://github.com/stellar/freighter/blob/master/extension/INTEGRATING_SOROSWAP.MD)                | DEX integration for token swaps                  |
| [Hardware Wallets](https://github.com/stellar/freighter/blob/master/extension/INTEGRATING_HARDWARE_WALLET.MD) | Ledger and other hardware wallet support         |


