Code coverage report for web3/lib/web3/contract.js

Statements: 59.6% (59 / 99)      Branches: 23.81% (10 / 42)      Functions: 77.27% (17 / 22)      Lines: 59.6% (59 / 99)      Ignored: none     

All files » web3/lib/web3/ » contract.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296                                            1 1 1 1                 1 1 1   1 1     1                     1 26 91   68   68                     1 26 91     26 26   26 22 22                         1                                                                                                                                         1 27 27   27                                               1 1     1 1   1 1 1     1 1 1     1 1   1     1 1       1     1                       1                       1 26       26 26   26     26               1                                           1 27 27 27 27     1    
/*
    This file is part of web3.js.
 
    web3.js is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
 
    web3.js is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.
 
    You should have received a copy of the GNU Lesser General Public License
    along with web3.js.  If not, see <http://www.gnu.org/licenses/>.
*/
/** 
 * @file contract.js
 * @author Marek Kotewicz <marek@ethdev.com>
 * @date 2014
 */
 
var utils = require('../utils/utils');
var coder = require('../solidity/coder');
var ContractEvent = require('./event');
var SolidityFunction = require('./function');
 
/**
 * Should be called to encode constructor params
 *
 * @method encodeConstructorParams
 * @param {Array} abi
 * @param {Array} constructor params
 */
var encodeConstructorParams = function (abi, params) {
    return abi.filter(function (json) {
        return json.type === 'constructor' && json.inputs.length === params.length;
    }).map(function (json) {
        return json.inputs.map(function (input) {
            return input.type;
        });
    }).map(function (types) {
        return coder.encodeParams(types, params);
    })[0] || '';
};
 
/**
 * Should be called to add functions to contract object
 *
 * @method addFunctionsToContract
 * @param {Contract} contract
 * @param {Array} abi
 */
var addFunctionsToContract = function (contract) {
    contract.abi.filter(function (json) {
        return json.type === 'function';
    }).map(function (json) {
        return new SolidityFunction(contract._eth, json, contract.address);
    }).forEach(function (f) {
        f.attachToContract(contract);
    });
};
 
/**
 * Should be called to add events to contract object
 *
 * @method addEventsToContract
 * @param {Contract} contract
 * @param {Array} abi
 */
var addEventsToContract = function (contract) {
    var events = contract.abi.filter(function (json) {
        return json.type === 'event';
    });
 
    var allEvents = new ContractEvent(contract._eth._requestManager, events, contract.address, true);
    allEvents.attachToContract(contract);
    
    events.map(function (json) {
        var ev = new ContractEvent(contract._eth._requestManager, json, contract.address);
        ev.attachToContract(contract);
    });
};
 
 
/**
 * Should be called to check if the contract gets properly deployed on the blockchain.
 *
 * @method checkForContractAddress
 * @param {Object} contract
 * @param {Function} callback
 * @returns {Undefined}
 */
var checkForContractAddress = function(contract, callback){
    var count = 0,
        callbackFired = false;
 
    // wait for receipt
    var filter = contract._eth.filter('latest', function(e){
        if (!e && !callbackFired) {
            count++;
 
            // stop watching after 50 blocks (timeout)
            if (count > 50) {
                
                filter.stopWatching();
                callbackFired = true;
 
                if (callback)
                    callback(new Error('Contract transaction couldn\'t be found after 50 blocks'));
                else
                    throw new Error('Contract transaction couldn\'t be found after 50 blocks');
 
 
            } else {
 
                contract._eth.getTransactionReceipt(contract.transactionHash, function(e, receipt){
                    if(receipt && !callbackFired) {
 
                        contract._eth.getCode(receipt.contractAddress, function(e, code){
                            /*jshint maxcomplexity: 6 */
 
                            if(callbackFired || !code)
                                return;
                            
                            filter.stopWatching();
                            callbackFired = true;
 
                            if(code.length > 2) {
 
                                // console.log('Contract code deployed!');
 
                                contract.address = receipt.contractAddress;
 
                                // attach events and methods again after we have
                                addFunctionsToContract(contract);
                                addEventsToContract(contract);
 
                                // call callback for the second time
                                if(callback)
                                    callback(null, contract);
 
                            } else {
                                if(callback)
                                    callback(new Error('The contract code couldn\'t be stored, please check your gas amount.'));
                                else
                                    throw new Error('The contract code couldn\'t be stored, please check your gas amount.');
                            }
                        });
                    }
                });
            }
        }
    });
};
 
