240519-temp/MyToken.t.sol

51 lines
1.5 KiB
Solidity

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
import {Test, console} from "forge-std/Test.sol";
import {MyToken} from "../src/MyToken.sol";
contract MyTokenTest is Test {
MyToken public myToken;
address public owner;
address public user;
function setUp() public {
owner = address(0x100);
user = address(0x101);
vm.deal(owner, 100 ether);
vm.deal(user, 100 ether);
vm.startPrank(owner);
myToken = new MyToken(1000);
vm.stopPrank();
}
function test_buyAndTransferTokens() public {
vm.startPrank(user); // User operations under here
uint ethAmount = 0.01 ether;
// uint ethAmount = 0.001 ether; // This will cause myToken.buyTokens() to revert
uint userBalanceBeforeBuy = myToken.balanceOf(user);
uint totalSupplyBeforeBuy = myToken.totalSupply();
console.log("User balance before buy:", userBalanceBeforeBuy);
console.log("Total supply before buy:", totalSupplyBeforeBuy);
uint expectedBalance = userBalanceBeforeBuy + ethAmount / myToken.tokenPrice();
myToken.buyTokens{value: ethAmount}();
uint userBalanceAfterBuy = myToken.balanceOf(user);
uint totalSupplyAfterBuy = myToken.totalSupply();
console.log("User balance after buy:", userBalanceAfterBuy);
console.log("Total supply after buy:", totalSupplyAfterBuy);
assert(userBalanceAfterBuy > userBalanceBeforeBuy);
assertEq(userBalanceAfterBuy, expectedBalance);
assertEq(totalSupplyAfterBuy, totalSupplyBeforeBuy + ethAmount / myToken.tokenPrice());
myToken.transfer(owner, userBalanceAfterBuy);
vm.stopPrank();
}
}