solang 0.3.4

Solang Solidity Compiler
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
// SPDX-License-Identifier: Apache-2.0

use crate::codegen::cfg::HashTy;
use crate::codegen::Builtin;
use crate::codegen::Expression;
use crate::emit::binary::Binary;
use crate::emit::soroban::{HostFunctions, SorobanTarget};
use crate::emit::ContractArgs;
use crate::emit::{TargetRuntime, Variable};
use crate::emit_context;
use crate::sema::ast;
use crate::sema::ast::CallTy;
use crate::sema::ast::{Function, Type};

use inkwell::types::{BasicTypeEnum, IntType};
use inkwell::values::{
    ArrayValue, BasicMetadataValueEnum, BasicValue, BasicValueEnum, FunctionValue, IntValue,
    PointerValue,
};

use solang_parser::pt::{Loc, StorageType};

use num_traits::ToPrimitive;

use std::collections::HashMap;

// TODO: Implement TargetRuntime for SorobanTarget.
#[allow(unused_variables)]
impl<'a> TargetRuntime<'a> for SorobanTarget {
    fn get_storage_int(
        &self,
        bin: &Binary<'a>,
        function: FunctionValue,
        slot: PointerValue<'a>,
        ty: IntType<'a>,
    ) -> IntValue<'a> {
        todo!()
    }

    fn storage_load(
        &self,
        bin: &Binary<'a>,
        ty: &ast::Type,
        slot: &mut IntValue<'a>,
        function: FunctionValue<'a>,
        storage_type: &Option<StorageType>,
    ) -> BasicValueEnum<'a> {
        let storage_type = storage_type_to_int(storage_type);
        emit_context!(bin);

        let slot = if slot.is_const() {
            slot.as_basic_value_enum()
                .into_int_value()
                .const_cast(bin.context.i64_type(), false)
        } else {
            *slot
        };

        // === Call HasContractData ===
        let has_data_val = call!(
            HostFunctions::HasContractData.name(),
            &[
                slot.into(),
                bin.context.i64_type().const_int(storage_type, false).into(),
            ]
        )
        .try_as_basic_value()
        .left()
        .unwrap()
        .into_int_value();

        // === Use helper to check if it's true ===
        let condition = is_val_true(bin, has_data_val);

        // === Prepare blocks ===
        let parent = function;
        let then_bb = bin.context.append_basic_block(parent, "has_data");
        let else_bb = bin.context.append_basic_block(parent, "no_data");
        let merge_bb = bin.context.append_basic_block(parent, "merge");

        bin.builder
            .build_conditional_branch(condition, then_bb, else_bb)
            .unwrap();

        // === THEN block: call GetContractData ===
        bin.builder.position_at_end(then_bb);
        let value_from_contract = call!(
            HostFunctions::GetContractData.name(),
            &[
                slot.into(),
                bin.context.i64_type().const_int(storage_type, false).into(),
            ]
        )
        .try_as_basic_value()
        .left()
        .unwrap();
        bin.builder.build_unconditional_branch(merge_bb).unwrap();
        let then_value = value_from_contract;

        // === ELSE block: return default ===
        bin.builder.position_at_end(else_bb);
        let default_value = type_to_tagged_zero_val(bin, ty);

        bin.builder.build_unconditional_branch(merge_bb).unwrap();

        // === MERGE block with phi node ===
        bin.builder.position_at_end(merge_bb);
        let phi = bin
            .builder
            .build_phi(bin.context.i64_type(), "storage_result")
            .unwrap();
        phi.add_incoming(&[(&then_value, then_bb), (&default_value, else_bb)]);

        phi.as_basic_value()
    }

    /// Recursively store a type to storage
    fn storage_store(
        &self,
        bin: &Binary<'a>,
        ty: &ast::Type,
        existing: bool,
        slot: &mut IntValue<'a>,
        dest: BasicValueEnum<'a>,
        function: FunctionValue<'a>,
        storage_type: &Option<StorageType>,
    ) {
        emit_context!(bin);

        let storage_type = storage_type_to_int(storage_type);

        let function_value = bin
            .module
            .get_function(HostFunctions::PutContractData.name())
            .unwrap();
        let slot = if slot.is_const() {
            slot.as_basic_value_enum()
                .into_int_value()
                .const_cast(bin.context.i64_type(), false)
        } else {
            *slot
        };

        let value = bin
            .builder
            .build_call(
                function_value,
                &[
                    slot.into(),
                    dest.into(),
                    bin.context.i64_type().const_int(storage_type, false).into(),
                ],
                HostFunctions::PutContractData.name(),
            )
            .unwrap()
            .try_as_basic_value()
            .left()
            .unwrap()
            .into_int_value();
    }

    /// Recursively clear storage. The default implementation is for slot-based storage
    fn storage_delete(
        &self,
        bin: &Binary<'a>,
        ty: &Type,
        slot: &mut IntValue<'a>,
        function: FunctionValue<'a>,
    ) {
        unimplemented!()
    }

    // Bytes and string have special storage layout
    fn set_storage_string(
        &self,
        bin: &Binary<'a>,
        function: FunctionValue<'a>,
        slot: PointerValue<'a>,
        dest: BasicValueEnum<'a>,
    ) {
        unimplemented!()
    }

    fn get_storage_string(
        &self,
        bin: &Binary<'a>,
        function: FunctionValue,
        slot: PointerValue<'a>,
    ) -> PointerValue<'a> {
        unimplemented!()
    }

    fn set_storage_extfunc(
        &self,
        bin: &Binary<'a>,
        function: FunctionValue,
        slot: PointerValue,
        dest: PointerValue,
        dest_ty: BasicTypeEnum,
    ) {
        unimplemented!()
    }

    fn get_storage_extfunc(
        &self,
        bin: &Binary<'a>,
        function: FunctionValue,
        slot: PointerValue<'a>,
    ) -> PointerValue<'a> {
        unimplemented!()
    }

    fn get_storage_bytes_subscript(
        &self,
        bin: &Binary<'a>,
        function: FunctionValue,
        slot: IntValue<'a>,
        index: IntValue<'a>,
        loc: Loc,
    ) -> IntValue<'a> {
        unimplemented!()
    }

    fn set_storage_bytes_subscript(
        &self,
        bin: &Binary<'a>,
        function: FunctionValue,
        slot: IntValue<'a>,
        index: IntValue<'a>,
        value: IntValue<'a>,
        loc: Loc,
    ) {
        unimplemented!()
    }

    fn storage_subscript(
        &self,
        bin: &Binary<'a>,
        function: FunctionValue<'a>,
        ty: &Type,
        slot: IntValue<'a>,
        index: BasicValueEnum<'a>,
    ) -> IntValue<'a> {
        let vec_new = bin
            .builder
            .build_call(
                bin.module
                    .get_function(HostFunctions::VectorNew.name())
                    .unwrap(),
                &[],
                "vec_new",
            )
            .unwrap()
            .try_as_basic_value()
            .left()
            .unwrap()
            .into_int_value();

        let slot = if slot.is_const() {
            slot.as_basic_value_enum()
                .into_int_value()
                .const_cast(bin.context.i64_type(), false)
        } else {
            slot
        };

        // push the slot to the vector
        let res = bin
            .builder
            .build_call(
                bin.module
                    .get_function(HostFunctions::VecPushBack.name())
                    .unwrap(),
                &[vec_new.as_basic_value_enum().into(), slot.into()],
                "push",
            )
            .unwrap()
            .try_as_basic_value()
            .left()
            .unwrap()
            .into_int_value();

        // push the index to the vector
        let res = bin
            .builder
            .build_call(
                bin.module
                    .get_function(HostFunctions::VecPushBack.name())
                    .unwrap(),
                &[res.as_basic_value_enum().into(), index.into()],
                "push",
            )
            .unwrap()
            .try_as_basic_value()
            .left()
            .unwrap()
            .into_int_value();
        res
    }

    fn storage_push(
        &self,
        bin: &Binary<'a>,
        function: FunctionValue<'a>,
        ty: &Type,
        slot: IntValue<'a>,
        val: Option<BasicValueEnum<'a>>,
    ) -> BasicValueEnum<'a> {
        unimplemented!()
    }

    fn storage_pop(
        &self,
        bin: &Binary<'a>,
        function: FunctionValue<'a>,
        ty: &Type,
        slot: IntValue<'a>,
        load: bool,
        loc: Loc,
    ) -> Option<BasicValueEnum<'a>> {
        unimplemented!()
    }

    fn storage_array_length(
        &self,
        _bin: &Binary<'a>,
        _function: FunctionValue,
        _slot: IntValue<'a>,
        _elem_ty: &Type,
    ) -> IntValue<'a> {
        unimplemented!()
    }

    /// keccak256 hash
    fn keccak256_hash(
        &self,
        bin: &Binary<'a>,
        src: PointerValue,
        length: IntValue,
        dest: PointerValue,
    ) {
        unimplemented!()
    }

    /// Prints a string
    /// TODO: Implement this function, with a call to the `log` function in the Soroban runtime.
    fn print(&self, bin: &Binary, string: PointerValue, length: IntValue) {
        if string.is_const() && length.is_const() {
            let msg_pos = bin
                .builder
                .build_ptr_to_int(string, bin.context.i64_type(), "msg_pos")
                .unwrap();
            let length = length.const_cast(bin.context.i64_type(), false);

            let msg_pos_encoded = encode_value(msg_pos, 32, 4, bin);
            let length_encoded = encode_value(length, 32, 4, bin);

            bin.builder
                .build_call(
                    bin.module
                        .get_function(HostFunctions::LogFromLinearMemory.name())
                        .unwrap(),
                    &[
                        msg_pos_encoded.into(),
                        length_encoded.into(),
                        msg_pos_encoded.into(),
                        encode_value(bin.context.i64_type().const_zero(), 32, 4, bin).into(),
                    ],
                    "log",
                )
                .unwrap();
        } else {
            todo!("Dynamic String printing is not yet supported")
        }
    }

    /// Return success without any result
    fn return_empty_abi(&self, bin: &Binary) {
        unimplemented!()
    }

    /// Return failure code
    fn return_code<'b>(&self, bin: &'b Binary, ret: IntValue<'b>) {
        unimplemented!()
    }

    /// Return failure without any result
    fn assert_failure(&self, bin: &Binary, data: PointerValue, length: IntValue) {
        bin.builder.build_unreachable().unwrap();
    }

    fn builtin_function(
        &self,
        bin: &Binary<'a>,
        function: FunctionValue<'a>,
        builtin_func: &Function,
        args: &[BasicMetadataValueEnum<'a>],
        first_arg_type: Option<BasicTypeEnum>,
    ) -> Option<BasicValueEnum<'a>> {
        unimplemented!()
    }

    /// Calls constructor
    fn create_contract<'b>(
        &mut self,
        bin: &Binary<'b>,
        function: FunctionValue<'b>,
        success: Option<&mut BasicValueEnum<'b>>,
        contract_no: usize,
        address: PointerValue<'b>,
        encoded_args: BasicValueEnum<'b>,
        encoded_args_len: BasicValueEnum<'b>,
        contract_args: ContractArgs<'b>,
        loc: Loc,
    ) {
        unimplemented!()
    }

    /// call external function
    fn external_call<'b>(
        &self,
        bin: &Binary<'b>,
        function: FunctionValue<'b>,
        success: Option<&mut BasicValueEnum<'b>>,
        payload: PointerValue<'b>,
        payload_len: IntValue<'b>,
        address: Option<BasicValueEnum<'b>>,
        contract_args: ContractArgs<'b>,
        ty: CallTy,
        loc: Loc,
    ) {
        let offset = bin.context.i64_type().const_int(0, false);

        let start = unsafe {
            bin.builder
                .build_gep(
                    bin.context.i64_type().array_type(1),
                    payload,
                    &[bin.context.i64_type().const_zero(), offset],
                    "start",
                )
                .unwrap()
        };

        let symbol = bin
            .builder
            .build_load(bin.context.i64_type(), start, "symbol")
            .unwrap()
            .into_int_value();

        let args_len = bin
            .builder
            .build_int_unsigned_div(
                payload_len,
                bin.context.i64_type().const_int(8, false),
                "args_len",
            )
            .unwrap();

        let args_len = bin
            .builder
            .build_int_sub(
                args_len,
                bin.context.i64_type().const_int(1, false),
                "args_len",
            )
            .unwrap();

        let args_len_encoded = encode_value(args_len, 32, 4, bin);

        let offset = bin.context.i64_type().const_int(1, false);
        let args_ptr = unsafe {
            bin.builder
                .build_gep(
                    bin.context.i64_type().array_type(1),
                    payload,
                    &[bin.context.i64_type().const_zero(), offset],
                    "start",
                )
                .unwrap()
        };

        let args_ptr_to_int = bin
            .builder
            .build_ptr_to_int(args_ptr, bin.context.i64_type(), "args_ptr")
            .unwrap();

        let args_ptr_encoded = encode_value(args_ptr_to_int, 32, 4, bin);

        let vec_object = bin
            .builder
            .build_call(
                bin.module
                    .get_function(HostFunctions::VectorNewFromLinearMemory.name())
                    .unwrap(),
                &[args_ptr_encoded.into(), args_len_encoded.into()],
                "vec_object",
            )
            .unwrap()
            .try_as_basic_value()
            .left()
            .unwrap()
            .into_int_value();

        let call_res = bin
            .builder
            .build_call(
                bin.module.get_function(HostFunctions::Call.name()).unwrap(),
                &[address.unwrap().into(), symbol.into(), vec_object.into()],
                "call",
            )
            .unwrap()
            .try_as_basic_value()
            .left()
            .unwrap()
            .into_int_value();

        let allocate_i64 = bin
            .builder
            .build_alloca(bin.context.i64_type(), "allocate_i64")
            .unwrap();

        bin.builder.build_store(allocate_i64, call_res).unwrap();

        *bin.return_data.borrow_mut() = Some(allocate_i64);
    }

    /// send value to address
    fn value_transfer<'b>(
        &self,
        _bin: &Binary<'b>,
        _function: FunctionValue,
        _success: Option<&mut BasicValueEnum<'b>>,
        _address: PointerValue<'b>,
        _value: IntValue<'b>,
        loc: Loc,
    ) {
        unimplemented!()
    }

    /// builtin expressions
    fn builtin<'b>(
        &self,
        bin: &Binary<'b>,
        expr: &Expression,
        vartab: &HashMap<usize, Variable<'b>>,
        function: FunctionValue<'b>,
    ) -> BasicValueEnum<'b> {
        emit_context!(bin);

        match expr {
            Expression::Builtin {
                kind: Builtin::ExtendTtl,
                args,
                ..
            } => {
                // Get arguments
                // (func $extend_contract_data_ttl (param $k_val i64) (param $t_storage_type i64) (param $threshold_u32_val i64) (param $extend_to_u32_val i64) (result i64))
                assert_eq!(args.len(), 4, "extendTtl expects 4 arguments");
                // SAFETY: We already checked that the length of args is 4 so it is safe to unwrap here
                let slot_no = match args.first().unwrap() {
                    Expression::NumberLiteral { value, .. } => value,
                    _ => panic!(
                        "Expected slot_no to be of type Expression::NumberLiteral. Actual: {:?}",
                        args.get(1).unwrap()
                    ),
                }
                .to_u64()
                .unwrap();
                let threshold = match args.get(1).unwrap() {
                    Expression::NumberLiteral { value, .. } => value,
                    _ => panic!(
                        "Expected threshold to be of type Expression::NumberLiteral. Actual: {:?}",
                        args.get(1).unwrap()
                    ),
                }
                .to_u64()
                .unwrap();
                let extend_to = match args.get(2).unwrap() {
                    Expression::NumberLiteral { value, .. } => value,
                    _ => panic!(
                        "Expected extend_to to be of type Expression::NumberLiteral. Actual: {:?}",
                        args.get(2).unwrap()
                    ),
                }
                .to_u64()
                .unwrap();
                let storage_type = match args.get(3).unwrap() {
                    Expression::NumberLiteral { value, .. } => value,
                    _ => panic!(
                    "Expected storage_type to be of type Expression::NumberLiteral. Actual: {:?}",
                    args.get(3).unwrap()
                ),
                }
                .to_u64()
                .unwrap();

                // Encode the values (threshold and extend_to)
                // See: https://github.com/stellar/stellar-protocol/blob/master/core/cap-0046-01.md#tag-values
                let threshold_u32_val = (threshold << 32) + 4;
                let extend_to_u32_val = (extend_to << 32) + 4;

                // Call the function
                let function_name = HostFunctions::ExtendContractDataTtl.name();
                let function_value = bin.module.get_function(function_name).unwrap();

                let value = bin
                    .builder
                    .build_call(
                        function_value,
                        &[
                            bin.context.i64_type().const_int(slot_no, false).into(),
                            bin.context.i64_type().const_int(storage_type, false).into(),
                            bin.context
                                .i64_type()
                                .const_int(threshold_u32_val, false)
                                .into(),
                            bin.context
                                .i64_type()
                                .const_int(extend_to_u32_val, false)
                                .into(),
                        ],
                        function_name,
                    )
                    .unwrap()
                    .try_as_basic_value()
                    .left()
                    .unwrap()
                    .into_int_value();

                value.into()
            }
            Expression::Builtin {
                kind: Builtin::ExtendInstanceTtl,
                args,
                ..
            } => {
                // Get arguments
                // (func $extend_contract_data_ttl (param $k_val i64) (param $t_storage_type i64) (param $threshold_u32_val i64) (param $extend_to_u32_val i64) (result i64))
                assert_eq!(args.len(), 2, "extendTtl expects 2 arguments");
                // SAFETY: We already checked that the length of args is 2 so it is safe to unwrap here
                let threshold = match args.first().unwrap() {
                    Expression::NumberLiteral { value, .. } => value,
                    _ => panic!(
                        "Expected threshold to be of type Expression::NumberLiteral. Actual: {:?}",
                        args.get(1).unwrap()
                    ),
                }
                .to_u64()
                .unwrap();
                let extend_to = match args.get(1).unwrap() {
                    Expression::NumberLiteral { value, .. } => value,
                    _ => panic!(
                        "Expected extend_to to be of type Expression::NumberLiteral. Actual: {:?}",
                        args.get(2).unwrap()
                    ),
                }
                .to_u64()
                .unwrap();

                // Encode the values (threshold and extend_to)
                // See: https://github.com/stellar/stellar-protocol/blob/master/core/cap-0046-01.md#tag-values
                let threshold_u32_val = (threshold << 32) + 4;
                let extend_to_u32_val = (extend_to << 32) + 4;

                // Call the function
                let function_name = HostFunctions::ExtendCurrentContractInstanceAndCodeTtl.name();
                let function_value = bin.module.get_function(function_name).unwrap();

                let value = bin
                    .builder
                    .build_call(
                        function_value,
                        &[
                            bin.context
                                .i64_type()
                                .const_int(threshold_u32_val, false)
                                .into(),
                            bin.context
                                .i64_type()
                                .const_int(extend_to_u32_val, false)
                                .into(),
                        ],
                        function_name,
                    )
                    .unwrap()
                    .try_as_basic_value()
                    .left()
                    .unwrap()
                    .into_int_value();

                value.into()
            }
            _ => unimplemented!("unsupported builtin"),
        }
    }

    /// Return the return data from an external call (either revert error or return values)
    fn return_data<'b>(&self, bin: &Binary<'b>, function: FunctionValue<'b>) -> PointerValue<'b> {
        bin.return_data.borrow().unwrap()
    }

    /// Return the value we received
    fn value_transferred<'b>(&self, bin: &Binary<'b>) -> IntValue<'b> {
        unimplemented!()
    }

    /// Terminate execution, destroy bin and send remaining funds to addr
    fn selfdestruct<'b>(&self, bin: &Binary<'b>, addr: ArrayValue<'b>) {
        unimplemented!()
    }

    /// Crypto Hash
    fn hash<'b>(
        &self,
        bin: &Binary<'b>,
        function: FunctionValue<'b>,
        hash: HashTy,
        string: PointerValue<'b>,
        length: IntValue<'b>,
    ) -> IntValue<'b> {
        unimplemented!()
    }

    /// Emit event
    fn emit_event<'b>(
        &self,
        bin: &Binary<'b>,
        function: FunctionValue<'b>,
        data: BasicValueEnum<'b>,
        topics: &[BasicValueEnum<'b>],
    ) {
        unimplemented!()
    }

    /// Return ABI encoded data
    fn return_abi_data<'b>(
        &self,
        bin: &Binary<'b>,
        data: PointerValue<'b>,
        data_len: BasicValueEnum<'b>,
    ) {
        unimplemented!()
    }
}

