1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
use cosmwasm_std::{
    DepsMut, Env, MessageInfo, Storage,
    Response, Binary, to_binary,
    StdResult, StdError,
    Addr, Uint128,
    CosmosMsg, entry_point, 
    // debug_print, 
};
use secret_toolkit::{
    utils::space_pad, 
    permit::RevokedPermits,
    viewing_key::{ViewingKey, ViewingKeyStore},
    crypto::sha_256,
};

use crate::{
    msg::{
        InstantiateMsg, ExecuteMsg, ExecuteAnswer,
        TransferAction, SendAction,
        ResponseStatus::Success,  
    },
    state::{
        RESPONSE_BLOCK_SIZE, PREFIX_REVOKED_PERMITS, 
        contr_conf_r, contr_conf_w, tkn_info_r, 
        tkn_info_w, balances_w, balances_r, 
        tkn_tot_supply_w, tkn_tot_supply_r,
        set_receiver_hash, get_receiver_hash, 
        state_structs::{ContractConfig, StoredTokenInfo, CurateTokenId, TokenAmount, },
        permissions::{Permission, new_permission, update_permission, may_load_any_permission,},
        txhistory::{store_transfer, store_mint, store_burn, append_new_owner, may_get_current_owner,}, 
        metadata::Metadata, 
        expiration::Expiration, blockinfo_w,  
    },
    receiver::Snip1155ReceiveMsg, 
};

/////////////////////////////////////////////////////////////////////////////////
// Init
/////////////////////////////////////////////////////////////////////////////////

/// instantiation function. See [InitMsg](crate::msg::InitMsg) for the api
#[entry_point]
pub fn instantiate(
    mut deps:  DepsMut,
    env: Env,
    info: MessageInfo,
    msg: InstantiateMsg,
) -> StdResult<Response> {
    // save latest block info. not necessary once we migrate to CosmWasm v1.0 
    blockinfo_w(deps.storage).save(&env.block)?;

    // set admin. If `has_admin` == None => no admin. 
    // If `has_admin` == true && msg.admin == None => admin is the instantiator
    let admin = match msg.has_admin {
        false => None,
        true => match msg.admin {
            Some(i) => Some(i),
            None => Some(info.sender.clone()),
        },
    };
    
    // create contract config -- save later
    let prng_seed_hashed = sha_256(msg.entropy.as_bytes());
    let prng_seed = prng_seed_hashed.to_vec();
    
    ViewingKey::set_seed(deps.storage, &prng_seed);

    let mut config = ContractConfig { 
        admin, 
        curators: msg.curators,
        token_id_list: vec![],
        tx_cnt: 0u64,
        prng_seed,
        contract_address: env.contract.address.clone(),
    };

    // set initial balances
    for initial_token in msg.initial_tokens {
        exec_curate_token_id(
           &mut deps, 
            &env,
            &info,
            &mut config,
            initial_token,
            None,
        )?;
    }

    // save contract config -- where tx_cnt would have increased post initial balances
    contr_conf_w(deps.storage).save(&config)?;
    
    Ok(Response::default())
}

/////////////////////////////////////////////////////////////////////////////////
// Handles
/////////////////////////////////////////////////////////////////////////////////

