Contract has not been deployed to detected network (network/artifact mismatch) - blockchain

I'm having some issues determining and connecting with the right MetaMask network.
In Ganache, my RPC server is 127.0.0.1.7545 and the network id is 5777. However, when I try to create a custom RPC in MetaMask with this info, I get the following error:
The endpoint returned a different chain ID: 1337
This is my truffle-config.js:
module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*" // Match any network id
},
develop: {
port: 8545
}
}
};
I'm hoping this would match any network id as I've specified, but the console shows the following error:
Contract has not been deployed to a detected network (network/artifact mismatch)
I've already tried truffle migrate --reset, without success. I've also tried creating an explicit network for testrpc in truffle-config.js - that didn't work either.
Any help would be much appreciated!

You are seeing that error because your contract is deployed to Ganache but you are connected to a different network.
The code that you are writing to load the contract should be inside try/catch block.
inside loading contract logic:
export const loadContract = async (name, provider) => {
// Load the contract
// set the provider
let deployedContract = null;
try {
// Get the contract
deployedContract = await _contract.deployed();
} catch {
console.error("You are connected to the wrong network");
}
return deployedContract;
};
In the component that you are using loadContract, call it inside useEffect.
useEffect(() => {
// Detect Provider
if (provider) {
// contract should be loaded when provider exists
const contract = await loadContract("ContractName", provider);
rLoaded: true,
// Add More logic
} else {
console.error("Please, install Metamask.");
}
};
}, []);
Now you need to make sure if you are not connected to Ganache, disable the button, so your app won't crash. for this create a state variable
// You probably already have logic to get account and contract
const canConnectToContract = account && contract;
now write a proper ui:
{!canConnectToContract && (
<h2>Connect to Ganache</h2>
)}
<button
disabled={!canConnectToContract}
>
Donate 1 Ethreum
</button>

Related

camunda External task js problem to pool https urls

