fuel-vm 0.66.3

FuelVM interpreter.
Documentation
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
use alloc::{
    vec,
    vec::Vec,
};

use rand::Rng;
use rstest::rstest;
use test_case::test_case;

use fuel_asm::{
    GTFArgs,
    Instruction,
    RegId,
    Word,
    op,
};
use fuel_tx::{
    Address,
    AssetId,
    ContractId,
    ContractIdExt,
    Output,
    PanicReason,
    Receipt,
    field::Outputs,
};
use fuel_types::{
    SubAssetId,
    canonical::Serialize,
};

use crate::{
    call::Call,
    consts::VM_MAX_RAM,
    prelude::TestBuilder,
    tests::test_helpers::set_full_word,
    util::test_helpers::find_change,
};

use super::test_helpers::RunResult;

fn run(mut test_context: TestBuilder, call_contract_id: ContractId) -> Vec<Receipt> {
    let script_ops = vec![
        op::gtf_args(0x10, RegId::ZERO, GTFArgs::ScriptData),
        op::call(0x10, RegId::ZERO, RegId::ZERO, RegId::CGAS),
        op::ret(RegId::ONE),
    ];
    let script_data: Vec<u8> = [Call::new(call_contract_id, 0, 0).to_bytes().as_slice()]
        .into_iter()
        .flatten()
        .copied()
        .collect();

    test_context
        .start_script(script_ops, script_data)
        .script_gas_limit(1_000_000)
        .contract_input(call_contract_id)
        .fee_input()
        .contract_output(&call_contract_id)
        .execute()
        .receipts()
        .to_vec()
}
fn first_log(receipts: &[Receipt]) -> Option<Word> {
    receipts
        .iter()
        .filter_map(|receipt| match receipt {
            Receipt::Log { ra, .. } => Some(*ra),
            _ => None,
        })
        .next()
}

fn first_tro(receipts: &[Receipt]) -> Option<Word> {
    receipts
        .iter()
        .filter_map(|receipt| match receipt {
            Receipt::TransferOut { amount, .. } => Some(*amount),
            _ => None,
        })
        .next()
}

const REG_DATA_PTR: u8 = 0x3f;
const REG_HELPER: u8 = 0x3e;

#[test_case(0, 0, op::bal(0x20, RegId::HP, REG_DATA_PTR) => RunResult::Success(0); "Works correctly with balance 0")]
#[test_case(1234, 0, op::bal(0x20, RegId::HP, REG_DATA_PTR) => RunResult::Success(1234); "Works correctly with balance 1234")]
#[test_case(Word::MAX, 0, op::bal(0x20, RegId::HP, REG_DATA_PTR) => RunResult::Success(Word::MAX); "Works correctly with balance Word::MAX")]
#[test_case(0, Word::MAX - 31, op::bal(0x20, REG_HELPER, REG_DATA_PTR) => RunResult::Panic(PanicReason::MemoryOverflow); "$rB + 32 overflows")]
#[test_case(0, VM_MAX_RAM - 31, op::bal(0x20, REG_HELPER, REG_DATA_PTR) => RunResult::Panic(PanicReason::MemoryOverflow); "$rB + 32 > VM_MAX_RAM")]
#[test_case(0, Word::MAX - 31, op::bal(0x20, RegId::HP, REG_HELPER) => RunResult::Panic(PanicReason::MemoryOverflow); "$rC + 32 overflows")]
#[test_case(0, VM_MAX_RAM - 31, op::bal(0x20, RegId::HP, REG_HELPER) => RunResult::Panic(PanicReason::MemoryOverflow); "$rC + 32 > VM_MAX_RAM")]
#[test_case(0, 0, op::bal(0x20, RegId::HP, RegId::ZERO) => RunResult::Panic(PanicReason::ContractNotInInputs); "Contract not in inputs")]
fn bal_external(amount: Word, helper: Word, bal_instr: Instruction) -> RunResult<Word> {
    let reg_len: u8 = 0x10;

    let mut ops = set_full_word(REG_HELPER.into(), helper);
    ops.extend(set_full_word(
        reg_len.into(),
        (ContractId::LEN + AssetId::LEN) as Word,
    ));
    ops.extend([
        // Compute asset id from contract id and sub asset id
        op::aloc(reg_len),
        op::gtf_args(REG_DATA_PTR, RegId::ZERO, GTFArgs::ScriptData),
        bal_instr,
        op::log(0x20, RegId::ZERO, RegId::ZERO, RegId::ZERO),
        op::ret(RegId::ONE),
    ]);

    let mut test_context = TestBuilder::new(1234u64);
    let contract_id = test_context
        .setup_contract(
            vec![op::ret(RegId::ONE)],
            Some((AssetId::zeroed(), amount)),
            None,
        )
        .contract_id;

    let result = test_context
        .start_script(ops, contract_id.to_bytes())
        .script_gas_limit(1_000_000)
        .contract_input(contract_id)
        .fee_input()
        .contract_output(&contract_id)
        .execute();

    RunResult::extract(result.receipts(), first_log)
}

