Вот пересмотренная версия контракта, в которой уязвимость устранена за счет введения внутреннего отслеживания комиссий и ограничения вывода средств администратором только на сумму начисленных комиссий:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SecuredVault {
address public admin;
// Maps user addresses to their deposited balances
mapping(address => uint256) public userBalances;
// This variable *only* accounts for fees that the admin can withdraw.
// It's explicitly separated from user balances.
uint256 public totalAccruedFees;
constructor() {
// The deployer of the contract becomes the admin
admin = msg.sender;
}
/// @notice Allows users to deposit Ether into the vault.
/// A 1% fee is applied to the deposit and sent to a fee pool.
function deposit() public payable {
require(msg.value > 0, "Deposit must be greater than zero");
// Calculate 1% fee
uint256 fee = msg.value / 100; // 1% of deposited amount
uint256 amountToDeposit = msg.value - fee;
userBalances[msg.sender] += amountToDeposit; // User's principal
totalAccruedFees += fee; // Accrue the fee for the protocol
}
/// @notice Allows users to withdraw their deposited funds.
/// @param amount The amount to withdraw.
function withdraw(uint256 amount) public {
require(userBalances[msg.sender] >= amount, "Insufficient balance");
userBalances[msg.sender] -= amount;
payable(msg.sender).transfer(amount);
}
/// @notice Admin can only withdraw the total accrued fees.
/// This prevents the rug pull as admin cannot touch user principal.
/// @param amount The amount of fees the admin wishes to withdraw.
function adminWithdrawFees(uint256 amount) public {
require(msg.sender == admin, "Admin control required");
// Crucial check: Ensure admin only withdraws what's available in fees,
// as tracked separately from user principal.
require(totalAccruedFees >= amount, "Insufficient accrued fees for withdrawal");
totalAccruedFees -= amount; // Deduct the withdrawn amount from available fees
payable(admin).transfer(amount); // Transfer only the requested fee amount to admin
}
}
В этой улучшенной версии SecuredVault функция adminWithdrawFees больше не взаимодействует напрямую с балансами пользователей. Средства пользователей защищены, поскольку они хранятся отдельно от переменной totalAccruedFees. Это снижает риск злоупотребления правами администратора в отношении пользователя, устраняя основную проблему, наблюдавшуюся при атаке Zunami.
#rugpull