@algorandfoundation/algorand-typescript-testing 1.0.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/abi-metadata.d.ts +16 -0
  2. package/collections/custom-key-map.d.ts +29 -0
  3. package/constants.d.ts +27 -0
  4. package/context-helpers/internal-context.d.ts +26 -0
  5. package/decode-logs.d.ts +9 -0
  6. package/encoders.d.ts +9 -0
  7. package/errors.d.ts +5 -0
  8. package/impl/account.d.ts +32 -0
  9. package/impl/acct-params.d.ts +5 -0
  10. package/impl/app-global.d.ts +2 -0
  11. package/impl/app-local.d.ts +2 -0
  12. package/impl/app-params.d.ts +3 -0
  13. package/impl/application.d.ts +30 -0
  14. package/impl/asset-holding.d.ts +2 -0
  15. package/impl/asset-params.d.ts +3 -0
  16. package/impl/asset.d.ts +24 -0
  17. package/impl/base.d.ts +18 -0
  18. package/impl/block.d.ts +2 -0
  19. package/impl/box.d.ts +2 -0
  20. package/impl/crypto.d.ts +12 -0
  21. package/impl/encoded-types.d.ts +165 -0
  22. package/impl/global.d.ts +18 -0
  23. package/impl/gtxn.d.ts +2 -0
  24. package/impl/index.d.ts +15 -0
  25. package/impl/inner-transactions.d.ts +51 -0
  26. package/impl/itxn.d.ts +8 -0
  27. package/impl/pure.d.ts +32 -0
  28. package/impl/scratch.d.ts +4 -0
  29. package/impl/state.d.ts +103 -0
  30. package/impl/transactions.d.ts +140 -0
  31. package/impl/txn.d.ts +3 -0
  32. package/index.d.ts +1 -0
  33. package/index.mjs +4563 -0
  34. package/index.mjs.map +1 -0
  35. package/package.json +45 -0
  36. package/runtime-helpers-DlIX78iw.js +1426 -0
  37. package/runtime-helpers-DlIX78iw.js.map +1 -0
  38. package/runtime-helpers.d.ts +11 -0
  39. package/runtime-helpers.mjs +8 -0
  40. package/runtime-helpers.mjs.map +1 -0
  41. package/set-up.d.ts +11 -0
  42. package/subcontexts/contract-context.d.ts +9 -0
  43. package/subcontexts/ledger-context.d.ts +45 -0
  44. package/subcontexts/transaction-context.d.ts +67 -0
  45. package/test-execution-context.d.ts +53 -0
  46. package/test-transformer/errors.d.ts +3 -0
  47. package/test-transformer/helpers.d.ts +3 -0
  48. package/test-transformer/index.d.ts +6 -0
  49. package/test-transformer/index.mjs +458 -0
  50. package/test-transformer/index.mjs.map +1 -0
  51. package/test-transformer/node-factory.d.ts +14 -0
  52. package/test-transformer/supported-binary-op-string.d.ts +4 -0
  53. package/test-transformer/visitors.d.ts +11 -0
  54. package/typescript-helpers.d.ts +15 -0
  55. package/util.d.ts +29 -0
  56. package/value-generators/avm.d.ts +23 -0
  57. package/value-generators/index.d.ts +6 -0
  58. package/value-generators/txn.d.ts +10 -0