#[test_case(0, 0, op::bal(0x20, RegId::HP, REG_DATA_PTR) => RunResult::Success(0); "Works correctly with balance 0")]
#[test_case(1234, 0, op::bal(0x20, RegId::HP, REG_DATA_PTR) => RunResult::Success(1234); "Works correctly with balance 1234")]
#[test_case(Word::MAX, 0, op::bal(0x20, RegId::HP, REG_DATA_PTR) => RunResult::Success(Word::MAX); "Works correctly with balance Word::MAX")]
#[test_case(0, Word::MAX - 31, op::bal(0x20, REG_HELPER, REG_DATA_PTR) => RunResult::Panic(PanicReason::MemoryOverflow); "$rB + 32 overflows")]
#[test_case(0, VM_MAX_RAM - 31, op::bal(0x20, REG_HELPER, REG_DATA_PTR) => RunResult::Panic(PanicReason::MemoryOverflow); "$rB + 32 > VM_MAX_RAM")]
#[test_case(0, Word::MAX - 31, op::bal(0x20, RegId::HP, REG_HELPER) => RunResult::Panic(PanicReason::MemoryOverflow); "$rC + 32 overflows")]
#[test_case(0, VM_MAX_RAM - 31, op::bal(0x20, RegId::HP, REG_HELPER) => RunResult::Panic(PanicReason::MemoryOverflow); "$rC + 32 > VM_MAX_RAM")]
#[test_case(0, 0, op::bal(0x20, RegId::HP, RegId::ZERO) => RunResult::Panic(PanicReason::ContractNotInInputs); "Contract not in inputs")]
fn mint_and_bal(
    mint_amount: Word,
    helper: Word,
    bal_instr: Instruction,
) -> RunResult<Word> {
    let reg_len: u8 = 0x10;
    let reg_mint_amount: u8 = 0x11;

    let mut ops = set_full_word(reg_mint_amount.into(), mint_amount);
    ops.extend(set_full_word(REG_HELPER.into(), helper));
    ops.extend(set_full_word(
        reg_len.into(),
        (ContractId::LEN + AssetId::LEN) as Word,
    ));
    ops.extend([
        // Compute asset id from contract id and sub asset id
        op::aloc(reg_len),
        op::mint(reg_mint_amount, RegId::HP), // Mint using the zero subid.
        op::gtf_args(REG_DATA_PTR, RegId::ZERO, GTFArgs::ScriptData),
        op::mcpi(RegId::HP, REG_DATA_PTR, ContractId::LEN.try_into().unwrap()),
        op::s256(RegId::HP, RegId::HP, reg_len),
        bal_instr,
        op::log(0x20, RegId::ZERO, RegId::ZERO, RegId::ZERO),
        op::ret(RegId::ONE),
    ]);

    let mut test_context = TestBuilder::new(1234u64);
    let contract_id = test_context.setup_contract(ops, None, None).contract_id;
    RunResult::extract(&run(test_context, contract_id), first_log)
}

#[rstest]
#[case(0, RegId::HP, RunResult::Success(()))]
#[case(Word::MAX, RegId::HP, RunResult::Success(()))]
#[case(Word::MAX - 31, REG_HELPER, RunResult::Panic(PanicReason::MemoryOverflow))]
#[case(VM_MAX_RAM - 31, REG_HELPER, RunResult::Panic(PanicReason::MemoryOverflow))]
fn mint_burn_bounds<R: Into<u8>>(
    #[values(op::mint, op::burn)] instr: fn(RegId, R) -> Instruction,
    #[case] helper: Word,
    #[case] sub_id_ptr_reg: R,
    #[case] result: RunResult<()>,
) {
    let reg_len: u8 = 0x10;

    let mut ops = set_full_word(REG_HELPER.into(), helper);
    ops.extend(set_full_word(
        reg_len.into(),
        (ContractId::LEN + AssetId::LEN) as Word,
    ));
    ops.extend([
        // Compute asset id from contract id and sub asset id
        op::gtf_args(REG_DATA_PTR, RegId::ZERO, GTFArgs::ScriptData),
        op::aloc(reg_len),
        instr(RegId::ZERO, sub_id_ptr_reg),
        op::log(RegId::ZERO, RegId::ZERO, RegId::ZERO, RegId::ZERO),
        op::ret(RegId::ONE),
    ]);

    let mut test_context = TestBuilder::new(1234u64);
    let contract_id = test_context
        .setup_contract(ops, Some((AssetId::zeroed(), Word::MAX - helper)), None) // Ensure enough but not too much balance
        .contract_id;
    assert_eq!(
        RunResult::extract_novalue(&run(test_context, contract_id)),
        result
    );
}

type MintOrBurnOpcode = fn(RegId, RegId) -> Instruction;