I use external camunda-external-task-client-js to setup a service task for deployed camunda tomcat with ssh setup.
geting error : * polling failed with RequestError: unable to verify the first certificate
tanks.
import {
Client,
logger,
BasicAuthInterceptor,
Variables,
File,
} from "camunda-external-task-client-js";
const basicAuthentication = new BasicAuthInterceptor({
username: "username",
password: "password",
});
const client = new Client({
baseUrl: "https://xxx/engine-rest",
interceptors: basicAuthentication,
use:logger
});
client.subscribe("topic-name", async function ({ task, taskService }) {
}
but i get this error in console :
polling failed with RequestError: unable to verify the first certificate
tanks.

Google Cloud TCP Timeouts (ETIMEDOUT)

I'm having the following issue:
Error: connect ETIMEDOUT 209.85.234.27:25
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1159:16) {
when running the following code on GCP (both Cloud Functions and Cloud Run fail):
const verifier = require('email-verify')
const express = require('express')
const app = express()
/**
* Verify an email address
*/
app.post('/verify', async (request, response, _next) => {
const email = request.query.email
console.log(`Verifying ${email}`)
const isValid = await new Promise(function (resolve, _reject) {
if (!email || typeof email !== 'string') {
return resolve(false)
}
verifier.verify(email, function (err, info) {
if (err) {
console.error(err)
return resolve(false)
}
return resolve(info.success)
})
})
response.json({ valid: isValid, email: typeof email === 'string' ? email : '' })
})
const port = process.env.PORT || 8080
app.listen(port, () => {
console.log(`Listening on port ${port}`)
})
I feel like GCP timeouts when trying to connect to distant servers, but I don't find any resource online to help me debug this. Does anyone already got this kind of issue?
If we look at the error message, we see that it is attempting to connect to an external service at port 25. Google always blocks outbound requests to port 25. You can find this documented and relevant alternatives at this page:
Sending email from an instance
In addition, here is a good search query (here on StackOverflow) for similar questions and answers.

Use AWS IoT Device SDK with Espruino and ESP8266

I'm trying to use the NodeMCU with Espruino IDE and Javascript to send data to AWS IoT Core. However, there's a problem because the Espruino doesn't find the aws-iot-device-sdk module. How can I import it? Or what's an alternative for what I want to do?
Below is the code:
var wifi = require("Wifi");
var awsIot = require('aws-iot-device-sdk');
var WIFI_SSID = "<Wifi>";
var WIFI_OPTIONS = {
password : "<Password>"
};
var device = awsIot.device({
keyPath: 'xxxxxxxxxx-private.pem.key',
certPath: 'xxxxxxxxxx-certificate.pem.crt',
caPath: 'rootCA.pem',
clientId: 'nodejs-thing',
host: 'xxxxxxxxxxxxxx-ats.iot.us-east-2.amazonaws.com'
});
wifi.stopAP(); // disable Wi-Fi AP
wifi.connect(WIFI_SSID, WIFI_OPTIONS, function(err) {
if (err) {
console.log("ERROR: Connection failed, error: " + err);
} else {
console.log("INFO: Successfully connected");
console.log(wifi.getStatus());
console.log(wifi.getIP());
// set hostname and make the NodeMCU available
// through espruino.local (ping or for using the
// Espruino IDE over Wi-Fi
wifi.setHostname("espruino");
// save the Wi-Fi settings and they'll be used
// automatically at power-up.
wifi.save();
}
});
device
.on('connect', function() {
console.log('connect');
//device.subscribe('topic_1');
device.publish('topic_1', JSON.stringify(
{
user: 'user',
device_id: '02',
timestamp: '00:00:00',
temp: 45
}));
});
device
.on('message', function(topic, payload) {
console.log('message', topic, payload.toString());
});
Thank you so much in advance.
I think you're out of luck I'm afraid (on ESP8266). There's no TLS/HTTPS support in Espruino for ESP8266 because of lack of RAM. However there is support on the official Espruino WiFi board, or even the ESP32 port of Espruino.
There's also no 'aws-iot-device-sdk' in Espruino, but as I understand it it's just an MQTT connection so you can create a secure socket with https://www.espruino.com/Internet#tls and then pass that into the MQTT library: https://www.espruino.com/MQTT
You can specify certificates like this: https://www.espruino.com/Reference#l_tls_connect
Otherwise you could use something like a Raspberry pi to run a local unencrypted MQTT server that connects to the Amazon server.

How to start apollo federation server only when all services are available

I want to start a federated apollo server:
const gateway = new ApolloGateway({
serviceList: [
... list of services
],
});
const startServer = async () => {
const gatewayConfig = await gateway.load();
const server = new ApolloServer({
...gatewayConfig,
subscriptions: false,
});
server.listen().then(({ url }) => {
console.log("Server running!");
});
};
startServer();
When I start the server and one of the services in the serviceList is available, the server starts and logs which services have failed. I want the server to only start when all the services are available, ie when one service is unavailable an error is thrown and the server stops. Any ideas how to do this?
Apollo can't do this as of writing this answer. The only solution is to monitor the availability manually and leverage apollo accordingly. I used apollo-server-express for this.
Below is a demonstration of how I managed to leverage my apollo gateway based on the availability of my services.
Basically, you wrap the middleware of your apollo server. This allows you to exchange your apollo server instance as well as throwing an error when they are not available.
import express from 'express';
import { ApolloServer } from 'apollo-server-express';
import bodyParser from 'body-parser'; // use express body-parser for convinience
// your list of federated services
const serviceList = [
{ name: 'service1', url: 'http://service1/graphql' }
];
// a variable to store the server. We will need to replace him when a service goes offline or comes back online again
let server = null;
// setup express
const app = express();
app.use(bodyParser.json());
app.use(customRouterToLeverageApolloServer); // defined below
// middleware to leverage apollo server
function customRouterToLeverageApolloServer(req, res, next) {
// if services are down (no apollo instance) throw an error
if(!server) {
res.json({ error: 'services are currently not available' });
return;
}
// else pass the request to apollo
const router = server.getMiddleware(); // https://www.apollographql.com/docs/apollo-server/api/apollo-server/#apolloservergetmiddleware
return router(req, res, next);
}
function servicesAreAvailable() {
// go through your serviceList and check availability
}
// periodically check the availability of your services and create/destroy an ApolloServer instance accordingly. This will also be the indication whether or not your services are available at the time.
// you might want to also call this function at startup
setInterval(() => {
if(servicesAreAvailable()) {
server = new ApolloServer({ ... });
}
else {
server = null;
}
}, 1000 * 60 * 5) // check every 5 minutes

Setting Up Apollo Server with subscriptions-transport-ws?

It seems like I have my server set up according to the Apollo docs at http://dev.apollodata.com/tools/apollo-server/setup.html. In my server/main.js file:
//SET UP APOLLO INCLUDING APOLLO PUBSUB
const executableSchema = makeExecutableSchema({
typeDefs: Schema,
resolvers: Resolvers,
connectors: Connectors,
logger: console,
});
const GRAPHQL_PORT = 8080;
const graphQLServer = express();
// `context` must be an object and can't be undefined when using connectors
graphQLServer.use('/graphql', bodyParser.json(), apolloExpress({
schema: executableSchema,
context: {}, //at least(!) an empty object
}));
graphQLServer.use('/graphiql', graphiqlExpress({
endpointURL: '/graphql',
}));
graphQLServer.listen(GRAPHQL_PORT, () => console.log(
`GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}/graphql`
));
//SET UP APOLLO INCLUDING APOLLO PUBSUB
It prints out "GraphQL Server is now running on http://localhost:8080/graphql" to the terminal log indicating that the server was successfully initialized.
But at the top of my main_layout component, when I run this code:
import { Client } from 'subscriptions-transport-ws';
const wsClient = new Client('ws://localhost:8080');
...I get this console message:
WebSocket connection to 'ws://localhost:8080/' failed: Connection closed before receiving a handshake response
What am I missing?
You need to create a dedicated websocket server. It will run on a different port and the code to set it up is provided on the subscriptions-transport-ws package.
Take a look on the following code from GitHunt-API example:
https://github.com/apollostack/GitHunt-API/blob/master/api/index.js#L101-L134
Also you would see that this code is dependent on a class called SubscriptionManager. It is a class from a package called graphql-subscriptions also by the apollo team, and you can find an example of how to use it here:
https://github.com/apollostack/GitHunt-API/blob/master/api/subscriptions.js
TL;DR: You can use graphql-up to quickly get a GraphQL server with subscriptions support up and ready. Here's a more detailed tutorial on using this in combination with Apollo and the websocket client subscriptions-transport-ws.
Obtain a GraphQL Server with one click
Let's say you want to build a Twitter clone based on this GraphQL Schema in IDL syntax:
type Tweet {
id: ID!
title: String!
author: User! #relation(name: "Tweets")
}
type User {
id: ID!
name: String!
tweets: [Tweet!]! #relation(name: "Tweets")
}
Click this button to receive your own GraphQL API and then open the Playground, where you can add some tweets, query all tweets and also test out subscriptions.
Simple to use API
First, let's create a user that will be the author for all coming tweets. Run this mutation in the Playground:
mutation createUser {
createUser(name: "Tweety") {
id # copy this id for future mutations!
}
}
Here's how you query all tweets and their authors stored at your GraphQL server:
query allTweets {
allTweets {
id
title
createdAt
author {
id
name
}
}
}
Subscription support using websockets
Let's now subscribe to new tweets from "Tweety". This is the syntax:
subscription createdTweets {
Message(filter: {
mutation_in: [CREATED]
node: {
author: {
name: "Tweety"
}
}
}) {
node {
id
text
createdAt
sentBy {
id
name
}
}
}
}
Now create a new tab in the Playground and create a new Tweet:
mutation createTweet {
createTweet(
title: "#GraphQL Subscriptions are awesome!"
authorId: "<id-from-above>"
) {
id
}
}
You should see a new event popping up in your other tab where you subscribed before.
Here is a demo about using Apollo GraphQL, React & Hapi: https://github.com/evolastech/todo-react. It's less overwhelmed than GitHunt-React & GitHunt-API
Seems like you aren't actually making the websocket server. use SubscriptionServer. Keep in mind that it is absolutely NOT true that you have to have a dedicated websocket port (I thought this once too) as davidyaha says. I have both my normal queries and subs on the same port.
import { createServer } from 'http';
import { SubscriptionServer } from 'subscriptions-transport-ws';
import { execute, subscribe } from 'graphql';
import { schema } from './my-schema';
// All your graphQLServer.use() etc setup goes here, MINUS the graphQLServer.listen(),
// you'll do that with websocketServer:
// Create WebSocket listener server
const websocketServer = createServer(graphQLServer);
// Bind it to port and start listening
websocketServer.listen(3000, () => console.log(
`Server is now running on http://localhost:3000`
));
const subscriptionServer = SubscriptionServer.create(
{
schema,
execute,
subscribe,
},
{
server: websocketServer,
path: '/subscriptions',
},
);