REVERT opcode executed. Message: SafeMath: subtraction overflow - blockchain

When I trigger buyMembership function from shasta.tronscan.io I am getting this error.
library SafeMath was working fine lately. But I do not know why it is giving me this error.
Please help me sort this thing I have already wasted a complete day on this.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
This is ITRC20 interface
interface ITRC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
SafeMath library I used.
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
This is my contract. buyMembership function with correct params generates this error of
REVERT opcode executed. Message: SafeMath: subtraction overflow
contract TEST101 {
ITRC20 USDT;
address payable public owner;
address payable public ma;
address payable public fw;
struct User {
uint256 commission_balance;
uint256 member_id;
uint40 membership_time;
uint256 order_history;
}
struct History {
uint256 order_amount;
uint40 order_time;
}
struct Admin {
uint256 active;
}
mapping(uint256 => User) public users;
mapping(address => Admin) public admins;
mapping(uint256 => mapping(uint256 => History)) public histories;
event BuymemberShip(address user_wallet, uint256 member_id, uint256 amount, uint40 time);
event BuyProduct(address user_wallet, uint256 member_id, uint256 amount, uint40 time);
event Withdraw(address user_wallet, uint256 member_id, uint256 amount, uint40 time);
event UpdateBalance(address user_wallet, uint256 member_id, uint256 amount, uint40 time);
constructor(address payable _ma, ITRC20 _usdt, address payable _fw) {
ma = _ma;
owner = payable(msg.sender);
USDT = _usdt;
fw = _fw;
}
function buyMembership(uint256 _mid, uint256 _amount, uint256 _charges) external {
USDT.transferFrom(msg.sender, address(this), _amount);
users[_mid].membership_time = uint40(block.timestamp);
users[_mid].order_history = 0;
users[_mid].member_id = _mid;
USDT.transfer(fw, _charges);
emit BuymemberShip(msg.sender, _mid, _amount, uint40(block.timestamp));
}
function purchase(uint256 _mid, uint256 _amount) external {
USDT.transferFrom(msg.sender, address(this), _amount);
users[_mid].order_history += 1;
histories[_mid][users[_mid].order_history].order_amount = _amount;
histories[_mid][users[_mid].order_history].order_time = uint40(block.timestamp);
emit BuyProduct(msg.sender, _mid, _amount, uint40(block.timestamp));
}
function withdraw(address addr, uint256 _mid, uint256 _amount) external {
if (admins[msg.sender].active == 1 || msg.sender == ma) {
if (users[_mid].commission_balance >= _amount) {
users[_mid].commission_balance -= _amount;
USDT.transfer(msg.sender, _amount);
emit Withdraw(msg.sender, _mid, _amount, uint40(block.timestamp));
} else {
revert("not enough balance");
}
} else {
revert("permission denied");
}
}
}

Related

ParserError: Function, variable, struct or modifier declaration expected in Solidity

