-
Notifications
You must be signed in to change notification settings - Fork 35
/
cis2_client.rs
686 lines (626 loc) · 25.5 KB
/
cis2_client.rs
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
//! CIS2 client is the intermediatory layer between any contract and
//! CIS2 compliant contract.
//!
//! # Description
//! It allows the contract to abstract away the logic of calling the
//! CIS2 contract for the following methods
//! - `supports_cis2` : Calls [`supports`](https://proposals.concordium.software/CIS/cis-0.html#supports)
//! - `operator_of` : Calls [`operatorOf`](https://proposals.concordium.software/CIS/cis-2.html#operatorof)
//! - `balance_of` : Calls [`balanceOf`](https://proposals.concordium.software/CIS/cis-2.html#balanceof)
//! - `transfer` : Calls [`transfer`](https://proposals.concordium.software/CIS/cis-2.html#transfer)
//! - `update_operator` : Calls [`updateOperator`](https://proposals.concordium.software/CIS/cis-2.html#updateoperator)
use crate::*;
use concordium_std::*;
const SUPPORTS_ENTRYPOINT_NAME: EntrypointName = EntrypointName::new_unchecked("supports");
const OPERATOR_OF_ENTRYPOINT_NAME: EntrypointName = EntrypointName::new_unchecked("operatorOf");
const BALANCE_OF_ENTRYPOINT_NAME: EntrypointName = EntrypointName::new_unchecked("balanceOf");
const TRANSFER_ENTRYPOINT_NAME: EntrypointName = EntrypointName::new_unchecked("transfer");
const UPDATE_OPERATOR_ENTRYPOINT_NAME: EntrypointName =
EntrypointName::new_unchecked("updateOperator");
pub type InvokeContractError<T> = CallContractError<Cis2Error<T>>;
/// Errors which can be returned by the `Cis2Client`.
#[derive(Debug)]
pub enum Cis2ClientError<T> {
/// Invoking the contract returned the given error.
InvokeContractError(InvokeContractError<T>),
/// The response from the contract could not be parsed.
ParseResult,
/// The response was not as expected, for example the response is an empty
/// vector for a single query.
InvalidResponse,
}
impl<T: Serial> Serial for Cis2ClientError<T> {
fn serial<W: Write>(&self, out: &mut W) -> Result<(), W::Err> {
match self {
Cis2ClientError::InvokeContractError(e) => {
out.write_u8(2)?;
match e {
CallContractError::AmountTooLarge => out.write_u8(0),
CallContractError::MissingAccount => out.write_u8(1),
CallContractError::MissingContract => out.write_u8(2),
CallContractError::MissingEntrypoint => out.write_u8(3),
CallContractError::MessageFailed => out.write_u8(4),
CallContractError::LogicReject {
reason,
return_value,
} => {
out.write_u8(5)?;
reason.serial(out)?;
return_value.serial(out)?;
Ok(())
}
CallContractError::Trap => out.write_u8(6),
}
}
Cis2ClientError::ParseResult => out.write_u8(0),
Cis2ClientError::InvalidResponse => out.write_u8(1),
}
}
}
impl<T: Read, R: Deserial> TryFrom<CallContractError<T>> for Cis2ClientError<R> {
type Error = Cis2ClientError<R>;
fn try_from(err: CallContractError<T>) -> Result<Cis2ClientError<R>, Cis2ClientError<R>> {
match err {
CallContractError::AmountTooLarge => {
Ok(Cis2ClientError::InvokeContractError(InvokeContractError::AmountTooLarge))
}
CallContractError::MissingAccount => {
Ok(Cis2ClientError::InvokeContractError(InvokeContractError::MissingAccount))
}
CallContractError::MissingContract => {
Ok(Cis2ClientError::InvokeContractError(InvokeContractError::MissingContract))
}
CallContractError::MissingEntrypoint => {
Ok(Cis2ClientError::InvokeContractError(InvokeContractError::MissingEntrypoint))
}
CallContractError::MessageFailed => {
Ok(Cis2ClientError::InvokeContractError(InvokeContractError::MessageFailed))
}
CallContractError::LogicReject {
reason,
mut return_value,
} => Ok(Cis2ClientError::InvokeContractError(InvokeContractError::LogicReject {
reason,
return_value: Cis2Error::<R>::deserial(&mut return_value)?,
})),
CallContractError::Trap => {
Ok(Cis2ClientError::InvokeContractError(InvokeContractError::Trap))
}
}
}
}
impl<T> From<ParseError> for Cis2ClientError<T> {
fn from(_: ParseError) -> Self { Cis2ClientError::ParseResult }
}
/// Client for interacting with CIS2 compliant contracts.
///
/// ## Examples
/// ```rust
/// use concordium_cis2::Cis2Client;
/// use concordium_std::ContractAddress;
/// let cis_contract_address = ContractAddress::new(0, 0);
/// Cis2Client::new(cis_contract_address);
/// ```
pub struct Cis2Client {
contract: ContractAddress,
}
impl Cis2Client {
pub fn new(contract: ContractAddress) -> Self {
Self {
contract,
}
}
/// Calls the `supports` entrypoint of the CIS2 contract to check if the
/// given contract supports CIS2 standard.
/// If the contract supports CIS2 standard, it returns
/// `Ok(SupportResult::Support)`, else it returns
/// `Ok(SupportResult::NoSupport)`. If the contract supports CIS2
/// standard by another contract, it returns
/// `Ok(SupportResult::SupportBy(Vec<ContractAddress>))`. If there is an
/// error, it returns `Err`.
///
/// # Examples
/// ```rust
/// use concordium_cis2::*;
/// use concordium_std::{test_infrastructure::*, *};
/// let mut host = TestHost::new((), TestStateBuilder::new());
/// host.setup_mock_entrypoint(
/// ContractAddress::new(0, 0),
/// OwnedEntrypointName::new_unchecked("supports".to_string()),
/// MockFn::new_v1(|_, _, _, _| {
/// Ok((false, SupportsQueryResponse {
/// results: vec![SupportResult::Support],
/// }))
/// }),
/// );
///
/// let client = Cis2Client::new(ContractAddress::new(0, 0));
/// let res: Result<SupportResult, Cis2ClientError<()>> = client.supports_cis2(&host);
/// assert!(res.is_ok());
/// match res.unwrap() {
/// SupportResult::NoSupport => fail!(),
/// SupportResult::Support => (),
/// SupportResult::SupportBy(_) => fail!(),
/// }
/// ```
pub fn supports_cis2<State, E: Deserial>(
&self,
host: &impl HasHost<State>,
) -> Result<SupportResult, Cis2ClientError<E>> {
let params = SupportsQueryParams {
queries: vec![CIS2_STANDARD_IDENTIFIER.to_owned()],
};
let mut res: SupportsQueryResponse =
self.invoke_contract_read_only(host, SUPPORTS_ENTRYPOINT_NAME, ¶ms)?;
let res = res.results.pop().ok_or(Cis2ClientError::InvalidResponse)?;
Ok(res)
}
/// Calls the `operatorOf` entrypoint of the CIS2 contract to check if the
/// given owner is an operator of the given contract. If the owner is an
/// operator of the given contract, it returns `Ok(true)`,
/// else it returns `Ok(false)`.
/// If there is an error, it returns `Err`.
///
/// # Examples
/// ```rust
/// use concordium_cis2::*;
/// use concordium_std::{test_infrastructure::*, *};
///
/// let mut host = TestHost::new((), TestStateBuilder::new());
/// host.setup_mock_entrypoint(
/// ContractAddress::new(0, 0),
/// OwnedEntrypointName::new_unchecked("operatorOf".to_string()),
/// MockFn::new_v1(|_, _, _, _| {
/// Ok((false, OperatorOfQueryResponse {
/// 0: vec![true],
/// }))
/// }),
/// );
///
/// let client = Cis2Client::new(ContractAddress::new(0, 0));
/// let res: Result<bool, Cis2ClientError<()>> = client.operator_of(
/// &mut host,
/// Address::Account(AccountAddress([1; 32])),
/// Address::Contract(ContractAddress::new(1, 0)),
/// );
///
/// assert_eq!(res.unwrap(), true);
/// ```
pub fn operator_of<State, E: Deserial>(
&self,
host: &impl HasHost<State>,
owner: Address,
address: Address,
) -> Result<bool, Cis2ClientError<E>> {
let params = &OperatorOfQueryParams {
queries: vec![OperatorOfQuery {
owner,
address,
}],
};
let mut res: OperatorOfQueryResponse =
self.invoke_contract_read_only(host, OPERATOR_OF_ENTRYPOINT_NAME, params)?;
let res = res.0.pop().ok_or(Cis2ClientError::InvalidResponse)?;
Ok(res)
}
/// Calls the `balanceOf` entrypoint of the CIS2 contract to get the balance
/// of the given owner for the given token. If the balance is returned,
/// it returns `Ok(balance)`, else it returns `Err`.
/// # Examples
/// ```rust
/// use concordium_cis2::*;
/// use concordium_std::{test_infrastructure::*, *};
/// let mut host = TestHost::new((), TestStateBuilder::new());
/// host.setup_mock_entrypoint(
/// ContractAddress::new(0, 0),
/// OwnedEntrypointName::new_unchecked("balanceOf".to_string()),
/// MockFn::new_v1(|_, _, _, _| {
/// Ok((false, BalanceOfQueryResponse::<TokenAmountU8>(vec![1.into()])))
/// }),
/// );
///
/// let client = Cis2Client::new(ContractAddress::new(0, 0));
/// let res: Result<TokenAmountU8, Cis2ClientError<()>> =
/// client.balance_of(&host, TokenIdU8(1), Address::Account(AccountAddress([1; 32])));
/// assert!(res.is_ok());
/// assert_eq!(res.unwrap(), 1.into());
/// ```
pub fn balance_of<State, T: IsTokenId, A: IsTokenAmount, E: Deserial>(
&self,
host: &impl HasHost<State>,
token_id: T,
address: Address,
) -> Result<A, Cis2ClientError<E>> {
let params = BalanceOfQueryParams {
queries: vec![BalanceOfQuery {
token_id,
address,
}],
};
let mut res: BalanceOfQueryResponse<A> =
self.invoke_contract_read_only(host, BALANCE_OF_ENTRYPOINT_NAME, ¶ms)?;
let res = res.0.pop().ok_or(Cis2ClientError::InvalidResponse)?;
Ok(res)
}
/// Calls the `transfer` entrypoint of the CIS2 contract to transfer the
/// given amount of tokens from the given owner to the given receiver.
/// If the transfer is successful and the state is modified, it returns
/// `Ok(true)`, else it returns `Ok(false)`. If there is an error, it
/// returns `Err`.
///
/// # Examples
/// ```rust
/// use concordium_cis2::*;
/// use concordium_std::{test_infrastructure::*, *};
/// let mut host = TestHost::new((), TestStateBuilder::new());
/// host.setup_mock_entrypoint(
/// ContractAddress::new(0, 0),
/// OwnedEntrypointName::new_unchecked("transfer".to_string()),
/// MockFn::new_v1(|_, _, _, _| Ok((false, ()))),
/// );
///
/// let client = Cis2Client::new(ContractAddress::new(0, 0));
/// let res: Result<bool, Cis2ClientError<()>> = client.transfer(&mut host, Transfer {
/// amount: TokenAmountU8(1),
/// from: Address::Account(AccountAddress([1; 32])),
/// to: Receiver::Account(AccountAddress([2; 32])),
/// token_id: TokenIdU8(1),
/// data: AdditionalData::empty(),
/// });
///
/// assert!(res.is_ok());
/// ```
pub fn transfer<State, T: IsTokenId, A: IsTokenAmount, E: Deserial>(
&self,
host: &mut impl HasHost<State>,
transfer: Transfer<T, A>,
) -> Result<bool, Cis2ClientError<E>> {
let params = TransferParams(vec![transfer]);
let (state_modified, _): (bool, Option<()>) =
self.invoke_contract(host, TRANSFER_ENTRYPOINT_NAME, ¶ms)?;
Ok(state_modified)
}
/// Calls the `updateOperator` of the CIS2 contract.
/// If the update is successful and the state is modified, it returns
/// `Ok(true)`, else it returns `Ok(false)`. If there is an error, it
/// returns `Err`.
///
/// # Examples
/// ```rust
/// use concordium_cis2::*;
/// use concordium_std::{test_infrastructure::*, *};
/// let mut host = TestHost::new((), TestStateBuilder::new());
/// host.setup_mock_entrypoint(
/// ContractAddress::new(0, 0),
/// OwnedEntrypointName::new_unchecked("updateOperator".to_string()),
/// MockFn::new_v1(|_, _, _, _| Ok((false, ()))),
/// );
///
/// let client = Cis2Client::new(ContractAddress::new(0, 0));
/// let res: Result<bool, Cis2ClientError<()>> = client.update_operator(
/// &mut host,
/// Address::Account(AccountAddress([1; 32])),
/// OperatorUpdate::Add,
/// );
///
/// assert!(res.is_ok());
/// ```
pub fn update_operator<State, E: Deserial>(
&self,
host: &mut impl HasHost<State>,
operator: Address,
update: OperatorUpdate,
) -> Result<bool, Cis2ClientError<E>> {
let params = UpdateOperator {
operator,
update,
};
let (state_modified, _): (bool, Option<()>) =
self.invoke_contract(host, UPDATE_OPERATOR_ENTRYPOINT_NAME, ¶ms)?;
Ok(state_modified)
}
fn invoke_contract_read_only<State, P: Serial, R: Deserial, E: Deserial>(
&self,
host: &impl HasHost<State>,
method: EntrypointName,
parameter: &P,
) -> Result<R, Cis2ClientError<E>> {
let res =
host.invoke_contract_read_only(&self.contract, parameter, method, Amount::from_ccd(0));
let res = match res {
Ok(val) => val,
Err(err) => return Err(Cis2ClientError::<E>::try_from(err)?),
};
let res = match res {
// Since the contract should return a response. If it doesn't, it is an error.
Some(mut res) => R::deserial(&mut res)?,
None => bail!(Cis2ClientError::InvalidResponse),
};
Ok(res)
}
fn invoke_contract<State, P: Serial, R: Deserial, E: Deserial>(
&self,
host: &mut impl HasHost<State>,
method: EntrypointName,
parameter: &P,
) -> Result<(bool, Option<R>), Cis2ClientError<E>> {
let res = host.invoke_contract(&self.contract, parameter, method, Amount::from_ccd(0));
let res = match res {
Ok(val) => {
let o = match val.1 {
Some(mut res) => Some(R::deserial(&mut res)?),
None => None,
};
(val.0, o)
}
Err(err) => return Err(Cis2ClientError::<E>::try_from(err)?),
};
Ok(res)
}
}
#[cfg(test)]
mod test {
use crate::*;
use concordium_std::test_infrastructure::*;
const INDEX: u64 = 0;
const SUBINDEX: u64 = 0;
type ContractTokenId = TokenIdU8;
type ContractTokenAmount = TokenAmountU8;
#[test]
fn supports_cis2_test() {
let mut host = TestHost::new((), TestStateBuilder::new());
fn mock_supports(
parameter: Parameter,
_a: Amount,
_a2: &mut Amount,
_s: &mut (),
) -> Result<(bool, SupportsQueryResponse), CallContractError<SupportsQueryResponse>>
{
// Check that parameters are deserialized correctly.
let mut cursor = Cursor::new(parameter);
let params: Result<SupportsQueryParams, ParseError> =
SupportsQueryParams::deserial(&mut cursor);
assert!(params.is_ok());
let params = params.unwrap();
assert_eq!(
params.queries[0],
StandardIdentifierOwned::new_unchecked("CIS-2".to_owned())
);
// Return a response with support.
Ok((false, SupportsQueryResponse {
results: vec![SupportResult::Support],
}))
}
let cis_contract_address = ContractAddress::new(INDEX, SUBINDEX);
host.setup_mock_entrypoint(
cis_contract_address,
OwnedEntrypointName::new_unchecked("supports".to_string()),
MockFn::new_v1(mock_supports),
);
let client = Cis2Client::new(cis_contract_address);
let res: Result<SupportResult, Cis2ClientError<()>> = client.supports_cis2(&host);
assert!(res.is_ok());
match res.unwrap() {
SupportResult::NoSupport => fail!(),
SupportResult::Support => (),
SupportResult::SupportBy(_) => fail!(),
}
}
#[test]
fn supports_cis2_test_no_support() {
let mut host = TestHost::new((), TestStateBuilder::new());
let cis_contract_address = ContractAddress::new(INDEX, SUBINDEX);
fn mock_supports(
_p: Parameter,
_a: Amount,
_a2: &mut Amount,
_s: &mut (),
) -> Result<(bool, SupportsQueryResponse), CallContractError<SupportsQueryResponse>>
{
Ok((false, SupportsQueryResponse {
results: vec![SupportResult::NoSupport],
}))
}
host.setup_mock_entrypoint(
cis_contract_address,
OwnedEntrypointName::new_unchecked("supports".to_string()),
MockFn::new_v1(mock_supports),
);
let client = Cis2Client::new(cis_contract_address);
let res: Result<SupportResult, Cis2ClientError<()>> = client.supports_cis2(&host);
assert!(res.is_ok());
match res.unwrap() {
SupportResult::NoSupport => (),
SupportResult::Support => fail!(),
SupportResult::SupportBy(_) => fail!(),
}
}
#[test]
fn supports_cis2_test_supported_by_other_contract() {
let mut host = TestHost::new((), TestStateBuilder::new());
let cis_contract_address = ContractAddress::new(INDEX, SUBINDEX);
fn mock_supports(
_p: Parameter,
_a: Amount,
_a2: &mut Amount,
_s: &mut (),
) -> Result<(bool, SupportsQueryResponse), CallContractError<SupportsQueryResponse>>
{
Ok((false, SupportsQueryResponse {
results: vec![SupportResult::SupportBy(vec![ContractAddress::new(
INDEX,
SUBINDEX + 1,
)])],
}))
}
host.setup_mock_entrypoint(
cis_contract_address,
OwnedEntrypointName::new_unchecked("supports".to_string()),
MockFn::new_v1(mock_supports),
);
let client = Cis2Client::new(cis_contract_address);
let res: Result<SupportResult, Cis2ClientError<()>> = client.supports_cis2(&host);
match res.unwrap() {
SupportResult::NoSupport => fail!(),
SupportResult::Support => fail!(),
SupportResult::SupportBy(addresses) => {
assert_eq!(addresses.first(), Some(&ContractAddress::new(INDEX, SUBINDEX + 1)))
}
}
}
#[test]
fn operator_of_test() {
let mut host = TestHost::new((), TestStateBuilder::new());
let cis_contract_address = ContractAddress::new(INDEX, SUBINDEX);
let owner = Address::Account(AccountAddress([1; 32]));
let current_contract_address = Address::Contract(ContractAddress::new(INDEX + 1, SUBINDEX));
fn mock_operator_of(
parameter: Parameter,
_a: Amount,
_a2: &mut Amount,
_s: &mut (),
) -> Result<(bool, OperatorOfQueryResponse), CallContractError<OperatorOfQueryResponse>>
{
// Check that parameters are deserialized correctly.
let mut cursor = Cursor::new(parameter);
let params: Result<OperatorOfQueryParams, ParseError> =
OperatorOfQueryParams::deserial(&mut cursor);
match params {
Ok(params) => {
assert_eq!(
params.queries[0].address,
Address::Contract(ContractAddress::new(INDEX + 1, SUBINDEX))
);
assert_eq!(params.queries[0].owner, Address::Account(AccountAddress([1; 32])));
}
Err(_) => fail!(),
};
// Return a response with operator true.
Ok((false, OperatorOfQueryResponse {
0: vec![true],
}))
}
host.setup_mock_entrypoint(
cis_contract_address,
OwnedEntrypointName::new_unchecked("operatorOf".to_string()),
MockFn::new_v1(mock_operator_of),
);
let client = Cis2Client::new(cis_contract_address);
let res: Result<bool, Cis2ClientError<()>> =
client.operator_of(&mut host, owner, current_contract_address);
assert_eq!(res.unwrap(), true);
}
#[test]
fn balance_of_test() {
let mut host = TestHost::new((), TestStateBuilder::new());
let cis_contract_address = ContractAddress::new(INDEX, SUBINDEX);
let owner = Address::Account(AccountAddress([1; 32]));
fn mock_balance_of(
parameter: Parameter,
_a: Amount,
_a2: &mut Amount,
_s: &mut (),
) -> Result<
(bool, BalanceOfQueryResponse<ContractTokenAmount>),
CallContractError<BalanceOfQueryResponse<ContractTokenAmount>>,
> {
// Check that parameters are deserialized correctly.
let mut cursor = Cursor::new(parameter);
let params: Result<BalanceOfQueryParams<ContractTokenId>, ParseError> =
BalanceOfQueryParams::deserial(&mut cursor);
assert!(params.is_ok());
let params = params.unwrap();
assert_eq!(params.queries[0].token_id, TokenIdU8(1));
assert_eq!(params.queries[0].address, Address::Account(AccountAddress([1; 32])));
// Return a balance of 1.
Ok((false, BalanceOfQueryResponse(vec![1.into()])))
}
host.setup_mock_entrypoint(
cis_contract_address,
OwnedEntrypointName::new_unchecked("balanceOf".to_string()),
MockFn::new_v1(mock_balance_of),
);
let client = Cis2Client::new(cis_contract_address);
let res: Result<TokenAmountU8, Cis2ClientError<()>> =
client.balance_of(&host, TokenIdU8(1), owner);
assert!(res.is_ok());
let res: ContractTokenAmount = res.unwrap();
assert_eq!(res, 1.into());
}
#[test]
fn transfer_test() {
let mut host = TestHost::new((), TestStateBuilder::new());
let cis_contract_address = ContractAddress::new(INDEX, SUBINDEX);
let from = Address::Account(AccountAddress([1; 32]));
let to_account = AccountAddress([2; 32]);
let amount: ContractTokenAmount = 1.into();
fn mock_transfer(
parameter: Parameter,
_a: Amount,
_a2: &mut Amount,
_s: &mut (),
) -> Result<(bool, ()), CallContractError<()>> {
// Check that parameters are deserialized correctly.
let mut cursor = Cursor::new(parameter);
let params: Result<TransferParams<ContractTokenId, ContractTokenAmount>, ParseError> =
TransferParams::deserial(&mut cursor);
assert!(params.is_ok());
let params = params.unwrap();
assert_eq!(params.0[0].token_id, TokenIdU8(1));
assert_eq!(params.0[0].to.address(), Address::Account(AccountAddress([2; 32])));
assert_eq!(params.0[0].amount, 1.into());
// Return a successful transfer.
Ok((false, ()))
}
host.setup_mock_entrypoint(
cis_contract_address,
OwnedEntrypointName::new_unchecked("transfer".to_string()),
MockFn::new_v1(mock_transfer),
);
let client = Cis2Client::new(cis_contract_address);
let res: Result<bool, Cis2ClientError<()>> = client.transfer(&mut host, Transfer {
amount,
from,
to: Receiver::Account(to_account),
token_id: TokenIdU8(1),
data: AdditionalData::empty(),
});
assert!(res.is_ok());
}
#[test]
fn update_operator_test() {
fn mock_update_operator(
parameter: Parameter,
_a: Amount,
_a2: &mut Amount,
_s: &mut (),
) -> Result<(bool, ()), CallContractError<()>> {
// Check that parameters are deserialized correctly.
let mut cursor = Cursor::new(parameter);
let params: Result<UpdateOperator, ParseError> = UpdateOperator::deserial(&mut cursor);
assert!(params.is_ok());
let params = params.unwrap();
assert_eq!(params.operator, Address::Account(AccountAddress([1; 32])));
match params.update {
OperatorUpdate::Add => (),
OperatorUpdate::Remove => fail!(),
}
// Return a successful update.
Ok((false, ()))
}
let mut host = TestHost::new((), TestStateBuilder::new());
let cis_contract_address = ContractAddress::new(INDEX, SUBINDEX);
host.setup_mock_entrypoint(
cis_contract_address,
OwnedEntrypointName::new_unchecked("updateOperator".to_string()),
MockFn::new_v1(mock_update_operator),
);
let client = Cis2Client::new(cis_contract_address);
let res: Result<bool, Cis2ClientError<()>> = client.update_operator(
&mut host,
Address::Account(AccountAddress([1; 32])),
OperatorUpdate::Add,
);
assert!(res.is_ok());
}
}