everscale_types/abi/
contract.rs

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
use std::borrow::Cow;
use std::str::FromStr;
use std::sync::Arc;

use ahash::HashMap;
use anyhow::Result;
use serde::Deserialize;
use sha2::Digest;

use crate::abi::value::ser::AbiSerializer;
use crate::abi::AbiHeader;
use crate::cell::{
    Cell, CellBuilder, CellFamily, CellSlice, CellSliceRange, DynCell, HashBytes, Size, Store,
};
use crate::dict::RawDict;
use crate::models::{
    ExtInMsgInfo, IntAddr, MsgInfo, OwnedMessage, OwnedRelaxedMessage, RelaxedIntMsgInfo,
    RelaxedMsgInfo, StateInit, StdAddr,
};
use crate::num::Tokens;
use crate::prelude::Dict;

use super::error::AbiError;
use super::{AbiHeaderType, AbiType, AbiValue, AbiVersion, NamedAbiType, NamedAbiValue};

/// Contract ABI definition.
pub struct Contract {
    /// ABI version.
    pub abi_version: AbiVersion,

    /// List of headers for external messages.
    ///
    /// NOTE: header order matters.
    pub headers: Arc<[AbiHeaderType]>,

    /// A mapping with all contract methods by name.
    pub functions: HashMap<Arc<str>, Function>,

    /// A mapping with all contract events by name.
    pub events: HashMap<Arc<str>, Event>,

    /// Contract init data.
    pub init_data: HashMap<Arc<str>, (u64, NamedAbiType)>,

    /// Contract storage fields.
    pub fields: Arc<[NamedAbiType]>,
}

impl Contract {
    /// Finds a method declaration with the specfied id.
    pub fn find_function_by_id(&self, id: u32, input: bool) -> Option<&Function> {
        self.functions
            .values()
            .find(|item| input && item.input_id == id || !input && item.output_id == id)
    }

    /// Finds an event with the specified id.
    pub fn find_event_by_id(&self, id: u32) -> Option<&Event> {
        self.events.values().find(|event| event.id == id)
    }

    /// Returns a new init data with replaced items.
    ///
    /// NOTE: `tokens` can be a subset of init data fields, all other
    /// will not be touched.
    pub fn update_init_data(
        &self,
        pubkey: Option<&ed25519_dalek::VerifyingKey>,
        tokens: &[NamedAbiValue],
        data: &Cell,
    ) -> Result<Cell> {
        // Always check if data is valid
        let mut result = data.parse::<RawDict<64>>()?;

        if pubkey.is_none() && tokens.is_empty() {
            // Do nothing if no items are updated
            return Ok(data.clone());
        }

        let context = &mut Cell::empty_context();
        let mut key_builder = CellBuilder::new();

        for token in tokens {
            let Some((key, ty)) = self.init_data.get(token.name.as_ref()) else {
                anyhow::bail!(AbiError::UnexpectedInitDataParam(token.name.clone()));
            };
            token.check_type(ty)?;

            key_builder.store_u64(*key)?;

            result.set_ext(
                key_builder.as_data_slice(),
                &token.make_builder(self.abi_version)?.as_full_slice(),
                context,
            )?;

            key_builder.rewind(64)?;
        }

        // Set public key if specified
        if let Some(pubkey) = pubkey {
            key_builder.store_u64(0)?;
            result.set_ext(
                key_builder.as_data_slice(),
                &CellBuilder::from_raw_data(pubkey.as_bytes(), 256)?.as_data_slice(),
                context,
            )?;
        }

        // Encode init data as mapping
        CellBuilder::build_from_ext(result, context).map_err(From::from)
    }

    /// Encodes an account data with the specified initial parameters.
    ///
    /// NOTE: `tokens` can be a subset of init data fields, all other
    /// will be set to default.
    pub fn encode_init_data(
        &self,
        pubkey: &ed25519_dalek::VerifyingKey,
        tokens: &[NamedAbiValue],
    ) -> Result<Cell> {
        let mut result = RawDict::<64>::new();

        let mut init_data = self
            .init_data
            .iter()
            .map(|(name, value)| (name.as_ref(), value))
            .collect::<HashMap<_, _>>();

        let context = &mut Cell::empty_context();
        let mut key_builder = CellBuilder::new();

        // Write explicitly provided values
        for token in tokens {
            let Some((key, ty)) = init_data.remove(token.name.as_ref()) else {
                anyhow::bail!(AbiError::UnexpectedInitDataParam(token.name.clone()));
            };
            token.check_type(ty)?;

            key_builder.store_u64(*key)?;

            result.set_ext(
                key_builder.as_data_slice(),
                &token.make_builder(self.abi_version)?.as_full_slice(),
                context,
            )?;

            key_builder.rewind(64)?;
        }

        // Write remaining values with default values
        for (key, ty) in init_data.into_values() {
            key_builder.store_u64(*key)?;

            result.set_ext(
                key_builder.as_data_slice(),
                &ty.make_default_value()
                    .make_builder(self.abi_version)?
                    .as_full_slice(),
                context,
            )?;

            key_builder.rewind(64)?;
        }

        // Set public key
        key_builder.store_u64(0)?;
        result.set_ext(
            key_builder.as_data_slice(),
            &CellBuilder::from_raw_data(pubkey.as_bytes(), 256)?.as_data_slice(),
            context,
        )?;

        // Encode init data as mapping
        CellBuilder::build_from_ext(result, context).map_err(From::from)
    }

