首页 > 区块链 > 区块链 > 浅谈swap去中心化交易所系统开发技术方案
现在,每当
gen_gender()在pallet内调用时,它都会返回
Gender的伪随机枚举值。
如果我们希望能够区分这些小猫,我们需要赋予它们独特的属性!在上一步中,我们使用了尚未实际定义的
KittyRandomness。
我们将使用
frame_support 中的
Randomness trait执行此操作。它将能够生成一个随机的种子,我们将用它来创建独特的小猫,并培育新的小猫。
Randomness特征约束的新类型。来自
frame_support中
Randomnesstrait 需要使用参数来指定
Output和
BlockNumber泛型。
将 ACTION #5 行替换为:
type KittyRandomness: Randomness<Self::Hash, Self::BlockNumber>;
鉴于我们在pallet的配置中添加了一个新类型,我们需要配置runtime以设置其具体类型。如果我们想更改正在使用的算法,而无需修改pallet内的使用位置,
KittyRandomness可能会派上用场。为了展示这一点,我们将设置 KittyRandomness 类型为 FRAME 的 RandomnessCollectiveFlip 的一个实例。 方便的是,node template已经有一个 RandomnessCollectiveFlip pallet的实例。
在runtime的
runtime/src/lib.rs 中设置
KittyRandomness 类型:
impl pallet_kitties::Config for Runtime {
type Event = Event;
type Currency = Balances;
type KittyRandomness = RandomnessCollectiveFlip; // <-- ACTION: add this line.}在这里,我们从其接口(
Randomness<Self::Hash, Self::BlockNumber>)中抽象出随机性生成实现(
RandomnessCollectiveFlip)。
生成DNA类似于使用随机性随机分配性别类型。不同之处在于,我们将使用在上一部分中导入的
blake2_128。如果我们在同一块中多次调用此函数,我们还将使用
extrinsic_index从
frame_systempallet中生成不同的哈希。将 ACTION #6 行替换为:
impl pallet_kitties::Config for Runtime {
type Event = Event;
type Currency = Balances;
type KittyRandomness = RandomnessCollectiveFlip; // <-- ACTION: add this line.}为了轻松跟踪我们所有的小猫咪,我们将标准化我们的逻辑,以使用一的 ID 作为存储项的全局KEY。这意味着单个唯键将指向我们的Kitty对象(即我们之前声明的结构)。
为了使其正常工作,我们需要确保新Kitty的ID始终是唯的。我们可以使用新的存储项
Kitties来执行此操作,该存储项将从ID(哈希)映射到Kitty对象。
使用此对象,我们只需检查此存储项是否已包含使用特定 ID 的映射,即可轻松检查冲突。例如,从可调度函数内部,我们可以使用以下命令进行检查:
ensure!(!<Kitties<T>>::exists(new_id), "This new id already exists");
我们的runtime需要注意:
Kitties的存储map持有)。KittiesOwned的新存储映射)。要为结构
Kitty创建存储实例,我们将使用
StorageMap — FRAME 提供给我们的。
存储项的外观如下:
#[pallet::storage]#[pallet::getter(fn kitties)]pub(super) type Kitties<T: Config> = StorageMap< _, Twox64Concat, T::Hash, Kitty<T>,>;
KittiesOwned存储项与此类似,只是我们将使用
BoundedVec来跟踪我们将在
runtime/src/lib.s中配置的 Kitties 的最大数量。
#[pallet::storage]#[pallet::getter(fn kitties_owned)]/// Keeps track of what accounts own what Kitty.pub(super) type KittiesOwned<T: Config> = StorageMap< _, Twox64Concat, T::AccountId, BoundedVec<T::Hash, T::MaxKittyOwned>, ValueQuery,>;
复制上面的两个代码片段以替换操作 #7 行。
在检查pallet编译之前,我们需要在配置特征中添加一个新类型
MaxKittyOwned,这是一个pallet常量类型(类似于前面
KittyRandomness的步骤)。将操作 #9 替换为:
#[pallet::constant]type MaxKittyOwned: Get<u32>;
最后,我们在
runtime/src/lib.rs中定义类型
MaxKittyOwned。这与我们对 Currency 和 KittyRandomness 遵循的模式相同,只是我们将使用 parameter_types ! 宏添加一个固定的 u32!
parameter_types! { // <- add this macro
// One can own at most 9,999 Kitties
pub const MaxKittyOwned: u32 = 9999;}/// Configure the pallet-kitties in pallets/kitties.impl pallet_kitties::Config for Runtime {
type Event = Event;
type Currency = Balances;
type KittyRandomness = RandomnessCollectiveFlip;
type MaxKittyOwned = MaxKittyOwned; // <- add this line}检查Kitties 区块链编译
cargo build --release
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70016646/viewspace-2944920/ ,如需转载,请注明出处,否则将追究法律责任。