it keeps bringing this error ParserError: Function, variable, struct or modifier declaration expected on this line of code
public address owner; here is the full code
pragma solidity ^0.4.24;
contract BasicToken is owned {
uint public totalSupply;
string public name;
string public symbol;
uint public decimals = 18;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer(address indexed _from, address indexed _to, uint tokens);
event Approval(address indexed _tokenOwner, address indexed _spender, uint tokens);
event Burn(address indexed _from, uint256 _value);
constructor (string tokenName, string tokenSymbol, uint initialSupply) public {
totalSupply = initialSupply*10**uint256(decimals);
balanceOf[msg.sender]= totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from,address _to,uint256 _value ) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool success){
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success){
require(_value <= allowance[_from][msg.sender]);
allowance [_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns(bool success){
allowance[msg.sender][_spender] = _value;
emit Approval (msg.sender, _spender, _value);
return true;
}
function mintToken (address _target, uint256 _mintedAmount) onlyOwner {
balanceOf[_target] += _mintedAmount;
totalSupply += _mintedAmount;
emit Transfer(0, owner, _mintedAmount);
emit Transfer(owner, _target, _mintedAmount);
}
function burn(uint256 _value) onlyOwner returns(bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
emit Burn(msg.sender, _value);
return true;
}
}
contract owned {
public address owner;
constructor {
owner = msg.sender;
}
modifier onlyOwner{
require(msg.sender == owner);
_;
}
function transferOwnership (address newOwner) onlyOwner{
owner = newOwner;
}
}
there are some errors:
in own contract
1- Instead of public address owner
address public owner;
2- instead of constructor
constructor()
3- add visibility to transferOwnership. I added public
function transferOwnership(address newOwner) public onlyOwner{
4- Since you are inhering from owner contract place it on top. Otherwise you get "definition of base has to precede definition of derived contract" error.
in BasicToken contract
1- add visibility like public to the last few functions
2- in constructor signature remove public (since I compiled at version 0.8.7 but in your version it was necessary I guess) and add memory for string args
constructor (string memory tokenName, string memory tokenSymbol, uint initialSupply) {
3-
function _transfer(address _from,address _to,uint256 _value ) internal {
// not 0x0 because _to is address type
require(_to != 0x0000000000000000000000000000000000000000);
// or require(_to != address(0);
4- in mintToken
function mintToken (address _target, uint256 _mintedAmount) public onlyOwner {
balanceOf[_target] += _mintedAmount;
totalSupply += _mintedAmount;
// not 0, address(0)
emit Transfer(address(0), owner, _mintedAmount);
emit Transfer(owner, _target, _mintedAmount);
}
I compiled it at version pragma solidity ^0.8.7;

SwapExactTokensForTokensSupportingFeeOnTransferTokens gives error in smart contract

I would like to call SwapExactTokensForTokensSupportingFeeOnTransferTokens in my contract to swap tokens with a transfer fee, however, the transaction reverts with an error. I have enough balance in the contract when calling the function.
The transaction that failed, which I called from the contract: https://dashboard.tenderly.co/tx/bsc/0xe44eba37baba3705376163d94f5d1051ac7ae9b2017ab9e403bad22f6a4c0577
When I perform the following (similar) transaction on the exchange, it works as expected: https://dashboard.tenderly.co/tx/bsc/0x5ab848527c12e76c6316859bab14a454a329aeade8046418f5dd542bcf1bd691/
With the debugging mode of Tenderly, I determined that the two transactions are similar except for the fact that the transaction in the contract had one additional approval call. Also when I submitted the transaction, a gas estimation error popped up in Remix.
Below is the code snippet of my contract. The other function, SwapExactTokensForTokens, is working in the contract call as expected. In the contract, SwapFeeOnExternal and SwapExternal are called to interact with the PancakeSwap Router.
pragma solidity >=0.8.14;
interface IERC20 {
function totalSupply() external view returns (uint);
function balanceOf(address account) external view returns (uint);
function transfer(address recipient, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint amount) external returns (bool);
function transferFrom(address sender, address recipient, uint amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
interface IUniswapV2Router {
function getAmountsOut(uint256 amountIn, address[] memory path) external view returns (uint256[] memory amounts);
function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts);
}
contract SwapTradeExecution {
address owner;
constructor(){
// Set the owner to the account that deployes the contract
owner = msg.sender;
}
modifier onlyOwner() {
// Only owner can execute some functions
require(msg.sender == owner, "Only the owner is allowed to execute");
_;
}
function swapFeeOn(address router, address _tokenIn, address _tokenOut, uint256 _amount) internal {
// Single swap function for uniswap v2 swap.
IERC20(_tokenIn).approve(router, _amount);
address[] memory path;
path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
uint deadline = block.timestamp + 300;
IUniswapV2Router(router).swapExactTokensForTokensSupportingFeeOnTransferTokens(_amount, 0, path, address(this), deadline);
}
function swapExternal(address router, address _tokenIn, address _tokenOut, uint256 _amount, uint256 minAmount) external onlyOwner {
// Single swap function for uniswap v2 swap.
IERC20(_tokenIn).approve(router, _amount);
address[] memory path;
path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
uint deadline = block.timestamp + 300;
IUniswapV2Router(router).swapExactTokensForTokens(_amount, minAmount, path, address(this), deadline);
}
function swapFeeOnExternal(address router, address _tokenIn, address _tokenOut, uint256 _amount,uint256 minAmount) external onlyOwner {
// Single swap function for uniswap v2 swap.
IERC20(_tokenIn).approve(router, _amount);
address[] memory path;
path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
uint deadline = block.timestamp + 300;
IUniswapV2Router(router).swapExactTokensForTokensSupportingFeeOnTransferTokens(_amount, minAmount, path, address(this), deadline);
}
function tokenBalance(address token) public view returns (uint256) {
IERC20 token = IERC20(token);
return token.balanceOf(address(this));
}
function withdrawFunds(address token) external onlyOwner {
IERC20 token = IERC20(token);
uint balance = token.balanceOf(address(this));
require(balance > 0, "No avaliable fund to withdraw");
token.transfer(msg.sender, balance);
}
}

Solidity - Execution reverted (how to debug in Remix)

I am creating blockchain lottery smart contract that is using my own ERC20 token.
The idea is simple. Players buy any amount of tickets they want. Each ticket that is bought is stored as a pair of address and ticketId.
When the manager calls the pickWinner() function, a random number is generated and one ticket is chosen as the winning one.
All is working good until I call the pickWinner() function. After I try to call it I get the following error:
Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending?
execution reverted { "originalError": { "code": 3, "data": "0x4e487b710000000000000000000000000000000000000000000000000000000000000032", "message": "execution reverted" } }
The problem is, it's not telling me where the problem is. I don't know how to proceed further without trying removing line by line and see where's the problem.
Here's the code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.15;
import "#openzeppelin/contracts/token/ERC20/ERC20.sol";
contract Lottery {
event TicketsBought(address playerAddress, uint256 quantity, uint256 ticketPrice);
event WinnerPicked(ticket ticket, uint256 amount);
struct ticket {
address walletAddress;
uint256 ticketId;
}
uint256 currentTicketId = 0;
address gamblinoAddress = 0xE9FEA6A6A1a8BB99E0C888c93A06D22f804A5fFA;
uint public ticketPrice = 50 * 10**18;
address public manager;
ticket public winner;
ticket[] public tickets;
uint256 public balance;
constructor() {
manager = msg.sender;
balance = 0;
}
function getPlayerAddresses() private view returns (address[] memory) {
address[] memory addresses;
for(uint i = 0; i < tickets.length; i++) {
addresses[i] = tickets[i].walletAddress;
}
return addresses;
}
function buyTickets(uint256 quantity) public payable {
uint256 amount = ticketPrice * quantity;
GamblinoToken gamblinoToken = GamblinoToken(gamblinoAddress);
uint256 allowance = gamblinoToken.allowance(msg.sender, address(this));
uint256 playerBalance = gamblinoToken.balanceOf(msg.sender);
require(playerBalance >= amount, 'Check token balance');
require(allowance >= amount, 'Check the token allowance');
balance = balance + amount;
for (uint i = 0; i < quantity; i++) {
ticket memory t = ticket(msg.sender, currentTicketId);
tickets.push(t);
currentTicketId++;
}
gamblinoToken.transferFrom(msg.sender, address(this), amount);
emit TicketsBought(msg.sender, quantity, ticketPrice);
}
function random() public view returns (uint) {
return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, getPlayerAddresses())));
}
function pickWinner() public {
uint index = random() % tickets.length;
uint256 amount = balance;
GamblinoToken gamblinoToken = GamblinoToken(gamblinoAddress);
// the entitre balance of this contract to the winner.
gamblinoToken.transfer(tickets[index].walletAddress, balance);
// set balance to 0
balance = 0;
// set winner
winner = tickets[index];
// reset ticket id
currentTicketId = 0;
// clear players and start over.
delete tickets;
emit WinnerPicked(winner, amount);
}
function getTickets() public view returns (ticket[] memory) {
return tickets;
}
// restrict to only the manager (the contract creator)
modifier restricted() {
require(msg.sender == manager);
_;
}
}
interface ERC20Interface {
function totalSupply() external view returns (uint256);
function balanceOf(address tokenOwner) external view returns (uint balance);
function allowance(address tokenOwner, address spender) external view returns (uint remaining);
function transfer(address to, uint tokens) external returns (bool success);
function approve(address spender, uint tokens) external returns (bool success);
function transferFrom(address from, address to, uint tokens) external returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract GamblinoToken is ERC20Interface {
function totalSupply() public override view returns (uint256) {}
function balanceOf(address tokenOwner) public override view returns (uint) {}
function transfer(address receiver, uint numTokens) public override returns (bool) {}
function approve(address delegate, uint numTokens) public override returns (bool) {}
function allowance(address owner, address delegate) public override view returns (uint) {}
function transferFrom(address owner, address buyer, uint numTokens) public override returns (bool) {}
}

Gas estimation error - execution reverted { "originalError": { "code": 3, "data": "0xfb7f5079", "message": "execution reverted" } }

I have a contract deployed on the rinkeby testnet. It is basically a clone of uniswapV2.
Whenever I try to call the router contract's addLiquidity/ removeLiquidity/ swapTokens functions this error pops up. All other functions in other contracts are working just fine! Only functions of the router contract are giving this error!
I am unable to rectify this problem at the moment kindly look into this and suggest some ways to make it work! Here is the code for reference:
//SPDX-License-Identifier: MIT
pragma solidity >=0.8.10;
import "../interfaces/IKswapPair.sol";
import "../interfaces/IKswapFactory.sol";
import "./KswapLibrary.sol";
contract KswapRouter {
error ExcessiveInputAmount();
error InsufficientAAmount();
error InsufficientBAmount();
error InsufficientOutputAmount();
error SafeTransferFailed();
IKswapFactory factory;
constructor(address factoryAddress) {
factory = IKswapFactory(factoryAddress);
}
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to
)
public
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
)
{
if (factory.pairs(tokenA, tokenB) == address(0)) {
factory.createPair(tokenA, tokenB);
}
(amountA, amountB) = _calculateLiquidity(
tokenA,
tokenB,
amountADesired,
amountBDesired,
amountAMin,
amountBMin
);
address pairAddress = KswapLibrary.pairFor(
address(factory),
tokenA,
tokenB
);
_safeTransferFrom(tokenA, msg.sender, pairAddress, amountA);
_safeTransferFrom(tokenB, msg.sender, pairAddress, amountB);
liquidity = IKswapPair(pairAddress).mint(to);
}
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to
) public returns (uint256 amountA, uint256 amountB) {
address pair = KswapLibrary.pairFor(
address(factory),
tokenA,
tokenB
);
IKswapPair(pair).transferFrom(msg.sender, pair, liquidity);
(amountA, amountB) = IKswapPair(pair).burn(to);
if (amountA < amountAMin) revert InsufficientAAmount();
if (amountB < amountBMin) revert InsufficientBAmount();
}
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to
) public returns (uint256[] memory amounts) {
amounts = KswapLibrary.getAmountsOut(
address(factory),
amountIn,
path
);
if (amounts[amounts.length - 1] < amountOutMin)
revert InsufficientOutputAmount();
_safeTransferFrom(
path[0],
msg.sender,
KswapLibrary.pairFor(address(factory), path[0], path[1]),
amounts[0]
);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to
) public returns (uint256[] memory amounts) {
amounts = KswapLibrary.getAmountsIn(
address(factory),
amountOut,
path
);
if (amounts[amounts.length - 1] > amountInMax)
revert ExcessiveInputAmount();
_safeTransferFrom(
path[0],
msg.sender,
KswapLibrary.pairFor(address(factory), path[0], path[1]),
amounts[0]
);
_swap(amounts, path, to);
}
//
//
//
// PRIVATE
//
//
//
function _swap(
uint256[] memory amounts,
address[] memory path,
address to_
) internal {
for (uint256 i = 0; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = KswapLibrary.sortTokens(input, output);
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) = input == token0
? (uint256(0), amountOut)
: (amountOut, uint256(0));
address to = i < path.length - 2
? KswapLibrary.pairFor(address(factory), output, path[i + 2])
: to_;
IKswapPair(
KswapLibrary.pairFor(address(factory), input, output)
).swap(amount0Out, amount1Out, to);
}
}
function _calculateLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin
) internal returns (uint256 amountA, uint256 amountB) {
(uint256 reserveA, uint256 reserveB) = KswapLibrary.getReserves(
address(factory),
tokenA,
tokenB
);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint256 amountBOptimal = KswapLibrary.quote(
amountADesired,
reserveA,
reserveB
); //calculates output amount
if (amountBOptimal <= amountBDesired) {
if (amountBOptimal <= amountBMin) revert InsufficientBAmount();
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint256 amountAOptimal = KswapLibrary.quote(
amountBDesired,
reserveB,
reserveA
);
assert(amountAOptimal <= amountADesired);
if (amountAOptimal <= amountAMin) revert InsufficientAAmount();
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function _safeTransferFrom(
address token,
address from,
address to,
uint256 value
) private {
(bool success, bytes memory data) = token.call(
abi.encodeWithSignature(
"transferFrom(address,address,uint256)",
from,
to,
value
)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool))))
revert SafeTransferFailed();
}
//
//
// LIBRARY FUNCTIONS
//
//
function quote(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) public pure returns (uint256 amountOut) {
return KswapLibrary.quote(amountIn, reserveIn, reserveOut);
}
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) public pure returns (uint256 amountOut) {
return KswapLibrary.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) public pure returns (uint256 amountIn) {
return KswapLibrary.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint256 amountIn, address[] memory path)
public
returns (uint256[] memory amounts)
{
return KswapLibrary.getAmountsOut(address(factory), amountIn, path);
}
function getAmountsIn(uint256 amountOut, address[] memory path)
public
returns (uint256[] memory amounts)
{
return KswapLibrary.getAmountsIn(address(factory), amountOut, path);
}
}