package/index.mjs ADDED
@@ -0,0 +1,4563 @@
1
+ import { internal, Bytes, Uint64, Account, arc4, Ecdsa, op, Base64, TransactionType, Asset, Application, BigUint, BaseContract, Contract } from '@algorandfoundation/algorand-typescript';
2
+ import algosdk from 'algosdk';
3
+ import { a as asMaybeUint64Cls, b as asUint64, c as asBytes, d as asNumber, M as MAX_BOX_SIZE, t as toBytes, e as asBytesCls, f as asUint8Array, g as conactUint8Arrays, L as LOGIC_DATA_PREFIX, h as asBigInt, i as getObjectReference, j as MIN_TXN_FEE, D as DEFAULT_ACCOUNT_MIN_BALANCE, k as DEFAULT_MAX_TXN_LIFE, Z as ZERO_ADDRESS, l as DEFAULT_ASSET_CREATE_MIN_BALANCE, m as DEFAULT_ASSET_OPT_IN_MIN_BALANCE, n as DEFAULT_GLOBAL_GENESIS_HASH, o as asUint64Cls, p as asMaybeBytesCls, q as asBigUint, B as BITS_IN_BYTE, r as MAX_BYTES_SIZE, s as MAX_UINT8, u as binaryStringToBytes, U as UINT64_SIZE, v as MAX_UINT64, w as Uint64BackedCls, A as ALWAYS_APPROVE_TEAL_PROGRAM, x as BytesBackedCls, y as combineIntoMaxBytePages, z as MAX_ITEMS_IN_LOG, C as ABI_RETURN_VALUE_LOG_PREFIX, E as getRandomBytes, F as getArc4Encoder, G as arc4Encoders, H as getGenericTypeInfo, I as getAbiMetadata, J as iterBigInt, K as getRandomBigInt, N as captureMethodConfig } from './runtime-helpers-DlIX78iw.js';
4
+ import { ec } from 'elliptic';
5
+ import { sha256 as sha256$1 } from 'js-sha256';
6
+ import { sha3_256 as sha3_256$1, keccak256 as keccak256$1 } from 'js-sha3';
7
+ import { sha512_256 as sha512_256$1 } from 'js-sha512';
8
+ import nacl from 'tweetnacl';
9
+ import { randomBytes } from 'crypto';
10
+ import '@algorandfoundation/algorand-typescript/arc4';
11
+ import '@algorandfoundation/puya-ts';
12
+ import 'assert';
13
+
14
+ /**
15
+ * For accessing implementation specific functions, with a convenient single entry
16
+ * point for other modules to import Also allows for a single place to check and
17
+ * provide.
18
+ */
19
+ class InternalContext {
20
+ get value() {
21
+ return internal.ctxMgr.instance;
22
+ }
23
+ get defaultSender() {
24
+ return this.value.defaultSender;
25
+ }
26
+ get ledger() {
27
+ return this.value.ledger;
28
+ }
29
+ get txn() {
30
+ return this.value.txn;
31
+ }
32
+ get contract() {
33
+ return this.value.contract;
34
+ }
35
+ get any() {
36
+ return this.value.any;
37
+ }
38
+ get activeApplication() {
39
+ return this.ledger.getApplication(this.activeGroup.activeApplicationId);
40
+ }
41
+ get activeGroup() {
42
+ return this.value.txn.activeGroup;
43
+ }
44
+ getAccountData(account) {
45
+ const data = this.ledger.accountDataMap.get(account);
46
+ if (!data) {
47
+ throw internal.errors.internalError('Unknown account, check correct testing context is active');
48
+ }
49
+ return data;
50
+ }
51
+ getAssetData(id) {
52
+ const key = internal.primitives.Uint64Cls.fromCompat(id);
53
+ const data = this.ledger.assetDataMap.get(key.asBigInt());
54
+ if (!data) {
55
+ throw internal.errors.internalError('Unknown asset, check correct testing context is active');
56
+ }
57
+ return data;
58
+ }
59
+ getApplicationData(id) {
60
+ const data = this.ledger.applicationDataMap.get(id);
61
+ if (!data) {
62
+ throw internal.errors.internalError('Unknown application, check correct testing context is active');
63
+ }
64
+ return data;
65
+ }
66
+ }
67
+ const lazyContext = new InternalContext();
68
+
69
+ const getAccount = (acct) => {
70
+ const acctId = asMaybeUint64Cls(acct);
71
+ if (acctId !== undefined) {
72
+ const activeTxn = lazyContext.activeGroup.activeTransaction;
73
+ return activeTxn.accounts(acctId.asAlgoTs());
74
+ }
75
+ return acct;
76
+ };
77
+ const balance = (a) => {
78
+ const acct = getAccount(a);
79
+ return acct.balance;
80
+ };
81
+ const minBalance = (a) => {
82
+ const acct = getAccount(a);
83
+ return acct.minBalance;
84
+ };
85
+ const AcctParams = {
86
+ acctBalance(a) {
87
+ const acct = getAccount(a);
88
+ return [acct.balance, acct.balance !== 0];
89
+ },
90
+ acctMinBalance(a) {
91
+ const acct = getAccount(a);
92
+ return [acct.minBalance, acct.balance !== 0];
93
+ },
94
+ acctAuthAddr(a) {
95
+ const acct = getAccount(a);
96
+ return [acct.authAddress, acct.balance !== 0];
97
+ },
98
+ acctTotalNumUint(a) {
99
+ const acct = getAccount(a);
100
+ return [acct.totalNumUint, acct.balance !== 0];
101
+ },
102
+ acctTotalNumByteSlice(a) {
103
+ const acct = getAccount(a);
104
+ return [acct.totalNumByteSlice, acct.balance !== 0];
105
+ },
106
+ acctTotalExtraAppPages(a) {
107
+ const acct = getAccount(a);
108
+ return [acct.totalExtraAppPages, acct.balance !== 0];
109
+ },
110
+ acctTotalAppsCreated(a) {
111
+ const acct = getAccount(a);
112
+ return [acct.totalAppsCreated, acct.balance !== 0];
113
+ },
114
+ acctTotalAppsOptedIn(a) {
115
+ const acct = getAccount(a);
116
+ return [acct.totalAppsOptedIn, acct.balance !== 0];
117
+ },
118
+ acctTotalAssetsCreated(a) {
119
+ const acct = getAccount(a);
120
+ return [acct.totalAssetsCreated, acct.balance !== 0];
121
+ },
122
+ acctTotalAssets(a) {
123
+ const acct = getAccount(a);
124
+ return [acct.totalAssets, acct.balance !== 0];
125
+ },
126
+ acctTotalBoxes(a) {
127
+ const acct = getAccount(a);
128
+ return [acct.totalBoxes, acct.balance !== 0];
129
+ },
130
+ acctTotalBoxBytes(a) {
131
+ const acct = getAccount(a);
132
+ return [acct.totalBoxBytes, acct.balance !== 0];
133
+ },
134
+ // TODO: implement v11 methods
135
+ acctIncentiveEligible: function (_a) {
136
+ throw new Error('Function not implemented.');
137
+ },
138
+ acctLastProposed: function (_a) {
139
+ throw new Error('Function not implemented.');
140
+ },
141
+ acctLastHeartbeat: function (_a) {
142
+ throw new Error('Function not implemented.');
143
+ },
144
+ };
145
+
146
+ const resolveAppIndex = (appIdOrIndex) => {
147
+ const input = asUint64(appIdOrIndex);
148
+ if (input >= 1001) {
149
+ return input;
150
+ }
151
+ const txn = lazyContext.activeGroup.activeTransaction;
152
+ return txn.apps(input).id;
153
+ };
154
+ const getApp = (app) => {
155
+ try {
156
+ const appId = asMaybeUint64Cls(app);
157
+ if (appId !== undefined) {
158
+ return lazyContext.ledger.getApplication(resolveAppIndex(appId));
159
+ }
160
+ return app;
161
+ }
162
+ catch {
163
+ return undefined;
164
+ }
165
+ };
166
+ const AppParams = {
167
+ appApprovalProgram(a) {
168
+ const app = getApp(a);
169
+ return app === undefined ? [Bytes(), false] : [app.approvalProgram, true];
170
+ },
171
+ appClearStateProgram(a) {
172
+ const app = getApp(a);
173
+ return app === undefined ? [Bytes(), false] : [app.clearStateProgram, true];
174
+ },
175
+ appGlobalNumUint(a) {
176
+ const app = getApp(a);
177
+ return app === undefined ? [Uint64(0), false] : [app.globalNumUint, true];
178
+ },
179
+ appGlobalNumByteSlice(a) {
180
+ const app = getApp(a);
181
+ return app === undefined ? [Uint64(0), false] : [app.globalNumBytes, true];
182
+ },
183
+ appLocalNumUint(a) {
184
+ const app = getApp(a);
185
+ return app === undefined ? [Uint64(0), false] : [app.localNumUint, true];
186
+ },
187
+ appLocalNumByteSlice(a) {
188
+ const app = getApp(a);
189
+ return app === undefined ? [Uint64(0), false] : [app.localNumBytes, true];
190
+ },
191
+ appExtraProgramPages(a) {
192
+ const app = getApp(a);
193
+ return app === undefined ? [Uint64(0), false] : [app.extraProgramPages, true];
194
+ },
195
+ appCreator(a) {
196
+ const app = getApp(a);
197
+ return app === undefined ? [Account(), false] : [app.creator, true];
198
+ },
199
+ appAddress(a) {
200
+ const app = getApp(a);
201
+ return app === undefined ? [Account(), false] : [app.address, true];
202
+ },
203
+ };
204
+
205
+ const AppGlobal = {
206
+ delete(a) {
207
+ lazyContext.ledger.setGlobalState(lazyContext.activeApplication, a, undefined);
208
+ },
209
+ getBytes(a) {
210
+ return this.getExBytes(0, asBytes(a))[0];
211
+ },
212
+ getUint64(a) {
213
+ return this.getExUint64(0, asBytes(a))[0];
214
+ },
215
+ getExBytes(a, b) {
216
+ const app = getApp(a);
217
+ if (app === undefined) {
218
+ return [Bytes(), false];
219
+ }
220
+ const [state, exists] = lazyContext.ledger.getGlobalState(app, b);
221
+ if (!exists) {
222
+ return [Bytes(), false];
223
+ }
224
+ return [state.value, exists];
225
+ },
226
+ getExUint64(a, b) {
227
+ const app = getApp(a);
228
+ if (app === undefined) {
229
+ return [Uint64(0), false];
230
+ }
231
+ const [state, exists] = lazyContext.ledger.getGlobalState(app, b);
232
+ if (!exists) {
233
+ return [Uint64(0), false];
234
+ }
235
+ return [state.value, exists];
236
+ },
237
+ put(a, b) {
238
+ lazyContext.ledger.setGlobalState(lazyContext.activeApplication, a, b);
239
+ },
240
+ };
241
+
242
+ const AppLocal = {
243
+ delete: function (a, b) {
244
+ const app = lazyContext.activeApplication;
245
+ const account = getAccount(a);
246
+ lazyContext.ledger.setLocalState(app, account, b, undefined);
247
+ },
248
+ getBytes: function (a, b) {
249
+ const account = getAccount(a);
250
+ return this.getExBytes(account, 0, asBytes(b))[0];
251
+ },
252
+ getUint64: function (a, b) {
253
+ const account = getAccount(a);
254
+ return this.getExUint64(account, 0, asBytes(b))[0];
255
+ },
256
+ getExBytes: function (a, b, c) {
257
+ const app = getApp(b);
258
+ const account = getAccount(a);
259
+ if (app === undefined || account === undefined) {
260
+ return [Bytes(), false];
261
+ }
262
+ const [state, exists] = lazyContext.ledger.getLocalState(app, account, c);
263
+ if (!exists) {
264
+ return [Bytes(), false];
265
+ }
266
+ return [state.value, exists];
267
+ },
268
+ getExUint64: function (a, b, c) {
269
+ const app = getApp(b);
270
+ const account = getAccount(a);
271
+ if (app === undefined || account === undefined) {
272
+ return [Uint64(0), false];
273
+ }
274
+ const [state, exists] = lazyContext.ledger.getLocalState(app, account, c);
275
+ if (!exists) {
276
+ return [Uint64(0), false];
277
+ }
278
+ return [state.value, exists];
279
+ },
280
+ put: function (a, b, c) {
281
+ const app = lazyContext.activeApplication;
282
+ const account = getAccount(a);
283
+ lazyContext.ledger.setLocalState(app, account, b, c);
284
+ },
285
+ };
286
+
287
+ const resolveAssetIndex = (assetIdOrIndex) => {
288
+ const input = asUint64(assetIdOrIndex);
289
+ if (input >= 1001) {
290
+ return input;
291
+ }
292
+ const txn = lazyContext.activeGroup.activeTransaction;
293
+ return txn.assets(input).id;
294
+ };
295
+ const getAsset = (asset) => {
296
+ try {
297
+ const assetId = asMaybeUint64Cls(asset);
298
+ if (assetId !== undefined) {
299
+ return lazyContext.ledger.getAsset(resolveAssetIndex(assetId));
300
+ }
301
+ return asset;
302
+ }
303
+ catch {
304
+ return undefined;
305
+ }
306
+ };
307
+ const AssetParams = {
308
+ assetTotal(a) {
309
+ const asset = getAsset(a);
310
+ return asset === undefined ? [Uint64(0), false] : [asset.total, true];
311
+ },
312
+ assetDecimals(a) {
313
+ const asset = getAsset(a);
314
+ return asset === undefined ? [Uint64(0), false] : [asset.decimals, true];
315
+ },
316
+ assetDefaultFrozen(a) {
317
+ const asset = getAsset(a);
318
+ return asset === undefined ? [false, false] : [asset.defaultFrozen, true];
319
+ },
320
+ assetUnitName(a) {
321
+ const asset = getAsset(a);
322
+ return asset === undefined ? [Bytes(), false] : [asset.unitName, true];
323
+ },
324
+ assetName(a) {
325
+ const asset = getAsset(a);
326
+ return asset === undefined ? [Bytes(), false] : [asset.name, true];
327
+ },
328
+ assetUrl(a) {
329
+ const asset = getAsset(a);
330
+ return asset === undefined ? [Bytes(), false] : [asset.url, true];
331
+ },
332
+ assetMetadataHash(a) {
333
+ const asset = getAsset(a);
334
+ return asset === undefined ? [Bytes(), false] : [asset.metadataHash, true];
335
+ },
336
+ assetManager(a) {
337
+ const asset = getAsset(a);
338
+ return asset === undefined ? [Account(), false] : [asset.manager, true];
339
+ },
340
+ assetReserve(a) {
341
+ const asset = getAsset(a);
342
+ return asset === undefined ? [Account(), false] : [asset.reserve, true];
343
+ },
344
+ assetFreeze(a) {
345
+ const asset = getAsset(a);
346
+ return asset === undefined ? [Account(), false] : [asset.freeze, true];
347
+ },
348
+ assetClawback(a) {
349
+ const asset = getAsset(a);
350
+ return asset === undefined ? [Account(), false] : [asset.clawback, true];
351
+ },
352
+ assetCreator(a) {
353
+ const asset = getAsset(a);
354
+ return asset === undefined ? [Account(), false] : [asset.creator, true];
355
+ },
356
+ };
357
+
358
+ const getAssetHolding = (acctOrIndex, assetOrIndex) => {
359
+ const account = getAccount(acctOrIndex);
360
+ const asset = getAsset(assetOrIndex);
361
+ if (asset === undefined) {
362
+ return undefined;
363
+ }
364
+ const accountData = lazyContext.getAccountData(account);
365
+ const holding = accountData.optedAssets.get(asset.id);
366
+ if (holding === undefined) {
367
+ return undefined;
368
+ }
369
+ return holding;
370
+ };
371
+ const AssetHolding$1 = {
372
+ assetBalance(a, b) {
373
+ const holding = getAssetHolding(a, b);
374
+ return holding === undefined ? [Uint64(0), false] : [holding.balance, true];
375
+ },
376
+ assetFrozen(a, b) {
377
+ const holding = getAssetHolding(a, b);
378
+ return holding === undefined ? [false, false] : [holding.frozen, true];
379
+ },
380
+ };
381
+
382
+ const Box$1 = {
383
+ create(a, b) {
384
+ const name = asBytes(a);
385
+ const size = asNumber(b);
386
+ if (name.length === 0 || size > MAX_BOX_SIZE) {
387
+ throw new internal.errors.InternalError('Invalid box name or size');
388
+ }
389
+ const app = lazyContext.activeApplication;
390
+ if (lazyContext.ledger.boxExists(app, name)) {
391
+ return false;
392
+ }
393
+ lazyContext.ledger.setBox(app, name, new Uint8Array(size));
394
+ return true;
395
+ },
396
+ delete(a) {
397
+ const name = asBytes(a);
398
+ const app = lazyContext.activeApplication;
399
+ if (!lazyContext.ledger.boxExists(app, name)) {
400
+ return false;
401
+ }
402
+ lazyContext.ledger.deleteBox(app, name);
403
+ return true;
404
+ },
405
+ extract(a, b, c) {
406
+ const name = asBytes(a);
407
+ const start = asNumber(b);
408
+ const length = asNumber(c);
409
+ const app = lazyContext.activeApplication;
410
+ if (!lazyContext.ledger.boxExists(app, name)) {
411
+ throw new internal.errors.InternalError('Box does not exist');
412
+ }
413
+ const boxContent = lazyContext.ledger.getBox(app, name);
414
+ return toBytes(boxContent.slice(start, start + length));
415
+ },
416
+ get(a) {
417
+ const name = asBytes(a);
418
+ const app = lazyContext.activeApplication;
419
+ const boxContent = lazyContext.ledger.getBox(app, name);
420
+ return [toBytes(boxContent), lazyContext.ledger.boxExists(app, name)];
421
+ },
422
+ length(a) {
423
+ const name = asBytes(a);
424
+ const app = lazyContext.activeApplication;
425
+ const boxContent = lazyContext.ledger.getBox(app, name);
426
+ const exists = lazyContext.ledger.boxExists(app, name);
427
+ return [boxContent.length, exists];
428
+ },
429
+ put(a, b) {
430
+ const name = asBytes(a);
431
+ const app = lazyContext.activeApplication;
432
+ const newContent = asBytesCls(b);
433
+ if (lazyContext.ledger.boxExists(app, name)) {
434
+ const boxContent = lazyContext.ledger.getBox(app, name);
435
+ const length = boxContent.length;
436
+ if (asNumber(length) !== asNumber(newContent.length)) {
437
+ throw new internal.errors.InternalError('New content length does not match existing box length');
438
+ }
439
+ }
440
+ lazyContext.ledger.setBox(app, name, newContent.asUint8Array());
441
+ },
442
+ replace(a, b, c) {
443
+ const name = asBytes(a);
444
+ const start = asNumber(b);
445
+ const newContent = asUint8Array(c);
446
+ const app = lazyContext.activeApplication;
447
+ if (!lazyContext.ledger.boxExists(app, name)) {
448
+ throw new internal.errors.InternalError('Box does not exist');
449
+ }
450
+ const boxContent = lazyContext.ledger.getBox(app, name);
451
+ if (start + newContent.length > boxContent.length) {
452
+ throw new internal.errors.InternalError('Replacement content exceeds box size');
453
+ }
454
+ const updatedContent = conactUint8Arrays(boxContent.slice(0, start), newContent, boxContent.slice(start + newContent.length));
455
+ lazyContext.ledger.setBox(app, name, updatedContent);
456
+ },
457
+ resize(a, b) {
458
+ const name = asBytes(a);
459
+ const newSize = asNumber(b);
460
+ const app = lazyContext.activeApplication;
461
+ if (!lazyContext.ledger.boxExists(app, name)) {
462
+ throw new internal.errors.InternalError('Box does not exist');
463
+ }
464
+ const boxContent = lazyContext.ledger.getBox(app, name);
465
+ const size = boxContent.length;
466
+ let updatedContent;
467
+ if (newSize > size) {
468
+ updatedContent = conactUint8Arrays(boxContent, new Uint8Array(newSize - size));
469
+ }
470
+ else {
471
+ updatedContent = boxContent.slice(0, newSize);
472
+ }
473
+ lazyContext.ledger.setBox(app, name, updatedContent);
474
+ },
475
+ splice(a, b, c, d) {
476
+ const name = asBytes(a);
477
+ const start = asNumber(b);
478
+ const length = asNumber(c);
479
+ const newContent = asUint8Array(d);
480
+ const app = lazyContext.activeApplication;
481
+ if (!lazyContext.ledger.boxExists(app, name)) {
482
+ throw new internal.errors.InternalError('Box does not exist');
483
+ }
484
+ const boxContent = lazyContext.ledger.getBox(app, name);
485
+ const size = boxContent.length;
486
+ if (start > size) {
487
+ throw new internal.errors.InternalError('Start index exceeds box size');
488
+ }
489
+ const end = Math.min(start + length, size);
490
+ let updatedContent = conactUint8Arrays(boxContent.slice(0, start), newContent, boxContent.slice(end));
491
+ // Adjust the size if necessary
492
+ if (updatedContent.length > size) {
493
+ updatedContent = updatedContent.slice(0, size);
494
+ }
495
+ else if (updatedContent.length < size) {
496
+ updatedContent = conactUint8Arrays(updatedContent, new Uint8Array(size - asNumber(updatedContent.length)));
497
+ }
498
+ lazyContext.ledger.setBox(app, name, updatedContent);
499
+ },
500
+ };
501
+
502
+ class NotImplementedError extends Error {
503
+ constructor(feature) {
504
+ super(`${feature} is not available in test context. Mock using your preferred testing framework.`);
505
+ }
506
+ }
507
+ function notImplementedError(feature) {
508
+ throw new NotImplementedError(feature);
509
+ }
510
+ function testInvariant(condition, message) {
511
+ if (!condition) {
512
+ throw new internal.errors.InternalError(message);
513
+ }
514
+ }
515
+
516
+ const sha256 = (a) => {
517
+ const bytesA = internal.primitives.BytesCls.fromCompat(a);
518
+ const hashArray = sha256$1.create().update(bytesA.asUint8Array()).digest();
519
+ const hashBytes = internal.primitives.BytesCls.fromCompat(new Uint8Array(hashArray));
520
+ return hashBytes.asAlgoTs();
521
+ };
522
+ const sha3_256 = (a) => {
523
+ const bytesA = internal.primitives.BytesCls.fromCompat(a);
524
+ const hashArray = sha3_256$1.create().update(bytesA.asUint8Array()).digest();
525
+ const hashBytes = internal.primitives.BytesCls.fromCompat(new Uint8Array(hashArray));
526
+ return hashBytes.asAlgoTs();
527
+ };
528
+ const keccak256 = (a) => {
529
+ const bytesA = internal.primitives.BytesCls.fromCompat(a);
530
+ const hashArray = keccak256$1.create().update(bytesA.asUint8Array()).digest();
531
+ const hashBytes = internal.primitives.BytesCls.fromCompat(new Uint8Array(hashArray));
532
+ return hashBytes.asAlgoTs();
533
+ };
534
+ const sha512_256 = (a) => {
535
+ const bytesA = internal.primitives.BytesCls.fromCompat(a);
536
+ const hashArray = sha512_256$1.create().update(bytesA.asUint8Array()).digest();
537
+ const hashBytes = internal.primitives.BytesCls.fromCompat(new Uint8Array(hashArray));
538
+ return hashBytes.asAlgoTs();
539
+ };
540
+ const ed25519verifyBare = (a, b, c) => {
541
+ const bytesA = internal.primitives.BytesCls.fromCompat(a);
542
+ const bytesB = internal.primitives.BytesCls.fromCompat(b);
543
+ const bytesC = internal.primitives.BytesCls.fromCompat(c);
544
+ return nacl.sign.detached.verify(bytesA.asUint8Array(), bytesB.asUint8Array(), bytesC.asUint8Array());
545
+ };
546
+ const ed25519verify = (a, b, c) => {
547
+ const txn = lazyContext.activeGroup.activeTransaction;
548
+ const programBytes = asBytesCls(txn.onCompletion == arc4.OnCompleteAction[arc4.OnCompleteAction.ClearState] ? txn.clearStateProgram : txn.approvalProgram);
549
+ const logicSig = new algosdk.LogicSig(programBytes.asUint8Array());
550
+ const decodedAddress = algosdk.decodeAddress(logicSig.address());
551
+ const addressBytes = Bytes(decodedAddress.publicKey);
552
+ const data = LOGIC_DATA_PREFIX.concat(addressBytes).concat(asBytes(a));
553
+ return ed25519verifyBare(data, b, c);
554
+ };
555
+ const ecdsaVerify = (v, a, b, c, d, e) => {
556
+ const dataBytes = internal.primitives.BytesCls.fromCompat(a);
557
+ const sigRBytes = internal.primitives.BytesCls.fromCompat(b);
558
+ const sigSBytes = internal.primitives.BytesCls.fromCompat(c);
559
+ const pubkeyXBytes = internal.primitives.BytesCls.fromCompat(d);
560
+ const pubkeyYBytes = internal.primitives.BytesCls.fromCompat(e);
561
+ const publicKey = internal.primitives.BytesCls.fromCompat(new Uint8Array([0x04]))
562
+ .concat(pubkeyXBytes)
563
+ .concat(pubkeyYBytes);
564
+ const ecdsa = new ec(curveMap[v]);
565
+ const keyPair = ecdsa.keyFromPublic(publicKey.asUint8Array());
566
+ return keyPair.verify(dataBytes.asUint8Array(), { r: sigRBytes.asUint8Array(), s: sigSBytes.asUint8Array() });
567
+ };
568
+ const ecdsaPkRecover = (v, a, b, c, d) => {
569
+ if (v !== Ecdsa.Secp256k1) {
570
+ internal.errors.internalError(`Unsupported ECDSA curve: ${v}`);
571
+ }
572
+ const dataBytes = internal.primitives.BytesCls.fromCompat(a);
573
+ const rBytes = internal.primitives.BytesCls.fromCompat(c);
574
+ const sBytes = internal.primitives.BytesCls.fromCompat(d);
575
+ const recoveryId = internal.primitives.Uint64Cls.fromCompat(b);
576
+ const ecdsa = new ec(curveMap[v]);
577
+ const pubKey = ecdsa.recoverPubKey(dataBytes.asUint8Array(), { r: rBytes.asUint8Array(), s: sBytes.asUint8Array() }, recoveryId.asNumber());
578
+ const x = pubKey.getX().toArray('be');
579
+ const y = pubKey.getY().toArray('be');
580
+ return [Bytes(x), Bytes(y)];
581
+ };
582
+ const ecdsaPkDecompress = (v, a) => {
583
+ const bytesA = internal.primitives.BytesCls.fromCompat(a);
584
+ const ecdsa = new ec(curveMap[v]);
585
+ const keyPair = ecdsa.keyFromPublic(bytesA.asUint8Array());
586
+ const pubKey = keyPair.getPublic();
587
+ const x = pubKey.getX().toArray('be');
588
+ const y = pubKey.getY().toArray('be');
589
+ return [Bytes(new Uint8Array(x)), Bytes(new Uint8Array(y))];
590
+ };
591
+ const vrfVerify = (_s, _a, _b, _c) => {
592
+ notImplementedError('vrfVerify');
593
+ };
594
+ const EllipticCurve = new Proxy({}, {
595
+ get: (_target, prop) => {
596
+ notImplementedError(`EllipticCurve.${prop.toString()}`);
597
+ },
598
+ });
599
+ const curveMap = {
600
+ [Ecdsa.Secp256k1]: 'secp256k1',
601
+ [Ecdsa.Secp256r1]: 'p256',
602
+ };
603
+
604
+ class GlobalData {
605
+ minTxnFee;
606
+ minBalance;
607
+ maxTxnLife;
608
+ zeroAddress;
609
+ logicSigVersion;
610
+ round;
611
+ latestTimestamp;
612
+ groupId;
613
+ callerApplicationId;
614
+ assetCreateMinBalance;
615
+ assetOptInMinBalance;
616
+ genesisHash;
617
+ opcodeBudget;
618
+ constructor() {
619
+ this.minTxnFee = Uint64(MIN_TXN_FEE);
620
+ this.minBalance = Uint64(DEFAULT_ACCOUNT_MIN_BALANCE);
621
+ this.maxTxnLife = Uint64(DEFAULT_MAX_TXN_LIFE);
622
+ this.zeroAddress = Account(ZERO_ADDRESS);
623
+ this.callerApplicationId = Uint64(0);
624
+ this.assetCreateMinBalance = Uint64(DEFAULT_ASSET_CREATE_MIN_BALANCE);
625
+ this.assetOptInMinBalance = Uint64(DEFAULT_ASSET_OPT_IN_MIN_BALANCE);
626
+ this.genesisHash = DEFAULT_GLOBAL_GENESIS_HASH;
627
+ }
628
+ }
629
+ const getGlobalData = () => {
630
+ return lazyContext.ledger.globalData;
631
+ };
632
+ const getMissingValueErrorMessage = (name) => `'algopy.Global' object has no value set for attribute named '${name}'. Use \`context.ledger.patchGlobalData({${name}: your_value})\` to set the value in your test setup."`;
633
+ const Global = {
634
+ /**
635
+ * microalgos
636
+ */
637
+ get minTxnFee() {
638
+ return getGlobalData().minTxnFee;
639
+ },
640
+ /**
641
+ * microalgos
642
+ */
643
+ get minBalance() {
644
+ return getGlobalData().minBalance;
645
+ },
646
+ /**
647
+ * rounds
648
+ */
649
+ get maxTxnLife() {
650
+ return getGlobalData().maxTxnLife;
651
+ },
652
+ /**
653
+ * 32 byte address of all zero bytes
654
+ */
655
+ get zeroAddress() {
656
+ return getGlobalData().zeroAddress;
657
+ },
658
+ /**
659
+ * Number of transactions in this atomic transaction group. At least 1
660
+ */
661
+ get groupSize() {
662
+ const currentTransactionGroup = lazyContext.activeGroup.transactions;
663
+ return Uint64(currentTransactionGroup.length);
664
+ },
665
+ /**
666
+ * Maximum supported version
667
+ */
668
+ get logicSigVersion() {
669
+ const data = getGlobalData();
670
+ if (data.logicSigVersion !== undefined)
671
+ return data.logicSigVersion;
672
+ throw new internal.errors.InternalError(getMissingValueErrorMessage('logicSigVersion'));
673
+ },
674
+ /**
675
+ * Current round number. Application mode only.
676
+ */
677
+ get round() {
678
+ const data = getGlobalData();
679
+ if (data.round !== undefined)
680
+ return data.round;
681
+ return Uint64(lazyContext.txn.groups.length + 1);
682
+ },
683
+ /**
684
+ * Last confirmed block UNIX timestamp. Fails if negative. Application mode only.
685
+ */
686
+ get latestTimestamp() {
687
+ const data = getGlobalData();
688
+ if (data.latestTimestamp !== undefined)
689
+ return data.latestTimestamp;
690
+ return Uint64(lazyContext.activeGroup.latestTimestamp);
691
+ },
692
+ /**
693
+ * ID of current application executing. Application mode only.
694
+ */
695
+ get currentApplicationId() {
696
+ return lazyContext.activeApplication;
697
+ },
698
+ /**
699
+ * Address of the creator of the current application. Application mode only.
700
+ */
701
+ get creatorAddress() {
702
+ const app = lazyContext.activeApplication;
703
+ return app.creator;
704
+ },
705
+ /**
706
+ * Address that the current application controls. Application mode only.
707
+ */
708
+ get currentApplicationAddress() {
709
+ const appAddress = algosdk.getApplicationAddress(asBigInt(this.currentApplicationId.id));
710
+ return Account(Bytes.fromBase32(appAddress));
711
+ },
712
+ /**
713
+ * ID of the transaction group. 32 zero bytes if the transaction is not part of a group.
714
+ */
715
+ get groupId() {
716
+ const data = getGlobalData();
717
+ if (data.groupId !== undefined)
718
+ return data.groupId;
719
+ const reference = getObjectReference(lazyContext.activeGroup);
720
+ const referenceBytes = Bytes(internal.encodingUtil.bigIntToUint8Array(reference));
721
+ return op.sha256(referenceBytes);
722
+ },
723
+ /**
724
+ * The remaining cost that can be spent by opcodes in this program.
725
+ */
726
+ get opcodeBudget() {
727
+ const data = getGlobalData();
728
+ if (data.opcodeBudget !== undefined)
729
+ return data.opcodeBudget;
730
+ throw new internal.errors.InternalError(getMissingValueErrorMessage('opcodeBudget'));
731
+ },
732
+ /**
733
+ * The application ID of the application that called this application. 0 if this application is at the top-level. Application mode only.
734
+ */
735
+ get callerApplicationId() {
736
+ return getGlobalData().callerApplicationId;
737
+ },
738
+ /**
739
+ * The application address of the application that called this application. ZeroAddress if this application is at the top-level. Application mode only.
740
+ */
741
+ get callerApplicationAddress() {
742
+ const appAddress = algosdk.getApplicationAddress(asBigInt(this.callerApplicationId));
743
+ return Account(Bytes.fromBase32(appAddress));
744
+ },
745
+ /**
746
+ * The additional minimum balance required to create (and opt-in to) an asset.
747
+ */
748
+ get assetCreateMinBalance() {
749
+ return getGlobalData().assetCreateMinBalance;
750
+ },
751
+ /**
752
+ * The additional minimum balance required to opt-in to an asset.
753
+ */
754
+ get assetOptInMinBalance() {
755
+ return getGlobalData().assetOptInMinBalance;
756
+ },
757
+ /**
758
+ * The Genesis Hash for the network.
759
+ */
760
+ get genesisHash() {
761
+ return getGlobalData().genesisHash;
762
+ },
763
+ payoutsEnabled: false,
764
+ // TODO: implement v11 fields
765
+ payoutsGoOnlineFee: 0,
766
+ payoutsPercent: 0,
767
+ payoutsMinBalance: 0,
768
+ payoutsMaxBalance: 0,
769
+ };
770
+
771
+ const GTxn = {
772
+ sender(t) {
773
+ return lazyContext.activeGroup.getTransaction(t).sender;
774
+ },
775
+ fee(t) {
776
+ return lazyContext.activeGroup.getTransaction(t).fee;
777
+ },
778
+ firstValid(t) {
779
+ return lazyContext.activeGroup.getTransaction(t).firstValid;
780
+ },
781
+ firstValidTime(t) {
782
+ return lazyContext.activeGroup.getTransaction(t).firstValidTime;
783
+ },
784
+ lastValid(t) {
785
+ return lazyContext.activeGroup.getTransaction(t).lastValid;
786
+ },
787
+ note(t) {
788
+ return lazyContext.activeGroup.getTransaction(t).note;
789
+ },
790
+ lease(t) {
791
+ return lazyContext.activeGroup.getTransaction(t).lease;
792
+ },
793
+ receiver(t) {
794
+ return lazyContext.activeGroup.getPaymentTransaction(t).receiver;
795
+ },
796
+ amount(t) {
797
+ return lazyContext.activeGroup.getPaymentTransaction(t).amount;
798
+ },
799
+ closeRemainderTo(t) {
800
+ return lazyContext.activeGroup.getPaymentTransaction(t).closeRemainderTo;
801
+ },
802
+ votePk(t) {
803
+ return lazyContext.activeGroup.getKeyRegistrationTransaction(t).voteKey;
804
+ },
805
+ selectionPk(t) {
806
+ return lazyContext.activeGroup.getKeyRegistrationTransaction(t).selectionKey;
807
+ },
808
+ voteFirst(t) {
809
+ return lazyContext.activeGroup.getKeyRegistrationTransaction(t).voteFirst;
810
+ },
811
+ voteLast(t) {
812
+ return lazyContext.activeGroup.getKeyRegistrationTransaction(t).voteLast;
813
+ },
814
+ voteKeyDilution(t) {
815
+ return lazyContext.activeGroup.getKeyRegistrationTransaction(t).voteKeyDilution;
816
+ },
817
+ type(t) {
818
+ return asUint64Cls(lazyContext.activeGroup.getTransaction(t).type).toBytes().asAlgoTs();
819
+ },
820
+ typeEnum(t) {
821
+ return asUint64(lazyContext.activeGroup.getTransaction(t).type);
822
+ },
823
+ xferAsset(t) {
824
+ return lazyContext.activeGroup.getAssetTransferTransaction(t).xferAsset;
825
+ },
826
+ assetAmount(t) {
827
+ return lazyContext.activeGroup.getAssetTransferTransaction(t).assetAmount;
828
+ },
829
+ assetSender(t) {
830
+ return lazyContext.activeGroup.getAssetTransferTransaction(t).assetSender;
831
+ },
832
+ assetReceiver(t) {
833
+ return lazyContext.activeGroup.getAssetTransferTransaction(t).assetReceiver;
834
+ },
835
+ assetCloseTo(t) {
836
+ return lazyContext.activeGroup.getAssetTransferTransaction(t).assetCloseTo;
837
+ },
838
+ groupIndex(t) {
839
+ return lazyContext.activeGroup.getTransaction(t).groupIndex;
840
+ },
841
+ txId(t) {
842
+ return lazyContext.activeGroup.getTransaction(t).txnId;
843
+ },
844
+ applicationId(t) {
845
+ return lazyContext.activeGroup.getApplicationTransaction(t).appId;
846
+ },
847
+ onCompletion(t) {
848
+ const onCompletionStr = lazyContext.activeGroup.getApplicationTransaction(t).onCompletion;
849
+ return asUint64(arc4.OnCompleteAction[onCompletionStr]);
850
+ },
851
+ applicationArgs(a, b) {
852
+ return lazyContext.activeGroup.getApplicationTransaction(a).appArgs(asUint64(b));
853
+ },
854
+ numAppArgs(t) {
855
+ return lazyContext.activeGroup.getApplicationTransaction(t).numAppArgs;
856
+ },
857
+ accounts(a, b) {
858
+ return lazyContext.activeGroup.getApplicationTransaction(a).accounts(asUint64(b));
859
+ },
860
+ numAccounts(t) {
861
+ return lazyContext.activeGroup.getApplicationTransaction(t).numAccounts;
862
+ },
863
+ approvalProgram(t) {
864
+ return lazyContext.activeGroup.getApplicationTransaction(t).approvalProgram;
865
+ },
866
+ clearStateProgram(t) {
867
+ return lazyContext.activeGroup.getApplicationTransaction(t).clearStateProgram;
868
+ },
869
+ rekeyTo(t) {
870
+ return lazyContext.activeGroup.getTransaction(t).rekeyTo;
871
+ },
872
+ configAsset(t) {
873
+ return lazyContext.activeGroup.getAssetConfigTransaction(t).configAsset;
874
+ },
875
+ configAssetTotal(t) {
876
+ return lazyContext.activeGroup.getAssetConfigTransaction(t).total;
877
+ },
878
+ configAssetDecimals(t) {
879
+ return lazyContext.activeGroup.getAssetConfigTransaction(t).decimals;
880
+ },
881
+ configAssetDefaultFrozen(t) {
882
+ return lazyContext.activeGroup.getAssetConfigTransaction(t).defaultFrozen;
883
+ },
884
+ configAssetUnitName(t) {
885
+ return lazyContext.activeGroup.getAssetConfigTransaction(t).unitName;
886
+ },
887
+ configAssetName(t) {
888
+ return lazyContext.activeGroup.getAssetConfigTransaction(t).assetName;
889
+ },
890
+ configAssetUrl(t) {
891
+ return lazyContext.activeGroup.getAssetConfigTransaction(t).url;
892
+ },
893
+ configAssetMetadataHash(t) {
894
+ return lazyContext.activeGroup.getAssetConfigTransaction(t).metadataHash;
895
+ },
896
+ configAssetManager(t) {
897
+ return lazyContext.activeGroup.getAssetConfigTransaction(t).manager;
898
+ },
899
+ configAssetReserve(t) {
900
+ return lazyContext.activeGroup.getAssetConfigTransaction(t).reserve;
901
+ },
902
+ configAssetFreeze(t) {
903
+ return lazyContext.activeGroup.getAssetConfigTransaction(t).freeze;
904
+ },
905
+ configAssetClawback(t) {
906
+ return lazyContext.activeGroup.getAssetConfigTransaction(t).clawback;
907
+ },
908
+ freezeAsset(t) {
909
+ return lazyContext.activeGroup.getAssetFreezeTransaction(t).freezeAsset;
910
+ },
911
+ freezeAssetAccount(t) {
912
+ return lazyContext.activeGroup.getAssetFreezeTransaction(t).freezeAccount;
913
+ },
914
+ freezeAssetFrozen(t) {
915
+ return lazyContext.activeGroup.getAssetFreezeTransaction(t).frozen;
916
+ },
917
+ assets(a, b) {
918
+ return lazyContext.activeGroup.getApplicationTransaction(a).assets(asUint64(b));
919
+ },
920
+ numAssets(t) {
921
+ return lazyContext.activeGroup.getApplicationTransaction(t).numAssets;
922
+ },
923
+ applications(a, b) {
924
+ return lazyContext.activeGroup.getApplicationTransaction(a).apps(asUint64(b));
925
+ },
926
+ numApplications(t) {
927
+ return lazyContext.activeGroup.getApplicationTransaction(t).numApps;
928
+ },
929
+ globalNumUint(t) {
930
+ return lazyContext.activeGroup.getApplicationTransaction(t).globalNumUint;
931
+ },
932
+ globalNumByteSlice(t) {
933
+ return lazyContext.activeGroup.getApplicationTransaction(t).globalNumBytes;
934
+ },
935
+ localNumUint(t) {
936
+ return lazyContext.activeGroup.getApplicationTransaction(t).localNumUint;
937
+ },
938
+ localNumByteSlice(t) {
939
+ return lazyContext.activeGroup.getApplicationTransaction(t).localNumBytes;
940
+ },
941
+ extraProgramPages(t) {
942
+ return lazyContext.activeGroup.getApplicationTransaction(t).extraProgramPages;
943
+ },
944
+ nonparticipation(t) {
945
+ return lazyContext.activeGroup.getKeyRegistrationTransaction(t).nonparticipation;
946
+ },
947
+ logs(a, b) {
948
+ return lazyContext.activeGroup.getApplicationTransaction(a).logs(asUint64(b));
949
+ },
950
+ numLogs(t) {
951
+ return lazyContext.activeGroup.getApplicationTransaction(t).numLogs;
952
+ },
953
+ createdAssetId(t) {
954
+ return lazyContext.activeGroup.getAssetConfigTransaction(t).createdAsset;
955
+ },
956
+ createdApplicationId(t) {
957
+ return lazyContext.activeGroup.getApplicationTransaction(t).createdApp;
958
+ },
959
+ lastLog(t) {
960
+ return lazyContext.activeGroup.getApplicationTransaction(t).lastLog;
961
+ },
962
+ stateProofPk(t) {
963
+ return lazyContext.activeGroup.getKeyRegistrationTransaction(t).stateProofKey;
964
+ },
965
+ approvalProgramPages(a, b) {
966
+ return lazyContext.activeGroup.getApplicationTransaction(a).approvalProgramPages(asUint64(b));
967
+ },
968
+ numApprovalProgramPages(t) {
969
+ return lazyContext.activeGroup.getApplicationTransaction(t).numApprovalProgramPages;
970
+ },
971
+ clearStateProgramPages(a, b) {
972
+ return lazyContext.activeGroup.getApplicationTransaction(a).clearStateProgramPages(asUint64(b));
973
+ },
974
+ numClearStateProgramPages(t) {
975
+ return lazyContext.activeGroup.getApplicationTransaction(t).numClearStateProgramPages;
976
+ },
977
+ };
978
+
979
+ const GITxn = {
980
+ sender: function (t) {
981
+ return lazyContext.activeGroup.getItxnGroup().getInnerTxn(t).sender;
982
+ },
983
+ fee: function (t) {
984
+ return lazyContext.activeGroup.getItxnGroup().getInnerTxn(t).fee;
985
+ },
986
+ firstValid: function (t) {
987
+ return lazyContext.activeGroup.getItxnGroup().getInnerTxn(t).firstValid;
988
+ },
989
+ firstValidTime: function (t) {
990
+ return lazyContext.activeGroup.getItxnGroup().getInnerTxn(t).firstValidTime;
991
+ },
992
+ lastValid: function (t) {
993
+ return lazyContext.activeGroup.getItxnGroup().getInnerTxn(t).lastValid;
994
+ },
995
+ note: function (t) {
996
+ return lazyContext.activeGroup.getItxnGroup().getInnerTxn(t).note;
997
+ },
998
+ lease: function (t) {
999
+ return lazyContext.activeGroup.getItxnGroup().getInnerTxn(t).lease;
1000
+ },
1001
+ receiver: function (t) {
1002
+ return lazyContext.activeGroup.getItxnGroup().getPaymentInnerTxn(t).receiver;
1003
+ },
1004
+ amount: function (t) {
1005
+ return lazyContext.activeGroup.getItxnGroup().getPaymentInnerTxn(t).amount;
1006
+ },
1007
+ closeRemainderTo: function (t) {
1008
+ return lazyContext.activeGroup.getItxnGroup().getPaymentInnerTxn(t).closeRemainderTo;
1009
+ },
1010
+ votePk: function (t) {
1011
+ return lazyContext.activeGroup.getItxnGroup().getKeyRegistrationInnerTxn(t).voteKey;
1012
+ },
1013
+ selectionPk: function (t) {
1014
+ return lazyContext.activeGroup.getItxnGroup().getKeyRegistrationInnerTxn(t).selectionKey;
1015
+ },
1016
+ voteFirst: function (t) {
1017
+ return lazyContext.activeGroup.getItxnGroup().getKeyRegistrationInnerTxn(t).voteFirst;
1018
+ },
1019
+ voteLast: function (t) {
1020
+ return lazyContext.activeGroup.getItxnGroup().getKeyRegistrationInnerTxn(t).voteLast;
1021
+ },
1022
+ voteKeyDilution: function (t) {
1023
+ return lazyContext.activeGroup.getItxnGroup().getKeyRegistrationInnerTxn(t).voteKeyDilution;
1024
+ },
1025
+ type: function (t) {
1026
+ return asUint64Cls(lazyContext.activeGroup.getItxnGroup().getInnerTxn(t).type).toBytes().asAlgoTs();
1027
+ },
1028
+ typeEnum: function (t) {
1029
+ return asUint64(lazyContext.activeGroup.getItxnGroup().getInnerTxn(t).type);
1030
+ },
1031
+ xferAsset: function (t) {
1032
+ return lazyContext.activeGroup.getItxnGroup().getAssetTransferInnerTxn(t).xferAsset;
1033
+ },
1034
+ assetAmount: function (t) {
1035
+ return lazyContext.activeGroup.getItxnGroup().getAssetTransferInnerTxn(t).assetAmount;
1036
+ },
1037
+ assetSender: function (t) {
1038
+ return lazyContext.activeGroup.getItxnGroup().getAssetTransferInnerTxn(t).assetSender;
1039
+ },
1040
+ assetReceiver: function (t) {
1041
+ return lazyContext.activeGroup.getItxnGroup().getAssetTransferInnerTxn(t).assetReceiver;
1042
+ },
1043
+ assetCloseTo: function (t) {
1044
+ return lazyContext.activeGroup.getItxnGroup().getAssetTransferInnerTxn(t).assetCloseTo;
1045
+ },
1046
+ groupIndex: function (t) {
1047
+ return lazyContext.activeGroup.getItxnGroup().getInnerTxn(t).groupIndex;
1048
+ },
1049
+ txId: function (t) {
1050
+ return lazyContext.activeGroup.getItxnGroup().getInnerTxn(t).txnId;
1051
+ },
1052
+ applicationId: function (t) {
1053
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).appId;
1054
+ },
1055
+ onCompletion: function (t) {
1056
+ const onCompletionStr = lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).onCompletion;
1057
+ return asUint64(arc4.OnCompleteAction[onCompletionStr]);
1058
+ },
1059
+ applicationArgs: function (t, a) {
1060
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).appArgs(asUint64(a));
1061
+ },
1062
+ numAppArgs: function (t) {
1063
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).numAppArgs;
1064
+ },
1065
+ accounts: function (t, a) {
1066
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).accounts(asUint64(a));
1067
+ },
1068
+ numAccounts: function (t) {
1069
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).numAccounts;
1070
+ },
1071
+ approvalProgram: function (t) {
1072
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).approvalProgram;
1073
+ },
1074
+ clearStateProgram: function (t) {
1075
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).clearStateProgram;
1076
+ },
1077
+ rekeyTo: function (t) {
1078
+ return lazyContext.activeGroup.getItxnGroup().getInnerTxn(t).rekeyTo;
1079
+ },
1080
+ configAsset: function (t) {
1081
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn(t).configAsset;
1082
+ },
1083
+ configAssetTotal: function (t) {
1084
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn(t).total;
1085
+ },
1086
+ configAssetDecimals: function (t) {
1087
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn(t).decimals;
1088
+ },
1089
+ configAssetDefaultFrozen: function (t) {
1090
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn(t).defaultFrozen;
1091
+ },
1092
+ configAssetUnitName: function (t) {
1093
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn(t).unitName;
1094
+ },
1095
+ configAssetName: function (t) {
1096
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn(t).assetName;
1097
+ },
1098
+ configAssetUrl: function (t) {
1099
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn(t).url;
1100
+ },
1101
+ configAssetMetadataHash: function (t) {
1102
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn(t).metadataHash;
1103
+ },
1104
+ configAssetManager: function (t) {
1105
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn(t).manager;
1106
+ },
1107
+ configAssetReserve: function (t) {
1108
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn(t).reserve;
1109
+ },
1110
+ configAssetFreeze: function (t) {
1111
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn(t).freeze;
1112
+ },
1113
+ configAssetClawback: function (t) {
1114
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn(t).clawback;
1115
+ },
1116
+ freezeAsset: function (t) {
1117
+ return lazyContext.activeGroup.getItxnGroup().getAssetFreezeInnerTxn(t).freezeAsset;
1118
+ },
1119
+ freezeAssetAccount: function (t) {
1120
+ return lazyContext.activeGroup.getItxnGroup().getAssetFreezeInnerTxn(t).freezeAccount;
1121
+ },
1122
+ freezeAssetFrozen: function (t) {
1123
+ return lazyContext.activeGroup.getItxnGroup().getAssetFreezeInnerTxn(t).frozen;
1124
+ },
1125
+ assets: function (t, a) {
1126
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).assets(asUint64(a));
1127
+ },
1128
+ numAssets: function (t) {
1129
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).numAssets;
1130
+ },
1131
+ applications: function (t, a) {
1132
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).apps(asUint64(a));
1133
+ },
1134
+ numApplications: function (t) {
1135
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).numApps;
1136
+ },
1137
+ globalNumUint: function (t) {
1138
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).globalNumUint;
1139
+ },
1140
+ globalNumByteSlice: function (t) {
1141
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).globalNumBytes;
1142
+ },
1143
+ localNumUint: function (t) {
1144
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).localNumUint;
1145
+ },
1146
+ localNumByteSlice: function (t) {
1147
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).localNumBytes;
1148
+ },
1149
+ extraProgramPages: function (t) {
1150
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).extraProgramPages;
1151
+ },
1152
+ nonparticipation: function (t) {
1153
+ return lazyContext.activeGroup.getItxnGroup().getKeyRegistrationInnerTxn(t).nonparticipation;
1154
+ },
1155
+ logs: function (t, a) {
1156
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).logs(asUint64(a));
1157
+ },
1158
+ numLogs: function (t) {
1159
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).numLogs;
1160
+ },
1161
+ createdAssetId: function (t) {
1162
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn(t).createdAsset;
1163
+ },
1164
+ createdApplicationId: function (t) {
1165
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).createdApp;
1166
+ },
1167
+ lastLog: function (t) {
1168
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).lastLog;
1169
+ },
1170
+ stateProofPk: function (t) {
1171
+ return lazyContext.activeGroup.getItxnGroup().getKeyRegistrationInnerTxn(t).stateProofKey;
1172
+ },
1173
+ approvalProgramPages: function (t, a) {
1174
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).approvalProgramPages(asUint64(a));
1175
+ },
1176
+ numApprovalProgramPages: function (t) {
1177
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).numApprovalProgramPages;
1178
+ },
1179
+ clearStateProgramPages: function (t, a) {
1180
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).clearStateProgramPages(asUint64(a));
1181
+ },
1182
+ numClearStateProgramPages: function (t) {
1183
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn(t).numClearStateProgramPages;
1184
+ },
1185
+ };
1186
+ const ITxn = {
1187
+ /**
1188
+ * 32 byte address
1189
+ */
1190
+ get sender() {
1191
+ return lazyContext.activeGroup.getItxnGroup().getInnerTxn().sender;
1192
+ },
1193
+ /**
1194
+ * microalgos
1195
+ */
1196
+ get fee() {
1197
+ return lazyContext.activeGroup.getItxnGroup().getInnerTxn().fee;
1198
+ },
1199
+ /**
1200
+ * round number
1201
+ */
1202
+ get firstValid() {
1203
+ return lazyContext.activeGroup.getItxnGroup().getInnerTxn().firstValid;
1204
+ },
1205
+ /**
1206
+ * UNIX timestamp of block before txn.FirstValid. Fails if negative
1207
+ */
1208
+ get firstValidTime() {
1209
+ return lazyContext.activeGroup.getItxnGroup().getInnerTxn().firstValidTime;
1210
+ },
1211
+ /**
1212
+ * round number
1213
+ */
1214
+ get lastValid() {
1215
+ return lazyContext.activeGroup.getItxnGroup().getInnerTxn().lastValid;
1216
+ },
1217
+ /**
1218
+ * Any data up to 1024 bytes
1219
+ */
1220
+ get note() {
1221
+ return lazyContext.activeGroup.getItxnGroup().getInnerTxn().note;
1222
+ },
1223
+ /**
1224
+ * 32 byte lease value
1225
+ */
1226
+ get lease() {
1227
+ return lazyContext.activeGroup.getItxnGroup().getInnerTxn().lease;
1228
+ },
1229
+ /**
1230
+ * 32 byte address
1231
+ */
1232
+ get receiver() {
1233
+ return lazyContext.activeGroup.getItxnGroup().getPaymentInnerTxn().receiver;
1234
+ },
1235
+ /**
1236
+ * microalgos
1237
+ */
1238
+ get amount() {
1239
+ return lazyContext.activeGroup.getItxnGroup().getPaymentInnerTxn().amount;
1240
+ },
1241
+ /**
1242
+ * 32 byte address
1243
+ */
1244
+ get closeRemainderTo() {
1245
+ return lazyContext.activeGroup.getItxnGroup().getPaymentInnerTxn().closeRemainderTo;
1246
+ },
1247
+ /**
1248
+ * 32 byte address
1249
+ */
1250
+ get votePk() {
1251
+ return lazyContext.activeGroup.getItxnGroup().getKeyRegistrationInnerTxn().voteKey;
1252
+ },
1253
+ /**
1254
+ * 32 byte address
1255
+ */
1256
+ get selectionPk() {
1257
+ return lazyContext.activeGroup.getItxnGroup().getKeyRegistrationInnerTxn().selectionKey;
1258
+ },
1259
+ /**
1260
+ * The first round that the participation key is valid.
1261
+ */
1262
+ get voteFirst() {
1263
+ return lazyContext.activeGroup.getItxnGroup().getKeyRegistrationInnerTxn().voteFirst;
1264
+ },
1265
+ /**
1266
+ * The last round that the participation key is valid.
1267
+ */
1268
+ get voteLast() {
1269
+ return lazyContext.activeGroup.getItxnGroup().getKeyRegistrationInnerTxn().voteLast;
1270
+ },
1271
+ /**
1272
+ * Dilution for the 2-level participation key
1273
+ */
1274
+ get voteKeyDilution() {
1275
+ return lazyContext.activeGroup.getItxnGroup().getKeyRegistrationInnerTxn().voteKeyDilution;
1276
+ },
1277
+ /**
1278
+ * Transaction type as bytes
1279
+ */
1280
+ get type() {
1281
+ return asUint64Cls(lazyContext.activeGroup.getItxnGroup().getInnerTxn().type).toBytes().asAlgoTs();
1282
+ },
1283
+ /**
1284
+ * Transaction type as integer
1285
+ */
1286
+ get typeEnum() {
1287
+ return asUint64(lazyContext.activeGroup.getItxnGroup().getInnerTxn().type);
1288
+ },
1289
+ /**
1290
+ * Asset ID
1291
+ */
1292
+ get xferAsset() {
1293
+ return lazyContext.activeGroup.getItxnGroup().getAssetTransferInnerTxn().xferAsset;
1294
+ },
1295
+ /**
1296
+ * value in Asset's units
1297
+ */
1298
+ get assetAmount() {
1299
+ return lazyContext.activeGroup.getItxnGroup().getAssetTransferInnerTxn().assetAmount;
1300
+ },
1301
+ /**
1302
+ * 32 byte address. Source of assets if Sender is the Asset's Clawback address.
1303
+ */
1304
+ get assetSender() {
1305
+ return lazyContext.activeGroup.getItxnGroup().getAssetTransferInnerTxn().assetSender;
1306
+ },
1307
+ /**
1308
+ * 32 byte address
1309
+ */
1310
+ get assetReceiver() {
1311
+ return lazyContext.activeGroup.getItxnGroup().getAssetTransferInnerTxn().assetReceiver;
1312
+ },
1313
+ /**
1314
+ * 32 byte address
1315
+ */
1316
+ get assetCloseTo() {
1317
+ return lazyContext.activeGroup.getItxnGroup().getAssetTransferInnerTxn().assetCloseTo;
1318
+ },
1319
+ /**
1320
+ * Position of this transaction within an atomic transaction group. A stand-alone transaction is implicitly element 0 in a group of 1
1321
+ */
1322
+ get groupIndex() {
1323
+ return lazyContext.activeGroup.getItxnGroup().getInnerTxn().groupIndex;
1324
+ },
1325
+ /**
1326
+ * The computed ID for this transaction. 32 bytes.
1327
+ */
1328
+ get txId() {
1329
+ return lazyContext.activeGroup.getItxnGroup().getInnerTxn().txnId;
1330
+ },
1331
+ /**
1332
+ * ApplicationID from ApplicationCall transaction
1333
+ */
1334
+ get applicationId() {
1335
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().appId;
1336
+ },
1337
+ /**
1338
+ * ApplicationCall transaction on completion action
1339
+ */
1340
+ get onCompletion() {
1341
+ const onCompletionStr = lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().onCompletion;
1342
+ return asUint64(arc4.OnCompleteAction[onCompletionStr]);
1343
+ },
1344
+ /**
1345
+ * Arguments passed to the application in the ApplicationCall transaction
1346
+ */
1347
+ applicationArgs(a) {
1348
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().appArgs(asUint64(a));
1349
+ },
1350
+ /**
1351
+ * Number of ApplicationArgs
1352
+ */
1353
+ get numAppArgs() {
1354
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().numAppArgs;
1355
+ },
1356
+ /**
1357
+ * Accounts listed in the ApplicationCall transaction
1358
+ */
1359
+ accounts(a) {
1360
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().accounts(asUint64(a));
1361
+ },
1362
+ /**
1363
+ * Number of Accounts
1364
+ */
1365
+ get numAccounts() {
1366
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().numAccounts;
1367
+ },
1368
+ /**
1369
+ * Approval program
1370
+ */
1371
+ get approvalProgram() {
1372
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().approvalProgram;
1373
+ },
1374
+ /**
1375
+ * Clear state program
1376
+ */
1377
+ get clearStateProgram() {
1378
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().clearStateProgram;
1379
+ },
1380
+ /**
1381
+ * 32 byte Sender's new AuthAddr
1382
+ */
1383
+ get rekeyTo() {
1384
+ return lazyContext.activeGroup.getItxnGroup().getInnerTxn().rekeyTo;
1385
+ },
1386
+ /**
1387
+ * Asset ID in asset config transaction
1388
+ */
1389
+ get configAsset() {
1390
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn().configAsset;
1391
+ },
1392
+ /**
1393
+ * Total number of units of this asset created
1394
+ */
1395
+ get configAssetTotal() {
1396
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn().total;
1397
+ },
1398
+ /**
1399
+ * Number of digits to display after the decimal place when displaying the asset
1400
+ */
1401
+ get configAssetDecimals() {
1402
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn().decimals;
1403
+ },
1404
+ /**
1405
+ * Whether the asset's slots are frozen by default or not, 0 or 1
1406
+ */
1407
+ get configAssetDefaultFrozen() {
1408
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn().defaultFrozen;
1409
+ },
1410
+ /**
1411
+ * Unit name of the asset
1412
+ */
1413
+ get configAssetUnitName() {
1414
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn().unitName;
1415
+ },
1416
+ /**
1417
+ * The asset name
1418
+ */
1419
+ get configAssetName() {
1420
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn().assetName;
1421
+ },
1422
+ /**
1423
+ * URL
1424
+ */
1425
+ get configAssetUrl() {
1426
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn().url;
1427
+ },
1428
+ /**
1429
+ * 32 byte commitment to unspecified asset metadata
1430
+ */
1431
+ get configAssetMetadataHash() {
1432
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn().metadataHash;
1433
+ },
1434
+ /**
1435
+ * 32 byte address
1436
+ */
1437
+ get configAssetManager() {
1438
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn().manager;
1439
+ },
1440
+ /**
1441
+ * 32 byte address
1442
+ */
1443
+ get configAssetReserve() {
1444
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn().reserve;
1445
+ },
1446
+ /**
1447
+ * 32 byte address
1448
+ */
1449
+ get configAssetFreeze() {
1450
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn().freeze;
1451
+ },
1452
+ /**
1453
+ * 32 byte address
1454
+ */
1455
+ get configAssetClawback() {
1456
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn().clawback;
1457
+ },
1458
+ /**
1459
+ * Asset ID being frozen or un-frozen
1460
+ */
1461
+ get freezeAsset() {
1462
+ return lazyContext.activeGroup.getItxnGroup().getAssetFreezeInnerTxn().freezeAsset;
1463
+ },
1464
+ /**
1465
+ * 32 byte address of the account whose asset slot is being frozen or un-frozen
1466
+ */
1467
+ get freezeAssetAccount() {
1468
+ return lazyContext.activeGroup.getItxnGroup().getAssetFreezeInnerTxn().freezeAccount;
1469
+ },
1470
+ /**
1471
+ * The new frozen value, 0 or 1
1472
+ */
1473
+ get freezeAssetFrozen() {
1474
+ return lazyContext.activeGroup.getItxnGroup().getAssetFreezeInnerTxn().frozen;
1475
+ },
1476
+ /**
1477
+ * Foreign Assets listed in the ApplicationCall transaction
1478
+ */
1479
+ assets(a) {
1480
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().assets(asUint64(a));
1481
+ },
1482
+ /**
1483
+ * Number of Assets
1484
+ */
1485
+ get numAssets() {
1486
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().numAssets;
1487
+ },
1488
+ /**
1489
+ * Foreign Apps listed in the ApplicationCall transaction
1490
+ */
1491
+ applications(a) {
1492
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().apps(asUint64(a));
1493
+ },
1494
+ /**
1495
+ * Number of Applications
1496
+ */
1497
+ get numApplications() {
1498
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().numApps;
1499
+ },
1500
+ /**
1501
+ * Number of global state integers in ApplicationCall
1502
+ */
1503
+ get globalNumUint() {
1504
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().globalNumUint;
1505
+ },
1506
+ /**
1507
+ * Number of global state byteslices in ApplicationCall
1508
+ */
1509
+ get globalNumByteSlice() {
1510
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().globalNumBytes;
1511
+ },
1512
+ /**
1513
+ * Number of local state integers in ApplicationCall
1514
+ */
1515
+ get localNumUint() {
1516
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().localNumUint;
1517
+ },
1518
+ /**
1519
+ * Number of local state byteslices in ApplicationCall
1520
+ */
1521
+ get localNumByteSlice() {
1522
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().localNumBytes;
1523
+ },
1524
+ /**
1525
+ * Number of additional pages for each of the application's approval and clear state programs. An ExtraProgramPages of 1 means 2048 more total bytes, or 1024 for each program.
1526
+ */
1527
+ get extraProgramPages() {
1528
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().extraProgramPages;
1529
+ },
1530
+ /**
1531
+ * Marks an account nonparticipating for rewards
1532
+ */
1533
+ get nonparticipation() {
1534
+ return lazyContext.activeGroup.getItxnGroup().getKeyRegistrationInnerTxn().nonparticipation;
1535
+ },
1536
+ /**
1537
+ * Log messages emitted by an application call (only with `itxn` in v5). Application mode only
1538
+ */
1539
+ logs(a) {
1540
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().logs(asUint64(a));
1541
+ },
1542
+ /**
1543
+ * Number of Logs (only with `itxn` in v5). Application mode only
1544
+ */
1545
+ get numLogs() {
1546
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().numLogs;
1547
+ },
1548
+ /**
1549
+ * Asset ID allocated by the creation of an ASA (only with `itxn` in v5). Application mode only
1550
+ */
1551
+ get createdAssetId() {
1552
+ return lazyContext.activeGroup.getItxnGroup().getAssetConfigInnerTxn().createdAsset;
1553
+ },
1554
+ /**
1555
+ * ApplicationID allocated by the creation of an application (only with `itxn` in v5). Application mode only
1556
+ */
1557
+ get createdApplicationId() {
1558
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().createdApp;
1559
+ },
1560
+ /**
1561
+ * The last message emitted. Empty bytes if none were emitted. Application mode only
1562
+ */
1563
+ get lastLog() {
1564
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().lastLog;
1565
+ },
1566
+ /**
1567
+ * 64 byte state proof public key
1568
+ */
1569
+ get stateProofPk() {
1570
+ return lazyContext.activeGroup.getItxnGroup().getKeyRegistrationInnerTxn().stateProofKey;
1571
+ },
1572
+ /**
1573
+ * Approval Program as an array of pages
1574
+ */
1575
+ approvalProgramPages(a) {
1576
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().approvalProgramPages(asUint64(a));
1577
+ },
1578
+ /**
1579
+ * Number of Approval Program pages
1580
+ */
1581
+ get numApprovalProgramPages() {
1582
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().numApprovalProgramPages;
1583
+ },
1584
+ /**
1585
+ * ClearState Program as an array of pages
1586
+ */
1587
+ clearStateProgramPages(a) {
1588
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().clearStateProgramPages(asUint64(a));
1589
+ },
1590
+ /**
1591
+ * Number of ClearState Program pages
1592
+ */
1593
+ get numClearStateProgramPages() {
1594
+ return lazyContext.activeGroup.getItxnGroup().getApplicationInnerTxn().numClearStateProgramPages;
1595
+ },
1596
+ };
1597
+ const setConstructingItxnField = (fields) => {
1598
+ Object.assign(lazyContext.activeGroup.constructingItxn, fields);
1599
+ };
1600
+ const getConstructingItxn = () => {
1601
+ return lazyContext.activeGroup.constructingItxn;
1602
+ };
1603
+ const ITxnCreate = {
1604
+ begin: function () {
1605
+ lazyContext.activeGroup.beginInnerTransactionGroup();
1606
+ },
1607
+ setSender: function (a) {
1608
+ setConstructingItxnField({ sender: a });
1609
+ },
1610
+ setFee: function (a) {
1611
+ setConstructingItxnField({ fee: asUint64(a) });
1612
+ },
1613
+ setNote: function (a) {
1614
+ setConstructingItxnField({ note: asBytes(a) });
1615
+ },
1616
+ setReceiver: function (a) {
1617
+ setConstructingItxnField({ receiver: a });
1618
+ },
1619
+ setAmount: function (a) {
1620
+ setConstructingItxnField({ amount: asUint64(a) });
1621
+ },
1622
+ setCloseRemainderTo: function (a) {
1623
+ setConstructingItxnField({ closeRemainderTo: a });
1624
+ },
1625
+ setVotePk: function (a) {
1626
+ setConstructingItxnField({ voteKey: asBytes(a) });
1627
+ },
1628
+ setSelectionPk: function (a) {
1629
+ setConstructingItxnField({ selectionKey: asBytes(a) });
1630
+ },
1631
+ setVoteFirst: function (a) {
1632
+ setConstructingItxnField({ voteFirst: asUint64(a) });
1633
+ },
1634
+ setVoteLast: function (a) {
1635
+ setConstructingItxnField({ voteLast: asUint64(a) });
1636
+ },
1637
+ setVoteKeyDilution: function (a) {
1638
+ setConstructingItxnField({ voteKeyDilution: asUint64(a) });
1639
+ },
1640
+ setType: function (a) {
1641
+ setConstructingItxnField({ type: asBytesCls(a).toUint64().asNumber() });
1642
+ },
1643
+ setTypeEnum: function (a) {
1644
+ setConstructingItxnField({ type: asUint64Cls(a).asNumber() });
1645
+ },
1646
+ setXferAsset: function (a) {
1647
+ setConstructingItxnField({ xferAsset: getAsset(a) });
1648
+ },
1649
+ setAssetAmount: function (a) {
1650
+ setConstructingItxnField({ assetAmount: asUint64(a) });
1651
+ },
1652
+ setAssetSender: function (a) {
1653
+ setConstructingItxnField({ assetSender: a });
1654
+ },
1655
+ setAssetReceiver: function (a) {
1656
+ setConstructingItxnField({ assetReceiver: a });
1657
+ },
1658
+ setAssetCloseTo: function (a) {
1659
+ setConstructingItxnField({ assetCloseTo: a });
1660
+ },
1661
+ setApplicationId: function (a) {
1662
+ setConstructingItxnField({ appId: getApp(a) });
1663
+ },
1664
+ setOnCompletion: function (a) {
1665
+ setConstructingItxnField({ onCompletion: asUint64(a) });
1666
+ },
1667
+ setApplicationArgs: function (a) {
1668
+ const appArgs = (getConstructingItxn().appArgs ?? []);
1669
+ appArgs.push(asBytes(a));
1670
+ setConstructingItxnField({ appArgs });
1671
+ },
1672
+ setAccounts: function (a) {
1673
+ const accounts = (getConstructingItxn().accounts ?? []);
1674
+ accounts.push(a);
1675
+ setConstructingItxnField({ accounts });
1676
+ },
1677
+ setApprovalProgram: function (a) {
1678
+ setConstructingItxnField({ approvalProgram: asBytes(a) });
1679
+ },
1680
+ setClearStateProgram: function (a) {
1681
+ setConstructingItxnField({ clearStateProgram: asBytes(a) });
1682
+ },
1683
+ setRekeyTo: function (a) {
1684
+ setConstructingItxnField({ rekeyTo: a });
1685
+ },
1686
+ setConfigAsset: function (a) {
1687
+ setConstructingItxnField({ configAsset: getAsset(a) });
1688
+ },
1689
+ setConfigAssetTotal: function (a) {
1690
+ setConstructingItxnField({ total: asUint64(a) });
1691
+ },
1692
+ setConfigAssetDecimals: function (a) {
1693
+ setConstructingItxnField({ decimals: asUint64(a) });
1694
+ },
1695
+ setConfigAssetDefaultFrozen: function (a) {
1696
+ setConstructingItxnField({ defaultFrozen: a });
1697
+ },
1698
+ setConfigAssetUnitName: function (a) {
1699
+ setConstructingItxnField({ unitName: asBytes(a) });
1700
+ },
1701
+ setConfigAssetName: function (a) {
1702
+ setConstructingItxnField({ assetName: asBytes(a) });
1703
+ },
1704
+ setConfigAssetUrl: function (a) {
1705
+ setConstructingItxnField({ url: asBytes(a) });
1706
+ },
1707
+ setConfigAssetMetadataHash: function (a) {
1708
+ setConstructingItxnField({ metadataHash: asBytes(a) });
1709
+ },
1710
+ setConfigAssetManager: function (a) {
1711
+ setConstructingItxnField({ manager: a });
1712
+ },
1713
+ setConfigAssetReserve: function (a) {
1714
+ setConstructingItxnField({ reserve: a });
1715
+ },
1716
+ setConfigAssetFreeze: function (a) {
1717
+ setConstructingItxnField({ freeze: a });
1718
+ },
1719
+ setConfigAssetClawback: function (a) {
1720
+ setConstructingItxnField({ clawback: a });
1721
+ },
1722
+ setFreezeAsset: function (a) {
1723
+ setConstructingItxnField({ freezeAsset: getAsset(a) });
1724
+ },
1725
+ setFreezeAssetAccount: function (a) {
1726
+ setConstructingItxnField({ freezeAccount: a });
1727
+ },
1728
+ setFreezeAssetFrozen: function (a) {
1729
+ setConstructingItxnField({ frozen: a });
1730
+ },
1731
+ setAssets: function (a) {
1732
+ const asset = getAsset(a);
1733
+ if (asset) {
1734
+ const assets = (getConstructingItxn().assets ?? []);
1735
+ assets.push(asset);
1736
+ setConstructingItxnField({ assets });
1737
+ }
1738
+ },
1739
+ setApplications: function (a) {
1740
+ const app = getApp(a);
1741
+ if (app) {
1742
+ const apps = (getConstructingItxn().apps ?? []);
1743
+ apps.push(app);
1744
+ setConstructingItxnField({ apps });
1745
+ }
1746
+ },
1747
+ setGlobalNumUint: function (a) {
1748
+ setConstructingItxnField({ globalNumUint: asUint64(a) });
1749
+ },
1750
+ setGlobalNumByteSlice: function (a) {
1751
+ setConstructingItxnField({ globalNumBytes: asUint64(a) });
1752
+ },
1753
+ setLocalNumUint: function (a) {
1754
+ setConstructingItxnField({ localNumUint: asUint64(a) });
1755
+ },
1756
+ setLocalNumByteSlice: function (a) {
1757
+ setConstructingItxnField({ localNumBytes: asUint64(a) });
1758
+ },
1759
+ setExtraProgramPages: function (a) {
1760
+ setConstructingItxnField({ extraProgramPages: asUint64(a) });
1761
+ },
1762
+ setNonparticipation: function (a) {
1763
+ setConstructingItxnField({ nonparticipation: a });
1764
+ },
1765
+ setStateProofPk: function (a) {
1766
+ setConstructingItxnField({ stateProofKey: asBytes(a) });
1767
+ },
1768
+ setApprovalProgramPages: function (a) {
1769
+ let pages = (getConstructingItxn().approvalProgram ?? []);
1770
+ if (!Array.isArray(pages)) {
1771
+ pages = [pages];
1772
+ }
1773
+ pages.push(asBytes(a));
1774
+ setConstructingItxnField({ approvalProgram: pages });
1775
+ },
1776
+ setClearStateProgramPages: function (a) {
1777
+ let pages = (getConstructingItxn().clearStateProgram ?? []);
1778
+ if (!Array.isArray(pages)) {
1779
+ pages = [pages];
1780
+ }
1781
+ pages.push(asBytes(a));
1782
+ setConstructingItxnField({ clearStateProgram: pages });
1783
+ },
1784
+ next: function () {
1785
+ lazyContext.activeGroup.appendInnerTransactionGroup();
1786
+ },
1787
+ submit: function () {
1788
+ lazyContext.activeGroup.submitInnerTransactionGroup();
1789
+ },
1790
+ };
1791
+
1792
+ const addw = (a, b) => {
1793
+ const uint64A = internal.primitives.Uint64Cls.fromCompat(a);
1794
+ const uint64B = internal.primitives.Uint64Cls.fromCompat(b);
1795
+ const sum = uint64A.asBigInt() + uint64B.asBigInt();
1796
+ return toUint128(sum);
1797
+ };
1798
+ const base64Decode = (e, a) => {
1799
+ const encoding = e === Base64.StdEncoding ? 'base64' : 'base64url';
1800
+ const bytesValue = internal.primitives.BytesCls.fromCompat(a);
1801
+ const stringValue = bytesValue.toString();
1802
+ const bufferResult = Buffer.from(stringValue, encoding);
1803
+ if (bufferResult.toString(encoding) !== stringValue) {
1804
+ internal.errors.avmError('illegal base64 data');
1805
+ }
1806
+ const uint8ArrayResult = new Uint8Array(bufferResult);
1807
+ return Bytes(uint8ArrayResult);
1808
+ };
1809
+ const bitLength = (a) => {
1810
+ const uint64Cls = asMaybeUint64Cls(a);
1811
+ const bigUintCls = asMaybeBytesCls(a)?.toBigUint();
1812
+ const bigIntValue = (uint64Cls?.asBigInt() ?? bigUintCls?.asBigInt());
1813
+ const binaryValue = bigIntValue === 0n ? '' : bigIntValue.toString(2);
1814
+ return Uint64(binaryValue.length);
1815
+ };
1816
+ const bsqrt = (a) => {
1817
+ const bigUintClsValue = internal.primitives.BigUintCls.fromCompat(a);
1818
+ const bigintValue = internal.primitives.checkBigUint(bigUintClsValue.asBigInt());
1819
+ const sqrtValue = squareroot(bigintValue);
1820
+ return asBigUint(sqrtValue);
1821
+ };
1822
+ const btoi = (a) => {
1823
+ const bytesValue = internal.primitives.BytesCls.fromCompat(a);
1824
+ if (bytesValue.length.asAlgoTs() > BITS_IN_BYTE) {
1825
+ internal.errors.avmError(`btoi arg too long, got [${bytesValue.length.valueOf()}]bytes`);
1826
+ }
1827
+ return bytesValue.toUint64().asAlgoTs();
1828
+ };
1829
+ const bzero = (a) => {
1830
+ const size = internal.primitives.Uint64Cls.fromCompat(a).asBigInt();
1831
+ if (size > MAX_BYTES_SIZE) {
1832
+ internal.errors.avmError('bzero attempted to create a too large string');
1833
+ }
1834
+ return Bytes(new Uint8Array(Number(size)));
1835
+ };
1836
+ const concat = (a, b) => {
1837
+ const bytesA = internal.primitives.BytesCls.fromCompat(a);
1838
+ const bytesB = internal.primitives.BytesCls.fromCompat(b);
1839
+ return bytesA.concat(bytesB).asAlgoTs();
1840
+ };
1841
+ const divmodw = (a, b, c, d) => {
1842
+ const i = uint128ToBigInt(a, b);
1843
+ const j = uint128ToBigInt(c, d);
1844
+ const div = i / j;
1845
+ const mod = i % j;
1846
+ return [...toUint128(div), ...toUint128(mod)];
1847
+ };
1848
+ const divw = (a, b, c) => {
1849
+ const i = uint128ToBigInt(a, b);
1850
+ const j = internal.primitives.Uint64Cls.fromCompat(c).asBigInt();
1851
+ return Uint64(i / j);
1852
+ };
1853
+ const exp = (a, b) => {
1854
+ const base = internal.primitives.Uint64Cls.fromCompat(a).asBigInt();
1855
+ const exponent = internal.primitives.Uint64Cls.fromCompat(b).asBigInt();
1856
+ if (base === 0n && exponent === 0n) {
1857
+ throw internal.errors.codeError('0 ** 0 is undefined');
1858
+ }
1859
+ return Uint64(base ** exponent);
1860
+ };
1861
+ const expw = (a, b) => {
1862
+ const base = internal.primitives.Uint64Cls.fromCompat(a).asBigInt();
1863
+ const exponent = internal.primitives.Uint64Cls.fromCompat(b).asBigInt();
1864
+ if (base === 0n && exponent === 0n) {
1865
+ throw internal.errors.codeError('0 ** 0 is undefined');
1866
+ }
1867
+ return toUint128(base ** exponent);
1868
+ };
1869
+ const extract = (a, b, c) => {
1870
+ const bytesValue = internal.primitives.BytesCls.fromCompat(a);
1871
+ const bytesLength = bytesValue.length.asBigInt();
1872
+ const start = internal.primitives.Uint64Cls.fromCompat(b).asBigInt();
1873
+ const length = internal.primitives.Uint64Cls.fromCompat(c).asBigInt();
1874
+ let end = start + length;
1875
+ if ((typeof b === 'number' || typeof b === 'bigint') && (typeof c === 'number' || typeof c === 'bigint') && length === 0n) {
1876
+ end = bytesLength;
1877
+ }
1878
+ if (start > bytesLength) {
1879
+ internal.errors.codeError(`extraction start ${start} is beyond length`);
1880
+ }
1881
+ if (end > bytesLength) {
1882
+ internal.errors.codeError(`extraction end ${end} is beyond length`);
1883
+ }
1884
+ return bytesValue.slice(start, end).asAlgoTs();
1885
+ };
1886
+ const extractUint16 = (a, b) => {
1887
+ const result = extract(a, b, 2);
1888
+ const bytesResult = internal.primitives.BytesCls.fromCompat(result);
1889
+ return bytesResult.toUint64().asAlgoTs();
1890
+ };
1891
+ const extractUint32 = (a, b) => {
1892
+ const result = extract(a, b, 4);
1893
+ const bytesResult = internal.primitives.BytesCls.fromCompat(result);
1894
+ return bytesResult.toUint64().asAlgoTs();
1895
+ };
1896
+ const extractUint64 = (a, b) => {
1897
+ const result = extract(a, b, 8);
1898
+ const bytesResult = internal.primitives.BytesCls.fromCompat(result);
1899
+ return bytesResult.toUint64().asAlgoTs();
1900
+ };
1901
+ const getBit = (a, b) => {
1902
+ const binaryString = toBinaryString(internal.primitives.isUint64(a) ? asUint64Cls(a).toBytes().asAlgoTs() : asBytes(a));
1903
+ const index = internal.primitives.Uint64Cls.fromCompat(b).asNumber();
1904
+ const adjustedIndex = asMaybeUint64Cls(a) ? binaryString.length - index - 1 : index;
1905
+ if (adjustedIndex < 0 || adjustedIndex >= binaryString.length) {
1906
+ internal.errors.codeError(`getBit index ${index} is beyond length`);
1907
+ }
1908
+ return binaryString[adjustedIndex] === '1' ? Uint64(1) : Uint64(0);
1909
+ };
1910
+ const getByte = (a, b) => {
1911
+ const bytesValue = internal.primitives.BytesCls.fromCompat(a);
1912
+ const index = internal.primitives.Uint64Cls.fromCompat(b).asNumber();
1913
+ if (index >= bytesValue.length.asNumber()) {
1914
+ internal.errors.codeError(`getBytes index ${index} is beyond length`);
1915
+ }
1916
+ return bytesValue.at(index).toUint64().asAlgoTs();
1917
+ };
1918
+ const itob = (a) => {
1919
+ return asUint64Cls(a).toBytes().asAlgoTs();
1920
+ };
1921
+ const mulw = (a, b) => {
1922
+ const uint64A = internal.primitives.Uint64Cls.fromCompat(a);
1923
+ const uint64B = internal.primitives.Uint64Cls.fromCompat(b);
1924
+ const product = uint64A.asBigInt() * uint64B.asBigInt();
1925
+ return toUint128(product);
1926
+ };
1927
+ const replace = (a, b, c) => {
1928
+ const bytesValue = internal.primitives.BytesCls.fromCompat(a);
1929
+ const index = internal.primitives.Uint64Cls.fromCompat(b).asNumber();
1930
+ const replacement = internal.primitives.BytesCls.fromCompat(c);
1931
+ const valueLength = bytesValue.length.asNumber();
1932
+ const replacementLength = replacement.length.asNumber();
1933
+ if (index + replacementLength > valueLength) {
1934
+ internal.errors.codeError(`expected value <= ${valueLength}, got: ${index + replacementLength}`);
1935
+ }
1936
+ return bytesValue
1937
+ .slice(0, index)
1938
+ .concat(replacement)
1939
+ .concat(bytesValue.slice(index + replacementLength, valueLength))
1940
+ .asAlgoTs();
1941
+ };
1942
+ const select = ((a, b, c) => {
1943
+ const uint64A = asMaybeUint64Cls(a);
1944
+ const uint64B = asMaybeUint64Cls(b);
1945
+ const bytesA = asMaybeBytesCls(a);
1946
+ const bytesB = asMaybeBytesCls(b);
1947
+ const bigIntC = internal.primitives.Uint64Cls.fromCompat(c).asBigInt();
1948
+ return (bigIntC !== 0n ? (uint64B ?? bytesB) : (uint64A ?? bytesA)).asAlgoTs();
1949
+ });
1950
+ const setBit = ((a, b, c) => {
1951
+ const uint64Cls = asMaybeUint64Cls(a);
1952
+ const indexParam = internal.primitives.Uint64Cls.fromCompat(b).asNumber();
1953
+ const bit = internal.primitives.Uint64Cls.fromCompat(c).asNumber();
1954
+ if (uint64Cls) {
1955
+ const binaryString = toBinaryString(uint64Cls?.toBytes().asAlgoTs());
1956
+ const index = binaryString.length - indexParam - 1;
1957
+ const newBytes = doSetBit(binaryString, index, bit);
1958
+ return newBytes.toUint64().asAlgoTs();
1959
+ }
1960
+ else {
1961
+ const bytesCls = asMaybeBytesCls(a);
1962
+ testInvariant(bytesCls, 'a must be uint64 or bytes');
1963
+ const binaryString = toBinaryString(bytesCls.asAlgoTs());
1964
+ const newBytes = doSetBit(binaryString, indexParam, bit);
1965
+ return newBytes.asAlgoTs();
1966
+ }
1967
+ });
1968
+ const setByte = (a, b, c) => {
1969
+ const binaryString = toBinaryString(internal.primitives.BytesCls.fromCompat(a).asAlgoTs());
1970
+ const byteIndex = internal.primitives.Uint64Cls.fromCompat(b).asNumber();
1971
+ const bitIndex = byteIndex * BITS_IN_BYTE;
1972
+ const replacementNumber = internal.primitives.Uint64Cls.fromCompat(c);
1973
+ const replacement = toBinaryString(replacementNumber.toBytes().at(-1).asAlgoTs());
1974
+ if (bitIndex >= binaryString.length) {
1975
+ internal.errors.codeError(`setByte index ${byteIndex} is beyond length`);
1976
+ }
1977
+ if (replacementNumber.valueOf() > MAX_UINT8) {
1978
+ internal.errors.codeError(`setByte value ${replacementNumber.asNumber()} > ${MAX_UINT8}`);
1979
+ }
1980
+ const updatedString = binaryString.slice(0, bitIndex) + replacement + binaryString.slice(bitIndex + replacement.length);
1981
+ const updatedBytes = binaryStringToBytes(updatedString);
1982
+ return updatedBytes.asAlgoTs();
1983
+ };
1984
+ const shl = (a, b) => {
1985
+ const uint64A = internal.primitives.Uint64Cls.fromCompat(a);
1986
+ const uint64B = internal.primitives.Uint64Cls.fromCompat(b);
1987
+ const bigIntA = uint64A.asBigInt();
1988
+ const bigIntB = uint64B.asBigInt();
1989
+ if (bigIntB >= UINT64_SIZE) {
1990
+ internal.errors.codeError(`shl value ${bigIntB} >= ${UINT64_SIZE}`);
1991
+ }
1992
+ const shifted = (bigIntA * 2n ** bigIntB) % 2n ** BigInt(UINT64_SIZE);
1993
+ return Uint64(shifted);
1994
+ };
1995
+ const shr = (a, b) => {
1996
+ const uint64A = internal.primitives.Uint64Cls.fromCompat(a);
1997
+ const uint64B = internal.primitives.Uint64Cls.fromCompat(b);
1998
+ const bigIntA = uint64A.asBigInt();
1999
+ const bigIntB = uint64B.asBigInt();
2000
+ if (bigIntB >= UINT64_SIZE) {
2001
+ internal.errors.codeError(`shr value ${bigIntB} >= ${UINT64_SIZE}`);
2002
+ }
2003
+ const shifted = bigIntA / 2n ** bigIntB;
2004
+ return Uint64(shifted);
2005
+ };
2006
+ const sqrt = (a) => {
2007
+ const bigIntValue = internal.primitives.Uint64Cls.fromCompat(a).asBigInt();
2008
+ const sqrtValue = squareroot(bigIntValue);
2009
+ return Uint64(sqrtValue);
2010
+ };
2011
+ const substring = (a, b, c) => {
2012
+ const bytesValue = internal.primitives.BytesCls.fromCompat(a);
2013
+ const start = internal.primitives.Uint64Cls.fromCompat(b).asBigInt();
2014
+ const end = internal.primitives.Uint64Cls.fromCompat(c).asBigInt();
2015
+ if (start > end) {
2016
+ internal.errors.codeError('substring end before start');
2017
+ }
2018
+ if (end > bytesValue.length.asNumber()) {
2019
+ internal.errors.codeError('substring range beyond length of string');
2020
+ }
2021
+ return bytesValue.slice(start, end).asAlgoTs();
2022
+ };
2023
+ const JsonRef = new Proxy({}, {
2024
+ get: (_target, prop) => {
2025
+ notImplementedError(`JsonRef.${prop.toString()}`);
2026
+ },
2027
+ });
2028
+ const squareroot = (x) => {
2029
+ let lo = 0n, hi = x;
2030
+ while (lo <= hi) {
2031
+ const mid = (lo + hi) / 2n;
2032
+ if (mid * mid > x)
2033
+ hi = mid - 1n;
2034
+ else
2035
+ lo = mid + 1n;
2036
+ }
2037
+ return hi;
2038
+ };
2039
+ const toUint128 = (value) => {
2040
+ const cf = value >> 64n;
2041
+ const rest = value & MAX_UINT64;
2042
+ return [Uint64(cf), Uint64(rest)];
2043
+ };
2044
+ const uint128ToBigInt = (a, b) => {
2045
+ const bigIntA = internal.primitives.Uint64Cls.fromCompat(a).asBigInt();
2046
+ const bigIntB = internal.primitives.Uint64Cls.fromCompat(b).asBigInt();
2047
+ return (bigIntA << 64n) + bigIntB;
2048
+ };
2049
+ const toBinaryString = (a) => {
2050
+ return [...internal.primitives.BytesCls.fromCompat(a).asUint8Array()].map((x) => x.toString(2).padStart(BITS_IN_BYTE, '0')).join('');
2051
+ };
2052
+ const doSetBit = (binaryString, index, bit) => {
2053
+ if (index < 0 || index >= binaryString.length) {
2054
+ internal.errors.codeError(`setBit index ${index < 0 ? binaryString.length - index : index} is beyond length`);
2055
+ }
2056
+ if (bit !== 0 && bit !== 1) {
2057
+ internal.errors.codeError(`setBit value > 1`);
2058
+ }
2059
+ const updatedString = binaryString.slice(0, index) + bit.toString() + binaryString.slice(index + 1);
2060
+ return binaryStringToBytes(updatedString);
2061
+ };
2062
+
2063
+ const gloadUint64 = (a, b) => {
2064
+ const txn = lazyContext.activeGroup.getTransaction(a);
2065
+ const result = txn.getScratchSlot(b);
2066
+ if (result instanceof internal.primitives.Uint64Cls) {
2067
+ return result.asAlgoTs();
2068
+ }
2069
+ throw new internal.errors.InternalError('invalid scratch slot type');
2070
+ };
2071
+ const gloadBytes = (a, b) => {
2072
+ const txn = lazyContext.activeGroup.getTransaction(a);
2073
+ const result = txn.getScratchSlot(b);
2074
+ if (result instanceof internal.primitives.BytesCls) {
2075
+ return result.asAlgoTs();
2076
+ }
2077
+ throw new internal.errors.InternalError('invalid scratch slot type');
2078
+ };
2079
+ const Scratch = {
2080
+ loadBytes: function (a) {
2081
+ const result = lazyContext.activeGroup.activeTransaction.getScratchSlot(a);
2082
+ if (result instanceof internal.primitives.BytesCls) {
2083
+ return result;
2084
+ }
2085
+ throw new internal.errors.InternalError('invalid scratch slot type');
2086
+ },
2087
+ loadUint64: function (a) {
2088
+ const result = lazyContext.activeGroup.activeTransaction.getScratchSlot(a);
2089
+ if (result instanceof internal.primitives.Uint64Cls) {
2090
+ return result;
2091
+ }
2092
+ throw new internal.errors.InternalError('invalid scratch slot type');
2093
+ },
2094
+ store: function (a, b) {
2095
+ lazyContext.activeGroup.activeTransaction.setScratchSlot(a, b);
2096
+ },
2097
+ };
2098
+
2099
+ const Block = {
2100
+ blkSeed: function (a) {
2101
+ return itob(lazyContext.ledger.getBlockContent(a).seed);
2102
+ },
2103
+ blkTimestamp: function (a) {
2104
+ return asUint64(lazyContext.ledger.getBlockContent(a).timestamp);
2105
+ },
2106
+ // TODO: implement v11 methods
2107
+ blkProposer: function (_a) {
2108
+ throw new Error('Function not implemented.');
2109
+ },
2110
+ blkFeesCollected: function (_a) {
2111
+ throw new Error('Function not implemented.');
2112
+ },
2113
+ blkBonus: function (_a) {
2114
+ throw new Error('Function not implemented.');
2115
+ },
2116
+ blkBranch: function (_a) {
2117
+ throw new Error('Function not implemented.');
2118
+ },
2119
+ blkFeeSink: function (_a) {
2120
+ throw new Error('Function not implemented.');
2121
+ },
2122
+ blkProtocol: function (_a) {
2123
+ throw new Error('Function not implemented.');
2124
+ },
2125
+ blkTxnCounter: function (_a) {
2126
+ throw new Error('Function not implemented.');
2127
+ },
2128
+ blkProposerPayout: function (_a) {
2129
+ throw new Error('Function not implemented.');
2130
+ },
2131
+ };
2132
+
2133
+ const gaid = (a) => {
2134
+ const group = lazyContext.activeGroup;
2135
+ const transaction = group.getTransaction(a);
2136
+ if (transaction.type === TransactionType.ApplicationCall) {
2137
+ return transaction.createdApp.id;
2138
+ }
2139
+ else if (transaction.type === TransactionType.AssetConfig) {
2140
+ return transaction.createdAsset.id;
2141
+ }
2142
+ else {
2143
+ throw new internal.errors.InternalError(`transaction at index ${asNumber(a)} is not an Application Call or Asset Config`);
2144
+ }
2145
+ };
2146
+ const Txn = {
2147
+ get sender() {
2148
+ return lazyContext.activeGroup.getTransaction().sender;
2149
+ },
2150
+ /**
2151
+ * microalgos
2152
+ */
2153
+ get fee() {
2154
+ return lazyContext.activeGroup.getTransaction().fee;
2155
+ },
2156
+ /**
2157
+ * round number
2158
+ */
2159
+ get firstValid() {
2160
+ return lazyContext.activeGroup.getTransaction().firstValid;
2161
+ },
2162
+ /**
2163
+ * UNIX timestamp of block before txn.FirstValid. Fails if negative
2164
+ */
2165
+ get firstValidTime() {
2166
+ return lazyContext.activeGroup.getTransaction().firstValidTime;
2167
+ },
2168
+ /**
2169
+ * round number
2170
+ */
2171
+ get lastValid() {
2172
+ return lazyContext.activeGroup.getTransaction().lastValid;
2173
+ },
2174
+ /**
2175
+ * Any data up to 1024 bytes
2176
+ */
2177
+ get note() {
2178
+ return lazyContext.activeGroup.getTransaction().note;
2179
+ },
2180
+ /**
2181
+ * 32 byte lease value
2182
+ */
2183
+ get lease() {
2184
+ return lazyContext.activeGroup.getTransaction().lease;
2185
+ },
2186
+ /**
2187
+ * 32 byte address
2188
+ */
2189
+ get receiver() {
2190
+ return lazyContext.activeGroup.getPaymentTransaction().receiver;
2191
+ },
2192
+ /**
2193
+ * microalgos
2194
+ */
2195
+ get amount() {
2196
+ return lazyContext.activeGroup.getPaymentTransaction().amount;
2197
+ },
2198
+ /**
2199
+ * 32 byte address
2200
+ */
2201
+ get closeRemainderTo() {
2202
+ return lazyContext.activeGroup.getPaymentTransaction().closeRemainderTo;
2203
+ },
2204
+ /**
2205
+ * 32 byte address
2206
+ */
2207
+ get votePk() {
2208
+ return lazyContext.activeGroup.getKeyRegistrationTransaction().voteKey;
2209
+ },
2210
+ /**
2211
+ * 32 byte address
2212
+ */
2213
+ get selectionPk() {
2214
+ return lazyContext.activeGroup.getKeyRegistrationTransaction().selectionKey;
2215
+ },
2216
+ /**
2217
+ * The first round that the participation key is valid.
2218
+ */
2219
+ get voteFirst() {
2220
+ return lazyContext.activeGroup.getKeyRegistrationTransaction().voteFirst;
2221
+ },
2222
+ /**
2223
+ * The last round that the participation key is valid.
2224
+ */
2225
+ get voteLast() {
2226
+ return lazyContext.activeGroup.getKeyRegistrationTransaction().voteLast;
2227
+ },
2228
+ /**
2229
+ * Dilution for the 2-level participation key
2230
+ */
2231
+ get voteKeyDilution() {
2232
+ return lazyContext.activeGroup.getKeyRegistrationTransaction().voteKeyDilution;
2233
+ },
2234
+ /**
2235
+ * Transaction type as bytes
2236
+ */
2237
+ get type() {
2238
+ return asUint64Cls(lazyContext.activeGroup.getTransaction().type).toBytes().asAlgoTs();
2239
+ },
2240
+ /**
2241
+ * Transaction type as integer
2242
+ */
2243
+ get typeEnum() {
2244
+ return asUint64(lazyContext.activeGroup.getTransaction().type);
2245
+ },
2246
+ /**
2247
+ * Asset ID
2248
+ */
2249
+ get xferAsset() {
2250
+ return lazyContext.activeGroup.getAssetTransferTransaction().xferAsset;
2251
+ },
2252
+ /**
2253
+ * value in Asset's units
2254
+ */
2255
+ get assetAmount() {
2256
+ return lazyContext.activeGroup.getAssetTransferTransaction().assetAmount;
2257
+ },
2258
+ /**
2259
+ * 32 byte address. Source of assets if Sender is the Asset's Clawback address.
2260
+ */
2261
+ get assetSender() {
2262
+ return lazyContext.activeGroup.getAssetTransferTransaction().assetSender;
2263
+ },
2264
+ /**
2265
+ * 32 byte address
2266
+ */
2267
+ get assetReceiver() {
2268
+ return lazyContext.activeGroup.getAssetTransferTransaction().assetReceiver;
2269
+ },
2270
+ /**
2271
+ * 32 byte address
2272
+ */
2273
+ get assetCloseTo() {
2274
+ return lazyContext.activeGroup.getAssetTransferTransaction().assetCloseTo;
2275
+ },
2276
+ /**
2277
+ * Position of this transaction within an atomic transaction group. A stand-alone transaction is implicitly element 0 in a group of 1
2278
+ */
2279
+ get groupIndex() {
2280
+ return lazyContext.activeGroup.getTransaction().groupIndex;
2281
+ },
2282
+ /**
2283
+ * The computed ID for this transaction. 32 bytes.
2284
+ */
2285
+ get txId() {
2286
+ return lazyContext.activeGroup.getTransaction().txnId;
2287
+ },
2288
+ /**
2289
+ * ApplicationID from ApplicationCall transaction
2290
+ */
2291
+ get applicationId() {
2292
+ return lazyContext.activeGroup.getApplicationTransaction().appId;
2293
+ },
2294
+ /**
2295
+ * ApplicationCall transaction on completion action
2296
+ */
2297
+ get onCompletion() {
2298
+ const onCompletionStr = lazyContext.activeGroup.getApplicationTransaction().onCompletion;
2299
+ return asUint64(arc4.OnCompleteAction[onCompletionStr]);
2300
+ },
2301
+ /**
2302
+ * Arguments passed to the application in the ApplicationCall transaction
2303
+ */
2304
+ applicationArgs(a) {
2305
+ return lazyContext.activeGroup.getApplicationTransaction().appArgs(asUint64(a));
2306
+ },
2307
+ /**
2308
+ * Number of ApplicationArgs
2309
+ */
2310
+ get numAppArgs() {
2311
+ return lazyContext.activeGroup.getApplicationTransaction().numAppArgs;
2312
+ },
2313
+ /**
2314
+ * Accounts listed in the ApplicationCall transaction
2315
+ */
2316
+ accounts(a) {
2317
+ return lazyContext.activeGroup.getApplicationTransaction().accounts(asUint64(a));
2318
+ },
2319
+ /**
2320
+ * Number of Accounts
2321
+ */
2322
+ get numAccounts() {
2323
+ return lazyContext.activeGroup.getApplicationTransaction().numAccounts;
2324
+ },
2325
+ /**
2326
+ * Approval program
2327
+ */
2328
+ get approvalProgram() {
2329
+ return lazyContext.activeGroup.getApplicationTransaction().approvalProgram;
2330
+ },
2331
+ /**
2332
+ * Clear state program
2333
+ */
2334
+ get clearStateProgram() {
2335
+ return lazyContext.activeGroup.getApplicationTransaction().clearStateProgram;
2336
+ },
2337
+ /**
2338
+ * 32 byte Sender's new AuthAddr
2339
+ */
2340
+ get rekeyTo() {
2341
+ return lazyContext.activeGroup.getTransaction().rekeyTo;
2342
+ },
2343
+ /**
2344
+ * Asset ID in asset config transaction
2345
+ */
2346
+ get configAsset() {
2347
+ return lazyContext.activeGroup.getAssetConfigTransaction().configAsset;
2348
+ },
2349
+ /**
2350
+ * Total number of units of this asset created
2351
+ */
2352
+ get configAssetTotal() {
2353
+ return lazyContext.activeGroup.getAssetConfigTransaction().total;
2354
+ },
2355
+ /**
2356
+ * Number of digits to display after the decimal place when displaying the asset
2357
+ */
2358
+ get configAssetDecimals() {
2359
+ return lazyContext.activeGroup.getAssetConfigTransaction().decimals;
2360
+ },
2361
+ /**
2362
+ * Whether the asset's slots are frozen by default or not, 0 or 1
2363
+ */
2364
+ get configAssetDefaultFrozen() {
2365
+ return lazyContext.activeGroup.getAssetConfigTransaction().defaultFrozen;
2366
+ },
2367
+ /**
2368
+ * Unit name of the asset
2369
+ */
2370
+ get configAssetUnitName() {
2371
+ return lazyContext.activeGroup.getAssetConfigTransaction().unitName;
2372
+ },
2373
+ /**
2374
+ * The asset name
2375
+ */
2376
+ get configAssetName() {
2377
+ return lazyContext.activeGroup.getAssetConfigTransaction().assetName;
2378
+ },
2379
+ /**
2380
+ * URL
2381
+ */
2382
+ get configAssetUrl() {
2383
+ return lazyContext.activeGroup.getAssetConfigTransaction().url;
2384
+ },
2385
+ /**
2386
+ * 32 byte commitment to unspecified asset metadata
2387
+ */
2388
+ get configAssetMetadataHash() {
2389
+ return lazyContext.activeGroup.getAssetConfigTransaction().metadataHash;
2390
+ },
2391
+ /**
2392
+ * 32 byte address
2393
+ */
2394
+ get configAssetManager() {
2395
+ return lazyContext.activeGroup.getAssetConfigTransaction().manager;
2396
+ },
2397
+ /**
2398
+ * 32 byte address
2399
+ */
2400
+ get configAssetReserve() {
2401
+ return lazyContext.activeGroup.getAssetConfigTransaction().reserve;
2402
+ },
2403
+ /**
2404
+ * 32 byte address
2405
+ */
2406
+ get configAssetFreeze() {
2407
+ return lazyContext.activeGroup.getAssetConfigTransaction().freeze;
2408
+ },
2409
+ /**
2410
+ * 32 byte address
2411
+ */
2412
+ get configAssetClawback() {
2413
+ return lazyContext.activeGroup.getAssetConfigTransaction().clawback;
2414
+ },
2415
+ /**
2416
+ * Asset ID being frozen or un-frozen
2417
+ */
2418
+ get freezeAsset() {
2419
+ return lazyContext.activeGroup.getAssetFreezeTransaction().freezeAsset;
2420
+ },
2421
+ /**
2422
+ * 32 byte address of the account whose asset slot is being frozen or un-frozen
2423
+ */
2424
+ get freezeAssetAccount() {
2425
+ return lazyContext.activeGroup.getAssetFreezeTransaction().freezeAccount;
2426
+ },
2427
+ /**
2428
+ * The new frozen value, 0 or 1
2429
+ */
2430
+ get freezeAssetFrozen() {
2431
+ return lazyContext.activeGroup.getAssetFreezeTransaction().frozen;
2432
+ },
2433
+ /**
2434
+ * Foreign Assets listed in the ApplicationCall transaction
2435
+ */
2436
+ assets(a) {
2437
+ return lazyContext.activeGroup.getApplicationTransaction().assets(asUint64(a));
2438
+ },
2439
+ /**
2440
+ * Number of Assets
2441
+ */
2442
+ get numAssets() {
2443
+ return lazyContext.activeGroup.getApplicationTransaction().numAssets;
2444
+ },
2445
+ /**
2446
+ * Foreign Apps listed in the ApplicationCall transaction
2447
+ */
2448
+ applications(a) {
2449
+ return lazyContext.activeGroup.getApplicationTransaction().apps(asUint64(a));
2450
+ },
2451
+ /**
2452
+ * Number of Applications
2453
+ */
2454
+ get numApplications() {
2455
+ return lazyContext.activeGroup.getApplicationTransaction().numApps;
2456
+ },
2457
+ /**
2458
+ * Number of global state integers in ApplicationCall
2459
+ */
2460
+ get globalNumUint() {
2461
+ return lazyContext.activeGroup.getApplicationTransaction().globalNumUint;
2462
+ },
2463
+ /**
2464
+ * Number of global state byteslices in ApplicationCall
2465
+ */
2466
+ get globalNumByteSlice() {
2467
+ return lazyContext.activeGroup.getApplicationTransaction().globalNumBytes;
2468
+ },
2469
+ /**
2470
+ * Number of local state integers in ApplicationCall
2471
+ */
2472
+ get localNumUint() {
2473
+ return lazyContext.activeGroup.getApplicationTransaction().localNumUint;
2474
+ },
2475
+ /**
2476
+ * Number of local state byteslices in ApplicationCall
2477
+ */
2478
+ get localNumByteSlice() {
2479
+ return lazyContext.activeGroup.getApplicationTransaction().localNumBytes;
2480
+ },
2481
+ /**
2482
+ * Number of additional pages for each of the application's approval and clear state programs. An ExtraProgramPages of 1 means 2048 more total bytes, or 1024 for each program.
2483
+ */
2484
+ get extraProgramPages() {
2485
+ return lazyContext.activeGroup.getApplicationTransaction().extraProgramPages;
2486
+ },
2487
+ /**
2488
+ * Marks an account nonparticipating for rewards
2489
+ */
2490
+ get nonparticipation() {
2491
+ return lazyContext.activeGroup.getKeyRegistrationTransaction().nonparticipation;
2492
+ },
2493
+ /**
2494
+ * Log messages emitted by an application call (only with `itxn` in v5). Application mode only
2495
+ */
2496
+ logs(a) {
2497
+ return lazyContext.activeGroup.getApplicationTransaction().logs(asUint64(a));
2498
+ },
2499
+ /**
2500
+ * Number of Logs (only with `itxn` in v5). Application mode only
2501
+ */
2502
+ get numLogs() {
2503
+ return lazyContext.activeGroup.getApplicationTransaction().numLogs;
2504
+ },
2505
+ /**
2506
+ * Asset ID allocated by the creation of an ASA (only with `itxn` in v5). Application mode only
2507
+ */
2508
+ get createdAssetId() {
2509
+ return lazyContext.activeGroup.getAssetConfigTransaction().createdAsset;
2510
+ },
2511
+ /**
2512
+ * ApplicationID allocated by the creation of an application (only with `itxn` in v5). Application mode only
2513
+ */
2514
+ get createdApplicationId() {
2515
+ return lazyContext.activeGroup.getApplicationTransaction().createdApp;
2516
+ },
2517
+ /**
2518
+ * The last message emitted. Empty bytes if none were emitted. Application mode only
2519
+ */
2520
+ get lastLog() {
2521
+ return lazyContext.activeGroup.getApplicationTransaction().lastLog;
2522
+ },
2523
+ /**
2524
+ * 64 byte state proof public key
2525
+ */
2526
+ get stateProofPk() {
2527
+ return lazyContext.activeGroup.getKeyRegistrationTransaction().stateProofKey;
2528
+ },
2529
+ /**
2530
+ * Approval Program as an array of pages
2531
+ */
2532
+ approvalProgramPages(a) {
2533
+ return lazyContext.activeGroup.getApplicationTransaction().approvalProgramPages(asUint64(a));
2534
+ },
2535
+ /**
2536
+ * Number of Approval Program pages
2537
+ */
2538
+ get numApprovalProgramPages() {
2539
+ return lazyContext.activeGroup.getApplicationTransaction().numApprovalProgramPages;
2540
+ },
2541
+ /**
2542
+ * ClearState Program as an array of pages
2543
+ */
2544
+ clearStateProgramPages(a) {
2545
+ return lazyContext.activeGroup.getApplicationTransaction().clearStateProgramPages(asUint64(a));
2546
+ },
2547
+ /**
2548
+ * Number of ClearState Program pages
2549
+ */
2550
+ get numClearStateProgramPages() {
2551
+ return lazyContext.activeGroup.getApplicationTransaction().numClearStateProgramPages;
2552
+ },
2553
+ };
2554
+
2555
+ var ops = /*#__PURE__*/Object.freeze({
2556
+ __proto__: null,
2557
+ AcctParams: AcctParams,
2558
+ AppGlobal: AppGlobal,
2559
+ AppLocal: AppLocal,
2560
+ AppParams: AppParams,
2561
+ AssetHolding: AssetHolding$1,
2562
+ AssetParams: AssetParams,
2563
+ Block: Block,
2564
+ Box: Box$1,
2565
+ EllipticCurve: EllipticCurve,
2566
+ GITxn: GITxn,
2567
+ GTxn: GTxn,
2568
+ Global: Global,
2569
+ ITxn: ITxn,
2570
+ ITxnCreate: ITxnCreate,
2571
+ JsonRef: JsonRef,
2572
+ Scratch: Scratch,
2573
+ Txn: Txn,
2574
+ addw: addw,
2575
+ balance: balance,
2576
+ base64Decode: base64Decode,
2577
+ bitLength: bitLength,
2578
+ bsqrt: bsqrt,
2579
+ btoi: btoi,
2580
+ bzero: bzero,
2581
+ concat: concat,
2582
+ divmodw: divmodw,
2583
+ divw: divw,
2584
+ ecdsaPkDecompress: ecdsaPkDecompress,
2585
+ ecdsaPkRecover: ecdsaPkRecover,
2586
+ ecdsaVerify: ecdsaVerify,
2587
+ ed25519verify: ed25519verify,
2588
+ ed25519verifyBare: ed25519verifyBare,
2589
+ exp: exp,
2590
+ expw: expw,
2591
+ extract: extract,
2592
+ extractUint16: extractUint16,
2593
+ extractUint32: extractUint32,
2594
+ extractUint64: extractUint64,
2595
+ gaid: gaid,
2596
+ getBit: getBit,
2597
+ getByte: getByte,
2598
+ gloadBytes: gloadBytes,
2599
+ gloadUint64: gloadUint64,
2600
+ itob: itob,
2601
+ keccak256: keccak256,
2602
+ minBalance: minBalance,
2603
+ mulw: mulw,
2604
+ replace: replace,
2605
+ select: select,
2606
+ setBit: setBit,
2607
+ setByte: setByte,
2608
+ sha256: sha256,
2609
+ sha3_256: sha3_256,
2610
+ sha512_256: sha512_256,
2611
+ shl: shl,
2612
+ shr: shr,
2613
+ sqrt: sqrt,
2614
+ substring: substring,
2615
+ vrfVerify: vrfVerify
2616
+ });
2617
+
2618
+ class CustomKeyMap {
2619
+ #keySerializer;
2620
+ #map = new Map();
2621
+ constructor(keySerializer) {
2622
+ this.#keySerializer = keySerializer;
2623
+ }
2624
+ clear() {
2625
+ this.#map.clear();
2626
+ }
2627
+ delete(key) {
2628
+ return this.#map.delete(this.#keySerializer(key));
2629
+ }
2630
+ forEach(callbackfn, thisArg) {
2631
+ for (const [key, value] of this.#map.values()) {
2632
+ callbackfn.call(thisArg ?? this, value, key, this);
2633
+ }
2634
+ }
2635
+ get(key) {
2636
+ return this.#map.get(this.#keySerializer(key))?.[1];
2637
+ }
2638
+ getOrFail(key) {
2639
+ const value = this.get(key);
2640
+ if (value === undefined) {
2641
+ throw internal.errors.internalError('Key not found');
2642
+ }
2643
+ return value;
2644
+ }
2645
+ has(key) {
2646
+ return this.#map.has(this.#keySerializer(key));
2647
+ }
2648
+ set(key, value) {
2649
+ this.#map.set(this.#keySerializer(key), [key, value]);
2650
+ return this;
2651
+ }
2652
+ get size() {
2653
+ return this.#map.size;
2654
+ }
2655
+ entries() {
2656
+ return this.#map.values();
2657
+ }
2658
+ *keys() {
2659
+ for (const [key] of this.#map.values()) {
2660
+ yield key;
2661
+ }
2662
+ }
2663
+ *values() {
2664
+ for (const [, value] of this.#map.values()) {
2665
+ yield value;
2666
+ }
2667
+ }
2668
+ [Symbol.iterator]() {
2669
+ return this.#map.values();
2670
+ }
2671
+ get [Symbol.toStringTag]() {
2672
+ return this.constructor.name;
2673
+ }
2674
+ }
2675
+ class AccountMap extends CustomKeyMap {
2676
+ constructor() {
2677
+ super(AccountMap.getAddressStrFromAccount);
2678
+ }
2679
+ static getAddressStrFromAccount = (acc) => {
2680
+ return asBytesCls(acc.bytes).valueOf();
2681
+ };
2682
+ }
2683
+ class BytesMap extends CustomKeyMap {
2684
+ constructor() {
2685
+ super((bytes) => asBytesCls(bytes).valueOf());
2686
+ }
2687
+ }
2688
+ class Uint64Map extends CustomKeyMap {
2689
+ constructor() {
2690
+ super((uint64) => asUint64Cls(uint64).valueOf());
2691
+ }
2692
+ }
2693
+
2694
+ class ApplicationData {
2695
+ application;
2696
+ isCreating = false;
2697
+ get appLogs() {
2698
+ return this.application.appLogs;
2699
+ }
2700
+ constructor() {
2701
+ this.application = {
2702
+ approvalProgram: ALWAYS_APPROVE_TEAL_PROGRAM,
2703
+ clearStateProgram: ALWAYS_APPROVE_TEAL_PROGRAM,
2704
+ globalNumUint: 0,
2705
+ globalNumBytes: 0,
2706
+ localNumUint: 0,
2707
+ localNumBytes: 0,
2708
+ extraProgramPages: 0,
2709
+ creator: lazyContext.defaultSender,
2710
+ appLogs: [],
2711
+ globalStates: new BytesMap(),
2712
+ localStates: new BytesMap(),
2713
+ boxes: new BytesMap(),
2714
+ };
2715
+ }
2716
+ }
2717
+ class ApplicationCls extends Uint64BackedCls {
2718
+ get id() {
2719
+ return this.uint64;
2720
+ }
2721
+ constructor(id) {
2722
+ super(asUint64(id ?? 0));
2723
+ }
2724
+ get data() {
2725
+ return lazyContext.getApplicationData(this.id);
2726
+ }
2727
+ get approvalProgram() {
2728
+ return this.data.application.approvalProgram;
2729
+ }
2730
+ get clearStateProgram() {
2731
+ return this.data.application.clearStateProgram;
2732
+ }
2733
+ get globalNumUint() {
2734
+ return this.data.application.globalNumUint;
2735
+ }
2736
+ get globalNumBytes() {
2737
+ return this.data.application.globalNumBytes;
2738
+ }
2739
+ get localNumUint() {
2740
+ return this.data.application.localNumUint;
2741
+ }
2742
+ get localNumBytes() {
2743
+ return this.data.application.localNumBytes;
2744
+ }
2745
+ get extraProgramPages() {
2746
+ return this.data.application.extraProgramPages;
2747
+ }
2748
+ get creator() {
2749
+ return this.data.application.creator;
2750
+ }
2751
+ get address() {
2752
+ const addr = algosdk.getApplicationAddress(asBigInt(this.id));
2753
+ return Account(Bytes.fromBase32(addr));
2754
+ }
2755
+ }
2756
+
2757
+ class AssetCls extends Uint64BackedCls {
2758
+ get id() {
2759
+ return this.uint64;
2760
+ }
2761
+ constructor(id) {
2762
+ super(asUint64(id ?? 0));
2763
+ }
2764
+ get data() {
2765
+ return lazyContext.getAssetData(this.id);
2766
+ }
2767
+ get total() {
2768
+ return this.data.total;
2769
+ }
2770
+ get decimals() {
2771
+ return this.data.decimals;
2772
+ }
2773
+ get defaultFrozen() {
2774
+ return this.data.defaultFrozen;
2775
+ }
2776
+ get unitName() {
2777
+ return this.data.unitName;
2778
+ }
2779
+ get name() {
2780
+ return this.data.name;
2781
+ }
2782
+ get url() {
2783
+ return this.data.url;
2784
+ }
2785
+ get metadataHash() {
2786
+ return this.data.metadataHash;
2787
+ }
2788
+ get manager() {
2789
+ return this.data.manager;
2790
+ }
2791
+ get reserve() {
2792
+ return this.data.reserve;
2793
+ }
2794
+ get freeze() {
2795
+ return this.data.freeze;
2796
+ }
2797
+ get clawback() {
2798
+ return this.data.clawback;
2799
+ }
2800
+ get creator() {
2801
+ return this.data.creator;
2802
+ }
2803
+ balance(account) {
2804
+ return this.getAssetHolding(account).balance;
2805
+ }
2806
+ frozen(account) {
2807
+ return this.getAssetHolding(account).frozen;
2808
+ }
2809
+ getAssetHolding(account) {
2810
+ const accountData = lazyContext.getAccountData(account);
2811
+ const assetHolding = accountData.optedAssets.get(this.id);
2812
+ if (assetHolding === undefined) {
2813
+ internal.errors.internalError('The asset is not opted into the account! Use `ctx.any.account(opted_asset_balances={{ASSET_ID: VALUE}})` to set emulated opted asset into the account.');
2814
+ }
2815
+ return assetHolding;
2816
+ }
2817
+ }
2818
+
2819
+ class AssetHolding {
2820
+ balance;
2821
+ frozen;
2822
+ constructor(balance, frozen) {
2823
+ this.balance = asUint64(balance);
2824
+ this.frozen = frozen;
2825
+ }
2826
+ }
2827
+ class AccountData {
2828
+ optedAssets = new Uint64Map();
2829
+ optedApplications = new Uint64Map();
2830
+ account;
2831
+ constructor() {
2832
+ this.account = {
2833
+ totalAppsCreated: 0,
2834
+ totalAppsOptedIn: 0,
2835
+ totalAssets: 0,
2836
+ totalAssetsCreated: 0,
2837
+ totalBoxBytes: 0,
2838
+ totalBoxes: 0,
2839
+ totalExtraAppPages: 0,
2840
+ totalNumByteSlice: 0,
2841
+ totalNumUint: 0,
2842
+ minBalance: DEFAULT_ACCOUNT_MIN_BALANCE,
2843
+ balance: 0,
2844
+ authAddress: Account(),
2845
+ };
2846
+ }
2847
+ }
2848
+ class AccountCls extends BytesBackedCls {
2849
+ constructor(address) {
2850
+ const addressBytes = address ?? ZERO_ADDRESS;
2851
+ if (![32n, 36n].includes(asUint64Cls(addressBytes.length).valueOf())) {
2852
+ throw new internal.errors.AvmError('Address must be 32 bytes long, or 36 bytes including checksum');
2853
+ }
2854
+ super(addressBytes.slice(0, 32));
2855
+ }
2856
+ get data() {
2857
+ return lazyContext.getAccountData(this);
2858
+ }
2859
+ get balance() {
2860
+ return this.data.account.balance;
2861
+ }
2862
+ get minBalance() {
2863
+ return this.data.account.minBalance;
2864
+ }
2865
+ get authAddress() {
2866
+ return this.data.account.authAddress;
2867
+ }
2868
+ get totalNumUint() {
2869
+ return this.data.account.totalNumUint;
2870
+ }
2871
+ get totalNumByteSlice() {
2872
+ return this.data.account.totalNumByteSlice;
2873
+ }
2874
+ get totalExtraAppPages() {
2875
+ return this.data.account.totalExtraAppPages;
2876
+ }
2877
+ get totalAppsCreated() {
2878
+ return this.data.account.totalAppsCreated;
2879
+ }
2880
+ get totalAppsOptedIn() {
2881
+ return this.data.account.totalAppsOptedIn;
2882
+ }
2883
+ get totalAssetsCreated() {
2884
+ return this.data.account.totalAssetsCreated;
2885
+ }
2886
+ get totalAssets() {
2887
+ return this.data.account.totalAssets;
2888
+ }
2889
+ get totalBoxes() {
2890
+ return this.data.account.totalBoxes;
2891
+ }
2892
+ get totalBoxBytes() {
2893
+ return this.data.account.totalBoxBytes;
2894
+ }
2895
+ isOptedIn(assetOrApp) {
2896
+ if (assetOrApp instanceof AssetCls) {
2897
+ return this.data.optedAssets.has(assetOrApp.id);
2898
+ }
2899
+ if (assetOrApp instanceof ApplicationCls) {
2900
+ return this.data.optedApplications.has(asUint64Cls(assetOrApp.id).asBigInt());
2901
+ }
2902
+ throw new internal.errors.InternalError('Invalid argument type. Must be an `algopy.Asset` or `algopy.Application` instance.');
2903
+ }
2904
+ }
2905
+
2906
+ const baseDefaultFields = () => ({
2907
+ sender: lazyContext.defaultSender,
2908
+ fee: Uint64(0),
2909
+ firstValid: Uint64(0),
2910
+ firstValidTime: Uint64(0),
2911
+ lastValid: Uint64(0),
2912
+ note: Bytes(),
2913
+ lease: Bytes(),
2914
+ groupIndex: Uint64(0),
2915
+ txnId: getRandomBytes(32).asAlgoTs(),
2916
+ rekeyTo: Account(),
2917
+ });
2918
+ class TransactionBase {
2919
+ constructor(fields) {
2920
+ const baseDefaults = baseDefaultFields();
2921
+ this.sender = fields.sender ?? baseDefaults.sender;
2922
+ this.fee = fields.fee ?? baseDefaults.fee;
2923
+ this.firstValid = fields.firstValid ?? baseDefaults.firstValid;
2924
+ this.firstValidTime = fields.firstValidTime ?? baseDefaults.firstValidTime;
2925
+ this.lastValid = fields.lastValid ?? baseDefaults.lastValid;
2926
+ this.note = fields.note ?? baseDefaults.note;
2927
+ this.lease = fields.lease ?? baseDefaults.lease;
2928
+ this.groupIndex = fields.groupIndex ?? baseDefaults.groupIndex;
2929
+ this.txnId = fields.txnId ?? baseDefaults.txnId;
2930
+ this.rekeyTo = fields.rekeyTo ?? baseDefaults.rekeyTo;
2931
+ this.scratchSpace = Array(256).fill(Uint64(0));
2932
+ }
2933
+ sender;
2934
+ fee;
2935
+ firstValid;
2936
+ firstValidTime;
2937
+ lastValid;
2938
+ note;
2939
+ lease;
2940
+ groupIndex;
2941
+ txnId;
2942
+ rekeyTo;
2943
+ scratchSpace;
2944
+ setScratchSlot(index, value) {
2945
+ const i = asNumber(index);
2946
+ if (i >= this.scratchSpace.length) {
2947
+ throw internal.errors.internalError('invalid scratch slot');
2948
+ }
2949
+ const bytesValue = asMaybeBytesCls(value);
2950
+ const uint64Value = asMaybeUint64Cls(value);
2951
+ this.scratchSpace[i] = bytesValue?.asAlgoTs() ?? uint64Value?.asAlgoTs() ?? Uint64(0);
2952
+ }
2953
+ getScratchSlot(index) {
2954
+ const i = asNumber(index);
2955
+ if (i >= this.scratchSpace.length) {
2956
+ throw internal.errors.internalError('invalid scratch slot');
2957
+ }
2958
+ return this.scratchSpace[i];
2959
+ }
2960
+ }
2961
+ class PaymentTransaction extends TransactionBase {
2962
+ /* @internal */
2963
+ static create(fields) {
2964
+ return new PaymentTransaction(fields);
2965
+ }
2966
+ constructor(fields) {
2967
+ super(fields);
2968
+ this.receiver = fields.receiver ?? Account();
2969
+ this.amount = fields.amount ?? Uint64(0);
2970
+ this.closeRemainderTo = fields.closeRemainderTo ?? Account();
2971
+ }
2972
+ receiver;
2973
+ amount;
2974
+ closeRemainderTo;
2975
+ type = TransactionType.Payment;
2976
+ typeBytes = asUint64Cls(TransactionType.Payment).toBytes().asAlgoTs();
2977
+ }
2978
+ class KeyRegistrationTransaction extends TransactionBase {
2979
+ /* @internal */
2980
+ static create(fields) {
2981
+ return new KeyRegistrationTransaction(fields);
2982
+ }
2983
+ constructor(fields) {
2984
+ super(fields);
2985
+ this.voteKey = fields.voteKey ?? Bytes();
2986
+ this.selectionKey = fields.selectionKey ?? Bytes();
2987
+ this.voteFirst = fields.voteFirst ?? Uint64(0);
2988
+ this.voteLast = fields.voteLast ?? Uint64(0);
2989
+ this.voteKeyDilution = fields.voteKeyDilution ?? Uint64(0);
2990
+ this.nonparticipation = fields.nonparticipation ?? false;
2991
+ this.stateProofKey = fields.stateProofKey ?? Bytes();
2992
+ }
2993
+ voteKey;
2994
+ selectionKey;
2995
+ voteFirst;
2996
+ voteLast;
2997
+ voteKeyDilution;
2998
+ nonparticipation;
2999
+ stateProofKey;
3000
+ type = TransactionType.KeyRegistration;
3001
+ typeBytes = asUint64Cls(TransactionType.KeyRegistration).toBytes().asAlgoTs();
3002
+ }
3003
+ class AssetConfigTransaction extends TransactionBase {
3004
+ /* @internal */
3005
+ static create(fields) {
3006
+ return new AssetConfigTransaction(fields);
3007
+ }
3008
+ constructor(fields) {
3009
+ super(fields);
3010
+ this.configAsset = fields.configAsset ?? Asset();
3011
+ this.total = fields.total ?? Uint64(0);
3012
+ this.decimals = fields.decimals ?? Uint64(0);
3013
+ this.defaultFrozen = fields.defaultFrozen ?? false;
3014
+ this.unitName = fields.unitName ?? Bytes();
3015
+ this.assetName = fields.assetName ?? Bytes();
3016
+ this.url = fields.url ?? Bytes();
3017
+ this.metadataHash = fields.metadataHash ?? Bytes();
3018
+ this.manager = fields.manager ?? Account();
3019
+ this.reserve = fields.reserve ?? Account();
3020
+ this.freeze = fields.freeze ?? Account();
3021
+ this.clawback = fields.clawback ?? Account();
3022
+ this.createdAsset = fields.createdAsset ?? Asset();
3023
+ }
3024
+ configAsset;
3025
+ total;
3026
+ decimals;
3027
+ defaultFrozen;
3028
+ unitName;
3029
+ assetName;
3030
+ url;
3031
+ metadataHash;
3032
+ manager;
3033
+ reserve;
3034
+ freeze;
3035
+ clawback;
3036
+ createdAsset;
3037
+ type = TransactionType.AssetConfig;
3038
+ typeBytes = asUint64Cls(TransactionType.AssetConfig).toBytes().asAlgoTs();
3039
+ }
3040
+ class AssetTransferTransaction extends TransactionBase {
3041
+ /* @internal */
3042
+ static create(fields) {
3043
+ return new AssetTransferTransaction(fields);
3044
+ }
3045
+ constructor(fields) {
3046
+ super(fields);
3047
+ this.xferAsset = fields.xferAsset ?? Asset();
3048
+ this.assetAmount = fields.assetAmount ?? Uint64(0);
3049
+ this.assetSender = fields.assetSender ?? Account();
3050
+ this.assetReceiver = fields.assetReceiver ?? Account();
3051
+ this.assetCloseTo = fields.assetCloseTo ?? Account();
3052
+ }
3053
+ xferAsset;
3054
+ assetAmount;
3055
+ assetSender;
3056
+ assetReceiver;
3057
+ assetCloseTo;
3058
+ type = TransactionType.AssetTransfer;
3059
+ typeBytes = asUint64Cls(TransactionType.AssetTransfer).toBytes().asAlgoTs();
3060
+ }
3061
+ class AssetFreezeTransaction extends TransactionBase {
3062
+ /* @internal */
3063
+ static create(fields) {
3064
+ return new AssetFreezeTransaction(fields);
3065
+ }
3066
+ constructor(fields) {
3067
+ super(fields);
3068
+ this.freezeAsset = fields.freezeAsset ?? Asset();
3069
+ this.freezeAccount = fields.freezeAccount ?? Account();
3070
+ this.frozen = fields.frozen ?? false;
3071
+ }
3072
+ freezeAsset;
3073
+ freezeAccount;
3074
+ frozen;
3075
+ type = TransactionType.AssetFreeze;
3076
+ typeBytes = asUint64Cls(TransactionType.AssetFreeze).toBytes().asAlgoTs();
3077
+ }
3078
+ class ApplicationTransaction extends TransactionBase {
3079
+ /* @internal */
3080
+ static create(fields) {
3081
+ return new ApplicationTransaction(fields);
3082
+ }
3083
+ #appArgs;
3084
+ #accounts;
3085
+ #assets;
3086
+ #apps;
3087
+ #approvalProgramPages;
3088
+ #clearStateProgramPages;
3089
+ #appLogs;
3090
+ constructor(fields) {
3091
+ super(fields);
3092
+ this.appId = fields.appId ?? Application();
3093
+ this.onCompletion = fields.onCompletion ?? 'NoOp';
3094
+ this.globalNumUint = fields.globalNumUint ?? Uint64(0);
3095
+ this.globalNumBytes = fields.globalNumBytes ?? Uint64(0);
3096
+ this.localNumUint = fields.localNumUint ?? Uint64(0);
3097
+ this.localNumBytes = fields.localNumBytes ?? Uint64(0);
3098
+ this.extraProgramPages = fields.extraProgramPages ?? Uint64(0);
3099
+ this.createdApp = fields.createdApp ?? Application();
3100
+ this.#appArgs = fields.appArgs ?? [];
3101
+ this.#appLogs = fields.appLogs ?? [];
3102
+ this.#accounts = fields.accounts ?? [];
3103
+ this.#assets = fields.assets ?? [];
3104
+ this.#apps = fields.apps ?? [];
3105
+ this.#approvalProgramPages = fields.approvalProgramPages ?? (fields.approvalProgram ? [fields.approvalProgram] : []);
3106
+ this.#clearStateProgramPages = fields.clearStateProgramPages ?? (fields.clearStateProgram ? [fields.clearStateProgram] : []);
3107
+ Object.entries(fields.scratchSpace ?? {}).forEach(([k, v]) => this.setScratchSlot(Number(k), v));
3108
+ }
3109
+ appId;
3110
+ onCompletion;
3111
+ globalNumUint;
3112
+ globalNumBytes;
3113
+ localNumUint;
3114
+ localNumBytes;
3115
+ extraProgramPages;
3116
+ createdApp;
3117
+ get approvalProgram() {
3118
+ return this.approvalProgramPages(0);
3119
+ }
3120
+ get clearStateProgram() {
3121
+ return this.clearStateProgramPages(0);
3122
+ }
3123
+ get numAppArgs() {
3124
+ return Uint64(this.#appArgs.length);
3125
+ }
3126
+ get numAccounts() {
3127
+ return Uint64(this.#accounts.length);
3128
+ }
3129
+ get numAssets() {
3130
+ return Uint64(this.#assets.length);
3131
+ }
3132
+ get numApps() {
3133
+ return Uint64(this.#apps.length);
3134
+ }
3135
+ get numApprovalProgramPages() {
3136
+ return Uint64(this.approvalProgramPages.length);
3137
+ }
3138
+ get numClearStateProgramPages() {
3139
+ return Uint64(this.clearStateProgramPages.length);
3140
+ }
3141
+ get numLogs() {
3142
+ return Uint64(this.#appLogs.length || lazyContext.getApplicationData(this.appId.id).appLogs.length);
3143
+ }
3144
+ get lastLog() {
3145
+ return this.#appLogs.at(-1) ?? lazyContext.getApplicationData(this.appId.id).appLogs.at(-1) ?? Bytes();
3146
+ }
3147
+ appArgs(index) {
3148
+ return this.#appArgs[asNumber(index)];
3149
+ }
3150
+ accounts(index) {
3151
+ return this.#accounts[asNumber(index)];
3152
+ }
3153
+ assets(index) {
3154
+ return this.#assets[asNumber(index)];
3155
+ }
3156
+ apps(index) {
3157
+ return this.#apps[asNumber(index)];
3158
+ }
3159
+ approvalProgramPages(index) {
3160
+ return combineIntoMaxBytePages(this.#approvalProgramPages)[asNumber(index)];
3161
+ }
3162
+ clearStateProgramPages(index) {
3163
+ return combineIntoMaxBytePages(this.#clearStateProgramPages)[asNumber(index)];
3164
+ }
3165
+ logs(index) {
3166
+ const i = asNumber(index);
3167
+ return this.#appLogs[i] ?? lazyContext.getApplicationData(this.appId.id).appLogs ?? Bytes();
3168
+ }
3169
+ type = TransactionType.ApplicationCall;
3170
+ typeBytes = asUint64Cls(TransactionType.ApplicationCall).toBytes().asAlgoTs();
3171
+ /* @internal */
3172
+ get appLogs() {
3173
+ return this.#appLogs;
3174
+ }
3175
+ /* @internal */
3176
+ appendLog(value) {
3177
+ if (this.#appLogs.length + 1 > MAX_ITEMS_IN_LOG) {
3178
+ throw internal.errors.internalError(`Too many log calls in program, up to ${MAX_ITEMS_IN_LOG} is allowed`);
3179
+ }
3180
+ this.#appLogs.push(asBytes(value));
3181
+ }
3182
+ /* @internal */
3183
+ logArc4ReturnValue(value) {
3184
+ this.appendLog(ABI_RETURN_VALUE_LOG_PREFIX.concat(toBytes(value)));
3185
+ }
3186
+ }
3187
+
3188
+ const mapCommonFields = (fields) => {
3189
+ const { sender, note, rekeyTo, ...rest } = fields;
3190
+ return {
3191
+ sender: sender instanceof Account ? sender : typeof sender === 'string' ? Account(asBytes(sender)) : lazyContext.activeApplication.address,
3192
+ note: note !== undefined ? asBytes(note) : undefined,
3193
+ rekeyTo: rekeyTo instanceof Account ? rekeyTo : typeof rekeyTo === 'string' ? Account(asBytes(rekeyTo)) : undefined,
3194
+ ...rest,
3195
+ };
3196
+ };
3197
+ class PaymentInnerTxn extends PaymentTransaction {
3198
+ isItxn;
3199
+ /* @internal */
3200
+ static create(fields) {
3201
+ return new PaymentInnerTxn(fields);
3202
+ }
3203
+ /* @internal */
3204
+ constructor(fields) {
3205
+ super(mapCommonFields(fields));
3206
+ }
3207
+ }
3208
+ class KeyRegistrationInnerTxn extends KeyRegistrationTransaction {
3209
+ isItxn;
3210
+ /* @internal */
3211
+ static create(fields) {
3212
+ return new KeyRegistrationInnerTxn(fields);
3213
+ }
3214
+ /* @internal */
3215
+ constructor(fields) {
3216
+ super(mapCommonFields(fields));
3217
+ }
3218
+ }
3219
+ class AssetConfigInnerTxn extends AssetConfigTransaction {
3220
+ isItxn;
3221
+ /* @internal */
3222
+ static create(fields) {
3223
+ return new AssetConfigInnerTxn(fields);
3224
+ }
3225
+ /* @internal */
3226
+ constructor(fields) {
3227
+ const { assetName, unitName, url, ...rest } = mapCommonFields(fields);
3228
+ const createdAsset = lazyContext.any.asset({
3229
+ name: typeof assetName === 'string' ? asBytes(assetName) : assetName,
3230
+ unitName: typeof unitName === 'string' ? asBytes(unitName) : unitName,
3231
+ url: typeof url === 'string' ? asBytes(url) : url,
3232
+ ...rest,
3233
+ });
3234
+ super({
3235
+ assetName: typeof assetName === 'string' ? asBytes(assetName) : assetName,
3236
+ unitName: typeof unitName === 'string' ? asBytes(unitName) : unitName,
3237
+ url: typeof url === 'string' ? asBytes(url) : url,
3238
+ ...rest,
3239
+ createdAsset: createdAsset,
3240
+ });
3241
+ }
3242
+ }
3243
+ class AssetTransferInnerTxn extends AssetTransferTransaction {
3244
+ isItxn;
3245
+ /* @internal */
3246
+ static create(fields) {
3247
+ if (fields.xferAsset === undefined) {
3248
+ throw new Error('xferAsset is required');
3249
+ }
3250
+ return new AssetTransferInnerTxn(fields);
3251
+ }
3252
+ /* @internal */
3253
+ constructor(fields) {
3254
+ super(mapCommonFields(fields));
3255
+ }
3256
+ }
3257
+ class AssetFreezeInnerTxn extends AssetFreezeTransaction {
3258
+ isItxn;
3259
+ /* @internal */
3260
+ static create(fields) {
3261
+ if (fields.freezeAsset === undefined) {
3262
+ throw new Error('freezeAsset is required');
3263
+ }
3264
+ return new AssetFreezeInnerTxn(fields);
3265
+ }
3266
+ /* @internal */
3267
+ constructor(fields) {
3268
+ const { freezeAsset, freezeAccount, ...rest } = mapCommonFields(fields);
3269
+ const asset = freezeAsset instanceof internal.primitives.Uint64Cls ? getAsset(freezeAsset) : freezeAsset;
3270
+ const account = typeof freezeAccount === 'string' ? Account(asBytes(freezeAccount)) : freezeAccount;
3271
+ super({
3272
+ freezeAsset: asset,
3273
+ freezeAccount: account,
3274
+ ...rest,
3275
+ });
3276
+ }
3277
+ }
3278
+ class ApplicationInnerTxn extends ApplicationTransaction {
3279
+ isItxn;
3280
+ /* @internal */
3281
+ static create(fields) {
3282
+ return new ApplicationInnerTxn(fields);
3283
+ }
3284
+ /* @internal */
3285
+ constructor(fields) {
3286
+ const { appId, approvalProgram, clearStateProgram, onCompletion, appArgs, accounts, assets, apps, ...rest } = mapCommonFields(fields);
3287
+ super({
3288
+ appId: appId instanceof internal.primitives.Uint64Cls ? getApp(appId) : appId,
3289
+ onCompletion: typeof onCompletion === 'string'
3290
+ ? onCompletion
3291
+ : onCompletion !== undefined
3292
+ ? arc4.OnCompleteAction[onCompletion]
3293
+ : undefined,
3294
+ approvalProgram: Array.isArray(approvalProgram) ? undefined : approvalProgram,
3295
+ approvalProgramPages: Array.isArray(approvalProgram) ? approvalProgram : undefined,
3296
+ clearStateProgram: Array.isArray(clearStateProgram) ? undefined : clearStateProgram,
3297
+ clearStateProgramPages: Array.isArray(clearStateProgram) ? clearStateProgram : undefined,
3298
+ appArgs: appArgs?.map((x) => toBytes(x)),
3299
+ accounts: accounts?.map((x) => x),
3300
+ assets: assets?.map((x) => x),
3301
+ apps: apps?.map((x) => x),
3302
+ ...rest,
3303
+ });
3304
+ }
3305
+ }
3306
+ const createInnerTxn = (fields) => {
3307
+ switch (fields.type) {
3308
+ case TransactionType.Payment:
3309
+ return new PaymentInnerTxn(fields);
3310
+ case TransactionType.AssetConfig:
3311
+ return new AssetConfigInnerTxn(fields);
3312
+ case TransactionType.AssetTransfer:
3313
+ return new AssetTransferInnerTxn(fields);
3314
+ case TransactionType.AssetFreeze:
3315
+ return new AssetFreezeInnerTxn(fields);
3316
+ case TransactionType.ApplicationCall:
3317
+ return new ApplicationInnerTxn(fields);
3318
+ case TransactionType.KeyRegistration:
3319
+ return new KeyRegistrationInnerTxn(fields);
3320
+ default:
3321
+ throw new internal.errors.InternalError(`Invalid inner transaction type: ${fields.type}`);
3322
+ }
3323
+ };
3324
+ function submitGroup(...transactionFields) {
3325
+ return transactionFields.map((f) => f.submit());
3326
+ }
3327
+ function payment(fields) {
3328
+ ensureItxnGroupBegin();
3329
+ return new ItxnParams(fields, TransactionType.Payment);
3330
+ }
3331
+ function keyRegistration(fields) {
3332
+ ensureItxnGroupBegin();
3333
+ return new ItxnParams(fields, TransactionType.KeyRegistration);
3334
+ }
3335
+ function assetConfig(fields) {
3336
+ ensureItxnGroupBegin();
3337
+ return new ItxnParams(fields, TransactionType.AssetConfig);
3338
+ }
3339
+ function assetTransfer(fields) {
3340
+ ensureItxnGroupBegin();
3341
+ return new ItxnParams(fields, TransactionType.AssetTransfer);
3342
+ }
3343
+ function assetFreeze(fields) {
3344
+ ensureItxnGroupBegin();
3345
+ return new ItxnParams(fields, TransactionType.AssetFreeze);
3346
+ }
3347
+ function applicationCall(fields) {
3348
+ ensureItxnGroupBegin();
3349
+ return new ItxnParams(fields, TransactionType.ApplicationCall);
3350
+ }
3351
+ class ItxnParams {
3352
+ #fields;
3353
+ constructor(fields, type) {
3354
+ this.#fields = { ...fields, type };
3355
+ }
3356
+ submit() {
3357
+ return createInnerTxn(this.#fields);
3358
+ }
3359
+ set(p) {
3360
+ Object.assign(this.#fields, p);
3361
+ }
3362
+ copy() {
3363
+ return new ItxnParams(this.#fields, this.#fields.type);
3364
+ }
3365
+ }
3366
+ const ensureItxnGroupBegin = () => {
3367
+ if (!lazyContext.activeGroup.constructingItxnGroup.length) {
3368
+ lazyContext.activeGroup.beginInnerTransactionGroup();
3369
+ }
3370
+ };
3371
+
3372
+ const booleanFromBytes = (val) => {
3373
+ return internal.encodingUtil.uint8ArrayToBigInt(asUint8Array(val)) > 0n;
3374
+ };
3375
+ const bigUintFromBytes = (val) => {
3376
+ return BigUint(internal.encodingUtil.uint8ArrayToBigInt(asUint8Array(val)));
3377
+ };
3378
+ const bytesFromBytes = (val) => {
3379
+ return asBytes(val);
3380
+ };
3381
+ const stringFromBytes = (val) => {
3382
+ return asBytes(val).toString();
3383
+ };
3384
+ const uint64FromBytes = (val) => {
3385
+ return Uint64(internal.encodingUtil.uint8ArrayToBigInt(asUint8Array(val)));
3386
+ };
3387
+ const onCompletionFromBytes = (val) => {
3388
+ return Uint64(internal.encodingUtil.uint8ArrayToBigInt(asUint8Array(val)));
3389
+ };
3390
+ const transactionTypeFromBytes = (val) => {
3391
+ return Uint64(internal.encodingUtil.uint8ArrayToBigInt(asUint8Array(val)));
3392
+ };
3393
+ const encoders = {
3394
+ account: AccountCls.fromBytes,
3395
+ application: ApplicationCls.fromBytes,
3396
+ asset: AssetCls.fromBytes,
3397
+ boolean: booleanFromBytes,
3398
+ biguint: bigUintFromBytes,
3399
+ bytes: bytesFromBytes,
3400
+ string: stringFromBytes,
3401
+ uint64: uint64FromBytes,
3402
+ OnCompleteAction: onCompletionFromBytes,
3403
+ TransactionType: transactionTypeFromBytes,
3404
+ ...arc4Encoders,
3405
+ };
3406
+ const getEncoder = (typeInfo) => {
3407
+ return getArc4Encoder(typeInfo, encoders);
3408
+ };
3409
+
3410
+ class GlobalStateCls {
3411
+ _type = GlobalStateCls.name;
3412
+ #value;
3413
+ key;
3414
+ get hasKey() {
3415
+ return this.key !== undefined && this.key.length > 0;
3416
+ }
3417
+ delete = () => {
3418
+ if (this.#value instanceof internal.primitives.Uint64Cls) {
3419
+ this.#value = Uint64(0);
3420
+ }
3421
+ else {
3422
+ this.#value = undefined;
3423
+ }
3424
+ };
3425
+ static [Symbol.hasInstance](x) {
3426
+ return x instanceof Object && '_type' in x && x['_type'] === GlobalStateCls.name;
3427
+ }
3428
+ get value() {
3429
+ if (this.#value === undefined) {
3430
+ throw new internal.errors.AssertError('value is not set');
3431
+ }
3432
+ return this.#value;
3433
+ }
3434
+ set value(v) {
3435
+ this.#value = v;
3436
+ }
3437
+ get hasValue() {
3438
+ return this.#value !== undefined;
3439
+ }
3440
+ constructor(key, value) {
3441
+ this.key = key !== undefined ? asBytes(key) : undefined;
3442
+ this.#value = value;
3443
+ }
3444
+ }
3445
+ class LocalStateCls {
3446
+ #value;
3447
+ delete = () => {
3448
+ if (this.#value instanceof internal.primitives.Uint64Cls) {
3449
+ this.#value = Uint64(0);
3450
+ }
3451
+ else {
3452
+ this.#value = undefined;
3453
+ }
3454
+ };
3455
+ get value() {
3456
+ if (this.#value === undefined) {
3457
+ throw new internal.errors.AssertError('value is not set');
3458
+ }
3459
+ return this.#value;
3460
+ }
3461
+ set value(v) {
3462
+ this.#value = v;
3463
+ }
3464
+ get hasValue() {
3465
+ return this.#value !== undefined;
3466
+ }
3467
+ }
3468
+ class LocalStateMapCls {
3469
+ #value = new AccountMap();
3470
+ getValue(account) {
3471
+ if (!this.#value.has(account)) {
3472
+ this.#value.set(account, new LocalStateCls());
3473
+ }
3474
+ return this.#value.getOrFail(account);
3475
+ }
3476
+ }
3477
+ function GlobalState(options) {
3478
+ return new GlobalStateCls(options?.key, options?.initialValue);
3479
+ }
3480
+ function LocalState(options) {
3481
+ function localStateInternal(account) {
3482
+ return localStateInternal.map.getValue(account);
3483
+ }
3484
+ localStateInternal.key = options?.key;
3485
+ localStateInternal.hasKey = options?.key !== undefined && options.key.length > 0;
3486
+ localStateInternal.map = new LocalStateMapCls();
3487
+ return localStateInternal;
3488
+ }
3489
+ class BoxCls {
3490
+ #key;
3491
+ #app;
3492
+ _type = BoxCls.name;
3493
+ static [Symbol.hasInstance](x) {
3494
+ return x instanceof Object && '_type' in x && x['_type'] === BoxCls.name;
3495
+ }
3496
+ constructor(key) {
3497
+ this.#key = key ? asBytes(key) : undefined;
3498
+ this.#app = lazyContext.activeApplication;
3499
+ }
3500
+ get fromBytes() {
3501
+ const typeInfo = getGenericTypeInfo(this);
3502
+ const valueType = typeInfo.genericArgs[0];
3503
+ return (val) => getEncoder(valueType)(val, valueType);
3504
+ }
3505
+ get value() {
3506
+ if (!this.exists) {
3507
+ throw new internal.errors.InternalError('Box has not been created');
3508
+ }
3509
+ return this.fromBytes(lazyContext.ledger.getBox(this.#app, this.key));
3510
+ }
3511
+ set value(v) {
3512
+ lazyContext.ledger.setBox(this.#app, this.key, asUint8Array(toBytes(v)));
3513
+ }
3514
+ get hasKey() {
3515
+ return this.#key !== undefined && this.#key.length > 0;
3516
+ }
3517
+ get key() {
3518
+ if (this.#key === undefined || this.#key.length === 0) {
3519
+ throw new internal.errors.InternalError('Box key is empty');
3520
+ }
3521
+ return this.#key;
3522
+ }
3523
+ set key(key) {
3524
+ this.#key = asBytes(key);
3525
+ }
3526
+ get exists() {
3527
+ return lazyContext.ledger.boxExists(this.#app, this.key);
3528
+ }
3529
+ get length() {
3530
+ if (!this.exists) {
3531
+ throw new internal.errors.InternalError('Box has not been created');
3532
+ }
3533
+ return toBytes(this.value).length;
3534
+ }
3535
+ get(options) {
3536
+ const [value, exists] = this.maybe();
3537
+ return exists ? value : options.default;
3538
+ }
3539
+ delete() {
3540
+ return lazyContext.ledger.deleteBox(this.#app, this.key);
3541
+ }
3542
+ maybe() {
3543
+ const value = this.fromBytes(lazyContext.ledger.getBox(this.#app, this.key));
3544
+ return [value, lazyContext.ledger.boxExists(this.#app, this.key)];
3545
+ }
3546
+ }
3547
+ class BoxMapCls {
3548
+ #keyPrefix;
3549
+ #app;
3550
+ _type = BoxMapCls.name;
3551
+ static [Symbol.hasInstance](x) {
3552
+ return x instanceof Object && '_type' in x && x['_type'] === BoxMapCls.name;
3553
+ }
3554
+ get fromBytes() {
3555
+ const typeInfo = getGenericTypeInfo(this);
3556
+ const valueType = typeInfo.genericArgs[1];
3557
+ return (val) => getEncoder(valueType)(val, valueType);
3558
+ }
3559
+ constructor(keyPrefix) {
3560
+ this.#keyPrefix = keyPrefix ? asBytes(keyPrefix) : undefined;
3561
+ this.#app = lazyContext.activeApplication;
3562
+ }
3563
+ get hasKeyPrefix() {
3564
+ return this.#keyPrefix !== undefined && this.#keyPrefix.length > 0;
3565
+ }
3566
+ get keyPrefix() {
3567
+ if (this.#keyPrefix === undefined || this.#keyPrefix.length === 0) {
3568
+ throw new internal.errors.InternalError('Box key prefix is empty');
3569
+ }
3570
+ return this.#keyPrefix;
3571
+ }
3572
+ set keyPrefix(keyPrefix) {
3573
+ this.#keyPrefix = asBytes(keyPrefix);
3574
+ }
3575
+ get(key, options) {
3576
+ const [value, exists] = this.maybe(key);
3577
+ if (!exists && options === undefined) {
3578
+ throw new internal.errors.InternalError('Box has not been created');
3579
+ }
3580
+ return exists ? value : options.default;
3581
+ }
3582
+ set(key, value) {
3583
+ lazyContext.ledger.setBox(this.#app, this.getFullKey(key), asUint8Array(toBytes(value)));
3584
+ }
3585
+ delete(key) {
3586
+ return lazyContext.ledger.deleteBox(this.#app, this.getFullKey(key));
3587
+ }
3588
+ has(key) {
3589
+ return lazyContext.ledger.boxExists(this.#app, this.getFullKey(key));
3590
+ }
3591
+ maybe(key) {
3592
+ const fullKey = this.getFullKey(key);
3593
+ const value = this.fromBytes(lazyContext.ledger.getBox(this.#app, fullKey));
3594
+ return [value, lazyContext.ledger.boxExists(this.#app, fullKey)];
3595
+ }
3596
+ length(key) {
3597
+ return toBytes(this.get(key)).length;
3598
+ }
3599
+ getFullKey(key) {
3600
+ return this.keyPrefix.concat(toBytes(key));
3601
+ }
3602
+ }
3603
+ class BoxRefCls {
3604
+ #key;
3605
+ #app;
3606
+ _type = BoxRefCls.name;
3607
+ static [Symbol.hasInstance](x) {
3608
+ return x instanceof Object && '_type' in x && x['_type'] === BoxRefCls.name;
3609
+ }
3610
+ constructor(key) {
3611
+ this.#key = key ? asBytes(key) : undefined;
3612
+ this.#app = lazyContext.activeApplication;
3613
+ }
3614
+ get hasKey() {
3615
+ return this.#key !== undefined && this.#key.length > 0;
3616
+ }
3617
+ get key() {
3618
+ if (this.#key === undefined || this.#key.length === 0) {
3619
+ throw new internal.errors.InternalError('Box key is empty');
3620
+ }
3621
+ return this.#key;
3622
+ }
3623
+ set key(key) {
3624
+ this.#key = asBytes(key);
3625
+ }
3626
+ get value() {
3627
+ if (!this.exists) {
3628
+ throw new internal.errors.InternalError('Box has not been created');
3629
+ }
3630
+ return toBytes(this.backingValue);
3631
+ }
3632
+ set value(v) {
3633
+ const bytesValue = asBytesCls(v);
3634
+ const content = this.backingValue;
3635
+ if (this.exists && content.length !== bytesValue.length.asNumber()) {
3636
+ throw new internal.errors.InternalError('Box already exists with a different size');
3637
+ }
3638
+ this.backingValue = bytesValue.asUint8Array();
3639
+ }
3640
+ get exists() {
3641
+ return lazyContext.ledger.boxExists(this.#app, this.key);
3642
+ }
3643
+ create(options) {
3644
+ const size = asNumber(options.size);
3645
+ if (size > MAX_BOX_SIZE) {
3646
+ throw new internal.errors.InternalError(`Box size cannot exceed ${MAX_BOX_SIZE}`);
3647
+ }
3648
+ const content = this.backingValue;
3649
+ if (this.exists && content.length !== size) {
3650
+ throw new internal.errors.InternalError('Box already exists with a different size');
3651
+ }
3652
+ if (this.exists) {
3653
+ return false;
3654
+ }
3655
+ this.backingValue = new Uint8Array(size);
3656
+ return true;
3657
+ }
3658
+ get(options) {
3659
+ const [value, exists] = this.maybe();
3660
+ return exists ? value : asBytes(options.default);
3661
+ }
3662
+ put(value) {
3663
+ this.value = value;
3664
+ }
3665
+ splice(start, length, value) {
3666
+ const content = this.backingValue;
3667
+ const startNumber = asNumber(start);
3668
+ const lengthNumber = asNumber(length);
3669
+ const valueBytes = asBytesCls(value);
3670
+ if (!this.exists) {
3671
+ throw new internal.errors.InternalError('Box has not been created');
3672
+ }
3673
+ if (startNumber > content.length) {
3674
+ throw new internal.errors.InternalError('Start index exceeds box size');
3675
+ }
3676
+ const end = Math.min(startNumber + lengthNumber, content.length);
3677
+ let updatedContent = conactUint8Arrays(content.slice(0, startNumber), valueBytes.asUint8Array(), content.slice(end));
3678
+ if (updatedContent.length > content.length) {
3679
+ updatedContent = updatedContent.slice(0, content.length);
3680
+ }
3681
+ else if (updatedContent.length < content.length) {
3682
+ updatedContent = conactUint8Arrays(updatedContent, new Uint8Array(content.length - updatedContent.length));
3683
+ }
3684
+ this.backingValue = updatedContent;
3685
+ }
3686
+ replace(start, value) {
3687
+ const content = this.backingValue;
3688
+ const startNumber = asNumber(start);
3689
+ const valueBytes = asBytesCls(value);
3690
+ if (!this.exists) {
3691
+ throw new internal.errors.InternalError('Box has not been created');
3692
+ }
3693
+ if (startNumber + asNumber(valueBytes.length) > content.length) {
3694
+ throw new internal.errors.InternalError('Replacement content exceeds box size');
3695
+ }
3696
+ const updatedContent = conactUint8Arrays(content.slice(0, startNumber), valueBytes.asUint8Array(), content.slice(startNumber + valueBytes.length.asNumber()));
3697
+ this.backingValue = updatedContent;
3698
+ }
3699
+ extract(start, length) {
3700
+ const content = this.backingValue;
3701
+ const startNumber = asNumber(start);
3702
+ const lengthNumber = asNumber(length);
3703
+ if (!this.exists) {
3704
+ throw new internal.errors.InternalError('Box has not been created');
3705
+ }
3706
+ if (startNumber + lengthNumber > content.length) {
3707
+ throw new internal.errors.InternalError('Index out of bounds');
3708
+ }
3709
+ return toBytes(content.slice(startNumber, startNumber + lengthNumber));
3710
+ }
3711
+ delete() {
3712
+ return lazyContext.ledger.deleteBox(this.#app, this.key);
3713
+ }
3714
+ resize(newSize) {
3715
+ const newSizeNumber = asNumber(newSize);
3716
+ if (newSizeNumber > MAX_BOX_SIZE) {
3717
+ throw new internal.errors.InternalError(`Box size cannot exceed ${MAX_BOX_SIZE}`);
3718
+ }
3719
+ const content = this.backingValue;
3720
+ if (!this.exists) {
3721
+ throw new internal.errors.InternalError('Box has not been created');
3722
+ }
3723
+ let updatedContent;
3724
+ if (newSizeNumber > content.length) {
3725
+ updatedContent = conactUint8Arrays(content, new Uint8Array(newSizeNumber - content.length));
3726
+ }
3727
+ else {
3728
+ updatedContent = content.slice(0, newSize);
3729
+ }
3730
+ this.backingValue = updatedContent;
3731
+ }
3732
+ maybe() {
3733
+ return [Bytes(lazyContext.ledger.getBox(this.#app, this.key)), lazyContext.ledger.boxExists(this.#app, this.key)];
3734
+ }
3735
+ get length() {
3736
+ if (!this.exists) {
3737
+ throw new internal.errors.InternalError('Box has not been created');
3738
+ }
3739
+ return this.backingValue.length;
3740
+ }
3741
+ get backingValue() {
3742
+ return lazyContext.ledger.getBox(this.#app, this.key);
3743
+ }
3744
+ set backingValue(value) {
3745
+ lazyContext.ledger.setBox(this.#app, this.key, value);
3746
+ }
3747
+ }
3748
+ function Box(options) {
3749
+ return new BoxCls(options?.key);
3750
+ }
3751
+ function BoxMap(options) {
3752
+ return new BoxMapCls(options?.keyPrefix);
3753
+ }
3754
+ function BoxRef(options) {
3755
+ return new BoxRefCls(options?.key);
3756
+ }
3757
+
3758
+ const isUint64GenericType = (typeInfo) => {
3759
+ if (!Array.isArray(typeInfo?.genericArgs) || !typeInfo?.genericArgs?.length)
3760
+ return false;
3761
+ return typeInfo.genericArgs.some((t) => t.name.toLocaleLowerCase() === 'uint64');
3762
+ };
3763
+ const extractStates = (contract) => {
3764
+ const stateTotals = { globalNumBytes: 0, globalNumUint: 0, localNumBytes: 0, localNumUint: 0 };
3765
+ const states = {
3766
+ globalStates: new BytesMap(),
3767
+ localStates: new BytesMap(),
3768
+ totals: stateTotals,
3769
+ };
3770
+ Object.entries(contract).forEach(([key, value]) => {
3771
+ const isLocalState = value instanceof Function && value.name === 'localStateInternal';
3772
+ const isGlobalState = value instanceof GlobalStateCls;
3773
+ const isBox = value instanceof BoxCls;
3774
+ const isBoxRef = value instanceof BoxRefCls;
3775
+ const isBoxMap = value instanceof BoxMapCls;
3776
+ if (isLocalState || isGlobalState || isBox || isBoxRef) {
3777
+ // set key using property name if not already set
3778
+ if (!value.hasKey)
3779
+ value.key = Bytes(key);
3780
+ }
3781
+ else if (isBoxMap) {
3782
+ if (!value.hasKeyPrefix)
3783
+ value.keyPrefix = Bytes(key);
3784
+ }
3785
+ if (isLocalState || isGlobalState) {
3786
+ // capture state into the context
3787
+ if (isLocalState)
3788
+ states.localStates.set(value.key, value);
3789
+ else
3790
+ states.globalStates.set(value.key, value);
3791
+ // populate state totals
3792
+ const isUint64State = isUint64GenericType(getGenericTypeInfo(value));
3793
+ stateTotals.globalNumUint += isGlobalState && isUint64State ? 1 : 0;
3794
+ stateTotals.globalNumBytes += isGlobalState && !isUint64State ? 1 : 0;
3795
+ stateTotals.localNumUint += isLocalState && isUint64State ? 1 : 0;
3796
+ stateTotals.localNumBytes += isLocalState && !isUint64State ? 1 : 0;
3797
+ }
3798
+ });
3799
+ return states;
3800
+ };
3801
+ const extractArraysFromArgs = (app, args) => {
3802
+ const transactions = [];
3803
+ const accounts = [];
3804
+ const apps = [app];
3805
+ const assets = [];
3806
+ const appArgs = [];
3807
+ // TODO: replace `asUint64Cls(accounts.length).toBytes().asAlgoTs()` with `arc4.Uint8(account.length).toBytes().asAlgoTs()`
3808
+ for (const arg of args) {
3809
+ if (isTransaction(arg)) {
3810
+ transactions.push(arg);
3811
+ }
3812
+ else if (arg instanceof AccountCls) {
3813
+ appArgs.push(asUint64Cls(accounts.length).toBytes().asAlgoTs());
3814
+ accounts.push(arg);
3815
+ }
3816
+ else if (arg instanceof ApplicationCls) {
3817
+ appArgs.push(asUint64Cls(apps.length).toBytes().asAlgoTs());
3818
+ apps.push(arg);
3819
+ }
3820
+ else if (arg instanceof AssetCls) {
3821
+ appArgs.push(asUint64Cls(assets.length).toBytes().asAlgoTs());
3822
+ assets.push(arg);
3823
+ }
3824
+ }
3825
+ // TODO: use actual method selector in appArgs
3826
+ return { accounts, apps, assets, transactions, appArgs: [Bytes('method_selector'), ...appArgs] };
3827
+ };
3828
+ function isTransaction(obj) {
3829
+ return (obj instanceof PaymentTransaction ||
3830
+ obj instanceof KeyRegistrationTransaction ||
3831
+ obj instanceof AssetConfigTransaction ||
3832
+ obj instanceof AssetTransferTransaction ||
3833
+ obj instanceof AssetFreezeTransaction ||
3834
+ obj instanceof ApplicationTransaction);
3835
+ }
3836
+ class ContractContext {
3837
+ create(type, ...args) {
3838
+ const proxy = new Proxy(type, this.getContractProxyHandler(this.isArc4(type)));
3839
+ return new proxy(...args);
3840
+ }
3841
+ static createMethodCallTxns(contract, method, ...args) {
3842
+ const abiMetadata = getAbiMetadata(contract, method.name);
3843
+ const app = lazyContext.ledger.getApplicationForContract(contract);
3844
+ const { transactions, ...appCallArgs } = extractArraysFromArgs(app, args);
3845
+ const appTxn = lazyContext.any.txn.applicationCall({
3846
+ appId: app,
3847
+ ...appCallArgs,
3848
+ // TODO: This needs to be specifiable by the test code
3849
+ onCompletion: (abiMetadata?.allowActions ?? [])[0],
3850
+ });
3851
+ const txns = [...(transactions ?? []), appTxn];
3852
+ return txns;
3853
+ }
3854
+ isArc4(type) {
3855
+ const proto = Object.getPrototypeOf(type);
3856
+ if (proto === BaseContract) {
3857
+ return false;
3858
+ }
3859
+ else if (proto === Contract) {
3860
+ return true;
3861
+ }
3862
+ else if (proto === Object) {
3863
+ throw new Error('Cannot create a contract for class as it does not extend Contract or BaseContract');
3864
+ }
3865
+ return this.isArc4(proto);
3866
+ }
3867
+ getContractProxyHandler(isArc4) {
3868
+ const onConstructed = (application, instance) => {
3869
+ const states = extractStates(instance);
3870
+ const applicationData = lazyContext.ledger.applicationDataMap.getOrFail(application.id);
3871
+ applicationData.application = {
3872
+ ...applicationData.application,
3873
+ globalStates: states.globalStates,
3874
+ localStates: states.localStates,
3875
+ ...states.totals,
3876
+ };
3877
+ lazyContext.ledger.addAppIdContractMap(application.id, instance);
3878
+ };
3879
+ return {
3880
+ construct(target, args) {
3881
+ let t = undefined;
3882
+ const application = lazyContext.any.application();
3883
+ const txn = lazyContext.any.txn.applicationCall({ appId: application });
3884
+ lazyContext.txn.ensureScope([txn]).execute(() => {
3885
+ t = new target(...args);
3886
+ });
3887
+ const instance = new Proxy(t, {
3888
+ get(target, prop, receiver) {
3889
+ const orig = Reflect.get(target, prop, receiver);
3890
+ const abiMetadata = getAbiMetadata(target, prop);
3891
+ const isProgramMethod = prop === 'approvalProgram' || prop === 'clearStateProgram';
3892
+ const isAbiMethod = isArc4 && abiMetadata;
3893
+ if (isAbiMethod || isProgramMethod) {
3894
+ return (...args) => {
3895
+ const txns = ContractContext.createMethodCallTxns(receiver, orig, ...args);
3896
+ return lazyContext.txn.ensureScope(txns).execute(() => {
3897
+ const returnValue = orig.apply(target, args);
3898
+ if (!isProgramMethod && isAbiMethod && returnValue !== undefined) {
3899
+ txns.at(-1).logArc4ReturnValue(returnValue);
3900
+ }
3901
+ return returnValue;
3902
+ });
3903
+ };
3904
+ }
3905
+ return orig;
3906
+ },
3907
+ });
3908
+ onConstructed(application, instance);
3909
+ return instance;
3910
+ },
3911
+ };
3912
+ }
3913
+ }
3914
+
3915
+ class LedgerContext {
3916
+ appIdIter = iterBigInt(1001n, MAX_UINT64);
3917
+ assetIdIter = iterBigInt(1001n, MAX_UINT64);
3918
+ applicationDataMap = new Uint64Map();
3919
+ appIdContractMap = new Uint64Map();
3920
+ accountDataMap = new AccountMap();
3921
+ assetDataMap = new Uint64Map();
3922
+ blocks = new Uint64Map();
3923
+ globalData = new GlobalData();
3924
+ addAppIdContractMap(appId, contract) {
3925
+ this.appIdContractMap.set(appId, contract);
3926
+ }
3927
+ getAsset(assetId) {
3928
+ if (this.assetDataMap.has(assetId)) {
3929
+ return Asset(asUint64(assetId));
3930
+ }
3931
+ throw internal.errors.internalError('Unknown asset, check correct testing context is active');
3932
+ }
3933
+ getApplication(applicationId) {
3934
+ if (this.applicationDataMap.has(applicationId)) {
3935
+ return Application(asUint64(applicationId));
3936
+ }
3937
+ throw internal.errors.internalError('Unknown application, check correct testing context is active');
3938
+ }
3939
+ getApplicationForContract(contract) {
3940
+ for (const [appId, c] of this.appIdContractMap) {
3941
+ if (c === contract) {
3942
+ if (this.applicationDataMap.has(appId)) {
3943
+ return Application(asUint64(appId));
3944
+ }
3945
+ }
3946
+ }
3947
+ throw internal.errors.internalError('Unknown contract, check correct testing context is active');
3948
+ }
3949
+ /**
3950
+ * Update asset holdings for account, only specified values will be updated.
3951
+ * Account will also be opted-in to asset
3952
+ * @param account
3953
+ * @param assetId
3954
+ * @param balance
3955
+ * @param frozen
3956
+ */
3957
+ updateAssetHolding(account, assetId, balance, frozen) {
3958
+ const id = asMaybeUint64Cls(assetId) ?? asUint64Cls(assetId.id);
3959
+ const accountData = this.accountDataMap.get(account);
3960
+ const asset = this.assetDataMap.get(id);
3961
+ const holding = accountData.optedAssets.get(id) ?? new AssetHolding(0n, asset.defaultFrozen);
3962
+ if (balance !== undefined)
3963
+ holding.balance = asUint64(balance);
3964
+ if (frozen !== undefined)
3965
+ holding.frozen = frozen;
3966
+ accountData.optedAssets.set(id, holding);
3967
+ }
3968
+ patchGlobalData(data) {
3969
+ this.globalData = {
3970
+ ...this.globalData,
3971
+ ...data,
3972
+ };
3973
+ }
3974
+ setBlock(index, seed, timestamp) {
3975
+ const i = asBigInt(index);
3976
+ const s = asBigInt(seed);
3977
+ const t = asBigInt(timestamp);
3978
+ this.blocks.set(i, { seed: s, timestamp: t });
3979
+ }
3980
+ getBlockContent(index) {
3981
+ const i = asBigInt(index);
3982
+ if (this.blocks.has(i)) {
3983
+ return this.blocks.get(i);
3984
+ }
3985
+ throw internal.errors.internalError(`Block ${i} not set`);
3986
+ }
3987
+ getGlobalState(app, key) {
3988
+ const appData = this.applicationDataMap.get(app.id);
3989
+ if (!appData?.application.globalStates.has(key)) {
3990
+ return [undefined, false];
3991
+ }
3992
+ return [appData.application.globalStates.getOrFail(key), true];
3993
+ }
3994
+ setGlobalState(app, key, value) {
3995
+ const appData = this.applicationDataMap.getOrFail(app.id);
3996
+ const globalState = appData.application.globalStates.getOrFail(key);
3997
+ if (value === undefined) {
3998
+ globalState.delete();
3999
+ }
4000
+ else {
4001
+ globalState.value = asMaybeUint64Cls(value) ?? asMaybeBytesCls(value);
4002
+ }
4003
+ }
4004
+ getLocalState(app, account, key) {
4005
+ const appData = this.applicationDataMap.get(app.id);
4006
+ if (!appData?.application.localStates.has(key)) {
4007
+ return [undefined, false];
4008
+ }
4009
+ const localState = appData.application.localStates.getOrFail(key);
4010
+ return [localState(account), true];
4011
+ }
4012
+ setLocalState(app, account, key, value) {
4013
+ const appData = this.applicationDataMap.getOrFail(app.id);
4014
+ const localState = appData.application.localStates.getOrFail(key);
4015
+ const accountLocalState = localState(account);
4016
+ if (value === undefined) {
4017
+ accountLocalState.delete();
4018
+ }
4019
+ else {
4020
+ accountLocalState.value = asMaybeUint64Cls(value) ?? asMaybeBytesCls(value);
4021
+ }
4022
+ }
4023
+ getBox(app, key) {
4024
+ const appData = this.applicationDataMap.getOrFail(app.id);
4025
+ return appData.application.boxes.get(key) ?? new Uint8Array();
4026
+ }
4027
+ setBox(app, key, value) {
4028
+ const appData = this.applicationDataMap.getOrFail(app.id);
4029
+ appData.application.boxes.set(key, value);
4030
+ }
4031
+ deleteBox(app, key) {
4032
+ const appData = this.applicationDataMap.getOrFail(app.id);
4033
+ return appData.application.boxes.delete(key);
4034
+ }
4035
+ boxExists(app, key) {
4036
+ const appData = this.applicationDataMap.getOrFail(app.id);
4037
+ return appData.application.boxes.has(key);
4038
+ }
4039
+ }
4040
+
4041
+ function decodeLogs(logs, decoding) {
4042
+ return logs.map((log, i) => {
4043
+ switch (decoding[i]) {
4044
+ case 'i':
4045
+ return op.btoi(log);
4046
+ case 's':
4047
+ return log.toString();
4048
+ default:
4049
+ return log;
4050
+ }
4051
+ });
4052
+ }
4053
+
4054
+ function ScopeGenerator(dispose) {
4055
+ function* internal() {
4056
+ try {
4057
+ yield;
4058
+ }
4059
+ finally {
4060
+ dispose();
4061
+ }
4062
+ }
4063
+ const scope = internal();
4064
+ scope.next();
4065
+ return {
4066
+ done: () => {
4067
+ scope.return();
4068
+ },
4069
+ };
4070
+ }
4071
+ class DeferredAppCall {
4072
+ appId;
4073
+ txns;
4074
+ method;
4075
+ args;
4076
+ constructor(appId, txns, method, args) {
4077
+ this.appId = appId;
4078
+ this.txns = txns;
4079
+ this.method = method;
4080
+ this.args = args;
4081
+ }
4082
+ submit() {
4083
+ // TODO: check_routing_conditions
4084
+ return this.method(...this.args);
4085
+ }
4086
+ }
4087
+ class TransactionContext {
4088
+ groups = [];
4089
+ #activeGroup;
4090
+ createScope(group, activeTransactionIndex) {
4091
+ const transactions = group.map((t) => (t instanceof DeferredAppCall ? t.txns : [t])).flat();
4092
+ const transactionGroup = new TransactionGroup(transactions, activeTransactionIndex);
4093
+ const previousGroup = this.#activeGroup;
4094
+ this.#activeGroup = transactionGroup;
4095
+ const scope = ScopeGenerator(() => {
4096
+ if (this.#activeGroup?.transactions?.length) {
4097
+ this.groups.push(this.#activeGroup);
4098
+ }
4099
+ this.#activeGroup = previousGroup;
4100
+ });
4101
+ return {
4102
+ execute: (body) => {
4103
+ const result = body();
4104
+ scope.done();
4105
+ return result;
4106
+ },
4107
+ };
4108
+ }
4109
+ ensureScope(group, activeTransactionIndex) {
4110
+ if (!this.#activeGroup || !this.#activeGroup.transactions.length) {
4111
+ return this.createScope(group, activeTransactionIndex);
4112
+ }
4113
+ return {
4114
+ execute: (body) => {
4115
+ return body();
4116
+ },
4117
+ };
4118
+ }
4119
+ get activeGroup() {
4120
+ if (this.#activeGroup) {
4121
+ return this.#activeGroup;
4122
+ }
4123
+ throw internal.errors.internalError('no active txn group');
4124
+ }
4125
+ get lastGroup() {
4126
+ if (this.groups.length === 0) {
4127
+ internal.errors.internalError('No group transactions found!');
4128
+ }
4129
+ return this.groups.at(-1);
4130
+ }
4131
+ get lastActive() {
4132
+ return this.lastGroup.activeTransaction;
4133
+ }
4134
+ /* internal */
4135
+ appendLog(value) {
4136
+ const activeTransaction = this.activeGroup.activeTransaction;
4137
+ if (activeTransaction.type !== TransactionType.ApplicationCall) {
4138
+ throw internal.errors.internalError('Can only add logs to ApplicationCallTransaction!');
4139
+ }
4140
+ activeTransaction.appendLog(value);
4141
+ }
4142
+ deferAppCall(contract, method, ...args) {
4143
+ const appId = lazyContext.ledger.getApplicationForContract(contract);
4144
+ const txns = ContractContext.createMethodCallTxns(contract, method, ...args);
4145
+ return new DeferredAppCall(appId.id, txns, method, args);
4146
+ }
4147
+ exportLogs(appId, ...decoding) {
4148
+ const transaction = this.lastGroup.transactions
4149
+ .filter((t) => t.type === TransactionType.ApplicationCall)
4150
+ .find((t) => asBigInt(t.appId.id) === asBigInt(appId));
4151
+ let logs = [];
4152
+ if (transaction) {
4153
+ logs = transaction.appLogs;
4154
+ }
4155
+ else {
4156
+ logs = lazyContext.getApplicationData(appId).appLogs;
4157
+ }
4158
+ return decodeLogs(logs, decoding);
4159
+ }
4160
+ }
4161
+ class TransactionGroup {
4162
+ activeTransactionIndex;
4163
+ latestTimestamp;
4164
+ transactions;
4165
+ itxnGroups = [];
4166
+ constructingItxnGroup = [];
4167
+ constructor(transactions, activeTransactionIndex) {
4168
+ this.latestTimestamp = Date.now();
4169
+ if (transactions.length > algosdk.AtomicTransactionComposer.MAX_GROUP_SIZE) {
4170
+ internal.errors.internalError(`Transaction group can have at most ${algosdk.AtomicTransactionComposer.MAX_GROUP_SIZE} transactions, as per AVM limits.`);
4171
+ }
4172
+ transactions.forEach((txn, index) => Object.assign(txn, { groupIndex: asUint64(index) }));
4173
+ this.activeTransactionIndex = activeTransactionIndex === undefined ? transactions.length - 1 : activeTransactionIndex;
4174
+ this.transactions = transactions;
4175
+ }
4176
+ get activeTransaction() {
4177
+ return this.transactions[this.activeTransactionIndex];
4178
+ }
4179
+ get activeApplicationId() {
4180
+ if (this.transactions.length === 0) {
4181
+ internal.errors.internalError('No transactions in the group');
4182
+ }
4183
+ testInvariant(this.activeTransaction.type === TransactionType.ApplicationCall, 'No app_id found in the active transaction');
4184
+ return this.activeTransaction.appId.id;
4185
+ }
4186
+ get constructingItxn() {
4187
+ if (!this.constructingItxnGroup.length) {
4188
+ internal.errors.internalError('itxn field without itxn begin');
4189
+ }
4190
+ return this.constructingItxnGroup.at(-1);
4191
+ }
4192
+ getScratchSpace() {
4193
+ return this.activeTransaction.scratchSpace;
4194
+ }
4195
+ getScratchSlot(index) {
4196
+ return this.activeTransaction.getScratchSlot(index);
4197
+ }
4198
+ patchActiveTransactionFields(fields) {
4199
+ const activeTransaction = this.activeTransaction;
4200
+ const filteredFields = Object.fromEntries(Object.entries(fields).filter(([_, value]) => value !== undefined));
4201
+ Object.assign(activeTransaction, filteredFields);
4202
+ }
4203
+ beginInnerTransactionGroup() {
4204
+ if (this.constructingItxnGroup.length) {
4205
+ internal.errors.internalError('itxn begin without itxn submit');
4206
+ }
4207
+ testInvariant(this.activeTransaction.type === TransactionType.ApplicationCall, 'No active application call transaction');
4208
+ if (this.activeTransaction.onCompletion === 'ClearState') {
4209
+ internal.errors.internalError('Cannot begin inner transaction group in a clear state call');
4210
+ }
4211
+ this.constructingItxnGroup.push({});
4212
+ }
4213
+ appendInnerTransactionGroup() {
4214
+ if (!this.constructingItxnGroup.length) {
4215
+ internal.errors.internalError('itxn next without itxn begin');
4216
+ }
4217
+ this.constructingItxnGroup.push({ type: TransactionType.Payment });
4218
+ }
4219
+ submitInnerTransactionGroup() {
4220
+ if (!this.constructingItxnGroup.length) {
4221
+ internal.errors.internalError('itxn submit without itxn begin');
4222
+ }
4223
+ if (this.constructingItxnGroup.length > algosdk.AtomicTransactionComposer.MAX_GROUP_SIZE) {
4224
+ internal.errors.internalError('Cannot submit more than 16 inner transactions at once');
4225
+ }
4226
+ const itxns = this.constructingItxnGroup.map((t) => createInnerTxn(t));
4227
+ itxns.forEach((itxn, index) => Object.assign(itxn, { groupIndex: asUint64(index) }));
4228
+ this.itxnGroups.push(new ItxnGroup(itxns));
4229
+ this.constructingItxnGroup = [];
4230
+ }
4231
+ getItxnGroup(index) {
4232
+ const i = index !== undefined ? asNumber(index) : undefined;
4233
+ testInvariant(this.itxnGroups.length > 0, 'no previous inner transactions');
4234
+ if (i !== undefined && i >= this.itxnGroups.length) {
4235
+ throw new internal.errors.InternalError('Invalid group index');
4236
+ }
4237
+ const group = i !== undefined ? this.itxnGroups[i] : this.itxnGroups.at(-1);
4238
+ testInvariant(group.itxns.length > 0, 'no previous inner transactions');
4239
+ return group;
4240
+ }
4241
+ getApplicationTransaction(index) {
4242
+ return this.getTransactionImpl({ type: TransactionType.ApplicationCall, index });
4243
+ }
4244
+ getAssetConfigTransaction(index) {
4245
+ return this.getTransactionImpl({ type: TransactionType.AssetConfig, index });
4246
+ }
4247
+ getAssetTransferTransaction(index) {
4248
+ return this.getTransactionImpl({ type: TransactionType.AssetTransfer, index });
4249
+ }
4250
+ getAssetFreezeTransaction(index) {
4251
+ return this.getTransactionImpl({ type: TransactionType.AssetFreeze, index });
4252
+ }
4253
+ getKeyRegistrationTransaction(index) {
4254
+ return this.getTransactionImpl({ type: TransactionType.KeyRegistration, index });
4255
+ }
4256
+ getPaymentTransaction(index) {
4257
+ return this.getTransactionImpl({ type: TransactionType.Payment, index });
4258
+ }
4259
+ getTransaction(index) {
4260
+ return this.getTransactionImpl({ index });
4261
+ }
4262
+ getTransactionImpl({ type, index }) {
4263
+ const i = index !== undefined ? asNumber(index) : undefined;
4264
+ if (i !== undefined && i >= lazyContext.activeGroup.transactions.length) {
4265
+ throw new internal.errors.InternalError('Invalid group index');
4266
+ }
4267
+ const transaction = i !== undefined ? lazyContext.activeGroup.transactions[i] : lazyContext.activeGroup.activeTransaction;
4268
+ if (type === undefined) {
4269
+ return transaction;
4270
+ }
4271
+ if (transaction.type !== type) {
4272
+ throw new internal.errors.InternalError(`Invalid transaction type: ${transaction.type}`);
4273
+ }
4274
+ switch (type) {
4275
+ case TransactionType.ApplicationCall:
4276
+ return transaction;
4277
+ case TransactionType.Payment:
4278
+ return transaction;
4279
+ case TransactionType.AssetConfig:
4280
+ return transaction;
4281
+ case TransactionType.AssetTransfer:
4282
+ return transaction;
4283
+ case TransactionType.AssetFreeze:
4284
+ return transaction;
4285
+ case TransactionType.KeyRegistration:
4286
+ return transaction;
4287
+ default:
4288
+ throw new internal.errors.InternalError(`Invalid transaction type: ${type}`);
4289
+ }
4290
+ }
4291
+ }
4292
+ class ItxnGroup {
4293
+ itxns = [];
4294
+ constructor(itxns) {
4295
+ this.itxns = itxns;
4296
+ }
4297
+ getApplicationInnerTxn(index) {
4298
+ return this.getInnerTxnImpl({ type: TransactionType.ApplicationCall, index });
4299
+ }
4300
+ getAssetConfigInnerTxn(index) {
4301
+ return this.getInnerTxnImpl({ type: TransactionType.AssetConfig, index });
4302
+ }
4303
+ getAssetTransferInnerTxn(index) {
4304
+ return this.getInnerTxnImpl({ type: TransactionType.AssetTransfer, index });
4305
+ }
4306
+ getAssetFreezeInnerTxn(index) {
4307
+ return this.getInnerTxnImpl({ type: TransactionType.AssetFreeze, index });
4308
+ }
4309
+ getKeyRegistrationInnerTxn(index) {
4310
+ return this.getInnerTxnImpl({ type: TransactionType.KeyRegistration, index });
4311
+ }
4312
+ getPaymentInnerTxn(index) {
4313
+ return this.getInnerTxnImpl({ type: TransactionType.Payment, index });
4314
+ }
4315
+ getInnerTxn(index) {
4316
+ return this.getInnerTxnImpl({ index });
4317
+ }
4318
+ getInnerTxnImpl({ type, index }) {
4319
+ testInvariant(this.itxns.length > 0, 'no previous inner transactions');
4320
+ const i = index !== undefined ? asNumber(index) : undefined;
4321
+ if (i !== undefined && i >= this.itxns.length) {
4322
+ throw new internal.errors.InternalError('Invalid group index');
4323
+ }
4324
+ const transaction = i !== undefined ? this.itxns[i] : this.itxns.at(-1);
4325
+ if (type === undefined) {
4326
+ return transaction;
4327
+ }
4328
+ if (transaction.type !== type) {
4329
+ throw new internal.errors.InternalError(`Invalid transaction type: ${transaction.type}`);
4330
+ }
4331
+ switch (type) {
4332
+ case TransactionType.ApplicationCall:
4333
+ return transaction;
4334
+ case TransactionType.Payment:
4335
+ return transaction;
4336
+ case TransactionType.AssetConfig:
4337
+ return transaction;
4338
+ case TransactionType.AssetTransfer:
4339
+ return transaction;
4340
+ case TransactionType.AssetFreeze:
4341
+ return transaction;
4342
+ case TransactionType.KeyRegistration:
4343
+ return transaction;
4344
+ default:
4345
+ throw new internal.errors.InternalError(`Invalid transaction type: ${type}`);
4346
+ }
4347
+ }
4348
+ }
4349
+
4350
+ class AvmValueGenerator {
4351
+ uint64(minValue = 0n, maxValue = MAX_UINT64) {
4352
+ if (maxValue > MAX_UINT64) {
4353
+ internal.errors.internalError('maxValue must be less than or equal to MAX_UINT64');
4354
+ }
4355
+ if (minValue > maxValue) {
4356
+ internal.errors.internalError('minValue must be less than or equal to maxValue');
4357
+ }
4358
+ if (minValue < 0n || maxValue < 0n) {
4359
+ internal.errors.internalError('minValue and maxValue must be greater than or equal to 0');
4360
+ }
4361
+ return Uint64(getRandomBigInt(minValue, maxValue));
4362
+ }
4363
+ bytes(length = MAX_BYTES_SIZE) {
4364
+ return Bytes(new Uint8Array(randomBytes(length)));
4365
+ }
4366
+ account(input) {
4367
+ const account = input?.address ?? Account(Bytes.fromBase32(algosdk.generateAccount().addr));
4368
+ if (input?.address && lazyContext.ledger.accountDataMap.has(account)) {
4369
+ internal.errors.internalError('Account with such address already exists in testing context. Use `context.ledger.getAccount(address)` to retrieve the existing account.');
4370
+ }
4371
+ const data = new AccountData();
4372
+ const { address, optedAssetBalances, optedApplications, ...accountData } = input ?? {};
4373
+ data.account = {
4374
+ ...data.account,
4375
+ ...accountData,
4376
+ };
4377
+ lazyContext.ledger.accountDataMap.set(account, data);
4378
+ if (input?.optedAssetBalances) {
4379
+ for (const [assetId, balance] of input.optedAssetBalances) {
4380
+ lazyContext.ledger.updateAssetHolding(account, assetId, balance);
4381
+ }
4382
+ }
4383
+ if (input?.optedApplications) {
4384
+ for (const app of input.optedApplications) {
4385
+ data.optedApplications.set(asBigInt(app.id), app);
4386
+ }
4387
+ }
4388
+ return account;
4389
+ }
4390
+ asset(input) {
4391
+ const id = input?.assetId;
4392
+ if (id && lazyContext.ledger.assetDataMap.has(id)) {
4393
+ internal.errors.internalError('Asset with such ID already exists in testing context!');
4394
+ }
4395
+ const assetId = asUint64Cls(id ?? lazyContext.ledger.assetIdIter.next().value);
4396
+ const defaultAssetData = {
4397
+ total: lazyContext.any.uint64(),
4398
+ decimals: lazyContext.any.uint64(1, 6),
4399
+ defaultFrozen: false,
4400
+ unitName: lazyContext.any.bytes(4),
4401
+ name: lazyContext.any.bytes(32),
4402
+ url: lazyContext.any.bytes(10),
4403
+ metadataHash: lazyContext.any.bytes(32),
4404
+ manager: Account(ZERO_ADDRESS),
4405
+ freeze: Account(ZERO_ADDRESS),
4406
+ clawback: Account(ZERO_ADDRESS),
4407
+ creator: lazyContext.defaultSender,
4408
+ reserve: Account(ZERO_ADDRESS),
4409
+ };
4410
+ const { assetId: _, ...assetData } = input ?? {};
4411
+ lazyContext.ledger.assetDataMap.set(assetId, {
4412
+ ...defaultAssetData,
4413
+ ...assetData,
4414
+ });
4415
+ return new AssetCls(assetId.asAlgoTs());
4416
+ }
4417
+ application(input) {
4418
+ const id = input?.applicationId;
4419
+ if (id && lazyContext.ledger.applicationDataMap.has(id)) {
4420
+ internal.errors.internalError('Application with such ID already exists in testing context!');
4421
+ }
4422
+ const applicationId = asUint64Cls(id ?? lazyContext.ledger.appIdIter.next().value);
4423
+ const data = new ApplicationData();
4424
+ const { applicationId: _, ...applicationData } = input ?? {};
4425
+ data.application = {
4426
+ ...data.application,
4427
+ ...applicationData,
4428
+ };
4429
+ lazyContext.ledger.applicationDataMap.set(applicationId, data);
4430
+ return new ApplicationCls(applicationId.asAlgoTs());
4431
+ }
4432
+ }
4433
+
4434
+ class TxnValueGenerator {
4435
+ applicationCall(fields) {
4436
+ const params = fields ?? {};
4437
+ if (params.appId && !lazyContext.ledger.applicationDataMap.has(params.appId.id)) {
4438
+ internal.errors.internalError(`Application ID ${params.appId.id} not found in test context`);
4439
+ }
4440
+ if (!params.appId) {
4441
+ params.appId = lazyContext.any.application();
4442
+ }
4443
+ return ApplicationTransaction.create(params);
4444
+ }
4445
+ payment(fields) {
4446
+ return PaymentTransaction.create(fields ?? {});
4447
+ }
4448
+ keyRegistration(fields) {
4449
+ return KeyRegistrationTransaction.create(fields ?? {});
4450
+ }
4451
+ assetConfig(fields) {
4452
+ return AssetConfigTransaction.create(fields ?? {});
4453
+ }
4454
+ assetTransfer(fields) {
4455
+ return AssetTransferTransaction.create(fields ?? {});
4456
+ }
4457
+ assetFreeze(fields) {
4458
+ return AssetFreezeTransaction.create(fields ?? {});
4459
+ }
4460
+ }
4461
+
4462
+ class ValueGenerator extends AvmValueGenerator {
4463
+ txn;
4464
+ constructor() {
4465
+ super();
4466
+ this.txn = new TxnValueGenerator();
4467
+ }
4468
+ }
4469
+
4470
+ class TestExecutionContext {
4471
+ #contractContext;
4472
+ #ledgerContext;
4473
+ #txnContext;
4474
+ #valueGenerator;
4475
+ #defaultSender;
4476
+ constructor() {
4477
+ internal.ctxMgr.instance = this;
4478
+ this.#contractContext = new ContractContext();
4479
+ this.#ledgerContext = new LedgerContext();
4480
+ this.#txnContext = new TransactionContext();
4481
+ this.#valueGenerator = new ValueGenerator();
4482
+ this.#defaultSender = Account(Bytes.fromBase32(algosdk.generateAccount().addr));
4483
+ }
4484
+ account(address) {
4485
+ return new AccountCls(address);
4486
+ }
4487
+ application(id) {
4488
+ return new ApplicationCls(id);
4489
+ }
4490
+ asset(id) {
4491
+ return new AssetCls(id);
4492
+ }
4493
+ log(value) {
4494
+ this.txn.appendLog(value);
4495
+ }
4496
+ exportLogs(appId, ...decoding) {
4497
+ return this.txn.exportLogs(appId, ...decoding);
4498
+ }
4499
+ get op() {
4500
+ return ops;
4501
+ }
4502
+ get contract() {
4503
+ return this.#contractContext;
4504
+ }
4505
+ get ledger() {
4506
+ return this.#ledgerContext;
4507
+ }
4508
+ get txn() {
4509
+ return this.#txnContext;
4510
+ }
4511
+ get any() {
4512
+ return this.#valueGenerator;
4513
+ }
4514
+ get defaultSender() {
4515
+ return this.#defaultSender;
4516
+ }
4517
+ get abiMetadata() {
4518
+ return {
4519
+ captureMethodConfig,
4520
+ };
4521
+ }
4522
+ get gtxn() {
4523
+ return {
4524
+ Transaction: (index) => this.txn.activeGroup.getTransaction(index),
4525
+ PaymentTxn: (index) => this.txn.activeGroup.getPaymentTransaction(index),
4526
+ KeyRegistrationTxn: (index) => this.txn.activeGroup.getKeyRegistrationTransaction(index),
4527
+ AssetConfigTxn: (index) => this.txn.activeGroup.getAssetConfigTransaction(index),
4528
+ AssetTransferTxn: (index) => this.txn.activeGroup.getAssetTransferTransaction(index),
4529
+ AssetFreezeTxn: (index) => this.txn.activeGroup.getAssetFreezeTransaction(index),
4530
+ ApplicationTxn: (index) => this.txn.activeGroup.getApplicationTransaction(index),
4531
+ };
4532
+ }
4533
+ get itxn() {
4534
+ return {
4535
+ submitGroup: submitGroup,
4536
+ payment: payment,
4537
+ keyRegistration: keyRegistration,
4538
+ assetConfig: assetConfig,
4539
+ assetTransfer: assetTransfer,
4540
+ assetFreeze: assetFreeze,
4541
+ applicationCall: applicationCall,
4542
+ };
4543
+ }
4544
+ get state() {
4545
+ return {
4546
+ GlobalState,
4547
+ LocalState,
4548
+ Box,
4549
+ BoxMap,
4550
+ BoxRef,
4551
+ };
4552
+ }
4553
+ reset() {
4554
+ this.#contractContext = new ContractContext();
4555
+ this.#ledgerContext = new LedgerContext();
4556
+ this.#txnContext = new TransactionContext();
4557
+ internal.ctxMgr.reset();
4558
+ internal.ctxMgr.instance = this;
4559
+ }
4560
+ }
4561
+
4562
+ export { TestExecutionContext };
4563
+ //# sourceMappingURL=index.mjs.map