-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathassets.rs
317 lines (293 loc) · 11.5 KB
/
assets.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
use codec::{Decode, Encode};
use frame_support::{
pallet_prelude::Get,
parameter_types,
traits::{AsEnsureOriginWithArg, ConstU32},
BoundedVec, PalletId,
};
use frame_system::{EnsureRoot, EnsureSigned};
use pallet_nfts::PalletFeatures;
use parachains_common::{AssetIdForTrustBackedAssets, CollectionId, ItemId, Signature};
use sp_runtime::traits::{StaticLookup, Verify};
use crate::{
deposit, AccountId, AssetManager, Assets, Balance, Balances, BlockNumber, Nfts, Runtime,
RuntimeCall, RuntimeEvent, RuntimeHoldReason, RuntimeOrigin, Vec, Weight, DAYS,
EXISTENTIAL_DEPOSIT, UNIT,
};
/// We allow root to execute privileged asset operations.
pub type AssetsForceOrigin = EnsureRoot<AccountId>;
parameter_types! {
pub const AssetDeposit: Balance = 10 * UNIT;
pub const AssetAccountDeposit: Balance = deposit(1, 16);
pub const ApprovalDeposit: Balance = EXISTENTIAL_DEPOSIT;
pub const AssetsStringLimit: u32 = 50;
/// Key = 32 bytes, Value = 36 bytes (32+1+1+1+1)
// https://github.com/paritytech/substrate/blob/069917b/frame/assets/src/lib.rs#L257L271
pub const MetadataDepositBase: Balance = deposit(1, 68);
pub const MetadataDepositPerByte: Balance = deposit(0, 1);
}
parameter_types! {
pub NftsPalletFeatures: PalletFeatures = PalletFeatures::all_enabled();
// Key = 68 bytes (4+16+32+16), Value = 52 bytes (4+32+16)
pub const NftsCollectionBalanceDeposit: Balance = deposit(1, 120);
pub const NftsCollectionDeposit: Balance = 10 * UNIT;
// Key = 116 bytes (4+16+32+16+32+16), Value = 21 bytes (1+4+16)
pub const NftsCollectionApprovalDeposit: Balance = deposit(1, 137);
pub const NftsItemDeposit: Balance = UNIT / 100;
pub const NftsMetadataDepositBase: Balance = deposit(1, 129);
pub const NftsAttributeDepositBase: Balance = deposit(1, 0);
pub const NftsDepositPerByte: Balance = deposit(0, 1);
pub const NftsMaxDeadlineDuration: BlockNumber = 12 * 30 * DAYS;
}
#[derive(Debug)]
#[cfg_attr(feature = "std", derive(PartialEq, Clone))]
/// The maximum length of an attribute key.
pub struct KeyLimit<const N: u32>;
impl<const N: u32> Get<u32> for KeyLimit<N> {
fn get() -> u32 {
N
}
}
// Trust backed NFTs as an instance of the `pallet-nfts` module. The name "TrustBacked" reflects the
// assumption that non-fungible tokens are registered by an account and are trusted to have some
// claimed backing.
pub(crate) type TrustBackedNftsInstance = pallet_nfts::Instance1;
/// Call type for trust backed NFTs. The type represents the calls that can be made to the
/// `pallet-nfts` module with the `TrustBackedNftsInstance` configuration.
pub type TrustBackedNftsCall = pallet_nfts::Call<Runtime, TrustBackedNftsInstance>;
impl pallet_nfts::Config<TrustBackedNftsInstance> for Runtime {
// TODO: source from primitives
type ApprovalsLimit = ConstU32<20>;
type AttributeDepositBase = NftsAttributeDepositBase;
type CollectionApprovalDeposit = NftsCollectionApprovalDeposit;
type CollectionBalanceDeposit = NftsCollectionBalanceDeposit;
type CollectionDeposit = NftsCollectionDeposit;
// TODO: source from primitives
type CollectionId = CollectionId;
type CreateOrigin = AsEnsureOriginWithArg<EnsureSigned<AccountId>>;
type Currency = Balances;
type DepositPerByte = NftsDepositPerByte;
type Features = NftsPalletFeatures;
type ForceOrigin = AssetsForceOrigin;
#[cfg(feature = "runtime-benchmarks")]
type Helper = ();
type ItemAttributesApprovalsLimit = ConstU32<30>;
type ItemDeposit = NftsItemDeposit;
// TODO: source from primitives
type ItemId = ItemId;
// TODO: source from primitives
type KeyLimit = KeyLimit<64>;
type Locker = ();
type MaxAttributesPerCall = ConstU32<10>;
type MaxDeadlineDuration = NftsMaxDeadlineDuration;
type MaxTips = ConstU32<10>;
type MetadataDepositBase = NftsMetadataDepositBase;
type OffchainPublic = <Signature as Verify>::Signer;
type OffchainSignature = Signature;
type RuntimeEvent = RuntimeEvent;
type StringLimit = ConstU32<256>;
type ValueLimit = ConstU32<256>;
type WeightInfo = pallet_nfts::weights::SubstrateWeight<Self>;
}
parameter_types! {
pub const NftFractionalizationPalletId: PalletId = PalletId(*b"fraction");
pub NewAssetSymbol: BoundedVec<u8, AssetsStringLimit> = (*b"FRAC").to_vec().try_into().unwrap();
pub NewAssetName: BoundedVec<u8, AssetsStringLimit> = (*b"Frac").to_vec().try_into().unwrap();
}
impl pallet_nft_fractionalization::Config for Runtime {
type AssetBalance = <Self as pallet_assets::Config<TrustBackedAssetsInstance>>::Balance;
type AssetId = <Self as pallet_assets::Config<TrustBackedAssetsInstance>>::AssetId;
type Assets = Assets;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = ();
type Currency = Balances;
type Deposit = AssetDeposit;
type NewAssetName = NewAssetName;
type NewAssetSymbol = NewAssetSymbol;
type NftCollectionId = <Self as pallet_nfts::Config<TrustBackedNftsInstance>>::CollectionId;
type NftId = <Self as pallet_nfts::Config<TrustBackedNftsInstance>>::ItemId;
type Nfts = Nfts;
type PalletId = NftFractionalizationPalletId;
type RuntimeEvent = RuntimeEvent;
type RuntimeHoldReason = RuntimeHoldReason;
type StringLimit = AssetsStringLimit;
type WeightInfo = pallet_nft_fractionalization::weights::SubstrateWeight<Self>;
}
pub(crate) type TrustBackedAssetsInstance = pallet_assets::Instance1;
pub type TrustBackedAssetsCall = pallet_assets::Call<Runtime, TrustBackedAssetsInstance>;
impl pallet_assets::Config<TrustBackedAssetsInstance> for Runtime {
type ApprovalDeposit = ApprovalDeposit;
type AssetAccountDeposit = AssetAccountDeposit;
type AssetDeposit = AssetDeposit;
type AssetId = AssetIdForTrustBackedAssets;
type AssetIdParameter = codec::Compact<AssetIdForTrustBackedAssets>;
type Balance = Balance;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = ();
type CallbackHandle = pallet_assets::AutoIncAssetId<Runtime, TrustBackedNftsInstance>;
type CreateOrigin = AsEnsureOriginWithArg<EnsureSigned<AccountId>>;
type Currency = Balances;
type Extra = ();
type ForceOrigin = AssetsForceOrigin;
type Freezer = ();
type MetadataDepositBase = MetadataDepositBase;
type MetadataDepositPerByte = MetadataDepositPerByte;
type RemoveItemsLimit = ConstU32<1000>;
type RuntimeEvent = RuntimeEvent;
type StringLimit = AssetsStringLimit;
type WeightInfo = pallet_assets::weights::SubstrateWeight<Self>;
}
pub struct AssetRegistrar;
use frame_support::{dispatch::GetDispatchInfo, pallet_prelude::DispatchResult, transactional};
impl pallet_asset_manager::AssetRegistrar<Runtime> for AssetRegistrar {
fn next_asset_id() -> AssetIdForTrustBackedAssets {
pallet_assets::NextAssetId::<Runtime, TrustBackedAssetsInstance>::get().unwrap()
}
#[transactional]
fn create_foreign_asset(
asset: AssetIdForTrustBackedAssets,
min_balance: Balance,
metadata: AssetRegistrarMetadata,
is_sufficient: bool,
) -> DispatchResult {
// Create the asset. Unlike `create`, no funds are reserved.
Assets::force_create(
RuntimeOrigin::root(),
asset.into(),
// Asset manager pallet is the owner of the asset. This means changes to the asset can
// only be made through this pallet.
<Runtime as frame_system::Config>::Lookup::unlookup(AssetManager::account_id()),
is_sufficient,
min_balance,
)?;
// Set metadata for created asset. Deposit is left alone, meaning that also no deposit will
// be taken unless metadata was already set for this asset which in this case wouldn't be
// the case.
Assets::force_set_metadata(
RuntimeOrigin::root(),
asset.into(),
metadata.name,
metadata.symbol,
metadata.decimals,
metadata.is_frozen,
)
}
#[transactional]
fn destroy_foreign_asset(asset: AssetIdForTrustBackedAssets) -> DispatchResult {
Assets::start_destroy(RuntimeOrigin::root(), asset.into())
}
fn destroy_asset_dispatch_info_weight(asset: AssetIdForTrustBackedAssets) -> Weight {
use pallet_assets::WeightInfo;
<Runtime as pallet_assets::Config<TrustBackedAssetsInstance>>::WeightInfo::start_destroy()
}
}
use frame_support::pallet_prelude::TypeInfo;
#[derive(Clone, Default, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
pub struct AssetRegistrarMetadata {
pub name: Vec<u8>,
pub symbol: Vec<u8>,
pub decimals: u8,
pub is_frozen: bool,
}
impl pallet_asset_manager::Config for Runtime {
type AssetId = <Self as pallet_assets::Config<TrustBackedAssetsInstance>>::AssetId;
type AssetRegistrar = AssetRegistrar;
type AssetRegistrarMetadata = AssetRegistrarMetadata;
type Balance = Balance;
type ForeignAssetModifierOrigin = EnsureRoot<AccountId>;
type ForeignAssetType = xcm::v5::Location;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = pallet_asset_manager::weights::SubstrateWeight<Runtime>;
}
#[cfg(test)]
mod tests {
use frame_support::{
assert_ok,
traits::{fungibles::Inspect, StorageInfoTrait},
};
use sp_keyring::AccountKeyring as Keyring;
use sp_runtime::BuildStorage;
use super::*;
use crate::{config::xcm::AssetHub, ExistentialDeposit, System};
fn new_test_ext() -> sp_io::TestExternalities {
let initial_balance = 100_000_000 * UNIT;
let mut t = frame_system::GenesisConfig::<Runtime>::default().build_storage().unwrap();
pallet_balances::GenesisConfig::<Runtime> {
balances: vec![(Keyring::Alice.to_account_id(), initial_balance)],
}
.assimilate_storage(&mut t)
.unwrap();
pallet_assets::GenesisConfig::<Runtime, TrustBackedAssetsInstance> {
next_asset_id: Some(1),
..Default::default()
}
.assimilate_storage(&mut t)
.unwrap();
let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| System::set_block_number(1));
ext
}
#[test]
fn test_foreign_asset_creation() {
new_test_ext().execute_with(|| {
let metadata = AssetRegistrarMetadata {
name: "DOT".encode(),
symbol: "DOT".encode(),
decimals: 10,
is_frozen: false,
};
// Obtain the next asset id from pallet assets.
let asset_id =
pallet_assets::NextAssetId::<Runtime, TrustBackedAssetsInstance>::get().unwrap();
// Register a foreign asset in the asset manager pallet.
assert_ok!(AssetManager::register_foreign_asset(
RuntimeOrigin::root(),
xcm::v5::Parent.into(),
metadata,
ExistentialDeposit::get(),
true
));
// Foreign asset has been created with the next asset id queried.
assert!(Assets::asset_exists(asset_id));
// Next asset id is incremented for the next foreign asset created.
let next_asset_id =
pallet_assets::NextAssetId::<Runtime, TrustBackedAssetsInstance>::get().unwrap();
assert_eq!(next_asset_id, asset_id + 1);
let metadata = AssetRegistrarMetadata {
name: "AH".encode(),
symbol: "AH".encode(),
decimals: 12,
is_frozen: false,
};
assert_ok!(AssetManager::register_foreign_asset(
RuntimeOrigin::root(),
AssetHub::get(),
metadata,
ExistentialDeposit::get(),
true
));
assert!(Assets::asset_exists(next_asset_id));
// There is no way to modify the assets metadata, mint or burn tokens or any other
// action with owner privileges because the asset manager pallet is the owner and
// doesn't have this functionality.
});
}
#[test]
fn ensure_account_balance_deposit() {
let max_size =
pallet_nfts::AccountBalance::<Runtime, TrustBackedNftsInstance>::storage_info()
.first()
.and_then(|info| info.max_size)
.unwrap_or_default();
assert_eq!(deposit(1, max_size), NftsCollectionBalanceDeposit::get());
}
#[test]
fn ensure_collection_approval_deposit() {
let max_size =
pallet_nfts::CollectionApprovals::<Runtime, TrustBackedNftsInstance>::storage_info()
.first()
.and_then(|info| info.max_size)
.unwrap_or_default();
assert_eq!(deposit(1, max_size), NftsCollectionApprovalDeposit::get());
}
}