Unable to connect Ganache with Truffle/Npm Dev server - npm

I am able to work with Truffle and Ganache-cli. Have deployed the contract and can play with that using truffle console
truffle(development)>
Voting.deployed().then(function(contractInstance)
{contractInstance.voteForCandidate('Rama').then(function(v)
{console.log(v)})})
undefined
truffle(development)> { tx:
'0xe4f8d00f7732c09df9e832bba0be9f37c3e2f594d3fbb8aba93fcb7faa0f441d',
receipt:
{ transactionHash:
'0xe4f8d00f7732c09df9e832bba0be9f37c3e2f594d3fbb8aba93fcb7faa0f441d',
transactionIndex: 0,
blockHash:
'0x639482c03dba071973c162668903ab98fb6ba4dbd8878e15ec7539b83f0e888f',
blockNumber: 10,
gasUsed: 28387,
cumulativeGasUsed: 28387,
contractAddress: null,
logs: [],
status: '0x01',
logsBloom: ... }
Now when i started a server using "npm run dev". Server started fine but is not connecting with the Blockchain
i am getting the error
Uncaught (in promise) Error: Contract has not been deployed to detected network (network/artifact mismatch)
This is my truffle.js
// Allows us to use ES6 in our migrations and tests.
require('babel-register')
module.exports = {
networks: {
development: {
host: '127.0.0.1',
port: 8545,
network_id: '*', // Match any network id
gas: 1470000
}
}
}
Can you please guide me how i can connect ?

Solve the issue.
issue was at currentProvider, i gave the url of ganache blockchain provider and it worked.
if (typeof web3 !== 'undefined') {
console.warn("Using web3 detected from external source like Metamask")
// Use Mist/MetaMask's provider
// window.web3 = new Web3(web3.currentProvider);
window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545"));
} else {
console.warn("No web3 detected. Falling back to http://localhost:8545. You should remove this fallback when you deploy live, as it's inherently insecure. Consider switching to Metamask for development. More info here: http://truffleframework.com/tutorials/truffle-and-metamask");
// fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}

In your truffle.js, change 8545 to 7545.
Or, in Ganache (GUI), click the gear in the upper right corner and change the port number from 7545 to 8545, then restart. With ganache-cli use -p 8545 option on startup to set 8545 as the port to listen on.
Either way, the mismatch seems to be the issue; these numbers should match. This is a common issue.
Also feel free to check out ethereum.stackexchange.com. If you want your question moved there, you can flag it and leave a message for a moderator to do that.

Related

WalletConnect disable infura error message

I am currently developing a dapp and I am integrating walletconnect.
I use this code for connecting:
const chainId = ContractService.getPreferredChainId();
const rpc = ContractService.getRpcAddress();
provider = new WalletConnectProvider({
infuraId: undefined,
rpc: {
[chainId]: rpc,
},
});
await provider.enable();
chainId is dynamically chosen based on if the app is in development mode or not. while in development it runs on chain id 97.
RPC is the same story, it just gets the binance smart chain RPC JSON provider.
Connecting works well, but I get the following error:
Any idea on how I can fix this without making an infura account? Or is that required..
I found out what the problem was.
make sure to add a chainId to the object like this:
new WalletConnectProvider({
infuraId: undefined,
rpc: {
1: "https://RPC_URL",
},
chainId: 1
});
Then it should work without issues, you can even omit the infuraId field

Best way to configure truffle `from` address

I'm setting up my truffle config file and I'm setting the from address from an env variable like this:
module.exports = {
networks: {
local: {
host: "127.0.0.1",
port: 8545,
network_id: "*",
from: process.env.OWNER,
}
}
};
Then I run OWNER=<address> truffle migrate --network local
Any suggestions on a better way to do this, to get truffle to use the first address generated by ganache?
If you omit the from parameter in your truffle.cfg, it will automatically default to the first account returned by web3.eth.getAccounts from the provider you're connected to.
If you want more dynamic control over the account used, you can control this with the deployer.
var SimpleContract = artifacts.require("SimpleContract");
module.exports = function(deployer, network, accounts) {
deployer.deploy(SimpleContract, { from: accounts[1] }); // Deploy contract from the 2nd account in the list
deployer.deploy(SimpleContract, { from: accounts[2] }); // Deploy the same contract again (different address) from the 3rd account.
};
Of course, you don't have to use the account list passed in and you can pull in a list from any other data source you want. You can also use network if you want to have environment specific logic.

Soap client with Node and strong-soap returning error with cerficate

I am using strong-soap (but with node-soap is the same result) node module to connect with soap services.
In the first step I am creating the client and trying to connect one method in this case "doLogin" method.
My code is:
soap.createClient(url, clientOptions, (err, client) => {
var loginApi = { UserName: "xxxx", Password: "xxxxxx" };
var loginUser = {
userName: "comercial#xxxxx.com"
};
client.addSoapHeader(header);
//client.setSecurity(new soap.BasicAuthSecurity(loginApi));
// we now have a soapClient - we also need to make sure there's no `err` here.
client.doLogin(loginUser, (err, result) => {
//'result' is the response body
console.error(err);
console.log("Result: \n" + JSON.stringify(result));
});
But the variable err is returning this error in the console:
{ Error: unable to verify the first certificate
at TLSSocket.<anonymous> (_tls_wrap.js:1105:38)
at emitNone (events.js:106:13)
at TLSSocket.emit (events.js:208:7)
at TLSSocket._finishInit (_tls_wrap.js:639:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:469:38) code:
'UNABLE_TO_VERIFY_LEAF_SIGNATURE' }
and result is undefined.
why is happening this error?
result is undefined by the error?
I have faced same error, unable to verify the first certificate.
This is because of SSL cerficate isnt verified.
Your nodejs script calls your server, it is going to carry out the full TLS check process (as you would hope). This will check the certificates for validity etc.
To work around this issue, you can run the following Steps:
npm config set strict-ssl false
As a best practice, it is wise to set it back to true afterwords so you do not accidentally install an untrusted module that you actually do not trust.
After this,
npm cache clean --force
Add the following environment variable:
NODE_TLS_REJECT_UNAUTHORIZED=0
For Linux:
export NODE_TLS_REJECT_UNAUTHORIZED=0
For Nginx
NODE_TLS_REJECT_UNAUTHORIZED=0
For Window:
this will set for only current command prompt screen,
set NODE_TLS_REJECT_UNAUTHORIZED=0
This has solved issue for me. Please try
Note: Make sure you do not leave this option on in production. Please don't disable TLS checks at all.
FIXED:
I have added correct certificates and rejectUnauthorized: false to create client and added "envelope" directive to the headers and now it is working.
I donĀ“t like the instruction rejectUnauthorized: false by security topics and I would like to know how to remove this in production environment.
Thank you!!

pouchdb - secure replication with remote LevelDB

I am keen on using PouchDB in browser memory for an Angular application. This PouchDB will replicate from a remote LevelDB database that is fed key-value pairs from an algorithm. So, on the remote end, I would install PouchDB-Server. On the local end, I would do the following (as described here) on a node prompt.
var localDB = new PouchDB('mylocaldb')
var remoteDB = new PouchDB('https://remote-ip-address:5984/myremotedb')
localDB.sync(remoteDB, {
live: true
}).on('change', function (change) {
// yo, something changed!
}).on('error', function (err) {
// yo, we got an error! (maybe the user went offline?)
});
How do we start a PouchDB instance that supports TLS for live replication as described in the snippet above?
How do I start a PouchDB instance that supports TLS for live replication?
So after some more searching, it is clear from this topic, HTTPS is not supported for PocuhDB-Server.
Sorry, I misunderstood your question. I thought you intend to connect to a CouchDB server with PouchDB through HTTPS. Therefore, the following answer actually doesn't answer your question.
I created a server.js file like below to communicate with my CouchDB through HTTPS. Please note that the SSL certificate is (in my case) self-signed, and also CouchDB listens by default on port 6984 in the case of TLS:
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; // Ignore rejection, becasue CouchDB SSL certificate is self-signed
//import PouchDB from 'pouchdb'
const PouchDB = require('pouchdb')
const db = new PouchDB('https://admin:****#192.168.1.106:6984/reproduce')
db.allDocs({
include_docs: true,
attachments: false
}).then(function (result) {
// handle result
console.log(result)
}).catch(function (err) {
console.log(err);
});
I'm running the above file with $ node server.js and I'm getting the expected results:
$ node server.js
{ total_rows: 3,
offset: 0,
rows:
[ { id: '5d6590d3-41c7-4011-be5d-b21f80079ae5',
key: '5d6590d3-41c7-4011-be5d-b21f80079ae5',
value: [Object],
doc: [Object] },
{ id: 'ec6a36d1-952e-4d86-9865-3587c6079fb5',
key: 'ec6a36d1-952e-4d86-9865-3587c6079fb5',
value: [Object],
doc: [Object] },
{ id: 'f508e7aa-b4dc-42fc-96be-b7c1ffa54172',
key: 'f508e7aa-b4dc-42fc-96be-b7c1ffa54172',
value: [Object],
doc: [Object] } ] }
I created the above code with NodeJS on server-side. However, if you want to communicate with CouchDB through HTTPS inside the browser, i.e. on client-side, you have to enable CORS on CouchDB.

Express server crashing due to MongoDB connection loss

I am having issues with an HTTP Node.js server built with:
Ubuntu 14.04
MongoDB 3.0.4
iojs v2.3.3
express=4.10.*
mongodb=1.4.34
The following middleware are being used:
app.use(response_time());
app.use(body_parser.urlencoded({extended: true}));
app.use(body_parser.json());
var MongoClient = require('mongodb').MongoClient;
app.use(function (req, res, next) {
var connection_options = {auto_reconnect: false};
MongoClient.connect(config.server.db, connection_options, function (err, db) {
if (err) {
log.error(err); // Logging error.
return next(err);
}
req.db = db;
next();
});
});
The server started running at 20:40:10 and successfully handled multiple requests.
At 02:59:02, the following error started to get logged on every request:
02:59:02.114Z ERROR CrowdStudy: failed to connect to [127.0.0.1:27017]
Error: failed to connect to [127.0.0.1:27017]
at null.<anonymous> (/home/ncphillips/Projects/crowdstudy/node_modules/mongodb/lib/mongodb/connection/server.js:555:74)
at emitThree (events.js:97:13)
at emit (events.js:175:7)
at null.<anonymous> (/home/ncphillips/Projects/crowdstudy/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:156:15)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at Socket.<anonymous> (/home/ncphillips/Projects/crowdstudy/node_modules/mongodb/lib/mongodb/connection/connection.js:534:10)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at emitErrorNT (net.js:1237:8)
My initial suspicion was that I was that the connection pool was filling up because I don't have anything to handle calling req.db.close(). I thought that passing in the options {auto_reconnect: false} would fix this issue by automatically closing the connection after some time, but it seems I was wrong.
Note that restarting the server fixes the issue, so I believe the problem has to do with Node rather than Mongo.
If this has to do with the connection pool, is there some setting I can pass to fix this, or can I have an end-ware that makes sure the connection always gets closed?
Thanks a lot to anyone who can help me out!
autoReconnect is an option that should be passed to the server configuration:
MongoClient.connect(config.server.db, {
server : { autoReconnect : false }
}, ...);
The documentation contains some errors: it states that the default setting is false (which it isn't), and it also states that autoReconnect should be set in an object called socketOptions (which it shouldn't).
You can add various event listeners to the db object that gets passed back, to detect when the connection to the database got closed/reconnected/...:
db.on('close', function(reason) { ... });
db.on('reconnect', function(db) { ... });
More events here.