One call to contract function generates multiple transactions - web3js

I am adding functionality to the Truffle Pet Shop example dApp. I have created a returnPet function in the solidity contract, and have tested it via console and test contracts. I would now like to call it in my JS app.
The problem is, when I call it, the handleReturn() function,
handleReturn: function(event) {
event.preventDefault();
var petId = parseInt($(event.target).data('id'));
var adoptionInstance;
web3.eth.getAccounts(function(error, accounts) {
if (error) {
console.log(error);
}
var account = accounts[0];
App.contracts.Adoption.deployed().then(function(instance) {
adoptionInstance = instance;
return adoptionInstance.returnPet(petId);
}).then(function(result) {
return App.markAdopted();
}).catch(function(err) {
console.log(err.message);
});
});
generates multiple transactions, and does not affect the blockchain (a different problem. If you have answers to this, I would love to hear them.). As far as I can tell, handleReturn() only gets called once, so why is it generating multiple transactions?

This should work:
handleReturn: function(event) {
event.preventDefault();
var petId = parseInt($(event.target).data('id'));
var adoptionInstance;
web3.eth.getAccounts(function(error, accounts) {
if (error) {
console.log(error);
}
var account = accounts[0];
});
App.contracts.Adoption.deployed().then(function(instance) {
adoptionInstance = instance;
})
adoptionInstance.returnPet(petId).then(function(result) {
return App.markAdopted();
}).catch(function(err) {
console.log(err.message);
});
It calling multiple transactions because you are calling it under the web3.eth.getAccounts methods,if it doesn't work call your contract methods/fuctions using truffle by importing your contracrt artifacts and use webpack to bundle it

Related

Calling $http.delete but nothing happens

I'm actually working on a webclient calling a REST service.
After my last question, the GET request is working now.
Now i want o implement a DEL request using angulars delete method.
In the following example is my service request implemented.
function ItemsService($http) {
this.$http = $http;
}
ItemsService.prototype = {
deleteFoo: function (id) {
this.$http.delete('http://localhost:3001/posts/' + id)
.then(function successCallback(response) {
console.log("DEL send...");
console.log(response.data);
}, function errorCallback(response) {
console.log('Error');
});
}
}
module.exports = {
ItemsService: ItemsService
}
I added a button on the webpage with ng-click="$ctrl.deleteMe()".
The controller looks like the following example:
function Foo(ItemsService) {
this.itemsService = ItemsService;
}
Foo.prototype = {
deleteMe: function () {
console.log('delete now');
this.itemsService.deleteFoo(1).then(
response => {
console.log('gelöscht? ' + response);
}
);
}
};
If i now click on the button, nothing happens. In the network trace log in the dev tools in the browser i can't see a DEL request.
To test this REST service request, i run the JSON Server tool on port 3001.
I testet the availability of the server with SOAPUI, it works, i see all the requests in the console.
But no request from my test webpage.
Can anyone help me?
You need to return
return this.$http.delete('http://localhost:3001/posts/' + id)
.then(function successCallback(response) {
console.log("DEL send...");
console.log(response.data);
}, function errorCallback(response) {
console.log('Error');
});

Handle connection losses: reperform request or resend response

Using angular-sails the sailsjs backend is usually called this way:
this.doSomethingWithItem = function(itemID, callback){
$sails.put('/item/doSomething', {itemID:itemID}).
success(function (data, status, headers, config) {
callback(data);
}).
error(function (data, status, headers, config){
alert('Error!');
});
};
In the backend, most of the Sails (v0.11.0) Controller functions are rather simple. An example might look like such:
doSomething: function(req, res) {
var p = req.params.all();
postgresClientPool.connect(function(err, client, done) {
client.query("SELECT item_do_something_in_this_awesome_function($1) AS dbreturn", [p.itemID], function(err, result) {
done();
if(err) {
res.status(500).json({success: false});
}
else {
res.json(result.rows[0].dbreturn[0]);
}
});
});
}
Now for reasons we can't influence we're experiencing quite frequent but rather short connection losses (between Client/Browser and nodeJS/sails-Server). The task is now to handle them as smooth for the user as possible and avoid any further inconvenience.
So, if during an ongoing request the connection is interrupted, the logic has to be something like:
Check if the connection interruption happened before or after the request reached the server.
If it happened before: re-perform the request.
If it happened afterwards: tell the backend to re-send the result of the request.
Now, how to achieve that?
I don't know if registering a $sails.on('disconnect'... in each service function is the best idea. And anyway, I haven't figured out yet how the de-register them after the function finished executing.
First of all, I would recommend you to separate your business logic out of the controller.
You can check this other answer: sails.js access controller method from controller method
By doing so, you would be able to actually make the call again from the controller, without having to do much.
Also, we will use the async.retry and async.apply functions from the async module.
For example, imagine you move your code to a service in api/services/CustomerService.js ex:
module.exports = {
get: function (customerId, done) {
// postgresClientPool should be available in a param or globally?
// I'd prefer assigning it to the sails object...
// and use it like sails.postgresClientPool
postgresClientPool.connect(function (err, client, release) {
if (err) {
release();
done(err);
}
client.query("SELECT getCustomer($1) AS dbreturn", [customerId],
function (err, result) {
release();
if (err) {
done(err);
} else {
done(undefined, result.rows[0].dbreturn[0]);
}
});
});
}
};
Then, in your controller, for example, api/controllers/Customer.js:
get: function (req, res) {
var p = req.params.all();
async.retry(3, async.apply(CustomerService.get, p.customerID), function (err, result) {
if (err) {
res.status(500).json({
success: false
});
} else {
res.json(result);
}
})
}
You should require async in the top of your controller.

AngularJS - MeanJS articles update, blink and reloads on socket emit

I am using github repo by #mleanos for MeanJS using Socket for article create and update, it uses socket to create and update articles in realtime, while updating article, the data reloads, as in, the list of articles blinks off and comes again. this happens only while updating the article. While creating, it creates new article seamlessly. how do i update the article without the data blinking on and off.
Follow this link for the github repo.
Socket Article server controller
socket.on('orderCreate', function (order) {
var user = socket.request.user;
order = new Order(order);
order.user = user;
order.save(function (err) {
if (err) {
// Emit an error response event
io.emit('orderCreateError', { data: order, message: errorHandler.getErrorMessage(err) });
} else {
// Emit a success response event
io.emit('orderCreateSuccess', { data: order, message: 'Order created' });
}
});
});
// Update an Order, and then emit the response back to all connected clients.
socket.on('orderUpdate', function (data) {
var user = socket.request.user;
// Find the Order to update
Order.findById(data._id).populate('user', 'displayName').exec(function (err, order) {
if (err) {
// Emit an error response event
io.emit('orderUpdateError', { data: data, message: errorHandler.getErrorMessage(err) });
} else if (!order) {
// Emit an error response event
io.emit('orderUpdateError', { data: data, message: 'No order with that identifier has been found' });
} else {
order.name = data.name;
order.save(function (err) {
if (err) {
// Emit an error response event
io.emit('orderUpdateError', { data: data, message: errorHandler.getErrorMessage(err) });
} else {
// Emit a success response event
io.emit('orderUpdateSuccess', { data: order, updatedBy: user.displayName, updatedAt: new Date(Date.now()).toLocaleString(), message: 'Updated' });
}
});
}
});
});
Socket Client Controller
function saveUsingSocketEventsUpdate(isValid) {
vm.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'orderForm');
return false;
}
var order = vm.order;
// we can send the user back to the orders list already
// TODO: move create/update logic to service
if (vm.order._id) {
vm.order.$update(successCallback, errorCallback);
} else {
vm.order.$save(successCallback, errorCallback);
}
function successCallback(res) {
$state.go('orders.view', {
orderId: res._id
});
}
function errorCallback(res) {
vm.error = res.data.message;
}
// wait to send create request so we can create a smooth transition
$timeout(function () {
// TODO: move create/update logic to service
if (vm.order._id) {
Socket.emit('orderUpdate', vm.order);
} else {
Socket.emit('orderCreate', vm.order);
}
}, 2000);
}
I provided an answer in the MEANJS issue that was created for this. Since I'm the contributor that provided the branch that was used as a basis for this implementation.
The cause of the issue was that the entire list was being reloaded when any Order was updated. The solution was to update the Order that already existed in the list.
Side note: I suggested that if the Order wasn't found to get it from the server & add it to the list. This may or may not be the desired behavior. This would depend on the needs of the application.

