@algorandfoundation/algokit-utils 10.0.0-alpha.20 → 10.0.0-alpha.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/package.json +1 -6
  2. package/packages/algo25/src/index.js +1 -1
  3. package/packages/algo25/src/index.mjs +1 -1
  4. package/packages/common/src/json.mjs +2 -2
  5. package/packages/common/src/json.mjs.map +1 -1
  6. package/packages/{sdk/src/logic → common/src}/sourcemap.d.ts +2 -2
  7. package/packages/{sdk/src/logic → common/src}/sourcemap.js +2 -2
  8. package/packages/{sdk/src/logic → common/src}/sourcemap.js.map +1 -1
  9. package/packages/{sdk/src/logic → common/src}/sourcemap.mjs +1 -1
  10. package/packages/{sdk/src/logic → common/src}/sourcemap.mjs.map +1 -1
  11. package/testing/transaction-logger.js +1 -1
  12. package/testing/transaction-logger.mjs +1 -1
  13. package/transactions/app-call.js +1 -1
  14. package/transactions/app-call.mjs +1 -1
  15. package/transactions/method-call.js +1 -1
  16. package/transactions/method-call.mjs +1 -1
  17. package/types/account-manager.js +3 -3
  18. package/types/account-manager.mjs +3 -3
  19. package/types/algorand-client-transaction-creator.d.ts +18 -18
  20. package/types/algorand-client-transaction-sender.d.ts +18 -18
  21. package/types/amount.js +23 -4
  22. package/types/amount.js.map +1 -1
  23. package/types/amount.mjs +20 -2
  24. package/types/amount.mjs.map +1 -1
  25. package/types/app-client.d.ts +64 -64
  26. package/types/app-client.js +2 -2
  27. package/types/app-client.js.map +1 -1
  28. package/types/app-client.mjs +2 -2
  29. package/types/app-client.mjs.map +1 -1
  30. package/types/app-deployer.js +1 -1
  31. package/types/app-deployer.mjs +1 -1
  32. package/types/app-factory.d.ts +26 -26
  33. package/types/app-factory.js +2 -2
  34. package/types/app-factory.js.map +1 -1
  35. package/types/app-factory.mjs +2 -2
  36. package/types/app-factory.mjs.map +1 -1
  37. package/types/app-manager.js +1 -1
  38. package/types/app-manager.js.map +1 -1
  39. package/types/app-manager.mjs +1 -1
  40. package/types/app-manager.mjs.map +1 -1
  41. package/types/app.d.ts +1 -1
  42. package/types/app.js.map +1 -1
  43. package/types/app.mjs.map +1 -1
  44. package/types/composer.js +20 -20
  45. package/types/composer.js.map +1 -1
  46. package/types/composer.mjs +4 -4
  47. package/types/kmd-account-manager.js +1 -1
  48. package/types/kmd-account-manager.mjs +1 -1
  49. package/packages/sdk/src/convert.d.ts +0 -17
  50. package/packages/sdk/src/convert.js +0 -28
  51. package/packages/sdk/src/convert.js.map +0 -1
  52. package/packages/sdk/src/convert.mjs +0 -25
  53. package/packages/sdk/src/convert.mjs.map +0 -1
  54. package/packages/sdk/src/encoding/binarydata.d.ts +0 -34
  55. package/packages/sdk/src/encoding/binarydata.js +0 -65
  56. package/packages/sdk/src/encoding/binarydata.js.map +0 -1
  57. package/packages/sdk/src/encoding/binarydata.mjs +0 -60
  58. package/packages/sdk/src/encoding/binarydata.mjs.map +0 -1
  59. package/packages/sdk/src/encoding/encoding.d.ts +0 -237
  60. package/packages/sdk/src/encoding/encoding.js +0 -312
  61. package/packages/sdk/src/encoding/encoding.js.map +0 -1
  62. package/packages/sdk/src/encoding/encoding.mjs +0 -298
  63. package/packages/sdk/src/encoding/encoding.mjs.map +0 -1
  64. package/packages/sdk/src/encoding/schema/array.js +0 -35
  65. package/packages/sdk/src/encoding/schema/array.js.map +0 -1
  66. package/packages/sdk/src/encoding/schema/array.mjs +0 -35
  67. package/packages/sdk/src/encoding/schema/array.mjs.map +0 -1
  68. package/packages/sdk/src/encoding/schema/bytearray.js +0 -49
  69. package/packages/sdk/src/encoding/schema/bytearray.js.map +0 -1
  70. package/packages/sdk/src/encoding/schema/bytearray.mjs +0 -49
  71. package/packages/sdk/src/encoding/schema/bytearray.mjs.map +0 -1
  72. package/packages/sdk/src/encoding/schema/map.d.ts +0 -58
  73. package/packages/sdk/src/encoding/schema/map.js +0 -108
  74. package/packages/sdk/src/encoding/schema/map.js.map +0 -1
  75. package/packages/sdk/src/encoding/schema/map.mjs +0 -107
  76. package/packages/sdk/src/encoding/schema/map.mjs.map +0 -1
  77. package/packages/sdk/src/encoding/schema/optional.js +0 -46
  78. package/packages/sdk/src/encoding/schema/optional.js.map +0 -1
  79. package/packages/sdk/src/encoding/schema/optional.mjs +0 -46
  80. package/packages/sdk/src/encoding/schema/optional.mjs.map +0 -1
  81. package/packages/sdk/src/encoding/schema/uint64.js +0 -30
  82. package/packages/sdk/src/encoding/schema/uint64.js.map +0 -1
  83. package/packages/sdk/src/encoding/schema/uint64.mjs +0 -30
  84. package/packages/sdk/src/encoding/schema/uint64.mjs.map +0 -1
  85. package/packages/sdk/src/encoding/uint64.d.ts +0 -34
  86. package/packages/sdk/src/encoding/uint64.js +0 -34
  87. package/packages/sdk/src/encoding/uint64.js.map +0 -1
  88. package/packages/sdk/src/encoding/uint64.mjs +0 -33
  89. package/packages/sdk/src/encoding/uint64.mjs.map +0 -1
  90. package/packages/sdk/src/index.d.ts +0 -44
  91. package/packages/sdk/src/index.js +0 -62
  92. package/packages/sdk/src/index.js.map +0 -1
  93. package/packages/sdk/src/index.mjs +0 -58
  94. package/packages/sdk/src/index.mjs.map +0 -1
  95. package/packages/sdk/src/nacl/naclWrappers.js +0 -14
  96. package/packages/sdk/src/nacl/naclWrappers.js.map +0 -1
  97. package/packages/sdk/src/nacl/naclWrappers.mjs +0 -11
  98. package/packages/sdk/src/nacl/naclWrappers.mjs.map +0 -1
  99. package/packages/sdk/src/types/intDecoding.d.ts +0 -28
  100. package/packages/sdk/src/types/intDecoding.js +0 -32
  101. package/packages/sdk/src/types/intDecoding.js.map +0 -1
  102. package/packages/sdk/src/types/intDecoding.mjs +0 -31
  103. package/packages/sdk/src/types/intDecoding.mjs.map +0 -1
  104. package/packages/sdk/src/types/transactions/encoded.d.ts +0 -40
  105. package/packages/sdk/src/types/transactions/encoded.js +0 -64
  106. package/packages/sdk/src/types/transactions/encoded.js.map +0 -1
  107. package/packages/sdk/src/types/transactions/encoded.mjs +0 -59
  108. package/packages/sdk/src/types/transactions/encoded.mjs.map +0 -1
  109. package/packages/sdk/src/utils/utils.d.ts +0 -64
  110. package/packages/sdk/src/utils/utils.js +0 -140
  111. package/packages/sdk/src/utils/utils.js.map +0 -1
  112. package/packages/sdk/src/utils/utils.mjs +0 -128
  113. package/packages/sdk/src/utils/utils.mjs.map +0 -1
  114. package/sdk/index.d.ts +0 -10
  115. package/sdk/index.js +0 -59
  116. package/sdk/index.mjs +0 -11
