Insufficient intermediate value precision in StableSwap calculations
The StableSwap helper function used 256-bit integers for intermediate multiplication and division, so swaps involving large token amounts with 18 decimals overflowed and the calculation failed. An attacker or ordinary user could not complete legitimate large swaps, and the pool could be pushed into a state where swaps revert.
Submitted by Lambda
The calculate_stableswap_y function uses Uint256 for intermediate calculations which can cause arithmetic overflow errors when dealing with large token amounts, especially for tokens with high decimal places (e.g. 18 decimals). This significantly impacts the reliability of the StableSwap pool implementation.
Proof of Concept
The issue occurs in src/helpers.rs#L106-L152 where calculate_stableswap_y performs multiplication and division operations using Uint256.
The problem manifests when performing swaps with large token amounts. A proof of concept that demonstrates the failure is provided here:
#[test]
fn test_stableswap_large_swap() {
// Use realistic large pool values (e.g. 1M tokens with 18 decimals)
let large_pool = Uint128::new(1_000_000_000_000_000_000_000_000u128); // 1M tokens
// Large swap amount (100k tokens)
let large_amount = Uint128::new(100_000_000_000_000_000_000_000u128);
let test_cases = vec![
// (amp, offer_pool, ask_pool, offer_amount, description)
(
MIN_AMP,
large_pool,
large_pool,
large_amount,
"Balanced pool, minimum amplification"
),
];
for (amp, offer_pool, ask_pool, offer_amount, description) in test_cases {
println!("\nTesting case: {}", description);
println!("Parameters: amp={}, offer_pool={}, ask_pool={}, offer_amount={}",
amp, offer_pool, ask_pool, offer_amount);
// Convert to Decimal256 for precision
let offer_pool_dec = Decimal256::from_ratio(offer_pool, Uint128::new(1));
let ask_pool_dec = Decimal256::from_ratio(ask_pool, Uint128::new(1));
let offer_amount_dec = Decimal256::from_ratio(offer_amount, Uint128::new(1));
let result = calculate_stableswap_y(
Uint256::from(2u8),
offer_pool_dec,
ask_pool_dec,
offer_amount_dec,
&,
18, // Using 18 decimals precision
StableSwapDirection::Simulate,
);
match result {
Ok(value) => {
println!("Result: {}", value);
}
Err(e) => {
panic!(
"Failed to converge: {:?}",
e
);
}
}
}
}
The test fails with CheckedMultiplyRatioError(Overflow) because intermediate calculations in calculate_stableswap_y overflow Uint256 when dealing with:
- Pool amounts of 1M tokens with 18 decimals (
1e24). - Swap amounts of 100k tokens with 18 decimals (
1e23).
These are realistic values that could occur in production, making this an issue that could prevent legitimate swaps from executing. Moreover, the following was mentioned in the audit description:
Approximation errors when handling very large amounts, especially with assets having 18 decimal places. Think of handling trillions of such assets.
Recommended mitigation steps
Replace Uint256 with Uint512 for intermediate calculations in calculate_stableswap_y. This provides sufficient precision to handle large token amounts with high decimal places.
pub fn calculate_stableswap_y(
n_coins: Uint256,
offer_pool: Decimal256,
ask_pool: Decimal256,
offer_amount: Decimal256,
amp: &u64,
ask_precision: u8,
direction: StableSwapDirection,
) -> Result<Uint128, ContractError> {
// Convert inputs to Uint512 for intermediate calculations
let ann = Uint512::from(Uint256::from_u128((*amp).into()).checked_mul(n_coins)?);
// ... rest of calculations using Uint512
}
The final result can still be converted back to Uint128 since the actual swap amounts will fit within that range. This change ensures the contract can handle realistic token amounts while maintaining precision in the StableSwap calculations.
A test suite should be added that verifies the contract handles large token amounts correctly across different pool configurations and swap scenarios.
jvr0x (MANTRA) confirmed
Context
MANTRA DEX is a decentralised exchange whose pool manager contract implements a StableSwap pool alongside other pool types. StableSwap uses an invariant that mixes a constant-sum and a constant-product curve, and computing the output of a swap requires solving for an unknown pool balance y. In this codebase that solve is done by the calculate_stableswap_y function in src/helpers.rs, which iterates towards a solution using fixed-point decimal arithmetic.
The report concerns the numeric types used inside that function. The pool manager is written in Rust for a CosmWasm-style contract, and the arithmetic relies on the Uint128, Uint256 and Decimal256 types from the cosmwasm-std family. The finding is that the intermediate products in calculate_stableswap_y are computed in Uint256, which is not wide enough for realistic pool sizes once 18-decimal tokens are involved.
Setup
The finding was demonstrated with a unit test written against the helper function directly. The relevant code is at src/helpers.rs, lines 106 to 152, in the audited commit.
The function signature under review takes the number of coins, the offer and ask pool balances, the offer amount, the amplification coefficient, the ask-side precision and a direction enum, and returns a Uint128 result or a ContractError:
pub fn calculate_stableswap_y(
n_coins: Uint256,
offer_pool: Decimal256,
ask_pool: Decimal256,
offer_amount: Decimal256,
amp: &u64,
ask_precision: u8,
direction: StableSwapDirection,
) -> Result<Uint128, ContractError>
Finding it
The researcher observed that calculate_stableswap_y performs its multiplication and division operations using Uint256. The StableSwap y solve involves repeated products of pool balances and amounts, so the intermediate values grow much faster than the inputs. With tokens that use 18 decimals, a pool holding a million tokens is represented as 1e24, and a swap of a hundred thousand tokens as 1e23. Products of numbers at that scale exceed the range of a 256-bit unsigned integer, so the calculation can fail with an arithmetic overflow rather than returning a result.
The audit description for the engagement had already flagged the general risk area: approximation errors when handling very large amounts, especially with assets having 18 decimal places, and the need to think about handling trillions of such assets. The researcher turned that hint into a concrete, reproducible failure.
Exploitation
This is a correctness bug in the contract's arithmetic rather than an attack chain, so the demonstration is a failing unit test. The steps below reproduce it.
Step 1: Build a realistic large pool and swap
The test constructs a balanced pool of one million tokens at 18 decimals and a swap of one hundred thousand tokens, both as Uint128:
#[test]
fn test_stableswap_large_swap() {
// Use realistic large pool values (e.g. 1M tokens with 18 decimals)
let large_pool = Uint128::new([redacted]); // 1M tokens
// Large swap amount (100k tokens)
let large_amount = Uint128::new([redacted]);
The two literals are 1e24 and 1e23 respectively, matching the decimal scaling of an 18-decimal token.
Step 2: Define the test case
A single case is placed in a vector, using the minimum amplification coefficient and identical offer and ask pools:
let test_cases = vec![
// (amp, offer_pool, ask_pool, offer_amount, description)
(
MIN_AMP,
large_pool,
large_pool,
large_amount,
"Balanced pool, minimum amplification"
),
];
Step 3: Convert to Decimal256 and call the helper
Each value is converted to Decimal256 with a ratio over one, and the helper is invoked with two coins, 18 decimals of precision and the Simulate direction:
for (amp, offer_pool, ask_pool, offer_amount, description) in test_cases {
println!("\nTesting case: {}", description);
println!("Parameters: amp={}, offer_pool={}, ask_pool={}, offer_amount={}",
amp, offer_pool, ask_pool, offer_amount);
// Convert to Decimal256 for precision
let offer_pool_dec = Decimal256::from_ratio(offer_pool, Uint128::new(1));
let ask_pool_dec = Decimal256::from_ratio(ask_pool, Uint128::new(1));
let offer_amount_dec = Decimal256::from_ratio(offer_amount, Uint128::new(1));
let result = calculate_stableswap_y(
Uint256::from(2u8),
offer_pool_dec,
ask_pool_dec,
offer_amount_dec,
&,
18, // Using 18 decimals precision
StableSwapDirection::Simulate,
);
Step 4: Observe the failure
The result is matched: a successful value is printed, and an error panics the test with the error's debug representation:
match result {
Ok(value) => {
println!("Result: {}", value);
}
Err(e) => {
panic!(
"Failed to converge: {:?}",
e
);
}
};
}
}
The test fails with CheckedMultiplyRatioError(Overflow). The overflow occurs in the intermediate calculations of calculate_stableswap_y when dealing with pool amounts of one million tokens at 18 decimals (1e24) and swap amounts of one hundred thousand tokens at 18 decimals (1e23).
Root cause
The intermediate products inside calculate_stableswap_y are evaluated in Uint256. The inputs themselves fit comfortably in that type, but the StableSwap solve multiplies balances and amounts together, and the products of values around 1e24 and 1e23 exceed the 256-bit range. The checked arithmetic in the decimal helpers then returns an overflow error instead of a result, so the function cannot converge for these inputs.
The conversion to Decimal256 preserves precision but does not widen the integer type used for the intermediate products. The failure is therefore a limit of the chosen intermediate width.
Impact
Swaps against StableSwap pools holding large balances of high-decimal tokens can fail outright, because the y calculation overflows before it produces an answer. The researcher describes these as realistic values that could occur in production, so the effect is that legitimate swaps are prevented from executing. The report does not quantify how often such pools occur or whether any funds are at risk; the stated impact is on the reliability of the StableSwap pool implementation.
Fix
The recommended mitigation is to replace Uint256 with Uint512 for the intermediate calculations in calculate_stableswap_y, which provides enough precision for large token amounts with high decimal places. The report sketches the start of the change:
pub fn calculate_stableswap_y(
n_coins: Uint256,
offer_pool: Decimal256,
ask_pool: Decimal256,
offer_amount: Decimal256,
amp: &u64,
ask_precision: u8,
direction: StableSwapDirection,
) -> Result<Uint128, ContractError> {
// Convert inputs to Uint512 for intermediate calculations
let ann = Uint512::from(Uint256::from_u128((*amp).into()).checked_mul(n_coins)?);
// ... rest of calculations using Uint512
}
The final result can still be converted back to Uint128, since the actual swap amounts fit within that range. The report also asks for a test suite that verifies the contract handles large token amounts correctly across different pool configurations and swap scenarios. jvr0x of MANTRA confirmed the finding.
- Other fixed-point solves in the same contract. Look for any helper that multiplies two pool balances or a balance and an amount before dividing. A positive result is a unit test with 18-decimal balances in the millions that returns an overflow error rather than a value.
- Higher decimal counts. Repeat the large-pool test with tokens that use more than 18 decimals, if the pool supports them. A positive result is the same overflow at a lower token count.
- Asymmetric pools. Run the test with offer and ask pools of very different sizes, and with amplification values other than the minimum. A positive result is a failure on any configuration that a real pool could reach.
- Boundary search. Increase the pool size in steps until the helper fails, and compare that threshold with the pool sizes the product is expected to hold. A positive result is a threshold below realistic production values.
Hunting notes
This class of bug hides in arithmetic-heavy code: AMM invariants, interest and exchange-rate calculations, and any routine that solves for an unknown balance by iteration. During review, the signals are fixed-width integer types used for intermediate products, checked arithmetic that can return overflow errors, and decimal scaling that multiplies user-facing amounts by large powers of ten. The engagement description itself pointed at large amounts and 18-decimal assets.
The report includes a runnable test with realistic pool and swap sizes that fails with a specific error.
What happened, in plain words
MANTRA DEX is a decentralised exchange: a piece of software that lets people trade one kind of digital token for another without a company in the middle. One of the pool types it offers is called StableSwap, which is designed for trading tokens that are meant to stay close in value to each other. To work out how many tokens a trader should receive, the contract has to solve a small maths problem, and it does that inside a function called calculate_stableswap_y.
The problem is the size of the numbers that function uses while it does its sums. Computers store whole numbers in fixed-size boxes, and each box has a maximum value it can hold. The function was doing its intermediate multiplications in a box that is too small for realistic pool sizes once tokens with 18 decimal places are involved. When the numbers grow past the box's limit, the calculation does not produce an answer at all: it stops with an overflow error. The practical result is that a perfectly normal swap, against a pool holding a million tokens, can be refused.
The researcher, Lambda, demonstrated this with a small automated test that fails with a specific error. jvr0x of MANTRA confirmed the finding. The fix is to do the intermediate sums in a bigger box.
Background you need first
A few ideas come up repeatedly below, so here they are from zero.
A smart contract is a program that lives on a blockchain. Once deployed, it runs the same way for everyone, and nobody can quietly change its behaviour. MANTRA DEX's pool manager is such a contract.
A pool is a pot of tokens that the contract holds on behalf of traders. When you swap, you put one token in and take another out, and the pool's balances change. The contract decides the exchange rate from those balances.
StableSwap is a recipe for deciding that rate. It blends two classic behaviours: one where the total of the two balances stays constant (good for tokens of equal value), and one where the product of the balances stays constant (good for tokens whose prices move). The blend is controlled by a number called the amplification coefficient, usually shortened to amp. A low amp behaves more like the product rule; a high amp behaves more like the sum rule.
Solving for y. To know how much you receive, the contract has to find the pool balance on the output side after your trade. That unknown balance is conventionally called y. There is no neat formula for it, so the code guesses a value and refines the guess over and over until it settles. This is called iteration, and the result is called convergence. If the arithmetic breaks partway through, it never converges.
Decimals. Tokens are whole numbers inside the computer. To allow fractions, a token declares how many decimal places it uses. An 18-decimal token stores one whole token as 1 followed by 18 zeros, that is 1000000000000000000. So a million of those tokens is stored as 1 followed by 24 zeros, written 1e24 for short. A hundred thousand tokens is 1e23.
Integer types and overflow. A computer cannot store an arbitrarily large whole number in a fixed slot. Rust, the language this contract is written in, makes the slot size explicit in the type name. Uint128 holds an unsigned (non-negative) whole number up to 128 bits wide. Uint256 holds up to 256 bits. Uint512 holds up to 512 bits. Each step up roughly squares the maximum value. If a multiplication produces a number bigger than the slot allows, that is an overflow. Rust's checked arithmetic detects this and returns an error instead of silently wrapping around to a wrong number, which is safer but still means the operation fails.
Fixed-point decimals. Decimal256 is a type that stores a fractional number as a scaled integer, keeping a fixed number of digits after the point. It preserves precision, but it does not make the underlying integer slot any wider.
CosmWasm and cosmwasm-std. CosmWasm is a framework for writing smart contracts that run on certain blockchains. cosmwasm-std is its standard library, and it is where Uint128, Uint256, Decimal256 and the checked arithmetic helpers come from.
A unit test is a small program that calls one function directly and checks the result. It is not an attack; it is a way to prove that a specific input produces a specific outcome. Here the outcome is an error, which is exactly the point.
Context
MANTRA DEX is a decentralised exchange whose pool manager contract implements a StableSwap pool alongside other pool types. StableSwap uses an invariant that mixes a constant-sum and a constant-product curve, and computing the output of a swap requires solving for an unknown pool balance y. In this codebase that solve is done by the calculate_stableswap_y function in src/helpers.rs, which iterates towards a solution using fixed-point decimal arithmetic.
The report concerns the numeric types used inside that function. The pool manager is written in Rust for a CosmWasm-style contract, and the arithmetic relies on the Uint128, Uint256 and Decimal256 types from the cosmwasm-std family. The finding is that the intermediate products in calculate_stableswap_y are computed in Uint256, which is not wide enough for realistic pool sizes once 18-decimal tokens are involved.
In plain terms: the inputs fit, but the sums done along the way do not.
Setup
The finding was demonstrated with a unit test written against the helper function directly. A code review means reading the source and reasoning about what it does, rather than poking at a live website. The relevant code is at src/helpers.rs, lines 106 to 152, in the audited commit. A crate is Rust's word for a package of code.
The function signature under review takes the number of coins, the offer and ask pool balances, the offer amount, the amplification coefficient, the ask-side precision and a direction enum, and returns a Uint128 result or a ContractError:
pub fn calculate_stableswap_y(
n_coins: Uint256,
offer_pool: Decimal256,
ask_pool: Decimal256,
offer_amount: Decimal256,
amp: &u64,
ask_precision: u8,
direction: StableSwapDirection,
) -> Result<Uint128, ContractError>
Line by line:
pub fn calculate_stableswap_y(starts the definition of a public function, meaning other parts of the contract can call it.n_coins: Uint256is how many different tokens the pool holds, passed as a 256-bit unsigned integer.offer_pool: Decimal256is the balance of the token the trader is putting in, as a fixed-point decimal.ask_pool: Decimal256is the balance of the token the trader wants out.offer_amount: Decimal256is how much the trader is putting in.amp: &u64is the amplification coefficient, passed by reference (the&means the function borrows it rather than copying it), as a 64-bit unsigned integer.ask_precision: u8is the number of decimal places on the output side, as an 8-bit unsigned integer.direction: StableSwapDirectionis a direction enum passed to the function.-> Result<Uint128, ContractError>is the return type: either a successful 128-bit number, or an error describing what went wrong. Rust forces the caller to deal with both possibilities, which is why the failure below surfaces as a value rather than a crash.
Finding it
The researcher observed that calculate_stableswap_y performs its multiplication and division operations using Uint256. The StableSwap y solve involves repeated products of pool balances and amounts, so the intermediate values grow much faster than the inputs. With tokens that use 18 decimals, a pool holding a million tokens is represented as 1e24, and a swap of a hundred thousand tokens as 1e23. Products of numbers at that scale exceed the range of a 256-bit unsigned integer, so the calculation can fail with an arithmetic overflow rather than returning a result.
An everyday comparison: imagine a till that can display at most six digits. Ringing up a single item priced at 999 is fine, and so is a second item at 999, but the moment the till multiplies them to work out a subtotal it needs seven digits and the display gives up. The individual prices were never the problem; the multiplication was.
The audit description for the engagement had already flagged the general risk area: approximation errors when handling very large amounts, especially with assets having 18 decimal places, and the need to think about handling trillions of such assets. The researcher turned that hint into a concrete, reproducible failure. A hint in a brief is not proof; a failing test is.
Exploitation
This is a correctness bug in the contract's arithmetic rather than an attack chain, so the demonstration is a failing unit test. Nobody steals anything here; the test simply shows that a legitimate request is rejected. The steps below reproduce it.
Step 1: Build a realistic large pool and swap
The test constructs a balanced pool of one million tokens at 18 decimals and a swap of one hundred thousand tokens, both as Uint128:
#[test]
fn test_stableswap_large_swap() {
// Use realistic large pool values (e.g. 1M tokens with 18 decimals)
let large_pool = Uint128::new([redacted]); // 1M tokens
// Large swap amount (100k tokens)
let large_amount = Uint128::new([redacted]);
Line by line:
#[test]is an annotation telling the Rust test runner that the next function is a test to be executed.fn test_stableswap_large_swap() {declares the test function and opens its body.- The comment notes that the values are meant to be realistic: a million tokens with 18 decimals.
let large_pool = Uint128::new([redacted]);creates a 128-bit unsigned integer holding1e24, which is one million tokens scaled by 18 decimal places. Theu128suffix tells Rust the literal is of that type.let large_amount = Uint128::new([redacted]);does the same for the swap size,1e23, that is one hundred thousand tokens.
The two literals are 1e24 and 1e23 respectively, matching the decimal scaling of an 18-decimal token. Choosing production-scale numbers rather than tiny ones is deliberate: a bug that only appears at unrealistic sizes would not matter much.
Step 2: Define the test case
A single case is placed in a vector, using the minimum amplification coefficient and identical offer and ask pools:
let test_cases = vec![
// (amp, offer_pool, ask_pool, offer_amount, description)
(
MIN_AMP,
large_pool,
large_pool,
large_amount,
"Balanced pool, minimum amplification"
),
];
Line by line:
let test_cases = vec![starts a vector, which is Rust's growable list, so several scenarios could be added later.- The comment documents the shape of each entry: amplification, offer pool, ask pool, offer amount, and a human-readable description.
MIN_AMPis the minimum amplification coefficient used in the test.large_pool, large_poolsets both sides of the pool to the same size, so the pool is balanced and nothing about asymmetry can be blamed for the failure.large_amountis the swap size from step 1."Balanced pool, minimum amplification"is the label printed when the test runs, so the output is readable.
Step 3: Convert to Decimal256 and call the helper
Each value is converted to Decimal256 with a ratio over one, and the helper is invoked with two coins, 18 decimals of precision and the Simulate direction:
for (amp, offer_pool, ask_pool, offer_amount, description) in test_cases {
println!("\nTesting case: {}", description);
println!("Parameters: amp={}, offer_pool={}, ask_pool={}, offer_amount={}",
amp, offer_pool, ask_pool, offer_amount);
// Convert to Decimal256 for precision
let offer_pool_dec = Decimal256::from_ratio(offer_pool, Uint128::new(1));
let ask_pool_dec = Decimal256::from_ratio(ask_pool, Uint128::new(1));
let offer_amount_dec = Decimal256::from_ratio(offer_amount, Uint128::new(1));
let result = calculate_stableswap_y(
Uint256::from(2u8),
offer_pool_dec,
ask_pool_dec,
offer_amount_dec,
&,
18, // Using 18 decimals precision
StableSwapDirection::Simulate,
);
Line by line:
for (amp, offer_pool, ask_pool, offer_amount, description) in test_cases {loops over the list, unpacking each entry into named variables.- The two
println!lines print the case label and its parameters, so the test output shows exactly what was tried. Decimal256::from_ratio(offer_pool, Uint128::new(1))turns the integer balance into a fixed-point decimal by dividing it by one. Dividing by one changes nothing numerically; it just moves the value into the decimal type the function expects.- The same conversion is repeated for the ask pool and the offer amount.
let result = calculate_stableswap_y(calls the function under test and stores whatever comes back.Uint256::from(2u8)passes the number of coins as two, in the type the signature requires.- The three decimal values are passed next.
&passes the amplification coefficient by reference.18, // Using 18 decimals precisionsets the output-side precision to 18.StableSwapDirection::Simulatepasses the simulation direction.
Step 4: Observe the failure
The result is matched: a successful value is printed, and an error panics the test with the error's debug representation:
match result {
Ok(value) => {
println!("Result: {}", value);
}
Err(e) => {
panic!(
"Failed to converge: {:?}",
e
);
}
};
}
}
Line by line:
match result {inspects the two possible outcomes of the call.Ok(value) => {handles the success case and binds the returned number tovalue.println!("Result: {}", value);would print the answer if there were one.Err(e) => {handles the failure case and binds the error toe.panic!("Failed to converge: {:?}", e);deliberately aborts the test with a message. The{:?}placeholder prints the error in a developer-readable form, which is how the exact error name becomes visible.- The closing braces end the match, the loop and the function.
The test fails with CheckedMultiplyRatioError(Overflow). The overflow occurs in the intermediate calculations of calculate_stableswap_y when dealing with pool amounts of one million tokens at 18 decimals (1e24) and swap amounts of one hundred thousand tokens at 18 decimals (1e23).
Root cause
The intermediate products inside calculate_stableswap_y are evaluated in Uint256. The inputs themselves fit comfortably in that type, but the StableSwap solve multiplies balances and amounts together, and the products of values around 1e24 and 1e23 exceed the 256-bit range. The checked arithmetic in the decimal helpers then returns an overflow error instead of a result, so the function cannot converge for these inputs.
The conversion to Decimal256 preserves precision but does not widen the integer type used for the intermediate products. The failure is therefore a limit of the chosen intermediate width, not of the input validation.
Impact
Swaps against StableSwap pools holding large balances of high-decimal tokens can fail outright, because the y calculation overflows before it produces an answer. The researcher describes these as realistic values that could occur in production, so the effect is that legitimate swaps are prevented from executing. The report does not quantify how often such pools occur or whether any funds are at risk; the stated impact is on the reliability of the StableSwap pool implementation.
Fix
The recommended mitigation is to replace Uint256 with Uint512 for the intermediate calculations in calculate_stableswap_y, which provides enough precision for large token amounts with high decimal places. The report sketches the start of the change:
pub fn calculate_stableswap_y(
n_coins: Uint256,
offer_pool: Decimal256,
ask_pool: Decimal256,
offer_amount: Decimal256,
amp: &u64,
ask_precision: u8,
direction: StableSwapDirection,
) -> Result<Uint128, ContractError> {
// Convert inputs to Uint512 for intermediate calculations
let ann = Uint512::from(Uint256::from_u128((*amp).into()).checked_mul(n_coins)?);
// ... rest of calculations using Uint512
}
Line by line:
- The signature is unchanged, so callers do not need to be rewritten.
- The comment states the intent: do the working in 512 bits.
let ann =starts computing a value derived from the amplification coefficient and the number of coins, a quantity the StableSwap formula needs.Uint256::from_u128((*amp).into())takes the amplification coefficient, dereferences it with*to get the value, converts it into a 128-bit number, then into a 256-bit number..checked_mul(n_coins)?multiplies that by the number of coins using checked arithmetic, which returns an error rather than wrapping if the result does not fit. The?passes any such error straight back to the caller.Uint512::from(...)widens the product into the 512-bit type, so the later multiplications have room.- The comment notes that the rest of the calculations would follow the same pattern.
The final result can still be converted back to Uint128, since the actual swap amounts fit within that range. The report also asks for a test suite that verifies the contract handles large token amounts correctly across different pool configurations and swap scenarios. jvr0x of MANTRA confirmed the finding.
Once a bug like this is found, the natural next question is where else the same mistake might be hiding.
- Other fixed-point solves in the same contract. Look for any helper that multiplies two pool balances or a balance and an amount before dividing. A positive result is a unit test with 18-decimal balances in the millions that returns an overflow error rather than a value.
- Higher decimal counts. Repeat the large-pool test with tokens that use more than 18 decimals, if the pool supports them. A positive result is the same overflow at a lower token count.
- Asymmetric pools. Run the test with offer and ask pools of very different sizes, and with amplification values other than the minimum. A positive result is a failure on any configuration that a real pool could reach.
- Boundary search. Increase the pool size in steps until the helper fails, and compare that threshold with the pool sizes the product is expected to hold. A positive result is a threshold below realistic production values.
Hunting notes
This class of bug hides in arithmetic-heavy code: AMM invariants, interest and exchange-rate calculations, and any routine that solves for an unknown balance by iteration. An AMM, or automated market maker, is the kind of contract that holds a pool and prices trades from its balances. During review, the signals are fixed-width integer types used for intermediate products, checked arithmetic that can return overflow errors, and decimal scaling that multiplies user-facing amounts by large powers of ten. The engagement description itself pointed at large amounts and 18-decimal assets.
The report includes a runnable test with realistic pool and swap sizes that fails with a specific error.
Glossary
- AMM (automated market maker): a smart contract that holds pools of tokens and sets trade prices from the pool balances, without a traditional order book.
- Amplification coefficient (
amp): a setting in StableSwap that controls how strongly the pool behaves like a constant-sum market rather than a constant-product one. - Checked arithmetic: arithmetic that detects when a result does not fit and returns an error instead of silently producing a wrong number.
- Code review: reading source code carefully to find problems, as opposed to testing a running system from outside.
- Constant-product curve: a pricing rule where the product of the two pool balances stays the same after a trade.
- Constant-sum curve: a pricing rule where the sum of the two pool balances stays the same after a trade.
- Contract (smart contract): a program deployed on a blockchain that runs identically for everyone and cannot be quietly altered.
- Converge: for an iterative calculation, to settle on a stable answer.
- CosmWasm: a framework for writing smart contracts that run on certain blockchains.
cosmwasm-std: the standard library for CosmWasm contracts, providing types such asUint128,Uint256andDecimal256.- Crate: Rust's term for a package of code.
Decimal256: a fixed-point decimal type that stores fractional numbers as scaled integers, preserving precision without widening the integer slot.- Decimals: the number of digits after the point a token uses; an 18-decimal token stores one whole token as
1000000000000000000. - Decentralised exchange (DEX): a service that lets people trade tokens directly through smart contracts rather than a central company.
- Enum: a type whose value is one of a fixed set of named options, such as real swap versus simulation.
- Fixed-point arithmetic: representing fractions as scaled whole numbers so that calculations stay exact and predictable.
- Function signature: the part of a function definition that lists its name, inputs and return type.
- Intermediate value: a number produced partway through a calculation, before the final answer.
- Invariant: a mathematical relationship a pool is designed to preserve across trades.
- Iteration: repeating a calculation, each time refining the previous guess, until it settles.
- Overflow: the situation where a result is too large for the number type holding it.
- Panic: in Rust, an immediate abort of the running program, used in tests here to make a failure loud.
- Pool: the pot of tokens a contract holds on behalf of traders.
- Precision: the number of digits kept after the decimal point.
- Rust: the programming language the contract is written in.
- StableSwap: a pool design that blends constant-sum and constant-product behaviour, intended for tokens meant to hold similar values.
- Unit test: a small program that calls one function directly and checks what it returns.
Uint128,Uint256,Uint512: unsigned whole-number types that can hold values up to 128, 256 and 512 bits wide respectively; each step up allows vastly larger numbers.- Vector (
vec!): Rust's growable list type, used here to hold test cases. y: the unknown pool balance on the output side of a swap that the StableSwap calculation solves for.