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
use cosmwasm_std::{
    coin, to_binary, Addr, Binary, Coin, CosmosMsg, CustomMsg, StdError, StdResult,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::common::{validate_address, validate_string};
use crate::types::{AttributeValueType, MarkerAccess, MarkerType, NameBinding, ProvenanceRoute};
use crate::Scope;

// The data format version to pass into provenance for message encoding
static MSG_DATAFMT_VERSION: &str = "2.0.0";

/// Represents a request to encode custom provenance messages.
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct ProvenanceMsg {
    pub route: ProvenanceRoute,      // The module router key
    pub params: ProvenanceMsgParams, // The module-specific encoder params
    pub version: String,             // The data format version
}

impl CustomMsg for ProvenanceMsg {}

// Implements From for ProvenanceMsg so it can be used in place of CosmosMsg<ProvenanceMsg>
impl From<ProvenanceMsg> for CosmosMsg<ProvenanceMsg> {
    fn from(msg: ProvenanceMsg) -> Self {
        CosmosMsg::Custom(msg)
    }
}

/// Input params for custom provenance message encoders.
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, JsonSchema)]
pub enum ProvenanceMsgParams {
    Name(NameMsgParams),
    Attribute(AttributeMsgParams),
    Marker(MarkerMsgParams),
    Metadata(MetadataMsgParams),
    MsgFees(MsgFeesMsgParams),
}

/// Input params for creating name module messages.
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum NameMsgParams {
    BindName {
        name: String,
        address: Addr,
        restrict: bool,
    },
    DeleteName {
        name: String,
    },
}

// Create a custom cosmos message using name module params.
fn create_name_msg(params: NameMsgParams) -> CosmosMsg<ProvenanceMsg> {
    CosmosMsg::Custom(ProvenanceMsg {
        route: ProvenanceRoute::Name,
        params: ProvenanceMsgParams::Name(params),
        version: String::from(MSG_DATAFMT_VERSION),
    })
}

/// Create a message that will bind a name to an address.
///
/// ### Example
///
/// ```rust
/// // Imports required
/// use cosmwasm_std::{Addr, Response, StdResult};
/// use provwasm_std::{bind_name, NameBinding, ProvenanceMsg};
///
/// // Bind a name to an address.
/// fn exec_bind_name(
///     name: String,
///     address: Addr,
/// ) -> StdResult<Response<ProvenanceMsg>> {
///    let msg = bind_name(&name, address, NameBinding::Restricted)?;
///    let mut res = Response::new().add_message(msg);
///    Ok(res)
/// }
/// ```
pub fn bind_name<S: Into<String>, H: Into<Addr>>(
    name: S,
    address: H,
    binding: NameBinding,
) -> StdResult<CosmosMsg<ProvenanceMsg>> {
    Ok(create_name_msg(NameMsgParams::BindName {
        name: validate_string(name, "name")?,
        address: validate_address(address)?,
        restrict: matches!(binding, NameBinding::Restricted),
    }))
}

/// Create a message that will un-bind a name from an address.
///
/// ### Example
///
/// ```rust
/// // Imports required
/// use cosmwasm_std::{Response, StdResult};
/// use provwasm_std::{unbind_name, ProvenanceMsg};
///
/// // Unbind a name
/// fn exec_unbind_name(name: String) -> StdResult<Response<ProvenanceMsg>> {
///     let msg = unbind_name(&name)?;
///     let mut res = Response::new().add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn unbind_name<S: Into<String>>(name: S) -> StdResult<CosmosMsg<ProvenanceMsg>> {
    Ok(create_name_msg(NameMsgParams::DeleteName {
        name: validate_string(name, "name")?,
    }))
}

/// Input params for creating attribute module messages.
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum AttributeMsgParams {
    AddAttribute {
        address: Addr,
        name: String,
        value: Binary,
        value_type: AttributeValueType,
    },
    DeleteAttribute {
        address: Addr,
        name: String,
    },
    DeleteDistinctAttribute {
        address: Addr,
        name: String,
        value: Binary,
    },
    UpdateAttribute {
        address: Addr,
        name: String,
        original_value: Binary,
        original_value_type: AttributeValueType,
        update_value: Binary,
        update_value_type: AttributeValueType,
    },
}