@@ -1 +1 @@
1
- {"version":3,"file":"app-manager.js","names":["ProgramSourceMap","getApplicationAddress","getAddress","valueBase64: string","valueRaw: Buffer","ABI_RETURN_PREFIX","UPDATABLE_TEMPLATE_NAME","DELETABLE_TEMPLATE_NAME","result: string[]"],"sources":["../../src/types/app-manager.ts"],"sourcesContent":["import { ABIMethod, ABIReturn, ABIType, ABIValue } from '@algorandfoundation/algokit-abi'\nimport { AlgodClient, EvalDelta, PendingTransactionResponse, TealValue } from '@algorandfoundation/algokit-algod-client'\nimport { Address, ReadableAddress, getAddress, getApplicationAddress } from '@algorandfoundation/algokit-common'\nimport { AddressWithTransactionSigner, BoxReference as TransactionBoxReference } from '@algorandfoundation/algokit-transact'\nimport { ProgramSourceMap } from '@algorandfoundation/sdk'\nimport {\n ABI_RETURN_PREFIX,\n BoxName,\n DELETABLE_TEMPLATE_NAME,\n UPDATABLE_TEMPLATE_NAME,\n type AppState,\n type CompiledTeal,\n type TealTemplateParams,\n} from './app'\n\n/** Information about an app. */\nexport interface AppInformation {\n /** The ID of the app. */\n appId: bigint\n /** The escrow address that the app operates with. */\n appAddress: Address\n /**\n * Approval program.\n */\n approvalProgram: Uint8Array\n /**\n * Clear state program.\n */\n clearStateProgram: Uint8Array\n /**\n * The address that created this application. This is the address where the\n * parameters and global state for this application can be found.\n */\n creator: Address\n /**\n * Current global state values.\n */\n globalState: AppState\n /** The number of allocated ints in per-user local state. */\n localInts: number\n /** The number of allocated byte slices in per-user local state. */\n localByteSlices: number\n /** The number of allocated ints in global state. */\n globalInts: number\n /** The number of allocated byte slices in global state. */\n globalByteSlices: number\n /** Any extra pages that are needed for the smart contract. */\n extraProgramPages?: number\n /** The number of updates to the application programs */\n version?: number\n}\n\n/**\n * Something that identifies an app box name - either a:\n * * `Uint8Array` (the actual binary of the box name)\n * * `string` (that will be encoded to a `Uint8Array`)\n * * `AddressWithSigner` (that will be encoded into the\n * public key address of the corresponding account)\n */\nexport type BoxIdentifier = string | Uint8Array | AddressWithTransactionSigner\n\n/**\n * A grouping of the app ID and name identifier to reference an app box.\n */\nexport interface BoxReference {\n /**\n * A unique application id\n */\n appId: bigint\n /**\n * Identifier for a box name\n */\n name: BoxIdentifier\n}\n\n/**\n * Parameters to get and decode a box value as an ABI type.\n */\nexport interface BoxValueRequestParams {\n /** The ID of the app return box names for */\n appId: bigint\n /** The name of the box to return either as a string, binary array or `BoxName` */\n boxName: BoxIdentifier\n /** The ABI type to decode the value using */\n type: ABIType\n}\n\n/**\n * Parameters to get and decode a box value as an ABI type.\n */\nexport interface BoxValuesRequestParams {\n /** The ID of the app return box names for */\n appId: bigint\n /** The names of the boxes to return either as a string, binary array or BoxName` */\n boxNames: BoxIdentifier[]\n /** The ABI type to decode the value using */\n type: ABIType\n}\n\n/** Allows management of application information. */\nexport class AppManager {\n private _algod: AlgodClient\n private _compilationResults: Record<string, CompiledTeal> = {}\n\n /**\n * Creates an `AppManager`\n * @param algod An algod instance\n */\n constructor(algod: AlgodClient) {\n this._algod = algod\n }\n\n /**\n * Compiles the given TEAL using algod and returns the result, including source map.\n *\n * The result of this compilation is also cached keyed by the TEAL\n * code so it can be retrieved via `getCompilationResult`.\n *\n * This function is re-entrant; it will only compile the same code once.\n *\n * @param tealCode The TEAL code\n * @returns The information about the compiled file\n * @example\n * ```typescript\n * const compiled = await appManager.compileTeal(tealProgram)\n * ```\n */\n async compileTeal(tealCode: string): Promise<CompiledTeal> {\n if (this._compilationResults[tealCode]) {\n return this._compilationResults[tealCode]\n }\n\n const compiled = await this._algod.tealCompile(tealCode, { sourcemap: true })\n const result = {\n teal: tealCode,\n compiled: compiled.result,\n compiledHash: compiled.hash,\n compiledBase64ToBytes: new Uint8Array(Buffer.from(compiled.result, 'base64')),\n sourceMap: new ProgramSourceMap(compiled.sourcemap as { version: number; sources: string[]; names: string[]; mappings: string }),\n }\n this._compilationResults[tealCode] = result\n\n return result\n }\n\n /**\n * Performs template substitution of a teal template and compiles it, returning the compiled result.\n *\n * Looks for `TMPL_{parameter}` for template replacements and replaces AlgoKit deploy-time control parameters\n * if deployment metadata is specified.\n *\n * * `TMPL_UPDATABLE` for updatability / immutability control\n * * `TMPL_DELETABLE` for deletability / permanence control\n *\n * @param tealTemplateCode The TEAL logic to compile\n * @param templateParams Any parameters to replace in the .teal file before compiling\n * @param deploymentMetadata The deployment metadata the app will be deployed with\n * @returns The information about the compiled code\n * @example\n * ```typescript\n * const compiled = await appManager.compileTealTemplate(tealTemplate, { TMPL_APP_ID: 12345n }, { updatable: true, deletable: false })\n * ```\n */\n async compileTealTemplate(\n tealTemplateCode: string,\n templateParams?: TealTemplateParams,\n deploymentMetadata?: { updatable?: boolean; deletable?: boolean },\n ): Promise<CompiledTeal> {\n let tealCode = AppManager.stripTealComments(tealTemplateCode)\n\n tealCode = AppManager.replaceTealTemplateParams(tealCode, templateParams)\n\n if (deploymentMetadata) {\n tealCode = AppManager.replaceTealTemplateDeployTimeControlParams(tealCode, deploymentMetadata)\n }\n\n return await this.compileTeal(tealCode)\n }\n\n /**\n * Returns a previous compilation result.\n * @param tealCode The TEAL code\n * @returns The information about the previously compiled file\n * or `undefined` if that TEAL code wasn't previously compiled\n * @example\n * ```typescript\n * const compiled = appManager.getCompilationResult(tealProgram)\n * ```\n */\n getCompilationResult(tealCode: string): CompiledTeal | undefined {\n return this._compilationResults[tealCode]\n }\n\n /**\n * Returns the current app information for the app with the given ID.\n *\n * @example\n * ```typescript\n * const appInfo = await appManager.getById(12353n);\n * ```\n *\n * @param appId The ID of the app\n * @returns The app information\n */\n public async getById(appId: bigint): Promise<AppInformation> {\n const app = await this._algod.applicationById(appId)\n const convertedGlobalState = (app.params.globalState ?? []).map((kv) => ({ key: kv.key, value: kv.value }))\n\n return {\n appId: BigInt(app.id),\n appAddress: getApplicationAddress(app.id),\n approvalProgram: app.params.approvalProgram,\n clearStateProgram: app.params.clearStateProgram,\n creator: app.params.creator,\n localInts: app.params.localStateSchema?.numUints ?? 0,\n localByteSlices: app.params.localStateSchema?.numByteSlices ?? 0,\n globalInts: app.params.globalStateSchema?.numUints ?? 0,\n globalByteSlices: app.params.globalStateSchema?.numByteSlices ?? 0,\n extraProgramPages: app.params.extraProgramPages ?? 0,\n globalState: AppManager.decodeAppState(convertedGlobalState),\n version: app.params.version,\n }\n }\n\n /**\n * Returns the current global state values for the given app ID and account address\n *\n * @param appId The ID of the app to return global state for\n * @returns The current global state for the given app\n * @example\n * ```typescript\n * const globalState = await appManager.getGlobalState(12353n);\n * ```\n */\n public async getGlobalState(appId: bigint) {\n return (await this.getById(appId)).globalState\n }\n\n /**\n * Returns the current local state values for the given app ID and account address\n *\n * @param appId The ID of the app to return local state for\n * @param address The string address of the account to get local state for the given app\n * @returns The current local state for the given (app, account) combination\n * @example\n * ```typescript\n * const localState = await appManager.getLocalState(12353n, 'ACCOUNTADDRESS');\n * ```\n */\n public async getLocalState(appId: bigint, address: ReadableAddress) {\n const appInfo = await this._algod.accountApplicationInformation(getAddress(address).toString(), Number(appId))\n\n if (!appInfo.appLocalState) {\n throw new Error(\"Couldn't find local state\")\n }\n\n // If keyValue is undefined or empty, return empty state\n if (!appInfo.appLocalState.keyValue || appInfo.appLocalState.keyValue.length === 0) {\n return {}\n }\n\n const convertedState = appInfo.appLocalState.keyValue.map((kv) => ({ key: kv.key, value: kv.value }))\n\n return AppManager.decodeAppState(convertedState)\n }\n\n /**\n * Returns the names of the current boxes for the given app.\n * @param appId The ID of the app return box names for\n * @returns The current box names\n * @example\n * ```typescript\n * const boxNames = await appManager.getBoxNames(12353n);\n * ```\n */\n public async getBoxNames(appId: bigint): Promise<BoxName[]> {\n const boxResult = await this._algod.applicationBoxes(appId)\n return boxResult.boxes.map((b: { name: Uint8Array }) => {\n return { nameRaw: b.name, nameBase64: Buffer.from(b.name).toString('base64'), name: Buffer.from(b.name).toString('utf-8') }\n })\n }\n\n /**\n * Returns the value of the given box name for the given app.\n * @param appId The ID of the app return box names for\n * @param boxName 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 * @example\n * ```typescript\n * const boxValue = await appManager.getBoxValue(12353n, 'boxName');\n * ```\n */\n public async getBoxValue(appId: bigint, boxName: BoxIdentifier | BoxName): Promise<Uint8Array> {\n const boxId = typeof boxName === 'object' && 'nameRaw' in boxName ? boxName.nameRaw : boxName\n const name = AppManager.getBoxReference(boxId).name\n const boxResult = await this._algod.applicationBoxByName(Number(appId), name)\n return boxResult.value\n }\n\n /**\n * Returns the value of the given box names for the given app.\n * @param appId The ID of the app return box names for\n * @param boxNames The names of the boxes to return either as a string, binary array or `BoxName`\n * @returns The current box values as a byte array in the same order as the passed in box names\n * @example\n * ```typescript\n * const boxValues = await appManager.getBoxValues(12353n, ['boxName1', 'boxName2']);\n * ```\n */\n public async getBoxValues(appId: bigint, boxNames: (BoxIdentifier | BoxName)[]): Promise<Uint8Array[]> {\n return await Promise.all(boxNames.map(async (boxName) => await this.getBoxValue(appId, boxName)))\n }\n\n /**\n * Returns the value of the given box name for the given app decoded based on the given ABI type.\n * @param request The parameters for the box value request\n * @returns The current box value as an ABI value\n * @example\n * ```typescript\n * const boxValue = await appManager.getBoxValueFromABIType({ appId: 12353n, boxName: 'boxName', type: new ABIUintType(32) });\n * ```\n */\n public async getBoxValueFromABIType(request: BoxValueRequestParams): Promise<ABIValue> {\n const { appId, boxName, type } = request\n const value = await this.getBoxValue(appId, boxName)\n return type.decode(value)\n }\n\n /**\n * Returns the value of the given box names for the given app decoded based on the given ABI type.\n * @param request The parameters for the box value request\n * @returns The current box values as an ABI value in the same order as the passed in box names\n * @example\n * ```typescript\n * const boxValues = await appManager.getBoxValuesFromABIType({ appId: 12353n, boxNames: ['boxName1', 'boxName2'], type: new ABIUintType(32) });\n * ```\n */\n public async getBoxValuesFromABIType(request: BoxValuesRequestParams): Promise<ABIValue[]> {\n const { appId, boxNames, type } = request\n return await Promise.all(boxNames.map(async (boxName) => await this.getBoxValueFromABIType({ appId, boxName, type })))\n }\n\n /**\n * Returns a `algosdk.BoxReference` given a `BoxIdentifier` or `BoxReference`.\n * @param boxId The box to return a reference for\n * @returns The box reference ready to pass into a `algosdk.Transaction`\n * @example\n * ```typescript\n * const boxRef = AppManager.getBoxReference('boxName');\n * ```\n */\n public static getBoxReference(boxId: BoxIdentifier | BoxReference): TransactionBoxReference {\n const ref = typeof boxId === 'object' && 'appId' in boxId ? boxId : { appId: 0n, name: boxId }\n return {\n appId: ref.appId,\n name: typeof ref.name === 'string' ? new TextEncoder().encode(ref.name) : 'length' in ref.name ? ref.name : ref.name.addr.publicKey,\n } as TransactionBoxReference\n }\n\n /**\n * Converts an array of global/local state values from the algod api to a more friendly\n * generic object keyed by the UTF-8 value of the key.\n * @param state A `global-state`, `local-state`, `global-state-deltas` or `local-state-deltas`\n * @returns An object keyeed by the UTF-8 representation of the key with various parsings of the values\n * @example\n * ```typescript\n * const stateValues = AppManager.decodeAppState(state);\n * ```\n */\n public static decodeAppState(state: { key: Uint8Array; value: TealValue | EvalDelta }[]): AppState {\n const stateValues = {} as AppState\n\n // Start with empty set\n for (const stateVal of state) {\n const keyBase64 = Buffer.from(stateVal.key).toString('base64')\n const keyRaw = stateVal.key\n const key = Buffer.from(stateVal.key).toString('utf-8')\n const tealValue = stateVal.value\n\n const dataTypeFlag = Number('action' in tealValue ? tealValue.action : tealValue.type)\n let valueBase64: string\n let valueRaw: Buffer\n switch (dataTypeFlag) {\n case 1:\n valueBase64 =\n typeof tealValue.bytes === 'string' ? tealValue.bytes : tealValue.bytes ? Buffer.from(tealValue.bytes).toString('base64') : ''\n valueRaw = Buffer.from(valueBase64, 'base64')\n stateValues[key] = {\n keyRaw,\n keyBase64,\n valueRaw: new Uint8Array(valueRaw),\n valueBase64: valueBase64,\n value: valueRaw.toString('utf-8'),\n }\n break\n case 2: {\n const value = tealValue.uint ?? 0\n stateValues[key] = { keyRaw, keyBase64, value: BigInt(value) }\n break\n }\n default:\n throw new Error(`Received unknown state data type of ${dataTypeFlag}`)\n }\n }\n\n return stateValues\n }\n\n /**\n * Returns any ABI return values for the given app call arguments and transaction confirmation.\n * @param confirmation The transaction confirmation from algod\n * @param method The ABI method\n * @returns The return value for the method call\n * @example\n * ```typescript\n * const returnValue = AppManager.getABIReturn(confirmation, ABIMethod.fromSignature('hello(string)void'));\n * ```\n */\n public static getABIReturn(confirmation: PendingTransactionResponse | undefined, method: ABIMethod | undefined): ABIReturn | undefined {\n if (!method || !confirmation) {\n return undefined\n }\n\n if (method.returns.type === 'void') {\n return { method, rawReturnValue: undefined, returnValue: undefined }\n }\n\n try {\n const logs = confirmation.logs || []\n if (logs.length === 0) {\n throw new Error(`App call transaction did not log a return value`)\n }\n const lastLog = logs[logs.length - 1]\n if (!AppManager.hasAbiReturnPrefix(lastLog)) {\n throw new Error(`App call transaction did not log an ABI return value`)\n }\n\n const rawReturnValue = new Uint8Array(lastLog.slice(4))\n return { method: method, rawReturnValue, decodeError: undefined, returnValue: method.returns.type.decode(rawReturnValue) }\n } catch (err) {\n return { method: method, rawReturnValue: undefined, decodeError: err as Error, returnValue: undefined }\n }\n }\n\n private static hasAbiReturnPrefix(log: Uint8Array): boolean {\n if (log.length < ABI_RETURN_PREFIX.length) {\n return false\n }\n for (let i = 0; i < ABI_RETURN_PREFIX.length; i++) {\n if (log[i] !== ABI_RETURN_PREFIX[i]) {\n return false\n }\n }\n return true\n }\n\n /**\n * Replaces AlgoKit deploy-time deployment control parameters within the given TEAL template code.\n *\n * * `TMPL_UPDATABLE` for updatability / immutability control\n * * `TMPL_DELETABLE` for deletability / permanence control\n *\n * Note: If these values are defined, but the corresponding `TMPL_*` value\n * isn't in the teal code it will throw an exception.\n *\n * @param tealTemplateCode The TEAL template code to substitute\n * @param params The deploy-time deployment control parameter value to replace\n * @returns The replaced TEAL code\n * @example\n * ```typescript\n * const tealCode = AppManager.replaceTealTemplateDeployTimeControlParams(tealTemplate, { updatable: true, deletable: false });\n * ```\n */\n static replaceTealTemplateDeployTimeControlParams(tealTemplateCode: string, params: { updatable?: boolean; deletable?: boolean }) {\n if (params.updatable !== undefined) {\n if (!tealTemplateCode.includes(UPDATABLE_TEMPLATE_NAME)) {\n throw new Error(\n `Deploy-time updatability control requested for app deployment, but ${UPDATABLE_TEMPLATE_NAME} not present in TEAL code`,\n )\n }\n tealTemplateCode = replaceTemplateVariable(tealTemplateCode, UPDATABLE_TEMPLATE_NAME, (params.updatable ? 1 : 0).toString())\n }\n\n if (params.deletable !== undefined) {\n if (!tealTemplateCode.includes(DELETABLE_TEMPLATE_NAME)) {\n throw new Error(\n `Deploy-time deletability control requested for app deployment, but ${DELETABLE_TEMPLATE_NAME} not present in TEAL code`,\n )\n }\n tealTemplateCode = replaceTemplateVariable(tealTemplateCode, DELETABLE_TEMPLATE_NAME, (params.deletable ? 1 : 0).toString())\n }\n\n return tealTemplateCode\n }\n\n /**\n * Performs template substitution of a teal file.\n *\n * Looks for `TMPL_{parameter}` for template replacements.\n *\n * @param tealTemplateCode The TEAL template code to make parameter replacements in\n * @param templateParams Any parameters to replace in the teal code\n * @returns The TEAL code with replacements\n * @example\n * ```typescript\n * const tealCode = AppManager.replaceTealTemplateParams(tealTemplate, { TMPL_APP_ID: 12345n });\n * ```\n */\n static replaceTealTemplateParams(tealTemplateCode: string, templateParams?: TealTemplateParams) {\n if (templateParams !== undefined) {\n for (const key in templateParams) {\n const value = templateParams[key]\n const token = `TMPL_${key.replace(/^TMPL_/, '')}`\n\n // If this is a number, first replace any byte representations of the number\n // These may appear in the TEAL in order to circumvent int compression and preserve PC values\n if (typeof value === 'number' || typeof value === 'bigint') {\n tealTemplateCode = tealTemplateCode.replace(new RegExp(`(?<=bytes )${token}`, 'g'), `0x${value.toString(16).padStart(16, '0')}`)\n\n // We could probably return here since mixing pushint and pushbytes is likely not going to happen, but might as well do both\n }\n\n tealTemplateCode = replaceTemplateVariable(\n tealTemplateCode,\n token,\n typeof value === 'string'\n ? `0x${Buffer.from(value, 'utf-8').toString('hex')}`\n : ArrayBuffer.isView(value)\n ? `0x${Buffer.from(value).toString('hex')}`\n : value.toString(),\n )\n }\n }\n\n return tealTemplateCode\n }\n\n /**\n * Remove comments from TEAL code (useful to reduce code size before compilation).\n *\n * @param tealCode The TEAL logic to strip\n * @returns The TEAL without comments\n * @example\n * ```typescript\n * const stripped = AppManager.stripTealComments(tealProgram);\n * ```\n */\n static stripTealComments(tealCode: string) {\n const stripCommentFromLine = (line: string) => {\n const commentIndex = findUnquotedString(line, '//')\n if (commentIndex === undefined) {\n return line\n }\n return line.slice(0, commentIndex).trimEnd()\n }\n\n return tealCode\n .split('\\n')\n .map((line) => stripCommentFromLine(line))\n .join('\\n')\n }\n}\n\n/**\n * Find the first string within a line of TEAL. Only matches outside of quotes and base64 are returned.\n * Returns undefined if not found\n */\nconst findUnquotedString = (line: string, token: string, startIndex: number = 0, _endIndex?: number): number | undefined => {\n const endIndex = _endIndex === undefined ? line.length : _endIndex\n let index = startIndex\n let inQuotes = false\n let inBase64 = false\n\n while (index < endIndex) {\n const currentChar = line[index]\n if ((currentChar === ' ' || currentChar === '(') && !inQuotes && lastTokenBase64(line, index)) {\n // enter base64\n inBase64 = true\n } else if ((currentChar === ' ' || currentChar === ')') && !inQuotes && inBase64) {\n // exit base64\n inBase64 = false\n } else if (currentChar === '\\\\' && inQuotes) {\n // escaped char, skip next character\n index += 1\n } else if (currentChar === '\"') {\n // quote boundary\n inQuotes = !inQuotes\n } else if (!inQuotes && !inBase64 && line.startsWith(token, index)) {\n // can test for match\n return index\n }\n index += 1\n }\n return undefined\n}\n\nconst lastTokenBase64 = (line: string, index: number): boolean => {\n try {\n const tokens = line.slice(0, index).split(/\\s+/)\n const last = tokens[tokens.length - 1]\n return ['base64', 'b64'].includes(last)\n } catch {\n return false\n }\n}\n\nfunction replaceTemplateVariable(program: string, token: string, replacement: string): string {\n const result: string[] = []\n const tokenIndexOffset = replacement.length - token.length\n\n const programLines = program.split('\\n')\n\n for (const line of programLines) {\n const _commentIndex = findUnquotedString(line, '//')\n const commentIndex = _commentIndex === undefined ? line.length : _commentIndex\n let code = line.substring(0, commentIndex)\n const comment = line.substring(commentIndex)\n let trailingIndex = 0\n\n while (true) {\n const tokenIndex = findTemplateToken(code, token, trailingIndex)\n if (tokenIndex === undefined) {\n break\n }\n trailingIndex = tokenIndex + token.length\n const prefix = code.substring(0, tokenIndex)\n const suffix = code.substring(trailingIndex)\n code = `${prefix}${replacement}${suffix}`\n trailingIndex += tokenIndexOffset\n }\n result.push(code + comment)\n }\n\n return result.join('\\n')\n}\n\nconst findTemplateToken = (line: string, token: string, startIndex: number = 0, _endIndex?: number): number | undefined => {\n const endIndex = _endIndex === undefined ? line.length : _endIndex\n\n let index = startIndex\n while (index < endIndex) {\n const tokenIndex = findUnquotedString(line, token, index, endIndex)\n if (tokenIndex === undefined) {\n break\n }\n const trailingIndex = tokenIndex + token.length\n if (\n (tokenIndex === 0 || !isValidTokenCharacter(line[tokenIndex - 1])) &&\n (trailingIndex >= line.length || !isValidTokenCharacter(line[trailingIndex]))\n ) {\n return tokenIndex\n }\n index = trailingIndex\n }\n return undefined\n}\n\nfunction isValidTokenCharacter(char: string): boolean {\n return char.length === 1 && (/\\w/.test(char) || char === '_')\n}\n"],"mappings":";;;;;;AAoGA,IAAa,aAAb,MAAa,WAAW;CACtB,AAAQ;CACR,AAAQ,sBAAoD,EAAE;;;;;CAM9D,YAAY,OAAoB;AAC9B,OAAK,SAAS;;;;;;;;;;;;;;;;;CAkBhB,MAAM,YAAY,UAAyC;AACzD,MAAI,KAAK,oBAAoB,UAC3B,QAAO,KAAK,oBAAoB;EAGlC,MAAM,WAAW,MAAM,K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AAO,OAAO,SAAS;AACnE,MAAI,eAAe,OACjB;EAEF,MAAM,gBAAgB,aAAa,MAAM;AACzC,OACG,eAAe,KAAK,CAAC,sBAAsB,KAAK,aAAa,GAAG,MAChE,iBAAiB,KAAK,UAAU,CAAC,sBAAsB,KAAK,eAAe,EAE5E,QAAO;AAET,UAAQ;;;AAKZ,SAAS,sBAAsB,MAAuB;AACpD,QAAO,KAAK,WAAW,MAAM,KAAK,KAAK,KAAK,IAAI,SAAS"}
1
+ {"version":3,"file":"app-manager.js","names":["ProgramSourceMap","getApplicationAddress","getAddress","valueBase64: string","valueRaw: Buffer","ABI_RETURN_PREFIX","UPDATABLE_TEMPLATE_NAME","DELETABLE_TEMPLATE_NAME","result: string[]"],"sources":["../../src/types/app-manager.ts"],"sourcesContent":["import { ABIMethod, ABIReturn, ABIType, ABIValue } from '@algorandfoundation/algokit-abi'\nimport { AlgodClient, EvalDelta, PendingTransactionResponse, TealValue } from '@algorandfoundation/algokit-algod-client'\nimport { Address, ProgramSourceMap, ReadableAddress, getAddress, getApplicationAddress } from '@algorandfoundation/algokit-common'\nimport { AddressWithTransactionSigner, BoxReference as TransactionBoxReference } from '@algorandfoundation/algokit-transact'\nimport {\n ABI_RETURN_PREFIX,\n BoxName,\n DELETABLE_TEMPLATE_NAME,\n UPDATABLE_TEMPLATE_NAME,\n type AppState,\n type CompiledTeal,\n type TealTemplateParams,\n} from './app'\n\n/** Information about an app. */\nexport interface AppInformation {\n /** The ID of the app. */\n appId: bigint\n /** The escrow address that the app operates with. */\n appAddress: Address\n /**\n * Approval program.\n */\n approvalProgram: Uint8Array\n /**\n * Clear state program.\n */\n clearStateProgram: Uint8Array\n /**\n * The address that created this application. This is the address where the\n * parameters and global state for this application can be found.\n */\n creator: Address\n /**\n * Current global state values.\n */\n globalState: AppState\n /** The number of allocated ints in per-user local state. */\n localInts: number\n /** The number of allocated byte slices in per-user local state. */\n localByteSlices: number\n /** The number of allocated ints in global state. */\n globalInts: number\n /** The number of allocated byte slices in global state. */\n globalByteSlices: number\n /** Any extra pages that are needed for the smart contract. */\n extraProgramPages?: number\n /** The number of updates to the application programs */\n version?: number\n}\n\n/**\n * Something that identifies an app box name - either a:\n * * `Uint8Array` (the actual binary of the box name)\n * * `string` (that will be encoded to a `Uint8Array`)\n * * `AddressWithSigner` (that will be encoded into the\n * public key address of the corresponding account)\n */\nexport type BoxIdentifier = string | Uint8Array | AddressWithTransactionSigner\n\n/**\n * A grouping of the app ID and name identifier to reference an app box.\n */\nexport interface BoxReference {\n /**\n * A unique application id\n */\n appId: bigint\n /**\n * Identifier for a box name\n */\n name: BoxIdentifier\n}\n\n/**\n * Parameters to get and decode a box value as an ABI type.\n */\nexport interface BoxValueRequestParams {\n /** The ID of the app return box names for */\n appId: bigint\n /** The name of the box to return either as a string, binary array or `BoxName` */\n boxName: BoxIdentifier\n /** The ABI type to decode the value using */\n type: ABIType\n}\n\n/**\n * Parameters to get and decode a box value as an ABI type.\n */\nexport interface BoxValuesRequestParams {\n /** The ID of the app return box names for */\n appId: bigint\n /** The names of the boxes to return either as a string, binary array or BoxName` */\n boxNames: BoxIdentifier[]\n /** The ABI type to decode the value using */\n type: ABIType\n}\n\n/** Allows management of application information. */\nexport class AppManager {\n private _algod: AlgodClient\n private _compilationResults: Record<string, CompiledTeal> = {}\n\n /**\n * Creates an `AppManager`\n * @param algod An algod instance\n */\n constructor(algod: AlgodClient) {\n this._algod = algod\n }\n\n /**\n * Compiles the given TEAL using algod and returns the result, including source map.\n *\n * The result of this compilation is also cached keyed by the TEAL\n * code so it can be retrieved via `getCompilationResult`.\n *\n * This function is re-entrant; it will only compile the same code once.\n *\n * @param tealCode The TEAL code\n * @returns The information about the compiled file\n * @example\n * ```typescript\n * const compiled = await appManager.compileTeal(tealProgram)\n * ```\n */\n async compileTeal(tealCode: string): Promise<CompiledTeal> {\n if (this._compilationResults[tealCode]) {\n return this._compilationResults[tealCode]\n }\n\n const compiled = await this._algod.tealCompile(tealCode, { sourcemap: true })\n const result = {\n teal: tealCode,\n compiled: compiled.result,\n compiledHash: compiled.hash,\n compiledBase64ToBytes: new Uint8Array(Buffer.from(compiled.result, 'base64')),\n sourceMap: new ProgramSourceMap(compiled.sourcemap as { version: number; sources: string[]; names: string[]; mappings: string }),\n }\n this._compilationResults[tealCode] = result\n\n return result\n }\n\n /**\n * Performs template substitution of a teal template and compiles it, returning the compiled result.\n *\n * Looks for `TMPL_{parameter}` for template replacements and replaces AlgoKit deploy-time control parameters\n * if deployment metadata is specified.\n *\n * * `TMPL_UPDATABLE` for updatability / immutability control\n * * `TMPL_DELETABLE` for deletability / permanence control\n *\n * @param tealTemplateCode The TEAL logic to compile\n * @param templateParams Any parameters to replace in the .teal file before compiling\n * @param deploymentMetadata The deployment metadata the app will be deployed with\n * @returns The information about the compiled code\n * @example\n * ```typescript\n * const compiled = await appManager.compileTealTemplate(tealTemplate, { TMPL_APP_ID: 12345n }, { updatable: true, deletable: false })\n * ```\n */\n async compileTealTemplate(\n tealTemplateCode: string,\n templateParams?: TealTemplateParams,\n deploymentMetadata?: { updatable?: boolean; deletable?: boolean },\n ): Promise<CompiledTeal> {\n let tealCode = AppManager.stripTealComments(tealTemplateCode)\n\n tealCode = AppManager.replaceTealTemplateParams(tealCode, templateParams)\n\n if (deploymentMetadata) {\n tealCode = AppManager.replaceTealTemplateDeployTimeControlParams(tealCode, deploymentMetadata)\n }\n\n return await this.compileTeal(tealCode)\n }\n\n /**\n * Returns a previous compilation result.\n * @param tealCode The TEAL code\n * @returns The information about the previously compiled file\n * or `undefined` if that TEAL code wasn't previously compiled\n * @example\n * ```typescript\n * const compiled = appManager.getCompilationResult(tealProgram)\n * ```\n */\n getCompilationResult(tealCode: string): CompiledTeal | undefined {\n return this._compilationResults[tealCode]\n }\n\n /**\n * Returns the current app information for the app with the given ID.\n *\n * @example\n * ```typescript\n * const appInfo = await appManager.getById(12353n);\n * ```\n *\n * @param appId The ID of the app\n * @returns The app information\n */\n public async getById(appId: bigint): Promise<AppInformation> {\n const app = await this._algod.applicationById(appId)\n const convertedGlobalState = (app.params.globalState ?? []).map((kv) => ({ key: kv.key, value: kv.value }))\n\n return {\n appId: BigInt(app.id),\n appAddress: getApplicationAddress(app.id),\n approvalProgram: app.params.approvalProgram,\n clearStateProgram: app.params.clearStateProgram,\n creator: app.params.creator,\n localInts: app.params.localStateSchema?.numUints ?? 0,\n localByteSlices: app.params.localStateSchema?.numByteSlices ?? 0,\n globalInts: app.params.globalStateSchema?.numUints ?? 0,\n globalByteSlices: app.params.globalStateSchema?.numByteSlices ?? 0,\n extraProgramPages: app.params.extraProgramPages ?? 0,\n globalState: AppManager.decodeAppState(convertedGlobalState),\n version: app.params.version,\n }\n }\n\n /**\n * Returns the current global state values for the given app ID and account address\n *\n * @param appId The ID of the app to return global state for\n * @returns The current global state for the given app\n * @example\n * ```typescript\n * const globalState = await appManager.getGlobalState(12353n);\n * ```\n */\n public async getGlobalState(appId: bigint) {\n return (await this.getById(appId)).globalState\n }\n\n /**\n * Returns the current local state values for the given app ID and account address\n *\n * @param appId The ID of the app to return local state for\n * @param address The string address of the account to get local state for the given app\n * @returns The current local state for the given (app, account) combination\n * @example\n * ```typescript\n * const localState = await appManager.getLocalState(12353n, 'ACCOUNTADDRESS');\n * ```\n */\n public async getLocalState(appId: bigint, address: ReadableAddress) {\n const appInfo = await this._algod.accountApplicationInformation(getAddress(address).toString(), Number(appId))\n\n if (!appInfo.appLocalState) {\n throw new Error(\"Couldn't find local state\")\n }\n\n // If keyValue is undefined or empty, return empty state\n if (!appInfo.appLocalState.keyValue || appInfo.appLocalState.keyValue.length === 0) {\n return {}\n }\n\n const convertedState = appInfo.appLocalState.keyValue.map((kv) => ({ key: kv.key, value: kv.value }))\n\n return AppManager.decodeAppState(convertedState)\n }\n\n /**\n * Returns the names of the current boxes for the given app.\n * @param appId The ID of the app return box names for\n * @returns The current box names\n * @example\n * ```typescript\n * const boxNames = await appManager.getBoxNames(12353n);\n * ```\n */\n public async getBoxNames(appId: bigint): Promise<BoxName[]> {\n const boxResult = await this._algod.applicationBoxes(appId)\n return boxResult.boxes.map((b: { name: Uint8Array }) => {\n return { nameRaw: b.name, nameBase64: Buffer.from(b.name).toString('base64'), name: Buffer.from(b.name).toString('utf-8') }\n })\n }\n\n /**\n * Returns the value of the given box name for the given app.\n * @param appId The ID of the app return box names for\n * @param boxName 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 * @example\n * ```typescript\n * const boxValue = await appManager.getBoxValue(12353n, 'boxName');\n * ```\n */\n public async getBoxValue(appId: bigint, boxName: BoxIdentifier | BoxName): Promise<Uint8Array> {\n const boxId = typeof boxName === 'object' && 'nameRaw' in boxName ? boxName.nameRaw : boxName\n const name = AppManager.getBoxReference(boxId).name\n const boxResult = await this._algod.applicationBoxByName(Number(appId), name)\n return boxResult.value\n }\n\n /**\n * Returns the value of the given box names for the given app.\n * @param appId The ID of the app return box names for\n * @param boxNames The names of the boxes to return either as a string, binary array or `BoxName`\n * @returns The current box values as a byte array in the same order as the passed in box names\n * @example\n * ```typescript\n * const boxValues = await appManager.getBoxValues(12353n, ['boxName1', 'boxName2']);\n * ```\n */\n public async getBoxValues(appId: bigint, boxNames: (BoxIdentifier | BoxName)[]): Promise<Uint8Array[]> {\n return await Promise.all(boxNames.map(async (boxName) => await this.getBoxValue(appId, boxName)))\n }\n\n /**\n * Returns the value of the given box name for the given app decoded based on the given ABI type.\n * @param request The parameters for the box value request\n * @returns The current box value as an ABI value\n * @example\n * ```typescript\n * const boxValue = await appManager.getBoxValueFromABIType({ appId: 12353n, boxName: 'boxName', type: new ABIUintType(32) });\n * ```\n */\n public async getBoxValueFromABIType(request: BoxValueRequestParams): Promise<ABIValue> {\n const { appId, boxName, type } = request\n const value = await this.getBoxValue(appId, boxName)\n return type.decode(value)\n }\n\n /**\n * Returns the value of the given box names for the given app decoded based on the given ABI type.\n * @param request The parameters for the box value request\n * @returns The current box values as an ABI value in the same order as the passed in box names\n * @example\n * ```typescript\n * const boxValues = await appManager.getBoxValuesFromABIType({ appId: 12353n, boxNames: ['boxName1', 'boxName2'], type: new ABIUintType(32) });\n * ```\n */\n public async getBoxValuesFromABIType(request: BoxValuesRequestParams): Promise<ABIValue[]> {\n const { appId, boxNames, type } = request\n return await Promise.all(boxNames.map(async (boxName) => await this.getBoxValueFromABIType({ appId, boxName, type })))\n }\n\n /**\n * Returns a `algosdk.BoxReference` given a `BoxIdentifier` or `BoxReference`.\n * @param boxId The box to return a reference for\n * @returns The box reference ready to pass into a `algosdk.Transaction`\n * @example\n * ```typescript\n * const boxRef = AppManager.getBoxReference('boxName');\n * ```\n */\n public static getBoxReference(boxId: BoxIdentifier | BoxReference): TransactionBoxReference {\n const ref = typeof boxId === 'object' && 'appId' in boxId ? boxId : { appId: 0n, name: boxId }\n return {\n appId: ref.appId,\n name: typeof ref.name === 'string' ? new TextEncoder().encode(ref.name) : 'length' in ref.name ? ref.name : ref.name.addr.publicKey,\n } as TransactionBoxReference\n }\n\n /**\n * Converts an array of global/local state values from the algod api to a more friendly\n * generic object keyed by the UTF-8 value of the key.\n * @param state A `global-state`, `local-state`, `global-state-deltas` or `local-state-deltas`\n * @returns An object keyeed by the UTF-8 representation of the key with various parsings of the values\n * @example\n * ```typescript\n * const stateValues = AppManager.decodeAppState(state);\n * ```\n */\n public static decodeAppState(state: { key: Uint8Array; value: TealValue | EvalDelta }[]): AppState {\n const stateValues = {} as AppState\n\n // Start with empty set\n for (const stateVal of state) {\n const keyBase64 = Buffer.from(stateVal.key).toString('base64')\n const keyRaw = stateVal.key\n const key = Buffer.from(stateVal.key).toString('utf-8')\n const tealValue = stateVal.value\n\n const dataTypeFlag = Number('action' in tealValue ? tealValue.action : tealValue.type)\n let valueBase64: string\n let valueRaw: Buffer\n switch (dataTypeFlag) {\n case 1:\n valueBase64 =\n typeof tealValue.bytes === 'string' ? tealValue.bytes : tealValue.bytes ? Buffer.from(tealValue.bytes).toString('base64') : ''\n valueRaw = Buffer.from(valueBase64, 'base64')\n stateValues[key] = {\n keyRaw,\n keyBase64,\n valueRaw: new Uint8Array(valueRaw),\n valueBase64: valueBase64,\n value: valueRaw.toString('utf-8'),\n }\n break\n case 2: {\n const value = tealValue.uint ?? 0\n stateValues[key] = { keyRaw, keyBase64, value: BigInt(value) }\n break\n }\n default:\n throw new Error(`Received unknown state data type of ${dataTypeFlag}`)\n }\n }\n\n return stateValues\n }\n\n /**\n * Returns any ABI return values for the given app call arguments and transaction confirmation.\n * @param confirmation The transaction confirmation from algod\n * @param method The ABI method\n * @returns The return value for the method call\n * @example\n * ```typescript\n * const returnValue = AppManager.getABIReturn(confirmation, ABIMethod.fromSignature('hello(string)void'));\n * ```\n */\n public static getABIReturn(confirmation: PendingTransactionResponse | undefined, method: ABIMethod | undefined): ABIReturn | undefined {\n if (!method || !confirmation) {\n return undefined\n }\n\n if (method.returns.type === 'void') {\n return { method, rawReturnValue: undefined, returnValue: undefined }\n }\n\n try {\n const logs = confirmation.logs || []\n if (logs.length === 0) {\n throw new Error(`App call transaction did not log a return value`)\n }\n const lastLog = logs[logs.length - 1]\n if (!AppManager.hasAbiReturnPrefix(lastLog)) {\n throw new Error(`App call transaction did not log an ABI return value`)\n }\n\n const rawReturnValue = new Uint8Array(lastLog.slice(4))\n return { method: method, rawReturnValue, decodeError: undefined, returnValue: method.returns.type.decode(rawReturnValue) }\n } catch (err) {\n return { method: method, rawReturnValue: undefined, decodeError: err as Error, returnValue: undefined }\n }\n }\n\n private static hasAbiReturnPrefix(log: Uint8Array): boolean {\n if (log.length < ABI_RETURN_PREFIX.length) {\n return false\n }\n for (let i = 0; i < ABI_RETURN_PREFIX.length; i++) {\n if (log[i] !== ABI_RETURN_PREFIX[i]) {\n return false\n }\n }\n return true\n }\n\n /**\n * Replaces AlgoKit deploy-time deployment control parameters within the given TEAL template code.\n *\n * * `TMPL_UPDATABLE` for updatability / immutability control\n * * `TMPL_DELETABLE` for deletability / permanence control\n *\n * Note: If these values are defined, but the corresponding `TMPL_*` value\n * isn't in the teal code it will throw an exception.\n *\n * @param tealTemplateCode The TEAL template code to substitute\n * @param params The deploy-time deployment control parameter value to replace\n * @returns The replaced TEAL code\n * @example\n * ```typescript\n * const tealCode = AppManager.replaceTealTemplateDeployTimeControlParams(tealTemplate, { updatable: true, deletable: false });\n * ```\n */\n static replaceTealTemplateDeployTimeControlParams(tealTemplateCode: string, params: { updatable?: boolean; deletable?: boolean }) {\n if (params.updatable !== undefined) {\n if (!tealTemplateCode.includes(UPDATABLE_TEMPLATE_NAME)) {\n throw new Error(\n `Deploy-time updatability control requested for app deployment, but ${UPDATABLE_TEMPLATE_NAME} not present in TEAL code`,\n )\n }\n tealTemplateCode = replaceTemplateVariable(tealTemplateCode, UPDATABLE_TEMPLATE_NAME, (params.updatable ? 1 : 0).toString())\n }\n\n if (params.deletable !== undefined) {\n if (!tealTemplateCode.includes(DELETABLE_TEMPLATE_NAME)) {\n throw new Error(\n `Deploy-time deletability control requested for app deployment, but ${DELETABLE_TEMPLATE_NAME} not present in TEAL code`,\n )\n }\n tealTemplateCode = replaceTemplateVariable(tealTemplateCode, DELETABLE_TEMPLATE_NAME, (params.deletable ? 1 : 0).toString())\n }\n\n return tealTemplateCode\n }\n\n /**\n * Performs template substitution of a teal file.\n *\n * Looks for `TMPL_{parameter}` for template replacements.\n *\n * @param tealTemplateCode The TEAL template code to make parameter replacements in\n * @param templateParams Any parameters to replace in the teal code\n * @returns The TEAL code with replacements\n * @example\n * ```typescript\n * const tealCode = AppManager.replaceTealTemplateParams(tealTemplate, { TMPL_APP_ID: 12345n });\n * ```\n */\n static replaceTealTemplateParams(tealTemplateCode: string, templateParams?: TealTemplateParams) {\n if (templateParams !== undefined) {\n for (const key in templateParams) {\n const value = templateParams[key]\n const token = `TMPL_${key.replace(/^TMPL_/, '')}`\n\n // If this is a number, first replace any byte representations of the number\n // These may appear in the TEAL in order to circumvent int compression and preserve PC values\n if (typeof value === 'number' || typeof value === 'bigint') {\n tealTemplateCode = tealTemplateCode.replace(new RegExp(`(?<=bytes )${token}`, 'g'), `0x${value.toString(16).padStart(16, '0')}`)\n\n // We could probably return here since mixing pushint and pushbytes is likely not going to happen, but might as well do both\n }\n\n tealTemplateCode = replaceTemplateVariable(\n tealTemplateCode,\n token,\n typeof value === 'string'\n ? `0x${Buffer.from(value, 'utf-8').toString('hex')}`\n : ArrayBuffer.isView(value)\n ? `0x${Buffer.from(value).toString('hex')}`\n : value.toString(),\n )\n }\n }\n\n return tealTemplateCode\n }\n\n /**\n * Remove comments from TEAL code (useful to reduce code size before compilation).\n *\n * @param tealCode The TEAL logic to strip\n * @returns The TEAL without comments\n * @example\n * ```typescript\n * const stripped = AppManager.stripTealComments(tealProgram);\n * ```\n */\n static stripTealComments(tealCode: string) {\n const stripCommentFromLine = (line: string) => {\n const commentIndex = findUnquotedString(line, '//')\n if (commentIndex === undefined) {\n return line\n }\n return line.slice(0, commentIndex).trimEnd()\n }\n\n return tealCode\n .split('\\n')\n .map((line) => stripCommentFromLine(line))\n .join('\\n')\n }\n}\n\n/**\n * Find the first string within a line of TEAL. Only matches outside of quotes and base64 are returned.\n * Returns undefined if not found\n */\nconst findUnquotedString = (line: string, token: string, startIndex: number = 0, _endIndex?: number): number | undefined => {\n const endIndex = _endIndex === undefined ? line.length : _endIndex\n let index = startIndex\n let inQuotes = false\n let inBase64 = false\n\n while (index < endIndex) {\n const currentChar = line[index]\n if ((currentChar === ' ' || currentChar === '(') && !inQuotes && lastTokenBase64(line, index)) {\n // enter base64\n inBase64 = true\n } else if ((currentChar === ' ' || currentChar === ')') && !inQuotes && inBase64) {\n // exit base64\n inBase64 = false\n } else if (currentChar === '\\\\' && inQuotes) {\n // escaped char, skip next character\n index += 1\n } else if (currentChar === '\"') {\n // quote boundary\n inQuotes = !inQuotes\n } else if (!inQuotes && !inBase64 && line.startsWith(token, index)) {\n // can test for match\n return index\n }\n index += 1\n }\n return undefined\n}\n\nconst lastTokenBase64 = (line: string, index: number): boolean => {\n try {\n const tokens = line.slice(0, index).split(/\\s+/)\n const last = tokens[tokens.length - 1]\n return ['base64', 'b64'].includes(last)\n } catch {\n return false\n }\n}\n\nfunction replaceTemplateVariable(program: string, token: string, replacement: string): string {\n const result: string[] = []\n const tokenIndexOffset = replacement.length - token.length\n\n const programLines = program.split('\\n')\n\n for (const line of programLines) {\n const _commentIndex = findUnquotedString(line, '//')\n const commentIndex = _commentIndex === undefined ? line.length : _commentIndex\n let code = line.substring(0, commentIndex)\n const comment = line.substring(commentIndex)\n let trailingIndex = 0\n\n while (true) {\n const tokenIndex = findTemplateToken(code, token, trailingIndex)\n if (tokenIndex === undefined) {\n break\n }\n trailingIndex = tokenIndex + token.length\n const prefix = code.substring(0, tokenIndex)\n const suffix = code.substring(trailingIndex)\n code = `${prefix}${replacement}${suffix}`\n trailingIndex += tokenIndexOffset\n }\n result.push(code + comment)\n }\n\n return result.join('\\n')\n}\n\nconst findTemplateToken = (line: string, token: string, startIndex: number = 0, _endIndex?: number): number | undefined => {\n const endIndex = _endIndex === undefined ? line.length : _endIndex\n\n let index = startIndex\n while (index < endIndex) {\n const tokenIndex = findUnquotedString(line, token, index, endIndex)\n if (tokenIndex === undefined) {\n break\n }\n const trailingIndex = tokenIndex + token.length\n if (\n (tokenIndex === 0 || !isValidTokenCharacter(line[tokenIndex - 1])) &&\n (trailingIndex >= line.length || !isValidTokenCharacter(line[trailingIndex]))\n ) {\n return tokenIndex\n }\n index = trailingIndex\n }\n return undefined\n}\n\nfunction isValidTokenCharacter(char: string): boolean {\n return char.length === 1 && (/\\w/.test(char) || char === '_')\n}\n"],"mappings":";;;;;;AAmGA,IAAa,aAAb,MAAa,WAAW;CACtB,AAAQ;CACR,AAAQ,sBAAoD,EAAE;;;;;CAM9D,YAAY,OAAoB;AAC9B,OAAK,SAAS;;;;;;;;;;;;;;;;;CAkBhB,MAAM,YAAY,UAAyC;AACzD,MAAI,KAAK,oBAAoB,UAC3B,QAAO,KAAK,oBAAoB;EAGlC,MAAM,WAAW,MAAM,KAAK,OAAO,YAAY,UAAU,EA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AI,eAAe,OACjB;EAEF,MAAM,gBAAgB,aAAa,MAAM;AACzC,OACG,eAAe,KAAK,CAAC,sBAAsB,KAAK,aAAa,GAAG,MAChE,iBAAiB,KAAK,UAAU,CAAC,sBAAsB,KAAK,eAAe,EAE5E,QAAO;AAET,UAAQ;;;AAKZ,SAAS,sBAAsB,MAAuB;AACpD,QAAO,KAAK,WAAW,MAAM,KAAK,KAAK,KAAK,IAAI,SAAS"}
@@ -1,6 +1,6 @@
1
1
  import { getAddress, getApplicationAddress } from "../packages/common/src/address.mjs";
