All files / src/contract contractMethod.js

99.33% Statements 149/150
95.45% Branches 63/66
100% Functions 28/28
99.31% Lines 145/146

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                                  126x 126x 126x 126x 126x 126x 126x 126x 126x   126x 126x 126x 126x 126x 126x 126x 126x 126x 126x       21x 1x   20x 20x 20x 20x       2x 1x   1x       1x 1x 1x       5x 1x   4x       4x 4x 4x       2x 1x   1x   1x   1x 1x       16x   16x   16x     16x 16x           8x 8x   8x 1x   7x 7x   7x   7x 7x   3x 1x   2x 1x   1x       5x 1x 1x     1x     5x                   12x 9x   9x 1x     8x   8x 10x   3x 1x   2x 1x   1x       6x       6x   6x 1x 1x     1x     6x       4x 2x   2x   2x       3x 3x 1x 1x         2x 2x         2x 2x 1x 1x             1x 1x   1x             8x       8x   1x   7x 2x   7x 11x 2x     7x         5x   3x 2x 2x 1x   1x     1x       18x 18x 16x   18x 16x 16x   18x       1x 1x 1x                 1x       125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x   125x      
/**
 * @file contract method
 * @author atom-yang
 */
import { getTransaction, Transaction } from '../util/proto';
import {
  transformArrayToMap,
  transformMapToArray,
  transform,
  INPUT_TRANSFORMERS,
  OUTPUT_TRANSFORMERS
} from '../util/transform';
import { isBoolean, isFunction, isNumber, noop, uint8ArrayToHex, unpackSpecifiedTypeData } from '../util/utils';
import wallet from '../wallet';
 
export default class ContractMethod {
  constructor(chain, method, contractAddress, walletInstance, option) {
    this._chain = chain;
    this._method = method;
    this._option = option || {};
    const { resolvedRequestType, resolvedResponseType } = method;
    this._inputType = resolvedRequestType;
    this._outputType = resolvedResponseType;
    this._name = method.name;
    this._contractAddress = contractAddress;
    this._wallet = walletInstance;
 
    this.sendTransaction = this.sendTransaction.bind(this);
    this.unpackPackedInput = this.unpackPackedInput.bind(this);
    this.packInput = this.packInput.bind(this);
    this.unpackOutput = this.unpackOutput.bind(this);
    this.bindMethodToContract = this.bindMethodToContract.bind(this);
    this.run = this.run.bind(this);
    this.request = this.request.bind(this);
    this.callReadOnly = this.callReadOnly.bind(this);
    this.getSignedTx = this.getSignedTx.bind(this);
    this.getRawTx = this.getRawTx.bind(this);
  }
 
  packInput(input) {
    if (!input) {
      return null;
    }
    let params = transformMapToArray(this._inputType, input);
    params = transform(this._inputType, params, INPUT_TRANSFORMERS);
    const message = this._inputType.fromObject(params);
    return this._inputType.encode(message).finish();
  }
 
  unpackPackedInput(inputPacked) {
    if (!inputPacked) {
      return null;
    }
    const result = unpackSpecifiedTypeData({
      data: inputPacked,
      dataType: this._inputType
    });
    let params = transform(this._inputType, result, OUTPUT_TRANSFORMERS);
    params = transformArrayToMap(this._inputType, params);
    return params;
  }
 
  unpackOutput(output) {
    if (!output) {
      return null;
    }
    let result = unpackSpecifiedTypeData({
      data: isNumber(output) ? String(output) : output,
      dataType: this._outputType
    });
    result = transform(this._outputType, result, OUTPUT_TRANSFORMERS);
    result = transformArrayToMap(this._outputType, result);
    return result;
  }
 
  packOutput(result) {
    if (!result) {
      return null;
    }
    let params = transformMapToArray(this._outputType, result);
 
    params = transform(this._outputType, params, INPUT_TRANSFORMERS);
 
    const message = this._outputType.fromObject(params);
    return this._outputType.encode(message).finish();
  }
 
  handleTransaction(height, hash, encoded) {
    const rawTx = this.getRawTx(height, hash, encoded);
 
    let tx = wallet.signTransaction(rawTx, this._wallet.keyPair);
 
    tx = Transaction.encode(tx).finish();
    // jest environment just go into Buffer branch
    // we have test in browser example handly
    Eif (tx instanceof Buffer) {
      return tx.toString('hex');
    }
    return uint8ArrayToHex(tx);
  }
 
  prepareParametersAsync(args, isView) {
    const filterArgs = args.filter(arg => !isFunction(arg) && !isBoolean(arg.sync));
    const encoded = this.packInput(filterArgs[0]);
 
    if (isView) {
      return Promise.resolve(this.handleTransaction('', '', encoded));
    }
    return this._chain.getChainStatus().then(status => {
      let { BestChainHeight, BestChainHash } = status;
 
      let { refBlockNumberStrategy } = this._option || {};
 
      args.forEach(arg => {
        if (arg.refBlockNumberStrategy) {
          // eslint-disable-next-line max-len
          if (typeof arg.refBlockNumberStrategy !== 'number') {
            throw new Error('Invalid type, refBlockNumberStrategy must be number');
          }
          if (arg.refBlockNumberStrategy > 0) {
            throw new Error('refBlockNumberStrategy must be less than 0');
          }
          refBlockNumberStrategy = arg.refBlockNumberStrategy;
        }
      });
 
      if (refBlockNumberStrategy) {
        BestChainHeight += refBlockNumberStrategy;
        const block = this._chain.getBlockByHeight(BestChainHeight, true, {
          sync: true
        });
        BestChainHash = block.BlockHash;
      }
 
      return this.handleTransaction(BestChainHeight, BestChainHash, encoded);
    });
  }
 
