tronweb : how to get return value using tronweb contract send function - return-value

let contract = await window.tronWeb.contract().at(config.contract);
let result = await contract.methods.depositTron()
.send({callValue:amount*1000000})
.then(output=>transaction = output);
console.log("result", result);
I tried to get the result of depositTron method, but returned hash value.
how should I do?
please help me.

Functions invoked by transactions only return value within the EVM (usually when called from another contract).
The hash returned from the send() JS function, is the transaction hash.
You can workaround this by emitting an event log within the contract. Then you can get the value or read emitted logs from the transaction receipt (emitted in JS after the transaction is mined).
Solidity:
contract MyContract {
event Deposit(uint256 indexed amount);
function depositTron() external payable {
emit Deposit(msg.value);
}
}
JS:
contract.methods.depositTron().send({callValue:amount*1000000})
.on('receipt', (receipt) => {
console.log(receipt.logs);
})

Related

How to sequentially send requests to the server?

I have a List, and I need to send each element of this List to the server sequentially. And if the answer is with an error, then do not continue sending, but display an error. I am trying to use
await Future.wait([]);
but I do not quite understand how to complete the send on failure, and how to iterate over the elements.
To iterate over elements through .forEach(element) {}
The compiler throws an error: The argument type 'List' can't be assigned to the parameter type 'Iterable<Future>'
Here is what I am trying to do:
await Future.wait([
state.revisionFill.forEach((element) {
var successOrFail = await ContainerExpire.call(ContainerExpireParams(token: token, entity: element.entity));
})
]);
I'm new and don't fully understand async/sync requests in flutter. Tell me which direction to study.
How to complete the next send if it fails?
This seems to be what you're looking for:
for (var element in state.revisionFill) {
var successOrFail = await ContainerExpire.call(ContainerExpireParams(token: token, entity: element.entity));
if (successOrFail.hasFailed()) {
//add code for some possible error handling
break;
}
}
I am assuming that based on the value of successOrFail you can tell whether or not an error occured. Basically after each request you check for the status, and break on an error. You can add logic for displaying your error message.

Cloud function http function fails on first run

