hyli-model 0.14.0

Hyli datamodel
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
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
use std::{
    fmt::Display,
    ops::{Add, Deref, DerefMut, Sub},
};

use borsh::{BorshDeserialize, BorshSerialize};
use serde::{Deserialize, Serialize};

use crate::{utils::TimestampMs, LaneId};

#[derive(
    Serialize,
    Deserialize,
    Clone,
    BorshSerialize,
    BorshDeserialize,
    PartialEq,
    Eq,
    Default,
    Ord,
    PartialOrd,
)]
#[cfg_attr(feature = "full", derive(utoipa::ToSchema))]
pub struct ConsensusProposalHash(#[serde(with = "crate::utils::hex_bytes")] pub Vec<u8>);
pub type BlockHash = ConsensusProposalHash;

impl std::hash::Hash for ConsensusProposalHash {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        state.write(&self.0);
    }
}

impl std::fmt::Debug for ConsensusProposalHash {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "ConsensusProposalHash({})", hex::encode(&self.0))
    }
}

pub trait Hashed<T> {
    fn hashed(&self) -> T;
}

pub trait DataSized {
    fn estimate_size(&self) -> usize;
}

/// Blob of the transactions the contract uses to validate its transition
#[derive(
    Default,
    Serialize,
    Deserialize,
    Debug,
    Clone,
    PartialEq,
    Eq,
    Hash,
    BorshSerialize,
    BorshDeserialize,
)]
#[cfg_attr(feature = "full", derive(utoipa::ToSchema))]
pub struct IndexedBlobs(pub Vec<(BlobIndex, Blob)>);

impl Deref for IndexedBlobs {
    type Target = Vec<(BlobIndex, Blob)>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for IndexedBlobs {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl IndexedBlobs {
    pub fn get(&self, index: &BlobIndex) -> Option<&Blob> {
        self.0.iter().find(|(i, _)| i == index).map(|(_, b)| b)
    }
}

impl<T> From<T> for IndexedBlobs
where
    T: IntoIterator<Item = Blob>,
{
    fn from(vec: T) -> Self {
        let mut blobs = IndexedBlobs::default();
        for (i, blob) in vec.into_iter().enumerate() {
            blobs.push((BlobIndex(i), blob));
        }
        blobs
    }
}

impl<'a> IntoIterator for &'a IndexedBlobs {
    type Item = &'a (BlobIndex, Blob);
    type IntoIter = std::slice::Iter<'a, (BlobIndex, Blob)>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

/// This struct is passed from the application backend to the contract as an input.
/// It contains the data that the contract will use to run the blob's action on its state.
#[derive(Default, Serialize, Deserialize, BorshSerialize, BorshDeserialize, Debug, Clone)]
pub struct Calldata {
    /// TxHash of the BlobTransaction being proved
    pub tx_hash: TxHash,
    /// User's identity used for the BlobTransaction
    pub identity: Identity,
    /// Subset of [Blob]s of the BlobTransaction
    pub blobs: IndexedBlobs,
    /// Number of ALL blobs in the transaction. tx_blob_count >= blobs.len()
    pub tx_blob_count: usize,
    /// Index of the blob corresponding to the contract.
    /// The [Blob] referenced by this index has to be parsed by the contract
    pub index: BlobIndex,
    /// Optional additional context of the BlobTransaction
    pub tx_ctx: Option<TxContext>,
    /// Additional input for the contract that is not written on-chain in the BlobTransaction
    pub private_input: Vec<u8>,
}

/// State commitment of the contract.
#[derive(
    Default, Serialize, Deserialize, Clone, PartialEq, Eq, Hash, BorshSerialize, BorshDeserialize,
)]
#[cfg_attr(feature = "full", derive(utoipa::ToSchema))]
pub struct StateCommitment(pub Vec<u8>);

impl std::fmt::Debug for StateCommitment {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "StateCommitment({})", hex::encode(&self.0))
    }
}

#[derive(
    Default,
    Serialize,
    Deserialize,
    Debug,
    Clone,
    PartialEq,
    Eq,
    Hash,
    BorshSerialize,
    BorshDeserialize,
    Ord,
    PartialOrd,
)]
#[cfg_attr(feature = "full", derive(utoipa::ToSchema))]
/// An identity is a string that identifies the person that sent
/// the BlobTransaction
pub struct Identity(pub String);

#[derive(
    Default,
    Serialize,
    Deserialize,
    Clone,
    PartialEq,
    Eq,
    Hash,
    BorshSerialize,
    BorshDeserialize,
    Ord,
    PartialOrd,
)]
#[cfg_attr(feature = "full", derive(utoipa::ToSchema))]
pub struct TxHash(#[serde(with = "crate::utils::hex_bytes")] pub Vec<u8>);

#[derive(
    Default,
    Serialize,
    Deserialize,
    Debug,
    Clone,
    PartialEq,
    Eq,
    Hash,
    BorshDeserialize,
    BorshSerialize,
    Copy,
    PartialOrd,
    Ord,
)]
#[cfg_attr(feature = "full", derive(utoipa::ToSchema))]
pub struct BlobIndex(pub usize);