// Create a custom cosmos message using attribute module params.
fn create_attribute_msg(params: AttributeMsgParams) -> CosmosMsg<ProvenanceMsg> {
    CosmosMsg::Custom(ProvenanceMsg {
        route: ProvenanceRoute::Attribute,
        params: ProvenanceMsgParams::Attribute(params),
        version: String::from(MSG_DATAFMT_VERSION),
    })
}

/// Create a message that will add an attribute (a typed key-value pair) to an account.
///
/// ### Example
///
/// ```rust
/// // Imports required
/// use cosmwasm_std::{Binary, Env, Addr, Response, StdResult};
/// use provwasm_std::{add_attribute, AttributeValueType, ProvenanceMsg};
///
/// // Add a greeting attribute to an account.
/// // NOTE: The name below must resolve to the contract address.
/// fn exec_add_greeting(
///     env: Env,
///     address: Addr,
///     text: String,
/// ) -> StdResult<Response<ProvenanceMsg>> {
///     let attr_name = String::from("greeting.my-contract.sc.pb");
///     let greeting = String::from("hello");
///     let msg = add_attribute(
///         address,
///         &attr_name,
///         Binary::from(greeting.as_bytes()),
///         AttributeValueType::String,
///     )?;
///     let mut res = Response::new().add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn add_attribute<H: Into<Addr>, S: Into<String>, B: Into<Binary>>(
    address: H,
    name: S,
    value: B,
    value_type: AttributeValueType,
) -> StdResult<CosmosMsg<ProvenanceMsg>> {
    if value_type == AttributeValueType::Unspecified {
        return Err(StdError::generic_err(
            "cannot add attribute with unspecified value type",
        ));
    }
    Ok(create_attribute_msg(AttributeMsgParams::AddAttribute {
        address: validate_address(address)?,
        name: validate_string(name, "name")?,
        value: value.into(),
        value_type,
    }))
}

/// Create a message that will add a JSON attribute to an account. Serializable types can be passed
/// into this function, but it's up to the user to handle StdResult error case.
///
/// ### Example
///
/// ```rust
/// // Imports required
/// use cosmwasm_std::{Env, Addr, Response, StdResult};
/// use provwasm_std::{add_json_attribute, ProvenanceMsg};
/// use schemars::JsonSchema;
/// use serde::{Deserialize, Serialize};
///
/// // Add a label attribute. NOTE: The name below must resolve to the contract address.
/// fn exec_add_label(
///     env: Env,
///     address: Addr,
///     text: String,
/// ) -> StdResult<Response<ProvenanceMsg>> {
///     let attr_name = String::from("label.my-contract.sc.pb");
///     let timestamp = env.block.time.nanos();
///     let label = Label { text, timestamp };
///     let msg = add_json_attribute(address, &attr_name, &label)?;
///     let mut res = Response::new().add_message(msg);
///     Ok(res)
/// }
///
/// // Text with a timestamp.
/// #[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, JsonSchema)]
/// #[serde(rename_all = "snake_case")]
/// pub struct Label {
///     pub text: String,
///     pub timestamp: u64,
/// }
///
/// ```
pub fn add_json_attribute<H: Into<Addr>, S: Into<String>, T: Serialize + ?Sized>(
    address: H,
    name: S,
    data: &T,
) -> StdResult<CosmosMsg<ProvenanceMsg>> {
    // Serialize the value, bailing on error
    let value = to_binary(data)?;
    // Create and return json typed message
    add_attribute(address, name, value, AttributeValueType::Json)
}

