marlowe_lang 0.3.0

experimental parser lib for Cardano Marlowe DSL
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
use std::collections::{HashMap};
use console_error_panic_hook;

use serde::{Serialize, Deserialize};
use wasm_bindgen::{prelude::*};
use crate::parsing::marlowe::ParseError;

#[cfg(feature="unstable")]
use crate::semantics::{MachineState, ProcessError, ContractSemantics};

use crate::types::marlowe::*;
use crate::extras::utils::*;

use plutus_data::FromPlutusData;


#[cfg(feature="infinite-recursion")]
pub fn basic_deserialize<'a,T : 'static>(json:&str) -> Result<T,serde_json::Error> 
where T : serde::de::DeserializeOwned + std::marker::Send{
    let j = json.to_owned();
    let mut deserializer = serde_json::Deserializer::from_str(&j);
    deserializer.disable_recursion_limit();
    let deserializer = serde_stacker::Deserializer::new(&mut deserializer);
    let value = T::deserialize(deserializer).unwrap();
    Ok(value)
}

#[cfg(not(feature="infinite-recursion"))]
pub fn basic_deserialize<'a,T : 'static>(json:&str) -> Result<T,serde_json::Error> 
where T : serde::de::DeserializeOwned + std::marker::Send{
    serde_json::de::from_str(&json)
}


#[wasm_bindgen]
pub fn decode_marlowe_dsl_from_json(dsl:&str) -> String {
    let result : Contract = basic_deserialize(dsl).unwrap();
    result.to_dsl()
}

#[wasm_bindgen]
pub fn decode_marlowe_input_cbor_hex(redeemer_cbor_hex:&str) -> String {
    let s = super::utils::try_decode_redeemer_input_cbor_hex(redeemer_cbor_hex);
    let s = serde_json::to_string_pretty(&s).unwrap();
    s
}

#[wasm_bindgen]
pub fn u64_to_i64(x:u64) -> i64 {
    x as i64
}

#[wasm_bindgen]
pub fn u64_to_string(x:u64) -> String {
    x.to_string()
}
#[wasm_bindgen]
pub fn i64_to_string(x:i64) -> String {
    x.to_string()
}

#[wasm_bindgen(start)] 
pub fn wasm_main() -> Result<(), JsValue> {
   console_error_panic_hook::set_once();
   wasm_log("marlowe_lang utils initialized.");
   Ok(())
}

fn wasm_log(x:&str) {
    web_sys::console::log_1(&JsValue::from_str(x));
}

#[wasm_bindgen]
pub fn marlowe_to_json(contract:&str) -> Result<String,String> {
    match super::utils::try_marlowe_to_json(&contract,&std::collections::HashMap::new()) {
        Ok(j) => Ok(j),
        Err(e) => Err(e)
    }
}


/// params_str format by example:
/// "variable_one_name=12345,variable_two_name=6789"
#[wasm_bindgen()]
pub fn marlowe_to_json_with_variables(contract:&str,params_str:&str) -> Result<String,String> {
    let mut h = HashMap::new();
    if params_str.contains("=") {
        for x in params_str.split(",") {
            let (name,value) = x.split_once("=").unwrap();
            let value_num = value.trim().parse::<i128>().unwrap();                        
            h.insert(name.trim().to_string(),value_num);
        }
    }
    match super::utils::try_marlowe_to_json(&contract,&h) {
        Ok(j) => Ok(j),
        Err(e) => Err(e)
    }
}

/// params_str format by example:
/// "variable_one_name=12345,variable_two_name=6789"
#[wasm_bindgen()]
pub fn parse_marlowe_with_variables(contract:&str,params_str:&str) -> Result<String,ParseError> {
    let mut h = HashMap::new();
    if params_str.contains("=") {
        for x in params_str.split(",") {
            let (name,value) = x.split_once("=").unwrap();
            let value_num = value.trim().parse::<i128>().unwrap();                        
            h.insert(name.trim().to_string(),value_num);
        }
    }
    let result = crate::deserialization::marlowe::deserialize_with_input(contract, h);
    match result{
        Ok(j) => Ok(crate::serialization::marlowe::serialize(j.contract)),
        Err(e) => Err(e)
    }
}

#[wasm_bindgen()]
pub fn format_marlowe(contract:&str) -> String {
    crate::parsing::fmt::fmt(contract)
}

fn marlowe_datum_to_json_type(x:MarloweDatum) -> String {
    
    serde_json::to_string_pretty(&x).unwrap()
}


#[wasm_bindgen()]
pub fn decode_cborhex_marlowe_plutus_datum(cbor_hex:&str) -> Result<String,JsError> {
    
    let cbor = decode_hex(cbor_hex);
    if cbor.is_err() {
        return Err(JsError::new("Input was not in hex format."))
    }

    let cbor = cbor.unwrap();

    let datum = plutus_data::from_bytes(&cbor);    
    if datum.is_err() {
        return Err(JsError::new("cbor is not in plutus data format."))
    }
    
    let datum = datum.unwrap();

    match MarloweDatum::from_plutus_data(datum,&vec![]) {
        Ok(result) => {
            Ok(marlowe_datum_to_json_type(result))    
        } 
        Err(e) => {
            Err(JsError::new(&format!("cborhex is valid, but we failed to process contents due to this error: {}",e)))
        }
    }
}


