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

Update chain extension example to show argument passing #1029

Merged
merged 5 commits into from
Nov 24, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
12 changes: 7 additions & 5 deletions examples/rand-extension/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub trait FetchRandom {
/// Note: this gives the operation a corresponding `func_id` (1101 in this case),
/// and the chain-side chain extension will get the `func_id` to do further operations.
#[ink(extension = 1101, returns_result = false)]
fn fetch_random() -> [u8; 32];
fn fetch_random(subject: [u8; 32]) -> [u8; 32];
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)]
Expand Down Expand Up @@ -86,11 +86,13 @@ mod rand_extension {
Self::new(Default::default())
}

/// Update the value from the runtimes random source.
/// Seed a random value by passing some known argument `subject` to the runtime's
/// random source. Then, update the current `value` stored in this contract with the
/// new random value.
#[ink(message)]
pub fn update(&mut self) -> Result<(), RandomReadErr> {
pub fn update(&mut self, subject: [u8; 32]) -> Result<(), RandomReadErr> {
// Get the on-chain random seed
let new_random = self.env().extension().fetch_random()?;
let new_random = self.env().extension().fetch_random(subject)?;
self.value = new_random;
// Emit the `RandomUpdated` event when the random seed
// is successfully fetched.
Expand Down Expand Up @@ -146,7 +148,7 @@ mod rand_extension {
assert_eq!(rand_extension.get(), [0; 32]);

// when
rand_extension.update().expect("update must work");
rand_extension.update([0_u8; 32]).expect("update must work");

// then
assert_eq!(rand_extension.get(), [1; 32]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ impl ChainExtension<Runtime> for FetchRandomExtension {
match func_id {
1101 => {
let mut env = env.buf_in_buf_out();
let random_seed = crate::RandomnessCollectiveFlip::random_seed().0;
let arg: [u8; 32] = env.read_as()?;
let random_seed = crate::RandomnessCollectiveFlip::random(&arg).0;
let random_slice = random_seed.encode();
trace!(
target: "runtime",
Expand Down