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

TradableKitty piece #171

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 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 tuxedo-template-runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ money = { default-features = false, path = "../wardrobe/money" }
poe = { default-features = false, path = "../wardrobe/poe" }
runtime-upgrade = { default-features = false, path = "../wardrobe/runtime_upgrade" }
timestamp = { default-features = false, path = "../wardrobe/timestamp" }
tradable-kitties = { default-features = false, path = "../wardrobe/tradable_kitties" }
tuxedo-core = { default-features = false, path = "../tuxedo-core" }

# Parachain related ones
Expand Down
5 changes: 5 additions & 0 deletions tuxedo-template-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ pub use money;
pub use poe;
pub use runtime_upgrade;
pub use timestamp;
pub use tradable_kitties;

/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
Expand Down Expand Up @@ -170,6 +171,8 @@ pub enum OuterConstraintChecker {
Money(money::MoneyConstraintChecker<0>),
/// Checks Free Kitty transactions
FreeKittyConstraintChecker(kitties::FreeKittyConstraintChecker),
/// Checks tradable Kitty transactions
TradableKittyConstraintChecker(tradable_kitties::TradableKittyConstraintChecker<0>),
muraca marked this conversation as resolved.
Show resolved Hide resolved
/// Checks that an amoeba can split into two new amoebas
AmoebaMitosis(amoeba::AmoebaMitosis),
/// Checks that a single amoeba is simply removed from the state
Expand Down Expand Up @@ -205,6 +208,8 @@ pub enum OuterConstraintChecker {
Money(money::MoneyConstraintChecker<0>),
/// Checks Free Kitty transactions
FreeKittyConstraintChecker(kitties::FreeKittyConstraintChecker),
/// Checks Paid Kitty transactions
TradableKittyConstraintChecker(tradable_kitties::TradableKittyConstraintChecker<0>),
/// Checks that an amoeba can split into two new amoebas
AmoebaMitosis(amoeba::AmoebaMitosis),
/// Checks that a single amoeba is simply removed from the state
Expand Down
165 changes: 147 additions & 18 deletions wardrobe/kitties/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
//! An NFT game inspired by cryptokitties.
//! This is a game which allows for kitties to be bred based on a few factors
//! This is a game which allows for kitties to be create,bred and update name of kitty.
//!
//! ## Features
//!
//! - **Create:** Generate a new kitty.
//! To submit a valid transaction for creating a kitty, adhere to the following structure:
muraca marked this conversation as resolved.
Show resolved Hide resolved
//! 1. Input must be empty.
//! 2. Output must contain only the newly created kitty as a child.

//! - **Update Name:** Modify the name of a kitty.
//! To submit a valid transaction for updating a kitty's name, adhere to the following structure:
//! 1. Input must be the kitty to be updated.
//! 2. Output must contain the kitty with the updated name.
//!
//! **Note:** All other properties such as DNA, parents, free breedings, etc., must remain unaltered in the output.
//!
//! - **Breed:** Breeds a new kitty using mom and dad based on below factors
//! 1.) Mom and Tired have to be in a state where they are ready to breed
//! 2.) Each Mom and Dad have some DNA and the child will have unique DNA combined from the both of them
//! Linkable back to the Mom and Dad
Expand All @@ -25,6 +41,7 @@ use sp_runtime::{
traits::{BlakeTwo256, Hash as HashT},
transaction_validity::TransactionPriority,
};
use sp_std::collections::btree_map::BTreeMap;
use sp_std::prelude::*;
use tuxedo_core::{
dynamic_typing::{DynamicallyTypedData, UtxoData},
Expand All @@ -50,7 +67,14 @@ mod tests;
Debug,
TypeInfo,
)]
pub struct FreeKittyConstraintChecker;
pub enum FreeKittyConstraintChecker {
/// A transaction that creates kitty without parents.
Create,
/// A Transaction that updates kitty Name.
UpdateKittyName,
/// A transaction where kitties are consumed and new family(Parents(mom,dad) and child) is created.
Breed,
}

#[derive(
Serialize,
Expand Down Expand Up @@ -165,6 +189,7 @@ pub struct KittyData {
pub free_breedings: u64, // Ignore in breed for money case
pub dna: KittyDNA,
pub num_breedings: u128,
pub name: [u8; 4],
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, I think the fields should follow a more logical order, such as:

  • DNA
  • Name
  • Parents
  • free_breedings
  • num_breedings

Copy link
Contributor Author

@NadigerAmit NadigerAmit Mar 11, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is generally better to add new members at the end of a struct. This practice aligns with the principle of maintaining backward compatibility. When we add a new member at the end of the struct, existing code that uses the struct won't be affected, as the layout of the existing members remains unchanged.

If you add a new member in the middle of a struct, it can break existing code that relies on the order and size of the struct members. This is because the memory layout of the struct may change, leading to potential issues with code that assumes a specific order or size.

By appending new members at the end, we follow a practice commonly referred to as "struct versioning" or "extensible struct pattern," where you ensure that new fields are added without affecting the existing layout. This helps in maintaining compatibility and minimizes the risk of introducing errors in the existing codebase.

As of now, I don't see any code which is relying on the layout of the structure.
If it is a strong request, I will update it. Otherwise, I want to keep it as it is.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is generally better to add new members at the end of a struct. This practice aligns with the principle of maintaining backward compatibility.

Although you are not wrong, at this stage of the development we don't need to care about this, and we should prioritize doing stuff that makes sense and is clear and understandable.

And sometimes, you do want to break compatibility.

Copy link
Contributor Author

@NadigerAmit NadigerAmit Mar 15, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok. I updated the struct as you suggested.

}

impl KittyData {
Expand All @@ -187,7 +212,7 @@ impl KittyData {
v,
)
.into()],
checker: FreeKittyConstraintChecker.into(),
checker: FreeKittyConstraintChecker::Create.into(),
}
}
}
Expand All @@ -199,6 +224,7 @@ impl Default for KittyData {
free_breedings: 2,
dna: KittyDNA(H256::from_slice(b"mom_kitty_1asdfasdfasdfasdfasdfa")),
num_breedings: 3,
name: *b"kity",
NadigerAmit marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
Expand Down Expand Up @@ -261,9 +287,25 @@ pub enum ConstraintCheckerError {
TooManyBreedingsForKitty,
/// Not enough free breedings available for these parents.
NotEnoughFreeBreedings,
/// The transaction attempts to create no Kitty.
CreatingNothing,
/// Inputs(Parents) not required for mint.
CreatingWithInputs,
/// No input for kitty Update.
InvalidNumberOfInputOutput,
/// Updating nothing
OutputUtxoMissingError,
/// Name is not updated
KittyNameUnAltered,
/// Kitty FreeBreeding cannot be updated.
FreeBreedingCannotBeUpdated,
/// Kitty NumOfBreeding cannot be updated.
NumOfBreedingCannotBeUpdated,
/// Gender cannot be updated
KittyGenderCannotBeUpdated,
}

trait Breed {
pub trait Breed {
/// The Cost to breed a kitty if it is not free.
const COST: u128;
/// Number of free breedings a kitty will have.
Expand Down Expand Up @@ -500,28 +542,115 @@ impl TryFrom<&DynamicallyTypedData> for KittyData {

impl SimpleConstraintChecker for FreeKittyConstraintChecker {
type Error = ConstraintCheckerError;
/// Checks:
/// - `input_data` is of length 2
/// - `output_data` is of length 3
///

fn check(
&self,
input_data: &[DynamicallyTypedData],
_peeks: &[DynamicallyTypedData],
output_data: &[DynamicallyTypedData],
) -> Result<TransactionPriority, Self::Error> {
// Input must be a Mom and a Dad
ensure!(input_data.len() == 2, Self::Error::TwoParentsDoNotExist);

let mom = KittyData::try_from(&input_data[0])?;
let dad = KittyData::try_from(&input_data[1])?;
KittyHelpers::can_breed(&mom, &dad)?;
match &self {
Self::Create => {
// Make sure there are no inputs being consumed
ensure!(
input_data.is_empty(),
ConstraintCheckerError::CreatingWithInputs
);

// Make sure there is at least one output being minted
ensure!(
!output_data.is_empty(),
ConstraintCheckerError::CreatingNothing
);

// Make sure the outputs are the right type
for utxo in output_data {
let _utxo_kitty = utxo
.extract::<KittyData>()
.map_err(|_| ConstraintCheckerError::BadlyTyped)?;
}
Ok(0)
}
Self::Breed => {
// Check that we are consuming at least one input
ensure!(input_data.len() == 2, Self::Error::TwoParentsDoNotExist);

let mom = KittyData::try_from(&input_data[0])?;
let dad = KittyData::try_from(&input_data[1])?;
KittyHelpers::can_breed(&mom, &dad)?;
// Output must be Mom, Dad, Child
ensure!(output_data.len() == 3, Self::Error::NotEnoughFamilyMembers);
KittyHelpers::check_new_family(&mom, &dad, output_data)?;
Ok(0)
}
Self::UpdateKittyName => {
can_kitty_name_be_updated(input_data, output_data)?;
Ok(0)
}
}
}
}

// Output must be Mom, Dad, Child
ensure!(output_data.len() == 3, Self::Error::NotEnoughFamilyMembers);
/// Checks:
/// - Input and output is of kittyType
/// - Only name is updated and ther basicproperties are not updated.
///
pub fn can_kitty_name_be_updated(
input_data: &[DynamicallyTypedData],
output_data: &[DynamicallyTypedData],
) -> Result<TransactionPriority, ConstraintCheckerError> {
ensure!(
input_data.len() == output_data.len() && !input_data.is_empty(),
{ ConstraintCheckerError::InvalidNumberOfInputOutput }
);

let mut map: BTreeMap<KittyDNA, KittyData> = BTreeMap::new();

for utxo in input_data {
let utxo_kitty = utxo
.extract::<KittyData>()
.map_err(|_| ConstraintCheckerError::BadlyTyped)?;
map.insert(utxo_kitty.clone().dna, utxo_kitty);
}

KittyHelpers::check_new_family(&mom, &dad, output_data)?;
for utxo in output_data {
let utxo_output_kitty = utxo
.extract::<KittyData>()
.map_err(|_| ConstraintCheckerError::BadlyTyped)?;

Ok(0)
if let Some(input_kitty) = map.remove(&utxo_output_kitty.dna) {
// Element found, access the value
check_kitty_name_update(&input_kitty, &utxo_output_kitty)?;
} else {
return Err(ConstraintCheckerError::OutputUtxoMissingError);
}
}
return Ok(0);
}

/// Checks:
/// - Private function used by can_kitty_name_be_updated.
/// - Only name is updated and ther basicproperties are not updated.
///
fn check_kitty_name_update(
original_kitty: &KittyData,
updated_kitty: &KittyData,
) -> Result<TransactionPriority, ConstraintCheckerError> {
ensure!(
original_kitty != updated_kitty,
ConstraintCheckerError::KittyNameUnAltered
);
ensure!(
original_kitty.free_breedings == updated_kitty.free_breedings,
ConstraintCheckerError::FreeBreedingCannotBeUpdated
);
ensure!(
original_kitty.num_breedings == updated_kitty.num_breedings,
ConstraintCheckerError::NumOfBreedingCannotBeUpdated
);
ensure!(
original_kitty.parent == updated_kitty.parent,
ConstraintCheckerError::KittyGenderCannotBeUpdated
);
return Ok(0);
}
Loading
Loading