Web3 Async/Await Problems - async-await

I'm working on a simple Ethereum project, but since I'm not certain whether the issue I'm having is to do with Web3 or Async/Await, I decided to post this question to both Stackoverflow and Ethereum Stackexchange. I'm using javascript with Web3 for this project.
Essentially, I'm running with three async functions, one of which is meant to call the others before performing some calculations and returning the results of its efforts:
async function getFounder() {
console.log("getFounder method");
try{
console.log("just before whoIsFounder");
whoIsFounder = await promisify(RegionalContract2.getFounder);
}catch(err) {
console.log(err)
}
console.log("This Election's Founder is : " + whoIsFounder);
return whoIsFounder;
}
async function getCurrentAccount(){ <<<<<<The problem method
console.log("getCurrentAccount method");
currentAccount = await web3.eth.getAccounts();
return currentAccount;
}
async function isItYours(){
try{
console.log("Inside the isItYours method");
currentAccount = await getCurrentAccount();
founder = await getFounder();
console.log("The getFounder method has resolved completely");
console.log("founder is " + founder);
if (founder != null){
if (founder === currentAccount) {//if the Founder is the same as the value entered.
alert("You are in fact the owner of this Election.");
var x = document.getElementById("hidden");
x.style.display = "block";
}
else {
alert("You are NOT the owner of this Election. The value sent in was " + currentAccount);
}
}
else {
alert("Founder can't be null. Either you're not logged into Metamask, or your account somehow isn't linked up properly.");
}
}catch (err) {
console.log(err)
}
}
isItYours();
When I tried to run this code, however, I got the following error:
Uncaught TypeError: e is not a function
at inpage.js:1
at inpage.js:1
at inpage.js:1
at inpage.js:1
at i (inpage.js:1)
at inpage.js:1
at inpage.js:1
at u (inpage.js:1)
at s (inpage.js:1)
at inpage.js:1
The full console log is:
The founder is:
inpage.js:1 null "0x59a09d00eb11caa5fa70484bf4d78015d10938bc"
admin.html:340 Inside the isItYours method
admin.html:331 getCurrentAccount method
admin.html:305 getFounder method
admin.html:318 just before whoIsFounder
***the aforementioned error from the previous segment***
This Election's Founder is : 0x59a09d00eb11caa5fa70484bf4d78015d10938bc
admin.html:344 The getFounder method has resolved completely
admin.html:345 founder is 0x59a09d00eb11caa5fa70484bf4d78015d10938bc
This leads me to think that the problem lies with getCurrentAccount(), since it employs web3.eth.getAccounts(), rather than a custom method, to return its value. Does anyone know why this might be happening? Thanks.

Related

Angular 8 patch request httpclient.subscribe() doesnt hit response, err or ()