#[test_case(vec![(op::mint, 0, 0)] => RunResult::Success(()); "Mint 0")]
#[test_case(vec![(op::burn, 0, 0)] => RunResult::Success(()); "Burn 0")]
#[test_case(vec![(op::mint, 100, 0)] => RunResult::Success(()); "Mint 100")]
#[test_case(vec![(op::mint, Word::MAX, 0)] => RunResult::Success(()); "Mint Word::MAX")]
#[test_case(vec![(op::mint, 100, 0), (op::burn, 100, 0)] => RunResult::Success(()); "Mint 100, Burn all")]
#[test_case(vec![(op::mint, Word::MAX, 0), (op::burn, Word::MAX, 0)] => RunResult::Success(()); "Mint Word::MAX, Burn all")]
#[test_case(vec![(op::mint, 100, 0), (op::mint, 10, 0), (op::burn, 20, 0)] => RunResult::Success(()); "Mint 10 and 10, Burn all")]
#[test_case(vec![(op::mint, 2, 0), (op::mint, 3, 1), (op::burn, 2, 0), (op::burn, 3, 1)] => RunResult::Success(()); "Mint multiple assets, Burn all")]
#[test_case(vec![(op::burn, 1, 0)] => RunResult::Panic(PanicReason::NotEnoughBalance); "Burn nonexisting 1")]
#[test_case(vec![(op::burn, Word::MAX, 0)] => RunResult::Panic(PanicReason::NotEnoughBalance); "Burn nonexisting Word::MAX")]
#[test_case(vec![(op::mint, Word::MAX, 0), (op::mint, 1, 0)] => RunResult::Panic(PanicReason::BalanceOverflow); "Mint overflow")]
#[test_case(vec![(op::mint, Word::MAX, 0), (op::burn, 1, 0), (op::mint, 2, 0)] => RunResult::Panic(PanicReason::BalanceOverflow); "Mint,Burn,Mint overflow")]
fn mint_burn_single_sequence(seq: Vec<(MintOrBurnOpcode, Word, u8)>) -> RunResult<()> {
    let reg_len: u8 = 0x10;
    let reg_mint_amount: u8 = 0x11;

    let mut ops = vec![
        // Allocate space for sub asset id
        op::movi(reg_len, 32),
        op::aloc(reg_len),
    ];

    for (mint_or_burn, amount, sub_id) in seq {
        ops.push(op::sb(RegId::HP, sub_id, 0));
        ops.extend(set_full_word(reg_mint_amount.into(), amount));
        ops.push(mint_or_burn(reg_mint_amount.into(), RegId::HP));
    }
    ops.push(op::ret(RegId::ONE));

    let mut test_context = TestBuilder::new(1234u64);
    let contract_id = test_context.setup_contract(ops, None, None).contract_id;
    RunResult::extract_novalue(&run(test_context, contract_id))
}

enum MintOrBurn {
    Mint,
    Burn,
}

#[test_case(vec![MintOrBurn::Burn] => RunResult::Panic(PanicReason::NotEnoughBalance); "Burn")]
#[test_case(vec![MintOrBurn::Mint, MintOrBurn::Burn, MintOrBurn::Burn] => RunResult::Panic(PanicReason::NotEnoughBalance); "Mint,Burn,Burn")]
#[test_case(vec![MintOrBurn::Mint, MintOrBurn::Mint, MintOrBurn::Burn] => RunResult::Success(1); "Mint,Mint,Burn")]
fn mint_burn_many_calls_sequence(seq: Vec<MintOrBurn>) -> RunResult<Word> {
    let reg_len: u8 = 0x10;
    let reg_jump: u8 = 0x11;

    let ops = vec![
        // Allocate space for zero sub asset id
        op::movi(reg_len, 32),
        op::aloc(reg_len),
        op::jmpf(reg_jump, 0),
        op::mint(RegId::ONE, RegId::HP), // Jump of 0 - mint 1
        op::ret(RegId::ONE),             // Jump of 1 - do nothing
        op::burn(RegId::ONE, RegId::HP), // Jump of 2 - burn 1
        op::ret(RegId::ONE),             // Jump of 3 - do nothing
    ];

    let mut test_context = TestBuilder::new(1234u64);
    let contract_id = test_context.setup_contract(ops, None, None).contract_id;

    for instr in seq {
        let script_ops = vec![
            op::movi(
                reg_jump,
                match instr {
                    MintOrBurn::Mint => 0,
                    MintOrBurn::Burn => 2,
                },
            ),
            op::gtf_args(0x10, RegId::ZERO, GTFArgs::ScriptData),
            op::call(0x10, RegId::ZERO, RegId::ZERO, RegId::CGAS),
            op::ret(RegId::ONE),
        ];
        let script_data: Vec<u8> = [Call::new(contract_id, 0, 0).to_bytes().as_slice()]
            .into_iter()
            .flatten()
            .copied()
            .collect();

        let receipts = test_context
            .start_script(script_ops, script_data)
            .script_gas_limit(1_000_000)
            .contract_input(contract_id)
            .fee_input()
            .contract_output(&contract_id)
            .execute()
            .receipts()
            .to_vec();

        let result = RunResult::extract_novalue(&receipts);
        if !result.is_ok() {
            return result.map(|_| unreachable!());
        }
    }

    RunResult::Success(
        test_context.get_contract_balance(
            &contract_id,
            &contract_id.asset_id(&SubAssetId::zeroed()),
        ),
    )
}