/// contract handle function. See [ExecuteMsg](crate::msg::ExecuteMsg) and 
/// [ExecuteAnswer](crate::msg::ExecuteAnswer) for the api
#[entry_point]
pub fn execute(
    deps: DepsMut,
    env: Env,
    info: MessageInfo,
    msg: ExecuteMsg,
) -> StdResult<Response> {
    // allows approx latest block info to be available for queries. Important to enforce
    // allowance expiration. Remove this after BlockInfo becomes available to queries
    blockinfo_w(deps.storage).save(&env.block)?;

    let response = match msg {
        ExecuteMsg::CurateTokenIds {
            initial_tokens,
            memo,
            padding: _,
         } => try_curate_token_ids(
            deps,
            env,
            info,
            initial_tokens,
            memo,
        ),
        ExecuteMsg::MintTokens {
            mint_tokens,
            memo,
            padding: _
         } => try_mint_tokens(
            deps, 
            env,
            info,
            mint_tokens,
            memo
        ),
        ExecuteMsg::BurnTokens { 
            burn_tokens, 
            memo, 
            padding: _ 
        } => try_burn_tokens(
            deps, 
            env, 
            info,
            burn_tokens, 
            memo
        ),
        ExecuteMsg::ChangeMetadata { 
            token_id,
            public_metadata, 
            private_metadata 
        } => try_change_metadata(
            deps,
            env,
            info,
            token_id,
            *public_metadata,
            *private_metadata,
        ),
        ExecuteMsg::Transfer { 
            token_id,
            from,
            recipient, 
            amount,
            memo,
            padding: _,
        } => try_transfer(
            deps,
            env,
            info,
            token_id,
            from,
            recipient,
            amount,
            memo,
        ),
        ExecuteMsg::BatchTransfer { actions, padding: _ 
        } => try_batch_transfer(
            deps,
            env,
            info,
            actions,
        ),
        ExecuteMsg::Send { 
            token_id, 
            from, 
            recipient, 
            recipient_code_hash, 
            amount, 
            msg, 
            memo, 
            padding: _, 
        } => try_send(
            deps,
            env,
            info,
            SendAction {
                token_id,
                from,
                recipient,
                recipient_code_hash,
                amount,
                msg,
                memo,
            }
        ),
        ExecuteMsg::BatchSend { actions, padding: _ 
        } => try_batch_send(
            deps,
            env,
            info,
            actions,
        ),     
        ExecuteMsg::GivePermission {
            allowed_address,
            token_id,
            view_balance,
            view_balance_expiry,
            view_private_metadata,
            view_private_metadata_expiry,
            transfer,
            transfer_expiry,
            padding: _,
        } => try_give_permission(
            deps,
            env,
            info,
            allowed_address,
            token_id,
            view_balance,
            view_balance_expiry,
            view_private_metadata,
            view_private_metadata_expiry,
            transfer,
            transfer_expiry,
            ),
        ExecuteMsg::RevokePermission { 
            token_id, 
            owner, 
            allowed_address, 
            padding: _ 
        } => try_revoke_permission(
            deps,
            env,
            info,
            token_id,
            owner,
            allowed_address,
        ),
        ExecuteMsg::CreateViewingKey { 
            entropy, 
            padding: _ 
        } => try_create_viewing_key(
            deps, 
            env, 
            info,
            entropy
        ),
        ExecuteMsg::SetViewingKey { 
            key, 
            padding: _ 
        } => try_set_viewing_key(
            deps, 
            env, 
            info,
            key
        ),
        ExecuteMsg::RevokePermit { permit_name, padding: _ } => try_revoke_permit(
            deps, 
            env,
            info,
            permit_name,
        ),
        ExecuteMsg::AddCurators { add_curators, padding: _ 
        } => try_add_curators(
            deps,
            env,
            info,
            add_curators,
        ),
        ExecuteMsg::RemoveCurators { remove_curators, padding: _ 
        } => try_remove_curators(
            deps,
            env,
            info,
            remove_curators,
        ),
        ExecuteMsg::AddMinters { token_id, add_minters, padding: _ 
        } => try_add_minters(
            deps,
            env,
            info,
            token_id, 
            add_minters,
        ),
        ExecuteMsg::RemoveMinters { token_id, remove_minters, padding: _ 
        } => try_remove_minters(
            deps,
            env,
            info,
            token_id, 
            remove_minters,
        ),
        ExecuteMsg::ChangeAdmin { new_admin, padding: _ 
        } => try_change_admin(
            deps,
            env,
            info,
            new_admin,
        ),
        ExecuteMsg::RemoveAdmin { 
            current_admin, 
            contract_address, 
            padding: _ 
        } => try_remove_admin(
            deps,
            env,
            info,
            current_admin,
            contract_address,
        ),   
        ExecuteMsg::RegisterReceive { 
            code_hash, 
            padding: _, 
        } => try_register_receive(
            deps, 
            env, 
            info,
            code_hash
        ),
    };
    pad_response(response)
}

fn try_curate_token_ids(
    mut deps: DepsMut,
    env: Env,
    info: MessageInfo,
    initial_tokens: Vec<CurateTokenId>,
    memo: Option<String>,
) -> StdResult<Response> {
    let mut config = contr_conf_r(deps.storage).load()?;
    // check if sender is a curator
    verify_curator(&config, &info)?;

    // curate new token_ids
    for initial_token in initial_tokens {
        exec_curate_token_id(
            &mut deps, 
            &env,
            &info,
            &mut config,
            initial_token, 
            memo.clone(),
        )?;
    } 

    contr_conf_w(deps.storage).save(&config)?;

    Ok(Response::new().set_data(to_binary(&ExecuteAnswer::CurateTokenIds { status: Success })?))
}

fn try_mint_tokens(
    deps: DepsMut,
    env: Env,
    info: MessageInfo,
    mint_tokens: Vec<TokenAmount>,
    memo: Option<String>,
) -> StdResult<Response> {
    let mut config = contr_conf_r(deps.storage).load()?;

    // mint tokens
    for mint_token in mint_tokens {
        let token_info_op = tkn_info_r(deps.storage).may_load(mint_token.token_id.as_bytes())?;
        
        // check if token_id exists
        if token_info_op.is_none() {
            return Err(StdError::generic_err(
                "token_id does not exist. Cannot mint non-existent `token_ids`. Use `curate_token_ids` to create tokens on new `token_ids`"
            ))
        }

        // check if enable_mint == true
        if !token_info_op.clone().unwrap().token_config.flatten().enable_mint {
            return Err(StdError::generic_err(
                "minting is not enabled for this token_id"
            ))
        }

        // check if sender is a minter
        verify_minter(token_info_op.as_ref().unwrap(), &info)?;

        // add balances
        for add_balance in mint_token.balances {
            exec_change_balance(
                deps.storage, 
                &mint_token.token_id, 
                None, 
                Some(&add_balance.address), 
                &add_balance.amount, 
                &token_info_op.clone().unwrap()
            )?;

            // store mint_token
            store_mint(
                deps.storage, 
                &mut config, 
                &env.block,
                &mint_token.token_id,
                deps.api.addr_canonicalize(info.sender.as_str())?, 
                deps.api.addr_canonicalize(add_balance.address.as_str())?, 
                add_balance.amount, 
                memo.clone()
            )?;
        }
    }

    contr_conf_w(deps.storage).save(&config)?;

    Ok(Response::new().set_data(to_binary(&ExecuteAnswer::MintTokens { status: Success })?))
}

