DEV Community

ChristianErdtmann
ChristianErdtmann

Posted on

Interact with existing Smart Contract

Hey i want to automate my staking on The Sandbox. For that i need in the first step to interact with the mSand-Matic Pool Contract. It is this one: https://polygonscan.com/address/0x4ab071c42c28c4858c4bac171f06b13586b20f30#code

I have written a little programm in a github repo to show what i have done see here: https://github.com/ChristianErdtmann/mSandMaticStakingAutomation

Or here the code example from the contract-interact.js

Web3 = require('web3')
const fs = require('fs');

const web3 = new Web3("https://polygon-rpc.com")
const contractAddress = "0x4AB071C42C28c4858C4BAc171F06b13586b20F30"
const contractJson = fs.readFileSync('./abi.json')
const abi = JSON.parse(contractJson)
const mSandMaticContract = new web3.eth.Contract(abi, contractAddress)
mSandMaticContract.balanceOf('0x7e5475290Df8E66234A541483453B5503551C780')
Enter fullscreen mode Exit fullscreen mode

The abi i have taken from the contract link on the top. But it seems there is a problem.

I tried for testing to read someting from the contract. For that i used the function balanceOf(address), how you can see in the code.

But i get alltimes the error: TypeError: mSandMaticContract.balanceOf is not a function

Top comments (1)

Collapse
 
christianerdtmann profile image
ChristianErdtmann • Edited

I found the solution

  1. web3 needs .methots to get acces to the balanceOf() function
  2. if we want only to read so we need to add .call()
  3. we need to add await before the function is called this needs to be in a asynchonus function

So the final working code is:

Web3 = require('web3')
const fs = require('fs');

const web3 = new Web3("https://polygon-rpc.com")
const contractAddress = "0x4AB071C42C28c4858C4BAc171F06b13586b20F30"
const contractJson = fs.readFileSync('./abi.json')
const abi = JSON.parse(contractJson)
const mSandMaticContract = new web3.eth.Contract(abi, contractAddress)

asyncCall()

async function asyncCall() {
    console.log(await mSandMaticContract.methods.balanceOf('0x7e5475290Df8E66234A541483453B5503551C780').call())
}
Enter fullscreen mode Exit fullscreen mode

If you additional want to do a write transaction you need the following:

encoded = mSandMaticContract.methods.getReward().encodeABI()
var block = await web3.eth.getBlock("latest");
var gasLimit = Math.round(block.gasLimit / block.transactions.length);

var tx = {
    gas: gasLimit,
    to: publicKey,
    data: encoded
}

web3.eth.accounts.signTransaction(tx, privateKey).then(signed => {
    web3.eth.sendSignedTransaction(signed.rawTransaction).on('receipt', console.log)
})
Enter fullscreen mode Exit fullscreen mode