2
- import { ProgramSourceMap } from "../packages/sdk/src/logic/sourcemap.mjs";
3
2
  import { ABI_RETURN_PREFIX, DELETABLE_TEMPLATE_NAME, UPDATABLE_TEMPLATE_NAME } from "./app.mjs";
3
+ import { ProgramSourceMap } from "../packages/common/src/sourcemap.mjs";
4
4
 
5
5
  //#region src/types/app-manager.ts
6
6
  /** Allows management of application information. */
@@ -1 +1 @@
1
- {"version":3,"file":"app-manager.mjs","names":["valueBase64: string","valueRaw: Buffer","result: string[]"],"sources":["../../src/types/app-manager.ts"],"sourcesContent":["import { ABIMethod, ABIReturn, ABIType, ABIValue } from '@algorandfoundation/algokit-abi'\nimport { AlgodClient, EvalDelta, PendingTransactionResponse, TealValue } from '@algorandfoundation/algokit-algod-client'\nimport { Address, ReadableAddress, getAddress, getApplicationAddress } from '@algorandfoundation/algokit-common'\nimport { AddressWithTransactionSigner, BoxReference as TransactionBoxReference } from '@algorandfoundation/algokit-transact'\nimport { ProgramSourceMap } from '@algorandfoundation/sdk'\nimport {\n ABI_RETURN_PREFIX,\n BoxName,\n DELETABLE_TEMPLATE_NAME,\n UPDATABLE_TEMPLATE_NAME,\n type AppState,\n type CompiledTeal,\n type TealTemplateParams,\n} from './app'\n\n/** Information about an app. */\nexport interface AppInformation {\n /** The ID of the app. */\n appId: bigint\n /** The escrow address that the app operates with. */\n appAddress: Address\n /**\n * Approval program.\n */\n approvalProgram: Uint8Array\n /**\n * Clear state program.\n */\n clearStateProgram: Uint8Array\n /**\n * The address that created this application. This is the address where the\n * parameters and global state for this application can be found.\n */\n creator: Address\n /**\n * Current global state values.\n */\n globalState: AppState\n /** The number of allocated ints in per-user local state. */\n localInts: number\n /** The number of allocated byte slices in per-user local state. */\n localByteSlices: number\n /** The number of allocated ints in global state. */\n globalInts: number\n /** The number of allocated byte slices in global state. */\n globalByteSlices: number\n /** Any extra pages that are needed for the smart contract. */\n extraProgramPages?: number\n /** The number of updates to the application programs */\n version?: number\n}\n\n/**\n * Something that identifies an app box name - either a:\n * * `Uint8Array` (the actual binary of the box name)\n * * `string` (that will be encoded to a `Uint8Array`)\n * * `AddressWithSigner` (that will be encoded into the\n * public key address of the corresponding account)\n */\nexport type BoxIdentifier = string | Uint8Array | AddressWithTransactionSigner\n\n/**\n * A grouping of the app ID and name identifier to reference an app box.\n */\nexport interface BoxReference {\n /**\n * A unique application id\n */\n appId: bigint\n /**\n * Identifier for a box name\n */\n name: BoxIdentifier\n}\n\n/**\n * Parameters to get and decode a box value as an ABI type.\n */\nexport interface BoxValueRequestParams {\n /** The ID of the app return box names for */\n appId: bigint\n /** The name of the box to return either as a string, binary array or `BoxName` */\n boxName: BoxIdentifier\n /** The ABI type to decode the value using */\n type: ABIType\n}\n\n/**\n * Parameters to get and decode a box value as an ABI type.\n */\nexport interface BoxValuesRequestParams {\n /** The ID of the app return box names for */\n appId: bigint\n /** The names of the boxes to return either as a string, binary array or BoxName` */\n boxNames: BoxIdentifier[]\n /** The ABI type to decode the value using */\n type: ABIType\n}\n\n/** Allows management of application information. */\nexport class AppManager {\n private _algod: AlgodClient\n private _compilationResults: Record<string, CompiledTeal> = {}\n\n /**\n * Creates an `AppManager`\n * @param algod An algod instance\n */\n constructor(algod: AlgodClient) {\n this._algod = algod\n }\n\n /**\n * Compiles the given TEAL using algod and returns the result, including source map.\n *\n * The result of this compilation is also cached keyed by the TEAL\n * code so it can be retrieved via `getCompilationResult`.\n *\n * This function is re-entrant; it will only compile the same code once.\n *\n * @param tealCode The TEAL code\n * @returns The information about the compiled file\n * @example\n * ```typescript\n * const compiled = await appManager.compileTeal(tealProgram)\n * ```\n */\n async compileTeal(tealCode: string): Promise<CompiledTeal> {\n if (this._compilationResults[tealCode]) {\n return this._compilationResults[tealCode]\n }\n\n const compiled = await this._algod.tealCompile(tealCode, { sourcemap: true })\n const result = {\n teal: tealCode,\n compiled: compiled.result,\n compiledHash: compiled.hash,\n compiledBase64ToBytes: new Uint8Array(Buffer.from(compiled.result, 'base64')),\n sourceMap: new ProgramSourceMap(compiled.sourcemap as { version: number; sources: string[]; names: string[]; mappings: string }),\n }\n this._compilationResults[tealCode] = result\n\n return result\n }\n\n /**\n * Performs template substitution of a teal template and compiles it, returning the compiled result.\n *\n * Looks for `TMPL_{parameter}` for template replacements and replaces AlgoKit deploy-time control parameters\n * if deployment metadata is specified.\n *\n * * `TMPL_UPDATABLE` for updatability / immutability control\n * * `TMPL_DELETABLE` for deletability / permanence control\n *\n * @param tealTemplateCode The TEAL logic to compile\n * @param templateParams Any parameters to replace in the .teal file before compiling\n * @param deploymentMetadata The deployment metadata the app will be deployed with\n * @returns The information about the compiled code\n * @example\n * ```typescript\n * const compiled = await appManager.compileTealTemplate(tealTemplate, { TMPL_APP_ID: 12345n }, { updatable: true, deletable: false })\n * ```\n */\n async compileTealTemplate(\n tealTemplateCode: string,\n templateParams?: TealTemplateParams,\n deploymentMetadata?: { updatable?: boolean; deletable?: boolean },\n ): Promise<CompiledTeal> {\n let tealCode = AppManager.stripTealComments(tealTemplateCode)\n\n tealCode = AppManager.replaceTealTemplateParams(tealCode, templateParams)\n\n if (deploymentMetadata) {\n tealCode = AppManager.replaceTealTemplateDeployTimeControlParams(tealCode, deploymentMetadata)\n }\n\n return await this.compileTeal(tealCode)\n }\n\n /**\n * Returns a previous compilation result.\n * @param tealCode The TEAL code\n * @returns The information about the previously compiled file\n * or `undefined` if that TEAL code wasn't previously compiled\n * @example\n * ```typescript\n * const compiled = appManager.getCompilationResult(tealProgram)\n * ```\n */\n getCompilationResult(tealCode: string): CompiledTeal | undefined {\n return this._compilationResults[tealCode]\n }\n\n /**\n * Returns the current app information for the app with the given ID.\n *\n * @example\n * ```typescript\n * const appInfo = await appManager.getById(12353n);\n * ```\n *\n * @param appId The ID of the app\n * @returns The app information\n */\n public async getById(appId: bigint): Promise<AppInformation> {\n const app = await this._algod.applicationById(appId)\n const convertedGlobalState = (app.params.globalState ?? []).map((kv) => ({ key: kv.key, value: kv.value }))\n\n return {\n appId: BigInt(app.id),\n appAddress: getApplicationAddress(app.id),\n approvalProgram: app.params.approvalProgram,\n clearStateProgram: app.params.clearStateProgram,\n creator: app.params.creator,\n localInts: app.params.localStateSchema?.numUints ?? 0,\n localByteSlices: app.params.localStateSchema?.numByteSlices ?? 0,\n globalInts: app.params.globalStateSchema?.numUints ?? 0,\n globalByteSlices: app.params.globalStateSchema?.numByteSlices ?? 0,\n extraProgramPages: app.params.extraProgramPages ?? 0,\n globalState: AppManager.decodeAppState(convertedGlobalState),\n version: app.params.version,\n }\n }\n\n /**\n * Returns the current global state values for the given app ID and account address\n *\n * @param appId The ID of the app to return global state for\n * @returns The current global state for the given app\n * @example\n * ```typescript\n * const globalState = await appManager.getGlobalState(12353n);\n * ```\n */\n public async getGlobalState(appId: bigint) {\n return (await this.getById(appId)).globalState\n }\n\n /**\n * Returns the current local state values for the given app ID and account address\n *\n * @param appId The ID of the app to return local state for\n * @param address The string address of the account to get local state for the given app\n * @returns The current local state for the given (app, account) combination\n * @example\n * ```typescript\n * const localState = await appManager.getLocalState(12353n, 'ACCOUNTADDRESS');\n * ```\n */\n public async getLocalState(appId: bigint, address: ReadableAddress) {\n const appInfo = await this._algod.accountApplicationInformation(getAddress(address).toString(), Number(appId))\n\n if (!appInfo.appLocalState) {\n throw new Error(\"Couldn't find local state\")\n }\n\n // If keyValue is undefined or empty, return empty state\n if (!appInfo.appLocalState.keyValue || appInfo.appLocalState.keyValue.length === 0) {\n return {}\n }\n\n const convertedState = appInfo.appLocalState.keyValue.map((kv) => ({ key: kv.key, value: kv.value }))\n\n return AppManager.decodeAppState(convertedState)\n }\n\n /**\n * Returns the names of the current boxes for the given app.\n * @param appId The ID of the app return box names for\n * @returns The current box names\n * @example\n * ```typescript\n * const boxNames = await appManager.getBoxNames(12353n);\n * ```\n */\n public async getBoxNames(appId: bigint): Promise<BoxName[]> {\n const boxResult = await this._algod.applicationBoxes(appId)\n return boxResult.boxes.map((b: { name: Uint8Array }) => {\n return { nameRaw: b.name, nameBase64: Buffer.from(b.name).toString('base64'), name: Buffer.from(b.name).toString('utf-8') }\n })\n }\n\n /**\n * Returns the value of the given box name for the given app.\n * @param appId The ID of the app return box names for\n * @param boxName 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 * @example\n * ```typescript\n * const boxValue = await appManager.getBoxValue(12353n, 'boxName');\n * ```\n */\n public async getBoxValue(appId: bigint, boxName: BoxIdentifier | BoxName): Promise<Uint8Array> {\n const boxId = typeof boxName === 'object' && 'nameRaw' in boxName ? boxName.nameRaw : boxName\n const name = AppManager.getBoxReference(boxId).name\n const boxResult = await this._algod.applicationBoxByName(Number(appId), name)\n return boxResult.value\n }\n\n /**\n * Returns the value of the given box names for the given app.\n * @param appId The ID of the app return box names for\n * @param boxNames The names of the boxes to return either as a string, binary array or `BoxName`\n * @returns The current box values as a byte array in the same order as the passed in box names\n * @example\n * ```typescript\n * const boxValues = await appManager.getBoxValues(12353n, ['boxName1', 'boxName2']);\n * ```\n */\n public async getBoxValues(appId: bigint, boxNames: (BoxIdentifier | BoxName)[]): Promise<Uint8Array[]> {\n return await Promise.all(boxNames.map(async (boxName) => await this.getBoxValue(appId, boxName)))\n }\n\n /**\n * Returns the value of the given box name for the given app decoded based on the given ABI type.\n * @param request The parameters for the box value request\n * @returns The current box value as an ABI value\n * @example\n * ```typescript\n * const boxValue = await appManager.getBoxValueFromABIType({ appId: 12353n, boxName: 'boxName', type: new ABIUintType(32) });\n * ```\n */\n public async getBoxValueFromABIType(request: BoxValueRequestParams): Promise<ABIValue> {\n const { appId, boxName, type } = request\n const value = await this.getBoxValue(appId, boxName)\n return type.decode(value)\n }\n\n /**\n * Returns the value of the given box names for the given app decoded based on the given ABI type.\n * @param request The parameters for the box value request\n * @returns The current box values as an ABI value in the same order as the passed in box names\n * @example\n * ```typescript\n * const boxValues = await appManager.getBoxValuesFromABIType({ appId: 12353n, boxNames: ['boxName1', 'boxName2'], type: new ABIUintType(32) });\n * ```\n */\n public async getBoxValuesFromABIType(request: BoxValuesRequestParams): Promise<ABIValue[]> {\n const { appId, boxNames, type } = request\n return await Promise.all(boxNames.map(async (boxName) => await this.getBoxValueFromABIType({ appId, boxName, type })))\n }\n\n /**\n * Returns a `algosdk.BoxReference` given a `BoxIdentifier` or `BoxReference`.\n * @param boxId The box to return a reference for\n * @returns The box reference ready to pass into a `algosdk.Transaction`\n * @example\n * ```typescript\n * const boxRef = AppManager.getBoxReference('boxName');\n * ```\n */\n public static getBoxReference(boxId: BoxIdentifier | BoxReference): TransactionBoxReference {\n const ref = typeof boxId === 'object' && 'appId' in boxId ? boxId : { appId: 0n, name: boxId }\n return {\n appId: ref.appId,\n name: typeof ref.name === 'string' ? new TextEncoder().encode(ref.name) : 'length' in ref.name ? ref.name : ref.name.addr.publicKey,\n } as TransactionBoxReference\n }\n\n /**\n * Converts an array of global/local state values from the algod api to a more friendly\n * generic object keyed by the UTF-8 value of the key.\n * @param state A `global-state`, `local-state`, `global-state-deltas` or `local-state-deltas`\n * @returns An object keyeed by the UTF-8 representation of the key with various parsings of the values\n * @example\n * ```typescript\n * const stateValues = AppManager.decodeAppState(state);\n * ```\n */\n public static decodeAppState(state: { key: Uint8Array; value: TealValue | EvalDelta }[]): AppState {\n const stateValues = {} as AppState\n\n // Start with empty set\n for (const stateVal of state) {\n const keyBase64 = Buffer.from(stateVal.key).toString('base64')\n const keyRaw = stateVal.key\n const key = Buffer.from(stateVal.key).toString('utf-8')\n const tealValue = stateVal.value\n\n const dataTypeFlag = Number('action' in tealValue ? tealValue.action : tealValue.type)\n let valueBase64: string\n let valueRaw: Buffer\n switch (dataTypeFlag) {\n case 1:\n valueBase64 =\n typeof tealValue.bytes === 'string' ? tealValue.bytes : tealValue.bytes ? Buffer.from(tealValue.bytes).toString('base64') : ''\n valueRaw = Buffer.from(valueBase64, 'base64')\n stateValues[key] = {\n keyRaw,\n keyBase64,\n valueRaw: new Uint8Array(valueRaw),\n valueBase64: valueBase64,\n value: valueRaw.toString('utf-8'),\n }\n break\n case 2: {\n const value = tealValue.uint ?? 0\n stateValues[key] = { keyRaw, keyBase64, value: BigInt(value) }\n break\n }\n default:\n throw new Error(`Received unknown state data type of ${dataTypeFlag}`)\n }\n }\n\n return stateValues\n }\n\n /**\n * Returns any ABI return values for the given app call arguments and transaction confirmation.\n * @param confirmation The transaction confirmation from algod\n * @param method The ABI method\n * @returns The return value for the method call\n * @example\n * ```typescript\n * const returnValue = AppManager.getABIReturn(confirmation, ABIMethod.fromSignature('hello(string)void'));\n * ```\n */\n public static getABIReturn(confirmation: PendingTransactionResponse | undefined, method: ABIMethod | undefined): ABIReturn | undefined {\n if (!method || !confirmation) {\n return undefined\n }\n\n if (method.returns.type === 'void') {\n return { method, rawReturnValue: undefined, returnValue: undefined }\n }\n\n try {\n const logs = confirmation.logs || []\n if (logs.length === 0) {\n throw new Error(`App call transaction did not log a return value`)\n }\n const lastLog = logs[logs.length - 1]\n if (!AppManager.hasAbiReturnPrefix(lastLog)) {\n throw new Error(`App call transaction did not log an ABI return value`)\n }\n\n const rawReturnValue = new Uint8Array(lastLog.slice(4))\n return { method: method, rawReturnValue, decodeError: undefined, returnValue: method.returns.type.decode(rawReturnValue) }\n } catch (err) {\n return { method: method, rawReturnValue: undefined, decodeError: err as Error, returnValue: undefined }\n }\n }\n\n private static hasAbiReturnPrefix(log: Uint8Array): boolean {\n if (log.length < ABI_RETURN_PREFIX.length) {\n return false\n }\n for (let i = 0; i < ABI_RETURN_PREFIX.length; i++) {\n if (log[i] !== ABI_RETURN_PREFIX[i]) {\n return false\n }\n }\n return true\n }\n\n /**\n * Replaces AlgoKit deploy-time deployment control parameters within the given TEAL template code.\n *\n * * `TMPL_UPDATABLE` for updatability / immutability control\n * * `TMPL_DELETABLE` for deletability / permanence control\n *\n * Note: If these values are defined, but the corresponding `TMPL_*` value\n * isn't in the teal code it will throw an exception.\n *\n * @param tealTemplateCode The TEAL template code to substitute\n * @param params The deploy-time deployment control parameter value to replace\n * @returns The replaced TEAL code\n * @example\n * ```typescript\n * const tealCode = AppManager.replaceTealTemplateDeployTimeControlParams(tealTemplate, { updatable: true, deletable: false });\n * ```\n */\n static replaceTealTemplateDeployTimeControlParams(tealTemplateCode: string, params: { updatable?: boolean; deletable?: boolean }) {\n if (params.updatable !== undefined) {\n if (!tealTemplateCode.includes(UPDATABLE_TEMPLATE_NAME)) {\n throw new Error(\n `Deploy-time updatability control requested for app deployment, but ${UPDATABLE_TEMPLATE_NAME} not present in TEAL code`,\n )\n }\n tealTemplateCode = replaceTemplateVariable(tealTemplateCode, UPDATABLE_TEMPLATE_NAME, (params.updatable ? 1 : 0).toString())\n }\n\n if (params.deletable !== undefined) {\n if (!tealTemplateCode.includes(DELETABLE_TEMPLATE_NAME)) {\n throw new Error(\n `Deploy-time deletability control requested for app deployment, but ${DELETABLE_TEMPLATE_NAME} not present in TEAL code`,\n )\n }\n tealTemplateCode = replaceTemplateVariable(tealTemplateCode, DELETABLE_TEMPLATE_NAME, (params.deletable ? 1 : 0).toString())\n }\n\n return tealTemplateCode\n }\n\n /**\n * Performs template substitution of a teal file.\n *\n * Looks for `TMPL_{parameter}` for template replacements.\n *\n * @param tealTemplateCode The TEAL template code to make parameter replacements in\n * @param templateParams Any parameters to replace in the teal code\n * @returns The TEAL code with replacements\n * @example\n * ```typescript\n * const tealCode = AppManager.replaceTealTemplateParams(tealTemplate, { TMPL_APP_ID: 12345n });\n * ```\n */\n static replaceTealTemplateParams(tealTemplateCode: string, templateParams?: TealTemplateParams) {\n if (templateParams !== undefined) {\n for (const key in templateParams) {\n const value = templateParams[key]\n const token = `TMPL_${key.replace(/^TMPL_/, '')}`\n\n // If this is a number, first replace any byte representations of the number\n // These may appear in the TEAL in order to circumvent int compression and preserve PC values\n if (typeof value === 'number' || typeof value === 'bigint') {\n tealTemplateCode = tealTemplateCode.replace(new RegExp(`(?<=bytes )${token}`, 'g'), `0x${value.toString(16).padStart(16, '0')}`)\n\n // We could probably return here since mixing pushint and pushbytes is likely not going to happen, but might as well do both\n }\n\n tealTemplateCode = replaceTemplateVariable(\n tealTemplateCode,\n token,\n typeof value === 'string'\n ? `0x${Buffer.from(value, 'utf-8').toString('hex')}`\n : ArrayBuffer.isView(value)\n ? `0x${Buffer.from(value).toString('hex')}`\n : value.toString(),\n )\n }\n }\n\n return tealTemplateCode\n }\n\n /**\n * Remove comments from TEAL code (useful to reduce code size before compilation).\n *\n * @param tealCode The TEAL logic to strip\n * @returns The TEAL without comments\n * @example\n * ```typescript\n * const stripped = AppManager.stripTealComments(tealProgram);\n * ```\n */\n static stripTealComments(tealCode: string) {\n const stripCommentFromLine = (line: string) => {\n const commentIndex = findUnquotedString(line, '//')\n if (commentIndex === undefined) {\n return line\n }\n return line.slice(0, commentIndex).trimEnd()\n }\n\n return tealCode\n .split('\\n')\n .map((line) => stripCommentFromLine(line))\n .join('\\n')\n }\n}\n\n/**\n * Find the first string within a line of TEAL. Only matches outside of quotes and base64 are returned.\n * Returns undefined if not found\n */\nconst findUnquotedString = (line: string, token: string, startIndex: number = 0, _endIndex?: number): number | undefined => {\n const endIndex = _endIndex === undefined ? line.length : _endIndex\n let index = startIndex\n let inQuotes = false\n let inBase64 = false\n\n while (index < endIndex) {\n const currentChar = line[index]\n if ((currentChar === ' ' || currentChar === '(') && !inQuotes && lastTokenBase64(line, index)) {\n // enter base64\n inBase64 = true\n } else if ((currentChar === ' ' || currentChar === ')') && !inQuotes && inBase64) {\n // exit base64\n inBase64 = false\n } else if (currentChar === '\\\\' && inQuotes) {\n // escaped char, skip next character\n index += 1\n } else if (currentChar === '\"') {\n // quote boundary\n inQuotes = !inQuotes\n } else if (!inQuotes && !inBase64 && line.startsWith(token, index)) {\n // can test for match\n return index\n }\n index += 1\n }\n return undefined\n}\n\nconst lastTokenBase64 = (line: string, index: number): boolean => {\n try {\n const tokens = line.slice(0, index).split(/\\s+/)\n const last = tokens[tokens.length - 1]\n return ['base64', 'b64'].includes(last)\n } catch {\n return false\n }\n}\n\nfunction replaceTemplateVariable(program: string, token: string, replacement: string): string {\n const result: string[] = []\n const tokenIndexOffset = replacement.length - token.length\n\n const programLines = program.split('\\n')\n\n for (const line of programLines) {\n const _commentIndex = findUnquotedString(line, '//')\n const commentIndex = _commentIndex === undefined ? line.length : _commentIndex\n let code = line.substring(0, commentIndex)\n const comment = line.substring(commentIndex)\n let trailingIndex = 0\n\n while (true) {\n const tokenIndex = findTemplateToken(code, token, trailingIndex)\n if (tokenIndex === undefined) {\n break\n }\n trailingIndex = tokenIndex + token.length\n const prefix = code.substring(0, tokenIndex)\n const suffix = code.substring(trailingIndex)\n code = `${prefix}${replacement}${suffix}`\n trailingIndex += tokenIndexOffset\n }\n result.push(code + comment)\n }\n\n return result.join('\\n')\n}\n\nconst findTemplateToken = (line: string, token: string, startIndex: number = 0, _endIndex?: number): number | undefined => {\n const endIndex = _endIndex === undefined ? line.length : _endIndex\n\n let index = startIndex\n while (index < endIndex) {\n const tokenIndex = findUnquotedString(line, token, index, endIndex)\n if (tokenIndex === undefined) {\n break\n }\n const trailingIndex = tokenIndex + token.length\n if (\n (tokenIndex === 0 || !isValidTokenCharacter(line[tokenIndex - 1])) &&\n (trailingIndex >= line.length || !isValidTokenCharacter(line[trailingIndex]))\n ) {\n return tokenIndex\n }\n index = trailingIndex\n }\n return undefined\n}\n\nfunction isValidTokenCharacter(char: string): boolean {\n return char.length === 1 && (/\\w/.test(char) || char === '_')\n}\n"],"mappings":";;;;;;AAoGA,IAAa,aAAb,MAAa,WAAW;CACtB,AAAQ;CACR,AA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K;;AAG1B,MAAM,qBAAqB,MAAc,OAAe,aAAqB,GAAG,cAA2C;CACzH,MAAM,WAAW,cAAc,SAAY,KAAK,SAAS;CAEzD,IAAI,QAAQ;AACZ,QAAO,QAAQ,UAAU;EACvB,MAAM,aAAa,mBAAmB,MAAM,OAAO,OAAO,SAAS;AACnE,MAAI,eAAe,OACjB;EAEF,MAAM,gBAAgB,aAAa,MAAM;AACzC,OACG,eAAe,KAAK,CAAC,sBAAsB,KAAK,aAAa,GAAG,MAChE,iBAAiB,KAAK,UAAU,CAAC,sBAAsB,KAAK,eAAe,EAE5E,QAAO;AAET,UAAQ;;;AAKZ,SAAS,sBAAsB,MAAuB;AACpD,QAAO,KAAK,WAAW,MAAM,KAAK,KAAK,KAAK,IAAI,SAAS"}
1
+ {"version":3,"file":"app-manager.mjs","names":["valueBase64: string","valueRaw: Buffer","result: string[]"],"sources":["../../src/types/app-manager.ts"],"sourcesContent":["import { ABIMethod, ABIReturn, ABIType, ABIValue } from '@algorandfoundation/algokit-abi'\nimport { AlgodClient, EvalDelta, PendingTransactionResponse, TealValue } from '@algorandfoundation/algokit-algod-client'\nimport { Address, ProgramSourceMap, ReadableAddress, getAddress, getApplicationAddress } from '@algorandfoundation/algokit-common'\nimport { AddressWithTransactionSigner, BoxReference as TransactionBoxReference } from '@algorandfoundation/algokit-transact'\nimport {\n ABI_RETURN_PREFIX,\n BoxName,\n DELETABLE_TEMPLATE_NAME,\n UPDATABLE_TEMPLATE_NAME,\n type AppState,\n type CompiledTeal,\n type TealTemplateParams,\n} from './app'\n\n/** Information about an app. */\nexport interface AppInformation {\n /** The ID of the app. */\n appId: bigint\n /** The escrow address that the app operates with. */\n appAddress: Address\n /**\n * Approval program.\n */\n approvalProgram: Uint8Array\n /**\n * Clear state program.\n */\n clearStateProgram: Uint8Array\n /**\n * The address that created this application. This is the address where the\n * parameters and global state for this application can be found.\n */\n creator: Address\n /**\n * Current global state values.\n */\n globalState: AppState\n /** The number of allocated ints in per-user local state. */\n localInts: number\n /** The number of allocated byte slices in per-user local state. */\n localByteSlices: number\n /** The number of allocated ints in global state. */\n globalInts: number\n /** The number of allocated byte slices in global state. */\n globalByteSlices: number\n /** Any extra pages that are needed for the smart contract. */\n extraProgramPages?: number\n /** The number of updates to the application programs */\n version?: number\n}\n\n/**\n * Something that identifies an app box name - either a:\n * * `Uint8Array` (the actual binary of the box name)\n * * `string` (that will be encoded to a `Uint8Array`)\n * * `AddressWithSigner` (that will be encoded into the\n * public key address of the corresponding account)\n */\nexport type BoxIdentifier = string | Uint8Array | AddressWithTransactionSigner\n\n/**\n * A grouping of the app ID and name identifier to reference an app box.\n */\nexport interface BoxReference {\n /**\n * A unique application id\n */\n appId: bigint\n /**\n * Identifier for a box name\n */\n name: BoxIdentifier\n}\n\n/**\n * Parameters to get and decode a box value as an ABI type.\n */\nexport interface BoxValueRequestParams {\n /** The ID of the app return box names for */\n appId: bigint\n /** The name of the box to return either as a string, binary array or `BoxName` */\n boxName: BoxIdentifier\n /** The ABI type to decode the value using */\n type: ABIType\n}\n\n/**\n * Parameters to get and decode a box value as an ABI type.\n */\nexport interface BoxValuesRequestParams {\n /** The ID of the app return box names for */\n appId: bigint\n /** The names of the boxes to return either as a string, binary array or BoxName` */\n boxNames: BoxIdentifier[]\n /** The ABI type to decode the value using */\n type: ABIType\n}\n\n/** Allows management of application information. */\nexport class AppManager {\n private _algod: AlgodClient\n private _compilationResults: Record<string, CompiledTeal> = {}\n\n /**\n * Creates an `AppManager`\n * @param algod An algod instance\n */\n constructor(algod: AlgodClient) {\n this._algod = algod\n }\n\n /**\n * Compiles the given TEAL using algod and returns the result, including source map.\n *\n * The result of this compilation is also cached keyed by the TEAL\n * code so it can be retrieved via `getCompilationResult`.\n *\n * This function is re-entrant; it will only compile the same code once.\n *\n * @param tealCode The TEAL code\n * @returns The information about the compiled file\n * @example\n * ```typescript\n * const compiled = await appManager.compileTeal(tealProgram)\n * ```\n */\n async compileTeal(tealCode: string): Promise<CompiledTeal> {\n if (this._compilationResults[tealCode]) {\n return this._compilationResults[tealCode]\n }\n\n const compiled = await this._algod.tealCompile(tealCode, { sourcemap: true })\n const result = {\n teal: tealCode,\n compiled: compiled.result,\n compiledHash: compiled.hash,\n compiledBase64ToBytes: new Uint8Array(Buffer.from(compiled.result, 'base64')),\n sourceMap: new ProgramSourceMap(compiled.sourcemap as { version: number; sources: string[]; names: string[]; mappings: string }),\n }\n this._compilationResults[tealCode] = result\n\n return result\n }\n\n /**\n * Performs template substitution of a teal template and compiles it, returning the compiled result.\n *\n * Looks for `TMPL_{parameter}` for template replacements and replaces AlgoKit deploy-time control parameters\n * if deployment metadata is specified.\n *\n * * `TMPL_UPDATABLE` for updatability / immutability control\n * * `TMPL_DELETABLE` for deletability / permanence control\n *\n * @param tealTemplateCode The TEAL logic to compile\n * @param templateParams Any parameters to replace in the .teal file before compiling\n * @param deploymentMetadata The deployment metadata the app will be deployed with\n * @returns The information about the compiled code\n * @example\n * ```typescript\n * const compiled = await appManager.compileTealTemplate(tealTemplate, { TMPL_APP_ID: 12345n }, { updatable: true, deletable: false })\n * ```\n */\n async compileTealTemplate(\n tealTemplateCode: string,\n templateParams?: TealTemplateParams,\n deploymentMetadata?: { updatable?: boolean; deletable?: boolean },\n ): Promise<CompiledTeal> {\n let tealCode = AppManager.stripTealComments(tealTemplateCode)\n\n tealCode = AppManager.replaceTealTemplateParams(tealCode, templateParams)\n\n if (deploymentMetadata) {\n tealCode = AppManager.replaceTealTemplateDeployTimeControlParams(tealCode, deploymentMetadata)\n }\n\n return await this.compileTeal(tealCode)\n }\n\n /**\n * Returns a previous compilation result.\n * @param tealCode The TEAL code\n * @returns The information about the previously compiled file\n * or `undefined` if that TEAL code wasn't previously compiled\n * @example\n * ```typescript\n * const compiled = appManager.getCompilationResult(tealProgram)\n * ```\n */\n getCompilationResult(tealCode: string): CompiledTeal | undefined {\n return this._compilationResults[tealCode]\n }\n\n /**\n * Returns the current app information for the app with the given ID.\n *\n * @example\n * ```typescript\n * const appInfo = await appManager.getById(12353n);\n * ```\n *\n * @param appId The ID of the app\n * @returns The app information\n */\n public async getById(appId: bigint): Promise<AppInformation> {\n const app = await this._algod.applicationById(appId)\n const convertedGlobalState = (app.params.globalState ?? []).map((kv) => ({ key: kv.key, value: kv.value }))\n\n return {\n appId: BigInt(app.id),\n appAddress: getApplicationAddress(app.id),\n approvalProgram: app.params.approvalProgram,\n clearStateProgram: app.params.clearStateProgram,\n creator: app.params.creator,\n localInts: app.params.localStateSchema?.numUints ?? 0,\n localByteSlices: app.params.localStateSchema?.numByteSlices ?? 0,\n globalInts: app.params.globalStateSchema?.numUints ?? 0,\n globalByteSlices: app.params.globalStateSchema?.numByteSlices ?? 0,\n extraProgramPages: app.params.extraProgramPages ?? 0,\n globalState: AppManager.decodeAppState(convertedGlobalState),\n version: app.params.version,\n }\n }\n\n /**\n * Returns the current global state values for the given app ID and account address\n *\n * @param appId The ID of the app to return global state for\n * @returns The current global state for the given app\n * @example\n * ```typescript\n * const globalState = await appManager.getGlobalState(12353n);\n * ```\n */\n public async getGlobalState(appId: bigint) {\n return (await this.getById(appId)).globalState\n }\n\n /**\n * Returns the current local state values for the given app ID and account address\n *\n * @param appId The ID of the app to return local state for\n * @param address The string address of the account to get local state for the given app\n * @returns The current local state for the given (app, account) combination\n * @example\n * ```typescript\n * const localState = await appManager.getLocalState(12353n, 'ACCOUNTADDRESS');\n * ```\n */\n public async getLocalState(appId: bigint, address: ReadableAddress) {\n const appInfo = await this._algod.accountApplicationInformation(getAddress(address).toString(), Number(appId))\n\n if (!appInfo.appLocalState) {\n throw new Error(\"Couldn't find local state\")\n }\n\n // If keyValue is undefined or empty, return empty state\n if (!appInfo.appLocalState.keyValue || appInfo.appLocalState.keyValue.length === 0) {\n return {}\n }\n\n const convertedState = appInfo.appLocalState.keyValue.map((kv) => ({ key: kv.key, value: kv.value }))\n\n return AppManager.decodeAppState(convertedState)\n }\n\n /**\n * Returns the names of the current boxes for the given app.\n * @param appId The ID of the app return box names for\n * @returns The current box names\n * @example\n * ```typescript\n * const boxNames = await appManager.getBoxNames(12353n);\n * ```\n */\n public async getBoxNames(appId: bigint): Promise<BoxName[]> {\n const boxResult = await this._algod.applicationBoxes(appId)\n return boxResult.boxes.map((b: { name: Uint8Array }) => {\n return { nameRaw: b.name, nameBase64: Buffer.from(b.name).toString('base64'), name: Buffer.from(b.name).toString('utf-8') }\n })\n }\n\n /**\n * Returns the value of the given box name for the given app.\n * @param appId The ID of the app return box names for\n * @param boxName 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 * @example\n * ```typescript\n * const boxValue = await appManager.getBoxValue(12353n, 'boxName');\n * ```\n */\n public async getBoxValue(appId: bigint, boxName: BoxIdentifier | BoxName): Promise<Uint8Array> {\n const boxId = typeof boxName === 'object' && 'nameRaw' in boxName ? boxName.nameRaw : boxName\n const name = AppManager.getBoxReference(boxId).name\n const boxResult = await this._algod.applicationBoxByName(Number(appId), name)\n return boxResult.value\n }\n\n /**\n * Returns the value of the given box names for the given app.\n * @param appId The ID of the app return box names for\n * @param boxNames The names of the boxes to return either as a string, binary array or `BoxName`\n * @returns The current box values as a byte array in the same order as the passed in box names\n * @example\n * ```typescript\n * const boxValues = await appManager.getBoxValues(12353n, ['boxName1', 'boxName2']);\n * ```\n */\n public async getBoxValues(appId: bigint, boxNames: (BoxIdentifier | BoxName)[]): Promise<Uint8Array[]> {\n return await Promise.all(boxNames.map(async (boxName) => await this.getBoxValue(appId, boxName)))\n }\n\n /**\n * Returns the value of the given box name for the given app decoded based on the given ABI type.\n * @param request The parameters for the box value request\n * @returns The current box value as an ABI value\n * @example\n * ```typescript\n * const boxValue = await appManager.getBoxValueFromABIType({ appId: 12353n, boxName: 'boxName', type: new ABIUintType(32) });\n * ```\n */\n public async getBoxValueFromABIType(request: BoxValueRequestParams): Promise<ABIValue> {\n const { appId, boxName, type } = request\n const value = await this.getBoxValue(appId, boxName)\n return type.decode(value)\n }\n\n /**\n * Returns the value of the given box names for the given app decoded based on the given ABI type.\n * @param request The parameters for the box value request\n * @returns The current box values as an ABI value in the same order as the passed in box names\n * @example\n * ```typescript\n * const boxValues = await appManager.getBoxValuesFromABIType({ appId: 12353n, boxNames: ['boxName1', 'boxName2'], type: new ABIUintType(32) });\n * ```\n */\n public async getBoxValuesFromABIType(request: BoxValuesRequestParams): Promise<ABIValue[]> {\n const { appId, boxNames, type } = request\n return await Promise.all(boxNames.map(async (boxName) => await this.getBoxValueFromABIType({ appId, boxName, type })))\n }\n\n /**\n * Returns a `algosdk.BoxReference` given a `BoxIdentifier` or `BoxReference`.\n * @param boxId The box to return a reference for\n * @returns The box reference ready to pass into a `algosdk.Transaction`\n * @example\n * ```typescript\n * const boxRef = AppManager.getBoxReference('boxName');\n * ```\n */\n public static getBoxReference(boxId: BoxIdentifier | BoxReference): TransactionBoxReference {\n const ref = typeof boxId === 'object' && 'appId' in boxId ? boxId : { appId: 0n, name: boxId }\n return {\n appId: ref.appId,\n name: typeof ref.name === 'string' ? new TextEncoder().encode(ref.name) : 'length' in ref.name ? ref.name : ref.name.addr.publicKey,\n } as TransactionBoxReference\n }\n\n /**\n * Converts an array of global/local state values from the algod api to a more friendly\n * generic object keyed by the UTF-8 value of the key.\n * @param state A `global-state`, `local-state`, `global-state-deltas` or `local-state-deltas`\n * @returns An object keyeed by the UTF-8 representation of the key with various parsings of the values\n * @example\n * ```typescript\n * const stateValues = AppManager.decodeAppState(state);\n * ```\n */\n public static decodeAppState(state: { key: Uint8Array; value: TealValue | EvalDelta }[]): AppState {\n const stateValues = {} as AppState\n\n // Start with empty set\n for (const stateVal of state) {\n const keyBase64 = Buffer.from(stateVal.key).toString('base64')\n const keyRaw = stateVal.key\n const key = Buffer.from(stateVal.key).toString('utf-8')\n const tealValue = stateVal.value\n\n const dataTypeFlag = Number('action' in tealValue ? tealValue.action : tealValue.type)\n let valueBase64: string\n let valueRaw: Buffer\n switch (dataTypeFlag) {\n case 1:\n valueBase64 =\n typeof tealValue.bytes === 'string' ? tealValue.bytes : tealValue.bytes ? Buffer.from(tealValue.bytes).toString('base64') : ''\n valueRaw = Buffer.from(valueBase64, 'base64')\n stateValues[key] = {\n keyRaw,\n keyBase64,\n valueRaw: new Uint8Array(valueRaw),\n valueBase64: valueBase64,\n value: valueRaw.toString('utf-8'),\n }\n break\n case 2: {\n const value = tealValue.uint ?? 0\n stateValues[key] = { keyRaw, keyBase64, value: BigInt(value) }\n break\n }\n default:\n throw new Error(`Received unknown state data type of ${dataTypeFlag}`)\n }\n }\n\n return stateValues\n }\n\n /**\n * Returns any ABI return values for the given app call arguments and transaction confirmation.\n * @param confirmation The transaction confirmation from algod\n * @param method The ABI method\n * @returns The return value for the method call\n * @example\n * ```typescript\n * const returnValue = AppManager.getABIReturn(confirmation, ABIMethod.fromSignature('hello(string)void'));\n * ```\n */\n public static getABIReturn(confirmation: PendingTransactionResponse | undefined, method: ABIMethod | undefined): ABIReturn | undefined {\n if (!method || !confirmation) {\n return undefined\n }\n\n if (method.returns.type === 'void') {\n return { method, rawReturnValue: undefined, returnValue: undefined }\n }\n\n try {\n const logs = confirmation.logs || []\n if (logs.length === 0) {\n throw new Error(`App call transaction did not log a return value`)\n }\n const lastLog = logs[logs.length - 1]\n if (!AppManager.hasAbiReturnPrefix(lastLog)) {\n throw new Error(`App call transaction did not log an ABI return value`)\n }\n\n const rawReturnValue = new Uint8Array(lastLog.slice(4))\n return { method: method, rawReturnValue, decodeError: undefined, returnValue: method.returns.type.decode(rawReturnValue) }\n } catch (err) {\n return { method: method, rawReturnValue: undefined, decodeError: err as Error, returnValue: undefined }\n }\n }\n\n private static hasAbiReturnPrefix(log: Uint8Array): boolean {\n if (log.length < ABI_RETURN_PREFIX.length) {\n return false\n }\n for (let i = 0; i < ABI_RETURN_PREFIX.length; i++) {\n if (log[i] !== ABI_RETURN_PREFIX[i]) {\n return false\n }\n }\n return true\n }\n\n /**\n * Replaces AlgoKit deploy-time deployment control parameters within the given TEAL template code.\n *\n * * `TMPL_UPDATABLE` for updatability / immutability control\n * * `TMPL_DELETABLE` for deletability / permanence control\n *\n * Note: If these values are defined, but the corresponding `TMPL_*` value\n * isn't in the teal code it will throw an exception.\n *\n * @param tealTemplateCode The TEAL template code to substitute\n * @param params The deploy-time deployment control parameter value to replace\n * @returns The replaced TEAL code\n * @example\n * ```typescript\n * const tealCode = AppManager.replaceTealTemplateDeployTimeControlParams(tealTemplate, { updatable: true, deletable: false });\n * ```\n */\n static replaceTealTemplateDeployTimeControlParams(tealTemplateCode: string, params: { updatable?: boolean; deletable?: boolean }) {\n if (params.updatable !== undefined) {\n if (!tealTemplateCode.includes(UPDATABLE_TEMPLATE_NAME)) {\n throw new Error(\n `Deploy-time updatability control requested for app deployment, but ${UPDATABLE_TEMPLATE_NAME} not present in TEAL code`,\n )\n }\n tealTemplateCode = replaceTemplateVariable(tealTemplateCode, UPDATABLE_TEMPLATE_NAME, (params.updatable ? 1 : 0).toString())\n }\n\n if (params.deletable !== undefined) {\n if (!tealTemplateCode.includes(DELETABLE_TEMPLATE_NAME)) {\n throw new Error(\n `Deploy-time deletability control requested for app deployment, but ${DELETABLE_TEMPLATE_NAME} not present in TEAL code`,\n )\n }\n tealTemplateCode = replaceTemplateVariable(tealTemplateCode, DELETABLE_TEMPLATE_NAME, (params.deletable ? 1 : 0).toString())\n }\n\n return tealTemplateCode\n }\n\n /**\n * Performs template substitution of a teal file.\n *\n * Looks for `TMPL_{parameter}` for template replacements.\n *\n * @param tealTemplateCode The TEAL template code to make parameter replacements in\n * @param templateParams Any parameters to replace in the teal code\n * @returns The TEAL code with replacements\n * @example\n * ```typescript\n * const tealCode = AppManager.replaceTealTemplateParams(tealTemplate, { TMPL_APP_ID: 12345n });\n * ```\n */\n static replaceTealTemplateParams(tealTemplateCode: string, templateParams?: TealTemplateParams) {\n if (templateParams !== undefined) {\n for (const key in templateParams) {\n const value = templateParams[key]\n const token = `TMPL_${key.replace(/^TMPL_/, '')}`\n\n // If this is a number, first replace any byte representations of the number\n // These may appear in the TEAL in order to circumvent int compression and preserve PC values\n if (typeof value === 'number' || typeof value === 'bigint') {\n tealTemplateCode = tealTemplateCode.replace(new RegExp(`(?<=bytes )${token}`, 'g'), `0x${value.toString(16).padStart(16, '0')}`)\n\n // We could probably return here since mixing pushint and pushbytes is likely not going to happen, but might as well do both\n }\n\n tealTemplateCode = replaceTemplateVariable(\n tealTemplateCode,\n token,\n typeof value === 'string'\n ? `0x${Buffer.from(value, 'utf-8').toString('hex')}`\n : ArrayBuffer.isView(value)\n ? `0x${Buffer.from(value).toString('hex')}`\n : value.toString(),\n )\n }\n }\n\n return tealTemplateCode\n }\n\n /**\n * Remove comments from TEAL code (useful to reduce code size before compilation).\n *\n * @param tealCode The TEAL logic to strip\n * @returns The TEAL without comments\n * @example\n * ```typescript\n * const stripped = AppManager.stripTealComments(tealProgram);\n * ```\n */\n static stripTealComments(tealCode: string) {\n const stripCommentFromLine = (line: string) => {\n const commentIndex = findUnquotedString(line, '//')\n if (commentIndex === undefined) {\n return line\n }\n return line.slice(0, commentIndex).trimEnd()\n }\n\n return tealCode\n .split('\\n')\n .map((line) => stripCommentFromLine(line))\n .join('\\n')\n }\n}\n\n/**\n * Find the first string within a line of TEAL. Only matches outside of quotes and base64 are returned.\n * Returns undefined if not found\n */\nconst findUnquotedString = (line: string, token: string, startIndex: number = 0, _endIndex?: number): number | undefined => {\n const endIndex = _endIndex === undefined ? line.length : _endIndex\n let index = startIndex\n let inQuotes = false\n let inBase64 = false\n\n while (index < endIndex) {\n const currentChar = line[index]\n if ((currentChar === ' ' || currentChar === '(') && !inQuotes && lastTokenBase64(line, index)) {\n // enter base64\n inBase64 = true\n } else if ((currentChar === ' ' || currentChar === ')') && !inQuotes && inBase64) {\n // exit base64\n inBase64 = false\n } else if (currentChar === '\\\\' && inQuotes) {\n // escaped char, skip next character\n index += 1\n } else if (currentChar === '\"') {\n // quote boundary\n inQuotes = !inQuotes\n } else if (!inQuotes && !inBase64 && line.startsWith(token, index)) {\n // can test for match\n return index\n }\n index += 1\n }\n return undefined\n}\n\nconst lastTokenBase64 = (line: string, index: number): boolean => {\n try {\n const tokens = line.slice(0, index).split(/\\s+/)\n const last = tokens[tokens.length - 1]\n return ['base64', 'b64'].includes(last)\n } catch {\n return false\n }\n}\n\nfunction replaceTemplateVariable(program: string, token: string, replacement: string): string {\n const result: string[] = []\n const tokenIndexOffset = replacement.length - token.length\n\n const programLines = program.split('\\n')\n\n for (const line of programLines) {\n const _commentIndex = findUnquotedString(line, '//')\n const commentIndex = _commentIndex === undefined ? line.length : _commentIndex\n let code = line.substring(0, commentIndex)\n const comment = line.substring(commentIndex)\n let trailingIndex = 0\n\n while (true) {\n const tokenIndex = findTemplateToken(code, token, trailingIndex)\n if (tokenIndex === undefined) {\n break\n }\n trailingIndex = tokenIndex + token.length\n const prefix = code.substring(0, tokenIndex)\n const suffix = code.substring(trailingIndex)\n code = `${prefix}${replacement}${suffix}`\n trailingIndex += tokenIndexOffset\n }\n result.push(code + comment)\n }\n\n return result.join('\\n')\n}\n\nconst findTemplateToken = (line: string, token: string, startIndex: number = 0, _endIndex?: number): number | undefined => {\n const endIndex = _endIndex === undefined ? line.length : _endIndex\n\n let index = startIndex\n while (index < endIndex) {\n const tokenIndex = findUnquotedString(line, token, index, endIndex)\n if (tokenIndex === undefined) {\n break\n }\n const trailingIndex = tokenIndex + token.length\n if (\n (tokenIndex === 0 || !isValidTokenCharacter(line[tokenIndex - 1])) &&\n (trailingIndex >= line.length || !isValidTokenCharacter(line[trailingIndex]))\n ) {\n return tokenIndex\n }\n index = trailingIndex\n }\n return undefined\n}\n\nfunction isValidTokenCharacter(char: string): boolean {\n return char.length === 1 && (/\\w/.test(char) || char === '_')\n}\n"],"mappings":";;;;;;AAmGA,IAAa,aAAb,MAAa,WAAW;CACtB,AAAQ;CACR,AAAQ,sBAAoD,EAAE;;;;;CAM9D,YAAY,OAAoB;AAC9B,OAAK,SAAS;;;;;;;;;;;;;;;;;CAkBhB,MAAM,YAAY,UAAyC;AACzD,MAAI,KAAK,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AO,QAAQ,UAAU;EACvB,MAAM,aAAa,mBAAmB,MAAM,OAAO,OAAO,SAAS;AACnE,MAAI,eAAe,OACjB;EAEF,MAAM,gBAAgB,aAAa,MAAM;AACzC,OACG,eAAe,KAAK,CAAC,sBAAsB,KAAK,aAAa,GAAG,MAChE,iBAAiB,KAAK,UAAU,CAAC,sBAAsB,KAAK,eAAe,EAE5E,QAAO;AAET,UAAQ;;;AAKZ,SAAS,sBAAsB,MAAuB;AACpD,QAAO,KAAK,WAAW,MAAM,KAAK,KAAK,KAAK,IAAI,SAAS"}
package/types/app.d.ts CHANGED
@@ -1,12 +1,12 @@
1
1
  import { Address } from "../packages/common/src/address.js";
