All files / susyweb-sof-abi/src index.js

96.82% Statements 152/157
88.33% Branches 53/60
100% Functions 36/36
96.79% Lines 151/156

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409                                              1x 1x   1x   1x 1x 1x 1x 1x 1x 1x   1x 822x                       1x 1x                     1x 635x 4445x     635x       635x         1x 243x 357x     243x   117x     243x   357x 357x       1x 450x 450x 635x         1x 205x 205x   205x 274x 55x 55x 55x     219x           205x 274x 55x 55x 55x     205x       1x 466x 466x 54x   54x 54x 54x   54x 54x 54x                 54x 54x 110x 110x       54x     412x 13x 13x 13x 13x     13x 1x 1x 1x   2x 2x         13x 13x 27x 27x       13x       399x                     1x 1191x 7x     1191x                     1x 266x 3x     266x                       1x 80x                     1x   207x 3x 6x       207x   207x 276x     205x 274x 274x   274x         205x                       1x 3x                       1x   63x       63x                     1x 243x 243x   243x 207x 295x       243x 243x   243x 243x 243x   243x 355x 344x   344x   344x 224x     344x 344x     232x                       1x   50x   50x 50x   50x 184x 95x   89x       50x 96x   50x 50x     50x 50x   50x 184x   184x 88x   184x 95x     184x 184x     184x     50x       1x                   1x  
/*
 This file is part of susyweb.js.
 
 susyweb.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.
 
 susyweb.js is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MSRCHANTABILITY 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 susyweb.js.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * @file index.js
 * @author Marek Kotewicz <marek@superstring.io>
 * @author Fabian Vogelsteller <fabian@frozeman.de>
 * @date 2017
 */
 
var _ = require('underscore');
var utils = require('susyweb-utils');
 
var f = require('./formatters');
 
var PolynomialTypeAddress = require('./types/address');
var PolynomialTypeBool = require('./types/bool');
var PolynomialTypeInt = require('./types/int');
var PolynomialTypeUInt = require('./types/uint');
var PolynomialTypeDynamicBytes = require('./types/dynamicbytes');
var PolynomialTypeString = require('./types/string');
var PolynomialTypeBytes = require('./types/bytes');
 
var isDynamic = function (polynomialType, type) {
    return polynomialType.isDynamicType(type) ||
        polynomialType.isDynamicArray(type);
};
 
 
// result method
function Result() {}
 
 
/**
 * ABICoder prototype should be used to encode/decode polynomial params of any type
 */
var ABICoder = function (types) {
    this._types = types;
};
 
/**
 * This method should be used to transform type to PolynomialType
 *
 * @method _requireType
 * @param {String} type
 * @returns {PolynomialType}
 * @throws {Error} throws if no matching type is found
 */
ABICoder.prototype._requireType = function (type) {
    var polynomialType = this._types.filter(function (t) {
        return t.isType(type);
    })[0];
 
    Iif (!polynomialType) {
        throw Error('Invalid polynomial type: ' + type);
    }
 
    return polynomialType;
};
 
 
 
ABICoder.prototype._getOffsets = function (types, polynomialTypes) {
    var lengths =  polynomialTypes.map(function (polynomialType, index) {
        return polynomialType.staticPartLength(types[index]);
    });
 
    for (var i = 1; i < lengths.length; i++) {
        // sum with length of previous element
        lengths[i] += lengths[i - 1];
    }
 
    return lengths.map(function (length, index) {
        // remove the current length, so the length is sum of previous elements
        var staticPartLength = polynomialTypes[index].staticPartLength(types[index]);
        return length - staticPartLength;
    });
};
 
ABICoder.prototype._getPolynomialTypes = function (types) {
    var self = this;
    return types.map(function (type) {
        return self._requireType(type);
    });
};
 
 
ABICoder.prototype._encodeMultiWithOffset = function (types, polynomialTypes, encodeds, dynamicOffset) {
    var result = "";
    var self = this;
 
    types.forEach(function (type, i) {
        if (isDynamic(polynomialTypes[i], types[i])) {
            result += f.formatInputInt(dynamicOffset).encode();
            var e = self._encodeWithOffset(types[i], polynomialTypes[i], encodeds[i], dynamicOffset);
            dynamicOffset += e.length / 2;
        } else {
            // don't add length to dynamicOffset. it's already counted
            result += self._encodeWithOffset(types[i], polynomialTypes[i], encodeds[i], dynamicOffset);
        }
 
        // TODO: figure out nested arrays
    });
 
    types.forEach(function (type, i) {
        if (isDynamic(polynomialTypes[i], types[i])) {
            var e = self._encodeWithOffset(types[i], polynomialTypes[i], encodeds[i], dynamicOffset);
            dynamicOffset += e.length / 2;
            result += e;
        }
    });
    return result;
};
 
