-
Notifications
You must be signed in to change notification settings - Fork 12
/
lib.rs
executable file
·891 lines (787 loc) · 35.5 KB
/
lib.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
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
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
#![cfg_attr(not(feature = "std"), no_std, no_main)]
#[openbrush::implementation(Ownable, AccessControl)]
#[openbrush::contract]
pub mod test_oracle {
use ink::codegen::{EmitEvent, Env};
use ink::prelude::string::String;
use ink::prelude::vec::Vec;
use ink::storage::Mapping;
use openbrush::contracts::access_control::*;
use openbrush::contracts::ownable::*;
use openbrush::traits::Storage;
use scale::{Decode, Encode};
use phat_rollup_anchor_ink::traits::{
meta_transaction, meta_transaction::*, rollup_anchor, rollup_anchor::*,
};
pub type TradingPairId = u32;
pub const MANAGER_ROLE: RoleType = ink::selector_id!("MANAGER_ROLE");
/// Events emitted when a price is received
#[ink(event)]
pub struct PriceReceived {
trading_pair_id: TradingPairId,
price: u128,
}
/// Events emitted when a error is received
#[ink(event)]
pub struct ErrorReceived {
trading_pair_id: TradingPairId,
err_no: u128,
}
/// Errors occurred in the contract
#[derive(Encode, Decode, Debug)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum ContractError {
AccessControlError(AccessControlError),
RollupAnchorError(RollupAnchorError),
MetaTransactionError(MetaTransactionError),
MissingTradingPair,
}
/// convertor from MessageQueueError to ContractError
impl From<AccessControlError> for ContractError {
fn from(error: AccessControlError) -> Self {
ContractError::AccessControlError(error)
}
}
/// convertor from RollupAnchorError to ContractError
impl From<RollupAnchorError> for ContractError {
fn from(error: RollupAnchorError) -> Self {
ContractError::RollupAnchorError(error)
}
}
/// convertor from MetaTxError to ContractError
impl From<MetaTransactionError> for ContractError {
fn from(error: MetaTransactionError) -> Self {
ContractError::MetaTransactionError(error)
}
}
/// Message to request the price of the trading pair
/// message pushed in the queue by this contract and read by the offchain rollup
#[derive(Encode, Decode)]
struct PriceRequestMessage {
/// id of the pair (use as key in the Mapping)
trading_pair_id: TradingPairId,
/// trading pair like 'polkdatot/usd'
/// Note: it will be better to not save this data in the storage
token0: String,
token1: String,
}
/// Message sent to provide the price of the trading pair
/// response pushed in the queue by the offchain rollup and read by this contract
#[derive(Encode, Decode)]
struct PriceResponseMessage {
/// Type of response
resp_type: u8,
/// id of the pair
trading_pair_id: TradingPairId,
/// price of the trading pair
price: Option<u128>,
/// error when the price is read
err_no: Option<u128>,
}
/// Type of response when the offchain rollup communicates with this contract
const TYPE_ERROR: u8 = 0;
const TYPE_RESPONSE: u8 = 10;
const TYPE_FEED: u8 = 11;
/// Data storage
#[derive(Encode, Decode, Default, Eq, PartialEq, Clone, Debug)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub struct TradingPair {
/// trading pair like 'polkdatot/usd'
/// Note: it will be better to not save this data outside of the storage
token0: String,
token1: String,
/// value of the trading pair
value: u128,
/// number of updates of the value
nb_updates: u16,
/// when the last value has been updated
last_update: u64,
}
#[ink(storage)]
#[derive(Default, Storage)]
pub struct TestOracle {
#[storage_field]
ownable: ownable::Data,
#[storage_field]
access: access_control::Data,
#[storage_field]
rollup_anchor: rollup_anchor::Data,
#[storage_field]
meta_transaction: meta_transaction::Data,
trading_pairs: Mapping<TradingPairId, TradingPair>,
}
impl TestOracle {
#[ink(constructor)]
pub fn new() -> Self {
let mut instance = Self::default();
let caller = instance.env().caller();
// set the owner of this contract
ownable::Internal::_init_with_owner(&mut instance, caller);
// set the admin of this contract
access_control::Internal::_init_with_admin(&mut instance, Some(caller));
// grant the role manager
AccessControl::grant_role(&mut instance, MANAGER_ROLE, Some(caller))
.expect("Should grant the role MANAGER_ROLE");
instance
}
#[ink(message)]
#[openbrush::modifiers(access_control::only_role(MANAGER_ROLE))]
pub fn create_trading_pair(
&mut self,
trading_pair_id: TradingPairId,
token0: String,
token1: String,
) -> Result<(), ContractError> {
// we create a new trading pair or override an existing one
let trading_pair = TradingPair {
token0,
token1,
value: 0,
nb_updates: 0,
last_update: 0,
};
self.trading_pairs.insert(trading_pair_id, &trading_pair);
Ok(())
}
#[ink(message)]
#[openbrush::modifiers(access_control::only_role(MANAGER_ROLE))]
pub fn request_price(
&mut self,
trading_pair_id: TradingPairId,
) -> Result<QueueIndex, ContractError> {
let index = match self.trading_pairs.get(trading_pair_id) {
Some(t) => {
// push the message in the queue
let message = PriceRequestMessage {
trading_pair_id,
token0: t.token0,
token1: t.token1,
};
self.push_message(&message)?
}
_ => return Err(ContractError::MissingTradingPair),
};
Ok(index)
}
#[ink(message)]
pub fn get_trading_pair(&self, trading_pair_id: TradingPairId) -> Option<TradingPair> {
self.trading_pairs.get(trading_pair_id)
}
#[ink(message)]
pub fn register_attestor(&mut self, account_id: AccountId) -> Result<(), ContractError> {
AccessControl::grant_role(self, ATTESTOR_ROLE, Some(account_id))?;
Ok(())
}
#[ink(message)]
pub fn get_attestor_role(&self) -> RoleType {
ATTESTOR_ROLE
}
#[ink(message)]
pub fn get_manager_role(&self) -> RoleType {
MANAGER_ROLE
}
}
impl RollupAnchor for TestOracle {}
impl MetaTransaction for TestOracle {}
impl rollup_anchor::MessageHandler for TestOracle {
fn on_message_received(&mut self, action: Vec<u8>) -> Result<(), RollupAnchorError> {
// parse the response
let message: PriceResponseMessage =
Decode::decode(&mut &action[..]).or(Err(RollupAnchorError::FailedToDecode))?;
// handle the response
if message.resp_type == TYPE_RESPONSE || message.resp_type == TYPE_FEED {
// we received the price
// register the info
let mut trading_pair = self
.trading_pairs
.get(message.trading_pair_id)
.unwrap_or_default();
trading_pair.value = message.price.unwrap_or_default();
trading_pair.nb_updates += 1;
trading_pair.last_update = self.env().block_timestamp();
self.trading_pairs
.insert(message.trading_pair_id, &trading_pair);
// emmit te event
self.env().emit_event(PriceReceived {
trading_pair_id: message.trading_pair_id,
price: message.price.unwrap_or_default(),
});
} else if message.resp_type == TYPE_ERROR {
// we received an error
self.env().emit_event(ErrorReceived {
trading_pair_id: message.trading_pair_id,
err_no: message.err_no.unwrap_or_default(),
});
} else {
// response type unknown
return Err(RollupAnchorError::UnsupportedAction);
}
Ok(())
}
}
/// Events emitted when a message is pushed in the queue
#[ink(event)]
pub struct MessageQueued {
pub id: u32,
pub data: Vec<u8>,
}
/// Events emitted when a message is proceed
#[ink(event)]
pub struct MessageProcessedTo {
pub id: u32,
}
impl rollup_anchor::EventBroadcaster for TestOracle {
fn emit_event_message_queued(&self, id: u32, data: Vec<u8>) {
self.env().emit_event(MessageQueued { id, data });
}
fn emit_event_message_processed_to(&self, id: u32) {
self.env().emit_event(MessageProcessedTo { id });
}
}
impl meta_transaction::EventBroadcaster for TestOracle {
fn emit_event_meta_tx_decoded(&self) {
self.env().emit_event(MetaTxDecoded {});
}
}
/// Events emitted when a meta transaction is decoded
#[ink(event)]
pub struct MetaTxDecoded {}
#[cfg(all(test, feature = "e2e-tests"))]
mod e2e_tests {
use super::*;
use openbrush::contracts::access_control::accesscontrol_external::AccessControl;
use ink_e2e::subxt::tx::Signer;
use ink_e2e::{build_message, PolkadotConfig};
use phat_rollup_anchor_ink::traits::{
meta_transaction::metatransaction_external::MetaTransaction,
rollup_anchor::rollupanchor_external::RollupAnchor,
};
type E2EResult<T> = std::result::Result<T, Box<dyn std::error::Error>>;
#[ink_e2e::test]
async fn test_create_trading_pair(mut client: ink_e2e::Client<C, E>) -> E2EResult<()> {
// given
let constructor = TestOracleRef::new();
let contract_acc_id = client
.instantiate("test_oracle", &ink_e2e::alice(), constructor, 0, None)
.await
.expect("instantiate failed")
.account_id;
let trading_pair_id = 10;
// read the trading pair and check it doesn't exist yet
let get_trading_pair = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.get_trading_pair(trading_pair_id));
let get_res = client
.call_dry_run(&ink_e2e::bob(), &get_trading_pair, 0, None)
.await;
assert_eq!(None, get_res.return_value());
// bob is not granted as manager => it should not be able to create the trading pair
let create_trading_pair =
build_message::<TestOracleRef>(contract_acc_id.clone()).call(|oracle| {
oracle.create_trading_pair(
trading_pair_id,
String::from("polkadot"),
String::from("usd"),
)
});
let result = client
.call(&ink_e2e::bob(), create_trading_pair, 0, None)
.await;
assert!(
result.is_err(),
"only manager should not be able to create trading pair"
);
// bob is granted as manager
let bob_address = ink::primitives::AccountId::from(
Signer::<PolkadotConfig>::account_id(&ink_e2e::bob()).0,
);
let grant_role = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.grant_role(MANAGER_ROLE, Some(bob_address)));
client
.call(&ink_e2e::alice(), grant_role, 0, None)
.await
.expect("grant bob as attestor failed");
// create the trading pair
let create_trading_pair =
build_message::<TestOracleRef>(contract_acc_id.clone()).call(|oracle| {
oracle.create_trading_pair(
trading_pair_id,
String::from("polkadot"),
String::from("usd"),
)
});
client
.call(&ink_e2e::bob(), create_trading_pair, 0, None)
.await
.expect("create trading pair failed");
// then check if the trading pair exists
let get_trading_pair = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.get_trading_pair(trading_pair_id));
let get_res = client
.call_dry_run(&ink_e2e::bob(), &get_trading_pair, 0, None)
.await;
let expected_trading_pair = TradingPair {
token0: String::from("polkadot"),
token1: String::from("usd"),
value: 0,
nb_updates: 0,
last_update: 0,
};
assert_eq!(Some(expected_trading_pair), get_res.return_value());
Ok(())
}
#[ink_e2e::test]
async fn test_feed_price(mut client: ink_e2e::Client<C, E>) -> E2EResult<()> {
// given
let constructor = TestOracleRef::new();
let contract_acc_id = client
.instantiate("test_oracle", &ink_e2e::alice(), constructor, 0, None)
.await
.expect("instantiate failed")
.account_id;
let trading_pair_id = 10;
// create the trading pair
let create_trading_pair =
build_message::<TestOracleRef>(contract_acc_id.clone()).call(|oracle| {
oracle.create_trading_pair(
trading_pair_id,
String::from("polkadot"),
String::from("usd"),
)
});
client
.call(&ink_e2e::alice(), create_trading_pair, 0, None)
.await
.expect("create trading pair failed");
// bob is granted as attestor
let bob_address = ink::primitives::AccountId::from(
Signer::<PolkadotConfig>::account_id(&ink_e2e::bob()).0,
);
let grant_role = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.grant_role(ATTESTOR_ROLE, Some(bob_address)));
client
.call(&ink_e2e::alice(), grant_role, 0, None)
.await
.expect("grant bob as attestor failed");
// then bob feeds the price
let value: u128 = 150_000_000_000_000_000_000;
let payload = PriceResponseMessage {
resp_type: TYPE_FEED,
trading_pair_id,
price: Some(value),
err_no: None,
};
let actions = vec![HandleActionInput::Reply(payload.encode())];
let rollup_cond_eq = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.rollup_cond_eq(vec![], vec![], actions.clone()));
let result = client
.call(&ink_e2e::bob(), rollup_cond_eq, 0, None)
.await
.expect("rollup cond eq failed");
// events PriceReceived
assert!(result.contains_event("Contracts", "ContractEmitted"));
// and check if the price is filled
let get_trading_pair = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.get_trading_pair(trading_pair_id));
let get_res = client
.call_dry_run(&ink_e2e::bob(), &get_trading_pair, 0, None)
.await;
let trading_pair = get_res.return_value().expect("Trading pair not found");
assert_eq!(value, trading_pair.value);
assert_eq!(1, trading_pair.nb_updates);
assert_ne!(0, trading_pair.last_update);
Ok(())
}
#[ink_e2e::test]
async fn test_receive_reply(mut client: ink_e2e::Client<C, E>) -> E2EResult<()> {
// given
let constructor = TestOracleRef::new();
let contract_acc_id = client
.instantiate("test_oracle", &ink_e2e::alice(), constructor, 0, None)
.await
.expect("instantiate failed")
.account_id;
let trading_pair_id = 10;
// create the trading pair
let create_trading_pair =
build_message::<TestOracleRef>(contract_acc_id.clone()).call(|oracle| {
oracle.create_trading_pair(
trading_pair_id,
String::from("polkadot"),
String::from("usd"),
)
});
client
.call(&ink_e2e::alice(), create_trading_pair, 0, None)
.await
.expect("create trading pair failed");
// bob is granted as attestor
let bob_address = ink::primitives::AccountId::from(
Signer::<PolkadotConfig>::account_id(&ink_e2e::bob()).0,
);
let grant_role = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.grant_role(ATTESTOR_ROLE, Some(bob_address)));
client
.call(&ink_e2e::alice(), grant_role, 0, None)
.await
.expect("grant bob as attestor failed");
// a price request is sent
let request_price = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.request_price(trading_pair_id));
let result = client
.call(&ink_e2e::alice(), request_price, 0, None)
.await
.expect("Request price should be sent");
// event MessageQueued
assert!(result.contains_event("Contracts", "ContractEmitted"));
let request_id = result.return_value().expect("Request id not found");
// then a response is received
let value: u128 = 150_000_000_000_000_000_000;
let payload = PriceResponseMessage {
resp_type: TYPE_RESPONSE,
trading_pair_id,
price: Some(value),
err_no: None,
};
let actions = vec![
HandleActionInput::Reply(payload.encode()),
HandleActionInput::SetQueueHead(request_id + 1),
];
let rollup_cond_eq = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.rollup_cond_eq(vec![], vec![], actions.clone()));
let result = client
.call(&ink_e2e::bob(), rollup_cond_eq, 0, None)
.await
.expect("rollup cond eq should be ok");
// two events : MessageProcessedTo and PricesRecieved
assert!(result.contains_event("Contracts", "ContractEmitted"));
// and check if the price is filled
let get_trading_pair = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.get_trading_pair(trading_pair_id));
let get_res = client
.call_dry_run(&ink_e2e::bob(), &get_trading_pair, 0, None)
.await;
let trading_pair = get_res.return_value().expect("Trading pair not found");
assert_eq!(value, trading_pair.value);
assert_eq!(1, trading_pair.nb_updates);
assert_ne!(0, trading_pair.last_update);
// reply in the future should fail
let actions = vec![
HandleActionInput::Reply(payload.encode()),
HandleActionInput::SetQueueHead(request_id + 2),
];
let rollup_cond_eq = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.rollup_cond_eq(vec![], vec![], actions.clone()));
let result = client.call(&ink_e2e::bob(), rollup_cond_eq, 0, None).await;
assert!(
result.is_err(),
"Rollup should fail because we try to pop in the future"
);
// reply in the past should fail
let actions = vec![
HandleActionInput::Reply(payload.encode()),
HandleActionInput::SetQueueHead(request_id),
];
let rollup_cond_eq = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.rollup_cond_eq(vec![], vec![], actions.clone()));
let result = client.call(&ink_e2e::bob(), rollup_cond_eq, 0, None).await;
assert!(
result.is_err(),
"Rollup should fail because we try to pop in the past"
);
Ok(())
}
#[ink_e2e::test]
async fn test_receive_error(mut client: ink_e2e::Client<C, E>) -> E2EResult<()> {
// given
let constructor = TestOracleRef::new();
let contract_acc_id = client
.instantiate("test_oracle", &ink_e2e::alice(), constructor, 0, None)
.await
.expect("instantiate failed")
.account_id;
let trading_pair_id = 10;
// create the trading pair
let create_trading_pair =
build_message::<TestOracleRef>(contract_acc_id.clone()).call(|oracle| {
oracle.create_trading_pair(
trading_pair_id,
String::from("polkadot"),
String::from("usd"),
)
});
client
.call(&ink_e2e::alice(), create_trading_pair, 0, None)
.await
.expect("create trading pair failed");
// bob is granted as attestor
let bob_address = ink::primitives::AccountId::from(
Signer::<PolkadotConfig>::account_id(&ink_e2e::bob()).0,
);
let grant_role = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.grant_role(ATTESTOR_ROLE, Some(bob_address)));
client
.call(&ink_e2e::alice(), grant_role, 0, None)
.await
.expect("grant bob as attestor failed");
// a price request is sent
let request_price = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.request_price(trading_pair_id));
let result = client
.call(&ink_e2e::alice(), request_price, 0, None)
.await
.expect("Request price should be sent");
// event : MessageQueued
assert!(result.contains_event("Contracts", "ContractEmitted"));
let request_id = result.return_value().expect("Request id not found");
// then a response is received
let payload = PriceResponseMessage {
resp_type: TYPE_ERROR,
trading_pair_id,
price: None,
err_no: Some(12356),
};
let actions = vec![
HandleActionInput::Reply(payload.encode()),
HandleActionInput::SetQueueHead(request_id + 1),
];
let rollup_cond_eq = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.rollup_cond_eq(vec![], vec![], actions.clone()));
let result = client
.call(&ink_e2e::bob(), rollup_cond_eq, 0, None)
.await
.expect("we should proceed error message");
// two events : MessageProcessedTo and PricesReceived
assert!(result.contains_event("Contracts", "ContractEmitted"));
Ok(())
}
#[ink_e2e::test]
async fn test_bad_attestor(mut client: ink_e2e::Client<C, E>) -> E2EResult<()> {
// given
let constructor = TestOracleRef::new();
let contract_acc_id = client
.instantiate("test_oracle", &ink_e2e::alice(), constructor, 0, None)
.await
.expect("instantiate failed")
.account_id;
// bob is not granted as attestor => it should not be able to send a message
let rollup_cond_eq = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.rollup_cond_eq(vec![], vec![], vec![]));
let result = client.call(&ink_e2e::bob(), rollup_cond_eq, 0, None).await;
assert!(
result.is_err(),
"only attestor should be able to send messages"
);
// bob is granted as attestor
let bob_address = ink::primitives::AccountId::from(
Signer::<PolkadotConfig>::account_id(&ink_e2e::bob()).0,
);
let grant_role = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.grant_role(ATTESTOR_ROLE, Some(bob_address)));
client
.call(&ink_e2e::alice(), grant_role, 0, None)
.await
.expect("grant bob as attestor failed");
// then bob is abel to send a message
let rollup_cond_eq = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.rollup_cond_eq(vec![], vec![], vec![]));
let result = client
.call(&ink_e2e::bob(), rollup_cond_eq, 0, None)
.await
.expect("rollup cond eq failed");
// no event
assert!(!result.contains_event("Contracts", "ContractEmitted"));
Ok(())
}
#[ink_e2e::test]
async fn test_bad_messages(mut client: ink_e2e::Client<C, E>) -> E2EResult<()> {
// given
let constructor = TestOracleRef::new();
let contract_acc_id = client
.instantiate("test_oracle", &ink_e2e::alice(), constructor, 0, None)
.await
.expect("instantiate failed")
.account_id;
let trading_pair_id = 10;
// create the trading pair
let create_trading_pair =
build_message::<TestOracleRef>(contract_acc_id.clone()).call(|oracle| {
oracle.create_trading_pair(
trading_pair_id,
String::from("polkadot"),
String::from("usd"),
)
});
client
.call(&ink_e2e::alice(), create_trading_pair, 0, None)
.await
.expect("create trading pair failed");
// bob is granted as attestor
let bob_address = ink::primitives::AccountId::from(
Signer::<PolkadotConfig>::account_id(&ink_e2e::bob()).0,
);
let grant_role = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.grant_role(ATTESTOR_ROLE, Some(bob_address)));
client
.call(&ink_e2e::alice(), grant_role, 0, None)
.await
.expect("grant bob as attestor failed");
let actions = vec![HandleActionInput::Reply(58u128.encode())];
let rollup_cond_eq = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.rollup_cond_eq(vec![], vec![], actions.clone()));
let result = client.call(&ink_e2e::bob(), rollup_cond_eq, 0, None).await;
assert!(
result.is_err(),
"we should not be able to proceed bad messages"
);
Ok(())
}
#[ink_e2e::test]
async fn test_optimistic_locking(mut client: ink_e2e::Client<C, E>) -> E2EResult<()> {
// given
let constructor = TestOracleRef::new();
let contract_acc_id = client
.instantiate("test_oracle", &ink_e2e::alice(), constructor, 0, None)
.await
.expect("instantiate failed")
.account_id;
// bob is granted as attestor
let bob_address = ink::primitives::AccountId::from(
Signer::<PolkadotConfig>::account_id(&ink_e2e::bob()).0,
);
let grant_role = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.grant_role(ATTESTOR_ROLE, Some(bob_address)));
client
.call(&ink_e2e::alice(), grant_role, 0, None)
.await
.expect("grant bob as attestor failed");
// then bob sends a message
// from v0 to v1 => it's ok
let conditions = vec![(123u8.encode(), None)];
let updates = vec![(123u8.encode(), Some(1u128.encode()))];
let rollup_cond_eq = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.rollup_cond_eq(conditions.clone(), updates.clone(), vec![]));
let result = client.call(&ink_e2e::bob(), rollup_cond_eq, 0, None).await;
result.expect("This message should be proceed because the condition is met");
// test idempotency it should fail because the conditions are not met
let rollup_cond_eq = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.rollup_cond_eq(conditions.clone(), updates.clone(), vec![]));
let result = client.call(&ink_e2e::bob(), rollup_cond_eq, 0, None).await;
assert!(
result.is_err(),
"This message should not be proceed because the condition is not met"
);
// from v1 to v2 => it's ok
let conditions = vec![(123u8.encode(), Some(1u128.encode()))];
let updates = vec![(123u8.encode(), Some(2u128.encode()))];
let rollup_cond_eq = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.rollup_cond_eq(conditions.clone(), updates.clone(), vec![]));
let result = client.call(&ink_e2e::bob(), rollup_cond_eq, 0, None).await;
result.expect("This message should be proceed because the condition is met");
// test idempotency it should fail because the conditions are not met
let rollup_cond_eq = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.rollup_cond_eq(conditions.clone(), updates.clone(), vec![]));
let result = client.call(&ink_e2e::bob(), rollup_cond_eq, 0, None).await;
assert!(
result.is_err(),
"This message should not be proceed because the condition is not met"
);
Ok(())
}
#[ink_e2e::test]
async fn test_prepare_meta_tx(mut client: ink_e2e::Client<C, E>) -> E2EResult<()> {
let constructor = TestOracleRef::new();
let contract_acc_id = client
.instantiate("test_oracle", &ink_e2e::bob(), constructor, 0, None)
.await
.expect("instantiate failed")
.account_id;
// Alice is the attestor
// use the ecsda account because we are not able to verify the sr25519 signature
let from = ink::primitives::AccountId::from(
Signer::<PolkadotConfig>::account_id(&subxt_signer::ecdsa::dev::alice()).0,
);
// prepare the meta transaction
let data = u8::encode(&5);
let prepare_meta_tx = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.prepare(from, data.clone()));
let result = client
.call(&ink_e2e::bob(), prepare_meta_tx, 0, None)
.await
.expect("We should be able to prepare the meta tx");
let (request, _hash) = result
.return_value()
.expect("Expected value when preparing meta tx");
assert_eq!(0, request.nonce);
assert_eq!(from, request.from);
assert_eq!(contract_acc_id, request.to);
assert_eq!(&data, &request.data);
Ok(())
}
///
/// Test the meta transactions
/// Charlie is the owner
/// Alice is the attestor
/// Bob is the sender (ie the payer)
///
#[ink_e2e::test]
async fn test_meta_tx_rollup_cond_eq(mut client: ink_e2e::Client<C, E>) -> E2EResult<()> {
let constructor = TestOracleRef::new();
let contract_acc_id = client
.instantiate("test_oracle", &ink_e2e::charlie(), constructor, 0, None)
.await
.expect("instantiate failed")
.account_id;
// Alice is the attestor
// use the ecsda account because we are not able to verify the sr25519 signature
let from = ink::primitives::AccountId::from(
Signer::<PolkadotConfig>::account_id(&subxt_signer::ecdsa::dev::alice()).0,
);
// add the role => it should be succeed
let grant_role = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.grant_role(ATTESTOR_ROLE, Some(from)));
client
.call(&ink_e2e::charlie(), grant_role, 0, None)
.await
.expect("grant the attestor failed");
// prepare the meta transaction
let data = RollupCondEqMethodParams::encode(&(vec![], vec![], vec![]));
let prepare_meta_tx = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.prepare(from, data.clone()));
let result = client
.call(&ink_e2e::bob(), prepare_meta_tx, 0, None)
.await
.expect("We should be able to prepare the meta tx");
let (request, _hash) = result
.return_value()
.expect("Expected value when preparing meta tx");
assert_eq!(0, request.nonce);
assert_eq!(from, request.from);
assert_eq!(contract_acc_id, request.to);
assert_eq!(&data, &request.data);
// Alice signs the message
let keypair = subxt_signer::ecdsa::dev::alice();
let signature = keypair.sign(&scale::Encode::encode(&request)).0;
// do the meta tx
let meta_tx_rollup_cond_eq = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.meta_tx_rollup_cond_eq(request.clone(), signature));
client
.call(&ink_e2e::bob(), meta_tx_rollup_cond_eq, 0, None)
.await
.expect("meta tx rollup cond eq should not failed");
// do it again => it must failed
let meta_tx_rollup_cond_eq = build_message::<TestOracleRef>(contract_acc_id.clone())
.call(|oracle| oracle.meta_tx_rollup_cond_eq(request.clone(), signature));
let result = client
.call(&ink_e2e::bob(), meta_tx_rollup_cond_eq, 0, None)
.await;
assert!(
result.is_err(),
"This message should not be proceed because the nonce is obsolete"
);
Ok(())
}
}
}