impl Add<usize> for BlobIndex {
    type Output = BlobIndex;
    fn add(self, other: usize) -> BlobIndex {
        BlobIndex(self.0 + other)
    }
}

#[derive(
    Default, Serialize, Deserialize, Clone, PartialEq, Eq, Hash, BorshSerialize, BorshDeserialize,
)]
#[cfg_attr(feature = "full", derive(utoipa::ToSchema))]
pub struct BlobData(pub Vec<u8>);

impl std::fmt::Debug for BlobData {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        if self.0.len() > 20 {
            write!(f, "BlobData({}...)", hex::encode(&self.0[..20]))
        } else {
            write!(f, "BlobData({})", hex::encode(&self.0))
        }
    }
}

/**
This struct allows to define cross-contract calls (aka contract composition).
A contract `A` can "call" an other contract `B` by being it's "caller":

Blob for contract `A` has to be a `StructuredBlobData` with callees vec including the blob index of
contract `B`.

Blob for contract `B` has to be a `StructuredBlobData` with caller = the blob index of contract
`A`.

## When to use cross-contract calls ?

When a contract needs to do an operation on an other one. Like transfering funds from
contract's wallet to the user doing the transaction.

### Example: Bob Swap 2 USDC to 2 USDT

A swap contract can use transactions with 4 blobs:

```text
┌─ Blob 0
│  Identity verification for user Bob
└─────
┌─ Blob 1 - Contract = "amm"
│  Swap action
│  callees = vec![2]
└─────
┌─ Blob 2 - Contract = "usdt"
│  Transfer action of 2 USDT to "Bob"
│  caller = 1
└─────
┌─ Blob 3 - Contract = "usdc"
│  Transfer action of 2 USDC to "amm"
└─────
```

Blob 2 will do various checks on the swap to ensure its validity (correct transfer amounts...)

As Blob 2 has a "caller", the identity used by the contract will be "amm", thus the
transfer of USDT will be done FROM "amm" TO Bob

And as Blob 3 has no "caller", the identity used by the contract will be the same as the
transaction identity, i.e: Bob.


An alternative way that is more evm-like with an token approve would look like:
```text
┌─ Blob 0
│  Identity verification for user Bob
└─────
┌─ Blob 1 - Contract = "usdc"
│  Approve action of 2 USDC for "amm"
└─────
┌─ Blob 2 - Contract = "amm"
│  Swap action
│  callees = vec![3, 4]
└─────
┌─ Blob 3 - Contract = "usdt"
│  Transfer action of 2 USDT to "Bob"
│  caller = 2
└─────
┌─ Blob 4 - Contract = "usdc"
│  TransferFrom action from "Bob" of 2 USDC to "amm"
│  caller = 2
└─────
```

As Blob 4 now has a "caller", the identity used by the contract will be "amm" and not "Bob".
Note that here we are using a TransferFrom in blob 4, contract "amm" got the approval from Bob
to initate a transfer on its behalf with blob 1.

You can find an example of this implementation in our [amm contract](https://github.com/hyli-org/hyli/tree/main/crates/contracts/amm/src/lib.rs)
*/
#[derive(Debug, BorshSerialize)]
pub struct StructuredBlobData<Action> {
    pub caller: Option<BlobIndex>,
    pub callees: Option<Vec<BlobIndex>>,
    pub parameters: Action,
}

/// Struct used to be able to deserialize a StructuredBlobData
/// without knowing the concrete type of `Action`
/// warning: this will drop the end of the reader, thus, you can't
/// deserialize a structure that contains a `StructuredBlobData<DropEndOfReader>`
/// Unless this struct is at the end of your data structure.
/// It's not meant to be used outside the sdk internal logic.
pub struct DropEndOfReader;

impl<Action: BorshDeserialize> BorshDeserialize for StructuredBlobData<Action> {
    fn deserialize_reader<R: std::io::Read>(reader: &mut R) -> std::io::Result<Self> {
        let caller = Option::<BlobIndex>::deserialize_reader(reader)?;
        let callees = Option::<Vec<BlobIndex>>::deserialize_reader(reader)?;
        let parameters = Action::deserialize_reader(reader)?;
        Ok(StructuredBlobData {
            caller,
            callees,
            parameters,
        })
    }
}

impl BorshDeserialize for StructuredBlobData<DropEndOfReader> {
    fn deserialize_reader<R: std::io::Read>(reader: &mut R) -> std::io::Result<Self> {
        let caller = Option::<BlobIndex>::deserialize_reader(reader)?;
        let callees = Option::<Vec<BlobIndex>>::deserialize_reader(reader)?;
        reader.read_to_end(&mut vec![])?;
        let parameters = DropEndOfReader;
        Ok(StructuredBlobData {
            caller,
            callees,
            parameters,
        })
    }
}