// in the base specifications, this function can be performed by token owner only
fn try_burn_tokens(
    deps: DepsMut,
    env: Env,
    info: MessageInfo,
    burn_tokens: Vec<TokenAmount>,
    memo: Option<String>,
) -> StdResult<Response> {
    let mut config = contr_conf_r(deps.storage).load()?;
    
    // burn tokens
    for burn_token in burn_tokens {
        let token_info_op = tkn_info_r(deps.storage).may_load(burn_token.token_id.as_bytes())?;
    
        if token_info_op.is_none() {
            return Err(StdError::generic_err(
                "token_id does not exist. Cannot burn non-existent `token_ids`. Use `curate_token_ids` to create tokens on new `token_ids`"
            ))
        }

        let token_info = token_info_op.clone().unwrap();

        if !token_info.token_config.flatten().enable_burn {
            return Err(StdError::generic_err(
                "burning is not enabled for this token_id"
            ))
        }

        // remove balances
        for rem_balance in burn_token.balances {
            // in base specification, burner MUST be the owner
            if rem_balance.address != info.sender {
                return Err(StdError::generic_err(format!(
                    "you do not have permission to burn {} tokens from address {}",
                    rem_balance.amount, rem_balance.address
                )))
            }

            exec_change_balance(
                deps.storage, 
                &burn_token.token_id, 
                Some(&rem_balance.address), 
                None,
                &rem_balance.amount, 
                &token_info
            )?;

            // store burn_token
            store_burn(
                deps.storage, 
                &mut config, 
                &env.block,
                &burn_token.token_id,
                // in base specification, burner MUST be the owner
                None, 
                deps.api.addr_canonicalize(rem_balance.address.as_str())?, 
                rem_balance.amount, 
                memo.clone()
            )?;
        }
    }

    contr_conf_w(deps.storage).save(&config)?;

    Ok(Response::new().set_data(to_binary(&ExecuteAnswer::BurnTokens { status: Success })?))
}

fn try_change_metadata(
    deps: DepsMut,
    _env: Env,
    info: MessageInfo,
    token_id: String,
    public_metadata: Option<Metadata>,
    private_metadata: Option<Metadata>,
) -> StdResult<Response> {
    let tkn_info_op = tkn_info_r(deps.storage).may_load(token_id.as_bytes())?;
    let tkn_conf = match tkn_info_op.clone() {
        None => return Err(StdError::generic_err(format!("token_id {} does not exist", token_id))),
        Some(i) => i.token_config.flatten(),
    };
    
    // define variables for control flow
    let owner = may_get_current_owner(deps.storage, &token_id)?;
    let is_owner = match owner {
        Some(owner_addr) => owner_addr == info.sender,
        None => false,
    };
    
    let is_minter = verify_minter(tkn_info_op.as_ref().unwrap(), &info).is_ok();

    // can sender change metadata? based on i) sender is minter or owner, ii) token_id config allows it or not 
    let allow_update = is_owner && tkn_conf.owner_may_update_metadata || is_minter && tkn_conf.minter_may_update_metadata;

    // control flow based on `allow_update`
    match allow_update {
        false => return Err(StdError::generic_err(format!(
            "unable to change the metadata for token_id {}",
            token_id
        ))),
        true => {
            let mut tkn_info = tkn_info_op.unwrap();
            if public_metadata.is_some() { tkn_info.public_metadata = public_metadata };
            if private_metadata.is_some() { tkn_info.private_metadata = private_metadata };
            tkn_info_w(deps.storage).save(token_id.as_bytes(), &tkn_info)?;
        }
    }

    Ok(Response::new().set_data(to_binary(&ExecuteAnswer::ChangeMetadata { status: Success })?))
}

#[allow(clippy::too_many_arguments)]
fn try_transfer(
    mut deps: DepsMut,
    env: Env,
    info: MessageInfo,
    token_id: String,
    from: Addr,
    recipient: Addr,
    amount: Uint128,
    memo: Option<String>,
) -> StdResult<Response> {
    impl_transfer(
        &mut deps, 
        &env, 
        &info,
        &token_id, 
        &from, 
        &recipient, 
        amount, 
        memo
    )?;

    Ok(Response::new().set_data(to_binary(&ExecuteAnswer::Transfer { status: Success })?))
}

fn try_batch_transfer(
    mut deps: DepsMut,
    env: Env,
    info: MessageInfo,
    actions: Vec<TransferAction>,
) -> StdResult<Response> {
    for action in actions {
        let from = deps.api.addr_validate(action.from.as_str())?;
        let recipient = deps.api.addr_validate(action.recipient.as_str())?;
        impl_transfer(
            &mut deps, 
            &env, 
            &info,
            &action.token_id, 
            &from, 
            &recipient, 
            action.amount, 
            action.memo
        )?;
    }

    Ok(Response::new().set_data(to_binary(&ExecuteAnswer::BatchTransfer { status: Success })?))
}

