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

Enable transfer and list #1170

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
25 changes: 23 additions & 2 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions pallets/phala/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ pallet-preimage = { git = "https://github.com/paritytech/substrate", branch = "p
# RMRK dependencies
pallet-rmrk-core = { git = "https://github.com/Phala-Network/rmrk-substrate", branch = "polkadot-v0.9.37", default-features = false }
rmrk-traits = { git = "https://github.com/Phala-Network/rmrk-substrate", branch = "polkadot-v0.9.37", default-features = false }
pallet-rmrk-market = { git = "https://github.com/Phala-Network/rmrk-substrate", branch = "polkadot-v0.9.37", default-features = false }

frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37", default-features = false }
frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.37", default-features = false }
Expand Down Expand Up @@ -86,6 +87,7 @@ std = [
"phala-types/enable_serde",
"pallet-rmrk-core/std",
"rmrk-traits/std",
"pallet-rmrk-market/std",
"pallet-collective/std",
"pallet-randomness-collective-flip/std",
"pallet-preimage/std",
Expand Down
34 changes: 13 additions & 21 deletions pallets/phala/src/compute/base_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,7 @@ pub mod pallet {
#[pallet::getter(fn next_nft_id)]
pub type NextNftId<T: Config> = StorageMap<_, Twox64Concat, CollectionId, NftId, ValueQuery>;

type LockKey = (
CollectionId,
NftId,
);
type LockKey = (CollectionId, NftId);

#[pallet::storage]
pub type LockIterateStartPos<T> = StorageValue<_, Option<LockKey>, ValueQuery>;
Expand Down Expand Up @@ -511,17 +508,18 @@ pub mod pallet {
let last_pos = LockIterateStartPos::<T>::get();
let mut iter = match last_pos {
Some(pos) => {
let key: Vec<u8> =
pallet_rmrk_core::pallet::Lock::<T>::hashed_key_for(pos);
let key: Vec<u8> = pallet_rmrk_core::pallet::Lock::<T>::hashed_key_for(pos);
pallet_rmrk_core::pallet::Lock::<T>::iter_from(key)
}
None => pallet_rmrk_core::pallet::Lock::<T>::iter(),
};
let mut record_vec = vec![];
let mut i = 0;
for ((cid, nft_id), _) in iter.by_ref() {
if cid >= RESERVE_CID_START && !pallet_rmrk_core::pallet::Nfts::<T>::contains_key(cid, nft_id) {
record_vec.push((cid, nft_id));
if cid >= RESERVE_CID_START
&& !pallet_rmrk_core::pallet::Nfts::<T>::contains_key(cid, nft_id)
{
record_vec.push((cid, nft_id));
}
i += 1;
if i > max_iterations {
Expand Down Expand Up @@ -639,11 +637,7 @@ pub mod pallet {
Error::<T>::NotInContributeWhitelist
);
}
Self::merge_nft_for_staker(
pool.cid,
account_id.clone(),
pool.pid,
)?;
Self::merge_nft_for_staker(pool.cid, account_id.clone(), pool.pid)?;
// The nft instance must be wrote to Nft storage at the end of the function
// this nft's property shouldn't be accessed or wrote again from storage before set_nft_attr
// is called. Or the property of the nft will be overwrote incorrectly.
Expand Down Expand Up @@ -909,11 +903,12 @@ pub mod pallet {
pid: u64,
) -> Result<Option<NftId>, DispatchError> {
let mut total_shares: BalanceOf<T> = Zero::zero();
let nfts: Vec<_> = pallet_uniques::Pallet::<T>::owned_in_collection(&cid, &staker).collect();
let nfts: Vec<_> =
pallet_uniques::Pallet::<T>::owned_in_collection(&cid, &staker).collect();
match nfts.len() {
0 => return Ok(None),
1 => return Ok(Some(nfts[0])),
_ => (),
0 => return Ok(None),
1 => return Ok(Some(nfts[0])),
_ => (),
};
for nftid in nfts {
let nft_guard =
Expand Down Expand Up @@ -952,10 +947,7 @@ pub mod pallet {
})
}

fn set_nft_desc_attr(
cid: CollectionId,
nft_id: NftId,
) -> DispatchResult {
fn set_nft_desc_attr(cid: CollectionId, nft_id: NftId) -> DispatchResult {
pallet_rmrk_core::Pallet::<T>::set_lock((cid, nft_id), false);
let key: BoundedVec<u8, <T as pallet_uniques::Config>::KeyLimit> = "createtime"
.as_bytes()
Expand Down
24 changes: 16 additions & 8 deletions pallets/phala/src/compute/stake_pool_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,9 @@ pub mod pallet {
#[pallet::without_storage_info]
pub struct Pallet<T>(_);


#[pallet::storage]
pub type LegacyRewards<T: Config> = StorageMap<_, Twox64Concat, (T::AccountId, u64), BalanceOf<T>>;
pub type LegacyRewards<T: Config> =
StorageMap<_, Twox64Concat, (T::AccountId, u64), BalanceOf<T>>;
/// Mapping from workers to the pool they belong to
///
/// The map entry lasts from `add_worker()` to `remove_worker()` or force unbinding.
Expand Down Expand Up @@ -316,6 +316,8 @@ pub mod pallet {
LockAccountStakeError,

NoLegacyRewardToClaim,
/// The pool's delegation nft is on sell.
UserNftListed,
}

#[pallet::call]
Expand Down Expand Up @@ -564,7 +566,8 @@ pub mod pallet {
target: T::AccountId,
) -> DispatchResult {
let who = ensure_signed(origin)?;
let rewards = LegacyRewards::<T>::take((who, pid)).ok_or(Error::<T>::NoLegacyRewardToClaim)?;
let rewards =
LegacyRewards::<T>::take((who, pid)).ok_or(Error::<T>::NoLegacyRewardToClaim)?;
computation::Pallet::<T>::withdraw_subsidy_pool(&target, rewards)
.or(Err(Error::<T>::InternalSubsidyPoolCannotWithdraw))?;
Ok(())
Expand Down Expand Up @@ -698,6 +701,10 @@ pub mod pallet {
maybe_vault = Some((vault_pid, vault_info));
}
let mut pool_info = ensure_stake_pool::<T>(pid)?;
ensure!(
!wrapped_balances::pallet::Pallet::<T>::have_nft_on_list(&who, &pool_info.basepool.cid),
Error::<T>::UserNftListed
);
let a = amount; // Alias to reduce confusion in the code below
// If the pool has a contribution whitelist in storages, check if the origin is authorized to contribute
ensure!(
Expand All @@ -713,11 +720,8 @@ pub mod pallet {
};
ensure!(free >= a, Error::<T>::InsufficientBalance);
// a lot of weird edge cases when dealing with pending slash.
let shares = base_pool::Pallet::<T>::contribute(
&mut pool_info.basepool,
who.clone(),
amount,
)?;
let shares =
base_pool::Pallet::<T>::contribute(&mut pool_info.basepool, who.clone(), amount)?;
if let Some((vault_pid, vault_info)) = &mut maybe_vault {
if !vault_info.invest_pools.contains(&pid) {
vault_info.invest_pools.push(pid);
Expand Down Expand Up @@ -796,6 +800,10 @@ pub mod pallet {
who = vault_info.basepool.pool_account_id;
}
let mut pool_info = ensure_stake_pool::<T>(pid)?;
ensure!(
!wrapped_balances::pallet::Pallet::<T>::have_nft_on_list(&who, &pool_info.basepool.cid),
Error::<T>::UserNftListed
);
let maybe_nft_id = base_pool::Pallet::<T>::merge_nft_for_staker(
pool_info.basepool.cid,
who.clone(),
Expand Down
21 changes: 16 additions & 5 deletions pallets/phala/src/compute/vault.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,8 @@ pub mod pallet {
VaultBankrupt,
/// The caller has no nft to withdraw
NoNftToWithdraw,
/// The pool's delegation nft is on sell.
UserNftListed,
}

#[pallet::call]
Expand Down Expand Up @@ -246,6 +248,10 @@ pub mod pallet {
) -> DispatchResult {
let who = ensure_signed(origin.clone())?;
let mut pool_info = ensure_vault::<T>(vault_pid)?;
ensure!(
!wrapped_balances::pallet::Pallet::<T>::have_nft_on_list(&who, &pool_info.basepool.cid),
Error::<T>::UserNftListed
);
ensure!(
who == pool_info.basepool.owner,
Error::<T>::UnauthorizedPoolOwner
Expand Down Expand Up @@ -429,6 +435,10 @@ pub mod pallet {
pub fn contribute(origin: OriginFor<T>, pid: u64, amount: BalanceOf<T>) -> DispatchResult {
let who = ensure_signed(origin)?;
let mut pool_info = ensure_vault::<T>(pid)?;
ensure!(
!wrapped_balances::pallet::Pallet::<T>::have_nft_on_list(&who, &pool_info.basepool.cid),
Error::<T>::UserNftListed
);
let a = amount; // Alias to reduce confusion in the code below

ensure!(
Expand All @@ -442,11 +452,8 @@ pub mod pallet {
.ok_or(Error::<T>::AssetAccountNotExist)?;
ensure!(free >= a, Error::<T>::InsufficientBalance);

let shares = base_pool::Pallet::<T>::contribute(
&mut pool_info.basepool,
who.clone(),
amount,
)?;
let shares =
base_pool::Pallet::<T>::contribute(&mut pool_info.basepool, who.clone(), amount)?;

// We have new free stake now, try to handle the waiting withdraw queue

Expand Down Expand Up @@ -486,6 +493,10 @@ pub mod pallet {
pub fn withdraw(origin: OriginFor<T>, pid: u64, shares: BalanceOf<T>) -> DispatchResult {
let who = ensure_signed(origin)?;
let mut pool_info = ensure_vault::<T>(pid)?;
ensure!(
!wrapped_balances::pallet::Pallet::<T>::have_nft_on_list(&who, &pool_info.basepool.cid),
Error::<T>::UserNftListed
);
let maybe_nft_id = base_pool::Pallet::<T>::merge_nft_for_staker(
pool_info.basepool.cid,
who.clone(),
Expand Down
23 changes: 22 additions & 1 deletion pallets/phala/src/compute/wrapped_balances.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub mod pallet {
+ crate::PhalaConfig
+ registry::Config
+ pallet_rmrk_core::Config
+ pallet_rmrk_market::Config
+ computation::Config
+ pallet_assets::Config
+ pallet_democracy::Config
Expand Down Expand Up @@ -143,8 +144,16 @@ pub mod pallet {
T: pallet_democracy::Config<Currency = <T as crate::PhalaConfig>::Currency>,
T: Config + vault::Config,
{
fn pre_check(sender: &T::AccountId, collection_id: &CollectionId, nft_id: &NftId) -> bool {
fn pre_check(
sender: &T::AccountId,
recipient: &T::AccountId,
collection_id: &CollectionId,
nft_id: &NftId,
) -> bool {
if let Some(pid) = base_pool::pallet::PoolCollections::<T>::get(collection_id) {
if Self::have_nft_on_list(recipient, collection_id) {
return false;
}
if let Ok(net_value) = Pallet::<T>::get_net_value((*sender).clone()) {
let property_guard =
base_pool::Pallet::<T>::get_nft_attr_guard(*collection_id, *nft_id)
Expand Down Expand Up @@ -463,6 +472,18 @@ pub mod pallet {
}
}

/// Check if recipient has Nft listing in a specific collection.
pub fn have_nft_on_list(recipient: &T::AccountId, collection_id: &CollectionId) -> bool {
let iter = pallet_uniques::Pallet::<T>::owned_in_collection(collection_id, recipient)
.take_while(|nftid| {
pallet_rmrk_market::ListedNfts::<T>::contains_key(collection_id, nftid)
});
if iter.count() > 0 {
return true;
}
false
}

/// Tries to update locked W-PHA amount of the user
fn update_user_locked(user: T::AccountId) -> DispatchResult {
let mut max_lock: BalanceOf<T> = Zero::zero();
Expand Down
17 changes: 17 additions & 0 deletions pallets/phala/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use sp_core::H256;
use sp_runtime::{
testing::Header,
traits::{BlakeTwo256, IdentityLookup},
Permill,
};

use frame_system::EnsureRoot;
Expand All @@ -42,6 +43,7 @@ frame_support::construct_runtime!(
Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
Uniques: pallet_uniques::{Pallet, Storage, Event<T>},
RmrkCore: pallet_rmrk_core::{Pallet, Call, Event<T>},
RmrkMarket: pallet_rmrk_market::{Pallet, Call, Event<T>},
Democracy: pallet_democracy::{Pallet, Call, Storage, Config<T>, Event<T>},
Assets: pallet_assets::{Pallet, Event<T>},
Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event<T>},
Expand Down Expand Up @@ -232,6 +234,21 @@ impl pallet_rmrk_core::Config for Test {
type Helper = pallet_rmrk_core::RmrkBenchmark;
}

parameter_types! {
pub const MinimumOfferAmount: Balance = DOLLARS / 10_000;
pub const MarketFee: Permill = Permill::from_parts(5_000);
}

impl pallet_rmrk_market::Config for Test {
type RuntimeEvent = RuntimeEvent;
type ProtocolOrigin = EnsureRoot<Self::AccountId>;
type Currency = Balances;
type MinimumOfferAmount = MinimumOfferAmount;
type WeightInfo = pallet_rmrk_market::weights::SubstrateWeight<Test>;
type MarketplaceHooks = ();
type MarketFee = MarketFee;
}

impl computation::Config for Test {
type RuntimeEvent = RuntimeEvent;
type ExpectedBlockTimeSec = ExpectedBlockTimeSec;
Expand Down
4 changes: 3 additions & 1 deletion pallets/phala/src/utils/balance_convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ impl FixedPointConvert for u128 {
Self::from_fixed(&FixedPoint::from_bits(bits))
}
fn from_fixed(v: &FixedPoint) -> Self {
U80F48::unwrapped_from_num(*v).unwrapped_mul_int(PHA).to_num()
U80F48::unwrapped_from_num(*v)
.unwrapped_mul_int(PHA)
.to_num()
}
fn to_fixed(&self) -> FixedPoint {
let v = U80F48::unwrapped_from_num(*self);
Expand Down
Loading