impl<Action: BorshSerialize> From<StructuredBlobData<Action>> for BlobData {
    fn from(val: StructuredBlobData<Action>) -> Self {
        BlobData(borsh::to_vec(&val).expect("failed to encode BlobData"))
    }
}
impl<Action: BorshDeserialize> TryFrom<BlobData> for StructuredBlobData<Action> {
    type Error = std::io::Error;

    fn try_from(val: BlobData) -> Result<StructuredBlobData<Action>, Self::Error> {
        borsh::from_slice(&val.0)
    }
}
impl TryFrom<BlobData> for StructuredBlobData<DropEndOfReader> {
    type Error = std::io::Error;

    fn try_from(val: BlobData) -> Result<StructuredBlobData<DropEndOfReader>, Self::Error> {
        borsh::from_slice(&val.0)
    }
}

#[derive(
    Debug,
    Serialize,
    Deserialize,
    Default,
    Clone,
    PartialEq,
    Eq,
    BorshSerialize,
    BorshDeserialize,
    Hash,
)]
#[cfg_attr(feature = "full", derive(utoipa::ToSchema))]
/// A Blob is a binary-serialized action that the contract has to parse
/// An action is often written as an enum representing the call of a specific
/// contract function.
pub struct Blob {
    pub contract_name: ContractName,
    pub data: BlobData,
}

#[derive(
    Default, Clone, Serialize, Deserialize, Eq, PartialEq, Hash, BorshSerialize, BorshDeserialize,
)]
#[cfg_attr(feature = "full", derive(utoipa::ToSchema))]
pub struct BlobHash(#[serde(with = "crate::utils::hex_bytes")] pub Vec<u8>);

#[cfg(feature = "full")]
impl Hashed<BlobHash> for Blob {
    fn hashed(&self) -> BlobHash {
        use sha3::{Digest, Sha3_256};

        let mut hasher = Sha3_256::new();
        hasher.update(self.contract_name.0.clone());
        hasher.update(self.data.0.clone());
        let hash_bytes = hasher.finalize();
        BlobHash(hash_bytes.to_vec())
    }
}

impl std::fmt::Debug for BlobHash {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "BlobHash({})", hex::encode(&self.0))
    }
}

impl std::fmt::Display for BlobHash {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", hex::encode(&self.0))
    }
}

#[derive(Debug, BorshSerialize, BorshDeserialize)]
pub struct StructuredBlob<Action> {
    pub contract_name: ContractName,
    pub data: StructuredBlobData<Action>,
}

impl<Action: BorshSerialize> From<StructuredBlob<Action>> for Blob {
    fn from(val: StructuredBlob<Action>) -> Self {
        Blob {
            contract_name: val.contract_name,
            data: BlobData::from(val.data),
        }
    }
}

impl<Action: BorshDeserialize> TryFrom<Blob> for StructuredBlob<Action> {
    type Error = std::io::Error;

    fn try_from(val: Blob) -> Result<StructuredBlob<Action>, Self::Error> {
        let data = borsh::from_slice(&val.data.0)?;
        Ok(StructuredBlob {
            contract_name: val.contract_name,
            data,
        })
    }
}

pub trait ContractAction: Send {
    fn as_blob(
        &self,
        contract_name: ContractName,
        caller: Option<BlobIndex>,
        callees: Option<Vec<BlobIndex>>,
    ) -> Blob;
}

#[derive(
    Default,
    Debug,
    Clone,
    Serialize,
    Deserialize,
    Eq,
    PartialEq,
    Hash,
    BorshSerialize,
    BorshDeserialize,
    Ord,
    PartialOrd,
)]
#[cfg_attr(feature = "full", derive(utoipa::ToSchema))]
pub struct ContractName(pub String);

#[derive(
    Default,
    Debug,
    Clone,
    Serialize,
    Deserialize,
    Eq,
    PartialEq,
    Hash,
    BorshSerialize,
    BorshDeserialize,
)]
#[cfg_attr(feature = "full", derive(utoipa::ToSchema))]
pub struct Verifier(pub String);

#[derive(
    Default,
    Debug,
    Clone,
    Serialize,
    Deserialize,
    Eq,
    PartialEq,
    Hash,
    BorshSerialize,
    BorshDeserialize,
)]
#[cfg_attr(feature = "full", derive(utoipa::ToSchema))]
pub struct ProgramId(pub Vec<u8>);

impl std::fmt::Display for ProgramId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", hex::encode(&self.0))
    }
}

