From e86552f01acf6be9b35364dec428d04fa71707d3 Mon Sep 17 00:00:00 2001 From: Niran Babalola Date: Thu, 30 Apr 2015 04:15:48 -0500 Subject: [PATCH] Use async contract calls when a callback is passed --- lib/web3/function.js | 52 +++++++++++++++++++++++++++++++++----------- 1 file changed, 39 insertions(+), 13 deletions(-) diff --git a/lib/web3/function.js b/lib/web3/function.js index 2bbb684..41ec19e 100644 --- a/lib/web3/function.js +++ b/lib/web3/function.js @@ -14,7 +14,7 @@ You should have received a copy of the GNU Lesser General Public License along with ethereum.js. If not, see . */ -/** +/** * @file function.js * @author Marek Kotewicz * @date 2015 @@ -67,21 +67,47 @@ SolidityFunction.prototype.signature = function () { return web3.sha3(web3.fromAscii(this._name)).slice(2, 10); }; -/** - * Should be used to call function - * - * @method call - * @param {Object} options - * @return {String} output bytes - */ -SolidityFunction.prototype.call = function () { - var payload = this.toPayload.apply(this, Array.prototype.slice.call(arguments)); - var output = web3.eth.call(payload); + +SolidityFunction.prototype.unpackOutput = function (output) { + if (output == null) { + return; + } + output = output.length >= 2 ? output.slice(2) : output; var result = coder.decodeParams(this._outputTypes, output); return result.length === 1 ? result[0] : result; }; +/** + * Calls a contract function. + * + * @method call + * @param {...Object} Contract function arguments + * @param {function} If the last argument is a function, the contract function + * call will be asynchronous, and the callback will be passed the + * error and result. + * @return {String} output bytes + */ +SolidityFunction.prototype.call = function () { + var this_ = this; + var args = Array.prototype.slice.call(arguments); + var callback; + if (typeof(args[args.length - 1]) === 'function') { + callback = args.pop(); + } + + var payload = this.toPayload.apply(this, args); + + if (typeof(callback) === 'undefined') { + var output = web3.eth.call(payload, callback); + return this.unpackOutput(output); + } else { + web3.eth.call(payload, function (error, output) { + callback(error, this_.unpackOutput(output)); + }); + } +}; + /** * Should be used to sendTransaction to solidity function * @@ -105,7 +131,7 @@ SolidityFunction.prototype.displayName = function () { /** * Should be used to get function type name - * + * * @method typeName * @return {String} type name of the function */ @@ -120,7 +146,7 @@ SolidityFunction.prototype.typeName = function () { */ SolidityFunction.prototype.execute = function () { var transaction = !this._constant; - + // send transaction if (transaction) { return this.sendTransaction.apply(this, Array.prototype.slice.call(arguments));