{"size": 1438, "ext": "js", "max_stars_repo_path": "src/utils/encoding.js", "max_stars_repo_name": "galtproject/cosmos-js", "max_stars_repo_stars_event_min_datetime": "2019-12-11T21:36:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-11T21:36:51.000Z", "max_issues_repo_path": "src/utils/encoding.js", "max_issues_repo_name": "galtproject/cosmos-js", "max_issues_repo_issues_event_min_datetime": "2019-11-03T16:37:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-09T22:14:23.000Z", "max_forks_repo_path": "src/utils/encoding.js", "max_forks_repo_name": "galtproject/cosmos-js", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1, "max_issues_count": 2, "max_forks_count": null, "avg_line_length": 24.7931034483, "max_line_length": 86, "alphanum_fraction": 0.6488178025}
/*
 * Copyright ©️ 2018 Galt•Project Society Construction and Terraforming Company
 * (Founded by [Nikolai Popeka](https://github.com/npopeka)
 *
 * Copyright ©️ 2018 Galt•Core Blockchain Company
 * (Founded by [Nikolai Popeka](https://github.com/npopeka) by
 * [Basic Agreement](ipfs/QmaCiXUmSrP16Gz8Jdzq6AJESY1EAANmmwha15uR3c1bsS)).
 */

const _ = require('lodash');
const { importPrivateKey } = require('./common');
const { isHex } = require('./hex');
const { addressToBech32 } = require('./bech32');

import { NetEncodingEnum } from '../config/abstract';

module.exports = function(config) {
  function encodeAccount(acc) {
    if (_.isEmpty(acc)) {
      return null;
    }

    switch (config.DEFAULT_ENCODING) {
      case NetEncodingEnum.BECH32: {
        if (isHex(acc.address)) {
          acc.address = addressToBech32(config.PREFIX_BECH32_ACCADDR, acc.address);
        }

        if (isHex(acc.publicKey)) {
          acc.publicKey = addressToBech32(config.PREFIX_BECH32_ACCPUB, acc.publicKey);
        }
        break;
      }
      default: {
      }
    }
    return acc;
  }

  function importAccount(privateKey) {
    const keyPair = importPrivateKey(privateKey);

    if (!keyPair) return null;

    return encodeAccount({
      address: keyPair.address,
      phrase: null,
      privateKey: keyPair.privateKey,
      publicKey: keyPair.publicKey,
    });
  }

  return {
    importAccount,
    encodeAccount,
  };
};
