Removal of a liquidity pool on AgentToken::removeLiquidityPool still incurs taxes on swaps
Originally disclosed on Code4rena
Submitted by YouCrossTheLineAlfie
Finding description
The AgentToken.sol contract uses tax mechanism whenever swaps take place for the added liquidity pools, which can be observed in the transfer functions.
function transfer(address to, uint256 amount) public virtual override(IERC20) returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount, (isLiquidityPool(owner) || isLiquidityPool(to))); << @ - // if `isLiquidityPool` returns true, then taxes are levied.
return true;
}
The liquidity pools are added via AgentToken::addLiquidityPool and during the AgentToken::_createPair call, which takes place during initialize.
function _createPair() internal returns (address uniswapV2Pair_) {
uniswapV2Pair_ = IUniswapV2Factory(_uniswapRouter.factory()).getPair(address(this), pairToken);
if (uniswapV2Pair_ == address(0)) {
uniswapV2Pair_ = IUniswapV2Factory(_uniswapRouter.factory()).createPair(address(this), pairToken);
emit LiquidityPoolCreated(uniswapV2Pair_);
}
_liquidityPools.add(uniswapV2Pair_); <<@ -- // Here the `uniswapV2Pair_` gets rightfully added
return (uniswapV2Pair_);
}
Similarly, these liquidity pools are removed via AgentToken::removeLiquidityPool
function removeLiquidityPool(address removedLiquidityPool_) external onlyOwnerOrFactory {
// Remove this from the enumerated list:
_liquidityPools.remove(removedLiquidityPool_); <<@
emit LiquidityPoolRemoved(removedLiquidityPool_);
}
However, the issue lies with the way AgentToken::isLiquidityPool has been implemented.
function isLiquidityPool(address queryAddress_) public view returns (bool) {
/** @dev We check the uniswapV2Pair address first as this is an immutable variable and therefore does not need
* to be fetched from storage, saving gas if this address IS the uniswapV2Pool. We also add this address
* to the enumerated set for ease of reference (for example it is returned in the getter), and it does
* not add gas to any other calls, that still complete in 0(1) time.
*/
return (queryAddress_ == uniswapV2Pair || _liquidityPools.contains(queryAddress_)); << @ - // Returns true even if `uniswapV2Pair` is removed.
}
As we can observe, even if the uniswapV2Pair is removed from the _liquidityPools via AgentToken::removeLiquidityPool call, the AgentToken::isLiquidityPool would still return true, which is incorrect and hence, would cause taxes upon swaps leading to unwanted loss of funds for the users.
Impact
Broken AgentToken::isLiquidityPool leads to excessive taxes for swaps to users, leading to loss of funds.
Recommended mitigation steps
It is recommended to set uniswapV2Pair to a dead/zero address to avoid isLiquidityPool returning true.
function removeLiquidityPool(address removedLiquidityPool_) external onlyOwnerOrFactory {
// Remove this from the enumerated list:
_liquidityPools.remove(removedLiquidityPool_);
+ if(removedLiquidityPool_ == uniswapV2Pair){
+ uniswapV2Pair = address(0);
+ }
emit LiquidityPoolRemoved(removedLiquidityPool_);
}
Proof of Concept
The test case below was ran using a base mainnet fork, please add the same to the hardhat.config.js file. The hardhat version wasn’t supporting the base mainnet fork, so it had to be upgraded:
"hardhat": "^2.23.0",
Add the following values to the .env file (along with private keys):
### Genesis DAO settings
GENESIS_VOTING_DELAY=0
GENESIS_VOTING_PERIOD=900
GENESIS_PROPOSAL_THRESHOLD=0
### Virtual DAO settings
PROTOCOL_VOTING_DELAY=0
PROTOCOL_VOTING_PERIOD=900
PROTOCOL_PROPOSAL_THRESHOLD=1000000000000000000000000
PROTOCOL_QUORUM_NUMERATOR=1000
### Other settings
CHAIN_ID=84532
VIRTUAL_APPLICATION_THRESHOLD=50000000000000000000 # 50
VIRTUAL_APPLICATION_THRESHOLD_VIP=125000000000000000000 #125 $V
MATURITY_DURATION=1000 # number of blocks until initial virtual staker can withdraw (1000 blocks = ~33 minutes)
### AgentToken settings
AGENT_TOKEN_SUPPLY=1000000000 # 1B supply
AGENT_TOKEN_LIMIT_TRX=100000 # 100k max token per txn
AGENT_TOKEN_LIMIT_WALLET=1000000 # 1M token per wallet
AGENT_TOKEN_LP_SUPPLY=1000000000 # 1B LP tokens
AGENT_TOKEN_LIMIT=1000000000
AGENT_TOKEN_VAULT_SUPPLY=0 #
BOT_PROTECTION=3600 # 1hr
TAX=100 # 3%
BONDING_TAX=1
SWAP_THRESHOLD=1 # 0.00001% of total supply
### VOTING_TOKEN=
TBA_REGISTRY=
### Reward settings
PARENT_SHARES=2000 # 20%
PROTOCOL_SHARES=1000 # 10%
CONTRIBUTOR_SHARES=5000 # 50%
STAKER_SHARES=9000 # 90%
REWARD_STAKE_THRESHOLD=2000000000000000000 # 2 eth
DATASET_SHARES=7000 # 70%
### TAX MANAGER
MIN_SWAP_THRESHOLD=100000000000000000 # 0.1
MAX_SWAP_THRESHOLD=1000000000000000000000 # 1000
UNISWAP_ROUTER=0x4752ba5dbc23f44d87826276bf6fd6b1c372ad24
Create a file called PoC.js and add the following test case inside the /tests folder and run npx hardhat test --grep "Removed liquidity pair still accrues taxes":
const { parseEther, toBeHex, formatEther } = require("ethers/utils");
const { expect } = require("chai");
const {
loadFixture,
mine,
impersonateAccount,
setBalance,
} = require("@nomicfoundation/hardhat-toolbox/network-helpers");
const { ethers } = require("hardhat");
describe("AgentFactory", () => {
const PROPOSAL_THRESHOLD = parseEther("50000"); // 50k
const MATURITY_SCORE = toBeHex(2000, 32); // 20%
const IP_SHARE = 1000; // 10%
const genesisInput = {
name: "Jessica",
symbol: "JSC",
tokenURI: "http://jessica",
daoName: "Jessica DAO",
cores: [0, 1, 2],
tbaSalt:
"0xa7647ac9429fdce477ebd9a95510385b756c757c26149e740abbab0ad1be2f16",
tbaImplementation: process.env.TBA_IMPLEMENTATION || ethers.ZeroAddress,
daoVotingPeriod: 600,
daoThreshold: 1000000000000000000000n,
};
const getAccounts = async () => {
const [deployer, ipVault, founder, poorMan, trader, treasury, randomAddr] = await ethers.getSigners();
// Fund all accounts with ETH for gas (10 ETH each)
const fundAccounts = [deployer, ipVault, founder, poorMan, trader, treasury];
for (const account of fundAccounts) {
await setBalance(account.address, parseEther("10"));
}
return { deployer, ipVault, founder, poorMan, trader, treasury, randomAddr };
};
async function deployBaseContracts() {
const { deployer, ipVault, treasury } = await getAccounts();
// Setting up environment variables if not present in the actual .env
// This is for testing purposes only
if (!process.env.TBA_IMPLEMENTATION) process.env.TBA_IMPLEMENTATION = ethers.ZeroAddress;
if (!process.env.DATASET_SHARES) process.env.DATASET_SHARES = "1000"; // 10%
if (!process.env.UNISWAP_ROUTER) process.env.UNISWAP_ROUTER = "0x8aEF2b5C33686F8621A17B9Aaff079E7d8D673f9"; // Base mainnet Uniswap router
if (!process.env.AGENT_TOKEN_LIMIT) process.env.AGENT_TOKEN_LIMIT = parseEther("10000000").toString(); // 10M
if (!process.env.AGENT_TOKEN_LP_SUPPLY) process.env.AGENT_TOKEN_LP_SUPPLY = parseEther("5000000").toString(); // 5M
if (!process.env.AGENT_TOKEN_VAULT_SUPPLY) process.env.AGENT_TOKEN_VAULT_SUPPLY = parseEther("2000000").toString(); // 2M
if (!process.env.BOT_PROTECTION) process.env.BOT_PROTECTION = "100"; // 1%
if (!process.env.TAX) process.env.TAX = "500"; // 5%
if (!process.env.SWAP_THRESHOLD) process.env.SWAP_THRESHOLD = parseEther("10").toString(); // 10 tokens
console.log("Deploying VirtualToken...");
const virtualToken = await ethers.deployContract(
"VirtualToken",
[PROPOSAL_THRESHOLD, deployer.address],
{}
);
await virtualToken.waitForDeployment();
console.log(`VirtualToken deployed at ${virtualToken.target}`);
console.log("Deploying ERC6551Registry Registry");
const tbaRegistry = await ethers.deployContract("ERC6551Registry");
await tbaRegistry.waitForDeployment();
console.log("Deployed ERC6551Registry Registry");
console.log("Deploying AgentNftV2...");
const AgentNft = await ethers.getContractFactory("AgentNftV2");
const agentNft = await upgrades.deployProxy(AgentNft, [deployer.address]);
console.log(`AgentNftV2 deployed at ${agentNft.target}`);
console.log("Deploying ContributionNft...");
const contribution = await upgrades.deployProxy(
await ethers.getContractFactory("ContributionNft"),
[agentNft.target],
{}
);
console.log(`ContributionNft deployed at ${contribution.target}`);
console.log("Deploying ServiceNft...");
const service = await upgrades.deployProxy(
await ethers.getContractFactory("ServiceNft"),
[agentNft.target, contribution.target, process.env.DATASET_SHARES],
{}
);
console.log(`ServiceNft deployed at ${service.target}`);
await agentNft.setContributionService(contribution.target, service.target);
console.log("Set contribution and service on AgentNft");
// Implementation contracts
console.log("Deploying AgentToken...");
const agentToken = await ethers.deployContract("AgentToken");
await agentToken.waitForDeployment();
console.log(`AgentToken deployed at ${agentToken.target}`);
console.log("Deploying AgentDAO...");
const agentDAO = await ethers.deployContract("AgentDAO");
await agentDAO.waitForDeployment();
console.log(`AgentDAO deployed at ${agentDAO.target}`);
console.log("Deploying AgentVeToken...");
const agentVeToken = await ethers.deployContract("AgentVeToken");
await agentVeToken.waitForDeployment();
console.log(`AgentVeToken deployed at ${agentVeToken.target}`);
console.log("Deploying AgentFactoryV2...");
const agentFactory = await upgrades.deployProxy(
await ethers.getContractFactory("AgentFactoryV2"),
[
agentToken.target,
agentVeToken.target,
agentDAO.target,
tbaRegistry.target,
virtualToken.target,
agentNft.target,
PROPOSAL_THRESHOLD,
deployer.address,
]
);
await agentFactory.waitForDeployment();
console.log(`AgentFactoryV2 deployed at ${agentFactory.target}`);
await agentNft.grantRole(await agentNft.MINTER_ROLE(), agentFactory.target);
console.log("Granted MINTER_ROLE to AgentFactory");
console.log("Deploying Minter...");
const minter = await upgrades.deployProxy(
await ethers.getContractFactory("Minter"),
[
service.target,
contribution.target,
agentNft.target,
1e12,
20,
ipVault.address,
agentFactory.target,
deployer.address,
1e10,
]
);
await minter.waitForDeployment();
console.log(`Minter deployed at ${minter.target}`);
console.log("Setting parameters on AgentFactory...");
await agentFactory.setMaturityDuration(86400 * 365 * 10); // 10years
await agentFactory.setUniswapRouter(process.env.UNISWAP_ROUTER);
await agentFactory.setTokenAdmin(deployer.address);
await agentFactory.setTokenSupplyParams(
process.env.AGENT_TOKEN_LIMIT,
process.env.AGENT_TOKEN_LP_SUPPLY,
process.env.AGENT_TOKEN_VAULT_SUPPLY,
process.env.AGENT_TOKEN_LIMIT,
process.env.AGENT_TOKEN_LIMIT,
process.env.BOT_PROTECTION,
minter.target
);
await agentFactory.setTokenTaxParams(
process.env.TAX,
process.env.TAX,
process.env.SWAP_THRESHOLD,
treasury.address
);
console.log("AgentFactory parameters set");
return { virtualToken, agentFactory, agentNft, minter, tbaRegistry };
}
async function deployWithApplication() {
const base = await deployBaseContracts();
const { agentFactory, virtualToken, tbaRegistry } = base;
const { founder } = await getAccounts();
// Prepare tokens for proposal
console.log("Minting VirtualToken for founder...");
await virtualToken.mint(founder.address, PROPOSAL_THRESHOLD);
await virtualToken
.connect(founder)
.approve(agentFactory.target, PROPOSAL_THRESHOLD);
console.log("Proposing agent...");
const tx = await agentFactory
.connect(founder)
.proposeAgent(
genesisInput.name,
genesisInput.symbol,
genesisInput.tokenURI,
genesisInput.cores,
genesisInput.tbaSalt,
tbaRegistry.target,
genesisInput.daoVotingPeriod,
genesisInput.daoThreshold
);
await tx.wait();
const filter = agentFactory.filters.NewApplication;
const events = await agentFactory.queryFilter(filter, -1);
const event = events[0];
const { id } = event.args;
console.log(`Agent application created with ID: ${id}`);
return { applicationId: id, ...base };
}
async function deployWithAgent() {
const base = await deployWithApplication();
const { agentFactory, applicationId } = base;
const { founder } = await getAccounts();
console.log("Executing application...");
await agentFactory
.connect(founder)
.executeApplication(applicationId, false);
const factoryFilter = agentFactory.filters.NewPersona;
const factoryEvents = await agentFactory.queryFilter(factoryFilter, -1);
const factoryEvent = factoryEvents[0];
const { virtualId, token, veToken, dao, tba, lp } = await factoryEvent.args;
console.log(`Agent created with virtualId: ${virtualId}`);
return {
...base,
agent: {
virtualId,
token,
veToken,
dao,
tba,
lp,
},
};
}
before(async function () {
// Increase timeout for all tests
this.timeout(60000);
});
it("Removed liquidity pair still accrues taxes", async function () {
const { agent, agentNft, virtualToken} = await loadFixture(
deployWithAgent
);
const { trader, poorMan, founder, randomAddr, deployer } = await getAccounts();
const router = await ethers.getContractAt(
"IUniswapV2Router02",
process.env.UNISWAP_ROUTER
);
const agentToken = await ethers.getContractAt("AgentToken", agent.token);
const uniswapV2Pair = await agentToken.uniswapV2Pair();
console.log("uniswapV2Pair: ", uniswapV2Pair);
await agentToken.connect(deployer).removeLiquidityPool(uniswapV2Pair);
// Should still assert isLiquidityPool as true
expect(await agentToken.isLiquidityPool(uniswapV2Pair)).to.be.eq(true);
});
});
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
What is known
A medium-severity business logic bug in Virtuals Protocol. Code4rena made it public on 4 August 2025. Found in the 2025-04-virtuals-protocol audit contest (finding M-13).
About Business logic
The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
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.