0

I want to connect to my smart contract in a Truffle project and get some information from it. The smart contract's name is "TEST". The follow is my app.js code that should communicate with my smart contract:

var Web3=require("web3");
var web3= new Web3('ws://localhost:8545');
   web3.eth.getAccounts().then(console.log);
let request=new XMLHttpRequest();
    request.open("GET","E:\Emrooz\build\contracts\TEST.json");
    request.send(null);
var jsonFile=JSON.parse(request.responseText);
var myContract=new 
    web3.eth.Contract(jsonFile,"0xC8129A44979263D578A8BD52d403d6537820e969",{ 
    account:"0xeB2a9E0338616e35B5e844Bd38924C79D99d7346", balance:"99.98990494"});
var acc=myContract.defaultAccount;
    console.log(acc.toString());

Here, "Emrooz" is name of file of Truffle project. But when i complie app.js with Nodejs the following error occurrs:

enter image description here

Even, i added var XMLHttpRequest=require('xmlhttprequest').XMLHttpRequest; to the code but that error occurrs again. Whats the problem? What should i do?

  • Is that me or you try to send an HTTP request to a file ? – Florian Castelain Feb 10 at 8:31
  • Client-side application – Alireza Feb 10 at 9:15
  • I don't understand. A file cannot handle a HTTP request. – Florian Castelain Feb 10 at 10:41
0

XMLHttpRequest(); is not required to connect with the smart contract and receive information from it. The purpose of the provided code in question is receiving the address that exist in new web3.eth.Contract(…). For that, we can use myContract.options.account instead of myContract.defaultAccount.

The below code is the altered version of the question code that outputs the desirable result:

var Web3=require("web3");
var fs=require('fs');//fs module added in solution.
var web3= new Web3('ws://localhost:8545');
web3.eth.getAccounts().then(console.log);// shows all accounts exist in the project
var JsonFile=fs.readFileSync("E:/Emrooz/build/contracts/TEST.json");
var JsFile=JSON.parse(JsonFile);
var myContract=new web3.eth.Contract(JsFile.abi," 0xC8129A44979263D578A8BD52d403d6537820e969
",{ account:" 0xeB2a9E0338616e35B5e844Bd38924C79D99d7346
", balance:"99.98990494"});
console.log(myContract.options.account);//shows the desirable result.
| improve this answer | |

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.