0

I am working on a simple Truffle project that just shows "Yerevan is love". My contract code:

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

And by app.js i could create a communication between the contract and JavaScript but i don't know what is an appropriate code to show "Yerevan is love" in Node-js .My app.js code:

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" );

This app.js has not a code to show "Yerevan is love" because i don't know that. Please provide the appropriate code and a guide for a beginner man.

2

Here is a working js script example of your contract:

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) 
| improve this answer | |
  • Thank you, Is there any code to see the result of testContract.methods.fname().call().then(console.log) in browser by Node-js or another tool? Is an appropriate code for that? – Alireza Feb 12 at 15:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.