/**
 * Should be called to create new ContractFactory instance
 *
 * @method ContractFactory
 * @param {Array} abi
 */
var ContractFactory = function (eth, abi) {
    this.eth = eth;
    this.abi = abi;
 
    this.new.getData = this.getData.bind(this);
};
 
/**
 * Should be called to create new ContractFactory
 *
 * @method contract
 * @param {Array} abi
 * @returns {ContractFactory} new contract factory
 */
//var contract = function (abi) {
    //return new ContractFactory(abi);
//};
 
/**
 * Should be called to create new contract on a blockchain
 * 
 * @method new
 * @param {Any} contract constructor param1 (optional)
 * @param {Any} contract constructor param2 (optional)
 * @param {Object} contract transaction object (required)
 * @param {Function} callback
 * @returns {Contract} returns contract instance
 */
ContractFactory.prototype.new = function () {
    var contract = new Contract(this.eth, this.abi);
 
    // parse arguments
    var options = {}; // required!
    var callback;
 
    var args = Array.prototype.slice.call(arguments);
    Eif (utils.isFunction(args[args.length - 1])) {
        callback = args.pop();
    }
 
    var last = args[args.length - 1];
    Eif (utils.isObject(last) && !utils.isArray(last)) {
        options = args.pop();
    }
 
    var bytes = encodeConstructorParams(this.abi, args);
    options.data += bytes;
 
    Eif (callback) {
 
        // wait for the contract address adn check if the code was deployed
        this.eth.sendTransaction(options, function (err, hash) {
            Iif (err) {
                callback(err);
            } else {
                // add the transaction hash
                contract.transactionHash = hash;
 
                // call callback for the first time
                callback(null, contract);
 
                checkForContractAddress(contract, callback);
            }
        });
    } else {
        var hash = this.eth.sendTransaction(options);
        // add the transaction hash
        contract.transactionHash = hash;
        checkForContractAddress(contract);
    }
 
    return contract;
};
 
/**
 * Should be called to get access to existing contract on a blockchain
 *
 * @method at
 * @param {Address} contract address (required)
 * @param {Function} callback {optional)
 * @returns {Contract} returns contract if no callback was passed,
 * otherwise calls callback function (err, contract)
 */
ContractFactory.prototype.at = function (address, callback) {
    var contract = new Contract(this.eth, this.abi, address);
 
    // this functions are not part of prototype, 
    // because we dont want to spoil the interface
    addFunctionsToContract(contract);
    addEventsToContract(contract);
    
    Iif (callback) {
        callback(null, contract);
    } 
    return contract;
};
 
/**
 * Gets the data, which is data to deploy plus constructor params
 *
 * @method getData
 */
ContractFactory.prototype.getData = function () {
    var options = {}; // required!
    var args = Array.prototype.slice.call(arguments);
 
    var last = args[args.length - 1];
    if (utils.isObject(last) && !utils.isArray(last)) {
        options = args.pop();
    }
 
    var bytes = encodeConstructorParams(this.abi, args);
    options.data += bytes;
 
    return options.data;
};
 
/**
 * Should be called to create new contract instance
 *
 * @method Contract
 * @param {Array} abi
 * @param {Address} contract address
 */
var Contract = function (eth, abi, address) {
    this._eth = eth;
    this.transactionHash = null;
    this.address = address;
    this.abi = abi;
};
 
module.exports = ContractFactory;