#[derive(Debug, Default, PartialEq, Eq, Clone, BorshSerialize, BorshDeserialize)]
#[cfg_attr(feature = "full", derive(Serialize, utoipa::ToSchema))]
pub struct ProofData(#[cfg_attr(feature = "full", serde(with = "base64_field"))] pub Vec<u8>);

#[derive(Debug, Default, PartialEq, Eq, Clone, BorshSerialize, BorshDeserialize)]
#[cfg_attr(feature = "full", derive(Serialize, utoipa::ToSchema))]
pub struct ProofMetadata {
    pub cycles: Option<u64>,
    pub prover: Option<String>,
    /// SessionId, TxHash, ... of the proof request on a prover network
    pub id: Option<String>,
}

#[derive(Debug, Default, PartialEq, Eq, Clone, BorshSerialize, BorshDeserialize)]
#[cfg_attr(feature = "full", derive(Serialize, utoipa::ToSchema))]
pub struct Proof {
    pub data: ProofData,
    pub metadata: ProofMetadata,
}

#[cfg(feature = "full")]
impl<'de> Deserialize<'de> for ProofData {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct ProofDataVisitor;

        impl<'de> serde::de::Visitor<'de> for ProofDataVisitor {
            type Value = ProofData;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("a Base64 string or a Vec<u8>")
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                use base64::prelude::*;
                let decoded = BASE64_STANDARD
                    .decode(value)
                    .map_err(serde::de::Error::custom)?;
                Ok(ProofData(decoded))
            }

            fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
            where
                A: serde::de::SeqAccess<'de>,
            {
                let vec_u8: Vec<u8> = serde::de::Deserialize::deserialize(
                    serde::de::value::SeqAccessDeserializer::new(seq),
                )?;
                Ok(ProofData(vec_u8))
            }
        }

        deserializer.deserialize_any(ProofDataVisitor)
    }
}

#[derive(
    Default, Serialize, Deserialize, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize,
)]
pub struct ProofDataHash(#[serde(with = "crate::utils::hex_bytes")] pub Vec<u8>);

impl From<Vec<u8>> for ProofDataHash {
    fn from(v: Vec<u8>) -> Self {
        ProofDataHash(v)
    }
}
impl From<&[u8]> for ProofDataHash {
    fn from(v: &[u8]) -> Self {
        ProofDataHash(v.to_vec())
    }
}
impl<const N: usize> From<&[u8; N]> for ProofDataHash {
    fn from(v: &[u8; N]) -> Self {
        ProofDataHash(v.to_vec())
    }
}
impl ProofDataHash {
    pub fn from_hex(s: &str) -> Result<Self, hex::FromHexError> {
        crate::utils::decode_hex_string_checked(s).map(ProofDataHash)
    }
}

impl std::fmt::Debug for ProofDataHash {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "ProofDataHash({})", hex::encode(&self.0))
    }
}

impl Display for ProofDataHash {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", hex::encode(&self.0))
    }
}

#[cfg(feature = "full")]
impl Hashed<ProofDataHash> for ProofData {
    fn hashed(&self) -> ProofDataHash {
        use sha3::Digest;
        let mut hasher = sha3::Sha3_256::new();
        hasher.update(self.0.as_slice());
        let hash_bytes = hasher.finalize();
        ProofDataHash(hash_bytes.to_vec())
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
#[cfg_attr(feature = "full", derive(utoipa::ToSchema))]
/// Enum for various side-effects blobs can have on the chain.
/// This is implemented as an enum for easier forward compatibility.
pub enum OnchainEffect {
    /// RegisterContractWithConstructor means that we expect the next blob from the contract to be a placeholder containing the constructor_metadata
    RegisterContractWithConstructor(RegisterContractEffect),
    /// RegisterContract means that we expect the contract's next blob to be a real blob that will get proven
    RegisterContract(RegisterContractEffect),
    DeleteContract(ContractName),
    UpdateContractProgramId(ContractName, ProgramId),
    UpdateTimeoutWindow(ContractName, TimeoutWindow),
}

pub struct OnchainEffectHash(pub Vec<u8>);

#[cfg(feature = "full")]
impl Hashed<OnchainEffectHash> for OnchainEffect {
    fn hashed(&self) -> OnchainEffectHash {
        use sha3::{Digest, Sha3_256};
        let mut hasher = Sha3_256::new();
        match self {
            OnchainEffect::RegisterContractWithConstructor(c) => hasher.update(&c.hashed().0),
            OnchainEffect::RegisterContract(c) => hasher.update(&c.hashed().0),
            OnchainEffect::DeleteContract(cn) => hasher.update(cn.0.as_bytes()),
            OnchainEffect::UpdateContractProgramId(cn, pid) => {
                hasher.update(cn.0.as_bytes());
                hasher.update(pid.0.clone());
            }
            OnchainEffect::UpdateTimeoutWindow(cn, timeout_window) => {
                hasher.update(cn.0.as_bytes());
                match timeout_window {
                    TimeoutWindow::NoTimeout => hasher.update(0u8.to_le_bytes()),
                    TimeoutWindow::Timeout {
                        hard_timeout,
                        soft_timeout,
                    } => {
                        hasher.update(hard_timeout.0.to_le_bytes());
                        hasher.update(soft_timeout.0.to_le_bytes());
                    }
                }
            }
        };
        OnchainEffectHash(hasher.finalize().to_vec())
    }
}

/// This struct has to be the zkvm committed output. It will be used by
/// hyli node to verify & settle the blob transaction.
#[derive(
    Default, Serialize, Deserialize, Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize,
)]
#[cfg_attr(feature = "full", derive(utoipa::ToSchema))]
pub struct HyliOutput {
    /// The version of the HyliOutput. This is unchecked for now.
    pub version: u32,
    /// The initial state of the contract. This is the state before the transaction is executed.
    pub initial_state: StateCommitment,
    /// The state of the contract after the transaction is executed.
    pub next_state: StateCommitment,
    /// The identity used to execute the transaction.
    /// This must match the one used in the BlobTransaction.
    pub identity: Identity,

