Web3js

將交易發送到智能合約時出錯

  • May 1, 2020

我有這個問題,我正在做一個關於如何通過 web3 與區塊鏈互動的教程,我從區塊鏈得到一些響應,但問題是當我嘗試發送交易或嘗試與智能合約互動時。當我點擊發送按鈕時出現錯誤:未擷取的 ReferenceError:myContract 未定義,但是,在此之前程式碼執行良好,顯示數據並且一切看起來都很好,但是當我點擊錯誤並且函式沒有不行。

我正在處理 localhost、remix 和 metamask。未部署 ganache/rpc/geth。只想從 HTML 文件連接到區塊鏈。

這是我的完整程式碼:

<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Testing web3 connection</title>

<link rel="stylesheet" type="text/css" href="main.css">

<script src="./node_modules/web3/dist/web3.min.js"></script>
<script src="abi.js"></script>
</head>
<body>
<div class="container">
   <h1>Web 3 test</h1>
       Welcome to our token creator site 
       <p></p>
       <p></p>
       Your address is:<strong><div id="mywallet"></div></strong>
       <p></p>
       <p></p>
       Contract Owner: <br><strong><div id="owner"></div></strong>  
       <p></p>
       Total Supply: <br><strong><div id="total"></div></strong>  
       <p></p>
       <input type="text" id="name">
       <p></p>
       <input type="text" id="amount">
       <p></p>
       <button id="sending">Send</button>
   <strong><div id="txStatus"></div></strong> 

</div>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
 <script>
 window.addEventListener('load', async () => {
       if (window.ethereum) {
               window.web3 = new Web3(ethereum);
               try {
                   await ethereum.enable();
                   if (web3) {

                   switch (web3.version.network) {
                       case '1':
                           console.log('This is mainnet');
                           break;
                       case '2':
                           console.log('This is the deprecated Morden test network.');
                           break;
                       case '3':
                           console.log('This is the ropsten test network.');
                           break;
                       case '4':
                           console.log('This is the Rinkeby test network.');
                           break;
                       case '42':
                           console.log('This is the Kovan test network.');
                           break;
                       default:
                           console.log('This is an unknown network.');
                   }


                   var desiredNetwork = 4;
                   if (web3.version.network != desiredNetwork){ 
                      // alert('Please switch to main network.');
                   }  

                   web3.eth.getAccounts(function(err, accounts){
                   if (err != null) {
                       console.log(err)
                   } else if (accounts.length === 0){ 
                       console.log('MetaMask is locked');
                       alert('Please connect to MetaMask');
                   } else {
                       console.log('MetaMask is unlocked')
                   }
                   }); 
                   //This data is showed in the test file on localhost, so I got response from blockchain    
                   account = await web3.eth.getAccounts();

                   $('#mywallet').html(account); 

                   var myContract = new web3.eth.Contract(myABI, '0xf65eFbCA9C36299AD50CF177bdE261973661174D');
                   var owner = await myContract.methods.owner().call();
                   $('#owner').html(owner); 
     //End data response                                   
                   }      

               } catch (error) {

               }
           }

           // Legacy dapp browsers...
           else if (window.web3) {
               window.web3 = new Web3(web3.currentProvider);

           }
           // Non-dapp browsers...
           else {
               console.log('Non-Ethereum browser detected. You should consider trying MetaMask or Trust Wallet!');
           }
  });


                    $("#sending").click(function() {
                       //when I clicked here an error appears => Uncaught ReferenceError: myContract is not defined
                       var id = $('#name').val();
                       var amount = $('#amount').val();
                       myContract.methods.addName(id , amount, account).send();
                    }); 

</script> 

我已經測試了一個星期,我看不到我的錯誤。

通過 web3 + java 執行此操作的正確方法:

   //Check if the object is definied
   if (typeof web3 !== 'undefined') {
       web3 = new Web3(web3.currentProvider);
   } else {
       // set the provider you want from Web3.providers
       web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
   }

   //Init my constant
   const contractAddress = 'MY CONTRACT ADDRESS HERE';
   // I created my contract instance
   const myContract = new web3.eth.Contract(myABI, 'MY CONTRACT ADDRESS');

   //As I'm working with promises, I need an async function
   //to get the blockchain data and to interact with blockchain

   async function getDetais() {
       //maybe there is a better option that getaccount, this works for me
       const account = await web3.eth.getAccounts();
       $('#mywallet').html(account);

       const balance = await web3.eth.getBalance(account[0]);
       const balanceinETH = balance/1000000000000000000;
       $('#mybalance').html(balanceinETH +' ETH'); 

       const ContractOwner = await myContract.methods.owner().call();
       $('#owner').html(ContractOwner); 

       const BaseURL =  await myContract.methods.url().call();
       $('#BaseURL').html(BaseURL);

       const totalSupply =  await myContract.methods.totalSupply().call();
       $('#total').html(totalSupply);

       $("#sending").click(function() {
        //I need to set up the value of gas inside the send function. See 
        //web3 documentation to know more about it   
        myContract.methods.createToken($("#name").val(), $("#fdate").val()).send({from: account[0], to: contractAddress, gas: 2100000});
   });

   }
   //I call my function
   getDetais(); 

使用此程式碼,您可以非常輕鬆地與區塊鏈智能合約進行互動。

您必須將發送功能轉移到包含 myContract 實例的主文件(您在其中部署/分配了包含您的 abis 的契約)。您可以通過將 id 分配給前端的標籤來做到這一點。您最好嘗試 REACTJS,它將是有用。

引用自:https://ethereum.stackexchange.com/questions/82954