"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = fromMetadata;

var _codec = require("@polkadot/types/codec");

var _util = require("@polkadot/util");

// Copyright 2017-2019 @polkadot/api-metadata authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.

/**
 * Retrieve the parameter types (module constants) from the runtime metadata.
 *
 * @param metadata - The metadata
 */
function fromMetadata(metadata) {
  return metadata.asLatest.modules.reduce((result, moduleMetadata) => {
    if (moduleMetadata.constants.isEmpty) {
      return result;
    }

    const {
      name
    } = moduleMetadata; // For access, we change the index names, i.e. Democracy.EnactmentPeriod -> democracy.enactmentPeriod

    result[(0, _util.stringCamelCase)(name.toString())] = moduleMetadata.constants.reduce((newModule, meta) => {
      const codec = (0, _codec.createTypeUnsafe)(meta.type.toString(), [meta.value]); // This is not a perfect idea, however as it stands with number-only constants on the metadata
      // does not have any effect. However, this could become problematic in cases where items are
      // exposed that contain their own metadata. As of now, the compatibility with current, e.g.
      // storage is the driving factor, one consistent way of handling interfaces

      codec.meta = meta;
      newModule[(0, _util.stringCamelCase)(meta.name.toString())] = codec;
      return newModule;
    }, {});
    return result;
  }, {});
}