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
use cosmwasm_std::{from_binary, Addr, QuerierWrapper, StdError, StdResult};
use serde::de::DeserializeOwned;

use crate::common::{validate_address, validate_string};
use crate::query::{
    AttributeQueryParams, MarkerQueryParams, MetadataQueryParams, NameQueryParams, ProvenanceQuery,
    ProvenanceQueryParams,
};
use crate::types::{
    AttributeValueType, Attributes, Marker, Name, Names, ProvenanceRoute, Record, Records, Scope,
    Sessions,
};

// The data format version to pass into provenance for queries.
static QUERY_DATAFMT_VERSION: &str = "2.0.0";

/// A type for simplifying provenance custom queries.
pub struct ProvenanceQuerier<'a> {
    querier: &'a QuerierWrapper<'a, ProvenanceQuery>,
}

impl<'a> ProvenanceQuerier<'a> {
    /// Creates a new provenance querier
    pub fn new(querier: &'a QuerierWrapper<'a, ProvenanceQuery>) -> Self {
        ProvenanceQuerier { querier }
    }

    // Execute a name module query.
    fn query_name_module(&self, params: NameQueryParams) -> StdResult<Names> {
        let request = ProvenanceQuery {
            route: ProvenanceRoute::Name,
            params: ProvenanceQueryParams::Name(params),
            version: String::from(QUERY_DATAFMT_VERSION),
        };
        let res: Names = self.querier.query(&request.into())?;
        Ok(res)
    }

    /// Resolve the address for a name.
    ///
    /// ### Example
    ///
    /// ```rust
    /// // Imports required
    /// use cosmwasm_std::{Deps, QueryResponse, StdResult};
    /// use provwasm_std::{Name, ProvenanceQuerier, ProvenanceQuery};
    ///
    /// // Resolve the address for a name.
    /// fn query_resolve_name(deps: Deps<ProvenanceQuery>, name: String) -> StdResult<QueryResponse> {
    ///     let querier = ProvenanceQuerier::new(&deps.querier);
    ///     let name: Name = querier.resolve_name(&name)?;
    ///     // Do something with name.address ...
    ///     todo!()
    /// }
    /// ```
    pub fn resolve_name<S: Into<String>>(&self, name: S) -> StdResult<Name> {
        let res = self.query_name_module(NameQueryParams::Resolve {
            name: validate_string(name, "name")?,
        })?;
        if res.records.len() != 1 {
            return Err(StdError::generic_err(
                "expected only one address bound to name",
            ));
        }
        Ok(res.records[0].clone())
    }

    /// Lookup all names bound to the given address.
    ///
    /// ### Example
    ///
    /// ```rust
    /// // Imports required
    /// use cosmwasm_std::{Addr, Deps, QueryResponse, StdResult};
    /// use provwasm_std::{Names, ProvenanceQuerier, ProvenanceQuery};
    ///
    /// // Lookup all names bound to an address.
    /// fn query_lookup_names(deps: Deps<ProvenanceQuery>, address: Addr) -> StdResult<QueryResponse> {
    ///     let querier = ProvenanceQuerier::new(&deps.querier);
    ///     let names: Names = querier.lookup_names(address)?;
    ///     // Do something with names.records ...
    ///     todo!()
    /// }
    /// ```
    pub fn lookup_names<H: Into<Addr>>(&self, address: H) -> StdResult<Names> {
        self.query_name_module(NameQueryParams::Lookup {
            address: validate_address(address)?,
        })
    }

    // Execute a attribute module query.
    fn query_attributes(&self, params: AttributeQueryParams) -> StdResult<Attributes> {
        let request = ProvenanceQuery {
            route: ProvenanceRoute::Attribute,
            params: ProvenanceQueryParams::Attribute(params),
            version: String::from(QUERY_DATAFMT_VERSION),
        };
        let res: Attributes = self.querier.query(&request.into())?;
        Ok(res)
    }

    /// Get attributes for an account. If the name parameter is `None`, all attributes are returned.
    ///
    ///  ### Example
    ///
    /// ```rust
    /// // Imports required
    /// use cosmwasm_std::{Addr, Deps, QueryResponse, StdResult};
    /// use provwasm_std::{Attributes, ProvenanceQuerier, ProvenanceQuery};
    ///
    /// // Query all attributes added to an account.
    /// pub fn try_query_attributes(deps: Deps<ProvenanceQuery>, address: Addr) -> StdResult<QueryResponse> {
    ///     let querier = ProvenanceQuerier::new(&deps.querier);
    ///     let none: Option<String> = None;
    ///     let res: Attributes = querier.get_attributes(address, none)?;
    ///     // Do something with res.attributes ...
    ///     todo!()
    /// }
    /// ```
    pub fn get_attributes<H: Into<Addr>, S: Into<String>>(
        &self,
        address: H,
        name: Option<S>,
    ) -> StdResult<Attributes> {
        let address = validate_address(address)?;
        match name {
            None => self.query_attributes(AttributeQueryParams::GetAllAttributes { address }),
            Some(name) => self.query_attributes(AttributeQueryParams::GetAttributes {
                address,
                name: validate_string(name, "name")?,
            }),
        }
    }

