0

I am looking for a way that when you make the purchase with a fixed amount of BUSD to a smart contract address that I already have implemented. My problem is that I can't find the way to send BUSD instead of BNB, when I buy the token I get the price in BNB, that is, for example: 1 token = 1 BNB, how can this be configured when buying the token? How could we do for this? I want to send 1 BUSD instead of 1 BNB leaving the functions already established

import React, { Component } from 'react';
import smart_contract from '../abis/tris.json';
import Web3 from 'web3';
import Swal from 'sweetalert2';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';

import Navigation from './Navbar';
import MyCarousel from './Carousel';
import { Container } from 'react-bootstrap';

class Tokens extends Component {

  async componentDidMount() {
      await this.loadWeb3()
      await this.loadBlockchainData()
  }

   async loadWeb3() {
    if (window.ethereum) {
      window.web3 = new Web3(window.ethereum)
      const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
      console.log('Accounts: ', accounts)
    }
    else if (window.web3) {
      window.web3 = new Web3(window.web3.currentProvider)
    }
    else {
      window.alert('¡Uses Metamask!')
    }
  }


  async loadBlockchainData() {
    const web3 = window.web3
    const accounts = await web3.eth.getAccounts()
    this.setState({ account: accounts[0] })

    const networkId = await web3.eth.net.getId()
    console.log('networkid:', networkId)
    const networkData = smart_contract.networks[networkId]
    console.log('NetworkData:', networkData)

    if (networkData) {
      const abi = smart_contract.abi
      console.log('abi', abi)
      const address = networkData.address
      console.log('address:', address)
      const contract = new web3.eth.Contract(abi, address)
      this.setState({ contract })
    } else {
      window.alert('¡Smart Contract here no deployed!')
    }
  }

  constructor(props) {
    super(props)
    this.state = {
      account: '0x0',
      loading: true,
      contract: null,
      errorMessage: ""
    }
  }

  _balanceTokens = async () => {
    try {
      console.log("Balance tokens...")
      const _balance = await this.state.contract.methods.balanceTokens(this.state.account).call()
      Swal.fire({
        icon: 'info',
        title: 'Balance tokens users:',
        width: 800,
        padding: '3em',
        text: `${_balance} tokens`,
        backdrop: `
          rgba(15, 238, 168, 0.2)
          left top
          no-repeat
        `
      })
    } catch (err) {
      this.setState({ errorMessage: err })
    } finally {
      this.setState({ loading: false })
    }
  }

  _balanceTokensSC = async () => {
    try {
      console.log("Balance of tokens of Smart Contract...")
      const _balanceTokensSC = await this.state.contract.methods.balanceTokensSC().call()
      Swal.fire({
        icon: 'info',
        title: 'Balance tokens of Smart Contract:',
        width: 800,
        padding: '3em',
        text: `${_balanceTokensSC} tokens`,
        backdrop: `
          rgba(15, 238, 168, 0.2)
          left top
          no-repeat
        `
      })
    } catch (err) {
      this.setState({ errorMessage: err })
    } finally {
      this.setState({ loading: false })
    }
  }

  _balanceEthersSC = async () => {
    try {
      console.log("Balance ethers of Smart Contract...")
      const _balanceEthersSC = await this.state.contract.methods.balanceEthersSC().call()
      Swal.fire({
        icon: 'info',
        title: 'Balance of ethers Smart Contract:',
        width: 800,
        padding: '3em',
        text: `${_balanceEthersSC} ethers`,
        backdrop: `
          rgba(15, 238, 168, 0.2)
          left top
          no-repeat
        `
      })
    } catch (err) {
      this.setState({ errorMessage: err })
    } finally {
      this.setState({ loading: false })
    }
  }