#[wasm_bindgen]
pub fn get_input_params_for_contract(marlowe_dsl:&str) -> Result<Vec<JsValue>,ParseError> {
    let contract = 
        crate::deserialization::marlowe::deserialize(marlowe_dsl)?;
    Ok([
        contract.uninitialized_const_params.iter().map(|x| 
            JsValue::from_str(&format!("CONST_PARAM:{x}"))).collect::<Vec<JsValue>>(),

        contract.uninitialized_time_params.iter().map(|x| 
            JsValue::from_str(&format!("TIME_PARAM:{x}"))).collect::<Vec<JsValue>>()

    ].concat())
}



#[wasm_bindgen]
pub fn get_marlowe_dsl_parser_errors(marlowe_dsl:&str) -> Option<ParseError> {
    match crate::deserialization::marlowe::deserialize(marlowe_dsl) {
        Ok(_) => None,
        Err(e) => Some(e)
    }
}


#[cfg(feature="unstable")]
#[wasm_bindgen]
pub struct WASMMarloweStateMachine {
    internal_instance : crate::semantics::ContractInstance
} 

#[wasm_bindgen]
#[derive(Debug,Clone)] 
pub struct WasmDatum {
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub state : WasmState,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub payout_validator_hash : String,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub contract_dsl : String
}

#[wasm_bindgen]
pub struct ObservationWasmResult {
    pub value: bool,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub warnings: WasmTransactionWarnings
}

#[cfg(feature="unstable")]
#[wasm_bindgen]
impl WASMMarloweStateMachine {

    #[wasm_bindgen]
    pub fn set_mintime(&mut self,mintime:&str) {
        let new_instance = self.internal_instance.with_min_time(&mintime.parse::<u64>().unwrap());
        self.internal_instance = new_instance;
    }

    #[wasm_bindgen]
    /// Takes an initialized (non-marlowe-extended) MarloweDSL contract as input.
    pub fn from_datum_json(datum_json:&str) -> Result<WASMMarloweStateMachine,ParseError> {
        // TODO - not plutus encoded dammit... json decode this shit?
        let datum = serde_json::de::from_str::<MarloweDatum>(&datum_json).unwrap();
        //let datum = try_decode_json_encoded_marlowe_plutus_datum(&datum_json).unwrap();
        Ok(Self {
            internal_instance : crate::semantics::ContractInstance::from_datum(&datum)
        })
    }

    #[wasm_bindgen]
    /// Takes an initialized (non-marlowe-extended) MarloweDSL contract as input.
    pub fn from_datum(datum:WasmDatum) -> Result<WASMMarloweStateMachine,ParseError> {
        let contract = Contract::from_dsl(&datum.contract_dsl,vec![]).unwrap();
        let params = MarloweParams(datum.payout_validator_hash);
        let state = datum.state.try_into().unwrap();
        let datumx = MarloweDatum{contract:contract,marlowe_params:params,state:state};
        Ok(Self {
            internal_instance : crate::semantics::ContractInstance::from_datum(&datumx)
        })
    }

    #[wasm_bindgen(constructor)]
    /// Takes an initialized (non-marlowe-extended) MarloweDSL contract as input.
    pub fn new(contract_dsl:&str,role_payout_validator_hash:&str) -> Result<WASMMarloweStateMachine,ParseError> {
        let c = crate::deserialization::marlowe::deserialize(&contract_dsl)?;
        Ok(Self {
            internal_instance : crate::semantics::ContractInstance::new(&c.contract,Some(role_payout_validator_hash.to_string())),
        })
    }

    #[wasm_bindgen]
    pub fn as_datum(&self) -> WasmDatum {
        let datum = self.internal_instance.as_datum();
        let s = self.state();
        let payout_validator_hash = datum.marlowe_params.0;
        WasmDatum {
            state : s,
            payout_validator_hash: payout_validator_hash,
            contract_dsl : datum.contract.to_dsl()
        }
    }

    #[wasm_bindgen]
    pub fn datum_json(&self) -> String {
        serde_json::to_string_pretty(&self.internal_instance.as_datum()).unwrap()
    }

    #[wasm_bindgen]
    pub fn datum_text(&self) -> String {
        let x = self.internal_instance.as_datum();
        let marlowe_params = x.marlowe_params;

        let contract = 
            format!("Contract (Marlowe-DSL): {}",
                crate::serialization::marlowe::serialize(x.contract));
        
        format!("Marlowe params: {marlowe_params:?}\n\nState: {}\n\nContinuation: {}",x.state,contract)
    }

    #[wasm_bindgen(getter)]
    pub fn contract(&self) -> String {
        self.internal_instance.contract.to_dsl()
    }

    #[wasm_bindgen]
    pub fn timeout_continuation(&self) -> String {
        match self.internal_instance.contract.clone() {
            Contract::When { when:_, timeout:_, timeout_continuation } => 
                timeout_continuation.unwrap().to_dsl(),
            _ => String::new()
        }
    }

    #[wasm_bindgen]
    pub fn logs(&self) -> StringVec {
        StringVec { items: self.internal_instance.logs.clone() }
    }