    /// The index of the blob being proven.
    pub index: BlobIndex,
    /// The blobs that were used by the contract. It has to be a subset of the transactions blobs
    /// It can be the complete list of blobs if the contract used all of them.
    pub blobs: IndexedBlobs,
    /// Number of blobs in the transaction. tx_blob_count >= blobs.len()
    pub tx_blob_count: usize,

    /// TxHash of the BlobTransaction.
    pub tx_hash: TxHash, // Technically redundant with identity + blobs hash

    /// Whether the execution was successful or not. If false, the BlobTransaction will be
    /// settled as failed.
    pub success: bool,

    /// List of other contracts used by the proof. Each state commitment will be checked
    /// against the contract's state when settling.
    pub state_reads: Vec<(ContractName, StateCommitment)>,

    /// Optional - if empty, these won't be checked, but also can't be used inside the program.
    pub tx_ctx: Option<TxContext>,

    pub onchain_effects: Vec<OnchainEffect>,

    /// Arbitrary data that could be used by indexers or other tools. Some contracts write a utf-8
    /// string here, but it can be anything.
    /// Note: As this data is generated by the contract in the zkvm, this can be trusted.
    pub program_outputs: Vec<u8>,
}

#[derive(
    Default,
    Serialize,
    Deserialize,
    Debug,
    Clone,
    PartialEq,
    Eq,
    Hash,
    BorshSerialize,
    BorshDeserialize,
)]
#[cfg_attr(feature = "full", derive(utoipa::ToSchema))]
pub struct TxContext {
    pub lane_id: LaneId,
    pub block_hash: BlockHash,
    pub block_height: BlockHeight,
    pub timestamp: TimestampMs,
    #[serde(
        serialize_with = "serialize_chain_id",
        deserialize_with = "deserialize_chain_id"
    )]
    pub chain_id: u128,
}

fn serialize_chain_id<S>(chain_id: &u128, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serializer.serialize_str(&chain_id.to_string())
}

fn deserialize_chain_id<'de, D>(deserializer: D) -> Result<u128, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let s: String = serde::Deserialize::deserialize(deserializer)?;
    s.parse::<u128>().map_err(serde::de::Error::custom)
}

impl Identity {
    pub fn new<S: Into<Self>>(s: S) -> Self {
        s.into()
    }
}
impl<S: Into<String>> From<S> for Identity {
    fn from(s: S) -> Self {
        Identity(s.into())
    }
}

impl ConsensusProposalHash {
    pub fn new<S: Into<Self>>(s: S) -> Self {
        s.into()
    }
}
impl From<Vec<u8>> for ConsensusProposalHash {
    fn from(v: Vec<u8>) -> Self {
        ConsensusProposalHash(v)
    }
}
impl From<&[u8]> for ConsensusProposalHash {
    fn from(v: &[u8]) -> Self {
        ConsensusProposalHash(v.to_vec())
    }
}
impl<const N: usize> From<&[u8; N]> for ConsensusProposalHash {
    fn from(v: &[u8; N]) -> Self {
        ConsensusProposalHash(v.to_vec())
    }
}
impl ConsensusProposalHash {
    pub fn from_hex(s: &str) -> Result<Self, hex::FromHexError> {
        crate::utils::decode_hex_string_checked(s).map(ConsensusProposalHash)
    }
}

impl TxHash {
    pub fn new<S: Into<Self>>(s: S) -> Self {
        s.into()
    }
}
impl From<Vec<u8>> for TxHash {
    fn from(v: Vec<u8>) -> Self {
        TxHash(v)
    }
}
impl From<&[u8]> for TxHash {
    fn from(v: &[u8]) -> Self {
        TxHash(v.to_vec())
    }
}
impl<const N: usize> From<&[u8; N]> for TxHash {
    fn from(v: &[u8; N]) -> Self {
        TxHash(v.to_vec())
    }
}
impl TxHash {
    pub fn from_hex(s: &str) -> Result<Self, hex::FromHexError> {
        crate::utils::decode_hex_string_checked(s).map(TxHash)
    }
}

