0

Good day, I am busy with a small project trying to call a buy() function on an Ethereum Smart Contract. This Contract is found on the Ropsten Test Network here:https://ropsten.etherscan.io/address/0xA8E7798546D846Ee17a52d594c410564dF034F90

A user sends ETH to that function, and the contract returns an ERC20 Token(s) in return, depending on the rate and amount of ETH.

Here is the HTML including only the buy function call:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/Style.css"> 
   <script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js@1.0.0-beta.36/dist/web3.min.js" integrity="sha256-nWBTbvxhJgjslRyuAKJHK+XcZPlCnmIAAMixz6EefVk=" crossorigin="anonymous"></script>
    <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js' crossorigin='anonymous'></script>
  <script src ='/Web3.js'></script>
    
</head>
<body>

 
  <!--BUY-->
<input id="amountBuy" value="0">
  <button type="button" id='buybtn' onclick="buyTokens();"> Buy ECHO Tokens </button>
    <br>
    <br>
    Status:<span id="buystatus">Loading. ..</span>
    <br>
    <!--END  BUY-->
    

</body>
</html>

I have created the following web3 script to execute the function:

And here is the script I call: NOTE: I took out the ABI just here to make it more readable, but the correct ABI is in the script

async function loadWeb3() {
  if (window.ethereum) {
      window.web3 = new Web3(window.ethereum);
      ethereum.enable();
  }
 
}

async function load() {
  await loadWeb3();
  updateStatus('Ready!');
}

function updatebuyStatus(status) {
  const statusEl = document.getElementById('buystatus');
  statusEl.innerHTML = status;
  console.log(status);
}

load();
async function loadContract() {
  return await new window.web3.eth.Contract(ABI , "0xA8E7798546D846Ee17a52d594c410564dF034F90");
}

async function load() {
  await loadWeb3();
  window.contract = await loadContract();
  updateStatus('Ready!');
}



// BUY FUNCTION
async function getCurrentAccount() {
    const accounts = await window.web3.eth.getAccounts();
    return accounts[0];r
}

async function buyTokens() {
  const value = parseInt(document.getElementById("amountBuy").value);
  updatebuyStatus(`Transaction Pending ... ${value}`);
  const account = await getCurrentAccount();
  const coolNumber =  window.contract.methods.buy(value).call();
  updatebuyStatus('Transaction Successfull');
}


Can anyone help me call the buy function? A metamask popup should appear to let me confirm and/or edit and then I should just send

Thank you in advance :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.