Skip to content

Commit

Permalink
FI v2: refactor without states (#1698)
Browse files Browse the repository at this point in the history
* increase & decrease investments

* add rest of methods

* remove unused code

* generalize swapping

* Create DecreaseForeignInvestment event

* ForeignInvestment trait fully implemented

* notify status for fulfilling swaps

* simplify storages

* implements collected part

* minor cleanings and renamings

* minor rename

* collection refactors

* protect agains 0 investment changes

* Events computed in both swap directions

* protect againts different foreign currency

* minor comment

* add some notes

* fix notify_swap_done

* BaseInfo to extract common parts

* minor rename

* Remove inverse swap optimization

* William suggestions

* fix redemption tranche tokens

* fix collected redemption

* minor notes

* simplify and collected redemption

* fix decrease and fix error in amount denominations

* fix redemption condition

* minor fixes to mirror legacy implementation

* total to pending tranche tokens

* determine pool currency from investment id

* apply William review

* Use apply swap to cancel inverse orders

* fix decrement issue

* fix apply_swap issue

* minor fix

* minor foreign trait simplification

* minor simplifications. mock compiling

* add testing for swaps

* add some tests. Fix issue when decreasing after increasing

* add tests, remove increment/decrement check

* fix amount_reminder for decrease msng, adding the pending increasing amount

* add error to handle too much decrease

* fulfill test working

* decrease after fulfill works

* remove inverse swap notifications

* Extract notifications from mutable closures

* full investment test

* collect investment working

* minor refactorizations

* logic moved to Info structures

* split in files

* add complex decrease test

* correct pending redemption calculation

* better swap done split

* Improve readability for notifications/swaps

* minor renames

* add some docs

* better naming SwapDone

* remove field from InvestmentInfo, computed now from the state

* bypassing swapping for the same currencies

* test collect redemptions with swaps

* nit

* chore: enable runtime compilation

* chore: expose FI hook impls

* clean unused dependencies

* remove old benchmark

* reduce Config associated types

* adapt other tests to last trait changes

* fix investment mock

* fix clippy issues

* fix complex type clippy issues

* avoid failing the notification when the investment is not found

* fix redemption collection denomination

* fix clippy

* tests: fix FI v2 integration  (#1700)

* tests: fix foreign investments v2

* chore: expose ForeignIdToSwapId storage

* fix: remove events

* chore: add swap_id_from

* refactor: use give_pool_role

---------

Co-authored-by: William Freudenberger <[email protected]>
  • Loading branch information
lemunozm and wischli authored Jan 29, 2024
1 parent 683dce0 commit d781a10
Show file tree
Hide file tree
Showing 36 changed files with 2,619 additions and 7,584 deletions.
3 changes: 0 additions & 3 deletions Cargo.lock

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

5 changes: 1 addition & 4 deletions libs/traits/src/investments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,6 @@ pub trait ForeignInvestment<AccountId> {
investment_id: Self::InvestmentId,
amount: Self::Amount,
foreign_payment_currency: Self::CurrencyId,
pool_currency: Self::CurrencyId,
) -> Result<(), Self::Error>;

/// Initiates the decrement of a foreign investment amount in
Expand All @@ -258,7 +257,6 @@ pub trait ForeignInvestment<AccountId> {
investment_id: Self::InvestmentId,
amount: Self::Amount,
foreign_payment_currency: Self::CurrencyId,
pool_currency: Self::CurrencyId,
) -> Result<(), Self::Error>;

/// Initiates the increment of a foreign redemption amount for the given
Expand Down Expand Up @@ -286,7 +284,7 @@ pub trait ForeignInvestment<AccountId> {
investment_id: Self::InvestmentId,
amount: Self::Amount,
foreign_payout_currency: Self::CurrencyId,
) -> Result<(Self::Amount, Self::Amount), Self::Error>;
) -> Result<(), Self::Error>;

/// Collect the results of a user's foreign invest orders for the given
/// investment. If any amounts are not fulfilled they are directly
Expand All @@ -308,7 +306,6 @@ pub trait ForeignInvestment<AccountId> {
who: &AccountId,
investment_id: Self::InvestmentId,
foreign_payout_currency: Self::CurrencyId,
pool_currency: Self::CurrencyId,
) -> Result<(), Self::Error>;

/// Returns, if possible, the currently unprocessed investment amount (in
Expand Down
38 changes: 24 additions & 14 deletions libs/types/src/investments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ use frame_support::{dispatch::fmt::Debug, RuntimeDebug};
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
use scale_info::TypeInfo;
use sp_arithmetic::traits::{EnsureAdd, EnsureSub};
use sp_runtime::{traits::Zero, DispatchError, DispatchResult};
use sp_runtime::{
traits::{EnsureAddAssign, Zero},
ArithmeticError, DispatchError, DispatchResult,
};
use sp_std::cmp::PartialEq;

use crate::orders::Order;
Expand Down Expand Up @@ -127,6 +130,14 @@ pub struct CollectedAmount<Balance> {
pub amount_payment: Balance,
}

impl<Balance: EnsureAddAssign + Copy> CollectedAmount<Balance> {
pub fn increase(&mut self, other: &Self) -> Result<(), ArithmeticError> {
self.amount_collected
.ensure_add_assign(other.amount_collected)?;
self.amount_payment.ensure_add_assign(other.amount_payment)
}
}

/// A representation of an investment identifier and the corresponding owner.
///
/// NOTE: Trimmed version of `InvestmentInfo` required for foreign investments.
Expand All @@ -140,18 +151,7 @@ pub struct ForeignInvestmentInfo<AccountId, InvestmentId, TokenSwapReason> {

/// A simple representation of a currency swap.
#[derive(
Clone,
Default,
Copy,
PartialOrd,
Ord,
PartialEq,
Eq,
Debug,
Encode,
Decode,
TypeInfo,
MaxEncodedLen,
Clone, Default, PartialOrd, Ord, PartialEq, Eq, Debug, Encode, Decode, TypeInfo, MaxEncodedLen,
)]
pub struct Swap<
Balance: Clone + Copy + EnsureAdd + EnsureSub + Ord + Debug,
Expand All @@ -162,7 +162,7 @@ pub struct Swap<
/// The outgoing currency, i.e. the one which should be replaced.
pub currency_out: Currency,
/// The amount of incoming currency which shall be bought.
pub amount: Balance,
pub amount_in: Balance,
}