impl ContractName {
    pub fn new<S: Into<Self>>(s: S) -> Self {
        s.into()
    }
}
impl<S: Into<String>> From<S> for ContractName {
    fn from(s: S) -> Self {
        ContractName(s.into())
    }
}

impl Verifier {
    pub fn new<S: Into<Self>>(s: S) -> Self {
        s.into()
    }
}
impl<S: Into<String>> From<S> for Verifier {
    fn from(s: S) -> Self {
        Verifier(s.into())
    }
}
impl From<Vec<u8>> for ProgramId {
    fn from(v: Vec<u8>) -> Self {
        ProgramId(v.clone())
    }
}
impl From<&Vec<u8>> for ProgramId {
    fn from(v: &Vec<u8>) -> Self {
        ProgramId(v.clone())
    }
}
impl<const N: usize> From<&[u8; N]> for ProgramId {
    fn from(v: &[u8; N]) -> Self {
        ProgramId(v.to_vec())
    }
}
impl From<&[u8]> for ProgramId {
    fn from(v: &[u8]) -> Self {
        ProgramId(v.to_vec().clone())
    }
}

impl Display for TxHash {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", hex::encode(&self.0))
    }
}
impl std::fmt::Debug for TxHash {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "TxHash({})", hex::encode(&self.0))
    }
}
impl Display for BlobIndex {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", &self.0)
    }
}
impl Display for ContractName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", &self.0)
    }
}
impl Display for Identity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", &self.0)
    }
}
impl Display for Verifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", &self.0)
    }
}
impl From<usize> for BlobIndex {
    fn from(i: usize) -> Self {
        BlobIndex(i)
    }
}

#[cfg_attr(feature = "full", derive(derive_more::derive::Display))]
#[derive(
    Default,
    Debug,
    Clone,
    Serialize,
    Deserialize,
    Eq,
    PartialEq,
    Hash,
    Copy,
    BorshSerialize,
    BorshDeserialize,
    PartialOrd,
    Ord,
)]
#[cfg_attr(feature = "full", derive(utoipa::ToSchema))]
pub struct BlockHeight(pub u64);

impl Add<BlockHeight> for u64 {
    type Output = BlockHeight;
    fn add(self, other: BlockHeight) -> BlockHeight {
        BlockHeight(self + other.0)
    }
}

impl Add<u64> for BlockHeight {
    type Output = BlockHeight;
    fn add(self, other: u64) -> BlockHeight {
        BlockHeight(self.0 + other)
    }
}

impl Sub<u64> for BlockHeight {
    type Output = BlockHeight;
    fn sub(self, other: u64) -> BlockHeight {
        BlockHeight(self.0 - other)
    }
}

impl Add<BlockHeight> for BlockHeight {
    type Output = BlockHeight;
    fn add(self, other: BlockHeight) -> BlockHeight {
        BlockHeight(self.0 + other.0)
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
#[cfg_attr(feature = "full", derive(utoipa::ToSchema))]
pub enum TimeoutWindow {
    NoTimeout,
    Timeout {
        // The hard_timeout is the timeout value used to set a transaction's timeout when the blobs for the contract are NOT proved.
        // It is expected that hard_timeout <= soft_timeout.
        hard_timeout: BlockHeight,
        // The soft_timeout is the timeout value used when the blobs for the contract ARE proved.
        // In other words, if blobs are proved, soft_timeout is used; if not proved, hard_timeout is used.
        soft_timeout: BlockHeight,
    },
}
impl Display for TimeoutWindow {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self {
            TimeoutWindow::NoTimeout => write!(f, "NoTimeout"),
            TimeoutWindow::Timeout {
                hard_timeout,
                soft_timeout,
            } => write!(f, "Timeout({},{})", hard_timeout.0, soft_timeout.0),
        }
    }
}

impl Default for TimeoutWindow {
    fn default() -> Self {
        TimeoutWindow::timeout(BlockHeight(100), BlockHeight(100))
    }
}

/// Creates a new timeout window with hard and soft timeout block heights.
///
/// This function automatically ensures that `hard_timeout <= soft_timeout` by
/// swapping the parameters if they are provided in the wrong order. If the
/// `hard_timeout` is greater than `soft_timeout`, the values will be swapped
/// internally to maintain the invariant that hard timeout should occur before
/// or at the same time as the soft timeout.
///
/// # Parameters
///
/// * `hard_timeout` - The block height for the hard timeout (will be the earlier timeout)
/// * `soft_timeout` - The block height for the soft timeout (will be the later timeout)
///
/// # Returns
///
/// A `TimeoutWindow::Timeout` variant with properly ordered timeout values.
impl TimeoutWindow {
    pub fn timeout(hard_timeout: BlockHeight, soft_timeout: BlockHeight) -> Self {
        let (hard_timeout, soft_timeout) = if hard_timeout <= soft_timeout {
            (hard_timeout, soft_timeout)
        } else {
            (soft_timeout, hard_timeout)
        };
        TimeoutWindow::Timeout {
            hard_timeout,
            soft_timeout,
        }
    }
}

#[derive(
    Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize,
)]
#[cfg_attr(feature = "full", derive(utoipa::ToSchema))]
/// Used as a blob action to register a contract.
pub struct RegisterContractAction {
    /// Verifier to use for transactions sent to this new contract.
    pub verifier: Verifier,
    /// Other verifier data, such as a Risc0 program ID or noir public key.
    /// Transactions sent to this contract will have to match this program ID.
    pub program_id: ProgramId,
    /// Initial state commitment of the contract to register.
    pub state_commitment: StateCommitment,
    /// Name of the contract to register.
    pub contract_name: ContractName,
    /// Optionally set the timeout window for the contract.
    /// If the contract exists, the timeout window will be unchanged, otherwise, the default value will be used.
    pub timeout_window: Option<TimeoutWindow>,
    /// Optional data for indexers to construct the initial state of the contract.
    /// Importantly, this is *never* checked by the node. You should verify manually it matches the state commitment.
    pub constructor_metadata: Option<Vec<u8>>,
}

