Skip to content

Commit

Permalink
initialize and shuffle
Browse files Browse the repository at this point in the history
  • Loading branch information
jhernandezb committed Dec 19, 2024
1 parent 3e5688e commit 77123ea
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
16 changes: 15 additions & 1 deletion contracts/minters/vending-minter/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,21 @@ pub fn instantiate(
let last_discount_time = env.block.time.minus_seconds(60 * 60 * 12);
LAST_DISCOUNT_TIME.save(deps.storage, &last_discount_time)?;

sg_minter_utils::initialize(deps.storage, msg.init_msg.num_tokens)
let sha256 = Sha256::digest(
format!(
"{}{}{}{}{}",
info.sender,
env.block.height,
&msg.init_msg.num_tokens,
env.block.time.nanos(),
env.transaction.map_or(0, |tx| tx.index),
)
.into_bytes(),
);
let randomness: [u8; 32] = sha256.to_vec()[0..32].try_into().map_err(|_| {
ContractError::Std(StdError::generic_err("Failed to convert sha256 to array"))
})?;
sg_minter_utils::initialize_and_shuffle(deps.storage, msg.init_msg.num_tokens, randomness)
.map_err(ContractError::MinterUtils)?;

// Submessage to instantiate sg721 contract
Expand Down
31 changes: 31 additions & 0 deletions packages/sg-minter-utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,16 @@ pub enum MinterUtilsError {
InvalidTokenId { token_id: u32 },
}

pub fn initialize_and_shuffle(
storage: &mut dyn Storage,
size: u32,
random_seed: [u8; 32],
) -> Result<(), MinterUtilsError> {
initialize(storage, size)?;
shuffle(storage, random_seed)?;
Ok(())
}

pub fn initialize(storage: &mut dyn Storage, size: u32) -> Result<(), MinterUtilsError> {
if size > MAX_SIZE {
return Err(MinterUtilsError::InvalidSize {
Expand Down Expand Up @@ -472,6 +482,27 @@ mod tests {
);
}

#[test]
fn test_initialize_with_seed() {
let mut deps = mock_dependencies();
let r: Result<(), MinterUtilsError> =
initialize_and_shuffle(&mut deps.storage, 10_000, [0; 32]);
assert!(r.is_ok());
let available_buckets = deps.storage.get(&AVAILABLE_BUCKETS_KEY).unwrap();
assert_eq!(available_buckets.len(), 40);
assert_ne!(
available_buckets,
(0..40).map(|x| x as u8).collect::<Vec<u8>>()
);
assert_eq!(
available_buckets,
[
21, 30, 37, 23, 11, 2, 29, 27, 8, 0, 7, 5, 15, 17, 6, 32, 25, 9, 36, 26, 13, 31,
24, 10, 39, 35, 33, 12, 20, 16, 28, 18, 34, 19, 1, 4, 38, 22, 14, 3
]
);
}

#[test]
fn test_shuffle_and_pick_token() {
let mut deps = mock_dependencies();
Expand Down

0 comments on commit 77123ea

Please sign in to comment.