"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

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

var _codec = require("../../codec");

var _StorageHasher = _interopRequireDefault(require("../../primitive/StorageHasher"));

var _v = _interopRequireDefault(require("../v4"));

var _Metadata = require("../v4/Metadata");

var _Storage = require("../v4/Storage");

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

/**
 * Convert V3 StorageFunction to V4 StorageFunction
 */
function toV4StorageFunction(storageFn) {
  const {
    documentation,
    fallback,
    modifier,
    name,
    type
  } = storageFn; // Convert the old type to the new type: there is one new field
  // called `hasher`, which we initialize to xxHash (the default in
  // v3).

  const [newType, index] = type.isPlainType ? [type, 0] : type.isMap ? [(0, _codec.createType)('MapTypeV4', {
    hasher: new _StorageHasher.default('Twox128'),
    key: type.asMap.key,
    value: type.asMap.value,
    linked: type.asMap.linked
  }), 1] : [(0, _codec.createType)('DoubleMapTypeV4', {
    hasher: new _StorageHasher.default('Twox128'),
    key1: type.asDoubleMap.key1,
    key2: type.asDoubleMap.key2,
    value: type.asDoubleMap.value,
    key2Hasher: type.asDoubleMap.key2Hasher
  }), 2];
  return new _Storage.StorageFunctionMetadata({
    documentation,
    fallback,
    name,
    modifier,
    type: new _Storage.StorageFunctionType(newType, index)
  });
}
/**
 * Convert from MetadataV3 to MetadataV4
 * See https://github.com/paritytech/substrate/pull/2268 for details
 */


function toV4(_ref) {
  let {
    modules
  } = _ref;
  return new _v.default({
    modules: modules.map((_ref2) => {
      let {
        calls,
        events,
        name,
        prefix,
        storage
      } = _ref2;
      return new _Metadata.ModuleMetadataV4({
        calls,
        events,
        name,
        prefix,
        storage: storage.isSome ? new _codec.Option(_codec.Vec.with(_Storage.StorageFunctionMetadata), storage.unwrap().map(toV4StorageFunction)) : undefined
      });
    })
  });
}