fn try_send(
    mut deps: DepsMut,
    env: Env,
    info: MessageInfo,
    action: SendAction,
) -> StdResult<Response> {
    // set up cosmos messages
    let mut messages = vec![];

    impl_send(
        &mut deps,
        &env,
        &info,
        &mut messages,
        action,
    )?;

    let data = to_binary(&ExecuteAnswer::Send { status: Success })?;
    let res = Response::new().add_messages(messages).set_data(data);
    Ok(res)
}

fn try_batch_send(
    mut deps: DepsMut,
    env: Env,
    info: MessageInfo,
    actions: Vec<SendAction>,
) -> StdResult<Response> {
    // declare vector for cosmos messages
    let mut messages = vec![];

    for action in actions {
        impl_send(
            &mut deps,
            &env,
            &info,
            &mut messages,
            action
        )?;
    }

    let data = to_binary(&ExecuteAnswer::BatchSend { status: Success })?;
    let res = Response::new().add_messages(messages).set_data(data);
    Ok(res)
}

/// does not check if `token_id` exists so attacker cannot easily figure out if
/// a `token_id` has been created 
#[allow(clippy::too_many_arguments)]
fn try_give_permission(
    deps: DepsMut,
    _env: Env,
    info: MessageInfo,
    allowed_address: Addr,
    token_id: String,
    view_balance: Option<bool>,
    view_balance_expiry: Option<Expiration>,
    view_private_metadata: Option<bool>,
    view_private_metadata_expiry: Option<Expiration>,
    transfer: Option<Uint128>,
    transfer_expiry: Option<Expiration>,
) -> StdResult<Response> {
    // may_load current permission
    let permission_op = may_load_any_permission(
        deps.storage,
        &info.sender,
        &token_id,
        &allowed_address,
    )?;
    
    let action = |
        old_perm: Permission,
        view_balance: Option<bool>,
        view_balance_expiry: Option<Expiration>,
        view_private_metadata: Option<bool>,
        view_private_metadata_expiry: Option<Expiration>,
        transfer: Option<Uint128>,
        transfer_expiry: Option<Expiration>,
    | -> Permission {
        Permission {
            view_balance_perm: match view_balance { Some(i) => i, None => old_perm.view_balance_perm}, 
            view_balance_exp: match view_balance_expiry { Some(i) => i, None => old_perm.view_balance_exp}, 
            view_pr_metadata_perm: match view_private_metadata { Some(i) => i, None => old_perm.view_pr_metadata_perm}, 
            view_pr_metadata_exp: match view_private_metadata_expiry { Some(i) => i, None => old_perm.view_pr_metadata_exp}, 
            trfer_allowance_perm: match transfer { Some(i) => i, None => old_perm.trfer_allowance_perm}, 
            trfer_allowance_exp: match transfer_expiry { Some(i) => i, None => old_perm.trfer_allowance_exp}, 
        }
    };

    // create new permission if not created yet, otherwise update existing permission
    match permission_op {
        Some(old_perm) => {
            let updated_permission = action(
                old_perm, 
                view_balance,
                view_balance_expiry,
                view_private_metadata,
                view_private_metadata_expiry,
                transfer,
                transfer_expiry,
            );     
            update_permission(deps.storage, &info.sender, &token_id, &allowed_address, &updated_permission)?;
        },
        None => {
            let default_permission = Permission::default();
            let updated_permission = action(
                default_permission, 
                view_balance,
                view_balance_expiry,
                view_private_metadata,
                view_private_metadata_expiry,
                transfer,
                transfer_expiry,
            ); 
            new_permission(deps.storage, &info.sender, &token_id, &allowed_address, &updated_permission)?;
        }
    };

    Ok(Response::new().set_data(to_binary(&ExecuteAnswer::GivePermission { status: Success })?))
}

/// changes an existing permission entry to default (ie: revoke all permissions granted). Does not remove 
/// entry in storage, because it is unecessarily in most use cases, but will require also removing 
/// owner-specific PermissionKeys, which introduces complexity and increases gas cost. 
/// If permission does not exist, message will return an error. 
fn try_revoke_permission(
    deps: DepsMut,
    _env: Env,
    info: MessageInfo,
    token_id: String,
    owner: Addr,
    allowed_addr: Addr,
) -> StdResult<Response> {
    // either owner or allowed_address can remove permission
    if info.sender != owner && info.sender != allowed_addr {
        return Err(StdError::generic_err(
            "only the owner or address with permission can remove permission"
        ))
    }
    
    update_permission(deps.storage, &owner, &token_id, &allowed_addr, &Permission::default())?;

    Ok(Response::new().set_data(to_binary(&ExecuteAnswer::RevokePermission { status: Success })?))
}

fn try_create_viewing_key(
    deps: DepsMut,
    env: Env,
    info: MessageInfo,
    entropy: String,
) -> StdResult<Response> {
    let key = ViewingKey::create(
        deps.storage,
        &info,
        &env,
        info.sender.as_str(),
        entropy.as_ref(),
    );

    Ok(Response::new().set_data(to_binary(&ExecuteAnswer::CreateViewingKey { key })?))
}

fn try_set_viewing_key(
    deps: DepsMut,
    _env: Env,
    info: MessageInfo,
    key: String,
) -> StdResult<Response> {
    ViewingKey::set(deps.storage, info.sender.as_str(), key.as_str());
    Ok(Response::new().set_data(to_binary(&ExecuteAnswer::SetViewingKey { status: Success })?))
}