    /// Tries to parse init data fields of this contract from an account data.
    pub fn decode_init_data(&self, data: &DynCell) -> Result<Vec<NamedAbiValue>> {
        let init_data = data.parse::<Dict<u64, CellSlice>>()?;

        let mut result = Vec::with_capacity(self.init_data.len());

        for (key, item) in self.init_data.values() {
            let Some(mut value) = init_data.get(key)? else {
                anyhow::bail!(AbiError::InitDataFieldNotFound(item.name.clone()));
            };
            result.push(NamedAbiValue::load(item, self.abi_version, &mut value)?);
        }

        Ok(result)
    }

    /// Encodes an account data with the specified storage fields of this contract.
    pub fn encode_fields(&self, tokens: &[NamedAbiValue]) -> Result<CellBuilder> {
        ok!(NamedAbiValue::check_types(tokens, &self.fields));
        NamedAbiValue::tuple_to_builder(tokens, self.abi_version).map_err(From::from)
    }

    /// Tries to parse storage fields of this contract from an account data.
    ///
    /// NOTE: The slice is required to contain nothing other than these fields.
    pub fn decode_fields(&self, mut slice: CellSlice<'_>) -> Result<Vec<NamedAbiValue>> {
        self.decode_fields_ext(&mut slice, false)
    }

    /// Tries to parse storage fields of this contract from an account data.
    pub fn decode_fields_ext(
        &self,
        slice: &mut CellSlice<'_>,
        allow_partial: bool,
    ) -> Result<Vec<NamedAbiValue>> {
        let res = ok!(NamedAbiValue::load_tuple_ext(
            &self.fields,
            self.abi_version,
            true,
            allow_partial,
            slice
        ));
        ok!(AbiValue::check_remaining(slice, allow_partial));
        Ok(res)
    }
}

impl<'de> Deserialize<'de> for Contract {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use serde::de::Error;

        #[repr(transparent)]
        struct Id(u32);

        impl<'de> Deserialize<'de> for Id {
            fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                #[derive(Deserialize)]
                #[serde(transparent)]
                struct Id<'a>(#[serde(borrow)] Cow<'a, str>);

                match ok!(Id::deserialize(deserializer)).0.strip_prefix("0x") {
                    Some(s) => u32::from_str_radix(s, 16).map(Self).map_err(Error::custom),
                    None => Err(Error::custom("Hex number must be prefixed with 0x")),
                }
            }
        }

        #[derive(Deserialize)]
        struct SerdeContract {
            #[serde(default, rename = "ABI version")]
            abi_version: Option<u8>,
            #[serde(default)]
            version: Option<String>,
            #[serde(default)]
            header: Vec<AbiHeaderType>,
            functions: Vec<SerdeFunction>,
            #[serde(default)]
            events: Vec<SerdeEvent>,
            #[serde(default)]
            data: Vec<InitData>,
            #[serde(default)]
            fields: Vec<NamedAbiType>,
        }

        #[derive(Deserialize)]
        struct SerdeFunction {
            name: String,
            #[serde(default)]
            inputs: Vec<NamedAbiType>,
            #[serde(default)]
            outputs: Vec<NamedAbiType>,
            #[serde(default)]
            id: Option<Id>,
        }

        #[derive(Deserialize)]
        struct SerdeEvent {
            name: String,
            #[serde(default)]
            inputs: Vec<NamedAbiType>,
            #[serde(default)]
            id: Option<Id>,
        }

        #[derive(Deserialize)]
        struct InitData {
            key: u64,
            #[serde(flatten)]
            ty: NamedAbiType,
        }

        let contract = ok!(SerdeContract::deserialize(deserializer));
        let abi_version = if let Some(version) = &contract.version {
            ok!(AbiVersion::from_str(version).map_err(Error::custom))
        } else if let Some(major) = contract.abi_version {
            AbiVersion::new(major, 0)
        } else {
            return Err(Error::custom("No ABI version found"));
        };

        let headers = Arc::<[AbiHeaderType]>::from(contract.header);

        let functions = contract
            .functions
            .into_iter()
            .map(|item| {
                let (input_id, output_id) = match item.id {
                    Some(Id(id)) => (id, id),
                    None => {
                        let id = Function::compute_function_id(
                            abi_version,
                            &item.name,
                            headers.as_ref(),
                            &item.inputs,
                            &item.outputs,
                        );
                        (id & Function::INPUT_ID_MASK, id | !Function::INPUT_ID_MASK)
                    }
                };
                let name = Arc::<str>::from(item.name);
                (
                    name.clone(),
                    Function {
                        abi_version,
                        name,
                        headers: headers.clone(),
                        inputs: Arc::from(item.inputs),
                        outputs: Arc::from(item.outputs),
                        input_id,
                        output_id,
                    },
                )
            })
            .collect();

        let events = contract
            .events
            .into_iter()
            .map(|item| {
                let id = match item.id {
                    Some(Id(id)) => id,
                    None => {
                        let id = Event::compute_event_id(abi_version, &item.name, &item.inputs);
                        id & Function::INPUT_ID_MASK
                    }
                };
                let name = Arc::<str>::from(item.name);
                (
                    name.clone(),
                    Event {
                        abi_version,
                        name,
                        inputs: Arc::from(item.inputs),
                        id,
                    },
                )
            })
            .collect();

        let init_data = contract
            .data
            .into_iter()
            .map(|item| {
                let name = item.ty.name.clone();
                (name, (item.key, item.ty))
            })
            .collect();

        Ok(Self {
            abi_version,
            headers,
            functions,
            events,
            init_data,
            fields: Arc::from(contract.fields),
        })
    }
}