    #[wasm_bindgen(getter)]
    pub fn payments(&self) -> WasmPayments {
        WasmPayments {
            items: self.internal_instance.payments.iter().map(|x|{
                let payee_account_id = {
                    match &x.to {
                        Payee::Account(Some(p)) => p,
                        Payee::Party(Some(p)) => p,
                        _ => panic!("missing payee in payment.")
                    }
                };
                let payee = match payee_account_id {
                    AccountId::Address(a) => WasmPayee { typ: WasmPayeeType::AccountAddress, val: a.as_bech32().unwrap() },
                    AccountId::Role {role_token} => WasmPayee { typ: WasmPayeeType::AccountRole, val: role_token.to_string() },
                };
                WasmPayment {
                    amount_i128: x.amount.to_string(),
                    to: payee,
                    from:{
                        match &x.payment_from {
                            AccountId::Address(a) => WasmParty { typ: WasmPartyType::Address, val: a.as_bech32().unwrap() },
                            AccountId::Role {role_token} => WasmParty { typ: WasmPartyType::Role, val: role_token.to_string() },
                        }
                    },
                    token: WasmToken {
                        name: x.token.token_name.to_string(),
                        pol: x.token.currency_symbol.to_string(),
                    }
                }
            }).collect()
        }
    }

    #[wasm_bindgen(getter)]
    pub fn state(&self) -> WasmState {
        self.internal_instance.state.clone().try_into().unwrap()
    }

    #[wasm_bindgen]
    pub fn warnings(&self) -> WasmTransactionWarnings {
        WasmTransactionWarnings { items: self.internal_instance.warnings.clone() }
    }

    #[wasm_bindgen]
    pub fn set_acc_of_addr(&mut self,bech32_addr:&str,token_name:&str,currency_symbol:&str,quantity:&str) {
        let asset = Token {
            currency_symbol: currency_symbol.into(),
            token_name: token_name.into()
        };
        let new_instance = self.internal_instance.with_account_addr(bech32_addr, &asset, quantity.parse::<u128>().unwrap()).unwrap();
        self.internal_instance = new_instance;
    }

    #[wasm_bindgen]
    pub fn set_acc_of_role(&mut self,role:&str,token_name:&str,currency_symbol:&str,quantity:&str) {
        let asset = Token {
            currency_symbol: currency_symbol.into(),
            token_name: token_name.into()
        };
        let new_instance = self.internal_instance.with_account_role(role, &asset, quantity.parse::<u128>().unwrap());
        self.internal_instance = new_instance;
    }

    #[wasm_bindgen]
    pub fn describe(&mut self) -> String {
        serde_json::to_string_pretty(&self.internal_instance).unwrap()
    }

    #[wasm_bindgen]
    pub fn machine_state(&self) -> WasmMachineState {
        let (_a,b) = self.internal_instance.clone().process().unwrap();
        b.try_into().unwrap()
    }

    #[wasm_bindgen]
    pub fn apply_input_deposit_for_role(&mut self,from_role:&str,to_role:&str,token_name:&str,currency_symbol:&str,quantity:&str) {
        let asset = Token {
            currency_symbol: currency_symbol.into(),
            token_name: token_name.into()
        };
        let from_role_party = AccountId::role(from_role);
        let to_role_party = AccountId::role(to_role);
        let new_instance = self.internal_instance.apply_input_deposit(from_role_party, asset, quantity.parse::<i128>().unwrap(), to_role_party).unwrap();
        self.internal_instance = new_instance;
    }

    #[wasm_bindgen]
    pub fn apply_input_deposit_for_addr(&mut self,from_bech32_addr:&str,to_bech32_addr:&str,token_name:&str,currency_symbol:&str,quantity:&str) {
        let asset = Token {
            currency_symbol: currency_symbol.into(),
            token_name: token_name.into()
        };
        let from_addr_party = AccountId::Address(Address::from_bech32(from_bech32_addr).unwrap());
        let to_addr_party = AccountId::Address(Address::from_bech32(to_bech32_addr).unwrap());
        let new_instance = self.internal_instance.apply_input_deposit(from_addr_party, asset, quantity.parse::<i128>().unwrap(),to_addr_party).unwrap();
        self.internal_instance = new_instance;
    }

    #[wasm_bindgen]
    pub fn apply_input_choice_for_role(&mut self,choice_name:&str,role_name:&str,chosen_value:&str) {
        let role_party = AccountId::role(role_name);
        self.internal_instance = self.internal_instance.apply_input_choice(choice_name, role_party, chosen_value.parse::<i128>().unwrap()).unwrap();
    }

    #[wasm_bindgen]
    pub fn apply_input_choice_for_addr(&mut self,choice_name:&str,bech32_addr:&str,chosen_value:&str) {
        let role_party = AccountId::Address(Address::from_bech32(bech32_addr).unwrap());
        self.internal_instance = self.internal_instance.apply_input_choice(choice_name, role_party, chosen_value.parse::<i128>().unwrap()).unwrap()
    }

    #[wasm_bindgen]
    pub fn machine_state_json(&mut self) -> String {
        let x = self.internal_instance.process().unwrap();
        let xx : MachineState = x.1;
        let r = serde_json::to_string_pretty(&xx).unwrap();
        r
    }

