Prepared by:
HALBORN
Last Updated 05/02/2025
Date of Engagement: February 3rd, 2025 - February 5th, 2025
100% of all REPORTED Findings have been addressed
All findings
3
Critical
0
High
3
Medium
0
Low
0
Informational
0
THORChain
engaged Halborn to conduct a security assessment of the Rujira Pools (BOW)
contracts, beginning on February 3rd, 2025 and ending on February 5th, 2025. This security assessment was scoped to the smart contracts in the Rujira GitHub repository. Commit hashes and further details can be found in the Scope section of this report.
Rujira Trade (FIN)
is a fully on-chain, decentralized orderbook DEX that combines an O(1) matching algorithm with liquidity from multiple sources, including Rujira's AMM pools (BOW)
and THORChain’s Base Layer liquidity.
The team at Halborn assigned a full-time security engineer to verify the security of the smart contracts. The security engineer is a blockchain and smart-contract security expert with advanced penetration testing, smart-contract hacking, and deep knowledge of multiple blockchain protocols.
The purpose of this assessment is to:
Ensure that smart contract functions operate as intended
Identify potential security issues with the smart contracts
In summary, Halborn identified some improvements to reduce the likelihood and impact of risks, which were successfully addressed by the Rujira team
. The main ones were the following:
Calculate the price using the total pool values to prevent precision loss and underflow errors.
Ensure consistent rounding behavior in both MM and XYK swaps.
Halborn performed a combination of manual and automated security testing to balance efficiency, timeliness, practicality, and accuracy in regard to the scope of this assessment. While manual testing is recommended to uncover flaws in logic, process, and implementation; automated testing techniques help enhance coverage of the code and can quickly identify items that do not follow the security best practices. The following phases and associated tools were used during the assessment:
Research into architecture, purpose, and use of the platform.
Manual code read and walk through.
Manual Assessment of use and safety for the critical Rust variables and functions in scope to identify any arithmetic related vulnerability classes.
Architecture related logical controls.
Cross contract call controls.
Scanning of Rust files for vulnerabilities(cargo audit
)
Review and improvement of integration tests.
Verification of integration tests and implementation of new ones.
EXPLOITABILITY METRIC () | METRIC VALUE | NUMERICAL VALUE |
---|---|---|
Attack Origin (AO) | Arbitrary (AO:A) Specific (AO:S) | 1 0.2 |
Attack Cost (AC) | Low (AC:L) Medium (AC:M) High (AC:H) | 1 0.67 0.33 |
Attack Complexity (AX) | Low (AX:L) Medium (AX:M) High (AX:H) | 1 0.67 0.33 |
IMPACT METRIC () | METRIC VALUE | NUMERICAL VALUE |
---|---|---|
Confidentiality (C) | None (I:N) Low (I:L) Medium (I:M) High (I:H) Critical (I:C) | 0 0.25 0.5 0.75 1 |
Integrity (I) | None (I:N) Low (I:L) Medium (I:M) High (I:H) Critical (I:C) | 0 0.25 0.5 0.75 1 |
Availability (A) | None (A:N) Low (A:L) Medium (A:M) High (A:H) Critical (A:C) | 0 0.25 0.5 0.75 1 |
Deposit (D) | None (D:N) Low (D:L) Medium (D:M) High (D:H) Critical (D:C) | 0 0.25 0.5 0.75 1 |
Yield (Y) | None (Y:N) Low (Y:L) Medium (Y:M) High (Y:H) Critical (Y:C) | 0 0.25 0.5 0.75 1 |
SEVERITY COEFFICIENT () | COEFFICIENT VALUE | NUMERICAL VALUE |
---|---|---|
Reversibility () | None (R:N) Partial (R:P) Full (R:F) | 1 0.5 0.25 |
Scope () | Changed (S:C) Unchanged (S:U) | 1.25 1 |
Severity | Score Value Range |
---|---|
Critical | 9 - 10 |
High | 7 - 8.9 |
Medium | 4.5 - 6.9 |
Low | 2 - 4.4 |
Informational | 0 - 1.9 |
Critical
0
High
3
Medium
0
Low
0
Informational
0
Security analysis | Risk level | Remediation Date |
---|---|---|
Precision Loss in Price Calculation Leading to Underflow Error | High | Solved - 04/08/2025 |
Rounding Errors in Market Maker and XYK Swap Causing Insufficient Return Error | High | Solved - 04/08/2025 |
RUJIRA - Liquidity Overwritten on Deposit | High | Solved - 04/29/2025 |
//
The swap
function from XYK pool incorrectly calculates the price using return_amount / offer_amount
instead of the total amounts in the pool. This results in precision loss that accumulates over swaps.
Eventually, when a user queries a price using QueryMsg::Quote
and try to verify the minimum price condition, the total pool amounts are used for validation. The accumulated precision loss causes a mismatch, leading to an underflow error that reverts all previously executed transactions (including arbitrage operations and fixed-price orders).
Code of swap
function from packages/rujira-rs/src/interfaces/bow/xyk.rs file:
pub fn swap(&mut self, offer_amount: Uint128) -> Result<(Uint128, Decimal), StrategyError> {
let k = self.k;
self.x = self.x.add(offer_amount);
let ratio = Decimal256::from_ratio(self.k, self.x);
let y = self.y;
// Ceil the ask amount in order to ensure rounding maintains new_k > self.k
self.y = Decimal256::one().mul(ratio).to_uint_ceil().try_into()?;
let return_amount = y.sub(self.y);
let price: Decimal = Decimal::from_ratio(return_amount, offer_amount);
self.k = Uint256::from(self.x) * Uint256::from(self.y);
ensure!(self.k >= k, StrategyError::Underflow {});
Ok((return_amount, price))
}
Code of quote
function from packages/rujira-rs/src/interfaces/bow/xyk.rs file:
fn quote(
&self,
deps: Deps,
env: Env,
req: QuoteRequest,
) -> Result<Option<QuoteResponse>, StrategyError> {
let mut state: PoolState = match req.data {
Some(binary) => from_json(binary)?,
None => self.state(
deps,
env,
// Quote is always a query, no need for info.funds
vec![],
req.offer_denom.as_str(),
req.ask_denom.as_str(),
)?,
};
if state.k.lt(&self.min_k) {
return Ok(None);
}
let offer_size = match req.min_price {
Some(price) => {
let offer_dec = Decimal::from_ratio(state.x, 1u128);
let ask_dec = Decimal::from_ratio(state.y, 1u128);
offer_dec.mul(price).sub(ask_dec).div(price).to_uint_floor()
}
None => Decimal::from_ratio(state.x, 1u128)
.mul(self.step)
.to_uint_floor(),
};
Scenario:
This test simulates a full distribution swap in a market-making (MM) environment, utilizing custom setup functions and balance query utilities.
It begins by setting up a liquidity pool and initializing multiple users with balances. Three users create sell orders at a fixed price, and the market maker (MM) is also included as a liquidity provider.
A large swap operation is executed, aiming to distribute 8,100,000 units of eth-usdc, with 8,000,000 allocated to fixed-price orders and 100,000 to the MM. After the swap, the test queries remaining user orders and compares balance changes for the owner, contract, and MM to verify the distribution.
Test:
#[test]
fn test_full_distribution_with_mm() {
let (mut app, contract, contract_mm, fee_address) = setup_with_mm();
let owner = app.api().addr_make("owner");
let funds = vec![
coin(500_000_000_000, "btc-btc"),
coin(500_000_000_000, "eth-usdc"),
];
app.init_modules(|router, _, storage| {
router
.bank
.init_balance(storage, &owner, funds.clone())
.unwrap();
});
let user = app.api().addr_make("user");
app.init_modules(|router, _, storage| {
router
.bank
.init_balance(storage, &user, funds.clone())
.unwrap();
});
let user2 = app.api().addr_make("user2");
app.init_modules(|router, _, storage| {
router
.bank
.init_balance(storage, &user2, funds.clone())
.unwrap();
});
let user3 = app.api().addr_make("user3");
app.init_modules(|router, _, storage| {
router
.bank
.init_balance(storage, &user3, funds.clone())
.unwrap();
});
let owner_balance_before = app.wrap().query_all_balances(owner.clone()).unwrap();
let mm_balance_before = app.wrap().query_all_balances(contract_mm.clone()).unwrap();
let contract_balance_before = app.wrap().query_all_balances(contract.clone()).unwrap();
println!("----> Create Orders ----");
let funds = vec![
coin(100_000_000, "btc-btc"),
coin(100_000_000, "eth-usdc"),
];
app.execute_contract(
user.clone(),
contract.clone(),
&ExecuteMsg::Order(vec![
(
Side::Base,
Price::Fixed(Decimal::from_str("1000.00").unwrap()),
Uint128::from(1000u128),
),
]),
&funds,
)
.unwrap();
app.execute_contract(
user2.clone(),
contract.clone(),
&ExecuteMsg::Order(vec![
(
Side::Base,
Price::Fixed(Decimal::from_str("1000.00").unwrap()),
Uint128::from(2000u128),
),
]),
&funds,
)
.unwrap();
app.execute_contract(
user3.clone(),
contract.clone(),
&ExecuteMsg::Order(vec![
(
Side::Base,
Price::Fixed(Decimal::from_str("1000.00").unwrap()),
Uint128::from(5000u128),
),
]),
&funds,
)
.unwrap();
println!("----> Swap: Full Distribution of 8_100_000 : 8_000_000 for Fixed, 100_000 for MM ----");
let swap_amount = coin(8_100_000, "eth-usdc");
app.execute_contract(
owner.clone(),
contract.clone(),
&ExecuteMsg::Swap(SwapRequest {
min_return: None,
to: None,
callback: None,
}),
&[swap_amount],
)
.unwrap();
println!("-----> Check Orders ------");
let orders_user: OrdersResponse = app
.wrap()
.query_wasm_smart(contract.clone(), &QueryMsg::Orders{owner:user.clone().to_string(),side:None,offset:None,limit:None})
.unwrap();
let orders_user2: OrdersResponse = app
.wrap()
.query_wasm_smart(contract.clone(), &QueryMsg::Orders{owner:user2.clone().to_string(),side:None,offset:None,limit:None})
.unwrap();
let orders_user3: OrdersResponse = app
.wrap()
.query_wasm_smart(contract.clone(), &QueryMsg::Orders{owner:user3.clone().to_string(),side:None,offset:None,limit:None})
.unwrap();
println!("User Orders:");
for (i, order) in orders_user.orders.iter().enumerate() {
println!(" - Order {} -> Filled: {}, Remaining: {}", i, order.filled, order.remaining);
}
println!("");
println!("User2 Orders:");
for (i, order) in orders_user2.orders.iter().enumerate() {
println!(" - Order {} -> Filled: {}, Remaining: {}", i, order.filled, order.remaining);
}
println!("");
println!("User3 Orders:");
for (i, order) in orders_user3.orders.iter().enumerate() {
println!(" - Order {} -> Filled: {}, Remaining: {}", i, order.filled, order.remaining);
}
// --- After all operations ---
// Query the final balances for owner and user.
let owner_balance_after = app.wrap().query_all_balances(owner.clone()).unwrap();
let contract_balance_after = app.wrap().query_all_balances(contract.clone()).unwrap();
let mm_balance_after = app.wrap().query_all_balances(contract_mm.clone()).unwrap();
// Extract the balances for "btc-btc" and "eth-usdc" for each account.
// Owner balances.
let owner_btc_before = get_balance(&owner_balance_before, "btc-btc");
let owner_usdc_before = get_balance(&owner_balance_before, "eth-usdc");
let owner_btc_after = get_balance(&owner_balance_after, "btc-btc");
let owner_usdc_after = get_balance(&owner_balance_after, "eth-usdc");
// Contract balances.
let contract_btc_before = get_balance(&contract_balance_before, "btc-btc");
let contract_usdc_before = get_balance(&contract_balance_before, "eth-usdc");
let contract_btc_after = get_balance(&contract_balance_after, "btc-btc");
let contract_usdc_after = get_balance(&contract_balance_after, "eth-usdc");
//Market Maker balances
let mm_btc_before = get_balance(&mm_balance_before, "btc-btc");
let mm_usdc_before = get_balance(&mm_balance_before, "eth-usdc");
let mm_btc_after = get_balance(&mm_balance_after, "btc-btc");
let mm_usdc_after = get_balance(&mm_balance_after, "eth-usdc");
// ------------------------------------------------------------------
// Print the balance changes for each account.
// Owner outcome.
println!("Owner balance changes:");
print_difference("btc-btc", owner_btc_before, owner_btc_after);
print_difference("eth-usdc", owner_usdc_before, owner_usdc_after);
// Contract outcome.
println!("Contract balance changes:");
print_difference("btc-btc", contract_btc_before, contract_btc_after);
print_difference("eth-usdc", contract_usdc_before, contract_usdc_after);
// Market maker outcome.
println!("Market Maker balance changes:");
print_difference("btc-btc", mm_btc_before, mm_btc_after);
print_difference("eth-usdc", mm_usdc_before, mm_usdc_after);
}
Result:
The swap execution introduces precision loss, which accumulates over multiple transactions. When querying the quote function in the XYK pool, an underflow condition occurs when the min_price
check is performed in the contract. This triggers a reversal of previous operations, disrupting arbitrage, fixed-price orders, and market-making functions.
It is recommended to calculate the price using the total pool values and review the min_price
verification in the quote
function to ensure proper precision adjustments.
SOLVED: The Rujira team has solved this issue by modifying the XYK Strategy code, specifically the quote
and swap
functions, addressing the precision loss problem. The previously failing POC test is now passing successfully.
This issue was fixed across several commits included in this pull request.
//
The Market Maker (MM) swap function rounds the offer_value
upward (to_uint_ceil()
), while the XYK pool swap function also rounds upward when calculating self.y
. This double rounding behavior causes a discrepancy in the expected return amount.
When the final return amount is calculated as y_original - self.y
, it results in a slightly smaller value than expected. When validated against ask_amount
, this difference will trigger the StrategyError::InsufficientReturn error in the contract.
Code of swap
function from packages/rujira-rs/src/interfaces/bow/xyk.rs file:
pub fn swap(&mut self, offer_amount: Uint128) -> Result<(Uint128, Decimal), StrategyError> {
let k = self.k;
self.x = self.x.add(offer_amount);
let ratio = Decimal256::from_ratio(self.k, self.x);
let y = self.y;
// Ceil the ask amount in order to ensure rounding maintains new_k > self.k
self.y = Decimal256::one().mul(ratio).to_uint_ceil().try_into()?;
let return_amount = y.sub(self.y);
let price: Decimal = Decimal::from_ratio(return_amount, offer_amount);
self.k = Uint256::from(self.x) * Uint256::from(self.y);
ensure!(self.k >= k, StrategyError::Underflow {});
Ok((return_amount, price))
}
Code of swap
function from contracts/rujira-fin/src/market_maker.rs file:
fn swap(&mut self, offer: Uint128) -> Result<(Uint128, Uint128), SwapError> {
let offer_value = Decimal::from_ratio(offer, 1u128)
.mul(self.price)
.to_uint_ceil();
let pool_value = Decimal::from_ratio(self.total, 1u128)
.div(self.price)
.to_uint_floor();
let res = match self.total.cmp(&offer_value) {
Ordering::Greater => {
self.total -= offer_value;
(offer, offer_value)
}
// Complete fill
_ => {
let size = self.total;
self.total = Uint128::zero();
(pool_value, size)
}
};
self.commitment = res;
Ok(res)
}
Scenario:
This test simulates a full distribution swap in a market-making (MM) environment, utilizing custom setup functions and balance query utilities.
A large swap operation is executed, aiming to distribute 8,100,000 units of eth-usdc, with 8,000,000 allocated to fixed-price orders and 100,000 to the MM.
After the swap, the test queries remaining user orders and compares balance changes for the owner, contract, and MM to verify the distribution.
NOTE: The min_price
check from Quote function has been skipped in order to continue with this test.
Test:
#[test]
fn test_full_distribution_with_mm() {
let (mut app, contract, contract_mm, fee_address) = setup_with_mm();
let owner = app.api().addr_make("owner");
let funds = vec![
coin(500_000_000_000, "btc-btc"),
coin(500_000_000_000, "eth-usdc"),
];
app.init_modules(|router, _, storage| {
router
.bank
.init_balance(storage, &owner, funds.clone())
.unwrap();
});
let user= app.api().addr_make("user");
app.init_modules(|router, _, storage| {
router
.bank
.init_balance(storage, &user, funds.clone())
.unwrap();
});
let user2= app.api().addr_make("user2");
app.init_modules(|router, _, storage| {
router
.bank
.init_balance(storage, &user2, funds.clone())
.unwrap();
});
let user3= app.api().addr_make("user3");
app.init_modules(|router, _, storage| {
router
.bank
.init_balance(storage, &user3, funds.clone())
.unwrap();
});
let owner_balance_before = app.wrap().query_all_balances(owner.clone()).unwrap();
let mm_balance_before = app.wrap().query_all_balances(contract_mm.clone()).unwrap();
let contract_balance_before = app.wrap().query_all_balances(contract.clone()).unwrap();
println!("----> Create Orders ----");
let funds = vec![
coin(100_000_000, "btc-btc"),
coin(100_000_000, "eth-usdc"),
];
app.execute_contract(
user.clone(),
contract.clone(),
&ExecuteMsg::Order(vec![
(
Side::Base,
Price::Fixed(Decimal::from_str("1000.00").unwrap()),
Uint128::from(1000u128),
),
]),
&funds,
)
.unwrap();
app.execute_contract(
user2.clone(),
contract.clone(),
&ExecuteMsg::Order(vec![
(
Side::Base,
Price::Fixed(Decimal::from_str("1000.00").unwrap()),
Uint128::from(2000u128),
),
]),
&funds,
)
.unwrap();
app.execute_contract(
user3.clone(),
contract.clone(),
&ExecuteMsg::Order(vec![
(
Side::Base,
Price::Fixed(Decimal::from_str("1000.00").unwrap()),
Uint128::from(5000u128),
),
]),
&funds,
)
.unwrap();
println!("----> Swap: Full Distribution of 8_100_000 : 8_000_000 for Fixed, 100_000 for MM ----");
let swap_amount = coin(8_100_000, "eth-usdc");
app.execute_contract(
owner.clone(),
contract.clone(),
&ExecuteMsg::Swap(SwapRequest {
min_return: None,
to: None,
callback: None,
}),
&[swap_amount],
)
.unwrap();
println!("-----> Check Orders ------");
let orders_user: OrdersResponse = app
.wrap()
.query_wasm_smart(contract.clone(), &QueryMsg::Orders{owner:user.clone().to_string(),side:None,offset:None,limit:None})
.unwrap();
let orders_user2: OrdersResponse = app
.wrap()
.query_wasm_smart(contract.clone(), &QueryMsg::Orders{owner:user2.clone().to_string(),side:None,offset:None,limit:None})
.unwrap();
let orders_user3: OrdersResponse = app
.wrap()
.query_wasm_smart(contract.clone(), &QueryMsg::Orders{owner:user3.clone().to_string(),side:None,offset:None,limit:None})
.unwrap();
println!("User Orders:");
for (i, order) in orders_user.orders.iter().enumerate() {
println!(" - Order {} -> Filled: {}, Remaining: {}", i, order.filled, order.remaining);
}
println!("");
println!("User2 Orders:");
for (i, order) in orders_user2.orders.iter().enumerate() {
println!(" - Order {} -> Filled: {}, Remaining: {}", i, order.filled, order.remaining);
}
println!("");
println!("User3 Orders:");
for (i, order) in orders_user3.orders.iter().enumerate() {
println!(" - Order {} -> Filled: {}, Remaining: {}", i, order.filled, order.remaining);
}
// --- After all operations ---
// Query the final balances for owner and user.
let owner_balance_after = app.wrap().query_all_balances(owner.clone()).unwrap();
let contract_balance_after = app.wrap().query_all_balances(contract.clone()).unwrap();
let mm_balance_after = app.wrap().query_all_balances(contract_mm.clone()).unwrap();
// Extract the balances for "btc-btc" and "eth-usdc" for each account.
// Owner balances.
let owner_btc_before = get_balance(&owner_balance_before, "btc-btc");
let owner_usdc_before = get_balance(&owner_balance_before, "eth-usdc");
let owner_btc_after = get_balance(&owner_balance_after, "btc-btc");
let owner_usdc_after = get_balance(&owner_balance_after, "eth-usdc");
// Contract balances.
let contract_btc_before = get_balance(&contract_balance_before, "btc-btc");
let contract_usdc_before = get_balance(&contract_balance_before, "eth-usdc");
let contract_btc_after = get_balance(&contract_balance_after, "btc-btc");
let contract_usdc_after = get_balance(&contract_balance_after, "eth-usdc");
//Market Maker balances
let mm_btc_before = get_balance(&mm_balance_before, "btc-btc");
let mm_usdc_before = get_balance(&mm_balance_before, "eth-usdc");
let mm_btc_after = get_balance(&mm_balance_after, "btc-btc");
let mm_usdc_after = get_balance(&mm_balance_after, "eth-usdc");
// ------------------------------------------------------------------
// Print the balance changes for each account.
// Owner outcome.
println!("Owner balance changes:");
print_difference("btc-btc", owner_btc_before, owner_btc_after);
print_difference("eth-usdc", owner_usdc_before, owner_usdc_after);
// Contract outcome.
println!("Contract balance changes:");
print_difference("btc-btc", contract_btc_before, contract_btc_after);
print_difference("eth-usdc", contract_usdc_before, contract_usdc_after);
// Market maker outcome.
println!("Market Maker balance changes:");
print_difference("btc-btc", mm_btc_before, mm_btc_after);
print_difference("eth-usdc", mm_usdc_before, mm_usdc_after);
}
Result:
The swap fails due to accumulated precision loss from double rounding, causing the return amount to be lower than expected and triggering StrategyError::InsufficientReturn, which results in a transaction revert and disrupts liquidity operations. This triggers a reversal of previous operations, disrupting arbitrage, fixed-price orders, and market-making functions.
It is recommended to ensure consistent rounding behavior in both MM and XYK swaps to mitigate rounding effects and prevent precision loss.
SOLVED: The Rujira team has solved this issue by modifying the XYK Strategy code, specifically the quote
and swap
functions, addressing the precision loss problem. The previously failing POC test is now passing successfully.
This issue was fixed across several commits included in this pull request.
//
The deposit
function incorrectly replaces the pool's internal balances with the new deposit amounts, rather than adding them to the existing totals.
Specifically, the call to state.set(x, y)
stores only the current deposit in the pool state, discarding any previous liquidity.
It is recommended to update the deposit logic to accumulate the new liquidity instead of overwriting.
SOLVED: The Rujira team resolved this issue by updating the logic to add the deposited amounts instead of overwriting the existing pool balances.
state.set(state.x.add(x), state.y.add(y));
Halborn used automated security scanners to assist with detection of well-known security issues and vulnerabilities. Among the tools used was cargo audit
, a security scanner for vulnerabilities reported to the RustSec Advisory Database. All vulnerabilities published in https://crates.io
are stored in a repository named The RustSec Advisory Database. cargo audit
is a human-readable version of the advisory database which performs a scanning on Cargo.lock. Security Detections are only in scope. To better assist the developers maintaining this code, the auditors are including the output with the dependencies tree, and this is included in the cargo audit output to better know the dependencies affected by unmaintained and vulnerable crates.
No security issues were found.
Halborn strongly recommends conducting a follow-up assessment of the project either within six months or immediately following any material changes to the codebase, whichever comes first. This approach is crucial for maintaining the project’s integrity and addressing potential vulnerabilities introduced by code modifications.
// Download the full report
RUJI Pools (BOW)
* Use Google Chrome for best results
** Check "Background Graphics" in the print settings if needed