/// Contract method ABI definition.
#[derive(Debug, Clone)]
pub struct Function {
    /// ABI version (same as contract ABI version).
    pub abi_version: AbiVersion,
    /// List of headers for external messages.
    /// Must be the same as in contract.
    ///
    /// NOTE: header order matters.
    pub headers: Arc<[AbiHeaderType]>,
    /// Method name.
    pub name: Arc<str>,
    /// Method input argument types.
    pub inputs: Arc<[NamedAbiType]>,
    /// Method output types.
    pub outputs: Arc<[NamedAbiType]>,
    /// Function id in incoming messages (with input).
    pub input_id: u32,
    /// Function id in outgoing messages (with output).
    pub output_id: u32,
}

impl Function {
    /// Mask with a bit difference of input id and output id.
    pub const INPUT_ID_MASK: u32 = 0x7fffffff;

    /// Computes function id from the full function signature.
    pub fn compute_function_id(
        abi_version: AbiVersion,
        name: &str,
        headers: &[AbiHeaderType],
        inputs: &[NamedAbiType],
        outputs: &[NamedAbiType],
    ) -> u32 {
        let mut hasher = sha2::Sha256::new();
        FunctionSignatureRaw {
            abi_version,
            name,
            headers,
            inputs,
            outputs,
        }
        .update_hasher(&mut hasher);

        let hash: [u8; 32] = hasher.finalize().into();
        u32::from_be_bytes(hash[0..4].try_into().unwrap())
    }

    /// Encodes message body without headers.
    pub fn encode_internal_msg_body(
        version: AbiVersion,
        id: u32,
        tokens: &[NamedAbiValue],
    ) -> Result<CellBuilder> {
        let mut serializer = AbiSerializer::new(version);
        let output_id = AbiValue::uint(32, id);

        serializer.reserve_value(&output_id);
        for token in tokens {
            serializer.reserve_value(&token.value);
        }

        let context = &mut Cell::empty_context();
        serializer.write_value(&output_id, context)?;
        serializer.write_tuple(tokens, context)?;
        serializer.finalize(context).map_err(From::from)
    }

    /// Returns a method builder with the specified ABI version and name.
    #[inline]
    pub fn builder<T: Into<String>>(abi_version: AbiVersion, name: T) -> FunctionBuilder {
        FunctionBuilder::new(abi_version, name)
    }