I am encountering an issue I do not understand.
Inside one service I have the following code.
when the code hits PATCH LINE, it jumps immediately to RETURN NOTHING LINE.
the catchError line is not hit.
the () line is not hit
the err line is not hit.
I have compared this to working services and I do not see any difference.
patchItem(item_: Project): Observable<Project> {
const url: string = `${this.serviceUrl}/${item_.id}`;
const data = JSON.stringify(item_);
console.log('inside patch item');
console.log(url);
this.http.patch(url, data, httpOptions) //PATCH LINE
.pipe(
catchError(err => this.handleError('PatchItem', err))
)
.subscribe((response) => {
console.log('item patched ');
return this.myResponse.push(response);
}
, err => console.log("inline error encountered")
,() => console.log("this seems to have completed")
);
console.log("return nothing"); //RETURN NOTHING LINE
return null;
}
The API is C# webapi 2
It is being hit.
There is a problem though, I am expecting the JSON to be passed in and webForm_ is always NULL.
This is probably an important clue.
Again, i compare this to working calls and can not find a difference.
When I inspect the variable in jquery, it has the correct value.
In postman, i get the expected response.
[System.Web.Http.HttpPatch]
[Route("{itemId_}")]
public IHttpActionResult PatchById([FromUri] int itemId_, [FromBody] Models.mpgProject webForm_)
{
return JSONStringResultExtension.JSONString(this, "foobar for now", HttpStatusCode.OK);
}
To save a cycle, here is the handleError function.
I have copy/pasted this from a service that is working as expected.
protected handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
console.error(error); // log to console instead
console.log(`${operation} failed: ${error.message}`);
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
How can Angular be skipping all the subscription stuff when it IS actually calling the API?
I think it has to be a simple syntax issue, but I have been staring at it for hours... :-(
Happy to post any other code requested...
tyia
ps - I would also be happy to retitle the question. I am at a loss for how to phrase a good question title for this...
Your handleError method returns a function (that returns an Observable) when it should return an Observable.
It looks as if the error handler you copied from another service does not fit here.
I could imagine an error handler like this:
private handleError<T>(operation = "operation", error: HttpErrorResponse) {
console.error(error); // log to console instead
console.log(`${operation} failed: ${error.message}`);
// Let the app keep running by returning an empty result.
return of({} as T);
}
This method returns an Observable of an empty object. However, this might not be the best option to react on a failing HTTP PATCH request. You would better throw that error up to the component and let the user retry.

Flutter Response issue

I m having very strange issues in flutter,
i have a function in flutter which is calling api, it work perfectly but sometime it throw error,and app paused the app, Here is my function fluter function and also the api which i m calling,
//this is my flutter function work fine,but sometime it thow this error
Error:Exception has occurred.
_AssertionError (Failed assertion: boolean expression must not be null), the error ocure on this line
//on this line if(body['success']){//
Future countcartdata() async {
var count=0;
SharedPreferences sharedPrefs = await SharedPreferences.getInstance();
String identifier = sharedPrefs.getString('identifier');
final String url = ApiUtility.Main_Url+ApiUtility.countcart+'identifier='+identifier;
var res=await http .get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
var body = json.decode(res.body);
if(body['success']){
print(url);
count=body['coutcart'];
if(count>0){
sharedPrefs.setString('carthasdata','yes');
return count;
}
else{
sharedPrefs.setString('carthasdata','no');
return count=0;
}
}
return count;
}
this is my api function mean it will always return success true,,,because i have used the count method,please help,,,my app run smoothly but suddenly stop working,even hang my mobile ,so i have to reboot then it will work,,,
public function countcart(Request $request){
$identifier=$request->identifier;
$coutcart=Restcart::where('identifier',$identifier)->count();
return Response::json(array(
'coutcart' => $coutcart,
'success' => true,
));
}

How to extract entities in text prompt using bot framework sdk for node.js?

I'm developing a bot using the bot framework for node.js v4. Imagine the following scenario:
user: Hello
bot: How can I help you?
user: What is the deadline for completing the transfer?
bot: What is the value of the transfer?
user: $ 5,000
At this time, I am executing the textprompt to request the value of the transfer and I need to validate if the user entity ($ 5,000) has been identified as the money entity.
This is the dialog stack:
this.addDialog(new WaterfallDialog(DUVIDA_NIVEL_APROVACAO_DIALOG, [
this.initializeStateStep.bind(this),
this.moneyStep.bind(this),
this.captureMoney.bind(this),
this.endConversation.bind(this)
]));
this.addDialog(new TextPrompt(MONEY_PROMPT, this.validateMoneyInput));
And the validate method:
async validateMoneyInput(validatorContext) {
const value = validatorContext.recognized.value; //how to get entities?
if (value == 'money') {
return VALIDATION_SUCCEEDED;
} else {
await validatorContext.context.sendActivity(`What is the value of the transfer?`);
return VALIDATION_FAILED;
}
}
However, in the callback to validate the textprompt, I have only the text sent by the user.
How can I get the entities extracted by Luis within the textprompt validation method?
To get any LUIS results into the dialog waterfall, you first need to capture the results on the turnContext, like so:
if (turnContext.activity.type === ActivityTypes.Message) {
// Returns LUIS matched results
const results = await this.luisRecognizer.recognize(turnContext);
// Results are assigned to the turnContext object and is passed into the dialog stack
turnContext.topIntent = results.luisResult.topScoringIntent;
turnContext.topIntent.entities = results.luisResult.entities;
turnContext.topIntent.value = results.luisResult.query;
// Create a dialog context object.
const dc = await this.dialogs.createContext(turnContext);
const utterance = (turnContext.activity.text || '').trim().toLowerCase();
if (utterance === 'cancel') {
if (dc.activeDialog) {
await dc.cancelAllDialogs();
await dc.context.sendActivity(`Ok... canceled.`);
} else {
await dc.context.sendActivity(`Nothing to cancel.`);
}
}
// If the bot has not yet responded, continue processing the current dialog.
await dc.continueDialog();
// Start the sample dialog in response to any other input.
if (!turnContext.responded) {
await dc.beginDialog(DUVIDA_NIVEL_APROVACAO_DIALOG);
}
}
Now that the results have been passed in, you can access the results via the step.context object, like so:
this.dialogs.add(new TextPrompt(MONEY_PROMPT, this.validateMoneyInput.bind(this)));
async moneyStep(step) {
await step.prompt(MONEY_PROMPT, `What is the value of the transfer?`,
{
retryPrompt: 'Try again. What is the value of the transfer?'
}
);
}
async validateMoneyInput(step) {
// LUIS results passed into turnContext are retrieved
const intent = step.context.topIntent['intent'];
const entity = step.context.topIntent.entities;
console.log(entity);
// Validation based on matched intent
if (intent == 'Money') {
return await step.context.sendActivity('Validation succeeded');
} else if (intent != 'Money') {
return await step.context.sendActivity('Validation failed');
}
}
I also assigned the entities value to a variable for accessing since you were asking about it.
Hope of help!

Invalid Response Error with Alexa SDK v2

For 2 days now, I have the issue that my lambda function using the ask-sdk-core v2.0.2 returns invalid responses.
A very simple setup:
HelloIntent is handled by HelloIntentHandler:
const HelloIntentHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'HelloIntent';
},
handle(handlerInput) {
const speechText = 'Hello back';
return handlerInput.responseBuilder
.speak(speechText)
.reprompt(speechText)
.getResponse();
}
};
When I call this intent, the simulator goes straight to:
There was a problem with the requested skill's response
Using the ErrorHandler, I checked and the results of handlerInput.requestEnvelope.request.error are:
{ type: 'INVALID_RESPONSE',
message: 'An exception occurred while dispatching the request to the skill.' }
Question: What is the problem here? When I open the skill using the invocation name, the LaunchRequestHandler gets called and responds properly, but any other intent does not work.
Okay I found the problem, it is sort of difficult to deduct from the above error:
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'IntentRequest'
&& handlerInput.requestEnvelope.request.intent.name === 'HelloIntent';
},
In the canHandle function, you need to check for the request type and intent name.

