summaryrefslogtreecommitdiff
path: root/data/transactions/logic/evalStateful_test.go
blob: f782fcce9a177f3a5377543a00a3cd841fe1d8f0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
// Copyright (C) 2019-2021 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand.  If not, see <https://www.gnu.org/licenses/>.

package logic

import (
	"encoding/hex"
	"fmt"
	"math/rand"
	"strings"
	"testing"

	"github.com/stretchr/testify/require"

	"github.com/algorand/go-algorand/config"
	"github.com/algorand/go-algorand/data/basics"
	"github.com/algorand/go-algorand/data/transactions"
	"github.com/algorand/go-algorand/protocol"
	"github.com/algorand/go-algorand/test/partitiontest"
)

type balanceRecord struct {
	addr     basics.Address
	balance  uint64
	locals   map[basics.AppIndex]basics.TealKeyValue
	holdings map[basics.AssetIndex]basics.AssetHolding
	mods     map[basics.AppIndex]map[string]basics.ValueDelta
}

// In our test ledger, we don't store the creatables with their
// creators, so we need to carry the creator around with them.
type appParams struct {
	basics.AppParams
	Creator basics.Address
}

type asaParams struct {
	basics.AssetParams
	Creator basics.Address
}

type testLedger struct {
	balances          map[basics.Address]balanceRecord
	applications      map[basics.AppIndex]appParams
	assets            map[basics.AssetIndex]asaParams
	trackedCreatables map[int]basics.CreatableIndex
	appID             basics.AppIndex
	creatorAddr       basics.Address
	mods              map[basics.AppIndex]map[string]basics.ValueDelta
	logs              []basics.LogItem
}

func makeApp(li uint64, lb uint64, gi uint64, gb uint64) basics.AppParams {
	return basics.AppParams{
		ApprovalProgram:   []byte{},
		ClearStateProgram: []byte{},
		GlobalState:       map[string]basics.TealValue{},
		StateSchemas: basics.StateSchemas{
			LocalStateSchema:  basics.StateSchema{NumUint: li, NumByteSlice: lb},
			GlobalStateSchema: basics.StateSchema{NumUint: gi, NumByteSlice: gb},
		},
		ExtraProgramPages: 0,
	}
}

func makeBalanceRecord(addr basics.Address, balance uint64) balanceRecord {
	br := balanceRecord{
		addr:     addr,
		balance:  balance,
		locals:   make(map[basics.AppIndex]basics.TealKeyValue),
		holdings: make(map[basics.AssetIndex]basics.AssetHolding),
		mods:     make(map[basics.AppIndex]map[string]basics.ValueDelta),
	}
	return br
}

func makeSampleEnv() (EvalParams, *testLedger) {
	txn := makeSampleTxn()
	ep := defaultEvalParams(nil, &txn)
	ep.TxnGroup = makeSampleTxnGroup(txn)
	ledger := makeTestLedger(map[basics.Address]uint64{})
	ep.Ledger = ledger
	return ep, ledger
}

func makeTestLedger(balances map[basics.Address]uint64) *testLedger {
	l := new(testLedger)
	l.balances = make(map[basics.Address]balanceRecord)
	for addr, balance := range balances {
		l.newAccount(addr, balance)
	}
	l.applications = make(map[basics.AppIndex]appParams)
	l.assets = make(map[basics.AssetIndex]asaParams)
	l.trackedCreatables = make(map[int]basics.CreatableIndex)
	l.mods = make(map[basics.AppIndex]map[string]basics.ValueDelta)
	return l
}

func (l *testLedger) reset() {
	l.mods = make(map[basics.AppIndex]map[string]basics.ValueDelta)
	for addr, br := range l.balances {
		br.mods = make(map[basics.AppIndex]map[string]basics.ValueDelta)
		l.balances[addr] = br
	}
}

func (l *testLedger) newAccount(addr basics.Address, balance uint64) {
	l.balances[addr] = makeBalanceRecord(addr, balance)
}

func (l *testLedger) newApp(creator basics.Address, appID basics.AppIndex, params basics.AppParams) {
	l.appID = appID
	params = params.Clone()
	if params.GlobalState == nil {
		params.GlobalState = make(basics.TealKeyValue)
	}
	l.applications[appID] = appParams{
		Creator:   creator,
		AppParams: params.Clone(),
	}
	br, ok := l.balances[creator]
	if !ok {
		br = makeBalanceRecord(creator, 0)
	}
	br.locals[appID] = make(map[string]basics.TealValue)
	l.balances[creator] = br
}

func (l *testLedger) newAsset(creator basics.Address, assetID basics.AssetIndex, params basics.AssetParams) {
	l.assets[assetID] = asaParams{
		Creator:     creator,
		AssetParams: params,
	}
	br, ok := l.balances[creator]
	if !ok {
		br = makeBalanceRecord(creator, 0)
	}
	br.holdings[assetID] = basics.AssetHolding{Amount: params.Total, Frozen: params.DefaultFrozen}
	l.balances[creator] = br
}

func (l *testLedger) setHolding(addr basics.Address, assetID uint64, amount uint64, frozen bool) {
	br, ok := l.balances[addr]
	if !ok {
		br = makeBalanceRecord(addr, 0)
	}
	br.holdings[basics.AssetIndex(assetID)] = basics.AssetHolding{Amount: amount, Frozen: frozen}
	l.balances[addr] = br
}

func (l *testLedger) Round() basics.Round {
	return basics.Round(rand.Uint32() + 1)
}

func (l *testLedger) LatestTimestamp() int64 {
	return int64(rand.Uint32() + 1)
}

func (l *testLedger) Balance(addr basics.Address) (amount basics.MicroAlgos, err error) {
	if l.balances == nil {
		err = fmt.Errorf("empty ledger")
		return
	}
	br, ok := l.balances[addr]
	if !ok {
		err = fmt.Errorf("no such address")
		return
	}
	return basics.MicroAlgos{Raw: br.balance}, nil
}

func (l *testLedger) MinBalance(addr basics.Address, proto *config.ConsensusParams) (amount basics.MicroAlgos, err error) {
	if l.balances == nil {
		err = fmt.Errorf("empty ledger")
		return
	}
	br, ok := l.balances[addr]
	if !ok {
		err = fmt.Errorf("no such address")
		return
	}

	var min uint64

	// First, base MinBalance
	min = proto.MinBalance

	// MinBalance for each Asset
	assetCost := basics.MulSaturate(proto.MinBalance, uint64(len(br.holdings)))
	min = basics.AddSaturate(min, assetCost)

	// Base MinBalance + GlobalStateSchema.MinBalance + ExtraProgramPages MinBalance for each created application
	for _, params := range l.applications {
		if params.Creator == addr {
			min = basics.AddSaturate(min, proto.AppFlatParamsMinBalance)
			min = basics.AddSaturate(min, params.GlobalStateSchema.MinBalance(proto).Raw)
			min = basics.AddSaturate(min, basics.MulSaturate(proto.AppFlatParamsMinBalance, uint64(params.ExtraProgramPages)))
		}
	}

	// Base MinBalance + LocalStateSchema.MinBalance for each opted in application
	for idx := range br.locals {
		min = basics.AddSaturate(min, proto.AppFlatParamsMinBalance)
		min = basics.AddSaturate(min, l.applications[idx].LocalStateSchema.MinBalance(proto).Raw)
	}

	return basics.MicroAlgos{Raw: min}, nil
}

func (l *testLedger) GetGlobal(appIdx basics.AppIndex, key string) (basics.TealValue, bool, error) {
	if appIdx == basics.AppIndex(0) {
		appIdx = l.appID
	}
	params, ok := l.applications[appIdx]
	if !ok {
		return basics.TealValue{}, false, fmt.Errorf("no such app")
	}

	// return most recent value if available
	tkvm, ok := l.mods[appIdx]
	if ok {
		val, ok := tkvm[key]
		if ok {
			tv, ok := val.ToTealValue()
			return tv, ok, nil
		}
	}

	// otherwise return original one
	val, ok := params.GlobalState[key]
	return val, ok, nil
}

func (l *testLedger) SetGlobal(key string, value basics.TealValue) error {
	appIdx := l.appID
	params, ok := l.applications[appIdx]
	if !ok {
		return fmt.Errorf("no such app")
	}

	// if writing the same value, return
	// this simulates real ledger behavior for tests
	val, ok := params.GlobalState[key]
	if ok && val == value {
		return nil
	}

	// write to deltas
	_, ok = l.mods[appIdx]
	if !ok {
		l.mods[appIdx] = make(map[string]basics.ValueDelta)
	}
	l.mods[appIdx][key] = value.ToValueDelta()
	return nil
}

func (l *testLedger) DelGlobal(key string) error {
	appIdx := l.appID
	params, ok := l.applications[appIdx]
	if !ok {
		return fmt.Errorf("no such app")
	}

	exist := false
	if _, ok := params.GlobalState[key]; ok {
		exist = true
	}

	_, ok = l.mods[appIdx]
	if !ok && !exist {
		// nothing to delete
		return nil
	}
	if !ok {
		l.mods[appIdx] = make(map[string]basics.ValueDelta)
	}
	_, ok = l.mods[appIdx][key]
	if ok || exist {
		l.mods[appIdx][key] = basics.ValueDelta{Action: basics.DeleteAction}
	}
	return nil
}

func (l *testLedger) GetLocal(addr basics.Address, appIdx basics.AppIndex, key string, accountIdx uint64) (basics.TealValue, bool, error) {
	if appIdx == 0 {
		appIdx = l.appID
	}
	br, ok := l.balances[addr]
	if !ok {
		return basics.TealValue{}, false, fmt.Errorf("no such address")
	}
	tkvd, ok := br.locals[appIdx]
	if !ok {
		return basics.TealValue{}, false, fmt.Errorf("no app for account")
	}

	// check deltas first
	tkvm, ok := br.mods[appIdx]
	if ok {
		val, ok := tkvm[key]
		if ok {
			tv, ok := val.ToTealValue()
			return tv, ok, nil
		}
	}

	val, ok := tkvd[key]
	return val, ok, nil
}

func (l *testLedger) SetLocal(addr basics.Address, key string, value basics.TealValue, accountIdx uint64) error {
	appIdx := l.appID

	br, ok := l.balances[addr]
	if !ok {
		return fmt.Errorf("no such address")
	}
	tkv, ok := br.locals[appIdx]
	if !ok {
		return fmt.Errorf("no app for account")
	}

	// if writing the same value, return
	// this simulates real ledger behavior for tests
	val, ok := tkv[key]
	if ok && val == value {
		return nil
	}

	// write to deltas
	_, ok = br.mods[appIdx]
	if !ok {
		br.mods[appIdx] = make(map[string]basics.ValueDelta)
	}
	br.mods[appIdx][key] = value.ToValueDelta()
	return nil
}

func (l *testLedger) DelLocal(addr basics.Address, key string, accountIdx uint64) error {
	appIdx := l.appID

	br, ok := l.balances[addr]
	if !ok {
		return fmt.Errorf("no such address")
	}
	tkv, ok := br.locals[appIdx]
	if !ok {
		return fmt.Errorf("no app for account")
	}
	exist := false
	if _, ok := tkv[key]; ok {
		exist = true
	}

	_, ok = br.mods[appIdx]
	if !ok && !exist {
		// nothing to delete
		return nil
	}
	if !ok {
		br.mods[appIdx] = make(map[string]basics.ValueDelta)
	}
	_, ok = br.mods[appIdx][key]
	if ok || exist {
		br.mods[appIdx][key] = basics.ValueDelta{Action: basics.DeleteAction}
	}
	return nil
}

func (l *testLedger) OptedIn(addr basics.Address, appIdx basics.AppIndex) (bool, error) {
	if appIdx == 0 {
		appIdx = l.appID
	}
	br, ok := l.balances[addr]
	if !ok {
		return false, fmt.Errorf("no such address")
	}
	_, ok = br.locals[appIdx]
	return ok, nil
}

func (l *testLedger) setTrackedCreatable(groupIdx int, cl basics.CreatableLocator) {
	l.trackedCreatables[groupIdx] = cl.Index
}

func (l *testLedger) GetCreatableID(groupIdx int) basics.CreatableIndex {
	return l.trackedCreatables[groupIdx]
}