    /// Encodes an unsigned body with invocation of this method as an external message.
    pub fn encode_external<'f, 'a: 'f>(&'f self, tokens: &'a [NamedAbiValue]) -> ExternalInput {
        ExternalInput {
            function: self,
            tokens,
            time: None,
            expire_at: None,
            pubkey: None,
            address: None,
        }
    }

    /// Tries to parse input arguments for this method from an external message body.
    ///
    /// NOTE: The slice is required to contain nothing other than these arguments.
    pub fn decode_external_input(&self, mut slice: CellSlice<'_>) -> Result<Vec<NamedAbiValue>> {
        self.decode_external_input_ext(&mut slice, false)
    }

    /// Tries to parse input arguments for this method from an external message body.
    pub fn decode_external_input_ext(
        &self,
        slice: &mut CellSlice<'_>,
        allow_partial: bool,
    ) -> Result<Vec<NamedAbiValue>> {
        // Read prefix
        let id = if self.abi_version.major == 1 {
            // Load input id
            let id = slice.load_u32()?;
            // Skip signature
            slice.load_reference()?;
            // Skip headers
            ok!(AbiHeader::skip_all(&self.headers, slice));

            id
        } else {
            // Skip signature
            if slice.load_bit()? {
                slice.skip_first(512, 0)?;
            }
            // Skip headers
            ok!(AbiHeader::skip_all(&self.headers, slice));
            // Load input id
            slice.load_u32()?
        };

        // Check input id
        anyhow::ensure!(
            id == self.input_id,
            AbiError::InputIdMismatch {
                expected: self.input_id,
                id
            }
        );

        let res = ok!(NamedAbiValue::load_tuple_ext(
            &self.inputs,
            self.abi_version,
            true,
            allow_partial,
            slice
        ));
        ok!(AbiValue::check_remaining(slice, allow_partial));
        Ok(res)
    }

    /// Encodes a message body with invocation of this method as an internal message.
    pub fn encode_internal_input(&self, tokens: &[NamedAbiValue]) -> Result<CellBuilder> {
        ok!(NamedAbiValue::check_types(tokens, &self.inputs));
        Self::encode_internal_msg_body(self.abi_version, self.input_id, tokens)
    }

    /// Encodes an internal message with invocation of this method.
    pub fn encode_internal_message(
        &self,
        tokens: &[NamedAbiValue],
        dst: IntAddr,
        value: Tokens,
        bounce: bool,
        state_init: Option<&StateInit>,
    ) -> Result<Box<OwnedRelaxedMessage>> {
        let body = self.encode_internal_input(tokens)?;
        let cell = body.build()?;
        let range = CellSliceRange::full(cell.as_ref());

        Ok(Box::new(OwnedRelaxedMessage {
            info: RelaxedMsgInfo::Int(RelaxedIntMsgInfo {
                dst,
                bounce,
                value: value.into(),
                ..Default::default()
            }),
            body: (cell, range),
            init: state_init.cloned(),
            layout: None,
        }))
    }

    /// Tries to parse input arguments for this method from an internal message body.
    ///
    /// NOTE: The slice is required to contain nothing other than these arguments.
    pub fn decode_internal_input(&self, mut slice: CellSlice<'_>) -> Result<Vec<NamedAbiValue>> {
        self.decode_internal_input_ext(&mut slice, false)
    }

    /// Tries to parse input arguments for this method from an internal message body.
    pub fn decode_internal_input_ext(
        &self,
        slice: &mut CellSlice<'_>,
        allow_partial: bool,
    ) -> Result<Vec<NamedAbiValue>> {
        let id = slice.load_u32()?;
        anyhow::ensure!(
            id == self.input_id,
            AbiError::InputIdMismatch {
                expected: self.input_id,
                id
            }
        );
        let res = ok!(NamedAbiValue::load_tuple_ext(
            &self.inputs,
            self.abi_version,
            true,
            allow_partial,
            slice
        ));
        ok!(AbiValue::check_remaining(slice, allow_partial));
        Ok(res)
    }

    /// Encodes a message body with result of invocation of this method.
    pub fn encode_output(&self, tokens: &[NamedAbiValue]) -> Result<CellBuilder> {
        ok!(NamedAbiValue::check_types(tokens, &self.outputs));
        Self::encode_internal_msg_body(self.abi_version, self.output_id, tokens)
    }

    /// Tries to parse output arguments of this method from a message body.
    ///
    /// NOTE: The slice is required to contain nothing other than these arguments.
    pub fn decode_output(&self, mut slice: CellSlice<'_>) -> Result<Vec<NamedAbiValue>> {
        self.decode_output_ext(&mut slice, false)
    }

    /// Tries to parse output arguments of this method from a message body.
    pub fn decode_output_ext(
        &self,
        slice: &mut CellSlice<'_>,
        allow_partial: bool,
    ) -> Result<Vec<NamedAbiValue>> {
        let id = slice.load_u32()?;
        anyhow::ensure!(
            id == self.output_id,
            AbiError::OutputIdMismatch {
                expected: self.output_id,
                id
            }
        );
        let res = ok!(NamedAbiValue::load_tuple_ext(
            &self.outputs,
            self.abi_version,
            true,
            allow_partial,
            slice
        ));
        ok!(AbiValue::check_remaining(slice, allow_partial));
        Ok(res)
    }

    /// Returns an object which can be used to display the normalized signature of this method.
    pub fn display_signature(&self) -> impl std::fmt::Display + '_ {
        FunctionSignatureRaw {
            abi_version: self.abi_version,
            name: &self.name,
            headers: &self.headers,
            inputs: &self.inputs,
            outputs: &self.outputs,
        }
    }
}

/// External input builder.
#[derive(Clone)]
pub struct ExternalInput<'f, 'a> {
    function: &'f Function,
    tokens: &'a [NamedAbiValue],
    time: Option<u64>,
    expire_at: Option<u32>,
    pubkey: Option<&'a ed25519_dalek::VerifyingKey>,
    address: Option<&'a StdAddr>,
}

impl<'f, 'a> ExternalInput<'f, 'a> {
    /// Builds an external message to the specified address.
    pub fn build_message(&self, address: &StdAddr) -> Result<UnsignedExternalMessage> {
        Ok(ok!(self.build_input_ext(Some(address))).with_dst(address.clone()))
    }

    /// Builds an exteranl message to the specified address without signature.
    ///
    /// Returns an expiration timestamp along with message.
    pub fn build_message_without_signature(
        &self,
        address: &StdAddr,
    ) -> Result<(u32, OwnedMessage)> {
        let (expire_at, body) = ok!(self.build_input_without_signature());
        let range = CellSliceRange::full(body.as_ref());
        Ok((
            expire_at,
            OwnedMessage {
                info: MsgInfo::ExtIn(ExtInMsgInfo {
                    dst: IntAddr::Std(address.clone()),
                    ..Default::default()
                }),
                body: (body, range),
                init: None,
                layout: None,
            },
        ))
    }

