Skip to content

Commit 0d2acf0

Browse files
authored
Fix(xcc): Ensure near_withdraw comes after ft_transfer (#864)
## Description The XCC feature was designed to allow users to spend their own wNEAR ERC-20 tokens on Aurora in Near native interaction as if it were the base token. This works by bridging the wNEAR from Aurora out to the user's XCC account, then unwrapping it. The Rainbow bridge team noticed an issue where it is possible for the `wrap.near:withdraw_near` promise to resolve before the `wrap.near:ft_transfer` promise. This causes the XCC flow to fail if the user's XCC account does not carry a wNEAR balance because we attempt to withdraw tokens we don't yet have. This PR aims to solve that issue. To see why this fix works, we need to know why the issue happens in the first place. The problem is the XCC flow used to use the `call` entry point to trigger the exit to Near function on the wNEAR ERC-20 token. That function invokes the exit to Near precompile which creates a promise to transfer the corresponding NEP-141 token from `aurora` to the destination account. However, that promise is not returned from `call` because instead it must return the EVM `SubmitResult` (the normal use-case for `call` is simply to invoke the EVM). By not returning the `ft_transfer` promise, it is disconnected from the subsequent execution graph and therefore Near does not make any guarantees about when it will resolve relative to other promises the execution will create. Under normal (non-congested) conditions, the `ft_transfer` does resolve first because there is one block before the `wrap.near:withdraw_near` call is created (since after `aurora:call` comes `xcc_router:unwrap_and_refund_storage` which then makes the withdraw call). However, if the shard containing `wrap.near` is congested then the `ft_transfer` call can delayed by one block and then need to execute in the same block as `near_withdraw`, resulting in a 50% chance of failure. Therefore, to fix the issue we must make sure the promise from the exit precompile is given as the return value of the call in the XCC flow to make sure it stays connected with the rest of the execution graph. Doing this will ensure `wrap.near:ft_transfer` resolves before `xcc_router:unwrap_and_refund_storage` is allowed to execute. To that end, in this PR I introduce a new private function called `withdraw_wnear_to_router`. The only purpose of this function is to make the call to the exit precompile while capturing its promise and then return that promise. With that context, this change should be pretty easy to follow. The new function is defined in `contract_methods::xcc`, and that logic is applied in both `lib.rs` and the standalone engine. ## Performance / NEAR gas cost considerations All costs should remain unchanged. The same work is done, just in a different method to allow the promise return. ## Testing The bug described above only occurs under congested conditions, so I do not know how to write a good test for it in near-workspaces. I am relying on the existing XCC tests to at least be sure this change does not break the feature.
1 parent 4527320 commit 0d2acf0

File tree

8 files changed

+234
-28
lines changed

8 files changed

+234
-28
lines changed

engine-precompiles/src/xcc.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ mod consts {
5252
pub(super) const ERR_SERIALIZE: &str = "ERR_XCC_CALL_SERIALIZE";
5353
pub(super) const ERR_STATIC: &str = "ERR_INVALID_IN_STATIC";
5454
pub(super) const ERR_DELEGATE: &str = "ERR_INVALID_IN_DELEGATE";
55+
pub(super) const ERR_XCC_ACCOUNT_ID: &str = "ERR_FAILED_TO_CREATE_XCC_ACCOUNT_ID";
5556
pub(super) const ROUTER_EXEC_NAME: &str = "execute";
5657
pub(super) const ROUTER_SCHEDULE_NAME: &str = "schedule";
5758
/// Solidity selector for the ERC-20 transferFrom function
@@ -130,7 +131,7 @@ impl<I: IO> HandleBasedPrecompile for CrossContractCall<I> {
130131
}
131132

132133
let sender = context.caller;
133-
let target_account_id = create_target_account_id(sender, self.engine_account_id.as_ref());
134+
let target_account_id = create_target_account_id(sender, self.engine_account_id.as_ref())?;
134135
let args = CrossContractCallArgs::try_from_slice(input)
135136
.map_err(|_| ExitError::Other(Cow::from(consts::ERR_INVALID_INPUT)))?;
136137
let (promise, attached_near) = match args {
@@ -295,10 +296,13 @@ fn transfer_from_args(from: H160, to: H160, amount: U256) -> Vec<u8> {
295296
[&consts::TRANSFER_FROM_SELECTOR, args.as_slice()].concat()
296297
}
297298

298-
fn create_target_account_id(sender: H160, engine_account_id: &str) -> AccountId {
299+
fn create_target_account_id(
300+
sender: H160,
301+
engine_account_id: &str,
302+
) -> Result<AccountId, PrecompileFailure> {
299303
format!("{}.{}", hex::encode(sender.as_bytes()), engine_account_id)
300304
.parse()
301-
.unwrap_or_default()
305+
.map_err(|_| revert_with_message(consts::ERR_XCC_ACCOUNT_ID))
302306
}
303307

304308
fn revert_with_message(message: &str) -> PrecompileFailure {

engine-standalone-storage/src/sync/mod.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,10 @@ pub fn parse_transaction_kind(
189189
})?;
190190
TransactionKind::FactorySetWNearAddress(address)
191191
}
192+
TransactionKindTag::WithdrawWnearToRouter => {
193+
let args = xcc::WithdrawWnearToRouterArgs::try_from_slice(&bytes).map_err(f)?;
194+
TransactionKind::WithdrawWnearToRouter(args)
195+
}
192196
TransactionKindTag::SetUpgradeDelayBlocks => {
193197
let args = parameters::SetUpgradeDelayBlocksArgs::try_from_slice(&bytes).map_err(f)?;
194198
TransactionKind::SetUpgradeDelayBlocks(args)
@@ -644,6 +648,12 @@ fn non_submit_execute<I: IO + Copy>(
644648

645649
None
646650
}
651+
TransactionKind::WithdrawWnearToRouter(_) => {
652+
let mut handler = crate::promise::NoScheduler { promise_data };
653+
let result = contract_methods::xcc::withdraw_wnear_to_router(io, env, &mut handler)?;
654+
655+
Some(TransactionExecutionResult::Submit(Ok(result)))
656+
}
647657
TransactionKind::Unknown => None,
648658
// Not handled in this function; is handled by the general `execute_transaction` function
649659
TransactionKind::Submit(_) | TransactionKind::SubmitWithArgs(_) => unreachable!(),

engine-standalone-storage/src/sync/types.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use aurora_engine::xcc::{AddressVersionUpdateArgs, FundXccArgs};
55
use aurora_engine_transactions::{EthTransactionKind, NormalizedEthTransaction};
66
use aurora_engine_types::account_id::AccountId;
77
use aurora_engine_types::parameters::silo;
8+
use aurora_engine_types::parameters::xcc::WithdrawWnearToRouterArgs;
89
use aurora_engine_types::types::Address;
910
use aurora_engine_types::{
1011
borsh::{self, BorshDeserialize, BorshSerialize},
@@ -146,6 +147,8 @@ pub enum TransactionKind {
146147
FactoryUpdateAddressVersion(AddressVersionUpdateArgs),
147148
FactorySetWNearAddress(Address),
148149
FundXccSubAccount(FundXccArgs),
150+
/// Self-call used during XCC flow to move wNEAR tokens to user's XCC account
151+
WithdrawWnearToRouter(WithdrawWnearToRouterArgs),
149152
/// Pause the contract
150153
PauseContract,
151154
/// Resume the contract
@@ -374,6 +377,31 @@ impl TransactionKind {
374377
},
375378
)
376379
}
380+
Self::WithdrawWnearToRouter(args) => {
381+
let recipient = AccountId::new(&format!(
382+
"{}.{}",
383+
args.target.encode(),
384+
engine_account.as_ref()
385+
))
386+
.unwrap_or_else(|_| engine_account.clone());
387+
let wnear_address = storage
388+
.with_engine_access(block_height, transaction_position, &[], |io| {
389+
aurora_engine_precompiles::xcc::state::get_wnear_address(&io)
390+
})
391+
.result;
392+
let call_args = aurora_engine::xcc::withdraw_wnear_call_args(
393+
&recipient,
394+
args.amount,
395+
wnear_address,
396+
);
397+
Self::Call(call_args).eth_repr(
398+
engine_account,
399+
caller,
400+
block_height,
401+
transaction_position,
402+
storage,
403+
)
404+
}
377405
Self::Deposit(_) => Self::no_evm_execution("deposit"),
378406
Self::FtTransferCall(_) => Self::no_evm_execution("ft_transfer_call"),
379407
Self::FinishDeposit(_) => Self::no_evm_execution("finish_deposit"),
@@ -550,6 +578,8 @@ pub enum TransactionKindTag {
550578
RemoveEntryFromWhitelist,
551579
#[strum(serialize = "mirror_erc20_token_callback")]
552580
MirrorErc20TokenCallback,
581+
#[strum(serialize = "withdraw_wnear_to_router")]
582+
WithdrawWnearToRouter,
553583
Unknown,
554584
}
555585

@@ -592,6 +622,7 @@ impl TransactionKind {
592622
Self::NewEngine(args) => args.try_to_vec().unwrap_or_default(),
593623
Self::FactoryUpdateAddressVersion(args) => args.try_to_vec().unwrap_or_default(),
594624
Self::FundXccSubAccount(args) => args.try_to_vec().unwrap_or_default(),
625+
Self::WithdrawWnearToRouter(args) => args.try_to_vec().unwrap_or_default(),
595626
Self::PauseContract | Self::ResumeContract | Self::Unknown => Vec::new(),
596627
Self::SetKeyManager(args) => args.try_to_vec().unwrap_or_default(),
597628
Self::AddRelayerKey(args) | Self::RemoveRelayerKey(args) => {
@@ -641,6 +672,7 @@ impl From<&TransactionKind> for TransactionKindTag {
641672
TransactionKind::FactoryUpdate(_) => Self::FactoryUpdate,
642673
TransactionKind::FactoryUpdateAddressVersion(_) => Self::FactoryUpdateAddressVersion,
643674
TransactionKind::FactorySetWNearAddress(_) => Self::FactorySetWNearAddress,
675+
TransactionKind::WithdrawWnearToRouter(_) => Self::WithdrawWnearToRouter,
644676
TransactionKind::SetOwner(_) => Self::SetOwner,
645677
TransactionKind::SubmitWithArgs(_) => Self::SubmitWithArgs,
646678
TransactionKind::SetUpgradeDelayBlocks(_) => Self::SetUpgradeDelayBlocks,
@@ -886,6 +918,7 @@ enum BorshableTransactionKind<'a> {
886918
SetWhitelistStatus(Cow<'a, silo::WhitelistStatusArgs>),
887919
SetEthConnectorContractAccount(Cow<'a, parameters::SetEthConnectorContractAccountArgs>),
888920
MirrorErc20TokenCallback(Cow<'a, parameters::MirrorErc20TokenArgs>),
921+
WithdrawWnearToRouter(Cow<'a, WithdrawWnearToRouterArgs>),
889922
}
890923

891924
impl<'a> From<&'a TransactionKind> for BorshableTransactionKind<'a> {
@@ -924,6 +957,9 @@ impl<'a> From<&'a TransactionKind> for BorshableTransactionKind<'a> {
924957
TransactionKind::FactorySetWNearAddress(address) => {
925958
Self::FactorySetWNearAddress(*address)
926959
}
960+
TransactionKind::WithdrawWnearToRouter(x) => {
961+
Self::WithdrawWnearToRouter(Cow::Borrowed(x))
962+
}
927963
TransactionKind::Unknown => Self::Unknown,
928964
TransactionKind::PausePrecompiles(x) => Self::PausePrecompiles(Cow::Borrowed(x)),
929965
TransactionKind::ResumePrecompiles(x) => Self::ResumePrecompiles(Cow::Borrowed(x)),
@@ -1051,6 +1087,9 @@ impl<'a> TryFrom<BorshableTransactionKind<'a>> for TransactionKind {
10511087
BorshableTransactionKind::MirrorErc20TokenCallback(x) => {
10521088
Ok(Self::MirrorErc20TokenCallback(x.into_owned()))
10531089
}
1090+
BorshableTransactionKind::WithdrawWnearToRouter(x) => {
1091+
Ok(Self::WithdrawWnearToRouter(x.into_owned()))
1092+
}
10541093
}
10551094
}
10561095
}

engine-types/src/parameters/xcc.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use crate::account_id::AccountId;
22
use crate::borsh::{self, BorshDeserialize, BorshSerialize};
3-
use crate::types::Address;
3+
use crate::types::{Address, Yocto};
44

55
#[derive(Debug, Clone, PartialEq, Eq, BorshDeserialize, BorshSerialize)]
66
pub struct AddressVersionUpdateArgs {
@@ -14,6 +14,12 @@ pub struct FundXccArgs {
1414
pub wnear_account_id: Option<AccountId>,
1515
}
1616

17+
#[derive(Debug, Clone, PartialEq, Eq, BorshDeserialize, BorshSerialize)]
18+
pub struct WithdrawWnearToRouterArgs {
19+
pub target: Address,
20+
pub amount: Yocto,
21+
}
22+
1723
/// Type wrapper for version of router contracts.
1824
#[derive(
1925
Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, BorshDeserialize, BorshSerialize,

engine/src/contract_methods/evm_transactions.rs

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -56,17 +56,6 @@ pub fn call<I: IO + Copy, E: Env, H: PromiseHandler>(
5656
let current_account_id = env.current_account_id();
5757
let predecessor_account_id = env.predecessor_account_id();
5858

59-
// During the XCC flow the Engine will call itself to move wNEAR
60-
// to the user's sub-account. We do not want this move to happen
61-
// if prior promises in the flow have failed.
62-
if current_account_id == predecessor_account_id {
63-
let check_promise: Result<(), &[u8]> = match handler.promise_result_check() {
64-
Some(true) | None => Ok(()),
65-
Some(false) => Err(b"ERR_CALLBACK_OF_FAILED_PROMISE"),
66-
};
67-
check_promise?;
68-
}
69-
7059
let mut engine: Engine<_, E, AuroraModExp> = Engine::new_with_state(
7160
state,
7261
predecessor_address(&predecessor_account_id),

engine/src/contract_methods/xcc.rs

Lines changed: 55 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,69 @@
11
use crate::{
2-
contract_methods::{require_owner_only, require_running, ContractError},
2+
contract_methods::{predecessor_address, require_owner_only, require_running, ContractError},
3+
engine::Engine,
34
errors,
4-
hashchain::with_hashchain,
5+
hashchain::{with_hashchain, with_logs_hashchain},
56
state, xcc,
67
};
8+
use aurora_engine_modexp::AuroraModExp;
79
use aurora_engine_sdk::{
810
env::Env,
911
io::{StorageIntermediate, IO},
1012
promise::PromiseHandler,
1113
};
12-
use aurora_engine_types::{borsh::BorshSerialize, types::Address};
14+
use aurora_engine_types::{
15+
account_id::AccountId,
16+
borsh::BorshSerialize,
17+
format,
18+
parameters::{engine::SubmitResult, xcc::WithdrawWnearToRouterArgs},
19+
types::Address,
20+
};
1321
use function_name::named;
1422

23+
#[named]
24+
pub fn withdraw_wnear_to_router<I: IO + Copy, E: Env, H: PromiseHandler>(
25+
io: I,
26+
env: &E,
27+
handler: &mut H,
28+
) -> Result<SubmitResult, ContractError> {
29+
with_logs_hashchain(io, env, function_name!(), |io| {
30+
let state = state::get_state(&io)?;
31+
require_running(&state)?;
32+
env.assert_private_call()?;
33+
if matches!(handler.promise_result_check(), Some(false)) {
34+
return Err(b"ERR_CALLBACK_OF_FAILED_PROMISE".into());
35+
}
36+
let args: WithdrawWnearToRouterArgs = io.read_input_borsh()?;
37+
let current_account_id = env.current_account_id();
38+
let recipient = AccountId::new(&format!(
39+
"{}.{}",
40+
args.target.encode(),
41+
current_account_id.as_ref()
42+
))?;
43+
let wnear_address = aurora_engine_precompiles::xcc::state::get_wnear_address(&io);
44+
let mut engine: Engine<_, E, AuroraModExp> = Engine::new_with_state(
45+
state,
46+
predecessor_address(&current_account_id),
47+
current_account_id,
48+
io,
49+
env,
50+
);
51+
let (result, ids) = xcc::withdraw_wnear_to_router(
52+
&recipient,
53+
args.amount,
54+
wnear_address,
55+
&mut engine,
56+
handler,
57+
)?;
58+
if !result.status.is_ok() {
59+
return Err(b"ERR_WITHDRAW_FAILED".into());
60+
}
61+
let id = ids.last().ok_or(b"ERR_NO_PROMISE_CREATED")?;
62+
handler.promise_return(*id);
63+
Ok(result)
64+
})
65+
}
66+
1567
#[named]
1668
pub fn factory_update<I: IO + Copy, E: Env>(io: I, env: &E) -> Result<(), ContractError> {
1769
with_hashchain(io, env, function_name!(), |mut io| {

engine/src/lib.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -388,6 +388,19 @@ mod contract {
388388
.sdk_unwrap();
389389
}
390390

391+
/// A private function (only callable by the contract itself) used as part of the XCC flow.
392+
/// This function uses the exit to Near precompile to move wNear from Aurora to a user's
393+
/// XCC account.
394+
#[no_mangle]
395+
pub extern "C" fn withdraw_wnear_to_router() {
396+
let io = Runtime;
397+
let env = Runtime;
398+
let mut handler = Runtime;
399+
contract_methods::xcc::withdraw_wnear_to_router(io, &env, &mut handler)
400+
.map_err(ContractError::msg)
401+
.sdk_unwrap();
402+
}
403+
391404
/// Mirror existing ERC-20 token on the main Aurora contract.
392405
/// Notice: It works if the SILO mode is on.
393406
#[no_mangle]

0 commit comments

Comments
 (0)