func (l *testLedger) AssetHolding(addr basics.Address, assetID basics.AssetIndex) (basics.AssetHolding, error) {
	if br, ok := l.balances[addr]; ok {
		if asset, ok := br.holdings[assetID]; ok {
			return asset, nil
		}
		return basics.AssetHolding{}, fmt.Errorf("No asset for account")
	}
	return basics.AssetHolding{}, fmt.Errorf("no such address")
}

func (l *testLedger) AssetParams(assetID basics.AssetIndex) (basics.AssetParams, basics.Address, error) {
	if asset, ok := l.assets[assetID]; ok {
		return asset.AssetParams, asset.Creator, nil
	}
	return basics.AssetParams{}, basics.Address{}, fmt.Errorf("no such asset")
}

func (l *testLedger) AppParams(appID basics.AppIndex) (basics.AppParams, basics.Address, error) {
	if app, ok := l.applications[appID]; ok {
		return app.AppParams, app.Creator, nil
	}
	return basics.AppParams{}, basics.Address{}, fmt.Errorf("no such app")
}

func (l *testLedger) ApplicationID() basics.AppIndex {
	return l.appID
}

func (l *testLedger) CreatorAddress() basics.Address {
	return l.creatorAddr
}

func (l *testLedger) LocalSchema() basics.StateSchema {
	return basics.StateSchema{
		NumUint:      100,
		NumByteSlice: 100,
	}
}

func (l *testLedger) GlobalSchema() basics.StateSchema {
	return basics.StateSchema{
		NumUint:      100,
		NumByteSlice: 100,
	}
}

func (l *testLedger) GetDelta(txn *transactions.Transaction) (evalDelta basics.EvalDelta, err error) {
	if tkv, ok := l.mods[l.appID]; ok {
		evalDelta.GlobalDelta = tkv
	}
	if len(txn.Accounts) > 0 {
		accounts := make(map[basics.Address]int)
		accounts[txn.Sender] = 0
		for idx, addr := range txn.Accounts {
			accounts[addr] = idx + 1
		}
		evalDelta.LocalDeltas = make(map[uint64]basics.StateDelta)
		for addr, br := range l.balances {
			if idx, ok := accounts[addr]; ok {
				if delta, ok := br.mods[l.appID]; ok {
					evalDelta.LocalDeltas[uint64(idx)] = delta
				}
			}
		}
	}
	evalDelta.Logs = l.logs
	return
}

func (l *testLedger) AppendLog(txn *transactions.Transaction, value string) error {

	appIdx, err := txn.IndexByAppID(l.appID)
	if err != nil {
		return err
	}
	_, ok := l.applications[l.appID]
	if !ok {
		return fmt.Errorf("no such app")
	}

	l.logs = append(l.logs, basics.LogItem{ID: appIdx, Message: value})
	return nil
}

func TestEvalModes(t *testing.T) {
	partitiontest.PartitionTest(t)

	t.Parallel()
	// ed25519verify and err are tested separately below

	// check modeAny (TEAL v1 + txna/gtxna) are available in RunModeSignature
	// check all opcodes available in runModeApplication
	opcodesRunModeAny := `intcblock 0 1 1 1 1 5 100
	bytecblock 0x414c474f 0x1337 0x2001 0xdeadbeef 0x70077007
bytec 0
sha256
keccak256
sha512_256
len
intc_0
+
intc_1
-
intc_2
/
intc_3
*
intc 4
<
intc_1
>
intc_1
<=
intc_1
>=
intc_1
&&
intc_1
||
bytec_1
bytec_2
!=
bytec_3
bytec 4
==
!
itob
btoi
%	// use values left after bytes comparison
|
intc_1
&
txn Fee
^
global MinTxnFee
~
gtxn 0 LastValid
mulw
pop
store 0
load 0
bnz label
label:
dup
pop
txna Accounts 0
gtxna 0 ApplicationArgs 0
==
`
	opcodesRunModeSignature := `arg_0
arg_1
!=
arg_2
arg_3
!=
&&
txn Sender
arg 4
!=
&&
!=
&&
`

	opcodesRunModeApplication := `int 0
balance
&&
int 0
min_balance
&&
intc_0
intc 6  // 100
app_opted_in
&&
intc_0
bytec_0 // ALGO
intc_1
app_local_put
bytec_0
intc_1
app_global_put
intc_0
intc 6
bytec_0
app_local_get_ex
pop
&&
int 0
bytec_0
app_global_get_ex
pop
&&
intc_0
bytec_0
app_local_del
bytec_0
app_global_del
intc_0
intc 5 // 5
asset_holding_get AssetBalance
pop
&&
intc_0
asset_params_get AssetTotal
pop
&&
!=
bytec_0
log
`
	type desc struct {
		source string
		eval   func([]byte, EvalParams) (bool, error)
		check  func([]byte, EvalParams) error
	}
	tests := map[runMode]desc{
		runModeSignature: {
			source: opcodesRunModeAny + opcodesRunModeSignature,
			eval:   func(program []byte, ep EvalParams) (bool, error) { return Eval(program, ep) },
			check:  func(program []byte, ep EvalParams) error { return Check(program, ep) },
		},
		runModeApplication: {
			source: opcodesRunModeAny + opcodesRunModeApplication,
			eval:   func(program []byte, ep EvalParams) (bool, error) { return EvalStateful(program, ep) },
			check:  func(program []byte, ep EvalParams) error { return CheckStateful(program, ep) },
		},
	}

	txn := makeSampleTxn()
	txgroup := makeSampleTxnGroup(txn)
	txn.Lsig.Args = [][]byte{
		txn.Txn.Sender[:],
		txn.Txn.Receiver[:],
		txn.Txn.CloseRemainderTo[:],
		txn.Txn.VotePK[:],
		txn.Txn.SelectionPK[:],
		txn.Txn.Note,
	}
	params := basics.AssetParams{
		Total:         1000,
		Decimals:      2,
		DefaultFrozen: false,
		UnitName:      "ALGO",
		AssetName:     "",
		URL:           string(protocol.PaymentTx),
		Manager:       txn.Txn.Sender,
		Reserve:       txn.Txn.Receiver,
		Freeze:        txn.Txn.Receiver,
		Clawback:      txn.Txn.Receiver,
	}
	algoValue := basics.TealValue{Type: basics.TealUintType, Uint: 0x77}
	ledger := makeTestLedger(
		map[basics.Address]uint64{
			txn.Txn.Sender: 1,
		},
	)
	ledger.newApp(txn.Txn.Sender, 100, basics.AppParams{})
	ledger.balances[txn.Txn.Sender].locals[100]["ALGO"] = algoValue
	ledger.newAsset(txn.Txn.Sender, 5, params)

	for mode, test := range tests {
		t.Run(fmt.Sprintf("opcodes_mode=%d", mode), func(t *testing.T) {
			ops := testProg(t, test.source, AssemblerMaxVersion)
			sb := strings.Builder{}
			ep := defaultEvalParams(&sb, &txn)
			ep.TxnGroup = txgroup
			ep.Ledger = ledger
			ep.Txn.Txn.ApplicationID = 100
			ep.Txn.Txn.ForeignAssets = []basics.AssetIndex{5} // needed since v4

			err := test.check(ops.Program, ep)
			require.NoError(t, err)
			_, err = test.eval(ops.Program, ep)
			if err != nil {
				t.Log(hex.EncodeToString(ops.Program))
				t.Log(sb.String())
			}
			require.NoError(t, err)
		})
	}

	// check err opcode work in both modes
	for mode, test := range tests {
		t.Run(fmt.Sprintf("err_mode=%d", mode), func(t *testing.T) {
			source := "err"
			ops, err := AssembleStringWithVersion(source, AssemblerMaxVersion)
			require.NoError(t, err)
			ep := defaultEvalParams(nil, nil)
			err = test.check(ops.Program, ep)
			require.NoError(t, err)
			_, err = test.eval(ops.Program, ep)
			require.Error(t, err)
			require.NotContains(t, err.Error(), "not allowed in current mode")
			require.Contains(t, err.Error(), "err opcode")
		})
	}

	// check that ed25519verify and arg is not allowed in stateful mode between v2-v4
	disallowedV4 := []string{
		"byte 0x01\nbyte 0x01\nbyte 0x01\ned25519verify",
		"arg 0",
		"arg_0",
		"arg_1",
		"arg_2",
		"arg_3",
	}
	for _, source := range disallowedV4 {
		ops := testProg(t, source, 4)
		ep := defaultEvalParams(nil, nil)
		err := CheckStateful(ops.Program, ep)
		require.Error(t, err)
		_, err = EvalStateful(ops.Program, ep)
		require.Error(t, err)
		require.Contains(t, err.Error(), "not allowed in current mode")
	}

	// check that arg is not allowed in stateful mode beyond v5
	disallowed := []string{
		"arg 0",
		"arg_0",
		"arg_1",
		"arg_2",
		"arg_3",
	}
	for _, source := range disallowed {
		ops := testProg(t, source, AssemblerMaxVersion)
		ep := defaultEvalParams(nil, nil)
		err := CheckStateful(ops.Program, ep)
		require.Error(t, err)
		_, err = EvalStateful(ops.Program, ep)
		require.Error(t, err)
		require.Contains(t, err.Error(), "not allowed in current mode")
	}

	// check stateful opcodes are not allowed in stateless mode
	statefulOpcodeCalls := []string{
		"int 0\nbalance",
		"int 0\nmin_balance",
		"int 0\nint 0\napp_opted_in",
		"int 0\nint 0\nbyte 0x01\napp_local_get_ex",
		"byte 0x01\napp_global_get",
		"int 0\nbyte 0x01\napp_global_get_ex",
		"int 1\nbyte 0x01\nbyte 0x01\napp_local_put",
		"byte 0x01\nint 0\napp_global_put",
		"int 0\nbyte 0x01\napp_local_del",
		"byte 0x01\napp_global_del",
		"int 0\nint 0\nasset_holding_get AssetFrozen",
		"int 0\nint 0\nasset_params_get AssetManager",
		"int 0\nint 0\napp_params_get AppApprovalProgram",
		"byte 0x01\nlog",
	}

	for _, source := range statefulOpcodeCalls {
		ops := testProg(t, source, AssemblerMaxVersion)
		ep := defaultEvalParams(nil, nil)
		err := Check(ops.Program, ep)
		require.Error(t, err)
		_, err = Eval(ops.Program, ep)
		require.Error(t, err)
		require.Contains(t, err.Error(), "not allowed in current mode")
	}

	require.Equal(t, runMode(1), runModeSignature)
	require.Equal(t, runMode(2), runModeApplication)
	require.True(t, modeAny == runModeSignature|runModeApplication)
	require.True(t, modeAny.Any())
}

func TestBalance(t *testing.T) {
	partitiontest.PartitionTest(t)

	t.Parallel()

	ep, ledger := makeSampleEnv()
	text := "int 2; balance; int 177; =="
	ledger.newAccount(ep.Txn.Txn.Receiver, 177)
	testApp(t, text, ep, "invalid Account reference")

	text = `int 1; balance; int 177; ==`
	testApp(t, text, ep)

	text = `txn Accounts 1; balance; int 177; ==;`
	// won't assemble in old version teal
	testProg(t, text, directRefEnabledVersion-1, expect{2, "balance arg 0 wanted type uint64..."})
	// but legal after that
	testApp(t, text, ep)

	text = "int 0; balance; int 13; =="
	var addr basics.Address
	copy(addr[:], []byte("aoeuiaoeuiaoeuiaoeuiaoeuiaoeui02"))
	ledger.newAccount(addr, 13)
	testApp(t, text, ep, "failed to fetch balance")

	ledger.newAccount(ep.Txn.Txn.Sender, 13)
	testApp(t, text, ep)
}

