Serum Error What is "Unable to simulate swap"? - javascript

I would like to swap using project-serum/serum-ts.
I prepared the following while reading readme.MD.
Use the latest version of Yarn etc.
Install the dependent modules according to readme.MD
Prepare the id.json file containing the wallet secret in ./config/solana/id.json
Put 0.01 SOL in the wallet on mainnet-beta.
After that, I tried to run node ./package/swap/example/swap.js, which is prepared for the sample.
This file -> https://github.com/project-serum/serum-ts/blob/master/packages/swap/examples/swap.js
I confirmed that it worked until line 26 _srmSwapPairs.
However, at line 29, I get the following error
Error: Unable to simulate swap
at Swap.estimate (/mnt/c/Users/username/Desktop/solana_test/serum-ts/packages/swap/lib/index.js:401:19)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async main (/mnt/c/Users/username/Desktop/solana_test/serum-ts/packages/swap/examples/swap.js:29:25)
My OS is Windows 10, but I am using WSL.
What could be the cause?

This is most likely failing because you're trying to simulate a swap from SRM to USDC on your wallet, but your wallet doesn't have enough SRM to complete the trade, or doesn't have the accounts to conduct the trade.
To learn more about the issue, you can hack the code to print out more information about the failure:
const resp = await this.program.provider.simulate(
tx,
signers,
params.options,
);
if (resp === undefined || resp.value.err || !resp.value.logs) {
console.error(resp); // get more information about the error
throw new Error('Unable to simulate swap');
}
You can make the changes at https://github.com/project-serum/serum-ts/blob/93946077cbacc4149a3372d9e6651bf4de18a255/packages/swap/src/index.ts#L535

Related

Cloud Build Trigger returns 14 UNAVAILABLE: 502:Bad Gateway

Using the JavaScript library, NodeJS-CloudBuild we've been able to write a Cloud Function that triggers a new Cloud Build whenever we need.
It's been stable for a few months, but starting monday, we've been getting an inconsistent error whenever we call the function:
Error: 14 UNAVAILABLE: 502:Bad Gateway
The code sample is pretty simple, taken straight from the repository but with our variables.
// Creates a client
const cb = new CloudBuildClient();
// Starts a build against the branch provided.
const [resp] = await cb.runBuildTrigger({
projectId,
triggerId,
source: {
projectId,
dir: './',
branchName,
},
});
console.info(`triggered build for ${triggerId}`);
I'm not sure what changed recently to cause these return errors. It works fine when doing a "manual" trigger from the Cloud build dashboard, too.
It's been solved upstream. It wasn't the library's fault.

Error: getaddrinfo EAI_AGAIN api.spotify.com:443

