首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将智能契约添加到元问题中?

如何将智能契约添加到元问题中?
EN

Ethereum用户
提问于 2020-01-15 23:41:17
回答 2查看 5.7K关注 0票数 1

我有一个智能契约,我需要与元询问和ui挂钩。

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

我有一个exchange.js文件

代码语言:javascript
复制
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))
 })

我想得到合同余额,使用,买入,卖出,提取和再投资的功能,以及获得帐户余额,所有这一切也应该与元要求。

但是当我试图获得平衡时,我已经犯了一个错误。

这些是我所犯的错误

web3.min.js:1 Uncaught : require未定义在web3.min.js:1 (匿名)@ web3.min.js:1 exchange.js:14 Uncaught TypeError: web3.eth.Contract不是exchange.js:14的构造函数

Uncaught : this.provider.sendAsync不是s.sendAsync (web3.js:1)在r.e as getAccounts at localhost/:72上的一个函数。

在我的索引文件中有以下脚本

代码语言: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>';

              }

            });

          })

和链接到

代码语言:javascript
复制

所以我不确定我需要什么,也不知道为什么,因为我在做这件事时找不到任何的推荐信?

我知道要与合同进行交互,我需要abi和合同地址,但我不知道这是如何与meatamsk一起工作的。

EN

回答 2

Ethereum用户

发布于 2020-01-16 01:15:39

下面是一个使用react、醚和元请求与ropesten上的erc20合同交互的示例。当页面加载时,它会在MetaMask中触发以下事务请求来传输erc20令牌:

这里还有一个使用web3 3的示例

MetaMask事务请求

React / JS代码

代码语言:javascript
复制
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 (
    hi
  )
};

export default MetaMaskInterface;

Smart合同(从混料中获得)

代码语言:javascript
复制
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())));
    }
}
票数 1
EN

Ethereum用户

发布于 2020-01-16 05:38:40

这更多的是javascript问题,而不是稳健性或web3。require()不存在于浏览器/客户端JavaScript中。您可以做的是遵循示例这里,然后将绑定的javascript文件附加到您的html中。

票数 0
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/79011

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档