func testApp(t *testing.T, program string, ep EvalParams, problems ...string) basics.EvalDelta {
	ops := testProg(t, program, ep.Proto.LogicSigVersion)
	err := CheckStateful(ops.Program, ep)
	require.NoError(t, err)

	// we only use this to test stateful apps.  While, I suppose
	// it's *legal* to have an app with no stateful ops, this
	// convenience routine can assume it, and check it.
	pass, err := Eval(ops.Program, ep)
	require.Error(t, err)
	require.Contains(t, err.Error(), "not allowed in current mode")
	require.False(t, pass)

	sb := &strings.Builder{}
	ep.Trace = sb
	pass, err = EvalStateful(ops.Program, ep)
	if len(problems) == 0 {
		require.NoError(t, err, sb.String())
		require.True(t, pass, sb.String())
		delta, err := ep.Ledger.GetDelta(&ep.Txn.Txn)
		require.NoError(t, err)
		return delta
	}

	require.Error(t, err, sb.String())
	for _, problem := range problems {
		require.Contains(t, err.Error(), problem)
	}
	if ep.Ledger != nil {
		delta, err := ep.Ledger.GetDelta(&ep.Txn.Txn)
		require.NoError(t, err)
		require.Empty(t, delta.GlobalDelta)
		require.Empty(t, delta.LocalDeltas)
		require.Empty(t, delta.Logs)
		return delta
	}
	return basics.EvalDelta{}
}

func TestMinBalance(t *testing.T) {
	partitiontest.PartitionTest(t)

	t.Parallel()

	ep, ledger := makeSampleEnv()

	ledger.newAccount(ep.Txn.Txn.Sender, 234)
	ledger.newAccount(ep.Txn.Txn.Receiver, 123)

	testApp(t, "int 0; min_balance; int 1001; ==", ep)
	// Sender makes an asset, min balance goes up
	ledger.newAsset(ep.Txn.Txn.Sender, 7, basics.AssetParams{Total: 1000})
	testApp(t, "int 0; min_balance; int 2002; ==", ep)
	schemas := makeApp(1, 2, 3, 4)
	ledger.newApp(ep.Txn.Txn.Sender, 77, schemas)
	// create + optin + 10 schema base + 4 ints + 6 bytes (local
	// and global count b/c newApp opts the creator in)
	minb := 2*1002 + 10*1003 + 4*1004 + 6*1005
	testApp(t, fmt.Sprintf("int 0; min_balance; int %d; ==", 2002+minb), ep)
	// request extra program pages, min balance increase
	app := ledger.applications[77]
	app.ExtraProgramPages = 2
	ledger.applications[77] = app
	minb += 2 * 1002
	testApp(t, fmt.Sprintf("int 0; min_balance; int %d; ==", 2002+minb), ep)

	testApp(t, "int 1; min_balance; int 1001; ==", ep) // 1 == Accounts[0]
	testProg(t, "txn Accounts 1; min_balance; int 1001; ==", directRefEnabledVersion-1,
		expect{2, "min_balance arg 0 wanted type uint64..."})
	testProg(t, "txn Accounts 1; min_balance; int 1001; ==", directRefEnabledVersion)
	testApp(t, "txn Accounts 1; min_balance; int 1001; ==", ep) // 1 == Accounts[0]
	// Receiver opts in
	ledger.setHolding(ep.Txn.Txn.Receiver, 7, 1, true)
	testApp(t, "int 1; min_balance; int 2002; ==", ep) // 1 == Accounts[0]

	testApp(t, "int 2; min_balance; int 1001; ==", ep, "invalid Account reference 2")

}

func TestAppCheckOptedIn(t *testing.T) {
	partitiontest.PartitionTest(t)

	t.Parallel()

	txn := makeSampleTxn()
	txgroup := makeSampleTxnGroup(txn)
	now := defaultEvalParams(nil, nil)
	now.Txn = &txn
	now.TxnGroup = txgroup
	pre := defaultEvalParamsWithVersion(nil, nil, directRefEnabledVersion-1)
	pre.Txn = &txn
	pre.TxnGroup = txgroup
	testApp(t, "int 2; int 100; app_opted_in; int 1; ==", now, "ledger not available")

	ledger := makeTestLedger(
		map[basics.Address]uint64{
			txn.Txn.Receiver: 1,
			txn.Txn.Sender:   1,
		},
	)
	now.Ledger = ledger
	pre.Ledger = ledger
	testApp(t, "int 2; int 100; app_opted_in; int 1; ==", now, "invalid Account reference")

	// Receiver is not opted in
	testApp(t, "int 1; int 100; app_opted_in; int 0; ==", now)
	//testApp(t, "int 1; int 3; app_opted_in; int 0; ==", now)
	//testApp(t, "int 1; int 3; app_opted_in; int 0; ==", pre) // not an indirect reference though: app 3

	// Sender is not opted in
	testApp(t, "int 0; int 100; app_opted_in; int 0; ==", now)

	// Receiver opted in
	ledger.newApp(txn.Txn.Receiver, 100, basics.AppParams{})
	testApp(t, "int 1; int 100; app_opted_in; int 1; ==", now)
	testApp(t, "int 1; int 2; app_opted_in; int 1; ==", now)
	testApp(t, "int 1; int 2; app_opted_in; int 0; ==", pre) // in pre, int 2 is an actual app id
	testApp(t, "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui01\"; int 2; app_opted_in; int 1; ==", now)
	testProg(t, "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui01\"; int 2; app_opted_in; int 1; ==", directRefEnabledVersion-1,
		expect{3, "app_opted_in arg 0 wanted type uint64..."})

	// Sender opted in
	ledger.newApp(txn.Txn.Sender, 100, basics.AppParams{})
	testApp(t, "int 0; int 100; app_opted_in; int 1; ==", now)
}

func TestAppReadLocalState(t *testing.T) {
	partitiontest.PartitionTest(t)

	t.Parallel()

	text := `int 2  // account idx
int 100 // app id
txn ApplicationArgs 0
app_local_get_ex
bnz exist
int 0
==
bnz exit
exist:
err
exit:
int 1
==`

	txn := makeSampleTxn()
	txgroup := makeSampleTxnGroup(txn)
	now := defaultEvalParams(nil, nil)
	now.Txn = &txn
	now.TxnGroup = txgroup
	pre := defaultEvalParamsWithVersion(nil, nil, directRefEnabledVersion-1)
	pre.Txn = &txn
	pre.TxnGroup = txgroup

	testApp(t, text, now, "ledger not available")

	ledger := makeTestLedger(
		map[basics.Address]uint64{
			txn.Txn.Receiver: 1,
		},
	)
	now.Ledger = ledger
	pre.Ledger = ledger
	testApp(t, text, now, "invalid Account reference")

	text = `int 1  // account idx
int 100 // app id
txn ApplicationArgs 0
app_local_get_ex
bnz exist
int 0
==
bnz exit
exist:
err
exit:
int 1`

	testApp(t, text, now, "no app for account")

	// Make a different app (not 100)
	ledger.newApp(txn.Txn.Receiver, 9999, basics.AppParams{})
	testApp(t, text, now, "no app for account")

	// create the app and check the value from ApplicationArgs[0] (protocol.PaymentTx) does not exist
	ledger.newApp(txn.Txn.Receiver, 100, basics.AppParams{})
	testApp(t, text, now)

	text = `int 1  // account idx
int 100 // app id
txn ApplicationArgs 0
app_local_get_ex
bnz exist
err
exist:
byte 0x414c474f
==`
	ledger.balances[txn.Txn.Receiver].locals[100][string(protocol.PaymentTx)] = basics.TealValue{Type: basics.TealBytesType, Bytes: "ALGO"}

	testApp(t, text, now)
	testApp(t, strings.Replace(text, "int 1  // account idx", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui01\"", -1), now)
	testProg(t, strings.Replace(text, "int 1  // account idx", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui01\"", -1), directRefEnabledVersion-1,
		expect{4, "app_local_get_ex arg 0 wanted type uint64..."})
	testApp(t, strings.Replace(text, "int 100 // app id", "int 2", -1), now)
	// Next we're testing if the use of the current app's id works
	// as a direct reference. The error is because the sender
	// account is not opted into 123.
	ledger.appID = basics.AppIndex(123)
	testApp(t, strings.Replace(text, "int 100 // app id", "int 123", -1), now, "no app for account")
	testApp(t, strings.Replace(text, "int 100 // app id", "int 2", -1), pre, "no app for account")
	testApp(t, strings.Replace(text, "int 100 // app id", "int 9", -1), now, "invalid App reference 9")
	testApp(t, strings.Replace(text, "int 1  // account idx", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui00\"", -1), now,
		"no such address")

	// check special case account idx == 0 => sender
	ledger.newApp(txn.Txn.Sender, 100, basics.AppParams{})
	text = `int 0  // account idx
int 100 // app id
txn ApplicationArgs 0
app_local_get_ex
bnz exist
err
exist:
byte 0x414c474f
==`

	ledger.balances[txn.Txn.Sender].locals[100][string(protocol.PaymentTx)] = basics.TealValue{Type: basics.TealBytesType, Bytes: "ALGO"}
	testApp(t, text, now)
	testApp(t, strings.Replace(text, "int 0  // account idx", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui00\"", -1), now)
	testApp(t, strings.Replace(text, "int 0  // account idx", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui02\"", -1), now,
		"invalid Account reference")

	// check reading state of other app
	ledger.newApp(txn.Txn.Sender, 56, basics.AppParams{})
	ledger.newApp(txn.Txn.Sender, 100, basics.AppParams{})
	text = `int 0  // account idx
int 56 // app id
txn ApplicationArgs 0
app_local_get_ex
bnz exist
err
exist:
byte 0x414c474f
==`

	ledger.balances[txn.Txn.Sender].locals[56][string(protocol.PaymentTx)] = basics.TealValue{Type: basics.TealBytesType, Bytes: "ALGO"}
	testApp(t, text, now)

	// check app_local_get
	text = `int 0  // account idx
txn ApplicationArgs 0
app_local_get
byte 0x414c474f
==`

	ledger.balances[txn.Txn.Sender].locals[100][string(protocol.PaymentTx)] = basics.TealValue{Type: basics.TealBytesType, Bytes: "ALGO"}
	testApp(t, text, now)
	testApp(t, strings.Replace(text, "int 0  // account idx", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui00\"", -1), now)
	testProg(t, strings.Replace(text, "int 0  // account idx", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui00\"", -1), directRefEnabledVersion-1,
		expect{3, "app_local_get arg 0 wanted type uint64..."})
	testApp(t, strings.Replace(text, "int 0  // account idx", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui01\"", -1), now)
	testApp(t, strings.Replace(text, "int 0  // account idx", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui02\"", -1), now,
		"invalid Account reference")

	// check app_local_get default value
	text = `int 0  // account idx
byte 0x414c474f
app_local_get
int 0
==`

	ledger.balances[txn.Txn.Sender].locals[100][string(protocol.PaymentTx)] = basics.TealValue{Type: basics.TealBytesType, Bytes: "ALGO"}
	testApp(t, text, now)
}

