@algorandfoundation/algokit-utils 7.0.0-beta.21 → 7.0.0-beta.22

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.
package/app-deploy.js CHANGED
@@ -253,15 +253,7 @@ async function performTemplateSubstitutionAndCompile(tealCode, algod, templatePa
253
253
  * @returns The TEAL without comments
254
254
  */
255
255
  function stripTealComments(tealCode) {
256
- // find // outside quotes, i.e. won't pick up "//not a comment"
257
- const regex = /\/\/(?=([^"\\]*(\\.|"([^"\\]*\\.)*[^"\\]*"))*[^"]*$)/;
258
- tealCode = tealCode
259
- .split('\n')
260
- .map((tealCodeLine) => {
261
- return tealCodeLine.split(regex)[0].trim();
262
- })
263
- .join('\n');
264
- return tealCode;
256
+ return types_appManager.AppManager.stripTealComments(tealCode);
265
257
  }
266
258
 
267
259
  exports.deployApp = deployApp;
package/app-deploy.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"app-deploy.js","sources":["../src/app-deploy.ts"],"sourcesContent":["import algosdk from 'algosdk'\nimport { compileTeal, getAppOnCompleteAction } from './app'\nimport { _getAppArgsForABICall, _getBoxReference } from './transaction/legacy-bridge'\nimport { getSenderAddress, getSenderTransactionSigner } from './transaction/transaction'\nimport { AlgorandClientTransactionSender } from './types/algorand-client-transaction-sender'\nimport {\n ABIReturn,\n APP_DEPLOY_NOTE_DAPP,\n AppCompilationResult,\n AppDeployMetadata,\n AppDeploymentParams,\n AppLookup,\n AppMetadata,\n CompiledTeal,\n TealTemplateParams,\n} from './types/app'\nimport { AppDeployer } from './types/app-deployer'\nimport { AppManager, BoxReference } from './types/app-manager'\nimport { AssetManager } from './types/asset-manager'\nimport TransactionComposer, {\n AppCreateMethodCall,\n AppCreateParams,\n AppDeleteMethodCall,\n AppDeleteParams,\n AppUpdateMethodCall,\n AppUpdateParams,\n} from './types/composer'\nimport { Arc2TransactionNote, ConfirmedTransactionResult, ConfirmedTransactionResults, SendTransactionFrom } from './types/transaction'\nimport Algodv2 = algosdk.Algodv2\nimport Indexer = algosdk.Indexer\nimport modelsv2 = algosdk.modelsv2\n\n/**\n * @deprecated Use `algorand.appDeployer.deploy` instead.\n *\n * Idempotently deploy (create, update/delete if changed) an app against the given name via the given creator account, including deploy-time template placeholder substitutions.\n *\n * To understand the architecture decisions behind this functionality please see https://github.com/algorandfoundation/algokit-cli/blob/main/docs/architecture-decisions/2023-01-12_smart-contract-deployment.md\n *\n * **Note:** When using the return from this function be sure to check `operationPerformed` to get access to various return properties like `transaction`, `confirmation` and `deleteResult`.\n *\n * **Note:** if there is a breaking state schema change to an existing app (and `onSchemaBreak` is set to `'replace'`) the existing app will be deleted and re-created.\n *\n * **Note:** if there is an update (different TEAL code) to an existing app (and `onUpdate` is set to `'replace'`) the existing app will be deleted and re-created.\n * @param deployment The arguments to control the app deployment\n * @param algod An algod client\n * @param indexer An indexer client, needed if `existingDeployments` not passed in\n * @returns The app reference of the new/existing app\n */\nexport async function deployApp(\n deployment: AppDeploymentParams,\n algod: Algodv2,\n indexer?: Indexer,\n): Promise<\n Partial<AppCompilationResult> &\n (\n | (ConfirmedTransactionResults & AppMetadata & { return?: ABIReturn; operationPerformed: 'create' | 'update' })\n | (ConfirmedTransactionResults &\n AppMetadata & {\n return?: ABIReturn\n deleteReturn?: ABIReturn\n deleteResult: ConfirmedTransactionResult\n operationPerformed: 'replace'\n })\n | (AppMetadata & { operationPerformed: 'nothing' })\n )\n> {\n const appManager = new AppManager(algod)\n const newGroup = () =>\n new TransactionComposer({\n algod,\n getSigner: () => getSenderTransactionSigner(deployment.from),\n getSuggestedParams: async () =>\n deployment.transactionParams ? { ...deployment.transactionParams } : await algod.getTransactionParams().do(),\n appManager,\n })\n const deployer = new AppDeployer(\n appManager,\n new AlgorandClientTransactionSender(newGroup, new AssetManager(algod, newGroup), appManager),\n indexer,\n )\n\n const createParams = {\n approvalProgram: deployment.approvalProgram,\n clearStateProgram: deployment.clearStateProgram,\n sender: getSenderAddress(deployment.from),\n accountReferences: deployment.createArgs?.accounts?.map((a) => (typeof a === 'string' ? a : algosdk.encodeAddress(a.publicKey))),\n appReferences: deployment.createArgs?.apps?.map((a) => BigInt(a)),\n assetReferences: deployment.createArgs?.assets?.map((a) => BigInt(a)),\n boxReferences: deployment.createArgs?.boxes\n ?.map(_getBoxReference)\n ?.map((r) => ({ appId: BigInt(r.appIndex), name: r.name }) satisfies BoxReference),\n lease: deployment.createArgs?.lease,\n rekeyTo: deployment.createArgs?.rekeyTo ? getSenderAddress(deployment.createArgs?.rekeyTo) : undefined,\n staticFee: deployment.fee,\n maxFee: deployment.maxFee,\n extraProgramPages: deployment.schema.extraPages,\n onComplete: getAppOnCompleteAction(deployment.createOnCompleteAction) as Exclude<\n algosdk.OnApplicationComplete,\n algosdk.OnApplicationComplete.ClearStateOC\n >,\n schema: deployment.schema,\n } satisfies Partial<AppCreateParams>\n\n const updateParams = {\n approvalProgram: deployment.approvalProgram,\n clearStateProgram: deployment.clearStateProgram,\n sender: getSenderAddress(deployment.from),\n accountReferences: deployment.updateArgs?.accounts?.map((a) => (typeof a === 'string' ? a : algosdk.encodeAddress(a.publicKey))),\n appReferences: deployment.updateArgs?.apps?.map((a) => BigInt(a)),\n assetReferences: deployment.updateArgs?.assets?.map((a) => BigInt(a)),\n boxReferences: deployment.updateArgs?.boxes\n ?.map(_getBoxReference)\n ?.map((r) => ({ appId: BigInt(r.appIndex), name: r.name }) satisfies BoxReference),\n lease: deployment.updateArgs?.lease,\n rekeyTo: deployment.updateArgs?.rekeyTo ? getSenderAddress(deployment.updateArgs?.rekeyTo) : undefined,\n staticFee: deployment.fee,\n maxFee: deployment.maxFee,\n onComplete: algosdk.OnApplicationComplete.UpdateApplicationOC,\n } satisfies Partial<AppUpdateParams>\n\n const deleteParams = {\n sender: getSenderAddress(deployment.from),\n accountReferences: deployment.deleteArgs?.accounts?.map((a) => (typeof a === 'string' ? a : algosdk.encodeAddress(a.publicKey))),\n appReferences: deployment.deleteArgs?.apps?.map((a) => BigInt(a)),\n assetReferences: deployment.deleteArgs?.assets?.map((a) => BigInt(a)),\n boxReferences: deployment.deleteArgs?.boxes\n ?.map(_getBoxReference)\n ?.map((r) => ({ appId: BigInt(r.appIndex), name: r.name }) satisfies BoxReference),\n lease: deployment.deleteArgs?.lease,\n rekeyTo: deployment.deleteArgs?.rekeyTo ? getSenderAddress(deployment.deleteArgs?.rekeyTo) : undefined,\n staticFee: deployment.fee,\n maxFee: deployment.maxFee,\n onComplete: algosdk.OnApplicationComplete.DeleteApplicationOC,\n } satisfies Partial<AppDeleteParams>\n\n const encoder = new TextEncoder()\n\n const result = await deployer.deploy({\n createParams: deployment.createArgs?.method\n ? ({\n ...createParams,\n method:\n 'txnCount' in deployment.createArgs.method ? deployment.createArgs.method : new algosdk.ABIMethod(deployment.createArgs.method),\n args: (await _getAppArgsForABICall(deployment.createArgs, deployment.from)).methodArgs,\n } satisfies AppCreateMethodCall)\n : ({\n ...createParams,\n args:\n 'appArgs' in (deployment?.createArgs ?? {})\n ? deployment.createArgs?.appArgs?.map((a) => (typeof a === 'string' ? encoder.encode(a) : a))\n : undefined,\n } satisfies AppCreateParams),\n updateParams: deployment.updateArgs?.method\n ? ({\n ...updateParams,\n method:\n 'txnCount' in deployment.updateArgs.method ? deployment.updateArgs.method : new algosdk.ABIMethod(deployment.updateArgs.method),\n args: (await _getAppArgsForABICall(deployment.updateArgs, deployment.from)).methodArgs,\n } satisfies Omit<AppUpdateMethodCall, 'appId'>)\n : ({\n ...updateParams,\n args:\n 'appArgs' in (deployment?.updateArgs ?? {})\n ? deployment.updateArgs?.appArgs?.map((a) => (typeof a === 'string' ? encoder.encode(a) : a))\n : undefined,\n } satisfies Omit<AppUpdateParams, 'appId'>),\n deleteParams: deployment.deleteArgs?.method\n ? ({\n ...deleteParams,\n method:\n 'txnCount' in deployment.deleteArgs.method ? deployment.deleteArgs.method : new algosdk.ABIMethod(deployment.deleteArgs.method),\n args: (await _getAppArgsForABICall(deployment.deleteArgs, deployment.from)).methodArgs,\n } satisfies Omit<AppDeleteMethodCall, 'appId'>)\n : ({\n ...deleteParams,\n args:\n 'appArgs' in (deployment?.deleteArgs ?? {})\n ? deployment.deleteArgs?.appArgs?.map((a) => (typeof a === 'string' ? encoder.encode(a) : a))\n : undefined,\n } satisfies Omit<AppDeleteParams, 'appId'>),\n metadata: deployment.metadata,\n deployTimeParams: deployment.deployTimeParams,\n onSchemaBreak: deployment.onSchemaBreak,\n onUpdate: deployment.onUpdate,\n existingDeployments: deployment.existingDeployments\n ? {\n creator: deployment.existingDeployments.creator,\n apps: Object.fromEntries(\n Object.entries(deployment.existingDeployments.apps).map(([name, app]) => [\n name,\n { ...app, appId: BigInt(app.appId), createdRound: BigInt(app.createdRound), updatedRound: BigInt(app.updatedRound) },\n ]),\n ),\n }\n : undefined,\n maxRoundsToWaitForConfirmation: deployment.maxRoundsToWaitForConfirmation,\n populateAppCallResources: deployment.populateAppCallResources,\n suppressLog: deployment.suppressLog,\n })\n\n return { ...result, appId: Number(result.appId), createdRound: Number(result.createdRound), updatedRound: Number(result.updatedRound) }\n}\n\n/**\n * @deprecated Use `before.numByteSlice < after.numByteSlice || before.numUint < after.numUint` instead.\n *\n * Returns true is there is a breaking change in the application state schema from before to after.\n * i.e. if the schema becomes larger, since applications can't ask for more schema after creation.\n * Otherwise, there is no error, the app just doesn't store data in the extra schema :(\n *\n * @param before The existing schema\n * @param after The new schema\n * @returns Whether or not there is a breaking change\n */\nexport function isSchemaIsBroken(before: modelsv2.ApplicationStateSchema, after: modelsv2.ApplicationStateSchema) {\n return before.numByteSlice < after.numByteSlice || before.numUint < after.numUint\n}\n\n/**\n * @deprecated Use `algorand.appDeployer.getCreatorAppsByName` instead.\n *\n * Returns a lookup of name => app metadata (id, address, ...metadata) for all apps created by the given account that have an `AppDeployNote` in the transaction note of the creation transaction.\n *\n * **Note:** It's recommended this is only called once and then stored since it's a somewhat expensive operation (multiple indexer calls).\n *\n * @param creatorAccount The account (with private key loaded) or string address of an account that is the creator of the apps you want to search for\n * @param indexer An indexer client\n * @returns A name-based lookup of the app information (id, address)\n */\nexport async function getCreatorAppsByName(creatorAccount: SendTransactionFrom | string, indexer: Indexer): Promise<AppLookup> {\n const lookup = await new AppDeployer(undefined!, undefined!, indexer).getCreatorAppsByName(getSenderAddress(creatorAccount))\n\n return {\n creator: lookup.creator,\n apps: Object.fromEntries(\n Object.entries(lookup.apps).map(([name, app]) => [\n name,\n { ...app, appId: Number(app.appId), createdRound: Number(app.createdRound), updatedRound: Number(app.updatedRound) },\n ]),\n ),\n }\n}\n\n/**\n * @deprecated Use `{ dAppName: APP_DEPLOY_NOTE_DAPP, data: metadata, format: 'j' }` instead.\n *\n * Return the transaction note for an app deployment.\n * @param metadata The metadata of the deployment\n * @returns The transaction note as a utf-8 string\n */\nexport function getAppDeploymentTransactionNote(metadata: AppDeployMetadata): Arc2TransactionNote {\n return {\n dAppName: APP_DEPLOY_NOTE_DAPP,\n data: metadata,\n format: 'j',\n }\n}\n\n/**\n * @deprecated Use `AppManager.replaceTealTemplateDeployTimeControlParams` instead\n *\n * Replaces deploy-time deployment control parameters within the given teal code.\n *\n * * `TMPL_UPDATABLE` for updatability / immutability control\n * * `TMPL_DELETABLE` for deletability / permanence control\n *\n * Note: If these values are not undefined, but the corresponding `TMPL_*` value\n * isn't in the teal code it will throw an exception.\n *\n * @param tealCode The TEAL code to substitute\n * @param params The deploy-time deployment control parameter value to replace\n * @returns The replaced TEAL code\n */\nexport function replaceDeployTimeControlParams(tealCode: string, params: { updatable?: boolean; deletable?: boolean }) {\n return AppManager.replaceTealTemplateDeployTimeControlParams(tealCode, params)\n}\n\n/**\n * @deprecated Use `AppManager.replaceTealTemplateParams` instead\n *\n * Performs template substitution of a teal file.\n *\n * Looks for `TMPL_{parameter}` for template replacements.\n *\n * @param tealCode The TEAL logic to compile\n * @param templateParams Any parameters to replace in the .teal file before compiling\n * @returns The TEAL code with replacements\n */\nexport function performTemplateSubstitution(tealCode: string, templateParams?: TealTemplateParams) {\n return AppManager.replaceTealTemplateParams(tealCode, templateParams)\n}\n\n/**\n * @deprecated Use `algorand.appManager.compileTealTemplate` instead.\n *\n * Performs template substitution of a teal file and compiles it, returning the compiled result.\n *\n * Looks for `TMPL_{parameter}` for template replacements.\n *\n * @param tealCode The TEAL logic to compile\n * @param algod An algod client\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 */\nexport async function performTemplateSubstitutionAndCompile(\n tealCode: string,\n algod: Algodv2,\n templateParams?: TealTemplateParams,\n deploymentMetadata?: AppDeployMetadata,\n): Promise<CompiledTeal> {\n tealCode = stripTealComments(tealCode)\n\n tealCode = performTemplateSubstitution(tealCode, templateParams)\n\n if (deploymentMetadata) {\n tealCode = replaceDeployTimeControlParams(tealCode, deploymentMetadata)\n }\n\n return await compileTeal(tealCode, algod)\n}\n\n/**\n * @deprecated Use `AppManager.stripTealComments` instead.\n *\n * Remove comments from TEAL Code\n *\n * @param tealCode The TEAL logic to compile\n * @returns The TEAL without comments\n */\nexport function stripTealComments(tealCode: string) {\n // find // outside quotes, i.e. won't pick up \"//not a comment\"\n const regex = /\\/\\/(?=([^\"\\\\]*(\\\\.|\"([^\"\\\\]*\\\\.)*[^\"\\\\]*\"))*[^\"]*$)/\n\n tealCode = tealCode\n .split('\\n')\n .map((tealCodeLine) => {\n return tealCodeLine.split(regex)[0].trim()\n })\n .join('\\n')\n\n return tealCode\n}\n"],"names":["AppManager","TransactionComposer","getSenderTransactionSigner","AppDeployer","AlgorandClientTransactionSender","AssetManager","getSenderAddress","_getBoxReference","getAppOnCompleteAction","_getAppArgsForABICall","APP_DEPLOY_NOTE_DAPP","compileTeal"],"mappings":";;;;;;;;;;;;;AAgCA;;;;;;;;;;;;;;;;AAgBG;AACI,eAAe,SAAS,CAC7B,UAA+B,EAC/B,KAAc,EACd,OAAiB,EAAA;AAejB,IAAA,MAAM,UAAU,GAAG,IAAIA,2BAAU,CAAC,KA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CAAC,CAAA;AACvE,CAAC;AAED;;;;;;;;;;;;AAYG;AACI,eAAe,qCAAqC,CACzD,QAAgB,EAChB,KAAc,EACd,cAAmC,EACnC,kBAAsC,EAAA;AAEtC,IAAA,QAAQ,GAAG,iBAAiB,CAAC,QAAQ,CAAC,CAAA;AAEtC,IAAA,QAAQ,GAAG,2BAA2B,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAA;IAEhE,IAAI,kBAAkB,EAAE;AACtB,QAAA,QAAQ,GAAG,8BAA8B,CAAC,QAAQ,EAAE,kBAAkB,CAAC,CAAA;KACxE;AAED,IAAA,OAAO,MAAMW,eAAW,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAA;AAC3C,CAAC;AAED;;;;;;;AAOG;AACG,SAAU,iBAAiB,CAAC,QAAgB,EAAA;;IAEhD,MAAM,KAAK,GAAG,sDAAsD,CAAA;AAEpE,IAAA,QAAQ,GAAG,QAAQ;SAChB,KAAK,CAAC,IAAI,CAAC;AACX,SAAA,GAAG,CAAC,CAAC,YAAY,KAAI;AACpB,QAAA,OAAO,YAAY,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAA;AAC5C,KAAC,CAAC;SACD,IAAI,CAAC,IAAI,CAAC,CAAA;AAEb,IAAA,OAAO,QAAQ,CAAA;AACjB;;;;;;;;;;;"}
1
+ {"version":3,"file":"app-deploy.js","sources":["../src/app-deploy.ts"],"sourcesContent":["import algosdk from 'algosdk'\nimport { compileTeal, getAppOnCompleteAction } from './app'\nimport { _getAppArgsForABICall, _getBoxReference } from './transaction/legacy-bridge'\nimport { getSenderAddress, getSenderTransactionSigner } from './transaction/transaction'\nimport { AlgorandClientTransactionSender } from './types/algorand-client-transaction-sender'\nimport {\n ABIReturn,\n APP_DEPLOY_NOTE_DAPP,\n AppCompilationResult,\n AppDeployMetadata,\n AppDeploymentParams,\n AppLookup,\n AppMetadata,\n CompiledTeal,\n TealTemplateParams,\n} from './types/app'\nimport { AppDeployer } from './types/app-deployer'\nimport { AppManager, BoxReference } from './types/app-manager'\nimport { AssetManager } from './types/asset-manager'\nimport TransactionComposer, {\n AppCreateMethodCall,\n AppCreateParams,\n AppDeleteMethodCall,\n AppDeleteParams,\n AppUpdateMethodCall,\n AppUpdateParams,\n} from './types/composer'\nimport { Arc2TransactionNote, ConfirmedTransactionResult, ConfirmedTransactionResults, SendTransactionFrom } from './types/transaction'\nimport Algodv2 = algosdk.Algodv2\nimport Indexer = algosdk.Indexer\nimport modelsv2 = algosdk.modelsv2\n\n/**\n * @deprecated Use `algorand.appDeployer.deploy` instead.\n *\n * Idempotently deploy (create, update/delete if changed) an app against the given name via the given creator account, including deploy-time template placeholder substitutions.\n *\n * To understand the architecture decisions behind this functionality please see https://github.com/algorandfoundation/algokit-cli/blob/main/docs/architecture-decisions/2023-01-12_smart-contract-deployment.md\n *\n * **Note:** When using the return from this function be sure to check `operationPerformed` to get access to various return properties like `transaction`, `confirmation` and `deleteResult`.\n *\n * **Note:** if there is a breaking state schema change to an existing app (and `onSchemaBreak` is set to `'replace'`) the existing app will be deleted and re-created.\n *\n * **Note:** if there is an update (different TEAL code) to an existing app (and `onUpdate` is set to `'replace'`) the existing app will be deleted and re-created.\n * @param deployment The arguments to control the app deployment\n * @param algod An algod client\n * @param indexer An indexer client, needed if `existingDeployments` not passed in\n * @returns The app reference of the new/existing app\n */\nexport async function deployApp(\n deployment: AppDeploymentParams,\n algod: Algodv2,\n indexer?: Indexer,\n): Promise<\n Partial<AppCompilationResult> &\n (\n | (ConfirmedTransactionResults & AppMetadata & { return?: ABIReturn; operationPerformed: 'create' | 'update' })\n | (ConfirmedTransactionResults &\n AppMetadata & {\n return?: ABIReturn\n deleteReturn?: ABIReturn\n deleteResult: ConfirmedTransactionResult\n operationPerformed: 'replace'\n })\n | (AppMetadata & { operationPerformed: 'nothing' })\n )\n> {\n const appManager = new AppManager(algod)\n const newGroup = () =>\n new TransactionComposer({\n algod,\n getSigner: () => getSenderTransactionSigner(deployment.from),\n getSuggestedParams: async () =>\n deployment.transactionParams ? { ...deployment.transactionParams } : await algod.getTransactionParams().do(),\n appManager,\n })\n const deployer = new AppDeployer(\n appManager,\n new AlgorandClientTransactionSender(newGroup, new AssetManager(algod, newGroup), appManager),\n indexer,\n )\n\n const createParams = {\n approvalProgram: deployment.approvalProgram,\n clearStateProgram: deployment.clearStateProgram,\n sender: getSenderAddress(deployment.from),\n accountReferences: deployment.createArgs?.accounts?.map((a) => (typeof a === 'string' ? a : algosdk.encodeAddress(a.publicKey))),\n appReferences: deployment.createArgs?.apps?.map((a) => BigInt(a)),\n assetReferences: deployment.createArgs?.assets?.map((a) => BigInt(a)),\n boxReferences: deployment.createArgs?.boxes\n ?.map(_getBoxReference)\n ?.map((r) => ({ appId: BigInt(r.appIndex), name: r.name }) satisfies BoxReference),\n lease: deployment.createArgs?.lease,\n rekeyTo: deployment.createArgs?.rekeyTo ? getSenderAddress(deployment.createArgs?.rekeyTo) : undefined,\n staticFee: deployment.fee,\n maxFee: deployment.maxFee,\n extraProgramPages: deployment.schema.extraPages,\n onComplete: getAppOnCompleteAction(deployment.createOnCompleteAction) as Exclude<\n algosdk.OnApplicationComplete,\n algosdk.OnApplicationComplete.ClearStateOC\n >,\n schema: deployment.schema,\n } satisfies Partial<AppCreateParams>\n\n const updateParams = {\n approvalProgram: deployment.approvalProgram,\n clearStateProgram: deployment.clearStateProgram,\n sender: getSenderAddress(deployment.from),\n accountReferences: deployment.updateArgs?.accounts?.map((a) => (typeof a === 'string' ? a : algosdk.encodeAddress(a.publicKey))),\n appReferences: deployment.updateArgs?.apps?.map((a) => BigInt(a)),\n assetReferences: deployment.updateArgs?.assets?.map((a) => BigInt(a)),\n boxReferences: deployment.updateArgs?.boxes\n ?.map(_getBoxReference)\n ?.map((r) => ({ appId: BigInt(r.appIndex), name: r.name }) satisfies BoxReference),\n lease: deployment.updateArgs?.lease,\n rekeyTo: deployment.updateArgs?.rekeyTo ? getSenderAddress(deployment.updateArgs?.rekeyTo) : undefined,\n staticFee: deployment.fee,\n maxFee: deployment.maxFee,\n onComplete: algosdk.OnApplicationComplete.UpdateApplicationOC,\n } satisfies Partial<AppUpdateParams>\n\n const deleteParams = {\n sender: getSenderAddress(deployment.from),\n accountReferences: deployment.deleteArgs?.accounts?.map((a) => (typeof a === 'string' ? a : algosdk.encodeAddress(a.publicKey))),\n appReferences: deployment.deleteArgs?.apps?.map((a) => BigInt(a)),\n assetReferences: deployment.deleteArgs?.assets?.map((a) => BigInt(a)),\n boxReferences: deployment.deleteArgs?.boxes\n ?.map(_getBoxReference)\n ?.map((r) => ({ appId: BigInt(r.appIndex), name: r.name }) satisfies BoxReference),\n lease: deployment.deleteArgs?.lease,\n rekeyTo: deployment.deleteArgs?.rekeyTo ? getSenderAddress(deployment.deleteArgs?.rekeyTo) : undefined,\n staticFee: deployment.fee,\n maxFee: deployment.maxFee,\n onComplete: algosdk.OnApplicationComplete.DeleteApplicationOC,\n } satisfies Partial<AppDeleteParams>\n\n const encoder = new TextEncoder()\n\n const result = await deployer.deploy({\n createParams: deployment.createArgs?.method\n ? ({\n ...createParams,\n method:\n 'txnCount' in deployment.createArgs.method ? deployment.createArgs.method : new algosdk.ABIMethod(deployment.createArgs.method),\n args: (await _getAppArgsForABICall(deployment.createArgs, deployment.from)).methodArgs,\n } satisfies AppCreateMethodCall)\n : ({\n ...createParams,\n args:\n 'appArgs' in (deployment?.createArgs ?? {})\n ? deployment.createArgs?.appArgs?.map((a) => (typeof a === 'string' ? encoder.encode(a) : a))\n : undefined,\n } satisfies AppCreateParams),\n updateParams: deployment.updateArgs?.method\n ? ({\n ...updateParams,\n method:\n 'txnCount' in deployment.updateArgs.method ? deployment.updateArgs.method : new algosdk.ABIMethod(deployment.updateArgs.method),\n args: (await _getAppArgsForABICall(deployment.updateArgs, deployment.from)).methodArgs,\n } satisfies Omit<AppUpdateMethodCall, 'appId'>)\n : ({\n ...updateParams,\n args:\n 'appArgs' in (deployment?.updateArgs ?? {})\n ? deployment.updateArgs?.appArgs?.map((a) => (typeof a === 'string' ? encoder.encode(a) : a))\n : undefined,\n } satisfies Omit<AppUpdateParams, 'appId'>),\n deleteParams: deployment.deleteArgs?.method\n ? ({\n ...deleteParams,\n method:\n 'txnCount' in deployment.deleteArgs.method ? deployment.deleteArgs.method : new algosdk.ABIMethod(deployment.deleteArgs.method),\n args: (await _getAppArgsForABICall(deployment.deleteArgs, deployment.from)).methodArgs,\n } satisfies Omit<AppDeleteMethodCall, 'appId'>)\n : ({\n ...deleteParams,\n args:\n 'appArgs' in (deployment?.deleteArgs ?? {})\n ? deployment.deleteArgs?.appArgs?.map((a) => (typeof a === 'string' ? encoder.encode(a) : a))\n : undefined,\n } satisfies Omit<AppDeleteParams, 'appId'>),\n metadata: deployment.metadata,\n deployTimeParams: deployment.deployTimeParams,\n onSchemaBreak: deployment.onSchemaBreak,\n onUpdate: deployment.onUpdate,\n existingDeployments: deployment.existingDeployments\n ? {\n creator: deployment.existingDeployments.creator,\n apps: Object.fromEntries(\n Object.entries(deployment.existingDeployments.apps).map(([name, app]) => [\n name,\n { ...app, appId: BigInt(app.appId), createdRound: BigInt(app.createdRound), updatedRound: BigInt(app.updatedRound) },\n ]),\n ),\n }\n : undefined,\n maxRoundsToWaitForConfirmation: deployment.maxRoundsToWaitForConfirmation,\n populateAppCallResources: deployment.populateAppCallResources,\n suppressLog: deployment.suppressLog,\n })\n\n return { ...result, appId: Number(result.appId), createdRound: Number(result.createdRound), updatedRound: Number(result.updatedRound) }\n}\n\n/**\n * @deprecated Use `before.numByteSlice < after.numByteSlice || before.numUint < after.numUint` instead.\n *\n * Returns true is there is a breaking change in the application state schema from before to after.\n * i.e. if the schema becomes larger, since applications can't ask for more schema after creation.\n * Otherwise, there is no error, the app just doesn't store data in the extra schema :(\n *\n * @param before The existing schema\n * @param after The new schema\n * @returns Whether or not there is a breaking change\n */\nexport function isSchemaIsBroken(before: modelsv2.ApplicationStateSchema, after: modelsv2.ApplicationStateSchema) {\n return before.numByteSlice < after.numByteSlice || before.numUint < after.numUint\n}\n\n/**\n * @deprecated Use `algorand.appDeployer.getCreatorAppsByName` instead.\n *\n * Returns a lookup of name => app metadata (id, address, ...metadata) for all apps created by the given account that have an `AppDeployNote` in the transaction note of the creation transaction.\n *\n * **Note:** It's recommended this is only called once and then stored since it's a somewhat expensive operation (multiple indexer calls).\n *\n * @param creatorAccount The account (with private key loaded) or string address of an account that is the creator of the apps you want to search for\n * @param indexer An indexer client\n * @returns A name-based lookup of the app information (id, address)\n */\nexport async function getCreatorAppsByName(creatorAccount: SendTransactionFrom | string, indexer: Indexer): Promise<AppLookup> {\n const lookup = await new AppDeployer(undefined!, undefined!, indexer).getCreatorAppsByName(getSenderAddress(creatorAccount))\n\n return {\n creator: lookup.creator,\n apps: Object.fromEntries(\n Object.entries(lookup.apps).map(([name, app]) => [\n name,\n { ...app, appId: Number(app.appId), createdRound: Number(app.createdRound), updatedRound: Number(app.updatedRound) },\n ]),\n ),\n }\n}\n\n/**\n * @deprecated Use `{ dAppName: APP_DEPLOY_NOTE_DAPP, data: metadata, format: 'j' }` instead.\n *\n * Return the transaction note for an app deployment.\n * @param metadata The metadata of the deployment\n * @returns The transaction note as a utf-8 string\n */\nexport function getAppDeploymentTransactionNote(metadata: AppDeployMetadata): Arc2TransactionNote {\n return {\n dAppName: APP_DEPLOY_NOTE_DAPP,\n data: metadata,\n format: 'j',\n }\n}\n\n/**\n * @deprecated Use `AppManager.replaceTealTemplateDeployTimeControlParams` instead\n *\n * Replaces deploy-time deployment control parameters within the given teal code.\n *\n * * `TMPL_UPDATABLE` for updatability / immutability control\n * * `TMPL_DELETABLE` for deletability / permanence control\n *\n * Note: If these values are not undefined, but the corresponding `TMPL_*` value\n * isn't in the teal code it will throw an exception.\n *\n * @param tealCode The TEAL code to substitute\n * @param params The deploy-time deployment control parameter value to replace\n * @returns The replaced TEAL code\n */\nexport function replaceDeployTimeControlParams(tealCode: string, params: { updatable?: boolean; deletable?: boolean }) {\n return AppManager.replaceTealTemplateDeployTimeControlParams(tealCode, params)\n}\n\n/**\n * @deprecated Use `AppManager.replaceTealTemplateParams` instead\n *\n * Performs template substitution of a teal file.\n *\n * Looks for `TMPL_{parameter}` for template replacements.\n *\n * @param tealCode The TEAL logic to compile\n * @param templateParams Any parameters to replace in the .teal file before compiling\n * @returns The TEAL code with replacements\n */\nexport function performTemplateSubstitution(tealCode: string, templateParams?: TealTemplateParams) {\n return AppManager.replaceTealTemplateParams(tealCode, templateParams)\n}\n\n/**\n * @deprecated Use `algorand.appManager.compileTealTemplate` instead.\n *\n * Performs template substitution of a teal file and compiles it, returning the compiled result.\n *\n * Looks for `TMPL_{parameter}` for template replacements.\n *\n * @param tealCode The TEAL logic to compile\n * @param algod An algod client\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 */\nexport async function performTemplateSubstitutionAndCompile(\n tealCode: string,\n algod: Algodv2,\n templateParams?: TealTemplateParams,\n deploymentMetadata?: AppDeployMetadata,\n): Promise<CompiledTeal> {\n tealCode = stripTealComments(tealCode)\n\n tealCode = performTemplateSubstitution(tealCode, templateParams)\n\n if (deploymentMetadata) {\n tealCode = replaceDeployTimeControlParams(tealCode, deploymentMetadata)\n }\n\n return await compileTeal(tealCode, algod)\n}\n\n/**\n * @deprecated Use `AppManager.stripTealComments` instead.\n *\n * Remove comments from TEAL Code\n *\n * @param tealCode The TEAL logic to compile\n * @returns The TEAL without comments\n */\nexport function stripTealComments(tealCode: string) {\n return AppManager.stripTealComments(tealCode)\n}\n"],"names":["AppManager","TransactionComposer","getSenderTransactionSigner","AppDeployer","AlgorandClientTransactionSender","AssetManager","getSenderAddress","_getBoxReference","getAppOnCompleteAction","_getAppArgsForABICall","APP_DEPLOY_NOTE_DAPP","compileTeal"],"mappings":";;;;;;;;;;;;;AAgCA;;;;;;;;;;;;;;;;AAgBG;AACI,eAAe,SAAS,CAC7B,UAA+B,EAC/B,KAAc,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mC,EAAA;IAC/F,OAAOA,2BAAU,CAAC,yBAAyB,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAA;AACvE,CAAC;AAED;;;;;;;;;;;;AAYG;AACI,eAAe,qCAAqC,CACzD,QAAgB,EAChB,KAAc,EACd,cAAmC,EACnC,kBAAsC,EAAA;AAEtC,IAAA,QAAQ,GAAG,iBAAiB,CAAC,QAAQ,CAAC,CAAA;AAEtC,IAAA,QAAQ,GAAG,2BAA2B,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAA;IAEhE,IAAI,kBAAkB,EAAE;AACtB,QAAA,QAAQ,GAAG,8BAA8B,CAAC,QAAQ,EAAE,kBAAkB,CAAC,CAAA;KACxE;AAED,IAAA,OAAO,MAAMW,eAAW,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAA;AAC3C,CAAC;AAED;;;;;;;AAOG;AACG,SAAU,iBAAiB,CAAC,QAAgB,EAAA;AAChD,IAAA,OAAOX,2BAAU,CAAC,iBAAiB,CAAC,QAAQ,CAAC,CAAA;AAC/C;;;;;;;;;;;"}
package/app-deploy.mjs CHANGED
@@ -251,15 +251,7 @@ async function performTemplateSubstitutionAndCompile(tealCode, algod, templatePa
251
251
  * @returns The TEAL without comments
252
252
  */
253
253
  function stripTealComments(tealCode) {
254
- // find // outside quotes, i.e. won't pick up "//not a comment"
255
- const regex = /\/\/(?=([^"\\]*(\\.|"([^"\\]*\\.)*[^"\\]*"))*[^"]*$)/;
256
- tealCode = tealCode
257
- .split('\n')
258
- .map((tealCodeLine) => {
259
- return tealCodeLine.split(regex)[0].trim();
260
- })
261
- .join('\n');
262
- return tealCode;
254
+ return AppManager.stripTealComments(tealCode);
263
255
  }
264
256
 
265
257
  export { deployApp, getAppDeploymentTransactionNote, getCreatorAppsByName, isSchemaIsBroken, performTemplateSubstitution, performTemplateSubstitutionAndCompile, replaceDeployTimeControlParams, stripTealComments };
@@ -1 +1 @@
1
- {"version":3,"file":"app-deploy.mjs","sources":["../src/app-deploy.ts"],"sourcesContent":["import algosdk from 'algosdk'\nimport { compileTeal, getAppOnCompleteAction } from './app'\nimport { _getAppArgsForABICall, _getBoxReference } from './transaction/legacy-bridge'\nimport { getSenderAddress, getSenderTransactionSigner } from './transaction/transaction'\nimport { AlgorandClientTransactionSender } from './types/algorand-client-transaction-sender'\nimport {\n ABIReturn,\n APP_DEPLOY_NOTE_DAPP,\n AppCompilationResult,\n AppDeployMetadata,\n AppDeploymentParams,\n AppLookup,\n AppMetadata,\n CompiledTeal,\n TealTemplateParams,\n} from './types/app'\nimport { AppDeployer } from './types/app-deployer'\nimport { AppManager, BoxReference } from './types/app-manager'\nimport { AssetManager } from './types/asset-manager'\nimport TransactionComposer, {\n AppCreateMethodCall,\n AppCreateParams,\n AppDeleteMethodCall,\n AppDeleteParams,\n AppUpdateMethodCall,\n AppUpdateParams,\n} from './types/composer'\nimport { Arc2TransactionNote, ConfirmedTransactionResult, ConfirmedTransactionResults, SendTransactionFrom } from './types/transaction'\nimport Algodv2 = algosdk.Algodv2\nimport Indexer = algosdk.Indexer\nimport modelsv2 = algosdk.modelsv2\n\n/**\n * @deprecated Use `algorand.appDeployer.deploy` instead.\n *\n * Idempotently deploy (create, update/delete if changed) an app against the given name via the given creator account, including deploy-time template placeholder substitutions.\n *\n * To understand the architecture decisions behind this functionality please see https://github.com/algorandfoundation/algokit-cli/blob/main/docs/architecture-decisions/2023-01-12_smart-contract-deployment.md\n *\n * **Note:** When using the return from this function be sure to check `operationPerformed` to get access to various return properties like `transaction`, `confirmation` and `deleteResult`.\n *\n * **Note:** if there is a breaking state schema change to an existing app (and `onSchemaBreak` is set to `'replace'`) the existing app will be deleted and re-created.\n *\n * **Note:** if there is an update (different TEAL code) to an existing app (and `onUpdate` is set to `'replace'`) the existing app will be deleted and re-created.\n * @param deployment The arguments to control the app deployment\n * @param algod An algod client\n * @param indexer An indexer client, needed if `existingDeployments` not passed in\n * @returns The app reference of the new/existing app\n */\nexport async function deployApp(\n deployment: AppDeploymentParams,\n algod: Algodv2,\n indexer?: Indexer,\n): Promise<\n Partial<AppCompilationResult> &\n (\n | (ConfirmedTransactionResults & AppMetadata & { return?: ABIReturn; operationPerformed: 'create' | 'update' })\n | (ConfirmedTransactionResults &\n AppMetadata & {\n return?: ABIReturn\n deleteReturn?: ABIReturn\n deleteResult: ConfirmedTransactionResult\n operationPerformed: 'replace'\n })\n | (AppMetadata & { operationPerformed: 'nothing' })\n )\n> {\n const appManager = new AppManager(algod)\n const newGroup = () =>\n new TransactionComposer({\n algod,\n getSigner: () => getSenderTransactionSigner(deployment.from),\n getSuggestedParams: async () =>\n deployment.transactionParams ? { ...deployment.transactionParams } : await algod.getTransactionParams().do(),\n appManager,\n })\n const deployer = new AppDeployer(\n appManager,\n new AlgorandClientTransactionSender(newGroup, new AssetManager(algod, newGroup), appManager),\n indexer,\n )\n\n const createParams = {\n approvalProgram: deployment.approvalProgram,\n clearStateProgram: deployment.clearStateProgram,\n sender: getSenderAddress(deployment.from),\n accountReferences: deployment.createArgs?.accounts?.map((a) => (typeof a === 'string' ? a : algosdk.encodeAddress(a.publicKey))),\n appReferences: deployment.createArgs?.apps?.map((a) => BigInt(a)),\n assetReferences: deployment.createArgs?.assets?.map((a) => BigInt(a)),\n boxReferences: deployment.createArgs?.boxes\n ?.map(_getBoxReference)\n ?.map((r) => ({ appId: BigInt(r.appIndex), name: r.name }) satisfies BoxReference),\n lease: deployment.createArgs?.lease,\n rekeyTo: deployment.createArgs?.rekeyTo ? getSenderAddress(deployment.createArgs?.rekeyTo) : undefined,\n staticFee: deployment.fee,\n maxFee: deployment.maxFee,\n extraProgramPages: deployment.schema.extraPages,\n onComplete: getAppOnCompleteAction(deployment.createOnCompleteAction) as Exclude<\n algosdk.OnApplicationComplete,\n algosdk.OnApplicationComplete.ClearStateOC\n >,\n schema: deployment.schema,\n } satisfies Partial<AppCreateParams>\n\n const updateParams = {\n approvalProgram: deployment.approvalProgram,\n clearStateProgram: deployment.clearStateProgram,\n sender: getSenderAddress(deployment.from),\n accountReferences: deployment.updateArgs?.accounts?.map((a) => (typeof a === 'string' ? a : algosdk.encodeAddress(a.publicKey))),\n appReferences: deployment.updateArgs?.apps?.map((a) => BigInt(a)),\n assetReferences: deployment.updateArgs?.assets?.map((a) => BigInt(a)),\n boxReferences: deployment.updateArgs?.boxes\n ?.map(_getBoxReference)\n ?.map((r) => ({ appId: BigInt(r.appIndex), name: r.name }) satisfies BoxReference),\n lease: deployment.updateArgs?.lease,\n rekeyTo: deployment.updateArgs?.rekeyTo ? getSenderAddress(deployment.updateArgs?.rekeyTo) : undefined,\n staticFee: deployment.fee,\n maxFee: deployment.maxFee,\n onComplete: algosdk.OnApplicationComplete.UpdateApplicationOC,\n } satisfies Partial<AppUpdateParams>\n\n const deleteParams = {\n sender: getSenderAddress(deployment.from),\n accountReferences: deployment.deleteArgs?.accounts?.map((a) => (typeof a === 'string' ? a : algosdk.encodeAddress(a.publicKey))),\n appReferences: deployment.deleteArgs?.apps?.map((a) => BigInt(a)),\n assetReferences: deployment.deleteArgs?.assets?.map((a) => BigInt(a)),\n boxReferences: deployment.deleteArgs?.boxes\n ?.map(_getBoxReference)\n ?.map((r) => ({ appId: BigInt(r.appIndex), name: r.name }) satisfies BoxReference),\n lease: deployment.deleteArgs?.lease,\n rekeyTo: deployment.deleteArgs?.rekeyTo ? getSenderAddress(deployment.deleteArgs?.rekeyTo) : undefined,\n staticFee: deployment.fee,\n maxFee: deployment.maxFee,\n onComplete: algosdk.OnApplicationComplete.DeleteApplicationOC,\n } satisfies Partial<AppDeleteParams>\n\n const encoder = new TextEncoder()\n\n const result = await deployer.deploy({\n createParams: deployment.createArgs?.method\n ? ({\n ...createParams,\n method:\n 'txnCount' in deployment.createArgs.method ? deployment.createArgs.method : new algosdk.ABIMethod(deployment.createArgs.method),\n args: (await _getAppArgsForABICall(deployment.createArgs, deployment.from)).methodArgs,\n } satisfies AppCreateMethodCall)\n : ({\n ...createParams,\n args:\n 'appArgs' in (deployment?.createArgs ?? {})\n ? deployment.createArgs?.appArgs?.map((a) => (typeof a === 'string' ? encoder.encode(a) : a))\n : undefined,\n } satisfies AppCreateParams),\n updateParams: deployment.updateArgs?.method\n ? ({\n ...updateParams,\n method:\n 'txnCount' in deployment.updateArgs.method ? deployment.updateArgs.method : new algosdk.ABIMethod(deployment.updateArgs.method),\n args: (await _getAppArgsForABICall(deployment.updateArgs, deployment.from)).methodArgs,\n } satisfies Omit<AppUpdateMethodCall, 'appId'>)\n : ({\n ...updateParams,\n args:\n 'appArgs' in (deployment?.updateArgs ?? {})\n ? deployment.updateArgs?.appArgs?.map((a) => (typeof a === 'string' ? encoder.encode(a) : a))\n : undefined,\n } satisfies Omit<AppUpdateParams, 'appId'>),\n deleteParams: deployment.deleteArgs?.method\n ? ({\n ...deleteParams,\n method:\n 'txnCount' in deployment.deleteArgs.method ? deployment.deleteArgs.method : new algosdk.ABIMethod(deployment.deleteArgs.method),\n args: (await _getAppArgsForABICall(deployment.deleteArgs, deployment.from)).methodArgs,\n } satisfies Omit<AppDeleteMethodCall, 'appId'>)\n : ({\n ...deleteParams,\n args:\n 'appArgs' in (deployment?.deleteArgs ?? {})\n ? deployment.deleteArgs?.appArgs?.map((a) => (typeof a === 'string' ? encoder.encode(a) : a))\n : undefined,\n } satisfies Omit<AppDeleteParams, 'appId'>),\n metadata: deployment.metadata,\n deployTimeParams: deployment.deployTimeParams,\n onSchemaBreak: deployment.onSchemaBreak,\n onUpdate: deployment.onUpdate,\n existingDeployments: deployment.existingDeployments\n ? {\n creator: deployment.existingDeployments.creator,\n apps: Object.fromEntries(\n Object.entries(deployment.existingDeployments.apps).map(([name, app]) => [\n name,\n { ...app, appId: BigInt(app.appId), createdRound: BigInt(app.createdRound), updatedRound: BigInt(app.updatedRound) },\n ]),\n ),\n }\n : undefined,\n maxRoundsToWaitForConfirmation: deployment.maxRoundsToWaitForConfirmation,\n populateAppCallResources: deployment.populateAppCallResources,\n suppressLog: deployment.suppressLog,\n })\n\n return { ...result, appId: Number(result.appId), createdRound: Number(result.createdRound), updatedRound: Number(result.updatedRound) }\n}\n\n/**\n * @deprecated Use `before.numByteSlice < after.numByteSlice || before.numUint < after.numUint` instead.\n *\n * Returns true is there is a breaking change in the application state schema from before to after.\n * i.e. if the schema becomes larger, since applications can't ask for more schema after creation.\n * Otherwise, there is no error, the app just doesn't store data in the extra schema :(\n *\n * @param before The existing schema\n * @param after The new schema\n * @returns Whether or not there is a breaking change\n */\nexport function isSchemaIsBroken(before: modelsv2.ApplicationStateSchema, after: modelsv2.ApplicationStateSchema) {\n return before.numByteSlice < after.numByteSlice || before.numUint < after.numUint\n}\n\n/**\n * @deprecated Use `algorand.appDeployer.getCreatorAppsByName` instead.\n *\n * Returns a lookup of name => app metadata (id, address, ...metadata) for all apps created by the given account that have an `AppDeployNote` in the transaction note of the creation transaction.\n *\n * **Note:** It's recommended this is only called once and then stored since it's a somewhat expensive operation (multiple indexer calls).\n *\n * @param creatorAccount The account (with private key loaded) or string address of an account that is the creator of the apps you want to search for\n * @param indexer An indexer client\n * @returns A name-based lookup of the app information (id, address)\n */\nexport async function getCreatorAppsByName(creatorAccount: SendTransactionFrom | string, indexer: Indexer): Promise<AppLookup> {\n const lookup = await new AppDeployer(undefined!, undefined!, indexer).getCreatorAppsByName(getSenderAddress(creatorAccount))\n\n return {\n creator: lookup.creator,\n apps: Object.fromEntries(\n Object.entries(lookup.apps).map(([name, app]) => [\n name,\n { ...app, appId: Number(app.appId), createdRound: Number(app.createdRound), updatedRound: Number(app.updatedRound) },\n ]),\n ),\n }\n}\n\n/**\n * @deprecated Use `{ dAppName: APP_DEPLOY_NOTE_DAPP, data: metadata, format: 'j' }` instead.\n *\n * Return the transaction note for an app deployment.\n * @param metadata The metadata of the deployment\n * @returns The transaction note as a utf-8 string\n */\nexport function getAppDeploymentTransactionNote(metadata: AppDeployMetadata): Arc2TransactionNote {\n return {\n dAppName: APP_DEPLOY_NOTE_DAPP,\n data: metadata,\n format: 'j',\n }\n}\n\n/**\n * @deprecated Use `AppManager.replaceTealTemplateDeployTimeControlParams` instead\n *\n * Replaces deploy-time deployment control parameters within the given teal code.\n *\n * * `TMPL_UPDATABLE` for updatability / immutability control\n * * `TMPL_DELETABLE` for deletability / permanence control\n *\n * Note: If these values are not undefined, but the corresponding `TMPL_*` value\n * isn't in the teal code it will throw an exception.\n *\n * @param tealCode The TEAL code to substitute\n * @param params The deploy-time deployment control parameter value to replace\n * @returns The replaced TEAL code\n */\nexport function replaceDeployTimeControlParams(tealCode: string, params: { updatable?: boolean; deletable?: boolean }) {\n return AppManager.replaceTealTemplateDeployTimeControlParams(tealCode, params)\n}\n\n/**\n * @deprecated Use `AppManager.replaceTealTemplateParams` instead\n *\n * Performs template substitution of a teal file.\n *\n * Looks for `TMPL_{parameter}` for template replacements.\n *\n * @param tealCode The TEAL logic to compile\n * @param templateParams Any parameters to replace in the .teal file before compiling\n * @returns The TEAL code with replacements\n */\nexport function performTemplateSubstitution(tealCode: string, templateParams?: TealTemplateParams) {\n return AppManager.replaceTealTemplateParams(tealCode, templateParams)\n}\n\n/**\n * @deprecated Use `algorand.appManager.compileTealTemplate` instead.\n *\n * Performs template substitution of a teal file and compiles it, returning the compiled result.\n *\n * Looks for `TMPL_{parameter}` for template replacements.\n *\n * @param tealCode The TEAL logic to compile\n * @param algod An algod client\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 */\nexport async function performTemplateSubstitutionAndCompile(\n tealCode: string,\n algod: Algodv2,\n templateParams?: TealTemplateParams,\n deploymentMetadata?: AppDeployMetadata,\n): Promise<CompiledTeal> {\n tealCode = stripTealComments(tealCode)\n\n tealCode = performTemplateSubstitution(tealCode, templateParams)\n\n if (deploymentMetadata) {\n tealCode = replaceDeployTimeControlParams(tealCode, deploymentMetadata)\n }\n\n return await compileTeal(tealCode, algod)\n}\n\n/**\n * @deprecated Use `AppManager.stripTealComments` instead.\n *\n * Remove comments from TEAL Code\n *\n * @param tealCode The TEAL logic to compile\n * @returns The TEAL without comments\n */\nexport function stripTealComments(tealCode: string) {\n // find // outside quotes, i.e. won't pick up \"//not a comment\"\n const regex = /\\/\\/(?=([^\"\\\\]*(\\\\.|\"([^\"\\\\]*\\\\.)*[^\"\\\\]*\"))*[^\"]*$)/\n\n tealCode = tealCode\n .split('\\n')\n .map((tealCodeLine) => {\n return tealCodeLine.split(regex)[0].trim()\n })\n .join('\\n')\n\n return tealCode\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAgCA;;;;;;;;;;;;;;;;AAgBG;AACI,eAAe,SAAS,CAC7B,UAA+B,EAC/B,KAAc,EACd,OAAiB,EAAA;AAejB,IAAA,MAAM,UAAU,GAAG,IAAI,UAAU,CAAC,KAAK,CAAC,CAAA;AACxC,IAAA,MAAM,QAAQ,GAAG,MACf,IAAI,mBAAmB,CAAC;QACtB,KAAK;QACL,SAAS,EAAE,MAAM,0BAA0B,CAAC,UAAU,CAAC,IAAI,CAAC;QAC5D,kBAAkB,EAAE,YAClB,UAAU,CAAC,iBAAiB,GAAG,EAAE,GAAG,UAAU,CAAC,iBAAiB,EAAE,GAAG,MAAM,KAAK,CAAC,oBAAoB,EAAE,CAAC,EAAE,EAAE;QAC9G,UAAU;AACX,KAAA,CAAC,CAAA;IACJ,MAAM,QAAQ,GAAG,IAAI,WAAW,CAC9B,UAAU,EACV,IAAI,+BAA+B,CAAC,QAAQ,EAAE,IAAI,YAAY,CAAC,KAAK,EAAE,QAAQ,CAAC,EAAE,UAAU,CAAC,EAC5F,OAAO,CACR,CAAA;AAED,IAAA,MAAM,YAAY,GAAG;QACnB,eAAe,EAAE,UAAU,CAAC,eAAe;QAC3C,iBAAiB,EAAE,UAAU,CAAC,iBAAiB;AAC/C,QAAA,MAAM,EAAE,gBAAgB,CAAC,UAAU,CAAC,IAAI,CAAC;AACzC,QAAA,iBAAiB,EAAE,UAAU,CAAC,UAAU,EAAE,QAAQ,EAAE,GAAG,CAAC,CAAC,CAAC,MAAM,OAAO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AAA,OAAO,QAAQ,CAAA;AACjB;;;;"}
1
+ {"version":3,"file":"app-deploy.mjs","sources":["../src/app-deploy.ts"],"sourcesContent":["import algosdk from 'algosdk'\nimport { compileTeal, getAppOnCompleteAction } from './app'\nimport { _getAppArgsForABICall, _getBoxReference } from './transaction/legacy-bridge'\nimport { getSenderAddress, getSenderTransactionSigner } from './transaction/transaction'\nimport { AlgorandClientTransactionSender } from './types/algorand-client-transaction-sender'\nimport {\n ABIReturn,\n APP_DEPLOY_NOTE_DAPP,\n AppCompilationResult,\n AppDeployMetadata,\n AppDeploymentParams,\n AppLookup,\n AppMetadata,\n CompiledTeal,\n TealTemplateParams,\n} from './types/app'\nimport { AppDeployer } from './types/app-deployer'\nimport { AppManager, BoxReference } from './types/app-manager'\nimport { AssetManager } from './types/asset-manager'\nimport TransactionComposer, {\n AppCreateMethodCall,\n AppCreateParams,\n AppDeleteMethodCall,\n AppDeleteParams,\n AppUpdateMethodCall,\n AppUpdateParams,\n} from './types/composer'\nimport { Arc2TransactionNote, ConfirmedTransactionResult, ConfirmedTransactionResults, SendTransactionFrom } from './types/transaction'\nimport Algodv2 = algosdk.Algodv2\nimport Indexer = algosdk.Indexer\nimport modelsv2 = algosdk.modelsv2\n\n/**\n * @deprecated Use `algorand.appDeployer.deploy` instead.\n *\n * Idempotently deploy (create, update/delete if changed) an app against the given name via the given creator account, including deploy-time template placeholder substitutions.\n *\n * To understand the architecture decisions behind this functionality please see https://github.com/algorandfoundation/algokit-cli/blob/main/docs/architecture-decisions/2023-01-12_smart-contract-deployment.md\n *\n * **Note:** When using the return from this function be sure to check `operationPerformed` to get access to various return properties like `transaction`, `confirmation` and `deleteResult`.\n *\n * **Note:** if there is a breaking state schema change to an existing app (and `onSchemaBreak` is set to `'replace'`) the existing app will be deleted and re-created.\n *\n * **Note:** if there is an update (different TEAL code) to an existing app (and `onUpdate` is set to `'replace'`) the existing app will be deleted and re-created.\n * @param deployment The arguments to control the app deployment\n * @param algod An algod client\n * @param indexer An indexer client, needed if `existingDeployments` not passed in\n * @returns The app reference of the new/existing app\n */\nexport async function deployApp(\n deployment: AppDeploymentParams,\n algod: Algodv2,\n indexer?: Indexer,\n): Promise<\n Partial<AppCompilationResult> &\n (\n | (ConfirmedTransactionResults & AppMetadata & { return?: ABIReturn; operationPerformed: 'create' | 'update' })\n | (ConfirmedTransactionResults &\n AppMetadata & {\n return?: ABIReturn\n deleteReturn?: ABIReturn\n deleteResult: ConfirmedTransactionResult\n operationPerformed: 'replace'\n })\n | (AppMetadata & { operationPerformed: 'nothing' })\n )\n> {\n const appManager = new AppManager(algod)\n const newGroup = () =>\n new TransactionComposer({\n algod,\n getSigner: () => getSenderTransactionSigner(deployment.from),\n getSuggestedParams: async () =>\n deployment.transactionParams ? { ...deployment.transactionParams } : await algod.getTransactionParams().do(),\n appManager,\n })\n const deployer = new AppDeployer(\n appManager,\n new AlgorandClientTransactionSender(newGroup, new AssetManager(algod, newGroup), appManager),\n indexer,\n )\n\n const createParams = {\n approvalProgram: deployment.approvalProgram,\n clearStateProgram: deployment.clearStateProgram,\n sender: getSenderAddress(deployment.from),\n accountReferences: deployment.createArgs?.accounts?.map((a) => (typeof a === 'string' ? a : algosdk.encodeAddress(a.publicKey))),\n appReferences: deployment.createArgs?.apps?.map((a) => BigInt(a)),\n assetReferences: deployment.createArgs?.assets?.map((a) => BigInt(a)),\n boxReferences: deployment.createArgs?.boxes\n ?.map(_getBoxReference)\n ?.map((r) => ({ appId: BigInt(r.appIndex), name: r.name }) satisfies BoxReference),\n lease: deployment.createArgs?.lease,\n rekeyTo: deployment.createArgs?.rekeyTo ? getSenderAddress(deployment.createArgs?.rekeyTo) : undefined,\n staticFee: deployment.fee,\n maxFee: deployment.maxFee,\n extraProgramPages: deployment.schema.extraPages,\n onComplete: getAppOnCompleteAction(deployment.createOnCompleteAction) as Exclude<\n algosdk.OnApplicationComplete,\n algosdk.OnApplicationComplete.ClearStateOC\n >,\n schema: deployment.schema,\n } satisfies Partial<AppCreateParams>\n\n const updateParams = {\n approvalProgram: deployment.approvalProgram,\n clearStateProgram: deployment.clearStateProgram,\n sender: getSenderAddress(deployment.from),\n accountReferences: deployment.updateArgs?.accounts?.map((a) => (typeof a === 'string' ? a : algosdk.encodeAddress(a.publicKey))),\n appReferences: deployment.updateArgs?.apps?.map((a) => BigInt(a)),\n assetReferences: deployment.updateArgs?.assets?.map((a) => BigInt(a)),\n boxReferences: deployment.updateArgs?.boxes\n ?.map(_getBoxReference)\n ?.map((r) => ({ appId: BigInt(r.appIndex), name: r.name }) satisfies BoxReference),\n lease: deployment.updateArgs?.lease,\n rekeyTo: deployment.updateArgs?.rekeyTo ? getSenderAddress(deployment.updateArgs?.rekeyTo) : undefined,\n staticFee: deployment.fee,\n maxFee: deployment.maxFee,\n onComplete: algosdk.OnApplicationComplete.UpdateApplicationOC,\n } satisfies Partial<AppUpdateParams>\n\n const deleteParams = {\n sender: getSenderAddress(deployment.from),\n accountReferences: deployment.deleteArgs?.accounts?.map((a) => (typeof a === 'string' ? a : algosdk.encodeAddress(a.publicKey))),\n appReferences: deployment.deleteArgs?.apps?.map((a) => BigInt(a)),\n assetReferences: deployment.deleteArgs?.assets?.map((a) => BigInt(a)),\n boxReferences: deployment.deleteArgs?.boxes\n ?.map(_getBoxReference)\n ?.map((r) => ({ appId: BigInt(r.appIndex), name: r.name }) satisfies BoxReference),\n lease: deployment.deleteArgs?.lease,\n rekeyTo: deployment.deleteArgs?.rekeyTo ? getSenderAddress(deployment.deleteArgs?.rekeyTo) : undefined,\n staticFee: deployment.fee,\n maxFee: deployment.maxFee,\n onComplete: algosdk.OnApplicationComplete.DeleteApplicationOC,\n } satisfies Partial<AppDeleteParams>\n\n const encoder = new TextEncoder()\n\n const result = await deployer.deploy({\n createParams: deployment.createArgs?.method\n ? ({\n ...createParams,\n method:\n 'txnCount' in deployment.createArgs.method ? deployment.createArgs.method : new algosdk.ABIMethod(deployment.createArgs.method),\n args: (await _getAppArgsForABICall(deployment.createArgs, deployment.from)).methodArgs,\n } satisfies AppCreateMethodCall)\n : ({\n ...createParams,\n args:\n 'appArgs' in (deployment?.createArgs ?? {})\n ? deployment.createArgs?.appArgs?.map((a) => (typeof a === 'string' ? encoder.encode(a) : a))\n : undefined,\n } satisfies AppCreateParams),\n updateParams: deployment.updateArgs?.method\n ? ({\n ...updateParams,\n method:\n 'txnCount' in deployment.updateArgs.method ? deployment.updateArgs.method : new algosdk.ABIMethod(deployment.updateArgs.method),\n args: (await _getAppArgsForABICall(deployment.updateArgs, deployment.from)).methodArgs,\n } satisfies Omit<AppUpdateMethodCall, 'appId'>)\n : ({\n ...updateParams,\n args:\n 'appArgs' in (deployment?.updateArgs ?? {})\n ? deployment.updateArgs?.appArgs?.map((a) => (typeof a === 'string' ? encoder.encode(a) : a))\n : undefined,\n } satisfies Omit<AppUpdateParams, 'appId'>),\n deleteParams: deployment.deleteArgs?.method\n ? ({\n ...deleteParams,\n method:\n 'txnCount' in deployment.deleteArgs.method ? deployment.deleteArgs.method : new algosdk.ABIMethod(deployment.deleteArgs.method),\n args: (await _getAppArgsForABICall(deployment.deleteArgs, deployment.from)).methodArgs,\n } satisfies Omit<AppDeleteMethodCall, 'appId'>)\n : ({\n ...deleteParams,\n args:\n 'appArgs' in (deployment?.deleteArgs ?? {})\n ? deployment.deleteArgs?.appArgs?.map((a) => (typeof a === 'string' ? encoder.encode(a) : a))\n : undefined,\n } satisfies Omit<AppDeleteParams, 'appId'>),\n metadata: deployment.metadata,\n deployTimeParams: deployment.deployTimeParams,\n onSchemaBreak: deployment.onSchemaBreak,\n onUpdate: deployment.onUpdate,\n existingDeployments: deployment.existingDeployments\n ? {\n creator: deployment.existingDeployments.creator,\n apps: Object.fromEntries(\n Object.entries(deployment.existingDeployments.apps).map(([name, app]) => [\n name,\n { ...app, appId: BigInt(app.appId), createdRound: BigInt(app.createdRound), updatedRound: BigInt(app.updatedRound) },\n ]),\n ),\n }\n : undefined,\n maxRoundsToWaitForConfirmation: deployment.maxRoundsToWaitForConfirmation,\n populateAppCallResources: deployment.populateAppCallResources,\n suppressLog: deployment.suppressLog,\n })\n\n return { ...result, appId: Number(result.appId), createdRound: Number(result.createdRound), updatedRound: Number(result.updatedRound) }\n}\n\n/**\n * @deprecated Use `before.numByteSlice < after.numByteSlice || before.numUint < after.numUint` instead.\n *\n * Returns true is there is a breaking change in the application state schema from before to after.\n * i.e. if the schema becomes larger, since applications can't ask for more schema after creation.\n * Otherwise, there is no error, the app just doesn't store data in the extra schema :(\n *\n * @param before The existing schema\n * @param after The new schema\n * @returns Whether or not there is a breaking change\n */\nexport function isSchemaIsBroken(before: modelsv2.ApplicationStateSchema, after: modelsv2.ApplicationStateSchema) {\n return before.numByteSlice < after.numByteSlice || before.numUint < after.numUint\n}\n\n/**\n * @deprecated Use `algorand.appDeployer.getCreatorAppsByName` instead.\n *\n * Returns a lookup of name => app metadata (id, address, ...metadata) for all apps created by the given account that have an `AppDeployNote` in the transaction note of the creation transaction.\n *\n * **Note:** It's recommended this is only called once and then stored since it's a somewhat expensive operation (multiple indexer calls).\n *\n * @param creatorAccount The account (with private key loaded) or string address of an account that is the creator of the apps you want to search for\n * @param indexer An indexer client\n * @returns A name-based lookup of the app information (id, address)\n */\nexport async function getCreatorAppsByName(creatorAccount: SendTransactionFrom | string, indexer: Indexer): Promise<AppLookup> {\n const lookup = await new AppDeployer(undefined!, undefined!, indexer).getCreatorAppsByName(getSenderAddress(creatorAccount))\n\n return {\n creator: lookup.creator,\n apps: Object.fromEntries(\n Object.entries(lookup.apps).map(([name, app]) => [\n name,\n { ...app, appId: Number(app.appId), createdRound: Number(app.createdRound), updatedRound: Number(app.updatedRound) },\n ]),\n ),\n }\n}\n\n/**\n * @deprecated Use `{ dAppName: APP_DEPLOY_NOTE_DAPP, data: metadata, format: 'j' }` instead.\n *\n * Return the transaction note for an app deployment.\n * @param metadata The metadata of the deployment\n * @returns The transaction note as a utf-8 string\n */\nexport function getAppDeploymentTransactionNote(metadata: AppDeployMetadata): Arc2TransactionNote {\n return {\n dAppName: APP_DEPLOY_NOTE_DAPP,\n data: metadata,\n format: 'j',\n }\n}\n\n/**\n * @deprecated Use `AppManager.replaceTealTemplateDeployTimeControlParams` instead\n *\n * Replaces deploy-time deployment control parameters within the given teal code.\n *\n * * `TMPL_UPDATABLE` for updatability / immutability control\n * * `TMPL_DELETABLE` for deletability / permanence control\n *\n * Note: If these values are not undefined, but the corresponding `TMPL_*` value\n * isn't in the teal code it will throw an exception.\n *\n * @param tealCode The TEAL code to substitute\n * @param params The deploy-time deployment control parameter value to replace\n * @returns The replaced TEAL code\n */\nexport function replaceDeployTimeControlParams(tealCode: string, params: { updatable?: boolean; deletable?: boolean }) {\n return AppManager.replaceTealTemplateDeployTimeControlParams(tealCode, params)\n}\n\n/**\n * @deprecated Use `AppManager.replaceTealTemplateParams` instead\n *\n * Performs template substitution of a teal file.\n *\n * Looks for `TMPL_{parameter}` for template replacements.\n *\n * @param tealCode The TEAL logic to compile\n * @param templateParams Any parameters to replace in the .teal file before compiling\n * @returns The TEAL code with replacements\n */\nexport function performTemplateSubstitution(tealCode: string, templateParams?: TealTemplateParams) {\n return AppManager.replaceTealTemplateParams(tealCode, templateParams)\n}\n\n/**\n * @deprecated Use `algorand.appManager.compileTealTemplate` instead.\n *\n * Performs template substitution of a teal file and compiles it, returning the compiled result.\n *\n * Looks for `TMPL_{parameter}` for template replacements.\n *\n * @param tealCode The TEAL logic to compile\n * @param algod An algod client\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 */\nexport async function performTemplateSubstitutionAndCompile(\n tealCode: string,\n algod: Algodv2,\n templateParams?: TealTemplateParams,\n deploymentMetadata?: AppDeployMetadata,\n): Promise<CompiledTeal> {\n tealCode = stripTealComments(tealCode)\n\n tealCode = performTemplateSubstitution(tealCode, templateParams)\n\n if (deploymentMetadata) {\n tealCode = replaceDeployTimeControlParams(tealCode, deploymentMetadata)\n }\n\n return await compileTeal(tealCode, algod)\n}\n\n/**\n * @deprecated Use `AppManager.stripTealComments` instead.\n *\n * Remove comments from TEAL Code\n *\n * @param tealCode The TEAL logic to compile\n * @returns The TEAL without comments\n */\nexport function stripTealComments(tealCode: string) {\n return AppManager.stripTealComments(tealCode)\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAgCA;;;;;;;;;;;;;;;;AAgBG;AACI,eAAe,SAAS,CAC7B,UAA+B,EAC/B,KAAc,EACd,OAAiB,EAAA;AAejB,IAAA,MAAM,UAAU,GAAG,IAAI,UAAU,CAAC,KAAK,CAAC,CAAA;AACxC,IAAA,MAAM,QAAQ,GAAG,MACf,IAAI,mBAAmB,CAAC;QACtB,KAAK;QACL,SAAS,EAAE,MAAM,0BAA0B,CAAC,UAAU,CAAC,IAAI,CAAC;QAC5D,kBAAkB,EAAE,YAClB,UAAU,CAAC,iBAAiB,GAAG,EAAE,GAAG,UAAU,CAAC,iBAAiB,EAAE,GAAG,MAAM,KAAK,CAAC,oBAAoB,EAAE,CAAC,EAAE,EAAE;QAC9G,UAAU;AACX,KAAA,CAAC,CAAA;IACJ,MAAM,QAAQ,GAAG,IAAI,WAAW,CAC9B,UAAU,EACV,IAAI,+BAA+B,CAAC,QAAQ,EAAE,IAAI,YAAY,CAAC,KAAK,EAAE,QAAQ,CAAC,EAAE,UAAU,CAAC,EAC5F,OAAO,CACR,CAAA;AAED,IAAA,MAAM,YAAY,GAAG;QACnB,eAAe,EAAE,UAAU,CAAC,eAAe;QAC3C,iBAAiB,EAAE,UAAU,CAAC,iBAAiB;AAC/C,QAAA,MAAM,EAAE,gBAAgB,CAAC,UAAU,CAAC,IAAI,CAAC;AACzC,QAAA,iBAAiB,EAAE,UAAU,CAAC,UAAU,EAAE,QAAQ,EAAE,GAAG,CAAC,CAAC,CAAC,MAAM,OAAO,CAAC,KAAK,QAAQ,GAAG,CAAC,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC;AAChI,QAAA,a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;KACZ,CAAA;AACH,CAAC;AAED;;;;;;;;;;;;;;AAcG;AACa,SAAA,8BAA8B,CAAC,QAAgB,EAAE,MAAoD,EAAA;IACnH,OAAO,UAAU,CAAC,0CAA0C,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAA;AAChF,CAAC;AAED;;;;;;;;;;AAUG;AACa,SAAA,2BAA2B,CAAC,QAAgB,EAAE,cAAmC,EAAA;IAC/F,OAAO,UAAU,CAAC,yBAAyB,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAA;AACvE,CAAC;AAED;;;;;;;;;;;;AAYG;AACI,eAAe,qCAAqC,CACzD,QAAgB,EAChB,KAAc,EACd,cAAmC,EACnC,kBAAsC,EAAA;AAEtC,IAAA,QAAQ,GAAG,iBAAiB,CAAC,QAAQ,CAAC,CAAA;AAEtC,IAAA,QAAQ,GAAG,2BAA2B,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAA;IAEhE,IAAI,kBAAkB,EAAE;AACtB,QAAA,QAAQ,GAAG,8BAA8B,CAAC,QAAQ,EAAE,kBAAkB,CAAC,CAAA;KACxE;AAED,IAAA,OAAO,MAAM,WAAW,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAA;AAC3C,CAAC;AAED;;;;;;;AAOG;AACG,SAAU,iBAAiB,CAAC,QAAgB,EAAA;AAChD,IAAA,OAAO,UAAU,CAAC,iBAAiB,CAAC,QAAQ,CAAC,CAAA;AAC/C;;;;"}
package/package.json CHANGED
@@ -6,7 +6,7 @@
6
6
  "**"
7
7
  ],
8
8
  "name": "@algorandfoundation/algokit-utils",
9
- "version": "7.0.0-beta.21",
9
+ "version": "7.0.0-beta.22",
10
10
  "private": false,
11
11
  "description": "A set of core Algorand utilities written in TypeScript and released via npm that make it easier to build solutions on Algorand.",
12
12
  "author": "Algorand Foundation",
@@ -93,7 +93,7 @@ export interface Arc56Contract {
93
93
  * The key is the base64 genesis hash of the network, and the value contains
94
94
  * information about the deployed contract in the network indicated by the
95
95
  * key. A key containing the human-readable name of the network MAY be
96
- * included, but the corresponding genesis hash key MUST also be define
96
+ * included, but the corresponding genesis hash key MUST also be defined
97
97
  */
98
98
  networks?: {
99
99
  [network: string]: {
@@ -101,7 +101,7 @@ export interface Arc56Contract {
101
101
  appID: number;
102
102
  };
103
103
  };
104
- /** Named structs use by the application. Each struct field appears in the same order as ABI encoding. */
104
+ /** Named structs used by the application. Each struct field appears in the same order as ABI encoding. */
105
105
  structs: {
106
106
  [structName: StructName]: StructField[];
107
107
  };
@@ -186,12 +186,12 @@ export interface Arc56Contract {
186
186
  };
187
187
  /** ARC-28 events that MAY be emitted by this contract */
188
188
  events?: Array<Event>;
189
- /** A mapping of template variable names as they appear in the teal (not including TMPL_ prefix) to their respective types and values (if applicable) */
189
+ /** A mapping of template variable names as they appear in the TEAL (not including TMPL_ prefix) to their respective types and values (if applicable) */
190
190
  templateVariables?: {
191
191
  [name: string]: {
192
192
  /** The type of the template variable */
193
193
  type: ABIType | AVMType | StructName;
194
- /** If given, the the base64 encoded value used for the given app/program */
194
+ /** If given, the base64 encoded value used for the given app/program */
195
195
  value?: string;
196
196
  };
197
197
  };
@@ -1 +1 @@
1
- {"version":3,"file":"app-arc56.js","sources":["../../src/types/app-arc56.ts"],"sourcesContent":["import algosdk from 'algosdk'\nimport { ABIReturn } from './app'\nimport { Expand } from './expand'\n\n/** Type to describe an argument within an `Arc56Method`. */\nexport type Arc56MethodArg = Expand<\n Omit<Method['args'][number], 'type'> & {\n type: algosdk.ABIArgumentType\n }\n>\n\n/** Type to describe a return type within an `Arc56Method`. */\nexport type Arc56MethodReturnType = Expand<\n Omit<Method['returns'], 'type'> & {\n type: algosdk.ABIReturnType\n }\n>\n\n/**\n * Wrapper around `algosdk.ABIMethod` that represents an ARC-56 ABI method.\n */\nexport class Arc56Method extends algosdk.ABIMethod {\n override readonly args: Array<Arc56MethodArg>\n override readonly returns: Arc56MethodReturnType\n\n constructor(public method: Method) {\n super(method)\n this.args = method.args.map((arg) => ({\n ...arg,\n type: algosdk.abiTypeIsTransaction(arg.type) || algosdk.abiTypeIsReference(arg.type) ? arg.type : algosdk.ABIType.from(arg.type),\n }))\n this.returns = {\n ...this.method.returns,\n type: this.method.returns.type === 'void' ? 'void' : algosdk.ABIType.from(this.method.returns.type),\n }\n }\n\n override toJSON(): Method {\n return this.method\n }\n}\n\n/**\n * Returns the `ABITupleType` for the given ARC-56 struct definition\n * @param struct The ARC-56 struct definition\n * @returns The `ABITupleType`\n */\nexport function getABITupleTypeFromABIStructDefinition(\n struct: StructField[],\n structs: Record<string, StructField[]>,\n): algosdk.ABITupleType {\n return new algosdk.ABITupleType(\n struct.map((v) =>\n typeof v.type === 'string'\n ? structs[v.type]\n ? getABITupleTypeFromABIStructDefinition(structs[v.type], structs)\n : algosdk.ABIType.from(v.type)\n : getABITupleTypeFromABIStructDefinition(v.type, structs),\n ),\n )\n}\n\n/**\n * Converts a decoded ABI tuple as a struct.\n * @param decodedABITuple The decoded ABI tuple value\n * @param structFields The struct fields from an ARC-56 app spec\n * @returns The struct as a Record<string, any>\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getABIStructFromABITuple<TReturn extends ABIStruct = Record<string, any>>(\n decodedABITuple: algosdk.ABIValue[],\n structFields: StructField[],\n structs: Record<string, StructField[]>,\n): TReturn {\n return Object.fromEntries(\n structFields.map(({ name: key, type }, i) => {\n const abiValue = decodedABITuple[i]\n return [\n key,\n (typeof type === 'string' && !structs[type]) || !Array.isArray(abiValue)\n ? decodedABITuple[i]\n : getABIStructFromABITuple(abiValue, typeof type === 'string' ? structs[type] : type, structs),\n ]\n }),\n ) as TReturn\n}\n\n/**\n * Converts an ARC-56 struct as an ABI tuple.\n * @param struct The struct to convert\n * @param structFields The struct fields from an ARC-56 app spec\n * @returns The struct as a decoded ABI tuple\n */\nexport function getABITupleFromABIStruct(\n struct: ABIStruct,\n structFields: StructField[],\n structs: Record<string, StructField[]>,\n): algosdk.ABIValue[] {\n return structFields.map(({ name: key, type }) => {\n const value = struct[key]\n return typeof type === 'string' && !structs[type]\n ? (value as algosdk.ABIValue)\n : getABITupleFromABIStruct(value as ABIStruct, typeof type === 'string' ? structs[type] : type, structs)\n })\n}\n\n/** Decoded ARC-56 struct as a struct rather than a tuple. */\nexport type ABIStruct = {\n [key: string]: ABIStruct | algosdk.ABIValue\n}\n\n/**\n * Returns the decoded ABI value (or struct for a struct type)\n * for the given raw Algorand value given an ARC-56 type and defined ARC-56 structs.\n * @param value The raw Algorand value (bytes or uint64)\n * @param type The ARC-56 type - either an ABI Type string or a struct name\n * @param structs The defined ARC-56 structs\n * @returns The decoded ABI value or struct\n */\nexport function getABIDecodedValue(\n value: Uint8Array | number | bigint,\n type: string,\n structs: Record<string, StructField[]>,\n): algosdk.ABIValue | ABIStruct {\n if (type === 'AVMBytes' || typeof value !== 'object') return value\n if (type === 'AVMString') return Buffer.from(value).toString('utf-8')\n if (type === 'AVMUint64') return algosdk.ABIType.from('uint64').decode(value)\n if (structs[type]) {\n const tupleValue = getABITupleTypeFromABIStructDefinition(structs[type], structs).decode(value)\n return getABIStructFromABITuple(tupleValue, structs[type], structs)\n }\n return algosdk.ABIType.from(type).decode(value)\n}\n\n/**\n * Returns the ABI-encoded value for the given value.\n * @param value The value to encode either already in encoded binary form (`Uint8Array`), a decoded ABI value or an ARC-56 struct\n * @param type The ARC-56 type - either an ABI Type string or a struct name\n * @param structs The defined ARC-56 structs\n * @returns The binary ABI-encoded value\n */\nexport function getABIEncodedValue(\n value: Uint8Array | algosdk.ABIValue | ABIStruct,\n type: string,\n structs: Record<string, StructField[]>,\n): Uint8Array {\n if (typeof value === 'object' && value instanceof Uint8Array) return value\n if (type === 'AVMUint64') return algosdk.ABIType.from('uint64').encode(value as bigint | number)\n if (type === 'AVMBytes' || type === 'AVMString') {\n if (typeof value === 'string') return Buffer.from(value, 'utf-8')\n if (typeof value !== 'object' || !(value instanceof Uint8Array)) throw new Error(`Expected bytes value for ${type}, but got ${value}`)\n return value\n }\n if (structs[type]) {\n const tupleType = getABITupleTypeFromABIStructDefinition(structs[type], structs)\n if (Array.isArray(value)) {\n tupleType.encode(value as algosdk.ABIValue[])\n } else {\n return tupleType.encode(getABITupleFromABIStruct(value as ABIStruct, structs[type], structs))\n }\n }\n return algosdk.ABIType.from(type).encode(value as algosdk.ABIValue)\n}\n\n/**\n * Returns the ARC-56 ABI method object for a given method name or signature and ARC-56 app spec.\n * @param methodNameOrSignature The method name or method signature to call if an ABI call is being emitted.\n * e.g. `my_method` or `my_method(unit64,string)bytes`\n * @param appSpec The app spec for the app\n * @returns The `Arc56Method`\n */\nexport function getArc56Method(methodNameOrSignature: string, appSpec: Arc56Contract): Arc56Method {\n let method: Method\n if (!methodNameOrSignature.includes('(')) {\n const methods = appSpec.methods.filter((m) => m.name === methodNameOrSignature)\n if (methods.length === 0) throw new Error(`Unable to find method ${methodNameOrSignature} in ${appSpec.name} app.`)\n if (methods.length > 1) {\n throw new Error(\n `Received a call to method ${methodNameOrSignature} in contract ${\n appSpec.name\n }, but this resolved to multiple methods; please pass in an ABI signature instead: ${appSpec.methods\n .map((m) => new algosdk.ABIMethod(m).getSignature())\n .join(', ')}`,\n )\n }\n method = methods[0]\n } else {\n const m = appSpec.methods.find((m) => new algosdk.ABIMethod(m).getSignature() === methodNameOrSignature)\n if (!m) throw new Error(`Unable to find method ${methodNameOrSignature} in ${appSpec.name} app.`)\n method = m\n }\n return new Arc56Method(method)\n}\n\n/**\n * Checks for decode errors on the AppCallTransactionResult and maps the return value to the specified generic type\n *\n * @param returnValue The smart contract response\n * @param method The method that was called\n * @param structs The struct fields from the app spec\n * @returns The smart contract response with an updated return value\n */\nexport function getArc56ReturnValue<TReturn extends Uint8Array | algosdk.ABIValue | ABIStruct | undefined>(\n returnValue: ABIReturn | undefined,\n method: Method | Arc56Method,\n structs: Record<string, StructField[]>,\n): TReturn {\n const m = 'method' in method ? method.method : method\n const type = m.returns.struct ?? m.returns.type\n if (returnValue?.decodeError) {\n throw returnValue.decodeError\n }\n if (type === undefined || type === 'void' || returnValue?.returnValue === undefined) return undefined as TReturn\n\n if (type === 'AVMBytes') return returnValue.rawReturnValue as TReturn\n if (type === 'AVMString') return Buffer.from(returnValue.rawReturnValue).toString('utf-8') as TReturn\n if (type === 'AVMUint64') return algosdk.ABIType.from('uint64').decode(returnValue.rawReturnValue) as TReturn\n\n if (structs[type]) {\n return getABIStructFromABITuple(returnValue.returnValue as algosdk.ABIValue[], structs[type], structs) as TReturn\n }\n\n return returnValue.returnValue as TReturn\n}\n\n/****************/\n/** ARC-56 spec */\n/****************/\n\n/** Describes the entire contract. This interface is an extension of the interface described in ARC-4 */\nexport interface Arc56Contract {\n /** The ARCs used and/or supported by this contract. All contracts implicitly support ARC4 and ARC56 */\n arcs: number[]\n /** A user-friendly name for the contract */\n name: string\n /** Optional, user-friendly description for the interface */\n desc?: string\n /**\n * Optional object listing the contract instances across different networks.\n * The key is the base64 genesis hash of the network, and the value contains\n * information about the deployed contract in the network indicated by the\n * key. A key containing the human-readable name of the network MAY be\n * included, but the corresponding genesis hash key MUST also be define\n */\n networks?: {\n [network: string]: {\n /** The app ID of the deployed contract in this network */\n appID: number\n }\n }\n /** Named structs use by the application. Each struct field appears in the same order as ABI encoding. */\n structs: { [structName: StructName]: StructField[] }\n /** All of the methods that the contract implements */\n methods: Method[]\n state: {\n /** Defines the values that should be used for GlobalNumUint, GlobalNumByteSlice, LocalNumUint, and LocalNumByteSlice when creating the application */\n schema: {\n global: {\n ints: number\n bytes: number\n }\n local: {\n ints: number\n bytes: number\n }\n }\n /** Mapping of human-readable names to StorageKey objects */\n keys: {\n global: { [name: string]: StorageKey }\n local: { [name: string]: StorageKey }\n box: { [name: string]: StorageKey }\n }\n /** Mapping of human-readable names to StorageMap objects */\n maps: {\n global: { [name: string]: StorageMap }\n local: { [name: string]: StorageMap }\n box: { [name: string]: StorageMap }\n }\n }\n /** Supported bare actions for the contract. An action is a combination of call/create and an OnComplete */\n bareActions: {\n /** OnCompletes this method allows when appID === 0 */\n create: ('NoOp' | 'OptIn' | 'DeleteApplication')[]\n /** OnCompletes this method allows when appID !== 0 */\n call: ('NoOp' | 'OptIn' | 'CloseOut' | 'ClearState' | 'UpdateApplication' | 'DeleteApplication')[]\n }\n /** Information about the TEAL programs */\n sourceInfo?: {\n /** Approval program information */\n approval: ProgramSourceInfo\n /** Clear program information */\n clear: ProgramSourceInfo\n }\n /** The pre-compiled TEAL that may contain template variables. MUST be omitted if included as part of ARC23 */\n source?: {\n /** The approval program */\n approval: string\n /** The clear program */\n clear: string\n }\n /** The compiled bytecode for the application. MUST be omitted if included as part of ARC23 */\n byteCode?: {\n /** The approval program */\n approval: string\n /** The clear program */\n clear: string\n }\n /** Information used to get the given byteCode and/or PC values in sourceInfo. MUST be given if byteCode or PC values are present */\n compilerInfo?: {\n /** The name of the compiler */\n compiler: 'algod' | 'puya'\n /** Compiler version information */\n compilerVersion: {\n major: number\n minor: number\n patch: number\n commitHash?: string\n }\n }\n /** ARC-28 events that MAY be emitted by this contract */\n events?: Array<Event>\n /** A mapping of template variable names as they appear in the teal (not including TMPL_ prefix) to their respective types and values (if applicable) */\n templateVariables?: {\n [name: string]: {\n /** The type of the template variable */\n type: ABIType | AVMType | StructName\n /** If given, the the base64 encoded value used for the given app/program */\n value?: string\n }\n }\n /** The scratch variables used during runtime */\n scratchVariables?: {\n [name: string]: {\n slot: number\n type: ABIType | AVMType | StructName\n }\n }\n}\n\n/** Describes a method in the contract. This interface is an extension of the interface described in ARC-4 */\nexport interface Method {\n /** The name of the method */\n name: string\n /** Optional, user-friendly description for the method */\n desc?: string\n /** The arguments of the method, in order */\n args: Array<{\n /** The type of the argument. The `struct` field should also be checked to determine if this arg is a struct. */\n type: ABIType\n /** If the type is a struct, the name of the struct */\n struct?: StructName\n /** Optional, user-friendly name for the argument */\n name?: string\n /** Optional, user-friendly description for the argument */\n desc?: string\n /** The default value that clients should use. */\n defaultValue?: {\n /** Base64 encoded bytes, base64 ARC4 encoded uint64, or UTF-8 method selector */\n data: string\n /** How the data is encoded. This is the encoding for the data provided here, not the arg type */\n type?: ABIType | AVMType\n /** Where the default value is coming from\n * - box: The data key signifies the box key to read the value from\n * - global: The data key signifies the global state key to read the value from\n * - local: The data key signifies the local state key to read the value from (for the sender)\n * - literal: the value is a literal and should be passed directly as the argument\n * - method: The utf8 signature of the method in this contract to call to get the default value. If the method has arguments, they all must have default values. The method **MUST** be readonly so simulate can be used to get the default value\n */\n source: 'box' | 'global' | 'local' | 'literal' | 'method'\n }\n }>\n /** Information about the method's return value */\n returns: {\n /** The type of the return value, or \"void\" to indicate no return value. The `struct` field should also be checked to determine if this return value is a struct. */\n type: ABIType\n /** If the type is a struct, the name of the struct */\n struct?: StructName\n /** Optional, user-friendly description for the return value */\n desc?: string\n }\n /** an action is a combination of call/create and an OnComplete */\n actions: {\n /** OnCompletes this method allows when appID === 0 */\n create: ('NoOp' | 'OptIn' | 'DeleteApplication')[]\n /** OnCompletes this method allows when appID !== 0 */\n call: ('NoOp' | 'OptIn' | 'CloseOut' | 'ClearState' | 'UpdateApplication' | 'DeleteApplication')[]\n }\n /** If this method does not write anything to the ledger (ARC-22) */\n readonly?: boolean\n /** ARC-28 events that MAY be emitted by this method */\n events?: Array<Event>\n /** Information that clients can use when calling the method */\n recommendations?: {\n /** The number of inner transactions the caller should cover the fees for */\n innerTransactionCount?: number\n /** Recommended box references to include */\n boxes?: {\n /** The app ID for the box */\n app?: number\n /** The base64 encoded box key */\n key: string\n /** The number of bytes being read from the box */\n readBytes: number\n /** The number of bytes being written to the box */\n writeBytes: number\n }\n /** Recommended foreign accounts */\n accounts?: string[]\n /** Recommended foreign apps */\n apps?: number[]\n /** Recommended foreign assets */\n assets?: number[]\n }\n}\n\n/** ARC-28 event */\nexport interface Event {\n /** The name of the event */\n name: string\n /** Optional, user-friendly description for the event */\n desc?: string\n /** The arguments of the event, in order */\n args: Array<{\n /** The type of the argument. The `struct` field should also be checked to determine if this arg is a struct. */\n type: ABIType\n /** Optional, user-friendly name for the argument */\n name?: string\n /** Optional, user-friendly description for the argument */\n desc?: string\n /** If the type is a struct, the name of the struct */\n struct?: StructName\n }>\n}\n\n/** An ABI-encoded type */\nexport type ABIType = string\n\n/** The name of a defined struct */\nexport type StructName = string\n\n/** Raw byteslice without the length prefixed that is specified in ARC-4 */\nexport type AVMBytes = 'AVMBytes'\n\n/** A utf-8 string without the length prefix that is specified in ARC-4 */\nexport type AVMString = 'AVMString'\n\n/** A 64-bit unsigned integer */\nexport type AVMUint64 = 'AVMUint64'\n\n/** A native AVM type */\nexport type AVMType = AVMBytes | AVMString | AVMUint64\n\n/** Information about a single field in a struct */\nexport interface StructField {\n /** The name of the struct field */\n name: string\n /** The type of the struct field's value */\n type: ABIType | StructName | StructField[]\n}\n\n/** Describes a single key in app storage */\nexport interface StorageKey {\n /** Description of what this storage key holds */\n desc?: string\n /** The type of the key */\n keyType: ABIType | AVMType | StructName\n\n /** The type of the value */\n valueType: ABIType | AVMType | StructName\n /** The bytes of the key encoded as base64 */\n key: string\n}\n\n/** Describes a mapping of key-value pairs in storage */\nexport interface StorageMap {\n /** Description of what the key-value pairs in this mapping hold */\n desc?: string\n /** The type of the keys in the map */\n keyType: ABIType | AVMType | StructName\n /** The type of the values in the map */\n valueType: ABIType | AVMType | StructName\n /** The base64-encoded prefix of the map keys*/\n prefix?: string\n}\n\ninterface SourceInfo {\n /** The program counter value(s). Could be offset if pcOffsetMethod is not \"none\" */\n pc: Array<number>\n /** A human-readable string that describes the error when the program fails at the given PC */\n errorMessage?: string\n /** The TEAL line number that corresponds to the given PC. RECOMMENDED to be used for development purposes, but not required for clients */\n teal?: number\n /** The original source file and line number that corresponds to the given PC. RECOMMENDED to be used for development purposes, but not required for clients */\n source?: string\n}\n\nexport interface ProgramSourceInfo {\n /** The source information for the program */\n sourceInfo: SourceInfo[]\n /** How the program counter offset is calculated\n * - none: The pc values in sourceInfo are not offset\n * - cblocks: The pc values in sourceInfo are offset by the PC of the first op following the last cblock at the top of the program\n */\n pcOffsetMethod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C5B,MAAM,WAAW,CAAC,WAAW,CAAA;KAC9B;AACD,IAAA,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,MAAM,IAAI,WAAW,EAAE,WAAW,KAAK,SAAS;AAAE,QAAA,OAAO,SAAoB,CAAA;IAEhH,IAAI,IAAI,KAAK,UAAU;QAAE,OAAO,WAAW,CAAC,cAAyB,CAAA;IACrE,IAAI,IAAI,KAAK,WAAW;AAAE,QAAA,OAAO,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAY,CAAA;IACrG,IAAI,IAAI,KAAK,WAAW;AAAE,QAAA,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,cAAc,CAAY,CAAA;AAE7G,IAAA,IAAI,OAAO,CAAC,IAAI,CAAC,EAAE;AACjB,QAAA,OAAO,wBAAwB,CAAC,WAAW,CAAC,WAAiC,EAAE,OAAO,CAAC,IAAI,CAAC,EAAE,OAAO,CAAY,CAAA;KAClH;IAED,OAAO,WAAW,CAAC,WAAsB,CAAA;AAC3C;;;;;;;;;;;"}
1
+ {"version":3,"file":"app-arc56.js","sources":["../../src/types/app-arc56.ts"],"sourcesContent":["import algosdk from 'algosdk'\nimport { ABIReturn } from './app'\nimport { Expand } from './expand'\n\n/** Type to describe an argument within an `Arc56Method`. */\nexport type Arc56MethodArg = Expand<\n Omit<Method['args'][number], 'type'> & {\n type: algosdk.ABIArgumentType\n }\n>\n\n/** Type to describe a return type within an `Arc56Method`. */\nexport type Arc56MethodReturnType = Expand<\n Omit<Method['returns'], 'type'> & {\n type: algosdk.ABIReturnType\n }\n>\n\n/**\n * Wrapper around `algosdk.ABIMethod` that represents an ARC-56 ABI method.\n */\nexport class Arc56Method extends algosdk.ABIMethod {\n override readonly args: Array<Arc56MethodArg>\n override readonly returns: Arc56MethodReturnType\n\n constructor(public method: Method) {\n super(method)\n this.args = method.args.map((arg) => ({\n ...arg,\n type: algosdk.abiTypeIsTransaction(arg.type) || algosdk.abiTypeIsReference(arg.type) ? arg.type : algosdk.ABIType.from(arg.type),\n }))\n this.returns = {\n ...this.method.returns,\n type: this.method.returns.type === 'void' ? 'void' : algosdk.ABIType.from(this.method.returns.type),\n }\n }\n\n override toJSON(): Method {\n return this.method\n }\n}\n\n/**\n * Returns the `ABITupleType` for the given ARC-56 struct definition\n * @param struct The ARC-56 struct definition\n * @returns The `ABITupleType`\n */\nexport function getABITupleTypeFromABIStructDefinition(\n struct: StructField[],\n structs: Record<string, StructField[]>,\n): algosdk.ABITupleType {\n return new algosdk.ABITupleType(\n struct.map((v) =>\n typeof v.type === 'string'\n ? structs[v.type]\n ? getABITupleTypeFromABIStructDefinition(structs[v.type], structs)\n : algosdk.ABIType.from(v.type)\n : getABITupleTypeFromABIStructDefinition(v.type, structs),\n ),\n )\n}\n\n/**\n * Converts a decoded ABI tuple as a struct.\n * @param decodedABITuple The decoded ABI tuple value\n * @param structFields The struct fields from an ARC-56 app spec\n * @returns The struct as a Record<string, any>\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getABIStructFromABITuple<TReturn extends ABIStruct = Record<string, any>>(\n decodedABITuple: algosdk.ABIValue[],\n structFields: StructField[],\n structs: Record<string, StructField[]>,\n): TReturn {\n return Object.fromEntries(\n structFields.map(({ name: key, type }, i) => {\n const abiValue = decodedABITuple[i]\n return [\n key,\n (typeof type === 'string' && !structs[type]) || !Array.isArray(abiValue)\n ? decodedABITuple[i]\n : getABIStructFromABITuple(abiValue, typeof type === 'string' ? structs[type] : type, structs),\n ]\n }),\n ) as TReturn\n}\n\n/**\n * Converts an ARC-56 struct as an ABI tuple.\n * @param struct The struct to convert\n * @param structFields The struct fields from an ARC-56 app spec\n * @returns The struct as a decoded ABI tuple\n */\nexport function getABITupleFromABIStruct(\n struct: ABIStruct,\n structFields: StructField[],\n structs: Record<string, StructField[]>,\n): algosdk.ABIValue[] {\n return structFields.map(({ name: key, type }) => {\n const value = struct[key]\n return typeof type === 'string' && !structs[type]\n ? (value as algosdk.ABIValue)\n : getABITupleFromABIStruct(value as ABIStruct, typeof type === 'string' ? structs[type] : type, structs)\n })\n}\n\n/** Decoded ARC-56 struct as a struct rather than a tuple. */\nexport type ABIStruct = {\n [key: string]: ABIStruct | algosdk.ABIValue\n}\n\n/**\n * Returns the decoded ABI value (or struct for a struct type)\n * for the given raw Algorand value given an ARC-56 type and defined ARC-56 structs.\n * @param value The raw Algorand value (bytes or uint64)\n * @param type The ARC-56 type - either an ABI Type string or a struct name\n * @param structs The defined ARC-56 structs\n * @returns The decoded ABI value or struct\n */\nexport function getABIDecodedValue(\n value: Uint8Array | number | bigint,\n type: string,\n structs: Record<string, StructField[]>,\n): algosdk.ABIValue | ABIStruct {\n if (type === 'AVMBytes' || typeof value !== 'object') return value\n if (type === 'AVMString') return Buffer.from(value).toString('utf-8')\n if (type === 'AVMUint64') return algosdk.ABIType.from('uint64').decode(value)\n if (structs[type]) {\n const tupleValue = getABITupleTypeFromABIStructDefinition(structs[type], structs).decode(value)\n return getABIStructFromABITuple(tupleValue, structs[type], structs)\n }\n return algosdk.ABIType.from(type).decode(value)\n}\n\n/**\n * Returns the ABI-encoded value for the given value.\n * @param value The value to encode either already in encoded binary form (`Uint8Array`), a decoded ABI value or an ARC-56 struct\n * @param type The ARC-56 type - either an ABI Type string or a struct name\n * @param structs The defined ARC-56 structs\n * @returns The binary ABI-encoded value\n */\nexport function getABIEncodedValue(\n value: Uint8Array | algosdk.ABIValue | ABIStruct,\n type: string,\n structs: Record<string, StructField[]>,\n): Uint8Array {\n if (typeof value === 'object' && value instanceof Uint8Array) return value\n if (type === 'AVMUint64') return algosdk.ABIType.from('uint64').encode(value as bigint | number)\n if (type === 'AVMBytes' || type === 'AVMString') {\n if (typeof value === 'string') return Buffer.from(value, 'utf-8')\n if (typeof value !== 'object' || !(value instanceof Uint8Array)) throw new Error(`Expected bytes value for ${type}, but got ${value}`)\n return value\n }\n if (structs[type]) {\n const tupleType = getABITupleTypeFromABIStructDefinition(structs[type], structs)\n if (Array.isArray(value)) {\n tupleType.encode(value as algosdk.ABIValue[])\n } else {\n return tupleType.encode(getABITupleFromABIStruct(value as ABIStruct, structs[type], structs))\n }\n }\n return algosdk.ABIType.from(type).encode(value as algosdk.ABIValue)\n}\n\n/**\n * Returns the ARC-56 ABI method object for a given method name or signature and ARC-56 app spec.\n * @param methodNameOrSignature The method name or method signature to call if an ABI call is being emitted.\n * e.g. `my_method` or `my_method(unit64,string)bytes`\n * @param appSpec The app spec for the app\n * @returns The `Arc56Method`\n */\nexport function getArc56Method(methodNameOrSignature: string, appSpec: Arc56Contract): Arc56Method {\n let method: Method\n if (!methodNameOrSignature.includes('(')) {\n const methods = appSpec.methods.filter((m) => m.name === methodNameOrSignature)\n if (methods.length === 0) throw new Error(`Unable to find method ${methodNameOrSignature} in ${appSpec.name} app.`)\n if (methods.length > 1) {\n throw new Error(\n `Received a call to method ${methodNameOrSignature} in contract ${\n appSpec.name\n }, but this resolved to multiple methods; please pass in an ABI signature instead: ${appSpec.methods\n .map((m) => new algosdk.ABIMethod(m).getSignature())\n .join(', ')}`,\n )\n }\n method = methods[0]\n } else {\n const m = appSpec.methods.find((m) => new algosdk.ABIMethod(m).getSignature() === methodNameOrSignature)\n if (!m) throw new Error(`Unable to find method ${methodNameOrSignature} in ${appSpec.name} app.`)\n method = m\n }\n return new Arc56Method(method)\n}\n\n/**\n * Checks for decode errors on the AppCallTransactionResult and maps the return value to the specified generic type\n *\n * @param returnValue The smart contract response\n * @param method The method that was called\n * @param structs The struct fields from the app spec\n * @returns The smart contract response with an updated return value\n */\nexport function getArc56ReturnValue<TReturn extends Uint8Array | algosdk.ABIValue | ABIStruct | undefined>(\n returnValue: ABIReturn | undefined,\n method: Method | Arc56Method,\n structs: Record<string, StructField[]>,\n): TReturn {\n const m = 'method' in method ? method.method : method\n const type = m.returns.struct ?? m.returns.type\n if (returnValue?.decodeError) {\n throw returnValue.decodeError\n }\n if (type === undefined || type === 'void' || returnValue?.returnValue === undefined) return undefined as TReturn\n\n if (type === 'AVMBytes') return returnValue.rawReturnValue as TReturn\n if (type === 'AVMString') return Buffer.from(returnValue.rawReturnValue).toString('utf-8') as TReturn\n if (type === 'AVMUint64') return algosdk.ABIType.from('uint64').decode(returnValue.rawReturnValue) as TReturn\n\n if (structs[type]) {\n return getABIStructFromABITuple(returnValue.returnValue as algosdk.ABIValue[], structs[type], structs) as TReturn\n }\n\n return returnValue.returnValue as TReturn\n}\n\n/****************/\n/** ARC-56 spec */\n/****************/\n\n/** Describes the entire contract. This interface is an extension of the interface described in ARC-4 */\nexport interface Arc56Contract {\n /** The ARCs used and/or supported by this contract. All contracts implicitly support ARC4 and ARC56 */\n arcs: number[]\n /** A user-friendly name for the contract */\n name: string\n /** Optional, user-friendly description for the interface */\n desc?: string\n /**\n * Optional object listing the contract instances across different networks.\n * The key is the base64 genesis hash of the network, and the value contains\n * information about the deployed contract in the network indicated by the\n * key. A key containing the human-readable name of the network MAY be\n * included, but the corresponding genesis hash key MUST also be defined\n */\n networks?: {\n [network: string]: {\n /** The app ID of the deployed contract in this network */\n appID: number\n }\n }\n /** Named structs used by the application. Each struct field appears in the same order as ABI encoding. */\n structs: { [structName: StructName]: StructField[] }\n /** All of the methods that the contract implements */\n methods: Method[]\n state: {\n /** Defines the values that should be used for GlobalNumUint, GlobalNumByteSlice, LocalNumUint, and LocalNumByteSlice when creating the application */\n schema: {\n global: {\n ints: number\n bytes: number\n }\n local: {\n ints: number\n bytes: number\n }\n }\n /** Mapping of human-readable names to StorageKey objects */\n keys: {\n global: { [name: string]: StorageKey }\n local: { [name: string]: StorageKey }\n box: { [name: string]: StorageKey }\n }\n /** Mapping of human-readable names to StorageMap objects */\n maps: {\n global: { [name: string]: StorageMap }\n local: { [name: string]: StorageMap }\n box: { [name: string]: StorageMap }\n }\n }\n /** Supported bare actions for the contract. An action is a combination of call/create and an OnComplete */\n bareActions: {\n /** OnCompletes this method allows when appID === 0 */\n create: ('NoOp' | 'OptIn' | 'DeleteApplication')[]\n /** OnCompletes this method allows when appID !== 0 */\n call: ('NoOp' | 'OptIn' | 'CloseOut' | 'ClearState' | 'UpdateApplication' | 'DeleteApplication')[]\n }\n /** Information about the TEAL programs */\n sourceInfo?: {\n /** Approval program information */\n approval: ProgramSourceInfo\n /** Clear program information */\n clear: ProgramSourceInfo\n }\n /** The pre-compiled TEAL that may contain template variables. MUST be omitted if included as part of ARC23 */\n source?: {\n /** The approval program */\n approval: string\n /** The clear program */\n clear: string\n }\n /** The compiled bytecode for the application. MUST be omitted if included as part of ARC23 */\n byteCode?: {\n /** The approval program */\n approval: string\n /** The clear program */\n clear: string\n }\n /** Information used to get the given byteCode and/or PC values in sourceInfo. MUST be given if byteCode or PC values are present */\n compilerInfo?: {\n /** The name of the compiler */\n compiler: 'algod' | 'puya'\n /** Compiler version information */\n compilerVersion: {\n major: number\n minor: number\n patch: number\n commitHash?: string\n }\n }\n /** ARC-28 events that MAY be emitted by this contract */\n events?: Array<Event>\n /** A mapping of template variable names as they appear in the TEAL (not including TMPL_ prefix) to their respective types and values (if applicable) */\n templateVariables?: {\n [name: string]: {\n /** The type of the template variable */\n type: ABIType | AVMType | StructName\n /** If given, the base64 encoded value used for the given app/program */\n value?: string\n }\n }\n /** The scratch variables used during runtime */\n scratchVariables?: {\n [name: string]: {\n slot: number\n type: ABIType | AVMType | StructName\n }\n }\n}\n\n/** Describes a method in the contract. This interface is an extension of the interface described in ARC-4 */\nexport interface Method {\n /** The name of the method */\n name: string\n /** Optional, user-friendly description for the method */\n desc?: string\n /** The arguments of the method, in order */\n args: Array<{\n /** The type of the argument. The `struct` field should also be checked to determine if this arg is a struct. */\n type: ABIType\n /** If the type is a struct, the name of the struct */\n struct?: StructName\n /** Optional, user-friendly name for the argument */\n name?: string\n /** Optional, user-friendly description for the argument */\n desc?: string\n /** The default value that clients should use. */\n defaultValue?: {\n /** Base64 encoded bytes, base64 ARC4 encoded uint64, or UTF-8 method selector */\n data: string\n /** How the data is encoded. This is the encoding for the data provided here, not the arg type */\n type?: ABIType | AVMType\n /** Where the default value is coming from\n * - box: The data key signifies the box key to read the value from\n * - global: The data key signifies the global state key to read the value from\n * - local: The data key signifies the local state key to read the value from (for the sender)\n * - literal: the value is a literal and should be passed directly as the argument\n * - method: The utf8 signature of the method in this contract to call to get the default value. If the method has arguments, they all must have default values. The method **MUST** be readonly so simulate can be used to get the default value\n */\n source: 'box' | 'global' | 'local' | 'literal' | 'method'\n }\n }>\n /** Information about the method's return value */\n returns: {\n /** The type of the return value, or \"void\" to indicate no return value. The `struct` field should also be checked to determine if this return value is a struct. */\n type: ABIType\n /** If the type is a struct, the name of the struct */\n struct?: StructName\n /** Optional, user-friendly description for the return value */\n desc?: string\n }\n /** an action is a combination of call/create and an OnComplete */\n actions: {\n /** OnCompletes this method allows when appID === 0 */\n create: ('NoOp' | 'OptIn' | 'DeleteApplication')[]\n /** OnCompletes this method allows when appID !== 0 */\n call: ('NoOp' | 'OptIn' | 'CloseOut' | 'ClearState' | 'UpdateApplication' | 'DeleteApplication')[]\n }\n /** If this method does not write anything to the ledger (ARC-22) */\n readonly?: boolean\n /** ARC-28 events that MAY be emitted by this method */\n events?: Array<Event>\n /** Information that clients can use when calling the method */\n recommendations?: {\n /** The number of inner transactions the caller should cover the fees for */\n innerTransactionCount?: number\n /** Recommended box references to include */\n boxes?: {\n /** The app ID for the box */\n app?: number\n /** The base64 encoded box key */\n key: string\n /** The number of bytes being read from the box */\n readBytes: number\n /** The number of bytes being written to the box */\n writeBytes: number\n }\n /** Recommended foreign accounts */\n accounts?: string[]\n /** Recommended foreign apps */\n apps?: number[]\n /** Recommended foreign assets */\n assets?: number[]\n }\n}\n\n/** ARC-28 event */\nexport interface Event {\n /** The name of the event */\n name: string\n /** Optional, user-friendly description for the event */\n desc?: string\n /** The arguments of the event, in order */\n args: Array<{\n /** The type of the argument. The `struct` field should also be checked to determine if this arg is a struct. */\n type: ABIType\n /** Optional, user-friendly name for the argument */\n name?: string\n /** Optional, user-friendly description for the argument */\n desc?: string\n /** If the type is a struct, the name of the struct */\n struct?: StructName\n }>\n}\n\n/** An ABI-encoded type */\nexport type ABIType = string\n\n/** The name of a defined struct */\nexport type StructName = string\n\n/** Raw byteslice without the length prefixed that is specified in ARC-4 */\nexport type AVMBytes = 'AVMBytes'\n\n/** A utf-8 string without the length prefix that is specified in ARC-4 */\nexport type AVMString = 'AVMString'\n\n/** A 64-bit unsigned integer */\nexport type AVMUint64 = 'AVMUint64'\n\n/** A native AVM type */\nexport type AVMType = AVMBytes | AVMString | AVMUint64\n\n/** Information about a single field in a struct */\nexport interface StructField {\n /** The name of the struct field */\n name: string\n /** The type of the struct field's value */\n type: ABIType | StructName | StructField[]\n}\n\n/** Describes a single key in app storage */\nexport interface StorageKey {\n /** Description of what this storage key holds */\n desc?: string\n /** The type of the key */\n keyType: ABIType | AVMType | StructName\n\n /** The type of the value */\n valueType: ABIType | AVMType | StructName\n /** The bytes of the key encoded as base64 */\n key: string\n}\n\n/** Describes a mapping of key-value pairs in storage */\nexport interface StorageMap {\n /** Description of what the key-value pairs in this mapping hold */\n desc?: string\n /** The type of the keys in the map */\n keyType: ABIType | AVMType | StructName\n /** The type of the values in the map */\n valueType: ABIType | AVMType | StructName\n /** The base64-encoded prefix of the map keys*/\n prefix?: string\n}\n\ninterface SourceInfo {\n /** The program counter value(s). Could be offset if pcOffsetMethod is not \"none\" */\n pc: Array<number>\n /** A human-readable string that describes the error when the program fails at the given PC */\n errorMessage?: string\n /** The TEAL line number that corresponds to the given PC. RECOMMENDED to be used for development purposes, but not required for clients */\n teal?: number\n /** The original source file and line number that corresponds to the given PC. RECOMMENDED to be used for development purposes, but not required for clients */\n source?: string\n}\n\nexport interface ProgramSourceInfo {\n /** The source information for the program */\n sourceInfo: SourceInfo[]\n /** How the program counter offset is calculated\n * - none: The pc values in sourceInfo are not offset\n * - cblocks: The pc values in sourceInfo are offset by the PC of the first op following the last cbl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AAW,EAAE,WAAW,EAAE;QAC5B,MAAM,WAAW,CAAC,WAAW,CAAA;KAC9B;AACD,IAAA,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,MAAM,IAAI,WAAW,EAAE,WAAW,KAAK,SAAS;AAAE,QAAA,OAAO,SAAoB,CAAA;IAEhH,IAAI,IAAI,KAAK,UAAU;QAAE,OAAO,WAAW,CAAC,cAAyB,CAAA;IACrE,IAAI,IAAI,KAAK,WAAW;AAAE,QAAA,OAAO,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAY,CAAA;IACrG,IAAI,IAAI,KAAK,WAAW;AAAE,QAAA,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,cAAc,CAAY,CAAA;AAE7G,IAAA,IAAI,OAAO,CAAC,IAAI,CAAC,EAAE;AACjB,QAAA,OAAO,wBAAwB,CAAC,WAAW,CAAC,WAAiC,EAAE,OAAO,CAAC,IAAI,CAAC,EAAE,OAAO,CAAY,CAAA;KAClH;IAED,OAAO,WAAW,CAAC,WAAsB,CAAA;AAC3C;;;;;;;;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"app-arc56.mjs","sources":["../../src/types/app-arc56.ts"],"sourcesContent":["import algosdk from 'algosdk'\nimport { ABIReturn } from './app'\nimport { Expand } from './expand'\n\n/** Type to describe an argument within an `Arc56Method`. */\nexport type Arc56MethodArg = Expand<\n Omit<Method['args'][number], 'type'> & {\n type: algosdk.ABIArgumentType\n }\n>\n\n/** Type to describe a return type within an `Arc56Method`. */\nexport type Arc56MethodReturnType = Expand<\n Omit<Method['returns'], 'type'> & {\n type: algosdk.ABIReturnType\n }\n>\n\n/**\n * Wrapper around `algosdk.ABIMethod` that represents an ARC-56 ABI method.\n */\nexport class Arc56Method extends algosdk.ABIMethod {\n override readonly args: Array<Arc56MethodArg>\n override readonly returns: Arc56MethodReturnType\n\n constructor(public method: Method) {\n super(method)\n this.args = method.args.map((arg) => ({\n ...arg,\n type: algosdk.abiTypeIsTransaction(arg.type) || algosdk.abiTypeIsReference(arg.type) ? arg.type : algosdk.ABIType.from(arg.type),\n }))\n this.returns = {\n ...this.method.returns,\n type: this.method.returns.type === 'void' ? 'void' : algosdk.ABIType.from(this.method.returns.type),\n }\n }\n\n override toJSON(): Method {\n return this.method\n }\n}\n\n/**\n * Returns the `ABITupleType` for the given ARC-56 struct definition\n * @param struct The ARC-56 struct definition\n * @returns The `ABITupleType`\n */\nexport function getABITupleTypeFromABIStructDefinition(\n struct: StructField[],\n structs: Record<string, StructField[]>,\n): algosdk.ABITupleType {\n return new algosdk.ABITupleType(\n struct.map((v) =>\n typeof v.type === 'string'\n ? structs[v.type]\n ? getABITupleTypeFromABIStructDefinition(structs[v.type], structs)\n : algosdk.ABIType.from(v.type)\n : getABITupleTypeFromABIStructDefinition(v.type, structs),\n ),\n )\n}\n\n/**\n * Converts a decoded ABI tuple as a struct.\n * @param decodedABITuple The decoded ABI tuple value\n * @param structFields The struct fields from an ARC-56 app spec\n * @returns The struct as a Record<string, any>\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getABIStructFromABITuple<TReturn extends ABIStruct = Record<string, any>>(\n decodedABITuple: algosdk.ABIValue[],\n structFields: StructField[],\n structs: Record<string, StructField[]>,\n): TReturn {\n return Object.fromEntries(\n structFields.map(({ name: key, type }, i) => {\n const abiValue = decodedABITuple[i]\n return [\n key,\n (typeof type === 'string' && !structs[type]) || !Array.isArray(abiValue)\n ? decodedABITuple[i]\n : getABIStructFromABITuple(abiValue, typeof type === 'string' ? structs[type] : type, structs),\n ]\n }),\n ) as TReturn\n}\n\n/**\n * Converts an ARC-56 struct as an ABI tuple.\n * @param struct The struct to convert\n * @param structFields The struct fields from an ARC-56 app spec\n * @returns The struct as a decoded ABI tuple\n */\nexport function getABITupleFromABIStruct(\n struct: ABIStruct,\n structFields: StructField[],\n structs: Record<string, StructField[]>,\n): algosdk.ABIValue[] {\n return structFields.map(({ name: key, type }) => {\n const value = struct[key]\n return typeof type === 'string' && !structs[type]\n ? (value as algosdk.ABIValue)\n : getABITupleFromABIStruct(value as ABIStruct, typeof type === 'string' ? structs[type] : type, structs)\n })\n}\n\n/** Decoded ARC-56 struct as a struct rather than a tuple. */\nexport type ABIStruct = {\n [key: string]: ABIStruct | algosdk.ABIValue\n}\n\n/**\n * Returns the decoded ABI value (or struct for a struct type)\n * for the given raw Algorand value given an ARC-56 type and defined ARC-56 structs.\n * @param value The raw Algorand value (bytes or uint64)\n * @param type The ARC-56 type - either an ABI Type string or a struct name\n * @param structs The defined ARC-56 structs\n * @returns The decoded ABI value or struct\n */\nexport function getABIDecodedValue(\n value: Uint8Array | number | bigint,\n type: string,\n structs: Record<string, StructField[]>,\n): algosdk.ABIValue | ABIStruct {\n if (type === 'AVMBytes' || typeof value !== 'object') return value\n if (type === 'AVMString') return Buffer.from(value).toString('utf-8')\n if (type === 'AVMUint64') return algosdk.ABIType.from('uint64').decode(value)\n if (structs[type]) {\n const tupleValue = getABITupleTypeFromABIStructDefinition(structs[type], structs).decode(value)\n return getABIStructFromABITuple(tupleValue, structs[type], structs)\n }\n return algosdk.ABIType.from(type).decode(value)\n}\n\n/**\n * Returns the ABI-encoded value for the given value.\n * @param value The value to encode either already in encoded binary form (`Uint8Array`), a decoded ABI value or an ARC-56 struct\n * @param type The ARC-56 type - either an ABI Type string or a struct name\n * @param structs The defined ARC-56 structs\n * @returns The binary ABI-encoded value\n */\nexport function getABIEncodedValue(\n value: Uint8Array | algosdk.ABIValue | ABIStruct,\n type: string,\n structs: Record<string, StructField[]>,\n): Uint8Array {\n if (typeof value === 'object' && value instanceof Uint8Array) return value\n if (type === 'AVMUint64') return algosdk.ABIType.from('uint64').encode(value as bigint | number)\n if (type === 'AVMBytes' || type === 'AVMString') {\n if (typeof value === 'string') return Buffer.from(value, 'utf-8')\n if (typeof value !== 'object' || !(value instanceof Uint8Array)) throw new Error(`Expected bytes value for ${type}, but got ${value}`)\n return value\n }\n if (structs[type]) {\n const tupleType = getABITupleTypeFromABIStructDefinition(structs[type], structs)\n if (Array.isArray(value)) {\n tupleType.encode(value as algosdk.ABIValue[])\n } else {\n return tupleType.encode(getABITupleFromABIStruct(value as ABIStruct, structs[type], structs))\n }\n }\n return algosdk.ABIType.from(type).encode(value as algosdk.ABIValue)\n}\n\n/**\n * Returns the ARC-56 ABI method object for a given method name or signature and ARC-56 app spec.\n * @param methodNameOrSignature The method name or method signature to call if an ABI call is being emitted.\n * e.g. `my_method` or `my_method(unit64,string)bytes`\n * @param appSpec The app spec for the app\n * @returns The `Arc56Method`\n */\nexport function getArc56Method(methodNameOrSignature: string, appSpec: Arc56Contract): Arc56Method {\n let method: Method\n if (!methodNameOrSignature.includes('(')) {\n const methods = appSpec.methods.filter((m) => m.name === methodNameOrSignature)\n if (methods.length === 0) throw new Error(`Unable to find method ${methodNameOrSignature} in ${appSpec.name} app.`)\n if (methods.length > 1) {\n throw new Error(\n `Received a call to method ${methodNameOrSignature} in contract ${\n appSpec.name\n }, but this resolved to multiple methods; please pass in an ABI signature instead: ${appSpec.methods\n .map((m) => new algosdk.ABIMethod(m).getSignature())\n .join(', ')}`,\n )\n }\n method = methods[0]\n } else {\n const m = appSpec.methods.find((m) => new algosdk.ABIMethod(m).getSignature() === methodNameOrSignature)\n if (!m) throw new Error(`Unable to find method ${methodNameOrSignature} in ${appSpec.name} app.`)\n method = m\n }\n return new Arc56Method(method)\n}\n\n/**\n * Checks for decode errors on the AppCallTransactionResult and maps the return value to the specified generic type\n *\n * @param returnValue The smart contract response\n * @param method The method that was called\n * @param structs The struct fields from the app spec\n * @returns The smart contract response with an updated return value\n */\nexport function getArc56ReturnValue<TReturn extends Uint8Array | algosdk.ABIValue | ABIStruct | undefined>(\n returnValue: ABIReturn | undefined,\n method: Method | Arc56Method,\n structs: Record<string, StructField[]>,\n): TReturn {\n const m = 'method' in method ? method.method : method\n const type = m.returns.struct ?? m.returns.type\n if (returnValue?.decodeError) {\n throw returnValue.decodeError\n }\n if (type === undefined || type === 'void' || returnValue?.returnValue === undefined) return undefined as TReturn\n\n if (type === 'AVMBytes') return returnValue.rawReturnValue as TReturn\n if (type === 'AVMString') return Buffer.from(returnValue.rawReturnValue).toString('utf-8') as TReturn\n if (type === 'AVMUint64') return algosdk.ABIType.from('uint64').decode(returnValue.rawReturnValue) as TReturn\n\n if (structs[type]) {\n return getABIStructFromABITuple(returnValue.returnValue as algosdk.ABIValue[], structs[type], structs) as TReturn\n }\n\n return returnValue.returnValue as TReturn\n}\n\n/****************/\n/** ARC-56 spec */\n/****************/\n\n/** Describes the entire contract. This interface is an extension of the interface described in ARC-4 */\nexport interface Arc56Contract {\n /** The ARCs used and/or supported by this contract. All contracts implicitly support ARC4 and ARC56 */\n arcs: number[]\n /** A user-friendly name for the contract */\n name: string\n /** Optional, user-friendly description for the interface */\n desc?: string\n /**\n * Optional object listing the contract instances across different networks.\n * The key is the base64 genesis hash of the network, and the value contains\n * information about the deployed contract in the network indicated by the\n * key. A key containing the human-readable name of the network MAY be\n * included, but the corresponding genesis hash key MUST also be define\n */\n networks?: {\n [network: string]: {\n /** The app ID of the deployed contract in this network */\n appID: number\n }\n }\n /** Named structs use by the application. Each struct field appears in the same order as ABI encoding. */\n structs: { [structName: StructName]: StructField[] }\n /** All of the methods that the contract implements */\n methods: Method[]\n state: {\n /** Defines the values that should be used for GlobalNumUint, GlobalNumByteSlice, LocalNumUint, and LocalNumByteSlice when creating the application */\n schema: {\n global: {\n ints: number\n bytes: number\n }\n local: {\n ints: number\n bytes: number\n }\n }\n /** Mapping of human-readable names to StorageKey objects */\n keys: {\n global: { [name: string]: StorageKey }\n local: { [name: string]: StorageKey }\n box: { [name: string]: StorageKey }\n }\n /** Mapping of human-readable names to StorageMap objects */\n maps: {\n global: { [name: string]: StorageMap }\n local: { [name: string]: StorageMap }\n box: { [name: string]: StorageMap }\n }\n }\n /** Supported bare actions for the contract. An action is a combination of call/create and an OnComplete */\n bareActions: {\n /** OnCompletes this method allows when appID === 0 */\n create: ('NoOp' | 'OptIn' | 'DeleteApplication')[]\n /** OnCompletes this method allows when appID !== 0 */\n call: ('NoOp' | 'OptIn' | 'CloseOut' | 'ClearState' | 'UpdateApplication' | 'DeleteApplication')[]\n }\n /** Information about the TEAL programs */\n sourceInfo?: {\n /** Approval program information */\n approval: ProgramSourceInfo\n /** Clear program information */\n clear: ProgramSourceInfo\n }\n /** The pre-compiled TEAL that may contain template variables. MUST be omitted if included as part of ARC23 */\n source?: {\n /** The approval program */\n approval: string\n /** The clear program */\n clear: string\n }\n /** The compiled bytecode for the application. MUST be omitted if included as part of ARC23 */\n byteCode?: {\n /** The approval program */\n approval: string\n /** The clear program */\n clear: string\n }\n /** Information used to get the given byteCode and/or PC values in sourceInfo. MUST be given if byteCode or PC values are present */\n compilerInfo?: {\n /** The name of the compiler */\n compiler: 'algod' | 'puya'\n /** Compiler version information */\n compilerVersion: {\n major: number\n minor: number\n patch: number\n commitHash?: string\n }\n }\n /** ARC-28 events that MAY be emitted by this contract */\n events?: Array<Event>\n /** A mapping of template variable names as they appear in the teal (not including TMPL_ prefix) to their respective types and values (if applicable) */\n templateVariables?: {\n [name: string]: {\n /** The type of the template variable */\n type: ABIType | AVMType | StructName\n /** If given, the the base64 encoded value used for the given app/program */\n value?: string\n }\n }\n /** The scratch variables used during runtime */\n scratchVariables?: {\n [name: string]: {\n slot: number\n type: ABIType | AVMType | StructName\n }\n }\n}\n\n/** Describes a method in the contract. This interface is an extension of the interface described in ARC-4 */\nexport interface Method {\n /** The name of the method */\n name: string\n /** Optional, user-friendly description for the method */\n desc?: string\n /** The arguments of the method, in order */\n args: Array<{\n /** The type of the argument. The `struct` field should also be checked to determine if this arg is a struct. */\n type: ABIType\n /** If the type is a struct, the name of the struct */\n struct?: StructName\n /** Optional, user-friendly name for the argument */\n name?: string\n /** Optional, user-friendly description for the argument */\n desc?: string\n /** The default value that clients should use. */\n defaultValue?: {\n /** Base64 encoded bytes, base64 ARC4 encoded uint64, or UTF-8 method selector */\n data: string\n /** How the data is encoded. This is the encoding for the data provided here, not the arg type */\n type?: ABIType | AVMType\n /** Where the default value is coming from\n * - box: The data key signifies the box key to read the value from\n * - global: The data key signifies the global state key to read the value from\n * - local: The data key signifies the local state key to read the value from (for the sender)\n * - literal: the value is a literal and should be passed directly as the argument\n * - method: The utf8 signature of the method in this contract to call to get the default value. If the method has arguments, they all must have default values. The method **MUST** be readonly so simulate can be used to get the default value\n */\n source: 'box' | 'global' | 'local' | 'literal' | 'method'\n }\n }>\n /** Information about the method's return value */\n returns: {\n /** The type of the return value, or \"void\" to indicate no return value. The `struct` field should also be checked to determine if this return value is a struct. */\n type: ABIType\n /** If the type is a struct, the name of the struct */\n struct?: StructName\n /** Optional, user-friendly description for the return value */\n desc?: string\n }\n /** an action is a combination of call/create and an OnComplete */\n actions: {\n /** OnCompletes this method allows when appID === 0 */\n create: ('NoOp' | 'OptIn' | 'DeleteApplication')[]\n /** OnCompletes this method allows when appID !== 0 */\n call: ('NoOp' | 'OptIn' | 'CloseOut' | 'ClearState' | 'UpdateApplication' | 'DeleteApplication')[]\n }\n /** If this method does not write anything to the ledger (ARC-22) */\n readonly?: boolean\n /** ARC-28 events that MAY be emitted by this method */\n events?: Array<Event>\n /** Information that clients can use when calling the method */\n recommendations?: {\n /** The number of inner transactions the caller should cover the fees for */\n innerTransactionCount?: number\n /** Recommended box references to include */\n boxes?: {\n /** The app ID for the box */\n app?: number\n /** The base64 encoded box key */\n key: string\n /** The number of bytes being read from the box */\n readBytes: number\n /** The number of bytes being written to the box */\n writeBytes: number\n }\n /** Recommended foreign accounts */\n accounts?: string[]\n /** Recommended foreign apps */\n apps?: number[]\n /** Recommended foreign assets */\n assets?: number[]\n }\n}\n\n/** ARC-28 event */\nexport interface Event {\n /** The name of the event */\n name: string\n /** Optional, user-friendly description for the event */\n desc?: string\n /** The arguments of the event, in order */\n args: Array<{\n /** The type of the argument. The `struct` field should also be checked to determine if this arg is a struct. */\n type: ABIType\n /** Optional, user-friendly name for the argument */\n name?: string\n /** Optional, user-friendly description for the argument */\n desc?: string\n /** If the type is a struct, the name of the struct */\n struct?: StructName\n }>\n}\n\n/** An ABI-encoded type */\nexport type ABIType = string\n\n/** The name of a defined struct */\nexport type StructName = string\n\n/** Raw byteslice without the length prefixed that is specified in ARC-4 */\nexport type AVMBytes = 'AVMBytes'\n\n/** A utf-8 string without the length prefix that is specified in ARC-4 */\nexport type AVMString = 'AVMString'\n\n/** A 64-bit unsigned integer */\nexport type AVMUint64 = 'AVMUint64'\n\n/** A native AVM type */\nexport type AVMType = AVMBytes | AVMString | AVMUint64\n\n/** Information about a single field in a struct */\nexport interface StructField {\n /** The name of the struct field */\n name: string\n /** The type of the struct field's value */\n type: ABIType | StructName | StructField[]\n}\n\n/** Describes a single key in app storage */\nexport interface StorageKey {\n /** Description of what this storage key holds */\n desc?: string\n /** The type of the key */\n keyType: ABIType | AVMType | StructName\n\n /** The type of the value */\n valueType: ABIType | AVMType | StructName\n /** The bytes of the key encoded as base64 */\n key: string\n}\n\n/** Describes a mapping of key-value pairs in storage */\nexport interface StorageMap {\n /** Description of what the key-value pairs in this mapping hold */\n desc?: string\n /** The type of the keys in the map */\n keyType: ABIType | AVMType | StructName\n /** The type of the values in the map */\n valueType: ABIType | AVMType | StructName\n /** The base64-encoded prefix of the map keys*/\n prefix?: string\n}\n\ninterface SourceInfo {\n /** The program counter value(s). Could be offset if pcOffsetMethod is not \"none\" */\n pc: Array<number>\n /** A human-readable string that describes the error when the program fails at the given PC */\n errorMessage?: string\n /** The TEAL line number that corresponds to the given PC. RECOMMENDED to be used for development purposes, but not required for clients */\n teal?: number\n /** The original source file and line number that corresponds to the given PC. RECOMMENDED to be used for development purposes, but not required for clients */\n source?: string\n}\n\nexport interface ProgramSourceInfo {\n /** The source information for the program */\n sourceInfo: SourceInfo[]\n /** How the program counter offset is calculated\n * - none: The pc values in sourceInfo are not offset\n * - cblocks: The pc values in sourceInfo are offset by the PC of the first op following the last cblock at the top of the program\n */\n pcOffsetMethod: 'none' | 'cblocks'\n}\n"],"names":[],"mappings":";;AAkBA;;AAEG;AACU,MAAA,WAAY,SAAQ,OAAO,CAAC,SAAS,CAAA;AAIhD,IAAA,WAAA,CAAmB,MAAc,EAAA;QAC/B,KAAK,CAAC,MAAM,CAAC,CAAA;QADI,IAAM,CAAA,MAAA,GAAN,MAAM,CAAQ;AAE/B,QAAA,IAAI,CAAC,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,MAAM;AACpC,YAAA,GAAG,GAAG;AACN,YAAA,IAAI,EAAE,OAAO,CAAC,oBAAoB,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,OAAO,CAAC,kBAAkB,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC;AACjI,SAAA,CAAC,CAAC,CAAA;QACH,IAAI,CAAC,OAAO,GAAG;AACb,YAAA,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO;AACtB,YAAA,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC;SACpG,CAAA;KACF;IAEQ,MAAM,GAAA;QACb,OAAO,IAAI,CAAC,MAAM,CAAA;KACnB;AACF,CAAA;AAED;;;;AAIG;AACa,SAAA,sCAAsC,CACpD,MAAqB,EACrB,OAAsC,EAAA;AAEtC,IAAA,OAAO,IAAI,OAAO,CAAC,YAAY,CAC7B,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,KACX,OAAO,CAAC,CAAC,IAAI,KAAK,QAAQ;AACxB,UAAE,OAAO,CAAC,CAAC,CAAC,IAAI,CA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AC,IAAI,CAAA;AAC/C,IAAA,IAAI,WAAW,EAAE,WAAW,EAAE;QAC5B,MAAM,WAAW,CAAC,WAAW,CAAA;KAC9B;AACD,IAAA,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,MAAM,IAAI,WAAW,EAAE,WAAW,KAAK,SAAS;AAAE,QAAA,OAAO,SAAoB,CAAA;IAEhH,IAAI,IAAI,KAAK,UAAU;QAAE,OAAO,WAAW,CAAC,cAAyB,CAAA;IACrE,IAAI,IAAI,KAAK,WAAW;AAAE,QAAA,OAAO,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAY,CAAA;IACrG,IAAI,IAAI,KAAK,WAAW;AAAE,QAAA,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,cAAc,CAAY,CAAA;AAE7G,IAAA,IAAI,OAAO,CAAC,IAAI,CAAC,EAAE;AACjB,QAAA,OAAO,wBAAwB,CAAC,WAAW,CAAC,WAAiC,EAAE,OAAO,CAAC,IAAI,CAAC,EAAE,OAAO,CAAY,CAAA;KAClH;IAED,OAAO,WAAW,CAAC,WAAsB,CAAA;AAC3C;;;;"}
1
+ {"version":3,"file":"app-arc56.mjs","sources":["../../src/types/app-arc56.ts"],"sourcesContent":["import algosdk from 'algosdk'\nimport { ABIReturn } from './app'\nimport { Expand } from './expand'\n\n/** Type to describe an argument within an `Arc56Method`. */\nexport type Arc56MethodArg = Expand<\n Omit<Method['args'][number], 'type'> & {\n type: algosdk.ABIArgumentType\n }\n>\n\n/** Type to describe a return type within an `Arc56Method`. */\nexport type Arc56MethodReturnType = Expand<\n Omit<Method['returns'], 'type'> & {\n type: algosdk.ABIReturnType\n }\n>\n\n/**\n * Wrapper around `algosdk.ABIMethod` that represents an ARC-56 ABI method.\n */\nexport class Arc56Method extends algosdk.ABIMethod {\n override readonly args: Array<Arc56MethodArg>\n override readonly returns: Arc56MethodReturnType\n\n constructor(public method: Method) {\n super(method)\n this.args = method.args.map((arg) => ({\n ...arg,\n type: algosdk.abiTypeIsTransaction(arg.type) || algosdk.abiTypeIsReference(arg.type) ? arg.type : algosdk.ABIType.from(arg.type),\n }))\n this.returns = {\n ...this.method.returns,\n type: this.method.returns.type === 'void' ? 'void' : algosdk.ABIType.from(this.method.returns.type),\n }\n }\n\n override toJSON(): Method {\n return this.method\n }\n}\n\n/**\n * Returns the `ABITupleType` for the given ARC-56 struct definition\n * @param struct The ARC-56 struct definition\n * @returns The `ABITupleType`\n */\nexport function getABITupleTypeFromABIStructDefinition(\n struct: StructField[],\n structs: Record<string, StructField[]>,\n): algosdk.ABITupleType {\n return new algosdk.ABITupleType(\n struct.map((v) =>\n typeof v.type === 'string'\n ? structs[v.type]\n ? getABITupleTypeFromABIStructDefinition(structs[v.type], structs)\n : algosdk.ABIType.from(v.type)\n : getABITupleTypeFromABIStructDefinition(v.type, structs),\n ),\n )\n}\n\n/**\n * Converts a decoded ABI tuple as a struct.\n * @param decodedABITuple The decoded ABI tuple value\n * @param structFields The struct fields from an ARC-56 app spec\n * @returns The struct as a Record<string, any>\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getABIStructFromABITuple<TReturn extends ABIStruct = Record<string, any>>(\n decodedABITuple: algosdk.ABIValue[],\n structFields: StructField[],\n structs: Record<string, StructField[]>,\n): TReturn {\n return Object.fromEntries(\n structFields.map(({ name: key, type }, i) => {\n const abiValue = decodedABITuple[i]\n return [\n key,\n (typeof type === 'string' && !structs[type]) || !Array.isArray(abiValue)\n ? decodedABITuple[i]\n : getABIStructFromABITuple(abiValue, typeof type === 'string' ? structs[type] : type, structs),\n ]\n }),\n ) as TReturn\n}\n\n/**\n * Converts an ARC-56 struct as an ABI tuple.\n * @param struct The struct to convert\n * @param structFields The struct fields from an ARC-56 app spec\n * @returns The struct as a decoded ABI tuple\n */\nexport function getABITupleFromABIStruct(\n struct: ABIStruct,\n structFields: StructField[],\n structs: Record<string, StructField[]>,\n): algosdk.ABIValue[] {\n return structFields.map(({ name: key, type }) => {\n const value = struct[key]\n return typeof type === 'string' && !structs[type]\n ? (value as algosdk.ABIValue)\n : getABITupleFromABIStruct(value as ABIStruct, typeof type === 'string' ? structs[type] : type, structs)\n })\n}\n\n/** Decoded ARC-56 struct as a struct rather than a tuple. */\nexport type ABIStruct = {\n [key: string]: ABIStruct | algosdk.ABIValue\n}\n\n/**\n * Returns the decoded ABI value (or struct for a struct type)\n * for the given raw Algorand value given an ARC-56 type and defined ARC-56 structs.\n * @param value The raw Algorand value (bytes or uint64)\n * @param type The ARC-56 type - either an ABI Type string or a struct name\n * @param structs The defined ARC-56 structs\n * @returns The decoded ABI value or struct\n */\nexport function getABIDecodedValue(\n value: Uint8Array | number | bigint,\n type: string,\n structs: Record<string, StructField[]>,\n): algosdk.ABIValue | ABIStruct {\n if (type === 'AVMBytes' || typeof value !== 'object') return value\n if (type === 'AVMString') return Buffer.from(value).toString('utf-8')\n if (type === 'AVMUint64') return algosdk.ABIType.from('uint64').decode(value)\n if (structs[type]) {\n const tupleValue = getABITupleTypeFromABIStructDefinition(structs[type], structs).decode(value)\n return getABIStructFromABITuple(tupleValue, structs[type], structs)\n }\n return algosdk.ABIType.from(type).decode(value)\n}\n\n/**\n * Returns the ABI-encoded value for the given value.\n * @param value The value to encode either already in encoded binary form (`Uint8Array`), a decoded ABI value or an ARC-56 struct\n * @param type The ARC-56 type - either an ABI Type string or a struct name\n * @param structs The defined ARC-56 structs\n * @returns The binary ABI-encoded value\n */\nexport function getABIEncodedValue(\n value: Uint8Array | algosdk.ABIValue | ABIStruct,\n type: string,\n structs: Record<string, StructField[]>,\n): Uint8Array {\n if (typeof value === 'object' && value instanceof Uint8Array) return value\n if (type === 'AVMUint64') return algosdk.ABIType.from('uint64').encode(value as bigint | number)\n if (type === 'AVMBytes' || type === 'AVMString') {\n if (typeof value === 'string') return Buffer.from(value, 'utf-8')\n if (typeof value !== 'object' || !(value instanceof Uint8Array)) throw new Error(`Expected bytes value for ${type}, but got ${value}`)\n return value\n }\n if (structs[type]) {\n const tupleType = getABITupleTypeFromABIStructDefinition(structs[type], structs)\n if (Array.isArray(value)) {\n tupleType.encode(value as algosdk.ABIValue[])\n } else {\n return tupleType.encode(getABITupleFromABIStruct(value as ABIStruct, structs[type], structs))\n }\n }\n return algosdk.ABIType.from(type).encode(value as algosdk.ABIValue)\n}\n\n/**\n * Returns the ARC-56 ABI method object for a given method name or signature and ARC-56 app spec.\n * @param methodNameOrSignature The method name or method signature to call if an ABI call is being emitted.\n * e.g. `my_method` or `my_method(unit64,string)bytes`\n * @param appSpec The app spec for the app\n * @returns The `Arc56Method`\n */\nexport function getArc56Method(methodNameOrSignature: string, appSpec: Arc56Contract): Arc56Method {\n let method: Method\n if (!methodNameOrSignature.includes('(')) {\n const methods = appSpec.methods.filter((m) => m.name === methodNameOrSignature)\n if (methods.length === 0) throw new Error(`Unable to find method ${methodNameOrSignature} in ${appSpec.name} app.`)\n if (methods.length > 1) {\n throw new Error(\n `Received a call to method ${methodNameOrSignature} in contract ${\n appSpec.name\n }, but this resolved to multiple methods; please pass in an ABI signature instead: ${appSpec.methods\n .map((m) => new algosdk.ABIMethod(m).getSignature())\n .join(', ')}`,\n )\n }\n method = methods[0]\n } else {\n const m = appSpec.methods.find((m) => new algosdk.ABIMethod(m).getSignature() === methodNameOrSignature)\n if (!m) throw new Error(`Unable to find method ${methodNameOrSignature} in ${appSpec.name} app.`)\n method = m\n }\n return new Arc56Method(method)\n}\n\n/**\n * Checks for decode errors on the AppCallTransactionResult and maps the return value to the specified generic type\n *\n * @param returnValue The smart contract response\n * @param method The method that was called\n * @param structs The struct fields from the app spec\n * @returns The smart contract response with an updated return value\n */\nexport function getArc56ReturnValue<TReturn extends Uint8Array | algosdk.ABIValue | ABIStruct | undefined>(\n returnValue: ABIReturn | undefined,\n method: Method | Arc56Method,\n structs: Record<string, StructField[]>,\n): TReturn {\n const m = 'method' in method ? method.method : method\n const type = m.returns.struct ?? m.returns.type\n if (returnValue?.decodeError) {\n throw returnValue.decodeError\n }\n if (type === undefined || type === 'void' || returnValue?.returnValue === undefined) return undefined as TReturn\n\n if (type === 'AVMBytes') return returnValue.rawReturnValue as TReturn\n if (type === 'AVMString') return Buffer.from(returnValue.rawReturnValue).toString('utf-8') as TReturn\n if (type === 'AVMUint64') return algosdk.ABIType.from('uint64').decode(returnValue.rawReturnValue) as TReturn\n\n if (structs[type]) {\n return getABIStructFromABITuple(returnValue.returnValue as algosdk.ABIValue[], structs[type], structs) as TReturn\n }\n\n return returnValue.returnValue as TReturn\n}\n\n/****************/\n/** ARC-56 spec */\n/****************/\n\n/** Describes the entire contract. This interface is an extension of the interface described in ARC-4 */\nexport interface Arc56Contract {\n /** The ARCs used and/or supported by this contract. All contracts implicitly support ARC4 and ARC56 */\n arcs: number[]\n /** A user-friendly name for the contract */\n name: string\n /** Optional, user-friendly description for the interface */\n desc?: string\n /**\n * Optional object listing the contract instances across different networks.\n * The key is the base64 genesis hash of the network, and the value contains\n * information about the deployed contract in the network indicated by the\n * key. A key containing the human-readable name of the network MAY be\n * included, but the corresponding genesis hash key MUST also be defined\n */\n networks?: {\n [network: string]: {\n /** The app ID of the deployed contract in this network */\n appID: number\n }\n }\n /** Named structs used by the application. Each struct field appears in the same order as ABI encoding. */\n structs: { [structName: StructName]: StructField[] }\n /** All of the methods that the contract implements */\n methods: Method[]\n state: {\n /** Defines the values that should be used for GlobalNumUint, GlobalNumByteSlice, LocalNumUint, and LocalNumByteSlice when creating the application */\n schema: {\n global: {\n ints: number\n bytes: number\n }\n local: {\n ints: number\n bytes: number\n }\n }\n /** Mapping of human-readable names to StorageKey objects */\n keys: {\n global: { [name: string]: StorageKey }\n local: { [name: string]: StorageKey }\n box: { [name: string]: StorageKey }\n }\n /** Mapping of human-readable names to StorageMap objects */\n maps: {\n global: { [name: string]: StorageMap }\n local: { [name: string]: StorageMap }\n box: { [name: string]: StorageMap }\n }\n }\n /** Supported bare actions for the contract. An action is a combination of call/create and an OnComplete */\n bareActions: {\n /** OnCompletes this method allows when appID === 0 */\n create: ('NoOp' | 'OptIn' | 'DeleteApplication')[]\n /** OnCompletes this method allows when appID !== 0 */\n call: ('NoOp' | 'OptIn' | 'CloseOut' | 'ClearState' | 'UpdateApplication' | 'DeleteApplication')[]\n }\n /** Information about the TEAL programs */\n sourceInfo?: {\n /** Approval program information */\n approval: ProgramSourceInfo\n /** Clear program information */\n clear: ProgramSourceInfo\n }\n /** The pre-compiled TEAL that may contain template variables. MUST be omitted if included as part of ARC23 */\n source?: {\n /** The approval program */\n approval: string\n /** The clear program */\n clear: string\n }\n /** The compiled bytecode for the application. MUST be omitted if included as part of ARC23 */\n byteCode?: {\n /** The approval program */\n approval: string\n /** The clear program */\n clear: string\n }\n /** Information used to get the given byteCode and/or PC values in sourceInfo. MUST be given if byteCode or PC values are present */\n compilerInfo?: {\n /** The name of the compiler */\n compiler: 'algod' | 'puya'\n /** Compiler version information */\n compilerVersion: {\n major: number\n minor: number\n patch: number\n commitHash?: string\n }\n }\n /** ARC-28 events that MAY be emitted by this contract */\n events?: Array<Event>\n /** A mapping of template variable names as they appear in the TEAL (not including TMPL_ prefix) to their respective types and values (if applicable) */\n templateVariables?: {\n [name: string]: {\n /** The type of the template variable */\n type: ABIType | AVMType | StructName\n /** If given, the base64 encoded value used for the given app/program */\n value?: string\n }\n }\n /** The scratch variables used during runtime */\n scratchVariables?: {\n [name: string]: {\n slot: number\n type: ABIType | AVMType | StructName\n }\n }\n}\n\n/** Describes a method in the contract. This interface is an extension of the interface described in ARC-4 */\nexport interface Method {\n /** The name of the method */\n name: string\n /** Optional, user-friendly description for the method */\n desc?: string\n /** The arguments of the method, in order */\n args: Array<{\n /** The type of the argument. The `struct` field should also be checked to determine if this arg is a struct. */\n type: ABIType\n /** If the type is a struct, the name of the struct */\n struct?: StructName\n /** Optional, user-friendly name for the argument */\n name?: string\n /** Optional, user-friendly description for the argument */\n desc?: string\n /** The default value that clients should use. */\n defaultValue?: {\n /** Base64 encoded bytes, base64 ARC4 encoded uint64, or UTF-8 method selector */\n data: string\n /** How the data is encoded. This is the encoding for the data provided here, not the arg type */\n type?: ABIType | AVMType\n /** Where the default value is coming from\n * - box: The data key signifies the box key to read the value from\n * - global: The data key signifies the global state key to read the value from\n * - local: The data key signifies the local state key to read the value from (for the sender)\n * - literal: the value is a literal and should be passed directly as the argument\n * - method: The utf8 signature of the method in this contract to call to get the default value. If the method has arguments, they all must have default values. The method **MUST** be readonly so simulate can be used to get the default value\n */\n source: 'box' | 'global' | 'local' | 'literal' | 'method'\n }\n }>\n /** Information about the method's return value */\n returns: {\n /** The type of the return value, or \"void\" to indicate no return value. The `struct` field should also be checked to determine if this return value is a struct. */\n type: ABIType\n /** If the type is a struct, the name of the struct */\n struct?: StructName\n /** Optional, user-friendly description for the return value */\n desc?: string\n }\n /** an action is a combination of call/create and an OnComplete */\n actions: {\n /** OnCompletes this method allows when appID === 0 */\n create: ('NoOp' | 'OptIn' | 'DeleteApplication')[]\n /** OnCompletes this method allows when appID !== 0 */\n call: ('NoOp' | 'OptIn' | 'CloseOut' | 'ClearState' | 'UpdateApplication' | 'DeleteApplication')[]\n }\n /** If this method does not write anything to the ledger (ARC-22) */\n readonly?: boolean\n /** ARC-28 events that MAY be emitted by this method */\n events?: Array<Event>\n /** Information that clients can use when calling the method */\n recommendations?: {\n /** The number of inner transactions the caller should cover the fees for */\n innerTransactionCount?: number\n /** Recommended box references to include */\n boxes?: {\n /** The app ID for the box */\n app?: number\n /** The base64 encoded box key */\n key: string\n /** The number of bytes being read from the box */\n readBytes: number\n /** The number of bytes being written to the box */\n writeBytes: number\n }\n /** Recommended foreign accounts */\n accounts?: string[]\n /** Recommended foreign apps */\n apps?: number[]\n /** Recommended foreign assets */\n assets?: number[]\n }\n}\n\n/** ARC-28 event */\nexport interface Event {\n /** The name of the event */\n name: string\n /** Optional, user-friendly description for the event */\n desc?: string\n /** The arguments of the event, in order */\n args: Array<{\n /** The type of the argument. The `struct` field should also be checked to determine if this arg is a struct. */\n type: ABIType\n /** Optional, user-friendly name for the argument */\n name?: string\n /** Optional, user-friendly description for the argument */\n desc?: string\n /** If the type is a struct, the name of the struct */\n struct?: StructName\n }>\n}\n\n/** An ABI-encoded type */\nexport type ABIType = string\n\n/** The name of a defined struct */\nexport type StructName = string\n\n/** Raw byteslice without the length prefixed that is specified in ARC-4 */\nexport type AVMBytes = 'AVMBytes'\n\n/** A utf-8 string without the length prefix that is specified in ARC-4 */\nexport type AVMString = 'AVMString'\n\n/** A 64-bit unsigned integer */\nexport type AVMUint64 = 'AVMUint64'\n\n/** A native AVM type */\nexport type AVMType = AVMBytes | AVMString | AVMUint64\n\n/** Information about a single field in a struct */\nexport interface StructField {\n /** The name of the struct field */\n name: string\n /** The type of the struct field's value */\n type: ABIType | StructName | StructField[]\n}\n\n/** Describes a single key in app storage */\nexport interface StorageKey {\n /** Description of what this storage key holds */\n desc?: string\n /** The type of the key */\n keyType: ABIType | AVMType | StructName\n\n /** The type of the value */\n valueType: ABIType | AVMType | StructName\n /** The bytes of the key encoded as base64 */\n key: string\n}\n\n/** Describes a mapping of key-value pairs in storage */\nexport interface StorageMap {\n /** Description of what the key-value pairs in this mapping hold */\n desc?: string\n /** The type of the keys in the map */\n keyType: ABIType | AVMType | StructName\n /** The type of the values in the map */\n valueType: ABIType | AVMType | StructName\n /** The base64-encoded prefix of the map keys*/\n prefix?: string\n}\n\ninterface SourceInfo {\n /** The program counter value(s). Could be offset if pcOffsetMethod is not \"none\" */\n pc: Array<number>\n /** A human-readable string that describes the error when the program fails at the given PC */\n errorMessage?: string\n /** The TEAL line number that corresponds to the given PC. RECOMMENDED to be used for development purposes, but not required for clients */\n teal?: number\n /** The original source file and line number that corresponds to the given PC. RECOMMENDED to be used for development purposes, but not required for clients */\n source?: string\n}\n\nexport interface ProgramSourceInfo {\n /** The source information for the program */\n sourceInfo: SourceInfo[]\n /** How the program counter offset is calculated\n * - none: The pc values in sourceInfo are not offset\n * - cblocks: The pc values in sourceInfo are offset by the PC of the first op following the last cblock at the top of the program\n */\n pcOffsetMethod: 'none' | 'cblocks'\n}\n"],"names":[],"mappings":";;AAkBA;;AAEG;AACU,MAAA,WAAY,SAAQ,OAAO,CAAC,SAAS,CAAA;AAIhD,IAAA,WAAA,CAAmB,MAAc,EAAA;QAC/B,KAAK,CAAC,MAAM,CAAC,CAAA;QADI,IAAM,CAAA,MAAA,GAAN,MAAM,CAAQ;AAE/B,QAAA,IAAI,CAAC,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,MAAM;AACpC,YAAA,GAAG,GAAG;AACN,YAAA,IAAI,EAAE,OAAO,CAAC,oBAAoB,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,OAAO,CAAC,kBAAkB,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC;AACjI,SAAA,CAAC,CAAC,CAAA;QACH,IAAI,CAAC,OAAO,GAAG;AACb,YAAA,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO;AACtB,YAAA,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC;SACpG,CAAA;KACF;IAEQ,MAAM,GAAA;QACb,OAAO,IAAI,CAAC,MAAM,CAAA;KACnB;AACF,CAAA;AAED;;;;AAIG;AACa,SAAA,sCAAsC,CACpD,MAAqB,EACrB,OAAsC,EAAA;AAEtC,IAAA,OAAO,IAAI,OAAO,CAAC,YAAY,CAC7B,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,KACX,OAAO,CAAC,CAAC,IAAI,KAAK,QAAQ;AACxB,UAAE,OAAO,CAAC,CAA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C,CAAC,OAAO,CAAC,IAAI,CAAA;AAC/C,IAAA,IAAI,WAAW,EAAE,WAAW,EAAE;QAC5B,MAAM,WAAW,CAAC,WAAW,CAAA;KAC9B;AACD,IAAA,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,MAAM,IAAI,WAAW,EAAE,WAAW,KAAK,SAAS;AAAE,QAAA,OAAO,SAAoB,CAAA;IAEhH,IAAI,IAAI,KAAK,UAAU;QAAE,OAAO,WAAW,CAAC,cAAyB,CAAA;IACrE,IAAI,IAAI,KAAK,WAAW;AAAE,QAAA,OAAO,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAY,CAAA;IACrG,IAAI,IAAI,KAAK,WAAW;AAAE,QAAA,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,cAAc,CAAY,CAAA;AAE7G,IAAA,IAAI,OAAO,CAAC,IAAI,CAAC,EAAE;AACjB,QAAA,OAAO,wBAAwB,CAAC,WAAW,CAAC,WAAiC,EAAE,OAAO,CAAC,IAAI,CAAC,EAAE,OAAO,CAAY,CAAA;KAClH;IAED,OAAO,WAAW,CAAC,WAAsB,CAAA;AAC3C;;;;"}
@@ -272,13 +272,13 @@ class AppManager {
272
272
  if (!tealTemplateCode.includes(types_app.UPDATABLE_TEMPLATE_NAME)) {
273
273
  throw new Error(`Deploy-time updatability control requested for app deployment, but ${types_app.UPDATABLE_TEMPLATE_NAME} not present in TEAL code`);
274
274
  }
275
- tealTemplateCode = tealTemplateCode.replace(new RegExp(types_app.UPDATABLE_TEMPLATE_NAME, 'g'), (params.updatable ? 1 : 0).toString());
275
+ tealTemplateCode = replaceTemplateVariable(tealTemplateCode, types_app.UPDATABLE_TEMPLATE_NAME, (params.updatable ? 1 : 0).toString());
276
276
  }
277
277
  if (params.deletable !== undefined) {
278
278
  if (!tealTemplateCode.includes(types_app.DELETABLE_TEMPLATE_NAME)) {
279
279
  throw new Error(`Deploy-time deletability control requested for app deployment, but ${types_app.DELETABLE_TEMPLATE_NAME} not present in TEAL code`);
280
280
  }
281
- tealTemplateCode = tealTemplateCode.replace(new RegExp(types_app.DELETABLE_TEMPLATE_NAME, 'g'), (params.deletable ? 1 : 0).toString());
281
+ tealTemplateCode = replaceTemplateVariable(tealTemplateCode, types_app.DELETABLE_TEMPLATE_NAME, (params.deletable ? 1 : 0).toString());
282
282
  }
283
283
  return tealTemplateCode;
284
284
  }
@@ -302,7 +302,7 @@ class AppManager {
302
302
  tealTemplateCode = tealTemplateCode.replace(new RegExp(`(?<=bytes )${token}`, 'g'), `0x${value.toString(16).padStart(16, '0')}`);
303
303
  // We could probably return here since mixing pushint and pushbytes is likely not going to happen, but might as well do both
304
304
  }
305
- tealTemplateCode = tealTemplateCode.replace(new RegExp(token, 'g'), typeof value === 'string'
305
+ tealTemplateCode = replaceTemplateVariable(tealTemplateCode, token, typeof value === 'string'
306
306
  ? `0x${Buffer.from(value, 'utf-8').toString('hex')}`
307
307
  : ArrayBuffer.isView(value)
308
308
  ? `0x${Buffer.from(value).toString('hex')}`
@@ -318,17 +318,110 @@ class AppManager {
318
318
  * @returns The TEAL without comments
319
319
  */
320
320
  static stripTealComments(tealCode) {
321
- // find // outside quotes, i.e. won't pick up "//not a comment"
322
- const regex = /\/\/(?=([^"\\]*(\\.|"([^"\\]*\\.)*[^"\\]*"))*[^"]*$)/;
323
- tealCode = tealCode
321
+ const stripCommentFromLine = (line) => {
322
+ const commentIndex = findUnquotedString(line, '//');
323
+ if (commentIndex === undefined) {
324
+ return line;
325
+ }
326
+ return line.slice(0, commentIndex).trimEnd();
327
+ };
328
+ return tealCode
324
329
  .split('\n')
325
- .map((tealCodeLine) => {
326
- return tealCodeLine.split(regex)[0].trim();
327
- })
330
+ .map((line) => stripCommentFromLine(line))
328
331
  .join('\n');
329
- return tealCode;
330
332
  }
331
333
  }
334
+ /**
335
+ * Find the first string within a line of TEAL. Only matches outside of quotes and base64 are returned.
336
+ * Returns undefined if not found
337
+ */
338
+ const findUnquotedString = (line, token, startIndex = 0, _endIndex) => {
339
+ const endIndex = _endIndex === undefined ? line.length : _endIndex;
340
+ let index = startIndex;
341
+ let inQuotes = false;
342
+ let inBase64 = false;
343
+ while (index < endIndex) {
344
+ const currentChar = line[index];
345
+ if ((currentChar === ' ' || currentChar === '(') && !inQuotes && lastTokenBase64(line, index)) {
346
+ // enter base64
347
+ inBase64 = true;
348
+ }
349
+ else if ((currentChar === ' ' || currentChar === ')') && !inQuotes && inBase64) {
350
+ // exit base64
351
+ inBase64 = false;
352
+ }
353
+ else if (currentChar === '\\' && inQuotes) {
354
+ // escaped char, skip next character
355
+ index += 1;
356
+ }
357
+ else if (currentChar === '"') {
358
+ // quote boundary
359
+ inQuotes = !inQuotes;
360
+ }
361
+ else if (!inQuotes && !inBase64 && line.startsWith(token, index)) {
362
+ // can test for match
363
+ return index;
364
+ }
365
+ index += 1;
366
+ }
367
+ return undefined;
368
+ };
369
+ const lastTokenBase64 = (line, index) => {
370
+ try {
371
+ const tokens = line.slice(0, index).split(/\s+/);
372
+ const last = tokens[tokens.length - 1];
373
+ return ['base64', 'b64'].includes(last);
374
+ }
375
+ catch {
376
+ return false;
377
+ }
378
+ };
379
+ function replaceTemplateVariable(program, token, replacement) {
380
+ const result = [];
381
+ const tokenIndexOffset = replacement.length - token.length;
382
+ const programLines = program.split('\n');
383
+ for (const line of programLines) {
384
+ const _commentIndex = findUnquotedString(line, '//');
385
+ const commentIndex = _commentIndex === undefined ? line.length : _commentIndex;
386
+ let code = line.substring(0, commentIndex);
387
+ const comment = line.substring(commentIndex);
388
+ let trailingIndex = 0;
389
+ // eslint-disable-next-line no-constant-condition
390
+ while (true) {
391
+ const tokenIndex = findTemplateToken(code, token, trailingIndex);
392
+ if (tokenIndex === undefined) {
393
+ break;
394
+ }
395
+ trailingIndex = tokenIndex + token.length;
396
+ const prefix = code.substring(0, tokenIndex);
397
+ const suffix = code.substring(trailingIndex);
398
+ code = `${prefix}${replacement}${suffix}`;
399
+ trailingIndex += tokenIndexOffset;
400
+ }
401
+ result.push(code + comment);
402
+ }
403
+ return result.join('\n');
404
+ }
405
+ const findTemplateToken = (line, token, startIndex = 0, _endIndex) => {
406
+ const endIndex = line.length ;
407
+ let index = startIndex;
408
+ while (index < endIndex) {
409
+ const tokenIndex = findUnquotedString(line, token, index, endIndex);
410
+ if (tokenIndex === undefined) {
411
+ break;
412
+ }
413
+ const trailingIndex = tokenIndex + token.length;
414
+ if ((tokenIndex === 0 || !isValidTokenCharacter(line[tokenIndex - 1])) &&
415
+ (trailingIndex >= line.length || !isValidTokenCharacter(line[trailingIndex]))) {
416
+ return tokenIndex;
417
+ }
418
+ index = trailingIndex;
419
+ }
420
+ return undefined;
421
+ };
422
+ function isValidTokenCharacter(char) {
423
+ return char.length === 1 && (/\w/.test(char) || char === '_');
424
+ }
332
425
 
333
426
  exports.AppManager = AppManager;
334
427
  //# sourceMappingURL=app-manager.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"app-manager.js","sources":["../../src/types/app-manager.ts"],"sourcesContent":["import algosdk from 'algosdk'\nimport { getABIReturnValue } from '../transaction/transaction'\nimport { TransactionSignerAccount } from './account'\nimport {\n BoxName,\n DELETABLE_TEMPLATE_NAME,\n UPDATABLE_TEMPLATE_NAME,\n type ABIReturn,\n type AppState,\n type CompiledTeal,\n type TealTemplateParams,\n} from './app'\nimport modelsv2 = algosdk.modelsv2\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: string\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: string\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}\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 * * `TransactionSignerAccount` (that will be encoded into the\n * public key address of the corresponding account)\n */\nexport type BoxIdentifier = string | Uint8Array | TransactionSignerAccount\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: algosdk.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: algosdk.ABIType\n}\n\n/** Allows management of application information. */\nexport class AppManager {\n private _algod: algosdk.Algodv2\n private _compilationResults: Record<string, CompiledTeal> = {}\n\n /**\n * Creates an `AppManager`\n * @param algod An algod instance\n */\n constructor(algod: algosdk.Algodv2) {\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 */\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.compile(tealCode).sourcemap(true).do()\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 algosdk.SourceMap(compiled['sourcemap']),\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 */\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 */\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 = modelsv2.Application.from_obj_for_encoding(await this._algod.getApplicationByID(Number(appId)).do())\n return {\n appId: BigInt(app.id),\n appAddress: algosdk.getApplicationAddress(app.id),\n approvalProgram: app.params.approvalProgram,\n clearStateProgram: app.params.clearStateProgram,\n creator: app.params.creator,\n localInts: Number(app.params.localStateSchema?.numUint ?? 0),\n localByteSlices: Number(app.params.localStateSchema?.numByteSlice ?? 0),\n globalInts: Number(app.params.globalStateSchema?.numUint ?? 0),\n globalByteSlices: Number(app.params.globalStateSchema?.numByteSlice ?? 0),\n extraProgramPages: Number(app.params.extraProgramPages ?? 0),\n globalState: AppManager.decodeAppState(app.params.globalState ?? []),\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 */\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 */\n public async getLocalState(appId: bigint, address: string) {\n const appInfo = modelsv2.AccountApplicationResponse.from_obj_for_encoding(\n await this._algod.accountApplicationInformation(address, Number(appId)).do(),\n )\n\n if (!appInfo.appLocalState?.keyValue) {\n throw new Error(\"Couldn't find local state\")\n }\n\n return AppManager.decodeAppState(appInfo.appLocalState.keyValue)\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 */\n public async getBoxNames(appId: bigint): Promise<BoxName[]> {\n const boxResult = await this._algod.getApplicationBoxes(Number(appId)).do()\n return boxResult.boxes.map((b) => {\n return {\n nameRaw: b.name,\n nameBase64: Buffer.from(b.name).toString('base64'),\n name: Buffer.from(b.name).toString('utf-8'),\n }\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 */\n public async getBoxValue(appId: bigint, boxName: BoxIdentifier): Promise<Uint8Array> {\n const name = AppManager.getBoxReference(boxName).name\n const boxResult = await this._algod.getApplicationBoxByName(Number(appId), name).do()\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 */\n public async getBoxValues(appId: bigint, boxNames: BoxIdentifier[]): 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 */\n public async getBoxValueFromABIType(request: BoxValueRequestParams): Promise<algosdk.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 */\n public async getBoxValuesFromABIType(request: BoxValuesRequestParams): Promise<algosdk.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 */\n public static getBoxReference(boxId: BoxIdentifier | BoxReference): algosdk.BoxReference {\n const ref = typeof boxId === 'object' && 'appId' in boxId ? boxId : { appId: 0n, name: boxId }\n return {\n appIndex: Number(ref.appId),\n name:\n typeof ref.name === 'string'\n ? new TextEncoder().encode(ref.name)\n : 'length' in ref.name\n ? ref.name\n : algosdk.decodeAddress(ref.name.addr).publicKey,\n } as algosdk.BoxReference\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 */\n public static decodeAppState(state: { key: string; value: modelsv2.TealValue | modelsv2.EvalDelta }[]): AppState {\n const stateValues = {} as AppState\n\n // Start with empty set\n for (const stateVal of state) {\n const keyBase64 = stateVal.key\n const keyRaw = Buffer.from(keyBase64, 'base64')\n const key = keyRaw.toString('utf-8')\n const tealValue = stateVal.value\n\n const dataTypeFlag = 'action' in tealValue ? tealValue.action : tealValue.type\n let valueBase64: string\n let valueRaw: Buffer\n switch (dataTypeFlag) {\n case 1:\n valueBase64 = tealValue.bytes ?? ''\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] = {\n keyRaw,\n keyBase64,\n value: BigInt(value),\n }\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 */\n public static getABIReturn(\n confirmation: modelsv2.PendingTransactionResponse | undefined,\n method: algosdk.ABIMethod | undefined,\n ): ABIReturn | undefined {\n if (!method || !confirmation || method.returns.type === 'void') {\n return undefined\n }\n\n // The parseMethodResponse method mutates the second parameter :(\n const resultDummy: algosdk.ABIResult = {\n txID: '',\n method,\n rawReturnValue: new Uint8Array(),\n }\n return getABIReturnValue(algosdk.AtomicTransactionComposer.parseMethodResponse(method, resultDummy, confirmation))\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 */\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 = tealTemplateCode.replace(new RegExp(UPDATABLE_TEMPLATE_NAME, 'g'), (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 = tealTemplateCode.replace(new RegExp(DELETABLE_TEMPLATE_NAME, 'g'), (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 */\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 = tealTemplateCode.replace(\n new RegExp(token, 'g'),\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 */\n static stripTealComments(tealCode: string) {\n // find // outside quotes, i.e. won't pick up \"//not a comment\"\n const regex = /\\/\\/(?=([^\"\\\\]*(\\\\.|\"([^\"\\\\]*\\\\.)*[^\"\\\\]*\"))*[^\"]*$)/\n\n tealCode = tealCode\n .split('\\n')\n .map((tealCodeLine) => {\n return tealCodeLine.split(regex)[0].trim()\n })\n .join('\\n')\n\n return tealCode\n }\n}\n"],"names":["getABIReturnValue","UPDATABLE_TEMPLATE_NAME","DELETABLE_TEMPLATE_NAME"],"mappings":";;;;;;AAYA,IAAO,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAA;AAoFlC;MACa,UAAU,CAAA;AAIrB;;;AAGG;AACH,IAAA,WAAA,CAAY,KAAsB,EAAA;QAN1B,IAAmB,CAAA,mBAAA,GAAiC,EAAE,CAAA;AAO5D,QAAA,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;KACpB;AAED;;;;;;;;;;AAUG;IACH,MAAM,WAAW,CAAC,QAAgB,EAAA;AAChC,QAAA,IAAI,IAAI,CAAC,mBAAmB,CAAC,QAAQ,CAAC,EAAE;AACtC,YAAA,OAAO,IAAI,CAAC,mBAAmB,CAAC,QAAQ,CAAC,CAAA;SAC1C;AAED,QAAA,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,CAAA;AACzE,QAAA,MAAM,MAAM,GAAG;AACb,YAAA,IAAI,EAAE,QAAQ;YACd,QAAQ,EAAE,QAAQ,CAAC,MAAM;YACzB,YAAY,EAAE,QAAQ,CAAC,IAAI;AAC3B,YAAA,qBAAqB,EAAE,IAAI,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;YAC7E,SAAS,EAAE,IAAI,OAAO,CAAC,SAAS,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AA;aACF;SACF;AAED,QAAA,OAAO,gBAAgB,CAAA;KACxB;AAED;;;;;AAKG;IACH,OAAO,iBAAiB,CAAC,QAAgB,EAAA;;QAEvC,MAAM,KAAK,GAAG,sDAAsD,CAAA;AAEpE,QAAA,QAAQ,GAAG,QAAQ;aAChB,KAAK,CAAC,IAAI,CAAC;AACX,aAAA,GAAG,CAAC,CAAC,YAAY,KAAI;AACpB,YAAA,OAAO,YAAY,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAA;AAC5C,SAAC,CAAC;aACD,IAAI,CAAC,IAAI,CAAC,CAAA;AAEb,QAAA,OAAO,QAAQ,CAAA;KAChB;AACF;;;;"}
1
+ {"version":3,"file":"app-manager.js","sources":["../../src/types/app-manager.ts"],"sourcesContent":["import algosdk from 'algosdk'\nimport { getABIReturnValue } from '../transaction/transaction'\nimport { TransactionSignerAccount } from './account'\nimport {\n BoxName,\n DELETABLE_TEMPLATE_NAME,\n UPDATABLE_TEMPLATE_NAME,\n type ABIReturn,\n type AppState,\n type CompiledTeal,\n type TealTemplateParams,\n} from './app'\nimport modelsv2 = algosdk.modelsv2\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: string\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: string\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}\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 * * `TransactionSignerAccount` (that will be encoded into the\n * public key address of the corresponding account)\n */\nexport type BoxIdentifier = string | Uint8Array | TransactionSignerAccount\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: algosdk.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: algosdk.ABIType\n}\n\n/** Allows management of application information. */\nexport class AppManager {\n private _algod: algosdk.Algodv2\n private _compilationResults: Record<string, CompiledTeal> = {}\n\n /**\n * Creates an `AppManager`\n * @param algod An algod instance\n */\n constructor(algod: algosdk.Algodv2) {\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 */\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.compile(tealCode).sourcemap(true).do()\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 algosdk.SourceMap(compiled['sourcemap']),\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 */\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 */\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 = modelsv2.Application.from_obj_for_encoding(await this._algod.getApplicationByID(Number(appId)).do())\n return {\n appId: BigInt(app.id),\n appAddress: algosdk.getApplicationAddress(app.id),\n approvalProgram: app.params.approvalProgram,\n clearStateProgram: app.params.clearStateProgram,\n creator: app.params.creator,\n localInts: Number(app.params.localStateSchema?.numUint ?? 0),\n localByteSlices: Number(app.params.localStateSchema?.numByteSlice ?? 0),\n globalInts: Number(app.params.globalStateSchema?.numUint ?? 0),\n globalByteSlices: Number(app.params.globalStateSchema?.numByteSlice ?? 0),\n extraProgramPages: Number(app.params.extraProgramPages ?? 0),\n globalState: AppManager.decodeAppState(app.params.globalState ?? []),\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 */\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 */\n public async getLocalState(appId: bigint, address: string) {\n const appInfo = modelsv2.AccountApplicationResponse.from_obj_for_encoding(\n await this._algod.accountApplicationInformation(address, Number(appId)).do(),\n )\n\n if (!appInfo.appLocalState?.keyValue) {\n throw new Error(\"Couldn't find local state\")\n }\n\n return AppManager.decodeAppState(appInfo.appLocalState.keyValue)\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 */\n public async getBoxNames(appId: bigint): Promise<BoxName[]> {\n const boxResult = await this._algod.getApplicationBoxes(Number(appId)).do()\n return boxResult.boxes.map((b) => {\n return {\n nameRaw: b.name,\n nameBase64: Buffer.from(b.name).toString('base64'),\n name: Buffer.from(b.name).toString('utf-8'),\n }\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 */\n public async getBoxValue(appId: bigint, boxName: BoxIdentifier): Promise<Uint8Array> {\n const name = AppManager.getBoxReference(boxName).name\n const boxResult = await this._algod.getApplicationBoxByName(Number(appId), name).do()\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 */\n public async getBoxValues(appId: bigint, boxNames: BoxIdentifier[]): 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 */\n public async getBoxValueFromABIType(request: BoxValueRequestParams): Promise<algosdk.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 */\n public async getBoxValuesFromABIType(request: BoxValuesRequestParams): Promise<algosdk.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 */\n public static getBoxReference(boxId: BoxIdentifier | BoxReference): algosdk.BoxReference {\n const ref = typeof boxId === 'object' && 'appId' in boxId ? boxId : { appId: 0n, name: boxId }\n return {\n appIndex: Number(ref.appId),\n name:\n typeof ref.name === 'string'\n ? new TextEncoder().encode(ref.name)\n : 'length' in ref.name\n ? ref.name\n : algosdk.decodeAddress(ref.name.addr).publicKey,\n } as algosdk.BoxReference\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 */\n public static decodeAppState(state: { key: string; value: modelsv2.TealValue | modelsv2.EvalDelta }[]): AppState {\n const stateValues = {} as AppState\n\n // Start with empty set\n for (const stateVal of state) {\n const keyBase64 = stateVal.key\n const keyRaw = Buffer.from(keyBase64, 'base64')\n const key = keyRaw.toString('utf-8')\n const tealValue = stateVal.value\n\n const dataTypeFlag = 'action' in tealValue ? tealValue.action : tealValue.type\n let valueBase64: string\n let valueRaw: Buffer\n switch (dataTypeFlag) {\n case 1:\n valueBase64 = tealValue.bytes ?? ''\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] = {\n keyRaw,\n keyBase64,\n value: BigInt(value),\n }\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 */\n public static getABIReturn(\n confirmation: modelsv2.PendingTransactionResponse | undefined,\n method: algosdk.ABIMethod | undefined,\n ): ABIReturn | undefined {\n if (!method || !confirmation || method.returns.type === 'void') {\n return undefined\n }\n\n // The parseMethodResponse method mutates the second parameter :(\n const resultDummy: algosdk.ABIResult = {\n txID: '',\n method,\n rawReturnValue: new Uint8Array(),\n }\n return getABIReturnValue(algosdk.AtomicTransactionComposer.parseMethodResponse(method, resultDummy, confirmation))\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 */\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 */\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 */\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 // eslint-disable-next-line no-constant-condition\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"],"names":["getABIReturnValue","UPDATABLE_TEMPLATE_NAME","DELETABLE_TEMPLATE_NAME"],"mappings":";;;;;;AAYA,IAAO,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAA;AAoFlC;MACa,UAAU,CAAA;AAIrB;;;AAGG;AACH,IAAA,WAAA,CAAY,KAAsB,EAAA;QAN1B,IAAmB,CAAA,mBAAA,GAAiC,EAAE,CAAA;AAO5D,QAAA,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;KACpB;AAED;;;;;;;;;;AAUG;IACH,MAAM,WAAW,CAAC,QAAgB,EAAA;AAChC,QAAA,IAAI,IAAI,CAAC,mBAAmB,CAAC,QAAQ,CAAC,EAAE;AACtC,YAAA,OAAO,IAAI,CAAC,mBAAmB,CAAC,QAAQ,CAAC,CAAA;SAC1C;AAED,QAAA,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,CAAA;AACzE,QAAA,MAAM,MAAM,GAAG;AACb,YAAA,IAAI,EAAE,QAAQ;YACd,QAAQ,EAAE,QAAQ,CAAC,MAAM;YACzB,YAAY,EAAE,QAAQ,CAAC,IAAI;AAC3B,YAAA,qBAAqB,EAAE,IAAI,UAAU,CAAC,MAAM,CAAC,IAAI,CA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QAAQ,CAAC,CAAA;AACnE,QAAA,IAAI,UAAU,KAAK,SAAS,EAAE;YAC5B,MAAK;SACN;AACD,QAAA,MAAM,aAAa,GAAG,UAAU,GAAG,KAAK,CAAC,MAAM,CAAA;AAC/C,QAAA,IACE,CAAC,UAAU,KAAK,CAAC,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,UAAU,GAAG,CAAC,CAAC,CAAC;AACjE,aAAC,aAAa,IAAI,IAAI,CAAC,MAAM,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,EAC7E;AACA,YAAA,OAAO,UAAU,CAAA;SAClB;QACD,KAAK,GAAG,aAAa,CAAA;KACtB;AACD,IAAA,OAAO,SAAS,CAAA;AAClB,CAAC,CAAA;AAED,SAAS,qBAAqB,CAAC,IAAY,EAAA;AACzC,IAAA,OAAO,IAAI,CAAC,MAAM,KAAK,CAAC,KAAK,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,IAAI,KAAK,GAAG,CAAC,CAAA;AAC/D;;;;"}
@@ -270,13 +270,13 @@ class AppManager {
270
270
  if (!tealTemplateCode.includes(UPDATABLE_TEMPLATE_NAME)) {
271
271
  throw new Error(`Deploy-time updatability control requested for app deployment, but ${UPDATABLE_TEMPLATE_NAME} not present in TEAL code`);
272
272
  }
273
- tealTemplateCode = tealTemplateCode.replace(new RegExp(UPDATABLE_TEMPLATE_NAME, 'g'), (params.updatable ? 1 : 0).toString());
273
+ tealTemplateCode = replaceTemplateVariable(tealTemplateCode, UPDATABLE_TEMPLATE_NAME, (params.updatable ? 1 : 0).toString());
274
274
  }
275
275
  if (params.deletable !== undefined) {
276
276
  if (!tealTemplateCode.includes(DELETABLE_TEMPLATE_NAME)) {
277
277
  throw new Error(`Deploy-time deletability control requested for app deployment, but ${DELETABLE_TEMPLATE_NAME} not present in TEAL code`);
278
278
  }
279
- tealTemplateCode = tealTemplateCode.replace(new RegExp(DELETABLE_TEMPLATE_NAME, 'g'), (params.deletable ? 1 : 0).toString());
279
+ tealTemplateCode = replaceTemplateVariable(tealTemplateCode, DELETABLE_TEMPLATE_NAME, (params.deletable ? 1 : 0).toString());
280
280
  }
281
281
  return tealTemplateCode;
282
282
  }
@@ -300,7 +300,7 @@ class AppManager {
300
300
  tealTemplateCode = tealTemplateCode.replace(new RegExp(`(?<=bytes )${token}`, 'g'), `0x${value.toString(16).padStart(16, '0')}`);
301
301
  // We could probably return here since mixing pushint and pushbytes is likely not going to happen, but might as well do both
302
302
  }
303
- tealTemplateCode = tealTemplateCode.replace(new RegExp(token, 'g'), typeof value === 'string'
303
+ tealTemplateCode = replaceTemplateVariable(tealTemplateCode, token, typeof value === 'string'
304
304
  ? `0x${Buffer.from(value, 'utf-8').toString('hex')}`
305
305
  : ArrayBuffer.isView(value)
306
306
  ? `0x${Buffer.from(value).toString('hex')}`
@@ -316,17 +316,110 @@ class AppManager {
316
316
  * @returns The TEAL without comments
317
317
  */
318
318
  static stripTealComments(tealCode) {
319
- // find // outside quotes, i.e. won't pick up "//not a comment"
320
- const regex = /\/\/(?=([^"\\]*(\\.|"([^"\\]*\\.)*[^"\\]*"))*[^"]*$)/;
321
- tealCode = tealCode
319
+ const stripCommentFromLine = (line) => {
320
+ const commentIndex = findUnquotedString(line, '//');
321
+ if (commentIndex === undefined) {
322
+ return line;
323
+ }
324
+ return line.slice(0, commentIndex).trimEnd();
325
+ };
326
+ return tealCode
322
327
  .split('\n')
323
- .map((tealCodeLine) => {
324
- return tealCodeLine.split(regex)[0].trim();
325
- })
328
+ .map((line) => stripCommentFromLine(line))
326
329
  .join('\n');
327
- return tealCode;
328
330
  }
329
331
  }
332
+ /**
333
+ * Find the first string within a line of TEAL. Only matches outside of quotes and base64 are returned.
334
+ * Returns undefined if not found
335
+ */
336
+ const findUnquotedString = (line, token, startIndex = 0, _endIndex) => {
337
+ const endIndex = _endIndex === undefined ? line.length : _endIndex;
338
+ let index = startIndex;
339
+ let inQuotes = false;
340
+ let inBase64 = false;
341
+ while (index < endIndex) {
342
+ const currentChar = line[index];
343
+ if ((currentChar === ' ' || currentChar === '(') && !inQuotes && lastTokenBase64(line, index)) {
344
+ // enter base64
345
+ inBase64 = true;
346
+ }
347
+ else if ((currentChar === ' ' || currentChar === ')') && !inQuotes && inBase64) {
348
+ // exit base64
349
+ inBase64 = false;
350
+ }
351
+ else if (currentChar === '\\' && inQuotes) {
352
+ // escaped char, skip next character
353
+ index += 1;
354
+ }
355
+ else if (currentChar === '"') {
356
+ // quote boundary
357
+ inQuotes = !inQuotes;
358
+ }
359
+ else if (!inQuotes && !inBase64 && line.startsWith(token, index)) {
360
+ // can test for match
361
+ return index;
362
+ }
363
+ index += 1;
364
+ }
365
+ return undefined;
366
+ };
367
+ const lastTokenBase64 = (line, index) => {
368
+ try {
369
+ const tokens = line.slice(0, index).split(/\s+/);
370
+ const last = tokens[tokens.length - 1];
371
+ return ['base64', 'b64'].includes(last);
372
+ }
373
+ catch {
374
+ return false;
375
+ }
376
+ };
377
+ function replaceTemplateVariable(program, token, replacement) {
378
+ const result = [];
379
+ const tokenIndexOffset = replacement.length - token.length;
380
+ const programLines = program.split('\n');
381
+ for (const line of programLines) {
382
+ const _commentIndex = findUnquotedString(line, '//');
383
+ const commentIndex = _commentIndex === undefined ? line.length : _commentIndex;
384
+ let code = line.substring(0, commentIndex);
385
+ const comment = line.substring(commentIndex);
386
+ let trailingIndex = 0;
387
+ // eslint-disable-next-line no-constant-condition
388
+ while (true) {
389
+ const tokenIndex = findTemplateToken(code, token, trailingIndex);
390
+ if (tokenIndex === undefined) {
391
+ break;
392
+ }
393
+ trailingIndex = tokenIndex + token.length;
394
+ const prefix = code.substring(0, tokenIndex);
395
+ const suffix = code.substring(trailingIndex);
396
+ code = `${prefix}${replacement}${suffix}`;
397
+ trailingIndex += tokenIndexOffset;
398
+ }
399
+ result.push(code + comment);
400
+ }
401
+ return result.join('\n');
402
+ }
403
+ const findTemplateToken = (line, token, startIndex = 0, _endIndex) => {
404
+ const endIndex = line.length ;
405
+ let index = startIndex;
406
+ while (index < endIndex) {
407
+ const tokenIndex = findUnquotedString(line, token, index, endIndex);
408
+ if (tokenIndex === undefined) {
409
+ break;
410
+ }
411
+ const trailingIndex = tokenIndex + token.length;
412
+ if ((tokenIndex === 0 || !isValidTokenCharacter(line[tokenIndex - 1])) &&
413
+ (trailingIndex >= line.length || !isValidTokenCharacter(line[trailingIndex]))) {
414
+ return tokenIndex;
415
+ }
416
+ index = trailingIndex;
417
+ }
418
+ return undefined;
419
+ };
420
+ function isValidTokenCharacter(char) {
421
+ return char.length === 1 && (/\w/.test(char) || char === '_');
422
+ }
330
423
 
331
424
  export { AppManager };
332
425
  //# sourceMappingURL=app-manager.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"app-manager.mjs","sources":["../../src/types/app-manager.ts"],"sourcesContent":["import algosdk from 'algosdk'\nimport { getABIReturnValue } from '../transaction/transaction'\nimport { TransactionSignerAccount } from './account'\nimport {\n BoxName,\n DELETABLE_TEMPLATE_NAME,\n UPDATABLE_TEMPLATE_NAME,\n type ABIReturn,\n type AppState,\n type CompiledTeal,\n type TealTemplateParams,\n} from './app'\nimport modelsv2 = algosdk.modelsv2\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: string\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: string\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}\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 * * `TransactionSignerAccount` (that will be encoded into the\n * public key address of the corresponding account)\n */\nexport type BoxIdentifier = string | Uint8Array | TransactionSignerAccount\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: algosdk.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: algosdk.ABIType\n}\n\n/** Allows management of application information. */\nexport class AppManager {\n private _algod: algosdk.Algodv2\n private _compilationResults: Record<string, CompiledTeal> = {}\n\n /**\n * Creates an `AppManager`\n * @param algod An algod instance\n */\n constructor(algod: algosdk.Algodv2) {\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 */\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.compile(tealCode).sourcemap(true).do()\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 algosdk.SourceMap(compiled['sourcemap']),\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 */\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 */\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 = modelsv2.Application.from_obj_for_encoding(await this._algod.getApplicationByID(Number(appId)).do())\n return {\n appId: BigInt(app.id),\n appAddress: algosdk.getApplicationAddress(app.id),\n approvalProgram: app.params.approvalProgram,\n clearStateProgram: app.params.clearStateProgram,\n creator: app.params.creator,\n localInts: Number(app.params.localStateSchema?.numUint ?? 0),\n localByteSlices: Number(app.params.localStateSchema?.numByteSlice ?? 0),\n globalInts: Number(app.params.globalStateSchema?.numUint ?? 0),\n globalByteSlices: Number(app.params.globalStateSchema?.numByteSlice ?? 0),\n extraProgramPages: Number(app.params.extraProgramPages ?? 0),\n globalState: AppManager.decodeAppState(app.params.globalState ?? []),\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 */\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 */\n public async getLocalState(appId: bigint, address: string) {\n const appInfo = modelsv2.AccountApplicationResponse.from_obj_for_encoding(\n await this._algod.accountApplicationInformation(address, Number(appId)).do(),\n )\n\n if (!appInfo.appLocalState?.keyValue) {\n throw new Error(\"Couldn't find local state\")\n }\n\n return AppManager.decodeAppState(appInfo.appLocalState.keyValue)\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 */\n public async getBoxNames(appId: bigint): Promise<BoxName[]> {\n const boxResult = await this._algod.getApplicationBoxes(Number(appId)).do()\n return boxResult.boxes.map((b) => {\n return {\n nameRaw: b.name,\n nameBase64: Buffer.from(b.name).toString('base64'),\n name: Buffer.from(b.name).toString('utf-8'),\n }\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 */\n public async getBoxValue(appId: bigint, boxName: BoxIdentifier): Promise<Uint8Array> {\n const name = AppManager.getBoxReference(boxName).name\n const boxResult = await this._algod.getApplicationBoxByName(Number(appId), name).do()\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 */\n public async getBoxValues(appId: bigint, boxNames: BoxIdentifier[]): 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 */\n public async getBoxValueFromABIType(request: BoxValueRequestParams): Promise<algosdk.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 */\n public async getBoxValuesFromABIType(request: BoxValuesRequestParams): Promise<algosdk.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 */\n public static getBoxReference(boxId: BoxIdentifier | BoxReference): algosdk.BoxReference {\n const ref = typeof boxId === 'object' && 'appId' in boxId ? boxId : { appId: 0n, name: boxId }\n return {\n appIndex: Number(ref.appId),\n name:\n typeof ref.name === 'string'\n ? new TextEncoder().encode(ref.name)\n : 'length' in ref.name\n ? ref.name\n : algosdk.decodeAddress(ref.name.addr).publicKey,\n } as algosdk.BoxReference\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 */\n public static decodeAppState(state: { key: string; value: modelsv2.TealValue | modelsv2.EvalDelta }[]): AppState {\n const stateValues = {} as AppState\n\n // Start with empty set\n for (const stateVal of state) {\n const keyBase64 = stateVal.key\n const keyRaw = Buffer.from(keyBase64, 'base64')\n const key = keyRaw.toString('utf-8')\n const tealValue = stateVal.value\n\n const dataTypeFlag = 'action' in tealValue ? tealValue.action : tealValue.type\n let valueBase64: string\n let valueRaw: Buffer\n switch (dataTypeFlag) {\n case 1:\n valueBase64 = tealValue.bytes ?? ''\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] = {\n keyRaw,\n keyBase64,\n value: BigInt(value),\n }\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 */\n public static getABIReturn(\n confirmation: modelsv2.PendingTransactionResponse | undefined,\n method: algosdk.ABIMethod | undefined,\n ): ABIReturn | undefined {\n if (!method || !confirmation || method.returns.type === 'void') {\n return undefined\n }\n\n // The parseMethodResponse method mutates the second parameter :(\n const resultDummy: algosdk.ABIResult = {\n txID: '',\n method,\n rawReturnValue: new Uint8Array(),\n }\n return getABIReturnValue(algosdk.AtomicTransactionComposer.parseMethodResponse(method, resultDummy, confirmation))\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 */\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 = tealTemplateCode.replace(new RegExp(UPDATABLE_TEMPLATE_NAME, 'g'), (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 = tealTemplateCode.replace(new RegExp(DELETABLE_TEMPLATE_NAME, 'g'), (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 */\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 = tealTemplateCode.replace(\n new RegExp(token, 'g'),\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 */\n static stripTealComments(tealCode: string) {\n // find // outside quotes, i.e. won't pick up \"//not a comment\"\n const regex = /\\/\\/(?=([^\"\\\\]*(\\\\.|\"([^\"\\\\]*\\\\.)*[^\"\\\\]*\"))*[^\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;AACpB,YAAA,OAAO,YAAY,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAA;AAC5C,SAAC,CAAC;aACD,IAAI,CAAC,IAAI,CAAC,CAAA;AAEb,QAAA,OAAO,QAAQ,CAAA;KAChB;AACF;;;;"}
1
+ {"version":3,"file":"app-manager.mjs","sources":["../../src/types/app-manager.ts"],"sourcesContent":["import algosdk from 'algosdk'\nimport { getABIReturnValue } from '../transaction/transaction'\nimport { TransactionSignerAccount } from './account'\nimport {\n BoxName,\n DELETABLE_TEMPLATE_NAME,\n UPDATABLE_TEMPLATE_NAME,\n type ABIReturn,\n type AppState,\n type CompiledTeal,\n type TealTemplateParams,\n} from './app'\nimport modelsv2 = algosdk.modelsv2\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: string\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: string\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}\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 * * `TransactionSignerAccount` (that will be encoded into the\n * public key address of the corresponding account)\n */\nexport type BoxIdentifier = string | Uint8Array | TransactionSignerAccount\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: algosdk.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: algosdk.ABIType\n}\n\n/** Allows management of application information. */\nexport class AppManager {\n private _algod: algosdk.Algodv2\n private _compilationResults: Record<string, CompiledTeal> = {}\n\n /**\n * Creates an `AppManager`\n * @param algod An algod instance\n */\n constructor(algod: algosdk.Algodv2) {\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 */\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.compile(tealCode).sourcemap(true).do()\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 algosdk.SourceMap(compiled['sourcemap']),\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 */\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 */\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 = modelsv2.Application.from_obj_for_encoding(await this._algod.getApplicationByID(Number(appId)).do())\n return {\n appId: BigInt(app.id),\n appAddress: algosdk.getApplicationAddress(app.id),\n approvalProgram: app.params.approvalProgram,\n clearStateProgram: app.params.clearStateProgram,\n creator: app.params.creator,\n localInts: Number(app.params.localStateSchema?.numUint ?? 0),\n localByteSlices: Number(app.params.localStateSchema?.numByteSlice ?? 0),\n globalInts: Number(app.params.globalStateSchema?.numUint ?? 0),\n globalByteSlices: Number(app.params.globalStateSchema?.numByteSlice ?? 0),\n extraProgramPages: Number(app.params.extraProgramPages ?? 0),\n globalState: AppManager.decodeAppState(app.params.globalState ?? []),\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 */\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 */\n public async getLocalState(appId: bigint, address: string) {\n const appInfo = modelsv2.AccountApplicationResponse.from_obj_for_encoding(\n await this._algod.accountApplicationInformation(address, Number(appId)).do(),\n )\n\n if (!appInfo.appLocalState?.keyValue) {\n throw new Error(\"Couldn't find local state\")\n }\n\n return AppManager.decodeAppState(appInfo.appLocalState.keyValue)\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 */\n public async getBoxNames(appId: bigint): Promise<BoxName[]> {\n const boxResult = await this._algod.getApplicationBoxes(Number(appId)).do()\n return boxResult.boxes.map((b) => {\n return {\n nameRaw: b.name,\n nameBase64: Buffer.from(b.name).toString('base64'),\n name: Buffer.from(b.name).toString('utf-8'),\n }\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 */\n public async getBoxValue(appId: bigint, boxName: BoxIdentifier): Promise<Uint8Array> {\n const name = AppManager.getBoxReference(boxName).name\n const boxResult = await this._algod.getApplicationBoxByName(Number(appId), name).do()\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 */\n public async getBoxValues(appId: bigint, boxNames: BoxIdentifier[]): 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 */\n public async getBoxValueFromABIType(request: BoxValueRequestParams): Promise<algosdk.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 */\n public async getBoxValuesFromABIType(request: BoxValuesRequestParams): Promise<algosdk.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 */\n public static getBoxReference(boxId: BoxIdentifier | BoxReference): algosdk.BoxReference {\n const ref = typeof boxId === 'object' && 'appId' in boxId ? boxId : { appId: 0n, name: boxId }\n return {\n appIndex: Number(ref.appId),\n name:\n typeof ref.name === 'string'\n ? new TextEncoder().encode(ref.name)\n : 'length' in ref.name\n ? ref.name\n : algosdk.decodeAddress(ref.name.addr).publicKey,\n } as algosdk.BoxReference\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 */\n public static decodeAppState(state: { key: string; value: modelsv2.TealValue | modelsv2.EvalDelta }[]): AppState {\n const stateValues = {} as AppState\n\n // Start with empty set\n for (const stateVal of state) {\n const keyBase64 = stateVal.key\n const keyRaw = Buffer.from(keyBase64, 'base64')\n const key = keyRaw.toString('utf-8')\n const tealValue = stateVal.value\n\n const dataTypeFlag = 'action' in tealValue ? tealValue.action : tealValue.type\n let valueBase64: string\n let valueRaw: Buffer\n switch (dataTypeFlag) {\n case 1:\n valueBase64 = tealValue.bytes ?? ''\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] = {\n keyRaw,\n keyBase64,\n value: BigInt(value),\n }\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 */\n public static getABIReturn(\n confirmation: modelsv2.PendingTransactionResponse | undefined,\n method: algosdk.ABIMethod | undefined,\n ): ABIReturn | undefined {\n if (!method || !confirmation || method.returns.type === 'void') {\n return undefined\n }\n\n // The parseMethodResponse method mutates the second parameter :(\n const resultDummy: algosdk.ABIResult = {\n txID: '',\n method,\n rawReturnValue: new Uint8Array(),\n }\n return getABIReturnValue(algosdk.AtomicTransactionComposer.parseMethodResponse(method, resultDummy, confirmation))\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 */\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 */\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 */\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 // eslint-disable-next-line no-constant-condition\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"],"names":[],"mappings":";;;;AAYA,IAAO,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAA;AAoFlC;MACa,UAAU,CAAA;AAIrB;;;AAGG;AACH,IAAA,WAAA,CAAY,KAAsB,EAAA;QAN1B,IAAmB,CAAA,mBAAA,GAAiC,EAAE,CAAA;AAO5D,QAAA,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;KACpB;AAED;;;;;;;;;;AAUG;IACH,MAAM,WAAW,CAAC,QAAgB,EAAA;AAChC,QAAA,IAAI,IAAI,CAAC,mBAAmB,CAAC,QAAQ,CAAC,EAAE;AACtC,YAAA,OAAO,IAAI,CAAC,mBAAmB,CAAC,QAAQ,CAAC,CAAA;SAC1C;AAED,QAAA,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,CAAA;AACzE,QAAA,MAAM,MAAM,GAAG;AACb,YAAA,IAAI,EAAE,QAAQ;YACd,QAAQ,EAAE,QAAQ,CAAC,MAAM;YACzB,YAAY,EAAE,QAAQ,CAAC,IAAI;AAC3B,YAAA,qBAAqB,EAAE,IAAI,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;YAC7E,SAAS,EAAE,IAAI,OAAO,CAAC,SAAS,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;SACxD,CAAA;AACD,QAAA,IAAI,CAAC,mBAAmB,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAA;AAE3C,QAAA,OAAO,MAAM,CAAA;KACd;AAED;;;;;;;;;;;;;AAaG;AACH,IAAA,MAAM,mBAAmB,CACvB,gBAA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