{"version":3,"sources":["../src/error.ts","../src/utils.ts","../src/signers.ts","../src/types.ts","../src/client.ts"],"sourcesContent":["export class CosmiframeTimeoutError extends Error {\n  constructor(message: string) {\n    super(message)\n    this.name = 'CosmiframeTimeoutError'\n  }\n}\n","import { v4 as uuidv4 } from 'uuid'\n\nimport { CosmiframeTimeoutError } from './error'\nimport {\n  CalledParentMethodResult,\n  MethodCallResultMessageNoId,\n  Origin,\n  OverrideHandler,\n  RequestMethodCallMessageNoId,\n} from './types'\n\n/**\n * Origin specified by the iframe to allow all origins. This is unsafe and\n * should not be done.\n */\nexport const UNSAFE_ALLOW_ANY_ORIGIN = 'UNSAFE_ALLOW_ANY_ORIGIN'\n\n/**\n * Send message call request to parent and listen for the result, only accepting\n * results from parents of allowed origins. Returns a promise that resolves with\n * the result on success or rejects with an error.\n */\nexport const callParentMethod = <T = any>(\n  message: RequestMethodCallMessageNoId,\n  origins: Origin[],\n  /**\n   * The timeout in milliseconds after which to reject the promise and stop\n   * listening if the parent has not responded. If undefined, no timeout.\n   *\n   * Defaults to no timeout.\n   */\n  timeout?: number\n): Promise<CalledParentMethodResult<T>> =>\n  new Promise<CalledParentMethodResult<T>>((resolve, reject) => {\n    let timeoutId: number | null = null\n    const id = uuidv4()\n\n    // Add one-time listener that waits for a response for the request we're\n    // about to send.\n    const listener = ({ origin, source, data }: MessageEvent) => {\n      // Verify we are receiving a response for the correct request from an\n      // allowed parent.\n      if (\n        !isOriginAllowed(origins, origin) ||\n        source !== window.parent ||\n        data.id !== id\n      ) {\n        return\n      }\n\n      // Remove listener once we receive a response for the correct request.\n      window.removeEventListener('message', listener)\n\n      // Remove timeout if set.\n      if (timeoutId !== null) {\n        clearTimeout(timeoutId)\n      }\n\n      if (data.type === 'success') {\n        resolve({\n          result: data.response,\n          origin,\n        })\n      } else {\n        reject(new Error(data.error))\n      }\n    }\n\n    window.addEventListener('message', listener)\n\n    try {\n      const data = {\n        ...message,\n        id,\n      }\n\n      // Send the message to our parent of any origin. This is safe because we\n      // will only accept responses back from parents of allowed origins.\n      window.parent.postMessage(data, '*')\n    } catch (err) {\n      // If fails to send, remove the listener and reject.\n      window.removeEventListener('message', listener)\n      reject(err)\n    }\n\n    // If timeout is set, add a timeout listener that will reject the promise\n    // if the parent has not responded.\n    if (timeout) {\n      timeoutId = setTimeout(() => {\n        window.removeEventListener('message', listener)\n        reject(\n          new CosmiframeTimeoutError(\n            `Timed out after ${timeout}ms waiting for parent to respond.`\n          )\n        )\n      }, timeout)\n    }\n  })\n\n/**\n * Convert override handler into a method call result message. If the override\n * handler is to call the method normally, returns undefined.\n */\nexport const processOverrideHandler = (\n  handler: OverrideHandler\n): MethodCallResultMessageNoId | undefined => {\n  if (!handler || handler.type === 'error') {\n    return {\n      type: 'error',\n      error:\n        (handler && handler.type === 'error' && handler.error) ||\n        'Handled by outer wallet.',\n    }\n  } else if (handler.type === 'success') {\n    return {\n      type: 'success',\n      response: handler.value,\n    }\n  }\n}\n\n/**\n * Returns whether or not the current app is being used in an iframe.\n */\nexport const isInIframe = () =>\n  typeof window !== 'undefined' && window.self !== window.parent\n\n/**\n * Returns whether or not the origin is allowed.\n */\nexport const isOriginAllowed = (allowedOrigins: Origin[], origin: string) =>\n  allowedOrigins.some(\n    (allowed) =>\n      // Allow all origins.\n      allowed === '*' ||\n      // Allow a specific origin.\n      (typeof allowed === 'string' && origin === allowed) ||\n      // Allow an origin that matches a regular expression.\n      (allowed instanceof RegExp && allowed.test(origin))\n  )\n","import {\n  AminoSignResponse,\n  OfflineAminoSigner,\n  StdSignDoc,\n} from '@cosmjs/amino'\nimport {\n  AccountData,\n  DirectSignResponse,\n  OfflineDirectSigner,\n} from '@cosmjs/proto-signing'\n\nimport { Origin } from './types'\nimport { callParentMethod } from './utils'\n\nexport class CosmiframeDirectSigner implements OfflineDirectSigner {\n  /**\n   * Parent origins we are allowed to communicate with.\n   */\n  #allowedOrigins: Origin[]\n\n  constructor(\n    public chainId: string,\n    allowedParentOrigins: Origin[]\n  ) {\n    this.#allowedOrigins = allowedParentOrigins\n  }\n\n  async getAccounts(): Promise<readonly AccountData[]> {\n    return (\n      await callParentMethod<readonly AccountData[]>(\n        {\n          method: 'getAccounts',\n          params: [],\n          chainId: this.chainId,\n          signerType: 'direct',\n        },\n        this.#allowedOrigins\n      )\n    ).result\n  }\n\n  async signDirect(\n    signerAddress: string,\n    signDoc: DirectSignResponse['signed']\n  ): Promise<DirectSignResponse> {\n    return (\n      await callParentMethod<DirectSignResponse>(\n        {\n          method: 'signDirect',\n          params: [signerAddress, signDoc],\n          chainId: this.chainId,\n          signerType: 'direct',\n        },\n        this.#allowedOrigins\n      )\n    ).result\n  }\n}\n\nexport class CosmiframeAminoSigner implements OfflineAminoSigner {\n  /**\n   * Parent origins we are allowed to communicate with.\n   */\n  #allowedOrigins: Origin[]\n\n  constructor(\n    public chainId: string,\n    allowedParentOrigins: Origin[]\n  ) {\n    this.#allowedOrigins = allowedParentOrigins\n  }\n\n  async getAccounts(): Promise<readonly AccountData[]> {\n    return (\n      await callParentMethod<readonly AccountData[]>(\n        {\n          method: 'getAccounts',\n          params: [],\n          chainId: this.chainId,\n          signerType: 'amino',\n        },\n        this.#allowedOrigins\n      )\n    ).result\n  }\n\n  async signAmino(\n    signerAddress: string,\n    signDoc: StdSignDoc\n  ): Promise<AminoSignResponse> {\n    return (\n      await callParentMethod<AminoSignResponse>(\n        {\n          method: 'signAmino',\n          params: [signerAddress, signDoc],\n          chainId: this.chainId,\n          signerType: 'amino',\n        },\n        this.#allowedOrigins\n      )\n    ).result\n  }\n}\n\nexport class CosmiframeEitherSigner\n  implements OfflineDirectSigner, OfflineAminoSigner\n{\n  /**\n   * Parent origins we are allowed to communicate with.\n   */\n  #allowedOrigins: Origin[]\n\n  constructor(\n    public chainId: string,\n    allowedParentOrigins: Origin[]\n  ) {\n    this.#allowedOrigins = allowedParentOrigins\n  }\n\n  async getAccounts(): Promise<readonly AccountData[]> {\n    // Try amino first, falling back to direct.\n    try {\n      return (\n        await callParentMethod<readonly AccountData[]>(\n          {\n            method: 'getAccounts',\n            params: [],\n            chainId: this.chainId,\n            signerType: 'amino',\n          },\n          this.#allowedOrigins\n        )\n      ).result\n    } catch {\n      return (\n        await callParentMethod<readonly AccountData[]>(\n          {\n            method: 'getAccounts',\n            params: [],\n            chainId: this.chainId,\n            signerType: 'direct',\n          },\n          this.#allowedOrigins\n        )\n      ).result\n    }\n  }\n\n  async signDirect(\n    signerAddress: string,\n    signDoc: DirectSignResponse['signed']\n  ): Promise<DirectSignResponse> {\n    return (\n      await callParentMethod<DirectSignResponse>(\n        {\n          method: 'signDirect',\n          params: [signerAddress, signDoc],\n          chainId: this.chainId,\n          signerType: 'direct',\n        },\n        this.#allowedOrigins\n      )\n    ).result\n  }\n\n  async signAmino(\n    signerAddress: string,\n    signDoc: StdSignDoc\n  ): Promise<AminoSignResponse> {\n    return (\n      await callParentMethod<AminoSignResponse>(\n        {\n          method: 'signAmino',\n          params: [signerAddress, signDoc],\n          chainId: this.chainId,\n          signerType: 'amino',\n        },\n        this.#allowedOrigins\n      )\n    ).result\n  }\n}\n","import { OfflineAminoSigner } from '@cosmjs/amino'\nimport { OfflineDirectSigner } from '@cosmjs/proto-signing'\n\n/**\n * The two signer types.\n */\nexport type SignerType = 'amino' | 'direct'\n\n/**\n * The types of origins accepted.\n */\nexport type Origin = string | RegExp\n\n/**\n * A message sent from the iframe to the parent requesting a method be called.\n */\nexport type RequestMethodCallMessage = {\n  id: string\n\n  method: string\n  params: any[]\n\n  // For signer messages.\n  chainId?: string\n  signerType?: SignerType\n  /**\n   * @deprecated Backwards compatibility.\n   */\n  signType?: SignerType\n\n  // For internal messages.\n  internal?: boolean\n}\n\nexport type RequestMethodCallMessageNoId = Omit<RequestMethodCallMessage, 'id'>\n\n/**\n * A message sent from the parent to the iframe with the result of a method\n * call.\n */\nexport type MethodCallResultMessage<T = any> = {\n  id: string\n} & (\n  | {\n      type: 'success'\n      response: T\n      error?: never\n    }\n  | {\n      type: 'error'\n      error: string\n      response?: never\n    }\n)\n\nexport type MethodCallResultMessageNoId<T = any> = Omit<\n  MethodCallResultMessage<T>,\n  'id'\n>\n\n/**\n * The result with metadata from calling a parent method.\n */\nexport type CalledParentMethodResult<T> = {\n  /**\n   * The parent's result for the requested method.\n   */\n  result: T\n  /**\n   * The origin of the parent response message, which should be the parent's\n   * origin. This is pulled directly from the `MessageEvent`.\n   */\n  origin: string\n}\n\n/**\n * The override handler that throws an error, defaulting to \"Handled by outer\n * wallet.\"\n */\nexport type OverrideHandlerError = {\n  type: 'error'\n  error?: string\n}\n\n/**\n * The override handler that returns a specific value.\n */\nexport type OverrideHandlerSuccess = {\n  type: 'success'\n  value?: unknown\n}\n\n/**\n * The override handler that calls the method normally.\n */\nexport type OverrideHandlerCall = {\n  type: 'call'\n}\n\n/**\n * An override handler defines how a message from the iframe should be handled\n * by the parent and is called with the original method's parameters. This is\n * set when listening. If nothing is returned from an override handler, an error\n * will be thrown with the message \"Handled by parent.\"\n */\nexport type OverrideHandler =\n  | OverrideHandlerError\n  | OverrideHandlerSuccess\n  | OverrideHandlerCall\n  | undefined\n  | void\n\n/**\n * Object containing override handlers for methods.\n */\nexport type Overrides = Record<\n  string,\n  (...params: any[]) => OverrideHandler | Promise<OverrideHandler> | undefined\n>\n\n/**\n * Options passed when setting up listening by the parent.\n */\nexport type ListenOptions = {\n  /**\n   * The iframe HTML element to listen to.\n   */\n  iframe: HTMLIFrameElement\n  /**\n   * The client or object whose methods to call.\n   */\n  target: Record<string, any>\n  /**\n   * A function to retrieve the offline direct signer.\n   */\n  getOfflineSignerDirect: (\n    chainId: string\n  ) => OfflineDirectSigner | Promise<OfflineDirectSigner>\n  /**\n   * A function to retrieve the offline amino signer.\n   */\n  getOfflineSignerAmino: (\n    chainId: string\n  ) => OfflineAminoSigner | Promise<OfflineAminoSigner>\n  /**\n   * Overrides applied to non-signer message requests.\n   */\n  nonSignerOverrides?:\n    | Overrides\n    | (() => Overrides)\n    | (() => Promise<Overrides>)\n  /**\n   * Overrides applied to signer message requests.\n   */\n  signerOverrides?:\n    | Overrides\n    | ((chainId: string) => Overrides)\n    | ((chainId: string) => Promise<Overrides>)\n  /**\n   * Restrict iframe origins that are allowed to connect to this listening\n   * instance of Cosmiframe. If undefined or empty, all origins are allowed.\n   *\n   * It is safe to allow all origins since the current window is the listening\n   * parent and is responsible for handling signing requests from the iframe.\n   * The iframe, on the other hand, should not trust us.\n   */\n  origins?: Origin[]\n  /**\n   * Optionally set a name and imageUrl that represent the parent window to be\n   * shown by the iframe.\n   */\n  metadata?: ParentMetadata\n}\n\nexport type ParentMetadata = {\n  name?: string\n  imageUrl?: string\n}\n\n/**\n * Internal methods.\n */\nexport enum InternalMethod {\n  IsCosmiframe = 'isCosmiframe',\n  GetMetadata = 'getMetadata',\n}\n","import { Keplr, SecretUtils } from '@keplr-wallet/types'\n\nimport { CosmiframeTimeoutError } from './error'\nimport {\n  CosmiframeAminoSigner,\n  CosmiframeDirectSigner,\n  CosmiframeEitherSigner,\n} from './signers'\nimport {\n  CalledParentMethodResult,\n  InternalMethod,\n  ListenOptions,\n  MethodCallResultMessage,\n  Origin,\n  ParentMetadata,\n  RequestMethodCallMessage,\n} from './types'\nimport {\n  UNSAFE_ALLOW_ANY_ORIGIN,\n  callParentMethod,\n  isInIframe,\n  isOriginAllowed,\n  processOverrideHandler,\n} from './utils'\n\nexport class Cosmiframe {\n  /**\n   * Parent origins we are allowed to communicate with.\n   */\n  #allowedOrigins: Origin[]\n\n  /**\n   * Proxy object that can be used to call methods on the parent frame. This\n   * serves as a passthrough and is a convenient alternative to using\n   * `callParentMethod`. This should be used by the iframe.\n   *\n   * For example:\n   *\n   * const cosmiframe = new Cosmiframe()\n   * const accounts = await cosmiframe.p.getAccounts()\n   */\n  public p: { [key: string]: <T = any>(...params: any[]) => Promise<T> }\n\n  constructor(\n    /**\n     * List of allowed parent origins.\n     *\n     * In order to allow all origins, you must explicitly pass in the string\n     * `UNSAFE_ALLOW_ANY_ORIGIN`. Do not do this. It is very unsafe.\n     */\n    allowedParentOrigins: Origin[]\n  ) {\n    if (!allowedParentOrigins.length) {\n      throw new Error('You must explicitly allow parent origins.')\n    }\n\n    if (allowedParentOrigins.includes('*')) {\n      throw new Error(\n        'It is very unsafe to allow all origins because a controlling app has the power to manipulate messages before they are signed. If you really want to do this, pass in `UNSAFE_ALLOW_ANY_ORIGIN`.'\n      )\n    }\n\n    this.#allowedOrigins = allowedParentOrigins.includes(\n      UNSAFE_ALLOW_ANY_ORIGIN\n    )\n      ? ['*']\n      : [...allowedParentOrigins]\n\n    this.p = new Proxy(\n      {\n        // `getEnigmaUtils` is expected to return an object with functions;\n        // override them with proxied functions instead. This follows Keplr's\n        // SecretUtils interface.\n        getEnigmaUtils: (chainId: string) =>\n          ({\n            getPubkey: () => this.p.getEnigmaPubKey(chainId),\n            decrypt: (...params) => this.p.enigmaDecrypt(chainId, ...params),\n            encrypt: (...params) => this.p.enigmaEncrypt(chainId, ...params),\n            getTxEncryptionKey: (...params) =>\n              this.p.getEnigmaTxEncryptionKey(chainId, ...params),\n          }) as SecretUtils,\n      } as any,\n      {\n        get: (obj, name) =>\n          // Override variables.\n          name in obj && typeof obj[name as keyof typeof obj] !== 'function'\n            ? obj[name as keyof typeof obj]\n            : // Override functions.\n              <T = any>(...params: any[]) =>\n                name in obj &&\n                typeof obj[name as keyof typeof obj] === 'function'\n                  ? (obj[name as keyof typeof obj] as (...params: any[]) => T)(\n                      ...params\n                    )\n                  : // Proxy to parent if not defined above.\n                    this.callParentMethod<T>({\n                      method: name.toString(),\n                      params,\n                    }).then(({ result }) => result),\n      }\n    )\n  }\n\n  /**\n   * Call a method on the parent frame, returning the result with metadata, such\n   * as the response message origin, which should be the parent frame origin.\n   * This should be used by the iframe.\n   */\n  callParentMethod<T = any>(\n    options: Pick<RequestMethodCallMessage, 'method' | 'params' | 'internal'>,\n    /**\n     * The timeout in milliseconds after which to reject the promise and stop\n     * listening if the parent has not responded. If undefined, no timeout.\n     *\n     * Defaults to no timeout.\n     */\n    timeout?: number\n  ): Promise<CalledParentMethodResult<T>> {\n    return callParentMethod<T>(options, this.#allowedOrigins, timeout)\n  }\n\n  /**\n   * Returns whether or not Cosmiframe is ready to use, meaning all of these are\n   * true:\n   * - The current app is being used in an iframe.\n   * - The parent window is running Cosmiframe.\n   * - The parent window is one of the allowed origins.\n   *\n   * If ready to use, this returns the origin of the parent frame that\n   * acknowledged the request. If no origin is set for some reason, this returns\n   * true. Otherwise, this returns false.\n   *\n   * This should be used by the iframe.\n   */\n  async isReady(): Promise<string | boolean> {\n    if (!isInIframe()) {\n      return false\n    }\n\n    try {\n      const { origin, result } = await this.callParentMethod<boolean>(\n        {\n          internal: true,\n          method: InternalMethod.IsCosmiframe,\n          params: [],\n        },\n        // If the parent is listening, it should respond immediately, so a\n        // short timeout should suffice.\n        500\n      )\n\n      return origin || result\n    } catch (err) {\n      // If the parent has not responded, assume it is not ready. Otherwise,\n      // rethrow the error.\n      if (err instanceof CosmiframeTimeoutError) {\n        return false\n      }\n\n      throw err\n    }\n  }\n\n  /**\n   * Returns the metadata set by the parent when it started listening. This\n   * should be used by the iframe to display information about the parent.\n   */\n  async getMetadata(): Promise<ParentMetadata | null> {\n    return (\n      await this.callParentMethod<ParentMetadata | null>(\n        {\n          internal: true,\n          method: InternalMethod.GetMetadata,\n          params: [],\n        },\n        // If the parent is listening, it should respond immediately, so a short\n        // timeout should suffice.\n        500\n      )\n    ).result\n  }\n\n  /**\n   * Get client that conforms to Keplr's interface.\n   */\n  getKeplrClient(): Keplr {\n    const proxy = new Proxy(\n      {\n        version: 'cosmiframe',\n        mode: 'extension',\n        defaultOptions: {},\n        getOfflineSigner: this.getOfflineSigner.bind(this),\n        getOfflineSignerOnlyAmino: this.getOfflineSignerAmino.bind(this),\n        getOfflineSignerAuto: (chainId) =>\n          Promise.resolve(this.getOfflineSigner(chainId)),\n        // `getEnigmaUtils` is expected to return an object with functions;\n        // override them with proxied functions instead.\n        getEnigmaUtils: (chainId: string) => ({\n          getPubkey: () => proxy.getEnigmaPubKey(chainId),\n          decrypt: (...params) => proxy.enigmaDecrypt(chainId, ...params),\n          encrypt: (...params) => proxy.enigmaEncrypt(chainId, ...params),\n          getTxEncryptionKey: (...params) =>\n            proxy.getEnigmaTxEncryptionKey(chainId, ...params),\n        }),\n      } as Partial<Keplr>,\n      {\n        get: (obj, name) =>\n          // Override variables.\n          name in obj && typeof obj[name as keyof typeof obj] !== 'function'\n            ? obj[name as keyof typeof obj]\n            : // Override functions.\n              <T = any>(...params: any[]) =>\n                name in obj &&\n                typeof obj[name as keyof typeof obj] === 'function'\n                  ? (obj[name as keyof typeof obj] as (...params: any[]) => T)(\n                      ...params\n                    )\n                  : // Proxy to parent if not defined above.\n                    this.callParentMethod<T>({\n                      method: name.toString(),\n                      params,\n                    }).then(({ result }) => result),\n      }\n    ) as Keplr\n\n    return proxy\n  }\n\n  /**\n   * Get an offline signer with both direct and amino sign functions that\n   * forwards requests to the parent frame. The parent frame must be listening\n   * (using the `listen` function). This should be used by the iframe.\n   */\n  getOfflineSigner(chainId: string): CosmiframeEitherSigner {\n    return new CosmiframeEitherSigner(chainId, this.#allowedOrigins)\n  }\n\n  /**\n   * Get an offline amino signer that forwards requests to the parent frame. The\n   * parent frame must be listening (using the `listen` function). This should\n   * be used by the iframe.\n   */\n  getOfflineSignerAmino(chainId: string): CosmiframeAminoSigner {\n    return new CosmiframeAminoSigner(chainId, this.#allowedOrigins)\n  }\n\n  /**\n   * Get an offline direct signer that forwards requests to the parent frame.\n   * The parent frame must be listening (using the `listen` function). This\n   * should be used by the iframe.\n   */\n  getOfflineSignerDirect(chainId: string): CosmiframeDirectSigner {\n    return new CosmiframeDirectSigner(chainId, this.#allowedOrigins)\n  }\n\n  /**\n   * Listen for requests from the provided iframe. This should be used by the\n   * parent. Returns a function that can be called to stop listening.\n   */\n  static listen(options: ListenOptions): () => void {\n    const {\n      iframe,\n      target,\n      getOfflineSignerDirect,\n      getOfflineSignerAmino,\n      nonSignerOverrides,\n      signerOverrides,\n      origins: _origins,\n      metadata,\n    } = options\n\n    const origins = _origins?.length ? _origins : ['*']\n\n    const internalMethods: Record<InternalMethod, (...params: any[]) => any> = {\n      [InternalMethod.IsCosmiframe]: () => true,\n      [InternalMethod.GetMetadata]: () => metadata || null,\n    }\n\n    const listener = async ({\n      source,\n      origin,\n      data,\n    }: MessageEvent<RequestMethodCallMessage | string>) => {\n      // Verify iframe window exists.\n      if (!iframe.contentWindow) {\n        throw new Error('Iframe contentWindow does not exist.')\n      }\n\n      // Verify event is coming from the iframe.\n      if (source !== iframe.contentWindow) {\n        return\n      }\n\n      // Verify origin is allowed.\n      if (!isOriginAllowed(origins, origin)) {\n        return\n      }\n\n      // Verify message contains required fields.\n      if (\n        !data ||\n        typeof data !== 'object' ||\n        !('id' in data) ||\n        !('method' in data) ||\n        !('params' in data)\n      ) {\n        return\n      }\n\n      const { id, params, chainId, signType, internal } = data\n      let { method, signerType } = data\n\n      // Backwards compatibility.\n      signerType ||= signType\n      method = method.replace(/^signer:/, '')\n\n      let msg: Omit<MethodCallResultMessage, 'id'> | undefined\n      try {\n        if (internal) {\n          if (\n            typeof internalMethods[method as keyof typeof internalMethods] !==\n            'function'\n          ) {\n            throw new Error(`Unknown internal method: ${method}`)\n          }\n\n          const response = await (\n            internalMethods[method as keyof typeof internalMethods] as (\n              ...params: any[]\n            ) => any\n          )(...params)\n\n          msg = {\n            type: 'success',\n            response,\n          }\n        } else if (signerType) {\n          if (!chainId) {\n            throw new Error('Missing chainId in signer message request')\n          }\n\n          // Try signer override method.\n          const overrides =\n            typeof signerOverrides === 'function'\n              ? await signerOverrides(chainId)\n              : signerOverrides\n          if (overrides && method in overrides) {\n            const handledMsg = processOverrideHandler(\n              await overrides[method](...params)\n            )\n            if (handledMsg) {\n              msg = handledMsg\n            }\n          }\n\n          // If override does not handle it, call the original method.\n          if (!msg) {\n            const signer =\n              signerType === 'direct'\n                ? await getOfflineSignerDirect(chainId)\n                : await getOfflineSignerAmino(chainId)\n            if (\n              !(method in signer) ||\n              typeof signer[method as keyof typeof signer] !== 'function'\n            ) {\n              throw new Error(\n                `No ${signerType} signer method '${method}' for chain ID '${chainId}'.`\n              )\n            }\n\n            const response = await (\n              signer[method as keyof typeof signer] as (...params: any[]) => any\n            )(...params)\n\n            msg = {\n              type: 'success',\n              response,\n            }\n          }\n        } else {\n          // Try override method.\n          const overrides =\n            typeof nonSignerOverrides === 'function'\n              ? await nonSignerOverrides()\n              : nonSignerOverrides\n\n          if (overrides && method in overrides) {\n            const handledMsg = processOverrideHandler(\n              await overrides[method](...params)\n            )\n            if (handledMsg) {\n              msg = handledMsg\n            }\n          }\n\n          // If override does not handle it, call the original method.\n          if (!msg) {\n            if (!(method in target) || typeof target[method] !== 'function') {\n              throw new Error(`No method '${method}' on target.`)\n            }\n\n            const response = await target[method](...params)\n\n            msg = {\n              type: 'success',\n              response,\n            }\n          }\n        }\n      } catch (err) {\n        msg = {\n          type: 'error',\n          error: err instanceof Error ? err.message : `${err}`,\n        }\n      }\n\n      // Send back to same origin.\n      iframe.contentWindow?.postMessage(\n        {\n          ...msg,\n          id,\n        },\n        origin\n      )\n    }\n\n    // Listen.\n    window.addEventListener('message', listener)\n\n    // Return a function to stop listening.\n    return () => window.removeEventListener('message', listener)\n  }\n}\n"],"mappings":"0iBAAO,IAAMA,EAAN,MAAMA,UAA+BC,KAAAA,CAC1CC,YAAYC,EAAiB,CAC3B,MAAMA,CAAAA,EACN,KAAKC,KAAO,wBACd,CACF,EAL4CH,EAAAA,EAAAA,0BAArC,IAAMD,EAANK,ECAP,OAASC,MAAMC,OAAc,OAetB,IAAMC,EAA0B,0BAO1BC,EAAmBC,EAAA,CAC9BC,EACAC,EAOAC,IAEA,IAAIC,QAAqC,CAACC,EAASC,IAAAA,CACjD,IAAIC,EAA2B,KACzBC,EAAKC,GAAAA,EAILC,EAAWV,EAAA,CAAC,CAAEW,OAAAA,EAAQC,OAAAA,EAAQC,KAAAA,CAAI,IAAgB,CAIpD,CAACC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,IACZ,OAAOA,EAAO1D,CAAAA,GAAmC,WAEjD,MAAM,IAAIpB,MACR,MAAMsE,CAAAA,mBAA6BlD,CAAAA,mBAAyBd,CAAAA,IAAW,EAQ3EkE,EAAM,CACJC,KAAM,UACNC,SANe,MACfI,EAAO1D,CAAAA,EAA8B,GAClCV,CAAAA,CAKL,CACF,CACF,KAAO,CAEL,IAAMiE,EACJ,OAAOnB,GAAuB,WAC1B,MAAMA,EAAAA,EACNA,EAEN,GAAImB,GAAavD,KAAUuD,EAAW,CACpC,IAAMC,EAAaC,EACjB,MAAMF,EAAUvD,CAAAA,EAAO,GAAIV,CAAAA,CAAAA,EAEzBkE,IACFJ,EAAMI,EAEV,CAGA,GAAI,CAACJ,EAAK,CACR,GAAI,EAAEpD,KAAUmC,IAAW,OAAOA,EAAOnC,CAAAA,GAAY,WACnD,MAAM,IAAIpB,MAAM,cAAcoB,CAAAA,cAAoB,EAKpDoD,EAAM,CACJC,KAAM,UACNC,SAJe,MAAMnB,EAAOnC,CAAAA,EAAO,GAAIV,CAAAA,CAKzC,CACF,CACF,CACF,OAASuB,EAAK,CACZuC,EAAM,CACJC,KAAM,QACNM,MAAO9C,aAAejC,MAAQiC,EAAI+C,QAAU,GAAG/C,CAAAA,EACjD,CACF,CAGAqB,EAAOY,eAAee,YACpB,CACE,GAAGT,EACHJ,GAAAA,CACF,EACAvC,CAAAA,CAEJ,EAlJiB,YAqJjBqD,cAAOC,iBAAiB,UAAWrB,CAAAA,EAG5B,IAAMoB,OAAOE,oBAAoB,UAAWtB,CAAAA,CACrD,CACF,EAnZErE,EAAA,YAJWC,EAAAA,EAAAA,cAAN,IAAMA,EAAN2F","names":["CosmiframeTimeoutError","Error","constructor","message","name","_CosmiframeTimeoutError","v4","uuidv4","UNSAFE_ALLOW_ANY_ORIGIN","callParentMethod","__name","message","origins","timeout","Promise","resolve","reject","timeoutId","id","uuidv4","listener","origin","source","data","isOriginAllowed","window","parent","removeEventListener","clearTimeout","type","result","response","Error","error","addEventListener","postMessage","err","setTimeout","CosmiframeTimeoutError","processOverrideHandler","handler","value","isInIframe","self","allowedOrigins","some","allowed","RegExp","test","_allowedOrigins","CosmiframeDirectSigner","constructor","chainId","allowedParentOrigins","__privateAdd","__privateSet","getAccounts","callParentMethod","method","params","signerType","__privateGet","result","signDirect","signerAddress","signDoc","_CosmiframeDirectSigner","CosmiframeAminoSigner","signAmino","_CosmiframeAminoSigner","CosmiframeEitherSigner","_CosmiframeEitherSigner","InternalMethod","_allowedOrigins","Cosmiframe","constructor","allowedParentOrigins","__privateAdd","p","length","Error","includes","__privateSet","UNSAFE_ALLOW_ANY_ORIGIN","Proxy","getEnigmaUtils","chainId","getPubkey","getEnigmaPubKey","decrypt","params","enigmaDecrypt","encrypt","enigmaEncrypt","getTxEncryptionKey","getEnigmaTxEncryptionKey","get","obj","name","callParentMethod","method","toString","then","result","options","timeout","__privateGet","isReady","isInIframe","origin","internal","InternalMethod","IsCosmiframe","err","CosmiframeTimeoutError","getMetadata","GetMetadata","getKeplrClient","proxy","version","mode","defaultOptions","getOfflineSigner","bind","getOfflineSignerOnlyAmino","getOfflineSignerAmino","getOfflineSignerAuto","Promise","resolve","CosmiframeEitherSigner","CosmiframeAminoSigner","getOfflineSignerDirect","CosmiframeDirectSigner","listen","iframe","target","nonSignerOverrides","signerOverrides","origins","_origins","metadata","internalMethods","listener","__name","source","data","contentWindow","isOriginAllowed","id","signType","signerType","replace","msg","type","response","overrides","handledMsg","processOverrideHandler","signer","error","message","postMessage","window","addEventListener","removeEventListener","_Cosmiframe"]}