func TestAppReadGlobalState(t *testing.T) {
	partitiontest.PartitionTest(t)

	t.Parallel()

	text := `int 0
txn ApplicationArgs 0
app_global_get_ex
bnz exist
err
exist:
byte 0x414c474f
==
int 1  // ForeignApps index
txn ApplicationArgs 0
app_global_get_ex
bnz exist1
err
exist1:
byte 0x414c474f
==
&&
txn ApplicationArgs 0
app_global_get
byte 0x414c474f
==
&&
`
	txn := makeSampleTxn()
	txgroup := makeSampleTxnGroup(txn)
	now := defaultEvalParams(nil, nil)
	now.Txn = &txn
	now.TxnGroup = txgroup
	pre := defaultEvalParamsWithVersion(nil, nil, directRefEnabledVersion-1)
	pre.Txn = &txn
	pre.TxnGroup = txgroup

	testApp(t, text, now, "ledger not available")

	ledger := makeTestLedger(
		map[basics.Address]uint64{
			txn.Txn.Sender: 1,
		},
	)
	now.Ledger = ledger
	pre.Ledger = ledger

	now.Txn.Txn.ApplicationID = 100
	now.Txn.Txn.ForeignApps = []basics.AppIndex{now.Txn.Txn.ApplicationID}
	testApp(t, text, now, "no such app")

	// create the app and check the value from ApplicationArgs[0] (protocol.PaymentTx) does not exist
	ledger.newApp(txn.Txn.Sender, 100, basics.AppParams{})

	testApp(t, text, now, "err opcode")

	ledger.applications[100].GlobalState[string(protocol.PaymentTx)] = basics.TealValue{Type: basics.TealBytesType, Bytes: "ALGO"}

	testApp(t, text, now)

	// check error on invalid app index for app_global_get_ex
	text = "int 2; txn ApplicationArgs 0; app_global_get_ex"
	testApp(t, text, now, "invalid App reference 2")
	// check that actual app id ok instead of indirect reference
	text = "int 100; txn ApplicationArgs 0; app_global_get_ex; int 1; ==; assert; byte 0x414c474f; =="
	testApp(t, text, now)
	testApp(t, text, pre, "invalid App reference 100") // but not in old teal

	// check app_global_get default value
	text = "byte 0x414c474f55; app_global_get; int 0; =="

	ledger.balances[txn.Txn.Sender].locals[100][string(protocol.PaymentTx)] = basics.TealValue{Type: basics.TealBytesType, Bytes: "ALGO"}
	testApp(t, text, now)

	text = `
byte 0x41414141
int 4141
app_global_put
int 1  // ForeignApps index
byte 0x41414141
app_global_get_ex
bnz exist
err
exist:
int 4141
==
`
	// check that even during application creation (Txn.ApplicationID == 0)
	// we will use the the kvCow if the exact application ID (100) is
	// specified in the transaction
	now.Txn.Txn.ApplicationID = 0
	now.Txn.Txn.ForeignApps = []basics.AppIndex{100}
	testApp(t, text, now)

	// Direct reference to the current app also works
	ledger.appID = basics.AppIndex(100)
	now.Txn.Txn.ForeignApps = []basics.AppIndex{}
	testApp(t, strings.Replace(text, "int 1  // ForeignApps index", "int 100", -1), now)
	testApp(t, strings.Replace(text, "int 1  // ForeignApps index", "global CurrentApplicationID", -1), now)
}

const assetsTestTemplate = `int 0//account
int 55
asset_holding_get AssetBalance
!
bnz error
int 123
==
int 0//account
int 55
asset_holding_get AssetFrozen
!
bnz error
int 1
==
&&
int 0//params
asset_params_get AssetTotal
!
bnz error
int 1000
==
&&
int 0//params
asset_params_get AssetDecimals
!
bnz error
int 2
==
&&
int 0//params
asset_params_get AssetDefaultFrozen
!
bnz error
int 0
==
&&
int 0//params
asset_params_get AssetUnitName
!
bnz error
byte 0x414c474f
==
&&
int 0//params
asset_params_get AssetName
!
bnz error
len
int 0
==
&&
int 0//params
asset_params_get AssetURL
!
bnz error
txna ApplicationArgs 0
==
&&
int 0//params
asset_params_get AssetMetadataHash
!
bnz error
byte 0x0000000000000000000000000000000000000000000000000000000000000000
==
&&
int 0//params
asset_params_get AssetManager
!
bnz error
txna Accounts 0
==
&&
int 0//params
asset_params_get AssetReserve
!
bnz error
txna Accounts 1
==
&&
int 0//params
asset_params_get AssetFreeze
!
bnz error
txna Accounts 1
==
&&
int 0//params
asset_params_get AssetClawback
!
bnz error
txna Accounts 1
==
&&
bnz ok
error:
err
ok:
%s
int 1
`

const v5extras = `
int 0//params
asset_params_get AssetCreator
pop
txn Sender
==
assert
`

func TestAssets(t *testing.T) {
	partitiontest.PartitionTest(t)

	t.Parallel()
	tests := map[uint64]string{
		4: fmt.Sprintf(assetsTestTemplate, ""),
		5: fmt.Sprintf(assetsTestTemplate, v5extras),
	}

	for v, source := range tests {
		testAssetsByVersion(t, source, v)
	}
}

func testAssetsByVersion(t *testing.T, assetsTestProgram string, version uint64) {
	for _, field := range AssetHoldingFieldNames {
		fs := assetHoldingFieldSpecByName[field]
		if fs.version <= version && !strings.Contains(assetsTestProgram, field) {
			t.Errorf("TestAssets missing field %v", field)
		}
	}
	for _, field := range AssetParamsFieldNames {
		fs := assetParamsFieldSpecByName[field]
		if fs.version <= version && !strings.Contains(assetsTestProgram, field) {
			t.Errorf("TestAssets missing field %v", field)
		}
	}

	txn := makeSampleTxn()
	pre := defaultEvalParamsWithVersion(nil, &txn, directRefEnabledVersion-1)
	require.GreaterOrEqual(t, version, uint64(directRefEnabledVersion))
	now := defaultEvalParamsWithVersion(nil, &txn, version)
	ledger := makeTestLedger(
		map[basics.Address]uint64{
			txn.Txn.Sender: 1,
		},
	)
	pre.Ledger = ledger
	now.Ledger = ledger

	// bear in mind: the sample transaction has ForeignAccounts{55,77}
	testApp(t, "int 5; int 55; asset_holding_get AssetBalance", now, "invalid Account reference 5")
	// was legal to get balance on a non-ForeignAsset
	testApp(t, "int 0; int 54; asset_holding_get AssetBalance; ==", pre)
	// but not since directRefEnabledVersion
	testApp(t, "int 0; int 54; asset_holding_get AssetBalance", now, "invalid Asset reference 54")

	// it wasn't legal to use a direct ref for account
	testProg(t, `byte "aoeuiaoeuiaoeuiaoeuiaoeuiaoeui00"; int 54; asset_holding_get AssetBalance`,
		directRefEnabledVersion-1, expect{3, "asset_holding_get AssetBalance arg 0 wanted type uint64..."})
	// but it is now (empty asset yields 0,0 on stack)
	testApp(t, `byte "aoeuiaoeuiaoeuiaoeuiaoeuiaoeui00"; int 55; asset_holding_get AssetBalance; ==`, now)
	// This is receiver, who is in Assets array
	testApp(t, `byte "aoeuiaoeuiaoeuiaoeuiaoeuiaoeui01"; int 55; asset_holding_get AssetBalance; ==`, now)
	// But this is not in Assets, so illegal
	testApp(t, `byte "aoeuiaoeuiaoeuiaoeuiaoeuiaoeui02"; int 55; asset_holding_get AssetBalance; ==`, now, "invalid")

	// for params get, presence in ForeignAssets has always be required
	testApp(t, "int 5; asset_params_get AssetTotal", pre, "invalid Asset reference 5")
	testApp(t, "int 5; asset_params_get AssetTotal", now, "invalid Asset reference 5")

	params := basics.AssetParams{
		Total:         1000,
		Decimals:      2,
		DefaultFrozen: false,
		UnitName:      "ALGO",
		AssetName:     "",
		URL:           string(protocol.PaymentTx),
		Manager:       txn.Txn.Sender,
		Reserve:       txn.Txn.Receiver,
		Freeze:        txn.Txn.Receiver,
		Clawback:      txn.Txn.Receiver,
	}

	ledger.newAsset(txn.Txn.Sender, 55, params)
	ledger.setHolding(txn.Txn.Sender, 55, 123, true)
	// For consistency you can now use an indirect ref in holding_get
	// (recall ForeignAssets[0] = 55, which has balance 123)
	testApp(t, "int 0; int 0; asset_holding_get AssetBalance; int 1; ==; assert; int 123; ==", now)
	// but previous code would still try to read ASA 0
	testApp(t, "int 0; int 0; asset_holding_get AssetBalance; int 0; ==; assert; int 0; ==", pre)

	testApp(t, assetsTestProgram, now)

	// In current versions, can swap out the account index for the account
	testApp(t, strings.Replace(assetsTestProgram, "int 0//account", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui00\"", -1), now)
	// Or an asset index for the asset id
	testApp(t, strings.Replace(assetsTestProgram, "int 0//params", "int 55", -1), now)
	// Or an index for the asset id
	testApp(t, strings.Replace(assetsTestProgram, "int 55", "int 0", -1), now)

	// but old code cannot
	testProg(t, strings.Replace(assetsTestProgram, "int 0//account", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui00\"", -1), directRefEnabledVersion-1, expect{3, "asset_holding_get AssetBalance arg 0 wanted type uint64..."})

	if version < 5 {
		// Can't run these with AppCreator anyway
		testApp(t, strings.Replace(assetsTestProgram, "int 0//params", "int 55", -1), pre, "invalid Asset ref")
		testApp(t, strings.Replace(assetsTestProgram, "int 55", "int 0", -1), pre, "err opcode")
	}

	// check holdings bool value
	source := `intcblock 0 55 1
intc_0  // 0, account idx (txn.Sender)
intc_1  // 55
asset_holding_get AssetFrozen
!
bnz error
intc_0 // 0
==
bnz ok
error:
err
ok:
intc_2 // 1
`
	ledger.setHolding(txn.Txn.Sender, 55, 123, false)
	testApp(t, source, now)

	// check holdings invalid offsets
	ops := testProg(t, source, version)
	require.Equal(t, OpsByName[now.Proto.LogicSigVersion]["asset_holding_get"].Opcode, ops.Program[8])
	ops.Program[9] = 0x02
	_, err := EvalStateful(ops.Program, now)
	require.Error(t, err)
	require.Contains(t, err.Error(), "invalid asset_holding_get field 2")

	// check holdings bool value
	source = `intcblock 0 1
intc_0
asset_params_get AssetDefaultFrozen
!
bnz error
intc_1
==
bnz ok
error:
err
ok:
intc_1
`
	params.DefaultFrozen = true
	ledger.newAsset(txn.Txn.Sender, 55, params)
	testApp(t, source, now)
	// check holdings invalid offsets
	ops = testProg(t, source, version)
	require.Equal(t, OpsByName[now.Proto.LogicSigVersion]["asset_params_get"].Opcode, ops.Program[6])
	ops.Program[7] = 0x20
	_, err = EvalStateful(ops.Program, now)
	require.Error(t, err)
	require.Contains(t, err.Error(), "invalid asset_params_get field 32")

	// check empty string
	source = `intcblock 0 1
intc_0  // foreign asset idx (txn.ForeignAssets[0])
asset_params_get AssetURL
!
bnz error
len
intc_0
==
bnz ok
error:
err
ok:
intc_1
`
	params.URL = ""
	ledger.newAsset(txn.Txn.Sender, 55, params)
	testApp(t, source, now)

	source = `intcblock 1 9
intc_0  // foreign asset idx (txn.ForeignAssets[1])
asset_params_get AssetURL
!
bnz error
len
intc_1
==
bnz ok
error:
err
ok:
intc_0
`
	params.URL = "foobarbaz"
	ledger.newAsset(txn.Txn.Sender, 77, params)
	testApp(t, source, now)

	source = `intcblock 0 1
intc_0
asset_params_get AssetURL
!
bnz error
intc_0
==
bnz ok
error:
err
ok:
intc_1
`
	params.URL = ""
	ledger.newAsset(txn.Txn.Sender, 55, params)
	testApp(t, source, now, "cannot compare ([]byte to uint64)")
}

func TestAppParams(t *testing.T) {
	t.Parallel()
	ep, ledger := makeSampleEnv()
	ledger.newAccount(ep.Txn.Txn.Sender, 1)
	ledger.newApp(ep.Txn.Txn.Sender, 100, basics.AppParams{})

	/* app id is in ForeignApps, but does not exist */
	source := "int 56; app_params_get AppExtraProgramPages; int 0; ==; assert; int 0; =="
	testApp(t, source, ep)
	/* app id is in ForeignApps, but has zero ExtraProgramPages */
	source = "int 100; app_params_get AppExtraProgramPages; int 1; ==; assert; int 0; =="
	testApp(t, source, ep)
}

