Error when creating a wallet using kin.js - typescript2.0

Trying to embed kin.js in an Ionic App, I can see that the key creation using Keypairs and network initialization is ok
const keys = Keypair.random();
const network = KinNetwork.Production;
However when I try to create the wallet
createWallet(network, keys)
.then(res => {
console.log(res);
}, (err) => {
console.log(err)
});
It keeps retrying but at the end it replies with Error: failed to load account:
I can see the API call is made
https://horizon-kin-ecosystem.kininfrastructure.com/accounts/GANWXV7IHG6YGWVIXJNB56OCBIYI7LYKD34CH556YCDOP5LRC2WDJLTC?c=0.32263221858689695
but the response includes this object
{
“type”: “https://stellar.org/horizon-errors/not_found",
“title”: “Resource Missing”,
“status”: 404,
“detail”: “The resource at the url requested was not found. This is usually occurs for one of two reasons: The url requested is not valid, or no data in our database could be found with the parameters provided.”
}
Any missing parameters I should supply beyond the network and keys

Related

Handling errors if no network is available

I just implemented my first backend file where I fetch some user data, messages and so on.
Now I wanted to include error handling if there is no network available.
I don´t know if I did it right but this was my approach so far:
import axios from 'axios'
const host = process.env.VUE_APP_URL
export default {
person: async function (currentPerson) {
let params = {
currentPerson: localStorage.getItem("person"),
};
if (user) {
params['currentPerson'] = currentPerson;
}
return axios.get(`${host}/api/currentPerson`, {
params: params
})
//catching network errors
.catch (error => {
if (error.response) {
/*
* The request was made and the server responded with a
4xx/5xx error
*/
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
/*
* The request was made but no response was received
*/
console.log(error.request);
} else {
// Something happened in setting up the request and triggered an Error
console.log('Error', error.message);
}
console.log(error)
});
},
In my mounted() function of my main view I fetch the data from my backend file from above:
backend.matches().then(function (response) {
self.contacts = response.data.persons;
});
I tried to check in console if it is working but all I get is the following:
In the catch block I check for
response errors: like 4xx/5xx
request errors: if my network not responding in time
and any other errors
Would this be the right approach to check if a network is available or not? Or does it degrade the user experience when the user checks the error?
My backend file includes more methods.. do I have to write for each method these kind of requests?
In your backend file you don't react whether there is a network connection or not I think.
And only for reference: that is not the backend, but communicates with the backend - the backend is the part of your code what you communicate with, e.g. Laravel code, an API, ...
Try adding the following at the beginning of your catch part:
if (!error.response) {
//network error
console.log('No network connection');
} else if (error.response) {
//the rest of your code
This should print out No network connection in your console.
Run your application, turn off the internet connection and check the console.
These kind of code should always be located in your backend part.
My answer maybe different from your question.
When i create a .net core API with Angular i used three things to check is there network or not?
subscribe to windows's offline/online event
create signalR hub from layout component to API server
API request failed (it means lot of incident, but if 1. or 2. case is true i know what cause 3. case

API GET request URL works on Brave/Chrome but not on fetch()

When I paste and search this url
https://api.openweathermap.org/data/2.5/forecast?lat=39.48923&lon=-0.4780256&appid=b11fc49d6b14456d6aacedc8d0153072
it makes the request just fine:
But then on my code, when I want to fetch it and save this json it turns out with "Network request failed":
I have only used fetch() with local urls and it always worked.
This is my code (you can use my api key I can generate a new one later):
GetClima() {
//fetch(`${this.state.api.url}lat=${this.props.latitudDestino}&lon=${this.props.longitudDestino}&appid=${this.state.api.key}`)
fetch("https://api.openweathermap.org/data/2.5/forecast?lat=39.48923&lon=-0.4780256&appid=b11fc49d6b14456d6aacedc8d0153072")
.then(res => res.json())
.then(res => {
this.setState({
dataClima: res
})
})
}
This is because your emulator/simulator isn't connected to the internet. I can see your Wi-Fi icon in the status bar saying that it isn't connected to the internet.
It clearly says Type Error: Network Request Failed. Make sure that you have configured your virtual device properly and check your internet connection.
Having that said, make sure that you catch the errors properly using .catch() or using try-catch block if you're using async-await

unable to encrypt message in matrix-js-sdk

I'm used 'olm' version '3.1.4' and 'matrix-js-sdk' version '2.4.6'
Trying use end to end encryption supported in matrix using olm
I'm using the following code snipping:
const cryptoStore = new sdk.MemoryCryptoStore(window.localStorage);
const webStorageSessionStore = new sdk.WebStorageSessionStore(window.localStorage);
var matrixStore = new sdk.MatrixInMemoryStore();
matrixClient = sdk.createClient({
baseUrl: 'SERVER_HOME',
accessToken: token,
userId: 'USER_ID',
store: matrixStore,
sessionStore: webStorageSessionStore,
cryptoStore: cryptoStore,
deviceId: 'DEVICE_ID'});
matrixClient.initCrypto()
.then(() => {
matrixClient.startClient({ initialSyncLimit: 10 });
})
1- I have error with post key/upload API bad request
REQUEST: POST Request URL: https://SERVER_HOME/_matrix/client/r0/keys/upload/DEVICE_ID?access_token=XXXX
RESPONSE: 400 Bad Request {"errcode":"M_UNKNOWN","error":"One time key signed_curve25519:XXXX already exists. Old key: {\"key\":\"64zJVMH61Toei8Kaz2SRXEZ4VyNBjjG2vfaGjSXXXX\",\"signatures\":{\"#USER_ID\":{\"ed25519:869254020336060\":\"HBnlhazYGY+IrvImq5d4OcIYsXeo094St2p/SMYWobMfteML1gH1jMSUmAh9o7EYIXQMnshiPSh6FSdL4XXXXw\"}}}; new key: {'key': 'VSfPQ7NFzdPl0owA1pVK8CqTzLCyF6NQCuS8aTIIYmc', 'signatures': {'#USER_ID': {'ed25519:869254020336060': 'rIQHea/3kh5w8PaC91H83zsTKQDevbkPpnJ5Dpj7YHv3o4Jzq1O3AmgMzfhFzhlXBwn1N6gRPfC+jNMCIPXXXX'}}}"}
2- When I test it with encryption Roit room and try to send message from sdk to Roit find this is error get this error
Error sending event UnknownDeviceError: This room contains unknown devices which have not been verified. We strongly recommend you verify them before continuing.
3- When I test it with encryption Roit room and send message from Roit to sdk I get this error
Error decrypting event (id=xxxx): DecryptionError[msg: The sender's device has not sent us the keys for this message., session: FoIZTb4W906iFiQofhzgyZlkjeR9XazjN9vfIC9uzFQ|nCwWvT+VU/FVz7uNLojW51+PtkrXj++eMC1d/Xxxxxxx]

Botkit slackbot error "Could not load team while processing webhook"

I have created a simple express server and added a /slack/receive route to handle webhook requests from the Slack events API:
// routes.js (which is used by my app defined in server.js)
...
let slack = require('./controllers/slack');
router.post('/slack/receive', slack.receive);
...
I then use Botkit to create a simple Slack application:
// controllers/slack.js
'use strict';
const logger = require('../config/winston');
// initialise firebase storage for botkit
const admin = require('firebase-admin');
var serviceAccount = require('../config/firebase.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
var db = admin.firestore();
db.settings({
timestampsInSnapshots: true
})
// initialise botkit for slack
const botkit = require('botkit');
const controller = botkit.slackbot({
storage: require('botkit-storage-firestore')({ database: db }),
clientId: process.env.SLACK_CLIENT_ID,
clientSecret: process.env.SLACK_CLIENT_SECRET,
clientSigningSecret: process.env.SLACK_SIGNING_SECRET,
redirectUri: process.env.SLACK_REDIRECT,
disable_startup_messages: true,
send_via_rtm: false,
debug: true,
scopes: ['bot', 'chat:write:bot'],
})
controller.hears('Hello', 'direct_mention,direct_message', (bot, message) => {
logger.info(message);
bot.reply(message, 'I heard a message!');
})
exports.receive = (req, res, next) => {
res.sendStatus(200);
logger.debug(req.body);
controller.handleWebhookPayload(req, res);
};
The server initialises correctly, but as soon as the slack webhook receives a request the following error happens:
Could not load team while processing webhook: Error: could not find team T5VDRMWKX
at E:\Documents\upper-revolutions\node_modules\botkit\lib\SlackBot.js:169:24
at firebaseRef.doc.get.then.catch.err (E:\Documents\upper-revolutions\node_modules\botkit-storage-firestore\src\index.js:86:13)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:118:7)
So far I have found that:
Having/not having storage in the botkit slackbot makes no difference
The error happens within the handleWebhookPayload method as code within controller.hears() does not get executed
This error occurs because botkit needs some form of storage where it can store all the teams (channels and users too) and retrive it later on.
So, When your method handleWebhookPayload gets executed it calls another method called
findAppropriateTeam that will query for the specified team record in the storage provided by you (It might be mongoDB or a JSON file or other). The error is saying that you do not have any record in the storage with the id provided.
So this might implicate two things:
You did not provide a storage for botkit to work
You did not save the team id in the storage
The solution to the first problem is quite simple. You just need to install mongodb in your machine and then pass to botkit the MONGO_URL.
NOTE: I see that you are using the botkit simple storage and this might be the problem since I also have experieced some troubles with this kind of storage not saving records.
const controller = botkit.slackbot({
storage: 'mongodb//localhost:27017:/yourdb',
})
//OR
const controller = botkit.slackbot({
storage: process.env.MONGO_URL,
})
The possible solution to the second problem:
I will assume you are using botkit locally, so you must be using some tunneling like ngrok or localtunnel. In that case make sure:
You provided the redirect URL to Slack (Ex, https://your_url/oauth)
You accessed the https://your_url/login page
Botkit saves your team id on the provided storage when you access the /login route and authorizes the app. So if you skipped that part then botkit won't save your team id and therfore will throw an error when you receive events later on.
Check this like [https://github.com/howdyai/botkit/issues/938] for discutions on the topic
I hope this helps!

getaddrinfo ENOTFOUND API Google Cloud

I'm trying to execute API.AI tutorial for building a weather bot for Google Assistant (the one here: https://dialogflow.com/docs/getting-started/basic-fulfillment-conversation)
I made everything successfully, created the bot within API, created the Fulfillments, installed NodeJS on my pc, connected Google Cloud Platform, etc.
Then I created the index.js file by copying it exactly how it's stated on API.ai tutorial with my API key from World Weather Organisation (see below).
But when I use the bot, it doesn't work. On the Google Cloud Platform the error is always the same:
Error: getaddrinfo ENOTFOUND api.worldweatheronline.com
api.worldweatheronline.com:80
at errnoException (dns.js:28)
at GetAddrInfoReqWrap.onlookup (dns.js:76)
No matter how often I do it I get the same error. So I don't actually reach the API. I tried to see if anything changed from WWO side (URL, etc.) but apparently no. I updated NodeJS and still same issue. I refreshed the Google Cloud platform completely and didn't help.
That one I really can't debug. Could anyone help?
Here's the code from API.ai:
'use strict';
const http = require('http');
const host = 'api.worldweatheronline.com';
const wwoApiKey = '[YOUR_API_KEY]';
exports.weatherWebhook = (req, res) => {
// Get the city and date from the request
let city = req.body.result.parameters['geo-city']; // city is a required param
// Get the date for the weather forecast (if present)
let date = '';
if (req.body.result.parameters['date']) {
date = req.body.result.parameters['date'];
console.log('Date: ' + date);
}
// Call the weather API
callWeatherApi(city, date).then((output) => {
// Return the results of the weather API to Dialogflow
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ 'speech': output, 'displayText': output }));
}).catch((error) => {
// If there is an error let the user know
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ 'speech': error, 'displayText': error }));
});
};
function callWeatherApi (city, date) {
return new Promise((resolve, reject) => {
// Create the path for the HTTP request to get the weather
let path = '/premium/v1/weather.ashx?format=json&num_of_days=1' +
'&q=' + encodeURIComponent(city) + '&key=' + wwoApiKey + '&date=' + date;
console.log('API Request: ' + host + path);
// Make the HTTP request to get the weather
http.get({host: host, path: path}, (res) => {
let body = ''; // var to store the response chunks
res.on('data', (d) => { body += d; }); // store each response chunk
res.on('end', () => {
// After all the data has been received parse the JSON for desired data
let response = JSON.parse(body);
let forecast = response['data']['weather'][0];
let location = response['data']['request'][0];
let conditions = response['data']['current_condition'][0];
let currentConditions = conditions['weatherDesc'][0]['value'];
// Create response
let output = `Current conditions in the ${location['type']}
${location['query']} are ${currentConditions} with a projected high of
${forecast['maxtempC']}°C or ${forecast['maxtempF']}°F and a low of
${forecast['mintempC']}°C or ${forecast['mintempF']}°F on
${forecast['date']}.`;
// Resolve the promise with the output text
console.log(output);
resolve(output);
});
res.on('error', (error) => {
reject(error);
});
});
});
}
Oh boy, in fact the reason was most stupid ever. I didn't enable "billing" on Google Cloud Platform and that's why it blocked everything (even though I'm using a free test of the API). They just wanted my credit card number. It works now
I had the same issue trying to hit my db. Billing wasn't the fix as I had billing enabled already.
For me it was knexfile.js setup for MySql - specifically the connection object. In that object, you should replace the host key with socketPath; and prepend /cloudsql/ to the value. Here's an example:
connection: {
// host: process.env.APP_DB_HOST, // The problem
socketPath: `/cloudsql/${process.env.APP_DB_HOST}`, // The fix
database: process.env.APP_DB_NAME,
user: process.env.APP_DB_USR,
password: process.env.APP_DB_PWD
}
Where process.env.APP_DB_HOST is your Instance connection name.
PS: I imagine that even if you're not using Knex, the host or server parameter of a typical DB connectionstring will have to be called socketPath when connecting to Google Cloud SQL.