Skip to content
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

precompile for liquid-crowdloan #2575

Merged
merged 8 commits into from
Jul 13, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

66 changes: 38 additions & 28 deletions modules/liquid-crowdloan/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ pub mod module {
}

#[pallet::event]
#[pallet::generate_deposit(fn deposit_event)]
#[pallet::generate_deposit(pub(crate) fn deposit_event)]
pub enum Event<T: Config> {
/// Liquid Crowdloan asset was redeemed.
Redeemed { currency_id: CurrencyId, amount: Balance },
Expand All @@ -100,33 +100,7 @@ pub mod module {
pub fn redeem(origin: OriginFor<T>, #[pallet::compact] amount: Balance) -> DispatchResult {
let who = ensure_signed(origin)?;

let (currency_id, redeem_amount) = if let Some(redeem_currency_id) = RedeemCurrencyId::<T>::get() {
// redeem the RedeemCurrencyId
// amount_pect = amount / lcdot_total_supply
// amount_redeem = amount_pect * redeem_currency_balance

let redeem_currency_balance = T::Currency::free_balance(redeem_currency_id, &Self::account_id());
let lcdot_total_supply = T::Currency::total_issuance(T::LiquidCrowdloanCurrencyId::get());

let amount_redeem = amount
.checked_mul(redeem_currency_balance)
.and_then(|x| x.checked_div(lcdot_total_supply))
.ok_or(ArithmeticError::Overflow)?;

(redeem_currency_id, amount_redeem)
} else {
// redeem DOT
let currency_id = T::RelayChainCurrencyId::get();
(currency_id, amount)
};

T::Currency::withdraw(T::LiquidCrowdloanCurrencyId::get(), &who, amount)?;
T::Currency::transfer(currency_id, &Self::account_id(), &who, redeem_amount)?;

Self::deposit_event(Event::Redeemed {
currency_id,
amount: redeem_amount,
});
Self::do_redeem(&who, amount)?;

Ok(())
}
Expand Down Expand Up @@ -175,4 +149,40 @@ impl<T: Config> Pallet<T> {
pub fn account_id() -> T::AccountId {
T::PalletId::get().into_account_truncating()
}

pub fn do_redeem(who: &T::AccountId, amount: Balance) -> Result<Balance, DispatchError> {
let (currency_id, redeem_amount) = if let Some(redeem_currency_id) = RedeemCurrencyId::<T>::get() {
// redeem the RedeemCurrencyId
// amount_pect = amount / lcdot_total_supply
// amount_redeem = amount_pect * redeem_currency_balance

let redeem_currency_balance = T::Currency::free_balance(redeem_currency_id, &Self::account_id());
let lcdot_total_supply = T::Currency::total_issuance(T::LiquidCrowdloanCurrencyId::get());

let amount_redeem = amount
.checked_mul(redeem_currency_balance)
.and_then(|x| x.checked_div(lcdot_total_supply))
.ok_or(ArithmeticError::Overflow)?;

(redeem_currency_id, amount_redeem)
} else {
// redeem DOT
let currency_id = T::RelayChainCurrencyId::get();
(currency_id, amount)
};

T::Currency::withdraw(T::LiquidCrowdloanCurrencyId::get(), &who, amount)?;
T::Currency::transfer(currency_id, &Self::account_id(), &who, redeem_amount)?;

Self::deposit_event(Event::Redeemed {
currency_id,
amount: redeem_amount,
});

Ok(redeem_amount)
}

pub fn redeem_currency() -> CurrencyId {
RedeemCurrencyId::<T>::get().unwrap_or_else(|| T::RelayChainCurrencyId::get())
}
}
2 changes: 2 additions & 0 deletions runtime/common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ module-cdp-engine = { path = "../../modules/cdp-engine", default-features = fals
module-cdp-treasury = { path = "../../modules/cdp-treasury", default-features = false, optional = true }
module-incentives = { path = "../../modules/incentives", default-features = false }
module-transaction-pause = { path = "../../modules/transaction-pause", default-features = false }
module-liquid-crowdloan = { path = "../../modules/liquid-crowdloan", default-features = false }

# orml
orml-oracle = { path = "../../orml/oracle", default-features = false }
Expand Down Expand Up @@ -142,6 +143,7 @@ std = [
"module-support/std",
"module-transaction-pause/std",
"module-transaction-payment/std",
"module-liquid-crowdloan/std",
"primitives/std",

"nutsfinance-stable-asset/std",
Expand Down
286 changes: 286 additions & 0 deletions runtime/common/src/precompile/liquid_crowdloan.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,286 @@
// This file is part of Acala.

// Copyright (C) 2020-2023 Acala Foundation.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use super::{
input::{Input, InputPricer, InputT, Output},
target_gas_limit,
};
use crate::WeightToGas;
use frame_support::log;
use module_evm::{
precompiles::Precompile,
runner::state::{PrecompileFailure, PrecompileOutput, PrecompileResult},
Context, ExitError, ExitRevert, ExitSucceed,
};
use module_liquid_crowdloan::WeightInfo;
use module_support::Erc20InfoMapping as _;
use num_enum::{IntoPrimitive, TryFromPrimitive};
use sp_core::Get;
use sp_runtime::{traits::Convert, RuntimeDebug};
use sp_std::{marker::PhantomData, prelude::*};

/// The `LiquidCrowdloan` impl precompile.
pub struct LiquidCrowdloanPrecompile<R>(PhantomData<R>);

#[module_evm_utility_macro::generate_function_selector]
#[derive(RuntimeDebug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive)]
#[repr(u32)]
pub enum Action {
Redeem = "redeem(address,uint256)",
GetRedeemCurrency = "getRedeemCurrency()",
}

impl<Runtime> Precompile for LiquidCrowdloanPrecompile<Runtime>
where
Runtime: module_evm::Config + module_prices::Config + module_liquid_crowdloan::Config,
{
fn execute(input: &[u8], target_gas: Option<u64>, _context: &Context, _is_static: bool) -> PrecompileResult {
let input = Input::<Action, Runtime::AccountId, Runtime::AddressMapping, Runtime::Erc20InfoMapping>::new(
input,
target_gas_limit(target_gas),
);

let gas_cost = Pricer::<Runtime>::cost(&input)?;

if let Some(gas_limit) = target_gas {
if gas_limit < gas_cost {
return Err(PrecompileFailure::Error {
exit_status: ExitError::OutOfGas,
});
}
}

let action = input.action()?;

match action {
Action::Redeem => {
let who = input.account_id_at(1)?;
let amount = input.balance_at(2)?;

let redeem_amount =
<module_liquid_crowdloan::Pallet<Runtime>>::do_redeem(&who, amount).map_err(|e| {
PrecompileFailure::Revert {
exit_status: ExitRevert::Reverted,
output: Output::encode_error_msg("LiquidCrowdloan redeem failed", e),
cost: target_gas_limit(target_gas).unwrap_or_default(),
}
})?;

log::debug!(target: "evm", "liuqid_crowdloan: Redeem who: {:?}, amount: {:?}, output: {:?}", who, amount, redeem_amount);
Ok(PrecompileOutput {
exit_status: ExitSucceed::Returned,
cost: gas_cost,
output: Output::encode_uint(redeem_amount),
logs: Default::default(),
})
}
Action::GetRedeemCurrency => {
let currency_id = <module_liquid_crowdloan::Pallet<Runtime>>::redeem_currency();
let address = <Runtime as module_prices::Config>::Erc20InfoMapping::encode_evm_address(currency_id)
.unwrap_or_default();
xlc marked this conversation as resolved.
Show resolved Hide resolved

log::debug!(target: "evm", "liuqid_crowdloan: GetRedeemCurrency output: {:?}", currency_id);
Ok(PrecompileOutput {
exit_status: ExitSucceed::Returned,
cost: gas_cost,
output: Output::encode_address(address),
logs: Default::default(),
})
}
}
}
}

struct Pricer<R>(PhantomData<R>);

impl<Runtime> Pricer<Runtime>
where
Runtime: module_evm::Config + module_prices::Config + module_liquid_crowdloan::Config,
{
const BASE_COST: u64 = 200;

fn cost(
input: &Input<Action, Runtime::AccountId, Runtime::AddressMapping, Runtime::Erc20InfoMapping>,
) -> Result<u64, PrecompileFailure> {
let action = input.action()?;

let cost = match action {
Action::Redeem => {
let read_account = InputPricer::<Runtime>::read_accounts(1);
let weight = <Runtime as module_liquid_crowdloan::Config>::WeightInfo::redeem();

Self::BASE_COST
.saturating_add(read_account)
.saturating_add(WeightToGas::convert(weight))
}
Action::GetRedeemCurrency => {
let weight = <Runtime as frame_system::Config>::DbWeight::get().reads(1);

Self::BASE_COST.saturating_add(WeightToGas::convert(weight))
}
};
Ok(Self::BASE_COST.saturating_add(cost))
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::precompile::mock::{
bob, bob_evm_addr, new_test_ext, Currencies, LiquidCrowdloan, LiquidCrowdloanPalletId, RuntimeOrigin, Test,
DOT, LCDOT, LDOT,
};
use frame_support::assert_ok;
use hex_literal::hex;
use orml_traits::MultiCurrency;
use sp_runtime::traits::AccountIdConversion;

type LiquidCrowdloanPrecompile = crate::precompile::LiquidCrowdloanPrecompile<Test>;

#[test]
fn redeem_dot() {
new_test_ext().execute_with(|| {
let context = Context {
address: Default::default(),
caller: bob_evm_addr(),
apparent_value: Default::default(),
};

assert_ok!(Currencies::update_balance(
RuntimeOrigin::root(),
bob(),
LCDOT,
1_000_000_000
));

assert_ok!(Currencies::update_balance(
RuntimeOrigin::root(),
LiquidCrowdloanPalletId::get().into_account_truncating(),
DOT,
1_000_000_000
));

// redeem(address,uint256) -> 1e9a6950
// who
// amount 1e9
let input = hex!(
xlc marked this conversation as resolved.
Show resolved Hide resolved
"
1e9a6950
000000000000000000000000 1000000000000000000000000000000000000002
00000000000000000000000000000000 0000000000000000000000003b9aca00
"
);

// 1e9
let expected_output = hex! {"
00000000000000000000000000000000 0000000000000000000000003b9aca00
"};

let res = LiquidCrowdloanPrecompile::execute(&input, None, &context, false).unwrap();
assert_eq!(res.exit_status, ExitSucceed::Returned);
assert_eq!(res.output, expected_output.to_vec());

assert_eq!(Currencies::free_balance(DOT, &bob()), 1_000_000_000);
assert_eq!(Currencies::free_balance(LCDOT, &bob()), 0);
});
}

#[test]
fn redeem_ldot() {
new_test_ext().execute_with(|| {
let context = Context {
address: Default::default(),
caller: bob_evm_addr(),
apparent_value: Default::default(),
};

assert_ok!(Currencies::update_balance(
RuntimeOrigin::root(),
bob(),
LCDOT,
1_000_000_000
));

assert_ok!(Currencies::update_balance(
RuntimeOrigin::root(),
LiquidCrowdloanPalletId::get().into_account_truncating(),
LDOT,
11_000_000_000
));

assert_ok!(LiquidCrowdloan::set_redeem_currency_id(RuntimeOrigin::root(), LDOT));

// redeem(address,uint256) -> 1e9a6950
// who
// amount 1e9
let input = hex!(
"
1e9a6950
000000000000000000000000 1000000000000000000000000000000000000002
00000000000000000000000000000000 0000000000000000000000003b9aca00
"
);

// 11e9
let expected_output = hex! {"
00000000000000000000000000000000 0000000000000000000000028fa6ae00
"};

let res = LiquidCrowdloanPrecompile::execute(&input, None, &context, false).unwrap();
assert_eq!(res.exit_status, ExitSucceed::Returned);
assert_eq!(res.output, expected_output.to_vec());

assert_eq!(Currencies::free_balance(LDOT, &bob()), 11_000_000_000);
assert_eq!(Currencies::free_balance(LCDOT, &bob()), 0);
});
}

#[test]
fn redeem_currency() {
new_test_ext().execute_with(|| {
let context = Context {
address: Default::default(),
caller: bob_evm_addr(),
apparent_value: Default::default(),
};

// getRedeemCurrency() -> 785ad4c3
let input = hex!("785ad4c3");

// DOT
let expected_output = hex! {"
000000000000000000000000 0000000000000000000100000000000000000002
"};

let res = LiquidCrowdloanPrecompile::execute(&input, None, &context, false).unwrap();
assert_eq!(res.exit_status, ExitSucceed::Returned);
assert_eq!(res.output, expected_output.to_vec());

assert_ok!(LiquidCrowdloan::set_redeem_currency_id(RuntimeOrigin::root(), LDOT));

// LDOT
let expected_output = hex! {"
000000000000000000000000 0000000000000000000100000000000000000003
"};

let res = LiquidCrowdloanPrecompile::execute(&input, None, &context, false).unwrap();
assert_eq!(res.exit_status, ExitSucceed::Returned);
assert_eq!(res.output, expected_output.to_vec());
});
}
}
Loading
Loading