Skip to content

Instantly share code, notes, and snippets.

@mattlockyer
Last active June 2, 2022 17:40
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattlockyer/4821401b74cfef788642316d6279f4fc to your computer and use it in GitHub Desktop.
Save mattlockyer/4821401b74cfef788642316d6279f4fc to your computer and use it in GitHub Desktop.
NEAR Random Number (u128)
// anywhere in your contract
fn random_u128() -> u128 {
let random_seed = env::random_seed(); // len 32
// using first 16 bytes (doesn't affect randomness)
as_u128(random_seed.get(..16).unwrap())
}
fn as_u128(arr: &[u8]) -> u128 {
((arr[0] as u128) << 0) +
((arr[1] as u128) << 8) +
((arr[2] as u128) << 16) +
((arr[3] as u128) << 24) +
((arr[4] as u128) << 32) +
((arr[5] as u128) << 40) +
((arr[6] as u128) << 48) +
((arr[7] as u128) << 56) +
((arr[8] as u128) << 64) +
((arr[9] as u128) << 72) +
((arr[10] as u128) << 80) +
((arr[11] as u128) << 88) +
((arr[12] as u128) << 96) +
((arr[13] as u128) << 104) +
((arr[14] as u128) << 112) +
((arr[15] as u128) << 120)
}
@mikedotexe
Copy link

my man!

@mattlockyer
Copy link
Author

my man!

😆

@jobyid
Copy link

jobyid commented Oct 31, 2021

Hey Matt, I am trying to use this in my contract but I get an error.
panicked at 'called Option::unwrap()on aNonevalue'
Any pointers on how to fix this?
Thanks

@mattlockyer
Copy link
Author

Are you sure it has to do with slicing the random seed value?

According to the docs it should still return a vec of u8

https://docs.rs/near-sdk/4.0.0-pre.4/near_sdk/env/fn.random_seed.html

@jobyid
Copy link

jobyid commented Nov 1, 2021

I am not sure, but I have tried to isolate it and it seems to be the thing that fails. I am only learning rust so could totally be a simple error.

@mattlockyer
Copy link
Author

try not slicing it and logging the output, or using only 1 value from the vector.

Might be something wrong with your contract setup or the way you're running it e.g. perhaps env::random_seed isn't available in simulation tests or something?

I don't think it's available or has no real values in Rust unit tests.

@jobyid
Copy link

jobyid commented Nov 1, 2021

Ok cool I am testing it with unit tests right now so that is probably the issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment