concordium-rust-sdk 9.0.1

An SDK to use the Concordium blockchain.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! This module contains types and functions for interacting with smart
//! contracts following the [CIS-2](https://proposals.concordium.software/CIS/cis-2.html) specification.
//!
//! The type [`Cis2Contract`] act as a wrapper around
//! the [Client](crate::v2::Client) and a contract address providing
//! functions for querying and making transactions to smart contract.
mod types;

use crate::{
    contract_client::*,
    types as sdk_types,
    v2::{self, IntoBlockIdentifier},
};
use concordium_base::{
    base::Energy,
    contracts_common::{Address, Amount},
    transactions::{AccountTransaction, EncodedPayload},
};
use sdk_types::{smart_contracts, transactions};
use smart_contracts::concordium_contracts_common;
use std::convert::From;
use thiserror::*;
pub use types::*;

#[derive(Debug, Clone, Copy)]
/// A marker type to indicate that a [`ContractClient`] is a client for a `CIS2`
/// contract.
pub enum Cis2Type {}

/// A wrapper around the client representing a CIS2 token smart contract, which
/// provides functions for interaction specific to CIS2 contracts.
///
/// Note that cloning is cheap and is, therefore, the intended way of sharing
/// this type between multiple tasks.
///
/// See also [`ContractClient`] for generic methods available for any contract.
pub type Cis2Contract = ContractClient<Cis2Type>;