I am testing with a payment processing system and every time a transaction is completed, the payment processor should hit my endpoint with a POST request with payment details so I can save it to my database (Firestore).
Only thing is the function fails on the first try. What I mean is, say a customer pays, the payment processor hits my cloud function, it fails to save to my database. When a second customer makes the transaction a minute, 5 minutes or even 18 minutes later according to my observation, everything works as expected.
Am I facing a cold start problem or what is happening. And how do I solve this.
Here is my function
exports.stkCallback = functions.https.onRequest(async (request, response) => {
if (request.method === 'POST') {
if (request.body.Body.stkCallback.ResultCode === 0) {
const jsonData = request.body.Body.CallbackMetadata;
console.log("USER HAS COMPLETED THE TRANSACTION");
var transactionID;
///This below line logs successfully everytime meaning my payment processor has sent the POST
/// request
console.log("checkoutid:", request.body.Body.CheckoutRequestID)
///I have saved the CheckoutRequestID previously to Firestore so I first query the document
//// with that ID (CheckoutRequestID) and get its data so I can update the transaction as
//// complete
var docRef=db.collection("Transactions").doc(request.body.Body.CheckoutRequestID);
await docRef.get().then((doc) =>{
// eslint-disable-next-line promise/always-return
if (doc.exists) {
//console.log("Document data:", doc.data());
transactionID=doc.id;
transactionData.push(doc.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch((error)=> {
console.log("Error getting document:", error);
});
///Once I get the data I can then go ahead and do other operations.
///Only the above query fails the first time which I don't know why
///By failing Saying No such Document. Which the document does exist
***carrying out other operations using the fetched transactionID and transactionData***
response.sendStatus(200);
} else {
console.log("USER HAS CANCELLED THE TRANSACTION");
response.sendStatus(200);
}
I have refactored my code and reproduced it to the below
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
exports.stkCallback = functions.https.onRequest(async (request, response) => {
const accountSid = "#";
const authToken = "#";
const client = require("twilio")(accountSid, authToken);
if (request.method === 'POST') {
if (request.body.Body.ResultCode === 0) {
const jsonData = request.body.Body.CallbackMetadata;
console.log("USER HAS COMPLETED THE TRANSACTION");
var transactionID;
///This below line logs successfully everytime meaning my
/////payment processor has sent the POST request
console.log("checkoutid:",
request.body.Body.CheckoutRequestID)
////The below function is critical to all the other below functions below it as
///it supplies the necessary data all the way down
///It is also the function that fails on the first run
var docRef= await db.collection("Transactions").doc(request.body.Body.CheckoutRequestID).get()
.catch((error)=> {
console.log("Error getting document:", error);
});
//// a log of some data from the above function
//// when it fails, the below log is undefined,
console.log("tyyy",docRef.data().Home)
transactionID=docRef.id;
////the data returned from above function is used to perform other operations.
////Below is just one of them
////consequently, it will fail as some values like doc.data().Uid will be ////undefined
await db.collection("Users").doc(doc.data().Uid).collection("Transactions").doc(transactionID).update({
TransactionComplete: true,
transactionCompletedTimeDb: admin.firestore.FieldValue.serverTimestamp(),
Amount: jsonData.Item[0].Value,
ReceiptNO: jsonData.Item[1].Value,
TransactionDate: jsonData.Item[3].Value,
PhoneNumber: jsonData.Item[4].Value,
UserId: doc.data().Uid
})
// eslint-disable-next-line promise/always-return
.catch((error)=> {
// The document probably doesn't exist.
console.error("Error updating document: ", error);
});
response.sendStatus(200);
} else {
console.log("USER HAS CANCELLED THE TRANSACTION");
response.sendStatus(200);
}
});
Attaching an image of a failed function, do note the time
An image of logs of the same triggered function right after (3 minutes later). As you can see the function completes successfully
This seems like a Cold Start Issue
The mitigation of this issue will depend on many information that you are not sharing with us like the complete function, dependencies that you are using, and instance size.
Spreading a loaded function into multiple small functions will help with the cold start time, also using smaller, updated, and cloud oriented libraries will also help.
Also, the size of the payload could be an important factor here, how big is the size of the payload sent to the function and how big is the size of the info that you are writing into the logs? All these small pieces have an important influence on the performance of a cold start.
As a quick solution for your Issue, I can safely say that creating a Scheduled task that triggers your functions every 30 minutes, for example, would be enough to mitigate your issue in the short term.

actions on google--unable to use app.tell to give response from JSON

I am trying to get my webhook to return a parsed JSON response from an API. I can log it on the console, but when I try to use app.tell; it gives me: TypeError: Cannot read property 'tell' of undefined. I am basically able to successfully get the data from the API, but I'm not able to use it in a response for some reason. Thanks for the help!
[Actions.API_TRY] () {
var request = http.get(url2, function (response) {
// data is streamed in chunks from the server
// so we have to handle the "data" event
var buffer = "",
data,
route;
response.on("data", function (chunk) {
buffer += chunk;
});
response.on("end", function (err) {
// finished transferring data
// dump the raw data
console.log(buffer);
console.log("\n");
data = JSON.parse(buffer);
route = data.routes[0];
// extract the distance and time
console.log("Walking Distance: " + route.legs[0].distance.text);
console.log("Time: " + route.legs[0].duration.text);
this.app.tell(route.legs[0].distance.text);
});
});
}
This looks to me to be more of a JavaScript scoping issue than anything else. The error message is telling you that app is undefined. Often in Actions, you find code like yours embedded in a function which is defined inside the intent handler which is passed the instance of your Actions app (SDK or Dialog Flow).

Bluebird Promise each in mocha/chai test not working

I would like some help to determine why my unit test in a sails.js app is not working as expected.
I am using mocha, chai and bluebird promise library on a sails.js app.
What I want to achieve:
Create a test for TagsService.create(name) method, which accepts a name
parameter.
Test that this method will not create a new tag record based on invalid names I pass
The name parameter is required and should be less than 121 characters long
What I currently have:
// Test the 'create' method
describe('Method \'create\' test result: \n', function () {
// Test that name is required and less than 121 chars long
it('Must receive the name parameter and be less than 121 chars long', function(done) {
// It should not accept any of the following names
var names = ['',' ','thisstringislongerthanthemaxof121characterslongthisstringislongerthanthemaxof121characterslongthisstringislongerthanthema',[],[{}],[{test: 'test'}],'wrongchars*[]$£%fsf','$%#~}[','£$%jkdfi',' $%"£asdwdFDE','hD8U £$&{DS ds'];
sails.bluebird.each(names,function(name){
TagsService.create(name).then(function(data){
assert.propertyVal(data,'status','err','An error was NOT returned - even though names provided should be invalid');
});
}).then(function(){
done();
});
});
});
What happens is it seems to pass, even if I pass in a valid name or return null from the method.
Well, looks like I managed to solve it, after much trial and error.
Turns out I need to catch the done() callback from the Promise after the each method executed. Also needed to return the result of the tests done from the TagsService promise object. (Still not 100% sure this is the correct way to think about it..). Anyway the test seems to function properly now.
Here is my result:
var names = ['',' ','thisstringislongerthanthemaxof121characterslongthisstringislongerthanthemaxof121characterslongthisstringislongerthanthema',[],[{}],[{test: 'test'}],'wrongchars*[]$%fsf','$%#~}[','�$%jkdfi',' $%"�asdwdFDE','hD8U �$&{DS ds'];
sails.bluebird.each(names, function(name){
return TagsService.create(name).then(function(data) {
assert.property(data, 'status', 'create method did not return a status property');
assert(data.status === 'err', 'even with an invalid name parameter passed - it did not return an err status, which it must do with an invalid name.');
});
}).then(function(){
done();
}).catch(done);

Get a server method result before executing a Collection transform

Working on CoinsManager, I have a model directory with a class per file, and I want to read and list all those files in my collection transform method, to initialize my doc with the correct class.
server/methods.coffee:
Meteor.methods
implemented_coins: ->
"""
Returns a list of coins that have been implemented
"""
files = fs.readdirSync './app/models/cryptos/'
file.replace(".coffee.js", "") for file in files.filter (file) ->
file.search("(base_crypto*)|(js.map)") == -1
collections/addresses.coffee:
if Meteor.isReady
#implementedCoins = Meteor.call "implemented_coins"
#Addresses = new Meteor.Collection "addresses",
transform: (doc) ->
# Retrieve class from code, and pass it the address
if doc.code in #implementedCoins
new #[doc.code] doc.address
else doc
client/views/addresses/addresses_list.coffee
Template.userAddresses.helpers
userAddresses: ->
addresses = Addresses.find
userId: Meteor.user()._id
address.set_balance() for address in addresses
return addresses
Right now, I'm getting the following error on the client console:
Exception from Deps recompute: TypeError: Array.prototype.indexOf called on null or undefined
at indexOf (native)
at Addresses.Meteor.Collection.transform
Which means that in my collection transform, the #implementedCoins variable is undefined, because I didn't implement it correctly.
Any idea how to solve this problem ?
I'm pretty sure that this is wrong:
if Meteor.isReady
#implementedCoins = Meteor.call "implemented_coins"
I don't think there is a field in Meteor with that name, and even if it was, then it would get executed on startup, but at that time isReady is probably false and so your variable doesn't get set. Did you mean Meteor.startup? Secondly, on the client you need to use a callback for call, since there are no fibers on the client.
Would this work instead?
Meteor.startup(function () {
Meteor.call("implemented_coins", function(err, res) {
implementedCoins = res;
});
});