Skip to content

Commit

Permalink
Update chain extension example to show argument passing (use-ink#1029)
Browse files Browse the repository at this point in the history
* Add argument to rand-extension example

* add appropriate runtime and test example changes

* Clarify rand-extension  comment wrt subject argument

* Update examples/rand-extension/lib.rs

Co-authored-by: Hernando Castano <[email protected]>
Co-authored-by: Michael Müller <[email protected]>
  • Loading branch information
3 people authored and xgreenx committed Feb 8, 2022
1 parent 2521790 commit 22d5065
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
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
3 changes: 2 additions & 1 deletion examples/rand-extension/runtime/chain-extension-example.rs
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

0 comments on commit 22d5065

Please sign in to comment.