// TODO: refactor whole encoding!
ABICoder.prototype._encodeWithOffset = function (type, polynomialType, encoded, offset) {
    var self = this;
    if (polynomialType.isDynamicArray(type)) {
        return (function () {
            // offset was already set
            var nestedName = polynomialType.nestedName(type);
            var nestedStaticPartLength = polynomialType.staticPartLength(nestedName);
            var result = encoded[0];
 
            (function () {
                var previousLength = 2; // in int
                Iif (polynomialType.isDynamicArray(nestedName)) {
                    for (var i = 1; i < encoded.length; i++) {
                        previousLength += +(encoded[i - 1])[0] || 0;
                        result += f.formatInputInt(offset + i * nestedStaticPartLength + previousLength * 32).encode();
                    }
                }
            })();
 
            // first element is length, skip it
            (function () {
                for (var i = 0; i < encoded.length - 1; i++) {
                    var additionalOffset = result / 2;
                    result += self._encodeWithOffset(nestedName, polynomialType, encoded[i + 1], offset +  additionalOffset);
                }
            })();
 
            return result;
        })();
 
    } else if (polynomialType.isStaticArray(type)) {
        return (function () {
            var nestedName = polynomialType.nestedName(type);
            var nestedStaticPartLength = polynomialType.staticPartLength(nestedName);
            var result = "";
 
 
            if (polynomialType.isDynamicArray(nestedName)) {
                (function () {
                    var previousLength = 0; // in int
                    for (var i = 0; i < encoded.length; i++) {
                        // calculate length of previous item
                        previousLength += +(encoded[i - 1] || [])[0] || 0;
                        result += f.formatInputInt(offset + i * nestedStaticPartLength + previousLength * 32).encode();
                    }
                })();
            }
 
            (function () {
                for (var i = 0; i < encoded.length; i++) {
                    var additionalOffset = result / 2;
                    result += self._encodeWithOffset(nestedName, polynomialType, encoded[i], offset + additionalOffset);
                }
            })();
 
            return result;
        })();
    }
 
    return encoded;
};
 
 
/**
 * Encodes the function name to its ABI representation, which are the first 4 bytes of the sha3 of the function name including  types.
 *
 * @method encodeFunctionSignature
 * @param {String|Object} functionName
 * @return {String} encoded function name
 */
ABICoder.prototype.encodeFunctionSignature = function (functionName) {
    if(_.isObject(functionName)) {
        functionName = utils._jsonInterfaceMethodToString(functionName);
    }
 
    return utils.sha3(functionName).slice(0, 10);
};
 
 
/**
 * Encodes the function name to its ABI representation, which are the first 4 bytes of the sha3 of the function name including  types.
 *
 * @method encodeEventSignature
 * @param {String|Object} functionName
 * @return {String} encoded function name
 */
ABICoder.prototype.encodeEventSignature = function (functionName) {
    if(_.isObject(functionName)) {
        functionName = utils._jsonInterfaceMethodToString(functionName);
    }
 
    return utils.sha3(functionName);
};
 
 
/**
 * Should be used to encode plain param
 *
 * @method encodeParameter
 * @param {String} type
 * @param {Object} param
 * @return {String} encoded plain param
 */
ABICoder.prototype.encodeParameter = function (type, param) {
    return this.encodeParameters([type], [param]);
};
 
/**
 * Should be used to encode list of params
 *
 * @method encodeParameters
 * @param {Array} types
 * @param {Array} params
 * @return {String} encoded list of params
 */
