Search code examples
javascriptreactjssolidityweb3js

Call specific solidity function from deployed smart contract within react through javascript (web3.js)


I try to call the transferMargin() function from the Synthetix Contract on Optimism Kovan through react/javascript(web3.js) and Metamask. I want to use on Button click the transferMargin function from the deployed smart contract but its not working iam not sure what is wrong with my code i have copied the full ABI from the contract and the address

This is my code:

import react, { useState } from "react";
import  { Component } from 'react';
import Web3 from 'web3'


export default function KwentaOptimism()
{

let provider = window.ethereum;
let selectedAccount;


if (typeof provider !== 'undefined') {  
    provider
    .request({method: 'eth_requestAccounts' })
    .then((accounts) => {
    selectedAccount = accounts[0];
    console.log(`Selected account is ${selectedAccount}`);
    })
                                                            }
                                                            
                                                            
const web3 = new Web3(provider);


async function loadContract(){

    let address = "0x1e28378F64bC04E872a9D01Eb261926717346F98";
    let chainlinkFutureContractABI = [{"constant":false,"inputs":[{"internalType":"int256","name":"marginDelta","type":"int256"}],"name":"transferMargin","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}];
    

    var Contract = require('web3-eth-contract');
    var chainlinkFutureContract =  new Contract(chainlinkFutureContractABI, address);

    return await chainlinkFutureContract;

}


async function openLong(){
    let linkContract = await loadContract();
    linkContract.methods.transferMargin("100000000000000000000").send({from: '0xce05626e35c053995d4988b75af85e2eb7251b3c'});        



}




return(


<div>
    <br/>
    <button onclick = {openLong()}>Chainlink Long</button>
    
    
    
</div>

)


}

The console error is gone but the onclick function openLong() is called automtically by react when i start the server or refresh the page. But the function should only be called when i click the button "Chainlink Long". Why this strange behavior?


Solution

  • This is because you are trying to call the smart contract function using .call() when you should be using .send()

    So you should try using

    linkContract.methods.transferMargin("100000000000000000000").send();
        
    

    Here you can read the documentation for each use case:

    https://web3js.readthedocs.io/en/v1.2.11/web3-eth-contract.html#methods-mymethod-call

    https://web3js.readthedocs.io/en/v1.2.11/web3-eth-contract.html#methods-mymethod-send