func TestAppLocalReadWriteDeleteErrors(t *testing.T) {
	partitiontest.PartitionTest(t)

	t.Parallel()

	sourceRead := `intcblock 0 100 0x77 1
bytecblock 0x414c474f 0x414c474f41
intc_0                    // 0, account idx (txn.Sender)
intc_1                    // 100, app id
bytec_0                   // key "ALGO"
app_local_get_ex
!
bnz error
intc_2                    // 0x77
==
intc_0                    // 0
intc_1                    // 100
bytec_1                   // ALGOA
app_local_get_ex
!
bnz error
intc_3                    // 1
==
&&
bnz ok
error:
err
ok:
intc_3                    // 1
`
	sourceWrite := `intcblock 0 100 1
bytecblock 0x414c474f
intc_0                     // 0, account idx (txn.Sender)
bytec_0                    // key "ALGO"
intc_1                     // 100
app_local_put
intc_2                     // 1
`
	sourceDelete := `intcblock 0 100
bytecblock 0x414c474f
intc_0                       // account idx
bytec_0                      // key "ALGO"
app_local_del
intc_1
`
	type test struct {
		source       string
		accNumOffset int
	}

	tests := map[string]test{
		"read":   {sourceRead, 20},
		"write":  {sourceWrite, 13},
		"delete": {sourceDelete, 12},
	}
	for name, test := range tests {
		t.Run(fmt.Sprintf("test=%s", name), func(t *testing.T) {
			source := test.source
			firstCmdOffset := test.accNumOffset

			ops, err := AssembleStringWithVersion(source, AssemblerMaxVersion)
			require.NoError(t, err)

			txn := makeSampleTxn()
			ep := defaultEvalParams(nil, nil)
			ep.Txn = &txn
			ep.Txn.Txn.ApplicationID = 100
			err = CheckStateful(ops.Program, ep)
			require.NoError(t, err)
			_, err = EvalStateful(ops.Program, ep)
			require.Error(t, err)
			require.Contains(t, err.Error(), "ledger not available")

			ledger := makeTestLedger(
				map[basics.Address]uint64{
					txn.Txn.Sender: 1,
				},
			)
			ep.Ledger = ledger

			saved := ops.Program[firstCmdOffset]
			require.Equal(t, OpsByName[0]["intc_0"].Opcode, saved)
			ops.Program[firstCmdOffset] = OpsByName[0]["intc_1"].Opcode
			_, err = EvalStateful(ops.Program, ep)
			require.Error(t, err)
			require.Contains(t, err.Error(), "invalid Account reference 100")

			ops.Program[firstCmdOffset] = saved
			_, err = EvalStateful(ops.Program, ep)
			require.Error(t, err)
			require.Contains(t, err.Error(), "no app for account")

			ledger.newApp(txn.Txn.Sender, 100, basics.AppParams{})

			if name == "read" {
				_, err = EvalStateful(ops.Program, ep)
				require.Error(t, err)
				require.Contains(t, err.Error(), "err opcode") // no such key
			}

			ledger.balances[txn.Txn.Sender].locals[100]["ALGO"] = basics.TealValue{Type: basics.TealUintType, Uint: 0x77}
			ledger.balances[txn.Txn.Sender].locals[100]["ALGOA"] = basics.TealValue{Type: basics.TealUintType, Uint: 1}

			ledger.reset()
			pass, err := EvalStateful(ops.Program, ep)
			require.NoError(t, err)
			require.True(t, pass)
			delta, err := ledger.GetDelta(&ep.Txn.Txn)
			require.NoError(t, err)
			require.Empty(t, delta.GlobalDelta)
			expLocal := 1
			if name == "read" {
				expLocal = 0
			}
			require.Len(t, delta.LocalDeltas, expLocal)
		})
	}
}

func TestAppLocalStateReadWrite(t *testing.T) {
	partitiontest.PartitionTest(t)

	t.Parallel()

	ep := defaultEvalParams(nil, nil)
	txn := makeSampleTxn()
	txn.Txn.ApplicationID = 100
	ep.Txn = &txn
	ledger := makeTestLedger(
		map[basics.Address]uint64{
			txn.Txn.Sender: 1,
		},
	)
	ep.Ledger = ledger
	ledger.newApp(txn.Txn.Sender, 100, basics.AppParams{})

	// write int and bytes values
	source := `int 0 // account
byte 0x414c474f      // key "ALGO"
int 0x77             // value
app_local_put
int 0 				 // account
byte 0x414c474f41    // key "ALGOA"
byte 0x414c474f      // value
app_local_put
int 0                // account
int 100              // app id
byte 0x414c474f41    // key "ALGOA"
app_local_get_ex
bnz exist
err
exist:
byte 0x414c474f
==
int 0                // account
int 100              // app id
byte 0x414c474f      // key "ALGO"
app_local_get_ex
bnz exist2
err
exist2:
int 0x77
==
&&
`
	ops, err := AssembleStringWithVersion(source, AssemblerMaxVersion)
	require.NoError(t, err)
	err = CheckStateful(ops.Program, ep)
	require.NoError(t, err)
	pass, err := EvalStateful(ops.Program, ep)
	require.NoError(t, err)
	require.True(t, pass)
	delta, err := ledger.GetDelta(&ep.Txn.Txn)
	require.NoError(t, err)
	require.Empty(t, 0, delta.GlobalDelta)
	require.Len(t, delta.LocalDeltas, 1)

	require.Len(t, delta.LocalDeltas[0], 2)
	vd := delta.LocalDeltas[0]["ALGO"]
	require.Equal(t, basics.SetUintAction, vd.Action)
	require.Equal(t, uint64(0x77), vd.Uint)

	vd = delta.LocalDeltas[0]["ALGOA"]
	require.Equal(t, basics.SetBytesAction, vd.Action)
	require.Equal(t, "ALGO", vd.Bytes)

	// write same value without writing, expect no local delta
	source = `int 0  // account
byte 0x414c474f       // key
int 0x77              // value
app_local_put
int 0                 // account
int 100               // app id
byte 0x414c474f       // key
app_local_get_ex
bnz exist
err
exist:
int 0x77
==
`
	ledger.reset()
	delete(ledger.balances[txn.Txn.Sender].locals[100], "ALGOA")
	delete(ledger.balances[txn.Txn.Sender].locals[100], "ALGO")

	algoValue := basics.TealValue{Type: basics.TealUintType, Uint: 0x77}
	ledger.balances[txn.Txn.Sender].locals[100]["ALGO"] = algoValue

	ops, err = AssembleStringWithVersion(source, AssemblerMaxVersion)
	require.NoError(t, err)
	err = CheckStateful(ops.Program, ep)
	require.NoError(t, err)
	pass, err = EvalStateful(ops.Program, ep)
	require.NoError(t, err)
	require.True(t, pass)
	delta, err = ledger.GetDelta(&ep.Txn.Txn)
	require.NoError(t, err)
	require.Empty(t, delta.GlobalDelta)
	require.Empty(t, delta.LocalDeltas)

	// write same value after reading, expect no local delta
	source = `int 0  // account
int 100              // app id
byte 0x414c474f      // key
app_local_get_ex
bnz exist
err
exist:
int 0                // account
byte 0x414c474f      // key
int 0x77             // value
app_local_put
int 0                // account
int 100              // app id
byte 0x414c474f      // key
app_local_get_ex
bnz exist2
err
exist2:
==
`
	ledger.reset()
	ledger.balances[txn.Txn.Sender].locals[100]["ALGO"] = algoValue
	delete(ledger.balances[txn.Txn.Sender].locals[100], "ALGOA")

	ops, err = AssembleStringWithVersion(source, AssemblerMaxVersion)
	require.NoError(t, err)
	pass, err = EvalStateful(ops.Program, ep)
	require.NoError(t, err)
	require.True(t, pass)
	delta, err = ledger.GetDelta(&ep.Txn.Txn)
	require.NoError(t, err)
	require.Empty(t, delta.GlobalDelta)
	require.Empty(t, delta.LocalDeltas)

	// write a value and expect local delta change
	source = `int 0  // account
byte 0x414c474f41    // key "ALGOA"
int 0x78             // value
app_local_put
int 1
`
	ledger.reset()
	ledger.balances[txn.Txn.Sender].locals[100]["ALGO"] = algoValue
	delete(ledger.balances[txn.Txn.Sender].locals[100], "ALGOA")

	ops, err = AssembleStringWithVersion(source, AssemblerMaxVersion)
	require.NoError(t, err)
	pass, err = EvalStateful(ops.Program, ep)
	require.NoError(t, err)
	require.True(t, pass)
	delta, err = ledger.GetDelta(&ep.Txn.Txn)
	require.NoError(t, err)
	require.Empty(t, delta.GlobalDelta)
	require.Len(t, delta.LocalDeltas, 1)
	require.Len(t, delta.LocalDeltas[0], 1)
	vd = delta.LocalDeltas[0]["ALGOA"]
	require.Equal(t, basics.SetUintAction, vd.Action)
	require.Equal(t, uint64(0x78), vd.Uint)

	// write a value to existing key and expect delta change and reading the new value
	source = `int 0  // account
byte 0x414c474f      // key "ALGO"
int 0x78             // value
app_local_put
int 0                // account
int 100              // app id
byte 0x414c474f      // key "ALGO"
app_local_get_ex
bnz exist
err
exist:
int 0x78
==
`
	ledger.reset()
	ledger.balances[txn.Txn.Sender].locals[100]["ALGO"] = algoValue
	delete(ledger.balances[txn.Txn.Sender].locals[100], "ALGOA")

	ops, err = AssembleStringWithVersion(source, AssemblerMaxVersion)
	require.NoError(t, err)
	pass, err = EvalStateful(ops.Program, ep)
	require.NoError(t, err)
	require.True(t, pass)
	delta, err = ledger.GetDelta(&ep.Txn.Txn)
	require.NoError(t, err)
	require.Empty(t, delta.GlobalDelta)
	require.Len(t, delta.LocalDeltas, 1)
	require.Len(t, delta.LocalDeltas[0], 1)
	vd = delta.LocalDeltas[0]["ALGO"]
	require.Equal(t, basics.SetUintAction, vd.Action)
	require.Equal(t, uint64(0x78), vd.Uint)

	// write a value after read and expect delta change
	source = `int 0  // account
int 100              // app id
byte 0x414c474f      // key "ALGO"
app_local_get_ex
bnz exist
err
exist:
int 0  				 // account
byte 0x414c474f      // key "ALGO"
int 0x78             // value
app_local_put
`
	ledger.reset()
	ledger.balances[txn.Txn.Sender].locals[100]["ALGO"] = algoValue
	delete(ledger.balances[txn.Txn.Sender].locals[100], "ALGOA")

	ops, err = AssembleStringWithVersion(source, AssemblerMaxVersion)
	require.NoError(t, err)
	pass, err = EvalStateful(ops.Program, ep)
	require.NoError(t, err)
	require.True(t, pass)
	delta, err = ledger.GetDelta(&ep.Txn.Txn)
	require.NoError(t, err)
	require.Empty(t, delta.GlobalDelta)
	require.Len(t, delta.LocalDeltas, 1)
	require.Len(t, delta.LocalDeltas[0], 1)
	vd = delta.LocalDeltas[0]["ALGO"]
	require.Equal(t, basics.SetUintAction, vd.Action)
	require.Equal(t, uint64(0x78), vd.Uint)

	// write a few values and expect delta change only for unique changed
	source = `int 0  // account
byte 0x414c474f      // key "ALGO"
int 0x77             // value
app_local_put
int 0                // account
byte 0x414c474f      // key "ALGO"
int 0x78             // value
app_local_put
int 0                // account
byte 0x414c474f41    // key "ALGOA"
int 0x78             // value
app_local_put
int 1                // account
byte 0x414c474f      // key "ALGO"
int 0x79             // value
app_local_put
int 1
`
	ledger.reset()
	ledger.balances[txn.Txn.Sender].locals[100]["ALGO"] = algoValue
	delete(ledger.balances[txn.Txn.Sender].locals[100], "ALGOA")

	ledger.balances[txn.Txn.Receiver] = makeBalanceRecord(txn.Txn.Receiver, 500)
	ledger.balances[txn.Txn.Receiver].locals[100] = make(basics.TealKeyValue)

	ops, err = AssembleStringWithVersion(source, AssemblerMaxVersion)
	require.NoError(t, err)
	err = CheckStateful(ops.Program, ep)
	require.NoError(t, err)
	pass, err = EvalStateful(ops.Program, ep)
	require.NoError(t, err)
	require.True(t, pass)
	delta, err = ledger.GetDelta(&ep.Txn.Txn)
	require.NoError(t, err)
	require.Empty(t, delta.GlobalDelta)
	require.Len(t, delta.LocalDeltas, 2)
	require.Len(t, delta.LocalDeltas[0], 2)
	require.Len(t, delta.LocalDeltas[1], 1)
	vd = delta.LocalDeltas[0]["ALGO"]
	require.Equal(t, basics.SetUintAction, vd.Action)
	require.Equal(t, uint64(0x78), vd.Uint)

	vd = delta.LocalDeltas[0]["ALGOA"]
	require.Equal(t, basics.SetUintAction, vd.Action)
	require.Equal(t, uint64(0x78), vd.Uint)

	vd = delta.LocalDeltas[1]["ALGO"]
	require.Equal(t, basics.SetUintAction, vd.Action)
	require.Equal(t, uint64(0x79), vd.Uint)
}