impl<Balance: Clone + Copy + EnsureAdd + EnsureSub + Ord + Debug, Currency: Clone + PartialEq>
Expand Down Expand Up @@ -196,6 +196,16 @@ impl<Balance: Clone + Copy + EnsureAdd + EnsureSub + Ord + Debug, Currency: Clon
Ok(())
}
}

pub fn is_same_direction(&self, other: &Self) -> Result<bool, DispatchError> {
if self.currency_in == other.currency_in && self.currency_out == other.currency_out {
Ok(true)
} else if self.currency_in == other.currency_out && self.currency_out == other.currency_in {
Ok(false)
} else {
Err(DispatchError::Other("Swap contains different currencies"))
}
}
}

/// A representation of an executed investment decrement.
Expand Down
7 changes: 0 additions & 7 deletions pallets/foreign-investments/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,9 @@ version = "1.0.0"
targets = ["x86_64-unknown-linux-gnu"]

[dependencies]
log = { version = "0.4.17", default-features = false }
parity-scale-codec = { version = "3.0.0", features = ["derive"], default-features = false }
scale-info = { version = "2.3.0", default-features = false, features = ["derive"] }

cfg-primitives = { path = "../../libs/primitives", default-features = false }
cfg-traits = { path = "../../libs/traits", default-features = false }
cfg-types = { path = "../../libs/types", default-features = false }

Expand All @@ -28,7 +26,6 @@ sp-std = { git = "https://github.com/paritytech/substrate", default-features = f
frame-benchmarking = { git = "https://github.com/paritytech/substrate", default-features = false, optional = true, branch = "polkadot-v0.9.43" }

[dev-dependencies]
rand = "0.8"
sp-core = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" }
sp-io = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.43" }

Expand All @@ -37,30 +34,26 @@ cfg-mocks = { path = "../../libs/mocks" }
[features]
default = ["std"]
std = [
"cfg-primitives/std",
"cfg-traits/std",
"cfg-types/std",
"parity-scale-codec/std",
"frame-benchmarking?/std",
"frame-support/std",
"frame-system/std",
"log/std",
"scale-info/std",
"sp-runtime/std",
"sp-std/std",
]
runtime-benchmarks = [
"cfg-traits/runtime-benchmarks",
"cfg-types/runtime-benchmarks",
"cfg-primitives/runtime-benchmarks",
"frame-benchmarking/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"cfg-mocks/runtime-benchmarks",
]
try-runtime = [
"cfg-primitives/try-runtime",
"cfg-traits/try-runtime",
"cfg-types/try-runtime",
"frame-support/try-runtime",
Expand Down
Loading

0 comments on commit d781a10

Please sign in to comment.