Web3js

如何使用元遮罩和 web3.js 向智能合約函式發送值?

  • March 17, 2022

我試圖按照教程https://livecodestream.dev/post/interacting-with-smart-contracts-from-web-apps/

我能夠通過呼叫功能檢索號碼,但無法通過發送功能更新號碼。我不使用infura。我使用 MetaMask,它連接到我在本地主機上的頁面。我允許使用 Meta Mask 帳戶。

我通過按鈕觸發功能

<button onclick="changeCoolNumber();">Change Cool Number</button>

我的頁面內 Javascript 如下:

<script type="text/javascript">
async function loadWeb3() {
     if (window.ethereum) {
         window.web3 = new Web3(window.ethereum);
         window.ethereum.enable();
     }
}

async function loadContract() {
   return await new window.web3.eth.Contract([
       {
           "inputs": [],
           "name": "coolNumber",
           "outputs": [
               {
                   "internalType": "uint256",
                   "name": "",
                   "type": "uint256"
               }
           ],
           "stateMutability": "view",
           "type": "function"
       },
       {
           "inputs": [
               {
                   "internalType": "uint256",
                   "name": "_coolNumber",
                   "type": "uint256"
               }
           ],
           "name": "setCoolNumber",
           "outputs": [],
           "stateMutability": "nonpayable",
           "type": "function"
       }
   ], '0x5F4a8C71AFB0c01BA741106d418E78888607Ee63');
}

async function getCurrentAccount() {
   const accounts = await window.web3.eth.getAccounts();
   return accounts[0];
}

async function printCoolNumber() {
   const num = await window.contract.methods.coolNumber().call();
   document.querySelector("output").textContent = num;
}

async function changeCoolNumber() {
   const value = parseInt(45);
   const account = await getCurrentAccount();
   console.log("accounts", account);
   const coolNumber = await window.contract.methods.setCoolNumber(value).send({ from: account });
}

async function load() {
   await loadWeb3();
   updateStatus('Web3 Ready!');
   window.contract = await loadContract(); 
   updateStatus('Contract Ready!');
   
}

load();

到目前為止,我所聽到的是,Meta Mask 應該彈出來簽署交易以通過 setCoolNumber() 更改數字。我正在使用帶有 MetaMask 擴展的 Firefox。HTTP-Server 作為本地伺服器和以下 web3.js

<script src="https://cdn.jsdelivr.net/npm/web3@1.7.0/dist/web3.min.js"></script>

我希望有人能幫我解決這個問題。提前致謝!

我有同樣的問題。添加預設帳戶對我有幫助:web3.eth.defaultAccount = web3.eth.accounts[0];

最後 MetaMask 彈出以下 send() 命令。(accountadress後面有一個冒號)

const coolNumber = await window.contract.methods.setCoolNumber(45).send({ from: '0xDe.....', });

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