/// Create a message that will remove all attributes with the given name from an account.
///
/// ### Example
///
/// ```rust
/// // Imports required
/// use cosmwasm_std::{Addr, Response, StdResult};
/// use provwasm_std::{delete_attributes, ProvenanceMsg};
///
/// // Delete all label attributes. NOTE: The name below must resolve to the contract address.
/// fn exec_delete_labels(
///     address: Addr,
/// ) -> StdResult<Response<ProvenanceMsg>> {
///     let attr_name = String::from("label.my-contract.sc.pb");
///     let msg = delete_attributes(address, &attr_name)?;
///     let mut res = Response::new().add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn delete_attributes<H: Into<Addr>, S: Into<String>>(
    address: H,
    name: S,
) -> StdResult<CosmosMsg<ProvenanceMsg>> {
    Ok(create_attribute_msg(AttributeMsgParams::DeleteAttribute {
        address: validate_address(address)?,
        name: validate_string(name, "name")?,
    }))
}

/// Create a message that will delete a distinct attribute with the given name and value from an account.
///
/// ### Example
///
/// ```rust
/// // Imports required
/// use cosmwasm_std::{Addr, Response, StdResult, to_binary};
/// use provwasm_std::{delete_distinct_attribute, ProvenanceMsg};
///
/// // Delete the distinct label attribute. NOTE: The name below must resolve to the contract address.
/// fn try_delete_distinct_label(
///     address: Addr,
/// ) -> StdResult<Response<ProvenanceMsg>> {
///     let attr_name = String::from("label.my-contract.sc.pb");
///     let attr_value = String::from("hello");
///     let msg = delete_distinct_attribute(address, &attr_name, to_binary(&attr_value)?)?;
///     let mut res = Response::new().add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn delete_distinct_attribute<H: Into<Addr>, S: Into<String>, B: Into<Binary>>(
    address: H,
    name: S,
    value: B,
) -> StdResult<CosmosMsg<ProvenanceMsg>> {
    Ok(create_attribute_msg(
        AttributeMsgParams::DeleteDistinctAttribute {
            address: validate_address(address)?,
            name: validate_string(name, "name")?,
            value: value.into(),
        },
    ))
}

/// Create a message that will update an attribute (a typed key-value pair) on an account.
///
/// ### Example
///
/// ```rust
/// // Imports required
/// use cosmwasm_std::{Binary, Env, Addr, Response, StdResult};
/// use provwasm_std::{update_attribute, AttributeValueType, ProvenanceMsg};
///
/// // Update an attribute on an account.
/// // NOTE: The name below must resolve to the contract address.
/// fn try_update_attribute(
///     env: Env,
///     address: Addr,
///     text: String,
/// ) -> StdResult<Response<ProvenanceMsg>> {
///     let attr_name = String::from("attribute.my-contract.sc.pb");
///     let original_attribute_value = String::from("hello");
///     let updated_attribute_value = String::from("goodbye");
///     let msg = update_attribute(
///         address,
///         &attr_name,
///         Binary::from(original_attribute_value.as_bytes()),
///         AttributeValueType::String,
///         Binary::from(original_attribute_value.as_bytes()),
///         AttributeValueType::String,
///     )?;
///     let mut res = Response::new().add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn update_attribute<H: Into<Addr>, S: Into<String>, B: Into<Binary>>(
    address: H,
    name: S,
    original_value: B,
    original_value_type: AttributeValueType,
    update_value: B,
    update_value_type: AttributeValueType,
) -> StdResult<CosmosMsg<ProvenanceMsg>> {
    if original_value_type == AttributeValueType::Unspecified {
        return Err(StdError::generic_err(
            "cannot update attribute with unspecified original value type",
        ));
    }
    if update_value_type == AttributeValueType::Unspecified {
        return Err(StdError::generic_err(
            "cannot update attribute with unspecified update value type",
        ));
    }
    Ok(create_attribute_msg(AttributeMsgParams::UpdateAttribute {
        address: validate_address(address)?,
        name: validate_string(name, "name")?,
        original_value: original_value.into(),
        original_value_type,
        update_value: update_value.into(),
        update_value_type,
    }))
}

