var __awaiter =
  (this && this.__awaiter) ||
  function (thisArg, _arguments, P, generator) {
    function adopt(value) {
      return value instanceof P
        ? value
        : new P(function (resolve) {
            resolve(value);
          });
    }
    return new (P || (P = Promise))(function (resolve, reject) {
      function fulfilled(value) {
        try {
          step(generator.next(value));
        } catch (e) {
          reject(e);
        }
      }
      function rejected(value) {
        try {
          step(generator["throw"](value));
        } catch (e) {
          reject(e);
        }
      }
      function step(result) {
        result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
      }
      step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
  };
import { get, post } from "@toruslabs/http-helpers";
import { log, WALLET_ADAPTERS } from "@web3auth/base";
import CID from "cids";
import { OPENLOGIN_PROVIDERS, OPENLOGIN_PROVIDERS_NAMES, PASSWORDLESS_BACKEND } from "./config";
export const getAdapterSocialLogins = (adapterName, adapter, loginMethodsConfig = {}) => {
  const finalLoginMethodsConfig = {};
  if (adapterName === WALLET_ADAPTERS.OPENLOGIN) {
    OPENLOGIN_PROVIDERS.forEach((loginMethod) => {
      const currentLoginMethodConfig = loginMethodsConfig[loginMethod] || {
        name: OPENLOGIN_PROVIDERS_NAMES[loginMethod],
        showOnMobile: true,
        showOnModal: true,
        showOnDesktop: true,
      };
      finalLoginMethodsConfig[loginMethod] = Object.assign({}, currentLoginMethodConfig);
    });
    log.debug("OpenLogin login method ui config", finalLoginMethodsConfig);
  } else {
    throw new Error(`${adapterName} is not a valid adapter`);
  }
  return finalLoginMethodsConfig;
};
export function validateImageUrl(url) {
  return __awaiter(this, void 0, void 0, function* () {
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.src = url;
      if (img.complete) {
        resolve(true);
      } else {
        img.addEventListener("load", () => {
          resolve(true);
        });
        img.addEventListener("error", () => {
          reject();
        });
      }
    });
  });
}
export function getNetworkIconId(ticker) {
  return __awaiter(this, void 0, void 0, function* () {
    const fallbackId = "network-default";
    if (!ticker) return fallbackId;
    try {
      const url = `https://images.web3auth.io/network-${ticker.toLowerCase()}.svg`;
      const isValid = yield validateImageUrl(url);
      if (isValid) {
        return `network-${ticker.toLowerCase()}`;
      }
      return fallbackId;
    } catch (_a) {
      return fallbackId;
    }
  });
}
export const getPasswordlessBackendUrl = (web3AuthNetwork) => {
  var _a;
  return (_a = PASSWORDLESS_BACKEND[web3AuthNetwork]) !== null && _a !== void 0 ? _a : PASSWORDLESS_BACKEND.mainnet;
};
export const getUserCountry = (web3AuthNetwork) =>
  __awaiter(void 0, void 0, void 0, function* () {
    try {
      const result = yield get(`${getPasswordlessBackendUrl(web3AuthNetwork)}/api/v2/user/location`);
      if (result && result.data.country) return { country: result.data.country, dialCode: result.data.dial_code };
      return null;
    } catch (error) {
      log.error("error getting user country", error);
      return null;
    }
  });
export const validatePhoneNumber = (phoneNumber, web3AuthNetwork) =>
  __awaiter(void 0, void 0, void 0, function* () {
    try {
      const result = yield post(`${getPasswordlessBackendUrl(web3AuthNetwork)}/api/v2/phone_number/validate`, {
        phone_number: phoneNumber,
      });
      if (result && result.success) return result.parsed_number;
      return false;
    } catch (error) {
      log.error("error validating phone number", error);
      if (error.status === 400) {
        return false;
      }
      // sending true because we don't want the user to be stuck on a flow
      // if there is an error with the api or something went wrong.
      return true;
    }
  });
export const languageMap = {
  en: "english",
  de: "german",
  ja: "japanese",
  ko: "korean",
  zh: "mandarin",
  es: "spanish",
  fr: "french",
  pt: "portuguese",
  nl: "dutch",
};
export function handleFixIpfs(img = "") {
  let newImg = img;
  if (newImg.indexOf("ipfs://") > -1) {
    let url = newImg.split("//")[1];
    if (url.startsWith("Qm") && url.indexOf("/") > 0) {
      const cid = new CID(url.split("/")[0]);
      url = cid.toV1().toString();
      return `https://${url}.ipfs.nftstorage.link/${newImg.split("//")[1].split("/")[1]}`;
    }
    if (url.startsWith("Qm")) {
      const cid = new CID(url);
      newImg = cid.toV1().toString();
      // return `https://${img}.ipfs.nftstorage.link`;
      return `https://thedial.infura-ipfs.io/ipfs/${newImg}`;
      // return `https://gateway.pinata.cloud/ipfs/${url}`
      // return `https://cloudflare-ipfs.com/ipfs/${url}`
    }
    return `https://${url}.ipfs.nftstorage.link`;
  }
  return newImg;
}
const imageCache = {};
export function isNft(contract) {
  if (!contract) return false;
  if (contract.indexOf("0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee") > -1) return false;
  return true;
}
export const handleGetImageUrl = (url) => {
  if (!url) {
    return "";
  }
  if (imageCache[url]) {
    return imageCache[url].src;
  }
  const img = new Image();
  img.src = handleFixIpfs(url);
  imageCache[url] = img;
  return img.src;
};
export function normalizeHexAddress(address) {
  if (!address) {
    return "";
  }
  const addressString = typeof address === "object" && !("toLowerCase" in address) ? address.toString("hex") : address;
  if (typeof addressString === "string") {
    const noPrefix = addressString.replace(/^0x/, "");
    const even = noPrefix.length % 2 === 0 ? noPrefix : `0${noPrefix}`;
    return `0x${Buffer.from(even, "hex").toString("hex")}`;
  }
  return "";
}
export function isProbablyEVMAddress(str) {
  if (!str) {
    return false;
  }
  if (normalizeHexAddress(str).startsWith("0x") && str.length === 42) {
    return true;
  }
  return false;
}
export function truncateAddress(address) {
  if (!address) {
    return "";
  }
  if (isProbablyEVMAddress(address)) {
    if ((address === null || address === void 0 ? void 0 : address.length) < 14) {
      return address;
    }
    return `${address.slice(0, 6)}…${address.slice(-4)}`;
  }
  if (address.length > 42) {
    return `${address.slice(0, 6)}…${address.slice(-6)}`;
  }
  return address;
}
//# sourceMappingURL=utils.js.map