    /// Get named JSON attributes from an account and deserialize the values.
    /// Attribute values with the same name must be able to be deserialized to the same type.
    ///
    /// ### Example
    ///
    /// ```rust
    /// // Imports required
    /// use cosmwasm_std::{Addr, Deps, QueryResponse, StdResult};
    /// use provwasm_std::{ProvenanceQuerier, ProvenanceQuery};
    /// use schemars::JsonSchema;
    /// use serde::{Deserialize, Serialize};
    ///
    /// // Query all label attributes added to an account.
    /// pub fn query_labels(deps: Deps<ProvenanceQuery>, address: Addr) -> StdResult<QueryResponse> {
    ///     let attr_name = String::from("label.my-contract.sc.pb");
    ///     let querier = ProvenanceQuerier::new(&deps.querier);
    ///     let labels: Vec<Label> = querier.get_json_attributes(address, &attr_name)?;
    ///     // Do something with labels...
    ///     todo!()
    /// }
    ///
    /// // Text with 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 get_json_attributes<H: Into<Addr>, S: Into<String>, T: DeserializeOwned>(
        &self,
        address: H,
        name: S,
    ) -> StdResult<Vec<T>> {
        // Gather results
        let resp = self.query_attributes(AttributeQueryParams::GetAttributes {
            address: validate_address(address)?,
            name: validate_string(name, "name")?,
        })?;
        // Map deserialize, returning values or failure.
        resp.attributes
            .iter()
            .filter(|a| a.value_type == AttributeValueType::Json)
            .map(|a| from_binary(&a.value))
            .collect()
    }

    // Execute a marker module query.
    fn query_marker(&self, params: MarkerQueryParams) -> StdResult<Marker> {
        let request = ProvenanceQuery {
            route: ProvenanceRoute::Marker,
            params: ProvenanceQueryParams::Marker(params),
            version: String::from(QUERY_DATAFMT_VERSION),
        };
        let res: Marker = self.querier.query(&request.into())?;
        Ok(res)
    }

    /// Get a marker by address.
    ///
    /// ### Example
    ///
    /// ```rust
    /// // Imports required
    /// use provwasm_std::{ProvenanceQuerier, Marker, ProvenanceQuery};
    /// use cosmwasm_std::{Addr, Deps, QueryResponse, StdResult};
    ///
    /// // Query a marker by address.
    /// fn try_get_marker_by_address(deps: Deps<ProvenanceQuery>, address: Addr) -> StdResult<QueryResponse> {
    ///     let querier = ProvenanceQuerier::new(&deps.querier);
    ///     let marker: Marker = querier.get_marker_by_address(address)?;
    ///     // Do something with marker ...
    ///     todo!()
    /// }
    /// ```
    pub fn get_marker_by_address<H: Into<Addr>>(&self, address: H) -> StdResult<Marker> {
        self.query_marker(MarkerQueryParams::GetMarkerByAddress {
            address: validate_address(address)?,
        })
    }

    /// Get a marker by denomination.
    ///
    /// ### Example
    ///
    /// ```rust
    /// // Imports required
    /// use cosmwasm_std::{Deps, QueryResponse, StdResult};
    /// use provwasm_std::{ProvenanceQuerier, Marker, ProvenanceQuery};
    ///
    /// // Query a marker by denom.
    /// fn try_get_marker_by_denom(deps: Deps<ProvenanceQuery>, denom: String) -> StdResult<QueryResponse> {
    ///     let querier = ProvenanceQuerier::new(&deps.querier);
    ///     let marker: Marker = querier.get_marker_by_denom(&denom)?;
    ///     // Do something with marker ...
    ///     todo!()
    /// }
    /// ```
    pub fn get_marker_by_denom<S: Into<String>>(&self, denom: S) -> StdResult<Marker> {
        self.query_marker(MarkerQueryParams::GetMarkerByDenom {
            denom: validate_string(denom, "denom")?,
        })
    }

    // Execute a scope query against the metadata module.
    fn query_scope(&self, params: MetadataQueryParams) -> StdResult<Scope> {
        let request = ProvenanceQuery {
            route: ProvenanceRoute::Metadata,
            params: ProvenanceQueryParams::Metadata(params),
            version: String::from(QUERY_DATAFMT_VERSION),
        };
        let res: Scope = self.querier.query(&request.into())?;
        Ok(res)
    }

    /// Get a scope by metadata ID (bech32 address string).
    ///
    /// ### Example
    /// ```rust
    /// // Imports required
    /// use provwasm_std::{ProvenanceQuerier, ProvenanceQuery, Scope};
    /// use cosmwasm_std::{Deps, QueryResponse, StdResult};
    ///
    /// // Query a scope by id.
    /// fn try_get_scope(deps: Deps<ProvenanceQuery>, scope_id: String) -> StdResult<QueryResponse> {
    ///     let querier = ProvenanceQuerier::new(&deps.querier);
    ///     let scope: Scope = querier.get_scope(scope_id)?;
    ///     // Do something with scope ...
    ///     todo!()
    /// }
    /// ```
    pub fn get_scope<S: Into<String>>(&self, scope_id: S) -> StdResult<Scope> {
        self.query_scope(MetadataQueryParams::GetScope {
            scope_id: validate_string(scope_id, "scope_id")?,
        })
    }

    // Execute a sessions query against the metadata module.
    fn query_sessions(&self, params: MetadataQueryParams) -> StdResult<Sessions> {
        let request = ProvenanceQuery {
            route: ProvenanceRoute::Metadata,
            params: ProvenanceQueryParams::Metadata(params),
            version: String::from(QUERY_DATAFMT_VERSION),
        };
        let res: Sessions = self.querier.query(&request.into())?;
        Ok(res)
    }

    /// Get all scope sessions.
    ///
    /// ### Example
    /// ```rust
    /// // Imports required
    /// use provwasm_std::{ProvenanceQuerier, ProvenanceQuery, Sessions};
    /// use cosmwasm_std::{Deps, QueryResponse, StdResult};
    ///
    /// // Query all sessions for a scope.
    /// fn try_get_sessions(deps: Deps<ProvenanceQuery>, scope_id: String) -> StdResult<QueryResponse> {
    ///     let querier = ProvenanceQuerier::new(&deps.querier);
    ///     let res: Sessions = querier.get_sessions(scope_id)?;
    ///     // Do something with res.sessions ...
    ///     todo!()
    /// }
    /// ```
    pub fn get_sessions<S: Into<String>>(&self, scope_id: S) -> StdResult<Sessions> {
        let scope_id = validate_string(scope_id, "scope_id")?;
        self.query_sessions(MetadataQueryParams::GetSessions { scope_id })
    }

    // Execute a record query against the metadata module.
    fn query_records(&self, params: MetadataQueryParams) -> StdResult<Records> {
        let request = ProvenanceQuery {
            route: ProvenanceRoute::Metadata,
            params: ProvenanceQueryParams::Metadata(params),
            version: String::from(QUERY_DATAFMT_VERSION),
        };
        let res: Records = self.querier.query(&request.into())?;
        Ok(res)
    }

    /// Get all scope records.
    ///
    /// ### Example
    /// ```rust
    /// // Imports required
    /// use provwasm_std::{ProvenanceQuerier, ProvenanceQuery, Records};
    /// use cosmwasm_std::{Deps, QueryResponse, StdResult};
    ///
    /// // Query all records for a scope.
    /// fn try_get_records(deps: Deps<ProvenanceQuery>, scope_id: String) -> StdResult<QueryResponse> {
    ///     let querier = ProvenanceQuerier::new(&deps.querier);
    ///     let res: Records = querier.get_records(scope_id)?;
    ///     // Do something with res.records ...
    ///     todo!()
    /// }
    /// ```
    pub fn get_records<S: Into<String>>(&self, scope_id: S) -> StdResult<Records> {
        let scope_id = validate_string(scope_id, "scope_id")?;
        let name: Option<String> = None;
        self.query_records(MetadataQueryParams::GetRecords { scope_id, name })
    }

    /// Get a scope record with the given name.
    ///
    /// ### Example
    /// ```rust
    /// // Imports required
    /// use provwasm_std::{ProvenanceQuerier, ProvenanceQuery, Record};
    /// use cosmwasm_std::{Deps, QueryResponse, StdResult};
    ///
    /// // Query a loan record for a scope.
    /// fn try_get_loan_record(deps: Deps<ProvenanceQuery>, scope_id: String) -> StdResult<QueryResponse> {
    ///     let querier = ProvenanceQuerier::new(&deps.querier);
    ///     let record: Record = querier.get_record_by_name(scope_id, "loan")?;
    ///     // Do something with record ...
    ///     todo!()
    /// }
    /// ```
    pub fn get_record_by_name<S: Into<String>, T: Into<String>>(
        &self,
        scope_id: S,
        name: T,
    ) -> StdResult<Record> {
        let scope_id = validate_string(scope_id, "scope_id")?;
        let name: String = validate_string(name, "name")?;
        let res = self.query_records(MetadataQueryParams::GetRecords {
            scope_id,
            name: Some(name.clone()),
        })?;
        if res.records.is_empty() {
            return Err(StdError::not_found(format!("record not found: {name}")));
        }
        Ok(res.records[0].clone())
    }
}