Web3js

在 Node-js 中訪問智能合約的價值

  • May 22, 2021

我正在做一個簡單的 Truffle 項目,它只顯示"Yerevan is love". 我的合約程式碼:

pragma solidity ^0.5.12;
contract TEST{
  bytes note="Yerevan is love";
  function fname() public view returns(string memory){
     return string(note);
  }
}

通過 app.js,我可以在契約和 JavaScript 之間創建通信,但我不知道"Yerevan is love"在 Node-js 中顯示的合適程式碼是什麼。我的 app.js 程式碼:

var Web3=require("web3");
var web3= new Web3('ws://localhost:8545');
var fs=require('fs') ;
var jsonFile="C:/Users/lenovo/node_modules/Yerevan/build/contracts/TEST.json";
var parsed=JSON.parse(fs.readFileSync(jsonFile));
var abi=parsed.abi;
var myContract= new 
   web3.eth.Contract(abi,"0xEC3B8e1607C92D5695dE5FaCdE3db76EBff7f5eA" );

這個 app.js 沒有要顯示的程式碼,"Yerevan is love"因為我不知道。請為初學者提供適當的程式碼和指南。

這是您的契約的有效 js 腳本範例:

var Web3 = require('web3')
let abi = [
   {
       "constant": true,
       "inputs": [],
       "name": "fname",
       "outputs": [
           {
               "internalType": "string",
               "name": "",
               "type": "string"
           }
       ],
       "payable": false,
       "stateMutability": "view",
       "type": "function"
   }
]

let addressOfContract = '<PUT_ADDRESS_OF_CONTRACT_HERE>'
let endPoint = '<PUT_YOUR_ENDPOINT_HERE>'

// Destinguishes browser from server side
if (typeof window !== "undefined" && typeof window.web3 !== "undefined") {
   // we are in the browser and metamask injected a provider and is running
   web3 = new Web3(window.web3.currentProvider);
} else {
   // we are in the server side and metmask is not available
   const provider = new Web3.providers.HttpProvider(
       endPoint
   );
   web3 = new Web3(provider);
}

testContract = new web3.eth.Contract(abi, addressOfContract)

testContract.methods.fname().call().then(console.log) 

您應該在嵌入問題的最後一行之後添加以下命令:

myContract.methods.fname().call().then(function(instance){console.log(instance)});

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