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
#![allow(clippy::field_reassign_with_default)]
use cosmwasm_std::{coin, to_binary, Binary, Coin, CosmosMsg, HumanAddr, StdError, StdResult};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

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

// 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, 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
}

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

/// Input params for creating name module messages.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum NameMsgParams {
    BindName {
        name: String,
        address: HumanAddr,
        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 restricted name to an address.
///
/// ### Example
///
/// ```rust
/// // Imports required
/// use cosmwasm_std::{HumanAddr, Response, StdResult};
/// use provwasm_std::{bind_name, NameBinding, ProvenanceMsg};
///
/// // Bind a name to an address.
/// fn exec_bind_name(
///     name: String,
///     address: HumanAddr,
/// ) -> StdResult<Response<ProvenanceMsg>> {
///    let msg = bind_name(&name, &address, NameBinding::Restricted)?;
///    let mut res = Response::new();
///    res.add_message(msg);
///    Ok(res)
/// }
/// ```
pub fn bind_name<S: Into<String>, H: Into<HumanAddr>>(
    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();
///     res.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, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum AttributeMsgParams {
    AddAttribute {
        address: HumanAddr,
        name: String,
        value: Binary,
        value_type: AttributeValueType,
    },
    DeleteAttribute {
        address: HumanAddr,
        name: String,
    },
}

// 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 a an attribute (a typed key-value pair) to an account.
///
/// ### Example
///
/// ```rust
/// // Imports required
/// use cosmwasm_std::{Binary, Env, HumanAddr, 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: HumanAddr,
///     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();
///     res.add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn add_attribute<H: Into<HumanAddr>, S: Into<String>, B: Into<Binary>>(
    address: H,
    name: S,
    value: B,
    value_type: AttributeValueType,
) -> StdResult<CosmosMsg<ProvenanceMsg>> {
    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, HumanAddr, 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: HumanAddr,
///     text: String,
/// ) -> StdResult<Response<ProvenanceMsg>> {
///     let attr_name = String::from("label.my-contract.sc.pb");
///     let timestamp = env.block.time;
///     let label = Label { text, timestamp };
///     let msg = add_json_attribute(&address, &attr_name, &label)?;
///     let mut res = Response::new();
///     res.add_message(msg);
///     Ok(res)
/// }
///
/// // Text with a timestamp.
/// #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
/// #[serde(rename_all = "snake_case")]
/// pub struct Label {
///     pub text: String,
///     pub timestamp: u64,
/// }
///
/// ```
pub fn add_json_attribute<H: Into<HumanAddr>, 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::{HumanAddr, 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: HumanAddr,
/// ) -> 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();
///     res.add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn delete_attributes<H: Into<HumanAddr>, 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")?,
    }))
}

/// Input params for creating marker module messages.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum MarkerMsgParams {
    CreateMarker {
        coin: Coin,
        marker_type: MarkerType,
    },
    GrantMarkerAccess {
        denom: String,
        address: HumanAddr,
        permissions: Vec<MarkerAccess>,
    },
    RevokeMarkerAccess {
        denom: String,
        address: HumanAddr,
    },
    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: HumanAddr,
    },
    TransferMarkerCoins {
        coin: Coin,
        to: HumanAddr,
        from: HumanAddr,
    },
}

// 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.
pub fn create_marker<S: Into<String>>(
    amount: u128,
    denom: S,
    marker_type: MarkerType,
) -> StdResult<CosmosMsg<ProvenanceMsg>> {
    if amount == 0 {
        return Err(StdError::generic_err("marker supply must be > 0"));
    }
    let coin = coin(amount, validate_string(denom, "denom")?);
    Ok(create_marker_msg(MarkerMsgParams::CreateMarker {
        coin,
        marker_type,
    }))
}

/// Create a message that will grant permissions on a marker.
///
/// ### Example
///
/// ```rust
/// // Imports required
/// use cosmwasm_std::{HumanAddr, 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: HumanAddr,
/// ) -> StdResult<Response<ProvenanceMsg>> {
///     let permissions = vec![MarkerAccess::Burn, MarkerAccess::Mint];
///     let msg = grant_marker_access(&denom, &address, permissions)?;
///     let mut res = Response::new();
///     res.add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn grant_marker_access<S: Into<String>, H: Into<HumanAddr>>(
    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::{HumanAddr, 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: HumanAddr,
/// ) -> StdResult<Response<ProvenanceMsg>> {
///     let msg = revoke_marker_access(&denom, &address)?;
///     let mut res = Response::new();
///     res.add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn revoke_marker_access<S: Into<String>, H: Into<HumanAddr>>(
    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();
///     res.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();
///     res.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();
///     res.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();
///     res.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();
///     res.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();
///     res.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::{HumanAddr, 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: HumanAddr,
/// ) -> StdResult<Response<ProvenanceMsg>> {
///     let msg = withdraw_coins(&marker_denom, amount, &denom, &recipient)?;
///     let mut res = Response::new();
///     res.add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn withdraw_coins<S: Into<String>, H: Into<HumanAddr>>(
    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::{HumanAddr, 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: HumanAddr,
///     from: HumanAddr,
/// ) -> StdResult<Response<ProvenanceMsg>> {
///     let msg = transfer_marker_coins(amount, &denom, &to, &from)?;
///     let mut res = Response::new();
///     res.add_message(msg);
///     Ok(res)
/// }
/// ```
pub fn transfer_marker_coins<S: Into<String>, H: Into<HumanAddr>>(
    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)
}