/// Input params for creating marker module messages.
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum MarkerMsgParams {
    CreateMarker {
        coin: Coin,
        marker_type: MarkerType,
        allow_forced_transfer: bool,
    },
    GrantMarkerAccess {
        denom: String,
        address: Addr,
        permissions: Vec<MarkerAccess>,
    },
    RevokeMarkerAccess {
        denom: String,
        address: Addr,
    },
    FinalizeMarker {
        denom: String,
    },
    ActivateMarker {
        denom: String,
    },
    CancelMarker {
        denom: String,
    },
    DestroyMarker {
        denom: String,
    },
    MintMarkerSupply {
        coin: Coin,
    },
    BurnMarkerSupply {
        coin: Coin,
    },
    WithdrawCoins {
        marker_denom: String,
        coin: Coin,
        recipient: Addr,
    },
    TransferMarkerCoins {
        coin: Coin,
        to: Addr,
        from: Addr,
    },
}

// Create a custom cosmos message using marker module params.
fn create_marker_msg(params: MarkerMsgParams) -> CosmosMsg<ProvenanceMsg> {
    CosmosMsg::Custom(ProvenanceMsg {
        route: ProvenanceRoute::Marker,
        params: ProvenanceMsgParams::Marker(params),
        version: String::from(MSG_DATAFMT_VERSION),
    })
}

/// Create a message that will propose a new marker with a given type.
///
/// ### Example
///
/// ```rust
/// // Imports required
/// use cosmwasm_std::{Response, StdResult};
/// use provwasm_std::{create_marker, MarkerType, ProvenanceMsg};
///
/// // Create and dispatch a message that will propose a new unrestricted marker.
/// fn try_create_marker(
///     amount: u128,
///     denom: String,
/// ) -> StdResult<Response<ProvenanceMsg>> {
///     let msg = create_marker(amount, &denom, MarkerType::Coin)?;
///     let mut res = Response::new().add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn create_marker<S: Into<String>>(
    amount: u128,
    denom: S,
    marker_type: MarkerType,
) -> StdResult<CosmosMsg<ProvenanceMsg>> {
    let coin = coin(amount, validate_string(denom, "denom")?);
    Ok(create_marker_msg(MarkerMsgParams::CreateMarker {
        coin,
        marker_type,
        allow_forced_transfer: false,
    }))
}

/// Create a message that will propose a new restricted marker that allows forced transfers.
///
/// ### Example
///
/// ```rust
/// // Imports required
/// use cosmwasm_std::{Response, StdResult};
/// use provwasm_std::{create_forced_transfer_marker, MarkerType, ProvenanceMsg};
///
/// // Create and dispatch a message that will propose a new restricted marker that allows forced transfers.
/// fn try_create_forced_transfer_marker(
///     amount: u128,
///     denom: String,
/// ) -> StdResult<Response<ProvenanceMsg>> {
///     let msg = create_forced_transfer_marker(amount, &denom)?;
///     let mut res = Response::new().add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn create_forced_transfer_marker<S: Into<String>>(
    amount: u128,
    denom: S,
) -> StdResult<CosmosMsg<ProvenanceMsg>> {
    let coin = coin(amount, validate_string(denom, "denom")?);
    Ok(create_marker_msg(MarkerMsgParams::CreateMarker {
        coin,
        marker_type: MarkerType::Restricted,
        allow_forced_transfer: true,
    }))
}

/// Create a message that will grant permissions on a marker.
///
/// ### Example
///
/// ```rust
/// // Imports required
/// use cosmwasm_std::{Addr, Response, StdResult};
/// use provwasm_std::{grant_marker_access, MarkerAccess, ProvenanceMsg};
///
/// // Create and dispatch a message that will grant specific permissions to a marker for an address.
/// fn try_grant_marker_access(
///     denom: String,
///     address: Addr,
/// ) -> StdResult<Response<ProvenanceMsg>> {
///     let permissions = vec![MarkerAccess::Burn, MarkerAccess::Mint];
///     let msg = grant_marker_access(&denom, address, permissions)?;
///     let mut res = Response::new().add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn grant_marker_access<S: Into<String>, H: Into<Addr>>(
    denom: S,
    address: H,
    permissions: Vec<MarkerAccess>,
) -> StdResult<CosmosMsg<ProvenanceMsg>> {
    Ok(create_marker_msg(MarkerMsgParams::GrantMarkerAccess {
        denom: validate_string(denom, "denom")?,
        address: validate_address(address)?,
        permissions,
    }))
}

