-
Notifications
You must be signed in to change notification settings - Fork 20
Currency swap precompile #682
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 14 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
de3f257
Initial currency swap precompile implementation
MOZGIII 5c70ec9
Add initial tests setup
MOZGIII 9c5cfb6
wip
MOZGIII 6378e7f
Implement tests and corrections
MOZGIII 024506f
Remove unused PrecompileHandle mock
MOZGIII 845cef6
More tests
MOZGIII d269f45
Correct the wording in the tests
MOZGIII a8e66ed
More tests
MOZGIII c5694e5
Fix a typo at the error message
MOZGIII 33ec84b
Rework the CurrencySwap trait error behaviour
MOZGIII c799417
Add more comments to the tests
MOZGIII 94a6f02
More tests
MOZGIII 57bd825
Add a check for junk at the end of the input
MOZGIII a847caf
Fix the docs
MOZGIII dc1ff81
Rename the balance var to be better correlated with the account naming
MOZGIII 382afc1
Reduce the dependencies set
MOZGIII 0ba50ca
Fix the docs again
MOZGIII File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| [package] | ||
| name = "precompile-currency-swap" | ||
| version = "0.1.0" | ||
| edition = "2021" | ||
| publish = false | ||
|
|
||
| [dependencies] | ||
| precompile-utils = { path = "../precompile-utils", default-features = false } | ||
| primitives-currency-swap = { path = "../primitives-currency-swap", default-features = false } | ||
|
|
||
| codec = { package = "parity-scale-codec", version = "3.2.2", default-features = false, features = ["derive"] } | ||
| fp-evm = { git = "https://github.com/humanode-network/frontier", branch = "locked/polkadot-v0.9.38", default-features = false } | ||
| frame-support = { default-features = false, git = "https://github.com/humanode-network/substrate", branch = "locked/polkadot-v0.9.38" } | ||
| frame-system = { default-features = false, git = "https://github.com/humanode-network/substrate", branch = "locked/polkadot-v0.9.38" } | ||
| getrandom = { version = "0.2", features = ["js"] } | ||
| num_enum = { version = "0.6.0", default-features = false } | ||
| pallet-evm = { git = "https://github.com/humanode-network/frontier", branch = "locked/polkadot-v0.9.38", default-features = false } | ||
| scale-info = { version = "2.5.0", default-features = false, features = ["derive"] } | ||
| serde = { version = "1", features = ["derive"], optional = true } | ||
| sp-core = { default-features = false, git = "https://github.com/humanode-network/substrate", branch = "locked/polkadot-v0.9.38" } | ||
| sp-runtime = { default-features = false, git = "https://github.com/humanode-network/substrate", branch = "locked/polkadot-v0.9.38" } | ||
| sp-std = { default-features = false, git = "https://github.com/humanode-network/substrate", branch = "locked/polkadot-v0.9.38" } | ||
|
|
||
| [dev-dependencies] | ||
| hex-literal = "0.4" | ||
| mockall = "0.11" | ||
| pallet-balances = { default-features = false, git = "https://github.com/humanode-network/substrate", branch = "locked/polkadot-v0.9.38" } | ||
| pallet-evm = { default-features = false, git = "https://github.com/humanode-network/frontier", branch = "locked/polkadot-v0.9.38" } | ||
| pallet-evm-balances = { default-features = false, git = "https://github.com/humanode-network/frontier", branch = "locked/polkadot-v0.9.38" } | ||
| pallet-evm-system = { default-features = false, git = "https://github.com/humanode-network/frontier", branch = "locked/polkadot-v0.9.38" } | ||
| pallet-timestamp = { default-features = false, git = "https://github.com/humanode-network/substrate", branch = "locked/polkadot-v0.9.38" } | ||
| sp-io = { default-features = false, git = "https://github.com/humanode-network/substrate", branch = "locked/polkadot-v0.9.38" } | ||
|
|
||
| [features] | ||
| default = ["std"] | ||
| std = [ | ||
| "codec/std", | ||
| "fp-evm/std", | ||
| "frame-support/std", | ||
| "frame-system/std", | ||
| "getrandom/std", | ||
| "num_enum/std", | ||
| "pallet-balances/std", | ||
| "pallet-evm-balances/std", | ||
| "pallet-evm-system/std", | ||
| "pallet-evm/std", | ||
| "pallet-timestamp/std", | ||
| "precompile-utils/std", | ||
| "primitives-currency-swap/std", | ||
| "scale-info/std", | ||
| "serde", | ||
| "sp-core/std", | ||
| "sp-io/std", | ||
| "sp-runtime/std", | ||
| "sp-std/std", | ||
| ] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| // SPDX-License-Identifier: UNLICENSED | ||
|
|
||
| pragma solidity >=0.7.0 <0.9.0; | ||
|
|
||
| /** | ||
| * @title Currency Swap Interface | ||
| * | ||
| * An interface enabling swapping the funds from EVM accounts to | ||
| * native Substrate accounts. | ||
| * | ||
| * Address: 0x0000000000000000000000000000000000000900 | ||
| */ | ||
| interface CurrencySwap { | ||
| /** | ||
| * Transfer the funds from an EVM account to native substrate account. | ||
| * Selector: 76467cbd | ||
| * | ||
| * @param nativeAddress The native address to send the funds to. | ||
| * @return success Whether or not the swap was successful. | ||
| */ | ||
| function swap(bytes32 nativeAddress) external payable returns (bool success); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,143 @@ | ||
| //! A precompile to swap EVM tokens with native chain tokens. | ||
|
|
||
| #![cfg_attr(not(feature = "std"), no_std)] | ||
|
|
||
| use frame_support::traits::tokens::currency::Currency; | ||
| use pallet_evm::{ | ||
| ExitError, ExitRevert, Precompile, PrecompileFailure, PrecompileHandle, PrecompileOutput, | ||
| PrecompileResult, | ||
| }; | ||
| use precompile_utils::{succeed, EvmDataWriter, EvmResult, PrecompileHandleExt}; | ||
| use sp_core::{Get, H160, H256, U256}; | ||
| use sp_std::marker::PhantomData; | ||
| use sp_std::prelude::*; | ||
|
|
||
| #[cfg(test)] | ||
| mod mock; | ||
|
|
||
| #[cfg(test)] | ||
| mod tests; | ||
|
|
||
| /// Possible actions for this interface. | ||
| #[precompile_utils::generate_function_selector] | ||
| #[derive(Debug, PartialEq)] | ||
| pub enum Action { | ||
| /// Swap EVM tokens to native tokens. | ||
| Swap = "swap(bytes32)", | ||
| } | ||
|
|
||
| /// Exposes the currency swap interface to EVM. | ||
| pub struct CurrencySwap<CurrencySwapT, AccountIdFrom, AccountIdTo, GasCost>( | ||
| PhantomData<(CurrencySwapT, AccountIdFrom, AccountIdTo, GasCost)>, | ||
| ) | ||
| where | ||
| AccountIdFrom: From<H160>, | ||
| AccountIdTo: From<[u8; 32]>, | ||
| CurrencySwapT: primitives_currency_swap::CurrencySwap<AccountIdFrom, AccountIdTo>, | ||
| FromBalanceFor<CurrencySwapT, AccountIdFrom, AccountIdTo>: TryFrom<U256>, | ||
| GasCost: Get<u64>; | ||
|
|
||
| impl<CurrencySwapT, AccountIdFrom, AccountIdTo, GasCost> Precompile | ||
| for CurrencySwap<CurrencySwapT, AccountIdFrom, AccountIdTo, GasCost> | ||
| where | ||
| AccountIdFrom: From<H160>, | ||
| AccountIdTo: From<[u8; 32]>, | ||
| CurrencySwapT: primitives_currency_swap::CurrencySwap<AccountIdFrom, AccountIdTo>, | ||
| FromBalanceFor<CurrencySwapT, AccountIdFrom, AccountIdTo>: TryFrom<U256>, | ||
| GasCost: Get<u64>, | ||
| { | ||
| fn execute(handle: &mut impl PrecompileHandle) -> PrecompileResult { | ||
| handle.record_cost(GasCost::get())?; | ||
|
|
||
| let selector = handle | ||
| .read_selector() | ||
| .map_err(|_| PrecompileFailure::Error { | ||
| exit_status: ExitError::Other("invalid function selector".into()), | ||
| })?; | ||
|
|
||
| match selector { | ||
| Action::Swap => Self::swap(handle), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Utility alias for easy access to [`primitives_currency_swap::CurrencySwap::From::Balance`] type. | ||
| type FromBalanceFor<T, AccountIdFrom, AccountIdTo> = | ||
| <FromCurrencyFor<T, AccountIdFrom, AccountIdTo> as Currency<AccountIdFrom>>::Balance; | ||
|
|
||
| /// Utility alias for easy access to [`primitives_currency_swap::CurrencySwap::From`] type. | ||
| type FromCurrencyFor<T, AccountIdFrom, AccountIdTo> = | ||
| <T as primitives_currency_swap::CurrencySwap<AccountIdFrom, AccountIdTo>>::From; | ||
|
|
||
| impl<CurrencySwapT, AccountIdFrom, AccountIdTo, GasCost> | ||
| CurrencySwap<CurrencySwapT, AccountIdFrom, AccountIdTo, GasCost> | ||
| where | ||
| AccountIdFrom: From<H160>, | ||
| AccountIdTo: From<[u8; 32]>, | ||
| CurrencySwapT: primitives_currency_swap::CurrencySwap<AccountIdFrom, AccountIdTo>, | ||
| FromBalanceFor<CurrencySwapT, AccountIdFrom, AccountIdTo>: TryFrom<U256>, | ||
| GasCost: Get<u64>, | ||
| { | ||
| /// Swap EVM tokens to native tokens. | ||
| fn swap(handle: &mut impl PrecompileHandle) -> EvmResult<PrecompileOutput> { | ||
| let mut input = handle.read_input()?; | ||
|
|
||
| let fp_evm::Context { | ||
| address, | ||
| apparent_value: value, | ||
| .. | ||
| } = handle.context(); | ||
|
|
||
| // Here we must withdraw from self (i.e. from the precompile address, not from the caller | ||
| // address), since the funds have already been transferred to us (precompile) as this point. | ||
| let from: AccountIdFrom = (*address).into(); | ||
|
|
||
| let value: FromBalanceFor<CurrencySwapT, AccountIdFrom, AccountIdTo> = | ||
| (*value).try_into().map_err(|_| PrecompileFailure::Error { | ||
| exit_status: ExitError::Other("value is out of bounds".into()), | ||
| })?; | ||
|
|
||
| input | ||
| .expect_arguments(1) | ||
| .map_err(|_| PrecompileFailure::Error { | ||
| exit_status: ExitError::Other("exactly one argument is expected".into()), | ||
| })?; | ||
|
|
||
| let to: H256 = input.read()?; | ||
| let to: [u8; 32] = to.into(); | ||
| let to: AccountIdTo = to.into(); | ||
|
|
||
| let junk_data = input.read_till_end()?; | ||
| if !junk_data.is_empty() { | ||
| return Err(PrecompileFailure::Error { | ||
| exit_status: ExitError::Other("junk at the end of input".into()), | ||
| }); | ||
| } | ||
|
|
||
| let imbalance = CurrencySwapT::From::withdraw( | ||
| &from, | ||
| value, | ||
| frame_support::traits::WithdrawReasons::TRANSFER, | ||
| frame_support::traits::ExistenceRequirement::AllowDeath, | ||
| ) | ||
| .map_err(|error| match error { | ||
| sp_runtime::DispatchError::Token(sp_runtime::TokenError::NoFunds) => { | ||
| PrecompileFailure::Error { | ||
| exit_status: ExitError::OutOfFund, | ||
| } | ||
| } | ||
| _ => PrecompileFailure::Error { | ||
| exit_status: ExitError::Other("unable to withdraw funds".into()), | ||
| }, | ||
| })?; | ||
|
|
||
| let imbalance = CurrencySwapT::swap(imbalance).map_err(|_| PrecompileFailure::Revert { | ||
| exit_status: ExitRevert::Reverted, | ||
| output: "unable to swap the currency".into(), | ||
| })?; | ||
|
|
||
| CurrencySwapT::To::resolve_creating(&to, imbalance); | ||
|
|
||
| Ok(succeed(EvmDataWriter::new().write(true).build())) | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.