60 lines
No EOL
1.9 KiB
Solidity
60 lines
No EOL
1.9 KiB
Solidity
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
pragma solidity ^0.8.0;
|
|
|
|
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol";
|
|
import "@openzeppelin/contracts/access/Ownable.sol";
|
|
|
|
contract Exchange is Ownable {
|
|
IERC20 _token;
|
|
uint256 price = 10;
|
|
uint256 priceDivider = 1;
|
|
// token = MyToken's contract address
|
|
constructor(address token) {
|
|
_token = IERC20(token);
|
|
}
|
|
|
|
function setPrice(uint256 _price) public onlyOwner(){
|
|
price = _price;
|
|
}
|
|
|
|
function getPrice() public view returns (uint256) {
|
|
return price;
|
|
}
|
|
|
|
function setPriceDivider(uint256 _priceDivider) public onlyOwner() {
|
|
priceDivider = _priceDivider;
|
|
}
|
|
|
|
function getPriceDivider() public view returns (uint256) {
|
|
return priceDivider;
|
|
}
|
|
|
|
// Modifier to check token allowance
|
|
modifier checkAllowance(uint amount) {
|
|
require(_token.allowance(msg.sender, address(this)) >= amount, "Error");
|
|
_;
|
|
}
|
|
|
|
// In your case, Account A must to call this function and then deposit an amount of tokens
|
|
function sellTokens(uint _amount) public checkAllowance(_amount) {
|
|
_token.transferFrom(msg.sender, address(this), _amount);
|
|
payable(msg.sender).transfer(_amount*priceDivider/price);
|
|
}
|
|
|
|
function depositTokens(uint _amount) public checkAllowance(_amount) {
|
|
_token.transferFrom(msg.sender, address(this), _amount);
|
|
}
|
|
|
|
|
|
function buyToken() public payable {
|
|
require(msg.value >= 10000000000000000);
|
|
uint256 tokenAmount = msg.value / priceDivider * price;
|
|
require(getSmartContractBalance() >= tokenAmount);
|
|
_token.transfer(msg.sender,tokenAmount);
|
|
}
|
|
|
|
// Allow you to show how many tokens owns this smart contract
|
|
function getSmartContractBalance() public view returns(uint) {
|
|
return _token.balanceOf(address(this));
|
|
}
|
|
} |