MobileFirst: Adapter Authentication calls Submit success repeatedly in Angular App

Environment:
MFPF v7.0
Eclipse: Luna SR.2 (4.4.2)
Windows 7
I face an strange issue. I am using adapter based authentication in one of my Angular based project.
The app authenticates well, but it repeatedly calls the submitSuccess.
I guess, it has something with the way Angular works, either I should use Challenge Handler as a Service or Controller. Because the way MobileFirst detects & handle instances of a/any handler objects. And that cause reference mis-match to dispose off or execute the relevant functions at appropriate time.
Currently I use it as a service.
Below is the challenge handler that I use.
define(['angular'], function(angular){
var loginChallengeHandler = angular.module('webApp.loginChallengeHandler', [])
.service('loginChallengeHandler', function(){
var _this = this;
_this.AuthRealmChallengeHandler = WL.Client.createChallengeHandler("AdapterAuthRealm");
_this.AuthRealmChallengeHandler.isCustomResponse = function(response) {
console.error("AuthRealmChallengeHandler.isCustomResponse:: " , response);
if (!response || !response.responseJSON || response.responseText === null) {
return false;
}
if (typeof(response.responseJSON.authRequired) !== 'undefined' || response.responseJSON.authRequired == true){
return true;
} else {
return false;
}
};
_this.AuthRealmChallengeHandler.handleChallenge = function(response){
console.error("AuthRealmChallengeHandler.handleChallenge:: " , response);
var authRequired = response.responseJSON.authRequired;
if (authRequired == true){
console.error("------Auth Required----- ");
_authenticationFailed(response);
} else if (authRequired == false){
console.error("------Auth PASSED ----- ");
//Now tell WL Authentication that user has been verified successfully so that it finishes the authentication process
_this.AuthRealmChallengeHandler.submitSuccess();
console.error("------ submitSuccess ----- ");
}
};
_this.AuthRealmChallengeHandler.userLogin = function(dataObjRef) {
var loginStatePromise = $q.defer();
_this.AuthRealmChallengeHandler.submitAdapterAuthentication(options,{
onFailure: function (error) {
loginStatePromise.resolve({ state:false , val: "" });
console.log("submitAdapterAuthentication Failed called ", error);
},
onSuccess: function(response) {
console.log("-> submitAdapterAuthentication onSuccess called " , response);
loginStatePromise.resolve({ state: _state , val: _msg });
},
timeout: 30000
});
return loginStatePromise.promise;
};
_this.AuthRealmChallengeHandler.logout = function (){
var userLogoutPromise = $q.defer();
WL.Client.logout("AdapterAuthRealm",{
onSuccess: function(){
console.log("onSuccess");
userLogoutPromise.resolve(true);
},
onFailure: function(){
console.log("onFailure");
userLogoutPromise.resolve(false);
},
timeout: 30000
});
return userLogoutPromise.promise;
};
var _authenticationFailed = function(response){
console.error("_authenticationFailed:: " , response);
//register failure request
_this.AuthRealmChallengeHandler.submitFailure();
};
});
return loginChallengeHandler;
});
I have also tried to bind the handler object with window object, so that it can access the handler's instance methods correctly.
Like:
window.AuthRealmChallengeHandler = WL.Client.createChallengeHandler("AdapterAuthRealm");
window.AuthRealmChallengeHandler.isCustomResponse = function(response) {
.
.
But still same issue.
I solved this issue and here is my solution for anyone facing similar issue in future.
Solution Description (few words)
As per my understanding, the IBM MobileFirst is expecting only one challenge-handler instance (the object that is create via createChallengeHandler function) to exists in the app. So most probably it assumes that the instance would be hooked into the window object.
Now based on this knowledge, we can see that above code is not working even we made instance through service ( i.e. singleton per angular app). Why ? Because, now the handler object becomes accessible via another reference, and this caused issues in resolving the handler references within the WL APIs.
So I just changed a bit of code (hooked it into window) so that WL APIs could reach the correct handler instance and clean-up the requests poll before marking the call successful and dispose off all the cached requests.
One more thing I would suggest.
Create only one handler instance in your client code
Create it as a service or factory - both are singletons in angularjs
Avoid using controllers, because there can be many controller instances within the angular app and it would lead to multiple handler references
And importantly trust IBM MobileFirst :)
Working Challenge Handler as Service
define(['angular'], function(angular){
'use strict';
var loginChallengeHandler = angular.module('webApp.loginChallengeHandler', [])
.service('loginChallengeHandler', function(){
//NOTE:- Below Must be bind with Window Object, otherwise will NOT work as per challenge handlers default behavior
window.AuthRealmChallengeHandler = WL.Client.createChallengeHandler("AdapterAuthRealm");
AuthRealmChallengeHandler.isCustomResponse = function(response) {
if (response && response.responseJSON && typeof (response.responseJSON.authStatus) === "string"){
return true;
} else {
return false;
}
};
AuthRealmChallengeHandler.handleChallenge = function(response){
var authStatus = response.responseJSON.authStatus;
if (authStatus === "failed"){
console.error("------Auth Required----- ");
_authenticationFailed(response);
} else if (authStatus === "passed"){
console.error("------Auth PASSED ----- ");
//do something here like change page etc.
//Now tell WL Authentication that user has been verified successfully so that it finishes the authentication process
AuthRealmChallengeHandler.submitSuccess();
}
};
AuthRealmChallengeHandler.userLogin = function(dataObjRef) {
var loginStatePromise = $q.defer();
AuthRealmChallengeHandler.submitAdapterAuthentication(options,{
onFailure: function (error) {
loginStatePromise.resolve({ state:false , val: "" });
},
onSuccess: function(response) {
loginStatePromise.resolve({ state: _state , val: _msg });
},
timeout: 30000
});
return loginStatePromise.promise;
};
AuthRealmChallengeHandler.logout = function (){
var userLogoutPromise = $q.defer();
WL.Client.logout("AdapterAuthRealm",{
onSuccess: function(){
//$state.go("home.login");
userLogoutPromise.resolve(true);
},
onFailure: function(){
userLogoutPromise.resolve(false);
},
timeout: 30000
});
return userLogoutPromise.promise;
};
var _authenticationFailed = function(response){
//register failure request
AuthRealmChallengeHandler.submitFailure();
};
});//end of service
return loginChallengeHandler;
});
Adapter
function onAuthRequired(headers, errorMessage){
errorMessage = errorMessage ? errorMessage : null;
return {
authStatus: "failed",
errorMessage: errorMessage
};
}
function Login(request){
if(request){
/* IF user credentials are Verified Correctly
* and user is authenticated then create User Identity
* and return success message if it is required by client app.
*/
userIdentity = {
userId: "abc",
displayName: "ABc",
attributes: {}
};
WL.Server.setActiveUser("AdapterAuthRealm", userIdentity);
WL.Logger.error("Auth Successful:");
return {
authStatus: "passed",
submitResponse: "send a Success message in case is required on client-side"
};
}else{
return onAuthRequired(null, "send an error message if required on client side");
}
}
I faced the same issue with adapter based authentication but I was using pure javascript, so no angular. From that I can tell you it's a MobileFirst issue and nothing related to angular.
This might sound contradictory to the documentations but don't call the submitSuccess function, just call your code on successful authentication. It will work fine and authenticate properly.
Also, make sure that you only have the security test set on the specific functions that you use after auth and not on the auth function itself.
Your code seems fine to me but I'm not that good in angular.

