> For the complete documentation index, see [llms.txt](https://docs.rujira.network/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.rujira.network/developers/elixir-library-rujira_ex.md).

# Elixir Library (rujira\_ex)

`rujira_ex` is an Elixir library for querying Rujira and THORChain data, resolving assets and amounts, and parsing blockchain events.

You can use it directly within an Elixir application or as the data layer of a service consumed by applications written in other languages. For example, an Elixir service using `rujira_ex` can supply market data and parsed events to a trading bot written in Python, TypeScript, or Rust through an API, message queue, or database.

This lets builders use `rujira_ex` for data collection and processing while choosing their preferred language for trading strategies, user interfaces, and transaction execution.

[View the repository](https://github.com/RujiraNetwork/rujira_ex) · [View the Hex package](https://hex.pm/packages/rujira_ex)

### What can you build?

Use `rujira_ex` to build applications that connect users and trading strategies to Rujira’s markets:

* **Trading bots:** use market data, order books, and order queries to inform automated trading strategies. Combine these reads with your application’s transaction signing and submission to place and manage orders on RUJI Trade.
* **Market-making tools:** monitor market conditions, existing orders, and liquidity ranges to support strategies that quote prices and provide liquidity.
* **Strategy monitoring and analytics:** process trade events and query protocol state to track fills, analyse strategy activity, and identify when your application should act.
* **Market dashboards:** help traders explore available pairs, inspect order book depth, and make informed trading decisions.
* **Trading interfaces and execution services:** build backend services that supply market data and track orders for user-facing trading applications.

`rujira_ex` provides the data-querying and event-parsing components for these applications. Your application supplies the strategy logic, wallet integration, transaction signing and submission, and operational controls.

For applications that need access to Rujira’s hosted GraphQL or REST APIs, see [Developer Endpoints](https://docs.rujira.network/developers/developer-endpoints).

### Main components

| Component                         | Purpose                                                        |
| --------------------------------- | -------------------------------------------------------------- |
| `Rujira.Fin`                      | Query RUJI Trade markets, order books, orders, and ranges.     |
| `Rujira.Events`                   | Parse blockchain events into protocol-specific structs.        |
| `Rujira.Assets`                   | Resolve asset identifiers and chain denominations.             |
| `Rujira.Amount` and `Rujira.Coin` | Work with amounts and asset–amount pairs.                      |
| `Rujira.Contracts`                | Query CosmWasm smart contracts.                                |
| `Rujira.Deployments`              | Resolve deployed contracts from THORChain’s on-chain registry. |
| `Rujira.Node`                     | Connect the library to your application’s gRPC node client.    |

### Quick start

#### 1. Install the library

You need an Elixir project using Elixir 1.18 or a compatible later 1.x release.

Add the dependency to the existing dependency list in `mix.exs`:

```elixir
{:rujira_ex, "~> 0.7.2"}
```

Fetch dependencies and start an interactive session:

```bash
mix deps.get
iex -S mix
```

#### 2. Work with amounts

THORChain and Rujira represent asset amounts as integers using eight decimal places. One whole unit is `100_000_000`, so an amount of `150_000_000` represents 1.5 units.

Use `Rujira.Amount.new/1` to parse an amount supplied as a string, then `format/1` to produce a human-readable value. This example does not require a node connection:

```elixir
# An amount already expressed in eight-decimal base units.
{:ok, amount} = Rujira.Amount.new("150000000")
# amount is 150_000_000

Rujira.Amount.format(amount)
# "1.5"
```

`new/1` parses the supplied base-unit amount without changing its precision. `format/1` converts the eight-decimal integer into a display string.

If your application also reads raw amounts directly from external chains, use `Rujira.Amount.normalize/2` to convert their native precision into eight decimals. For example, a six-decimal amount of `1_500_000` becomes `150_000_000`; both represent 1.5 units. Only apply this conversion when the input is still expressed in the external chain’s native precision.

#### 3. Configure chain queries

To read chain data, provide a module implementing the `Rujira.Node` behaviour and configure it in your application:

```elixir
# config/config.exs
import Config

config :rujira_ex,
  node: MyApp.Node
```

`MyApp.Node` represents a module you implement. Its `query/3` function connects queries to your gRPC client. The implementation must forward query options and preserve the returned response metadata, which the library uses to verify queries at a specific block height.

See the [Rujira.Node implementation contract](https://github.com/RujiraNetwork/rujira_ex/blob/main/lib/rujira/node.ex) and [Developer Endpoints](https://docs.rujira.network/developers/developer-endpoints) for connection options.

#### 4. Discover RUJI Trade markets

Once your node implementation is configured, your application can advance the library to a confirmed block height and query the available pairs:

```elixir
# height comes from your application's block listener or indexer.
with :ok <- Rujira.Node.advance(height) do
  Rujira.Fin.list_pairs(height: height)
end
```

This returns `{:ok, pairs}` on success or an error tuple if the operation fails.

Listing pairs is the starting point for a trading integration. From there, use `Rujira.Fin.get_pair/2` and `Rujira.Fin.load_pair/3` to inspect a market and its order book, then query orders or liquidity ranges relevant to your application.

A trading bot can use these reads to evaluate market conditions, submit transactions through its execution layer, and monitor subsequent blocks to check the outcome.

#### 5. Keep your application up to date

Keep calling `Rujira.Node.advance/1` as new blocks arrive. The library uses block events to update its cache.

Queries without an explicit `height:` use the library’s current head—the latest block height it has applied. Before the first successful advance, these cached queries return `{:error, :no_head}`.

Pass the same explicit `height:` to related queries when your application needs a consistent view of a market at one block. Queries at historical heights depend on the connected node retaining the requested data.

See the [caching guide](https://github.com/RujiraNetwork/rujira_ex/blob/main/guides/caching.md) for the full model.

### Working with events

`Rujira.Events` converts chain events into structs your application can inspect through Elixir pattern matching. For example, a recognised FIN trade is represented by a `Rujira.Fin.Events.Event` envelope containing `Rujira.Fin.Events.Trade` data.

For trading applications, events help connect a submitted action to what happened on-chain. Your application can use recognised trade events to record fills, update its view of market activity, or trigger a strategy review. Combine event processing with order queries to reconcile the state your application tracks.

You can handle specific actions, such as trades, or broader groups of protocol events. Your application remains responsible for receiving the events, handling parsing errors, and storing or processing the results.

Follow the [event pipeline walkthrough](https://github.com/RujiraNetwork/rujira_ex/blob/main/guides/event_pipeline.md) for a complete example.

### Further reading

* [README and usage examples](https://github.com/RujiraNetwork/rujira_ex#readme)
* [Architecture](https://github.com/RujiraNetwork/rujira_ex/blob/main/guides/architecture.md) — protocol modules, resources, event routing, and adding support for a protocol.
* [Caching](https://github.com/RujiraNetwork/rujira_ex/blob/main/guides/caching.md) — block heights, cache updates, historical reads, and configuration.
* [Event pipeline](https://github.com/RujiraNetwork/rujira_ex/blob/main/guides/event_pipeline.md) — how a raw event becomes a structured value.
* [Coding conventions](https://github.com/RujiraNetwork/rujira_ex/blob/main/guides/conventions.md) — guidance for contributing to the library.


---

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

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

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

```
GET https://docs.rujira.network/developers/elixir-library-rujira_ex.md?ask=<question>&goal=<user_goal>
```

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

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

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