  _buyTokens = async (_numTokens) => {
    try {
      console.log("buy tokens...")
      const web3 = window.web3
      const ethers = web3.utils.toWei(_numTokens, 'ether')
      await this.state.contract.methods.compraTokens(_numTokens).send({
        from: this.state.account,
        value: ethers
      })
      Swal.fire({
        icon: 'success',
        title: '¡buy tokens!',
        width: 800,
        padding: '3em',
        text: ` you have ${_numTokens} token/s value of ${ethers} ether/s`,
        backdrop: `
          rgba(15, 238, 168, 0.2)
          left top
          no-repeat
        `
      })
    } catch (err) {
      this.setState({ errorMessage: err })
    } finally {
      this.setState({ loading: false })
    }
  }

The contract:

    function compraTokens(uint256 _numTokens) public payable { 
        if(usuario_contract[msg.sender] == address(0)){ 
            registrar();
        }
        uint256 costo = precioTokens(_numTokens);
        require (msg.value >= costo ,"Compra menos tokens o paga con mas ethers");
        uint256 balance = balanceTokensSC();  
        require(_numTokens <= balance, "Compra un numero menor de tokens"); 
        uint256 returnValue = msg.value - costo; 
        payable(msg.sender).transfer(returnValue);
        _transfer(address(this), msg.sender, _numTokens); 
    }
5
  • Sending a token is way different than using the native coin (BNB). It's the smart contract that should handle pulling the tokens from the user, instead of the user sending the tokens directly. Is this clear? You need to code the contract to pull the tokens from the user
    – 0xSanson
    Commented Dec 12, 2022 at 13:11
  • Good morning, I understand you but in the smart contract, I have it to receive it as a unit in (ETHER) now my problem is that when I deploy it in (BNB) it only receives me (BNB), now I want it to receive (BUSD) Commented Dec 12, 2022 at 14:20
  • Can you share the code of the contract, in particular the compraTokens function?
    – 0xSanson
    Commented Dec 12, 2022 at 18:09
  • function compraTokens(uint256 _numTokens) public payable { if(usuario_contract[msg.sender] == address(0)){ registrar(); } uint256 costo = precioTokens(_numTokens); require (msg.value >= costo ,"Compra menos tokens o paga con mas ethers"); uint256 balance = balanceTokensSC(); require(_numTokens <= balance, "Compra un numero menor de tokens"); uint256 returnValue = msg.value - costo; payable(msg.sender).transfer(returnValue); _transfer(address(this), msg.sender, _numTokens); } Commented Dec 12, 2022 at 20:25
  • I just included the IERC20 interface in the smart contract for BUSD for now on tesnet Commented Dec 12, 2022 at 20:27

2 Answers 2

0

You can do it implementing a function like this:

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
contract YourContract {
    using SafeERC20 for IERC20;
    address public constant BUSD = ...; // put the address here

    // ...
    // ...

    function compraTokensWithBUSD(uint256 _numTokens) public {
        if(usuario_contract[msg.sender] == address(0)){ 
                    registrar();         
        }
        uint256 costo = precioTokens(_numTokens);

        // pull tokens from msg.sender
        IERC20(BUSD).safeTransferFrom(msg.sender, address(this), costo);

        uint256 balance = balanceTokensSC();
        require(_numTokens <= balance, "Compra un numero menor de tokens");
        _transfer(address(this), msg.sender, _numTokens);
    }
}

Remember to add also a function to pull out the tokens from the contract.

You can see that the difference is that BNB is sent using msg.value while the token by calling their contract's transferFrom. This means that you don't have to write value: ethers when calling this function (value should be 0). The user however needs to approve your contract as spender, this is done by calling the function approve(address spender, uint256 amount) of BUSD.

1
  • Comments are not for extended discussion; this conversation has been moved to chat.
    – eth
    Commented Dec 14, 2022 at 20:37
0

withdrawals in BNB

I don't understand why BNB charges when I call this method this.state.contract.methods.purchaseTokens(_numTokens).send

Not the answer you're looking for? Browse other questions tagged or ask your own question.