@algorandfoundation/algokit-utils 9.2.0 → 9.2.1-beta.2

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 (340) hide show
  1. package/_virtual/_rolldown/runtime.js +33 -0
  2. package/_virtual/_rolldown/runtime.mjs +13 -0
  3. package/account/account.d.ts +25 -30
  4. package/account/account.js +151 -146
  5. package/account/account.js.map +1 -1
  6. package/account/account.mjs +149 -144
  7. package/account/account.mjs.map +1 -1
  8. package/account/get-account-config-from-environment.d.ts +7 -2
  9. package/account/get-account-config-from-environment.js +19 -21
  10. package/account/get-account-config-from-environment.js.map +1 -1
  11. package/account/get-account-config-from-environment.mjs +19 -19
  12. package/account/get-account-config-from-environment.mjs.map +1 -1
  13. package/account/get-account.d.ts +14 -12
  14. package/account/get-account.js +56 -59
  15. package/account/get-account.js.map +1 -1
  16. package/account/get-account.mjs +56 -57
  17. package/account/get-account.mjs.map +1 -1
  18. package/account/get-dispenser-account.d.ts +9 -5
  19. package/account/get-dispenser-account.js +20 -18
  20. package/account/get-dispenser-account.js.map +1 -1
  21. package/account/get-dispenser-account.mjs +20 -16
  22. package/account/get-dispenser-account.mjs.map +1 -1
  23. package/account/mnemonic-account.d.ts +7 -3
  24. package/account/mnemonic-account.js +17 -17
  25. package/account/mnemonic-account.js.map +1 -1
  26. package/account/mnemonic-account.mjs +15 -15
  27. package/account/mnemonic-account.mjs.map +1 -1
  28. package/amount.d.ts +40 -35
  29. package/amount.js +33 -34
  30. package/amount.js.map +1 -1
  31. package/amount.mjs +33 -32
  32. package/amount.mjs.map +1 -1
  33. package/app-client.d.ts +10 -6
  34. package/app-client.js +91 -86
  35. package/app-client.js.map +1 -1
  36. package/app-client.mjs +91 -84
  37. package/app-client.mjs.map +1 -1
  38. package/app-deploy.d.ts +26 -24
  39. package/app-deploy.js +235 -253
  40. package/app-deploy.js.map +1 -1
  41. package/app-deploy.mjs +233 -251
  42. package/app-deploy.mjs.map +1 -1
  43. package/app.d.ts +45 -46
  44. package/app.js +253 -271
  45. package/app.js.map +1 -1
  46. package/app.mjs +249 -267
  47. package/app.mjs.map +1 -1
  48. package/asset.d.ts +16 -12
  49. package/asset.js +116 -122
  50. package/asset.js.map +1 -1
  51. package/asset.mjs +116 -120
  52. package/asset.mjs.map +1 -1
  53. package/config.d.ts +7 -2
  54. package/config.js +5 -7
  55. package/config.js.map +1 -1
  56. package/config.mjs +5 -4
  57. package/config.mjs.map +1 -1
  58. package/debugging/debugging.d.ts +5 -1
  59. package/debugging/debugging.js +11 -11
  60. package/debugging/debugging.js.map +1 -1
  61. package/debugging/debugging.mjs +11 -9
  62. package/debugging/debugging.mjs.map +1 -1
  63. package/dispenser-client.d.ts +7 -2
  64. package/dispenser-client.js +23 -24
  65. package/dispenser-client.js.map +1 -1
  66. package/dispenser-client.mjs +23 -22
  67. package/dispenser-client.mjs.map +1 -1
  68. package/index.d.ts +27 -18
  69. package/index.js +140 -143
  70. package/index.mjs +27 -29
  71. package/indexer-lookup.d.ts +18 -11
  72. package/indexer-lookup.js +112 -120
  73. package/indexer-lookup.js.map +1 -1
  74. package/indexer-lookup.mjs +105 -118
  75. package/indexer-lookup.mjs.map +1 -1
  76. package/localnet/get-kmd-wallet-account.d.ts +9 -7
  77. package/localnet/get-kmd-wallet-account.js +28 -26
  78. package/localnet/get-kmd-wallet-account.js.map +1 -1
  79. package/localnet/get-kmd-wallet-account.mjs +28 -24
  80. package/localnet/get-kmd-wallet-account.mjs.map +1 -1
  81. package/localnet/get-localnet-dispenser-account.d.ts +7 -5
  82. package/localnet/get-localnet-dispenser-account.js +17 -15
  83. package/localnet/get-localnet-dispenser-account.js.map +1 -1
  84. package/localnet/get-localnet-dispenser-account.mjs +17 -13
  85. package/localnet/get-localnet-dispenser-account.mjs.map +1 -1
  86. package/localnet/get-or-create-kmd-wallet-account.d.ts +10 -8
  87. package/localnet/get-or-create-kmd-wallet-account.js +28 -26
  88. package/localnet/get-or-create-kmd-wallet-account.js.map +1 -1
  89. package/localnet/get-or-create-kmd-wallet-account.mjs +28 -24
  90. package/localnet/get-or-create-kmd-wallet-account.mjs.map +1 -1
  91. package/localnet/is-localnet.d.ts +7 -3
  92. package/localnet/is-localnet.js +9 -10
  93. package/localnet/is-localnet.js.map +1 -1
  94. package/localnet/is-localnet.mjs +9 -8
  95. package/localnet/is-localnet.mjs.map +1 -1
  96. package/network-client.d.ts +17 -15
  97. package/network-client.js +115 -116
  98. package/network-client.js.map +1 -1
  99. package/network-client.mjs +115 -114
  100. package/network-client.mjs.map +1 -1
  101. package/package.json +12 -3
  102. package/testing/account.d.ts +11 -9
  103. package/testing/account.js +31 -33
  104. package/testing/account.js.map +1 -1
  105. package/testing/account.mjs +29 -31
  106. package/testing/account.mjs.map +1 -1
  107. package/testing/fixtures/algokit-log-capture-fixture.d.ts +7 -2
  108. package/testing/fixtures/algokit-log-capture-fixture.js +36 -41
  109. package/testing/fixtures/algokit-log-capture-fixture.js.map +1 -1
  110. package/testing/fixtures/algokit-log-capture-fixture.mjs +36 -39
  111. package/testing/fixtures/algokit-log-capture-fixture.mjs.map +1 -1
  112. package/testing/fixtures/algorand-fixture.d.ts +9 -4
  113. package/testing/fixtures/algorand-fixture.js +67 -62
  114. package/testing/fixtures/algorand-fixture.js.map +1 -1
  115. package/testing/fixtures/algorand-fixture.mjs +66 -59
  116. package/testing/fixtures/algorand-fixture.mjs.map +1 -1
  117. package/testing/index.d.ts +7 -5
  118. package/testing/index.js +13 -18
  119. package/testing/index.mjs +7 -7
  120. package/testing/indexer.d.ts +5 -1
  121. package/testing/indexer.js +28 -37
  122. package/testing/indexer.js.map +1 -1
  123. package/testing/indexer.mjs +28 -35
  124. package/testing/indexer.mjs.map +1 -1
  125. package/testing/test-logger.d.ts +41 -36
  126. package/testing/test-logger.js +71 -76
  127. package/testing/test-logger.js.map +1 -1
  128. package/testing/test-logger.mjs +71 -74
  129. package/testing/test-logger.mjs.map +1 -1
  130. package/testing/transaction-logger.d.ts +30 -27
  131. package/testing/transaction-logger.js +77 -93
  132. package/testing/transaction-logger.js.map +1 -1
  133. package/testing/transaction-logger.mjs +74 -90
  134. package/testing/transaction-logger.mjs.map +1 -1
  135. package/transaction/legacy-bridge.js +100 -111
  136. package/transaction/legacy-bridge.js.map +1 -1
  137. package/transaction/legacy-bridge.mjs +97 -108
  138. package/transaction/legacy-bridge.mjs.map +1 -1
  139. package/transaction/perform-atomic-transaction-composer-simulate.d.ts +7 -5
  140. package/transaction/perform-atomic-transaction-composer-simulate.js +31 -36
  141. package/transaction/perform-atomic-transaction-composer-simulate.js.map +1 -1
  142. package/transaction/perform-atomic-transaction-composer-simulate.mjs +28 -33
  143. package/transaction/perform-atomic-transaction-composer-simulate.mjs.map +1 -1
  144. package/transaction/transaction.d.ts +34 -35
  145. package/transaction/transaction.js +716 -914
  146. package/transaction/transaction.js.map +1 -1
  147. package/transaction/transaction.mjs +713 -911
  148. package/transaction/transaction.mjs.map +1 -1
  149. package/transfer/transfer-algos.d.ts +9 -5
  150. package/transfer/transfer-algos.js +26 -27
  151. package/transfer/transfer-algos.js.map +1 -1
  152. package/transfer/transfer-algos.mjs +26 -25
  153. package/transfer/transfer-algos.mjs.map +1 -1
  154. package/transfer/transfer.d.ts +11 -8
  155. package/transfer/transfer.js +94 -100
  156. package/transfer/transfer.js.map +1 -1
  157. package/transfer/transfer.mjs +94 -98
  158. package/transfer/transfer.mjs.map +1 -1
  159. package/types/account-manager.d.ts +432 -429
  160. package/types/account-manager.js +591 -602
  161. package/types/account-manager.js.map +1 -1
  162. package/types/account-manager.mjs +587 -599
  163. package/types/account-manager.mjs.map +1 -1
  164. package/types/account.d.ts +192 -202
  165. package/types/account.js +91 -88
  166. package/types/account.js.map +1 -1
  167. package/types/account.mjs +88 -86
  168. package/types/account.mjs.map +1 -1
  169. package/types/algo-http-client-with-retry.d.ts +15 -10
  170. package/types/algo-http-client-with-retry.js +70 -92
  171. package/types/algo-http-client-with-retry.js.map +1 -1
  172. package/types/algo-http-client-with-retry.mjs +69 -90
  173. package/types/algo-http-client-with-retry.mjs.map +1 -1
  174. package/types/algorand-client-transaction-creator.d.ts +778 -771
  175. package/types/algorand-client-transaction-creator.js +733 -732
  176. package/types/algorand-client-transaction-creator.js.map +1 -1
  177. package/types/algorand-client-transaction-creator.mjs +732 -730
  178. package/types/algorand-client-transaction-creator.mjs.map +1 -1
  179. package/types/algorand-client-transaction-sender.d.ts +1090 -1360
  180. package/types/algorand-client-transaction-sender.js +930 -961
  181. package/types/algorand-client-transaction-sender.js.map +1 -1
  182. package/types/algorand-client-transaction-sender.mjs +927 -959
  183. package/types/algorand-client-transaction-sender.mjs.map +1 -1
  184. package/types/algorand-client.d.ts +239 -236
  185. package/types/algorand-client.js +322 -320
  186. package/types/algorand-client.js.map +1 -1
  187. package/types/algorand-client.mjs +321 -318
  188. package/types/algorand-client.mjs.map +1 -1
  189. package/types/amount.d.ts +47 -43
  190. package/types/amount.js +66 -70
  191. package/types/amount.js.map +1 -1
  192. package/types/amount.mjs +63 -68
  193. package/types/amount.mjs.map +1 -1
  194. package/types/app-arc56.d.ts +235 -272
  195. package/types/app-arc56.js +124 -170
  196. package/types/app-arc56.js.map +1 -1
  197. package/types/app-arc56.mjs +121 -168
  198. package/types/app-arc56.mjs.map +1 -1
  199. package/types/app-client.d.ts +1128 -2009
  200. package/types/app-client.js +1633 -1791
  201. package/types/app-client.js.map +1 -1
  202. package/types/app-client.mjs +1624 -1783
  203. package/types/app-client.mjs.map +1 -1
  204. package/types/app-deployer.d.ts +139 -141
  205. package/types/app-deployer.js +344 -384
  206. package/types/app-deployer.js.map +1 -1
  207. package/types/app-deployer.mjs +341 -382
  208. package/types/app-deployer.mjs.map +1 -1
  209. package/types/app-factory.d.ts +762 -932
  210. package/types/app-factory.js +496 -488
  211. package/types/app-factory.js.map +1 -1
  212. package/types/app-factory.mjs +491 -484
  213. package/types/app-factory.mjs.map +1 -1
  214. package/types/app-manager.d.ts +304 -310
  215. package/types/app-manager.js +422 -475
  216. package/types/app-manager.js.map +1 -1
  217. package/types/app-manager.mjs +419 -473
  218. package/types/app-manager.mjs.map +1 -1
  219. package/types/app-spec.d.ts +118 -117
  220. package/types/app-spec.js +125 -135
  221. package/types/app-spec.js.map +1 -1
  222. package/types/app-spec.mjs +121 -132
  223. package/types/app-spec.mjs.map +1 -1
  224. package/types/app.d.ts +229 -241
  225. package/types/app.js +36 -28
  226. package/types/app.js.map +1 -1
  227. package/types/app.mjs +33 -26
  228. package/types/app.mjs.map +1 -1
  229. package/types/asset-manager.d.ts +204 -199
  230. package/types/asset-manager.js +165 -174
  231. package/types/asset-manager.js.map +1 -1
  232. package/types/asset-manager.mjs +164 -172
  233. package/types/asset-manager.mjs.map +1 -1
  234. package/types/asset.d.ts +95 -91
  235. package/types/asset.js +0 -3
  236. package/types/asset.mjs +0 -2
  237. package/types/async-event-emitter.d.ts +18 -13
  238. package/types/async-event-emitter.js +37 -49
  239. package/types/async-event-emitter.js.map +1 -1
  240. package/types/async-event-emitter.mjs +36 -47
  241. package/types/async-event-emitter.mjs.map +1 -1
  242. package/types/client-manager.d.ts +453 -451
  243. package/types/client-manager.js +602 -598
  244. package/types/client-manager.js.map +1 -1
  245. package/types/client-manager.mjs +597 -594
  246. package/types/client-manager.mjs.map +1 -1
  247. package/types/composer.d.ts +1211 -1258
  248. package/types/composer.js +1436 -1498
  249. package/types/composer.js.map +1 -1
  250. package/types/composer.mjs +1430 -1493
  251. package/types/composer.mjs.map +1 -1
  252. package/types/config.d.ts +53 -48
  253. package/types/config.js +78 -77
  254. package/types/config.js.map +1 -1
  255. package/types/config.mjs +77 -75
  256. package/types/config.mjs.map +1 -1
  257. package/types/debugging.d.ts +25 -23
  258. package/types/debugging.js +9 -11
  259. package/types/debugging.js.map +1 -1
  260. package/types/debugging.mjs +8 -9
  261. package/types/debugging.mjs.map +1 -1
  262. package/types/dispenser-client.d.ts +57 -52
  263. package/types/dispenser-client.js +120 -141
  264. package/types/dispenser-client.js.map +1 -1
  265. package/types/dispenser-client.mjs +119 -139
  266. package/types/dispenser-client.mjs.map +1 -1
  267. package/types/expand.d.ts +5 -3
  268. package/types/expand.js +0 -3
  269. package/types/expand.mjs +0 -2
  270. package/types/indexer.d.ts +104 -100
  271. package/types/indexer.js +36 -31
  272. package/types/indexer.js.map +1 -1
  273. package/types/indexer.mjs +32 -30
  274. package/types/indexer.mjs.map +1 -1
  275. package/types/instance-of.d.ts +5 -3
  276. package/types/instance-of.js +0 -3
  277. package/types/instance-of.mjs +0 -2
  278. package/types/kmd-account-manager.d.ts +75 -70
  279. package/types/kmd-account-manager.js +150 -184
  280. package/types/kmd-account-manager.js.map +1 -1
  281. package/types/kmd-account-manager.mjs +147 -182
  282. package/types/kmd-account-manager.mjs.map +1 -1
  283. package/types/lifecycle-events.d.ts +13 -8
  284. package/types/lifecycle-events.js +10 -7
  285. package/types/lifecycle-events.js.map +1 -1
  286. package/types/lifecycle-events.mjs +9 -7
  287. package/types/lifecycle-events.mjs.map +1 -1
  288. package/types/logging.d.ts +15 -11
  289. package/types/logging.js +30 -31
  290. package/types/logging.js.map +1 -1
  291. package/types/logging.mjs +29 -29
  292. package/types/logging.mjs.map +1 -1
  293. package/types/logic-error.d.ts +33 -29
  294. package/types/logic-error.js +50 -49
  295. package/types/logic-error.js.map +1 -1
  296. package/types/logic-error.mjs +49 -47
  297. package/types/logic-error.mjs.map +1 -1
  298. package/types/network-client.d.ts +32 -27
  299. package/types/network-client.js +10 -9
  300. package/types/network-client.js.map +1 -1
  301. package/types/network-client.mjs +9 -7
  302. package/types/network-client.mjs.map +1 -1
  303. package/types/testing.d.ts +131 -132
  304. package/types/testing.js +0 -3
  305. package/types/testing.mjs +0 -2
  306. package/types/transaction.d.ts +110 -110
  307. package/types/transaction.js +0 -3
  308. package/types/transaction.mjs +0 -2
  309. package/types/transfer.d.ts +70 -66
  310. package/types/transfer.js +0 -3
  311. package/types/transfer.mjs +0 -2
  312. package/util.js +73 -118
  313. package/util.js.map +1 -1
  314. package/util.mjs +73 -116
  315. package/util.mjs.map +1 -1
  316. package/account/index.d.ts +0 -5
  317. package/debugging/index.d.ts +0 -1
  318. package/index.js.map +0 -1
  319. package/index.mjs.map +0 -1
  320. package/localnet/index.d.ts +0 -4
  321. package/testing/_asset.d.ts +0 -3
  322. package/testing/fixtures/index.d.ts +0 -2
  323. package/testing/index.js.map +0 -1
  324. package/testing/index.mjs.map +0 -1
  325. package/transaction/index.d.ts +0 -2
  326. package/transaction/legacy-bridge.d.ts +0 -35
  327. package/transfer/index.d.ts +0 -2
  328. package/types/asset.js.map +0 -1
  329. package/types/asset.mjs.map +0 -1
  330. package/types/expand.js.map +0 -1
  331. package/types/expand.mjs.map +0 -1
  332. package/types/instance-of.js.map +0 -1
  333. package/types/instance-of.mjs.map +0 -1
  334. package/types/testing.js.map +0 -1
  335. package/types/testing.mjs.map +0 -1
  336. package/types/transaction.js.map +0 -1
  337. package/types/transaction.mjs.map +0 -1
  338. package/types/transfer.js.map +0 -1
  339. package/types/transfer.mjs.map +0 -1
  340. package/util.d.ts +0 -48
