[SOLVED] Calling functions on BSC deployed contract

hey everyone, I have a super newb question

I have a bep20 already deployed on BSC and thereā€™s a claim function for rewards, I wanna build a simple dapp to pull some information from the events and create a couple buttons to call the functions. Can I do that with Moralis?

Hi,
You can get the events synced with Moralis in a database table. You can also call contract functions if you know the ABI and the contract address.
https://docs.moralis.io/moralis-server/automatic-transaction-sync/smart-contract-events#sync-and-watch-contract-events

Thatā€™s awesome! Can you tell me which tutorials to watch for this? The ones Iā€™ve seen so far seems to be for testnet and what not. Iā€™m sorry lol Iā€™m super new to this and I appreciate any help I can get.

You could try this one: https://www.youtube.com/watch?v=rd0TTLjQLy4&ab_channel=MoralisWeb3

Thanks! I am watching it and following along right now. But I ran into an issue and Iā€™ve been trying to figure out what went wrong for the last hour.

I copied the codes from Github and I am following along in the video. I was able to log in and authenticate with metamask before it got to the step for logging in before the game shows. Now when I click on the button, nothing happens. Can you help me?

Here is the index.html code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <title>Title</title>
    <script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script src="https://unpkg.com/moralis/dist/moralis.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="jumbotron jumbotron-fluid">
    <div class="container">
        <h1 class="display-4">Welcome</h1>
    </div>
</div>
<div class="container">
        <button id="login_button">Sign in with MetaMask</button>


    <div id="game" style="display: none;">
        <input type="number" id="amount">
        <button id="heads_button">Play Heads</button>
        <button id="tails_button">Play Tails</button>
    </div>

</div>

<script type="text/javascript" src="./main.js"></script>
</body>
</html>


And here is the main.js code:

Moralis.initialize("u5Xh0IBymdEsuqDiUJSYz6GvVMngBfhLc0sL2hJo"); // Application id from moralis.io
Moralis.serverURL = "https://mk09emev5xpe.grandmoralis.com:2053/server"; //Server url from moralis.io

async function login() {
    try {
        currentUser = await Moralis.User.current();
        if(!currentUser) {
            currentUser = await Moralis.Web3.authenticate();
        }
            console.log(user);
            alert ("User logged in")
            document.getElementById("login_button").style.display = "none";
            document.getElementById("game").style.display = "block";
    } catch (error) {
        console.log(error);
    }
}

async function flip(side){
    alert(side);
}

document.getElementById("login_button").onclick = login;
document.getElementById("heads_button").onclick = function(){flip("heads")};
document.getElementById("tails_button").onclick = function(){flip("tails")};

Thank you for any help I can get!

On what button you click and nothing happens?

on ā€œSign in with Metamaskā€. I think itā€™s because Iā€™m already signed in. But for signed in users, theyā€™re supposed to see the game.

If it helps at all, the Youtube video you showed me, at the timestamp 11:59 is where Iā€™m stuck.

In case you need the video link again:

You can open the console to see if it says anything there.

Thanks. It turns out that the console.log(user) was supposed to be console.log(currentUser). I didnā€™t make any changes to it because I thought whatever I copied from the Github should be the right code to use. Next time I know! Thank you again.

yep, now I also found that this was the problem :slight_smile:

Okay so I followed through all the videos, now I am back to building the frontend dapp to call a function of my contract. I saw in the Moralis docs and also another post in this forum that @Yoomoo recommended to use the Moralis.execute code.

Hereā€™s the code I found in the docs:

const ABI = [
  {
    constant: true,
    inputs: [
      {
        internalType: "address",
        name: "owner",
        type: "address"
      },
      {
        internalType: "address",
        name: "spender",
        type: "address"
      }
    ],
    name: "allowance",
    outputs: [
      {
        internalType: "uint256",
        name: "",
        type: "uint256"
      }
    ],
    payable: false,
    stateMutability: "view",
    type: "function"
  }
];

const options = {
  contractAddress: "0xe...56",
  functionName: "allowance",
  abi: ABI,
  params: {
    owner: "0x2...45",
    spender: "0x3...49"
  },
};

const allowance = await Moralis.executeFunction(options);

Since I have the abi of the contract code in another js file from when I followed the Serverless dapp videos, I modified the codes a little. Please take a look:

const claimRewards = {
    contractAddress: "0xb48D1488266F636dB97597875dE305Bb981EC5a5",
    functionName: "claimRewards",
    abi: window.abi,
    params: {
      // I don't know what to set for params because the function is claimRewards.
     // It simply calls the contract to send the rewards to the connected wallet.


    }
  };
  
  const allowance = await Moralis.executeFunction(claimRewards);

