-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathlib.rs
More file actions
721 lines (651 loc) · 27.4 KB
/
Copy pathlib.rs
File metadata and controls
721 lines (651 loc) · 27.4 KB
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
#![deny(clippy::pedantic, clippy::nursery)]
#![allow(clippy::module_name_repetitions)]
use crate::connector::{
EngineConnectorWithdraw, EngineFungibleToken, EngineStorageManagement, Withdraw,
};
use crate::deposit_event::FtTransferMessageData;
use crate::types::SdkUnwrap;
use aurora_engine_types::types::Address;
#[cfg(any(feature = "integration-test", feature = "migration"))]
use aurora_engine_types::HashMap;
use connector::ext_omni_bridge;
use near_contract_standards::fungible_token::core::FungibleTokenCore;
use near_contract_standards::fungible_token::metadata::{
FungibleTokenMetadata, FungibleTokenMetadataProvider, FT_METADATA_SPEC,
};
use near_contract_standards::fungible_token::receiver::ext_ft_receiver;
use near_contract_standards::fungible_token::resolver::{ext_ft_resolver, FungibleTokenResolver};
use near_contract_standards::fungible_token::FungibleToken;
use near_contract_standards::storage_management::{
StorageBalance, StorageBalanceBounds, StorageManagement,
};
use near_plugins::{
access_control, access_control_any, pause, AccessControlRole, AccessControllable, Pausable,
Upgradable,
};
use near_sdk::{
assert_one_yocto,
borsh::{self, BorshDeserialize, BorshSerialize},
collections::LazyOption,
env,
json_types::U128,
near, near_bindgen, require, AccountId, BorshStorageKey, Gas, NearToken, PanicOnDefault,
Promise, PromiseOrValue,
};
use serde::{Deserialize, Serialize};
pub mod connector;
pub mod deposit_event;
pub mod errors;
pub mod log_entry;
pub mod migration;
pub mod types;
const GAS_FOR_RESOLVE_TRANSFER: Gas = Gas::from_tgas(5);
const GAS_FOR_FT_TRANSFER_CALL: Gas = Gas::from_tgas(25).saturating_add(GAS_FOR_RESOLVE_TRANSFER);
const GAS_FINISH_WITHDRAW: Gas = Gas::from_tgas(5);
#[derive(BorshSerialize, BorshStorageKey)]
#[borsh(use_discriminant = true)]
enum StorageKey {
FungibleToken = 0x1,
_Proof = 0x2,
Metadata = 0x3,
_EngineAccounts = 0x4,
}
#[derive(AccessControlRole, Deserialize, Serialize, Copy, Clone)]
#[serde(crate = "near_sdk::serde")]
pub enum Role {
PauseManager,
UpgradableCodeStager,
UpgradableCodeDeployer,
DAO,
Migrator,
}
/// Eth-connector contract data. It's stored in the storage.
/// Contains:
/// * connector specific data
/// * Fungible token data
/// * paused_mask - admin control flow data
#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize, PanicOnDefault, Pausable, Upgradable)]
#[access_control(role_type(Role))]
#[pausable(manager_roles(Role::PauseManager, Role::DAO))]
#[upgradable(access_control_roles(
code_stagers(Role::UpgradableCodeStager, Role::DAO),
code_deployers(Role::UpgradableCodeDeployer, Role::DAO),
duration_initializers(Role::DAO),
duration_update_stagers(Role::DAO),
duration_update_appliers(Role::DAO),
))]
pub struct EthConnectorContract {
controller: AccountId,
ft: FungibleToken,
metadata: LazyOption<FungibleTokenMetadata>,
aurora_engine_account_id: AccountId,
}
impl EthConnectorContract {
/// Mint `nETH` tokens
fn mint_eth_on_near(&mut self, owner_id: &AccountId, amount: NearToken) {
log!("Mint {} nETH tokens for: {}", amount, owner_id);
// Create account to avoid panic with deposit
self.ft.internal_deposit(owner_id, amount.as_yoctonear());
}
// Register user and calculate counter
fn register_if_not_exists(&mut self, account: &AccountId) {
if self.ft.account_storage_usage == 0 && !self.ft.accounts.contains_key(account) {
self.ft.internal_register_account(account);
}
}
fn internal_ft_transfer_call(
&mut self,
sender_id: AccountId,
receiver_id: AccountId,
amount: U128,
memo: Option<String>,
msg: String,
) -> PromiseOrValue<U128> {
let amount: u128 = amount.into();
log!(
"Transfer call from {} to {} amount {}",
sender_id,
receiver_id,
amount,
);
// Verify message data before `ft_on_transfer` call for Engine account
// to avoid verification panics inside `ft_on_transfer`.
// Allowed empty message if `receiver_id != aurora_engine_account_id`.
if self.aurora_engine_account_id == receiver_id {
let _: FtTransferMessageData =
FtTransferMessageData::parse_on_transfer_message(&msg).sdk_unwrap();
}
let balance = self.ft.ft_balance_of(sender_id.clone());
require!(balance.0 >= amount, "Insufficient sender balance");
// Special case, we do not fail if `sender_id == receiver_id`
// if `predecessor_account_id` call `ft_transfer_call` as receiver itself
// to call `ft_on_transfer`.
if sender_id == receiver_id {
// If `sender_id == receiver_id` we should verify
// that sender account has sufficient account balance.
// NOTE: Related to Audit AUR-11 report issue
require!(
amount > 0,
"The amount should be a positive non zero number"
);
} else {
self.ft
.internal_transfer(&sender_id, &receiver_id, amount, memo);
}
let receiver_gas = env::prepaid_gas()
.checked_sub(GAS_FOR_FT_TRANSFER_CALL)
.unwrap_or_else(|| env::panic_str("Prepaid gas overflow"));
// Initiating receiver's call and the callback
ext_ft_receiver::ext(receiver_id.clone())
.with_static_gas(receiver_gas)
.ft_on_transfer(sender_id.clone(), amount.into(), msg)
.then(
ext_ft_resolver::ext(env::current_account_id())
.with_static_gas(GAS_FOR_RESOLVE_TRANSFER)
.ft_resolve_transfer(sender_id, receiver_id, amount.into()),
)
.into()
}
// Check if predecessor account is the aurora engine
fn assert_aurora_engine_access_right(&self) {
require!(
env::predecessor_account_id() == self.aurora_engine_account_id,
"Method can be called only by aurora engine"
);
}
fn assert_controller(&self) {
require!(
env::predecessor_account_id() == self.controller,
"Method can be called only by controller"
);
}
}
#[near_bindgen]
impl EthConnectorContract {
#[init]
#[must_use]
#[allow(clippy::use_self)]
pub fn new(
metadata: &FungibleTokenMetadata,
aurora_engine_account_id: AccountId,
owner_id: &AccountId,
controller: &AccountId,
) -> Self {
metadata.assert_valid();
let mut this = Self {
controller: controller.clone(),
ft: FungibleToken {
accounts: near_sdk::collections::LookupMap::new(StorageKey::FungibleToken),
total_supply: 0,
account_storage_usage: 0,
},
metadata: LazyOption::new(StorageKey::Metadata, Some(metadata)),
aurora_engine_account_id,
};
this.register_if_not_exists(&env::current_account_id());
this.register_if_not_exists(owner_id);
this.register_if_not_exists(controller);
this.acl_init_super_admin(env::predecessor_account_id());
this.acl_grant_role("DAO".to_string(), owner_id.clone());
this.acl_grant_role("PauseManager".to_string(), env::predecessor_account_id());
this.pa_pause_feature("ALL".to_string());
this
}
#[cfg(feature = "integration-test")]
#[result_serializer(borsh)]
#[must_use]
pub fn ft_balances_of(
&self,
#[serializer(borsh)] accounts: Vec<AccountId>,
) -> std::collections::HashMap<AccountId, U128> {
let mut balances = std::collections::HashMap::new();
for account_id in accounts {
balances.insert(account_id, U128(10));
}
balances
}
#[payable]
#[access_control_any(roles(Role::DAO))]
pub fn set_aurora_engine_account_id(&mut self, new_aurora_engine_account_id: AccountId) {
assert_one_yocto();
self.aurora_engine_account_id = new_aurora_engine_account_id;
}
#[must_use]
pub fn get_aurora_engine_account_id(&self) -> AccountId {
self.aurora_engine_account_id.clone()
}
#[must_use]
pub fn get_controller(&self) -> AccountId {
self.controller.clone()
}
#[payable]
pub fn mint(
&mut self,
account_id: AccountId,
amount: U128,
msg: Option<String>,
) -> PromiseOrValue<U128> {
self.assert_controller();
self.register_if_not_exists(&account_id);
if let Some(msg) = msg {
self.mint_eth_on_near(
&env::predecessor_account_id(),
NearToken::from_yoctonear(amount.0),
);
self.ft_transfer_call(account_id, amount, None, msg)
} else {
self.mint_eth_on_near(&account_id, NearToken::from_yoctonear(amount.0));
PromiseOrValue::Value(amount)
}
}
pub fn burn(&mut self, amount: U128) {
self.assert_controller();
self.ft
.internal_withdraw(&env::predecessor_account_id(), amount.0);
}
}
#[near_bindgen]
impl FungibleTokenCore for EthConnectorContract {
#[payable]
#[pause(except(roles(Role::DAO)))]
fn ft_transfer(&mut self, receiver_id: AccountId, amount: U128, memo: Option<String>) {
self.register_if_not_exists(&receiver_id);
self.ft.ft_transfer(receiver_id, amount, memo);
}
#[payable]
#[pause(except(roles(Role::DAO)))]
fn ft_transfer_call(
&mut self,
receiver_id: AccountId,
amount: U128,
memo: Option<String>,
msg: String,
) -> PromiseOrValue<U128> {
assert_one_yocto();
require!(
env::prepaid_gas() > GAS_FOR_FT_TRANSFER_CALL,
"More gas is required"
);
let sender_id = env::predecessor_account_id();
self.register_if_not_exists(&receiver_id);
self.internal_ft_transfer_call(sender_id, receiver_id, amount, memo, msg)
}
fn ft_total_supply(&self) -> U128 {
self.ft.ft_total_supply()
}
fn ft_balance_of(&self, account_id: AccountId) -> U128 {
self.ft.ft_balance_of(account_id)
}
}
/// Fungible Token Trait implementation for compatibility with Engine NEP-141 methods.
/// It's because should have a known correct `sender_id`. In reference
/// implementation it's `predecessor_account_id`. To resolve it
/// we just set `sender_id` explicitly as function parameter.
/// Also we check access right to manage access rights.
#[near_bindgen]
impl EngineFungibleToken for EthConnectorContract {
#[payable]
#[pause(name = "engine")]
fn engine_ft_transfer(
&mut self,
sender_id: AccountId,
receiver_id: AccountId,
amount: U128,
memo: Option<String>,
) {
self.assert_aurora_engine_access_right();
self.register_if_not_exists(&receiver_id);
assert_one_yocto();
let amount: u128 = amount.into();
self.ft
.internal_transfer(&sender_id, &receiver_id, amount, memo);
}
#[payable]
#[pause(name = "engine")]
fn engine_ft_transfer_call(
&mut self,
sender_id: AccountId,
receiver_id: AccountId,
amount: U128,
memo: Option<String>,
msg: String,
) -> PromiseOrValue<U128> {
self.assert_aurora_engine_access_right();
assert_one_yocto();
require!(
env::prepaid_gas() > GAS_FOR_FT_TRANSFER_CALL,
"More gas is required"
);
self.register_if_not_exists(&receiver_id);
self.internal_ft_transfer_call(sender_id, receiver_id, amount, memo, msg)
}
}
/// Implementations used only for `EngineStorageManagement`
impl EthConnectorContract {
fn internal_storage_balance_of(&self, account_id: &AccountId) -> Option<StorageBalance> {
if self.ft.accounts.contains_key(account_id) {
Some(StorageBalance {
total: self.storage_balance_bounds().min,
available: NearToken::from_yoctonear(0),
})
} else {
None
}
}
fn internal_storage_unregister(
&mut self,
sender_id: AccountId,
force: Option<bool>,
) -> Option<(AccountId, NearToken)> {
assert_one_yocto();
let account_id = sender_id;
let force = force.unwrap_or(false);
if let Some(balance) = self.ft.accounts.get(&account_id) {
if balance == 0 || force {
self.ft.accounts.remove(&account_id);
self.ft.total_supply -= balance;
let withdraw_amount = self
.storage_balance_bounds()
.min
.checked_add(NearToken::from_yoctonear(1))
.expect("Overflow in withdrawal amount calculation");
Promise::new(account_id.clone()).transfer(withdraw_amount);
Some((account_id, NearToken::from_yoctonear(balance)))
} else {
env::panic_str(
"Can't unregister the account with the positive balance without force",
)
}
} else {
log!("The account {} is not registered", &account_id);
None
}
}
}
/// Storage Management Trait implementation for compatibility with Engine NEP-141 methods.
/// It's because we should ve known correct `sender_id`. In reference
/// implementation it's `predecessor_account_id`. To resolve it
/// we just set `sender_id` explicitly as function parameter.
#[near_bindgen]
impl EngineStorageManagement for EthConnectorContract {
/// Store a deposit for account.
///
/// # Panics
///
/// If the attached deposit is less then the balance of the smart contract.
#[allow(unused_variables)]
#[payable]
#[pause(name = "engine")]
fn engine_storage_deposit(
&mut self,
sender_id: AccountId,
account_id: Option<AccountId>,
registration_only: Option<bool>,
) -> StorageBalance {
self.assert_aurora_engine_access_right();
let amount: NearToken = env::attached_deposit();
let account_id = account_id.unwrap_or_else(|| sender_id.clone());
if self.ft.accounts.contains_key(&account_id) {
log!("The account is already registered, refunding the deposit");
if amount > NearToken::from_yoctonear(0) {
Promise::new(sender_id).transfer(amount);
}
} else {
let min_balance = self.storage_balance_bounds().min;
if amount < min_balance {
env::panic_str("The attached deposit is less than the minimum storage balance");
}
self.ft.internal_register_account(&account_id);
let refund = amount.saturating_sub(min_balance);
if refund > NearToken::from_yoctonear(0) {
Promise::new(sender_id).transfer(refund);
}
}
self.internal_storage_balance_of(&account_id).unwrap()
}
#[payable]
#[pause(name = "engine")]
fn engine_storage_withdraw(
&mut self,
sender_id: AccountId,
amount: Option<U128>,
) -> StorageBalance {
self.assert_aurora_engine_access_right();
assert_one_yocto();
let predecessor_account_id = sender_id;
self.internal_storage_balance_of(&predecessor_account_id)
.map_or_else(
|| {
env::panic_str(
format!("The account {} is not registered", &predecessor_account_id)
.as_str(),
);
},
|storage_balance| match amount {
Some(amount) if amount.0 > 0 => {
env::panic_str("The amount is greater than the available storage balance");
}
_ => storage_balance,
},
)
}
#[payable]
#[pause(name = "engine")]
fn engine_storage_unregister(&mut self, sender_id: AccountId, force: Option<bool>) -> bool {
self.assert_aurora_engine_access_right();
self.internal_storage_unregister(sender_id, force).is_some()
}
}
#[near_bindgen]
impl FungibleTokenResolver for EthConnectorContract {
#[private]
fn ft_resolve_transfer(
&mut self,
sender_id: AccountId,
receiver_id: AccountId,
amount: U128,
) -> U128 {
self.ft.ft_resolve_transfer(sender_id, receiver_id, amount)
}
}
#[near_bindgen]
impl StorageManagement for EthConnectorContract {
#[payable]
fn storage_deposit(
&mut self,
account_id: Option<AccountId>,
registration_only: Option<bool>,
) -> StorageBalance {
self.ft.storage_deposit(account_id, registration_only)
}
#[payable]
fn storage_withdraw(&mut self, amount: Option<NearToken>) -> StorageBalance {
self.ft.storage_withdraw(amount)
}
#[payable]
fn storage_unregister(&mut self, force: Option<bool>) -> bool {
self.ft.internal_storage_unregister(force).is_some()
}
fn storage_balance_bounds(&self) -> StorageBalanceBounds {
self.ft.storage_balance_bounds()
}
fn storage_balance_of(&self, account_id: AccountId) -> Option<StorageBalance> {
if self.ft.account_storage_usage == 0 {
Some(StorageBalance {
total: NearToken::from_yoctonear(0),
available: NearToken::from_yoctonear(0),
})
} else {
self.ft.storage_balance_of(account_id)
}
}
}
#[near_bindgen]
impl FungibleTokenMetadataProvider for EthConnectorContract {
fn ft_metadata(&self) -> FungibleTokenMetadata {
self.metadata.get().map_or_else(|| FungibleTokenMetadata {
spec: FT_METADATA_SPEC.to_string(),
name: "Ether".to_string(),
symbol: "ETH".to_string(),
icon: Some("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAs3SURBVHhe7Z1XqBQ9FMdFsYu999577wUfbCiiPoggFkQsCKJP9t57V7AgimLBjg8qKmLBXrD33hVUEAQ1H7+QXMb9Zndnd+/MJJf7h8Pu3c3Mzua3yTk5SeZmEZkySplADFMmEMOUCcQwZQggHz58EHfu3FF/2a0MAWTjxo2iWbNm6i+7ZT2QW7duiUWLFolixYqJQ4cOqVftlfVAZs6cKdauXSuqV68uKlWqpF61V1YDoUXMmTNHrFu3TtSoUUNCmTBhgnrXTlkL5Nu3b2Ly5MmyuwJIzZo1RaNGjUTx4sXFu3fvVCn7ZC2QVatWiQULFvwPSL169USnTp1UKftkJZCbN2+KGTNmSBiLFy/+BwhWoUIFsX//flXaLlkJZPr06WkwIoE0btxYNGzYUFSsWFGVtkvWATlw4IB05BqGGxAMBz9u3Dh1lD2yCsjXr1/THHk8IDwvVaqUeP36tTraDlkFZOXKldKRO2HEAoKD79ixozraDlkD5Pr16/848nhANBQc/N69e9VZzJc1QCIduRcgGA4eKLbICiD79u37nyN3WiwgvMZ7Y8eOVWczW8YDwZFPmTIlauvA4gHhsUSJEuLFixfqrObKeCArVqxwdeROiwUE43UcfNu2bdVZzZXRQK5duyYduRsEp8UDog1fsnPnTnV2M2U0kFiO3GlegeDgy5cvr85upowFQqg6d+5cVwCR5hUI71NuzJgx6lPMk5FAPn365Doij2ZegWCUIUX/9OlT9Wl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Ui0MhQKEeel4q995DyjcZ/Hz58/qSHfRrcTbSUuZdu3ayTEOYawbDIz3iLDiRYB+KRQgiP/3waJrNxjagMI0MK2AKC1ZjR49Wm5/JqEZDQTGe8A4fPiwOjJ4hQYEsS3By/5CwFCOVsWAzatIAhKVed3MQznWEIepUIEg/IUzFI5lgCEgYG1XrKQlyT9CY3wFXZBb5UcaURZ+JWyFDoSs8KRJk2L6E6dRDoB0YyQtneukSGAOHjxYDu70KNut8iONckRcJvzbpNCBIAZmXrcpYBoekRpgyBQzhiE1wkDOKwiMsuSr6BJNkBFAENEU45DIyo9nwGGxNs44ERAY5QlxmQsxRcYAIcxMdKubtmS3RVOe7u3Hjx/qKsKXMUAQA0EiKbdKj2XJAiEC2717t/p0M2QUEETaw0so7LREgVCO8l4Sj0HLOCAIB+81FMYSAUIZQmGSkybKSCAs1I7MCseyRIEwaveSJwtDRgJBR48e9RwKewXC+0x0AdtUGQsEMSL3cnMaL0B4j1wWc/Qmy2ggzG/ruXg3ENq8AmHgyCSZyTIaCLp06VLce8DHA8LrrGDxMnEVtowHgjZt2hR1QguLB4R0Su/evdXZzJYVQJBe25UoELK4Nv1PQ2uAPHv2LKo/iQaEv0mNeFn4bYqsAYL4p5IsGfIChOfMb7Dp1CZZBQTRQiJDYTcgerrWNlkHhHVbkV1XJBAemXDirqe2yTog6Ny5c9LJayhOIBgrS1h1b6OsBIKocB0KO4FwtwVu7WSrrAWC9NouDYQsLstCbZbVQNjmwCwjQFjCwzTuqVOn1Lt2ymogiBk/PafOfbdsl/VAEEBs+gfEsZQhgDChxVKgjKAMASQjKROIYcoEYpgygRglIf4D6lp/+XognSwAAAAASUVORK5CYII=".to_string()),
reference: None,
reference_hash: None,
decimals: 18,
}, |v|v)
}
}
#[near_bindgen]
impl Withdraw for EthConnectorContract {
#[payable]
#[pause(except(roles(Role::DAO)))]
fn withdraw(
&mut self,
#[serializer(borsh)] recipient_address: [u8; 20],
#[serializer(borsh)] amount: NearToken,
) -> Promise {
assert_one_yocto();
let sender_id = env::predecessor_account_id();
// Burn tokens to recipient
self.ft.internal_withdraw(&sender_id, amount.as_yoctonear());
ext_omni_bridge::ext(self.controller.clone())
.with_static_gas(GAS_FINISH_WITHDRAW)
.finish_withdraw_v2(
env::predecessor_account_id(),
amount,
Address::from_array(recipient_address).encode(),
)
}
}
#[near_bindgen]
impl EngineConnectorWithdraw for EthConnectorContract {
#[payable]
#[pause]
fn engine_withdraw(
&mut self,
#[serializer(borsh)] sender_id: AccountId,
#[serializer(borsh)] recipient_address: [u8; 20],
#[serializer(borsh)] amount: NearToken,
) -> Promise {
self.assert_aurora_engine_access_right();
assert_one_yocto();
// Burn tokens to recipient
self.ft.internal_withdraw(&sender_id, amount.as_yoctonear());
ext_omni_bridge::ext(self.controller.clone())
.with_static_gas(GAS_FINISH_WITHDRAW)
.finish_withdraw_v2(
sender_id,
amount,
Address::from_array(recipient_address).encode(),
)
}
}
#[cfg(feature = "migration")]
use crate::connector::{ext_engine_connector, ext_migrate};
#[cfg(feature = "migration")]
use crate::migration::{CheckResult, InputData, Migration};
#[cfg(feature = "migration")]
#[near_bindgen]
impl Migration for EthConnectorContract {
/// Migrate accounts balances
#[access_control_any(roles(Role::Migrator, Role::DAO))]
fn migrate(&mut self, #[serializer(borsh)] accounts: Vec<AccountId>) -> Promise {
const GAS_FOR_CALLS: Gas = Gas::from_tgas(140);
ext_engine_connector::ext(self.aurora_engine_account_id.clone())
.with_static_gas(GAS_FOR_CALLS)
.ft_balances_of(accounts)
.then(
ext_migrate::ext(env::current_account_id())
.with_static_gas(GAS_FOR_CALLS)
.migrate_callback(),
)
}
#[private]
fn migrate_callback(
&mut self,
#[callback]
#[serializer(borsh)]
balances: HashMap<AccountId, u128>,
) {
for (account, amount) in &balances {
if let Some(previous_balance) = self.ft.accounts.insert(account, amount) {
self.ft.total_supply -= previous_balance;
}
self.ft.total_supply += amount;
}
}
#[result_serializer(borsh)]
fn check_migration_correctness(&self, #[serializer(borsh)] data: InputData) -> CheckResult {
use std::collections::HashMap;
// Check accounts
let mut accounts_not_found: Vec<AccountId> = vec![];
let mut accounts_with_amount_not_found = HashMap::new();
for (account, amount) in &data.accounts {
self.ft.accounts.get(account).as_ref().map_or_else(
|| accounts_not_found.push(account.clone()),
|value| {
if value != amount {
accounts_with_amount_not_found.insert(account.clone(), *value);
}
},
);
}
if !accounts_not_found.is_empty() {
return CheckResult::AccountNotExist(accounts_not_found);
}
if !accounts_with_amount_not_found.is_empty() {
return CheckResult::AccountAmount(accounts_with_amount_not_found);
}
if let Some(total_supply) = data.total_supply {
if self.ft.total_supply != total_supply {
return CheckResult::TotalSupply(self.ft.total_supply);
}
}
CheckResult::Success
}
}
#[cfg(feature = "integration-test")]
use near_contract_standards::fungible_token::receiver::FungibleTokenReceiver;
#[cfg(feature = "integration-test")]
#[near_bindgen]
impl FungibleTokenReceiver for EthConnectorContract {
#[allow(unused_variables)]
fn ft_on_transfer(
&mut self,
sender_id: AccountId,
amount: U128,
msg: String,
) -> PromiseOrValue<U128> {
PromiseOrValue::Value(U128(0))
}
}
#[cfg(test)]
mod tests {
use super::*;
/// In the original implementation of the eth-connector contract the storage balance
/// was always 0. This test confirms this is true for the new implementation.
#[test]
fn test_storage_balance_bounds() {
let contract = create_contract();
let storage_balance = contract
.storage_balance_of(contract.acl_get_grantees("DAO".to_string(), 0, 1)[0].clone())
.unwrap();
assert_eq!(storage_balance.total.as_yoctonear(), 0);
assert_eq!(storage_balance.available.as_yoctonear(), 0);
}
fn create_contract() -> EthConnectorContract {
let metadata = FungibleTokenMetadata {
spec: FT_METADATA_SPEC.to_string(),
name: "Ether".to_string(),
symbol: "ETH".to_string(),
icon: None,
reference: None,
reference_hash: None,
decimals: 18,
};
let account_with_access_right = "engine.near".parse().unwrap();
let owner_id = "owner.near".parse().unwrap();
let controller = "controller.near".parse().unwrap();
EthConnectorContract::new(&metadata, account_with_access_right, &owner_id, &controller)
}
}