func TestAppGlobalReadWriteDeleteErrors(t *testing.T) {
	partitiontest.PartitionTest(t)

	t.Parallel()

	sourceRead := `int 0
byte 0x414c474f  // key "ALGO"
app_global_get_ex
bnz ok
err
ok:
int 0x77
==
`
	sourceReadSimple := `byte 0x414c474f  // key "ALGO"
app_global_get
int 0x77
==
`

	sourceWrite := `byte 0x414c474f  // key "ALGO"
int 100
app_global_put
int 1
`
	sourceDelete := `byte 0x414c474f  // key "ALGO"
app_global_del
int 1
`
	tests := map[string]string{
		"read":   sourceRead,
		"reads":  sourceReadSimple,
		"write":  sourceWrite,
		"delete": sourceDelete,
	}
	for name, source := range tests {
		t.Run(fmt.Sprintf("test=%s", name), func(t *testing.T) {
			ops, err := AssembleStringWithVersion(source, AssemblerMaxVersion)
			require.NoError(t, err)

			txn := makeSampleTxn()
			ep := defaultEvalParams(nil, nil)
			ep.Txn = &txn
			_, err = EvalStateful(ops.Program, ep)
			require.Error(t, err)
			require.Contains(t, err.Error(), "ledger not available")

			ledger := makeTestLedger(
				map[basics.Address]uint64{
					txn.Txn.Sender: 1,
				},
			)
			ep.Ledger = ledger

			txn.Txn.ApplicationID = 100
			_, err = EvalStateful(ops.Program, ep)
			require.Error(t, err)
			require.Contains(t, err.Error(), "no such app")

			ledger.newApp(txn.Txn.Sender, 100, makeApp(0, 0, 1, 0))

			// a special test for read
			if name == "read" {
				_, err = EvalStateful(ops.Program, ep)
				require.Error(t, err)
				require.Contains(t, err.Error(), "err opcode") // no such key
			}
			ledger.applications[100].GlobalState["ALGO"] = basics.TealValue{Type: basics.TealUintType, Uint: 0x77}

			ledger.reset()
			pass, err := EvalStateful(ops.Program, ep)
			require.NoError(t, err)
			require.True(t, pass)
			delta, err := ledger.GetDelta(&ep.Txn.Txn)
			require.NoError(t, err)

			require.Empty(t, delta.LocalDeltas)
		})
	}
}

func TestAppGlobalReadWrite(t *testing.T) {
	partitiontest.PartitionTest(t)

	t.Parallel()

	// check writing ints and bytes
	source := `byte 0x414c474f  // key "ALGO"
int 0x77						// value
app_global_put
byte 0x414c474f41  // key "ALGOA"
byte 0x414c474f    // value
app_global_put
// check simple
byte 0x414c474f41  // key "ALGOA"
app_global_get
byte 0x414c474f
==
// check generic with alias
int 0 // current app id alias
byte 0x414c474f41  // key "ALGOA"
app_global_get_ex
bnz ok
err
ok:
byte 0x414c474f
==
&&
// check generic with exact app id
int 1 // ForeignApps index - current app
byte 0x414c474f41  // key "ALGOA"
app_global_get_ex
bnz ok1
err
ok1:
byte 0x414c474f
==
&&
// check simple
byte 0x414c474f
app_global_get
int 0x77
==
&&
// check generic with alias
int 0 // ForeignApps index - current app
byte 0x414c474f
app_global_get_ex
bnz ok2
err
ok2:
int 0x77
==
&&
// check generic with exact app id
int 1 // ForeignApps index - current app
byte 0x414c474f
app_global_get_ex
bnz ok3
err
ok3:
int 0x77
==
&&
`
	ep := defaultEvalParams(nil, nil)
	txn := makeSampleTxn()
	txn.Txn.ApplicationID = 100
	txn.Txn.ForeignApps = []basics.AppIndex{txn.Txn.ApplicationID}
	ep.Txn = &txn
	ledger := makeTestLedger(
		map[basics.Address]uint64{
			txn.Txn.Sender: 1,
		},
	)
	ep.Ledger = ledger
	ledger.newApp(txn.Txn.Sender, 100, basics.AppParams{})

	ops, err := AssembleStringWithVersion(source, AssemblerMaxVersion)
	require.NoError(t, err)
	err = CheckStateful(ops.Program, ep)
	require.NoError(t, err)
	pass, err := EvalStateful(ops.Program, ep)
	require.NoError(t, err)
	require.True(t, pass)
	delta, err := ledger.GetDelta(&ep.Txn.Txn)
	require.NoError(t, err)

	require.Len(t, delta.GlobalDelta, 2)
	require.Empty(t, delta.LocalDeltas)

	vd := delta.GlobalDelta["ALGO"]
	require.Equal(t, basics.SetUintAction, vd.Action)
	require.Equal(t, uint64(0x77), vd.Uint)

	vd = delta.GlobalDelta["ALGOA"]
	require.Equal(t, basics.SetBytesAction, vd.Action)
	require.Equal(t, "ALGO", vd.Bytes)

	// write existing value before read
	source = `byte 0x414c474f  // key "ALGO"
int 0x77						// value
app_global_put
byte 0x414c474f
app_global_get
int 0x77
==
`
	ledger.reset()
	delete(ledger.applications[100].GlobalState, "ALGOA")
	delete(ledger.applications[100].GlobalState, "ALGO")

	algoValue := basics.TealValue{Type: basics.TealUintType, Uint: 0x77}
	ledger.applications[100].GlobalState["ALGO"] = algoValue

	ops, err = AssembleStringWithVersion(source, AssemblerMaxVersion)
	require.NoError(t, err)
	pass, err = EvalStateful(ops.Program, ep)
	require.NoError(t, err)
	require.True(t, pass)
	delta, err = ledger.GetDelta(&ep.Txn.Txn)
	require.NoError(t, err)

	require.Empty(t, delta.GlobalDelta)
	require.Empty(t, delta.LocalDeltas)

	// write existing value after read
	source = `int 0
byte 0x414c474f
app_global_get_ex
bnz ok
err
ok:
pop
byte 0x414c474f
int 0x77
app_global_put
byte 0x414c474f
app_global_get
int 0x77
==
`
	ledger.reset()
	delete(ledger.applications[100].GlobalState, "ALGOA")
	ledger.applications[100].GlobalState["ALGO"] = algoValue

	ops, err = AssembleStringWithVersion(source, AssemblerMaxVersion)
	require.NoError(t, err)
	pass, err = EvalStateful(ops.Program, ep)
	require.NoError(t, err)
	require.True(t, pass)
	delta, err = ledger.GetDelta(&ep.Txn.Txn)
	require.NoError(t, err)
	require.Empty(t, delta.GlobalDelta)
	require.Empty(t, delta.LocalDeltas)

	// write new values after and before read
	source = `int 0
byte 0x414c474f
app_global_get_ex
bnz ok
err
ok:
pop
byte 0x414c474f
int 0x78
app_global_put
int 0
byte 0x414c474f
app_global_get_ex
bnz ok2
err
ok2:
int 0x78
==
byte 0x414c474f41
byte 0x414c474f
app_global_put
int 0
byte 0x414c474f41
app_global_get_ex
bnz ok3
err
ok3:
byte 0x414c474f
==
&&
`
	ledger.reset()
	delete(ledger.applications[100].GlobalState, "ALGOA")
	ledger.applications[100].GlobalState["ALGO"] = algoValue

	ops, err = AssembleStringWithVersion(source, AssemblerMaxVersion)
	require.NoError(t, err)
	sb := strings.Builder{}
	ep.Trace = &sb
	err = CheckStateful(ops.Program, ep)
	require.NoError(t, err)
	pass, err = EvalStateful(ops.Program, ep)
	if !pass {
		t.Log(hex.EncodeToString(ops.Program))
		t.Log(sb.String())
	}
	require.NoError(t, err)
	require.True(t, pass)
	delta, err = ledger.GetDelta(&ep.Txn.Txn)
	require.NoError(t, err)

	require.Len(t, delta.GlobalDelta, 2)
	require.Empty(t, delta.LocalDeltas)

	vd = delta.GlobalDelta["ALGO"]
	require.Equal(t, basics.SetUintAction, vd.Action)
	require.Equal(t, uint64(0x78), vd.Uint)

	vd = delta.GlobalDelta["ALGOA"]
	require.Equal(t, basics.SetBytesAction, vd.Action)
	require.Equal(t, "ALGO", vd.Bytes)
}

func TestAppGlobalReadOtherApp(t *testing.T) {
	partitiontest.PartitionTest(t)

	t.Parallel()
	source := `int 2 // ForeignApps index
byte "mykey1"
app_global_get_ex
bz ok1
err
ok1:
pop
int 2 // ForeignApps index
byte "mykey"
app_global_get_ex
bnz ok2
err
ok2:
byte "myval"
==
`
	ep := defaultEvalParams(nil, nil)
	txn := makeSampleTxn()
	txn.Txn.ApplicationID = 100
	txn.Txn.ForeignApps = []basics.AppIndex{txn.Txn.ApplicationID, 101}
	ep.Txn = &txn
	ledger := makeTestLedger(
		map[basics.Address]uint64{
			txn.Txn.Sender: 1,
		},
	)
	ep.Ledger = ledger
	ledger.newApp(txn.Txn.Sender, 100, basics.AppParams{})

	delta := testApp(t, source, ep, "no such app")
	require.Empty(t, delta.GlobalDelta)
	require.Empty(t, delta.LocalDeltas)

	ledger.newApp(txn.Txn.Receiver, 101, basics.AppParams{})
	ledger.newApp(txn.Txn.Receiver, 100, basics.AppParams{}) // this keeps current app id = 100
	algoValue := basics.TealValue{Type: basics.TealBytesType, Bytes: "myval"}
	ledger.applications[101].GlobalState["mykey"] = algoValue

	delta = testApp(t, source, ep)
	require.Empty(t, delta.GlobalDelta)
	require.Empty(t, delta.LocalDeltas)
}

func TestBlankKey(t *testing.T) {
	partitiontest.PartitionTest(t)

	t.Parallel()
	source := `
byte ""
app_global_get
int 0
==
assert

byte ""
int 7
app_global_put

byte ""
app_global_get
int 7
==
`
	ep := defaultEvalParams(nil, nil)
	txn := makeSampleTxn()
	txn.Txn.ApplicationID = 100
	ep.Txn = &txn
	ledger := makeTestLedger(
		map[basics.Address]uint64{
			txn.Txn.Sender: 1,
		},
	)
	ep.Ledger = ledger
	ledger.newApp(txn.Txn.Sender, 100, basics.AppParams{})

	delta := testApp(t, source, ep)
	require.Empty(t, delta.LocalDeltas)
}