How to properly throw and handle errors in promises in Sails.js?

I'm starting to convert my callback code to promises in Sails.js, but I don't understand how I can raise custom errors and handle them in the promise chain. Sails.js uses Q as its promise library.
User.findOne({email: req.param('professorEmail'), role: 'professor'})
.then(function (user) {
if (user) {
return Course.create({
user_id: user.id,
section: req.param('section'),
session: req.param('session'),
course_code: req.param('course_code')
});
} else {
// At this point `user` is undefined which means that no professor was found so I want to throw an error.
// Right now the following statement does throw the error, but it crashes the server.
throw new Error('That professor does not exist.');
// I want to be able to handle the error in the .fail() or something similar in the promise chain.
}
}).then(function (createSuccess) {
console.log(createSuccess);
}).fail(function (err) {
console.log(err);
});
Right now the .fail() is never called because the thrown error crashes the server.
Use .catch() instead of .fail().
Waterline's claim complete Q promise object after the first then seems untrue by your test. I've verified it myself as well and found a workaround.
You can do this :
var Q = require('q');
[...]
Q(User.findOne({email: req.param('professorEmail'), role: 'professor'}))
.then(function (user) {
if (user) {
return Course.create({
user_id: user.id,
section: req.param('section'),
session: req.param('session'),
course_code: req.param('course_code')
});
} else {
// At this point `user` is undefined which means that no professor was found so I want to throw an error.
// Right now the following statement does throw the error, but it crashes the server.
throw new Error('That professor does not exist.');
// I want to be able to handle the error in the .fail() or something similar in the promise chain.
}
}).then(function (createSuccess) {
console.log(createSuccess);
}).fail(function (err) {
console.log(err);
});
This will return a true Q promise.

Resources