VotesUpgradeable::delegate bypasses the addValidator call, leads to a non-validator holding voting power along with loss of rewards
Originally disclosed on Code4rena
Submitted by YouCrossTheLineAlfie
Finding description
The AgentVeToken::stake allows users to stake their tokens in exchange of the power to delegate voting power to a delegatee. This delegatee can now take part in the governance process via AgentDAO contract.
These delegates are rewarded via AgentReward contract, this is performed via storing the validators during stake.
function stake(uint256 amount, address receiver, address delegatee) public {
// . . . Rest of the code . . .
if (totalSupply() == 0) {
initialLock = amount;
}
registry.addValidator(virtualId, delegatee); <<@ -- // Validators are added to the registry every time a stake happens.
IERC20(assetToken).safeTransferFrom(sender, address(this), amount);
_mint(receiver, amount);
_delegate(receiver, delegatee);
_balanceCheckpoints[receiver].push(clock(), SafeCast.toUint208(balanceOf(receiver)));
}
This registry is used inside the AgentRewardV2 and AgentRewardV3 contract via _distributeValidatorRewards and claimAllValidatorRewards respectively. However, there’s a loophole which allows stakers (which includes the founder) to delegate their votes to someone else who is not even a validator. This can be done via the VotesUpgradeable::delegate, the VotesUpgradeable is deeply nested, the way to reach this file is shown below:
(consider -> as inherits keyword)
AgentVeToken -> ERC20Votes -> ERC20VotesUpgradeable -> VotesUpgradeable
/**
* @dev Delegates votes from the sender to `delegatee`.
*/
function delegate(address delegatee) public virtual {
address account = _msgSender();
_delegate(account, delegatee);
}
As we can observe, this functionality by-passes the AgentNftV2::addValidator call; hence, allowing a non-validator to be involved in the governance process and at the same time, rewards would lost for both the staker and delegatee.
Impact
- Allows delegation to a non-validator (breaking core functionality).
- No validator would be added here to the registry upon
VotesUpgradeable::delegatecall. - No party here earns any rewards via
AgentRewardcontracts.
Recommended mitigation steps
Changing delegates via AgentVeToken::stake is sub-optimal, so the recommended solution would be to override the VotesUpgradeable::delegate and modify it to add the addValidator call:
function delegate(address delegatee) public override {
address account = _msgSender();
IAgentNft registry = IAgentNft(agentNft);
uint256 virtualId = registry.stakingTokenToVirtualId(address(this));
registry.addValidator(virtualId, delegatee);
_delegate(account, delegatee);
}
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 "Delegate a non-validator":
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("Delegate a non-validator", async function () {
// Need to provide LP first
const { agent, agentNft, virtualToken } = await loadFixture(
deployWithAgent
);
const { trader, poorMan, founder, randomAddr } = await getAccounts();
const router = await ethers.getContractAt(
"IUniswapV2Router02",
process.env.UNISWAP_ROUTER
);
const agentToken = await ethers.getContractAt("AgentToken", agent.token);
// Buy tokens
const amountToBuy = parseEther("10000000");
const capital = parseEther("200000000");
await virtualToken.mint(trader.address, capital);
await virtualToken
.connect(trader)
.approve(process.env.UNISWAP_ROUTER, capital);
await router
.connect(trader)
.swapTokensForExactTokens(
amountToBuy,
capital,
[virtualToken.target, agent.token],
trader.address,
Math.floor(new Date().getTime() / 1000 + 600000)
);
////
// Start providing liquidity
const lpToken = await ethers.getContractAt("ERC20", agent.lp);
const veToken = await ethers.getContractAt("AgentVeToken", agent.veToken);
await veToken.connect(founder).setCanStake(true);
expect(await lpToken.balanceOf(trader.address)).to.be.equal(0n);
await agentToken
.connect(trader)
.approve(process.env.UNISWAP_ROUTER, parseEther("10000000"));
await virtualToken
.connect(trader)
.approve(process.env.UNISWAP_ROUTER, parseEther("10000000"));
await router
.connect(trader)
.addLiquidity(
agentToken.target,
virtualToken.target,
await agentToken.balanceOf(trader.address),
await virtualToken.balanceOf(trader.address),
0,
0,
trader.address,
Math.floor(new Date().getTime() / 1000 + 6000)
);
/////////////////
// Staking, and able to delegate to anyone
await lpToken.connect(trader).approve(agent.veToken, parseEther("100"));
await expect(
veToken
.connect(trader)
.stake(parseEther("10"), trader.address, poorMan.address)
).to.be.not.reverted;
// Delegate to someone else without adding to the addValidator
await veToken.connect(trader).delegate(randomAddr);
// Assert poorMan as a validator
expect(await agentNft.isValidator(agent.virtualId , poorMan.address)).to.be.eq(true);
// Assert RandomAddress as not a validator
expect(await agentNft.isValidator(agent.virtualId , randomAddr.address)).to.be.eq(false);
});
});
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 access control bug in Virtuals Protocol. Code4rena made it public on 4 August 2025. Found in the 2025-04-virtuals-protocol audit contest (finding M-14).
About Access control
A user can do something their role should not allow: reach an admin function, act on a feature they have not paid for, or skip a permission check. IDOR is the special case where the object belongs to someone else.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
What is Access control?
A user can do something their role should not allow: reach an admin function, act on a feature they have not paid for, or skip a permission check. IDOR is the special case where the object belongs to someone else.