func TestAppGlobalDelete(t *testing.T) {
	partitiontest.PartitionTest(t)

	t.Parallel()

	// check write/delete/read
	source := `byte 0x414c474f  // key "ALGO"
int 0x77						// value
app_global_put
byte 0x414c474f41  // key "ALGOA"
byte 0x414c474f
app_global_put
byte 0x414c474f
app_global_del
byte 0x414c474f41
app_global_del
int 0
byte 0x414c474f
app_global_get_ex
bnz error
int 0
byte 0x414c474f41
app_global_get_ex
bnz error
==
bnz ok
error:
err
ok:
int 1
`
	ep := defaultEvalParams(nil, nil)
	txn := makeSampleTxn()
	txn.Txn.ApplicationID = 100
	ep.Txn = &txn
	ledger := makeTestLedger(
		map[basics.Address]uint64{
			txn.Txn.Sender: 1,
		},
	)
	ep.Ledger = ledger
	ledger.newApp(txn.Txn.Sender, 100, basics.AppParams{})

	delta := testApp(t, source, ep)
	require.Len(t, delta.GlobalDelta, 2)
	require.Empty(t, delta.LocalDeltas)

	ledger.reset()
	delete(ledger.applications[100].GlobalState, "ALGOA")
	delete(ledger.applications[100].GlobalState, "ALGO")

	algoValue := basics.TealValue{Type: basics.TealUintType, Uint: 0x77}
	ledger.applications[100].GlobalState["ALGO"] = algoValue

	// check delete existing
	source = `byte 0x414c474f   // key "ALGO"
app_global_del
int 1
byte 0x414c474f
app_global_get_ex
==  // two zeros
`
	ep.Txn.Txn.ForeignApps = []basics.AppIndex{txn.Txn.ApplicationID}
	delta = testApp(t, source, ep)
	require.Len(t, delta.GlobalDelta, 1)
	vd := delta.GlobalDelta["ALGO"]
	require.Equal(t, basics.DeleteAction, vd.Action)
	require.Equal(t, uint64(0), vd.Uint)
	require.Equal(t, "", vd.Bytes)
	require.Equal(t, 0, len(delta.LocalDeltas))

	ledger.reset()
	delete(ledger.applications[100].GlobalState, "ALGOA")
	delete(ledger.applications[100].GlobalState, "ALGO")

	ledger.applications[100].GlobalState["ALGO"] = algoValue

	// check delete and write non-existing
	source = `byte 0x414c474f41   // key "ALGOA"
app_global_del
int 0
byte 0x414c474f41
app_global_get_ex
==  // two zeros
byte 0x414c474f41
int 0x78
app_global_put
`
	delta = testApp(t, source, ep)
	require.Len(t, delta.GlobalDelta, 1)
	vd = delta.GlobalDelta["ALGOA"]
	require.Equal(t, basics.SetUintAction, vd.Action)
	require.Equal(t, uint64(0x78), vd.Uint)
	require.Equal(t, "", vd.Bytes)
	require.Empty(t, delta.LocalDeltas)

	ledger.reset()
	delete(ledger.applications[100].GlobalState, "ALGOA")
	delete(ledger.applications[100].GlobalState, "ALGO")

	ledger.applications[100].GlobalState["ALGO"] = algoValue

	// check delete and write existing
	source = `byte 0x414c474f   // key "ALGO"
app_global_del
byte 0x414c474f
int 0x78
app_global_put
int 1
`
	delta = testApp(t, source, ep)
	require.Len(t, delta.GlobalDelta, 1)
	vd = delta.GlobalDelta["ALGO"]
	require.Equal(t, basics.SetUintAction, vd.Action)
	require.Empty(t, delta.LocalDeltas)

	ledger.reset()
	delete(ledger.applications[100].GlobalState, "ALGOA")
	delete(ledger.applications[100].GlobalState, "ALGO")

	ledger.applications[100].GlobalState["ALGO"] = algoValue

	// check delete,write,delete existing
	source = `byte 0x414c474f   // key "ALGO"
app_global_del
byte 0x414c474f
int 0x78
app_global_put
byte 0x414c474f
app_global_del
int 1
`
	delta = testApp(t, source, ep)
	require.Len(t, delta.GlobalDelta, 1)
	vd = delta.GlobalDelta["ALGO"]
	require.Equal(t, basics.DeleteAction, vd.Action)
	require.Empty(t, delta.LocalDeltas)

	ledger.reset()
	delete(ledger.applications[100].GlobalState, "ALGOA")
	delete(ledger.applications[100].GlobalState, "ALGO")

	ledger.applications[100].GlobalState["ALGO"] = algoValue

	// check delete, write, delete non-existing
	source = `byte 0x414c474f41   // key "ALGOA"
app_global_del
byte 0x414c474f41
int 0x78
app_global_put
byte 0x414c474f41
app_global_del
int 1
`
	delta = testApp(t, source, ep)
	require.Len(t, delta.GlobalDelta, 1)
	require.Len(t, delta.LocalDeltas, 0)
}

func TestAppLocalDelete(t *testing.T) {
	partitiontest.PartitionTest(t)

	t.Parallel()

	// check write/delete/read
	source := `int 0 // sender
byte 0x414c474f       // key "ALGO"
int 0x77              // value
app_local_put
int 1
byte 0x414c474f41     // key "ALGOA"
byte 0x414c474f
app_local_put
int 0 // sender
byte 0x414c474f
app_local_del
int 1
byte 0x414c474f41
app_local_del
int 0 // sender
int 0 // app
byte 0x414c474f
app_local_get_ex
bnz error
int 1
int 100
byte 0x414c474f41
app_local_get_ex
bnz error
==
bnz ok
error:
err
ok:
int 1
`
	ep := defaultEvalParams(nil, nil)
	txn := makeSampleTxn()
	txn.Txn.ApplicationID = 100
	ep.Txn = &txn
	ledger := makeTestLedger(
		map[basics.Address]uint64{
			txn.Txn.Sender: 1,
		},
	)
	ep.Ledger = ledger
	ledger.newApp(txn.Txn.Sender, 100, basics.AppParams{})
	ledger.balances[txn.Txn.Receiver] = makeBalanceRecord(txn.Txn.Receiver, 1)
	ledger.balances[txn.Txn.Receiver].locals[100] = make(basics.TealKeyValue)

	sb := strings.Builder{}
	ep.Trace = &sb

	testApp(t, source, ep)
	delta, err := ledger.GetDelta(&ep.Txn.Txn)
	require.NoError(t, err)
	require.Equal(t, 0, len(delta.GlobalDelta))
	require.Equal(t, 2, len(delta.LocalDeltas))

	ledger.reset()
	// test that app_local_put and _app_local_del can use byte addresses
	testApp(t, strings.Replace(source, "int 0 // sender", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui00\"", -1), ep)
	// But won't compile in old teal
	testProg(t, strings.Replace(source, "int 0 // sender", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui00\"", -1), directRefEnabledVersion-1,
		expect{4, "app_local_put arg 0 wanted..."}, expect{11, "app_local_del arg 0 wanted..."})

	delta, err = ledger.GetDelta(&ep.Txn.Txn)
	require.NoError(t, err)
	require.Equal(t, 0, len(delta.GlobalDelta))
	require.Equal(t, 2, len(delta.LocalDeltas))

	ledger.reset()
	delete(ledger.balances[txn.Txn.Sender].locals[100], "ALGOA")
	delete(ledger.balances[txn.Txn.Sender].locals[100], "ALGO")
	delete(ledger.balances[txn.Txn.Receiver].locals[100], "ALGOA")
	delete(ledger.balances[txn.Txn.Receiver].locals[100], "ALGO")

	algoValue := basics.TealValue{Type: basics.TealUintType, Uint: 0x77}
	ledger.balances[txn.Txn.Sender].locals[100]["ALGO"] = algoValue

	// check delete existing
	source = `int 0  // account
byte 0x414c474f      // key "ALGO"
app_local_del
int 0
int 100
byte 0x414c474f
app_local_get_ex
==  // two zeros
`

	testApp(t, source, ep)
	delta, err = ledger.GetDelta(&ep.Txn.Txn)
	require.NoError(t, err)
	require.Equal(t, 0, len(delta.GlobalDelta))
	require.Equal(t, 1, len(delta.LocalDeltas))
	vd := delta.LocalDeltas[0]["ALGO"]
	require.Equal(t, basics.DeleteAction, vd.Action)
	require.Equal(t, uint64(0), vd.Uint)
	require.Equal(t, "", vd.Bytes)

	ledger.reset()
	delete(ledger.balances[txn.Txn.Sender].locals[100], "ALGOA")
	delete(ledger.balances[txn.Txn.Sender].locals[100], "ALGO")

	ledger.balances[txn.Txn.Sender].locals[100]["ALGO"] = algoValue

	// check delete and write non-existing
	source = `int 0  // account
byte 0x414c474f41    // key "ALGOA"
app_local_del
int 0
int 0
byte 0x414c474f41
app_local_get_ex
==  // two zeros
int 0
byte 0x414c474f41
int 0x78
app_local_put
`
	testApp(t, source, ep)
	delta, err = ledger.GetDelta(&ep.Txn.Txn)
	require.NoError(t, err)
	require.Equal(t, 0, len(delta.GlobalDelta))
	require.Equal(t, 1, len(delta.LocalDeltas))
	vd = delta.LocalDeltas[0]["ALGOA"]
	require.Equal(t, basics.SetUintAction, vd.Action)
	require.Equal(t, uint64(0x78), vd.Uint)
	require.Equal(t, "", vd.Bytes)

	ledger.reset()
	delete(ledger.balances[txn.Txn.Sender].locals[100], "ALGOA")
	delete(ledger.balances[txn.Txn.Sender].locals[100], "ALGO")

	ledger.balances[txn.Txn.Sender].locals[100]["ALGO"] = algoValue

	// check delete and write existing
	source = `int 0   // account
byte 0x414c474f       // key "ALGO"
app_local_del
int 0
byte 0x414c474f
int 0x78
app_local_put
int 1
`
	testApp(t, source, ep)
	delta, err = ledger.GetDelta(&ep.Txn.Txn)
	require.NoError(t, err)
	require.Equal(t, 0, len(delta.GlobalDelta))
	require.Equal(t, 1, len(delta.LocalDeltas))
	vd = delta.LocalDeltas[0]["ALGO"]
	require.Equal(t, basics.SetUintAction, vd.Action)
	require.Equal(t, uint64(0x78), vd.Uint)
	require.Equal(t, "", vd.Bytes)

	ledger.reset()
	delete(ledger.balances[txn.Txn.Sender].locals[100], "ALGOA")
	delete(ledger.balances[txn.Txn.Sender].locals[100], "ALGO")

	ledger.balances[txn.Txn.Sender].locals[100]["ALGO"] = algoValue

	// check delete,write,delete existing
	source = `int 0  // account
byte 0x414c474f      // key "ALGO"
app_local_del
int 0
byte 0x414c474f
int 0x78
app_local_put
int 0
byte 0x414c474f
app_local_del
int 1
`
	testApp(t, source, ep)
	delta, err = ledger.GetDelta(&ep.Txn.Txn)
	require.NoError(t, err)
	require.Equal(t, 0, len(delta.GlobalDelta))
	require.Equal(t, 1, len(delta.LocalDeltas))
	vd = delta.LocalDeltas[0]["ALGO"]
	require.Equal(t, basics.DeleteAction, vd.Action)
	require.Equal(t, uint64(0), vd.Uint)
	require.Equal(t, "", vd.Bytes)

	ledger.reset()
	delete(ledger.balances[txn.Txn.Sender].locals[100], "ALGOA")
	delete(ledger.balances[txn.Txn.Sender].locals[100], "ALGO")

	ledger.balances[txn.Txn.Sender].locals[100]["ALGO"] = algoValue

	// check delete, write, delete non-existing
	source = `int 0  // account
byte 0x414c474f41    // key "ALGOA"
app_local_del
int 0
byte 0x414c474f41
int 0x78
app_local_put
int 0
byte 0x414c474f41
app_local_del
int 1
`
	testApp(t, source, ep)
	delta, err = ledger.GetDelta(&ep.Txn.Txn)
	require.NoError(t, err)
	require.Equal(t, 0, len(delta.GlobalDelta))
	require.Equal(t, 1, len(delta.LocalDeltas))
	require.Equal(t, 1, len(delta.LocalDeltas[0]))
}