    /// Builds an external message body.
    pub fn build_input(&self) -> Result<UnsignedBody> {
        self.build_input_ext(self.address)
    }

    fn build_input_ext(&self, address: Option<&StdAddr>) -> Result<UnsignedBody> {
        let (expire_at, payload) = self.build_payload(true)?;

        let context = &mut Cell::empty_context();
        let hash = if self.function.abi_version >= AbiVersion::V2_3 {
            let mut to_sign = CellBuilder::new();
            match address {
                Some(address) => address.store_into(&mut to_sign, context)?,
                None => anyhow::bail!(AbiError::AddressNotProvided),
            };
            to_sign.store_slice(payload.as_slice()?)?;
            *to_sign.build_ext(context)?.repr_hash()
        } else {
            *payload.repr_hash()
        };

        Ok(UnsignedBody {
            abi_version: self.function.abi_version,
            expire_at,
            payload,
            hash,
        })
    }

    /// Builds an external message body without signature.
    pub fn build_input_without_signature(&self) -> Result<(u32, Cell)> {
        self.build_payload(false)
    }

    fn build_payload(&self, reserve_signature: bool) -> Result<(u32, Cell)> {
        const DEFAULT_TIMEOUT_SEC: u32 = 60;

        fn now_ms() -> u64 {
            std::time::SystemTime::now()
                .duration_since(std::time::SystemTime::UNIX_EPOCH)
                .unwrap()
                .as_millis() as u64
        }

        ok!(NamedAbiValue::check_types(
            self.tokens,
            &self.function.inputs
        ));

        let abi_version = self.function.abi_version;

        let mut serializer = AbiSerializer::new(abi_version);

        if reserve_signature {
            serializer.add_offset(if abi_version.major == 1 {
                // Reserve reference for signature
                Size { bits: 0, refs: 1 }
            } else {
                let bits = if abi_version >= AbiVersion::V2_3 {
                    // Reserve only for address as it also ensures the the signature will fit
                    IntAddr::BITS_MAX
                } else {
                    // Reserve for `Some` non-empty signature
                    1 + 512
                };
                Size { bits, refs: 0 }
            });
        }

        let input_id = AbiValue::uint(32, self.function.input_id);

        serializer.reserve_headers(&self.function.headers, self.pubkey.is_some());
        serializer.reserve_value(&input_id);
        for token in self.tokens {
            serializer.reserve_value(&token.value);
        }

        let context = &mut Cell::empty_context();

        if !reserve_signature {
            let value = if abi_version.major == 1 {
                AbiValue::Cell(Cell::default())
            } else {
                AbiValue::Bool(false)
            };
            serializer.reserve_value(&value);
            serializer.write_value(&value, context)?;
        }

        let time = self.time.unwrap_or_else(now_ms);
        let expire_at = self
            .expire_at
            .unwrap_or((time / 1000) as u32 + DEFAULT_TIMEOUT_SEC);

        for header in self.function.headers.as_ref() {
            serializer.write_header_value(&match header {
                AbiHeaderType::Time => AbiHeader::Time(time),
                AbiHeaderType::Expire => AbiHeader::Expire(expire_at),
                AbiHeaderType::PublicKey => {
                    AbiHeader::PublicKey(self.pubkey.map(|key| Box::new(*key)))
                }
            })?;
        }

        serializer.write_value(&input_id, context)?;
        serializer.write_tuple(self.tokens, context)?;

        let payload = serializer.finalize(context)?.build_ext(context)?;
        Ok((expire_at, payload))
    }

    /// Use the specified time for the `time` header.
    #[inline]
    pub fn set_time(&mut self, time: u64) {
        self.time = Some(time);
    }

    /// Use the specified time for the `time` header.
    #[inline]
    pub fn with_time(mut self, time: u64) -> Self {
        self.set_time(time);
        self
    }

    /// Use the specified expiration timestamp for the `expire` header.
    #[inline]
    pub fn set_expire_at(&mut self, expire_at: u32) {
        self.expire_at = Some(expire_at);
    }

    /// Use the specified expiration timestamp for the `expire` header.
    #[inline]
    pub fn with_expire_at(mut self, expire_at: u32) -> Self {
        self.set_expire_at(expire_at);
        self
    }

    /// Use the specified public key for the `pubkey` header.
    #[inline]
    pub fn set_pubkey(&mut self, pubkey: &'a ed25519_dalek::VerifyingKey) {
        self.pubkey = Some(pubkey);
    }

    /// Use the specified public key for the `pubkey` header.
    #[inline]
    pub fn with_pubkey(mut self, pubkey: &'a ed25519_dalek::VerifyingKey) -> Self {
        self.set_pubkey(pubkey);
        self
    }

    /// Use the specified address for ABIv2.3 signature.
    #[inline]
    pub fn set_address(&mut self, address: &'a StdAddr) {
        self.address = Some(address);
    }

