All files / src/contract index.js

100% Statements 25/25
100% Branches 6/6
100% Functions 11/11
100% Lines 24/24

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                    7x 6x 6x 58x   20x 20x 20x           9x 9x 9x       7x 7x           6x 6x 6x       9x 15x 124x 124x 124x           9x 9x 9x 9x      
/**
 * @file contract
 * @author atom-yang
 */
// eslint-disable-next-line max-classes-per-file
import * as protobuf from '@aelfqueen/protobufjs';
import ContractMethod from './contractMethod';
import { noop } from '../util/utils';
import { deserializeLog } from '../util/proto';
 
const getServicesFromFileDescriptors = descriptors => {
  const root = protobuf.Root.fromDescriptor(descriptors, 'proto3').resolveAll();
  return descriptors.file
    .filter(f => f.service.length > 0)
    .map(f => {
      const sn = f.service[0].name;
      const fullName = f.package ? `${f.package}.${sn}` : sn;
      return root.lookupService(fullName);
    });
};
 
class Contract {
  constructor(chain, services, address) {
    this._chain = chain;
    this.address = address;
    this.services = services;
  }
 
  deserializeLog(logs = [], logName) {
    const logInThisAddress = logs.filter(v => v.Address === this.address && v.Name === logName);
    return deserializeLog(logInThisAddress, this.services);
  }
}
 
export default class ContractFactory {
  constructor(chain, fileDescriptorSet, wallet) {
    this.chain = chain;
    this.services = getServicesFromFileDescriptors(fileDescriptorSet);
    this.wallet = wallet;
  }
 
  static bindMethodsToContract(contract, wallet) {
    contract.services.forEach(service => {
      Object.keys(service.methods).forEach(key => {
        const method = service.methods[key].resolve();
        const contractMethod = new ContractMethod(contract._chain, method, contract.address, wallet);
        contractMethod.bindMethodToContract(contract);
      });
    });
  }
 
  at(address, callback = noop) {
    const contractInstance = new Contract(this.chain, this.services, address);
    ContractFactory.bindMethodsToContract(contractInstance, this.wallet);
    callback(null, contractInstance);
    return contractInstance;
  }
}