While I am in a process of integrating Spotify API into Google Assistant app, implementing Account Linking,
getaddrinfo EAI_AGAIN api.spotify.com:443
This above error has been kept coming out in the console, although it seems to be working like nothing is wrong around API implementation. The access token is properly created and received and client and secret ids were filled without any typo. Also, I tested API calls on Spotify Console (https://developer.spotify.com/console/get-artist-albums/). No error was found. It fetched expected data from the Spotify server, so it should not be related to Account Linking and Spotify Server. The created code myself is below: I assume there is something wrong around spotify-web-api-node, node, npm, or firebase-functions?? I recently have done node versioning so I might did something wrong.
Node version: v7.9.0
spotify-web-api-node: ^4.0.0
firebase-functions: ^2.0.3
npm version: 6.4.1
Added engines: { "node": "8" } // this is in package.json to use asyn and await
app.intent(SomeIntent, async (conv, params) => {
console.log('user info', JSON.stringify(conv.user));
conv.ask('lets play'); //okay
const access_token = conv.user.access.token || ''; // okay
console.log('Your TOKEN information here: ' + access_token); // okay
spotifyApi.setAccessToken(access_token); // should be set correctly
let data = await findMusic(); // error in the findMusic func
conv.ask('found this song。', data.name); // so no data.name
});
function findMusic() {
return spotifyApi.getArtistAlbums('43ZHCT0cAZBISjO8DG9PnE').then((data) => {
console.log('artist song', data.body);
return data.body; //this does not return because error is produced
}).catch(err => {
console.log('Something went wrong!', err);
return err; // this error is WebapiError: getaddrinfo EAI_AGAIN api.spotify.com:443
});
}
UPDATE
#Nick-Felker mentioned in the comment below that external calls are allowed only through paid plans. So this might be the solution (not proved to be working right now because I am not using a paid plan. The detailed explanation below is quoted from An answer comment from another StackOverflow post
The Spark plan allows outbound network requests only to Google-owned services. Inbound invocation requests are allowed within the quota. On the Blaze plan, Cloud Functions provides a perpetual free tier. The first 2,000,000 invocations, 400,000 GB-sec, 200,000 CPU-sec, and 5 GB of Internet egress traffic is provided for free each month. You are only charged on usage past this free allotment. Pricing is based on total number of invocations, and compute time. Compute time is variable based on the amount of memory and CPU provisioned for a function. Usage limits are also enforced through daily and 100s quotas. For more information, see Cloud Functions Pricing.
UPDATE
In my case, the above solution worked. Hope this article helps others!
I got this error due to network problem. And solved when connected

Web3/Metamask: Error: Contract has not been deployed to detected network (network/artifact mismatch) on Kovan network

I try to deploy an instance of a contract that is already live on the Kovan network to interact with it with web3 and metamask.
So first thing first, I set metamask as my current provider then I deploy an instance of the contract like this:
deployContract = (contract) => {
contract.deployed().then(function(instance) {
let proxy = instance;
return proxy.ProxyAddress()
}).then(function(result){
this.setState({
address: result,
});
})
}
But then, I get the following error:
Uncaught (in promise) Error: Contract has not been deployed to detected network (network/artifact mismatch)
at eval (webpack:///./~/truffle-contract/contract.js?:429)
at <anonymous>
I found out that it was caused by the network ID of web3 which happen to be wrong.
My web3 network ID is set by Metamask which is supposed to inject web3 with the correct ID. But when I get the network ID I get a totaly different result:
web3.version.getNetwork(function(err,res){console.log(res)})
> 3
Is there a way to manualy set web3's version network? I looked in the documentation and github but there was no usefull insights.
EDIT:
It appears that closing and reopening chrome resolve the ID problem. So now I have both ID set as 42 but the error is still the same as before. Back to square one...
Ok so in the end the problem was caused by the way of importing my contracts. My previous import was done like this:
let contract = require('truffle-contract');
let Factory = contract("../contracts/Factory.json");
While it should actualy be imported this way:
let contract = require('truffle-contract');
let json = require("../contracts/Factory.json");
let Factory = contract(json);
So to sum up, if an error like this happen to you, do those checks first:
-Check contract import.
-Check your web3 provider. console.log(window.web3.currentProvider)
-Check web3 network ID. web3.version.getNetwork(function(err,res{console.log(res)})

Google Sign In for Websites causing "Signature verification failed" with JWT PHP library

Google web sign in has driven me positively crazy...
I'm building a simple web application, and I'm trying to integrate Google's sign in feature into the website (https://developers.google.com/identity/sign-in/web/).
The JavaScript seemed to go fairly well, and the next step was to verify the id_token I was receiving with my backend server (again, against Google's recommendation: https://developers.google.com/identity/sign-in/web/backend-auth).
It's a PHP-based web application, and I've successfully installed the Google Client API library using composer: composer require google/apiclient, but when posting my id_token value to my PHP backend system I'm consistently receiving the following error:
Firebase\JWT\SignatureInvalidException
File: .\vendor\firebase\php-jwt\src\JWT.php:112
Message: Signature verification failed
Stack trace:
#0 .\vendor\google\apiclient\src\Google\AccessToken\Verify.php(103): Firebase\JWT\JWT::decode('eyJhbGciOiJSUzI...', '-----BEGIN PUBL...', Array)
#1 .\vendor\google\apiclient\src\Google\Client.php(712): Google_AccessToken_Verify->verifyIdToken('eyJhbGciOiJSUzI...', '10...')
I've also used the id_token value on Google's "tokeninfo" endpoint (https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=ABC123), and the id_token validates perfectly, so I'm sure it's not the id_token value that's wrong. It's also passing it perfectly via the POST variable to the PHP script, so I'm at a bit of a loss.
Here's my code:
Javascript:
<script src="https://apis.google.com/js/platform.js?onload=googleAppStart" async defer></script>
<script>
var googleAppStart = function(){gapi.load('auth2', initGoogleSignIn);};
var auth = false;
function initGoogleSignIn(){
auth = gapi.auth2.init({
client_id : 'client-id-is-here',
scope : 'profile'
});
auth.attachClickHandler(document.getElementById('my-button'));
auth.isSignedIn.listen(googleSignInChanged);
auth.currentUser.listen(googleCurrentUserChanged);
if (auth.isSignedIn.get() == true)
auth.signIn();
}
function googleSignInChanged(signed_in){}
function googleCurrentUserChanged(user){
var auth_response = user.getAuthResponse();
var id_token = auth_response.id_token;
if (id_token != undefined){
var url = '/verify-google-signin';
var params = {id_token: id_token};
jQuery.post(url, params, function(data){}, 'json');
}
}
</script>
...and my PHP catching the POST:
<?php
require_once '/vendor/autoload.php';
$credentials = array("client_id" => "client-id-is-here");
$client = new \Google_Client($credentials);
$data = $_POST;
if (isset($data['id_token'])) {
$id_token = trim($data['id_token']);
// Exception generated here...
$payload = $client->verifyIdToken($id_token);
}
?>
Thank you so much for taking the time to read this, and for any assistance! It's greatly appreciated!
I had the same issue today.
Easier if you just execute:
composer require firebase/php-jwt:4.0
Fortunately you can verify id_token without google library as described here https://developers.google.com/identity/sign-in/web/backend-auth#calling-the-tokeninfo-endpoint
if (isset($data['id_token'])) {
$id_token = trim($data['id_token']);
try {
$res = (new \GuzzleHttp\Client())->request('GET',
'https://www.googleapis.com/oauth2/v3/tokeninfo', [
'query' => ['id_token' => $id_token],
]);
$payload = json_decode($res->getBody()->getContents(), true);
//you still need to check that the aud claim contains one of your app's client IDs
if ($payload['aud'] != "client-id-is-here") {
throw new \Exception("App Isn't valid", 422);
}
} catch (RequestException $e) {
//IF token isn't valid you will be here
if ($e->hasResponse()) {
/** #var \GuzzleHttp\Psr7\Response $resp */
$resp = $e->getResponse();
$error = json_decode($resp->getBody()->getContents(), true)['error_description'];
throw new \Exception($error, $resp->getStatusCode());
}
}
}
If you have no exceptions then your token is valid
It is a problem with php-jwt. Latest version is not working with Google Api Client.
Try to use php-jwt version 4.
I put "firebase/php-jwt": "<5.0" in my composer.json file.
Worked as a charm!
This has been fixed in v2.2.1 of google/apiclient so make sure you are running this version or later if anyone else encounters this issue.
Related discussions here and here.
I've got problems with Google Sign-In backend authentication yesterday, using both google/apiclient 2.2.0 and 2.1.3.
tl;dr it was most likely malfunctions on the Google side or some obscure limits I'm unaware of (nothing in the Developer Console about that).
First, the "idToken" Google was giving me client-side was not a valid JWT: openssl_verify() was rejecting it in Firebase\JWT\JWT, throwing a Firebase\JWT\SignatureInvalidException. I followed your advice, installed google/apiclient 2.1.3 and this exception was not being throwed anymore but the resulting payload was null (so the idToken was still invalid).
A few hours later, I had experienced intermittent results with the apiclient 2.3.0: sometimes the token was invalidated by signature verification (and throwing the signature exception) and sometimes the token was cryptographically valid but the returned payload was null. Once in a while, the token was valid (!).
In the end, the backend authenticaton process was succeeding every time.
As I began experiencing these problems, I tried to fix it generating new OAuth2 keys, revert to a previous verions of my codebase (both server-side and client-side) that I knew was working, removed all browser data and tried to get the token on Cordova with the Sign In for Android. Nothing worked. Also no message in the Developer Console, no visible limits, no security e-mail.
If it's not a bug but a feature, the error handling is quite harsh :)
If you are not using Firebase (taken from https://github.com/googleapis/google-api-php-client)
rm -r vendor/google/apiclient-services
Add this to composer.json
"scripts": {
"post-update-cmd": "Google\\Task\\Composer::cleanup"
},
"extra": {
"google/apiclient-services": [
"Drive" ,
"... any other services here ...",
]
}
Finally
composer install
This will resolve the error message with the added benefit of drastically reducing installed packages. As noted, there are at least 200 API services for GAPI

I have tried a sample example of bot builder connection to LUIS through Node.js. I am not able to connect to the LUIS

I have tried to connect the bot to the LUIS engine through the URL,
var builder = require('botbuilder');
// Create bot and bind to console
var connector = new builder.ConsoleConnector().listen();
var bot = new builder.UniversalBot(connector);
// Create LUIS recognizer that points at our model and add it as the root '/' dialog for our Cortana Bot.
var model = 'https://api.projectoxford.ai/luis/v1/application?id=c413b2ef-382c-45bd-8ff0-f76d60e2a821&subscription-key=[REMOVED SUBSCRIPTION KEY]&q=';
var recognizer = new builder.LuisRecognizer(model);
var dialog = new builder.IntentDialog({ recognizers: [recognizer] });
bot.dialog('/', dialog);
// Add intent handlers
dialog.matches('builtin.intent.alarm.set_alarm', builder.DialogAction.send('Creating Alarm'));
dialog.matches('builtin.intent.alarm.delete_alarm', builder.DialogAction.send('Deleting Alarm'));
dialog.onDefault(builder.DialogAction.send("I'm sorry I didn't understand. I can only create & delete alarms."));
I am getting an error like
D:\SID\Bot_Frame\LUIS_BOT1>node app.js
i want to create alarm
default_error
Error: getaddrinfo EAI_AGAIN api.projectoxford.ai:443
at Object.exports._errnoException (util.js:1007:11)
at errnoException (dns.js:33:15)
at GetAddrInfoReqWrap.on lookup [as oncomplete] (dns.js:79:26)
This seemed to be a transient error, so first try to run the app again. If the error persists, check your network settings. If you are using a proxy; make sure that node and npm are well configured.
From http://www.codingdefined.com/2015/06/nodejs-error-errno-eaiagain.html
EAI_AGAIN actually means a temporary failure in name resolution or simply the name server returned a temporary failure indication
EAI_AGAIN is actually a DNS lookup timed out error means it is either
a network connectivity error or some proxy related error. Try
resolving your proxy settings and check you have a decent internet
connection or not.
You can also try to run the LUIS Node.js sample but I don't think there is an error in your code and also the error message that you are getting is not around your code.

Categories