fn try_revoke_permit(
    deps: DepsMut,
    _env: Env,
    info: MessageInfo,
    permit_name: String,
) -> StdResult<Response> {
    RevokedPermits::revoke_permit(
        deps.storage,
        PREFIX_REVOKED_PERMITS,
        info.sender.as_ref(),
        &permit_name,
    );

    Ok(Response::new().set_data(to_binary(&ExecuteAnswer::RevokePermit { status: Success })?))
}

fn try_add_curators(
    deps: DepsMut,
    _env: Env,
    info: MessageInfo,
    add_curators: Vec<Addr>,
) -> StdResult<Response> {
    let mut config = contr_conf_r(deps.storage).load()?;

    // verify admin
    verify_admin(&config, &info)?;

    // add curators
    for curator in add_curators {
        config.curators.push(curator);
    }
    contr_conf_w(deps.storage).save(&config)?;

    Ok(Response::new().set_data(to_binary(&ExecuteAnswer::AddCurators { status: Success })?))
}

fn try_remove_curators(
    deps: DepsMut,
    _env: Env,
    info: MessageInfo,
    remove_curators: Vec<Addr>,
) -> StdResult<Response> {
    let mut config = contr_conf_r(deps.storage).load()?;

    // verify admin
    verify_admin(&config, &info)?;

    // remove curators
    for curator in remove_curators {
        config.curators.retain(|x| x != &curator);
    }
    contr_conf_w(deps.storage).save(&config)?;

    Ok(Response::new().set_data(to_binary(&ExecuteAnswer::RemoveCurators { status: Success })?))
}

fn try_add_minters(
    deps: DepsMut,
    _env: Env,
    info: MessageInfo,
    token_id: String,
    add_minters: Vec<Addr>,
) -> StdResult<Response> {
    let contract_config = contr_conf_r(deps.storage).load()?;
    let token_info_op = tkn_info_r(deps.storage).may_load(token_id.as_bytes())?;
    if token_info_op.is_none() { return Err(StdError::generic_err(format!("token_id {} does not exist", token_id))) };
    let mut token_info = token_info_op.unwrap();

    // check if either admin
    let admin_result = verify_admin(&contract_config, &info);
    // let curator_result = verify_curator_of_token_id(&token_info, &env); Not part of base specifications. 

    let verified = admin_result.is_ok(); // || curator_result.is_ok();
    if !verified {
        return Err(StdError::generic_err("You need to be the admin to add or remove minters"))
    }

    // add minters
    let mut flattened_token_config = token_info.token_config.flatten();
    for minter in add_minters {
        flattened_token_config.minters.push(minter)
    }

    // save token info with new minters
    token_info.token_config = flattened_token_config.to_enum();  
    tkn_info_w(deps.storage).save(token_id.as_bytes(), &token_info)?;

    Ok(Response::new().set_data(to_binary(&ExecuteAnswer::AddMinters { status: Success })?))
}

fn try_remove_minters(
    deps: DepsMut,
    _env: Env,
    info: MessageInfo,
    token_id: String,
    remove_minters: Vec<Addr>,
) -> StdResult<Response> {
    let contract_config = contr_conf_r(deps.storage).load()?;
    let token_info_op = tkn_info_r(deps.storage).may_load(token_id.as_bytes())?;
    if token_info_op.is_none() { return Err(StdError::generic_err(format!("token_id {} does not exist", token_id))) };
    let mut token_info = token_info_op.unwrap();

    // check if either admin or curator
    let admin_result = verify_admin(&contract_config, &info);
    // let curator_result = verify_curator_of_token_id(&token_info, &env); Not part of base specifications. 

    let verified = admin_result.is_ok(); // || curator_result.is_ok();
    if !verified {
        return Err(StdError::generic_err("You need to be the admin to add or remove minters"))
    }

    // remove minters
    let mut flattened_token_config = token_info.token_config.flatten();
    for minter in remove_minters {
        flattened_token_config.minters.retain(|x| x != &minter);
    }
    
    // save token info with new minters
    token_info.token_config = flattened_token_config.to_enum();  
    tkn_info_w(deps.storage).save(token_id.as_bytes(), &token_info)?;

    Ok(Response::new().set_data(to_binary(&ExecuteAnswer::RemoveMinters { status: Success })?))
}


fn try_change_admin(
    deps: DepsMut,
    _env: Env,
    info: MessageInfo,
    new_admin: Addr,
) -> StdResult<Response> {
    let mut config = contr_conf_r(deps.storage).load()?;

    // verify admin
    verify_admin(&config, &info)?;

    // change admin
    config.admin = Some(new_admin);
    contr_conf_w(deps.storage).save(&config)?;

    Ok(Response::new().set_data(to_binary(&ExecuteAnswer::ChangeAdmin { status: Success })?))
}

