-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathengine.rs
1699 lines (1524 loc) · 56.5 KB
/
engine.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
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::parameters::{CallArgs, NEP141FtOnTransferArgs, ResultLog, SubmitResult, ViewCallArgs};
use core::mem;
use evm::backend::{Apply, ApplyBackend, Backend, Basic, Log};
use evm::executor;
use evm::{Config, CreateScheme, ExitError, ExitFatal, ExitReason};
use crate::connector::EthConnectorContract;
use crate::map::BijectionMap;
use aurora_engine_sdk::caching::FullCache;
use aurora_engine_sdk::env::Env;
use aurora_engine_sdk::io::{StorageIntermediate, IO};
use aurora_engine_sdk::promise::{PromiseHandler, PromiseId};
use crate::accounting;
use crate::parameters::{DeployErc20TokenArgs, NewCallArgs, TransactionStatus};
use crate::prelude::parameters::RefundCallArgs;
use crate::prelude::precompiles::native::{exit_to_ethereum, exit_to_near};
use crate::prelude::precompiles::Precompiles;
use crate::prelude::transactions::{EthTransactionKind, NormalizedEthTransaction};
use crate::prelude::{
address_to_key, bytes_to_key, sdk, storage_to_key, u256_to_arr, vec, AccountId, Address,
BTreeMap, BorshDeserialize, BorshSerialize, KeyPrefix, PromiseArgs, PromiseCreateArgs,
ToString, Vec, Wei, ERC20_MINT_SELECTOR, H160, H256, U256,
};
use aurora_engine_precompiles::PrecompileConstructorContext;
use core::cell::RefCell;
/// Used as the first byte in the concatenation of data used to compute the blockhash.
/// Could be useful in the future as a version byte, or to distinguish different types of blocks.
const BLOCK_HASH_PREFIX: u8 = 0;
const BLOCK_HASH_PREFIX_SIZE: usize = 1;
const BLOCK_HEIGHT_SIZE: usize = 8;
const CHAIN_ID_SIZE: usize = 32;
#[cfg(not(feature = "contract"))]
/// Block height where the bug fix for parsing transactions to the zero address
/// is deployed. The current value is only approximate; will be updated once the
/// fix is actually deployed.
pub const ZERO_ADDRESS_FIX_HEIGHT: u64 = 61200152;
pub fn current_address(current_account_id: &AccountId) -> Address {
aurora_engine_sdk::types::near_account_to_evm_address(current_account_id.as_bytes())
}
macro_rules! unwrap_res_or_finish {
($e:expr, $output:expr, $io:expr) => {
match $e {
Ok(v) => v,
Err(_e) => {
#[cfg(feature = "log")]
sdk::log(crate::prelude::format!("{:?}", _e).as_str());
$io.return_output($output);
return;
}
}
};
}
macro_rules! assert_or_finish {
($e:expr, $output:expr, $io:expr) => {
if !$e {
$io.return_output($output);
return;
}
};
}
#[derive(Debug, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct EngineError {
pub kind: EngineErrorKind,
pub gas_used: u64,
}
impl From<EngineErrorKind> for EngineError {
fn from(kind: EngineErrorKind) -> Self {
Self { kind, gas_used: 0 }
}
}
impl AsRef<[u8]> for EngineError {
fn as_ref(&self) -> &[u8] {
self.kind.as_bytes()
}
}
/// Errors with the EVM engine.
#[derive(Debug, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub enum EngineErrorKind {
/// Normal EVM errors.
EvmError(ExitError),
/// Fatal EVM errors.
EvmFatal(ExitFatal),
/// Incorrect nonce.
IncorrectNonce,
FailedTransactionParse(crate::prelude::transactions::ParseTransactionError),
InvalidChainId,
InvalidSignature,
IntrinsicGasNotMet,
MaxPriorityGasFeeTooLarge,
GasPayment(GasPaymentError),
GasOverflow,
}
impl EngineErrorKind {
pub fn with_gas_used(self, gas_used: u64) -> EngineError {
EngineError {
kind: self,
gas_used,
}
}
pub fn as_bytes(&self) -> &[u8] {
use EngineErrorKind::*;
match self {
EvmError(ExitError::StackUnderflow) => b"ERR_STACK_UNDERFLOW",
EvmError(ExitError::StackOverflow) => b"ERR_STACK_OVERFLOW",
EvmError(ExitError::InvalidJump) => b"ERR_INVALID_JUMP",
EvmError(ExitError::InvalidRange) => b"ERR_INVALID_RANGE",
EvmError(ExitError::DesignatedInvalid) => b"ERR_DESIGNATED_INVALID",
EvmError(ExitError::CallTooDeep) => b"ERR_CALL_TOO_DEEP",
EvmError(ExitError::CreateCollision) => b"ERR_CREATE_COLLISION",
EvmError(ExitError::CreateContractLimit) => b"ERR_CREATE_CONTRACT_LIMIT",
EvmError(ExitError::OutOfOffset) => b"ERR_OUT_OF_OFFSET",
EvmError(ExitError::OutOfGas) => b"ERR_OUT_OF_GAS",
EvmError(ExitError::OutOfFund) => b"ERR_OUT_OF_FUND",
EvmError(ExitError::Other(m)) => m.as_bytes(),
EvmError(_) => unreachable!(), // unused misc
EvmFatal(ExitFatal::NotSupported) => b"ERR_NOT_SUPPORTED",
EvmFatal(ExitFatal::UnhandledInterrupt) => b"ERR_UNHANDLED_INTERRUPT",
EvmFatal(ExitFatal::Other(m)) => m.as_bytes(),
EvmFatal(_) => unreachable!(), // unused misc
IncorrectNonce => b"ERR_INCORRECT_NONCE",
FailedTransactionParse(e) => e.as_ref(),
InvalidChainId => b"ERR_INVALID_CHAIN_ID",
InvalidSignature => b"ERR_INVALID_ECDSA_SIGNATURE",
IntrinsicGasNotMet => b"ERR_INTRINSIC_GAS",
MaxPriorityGasFeeTooLarge => b"ERR_MAX_PRIORITY_FEE_GREATER",
GasPayment(e) => e.as_ref(),
GasOverflow => b"ERR_GAS_OVERFLOW",
}
}
}
impl AsRef<[u8]> for EngineErrorKind {
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl From<ExitError> for EngineErrorKind {
fn from(e: ExitError) -> Self {
EngineErrorKind::EvmError(e)
}
}
impl From<ExitFatal> for EngineErrorKind {
fn from(e: ExitFatal) -> Self {
EngineErrorKind::EvmFatal(e)
}
}
/// An engine result.
pub type EngineResult<T> = Result<T, EngineError>;
trait ExitIntoResult {
/// Checks if the EVM exit is ok or an error.
fn into_result(self, data: Vec<u8>) -> Result<TransactionStatus, EngineErrorKind>;
}
impl ExitIntoResult for ExitReason {
fn into_result(self, data: Vec<u8>) -> Result<TransactionStatus, EngineErrorKind> {
use ExitReason::*;
match self {
Succeed(_) => Ok(TransactionStatus::Succeed(data)),
Revert(_) => Ok(TransactionStatus::Revert(data)),
Error(ExitError::OutOfOffset) => Ok(TransactionStatus::OutOfOffset),
Error(ExitError::OutOfFund) => Ok(TransactionStatus::OutOfFund),
Error(ExitError::OutOfGas) => Ok(TransactionStatus::OutOfGas),
Error(e) => Err(e.into()),
Fatal(e) => Err(e.into()),
}
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BalanceOverflow;
impl AsRef<[u8]> for BalanceOverflow {
fn as_ref(&self) -> &[u8] {
b"ERR_BALANCE_OVERFLOW"
}
}
/// Errors resulting from trying to pay for gas
#[derive(Debug, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum GasPaymentError {
/// Overflow adding ETH to an account balance (should never happen)
BalanceOverflow(BalanceOverflow),
/// Overflow in gas * gas_price calculation
EthAmountOverflow,
/// Not enough balance for account to cover the gas cost
OutOfFund,
}
impl AsRef<[u8]> for GasPaymentError {
fn as_ref(&self) -> &[u8] {
match self {
Self::BalanceOverflow(overflow) => overflow.as_ref(),
Self::EthAmountOverflow => b"ERR_GAS_ETH_AMOUNT_OVERFLOW",
Self::OutOfFund => b"ERR_OUT_OF_FUND",
}
}
}
impl From<BalanceOverflow> for GasPaymentError {
fn from(overflow: BalanceOverflow) -> Self {
Self::BalanceOverflow(overflow)
}
}
#[derive(Debug)]
pub enum DeployErc20Error {
State(EngineStateError),
Failed(TransactionStatus),
Engine(EngineError),
Register(RegisterTokenError),
}
impl AsRef<[u8]> for DeployErc20Error {
fn as_ref(&self) -> &[u8] {
match self {
Self::State(e) => e.as_ref(),
Self::Failed(e) => e.as_ref(),
Self::Engine(e) => e.as_ref(),
Self::Register(e) => e.as_ref(),
}
}
}
pub struct ERC20Address(Address);
impl AsRef<[u8]> for ERC20Address {
fn as_ref(&self) -> &[u8] {
self.0.as_bytes()
}
}
impl TryFrom<Vec<u8>> for ERC20Address {
type Error = AddressParseError;
fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
if bytes.len() == 20 {
Ok(Self(
Address::try_from_slice(&bytes).map_err(|_| AddressParseError)?,
))
} else {
Err(AddressParseError)
}
}
}
pub struct AddressParseError;
impl AsRef<[u8]> for AddressParseError {
fn as_ref(&self) -> &[u8] {
b"ERR_PARSE_ADDRESS"
}
}
pub struct NEP141Account(AccountId);
impl AsRef<[u8]> for NEP141Account {
fn as_ref(&self) -> &[u8] {
self.0.as_bytes()
}
}
impl TryFrom<Vec<u8>> for NEP141Account {
type Error = aurora_engine_types::account_id::ParseAccountError;
fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
AccountId::try_from(bytes).map(Self)
}
}
pub const ERR_INVALID_NEP141_ACCOUNT_ID: &str = "ERR_INVALID_NEP141_ACCOUNT_ID";
#[derive(Debug)]
pub enum GetErc20FromNep141Error {
InvalidNep141AccountId,
Nep141NotFound,
}
impl GetErc20FromNep141Error {
pub fn to_str(&self) -> &str {
match self {
Self::InvalidNep141AccountId => ERR_INVALID_NEP141_ACCOUNT_ID,
Self::Nep141NotFound => "ERR_NEP141_NOT_FOUND",
}
}
}
impl AsRef<[u8]> for GetErc20FromNep141Error {
fn as_ref(&self) -> &[u8] {
self.to_str().as_bytes()
}
}
#[derive(Debug)]
pub enum RegisterTokenError {
InvalidNep141AccountId,
TokenAlreadyRegistered,
}
impl RegisterTokenError {
pub fn to_str(&self) -> &str {
match self {
Self::InvalidNep141AccountId => ERR_INVALID_NEP141_ACCOUNT_ID,
Self::TokenAlreadyRegistered => "ERR_NEP141_TOKEN_ALREADY_REGISTERED",
}
}
}
impl AsRef<[u8]> for RegisterTokenError {
fn as_ref(&self) -> &[u8] {
self.to_str().as_bytes()
}
}
#[derive(Debug)]
pub enum EngineStateError {
NotFound,
DeserializationFailed,
}
impl AsRef<[u8]> for EngineStateError {
fn as_ref(&self) -> &[u8] {
match self {
Self::NotFound => b"ERR_STATE_NOT_FOUND",
Self::DeserializationFailed => b"ERR_STATE_CORRUPTED",
}
}
}
struct StackExecutorParams<'a, I, E> {
precompiles: Precompiles<'a, I, E>,
gas_limit: u64,
}
impl<'env, I: IO + Copy, E: Env> StackExecutorParams<'env, I, E> {
fn new(
gas_limit: u64,
current_account_id: AccountId,
random_seed: H256,
io: I,
env: &'env E,
) -> Self {
Self {
precompiles: Precompiles::new_london(PrecompileConstructorContext {
current_account_id,
random_seed,
io,
env,
}),
gas_limit,
}
}
fn make_executor<'a>(
&'a self,
engine: &'a Engine<'env, I, E>,
) -> executor::stack::StackExecutor<
'static,
'a,
executor::stack::MemoryStackState<Engine<'env, I, E>>,
Precompiles<'env, I, E>,
> {
let metadata = executor::stack::StackSubstateMetadata::new(self.gas_limit, CONFIG);
let state = executor::stack::MemoryStackState::new(metadata, engine);
executor::stack::StackExecutor::new_with_precompiles(state, CONFIG, &self.precompiles)
}
}
#[derive(Debug, Default)]
pub struct GasPaymentResult {
pub prepaid_amount: Wei,
pub effective_gas_price: U256,
pub priority_fee_per_gas: U256,
}
/// Engine internal state, mostly configuration.
/// Should not contain anything large or enumerable.
#[derive(BorshSerialize, BorshDeserialize, Default, Clone)]
pub struct EngineState {
/// Chain id, according to the EIP-155 / ethereum-lists spec.
pub chain_id: [u8; 32],
/// Account which can upgrade this contract.
/// Use empty to disable updatability.
pub owner_id: AccountId,
/// Account of the bridge prover.
/// Use empty to not use base token as bridged asset.
pub bridge_prover_id: AccountId,
/// How many blocks after staging upgrade can deploy it.
pub upgrade_delay_blocks: u64,
}
impl From<NewCallArgs> for EngineState {
fn from(args: NewCallArgs) -> Self {
EngineState {
chain_id: args.chain_id,
owner_id: args.owner_id,
bridge_prover_id: args.bridge_prover_id,
upgrade_delay_blocks: args.upgrade_delay_blocks,
}
}
}
pub struct Engine<'env, I: IO, E: Env> {
state: EngineState,
origin: Address,
gas_price: U256,
current_account_id: AccountId,
io: I,
env: &'env E,
generation_cache: RefCell<BTreeMap<Address, u32>>,
account_info_cache: RefCell<FullCache<Address, Basic>>,
contract_code_cache: RefCell<FullCache<Address, Vec<u8>>>,
contract_storage_cache: RefCell<FullCache<(Address, H256), H256>>,
}
pub(crate) const CONFIG: &Config = &Config::london();
/// Key for storing the state of the engine.
const STATE_KEY: &[u8; 5] = b"STATE";
impl<'env, I: IO + Copy, E: Env> Engine<'env, I, E> {
pub fn new(
origin: Address,
current_account_id: AccountId,
io: I,
env: &'env E,
) -> Result<Self, EngineStateError> {
get_state(&io).map(|state| Self::new_with_state(state, origin, current_account_id, io, env))
}
pub fn new_with_state(
state: EngineState,
origin: Address,
current_account_id: AccountId,
io: I,
env: &'env E,
) -> Self {
Self {
state,
origin,
gas_price: U256::zero(),
current_account_id,
io,
env,
generation_cache: RefCell::new(BTreeMap::new()),
account_info_cache: RefCell::new(FullCache::default()),
contract_code_cache: RefCell::new(FullCache::default()),
contract_storage_cache: RefCell::new(FullCache::default()),
}
}
pub fn charge_gas(
&mut self,
sender: &Address,
transaction: &NormalizedEthTransaction,
) -> Result<GasPaymentResult, GasPaymentError> {
if transaction.max_fee_per_gas.is_zero() {
return Ok(GasPaymentResult::default());
}
let priority_fee_per_gas = transaction
.max_priority_fee_per_gas
.min(transaction.max_fee_per_gas - self.block_base_fee_per_gas());
let effective_gas_price = priority_fee_per_gas + self.block_base_fee_per_gas();
let gas_limit = transaction.gas_limit;
let prepaid_amount = gas_limit
.checked_mul(effective_gas_price)
.map(Wei::new)
.ok_or(GasPaymentError::EthAmountOverflow)?;
let new_balance = get_balance(&self.io, sender)
.checked_sub(prepaid_amount)
.ok_or(GasPaymentError::OutOfFund)?;
set_balance(&mut self.io, sender, &new_balance);
self.gas_price = effective_gas_price;
Ok(GasPaymentResult {
prepaid_amount,
effective_gas_price,
priority_fee_per_gas,
})
}
pub fn deploy_code_with_input<P: PromiseHandler>(
&mut self,
input: Vec<u8>,
handler: &mut P,
) -> EngineResult<SubmitResult> {
let origin = Address::new(self.origin());
let value = Wei::zero();
self.deploy_code(origin, value, input, u64::MAX, Vec::new(), handler)
}
pub fn deploy_code<P: PromiseHandler>(
&mut self,
origin: Address,
value: Wei,
input: Vec<u8>,
gas_limit: u64,
access_list: Vec<(H160, Vec<H256>)>, // See EIP-2930
handler: &mut P,
) -> EngineResult<SubmitResult> {
let executor_params = StackExecutorParams::new(
gas_limit,
self.current_account_id.clone(),
self.env.random_seed(),
self.io,
self.env,
);
let mut executor = executor_params.make_executor(self);
let address = executor.create_address(CreateScheme::Legacy {
caller: origin.raw(),
});
let (exit_reason, return_value) =
executor.transact_create(origin.raw(), value.raw(), input, gas_limit, access_list);
let result = if exit_reason.is_succeed() {
address.0.to_vec()
} else {
return_value
};
let used_gas = executor.used_gas();
let status = match exit_reason.into_result(result) {
Ok(status) => status,
Err(e) => {
increment_nonce(&mut self.io, &origin);
return Err(e.with_gas_used(used_gas));
}
};
let (values, logs) = executor.into_state().deconstruct();
let logs = filter_promises_from_logs(handler, logs);
self.apply(values, Vec::<Log>::new(), true);
Ok(SubmitResult::new(status, used_gas, logs))
}
/// Call the EVM contract with arguments
pub fn call_with_args<P: PromiseHandler>(
&mut self,
args: CallArgs,
handler: &mut P,
) -> EngineResult<SubmitResult> {
let origin = Address::new(self.origin());
match args {
CallArgs::V2(call_args) => {
let contract = call_args.contract;
let value = call_args.value.into();
let input = call_args.input;
self.call(
&origin,
&contract,
value,
input,
u64::MAX,
Vec::new(),
handler,
)
}
CallArgs::V1(call_args) => {
let contract = call_args.contract;
let value = Wei::zero();
let input = call_args.input;
self.call(
&origin,
&contract,
value,
input,
u64::MAX,
Vec::new(),
handler,
)
}
}
}
#[allow(clippy::too_many_arguments)]
pub fn call<P: PromiseHandler>(
&mut self,
origin: &Address,
contract: &Address,
value: Wei,
input: Vec<u8>,
gas_limit: u64,
access_list: Vec<(H160, Vec<H256>)>, // See EIP-2930
handler: &mut P,
) -> EngineResult<SubmitResult> {
let executor_params = StackExecutorParams::new(
gas_limit,
self.current_account_id.clone(),
self.env.random_seed(),
self.io,
self.env,
);
let mut executor = executor_params.make_executor(self);
let (exit_reason, result) = executor.transact_call(
origin.raw(),
contract.raw(),
value.raw(),
input,
gas_limit,
access_list,
);
let used_gas = executor.used_gas();
let status = match exit_reason.into_result(result) {
Ok(status) => status,
Err(e) => {
increment_nonce(&mut self.io, origin);
return Err(e.with_gas_used(used_gas));
}
};
let (values, logs) = executor.into_state().deconstruct();
let logs = filter_promises_from_logs(handler, logs);
// There is no way to return the logs to the NEAR log method as it only
// allows a return of UTF-8 strings.
self.apply(values, Vec::<Log>::new(), true);
Ok(SubmitResult::new(status, used_gas, logs))
}
pub fn view_with_args(&self, args: ViewCallArgs) -> Result<TransactionStatus, EngineErrorKind> {
let origin = &args.sender;
let contract = &args.address;
let value = U256::from_big_endian(&args.amount);
self.view(origin, contract, Wei::new(value), args.input, u64::MAX)
}
pub fn view(
&self,
origin: &Address,
contract: &Address,
value: Wei,
input: Vec<u8>,
gas_limit: u64,
) -> Result<TransactionStatus, EngineErrorKind> {
let executor_params = StackExecutorParams::new(
gas_limit,
self.current_account_id.clone(),
self.env.random_seed(),
self.io,
self.env,
);
let mut executor = executor_params.make_executor(self);
let (status, result) = executor.transact_call(
origin.raw(),
contract.raw(),
value.raw(),
input,
gas_limit,
Vec::new(),
);
status.into_result(result)
}
fn relayer_key(account_id: &[u8]) -> Vec<u8> {
bytes_to_key(KeyPrefix::RelayerEvmAddressMap, account_id)
}
pub fn register_relayer(&mut self, account_id: &[u8], evm_address: Address) {
let key = Self::relayer_key(account_id);
self.io.write_storage(&key, evm_address.as_bytes());
}
pub fn get_relayer(&self, account_id: &[u8]) -> Option<Address> {
let key = Self::relayer_key(account_id);
let raw_addr = self.io.read_storage(&key).map(|v| v.to_vec())?;
Address::try_from_slice(&raw_addr[..]).ok()
}
pub fn register_token(
&mut self,
erc20_token: Address,
nep141_token: AccountId,
) -> Result<(), RegisterTokenError> {
match get_erc20_from_nep141(&self.io, &nep141_token) {
Err(GetErc20FromNep141Error::Nep141NotFound) => (),
Err(GetErc20FromNep141Error::InvalidNep141AccountId) => {
return Err(RegisterTokenError::InvalidNep141AccountId);
}
Ok(_) => return Err(RegisterTokenError::TokenAlreadyRegistered),
}
let erc20_token = ERC20Address(erc20_token);
let nep141_token = NEP141Account(nep141_token);
nep141_erc20_map(self.io).insert(&nep141_token, &erc20_token);
Ok(())
}
/// Transfers an amount from a given sender to a receiver, provided that
/// the have enough in their balance.
///
/// If the sender can send, and the receiver can receive, then the transfer
/// will execute successfully.
pub fn transfer<P: PromiseHandler>(
&mut self,
sender: Address,
receiver: Address,
value: Wei,
gas_limit: u64,
handler: &mut P,
) -> EngineResult<SubmitResult> {
self.call(
&sender,
&receiver,
value,
Vec::new(),
gas_limit,
Vec::new(),
handler,
)
}
/// Mint tokens for recipient on a particular ERC20 token
/// This function should return the amount of tokens unused,
/// which will be always all (<amount>) if there is any problem
/// with the input, or 0 if tokens were minted successfully.
///
/// The output will be serialized as a String
/// https://github.com/near/NEPs/discussions/146
///
/// IMPORTANT: This function should not panic, otherwise it won't
/// be possible to return the tokens to the sender.
pub fn receive_erc20_tokens<P: PromiseHandler>(
&mut self,
token: &AccountId,
relayer_account_id: &AccountId,
args: &NEP141FtOnTransferArgs,
current_account_id: &AccountId,
handler: &mut P,
) {
let str_amount = crate::prelude::format!("\"{}\"", args.amount);
let output_on_fail = str_amount.as_bytes();
// Parse message to determine recipient and fee
let (recipient, fee) = {
// Message format:
// Recipient of the transaction - 40 characters (Address in hex)
// Fee to be paid in ETH (Optional) - 64 characters (Encoded in big endian / hex)
let message = args.msg.as_bytes();
assert_or_finish!(message.len() >= 40, output_on_fail, self.io);
let recipient = Address::new(H160(unwrap_res_or_finish!(
hex::decode(&message[..40]).unwrap().as_slice().try_into(),
output_on_fail,
self.io
)));
let fee = U256::zero();
(recipient, fee)
};
let erc20_token = Address::from_array(unwrap_res_or_finish!(
unwrap_res_or_finish!(
get_erc20_from_nep141(&self.io, token),
output_on_fail,
self.io
)
.as_slice()
.try_into(),
output_on_fail,
self.io
));
if fee != U256::from(0) {
let relayer_address = unwrap_res_or_finish!(
self.get_relayer(relayer_account_id.as_bytes()).ok_or(()),
output_on_fail,
self.io
);
unwrap_res_or_finish!(
self.transfer(
recipient,
relayer_address,
Wei::new_u64(fee.as_u64()),
u64::MAX,
handler,
),
output_on_fail,
self.io
);
}
let selector = ERC20_MINT_SELECTOR;
let tail = ethabi::encode(&[
ethabi::Token::Address(recipient.raw()),
ethabi::Token::Uint(U256::from(args.amount.as_u128())),
]);
let erc20_admin_address = current_address(current_account_id);
unwrap_res_or_finish!(
self.call(
&erc20_admin_address,
&erc20_token,
Wei::zero(),
[selector, tail.as_slice()].concat(),
u64::MAX,
Vec::new(), // TODO: are there values we should put here?
handler,
)
.and_then(|submit_result| {
match submit_result.status {
TransactionStatus::Succeed(_) => Ok(()),
TransactionStatus::Revert(bytes) => {
let error_message = crate::prelude::format!(
"Reverted with message: {}",
crate::prelude::String::from_utf8_lossy(&bytes)
);
Err(EngineError {
kind: EngineErrorKind::EvmError(ExitError::Other(
crate::prelude::Cow::from(error_message),
)),
gas_used: submit_result.gas_used,
})
}
TransactionStatus::OutOfFund => Err(EngineError {
kind: EngineErrorKind::EvmError(ExitError::OutOfFund),
gas_used: submit_result.gas_used,
}),
TransactionStatus::OutOfOffset => Err(EngineError {
kind: EngineErrorKind::EvmError(ExitError::OutOfOffset),
gas_used: submit_result.gas_used,
}),
TransactionStatus::OutOfGas => Err(EngineError {
kind: EngineErrorKind::EvmError(ExitError::OutOfGas),
gas_used: submit_result.gas_used,
}),
TransactionStatus::CallTooDeep => Err(EngineError {
kind: EngineErrorKind::EvmError(ExitError::CallTooDeep),
gas_used: submit_result.gas_used,
}),
}
}),
output_on_fail,
self.io
);
// TODO(marX)
// Everything succeed so return "0"
self.io.return_output(b"\"0\"");
}
}
pub fn submit<I: IO + Copy, E: Env, P: PromiseHandler>(
mut io: I,
env: &E,
transaction_bytes: &[u8],
state: EngineState,
current_account_id: AccountId,
relayer_address: Address,
handler: &mut P,
) -> EngineResult<SubmitResult> {
#[cfg(feature = "contract")]
let transaction: NormalizedEthTransaction = EthTransactionKind::try_from(transaction_bytes)
.map_err(EngineErrorKind::FailedTransactionParse)?
.into();
#[cfg(not(feature = "contract"))]
// The standalone engine must use the backwards compatible parser to reproduce the NEAR state,
// but the contract itself does not need to make such checks because it never executes historical
// transactions.
let transaction: NormalizedEthTransaction = {
let adapter =
aurora_engine_transactions::backwards_compatibility::EthTransactionKindAdapter::new(
ZERO_ADDRESS_FIX_HEIGHT,
);
let block_height = env.block_height();
let tx: EthTransactionKind = adapter
.try_parse_bytes(transaction_bytes, block_height)
.map_err(EngineErrorKind::FailedTransactionParse)?;
tx.into()
};
// Validate the chain ID, if provided inside the signature:
if let Some(chain_id) = transaction.chain_id {
if U256::from(chain_id) != U256::from(state.chain_id) {
return Err(EngineErrorKind::InvalidChainId.into());
}
}
// Retrieve the signer of the transaction:
let sender = transaction
.address
.ok_or(EngineErrorKind::InvalidSignature)?;
sdk::log!(crate::prelude::format!("signer_address {:?}", sender).as_str());
check_nonce(&io, &sender, &transaction.nonce)?;
// Check intrinsic gas is covered by transaction gas limit
match transaction.intrinsic_gas(crate::engine::CONFIG) {
None => {
return Err(EngineErrorKind::GasOverflow.into());
}
Some(intrinsic_gas) => {
if transaction.gas_limit < intrinsic_gas.into() {
return Err(EngineErrorKind::IntrinsicGasNotMet.into());
}
}
}
if transaction.max_priority_fee_per_gas > transaction.max_fee_per_gas {
return Err(EngineErrorKind::MaxPriorityGasFeeTooLarge.into());
}
let mut engine = Engine::new_with_state(state, sender, current_account_id, io, env);
let prepaid_amount = match engine.charge_gas(&sender, &transaction) {
Ok(gas_result) => gas_result,
Err(GasPaymentError::OutOfFund) => {
increment_nonce(&mut io, &sender);
let result = SubmitResult::new(TransactionStatus::OutOfFund, 0, vec![]);
return Ok(result);
}
Err(err) => {
return Err(EngineErrorKind::GasPayment(err).into());
}
};
let gas_limit: u64 = transaction
.gas_limit
.try_into()
.map_err(|_| EngineErrorKind::GasOverflow)?;
let access_list = transaction
.access_list
.into_iter()
.map(|a| (a.address, a.storage_keys))
.collect();
let result = if let Some(receiver) = transaction.to {
engine.call(
&sender,
&receiver,
transaction.value,
transaction.data,
gas_limit,
access_list,
handler,
)
// TODO: charge for storage
} else {
// Execute a contract deployment:
engine.deploy_code(
sender,
transaction.value,
transaction.data,
gas_limit,
access_list,
handler,
)
// TODO: charge for storage
};
// Give refund
let gas_used = match &result {
Ok(submit_result) => submit_result.gas_used,
Err(engine_err) => engine_err.gas_used,
};
refund_unused_gas(&mut io, &sender, gas_used, prepaid_amount, &relayer_address).map_err(
|e| EngineError {
gas_used,
kind: EngineErrorKind::GasPayment(e),
},
)?;
// return result to user
result
}
pub fn refund_on_error<I: IO + Copy, E: Env, P: PromiseHandler>(
io: I,
env: &E,
state: EngineState,
args: RefundCallArgs,
handler: &mut P,
) -> EngineResult<SubmitResult> {
let current_account_id = env.current_account_id();