$httpBackend return promise value issue

I want to implement a login function using AngularJS and my backend is in Rails. i decided to implement it using the $httpBackend but I have a problem.
When it gets into the $httpBackend function, it does update the token with the latest token from the database but i need to return the value to my services of which that doesnt seem to be happening. I know this has to do with promise and deferred etc but i am not well conversant with those.
SO this is my code
var authorized = false;
var token;
$httpBackend.whenPOST('https://login').respond(function(method, url, data) {
var loginDetails = data;
var d= $q.defer();
function startToken(loginDetails) {
getTokens.newToken(loginDetails).then(function(result) {
if(result.length > 0) {
var updateDB = "UPDATE preferences SET value='"+result[0].token+"' WHERE description='token'";
$cordovaSQLite.execute(db, updateDB).then(function(res) {
var updateDB1 = "UPDATE preferences SET value='true' WHERE description='logged_in'";
$cordovaSQLite.execute(db, updateDB1).then(function(res) {
var query = "SELECT description, value FROM preferences";
$cordovaSQLite.execute(db, query).then(function(res) {
if(res.rows.length > 0) {
if(res.rows.item(3).value!=null || res.rows.item(3).value!='') {
getTokens.getCRMToken(res.rows.item(2).value).then(function(resulttoken){
if(resulttoken[0].token == res.rows.item(3).value) {
token = res.rows.item(3).value;
}
d.resolve(token)
});
}
} else {
console.log("No results found");
}
}, function (err) {
console.error(err);
});
}, function (err) {
console.error(err);
});
}, function (err) {
console.error(err);
});
}
else {
console.log("reject")
d.reject(result);
}
}, 1000);
return d.promise;
}
var a = startToken(loginDetails).then(function(token) {
// in here the value for token is correct i then go ahead to set the value for authorized and resolve it
console.log(token)
if(token.length > 0){
console.log("authorized true")
authorized = true;
d.resolve(token, authorized)
}
else
{
console.log("authorized false")
authorized = false;
d.reject(token, authorized)
}
return d.promise;
})
// this is where i have my issue. all i want to do is to just check if the value for authorized is true, if yes, return the value for token.
//authorized = true;
//return [200 , { authorizationToken: token }];
});
Complete rewrite
Sadly, I think the short answer is that you cannot use promises with $httpBackend. See this discussion: https://github.com/angular/angular.js/issues/11245
In my original answer, I didn't recognize that you were using the $httpBackend mock as I merely concentrated on your incorrect promise code. The information on promises (https://docs.angularjs.org/api/ng/service/$q) is still valid.
The unit test version of ngMock does not handle promises. If you are using a version of $httpBackend which can handle promises, you need to return the promise, not the [200, "status"].
However, that said, in your rewrite, you also reuse the same promise after it has been resolved which is incorrect. You can only resolve or reject a defer once. So you need to either chain your then() functions or create a new defer. Also, you didn't actually need to create a defer since the newToken() function actually returns a promise.

Resources