fn try_remove_admin(
    deps: DepsMut,
    _env: Env,
    info: MessageInfo,
    current_admin: Addr,
    contract_address: Addr,
) -> StdResult<Response> {
    let mut config = contr_conf_r(deps.storage).load()?;

    // verify admin
    verify_admin(&config, &info)?;

    // checks on redundancy inputs, designed to reduce chances of accidentally 
    // calling this function
    if current_admin != config.admin.unwrap() || contract_address != config.contract_address { 
        return Err(StdError::generic_err("your inputs are incorrect to perform this function")) 
    }
    
    // remove admin
    config.admin = None;
    contr_conf_w(deps.storage).save(&config)?;

    Ok(Response::new().set_data(to_binary(&ExecuteAnswer::RemoveAdmin { status: Success })?))
}

fn try_register_receive(
    deps: DepsMut,
    _env: Env,
    info: MessageInfo,
    code_hash: String,
) -> StdResult<Response> {
    set_receiver_hash(deps.storage, &info.sender, code_hash);

    let data = to_binary(&ExecuteAnswer::RegisterReceive { status: Success })?;
    Ok(Response::new()
        .add_attribute("register_status", "success")
        .set_data(data))
}

/////////////////////////////////////////////////////////////////////////////////
// Private functions
/////////////////////////////////////////////////////////////////////////////////

fn pad_response(
    response: StdResult<Response>
) -> StdResult<Response> {
    response.map(|mut response| {
        response.data = response.data.map(|mut data| {
            space_pad(&mut data.0, RESPONSE_BLOCK_SIZE);
            data
        });
        response
    })
}

fn is_valid_name(name: &str) -> bool {
    let len = name.len();
    (3..=30).contains(&len)
}

fn is_valid_symbol(symbol: &str) -> bool {
    let len = symbol.len();
    let len_is_valid = (3..=6).contains(&len);

    // len_is_valid && symbol.bytes().all(|byte| (b'A'..=b'Z').contains(&byte))
    len_is_valid && symbol.bytes().all(|byte| byte.is_ascii_uppercase())
}

fn verify_admin(
    contract_config: &ContractConfig,
    info: &MessageInfo,
) -> StdResult<()> {
    let admin_op = &contract_config.admin;
    match admin_op {
        Some(admin) => {
            if admin != &info.sender {
                return Err(StdError::generic_err(
                    "This is an admin function",
                ));
            }
        },
        None => return Err(StdError::generic_err(
            "This contract has no admin",
        )),
    }
    
    Ok(())
}

/// verifies if sender is a curator
fn verify_curator(
    contract_config: &ContractConfig,
    info: &MessageInfo
) -> StdResult<()> {
    let curators = &contract_config.curators;
    if !curators.contains(&info.sender) {
        return Err(StdError::generic_err(
            "Only curators are allowed to curate token_ids",
        ));
    }
    Ok(())
}

// /// verifies if sender is the address that curated the token_id.
// /// Not part of base specifications, but function left here for potential use. 
// /// If this additional feature is implemented, it is important to ensure that the instantiator 
// /// still has the ability to set initial balances without later being able to change minters.
// fn verify_curator_of_token_id(
//     token_info: &StoredTokenInfo,
//     env: &Env
// ) -> StdResult<()> {
//     let curator = &token_info.curator;
//     if curator != &env.message.sender {
//         return Err(StdError::generic_err(
//             "You are not the curator of this token_id",
//         ));
//     }
//     Ok(())
// }

/// verifies if sender is a minter of the specific token_id
fn verify_minter(
    token_info: &StoredTokenInfo,
    info: &MessageInfo
) -> StdResult<()> {
    let minters = &token_info.token_config.flatten().minters;
    if !minters.contains(&info.sender) {
        return Err(StdError::generic_err(format!(
            "Only minters are allowed to mint additional tokens for token_id {}",
            token_info.token_id
        )));
    }
    Ok(())
}

/// checks if `token_id` is available (ie: not yet created), then creates new `token_id` and initial balances
fn exec_curate_token_id(
    deps: &mut DepsMut,
    env: &Env,
    info: &MessageInfo,
    config: &mut ContractConfig,
    initial_token: CurateTokenId,
    memo: Option<String>,
) -> StdResult<()> {
    // check: token_id has not been created yet
    if tkn_info_r(deps.storage).may_load(initial_token.token_info.token_id.as_bytes())?.is_some() {
        return Err(StdError::generic_err("token_id already exists. Try a different id String"))
    }

    // check: token_id is an NFT => cannot create more than one 
    if initial_token.token_info.token_config.flatten().is_nft {
        if initial_token.balances.len() > 1 {
            return Err(StdError::generic_err(format!(
                "token_id {} is an NFT; there can only be one NFT. Balances should only have one address",
                initial_token.token_info.token_id
            )))
        } else if initial_token.balances[0].amount != Uint128::from(1_u64) {
            return Err(StdError::generic_err(format!(
                "token_id {} is an NFT; there can only be one NFT. Balances.amount must == 1",
                initial_token.token_info.token_id
            )))           
        }
    }
    
    // Check name, symbol, decimals
    if !is_valid_name(&initial_token.token_info.name) {
        return Err(StdError::generic_err(
            "Name is not in the expected format (3-30 UTF-8 bytes)",
        ));
    }
    if !is_valid_symbol(&initial_token.token_info.symbol) {
        return Err(StdError::generic_err(
            "Ticker symbol is not in expected format [A-Z]{3,6}",
        ));
    }
    if initial_token.token_info.token_config.flatten().decimals > 18 {
        return Err(StdError::generic_err("Decimals must not exceed 18"));
    }


    // create and save new token info
    tkn_info_w(deps.storage).save(
        initial_token.token_info.token_id.as_bytes(), 
        &initial_token.token_info.to_store(&info.sender)
    )?;

    // set initial balances and store mint history
    for balance in initial_token.balances {
        // save new balances
        balances_w(deps.storage, &initial_token.token_info.token_id)
        .save(to_binary(&balance.address)?.as_slice(), &balance.amount)?;
        // if is_nft == true, store owner of NFT
        if initial_token.token_info.token_config.flatten().is_nft {
            append_new_owner(deps.storage, &initial_token.token_info.token_id, &balance.address)?;
        }
        // initiate total token supply
        tkn_tot_supply_w(deps.storage).save(initial_token.token_info.token_id.as_bytes(), &balance.amount)?;

        // store mint_token_id
        store_mint(
            deps.storage, 
            config, 
            &env.block,
            &initial_token.token_info.token_id, 
            deps.api.addr_canonicalize(info.sender.as_str())?, 
            deps.api.addr_canonicalize(balance.address.as_str())?, 
            balance.amount, 
            memo.clone()
        )?;
    }

    // push token_id to token_id_list
    config.token_id_list.push(initial_token.token_info.token_id);

    Ok(())
}

