如何将 Dapp 连接到 Metamask 并通过 Remix 与部署在 Ropsten 上的智能合约进行交互

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

我通过 remix 将智能合约部署到 ropsten 测试网,现在我想通过网站 (dapp) 与其交互。我正在创建一个拍卖 dapp。用户必须输入他想要为该文章出价的 ETH 数量。通过单击按钮提交值后,我希望弹出元掩码并处理交易。

我从 https://docs.metamask.io/guide/getting-started.html#basic-considerations

获得了连接到 metamask 的 js 代码
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;
}

它工作正常 Metamask 正在弹出,但我卡住的部分是如何将 dapp 连接到已部署的 ropsten 合约(通过 remix 部署它并且它在 ropsten etherscan 上可见)。

我试着用这个 js 脚本连接它

<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>

但我不知道如何将它连接到部署在 ropsten 上的合约。

在网上看了一些资料后,我创建了一个 infura 节点来连接到合约,但我又卡住了。当我只使用 metamask 与 dapp 交互时,是否必须连接到 infura 节点?

查看此question,了解如何将您的 Web3 与 Metamask 连接。

成功连接 Metamask 后。您需要将 contractABI 放入

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

合同地址

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

然后你可以通过在

中提供contractABIcontractAddress来初始化contract对象
// Set the Contract
   var contract = web3.eth.contract(contractAbi).at(contractAddress);

contract 对象将允许您与部署的合约进行交互..