#[test_case(0, 10, 0 => RunResult::Panic(PanicReason::TransferZeroCoins); "Cannot transfer 0 coins")]
#[test_case(1, 10, 0 => RunResult::Success((9, 1)); "Can transfer 1 coins to empty")]
#[test_case(1, 10, 5 => RunResult::Success((9, 6)); "Can transfer 1 coins to non-empty")]
#[test_case(11, 10, 0 => RunResult::Panic(PanicReason::NotEnoughBalance); "Cannot transfer just over balance coins")]
#[test_case(Word::MAX, 0, 0 => RunResult::Panic(PanicReason::NotEnoughBalance); "Cannot transfer max over balance coins")]
#[test_case(1, 1, Word::MAX => RunResult::Panic(PanicReason::BalanceOverflow); "Cannot overflow balance of contract")]
#[test_case(Word::MAX, Word::MAX, 0 => RunResult::Success((0, Word::MAX)); "Can transfer Word::MAX coins to empty contract")]
fn transfer_to_contract_external(
    amount: Word,
    balance: Word,
    other_balance: Word,
) -> RunResult<(Word, Word)> {
    let contract_id_ptr = 0x11;
    let asset_id_ptr = 0x12;
    let reg_amount = 0x13;

    let mut ops = set_full_word(reg_amount.into(), amount);

    ops.extend(&[
        op::gtf_args(contract_id_ptr, RegId::ZERO, GTFArgs::ScriptData),
        op::addi(
            asset_id_ptr,
            contract_id_ptr,
            ContractId::LEN.try_into().unwrap(),
        ),
        op::tr(contract_id_ptr, reg_amount, asset_id_ptr),
        op::ret(RegId::ONE),
    ]);

    let mut test_context = TestBuilder::new(1234u64);
    let asset_id: AssetId = test_context.rng.r#gen();

    let contract = test_context
        .setup_contract(
            vec![op::ret(RegId::ONE)],
            Some((asset_id, other_balance)),
            None,
        )
        .contract_id;

    let script_data: Vec<u8> = contract
        .to_bytes()
        .into_iter()
        .chain(asset_id.to_bytes())
        .collect();

    let (_, tx, receipts, _) = test_context
        .start_script(ops, script_data)
        .script_gas_limit(1_000_000)
        .contract_input(contract)
        .coin_input(asset_id, balance)
        .fee_input()
        .contract_output(&contract)
        .change_output(asset_id)
        .execute()
        .into_inner();

    let change = find_change(tx.outputs().to_vec(), asset_id);
    let result = RunResult::extract_novalue(&receipts);
    if !result.is_ok() {
        assert_eq!(change, balance, "Revert should not change balance")
    }
    result.map(|()| {
        (
            change,
            test_context.get_contract_balance(&contract, &asset_id),
        )
    })
}

enum TrTo {
    /// Transfer to self
    This,
    /// Transfer to other contract
    Other,
    /// Transfer to non-existing contract
    NonExisting,
}

#[test_case(TrTo::Other, 0, 10, 0 => RunResult::Panic(PanicReason::TransferZeroCoins); "Cannot transfer 0 coins to empty other")]
#[test_case(TrTo::Other, 0, 10, 5 => RunResult::Panic(PanicReason::TransferZeroCoins); "Cannot transfer 0 coins to non-empty other")]
#[test_case(TrTo::This, 0, 10, 0 => RunResult::Panic(PanicReason::TransferZeroCoins); "Cannot transfer 0 coins to self")]
#[test_case(TrTo::Other, 1, 10, 0 => RunResult::Success((9, 1)); "Can transfer 1 coins to other")]
#[test_case(TrTo::This, 1, 10, 0 => RunResult::Success((10, 0)); "Can transfer 1 coins to self")]
#[test_case(TrTo::Other, 11, 10, 0 => RunResult::Panic(PanicReason::NotEnoughBalance); "Cannot transfer just over balance coins to other")]
#[test_case(TrTo::This, 11, 10, 0 => RunResult::Panic(PanicReason::NotEnoughBalance); "Cannot transfer just over balance coins to self")]
#[test_case(TrTo::Other, Word::MAX, 0, 0 => RunResult::Panic(PanicReason::NotEnoughBalance); "Cannot transfer max over balance coins to other")]
#[test_case(TrTo::This, Word::MAX, 0, 0 => RunResult::Panic(PanicReason::NotEnoughBalance); "Cannot transfer max over balance coins to self")]
#[test_case(TrTo::Other, 1, 1, Word::MAX => RunResult::Panic(PanicReason::BalanceOverflow); "Cannot overflow balance of other contract")]
#[test_case(TrTo::This, Word::MAX, Word::MAX, 0 => RunResult::Success((Word::MAX, 0)); "Can transfer Word::MAX coins to self")]
#[test_case(TrTo::Other, Word::MAX, Word::MAX, 0 => RunResult::Success((0, Word::MAX)); "Can transfer Word::MAX coins to empty other")]
#[test_case(TrTo::NonExisting, 1, 1, 0 => RunResult::Panic(PanicReason::ContractNotInInputs); "Transfer target not in inputs")]
fn transfer_to_contract_internal(
    to: TrTo,
    amount: Word,
    balance: Word,
    other_balance: Word,
) -> RunResult<(Word, Word)> {
    let reg_tmp = 0x10;
    let contract_id_ptr = 0x11;
    let asset_id_ptr = 0x12;
    let reg_amount = 0x13;

    let mut ops = set_full_word(reg_amount.into(), amount);

    ops.extend(&[
        op::gtf_args(reg_tmp, RegId::ZERO, GTFArgs::ScriptData),
        op::addi(contract_id_ptr, reg_tmp, Call::LEN.try_into().unwrap()),
        op::addi(
            asset_id_ptr,
            contract_id_ptr,
            ContractId::LEN.try_into().unwrap(),
        ),
        op::tr(contract_id_ptr, reg_amount, asset_id_ptr),
        op::ret(RegId::ONE),
    ]);

    let mut test_context = TestBuilder::new(1234u64);
    let asset_id: AssetId = test_context.rng.r#gen();

    let this_contract = test_context
        .setup_contract(ops, Some((asset_id, balance)), None)
        .contract_id;

    let other_contract = test_context
        .setup_contract(
            vec![op::ret(RegId::ONE)],
            Some((asset_id, other_balance)),
            None,
        )
        .contract_id;

    let script_ops = vec![
        op::gtf_args(0x10, RegId::ZERO, GTFArgs::ScriptData),
        op::call(0x10, RegId::ZERO, RegId::ZERO, RegId::CGAS),
        op::ret(RegId::ONE),
    ];
    let script_data: Vec<u8> = [Call::new(this_contract, 0, 0).to_bytes().as_slice()]
        .into_iter()
        .flatten()
        .copied()
        .chain(match to {
            TrTo::This => this_contract.to_bytes(),
            TrTo::Other => other_contract.to_bytes(),
            TrTo::NonExisting => vec![1u8; 32], // Non-existing contract
        })
        .chain(asset_id.to_bytes())
        .collect();

    let result = test_context
        .start_script(script_ops, script_data)
        .script_gas_limit(1_000_000)
        .contract_input(this_contract)
        .contract_input(other_contract)
        .fee_input()
        .contract_output(&this_contract)
        .contract_output(&other_contract)
        .execute();

    RunResult::extract_novalue(result.receipts()).map(|()| {
        (
            test_context.get_contract_balance(&this_contract, &asset_id),
            test_context.get_contract_balance(&other_contract, &asset_id),
        )
    })
}