/// Implements a single `Send` function. Transfers Uint128 amount of a single `token_id`, 
/// saves transfer history, may register-receive, and creates callback message.
fn impl_send(
    deps: &mut DepsMut,
    env: &Env,
    info: &MessageInfo,
    messages: &mut Vec<CosmosMsg>,
    action: SendAction,
) -> StdResult<()> {
    // action variables from SendAction
    let token_id = action.token_id;
    let from = action.from;
    let amount = action.amount;
    let recipient = action.recipient;
    let recipient_code_hash = action.recipient_code_hash;
    let msg = action.msg;
    let memo = action.memo;

    // implements transfer of tokens
    impl_transfer(
        deps, 
        env, 
        info,
        &token_id, 
        &from, 
        &recipient, 
        amount, 
        memo.clone()
    )?;

    // create cosmos message
    try_add_receiver_api_callback(
        deps.storage,
        messages,
        recipient,
        recipient_code_hash,
        msg,
        info.sender.clone(),
        token_id,
        from.to_owned(),
        amount,
        memo,
    )?;

    Ok(())
}

/// Implements a single `Transfer` function. Transfers a Uint128 amount of a 
/// single `token_id` and saves the transfer history. Used by `Transfer` and 
/// `Send` (via `impl_send`) messages
#[allow(clippy::too_many_arguments)]
fn impl_transfer(
    deps: &mut DepsMut,
    env: &Env,
    info: &MessageInfo,
    token_id: &str,
    from: &Addr,
    recipient: &Addr,
    amount: Uint128,
    memo: Option<String>,
) -> StdResult<()> {
    // check if `from` == message sender || has enough allowance to send tokens
    // perform allowance check, and may reduce allowance 
    let mut throw_err = false;
    if from != &info.sender {
        // may_load_active_permission() or may_load_any_permission() both work. The former performs redundancy checks, which are
        // more relevant for authenticated queries (because transfer simply won't work if there is no balance)
        let permission_op = may_load_any_permission(deps.storage, from, token_id, &info.sender)?;

        match permission_op {
            // no permission given
            None => throw_err = true,
            // allowance has expired
            Some(perm) if perm.trfer_allowance_exp.is_expired(&env.block) 
                => return Err(StdError::generic_err(format!(
                "Allowance has expired: {}", perm.trfer_allowance_exp
            ))),
            // not enough allowance to transfer amount
            Some(perm) if perm.trfer_allowance_perm < amount => return Err(StdError::generic_err(format!(
                "Insufficient transfer allowance: {}", perm.trfer_allowance_perm
            ))),
            // success, so need to reduce allowance
            Some(mut perm) if perm.trfer_allowance_perm >= amount => {
                let new_allowance = Uint128::from(perm.trfer_allowance_perm.u128()
                    .checked_sub(amount.u128())
                    .expect("something strange happened"));
                perm.trfer_allowance_perm = new_allowance;
                update_permission(deps.storage, from, token_id, &info.sender, &perm)?;
            },
            Some(_) => unreachable!("impl_transfer permission check: this should not be reachable")
        }
    }

    // check that token_id exists
    let token_info_op = tkn_info_r(deps.storage).may_load(token_id.as_bytes())?;
    if token_info_op.is_none() { throw_err = true }

    // combined error message for no token_id or no permission given in one place to make it harder to identify if token_id already exists
    match throw_err {
        true => return Err(StdError::generic_err("These tokens do not exist or you have no permission to transfer")),
        false => (),
    }

    // transfer tokens
    exec_change_balance(
        deps.storage, 
        token_id, 
        Some(from), 
        Some(recipient), 
        &amount, 
        &token_info_op.unwrap()
    )?;

    // store transaction
    let mut config = contr_conf_r(deps.storage).load()?;
    store_transfer(
        deps.storage, 
        &mut config, 
        &env.block, 
        token_id, 
        deps.api.addr_canonicalize(from.as_str())?, 
        None, 
        deps.api.addr_canonicalize(recipient.as_str())?, 
        amount, 
        memo
    )?;
    contr_conf_w(deps.storage).save(&config)?;

    Ok(())
}