Token information does not show when compiled

I am using the code below to create a smart contract, which receives BNB and sends the token created by the contract back.
I'm using Remix, and selecting the DEX contract to compile.
However, when I do this, the Token information does not appear on BscScan.
Example: https://testnet.bscscan.com/token/0xb570E6Fff85CBE695c9394bDa7d55fb38a009A28
And I can't add it to my wallet either, it says that the token code doesn't recognize it.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract ERC20Basic is IERC20{
string public constant name = "ByeSeel";
string public constant symbol = "BYS";
uint8 public constant decimals = 18;
//event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
//event Transfer(address indexed from, address indexed to, uint tokens);
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
uint256 totalSupply_ = 10000000 * 10 ** 18;
using SafeMath for uint256;
constructor() {
balances[msg.sender] = totalSupply_;
}
function totalSupply() public override view returns (uint256) {
return totalSupply_;
}
function balanceOf(address tokenOwner) public override view returns (uint256) {
return balances[tokenOwner];
}
function transfer(address receiver, uint256 numTokens) public override returns (bool) {
require(numTokens <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(numTokens);
balances[receiver] = balances[receiver].add(numTokens);
emit Transfer(msg.sender, receiver, numTokens);
return true;
}
function approve(address delegate, uint256 numTokens) public override returns (bool) {
allowed[msg.sender][delegate] = numTokens;
emit Approval(msg.sender, delegate, numTokens);
return true;
}
function allowance(address owner, address delegate) public override view returns (uint) {
return allowed[owner][delegate];
}
function transferFrom(address owner, address buyer, uint256 numTokens) public override returns (bool) {
require(numTokens <= balances[owner]);
require(numTokens <= allowed[owner][msg.sender]);
balances[owner] = balances[owner].sub(numTokens);
allowed[owner][msg.sender] = allowed[owner][msg.sender].sub(numTokens);
balances[buyer] = balances[buyer].add(numTokens);
emit Transfer(owner, buyer, numTokens);
return true;
}
event Received(address, uint);
receive() external payable {
emit Received(msg.sender, msg.value);
}
}
library SafeMath {
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
} }
contract DEX {
event Bought(uint256 amount);
event Sold(uint256 amount);
IERC20 public token;
constructor() {
token = new ERC20Basic();
}
function buy() payable public {
uint256 amountTobuy = msg.value;
uint256 dexBalance = token.balanceOf(address(this));
require(amountTobuy > 0, "You need to send some Ether");
require(amountTobuy <= dexBalance, "Not enough tokens in the reserve");
token.transfer(msg.sender, amountTobuy);
emit Bought(amountTobuy);
}
function sell(uint256 amount) public {
require(amount > 0, "You need to sell at least some tokens");
uint256 allowance = token.allowance(msg.sender, address(this));
require(allowance >= amount, "Check the token allowance");
token.transferFrom(msg.sender, address(this), amount);
payable(msg.sender).transfer(amount);
emit Sold(amount);
}
receive() external payable {
buy();
}
}
The problem is that the DEX contract was not extending to the ERC20Basic contract
So I had to do:
contract DEX is ERC20Basic
This solved it, but I still have problems with the purchase and sale contract.