Search code examples
javascriptweb3jsmetamask

How to connect Dapp to Metamask and interact with smart contract deployed on Ropsten via Remix


I deployed a smart contract via remix to the ropsten testnet and now I want to interact with it via website(dapp). I am creating a auction dapp. The user has to input the amount of ETH he want's to bid for the article. After the value is submitted via button click I want metamask to pop up and handle the transaction.

I got the js code for connecting to metamask from https://docs.metamask.io/guide/getting-started.html#basic-considerations

if (typeof window.ethereum !== 'undefined') {
    console.log('MetaMask is installed!');
 }
else{
      console.log('MetaMask not installed!');
}

const ethereumButton = document.querySelector('.enableEthereumButton');
const showAccount = document.querySelector('.showAccount');

ethereumButton.addEventListener('click', () => {
  getAccount();
});

async function getAccount() {
  const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
  const account = accounts[0];
  showAccount.innerHTML = account;
}

And it's working fine Metamask is popping up, but the part where I am stuck is how to connect the dapp to the deployed ropsten contract(deployed it via remix and it's visible on ropsten etherscan).

I tried to connect it with this js script

<script>
      // Initialize Web3
      if (typeof web3 !== 'undefined') {
        web3 = new Web3(web3.currentProvider);
      } else {
        web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));
      }

      // Set Account
      web3.eth.defaultAccount = web3.eth.accounts[0];

      // Set Contract Abi
      var contractAbi = []; // Add Your Contract ABI here!!!

      // Set Contract Address
      var contractAddress = ''; // ?????

      // Set the Contract
      var contract = web3.eth.contract(contractAbi).at(contractAddress);
      ...

    </script>

But I don't know how to connect it to the contract deployed on ropsten.

After I have done some reading on the internet I created an infura node to connect to the contract, but I got stuck again. Do I have to connect to infura node when I am only using metamask to interact with the dapp.


Solution

  • Check out this question on how to connect your Web3 with Metamask.

    Once you are successfully connected with Metamask. You will need to put contractABI in

    // Set Contract Abi
       var contractAbi = []; // Add Your Contract ABI here!!!
    

    and contractAddress in

    // Set Contract Address
       var contractAddress = ''; // ?????
    

    Then you can initialize the contract object by providing contractABI and contractAddress in

    // Set the Contract
       var contract = web3.eth.contract(contractAbi).at(contractAddress);
    

    This contract object will then allow you to interact with your deployed contracts..