Untitled

mail@pastecode.io avatarunknown
plain_text
a month ago
2.7 kB
1
Indexable
Never
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
                                                                                                                                                                                        
import "./TestToken.sol";

// Learn more about the ERC20 implementation 
// on OpenZeppelin docs: https://docs.openzeppelin.com/contracts/4.x/api/access#Ownable
import "@openzeppelin/contracts/access/Ownable.sol";

contract Vendor is Ownable {

  // Our Token Contract
  testToken myToken;

  // token price = 0.45 BNB
  //uint256 public tokenPrice = 450000000 gwei;
  
  //This is token price during test: 0.025 BNB
  uint256 public tokenPrice = 2500000 gwei;

  // Event that log buy operation
  event BuyTokens(address buyer, uint256 amountOfBNB, uint256 amountOfTokens);

  constructor(address tokenAddress) {
    myToken = testToken(tokenAddress);
  }

  /**
  * @notice Allow users to check the contract balance
  */

  function getVendorBalance() public view returns (uint256 vendorBalance) {
    vendorBalance = myToken.balanceOf(address(this));
    return vendorBalance;
  }

  /**
  * @notice Allow users to buy token for BNB
  */

  function buyTokens() public payable returns (uint256 tokenAmount) {
    //we sell at 0.45 BNB -- 0.025 BNB for testing phase
    require(msg.value >= tokenPrice, "Not enough BNB sent, check price !");

    //C'est quand je fais cette opération que ça semble foirer
    uint256 amountToBuy = msg.value * tokenPrice;

    //Si je décommente ça et je vire le calcul au dessus ça fonctionne nickel 
    //uint256 amountToBuy = 1;

    // check if the Vendor Contract has enough amount of tokens for the transaction
    uint256 vendorBalance = getVendorBalance();
    //uint256 seedBuyLimit = 15;
    require(vendorBalance >= amountToBuy, "Test contract has not enough tokens in its balance");
   // require(amountToBuy <= seedBuyLimit, "You can't buy more than 15 tokens at once");

    // Transfer token to the msg.sender
    (bool sent) = myToken.transfer(msg.sender, amountToBuy);
    require(sent, "Failed to transfer token to user");

    // emit the event
    emit BuyTokens(msg.sender, msg.value, amountToBuy);

    return amountToBuy;
  }

  /**
  * @notice Allow the owner of the contract to withdraw BNB
  */
  function withdraw() public onlyOwner {
    uint256 ownerBalance = address(this).balance;
    require(ownerBalance > 0, "Owner has not balance to withdraw");

    (bool sent,) = msg.sender.call{value: address(this).balance}("");
    require(sent, "Failed to send user balance back to the owner");
  }
}