/// change token balance of an existing `token_id`. 
/// 
/// Should check that `token_id` already exists before calling this function, which is not done
/// explicitly in this function. Although token_info is an argument in this function, so it is 
/// likely that the calling function would have had to check. 
/// * If `remove_from` == None: minted new tokens.
/// * If `add_to` == None: burn tokens.
/// * If is_nft == true, then `remove_from` MUST be Some(_).
/// * If is_nft == true, stores new owner of NFT
fn exec_change_balance(
    storage: &mut dyn Storage,
    token_id: &str,
    remove_from: Option<&Addr>,
    add_to: Option<&Addr>,
    amount: &Uint128,
    token_info: &StoredTokenInfo,
) -> StdResult<()> {
    // check whether token_id is an NFT => cannot mint. This should not be reachable in standard implementation, 
    // as the calling function would have checked that enable_mint == false, which needs to be true for NFTs.
    // This is a redundancy check to make sure
    if token_info.token_config.flatten().is_nft && remove_from.is_none() {
        return Err(StdError::generic_err("NFTs can only be minted once using `mint_token_ids`"))
    }

    // check whether token_id is an NFT => assert!(amount == 1). 
    if token_info.token_config.flatten().is_nft && amount != Uint128::from(1_u64) {
        return Err(StdError::generic_err("NFT amount must == 1"))
    }

    // remove balance
    if let Some(from) = remove_from {
        let from_existing_bal = balances_r(storage, token_id).load(to_binary(&from)?.as_slice())?;
        let from_new_amount_op = from_existing_bal.u128().checked_sub(amount.u128());
        if from_new_amount_op.is_none() {
            return Err(StdError::generic_err("insufficient funds"))
        }    
        balances_w(storage, token_id)
        .save(to_binary(&from)?.as_slice(), &Uint128::from(from_new_amount_op.unwrap()))?;

        // NOTE: if nft, the ownership history remains in storage. Any existing viewing permissions of last owner 
        // will remain too
    }

    // add balance
    if let Some(to) = add_to {
        let to_existing_bal_op = balances_r(storage, token_id).may_load(to_binary(&to)?.as_slice())?; 
        let to_existing_bal = match to_existing_bal_op {
            Some(i) => i,
            // if `to` address has no balance yet, initiate zero balance
            None => Uint128::from(0_u64),
        };
        let to_new_amount_op = to_existing_bal.u128().checked_add(amount.u128());
        if to_new_amount_op.is_none() {
            return Err(StdError::generic_err("recipient will become too rich. Total tokens exceeds 2^128"))
        }

        // save new balances
        balances_w(storage, token_id)
        .save(to_binary(&to)?.as_slice(), &Uint128::from(to_new_amount_op.unwrap()))?;

        // if is_nft == true, store new owner of NFT
        if token_info.token_config.flatten().is_nft {
        append_new_owner(storage, &token_info.token_id, to)?;
        }
    }

    // may change total token supply
    match (remove_from, add_to) {
        (None, None) => (),
        (Some(_), Some(_)) => (),
        (None, Some(_)) => {
            let old_amount = tkn_tot_supply_r(storage).load(token_info.token_id.as_bytes())?;
            let new_amount_op = old_amount.u128().checked_add(amount.u128());
            let new_amount = match new_amount_op {
                Some(i) => Uint128::from(i),
                None => return Err(StdError::generic_err("total supply exceeds max allowed of 2^128")),
            };
            tkn_tot_supply_w(storage).save(token_info.token_id.as_bytes(), &new_amount)?;
        },
        (Some(_), None) => {
            let old_amount = tkn_tot_supply_r(storage).load(token_info.token_id.as_bytes())?;
            let new_amount_op = old_amount.u128().checked_sub(amount.u128());
            let new_amount = match new_amount_op {
                Some(i) => Uint128::from(i),
                None => return Err(StdError::generic_err("total supply drops below zero")),
            };
            tkn_tot_supply_w(storage).save(token_info.token_id.as_bytes(), &new_amount)?;
        },
    }

    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn try_add_receiver_api_callback(
    storage: &dyn Storage,
    messages: &mut Vec<CosmosMsg>,
    recipient: Addr,
    recipient_code_hash: Option<String>,
    msg: Option<Binary>,
    sender: Addr,
    token_id: String,
    from: Addr,
    amount: Uint128,
    memo: Option<String>,
) -> StdResult<()> {
    if let Some(receiver_hash) = recipient_code_hash {
        let receiver_msg = Snip1155ReceiveMsg::new(sender, token_id, from, amount, memo, msg);
        let callback_msg = receiver_msg.into_cosmos_msg(receiver_hash, recipient)?;

        messages.push(callback_msg);
        return Ok(());
    }

    let receiver_hash = get_receiver_hash(storage, &recipient);
    if let Some(receiver_hash) = receiver_hash {
        let receiver_hash = receiver_hash?;
        let receiver_msg = Snip1155ReceiveMsg::new(sender, token_id, from, amount, memo, msg);
        let callback_msg = receiver_msg.into_cosmos_msg(receiver_hash, recipient)?;

        messages.push(callback_msg);
    }
    
    Ok(())
}