@@ -1,966 +1,768 @@
1
- import algosdk, { TransactionType, stringifyJSON, Address } from 'algosdk';
2
- import { Buffer } from 'buffer';
3
- import { Config } from '../config.mjs';
4
- import { EventType } from '../types/lifecycle-events.mjs';
5
- import { asJson, convertAbiByteArrays, convertABIDecodedBigIntToNumber, toNumber } from '../util.mjs';
6
- import { performAtomicTransactionComposerSimulate } from './perform-atomic-transaction-composer-simulate.mjs';
7
-
1
+ import { Config } from "../config.mjs";
2
+ import "../types/lifecycle-events.mjs";
3
+ import { asJson, convertABIDecodedBigIntToNumber, convertAbiByteArrays, toNumber } from "../util.mjs";
4
+ import { performAtomicTransactionComposerSimulate } from "./perform-atomic-transaction-composer-simulate.mjs";
5
+ import algosdk, { Address, TransactionType, stringifyJSON } from "algosdk";
6
+ import { Buffer } from "buffer";
7
+ //#region src/transaction/transaction.ts
8
8
  var AtomicTransactionComposer = algosdk.AtomicTransactionComposer;
9
9
  const MAX_TRANSACTION_GROUP_SIZE = 16;
10
10
  const MAX_APP_CALL_FOREIGN_REFERENCES = 8;
11
11
  const MAX_APP_CALL_ACCOUNT_REFERENCES = 8;
12
12
  /**
13
- * @deprecated Convert your data to a `string` or `Uint8Array`, if using ARC-2 use `TransactionComposer.arc2Note`.
14
- *
15
- * Encodes a transaction note into a byte array ready to be included in an Algorand transaction.
16
- *
17
- * @param note The transaction note
18
- * @returns the transaction note ready for inclusion in a transaction
19
- *
20
- * Case on the value of `data` this either be:
21
- * * `null` | `undefined`: `undefined`
22
- * * `string`: The string value
23
- * * Uint8Array: passthrough
24
- * * Arc2TransactionNote object: ARC-0002 compatible transaction note
25
- * * Else: The object/value converted into a JSON string representation
26
- */
13
+ * @deprecated Convert your data to a `string` or `Uint8Array`, if using ARC-2 use `TransactionComposer.arc2Note`.
14
+ *
15
+ * Encodes a transaction note into a byte array ready to be included in an Algorand transaction.
16
+ *
17
+ * @param note The transaction note
18
+ * @returns the transaction note ready for inclusion in a transaction
19
+ *
20
+ * Case on the value of `data` this either be:
21
+ * * `null` | `undefined`: `undefined`
22
+ * * `string`: The string value
23
+ * * Uint8Array: passthrough
24
+ * * Arc2TransactionNote object: ARC-0002 compatible transaction note
25
+ * * Else: The object/value converted into a JSON string representation
26
+ */
27
27
  function encodeTransactionNote(note) {
28
- if (note == null || typeof note === 'undefined') {
29
- return undefined;
30
- }
31
- else if (typeof note === 'object' && note.constructor === Uint8Array) {
32
- return note;
33
- }
34
- else if (typeof note === 'object' && 'dAppName' in note) {
35
- const arc2Payload = `${note.dAppName}:${note.format}${typeof note.data === 'string' ? note.data : asJson(note.data)}`;
36
- const encoder = new TextEncoder();
37
- return encoder.encode(arc2Payload);
38
- }
39
- else {
40
- const n = typeof note === 'string' ? note : asJson(note);
41
- const encoder = new TextEncoder();
42
- return encoder.encode(n);
43
- }
28
+ if (note == null || typeof note === "undefined") return;
29
+ else if (typeof note === "object" && note.constructor === Uint8Array) return note;
30
+ else if (typeof note === "object" && "dAppName" in note) {
31
+ const arc2Payload = `${note.dAppName}:${note.format}${typeof note.data === "string" ? note.data : asJson(note.data)}`;
32
+ return new TextEncoder().encode(arc2Payload);
33
+ } else {
34
+ const n = typeof note === "string" ? note : asJson(note);
35
+ return new TextEncoder().encode(n);
36
+ }
44
37
  }
45
38
  /** Encodes a transaction lease into a 32-byte array ready to be included in an Algorand transaction.
46
- *
47
- * @param lease The transaction lease as a string or binary array or null/undefined if there is no lease
48
- * @returns the transaction lease ready for inclusion in a transaction or `undefined` if there is no lease
49
- * @throws if the length of the data is > 32 bytes or empty
50
- * @example algokit.encodeLease('UNIQUE_ID')
51
- * @example algokit.encodeLease(new Uint8Array([1, 2, 3]))
52
- */
39
+ *
40
+ * @param lease The transaction lease as a string or binary array or null/undefined if there is no lease
41
+ * @returns the transaction lease ready for inclusion in a transaction or `undefined` if there is no lease
42
+ * @throws if the length of the data is > 32 bytes or empty
43
+ * @example algokit.encodeLease('UNIQUE_ID')
44
+ * @example algokit.encodeLease(new Uint8Array([1, 2, 3]))
45
+ */
53
46
  function encodeLease(lease) {
54
- if (lease === null || typeof lease === 'undefined') {
55
- return undefined;
56
- }
57
- else if (typeof lease === 'object' && lease.constructor === Uint8Array) {
58
- if (lease.length === 0 || lease.length > 32) {
59
- throw new Error(`Received invalid lease; expected something with length between 1 and 32, but received bytes with length ${lease.length}`);
60
- }
61
- if (lease.length === 32)
62
- return lease;
63
- const lease32 = new Uint8Array(32);
64
- lease32.set(lease, 0);
65
- return lease32;
66
- }
67
- else if (typeof lease === 'string') {
68
- if (lease.length === 0 || lease.length > 32) {
69
- throw new Error(`Received invalid lease; expected something with length between 1 and 32, but received '${lease}' with length ${lease.length}`);
70
- }
71
- const encoder = new TextEncoder();
72
- const lease32 = new Uint8Array(32);
73
- lease32.set(encoder.encode(lease), 0);
74
- return lease32;
75
- }
76
- else {
77
- throw new Error(`Unknown lease type received of ${typeof lease}`);
78
- }
47
+ if (lease === null || typeof lease === "undefined") return;
48
+ else if (typeof lease === "object" && lease.constructor === Uint8Array) {
49
+ if (lease.length === 0 || lease.length > 32) throw new Error(`Received invalid lease; expected something with length between 1 and 32, but received bytes with length ${lease.length}`);
50
+ if (lease.length === 32) return lease;
51
+ const lease32 = /* @__PURE__ */ new Uint8Array(32);
52
+ lease32.set(lease, 0);
53
+ return lease32;
54
+ } else if (typeof lease === "string") {
55
+ if (lease.length === 0 || lease.length > 32) throw new Error(`Received invalid lease; expected something with length between 1 and 32, but received '${lease}' with length ${lease.length}`);
56
+ const encoder = new TextEncoder();
57
+ const lease32 = /* @__PURE__ */ new Uint8Array(32);
58
+ lease32.set(encoder.encode(lease), 0);
59
+ return lease32;
60
+ } else throw new Error(`Unknown lease type received of ${typeof lease}`);
79
61
  }
80
62
  /**
81
- * @deprecated Use `algorand.client` to interact with accounts, and use `.addr` to get the address
82
- * and/or move from using `SendTransactionFrom` to `TransactionSignerAccount` and use `.addr` instead.
83
- *
84
- * Returns the public address of the given transaction sender.
85
- * @param sender A transaction sender
86
- * @returns The public address
87
- */
88
- const getSenderAddress = function (sender) {
89
- return typeof sender === 'string' ? sender : 'addr' in sender ? sender.addr.toString() : sender.address().toString();
63
+ * @deprecated Use `algorand.client` to interact with accounts, and use `.addr` to get the address
64
+ * and/or move from using `SendTransactionFrom` to `TransactionSignerAccount` and use `.addr` instead.
65
+ *
66
+ * Returns the public address of the given transaction sender.
67
+ * @param sender A transaction sender
68
+ * @returns The public address
69
+ */
70
+ const getSenderAddress = function(sender) {
71
+ return typeof sender === "string" ? sender : "addr" in sender ? sender.addr.toString() : sender.address().toString();
90
72
  };
91
73
  /**
92
- * @deprecated Use `AlgorandClient` / `TransactionComposer` to construct transactions instead or
93
- * construct an `algosdk.TransactionWithSigner` manually instead.
94
- *
95
- * Given a transaction in a variety of supported formats, returns a TransactionWithSigner object ready to be passed to an
96
- * AtomicTransactionComposer's addTransaction method.
97
- * @param transaction One of: A TransactionWithSigner object (returned as is), a TransactionToSign object (signer is obtained from the
98
- * signer property), a Transaction object (signer is extracted from the defaultSender parameter), an async SendTransactionResult returned by
99
- * one of algokit utils' helpers (signer is obtained from the defaultSender parameter)
100
- * @param defaultSender The default sender to be used to obtain a signer where the object provided to the transaction parameter does not
101
- * include a signer.
102
- * @returns A TransactionWithSigner object.
103
- */
74
+ * @deprecated Use `AlgorandClient` / `TransactionComposer` to construct transactions instead or
75
+ * construct an `algosdk.TransactionWithSigner` manually instead.
76
+ *
77
+ * Given a transaction in a variety of supported formats, returns a TransactionWithSigner object ready to be passed to an
78
+ * AtomicTransactionComposer's addTransaction method.
79
+ * @param transaction One of: A TransactionWithSigner object (returned as is), a TransactionToSign object (signer is obtained from the
80
+ * signer property), a Transaction object (signer is extracted from the defaultSender parameter), an async SendTransactionResult returned by
81
+ * one of algokit utils' helpers (signer is obtained from the defaultSender parameter)
82
+ * @param defaultSender The default sender to be used to obtain a signer where the object provided to the transaction parameter does not
83
+ * include a signer.
84
+ * @returns A TransactionWithSigner object.
85
+ */
104
86
  const getTransactionWithSigner = async (transaction, defaultSender) => {
105
- if ('txn' in transaction)
106
- return transaction;
107
- if (defaultSender === undefined)
108
- throw new Error('Default sender must be provided when passing in a transaction object that does not contain its own signer');
109
- return transaction instanceof Promise
110
- ? {
111
- txn: (await transaction).transaction,
112
- signer: getSenderTransactionSigner(defaultSender),
113
- }
114
- : 'transaction' in transaction
115
- ? {
116
- txn: transaction.transaction,
117
- signer: getSenderTransactionSigner(transaction.signer),
118
- }
119
- : {
120
- txn: transaction,
121
- signer: getSenderTransactionSigner(defaultSender),
122
- };
87
+ if ("txn" in transaction) return transaction;
88
+ if (defaultSender === void 0) throw new Error("Default sender must be provided when passing in a transaction object that does not contain its own signer");
89
+ return transaction instanceof Promise ? {
90
+ txn: (await transaction).transaction,
91
+ signer: getSenderTransactionSigner(defaultSender)
92
+ } : "transaction" in transaction ? {
93
+ txn: transaction.transaction,
94
+ signer: getSenderTransactionSigner(transaction.signer)
95
+ } : {
96
+ txn: transaction,
97
+ signer: getSenderTransactionSigner(defaultSender)
98
+ };
123
99
  };
124
100
  const memoize = (fn) => {
125
- const cache = new Map();
126
- const cached = function (val) {
127
- return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val);
128
- };
129
- cached.cache = cache;
130
- return cached;
101
+ const cache = /* @__PURE__ */ new Map();
102
+ const cached = function(val) {
103
+ return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val);
104
+ };
105
+ cached.cache = cache;
106
+ return cached;
131
107
  };