2
2
  import { Expand } from "../packages/common/src/expand.js";
3
+ import { ProgramSourceMap } from "../packages/common/src/sourcemap.js";
3
4
  import { ABIValue } from "../packages/abi/src/abi-value.js";
4
5
  import { ABIType } from "../packages/abi/src/abi-type.js";
5
6
  import { ABIMethod, ABIReturn } from "../packages/abi/src/abi-method.js";
6
7
  import { BoxReference, OnApplicationComplete } from "../packages/transact/src/transactions/app-call.js";
7
8
  import { Transaction } from "../packages/transact/src/transactions/transaction.js";
8
9
  import { SuggestedParams } from "../packages/algod_client/src/models/suggested-params.js";
9
- import { ProgramSourceMap } from "../packages/sdk/src/logic/sourcemap.js";
10
10
  import { BoxIdentifier, BoxReference as BoxReference$1 } from "./app-manager.js";
11
11
  import { SendSingleTransactionResult, SendTransactionFrom, SendTransactionParams, SendTransactionResult, SendTransactionResults, TransactionNote, TransactionToSign } from "./transaction.js";
12
12
  import { TransactionWithSigner } from "../transaction/transaction.js";
package/types/app.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"app.js","names":[],"sources":["../../src/types/app.ts"],"sourcesContent":["import { ABIMethod, ABIReturn, ABIType, ABIValue } from '@algorandfoundation/algokit-abi'\nimport { SuggestedParams } from '@algorandfoundation/algokit-algod-client'\nimport { Address, Expand } from '@algorandfoundation/algokit-common'\nimport { OnApplicationComplete, BoxReference as TransactBoxReference, Transaction } from '@algorandfoundation/algokit-transact'\nimport { ProgramSourceMap } from '@algorandfoundation/sdk'\nimport { TransactionWithSigner } from '../transaction'\nimport { BoxIdentifier, BoxReference } from './app-manager'\nimport {\n SendSingleTransactionResult,\n SendTransactionFrom,\n SendTransactionParams,\n SendTransactionResult,\n SendTransactionResults,\n TransactionNote,\n TransactionToSign,\n} from './transaction'\ntype SourceMap = ProgramSourceMap\n\n/** The name of the TEAL template variable for deploy-time immutability control */\nexport const UPDATABLE_TEMPLATE_NAME = 'TMPL_UPDATABLE'\n\n/** The name of the TEAL template variable for deploy-time permanence control */\nexport const DELETABLE_TEMPLATE_NAME = 'TMPL_DELETABLE'\n\n/** The app create/update [ARC-2](https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0002.md) transaction note prefix */\nexport const APP_DEPLOY_NOTE_DAPP = 'ALGOKIT_DEPLOYER'\n\n/** The maximum number of bytes in a single app code page */\nexport const APP_PAGE_MAX_SIZE = 2048\n\n/** First 4 bytes of SHA-512/256 hash of \"return\" for retrieving ABI return values */\nexport const ABI_RETURN_PREFIX = new Uint8Array([21, 31, 124, 117])\n\n/** Information about an Algorand app */\nexport interface AppReference {\n /** The id of the app */\n appId: number | bigint\n /** The Algorand address of the account associated with the app */\n appAddress: string\n}\n\n/** Common app call arguments for ABI and non-ABI (raw) calls */\nexport interface CoreAppCallArgs {\n /** The optional lease for the transaction */\n lease?: string | Uint8Array\n /** Any box references to load */\n boxes?: (TransactBoxReference | BoxReference | BoxIdentifier)[]\n /** The address of any accounts to load in */\n accounts?: (string | Address)[]\n /** IDs of any apps to load into the foreignApps array */\n apps?: number[]\n /** IDs of any assets to load into the foreignAssets array */\n assets?: number[]\n /** Optional account / account address that should be authorised to transact on behalf of the from account the app call is sent from after this transaction.\n *\n * **Note:** Use with extreme caution and review the [official rekey guidance](https://dev.algorand.co/concepts/accounts/rekeying) first.\n */\n rekeyTo?: SendTransactionFrom | string\n}\n\n/**\n * App call args with non-ABI (raw) values (minus some processing like encoding strings as binary)\n */\nexport interface RawAppCallArgs extends CoreAppCallArgs {\n /** Any application arguments to pass through */\n appArgs?: (Uint8Array | string)[]\n /** Property to aid intellisense */\n method?: undefined\n}\n\n/** An argument for an ABI method, either a primitive value, or a transaction with or without signer, or the unawaited async return value of an algokit method that returns a `SendTransactionResult` */\nexport type ABIAppCallArg =\n | ABIValue\n | TransactionWithSigner\n | TransactionToSign\n | Transaction\n | Promise<SendTransactionResult>\n | SendTransactionResult\n | undefined\n\n/**\n * App call args for an ABI call\n */\nexport type ABIAppCallArgs = CoreAppCallArgs & {\n /** The ABI method to call */\n method: ABIMethod\n /** The ABI method args to pass in */\n methodArgs: ABIAppCallArg[]\n}\n\n/** Arguments to pass to an app call either:\n * * The raw app call values to pass through into the transaction (after processing); or\n * * An ABI method definition (method and args)\n **/\nexport type AppCallArgs = RawAppCallArgs | ABIAppCallArgs\n\n/** Parameters representing a call to an app. */\nexport interface AppCallParams extends SendTransactionParams {\n /** The id of the app to call */\n appId: number | bigint\n /** The type of call, everything except create (see `createApp`) and update (see `updateApp`) */\n callType: Exclude<OnApplicationComplete, OnApplicationComplete.UpdateApplication>\n /** The account to make the call from */\n from: SendTransactionFrom\n /** Optional transaction parameters */\n transactionParams?: SuggestedParams\n /** The (optional) transaction note */\n note?: TransactionNote\n /** The arguments passed in to the app call */\n args?: AppCallArgs\n}\n\n/** Parameters representing the storage schema of an app. */\nexport interface AppStorageSchema {\n /** Restricts number of ints in per-user local state */\n localInts: number\n /** Restricts number of byte slices in per-user local state */\n localByteSlices: number\n /** Restricts number of ints in global state */\n globalInts: number\n /** Restricts number of byte slices in global state */\n globalByteSlices: number\n /** Any extra pages that are needed for the smart contract; if left blank then the right number of pages will be calculated based on the teal code size */\n extraPages?: number\n}\n\n/** Information about a compiled teal program */\nexport interface CompiledTeal {\n /** Original TEAL code */\n teal: string\n /** The compiled code */\n compiled: string\n /** The hash returned by the compiler */\n compiledHash: string\n /** The base64 encoded code as a byte array */\n compiledBase64ToBytes: Uint8Array\n /** Source map from the compilation */\n sourceMap: SourceMap\n}\n\nexport interface AppCallTransactionResultOfType<T> extends SendTransactionResults, SendTransactionResult {\n /** If an ABI method was called the processed return value */\n return?: T\n}\n\n/** Result from calling an app */\nexport type AppCallTransactionResult = AppCallTransactionResultOfType<ABIReturn>\n\n/**\n * The payload of the metadata to add to the transaction note when deploying an app, noting it will be prefixed with `APP_DEPLOY_NOTE_PREFIX`.\n */\nexport interface AppDeployMetadata {\n /** The unique name identifier of the app within the creator account */\n name: string\n /** The version of app that is / will be deployed */\n version: string\n /** Whether or not the app is deletable / permanent / unspecified */\n deletable?: boolean\n /** Whether or not the app is updatable / immutable / unspecified */\n updatable?: boolean\n}\n\n/** The metadata that can be collected about a deployed app */\nexport interface AppMetadata extends AppReference, AppDeployMetadata {\n /** The round the app was created */\n createdRound: number\n /** The last round that the app was updated */\n updatedRound: number\n /** The metadata when the app was created */\n createdMetadata: AppDeployMetadata\n /** Whether or not the app is deleted */\n deleted: boolean\n}\n\n/** A lookup of name -> Algorand app for a creator */\nexport interface AppLookup {\n creator: Readonly<string>\n apps: Readonly<{\n [name: string]: AppMetadata\n }>\n}\n\n/** Dictionary of deploy-time parameters to replace in a teal template.\n *\n * Note: Looks for `TMPL_{parameter}` for template replacements i.e. you can leave out the `TMPL_`.\n *\n */\nexport interface TealTemplateParams {\n [key: string]: string | bigint | number | Uint8Array\n}\n\n/** What action to perform when deploying an app and an update is detected in the TEAL code */\nexport enum OnUpdate {\n /** Fail the deployment */\n Fail,\n /** Update the app */\n UpdateApp,\n /** Delete the app and create a new one in its place */\n ReplaceApp,\n /** Create a new app */\n AppendApp,\n}\n\n/** What action to perform when deploying an app and a breaking schema change is detected */\nexport enum OnSchemaBreak {\n /** Fail the deployment */\n Fail,\n /** Delete the app and create a new one in its place */\n ReplaceApp,\n /** Create a new app */\n AppendApp,\n}\n\n/** The result of compiling the approval and clear state TEAL programs for an app */\nexport interface AppCompilationResult {\n /** The result of compiling the approval program */\n compiledApproval: CompiledTeal\n /** The result of compiling the clear state program */\n compiledClear: CompiledTeal\n}\n\nexport type AppReturn<TReturn> = {\n /** The ABI method call return value */\n return?: TReturn\n}\n\n/** Result from sending a single app transaction. */\nexport type SendAppTransactionResult = Expand<\n SendSingleTransactionResult & {\n /** If an ABI method was called the processed return value */\n return?: ABIReturn\n }\n>\n\n/** Result from sending a single app transaction. */\nexport type SendAppUpdateTransactionResult = Expand<SendAppTransactionResult & Partial<AppCompilationResult>>\n\n/** Result from sending a single app transaction. */\nexport type SendAppCreateTransactionResult = Expand<\n SendAppUpdateTransactionResult & {\n /** The id of the created app */\n appId: bigint\n /** The Algorand address of the account associated with the app */\n appAddress: Address\n }\n>\n\n/** Object holding app state values */\nexport interface AppState {\n [key: string]:\n | {\n value: bigint\n keyRaw: Uint8Array\n keyBase64: string\n }\n | {\n value: string\n valueRaw: Uint8Array\n valueBase64: string\n keyRaw: Uint8Array\n keyBase64: string\n }\n}\n\n/**\n * The name of a box storage box */\nexport interface BoxName {\n /** Name in UTF-8 */\n name: string\n /** Name in binary bytes */\n nameRaw: Uint8Array\n /** Name in Base64 */\n nameBase64: string\n}\n\n/**\n * @deprecated Use `types/app-manager/BoxValueRequestParams` instead.\n * Parameters to get and decode a box value as an ABI type.\n */\nexport interface BoxValueRequestParams {\n /** The ID of the app return box names for */\n appId: number | bigint\n /** The name of the box to return either as a string, binary array or `BoxName` */\n boxName: string | Uint8Array | BoxName\n /** The ABI type to decode the value using */\n type: ABIType\n}\n\n/**\n * @deprecated Use `types/app-manager/BoxValuesRequestParams` instead.\n * Parameters to get and decode a box value as an ABI type.\n */\nexport interface BoxValuesRequestParams {\n /** The ID of the app return box names for */\n appId: number\n /** The names of the boxes to return either as a string, binary array or BoxName` */\n boxNames: (string | Uint8Array | BoxName)[]\n /** The ABI type to decode the value using */\n type: ABIType\n}\n"],"mappings":";;;AAmBA,MAAa,0BAA0B;;AAGvC,MAAa,0BAA0B;;AAGvC,MAAa,uBAAuB;;AAGpC,MAAa,oBAAoB;;AAGjC,MAAa,oBAAoB,IAAI,WAAW;CAAC;CAAI;CAAI;CAAK;CAAI,CAAC;;AAiKnE,IAAY,gDAAL;;AAEL;;AAEA;;AAEA;;AAEA;;;;AAIF,IAAY,0DAAL;;AAEL;;AAEA;;AAEA"}
1
+ {"version":3,"file":"app.js","names":[],"sources":["../../src/types/app.ts"],"sourcesContent":["import { ABIMethod, ABIReturn, ABIType, ABIValue } from '@algorandfoundation/algokit-abi'\nimport { SuggestedParams } from '@algorandfoundation/algokit-algod-client'\nimport { Address, Expand, ProgramSourceMap } from '@algorandfoundation/algokit-common'\nimport { OnApplicationComplete, BoxReference as TransactBoxReference, Transaction } from '@algorandfoundation/algokit-transact'\nimport { TransactionWithSigner } from '../transaction'\nimport { BoxIdentifier, BoxReference } from './app-manager'\nimport {\n SendSingleTransactionResult,\n SendTransactionFrom,\n SendTransactionParams,\n SendTransactionResult,\n SendTransactionResults,\n TransactionNote,\n TransactionToSign,\n} from './transaction'\ntype SourceMap = ProgramSourceMap\n\n/** The name of the TEAL template variable for deploy-time immutability control */\nexport const UPDATABLE_TEMPLATE_NAME = 'TMPL_UPDATABLE'\n\n/** The name of the TEAL template variable for deploy-time permanence control */\nexport const DELETABLE_TEMPLATE_NAME = 'TMPL_DELETABLE'\n\n/** The app create/update [ARC-2](https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0002.md) transaction note prefix */\nexport const APP_DEPLOY_NOTE_DAPP = 'ALGOKIT_DEPLOYER'\n\n/** The maximum number of bytes in a single app code page */\nexport const APP_PAGE_MAX_SIZE = 2048\n\n/** First 4 bytes of SHA-512/256 hash of \"return\" for retrieving ABI return values */\nexport const ABI_RETURN_PREFIX = new Uint8Array([21, 31, 124, 117])\n\n/** Information about an Algorand app */\nexport interface AppReference {\n /** The id of the app */\n appId: number | bigint\n /** The Algorand address of the account associated with the app */\n appAddress: string\n}\n\n/** Common app call arguments for ABI and non-ABI (raw) calls */\nexport interface CoreAppCallArgs {\n /** The optional lease for the transaction */\n lease?: string | Uint8Array\n /** Any box references to load */\n boxes?: (TransactBoxReference | BoxReference | BoxIdentifier)[]\n /** The address of any accounts to load in */\n accounts?: (string | Address)[]\n /** IDs of any apps to load into the foreignApps array */\n apps?: number[]\n /** IDs of any assets to load into the foreignAssets array */\n assets?: number[]\n /** Optional account / account address that should be authorised to transact on behalf of the from account the app call is sent from after this transaction.\n *\n * **Note:** Use with extreme caution and review the [official rekey guidance](https://dev.algorand.co/concepts/accounts/rekeying) first.\n */\n rekeyTo?: SendTransactionFrom | string\n}\n\n/**\n * App call args with non-ABI (raw) values (minus some processing like encoding strings as binary)\n */\nexport interface RawAppCallArgs extends CoreAppCallArgs {\n /** Any application arguments to pass through */\n appArgs?: (Uint8Array | string)[]\n /** Property to aid intellisense */\n method?: undefined\n}\n\n/** An argument for an ABI method, either a primitive value, or a transaction with or without signer, or the unawaited async return value of an algokit method that returns a `SendTransactionResult` */\nexport type ABIAppCallArg =\n | ABIValue\n | TransactionWithSigner\n | TransactionToSign\n | Transaction\n | Promise<SendTransactionResult>\n | SendTransactionResult\n | undefined\n\n/**\n * App call args for an ABI call\n */\nexport type ABIAppCallArgs = CoreAppCallArgs & {\n /** The ABI method to call */\n method: ABIMethod\n /** The ABI method args to pass in */\n methodArgs: ABIAppCallArg[]\n}\n\n/** Arguments to pass to an app call either:\n * * The raw app call values to pass through into the transaction (after processing); or\n * * An ABI method definition (method and args)\n **/\nexport type AppCallArgs = RawAppCallArgs | ABIAppCallArgs\n\n/** Parameters representing a call to an app. */\nexport interface AppCallParams extends SendTransactionParams {\n /** The id of the app to call */\n appId: number | bigint\n /** The type of call, everything except create (see `createApp`) and update (see `updateApp`) */\n callType: Exclude<OnApplicationComplete, OnApplicationComplete.UpdateApplication>\n /** The account to make the call from */\n from: SendTransactionFrom\n /** Optional transaction parameters */\n transactionParams?: SuggestedParams\n /** The (optional) transaction note */\n note?: TransactionNote\n /** The arguments passed in to the app call */\n args?: AppCallArgs\n}\n\n/** Parameters representing the storage schema of an app. */\nexport interface AppStorageSchema {\n /** Restricts number of ints in per-user local state */\n localInts: number\n /** Restricts number of byte slices in per-user local state */\n localByteSlices: number\n /** Restricts number of ints in global state */\n globalInts: number\n /** Restricts number of byte slices in global state */\n globalByteSlices: number\n /** Any extra pages that are needed for the smart contract; if left blank then the right number of pages will be calculated based on the teal code size */\n extraPages?: number\n}\n\n/** Information about a compiled teal program */\nexport interface CompiledTeal {\n /** Original TEAL code */\n teal: string\n /** The compiled code */\n compiled: string\n /** The hash returned by the compiler */\n compiledHash: string\n /** The base64 encoded code as a byte array */\n compiledBase64ToBytes: Uint8Array\n /** Source map from the compilation */\n sourceMap: SourceMap\n}\n\nexport interface AppCallTransactionResultOfType<T> extends SendTransactionResults, SendTransactionResult {\n /** If an ABI method was called the processed return value */\n return?: T\n}\n\n/** Result from calling an app */\nexport type AppCallTransactionResult = AppCallTransactionResultOfType<ABIReturn>\n\n/**\n * The payload of the metadata to add to the transaction note when deploying an app, noting it will be prefixed with `APP_DEPLOY_NOTE_PREFIX`.\n */\nexport interface AppDeployMetadata {\n /** The unique name identifier of the app within the creator account */\n name: string\n /** The version of app that is / will be deployed */\n version: string\n /** Whether or not the app is deletable / permanent / unspecified */\n deletable?: boolean\n /** Whether or not the app is updatable / immutable / unspecified */\n updatable?: boolean\n}\n\n/** The metadata that can be collected about a deployed app */\nexport interface AppMetadata extends AppReference, AppDeployMetadata {\n /** The round the app was created */\n createdRound: number\n /** The last round that the app was updated */\n updatedRound: number\n /** The metadata when the app was created */\n createdMetadata: AppDeployMetadata\n /** Whether or not the app is deleted */\n deleted: boolean\n}\n\n/** A lookup of name -> Algorand app for a creator */\nexport interface AppLookup {\n creator: Readonly<string>\n apps: Readonly<{\n [name: string]: AppMetadata\n }>\n}\n\n/** Dictionary of deploy-time parameters to replace in a teal template.\n *\n * Note: Looks for `TMPL_{parameter}` for template replacements i.e. you can leave out the `TMPL_`.\n *\n */\nexport interface TealTemplateParams {\n [key: string]: string | bigint | number | Uint8Array\n}\n\n/** What action to perform when deploying an app and an update is detected in the TEAL code */\nexport enum OnUpdate {\n /** Fail the deployment */\n Fail,\n /** Update the app */\n UpdateApp,\n /** Delete the app and create a new one in its place */\n ReplaceApp,\n /** Create a new app */\n AppendApp,\n}\n\n/** What action to perform when deploying an app and a breaking schema change is detected */\nexport enum OnSchemaBreak {\n /** Fail the deployment */\n Fail,\n /** Delete the app and create a new one in its place */\n ReplaceApp,\n /** Create a new app */\n AppendApp,\n}\n\n/** The result of compiling the approval and clear state TEAL programs for an app */\nexport interface AppCompilationResult {\n /** The result of compiling the approval program */\n compiledApproval: CompiledTeal\n /** The result of compiling the clear state program */\n compiledClear: CompiledTeal\n}\n\nexport type AppReturn<TReturn> = {\n /** The ABI method call return value */\n return?: TReturn\n}\n\n/** Result from sending a single app transaction. */\nexport type SendAppTransactionResult = Expand<\n SendSingleTransactionResult & {\n /** If an ABI method was called the processed return value */\n return?: ABIReturn\n }\n>\n\n/** Result from sending a single app transaction. */\nexport type SendAppUpdateTransactionResult = Expand<SendAppTransactionResult & Partial<AppCompilationResult>>\n\n/** Result from sending a single app transaction. */\nexport type SendAppCreateTransactionResult = Expand<\n SendAppUpdateTransactionResult & {\n /** The id of the created app */\n appId: bigint\n /** The Algorand address of the account associated with the app */\n appAddress: Address\n }\n>\n\n/** Object holding app state values */\nexport interface AppState {\n [key: string]:\n | {\n value: bigint\n keyRaw: Uint8Array\n keyBase64: string\n }\n | {\n value: string\n valueRaw: Uint8Array\n valueBase64: string\n keyRaw: Uint8Array\n keyBase64: string\n }\n}\n\n/**\n * The name of a box storage box */\nexport interface BoxName {\n /** Name in UTF-8 */\n name: string\n /** Name in binary bytes */\n nameRaw: Uint8Array\n /** Name in Base64 */\n nameBase64: string\n}\n\n/**\n * @deprecated Use `types/app-manager/BoxValueRequestParams` instead.\n * Parameters to get and decode a box value as an ABI type.\n */\nexport interface BoxValueRequestParams {\n /** The ID of the app return box names for */\n appId: number | bigint\n /** The name of the box to return either as a string, binary array or `BoxName` */\n boxName: string | Uint8Array | BoxName\n /** The ABI type to decode the value using */\n type: ABIType\n}\n\n/**\n * @deprecated Use `types/app-manager/BoxValuesRequestParams` instead.\n * Parameters to get and decode a box value as an ABI type.\n */\nexport interface BoxValuesRequestParams {\n /** The ID of the app return box names for */\n appId: number\n /** The names of the boxes to return either as a string, binary array or BoxName` */\n boxNames: (string | Uint8Array | BoxName)[]\n /** The ABI type to decode the value using */\n type: ABIType\n}\n"],"mappings":";;;AAkBA,MAAa,0BAA0B;;AAGvC,MAAa,0BAA0B;;AAGvC,MAAa,uBAAuB;;AAGpC,MAAa,oBAAoB;;AAGjC,MAAa,oBAAoB,IAAI,WAAW;CAAC;CAAI;CAAI;CAAK;CAAI,CAAC;;AAiKnE,IAAY,gDAAL;;AAEL;;AAEA;;AAEA;;AAEA;;;;AAIF,IAAY,0DAAL;;AAEL;;AAEA;;AAEA"}
package/types/app.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"app.mjs","names":[],"sources":["../../src/types/app.ts"],"sourcesContent":["import { ABIMethod, ABIReturn, ABIType, ABIValue } from '@algorandfoundation/algokit-abi'\nimport { SuggestedParams } from '@algorandfoundation/algokit-algod-client'\nimport { Address, Expand } from '@algorandfoundation/algokit-common'\nimport { OnApplicationComplete, BoxReference as TransactBoxReference, Transaction } from '@algorandfoundation/algokit-transact'\nimport { ProgramSourceMap } from '@algorandfoundation/sdk'\nimport { TransactionWithSigner } from '../transaction'\nimport { BoxIdentifier, BoxReference } from './app-manager'\nimport {\n SendSingleTransactionResult,\n SendTransactionFrom,\n SendTransactionParams,\n SendTransactionResult,\n SendTransactionResults,\n TransactionNote,\n TransactionToSign,\n} from './transaction'\ntype SourceMap = ProgramSourceMap\n\n/** The name of the TEAL template variable for deploy-time immutability control */\nexport const UPDATABLE_TEMPLATE_NAME = 'TMPL_UPDATABLE'\n\n/** The name of the TEAL template variable for deploy-time permanence control */\nexport const DELETABLE_TEMPLATE_NAME = 'TMPL_DELETABLE'\n\n/** The app create/update [ARC-2](https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0002.md) transaction note prefix */\nexport const APP_DEPLOY_NOTE_DAPP = 'ALGOKIT_DEPLOYER'\n\n/** The maximum number of bytes in a single app code page */\nexport const APP_PAGE_MAX_SIZE = 2048\n\n/** First 4 bytes of SHA-512/256 hash of \"return\" for retrieving ABI return values */\nexport const ABI_RETURN_PREFIX = new Uint8Array([21, 31, 124, 117])\n\n/** Information about an Algorand app */\nexport interface AppReference {\n /** The id of the app */\n appId: number | bigint\n /** The Algorand address of the account associated with the app */\n appAddress: string\n}\n\n/** Common app call arguments for ABI and non-ABI (raw) calls */\nexport interface CoreAppCallArgs {\n /** The optional lease for the transaction */\n lease?: string | Uint8Array\n /** Any box references to load */\n boxes?: (TransactBoxReference | BoxReference | BoxIdentifier)[]\n /** The address of any accounts to load in */\n accounts?: (string | Address)[]\n /** IDs of any apps to load into the foreignApps array */\n apps?: number[]\n /** IDs of any assets to load into the foreignAssets array */\n assets?: number[]\n /** Optional account / account address that should be authorised to transact on behalf of the from account the app call is sent from after this transaction.\n *\n * **Note:** Use with extreme caution and review the [official rekey guidance](https://dev.algorand.co/concepts/accounts/rekeying) first.\n */\n rekeyTo?: SendTransactionFrom | string\n}\n\n/**\n * App call args with non-ABI (raw) values (minus some processing like encoding strings as binary)\n */\nexport interface RawAppCallArgs extends CoreAppCallArgs {\n /** Any application arguments to pass through */\n appArgs?: (Uint8Array | string)[]\n /** Property to aid intellisense */\n method?: undefined\n}\n\n/** An argument for an ABI method, either a primitive value, or a transaction with or without signer, or the unawaited async return value of an algokit method that returns a `SendTransactionResult` */\nexport type ABIAppCallArg =\n | ABIValue\n | TransactionWithSigner\n | TransactionToSign\n | Transaction\n | Promise<SendTransactionResult>\n | SendTransactionResult\n | undefined\n\n/**\n * App call args for an ABI call\n */\nexport type ABIAppCallArgs = CoreAppCallArgs & {\n /** The ABI method to call */\n method: ABIMethod\n /** The ABI method args to pass in */\n methodArgs: ABIAppCallArg[]\n}\n\n/** Arguments to pass to an app call either:\n * * The raw app call values to pass through into the transaction (after processing); or\n * * An ABI method definition (method and args)\n **/\nexport type AppCallArgs = RawAppCallArgs | ABIAppCallArgs\n\n/** Parameters representing a call to an app. */\nexport interface AppCallParams extends SendTransactionParams {\n /** The id of the app to call */\n appId: number | bigint\n /** The type of call, everything except create (see `createApp`) and update (see `updateApp`) */\n callType: Exclude<OnApplicationComplete, OnApplicationComplete.UpdateApplication>\n /** The account to make the call from */\n from: SendTransactionFrom\n /** Optional transaction parameters */\n transactionParams?: SuggestedParams\n /** The (optional) transaction note */\n note?: TransactionNote\n /** The arguments passed in to the app call */\n args?: AppCallArgs\n}\n\n/** Parameters representing the storage schema of an app. */\nexport interface AppStorageSchema {\n /** Restricts number of ints in per-user local state */\n localInts: number\n /** Restricts number of byte slices in per-user local state */\n localByteSlices: number\n /** Restricts number of ints in global state */\n globalInts: number\n /** Restricts number of byte slices in global state */\n globalByteSlices: number\n /** Any extra pages that are needed for the smart contract; if left blank then the right number of pages will be calculated based on the teal code size */\n extraPages?: number\n}\n\n/** Information about a compiled teal program */\nexport interface CompiledTeal {\n /** Original TEAL code */\n teal: string\n /** The compiled code */\n compiled: string\n /** The hash returned by the compiler */\n compiledHash: string\n /** The base64 encoded code as a byte array */\n compiledBase64ToBytes: Uint8Array\n /** Source map from the compilation */\n sourceMap: SourceMap\n}\n\nexport interface AppCallTransactionResultOfType<T> extends SendTransactionResults, SendTransactionResult {\n /** If an ABI method was called the processed return value */\n return?: T\n}\n\n/** Result from calling an app */\nexport type AppCallTransactionResult = AppCallTransactionResultOfType<ABIReturn>\n\n/**\n * The payload of the metadata to add to the transaction note when deploying an app, noting it will be prefixed with `APP_DEPLOY_NOTE_PREFIX`.\n */\nexport interface AppDeployMetadata {\n /** The unique name identifier of the app within the creator account */\n name: string\n /** The version of app that is / will be deployed */\n version: string\n /** Whether or not the app is deletable / permanent / unspecified */\n deletable?: boolean\n /** Whether or not the app is updatable / immutable / unspecified */\n updatable?: boolean\n}\n\n/** The metadata that can be collected about a deployed app */\nexport interface AppMetadata extends AppReference, AppDeployMetadata {\n /** The round the app was created */\n createdRound: number\n /** The last round that the app was updated */\n updatedRound: number\n /** The metadata when the app was created */\n createdMetadata: AppDeployMetadata\n /** Whether or not the app is deleted */\n deleted: boolean\n}\n\n/** A lookup of name -> Algorand app for a creator */\nexport interface AppLookup {\n creator: Readonly<string>\n apps: Readonly<{\n [name: string]: AppMetadata\n }>\n}\n\n/** Dictionary of deploy-time parameters to replace in a teal template.\n *\n * Note: Looks for `TMPL_{parameter}` for template replacements i.e. you can leave out the `TMPL_`.\n *\n */\nexport interface TealTemplateParams {\n [key: string]: string | bigint | number | Uint8Array\n}\n\n/** What action to perform when deploying an app and an update is detected in the TEAL code */\nexport enum OnUpdate {\n /** Fail the deployment */\n Fail,\n /** Update the app */\n UpdateApp,\n /** Delete the app and create a new one in its place */\n ReplaceApp,\n /** Create a new app */\n AppendApp,\n}\n\n/** What action to perform when deploying an app and a breaking schema change is detected */\nexport enum OnSchemaBreak {\n /** Fail the deployment */\n Fail,\n /** Delete the app and create a new one in its place */\n ReplaceApp,\n /** Create a new app */\n AppendApp,\n}\n\n/** The result of compiling the approval and clear state TEAL programs for an app */\nexport interface AppCompilationResult {\n /** The result of compiling the approval program */\n compiledApproval: CompiledTeal\n /** The result of compiling the clear state program */\n compiledClear: CompiledTeal\n}\n\nexport type AppReturn<TReturn> = {\n /** The ABI method call return value */\n return?: TReturn\n}\n\n/** Result from sending a single app transaction. */\nexport type SendAppTransactionResult = Expand<\n SendSingleTransactionResult & {\n /** If an ABI method was called the processed return value */\n return?: ABIReturn\n }\n>\n\n/** Result from sending a single app transaction. */\nexport type SendAppUpdateTransactionResult = Expand<SendAppTransactionResult & Partial<AppCompilationResult>>\n\n/** Result from sending a single app transaction. */\nexport type SendAppCreateTransactionResult = Expand<\n SendAppUpdateTransactionResult & {\n /** The id of the created app */\n appId: bigint\n /** The Algorand address of the account associated with the app */\n appAddress: Address\n }\n>\n\n/** Object holding app state values */\nexport interface AppState {\n [key: string]:\n | {\n value: bigint\n keyRaw: Uint8Array\n keyBase64: string\n }\n | {\n value: string\n valueRaw: Uint8Array\n valueBase64: string\n keyRaw: Uint8Array\n keyBase64: string\n }\n}\n\n/**\n * The name of a box storage box */\nexport interface BoxName {\n /** Name in UTF-8 */\n name: string\n /** Name in binary bytes */\n nameRaw: Uint8Array\n /** Name in Base64 */\n nameBase64: string\n}\n\n/**\n * @deprecated Use `types/app-manager/BoxValueRequestParams` instead.\n * Parameters to get and decode a box value as an ABI type.\n */\nexport interface BoxValueRequestParams {\n /** The ID of the app return box names for */\n appId: number | bigint\n /** The name of the box to return either as a string, binary array or `BoxName` */\n boxName: string | Uint8Array | BoxName\n /** The ABI type to decode the value using */\n type: ABIType\n}\n\n/**\n * @deprecated Use `types/app-manager/BoxValuesRequestParams` instead.\n * Parameters to get and decode a box value as an ABI type.\n */\nexport interface BoxValuesRequestParams {\n /** The ID of the app return box names for */\n appId: number\n /** The names of the boxes to return either as a string, binary array or BoxName` */\n boxNames: (string | Uint8Array | BoxName)[]\n /** The ABI type to decode the value using */\n type: ABIType\n}\n"],"mappings":";;AAmBA,MAAa,0BAA0B;;AAGvC,MAAa,0BAA0B;;AAGvC,MAAa,uBAAuB;;AAGpC,MAAa,oBAAoB;;AAGjC,MAAa,oBAAoB,IAAI,WAAW;CAAC;CAAI;CAAI;CAAK;CAAI,CAAC;;AAiKnE,IAAY,gDAAL;;AAEL;;AAEA;;AAEA;;AAEA;;;;AAIF,IAAY,0DAAL;;AAEL;;AAEA;;AAEA"}
1
+ {"version":3,"file":"app.mjs","names":[],"sources":["../../src/types/app.ts"],"sourcesContent":["import { ABIMethod, ABIReturn, ABIType, ABIValue } from '@algorandfoundation/algokit-abi'\nimport { SuggestedParams } from '@algorandfoundation/algokit-algod-client'\nimport { Address, Expand, ProgramSourceMap } from '@algorandfoundation/algokit-common'\nimport { OnApplicationComplete, BoxReference as TransactBoxReference, Transaction } from '@algorandfoundation/algokit-transact'\nimport { TransactionWithSigner } from '../transaction'\nimport { BoxIdentifier, BoxReference } from './app-manager'\nimport {\n SendSingleTransactionResult,\n SendTransactionFrom,\n SendTransactionParams,\n SendTransactionResult,\n SendTransactionResults,\n TransactionNote,\n TransactionToSign,\n} from './transaction'\ntype SourceMap = ProgramSourceMap\n\n/** The name of the TEAL template variable for deploy-time immutability control */\nexport const UPDATABLE_TEMPLATE_NAME = 'TMPL_UPDATABLE'\n\n/** The name of the TEAL template variable for deploy-time permanence control */\nexport const DELETABLE_TEMPLATE_NAME = 'TMPL_DELETABLE'\n\n/** The app create/update [ARC-2](https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0002.md) transaction note prefix */\nexport const APP_DEPLOY_NOTE_DAPP = 'ALGOKIT_DEPLOYER'\n\n/** The maximum number of bytes in a single app code page */\nexport const APP_PAGE_MAX_SIZE = 2048\n\n/** First 4 bytes of SHA-512/256 hash of \"return\" for retrieving ABI return values */\nexport const ABI_RETURN_PREFIX = new Uint8Array([21, 31, 124, 117])\n\n/** Information about an Algorand app */\nexport interface AppReference {\n /** The id of the app */\n appId: number | bigint\n /** The Algorand address of the account associated with the app */\n appAddress: string\n}\n\n/** Common app call arguments for ABI and non-ABI (raw) calls */\nexport interface CoreAppCallArgs {\n /** The optional lease for the transaction */\n lease?: string | Uint8Array\n /** Any box references to load */\n boxes?: (TransactBoxReference | BoxReference | BoxIdentifier)[]\n /** The address of any accounts to load in */\n accounts?: (string | Address)[]\n /** IDs of any apps to load into the foreignApps array */\n apps?: number[]\n /** IDs of any assets to load into the foreignAssets array */\n assets?: number[]\n /** Optional account / account address that should be authorised to transact on behalf of the from account the app call is sent from after this transaction.\n *\n * **Note:** Use with extreme caution and review the [official rekey guidance](https://dev.algorand.co/concepts/accounts/rekeying) first.\n */\n rekeyTo?: SendTransactionFrom | string\n}\n\n/**\n * App call args with non-ABI (raw) values (minus some processing like encoding strings as binary)\n */\nexport interface RawAppCallArgs extends CoreAppCallArgs {\n /** Any application arguments to pass through */\n appArgs?: (Uint8Array | string)[]\n /** Property to aid intellisense */\n method?: undefined\n}\n\n/** An argument for an ABI method, either a primitive value, or a transaction with or without signer, or the unawaited async return value of an algokit method that returns a `SendTransactionResult` */\nexport type ABIAppCallArg =\n | ABIValue\n | TransactionWithSigner\n | TransactionToSign\n | Transaction\n | Promise<SendTransactionResult>\n | SendTransactionResult\n | undefined\n\n/**\n * App call args for an ABI call\n */\nexport type ABIAppCallArgs = CoreAppCallArgs & {\n /** The ABI method to call */\n method: ABIMethod\n /** The ABI method args to pass in */\n methodArgs: ABIAppCallArg[]\n}\n\n/** Arguments to pass to an app call either:\n * * The raw app call values to pass through into the transaction (after processing); or\n * * An ABI method definition (method and args)\n **/\nexport type AppCallArgs = RawAppCallArgs | ABIAppCallArgs\n\n/** Parameters representing a call to an app. */\nexport interface AppCallParams extends SendTransactionParams {\n /** The id of the app to call */\n appId: number | bigint\n /** The type of call, everything except create (see `createApp`) and update (see `updateApp`) */\n callType: Exclude<OnApplicationComplete, OnApplicationComplete.UpdateApplication>\n /** The account to make the call from */\n from: SendTransactionFrom\n /** Optional transaction parameters */\n transactionParams?: SuggestedParams\n /** The (optional) transaction note */\n note?: TransactionNote\n /** The arguments passed in to the app call */\n args?: AppCallArgs\n}\n\n/** Parameters representing the storage schema of an app. */\nexport interface AppStorageSchema {\n /** Restricts number of ints in per-user local state */\n localInts: number\n /** Restricts number of byte slices in per-user local state */\n localByteSlices: number\n /** Restricts number of ints in global state */\n globalInts: number\n /** Restricts number of byte slices in global state */\n globalByteSlices: number\n /** Any extra pages that are needed for the smart contract; if left blank then the right number of pages will be calculated based on the teal code size */\n extraPages?: number\n}\n\n/** Information about a compiled teal program */\nexport interface CompiledTeal {\n /** Original TEAL code */\n teal: string\n /** The compiled code */\n compiled: string\n /** The hash returned by the compiler */\n compiledHash: string\n /** The base64 encoded code as a byte array */\n compiledBase64ToBytes: Uint8Array\n /** Source map from the compilation */\n sourceMap: SourceMap\n}\n\nexport interface AppCallTransactionResultOfType<T> extends SendTransactionResults, SendTransactionResult {\n /** If an ABI method was called the processed return value */\n return?: T\n}\n\n/** Result from calling an app */\nexport type AppCallTransactionResult = AppCallTransactionResultOfType<ABIReturn>\n\n/**\n * The payload of the metadata to add to the transaction note when deploying an app, noting it will be prefixed with `APP_DEPLOY_NOTE_PREFIX`.\n */\nexport interface AppDeployMetadata {\n /** The unique name identifier of the app within the creator account */\n name: string\n /** The version of app that is / will be deployed */\n version: string\n /** Whether or not the app is deletable / permanent / unspecified */\n deletable?: boolean\n /** Whether or not the app is updatable / immutable / unspecified */\n updatable?: boolean\n}\n\n/** The metadata that can be collected about a deployed app */\nexport interface AppMetadata extends AppReference, AppDeployMetadata {\n /** The round the app was created */\n createdRound: number\n /** The last round that the app was updated */\n updatedRound: number\n /** The metadata when the app was created */\n createdMetadata: AppDeployMetadata\n /** Whether or not the app is deleted */\n deleted: boolean\n}\n\n/** A lookup of name -> Algorand app for a creator */\nexport interface AppLookup {\n creator: Readonly<string>\n apps: Readonly<{\n [name: string]: AppMetadata\n }>\n}\n\n/** Dictionary of deploy-time parameters to replace in a teal template.\n *\n * Note: Looks for `TMPL_{parameter}` for template replacements i.e. you can leave out the `TMPL_`.\n *\n */\nexport interface TealTemplateParams {\n [key: string]: string | bigint | number | Uint8Array\n}\n\n/** What action to perform when deploying an app and an update is detected in the TEAL code */\nexport enum OnUpdate {\n /** Fail the deployment */\n Fail,\n /** Update the app */\n UpdateApp,\n /** Delete the app and create a new one in its place */\n ReplaceApp,\n /** Create a new app */\n AppendApp,\n}\n\n/** What action to perform when deploying an app and a breaking schema change is detected */\nexport enum OnSchemaBreak {\n /** Fail the deployment */\n Fail,\n /** Delete the app and create a new one in its place */\n ReplaceApp,\n /** Create a new app */\n AppendApp,\n}\n\n/** The result of compiling the approval and clear state TEAL programs for an app */\nexport interface AppCompilationResult {\n /** The result of compiling the approval program */\n compiledApproval: CompiledTeal\n /** The result of compiling the clear state program */\n compiledClear: CompiledTeal\n}\n\nexport type AppReturn<TReturn> = {\n /** The ABI method call return value */\n return?: TReturn\n}\n\n/** Result from sending a single app transaction. */\nexport type SendAppTransactionResult = Expand<\n SendSingleTransactionResult & {\n /** If an ABI method was called the processed return value */\n return?: ABIReturn\n }\n>\n\n/** Result from sending a single app transaction. */\nexport type SendAppUpdateTransactionResult = Expand<SendAppTransactionResult & Partial<AppCompilationResult>>\n\n/** Result from sending a single app transaction. */\nexport type SendAppCreateTransactionResult = Expand<\n SendAppUpdateTransactionResult & {\n /** The id of the created app */\n appId: bigint\n /** The Algorand address of the account associated with the app */\n appAddress: Address\n }\n>\n\n/** Object holding app state values */\nexport interface AppState {\n [key: string]:\n | {\n value: bigint\n keyRaw: Uint8Array\n keyBase64: string\n }\n | {\n value: string\n valueRaw: Uint8Array\n valueBase64: string\n keyRaw: Uint8Array\n keyBase64: string\n }\n}\n\n/**\n * The name of a box storage box */\nexport interface BoxName {\n /** Name in UTF-8 */\n name: string\n /** Name in binary bytes */\n nameRaw: Uint8Array\n /** Name in Base64 */\n nameBase64: string\n}\n\n/**\n * @deprecated Use `types/app-manager/BoxValueRequestParams` instead.\n * Parameters to get and decode a box value as an ABI type.\n */\nexport interface BoxValueRequestParams {\n /** The ID of the app return box names for */\n appId: number | bigint\n /** The name of the box to return either as a string, binary array or `BoxName` */\n boxName: string | Uint8Array | BoxName\n /** The ABI type to decode the value using */\n type: ABIType\n}\n\n/**\n * @deprecated Use `types/app-manager/BoxValuesRequestParams` instead.\n * Parameters to get and decode a box value as an ABI type.\n */\nexport interface BoxValuesRequestParams {\n /** The ID of the app return box names for */\n appId: number\n /** The names of the boxes to return either as a string, binary array or BoxName` */\n boxNames: (string | Uint8Array | BoxName)[]\n /** The ABI type to decode the value using */\n type: ABIType\n}\n"],"mappings":";;AAkBA,MAAa,0BAA0B;;AAGvC,MAAa,0BAA0B;;AAGvC,MAAa,uBAAuB;;AAGpC,MAAa,oBAAoB;;AAGjC,MAAa,oBAAoB,IAAI,WAAW;CAAC;CAAI;CAAI;CAAK;CAAI,CAAC;;AAiKnE,IAAY,gDAAL;;AAEL;;AAEA;;AAEA;;AAEA;;;;AAIF,IAAY,0DAAL;;AAEL;;AAEA;;AAEA"}
package/types/composer.js CHANGED
@@ -1,14 +1,14 @@
1
1
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.js');
2
2
  const require_constants = require('../packages/common/src/constants.js');