fn storage_type_to_int(storage_type: &Option<StorageType>) -> u64 {
    if let Some(storage_type) = storage_type {
        match storage_type {
            StorageType::Temporary(_) => 0,
            StorageType::Persistent(_) => 1,
            StorageType::Instance(_) => 2,
        }
    } else {
        1
    }
}

fn encode_value<'a>(value: IntValue<'a>, shift: u64, add: u64, bin: &'a Binary) -> IntValue<'a> {
    let shifted = bin
        .builder
        .build_left_shift(
            value,
            bin.context.i64_type().const_int(shift, false),
            "temp",
        )
        .unwrap();
    bin.builder
        .build_int_add(
            shifted,
            bin.context.i64_type().const_int(add, false),
            "encoded",
        )
        .unwrap()
}

fn is_val_true<'ctx>(bin: &Binary<'ctx>, val: IntValue<'ctx>) -> IntValue<'ctx> {
    let tag_mask = bin.context.i64_type().const_int(0xff, false);
    let tag_true = bin.context.i64_type().const_int(1, false);

    let tag = bin
        .builder
        .build_and(val, tag_mask, "val_tag")
        .expect("build_and failed");

    bin.builder
        .build_int_compare(inkwell::IntPredicate::EQ, tag, tag_true, "is_val_true")
        .expect("build_int_compare failed")
}

/// Returns a Val representing a default zero value with the correct Soroban Tag.
pub fn type_to_tagged_zero_val<'ctx>(bin: &Binary<'ctx>, ty: &Type) -> IntValue<'ctx> {
    let context = &bin.context;
    let i64_type = context.i64_type();

    // Tag definitions from CAP-0046
    let tag = match ty {
        Type::Bool => 0,        // Tag::False
        Type::Uint(32) => 4,    // Tag::U32Val
        Type::Int(32) => 5,     // Tag::I32Val
        Type::Uint(64) => 6,    // Tag::U64Small
        Type::Int(64) => 7,     // Tag::I64Small
        Type::Uint(128) => 10,  // Tag::U128Small
        Type::Int(128) => 11,   // Tag::I128Small
        Type::Uint(256) => 12,  // Tag::U256Small
        Type::Int(256) => 13,   // Tag::I256Small
        Type::String => 73,     // Tag::StringObject
        Type::Address(_) => 77, // Tag::AddressObject
        Type::Void => 2,        // Tag::Void
        _ => {
            // Fallback to Void for unsupported types
            2 // Tag::Void
        }
    };

    // All zero body + tag in lower 8 bits
    let tag_val: u64 = tag;
    i64_type.const_int(tag_val, false)
}