132
108
  /**
133
- * @deprecated Use `TransactionSignerAccount` instead of `SendTransactionFrom` or use
134
- * `algosdk.makeBasicAccountTransactionSigner` / `algosdk.makeLogicSigAccountTransactionSigner`.
135
- *
136
- * Returns a `TransactionSigner` for the given transaction sender.
137
- * This function has memoization, so will return the same transaction signer for a given sender.
138
- * @param sender A transaction sender
139
- * @returns A transaction signer
140
- */
141
- const getSenderTransactionSigner = memoize(function (sender) {
142
- return 'signer' in sender
143
- ? sender.signer
144
- : 'lsig' in sender
145
- ? algosdk.makeLogicSigAccountTransactionSigner(sender)
146
- : algosdk.makeBasicAccountTransactionSigner(sender);
109
+ * @deprecated Use `TransactionSignerAccount` instead of `SendTransactionFrom` or use
110
+ * `algosdk.makeBasicAccountTransactionSigner` / `algosdk.makeLogicSigAccountTransactionSigner`.
111
+ *
112
+ * Returns a `TransactionSigner` for the given transaction sender.
113
+ * This function has memoization, so will return the same transaction signer for a given sender.
114
+ * @param sender A transaction sender
115
+ * @returns A transaction signer
116
+ */
117
+ const getSenderTransactionSigner = memoize(function(sender) {
118
+ return "signer" in sender ? sender.signer : "lsig" in sender ? algosdk.makeLogicSigAccountTransactionSigner(sender) : algosdk.makeBasicAccountTransactionSigner(sender);
147
119
  });
148
120
  /**
149
- * @deprecated Use `AlgorandClient` / `TransactionComposer` to sign transactions
150
- * or use the relevant underlying `account.signTxn` / `algosdk.signLogicSigTransactionObject`
151
- * / `multiSigAccount.sign` / `TransactionSigner` methods directly.
152
- *
153
- * Signs a single transaction by the given signer.
154
- * @param transaction The transaction to sign
155
- * @param signer The signer to sign
156
- * @returns The signed transaction as a `Uint8Array`
157
- */
121
+ * @deprecated Use `AlgorandClient` / `TransactionComposer` to sign transactions
122
+ * or use the relevant underlying `account.signTxn` / `algosdk.signLogicSigTransactionObject`
123
+ * / `multiSigAccount.sign` / `TransactionSigner` methods directly.
124
+ *
125
+ * Signs a single transaction by the given signer.
126
+ * @param transaction The transaction to sign
127
+ * @param signer The signer to sign
128
+ * @returns The signed transaction as a `Uint8Array`
129
+ */
158
130
  const signTransaction = async (transaction, signer) => {
159
- return 'sk' in signer
160
- ? transaction.signTxn(signer.sk)
161
- : 'lsig' in signer
162
- ? algosdk.signLogicSigTransactionObject(transaction, signer).blob
163
- : 'sign' in signer
164
- ? signer.sign(transaction)
165
- : (await signer.signer([transaction], [0]))[0];
131
+ return "sk" in signer ? transaction.signTxn(signer.sk) : "lsig" in signer ? algosdk.signLogicSigTransactionObject(transaction, signer).blob : "sign" in signer ? signer.sign(transaction) : (await signer.signer([transaction], [0]))[0];
166
132
  };
167
133
  /**
168
- * @deprecated Use `AlgorandClient` / `TransactionComposer` to send transactions.
169
- *
170
- * Prepares a transaction for sending and then (if instructed) signs and sends the given transaction to the chain.
171
- *
172
- * @param send The details for the transaction to prepare/send, including:
173
- * * `transaction`: The unsigned transaction
174
- * * `from`: The account to sign the transaction with: either an account with private key loaded or a logic signature account
175
- * * `config`: The sending configuration for this transaction
176
- * @param algod An algod client
177
- *
178
- * @returns An object with transaction (`transaction`) and (if `skipWaiting` is `false` or `undefined`) confirmation (`confirmation`)
179
- */
180
- const sendTransaction = async function (send, algod) {
181
- const { transaction, from, sendParams } = send;
182
- const { skipSending, skipWaiting, fee, maxFee, suppressLog, maxRoundsToWaitForConfirmation, atc } = sendParams ?? {};
183
- controlFees(transaction, { fee, maxFee });
184
- if (atc) {
185
- atc.addTransaction({ txn: transaction, signer: getSenderTransactionSigner(from) });
186
- return { transaction };
187
- }
188
- if (skipSending) {
189
- return { transaction };
190
- }
191
- let txnToSend = transaction;
192
- const populateAppCallResources = sendParams?.populateAppCallResources ?? Config.populateAppCallResources;
193
- // Populate resources if the transaction is an appcall and populateAppCallResources wasn't explicitly set to false
194
- if (txnToSend.type === algosdk.TransactionType.appl && populateAppCallResources) {
195
- const newAtc = new AtomicTransactionComposer();
196
- newAtc.addTransaction({ txn: txnToSend, signer: getSenderTransactionSigner(from) });
197
- const atc = await prepareGroupForSending(newAtc, algod, { ...sendParams, populateAppCallResources });
198
- txnToSend = atc.buildGroup()[0].txn;
199
- }
200
- const signedTransaction = await signTransaction(txnToSend, from);
201
- await algod.sendRawTransaction(signedTransaction).do();
202
- Config.getLogger(suppressLog).verbose(`Sent transaction ID ${txnToSend.txID()} ${txnToSend.type} from ${getSenderAddress(from)}`);
203
- let confirmation = undefined;
204
- if (!skipWaiting) {
205
- confirmation = await waitForConfirmation(txnToSend.txID(), maxRoundsToWaitForConfirmation ?? 5, algod);
206
- }
207
- return { transaction: txnToSend, confirmation };
134
+ * @deprecated Use `AlgorandClient` / `TransactionComposer` to send transactions.
135
+ *
136
+ * Prepares a transaction for sending and then (if instructed) signs and sends the given transaction to the chain.
137
+ *
138
+ * @param send The details for the transaction to prepare/send, including:
139
+ * * `transaction`: The unsigned transaction
140
+ * * `from`: The account to sign the transaction with: either an account with private key loaded or a logic signature account
141
+ * * `config`: The sending configuration for this transaction
142
+ * @param algod An algod client
143
+ *
144
+ * @returns An object with transaction (`transaction`) and (if `skipWaiting` is `false` or `undefined`) confirmation (`confirmation`)
145
+ */
146
+ const sendTransaction = async function(send, algod) {
147
+ const { transaction, from, sendParams } = send;
148
+ const { skipSending, skipWaiting, fee, maxFee, suppressLog, maxRoundsToWaitForConfirmation, atc } = sendParams ?? {};
149
+ controlFees(transaction, {
150
+ fee,
151
+ maxFee
152
+ });
153
+ if (atc) {
154
+ atc.addTransaction({
155
+ txn: transaction,
156
+ signer: getSenderTransactionSigner(from)
157
+ });
158
+ return { transaction };
159
+ }
160
+ if (skipSending) return { transaction };
161
+ let txnToSend = transaction;
162
+ const populateAppCallResources = sendParams?.populateAppCallResources ?? Config.populateAppCallResources;
163
+ if (txnToSend.type === algosdk.TransactionType.appl && populateAppCallResources) {
164
+ const newAtc = new AtomicTransactionComposer();
165
+ newAtc.addTransaction({
166
+ txn: txnToSend,
167
+ signer: getSenderTransactionSigner(from)
168
+ });
169
+ txnToSend = (await prepareGroupForSending(newAtc, algod, {
170
+ ...sendParams,
171
+ populateAppCallResources
172
+ })).buildGroup()[0].txn;
173
+ }
174
+ const signedTransaction = await signTransaction(txnToSend, from);
175
+ await algod.sendRawTransaction(signedTransaction).do();
176
+ Config.getLogger(suppressLog).verbose(`Sent transaction ID ${txnToSend.txID()} ${txnToSend.type} from ${getSenderAddress(from)}`);
177
+ let confirmation = void 0;
178
+ if (!skipWaiting) confirmation = await waitForConfirmation(txnToSend.txID(), maxRoundsToWaitForConfirmation ?? 5, algod);
179
+ return {
180
+ transaction: txnToSend,
181
+ confirmation
182
+ };
208
183
  };
209
184
  /**
210
- * Get the execution info of a transaction group for the given ATC
211
- * The function uses the simulate endpoint and depending on the sendParams can return the following:
212
- * - The unnamed resources accessed by the group
213
- * - The unnamed resources accessed by each transaction in the group
214
- * - The required fee delta for each transaction in the group. A positive value indicates a fee deficit, a negative value indicates a surplus.
215
- *
216
- * @param atc The ATC containing the txn group
217
- * @param algod The algod client to use for the simulation
218
- * @param sendParams The send params for the transaction group
219
- * @param additionalAtcContext Additional ATC context used to determine how best to alter transactions in the group
220
- * @returns The execution info for the group
221
- */
185
+ * Get the execution info of a transaction group for the given ATC
186
+ * The function uses the simulate endpoint and depending on the sendParams can return the following:
187
+ * - The unnamed resources accessed by the group
188
+ * - The unnamed resources accessed by each transaction in the group
189
+ * - The required fee delta for each transaction in the group. A positive value indicates a fee deficit, a negative value indicates a surplus.
190
+ *
191
+ * @param atc The ATC containing the txn group
192
+ * @param algod The algod client to use for the simulation
193
+ * @param sendParams The send params for the transaction group
194
+ * @param additionalAtcContext Additional ATC context used to determine how best to alter transactions in the group
195
+ * @returns The execution info for the group
196
+ */
222
197
  async function getGroupExecutionInfo(atc, algod, sendParams, additionalAtcContext) {
223
- const simulateRequest = new algosdk.modelsv2.SimulateRequest({
224
- txnGroups: [],
225
- allowUnnamedResources: true,
226
- allowEmptySignatures: true,
227
- fixSigners: true,
228
- });
229
- const nullSigner = algosdk.makeEmptyTransactionSigner();
230
- const emptySignerAtc = atc.clone();
231
- const appCallIndexesWithoutMaxFees = [];
232
- emptySignerAtc['transactions'].forEach((t, i) => {
233
- t.signer = nullSigner;
234
- if (sendParams.coverAppCallInnerTransactionFees && t.txn.type === TransactionType.appl) {
235
- if (!additionalAtcContext?.suggestedParams) {
236
- throw Error(`Please provide additionalAtcContext.suggestedParams when coverAppCallInnerTransactionFees is enabled`);
237
- }
238
- const maxFee = additionalAtcContext?.maxFees?.get(i)?.microAlgo;
239
- if (maxFee === undefined) {
240
- appCallIndexesWithoutMaxFees.push(i);
241
- }
242
- else {
243
- t.txn.fee = maxFee;
244
- }
245
- }
246
- });
247
- if (sendParams.coverAppCallInnerTransactionFees && appCallIndexesWithoutMaxFees.length > 0) {
248
- throw Error(`Please provide a maxFee for each app call transaction when coverAppCallInnerTransactionFees is enabled. Required for transaction ${appCallIndexesWithoutMaxFees.join(', ')}`);
249
- }
250
- const perByteTxnFee = BigInt(additionalAtcContext?.suggestedParams.fee ?? 0n);
251
- const minTxnFee = BigInt(additionalAtcContext?.suggestedParams.minFee ?? 1000n);
252
- const result = await emptySignerAtc.simulate(algod, simulateRequest);
253
- const groupResponse = result.simulateResponse.txnGroups[0];
254
- if (groupResponse.failureMessage) {
255
- if (sendParams.coverAppCallInnerTransactionFees && groupResponse.failureMessage.match(/fee too small/)) {
256
- throw Error(`Fees were too small to resolve execution info via simulate. You may need to increase an app call transaction maxFee.`);
257
- }
258
- throw Error(`Error resolving execution info via simulate in transaction ${groupResponse.failedAt}: ${groupResponse.failureMessage}`);
259
- }
260
- const sortedResources = groupResponse.unnamedResourcesAccessed;
261
- // NOTE: We explicitly want to avoid localeCompare as that can lead to different results in different environments
262
- const compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
263
- if (sortedResources) {
264
- sortedResources.accounts?.sort((a, b) => compare(a.toString(), b.toString()));
265
- sortedResources.assets?.sort(compare);
266
- sortedResources.apps?.sort(compare);
267
- sortedResources.boxes?.sort((a, b) => {
268
- const aStr = `${a.app}-${a.name}`;
269
- const bStr = `${b.app}-${b.name}`;
270
- return compare(aStr, bStr);
271
- });
272
- sortedResources.appLocals?.sort((a, b) => {
273
- const aStr = `${a.app}-${a.account}`;
274
- const bStr = `${b.app}-${b.account}`;
275
- return compare(aStr, bStr);
276
- });
277
- sortedResources.assetHoldings?.sort((a, b) => {
278
- const aStr = `${a.asset}-${a.account}`;
279
- const bStr = `${b.asset}-${b.account}`;
280
- return compare(aStr, bStr);
281
- });
282
- }
283
- return {
284
- groupUnnamedResourcesAccessed: sendParams.populateAppCallResources ? sortedResources : undefined,
285
- txns: groupResponse.txnResults.map((txn, i) => {
286
- const originalTxn = atc['transactions'][i].txn;
287
- let requiredFeeDelta = 0n;
288
- if (sendParams.coverAppCallInnerTransactionFees) {
289
- // Min fee calc is lifted from algosdk https://github.com/algorand/js-algorand-sdk/blob/6973ff583b243ddb0632e91f4c0383021430a789/src/transaction.ts#L710
290
- // 75 is the number of bytes added to a txn after signing it
291
- const parentPerByteFee = perByteTxnFee * BigInt(originalTxn.toByte().length + 75);
292
- const parentMinFee = parentPerByteFee < minTxnFee ? minTxnFee : parentPerByteFee;
293
- const parentFeeDelta = parentMinFee - originalTxn.fee;
294
- if (originalTxn.type === TransactionType.appl) {
295
- const calculateInnerFeeDelta = (itxns, acc = 0n) => {
296
- // Surplus inner transaction fees do not pool up to the parent transaction.
297
- // Additionally surplus inner transaction fees only pool from sibling transactions that are sent prior to a given inner transaction, hence why we iterate in reverse order.
298
- return itxns.reverse().reduce((acc, itxn) => {
299
- const currentFeeDelta = (itxn.innerTxns && itxn.innerTxns.length > 0 ? calculateInnerFeeDelta(itxn.innerTxns, acc) : acc) +
300
- (minTxnFee - itxn.txn.txn.fee); // Inner transactions don't require per byte fees
301
- return currentFeeDelta < 0n ? 0n : currentFeeDelta;
302
- }, acc);
303
- };
304
- const innerFeeDelta = calculateInnerFeeDelta(txn.txnResult.innerTxns ?? []);
305
- requiredFeeDelta = innerFeeDelta + parentFeeDelta;
306
- }
307
- else {
308
- requiredFeeDelta = parentFeeDelta;
309
- }
310
- }
311
- return {
312
- unnamedResourcesAccessed: sendParams.populateAppCallResources ? txn.unnamedResourcesAccessed : undefined,
313
- requiredFeeDelta,
314
- };
315
- }),
316
- };
198
+ const simulateRequest = new algosdk.modelsv2.SimulateRequest({
199
+ txnGroups: [],
200
+ allowUnnamedResources: true,
201
+ allowEmptySignatures: true,
202
+ fixSigners: true
203
+ });
204
+ const nullSigner = algosdk.makeEmptyTransactionSigner();
205
+ const emptySignerAtc = atc.clone();
206
+ const appCallIndexesWithoutMaxFees = [];
207
+ emptySignerAtc["transactions"].forEach((t, i) => {
208
+ t.signer = nullSigner;
209
+ if (sendParams.coverAppCallInnerTransactionFees && t.txn.type === TransactionType.appl) {
210
+ if (!additionalAtcContext?.suggestedParams) throw Error(`Please provide additionalAtcContext.suggestedParams when coverAppCallInnerTransactionFees is enabled`);
211
+ const maxFee = additionalAtcContext?.maxFees?.get(i)?.microAlgo;
212
+ if (maxFee === void 0) appCallIndexesWithoutMaxFees.push(i);
213
+ else t.txn.fee = maxFee;
214
+ }
215
+ });
216
+ if (sendParams.coverAppCallInnerTransactionFees && appCallIndexesWithoutMaxFees.length > 0) throw Error(`Please provide a maxFee for each app call transaction when coverAppCallInnerTransactionFees is enabled. Required for transaction ${appCallIndexesWithoutMaxFees.join(", ")}`);
217
+ const perByteTxnFee = BigInt(additionalAtcContext?.suggestedParams.fee ?? 0n);
218
+ const minTxnFee = BigInt(additionalAtcContext?.suggestedParams.minFee ?? 1000n);
219
+ const groupResponse = (await emptySignerAtc.simulate(algod, simulateRequest)).simulateResponse.txnGroups[0];
220
+ if (groupResponse.failureMessage) {
221
+ if (sendParams.coverAppCallInnerTransactionFees && groupResponse.failureMessage.match(/fee ([\w.]+\s+)?too small/)) throw Error(`Fees were too small to resolve execution info via simulate. You may need to increase an app call transaction maxFee.`);
222
+ throw Error(`Error resolving execution info via simulate in transaction ${groupResponse.failedAt}: ${groupResponse.failureMessage}`);
223
+ }
224
+ const sortedResources = groupResponse.unnamedResourcesAccessed;
225
+ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
226
+ if (sortedResources) {
227
+ sortedResources.accounts?.sort((a, b) => compare(a.toString(), b.toString()));
228
+ sortedResources.assets?.sort(compare);
229
+ sortedResources.apps?.sort(compare);
230
+ sortedResources.boxes?.sort((a, b) => {
231
+ const aStr = `${a.app}-${a.name}`;
232
+ const bStr = `${b.app}-${b.name}`;
233
+ return compare(aStr, bStr);
234
+ });
235
+ sortedResources.appLocals?.sort((a, b) => {
236
+ const aStr = `${a.app}-${a.account}`;
237
+ const bStr = `${b.app}-${b.account}`;
238
+ return compare(aStr, bStr);
239
+ });
240
+ sortedResources.assetHoldings?.sort((a, b) => {
241
+ const aStr = `${a.asset}-${a.account}`;
242
+ const bStr = `${b.asset}-${b.account}`;
243
+ return compare(aStr, bStr);
244
+ });
245
+ }
246
+ return {
247
+ groupUnnamedResourcesAccessed: sendParams.populateAppCallResources ? sortedResources : void 0,
248
+ txns: groupResponse.txnResults.map((txn, i) => {
249
+ const originalTxn = atc["transactions"][i].txn;
250
+ let requiredFeeDelta = 0n;
251
+ if (sendParams.coverAppCallInnerTransactionFees) {
252
+ const parentPerByteFee = perByteTxnFee * BigInt(originalTxn.toByte().length + 75);
253
+ const parentFeeDelta = (parentPerByteFee < minTxnFee ? minTxnFee : parentPerByteFee) - originalTxn.fee;
254
+ if (originalTxn.type === TransactionType.appl) {
255
+ const calculateInnerFeeDelta = (itxns, acc = 0n) => {
256
+ return itxns.reverse().reduce((acc, itxn) => {
257
+ const currentFeeDelta = (itxn.innerTxns && itxn.innerTxns.length > 0 ? calculateInnerFeeDelta(itxn.innerTxns, acc) : acc) + (minTxnFee - itxn.txn.txn.fee);
258
+ return currentFeeDelta < 0n ? 0n : currentFeeDelta;
259
+ }, acc);
260
+ };
261
+ requiredFeeDelta = calculateInnerFeeDelta(txn.txnResult.innerTxns ?? []) + parentFeeDelta;
262
+ } else requiredFeeDelta = parentFeeDelta;
263
+ }
264
+ return {
265
+ unnamedResourcesAccessed: sendParams.populateAppCallResources ? txn.unnamedResourcesAccessed : void 0,
266
+ requiredFeeDelta
267
+ };
268
+ })
269
+ };
317
270
  }
318
271
  /**
319
- * Take an existing Atomic Transaction Composer and return a new one with the required
320
- * app call resources populated into it
321
- *
322
- * @param algod The algod client to use for the simulation
323
- * @param atc The ATC containing the txn group
324
- * @returns A new ATC with the resources populated into the transactions
325
- *
326
- * @privateRemarks
327
- *
328
- * This entire function will eventually be implemented in simulate upstream in algod. The simulate endpoint will return
329
- * an array of refference arrays for each transaction, so this eventually will eventually just call simulate and set the
330
- * reference arrays in the transactions to the reference arrays returned by simulate.
331
- *
332
- * See https://github.com/algorand/go-algorand/pull/5684
333
- *
334
- */
272
+ * Take an existing Atomic Transaction Composer and return a new one with the required
273
+ * app call resources populated into it
274
+ *
275
+ * @param algod The algod client to use for the simulation
276
+ * @param atc The ATC containing the txn group
277
+ * @returns A new ATC with the resources populated into the transactions
278
+ *
279
+ * @privateRemarks
280
+ *
281
+ * This entire function will eventually be implemented in simulate upstream in algod. The simulate endpoint will return
282
+ * an array of refference arrays for each transaction, so this eventually will eventually just call simulate and set the
283
+ * reference arrays in the transactions to the reference arrays returned by simulate.
284
+ *
285
+ * See https://github.com/algorand/go-algorand/pull/5684
286
+ *
287
+ */
335
288
  async function populateAppCallResources(atc, algod) {
336
- return await prepareGroupForSending(atc, algod, { populateAppCallResources: true });
289
+ return await prepareGroupForSending(atc, algod, { populateAppCallResources: true });
337
290
  }
338
291
  /**
339
- * Take an existing Atomic Transaction Composer and return a new one with changes applied to the transactions
340
- * based on the supplied sendParams to prepare it for sending.
341
- * Please note, that before calling `.execute()` on the returned ATC, you must call `.buildGroup()`.
342
- *
343
- * @param algod The algod client to use for the simulation
344
- * @param atc The ATC containing the txn group
345
- * @param sendParams The send params for the transaction group
346
- * @param additionalAtcContext Additional ATC context used to determine how best to change the transactions in the group
347
- * @returns A new ATC with the changes applied
348
- *
349
- * @privateRemarks
350
- * Parts of this function will eventually be implemented in algod. Namely:
351
- * - Simulate will return information on how to populate reference arrays, see https://github.com/algorand/go-algorand/pull/6015
352
- */
292
+ * Take an existing Atomic Transaction Composer and return a new one with changes applied to the transactions
293
+ * based on the supplied sendParams to prepare it for sending.
294
+ * Please note, that before calling `.execute()` on the returned ATC, you must call `.buildGroup()`.
295
+ *
296
+ * @param algod The algod client to use for the simulation
297
+ * @param atc The ATC containing the txn group
298
+ * @param sendParams The send params for the transaction group
299
+ * @param additionalAtcContext Additional ATC context used to determine how best to change the transactions in the group
300
+ * @returns A new ATC with the changes applied
301
+ *
302
+ * @privateRemarks
303
+ * Parts of this function will eventually be implemented in algod. Namely:
304
+ * - Simulate will return information on how to populate reference arrays, see https://github.com/algorand/go-algorand/pull/6015
305
+ */
353
306
  async function prepareGroupForSending(atc, algod, sendParams, additionalAtcContext) {
354
- const executionInfo = await getGroupExecutionInfo(atc, algod, sendParams, additionalAtcContext);
355
- const group = atc.buildGroup();
356
- const [_, additionalTransactionFees] = sendParams.coverAppCallInnerTransactionFees
357
- ? executionInfo.txns
358
- .map((txn, i) => {
359
- const groupIndex = i;
360
- const txnInGroup = group[groupIndex].txn;
361
- const maxFee = additionalAtcContext?.maxFees?.get(i)?.microAlgo;
362
- const immutableFee = maxFee !== undefined && maxFee === txnInGroup.fee;
363
- // Because we don't alter non app call transaction, they take priority
364
- const priorityMultiplier = txn.requiredFeeDelta > 0n && (immutableFee || txnInGroup.type !== algosdk.TransactionType.appl) ? 1000n : 1n;
365
- return {
366
- ...txn,
367
- groupIndex,
368
- // Measures the priority level of covering the transaction fee using the surplus group fees. The higher the number, the higher the priority.
369
- surplusFeePriorityLevel: txn.requiredFeeDelta > 0n ? txn.requiredFeeDelta * priorityMultiplier : -1n,
370
- };
371
- })
372
- .sort((a, b) => {
373
- return a.surplusFeePriorityLevel > b.surplusFeePriorityLevel ? -1 : a.surplusFeePriorityLevel < b.surplusFeePriorityLevel ? 1 : 0;
374
- })
375
- .reduce((acc, { groupIndex, requiredFeeDelta }) => {
376
- if (requiredFeeDelta > 0n) {
377
- // There is a fee deficit on the transaction
378
- let surplusGroupFees = acc[0];
379
- const additionalTransactionFees = acc[1];
380
- const additionalFeeDelta = requiredFeeDelta - surplusGroupFees;
381
- if (additionalFeeDelta <= 0n) {
382
- // The surplus group fees fully cover the required fee delta
383
- surplusGroupFees = -additionalFeeDelta;
384
- }
385
- else {
386
- // The surplus group fees do not fully cover the required fee delta, use what is available
387
- additionalTransactionFees.set(groupIndex, additionalFeeDelta);
388
- surplusGroupFees = 0n;
389
- }
390
- return [surplusGroupFees, additionalTransactionFees];
391
- }
392
- return acc;
393
- }, [
394
- executionInfo.txns.reduce((acc, { requiredFeeDelta }) => {
395
- if (requiredFeeDelta < 0n) {
396
- return acc + -requiredFeeDelta;
397
- }
398
- return acc;
399
- }, 0n),
400
- new Map(),
401
- ])
402
- : [0n, new Map()];
403
- const appCallHasAccessReferences = (txn) => {
404
- return txn.type === TransactionType.appl && txn.applicationCall?.access && txn.applicationCall?.access.length > 0;
405
- };
406
- const indexesWithAccessReferences = [];
407
- executionInfo.txns.forEach(({ unnamedResourcesAccessed: r }, i) => {
408
- // Populate Transaction App Call Resources
409
- if (sendParams.populateAppCallResources && group[i].txn.type === TransactionType.appl) {
410
- const hasAccessReferences = appCallHasAccessReferences(group[i].txn);
411
- if (hasAccessReferences && (r || executionInfo.groupUnnamedResourcesAccessed)) {
412
- indexesWithAccessReferences.push(i);
413
- }
414
- if (r && !hasAccessReferences) {
415
- if (r.boxes || r.extraBoxRefs)
416
- throw Error('Unexpected boxes at the transaction level');
417
- if (r.appLocals)
418
- throw Error('Unexpected app local at the transaction level');
419
- if (r.assetHoldings)
420
- throw Error('Unexpected asset holding at the transaction level');
421
- group[i].txn['applicationCall'] = {
422
- ...group[i].txn.applicationCall,
423
- accounts: [...(group[i].txn?.applicationCall?.accounts ?? []), ...(r.accounts ?? [])],
424
- foreignApps: [...(group[i].txn?.applicationCall?.foreignApps ?? []), ...(r.apps ?? [])],
425
- foreignAssets: [...(group[i].txn?.applicationCall?.foreignAssets ?? []), ...(r.assets ?? [])],
426
- boxes: [...(group[i].txn?.applicationCall?.boxes ?? []), ...(r.boxes ?? [])],
427
- };
428
- const accounts = group[i].txn.applicationCall?.accounts?.length ?? 0;
429
- if (accounts > MAX_APP_CALL_ACCOUNT_REFERENCES)
430
- throw Error(`Account reference limit of ${MAX_APP_CALL_ACCOUNT_REFERENCES} exceeded in transaction ${i}`);
431
- const assets = group[i].txn.applicationCall?.foreignAssets?.length ?? 0;
432
- const apps = group[i].txn.applicationCall?.foreignApps?.length ?? 0;
433
- const boxes = group[i].txn.applicationCall?.boxes?.length ?? 0;
434
- if (accounts + assets + apps + boxes > MAX_APP_CALL_FOREIGN_REFERENCES) {
435
- throw Error(`Resource reference limit of ${MAX_APP_CALL_FOREIGN_REFERENCES} exceeded in transaction ${i}`);
436
- }
437
- }
438
- }
439
- // Cover App Call Inner Transaction Fees
440
- if (sendParams.coverAppCallInnerTransactionFees) {
441
- const additionalTransactionFee = additionalTransactionFees.get(i);
442
- if (additionalTransactionFee !== undefined) {
443
- if (group[i].txn.type !== algosdk.TransactionType.appl) {
444
- throw Error(`An additional fee of ${additionalTransactionFee} µALGO is required for non app call transaction ${i}`);
445
- }
446
- const transactionFee = group[i].txn.fee + additionalTransactionFee;
447
- const maxFee = additionalAtcContext?.maxFees?.get(i)?.microAlgo;
448
- if (maxFee === undefined || transactionFee > maxFee) {
449
- throw Error(`Calculated transaction fee ${transactionFee} µALGO is greater than max of ${maxFee ?? 'undefined'} for transaction ${i}`);
450
- }
451
- group[i].txn.fee = transactionFee;
452
- }
453
- }
454
- });
455
- // Populate Group App Call Resources
456
- if (sendParams.populateAppCallResources) {
457
- if (indexesWithAccessReferences.length > 0) {
458
- Config.logger.warn(`Resource population will be skipped for transaction indexes ${indexesWithAccessReferences.join(', ')} as they use access references.`);
459
- }
460
- const populateGroupResource = (txns, reference, type) => {
461
- const isApplBelowLimit = (t) => {
462
- if (t.txn.type !== algosdk.TransactionType.appl)
463
- return false;
464
- if (appCallHasAccessReferences(t.txn))
465
- return false;
466
- const accounts = t.txn.applicationCall?.accounts?.length ?? 0;
467
- const assets = t.txn.applicationCall?.foreignAssets?.length ?? 0;
468
- const apps = t.txn.applicationCall?.foreignApps?.length ?? 0;
469
- const boxes = t.txn.applicationCall?.boxes?.length ?? 0;
470
- return accounts + assets + apps + boxes < MAX_APP_CALL_FOREIGN_REFERENCES;
471
- };
472
- // If this is a asset holding or app local, first try to find a transaction that already has the account available
473
- if (type === 'assetHolding' || type === 'appLocal') {
474
- const { account } = reference;
475
- let txnIndex = txns.findIndex((t) => {
476
- if (!isApplBelowLimit(t))
477
- return false;
478
- return (
479
- // account is in the foreign accounts array
480
- t.txn.applicationCall?.accounts?.map((a) => a.toString()).includes(account.toString()) ||
481
- // account is available as an app account
482
- t.txn.applicationCall?.foreignApps?.map((a) => algosdk.getApplicationAddress(a).toString()).includes(account.toString()) ||
483
- // account is available since it's in one of the fields
484
- Object.values(t.txn).some((f) => stringifyJSON(f, (_, v) => (v instanceof Address ? v.toString() : v))?.includes(account.toString())));
485
- });
486
- if (txnIndex > -1) {
487
- if (type === 'assetHolding') {
488
- const { asset } = reference;
489
- txns[txnIndex].txn['applicationCall'] = {
490
- ...txns[txnIndex].txn.applicationCall,
491
- foreignAssets: [...(txns[txnIndex].txn?.applicationCall?.foreignAssets ?? []), ...[asset]],
492
- };
493
- }
494
- else {
495
- const { app } = reference;
496
- txns[txnIndex].txn['applicationCall'] = {
497
- ...txns[txnIndex].txn.applicationCall,
498
- foreignApps: [...(txns[txnIndex].txn?.applicationCall?.foreignApps ?? []), ...[app]],
499
- };
500
- }
501
- return;
502
- }
503
- // Now try to find a txn that already has that app or asset available
504
- txnIndex = txns.findIndex((t) => {
505
- if (!isApplBelowLimit(t))
506
- return false;
507
- // check if there is space in the accounts array
508
- if ((t.txn.applicationCall?.accounts?.length ?? 0) >= MAX_APP_CALL_ACCOUNT_REFERENCES)
509
- return false;
510
- if (type === 'assetHolding') {
511
- const { asset } = reference;
512
- return t.txn.applicationCall?.foreignAssets?.includes(asset);
513
- }
514
- else {
515
- const { app } = reference;
516
- return t.txn.applicationCall?.foreignApps?.includes(app) || t.txn.applicationCall?.appIndex === app;
517
- }
518
- });
519
- if (txnIndex > -1) {
520
- const { account } = reference;
521
- txns[txnIndex].txn['applicationCall'] = {
522
- ...txns[txnIndex].txn.applicationCall,
523
- accounts: [...(txns[txnIndex].txn?.applicationCall?.accounts ?? []), ...[account]],
524
- };
525
- return;
526
- }
527
- }
528
- // If this is a box, first try to find a transaction that already has the app available
529
- if (type === 'box') {
530
- const { app, name } = reference;
531
- const txnIndex = txns.findIndex((t) => {
532
- if (!isApplBelowLimit(t))
533
- return false;
534
- // If the app is in the foreign array OR the app being called, then we know it's available
535
- return t.txn.applicationCall?.foreignApps?.includes(app) || t.txn.applicationCall?.appIndex === app;
536
- });
537
- if (txnIndex > -1) {
538
- txns[txnIndex].txn['applicationCall'] = {
539
- ...txns[txnIndex].txn.applicationCall,
540
- boxes: [...(txns[txnIndex].txn?.applicationCall?.boxes ?? []), ...[{ appIndex: app, name }]],
541
- };
542
- return;
543
- }
544
- }
545
- // Find the txn index to put the reference(s)
546
- const txnIndex = txns.findIndex((t) => {
547
- if (t.txn.type !== algosdk.TransactionType.appl)
548
- return false;
549
- if (appCallHasAccessReferences(t.txn))
550
- return false;
551
- const accounts = t.txn.applicationCall?.accounts?.length ?? 0;
552
- const assets = t.txn.applicationCall?.foreignAssets?.length ?? 0;
553
- const apps = t.txn.applicationCall?.foreignApps?.length ?? 0;
554
- const boxes = t.txn.applicationCall?.boxes?.length ?? 0;
555
- if (type === 'account')
556
- return accounts < MAX_APP_CALL_ACCOUNT_REFERENCES && accounts + assets + apps + boxes < MAX_APP_CALL_FOREIGN_REFERENCES;
557
- // If we're adding local state or asset holding, we need space for the acocunt and the other reference
558
- if (type === 'assetHolding' || type === 'appLocal') {
559
- return accounts + assets + apps + boxes < MAX_APP_CALL_FOREIGN_REFERENCES - 1 && accounts < MAX_APP_CALL_ACCOUNT_REFERENCES;
560
- }
561
- // If we're adding a box, we need space for both the box ref and the app ref
562
- if (type === 'box' && BigInt(reference.app) !== BigInt(0)) {
563
- return accounts + assets + apps + boxes < MAX_APP_CALL_FOREIGN_REFERENCES - 1;
564
- }
565
- return accounts + assets + apps + boxes < MAX_APP_CALL_FOREIGN_REFERENCES;
566
- });
567
- if (txnIndex === -1) {
568
- throw Error('No more transactions below reference limit. Add another app call to the group.');
569
- }
570
- if (type === 'account') {
571
- txns[txnIndex].txn['applicationCall'] = {
572
- ...txns[txnIndex].txn.applicationCall,
573
- accounts: [...(txns[txnIndex].txn?.applicationCall?.accounts ?? []), ...[reference]],
574
- };
575
- }
576
- else if (type === 'app') {
577
- txns[txnIndex].txn['applicationCall'] = {
578
- ...txns[txnIndex].txn.applicationCall,
579
- foreignApps: [
580
- ...(txns[txnIndex].txn?.applicationCall?.foreignApps ?? []),
581
- ...[typeof reference === 'bigint' ? reference : BigInt(reference)],
582
- ],
583
- };
584
- }
585
- else if (type === 'box') {
586
- const { app, name } = reference;
587
- txns[txnIndex].txn['applicationCall'] = {
588
- ...txns[txnIndex].txn.applicationCall,
589
- boxes: [...(txns[txnIndex].txn?.applicationCall?.boxes ?? []), ...[{ appIndex: app, name }]],
590
- };
591
- if (app.toString() !== '0') {
592
- txns[txnIndex].txn['applicationCall'] = {
593
- ...txns[txnIndex].txn.applicationCall,
594
- foreignApps: [...(txns[txnIndex].txn?.applicationCall?.foreignApps ?? []), ...[app]],
595
- };
596
- }
597
- }
598
- else if (type === 'assetHolding') {
599
- const { asset, account } = reference;
600
- txns[txnIndex].txn['applicationCall'] = {
601
- ...txns[txnIndex].txn.applicationCall,
602
- foreignAssets: [...(txns[txnIndex].txn?.applicationCall?.foreignAssets ?? []), ...[asset]],
603
- accounts: [...(txns[txnIndex].txn?.applicationCall?.accounts ?? []), ...[account]],
604
- };
605
- }
606
- else if (type === 'appLocal') {
607
- const { app, account } = reference;
608
- txns[txnIndex].txn['applicationCall'] = {
609
- ...txns[txnIndex].txn.applicationCall,
610
- foreignApps: [...(txns[txnIndex].txn?.applicationCall?.foreignApps ?? []), ...[app]],
611
- accounts: [...(txns[txnIndex].txn?.applicationCall?.accounts ?? []), ...[account]],
612
- };
613
- }
614
- else if (type === 'asset') {
615
- txns[txnIndex].txn['applicationCall'] = {
616
- ...txns[txnIndex].txn.applicationCall,
617
- foreignAssets: [
618
- ...(txns[txnIndex].txn?.applicationCall?.foreignAssets ?? []),
619
- ...[typeof reference === 'bigint' ? reference : BigInt(reference)],
620
- ],
621
- };
622
- }
623
- };
624
- const g = executionInfo.groupUnnamedResourcesAccessed;
625
- if (g) {
626
- // Do cross-reference resources first because they are the most restrictive in terms
627
- // of which transactions can be used
628
- g.appLocals?.forEach((a) => {
629
- populateGroupResource(group, a, 'appLocal');
630
- // Remove resources from the group if we're adding them here
631
- g.accounts = g.accounts?.filter((acc) => acc !== a.account);
632
- g.apps = g.apps?.filter((app) => BigInt(app) !== BigInt(a.app));
633
- });
634
- g.assetHoldings?.forEach((a) => {
635
- populateGroupResource(group, a, 'assetHolding');
636
- // Remove resources from the group if we're adding them here
637
- g.accounts = g.accounts?.filter((acc) => acc !== a.account);
638
- g.assets = g.assets?.filter((asset) => BigInt(asset) !== BigInt(a.asset));
639
- });
640
- // Do accounts next because the account limit is 4
641
- g.accounts?.forEach((a) => {
642
- populateGroupResource(group, a, 'account');
643
- });
644
- g.boxes?.forEach((b) => {
645
- populateGroupResource(group, b, 'box');
646
- // Remove apps as resource from the group if we're adding it here
647
- g.apps = g.apps?.filter((app) => BigInt(app) !== BigInt(b.app));
648
- });
649
- g.assets?.forEach((a) => {
650
- populateGroupResource(group, a, 'asset');
651
- });
652
- g.apps?.forEach((a) => {
653
- populateGroupResource(group, a, 'app');
654
- });
655
- if (g.extraBoxRefs) {
656
- for (let i = 0; i < g.extraBoxRefs; i += 1) {
657
- const ref = new algosdk.modelsv2.BoxReference({ app: 0, name: new Uint8Array(0) });
658
- populateGroupResource(group, ref, 'box');
659
- }
660
- }
661
- }
662
- }
663
- const newAtc = new algosdk.AtomicTransactionComposer();
664
- group.forEach((t) => {
665
- t.txn.group = undefined;
666
- newAtc.addTransaction(t);
667
- });
668
- newAtc['methodCalls'] = atc['methodCalls'];
669
- return newAtc;
307
+ const executionInfo = await getGroupExecutionInfo(atc, algod, sendParams, additionalAtcContext);
308
+ const group = atc.buildGroup();
309
+ const [_, additionalTransactionFees] = sendParams.coverAppCallInnerTransactionFees ? executionInfo.txns.map((txn, i) => {
310
+ const groupIndex = i;
311
+ const txnInGroup = group[groupIndex].txn;
312
+ const maxFee = additionalAtcContext?.maxFees?.get(i)?.microAlgo;
313
+ const priorityMultiplier = txn.requiredFeeDelta > 0n && (maxFee !== void 0 && maxFee === txnInGroup.fee || txnInGroup.type !== algosdk.TransactionType.appl) ? 1000n : 1n;
314
+ return {
315
+ ...txn,
316
+ groupIndex,
317
+ surplusFeePriorityLevel: txn.requiredFeeDelta > 0n ? txn.requiredFeeDelta * priorityMultiplier : -1n
318
+ };
319
+ }).sort((a, b) => {
320
+ return a.surplusFeePriorityLevel > b.surplusFeePriorityLevel ? -1 : a.surplusFeePriorityLevel < b.surplusFeePriorityLevel ? 1 : 0;
321
+ }).reduce((acc, { groupIndex, requiredFeeDelta }) => {
322
+ if (requiredFeeDelta > 0n) {
323
+ let surplusGroupFees = acc[0];
324
+ const additionalTransactionFees = acc[1];
325
+ const additionalFeeDelta = requiredFeeDelta - surplusGroupFees;
326
+ if (additionalFeeDelta <= 0n) surplusGroupFees = -additionalFeeDelta;
327
+ else {
328
+ additionalTransactionFees.set(groupIndex, additionalFeeDelta);
329
+ surplusGroupFees = 0n;
330
+ }
331
+ return [surplusGroupFees, additionalTransactionFees];
332
+ }
333
+ return acc;
334
+ }, [executionInfo.txns.reduce((acc, { requiredFeeDelta }) => {
335
+ if (requiredFeeDelta < 0n) return acc + -requiredFeeDelta;
336
+ return acc;
337
+ }, 0n), /* @__PURE__ */ new Map()]) : [0n, /* @__PURE__ */ new Map()];
338
+ const appCallHasAccessReferences = (txn) => {
339
+ return txn.type === TransactionType.appl && txn.applicationCall?.access && txn.applicationCall?.access.length > 0;
340
+ };
341
+ const indexesWithAccessReferences = [];
342
+ executionInfo.txns.forEach(({ unnamedResourcesAccessed: r }, i) => {
343
+ if (sendParams.populateAppCallResources && group[i].txn.type === TransactionType.appl) {
344
+ const hasAccessReferences = appCallHasAccessReferences(group[i].txn);
345
+ if (hasAccessReferences && (r || executionInfo.groupUnnamedResourcesAccessed)) indexesWithAccessReferences.push(i);
346
+ if (r && !hasAccessReferences) {
347
+ if (r.boxes || r.extraBoxRefs) throw Error("Unexpected boxes at the transaction level");
348
+ if (r.appLocals) throw Error("Unexpected app local at the transaction level");
349
+ if (r.assetHoldings) throw Error("Unexpected asset holding at the transaction level");
350
+ group[i].txn["applicationCall"] = {
351
+ ...group[i].txn.applicationCall,
352
+ accounts: [...group[i].txn?.applicationCall?.accounts ?? [], ...r.accounts ?? []],
353
+ foreignApps: [...group[i].txn?.applicationCall?.foreignApps ?? [], ...r.apps ?? []],
354
+ foreignAssets: [...group[i].txn?.applicationCall?.foreignAssets ?? [], ...r.assets ?? []],
355
+ boxes: [...group[i].txn?.applicationCall?.boxes ?? [], ...r.boxes ?? []]
356
+ };
357
+ const accounts = group[i].txn.applicationCall?.accounts?.length ?? 0;
358
+ if (accounts > 8) throw Error(`Account reference limit of 8 exceeded in transaction ${i}`);
359
+ const assets = group[i].txn.applicationCall?.foreignAssets?.length ?? 0;
360
+ const apps = group[i].txn.applicationCall?.foreignApps?.length ?? 0;
361
+ const boxes = group[i].txn.applicationCall?.boxes?.length ?? 0;
362
+ if (accounts + assets + apps + boxes > 8) throw Error(`Resource reference limit of 8 exceeded in transaction ${i}`);
363
+ }
364
+ }
365
+ if (sendParams.coverAppCallInnerTransactionFees) {
366
+ const additionalTransactionFee = additionalTransactionFees.get(i);
367
+ if (additionalTransactionFee !== void 0) {
368
+ if (group[i].txn.type !== algosdk.TransactionType.appl) throw Error(`An additional fee of ${additionalTransactionFee} µALGO is required for non app call transaction ${i}`);
369
+ const transactionFee = group[i].txn.fee + additionalTransactionFee;
370
+ const maxFee = additionalAtcContext?.maxFees?.get(i)?.microAlgo;
371
+ if (maxFee === void 0 || transactionFee > maxFee) throw Error(`Calculated transaction fee ${transactionFee} µALGO is greater than max of ${maxFee ?? "undefined"} for transaction ${i}`);
372
+ group[i].txn.fee = transactionFee;
373
+ }
374
+ }
375
+ });
376
+ if (sendParams.populateAppCallResources) {
377
+ if (indexesWithAccessReferences.length > 0) Config.logger.warn(`Resource population will be skipped for transaction indexes ${indexesWithAccessReferences.join(", ")} as they use access references.`);
378
+ const populateGroupResource = (txns, reference, type) => {
379
+ const isApplBelowLimit = (t) => {
380
+ if (t.txn.type !== algosdk.TransactionType.appl) return false;
381
+ if (appCallHasAccessReferences(t.txn)) return false;
382
+ const accounts = t.txn.applicationCall?.accounts?.length ?? 0;
383
+ const assets = t.txn.applicationCall?.foreignAssets?.length ?? 0;
384
+ const apps = t.txn.applicationCall?.foreignApps?.length ?? 0;
385
+ const boxes = t.txn.applicationCall?.boxes?.length ?? 0;
386
+ return accounts + assets + apps + boxes < 8;
387
+ };
388
+ if (type === "assetHolding" || type === "appLocal") {
389
+ const { account } = reference;
390
+ let txnIndex = txns.findIndex((t) => {
391
+ if (!isApplBelowLimit(t)) return false;
392
+ return t.txn.applicationCall?.accounts?.map((a) => a.toString()).includes(account.toString()) || t.txn.applicationCall?.foreignApps?.map((a) => algosdk.getApplicationAddress(a).toString()).includes(account.toString()) || Object.values(t.txn).some((f) => stringifyJSON(f, (_, v) => v instanceof Address ? v.toString() : v)?.includes(account.toString()));
393
+ });
394
+ if (txnIndex > -1) {
395
+ if (type === "assetHolding") {
396
+ const { asset } = reference;
397
+ txns[txnIndex].txn["applicationCall"] = {
398
+ ...txns[txnIndex].txn.applicationCall,
399
+ foreignAssets: [...txns[txnIndex].txn?.applicationCall?.foreignAssets ?? [], ...[asset]]
400
+ };
401
+ } else {
402
+ const { app } = reference;
403
+ txns[txnIndex].txn["applicationCall"] = {
404
+ ...txns[txnIndex].txn.applicationCall,
405
+ foreignApps: [...txns[txnIndex].txn?.applicationCall?.foreignApps ?? [], ...[app]]
406
+ };
407
+ }
408
+ return;
409
+ }
410
+ txnIndex = txns.findIndex((t) => {
411
+ if (!isApplBelowLimit(t)) return false;
412
+ if ((t.txn.applicationCall?.accounts?.length ?? 0) >= 8) return false;
413
+ if (type === "assetHolding") {
414
+ const { asset } = reference;
415
+ return t.txn.applicationCall?.foreignAssets?.includes(asset);
416
+ } else {
417
+ const { app } = reference;
418
+ return t.txn.applicationCall?.foreignApps?.includes(app) || t.txn.applicationCall?.appIndex === app;
419
+ }
420
+ });
421
+ if (txnIndex > -1) {
422
+ const { account } = reference;
423
+ txns[txnIndex].txn["applicationCall"] = {
424
+ ...txns[txnIndex].txn.applicationCall,
425
+ accounts: [...txns[txnIndex].txn?.applicationCall?.accounts ?? [], ...[account]]
426
+ };
427
+ return;
428
+ }
429
+ }
430
+ if (type === "box") {
431
+ const { app, name } = reference;
432
+ const txnIndex = txns.findIndex((t) => {
433
+ if (!isApplBelowLimit(t)) return false;
434
+ return t.txn.applicationCall?.foreignApps?.includes(app) || t.txn.applicationCall?.appIndex === app;
435
+ });
436
+ if (txnIndex > -1) {
437
+ txns[txnIndex].txn["applicationCall"] = {
438
+ ...txns[txnIndex].txn.applicationCall,
439
+ boxes: [...txns[txnIndex].txn?.applicationCall?.boxes ?? [], ...[{
440
+ appIndex: app,
441
+ name
442
+ }]]
443
+ };
444
+ return;
445
+ }
446
+ }
447
+ const txnIndex = txns.findIndex((t) => {
448
+ if (t.txn.type !== algosdk.TransactionType.appl) return false;
449
+ if (appCallHasAccessReferences(t.txn)) return false;
450
+ const accounts = t.txn.applicationCall?.accounts?.length ?? 0;
451
+ const assets = t.txn.applicationCall?.foreignAssets?.length ?? 0;
452
+ const apps = t.txn.applicationCall?.foreignApps?.length ?? 0;
453
+ const boxes = t.txn.applicationCall?.boxes?.length ?? 0;
454
+ if (type === "account") return accounts < 8 && accounts + assets + apps + boxes < 8;
455
+ if (type === "assetHolding" || type === "appLocal") return accounts + assets + apps + boxes < 7 && accounts < 8;
456
+ if (type === "box" && BigInt(reference.app) !== BigInt(0)) return accounts + assets + apps + boxes < 7;
457
+ return accounts + assets + apps + boxes < 8;
458
+ });
459
+ if (txnIndex === -1) throw Error("No more transactions below reference limit. Add another app call to the group.");
460
+ if (type === "account") txns[txnIndex].txn["applicationCall"] = {
461
+ ...txns[txnIndex].txn.applicationCall,
462
+ accounts: [...txns[txnIndex].txn?.applicationCall?.accounts ?? [], ...[reference]]
463
+ };
464
+ else if (type === "app") txns[txnIndex].txn["applicationCall"] = {
465
+ ...txns[txnIndex].txn.applicationCall,
466
+ foreignApps: [...txns[txnIndex].txn?.applicationCall?.foreignApps ?? [], ...[typeof reference === "bigint" ? reference : BigInt(reference)]]
467
+ };
468
+ else if (type === "box") {
469
+ const { app, name } = reference;
470
+ txns[txnIndex].txn["applicationCall"] = {
471
+ ...txns[txnIndex].txn.applicationCall,
472
+ boxes: [...txns[txnIndex].txn?.applicationCall?.boxes ?? [], ...[{
473
+ appIndex: app,
474
+ name
475
+ }]]
476
+ };
477
+ if (app.toString() !== "0") txns[txnIndex].txn["applicationCall"] = {
478
+ ...txns[txnIndex].txn.applicationCall,
479
+ foreignApps: [...txns[txnIndex].txn?.applicationCall?.foreignApps ?? [], ...[app]]
480
+ };
481
+ } else if (type === "assetHolding") {
482
+ const { asset, account } = reference;
483
+ txns[txnIndex].txn["applicationCall"] = {
484
+ ...txns[txnIndex].txn.applicationCall,
485
+ foreignAssets: [...txns[txnIndex].txn?.applicationCall?.foreignAssets ?? [], ...[asset]],
486
+ accounts: [...txns[txnIndex].txn?.applicationCall?.accounts ?? [], ...[account]]
487
+ };
488
+ } else if (type === "appLocal") {
489
+ const { app, account } = reference;
490
+ txns[txnIndex].txn["applicationCall"] = {
491
+ ...txns[txnIndex].txn.applicationCall,
492
+ foreignApps: [...txns[txnIndex].txn?.applicationCall?.foreignApps ?? [], ...[app]],
493
+ accounts: [...txns[txnIndex].txn?.applicationCall?.accounts ?? [], ...[account]]
494
+ };
495
+ } else if (type === "asset") txns[txnIndex].txn["applicationCall"] = {
496
+ ...txns[txnIndex].txn.applicationCall,
497
+ foreignAssets: [...txns[txnIndex].txn?.applicationCall?.foreignAssets ?? [], ...[typeof reference === "bigint" ? reference : BigInt(reference)]]
498
+ };
499
+ };
500
+ const g = executionInfo.groupUnnamedResourcesAccessed;
501
+ if (g) {
502
+ g.appLocals?.forEach((a) => {
503
+ populateGroupResource(group, a, "appLocal");
504
+ g.accounts = g.accounts?.filter((acc) => acc !== a.account);
505
+ g.apps = g.apps?.filter((app) => BigInt(app) !== BigInt(a.app));
506
+ });
507
+ g.assetHoldings?.forEach((a) => {
508
+ populateGroupResource(group, a, "assetHolding");
509
+ g.accounts = g.accounts?.filter((acc) => acc !== a.account);
510
+ g.assets = g.assets?.filter((asset) => BigInt(asset) !== BigInt(a.asset));
511
+ });
512
+ g.accounts?.forEach((a) => {
513
+ populateGroupResource(group, a, "account");
514
+ });
515
+ g.boxes?.forEach((b) => {
516
+ populateGroupResource(group, b, "box");
517
+ g.apps = g.apps?.filter((app) => BigInt(app) !== BigInt(b.app));
518
+ });
519
+ g.assets?.forEach((a) => {
520
+ populateGroupResource(group, a, "asset");
521
+ });
522
+ g.apps?.forEach((a) => {
523
+ populateGroupResource(group, a, "app");
524
+ });
525
+ if (g.extraBoxRefs) for (let i = 0; i < g.extraBoxRefs; i += 1) populateGroupResource(group, new algosdk.modelsv2.BoxReference({
526
+ app: 0,
527
+ name: /* @__PURE__ */ new Uint8Array(0)
528
+ }), "box");
529
+ }
530
+ }
531
+ const newAtc = new algosdk.AtomicTransactionComposer();
532
+ group.forEach((t) => {
533
+ t.txn.group = void 0;
534
+ newAtc.addTransaction(t);
535
+ });
536
+ newAtc["methodCalls"] = atc["methodCalls"];
537
+ return newAtc;
670
538
  }
671
539
  /**
672
- * Signs and sends transactions that have been collected by an `AtomicTransactionComposer`.
673
- * @param atcSend The parameters controlling the send, including `atc` The `AtomicTransactionComposer` and params to control send behaviour
674
- * @param algod An algod client
675
- * @returns An object with transaction IDs, transactions, group transaction ID (`groupTransactionId`) if more than 1 transaction sent, and (if `skipWaiting` is `false` or unset) confirmation (`confirmation`)
676
- */
677
- const sendAtomicTransactionComposer = async function (atcSend, algod) {
678
- const { atc: givenAtc, sendParams, additionalAtcContext, ...executeParams } = atcSend;
679
- let atc;
680
- atc = givenAtc;
681
- try {
682
- const transactionsWithSigner = atc.buildGroup();
683
- // If populateAppCallResources is true OR if populateAppCallResources is undefined and there are app calls, then populate resources
684
- const populateAppCallResources = executeParams?.populateAppCallResources ?? sendParams?.populateAppCallResources ?? Config.populateAppCallResources;
685
- const coverAppCallInnerTransactionFees = executeParams?.coverAppCallInnerTransactionFees;
686
- if ((populateAppCallResources || coverAppCallInnerTransactionFees) &&
687
- transactionsWithSigner.map((t) => t.txn.type).includes(algosdk.TransactionType.appl)) {
688
- atc = await prepareGroupForSending(givenAtc, algod, { ...executeParams, populateAppCallResources, coverAppCallInnerTransactionFees }, additionalAtcContext);
689
- }
690
- // atc.buildGroup() is needed to ensure that any changes made by prepareGroupForSending are reflected and the group id is set
691
- const transactionsToSend = atc.buildGroup().map((t) => {
692
- return t.txn;
693
- });
694
- let groupId = undefined;
695
- if (transactionsToSend.length > 1) {
696
- groupId = transactionsToSend[0].group ? Buffer.from(transactionsToSend[0].group).toString('base64') : '';
697
- Config.getLogger(executeParams?.suppressLog ?? sendParams?.suppressLog).verbose(`Sending group of ${transactionsToSend.length} transactions (${groupId})`, {
698
- transactionsToSend,
699
- });
700
- Config.getLogger(executeParams?.suppressLog ?? sendParams?.suppressLog).debug(`Transaction IDs (${groupId})`, transactionsToSend.map((t) => t.txID()));
701
- }
702
- if (Config.debug && Config.traceAll) {
703
- // Emit the simulate response for use with AlgoKit AVM debugger
704
- const simulateResponse = await performAtomicTransactionComposerSimulate(atc, algod);
705
- await Config.events.emitAsync(EventType.TxnGroupSimulated, {
706
- simulateResponse,
707
- });
708
- }
709
- const result = await atc.execute(algod, executeParams?.maxRoundsToWaitForConfirmation ?? sendParams?.maxRoundsToWaitForConfirmation ?? 5);
710
- if (transactionsToSend.length > 1) {
711
- Config.getLogger(executeParams?.suppressLog ?? sendParams?.suppressLog).verbose(`Group transaction (${groupId}) sent with ${transactionsToSend.length} transactions`);
712
- }
713
- else {
714
- Config.getLogger(executeParams?.suppressLog ?? sendParams?.suppressLog).verbose(`Sent transaction ID ${transactionsToSend[0].txID()} ${transactionsToSend[0].type} from ${transactionsToSend[0].sender.toString()}`);
715
- }
716
- let confirmations = undefined;
717
- if (!sendParams?.skipWaiting) {
718
- confirmations = await Promise.all(transactionsToSend.map(async (t) => await algod.pendingTransactionInformation(t.txID()).do()));
719
- }
720
- const methodCalls = [...atc['methodCalls'].values()];
721
- return {
722
- groupId,
723
- confirmations,
724
- txIds: transactionsToSend.map((t) => t.txID()),
725
- transactions: transactionsToSend,
726
- returns: result.methodResults.map((r, i) => getABIReturnValue(r, methodCalls[i].returns.type)),
727
- };
728
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
729
- }
730
- catch (e) {
731
- // Create a new error object so the stack trace is correct (algosdk throws an error with a more limited stack trace)
732
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
733
- const err = new Error(typeof e === 'object' ? e?.message : 'Received error executing Atomic Transaction Composer');
734
- err.cause = e;
735
- if (typeof e === 'object') {
736
- // Remove headers as it doesn't have anything useful.
737
- delete e.response?.headers;
738
- err.response = e.response;
739
- // body property very noisy
740
- if (e.response && 'body' in e.response)
741
- delete err.response.body;
742
- err.name = e.name;
743
- }
744
- if (Config.debug && typeof e === 'object') {
745
- err.traces = [];
746
- Config.getLogger(executeParams?.suppressLog ?? sendParams?.suppressLog).error('Received error executing Atomic Transaction Composer and debug flag enabled; attempting simulation to get more information', err);
747
- const simulate = await performAtomicTransactionComposerSimulate(atc, algod);
748
- if (Config.debug && !Config.traceAll) {
749
- // Emit the event only if traceAll: false, as it should have already been emitted above
750
- await Config.events.emitAsync(EventType.TxnGroupSimulated, {
751
- simulateResponse: simulate,
752
- });
753
- }
754
- if (simulate && simulate.txnGroups[0].failedAt) {
755
- for (const txn of simulate.txnGroups[0].txnResults) {
756
- err.traces.push({
757
- trace: txn.execTrace?.toEncodingData(),
758
- appBudget: txn.appBudgetConsumed,
759
- logicSigBudget: txn.logicSigBudgetConsumed,
760
- logs: txn.txnResult.logs,
761
- message: simulate.txnGroups[0].failureMessage,
762
- });
763
- }
764
- }
765
- }
766
- else {
767
- Config.getLogger(executeParams?.suppressLog ?? sendParams?.suppressLog).error('Received error executing Atomic Transaction Composer, for more information enable the debug flag', err);
768
- }
769
- // Attach the sent transactions so we can use them in error transformers
770
- err.sentTransactions = atc.buildGroup().map((t) => t.txn);
771
- throw err;
772
- }
540
+ * Signs and sends transactions that have been collected by an `AtomicTransactionComposer`.
541
+ * @param atcSend The parameters controlling the send, including `atc` The `AtomicTransactionComposer` and params to control send behaviour
542
+ * @param algod An algod client
543
+ * @returns An object with transaction IDs, transactions, group transaction ID (`groupTransactionId`) if more than 1 transaction sent, and (if `skipWaiting` is `false` or unset) confirmation (`confirmation`)
544
+ */
545
+ const sendAtomicTransactionComposer = async function(atcSend, algod) {
546
+ const { atc: givenAtc, sendParams, additionalAtcContext, ...executeParams } = atcSend;
547
+ let atc;
548
+ atc = givenAtc;
549
+ try {
550
+ const transactionsWithSigner = atc.buildGroup();
551
+ const populateAppCallResources = executeParams?.populateAppCallResources ?? sendParams?.populateAppCallResources ?? Config.populateAppCallResources;
552
+ const coverAppCallInnerTransactionFees = executeParams?.coverAppCallInnerTransactionFees;
553
+ if ((populateAppCallResources || coverAppCallInnerTransactionFees) && transactionsWithSigner.map((t) => t.txn.type).includes(algosdk.TransactionType.appl)) atc = await prepareGroupForSending(givenAtc, algod, {
554
+ ...executeParams,
555
+ populateAppCallResources,
556
+ coverAppCallInnerTransactionFees
557
+ }, additionalAtcContext);
558
+ const transactionsToSend = atc.buildGroup().map((t) => {
559
+ return t.txn;
560
+ });
561
+ let groupId = void 0;
562
+ if (transactionsToSend.length > 1) {
563
+ groupId = transactionsToSend[0].group ? Buffer.from(transactionsToSend[0].group).toString("base64") : "";
564
+ Config.getLogger(executeParams?.suppressLog ?? sendParams?.suppressLog).verbose(`Sending group of ${transactionsToSend.length} transactions (${groupId})`, { transactionsToSend });
565
+ Config.getLogger(executeParams?.suppressLog ?? sendParams?.suppressLog).debug(`Transaction IDs (${groupId})`, transactionsToSend.map((t) => t.txID()));
566
+ }
567
+ if (Config.debug && Config.traceAll) {
568
+ const simulateResponse = await performAtomicTransactionComposerSimulate(atc, algod);
569
+ await Config.events.emitAsync("TxnGroupSimulated", { simulateResponse });
570
+ }
571
+ const result = await atc.execute(algod, executeParams?.maxRoundsToWaitForConfirmation ?? sendParams?.maxRoundsToWaitForConfirmation ?? 5);
572
+ if (transactionsToSend.length > 1) Config.getLogger(executeParams?.suppressLog ?? sendParams?.suppressLog).verbose(`Group transaction (${groupId}) sent with ${transactionsToSend.length} transactions`);
573
+ else Config.getLogger(executeParams?.suppressLog ?? sendParams?.suppressLog).verbose(`Sent transaction ID ${transactionsToSend[0].txID()} ${transactionsToSend[0].type} from ${transactionsToSend[0].sender.toString()}`);
574
+ let confirmations = void 0;
575
+ if (!sendParams?.skipWaiting) confirmations = await Promise.all(transactionsToSend.map(async (t) => await algod.pendingTransactionInformation(t.txID()).do()));
576
+ const methodCalls = [...atc["methodCalls"].values()];
577
+ return {
578
+ groupId,
579
+ confirmations,
580
+ txIds: transactionsToSend.map((t) => t.txID()),
581
+ transactions: transactionsToSend,
582
+ returns: result.methodResults.map((r, i) => getABIReturnValue(r, methodCalls[i].returns.type))
583
+ };
584
+ } catch (e) {
585
+ const err = new Error(typeof e === "object" ? e?.message : "Received error executing Atomic Transaction Composer");
586
+ err.cause = e;
587
+ if (typeof e === "object") {
588
+ delete e.response?.headers;
589
+ err.response = e.response;
590
+ if (e.response && "body" in e.response) delete err.response.body;
591
+ err.name = e.name;
592
+ }
593
+ if (Config.debug && typeof e === "object") {
594
+ err.traces = [];
595
+ Config.getLogger(executeParams?.suppressLog ?? sendParams?.suppressLog).error("Received error executing Atomic Transaction Composer and debug flag enabled; attempting simulation to get more information", err);
596
+ const simulate = await performAtomicTransactionComposerSimulate(atc, algod);
597
+ if (Config.debug && !Config.traceAll) await Config.events.emitAsync("TxnGroupSimulated", { simulateResponse: simulate });
598
+ if (simulate && simulate.txnGroups[0].failedAt) for (const txn of simulate.txnGroups[0].txnResults) err.traces.push({
599
+ trace: txn.execTrace?.toEncodingData(),
600
+ appBudget: txn.appBudgetConsumed,
601
+ logicSigBudget: txn.logicSigBudgetConsumed,
602
+ logs: txn.txnResult.logs,
603
+ message: simulate.txnGroups[0].failureMessage
604
+ });
605
+ } else Config.getLogger(executeParams?.suppressLog ?? sendParams?.suppressLog).error("Received error executing Atomic Transaction Composer, for more information enable the debug flag", err);
606
+ err.sentTransactions = atc.buildGroup().map((t) => t.txn);
607
+ throw err;
608
+ }
773
609
  };
774
610
  /**
775
- * Takes an algosdk `ABIResult` and converts it to an `ABIReturn`.
776
- * Converts `bigint`'s for Uint's < 64 to `number` for easier use.
777
- * @param result The `ABIReturn`
778
- */
611
+ * Takes an algosdk `ABIResult` and converts it to an `ABIReturn`.
612
+ * Converts `bigint`'s for Uint's < 64 to `number` for easier use.
613
+ * @param result The `ABIReturn`
614
+ */
779
615
  function getABIReturnValue(result, type) {
780
- if (result.decodeError) {
781
- return {
782
- decodeError: result.decodeError,
783
- };
784
- }
785
- const returnValue = convertAbiByteArrays(result.returnValue !== undefined && result.method.returns.type !== 'void'
786
- ? convertABIDecodedBigIntToNumber(result.returnValue, result.method.returns.type)
787
- : result.returnValue, type);
788
- return {
789
- method: result.method,
790
- rawReturnValue: result.rawReturnValue,
791
- decodeError: undefined,
792
- returnValue,
793
- };
616
+ if (result.decodeError) return { decodeError: result.decodeError };
617
+ const returnValue = convertAbiByteArrays(result.returnValue !== void 0 && result.method.returns.type !== "void" ? convertABIDecodedBigIntToNumber(result.returnValue, result.method.returns.type) : result.returnValue, type);
618
+ return {
619
+ method: result.method,
620
+ rawReturnValue: result.rawReturnValue,
621
+ decodeError: void 0,
622
+ returnValue
623
+ };
794
624
  }
795
625
  /**
796
- * @deprecated Use `TransactionComposer` (`algorand.newGroup()`) or `AtomicTransactionComposer` to construct and send group transactions instead.
797
- *
798
- * Signs and sends a group of [up to 16](https://dev.algorand.co/concepts/transactions/atomic-txn-groups/#create-transactions) transactions to the chain
799
- *
800
- * @param groupSend The group details to send, with:
801
- * * `transactions`: The array of transactions to send along with their signing account
802
- * * `sendParams`: The parameters to dictate how the group is sent
803
- * @param algod An algod client
804
- * @returns An object with transaction IDs, transactions, group transaction ID (`groupTransactionId`) if more than 1 transaction sent, and (if `skipWaiting` is `false` or unset) confirmation (`confirmation`)
805
- */
806
- const sendGroupOfTransactions = async function (groupSend, algod) {
807
- const { transactions, signer, sendParams } = groupSend;
808
- const defaultTransactionSigner = signer ? getSenderTransactionSigner(signer) : undefined;
809
- const transactionsWithSigner = await Promise.all(transactions.map(async (t) => {
810
- if ('signer' in t)
811
- return {
812
- txn: t.transaction,
813
- signer: getSenderTransactionSigner(t.signer),
814
- sender: t.signer,
815
- };
816
- const txn = 'then' in t ? (await t).transaction : t;
817
- if (!signer) {
818
- throw new Error(`Attempt to send transaction ${txn.txID()} as part of a group transaction, but no signer parameter was provided.`);
819
- }
820
- return {
821
- txn,
822
- signer: defaultTransactionSigner,
823
- sender: signer,
824
- };
825
- }));
826
- const atc = new AtomicTransactionComposer();
827
- transactionsWithSigner.forEach((txn) => atc.addTransaction(txn));
828
- return (await sendAtomicTransactionComposer({ atc, sendParams }, algod));
626
+ * @deprecated Use `TransactionComposer` (`algorand.newGroup()`) or `AtomicTransactionComposer` to construct and send group transactions instead.
627
+ *
628
+ * Signs and sends a group of [up to 16](https://dev.algorand.co/concepts/transactions/atomic-txn-groups/#create-transactions) transactions to the chain
629
+ *
630
+ * @param groupSend The group details to send, with:
631
+ * * `transactions`: The array of transactions to send along with their signing account
632
+ * * `sendParams`: The parameters to dictate how the group is sent
633
+ * @param algod An algod client
634
+ * @returns An object with transaction IDs, transactions, group transaction ID (`groupTransactionId`) if more than 1 transaction sent, and (if `skipWaiting` is `false` or unset) confirmation (`confirmation`)
635
+ */
636
+ const sendGroupOfTransactions = async function(groupSend, algod) {
637
+ const { transactions, signer, sendParams } = groupSend;
638
+ const defaultTransactionSigner = signer ? getSenderTransactionSigner(signer) : void 0;
639
+ const transactionsWithSigner = await Promise.all(transactions.map(async (t) => {
640
+ if ("signer" in t) return {
641
+ txn: t.transaction,
642
+ signer: getSenderTransactionSigner(t.signer),
643
+ sender: t.signer
644
+ };
645
+ const txn = "then" in t ? (await t).transaction : t;
646
+ if (!signer) throw new Error(`Attempt to send transaction ${txn.txID()} as part of a group transaction, but no signer parameter was provided.`);
647
+ return {
648
+ txn,
649
+ signer: defaultTransactionSigner,
650
+ sender: signer
651
+ };
652
+ }));
653
+ const atc = new AtomicTransactionComposer();
654
+ transactionsWithSigner.forEach((txn) => atc.addTransaction(txn));
655
+ return await sendAtomicTransactionComposer({
656
+ atc,
657
+ sendParams
658
+ }, algod);
829
659
  };
830
660
  /**
831
- * Wait until the transaction is confirmed or rejected, or until `timeout`
832
- * number of rounds have passed.
833
- *
834
- * @param algod An algod client
835
- * @param transactionId The transaction ID to wait for
836
- * @param maxRoundsToWait Maximum number of rounds to wait
837
- *
838
- * @return Pending transaction information
839
- * @throws Throws an error if the transaction is not confirmed or rejected in the next `timeout` rounds
840
- */
841
- const waitForConfirmation = async function (transactionId, maxRoundsToWait, algod) {
842
- if (maxRoundsToWait < 0) {
843
- throw new Error(`Invalid timeout, received ${maxRoundsToWait}, expected > 0`);
844
- }
845
- // Get current round
846
- const status = await algod.status().do();
847
- if (status === undefined) {
848
- throw new Error('Unable to get node status');
849
- }
850
- // Loop for up to `timeout` rounds looking for a confirmed transaction
851
- const startRound = BigInt(status.lastRound) + 1n;
852
- let currentRound = startRound;
853
- while (currentRound < startRound + BigInt(maxRoundsToWait)) {
854
- try {
855
- const pendingInfo = await algod.pendingTransactionInformation(transactionId).do();
856
- if (pendingInfo !== undefined) {
857
- const confirmedRound = pendingInfo.confirmedRound;
858
- if (confirmedRound && confirmedRound > 0) {
859
- return pendingInfo;
860
- }
861
- else {
862
- const poolError = pendingInfo.poolError;
863
- if (poolError != null && poolError.length > 0) {
864
- // If there was a pool error, then the transaction has been rejected!
865
- throw new Error(`Transaction ${transactionId} was rejected; pool error: ${poolError}`);
866
- }
867
- }
868
- }
869
- }
870
- catch (e) {
871
- if (e.name === 'URLTokenBaseHTTPError') {
872
- currentRound++;
873
- continue;
874
- }
875
- }
876
- await algod.statusAfterBlock(toNumber(currentRound)).do();
877
- currentRound++;
878
- }
879
- throw new Error(`Transaction ${transactionId} not confirmed after ${maxRoundsToWait} rounds`);
661
+ * Wait until the transaction is confirmed or rejected, or until `timeout`
662
+ * number of rounds have passed.
663
+ *
664
+ * @param algod An algod client
665
+ * @param transactionId The transaction ID to wait for
666
+ * @param maxRoundsToWait Maximum number of rounds to wait
667
+ *
668
+ * @return Pending transaction information
669
+ * @throws Throws an error if the transaction is not confirmed or rejected in the next `timeout` rounds
670
+ */
671
+ const waitForConfirmation = async function(transactionId, maxRoundsToWait, algod) {
672
+ if (maxRoundsToWait < 0) throw new Error(`Invalid timeout, received ${maxRoundsToWait}, expected > 0`);
673
+ const status = await algod.status().do();
674
+ if (status === void 0) throw new Error("Unable to get node status");
675
+ const startRound = BigInt(status.lastRound) + 1n;
676
+ let currentRound = startRound;
677
+ while (currentRound < startRound + BigInt(maxRoundsToWait)) {
678
+ try {
679
+ const pendingInfo = await algod.pendingTransactionInformation(transactionId).do();
680
+ if (pendingInfo !== void 0) {
681
+ const confirmedRound = pendingInfo.confirmedRound;
682
+ if (confirmedRound && confirmedRound > 0) return pendingInfo;
683
+ else {
684
+ const poolError = pendingInfo.poolError;
685
+ if (poolError != null && poolError.length > 0) throw new Error(`Transaction ${transactionId} was rejected; pool error: ${poolError}`);
686
+ }
687
+ }
688
+ } catch (e) {
689
+ if (e.name === "URLTokenBaseHTTPError") {
690
+ currentRound++;
691
+ continue;
692
+ }
693
+ }
694
+ await algod.statusAfterBlock(toNumber(currentRound)).do();
695
+ currentRound++;
696
+ }
697
+ throw new Error(`Transaction ${transactionId} not confirmed after ${maxRoundsToWait} rounds`);
880
698
  };
881
699
  /**
882
- * @deprecated Use `TransactionComposer` and the `maxFee` field in the transaction params instead.
883
- *
884
- * Limit the acceptable fee to a defined amount of µAlgo.
885
- * This also sets the transaction to be flatFee to ensure the transaction only succeeds at
886
- * the estimated rate.
887
- * @param transaction The transaction to cap or suggested params object about to be used to create a transaction
888
- * @param maxAcceptableFee The maximum acceptable fee to pay
889
- */
700
+ * @deprecated Use `TransactionComposer` and the `maxFee` field in the transaction params instead.
701
+ *
702
+ * Limit the acceptable fee to a defined amount of µAlgo.
703
+ * This also sets the transaction to be flatFee to ensure the transaction only succeeds at
704
+ * the estimated rate.
705
+ * @param transaction The transaction to cap or suggested params object about to be used to create a transaction
706
+ * @param maxAcceptableFee The maximum acceptable fee to pay
707
+ */
890
708
  function capTransactionFee(transaction, maxAcceptableFee) {
891
- // If a flat fee hasn't already been defined
892
- if (!('flatFee' in transaction) || !transaction.flatFee) {
893
- // Once a transaction has been constructed by algosdk, transaction.fee indicates what the total transaction fee
894
- // Will be based on the current suggested fee-per-byte value.
895
- if (transaction.fee > maxAcceptableFee.microAlgo) {
896
- throw new Error(`Cancelled transaction due to high network congestion fees. Algorand suggested fees would cause this transaction to cost ${transaction.fee} µALGO. Cap for this transaction is ${maxAcceptableFee.microAlgo} µALGO.`);
897
- }
898
- else if (transaction.fee > 1000000) {
899
- Config.logger.warn(`Algorand network congestion fees are in effect. This transaction will incur a fee of ${transaction.fee} µALGO.`);
900
- }
901
- // Now set the flat on the transaction. Otherwise the network may increase the fee above our cap and perform the transaction.
902
- if ('flatFee' in transaction) {
903
- transaction.flatFee = true;
904
- }
905
- }
709
+ if (!("flatFee" in transaction) || !transaction.flatFee) {
710
+ if (transaction.fee > maxAcceptableFee.microAlgo) throw new Error(`Cancelled transaction due to high network congestion fees. Algorand suggested fees would cause this transaction to cost ${transaction.fee} µALGO. Cap for this transaction is ${maxAcceptableFee.microAlgo} µALGO.`);
711
+ else if (transaction.fee > 1e6) Config.logger.warn(`Algorand network congestion fees are in effect. This transaction will incur a fee of ${transaction.fee} µALGO.`);
712
+ if ("flatFee" in transaction) transaction.flatFee = true;
713
+ }
906
714
  }
907
715
  /**
908
- * @deprecated Use `TransactionComposer` and the `maxFee` and `staticFee` fields in the transaction params instead.
909
- *
910
- * Allows for control of fees on a `Transaction` or `SuggestedParams` object
911
- * @param transaction The transaction or suggested params
912
- * @param feeControl The fee control parameters
913
- */
716
+ * @deprecated Use `TransactionComposer` and the `maxFee` and `staticFee` fields in the transaction params instead.
717
+ *
718
+ * Allows for control of fees on a `Transaction` or `SuggestedParams` object
719
+ * @param transaction The transaction or suggested params
720
+ * @param feeControl The fee control parameters
721
+ */
914
722
  function controlFees(transaction, feeControl) {
915
- const { fee, maxFee } = feeControl;
916
- if (fee) {
917
- transaction.fee = Number(fee.microAlgo);
918
- if ('flatFee' in transaction) {
919
- transaction.flatFee = true;
920
- }
921
- }
922
- if (maxFee !== undefined) {
923
- capTransactionFee(transaction, maxFee);
924
- }
925
- return transaction;
723
+ const { fee, maxFee } = feeControl;
724
+ if (fee) {
725
+ transaction.fee = Number(fee.microAlgo);
726
+ if ("flatFee" in transaction) transaction.flatFee = true;
727
+ }
728
+ if (maxFee !== void 0) capTransactionFee(transaction, maxFee);
729
+ return transaction;
926
730
  }
927
731
  /**
928
- * @deprecated Use `suggestedParams ? { ...suggestedParams } : await algod.getTransactionParams().do()` instead
929
- *
930
- * Returns suggested transaction parameters from algod unless some are already provided.
931
- * @param params Optionally provide parameters to use
932
- * @param algod Algod algod
933
- * @returns The suggested transaction parameters
934
- */
732
+ * @deprecated Use `suggestedParams ? { ...suggestedParams } : await algod.getTransactionParams().do()` instead
733
+ *
734
+ * Returns suggested transaction parameters from algod unless some are already provided.
735
+ * @param params Optionally provide parameters to use
736
+ * @param algod Algod algod
737
+ * @returns The suggested transaction parameters
738
+ */
935
739
  async function getTransactionParams(params, algod) {
936
- if (params) {
937
- return { ...params };
938
- }
939
- const p = await algod.getTransactionParams().do();
940
- return {
941
- fee: p.fee,
942
- firstValid: p.firstValid,
943
- lastValid: p.lastValid,
944
- genesisID: p.genesisID,
945
- genesisHash: p.genesisHash,
946
- minFee: p.minFee,
947
- };
740
+ if (params) return { ...params };
741
+ const p = await algod.getTransactionParams().do();
742
+ return {
743
+ fee: p.fee,
744
+ firstValid: p.firstValid,
745
+ lastValid: p.lastValid,
746
+ genesisID: p.genesisID,
747
+ genesisHash: p.genesisHash,
748
+ minFee: p.minFee
749
+ };
948
750
  }
949
751
  /**
950
- * @deprecated Use `atc.clone().buildGroup()` instead.
951
- *
952
- * Returns the array of transactions currently present in the given `AtomicTransactionComposer`
953
- * @param atc The atomic transaction composer
954
- * @returns The array of transactions with signers
955
- */
752
+ * @deprecated Use `atc.clone().buildGroup()` instead.
753
+ *
754
+ * Returns the array of transactions currently present in the given `AtomicTransactionComposer`
755
+ * @param atc The atomic transaction composer
756
+ * @returns The array of transactions with signers
757
+ */
956
758
  function getAtomicTransactionComposerTransactions(atc) {
957
- try {
958
- return atc.clone().buildGroup();
959
- }
960
- catch {
961
- return [];
962
- }
759
+ try {
760
+ return atc.clone().buildGroup();
761
+ } catch {
762
+ return [];
763
+ }
963
764
  }
964
-
765
+ //#endregion
965
766
  export { MAX_APP_CALL_ACCOUNT_REFERENCES, MAX_APP_CALL_FOREIGN_REFERENCES, MAX_TRANSACTION_GROUP_SIZE, capTransactionFee, controlFees, encodeLease, encodeTransactionNote, getABIReturnValue, getAtomicTransactionComposerTransactions, getSenderAddress, getSenderTransactionSigner, getTransactionParams, getTransactionWithSigner, populateAppCallResources, prepareGroupForSending, sendAtomicTransactionComposer, sendGroupOfTransactions, sendTransaction, signTransaction, waitForConfirmation };
966
- //# sourceMappingURL=transaction.mjs.map
767
+
768
+ //# sourceMappingURL=transaction.mjs.map