{"version":3,"file":"app-factory.mjs","names":[],"sources":["../../src/types/app-factory.ts"],"sourcesContent":["import algosdk, { Address } from 'algosdk'\nimport { TransactionSignerAccount } from './account'\nimport { type AlgorandClient } from './algorand-client'\nimport {\n  AppCompilationResult,\n  AppReturn,\n  DELETABLE_TEMPLATE_NAME,\n  SendAppTransactionResult,\n  TealTemplateParams,\n  UPDATABLE_TEMPLATE_NAME,\n} from './app'\nimport {\n  ABIStruct,\n  Arc56Contract,\n  Arc56Method,\n  getABIDecodedValue,\n  getABITupleFromABIStruct,\n  getArc56Method,\n  getArc56ReturnValue,\n} from './app-arc56'\nimport {\n  AppClient,\n  AppClientBareCallParams,\n  AppClientCompilationParams,\n  AppClientMethodCallParams,\n  AppClientParams,\n  AppSourceMaps,\n  ResolveAppClientByCreatorAndName,\n} from './app-client'\nimport {\n  AppDeployParams,\n  DeployAppDeleteMethodCall,\n  DeployAppDeleteParams,\n  DeployAppUpdateMethodCall,\n  DeployAppUpdateParams,\n} from './app-deployer'\nimport { AppSpec } from './app-spec'\nimport { AppCreateMethodCall, AppCreateParams, AppMethodCall, AppMethodCallTransactionArgument, CommonAppCallParams } from './composer'\nimport { Expand } from './expand'\nimport { SendParams } from './transaction'\nimport SourceMap = algosdk.ProgramSourceMap\nimport OnApplicationComplete = algosdk.OnApplicationComplete\nimport ABIValue = algosdk.ABIValue\nimport TransactionSigner = algosdk.TransactionSigner\n\n/** Parameters to create an app client */\nexport interface AppFactoryParams {\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  /** `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\n  /** Optional address to use for the account to use as the default sender for calls. */\n  defaultSender?: Address | string\n\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\n  /** The version of app that is / will be deployed; defaults to 1.0 */\n  version?: string\n\n  /**\n   * Whether or not the contract should have deploy-time immutability control set, undefined = ignore.\n   * If specified here will get used in calls to `deploy` and `create` calls unless overridden in those calls.\n   *\n   * Useful if you want to vend multiple contracts from the same factory without specifying this value\n   * for each call.\n   */\n  updatable?: boolean\n\n  /**\n   * Whether or not the contract should have deploy-time permanence control set, undefined = ignore.\n   * If specified here will get used in calls to `deploy` and `create` calls unless overridden in those calls.\n   *\n   * Useful if you want to vend multiple contracts from the same factory without specifying this value\n   * for each call.\n   */\n  deletable?: boolean\n\n  /**\n   * Optional deploy-time TEAL template replacement parameters.\n   * If specified here will get used in calls to `deploy` and `create` calls unless overridden in those calls.\n   *\n   * Useful if you want to vend multiple contracts from the same factory without specifying this value\n   * for each call.\n   */\n  deployTimeParams?: TealTemplateParams\n}\n\n/** onComplete parameter for a create app call */\nexport type CreateOnComplete = {\n  onComplete?: Exclude<OnApplicationComplete, OnApplicationComplete.ClearStateOC>\n}\n\n/** Specifies a schema used for creating an app */\nexport type CreateSchema = {\n  /** The state schema for the app. This is immutable once the app is created. By default uses the ARC32/ARC-56 spec. */\n  schema?: {\n    /** The number of integers saved in global state. */\n    globalInts: number\n    /** The number of byte slices saved in global state. */\n    globalByteSlices: number\n    /** The number of integers saved in local state. */\n    localInts: number\n    /** The number of byte slices saved in local state. */\n    localByteSlices: number\n  }\n  /** Number of extra pages required for the programs.\n   * Defaults to the number needed for the programs in this call if not specified.\n   * This is immutable once the app is created. */\n  extraProgramPages?: number\n}\n\n/** Params to specify a bare (raw) create call for an app */\nexport type AppFactoryCreateParams = Expand<AppClientBareCallParams & AppClientCompilationParams & CreateOnComplete & CreateSchema>\n\n/** Params to specify a create method call for an app */\nexport type AppFactoryCreateMethodCallParams = Expand<\n  AppClientMethodCallParams & AppClientCompilationParams & CreateOnComplete & CreateSchema\n>\n\n/** Params to get an app client by ID from an app factory. */\nexport type AppFactoryAppClientParams = Expand<Omit<AppClientParams, 'algorand' | 'appSpec'>>\n\n/** Params to get an app client by creator address and name from an app factory. */\nexport type AppFactoryResolveAppClientByCreatorAndNameParams = Expand<Omit<ResolveAppClientByCreatorAndName, 'algorand' | 'appSpec'>>\n\n/** Parameters to define a deployment for an `AppFactory` */\nexport type AppFactoryDeployParams = Expand<\n  Omit<AppDeployParams, 'createParams' | 'updateParams' | 'deleteParams' | 'metadata'> & {\n    /** Create transaction parameters to use if a create needs to be issued as part of deployment */\n    createParams?:\n      | Expand<AppClientMethodCallParams & CreateOnComplete & CreateSchema>\n      | Expand<AppClientBareCallParams & CreateOnComplete & CreateSchema>\n    /** Update transaction parameters to use if a create needs to be issued as part of deployment */\n    updateParams?: AppClientMethodCallParams | AppClientBareCallParams\n    /** Delete transaction parameters to use if a create needs to be issued as part of deployment */\n    deleteParams?: AppClientMethodCallParams | AppClientBareCallParams\n    /**\n     * Whether or not the contract should have deploy-time immutability control set.\n     * `undefined` = use AppFactory constructor value if set or base it on the app spec.\n     */\n    updatable?: boolean\n    /**\n     * Whether or not the contract should have deploy-time permanence control set.\n     * `undefined` = use AppFactory constructor value if set or base it on the app spec.\n     */\n    deletable?: boolean\n    /** Override the app name for this deployment */\n    appName?: string\n  }\n>\n\n/**\n * ARC-56/ARC-32 app factory that, for a given app spec, allows you to create\n * and deploy one or more app instances and to create one or more app clients\n * to interact with those (or other) app instances.\n */\nexport class AppFactory {\n  private _appSpec: Arc56Contract\n  private _appName: string\n  private _algorand: AlgorandClient\n  private _version: string\n  private _defaultSender?: Address\n  private _defaultSigner?: TransactionSigner\n  private _deployTimeParams?: TealTemplateParams\n  private _updatable?: boolean\n  private _deletable?: boolean\n\n  private _approvalSourceMap: SourceMap | undefined\n  private _clearSourceMap: SourceMap | undefined\n\n  private _paramsMethods: ReturnType<AppFactory['getParamsMethods']>\n\n  /**\n   * Create a new app factory.\n   * @param params The parameters to create the app factory\n   * @returns The `AppFactory` instance\n   * @example\n   * ```typescript\n   * const appFactory = new AppFactory({\n   *   appSpec: appSpec,\n   *   algorand: AlgorandClient.mainNet(),\n   * })\n   */\n  constructor(params: AppFactoryParams) {\n    this._appSpec = AppClient.normaliseAppSpec(params.appSpec)\n    this._appName = params.appName ?? this._appSpec.name\n    this._algorand = params.algorand\n    this._version = params.version ?? '1.0'\n    this._defaultSender = typeof params.defaultSender === 'string' ? Address.fromString(params.defaultSender) : params.defaultSender\n    this._defaultSigner = params.defaultSigner\n    this._deployTimeParams = params.deployTimeParams\n    this._updatable = params.updatable\n    this._deletable = params.deletable\n    this._paramsMethods = this.getParamsMethods()\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  get appSpec() {\n    return this._appSpec\n  }\n\n  /** Return the algorand client this factory is using. */\n  get algorand() {\n    return this._algorand\n  }\n\n  /** Get parameters to create transactions (create and deploy related calls) 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 createAppParams = appFactory.params.create({method: 'create_method', args: [123, 'hello']})\n   * // ...\n   * await algorand.send.AppCreateMethodCall(createAppParams)\n   * ```\n   * @example Define a nested transaction as an ABI argument\n   * ```typescript\n   * const createAppParams = appFactory.params.create({method: 'create_method', args: [123, 'hello']})\n   * await appClient.send.call({method: 'my_method', args: [createAppParams]})\n   * ```\n   */\n  get params() {\n    return this._paramsMethods\n  }\n\n  /** Create transactions for the current app */\n  readonly createTransaction = {\n    /** Create bare (raw) transactions for the current app */\n    bare: {\n      /**\n       * Create a create app call transaction using a bare (raw) create call.\n       *\n       * Performs deploy-time TEAL template placeholder substitutions (if specified).\n       * @param params The parameters to create the create call transaction\n       * @returns The create call transaction\n       */\n      create: async (params?: AppFactoryCreateParams) => {\n        return this._algorand.createTransaction.appCreate(await this.params.bare.create(params))\n      },\n    },\n\n    /**\n     * Create a create app call transaction using an ABI create call.\n     *\n     * Performs deploy-time TEAL template placeholder substitutions (if specified).\n     * @param params The parameters to create the create call transaction\n     * @returns The create call transaction\n     */\n    create: async (params: AppFactoryCreateMethodCallParams) => {\n      return this._algorand.createTransaction.appCreateMethodCall(await this.params.create(params))\n    },\n  }\n\n  /** Send transactions to the current app */\n  readonly send = {\n    /** Send bare (raw) transactions for the current app */\n    bare: {\n      /**\n       * Creates an instance of the app using a bare (raw) create call and returns the result\n       * of the creation transaction and an app client to interact with that app instance.\n       *\n       * Performs deploy-time TEAL template placeholder substitutions (if specified).\n       * @param params The parameters to create the app\n       * @returns The app client and the result of the creation transaction\n       */\n      create: async (params?: AppFactoryCreateParams & SendParams) => {\n        const updatable = params?.updatable ?? this._updatable\n        const deletable = params?.deletable ?? this._deletable\n        const deployTimeParams = params?.deployTimeParams ?? this._deployTimeParams\n        const compiled = await this.compile({ deployTimeParams, updatable, deletable })\n        const result = await this.handleCallErrors(async () => ({\n          ...(await this._algorand.send.appCreate(await this.params.bare.create({ ...params, updatable, deletable, deployTimeParams }))),\n          return: undefined,\n        }))\n        return {\n          appClient: this.getAppClientById({\n            appId: result.appId,\n          }),\n          result: {\n            ...result,\n            ...(compiled as Partial<AppCompilationResult>),\n          },\n        }\n      },\n    },\n\n    /**\n     * Creates an instance of the app and returns the result of the creation\n     * transaction and an app client to interact with that app instance.\n     *\n     * Performs deploy-time TEAL template placeholder substitutions (if specified).\n     * @param params The parameters to create the app\n     * @returns The app client and the result of the creation transaction\n     */\n    create: async (params: AppFactoryCreateMethodCallParams & SendParams) => {\n      const updatable = params?.updatable ?? this._updatable\n      const deletable = params?.deletable ?? this._deletable\n      const deployTimeParams = params?.deployTimeParams ?? this._deployTimeParams\n      const compiled = await this.compile({ deployTimeParams, updatable, deletable })\n      const result = await this.handleCallErrors(async () =>\n        this.parseMethodCallReturn(\n          this._algorand.send.appCreateMethodCall(await this.params.create({ ...params, updatable, deletable, deployTimeParams })),\n          getArc56Method(params.method, this._appSpec),\n        ),\n      )\n      return {\n        appClient: this.getAppClientById({\n          appId: result.appId,\n        }),\n        result: {\n          ...result,\n          ...(compiled as Partial<AppCompilationResult>),\n        },\n      }\n    },\n  }\n\n  /**\n   * Idempotently deploy (create if not exists, update if changed) an app against the given name for the given creator account, including deploy-time TEAL template placeholder substitutions (if specified).\n   *\n   * **Note:** When using the return from this function be sure to check `operationPerformed` to get access to various return properties like `transaction`, `confirmation` and `deleteResult`.\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 params The arguments to control the app deployment\n   * @returns The app client and the result of the deployment\n   * @example\n   * ```ts\n   * const { appClient, result } = await factory.deploy({\n   *   createParams: {\n   *     sender: 'SENDER_ADDRESS',\n   *     approvalProgram: 'APPROVAL PROGRAM',\n   *     clearStateProgram: 'CLEAR PROGRAM',\n   *     schema: {\n   *       globalByteSlices: 0,\n   *       globalInts: 0,\n   *       localByteSlices: 0,\n   *       localInts: 0\n   *     }\n   *   },\n   *   updateParams: {\n   *     sender: 'SENDER_ADDRESS'\n   *   },\n   *   deleteParams: {\n   *     sender: 'SENDER_ADDRESS'\n   *   },\n   *   metadata: { name: 'my_app', version: '2.0', updatable: false, deletable: false },\n   *   onSchemaBreak: 'append',\n   *   onUpdate: 'append'\n   *  })\n   * ```\n   */\n  public async deploy(params: AppFactoryDeployParams) {\n    const updatable = params.updatable ?? this._updatable ?? this.getDeployTimeControl('updatable')\n    const deletable = params.deletable ?? this._deletable ?? this.getDeployTimeControl('deletable')\n    const deployTimeParams = params.deployTimeParams ?? this._deployTimeParams\n\n    // Compile using a appID 0 AppClient so we can register the error handler and use the programs\n    // to identify the app within the error handler (because we can't use app ID 0)\n    const tempAppClient = this.getAppClientById({ appId: 0n })\n    const compiled = await tempAppClient.compile({ deployTimeParams, updatable, deletable })\n\n    const deployResult = await this._algorand.appDeployer.deploy({\n      ...params,\n      createParams: await (params.createParams && 'method' in params.createParams\n        ? this.params.create({ ...params.createParams, updatable, deletable, deployTimeParams })\n        : this.params.bare.create({ ...params.createParams, updatable, deletable, deployTimeParams })),\n      updateParams:\n        params.updateParams && 'method' in params.updateParams\n          ? this.params.deployUpdate(params.updateParams)\n          : this.params.bare.deployUpdate(params.updateParams),\n      deleteParams:\n        params.deleteParams && 'method' in params.deleteParams\n          ? this.params.deployDelete(params.deleteParams)\n          : this.params.bare.deployDelete(params.deleteParams),\n      metadata: {\n        name: params.appName ?? this._appName,\n        version: this._version,\n        updatable,\n        deletable,\n      },\n    })\n    const appClient = this.getAppClientById({\n      appId: deployResult.appId,\n      appName: params.appName,\n    })\n    const result = {\n      ...deployResult,\n      ...(compiled as Partial<AppCompilationResult>),\n    }\n    return {\n      appClient,\n      result: {\n        ...result,\n        return:\n          'return' in result\n            ? result.operationPerformed === 'update'\n              ? params.updateParams && 'method' in params.updateParams\n                ? getArc56ReturnValue(result.return, getArc56Method(params.updateParams.method, this._appSpec), this._appSpec.structs)\n                : undefined\n              : params.createParams && 'method' in params.createParams\n                ? getArc56ReturnValue(result.return, getArc56Method(params.createParams.method, this._appSpec), this._appSpec.structs)\n                : undefined\n            : undefined,\n        deleteReturn:\n          'deleteReturn' in result && params.deleteParams && 'method' in params.deleteParams\n            ? getArc56ReturnValue(result.deleteReturn, getArc56Method(params.deleteParams.method, this._appSpec), this._appSpec.structs)\n            : undefined,\n      },\n    }\n  }\n\n  /**\n   * Returns a new `AppClient` client for an app instance of the given ID.\n   *\n   * Automatically populates appName, defaultSender and source maps from the factory\n   * if not specified in the params.\n   * @param params The parameters to create the app client\n   * @returns The `AppClient` instance\n   * @example\n   * ```typescript\n   * const appClient = factory.getAppClientById({ appId: 12345n })\n   * ```\n   */\n  public getAppClientById(params: AppFactoryAppClientParams) {\n    return new AppClient({\n      ...params,\n      algorand: this._algorand,\n      appSpec: this._appSpec,\n      appName: params.appName ?? this._appName,\n      defaultSender: params.defaultSender ?? this._defaultSender,\n      defaultSigner: params.defaultSigner ?? this._defaultSigner,\n      approvalSourceMap: params.approvalSourceMap ?? this._approvalSourceMap,\n      clearSourceMap: params.clearSourceMap ?? this._clearSourceMap,\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   *\n   * Automatically populates appName, defaultSender and source maps from the factory\n   * if not specified in the params.\n   * @param params The parameters to create the app client\n   * @returns The `AppClient` instance\n   * @example\n   * ```typescript\n   * const appClient = factory.getAppClientByCreatorAndName({ creatorAddress: 'CREATOR_ADDRESS', appName: 'my_app' })\n   * ```\n   */\n  public getAppClientByCreatorAndName(params: AppFactoryResolveAppClientByCreatorAndNameParams) {\n    return AppClient.fromCreatorAndName({\n      ...params,\n      algorand: this._algorand,\n      appSpec: this._appSpec,\n      appName: params.appName ?? this._appName,\n      defaultSender: params.defaultSender ?? this._defaultSender,\n      approvalSourceMap: params.approvalSourceMap ?? this._approvalSourceMap,\n      clearSourceMap: params.clearSourceMap ?? this._clearSourceMap,\n    })\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  exposeLogicError(e: Error, isClearStateProgram?: boolean): Error {\n    return AppClient.exposeLogicError(e, this._appSpec, {\n      isClearStateProgram,\n      approvalSourceMap: this._approvalSourceMap,\n      clearSourceMap: this._clearSourceMap,\n    })\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  private getDeployTimeControl(control: 'updatable' | 'deletable'): boolean | undefined {\n    const approval = this._appSpec.source?.approval ? Buffer.from(this._appSpec.source.approval, 'base64').toString('utf-8') : undefined\n    // variable not present, so unknown control value\n    if (!approval || !approval.includes(control === 'updatable' ? UPDATABLE_TEMPLATE_NAME : DELETABLE_TEMPLATE_NAME)) return undefined\n\n    // A call is present and configured\n    return (\n      this._appSpec.bareActions.call.includes(control === 'updatable' ? 'UpdateApplication' : 'DeleteApplication') ||\n      Object.values(this._appSpec.methods).some((c) =>\n        c.actions.call.includes(control === 'updatable' ? 'UpdateApplication' : 'DeleteApplication'),\n      )\n    )\n  }\n\n  private getParamsMethods() {\n    return {\n      /** Return params for a create ABI call, including deploy-time TEAL template replacements and compilation if provided */\n      create: async (params: AppFactoryCreateMethodCallParams) => {\n        const compiled = await this.compile({ ...params, deployTimeParams: params.deployTimeParams ?? this._deployTimeParams })\n        return this.getABIParams(\n          {\n            ...params,\n            deployTimeParams: params.deployTimeParams ?? this._deployTimeParams,\n            schema: params.schema ?? {\n              globalByteSlices: this._appSpec.state.schema.global.bytes,\n              globalInts: this._appSpec.state.schema.global.ints,\n              localByteSlices: this._appSpec.state.schema.local.bytes,\n              localInts: this._appSpec.state.schema.local.ints,\n            },\n            approvalProgram: compiled.approvalProgram,\n            clearStateProgram: compiled.clearStateProgram,\n          },\n          params.onComplete ?? OnApplicationComplete.NoOpOC,\n        ) satisfies AppCreateMethodCall\n      },\n      /** Return params for a deployment update ABI call */\n      deployUpdate: (params: AppClientMethodCallParams) => {\n        return this.getABIParams(params, OnApplicationComplete.UpdateApplicationOC) satisfies DeployAppUpdateMethodCall\n      },\n      /** Return params for a deployment delete ABI call */\n      deployDelete: (params: AppClientMethodCallParams) => {\n        return this.getABIParams(params, OnApplicationComplete.DeleteApplicationOC) satisfies DeployAppDeleteMethodCall\n      },\n      bare: {\n        /** Return params for a create bare call, including deploy-time TEAL template replacements and compilation if provided */\n        create: async (params?: AppFactoryCreateParams) => {\n          return this.getBareParams(\n            {\n              ...params,\n              deployTimeParams: params?.deployTimeParams ?? this._deployTimeParams,\n              schema: params?.schema ?? {\n                globalByteSlices: this._appSpec.state.schema.global.bytes,\n                globalInts: this._appSpec.state.schema.global.ints,\n                localByteSlices: this._appSpec.state.schema.local.bytes,\n                localInts: this._appSpec.state.schema.local.ints,\n              },\n              ...(await this.compile({ ...params, deployTimeParams: params?.deployTimeParams ?? this._deployTimeParams })),\n            },\n            params?.onComplete ?? OnApplicationComplete.NoOpOC,\n          ) satisfies AppCreateParams\n        },\n        /** Return params for a deployment update bare call */\n        deployUpdate: (params?: AppClientBareCallParams) => {\n          return this.getBareParams(params, OnApplicationComplete.UpdateApplicationOC) satisfies DeployAppUpdateParams\n        },\n        /** Return params for a deployment delete bare call */\n        deployDelete: (params?: AppClientBareCallParams) => {\n          return this.getBareParams(params, OnApplicationComplete.DeleteApplicationOC) satisfies DeployAppDeleteParams\n        },\n      },\n    }\n  }\n\n  /** Make the given call and catch any errors, augmenting with debugging information before re-throwing. */\n  private async handleCallErrors<TResult>(call: () => Promise<TResult>) {\n    try {\n      return await call()\n    } catch (e) {\n      throw this.exposeLogicError(e as Error)\n    }\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 Optional compilation parameters to use for the compilation\n   * @returns The compilation result\n   * @example\n   * ```typescript\n   * const result = await factory.compile()\n   * ```\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    if (result.compiledClear) {\n      this._clearSourceMap = result.compiledClear.sourceMap\n    }\n\n    return result\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      sender: this.getSender(params?.sender),\n      signer: this.getSigner(params?.sender, params?.signer),\n      onComplete,\n    }\n  }\n\n  private 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    return {\n      ...params,\n      sender: this.getSender(params.sender),\n      signer: this.getSigner(params.sender, params.signer),\n      method: getArc56Method(params.method, this._appSpec),\n      args: this.getCreateABIArgsWithDefaultValues(params.method, params.args),\n      onComplete,\n    }\n  }\n\n  private getCreateABIArgsWithDefaultValues(\n    methodNameOrSignature: string,\n    args: AppClientMethodCallParams['args'] | undefined,\n  ): AppMethodCall<CommonAppCallParams>['args'] {\n    const m = getArc56Method(methodNameOrSignature, this._appSpec)\n    return args?.map((a, i) => {\n      const arg = m.args[i]\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(Buffer.from(defaultValue.data, 'base64'), m.method.args[i].type, this._appSpec.structs) as ABIValue\n          default:\n            throw new Error(`Can't provide default value for ${defaultValue.source} for a contract creation call`)\n        }\n      }\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  /** Returns the sender for a call, using the `defaultSender`\n   * if none provided and throws an error if neither provided */\n  private getSender(sender: string | Address | undefined): Address {\n    if (!sender && !this._defaultSender) {\n      throw new Error(`No sender provided and no default sender present in app factory 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  /**\n   * Checks for decode errors on the SendAppTransactionResult and maps the return value to the specified type\n   * on the ARC-56 method.\n   *\n   * If the return type is a 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  async parseMethodCallReturn<\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"],"mappings":";;;;;AAwCO,IAAA,YAAY,QAAQ;AACpB,IAAA,wBAAwB,QAAQ;;;;;;AAgIvC,IAAa,aAAb,MAAwB;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CAEA;;;;;;;;;;;;CAaA,YAAY,QAA0B;EACpC,KAAK,W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