# Introduction

Rujira: Building the Omnichain DeFi rails for Humans and Machines

Welcome to **Rujira**, the powerful App Layer on **THORChain** with an integrated suite of DeFi tools and dapps, accessible with native assets from all connected chains. As an introduction, we would like to share some background on what we stand for, and what makes us unique.

### Resilience

We are committed, long-term builders: we survived the Terra crash in 2022, we survived the KUJI liquidation cascade in 2024, and we survived the THORFi blow-up in 2025. No matter the challenge, we always find a way and keep building. This has allowed us to create one of the most resilient and passionate communities in crypto ❤️

### Change

Overzealous regulators in the US, lacking vision and clarity, have created pockets of darkness in the industry enabling some operators to act like big casinos, allowing scammers to lurk. This is a far cry from a productive crypto sector supporting new financial instruments, democratization of assets’ ownership and enabling innovation in areas such as artificial intelligence.

The latest US administration gives us a chance to build real products for real people, generating real value. With the hope that improved clarity on regulations will allow these DeFi products to be accessed outside of a pure crypto space.

Eventually, we hope to see the next generation of business owners using our launchpad to raise money to e.g. open a restaurant. Then launch a DAO to manage the board transparently and benefit from real time accounting and professional-grade reporting, at a fraction of the cost of running a traditional business. Crypto can only win if it moves beyond crypto.

### No bullshit, real value

Rujira is the place where everything comes together, a unified ecosystem where all the different chains, wallets, and DeFi products converge into something bigger. We are not playing the short-term hype game. We are building the omnichain DeFi rails for humans and machines, with a sustainable economic model for the decades to come. All products across our comprehensive DeFi stack charge some protocol fees which are distributed in USDC to RUJI stakers (net of the share of revenue going to THORChain Base Layer). Owning RUJI is owning a share of all economic activity happening on the App Layer.

### Built different

From great challenges emerge incredible opportunities. Building the App Layer on top of THORChain’s technology gives us some unique edges:

1. We can **tap into THORChain's deep liquidity**, which fixes one of Kujira's biggest historical challenges: liquidity bootstrapping.
2. We can **remove all dependence on third-party bridges and wrapped tokens**, enabling access to DeFi with native assets from all connected chains.
3. In particular, we can **become the cornerstone of BitFra**, providing access to DeFi with native BTC and capitalizing on the next wave of institutional and governmental BTC adoption.
4. Our apps are **omnichain, accessible from all connected chains**, all at once, and via any supported wallet.

Building the Rujira App Layer provides us with a unique opportunity in software development. We get to greenfield something we had already built and fix literally every issue we have seen over the years with Kujira. Truly satisfying.

### Drilling down - what makes Rujira unique

#### 1. DeFi with native assets

* No third-party bridges or wrapping by centralised intermediaries.
* The only place where you can trade native BTC, but also native assets from all other connected chains, in an orderbook DEX; take a loan against native BTC; have a stablecoin backed by native BTC, etc.

#### 2. Comprehensive DeFi suite in a Unified UI

* Orderbook DEX, AMM strategies, Perps, Money Market, BTC-backed stablecoin, Liquidations, Launchpad, NFT Marketplace, Options, AI Agents.
* No need to navigate between different websites for each application.
* Provides a CEX-like experience, but 100% decentralized.
* Accessible from a dedicated mobile app (Station).
* Accessible from a ChatGPT-like AI interface.

#### 3. Highly integrated ecosystem (circular)

* Because we control the full stack, everything works together as a seamless ecosystem.
* The AMM adds liquidity to the orderbook DEX.
* The money market provides leverage for regular CDP loans and margin trading.
* The liquidation engine protects all debt related products (loans, CDP stablecoins, margin trading).
* The liquidity of THORChain Base Layer is virtualized via an AMM arbitrage strategy tapping into liquidity from the money market.
* The liquidity in the orderbook supports liquidation bids which are processed via market orders.
* Everything works together seamlessly within a coherent ecosystem.

#### 4. Rujira is omnichain

* As a user, connect your Bitcoin, Ethereum, Solana, Cosmos, etc. wallets and you will see your aggregated balances appear across all apps, and you will be able to trigger transactions from any connected chain, regardless of where your assets are.
* As a builder, deploy once on Rujira and make your app available from all connected chains and wallets. Rujira is the only place where you can accept direct deposits from all major L1 to your app.

#### 5. No liquidity bootstrapping risk

* We virtualize THORChain's Base Layer liquidity via an arbitrage market making strategy, allowing Rujira to execute taker orders against TC \~$50m liquidity.
* For volumes executed against Base Layer liquidity, each $1 of volume on the App Layer = \~$1 of volume of the Base Layer, which generates fees for TC, which means 100% of the revenue on the App Layer side is sent to RUJI stakers.
* We expect the growth in other products in the next few years - notably Perps, BTC-backed stablecoin and launchpad - will reduce the share of revenue coming from spot trading, reducing the reliance on Base Layer liquidity.

#### 6. Sustainable economic model

* All products across our comprehensive DeFi stack charge some protocol fees which are distributed in USDC to RUJI stakers (net of the share of revenue going to THORChain Base Layer).&#x20;
* RUJI token has no inflation, all the staking rewards are based on real revenue.
* Owning RUJI is owning a share of all economic activity happening on the App Layer.

### Getting Started

Before exploring the App Layer on THORChain, take the time to understand how Rujira and RUJI came about, how it works by building on top of THORChain by first reviewing:

* [Understanding Rujira History](/understanding-rujira-history)
* [Understanding RUJI](/understanding-ruji-token)
* [How it Works](/how-it-works/understanding-the-app-layer)

If you are looking to build on Rujira, then you can go straight to [Getting Started](/developers/getting-started) and the [Development Process](/developers/development-process) in the Developers section.


# Understanding Rujira History

Rujira was born from a partnership between **Kujira**, **Levana** and **THORChain**, known as the Rujira Alliance. Kujira, Levana and three Kujira ecosystem projects are being merged into Rujira, which becomes the App Layer on THORChain, unlocking powerful synergies:

* **THORChain** provides deep liquidity, cross-chain capabilities and security for the App Layer.
* **Kujira + ecosystem projects** and **Levana** provide a complete suite of DeFi products unified under a single brand and UX, and a new stream of income for THORChain in the form of revenue share.

### **Core Projects in the Merger**

The unified THORChain App Layer will incorporate various teams including Kujira, three Kujira ecosystem projects (Fuzion, Unstake, Gojira) and Levana.

These teams will form the backbone of Rujira, focusing on specific verticals within the DeFi ecosystem, ensuring that each product is built by experts.

Following the merger, the Rujira brand will become the official face of the THORChain App Layer, with the core team continuing to build out a world-class suite of DeFi tools. All current protocols on Kujira are encouraged to migrate to the new App Layer to benefit from THORChain’s liquidity and interoperability.

Kujira’s vision of providing sustainable, decentralized financial tools remains intact, but now enhanced with THORChain’s capabilities. This partnership creates new possibilities for DeFi innovation, offering developers and users a unique ecosystem for building and scaling financial applications.

The Rujira merger represents a pivotal moment for both Kujira and THORChain, bringing together the best of both worlds: Kujira’s innovative DeFi solutions and THORChain’s deep liquidity and cross-chain capabilities. Together, they are building a decentralized future where financial opportunities are accessible, inclusive, and powered by community-driven innovation.

In the following sections, we will explore the relationship between Rujira and each of those three parties, and how it all ties together into the **RUJI tokens**, accruing value from the economic activity happening on the App Layer. To get going, dive into:

* [Rujira & Kujira](/understanding-rujira-history/rujira-and-kujira)
* [Rujira & THORChain](/understanding-rujira-history/rujira-and-thorchain)
* [Rujira & Levana](/understanding-rujira-history/rujira-and-levana)


# Rujira & Kujira

Kujira has successfully developed an innovative and cohesive DeFi ecosystem. However, recognizing past challenges, a newly announced partnership with THORChain marks an exciting new phase, offering significant potential for both platforms. See the official announcement about the Rujira Alliance:

{% embed url="<https://x.com/TeamKujira/status/1833068459367764025?t=idJB1EjKcb0MjtNVB_VwJg&s=19>" %}

### What Will This Partnership Solve?

While this collaboration will generate real-yield rewards for THORChain by distributing 50% of core Rujira dApps' revenue to RUNE bonders and liquidity providers (LPs), it's important to consider what THORChain offers to Rujira, as well as the additional benefits Rujira brings to THORChain.

#### THORChain’s Unique Capabilities

THORChain is a sovereign Layer-1 blockchain, distinct from most general-purpose platforms. Its design focuses on a specific set of groundbreaking functions, including:

* Direct integration with native tokens from external chains
* Cross-chain swaps
* Liquidity provision
* Savings and lending services

In essence, THORChain has solved the problem of native liquidity for cross-chain interoperability — a solution from which Rujira stands to gain substantially.

#### Integrated Core Functionalities

These functionalities are not deployed through smart contracts, but are embedded directly into the THORChain core. This is because THORChain does not support generic smart contracts like CosmWasm, which introduces certain limitations.

However, this also necessitates a more innovative approach to economic security. Unlike most DeFi platforms that use wrapped tokens (which can become worthless in case of an exploit), a breach of THORChain (e.g., draining native BTC or ETH) would still allow the attacker to profit from the stolen assets. To address this, THORChain employs rigorous security measures. Since 2021, THORSec, an always-on security detail, has safeguarded its operations, ensuring the highest levels of security for the ecosystem.

#### Enhancing with CosmWasm

Given THORChain’s design, it makes sense to develop an application layer with CosmWasm functionality, especially with support from Kujira’s experienced development team.

### The Missing Piece for Kujira

For Kujira, migrating to become Rujira fills a critical gap. By building on THORChain, Kujira gains access to one of the most liquid, high-volume environments of native assets and cross-chain interoperability within decentralized finance. This combination will help Kujira resolve key pain points (visibility and liquidity bootstrapping) and realize its vision of delivering a state-of-the-art DeFi experience.


# Rujira & THORChain

Rujira is the App Layer of THORChain, connecting its comprehensive ecosystem of DeFi applications with THORChain’s deep liquidity and cross-chain capabilities. This merger unlocks a powerful synergy, enabling projects to tap into THORChain’s liquidity, native token support, and interoperability while offering a seamless, user-friendly experience for DeFi users.

[RUJI](/understanding-ruji-token) will serve as the fee-switch token for the THORChain App Layer, enabling stakers to capture the revenue generated by applications that join the Rujira Alliance, after accounting for the portion shared with THORChain Base Layer to cover security costs.

The standard revenue split between core applications and the Base Layer is 50/50. However, any economic activity that already contributes value to the Base Layer, such as applications built on top of the Rujira primitives, will not be required to pay for security twice.


# Rujira & Levana

{% hint style="info" %}
This section is for historical context only. After the first 12 months, the Levana contract was not renewed, they are no longer part of the Rujira Alliance. Their isolated version of Perps has been discontinued and will be replaced by a peer-to-peer orderbook model fully integrated with the wider Rujira ecosystem.
{% endhint %}

## Introducing RUJI Perps

Levana is excited to announce its partnership with the Rujira Alliance to build RUJI Perps, a new perpetuals (perps) trading platform alongside Kujira and THORChain.

RUJI Perps is a cornerstone of the Rujira Alliance, combining THORChain’s liquidity with the expertise of Kujira and Levana. The platform aims to offer trustless, Bitcoin-backed perpetual futures trading, enabling users to trade using Bitcoin as collateral.

The market for Bitcoin is substantially larger than the DeFi market, and RUJI Perps seeks to attract these users by providing a seamless experience rivaling centralized exchanges.

## Staking and Rewards

All protocol fees from RUJI Perps will be distributed as staking rewards, enhancing the value proposition for RUJI and RUNE stakers. Based on current DeFi market volumes, if RUJI Perps captures just 1% of the perpetuals market (about $60 million in daily volume), it could generate approximately $5.7 million annually for RUJI and RUNE stakers.

The synergy between THORChain’s native cross-chain liquidity and RUJI Perps' unique design will drive the growth of liquidity and trading volume, benefiting the entire Rujira ecosystem.

## LVN to RUJI Conversion Process

Levana’s LVN holders will have the option to swap their tokens for a share of the 5% of the RUJI supply allocated to Levana. All locked and vested LVN tokens will be unlocked in advance of the swap. This process will operate on a bonding curve over 12 months, with better conversion rates available early in the process.

## Long-Term Merger Incentives

Users who keep their RUJI in the merger contract for up to 12 months will benefit from increased conversion rates over time. Users can withdraw their RUJI at any time, but once withdrawn, they cannot deposit back into the merger contract, leading to more rewards for the ones who stay. Early participants who stay deposited in the merger contract for the full 12-month period will receive the most RUJI relative to the LVN swapped.


# Understanding RUJI Token

RUJI is the native token for the THORChain App Layer. Staking RUJI allows users to earn fees generated across the App Layer, benefiting from THORChain’s high liquidity. Staking is available on the [Staking page](https://rujira.network/strategies/staking/RUJI).

## Tokenomics

### Total supply

100M RUJI

### Inflation

No inflation, supply is capped at 100m RUJI.

### Utility

RUJI will serve as the fee-switch token for Rujira core products, enabling stakers to capture the revenue generated by applications that join the Rujira Alliance, after accounting for the portion shared with THORChain Base Layer to cover security costs. As outlined in the initial partnership announcement, the standard revenue split between core applications and the Base Layer is 50/50. However, any economic activity that already contributes value to the Base Layer, such as applications built on top of the Rujira primitives, will not be required to pay for security twice.

<figure><img src="/files/gCjAZCDsdyGHRLld2JO1" alt=""><figcaption></figcaption></figure>

### Allocations

<figure><img src="/files/WKBOSjfPcBgS4XIskVCC" alt=""><figcaption><p><em>TGE date: 19 June 2025</em>  </p></figcaption></figure>

* Kujira & Merged Ecosystem Apps (50%)
* Levana (5%)
* Ecosystem Fund (7.5%): To be used at the discretion of the Rujira team for protocol-own liquidity, incentives, airdrops and other activities aimed at attracting users, builders and stimulating economic activity.
* Builders Incentive Pool (7.5%): To be allocated as performance bonuses to apps, builders, and other Rujira Alliance contributors based on revenue contribution over four years, to ensure that the verticals that contribute the most value to RUJI are rewarded for it.
* Operations (15%): To be used at the discretion of the Rujira team to fund operational expenses, developers' grants, centralized exchanges listings, provision market makers liquidity, and engage in value-added on-chain activities such as building up long-term protocol-own liquidity (e.g. to make market on the Rujira orderbook DEX via RUJI Pools or invest in ecosystem projects).
* New investors (15%): Raised in a single rounds to capitalize the Operations treasury.

## Conversion Process (closed)

{% hint style="info" %}
*The merge period terminated on 5th April 2026. Merging legacy tokens is no longer possible.*
{% endhint %}

RUJI was born from the merger of 6 projects where holders of KUJI, FUZN, NSTK, WINK, LVN, and NAMI were able to convert their tokens into RUJI.

There were two different merge processes that completed:

1. **The Merge:** Holders of KUJI, FUZN, NSTK, WINK, and LVN tokens had 12 months from the merger date (05 April 2025) to convert their tokens to RUJI. The conversion rate started to decay after 4 weeks and decreased linearly over the 12-month period, with early converters receiving the best rates. Key details:

<figure><img src="/files/0nw3Mvnny1mX7SgHpYeX" alt=""><figcaption></figcaption></figure>

2. **The NAMI Merge:** NAMI token holders had six months from the merger date (22 September 2025) to convert their tokens into RUJI. For the first four weeks, the conversion rate remained fixed at 0.013 RUJI per NAMI. After this period, the rate declined linearly over the remaining five months, incentivizing early participation. Maximum merge supply was capped at 74 million NAMI.

Users could choose to keep their RUJI in the merger contract during the conversion period to earn additional rewards. Users could withdraw their RUJI at any time, but once withdrawn, they were not able to deposit back into the merger contract, leading to more rewards for the ones who stayed.

#### Bonding Curve & Decay

Starting from the merger date, users had 12 months (6 months for NAMI) to convert their tokens into RUJI. During the first 4 weeks, the conversion rate was 1:1\*, after which it gradually decreased on a linear scale, reaching 1:0 by the end of the 12-month period.

*\*Note: The conversion rate shown in the table above is considered 1:1 in instances where 1 merge token does not equate to 1 RUJI.*

<figure><img src="/files/sbRcIBu8YZPZoQ4BC36S" alt=""><figcaption><p>12-month decay</p></figcaption></figure>

#### Token Bonus

As not all tokens were converted, and part was converted late at less than a 1:1 ratio, there were an accumulation of excess RUJI tokens. These excess tokens were distributed as rewards to users who chose not to withdraw their RUJI immediately.

The share of excess tokens a user earned depend on when they initiated the conversion and how long they held their RUJI before withdrawing.

Users could withdraw both their converted and reward tokens at any time without any unbonding period, but they could not redeposit to earn additional rewards. Partial withdrawal from the merger contract were possible.

<figure><img src="/files/dbgDB6quiHfwEO5TS00T" alt=""><figcaption><p>12-month token bonus</p></figcaption></figure>

## Merge Flow

The Switch Handler on THORChain facilitated the migration of assets from external chains (e.g. Gaia) to THORChain’s native assets.

Originally, it enabled users to convert RUNE tokens from Binance Chain (BEP2) to native RUNE on THORChain. The process involved sending BEP2 RUNE to a designated address with a SWITCH memo, triggering the handler to mint an equivalent amount of native RUNE to the user’s THORChain address.

We used this Switch Handler for all the Kujira and Levana tokens to migrate and become THORChain-native assets. These assets comprised two categories:

* Tokens migrating and merging into $RUJI: <mark style="color:blue;">$KUJI, $rKUJI, $FUZN, $NSTK, $WINK, $LVN, $NAMI</mark>
* Tokens migrating but not merging: <mark style="color:blue;">$AUTO, $LQDY (ex. $MNTA)</mark>

The process for switching above tokens to become THORChain-native assets involved:

1. Reinstating the Switch Handler: Removing the previous kill switch logic to allow new migrations.
2. Configuring On-Chain Parameters: Defining source assets, target denominations, and burn addresses in an on-chain configuration. For example for $KUJI:
   1. source\_asset: `GAIA.KUJI-XXXXXXXXX`
   2. target\_asset: `kuji`
   3. burn\_address: `cosmos100000000000000000000000000000000708mjz`
3. Executing the Switch: Users send their external assets to the THORChain GAIA.ATOM vaults, node operators validate the deposit and the network (a) mints a native token on THORChain and (b) sends the external asset on Gaia to the burn address.
4. Asset Purging: Transferred assets are sent to the designated burn address and removed from system accounting to prevent double-spending.

<figure><img src="/files/N2Jx5sFj3NxhdXfMXIB2" alt=""><figcaption></figcaption></figure>


# Understanding the App Layer

### Primer on Cosmos architecture

* Every address on a Cosmos chain has an Account.
* The Bank module accounts for ownership of tokens in a key-value store, where the key is the address<>denom, and the value is the balance.
* CosmWasm has a 2 step process:
  1. "Store" - Code is stored with an integer Code ID.&#x20;
  2. "Instantiate" - A Code ID is instantiated and each instance gets its own address.
* As it has an address, the bank module can now account for funds held by a contract.
* When a CosmWasm contract is executed, at the end of execution, it can emit SubMsgs which are basically the same as the contract signing and broadcasting those Msg types itself.

### App Layer’s authorization: What is the App Layer allowed to do?

* Cosmos chains have discrete Msg types. The only two on THORChain that a user is allowed to use are MsgSend and MsgDeposit. You use MsgSend for sending RUNE, and MsgDeposit to "do things". Those things are encoded in the memo, e.g. swap RUNE for BTC, bond RUNE to a node operator.
* There are a bunch of other message types which only active node operators can call, e.g. MsgObservedTxIn, MsgObservedTxOut and MsgMimir.
* When you install CosmWasm to a Cosmos chain, you can define "custom bindings", that you connect to Golang chain code for arbitrary execution (more info [here](https://docs.rs/cosmwasm-std/latest/cosmwasm_std/enum.CosmosMsg.html#variant.Custom)). THORChain's CosmWasm does not have this.
* In fact, THORChain has non-standard Staking, Distribution and Gov Msgs. The only variants of CosmosMsg that are valid are BankMsg, Any and Wasm.
* The Any msg variant is key here. A CosmWasm contract can only interact with THORChain via Any, and it's subject to all the same rules that an EOA is subject to.

### Consensus layer integration

* MsgDeposit has a fixed 0.02 RUNE fee.
* Smart Contracts are called with MsgExecuteContract, which can have a wide range of gas usage based on the logic of the contract.
* All Msg types share the same mempool. In our integration, any Msg type that is signed by an Active Node gets priority in the mempool. CosmWasm tx types are second class citizens in order to ensure that the core protocol continues to operate uninterrupted.
* The price that is charged for the gas that someone requests for their tx is set by node mimir. it defaults to 0, and is an economic Mimir to update it (2/3+ consensus required).

<br>

<figure><img src="/files/DiXtY3eZyrhLNrCovJCW" alt=""><figcaption></figcaption></figure>

### Secured Assets

* The App Layer only uses Secured Assets (which itself is a fork of Trade Assets, but transferable). Users deposit L1 assets and mint Secured Assets 1:1.&#x20;
* Secured Assets are "optimistically secured" by THORChain validators (they are not inside the Incentive Pendulum). Secured Assets make TC nodes money from App Layer fees, this is how they pay for their security.
* Secure+ memo deposit on an observed chain will mint a bank module token 1:1.
* MsgDeposit with secure- will withdraw those tokens back to the layer 1.
* As bank tokens, Secured Assets can be utilised in the App Layer, swapped across the Base Layer to another asset, or redeemed back to L1. The UX feels like depositing into an exchange, "doing things" then withdrawing.

<figure><img src="/files/fhd7xj5sF9u8EZJvuO4O" alt="" width="375"><figcaption></figcaption></figure>

### Mimir control

* If there is a bug in the App Layer, nodes can pause the entire layer, or specific contracts:
  1. HALTWASMGLOBAL - full shutdown of whole App Layer.
  2. HALTWASMCS-{checksum} - halt all contract instances of a specific checksum (i.e. code version).
  3. HALTWASMCONTRACT-{contract last6} - halt an individual contract.
* Considerations: Halting a contract that depends on an oracle price that moves during halt could cause issues. Apps such as these should be designed to protect against sudden price movements in some way.

<br>

<figure><img src="/files/jjRaoNt8gNSpPBusAODX" alt="" width="375"><figcaption></figcaption></figure>

### Verifying code integrity

* Checksum ⇒ deploy\_address must be registered in the THORNode codebase in order to permit code storage. This means that wasm code can be inspected, audited, and a reproducible checksum emitted by any 3rd party that wants to verify the permission.

<figure><img src="/files/kTAbERqClhhupEOGoB5X" alt=""><figcaption></figcaption></figure>


# Understanding Secured Assets

To understand how Rujira is the App Layer built on THORChain, please refer to the [THORChain Docs](https://docs.thorchain.org/frequently-asked-questions/app-layer-bridge-assets), where the assets that tie the base layer (THORChain) together with the app layer (Rujira) are referred to as **Secured Assets.**

Secured Assets enable users to deposit Layer1 (L1) tokens (e.g., Bitcoin, Ethereum) into THORChain, minting corresponding tokens that can be used on **Rujira** and across the THORChain ecosystem. These assets offer fast, efficient trading and transfer options and are designed to integrate seamlessly with CosmWasm smart contracts and connect to other IBC-enabled chains.

## Key Features of Secured Assets

* **Backed by L1 Deposits**: Users deposit L1 tokens like BTC into THORChain's decentralized Asgard Vaults, which mints a corresponding Secured Asset (e.g., `BTC-BTC`). These Secured Asset tokens represent a share of ownership of the underlying L1 assets in the vault. The Asgard Vaults are secured by Threshold Signature Schemes (TSS) with the private keys split among \~100 independent node operators that churn every 3 days.
* **Fungible and Transferable:** Secured Assets are easily transferred between accounts or sent across IBC to other chains, enabling cross-chain trading and interoperability.
* **App Layer Use (Rujira)**: Within Rujira, Secured Assets can be used for trading, swapping, and interacting with decentralized apps (dApps) like limit orders, lending, or liquidity provision.
* **Efficient Arbitrage**: Secured Assets allow traders (especially bots) to perform faster, more capital-efficient arbitrage compared to synthetics, adjusting market prices with less capital.
* **No wrapping or third-party bridges:** Secured Assets remove dependence on third-party bridges (e.g. Axellar, Gravity) and wrapping by centralized intermediaries (e.g. wBTC by BitGo, cbBTC by Coinbase), enabling access to DeFi with native assets from all connected chains.

#### Flow: Using Secured Assets on Rujira

```plaintext
Step 1: Deposit L1 Tokens ➡ Mint Secured Assets ➡ Trade or Swap on Rujira ➡ Withdraw L1 Tokens
```

## How Secured Assets Work on Rujira

1. **Deposit**: Users deposit L1 tokens (e.g., BTC) into THORChain's decentralized Asgard Vaults, creating a corresponding Secured Asset.
2. **Representation**: The Secured Asset represents shares in the pool of deposited L1 tokens.
3. **Trading and Swapping**: On **Rujira**, users can trade or swap Secured Assets (e.g., `BTC-BTC`) quickly and efficiently, without Layer1 fees.
4. **Smart Contracts**: Secured Assets interact with dApps on Rujira via CosmWasm, enabling features like limit orders, lending, or liquidity provisioning.
5. **Withdraw**: When users want to convert back to L1 tokens, they can withdraw their Secured Assets for an equivalent amount of the original token (e.g., Bitcoin).

## Security

Secured Assets are backed by L1 deposits but are separate from THORChain liquidity pools. To maintain security:

* **TVL Check** upon minting ensures that there is sufficient security budget to accommodate more Secured Assets.
* **Incentive Pendulum** can ensure the total value of L1 assets (including Secured Assets) does not exceed the security provided by bonded nodes. This feature is optional and controlled by a Mimir parameter '*PendulumUseVaultAssets'.* By default, Secured Assets are "optimistically secured" by THORChain validators (they are not inside the Incentive Pendulum). Secured Assets make THORChain nodes money from App Layer fees, that is how they pay for their security.

## Using Secured Assets in Rujira

#### Minting Secured Assets

To mint Secured Assets, users send L1 tokens with a specific memo to THORChain’s vault. The asset is then converted into a Secured Asset.

**Example**:

<pre><code><strong>S+:thor1... (BTC-BTC added)
</strong></code></pre>

#### Swapping and Trading

On **Rujira**, Secured Assets can be swapped or traded like any other token, enabling quick and low-fee transactions.

**Example**:

```
=:BTC-BTC:thor1... (Swap BTC-BTC to another asset)
```

#### Withdrawing Secured Assets

Users can convert their Secured Assets back into L1 tokens by sending a withdrawal memo, receiving the equivalent L1 token (e.g., Bitcoin) based on their Secured Asset balance.

**Example**:

```
S-:bc1... (Withdraw BTC)
```

## Transaction Flow

To understand the interactions between smart contracts on Rujira and the base layer L1 pools on THORChain, there are essentially two ways to call a contract:

* Path 1: Layer 1 Transaction + Memo
* Path 2: THORChain Transaction Direct Execution

#### Path 1: Layer 1 Transaction + Memo

A user initiates a transaction using a Layer 1 deposit along with a memo structured as `x:{contract}:{payload}`. This triggers the smart contract on Rujira, executing the specified function using the funds sent in the Layer 1 transaction. The smart contract can then emit sub-messages to perform additional actions such as:

* Swapping BTC to RUNE and bonding the RUNE with a Node Operator.
* Depositing BTC into a lending protocol, borrowing secured USDC, and withdrawing secured USDC to say Ethereum or any other network supporting USDC.

The execution follows the sequence dictated by the contract logic, with each step being carried out in order. Once all actions are completed, the contract returns a response to the user.

**Transaction flow using `x:` Memo in Layer 1 Transactions**

* User: A `MsgDeposit` is initiated by the user with a memo formatted as `x:{contract}:{payload}`.
* L1: The L1 performs a couple of actions when a user makes a deposit:
  * TxIn: The deposit is processed async without validation by the smart contract at this stage.
  * Mint Secured Asset: Mint x/bank token based on the user deposit
* The contract is called when required, executing the necessary actions once prior steps are complete.

<img src="/files/FvLNvARUv2pZwFSse8YT" alt="" class="gitbook-drawing">

#### Path 2: THORChain Transaction Direct Execution

A user interacts with the contract directly via a THORChain transaction using `MsgExecuteContract { contract, msg, funds }`. This method is functionally similar to the `x:` memo approach but offers additional capabilities:

* The `funds` field allows sending THORChain-native tokens such as `x/ruji`, which do not have a representation in `MsgDeposit` notation.
* The ability to send multiple tokens simultaneously, enabling operations like depositing `x/ruji` and `ETH-USDC` into a dual liquidity pool in a single transaction.

**Transaction flow using direct `MsgExecuteContract` Call**

* A user directly calls `MsgExecuteContract` on THORChain with `{ contract, msg, funds }`.
* The contract processes the message and executes multiple actions such as asset swaps, adding liquidity, etc.
* The L1 Pools handle swap and liquidity actions.
* `TxOut` generates output upon LP token minting.
* The smart contract handles final steps such as staking LP tokens.
* The contract then returns a response to the user.

<img src="/files/jyy50BgkfUf0rWZVnMMC" alt="" class="gitbook-drawing">


# Understanding App Layer Security

The App Layer is designed with strict boundaries to ensure it does not introduce new risks to the Base Layer. Smart contracts on the App Layer are essentially “accounts with code” that are only permitted to perform MsgSend and MsgDeposit operations. They are sandboxed within a walled garden, with no special privileges that could compromise the Base Layer.

This setup ensures that the App Layer introduces no greater risk than a centralized entity holding a large amount of RUNE today. To further minimize risk, applications that might lead to significant RUNE accumulation will be avoided. Instead, the focus is on building apps centered around Secured Assets.

Additionally, THORChain’s governance mechanism (Mimirs) allows for fine-grained control: they can pause specific apps, all apps, or the minting/burning of Secured Assets if needed. Developers must go through a due diligence process to have their deployer address and smart contract bytecode whitelisted before deploying on Mainnet, adding another layer of security.

<figure><img src="/files/jjRaoNt8gNSpPBusAODX" alt="" width="375"><figcaption></figcaption></figure>

**What if there is an exploit and** [**secured assets**](/how-it-works/understanding-secured-assets) **are all wiped? Any impact for the Base Layer?**\
If an app is exploited, the attacker may be able to misappropriate secured assets held or controlled by that app. This can affect users of the app, but it does not create a direct liability for the Base Layer. It would take a Base Layer vulnerability to "mess with secured assets".

If there is a smart contract exploit on the App Layer leading to the misappropriation of secured assets, the loss is for each individual user that interacted with the malicious smart contract. This would obviously be a bad outcome, but it has no impact for the Base Layer, it’s just a change of ownership. The Base Layer would continue to neutrally process minting and redemptions of secured assets, as it is supposed to do, and would not assume any loss.

Note that Node Operators have the ability to pause smart contracts as shown above if such an issue was to happen and they wish to mitigate it.

A key concept around security is the separation of concerns between the Base Layer and App Layer. Smart contracts on the App Layer interact with the Base Layer the same way as any EOA, they can only do things that regular users can do.

**What is the Mimir to stop minting/redeeming secured assets?**\
HaltSecuredDeposit-{CHAIN}\
HaltSecuredWithdraw-{CHAIN}

**What is the flow of redeeming secured assets and sending out the L1 outbound?**\
Swap to an L1 address with the redemption memo.

**How does secured asset accounting work? Is it held at App Layer or Base Layer?**\
The accounting is held on the Base Layer. The App Layer gets to use secured assets, but it does not control the Base Layer accounting.

**Can smart contracts mint secured assets?**\
No. They can only use secured assets across the different contracts, but not mint (or burn) secured assets.

**Are there TVL limits on the App Layer? Can secured asset balances grow larger than pools?**\
This depends on the TVL Cap, which is an ongoing discussion in the THORChain community.

**What happens if a protocol on the App Layer accrues bad debt?**\
Bad debt would be assumed by the lenders in the Lending vaults. As long as the bad debt IOU is not in RUNE, then it has no impact for the Base Layer - we don't entertain releasing apps that will take excessive RUNE collateral.

**Why can** [**RUJI Trade**](/core-products/ruji-trade) **swap against base-layer at 5-10bps rather than the mimir settings which results in 8bps at best and 31.9 bps at worst?**\
The minimum swap rate for Secured Assets is defined by the mimir *SecuredAssetSlipMinBps* currently set at 5bps, same as Trade Assets (*TradeAccountsSlipMinBps* = 5bps).\
In practice, no user will be able to swap at those rates. To understand that, you need to understand how the App Layer is able to atomically tap into the Base Layer liquidity with its [AMM Arbitrage strategy](/core-products/ruji-amm/base-layer-virtualization-strategy).\
The way this strategy works is that, for a given quantity of input token to swap, the AMM can estimate how many output token it would get if it was to execute a Base Layer swap, and then provide a quote for that quantity at Base Layer price + 2x SecuredAssetSlipMinBps + 15bps Taker Fee + 30bps Arbitrage Fee.\
You can think of the duo Arbitrage Fee + Taker Fee as an Affiliate Fee charged by traditional frontends, it’s economically the exact same thing for the end user, it’s just the mechanic for collecting those fees that is different.

**What audits have been made on the integration of the App Layer?**\
All apps deployed on Rujira have gone through rigorous internal testing and an external audit before release. You can find a collected overview of both contracts and audits in [RELEASES.md](https://gitlab.com/thorchain/rujira/-/blob/main/RELEASES.md?ref_type=heads)&#x20;

**What security measures are in place to prevent illicit actions in the mempool by MsgExecuteContract message?**\
Messages are de-prioritised against all Base Layer messages so can't DoS MsgExecuteContract wraps MsgSend or MsgDeposit actions.

**Will the Base Layer now need to consider each App Layer contract in its overall security posture?**\
No - the Base Layer doesn't know that the App Layer exists, because apps can only do what EoAs can already do, and nothing extra.

**Are there any risks App Layer products affecting Base Layer swap execution?**\
No. All msgs are de-prioritised against Base Layer. Apps use the Base Layer to settle swaps.


# Understanding Enshrined Oracles

The Enshrined Oracles are THORChain in-house solution allowing Node Operators to provide robust price feeds for established crypto assets that can be consumed by applications on the App Layer.

The Enshrined Oracles are used as the source of true by several Rujira core products:

* **RUJI Trade:** The enshrined oracles are used to price [Tracking Orders](/core-products/ruji-trade#key-features).
* **RUJI Money Market:** The enshrined oracles are used by [Credit Accounts](https://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-ghost-credit/README.md) to price the collateral for all debt products.
* **RUJI Perps:** The enshrined oracles are used by [Ghost Mint](https://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-ghost-mint/README.md) (the primitive that power the upcoming Perps v2) to price the collateral for Perps trading.

### How it works

Each node runs an instance of the oracle and reports observed prices independently. Prices are sourced from multiple whitelisted price providers for different centralized exchanges. Each node query prices from a different subset of providers.

Every second, the oracle collects all rates of all configured trading pairs from all enabled providers. It then calculates the USD value of each base asset and filters them for outliers.

All remaining USD rates for every asset are averaged into a single value weighted by the 24h trading volume, reported by the provider.

Prices are valid only for a single block to enhance accuracy and reduce manipulation risks.

For more info, check THORChain docs: <https://dev.thorchain.org/bifrost/oracle.html>

### Key Benefits

* **Decentralized by design:** Every node runs its own oracle and reports prices independently, reducing reliance on any single operator or source.
* **More robust pricing:** Prices are sourced from multiple exchange providers, then filtered for outliers before aggregation, which helps remove bad or anomalous data. Remaining prices are combined using volume weighting to give deeper, more liquid markets a greater influence on the result.
* **Manipulation resistance:** Feeds are signed, timestamped, stale messages are discarded, and Thornode takes the median across node submissions, making the final on-chain price harder to forge or skew.
* **Reduced third-party dependencies and risks:** By embedding oracles into the core protocol, THORChain eliminates reliance on external providers, minimizing points of failure such as network outages, data delays, or compromises in third-party systems. Enshrined designs ensure data is always accessible as part of the chain's operations.
* **Better protection against front-running**: Price feeds are handled in a single batch transaction, all oracle prices are cleared at every `BeginBlock`, and any transaction that tries to execute before fresh oracle pricing is available fails. This ensure applications always get access to fresh pricing and cannot be front-run by node oeprators. In contrast, external oracles often rely on predictable or observable data updates that can be exploited by bots monitoring mempools or oracle reports to front-run users.


# Understanding Revenue Flow

The diagram below summarizes where revenue is collected and how it is distributed between RUJI stakers, Rujira-owned protocol liquidity, THORChain-owned protocol liquidity, and the THORChain Reserve.

For revenue shared equally between Rujira and THORChain, each side redirects one-third of its share toward protocol-owned liquidity. This results in an effective distribution of 33.33% to RUJI stakers, 16.67% to the Rujira Ecosystem Fund, 16.67% to the THORChain POL Fund, and 33.33% to the THORChain Reserve.

Revenue attributable entirely to Rujira is distributed 66.67% to RUJI stakers and 33.33% to the Rujira Ecosystem Fund.

<figure><img src="/files/xyBrqZgx0s3A8RN4eRo6" alt=""><figcaption></figcaption></figure>

Rujira currently uses 5 revenue collector and converter contracts:

* **Revenue Collector 1 (RUJI Swap & bRUNE):** Used to collect RUJI Swap affiliate fees and bRUNE fee on bonding rewards, which are sent 100% to RUJI stakers since Rujira pays the Base Layer liquidity fee on the swaps and the Node Operators collect their own bonding fee from bRUNE. The contract is also used to aggregate Rujira's share of revenue from other products. Revenue is converted to USDC and distributed 66.67% to RUJI stakers and 33.33% to the Rujira Ecosystem Fund, where it is used to build Rujira-owned protocol liquidity.
  * Contract address: [thor1mcy9jtp4kzl8q2lvdgfgsl8jvqrf504uphkf0pz2p9wud8tsntesjvccew](https://thorchain.net/address/thor1mcy9jtp4kzl8q2lvdgfgsl8jvqrf504uphkf0pz2p9wud8tsntesjvccew)
* **Revenue Collector 2 (RUJI Trade):** Used to collect revenue from RUJI Trade. The revenue split between RUJI stakers and THORChain Base Layer is initially set at 50/50. However, part of this revenue is generated by the [virtualization strategy](/core-products/ruji-amm/base-layer-virtualization-strategy) which executes swaps on the Base Layer and pays THORChain liquidity fees. The fee pays by Rujira to THORChain should be deducted from the 50% share of revenue going to THORChain. Given it's technically not possible to differentiate the source of liquidity for a trade at the time an order is filled, we use historical data to periodically adjust the distribution weights to compensate for excess revenue sent to the Base Layer by RUJI Trade. Revenue from RUJI Trade is collected in various tokens that are split between Revenue Collector 1 and Revenue Collector 4 using the appropriate weights.
  * Contract address: [thor1gm8q2gr25nzzsxzdp2mpja4hyvyhjlr4s6krcsgv2y953uu0js3qhwpus7](https://thorchain.net/address/thor1gm8q2gr25nzzsxzdp2mpja4hyvyhjlr4s6krcsgv2y953uu0js3qhwpus7)
* **Revenue Collector 3 (Other Core Apps):** Used to collect revenue from all the other core apps, which is collected in various tokens and split between Revenue Collector 1 (50%) and Revenue Collector 4 (50%).
  * Contract address: [thor1jduxxzpyyvrgzx7zcnl7e5cdj34tnq5jxy00a4wp86szye25dndq575c0y](https://thorchain.net/address/thor1jduxxzpyyvrgzx7zcnl7e5cdj34tnq5jxy00a4wp86szye25dndq575c0y)
* **Revenue Collector 4 (Base Layer):** Used to collect the share of core apps revenue going to THORChain Base Layer. Revenue is received from Revenue Collectors 2 and 3 and converted to RUNE. It is then distributed 66.67% to the [THORChain Reserve](https://thorchain.net/address/thor1dheycdevq39qlkxs2a6wuuzyn4aqxhve4qxtxt), where it is included in THORChain’s Gross System Income, and 33.33% to the THORChain POL Fund, where it is used to build THORChain-owned protocol liquidity on Rujira.
  * Contract address: [thor1txum04wp8ykqudphxy9prtwsd9jpcm2kwdaxctxeeyr6g0r0we9qpfdktr](https://thorchain.net/address/thor1txum04wp8ykqudphxy9prtwsd9jpcm2kwdaxctxeeyr6g0r0we9qpfdktr)
* **Revenue Collector 5 (RUJI Index):** Following the merger with Nami, this contract collects all revenue generated by the RUJI Index & Earn vertical. 100% of these proceeds are sent to Revenue Collector 1 to be distributed to RUJI stakers, since the indexes and earn prodcuts are built exclusively on core applications that already contribute their security budget to the base layer.
  * **Contract address:** [thor132u9qpm9gfdqtgwxwl8ty409s6zmewfrum2k6wvtvtyphdn5urzsej764l](https://thorchain.net/address/thor132u9qpm9gfdqtgwxwl8ty409s6zmewfrum2k6wvtvtyphdn5urzsej764l)


# Frequently Asked Questions

In this section, you will find many Frequently Asked Questions grouped by category:

* [Understanding Rujira](/how-it-works/frequently-asked-questions/understanding-rujira)
* [RUJI Token](/how-it-works/frequently-asked-questions/ruji-token)
* [Secured Assets](/how-it-works/frequently-asked-questions/secured-assets)
* [Get started](/how-it-works/frequently-asked-questions/get-started)
* [RUJI Swap - Cross-chain swaps](/how-it-works/frequently-asked-questions/ruji-swap-cross-chain-swaps)
* [RUJI Trade - Orderbook DEX](/how-it-works/frequently-asked-questions/ruji-trade-orderbook-dex)
* [RUJI Perps - Perps DEX](/how-it-works/frequently-asked-questions/ruji-perps-perps-dex) (depreciated, new version coming)
* [RUJI ](/how-it-works/frequently-asked-questions/ruji-money-market-lending-and-borrowing)[Money Market](/how-it-works/frequently-asked-questions/ruji-money-market-lending-and-borrowing)[ - Lending & Borrowing](/how-it-works/frequently-asked-questions/ruji-money-market-lending-and-borrowing)
* [RUJI Liquidations - Bid on Liquidated Collateral](/how-it-works/frequently-asked-questions/ruji-liquidations-bid-on-liquidated-collateral)
* [RUJI Launchpad - Token Launchpad](/how-it-works/frequently-asked-questions/ruji-launchpad-token-launchpad)
* [RUJI Index - Crypto Indices](/how-it-works/frequently-asked-questions/ruji-index-crypto-indices)
* [Strategies - Put your assets to work](/how-it-works/frequently-asked-questions/strategies-put-your-assets-to-work)
* [RUJI Leagues - Points competition](/how-it-works/frequently-asked-questions/ruji-leagues-points-competition)
* [Contact](/how-it-works/frequently-asked-questions/contact)


# Understanding Rujira

**Q: What is Rujira?**\
Rujira is the App Layer on THORChain, designed to build a fair and open financial system for everyone. It brings together a full suite of decentralized products that let you trade, lend, borrow and earn using native assets from any connected blockchain, all from your own wallet, in one smooth interface. Rujira is open-source, permissionless and non-custodial.

**Q: What does Rujira stand for?**\
We stand for fairness, transparency, and true decentralization, the core principles that first defined Bitcoin.\
We believe in building an open and sustainable financial system where everyone has equal opportunity and full control of their assets. No intermediaries, no hidden rules, no gatekeepers, only a transparent and community-owned network that brings freedom and trust back to finance.

**Q: What makes Rujira different from other DeFi platforms?**\
Most DeFi platforms are limited to a single chain and rely on third-party bridges and wrapped assets to reach others. Rujira removes that risk and complexity by building on THORChain, giving you direct access to native assets from multiple blockchains in one unified ecosystem.

Unlike most of crypto, where each project focuses on a single product, Rujira brings every DeFi tool together under one roof. You can trade, earn, borrow and invest without switching between platforms and wallets or learning new interfaces, creating a smooth and consistent experience across the entire ecosystem.

**Q: What is Rujira built on?**\
Rujira is built on THORChain and the Cosmos SDK, bringing together the best of both worlds, cross-chain liquidity and powerful and secure scalability. This setup lets you swap and use native assets like BTC, ETH, and XRP without third-party bridges or wrapped tokens. Everything you need is built right into one connected ecosystem, so you can trade, earn, borrow, and invest across chains with ease.

**Q: What does Omnichain mean?**\
Omnichain is the next phase of interoperability, and goes beyond cross-chain. It means Rujira connects many different blockchains and many different wallets all at once, letting you use native assets across them through one unified platform, with your favorite wallet.

**Q: What products does Rujira have?**\
The products that are currently live on Rujira are:

* RUJI Trade (orderbook DEX)
* RUJI AMM (multi-strategy automated market maker for the DEX)
* RUJI Perps (perpetual futures - v1 built by Levana, an improved v2 fully integrated with the rest of the ecosystem will be launched later)
* RUJI Lending (money market)
* RUJI Index (crypto indices)
* RUJI Launchpad (fundraising platform - pending internal review & audit)
* RUJI Swap (cross-chain swaps)
* RUJI Liquidations (auctions on liquidated collateral - via tracking orders for now, advanced bidding interface coming later)

Many more products are on the roadmap, which can be found here (rujira.network/roadmap).

**Q: Is Rujira connected to other Cosmos chains through IBC?**\
No. Rujira does not use the IBC protocol. Among Cosmos chains, it is currently only connected directly to the Cosmos Hub, through a custom chain integration via THORChain.&#x20;

**Q: How does Rujira connect to non-Cosmos chains like Bitcoin or Ethereum?**\
Rujira connects to external chains through THORChain, which secures native assets like BTC and ETH in decentralized vaults and allows swaps between them without third-party bridges or wrapped tokens.

Thanks to a THORChain primitive called Secured Assets, we can offer you these native assets from different chains across our entire product suite.

**Q: Is Rujira open-source and audited?**\
Yes. Rujira is fully open-source and audited. You can view our code at[ gitlab.com/thorchain/rujira](https://gitlab.com/thorchain/rujira) and audits at[ docs.rujira.network/resources/releases-and-contracts](https://docs.rujira.network/resources/releases-and-contracts).

**Q: Who is building Rujira?**\
Rujira is built by an alliance of teams: Kujira, Fuzion, Nami, and Levana.\
The old Kujira team leads development and manages most core products and operations.\
Besides that, there are multiple external teams contributing to build a coherent ecosystem on top of Rujira core primitives, including AutoRujira, Liquidy, CALC, Redacted and some more.

**Q: How is Rujira secured?**\
Rujira is secured through THORChain, which runs on a network of over 100 decentralized nodes that continuously rotate the decentralized vaults where assets are kept, to maintain network security.

**Q: Where can I follow Rujira updates and announcements?**\
You can stay updated about our development via one of our social channels:

* Telegram: [t.me/Rujira\_Community](https://t.me/Rujira_Community)
* Dev Discord: [discord.gg/uRzqQmU9EE](https://discord.gg/uRzqQmU9EE)
* X (Twitter): [x.com/RujiraNetwork](https://x.com/RujiraNetwork)
* Medium: [medium.com/rujiranetwork](https://medium.com/rujiranetwork)


# RUJI Token

**Q: What is the RUJI token?**\
The RUJI token is the revenue-sharing token of the Rujira ecosystem. When you hold RUJI and stake it, you get a share of the income generated across all Rujira products.

**Q: Why does RUJI have value?**\
Holding RUJI means earning a share of all revenue Rujira generates. It represents a long-term bet on the success and growth of the ecosystem.

**Q: How does RUJI capture value?**\
Using Rujira’s products comes with a small fee, which differs per product. These fees are collected, converted to USDC and shared with everyone who stakes RUJI.

**Q: Where does the staking yield come from?**\
Rujira apps generate real revenue from user activity. After covering THORChain’s share (typically 50%, but can be less in some cases), the remaining fees are converted to USDC and distributed to RUJI stakers.

**Q: Is the RUJI token inflationary or deflationary?**\
RUJI has a fixed supply of 100 million tokens. There are no mechanisms that increase or decrease this number over time.

**Q: How are fees split between Rujira and THORChain’s Base Layer?**\
Normally, revenue is split 50/50 between core Rujira applications and THORChain’s base layer. However, apps that already support the base layer (for example, RUJI Swap, as it is already utilizing THORChain liquidity) keep 100% of their revenue, since they already pay the base layer fee and contribute to THORChain’s security budget this way.

**Q: What staking options are available for RUJI?**\
You can choose between two ways to stake:

1. Standard RUJI staking: You earn rewards in USDC to be claimed manually.
2. Auto-compounding staking: Your USDC rewards are used to automatically buy more RUJI and add it to your position.

**Q: What is the staking APR/APY?**\
The APR\* (if using standard staking) or APY\* (if using auto-compounding staking) will change based on several factors:

* The total revenue generated across all Rujira products;
* The revenue split between single-sided and LP staking (initially 50/50);
* How much RUJI is staked and how it is divided between both pools.

*\*APR (Annual Percentage Rate): your yearly non-compounded return rate.*\
*\*APY (Annual Percentage Yield): your yearly return rate including compounding.*

**Q: Can I stake RUJI directly from my wallet?**\
No. You can currently only stake RUJI through [rujira.network/strategies/staking/RUJI](https://rujira.network/strategies/staking/RUJI).

**Q: What are the benefits of staking RUJI?**\
Staking lets you earn a share of the fees generated by all Rujira products. It’s a simple way to benefit from the ecosystem’s growth.

**Q: How long does it take to unstake RUJI?**\
You can unstake instantly at any time. There is no lock-up period.

**Q: Does RUJI give governance rights?**\
No. RUJI is focused on revenue sharing and staking rewards. Governance is handled by the product teams in close collaboration with the community through X Spaces, dedicated feedback groups, polls, and more.

**Q: Is RUJI listed on centralized exchanges?**\
Yes. RUJI is currently listed on Kraken, MEXC, and Bitrue. More listings will be added over time to increase accessibility of the token.


# Secured Assets

**Q: What are Secured Assets?**\
Secured Assets are a novel answer to the problems of cross-chain interoperability, providing an open source, decentralized, and secure cross-chain asset model powered by THORChain. Secured Assets are backed 1:1 by native assets secured in THORChain’s decentralized vaults, which are secured by Threshold Signature Schemes (TSS) with the private keys split among 100+ decentralized node operators that churn every 3 days. Secured Assets remove all dependence on third-party bridges (e.g. Axelar, Gravity) and wrapping by centralized intermediaries (e.g. wBTC by BitGo, cbBTC by Coinbase), enabling access to DeFi with native assets from all connected chains.

**Q: How Secured Assets differ from traditional bridged assets?**\
**Answer:** Bridged assets are IOUs issued by a third-party protocol on the destination chain, and represent a claim on the underlying asset on its native chain. In the best case, the assets on the native chains are secured by an external validator set (e.g. Axelar, Gravity), and in many cases by low-security multisigs that have resulted in billions of dollars lost in hacks (Ronin Bridge $625m hack, Wormhole Bridge $326m hack, Nomad Bridge $190m hack, and the list goes on). In any case, they introduce an extra layer of exogenous risk between the native chain and the end user. Secured Assets, on the other hand, eliminate this additional layer of risk. While they do indeed mint new assets on THORChain, THORChain’s TSS eliminates the external risks associated with third-party bridges and their security designs. This provides a far more robust architecture for Secured Assets than traditional bridges.

**Q: How Secured Assets differ from wrapped assets?**\
**Answer:** Wrapped assets are also IOUs, but, unlike bridged assets, these are issued by a centralized intermediary, one that holds the underlying asset in custody (e.g., wBTC issued by BitGo or cbBTC issued by Coinbase). This allows assets like BTC to be used in DeFi on e.g. Ethereum, but it forces users to trust the centralized issuer to secure the underlying assets appropriately, not to misuse the reserves, and to not give in to censorship (e.g. freezing assets under the pressure of arbitrary governments). In using wrapped assets, a centralized intermediary has now become one’s unintended financial partners, negating the very ethos of decentralization. In contrast, Secured Assets require no error-prone and corruptible centralized custodian, and are never subject to permission or KYC requirements.

**Q: How are Secured Assets minted and redeemed?**\
They are minted when native assets are deposited into THORChain’s vaults and can be redeemed 1:1 for those same assets at any time.

**Q: Are Secured Assets backed 1:1 by native tokens?**\
Yes, every Secured Asset is fully backed and redeemable for its native token.

**Q: Can I transfer Secured Assets between chains?**\
Secured Assets are currently only tradeable on THORChain via Rujira.


# Get started

**Q: What products are available on Rujira?**\
Rujira brings multiple DeFi products together under one platform. The current products include:

1. RUJI Trade – Orderbook DEX
2. RUJI AMM – Automated Market Making strategies
3. RUJI Perps v1 – Peer-to-pool perpetuals (built by Levana)
4. RUJI Index – Crypto index products
5. RUJI Swap – Cross-chain swaps
6. RUJI Money Market – Lend and borrow with your assets
7. RUJI Launchpad – Token launch platform (pending audit)
8. RUJI Liquidations – Auction platform to bid on liquidated collateral

Many more products are on the roadmap, which can be found here (rujira.network/roadmap).

**Q: Do I need RUJI to use Rujira or pay gas fees?**\
No. You do not need RUJI to be able to use any of the apps. Gas fees on Rujira are normally paid in RUNE, but gas fees to interact with smart contracts (`MsgExecuteContract`) are currently set to zero as an experiment. If deemed necessary to prevent spam attacks, RUNE gas fees may be re-enabled at a later point.\
There is a fixed 0.02 RUNE fee enforced by THORChain for simple fund transfer transactions (`MsgSend`).

**Q: Which wallets can I use with Rujira?**\
Most popular wallets that support THORChain-connected chains work with Rujira. We will continue to add new wallets overtime:

**THORChain-Enabled wallets - You need to connect at least one to use Rujira:**

* **Recommended - Keplr (Desktop and Mobile):**\
  THORChain, Bitcoin, Ethereum, BNB, Base, Avalanche, Cosmos Hub.
* **Station (Coming soon):**\
  THORChain, Bitcoin, Ethereum, BNB, Base, Avalanche, Cosmos Hub, Litecoin, Bitcoin Cash, Dogecoin, XRP Ledger, TRON.
* **Vultisig:**\
  THORChain, Bitcoin, Ethereum, BNB, Base, Avalanche, Cosmos Hub, Litecoin, Bitcoin Cash, Dogecoin, XRP Ledger, TRON.
* **CTRL Wallet:**\
  THORChain, Bitcoin, Ethereum, BNB, Base, Avalanche, Cosmos Hub, Litecoin, Bitcoin Cash, Dogecoin, TRON.

**Other supported wallets - Connect to deposit and withdraw from any supported chains:**

* **Leap (Desktop and Mobile):**\
  THORChain (with limited capacity at the moment), Ethereum, BNB, Base, Avalanche, Cosmos Hub
* **OKX Wallet:**\
  Bitcoin, Ethereum, BNB, Base, Avalanche, Cosmos Hub
* **Brave Wallet:**\
  Ethereum, BNB, Avalanche, Base
* **Coinbase Wallet:**\
  Ethereum, BNB, Base, Avalanche
* **MetaMask:**\
  THORChain (with limited capacity at the moment), Ethereum, BNB, Base, Avalanche
* **Rabby Wallet:**\
  THORChain (with limited capacity at the moment), Ethereum, BNB, Base, Avalanche
* **Trust Wallet:**\
  THORChain (with limited capacity at the moment), Ethereum, BNB, Base, Avalanche
* **Xaman (Desktop and Mobile):**\
  XRP Ledger
* **TonKeep:**\
  TON

*Please be aware that some wallet extensions can interfere with each other when enabled simultaneously. So, we recommend disabling wallets if you experience connectivity issues.*

**Q: Which chains are supported?**\
Rujira supports native assets from: Bitcoin, Ethereum, XRP, BNB, TRON, Base, Avalanche, Cosmos Hub, TON, Bitcoin Cash, Litecoin, and Dogecoin.\
\
New chains are added regularly by THORChain. We are also working with the Maya Protocol team for an integration, which will allow us to connect to Cardano, Dash, Zcash and more.&#x20;

**Q: Which tokens are supported on Rujira?**\
Currently, only tokens paired with RUNE on THORChain’s base layer pools are supported.\
In the future, we plan to support any token from connected chains using a whitelist system.

A full overview can be found here: <https://medium.com/rujiranetwork/all?topic=tutorial>

**Q: How do I move my assets from a CEX to Rujira?**

1. On your CEX, choose Withdraw Crypto.
2. Enter your wallet address (e.g. BTC address for Bitcoin).
3. Confirm and wait for the withdrawal.
4. Visit[ rujira.network/portfolio](https://rujira.network/portfolio) and follow the deposit steps.

For the most popular CEXs, there is a step by step tutorial available on Medium in our Tutorial section.\
<https://medium.com/rujiranetwork/all?topic=tutorial>

**Q: How do I deposit assets on Rujira?**\
You can deposit by:

* Clicking Deposit in the top right corner,
* Starting a new DeFi position with assets on another chain, or
* Going to your Portfolio and selecting “Deposit” via the three-dots next to your asset.

**Q: How do I withdraw my assets from Rujira?**\
You can withdraw by:

* Clicking Withdraw in your wallet overview, or
* Going to your Portfolio, selecting the asset, and pressing Withdraw.

**Q: Are there any deposit or withdrawal fees?**

* Deposits: You only pay the network fee from the chain you are sending from. However, if you are depositing e.g. USDC from Base, you will have to swap it for the USDC version native to Ethereum to maximize utility on Rujira. The swap is automatic by default as part of the deposit and incur a swap fee that depends on the size of your deposit relative to the liquidity available.
* Withdrawals: You pay a small 0.02 RUNE fee plus the network fee for the destination chain. Similarly to deposits, you might also have to pay a swap fee if you try to withdraw e.g. native BTC on Rujira as wBTC on Ethereum.

**Q: Can I deposit EUR or USD directly?**\
Yes (soon). You can use our built-in on-ramp and off-ramp services (currently through BANXA) to deposit or withdraw fiat currencies like EUR or USD directly on Rujira.

**Q: Can I use Rujira on mobile?**\
Yes. You can access Rujira through mobile wallets such as Keplr Mobile using its in-app browser. Our own mobile wallet, Station, will be released at a later point.

**Q: Do I need to complete KYC to use Rujira?**\
No. Rujira is fully decentralized and non-custodial, and you can use all products without KYC (identity verification).


# RUJI Swap - Cross-chain swaps

**Q: What is RUJI Swap?**\
RUJI Swap is our cross-chain swap product. It gives you a simple way to swap any supported native asset into any other native asset.&#x20;

RUJI Swap connects directly to THORChain, which is the only fully decentralized network that can swap native assets like BTC, ETH, XRP, DOGE, ATOM, or BNB without wrapping or using third-party bridges.\
\
You can access it here: [rujira.network/swap](https://rujira.network/swap)

Note that you need to have a THORChain-enabled wallet connected to use RUJI Swap, even if you swap from two external chains. This was a compromise we had to make to be able to offer the omnichain experience across the rest of the Rujira apps.

**Q: How do cross-chain swaps work and how are they routed?**\
THORChain uses liquidity pools to move assets between blockchains. Each pool connects a native asset to RUNE. Your source asset is deposited into its pool, for example BTC into the BTC/RUNE pool. Inside the pool it is swapped to RUNE. Then RUNE is swapped into your target asset inside its pool, for example RUNE to ETH. The target asset is then sent to your destination address on its native chain.\
\
The swap happens in one continuous flow and does not use wrapped tokens or bridges.

**Q: What is a Source and Destination wallet?**\
The source wallet is where the asset you want to swap is currently stored. The destination wallet is the address where you want to receive the new asset.\
\
Both wallets can be your Rujira address or an address on an external chain such as Bitcoin or Ethereum.

**Q: What fees do I pay when swapping?**\
A cross-chain swap can include three types of fees:

* **Inbound fee:** the network gas fee to send your source asset into its pool on the native chain.
* **Swap fee:** a protocol fee inside the liquidity pool that depends on the size of your swap relative to the pool depth.
* **Outbound fee:** the network gas fee to send your destination asset out on its native chain.

Example for BTC to ETH:\
You pay the Bitcoin network fee as the inbound fee, a swap fee paid in RUNE, and the Ethereum network fee as the outbound fee. You only need to have BTC in your Bitcoin wallet to execute the transaction, the RUNE and ETH needed for the swap and outbound fees will be deducted from the output of your swap.\
\
RUJI Swap shows the expected fees before you confirm.

**Q: How long do swaps take?**\
Most swaps finish within 5 to 20 minutes. Timing depends on the block speed of the chains involved, overall swap activity and the size of your swap. If your swap is large, THORChain may split it into a streaming swap over multiple blocks. This protects you from suffering large price impact and can take up to 30 minutes or slightly longer.

**Q: I swapped a few minutes ago but my funds have not arrived. What should I do?**\
Cross-chain swaps rely on multiple chains so timing can vary. Waiting a little longer usually helps.\
\
If you want to check the status, you can go to [thorchain.net](https://thorchain.net) and paste your transaction hash to see each step of the process. If anything looks unclear you can reach out to the Rujira community for assistance.


# RUJI Trade - Orderbook DEX

**Q: What is RUJI Trade?**\
RUJI Trade is our fully on-chain orderbook DEX and the core of the Rujira ecosystem.\
It lets you trade pairs on the spot market and gives you full control over your trades with market orders, limit orders, tracking orders, and more.

You can access it here:[ rujira.network/trade](https://rujira.network/trade)

For more details, visit the RUJI Trade [docs](/core-products/ruji-trade).

**Q: What is an orderbook?**\
An orderbook is a list of buy and sell orders for a trading pair. It matches buyers and sellers' intents based on their desired prices and quantities.

**Q: What is a market order?**\
A market order lets you buy or sell instantly at the best available price in the market by consuming the liquidity in the orderbook.

**Q: What is a limit order?**\
A limit order lets you set your own price to buy or sell. Your order only executes when the market reaches that price.

**Q: What is a recurring order?**\
[Recurring orders](/ecosystem-products/recurring-orders) (also known as DCA - Dollar Cost Averaging), built by the CALC team, let you schedule trades over time using native assets. You can use them to gradually buy, sell, or take profits on your own schedule and with custom parameters such as price floor or ceiling to trigger orders, all fully on-chain.

**Q: What is a tracking order?**\
A tracking order lets you buy or sell at a fixed discount or premium to an asset’s oracle price\*. It allows for more advanced trading and market-making strategies.

For example, you can use a tracking order at a slight premium to market price to execute a large buy order with minimal price impact.

*\*Oracle price: the current market price of an asset provided by a trusted data source.*

**Q: What is a grid bot?**\
A grid bot automatically places buy and sell orders at preset price levels, creating a “grid” that lets you profit from market volatility by buying low and selling high within a chosen price range.

**Q: How do I claim my order?**\
You can claim your filled order by clicking the purple arrow at the bottom of the page.

You can also enable the AutoClaimer by the AutoRujira team, which automatically claims filled orders for selected markets. You can find this feature in the order panel.

Note that market orders are executed instantly and do not need to be claimed, but limit and tracking orders do.

**Q: What are the trading fees?**

The fees for RUJI Trade are:

* Maker orders (adding liquidity to the orderbook): 0.075% fee
* Taker orders (removing liquidity from the orderbook): 0.15% fee


# RUJI Perps - Perps DEX

**Q: What is RUJI Perps?**\
RUJI Perps (v1) is our perpetual trading product, built on a peer-to-pool model, where you can trade with up to 50x leverage. A more detailed description is available [here](/core-products/ruji-perps).

**Note:** The current version was built by the Levana team as an intermediate step and is not fully integrated with the rest of the applications. We will release a brand-new version of the protocol with a peer-to-peer orderbook model and improved UX as part of our 2026 roadmap.

**Q: How do perpetuals differ from spot trading?**\
Perpetuals let you use leverage, which means you can take a larger position than your actual capital. They are better suited to short-term trading, include different costs, and come with higher risk and higher potential reward compared to spot trading.

**Q: How do perpetuals differ from spot margin trading?**\
Spot margin trading also lets you use leverage in the spot market. The key difference is that you borrow funds to increase your position size in actual crypto assets using your existing balance as collateral, whereas with perps trading you are trading derivatives and settle trades in the same asset as your collateral (you only get exposure to the price fluctuations of the assets you trade, not the actual assets themselves). Spot margin trading typically offers lower leverage and has a different cost structure. Spot margin trading incurs interest on borrowed funds, while perpetual futures involve funding fees paid periodically between long and short traders to keep the contract price aligned with the spot price.

**Q: What leverage options are available?**\
You can choose your leverage from 1x to 50x. The available multiplier differs per market, with higher-market-cap assets offering higher maximum leverage.

**Q: How is the funding rate calculated?**\
The funding rate is used to keep the perpetual price aligned with the real market price. The system compares the perp price to the oracle price. If the perp price is higher than the oracle price, long traders pay a funding fee to short traders. If the perp price is lower, the short traders pay funding to long traders. This mechanism balances the pool’s exposure and helps keep perp prices close to market value. Funding is paid periodically and adjusted based on the difference between long and short open interest, and the difference between perp price and the oracle price.

**Q: What happens during liquidation?**\
When your position is liquidated, it means your margin is no longer enough to cover the position’s loss. The system automatically closes your trade, and your collateral is used to repay the pool. If there is any remaining collateral after covering the loss, it is returned to you. Liquidation protects the pool and ensures that account values cannot go negative.


# RUJI Money Market - Lending & Borrowing

**Q: What is RUJI Money Market?**\
RUJI Money Market is our decentralized lending and borrowing marketplace for crypto assets. Lenders earn interest on their tokens, while borrowers can use their crypto as collateral\* to take loans.

You can access it via:

* Lending: [rujira.network/strategies](https://rujira.network/strategies)
* Borrowing: [rujira.network/borrow](https://rujira.network/borrow)

For a full overview, visit our RUJI Money Market [docs](/core-products/ruji-money-market).

*\*Collateral: crypto you lock up as security for your loan.*

**Q: What are CDP loans?**\
CDP stands for Collateralized Debt Position. It is a way to borrow crypto by locking up other crypto as collateral, and it is always overcollateralized, meaning you must deposit more value than you borrow.

Here is how it works:

* You deposit crypto like BTC, ETH, XRP, etc. or stablecoin\* like USDC and USDT – this is your collateral.
* Each collateral type has a corresponding collateral ratio, which is a risk-adjusting factor applied to your collateral value to define how much you can borrow against it. For example, BTC has a collateral ratio of 70%, meaning you can borrow up to $70 for every $100 worth of BTC.
* You borrow a different token, or stablecoin\* such as USDC or USDT.
* Your loan stays open as long as your adjusted collateral value remains above the value of your debt.
* If your collateral value drops too much, it can be partially liquidated (sold via a market order) to repay part of the debt and bring the position back to a safe level.

*\*Stablecoin: a crypto token that aims to keep a fixed value, often linked to the US dollar.*

**Q: How is the interest rate decided?**\
The interest rate changes depending on how much of an asset is already borrowed. If most of the asset in the vault is borrowed (high utilization rate\*), the interest rate goes up. If more assets get added to the vault, or loaned assets are returned, the rate goes down.

*\*Utilization rate: how much of the total available supply in the vault is currently borrowed.*

**Q: Who am I borrowing from?**\
You borrow from other users who have deposited their assets into lending vaults. Every token you borrow comes from users who chose to lend them out. The interest you pay goes directly to those lenders (minus 10% protocol fee) and is distributed pro rata based on their share of the total deposits.

**Q: What is Collateral Ratio, Adjusted LTV, and Liquidation Price?**

* Collateral Ratio: risk-adjusting factor applied to the value of your collateral to define how much you can borrow against it. For example, BTC has a collateral ratio of 70%, meaning you can borrow up to $70 for every $100 worth of BTC.
* Adjusted LTV (Loan-to-Value): shows how much you borrowed compared to your adjusted collateral’s value. If your Adjusted LTV reaches 100%, your position becomes at risk and will start being liquidated.
* Liquidation Price: the price where your collateral would start to be sold to repay your loan and protect the system’s solvency.

**Q: What happens if my loan gets liquidated?**\
If liquidation happens, your collateral is partially sold on RUJI Trade, our orderbook DEX.\
The proceeds from that sale are used to repay part of your loan till your position gets back to a safe Adjusted LTV (i.e. <100%).

**Q: What is a collateral swap?**\
Collateral swaps are a special Rujira feature that lets you swap your locked collateral without closing your loan.

For example, if you borrowed USDC using BTC as collateral, you can swap your BTC for another token directly, without repaying the loan first.


# RUJI Liquidations - Bid on Liquidated Collateral

**Q: What is RUJI Liquidations?**\
RUJI Liquidations is the first public marketplace where anyone can bid on at-risk collateral and buy it at a discount through Dutch auctions, with no bots or coding needed.

By doing this, users can get discounted crypto while helping keep the Rujira ecosystem healthy and solvent. Creating competition on liquidated collateral also means that liquidations tend to happen at a better price than on other platforms for borrowers who get liquidated, meaning they are losing less in the event of a liquidation.

You can access it here: \[coming soon].

For more details, visit the RUJI Liquidations [docs](/core-products/ruji-liquidations).

**Q: What makes Rujira’s Liquidations different from CEXs and other DeFi platforms?**\
In DeFi, most liquidation systems are only accessible via sophisticated MEV bots that act first and take all the profit. On CEXs, liquidations are a black box with most volumes and profits captured by the platforms themselves and a few permitted market makers, leaving regular users out.

RUJI Liquidations lets anyone place bids at the discount they choose. It does not depend on speed or bots, and liquidations are distributed fairly among all participants, starting from the lowest discount (most favourable to the liquidated borrowers) and moving to higher discounts as the lower discount bids get filled.

This makes liquidations fair, and gives everyone an equal chance to take part.

**Q: Whose liquidations am I buying?**\
You are buying collateral from RUJI Money Market users whose debt positions have passed their safe Adjusted LTV\* level. Once these positions get liquidated, part of the collateral gets sold via a market order on the orderbook and people can place bids at a discount to the current market price to catch the wicks caused by liquidations.

Proceeds from the collateral sold are used to repay part of the users’ debt and bring back their positions to a healthy LTV level. Your bids allow you to buy the local low at a discount while helping to protect the system's solvency.

*\*Adjusted LTV: Adjusted Loan-to-Value ratio, which is a measure of a debt position’s health. For example if you have $100 worth of BTC collateral, the collateral ratio on BTC being 70% (meaning you can borrow maximum $70 for every $100 worth of collateral), then your Adjusted Collateral Value is $100 \* 70% = $70. If you borrow $50 in USDC, your Adjusted LTV would be $50 /* $70 = \~71.&#x34;*%. If the price of BTC drops and your Adjusted Collateral Value is now $48, your new Adjusted LTV would be \~104%, which is past the max limit of 100%, meaning part of your collateral can be liquidated to repay some of your debt.*

**Q: What happens to the bid I open?**\
When you place a bid on RUJI Liquidation, whether it’s to liquidate short or long positions, it gets placed as a Tracking order on our orderbook. Whenever a liquidation happens, the collateral gets sold on the orderbook via a market order and you can catch the discount with your bid, depending on the size of the wick the liquidation creates and where other people's bids are.

**Q: How can I make sense of the heatmap?**\
The heatmap shows at which price level most liquidations are likely to happen, where most bids are placed and how deep the queue is at each discount level.\
\
It helps you decide the best discount to set, lower discounts fill faster, higher discounts offer bigger potential gains but are less likely to get filled.


# RUJI Launchpad - Token Launchpad

**Q: What is RUJI Launchpad?**\
RUJI Launchpad is where ideas meet capital. It gives you early access to new crypto projects raising funds for growth by letting you take part in their token launch. You can support your favorite projects and benefit like a venture capitalist\*.

You can access it here: \[coming soon]

For more details, visit the RUJI Launchpad [docs](/core-products/ruji-launchpad).

*\*Venture capitalist: someone who invests early in new projects hoping for long-term growth.*

**Q: What makes RUJI Launchpad different?**\
RUJI Launchpad is more than a place to buy tokens. It gives projects a complete set of tools for every stage, from early fundraising to token generation events (TGE)\* and later growth rounds.\
\
The first product being released is the Launchpad, with additional products to be developed later.

*\*TGE (Token Generation Event): when a new project officially creates and distributes its token.*

**Q: How can I join a token launch?**\
When a sale is live, you can place bids at your chosen price.

Each sale has:

* A Token Price (the highest price)
* A Max Discounted Price (the lowest price)

Between those two, there are small price steps called Silos. For example, if the token price is 1.00 USDC and the max discount is 30%, there will be 30 silos ranging from 1.00 USDC down to 0.70 USDC.

When the sale ends, tokens are distributed starting with the highest bids and moving down through the silos until all tokens are allocated. Bids that receive tokens are called qualifying bids. If your bid doesn’t qualify, you can retrieve your funds and use them for future launches or anything else.

**Q: Can I launch my own token?**\
Yes. Anyone can create a sale without needing to code. You just need enough funds to pay a small deposit (to filter spam) and the cost of a few on-chain transactions. It is important to note that each address can only create one sale.

While using the launchpad is permissionless, you will need to sell the entire supply you allocate to the public launch and raise a minimum value of $1,000 to be able to complete your sale. This is to help filter spam projects that are not able to build a convincing case for potential investors, or prevent legit projects from not raising enough to be in a position to deliver on their plans.

**Q: Are tokens on RUJI Launchpad screened?**\
No. Launching is permissionless, which means anyone can start a token sale. You are responsible for doing your own research to decide whether a project is legitimate and worth supporting.

The Rujira team may also choose to participate in a sale at their own discretion. This is not an endorsement, and users should always make their own decisions about whether to take part.


# RUJI Index - Crypto Indices

**Q: What is RUJI Index?**\
RUJI Index is the index product on Rujira. It gives you access to curated sets of assets that follow a clear and transparent strategy.\
\
You can use RUJI Index at [rujira.network/index](https://rujira.network/index) or on <https://rujira.network/strategies?filters=IndexVault>\
\
A more detailed explanation can be found [here](/core-products/ruji-index).

**Q: What are crypto indices?**\
Crypto indices are bundles of assets grouped together in a single product. The bundle can have a predefined composition or a flexible one.\
Indices give you diversified exposure to a category, a theme, or a group of assets. They work in a similar way to ETFs in traditional finance.

**Q: What indices are available?**\
The following indices are currently available:

1. yTCY (yield bearing TCY index)
2. yRUNE (yield bearing RUNE index)
3. RJI (Rujira ecosystem index)

The next index we plan to release will include a set of blue chip assets.

**Q: How are the indices weighted and rebalanced?**\
There are two types of index implementations:

* NAV indices are automatically rebalanced based on target weights and the value of each component. These require every asset in the index to have an oracle price.
* Fixed indices keep a fixed unit ratio between the assets and do not auto-rebalance. This type does not require oracle pricing and is used for assets that exist only inside Rujira.

**Q: Can I create my own index?**\
Not yet. Personal index creation is something we plan to explore in the future.


# Strategies - Put your assets to work

### Strategies Overview

**Q: What is Strategies?**\
Strategies is the place where you can see all the ways to earn on Rujira. It gives you simple options and more advanced ones in one clear view, including RUJI AMM (automated market making strategies), Lending vaults, staking, Perp LPs and more.

You can access Strategies at [rujira.network/strategies](https://rujira.network/strategies).

**Q: What different strategies are available?**\
The following strategies are currently available:

1. XYK Pools
2. Fixed-range Concentrated Liquidity Pools (soon)
3. THORChain Continuous Liquidity Pools
4. Lending Vaults
5. Staking
6. Perp LPs (deprecated)

**Q: What is an Automated Market Maker (AMM)?**\
RUJI AMM is our multi-strategy Automated Market Maker. For each trading pair, it manages an inventory of base asset (e.g. BTC) and quote asset (e.g. USDC), automatically placing buy and sell orders on RUJI Trade orderbook to provide liquidity. Each strategy follows a specific set of rules to define how much of each asset to buy or sell at various price levels. Each strategy generates some return in the form of a spread every time it takes a trade (i.e. sells at a slightly higher price than it bought for / buys at a slightly lower price than it sold for).

AMM strategies democratize access to market making and allow anyone to put any two assets you are happy to get exposure to to work to generate some yield.

**Q: What makes Rujira’s AMM unique?**\
RUJI AMM works directly with RUJI Trade, our on-chain orderbook DEX. Liquidity from each strategy is placed into the orderbook in real time based on each strategy’s rules.

Rujira's unique design separates the DEX (RUJI Trade) from the multi-strategy AMM (RUJI AMM) with all strategies adding liquidity to the same orderbook, resulting in deeper markets for traders, while offering multiple opportunities with different risk profiles for everyone to become a market maker.

### Strategies - AMM/XYK

**Q: What is an XYK pool?**\
An XYK pool is a market-making strategy that keeps a 50/50 balance between two tokens (for example, BTC and USDC).

When one token goes up in price, the strategy automatically sells some of it and buys the other, earning small profits from these price movements.

This approach reduces downside risk compared to simply holding the tokens when price goes down, but it also lowers upside gains when price goes up. It’s a powerful tool for people who want steady returns with less volatility.

You can access XYK Pools here: <https://rujira.network/strategies?filters=BowPoolXyk>\
\
For more details, see the XYK strategy [docs](https://docs.rujira.network/strategies#xyk-strategy).

**Q: How can I open a position?**\
Go to the Strategies page, filter by XYK, choose a strategy, enter the amount you want to provide, and sign the transaction.

**Q: What is impermanent loss?**\
Impermanent loss (IL) is the reduction in value that happens when the prices of the two tokens you provided to a liquidity pool move apart, leaving you with less total value than simply holding them separately.\
\
Because an XYK pool automatically rebalances to a 50/50 target ratio, it sells some of the token that goes up in price and buys more of the one that goes down.\
\
If prices do not return to where they were when you entered, you end up with more of the underperforming token and less of the outperforming token, making the value of your position lower than if you had simply held the two tokens separately.

If volumes have been good during the period, the fees you generated by providing liquidity should more than offset the IL. If prices come back to their level at the time you opened your position, the IL will be reverted and the trading fees you earned will be pure profit.

### Strategies - AMM/Fixed-range Concentrated Liquidity

**Q: What is a Fixed-range Concentrated Liquidity pool?**\
A Fixed-range Concentrated Liquidity (FCL) pool lets you provide liquidity within a specific price range instead of across the entire market.

This means your capital works more efficiently: you earn higher fees when trading happens inside your chosen range.

The tighter your range, the more volume you will facilitate while price is inside your range and the more fees you will earn. The downside is that the tighter your range, the more likely price will move outside and you will be left holding the underperforming asset and not generating yield while price is out.

Finding the range that works for you depends on your time horizon and what your prospective view on the two tokens' prices is. Taking the example of a BTC/USDC FCL position, a helpful way to think about it is to ask at which price you would be happy to be holding 100% BTC, and at which price you would be happy to be 100% in USDC.

Let’s say the current price is $90,000 and you looked at the charts and believe it’s unlikely BTC will drop below $70,000, or go above $150,000 this cycle, which is the time horizon over which you plan to hold this position. Those would be the two limits of your range. It means you are happy to keep buying BTC with USDC till it drops to $70k and then have 100% of your position in BTC, or keep selling BTC for USDC till it reaches $150k and then have 100% of your position in USDC. Meanwhile, you are collecting fees on the trading volumes generated by your position, making money on volatility as long as the price stays in your range.

You can access CL Pools here: \[*coming soon*].

For more details, see the FCL strategy [docs](https://docs.rujira.network/strategies#concentrated-liquidity-strategy).

**Q: How can I open a position?**\
Go to the Strategies page, filter by FCL, choose a pair for which you want to provide liquidity, enter how much you want to provide and your range, and sign the transaction.

**Q: What is impermanent loss?**\
Impermanent loss is the reduction in value that happens when the prices of the two tokens you provide move apart, leaving you with less total value than simply holding them separately.

With fixed-range concentrated liquidity, your funds are active only within the price range you set. As the market moves within your range, the strategy sells the outperforming token to buy the underperforming token, making the value of your position lower than if you had simply held the two tokens separately.

If the price moves outside your range, your position becomes fully one-sided, and the loss becomes larger if the price never returns. This means impermanent loss is amplified for FCL positions compared to a standard XYK LP, but the yield is also much higher as long as the position remains in range.

### Strategies - AMM/THORChain Continuous LP

**Q: What is a THORChain Continuous Liquidity Pool?**\
A Continuous Liquidity Pool (CLP) provides liquidity to THORChain’s native pools, which pair tokens with RUNE using a constant product AMM model (XYK) and a dynamic slip-based fee.\
\
It works similarly to the XYK strategy on Rujira but directly on the THORChain base layer.

You earn yield from:

* Slip-based fees, which increase with trade size
* A share of Rujira’s revenue that is sent to THORChain

Rewards are split between liquidity providers (LPs) and THORChain node operators based on the Incentive Pendulum\*.

You can access Continuous LPs here: [rujira.network/strategies?filters=ThorchainPool\ <br>](https://rujira.network/strategies?filters=ThorchainPool)For more details, visit the Continuous LP docs: <https://docs.thorchain.org/technical-documentation/thorchain-finance/continuous-liquidity-pools>

*\*Incentive Pendulum: a system that dynamically balances rewards between THORChain’s liquidity providers and node operators to keep the network healthy.*

**Q: How can I open a position?**\
Go to the Strategies page, filter by Continuous LP, choose a pool, enter the amount you want to provide, and sign the transaction.

**Q: What is impermanent loss?**\
Impermanent loss is the difference in value between providing liquidity and simply holding your assets, caused by price movements between the two tokens in the pool.

With THORChain’s Continuous Liquidity Pool (CLP) model, the pool automatically rebalances your assets as prices move to keep the value of each side at 50/50. When one asset increases in price relative to the other, the pool sells some of it into the other asset to keep the pool balanced. Over time, this leaves you with more of the asset that underperformed and less of the one that outperformed.

THORChain reduces the impact of impermanent loss through its fee structure. Swappers pay liquidity fees, and those fees go directly to LPs. When the pool is active and swap volume is high, these fees can offset or even exceed impermanent loss. If prices never return to where they were when you entered, the difference between the LP value and the hold value becomes your impermanent loss.

### Strategies - Lending

**Q: What are Lending Vaults?**\
Lending vaults are where all assets from lenders are pooled together. For example, all BTC deposited by lenders is combined in a single BTC lending vault, and borrowers can take loans directly from that shared pool.

You can access them here: [rujira.network/strategies?filters=GhostVault](https://rujira.network/strategies?filters=GhostVault)

**Q: What happens to the assets that I lend out?**\
Your assets are added to the lending vault and combined with those from other lenders. When someone borrows that token, it comes from this shared vault, and the interest paid is split pro-rata among all lenders.

**Q: Can I always withdraw my assets?**\
You can withdraw your assets as long as they are not currently borrowed. If most of the vault’s assets are being borrowed (high utilization rate\*), you may need to wait until some borrowers repay or new lenders add more liquidity.

*\*Utilization rate: the percentage of total deposited assets that are currently borrowed.*

**Q: How is the lending rate determined?**\
The lending rate depends on the utilization rate:

* When more of an asset is borrowed, or when some lenders withdraw from the vault, the rate goes up.
* When borrowing demand is low, or when more lenders deposit into the vault, the rate goes down.

This market-driven mechanism helps balance supply and demand and keep interest rates in line with the broader DeFi market, attracting borrowers when there is an excess supply and rates are low, and attracting lenders when there is an excess demand and rates are high.

### Strategies - Staking

**Q: What is staking?**\
Staking lets you deposit your token in a smart contract (sometime with a lock-up period) to earn rewards over time. It’s a simple way to support the network and earn passive income.

You can access staking here:[ rujira.network/strategies?filters=StakingPool](https://rujira.network/strategies?filters=StakingPool)

For more details, visit the staking [docs](https://docs.rujira.network/strategies#staking).

Q: What tokens can be staked?\
You can currently stake the following tokens:

* $RUJI
* $TCY
* $AUTO (soon, currently available [here](https://daodao.zone/dao/thor1ervurprt6cwrpsy6t3h2gxeg5rw25xumhp58e6hct0jcse6feu5sxdnq0j))
* $LQDY (soon, currently available [here](https://daodao.zone/dao/thor1adumh9aj7urearxd0ezujaue4agclltu2y45qr2z4yazveqkvygqwmlgp6/home))

**Q: What is the difference between Standard and Auto-Compounding staking?**

* Standard staking: You earn rewards (usually in $USDC) which you can claim whenever you want.
* Auto-compounding staking: Your rewards are automatically used to buy more of the same token, which increases your staked balance over time.

*Example:*\
If you stake $RUJI, you normally earn $USDC rewards. With auto-compounding turned on, your $USDC is automatically used to buy more $RUJI, which is added to your stake.

**Q: Is there an unstaking period?**\
Staking might be subject to an unstaking period during which you have to wait after signaling your intention to unstake, before you can access your tokens:

* $RUJI: No unstaking period (instant).
* $TCY: No unstaking period (instant).
* $AUTO: 14-day unstaking period.
* $LQDY: 7-day unstaking period.


# RUJI Leagues - Points competition

**Q: What is RUJI Leagues?**\
RUJI Leagues is our in-house competition where you can earn rewards by using Rujira products.

You can access the leaderboard of RUJI Leagues on [rujira.network/leaderboard](https://rujira.network/leaderboard).

**Q: What do I have to do to be eligible?**\
The first season hasn't started yet, at the moment everyone is earning points. To be eligible and capitalize on the points you have earned to date, you will need to register your wallet for RUJI Leagues Season 1 (to be announced). Participating in the Leagues will require staking some RUJI.\
\
**Q: How do I earn points?**\
You earn points by using Rujira products. Every time you generate revenue for the protocol, the fees you pay are converted into points. The more points you collect, the higher your rank and the better your rewards.

**Q: How are points calculated?**\
The baseline is that every $1 of fees you paid gives you 69 points. But there will be some exceptions that might be temporary to highlight the usage of a product for a season, or permanent to sweeten certain negative events. For example, we plan to apply a larger multiplier to liquidation fees so that, even when the market isn't following your plans, there is still something extra to earn.

**Q: What are the rewards?**\
Rewards will be paid out at the end of each season in $USDC and $RUJI. A detailed breakdown of the rewards will be shared once we start the first season.

**Q: How long does a season last?**\
Each season lasts for 6 weeks. After that, rewards are distributed, points reset, and a new season begins.


# CALC Recurring Orders - DCA in and out of positions

**Q: What are Recurring Orders?**\
Recurring orders built by the [CALC](https://calculated.fi/) team let you create a trading schedule to swap over time using native (secured) assets on Rujira. Whether you want to gradually build a position or take profits in smaller parts, this feature runs fully on-chain and allows you to schedule swaps, and set custom parameters to trade on your own terms.

**Q: Where can I access recurring orders?**\
Recurring Orders are available from [RUJI Trade](https://rujira.network/trade/RUJI/USDC?orders=recurring-active\&order=recurring) by selecting Advanced in the trade panel.

**Q: How to set up a recurring order on RUJI Trade?**\
Assuming you already have funds on Rujira, you can create your first Recurring Order in three simple steps.

* Step 1: Choose a trading pair in [RUJI Trade](https://rujira.network/trade/BTC/USDC)
* Step 2: Set up your order via Advanced -> Recurring
* Step 3: Submit the transaction

**Q: How do recurring orders on RUJI Trade work?**\
Creating a recurring order is like setting up a machine that processes your trades at the intervals you set, here’s how it works in a nutshell. Let’s break it down into:

1. How recurring orders are created
2. How the recurring order mechanism works
3. How tokens are transferred

**Q: How are recurring orders created?**\
When you start a recurring order, the tokens will be transferred from your wallet into a smart contract vault that runs the strategy.

Once you create a recurring order, your first order is executed right away. For example, if you’re setting up an order from USDC into RUJI, the full USDC will be stored in your vault, and the first trade (say $100 USDC for RUJI) will happen immediately.

The remaining trades follow at regular intervals, based on the schedule you pick. For instance, if you’re splitting $1,000 USDC over 10 days, you’ll see the first $100 -> RUJI trade right away, and then 9 more trades of $100 each happening daily like clockwork (except when you set price protection and swaps do not meet the right conditions to execute).

**Q: How does the recurring order mechanism works?**\
When you create a recurring order, your total trade is split into smaller, bite-sized swaps. The number of swaps depends on your settings. Let’s break it down:

Say you’re recurring $900 USDC into RUJI over 3 swaps of 1 day. Your order will be split into 3 trades of $300 USDC each, one for every day. Let’s see this in action:

* Day 1: Once your order is confirmed, the first $300 USDC -> RUJI trade happens immediately.
* Day 2: 24 hours later, the second trade of $300 USDC -> RUJI gets executed.
* Day 3: Another 24 hours after that, the third and final trade wraps up your order and automatically sends the acquired RUJI to your wallet.

The amount of $RUJI you receive depends on its price at the time of each trade. Following the same example:

* Day 1: If RUJI costs $20, your $300 buys you 15 RUJI.
* Day 2: If RUJI jumps to $25, your $300 gets you 12 RUJI.
* Day 3: If RUJI dips to $15, your $300 scores you 20 RUJI.

*Note: CALC charges a 0.25% fee after withdrawals from an order. So, in the end a total of 47 RUJI (minus a fee of 0.1175 RUJI) is automatically sent to your wallet.*

**Q: How are tokens transferred?**\
Every time a swap executes, the swapped tokens are stored in the vault until the recurring swap order is finished. The recurring order is finished when there are no deposit tokens left to swap in the vault. Then the acquired tokens are automatically sent to your wallet.

💡 Pro Tip: If you don’t want to wait for a strategy to finish, you can edit, withdraw, deposit or pause your order details at any time.

**Q: How to manage multiple recurring orders?**\
It’s easy to manage your recurring strategies from the RUJI Trade orders overview and from the My Portfolio overview.

**Q: Does my recurring order automatically retry if it fails?**\
Yes, if a swap fails due to high price impact or exceeded price thresholds, the order will automatically retry at the next set scheduled interval.

**Q: How is the price calculated with each recurring swap?**\
Swaps are routed via the RUJI Trade orderbook at the current best market price.

The price for each swap is calculated at the time the transaction is executed. Swaps execute on the RUJI Trade order book and can include parameters like price impact or price protection, to ensure you receive a minimum amount of tokens. If the price exceeds the max price impact settings or price threshold, the transaction will fail in order to protect you from unfavorable swaps.

Before starting your strategy, make sure to have a look at the summary to make sure everything looks right. Or review your ongoing strategy from the Recurring Orders overview or the My Portfolio overview.

**Q: Can I pause the recurring order temporarily and resume it later?**\
Yes. Pausing and resuming of recurring orders is supported.

**Q: What are the fees?**\
An automation fee of 25bps (0.25%) applies to all funds exiting a recurring order, whether through completion or manual withdrawal. This fee is over and above standard RUJI Trade taker fees.


# Contact

**Q: I need help. Who can I talk to?**\
You can get support on our [Discord](https://discord.gg/XPvsxhWKfb) by submitting a support ticket, or on our [Telegram](https://t.me/Rujira_Community).\
Make sure you do not reply to private messages from unknown people to avoid scams.

**Q: I want to build something on Rujira. What should I do?**\
Start by checking our [Build Ideas](/developers/build-ideas) to see what you can create. Then send an email to <bd@rujira.network> with:

* Your idea name and concept
* Your Telegram handle
* Estimated timeline
* Team size

Our team will get in touch with you after that.

**Q: I want access to the API. Who do I reach out to?**\
Please email <api@rujira.network> with details about the request, and we will get in touch with you.&#x20;

**Q: Who do I contact for partnerships or integrations?**\
Please email <bd@rujira.network> with details about your project or proposal.

**Q: Who do I contact for marketing or collaborations?**\
For co-marketing, campaigns, or other collaborations, send an email to <marketing@rujira.network>.

**Q: How can I join the Rujira community?**\
Join our [Telegram group](https://t.me/Rujira_Community). That is where most of our community members are.\
You can also explore subcommunities using the #communities command in the chat.

**Q: Where can I give feedback or report bugs?**\
We appreciate all feedback and bug reports, and you can share them in our [Discord](https://discord.gg/XPvsxhWKfb) or [Telegram](https://t.me/Rujira_Community) chat. At a later stage, we will have a dedicated page to make this even easier.


# RUJI Trade

RUJI Trade provides a decentralized, scalable, and highly efficient orderbook exchange (DEX) operating fully on-chain. The orderbook DEX design offers fair execution, low fees, a great trading UX, and a superior trade execution vs. standard AMM-DEXs. All trading pairs on the RUJI Trade orderbook DEX can be found on the [Spot Trading page](https://rujira.network/trade).

### Key Features

* **Decentralized Orderbook Trading:** A 100% on-chain orderbook exchange (including order matching logic), offering decentralized and permissionless trading.
* **Scalable Performance:** Constant-time O(1) matching algorithms, allowing the DEX to handle very large transaction volumes efficiently.
* **Multi-source Liquidity:** A unique architecture allows the orderbook DEX to pull liquidity from multiple sources, including users' pending orders, Rujira's AMM strategies ([RUJI AMM](/core-products/ruji-amm)) on the App Layer and THORChain's liquidity pools on the Base Layer via a dedicated market making arbitrage strategy that virtualizes the liquidity in the Base Layer pools.
* **Limit Orders:** A standard limit order to buy or sell at the limit price or better. Orders submitted at a worse price than the current bid/ask are instantly executed as market orders up to the limit price, with any unfilled quantity remaining in the book as standing order.
* **Tracking Orders:** A novel type of order allowing users to buy or sell at a fixed discount/premium to the underlying asset's oracle price, opening up the design space for innovative trading and market making strategies.
* **Margin Trading:** The DEX connects directly into Rujira's [Money Market](/core-products/ruji-money-market) to offer high leverage (up to \[10x -TBD]) spot margin trading.
* **Low Fees:** A cost-effective trading experience with low gas and low maker/taker fees (7.5bps/15bps).

### Benefits

RUJI Trade orderbook model has several advantages over traditional AMM DEXs:

* **Better Trade Execution:** Orderbooks offer better pricing and capital efficiency. As long as there are willing counterparties on the other side of a trade, traders can execute orders of any size without moving the price.
* **Fair Order Execution:** Most orderbook exchanges (DEXs and CEXs alike) use either opaque off-chain logic or time-based rules (FIFO) to decide which order gets filled first at a given price level. This results in an unfair advantage for whoever controls the offchain logic or has the most performant infrastructure, allowing them to frontrun other participants. On RUJI Trade, the matching of orders is done 100% on-chain and follows a truly fair distribution logic, filling everyone's orders proportionally to their size at a given price level with no frontrunning possible.
* **Modular Architecture Enabling Deeper Liquidity:** Traditional AMM DEXs use a monolithic structure that distributes asset prices over a single bonding curve. The larger an order size relative to the size of the liquidity pool, the bigger the price impact suffered by the trader. In contrast, Rujira separates the DEX (orderbook) from the AMM (automated market maker), allowing it to pull liquidity from a variety of sources and market making strategies and combine them into a single orderbook, resulting in much deeper liquidity.
* **Intuitive Interface:** RUJI Trade interface design is user-friendly and offers a smooth trading experience, comparable to centralized exchanges, with support for market orders, limit orders, and tracking orders which are unique to Rujira.

### Fees & Fee Sharing with THORChain Base Layer

* RUJI Trade charges a 0.075% fee on Maker orders (i.e. orders adding liquidity to the orderbook) and a 0.15% fee on Taker orders (i.e. orders removing liquidity from the orderbook).
  * AMM Strategies from [RUJI AMM](/core-products/ruji-amm) benefit from a lower Maker Fee (0.025%) since they are key to providing liquidity and improve trading conditions for other users.
* RUJI Trade also captures any arbitrage between limit orders and other order types as protocol revenue, internalizing a source of profit that would typically be captured by MEV bots in traditional DEXs.
* In terms of fee sharing with THORChain Base Layer, a distinction must be made between the different fee types. The core logic regarding fee sharing is the following: For each transaction on the App Layer, is value accrued to the Base Layer?
  * If the answer is YES, there is no need to share revenue (the Base Layer already benefits).
  * If the answer is NO, then the 50/50 revenue split applies to pay for security.
* RUJI Trade pulls liquidity from various sources. Depending on the source, the fee sharing rule applies differently:
  * Orders executed against the App Layer liquidity do not accrue value to the Base Layer, therefore the 50% fee sharing with the Base Layer must apply to pay for security.
  * For trades executed against TC Base Layer liquidity (via the [Virtualization Strategy](/core-products/ruji-amm/base-layer-virtualization-strategy)), THORChain charges its own fee (defined by mimir *SecuredAssetSlipMinBps*) and benefits from those additional volumes. Orders executed against Base Layer liquidity are systematically accruing value to THORChain, therefore Rujira does not need to pay for security (i.e. RUJI stakers keep 100% of the RUJI Trade fees).

### Status

* RUJI Trade is live [here](https://rujira.network/trade/BTC/USDC).

### FAQ

* [RUJI Trade FAQ](/how-it-works/frequently-asked-questions/ruji-trade-orderbook-dex)


# RUJI AMM

​​RUJI AMM provides access to multiple Automated Market Making strategies built to add liquidity to the Orderbook DEX. Market making keeps bid-ask spreads tight and deepens orderbook liquidity. It is essential to optimize trading conditions and provide a great trading UX. Rujira's AMM attracts liquidity providers (LPs) by offering yield in the form of trading profits. RUJI AMM strategies are available from the [Strategies](/strategies) page.

### Key Features

* **Decentralized Market Making:** Permissionless, 100% on-chain market making with no need for external cranking.
* **Virtualized orders:** The protocol’s architecture enables the AMM to virtualize orders on the Orderbook DEX, meaning the AMM doesn’t need to move the funds to the DEX to place regular orders. It only needs to guarantee the DEX it can execute at the price it says it will, when a matching order comes in on the DEX (just-in-time liquidity). We call this passive market making, as opposed to active market making, where strategies place regular fixed-price orders in the orderbook. This allows for much more efficient operations with the AMM not requiring to cancel and replace all orders every time the price moves, saving on gas and block space.
* **Multi-strategy:** Rujira's AMM is a flexible framework allowing deployment of all sorts of strategies which add liquidity to the orderbook DEX. RUJI AMM comes with several in-house strategies, including:
  * **Custom Concentrated Liquidity strategy (live):** Deploys the liquidity within a user-defined fixed range, with custom spread between orders and flexible distribution of liquidity inside the range, allowing for more opinionated market making and higher capital efficiency vs. XYK strategies.
  * **Base Layer Virtualization strategy (live):** Arbitrage strategy that virtualizes the liquidity in THORChain's Base Layer pools onto the App Layer, allowing the App Layer to tap into Base Layer liquidity while retaining transaction atomicity and composability. This passive market making strategy is able to query the Base Layer pools to see how much target asset (e.g. BTC) it would get for a given quantity of asset to be sold (e.g. USDC), and then provide a quote at a slightly worse price (Base Layer price + small margin). This quote appears in the orderbook alongside any pending fixed-price and tracking orders. For a deeper understanding of the strategy, see [here](/core-products/ruji-amm/base-layer-virtualization-strategy).
  * **XYK strategy (depreciated):** Uses a pricing and order sizing algorithm replicating the standard XYK logic used by a traditional AMM-DEX like Uniswap v2, but tailored for an orderbook DEX. This strategy suits smaller tokens still in price discovery mode and subject to high volatility.
  * **Oracle-based Concentrated strategy (pending):** Deploys most of the liquidity around the current oracle price for a given pair, using Rujira's Tracking Orders functionality to provide deep liquidity and harvest volatility. This strategy suits established tokens with deep liquidity on other venues and reliable oracle prices.
  * **Orbital strategy (pending):** Provides liquidity for any number of highly correlated assets such as stablecoins, in a single pool, with high capital efficiency & built-in risk mitigation in case of a depeg.
* **Strategies Layering:** Rujira's Orderbook DEX allows the AMM to layer several strategies for any given pair in the orderbook, adding liquidity on top of liquidity from users' limit and tracking orders, and liquidity from the virtualization of TC Base Layer pools. This helps deepen liquidity vs. a traditional AMM-DEX and increases volumes on the DEX.
* **Third Party strategies (pending):** Rujira's AMM will enable third parties (e.g. experienced market makers, quants, and talented community members) to deploy their own strategies and get rewarded with a management fee and/or a performance fee. The design space for strategies is wide open: it could be other market making strategies,  more opinionated strategies with a directional bias such as momentum strategies, or anything else. This will effectively create a market for systematic strategies, allowing talented quants to monetize their know-how while adding opportunities for Rujira's users and generating more trading fees for RUJI stakers.
* **LP Incentives (pending):** Optionally, the AMM allows third party protocols to incentivize liquidity by allocating token rewards to LPs, distributed over a custom period with a custom issuance curve.
* **Leveraged Market Making (pending):** The AMM connects directly into Rujira's Money Market, allowing liquidity providers to use their LP tokens as collateral to borrow any side of the LP and increase the size of their position. This allows for things like single-sided LP provisioning (e.g. provide BTC and borrow the USDC part to market make in the BTC/USDC pair, or the other way around if you have a bearish view on BTC vs. USDC) and partial hedging of LP positions. The position is profitable if the net trading profit on the LP position is higher than the interest paid on the debt.

### Benefits

* **Sustainable APR for LPs:** An opportunity for Rujira users to generate sustainable returns on their crypto assets in the form of trading profits by providing liquidity. Users deposit in a given pool, and the AMM automatically places and adjusts orders in the Orderbook DEX based on the pool's specific strategy.
* **Multi-strategy Support:** A flexible framework allowing the deployment of multiple strategies, catering for various risk profiles and bias towards market direction. Strategies can be developed by the Rujira team or third parties.
* **Enhanced Liquidity:** The AMM brings the benefit of professional-grade market making on-chain to the Orderbook DEX, with enhanced liquidity and narrow spreads for a better trading experience.
* **Higher Trading Volume:** Layering AMM strategies in the orderbook for a given pair leads to increased volume opportunities. The relationship between regular orders (at a fixed price) and tracking orders (at a fixed discount/premium to oracle price) is particularly beneficial to volumes. It creates a dynamic where oracle-based AMM strategies can trade against XYK strategies and other fixed-price orders, resulting in more volumes and profit opportunities for LPs, and more fees to RUJI stakers.
* **Economic Sustainability:** Many top traditional AMM-DEX rely on unsustainable token incentives or inflationary rewards to generate attractive yield for LPs and attract liquidity. Uniswap rewards LPs with trading fees, but does not share any revenue with UNI token holders. Rujira’s Orderbook DEX model allows LPs in the AMM to generate sustainable returns from trading profits (e.g. by capturing the bid-ask spread defined by the strategy) without the need for any RUJI rewards. This mitigates the risk of continuous price pressure from LP incentives being farmed, alleviates the risk of liquidity disappearing once incentives run out, and allows trading fees (net of TC Base Layer share) to be 100% distributed to RUJI stakers.
* **Internalization of Market Making Revenue:** This enables projects to turn what was historically a source of costs (market making by paid professionals) into a source of sustainable profit via protocol-owned liquidity. Rujira will demonstrate this by deploying a portion of its operational funds to market make for RUJI and other top tokens using Rujira's AMM pools.

### Fees & Fee Sharing with THORChain Base Layer

* Rujira's AMM strategies are built on top of Rujira's Orderbook DEX. They are key to providing liquidity and offering a better trading UX and more volume opportunities. Because of the critical service they provide, AMM strategies benefit from a lower Maker Fee of 0.025% compared to regular limit and oracle orders.
* The AMM Maker Fee is distributed between the App Layer and the Base Layer following the same rules as the rest of [RUJI Trade](/core-products/ruji-trade#fees-and-fee-sharing-with-thorchain-base-layer).
* Liquidity Providers on the AMM generate returns from a mix of trading profits, and custom trading fees that can be added on top of the AMM Maker Fee and claimed separately from the principal.
* Strategies deployed by the Rujira team are not subject to any additional fees. However, strategies deployed by third-parties might be subject to performance and/or management fees.

### Status

* CCL strategies are live and can be found on [RUJI Trade](https://rujira.network/trade/BTC/USDC?orders=range\&range=t) by toggling "Algorithmic" on.
* The Virtualization Strategy is live. It is a self-contained contract that does not require third-party LP deposits.
* XYK strategies are depreciated, but can still be found [here](https://rujira.network/strategies?filters=BowPoolXyk).
* More strategies will be added over time.

### FAQ

* [XYK Strategy FAQ](/how-it-works/frequently-asked-questions/strategies-put-your-assets-to-work#strategies-amm-xyk)
* [Fixed-range Concentrated Liquidity Strategy FAQ](/how-it-works/frequently-asked-questions/strategies-put-your-assets-to-work#strategies-amm-fixed-range-concentrated-liquidity)
* [THORChain Continuous LP Strategy FAQ](/how-it-works/frequently-asked-questions/strategies-put-your-assets-to-work#strategies-amm-thorchain-continuous-lp)


# Base Layer Virtualization Strategy

The Base Layer Virtualization Strategy (VS) is a single-sided passive market making strategy that allows Rujira App Layer to virtualize the liquidity in THORChain's Base Layer pools via an arbitrage mechanism.

On the Base Layer, all swaps are executed at the end of block and ranked by price impact. This means that despite the App Layer sharing the same blocktime and - in theory - supporting atomic transactions between CosmWasm contracts and THORChain Base Layer, in practice we cannot have atomicity with the Base Layer swaps, i.e. we cannot within the same block do something on the App Layer, then do a Base Layer swap, then do something else on the App Layer with the proceeds from that swap. The Base Layer Virtualization strategy is Rujira's answer to this problem, it allows the App Layer to tap into Base Layer liquidity while retaining transaction atomicity and composability.

Whenever someone wants to do a swap on the App Layer (e.g. I want to swap 10,000 USDC for BTC), the market making strategy is able to query the Base Layer pools to see how many BTC it would get for 10,000 USDC and then provide a quote at a slightly worse price (Base Layer price + small margin). This quote appears in the orderbook alongside any pending fixed-price orders, tracking orders and CCL orders. Whenever an order is matched against it, the target asset is borrowed from RUJI Lending for the duration of 1 block and used to fill the buyer's order on the App Layer, then the opposite swap is executed on the Base Layer at the end of the block. Finally, in the next block, the loan is repaid with the proceeds from the Base Layer swap, and the remaining profits, if any, are retained in the VS contract as reserve to absorb any future loss from unfavourable base layer execution. Over the long run, most trades from the VS should be breakeven or slightly profitable, but there might be instances where the execution price in the Base Layer pool is worse than what was quoted, in that case the strategy makes a loss that is offset by the contract's reserve.

The chart below illustrates how the strategy works with the various flows of funds. A complete walkthrough is available in this [video](https://www.youtube.com/watch?v=sGBNbV5z2cc).

<figure><img src="/files/l9T0rIkCxnJPcNYaAnyY" alt=""><figcaption></figcaption></figure>

{% embed url="<https://www.youtube.com/watch?v=sGBNbV5z2cc>" %}


# RUJI Perps

{% hint style="info" %}
RUJI Perps v1 is an isolated perpetual futures product built by the Levana team. This version is being discontinued and will be replaced by a peer-to-peer orderbook model fully integrated with the wider Rujira ecosystem.
{% endhint %}

RUJI Perps is a decentralized, fully collateralized perpetual futures trading platform (Perp DEX) that allows users to trade tokens with up to 50x leverage, offering a secure and innovative trading experience. Unlike traditional perpetual futures platforms, RUJI Perps eliminates insolvency risk by ensuring all positions are fully funded, which guarantees the safety of traders' profits (PnL). With unique features such as locked liquidity, crypto-denominated pairs and cross margin, RUJI Perps is designed to overcome common challenges in the perpetual futures trading space, including liquidity imbalances and market manipulation.

### Key Features

* **Locked Liquidity:** RUJI Perps introduces an innovative system of locked liquidity, where liquidity providers (LPs) deposit assets that are locked against traders' positions. These locked assets represent the maximum potential profits traders can achieve, ensuring there is always liquidity to pay for trader’s gains. This system prevents the risk of illiquidity even during extreme market conditions, ensuring that the platform can cover profits for all traders. Liquidity providers are compensated for the risks they take by receiving trading and borrow fees from traders.
* **Crypto-Denominated Pairs & Infinite Max Gains:** For crypto-denominated pairs, RUJI Perps allows traders to open long positions with no cap on profits or fear of protocol solvency. As the base asset (e.g. BTC) increases in value, traders can benefit from infinite max gains in quote assets (e.g. USD). This offers a unique opportunity for traders to speculate on rising crypto prices without the limitations of stablecoin-denominated pairs. Trader collateral is denominated in the base asset (e.g. BTC), and gains are paid out for both long and short positions in the base asset. In short, when you win on RUJI Perps in a crypto-denominated market, you earn more of that crypto. This is a unique way to stack more of your favorite assets.
  * *Initially, RUJI Perps will only offer USDC-denominated pairs. BTC denominated pairs will be added at a later stage.*
* **Trade directly from your wallet:** Traders can start trading using the collateral in their wallet. Deposits are only required when opening a new position and are returned to traders' wallets when the position is closed, along with any gains or losses, once the position is closed. This ensures a smooth and efficient trading experience.
* **No Mark Price Manipulation:** Unlike traditional platforms that rely on an internal mark price, RUJI Perps uses oracle-based spot market prices for entry and PnL calculations. This increases the difficulty of price manipulation attacks, especially in low-volume environments, providing a more stable and transparent trading experience.
* **Low-cost leverage and Dynamic Fee Structures:** Traders can use leverage with low fees, allowing them to maximize positions with minimal capital. With RUJI  Perps, dynamic fees adjust based on market conditions, ensuring fair and competitive costs. Take profit triggers closer to your opening position result in lower fees for traders due to greater capital efficiency.

### Benefits

* **Insolvency Protection:** RUJI Perps eliminates insolvency risks by ensuring that all positions are fully backed by locked liquidity. This is particularly important during volatile market conditions, where traditional platforms struggle to provide enough liquidity to cover profits.
* **Real yield for LPs:** RUJI Perps provides real yield for liquidity providers with multiple risk-adjusted options. LPs provide single sided deposits (i.e. provide liquidity in a single asset such as BTC) and earn trading fees in exchange for taking on counter trading risk. The ability to provide single-sided liquidity means LPs are not exposed to any impermanent loss, but LPs do take on counter trading risk, i.e. the more traders lose, the more LPs win, and vice versa.
* **Sophisticated Trading Features:** RUJI Perps provides features such as stop losses, take profits and limit orders. Traders can open multiple isolated positions, both long and short, on the same market. This feature allows for strategic hedging during volatile periods, as well as the flexibility to use different levels of leverage for each position.
* **Market Stability Incentives:** To ensure system robustness and protect liquidity providers, RUJI Perps employs a delta neutrality fee to incentivize balanced positions and delta neutrality caps to prevent new positions from significantly unbalancing markets. The delta neutrality fund rewards traders, especially arbitrageurs, who contribute to market stability by keeping the system balanced. It collects lump-sum payments whenever trader actions exacerbate unbalanced markets though open, update, and close actions, and distributes rewards to traders who bring markets back towards a balanced, delta-neutral state.

### Fees & Fee Sharing with THORChain Base Layer

RUJI Perps generates revenue from various fee streams, which are shared between liquidity providers and the protocol (these fees may be adjusted from time to time on a general or per market basis to ensure protocol robustness):

* **Trading Fees**: Broken up into two components: (i) a percentage of the notional size, 0.1% by default; and (ii) a percentage of the counter collateral (funds borrowed from LPs for potential gains), 0.1% by default.
  * 70% goes to LPs, and 30% to the protocol.
* **Borrow Fees**: Dynamically adjusted based on supply and demand.
  * 70% to LPs, 30% to the protocol.
* **Delta Neutrality Fees**: This is primarily P2P, but anywhere between 5%-25% (depending on liquidity of the underlying spot market) is taken as a tax into the general fee bucket.
  * 70% to LPs, 30% to the protocol.
* **Crank Fees**: Collected by trading bots. These bots are run by the Levana team, but can also be run independently by community members to operate the protocol in exchange for crank fee rewards.
  * 100% to Crank operators.
* **Funding Fees**: Funding payments are collected but are completely peer to peer.
  * 100% to traders.

All protocol fees collected by RUJI Perps are split evenly between RUJI and RUNE stakers, ensuring strong integration with the broader THORChain ecosystem.

For users, all of these fees and/or earnings are factored into your PnL in real time.

### How does providing liquidity work?

On the Earn page, you can provide liquidity to the RUJI Perps protocol and earn yield for doing so.

Deposits are used by traders as counter-collateral for their positions. In return, you receive LP or xLP tokens that generate yield which comes from fees paid by traders. These are the APRs you see displayed for each liquidity pool.

Deposits are not risk-free. When traders win, counter-collateral is removed from the liquidity pool and LP/xLP tokens lose value. But when traders lose, your LP/xLP tokens increase in value. This is referred to as *impairment*.

LP tokens that are not currently locked in trader positions may be redeemed immediately for the liquidity that you provided.

Redeeming xLP tokens takes 45 days from when you submit the request—these tokens unlock linearly over this time period, and you receive the APR from LP tokens on the full amount.

Once you have accrued yield, you may withdraw it at any time directly to your wallet or reinvest it to earn additional yield.

For more information, please check: [Position size versus locked collateral](/core-products/ruji-perps/position-size-versus-locked-collateral)

### Understanding Data Sources

RUJI Perps calculates price exposure by using external spot prices exclusively. These spot prices are provided by the underlying liquidity pools on THORChain, ensuring we always have the most accurate and up to date price information available on-chain.

### Status

* RUJI Perps v1, built by the Levana team, is live [here](https://rujira.network/perps/trade/BTC_USDC) as an isolated product. This version will be discontinued and replaced by a peer-to-peer orderbook model fully integrated with the rest of the ecosystem.

### FAQ

* [RUJI Perps FAQ](/how-it-works/frequently-asked-questions/ruji-perps-perps-dex)


# Position size versus locked collateral

One of the defining features of RUJI Perps is *locked collateral*. This is the mechanism by which we ensure that each position's potential gains are well funded at all times. This can lead to some confusion about two similar but distinct topics: position size and locked collateral. We'll try to clarify that here.

> NOTE: This document will intentionally use simplifying assumptions to make the math a bit easier, such as describing a collateral-is-quote market. If you try the same numbers in a collateral-is-base market—which includes any USD-denominated market—the numbers will be slightly different. But that shouldn't impact the intuition discussed here.

### What is position size? <a href="#what-is-position-size" id="what-is-position-size"></a>

Position size represents how much *exposure to price movement* your position has. It is given by your deposit collateral times leverage. For example, if you deposit $500 in a long position and use 3x leverage, your exposure is equivalent to buying $1,500 of the asset on the spot market. If the price goes up by 10%, you will make $150 in profit, not $50.

> NOTE: This also explains why all leveraged positions have a liquidation price. In the above example, if the price went down by 50%, the position would have lost $750, which is more than the $500 the trader deposited initially. Therefore, we need a liquidation price that stops a position from losing more money than the deposit collateral. In this case, that would be a 33% price decrease. This also explains why the more heavily leveraged a position, the sooner you'll be liquidated if the price moves against you.

Position size is what determines open interest and net interest in the platform:

* Long open interest is the sum of the position sizes of all longs.
* Short open interest is the sum of the position sizes of all shorts.
* Total open interest is the sum of long and short open interest.
* Net open interest is the *difference* between long and short open interest.

### What is locked collateral? <a href="#what-is-locked-collateral" id="what-is-locked-collateral"></a>

When you open a position, you specify a take profit price. Internally, the system computes how much collateral to borrow from the liquidity pools. This becomes your *locked collateral*, also known as counter side collateral, and represents the maximum profits you can achieve on this position.

Let's use the example above again. You have a long with a $1,500 position size. The current price is $10. You set a take profit price of $12, or a 20% price increase. That means your maximum profit is `$1,500 * 20% == $300`. The protocol needs to borrow those $300 from the liquidity pool and lock it into your position.

By contrast, if you reduce your take profit price from $12 to $11, the protocol only needs to lock collateral for `$1,500 * 10% == $150`. Notice that the position size remains the same in both cases, but the locked collateral is significantly different.

As you can see in this example, the closer the take profit price is to the entry price, the smaller the locked liquidity. This is one of the reasons we recommend traders think carefully about the take profit prices they want. Not only is this a risk mitigation mechanism, but it is also a cost savings. Reducing your locked liquidity will reduce both your trading fees and your borrow fees.

### Price risk to liquidity providers <a href="#price-risk-to-liquidity-providers" id="price-risk-to-liquidity-providers"></a>

Let's continue with the above example. A trader opens a long with the parameters:

| Parameter          | Value |
| ------------------ | ----- |
| Deposit collateral | $500  |
| Leverage           | 3x    |
| Entry price        | $10   |
| Take profit price  | $12   |

The system will derive the following from these parameters:

| Derived parameter    | Value  |
| -------------------- | ------ |
| Trader position size | $1,500 |
| Locked collateral    | $300   |

Any gain the trader takes on the position will be withdrawn from the locked collateral, and vice-versa. Meaning, if the price moves up to $11:

* The trader has experienced a 10% increase via price exposure
* The trader will have profits of `$1,500 * 10% == $150`
* The liquidity pool will lose those $150 to the trader
  * Caveat: as we discuss below, we strive to keep the protocol balanced, which will protect liquidity providers from these losses by ensuring for every loss on a long position, they will experience an equivalent gain on a short position, and vice versa.

Similarly, if the price *decreases* by 10% instead, the trader will lose $150 to the pool. This is equivalent to saying that, every time a trader opens a long, it's as if the liquidity providers have opened a short of the same position size. This leads to one more concept: counter-side leverage. In our example, the liquidity pool opened a $1,500 short position using $300 of collateral. This means that the pool's counter-side leverage on this position is 5x, versus the trader's 3x leverage. From the liquidity pool's perspective:

| LP parameter          | Value  |
| --------------------- | ------ |
| Locked collateral     | $300   |
| Counter side leverage | 5x     |
| Position size         | $1,500 |

### Why net open interest matters <a href="#why-net-open-interest-matters" id="why-net-open-interest-matters"></a>

The reason why net open interest is so important to the protocol is because it represents exposure to price risk for liquidity providers. If the protocol has too much long interest, for example, liquidity providers are being forced to open up more short positions than long positions. If the actual price goes up, liquidity providers will lose funds to traders through *impairment*. It's true that if the price moves down instead, liquidity providers will instead make money through impairment. But we strive to insulate providers from risk. Therefore, our goal is to keep longs and shorts balanced, also known as:

* 0 net notional
* Delta neutral

The mechanisms we use for this are incentives via funding rate payments and delta neutrality fees, which provide a profit motive for the implementation of [cash-and-carry arbitrage](https://www.investopedia.com/terms/c/cash-and-carry-arbitrage.asp), also known as [basis trading](https://www.investopedia.com/terms/b/basis-trading.asp).

### Collateral lock-ups, risks and rewards <a href="#collateral-lock-ups-risks-and-rewards" id="collateral-lock-ups-risks-and-rewards"></a>

The inherent risk liquidity providers take on in this system is unbalanced price exposure. While—as just discussed—the protocol strives to minimize that risk, it cannot guarantee risk will be absent. And furthermore, in extreme market conditions (called a market meltdown or meltup), this risk is expected to be very high. In such a scenario, any liquidity in the pool is at risk of impairment, up to loss of 100% of their funds.

Liquidity providers can choose their level of risk, and receive commensurate rewards as a result. Therefore, there are two mechanisms for providing liquidity: LP tokens with no lock-up time, and xLP tokens with a 45 day lock-up window. LP tokens can be immediately withdrawn, provided that enough liquidity is in the system. xLP holders take on a higher degree of risk, and therefore receive higher rewards in terms of receiving a higher proportion of trade and borrow fees.

But to be clear, both groups are at risk of significant impairment. The protocol uses a dynamic borrow fee rate detection mechanism within the protocol to allow supply-and-demand forces to discover a fair market rate for this risk. In summary is: for assuming the risk of extreme market movements, LP and xLP holders are rewarded with high APRs on their deposits.


# RUJI Money Market

RUJI Money Market is a decentralized marketplace connecting lenders and borrowers of crypto assets. It enables lenders to earn interest on their tokens, and borrowers to secure loans against their crypto collateral.

### Key Features

* **Lending:** Generate passive returns by lending out your tokens, with a fairly low risk profile (all loans are overcollateralized though bad debt could still occur in case of smart contract exploit or extreme events). Lenders supply assets in exchange for a vault receipt token, which accrues interest over time. The receipt token is transferable and can be used in other dApps, or redeemed back for the original asset plus accrued interest. Deposits can be withdrawn at any time, as long as asset utilization remains under 100%.
* **Borrowing:** Unlock liquidity in the form of overcollateralized loans, without selling your crypto assets. Borrowing is permissionless; no credit checks or lengthy applications required. No minimum  or maximum loan duration, you can partially repay or fully close your position at any time.
* **Overcollateralized:** All loans are overcollateralized, meaning that at a maximum (illustrative) 70% Loan-To-Value ratio (LTV), there is always >$1 of collateral backing each $0.70 worth of debt.
* **Cross-marginated:** Under the hood, each borrowing position exists in a [Credit Account](https://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-ghost-credit/README.md) in which you can deposit any supported collateral (e.g. regular tokens or LP tokens). Each collateral type has a corresponding collateral ratio, which is a risk-adjusting factor applied to your collateral value to define how much you can borrow against it.
  * For example, BTC has a collateral ratio of 70% (meaning you can borrow up to $70 for every $100 worth of BTC), and DOGE has a collateral ratio of 60%. If you have $100 worth of BTC and $100 worth of DOGE in your Credit Account, your total Adjusted Collateral Value will be: $100\*70% + $100\*60% = $130, which will be the maximum amount you are allowed to borrow, corresponding to an Adjusted LTV of 100%. If the value of your collateral changes and your Adjusted LTV goes above 100%, your position will start to get liquidated to get back to a safe level and protect system solvency.
* **Custom Liquidation Preferences:** When using multiple collateral types inside a Credit Account, users can define their own liquidation preferences, which are rules applied when a liquidation is processed. Taking the above example, the user can specify that he wants all his DOGE to be liquidated first before his BTC can be touched.
* **Variable Interest Rate:** Borrowers are charged variable interest rates based on the utilization rate, which is a function of supply and demand for a given asset (utilization = total\_borrowed / total\_supplied). The interest rate curve (available in the UI for each market) typically starts at 0% borrowing APR when utilization rate is 0%, and increases linearly toward 5% APR when utilization rate reaches 85%. Beyond that point, the borrowing APR increases sharply towards 100% when utilization rate reaches 100%. This dynamic incentivizes new suppliers when markets are hot, while encouraging borrowers to unwind their positions until the interest rate finds an equilibrium.
* **Liquidations via RUJI Trade orderbook**: If a debt position exceeds its safe Adjusted LTV limit (either because of the value of the collateral dropping, or the value of the debt increasing due to interest), a portion of the collateral becomes available for liquidation to bring the position back to a safe level. The liquidated collateral is sold with a market order on RUJI Trade orderbook and can be acquired at a discount to market value via Rujira's [Liquidations](/core-products/ruji-liquidations) platform, using Tracking Orders.
* **Collateral Swap:** Borrowers are able to swap their collateral from one token to another without needing to repay their loan. For example, if you borrowed USDC using BTC as collateral, you can swap your BTC for ETH directly, without repaying the loan first.

### Benefits

* **Low-Risk Return:** Earn interest on your crypto assets by lending them out with a fairly low repayment risk (overcollateralized loans) and no exposure to Impermanent Loss (single-sided deposit, as opposed to deposits in the AMM pools which comprise two assets and are subject to IL risk).
* **Permissionless Borrowing:** Easily take a loan against your crypto assets, whether it is to speculate on the markets, or to pay for real-life expenses.
* **Native Assets Support:** Earn interest or borrow against all native assets connected to THORChain (including BTC, ETH, SOL, XRP, BCH, LTC, DOGE, TRX, etc.), no need for bridged or wrapped versions.
* **Fair Liquidations**: In case of adverse price movements for borrowers, liquidations are processed via market orders on RUJI Trade orderbook, allowing everyone to bid on at-risk collateral by placing Tracking Orders in the orderbook and using Rujira's Liquidations platform to make data-informed decisions. This creates a competitive market for liquidations, which tend to result in lower liquidation penalties for borrowers vs. traditional money markets where the liquidation discount is fixed.
* **Stay in Control:** With custom liquidation preferences, borrowers can define in which order their assets should be liquidated in case of adverse price movements. For example, this allows to preserve your BTC as last-resort collateral, as opposed to most borrowing platforms that would liquidate your most valuable collateral first.
* **Efficient Integration**: Fully integrated into Rujira's product suite, RUJI Money Market enables leverage features in core apps such as spot margin trading on RUJI Trade and leveraged market making on RUJI AMM. This leads to increased borrowing volumes, increased liquidity on the orderbook DEX, higher spot trading volumes and more liquidation opportunities.
* **Intuitive UX**: Simplifies the process of lending and borrowing assets.

### Fees & Fee Sharing with THORChain Base Layer

* Borrowers are charged an interest rate (borrowing APR) which is updated each block based on the utilization rate of the borrowed asset compared to the total supply available for lending.
* 90% of the interest charged goes to lenders and 10% is kept as protocol revenue, which is shared 50/50 with THORChain Base Layer.

### Status

* Lending vaults are live [here](https://rujira.network/lend).
* CDP Loans are available [here](https://rujira.network/borrow).

### FAQ

* [RUJI Money Market FAQ](/how-it-works/frequently-asked-questions/ruji-money-market-lending-and-borrowing)


# RUJI Liquidations

RUJI Liquidations is the world’s first public marketplace for bidding on at-risk collateral, enabling users to liquidate assets used as collateral on RUJI Money Market with ease - no bots, no code. By participating in a Dutch auction (via tracking orders on RUJI Trade orderbook), users can acquire liquidated collateral at up to a 30% discount while protecting the solvency of Rujira lending vaults.

### Key Features

* **Liquidations Marketplace:** A public marketplace for purchasing liquidated collateral at a discount through Dutch auctions with instant settlement. Under the hood, every liquidated collateral is sold via a market order on [RUJI Trade](/core-products/ruji-trade) orderbook DEX, and RUJI Liquidations provides a user-friendly interface allowing anyone to catch the wick by placing Tracking Orders at a discount to market price.
* **Queue-Based System:** Liquidations are not prioritized by speed but rather by the discount rate, filling bids from the smallest discount to the biggest. This helps to find an optimal discount rate and prevents immediate selling and damage to the market by MEV bot operators.
* **Ecosystem Solvency:** Secure the Rujira ecosystem solvency for all leveraged products, including CDP loans, and debt used for spot margin trading and leveraged market making.
* **Analytics (pending):** Liquidation analytics are planned across RUJI Liquidations markets, enabling users to craft bidding strategies driven by concrete market insights.

### Benefits

* **Mitigate Flaws in Standard Liquidation Mechanisms:** The typical liquidation mechanism for DeFi protocols functions on a first-come-first-served basis and at a fixed liquidation discount. Consequently, liquidations are based on the speed of execution, leaving this market to a few highly efficient, well-capitalized MEV bots that preclude most users from participating. The fixed discount also results in liquidations often costing more to borrowers than they would in an efficient market. RUJI Liquidations changes this.
* **Democratizes Access to Liquidations:** The RUJI Liquidations system revolutionizes DeFi liquidations by allowing anyone to bid on discounted collateral. Users place bids (tracking orders at a discount to oracle price) and bids at smaller discounts take priority, creating a fair system that discourages arbitrage and market dumping.
* **Reduces Cost of Liquidation for Borrowers:** RUJI Liquidations creates a competitive market for liquidations and encourages bidders to reduce their bid discount in order to increase their chances of capturing the liquidated collateral, which results in a less costly liquidation process for borrowers. RUJI Liquidations (formerly ORCA) had a TVL of $200m+ at its peak, prior to Terra Classic's collapse, that was being used to liquidate collateral on Anchor protocol with most of the liquidations happening within the 2-5% range.
* **Buy Assets at the Local Bottom:** RUJI Liquidations effectively enables users to buy local bottoms and sell local tops in their favorite assets. Even at a 0% discount, it’s a compelling opportunity.
* **Reduces Market Volatility to the Downside:** Most liquidation bots are arbitrage bots, they buy discounted liquidated collateral and sell it at market price within the same block, pocketing the liquidation discount in a risk-free transaction. This behavior leads to liquidation cascades, a feedback loop where selling pressure from the bots pushes prices further down, triggering more liquidations, which causes more sell pressure, and so on. RUJI Liquidations mitigates this immediate selling and damage to the market by MEV bots.

### Fees & Fee Sharing with THORChain Base Layer

* RUJI Liquidations charges two types of fees:
  * Liquidation fee: 1.0% taken on the repaid debt.
  * Liquidator fee: 0.5% taken on the repaid debt.
* The standard 50/50 revenue share with TC Base Layer applies to the Liquidation fees collected by RUJI Liquidations.
* The Liquidator fees are going to whoever triggers the liquidation first, incentivising off-chain solvers to find the liquidation routes that would often be impractical or impossible to calculate on-chain, whilst still internalising the liquidation volume across the Rujira Ecosystem.

### Status

* Liquidations are live here [RUJI Trade](https://rujira.network/liquidate) (analytics to inform bidding strategies will be added overtime).

### FAQ

* [RUJI Liquidations FAQ](/how-it-works/frequently-asked-questions/ruji-liquidations-bid-on-liquidated-collateral)


# RUJI Index

RUJI Index substantially simplifies managing your diverse crypto portfolio.

Instead of picking individual coins, you can hold ready-made index tokens that track a whole basket of assets. Behind the scenes, smart contract vaults keep everything fully backed and automatically balanced.

You can mint, redeem, or trade these index tokens anytime, without asking anyone for permission. All available indices are listed on our [Index](https://rujira.network/index) page.

### Key Features

* **Fully Decentralized, On-Chain Indices**: RUJI Index products are non-custodial and operate entirely on-chain. With no central intermediary, all asset management and trading logic is governed by smart contracts.
* **Tokenized Asset Baskets**: Each index represents a bundled basket of assets. Minting an index token generates a single receipt token that is composable and can be used in other DeFi protocols, simplifying liquidity and collateral management.
* **100% backed at all times**: At all times, every index is backed by its full complement of underlying assets stored in the smart contract vault. This model unlocks a wide range of DeFi applications, as each index token consistently reflects the combined value of its underlying assets.
* **No deposit & withdrawal lock-up**: The underlying assets are redeemable at all times (subject to orderbook liquidity), with no deposit or withdrawal lock-up period. Additionally, some indexes have their own order book on [RUJI Trade](https://rujira.network/trade/NAMI/ETH.USDC), where the receipt token can be bought and sold without requiring minting or redeeming. This enables efficient arbitrage, helping ensure the index token consistently trades near the combined value of its underlying assets.
* **Automated Rebalancing Engine:** For rebalancing indexes, the smart contract continuously adjusts the assets within the index to maintain predefined target weights. Each rebalance takes price impact and slippage into account, selling assets that have exceeded their target allocation and buying those that have fallen below. Fixed indexes do not rebalance, letting winners run and losers lose.

### Benefits

* **One-click diversification**: Access a diversified portfolio with a single action. By minting index tokens you gain broad market coverage and simplify your portfolio management.
* **Efficient rebalancing**: Since the index automatically rebalances according to pre-set parameters, you don’t need to monitor the market 24/7. The protocol minimizes slippage and price impact by executing trades strategically, helping maintain target allocations over time.
* **Permissionless minting & redemption**: Anyone can mint or redeem index tokens at any time. This open access minimizes price discrepancies between the index token and its underlying assets.
* **Cross-Chain Accessibility**: Thanks to THORChain's architecture, you can access RUJI Index from any supported network. Whether you’re on Bitcoin, an EVM chain, a Cosmos chain or any other chain integrated with THORChain, the index protocol remains interoperable across all supported ecosystems.

### Fees & Fee Sharing with THORChain Base Layer

* **RUJI Index:** There is no mint fee, only a redemption fee of 1.0% as well as an investment fee of 1.0% p.a., both accruing to RUJI stakers.
* **Rujira & THORChain:** RUJI Indexes are products built on top of Rujira's Orderbook DEX. Hence, every mint, redemption and rebalance is subject to the standard Orderbook DEX fee, accruing value to both RUJI stakers and THORChain Base Layer.

### Status

* RUJI Index is live [here](https://rujira.network/index).

### FAQ

* [RUJI Index FAQ](/how-it-works/frequently-asked-questions/ruji-index-crypto-indices)

***

### Advanced Documentation

#### Issuance and Redemption

When issuing & redeeming an index asset, the protocol handles calculations, swaps, mint/burning as well as maintaining all the underlying assets inside a vault.

A high-level asset / user flow is illustrated below.

**Issuing an index token**

The contract issues an asset in six steps:

1. Contract receives an amount of base asset from the user (RUNE or USDC, depending on the index).
2. Contract determines how many units of the base asset are used to buy each allocation based on stored index asset weights.
3. Contract initiates the swaps on the swap venue (RUJI Trade).
4. Contract receives swap output and adds it to the vault.
5. Contract mints the index receipt token based on received asset amounts.
6. Contract sends the index receipt token to the user.

**Redeeming an index token**

Redemption of an index token is done in five steps:

1. Contract receives an amount of index tokens from the user.
2. Contract determines how much of each underlying allocation is redeemed based on the total amount of underlying assets and total issued index tokens.
3. If needed, the contract initiates the swaps on the swap venue (RUJI Trade) to get the base asset.
4. Contract confirms the swap outputs & burns the index token.
5. User receives the base asset (RUNE or USDC, depending on the index).

#### Rebalancing

There are currently two different types of index implementation, due to some assets having oracle prices (secured assets), while some don't (assets native to Rujira).

**NAV indexes** are auto-rebalancing indexes, but require all underlying assets to have an oracle price.

**Fixed indexes** are non-auto-rebalancing indexes with a fixed unit ratio between the assets. This implementation does not require oracles to be available for each asset.

***

#### NAV Index Rebalancing <a href="#nav-index-rebalancing" id="nav-index-rebalancing"></a>

The smart contract for each NAV index stores asset target weights. During each contract crank (e.g. minting), the index is rebalanced back towards the target weights, if the asset weight is at least X% away from the target weights, subject to liquidity. X is a parameter set in the contract.

***

#### Fixed Unit Index Rebalancing <a href="#fixed-unit-index-rebalancing" id="fixed-unit-index-rebalancing"></a>

Fixed unit indexes do not auto-rebalance. However, they can be rebalanced manually including for the following reasons:

* Change the asset composition (i.e. add or remove an asset to/from the index).
* Remove an asset in an emergency, e.g. in case of a protocol exploit or security issue.
* Update asset weights to align with orderbook liquidity, in case the liquidity to index TVL share ratio changes drastically on one asset.

{% hint style="info" %}
**A note on rebalancing**

Auto-rebalancing keeps the index from being overweight in a single asset, but it also buys more of the losers and trims the winners. In crypto’s volatile markets, RUJI NAV Index is designed to let winners run while limiting exposure to losers. That’s why the NAV indexes use a rebalance buffer, avoiding instant rebalancing.
{% endhint %}


# RJI

{% hint style="info" %}
RJI live via <https://rujira.network/index/rji>.
{% endhint %}

The Rujira Index (RJI) is a basket of assets **representing the Rujira & THORChain ecosystem**. In order to ensure prime user experience and index performance, especially as the ecosystem grows, we have developed an asset framework as a base guideline for RJI.

### Which assets are eligible to be included in RJI? <a href="#which-assets-are-eligible-to-be-included-in-rji" id="which-assets-are-eligible-to-be-included-in-rji"></a>

There are **four eligibility criteria** that assets shall fulfill prior to being added to RJI. Namely **qualitative** requirements, **liquidity** requirements, **safety** requirements & they have to be **based on Rujira / THORChain**.

#### Qualitative <a href="#qualitative" id="qualitative"></a>

In order to be considered for the index the team behind the token has to be trusted & actively working on their vision. Further, it should have a clear value proposition and no signs of ill intent.

* Team has a proven track record building & maintaining products
* Project has a valid use case
* Token has valid economics / value capture mechanism
* No red flags
* Ongoing development (updates in past 3 months)

#### Liquidity <a href="#liquidity" id="liquidity"></a>

Assets are selected for strong liquidity, ensuring easy entry and exit with minimal slippage when minting, redeeming, or rebalancing. Clear token release schedules further prevent unexpected shifts in liquidity and supply.

* There must be enough liquidity on Rujira.
* The token release schedule must be predictable.

#### Safety <a href="#safety" id="safety"></a>

While code audits are often mostly a vanity metric, undergoing code reviews from professionals does make code less prone to certain attacks. Therefore, for newly launched projects that secure value in any form, it shall be a requirement to undergo reviews by an auditor.

* Code base must have undergone auditing
* Proven track record for safety incident response

#### Based on Rujira / THORChain <a href="#based-on-rujira" id="based-on-rujira"></a>

Only projects deployed on Rujira / THORChain are considered for RJI.

***

### Asset weights <a href="#asset-weights" id="asset-weights"></a>

RJI being a fixed unit index, the weights change constantly and are not automatically rebalanced. The initial weights on index creation were based on liquidity, market cap and growth potential. **RJI currently consists of:**

* **AUTO**
* **LQDY**
* **RUJI**
* **RUNE**
* **TCY**

The exact share of the total index AUM by each asset is fluctuating and can be found at <https://rujira.network/index/rji>

#### Risks <a href="#risks" id="risks"></a>

Key risks for RJI includes:

* Asset risk of all assets in the index.
* Smart contract risk of RUJI Fixed Index contract (audited).


# yRUNE

{% hint style="info" %}
yRUNE live via <https://rujira.network/index/yrune>.
{% endhint %}

Yield Bearing RUNE (yRUNE) is an **auto-rebalancing basket of RUNE and TCY**. yRUNE is a liquid asset that captures fees from THORChain system income (via staked TCY) while also providing exposure to the RUNE price.

### How are the weights between RUNE and TCY determined? <a href="#how-are-the-weights-between-rune-and-tcy-determined" id="how-are-the-weights-between-rune-and-tcy-determined"></a>

The weights of RUNE and TCY are set to maximize returns captured from:

* **TCY Yield (THORChain System income):** TCY is a unique asset, as it captures 10% of THORChain's system income. Our contract is whitelisted to receive these staking rewards, enabling yRUNE to fully benefit from the TCY component of the index.
* **RUNE / TCY mean reversion:** Due to price fluctuations, particularly for TCY caused by shallow liquidity, yRUNE captures volatility by automatically rebalancing towards the "cheaper" asset during price swings. This is achieved by keeping yRUNE close to a predefined target ratio between RUNE and TCY.
* **Liquidity:** Safeguards are implemented in the contract to ensure that rebalancing minimizes price impact and slippage.

Taking these three factors into account, initial weights are set to **80% RUNE : 20% TCY**. The contracts will initiate rebalancing if the weight is at least 1 percentage point off its target weight.

Current & target weights can be seen on the RUJIRA UI at <https://rujira.network/index/yrune>.

***

### Rebalancing <a href="#rebalancing" id="rebalancing"></a>

Rebalancing occurs automatically with each contract crank (at least once per minute). If insufficient liquidity prevents executing a rebalance, the contract will attempt again later to minimize price impact and slippage.

### Risks <a href="#risks" id="risks"></a>

Key risks for yRUNE include:

* Asset risk of RUNE and TCY.
* Smart contract risk of RUJI Nav Index contract (audited).
* Rebalancing/Trading risk: The automated rebalancing algorithm aims to maximise returns from trading, but those are not guaranteed and may depend on other factors such as market conditions, liquidity & more. Safeguards are in place to minimize this risk.

<br>


# yTCY

{% hint style="info" %}
yTCY live via <https://rujira.network/index/ytcy>.
{% endhint %}

Similar to yRUNE, Yield Bearing TCY (yTCY) is an **auto-rebalancing basket of TCY and RUNE**.

### How are the weights between TCY and RUNE determined? <a href="#how-are-the-weights-between-tcy-and-rune-determined" id="how-are-the-weights-between-tcy-and-rune-determined"></a>

The weights of RUNE and TCY are set to maximize returns captured from:

* **TCY Yield (THORChain System income):** TCY is a unique asset, as it captures 10% of THORChain's system income. Our contract is whitelisted to receive these staking rewards, enabling yTCY to fully benefit from the TCY component of the index.
* **RUNE / TCY mean reversion:** Due to price fluctuations, particularly for TCY caused by shallow liquidity, yRUNE captures volatility by automatically rebalancing towards the "cheaper" asset during price swings. This is achieved by keeping yTCY close to a predefined target ratio between RUNE and TCY.
* **Liquidity:** Safeguards are implemented in the contract to ensure that rebalancing minimizes price impact and slippage.

Taking these three factors into account, initial weights are set to **80% TCY : 20% RUNE**. The contracts will initiate rebalancing if the weight is at least 1 percentage point off its target weight.

Current & target weights can be seen on the RUJIRA UI at <https://rujira.network/index/yTCY>.

***

### Rebalancing <a href="#rebalancing" id="rebalancing"></a>

Rebalancing occurs automatically with each contract crank (at least once per minute). If insufficient liquidity prevents executing a rebalance, the contract will attempt again later to minimize price impact and slippage.

### Risks <a href="#risks" id="risks"></a>

Key risks for yTCY include:

* Asset risk of RUNE and TCY.
* Smart contract risk of RUJI Nav Index contract (audited).
* Rebalancing/Trading risk: The automated rebalancing algorithm aims to maximise returns from trading, but those are not guaranteed and may depend on other factors such as market conditions, liquidity & more. Safeguards are in place to minimize this risk.

<br>


# BIG5

Coming Soon


# RUJI Launchpad

RUJI Launchpad is where capital connects with ideas and everyone is a venture capitalist.

Users gain early access to promising protocols and opportunities to benefit from their favorite projects that raise capital for expansion and development.&#x20;

RUJI Launchpad differs from typical launchpads by providing a comprehensive suite of tools for projects at all stages, from bootstrapping to token generation events (TGE) and late-stage fundraising.

### Key Features

* **Flexible Raising Options:** Choose a fundraising mechanism suited to your needs and strategy from a range of options including fixed price first-come-first-served sales (whitelist optional), fair market auctions and bonded token offers.
* **Multi-chain Access:** Support for tokens minted on various blockchains, with seamless bridging for cross-chain sales or purchases.
* **Permissionless Self Service:** Launch a sale without restrictions, with self-service tools and technical support available.
* **Automated Ecosystem Integration:** Effortlessly create trading pairs, provide liquidity, and manage tokenomics, complete with vesting schedules and cliffs.
* **Easy Token Management:** Set out tokenomics and automate distribution as part of the process.

### Benefits

* **For Buyers:** Back the next unicorn with ease using a streamlined user experience and a marketplace designed to simplify investment discovery and manage your purchases seamlessly.
* **For Sellers:** RUJI Launchpad user interface enables project teams to create sales, mint tokens, establish trading pairs, and provide liquidity all in one place. An effortless fundraising process enables builders to focus on what they do best: building.
* **Mint Anywhere, Raise on Rujira:** It’s easy to bridge over and raise capital, whichever chain you call home.
* **Raise, Mint, Distribute in One Place:** Our tools help you speed up. Streamline your capital raising, minting, and distribution processes and stay focused on development.
* **Repeat Capitalisation:** Raise the funds you need, when you need them. Project requirements change and we have tools for every stage of your development.

### Fees & Fee Sharing with THORChain Base Layer

* **FCFS and Auction (initial token offerings):**
  * Token seller pays a commission of 5% on the proceeds from a sale.
  * Buyers pay a 0.5% commission on the withdrawal of tokens purchased.
  * Sellers pay a 0.5% commission on claim of LP tokens created during a sale.
* **Bonds (follow-on offerings):**
  * Token seller pays a commission of 0.5% on the proceeds from a sale.
  * bTOKEN holders pay a 0.35% commission on the redemption of tokens after the bond reaches maturity.
* The standard 50/50 revenue share with TC Base Layer applies to all the fees collected by RUJI Launchpad.

### Status

* Not live yet.

### FAQ

* [RUJI Launchpad FAQ](/how-it-works/frequently-asked-questions/ruji-launchpad-token-launchpad)


# bRUNE (Liquid Bonded RUNE)

bRUNE allows users to access THORChain node bonding through a liquid staking token, bRUNE. Instead of bonding RUNE directly to a node, users deposit RUNE into the bRUNE contract and receive bRUNE in return. Each bRUNE is always backed by at least 1 RUNE in the contract + unclaimed accrued yield. The contract bonds RUNE to a diversified set of THORChain nodes on behalf of users and distributes the resulting bonding yield proportionally to bRUNE stakers.

### Key Features

* **Simple access to RUNE yield:** Bonding is the most profitable way to earn yield on RUNE, but traditionally requires direct coordination with node operators and minimum size commitment. bRUNE abstracts this process away and allows users to stake any amount of RUNE in under a minute and earn a share of THORChain revenue.
* **Instant liquidity in and out:** Bonding traditionally exposes users to long unbonding periods, with deposits and withdrawals depending on Nodes churning out, which can take time and comes at a cost for Node Operators. With bRUNE, users can enter and exit at any time through RUJI Trade orderbook.
* **Risk diversification:** bRUNE automatically allocates RUNE across a wide number of nodes, mitigating the risk of loss of accrued rewards due to slashing in case of staking with a single node.
* **Fully integrated with Rujira stack:** Under the hood, bRUNE is implemented as an AMM strategy and fully integrated with RUJI Trade. Deposits are executed as buy orders for bRUNE, while withdrawals are executed as sell orders back into RUNE. Pricing is determined by the utilization of bonded versus liquid RUNE in the contract and available liquidity in the bRUNE/RUNE pair.

### Node Allocation

bRUNE bonds RUNE across a set of whitelisted THORChain nodes. During the initial testing phase, the whitelist is managed by Rujira. Over time, this is expected to transition to a permissionless system where nodes can self-register. Per ADR20, RUNE bonded by bRUNE should not exceed 10% of the Active Bond.

Before allocating RUNE, bRUNE checks each whitelisted node's current THORChain node state and preflight status (i.e. whether a node is ready to become bondable/active). Active nodes can receive bonds up to their configured `max_bond` caps. Standby nodes only receive new allocation if preflight indicates they are ready or if the only blocker is the THORChain minimum bond and bRUNE's allocation would clear that threshold.

RUNE deposits are distributed across eligible whitelisted nodes with a target of equal allocation. Allocation is adjusted based on the node operator fee:

* Nodes charging between 0% and the `min_node_fee` receive equal allocation.
* Nodes charging above the `min_node_fee` receive progressively lower allocation.

If a standby node later reveals a preflight failure for a reason other than minimum bond, bRUNE will attempt to unbond from that node and temporarily exclude it from new allocations. This temporary exclusion is controlled by the `quarantine` parameter, currently set at `259200` seconds (\~3 days). This gives a failing standby node the time of a churn to resolve operational preflight issues without causing bRUNE to repeatedly retry allocation in the meantime. During quarantine, the node remains on the whitelist but is treated as having zero bond capacity, so no new RUNE is allocated to it until the quarantine period expires and it passes eligibility checks again.

The `min_node_fee` parameter is currently set to 20%. Equal allocation to nodes at or below `min_node_fee` prevents over-allocation to very low-fee nodes and discourages a race to the bottom that could negatively affect node performance. Lower allocation to nodes above `min_node_fee` prevents over-allocation to high-fee nodes, which would reduce yield for bRUNE stakers and encourage a race to the top among node operators.

A `max_bond` parameter limits the amount of RUNE that bRUNE can allocate to any single node as a bond provider. The `max_bond` is currently set at 200k RUNE per node.

A separate `max_effective_bond` parameter avoids allocating to nodes above the maximum efficient bond (based on the THORChain `bondHardCap`, defined as the highest bond amount among the bottom two-thirds of active nodes). No additional rewards are earned past that limit, and further allocation would dilute existing bond providers.

You can see how RUNE bonded by the contract are currently allocated on [thorchain.net/nodes](https://thorchain.net/nodes), indicated by the little pink bRUNE icon <img src="/files/W1bUY6q606TBDQhHQpGN" alt="" data-size="line">.

### Utilization and Liquidity

To support instant withdrawals, the bRUNE contract does not bond 100% of deposited RUNE. Instead, it targets a utilization ratio (`target_utilization`), bonding only a portion of funds while keeping the remainder liquid.

* Current target utilization (testing): 85%
* Expected long-term target utilization: 90%

Because not all RUNE is bonded at all times, end-user yield is lower than direct node bonding, but users gain access to continuous liquidity and flexibility.

The contract rebalances toward `minted bRUNE * target_utilization`. If bonded RUNE is below target, available RUNE is allocated across eligible nodes. If bonded RUNE is above target, the contract can unbond from unsuitable nodes and may request churn-out from an active node when needed.

### Yield and Fees

Bonding rewards originate from THORChain system income earned by node operators. Gross yield is reduced by several factors before reaching bRUNE holders:

* Node operator commission
* bRUNE protocol fee
* Utilization ratio

Yield is distributed in RUNE to staked bRUNE holders. Users may choose to receive rewards as claimable RUNE or automatically compound them into additional staked bRUNE.

The bRUNE contract charges a 10% fee on bonding yield, collected as protocol revenue for Rujira.

Rewards are collected every time a node churns. To smooth APR, collected rewards are distributed over the `revenue_smear` period, currently set to 7 days.

#### Example

Assume we have an average 25% gross yield for node operators, an average node commission of 10%, and a 90% target utilization ratio for the bRUNE contract.

* From the 25% gross yield, 10% (= 2.5%) goes to nodes, leaving 22.5% yield to bonders.
* With a target utilization of 90%, the bRUNE contract receives 90% of those 22.5%, or \~20.3%.
* From those 20.3%, 10% (= \~2.0%) is collected by Rujira as protocol revenue.
* The remaining \~18.3% yield is distributed in RUNE among staked bRUNE. Assuming 100% of bRUNE is staked, that means end users receive a net yield of \~18.3%.

Actual yield per bRUNE may vary depending on:

* Average node commission: the higher, the lower the yield.
* Utilization rate: the higher, the higher the yield but the lower the available liquidity for instant withdrawal.
* Percentage of total bRUNE that is staked: the lower, the higher the yield for stakers.

### Deposits, Withdrawals, and Secondary Use

Depositing RUNE happens in one of two ways:

* When the bRUNE contract has capacity, RUNE is deposited directly to mint bRUNE at a 1:1 rate.
* When the contract is full, bRUNE can be acquired from other users.

In both cases, the deposit or purchase happens by executing an order in the [bRUNE/RUNE](https://rujira.network/trade/bRUNE/RUNE) pair on RUJI Trade orderbook. Direct minting is only available while the contract has both remaining mint capacity and eligible node bond capacity.

Once you hold bRUNE, it can be used in several ways:

* [Stake](https://rujira.network/stake/bRUNE) to earn the bonding yield, either paid out in RUNE or auto-compounded into more staked bRUNE.
* Provide liquidity in the bRUNE/RUNE pair using Custom Concentrated Liquidity positions.

Withdrawals are executed by selling bRUNE back into RUNE. The execution price depends on contract utilization and the available liquidity in the bRUNE/RUNE pair.

Withdrawal liquidity comes from liquid RUNE held by the contract and available bRUNE/RUNE market liquidity. Pending yield distribution is reserved before calculating the contract's bid-side liquidity.


# RUJI Options

RUJI Options is a decentralized options exchange designed to simplify options trading to anyone in the crypto space. RUJI Options offers a straightforward and intuitive user experience, free from convoluted tokenomics or pricing mechanics.

### Key Features

* **Decentralized Orderbook:** Options trading is facilitated via a decentralized orderbook that handles bids and asks for multiple strike prices within a given epoch.
* **Tokenized Options**: When a user's order is filled, the protocol generates a unique token representation, known as an "option denom," based on a combination of parameters such as the contract address, underlying asset, option type, strike price, and expiration timeframe.
* **European-style Options:** Options can only be exercised at expiration, providing greater flexibility and allowing investors to better manage their risk exposure without the need for early exercise or intervention.
* **Strike-Bound Liquidity**: An innovative liquidity mechanism ensuring ample liquidity across various strike prices.
* **Discretized Black-Scholes Pricing**: Options are priced using a discretized version of the industry standard Black-Scholes model, providing a transparent and well-understood pricing framework, optimized for liquidity concentration and transparency.
* **On-chain Historical Volatility**: Historical volatility is calculated and stored on-chain, serving as a key input for option pricing.
* **On-chain Pricing Engine**: Deployed fully on-chain for transparency and decentralization.

### Strike-Bound Liquidity

The mechanism leverages historical volatility data and confidence intervals to calculate strike prices, which are adjusted based on market conditions and risk tolerance. The calculation process involves the following steps:

1. **Historical Data Capture**: Captures periodic pricing data from an on-chain oracle.
2. **Historical Volatility Calculation:** Calculates the realized historical volatility over a specified time period.
3. **Confidence Intervals Selection:** Selects confidence intervals based on market conditions and risk tolerance, with the standard deviation serving as a proxy for risk.
4. **Strike Price Calculation**: Combines historical volatility and confidence intervals to calculate strike prices, using a standard normal distribution to generate a probabilistic range of potential strikes.

This process ensures accurate and responsive strike prices, reflecting actual market conditions.

### **Benefits**

* **Democratizes Access to Options:** Offers a censorship-resistant and transparent alternative to traditional centralized options markets, empowering users with unparalleled control and accessibility.
* **Fully Decentralized**: Enhances transparency (pricing and trading happen 100% on-chain) and reduces counterparty risk while ensuring users retain full custody of their assets throughout the trading process.
* **Efficiency**: Automatic strike prices selection reduces the need for manual orderbook management for liquidity providers, optimizing liquidity concentration and enhancing the trading experience.
* **Composability:** The use of unique "option denoms" standardizes the representation of options positions, enabling seamless integration with other protocols, and fostering the creation of new financial products.
* **Reselling into the Orderbook**: Users can resell their tokenized options back into the orderbook of the RUJI Options market. This innovative capability allows users to easily close their positions or take profits/losses without the need to find a counterparty outside the market, further enhancing the trading experience.

### Fees & Fee Sharing with THORChain Base Layer

* RUJI Options charges a 1.0% settlement fee on trading volumes.
* The standard 50/50 revenue share with TC Base Layer applies to all the fees collected by RUJI Options.

### Status

* Not live yet.


# RUJI Collections

RUJI Collections, operating under the Gojira brand & identity, is a sustainable NFT marketplace built on a revolutionary tech stack that enables higher creator earnings & platform revenue, fair & bot-free launches, mint customization, NFT-Fi, and RWA integrations.

Your portal to a colorful world of NFTs, Gojira reinvents NFT technology with its special auction mechanics, a new developer specification, and a unique focus on composability.

Gojira features deep integration with the rest of the Rujira Alliance.

### Key Features

* **Mint NFT collections with RUJI or USDC:** Spend RUJI to buy NFTs whose value and growth will directly align with the Rujira ecosystem. Collection creators also have the option to enable minting with USDC.
* **Efficient auction design:** NFTs are minted and traded on Gojira with a unique auction style optimized for blockchain performance, inspired by RUJI Ventures. Creators (or holders) will set their launch (or listing) date, and during the 48-hour auction period that follows, users can place bids to mint an NFT at their desired price and increase those bids as the auction progresses. Once the auction has closed, winners send a claim transaction to mint the NFT (or multiple) to their wallet, and any unsuccessful bids can be withdrawn. There are multiple auction types, including a descending price variant.
* **Accessible aftermarket sales:** Gojira provides extensive support for users to buy and sell tokens (NFTs) after they’re minted, and will generate additional revenue from a healthy trading market. Holders can choose to list their tokens for immediate sale or discover a fair price with a new auction, and buyers can make offers for any tokens (whether they are listed or not), which the holder can accept or reject.
* **Enabling real-world applications:** Gojira NFTs implement the GW721 specification, a superset of the Cosmos-standard CW721 with a greatly improved developer experience and unique features that allow creators to build endless new use-cases on top of our platform in a composable manner. Our first planned launch, Dive Domains (an on-chain nameservice built on Gojira NFTs), will showcase these capabilities.
* **Ecosystem content hub:** Gojira features a native content hub focusing on the wider Rujira ecosystem. It will include a creator hub and Rujira community articles (think Rujira’s own Medium platform).

### Benefits

* **Increases RUJI utility:** Spend RUJI to buy NFTs whose value and growth directly align with the Rujira ecosystem. At the same time, Gojira is one of multiple Rujira core products so RUJI-denominated collections should see limited downside risk from reflexivity.
* **Alignment with creators:** Gojira’s unique auction mechanics incentivize users to bid more money on collections. This means Gojira can charge bigger fees on excess profits and creators can make a killing relative to other platforms.
* **Fair, bot-free launches:** By prioritizing bigger bids over speed, the underlying auction model features behavioral incentives that prevent bots from gaming launches. Everyone has an equal opportunity to participate.
* **Optimized blockchain performance:** Bot-free auctions spread activity out over hours rather than seconds. As a result, Gojira does not congest the Rujira network even during periods of high usage and provides a superior user experience.
* **Greatly improved developer experience:** Our new smart contract framework features on-chain NFT attributes and eliminates any need to customize collection contracts for basic features. Gojira NFTs are also inherently upgradeable and composable.
* **Leverage Rujira DeFi:** Gojira is the only NFT marketplace in crypto with core access to an extensive selection of exclusive DeFi applications.
* **Community building:** NFT collections are excellent ways to onboard new users into the Rujira ecosystem and engage in general community building. Gojira’s content platform further unites the broader ecosystem.

### Fees & Fee Sharing with THORChain Base Layer

* Gojira’s auction mechanism ensures that successful NFT launches raise a certain “baseline level of funding”. Creators can fully customize this target baseline. We refer to any amount raised beyond that minimum threshold as “excess profit”.&#x20;
* A 4% fee is collected from baseline funding raised in a mint auction. A 15% fee will also be collected from any excess profit in a mint auction.&#x20;
* A 2% fee is collected from the total revenue for aftermarket auctions and trades.
* The standard 50/50 revenue share with TC Base Layer applies to all fees collected by Gojira.

### Status

* Not live yet.


# Strategies

The [Strategies](https://rujira.network/strategies) page acts as a repository showing earning opportunities across the ecosystem, both Automated Market Making strategies for RUJI Trade orderbook (provided by [RUJI AMM](/core-products/ruji-amm)), and opportunities such as [Lending](/core-products/ruji-money-market), staking, providing liquidity for [Perps trading](/core-products/ruji-perps#how-does-providing-liquidity-work), or strategies provided by other ecosystem projects. This list will be updated as more protocols roll out and more opportunities become available.

*Before making a deposit, make sure to read the* [*Terms & Conditions*](https://rujira.network/tou) *and understand the risks. Rujira is a suite of open-source, permissionless, non-custodial smart contracts*—*we simply provide tools, not financial advice or advice of any sort. Use the tools at your own risk.*

### Automated Market Making (AMM) Opportunities

<details>

<summary><strong>Custom Concentrated Liquidity (CCL) Strategy</strong></summary>

[CCL](https://rujira.network/trade/BTC/USDC?range=t) is an algorithmic strategy allowing users to provide liquidity inside a custom range, with a high level of customization for more opinionated market making and much higher capital efficiency vs. traditional XYK strategies.

To participate, users must set a series of parameters:

* **Set the high and the low of your range:** Above the upper end range, you are 100% in quote asset (e.g. USDC); Below the lower end of the range, you are 100% in base asset (e.g. BTC). Assuming you want to provide liquidity to the BTC/USDC pair, the two questions you should look to answer when setting your range are:
  * At what price are you happy to be 100% in BTC? That will be the bottom of your range.
  * At what price are you happy to be 100% in USDC? That will be the top of your range.
  * **Tightness Factor:** Once you set your price range (Low and High), Rujira automatically calculates the Tightness Factor as `Low/High`. This is a derived statistic that indicates how concentrated your liquidity is within the chosen range.

    * **Higher Tightness Factor** (max = 100%) → Your liquidity is more concentrated in a narrower band. This generally leads to higher volume and profits when the price stays inside your active range, but it also means your position can go out of range more easily if the price moves significantly.
    * **Lower Tightness Factor** (min = 0%) → Your liquidity is distributed across a wider range. This provides broader coverage and is more forgiving if the price moves, but with lower capital efficiency.

    The Tightness Factor helps you quickly understand how aggressive or conservative your range is.
* **Set the spread:** This is the target profit per round trip (i.e. sell quantity Q at price X, buy back same quantity at X minus spread). The higher the spread, the more profit you will be making per trade, but the more volatility you will need to complete a round-trip.
  * In high-volatility environment, higher spread will tend to generate higher returns.
  * In low-volatility environment, lower spread will tend to generate higher returns.
* **Set the skew:** This defines the shape of the liquidity inside the range; you can keep it uniform, or skew more towards the center or the edges.
  * For stable pairs like wBTC/BTC, you probably want most of the liquidity very close to the center of the range which you would likely set to be 1 wBTC = 1 BTC, but it allows you to still have some liquidity to catch the wider wicks.
  * For a volatile pair like BTC/USDC, you might want to overweight the end of the range, so you sell more BTC when price gets closer to the top, and buy more when price gets closer to the bottom. This would increase your average sell price if the price moves out of your range by the top, and lower your average buy price if the price moves out of your range by the bottom.
* **Set the fee:** This is the profits from the spread that are retained as claimable yield. "fee" can be set to any value between 0 (profit 100% compounded inside the position) and "spread" (all the profits are claimable as yield).

**Example 1: Wide range on the BTC/USDC pair**

* Alice has 10,000 USDC to invest, she has a long-term investment horizon, she checked the chart and believes BTC has a strong support at $70,000 and a strong resistance at $150,000.
  * She is happy to be 100% in BTC below $70,000, at which point she will close her position and keep the BTC with the aim of selling a portion for USDC and open a new position when BTC price has recovered, effectively using the CCL position as a tool to average down on BTC.
  * She is happy to be 100% in USDC above $150,000, at which point she will close her position and keep the USDC with the aim of selling a portion for BTC and opening a new position when BTC price drops again.
* Current BTC price is $100,000, she swaps some of her USDC for BTC to get the correct ratio based on her chosen range, and opens a position with the following parameters:
  * Spread: 0.30% --> Her position will automatically sell some BTC every time price moves up, and buys back every time the price moves down, targeting a 0.30% profit between buy and sell orders.
  * Fee: 100% --> She wants to use this position to create an income stream to complement her salary. She sets the fee equal to 100% of the spread to maximize her claimable yield.
  * Skew: 0 (balanced) --> She wants her positions to generate a relatively stable income, no matter where the price is inside her range, so she keeps the distribution of her liquidity uniform inside her range.
* As price moves through her range, buy and sell orders are automatically executed and she generates some yield from trading profits. The more the price moves (= volatility), the more yield she generates. She will be able to monitor the performance of her position with detailed analytics directly from the RUJI Trade page, and claim her yield periodically to supplement her income. Just like that, Alice became an algorithmic trader!

**Example 2: Narrow range on the BTC/USDC pair**

* Bob has 1,000 USDC to invest, he has a short-term investment horizon and actively manages his portfolio. He likes to open positions with a tight range around current price, maximizing his return while the price stays in his range. When the position gets out of range, he doesn't mind waiting for the price to move in his favor to re-open a new position.
* Current BTC price is $100,000, he decides to open a position with a tight +/-1.5% range around current price (low = 98,500 USDC / high = 101,500 USDC).
  * If his position gets out of range by the top, his plan is to close the position, keep the USDC and wait till price falls below 98,500 USDC to buy back some BTC and open a new position with a +/-1.5% range again.
  * If his position gets out of range by the bottom, his plan is to close the position, keep the BTC and wait till price rises above 101,500 USDC to sell some BTC and open a new position with a +/-1.5% range again.&#x20;
* He swaps some of his USDC for BTC to get the correct ratio based on his chosen range, and opens a position with the following parameters:
  * Spread: 0.10% --> His position will automatically sell BTC every time price moves up, and buys back every time the price moves down, targeting a 0.10% profit between buy and sell orders.
  * Fee: 0% --> He doesn't want any claimable yield, he prefers to maximize his return by compounding 100% of his trading profits inside his position.
  * Skew: overweight towards the edges --> He uses his position to swing trade and counts on it to get out of range either side before he closes it. By overweighting towards the edges, he lowers his average buy price or increase his average sell price when the position gets out of range.
* He will be able to monitor the performance of his position from the RUJI Trade page, however, given he set the "fee" parameter to 0, the APR will also be 0%, but he will still be able to track to total performance of his position by looking at the MOIC (Multiple of Invested Capital) which is a measure of total investment performance, including trading profits and price gain/loss.

</details>

<details>

<summary><strong>Base Layer Virtualization Strategy</strong></summary>

The strategy does not require any external liquidity providers to run as it relies on just-in-time borrowing from the Lending vaults to fill the quotes. Profits from the strategy are accumulated into the [contract](https://thorchain.net/address/thor1n5a08r0zvmqca39ka2tgwlkjy9ugalutk7fjpzptfppqcccnat2ska5t4g) and will be used to build liquidity or act as a Security Fund to cover bug bounties and potential exploits up to the amount available in there.

</details>

<details>

<summary><strong>Dynamic Concentrated Liquidity (DCL) Strategy</strong></summary>

Coming soon...

</details>

### Other Core Opportunities

<details>

<summary><strong>Lending Vaults</strong></summary>

Generate passive returns by [lending](https://rujira.network/strategies?filters=GhostVault) your crypto assets, with a relatively low risk profile (all loans are overcollateralized) and no exposure to Impermanent Loss. The yield comes from borrowers who are charged an interest rate every block based on the utilization rate of the borrowed asset compared to the total supplied available for lending.

</details>

### Staking

<details>

<summary><strong>RUJI</strong></summary>

Stake RUJI to earn a share of revenue generated by Rujira core products. Stakers have two options:

1. Standard RUJI staking: You earn rewards in USDC to be claimed manually.
2. Auto-compounding staking: Your USDC rewards are used to automatically buy more RUJI and add it to your position.

Users opting for the auto-compound option receive sRUJI, a liquid representation of their share in the strategy that can be redeemed for RUJI at any time.

</details>

<details>

<summary><strong>bRUNE (Liquid Bonded RUNE)</strong></summary>

[Stake bRUNE](https://rujira.network/strategies/staking/bRUNE) to access THORChain node bonding through a simple, permissionless interface, with instant liquidity to get in and out.

Each bRUNE is always backed by at least 1 RUNE in the contract + unclaimed accrued yield. The contract bonds RUNE to a diversified set of THORChain nodes on behalf of users and distributes the resulting bonding yield proportionally to bRUNE stakers.

bRUNE can be staked to earn claimable RUNE, or set to auto-compound, buying & staking more bRUNE automatically.

</details>

<details>

<summary><strong>TCY</strong></summary>

[Stake TCY](https://rujira.network/strategies/staking/TCY) and earn 10% of THORChain revenue distributed in RUNE once every 24 hours.

Users can choose the TCY AutoCompounder built by [AutoRujira](https://autorujira.app/) to passively grow their TCY holdings by automating the reinvestment of rewards. Rewards are sent directly to the smart contract which converts the RUNE into more TCY via RUJI Trade and redistributes it to depositors — compounding their position over time.

Users opting for the auto-compound option receive sTCY, a liquid representation of their share in the strategy that can be redeemed for TCY at any time.

</details>

<details>

<summary><strong>LQDY</strong></summary>

Coming soon...

</details>

### Indexes

<details>

<summary><strong>yRUNE</strong> (The Yield Bearing RUNE Index)</summary>

[yRUNE](https://rujira.network/index/yRUNE) combines RUNE (\~80%) and TCY (\~20%) into one asset using RUJI Index's vault infrastructure. It is the first liquid RUNE based asset that also captures yield from THORChain system income. With RUJI Index's rebalancing engine, yRUNE constantly rebalances the underlying RUNE and TCY to capture price swings and market inefficiencies while taking advantage of TCY generated fees.

Deposits into yRUNE are always made from RUNE, and redemption always to RUNE.

</details>

<details>

<summary><strong>yTCY</strong> (The Yield Bearing TCY Index)</summary>

yTCY combines TCY (\~80%) and RUNE (\~20%) into one asset using RUJI Index's vault infrastructure. It is designed to track the performance of both RUNE and TCY, with a strategic overweight on TCY to maximize yield potential. With RUJI Index's rebalancing engine, yTCY constantly rebalances the underlying TCY and RUNE to capture price swings and market inefficiencies while taking advantage of TCY generated fees.

Deposits into yTCY are always made from TCY, and redemption always to TCY.

</details>

<details>

<summary><strong>RJI</strong> (Rujira Index)</summary>

The [Rujira Index](https://rujira.network/index/RJI) (RJI) is a basket of tokens native to THORChain that tracks the performance of the App Layer economy. It currently comprises 5 components (RUNE, RUJI, TCY, LQDY and AUTO, with more to be added as the ecosystem grows) combined into one asset using RUJI Index's vault infrastructure. It is intended to capture Rujira ecosystem growth as a whole. The index does not auto-rebalance; therefore, it is designed to continuously overweight the top performers and underweight the underperformers.

Deposits into RJI are always made from USDC, and redemption always to USDC.

</details>

### FAQ

* [Strategies FAQ](/how-it-works/frequently-asked-questions/strategies-put-your-assets-to-work)


# TCY AutoCompounder

The TCY AutoCompounder is a permissionless smart contract on Rujira built by the [AutoRujira](https://autorujira.app/) team that automatically claims, converts, and reinvests TCY rewards to maximize yield — with zero manual intervention. Designed for users who want to earn more without constant monitoring, it’s the simplest way to compound TCY over time.

### Key Features

* **Fully Decentralized & Non-Custodial:** The AutoCompounder is 100% on-chain and permissionless. Your TCY always remains under your control — the smart contract simply automates the process.
* **Simple, One-Step Setup:** Just deposit your TCY into the AutoCompounder at [tcy.thorchain.org/manage](https://tcy.thorchain.org/manage). You’ll receive sTCY in return, representing your share of the vault. This allows you to stay liquid or use your position in future DeFi products.
* **Automated Claim, Conversion & Reinvestment:** Approximately every 24 hours, the contract receives rewards in RUNE. These rewards are automatically converted into more TCY via RUJI Trade and redistributed proportionally to all depositors — growing your position continuously.

### Benefits

* **Set & Forget Yield Optimization:** Forget about claiming rewards, tracking prices, or managing reinvestments. The AutoCompounder runs 24/7 and compounds for you — ensuring you never miss a chance to grow your position. It removes the friction of active management while delivering optimized returns over time.
* **Maximum Efficiency:** Rewards are claimed and reinvested as soon as they become available. No idle assets. No wasted time. No manual effort.
* **Future-Ready Design:** The sTCY token unlocks powerful integrations across the Rujira ecosystem. From lending to liquidation bids, your auto-compounded position becomes a core building block of your DeFi strategy.

### Fees & Fee Sharing with THORChain Base Layer

* **TCY AutoCompounder:** A 5% fee is collected from compounded rewards only (not principal) and is distributed to AUTO stakers as part of AutoRujira’s fee-sharing model. This is the first of many strategies being built by AutoRujira to unlock the full potential of TCY — and help users do more with their assets, effortlessly.
* **Rujira & THORChain:** TCY AutoCompounder is built on top of Rujira's Orderbook DEX. Hence, every auto-compounding transaction is subject to the standard Orderbook DEX fee, accruing value to both RUJI stakers and THORChain Base Layer.

### Status

* TCY AutoCompounder is live [here](https://rujira.network/strategies/staking/TCY).


# Recurring Orders

Recurring orders built by the [CALC](https://calculated.fi/) team let you create a trading schedule to swap over time using native (secured) assets on Rujira. Whether you want to gradually build a position or take profits in smaller parts, this feature runs fully on-chain and allows you to schedule swaps, and set custom parameters, so you can comfortably trade on your own terms.

### Key Features

* **Recurring Orders Setup:** Create automated buy or sell orders that execute over time using native and secured tokens.
* **Flexible Timing:** Choose how often swaps occur, including block-based, minute, hourly, and daily intervals.
* **Price Limits:** Set optional price floors or ceilings to prevent swaps from executing outside your desired range.
* **Price Protection:** Set maximum price impact to prevent unfavorable swaps.
* **On-Chain Execution:** All swaps are executed transparently through smart contracts on Rujira and THORChain.
* **Live Strategy Control:** Monitor, pause, edit, deposit, or withdraw funds from your orders at any time through RUJI Trade.
* **Auto Distribution:** Once the deposit token is fully used, the received tokens are automatically distributed back to your wallet.
* **Re-activate:** Completed recurring orders can be re-activated by topping them up or sending assets to their strategy address.

### Benefits

* **Reduced Volatility Risk:** Lowers the impact of short-term price movements by spreading out trades.
* **Full User Control:** You retain control over your funds, schedule, price and limits at all times.
* **Consistent Trading Approach:** Reduces emotional decisions by following a regular, rule-based plan.
* **Native Liquidity Access:** Access THORChain liquidity for native assets without wrapping.

### Fees and Fee Sharing

* **Automation Fee:** 25bps (0.25%) on all funds exiting a recurring order, whether completed or withdrawn. Paid to CALC for ongoing development.
* **Rujira Fee:** Every swap performed by recurring orders pays RUJI Trade taker fees.
* No additional fees apply for editing, pausing, resuming or topping up strategies.

### Status

• Recurring Orders are live, available from [RUJI Trade](https://rujira.network/trade/RUJI/USDC?orders=recurring-active\&order=recurring) by selecting **Advanced** in the trade panel.

### FAQ

* [CALC Recurring Orders FAQ](/how-it-works/frequently-asked-questions/calc-recurring-orders-dca-in-and-out-of-positions)


# Getting Started

Welcome to Rujira, the THORChain App Layer designed for building secure and sustainable decentralized applications (dApps) and smart contracts. This section will help you understand the core concepts you'll need to get started building on Rujira.

## Overview

Before getting started building on Rujira, make sure to familiarize yourself with:

* [**Secured Assets**](/how-it-works/understanding-secured-assets)**:** Being an App Layer on top of THORChain, it is key to understand how all assets on Rujira are secured by THORChain Base Layer.
* [**CosmWasm (Smart Contracts)**](https://cosmwasm.cosmos.network/)**:** Key parts of Rujira and THORChain are built on the Cosmos tech stack, and the go-to smart contracting platform in the Cosmos ecosystem is CosmWasm. It allows developers to write secure, efficient contracts in languages like Rust. If you're new to CosmWasm and Smart Contracts, we recommend starting with the official [CosmWasm docs](https://cosmwasm.cosmos.network/) and the [CW-Template repository](https://github.com/InterWasm/cw-template), which will help you understand the basic interfaces and models of CosmWasm smart contracts.&#x20;
* [**API & RPC Endpoints**](/developers/developer-endpoints): A full list of endpoints to connect to both stagenet and mainnet.
* Listen to this fireside chat with Hans, talking about the system architecture and building on Rujira: <https://www.youtube.com/watch?v=-wzPRC7eNkk>

Once you have a good understanding of the above, you are ready to dive into the [Development Process](/developers/development-process)—everything from development to staging to auditing to mainnet—enabling you to deploy fast onto Rujira.

## Ideas to Build

If you want to contribute to the Rujira ecosystem but aren’t sure what to build yet, explore our list of project ideas [Build Ideas](/developers/build-ideas). It’s a great starting point to find inspiration and identify areas where your skills can make an impact.

## Other Useful SDKs & Libraries

Besides the above, Rujira is made up of multiple moving parts making up the entire App Layer

* [**Rujira.js**](https://gitlab.com/thorchain/rujira-ui/-/tree/dev/packages/rujira.js): A JavaScript SDK tailored for TypeScript-based backend interaction between applications and smart contracts on Rujira.
* [**Rujira-rs**](https://gitlab.com/thorchain/rujira/-/tree/main/packages/rujira-rs): A Rust library that contains the essential message types and structures for interacting with Rujira's core app-layer smart contracts. This SDK simplifies integration between core smart contracts and any dApps built on top of them.
* [**Rujira.ui**](https://gitlab.com/thorchain/rujira-ui): A collection of reusable UI components that also provide wallet integration, enabling quick and easy development of dApps with consistent user experiences.


# Smart Contracts (CosmWasm)

### Getting Started

If you're new to **CosmWasm** and **Smart Contracts**, we recommend starting with the [CW-Template repository](https://github.com/InterWasm/cw-template). This template will help you understand the basic interfaces and models of CosmWasm smart contracts.

When you're ready to deploy your smart contract, you’ll need a local build of the chain core. This will allow you to store your code on-chain and submit governance proposals to instantiate it.

#### Installation Steps

1. Clone the Rujira core repository:

   ```bash
   git clone https://gitlab.com/thornode/thorchain/app-layer/
   cd core
   make install
   ```

### Deployment

Now that you've set up the environment, you're ready to store your code on-chain.

#### Step 1: Optimize the Code

To optimize your contract's code, run the following command:

```bash
cargo run-script optimize
```

#### Step 2: Create a Local Account

You’ll need a local account to handle transactions.

```bash
rujirad keys add <local-account>
```

This will generate a seed phrase and an associated Kujira address for your account. Make sure to store the seed phrase safely. You’ll also need to fund this address with **KUJI tokens** before proceeding to the next step.

#### Step 3: Store Code on Chain

To store the optimized code on-chain, run the following:

```bash
rujirad tx wasm store <./path/to/optimized/code.wasm> --from <local-account>
```

Upon successful execution, logs will be generated. These logs contain the `code_id` of your contract, which will look something like this:

```bash
logs:
- events:
  - attributes:
    - key: action
      value: /cosmwasm.wasm.v1.MsgStoreCode
    - key: module
      value: wasm
    - key: sender
      value: rujira1...
    type: message
  - attributes:
    - key: code_id
      value: "4"
    type: store_code
```

### Instantiation

Your code is now stored on-chain and behaves similarly to a class in an object-oriented language. Next, you need to instantiate the contract so you can interact with it.

On Kujira, instantiation must be done via a governance proposal. This ensures the quality and security of code and dApps on the network.

#### Step 1: Submit a Governance Proposal

Run the following command to submit an instantiation proposal:

```bash
rujirad tx gov submit-proposal instantiate-contract 4 \
  '{"count": 0}' \
  --title "Instantiate CW-Template" \
  --description "A more detailed description of this proposal" \
  --label "CW-Template" \
  --from <local-account> \
  --admin <local-account-address> \
  --run-as <local-account-address> \
  --gas 1000000 \
  --fees 1250ukuji
```

This creates a proposal at the funding stage. You can then visit Rujira Governance to deposit funds and open it for voting.

#### Step 2: Retrieve Contract Address

After the proposal passes and the contract is instantiated, the contract will have its own unique address. You can find the contract address with the following query:

```bash
rujirad query wasm list-contract-by-code 4
```

Once the contract is instantiated, you're ready to move on to building the UI for your newly deployed smart contract.


# Licenses

## License Overview

Rujira is an open-source software project, licensed under the MIT License. This license allows developers to freely use, modify, and distribute the software while providing certain protections to the authors and contributors.

Below are the details of the license and how it applies to the Rujira project.

***

## MIT License

The Rujira project is licensed under the MIT License, a permissive open-source license. Here's what the MIT License allows:

* **Free Usage**: You can use Rujira for any purpose, whether personal, academic, or commercial.
* **Modification**: You're free to modify the source code to fit your needs.
* **Distribution**: You may distribute the original or modified versions of Rujira.
* **Private Use**: You are allowed to use Rujira without publicly disclosing your modifications.

However, the MIT License also includes certain responsibilities:

* **Attribution**: You must include the original copyright notice and license in any significant portion of the software.
* **No Liability**: The software is provided "as is," without warranty of any kind. The authors and contributors are not liable for any damages arising from its use.

For more details, check the [full text of the MIT License](https://opensource.org/license/MIT).

***

## Open-Source Standards (OSS)

Rujira follows open-source standards to promote transparency, collaboration, and community-driven development. By using the MIT License, we align with OSS best practices, which include:

* **Accessibility**: The source code is freely available for anyone to inspect, contribute to, and improve.
* **Collaboration**: Contributions from developers are welcome, subject to the project's contribution guidelines.
* **Security**: Regular updates and community feedback ensure security vulnerabilities are addressed promptly.

We encourage developers to contribute back to the Rujira project and help enhance its features and stability.

***

## How to Contribute

We invite developers to collaborate on the Rujira project by:

1. Forking the repository.
2. Submitting pull requests for improvements.
3. Reporting bugs or security issues.
4. Participating in discussions and feature planning.

All contributions are governed by the MIT License and must adhere to the project's **Code of Conduct**.

***

By using Rujira, you agree to the terms of the MIT License and understand your rights and responsibilities under this open-source software model.


# RUJI Product Integration Guides

Technical documentation for integrating Rujira Network products into your application.

### Available Guides

#### [RUJI Trade and CCL](/developers/ruji-product-integration-guides/ruji-trade-and-ccl)

Integrate RUJI Trade orderbook DEX with native assets (BTC, ETH, SOL, XRP, DOGE, BCH, LTC and more) secured by THORChain - fully decentralized and permissionless.

* [**Funding Requirement: Secured Assets**](https://docs.rujira.network/developers/ruji-product-integration-guides/ruji-trade-and-ccl#funding-requirement-secured-assets)
  * Deposit native assets into THORChain to get Secured Assets
  * Withdraw Secured Asset back to the source L1
* [**Trading on RUJI Trade (FIN)**](/developers/ruji-product-integration-guides/ruji-trade-and-ccl#swap-integration)
  * Market orders (swap)
  * Limit orders
  * Tracking orders
* [**Custom Concentrated Liquidity (CCL) Positions**](/developers/ruji-product-integration-guides/ruji-trade-and-ccl#ccl-range-integration)
  * Create and manage ranges (fixed-range AMM strategies built directly into FIN)

#### [Money Market](/developers/ruji-product-integration-guides/ruji-lend-and-borrow)

Integrate lending and borrowing functionality with native assets (BTC, ETH, SOL, XRP, DOGE, BCH, LTC and more) secured by THORChain.

* [**Lending (Ghost Vault)**](/developers/ruji-product-integration-guides/ruji-lend-and-borrow#part-1-lending-integration-ghost-vault)
  * Deposit assets to earn yield
  * Receive transferable receipt tokens
  * Dynamic interest rates based on utilization
* [**Borrowing (Ghost Credit)**](/developers/ruji-product-integration-guides/ruji-lend-and-borrow#part-2-borrowing-integration-ghost-credit)
  * Create isolated Credit Accounts
  * Deposit multi-asset collateral
  * Borrow against collateral with overcollateralized loans

#### [Liquidations](/developers/ruji-product-integration-guides/ruji-liquidations)

* [**Bidding on Liquidations (for end users)**](/developers/ruji-product-integration-guides/ruji-liquidations/bidding-on-liquidations)
  * Integrate liquidation bidding into your application, allowing users to acquire collateral at discounted prices when CDP positions are liquidated.
* [**Build a Liquidation Solver (for developers)**](/developers/ruji-product-integration-guides/ruji-liquidations/liquidation-solvers)
  * Build liquidation bots that monitor at-risk positions, calculates optimal liquidation routes, and executes liquidations to earn the 0.5% executor fee.

#### [Staking](/developers/ruji-product-integration-guides/staking-ruji-brune-tcy)

Integrate staking markets powered by the Rujira staking contract, including RUJI, bRUNE and TCY. Allow users to stake and earn rewards from real economic activity. The staking contract supports both Account staking (claimable yield) and Liquid staking (auto-compounding).

#### [Liquidy Swap API](/developers/ruji-product-integration-guides/liquidy-swap-api)

[Liquidy](https://liquidy.finance/developer/swap-api) provide an easy way to integrate any SecuredAsset-to-SecuredAsset swap on Rujira, finding the best route between any two tokens through any of the RUJI Trade orderbooks. Liquidy API can also be used to find arbitrage opportunities across the orderbooks.

Liquidy charges 0.10% fee per swap and the optimize routing still often result for a net positive outcome for end users. Liquidy router support both a referral fee model (typically 10% of the 0.10% protocol fee shared with the integrating partner) and an affiliate fee model (additional fee the partner can add on top of the protocol fee - 100% retained by the partner).&#x20;

***

### Quick Reference

#### Main Supported Assets

<table><thead><tr><th width="150">Asset</th><th width="400">Denom</th><th>Decimals</th></tr></thead><tbody><tr><td>BTC</td><td><code>btc-btc</code></td><td>8</td></tr><tr><td>ETH</td><td><code>eth-eth</code></td><td>8</td></tr><tr><td>USDC</td><td><code>eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48</code></td><td>8</td></tr><tr><td>USDT</td><td><code>eth-usdt-0xdac17f958d2ee523a2206206994597c13d831ec7</code></td><td>8</td></tr><tr><td>BCH</td><td><code>bch-bch</code></td><td>8</td></tr><tr><td>DOGE</td><td><code>doge-doge</code></td><td>8</td></tr><tr><td>LTC</td><td><code>ltc-ltc</code></td><td>8</td></tr><tr><td>XRP</td><td><code>xrp-xrp</code></td><td>8</td></tr><tr><td>BNB</td><td><code>bsc-bnb</code></td><td>8</td></tr><tr><td>AVAX</td><td><code>avax-avax</code></td><td>8</td></tr><tr><td>TRX</td><td><code>tron-trx</code></td><td>8</td></tr><tr><td>ATOM</td><td><code>gaia-atom</code></td><td>8</td></tr></tbody></table>

> **Note:** For the full list of supported assets and chains, check THORChain active pools on <https://thorchain.net/pools/main>.

#### Network Endpoints

**THORChain Mainnet**

<table><thead><tr><th width="300">Type</th><th>URL</th></tr></thead><tbody><tr><td>RPC</td><td><code>https://gateway.liquify.com/chain/thorchain_rpc</code></td></tr><tr><td>gRPC</td><td><code>https://grpc-thorchain.rorcual.xyz</code></td></tr><tr><td>REST</td><td><code>https://gateway.liquify.com/chain/thorchain_api</code></td></tr></tbody></table>

**Rujira APIs**

<table><thead><tr><th width="300">Environment</th><th>URL</th></tr></thead><tbody><tr><td>Mainnet GraphQL</td><td><code>https://api.rujira.network/api/graphiql</code></td></tr></tbody></table>

***

### Development Tools

#### Libraries

RUJI contracts are standard CosmWasm. Use any Cosmos SDK compatible library:

| Language              | Library                                               |
| --------------------- | ----------------------------------------------------- |
| TypeScript/JavaScript | [CosmJS](https://github.com/cosmos/cosmjs)            |
| Rust                  | [cosmwasm-std](https://crates.io/crates/cosmwasm-std) |
| Go                    | [Cosmos SDK](https://github.com/cosmos/cosmos-sdk)    |
| Python                | [cosmpy](https://github.com/fetchai/cosmpy)           |

#### Contract Schemas

JSON schemas for all message types are available in each contract's `/schema` directory:

* [RUJI Trade (FIN) Schema](https://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-fin/schema/rujira-fin.json?ref_type=heads)
* [Ghost Vault Schema](https://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-ghost-vault/schema/rujira-ghost-vault.json?ref_type=heads)
* [Ghost Credit Schema](https://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-ghost-credit/schema/rujira-ghost-credit.json?ref_type=heads)

***

### Common Patterns

#### Querying Contract State

```typescript
import { CosmWasmClient } from "@cosmjs/cosmwasm-stargate";

const client = await CosmWasmClient.connect("https://rpc.ninerealms.com");

// Query any contract
const result = await client.queryContractSmart(
  CONTRACT_ADDRESS,
  { query_msg: { /* params */ } }
);
```

#### Executing Transactions

```typescript
import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";

const client = await SigningCosmWasmClient.connectWithSigner(
  "https://rpc.ninerealms.com",
  signer
);

// Execute with funds
const result = await client.execute(
  senderAddress,
  CONTRACT_ADDRESS,
  { execute_msg: { /* params */ } },
  "auto",  // gas
  "",      // memo
  [{ denom: "btc-btc", amount: "100000000" }]  // funds
);
```

#### Handling Decimals

All amounts use 8 decimal places:

```typescript
// Convert human-readable to chain format
function toChainAmount(amount: number): string {
  return Math.floor(amount * 1e8).toString();
}

// Convert chain format to human-readable
function fromChainAmount(amount: string): number {
  return parseInt(amount) / 1e8;
}

// Examples:
toChainAmount(1.5);        // "150000000" (1.5 BTC)
fromChainAmount("100000000"); // 1.0 BTC
```

***

### Support

* **Documentation**: [docs.rujira.network](https://docs.rujira.network)
* **Telegram**: [@Rujira\_Community ](https://t.me/Rujira_Community)
* **E-Mail**: [bd@rujira.network ](mailto://bd@rujira.network)
* **Discord**: [Join](https://discord.gg/AfmZN49grz)


# RUJI Trade and CCL

Technical documentation for wallets, swap routers, portfolio apps, and protocols integrating RUJI Trade through the FIN contract and its CCL range liquidity.

### Overview

RUJI Trade is the Rujira spot trading venue built around FIN order book contracts. Each FIN contract represents one market pair. Integrators interact with FIN using standard CosmWasm queries and `MsgExecuteContract` transactions.

Custom Concentrated Liquidity (CCL) ranges are managed by the same FIN contract through the `range` execute message. For integrators, this means swaps (market orders), limit orders, tracking orders, and CCL liquidity management all use the FIN contract address for the pair.

#### Who This Guide Is For

| Integrator         | Typical integration                                                                                                                                      |
| ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Wallets            | Show secured-asset balances, quote swaps (market orders), sign FIN market/limit/tracking orders, and guide users through securing assets before trading. |
| Swap routers       | Quote FIN liquidity for users who already hold secured assets, or split the route into a secure-asset step followed by the FIN swap.                     |
| Portfolio apps     | Query open orders, CCL positions, claimable fees, and pair configuration for display.                                                                    |
| Protocol UIs       | Use FIN swaps and orders directly, optionally with callbacks so the protocol can receive the output funds in the same transaction flow.                  |
| Liquidity managers | Create, update, withdraw, close, and transfer CCL positions.                                                                                             |

#### Funding Requirement: Secured Assets

FIN trades app-layer bank balances. A user cannot send ordinary L1 BTC, ETH, or USDC directly into a FIN swap or order. The user must first hold the relevant THORChain Secured Asset on the Rujira app layer.

Secured Assets use `-` as the asset delimiter. For example:

| Layer 1 Asset                                         | Secured Asset                                         | Example bank denom                                    |
| ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- |
| `BTC.BTC`                                             | `BTC-BTC`                                             | `btc-btc`                                             |
| `ETH.ETH`                                             | `ETH-ETH`                                             | `eth-eth`                                             |
| `ETH.USDC-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48` | `ETH-USDC-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48` | `eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48` |

For wallets and routers, this gives two possible user flows:

1. User already has the secured asset balance. Query the user's bank balances on their THOR address and call the FIN contract directly with those denoms.
2. User starts with an L1 asset. Guide the user through securing the asset first. THORChain documents the minting memo as `SECURE+:THORADD`, and the short memo form is commonly shown as `S+:THORADD`. The destination must be the user's THOR address, for example `SECURE+:thor1...`. Once the secured balance appears, submit the FIN transaction.

To redeem back out to an L1 address, THORChain documents `SECURE-:ADDR`; the short form is commonly shown as `S-:ADDR`. This is the reverse flow and is not part of the FIN swap itself.

Useful references:

* Rujira secured assets: <https://docs.rujira.network/developers/secured-assets>
* THORChain secured assets: <https://dev.thorchain.org/concepts/secured-assets.html>
* Deployment list for live FIN pair contracts: <https://rujira.network/developer/deployment>

### Architecture

```
External wallet / router / protocol UI
        |
        | 1. User secures L1 asset if needed
        v
THORChain/Rujira app layer bank balance
        |
        | 2. CosmWasm query / execute
        v
FIN pair contract
        |
        +-- Order book liquidity
        +-- CCL range positions
        +-- Optional protocol callbacks for swap/order outputs
```

Do not integrate the internal `do_swap`, `do_order`, or `do_range` messages. They are used by the contract itself after the public `swap`, `order`, or `range` message wraps execution through FIN's internal arbitrage step.

### Contract Addresses and Denoms

FIN contracts are pair-specific. Look up the current contract address for the pair you want to trade on the Rujira deployment page:

```
https://rujira.network/developer/deployment
```

Query the pair config before building UI or routes:

```json
{ "config": {} }
```

Response shape:

```json
{
  "denoms": ["btc-btc", "eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"],
  "oracles": null,
  "market_makers": [],
  "tick": 4,
  "range_delta": "0.001",
  "range_min": "1",
  "fee_taker": "0.001",
  "fee_maker": "0.001",
  "fee_range": "0.001",
  "fee_address": "thor1..."
}
```

The first denom is the base asset. The second denom is the quote asset.

All `Uint128` amounts are strings in JSON. All `Decimal` values are also strings. All Secured Assets use 8 decimal places for display, but integrators should read the active asset metadata and denom list instead of hardcoding display rules for every asset.

### FIN Concepts

#### Base, Quote, and Side

FIN uses two denoms:

```
denoms[0] = base
denoms[1] = quote
```

For swaps (market orders), the contract derives the side from the denom sent in `funds`.

| User sends  | Contract side | User receives |
| ----------- | ------------- | ------------- |
| base denom  | `quote`       | quote denom   |
| quote denom | `base`        | base denom    |

For orders, `side` means the denom locked in the resting order.

| Order side | Order locks | Order receives when filled |
| ---------- | ----------- | -------------------------- |
| `base`     | base denom  | quote denom                |
| `quote`    | quote denom | base denom                 |

This is the main side-related gotcha. A swap that sends quote funds routes through the `base` side and receives base. A resting order with side `quote` also uses quote funds, but there the side names what is locked in the order.

#### Price Types

FIN supports two price formats:

```json
{ "fixed": "90000" }
```

```json
{ "oracle": 0 }
```

`fixed` is an explicit decimal price, it is used for standard limit order.

`oracle` is an oracle-relative price in basis points, it is used for "tracking" orders, a novel order type pionnered by Rujira that reprices every block based on enshrined oracle price +/- a premium or discount. For example, `0` means the oracle price, `100` means oracle plus 1%, and `-100` means oracle minus 1%. Oracle values must have absolute value below `10000`.

Order fixed prices and CCL range bounds must be valid for the pair's `tick`. The `tick` is a significant-figure style validation used by the contract. If the price is not aligned to the configured tick, the transaction fails with an invalid price error.

Swap limit prices are also decimal strings, but they are not the same as `Price::Fixed` and are not tick-validated by FIN.

#### Querying the Book

```json
{
  "book": {
    "limit": 100,
    "offset": 0
  }
}
```

Response shape:

```json
{
  "base": [
    { "price": "90000", "total": "100000000" }
  ],
  "quote": [
    { "price": "89900", "total": "5000000000" }
  ]
}
```

The the query returns a paginated book response with:

* `limit`: the maximum number of price levels to return per side (defaults to `100`);
* `offset`: number of price levels to skip from the front of each side (defaults to `0`).

The book response merges all the liquidity that FIN can trade against, including limit orders, tracking orders, CCL range liquidity and THORChain base layer liquidity via the [Virtualization Strategy](/core-products/ruji-amm/base-layer-virtualization-strategy).

### Swap Integration

Use `simulate` to quote a market-style swap before asking the user to sign.

```json
{
  "simulate": {
    "denom": "eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
    "amount": "1000000000"
  }
}
```

Response:

```json
{
  "returned": "11000",
  "fee": "12"
}
```

`simulate` always simulates a market-style swap over the current available liquidity. It does not apply your UI slippage setting. For user protection, routers and wallets should convert the simulated result into a `min_return` swap.

#### Swap Messages

All swaps send exactly one native coin in `funds`.

Market swap without protection:

```json
{
  "swap": {
    "to": null,
    "callback": null
  }
}
```

Recommended wallet/router swap with slippage protection (return at least `min_return` or fail):

```json
{
  "swap": {
    "min_return": "10900",
    "to": null,
    "callback": null
  }
}
```

Exact-return swap (return exactly `exact_return` or fail):

```json
{
  "swap": {
    "exact_return": "11000",
    "to": null,
    "callback": null
  }
}
```

Limit-priced swap (swap as much of the input as possible at or better than `price`, returning any unused offer):

```json
{
  "swap": {
    "price": "90000",
    "to": null,
    "callback": null
  }
}
```

For a limit-priced swap, `price` is quoted in the ask token, which is the token the user sends. If the user sends quote to buy base, use the normal quote-per-base price. If the user sends base to sell for quote, use the inverse price.

The `to` field is optional. If omitted or `null`, the output goes to the signer. If set, the output goes to that address.

The `callback` field is optional and is mainly for protocol integrations. See the callback section below.

#### TypeScript Example: Quote and Swap

```ts
import { CosmWasmClient, SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";

const rpc = "https://gateway.liquify.com/chain/thorchain_rpc";
const finContract = "thor1..."; // Pair-specific FIN contract address.
const sender = "thor1...";
const offerDenom = "eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48";
const offerAmount = "1000000000";

function applySlippage(amount: string, slippageBps: bigint): string {
  const value = BigInt(amount);
  return ((value * (10_000n - slippageBps)) / 10_000n).toString();
}

const queryClient = await CosmWasmClient.connect(rpc);

const quote = await queryClient.queryContractSmart(finContract, {
  simulate: {
    denom: offerDenom,
    amount: offerAmount,
  },
});

const minReturn = applySlippage(quote.returned, 50n); // 0.50% max slippage.

const signingClient = await SigningCosmWasmClient.connectWithSigner(rpc, signer);

const tx = await signingClient.execute(
  sender,
  finContract,
  {
    swap: {
      min_return: minReturn,
      to: null,
      callback: null,
    },
  },
  "auto",
  "",
  [{ denom: offerDenom, amount: offerAmount }],
);
```

#### Router UX Notes

* Check the user's app-layer bank balance before building the FIN transaction.
* If the user only holds the L1 asset, show a separate secure-asset step first.
* Wait for the secured balance to appear before submitting the FIN swap.
* Use `simulate` for the quote, but execute with `min_return`.
* If the user sends the base denom, they are selling base for quote. If the user sends the quote denom, they are buying base with quote.

### Limit & Tracking Order Integration

Use the `order` execute message to create, resize, withdraw from, or cancel one or more orders.

The execute shape is:

```json
{
  "order": [
    [
      ["base", { "fixed": "90000" }, "1000000"],
      ["quote", { "oracle": 0 }, "5000000000"]
    ],
    null
  ]
}
```

Each order target is:

```
[side, price, target_offer_amount]
```

`target_offer_amount` is the desired resting offer amount after the message completes.

The target amount is denominated in the asset locked by the order side:

| Order side | Target amount denom |
| ---------- | ------------------- |
| `base`     | base denom          |
| `quote`    | quote denom         |

| Target value | Meaning                                                                           |
| ------------ | --------------------------------------------------------------------------------- |
| `"1000000"`  | Create the order if missing, or resize the existing order to this offer amount.   |
| `"0"`        | Withdraw filled amount first, then cancel the remaining offer.                    |
| `null`       | If the order exists, withdraw filled amount only. If no order exists, do nothing. |

FIN only allows to have one active limit order per price level. If an order already exists at a given price, a subsequent `order` execute message will update the size of the existing order.

Funds sent with the transaction must cover the net increase in order size. Funds withdrawn from filled or reduced orders in the same execution can be reused inside that same execution.

When creating a new order, FIN may immediately match part of the offer against opposite liquidity. Any remaining offer becomes the resting order.

#### Query One Order

```json
{
  "order": [
    "thor1owner...",
    "base",
    { "fixed": "90000" }
  ]
}
```

Response shape:

```json
{
  "owner": "thor1owner...",
  "side": "base",
  "price": { "fixed": "90000" },
  "rate": "90000",
  "updated_at": "1710000000000000000",
  "offer": "1000000",
  "remaining": "750000",
  "filled": "250000"
}
```

`filled` is not automatically paid out. A later `order` execution touching the same order withdraws the filled amount.

#### Query Orders

```json
{
  "orders": {
    "owner": "thor1owner...",
    "side": null,
    "start_after": null,
    "limit": 10
  }
}
```

`limit` defaults to `10`.

For pagination, pass the last returned order as:

```json
["thor1owner...", "base", { "fixed": "90000" }]
```

The cursor is always shaped as `(owner, side, price)`. When querying a single owner, the contract ignores the owner string inside the cursor, but the schema still requires the tuple.

#### TypeScript Example: Place a Buy Order

In this example the user sends quote funds and places a `quote` side order, meaning the order locks quote and receives base when filled.

```ts
import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";

const rpc = "https://gateway.liquify.com/chain/thorchain_rpc";
const finContract = "thor1...";
const sender = "thor1...";
const quoteDenom = "eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48";
const targetOfferAmount = "5000000000";

const client = await SigningCosmWasmClient.connectWithSigner(rpc, signer);

const result = await client.execute(
  sender,
  finContract,
  {
    order: [
      [
        ["quote", { fixed: "90000" }, targetOfferAmount],
      ],
      null,
    ],
  },
  "auto",
  "",
  [{ denom: quoteDenom, amount: targetOfferAmount }],
);
```

### CCL Range Integration

CCL ranges are concentrated liquidity positions inside FIN. A range has:

| Field    | Meaning                                                                                                                                        |
| -------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `low`    | Lower price bound.                                                                                                                             |
| `high`   | Upper price bound.                                                                                                                             |
| `skew`   | Distribution slope. Use `"0"` for normal integrations unless you are deliberately building an advanced strategy.                               |
| `spread` | Distance between the range's internal price and its best bid/ask. Must be below `1`.                                                           |
| `fee`    | Profit from the spread claimable as yield. If `spread` is `0`, `fee` must also be `0`. Otherwise `fee` must be less than or equal to `spread`. |

Range creation validates:

* `high` must be greater than `low`.
* `skew` must be greater than `-2` and less than `2`.
* `spread` must be less than `1`.
* `fee` must be `0` when `spread` is `0`.
* `fee` must be less than or equal to `spread` when `spread` is not `0`.
* `high` and `low` must be valid tick prices for the pair.

#### Create a Range

Send base funds, quote funds, or both. At least one of the two pair denoms must be present.

The range code only reads the pair's base and quote denoms from `funds`. Do not attach unrelated denoms. They are not part of the range deposit logic.

```json
{
  "range": {
    "create": {
      "config": {
        "high": "95000",
        "low": "85000",
        "skew": "0",
        "spread": "0.002",
        "fee": "0.001"
      },
      "slippage": ["90000", "0.005"]
    }
  }
}
```

The optional `slippage` field is `[expected_price, max_relative_difference]`. `expected_price` must be nonzero. In the example above, range creation fails if the resulting range price is more than `0.5%` away from `90000`.

If FIN can calculate a current mid price, the contract balances the sent base and quote amounts for the range and refunds excess funds. If no mid price is available, it creates the range from the sent funds as-is.

TypeScript example:

```ts
import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";

const rpc = "https://gateway.liquify.com/chain/thorchain_rpc";
const finContract = "thor1...";
const sender = "thor1...";
const baseDenom = "btc-btc";
const quoteDenom = "eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48";

const client = await SigningCosmWasmClient.connectWithSigner(rpc, signer);

await client.execute(
  sender,
  finContract,
  {
    range: {
      create: {
        config: {
          high: "95000",
          low: "85000",
          skew: "0",
          spread: "0.002",
          fee: "0.001",
        },
        slippage: ["90000", "0.005"],
      },
    },
  },
  "auto",
  "",
  [
    { denom: baseDenom, amount: "1000000" },
    { denom: quoteDenom, amount: "90000000000" },
  ],
);
```

#### Query One Range

```json
{ "range": "1" }
```

Response shape:

```json
{
  "idx": "1",
  "owner": "thor1owner...",
  "high": "95000",
  "low": "85000",
  "skew": "0",
  "spread": "0.002",
  "fee": "0.001",
  "base": "1000000",
  "quote": "90000000000",
  "price": "90000",
  "ask": "90180",
  "bid": "89820",
  "fees": ["123", "456"]
}
```

`fees` is `[base_fee, quote_fee]`.

Range `base`, `quote`, and `fees` are decimal strings. They can contain fractional values after trades. Bank sends are still whole-token amounts, so claim, withdraw, and close payouts floor the decimal values to integer coin amounts.

#### Query Ranges

```json
{
  "ranges": {
    "owner": "thor1owner...",
    "cursor": null,
    "limit": 30
  }
}
```

`limit` defaults to `30`. Use the last returned `idx` as `cursor` for the next page.

#### Deposit Into a Range

Only the current owner can deposit.

```json
{
  "range": {
    "deposit": {
      "idx": "1"
    }
  }
}
```

Send base funds, quote funds, or both. At least one pair denom must be present. As with create, do not attach unrelated denoms.

#### Claim Range Fees

Only the current owner can claim.

```json
{
  "range": {
    "claim": {
      "idx": "1"
    }
  }
}
```

Claimed fee amounts are floored to whole bank-token units. Fractional remainder stays in the range.

#### Withdraw From a Range

Only the current owner can withdraw.

```json
{
  "range": {
    "withdraw": {
      "idx": "1",
      "amount": "0.25"
    }
  }
}
```

`amount` is a fraction of the range to withdraw. `"0.25"` means 25%; `"1"` means 100%. Values above `1` fail.

#### Close a Range

Only the current owner can close.

```json
{
  "range": {
    "close": {
      "idx": "1"
    }
  }
}
```

Closing removes the range and returns its remaining base, quote, and claimable fees.

#### Transfer a Range

Only the current owner can transfer.

```json
{
  "range": {
    "transfer": {
      "idx": "1",
      "to": "thor1newowner..."
    }
  }
}
```

### Callbacks for Protocol Integrations

Swaps and orders can use callbacks. Ranges do not expose a callback field.

Callbacks are useful when a protocol wants FIN to send output funds to a contract instead of doing a plain bank send. The receiving contract must implement a `callback` execute message.

For swaps, the callback receiver is the `to` address when `to` is set; otherwise it is the signer. For orders, there is no `to` field, so the callback receiver is the account that submitted the order message. In practice, an order callback is mainly for contracts that call FIN themselves.

Callback execute shape received by your contract:

```json
{
  "callback": {
    "data": "base64_encoded_json_data",
    "callback": "base64_encoded_callback_payload"
  }
}
```

For FIN swaps, `data` is an empty JSON object encoded as binary. The output funds are attached to the callback execute message.

For FIN orders, the callback payload is supplied as the second element of the `order` execute tuple:

```json
{
  "order": [
    [
      ["base", { "fixed": "90000" }, "1000000"]
    ],
    "base64_encoded_callback_payload"
  ]
}
```

Use callbacks only when your receiving contract is prepared to handle the funds and decode the callback payload. Wallets and simple routers usually leave `callback` as `null`.

### Events

CosmWasm event types appear in transaction logs with a `wasm-` prefix.

Swap/trade event:

```
wasm-rujira-fin/trade
```

Common trade attributes:

| Attribute | Meaning                                                         |
| --------- | --------------------------------------------------------------- |
| `rate`    | Execution rate for that fill.                                   |
| `offer`   | Amount consumed from the offered asset.                         |
| `bid`     | Amount returned before swap-level fee accounting for that fill. |

Indexer caveat: treat trade event attributes as an ordered list, not a map with unique keys. A single trade event can include provider-specific attributes, and keys such as `price` or `side` can appear more than once when merged liquidity contributes to the fill.

Order events:

```
wasm-rujira-fin/order.create
wasm-rujira-fin/order.withdraw
wasm-rujira-fin/order.increase
wasm-rujira-fin/order.retract
```

Range events:

```
wasm-rujira-fin/range.create
wasm-rujira-fin/range.claim
wasm-rujira-fin/range.deposit
wasm-rujira-fin/range.withdraw
wasm-rujira-fin/range.close
wasm-rujira-fin/range.transfer
wasm-rujira-fin/range.fee
```

Use events for fast UI updates, but keep contract queries as the source of truth after a transaction is indexed.

### UI and UX Checklist

* Show the secured-asset funding step before FIN actions if the user does not have the required app-layer balance.
* Use the user's THOR address for secured-asset balances and FIN signing.
* Query `config` for denoms, fees, tick, and oracle support before rendering a market.
* Query `simulate` before swaps and execute with `min_return`.
* Display base and quote consistently. The second denom from `config.denoms` is the quote denom.
* Show open orders with `remaining` and `filled`; make it clear that filled orders need a later order touch to withdraw.
* Show CCL range ownership, bounds, current `price`, `ask`, `bid`, and `[base, quote]` fees.
* For CCL UIs, default `skew` to `"0"` unless the user is managing an advanced strategy.
* Refresh state after transaction inclusion by re-querying the contract.

### Common Errors and Gotchas

| Issue                                      | Why it happens                                                   | Integrator fix                                                                                     |
| ------------------------------------------ | ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| `invalid denom`                            | The sent fund denom is not one of the pair denoms.               | Query `config` and only use `denoms[0]` or `denoms[1]`.                                            |
| Swap fails with multiple funds             | FIN swaps require exactly one native coin.                       | Send one `funds` entry only.                                                                       |
| `InsufficientReturn`                       | `min_return` or `exact_return` was not met.                      | Requote and ask the user to confirm a new slippage setting.                                        |
| Invalid price / tick error                 | Order fixed price or range bound is not valid for the pair tick. | Round or truncate order prices and range bounds to valid tick values before signing.               |
| Limit swap executes in the wrong direction | Swap limit price is quoted in the token being sent.              | Use normal quote-per-base price for quote-to-base buys, and inverse price for base-to-quote sells. |
| `empty funds` on range create/deposit      | No base or quote funds were sent.                                | Send at least one of the pair denoms and no unrelated funds.                                       |
| `amount > 1` on range withdraw             | Withdraw amount is a fraction and cannot exceed 100%.            | Use `"1"` for full withdrawal.                                                                     |
| Callback does not fire                     | No payout funds were produced, or callback was not supplied.     | Only rely on callback when a payout is expected and the field is set.                              |
| User cannot trade L1 balance directly      | FIN uses app-layer secured-asset bank balances.                  | Secure the asset first with `SECURE+`/`S+`, then submit the FIN transaction.                       |

### Message Reference

#### FIN Queries

```json
{ "config": {} }
```

```json
{ "simulate": { "denom": "btc-btc", "amount": "1000000" } }
```

```json
{ "book": { "limit": 100, "offset": 0 } }
```

```json
{ "order": ["thor1owner...", "base", { "fixed": "90000" }] }
```

```json
{
  "orders": {
    "owner": "thor1owner...",
    "side": null,
    "start_after": null,
    "limit": 10
  }
}
```

```json
{ "range": "1" }
```

```json
{
  "ranges": {
    "owner": "thor1owner...",
    "cursor": null,
    "limit": 30
  }
}
```

#### FIN Executes

```json
{ "swap": { "min_return": "1000000", "to": null, "callback": null } }
```

```json
{
  "order": [
    [
      ["base", { "fixed": "90000" }, "1000000"]
    ],
    null
  ]
}
```

```json
{
  "range": {
    "create": {
      "config": {
        "high": "95000",
        "low": "85000",
        "skew": "0",
        "spread": "0.002",
        "fee": "0.001"
      },
      "slippage": ["90000", "0.005"]
    }
  }
}
```

```json
{ "range": { "deposit": { "idx": "1" } } }
```

```json
{ "range": { "claim": { "idx": "1" } } }
```

```json
{ "range": { "withdraw": { "idx": "1", "amount": "0.25" } } }
```

```json
{ "range": { "close": { "idx": "1" } } }
```

```json
{ "range": { "transfer": { "idx": "1", "to": "thor1newowner..." } } }
```


# RUJI Lend & Borrow

This guide covers integrating RUJI Lending (supply-side) and RUJI Credit (borrow-side CDP loans) into your application.

### Overview

The RUJI Money Market consists of two core contract types:

| Contract                                 | Purpose                      | User Actions                                     |
| ---------------------------------------- | ---------------------------- | ------------------------------------------------ |
| **Ghost Vault** (`rujira-ghost-vault`)   | Lending pools for each asset | Deposit, Withdraw                                |
| **Ghost Credit** (`rujira-ghost-credit`) | CDP loan management          | Create Account, Borrow, Repay, Manage Collateral |

#### Architecture

```
┌─────────────────┐     ┌─────────────────┐
│   Ghost Vault   │     │   Ghost Vault   │
│      (BTC)      │     │     (USDC)      │  ... per asset
└────────┬────────┘     └────────┬────────┘
         │                       │
         │    Borrows from       │
         ▼                       ▼
┌─────────────────────────────────────────┐
│            Ghost Credit                 │
│  (Manages Credit Accounts / CDPs)       │
└─────────────────────────────────────────┘
                    │
                    │ Creates
                    ▼
┌─────────────────────────────────────────┐
│          Credit Account                 │
│   (User's isolated margin account)      │
│   - Holds collateral                    │
│   - Tracks debt positions               │
└─────────────────────────────────────────┘
```

***

### Contract Addresses

#### Mainnet

<table><thead><tr><th width="180">Contract</th><th>Address</th></tr></thead><tbody><tr><td>Ghost Credit</td><td><code>thor1ekkt8wfls055t7f7yznj07j0s4mtndkq546swutzv2de7sfcxptq27duyt</code></td></tr><tr><td>Ghost Vault (BTC)</td><td><code>thor18e6gxcvmqfn06l09gurgwh3urlj9xztqagaslgspl2l74ejuujnqqlzzun</code></td></tr><tr><td>Ghost Vault (ETH)</td><td><code>thor1xufzny7n3565jy3rvglacengpn6eufw7lk5y9h4zxludkfe96q4s9j5uln</code></td></tr><tr><td>Ghost Vault (USDC)</td><td><code>thor1hs6wzyk4tf25ujd7lu07hhnkj4tl38m3wpp6qqw50y5r3e3x7zksnvj3qr</code></td></tr><tr><td>Ghost Vault (USDT)</td><td><code>thor1smdzjdm5q5e5kf6farvcgmxe44uhga2ety68veu2nupf5dzx55xsn3u4rj</code></td></tr><tr><td>Ghost Vault (BCH)</td><td><code>thor1km2sgadhmev34v40evf8qh2yw77hxecakn9nu0g35zdtsf905ehqhqk76r</code></td></tr><tr><td>Ghost Vault (DOGE)</td><td><code>thor1drfu6vrn06gam7fdk07xqmavthgy6rnmnmm2mh4fa047qsny52aqvxuck9</code></td></tr><tr><td>Ghost Vault (LTC)</td><td><code>thor1633kq6mxwn24ezdn38xpngksx8wlu458yesdqf3xhs2cfaan96cs2c3gdz</code></td></tr><tr><td>Ghost Vault (XRP)</td><td><code>thor1cvry7e7uzd89dv4hls5rg5m4xykczzu2qvj8dq5e93c75566tk9q7cya3l</code></td></tr></tbody></table>

> **Note:** For the full list of lending vaults, check <https://rujira.network/developer/deployment> and look for `rujira-ghost-vault`.

#### Stagenet (Testnet)

<table><thead><tr><th width="180">Contract</th><th>Address</th></tr></thead><tbody><tr><td>Ghost Credit</td><td><code>sthor16p65kngn6wtyxrngh2fkwtth4lr9eysvq7atsxt9qhnkknanw8yqza6pqa</code></td></tr><tr><td>Ghost Vault (USDT)</td><td><code>sthor165wfwxnw3vrp35h3ttf23vd0zgs3mt34r8rll50qe0jffun5ts8sdjp38e</code></td></tr></tbody></table>

***

### Supported Assets

All amounts use **8 decimal places** (THORChain standard).

<table><thead><tr><th width="111.640625">Asset</th><th>Denom</th><th width="160.9237060546875">Collateral Ratio</th><th>Lending Vault Receipt Token</th></tr></thead><tbody><tr><td>BTC</td><td><code>BTC-BTC</code></td><td>70%</td><td><code>x/ghost-vault/BTC-BTC</code></td></tr><tr><td>ETH</td><td><code>ETH-ETH</code></td><td>70%</td><td><code>x/ghost-vault/ETH-ETH</code></td></tr><tr><td>USDC</td><td><code>ETH-USDC-0XA0B86991C6218B36C1D19D4A2E9EB0CE3606EB48</code></td><td>70%</td><td><code>x/ghost-vault/ETH-USDC-0XA0B86991C6218B36C1D19D4A2E9EB0CE3606EB48</code></td></tr><tr><td>USDT</td><td><code>ETH-USDT-0XDAC17F958D2EE523A2206206994597C13D831EC7</code></td><td>70%</td><td><code>x/ghost-vault/ETH-USDT-0XDAC17F958D2EE523A2206206994597C13D831EC7</code></td></tr><tr><td>BCH</td><td><code>BCH-BCH</code></td><td>70%</td><td><code>x/ghost-vault/BCH-BCH</code></td></tr><tr><td>DOGE</td><td><code>DOGE-DOGE</code></td><td>70%</td><td><code>x/ghost-vault/DOGE-DOGE</code></td></tr><tr><td>LTC</td><td><code>LTC-LTC</code></td><td>70%</td><td><code>x/ghost-vault/LTC-LTC</code></td></tr><tr><td>XRP</td><td><code>XRP-XRP</code></td><td>70%</td><td><code>x/ghost-vault/XRP-XRP</code></td></tr></tbody></table>

> **Note**: Collateral ratios are configurable via governance. Query the Ghost Credit contract configuration (`{"config": {}}`) for full list of supported collaterals and their current collateral ratio values.

***

### Part 1: Lending Integration (Ghost Vault)

Lenders deposit assets into Ghost Vault contracts and receive receipt tokens that **accrue interest over time**.

#### 1.1 Query: Get Vault Status

Returns current rates, utilization, and pool sizes.

```typescript
// Query message
const queryMsg = { status: {} };

// Example using CosmJS
const result = await client.queryContractSmart(
  GHOST_VAULT_BTC_ADDRESS,
  queryMsg
);
```

**Response:**

```json
{
  "last_updated": "1703001600000000000",
  "utilization_ratio": "0.65",
  "debt_rate": "0.08",
  "lend_rate": "0.052",
  "debt_pool": {
    "size": "650000000000",
    "shares": "620000000000",
    "ratio": "1.048387"
  },
  "deposit_pool": {
    "size": "1000000000000",
    "shares": "980000000000",
    "ratio": "1.020408"
  }
}
```

**Field Explanations:**

* `utilization_ratio`: Percentage of deposits currently borrowed (0.65 = 65%)
* `debt_rate`: Annual borrow APR (0.08 = 8%)
* `lend_rate`: Annual supply APY (0.052 = 5.2%)
* `deposit_pool.ratio`: Value of 1 receipt token in underlying asset

#### 1.2 Query: Get Vault Config

Returns the underlying asset denom and interest rate parameters.

```typescript
const queryMsg = { config: {} };
```

**Response:**

```json
{
  "denom": "btc",
  "interest": {
    "target_utilization": "0.8",
    "base_rate": "0.03",
    "step1": "0.1",
    "step2": "2.0"
  }
}
```

#### 1.3 Calculate User Position Value

To display a user's lending position value:

```typescript
// 1. Get user's receipt token balance
const receiptBalance = await client.getBalance(
  userAddress,
  "x/ghost-vault/btc"
);

// 2. Get current pool ratio
const status = await client.queryContractSmart(
  GHOST_VAULT_BTC_ADDRESS,
  { status: {} }
);

// 3. Calculate underlying value
const underlyingValue = BigInt(receiptBalance.amount) *
  BigInt(status.deposit_pool.size) /
  BigInt(status.deposit_pool.shares);
```

#### 1.4 Execute: Deposit

Deposit assets to receive interest-bearing receipt tokens.

```typescript
const executeMsg = {
  deposit: {}
};

const result = await client.execute(
  userAddress,
  GHOST_VAULT_BTC_ADDRESS,
  executeMsg,
  "auto",
  "",
  [{ denom: "btc", amount: "100000000" }] // 1 BTC (8 decimals)
);
```

**What happens:**

1. User sends underlying asset (e.g., BTC)
2. Contract mints receipt tokens based on current `deposit_pool.ratio`
3. Receipt tokens are sent to user's wallet

#### 1.5 Execute: Withdraw

Burn receipt tokens to retrieve underlying assets plus accrued interest.

```typescript
const executeMsg = {
  withdraw: {}
};

const result = await client.execute(
  userAddress,
  GHOST_VAULT_BTC_ADDRESS,
  executeMsg,
  "auto",
  "",
  [{ denom: "x/ghost-vault/btc", amount: "100000000" }]
);
```

**What happens:**

1. User sends receipt tokens
2. Contract burns receipt tokens
3. Underlying asset (including accrued interest) is returned

> **Note**: Withdrawals may fail if utilization is at 100%. The contract ensures liquidity by incentivizing deposits when utilization is high.

***

### Part 2: Borrowing Integration (Ghost Credit)

Borrowers create Credit Accounts, deposit collateral, and borrow against it.

#### 2.1 Query: Get Credit Config

Returns collateral ratios, liquidation thresholds, and fee parameters.

```typescript
const queryMsg = { config: {} };

const config = await client.queryContractSmart(
  GHOST_CREDIT_ADDRESS,
  queryMsg
);
```

**Response:**

```json
{
  "code_id": 123,
  "collateral_ratios": {
    "btc": "0.7",
    "eth": "0.7",
    "usdc": "0.7"
  },
  "fee_liquidation": "0.01",
  "fee_liquidator": "0.005",
  "liquidation_threshold": "1.0",
  "adjustment_threshold": "0.9",
  "liquidation_max_slip": "0.3"
}
```

**Field Explanations:**

* `collateral_ratios`: Maximum borrowing power per collateral type (0.7 = can borrow up to 70% of value)
* `liquidation_threshold`: LTV at which liquidation is triggered (1.0 = 100%)
* `adjustment_threshold`: Maximum LTV users can manually adjust to (0.9 = 90%)
* `fee_liquidation`: Protocol fee on liquidations (1%)
* `fee_liquidator`: Fee paid to liquidation executors (0.5%)

#### 2.2 Query: Get User's Credit Accounts

```typescript
const queryMsg = {
  accounts: {
    owner: "thor1abc..."
  }
};

const accounts = await client.queryContractSmart(
  GHOST_CREDIT_ADDRESS,
  queryMsg
);
```

**Response:**

```json
{
  "accounts": [
    {
      "owner": "thor1abc...",
      "account": "thor1xyz...",
      "tag": "main",
      "ltv": "0.45",
      "collaterals": [
        {
          "collateral": { "coin": { "denom": "btc", "amount": "100000000" } },
          "value_full": "43000.0",
          "value_adjusted": "30100.0"
        }
      ],
      "debts": [
        {
          "debt": {
            "addr": "thor1xyz...",
            "borrower": { "denom": "usdc", "current": "15000000000" },
            "current": "15000000000",
            "shares": "14500000000"
          },
          "value": "15000.0"
        }
      ],
      "liquidation_preferences": {
        "messages": [],
        "order": { "map": {}, "limit": 100 }
      }
    }
  ]
}
```

**Field Explanations:**

* `account`: The Credit Account contract address (holds collateral)
* `ltv`: Current loan-to-value ratio (debt / adjusted collateral value)
* `value_full`: Full USD value of collateral
* `value_adjusted`: USD value after applying collateral ratio
* `debts[].current`: Current debt amount including accrued interest

#### 2.3 Query: Single Credit Account

```typescript
const queryMsg = {
  account: "thor1xyz..."  // Credit Account address
};
```

#### 2.4 Query: Predict Account Address

Get the deterministic address for a new Credit Account before creation.

```typescript
import { toBase64, toUtf8 } from "@cosmjs/encoding";

const salt = toBase64(toUtf8("my-account-1"));

const queryMsg = {
  predict: {
    owner: "thor1abc...",
    salt: salt
  }
};

const predictedAddress = await client.queryContractSmart(
  GHOST_CREDIT_ADDRESS,
  queryMsg
);
```

#### 2.5 Execute: Create Credit Account

```typescript
import { toBase64, toUtf8 } from "@cosmjs/encoding";

const executeMsg = {
  create: {
    salt: toBase64(toUtf8("unique-salt-123")),
    label: "My BTC Loan",
    tag: "wallet-app"
  }
};

const result = await client.execute(
  userAddress,
  GHOST_CREDIT_ADDRESS,
  executeMsg,
  "auto"
);

// Extract the new account address from events
const accountAddress = result.events
  .find(e => e.type === "wasm-rujira-ghost-credit/create_account")
  ?.attributes.find(a => a.key === "account")?.value;
```

#### 2.6 Execute: Deposit Collateral & Borrow

All Credit Account operations are batched in a single `account` message:

```typescript
const executeMsg = {
  account: {
    addr: "thor1xyz...",  // Credit Account address
    msgs: [
      // First: Send collateral to the account (standard bank send)
      // This is done separately before calling the contract

      // Then: Borrow against collateral
      {
        borrow: {
          denom: "usdc",
          amount: "10000000000"  // 100 USDC
        }
      }
    ]
  }
};
```

**Full flow to deposit collateral and borrow:**

```typescript
// Step 1: Send collateral to Credit Account address
const sendMsg = {
  typeUrl: "/cosmos.bank.v1beta1.MsgSend",
  value: {
    fromAddress: userAddress,
    toAddress: creditAccountAddress,
    amount: [{ denom: "btc", amount: "50000000" }]  // 0.5 BTC
  }
};

// Step 2: Borrow against the collateral
const borrowMsg = {
  account: {
    addr: creditAccountAddress,
    msgs: [
      {
        borrow: {
          denom: "usdc",
          amount: "10000000000"
        }
      }
    ]
  }
};

// Execute both in sequence
await client.signAndBroadcast(userAddress, [sendMsg], "auto");
await client.execute(userAddress, GHOST_CREDIT_ADDRESS, borrowMsg, "auto");
```

#### 2.7 Execute: Repay Debt

```typescript
const executeMsg = {
  account: {
    addr: creditAccountAddress,
    msgs: [
      {
        repay: {
          denom: "usdc",
          amount: "5000000000"  // 50 USDC
        }
      }
    ]
  }
};

// Note: The Credit Account must hold the repayment tokens
// First send USDC to the Credit Account, then call repay
```

#### 2.8 Execute: Withdraw Collateral

```typescript
const executeMsg = {
  account: {
    addr: creditAccountAddress,
    msgs: [
      {
        send: {
          to_address: userAddress,
          funds: [{ denom: "btc", amount: "10000000" }]
        }
      }
    ]
  }
};

// This will fail if it would push LTV above adjustment_threshold
```

#### 2.9 Execute: Close Position (Repay All & Withdraw)

```typescript
const executeMsg = {
  account: {
    addr: creditAccountAddress,
    msgs: [
      // Repay full debt (send slightly more to account for interest)
      { repay: { denom: "usdc", amount: "10050000000" } },
      // Withdraw all collateral
      { send: { to_address: userAddress, funds: [{ denom: "btc", amount: "50000000" }] } }
    ]
  }
};
```

***

### Part 3: Displaying Data in UI

#### 3.1 Lending Position

```typescript
interface LendingPosition {
  asset: string;
  deposited: string;      // Receipt token balance
  depositedValue: string; // Underlying value
  apy: string;            // Current lend rate
}

async function getLendingPosition(
  userAddress: string,
  vaultAddress: string,
  denom: string
): Promise<LendingPosition | null> {
  const receiptDenom = `x/ghost-vault/${denom}`;
  const balance = await client.getBalance(userAddress, receiptDenom);

  if (BigInt(balance.amount) === 0n) {
    return null;
  }

  const status = await client.queryContractSmart(vaultAddress, { status: {} });

  const underlyingValue = BigInt(balance.amount) *
    BigInt(status.deposit_pool.size) /
    BigInt(status.deposit_pool.shares);

  return {
    asset: denom.toUpperCase(),
    deposited: balance.amount,
    depositedValue: underlyingValue.toString(),
    apy: (parseFloat(status.lend_rate) * 100).toFixed(2) + "%"
  };
}
```

#### 3.2 Borrow Position

```typescript
interface BorrowPosition {
  accountAddress: string;
  collaterals: Array<{
    asset: string;
    amount: string;
    valueUsd: string;
  }>;
  debts: Array<{
    asset: string;
    amount: string;
    valueUsd: string;
  }>;
  ltv: string;
  healthFactor: string;  // 1 / ltv (higher is safer)
}

function parseBorrowPosition(accountResponse: any): BorrowPosition {
  return {
    accountAddress: accountResponse.account,
    collaterals: accountResponse.collaterals.map(c => ({
      asset: c.collateral.coin.denom.toUpperCase(),
      amount: c.collateral.coin.amount,
      valueUsd: c.value_full
    })),
    debts: accountResponse.debts.map(d => ({
      asset: d.debt.borrower.denom.toUpperCase(),
      amount: d.debt.current,
      valueUsd: d.value
    })),
    ltv: (parseFloat(accountResponse.ltv) * 100).toFixed(2) + "%",
    healthFactor: (1 / parseFloat(accountResponse.ltv)).toFixed(2)
  };
}
```

#### 3.3 Risk Indicators

Display clear risk levels based on LTV:

| LTV Range  | Health Status | Color          |
| ---------- | ------------- | -------------- |
| 0% - 50%   | Safe          | Green          |
| 50% - 75%  | Moderate      | Yellow         |
| 75% - 90%  | At Risk       | Orange         |
| 90% - 100% | Danger        | Red            |
| > 100%     | Liquidatable  | Red (flashing) |

***

### Part 4: Interest Rate Model

The protocol uses a kinked interest rate model:

```
borrow_rate = base_rate + (utilization / target) * step1           [if utilization <= target]
borrow_rate = base_rate + step1 + ((util - target) / (1 - target)) * step2  [if utilization > target]
```

#### Example Calculation

With parameters: `base_rate=3%`, `target=80%`, `step1=10%`, `step2=200%` , `fee=10%`

| Utilization | Borrow Rate | Supply Rate |
| ----------- | ----------- | ----------- |
| 0%          | 3.0%        | 0.0%        |
| 40%         | 8.0%        | 2.9%        |
| 80%         | 13.0%       | 9.4%        |
| 90%         | 113.0%      | 91.5%       |
| 100%        | 213.0%      | 191.7%      |

> **Supply Rate** = Borrow Rate × Utilization × (1 - Protocol Fee)

***

### Part 5: Fees

#### Protocol Fees

| Fee Type        | Rate                   | Distribution                |
| --------------- | ---------------------- | --------------------------- |
| Interest Fee    | 10% of borrow interest | 50% Protocol, 50% THORChain |
| Liquidation Fee | 1% of repaid debt      | 50% Protocol, 50% THORChain |
| Liquidator Fee  | 0.5% of repaid debt    | Liquidation executor        |

> Fee parameters are configurable via governance. Query contract config for current values.

***

### Part 6: Error Handling

#### Common Errors

| Error               | Cause                             | Solution                               |
| ------------------- | --------------------------------- | -------------------------------------- |
| `Unauthorized`      | Not the account owner             | Verify sender matches account owner    |
| `Unsafe`            | Operation would exceed LTV limit  | Reduce borrow amount or add collateral |
| `ZeroDebt`          | Repaying when no debt exists      | Check debt balance first               |
| `InvalidCollateral` | Asset not in collateral whitelist | Use only supported collateral types    |

#### Transaction Simulation

Always simulate transactions before broadcasting:

```typescript
try {
  const simResult = await client.simulate(
    userAddress,
    [executeMsg],
    ""
  );
  console.log("Estimated gas:", simResult);
} catch (error) {
  console.error("Transaction would fail:", error.message);
}
```

***

### Part 7: Code Examples

#### Complete Lending Flow (TypeScript)

```typescript
import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";
import { GasPrice } from "@cosmjs/stargate";

const GHOST_VAULT_BTC = "<GHOST_VAULT_BTC_ADDRESS>";

async function deposit(
  client: SigningCosmWasmClient,
  sender: string,
  amount: string
) {
  return client.execute(
    sender,
    GHOST_VAULT_BTC,
    { deposit: {} },
    "auto",
    "",
    [{ denom: "btc", amount }]
  );
}

async function withdraw(
  client: SigningCosmWasmClient,
  sender: string,
  receiptAmount: string
) {
  return client.execute(
    sender,
    GHOST_VAULT_BTC,
    { withdraw: {} },
    "auto",
    "",
    [{ denom: "x/ghost-vault/btc", amount: receiptAmount }]
  );
}

async function getPosition(
  client: SigningCosmWasmClient,
  userAddress: string
) {
  const balance = await client.getBalance(userAddress, "x/ghost-vault/btc");
  const status = await client.queryContractSmart(GHOST_VAULT_BTC, { status: {} });

  const underlying = BigInt(balance.amount) *
    BigInt(status.deposit_pool.size) /
    BigInt(status.deposit_pool.shares);

  return {
    receiptTokens: balance.amount,
    underlyingValue: underlying.toString(),
    currentApy: status.lend_rate
  };
}
```

#### Complete Borrowing Flow (TypeScript)

```typescript
const GHOST_CREDIT = "<GHOST_CREDIT_ADDRESS>";

async function createCreditAccount(
  client: SigningCosmWasmClient,
  sender: string,
  tag: string
) {
  const salt = Buffer.from(Date.now().toString()).toString("base64");

  const result = await client.execute(
    sender,
    GHOST_CREDIT,
    {
      create: {
        salt,
        label: `Credit Account ${tag}`,
        tag
      }
    },
    "auto"
  );

  // Parse account address from events
  const event = result.events.find(e =>
    e.type === "wasm-rujira-ghost-credit/create_account"
  );
  return event?.attributes.find(a => a.key === "account")?.value;
}

async function openLoan(
  client: SigningCosmWasmClient,
  sender: string,
  creditAccount: string,
  collateralDenom: string,
  collateralAmount: string,
  borrowDenom: string,
  borrowAmount: string
) {
  // Step 1: Send collateral to credit account
  await client.sendTokens(
    sender,
    creditAccount,
    [{ denom: collateralDenom, amount: collateralAmount }],
    "auto"
  );

  // Step 2: Borrow against collateral
  return client.execute(
    sender,
    GHOST_CREDIT,
    {
      account: {
        addr: creditAccount,
        msgs: [
          { borrow: { denom: borrowDenom, amount: borrowAmount } }
        ]
      }
    },
    "auto"
  );
}

async function repayAndClose(
  client: SigningCosmWasmClient,
  sender: string,
  creditAccount: string,
  debtDenom: string,
  debtAmount: string,
  collateralDenom: string,
  collateralAmount: string
) {
  // Step 1: Send repayment tokens to credit account
  await client.sendTokens(
    sender,
    creditAccount,
    [{ denom: debtDenom, amount: debtAmount }],
    "auto"
  );

  // Step 2: Repay and withdraw
  return client.execute(
    sender,
    GHOST_CREDIT,
    {
      account: {
        addr: creditAccount,
        msgs: [
          { repay: { denom: debtDenom, amount: debtAmount } },
          { send: { to_address: sender, funds: [{ denom: collateralDenom, amount: collateralAmount }] } }
        ]
      }
    },
    "auto"
  );
}
```

***

### Appendix A: Message Reference

#### Ghost Vault Execute Messages

```json
// Deposit
{ "deposit": {} }
// Attach funds: [{ "denom": "btc", "amount": "100000000" }]

// Withdraw
{ "withdraw": {} }
// Attach funds: [{ "denom": "x/ghost-vault/btc", "amount": "100000000" }]
```

#### Ghost Vault Query Messages

```json
// Get config
{ "config": {} }

// Get status (rates, utilization)
{ "status": {} }
```

#### Ghost Credit Execute Messages

```json
// Create account
{
  "create": {
    "salt": "base64-encoded-salt",
    "label": "My Account",
    "tag": "optional-tag"
  }
}

// Account operations (batched)
{
  "account": {
    "addr": "thor1...",
    "msgs": [
      { "borrow": { "denom": "usdc", "amount": "1000000000" } },
      { "repay": { "denom": "usdc", "amount": "500000000" } },
      { "send": { "to_address": "thor1...", "funds": [...] } },
      { "transfer": "thor1new_owner..." },
      { "set_preference_order": { "denom": "btc", "after": "eth" } },
      { "set_preference_msgs": [...] }
    ]
  }
}
```

#### Ghost Credit Query Messages

```json
// Get config
{ "config": {} }

// Get single account
{ "account": "thor1..." }

// Get accounts by owner
{ "accounts": { "owner": "thor1...", "tag": "optional" } }

// Get all accounts (paginated)
{ "all_accounts": { "cursor": "thor1...", "limit": 100 } }

// Predict account address
{ "predict": { "owner": "thor1...", "salt": "base64..." } }

// Get borrow capacity
{ "borrows": {} }
```

***

### Appendix B: Response Types

#### StatusResponse (Ghost Vault)

```typescript
interface StatusResponse {
  last_updated: string;      // Nanosecond timestamp
  utilization_ratio: string; // Decimal (0-1)
  debt_rate: string;         // Annual borrow rate
  lend_rate: string;         // Annual supply rate
  debt_pool: PoolResponse;
  deposit_pool: PoolResponse;
}

interface PoolResponse {
  size: string;    // Total underlying tokens
  shares: string;  // Total shares issued
  ratio: string;   // size/shares ratio
}
```

#### AccountResponse (Ghost Credit)

```typescript
interface AccountResponse {
  owner: string;
  account: string;
  tag: string;
  ltv: string;
  collaterals: CollateralResponse[];
  debts: DebtResponse[];
  liquidation_preferences: LiquidationPreferences;
}

interface CollateralResponse {
  collateral: { coin: { denom: string; amount: string } };
  value_full: string;     // USD value
  value_adjusted: string; // USD value * collateral_factor
}

interface DebtResponse {
  debt: {
    addr: string;
    borrower: { denom: string; current: string; /* ... */ };
    current: string;
    shares: string;
  };
  value: string;  // USD value
}
```


# RUJI Liquidations

This guide covers integrating RUJI Liquidations (bidding on at-risk collateral) into your application, and guidance to build a Liquidation Solver.

RUJI Liquidations is a public marketplace for acquiring collateral from at-risk borrowing positions. Unlike traditional DeFi liquidations that favor MEV bots, all liquidated collateral on Rujira is sold via market orders on [RUJI Trade](/core-products/ruji-trade) orderbook DEX, and anyone can bid to catch the wicks by placing [Tracking Orders](/core-products/ruji-trade#key-features) at a discount to market price.

Market price is defined by [THORChain enshrined oracle](https://dev.thorchain.org/bifrost/oracle.html). To bid on at-risk collateral, users must place tracking orders at a fixed discount to oracle price, the order then rest in the orderbook like a limit order with the limit price updating every block as the oracle price changes. When a liquidation occurs via a market order, it pushes the price below the oracle price and fills the tracking orders from the lowest discount to the highest discount.

### Two Integration Paths

There are two ways to participate in RUJI Liquidations:

#### Path 1: Bid on Liquidated Collateral (for end users)

Allow users to place tracking orders on RUJI Trade at a discount to oracle price. When liquidations occur and your order gets filled, you acquire collateral at your specified discount.

**Best for:**

* Users who want to accumulate assets at discounted prices
* Passive participation without running infrastructure
* DCA strategies during market volatility

[**Bidding Integration Guide**](/developers/ruji-product-integration-guides/ruji-liquidations/bidding-on-liquidations)

***

#### Path 2: Build a Liquidation Solver (for developers)

Build off-chain infrastructure that monitors at-risk positions, calculates optimal liquidation routes, and executes liquidations to earn the 0.5% executor fee.

**Best for:**

* Developers building trading infrastructure
* Teams with quantitative/algorithmic capabilities

[**Solver Integration Guide**](/developers/ruji-product-integration-guides/ruji-liquidations/liquidation-solvers)

***

### How Liquidations Work

When a Credit Account's loan-to-value (LTV) ratio exceeds its liquidation threshold, the position becomes liquidable:

```
┌─────────────────────────────────────────┐
│         Credit Account                  │
│  Collateral: 1 BTC ($40,000)            │
│  Debt: 32,000 USDC                      │
│  LTV: 80% (Safe)                        │
└─────────────────────────────────────────┘
                    │
                    │  BTC price drops
                    ▼
┌─────────────────────────────────────────┐
│         Credit Account                  │
│  Collateral: 1 BTC ($30,000)            │
│  Debt: 32,000 USDC                      │
│  LTV: 107% (Liquidatable)               │
└─────────────────────────────────────────┘
                    │
                    │  Liquidation triggered
                    ▼
┌─────────────────────────────────────────┐
│  1. Solver executes liquidation         │
│  2. Collateral swapped via RUJI Trade   │
│  3. Bidders' orders filled at discount  │
│  4. Debt repaid to lending pool         │
│  5. Solver earns 0.5% fee               │
└─────────────────────────────────────────┘
```

***

### Fee Structure

| Fee             | Rate                | Recipient                   |
| --------------- | ------------------- | --------------------------- |
| Liquidation Fee | 1% of repaid debt   | 50% Protocol, 50% THORChain |
| Solver Fee      | 0.5% of repaid debt | Liquidation executor        |

***

### Contract Addresses

<table><thead><tr><th width="220">Contract</th><th>Address</th></tr></thead><tbody><tr><td>Ghost Credit</td><td><code>thor1ekkt8wfls055t7f7yznj07j0s4mtndkq546swutzv2de7sfcxptq27duyt</code></td></tr><tr><td>RUJI Trade (BTC/USDC)</td><td><code>thor1dwsnlqw3lfhamc5dz3r57hlsppx3a2n2d7kppccxfdhfazjh06rs5077sz</code></td></tr><tr><td>RUJI Trade (ETH/USDC)</td><td><code>thor1tnd06uswj8033d0kzd5d7zre73u3uc44r2vvez26z5m4kr68vtusf2snva</code></td></tr></tbody></table>

> **Note:** For the full list of RUJI Trade pairs, check <https://rujira.network/developer/deployment> and look for `rujira-fin`.


# Bidding on Liquidations

This guide covers how to integrate liquidation bidding into your application, allowing users to acquire collateral at discounted prices when CDP positions are liquidated.

### Overview

When Credit Account positions become undercollateralized, their collateral is sold through RUJI Trade orderbooks. Users can place [**tracking orders**](#ruji-trade-tracking-orders) at a discount to the current oracle price (defined by [THORChain enshrined oracle](https://dev.thorchain.org/bifrost/oracle.html)). When liquidations route through these orders, users acquire collateral at their specified discount.

#### How It Works

```
1. User places order: "Buy BTC at 5% below oracle price"
   └─> Order sits in RUJI Trade orderbook

2. Borrower's position becomes liquidatable
   └─> Liquidation solver executes liquidation

3. Solver swaps collateral (BTC) for debt token (USDC) via a market order on RUJI Trade
   └─> If the market order creates a large enough wick, the order gets filled at 5% discount

4. User withdraws filled order
   └─> Receives BTC acquired at discounted price
```

#### Key Benefits

* **No active monitoring** - Set orders and wait
* **Guaranteed discount** - Only fills at your specified discount to market price, typically at the local low as this is when liquidations tend to happen
* **Pro-rata fills** - Fair distribution when multiple bidders at same price
* **Flexibility** - Withdraw unfilled orders anytime

***

### RUJI Trade Tracking Orders

**Tracking orders** track the oracle price with a basis point adjustment:

* `{ "oracle": 0 }` = Exactly at oracle price
* `{ "oracle": -100 }` = Oracle price minus 1% (100 bps)
* `{ "oracle": -500 }` = Oracle price minus 5% (500 bps)
* `{ "oracle": 100 }` = Oracle price plus 1%

***

### Placing Liquidation Bids

#### Order Message Structure

```typescript
const executeMsg = {
  order: [
    // Array of order targets
    [
      ["quote", { "oracle": -500 }, "100000000000"]  // [side, price, amount]
    ],
    null  // Optional callback
  ]
};
```

#### Parameters

| Field    | Type                  | Description                                       |
| -------- | --------------------- | ------------------------------------------------- |
| `side`   | `"base"` or `"quote"` | Which token you're offering                       |
| `price`  | `"oracle":` `integer` | Price expressed as a deviation from Oracle in bps |
| `amount` | `Uint128` or `null`   | Target amount (`null` = withdraw all)             |

#### Side Explanation

For a BTC/USDC pair:

* **Base** = BTC (first token)
* **Quote** = USDC (second token)

To **buy BTC at a discount** (typical liquidation bid on the long side):

* Side: `"quote"` (you're offering USDC)
* Price: `{ "oracle": -500 }` (5% below oracle)
* You receive BTC when filled

To **sell BTC at a premium** (to liquidate a position on the short side):

* Side: `"base"` (you're offering BTC)
* Price: `{ "oracle": 500 }` (5% above oracle)

***

### Code Examples

#### Place a Bid (TypeScript)

```typescript
import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";

const FIN_BTC_USDC = "<FIN_BTC_USDC_ADDRESS>";

async function placeLiquidationBid(
  client: SigningCosmWasmClient,
  sender: string,
  usdcAmount: string,
  discountBps: number  // e.g., 500 for 5% discount
) {
  const executeMsg = {
    order: [
      [
        // Buy BTC at X% discount to oracle
        ["quote", { oracle: -discountBps }, usdcAmount]
      ],
      null
    ]
  };

  return client.execute(
    sender,
    FIN_BTC_USDC,
    executeMsg,
    "auto",
    "",
    [{ denom: "usdc", amount: usdcAmount }]
  );
}

// Place 1000 USDC bid at 5% discount
await placeLiquidationBid(client, myAddress, "100000000000", 500);
```

#### Query Your Orders

```typescript
const queryMsg = {
  orders: {
    owner: myAddress
  }
};

const orders = await client.queryContractSmart(FIN_BTC_USDC, queryMsg);
console.log(orders);
```

**Response:**

```json
{
  "orders": [
    {
      "side": "quote",
      "price": { "oracle": -500 },
      "offer": "100000000000",
      "filled": "25000000000",
      "created_at": "1703001600000000000"
    }
  ]
}
```

#### Withdraw Filled Orders

```typescript
async function withdrawFilledOrders(
  client: SigningCosmWasmClient,
  sender: string
) {
  // Setting amount to null withdraws all filled amounts
  const executeMsg = {
    order: [
      [
        ["quote", { oracle: -500 }, null]  // null = withdraw
      ],
      null
    ]
  };

  return client.execute(
    sender,
    FIN_BTC_USDC,
    executeMsg,
    "auto"
  );
}
```

#### Modify Order Amount

```typescript
async function modifyBid(
  client: SigningCosmWasmClient,
  sender: string,
  newAmount: string,
  currentAmount: string,
  discountBps: number
) {
  const executeMsg = {
    order: [
      [
        ["quote", { oracle: -discountBps }, newAmount]
      ],
      null
    ]
  };

  // Calculate net change in funds
  const diff = BigInt(newAmount) - BigInt(currentAmount);

  const funds = diff > 0n
    ? [{ denom: "usdc", amount: diff.toString() }]
    : [];

  return client.execute(
    sender,
    FIN_BTC_USDC,
    executeMsg,
    "auto",
    "",
    funds
  );
}
```

***

### Multiple Orders at Different Discounts

Place a ladder of bids at various discount levels:

```typescript
async function placeBidLadder(
  client: SigningCosmWasmClient,
  sender: string
) {
  const executeMsg = {
    order: [
      [
        // 3% discount - highest priority, fills first
        ["quote", { oracle: -300 }, "30000000000"],
        // 5% discount
        ["quote", { oracle: -500 }, "40000000000"],
        // 10% discount - fills only in severe liquidations
        ["quote", { oracle: -1000 }, "30000000000"]
      ],
      null
    ]
  };

  const totalUsdc = "100000000000";  // 1000 USDC total

  return client.execute(
    sender,
    FIN_BTC_USDC,
    executeMsg,
    "auto",
    "",
    [{ denom: "usdc", amount: totalUsdc }]
  );
}
```

***

### How Orders Get Filled

#### Fill Priority

When liquidations swap collateral, orders are filled by price priority:

1. Orders closest to oracle price fill first
2. At same price level, orders fill **pro-rata** (proportional to size)
3. Tracking orders adjust automatically as oracle price moves

#### Pro-Rata Example

```
Pool at -5% discount has:
- Alice: 1000 USDC (50%)
- Bob:   600 USDC (30%)
- Carol: 400 USDC (20%)

Liquidation swaps 500 USDC worth:
- Alice receives: 250 USDC worth of BTC
- Bob receives:   150 USDC worth of BTC
- Carol receives: 100 USDC worth of BTC
```

#### Bid Pool Mechanics

Orders at the same price level share a **bid pool**. The contract tracks:

* `offer`: Your original USDC amount
* `filled`: Amount converted to BTC
* `product_snapshot`: Used for pro-rata calculation

***

### Fees

| Fee       | Rate   | When                           |
| --------- | ------ | ------------------------------ |
| Maker Fee | 0.075% | On withdrawal of filled orders |
| No fee    | -      | Cancelling unfilled orders     |

> Fee rates are configurable per trading pair. Query the pair config for current values.

***

### Risks and Considerations

#### Market Risk

* Collateral value may drop further after you acquire it
* Oracle price may differ from actual market price

#### Liquidity Risk

* Orders may not fill if liquidations don't occur at your desired discount
* Capital is locked while order is active

#### Timing Risk

* During high volatility, liquidations happen rapidly
* Orders at shallow discounts fill first

#### Recommendations

1. **Diversify discount levels** - Place orders at multiple price points
2. **Monitor positions** - Check filled amounts regularly
3. **Set realistic discounts** - Too deep = rarely fills, too shallow = less profit
4. **Understand the asset** - Only bid on collateral you want to hold

***

### Supported Trading Pairs

Liquidation flow routes through RUJI Trade pairs. Common pairs:

<table><thead><tr><th width="150">Pair</th><th>Contract</th></tr></thead><tbody><tr><td>BTC/USDC</td><td><code>thor1dwsnlqw3lfhamc5dz3r57hlsppx3a2n2d7kppccxfdhfazjh06rs5077sz</code></td></tr><tr><td>ETH/USDC</td><td><code>thor1tnd06uswj8033d0kzd5d7zre73u3uc44r2vvez26z5m4kr68vtusf2snva</code></td></tr><tr><td>BCH/USDC</td><td><code>thor1s4jpxtz0jsh6elyqcdujd303ptefz53gknmcp437rm9ykxnfhysqrm5hze</code></td></tr><tr><td>DOGE/USDC</td><td><code>thor1w8agselh7k2e4ty369v39lngkckljxfafm35d06f7wj3ar90h2esv75t7p</code></td></tr><tr><td>LTC/USDC</td><td><code>thor1ks9qq0nwv7qxtnznesys6ylflwruqlf85er6zls4erwgzkvw0m0qs3rghz</code></td></tr><tr><td>XRP/USDC</td><td><code>thor14v89h32ztmfg9d230cjly7ac26fvdkhgq7nkntsw4uy2f3yh2v7qrz6hsw</code></td></tr></tbody></table>

> **Note:** For the full list of RUJI Trade pairs, check <https://rujira.network/developer/deployment> and look for `rujira-fin`.

***

### Message Reference

#### ExecuteMsg::Order

```json
{
  "order": [
    [
      ["quote", { "oracle": -500 }, "100000000000"],
      ["quote", { "oracle": -1000 }, "50000000000"]
    ],
    null
  ]
}
```

#### QueryMsg::Orders

```json
{
  "orders": {
    "owner": "thor1..."
  }
}
```

#### QueryMsg::Config

```json
{
  "config": {}
}
```

Returns pair configuration including denoms, fees, and oracles.


# Liquidation Solvers

This guide covers building liquidation solvers (also called "path finders") - off-chain infrastructure that monitors at-risk positions, calculates optimal liquidation routes, and executes liquidations

### Overview

#### The Path Finding Challenge

RUJI supports **multiple collateral types** within its borrowing system. Each Credit Account can hold various assets (BTC, ETH, XRP, DOGE, etc.) as collateral against different debt positions. When liquidation is needed, each collateral type requires a unique swap path through RUJI Trade to convert it to the debt token.

**The challenge**: Calculating optimal multi-hop swap routes across multiple collateral types is computationally intensive - too expensive for on-chain execution. This creates an opportunity for external solvers.

#### How Solvers Earn

```
┌─────────────────────────────────────────────────────────┐
│                    Solver Workflow                      │
├─────────────────────────────────────────────────────────┤
│                                                         │
│  1. Monitor Credit Accounts for LTV >= 100%             │
│                                                         │
│  2. Analyze underwater position:                        │
│     - Multiple collateral types (BTC, ETH, DOGE, etc.)  │
│     - Debt denominated in USDC, USDT, etc.              │
│     - User liquidation preferences                      │
│                                                         │
│  3. Calculate optimal liquidation path:                 │
│     - Query RUJI Trade pools for liquidity              │
│     - Find best swap routes per collateral              │
│     - Respect preference order constraints              │
│     - Minimize slippage across all swaps                │
│                                                         │
│  4. Execute liquidation on-chain                        │
│     - Submit optimized route via ExecuteMsg::Liquidate  │
│     - Earn 0.5% of repaid debt as fee                   │
│                                                         │
└─────────────────────────────────────────────────────────┘
```

#### Permissionless Participation

Anyone can build and run a liquidation solver. There's no whitelist or approval process, the protocol is open to all participants. Competition drives better execution for the protocol and users.

***

### Fee Structure

| Fee             | Rate                    | Recipient                   |
| --------------- | ----------------------- | --------------------------- |
| Liquidation Fee | 1% of repaid debt       | 50% Protocol, 50% THORChain |
| **Solver Fee**  | **0.5% of repaid debt** | **You (the liquidator)**    |

Example: Liquidating a position with 10,000 USDC debt earns \~50 USDC for the solver.

***

### Contract Addresses

<table><thead><tr><th width="220">Contract</th><th>Address</th></tr></thead><tbody><tr><td>Ghost Credit</td><td><code>thor1ekkt8wfls055t7f7yznj07j0s4mtndkq546swutzv2de7sfcxptq27duyt</code></td></tr><tr><td>RUJI Trade (BTC/USDC)</td><td><code>thor1dwsnlqw3lfhamc5dz3r57hlsppx3a2n2d7kppccxfdhfazjh06rs5077sz</code></td></tr><tr><td>RUJI Trade (ETH/USDC)</td><td><code>thor1tnd06uswj8033d0kzd5d7zre73u3uc44r2vvez26z5m4kr68vtusf2snva</code></td></tr></tbody></table>

> **Note:** For the full list of RUJI Trade pairs, check <https://rujira.network/developer/deployment> and look for `rujira-fin`.

***

### Querying Liquidatable Positions

#### Find All Accounts (Paginated)

```typescript
const queryMsg = {
  all_accounts: {
    cursor: null,  // Start from beginning
    limit: 100
  }
};

const response = await client.queryContractSmart(
  GHOST_CREDIT_ADDRESS,
  queryMsg
);

// Filter for liquidatable positions
const liquidatable = response.accounts.filter(
  acc => parseFloat(acc.ltv) >= 1.0
);
```

#### Check Single Account

```typescript
const queryMsg = {
  account: "thor1creditaccount..."
};

const account = await client.queryContractSmart(
  GHOST_CREDIT_ADDRESS,
  queryMsg
);

if (parseFloat(account.ltv) >= 1.0) {
  console.log("Account is liquidatable");
  console.log("Collaterals:", account.collaterals);
  console.log("Debts:", account.debts);
  console.log("Preferences:", account.liquidation_preferences);
}
```

#### Account Response Structure

```typescript
interface AccountResponse {
  owner: string;
  account: string;
  tag: string;
  ltv: string;  // >= "1.0" means liquidatable
  collaterals: Array<{
    collateral: { coin: { denom: string; amount: string } };
    value_full: string;      // USD value
    value_adjusted: string;  // USD value after collateral factor
  }>;
  debts: Array<{
    debt: {
      addr: string;
      borrower: { denom: string; current: string };
      current: string;  // Current debt amount
      shares: string;
    };
    value: string;  // USD value
  }>;
  liquidation_preferences: LiquidationPreferences;
}
```

***

### Path Finding Strategy

#### Multi-Collateral Accounts

A typical underwater account might look like:

```
Collaterals:
  - 0.5 BTC  ($20,000)
  - 2.0 ETH  ($6,000)
  - 50,000 DOGE ($5,000)

Debt:
  - 32,000 USDC

LTV: 103% (liquidatable)

Preferences:
  - Liquidate DOGE before ETH
  - Liquidate ETH before BTC
```

#### Route Optimization Goals

1. **Minimize total slippage** across all swaps
2. **Respect user preferences** (mandatory)
3. **Maximize your profit** (fee - gas costs)
4. **Ensure LTV drops** below liquidation threshold

#### Querying RUJI Trade Liquidity

For each collateral type, query the corresponding RUJI Trade pool:

```typescript
async function getPoolLiquidity(finAddress: string) {
  const status = await client.queryContractSmart(finAddress, { status: {} });
  const book = await client.queryContractSmart(finAddress, { book: {} });

  return {
    baseReserve: status.base_reserve,
    quoteReserve: status.quote_reserve,
    orderbook: book.orders
  };
}
```

#### Building Multi-Hop Routes

For exotic collateral types, you may need multi-hop swaps:

```
DOGE → BTC → USDC  (if DOGE/USDC pool has low liquidity)
```

```typescript
function buildMultiHopRoute(
  collateralDenom: string,
  debtDenom: string,
  pools: Map<string, PoolInfo>
): SwapRoute {
  // Direct route
  const directPool = pools.get(`${collateralDenom}/${debtDenom}`);
  if (directPool && directPool.liquidity > MIN_LIQUIDITY) {
    return { hops: [{ pool: directPool.address, offer: collateralDenom }] };
  }

  // Multi-hop via BTC
  const toBtc = pools.get(`${collateralDenom}/btc`);
  const btcToDebt = pools.get(`btc/${debtDenom}`);
  if (toBtc && btcToDebt) {
    return {
      hops: [
        { pool: toBtc.address, offer: collateralDenom },
        { pool: btcToDebt.address, offer: "btc" }
      ]
    };
  }

  throw new Error(`No route found for ${collateralDenom} → ${debtDenom}`);
}
```

***

### Executing Liquidations

#### Liquidate Message Structure

```typescript
const executeMsg = {
  liquidate: {
    addr: "thor1creditaccount...",
    msgs: [
      // LiquidateMsg array - your optimized route
    ]
  }
};
```

#### LiquidateMsg Types

```typescript
// Execute a swap on RUJI Trade
{
  execute: {
    contract_addr: "thor1finpool...",
    msg: "<base64-encoded-swap-msg>",
    funds: [{ denom: "btc", amount: "10000000" }]
  }
}

// Repay debt with tokens now in the account
{
  repay: "usdc"
}
```

#### Example: Multi-Collateral Liquidation

```typescript
import { toBase64, toUtf8 } from "@cosmjs/encoding";

async function liquidateMultiCollateral(
  client: SigningCosmWasmClient,
  sender: string,
  account: AccountResponse
) {
  const msgs: LiquidateMsg[] = [];

  // Process collaterals in preference order
  const orderedCollaterals = sortByPreference(
    account.collaterals,
    account.liquidation_preferences.order
  );

  for (const collateral of orderedCollaterals) {
    const denom = collateral.collateral.coin.denom;
    const amount = collateral.collateral.coin.amount;

    // Find best swap route for this collateral
    const route = await findBestRoute(denom, "usdc", amount);

    // Build swap message
    const swapMsg = {
      swap: { min_return: route.minReturn }
    };

    msgs.push({
      execute: {
        contract_addr: route.poolAddress,
        msg: toBase64(toUtf8(JSON.stringify(swapMsg))),
        funds: [{ denom, amount }]
      }
    });
  }

  // Final step: repay debt
  msgs.push({ repay: "usdc" });

  return client.execute(
    sender,
    GHOST_CREDIT_ADDRESS,
    { liquidate: { addr: account.account, msgs } },
    "auto"
  );
}
```

***

### Handling User Preferences

#### Preference Order

Users can specify liquidation order constraints:

```typescript
// If user set: "liquidate DOGE only after ETH is exhausted"
// Your route MUST liquidate ETH before DOGE

function sortByPreference(
  collaterals: Collateral[],
  preferenceOrder: PreferenceOrder
): Collateral[] {
  // Build dependency graph from preferences
  // Topological sort to get valid liquidation order
  // Throw if constraints cannot be satisfied
}
```

#### Preference Messages

Users can pre-define swap routes. These execute BEFORE your messages:

```typescript
// User's preference messages run first (with error tolerance)
// Then your liquidator messages run
// If preference succeeds, it may reduce work needed
```

**Important**: User preference messages use `reply_always` - if they fail, liquidation continues with your messages. Don't assume preferences will succeed.

***

### Validation Rules

Your liquidation must satisfy:

#### 1. Position Must Be Underwater

```
ltv >= liquidation_threshold (1.0)
```

#### 2. No Over-Liquidation

After liquidation:

```
ltv >= adjustment_threshold (0.9)
```

Liquidate only enough to bring LTV below 100%, not all the way to 0%.

#### 3. Slippage Limit

```
(collateral_spent_usd - debt_repaid_usd) / collateral_spent_usd <= liquidation_max_slip
```

Default `liquidation_max_slip` is 30%. Bad routes that exceed this will fail.

#### 4. Preference Order Respected

Violating user preference order causes immediate failure.

***

### Building a Liquidation Bot

#### Architecture

```
┌─────────────────────────────────────────────────────────┐
│                   Liquidation Bot                       │
├─────────────────────────────────────────────────────────┤
│                                                         │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐ │
│  │  Monitor    │───▶│   Analyze   │───▶│  Execute    │ │
│  │  Service    │    │   Service   │    │  Service    │ │
│  └─────────────┘    └─────────────┘    └─────────────┘ │
│        │                  │                  │         │
│        ▼                  ▼                  ▼         │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐ │
│  │ Ghost Credit│    │ RUJI Trade  │    │  Broadcast  │ │
│  │  Queries    │    │  Queries    │    │     Tx      │ │
│  └─────────────┘    └─────────────┘    └─────────────┘ │
│                                                         │
└─────────────────────────────────────────────────────────┘
```

#### Monitor Service

```typescript
class LiquidationMonitor {
  private cursor: string | null = null;

  async scan(): Promise<AccountResponse[]> {
    const liquidatable: AccountResponse[] = [];

    while (true) {
      const { accounts } = await this.client.queryContractSmart(
        GHOST_CREDIT_ADDRESS,
        { all_accounts: { cursor: this.cursor, limit: 100 } }
      );

      for (const account of accounts) {
        if (parseFloat(account.ltv) >= 1.0) {
          liquidatable.push(account);
        }
      }

      if (accounts.length < 100) {
        this.cursor = null;
        break;
      }
      this.cursor = accounts[accounts.length - 1].account;
    }

    return liquidatable;
  }
}
```

#### Analyze Service

```typescript
class RouteAnalyzer {
  async analyze(account: AccountResponse): Promise<LiquidationPlan | null> {
    // 1. Parse collaterals and debts
    const collaterals = this.parseCollaterals(account);
    const debts = this.parseDebts(account);

    // 2. Sort by preference order
    const ordered = this.sortByPreference(collaterals, account.liquidation_preferences);

    // 3. Calculate minimum liquidation needed
    const targetLtv = 0.95;  // Target 95% LTV (below 100% threshold)
    const minRepay = this.calculateMinRepay(account, targetLtv);

    // 4. Find optimal routes for each collateral
    const routes: SwapRoute[] = [];
    let totalRepay = 0;

    for (const collateral of ordered) {
      if (totalRepay >= minRepay) break;

      const route = await this.findRoute(collateral, debts[0].denom);
      routes.push(route);
      totalRepay += route.expectedOutput;
    }

    // 5. Estimate profitability
    const gasEstimate = this.estimateGas(routes);
    const fee = totalRepay * 0.005;
    const profit = fee - gasEstimate;

    if (profit <= 0) return null;

    return { routes, expectedProfit: profit };
  }
}
```

#### Execute Service

```typescript
class LiquidationExecutor {
  async execute(account: AccountResponse, plan: LiquidationPlan) {
    const msgs = this.buildMessages(plan);

    try {
      const result = await this.client.execute(
        this.sender,
        GHOST_CREDIT_ADDRESS,
        { liquidate: { addr: account.account, msgs } },
        "auto"
      );

      console.log(`Liquidation successful: ${result.transactionHash}`);
      return result;
    } catch (error) {
      console.error(`Liquidation failed: ${error.message}`);
      throw error;
    }
  }
}
```

#### Main Loop

```typescript
async function main() {
  const monitor = new LiquidationMonitor(client);
  const analyzer = new RouteAnalyzer(client);
  const executor = new LiquidationExecutor(client, senderAddress);

  while (true) {
    try {
      const liquidatable = await monitor.scan();

      for (const account of liquidatable) {
        const plan = await analyzer.analyze(account);

        if (plan && plan.expectedProfit > MIN_PROFIT) {
          await executor.execute(account, plan);
        }
      }

      await sleep(5000);  // Poll interval
    } catch (error) {
      console.error("Error in main loop:", error);
      await sleep(10000);
    }
  }
}
```

***

### Profitability Calculation

```typescript
function calculateProfitability(
  account: AccountResponse,
  routes: SwapRoute[],
  gasPriceUsd: number
): ProfitAnalysis {
  // Total debt being repaid
  const totalRepay = routes.reduce((sum, r) => sum + r.expectedOutput, 0);

  // Solver fee (0.5%)
  const solverFee = totalRepay * 0.005;

  // Estimated gas cost
  const gasUnits = routes.length * 250_000;  // ~250k per swap
  const gasCost = gasUnits * gasPriceUsd;

  // Net profit
  const netProfit = solverFee - gasCost;

  // Slippage impact
  const totalCollateralValue = routes.reduce((sum, r) => sum + r.inputValueUsd, 0);
  const slippage = (totalCollateralValue - totalRepay) / totalCollateralValue;

  return {
    totalRepay,
    solverFee,
    gasCost,
    netProfit,
    slippage,
    profitable: netProfit > 0 && slippage <= 0.3
  };
}
```

***

### Error Handling

#### Common Errors

| Error                                                  | Cause                   | Solution                        |
| ------------------------------------------------------ | ----------------------- | ------------------------------- |
| `Safe`                                                 | Account LTV < 100%      | Position not liquidatable (yet) |
| `Unsafe`                                               | Final LTV still >= 100% | Liquidation route insufficient  |
| `LiquidationMaxSlipExceeded`                           | Slippage > 30%          | Find better swap routes         |
| `Invalid liquidation attempted {coin} before {before}` | Preference violated     | Reorder collateral liquidation  |

#### Retry Strategy

```typescript
async function attemptWithRetry(
  account: AccountResponse,
  maxRetries: number = 3
) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      // Re-analyze with fresh liquidity data
      const plan = await analyzer.analyze(account);
      if (!plan) return null;

      return await executor.execute(account, plan);
    } catch (error) {
      if (error.message.includes("Safe")) {
        // Position recovered, stop trying
        return null;
      }
      if (i === maxRetries - 1) throw error;

      await sleep(1000 * (i + 1));  // Backoff
    }
  }
}
```

***

### Message Reference

#### Liquidate (Execute)

```json
{
  "liquidate": {
    "addr": "thor1creditaccount...",
    "msgs": [
      {
        "execute": {
          "contract_addr": "thor1finpool...",
          "msg": "eyJzd2FwIjp7fX0=",
          "funds": [{ "denom": "btc", "amount": "50000000" }]
        }
      },
      {
        "execute": {
          "contract_addr": "thor1finpool2...",
          "msg": "eyJzd2FwIjp7fX0=",
          "funds": [{ "denom": "eth", "amount": "200000000" }]
        }
      },
      {
        "repay": "usdc"
      }
    ]
  }
}
```

***

### Configuration Parameters

Query the Ghost Credit config for current parameters:

```typescript
const config = await client.queryContractSmart(
  GHOST_CREDIT_ADDRESS,
  { config: {} }
);
```

| Parameter               | Description                | Typical Value |
| ----------------------- | -------------------------- | ------------- |
| `liquidation_threshold` | LTV triggering liquidation | 1.0 (100%)    |
| `adjustment_threshold`  | Min LTV after liquidation  | 0.9 (90%)     |
| `liquidation_max_slip`  | Max allowed slippage       | 0.3 (30%)     |
| `fee_liquidation`       | Protocol fee               | 0.01 (1%)     |
| `fee_liquidator`        | Your fee                   | 0.005 (0.5%)  |
| `collateral_ratios`     | Collateral factors         | varies        |


# Staking (RUJI, bRUNE, TCY)

Technical documentation for wallets, portfolio apps, staking dashboards, and user-facing apps integrating staking markets powered by the Rujira staking contract.

This guide is scoped to user-owned staking positions. It does not cover protocol/operator revenue setup, revenue converter administration, or contract `sudo` messages.

### Overview

The Rujira staking contract is generic. A deployed staking market can be configured for RUJI, bRUNE, TCY, or another supported bond token. Each market has its own contract address and config.

A staking market supports two user paths:

| Path            | User sends                | User receives                                | Reward behavior                                                                           |
| --------------- | ------------------------- | -------------------------------------------- | ----------------------------------------------------------------------------------------- |
| Account staking | The market's `bond_denom` | Account staking position (non-transferable)  | Rewards accrue as `revenue_denom` and are claimed manually.                               |
| Liquid staking  | The market's `bond_denom` | Liquid staking receipt tokens (transferable) | Rewards are converted into more `bond_denom`, increasing the value of each receipt token. |

Always query the staking contract config before building transactions. The contract tells you which token to stake through `bond_denom` and which reward token account stakers can claim through `revenue_denom`.

#### Existing Staking Markets

Use this table as an integration hint, not as the source of truth. The live contract config should still be queried before every staking flow.

| Market        | Bond denom | Typical display | Liquid receipt denom | Receipt display |
| ------------- | ---------- | --------------- | -------------------- | --------------- |
| RUJI staking  | `x/ruji`   | `RUJI`          | `x/staking-x/ruji`   | `sRUJI`         |
| bRUNE staking | `x/brune`  | `bRUNE`         | `x/staking-x/brune`  | `ybRUNE`        |
| TCY staking   | `tcy`      | `TCY`           | `x/staking-tcy`      | `sTCY`          |

The bank metadata for `x/ruji`, `x/brune`, and the liquid receipt denoms uses 8 display decimals. The `tcy` supply exists on chain, but the bank metadata endpoint may not return a base metadata object for `tcy`; clients should use the chain/app asset registry or a maintained token list as a display fallback.

#### Who This Guide Is For

| Integrator             | Typical integration                                                                                                          |
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| Wallets                | Show RUJI balance, account stake, pending revenue, liquid receipt balance, and sign bond/claim/withdraw/unbond transactions. |
| Portfolio apps         | Display account positions, pending rewards, liquid share positions, and pool status.                                         |
| Staking UIs            | Provide standard staking and auto-compounding staking flows.                                                                 |
| Card or repayment apps | Let users claim staking revenue and then use the claimed funds in the app's own repayment flow.                              |

#### Prerequisites

* The user needs a THOR/Rujira app-layer address.
* The user needs the staking `bond_denom`; for RUJI staking this is `x/ruji`.
* Account staking rewards are paid in `revenue_denom`, which should be read from contract config.
* Liquid staking receipt token denom is derived from the bond denom: `x/staking-<bond_denom>`.
* All `Uint128` amounts are strings in JSON.

Useful references:

* RUJI token [FAQ](https://docs.rujira.network/how-it-works/frequently-asked-questions/ruji-token)
* Rujira [secured assets](https://docs.rujira.network/developers/secured-assets)
* RUJI bank [metadata](https://api-thorchain.rorcual.xyz/cosmos/bank/v1beta1/denoms_metadata/x%2Fruji)
* Deployment [list](https://rujira.network/developer/deployment)

### Architecture

```
Wallet / staking UI / portfolio app
        |
        | CosmWasm query / execute
        v
Rujira staking contract
        |
        +-- Account staking
        |       +-- bond bond_denom
        |       +-- claim revenue_denom
        |       +-- withdraw bond_denom + claimed rewards
        |
        +-- Liquid staking
                +-- bond bond_denom
                +-- mint x/staking-<bond_denom>
                +-- convert revenue into more bond_denom
                +-- unbond receipt token for proportional bond_denom
```

{% hint style="info" %}
Do not call `settle` directly. It is an internal self-call used by the staking contract after revenue conversion.
{% endhint %}

### Contract Address and Config

The current staking contract addresses should be read from official deployment data. If static addresses are needed in a downstream guide, verify them first against the Rujira deployment page and look for the relevant `rujira-staking` instances.

Model staking markets by contract address:

```ts
type StakingMarket = {
  label: string;
  contract: string;
  expectedBondDenom?: string;
};

const markets: StakingMarket[] = [
  {
    label: "RUJI",
    contract: "thor1...", // Verify from deployment data.
    expectedBondDenom: "x/ruji",
  },
  {
    label: "bRUNE",
    contract: "thor1...", // Verify from deployment data.
    expectedBondDenom: "x/brune",
  },
  {
    label: "TCY",
    contract: "thor1...", // Verify from deployment data.
    expectedBondDenom: "tcy",
  },
];
```

Query config before rendering the staking UI:

```json
{ "config": {} }
```

Example response shape:

```json
{
  "bond_denom": "x/ruji",
  "revenue_denom": "rune",
  "revenue_converter": [
    "thor1converter...",
    "base64_encoded_execute_msg",
    "1000000"
  ],
  "fee": ["0.05", "thor1fees..."]
}
```

| Field               | Meaning for user integrations                                                                                           |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `bond_denom`        | Token users bond into this staking market. Examples: `x/ruji`, `x/brune`, `tcy`.                                        |
| `revenue_denom`     | Token account stakers claim as rewards.                                                                                 |
| `revenue_converter` | Converter used internally to compound liquid staking rewards. Wallet UIs should display or ignore this, not execute it. |
| `fee`               | Optional protocol fee on distributable revenue, shaped as `[percentage, recipient]`.                                    |

Do not hardcode the reward token from product copy. Different staking markets can pay different `revenue_denom` assets, and the live config is the source of truth for transaction builders.

### Staking Concepts

#### Account Staking vs. Liquid Staking

Account staking and liquid staking use the same bond token, but they behave differently.

| Concept           | Account staking                     | Liquid staking                               |
| ----------------- | ----------------------------------- | -------------------------------------------- |
| Execute namespace | `account`                           | `liquid`                                     |
| User sends        | `bond_denom`                        | `bond_denom`                                 |
| User receives     | Stored account position             | Receipt token balance                        |
| Rewards           | Claimed manually as `revenue_denom` | Converted into more `bond_denom` in the pool |
| Exit              | `account.withdraw`                  | `liquid.unbond` with receipt token funds     |

#### Liquid Receipt Denom

The liquid receipt denom is:

```
x/staking-<bond_denom>
```

Examples:

| Bond denom | Receipt denom       |
| ---------- | ------------------- |
| `x/ruji`   | `x/staking-x/ruji`  |
| `x/brune`  | `x/staking-x/brune` |
| `tcy`      | `x/staking-tcy`     |

Derive this from config in code:

```ts
function receiptDenom(bondDenom: string): string {
  return `x/staking-${bondDenom}`;
}
```

Do not assume the receipt denom from the display symbol. Use the bank denom.

#### Revenue Distribution Timing

Revenue distribution is lazy. Sending `revenue_denom` to the staking contract does not immediately update every account. The contract distributes pending revenue at the start of the next account or liquid staking execute.

For UI, this means:

* `status` shows the current stored state plus raw undistributed revenue.
* `account.pending_revenue` can change after any staking action triggers distribution.
* Re-query `status`, `account`, and bank balances after every staking transaction.

### Query Integration

#### Query Status

```json
{ "status": {} }
```

Response shape:

```json
{
  "account_bond": "100000000",
  "assigned_revenue": "5000000",
  "liquid_bond_shares": "75000000",
  "liquid_bond_size": "78000000",
  "undistributed_revenue": "1000000"
}
```

| Field                   | Meaning                                                                        |
| ----------------------- | ------------------------------------------------------------------------------ |
| `account_bond`          | Total `bond_denom` bonded in account staking.                                  |
| `assigned_revenue`      | Total `revenue_denom` already assigned to account stakers but not yet claimed. |
| `liquid_bond_shares`    | Total liquid receipt shares issued.                                            |
| `liquid_bond_size`      | Total `bond_denom` backing the liquid staking pool.                            |
| `undistributed_revenue` | `revenue_denom` currently in the contract but not yet distributed.             |

For liquid staking display, the simple pool ratio is:

```
bond_per_share = liquid_bond_size / liquid_bond_shares
```

If `liquid_bond_shares` is zero, show the ratio as zero or unavailable.

#### Query Account

```json
{
  "account": {
    "addr": "thor1user..."
  }
}
```

Response shape:

```json
{
  "addr": "thor1user...",
  "bonded": "100000000",
  "pending_revenue": "2500000"
}
```

`account` only works for addresses that have an account staking record. If the query returns not found, show a zero account position:

```json
{
  "addr": "thor1user...",
  "bonded": "0",
  "pending_revenue": "0"
}
```

There is no account-list query and no pagination in the staking contract.

### Account Staking Integration

Account staking is the standard staking path where the user bonds the market token and manually claims rewards.

#### Bond

```json
{
  "account": {
    "bond": {}
  }
}
```

Funds:

```json
[
  { "denom": "<config.bond_denom>", "amount": "100000000" }
]
```

Use `config.bond_denom` for the funds denom. Send only the bond denom.

If the account already has pending rewards, `bond` claims those rewards first and sends them to the user before increasing the bonded amount.

#### Claim

```json
{
  "account": {
    "claim": {}
  }
}
```

Claim is nonpayable. Send no funds.

If there are claimable rewards, the contract sends `revenue_denom` to the user. If the user already has an account staking record and rewards are zero, the transaction can still complete and emit a zero-amount claim event. If the user has never bonded, do not offer claim; there is no account record yet.

#### Withdraw

Partial withdraw:

```json
{
  "account": {
    "withdraw": {
      "amount": "50000000"
    }
  }
}
```

Full withdraw:

```json
{
  "account": {
    "withdraw": {
      "amount": null
    }
  }
}
```

Withdraw is nonpayable. Send no funds.

Withdraw requires an existing account staking record. It always claims pending rewards first. The payout can include both `bond_denom` and `revenue_denom`.

#### TypeScript Example: Account Bond

```ts
import { CosmWasmClient, SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";

const rpc = "See Developer Endpoints";
const sender = "thor1...";
const amount = "100000000"; // Base units for the selected bond denom.

const market = {
  label: "bRUNE",
  contract: "thor1...", // Verify from deployment data.
  expectedBondDenom: "x/brune",
};

const stakingContract = market.contract;

const queryClient = await CosmWasmClient.connect(rpc);

const config = await queryClient.queryContractSmart(stakingContract, {
  config: {},
});

if (market.expectedBondDenom && config.bond_denom !== market.expectedBondDenom) {
  throw new Error(`Unexpected bond denom: ${config.bond_denom}`);
}

const signingClient = await SigningCosmWasmClient.connectWithSigner(rpc, signer);

const tx = await signingClient.execute(
  sender,
  stakingContract,
  {
    account: {
      bond: {},
    },
  },
  "auto",
  "",
  [{ denom: config.bond_denom, amount }],
);
```

#### TypeScript Example: Claim and Use Rewards

This is the wallet/user flow a card or repayment app should use. The staking contract claims rewards to the user first; the app then uses the user's resulting `revenue_denom` balance in its own repayment flow.

```ts
async function queryAccountOrZero(addr: string) {
  try {
    return await queryClient.queryContractSmart(stakingContract, {
      account: {
        addr,
      },
    });
  } catch (error) {
    if (String(error).toLowerCase().includes("not found")) {
      return {
        addr,
        bonded: "0",
        pending_revenue: "0",
      };
    }

    throw error;
  }
}

const before = await queryAccountOrZero(sender);

if (BigInt(before.pending_revenue) > 0n) {
  await signingClient.execute(
    sender,
    stakingContract,
    {
      account: {
        claim: {},
      },
    },
    "auto",
    "",
    [],
  );
}

// After the claim is indexed, query the user's revenue_denom bank balance
// and use that balance in the app's own repayment transaction.
```

### Liquid Staking Integration

Liquid staking is the auto-compounding path. The user bonds the market token and receives receipt tokens. As revenue is converted into more `bond_denom`, the pool size grows and each receipt token represents more underlying bond token.

#### Bond

```json
{
  "liquid": {
    "bond": {}
  }
}
```

Funds:

```json
[
  { "denom": "<config.bond_denom>", "amount": "100000000" }
]
```

The contract mints receipt tokens to the user. Derive the receipt denom from config:

```
receipt_denom = x/staking-<config.bond_denom>
```

#### Unbond

```json
{
  "liquid": {
    "unbond": {}
  }
}
```

Funds:

```json
[
  { "denom": "<receipt_denom>", "amount": "100000000" }
]
```

Liquid unbond burns receipt tokens and returns the user's proportional `bond_denom`. The returned amount depends on the current pool ratio and is floor-rounded by share-pool math.

#### TypeScript Example: Liquid Bond and Unbond

```ts
function liquidReceiptDenom(bondDenom: string): string {
  return `x/staking-${bondDenom}`;
}

const config = await queryClient.queryContractSmart(stakingContract, {
  config: {},
});

const receipt = liquidReceiptDenom(config.bond_denom);

await signingClient.execute(
  sender,
  stakingContract,
  {
    liquid: {
      bond: {},
    },
  },
  "auto",
  "",
  [{ denom: config.bond_denom, amount: "100000000" }],
);

await signingClient.execute(
  sender,
  stakingContract,
  {
    liquid: {
      unbond: {},
    },
  },
  "auto",
  "",
  [{ denom: receipt, amount: "50000000" }],
);
```

### Events

CosmWasm event types usually appear in indexed transaction logs with a `wasm-` prefix.

Account staking events:

```
wasm-rujira-staking/account.bond
wasm-rujira-staking/account.claim
wasm-rujira-staking/account.withdraw
```

| Event              | Attributes                   |
| ------------------ | ---------------------------- |
| `account.bond`     | `owner`, `amount`            |
| `account.claim`    | `owner`, `amount`            |
| `account.withdraw` | `owner`, `amount`, `rewards` |

Liquid staking events:

```
wasm-rujira-staking/liquid.bond
wasm-rujira-staking/liquid.unbond
```

| Event           | Attributes                    |
| --------------- | ----------------------------- |
| `liquid.bond`   | `owner`, `amount`, `shares`   |
| `liquid.unbond` | `owner`, `shares`, `returned` |

Internal settlement event:

```
wasm-rujira-staking/settle
```

`settle` has a `returned` attribute and is emitted by the contract's internal revenue-conversion flow. User interfaces can index it, but users should not build or sign `settle` messages.

Use events for fast UI updates, but re-query contract state and bank balances after the transaction is indexed.

### UI and UX Checklist

* Show account staking and liquid staking as separate modes.
* Query `config` first and use its `bond_denom` and `revenue_denom`.
* Display the bond token from bank metadata or a maintained token registry. Do not hardcode a single staking denom.
* For TCY, handle metadata fallback because `tcy` may not return a base bank metadata object even though the denom exists on chain.
* For account staking, show `bonded` and `pending_revenue`.
* For account staking, explain that rewards are claimable manually in `revenue_denom`.
* For liquid staking, show receipt token balance and estimated underlying `bond_denom`.
* For liquid staking, explain that rewards compound by increasing pool value, not by sending revenue directly to the user.
* For card or repayment apps, claim rewards first, then use the user's claimed balance in the app repayment flow.
* Prevent users from attaching funds to `claim` or `withdraw`.
* Prevent users from sending `config.bond_denom` to `liquid.unbond`; it requires the receipt token.
* Refresh `status`, `account`, and bank balances after every transaction.

### Common Errors and Gotchas

| Issue                                                   | Why it happens                                           | Integrator fix                                                     |
| ------------------------------------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------ |
| Wrong funds denom on bond                               | Account and liquid bond require `bond_denom`.            | Query `config` and send only `config.bond_denom`.                  |
| Claim sent with funds                                   | `account.claim` is nonpayable.                           | Send no funds.                                                     |
| Withdraw sent with funds                                | `account.withdraw` is nonpayable.                        | Send no funds.                                                     |
| Liquid unbond sends the bond token                      | `liquid.unbond` burns receipt tokens, not bond tokens.   | Send `x/staking-<bond_denom>` funds.                               |
| Account query fails for a new user                      | The account record does not exist until the user bonds.  | Treat not found as zero bonded and zero pending revenue.           |
| Claim or withdraw fails for a new user                  | There is no account staking record yet.                  | Disable claim and withdraw until the user has an account position. |
| Pending rewards look stale                              | Distribution runs lazily during staking executes.        | Re-query after transactions and explain update timing.             |
| User expects liquid rewards as the account reward token | Liquid rewards are converted into more bond token value. | Show pool ratio and receipt-token underlying value.                |
| Tiny liquid bond mints zero shares                      | Share math floors issuance.                              | Block very small deposits or explain the failure.                  |
| Unbond amount exceeds receipt balance                   | Share pool rejects over-unbonding.                       | Check the user's receipt token balance before signing.             |

### Message Reference

#### Queries

```json
{ "config": {} }
```

```json
{ "status": {} }
```

```json
{ "account": { "addr": "thor1user..." } }
```

#### Executes

```json
{ "account": { "bond": {} } }
```

```json
{ "account": { "claim": {} } }
```

```json
{ "account": { "withdraw": { "amount": "1000000" } } }
```

```json
{ "account": { "withdraw": { "amount": null } } }
```

```json
{ "liquid": { "bond": {} } }
```

```json
{ "liquid": { "unbond": {} } }
```

Do **not** use this internal message in wallet or user integrations:

```json
{ "settle": { "balance": "0" } }
```


# Liquidy Swap API

Liquidy provide an easy way to integrate any SecuredAsset-to-SecuredAsset swap on Rujira, finding the best route between any two tokens through any of the RUJI Trade orderbooks. Liquidy API can also be used to find arbitrage opportunities across the orderbooks.

Liquidy charges 0.10% fee per swap and the optimize routing still often result for a net positive outcome for end users. Liquidy router support both a referral fee model (typically 10% of the 0.10% protocol fee shared with the integrating partner) and an affiliate fee model (additional fee the partner can add on top of the protocol fee - 100% retained by the partner).&#x20;

Developer reference and live playground: <https://liquidy.finance/developer/swap-api>

API base: `https://api.liquidy.finance`

## General

### How it works

The Liquidy Swap API is an off-chain router. It finds the best route between any two tokens through any of the RUJI Trade books and returns a `swap` message you can submit directly — it does not move funds for you.

1. Get supported tokens — GET `/swap/tokens` returns the denoms, decimals, and display metadata for tokens the router can quote and route.
2. Request a route — POST `/swap/route` (single route) or `/swap/sroute` (split route) with input denom, amount in atomics, output denom, and slippage.
3. Use the best route — the response ranks paths; typically take `routes[0]`. Each route includes expected output, price impact, and `tx.swap` (stages + `min_return`).
4. Execute on chain — send a CosmWasm execute to the router contract with `routes[0].tx` as the message and attach the input token as `funds` (full `input.amount` for a single route).

Router contract: `thor1efrmwk6fzhaugu056mz3nkq4vl0fgpfacm3gp6fhgrdkm4q8rrmsd5a6r5`

API base: `https://api.liquidy.finance`

Swap history (indexed transactions): `https://api.liquidy.finance/history`

#### Message shape

A single-route swap is one `MsgExecuteContract`: the `msg` field is the API's `tx` object; `funds` carries the coin you are swapping in.

```
{
  "contract": "thor1efrmwk6fzhaugu056mz3nkq4vl0fgpfacm3gp6fhgrdkm4q8rrmsd5a6r5",
  "msg": routes[0].tx,
  "funds": [{ "denom": "<input-denom>", "amount": "<input-amount-atomics>" }]
}
```

Split routes return multiple legs — broadcast one execute per leg, each funded with that leg's `split.amount`, not the full input.

#### Signing with CosmJS

Use [CosmJS](https://github.com/cosmos/cosmjs) to sign and broadcast on Rujira / Thorchain-style chains:

* `@cosmjs/cosmwasm-stargate` — `SigningCosmWasmClient` and `.execute()` for contract calls
* `@cosmjs/stargate` — wallet, fees, and `GasPrice`

```
import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";

await client.execute(
  senderAddress,
  routerContract,
  route.tx,                        // routes[0].tx from the API
  "auto",
  undefined,
  [{ denom: inputDenom, amount: inputAmount }],
);
```

Optional (recommended): simulate first with the router's `simulate` query (see Swap tab) to verify the returned amount before broadcasting.

## Swap

#### Endpoints

* GET `https://api.liquidy.finance/swap/tokens`\
  List supported swap tokens
* POST `https://api.liquidy.finance/swap/route`\
  Single-route request — one path, full input amount
* POST `https://api.liquidy.finance/swap/sroute`\
  Split-route request — multiple legs, split input per call
* QUERY `thor1efrmwk6fzhaugu056mz3nkq4vl0fgpfacm3gp6fhgrdkm4q8rrmsd5a6r5 — simulate` \
  On-chain simulate — stages from route/sroute tx.swap

#### Router contract

`thor1efrmwk6fzhaugu056mz3nkq4vl0fgpfacm3gp6fhgrdkm4q8rrmsd5a6r5`

#### GET `https://api.liquidy.finance/swap/tokens`

Returns all supported input/output tokens.

Example Response:

```
[
  {
    "code": "rune",
    "denom": "rune",
    "coingecko_id": "thorchain",
    "decimals": 8,
    "name": "rune"
  },
  {
    "code": "btc",
    "denom": "btc-btc",
    "coingecko_id": "bitcoin",
    "decimals": 8,
    "name": "btc"
  },
  {
    "code": "dai",
    "denom": "eth-dai-0x6b175474e89094c44da98b954eedeac495271d0f",
    "coingecko_id": "dai",
    "decimals": 8,
    "name": "dai"
  },
  {
    "code": "usdc",
    "denom": "eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
    "coingecko_id": "usd-coin",
    "decimals": 8,
    "name": "usdc"
  }
]
```

#### POST `https://api.liquidy.finance/swap/route`

Single-route request. Returns ranked routes with a ready-to-execute tx.swap for the full input amount.

`/route` finds one swap path for the entire input amount. Execute a single contract call using `routes[0].tx.swap` and fund it with the full `input.amount`.

Request body:

```
{
  "input": {
    "denom": "eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
    "amount": "500000000",
    "slippage": "0.01"
  },
  "output": {
    "denom": "rune"
  }
}
```

Example Response:

```
Best — USDC → RUJI → RUNE
Returns 11.601979 RUNE (1160197875 atomics)
```

```
{
  "direct_route_comparison": "0.0003237745838446937",
  "routes": [
    {
      "amount": "1160197875",
      "price_impact": 0.00044361,
      "fee": 0.011613592340000001,
      "route": [
        "RUJI",
        "RUNE"
      ],
      "tx": {
        "swap": {
          "stages": [
            {
              "address": "thor1j9euq8fjd5zdxdkx7auser7kp84tmwtx3snuptpec6azakzwv3dqq6ahwp",
              "denom": "x/ruji"
            },
            {
              "address": "thor17cawwg2lsnvcne69fek6nsqkf8snma6gc5ccceshul86rl0u3q4s5l5d0a",
              "denom": "eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
            }
          ],
          "min_return": {
            "denom": "rune",
            "amount": "1148595896"
          }
        }
      }
    }
  ],
  "timestamp": 1785078193415
}
```

Execute message (tx + funds):

```
{
  "typeUrl": "/cosmwasm.wasm.v1.MsgExecuteContract",
  "value": {
    "sender": "<your-address>",
    "contract": "thor1efrmwk6fzhaugu056mz3nkq4vl0fgpfacm3gp6fhgrdkm4q8rrmsd5a6r5",
    "msg": {
      "swap": {
        "stages": [
          {
            "address": "thor1j9euq8fjd5zdxdkx7auser7kp84tmwtx3snuptpec6azakzwv3dqq6ahwp",
            "denom": "x/ruji"
          },
          {
            "address": "thor17cawwg2lsnvcne69fek6nsqkf8snma6gc5ccceshul86rl0u3q4s5l5d0a",
            "denom": "eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
          }
        ],
        "min_return": {
          "denom": "rune",
          "amount": "1148595896"
        }
      }
    },
    "funds": [
      {
        "denom": "eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
        "amount": "500000000"
      }
    ]
  }
}
```

#### POST `https://api.liquidy.finance/swap/sroute`

Split-route request. May return multiple legs — fund each contract call with that leg's split.amount. Set split\_step (1–10) on input.

`/sroute` may return multiple legs, each with a `split.fraction` and `split.amount`. When split routing runs, you must execute one contract call per leg, sending that leg's `split.amount` as the coin — not the full input amount.

**split\_step — practical meaning**

| split\_step | Behavior                                               |
| ----------- | ------------------------------------------------------ |
| 1           | Finest search (99%, 98%, … 1%) — slowest, most precise |
| 5           | Default balance                                        |
| 10          | Coarsest allowed — fastest, may miss optimal split     |

Smaller `split_step` = more fraction trials = more route simulations = better chance of finding the best split, but slower.

It only matters when split routing actually runs; otherwise `/sroute` returns a single 100% leg and behaves like a single-route `/route` call (one contract call with the full input amount).

Request body:

```
{
  "input": {
    "denom": "eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
    "amount": "500000000",
    "slippage": "0.01",
    "split_step": 3
  },
  "output": {
    "denom": "rune"
  }
}
```

Example Response:

```
Best — USDC → RUJI → RUNE
100% — in 5 USDC (500000000 atomics)
Returns 11.601979 RUNE (1160197875 atomics)
```

```
{
  "single_route_comparison": "0.00",
  "routes": [
    {
      "split": {
        "fraction": 1,
        "amount": "500000000"
      },
      "amount": "1160197875",
      "price_impact": 0.00044361,
      "fee": 0.011613592340000001,
      "route": [
        "RUJI",
        "RUNE"
      ],
      "tx": {
        "swap": {
          "stages": [
            {
              "address": "thor1j9euq8fjd5zdxdkx7auser7kp84tmwtx3snuptpec6azakzwv3dqq6ahwp",
              "denom": "x/ruji"
            },
            {
              "address": "thor17cawwg2lsnvcne69fek6nsqkf8snma6gc5ccceshul86rl0u3q4s5l5d0a",
              "denom": "eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
            }
          ],
          "min_return": {
            "denom": "rune",
            "amount": "1148595896"
          }
        }
      }
    }
  ],
  "timestamp": 1785078580779
}
```

#### QUERY `thor1efrmwk6fzhaugu056mz3nkq4vl0fgpfacm3gp6fhgrdkm4q8rrmsd5a6r5 — simulate`

On-chain simulation via the router contract simulate query. Stages define the output token; copy them from routes\[n].tx.swap in a /route or /sroute response.

Simulate query:

`simulate.coin` is the input token and amount to simulate. `simulate.stages` is the hop sequence through the router — the last stage's denom is the output token.

Copy `stages` straight from a `/route` or `/sroute` response under `tx.swap`:

```
routes[0].tx.swap.stages

"tx": {
  "swap": {
    "stages": [ ... ],   // ← use this array
    "min_return": { ... }
  }
}
```

For split routes, use each leg's `split.amount` as `simulate.coin.amount` with that leg's stages. Example shape:

```
{
  "simulate": {
    "coin": { "denom": "...", "amount": "..." },
    "stages": [
      { "address": "thor1...", "denom": "..." },
      { "address": "thor1...", "denom": "..." }
    ]
  }
}
```

RPC endpoint (public default):

```
https://rpc-thorchain.rorcual.xyz
```

Simulate query:

```
{
  "simulate": {
    "coin": {
      "denom": "eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
      "amount": "500000000"
    },
    "stages": [
      {
        "address": "thor1j9euq8fjd5zdxdkx7auser7kp84tmwtx3snuptpec6azakzwv3dqq6ahwp",
        "denom": "x/ruji"
      },
      {
        "address": "thor17cawwg2lsnvcne69fek6nsqkf8snma6gc5ccceshul86rl0u3q4s5l5d0a",
        "denom": "eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
      }
    ]
  }
}
```

Simulate response:

`Returned: 11.601979 RUNE (1160197874 atomics)`

```
{
  "returned": "1160197874",
  "fee": "1161360"
}
```

## Arbitrage

#### Endpoints

* GET `https://api.liquidy.finance/swap/arbs`\
  Scan whitelisted denoms (\~$5–10 each) for arb opportunities
* POST `https://api.liquidy.finance/swap/arbroute`\
  Optimized circular arb route
* QUERY `thor1efrmwk6fzhaugu056mz3nkq4vl0fgpfacm3gp6fhgrdkm4q8rrmsd5a6r5 — simulate`\
  On-chain simulate — stages from route/sroute tx.swap

#### GET `https://api.liquidy.finance/swap/arbs?minPercent={min}`

Checks 7 whitelisted denoms using default amounts (\~$5–10 each). Returns circular arb opportunities where profit exceeds minPercent.

`minPercent={0.1}`

Checks 7 denoms with default amounts (\~$5–10 each):

* USDC · 5 USDC
* BTC · 0.0001 BTC
* ETH · 0.005 ETH
* RUNE · 20 RUNE
* LQDY · 50 LQDY
* RUJI · 30 RUJI
* TCY · 100 TCY

Example Response when arb exists:

```
{
  "results": [
    {
      "denom": "eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
      "hasArbitrage": true,
      "inputAmount": "500000000",
      "outputAmount": "502150000",
      "routeCount": 4,
      "bestRoute": {
        "amount": "502150000",
        "price_impact": 0.00012,
        "fee": 0.0050215,
        "route": [
          "LQDY",
          "BTC",
          "USDC"
        ],
        "tx": {
          "swap": {
            "stages": [
              {
                "address": "thor1dwsnlqw3lfhamc5dz3r57hlsppx3a2n2d7kppccxfdhfazjh06rs5077sz",
                "denom": "btc-btc"
              },
              {
                "address": "thor1t76lvqjq7avt6kxnul4pt0zaq6y06fhkw29wxs5rm4kt873s6y9sdp8rxf",
                "denom": "thor.lqdy"
              },
              {
                "address": "thor1ax94w4rldvdgc4xgsfwgve7g7xfyxhvuvquvx57vtmr6y4alev0qw3mlvr",
                "denom": "eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
              }
            ],
            "min_return": {
              "denom": "eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
              "amount": "500000000"
            },
            "affiliate_code": "arb"
          }
        }
      }
    }
  ],
  "meta": {
    "denomsChecked": [
      {
        "denom": "eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
        "amount": "500000000"
      },
      {
        "denom": "btc-btc",
        "amount": "10000"
      },
      {
        "denom": "rune",
        "amount": "2000000000"
      }
    ],
    "denomsCheckedCount": 3,
    "minPercent": 0.1
  }
}
```

#### POST `https://api.liquidy.finance/swap/arbroute`

Optimized circular arb steps for one denom and amount.

Request body:

```
{
  "denom": "eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
  "amount": "500000000"
}
```

Example Response:

`Step 1× — USDC → LQDY → ETH → USDC`\
`In 5 USDC (500000000 atomics) → Out 5.086411 USDC (498641116 atomics)`

```
[
  {
    "multiplier": 1,
    "inputAmount": "500000000",
    "outputAmount": "508641116",
    "hasArbitrage": false,
    "route": {
      "amount": "508641116",
      "price_impact": 0.00223304,
      "fee": 0.00509150266,
      "route": [
        "LQDY",
        "ETH",
        "USDC"
      ],
      "tx": {
        "swap": {
          "stages": [
            {
              "address": "thor1tnd06uswj8033d0kzd5d7zre73u3uc44r2vvez26z5m4kr68vtusf2snva",
              "denom": "eth-eth"
            },
            {
              "address": "thor15gdwez2jt8tdpukx4x4upul4pjtl8f4hx8dsj9a7htsszmas89gqqkx3kf",
              "denom": "thor.lqdy"
            },
            {
              "address": "thor1ax94w4rldvdgc4xgsfwgve7g7xfyxhvuvquvx57vtmr6y4alev0qw3mlvr",
              "denom": "eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
            }
          ],
          "min_return": {
            "denom": "eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
            "amount": "500000000"
          },
          "affiliate_code": "arb"
        }
      }
    },
    "timestamp": 1785079404497
  }
]
```

#### QUERY `thor1efrmwk6fzhaugu056mz3nkq4vl0fgpfacm3gp6fhgrdkm4q8rrmsd5a6r5 — simulate`&#x20;

On-chain simulation via the router contract simulate query. Stages define the output token; copy them from routes\[n].tx.swap in a /route or /sroute response.

Simulate query:

`simulate.coin` is the input token and amount to simulate. `simulate.stages` is the hop sequence through the router — the last stage's denom is the output token.

Copy `stages` straight from a `/route` or `/sroute` response under `tx.swap`:

```
routes[0].tx.swap.stages

"tx": {
  "swap": {
    "stages": [ ... ],   // ← use this array
    "min_return": { ... }
  }
}
```

For split routes, use each leg's `split.amount` as `simulate.coin.amount` with that leg's stages. Example shape:

```
{
  "simulate": {
    "coin": { "denom": "...", "amount": "..." },
    "stages": [
      { "address": "thor1...", "denom": "..." },
      { "address": "thor1...", "denom": "..." }
    ]
  }
}
```

RPC endpoint (public default)

```
https://rpc-thorchain.rorcual.xyz
```

Simulate query:

```
{
  "simulate": {
    "coin": {
      "denom": "eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
      "amount": "500000000"
    },
    "stages": [
      {
        "address": "thor1tnd06uswj8033d0kzd5d7zre73u3uc44r2vvez26z5m4kr68vtusf2snva",
        "denom": "eth-eth"
      },
      {
        "address": "thor15gdwez2jt8tdpukx4x4upul4pjtl8f4hx8dsj9a7htsszmas89gqqkx3kf",
        "denom": "thor.lqdy"
      },
      {
        "address": "thor1ax94w4rldvdgc4xgsfwgve7g7xfyxhvuvquvx57vtmr6y4alev0qw3mlvr",
        "denom": "eth-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
      }
    ]
  }
}
```

Simulate response:

`Returned: 4.98745 USDC (498745002 atomics)`

```
{
  "returned": "498745002",
  "fee": "499245"
}
```

## History

#### Endpoints

* GET `https://api.liquidy.finance/history`\
  Indexed swap transaction history

#### GET `https://api.liquidy.finance/history`

Query indexed swap transactions. Use query parameters to filter by sender, affiliate, tx hash, type (swap|arbitrage on latest), or fetch top swappers by volume.

Query mode:

* Latest: Paginated recent swaps (page, limit, optional type=swap|arbitrage)
* By sender: Swaps initiated by wallet address
* By tx hash: All swap legs in one transaction
* By affiliate: Swaps attributed to an affiliate address
* Top swappers: Volume leaderboard (period=1d|7d|30d)

<table><thead><tr><th width="165">Query mode</th><th width="165">type</th><th>GET</th></tr></thead><tbody><tr><td>Latest</td><td>all</td><td><code>https://api.liquidy.finance/history?page=1&#x26;limit=20</code></td></tr><tr><td>Latest</td><td>swap</td><td><code>https://api.liquidy.finance/history?page=1&#x26;limit=20&#x26;type=swap</code></td></tr><tr><td>Latest</td><td>arbitrage</td><td><code>https://api.liquidy.finance/history?page=1&#x26;limit=20&#x26;type=arbitrage</code></td></tr><tr><td>By sender</td><td>sender</td><td><code>https://api.liquidy.finance/history?sender=thor1cmgr5khhcyc9x0xln8cw0mfe5dzwzwtx7g5ca7&#x26;page=1&#x26;limit=20</code></td></tr><tr><td>By tx hash</td><td>txHash</td><td><code>https://api.liquidy.finance/history?txHash=DDE686E173EA4A60022B7A8639F8EFF03CAE120960A3F41112D89637EB1F2D53</code></td></tr><tr><td>By affiliate</td><td>affiliate code</td><td><code>https://api.liquidy.finance/history?affiliate=arb&#x26;page=1&#x26;limit=20</code></td></tr></tbody></table>

Example Response:

`https://api.liquidy.finance/history?page=1&limit=5`

```
{
  "swaps": [
    {
      "txHash": "FEBCA499B86EA7F97DADF90266CC06BFECC8FE4216A81727DE0A20B98EA6DCCD",
      "to": "eth-usdc",
      "from": "eth-usdc",
      "fromAmount": 2,
      "affiliate": "none",
      "affiliateFee": 0,
      "affiliateFeeUsd": 0,
      "blockHeight": 27169135,
      "layer1InputAddress": null,
      "layer1OutputAddress": "thor14ejgrnmt7ljw4vn7wpr6lpyj0up507v0wf2mf9",
      "platformFee": 0.00200398,
      "platformFeeUsd": 0.0020039198806,
      "priceUsd": 0.99997,
      "referralFee": 0,
      "referralFeeUsd": 0,
      "route": "eth-usdc:lqdy:eth-eth:eth-usdc",
      "rujiVolumeUsd": 5.99982,
      "sender": "thor14ejgrnmt7ljw4vn7wpr6lpyj0up507v0wf2mf9",
      "timestamp": 1785080537128,
      "toAmount": 2.00197077,
      "type": "arbitrage",
      "volumeUsd": 1.99994
    },
    {
      "txHash": "1FF3437F9D6718A5A97A4E775FBDF19FCD079582FD9AAD89099CE95C352279D6",
      "to": "eth-eth",
      "from": "eth-eth",
      "fromAmount": 0.00105401,
      "affiliate": "none",
      "affiliateFee": 0,
      "affiliateFeeUsd": 0,
      "blockHeight": 27169080,
      "layer1InputAddress": null,
      "layer1OutputAddress": "thor1lj3q7dfg4zwrmtkmqg4u44vy4l44uc68gx892g",
      "platformFee": 0.00000106,
      "platformFeeUsd": 0.0020286597999999998,
      "priceUsd": 1913.83,
      "referralFee": 0,
      "referralFeeUsd": 0,
      "route": "eth-eth:eth-usdc:lqdy:eth-eth",
      "rujiVolumeUsd": 6.051587874899999,
      "sender": "thor1lj3q7dfg4zwrmtkmqg4u44vy4l44uc68gx892g",
      "timestamp": 1785080189156,
      "toAmount": 0.00105551,
      "type": "arbitrage",
      "volumeUsd": 2.0171959583
    },
    {
      "fromAmount": 24.3131339,
      "from": "tcy",
      "to": "tcy",
      "txHash": "DDE686E173EA4A60022B7A8639F8EFF03CAE120960A3F41112D89637EB1F2D53",
      "affiliate": "none",
      "affiliateFee": 0,
      "affiliateFeeUsd": 0,
      "blockHeight": 27168984,
      "layer1InputAddress": null,
      "layer1OutputAddress": "thor1cmgr5khhcyc9x0xln8cw0mfe5dzwzwtx7g5ca7",
      "platformFee": 0.02435312,
      "platformFeeUsd": 0.00304496800608,
      "priceUsd": 0.125034,
      "referralFee": 0,
      "referralFeeUsd": 0,
      "route": "tcy:btc-btc:rune:tcy",
      "rujiVolumeUsd": 9.119905152157802,
      "sender": "thor1cmgr5khhcyc9x0xln8cw0mfe5dzwzwtx7g5ca7",
      "timestamp": 1785079593699,
      "toAmount": 24.3287655,
      "type": "arbitrage",
      "volumeUsd": 3.0399683840526004
    },
    {
      "fromAmount": 0.00052815,
      "from": "eth-eth",
      "to": "eth-eth",
      "txHash": "EBDA9D7072988D1F0FDCA4228404851193E0F455C7EEFCECC46676D0EEA78192",
      "affiliate": "none",
      "affiliateFee": 0,
      "affiliateFeeUsd": 0,
      "blockHeight": 27168899,
      "layer1InputAddress": null,
      "layer1OutputAddress": "thor1lj3q7dfg4zwrmtkmqg4u44vy4l44uc68gx892g",
      "platformFee": 5.3e-7,
      "platformFeeUsd": 0.001005569,
      "priceUsd": 1897.3,
      "referralFee": 0,
      "referralFeeUsd": 0,
      "route": "eth-eth:eth-usdc:lqdy:eth-eth",
      "rujiVolumeUsd": 3.006176985,
      "sender": "thor1lj3q7dfg4zwrmtkmqg4u44vy4l44uc68gx892g",
      "timestamp": 1785079063922,
      "toAmount": 0.0005287,
      "type": "arbitrage",
      "volumeUsd": 1.002058995
    },
    {
      "fromAmount": 1,
      "from": "eth-usdc",
      "to": "eth-usdc",
      "txHash": "F3E3EE0D78DB5F7C1FFB6B5621FCDE62822E3558CF76ED03F43107E1FAC4AD33",
      "affiliate": "none",
      "affiliateFee": 0,
      "affiliateFeeUsd": 0,
      "blockHeight": 27168891,
      "layer1InputAddress": null,
      "layer1OutputAddress": "thor14ejgrnmt7ljw4vn7wpr6lpyj0up507v0wf2mf9",
      "platformFee": 0.00100218,
      "platformFeeUsd": 0.00100212187356,
      "priceUsd": 0.999942,
      "referralFee": 0,
      "referralFeeUsd": 0,
      "route": "eth-usdc:lqdy:eth-eth:eth-usdc",
      "rujiVolumeUsd": 2.999826,
      "sender": "thor14ejgrnmt7ljw4vn7wpr6lpyj0up507v0wf2mf9",
      "timestamp": 1785079012494,
      "toAmount": 1.00117091,
      "type": "arbitrage",
      "volumeUsd": 0.999942
    }
  ],
  "total": 5037,
  "page": 1,
  "limit": 5,
  "totalPages": 1008
}
```


# Development Process

THORChain builds in the open—and Rujira is no exception—hence your smart contract code will have to be open source if you build on Rujira.

Deployments on Rujira are permissioned, we aim to create a coherent suite of apps and avoid duplicates. The development process includes vetting by the Rujira team, external audits and ultimately whitelisting by THORChain's node operators for mainnet deployment. Before starting to build, please contact the Rujira team to get introduced and make sure your project fits into the bigger picture and doesn't overlap with existing plans.

Make sure to check the [README.md](https://gitlab.com/thorchain/rujira) file before you start building on the App Layer, and take the time to check the commits of previous contracts deployed in the [RELEASES.md](https://gitlab.com/thorchain/rujira/-/blob/main/RELEASES.md) file.

## Start Developing

This guide will walk you through the development process for building, testing, and deploying CosmWasm contracts on Rujira. It covers everything from writing your contract, performing unit and integration testing, deploying to test environments, and finally deploying to mainnet.

### 1. Writing Your Contract

Rujira contracts are built using CosmWasm, a smart contract platform written in Rust. Follow the steps below to get started writing your contract:

1. **Set up your environment**: Ensure that you have Rust and the necessary development tools installed. You can follow [CosmWasm's setup guide](https://cosmwasm.cosmos.network/core/installation).
2. **Contract Structure**: CosmWasm contracts typically consist of the following components:
   * **InstantiateMsg**: Defines the parameters required to initialize the contract.
   * **ExecuteMsg**: Represents various actions that users can invoke on the contract.
   * **QueryMsg**: Represents read-only operations that fetch contract state.
3. **Serialization**: Contracts in CosmWasm use `#[cw_serde]` for serialization and deserialization. Rujira may introduce a modified implementation of `#[cw_serde]` to provide a more compact encoding of `ExecuteMsg`s, especially since these messages may be inserted into Layer 1 memos for CosmWasm callbacks. This will ensure efficient handling and smaller payloads.
4. **Best Practices**:
   * Organize your code into modular functions for better readability and maintenance.
   * Use meaningful types and clear names for your messages and state variables.
   * Ensure that your contract handles errors gracefully and follows security best practices to prevent issues like reentrancy.

For more details on writing CosmWasm contracts, refer to the official [CosmWasm documentation](https://docs.cosmwasm.com/core).

### 2. Testing

Before deploying your contract, it’s crucial to write and execute tests. CosmWasm provides a robust testing framework within Rust to simulate contract behavior and ensure correctness.

#### Unit Tests

Unit tests validate individual functions within your contract. Use these tests to check that your logic is working as expected for different scenarios, without the need for a full blockchain simulation.

1. **Write unit tests**: Add your test functions within the `tests` module in your contract.

   ```rust
   #[cfg(test)]
   mod tests {
       use super::*;
       // Your test cases here
   }
   ```
2. **Test execution**: Run your tests using the command:

   ```bash
   cargo test
   ```

#### Integration Testing with Multitest

For more comprehensive testing, you can use CosmWasm’s [Multitest](https://docs.cosmwasm.com/cw-multi-test) framework, which simulates a chain environment in Rust. This allows you to test your contract’s interaction with other contracts and the chain itself.

1. **Set up multitest**: Include the `cw-multi-test` package in your `Cargo.toml` dependencies.
2. **Simulate complex scenarios**: Write tests that involve message execution, querying, and contract-to-contract interactions.
3. **Run multitest**: Execute your multitest suite using:

   ```bash
   cargo test --features multitest
   ```

Multitest provides a highly realistic environment, simulating actual blockchain behavior without the need for a full node or deployment to a testnet.

### 3. Test Deployment

After validating your contract through unit and integration tests, the next step is deploying it to a permissionless test environment. Rujira offers two options for deploying your contract for further testing.

* **Localnet / Mocknet:** Spin up your own instance and deploy your contract(s) to a local THORChain environment so you can run a simulated THORChain network locally (Midgard, THORNode, mock L1 chains), interact with the chain via CLI and APIs to finally build and test contracts with no reliance on external node operators. See full guide in [Local Deployment Guide](/developers/local-deployment-guide)
* **Stagenet**: A permissionless testnet to verify your contract in a real end-to-end environment, but with real money. Contracts will need to be tested thoroughly on Stagenet to showcase compatibility with the network and with connections to existing apps on Rujira. See a general guide on [how to deploy on Stagenet with THORChain's Dev docs](https://dev.thorchain.org/release.html#deploy-stagenet), and do make sure to follow the steps in [Stagenet Deployment Guide](/developers/stagenet-deployment-guide)

To make sure you connect to the right networks, find the overview of connections in [Developer Endpoints](/developers/developer-endpoints)

To check txs in a block explorer when testing on stagenet, you can find under [stagenet.thorchain.net](https://stagenet.thorchain.net/dashboard)

### 4. Review & Audit

All contracts that want to deploy on THORChain and Rujira are subject to an internal review by a core team member and an external review by an auditor. Make sure to follow the [Rujira templates](https://gitlab.com/thorchain/rujira/-/tree/main/contracts/rujira-template?ref_type=heads) for README.md and Cargo.toml.

You can find the full review process under [Review and Audit Guide](/developers/review-and-audit-guide)

### 5. Setup multisig as deployer address

Before you can deploy your audited contracts to mainnet, you will need to deploy a THORChain multisig address that will be used as the deployer address for your smart contracts.&#x20;

Find out exactly how under [Setting Up a THORChain Multisig](/developers/setting-up-a-thorchain-multisig).

### 6. Mainnet Deployment

Once your contract has been thoroughly tested, it’s time to deploy it to THORChain mainnet to be live officially on Rujira. This process involves additional security checks and permissions to ensure the integrity of the contract on the network.

See exactly how in [Mainnet Deployment Guide](/developers/mainnet-deployment-guide)


# Secured Assets

The assets available on Rujira will be Secured Assets from THORChain, with the [delimiter](https://docs.thorchain.org/frequently-asked-questions/asset-types) to be a dash '-'. E.g. `ETH.ETH` is L1. `ETH-ETH` will be a Secured Asset.

You can find out more on [Secured Assets](https://docs.thorchain.org/thorchain-finance/secured-assets) on docs.thorchain.org.

## Assets Overview

### **Primary Asset: Secured Assets via "TokenFactory"**

`BTC-BTC (BA) ↔ BTC.BTC (L1)`

Secured Assets are fully supported on the Cosmos ecosystem represented as [x/bank](https://docs.cosmos.network/main/build/modules/bank) tokens using the bank module. They behave like traditional trade assets and can seamlessly interact with Base Layer pools. These interactions include:

* Redeeming
* Moving into and out of pools
* Depositing

Currently, Secured Assets support 1:1 redemption and deposits. A fee structure will be introduced in a future update. These assets will appear alongside **RUNE** on your THOR address.

### Application Interaction (App Layer and L1)

The first app utilizing these assets will be **RUJI Trade** orderbook DEX, which introduces limit orders. The user experience will b&#x65;**:**

* **Deposit/Swap**: Users can deposit or swap to BTC-BTC to fund their accounts.
* **Swaps**: For example, a BTC-BTC to ETH-USDC swap will use a wrapper over `MsgDeposit`, handling:
  * Thornames
  * Affiliate fees
  * Safety checks

### **Transaction Flows**

1. **To THOR EOA**: ETH-USDC is swapped via base pools and delivered to the user’s THOR address.
2. **To CosmWasm (CW) Contract**: ETH-USDC is swapped, and `DexAgg` features are leveraged to call a contract on THOR with specific parameters.
3. **To L1**: Similar to current behavior.

### **Input/Output:**

* **IN**: `MsgDeposit`
* **OUT**: `txOut` or `DexAgg.transferOutAndCall()`

All flows include comprehensive safety handling, adhering to existing THORChain (TC) mechanisms without bypassing critical processes.

### Query Support

We will add bindings for the following whitelisted query paths:

* `/inbound_addresses`: For checking halting status
* `/pools`: For pricing and depth
* `/pool/{asset}`: For querying specific asset pools

There are known attack vectors related to non-deterministic query aspects that could potentially lead to chain halts. These are being actively monitored.

### Sources

Relevant PR: [GitLab MR #3721](https://gitlab.com/thorchain/thornode/-/merge_requests/3721)


# Local Deployment Guide

Below is a practical guide on how to spin up your own instance and deploy your contract(s) to a local THORChain environment so you can:

* Run a simulated THORChain network locally (Midgard, THORNode, mock L1 chains)
* Interact with the chain via CLI and APIs
* Build and test contracts with no reliance on external node operators

## Setup local environment

If you want to build and run thornode or midgard locally (e.g. for custom tooling or debugging), follow this setup using macOS as an example.

#### 1. Install Required Tools

`brew install golang coreutils binutils diffutils findutils gnu-tar gnu-sed gawk grep make git protobuf`

#### 2. Update Your PATH (GNU Compatibility)

macOS uses BSD tools by default — THORChain requires GNU tools. Add this to your \~/.zshrc:

`# Core GNU tools`\
`export PATH="/opt/homebrew/opt/coreutils/libexec/gnubin:$PATH"`\
`export PATH="/opt/homebrew/opt/binutils/bin:$PATH"`\
`export LDFLAGS="-L/opt/homebrew/opt/binutils/lib"`\
`export CPPFLAGS="-I/opt/homebrew/opt/binutils/include"`\
\
`export PATH="/opt/homebrew/opt/findutils/libexec/gnubin:$PATH"`\
`export PATH="/opt/homebrew/opt/gnu-tar/libexec/gnubin:$PATH"`\
`export PATH="/opt/homebrew/opt/gnu-sed/libexec/gnubin:$PATH"`\
`export PATH="/opt/homebrew/opt/gawk/libexec/gnubin:$PATH"`\
`export PATH="/opt/homebrew/opt/grep/libexec/gnubin:$PATH"`\
`export PATH="/opt/homebrew/opt/make/libexec/gnubin:$PATH"`\
\
`# PostgreSQL for Midgard`\
`export PATH="/opt/homebrew/opt/postgresql@16/bin:$PATH"`\
`export LDFLAGS="-L/opt/homebrew/opt/postgresql@16/lib"`\
`export CPPFLAGS="-I/opt/homebrew/opt/postgresql@16/include"`\
\
`# Go binaries`\
`export GOBIN=$GOPATH/bin`\
\
`# Reload shell`\
`source ~/.zshrc`

#### 3. Verify Your Tools

`which gawk && gawk --version`\
`which gsed && gsed --version`

These should point to paths under `/opt/homebrew/opt/`.

#### 4. Install Docker

Install [Docker Desktop](https://www.docker.com/products/docker-desktop/)

Make sure it’s running before proceeding.

## Setup Localnet

#### 1. Clone THORNode

`git clone https://gitlab.com/thorchain/thornode.git`\
`cd THORNode`&#x20;

#### 2. Create mocknet

Create a deployment on mocknet to spin up a full local, permissioned network to check that all contracts have the permissions they need&#x20;

`make run-mocknet`&#x20;

#### 3. Start mocknet and set permissions

Start the local mocknet and set wasm permissions

`make start-mocknet`&#x20;

The command spins up: 4 validator nodes, Midgard, L1 mocks (BNB, BTC, ETH)

You’ll need to have a local version with wasm\_permissions\_mocknet containing your permissions. Set WASMPERMISSIONLESS mimir to 1 to be able to store contracts on the thornode container:&#x20;

`echo password | thornode tx thorchain mimir --keyring-backend file --from thorchain --chain-id thorchain --yes WASMPERMISSIONLESS 1`&#x20;

#### 4. Access Services

<table data-header-hidden><thead><tr><th width="241.91015625"></th><th></th></tr></thead><tbody><tr><td>Service</td><td>URL</td></tr><tr><td>Midgard API</td><td>http://localhost:8080/v2</td></tr><tr><td>THORNode RPC</td><td>http://localhost:1317</td></tr><tr><td>ETH RPC (mock)</td><td>http://localhost:8545</td></tr><tr><td>BNB RPC</td><td>http://localhost:26650</td></tr></tbody></table>

#### Helpful Localnet Commands

| Task                    | Command                         |
| ----------------------- | ------------------------------- |
| Stop the environment    | make stop                       |
| Rebuild and start clean | make clean start                |
| Tail logs               | docker compose logs -f          |
| Restart Midgard only    | docker compose restart midgard  |
| Interact with THORNode  | Use thornode CLI or curl to API |

#### Example Interactions

Query Midgard:

`curl http://localhost:8080/v2/pools`

Query THORNode RPC:

`curl http://localhost:1317/thorchain/inbound_addresses`<br>


# Stagenet Deployment Guide

Prior to diving into stagenet deployment, make sure to follow the [Local Deployment Guide](/developers/local-deployment-guide).&#x20;

Below is a practical guide on how to get started deploying to THORChain’s stagenet, taking inspiration from our friends at [Nami Protocol](https://x.com/NamiProtocol) who made a similar [Devnet Deployment Guide](https://namiprotocol.notion.site/Get-started-App-layer-development-15a7ce475ca8800d8f49fd6e48f48dfd).

It covers the steps from installing and setting up the daemon to connecting to different chain environments, getting funds on stagenet, and provides a broad overview of [Rujira.JS](http://rujira.js) & [Rujira.UI](http://rujira.ui).

## Install the thornode daemon (macOS)

1. After `brew install golang coreutils binutils diffutils findutils gnu-tar gnu-sed gawk grep make git protobuf` you need to prioritize the GNU versions and modify your PATH. You’ll find all the commands needed in the installation log of the command before. An example:

| <p><code>PATH="/opt/homebrew/opt/coreutils/libexec/gnubin:$PATH"</code><br><code>echo 'export PATH="/opt/homebrew/opt/binutils/bin:$PATH"' >> \~/.zshrc</code><br><code>export LDFLAGS="-L/opt/homebrew/opt/binutils/lib"</code><br><code>export CPPFLAGS="-I/opt/homebrew/opt/binutils/include"</code><br><code>PATH="/opt/homebrew/opt/findutils/libexec/gnubin:$PATH"</code><br><code>PATH="/opt/homebrew/opt/gnu-tar/libexec/gnubin:$PATH"</code><br><code>PATH="/opt/homebrew/opt/gnu-sed/libexec/gnubin:$PATH"</code><br><code>PATH="/opt/homebrew/opt/gawk/libexec/gnubin:$PATH"</code><br><code>PATH="/opt/homebrew/opt/grep/libexec/gnubin:$PATH"</code><br><code>PATH="/opt/homebrew/opt/make/libexec/gnubin:$PATH"</code><br><code>echo 'export PATH="/opt/homebrew/opt/postgresql\@16/bin:$PATH"' >> \~/.zshrc</code><br><code>export LDFLAGS="-L/opt/homebrew/opt/postgresql\@16/lib"</code><br><code>export CPPFLAGS="-I/opt/homebrew/opt/postgresql\@16/include"</code><br><code>// reload your shell</code><br><code>source \~/.zshrc</code></p> |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

| <p><code># Verify gawk is available</code><br><code>which gawk</code><br><code>gawk --version</code></p> |
| -------------------------------------------------------------------------------------------------------- |

2. Install Docker: <https://www.docker.com/products/docker-desktop/>
3. Add `GOBIN` to your `PATH`.&#x20;

| `export GOBIN=$GOPATH/bin` |
| -------------------------- |

4. Clone Repo

| <p><code>git clone <https://gitlab.com/thorchain/thornode.git></code><br><code>cd thornode</code><br><code>git checkout app/rc1</code></p> |
| ------------------------------------------------------------------------------------------------------------------------------------------ |

5. Install via `make` command

| `TAG=stagenet make go-generate openapi install` |
| ----------------------------------------------- |

6. Verify the correct installation&#x20;

| `thornode help` |
| --------------- |

## Connect to Stagenet

Stagenet is THORChain’s **permissionless** testnet, allowing you to freely test your contract(s) with **real money**.

### General connection

1. Connection Details (see details in [Developer Endpoints](/developers/developer-endpoints))
   1. Chain-ID: thorchain-stagenet-2
   2. RPC: [https://stagenet-rpc.ninerealms.com](https://stagenet-rpc.ninerealms.com/)
   3. API: [https://stagenet-thornode.ninerealms.com](http://stagenet-thornode.ninerealms.com)&#x20;
2. Example commands:

```
// Query all tokens
thornode query bank total-supply --node https://stagenet-rpc.ninerealms.com/

// Execute a transaction
thornode tx wasm execute <contract-addr> <json-msg> --from <account> --chain-id stage-1 --node https://stagenet-rpc.ninerealms.com/
```

### Deploy a contract using sudo entry points

To deploy a contract on stagenet, test and make sure your sudo entry points work.

1. Generate the transaction (generate-only):

First, create a basic MsgExecuteContract transaction using the --generate-only flag:

2. Generate your execute msg only:

Example: `thornode tx wasm execute <contract> '<msg>' --from wallet --node https://stagenet-rpc.ninerealms.com --chain-id thorchain-stagenet-2 --generate-only > sudo_tx.json`

3. Update the generated sudo\_tx.json:

* Change the message type to "/cosmwasm.wasm.v1.MsgSudoContract"
* Remove the sender and funds fields
* Add the authority field

```
{
    "body": {
        "messages": [
            {
                "@type": "/cosmwasm.wasm.v1.MsgSudoContract",
                "authority": "your_wallet",
                "contract": "your_contract",
                "msg": your_msg
                }
            }
        ],
        "memo": "",
        "timeout_height": "0",
        "extension_options": [],
        "non_critical_extension_options": []
    },
    "auth_info": {
        "signer_infos": [],
        "fee": {
            "amount": [],
            "gas_limit": "200000",
            "payer": "",
            "granter": ""
        },
        "tip": null
    },
    "signatures": []
}
```

4. Sign the json:

```
thornode tx sign sudo_tx.json \
  --from wallet \
  --chain-id thorchain-stagenet-2 \
  --node https://stagenet-rpc.ninerealms.com \
  --output-document signed_sudo_tx.json
```

5. Broadcast tx:

```
thornode tx broadcast signed_sudo_tx.json \
  --node https://stagenet-rpc.ninerealms.com
```

### Store & instantiate a contract

1. Build and optimize your cosmwasm contract, so you have an artifact. A good starting point is this template: <https://github.com/CosmWasm/cw-template/tree/main>
2. Store the contract:

| `thornode tx wasm store <wasm file> --from <account> --chain-id stage-1 --node https://stagenet-rpc.ninerealms.com/` |
| -------------------------------------------------------------------------------------------------------------------- |

3. Instantiate it

| `thornode tx wasm instantiate <code Id> <InstantiateMsg> --from <account> --chain-id stage-1 --node https://stagenet-rpc.ninerealms.com/` |
| ----------------------------------------------------------------------------------------------------------------------------------------- |

## Get assets on stagenet

Assets on stagenet are “real money” so to get assets to test, you will need to deposit real money (e.g. ATOM), swap some of it to another asset (e.g. RUNE) if you need a pair of assets to test, and then send by interacting with the different apps / contracts you want to test.

The easiest way to deposit and swap assets on stagenet is to use [preview.rujira.network](https://preview.rujira.network), which is connected to stagenet:

1. Deposit: Go to [preview.rujira.network/portfolio](https://preview.rujira.network/portfolio), connect your wallet (Keplr, Ctrl, Leap or whichever you prefer) and hit the Deposit button. You can find the stagenet thor address (sthor….) in the portfolio page:

<figure><img src="/files/YPqLKbdK2JR0lUmqblC2" alt=""><figcaption></figcaption></figure>

2. &#x20;Swap: Once you’ve made a deposit, you can swap to e.g. RUNE to get to your sthor address using [preview.rujira.network/swap/GAIA.ATOM/THOR.RUNE](http://preview.rujira.network/swap/GAIA.ATOM/THOR.RUNE)

If above doesn't work, you can also get RUNE on THORChain via AVAX using below method:

## Get RUNE on THORChain Stagenet from AVAX on Avalanche

This covers a manual conversion process from AVAX on the Avalanche-C chain to RUNE on THORChain Stagenet.

### 1. Determine the Avalanche inbound address

Go to this URL: <https://stagenet-thornode.ninerealms.com/thorchain/inbound_addresses>

Find the relevant section, e.g. AVAX:

![](https://lh7-rt.googleusercontent.com/docsz/AD_4nXcmGY9H3C39RxQFx8XtcV-yhdgvVee4ne6WJaIweoVhTWLLTVOhsfeoC79IKMXGktcQGS45w5GHbLfz9qbn8-zfZXvxPavyYVkePspqlabGMM4ndoLQ6crGXktF8VBpr5I6Qfbj?key=sebsrHsO-iozYwu95hQ06NJE)

Find the address field, e.g. 0xd6a6c0b3bb4150a98a379811934e440989209db6

### 2. Construct the correct message data

Find your deposit address, e.g.: sthor1e2r98hpf3eer8pfpcrsprmrx5vpfq8jpwt06jw

Construct a message using that address of the form: =:THOR.RUNE:sthor1egxvam70a86jafa8gcg3kqfmfax3s0m2ug8gzt

Hex encode that string, e.g.: 3d3a54484f522e52554e453a7374686f723165677876616d37306138366a61666138676367336b71666d6661783373306d32756738677a74

You can use any tool to hex encode data, for example this site: <https://www.hexator.com/>

And finally, prepend 0x to that string to match MetaMask expectations: 0x3d3a54484f522e52554e453a7374686f723165677876616d37306138366a61666138676367336b71666d6661783373306d32756738677a74

### 3. Configure MetaMask

You need to ensure that the “show data” option is enabled under advanced settings:

![](https://lh7-rt.googleusercontent.com/docsz/AD_4nXee4FSF-IS4sb2f0hpCIdkX0QYobpEltOwZbQloe9FTFGP-fMFQyPaxO699zIB2AE52NKW2fMtuecnJszsxGEKJKs7BYvxk_nZXon3lLXv1bnC0roMgOdiFB7TxHV4JU1uWP4_Upg?key=sebsrHsO-iozYwu95hQ06NJE)

### 4. Send funds

You can use any Avalanche-compatible wallet, but in this example we're using MetaMask. You need to set message data, which can only be done in the full-screen mode. Open MetaMask and choose expand view:

![](https://lh7-rt.googleusercontent.com/docsz/AD_4nXfhEXv5-juW0EypPRn5nvEUpAGK4v7z_2sdgwqf3aO5j-js8THs8BnG9mnjQPFerImEktu7WJ75UC_LHyZnKYxyXc5XOpnAZS75javouIj80AqmbD7-8bGyAM_3OC_ktdFb_w_C?key=sebsrHsO-iozYwu95hQ06NJE)

Initiate a send, and configure the destination address, token, and amount, plus the hex data from above:

![](https://lh7-rt.googleusercontent.com/docsz/AD_4nXfNSzZHS1y1lTkhfTDyL5XBTGm1yG29C3oGusCvFt-Hivw2CbIrtUsdNbTTiCdEUnt0xAZbDp__JGLeR5mroIIS1P-6GiDOU1Ek9mq-pYnsyZYqM1qqJl3vHeAGGV8JzQOKZV39?key=sebsrHsO-iozYwu95hQ06NJE)

### 5. Confirm funds received

Broadcast the transaction above: <https://snowtrace.io/tx/0xae863bd2b4407421ec0882d7eada20ba12cffeec8e93f7e77e22b946a952641e>

Take that transaction hash to: <https://stagenet.thorchain.net/dashboard>

Search for that transaction hash, and you’ll find: <https://stagenet.thorchain.net/tx/0xae863bd2b4407421ec0882d7eada20ba12cffeec8e93f7e77e22b946a952641e>


# Review and Audit Guide

This page outlines the audit and review process required before deploying contracts and applications to THORChain mainnet.&#x20;

## Review Process

Before any deployment to mainnet, all contracts go through a structured review and audit process from stagenet to mainnet. This involves technical verification, governance-level review, and clear communication of the code’s purpose and security posture.

### 1. Deploy and Test on Stagenet

* Deploy the application and contracts to Stagenet, which is a permissionless test environment. See the [Stagenet Deployment Guide](/developers/stagenet-deployment-guide)
* Once deployed and functional, notify a reviewer (typically Mark and/or PM) with the URL to test the application and contracts making up the application.

Before requesting a review of your deployed contracts on Stagenet, make sure to also test that the UI follows one of the following guidelines:

* If you are building as an **independent app**, you will host your own UI. You are free to use Rujira UI components for convenience and to stay on theme.
* If you are building a **new core app** as part of the Rujira Alliance, you will need to integrate your app into the main Rujira UI, using the[ Rujira.ui](https://ui.rujira.network/install) and[ Rujira.js](https://gitlab.com/thorchain/rujira-ui/-/tree/dev/packages/rujira.js?ref_type=heads) library. Here’s a list of useful topics for both:
  * Rujira.js:
    * [Account Provider](https://gitlab.com/thorchain/rujira-ui/-/blob/dev/packages/rujira.js/src/accounts.ts?ref_type=heads#L4): A single provider that helps you manage the different accounts of a user and gives you the signer as well. See more about[ Implementation Main Rujira Page](https://gitlab.com/thorchain/rujira-ui/-/blob/dev/packages/main/src/main.tsx?ref_type=heads)
    * [Msg interface](https://gitlab.com/thorchain/rujira-ui/-/blob/dev/packages/rujira.js/src/msgs.ts?ref_type=heads#L14): A generic representation of a message type. This can either be encoded as a L1 with a memo, base layer with a MsgDeposit, or app layer with MsgExecuteContract
    * [Individual Msg types](https://gitlab.com/thorchain/rujira-ui/-/tree/dev/packages/rujira.js/src/msgs?ref_type=heads)
  * Rujira.ui: Find official docs[ here](https://ui.rujira.network/usage). A list of interesting components from rujira.ui:
    * [Displaying / Handling Decimals](https://ui.rujira.network/numbers)
    * [Tabs](https://ui.rujira.network/tabs?tab=one)
    * [TxButton](https://ui.rujira.network/tx-button): Fully functional button that takes a msg to be executed as an input, encodes it for the right network, signs it with the correct signer
    * [IconDenom](https://ui.rujira.network/denomicons): Renders the icon for any token

### 2. Request Review

After successful testing on Stagenet, submit the following information in a dedicated channel on Discord to the core Rujira team including Hans and Mark:

* Contract **bytecode**
* **Deployer address** (generate using [Setting Up a THORChain Multisig](/developers/setting-up-a-thorchain-multisig))
* Link to the **GitHub/Gitlab repo** including:
  * Well-structured **source code** (example: [RUJI Trade](https://gitlab.com/thorchain/rujira/-/tree/main/contracts/rujira-fin?ref_type=heads))
  * [README.md](http://readme.md) in **plain language** describing the contract’s purpose (example:[ Rujira Merge Contracts](https://gitlab.com/thorchain/rujira/-/tree/d74d3dc4e2d384aef36af39bc200b59ed8206331/contracts/rujira-merge))

Before submitting a request to review, make sure to go through the following checklist:&#x20;

* Source code matches deployed bytecode
* Repo contains README and plain-language description
* Code is readable, modular, and reviewed for common exploits
* Permissions and roles (e.g., admin, cap settings) are properly scoped
* Dependencies and external calls are reviewed
* Contract(s) emit events that are (1) Individual and (2) Well-namespaced for the contract name, see [contracts/rujira-fin/src/events.rs](https://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-fin/src/events.rs?ref_type=heads) as a guiding example

### 3. Technical (Internal) Review

Once all points in the general checklist above have been completed, then and only then ping Mark in the dedicated channel to double-check, before Hans starts an internal review of the contracts:

* Verifying that the submitted **hashes match** the deployed bytecode on stagenet.
* Ensuring that **dependencies** (e.g., imported CosmWasm libraries) and compiler versions are explicitly locked to prevent mismatches or compilation inconsistencies.
* Helping **set up deployer address** on a THORChain multisig if needed.

### 4. Auditor (External) Review

Once you’ve gone through the internal review process, your contracts are ready for an external review by an auditor. This includes:

* Get in touch with Mark giving a status after the technical review and the latest commits + repos that an auditor should review.
* Mark will find a suitable and reliable auditor for your contracts. Depending on the type of contracts, the Rujira team might help you fund part or all of the audit costs.
* Once an auditor is found, a dedicated group chat with the auditor is set up with the start and delivery date of the audit.

The role of the auditor is to&#x20;

* Ensure the **contract logic is aligned** with the provided source code and documentation.
* Assessing **security vulnerabilities** such as: Reentrancy, Integer overflows/underflows, Denial of service (DoS), Front-running and MEV exposure, Insecure randomness sources
* Check for **best practices** in access control, rate-limiting, caps, and upgradability. Note that contracts involving sensitive logic (e.g., admin roles, asset caps) must include appropriate control mechanisms.

### 5. Request Permissions for Mainnet

Once both internal and external review has been completed, submit an MR to [THORNode](https://gitlab.com/thorchain/thornode) with all the information listed below to obtain permissions for contracts to go live on THORChain mainnet. Example:[ RUJI Perps Permission MR](https://gitlab.com/thorchain/thornode/-/merge_requests/4062)

* Contract **bytecode**
* **Deployer address** (generate using [Setting Up a THORChain Multisig](/developers/setting-up-a-thorchain-multisig))
* Link to the **GitHub/GitLab repo**&#x20;
* Link to most recent **audit** of the code (example: [RUJI Perps audit](https://github.com/fyeo-io/public-audit-reports/blob/main/Code%20Audit%20Reports/2025/Levana/Levana%20-%20Security%20Code%20Review%20of%20Ruji%20Perps%20v1.0.pdf))

### 6. Final Approval

* Members of ThorSec/TC core team perform the final review, assessing overall project readiness, risk exposure and any potential node operator / governance concerns.
* Upon approval, the application is listed in [RELEASES.md](https://gitlab.com/thorchain/rujira/-/blob/main/RELEASES.md?ref_type=heads) with commit id, checksum value and audit link, contracts are ready for mainnet deployment following [Mainnet Deployment Guide](/developers/mainnet-deployment-guide)

THORChain upgrades in 3-week cycles, which means new contracts that have been approved will be slotted into the next upgrade. Upgrades to the network take effect when supermajority has been reached (⅔). You can find the version number, how old the current version is, and follow how many nodes upgraded on <https://thorchain.net/network> and <https://thorchain.net/network/votes>&#x20;

<br>


# Setting Up a THORChain Multisig

To instantiate, store and deploy contracts on Rujira, teams need to set up a multisig on THORChain. There are currently three ways to setup a multisig on THORChain:

1. DAODAO
2. Keplr Multisig
3. Thornode Multisig Key

## 1. DAODAO

The preferred option to setup a multisig is using [daodao.zone](https://daodao.zone/) because it lets teams not just sign off on transactions, but contains a whole library of actions that satisfy all the needs a decentralized team will ever need:

<figure><img src="/files/o66I5of2RFPEht8xtoeA" alt=""><figcaption></figcaption></figure>

You can create a DAO on DAODAO using this link: <https://daodao.zone/dao/create?chain=thorchain-1>

## 2. Keplr Multisig

THORChain is available on [Keplr Wallet](https://www.keplr.app/) and hence [Keplr Multisig](https://multisig.keplr.app/), allowing teams to create simple multisigs to sign off on THORChain transactions:

<figure><img src="/files/sIuh2mF9Xi0NGq7bH6QB" alt=""><figcaption></figcaption></figure>

You can create a Keplr Multisig using this link: <https://multisig.keplr.app/account/register/create>

Consider using only individual Keplr wallets that are connected to Ledger hardware wallet to add an extra level of security to the Keplr Multisig.

## 3. Thornode Multisig Key

This guide walks you through the complete process of creating and using a multisig wallet on **THORChain**, including the installation of `thornode`, setting up the multisig key, generating and signing transactions, and finally broadcasting them.

This guide has been prepared with love by the [AutoRujira](https://autorujira.app/) team :heart:

### Special Instructions for macOS Users

If you're on macOS, you may encounter issues with default versions of tools like `awk`, `sed`, and `find`, which are not GNU-compliant. To fix this:

1. Install the GNU versions of the required utilities using Homebrew:

```bash
brew install coreutils binutils diffutils findutils gnu-tar gnu-sed gawk grep make
```

2. Add the GNU versions to your `PATH`. Add the following lines to your shell config (`~/.zshrc` or `~/.bash_profile`):

```bash
# GNU utils for macOS
export PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH"
export PATH="/usr/local/opt/findutils/libexec/gnubin:$PATH"
export PATH="/usr/local/opt/gnu-sed/libexec/gnubin:$PATH"
export PATH="/usr/local/opt/gawk/libexec/gnubin:$PATH"
```

Then run:

```bash
source ~/.zshrc  # or source ~/.bash_profile
```

3. Update Go to the required version (at least Go 1.23.4):

```bash
brew upgrade go
```

Verify with:

```bash
go version
```

Once all is set up, you're good to go with `make install`.

***

### Prerequisites

Each member of the multisig must:

* Have access to a local terminal.
* Install `thornode`.
* Share their public key with the group.
* Be able to sign and submit transactions individually.

***

### Step 1: Install `thornode`

Install the Thorchain CLI binary on your machine:

```bash
git clone https://gitlab.com/thorchain/thornode.git
cd thornode
TAG=mainnet make install
```

> This installs the `thornode` binary in your `$GOPATH/bin`. Make sure it's in your system path.

***

### Step 2: Generate and Share Public Keys

Each participant should create a new key (if they don't already have one):

```bash
thornode keys add <your-key-name>
```

Then export your **public key**:

```bash
thornode keys show <your-key-name> -p
```

Share this public key with all other members.

To import a public key shared by another participant, use:

```bash
thornode keys add <other-key-name> --pubkey <their-public-key>
```

Once you have everyone's pubkeys imported, you can create the multisig key.

***

### Step 3: Create the Multisig Key

Each participant must **locally** create the multisig key with the same set of public keys and threshold:

```bash
thornode keys add <multisig-key-name> --multisig=<comma-separated-pubkeys> --multisig-threshold=<N>
```

Example:

```bash
thornode keys add multisig-xx --multisig=pubkey1,pubkey2,pubkey3 --multisig-threshold=2
```

> ⚠️ This must be done **identically by all participants**.

***

### Step 4: Generate the Transaction (Only Once)

One participant prepares a transaction to send 1 RUNE and exports it to JSON (leave some RUNE for paying the fee):

```bash
thornode tx bank send <multisig-key-name> <destination-address> 1000000000rune --generate-only --chain-id thorchain-1 > tx.json
```

This transaction file is then shared with all multisig participants.

***

### Step 5: Each Participant Signs the Transaction

Each participant signs the transaction using their own key and the multisig key:

```bash
thornode tx sign tx.json \
  --from <your-key-name> \
  --multisig <multisig-key-name> \
  --node https://rpc.ninerealms.com:443 \
  --chain-id thorchain-1 \
  --output-document sig-<your-name>.json
```

Everyone sends their `sig-<your-name>.json` file to the coordinator.

***

### Step 6: Combine Signatures and Broadcast

One person aggregates the signatures and broadcasts the final signed transaction:

```bash
thornode tx multi-sign tx.json <multisig-key-name> sig-1.json sig-2.json ... --chain-id thorchain-1 --node https://rpc.ninerealms.com:443 > signed.json

thornode tx broadcast signed.json --chain-id thorchain-1 --node https://rpc.ninerealms.com:443
```

***

### Final Step: Test It

Once the multisig address is finalized and funded, you can test the setup by executing a multisig transaction that sends 1 RUNE to a known address as shown above.

***

### Summary

* Every member installs `thornode`, generates their key, and shares the pubkey.
* All members must create the same multisig locally.
* One person creates the transaction; everyone signs.
* The final signed transaction is broadcast by one member.
* The process ensures **security and collective review** before execution.


# Mainnet Deployment Guide

Once your contract has been thoroughly tested and audited as per [Review and Audit Guide](/developers/review-and-audit-guide), it’s time to deploy it to THORChain mainnet to officially go live on Rujira. This process involves additional security checks and permissions to ensure the integrity of the contract on the network.

### Registry and Permissions

For mainnet, Rujira maintains an on-chain [registry](https://gitlab.com/thorchain/rujira/-/blob/main/RELEASES.md) that maps each contract’s checksum to its deployer. This registry will grant permissions for instantiation based on the contract’s checksum rather than its code ID. The process will involve:

1. **Registry check**: The registry will verify that the deployer is allowed to instantiate a specific contract version, using the contract’s computed checksum.
2. **MsgStoreCore**: If the checksum matches the registry entry, the deployer will be granted permission to store the contract on-chain.
3. **MsgInstantiateContract**: Once the contract is stored, the deployer can instantiate it with the appropriate parameters.

By tying instantiation permissions to the contract checksum, THORChain node operators and hence the Rujira App Layer ensure that only approved contract versions can be deployed on mainnet, improving security and reliability.

### Deployment Steps

1. Create a thor address as a [multisig](/developers/setting-up-a-thorchain-multisig), if you haven't already
2. Submit a Merge Request on [THORNode](https://gitlab.com/thorchain/thornode/-/tree/develop) that whitelists the thor address in [wasm\_permissions\_mainnet.go](https://gitlab.com/thorchain/thornode/-/blob/develop/common/wasmpermissions/wasm_permissions_mainnet.go) to **instantiate** your contract(s)
3. Reach out to the Rujira Core team (e.g. in a group chat on Telegram or Discord) to make a proposal to store contract code via the [Rujira Deployment Multisig](https://daodao.zone/dao/thor1pnad3hhgktqde00jl6wvyuuspatle000wl9pehgqxmehl7974e4szc4zpn/proposals) using DAO DAO. The Rujira Core team will do a final review before storing contract code generating checksum
4. Instantiate contract from the thor address provided in step (2)
5. Wrap up the deployment process by providing the Rujira Core team with the release information to be added to [Releases & Contracts](/resources/releases-and-contracts)


# Developer Endpoints

Feel free to use these endpoints to build on Rujira!

Stay updated with health checks and notifications through our [Discord](https://discord.com/).

Detailed documentation is available in the [THORChain Dev Docs](https://docs.thorchain.org/).

***

### THORChain Public Endpoints

#### Mainnet

* **RPC**:
  * <https://gateway.liquify.com/chain/thorchain_rpc>
  * <https://rpc-thorchain.rorcual.xyz>
  * <https://thorchain.ibs.team/rpc/>
* **gRPC**:
  * <https://grpc-thorchain.rorcual.xyz>
  * <https://thorchain.ibs.team:443>
* **RPC REST API**:
  * <https://gateway.liquify.com/chain/thorchain_api>
  * [https://api-thorchain.rorcual.xyz](https://api-thorchain.rorcual.xyz/)
  * [https://thorchain.ibs.team/api/](<https://thorchain.ibs.team/api/ >)
* **Midgard REST API**: <https://gateway.liquify.com/chain/thorchain_midgard>

#### Stagenet (discontinued)

* **RPC**: [https://stagenet-rpc.thorchain.org](https://stagenet-rpc.thorchain.org/)
* **RPC REST API:** [https://stagenet-thornode.thorchain.org](https://stagenet-thornode.thorchain.org/)
* **Midgard REST API**: [https://stagenet-midgard.thorchain.org](https://stagenet-midgard.thorchain.org/)

***

### Rujira Ecosystem APIs

#### GraphQL API

High-performance API for extensive data across the Rujira ecosystem:

* **Mainnet**: [api.rujira.network/api/graphiql](https://api.rujira.network/api/graphiql)
* **Stagenet**: <https://api-preview.rujira.network/api/graphiql>
* **Docs:** Embedded inside the above links.
* **API key:** Email <api@rujira.network> to request an API key.

For GraphQL subscriptions and real-time data streaming, use a **Phoenix Socket-based connection** instead of HTTP. This ensures low-latency, bidirectional communication with Rujira’s endpoints. A working example is available [here](https://gitlab.com/thorchain/rujira-ui/-/blob/dev/packages/main/src/services/relay.tsx), which:

* Initializes a Phoenix Socket instance (`PhoenixSocket` from `phoenix`).
* Wraps it with `@absinthe/socket` for Relay-compatible GraphQL subscriptions.
* Includes fallback compatibility fixes for outdated libraries.

#### REST API

For RUJI Trade DEX and RUJI token supply integrations:

* **Mainnet**: [Trade](https://api.rujira.network/api/trade/), [RUJI](https://api.rujira.network/api/ruji/)
* **Stagenet**: [Trade](https://preview-api.rujira.network/api/trade/), [RUJI](https://preview-api.rujira.network/api/ruji/)
* **Docs:** [Rujira's REST API](/developers/developer-endpoints/rujira-rest-api)

For a more comprehensive solution, use our [GraphQL API](#graphql-api).

***

### Endpoint Testing

**RPC/API Endpoints:**

```bash
curl -X GET https://<endpoint>/status
```

**gRPC Endpoints:**

```bash
grpcurl <grpc-endpoint> list
```


# Rujira REST API

### Introduction

This document outlines the REST API endpoints available for RUJI Trade orderbook DEX and RUJI token supply, to be used by integrating partners such as CoinGecko and CoinMarketCap.

If you need a more complete, higher performance API, we recommend using our GraphQL API available here: <https://api.rujira.network/api/graphiql>.

#### General API Information

* The base endpoints are available at <https://api.rujira.network/api/>
* Responses are provided in JSON format.
* Data is returned in descending order. Newest first, oldest last.
* All time and timestamp related fields in the JSON responses are in milliseconds.
* Timestamp parameters (e.g. start\_time, end\_time) must be passed in milliseconds.
* The API has a dynamic rate limit set by Cloudflare to prevent spamming.

### RUJI Trade Orderbook DEX

#### Endpoints Overview

<table><thead><tr><th width="60">No.</th><th width="220">Endpoint</th><th>Description</th></tr></thead><tbody><tr><td>1.</td><td>/trade/tickers</td><td>Market related statistics for all markets for the last 24 hours.</td></tr><tr><td>2.</td><td>/trade/orderbook</td><td>Order book depth of any given trading pair, split into two different arrays for bid and ask orders.</td></tr><tr><td>3.</td><td>/trade/historical_trades</td><td>Historical trade data for any given trading pair. </td></tr></tbody></table>

#### Endpoint 1: /trade/tickers (Market Info)

The <https://api.rujira.network/api/trade/tickers> endpoint provides 24-hour pricing and volume information on each market pair available on RUJI Trade DEX.

| Example response                                                                                                                                                                                                                                                                                                                                                                            |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <p>\[</p><p>  {</p><p>    "ticker\_id": "TCY\_RUNE",</p><p>    "base\_currency": "TCY",</p><p>    "target\_currency": "RUNE",</p><p>    "last\_price": "0.24",</p><p>    "base\_volume": 0,</p><p>    "target\_volume": 0,</p><p>    "pair\_id": "thor12ds7fxj5g47jwzfzvzzhzxxd3cp6v55flgwxva0803r8k5mzm44skth6wa",</p><p>    "bid": "0.186",</p><p>    "ask": "0.22"</p><p>  }</p><p>]</p> |

/trade/tickers endpoint response description:

<table><thead><tr><th width="180">Name</th><th width="180">Data Type</th><th>Description</th></tr></thead><tbody><tr><td>ticker_id</td><td>string</td><td>Identifier of a ticker with delimiter to separate base/target, e.g. BTC_ETH</td></tr><tr><td>base_currency</td><td>string</td><td>Symbol/Currency code/Contract Address of a the base cryptoasset, e.g. BTC</td></tr><tr><td>target_currency</td><td>string</td><td>Symbol/Currency code/Contract Address of the target cryptoasset, e.g. ETH (Contract address for DEX)</td></tr><tr><td>last_price</td><td>decimal</td><td><p>Last transacted price of base currency based on given target currency<br>e.g.</p><p>1 base = X target</p></td></tr><tr><td>base_volume</td><td>decimal</td><td>24 hour trading volume for the pair (unit in base)</td></tr><tr><td>target_volume</td><td>decimal</td><td>24 hour trading volume for the pair (unit in target)</td></tr><tr><td>pair_id</td><td>string</td><td>Contract address for the pair</td></tr><tr><td>bid</td><td>decimal</td><td>Current highest bid price</td></tr><tr><td>ask</td><td>decimal</td><td>Current lowest ask price</td></tr></tbody></table>

#### Endpoint 2: /trade/orderbook (Orderbook depth details)

The trade/orderbook/ticker\_id endpoint provides orderbook information for a given market pair/ticker.

Endpoint parameters:

<table><thead><tr><th width="180">Name</th><th width="130">Type</th><th width="130">Mandatory</th><th>Description</th></tr></thead><tbody><tr><td>ticker_id</td><td>string</td><td>Yes</td><td>A ticker such as "BTC_ETH", with delimiter between different cryptoassets</td></tr><tr><td>depth</td><td>integer</td><td>No</td><td>Orders depth quantity: [0, 100, 200, 500...]. 0 returns full depth. Depth = 100 means 50 for each bid/ask side.</td></tr></tbody></table>

Example query: <https://api.rujira.network/api/trade/orderbook?ticker_id=BTC_USDC&depth=100>

| Example response                                                                                                                                                                                                                                                 |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <p>{</p><p>  "ticker\_id": "BTC\_USDC",</p><p>  "asks": \[</p><p>    \[</p><p>      "116329",</p><p>      "0.00157858"</p><p>    ]</p><p>  ],</p><p>  "bids": \[</p><p>    \[</p><p>      "115400",</p><p>      "182.89939237"</p><p>    ]</p><p>  ]</p><p>}</p> |

/trade/orderbook response descriptions:

<table><thead><tr><th width="180">Name</th><th width="180">Data Type</th><th>Description</th></tr></thead><tbody><tr><td>ticker_id</td><td>string</td><td>A pair such as "BTC_ETH", with delimiter between different cryptoassets</td></tr><tr><td>bids</td><td>decimal</td><td>An array containing 2 elements. The offer price and quantity for each bid order</td></tr><tr><td>asks</td><td>decimal</td><td>An array containing 2 elements. The ask price and quantity for each ask order</td></tr></tbody></table>

#### Endpoint 3: /trade/historical\_trades (Historical Data)

The /trade/historical\_trades/ticker\_id endpoint is used to return data on historical completed trades for a given market pair.

Endpoint parameters:

<table><thead><tr><th width="180">Name</th><th width="130">Data Type</th><th width="130">Mandatory</th><th>Description</th></tr></thead><tbody><tr><td>ticker_id</td><td>string</td><td>Yes</td><td>A pair such as "BTC_ETH", with delimiter between different cryptoassets</td></tr><tr><td>type</td><td>string</td><td>No</td><td>To indicate nature of trade - buy/sell</td></tr><tr><td>limit</td><td>integer</td><td>No</td><td>Number of historical trades to retrieve from time of query. [0, 200, 500...]. 0 returns full history.</td></tr><tr><td>start_time</td><td>date</td><td>No</td><td>Start time from which to query historical trades from</td></tr><tr><td>end_time</td><td>date</td><td>No</td><td>End time for historical trades query</td></tr></tbody></table>

Example query: <https://api.rujira.network/api/trade/historical_trades?ticker_id=BTC_USDC&limit=10>

| Example response                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <p>\[</p><p>  {</p><p>    "trade\_id": 21230,</p><p>    "price": "116659.0",</p><p>    "base\_volume": "0.00128579",</p><p>    "target\_volume": "150",</p><p>    "trade\_timestamp": 1754571399738,</p><p>    "type": "buy"</p><p>  },</p><p>  {</p><p>    "trade\_id": 21101,</p><p>    "price": "115271.58095761736",</p><p>    "base\_volume": "0.00000868",</p><p>    "target\_volume": "1",</p><p>    "trade\_timestamp": 1754546289060,</p><p>    "type": "sell"</p><p>  }</p><p>]</p> |

/trade/historical\_trades response descriptions:

<table><thead><tr><th width="180">Name</th><th width="180">Data Type</th><th>Description</th></tr></thead><tbody><tr><td>trade_id</td><td>integer</td><td>A unique ID associated with the trade for the currency pair transaction</td></tr><tr><td>price</td><td>decimal</td><td>Transaction price of base asset in target currency.</td></tr><tr><td>base_volume</td><td>decimal</td><td>Transaction amount in base pair volume.</td></tr><tr><td>target_volume</td><td>decimal</td><td>Transaction amount in target pair volume.</td></tr><tr><td>trade_timestamp</td><td>timestamp</td><td>Unix timestamp in milliseconds for when the transaction occurred.</td></tr><tr><td>type</td><td>string</td><td><p>Used to determine the type of the transaction that was completed.</p><p>Buy – Identifies an ask that was removed from the order book.</p><p>Sell – Identifies a bid that was removed from the order book.</p></td></tr></tbody></table>

### RUJI Token Supply

The /ruji/\* endpoints are used to return data on the RUJI token supply.

<table><thead><tr><th width="60">No.</th><th width="220">Endpoint</th><th>Description</th></tr></thead><tbody><tr><td>1.</td><td>/ruji/holders</td><td>Top 100 wallets/holders of the RUJI token.</td></tr><tr><td>2.</td><td>/ruji/total_supply</td><td>Total RUJI supply.</td></tr><tr><td>3.</td><td>/ruji/circulating_supply</td><td>Current RUJI circulating supply. Calculated as total supply minus currently vesting supply.</td></tr></tbody></table>

Example query: <https://api.rujira.network/api/ruji/holders>


# Trading Bot

The [Funttastic Labs](https://x.com/FunttasticLabs) team has built an open source trading bot template (written in TypeScript) for RUJI Trade orderbook DEX:

* Source code: <https://github.com/funttastic/barracuda-hft>
* Intro video: <https://www.youtube.com/watch?v=w4u9mopMBV4>

## Instructions

### Prerequisites

* Unix-like operating system (Linux, macOS) or, for Windows, Windows Subsystem for Linux (WSL)
* Latest version of [Bun](https://bun.com/)
* [Keplr](https://www.keplr.app/) wallet and access to your wallet mnemonic or private key from Rujira
* Funds in the gas payment token (RUNE), and in your desired base and quote tokens (ex.: RUJI/USDC)
* A Rujira [GraphQL API](/developers/developer-endpoints#graphql-api) authentication token (see below)

### Installation

```
git clone https://github.com/funttastic/barracuda-hft.git
cd barracuda-hft

./setup
```

When prompted, provide your `wallet mnemonic` or your `wallet private key`, or configure them directly in your `resources/configuration/production.yml` file.

### Running

Review all configuration files in `resources/configuration`. Local documentation is included there. Pay special attention to the `rujira.wallet` and `strategy` sections, and double-check that all parameters are tailored to you.

{% hint style="info" %}
**IMPORTANT:** The Rujira GraphQL API has restricted access; you will need an authentication token to use it. Contact the Rujira team at `api@rujira.network` or Funttastic via [Discord](https://www.funttastic.com/discord) to request one.

Configure it in the `rujira.tokens.graphql` section of your `production.yml` configuration file.
{% endhint %}

Then run:

```
./start
```

or

```
bun run start
```

***Disclaimer**: This application is provided as a bootstrap for HFT strategies. You are solely responsible for your trading decisions and financial outcomes. Cryptocurrency trading involves substantial risk, including the potential loss of your entire investment. Funttastic and Rujira are not responsible for any financial losses, bugs, or technical issues. Use at your own risk and only invest what you can afford to lose.*

## FAQ

**Question:** How do I resolve an error like `GraphQL errors: [{"message":"rate bucket full (5000). bucket drains 500/s.\ncontact api@rujira.network to increase your limit.\n","path":["node"],"locations":[{"line":3,"column":7}]}]`?\
**Answer:** You have reached the Rujira GraphQL API rate limit. You will need to wait for it to reset or, preferably, request an authentication token by contacting Rujira at `api@rujira.network` or Funttastic via [Discord](https://www.funttastic.com/discord).

**Question:** How do I reset the strategy state (for example, the initial balances used for comparison and PnL calculations)?\
**Answer:** Delete the file `resources/database/database.sqlite`, which stores the strategy state. Optionally, also delete the log files in the `logs` folder.

**Question:** How to contact the Funttastic team?\
**Answer:** Join [Rujira's Discord](https://discord.gg/XPvsxhWKfb) and ask for support in the [#barracuda-hft-bot](https://discord.com/channels/1280807332766548052/1408109042051715294) dedicated channel.


# Build Ideas

At Rujira, we’re constantly exploring new ways to extend the ecosystem.

This page lists open development ideas: things the community or independent builders can create around our core products.

Each idea is tagged by category, with direct contacts for guidance.

If you decide to build one, **please register your intent (see below)** so we can support you and avoid duplicate work.

{% hint style="info" %}

> *After your MVP goes live, the Rujira team may grant limited-time exclusivity for your product in the ecosystem.*
> {% endhint %}

#### How It Works

1. Learn about THORChain's App Layer and how we do things differently at Rujira
   * Understand that we are looking to build a coherent ecosystem, where protocols are deeply integrated with one another and accessible from a unified UI.
   * Therefore, deploying new smart contracts is permissioned and curated by the core Rujira team.
   * Read THORChain's [ADR-20](https://gitlab.com/thorchain/thornode/-/blob/6a02e7db7b837ce3acedd48cc9ec64dede84aacf/docs/architecture/adr-020-app-layer.md) for context and guiding principles.
   * Review [Rujira Builder's Paths](https://docs.google.com/document/d/1Az7WcXkBoiscixEpjz1_5UQmkrwnNvBW5HPTuu3b-sQ/edit?usp=sharing) to understand how we classify builders and what we have to offer.
   * We are mostly looking for contributors/teams either:
     * Interested in joining the Rujira Alliance (category 1) to develop something unique and that is not part of the existing roadmap; or
     * Building on top of Rujira’s core protocols as independent teams (category 2) and contributing to increased economic activity and user growth within Rujira.
2. Browse Ideas
   * Choose something that matches your skills and interests.
   * Each idea includes a description, helpful links, and Rujira contacts.
3. Register Your Build
   * Send a short email to [bd@rujira.network](mailto:undefined).
   * Include:
     * Idea name
     * Your Telegram handle
     * Estimated timeline
     * Team size
   * Once confirmed, we’ll mark the idea as *“In Progress”* and offer support where possible.
4. Build, Ship, and Share

#### Idea List

Below is a non-exhaustive list of ideas. We will update it over time depending on internally identified needs and community feedback.

<table><thead><tr><th>Category</th><th width="245.6304931640625">Idea</th><th width="588.086669921875">Description</th><th width="316.333251953125">Helpful Links</th><th>Contact</th><th>Status<select><option value="nIZF9WpmbfRK" label="In Progress" color="blue"></option><option value="Dv5Ub9wGoKAH" label="Free" color="blue"></option><option value="K723dbrkyjlT" label="Permissionless" color="blue"></option><option value="G8ihRpN6lAWE" label="In Progress, we want to welcome much more teams" color="blue"></option><option value="6BWCj7vwM8CR" label="In Progress, we want to welcome more contributors" color="blue"></option><option value="g5R0Z1H65AN7" label="In Progress, we want to welcome many more teams" color="blue"></option></select></th></tr></thead><tbody><tr><td>Bot</td><td>Liquidation Path Finder</td><td><p>Since Rujira supports multiple collateral types within its lending and borrowing system, each collateral type requires a unique liquidation path. </p><p>Additionally, a user can define its liquidation preference.</p><p></p><p>Because calculating the optimal path is too computationally intensive to execute on-chain, the protocol allows external actors to submit the optimal liquidation route off-chain and earn a fee for providing that computation.</p></td><td><ul><li><a href="https://gitlab.com/thorchain/rujira/-/blob/ghost-credit/contracts/rujira-ghost-credit/README.md#liquidation">Liquidation System</a></li><li><a href="/pages/fMdWVh0ylNEKgcNwk0dq#liquidations">Liquidation Solver docs</a></li></ul></td><td>@jp_labs</td><td><span data-option="K723dbrkyjlT">Permissionless</span></td></tr><tr><td>Vault</td><td>Systematic strategies</td><td>Build systematic strategies and make them available to the community via Trading vaults, after demonstrating a consistent track record.<br>Strategies could be advanced market making strategies, delta-neutral or directional strategies.<br>They should be built on top of Rujira core primitives, notably RUJI Trade orderbook and can use credit accounts to access leverage or hedging.<br>The AutoRujira team (https://t.me/autorujira) can help you access the smart contract infrastructure you need so you only have to focus on building the strategies.</td><td>NA</td><td>@PragmaticMonkey</td><td><span data-option="g5R0Z1H65AN7">In Progress, we want to welcome many more teams</span></td></tr><tr><td>Alternative Frontends</td><td>Integrate Rujira in your own frontend</td><td>Build your own frontend for any of the Rujira core products, no need to worry about protocol mechanics and bootstrapping liquidity, use our smart contracts in the backend and focus on providing a great UX and marketing it to your audience. Monetize with our upcoming referral and affiliate model: https://gitlab.com/thorchain/rujira/-/issues/11</td><td>NA</td><td>@jp_labs</td><td><span data-option="K723dbrkyjlT">Permissionless</span></td></tr><tr><td>Options</td><td>Option Trading</td><td>If you are an individual contributor with a strong understanding of the options market looking to join the Rujira Alliance to accelerate the development of the Option vertical (category 1), reach out!<br>We are not looking for large teams or dev shops, just a very competent individual with a clear vision and the drive to lead this vertical. Otherwise we will build it ourselves.</td><td><a href="https://docs.rujira.network/core-products/ruji-options">https://docs.rujira.network/core-products/ruji-options</a></td><td>@PragmaticMonkey</td><td><span data-option="Dv5Ub9wGoKAH">Free</span></td></tr><tr><td>Yield tokenization</td><td>Yield tokenization on top of Rujira core primitives</td><td>Build yield tokenization products on top of Rujira core yielding primitives (lending, staking, AMM strategies, etc.). Allow people to swap a variable interest rate for a fixed rate over a given period.<br>If you have the vision and skills, let’s connect!<br>You could launch as an independent value-added project building on top of core verticals (category 2).</td><td>NA</td><td>@PragmaticMonkey</td><td><span data-option="Dv5Ub9wGoKAH">Free</span></td></tr><tr><td>RWA</td><td>Tokenization of RWA via VNFTs</td><td>Build on top of our upcoming VNFT standard to tokenize some Real World Assets. Understand what’s possible, surprise us with original ideas.<br>You could launch as an independent value-added project building on top of core verticals (category 2).</td><td><a href="https://gitlab.com/thorchain/rujira/-/tree/nft/contracts/rujira-vnft">https://gitlab.com/thorchain/rujira/-/tree/nft/contracts/rujira-vnft</a></td><td>@PragmaticMonkey</td><td><span data-option="Dv5Ub9wGoKAH">Free</span></td></tr><tr><td>Games</td><td>Mini Games</td><td><p>If you are an individual contributor with experience building games and interested in joining the Rujira Alliance to contribute to the RUJI Games vertical (category 1), reach out!</p><p><br>We are also interested in mini games built on top of Rujira core primitives (e.g. using high-leverage bets under the hood), in that scenario, you could launch as an independent value-added project building on top of core verticals (category 2).</p></td><td>NA</td><td>@PragmaticMonkey</td><td><span data-option="6BWCj7vwM8CR">In Progress, we want to welcome more contributors</span></td></tr></tbody></table>


# Branding

## Logo

<figure><img src="/files/WhLfgTPoPqqJ0mGf0tBS" alt=""><figcaption><p>Logo with text</p></figcaption></figure>

<figure><img src="/files/kZFQcmw6zeWp9AgFRuMk" alt=""><figcaption><p>Logo without text 200x200 (PNG)</p></figcaption></figure>

## Favicon

### SVG

<div><figure><img src="/files/T1Z6Z8qOhduy7HDSGma4" alt=""><figcaption><p>180x180</p></figcaption></figure> <figure><img src="/files/Gs0nyfOdJTohUnOOkULw" alt=""><figcaption><p>96x96</p></figcaption></figure> <figure><img src="/files/bPVIhlpZJKS9giA6eESl" alt=""><figcaption><p>32x32</p></figcaption></figure> <figure><img src="/files/FqlMNtRTXq1h9Ak77KKx" alt=""><figcaption><p>16x16</p></figcaption></figure></div>

### PNG

<div><figure><img src="/files/nlxSYhJi7DUMz8OiWoNT" alt=""><figcaption><p>180x180</p></figcaption></figure> <figure><img src="/files/G3qD3MfspAIuWFnzMPBg" alt=""><figcaption><p>96x96</p></figcaption></figure> <figure><img src="/files/W0DQw2Eb5ZemZwmSu4sb" alt=""><figcaption><p>32x32</p></figcaption></figure> <figure><img src="/files/AWgEgfXCbq0kkdSdisyy" alt=""><figcaption><p>16x16</p></figcaption></figure></div>

## Colors

### Primary Colors

| Preview                                                             | HEX     |
| ------------------------------------------------------------------- | ------- |
| <img src="/files/wyFVJCl8dSObsAAzwhX2" alt="" data-size="original"> | #d534ea |
| <img src="/files/ylwdsdB2qd0j7rwkhEnz" alt="" data-size="original"> | #843ef6 |
| <img src="/files/IWqt6kkEaSFS5QB8xiGW" alt="" data-size="original"> | #5634d1 |
| <img src="/files/hbbiZBiSHn8huxGIEtVE" alt="" data-size="original"> | #080e50 |
| <img src="/files/YKi4NBrDWya0dK3EVFHw" alt="" data-size="original"> | #ebedf3 |

### Secondary Colors

| Preview                                                             | HEX     |
| ------------------------------------------------------------------- | ------- |
| <img src="/files/vN6rbPxBKf1W343XK0Zt" alt="" data-size="original"> | #5dfbd0 |
| <img src="/files/EgtA1uuV9sghMIAVq5sT" alt="" data-size="original"> | #38a989 |
| <img src="/files/yrbwPxTVRAPDoNM2SzWb" alt="" data-size="original"> | #1892e6 |
| <img src="/files/itHM96GEf14CorFvVrEC" alt="" data-size="original"> | #1e6599 |
| <img src="/files/3dEubuuxk31V8K7FnhJq" alt="" data-size="original"> | #f57b00 |
| <img src="/files/meMsrTUc5NIeDEpSdMUD" alt="" data-size="original"> | #fe5721 |
| <img src="/files/o6vjHaLF8q1Sffr3t0h1" alt="" data-size="original"> | #e53a37 |
| <img src="/files/G0npcqKjtdDEwuLCBBSP" alt="" data-size="original"> | #b81c1d |

### Greys

| Preview                                                             | HEX     |
| ------------------------------------------------------------------- | ------- |
| <img src="/files/kZzPcAWijTctMPN37zFH" alt="" data-size="original"> | #5e7e8d |
| <img src="/files/BZQnubrYWOJhPzxEVWsm" alt="" data-size="original"> | #90a5ae |
| <img src="/files/5kJMMbNOUtk5ELraFu0W" alt="" data-size="original"> | #22242d |
| <img src="/files/bJZ5aI1jDAh9vmd33DV7" alt="" data-size="original"> | #171620 |

## GitLab UI package

{% embed url="<https://gitlab.com/thorchain/rujira-ui/-/tree/staging/packages/ui?ref_type=heads>" %}

{% embed url="<https://ui.rujira.network/install>" %}


# Releases & Contracts

<table><thead><tr><th width="75.796875">Version</th><th width="141.48046875">Product</th><th width="195.00390625">Contract</th><th width="106.05859375">Commit</th><th width="324.5703125">Checksum</th><th width="174.7421875">Audit</th><th>Metadata</th><th data-hidden>Code ID Stagenet</th><th data-hidden>Code ID Mainnet</th></tr></thead><tbody><tr><td>v1.2</td><td>RUJI Trade</td><td>rujira-fin</td><td><a href="https://gitlab.com/thorchain/rujira/-/commit/9e78fabab7d5441743af3e925074beb79912be86">9e78faba</a></td><td><code>f6480e1228ec4a13c76bc3542e4313278232f11d4413470570bbd05307a50c8a</code></td><td><a href="https://getfailsafe.com/rujira-fin-smart-contract-audit">FailSafe</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-fin/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v1.0.0</td><td>RUJI Lending</td><td>rujira-ghost-credit</td><td><a href="https://gitlab.com/thorchain/rujira/-/commit/9989bb5b766e9098ed02582d22cd2df51e80cd7e">9989bb5</a></td><td>beaa3f6558853dbc1c57bcdd1353b26ef1e88083c96973f3b3f34d25e3d36f5a</td><td><a href="https://www.halborn.com/audits/thorchain/credit-accounts-21860f">Halborn</a></td><td><a href="cargo.tomlhttps://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-ghost-credit/Cargo.toml?ref_type=heads">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v1.1</td><td>RUJI Trade</td><td>rujira-fin</td><td><a href="https://gitlab.com/thorchain/rujira/-/commit/306dc1ed3e1705c7d3a3a2753099484916a64504">306dc1e</a></td><td>240a0994d37b7eb80bf2273c4224c736194160353ba6ccd9ae893eeab88794b9</td><td><a href="https://www.halborn.com/audits/thorchain/ruji-trade-fin-v11-9d7ca3">Halborn</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-fin/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v0.0.1</td><td>RUJI Lending</td><td>rujira-ghost-vault</td><td><a href="https://gitlab.com/thorchain/rujira/-/commit/787e63b2ab9e01e80cb9ece0010c2205d93d4565">787e63b2</a></td><td>74c460b811a404e36d3b9b0c3f718c2920f49bbcc15256db8fb063741e5a8475</td><td><a href="https://www.halborn.com/audits/thorchain/ruji-lending-48bc98">Halborn</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/aaf8542c7c019427d68b3103e03ae09d01a94b4d/contracts/rujira-ghost-vault/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v1.0.1</td><td>RUJI Trade</td><td>rujira-fin</td><td><a href="https://gitlab.com/thorchain/rujira/-/commit/7cf789c31cc3718af245e10695103495a7962f80">7cf789c3</a></td><td>6eb73e0bbe8e3da2e757bff9915e96060cc36df1be46914a92bceb95e8cf7920</td><td>Most recent audit in v1.0.0</td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-fin/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v1.0.1</td><td>RUJI Pools</td><td>rujira-bow</td><td><a href="https://gitlab.com/thorchain/rujira/-/commit/0f8e8949a875ea48eedccfee7b01cd6e00f4ae71">0f8e8949</a></td><td>d77de081ae6440fd46cb4620d5fc9e285f2343f972edc0f70685a4b5f9f49536</td><td>Most recent audit in v1.0.0</td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-bow/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v1.2.0</td><td>sTCY</td><td>rujira-staking</td><td><a href="https://gitlab.com/thorchain/rujira/-/tree/3b2942ba9921a700fcd58d19f06f762d9a1131ff">3b2942ba</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/artifacts/checksums.txt?ref_type=heads">artifacts/checksums.txt</a></td><td>Most recent audit in v1.0.1</td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-staking/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v0.1.2</td><td>RUJI Perps</td><td>levana-perpswap-cosmos-market</td><td><a href="https://github.com/Levana-Protocol/levana-perps/commit/c3c3f3d68ade93f6ee8d22883eedee38c23616d8">c3c3f3d</a></td><td>e38323078cecadcaef2293c1ffef31e593c760d597a127778b39039928ae6179</td><td>Most recent audit in v0.1.0</td><td><a href="https://github.com/Levana-Protocol/levana-perps/blob/main/contracts/market/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v1.2.0</td><td>$RUJI</td><td>rujira-staking</td><td><a href="https://gitlab.com/thorchain/rujira/-/commit/c8f91e692f0bd09884adeebf15f8d17f7b2251c2">c8f91e69</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/artifacts/checksums.txt?ref_type=heads">artifacts/checksums.txt</a></td><td>Most recent audit in v1.0.1</td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-staking/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v0.1.0</td><td>RUJI Perps</td><td>levana-perpswap-copy-trading</td><td><a href="https://github.com/Levana-Protocol/levana-perps/commit/85bd6c1c923e1cf617b23332d97a712145dfec68">85bd6c1</a></td><td>490edc0f489111fe3c99ae783b2f5c9c1b5e414f84c93e30cadce74fad014342</td><td><a href="https://github.com/fyeo-io/public-audit-reports/blob/main/Code%20Audit%20Reports/2025/Levana/Levana%20-%20Security%20Code%20Review%20of%20Ruji%20Perps%20v1.0.pdf">FYEO</a></td><td><a href="https://github.com/Levana-Protocol/levana-perps/blob/main/contracts/copy_trading/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v0.1.0</td><td>RUJI Perps</td><td>levana-perpswap-cosmos-copy-trading</td><td><a href="https://github.com/Levana-Protocol/levana-perps/commit/85bd6c1c923e1cf617b23332d97a712145dfec68">85bd6c1</a></td><td>490edc0f489111fe3c99ae783b2f5c9c1b5e414f84c93e30cadce74fad014342</td><td><a href="https://github.com/fyeo-io/public-audit-reports/blob/main/Code%20Audit%20Reports/2025/Levana/Levana%20-%20Security%20Code%20Review%20of%20Ruji%20Perps%20v1.0.pdf">FYEO</a></td><td><a href="https://github.com/Levana-Protocol/levana-perps/blob/main/contracts/copy_trading/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v0.1.0</td><td>RUJI Perps</td><td>levana-perpswap-cosmos-countertrade</td><td><a href="https://github.com/Levana-Protocol/levana-perps/commit/85bd6c1c923e1cf617b23332d97a712145dfec68">85bd6c1</a></td><td>7b2a303549b6e96cdeecaaabb40f862faae7d6f7c079fe28e12da2576caae856</td><td><a href="https://github.com/fyeo-io/public-audit-reports/blob/main/Code%20Audit%20Reports/2025/Levana/Levana%20-%20Security%20Code%20Review%20of%20Ruji%20Perps%20v1.0.pdf">FYEO</a></td><td><a href="https://github.com/Levana-Protocol/levana-perps/blob/main/contracts/countertrade/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v0.1.0</td><td>RUJI Perps</td><td>levana_perpswap_cosmos_cw20</td><td><a href="https://github.com/Levana-Protocol/levana-perps/commit/85bd6c1c923e1cf617b23332d97a712145dfec68">85bd6c1</a></td><td>db05c070060945d2e1117ea743bec96917d3bf5fb6d5d07ea766f6991d100fd9</td><td><a href="https://github.com/fyeo-io/public-audit-reports/blob/main/Code%20Audit%20Reports/2025/Levana/Levana%20-%20Security%20Code%20Review%20of%20Ruji%20Perps%20v1.0.pdf">FYEO</a></td><td><a href="https://github.com/Levana-Protocol/levana-perps/blob/main/contracts/cw20/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v0.1.1</td><td>RUJI Perps</td><td>levana-perpswap-cosmos-factory</td><td><a href="https://github.com/Levana-Protocol/levana-perps/commit/85bd6c1c923e1cf617b23332d97a712145dfec68">85bd6c1</a></td><td>67db51fd0f33477090239930d3e6e4dc29a4175abc59cd2569f515e573083d83</td><td><a href="https://github.com/fyeo-io/public-audit-reports/blob/main/Code%20Audit%20Reports/2025/Levana/Levana%20-%20Security%20Code%20Review%20of%20Ruji%20Perps%20v1.0.pdf">FYEO</a></td><td><a href="https://github.com/Levana-Protocol/levana-perps/blob/main/contracts/factory/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v0.1.1</td><td>RUJI Perps</td><td>levana-perpswap-cosmos-faucet</td><td><a href="https://github.com/Levana-Protocol/levana-perps/commit/85bd6c1c923e1cf617b23332d97a712145dfec68">85bd6c1</a></td><td>d82c0fb47fde35781818fa49e2ae9e441ec9cd298f7c11fb896530792eb8995c</td><td><a href="https://github.com/fyeo-io/public-audit-reports/blob/main/Code%20Audit%20Reports/2025/Levana/Levana%20-%20Security%20Code%20Review%20of%20Ruji%20Perps%20v1.0.pdf">FYEO</a></td><td><a href="https://github.com/Levana-Protocol/levana-perps/blob/main/contracts/faucet/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v0.1.1</td><td>RUJI Perps</td><td>levana-perpswap-cosmos-liquidity-token</td><td><a href="https://github.com/Levana-Protocol/levana-perps/commit/85bd6c1c923e1cf617b23332d97a712145dfec68">85bd6c1</a></td><td>f48d1c4c4bd4c129f421b7026f82614f3ed30759066185f678da7854f61e820a</td><td><a href="https://github.com/fyeo-io/public-audit-reports/blob/main/Code%20Audit%20Reports/2025/Levana/Levana%20-%20Security%20Code%20Review%20of%20Ruji%20Perps%20v1.0.pdf">FYEO</a></td><td><a href="https://github.com/Levana-Protocol/levana-perps/blob/main/contracts/liquidity_token/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v0.1.2</td><td>RUJI Perps</td><td>levana-perpswap-cosmos-market</td><td><a href="https://github.com/Levana-Protocol/levana-perps/commit/85bd6c1c923e1cf617b23332d97a712145dfec68">85bd6c1</a></td><td>fe632b2fde3771d2774ab4df619920ea14df3a99a05e4b09420229cb56c33701</td><td><a href="https://github.com/fyeo-io/public-audit-reports/blob/main/Code%20Audit%20Reports/2025/Levana/Levana%20-%20Security%20Code%20Review%20of%20Ruji%20Perps%20v1.0.pdf">FYEO</a></td><td><a href="https://github.com/Levana-Protocol/levana-perps/blob/main/contracts/market/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v0.1.1</td><td>RUJI Perps</td><td>levana-perpswap-cosmos-position-token</td><td><a href="https://github.com/Levana-Protocol/levana-perps/commit/85bd6c1c923e1cf617b23332d97a712145dfec68">85bd6c1</a></td><td>c654a041bb05201afa7a973a1cfc5a1dc8bfc6f9af1f0f614ac8478a47f61ea5</td><td><a href="https://github.com/fyeo-io/public-audit-reports/blob/main/Code%20Audit%20Reports/2025/Levana/Levana%20-%20Security%20Code%20Review%20of%20Ruji%20Perps%20v1.0.pdf">FYEO</a></td><td><a href="https://github.com/Levana-Protocol/levana-perps/blob/main/contracts/position_token/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v0.1.1</td><td>RUJI Perps</td><td>levana_perpswap_cosmos_tracker</td><td><a href="https://github.com/Levana-Protocol/levana-perps/commit/85bd6c1c923e1cf617b23332d97a712145dfec68">85bd6c1</a></td><td>8d0e2afb763c5e7d9d55a56ecc19eb2d9aa6eac20b66541ef117b0d3caff05a9</td><td><a href="https://github.com/fyeo-io/public-audit-reports/blob/main/Code%20Audit%20Reports/2025/Levana/Levana%20-%20Security%20Code%20Review%20of%20Ruji%20Perps%20v1.0.pdf">FYEO</a></td><td><a href="https://github.com/Levana-Protocol/levana-perps/blob/main/contracts/tracker/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v1.0.0</td><td>RUJI Index</td><td>nami-index-nav</td><td><a href="https://github.com/NAMIProtocol/nami-contracts/commit/3efb8706f2438323d5dbae29c337a11a6509de30">3efb870</a></td><td>e452f0568a1d73f4fb1a61f37df4c19ddd3cf48938fca39f3fb23022d4ddc8dc</td><td><a href="https://www.halborn.com/audits/thorchain/nami-protocol-rujira-index-product-0612c8">Halborn</a></td><td><a href="https://github.com/NAMIProtocol/nami-contracts/blob/audit/contracts/nami-index-nav/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v1.0.0</td><td>RUJI Index</td><td>nami-index-fixed</td><td><a href="https://github.com/NAMIProtocol/nami-contracts/commit/3efb8706f2438323d5dbae29c337a11a6509de30">3efb870</a></td><td>35af30fea124e7136c103048095318f89dbdbfe290015ed2c2aa88ed324488d9</td><td><a href="https://www.halborn.com/audits/thorchain/nami-protocol-rujira-index-product-0612c8">Halborn</a></td><td><a href="https://github.com/NAMIProtocol/nami-contracts/blob/audit/contracts/nami-index-fixed/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v1.0.0</td><td>RUJI Index</td><td>nami-index-entry-adapter</td><td><a href="https://github.com/NAMIProtocol/nami-contracts/commit/3efb8706f2438323d5dbae29c337a11a6509de30">3efb870</a></td><td>e9927b93feeef8fd2e8dcdca4695dddd38d0a832d8e62ad2c0e9cf2826a4f61a</td><td><a href="https://www.halborn.com/audits/thorchain/nami-protocol-rujira-index-product-0612c8">Halborn</a></td><td><a href="https://github.com/NAMIProtocol/nami-contracts/blob/audit/contracts/nami-index-entry-adapter/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v1.0.0</td><td>RUJI Index</td><td>nami-affiliate</td><td><a href="https://github.com/NAMIProtocol/nami-contracts/commit/3efb8706f2438323d5dbae29c337a11a6509de30">3efb870</a></td><td>223ea20a4463696fe32b23f845e9f90ae5c83ef0175894a4b0cec114b7dd4b26</td><td><a href="https://www.halborn.com/audits/thorchain/nami-protocol-rujira-index-product-0612c8">Halborn</a></td><td><a href="https://github.com/NAMIProtocol/nami-contracts/blob/audit/contracts/nami-affiliate/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v1.0.1</td><td>$RUJI</td><td>rujira-mint</td><td><a href="https://gitlab.com/thorchain/rujira/-/commit/25252ec557320d3fb507ad906e08ffa4fa4f5494">25252ec5</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/artifacts/checksums.txt?ref_type=heads">artifacts/checksums.txt</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/merge_requests/13">patch from 1.0.0 for TokenFactory</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-mint/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v1.0.0</td><td>RUJI Trade</td><td>rujira-fin</td><td><a href="https://gitlab.com/thorchain/rujira/-/commit/80b48eddc0f16f735855442fdbc5423ac5398ff6">80b48edd</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/artifacts/checksums.txt?ref_type=heads">artifacts/checksums.txt</a></td><td><a href="https://www.halborn.com/audits/thorchain/ruji-trade-fin-4604e5">Halborn</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-fin/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v1.0.0</td><td>RUJI Pools</td><td>rujira-bow</td><td><a href="https://gitlab.com/thorchain/rujira/-/commit/80b48eddc0f16f735855442fdbc5423ac5398ff6">80b48edd</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/artifacts/checksums.txt?ref_type=heads">artifacts/checksums.txt</a></td><td><a href="https://www.halborn.com/audits/thorchain/ruji-pools-bow-19e51f">Halborn</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-bow/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v1.1.0</td><td>$RUJI</td><td>rujira-revenue</td><td><a href="https://gitlab.com/thorchain/rujira/-/commit/80b48eddc0f16f735855442fdbc5423ac5398ff6">80b48edd</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/artifacts/checksums.txt?ref_type=heads">artifacts/checksums.txt</a></td><td><a href="https://www.halborn.com/audits/thorchain/rujira-staking-319044">Halborn</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-revenue/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v1.0.1</td><td>$RUJI</td><td>rujira-staking</td><td><a href="https://gitlab.com/thorchain/rujira/-/commit/80b48eddc0f16f735855442fdbc5423ac5398ff6">80b48edd</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/artifacts/checksums.txt?ref_type=heads">artifacts/checksums.txt</a></td><td><a href="https://www.halborn.com/audits/thorchain/rujira-staking-319044">Halborn</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-staking/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v1.0.1</td><td>$RUJI</td><td>rujira-merge</td><td><a href="https://gitlab.com/thorchain/rujira/-/commit/80b48eddc0f16f735855442fdbc5423ac5398ff6">80b48edd</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/artifacts/checksums.txt?ref_type=heads">artifacts/checksums.txt</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/merge_requests/8">patch from 1.0.0</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-merge/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v1.0.0</td><td>$RUJI</td><td>rujira-mint</td><td><a href="https://gitlab.com/thorchain/rujira/-/commit/52716f6b83af191d7c2cc261b15c6f08cf9b9836">52716f6b</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/artifacts/checksums.txt?ref_type=heads">artifacts/checksums.txt</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/merge_requests/5">create 1.0.0</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-mint/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v1.0.0</td><td>$RUJI</td><td>rujira-merge</td><td></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/artifacts/checksums.txt?ref_type=heads">artifacts/checksums.txt</a></td><td><a href="https://github.com/Zellic/publications/blob/master/Rujira%20-%20Zellic%20Audit%20Report.pdf">Zellic</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-merge/Cargo.toml">Cargo.toml</a></td><td>2</td><td>1</td></tr><tr><td>v1.0.0</td><td>$RUJI</td><td>rujira-revenue</td><td></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/artifacts/checksums.txt?ref_type=heads">artifacts/checksums.txt</a></td><td><a href="https://github.com/Zellic/publications/blob/master/Rujira%20-%20Zellic%20Audit%20Report.pdf">Zellic</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-revenue/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr><tr><td>v1.0.0</td><td>$RUJI</td><td>rujira-staking</td><td></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/artifacts/checksums.txt?ref_type=heads">artifacts/checksums.txt</a></td><td><a href="https://github.com/Zellic/publications/blob/master/Rujira%20-%20Zellic%20Audit%20Report.pdf">Zellic</a></td><td><a href="https://gitlab.com/thorchain/rujira/-/blob/main/contracts/rujira-staking/Cargo.toml">Cargo.toml</a></td><td></td><td></td></tr></tbody></table>

Notes:

* Cargo.toml (metadata): Lists all the contract's deployer addresses, commits, audits, auditors and docs
* To find a full overview of all deployments made on Rujira Network, go to <https://rujira.network/developer/deployment>


# Partnership Requests

Interested in launching something on Rujira, integrate or discuss some partnerships? Reach out to @Erudite35 or @PragmaticMonkey on Telegram.


# MiCAR Compliant White Paper

Ruji Holdings Limited has voluntarily submitted a MiCA-compliant whitepaper for Rujira token (RUJI), which is classified as an “Other Crypto-Asset” under Regulation (EU) 2023/1114 on Markets in Crypto-Assets (MiCA). Unlike Asset-Referenced Tokens (ARTs), Electronic Money Tokens (EMTs), or Utility Tokens, RUJI is not subject to a mandatory whitepaper requirement. However, pursuant to Article 6(1), second subparagraph of MiCA, service providers may voluntarily publish a whitepaper to promote transparency, regulatory clarity, and investor confidence. This document provides key disclosures regarding Rujira’s characteristics, associated risks, and the exemptions though decentralization to the regulatory framework under which RUJI can be offered within the EU/EEA.

The white paper is available here: [Rujira MiCAR Compliant White Paper\_v1.1.pdf](https://drive.google.com/file/d/1pVN7wRJeN_RLq9kjg9R6zeyLf4fQ49vk/view?usp=sharing)


