{"version":3,"file":"app-client.mjs","names":[],"sources":["../../src/types/app-client.ts"],"sourcesContent":["import algosdk, { Address } from 'algosdk'\nimport { Buffer } from 'buffer'\nimport {\n  callApp,\n  compileTeal,\n  createApp,\n  getAppBoxNames,\n  getAppBoxValue,\n  getAppBoxValueFromABIType,\n  getAppGlobalState,\n  getAppLocalState,\n  updateApp,\n} from '../app'\nimport { deployApp, getCreatorAppsByName, performTemplateSubstitution, replaceDeployTimeControlParams } from '../app-deploy'\nimport { Config } from '../config'\nimport { legacySendTransactionBridge } from '../transaction/legacy-bridge'\nimport { encodeTransactionNote, getSenderAddress } from '../transaction/transaction'\nimport { asJson, binaryStartsWith } from '../util'\nimport { TransactionSignerAccount } from './account'\nimport { type AlgorandClient } from './algorand-client'\nimport { AlgoAmount } from './amount'\nimport {\n  ABIAppCallArg,\n  ABIAppCallArgs,\n  ABIReturn,\n  AppCallArgs,\n  AppCallTransactionResult,\n  AppCallType,\n  AppCompilationResult,\n  AppMetadata,\n  AppReference,\n  AppReturn,\n  AppState,\n  AppStorageSchema,\n  BoxName,\n  DELETABLE_TEMPLATE_NAME,\n  AppLookup as LegacyAppLookup,\n  OnSchemaBreak,\n  OnUpdate,\n  RawAppCallArgs,\n  SendAppTransactionResult,\n  TealTemplateParams,\n  UPDATABLE_TEMPLATE_NAME,\n} from './app'\nimport {\n  ABIStruct,\n  Arc56Contract,\n  Arc56Method,\n  getABIDecodedValue,\n  getABIEncodedValue,\n  getABITupleFromABIStruct,\n  getArc56Method,\n  getArc56ReturnValue,\n  ProgramSourceInfo,\n  StorageKey,\n  StorageMap,\n} from './app-arc56'\nimport { AppLookup } from './app-deployer'\nimport { AppManager, BoxIdentifier } from './app-manager'\nimport { AppSpec, arc32ToArc56 } from './app-spec'\nimport {\n  AppCallMethodCall,\n  AppCallParams,\n  AppDeleteMethodCall,\n  AppDeleteParams,\n  AppMethodCall,\n  AppMethodCallTransactionArgument,\n  AppUpdateMethodCall,\n  AppUpdateParams,\n  CommonAppCallParams,\n  PaymentParams,\n} from './composer'\nimport { Expand } from './expand'\nimport { EventType } from './lifecycle-events'\nimport { LogicError } from './logic-error'\nimport { SendParams, SendTransactionFrom, SendTransactionParams, TransactionNote } from './transaction'\nimport ABIMethod = algosdk.ABIMethod\nimport ABIMethodParams = algosdk.ABIMethodParams\nimport ABIType = algosdk.ABIType\nimport ABIValue = algosdk.ABIValue\nimport Algodv2 = algosdk.Algodv2\nimport AtomicTransactionComposer = algosdk.AtomicTransactionComposer\nimport getApplicationAddress = algosdk.getApplicationAddress\nimport Indexer = algosdk.Indexer\nimport OnApplicationComplete = algosdk.OnApplicationComplete\nimport SourceMap = algosdk.ProgramSourceMap\nimport SuggestedParams = algosdk.SuggestedParams\nimport TransactionSigner = algosdk.TransactionSigner\n\n/** The maximum opcode budget for a simulate call as per https://github.com/algorand/go-algorand/blob/807b29a91c371d225e12b9287c5d56e9b33c4e4c/ledger/simulation/trace.go#L104 */\nconst MAX_SIMULATE_OPCODE_BUDGET = 20_000 * 16\n\n/** Configuration to resolve app by creator and name `getCreatorAppsByName` */\nexport type ResolveAppByCreatorAndNameBase = {\n  /** The address of the app creator account to resolve the app by */\n  creatorAddress: Address | string\n  /** The optional name override to resolve the app by within the creator account (default: uses the name in the ABI contract) */\n  name?: string\n  /** The mechanism to find an existing app instance metadata for the given creator and name; either:\n   *  * An indexer instance to search the creator account apps; or\n   *  * The cached value of the existing apps for the given creator from `getCreatorAppsByName`\n   */\n  findExistingUsing: Indexer | LegacyAppLookup\n}\n\n/** Configuration to resolve app by creator and name `getCreatorAppsByName` */\nexport type ResolveAppByCreatorAndName = ResolveAppByCreatorAndNameBase & {\n  /** How the app ID is resolved, either by `'id'` or `'creatorAndName'`; must be `'creatorAndName'` if you want to use `deploy` */\n  resolveBy: 'creatorAndName'\n}\n\n/** Configuration to resolve app by ID */\nexport interface ResolveAppByIdBase {\n  /** The id of an existing app to call using this client, or 0 if the app hasn't been created yet */\n  id: number | bigint\n  /** The optional name to use to mark the app when deploying `ApplicationClient.deploy` (default: uses the name in the ABI contract) */\n  name?: string\n}\n\nexport interface ResolveAppById extends ResolveAppByIdBase {\n  /** How the app ID is resolved, either by `'id'` or `'creatorAndName'`; must be `'creatorAndName'` if you want to use `deploy` */\n  resolveBy: 'id'\n}\n\n/** The details of an AlgoKit Utils deployed app */\nexport type AppDetailsBase = {\n  /** Default sender to use for transactions issued by this application client */\n  sender?: SendTransactionFrom\n  /** Default suggested params object to use */\n  params?: SuggestedParams\n  /** Optionally provide any deploy-time parameters to replace in the TEAL code; if specified here will get\n   * used in calls to `deploy`, `create` and `update` unless overridden in those calls\n   */\n  deployTimeParams?: TealTemplateParams\n}\n\n/** The details of an AlgoKit Utils deployed app */\nexport type AppDetails = AppDetailsBase & (ResolveAppById | ResolveAppByCreatorAndName)\n\n/** The details of an ARC-0032 app spec specified, AlgoKit Utils deployed app */\nexport type AppSpecAppDetailsBase = {\n  /** The ARC-0032 application spec as either:\n   *  * Parsed JSON `AppSpec`\n   *  * Raw JSON string\n   */\n  app: AppSpec | string\n}\n\n/** The details of an ARC-0032 app spec specified, AlgoKit Utils deployed app by id*/\nexport type AppSpecAppDetailsById = AppSpecAppDetailsBase & AppDetailsBase & ResolveAppByIdBase\n\n/** The details of an ARC-0032 app spec specified, AlgoKit Utils deployed app by creator and name*/\nexport type AppSpecAppDetailsByCreatorAndName = AppSpecAppDetailsBase & AppDetailsBase & ResolveAppByCreatorAndNameBase\n\n/** The details of an ARC-0032 app spec specified, AlgoKit Utils deployed app */\nexport type AppSpecAppDetails = AppSpecAppDetailsBase & AppDetails\n\n/** Core parameters to pass into ApplicationClient.deploy */\nexport interface AppClientDeployCoreParams {\n  /** The version of the contract, uses \"1.0\" by default */\n  version?: string\n  /** The optional sender to send the transaction from, will use the application client's default sender by default if specified */\n  sender?: SendTransactionFrom\n  /** Parameters to control transaction sending */\n  sendParams?: Omit<SendTransactionParams, 'skipSending' | 'skipWaiting'>\n  /** Whether or not to allow updates in the contract using the deploy-time updatability control if present in your contract.\n   * If this is not specified then it will automatically be determined based on the AppSpec definition\n   **/\n  allowUpdate?: boolean\n  /** Whether or not to allow deletes in the contract using the deploy-time deletability control if present in your contract.\n   * If this is not specified then it will automatically be determined based on the AppSpec definition\n   **/\n  allowDelete?: boolean\n  /** What action to perform if a schema break is detected */\n  onSchemaBreak?: 'replace' | 'fail' | 'append' | OnSchemaBreak\n  /** What action to perform if a TEAL update is detected */\n  onUpdate?: 'update' | 'replace' | 'append' | 'fail' | OnUpdate\n}\n\n/** Call interface parameters to pass into ApplicationClient.deploy */\nexport interface AppClientDeployCallInterfaceParams {\n  /** Any deploy-time parameters to replace in the TEAL code */\n  deployTimeParams?: TealTemplateParams\n  /** Any args to pass to any create transaction that is issued as part of deployment */\n  createArgs?: AppClientCallArgs\n  /** Override the on-completion action for the create call; defaults to NoOp */\n  createOnCompleteAction?: Exclude<AppCallType, 'clear_state'> | Exclude<OnApplicationComplete, OnApplicationComplete.ClearStateOC>\n  /** Any args to pass to any update transaction that is issued as part of deployment */\n  updateArgs?: AppClientCallArgs\n  /** Any args to pass to any delete transaction that is issued as part of deployment */\n  deleteArgs?: AppClientCallArgs\n}\n\n/** Parameters to pass into ApplicationClient.deploy */\nexport interface AppClientDeployParams extends AppClientDeployCoreParams, AppClientDeployCallInterfaceParams {\n  /** Any overrides for the storage schema to request for the created app; by default the schema indicated by the app spec is used. */\n  schema?: Partial<AppStorageSchema>\n}\n\nexport type AppClientCallRawArgs = RawAppCallArgs\n\nexport interface AppClientCallABIArgs extends Omit<ABIAppCallArgs, 'method'> {\n  /** If calling an ABI method then either the name of the method, or the ABI signature */\n  method: string\n}\n\n/** The arguments to pass to an Application Client smart contract call */\nexport type AppClientCallArgs = AppClientCallRawArgs | AppClientCallABIArgs\n\n/** Common (core) parameters to construct a ApplicationClient contract call */\nexport interface AppClientCallCoreParams {\n  /** The optional sender to send the transaction from, will use the application client's default sender by default if specified */\n  sender?: SendTransactionFrom\n  /** The transaction note for the smart contract call */\n  note?: TransactionNote\n  /** Parameters to control transaction sending */\n  sendParams?: SendTransactionParams\n}\n\n/** Parameters to construct a ApplicationClient contract call */\nexport type AppClientCallParams = AppClientCallArgs & AppClientCallCoreParams\n\n/** Parameters to construct a ApplicationClient clear state contract call */\nexport type AppClientClearStateParams = AppClientCallRawArgs & AppClientCallCoreParams\n\nexport interface AppClientCompilationParams {\n  /** Any deploy-time parameters to replace in the TEAL code */\n  deployTimeParams?: TealTemplateParams\n  /** Whether or not the contract should have deploy-time immutability control set, undefined = ignore */\n  updatable?: boolean\n  /** Whether or not the contract should have deploy-time permanence control set, undefined = ignore */\n  deletable?: boolean\n}\n\n/** On-complete action parameter for creating a contract using ApplicationClient */\nexport type AppClientCreateOnComplete = {\n  /** Override the on-completion action for the create call; defaults to NoOp */\n  onCompleteAction?: Exclude<AppCallType, 'clear_state'> | Exclude<OnApplicationComplete, OnApplicationComplete.ClearStateOC>\n}\n\n/** Parameters for creating a contract using ApplicationClient */\nexport type AppClientCreateParams = AppClientCallParams &\n  AppClientCompilationParams &\n  AppClientCreateOnComplete & {\n    /** Any overrides for the storage schema to request for the created app; by default the schema indicated by the app spec is used. */\n    schema?: Partial<AppStorageSchema>\n  }\n\n/** Parameters for updating a contract using ApplicationClient */\nexport type AppClientUpdateParams = AppClientCallParams & AppClientCompilationParams\n\n/** Parameters for funding an app account */\nexport interface FundAppAccountParams {\n  amount: AlgoAmount\n  /** The optional sender to send the transaction from, will use the application client's default sender by default if specified */\n  sender?: SendTransactionFrom\n  /** The transaction note for the smart contract call */\n  note?: TransactionNote\n  /** Parameters to control transaction sending */\n  sendParams?: SendTransactionParams\n}\n\n/** Source maps for an Algorand app */\nexport interface AppSourceMaps {\n  /** The source map of the approval program */\n  approvalSourceMap: SourceMapExport\n  /** The source map of the clear program */\n  clearSourceMap: SourceMapExport\n}\n\nexport interface SourceMapExport {\n  version: number\n  sources: string[]\n  names: string[]\n  mappings: string\n}\n\n/**\n * The result of asking an `AppClient` to compile a program.\n *\n * Always contains the compiled bytecode, and may contain the result of compiling TEAL (including sourcemap) if it was available.\n */\nexport interface AppClientCompilationResult extends Partial<AppCompilationResult> {\n  /** The compiled bytecode of the approval program, ready to deploy to algod */\n  approvalProgram: Uint8Array\n  /** The compiled bytecode of the clear state program, ready to deploy to algod */\n  clearStateProgram: Uint8Array\n}\n\n/**\n * Determines deploy time control (UPDATABLE, DELETABLE) value by inspecting application specification\n * @param approval TEAL Approval program, not the base64 version found on the appSpec\n * @param appSpec Application Specification\n * @param templateVariableName Template variable\n * @param callConfigKey Call config type\n * @returns true if applicable call config is found, false if not found or undefined if variable not present\n */\nfunction getDeployTimeControl(\n  approval: string,\n  appSpec: AppSpec,\n  templateVariableName: string,\n  callConfigKey: 'update_application' | 'delete_application',\n): boolean | undefined {\n  // variable not present, so unknown control value\n  if (!approval.includes(templateVariableName)) return undefined\n\n  // a bare call for specified CallConfig is present and configured\n  const bareCallConfig = appSpec.bare_call_config[callConfigKey]\n  if (!!bareCallConfig && bareCallConfig !== 'NEVER') return true\n\n  // an ABI call for specified CallConfig is present and configured\n  return Object.values(appSpec.hints).some((h) => {\n    const abiCallConfig = h.call_config[callConfigKey]\n    return !!abiCallConfig && abiCallConfig !== 'NEVER'\n  })\n}\n\n/** Parameters to create an app client */\nexport interface AppClientParams {\n  /** The ID of the app instance this client should make calls against. */\n  appId: bigint\n\n  /** The ARC-56 or ARC-32 application spec as either:\n   *  * Parsed JSON ARC-56 `Contract`\n   *  * Parsed JSON ARC-32 `AppSpec`\n   *  * Raw JSON string (in either ARC-56 or ARC-32 format)\n   */\n  appSpec: Arc56Contract | AppSpec | string\n\n  /** An `AlgorandClient` instance */\n  algorand: AlgorandClient\n\n  /**\n   * Optional override for the app name; used for on-chain metadata and lookups.\n   * Defaults to the ARC-32/ARC-56 app spec name\n   */\n  appName?: string\n  /** Optional address to use for the account to use as the default sender for calls. */\n  defaultSender?: Address | string\n  /** Optional signer to use as the default signer for default sender calls (if not specified then the signer will be resolved from `AlgorandClient`). */\n  defaultSigner?: TransactionSigner\n  /** Optional source map for the approval program */\n  approvalSourceMap?: SourceMap\n  /** Optional source map for the clear state program */\n  clearSourceMap?: SourceMap\n}\n\n/** Parameters to clone an app client */\nexport type CloneAppClientParams = Expand<Partial<Omit<AppClientParams, 'algorand' | 'appSpec'>>>\n\n/** onComplete parameter for a non-update app call */\nexport type CallOnComplete = {\n  /** On-complete of the call; defaults to no-op */\n  onComplete?: Exclude<OnApplicationComplete, OnApplicationComplete.UpdateApplicationOC>\n}\n\n/** AppClient common parameters for a bare app call */\nexport type AppClientBareCallParams = Expand<\n  Omit<CommonAppCallParams, 'appId' | 'sender' | 'onComplete'> & {\n    /** The address of the account sending the transaction, if undefined then the app client's defaultSender is used. */\n    sender?: Address | string\n  }\n>\n\n/** AppClient common parameters for an ABI method call */\nexport type AppClientMethodCallParams = Expand<\n  Omit<CommonAppCallParams, 'appId' | 'sender' | 'method' | 'args'> & {\n    /** The address of the account sending the transaction, if undefined then the app client's defaultSender is used. */\n    sender?: Address | string\n    /** The method name or method signature to call if an ABI call is being emitted\n     * @example Method name\n     * `my_method`\n     * @example Method signature\n     * `my_method(unit64,string)bytes`\n     */\n    method: string\n    /** Arguments to the ABI method, either:\n     * * An ABI value\n     * * An ARC-56 struct\n     * * A transaction with explicit signer\n     * * A transaction (where the signer will be automatically assigned)\n     * * An unawaited transaction (e.g. from algorand.createTransaction.transactionType())\n     * * Another method call (via method call params object)\n     * * undefined (this represents a placeholder for either a default argument or a transaction argument that is fulfilled by another method call argument)\n     */\n    args?: (ABIValue | ABIStruct | AppMethodCallTransactionArgument | undefined)[]\n  }\n>\n\n/** Parameters for funding an app account */\nexport type FundAppParams = Expand<\n  Omit<PaymentParams, 'receiver' | 'sender'> &\n    SendParams & {\n      /** The optional sender to send the transaction from, will use the application client's default sender by default if specified */\n      sender?: Address | string\n    }\n>\n\n/** Resolve an app client instance by looking up an app created by the given creator with the given name */\nexport type ResolveAppClientByCreatorAndName = Expand<\n  Omit<AppClientParams, 'appId'> & {\n    /** The address of the creator account for the app */\n    creatorAddress: Address | string\n    /** An optional cached app lookup that matches a name to on-chain details;\n     * either this is needed or indexer is required to be passed in to this `ClientManager` on construction.\n     */\n    appLookupCache?: AppLookup\n    /** Whether or not to ignore the `AppDeployer` lookup cache and force an on-chain lookup, default: use any cached value */\n    ignoreCache?: boolean\n  }\n>\n\n/** Resolve an app client instance by looking up the current network. */\nexport type ResolveAppClientByNetwork = Expand<Omit<AppClientParams, 'appId'>>\n\nconst BYTE_CBLOCK = 38\nconst INT_CBLOCK = 32\n\n/**\n * Get the offset of the last constant block at the beginning of the program\n * This value is used to calculate the program counter for an ARC56 program that has a pcOffsetMethod of \"cblocks\"\n *\n * @param program The program to parse\n * @returns The PC value of the opcode after the last constant block\n */\nfunction getConstantBlockOffset(program: Uint8Array) {\n  const bytes = [...program]\n\n  const programSize = bytes.length\n  bytes.shift() // remove version\n\n  /** The PC of the opcode after the bytecblock */\n  let bytecblockOffset: number | undefined\n\n  /** The PC of the opcode after the intcblock */\n  let intcblockOffset: number | undefined\n\n  while (bytes.length > 0) {\n    /** The current byte from the beginning of the byte array */\n    const byte = bytes.shift()!\n\n    // If the byte is a constant block...\n    if (byte === BYTE_CBLOCK || byte === INT_CBLOCK) {\n      const isBytecblock = byte === BYTE_CBLOCK\n\n      /** The byte following the opcode is the number of values in the constant block */\n      const valuesRemaining = bytes.shift()!\n\n      // Iterate over all the values in the constant block\n      for (let i = 0; i < valuesRemaining; i++) {\n        if (isBytecblock) {\n          /** The byte following the opcode is the length of the next element */\n          const length = bytes.shift()!\n          bytes.splice(0, length)\n        } else {\n          // intcblock is a uvarint, so we need to keep reading until we find the end (MSB is not set)\n          while ((bytes.shift()! & 0x80) !== 0) {\n            // Do nothing...\n          }\n        }\n      }\n\n      if (isBytecblock) bytecblockOffset = programSize - bytes.length - 1\n      else intcblockOffset = programSize - bytes.length - 1\n\n      if (bytes[0] !== BYTE_CBLOCK && bytes[0] !== INT_CBLOCK) {\n        // if the next opcode isn't a constant block, we're done\n        break\n      }\n    }\n  }\n\n  return Math.max(bytecblockOffset ?? 0, intcblockOffset ?? 0)\n}\n\n/** ARC-56/ARC-32 application client that allows you to manage calls and\n * state for a specific deployed instance of an app (with a known app ID). */\nexport class AppClient {\n  private _appId: bigint\n  private _appAddress: Address\n  private _appName: string\n  private _appSpec: Arc56Contract\n  private _algorand: AlgorandClient\n  private _defaultSender?: Address\n  private _defaultSigner?: TransactionSigner\n\n  private _approvalSourceMap: SourceMap | undefined\n  private _clearSourceMap: SourceMap | undefined\n\n  private _localStateMethods: (address: string | Address) => ReturnType<AppClient['getStateMethods']>\n  private _globalStateMethods: ReturnType<AppClient['getStateMethods']>\n  private _boxStateMethods: ReturnType<AppClient['getBoxMethods']>\n\n  private _paramsMethods: ReturnType<AppClient['getMethodCallParamsMethods']> & {\n    /** Interact with bare (raw) call parameters */ bare: ReturnType<AppClient['getBareParamsMethods']>\n  }\n  private _createTransactionsMethods: ReturnType<AppClient['getMethodCallCreateTransactionMethods']> & {\n    /** Interact with bare (raw) call transactions */ bare: ReturnType<AppClient['getBareCreateTransactionMethods']>\n  }\n  private _sendMethods: ReturnType<AppClient['getMethodCallSendMethods']> & {\n    /** Interact with bare (raw) calls */ bare: ReturnType<AppClient['getBareSendMethods']>\n  }\n  private _lastCompiled: { clear?: Uint8Array; approval?: Uint8Array }\n\n  /**\n   * Create a new app client.\n   * @param params The parameters to create the app client\n   * @returns The `AppClient` instance\n   * @example\n   * ```typescript\n   * const appClient = new AppClient({\n   *   appId: 12345678n,\n   *   appSpec: appSpec,\n   *   algorand: AlgorandClient.mainNet(),\n   * })\n   */\n  constructor(params: AppClientParams) {\n    this._appId = params.appId\n    this._appAddress = algosdk.getApplicationAddress(this._appId)\n    this._appSpec = AppClient.normaliseAppSpec(params.appSpec)\n    this._appName = params.appName ?? this._appSpec.name\n    this._algorand = params.algorand\n    this._algorand.registerErrorTransformer!(this.handleCallErrors)\n    this._defaultSender = typeof params.defaultSender === 'string' ? Address.fromString(params.defaultSender) : params.defaultSender\n    this._defaultSigner = params.defaultSigner\n    this._lastCompiled = {}\n\n    this._approvalSourceMap = params.approvalSourceMap\n    this._clearSourceMap = params.clearSourceMap\n    this._localStateMethods = (address: string | Address) =>\n      this.getStateMethods(\n        () => this.getLocalState(address),\n        () => this._appSpec.state.keys.local,\n        () => this._appSpec.state.maps.local,\n      )\n    this._globalStateMethods = this.getStateMethods(\n      () => this.getGlobalState(),\n      () => this._appSpec.state.keys.global,\n      () => this._appSpec.state.maps.global,\n    )\n    this._boxStateMethods = this.getBoxMethods()\n\n    this._paramsMethods = {\n      ...this.getMethodCallParamsMethods(),\n      /** Get parameters to define bare (raw) transactions to the current app */\n      bare: this.getBareParamsMethods(),\n    }\n    this._createTransactionsMethods = {\n      ...this.getMethodCallCreateTransactionMethods(),\n\n      /** Get transactions for bare (raw) calls to the current app */\n      bare: this.getBareCreateTransactionMethods(),\n    }\n    this._sendMethods = {\n      ...this.getMethodCallSendMethods(),\n\n      /** Send bare (raw) transactions to the current app */\n      bare: this.getBareSendMethods(),\n    }\n  }\n\n  /**\n   * Clone this app client with different params\n   *\n   * @param params The params to use for the the cloned app client. Omit a param to keep the original value. Set a param to override the original value. Setting to undefined will clear the original value.\n   * @returns A new app client with the altered params\n   * @example\n   * ```typescript\n   * const appClient2 = appClient.clone({ defaultSender: 'NEW_SENDER_ADDRESS' })\n   * ```\n   */\n  public clone(params: CloneAppClientParams) {\n    return new AppClient({\n      appId: this._appId,\n      appSpec: this._appSpec,\n      algorand: this._algorand,\n      appName: this._appName,\n      defaultSender: this._defaultSender,\n      defaultSigner: this._defaultSigner,\n      approvalSourceMap: this._approvalSourceMap,\n      clearSourceMap: this._clearSourceMap,\n      ...params,\n    })\n  }\n\n  /**\n   * Returns a new `AppClient` client, resolving the app by creator address and name\n   * using AlgoKit app deployment semantics (i.e. looking for the app creation transaction note).\n   * @param params The parameters to create the app client\n   * @returns The `AppClient` instance\n   * @example\n   * ```typescript\n   * const appClient = await AppClient.fromCreatorAndName({\n   *   creatorAddress: 'CREATOR_ADDRESS',\n   *   name: 'APP_NAME',\n   *   appSpec: appSpec,\n   *   algorand: AlgorandClient.mainNet(),\n   * })\n   */\n  public static async fromCreatorAndName(params: ResolveAppClientByCreatorAndName) {\n    const appSpec = AppClient.normaliseAppSpec(params.appSpec)\n    const appLookup =\n      params.appLookupCache ?? (await params.algorand.appDeployer.getCreatorAppsByName(params.creatorAddress, params.ignoreCache))\n    const appMetadata = appLookup.apps[params.appName ?? appSpec.name]\n    if (!appMetadata) {\n      throw new Error(`App not found for creator ${params.creatorAddress} and name ${params.appName ?? appSpec.name}`)\n    }\n    return new AppClient({\n      ...params,\n      algorand: params.algorand,\n      appId: appMetadata.appId,\n    })\n  }\n\n  /**\n   * Returns an `AppClient` instance for the current network based on\n   * pre-determined network-specific app IDs specified in the ARC-56 app spec.\n   *\n   * If no IDs are in the app spec or the network isn't recognised, an error is thrown.\n   * @param params The parameters to create the app client\n   * @returns The `AppClient` instance\n   * @example\n   * ```typescript\n   * const appClient = await AppClient.fromNetwork({\n   *   appSpec: appSpec,\n   *   algorand: AlgorandClient.mainNet(),\n   * })\n   */\n  public static async fromNetwork(params: ResolveAppClientByNetwork): Promise<AppClient> {\n    const network = await params.algorand.client.network()\n    const appSpec = AppClient.normaliseAppSpec(params.appSpec)\n    const networkNames = [network.genesisHash]\n    if (network.isLocalNet) networkNames.push('localnet')\n    if (network.isTestNet) networkNames.push('testnet')\n    if (network.isMainNet) networkNames.push('mainnet')\n    const availableAppSpecNetworks = Object.keys(appSpec.networks ?? {})\n    const networkIndex = availableAppSpecNetworks.findIndex((n) => networkNames.includes(n))\n\n    if (networkIndex === -1) {\n      throw new Error(`No app ID found for network ${asJson(networkNames)} in the app spec`)\n    }\n\n    const appId = BigInt(appSpec.networks![networkIndex].appID)\n    return new AppClient({ ...params, appId, appSpec })\n  }\n\n  /**\n   * Takes a string or parsed JSON object that could be ARC-32 or ARC-56 format and\n   * normalises it into a parsed ARC-56 contract object.\n   * @param spec The spec to normalise\n   * @returns The normalised ARC-56 contract object\n   * @example\n   * ```typescript\n   * const arc56AppSpec = AppClient.normaliseAppSpec(appSpec)\n   * ```\n   */\n  public static normaliseAppSpec(spec: Arc56Contract | AppSpec | string): Arc56Contract {\n    const parsedSpec = typeof spec === 'string' ? (JSON.parse(spec) as AppSpec | Arc56Contract) : spec\n    const appSpec = 'hints' in parsedSpec ? arc32ToArc56(parsedSpec) : parsedSpec\n    return appSpec\n  }\n\n  /** The ID of the app instance this client is linked to. */\n  public get appId() {\n    return this._appId\n  }\n\n  /** The app address of the app instance this client is linked to. */\n  public get appAddress() {\n    return this._appAddress\n  }\n\n  /** The name of the app (from the ARC-32 / ARC-56 app spec or override). */\n  public get appName() {\n    return this._appName\n  }\n\n  /** The ARC-56 app spec being used */\n  public get appSpec(): Arc56Contract {\n    return this._appSpec\n  }\n\n  /** A reference to the underlying `AlgorandClient` this app client is using. */\n  public get algorand(): AlgorandClient {\n    return this._algorand\n  }\n\n  /** Get parameters to create transactions for the current app.\n   *\n   * A good mental model for this is that these parameters represent a deferred transaction creation.\n   * @example Create a transaction in the future using Algorand Client\n   * ```typescript\n   * const myMethodCall = appClient.params.call({method: 'my_method', args: [123, 'hello']})\n   * // ...\n   * await algorand.send.AppMethodCall(myMethodCall)\n   * ```\n   * @example Define a nested transaction as an ABI argument\n   * ```typescript\n   * const myMethodCall = appClient.params.call({method: 'my_method', args: [123, 'hello']})\n   * await appClient.send.call({method: 'my_method2', args: [myMethodCall]})\n   * ```\n   */\n  public get params() {\n    return this._paramsMethods\n  }\n\n  /** Create transactions for the current app */\n  public get createTransaction() {\n    return this._createTransactionsMethods\n  }\n\n  /** Send transactions to the current app */\n  public get send() {\n    return this._sendMethods\n  }\n\n  /** Get state (local, global, box) from the current app */\n  public get state() {\n    return {\n      /**\n       * Methods to access local state for the current app\n       * @param address The address of the account to get the local state for\n       */\n      local: this._localStateMethods,\n      /**\n       * Methods to access global state for the current app\n       */\n      global: this._globalStateMethods,\n      /**\n       * Methods to access box storage for the current app\n       */\n      box: this._boxStateMethods,\n    }\n  }\n\n  /**\n   * Funds Algo into the app account for this app.\n   *\n   * An alias for `appClient.send.fundAppAccount(params)`.\n   * @param params The parameters for the funding transaction\n   * @returns The result of the funding\n   * @example\n   * ```typescript\n   * await appClient.fundAppAccount({ amount: algo(1) })\n   * ```\n   */\n  public async fundAppAccount(params: FundAppParams) {\n    return this.send.fundAppAccount(params)\n  }\n\n  /**\n   * Returns raw global state for the current app.\n   * @returns The global state\n   * @example\n   * ```typescript\n   * const globalState = await appClient.getGlobalState()\n   * ```\n   */\n  public async getGlobalState(): Promise<AppState> {\n    return await this._algorand.app.getGlobalState(this.appId)\n  }\n\n  /**\n   * Returns raw local state for the given account address.\n   * @param address The address of the account to get the local state for\n   * @returns The local state\n   * @example\n   * ```typescript\n   * const localState = await appClient.getLocalState('ACCOUNT_ADDRESS')\n   * ```\n   */\n  public async getLocalState(address: Address | string): Promise<AppState> {\n    return await this._algorand.app.getLocalState(this.appId, address)\n  }\n\n  /**\n   * Returns the names of all current boxes for the current app.\n   * @returns The names of the boxes\n   * @example\n   * ```typescript\n   * const boxNames = await appClient.getBoxNames()\n   * ```\n   */\n  public async getBoxNames(): Promise<BoxName[]> {\n    return await this._algorand.app.getBoxNames(this.appId)\n  }\n\n  /**\n   * Returns the value of the given box for the current app.\n   * @param name The identifier of the box to return\n   * @returns The current box value as a byte array\n   * @example\n   * ```typescript\n   * const boxValue = await appClient.getBoxValue('boxName')\n   * ```\n   */\n  public async getBoxValue(name: BoxIdentifier): Promise<Uint8Array> {\n    return await this._algorand.app.getBoxValue(this.appId, name)\n  }\n\n  /**\n   * Returns the value of the given box for the current app.\n   * @param name The identifier of the box to return\n   * @param type\n   * @returns The current box value as a byte array\n   * @example\n   * ```typescript\n   * const boxValue = await appClient.getBoxValueFromABIType('boxName', new ABIUintType(32))\n   * ```\n   */\n  public async getBoxValueFromABIType(name: BoxIdentifier, type: ABIType): Promise<ABIValue> {\n    return await this._algorand.app.getBoxValueFromABIType({\n      appId: this.appId,\n      boxName: name,\n      type,\n    })\n  }\n\n  /**\n   * Returns the values of all current boxes for the current app.\n   * Note: This will issue multiple HTTP requests (one per box) and it's not an atomic operation so values may be out of sync.\n   * @param filter Optional filter to filter which boxes' values are returned\n   * @returns The (name, value) pair of the boxes with values as raw byte arrays\n   * @example\n   * ```typescript\n   * const boxValues = await appClient.getBoxValues()\n   * ```\n   */\n  public async getBoxValues(filter?: (name: BoxName) => boolean): Promise<{ name: BoxName; value: Uint8Array }[]> {\n    const names = (await this.getBoxNames()).filter(filter ?? ((_) => true))\n    const values = await this._algorand.app.getBoxValues(\n      this.appId,\n      names.map((name) => name.nameRaw),\n    )\n    return names.map((name, i) => ({ name, value: values[i] }))\n  }\n\n  /**\n   * Returns the values of all current boxes for the current app decoded using an ABI Type.\n   * Note: This will issue multiple HTTP requests (one per box) and it's not an atomic operation so values may be out of sync.\n   * @param type The ABI type to decode the values with\n   * @param filter Optional filter to filter which boxes' values are returned\n   * @returns The (name, value) pair of the boxes with values as the ABI Value\n   * @example\n   * ```typescript\n   * const boxValues = await appClient.getBoxValuesFromABIType(new ABIUintType(32))\n   * ```\n   */\n  public async getBoxValuesFromABIType(type: ABIType, filter?: (name: BoxName) => boolean): Promise<{ name: BoxName; value: ABIValue }[]> {\n    const names = (await this.getBoxNames()).filter(filter ?? ((_) => true))\n    const values = await this._algorand.app.getBoxValuesFromABIType({\n      appId: this.appId,\n      boxNames: names.map((name) => name.nameRaw),\n      type,\n    })\n    return names.map((name, i) => ({ name, value: values[i] }))\n  }\n\n  /**\n   * Takes an error that may include a logic error from a call to the current app and re-exposes the\n   * error to include source code information via the source map and ARC-56 spec.\n   * @param e The error to parse\n   * @param isClearStateProgram Whether or not the code was running the clear state program (defaults to approval program)\n   * @returns The new error, or if there was no logic error or source map then the wrapped error with source details\n   */\n  public async exposeLogicError(e: Error, isClearStateProgram?: boolean): Promise<Error> {\n    const pcOffsetMethod = this._appSpec.sourceInfo?.[isClearStateProgram ? 'clear' : 'approval']?.pcOffsetMethod\n\n    let program: Uint8Array | undefined\n    if (pcOffsetMethod === 'cblocks') {\n      // TODO: Cache this if we deploy the app and it's not updateable\n      const appInfo = await this._algorand.app.getById(this.appId)\n      program = isClearStateProgram ? appInfo.clearStateProgram : appInfo.approvalProgram\n    }\n\n    return AppClient.exposeLogicError(e, this._appSpec, {\n      isClearStateProgram,\n      approvalSourceMap: this._approvalSourceMap,\n      clearSourceMap: this._clearSourceMap,\n      program,\n    })\n  }\n\n  /**\n   * Export the current source maps for the app.\n   * @returns The source maps\n   */\n  public exportSourceMaps(): AppSourceMaps {\n    if (!this._approvalSourceMap || !this._clearSourceMap) {\n      throw new Error(\n        \"Unable to export source maps; they haven't been loaded into this client - you need to call create, update, or deploy first\",\n      )\n    }\n\n    return {\n      approvalSourceMap: this._approvalSourceMap,\n      clearSourceMap: this._clearSourceMap,\n    }\n  }\n\n  /**\n   * Import source maps for the app.\n   * @param sourceMaps The source maps to import\n   */\n  public importSourceMaps(sourceMaps: AppSourceMaps) {\n    this._approvalSourceMap = new SourceMap(sourceMaps.approvalSourceMap)\n    this._clearSourceMap = new SourceMap(sourceMaps.clearSourceMap)\n  }\n\n  /**\n   * Returns the ABI Method spec for the given method string for the app represented by this application client instance\n   * @param methodNameOrSignature The method name or method signature to call if an ABI call is being emitted.\n   * e.g. `my_method` or `my_method(unit64,string)bytes`\n   * @returns A tuple with: [ARC-56 `Method`, algosdk `ABIMethod`]\n   */\n  public getABIMethod(methodNameOrSignature: string) {\n    return getArc56Method(methodNameOrSignature, this._appSpec)\n  }\n\n  /**\n   * Checks for decode errors on the SendAppTransactionResult and maps the return value to the specified type\n   * on the ARC-56 method, replacing the `return` property with the decoded type.\n   *\n   * If the return type is an ARC-56 struct then the struct will be returned.\n   *\n   * @param result The SendAppTransactionResult to be mapped\n   * @param method The method that was called\n   * @returns The smart contract response with an updated return value\n   */\n  public async processMethodCallReturn<\n    TReturn extends Uint8Array | ABIValue | ABIStruct | undefined,\n    TResult extends SendAppTransactionResult = SendAppTransactionResult,\n  >(result: Promise<TResult> | TResult, method: Arc56Method): Promise<Omit<TResult, 'return'> & AppReturn<TReturn>> {\n    const resultValue = await result\n    return { ...resultValue, return: getArc56ReturnValue(resultValue.return, method, this._appSpec.structs) }\n  }\n\n  /**\n   * Compiles the approval and clear state programs (if TEAL templates provided),\n   * performing any provided deploy-time parameter replacement and stores\n   * the source maps.\n   *\n   * If no TEAL templates provided it will use any byte code provided in the app spec.\n   *\n   * Will store any generated source maps for later use in debugging.\n   * @param compilation Any compilation parameters to use\n   * @returns The compiled code and any compilation results (including source maps)\n   */\n  public async compile(compilation?: AppClientCompilationParams) {\n    const result = await AppClient.compile(this._appSpec, this._algorand.app, compilation)\n\n    if (result.compiledApproval) {\n      this._approvalSourceMap = result.compiledApproval.sourceMap\n\n      this._lastCompiled.approval = result.compiledApproval.compiledBase64ToBytes\n    }\n    if (result.compiledClear) {\n      this._clearSourceMap = result.compiledClear.sourceMap\n      this._lastCompiled.clear = result.compiledClear.compiledBase64ToBytes\n    }\n\n    return result\n  }\n\n  /**\n   * Takes an error that may include a logic error from a call to the current app and re-exposes the\n   * error to include source code information via the source map and ARC-56 spec.\n   * @param e The error to parse\n   * @param appSpec The app spec for the app\n   * @param details Additional information to inform the error\n   * @returns The new error, or if there was no logic error or source map then the wrapped error with source details\n   */\n  public static exposeLogicError(\n    e: Error,\n    appSpec: Arc56Contract,\n    details: {\n      /** Whether or not the code was running the clear state program (defaults to approval program) */ isClearStateProgram?: boolean\n      /** Approval program source map */ approvalSourceMap?: SourceMap\n      /** Clear state program source map */ clearSourceMap?: SourceMap\n      /** program bytes */ program?: Uint8Array\n      /** ARC56 approval source info */ approvalSourceInfo?: ProgramSourceInfo\n      /** ARC56 clear source info */ clearSourceInfo?: ProgramSourceInfo\n    },\n  ): Error {\n    const { isClearStateProgram, approvalSourceMap, clearSourceMap, program } = details\n    const sourceMap = isClearStateProgram ? clearSourceMap : approvalSourceMap\n\n    const errorDetails = LogicError.parseLogicError(e)\n\n    // Return the error if we don't have a PC\n    if (errorDetails === undefined || errorDetails?.pc === undefined) return e\n\n    /** The PC value to find in the ARC56 SourceInfo */\n    let arc56Pc = errorDetails?.pc\n\n    const programSourceInfo = isClearStateProgram ? appSpec.sourceInfo?.clear : appSpec.sourceInfo?.approval\n\n    /** The offset to apply to the PC if using the cblocks pc offset method */\n    let cblocksOffset = 0\n\n    // If the program uses cblocks offset, then we need to adjust the PC accordingly\n    if (programSourceInfo?.pcOffsetMethod === 'cblocks') {\n      if (program === undefined) throw new Error('Program bytes are required to calculate the ARC56 cblocks PC offset')\n      cblocksOffset = getConstantBlockOffset(program)\n      arc56Pc = errorDetails.pc - cblocksOffset\n    }\n\n    // Find the source info for this PC and get the error message\n    const sourceInfo = programSourceInfo?.sourceInfo.find((s) => s.pc.includes(arc56Pc))\n    const errorMessage = sourceInfo?.errorMessage\n\n    // If we have the source we can display the TEAL in the error message\n    if (appSpec.source) {\n      let getLineForPc = (inputPc: number) => sourceMap?.getLocationForPc?.(inputPc)?.line\n\n      // If the SourceMap is not defined, we need to provide our own function for going from a PC to TEAL based on ARC56 SourceInfo[]\n      if (sourceMap === undefined) {\n        getLineForPc = (inputPc: number) => {\n          const teal = programSourceInfo?.sourceInfo.find((s) => s.pc.includes(inputPc - cblocksOffset))?.teal\n          if (teal === undefined) return undefined\n          return teal - 1\n        }\n      }\n      e = new LogicError(\n        errorDetails,\n        Buffer.from(isClearStateProgram ? appSpec.source.clear : appSpec.source.approval, 'base64')\n          .toString()\n          .split('\\n'),\n        getLineForPc,\n      )\n    }\n    if (errorMessage) {\n      const appId = asJson(e).match(/(?<=app=)\\d+/)?.[0] || ''\n      const txId = asJson(e).match(/(?<=transaction )\\S+(?=:)/)?.[0]\n      const error = new Error(`Runtime error when executing ${appSpec.name} (appId: ${appId}) in transaction ${txId}: ${errorMessage}`)\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n      ;(error as any).cause = e\n      return error\n    }\n\n    return e\n  }\n\n  /**\n   * Compiles the approval and clear state programs (if TEAL templates provided),\n   * performing any provided deploy-time parameter replacement and returns\n   * the compiled code and any compilation results (including source maps).\n   *\n   * If no TEAL templates provided it will use any byte code provided in the app spec.\n   *\n   * Will store any generated source maps for later use in debugging.\n   * @param appSpec The app spec for the app\n   * @param appManager The app manager to use for compilation\n   * @param compilation Any compilation parameters to use\n   * @returns The compiled code and any compilation results (including source maps)\n   */\n  public static async compile(\n    appSpec: Arc56Contract,\n    appManager: AppManager,\n    compilation?: AppClientCompilationParams,\n  ): Promise<AppClientCompilationResult> {\n    const { deployTimeParams, updatable, deletable } = compilation ?? {}\n\n    if (!appSpec.source) {\n      if (!appSpec.byteCode?.approval || !appSpec.byteCode?.clear) {\n        throw new Error(`Attempt to compile app ${appSpec.name} without source or byteCode`)\n      }\n\n      return {\n        approvalProgram: Buffer.from(appSpec.byteCode.approval, 'base64') as Uint8Array,\n        clearStateProgram: Buffer.from(appSpec.byteCode.clear, 'base64') as Uint8Array,\n      }\n    }\n\n    const approvalTemplate = Buffer.from(appSpec.source.approval, 'base64').toString('utf-8')\n    const compiledApproval = await appManager.compileTealTemplate(approvalTemplate, deployTimeParams, {\n      updatable,\n      deletable,\n    })\n\n    const clearTemplate = Buffer.from(appSpec.source.clear, 'base64').toString('utf-8')\n    const compiledClear = await appManager.compileTealTemplate(clearTemplate, deployTimeParams)\n\n    if (Config.debug) {\n      await Config.events.emitAsync(EventType.AppCompiled, {\n        sources: [\n          { compiledTeal: compiledApproval, appName: appSpec.name, fileName: 'approval' },\n          { compiledTeal: compiledClear, appName: appSpec.name, fileName: 'clear' },\n        ],\n      })\n    }\n\n    return {\n      approvalProgram: compiledApproval.compiledBase64ToBytes,\n      compiledApproval,\n      clearStateProgram: compiledClear.compiledBase64ToBytes,\n      compiledClear,\n    }\n  }\n\n  /**\n   * Returns ABI method arguments ready for a method call params object with default values populated\n   * and structs replaced with tuples.\n   *\n   * It does this by replacing any `undefined` values with the equivalent default value from the given ARC-56 app spec.\n   * @param methodNameOrSignature The method name or method signature to call if an ABI call is being emitted.\n   * e.g. `my_method` or `my_method(unit64,string)bytes`\n   * @param args The arguments to the method with `undefined` for any that should be populated with a default value\n   */\n  private async getABIArgsWithDefaultValues(\n    methodNameOrSignature: string,\n    args: AppClientMethodCallParams['args'] | undefined,\n    sender: Address | string,\n  ): Promise<AppMethodCall<CommonAppCallParams>['args']> {\n    const m = getArc56Method(methodNameOrSignature, this._appSpec)\n    return await Promise.all(\n      args?.map(async (a, i) => {\n        const arg = m.args[i]\n        if (!arg) {\n          throw new Error(`Unexpected arg at position ${i}. ${m.name} only expects ${m.args.length} args`)\n        }\n        if (a !== undefined) {\n          // If a struct then convert to tuple for the underlying call\n          return arg.struct && typeof a === 'object' && !Array.isArray(a)\n            ? getABITupleFromABIStruct(a as ABIStruct, this._appSpec.structs[arg.struct], this._appSpec.structs)\n            : (a as ABIValue | AppMethodCallTransactionArgument)\n        }\n        const defaultValue = arg.defaultValue\n        if (defaultValue) {\n          switch (defaultValue.source) {\n            case 'literal':\n              return getABIDecodedValue(\n                Buffer.from(defaultValue.data, 'base64'),\n                m.method.args[i].defaultValue?.type ?? m.method.args[i].type,\n                this._appSpec.structs,\n              ) as ABIValue\n            case 'method': {\n              const method = this.getABIMethod(defaultValue.data)\n              const result = await this.send.call({\n                method: defaultValue.data,\n                args: method.args.map(() => undefined),\n                sender,\n              })\n\n              if (result.return === undefined) {\n                throw new Error('Default value method call did not return a value')\n              }\n              if (\n                typeof result.return === 'object' &&\n                !(result.return instanceof Uint8Array) &&\n                !Array.isArray(result.return) &&\n                !(result.return instanceof Address)\n              ) {\n                return getABITupleFromABIStruct(result.return, this._appSpec.structs[method.returns.struct!], this._appSpec.structs)\n              }\n              return result.return\n            }\n            case 'local':\n            case 'global': {\n              const state = defaultValue.source === 'global' ? await this.getGlobalState() : await this.getLocalState(sender)\n              const value = Object.values(state).find((s) => s.keyBase64 === defaultValue.data)\n              if (!value) {\n                throw new Error(\n                  `Preparing default value for argument ${arg.name ?? `arg${i + 1}`} resulted in the failure: The key '${defaultValue.data}' could not be found in ${defaultValue.source} storage`,\n                )\n              }\n              return 'valueRaw' in value\n                ? (getABIDecodedValue(\n                    value.valueRaw,\n                    m.method.args[i].defaultValue?.type ?? m.method.args[i].type,\n                    this._appSpec.structs,\n                  ) as ABIValue)\n                : value.value\n            }\n            case 'box': {\n              const value = await this.getBoxValue(Buffer.from(defaultValue.data, 'base64'))\n              return getABIDecodedValue(\n                value,\n                m.method.args[i].defaultValue?.type ?? m.method.args[i].type,\n                this._appSpec.structs,\n              ) as ABIValue\n            }\n          }\n        }\n        if (!algosdk.abiTypeIsTransaction(arg.type)) {\n          throw new Error(`No value provided for required argument ${arg.name ?? `arg${i + 1}`} in call to method ${m.name}`)\n        }\n      }) ?? [],\n    )\n  }\n\n  private getBareParamsMethods() {\n    return {\n      /** Return params for an update call, including deploy-time TEAL template replacements and compilation if provided */\n      update: async (params?: AppClientBareCallParams & AppClientCompilationParams) => {\n        return this.getBareParams(\n          {\n            ...params,\n            ...(await this.compile(params)),\n          },\n          OnApplicationComplete.UpdateApplicationOC,\n        ) as AppUpdateParams\n      },\n      /** Return params for an opt-in call */\n      optIn: (params?: AppClientBareCallParams) => {\n        return this.getBareParams(params, OnApplicationComplete.OptInOC) as AppCallParams\n      },\n      /** Return params for a delete call */\n      delete: (params?: AppClientBareCallParams) => {\n        return this.getBareParams(params, OnApplicationComplete.DeleteApplicationOC) as AppDeleteParams\n      },\n      /** Return params for a clear state call */\n      clearState: (params?: AppClientBareCallParams) => {\n        return this.getBareParams(params, OnApplicationComplete.ClearStateOC) as AppCallParams\n      },\n      /** Return params for a close out call */\n      closeOut: (params?: AppClientBareCallParams) => {\n        return this.getBareParams(params, OnApplicationComplete.CloseOutOC) as AppCallParams\n      },\n      /** Return params for a call (defaults to no-op) */\n      call: (params?: AppClientBareCallParams & CallOnComplete) => {\n        return this.getBareParams(params, params?.onComplete ?? OnApplicationComplete.NoOpOC) as AppCallParams\n      },\n    }\n  }\n\n  private getBareCreateTransactionMethods() {\n    return {\n      /** Returns a transaction for an update call, including deploy-time TEAL template replacements and compilation if provided */\n      update: async (params?: AppClientBareCallParams & AppClientCompilationParams) => {\n        return this._algorand.createTransaction.appUpdate(await this.params.bare.update(params))\n      },\n      /** Returns a transaction for an opt-in call */\n      optIn: (params?: AppClientBareCallParams) => {\n        return this._algorand.createTransaction.appCall(this.params.bare.optIn(params))\n      },\n      /** Returns a transaction for a delete call */\n      delete: (params?: AppClientBareCallParams) => {\n        return this._algorand.createTransaction.appDelete(this.params.bare.delete(params))\n      },\n      /** Returns a transaction for a clear state call */\n      clearState: (params?: AppClientBareCallParams) => {\n        return this._algorand.createTransaction.appCall(this.params.bare.clearState(params))\n      },\n      /** Returns a transaction for a close out call */\n      closeOut: (params?: AppClientBareCallParams) => {\n        return this._algorand.createTransaction.appCall(this.params.bare.closeOut(params))\n      },\n      /** Returns a transaction for a call (defaults to no-op) */\n      call: (params?: AppClientBareCallParams & CallOnComplete) => {\n        return this._algorand.createTransaction.appCall(this.params.bare.call(params))\n      },\n    }\n  }\n\n  private getBareSendMethods() {\n    return {\n      /** Signs and sends an update call, including deploy-time TEAL template replacements and compilation if provided */\n      update: async (params?: AppClientBareCallParams & AppClientCompilationParams & SendParams) => {\n        const compiled = await this.compile(params)\n        return {\n          ...(await this._algorand.send.appUpdate(await this.params.bare.update(params))),\n          ...(compiled as Partial<AppCompilationResult>),\n        }\n      },\n      /** Signs and sends an opt-in call */\n      optIn: (params?: AppClientBareCallParams & SendParams) => {\n        return this._algorand.send.appCall(this.params.bare.optIn(params))\n      },\n      /** Signs and sends a delete call */\n      delete: (params?: AppClientBareCallParams & SendParams) => {\n        return this._algorand.send.appDelete(this.params.bare.delete(params))\n      },\n      /** Signs and sends a clear state call */\n      clearState: (params?: AppClientBareCallParams & SendParams) => {\n        return this._algorand.send.appCall(this.params.bare.clearState(params))\n      },\n      /** Signs and sends a close out call */\n      closeOut: (params?: AppClientBareCallParams & SendParams) => {\n        return this._algorand.send.appCall(this.params.bare.closeOut(params))\n      },\n      /** Signs and sends a call (defaults to no-op) */\n      call: (params?: AppClientBareCallParams & CallOnComplete & SendParams) => {\n        return this._algorand.send.appCall(this.params.bare.call(params))\n      },\n    }\n  }\n\n  private getMethodCallParamsMethods() {\n    return {\n      /**\n       * Return params for a payment transaction to fund the app account\n       * @param params The parameters for the fund app accont payment transaction\n       * @returns The parameters which can be used to create a fund app account payment transaction\n       */\n      fundAppAccount: (params: FundAppParams) => {\n        return {\n          ...params,\n          sender: this.getSender(params.sender),\n          signer: this.getSigner(params.sender, params.signer),\n          receiver: this.appAddress,\n        } satisfies PaymentParams\n      },\n      /**\n       * Return params for an update ABI call, including deploy-time TEAL template replacements and compilation if provided\n       * @param params The parameters for the update ABI method call\n       * @returns The parameters which can be used to create an update ABI method call\n       */\n      update: async (params: AppClientMethodCallParams & AppClientCompilationParams) => {\n        return (await this.getABIParams(\n          {\n            ...params,\n            ...(await this.compile(params)),\n          },\n          OnApplicationComplete.UpdateApplicationOC,\n        )) satisfies AppUpdateMethodCall\n      },\n      /**\n       * Return params for an opt-in ABI call\n       * @param params The parameters for the opt-in ABI method call\n       * @returns The parameters which can be used to create an opt-in ABI method call\n       */\n      optIn: async (params: AppClientMethodCallParams) => {\n        return (await this.getABIParams(params, OnApplicationComplete.OptInOC)) as AppCallMethodCall\n      },\n      /**\n       * Return params for an delete ABI call\n       * @param params The parameters for the delete ABI method call\n       * @returns The parameters which can be used to create a delete ABI method call\n       */\n      delete: async (params: AppClientMethodCallParams) => {\n        return (await this.getABIParams(params, OnApplicationComplete.DeleteApplicationOC)) as AppDeleteMethodCall\n      },\n      /** Return params for an close out ABI call\n       * @param params The parameters for the close out ABI method call\n       * @returns The parameters which can be used to create a close out ABI method call\n       */\n      closeOut: async (params: AppClientMethodCallParams) => {\n        return (await this.getABIParams(params, OnApplicationComplete.CloseOutOC)) as AppCallMethodCall\n      },\n      /** Return params for an ABI call\n       * @param params The parameters for the ABI method call\n       * @returns The parameters which can be used to create an ABI method call\n       */\n      call: async (params: AppClientMethodCallParams & CallOnComplete) => {\n        return (await this.getABIParams(params, params.onComplete ?? OnApplicationComplete.NoOpOC)) as AppCallMethodCall\n      },\n    }\n  }\n\n  private getMethodCallSendMethods() {\n    return {\n      /** Sign and send transactions for a payment transaction to fund the app account\n       * @param params The parameters for the fund app account payment transaction\n       * @returns The result of send the fund app account payment transaction\n       */\n      fundAppAccount: (params: FundAppParams & SendParams) => {\n        return this._algorand.send.payment(this.params.fundAppAccount(params))\n      },\n      /**\n       * Sign and send transactions for an update ABI call, including deploy-time TEAL template replacements and compilation if provided\n       * @param params The parameters for the update ABI method call\n       * @returns The result of sending the update ABI method call\n       */\n      update: async (params: AppClientMethodCallParams & AppClientCompilationParams & SendParams) => {\n        const compiled = await this.compile(params)\n        return {\n          ...(await this.processMethodCallReturn(\n            this._algorand.send.appUpdateMethodCall(await this.params.update({ ...params })),\n            getArc56Method(params.method, this._appSpec),\n          )),\n          ...(compiled as Partial<AppCompilationResult>),\n        }\n      },\n      /**\n       * Sign and send transactions for an opt-in ABI call\n       * @param params The parameters for the opt-in ABI method call\n       * @returns The result of sending the opt-in ABI method call\n       */\n      optIn: async (params: AppClientMethodCallParams & SendParams) => {\n        return this.processMethodCallReturn(\n          this._algorand.send.appCallMethodCall(await this.params.optIn(params)),\n          getArc56Method(params.method, this._appSpec),\n        )\n      },\n      /**\n       * Sign and send transactions for a delete ABI call\n       * @param params The parameters for the delete ABI method call\n       * @returns The result of sending the delete ABI method call\n       */\n      delete: async (params: AppClientMethodCallParams & SendParams) => {\n        return this.processMethodCallReturn(\n          this._algorand.send.appDeleteMethodCall(await this.params.delete(params)),\n          getArc56Method(params.method, this._appSpec),\n        )\n      },\n      /**\n       * Sign and send transactions for a close out ABI call\n       * @param params The parameters for the close out ABI method call\n       * @returns The result of sending the close out ABI method call\n       */\n      closeOut: async (params: AppClientMethodCallParams & SendParams) => {\n        return this.processMethodCallReturn(\n          this._algorand.send.appCallMethodCall(await this.params.closeOut(params)),\n          getArc56Method(params.method, this._appSpec),\n        )\n      },\n      /**\n       * Sign and send transactions for a call (defaults to no-op)\n       * @param params The parameters for the ABI method call\n       * @returns The result of sending the ABI method call\n       */\n      call: async (params: AppClientMethodCallParams & CallOnComplete & SendParams) => {\n        // Read-only call - do it via simulate\n        if (\n          (params.onComplete === OnApplicationComplete.NoOpOC || !params.onComplete) &&\n          getArc56Method(params.method, this._appSpec).method.readonly\n        ) {\n          const readonlyParams = {\n            ...params,\n          }\n\n          // Read-only calls do not require fees to be paid, as they are only simulated on the network.\n          // With maximum opcode budget provided, ensure_budget (and similar op-up utilities) won't need to create inner transactions,\n          // so fee coverage for op-up inner transactions does not need to be accounted for in readonly calls.\n          // If max_fee is provided, use it as static_fee, as there may still be inner transactions sent which need to be covered by the outermost transaction,\n          // even though ARC-22 specifies that readonly methods should not send inner transactions.\n          if (params.coverAppCallInnerTransactionFees && params.maxFee) {\n            readonlyParams.staticFee = params.maxFee\n            readonlyParams.extraFee = undefined\n          }\n\n          try {\n            const result = await this._algorand\n              .newGroup()\n              .addAppCallMethodCall(await this.params.call(readonlyParams))\n              .simulate({\n                allowUnnamedResources: params.populateAppCallResources ?? true,\n                // Simulate calls for a readonly method shouldn't invoke signing\n                skipSignatures: true,\n                // Simulate calls for a readonly method can use the max opcode budget\n                extraOpcodeBudget: MAX_SIMULATE_OPCODE_BUDGET,\n              })\n            return this.processMethodCallReturn(\n              {\n                ...result,\n                transaction: result.transactions.at(-1)!,\n                confirmation: result.confirmations.at(-1)!,\n                // eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain\n                return: (result.returns?.length ?? 0 > 0) ? result.returns?.at(-1)! : undefined,\n              } satisfies SendAppTransactionResult,\n              getArc56Method(params.method, this._appSpec),\n            )\n          } catch (e) {\n            const error = e as Error\n            // For read-only calls with max opcode budget, fee issues should be rare\n            // but we can still provide helpful error message if they occur\n            if (params.coverAppCallInnerTransactionFees && error && error.message && error.message.match(/fee ([\\w.]+\\s+)?too small/)) {\n              throw Error(`Fees were too small. You may need to increase the transaction maxFee.`, { cause: e })\n            }\n            throw e\n          }\n        }\n\n        return this.processMethodCallReturn(\n          this._algorand.send.appCallMethodCall(await this.params.call(params)),\n          getArc56Method(params.method, this._appSpec),\n        )\n      },\n    }\n  }\n\n  private getMethodCallCreateTransactionMethods() {\n    return {\n      /** Return transaction for a payment transaction to fund the app account\n       * @param params The parameters for the fund app account payment transaction\n       * @returns A transaction which can be used to fund the app account\n       */\n      fundAppAccount: (params: FundAppParams) => {\n        return this._algorand.createTransaction.payment(this.params.fundAppAccount(params))\n      },\n      /**\n       * Return transactions for an update ABI call, including deploy-time TEAL template replacements and compilation if provided\n       * @param params The parameters for the update ABI method call\n       * @returns The transactions which can be used to create an update ABI method call\n       */\n      update: async (params: AppClientMethodCallParams & AppClientCompilationParams) => {\n        return this._algorand.createTransaction.appUpdateMethodCall(await this.params.update(params))\n      },\n      /**\n       * Return transactions for an opt-in ABI call\n       * @param params The parameters for the opt-in ABI method call\n       * @returns The transactions which can be used to create an opt-in ABI method call\n       */\n      optIn: async (params: AppClientMethodCallParams) => {\n        return this._algorand.createTransaction.appCallMethodCall(await this.params.optIn(params))\n      },\n      /**\n       * Return transactions for a delete ABI call\n       * @param params The parameters for the delete ABI method call\n       * @returns The transactions which can be used to create a delete ABI method call\n       */\n      delete: async (params: AppClientMethodCallParams) => {\n        return this._algorand.createTransaction.appDeleteMethodCall(await this.params.delete(params))\n      },\n      /**\n       * Return transactions for a close out ABI call\n       * @param params The parameters for the close out ABI method call\n       * @returns The transactions which can be used to create a close out ABI method call\n       */\n      closeOut: async (params: AppClientMethodCallParams) => {\n        return this._algorand.createTransaction.appCallMethodCall(await this.params.closeOut(params))\n      },\n      /**\n       * Return transactions for an ABI call (defaults to no-op)\n       * @param params The parameters for the ABI method call\n       * @returns The transactions which can be used to create an ABI method call\n       */\n      call: async (params: AppClientMethodCallParams & CallOnComplete) => {\n        return this._algorand.createTransaction.appCallMethodCall(await this.params.call(params))\n      },\n    }\n  }\n\n  /** Returns the sender for a call, using the provided sender or using the `defaultSender`\n   * if none provided and throws an error if neither provided */\n  private getSender(sender: Address | string | undefined): Address {\n    if (!sender && !this._defaultSender) {\n      throw new Error(`No sender provided and no default sender present in app client for call to app ${this._appName}`)\n    }\n    return typeof sender === 'string' ? Address.fromString(sender) : (sender ?? this._defaultSender!)\n  }\n\n  /** Returns the signer for a call, using the provided signer or the `defaultSigner`\n   * if no signer was provided and the sender resolves to the default sender, the call will use default signer\n   * or `undefined` otherwise (so the signer is resolved from `AlgorandClient`) */\n  private getSigner(\n    sender: Address | string | undefined,\n    signer: TransactionSigner | TransactionSignerAccount | undefined,\n  ): TransactionSigner | TransactionSignerAccount | undefined {\n    return signer ?? (!sender || sender === this._defaultSender ? this._defaultSigner : undefined)\n  }\n\n  private getBareParams<\n    TParams extends { sender?: Address | string; signer?: TransactionSigner | TransactionSignerAccount } | undefined,\n    TOnComplete extends OnApplicationComplete,\n  >(params: TParams, onComplete: TOnComplete) {\n    return {\n      ...params,\n      appId: this._appId,\n      sender: this.getSender(params?.sender),\n      signer: this.getSigner(params?.sender, params?.signer),\n      onComplete,\n    }\n  }\n\n  private async getABIParams<\n    TParams extends {\n      method: string\n      sender?: Address | string\n      signer?: TransactionSigner | TransactionSignerAccount\n      args?: AppClientMethodCallParams['args']\n    },\n    TOnComplete extends OnApplicationComplete,\n  >(params: TParams, onComplete: TOnComplete) {\n    const sender = this.getSender(params.sender)\n    const method = getArc56Method(params.method, this._appSpec)\n    const args = await this.getABIArgsWithDefaultValues(params.method, params.args, sender)\n    return {\n      ...params,\n      appId: this._appId,\n      sender: sender,\n      signer: this.getSigner(params.sender, params.signer),\n      method,\n      onComplete,\n      args,\n    }\n  }\n\n  /** Make the given call and catch any errors, augmenting with debugging information before re-throwing. */\n  private handleCallErrors = async (e: Error & { sentTransactions?: algosdk.Transaction[] }) => {\n    // We can't use the app ID in an error to identify new apps, so instead we check the programs\n    // to identify if this is the correct app\n    if (this.appId === 0n) {\n      if (e.sentTransactions === undefined) return e\n\n      const txns = e.sentTransactions\n\n      const txn = txns.find((t) => e.message.includes(t.txID()))\n\n      const programsDefinedAndEqual = (a: Uint8Array | undefined, b: Uint8Array | undefined) => {\n        if (a === undefined || b === undefined) return false\n        if (a.length !== b.length) return false\n\n        for (let i = 0; i < a.length; i++) {\n          if (a[i] !== b[i]) return false\n        }\n\n        return true\n      }\n\n      if (\n        !programsDefinedAndEqual(txn?.applicationCall?.clearProgram, this._lastCompiled.clear) ||\n        !programsDefinedAndEqual(txn?.applicationCall?.approvalProgram, this._lastCompiled?.approval)\n      ) {\n        return e\n      }\n    } else {\n      // Only handle errors for this app.\n      if (!new RegExp(`app=${this._appId.toString()}(?!\\\\d)`).test(e.message)) return e\n    }\n\n    const logicError = await this.exposeLogicError(e)\n    if (logicError instanceof LogicError) {\n      let currentLine = logicError.teal_line - logicError.lines - 1\n      const stackWithLines = logicError.stack\n        ?.split('\\n')\n        .map((line) => `${(currentLine += 1)}: ${line}`)\n        .join('\\n')\n      Config.logger.error(`${logicError.message}\\n\\n${stackWithLines}`)\n    }\n\n    return logicError\n  }\n\n  private getBoxMethods() {\n    // eslint-disable-next-line @typescript-eslint/no-this-alias\n    const that = this\n    const stateMethods = {\n      /**\n       * Returns all single-key state values in a record keyed by the key name and the value a decoded ABI value.\n       */\n      getAll: async () => {\n        return Object.fromEntries(\n          await Promise.all(Object.keys(that._appSpec.state.keys.box).map(async (key) => [key, await stateMethods.getValue(key)])),\n          // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        ) as Record<string, any>\n      },\n      /**\n       * Returns a single state value for the current app with the value a decoded ABI value.\n       * @param name The name of the state value to retrieve the value for\n       * @returns\n       */\n      getValue: async (name: string) => {\n        const metadata = that._appSpec.state.keys.box[name]\n        const value = await that.getBoxValue(Buffer.from(metadata.key, 'base64'))\n        return getABIDecodedValue(value, metadata.valueType, that._appSpec.structs)\n      },\n      /**\n       *\n       * @param mapName The name of the map to read from\n       * @param key The key within the map (without any map prefix) as either a Buffer with the bytes or a value\n       *  that will be converted to bytes by encoding it using the specified ABI key type\n       *  in the ARC-56 spec\n       */\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n      getMapValue: async (mapName: string, key: Uint8Array | any) => {\n        const metadata = that._appSpec.state.maps.box[mapName]\n        const prefix = Buffer.from(metadata.prefix ?? '', 'base64')\n        const encodedKey = Buffer.concat([prefix, getABIEncodedValue(key, metadata.keyType, that._appSpec.structs)])\n        const base64Key = Buffer.from(encodedKey).toString('base64')\n        const value = await that.getBoxValue(Buffer.from(base64Key, 'base64'))\n        return getABIDecodedValue(value, metadata.valueType, that._appSpec.structs)\n      },\n\n      /**\n       *\n       * @param mapName The name of the map to read from\n       * @param key The key within the map as either a Buffer with the bytes or a value\n       *  that will be converted to bytes by encoding it using the specified ABI key type\n       *  in the ARC-56 spec\n       * @param appState\n       */\n      getMap: async (mapName: string) => {\n        const metadata = that._appSpec.state.maps.box[mapName]\n        const prefix = Buffer.from(metadata.prefix ?? '', 'base64')\n        const boxNames = await that.getBoxNames()\n\n        return new Map(\n          await Promise.all(\n            boxNames\n              .filter((b) => binaryStartsWith(b.nameRaw, prefix))\n              .map(async (b) => {\n                return [\n                  getABIDecodedValue(b.nameRaw.slice(prefix.length), metadata.keyType, that._appSpec.structs),\n                  getABIDecodedValue(await that.getBoxValue(b.nameRaw), metadata.valueType, that._appSpec.structs),\n                ] as const\n              }),\n          ),\n        )\n      },\n    }\n    return stateMethods\n  }\n\n  private getStateMethods(\n    stateGetter: () => Promise<AppState>,\n    keyGetter: () => {\n      [name: string]: StorageKey\n    },\n    mapGetter: () => {\n      [name: string]: StorageMap\n    },\n  ) {\n    // eslint-disable-next-line @typescript-eslint/no-this-alias\n    const that = this\n    const stateMethods = {\n      /**\n       * Returns all single-key state values in a record keyed by the key name and the value a decoded ABI value.\n       */\n      getAll: async () => {\n        const appState = await stateGetter()\n        return Object.fromEntries(\n          await Promise.all(Object.keys(keyGetter()).map(async (key) => [key, await stateMethods.getValue(key, appState)])),\n          // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        ) as Record<string, any>\n      },\n      /**\n       * Returns a single state value for the current app with the value a decoded ABI value.\n       * @param name The name of the state value to retrieve the value for\n       * @param appState Optional cached value of the current state\n       * @returns\n       */\n      getValue: async (name: string, appState?: AppState) => {\n        const state = Object.values(appState ?? (await stateGetter()))\n        const metadata = keyGetter()[name]\n\n        if (metadata === undefined) throw new Error(`Attempted to get state value ${name}, but it does not exist`)\n        const value = state.find((s) => s.keyBase64 === metadata.key)\n\n        if (value && 'valueRaw' in value) {\n          return getABIDecodedValue(value.valueRaw, metadata.valueType, that._appSpec.structs)\n        }\n\n        return value?.value\n      },\n      /**\n       * Returns a single value from the given map for the current app with the value a decoded ABI value.\n       * @param mapName The name of the map to read from\n       * @param key The key within the map (without any map prefix) as either a Buffer with the bytes or a value\n       *  that will be converted to bytes by encoding it using the specified ABI key type\n       *  in the ARC-56 spec\n       * @param appState Optional cached value of the current state\n       */\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n      getMapValue: async (mapName: string, key: Uint8Array | any, appState?: AppState) => {\n        const state = Object.values(appState ?? (await stateGetter()))\n        const metadata = mapGetter()[mapName]\n\n        const prefix = Buffer.from(metadata.prefix ?? '', 'base64')\n        const encodedKey = Buffer.concat([prefix, getABIEncodedValue(key, metadata.keyType, that._appSpec.structs)])\n        const base64Key = Buffer.from(encodedKey).toString('base64')\n        const value = state.find((s) => s.keyBase64 === base64Key)\n\n        if (value && 'valueRaw' in value) {\n          return getABIDecodedValue(value.valueRaw, metadata.valueType, that._appSpec.structs)\n        }\n\n        return value?.value\n      },\n\n      /**\n       * Returns all map values for the given map.\n       * @param mapName The name of the map to read from\n       * @param appState Optional cached value of the current state\n       * @returns A map of all key-value pairs in the map as a `Record<string, ABIValue>`\n       */\n      getMap: async (mapName: string) => {\n        const state = Object.values(await stateGetter())\n        const metadata = mapGetter()[mapName]\n\n        const prefix = Buffer.from(metadata.prefix ?? '', 'base64')\n\n        return new Map(\n          state\n            .filter((s) => binaryStartsWith(s.keyRaw, prefix))\n            .map((s) => {\n              const key = s.keyRaw.slice(prefix.length)\n              return [\n                getABIDecodedValue(key, metadata.keyType, this._appSpec.structs),\n                getABIDecodedValue('valueRaw' in s ? s.valueRaw : s.value, metadata.valueType, this._appSpec.structs),\n              ] as const\n            }),\n        )\n      },\n    }\n    return stateMethods\n  }\n}\n\n/**\n * @deprecated Use `AppClient` instead e.g. via `algorand.client.getAppClientById` or\n * `algorand.client.getAppClientByCreatorAndName`.\n * If you want to `create` or `deploy` then use `AppFactory` e.g. via `algorand.client.getAppFactory`,\n * which will in turn give you an `AppClient` instance against the created/deployed app to make other calls.\n *\n * Application client - a class that wraps an ARC-0032 app spec and provides high productivity methods to deploy and call the app */\nexport class ApplicationClient {\n  private algod: Algodv2\n  private indexer?: algosdk.Indexer\n  private appSpec: AppSpec\n  private sender: SendTransactionFrom | undefined\n  private params: SuggestedParams | undefined\n  private existingDeployments: LegacyAppLookup | undefined\n  private deployTimeParams?: TealTemplateParams\n\n  private _appId: number | bigint\n  private _appAddress: string\n  private _creator: string | undefined\n  private _appName: string\n\n  private _approvalSourceMap: SourceMap | undefined\n  private _clearSourceMap: SourceMap | undefined\n\n  /**\n   * @deprecated Use `AppClient` instead e.g. via `algorand.client.getAppClientById` or\n   * `algorand.client.getAppClientByCreatorAndName`.\n   * If you want to `create` or `deploy` then use `AppFactory` e.g. via `algorand.client.getAppFactory`,\n   * which will in turn give you an `AppClient` instance against the created/deployed app to make other calls.\n   *\n   * Create a new ApplicationClient instance\n   * @param appDetails The details of the app\n   * @param algod An algod instance\n   */\n  constructor(appDetails: AppSpecAppDetails, algod: Algodv2) {\n    const { app, sender, params, deployTimeParams, ...appIdentifier } = appDetails\n    this.algod = algod\n    this.appSpec = typeof app == 'string' ? (JSON.parse(app) as AppSpec) : app\n    this._appName = appIdentifier.name ?? this.appSpec.contract.name\n    this.deployTimeParams = deployTimeParams\n\n    if (appIdentifier.resolveBy === 'id') {\n      if (appIdentifier.id < 0) {\n        throw new Error(`Attempt to create application client with invalid app id of ${appIdentifier.id}`)\n      }\n      this._appId = appIdentifier.id\n    } else {\n      this._appId = 0\n      this._creator = appIdentifier.creatorAddress?.toString()\n      if (appIdentifier.findExistingUsing instanceof Indexer) {\n        this.indexer = appIdentifier.findExistingUsing\n      } else {\n        if (appIdentifier.findExistingUsing.creator !== this._creator) {\n          throw new Error(\n            `Attempt to create application client with invalid existingDeployments against a different creator (${appIdentifier.findExistingUsing.creator}) instead of expected creator ${this._creator}`,\n          )\n        }\n        this.existingDeployments = appIdentifier.findExistingUsing\n      }\n    }\n\n    this._appAddress = algosdk.getApplicationAddress(this._appId).toString()\n    this.sender = sender\n    this.params = params\n  }\n\n  /**\n   * @deprecated Use `AppClient.compile()` instead.\n   *\n   * Compiles the approval and clear state programs and sets up the source map.\n   * @param compilation The deploy-time parameters for the compilation\n   * @returns The compiled approval and clear state programs\n   */\n  async compile(compilation?: AppClientCompilationParams) {\n    const { deployTimeParams, updatable, deletable } = compilation ?? {}\n    const approvalTemplate = Buffer.from(this.appSpec.source.approval, 'base64').toString('utf-8')\n    const approval = replaceDeployTimeControlParams(\n      performTemplateSubstitution(approvalTemplate, deployTimeParams ?? this.deployTimeParams),\n      {\n        updatable,\n        deletable,\n      },\n    )\n    const approvalCompiled = await compileTeal(approval, this.algod)\n    this._approvalSourceMap = approvalCompiled?.sourceMap\n    const clearTemplate = Buffer.from(this.appSpec.source.clear, 'base64').toString('utf-8')\n    const clear = performTemplateSubstitution(clearTemplate, deployTimeParams ?? this.deployTimeParams)\n    const clearCompiled = await compileTeal(clear, this.algod)\n    this._clearSourceMap = clearCompiled?.sourceMap\n\n    if (Config.debug) {\n      await Config.events.emitAsync(EventType.AppCompiled, {\n        sources: [\n          { compiledTeal: approvalCompiled, appName: this._appName, fileName: 'approval' },\n          { compiledTeal: clearCompiled, appName: this._appName, fileName: 'clear' },\n        ],\n      })\n    }\n\n    return { approvalCompiled, clearCompiled }\n  }\n\n  /**\n   * Export the current source maps for the app.\n   * @returns The source maps\n   */\n  exportSourceMaps(): AppSourceMaps {\n    if (!this._approvalSourceMap || !this._clearSourceMap) {\n      throw new Error(\n        \"Unable to export source maps; they haven't been loaded into this client - you need to call create, update, or deploy first\",\n      )\n    }\n\n    return {\n      approvalSourceMap: this._approvalSourceMap,\n      clearSourceMap: this._clearSourceMap,\n    }\n  }\n\n  /**\n   * Import source maps for the app.\n   * @param sourceMaps The source maps to import\n   */\n  importSourceMaps(sourceMaps: AppSourceMaps) {\n    this._approvalSourceMap = new SourceMap(sourceMaps.approvalSourceMap)\n    this._clearSourceMap = new SourceMap(sourceMaps.clearSourceMap)\n  }\n\n  /**\n   * @deprecated Use `deploy` from an `AppFactory` instance instead.\n   *\n   * Idempotently deploy (create, update/delete if changed) an app against the given name via the given creator account, including deploy-time template placeholder substitutions.\n   *\n   * To understand the architecture decisions behind this functionality please see https://github.com/algorandfoundation/algokit-cli/blob/main/docs/src/content/docs/architecture-decisions/2023-01-12_smart-contract-deployment.md\n   *\n   * **Note:** if there is a breaking state schema change to an existing app (and `onSchemaBreak` is set to `'replace'`) the existing app will be deleted and re-created.\n   *\n   * **Note:** if there is an update (different TEAL code) to an existing app (and `onUpdate` is set to `'replace'`) the existing app will be deleted and re-created.\n   * @param deploy Deployment details\n   * @returns The metadata and transaction result(s) of the deployment, or just the metadata if it didn't need to issue transactions\n   */\n  async deploy(deploy?: AppClientDeployParams) {\n    const {\n      schema,\n      sender: deploySender,\n      version,\n      allowUpdate,\n      allowDelete,\n      sendParams,\n      createArgs,\n      createOnCompleteAction,\n      updateArgs,\n      deleteArgs,\n      ...deployArgs\n    } = deploy ?? {}\n\n    if (this._appId !== 0) {\n      throw new Error(`Attempt to deploy app which already has an app id of ${this._appId}`)\n    }\n    const sender = deploySender ?? this.sender\n    if (!sender) {\n      throw new Error('No sender provided, unable to deploy app')\n    }\n    const from = sender ?? this.sender!\n\n    if (!this._creator) {\n      throw new Error(\"Attempt to `deploy` a contract without specifying `resolveBy: 'creatorAndName'` in the constructor\")\n    }\n    if (this._creator !== getSenderAddress(from)) {\n      throw new Error(\n        `Attempt to deploy contract with a sender address (${getSenderAddress(\n          from,\n        )}) that differs from the given creator address for this application client: ${this._creator}`,\n      )\n    }\n\n    const approval = Buffer.from(this.appSpec.source.approval, 'base64').toString('utf-8')\n\n    const compilation = {\n      deployTimeParams: deployArgs.deployTimeParams,\n      updatable:\n        allowUpdate !== undefined\n          ? allowUpdate\n          : getDeployTimeControl(approval, this.appSpec, UPDATABLE_TEMPLATE_NAME, 'update_application'),\n      deletable:\n        allowDelete !== undefined\n          ? allowDelete\n          : getDeployTimeControl(approval, this.appSpec, DELETABLE_TEMPLATE_NAME, 'delete_application'),\n    }\n\n    const { approvalCompiled, clearCompiled } = await this.compile(compilation)\n\n    try {\n      await this.getAppReference()\n      const result = await deployApp(\n        {\n          from: sender,\n          approvalProgram: approvalCompiled.compiledBase64ToBytes,\n          clearStateProgram: clearCompiled.compiledBase64ToBytes,\n          metadata: {\n            name: this._appName,\n            version: version ?? '1.0',\n            updatable: compilation.updatable,\n            deletable: compilation.deletable,\n          },\n          schema: {\n            globalByteSlices: this.appSpec.state.global.num_byte_slices,\n            globalInts: this.appSpec.state.global.num_uints,\n            localByteSlices: this.appSpec.state.local.num_byte_slices,\n            localInts: this.appSpec.state.local.num_uints,\n            ...schema,\n          },\n          transactionParams: this.params,\n          ...(sendParams ?? {}),\n          existingDeployments: this.existingDeployments,\n          createArgs: await this.getCallArgs(createArgs, sender),\n          createOnCompleteAction: createOnCompleteAction,\n          updateArgs: await this.getCallArgs(updateArgs, sender),\n          deleteArgs: await this.getCallArgs(deleteArgs, sender),\n          ...deployArgs,\n        },\n        this.algod,\n        this.indexer,\n      )\n\n      // Nothing needed to happen\n      if (result.operationPerformed === 'nothing') {\n        return result\n      }\n\n      if (!this.existingDeployments) {\n        throw new Error('Expected existingDeployments to be present')\n      }\n      const { transaction, confirmation, operationPerformed, ...appMetadata } = result\n      this.existingDeployments = {\n        creator: this.existingDeployments.creator,\n        apps: { ...this.existingDeployments.apps, [this._appName]: appMetadata },\n      }\n\n      return { ...result, ...({ compiledApproval: approvalCompiled, compiledClear: clearCompiled } as AppCompilationResult) }\n    } catch (e) {\n      throw this.exposeLogicError(e as Error)\n    }\n  }\n\n  /**\n   * @deprecated Use `create` from an `AppFactory` instance instead.\n   *\n   * Creates a smart contract app, returns the details of the created app.\n   * @param create The parameters to create the app with\n   * @returns The details of the created app, or the transaction to create it if `skipSending` and the compilation result\n   */\n  async create(create?: AppClientCreateParams) {\n    const {\n      sender: createSender,\n      note,\n      sendParams,\n      deployTimeParams,\n      updatable,\n      deletable,\n      onCompleteAction,\n      schema,\n      ...args\n    } = create ?? {}\n\n    if (this._appId !== 0) {\n      throw new Error(`Attempt to create app which already has an app id of ${this._appId}`)\n    }\n\n    const sender = createSender ?? this.sender\n    if (!sender) {\n      throw new Error('No sender provided, unable to create app')\n    }\n\n    const { approvalCompiled, clearCompiled } = await this.compile(create)\n\n    try {\n      const result = await createApp(\n        {\n          from: sender,\n          approvalProgram: approvalCompiled.compiledBase64ToBytes,\n          clearStateProgram: clearCompiled.compiledBase64ToBytes,\n          schema: {\n            globalByteSlices: this.appSpec.state.global.num_byte_slices,\n            globalInts: this.appSpec.state.global.num_uints,\n            localByteSlices: this.appSpec.state.local.num_byte_slices,\n            localInts: this.appSpec.state.local.num_uints,\n            ...schema,\n          },\n          onCompleteAction,\n          args: await this.getCallArgs(args, sender),\n          note: note,\n          transactionParams: this.params,\n          ...(sendParams ?? {}),\n        },\n        this.algod,\n      )\n\n      if (result.confirmation) {\n        this._appId = result.confirmation.applicationIndex!\n        this._appAddress = getApplicationAddress(this._appId).toString()\n      }\n\n      return { ...result, ...({ compiledApproval: approvalCompiled, compiledClear: clearCompiled } as AppCompilationResult) }\n    } catch (e) {\n      throw await this.exposeLogicError(e as Error)\n    }\n  }\n\n  /**\n   * @deprecated Use `appClient.send.update` or `appClient.createTransaction.update` from an `AppClient` instance instead.\n   *\n   * Updates the smart contract app.\n   * @param update The parameters to update the app with\n   * @returns The transaction send result and the compilation result\n   */\n  async update(update?: AppClientUpdateParams) {\n    const { sender: updateSender, note, sendParams, deployTimeParams, updatable, deletable, ...args } = update ?? {}\n\n    if (this._appId === 0) {\n      throw new Error(`Attempt to update app which doesn't have an app id defined`)\n    }\n    const sender = updateSender ?? this.sender\n    if (!sender) {\n      throw new Error('No sender provided, unable to create app')\n    }\n\n    const { approvalCompiled, clearCompiled } = await this.compile(update)\n\n    try {\n      const result = await updateApp(\n        {\n          appId: this._appId,\n          from: sender,\n          approvalProgram: approvalCompiled.compiledBase64ToBytes,\n          clearStateProgram: clearCompiled.compiledBase64ToBytes,\n          args: await this.getCallArgs(args, sender),\n          note: note,\n          transactionParams: this.params,\n          ...(sendParams ?? {}),\n        },\n        this.algod,\n      )\n\n      return { ...result, ...({ compiledApproval: approvalCompiled, compiledClear: clearCompiled } as AppCompilationResult) }\n    } catch (e) {\n      throw await this.exposeLogicError(e as Error)\n    }\n  }\n\n  /**\n   * @deprecated Use `appClient.send.call` or `appClient.createTransaction.call` from an `AppClient` instance instead.\n   *\n   * Issues a no_op (normal) call to the app.\n   * @param call The call details.\n   * @returns The result of the call\n   */\n  async call(call?: AppClientCallParams) {\n    if (\n      // ABI call\n      call?.method &&\n      // We aren't skipping the send\n      !call.sendParams?.skipSending &&\n      // There isn't an ATC passed in\n      !call.sendParams?.atc &&\n      // The method is readonly\n      this.appSpec.hints[this.getABIMethodSignature(this.getABIMethod(call.method)!)].read_only\n    ) {\n      const atc = new AtomicTransactionComposer()\n      await this.callOfType({ ...call, sendParams: { ...call.sendParams, atc } }, 'no_op')\n      const result = await atc.simulate(this.algod)\n      if (result.simulateResponse.txnGroups.some((group) => group.failureMessage)) {\n        throw new Error(result.simulateResponse.txnGroups.find((x) => x.failureMessage)?.failureMessage)\n      }\n      const txns = atc.buildGroup()\n      return {\n        transaction: txns[txns.length - 1].txn,\n        confirmation: result.simulateResponse.txnGroups[0].txnResults.at(-1)?.txnResult,\n        confirmations: result.simulateResponse.txnGroups[0].txnResults.map((t) => t.txnResult),\n        transactions: txns.map((t) => t.txn),\n        return: (result.methodResults?.length ?? 0 > 0) ? (result.methodResults[result.methodResults.length - 1] as ABIReturn) : undefined,\n      } satisfies AppCallTransactionResult\n    }\n\n    return await this.callOfType(call, 'no_op')\n  }\n\n  /**\n   * @deprecated Use `appClient.send.optIn` or `appClient.createTransaction.optIn` from an `AppClient` instance instead.\n   *\n   * Issues a opt_in call to the app.\n   * @param call The call details.\n   * @returns The result of the call\n   */\n  async optIn(call?: AppClientCallParams) {\n    return await this.callOfType(call, 'opt_in')\n  }\n\n  /**\n   * @deprecated Use `appClient.send.closeOut` or `appClient.createTransaction.closeOut` from an `AppClient` instance instead.\n   *\n   * Issues a close_out call to the app.\n   * @param call The call details.\n   * @returns The result of the call\n   */\n  async closeOut(call?: AppClientCallParams) {\n    return await this.callOfType(call, 'close_out')\n  }\n\n  /**\n   * @deprecated Use `appClient.send.clearState` or `appClient.createTransaction.clearState` from an `AppClient` instance instead.\n   *\n   * Issues a clear_state call to the app.\n   * @param call The call details.\n   * @returns The result of the call\n   */\n  async clearState(call?: AppClientClearStateParams) {\n    return await this.callOfType(call, 'clear_state')\n  }\n\n  /**\n   * @deprecated Use `appClient.send.delete` or `appClient.createTransaction.delete` from an `AppClient` instance instead.\n   *\n   * Issues a delete_application call to the app.\n   * @param call The call details.\n   * @returns The result of the call\n   */\n  async delete(call?: AppClientCallParams) {\n    return await this.callOfType(call, 'delete_application')\n  }\n\n  /**\n   * @deprecated Use `appClient.send.call` or `appClient.createTransaction.call` from an `AppClient` instance instead.\n   *\n   * Issues a call to the app with the given call type.\n   * @param call The call details.\n   * @param callType The call type\n   * @returns The result of the call\n   */\n  async callOfType(\n    call: AppClientCallParams = {},\n    callType: Exclude<AppCallType, 'update_application'> | Exclude<OnApplicationComplete, OnApplicationComplete.UpdateApplicationOC>,\n  ) {\n    const { sender: callSender, note, sendParams, ...args } = call\n\n    const sender = callSender ?? this.sender\n    if (!sender) {\n      throw new Error('No sender provided, unable to call app')\n    }\n\n    const appMetadata = await this.getAppReference()\n    if (appMetadata.appId === 0) {\n      throw new Error(`Attempt to call an app that can't be found '${this._appName}' for creator '${this._creator}'.`)\n    }\n\n    try {\n      return await callApp(\n        {\n          appId: appMetadata.appId,\n          callType: callType,\n          from: sender,\n          args: await this.getCallArgs(args, sender),\n          note: note,\n          transactionParams: this.params,\n          ...(sendParams ?? {}),\n        },\n        this.algod,\n      )\n    } catch (e) {\n      throw this.exposeLogicError(e as Error)\n    }\n  }\n\n  /**\n   * Funds Algo into the app account for this app.\n   * @param fund The parameters for the funding or the funding amount\n   * @returns The result of the funding\n   */\n  async fundAppAccount(fund: FundAppAccountParams | AlgoAmount) {\n    const { amount, sender, note, sendParams } = 'microAlgos' in fund ? ({ amount: fund } as FundAppAccountParams) : fund\n\n    if (!sender && !this.sender) {\n      throw new Error('No sender provided, unable to call app')\n    }\n\n    const ref = await this.getAppReference()\n    return legacySendTransactionBridge(\n      this.algod,\n      sender ?? this.sender!,\n      sendParams ?? {},\n      {\n        receiver: ref.appAddress,\n        sender: getSenderAddress(sender ?? this.sender!),\n        amount: amount,\n        note: encodeTransactionNote(note),\n      },\n      (c) => c.payment,\n      (c) => c.payment,\n      this.params,\n    )\n  }\n\n  /**\n   * Returns global state for the current app.\n   * @returns The global state\n   */\n  async getGlobalState(): Promise<AppState> {\n    const appRef = await this.getAppReference()\n\n    if (appRef.appId === 0) {\n      throw new Error('No app has been created yet, unable to get global state')\n    }\n\n    return getAppGlobalState(appRef.appId, this.algod)\n  }\n\n  /**\n   * Returns local state for the given account / account address.\n   * @returns The global state\n   */\n  async getLocalState(account: string | SendTransactionFrom): Promise<AppState> {\n    const appRef = await this.getAppReference()\n\n    if (appRef.appId === 0) {\n      throw new Error('No app has been created yet, unable to get global state')\n    }\n\n    return getAppLocalState(appRef.appId, account, this.algod)\n  }\n\n  /**\n   * Returns the names of all current boxes for the current app.\n   * @returns The names of the boxes\n   */\n  async getBoxNames(): Promise<BoxName[]> {\n    const appRef = await this.getAppReference()\n\n    if (appRef.appId === 0) {\n      throw new Error('No app has been created yet, unable to get global state')\n    }\n\n    return await getAppBoxNames(appRef.appId, this.algod)\n  }\n\n  /**\n   * Returns the value of the given box for the current app.\n   * @param name The name of the box to return either as a string, binary array or `BoxName`\n   * @returns The current box value as a byte array\n   */\n  async getBoxValue(name: BoxName | string | Uint8Array): Promise<Uint8Array> {\n    const appRef = await this.getAppReference()\n\n    if (appRef.appId === 0) {\n      throw new Error('No app has been created yet, unable to get global state')\n    }\n\n    return await getAppBoxValue(appRef.appId, name, this.algod)\n  }\n\n  /**\n   * Returns the value of the given box for the current app.\n   * @param name The name of the box to return either as a string, binary array or `BoxName`\n   * @param type\n   * @returns The current box value as a byte array\n   */\n  async getBoxValueFromABIType(name: BoxName | string | Uint8Array, type: ABIType): Promise<ABIValue> {\n    const appRef = await this.getAppReference()\n\n    if (appRef.appId === 0) {\n      throw new Error('No app has been created yet, unable to get global state')\n    }\n\n    return await getAppBoxValueFromABIType({ appId: appRef.appId, boxName: name, type }, this.algod)\n  }\n\n  /**\n   * Returns the values of all current boxes for the current app.\n   * Note: This will issue multiple HTTP requests (one per box) and it's not an atomic operation so values may be out of sync.\n   * @param filter Optional filter to filter which boxes' values are returned\n   * @returns The (name, value) pair of the boxes with values as raw byte arrays\n   */\n  async getBoxValues(filter?: (name: BoxName) => boolean): Promise<{ name: BoxName; value: Uint8Array }[]> {\n    const appRef = await this.getAppReference()\n\n    if (appRef.appId === 0) {\n      throw new Error('No app has been created yet, unable to get global state')\n    }\n\n    const names = await this.getBoxNames()\n    return await Promise.all(\n      names\n        .filter(filter ?? ((_) => true))\n        .map(async (boxName) => ({ name: boxName, value: await getAppBoxValue(appRef.appId, boxName, this.algod) })),\n    )\n  }\n\n  /**\n   * Returns the values of all current boxes for the current app decoded using an ABI Type.\n   * Note: This will issue multiple HTTP requests (one per box) and it's not an atomic operation so values may be out of sync.\n   * @param type The ABI type to decode the values with\n   * @param filter Optional filter to filter which boxes' values are returned\n   * @returns The (name, value) pair of the boxes with values as the ABI Value\n   */\n  async getBoxValuesFromABIType(type: ABIType, filter?: (name: BoxName) => boolean): Promise<{ name: BoxName; value: ABIValue }[]> {\n    const appRef = await this.getAppReference()\n\n    if (appRef.appId === 0) {\n      throw new Error('No app has been created yet, unable to get global state')\n    }\n\n    const names = await this.getBoxNames()\n    return await Promise.all(\n      names.filter(filter ?? ((_) => true)).map(async (boxName) => ({\n        name: boxName,\n        value: await getAppBoxValueFromABIType({ appId: appRef.appId, boxName, type }, this.algod),\n      })),\n    )\n  }\n\n  /**\n   * @deprecated Use `appClient.params.*` from an `AppClient` instance instead.\n   *\n   * Returns the arguments for an app call for the given ABI method or raw method specification.\n   * @param args The call args specific to this application client\n   * @param sender The sender of this call. Will be used to fetch any default argument values if applicable\n   * @returns The call args ready to pass into an app call\n   */\n  async getCallArgs(args: AppClientCallArgs | undefined, sender: SendTransactionFrom): Promise<AppCallArgs | undefined> {\n    if (!args) {\n      return undefined\n    }\n\n    if (args.method) {\n      const abiMethod = this.getABIMethodParams(args.method)\n      if (!abiMethod) {\n        throw new Error(`Attempt to call ABI method ${args.method}, but it wasn't found`)\n      }\n\n      const methodSignature = this.getABIMethodSignature(abiMethod)\n\n      return {\n        ...args,\n        method: abiMethod,\n        methodArgs: await Promise.all(\n          args.methodArgs.map(async (arg, index): Promise<ABIAppCallArg> => {\n            if (arg !== undefined) return arg\n            const argName = abiMethod.args[index].name\n            const defaultValueStrategy = argName && this.appSpec.hints?.[methodSignature]?.default_arguments?.[argName]\n            if (!defaultValueStrategy)\n              throw new Error(\n                `Argument at position ${index} with the name ${argName} is undefined and does not have a default value strategy`,\n              )\n\n            switch (defaultValueStrategy.source) {\n              case 'constant':\n                return defaultValueStrategy.data\n              case 'abi-method': {\n                const method = defaultValueStrategy.data as ABIMethodParams\n                const result = await this.callOfType(\n                  {\n                    method: this.getABIMethodSignature(method),\n                    methodArgs: method.args.map(() => undefined),\n                    sender,\n                  },\n                  'no_op',\n                )\n                return result.return?.returnValue\n              }\n              case 'local-state':\n              case 'global-state': {\n                const state =\n                  defaultValueStrategy.source === 'global-state' ? await this.getGlobalState() : await this.getLocalState(sender)\n                const key = defaultValueStrategy.data\n                if (key in state) {\n                  return state[key].value\n                } else {\n                  throw new Error(\n                    `Preparing default value for argument at position ${index} with the name ${argName} resulted in the failure: The key '${key}' could not be found in ${defaultValueStrategy.source}`,\n                  )\n                }\n              }\n            }\n          }),\n        ),\n      }\n    } else {\n      return args as RawAppCallArgs\n    }\n  }\n\n  /**\n   * @deprecated Use `appClient.getABIMethod` instead.\n   *\n   * Returns the ABI Method parameters for the given method name string for the app represented by this application client instance\n   * @param method Either the name of the method or the ABI method spec definition string\n   * @returns The ABI method params for the given method\n   */\n  getABIMethodParams(method: string): ABIMethodParams | undefined {\n    if (!method.includes('(')) {\n      const methods = this.appSpec.contract.methods.filter((m) => m.name === method)\n      if (methods.length > 1) {\n        throw new Error(\n          `Received a call to method ${method} in contract ${\n            this._appName\n          }, but this resolved to multiple methods; please pass in an ABI signature instead: ${methods\n            .map(this.getABIMethodSignature)\n            .join(', ')}`,\n        )\n      }\n      return methods[0]\n    }\n    return this.appSpec.contract.methods.find((m) => this.getABIMethodSignature(m) === method)\n  }\n\n  /**\n   * Returns the ABI Method for the given method name string for the app represented by this application client instance\n   * @param method Either the name of the method or the ABI method spec definition string\n   * @returns The ABI method for the given method\n   */\n  getABIMethod(method: string): ABIMethod | undefined {\n    const methodParams = this.getABIMethodParams(method)\n    return methodParams ? new ABIMethod(methodParams) : undefined\n  }\n\n  /**\n   * @deprecated Use `appClient.appId` and `appClient.appAddress` from an `AppClient` instance instead.\n   *\n   * Gets the reference information for the current application instance.\n   * `appId` will be 0 if it can't find an app.\n   * @returns The app reference, or if deployed using the `deploy` method, the app metadata too\n   */\n  async getAppReference(): Promise<AppMetadata | AppReference> {\n    if (!this.existingDeployments && this._creator) {\n      this.existingDeployments = await getCreatorAppsByName(this._creator, this.indexer!)\n    }\n\n    if (this.existingDeployments && this._appId === 0) {\n      const app = this.existingDeployments.apps[this._appName]\n      if (!app) {\n        return {\n          appId: 0,\n          appAddress: getApplicationAddress(0).toString(),\n        }\n      }\n      return app\n    }\n\n    return {\n      appId: this._appId,\n      appAddress: this._appAddress,\n    } as AppReference\n  }\n\n  /**\n   * Takes an error that may include a logic error from a smart contract call and re-exposes the error to include source code information via the source map.\n   * This is automatically used within `ApplicationClient` but if you pass `skipSending: true` e.g. if doing a group transaction\n   *  then you can use this in a try/catch block to get better debugging information.\n   * @param e The error to parse\n   * @param isClear Whether or not the code was running the clear state program\n   * @returns The new error, or if there was no logic error or source map then the wrapped error with source details\n   */\n  exposeLogicError(e: Error, isClear?: boolean): Error {\n    if ((!isClear && this._approvalSourceMap == undefined) || (isClear && this._clearSourceMap == undefined)) return e\n\n    const errorDetails = LogicError.parseLogicError(e)\n\n    if (errorDetails !== undefined)\n      return new LogicError(\n        errorDetails,\n        Buffer.from(isClear ? this.appSpec.source.clear : this.appSpec.source.approval, 'base64')\n          .toString()\n          .split('\\n'),\n        (pc: number) => (isClear ? this._clearSourceMap : this._approvalSourceMap)?.getLocationForPc(pc)?.line,\n      )\n    else return e\n  }\n\n  private getABIMethodSignature(method: ABIMethodParams | ABIMethod) {\n    return 'getSignature' in method ? method.getSignature() : new ABIMethod(method).getSignature()\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;AA4EO,IAAA,YAAY,QAAQ;AAKpB,IAAA,4BAA4B,QAAQ;AACpC,IAAA,wBAAwB,QAAQ;AAChC,IAAA,UAAU,QAAQ;AAClB,IAAA,wBAAwB,QAAQ;AAChC,IAAA,YAAY,QAAQ;;AAK3B,MAAM,6BAA6B;;;;;;;;;AA+MnC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