func TestEnumFieldErrors(t *testing.T) {
	partitiontest.PartitionTest(t)

	ep := defaultEvalParams(nil, nil)

	source := `txn Amount`
	origTxnType := TxnFieldTypes[Amount]
	TxnFieldTypes[Amount] = StackBytes
	defer func() {
		TxnFieldTypes[Amount] = origTxnType
	}()

	ops := testProg(t, source, AssemblerMaxVersion)
	_, err := Eval(ops.Program, ep)
	require.Error(t, err)
	require.Contains(t, err.Error(), "Amount expected field type is []byte but got uint64")
	_, err = EvalStateful(ops.Program, ep)
	require.Error(t, err)
	require.Contains(t, err.Error(), "Amount expected field type is []byte but got uint64")

	source = `global MinTxnFee`

	origMinTxnFs := globalFieldSpecByField[MinTxnFee]
	badMinTxnFs := origMinTxnFs
	badMinTxnFs.ftype = StackBytes
	globalFieldSpecByField[MinTxnFee] = badMinTxnFs
	defer func() {
		globalFieldSpecByField[MinTxnFee] = origMinTxnFs
	}()

	ops = testProg(t, source, AssemblerMaxVersion)
	_, err = Eval(ops.Program, ep)
	require.Error(t, err)
	require.Contains(t, err.Error(), "MinTxnFee expected field type is []byte but got uint64")
	_, err = EvalStateful(ops.Program, ep)
	require.Error(t, err)
	require.Contains(t, err.Error(), "MinTxnFee expected field type is []byte but got uint64")

	txn := makeSampleTxn()
	ledger := makeTestLedger(
		map[basics.Address]uint64{
			txn.Txn.Sender: 1,
		},
	)
	params := basics.AssetParams{
		Total:         1000,
		Decimals:      2,
		DefaultFrozen: false,
		UnitName:      "ALGO",
		AssetName:     "",
		URL:           string(protocol.PaymentTx),
		Manager:       txn.Txn.Sender,
		Reserve:       txn.Txn.Receiver,
		Freeze:        txn.Txn.Receiver,
		Clawback:      txn.Txn.Receiver,
	}
	ledger.newAsset(txn.Txn.Sender, 55, params)

	ep.Txn = &txn
	ep.Ledger = ledger

	source = `int 0
int 55
asset_holding_get AssetBalance
pop
`
	origBalanceFs := assetHoldingFieldSpecByField[AssetBalance]
	badBalanceFs := origBalanceFs
	badBalanceFs.ftype = StackBytes
	assetHoldingFieldSpecByField[AssetBalance] = badBalanceFs
	defer func() {
		assetHoldingFieldSpecByField[AssetBalance] = origBalanceFs
	}()

	ops = testProg(t, source, AssemblerMaxVersion)
	_, err = EvalStateful(ops.Program, ep)
	require.Error(t, err)
	require.Contains(t, err.Error(), "AssetBalance expected field type is []byte but got uint64")

	source = `int 0
asset_params_get AssetTotal
pop
`
	origTotalFs := assetParamsFieldSpecByField[AssetTotal]
	badTotalFs := origTotalFs
	badTotalFs.ftype = StackBytes
	assetParamsFieldSpecByField[AssetTotal] = badTotalFs
	defer func() {
		assetParamsFieldSpecByField[AssetTotal] = origTotalFs
	}()

	ops = testProg(t, source, AssemblerMaxVersion)
	_, err = EvalStateful(ops.Program, ep)
	require.Error(t, err)
	require.Contains(t, err.Error(), "AssetTotal expected field type is []byte but got uint64")
}

func TestReturnTypes(t *testing.T) {
	partitiontest.PartitionTest(t)

	// Ensure all opcodes return values they supposed to according to the OpSpecs table
	t.Parallel()
	typeToArg := map[StackType]string{
		StackUint64: "int 1\n",
		StackAny:    "int 1\n",
		StackBytes:  "byte 0x33343536\n",
	}
	ep := defaultEvalParams(nil, nil)
	txn := makeSampleTxn()
	txn.Txn.Type = protocol.ApplicationCallTx
	txgroup := makeSampleTxnGroup(txn)
	ep.Txn = &txn
	ep.TxnGroup = txgroup
	ep.Txn.Txn.ApplicationID = 1
	ep.Txn.Txn.ForeignApps = []basics.AppIndex{txn.Txn.ApplicationID}
	ep.Txn.Txn.ForeignAssets = []basics.AssetIndex{basics.AssetIndex(1), basics.AssetIndex(1)}
	ep.GroupIndex = 1
	ep.PastSideEffects = MakePastSideEffects(len(txgroup))
	txn.Lsig.Args = [][]byte{
		[]byte("aoeu"),
		[]byte("aoeu"),
		[]byte("aoeu2"),
		[]byte("aoeu3"),
	}
	ledger := makeTestLedger(
		map[basics.Address]uint64{
			txn.Txn.Sender: 1,
		},
	)
	params := basics.AssetParams{
		Total:         1000,
		Decimals:      2,
		DefaultFrozen: false,
		UnitName:      "ALGO",
		AssetName:     "",
		URL:           string(protocol.PaymentTx),
		Manager:       txn.Txn.Sender,
		Reserve:       txn.Txn.Receiver,
		Freeze:        txn.Txn.Receiver,
		Clawback:      txn.Txn.Receiver,
	}
	ledger.newAsset(txn.Txn.Sender, 1, params)
	ledger.newApp(txn.Txn.Sender, 1, basics.AppParams{})
	ledger.setTrackedCreatable(0, basics.CreatableLocator{Index: 1})
	ledger.balances[txn.Txn.Receiver] = makeBalanceRecord(txn.Txn.Receiver, 1)
	ledger.balances[txn.Txn.Receiver].locals[1] = make(basics.TealKeyValue)
	key, err := hex.DecodeString("33343536")
	require.NoError(t, err)
	algoValue := basics.TealValue{Type: basics.TealUintType, Uint: 0x77}
	ledger.balances[txn.Txn.Receiver].locals[1][string(key)] = algoValue

	ep.Ledger = ledger

	specialCmd := map[string]string{
		"txn":               "txn Sender",
		"txna":              "txna ApplicationArgs 0",
		"gtxn":              "gtxn 0 Sender",
		"gtxna":             "gtxna 0 ApplicationArgs 0",
		"global":            "global MinTxnFee",
		"arg":               "arg 0",
		"load":              "load 0",
		"store":             "store 0",
		"gload":             "gload 0 0",
		"gloads":            "gloads 0",
		"gaid":              "gaid 0",
		"dig":               "dig 0",
		"cover":             "cover 0",
		"uncover":           "uncover 0",
		"intc":              "intcblock 0; intc 0",
		"intc_0":            "intcblock 0; intc_0",
		"intc_1":            "intcblock 0 0; intc_1",
		"intc_2":            "intcblock 0 0 0; intc_2",
		"intc_3":            "intcblock 0 0 0 0; intc_3",
		"bytec":             "bytecblock 0x32; bytec 0",
		"bytec_0":           "bytecblock 0x32; bytec_0",
		"bytec_1":           "bytecblock 0x32 0x33; bytec_1",
		"bytec_2":           "bytecblock 0x32 0x33 0x34; bytec_2",
		"bytec_3":           "bytecblock 0x32 0x33 0x34 0x35; bytec_3",
		"substring":         "substring 0 2",
		"ed25519verify":     "pop; pop; pop; int 1", // ignore
		"asset_params_get":  "asset_params_get AssetTotal",
		"asset_holding_get": "asset_holding_get AssetBalance",
		"gtxns":             "gtxns Sender",
		"gtxnsa":            "gtxnsa ApplicationArgs 0",
		"pushint":           "pushint 7272",
		"pushbytes":         `pushbytes "jojogoodgorilla"`,
		"app_params_get":    "app_params_get AppGlobalNumUint",
		"extract":           "extract 0 2",
	}

	byName := OpsByName[LogicVersion]
	for _, m := range []runMode{runModeSignature, runModeApplication} {
		t.Run(fmt.Sprintf("m=%s", m.String()), func(t *testing.T) {
			for name, spec := range byName {
				if len(spec.Returns) == 0 || (m&spec.Modes) == 0 {
					continue
				}
				var sb strings.Builder
				sb.Grow(64)
				for _, t := range spec.Args {
					sb.WriteString(typeToArg[t])
				}
				if cmd, ok := specialCmd[name]; ok {
					sb.WriteString(cmd + "\n")
				} else {
					sb.WriteString(name + "\n")
				}
				source := sb.String()
				ops := testProg(t, source, AssemblerMaxVersion)

				var cx evalContext
				cx.EvalParams = ep
				cx.runModeFlags = m

				eval(ops.Program, &cx)

				require.Equal(
					t,
					len(spec.Returns), len(cx.stack),
					fmt.Sprintf("%s expected to return %d values but stack has %d", spec.Name, len(spec.Returns), len(cx.stack)),
				)
				for i := 0; i < len(spec.Returns); i++ {
					sp := len(cx.stack) - 1 - i
					stackType := cx.stack[sp].argType()
					retType := spec.Returns[i]
					require.True(
						t, typecheck(retType, stackType),
						fmt.Sprintf("%s expected to return %s but actual is %s", spec.Name, retType.String(), stackType.String()),
					)
				}
			}
		})
	}
}

func TestRound(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()
	ep, _ := makeSampleEnv()
	source := "global Round; int 1; >="
	testApp(t, source, ep)
}

func TestLatestTimestamp(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()
	ep, _ := makeSampleEnv()
	source := "global LatestTimestamp; int 1; >="
	testApp(t, source, ep)
}

func TestCurrentApplicationID(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()
	ep, ledger := makeSampleEnv()
	ledger.appID = basics.AppIndex(42)
	source := "global CurrentApplicationID; int 42; =="
	testApp(t, source, ep)
}

func TestAppLoop(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()
	ep, _ := makeSampleEnv()

	stateful := "global CurrentApplicationID; pop;"

	// Double until > 10. Should be 16
	testApp(t, stateful+"int 1; loop: int 2; *; dup; int 10; <; bnz loop; int 16; ==", ep)

	testApp(t, stateful+"int 1; loop: int 2; *; dup; int 10; <; bnz loop; int 16; ==", ep)

	// Infinite loop because multiply by one instead of two
	testApp(t, stateful+"int 1; loop:; int 1; *; dup; int 10; <; bnz loop; int 16; ==", ep, "dynamic cost")
}

func TestWriteLogs(t *testing.T) {
	partitiontest.PartitionTest(t)

	t.Parallel()

	ep := defaultEvalParams(nil, nil)
	txn := makeSampleTxn()
	txn.Txn.ApplicationID = 100
	ep.Txn = &txn
	ledger := makeTestLedger(
		map[basics.Address]uint64{
			txn.Txn.Sender: 1,
		},
	)
	ep.Ledger = ledger
	ledger.newApp(txn.Txn.Sender, 100, basics.AppParams{})

	// write int and bytes values
	source := `int 1
loop: byte "a"
log
int 1
+
dup
int 30
<
bnz loop
`
	ops, err := AssembleStringWithVersion(source, AssemblerMaxVersion)
	require.NoError(t, err)
	err = CheckStateful(ops.Program, ep)
	require.NoError(t, err)
	pass, err := EvalStateful(ops.Program, ep)
	require.NoError(t, err)
	require.True(t, pass)
	delta, err := ledger.GetDelta(&ep.Txn.Txn)
	require.NoError(t, err)
	require.Empty(t, 0, delta.GlobalDelta)
	require.Empty(t, delta.LocalDeltas)
	require.Len(t, delta.Logs, 29)
}

func TestPooledAppCallsVerifyOp(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	source := `#pragma version 5
	global CurrentApplicationID
	pop
	byte 0x01
	byte "ZC9KNzlnWTlKZ1pwSkNzQXVzYjNBcG1xTU9YbkRNWUtIQXNKYVk2RzRBdExPakQx"
	addr DROUIZXGT3WFJR3QYVZWTR5OJJXJCMOLS7G4FUGZDSJM5PNOVOREH6HIZE
	ed25519verify
	pop
	int 1`

	ep, _ := makeSampleEnv()
	ep.Proto.EnableAppCostPooling = true
	ep.PooledApplicationBudget = new(uint64)
	// Simulate test with 2 grouped txn
	*ep.PooledApplicationBudget = uint64(ep.Proto.MaxAppProgramCost * 2)
	testApp(t, source, ep, "pc=107 dynamic cost budget exceeded, executing ed25519verify: remaining budget is 1400 but program cost was 1905")

	// Simulate test with 3 grouped txn
	*ep.PooledApplicationBudget = uint64(ep.Proto.MaxAppProgramCost * 3)
	testApp(t, source, ep)
}