    #[wasm_bindgen]
    pub fn test_observation(&mut self,obs_json:&str) -> ObservationWasmResult {
        let obs : Observation = serde_json::from_str(obs_json).unwrap();
        let (v,w) = self.internal_instance.assert_observation(&obs).unwrap();
        ObservationWasmResult { value: v, warnings: WasmTransactionWarnings { items: w } }
    }

    #[wasm_bindgen]
    pub fn process(&mut self) -> Result<String, String> {
        match &self.internal_instance.process() {
            Ok((new_instance,new_state)) => {
                self.internal_instance = new_instance.clone();
                match &new_state {
                    MachineState::ReadyForNextStep => Ok("ready".into()),
                    MachineState::WaitingForInput { expected:_,timeout:_ } => Ok("waiting".into()),
                    MachineState::Faulted(e) => Err(e.clone()),
                    MachineState::Closed => Ok(String::from("closed")),
                    MachineState::ContractHasTimedOut => Ok(String::from("timedout"))
                }
            },
            Err(ProcessError::AlreadyClosed) => Err(String::from("The contract is already closed")),
            Err(ProcessError::InvalidTime(t)) => Err(format!("Cannot apply due to invalid timeouts: {t}")),
            Err(ProcessError::UnexpectedInput(e)) => Err(format!("{e}")),
            Err(e) => Err(format!("Unknown error! {e:?}")),
        }
    }



}













// ===============================================================================
// THE TYPES BELOW EXIST ONLY FOR WASM INTEROP & ARE NOT MEANT TO BE USED DIRECTLY
// ===============================================================================

#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug,Clone)] 
pub struct WasmPayment {
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub from : WasmParty,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub to : WasmPayee,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub token : WasmToken,

    /// BIG INTEGER (i128)
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub amount_i128 : String
}

#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug,Clone,Serialize,Deserialize)] 
pub struct WasmToken {
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub name : String,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub pol : String
}

#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug,Clone)] 
pub struct WasmAccount {
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub party : WasmParty,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub token : WasmToken,

    /// BIG INTEGER (i128)
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub amount_u128 : String
}

#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug,Clone)] 
pub struct WasmChoice {
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub choice_name : String,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub choice_owner : WasmParty,
    /// BIG INTEGER (i128)
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub value_i128 : String
}

#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug,Clone)] 
pub struct WasmBoundValue {
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub name : String,

    /// BIG INTEGER (i128)
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub value_i128 : String
}

#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug,Clone)] 
pub struct WasmAccounts {
    #[wasm_bindgen::prelude::wasm_bindgen(skip)]pub items : Vec<WasmAccount>
}

#[wasm_bindgen::prelude::wasm_bindgen]
impl WasmAccounts {
    #[wasm_bindgen]
    pub fn length(&self) -> usize {
        self.items.len()
    }
    #[wasm_bindgen]
    pub fn get(&self,n:usize) -> WasmAccount {
        self.items.get(n).unwrap().clone()
    }
}

#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug,Clone)] 
pub struct WasmChoices {
    #[wasm_bindgen::prelude::wasm_bindgen(skip)]pub items : Vec<WasmChoice>
}
#[wasm_bindgen::prelude::wasm_bindgen]
impl WasmChoices {
    #[wasm_bindgen]
    pub fn length(&self) -> usize {
        self.items.len()
    }
    #[wasm_bindgen]
    pub fn get(&self,n:usize) -> WasmChoice {
        self.items.get(n).unwrap().clone()
    } 
}

#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug,Clone)] 
pub struct WasmBoundValues {
    #[wasm_bindgen::prelude::wasm_bindgen(skip)]pub items : Vec<WasmBoundValue>
}
#[wasm_bindgen::prelude::wasm_bindgen]
impl WasmBoundValues {
    #[wasm_bindgen]
    pub fn length(&self) -> usize {
        self.items.len()
    }
    #[wasm_bindgen]
    pub fn get(&self,n:usize) -> WasmBoundValue {
        self.items.get(n).unwrap().clone()
    } 
}

#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug,Clone)] 
pub struct WasmState {
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub accounts : WasmAccounts,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub choices : WasmChoices,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub bound_values : WasmBoundValues,
    pub min_time : Option<u64> , // POSIXTime
}

impl TryFrom<WasmState> for State {
    type Error = String;