#[cfg(feature = "full")]
impl Hashed<TxHash> for RegisterContractAction {
    fn hashed(&self) -> TxHash {
        use sha3::{Digest, Sha3_256};

        let mut hasher = Sha3_256::new();
        hasher.update(self.verifier.0.clone());
        hasher.update(self.program_id.0.clone());
        hasher.update(self.state_commitment.0.clone());
        hasher.update(self.contract_name.0.clone());
        if let Some(timeout_window) = &self.timeout_window {
            match timeout_window {
                TimeoutWindow::NoTimeout => hasher.update(0u8.to_le_bytes()),
                TimeoutWindow::Timeout {
                    hard_timeout,
                    soft_timeout,
                } => {
                    hasher.update(hard_timeout.0.to_le_bytes());
                    hasher.update(soft_timeout.0.to_le_bytes());
                }
            }
        }
        // We don't hash the constructor metadata.
        let hash_bytes = hasher.finalize();
        TxHash(hash_bytes.to_vec())
    }
}

impl RegisterContractAction {
    pub fn as_blob(&self, contract_name: ContractName) -> Blob {
        <Self as ContractAction>::as_blob(self, contract_name, None, None)
    }
}

impl ContractAction for RegisterContractAction {
    fn as_blob(
        &self,
        contract_name: ContractName,
        _caller: Option<BlobIndex>,
        _callees: Option<Vec<BlobIndex>>,
    ) -> Blob {
        Blob {
            contract_name,
            data: BlobData(borsh::to_vec(self).expect("failed to encode RegisterContractAction")),
        }
    }
}

#[derive(
    Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize,
)]
pub struct UpdateContractProgramIdAction {
    pub contract_name: ContractName,
    pub program_id: ProgramId,
}

impl UpdateContractProgramIdAction {
    pub fn as_blob(&self, contract_name: ContractName) -> Blob {
        <Self as ContractAction>::as_blob(self, contract_name, None, None)
    }
}

impl ContractAction for UpdateContractProgramIdAction {
    fn as_blob(
        &self,
        contract_name: ContractName,
        _caller: Option<BlobIndex>,
        _callees: Option<Vec<BlobIndex>>,
    ) -> Blob {
        Blob {
            contract_name,
            data: BlobData(
                borsh::to_vec(self).expect("failed to encode UpdateContractProgramIdAction"),
            ),
        }
    }
}

#[derive(
    Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize,
)]
pub struct UpdateContractTimeoutWindowAction {
    pub contract_name: ContractName,
    pub timeout_window: TimeoutWindow,
}

impl UpdateContractTimeoutWindowAction {
    pub fn as_blob(&self, contract_name: ContractName) -> Blob {
        <Self as ContractAction>::as_blob(self, contract_name, None, None)
    }
}

impl ContractAction for UpdateContractTimeoutWindowAction {
    fn as_blob(
        &self,
        contract_name: ContractName,
        _caller: Option<BlobIndex>,
        _callees: Option<Vec<BlobIndex>>,
    ) -> Blob {
        Blob {
            contract_name,
            data: BlobData(
                borsh::to_vec(self).expect("failed to encode UpdateContractTimeoutWindowAction"),
            ),
        }
    }
}

#[derive(
    Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize,
)]
/// Used as a blob action to delete a contract.
pub struct DeleteContractAction {
    pub contract_name: ContractName,
}

impl DeleteContractAction {
    pub fn as_blob(&self, contract_name: ContractName) -> Blob {
        <Self as ContractAction>::as_blob(self, contract_name, None, None)
    }
}