Iā€™d appreciate any help I can get with this!

You could try to use it without params.
An example without params.

Thanks for the super fast response!
I got this error in the console:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'find')
    at module.exports (moralis.js:26832)
    at Function.<anonymous> (moralis.js:5871)
    at tryCatch (moralis.js:25921)
    at Generator.invoke [as _invoke] (moralis.js:26151)
    at Generator.next (moralis.js:25976)
    at asyncGeneratorStep (moralis.js:25368)
    at _next (moralis.js:25390)
    at moralis.js:25397
    at new Promise (<anonymous>)
    at new Wrapper (moralis.js:28450)

I am using a Moralis server on Ganache, deployed smart contract to Ganache. I changed my code to this:

async function claimBudsRewards(){
    const web3 = await Moralis.enable();
    const contract = new web3.eth.Contract(window.abi, "0xac5FB3Ac3De96470C612CeDBcE80EB42b1f5C0e7");
    
    const Rewards = {
    contractAddress: "0xac5FB3Ac3De96470C612CeDBcE80EB42b1f5C0e7",
        functionName: "claimRewards",
        abi: window.abi,
    };
    const BudsRewards = await Moralis.executeFunction(claimBudsRewards);

}

Thank you again!

You may want to use:

async function claimBudsRewards(){

      const Rewards = {
    contractAddress: "0xac5FB3Ac3De96470C612CeDBcE80EB42b1f5C0e7",
        functionName: "claimRewards",
        abi: window.abi,
    };
    const BudsRewards = await Moralis.executeFunction(Rewards);

}

I got a ā€˜missing web3 instanceā€™

so I added the line back in:

async function claimBudsRewards(){

    const web3 = await Moralis.enable(); // added this line back in

    const Rewards = {
  contractAddress: "0xac5FB3Ac3De96470C612CeDBcE80EB42b1f5C0e7",
      functionName: "claimRewards",
      abi: window.abi,
  };
  const BudsRewards = await Moralis.executeFunction(Rewards);

}

It worked! Thank you for guiding me through this. Iā€™m new to all this and coding scared the crap out of me. But thanks to you guys, Iā€™m actually enjoying this quite a bit now. Canā€™t wait to come back and show yā€™all the results!

1 Like

Hey I m also going through same problem I call the totalSupply function from my bsc contract for that I have to apply execute or run contract?
And I want to show the total supply in my console

both Moralis.executeFunction and runContractFunction should work
an example:

ERC20_ABI = [
    {
      constant: true,
      inputs: [],
      name: "totalSupply",
      outputs: [{ name: "", type: "uint256" }],
      payable: false,
      stateMutability: "view",
      type: "function",
    },
  ];

x = await Moralis.Web3API.native.runContractFunction({
    chain: "avalanche",
    address: "0xb31f66aa3c1e785363f0875a1b74e27b85fd66c7",
    function_name: "totalSupply",
    abi: ERC20_ABI,
  })

thats my main js file , i want to read totalsupply from my contract which is on mainnet bscā€¦
and print it on my console ,

login = async () => {

  Moralis.Web3.authenticate().then(function (user) {

    console.log(user.get('ethAddress'))

  })

}

async function cptsupply() {

  const web3 = await moralis.enable();

  const options = {

    chain: "bsc",

    address: "0x28e4f32fa7e842ad0a6e530bb6b4ec03b36d5078",

    function_name: "totalSupply",

    abi: window.abi,

  };

  const allowance = await Moralis.runContractFunction(options);

  console.log(allowance);

}

you can look at the above example that I gave, where you replace chain and address and it should work fine

its right , bcz i dont change the abi too

ogin = async () => {

  Moralis.Web3.authenticate().then(function (user) {

    console.log(user.get('ethAddress'))

  })

}

async function cptsupply() {

  const web3 = await moralis.enable();

  ERC20_ABI = [

{

  constant: true,

  inputs: [],

  name: "totalSupply",

  outputs: [{ name: "", type: "uint256" }],

  payable: false,

  stateMutability: "view",

  type: "function",

},

];

x = await Moralis.Web3API.native.runContractFunction({

chain: "bsc",

address: "0x28e4f32fa7e842ad0a6e530bb6b4ec03b36d5078",

function_name: "totalSupply",

abi: ERC20_ABI,

})

console.log(x);

}