/// Create a message that will revoke marker permissions.
///
/// ### Example
///
/// ```rust
/// // Imports required
/// use cosmwasm_std::{Addr, Response, StdResult};
/// use provwasm_std::{revoke_marker_access, ProvenanceMsg};
///
/// // Create and dispatch a message that will revoke all permissions from a marker for an address.
/// fn try_revoke_marker_access(
///     denom: String,
///     address: Addr,
/// ) -> StdResult<Response<ProvenanceMsg>> {
///     let msg = revoke_marker_access(&denom, address)?;
///     let mut res = Response::new().add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn revoke_marker_access<S: Into<String>, H: Into<Addr>>(
    denom: S,
    address: H,
) -> StdResult<CosmosMsg<ProvenanceMsg>> {
    Ok(create_marker_msg(MarkerMsgParams::RevokeMarkerAccess {
        denom: validate_string(denom, "denom")?,
        address: validate_address(address)?,
    }))
}

/// Create a message that will finalize a proposed marker.
///
/// ### Example
///
/// ```rust
/// // Imports required
/// use cosmwasm_std::{Response, StdResult};
/// use provwasm_std::{finalize_marker, ProvenanceMsg};
///
/// // Create and dispatch a message that will finalize a proposed marker.
/// fn try_finalize_marker(denom: String) -> StdResult<Response<ProvenanceMsg>> {
///     let msg = finalize_marker(&denom)?;
///     let mut res = Response::new().add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn finalize_marker<S: Into<String>>(denom: S) -> StdResult<CosmosMsg<ProvenanceMsg>> {
    Ok(create_marker_msg(MarkerMsgParams::FinalizeMarker {
        denom: validate_string(denom, "denom")?,
    }))
}

/// Create a message that will activate a finalized marker.
///
/// ### Example
///
/// ```rust
/// // Imports required
/// use cosmwasm_std::{Response, StdResult};
/// use provwasm_std::{activate_marker, ProvenanceMsg};
///
/// // Create and dispatch a message that will activate a finalized marker.
/// fn try_activate_marker(denom: String) -> StdResult<Response<ProvenanceMsg>> {
///     let msg = activate_marker(&denom)?;
///     let mut res = Response::new().add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn activate_marker<S: Into<String>>(denom: S) -> StdResult<CosmosMsg<ProvenanceMsg>> {
    Ok(create_marker_msg(MarkerMsgParams::ActivateMarker {
        denom: validate_string(denom, "denom")?,
    }))
}

/// Create a message that will cancel a marker.
///
/// ### Example
///
/// ```rust
/// // Imports required
/// use cosmwasm_std::{Response, StdResult};
/// use provwasm_std::{cancel_marker, ProvenanceMsg};
///
/// // Create and dispatch a message that will cancel a marker.
/// fn try_cancel_marker(denom: String) -> StdResult<Response<ProvenanceMsg>> {
///     let msg = cancel_marker(&denom)?;
///     let mut res = Response::new().add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn cancel_marker<S: Into<String>>(denom: S) -> StdResult<CosmosMsg<ProvenanceMsg>> {
    Ok(create_marker_msg(MarkerMsgParams::CancelMarker {
        denom: validate_string(denom, "denom")?,
    }))
}

/// Create a message that will destroy a marker.
///
/// ### Example
///
/// ```rust
/// // Imports required
/// use cosmwasm_std::{Response, StdResult};
/// use provwasm_std::{destroy_marker, ProvenanceMsg};
///
/// // Create and dispatch a message that will destroy a marker.
/// fn try_destroy_marker(denom: String) -> StdResult<Response<ProvenanceMsg>> {
///     let msg = destroy_marker(&denom)?;
///     let mut res = Response::new().add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn destroy_marker<S: Into<String>>(denom: S) -> StdResult<CosmosMsg<ProvenanceMsg>> {
    Ok(create_marker_msg(MarkerMsgParams::DestroyMarker {
        denom: validate_string(denom, "denom")?,
    }))
}