#[test_case(None, None => RunResult::Success(()); "Normal case works")]
#[test_case(Some(Word::MAX - 31), None => RunResult::Panic(PanicReason::MemoryOverflow); "$rA + 32 overflows")]
#[test_case(Some(VM_MAX_RAM - 31), None => RunResult::Panic(PanicReason::MemoryOverflow); "$rA + 32 > VM_MAX_RAM")]
#[test_case(None, Some(Word::MAX - 31) => RunResult::Panic(PanicReason::MemoryOverflow); "$rC + 32 overflows")]
#[test_case(None, Some(VM_MAX_RAM - 31) => RunResult::Panic(PanicReason::MemoryOverflow); "$rC + 32 > VM_MAX_RAM")]
fn transfer_to_contract_bounds(
    overwrite_contract_id_ptr: Option<Word>,
    overwrite_asset_id_ptr: Option<Word>,
) -> RunResult<()> {
    let reg_tmp = 0x10;
    let contract_id_ptr = 0x11;
    let asset_id_ptr = 0x12;

    let mut ops = vec![
        op::gtf_args(reg_tmp, RegId::ZERO, GTFArgs::ScriptData),
        op::addi(contract_id_ptr, reg_tmp, Call::LEN.try_into().unwrap()),
        op::addi(
            asset_id_ptr,
            contract_id_ptr,
            ContractId::LEN.try_into().unwrap(),
        ),
    ];

    if let Some(value) = overwrite_contract_id_ptr {
        ops.extend(set_full_word(contract_id_ptr.into(), value));
    }

    if let Some(value) = overwrite_asset_id_ptr {
        ops.extend(set_full_word(asset_id_ptr.into(), value));
    }

    ops.extend(&[
        op::tr(contract_id_ptr, RegId::ONE, asset_id_ptr),
        op::ret(RegId::ONE),
    ]);

    let mut test_context = TestBuilder::new(1234u64);
    let asset_id: AssetId = test_context.rng.r#gen();

    let this_contract = test_context
        .setup_contract(ops, Some((asset_id, Word::MAX)), None)
        .contract_id;

    let script_ops = vec![
        op::gtf_args(0x10, RegId::ZERO, GTFArgs::ScriptData),
        op::call(0x10, RegId::ZERO, RegId::ZERO, RegId::CGAS),
        op::ret(RegId::ONE),
    ];
    let script_data: Vec<u8> = [Call::new(this_contract, 0, 0).to_bytes().as_slice()]
        .into_iter()
        .flatten()
        .copied()
        .chain(this_contract.to_bytes())
        .chain(asset_id.to_bytes())
        .collect();

    let result = test_context
        .start_script(script_ops, script_data)
        .script_gas_limit(1_000_000)
        .contract_input(this_contract)
        .fee_input()
        .contract_output(&this_contract)
        .execute();

    RunResult::extract_novalue(result.receipts())
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Ctx {
    Internal,
    External,
}

const M: Word = Word::MAX;

#[test_case(Ctx::External, 0, 0, 10 => RunResult::Panic(PanicReason::TransferZeroCoins); "(external) Cannot transfer 0 coins to non-Variable output")]
#[test_case(Ctx::External, 1, 0, 10 => RunResult::Panic(PanicReason::TransferZeroCoins); "(external) Cannot transfer 0 coins to valid output")]
#[test_case(Ctx::External, 9, 0, 10 => RunResult::Panic(PanicReason::TransferZeroCoins); "(external) Cannot transfer 0 coins to non-existing output")]
#[test_case(Ctx::External, 1, 1, 10 => RunResult::Success((1, 9)); "(external) Can transfer 1 coins")]
#[test_case(Ctx::External, 1, 11, 10 => RunResult::Panic(PanicReason::NotEnoughBalance); "(external) Cannot transfer just over balance coins")]
#[test_case(Ctx::External, 1, M, 0 => RunResult::Panic(PanicReason::NotEnoughBalance); "(external) Cannot transfer max over balance coins")]
#[test_case(Ctx::External, 1, M, M => RunResult::Success((Word::MAX, 0)); "(external) Can transfer Word::MAX coins")]
#[test_case(Ctx::External, 0, 1, 10 => RunResult::Panic(PanicReason::OutputNotFound); "(external) Target output is not Variable")]
#[test_case(Ctx::External, 9, 1, 1 => RunResult::Panic(PanicReason::OutputNotFound); "(external) Target output doesn't exist")]
#[test_case(Ctx::External, M, 1, 1 => RunResult::Panic(PanicReason::OutputNotFound); "(external) Target output is Word::MAX")]
#[test_case(Ctx::Internal, 0, 0, 10 => RunResult::Panic(PanicReason::TransferZeroCoins); "(internal) Cannot transfer 0 coins to non-Variable output")]
#[test_case(Ctx::Internal, 1, 0, 10 => RunResult::Panic(PanicReason::TransferZeroCoins); "(internal) Cannot transfer 0 coins to valid output")]
#[test_case(Ctx::Internal, 9, 0, 10 => RunResult::Panic(PanicReason::TransferZeroCoins); "(internal) Cannot transfer 0 coins to non-existing output")]
#[test_case(Ctx::Internal, 1, 1, 10 => RunResult::Success((1, 9)); "(internal) Can transfer 1 coins")]
#[test_case(Ctx::Internal, 1, 11, 10 => RunResult::Panic(PanicReason::NotEnoughBalance); "(internal) Cannot transfer just over balance coins")]
#[test_case(Ctx::Internal, 1, M, 0 => RunResult::Panic(PanicReason::NotEnoughBalance); "(internal) Cannot transfer max over balance coins")]
#[test_case(Ctx::Internal, 1, M, M => RunResult::Success((Word::MAX, 0)); "(internal) Can transfer Word::MAX coins")]
#[test_case(Ctx::Internal, 0, 1, 10 => RunResult::Panic(PanicReason::OutputNotFound); "(internal) Target output is not Variable")]
#[test_case(Ctx::Internal, 9, 1, 1 => RunResult::Panic(PanicReason::OutputNotFound); "(internal) Target output doesn't exist")]
#[test_case(Ctx::Internal, M, 1, 1 => RunResult::Panic(PanicReason::OutputNotFound); "(internal) Target output is Word::MAX")]
fn transfer_to_output(
    ctx: Ctx,
    to_index: Word, // 1 = the variable output
    amount: Word,
    balance: Word,
) -> RunResult<(Word, Word)> {
    let reg_tmp = 0x10;
    let asset_id_ptr = 0x12;
    let reg_amount = 0x13;
    let reg_index = 0x14;

    let mut ops = set_full_word(reg_amount.into(), amount);
    ops.extend(set_full_word(reg_index.into(), to_index));
    ops.extend(&[
        op::gtf_args(reg_tmp, RegId::ZERO, GTFArgs::ScriptData),
        op::addi(asset_id_ptr, reg_tmp, Call::LEN.try_into().unwrap()),
        op::tro(reg_tmp, reg_index, reg_amount, asset_id_ptr),
        op::ret(RegId::ONE),
    ]);

    let mut test_context = TestBuilder::new(1234u64);
    let asset_id: AssetId = test_context.rng.r#gen();

    let contract_id = test_context
        .setup_contract(ops.clone(), Some((asset_id, balance)), None)
        .contract_id;

    let script_ops = match ctx {
        Ctx::Internal => vec![
            op::gtf_args(0x10, RegId::ZERO, GTFArgs::ScriptData),
            op::call(0x10, RegId::ZERO, RegId::ZERO, RegId::CGAS),
            op::ret(RegId::ONE),
        ],
        Ctx::External => ops,
    };

    let script_data: Vec<u8> = [Call::new(contract_id, 0, 0).to_bytes().as_slice()]
        .into_iter()
        .flatten()
        .copied()
        .chain(asset_id.to_bytes())
        .collect();

    let mut builder = test_context
        .start_script(script_ops, script_data)
        .script_gas_limit(1_000_000)
        .contract_input(contract_id)
        .fee_input()
        .contract_output(&contract_id)
        .variable_output(asset_id);

    if ctx == Ctx::External {
        builder = builder
            .coin_input(asset_id, balance)
            .change_output(asset_id);
    }

    let (_, tx, receipts, _) = builder.execute().into_inner();
    let result = RunResult::extract(&receipts, first_tro);

    if let Some(Output::Variable {
        to: var_to,
        amount: var_amount,
        asset_id: var_asset_id,
    }) = tx.outputs().get(to_index as usize).copied()
    {
        if result.is_ok() {
            assert_eq!(var_amount, amount, "Transfer amount is wrong");
            assert_eq!(var_asset_id, asset_id, "Transfer asset id is wrong");
        } else {
            assert_eq!(
                var_to,
                Address::zeroed(),
                "Transfer target should be zeroed on failure"
            );
            assert_eq!(var_amount, 0, "Transfer amount should be 0 on failure");
            assert_eq!(
                var_asset_id,
                AssetId::zeroed(),
                "Transfer asset id should be zeroed on failure"
            );
        }
    }

    if !result.is_ok() && ctx == Ctx::External {
        assert_eq!(
            find_change(tx.outputs().to_vec(), asset_id),
            balance,
            "Revert should not change balance"
        )
    }

    result.map(|tr| {
        (
            tr,
            if ctx == Ctx::Internal {
                test_context.get_contract_balance(&contract_id, &asset_id)
            } else {
                find_change(tx.outputs().to_vec(), asset_id)
            },
        )
    })
}

#[test_case(None, None => RunResult::Success(()); "Normal case works")]
#[test_case(Some(Word::MAX - 31), None => RunResult::Panic(PanicReason::MemoryOverflow); "$rA + 32 overflows")]
#[test_case(Some(VM_MAX_RAM - 31), None => RunResult::Panic(PanicReason::MemoryOverflow); "$rA + 32 > VM_MAX_RAM")]
#[test_case(None, Some(Word::MAX - 31) => RunResult::Panic(PanicReason::MemoryOverflow); "$rC + 32 overflows")]
#[test_case(None, Some(VM_MAX_RAM - 31) => RunResult::Panic(PanicReason::MemoryOverflow); "$rC + 32 > VM_MAX_RAM")]
fn transfer_to_output_bounds(
    overwrite_contract_id_ptr: Option<Word>,
    overwrite_asset_id_ptr: Option<Word>,
) -> RunResult<()> {
    let reg_tmp = 0x10;
    let contract_id_ptr = 0x11;
    let asset_id_ptr = 0x12;

    let mut ops = vec![
        op::gtf_args(reg_tmp, RegId::ZERO, GTFArgs::ScriptData),
        op::addi(contract_id_ptr, reg_tmp, Call::LEN.try_into().unwrap()),
        op::addi(
            asset_id_ptr,
            contract_id_ptr,
            ContractId::LEN.try_into().unwrap(),
        ),
    ];

    if let Some(value) = overwrite_contract_id_ptr {
        ops.extend(set_full_word(contract_id_ptr.into(), value));
    }

    if let Some(value) = overwrite_asset_id_ptr {
        ops.extend(set_full_word(asset_id_ptr.into(), value));
    }

    ops.extend(&[
        op::tro(contract_id_ptr, RegId::ONE, RegId::ONE, asset_id_ptr),
        op::ret(RegId::ONE),
    ]);

    let mut test_context = TestBuilder::new(1234u64);
    let asset_id: AssetId = test_context.rng.r#gen();

    let this_contract = test_context
        .setup_contract(ops, Some((asset_id, Word::MAX)), None)
        .contract_id;

    let script_ops = vec![
        op::gtf_args(0x10, RegId::ZERO, GTFArgs::ScriptData),
        op::call(0x10, RegId::ZERO, RegId::ZERO, RegId::CGAS),
        op::ret(RegId::ONE),
    ];
    let script_data: Vec<u8> = [Call::new(this_contract, 0, 0).to_bytes().as_slice()]
        .into_iter()
        .flatten()
        .copied()
        .chain(this_contract.to_bytes())
        .chain(asset_id.to_bytes())
        .collect();

    let result = test_context
        .start_script(script_ops, script_data)
        .script_gas_limit(1_000_000)
        .contract_input(this_contract)
        .fee_input()
        .contract_output(&this_contract)
        .variable_output(asset_id)
        .execute();

    RunResult::extract_novalue(result.receipts())
}

// Calls script -> src -> dst
#[test_case(0, 0, 0, 0, 0 => ((0, 0, 0), RunResult::Success(())); "No coins moving, zero balances")]
#[test_case(1, 1, 1, 0, 0 => ((1, 1, 1), RunResult::Success(())); "No coins moving, nonzero balances")]
#[test_case(1, 0, 0, 1, 0 => ((0, 1, 0), RunResult::Success(())); "Fwd 1 from script to src")]
#[test_case(0, 1, 0, 0, 1 => ((0, 0, 1), RunResult::Success(())); "Fwd 1 from src to dst")]
#[test_case(1, 0, 0, 1, 1 => ((0, 0, 1), RunResult::Success(())); "Fwd 1 from script to dst")]
#[test_case(1, 2, 3, 1, 3 => ((0, 0, 6), RunResult::Success(())); "Fwd combination full")]
#[test_case(5, 5, 1, 3, 2 => ((2, 6, 3), RunResult::Success(())); "Fwd combination partial")]
#[test_case(M, 0, 0, M, 0 => ((0, M, 0), RunResult::Success(())); "Fwd Word::MAX from script to src")]
#[test_case(0, M, 0, 0, M => ((0, 0, M), RunResult::Success(())); "Fwd Word::MAX from src to dst")]
#[test_case(M, 0, 0, M, M => ((0, 0, M), RunResult::Success(())); "Fwd Word::MAX from script to dst")]
#[test_case(1, M, 0, 1, 0 => ((1, M, 0), RunResult::Panic(PanicReason::BalanceOverflow)); "Fwd 1 overflow on src")]
#[test_case(0, 1, M, 0, 1 => ((0, 1, M), RunResult::Panic(PanicReason::BalanceOverflow)); "Fwd 1 overflow on dst")]
#[test_case(M, 1, 0, M, 0 => ((M, 1, 0), RunResult::Panic(PanicReason::BalanceOverflow)); "Fwd Word::MAX overflow on src")]
#[test_case(0, M, 1, 0, M => ((0, M, 1), RunResult::Panic(PanicReason::BalanceOverflow)); "Fwd Word::MAX overflow on dst")]
#[test_case(M, M, M, M, M => ((M, M, M), RunResult::Panic(PanicReason::BalanceOverflow)); "Fwd Word::MAX both")]
#[test_case(0, 0, 0, 1, 0 => ((0, 0, 0), RunResult::Panic(PanicReason::NotEnoughBalance)); "Fwd 1 over empty script balance")]
#[test_case(1, 0, 0, 2, 0 => ((1, 0, 0), RunResult::Panic(PanicReason::NotEnoughBalance)); "Fwd 1 over script balance")]
#[test_case(0, 0, 0, M, 0 => ((0, 0, 0), RunResult::Panic(PanicReason::NotEnoughBalance)); "Fwd max over empty script balance")]
#[test_case(1, 0, 0, M, 0 => ((1, 0, 0), RunResult::Panic(PanicReason::NotEnoughBalance)); "Fwd max over script balance")]
#[test_case(0, 0, 0, 0, 1 => ((0, 0, 0), RunResult::Panic(PanicReason::NotEnoughBalance)); "Fwd 1 over empty src balance")]
#[test_case(0, 1, 0, 0, 2 => ((0, 1, 0), RunResult::Panic(PanicReason::NotEnoughBalance)); "Fwd 1 over src balance")]
#[test_case(0, 0, 0, 0, M => ((0, 0, 0), RunResult::Panic(PanicReason::NotEnoughBalance)); "Fwd max over empty src balance")]
#[test_case(0, 1, 0, 0, M => ((0, 1, 0), RunResult::Panic(PanicReason::NotEnoughBalance)); "Fwd max over src balance")]
fn call_forwarding(
    balance_in: Word,
    balance_src: Word,
    balance_dst: Word,
    fwd_to_src: Word,
    fwd_to_dst: Word,
) -> ((Word, Word, Word), RunResult<()>) {
    let reg_tmp = 0x10;
    let reg_dst_contract_ptr = 0x11;
    let reg_fwd_to_src: u8 = 0x12;
    let reg_fwd_to_dst: u8 = 0x13;
    let reg_asset_id_ptr: u8 = 0x14;

    let mut test_context = TestBuilder::new(1234u64);
    let asset_id: AssetId = test_context.rng.r#gen();

    // Setup the dst contract. This does nothing, just holds/receives the balance.
    let dst_contract = test_context
        .setup_contract(
            vec![op::ret(RegId::ONE)],
            Some((asset_id, balance_dst)),
            None,
        )
        .contract_id;

    // Setup the src contract. This just calls the dst to forward the coins.
    let src_contract = test_context
        .setup_contract(
            vec![
                op::call(reg_dst_contract_ptr, reg_fwd_to_dst, RegId::HP, RegId::CGAS),
                op::ret(RegId::ONE),
            ],
            Some((asset_id, balance_src)),
            None,
        )
        .contract_id;

    // Setup the script that does the call.
    let mut script_ops = Vec::new();
    script_ops.extend(set_full_word(reg_fwd_to_src.into(), fwd_to_src));
    script_ops.extend(set_full_word(reg_fwd_to_dst.into(), fwd_to_dst));
    script_ops.extend(&[
        op::movi(reg_tmp, AssetId::LEN.try_into().unwrap()),
        op::aloc(reg_tmp),
        op::gtf_args(reg_tmp, RegId::ZERO, GTFArgs::ScriptData),
        op::addi(
            reg_asset_id_ptr,
            reg_tmp,
            (Call::LEN * 2).try_into().unwrap(),
        ),
        op::mcpi(
            RegId::HP,
            reg_asset_id_ptr,
            AssetId::LEN.try_into().unwrap(),
        ),
        op::addi(reg_dst_contract_ptr, reg_tmp, Call::LEN.try_into().unwrap()),
        op::call(reg_tmp, reg_fwd_to_src, RegId::HP, RegId::CGAS),
        op::ret(RegId::ONE),
    ]);

    let script_data: Vec<u8> = [
        Call::new(src_contract, 0, 0).to_bytes().as_slice(),
        Call::new(dst_contract, 0, 0).to_bytes().as_slice(),
    ]
    .into_iter()
    .flatten()
    .copied()
    .chain(asset_id.to_bytes())
    .collect();

    let (_, tx, receipts, _) = test_context
        .start_script(script_ops, script_data)
        .script_gas_limit(1_000_000)
        .contract_input(src_contract)
        .contract_input(dst_contract)
        .coin_input(asset_id, balance_in)
        .fee_input()
        .contract_output(&src_contract)
        .contract_output(&dst_contract)
        .change_output(asset_id)
        .execute()
        .into_inner();

    let result = RunResult::extract_novalue(&receipts);
    let change = find_change(tx.outputs().to_vec(), asset_id);
    (
        (
            change,
            test_context.get_contract_balance(&src_contract, &asset_id),
            test_context.get_contract_balance(&dst_contract, &asset_id),
        ),
        result,
    )
}