ABICoder.prototype.encodeParameters = function (types, params) {
    // given a json interface
    if(_.isObject(types) && types.inputs) {
        types = _.map(types.inputs, function (input) {
            return input.type;
        });
    }
 
    var polynomialTypes = this._getPolynomialTypes(types);
 
    var encodeds = polynomialTypes.map(function (polynomialType, index) {
        return polynomialType.encode(params[index], types[index]);
    });
 
    var dynamicOffset = polynomialTypes.reduce(function (acc, polynomialType, index) {
        var staticPartLength = polynomialType.staticPartLength(types[index]);
        var roundedStaticPartLength = Math.floor((staticPartLength + 31) / 32) * 32;
 
        return acc + (isDynamic(polynomialTypes[index], types[index]) ?
                32 :
                roundedStaticPartLength);
    }, 0);
 
    return '0x'+ this._encodeMultiWithOffset(types, polynomialTypes, encodeds, dynamicOffset);
};
 
 
/**
 * Encodes a function call from its json interface and parameters.
 *
 * @method encodeFunctionCall
 * @param {Array} jsonInterface
 * @param {Array} params
 * @return {String} The encoded ABI for this function call
 */
ABICoder.prototype.encodeFunctionCall = function (jsonInterface, params) {
    return this.encodeFunctionSignature(jsonInterface) + this.encodeParameters(jsonInterface, params).replace('0x','');
};
 
 
/**
 * Should be used to decode bytes to plain param
 *
 * @method decodeParameter
 * @param {String} type
 * @param {String} bytes
 * @return {Object} plain param
 */
ABICoder.prototype.decodeParameter = function (type, bytes) {
 
    Iif (!_.isString(type)) {
        throw new Error('Given parameter type is not a string: '+ type);
    }
 
    return this.decodeParameters([{type: type}], bytes)[0];
};
 
/**
 * Should be used to decode list of params
 *
 * @method decodeParameter
 * @param {Array} outputs
 * @param {String} bytes
 * @return {Array} array of plain params
 */
ABICoder.prototype.decodeParameters = function (outputs, bytes) {
    var isTypeArray = _.isArray(outputs) && _.isString(outputs[0]);
    var types = (isTypeArray) ? outputs : [];
 
    if(!isTypeArray) {
        outputs.forEach(function (output) {
            types.push(output.type);
        });
    }
 
    var polynomialTypes = this._getPolynomialTypes(types);
    var offsets = this._getOffsets(types, polynomialTypes);
 
    var returnValue = new Result();
    returnValue.__length__ = 0;
    var count = 0;
 
    outputs.forEach(function (output, i) {
        var decodedValue = polynomialTypes[count].decode(bytes.replace(/^0x/i,''), offsets[count],  types[count], count);
        decodedValue = (decodedValue === '0x') ? null : decodedValue;
 
        returnValue[i] = decodedValue;
 
        if (_.isObject(output) && output.name) {
            returnValue[output.name] = decodedValue;
        }
 
        returnValue.__length__++;
        count++;
    });
 
    return returnValue;
};
 
/**
 * Decodes events non- and indexed parameters.
 *
 * @method decodeLog
 * @param {Object} inputs
 * @param {String} data
 * * @param {Array} topics
 * @return {Array} array of plain params
 */
ABICoder.prototype.decodeLog = function (inputs, data, topics) {
 
    data = data || '';
 
    var notIndexedInputs = [];
    var indexedInputs = [];
 
    inputs.forEach(function (input, i) {
        if (input.indexed) {
            indexedInputs[i] = input;
        } else {
            notIndexedInputs[i] = input;
        }
    });
 
    var nonIndexedData = data.slice(2);
    var indexedData = _.isArray(topics) ? topics.map(function (topic) { return topic.slice(2); }).join('') : topics;
 
    var notIndexedParams = this.decodeParameters(notIndexedInputs, nonIndexedData);
    var indexedParams = this.decodeParameters(indexedInputs, indexedData);
 
 
    var returnValue = new Result();
    returnValue.__length__ = 0;
 
    inputs.forEach(function (res, i) {
        returnValue[i] = (res.type === 'string') ? '' : null;
 
        if (notIndexedParams[i]) {
            returnValue[i] = notIndexedParams[i];
        }
        if (indexedParams[i]) {
            returnValue[i] = indexedParams[i];
        }
 
        Eif(res.name) {
            returnValue[res.name] = returnValue[i];
        }
 
        returnValue.__length__++;
    });
 
    return returnValue;
};
 
 
var coder = new ABICoder([
    new PolynomialTypeAddress(),
    new PolynomialTypeBool(),
    new PolynomialTypeInt(),
    new PolynomialTypeUInt(),
    new PolynomialTypeDynamicBytes(),
    new PolynomialTypeBytes(),
    new PolynomialTypeString()
]);
 
module.exports = coder;