/// Create a message that will mint marker coins.
///
/// ### Example
///
/// ```rust
/// // Imports required
/// use cosmwasm_std::{Response, StdResult};
/// use provwasm_std::{mint_marker_supply, ProvenanceMsg};
///
/// // Create and dispatch a message that will mint marker supply.
/// fn try_mint_marker(amount: u128, denom: String) -> StdResult<Response<ProvenanceMsg>> {
///     let msg = mint_marker_supply(amount, &denom)?;
///     let mut res = Response::new().add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn mint_marker_supply<S: Into<String>>(
    amount: u128,
    denom: S,
) -> StdResult<CosmosMsg<ProvenanceMsg>> {
    if amount == 0 {
        return Err(StdError::generic_err("mint amount must be > 0"));
    }
    let coin = coin(amount, validate_string(denom, "denom")?);
    Ok(create_marker_msg(MarkerMsgParams::MintMarkerSupply {
        coin,
    }))
}

/// Create a message that will burn marker coins.
///
/// ### Example
///
/// ```rust
/// // Imports required
/// use cosmwasm_std::{Response, StdResult};
/// use provwasm_std::{burn_marker_supply, ProvenanceMsg};
///
/// // Create and dispatch a message that will burn marker supply.
/// fn try_burn_marker(amount: u128, denom: String) -> StdResult<Response<ProvenanceMsg>> {
///     let msg = burn_marker_supply(amount, &denom)?;
///     let mut res = Response::new().add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn burn_marker_supply<S: Into<String>>(
    amount: u128,
    denom: S,
) -> StdResult<CosmosMsg<ProvenanceMsg>> {
    if amount == 0 {
        return Err(StdError::generic_err("burn amount must be > 0"));
    }
    let coin = coin(amount, validate_string(denom, "denom")?);
    Ok(create_marker_msg(MarkerMsgParams::BurnMarkerSupply {
        coin,
    }))
}

/// Create a message that will withdraw coins from a marker account to a recipient account.
///
/// ### Example
///
/// ```rust
/// // Imports required
/// use cosmwasm_std::{Addr, Response, StdResult};
/// use provwasm_std::{withdraw_coins, ProvenanceMsg};
///
/// // Create and dispatch a message that will withdraw coins from a marker.
/// fn try_withdraw_coins(
///     marker_denom: String,
///     amount: u128,
///     denom: String,
///     recipient: Addr,
/// ) -> StdResult<Response<ProvenanceMsg>> {
///     let msg = withdraw_coins(&marker_denom, amount, &denom, recipient)?;
///     let mut res = Response::new().add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn withdraw_coins<S: Into<String>, H: Into<Addr>>(
    marker_denom: S,
    amount: u128,
    denom: S,
    recipient: H,
) -> StdResult<CosmosMsg<ProvenanceMsg>> {
    if amount == 0 {
        return Err(StdError::generic_err("withdraw amount must be > 0"));
    }
    let coin = coin(amount, validate_string(denom, "denom")?);
    Ok(create_marker_msg(MarkerMsgParams::WithdrawCoins {
        marker_denom: validate_string(marker_denom, "marker_denom")?,
        coin,
        recipient: validate_address(recipient)?,
    }))
}

