Skip to content

Instantly share code, notes, and snippets.

@mattlockyer
Last active June 2, 2022 17:40
Show Gist options
  • 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)
}
@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