    fn try_from(value: WasmState) -> Result<Self, Self::Error> {
        let mut accounthash : AccMap<(AccountId, Token), u128> = AccMap::new();
        let mut choicehash : AccMap<ChoiceId, i128> = AccMap::new();

        for x in value.accounts.items {
            if let WasmPartyType::Address = &x.party.typ() {
                accounthash.insert(
                    (
                        AccountId::Address(Address::from_bech32(&x.party.value()).unwrap()),
                        Token {
                            currency_symbol: x.token.pol,
                            token_name: x.token.name
                        }
                    ), 
                    x.amount_u128.to_string().parse::<u128>().unwrap()
                );
                continue;
            }
            if let WasmPartyType::Role = &x.party.typ() {
                accounthash.insert(
                    (
                        AccountId::Role { role_token: x.party.value() },
                        Token {
                            currency_symbol: x.token.pol,
                            token_name: x.token.name
                        }
                    ), 
                    x.amount_u128.to_string().parse::<u128>().unwrap()
                );
                continue;
            }
            return Err(String::from("invalid state due to invalid account owner."))
        }

        for x in value.choices.items {
            if let WasmPartyType::Address = &x.choice_owner.typ() {
                choicehash.insert(
                    ChoiceId { choice_name: x.choice_name, choice_owner: Some(AccountId::Address(Address::from_bech32(&x.choice_owner.value()).unwrap())) }, 
                    x.value_i128.to_string().parse::<i128>().unwrap()
                );
                continue;
            }
            if let WasmPartyType::Role = &x.choice_owner.typ() {
                choicehash.insert(
                    ChoiceId { choice_name: x.choice_name, choice_owner: Some(AccountId::Role{role_token:x.choice_owner.value()}) }, 
                    x.value_i128.to_string().parse::<i128>().unwrap()
                );
                continue;
            }

            return Err(String::from("invalid state due to invalid choice owner."))
        }

        let mut boundhash : AccMap<ValueId,i128> = AccMap::new();
        for x in value.bound_values.items {
            boundhash.insert(ValueId::Name(x.name), x.value_i128.to_string().parse::<i128>().unwrap());
        } 

        Ok(State {
            accounts: accounthash,
            choices: choicehash,
            bound_values: boundhash,
            min_time: if let Some(v) = value.min_time { v.to_string().parse::<u64>().unwrap() } else {0},
        })
    }
    
}

impl TryFrom<State> for WasmState {
    type Error = String;

    fn try_from(value: State) -> Result<Self, Self::Error> {


        Ok(WasmState {
            accounts: WasmAccounts {
                items: (value.accounts.iter().map(|x|{

                    let (p,t) = x.0;
    
                    let tok_name = &t.token_name;
                    let tok_sym = &t.currency_symbol;
    
                    let party = match p {
                        AccountId::Role { role_token } => WasmParty::new_role(&role_token),
                        AccountId::Address(a) => WasmParty::new_addr(&a.as_bech32().unwrap())
                    };
                    
                    WasmAccount {
                        party,
                        token: WasmToken { 
                            name: tok_name.clone(), 
                            pol: tok_sym.clone() 
                        },
                        amount_u128: (*x.1).to_string()
                    }
                }).collect())
            },
            choices: WasmChoices {items:value.choices.iter().map(|a|WasmChoice{
                choice_name: a.0.choice_name.clone(),
                choice_owner: a.0.choice_owner.clone().unwrap().try_into().unwrap(),
                value_i128: (*a.1).to_string()
            }).collect()},
            bound_values: WasmBoundValues {items:value.bound_values.iter().map(|a|{
                WasmBoundValue {
                    name: match a.0 {
                        ValueId::Name(n) => n.to_string(),
                    },
                    value_i128: (*a.1).to_string(),
                }
            }).collect()},
            min_time: Some(value.min_time),
        })
    }
    
}



#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug,Clone,Serialize,Deserialize)] 
pub enum WasmPartyType {
    Role = 0,
    Address = 1
}
#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug,Clone,Serialize,Deserialize)] 
pub struct WasmParty {
    typ : WasmPartyType,
    val : String
}

#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug,Clone,Serialize,Deserialize)] 
pub enum WasmPayeeType {
    AccountRole = 0,
    AccountAddress = 1,
    PartyRole = 2,
    PartyAddress = 3,
    
}
#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug,Clone,Serialize,Deserialize)] 
pub struct WasmPayee {
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)]pub typ : WasmPayeeType,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)]pub val : String
}

#[wasm_bindgen::prelude::wasm_bindgen]
impl WasmParty {
    #[wasm_bindgen]
    pub fn value(&self) -> String {
        self.val.clone()
    }
    #[wasm_bindgen]
    pub fn typ(&self) -> WasmPartyType {
        self.typ.clone()
    }
    #[wasm_bindgen]
    pub fn new_addr(bech32_addr:&str) -> Self {
        Self {
            typ: WasmPartyType::Address,
            val: bech32_addr.to_owned()
        }
    }
    #[wasm_bindgen]
    pub fn new_role(role_token:&str) -> Self {
        Self {
            typ: WasmPartyType::Role,
            val: role_token.to_owned()
        }
    }
}
impl TryFrom<crate::types::marlowe::AccountId> for WasmParty {
    type Error = String;

    fn try_from(value: crate::types::marlowe::AccountId) -> Result<Self, Self::Error> {
        match value {
             crate::types::marlowe::AccountId::Role { role_token } => Ok(WasmParty::new_role(&role_token)),
             crate::types::marlowe::AccountId::Address(a) => Ok(WasmParty::new_addr(&a.as_bech32().unwrap()))
         }
     }
}
impl TryFrom<WasmParty> for crate::types::marlowe::AccountId {
    type Error = String;

    fn try_from(value: WasmParty) -> Result<Self, Self::Error> {
        match value.typ {
            WasmPartyType::Role => Ok(AccountId::role(&value.val)),
            WasmPartyType::Address => Ok(AccountId::Address(Address::from_bech32(&value.val).unwrap())),
        }
    }


}
impl TryFrom<crate::types::marlowe_strict::Party> for WasmParty {
    type Error = String;

    fn try_from(value: crate::types::marlowe_strict::Party) -> Result<Self, Self::Error> {
        match value {
            crate::types::marlowe_strict::Party::Address(a) => Ok(WasmParty::new_addr(&a)),
            crate::types::marlowe_strict::Party::Role(r) => Ok(WasmParty::new_role(&r)),
        }
    }   
}

#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug,Clone)]
pub struct WasmTransactionWarning {
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub typ : WasmTransactionWarningType,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub value : JsValue,
}

#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug,Clone)]
pub struct WasmTransactionWarnings {
    #[wasm_bindgen::prelude::wasm_bindgen(skip)]pub items : Vec<TransactionWarning>,
    
}
#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug,Clone)]
pub enum WasmTransactionWarningType {
    Failed,TransactionNonPositiveDeposit,
    TransactionNonPositivePay,TransactionPartialPay,
    TransactionShadowing
}
#[wasm_bindgen::prelude::wasm_bindgen]
impl WasmTransactionWarnings {
    #[wasm_bindgen]
    pub fn length(&self) -> usize {
        self.items.len()
    }
    #[wasm_bindgen]
    pub fn get(&self,n:usize) -> WasmTransactionWarning {
        let item = self.items.get(n).unwrap().clone();
        match &item {
            TransactionWarning::TransactionAssertionFailed(s) => 
                WasmTransactionWarning {  
                    typ: WasmTransactionWarningType::Failed,
                    value: WasmTransactionWarningFailed{value:s.to_string()}.into()
                },
            TransactionWarning::TransactionNonPositiveDeposit { asked_to_deposit, in_account, of_token, party } => 
                WasmTransactionWarning {
                    typ: WasmTransactionWarningType::TransactionNonPositiveDeposit,
                    value: WasmTransactionWarningTransactionNonPositiveDeposit {
                        asked_to_deposit_i128: asked_to_deposit.to_string(),
                        in_account: match in_account {
                            AccountId::Address(a) => WasmParty::new_addr(&a.as_bech32().unwrap()),
                            AccountId::Role { role_token } => WasmParty::new_role(role_token),
                        },
                        of_token: WasmToken { name: of_token.token_name.to_string(), pol: of_token.currency_symbol.to_string() },
                        party: match party {
                            AccountId::Address(a) => WasmParty::new_addr(&a.as_bech32().unwrap()),
                            AccountId::Role { role_token } => WasmParty::new_role(role_token)
                        }
                    }.into()
                },
            TransactionWarning::TransactionNonPositivePay { account, asked_to_pay, of_token, to_payee } => {
                WasmTransactionWarning {
                    typ: WasmTransactionWarningType::TransactionNonPositivePay,
                    value: WasmTransactionWarningTransactionTransactionNonPositivePay {
                        asked_to_pay_i128: asked_to_pay.to_string(),
                        to_payee: payee_to_wasm(to_payee),
                        account: account_id_to_wasm_party(account),
                        of_token: WasmToken { name: of_token.token_name.to_string(), pol: of_token.currency_symbol.to_string() },
                    }.into()
                }
            },
            TransactionWarning::TransactionPartialPay { account, asked_to_pay, of_token, to_payee, but_only_paid } => {
                WasmTransactionWarning {
                    typ: WasmTransactionWarningType::TransactionPartialPay,
                    value: WasmTransactionWarningTransactionPartialPay {
                        asked_to_pay_i128: asked_to_pay.to_string(),
                        to_payee: payee_to_wasm(to_payee),
                        account: account_id_to_wasm_party(account),
                        of_token: WasmToken { name: of_token.token_name.to_string(), pol: of_token.currency_symbol.to_string() },
                        but_only_paid_i128: but_only_paid.to_string()
                    }.into()
                }
            },
            TransactionWarning::TransactionShadowing { value_id, had_value, is_now_assigned } => {
                WasmTransactionWarning {
                    typ: WasmTransactionWarningType::TransactionShadowing,
                    value: WasmTransactionWarningTransactionShadowing {
                        had_value_i128: had_value.to_string(),
                        is_now_assigned_i128: is_now_assigned.to_string(),
                        value_id: value_id.to_string()
                    }.into()
                }
            }
        }
    }
}

#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(serde::Serialize,Clone)]
pub struct WasmTransactionWarningFailed {
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)]pub value : String
}

#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(serde::Serialize,Clone)]
pub struct WasmTransactionWarningTransactionShadowing {
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub value_id : String,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub had_value_i128 : String,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub is_now_assigned_i128 : String
}

#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(serde::Serialize,Clone)]
pub struct WasmTransactionWarningTransactionPartialPay  {
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub account : WasmParty,
    /// BigInt i128
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub asked_to_pay_i128 : String,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub of_token : WasmToken,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub to_payee : WasmPayee,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)]pub but_only_paid_i128 : String
}

#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(serde::Serialize,Clone)]
pub struct WasmTransactionWarningTransactionNonPositiveDeposit {

    /// BigInt i64
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub asked_to_deposit_i128 : String,
    
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub in_account : WasmParty,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub of_token : WasmToken,        
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub party : WasmParty
}

#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(serde::Serialize,Clone)]
pub struct WasmTransactionWarningTransactionTransactionNonPositivePay{
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)]  pub account : WasmParty,
    /// BigInt i64
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub asked_to_pay_i128 : String,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)]  pub of_token : WasmToken,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)]  pub to_payee : WasmPayee
}



  
#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug,Clone)]
pub struct StringVec {
    items : Vec<String>    
}
#[wasm_bindgen::prelude::wasm_bindgen]
impl StringVec {
    #[wasm_bindgen]
    pub fn length(&self) -> usize {
        self.items.len()
    }
    #[wasm_bindgen]
    pub fn get(&self,n:usize) -> String {
        self.items.get(n).unwrap().clone()
    }
}

#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug,Clone)]
pub struct WasmInputDeposits {
    deposits : Vec<WasmInputDeposit>    
}
#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug,Clone)]
pub struct WasmPayments {
    items : Vec<WasmPayment>    
}
#[wasm_bindgen::prelude::wasm_bindgen]
impl WasmPayments {
    #[wasm_bindgen]
    pub fn length(&self) -> usize {
        self.items.len()
    }
    #[wasm_bindgen]
    pub fn get(&self,n:usize) -> WasmPayment {
        self.items.get(n).unwrap().clone()
    }
}
#[wasm_bindgen::prelude::wasm_bindgen]
impl WasmInputDeposits {
    #[wasm_bindgen]
    pub fn length(&self) -> usize {
        self.deposits.len()
    }
    #[wasm_bindgen]
    pub fn get(&self,n:usize) -> WasmInputDeposit {
        self.deposits.get(n).unwrap().clone()
    }
}
#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug,Clone)]
pub struct WasmInputChoices {
    choices : Vec<WasmInputChoice>    
}
#[wasm_bindgen::prelude::wasm_bindgen]
impl WasmInputChoices {
    #[wasm_bindgen]
    pub fn length(&self) -> usize {
        self.choices.len()
    }
    #[wasm_bindgen]
    pub fn get(&self,n:usize) -> WasmInputChoice {
        self.choices.get(n).unwrap().clone()
    }
}

#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug,Clone)]
pub struct WasmInputNotifications {
    items : Vec<WasmInputNotification>    
}
#[wasm_bindgen::prelude::wasm_bindgen]
impl WasmInputNotifications {
    #[wasm_bindgen]
    pub fn length(&self) -> usize {
        self.items.len()
    }
    #[wasm_bindgen]
    pub fn get(&self,n:usize) -> WasmInputNotification {
        self.items.get(n).unwrap().clone()
    }
}

#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug,Clone)]
pub enum WasmMachineStateEnum {
    WaitingForInput,ReadyForNextStep,ContractHasTimedOut,Closed,Faulted
}

#[wasm_bindgen::prelude::wasm_bindgen]
#[derive(Debug)]
pub struct WasmMachineState {
   pub waiting_for_notification : bool,
   #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub expected_deposits : Option<WasmInputDeposits>,
   #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub expected_choices : Option<WasmInputChoices>,
   #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub expected_notifications : Option<WasmInputNotifications>,
   #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub error : Option<String>,
   #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub next_timeout : Option<i64>,
   #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub typ : WasmMachineStateEnum,
   
}


#[derive(Debug,Clone)]
#[wasm_bindgen::prelude::wasm_bindgen]
pub struct WasmInputDeposit {
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub who_is_expected_to_pay:WasmParty,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub expected_asset_type: WasmToken,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub expected_amount: i64,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub expected_payee:WasmPayee,
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub continuation_dsl: String
}

#[derive(Debug,Clone)]
#[wasm_bindgen::prelude::wasm_bindgen]
pub struct WasmInputChoice {
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub choice_name:String , 
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub who_is_allowed_to_make_the_choice: WasmParty, 
    // "1-14,17-115"
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub bounds : String, 
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub continuation_dsl: String
}

#[derive(Debug,Clone)]
#[wasm_bindgen::prelude::wasm_bindgen]
pub struct WasmInputNotification {
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub continuation:String, 
    #[wasm_bindgen::prelude::wasm_bindgen(getter_with_clone)] pub observation:String
}

#[cfg(feature="unstable")]
impl TryFrom<crate::semantics::MachineState> for WasmMachineState {
    type Error = String;