/// Error which can occur when submitting a transaction such as `transfer` and
/// `updateOperator` to a CIS2 smart contract.
#[derive(Debug, Error)]
pub enum Cis2TransactionError {
    /// The smart contract receive name is invalid.
    #[error("Invalid receive name: {0}")]
    InvalidReceiveName(#[from] concordium_contracts_common::NewReceiveNameError),

    /// The parameter for `transfer` is invalid.
    #[error("Invalid transfer parameter: {0}")]
    InvalidTransferParams(#[from] NewTransferParamsError),

    /// The parameter for `updateOperator` is invalid.
    #[error("Invalid updateOperator parameter: {0}")]
    InvalidUpdateOperatorParams(#[from] NewUpdateOperatorParamsError),

    /// A general RPC error occurred.
    #[error("RPC error: {0}")]
    RPCError(#[from] crate::endpoints::RPCError),
}

/// Error which can occur when submitting a transaction such as `transfer` and
/// `updateOperator` to a CIS2 smart contract.
#[derive(Debug, Error)]
pub enum Cis2DryRunError {
    /// The smart contract receive name is invalid.
    #[error("Invalid receive name: {0}")]
    InvalidReceiveName(#[from] concordium_contracts_common::NewReceiveNameError),

    /// The parameter for `transfer` is invalid.
    #[error("Invalid transfer parameter: {0}")]
    InvalidTransferParams(#[from] NewTransferParamsError),

    /// The parameter for `updateOperator` is invalid.
    #[error("Invalid updateOperator parameter: {0}")]
    InvalidUpdateOperatorParams(#[from] NewUpdateOperatorParamsError),

    /// An error occurred when querying the node.
    #[error("RPC error: {0}")]
    QueryError(#[from] crate::endpoints::QueryError),

    /// The node rejected the invocation.
    #[error("Rejected by the node: {0:?}.")]
    NodeRejected(v2::Upward<sdk_types::RejectReason>),
}

/// Error which can occur when invoking a query such as `balanceOf` and
/// `operatorOf` or `tokenMetadata` to a CIS2 smart contract.
#[derive(Debug, Error)]
pub enum Cis2QueryError {
    /// The smart contract receive name is invalid.
    #[error("Invalid receive name: {0}")]
    InvalidReceiveName(#[from] concordium_contracts_common::NewReceiveNameError),

    /// The parameter for `balanceOf` is invalid.
    #[error("Invalid balanceOf parameter: {0}")]
    InvalidBalanceOfParams(#[from] NewBalanceOfQueryParamsError),

    /// The parameter for `operatorOf` is invalid.
    #[error("Invalid operatorOf parameter: {0}")]
    InvalidOperatorOfParams(#[from] NewOperatorOfQueryParamsError),

    /// The parameter for `tokenMetadata` is invalid.
    #[error("Invalid tokenMetadata parameter: {0}")]
    InvalidTokenMetadataParams(#[from] NewTokenMetadataQueryParamsError),

    /// A general RPC error occurred.
    #[error("RPC error: {0}")]
    RPCError(#[from] super::v2::QueryError),

    /// The returned bytes from invoking the smart contract could not be parsed.
    #[error("Failed parsing the response.")]
    ResponseParseError(#[from] concordium_contracts_common::ParseError),

    /// The node rejected the invocation.
    #[error("Rejected by the node: {0:?}.")]
    NodeRejected(v2::Upward<sdk_types::RejectReason>),
}

// This is implemented manually, since deriving it using thiserror requires
// `RejectReason` to implement std::error::Error.
impl From<v2::Upward<sdk_types::RejectReason>> for Cis2QueryError {
    fn from(err: v2::Upward<sdk_types::RejectReason>) -> Self {
        Self::NodeRejected(err)
    }
}
impl From<sdk_types::RejectReason> for Cis2QueryError {
    fn from(err: sdk_types::RejectReason) -> Self {
        Self::NodeRejected(v2::Upward::Known(err))
    }
}

// This is implemented manually, since deriving it using thiserror requires
// `RejectReason` to implement std::error::Error.
impl From<v2::Upward<sdk_types::RejectReason>> for Cis2DryRunError {
    fn from(err: v2::Upward<sdk_types::RejectReason>) -> Self {
        Self::NodeRejected(err)
    }
}
impl From<sdk_types::RejectReason> for Cis2DryRunError {
    fn from(err: sdk_types::RejectReason) -> Self {
        Self::NodeRejected(v2::Upward::Known(err))
    }
}

/// Transaction metadata for CIS-2
pub type Cis2TransactionMetadata = ContractTransactionMetadata;

impl Cis2Contract {
    /// Like [`transfer`](Self::transfer) except it only dry-runs the
    /// transaction to get the response and, in case of success, amount of
    /// energy used for execution.
    ///
    /// # Arguments
    ///
    /// * `bi` - The block to dry-run at. The invocation happens at the end of
    ///   the specified block.
    /// * `sender` - The address that is invoking the entrypoint.
    /// * `transfers` - A list of CIS2 token transfers to execute.
    pub async fn transfer_dry_run(
        &mut self,
        bi: impl IntoBlockIdentifier,
        sender: Address,
        transfers: Vec<Transfer>,
    ) -> Result<Energy, Cis2DryRunError> {
        let parameter = TransferParams::new(transfers)?;
        let parameter = smart_contracts::OwnedParameter::from_serial(&parameter)
            .map_err(|_| Cis2DryRunError::InvalidTransferParams(NewTransferParamsError))?;
        let ir = self
            .invoke_raw::<Cis2DryRunError>("transfer", Amount::zero(), Some(sender), parameter, bi)
            .await?;
        match ir {
            smart_contracts::InvokeContractResult::Success { used_energy, .. } => Ok(used_energy),
            smart_contracts::InvokeContractResult::Failure { reason, .. } => Err(reason.into()),
        }
    }

    /// Like [`transfer_dry_run`](Self::transfer_dry_run) except it is more
    /// ergonomic when only a single transfer is to be made.
    pub async fn transfer_single_dry_run(
        &mut self,
        bi: impl IntoBlockIdentifier,
        sender: Address,
        transfer: Transfer,
    ) -> Result<Energy, Cis2DryRunError> {
        self.transfer_dry_run(bi, sender, vec![transfer]).await
    }

    /// Construct **and send** a CIS2 transfer smart contract update transaction
    /// given a list of CIS2 transfers. Returns a Result with the
    /// transaction hash.
    ///
    /// # Arguments
    ///
    /// * `signer` - The account keys to use for signing the smart contract
    ///   update transaction.
    /// * `transaction_metadata` - Metadata for constructing the transaction.
    /// * `transfers` - A list of CIS2 token transfers to execute.
    pub async fn transfer(
        &mut self,
        signer: &impl transactions::ExactSizeTransactionSigner,
        transaction_metadata: Cis2TransactionMetadata,
        transfers: Vec<Transfer>,
    ) -> Result<sdk_types::hashes::TransactionHash, Cis2TransactionError> {
        let transfer = self.make_transfer(signer, transaction_metadata, transfers)?;
        let hash = self.client.send_account_transaction(transfer).await?;
        Ok(hash)
    }

    /// Construct a CIS2 transfer smart contract update transaction
    /// given a list of CIS2 transfers. Returns a [`Result`] with an account
    /// transaction that can be sent.
    ///
    /// # Arguments
    ///
    /// * `signer` - The account keys to use for signing the smart contract
    ///   update transaction.
    /// * `transaction_metadata` - Metadata for constructing the transaction.
    /// * `transfers` - A list of CIS2 token transfers to execute.
    pub fn make_transfer(
        &self,
        signer: &impl transactions::ExactSizeTransactionSigner,
        transaction_metadata: Cis2TransactionMetadata,
        transfers: Vec<Transfer>,
    ) -> Result<AccountTransaction<EncodedPayload>, Cis2TransactionError> {
        let parameter = TransferParams::new(transfers)?;
        let message = smart_contracts::OwnedParameter::from_serial(&parameter)
            .map_err(|_| Cis2TransactionError::InvalidTransferParams(NewTransferParamsError))?;
        self.make_update_raw(signer, &transaction_metadata, "transfer", message)
    }

    /// Like [`transfer`](Self::transfer), except it is more ergonomic
    /// when transferring a single token.
    pub async fn transfer_single(
        &mut self,
        signer: &impl transactions::ExactSizeTransactionSigner,
        transaction_metadata: Cis2TransactionMetadata,
        transfer: Transfer,
    ) -> Result<sdk_types::hashes::TransactionHash, Cis2TransactionError> {
        self.transfer(signer, transaction_metadata, vec![transfer])
            .await
    }

    /// Like [`make_transfer`](Self::make_transfer), except it is more ergonomic
    /// when transferring a single token.
    pub fn make_transfer_single(
        &self,
        signer: &impl transactions::ExactSizeTransactionSigner,
        transaction_metadata: Cis2TransactionMetadata,
        transfer: Transfer,
    ) -> Result<AccountTransaction<EncodedPayload>, Cis2TransactionError> {
        self.make_transfer(signer, transaction_metadata, vec![transfer])
    }

    /// Dry run a CIS2 updateOperator transaction. This is analogous to
    /// [`update_operator`](Self::update_operator), except that it does not send
    /// a transaction to the chain, and just simulates the transaction.
    ///
    /// # Arguments
    ///
    /// * `bi` - The block to dry-run at. The invocation happens at the end of
    /// * `owner` - The address that is invoking. This is the owner of the
    ///   tokens.
    /// * `updates` - A list of CIS2 UpdateOperators to update.
    pub async fn update_operator_dry_run(
        &mut self,
        bi: impl IntoBlockIdentifier,
        owner: Address,
        updates: Vec<UpdateOperator>,
    ) -> anyhow::Result<Energy, Cis2DryRunError> {
        let parameter = UpdateOperatorParams::new(updates)?;
        let parameter = smart_contracts::OwnedParameter::from_serial(&parameter)
            .map_err(|_| Cis2DryRunError::InvalidTransferParams(NewTransferParamsError))?;
        let ir = self
            .invoke_raw::<Cis2DryRunError>(
                "updateOperator",
                Amount::zero(),
                Some(owner),
                parameter,
                bi,
            )
            .await?;
        match ir {
            smart_contracts::InvokeContractResult::Success { used_energy, .. } => Ok(used_energy),
            smart_contracts::InvokeContractResult::Failure { reason, .. } => Err(reason.into()),
        }
    }

    /// Like [`update_operator_dry_run`](Self::update_operator_dry_run) except
    /// more ergonomic when a single operator is to be updated.
    pub async fn update_operator_single_dry_run(
        &mut self,
        bi: impl IntoBlockIdentifier,
        owner: Address,
        operator: Address,
        update: OperatorUpdate,
    ) -> anyhow::Result<Energy, Cis2DryRunError> {
        self.update_operator_dry_run(bi, owner, vec![UpdateOperator { update, operator }])
            .await
    }

    /// Construct a CIS2 updateOperator smart contract update
    /// transaction given a list of CIS2 UpdateOperators. Returns a [`Result`]
    /// with the account transaction that can be sent.
    ///
    /// # Arguments
    ///
    /// * `signer` - The account keys to use for signing the smart contract
    ///   update transaction.
    /// * `transaction_metadata` - Metadata for constructing the transaction.
    /// * `updates` - A list of CIS2 UpdateOperators to update.
    pub fn make_update_operator(
        &self,
        signer: &impl transactions::ExactSizeTransactionSigner,
        transaction_metadata: Cis2TransactionMetadata,
        updates: Vec<UpdateOperator>,
    ) -> anyhow::Result<AccountTransaction<EncodedPayload>, Cis2TransactionError> {
        let parameter = UpdateOperatorParams::new(updates)?;
        let message = smart_contracts::OwnedParameter::from_serial(&parameter).map_err(|_| {
            Cis2TransactionError::InvalidUpdateOperatorParams(NewUpdateOperatorParamsError)
        })?;
        self.make_update_raw(signer, &transaction_metadata, "updateOperator", message)
    }

    /// Construct **and send** a CIS2 updateOperator smart contract update
    /// transaction given a list of CIS2 UpdateOperators. Returns a Result
    /// with the transaction hash.
    ///
    /// # Arguments
    ///
    /// * `signer` - The account keys to use for signing the smart contract
    ///   update transaction.
    /// * `transaction_metadata` - Metadata for constructing the transaction.
    /// * `updates` - A list of CIS2 UpdateOperators to update.
    pub async fn update_operator(
        &mut self,
        signer: &impl transactions::ExactSizeTransactionSigner,
        transaction_metadata: Cis2TransactionMetadata,
        updates: Vec<UpdateOperator>,
    ) -> anyhow::Result<sdk_types::hashes::TransactionHash, Cis2TransactionError> {
        let update = self.make_update_operator(signer, transaction_metadata, updates)?;
        let hash = self.client.send_account_transaction(update).await?;
        Ok(hash)
    }

    /// Like [`update_operator`](Self::update_operator), but more ergonomic
    /// when updating a single operator.
    pub async fn update_operator_single(
        &mut self,
        signer: &impl transactions::ExactSizeTransactionSigner,
        transaction_metadata: Cis2TransactionMetadata,
        operator: Address,
        update: OperatorUpdate,
    ) -> anyhow::Result<sdk_types::hashes::TransactionHash, Cis2TransactionError> {
        self.update_operator(
            signer,
            transaction_metadata,
            vec![UpdateOperator { update, operator }],
        )
        .await
    }

    /// Like [`make_update_operator`](Self::make_update_operator), but more
    /// ergonomic when updating a single operator.
    pub fn make_update_operator_single(
        &self,
        signer: &impl transactions::ExactSizeTransactionSigner,
        transaction_metadata: Cis2TransactionMetadata,
        operator: Address,
        update: OperatorUpdate,
    ) -> anyhow::Result<AccountTransaction<EncodedPayload>, Cis2TransactionError> {
        self.make_update_operator(
            signer,
            transaction_metadata,
            vec![UpdateOperator { update, operator }],
        )
    }

    /// Invoke the CIS2 balanceOf query given a list of BalanceOfQuery.
    ///
    /// Note: the query is executed locally by the node and does not produce a
    /// transaction on-chain.
    ///
    /// # Arguments
    ///
    /// * `bi` - The block to query. The query will be executed in the state of
    ///   the chain at the end of the block.
    /// * `queries` - A list queries to execute.
    pub async fn balance_of(
        &mut self,
        bi: impl IntoBlockIdentifier,
        queries: Vec<BalanceOfQuery>,
    ) -> Result<BalanceOfQueryResponse, Cis2QueryError> {
        let parameter = BalanceOfQueryParams::new(queries)?;
        let parameter = smart_contracts::OwnedParameter::from_serial(&parameter)
            .map_err(|_| Cis2QueryError::InvalidBalanceOfParams(NewBalanceOfQueryParamsError))?;
        self.view_raw("balanceOf", parameter, bi).await
    }

    /// Like [`balance_of`](Self::balance_of), except for querying a single
    /// token. This additionally ensures that the response has correct
    /// length.
    pub async fn balance_of_single(
        &mut self,
        bi: impl IntoBlockIdentifier,
        token_id: TokenId,
        address: Address,
    ) -> Result<TokenAmount, Cis2QueryError> {
        let res = self
            .balance_of(bi, vec![BalanceOfQuery { token_id, address }])
            .await?;
        only_one(res)
    }

    /// Invoke the CIS2 operatorOf query given a list of OperatorOfQuery.
    ///
    /// Note: the query is executed locally by the node and does not produce a
    /// transaction on-chain.
    ///
    /// # Arguments
    ///
    /// * `bi` - The block to query. The query will be executed in the state of
    ///   the chain at the end of the block.
    /// * `queries` - A list queries to execute.
    pub async fn operator_of(
        &mut self,
        bi: impl IntoBlockIdentifier,
        queries: Vec<OperatorOfQuery>,
    ) -> Result<OperatorOfQueryResponse, Cis2QueryError> {
        let parameter = OperatorOfQueryParams::new(queries)?;
        let parameter = smart_contracts::OwnedParameter::from_serial(&parameter)
            .map_err(|_| Cis2QueryError::InvalidOperatorOfParams(NewOperatorOfQueryParamsError))?;
        self.view_raw("operatorOf", parameter, bi).await
    }

    /// Like [`operator_of`](Self::operator_of), except for querying a single
    /// `owner`-`address` pair. This additionally ensures that the response
    /// has correct length.
    pub async fn operator_of_single(
        &mut self,
        bi: impl IntoBlockIdentifier,
        owner: Address,
        operator: Address,
    ) -> Result<bool, Cis2QueryError> {
        let res = self
            .operator_of(
                bi,
                vec![OperatorOfQuery {
                    owner,
                    address: operator,
                }],
            )
            .await?;
        only_one(res)
    }

    /// Invoke the CIS2 tokenMetadata query given a list of CIS2 TokenIds.
    ///
    /// Note: the query is executed locally by the node and does not produce a
    /// transaction on-chain.
    ///
    /// # Arguments
    ///
    /// * `bi` - The block to query. The query will be executed in the state of
    ///   the chain at the end of the block.
    /// * `queries` - A list queries to execute.
    pub async fn token_metadata(
        &mut self,
        bi: impl IntoBlockIdentifier,
        queries: Vec<TokenId>,
    ) -> Result<TokenMetadataQueryResponse, Cis2QueryError> {
        let parameter = TokenMetadataQueryParams::new(queries)?;
        let parameter = smart_contracts::OwnedParameter::from_serial(&parameter).map_err(|_| {
            Cis2QueryError::InvalidTokenMetadataParams(NewTokenMetadataQueryParamsError)
        })?;
        self.view_raw("tokenMetadata", parameter, bi).await
    }

    /// Like [`token_metadata`](Self::token_metadata), except for querying a
    /// single token. This additionally ensures that the response has
    /// correct length.
    pub async fn token_metadata_single(
        &mut self,
        bi: impl IntoBlockIdentifier,
        token_id: TokenId,
    ) -> Result<MetadataUrl, Cis2QueryError> {
        let res = self.token_metadata(bi, vec![token_id]).await?;
        only_one(res)
    }
}

/// Extract an element from the given vector if the vector has exactly one
/// element. Otherwise raise a parse error.
fn only_one<A, V: AsRef<Vec<A>>>(res: V) -> Result<A, Cis2QueryError>
where
    Vec<A>: From<V>,
{
    let err = Cis2QueryError::ResponseParseError(concordium_contracts_common::ParseError {});
    if res.as_ref().len() > 1 {
        Err(err)
    } else {
        Vec::from(res).pop().ok_or(err)
    }
}