All files / src/chain index.js

100% Statements 63/63
100% Branches 28/28
100% Functions 13/13
100% Lines 61/61

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                          26x 494x 494x 494x 494x 494x         12x         12x   4x   8x 1x   8x 8x 5x   8x 1x     8x                     5x 5x 2x     2x 1x 1x   1x     3x 3x 1x 1x 1x 1x   2x   2x 1x           4x 4x 2x     2x 2x 3x 2x 1x   1x     1x 11x 11x 11x 11x   1x   2x 2x 2x 3x 2x 1x   1x 1x 11x 11x 11x 11x   1x          
/**
 * @file chain
 * @author atom-yang
 */
import { isBoolean, isFunction, noop, setPath } from '../util/utils';
import { CHAIN_METHODS } from '../common/constants';
import ChainMethod from './chainMethod';
import * as merkleTree from '../util/merkleTree';
 
import ContractFactory from '../contract';
 
export default class Chain {
  constructor(requestManager) {
    Object.keys(CHAIN_METHODS).forEach(key => {
      const methodConfig = CHAIN_METHODS[key];
      const { name } = methodConfig;
      const method = new ChainMethod(methodConfig);
      method.setRequestManager(requestManager);
      setPath(this, name, method.run);
    });
  }
 
  extractArgumentsIntoObject(args) {
    const result = {
      callback: noop,
      isSync: false,
      refBlockNumberStrategy: 0
    };
    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;
      }
      if (typeof arg?.refBlockNumberStrategy === 'number') {
        result.refBlockNumberStrategy = arg.refBlockNumberStrategy;
      }
    });
    return result;
  }
 
  /**
   * @param {string} address - Contract address
   * @param {IBlockchainWallet} wallet - aelf wallet
   * @param {object} options - {sync: boolean, refBlockNumberStrategy: number}
   * @param  {...any} args
   * @returns
   */
  contractAt(address, wallet, ...args) {
    const { callback, isSync, refBlockNumberStrategy } = this.extractArgumentsIntoObject(args);
    if (isSync) {
      const fds = this.getContractFileDescriptorSet(address, {
        sync: true
      });
      if (fds && fds.file && fds.file.length > 0) {
        const factory = new ContractFactory(this, fds, wallet, { refBlockNumberStrategy });
        return factory.at(address);
      }
      throw new Error('no such contract');
    }
    // eslint-disable-next-line consistent-return
    return this.getContractFileDescriptorSet(address).then(fds => {
      if (fds && fds.file && fds.file.length > 0) {
        const factory = new ContractFactory(this, fds, wallet, { refBlockNumberStrategy });
        const result = factory.at(address);
        callback(null, result);
        return result;
      }
      callback(new Error('no such contract'));
      // if callback is noop, throw error
      if (callback.length === 0) {
        throw new Error('no such contract');
      }
    });
  }
 
  getMerklePath(txId, height, ...args) {
    const { isSync } = this.extractArgumentsIntoObject(args);
    if (isSync) {
      const block = this.getBlockByHeight(height, true, {
        sync: true
      });
      const { BlockHash, Body } = block;
      const txIds = Body.Transactions;
      const txIndex = txIds.findIndex(id => id === txId);
      if (txIndex === -1) {
        throw new Error(`txId ${txId} has no correspond transaction in the block with height ${height}`);
      }
      const txResults = this.getTxResults(BlockHash, 0, txIds.length, {
        sync: true
      });
      const nodes = txResults.map((result, index) => {
        const id = txIds[index];
        const status = result.Status;
        const buffer = Buffer.concat([Buffer.from(id.replace('0x', ''), 'hex'), Buffer.from(status, 'utf8')]);
        return merkleTree.node(buffer);
      });
      return merkleTree.getMerklePath(txIndex, nodes);
    }
    return this.getBlockByHeight(height, true).then(block => {
      const { BlockHash, Body } = block;
      const txIds = Body.Transactions;
      const txIndex = txIds.findIndex(id => id === txId);
      if (txIndex === -1) {
        throw new Error(`txId ${txId} has no correspond transaction in the block with height ${height}`);
      }
      return this.getTxResults(BlockHash, 0, txIds.length).then(results => {
        const nodes = results.map((result, index) => {
          const id = txIds[index];
          const status = result.Status;
          const buffer = Buffer.concat([Buffer.from(id.replace('0x', ''), 'hex'), Buffer.from(status, 'utf8')]);
          return merkleTree.node(buffer);
        });
        return merkleTree.getMerklePath(txIndex, nodes);
      });
    });
  }
}