    /// Use the specified address for ABIv2.3 signature.
    #[inline]
    pub fn with_address(mut self, address: &'a StdAddr) -> Self {
        self.set_address(address);
        self
    }
}

/// Method ABI declaration builder.
#[derive(Debug, Clone)]
pub struct FunctionBuilder {
    abi_version: AbiVersion,
    name: String,
    headers: Vec<AbiHeaderType>,
    inputs: Vec<NamedAbiType>,
    outputs: Vec<NamedAbiType>,
    id: Option<u32>,
}

impl FunctionBuilder {
    /// Creates an empty ABI declaration for a method with the specified ABI version and name.
    pub fn new<T: Into<String>>(abi_version: AbiVersion, name: T) -> Self {
        Self {
            abi_version,
            name: name.into(),
            headers: Default::default(),
            inputs: Default::default(),
            outputs: Default::default(),
            id: None,
        }
    }

    /// Finalizes an ABI declaration.
    pub fn build(self) -> Function {
        let (input_id, output_id) = match self.id {
            Some(id) => (id, id),
            None => {
                let id = Function::compute_function_id(
                    self.abi_version,
                    &self.name,
                    &self.headers,
                    &self.inputs,
                    &self.outputs,
                );
                (id & Function::INPUT_ID_MASK, id | !Function::INPUT_ID_MASK)
            }
        };

        Function {
            abi_version: self.abi_version,
            headers: Arc::from(self.headers),
            name: Arc::from(self.name),
            inputs: Arc::from(self.inputs),
            outputs: Arc::from(self.outputs),
            input_id,
            output_id,
        }
    }

    /// Sets method headers to the specified list.
    pub fn with_headers<I: IntoIterator<Item = AbiHeaderType>>(mut self, headers: I) -> Self {
        self.headers = headers.into_iter().collect();
        self
    }

    /// Sets method input types to the specified list of named arguments.
    pub fn with_inputs<I, T>(mut self, inputs: I) -> Self
    where
        I: IntoIterator<Item = T>,
        T: Into<NamedAbiType>,
    {
        self.inputs = inputs.into_iter().map(Into::into).collect();
        self
    }

    /// Sets method input types to the specified list of unnamed arguments.
    pub fn with_unnamed_inputs<I: IntoIterator<Item = AbiType>>(mut self, inputs: I) -> Self {
        self.inputs = inputs
            .into_iter()
            .enumerate()
            .map(NamedAbiType::from)
            .collect();
        self
    }

    /// Sets method output types to the specified list of named arguments.
    pub fn with_outputs<I, T>(mut self, outputs: I) -> Self
    where
        I: IntoIterator<Item = NamedAbiType>,
        T: Into<NamedAbiType>,
    {
        self.outputs = outputs.into_iter().collect();
        self
    }

    /// Sets method output types to the specified list of unnamed arguments.
    pub fn with_unnamed_outputs<I: IntoIterator<Item = AbiType>>(mut self, outputs: I) -> Self {
        self.outputs = outputs
            .into_iter()
            .enumerate()
            .map(NamedAbiType::from)
            .collect();
        self
    }

    /// Sets an explicit function id.
    pub fn with_id(mut self, id: u32) -> Self {
        self.id = Some(id);
        self
    }
}

/// Contract event ABI definition.
#[derive(Debug, Clone)]
pub struct Event {
    /// ABI version (same as contract ABI version).
    pub abi_version: AbiVersion,
    /// Event name.
    pub name: Arc<str>,
    /// Event arguments.
    pub inputs: Arc<[NamedAbiType]>,
    /// Event id derived from signature.
    pub id: u32,
}

impl Event {
    /// Computes event id from the full event signature.
    pub fn compute_event_id(abi_version: AbiVersion, name: &str, inputs: &[NamedAbiType]) -> u32 {
        let mut hasher = sha2::Sha256::new();
        EventSignatureRaw {
            abi_version,
            name,
            inputs,
        }
        .update_hasher(&mut hasher);

        let hash: [u8; 32] = hasher.finalize().into();
        u32::from_be_bytes(hash[0..4].try_into().unwrap())
    }

    /// Returns an event builder with the specified ABI version and name.
    #[inline]
    pub fn builder<T: Into<String>>(abi_version: AbiVersion, name: T) -> EventBuilder {
        EventBuilder::new(abi_version, name)
    }

    /// Encodes a message body with this event as an internal message.
    pub fn encode_internal_input(&self, tokens: &[NamedAbiValue]) -> Result<CellBuilder> {
        ok!(NamedAbiValue::check_types(tokens, &self.inputs));
        Function::encode_internal_msg_body(self.abi_version, self.id, tokens)
    }

    /// Tries to parse input arguments for this event from an internal message body.
    ///
    /// NOTE: The slice is required to contain nothing other than these arguments.
    pub fn decode_internal_input(&self, mut slice: CellSlice<'_>) -> Result<Vec<NamedAbiValue>> {
        self.decode_internal_input_ext(&mut slice, false)
    }