  /**
   * @param {Array} args - argument
   * @param {boolean} isView - view method
   * @returns any
   */
  prepareParameters(args, isView) {
    const filterArgs = args.filter(arg => !isFunction(arg) && !isBoolean(arg.sync));
    const encoded = this.packInput(filterArgs[0]);
 
    if (isView) {
      return this.handleTransaction('', '', encoded);
    }
 
    let { refBlockNumberStrategy } = this._option;
 
    args.forEach(arg => {
      if (arg.refBlockNumberStrategy) {
        // eslint-disable-next-line max-len
        if (typeof arg.refBlockNumberStrategy !== 'number') {
          throw new Error('Invalid type, refBlockNumberStrategy must be number');
        }
        if (arg.refBlockNumberStrategy > 0) {
          throw new Error('refBlockNumberStrategy must be less than 0');
        }
        refBlockNumberStrategy = arg.refBlockNumberStrategy;
      }
    });
 
    const statusRes = this._chain.getChainStatus({
      sync: true
    });
 
    let { BestChainHeight, BestChainHash } = statusRes;
 
    if (refBlockNumberStrategy) {
      BestChainHeight += refBlockNumberStrategy;
      const block = this._chain.getBlockByHeight(BestChainHeight, true, {
        sync: true
      });
      BestChainHash = block.BlockHash;
    }
 
    return this.handleTransaction(BestChainHeight, BestChainHash, encoded);
  }
 
  prepareParametersWithBlockInfo(args) {
    const filterArgs = args.filter(arg => !isFunction(arg) && !isBoolean(arg.sync));
    const encoded = this.packInput(filterArgs[0]);
 
    const { height, hash } = filterArgs[1]; // blockInfo
 
    return this.handleTransaction(height, hash, encoded);
  }
 
  sendTransaction(...args) {
    const argsObject = this.extractArgumentsIntoObject(args);
    if (argsObject.isSync) {
      const parameters = this.prepareParameters(args);
      return this._chain.sendTransaction(parameters, {
        sync: true
      });
    }
    // eslint-disable-next-line arrow-body-style
    return this.prepareParametersAsync(args).then(parameters => {
      return this._chain.sendTransaction(parameters, argsObject.callback);
    });
  }
 
  callReadOnly(...args) {
    const argsObject = this.extractArgumentsIntoObject(args);
    if (argsObject.isSync) {
      const parameters = this.prepareParameters(args, true);
      return this.unpackOutput(
        this._chain.callReadOnly(parameters, {
          sync: true
        })
      );
    }
    // eslint-disable-next-line arrow-body-style
    return this.prepareParametersAsync(args, true).then(parameters => {
      return this._chain
        .callReadOnly(parameters, (error, result) => {
          argsObject.callback(error, this.unpackOutput(result));
        })
        .then(this.unpackOutput);
    });
  }
 
  extractArgumentsIntoObject(args) {
    const result = {
      callback: noop,
      isSync: false
    };
    if (args.length === 0) {
      // has no callback, default to be async mode
      return result;
    }
    if (isFunction(args[args.length - 1])) {
      result.callback = args[args.length - 1];
    }
    args.forEach(arg => {
      if (isBoolean(arg.sync)) {
        result.isSync = arg.sync;
      }
    });
    return result;
  }
 
  // getData(...args) {
  getSignedTx(...args) {
    const filterArgs = args.filter(arg => !isFunction(arg) && !isBoolean(arg.sync));
 
    if (filterArgs[1]) {
      const { height, hash } = filterArgs[1]; // blockInfo
      if (hash && height) {
        return this.prepareParametersWithBlockInfo(args);
      }
      throw Error('The second param is the height & hash of a block');
    }
 
    return this.prepareParameters(args);
  }
 
  getRawTx(blockHeightInput, blockHashInput, packedInput) {
    const rawTx = getTransaction(this._wallet.address, this._contractAddress, this._name, packedInput);
    if (blockHeightInput) {
      rawTx.refBlockNumber = blockHeightInput;
    }
    if (blockHashInput) {
      const blockHash = blockHashInput.match(/^0x/) ? blockHashInput.substring(2) : blockHashInput;
      rawTx.refBlockPrefix = Buffer.from(blockHash, 'hex').slice(0, 4);
    }
    return rawTx;
  }
 
  request(...args) {
    const { callback } = this.extractArgumentsIntoObject(args);
    const params = this.prepareParameters(args);
    return {
      method: 'broadcast_tx',
      callback,
      params,
      format: this.unpackOutput
    };
  }
 
  run(...args) {
    return this.sendTransaction(...args);
  }
 
  bindMethodToContract(contract) {
    const { run } = this;
    run.request = this.request;
    run.call = this.callReadOnly;
    run.inputTypeInfo = this._inputType.toJSON();
    run.inputType = this._inputType;
    run.outputTypeInfo = this._outputType.toJSON();
    run.outputType = this._outputType;
    run.unpackPackedInput = this.unpackPackedInput;
    run.packInput = this.packInput;
    run.packOutput = this.packOutput.bind(this);
    run.sendTransaction = this.sendTransaction;
    run.getSignedTx = this.getSignedTx;
    run.getRawTx = this.getRawTx;
    run.unpackOutput = this.unpackOutput;
    // eslint-disable-next-line no-param-reassign
    contract[this._name] = run;
  }
}