impl ContractAction for DeleteContractAction {
    fn as_blob(
        &self,
        contract_name: ContractName,
        _caller: Option<BlobIndex>,
        _callees: Option<Vec<BlobIndex>>,
    ) -> Blob {
        Blob {
            contract_name,
            data: BlobData(borsh::to_vec(self).expect("failed to encode DeleteContractAction")),
        }
    }
}

/// Used by the Hyli node to recognize contract registration.
/// Simply output this struct in your HyliOutput registered_contracts.
/// See uuid-tld for examples.
#[derive(
    Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize,
)]
#[cfg_attr(feature = "full", derive(utoipa::ToSchema))]
pub struct RegisterContractEffect {
    /// Verifier to use for transactions sent to this new contract.
    pub verifier: Verifier,
    /// Other verifier data, such as a Risc0 program ID or noir public key.
    /// Transactions sent to this contract will have to match this program ID.
    pub program_id: ProgramId,
    /// Initial state commitment of the contract to register.
    pub state_commitment: StateCommitment,
    /// Name of the contract to register.
    pub contract_name: ContractName,
    /// Optionally set the timeout window for the contract.
    /// If the contract exists, the timeout window will be unchanged, otherwise, the default value will be used.
    pub timeout_window: Option<TimeoutWindow>,
}

impl From<RegisterContractAction> for RegisterContractEffect {
    fn from(action: RegisterContractAction) -> Self {
        RegisterContractEffect {
            verifier: action.verifier,
            program_id: action.program_id,
            state_commitment: action.state_commitment,
            contract_name: action.contract_name,
            timeout_window: action.timeout_window,
        }
    }
}

#[cfg(feature = "full")]
impl Hashed<TxHash> for RegisterContractEffect {
    fn hashed(&self) -> TxHash {
        use sha3::{Digest, Sha3_256};

        let mut hasher = Sha3_256::new();
        hasher.update(self.verifier.0.clone());
        hasher.update(self.program_id.0.clone());
        hasher.update(self.state_commitment.0.clone());
        hasher.update(self.contract_name.0.clone());
        if let Some(timeout_window) = &self.timeout_window {
            match timeout_window {
                TimeoutWindow::NoTimeout => hasher.update(0u8.to_le_bytes()),
                TimeoutWindow::Timeout {
                    hard_timeout,
                    soft_timeout,
                } => {
                    hasher.update(hard_timeout.0.to_le_bytes());
                    hasher.update(soft_timeout.0.to_le_bytes());
                }
            }
        }
        let hash_bytes = hasher.finalize();
        TxHash(hash_bytes.to_vec())
    }
}

#[cfg(feature = "full")]
pub mod base64_field {
    use base64::prelude::*;
    use serde::{Deserialize, Deserializer, Serializer};

    pub fn serialize<S>(bytes: &Vec<u8>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let encoded = BASE64_STANDARD.encode(bytes);
        serializer.serialize_str(&encoded)
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        BASE64_STANDARD.decode(&s).map_err(serde::de::Error::custom)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn consensus_proposal_hash_from_hex_str_roundtrip() {
        let hex_str = "74657374";
        let hash = ConsensusProposalHash::from_hex(hex_str).expect("consensus hash hex");
        assert_eq!(hash.0, b"test".to_vec());
        assert_eq!(format!("{hash}"), hex_str);
        let json = serde_json::to_string(&hash).expect("serialize consensus hash");
        assert_eq!(json, "\"74657374\"");
        let decoded: ConsensusProposalHash =
            serde_json::from_str(&json).expect("deserialize consensus hash");
        assert_eq!(decoded, hash);
    }

    #[test]
    fn txhash_from_hex_str_roundtrip() {
        let hex_str = "746573745f7478";
        let hash = TxHash::from_hex(hex_str).expect("txhash hex");
        assert_eq!(hash.0, b"test_tx".to_vec());
        assert_eq!(format!("{hash}"), hex_str);
        let json = serde_json::to_string(&hash).expect("serialize tx hash");
        assert_eq!(json, "\"746573745f7478\"");
        let decoded: TxHash = serde_json::from_str(&json).expect("deserialize tx hash");
        assert_eq!(decoded, hash);
    }

    #[test]
    fn proof_data_hash_from_hex_str_roundtrip() {
        let hex_str = "0x74657374";
        let hash = ProofDataHash::from_hex(hex_str).expect("proof hash hex");
        assert_eq!(hash.0, b"test".to_vec());
        assert_eq!(hex::encode(&hash.0), "74657374");
        let json = serde_json::to_string(&hash).expect("serialize proof hash");
        assert_eq!(json, "\"74657374\"");
        let decoded: ProofDataHash = serde_json::from_str(&json).expect("deserialize proof hash");
        assert_eq!(decoded, hash);
    }
}