    /// Tries to parse input arguments for this event from an internal message body.
    pub fn decode_internal_input_ext(
        &self,
        slice: &mut CellSlice<'_>,
        allow_partial: bool,
    ) -> Result<Vec<NamedAbiValue>> {
        let id = slice.load_u32()?;
        anyhow::ensure!(
            id == self.id,
            AbiError::InputIdMismatch {
                expected: self.id,
                id
            }
        );
        let res = ok!(NamedAbiValue::load_tuple_ext(
            &self.inputs,
            self.abi_version,
            true,
            allow_partial,
            slice
        ));
        ok!(AbiValue::check_remaining(slice, allow_partial));
        Ok(res)
    }

    /// Returns an object which can be used to display the normalized signature of this event.
    pub fn display_signature(&self) -> impl std::fmt::Display + '_ {
        EventSignatureRaw {
            abi_version: self.abi_version,
            name: &self.name,
            inputs: &self.inputs,
        }
    }
}

/// Event ABI declaration builder.
#[derive(Debug, Clone)]
pub struct EventBuilder {
    abi_version: AbiVersion,
    name: String,
    inputs: Vec<NamedAbiType>,
    id: Option<u32>,
}

impl EventBuilder {
    /// Creates an empty ABI declaration for an event with the specified ABI version and name.
    pub fn new<T: Into<String>>(abi_version: AbiVersion, name: T) -> Self {
        Self {
            abi_version,
            name: name.into(),
            inputs: Default::default(),
            id: None,
        }
    }

    /// Finalizes an ABI declaration.
    pub fn build(self) -> Event {
        let id = match self.id {
            Some(id) => id,
            None => {
                let id = Event::compute_event_id(self.abi_version, &self.name, &self.inputs);
                id & Function::INPUT_ID_MASK
            }
        };

        Event {
            abi_version: self.abi_version,
            name: Arc::from(self.name),
            inputs: Arc::from(self.inputs),
            id,
        }
    }

    /// Sets event input types to the specified list of named arguments.
    pub fn with_inputs<I, T>(mut self, inputs: I) -> Self
    where
        I: IntoIterator<Item = T>,
        T: Into<NamedAbiType>,
    {
        self.inputs = inputs.into_iter().map(Into::into).collect();
        self
    }

    /// Sets event input types to the specified list of unnamed arguments.
    pub fn with_unnamed_inputs<I: IntoIterator<Item = AbiType>>(mut self, inputs: I) -> Self {
        self.inputs = inputs
            .into_iter()
            .enumerate()
            .map(NamedAbiType::from)
            .collect();
        self
    }

    /// Sets an explicit event id.
    pub fn with_id(mut self, id: u32) -> Self {
        self.id = Some(id);
        self
    }
}

/// Unsigned external message.
pub struct UnsignedExternalMessage {
    /// Destination contract address.
    pub dst: StdAddr,
    /// Unsigned payload.
    pub body: UnsignedBody,
    /// Optional initial contract state.
    pub init: Option<StateInit>,
}

impl UnsignedExternalMessage {
    /// Updates the state init of the external message to the specified one.
    pub fn set_state_init(&mut self, init: Option<StateInit>) {
        self.init = init;
    }

    /// Returns an external message with the specified state init.
    pub fn with_state_init(mut self, init: StateInit) -> Self {
        self.set_state_init(Some(init));
        self
    }

    /// Returns the expiration timestamp of this message.
    #[inline]
    pub fn expire_at(&self) -> u32 {
        self.body.expire_at
    }

    /// Signs the payload and returns an external message with filled signature.
    pub fn sign(
        self,
        key: &ed25519_dalek::SigningKey,
        signature_id: Option<i32>,
    ) -> Result<OwnedMessage> {
        let signature =
            crate::abi::sign_with_signature_id(key, self.body.hash.as_slice(), signature_id);
        self.with_signature(&signature)
    }

    /// Returns an external message with filled signature.
    pub fn with_signature(self, signature: &ed25519_dalek::Signature) -> Result<OwnedMessage> {
        self.into_signed(Some(&signature.to_bytes()))
    }

    /// Returns an external message with signature filled with zero bytes.
    pub fn with_fake_signature(self) -> Result<OwnedMessage> {
        self.into_signed(Some(&[0u8; 64]))
    }

    /// Returns an external message with empty signature.
    pub fn without_signature(self) -> Result<OwnedMessage> {
        self.into_signed(None)
    }

    /// Returns an external message with filled signature.
    pub fn fill_signature(&self, signature: Option<&[u8; 64]>) -> Result<OwnedMessage> {
        let body = self.body.fill_signature(signature)?;
        let range = CellSliceRange::full(body.as_ref());
        Ok(OwnedMessage {
            info: MsgInfo::ExtIn(ExtInMsgInfo {
                dst: IntAddr::Std(self.dst.clone()),
                ..Default::default()
            }),
            body: (body, range),
            init: self.init.clone(),
            layout: None,
        })
    }