3
+ const require_amount = require('./amount.js');
4
+ const require_config = require('../config.js');
5
+ const require_util = require('../util.js');
6
+ const require_transaction = require('../transaction/transaction.js');
3
7
  const require_app_call = require('../packages/transact/src/transactions/app-call.js');
4
8
  const require_transaction_type = require('../packages/transact/src/transactions/transaction-type.js');
5
- const require_transaction = require('../packages/transact/src/transactions/transaction.js');
9
+ const require_transaction$1 = require('../packages/transact/src/transactions/transaction.js');
6
10
  const require_signed_transaction = require('../packages/transact/src/transactions/signed-transaction.js');
7
11
  const require_signer = require('../packages/transact/src/signer.js');
8
- const require_amount = require('./amount.js');
9
- const require_config = require('../config.js');
10
- const require_util = require('../util.js');
11
- const require_transaction$1 = require('../transaction/transaction.js');
12
12
  const require_app_manager = require('./app-manager.js');
13
13
  const require_app_call$1 = require('../transactions/app-call.js');
14
14
  const require_asset_transfer = require('../transactions/asset-transfer.js');
@@ -129,7 +129,7 @@ var TransactionComposer = class TransactionComposer {
129
129
  };
130
130
  case "txn": {
131
131
  const { txn: transaction, signer, maxFee } = txn.data;
132
- const clonedTxn = require_transaction.decodeTransaction(require_transaction.encodeTransactionRaw(transaction));
132
+ const clonedTxn = require_transaction$1.decodeTransaction(require_transaction$1.encodeTransactionRaw(transaction));
133
133
  delete clonedTxn.group;
134
134
  return {
135
135
  type: "txn",
@@ -146,7 +146,7 @@ var TransactionComposer = class TransactionComposer {
146
146
  type: "asyncTxn",
147
147
  data: {
148
148
  txn: txnPromise.then((resolvedTxn) => {
149
- const clonedTxn = require_transaction.decodeTransaction(require_transaction.encodeTransactionRaw(resolvedTxn));
149
+ const clonedTxn = require_transaction$1.decodeTransaction(require_transaction$1.encodeTransactionRaw(resolvedTxn));
150
150
  delete clonedTxn.group;
151
151
  return clonedTxn;
152
152
  }),
@@ -206,7 +206,7 @@ var TransactionComposer = class TransactionComposer {
206
206
  */
207
207
  addTransaction(transaction, signer) {
208
208
  if (transaction.group) throw new Error("Cannot add a transaction to the composer because it is already in a group");
209
- require_transaction.validateTransaction(transaction);
209
+ require_transaction$1.validateTransaction(transaction);
210
210
  this.push({
211
211
  data: {
212
212
  txn: transaction,
@@ -1086,7 +1086,7 @@ var TransactionComposer = class TransactionComposer {
1086
1086
  if (!this.transactionsWithSigners) {
1087
1087
  const suggestedParams = await this.getSuggestedParams();
1088
1088
  const builtTransactions = await this._buildTransactions(suggestedParams);
1089
- this.rawBuildTransactions = builtTransactions.transactions.map((txn) => new require_transaction.Transaction({ ...txn }));
1089
+ this.rawBuildTransactions = builtTransactions.transactions.map((txn) => new require_transaction$1.Transaction({ ...txn }));
1090
1090
  const groupAnalysis = (this.composerConfig.coverAppCallInnerTransactionFees || this.composerConfig.populateAppCallResources) && builtTransactions.transactions.some((txn) => txn.type === require_transaction_type.TransactionType.AppCall) ? await this.analyzeGroupRequirements(builtTransactions.transactions, suggestedParams, this.composerConfig) : void 0;
1091
1091
  this.populateTransactionAndGroupResources(builtTransactions.transactions, groupAnalysis);
1092
1092
  this.transactionsWithSigners = builtTransactions.transactions.map((txn, index) => {
@@ -1111,13 +1111,13 @@ var TransactionComposer = class TransactionComposer {
1111
1111
  const transactions = new Array();
1112
1112
  let transactionIndex = 0;
1113
1113
  for (const ctxn of this.txns) if (ctxn.type === "txn") {
1114
- require_transaction.validateTransaction(ctxn.data.txn);
1114
+ require_transaction$1.validateTransaction(ctxn.data.txn);
1115
1115
  transactions.push(ctxn.data.txn);
1116
1116
  if (ctxn.data.signer) signers.set(transactionIndex, ctxn.data.signer);
1117
1117
  transactionIndex++;
1118
1118
  } else if (ctxn.type === "asyncTxn") {
1119
1119
  const transaction = await ctxn.data.txn;
1120
- require_transaction.validateTransaction(transaction);
1120
+ require_transaction$1.validateTransaction(transaction);
1121
1121
  transactions.push(transaction);
1122
1122
  if (ctxn.data.signer) signers.set(transactionIndex, ctxn.data.signer);
1123
1123
  transactionIndex++;
@@ -1163,13 +1163,13 @@ var TransactionComposer = class TransactionComposer {
1163
1163
  break;
1164
1164
  default: throw new Error(`Unsupported transaction type: ${ctxn.type}`);
1165
1165
  }
1166
- if (transaction.fee === void 0) transaction = require_transaction.assignFee(transaction, {
1166
+ if (transaction.fee === void 0) transaction = require_transaction$1.assignFee(transaction, {
1167
1167
  feePerByte: suggestedParams.fee,
1168
1168
  minFee: suggestedParams.minFee,
1169
1169
  extraFee: ctxn.data.extraFee?.microAlgos,
1170
1170
  maxFee: ctxn.data.maxFee?.microAlgos
1171
1171
  });
1172
- require_transaction.validateTransaction(transaction);
1172
+ require_transaction$1.validateTransaction(transaction);
1173
1173
  transactions.push(transaction);
1174
1174
  if (ctxn.data.signer) {
1175
1175
  const signer = "signer" in ctxn.data.signer ? ctxn.data.signer.signer : ctxn.data.signer;
@@ -1259,7 +1259,7 @@ var TransactionComposer = class TransactionComposer {
1259
1259
  if (groupAnalysis.unnamedResourcesAccessed) require_app_call$1.populateGroupResources(transactions, groupAnalysis.unnamedResourcesAccessed);
1260
1260
  }
1261
1261
  if (transactions.length > 1) {
1262
- const groupedTransactions = require_transaction.groupTransactions(transactions);
1262
+ const groupedTransactions = require_transaction$1.groupTransactions(transactions);
1263
1263
  transactions.forEach((t) => t.group = groupedTransactions[0].group);
1264
1264
  return transactions;
1265
1265
  } else return transactions;
@@ -1275,9 +1275,9 @@ var TransactionComposer = class TransactionComposer {
1275
1275
  if (logicalMaxFee !== void 0) params.fee = logicalMaxFee;
1276
1276
  else appCallIndexesWithoutMaxFees.push(groupIndex);
1277
1277
  }
1278
- return new require_transaction.Transaction(params);
1278
+ return new require_transaction$1.Transaction(params);
1279
1279
  });
1280
- if (transactionsToSimulate.length > 1) transactionsToSimulate = require_transaction.groupTransactions(transactionsToSimulate);
1280
+ if (transactionsToSimulate.length > 1) transactionsToSimulate = require_transaction$1.groupTransactions(transactionsToSimulate);
1281
1281
  if (analysisParams.coverAppCallInnerTransactionFees && appCallIndexesWithoutMaxFees.length > 0) throw new Error(`Please provide a maxFee for each app call transaction when coverAppCallInnerTransactionFees is enabled. Required for transaction ${appCallIndexesWithoutMaxFees.join(", ")}`);
1282
1282
  const simulateRequest = {
1283
1283
  txnGroups: [{ txns: transactionsToSimulate.map((txn) => ({
@@ -1304,7 +1304,7 @@ var TransactionComposer = class TransactionComposer {
1304
1304
  const btxn = transactions[groupIndex];
1305
1305
  let requiredFeeDelta;
1306
1306
  if (analysisParams.coverAppCallInnerTransactionFees) {
1307
- const minTxnFee = require_transaction.calculateFee(btxn, {
1307
+ const minTxnFee = require_transaction$1.calculateFee(btxn, {
1308
1308
  feePerByte: suggestedParams.fee,
1309
1309
  minFee: suggestedParams.minFee
1310
1310
  });
@@ -1409,7 +1409,7 @@ var TransactionComposer = class TransactionComposer {
1409
1409
  if (transactionsToSend.length > 1 && group) require_config.Config.getLogger(params?.suppressLog).verbose(`Group transaction (${buffer.Buffer.from(group).toString("base64")}) sent with ${transactionsToSend.length} transactions`);
1410
1410
  else require_config.Config.getLogger(params?.suppressLog).verbose(`Sent transaction ID ${transactionsToSend[0].txId()} ${transactionsToSend[0].type} from ${transactionsToSend[0].sender}`);
1411
1411
  let confirmations = new Array();
1412
- if (params?.maxRoundsToWaitForConfirmation !== 0) confirmations = await Promise.all(transactionIds.map(async (id) => await require_transaction$1.waitForConfirmation(id, waitRounds, this.algod)));
1412
+ if (params?.maxRoundsToWaitForConfirmation !== 0) confirmations = await Promise.all(transactionIds.map(async (id) => await require_transaction.waitForConfirmation(id, waitRounds, this.algod)));
1413
1413
  const abiReturns = this.parseAbiReturnValues(confirmations);
1414
1414
  return {
1415
1415
  groupId: group ? buffer.Buffer.from(group).toString("base64") : void 0,
@@ -1425,7 +1425,7 @@ var TransactionComposer = class TransactionComposer {
1425
1425
  if (typeof originalError === "object") err.name = originalError.name;
1426
1426
  let sentTransactions;
1427
1427
  if (this.transactionsWithSigners) sentTransactions = this.transactionsWithSigners.map((t) => t.txn);
1428
- else if (this.rawBuildTransactions) sentTransactions = this.rawBuildTransactions.length > 1 ? require_transaction.groupTransactions(this.rawBuildTransactions) : this.rawBuildTransactions;
1428
+ else if (this.rawBuildTransactions) sentTransactions = this.rawBuildTransactions.length > 1 ? require_transaction$1.groupTransactions(this.rawBuildTransactions) : this.rawBuildTransactions;
1429
1429
  if (require_config.Config.debug && typeof originalError === "object" && sentTransactions) {
1430
1430
  err.traces = [];
1431
1431
  require_config.Config.getLogger(params?.suppressLog).error("Received error executing Transaction Composer and debug flag enabled; attempting simulation to get more information", err);
@@ -1468,7 +1468,7 @@ var TransactionComposer = class TransactionComposer {
1468
1468
  let transactionsWithSigner;
1469
1469
  if (!this.transactionsWithSigners) {
1470
1470
  const builtTransactions = await this.buildTransactions();
1471
- transactionsWithSigner = (builtTransactions.transactions.length > 1 ? require_transaction.groupTransactions(builtTransactions.transactions) : builtTransactions.transactions).map((txn, index) => ({
1471
+ transactionsWithSigner = (builtTransactions.transactions.length > 1 ? require_transaction$1.groupTransactions(builtTransactions.transactions) : builtTransactions.transactions).map((txn, index) => ({
1472
1472
  txn,
1473
1473
  signer: skipSignatures ? require_signer.makeEmptyTransactionSigner() : builtTransactions.signers.get(index) ?? require_signer.makeEmptyTransactionSigner()
1474
1474
  }));