/// Create a message that will transfer a marker amount from one account to another.
///
/// ### Example
///
/// ```rust
/// // Imports required
/// use cosmwasm_std::{Addr, Response, StdResult};
/// use provwasm_std::{transfer_marker_coins, ProvenanceMsg};
///
/// // Create and dispatch a message that will transfer marker coins from one account to another.
/// // NOTE: Transfer is only enabled for restricted markers.
/// fn try_transfer_marker_coins(
///     amount: u128,
///     denom: String,
///     to: Addr,
///     from: Addr,
/// ) -> StdResult<Response<ProvenanceMsg>> {
///     let msg = transfer_marker_coins(amount, &denom, to, from)?;
///     let mut res = Response::new().add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn transfer_marker_coins<S: Into<String>, H: Into<Addr>>(
    amount: u128,
    denom: S,
    to: H,
    from: H,
) -> StdResult<CosmosMsg<ProvenanceMsg>> {
    if amount == 0 {
        return Err(StdError::generic_err("transfer amount must be > 0"));
    }
    let coin = coin(amount, validate_string(denom, "denom")?);
    let msg = create_marker_msg(MarkerMsgParams::TransferMarkerCoins {
        coin,
        to: validate_address(to)?,
        from: validate_address(from)?,
    });
    Ok(msg)
}

/// Input params for creating marker module messages.
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum MetadataMsgParams {
    WriteScope { scope: Scope, signers: Vec<Addr> },
}

// Create a custom cosmos message using metadata module params.
fn create_metadata_msg(params: MetadataMsgParams) -> CosmosMsg<ProvenanceMsg> {
    CosmosMsg::Custom(ProvenanceMsg {
        route: ProvenanceRoute::Metadata,
        params: ProvenanceMsgParams::Metadata(params),
        version: String::from(MSG_DATAFMT_VERSION),
    })
}

/// Create a message that will create, or update, a scope.
///
/// ### Example
///
/// ```rust
/// // Imports required
/// use cosmwasm_std::{Addr, Response, StdError};
/// use provwasm_std::{ProvenanceMsg, Scope, write_scope};
///
/// // Create and dispatch a message that will create, or update, a scope.
/// fn try_write_scope(scope: Scope, signers: Vec<Addr>) -> Result<Response<ProvenanceMsg>, StdError> {
///     let msg = write_scope(scope, signers)?;
///     let mut res = Response::new().add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn write_scope<S: Into<Scope>, H: Into<Addr>>(
    scope: S,
    signers: Vec<H>,
) -> Result<CosmosMsg<ProvenanceMsg>, StdError> {
    Ok(create_metadata_msg(MetadataMsgParams::WriteScope {
        scope: scope.into(),
        signers: signers
            .into_iter()
            .map(validate_address)
            .collect::<Result<Vec<Addr>, _>>()?,
    }))
}

/// Input params for creating msgfee module messages.
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum MsgFeesMsgParams {
    AssessCustomFee {
        amount: Coin,
        from: Addr,
        name: Option<String>,
        recipient: Option<Addr>,
    },
}

// Create a custom cosmos message using msgfees module params.
fn create_msgfees_msg(params: MsgFeesMsgParams) -> CosmosMsg<ProvenanceMsg> {
    CosmosMsg::Custom(ProvenanceMsg {
        route: ProvenanceRoute::Msgfees,
        params: ProvenanceMsgParams::MsgFees(params),
        version: String::from(MSG_DATAFMT_VERSION),
    })
}

/// Create a message that will assess a custom fee
/// ### Example
///
/// ```rust
/// use cosmwasm_std::{Addr, Coin, Response, StdError};
/// use provwasm_std::{assess_custom_fee, MsgFeesMsgParams, ProvenanceMsg};
///
/// fn try_assess_custom_fee(amount: Coin, name: Option<String>, from: Addr, recipient: Option<Addr>) -> Result<Response<ProvenanceMsg>, StdError>{
///     let msg = assess_custom_fee(amount, name, from, recipient)?;
///     let res = Response::new().add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn assess_custom_fee<S: Into<String>>(
    amount: Coin,
    name: Option<S>,
    from: Addr,
    recipient: Option<Addr>,
) -> Result<CosmosMsg<ProvenanceMsg>, StdError> {
    Ok(create_msgfees_msg(MsgFeesMsgParams::AssessCustomFee {
        amount,
        name: name.map(|name| name.into()),
        from,
        recipient,
    }))
}