    /// Converts an unsigned message into an external message with filled signature.
    fn into_signed(self, signature: Option<&[u8; 64]>) -> Result<OwnedMessage> {
        let body = self.body.fill_signature(signature)?;
        let range = CellSliceRange::full(body.as_ref());
        Ok(OwnedMessage {
            info: MsgInfo::ExtIn(ExtInMsgInfo {
                dst: IntAddr::Std(self.dst),
                ..Default::default()
            }),
            body: (body, range),
            init: self.init,
            layout: None,
        })
    }
}

/// Unsigned external message payload.
pub struct UnsignedBody {
    /// ABI version used during encoding.
    pub abi_version: AbiVersion,
    /// Unsigned payload.
    pub payload: Cell,
    /// A hash to sign.
    pub hash: HashBytes,
    /// Message expiration timestamp (in seconds).
    pub expire_at: u32,
}

impl UnsignedBody {
    /// Extends message with the specified destination address and returns an
    /// unsigned external message.
    pub fn with_dst(self, dst: StdAddr) -> UnsignedExternalMessage {
        UnsignedExternalMessage {
            dst,
            body: self,
            init: None,
        }
    }

    /// Signs the payload and returns a body cell with filled signature.
    pub fn sign(self, key: &ed25519_dalek::SigningKey, signature_id: Option<i32>) -> Result<Cell> {
        let signature = crate::abi::sign_with_signature_id(key, self.hash.as_slice(), signature_id);
        self.with_signature(&signature)
    }

    /// Returns a body cell with filled signature.
    pub fn with_signature(self, signature: &ed25519_dalek::Signature) -> Result<Cell> {
        self.fill_signature(Some(&signature.to_bytes()))
    }

    /// Returns a body cell with signature filled with zero bytes.
    pub fn with_fake_signature(self) -> Result<Cell> {
        self.fill_signature(Some(&[0u8; 64]))
    }

    /// Returns a body cell with empty signature.
    pub fn without_signature(self) -> Result<Cell> {
        self.fill_signature(None)
    }

    /// Returns a body cell with filled signature.
    pub fn fill_signature(&self, signature: Option<&[u8; 64]>) -> Result<Cell> {
        let mut builder = CellBuilder::new();

        if self.abi_version.major == 1 {
            builder.store_reference(match signature {
                Some(signature) => {
                    // TODO: extend with public key?
                    CellBuilder::from_raw_data(signature, 512).and_then(CellBuilder::build)?
                }
                None => Cell::empty_cell(),
            })?;
        } else {
            match signature {
                Some(signature) => {
                    builder.store_bit_one()?;
                    builder.store_raw(signature, 512)?;
                }
                None => builder.store_bit_zero()?,
            }
            builder.store_slice(self.payload.as_slice()?)?;
        }

        builder.build().map_err(From::from)
    }
}

struct FunctionSignatureRaw<'a> {
    abi_version: AbiVersion,
    name: &'a str,
    headers: &'a [AbiHeaderType],
    inputs: &'a [NamedAbiType],
    outputs: &'a [NamedAbiType],
}

impl FunctionSignatureRaw<'_> {
    fn update_hasher<H: Digest>(&self, engine: &mut H) {
        std::fmt::write(&mut DisplayHasher(engine), format_args!("{self}")).unwrap();
    }
}

impl std::fmt::Display for FunctionSignatureRaw<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        ok!(write!(f, "{}(", self.name));

        let mut first = true;
        if self.abi_version.major == 1 {
            for header in self.headers {
                if !std::mem::take(&mut first) {
                    ok!(f.write_str(","));
                }
                ok!(std::fmt::Display::fmt(header, f));
            }
        }
        for item in self.inputs {
            if !std::mem::take(&mut first) {
                ok!(f.write_str(","));
            }
            ok!(std::fmt::Display::fmt(&item.ty, f));
        }

        ok!(f.write_str(")("));

        first = true;
        for item in self.outputs {
            if !std::mem::take(&mut first) {
                ok!(f.write_str(","));
            }
            ok!(std::fmt::Display::fmt(&item.ty, f));
        }

        write!(f, ")v{}", self.abi_version.major)
    }
}

struct EventSignatureRaw<'a> {
    abi_version: AbiVersion,
    name: &'a str,
    inputs: &'a [NamedAbiType],
}

impl EventSignatureRaw<'_> {
    fn update_hasher<H: Digest>(&self, engine: &mut H) {
        std::fmt::write(&mut DisplayHasher(engine), format_args!("{self}")).unwrap();
    }
}

impl std::fmt::Display for EventSignatureRaw<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        ok!(write!(f, "{}(", self.name));

        let mut first = true;
        for item in self.inputs {
            if !std::mem::take(&mut first) {
                ok!(f.write_str(","));
            }
            ok!(std::fmt::Display::fmt(&item.ty, f));
        }
        write!(f, ")v{}", self.abi_version.major)
    }
}

#[repr(transparent)]
struct DisplayHasher<'a, H>(&'a mut H);

impl<H: Digest> std::fmt::Write for DisplayHasher<'_, H> {
    #[inline]
    fn write_str(&mut self, s: &str) -> std::fmt::Result {
        self.0.update(s.as_bytes());
        Ok(())
    }
}