1

I have a smart Contract that i need to hook up with metamask and my ui.

https://ropsten.etherscan.io/address/0xe462cbee0cd420f6c199b0194b1d8d93fb5e7720#writeContract

I have an exchange.js file

const Web3 = require('web3');
const web3 = new Web3('https://ropsten.infura.io/v3/apikey');

const abi = abiegoeshere;

const contractAddress = '0xE462CbEE0cd420f6c199B0194B1D8D93Fb5e7720';
const contract = new web3.eth.Contract(abi, contractAddress);

web3.eth.getBalance(contract.address, function (e, r) {
   $('#contractBalanceAgi').text(convertCogToAgi(r).toFixed(4))
 })

I want to get the contract balance use buy sell withdraw and reinvest function as well as get account balance and all of this should also work with metamask.

but when i try to get balance i already get an error

These are the errors I get

web3.min.js:1 Uncaught ReferenceError: require is not defined at web3.min.js:1 (anonymous) @ web3.min.js:1 exchange.js:14 Uncaught TypeError: web3.eth.Contract is not a constructor at exchange.js:14

Uncaught TypeError: this.provider.sendAsync is not a function at s.sendAsync (web3.js:1) at r.e [as getAccounts] (web3.js:1) at localhost/:72

In my index file i have following script

  <script type="text/javascript">
    window.addEventListener('load', async () => {
      // Modern dapp browsers...
      if (window.ethereum) {
        window.web3 = new Web3(ethereum);
        try {
          // Request account access if needed
          await ethereum.enable();
          // Acccounts now exposed
          web3.eth.sendTransaction({/* ... */});
        } catch (error) {
          // User denied account access...
        }
      }
      // Legacy dapp browsers...
      else if (window.web3) {
        window.web3 = new Web3(web3.currentProvider);
        // Acccounts always exposed
        web3.eth.sendTransaction({/* ... */});
      }
      // Non-dapp browsers...
      else {
        console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
      }
    });

          window.addEventListener('load', function () {

            // Checking if Web3 has been injected by the browser (Mist/MetaMask)
            if (typeof web3 !== 'undefined') {

              // Use the browser's ethereum provider
              var provider = web3.currentProvider

            } else {
              document.getElementById("metamask_error").style.display = "block";
              if ($(window).width() < 1025) {
                document.getElementById("metamask_error").innerHTML = '<div id="alert-install-metamask" class="top-alert hidden">You will need Trust Wallet to communicate with Blue Chip Fund. Click <a href="https://trustwallet.com/" style="color:#000" target="_blank">Here</a> to download.</div>';
              } else {
                document.getElementById("metamask_error").innerHTML = '<div id="alert-install-metamask" class="top-alert hidden">You will need Metamask to communicate with Blue Chip Fund. Click <a href="https://metamask.io/" style="color:#000" target="_blank">Here</a> to download.</div>';
              }
            }
            web3.eth.getAccounts(function (err, accounts) {

              //console.log(accounts);

              if (err != null)
                console.error("An error occurred: " + err);
              else if (accounts.length == 0)
              {
                document.getElementById("metamask_error").style.display = "block";
                document.getElementById("metamask_error").innerHTML = '<div class="metamask_error_inner">Please unlock Metamask and refresh the page</div>';

              }

            });

          })
        </script>

and a link to

<script src="./node_modules/web3/dist/web3.min.js"></script>

So Im not sure what of this i need and what not since i cant find any turoials on doing this?

I know that to interact with the contract i need abi and contract address but i have no ideaon how this works with meatamsk

2 Answers 2

1

Below is an example using react, ethers, and metamask to interact with an erc20 contract on ropesten. When the page loads it triggers the following transaction request in MetaMask to transfer the erc20 tokens:

Also here is an example using web3

MetaMask Transaction Request

MetaMask Transaction

React / JS code

import React, { useState, useEffect } from 'react';
import abi from "./abi.json";
import { ethers }  from 'ethers';

const MetaMaskInterface = () => {
  let contractAddress = "0xA8fb9802fD8377FF120c6544b8DdE4a6f2EAc5EE";
  let provider = null;

  useEffect(() => {
    if(typeof window.ethereum !== 'undefined') {
      // Ethereum user detected. You can now use the provider.
      provider = window['ethereum']
      console.log('metamask found');
    }
    provider.enable()
    .then(function (accounts) {
      let ethersProvider = new ethers.providers.Web3Provider(provider);
      let contract = new ethers.Contract(contractAddress, abi, ethersProvider.getSigner());
      console.log(accounts);
      let value = ethers.utils.bigNumberify(Math.pow(10,9)).mul(ethers.utils.bigNumberify(Math.pow(10,9))).mul(ethers.utils.bigNumberify(10));
      let transaction = contract.transfer("0x8abaD0176217D8cF1a9fc9E559D30BfF36269737", value);
      console.log(transaction);
    })
    .catch(function (error) {
      // Handle error. Likely the user rejected the login
      console.error(error)
    })
  });

  return (
    <p>hi</p>
  )
};

export default MetaMaskInterface;

Smart Contract (abi obtained from remix)

pragma solidity ^0.5.0;

import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.4.0/contracts/token/ERC20/ERC20.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.4.0/contracts/token/ERC20/ERC20Detailed.sol";

contract Token is ERC20, ERC20Detailed {

    constructor () public ERC20Detailed("Token", "TKN", 18) {
        _mint(msg.sender, 1000000 * (10 ** uint256(decimals())));
    }
}
2
  • no thanks, i dont want to use react or any of that. web3 js and meatamsk is more than enough for that
    – yappy twan
    Commented Jan 16, 2020 at 1:41
  • ethers is just and alternative to web3.js and you should be able to modify to fit into your existing structure. let me try with web3.js
    – Steven V
    Commented Jan 16, 2020 at 1:52
0

This is more of a javascript problem not solidity or web3. require() does not exist in the browser/client-side JavaScript. What you can do is follow the example here and then attach the bundled javascript file to your html.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.