    fn try_from(value: crate::semantics::MachineState) -> Result<Self, Self::Error> {

        match value {
            MachineState::Closed => Ok(WasmMachineState{
                waiting_for_notification : false,
                next_timeout: None,
                expected_deposits: None,
                expected_choices: None,
                expected_notifications: None,
                error: None,
                typ: WasmMachineStateEnum::Closed,
            }),
            MachineState::Faulted(e) => Ok(WasmMachineState{
                waiting_for_notification : false,
                next_timeout: None,
                expected_deposits: None,
                expected_choices: None,
                expected_notifications: None,
                error: Some(e),
                typ: WasmMachineStateEnum::Faulted,
            }),
            MachineState::ContractHasTimedOut => Ok(WasmMachineState{
                waiting_for_notification : false,
                next_timeout: None,
                expected_deposits: None,
                expected_notifications: None,
                expected_choices: None,
                error: None,
                typ: WasmMachineStateEnum::ContractHasTimedOut,
            }),
            MachineState::WaitingForInput { expected, timeout } => {
                
                let mut expected_deposits : Vec<WasmInputDeposit> = vec![];
                let mut expected_notifications : Vec<WasmInputNotification> = vec![];
                let mut expected_choices : Vec<WasmInputChoice> = vec![];
                let mut expects_notify = false;

                for x in &expected {
                    match x {

                        crate::semantics::ExpectedInput::Deposit { 
                            who_is_expected_to_pay, 
                            expected_asset_type, 
                            expected_amount, 
                            expected_payee, 
                            continuation 
                        } => {
                            let dep = WasmInputDeposit { 
                                who_is_expected_to_pay: who_is_expected_to_pay.clone().try_into().unwrap(), 
                                expected_asset_type: WasmToken { name: expected_asset_type.token_name.to_string(), pol: expected_asset_type.currency_symbol.to_string() }, 
                                expected_amount: *expected_amount as i64, 
                                expected_payee: {
                                    match expected_payee {
                                        AccountId::Address(a) => WasmPayee { typ: WasmPayeeType::AccountAddress, val: a.as_bech32().unwrap() },
                                        AccountId::Role { role_token } => WasmPayee { typ: WasmPayeeType::AccountRole, val: role_token.to_string() },
                                    }
                                }, 
                                continuation_dsl: match continuation {
                                    PossiblyMerkleizedContract::Raw(r) => r.to_dsl(),
                                    PossiblyMerkleizedContract::Merkleized(m) => format!("expected continuation merkle hash: {}",m),
                                }
                            };
                            expected_deposits.push(dep);
                        },

                        crate::semantics::ExpectedInput::Choice { 
                            choice_name, 
                            who_is_allowed_to_make_the_choice, 
                            bounds, 
                            continuation
                        } => {
                            let dslcon = match continuation {
                                PossiblyMerkleizedContract::Raw(r) => r.to_dsl(),
                                PossiblyMerkleizedContract::Merkleized(m) => format!("expected continuation merkle hash: {}",m),
                            };
                            let strbounds = bounds.iter().map(|x|format!("{}-{}",x.0,x.1)).collect::<Vec<String>>().join(",");
                            let choice = WasmInputChoice { 
                                choice_name: choice_name.to_string(), 
                                who_is_allowed_to_make_the_choice: who_is_allowed_to_make_the_choice.clone().try_into().unwrap(), 
                                bounds: strbounds.to_string(), 
                                continuation_dsl: dslcon.to_string() 
                            };
                            expected_choices.push(choice);
                        },

                        crate::semantics::ExpectedInput::Notify{continuation,obs} => {
                            expects_notify = true;
                            expected_notifications.push(WasmInputNotification {
                                observation: serde_json::to_string_pretty(obs).unwrap(), 
                                continuation: match continuation {
                                    PossiblyMerkleizedContract::Raw(r) => r.to_dsl(),
                                    PossiblyMerkleizedContract::Merkleized(m) => m.to_string()
                                }
                            })
                        }
                    }
                }

                Ok(WasmMachineState {
                    waiting_for_notification : expects_notify,
                    next_timeout: Some(timeout as i64),
                    expected_deposits: if expected_deposits.len() > 0 { Some(WasmInputDeposits{deposits:expected_deposits}) } else { None },
                    expected_choices: if expected_choices.len() > 0 { Some(WasmInputChoices{choices:expected_choices}) } else { None },
                    expected_notifications: if expected_notifications.len() > 0 { Some(WasmInputNotifications{items:expected_notifications}) } else { None },
                    error: None,
                    typ: WasmMachineStateEnum::WaitingForInput
                })
            },
            MachineState::ReadyForNextStep => Ok(WasmMachineState{
                waiting_for_notification : false,
                next_timeout: None,
                expected_deposits: None,
                expected_choices: None,
                expected_notifications: None,
                error: None,
                typ: WasmMachineStateEnum::ReadyForNextStep,
            }),
        }

    }   
}


fn account_id_to_wasm_party(x:&AccountId) -> WasmParty {
    match x {
        AccountId::Address(a) => WasmParty { typ: WasmPartyType::Address, val: a.as_bech32().unwrap().into() },
        AccountId::Role { role_token } => WasmParty { typ: WasmPartyType::Role, val: role_token.to_string() },
    }
}
fn account_id_to_wasm_payee(x:&AccountId) -> WasmPayee {
    match x {
        AccountId::Address(a) => WasmPayee { typ: WasmPayeeType::AccountAddress, val: a.as_bech32().unwrap().into() },
        AccountId::Role { role_token } => WasmPayee { typ: WasmPayeeType::AccountRole, val: role_token.to_string() },
    }
}

fn payee_to_wasm(x:&Payee) -> WasmPayee {
    let accid = match x {
        Payee::Account(Some(a)) => a,
        Payee::Party(Some(b)) => b,
        _ => panic!("cannot convert payee to wasm because it is null.")
    };
    account_id_to_wasm_payee(accid)
}