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

Phat Contract 2.0 Compliance #35

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion ink/contracts/test_oracle/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ pub mod test_oracle {
.get(message.trading_pair_id)
.unwrap_or_default();
trading_pair.value = message.price.unwrap_or_default();
trading_pair.nb_updates += 1;
trading_pair.nb_updates = trading_pair.nb_updates.checked_add(1).unwrap_or(0);
trading_pair.last_update = self.env().block_timestamp();
self.trading_pairs
.insert(message.trading_pair_id, &trading_pair);
Expand Down
145 changes: 145 additions & 0 deletions ink/crates/phat_rollup_anchor_ink/src/traits/js_rollup_anchor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
use crate::traits::rollup_anchor::RollupAnchorError;
use ink::prelude::vec::Vec;
use ink::storage::Lazy;
use openbrush::contracts::access_control::{self, AccessControlError, RoleType};
use openbrush::traits::Storage;
use scale::{Decode, Encode};


pub const JS_RA_MANAGER_ROLE: RoleType = ink::selector_id!("JS_RA_MANAGER_ROLE");

#[derive(Debug, Eq, PartialEq, scale::Encode, scale::Decode)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum JsRollupAnchorError {
AccessControlError(AccessControlError),
}

/// convertor from AccessControlError to JsRollupAnchorError
impl From<AccessControlError> for JsRollupAnchorError {
fn from(error: AccessControlError) -> Self {
JsRollupAnchorError::AccessControlError(error)
}
}

type CodeHash = [u8; 32];

/// Message sent to provide the data
/// response pushed in the queue by the offchain rollup and read by the Ink! smart contract
#[derive(Encode, Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub enum ResponseMessage {
JsResponse {
/// hash of js script executed to get the data
js_script_hash: CodeHash,
/// hash of data in input of js
input_hash: CodeHash,
/// hash of settings of js
settings_hash: CodeHash,
/// response value
output_value: Vec<u8>,
},
Error {
/// hash of js script
js_script_hash: CodeHash,
/// input in js
input_value: Vec<u8>,
/// hash of settings of js
settings_hash: CodeHash,
/// when an error occurs
error: Vec<u8>,
},
}

/// Enum used in the function on_message_received to return the result
/// Input is the request type sent from the smart contract to phat offchain rollup
/// Output is the response type receive by the smart contract
pub enum MessageReceived<Input, Output> {
Ok { output: Output },
Error { input: Input, error: Vec<u8> },
}

#[derive(Default, Debug)]
#[openbrush::storage_item]
pub struct Data {
/// hash of js script executed to query the data
js_script_hash: Lazy<CodeHash>,
h4x3rotab marked this conversation as resolved.
Show resolved Hide resolved
/// hash of settings given in parameter to js runner
settings_hash: Lazy<CodeHash>,
}

#[openbrush::trait_definition]
pub trait JsRollupAnchor:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How does it simplify the use of the JS-based rollup anchor? Could you give some exapmle?

Copy link
Contributor Author

@GuiGou12358 GuiGou12358 Dec 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can find an example here: https://github.com/GuiGou12358/decentralized_oracle-graph-api-oracle/blob/main/ink/contracts/graph_api_consumer/lib.rs#L215

The JsRollupAnchor trait implements the communication logic between the JS Phat contract and the ink! contract consumer.
It alows to reduce the complexity of the contrat consumer. The developer:

  • doesn't have to test if the configured script/settings hashes match with the received ones. All is done in the JsRollupAnchor trait.
  • can use directly the business struct without care to the struct JsResponse

Storage<Data> + access_control::Internal
{
#[ink(message)]
#[openbrush::modifiers(access_control::only_role(JS_RA_MANAGER_ROLE))]
fn set_js_script_hash(&mut self, js_script_hash: CodeHash) -> Result<(), JsRollupAnchorError> {
self.data::<Data>().js_script_hash.set(&js_script_hash);
Ok(())
}

#[ink(message)]
fn get_js_script_hash(&self) -> Option<CodeHash> {
self.data::<Data>().js_script_hash.get()
}

#[ink(message)]
#[openbrush::modifiers(access_control::only_role(JS_RA_MANAGER_ROLE))]
fn set_settings_hash(&mut self, settings_hash: CodeHash) -> Result<(), JsRollupAnchorError> {
self.data::<Data>().settings_hash.set(&settings_hash);
Ok(())
}

#[ink(message)]
fn get_settings_hash(&self) -> Option<CodeHash> {
self.data::<Data>().settings_hash.get()
}

fn on_message_received<I: Decode, O: Decode>(
&mut self,
action: Vec<u8>,
) -> Result<MessageReceived<I, O>, RollupAnchorError> {
// parse the response
let response: ResponseMessage =
Decode::decode(&mut &action[..]).or(Err(RollupAnchorError::FailedToDecode))?;

match response {
ResponseMessage::JsResponse {
js_script_hash,
settings_hash,
output_value,
..
} => {
// check the js code hash
if let Some(expected_js_hash) = self.data::<Data>().js_script_hash.get() {
if js_script_hash != expected_js_hash {
return Err(RollupAnchorError::ConditionNotMet);
}
}

// check the settings hash
if let Some(expected_settings_hash) = self.data::<Data>().settings_hash.get() {
if settings_hash != expected_settings_hash {
return Err(RollupAnchorError::ConditionNotMet);
}
}

// we received the data
let output = O::decode(&mut output_value.as_slice())
.map_err(|_| RollupAnchorError::FailedToDecode)?;
Ok(MessageReceived::<I,O>::Ok { output })
}
ResponseMessage::Error {
error, input_value, ..
} => {
// we received an error
let input = I::decode(&mut input_value.as_slice())
.map_err(|_| RollupAnchorError::FailedToDecode)?;
Ok(MessageReceived::<I,O>::Error { input, error })
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ pub enum MetaTransactionError {
PublicKeyNotMatch,
PublicKeyIncorrect,
RollupAnchorError(RollupAnchorError),
NonceOverflow,
}

/// convertor from RollupAnchorError to MetaTxError
Expand Down Expand Up @@ -105,7 +106,10 @@ pub trait MetaTransaction: Storage<Data> + EventBroadcaster + RollupAnchor {
// verify the signature
self.verify(request, signature)?;
// update the nonce
let nonce = request.nonce + 1;
let nonce = request
.nonce
.checked_add(1)
.ok_or(MetaTransactionError::NonceOverflow)?;
self.data::<Data>().nonces.insert(&request.from, &nonce);
Ok(())
}
Expand Down
1 change: 1 addition & 0 deletions ink/crates/phat_rollup_anchor_ink/src/traits/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod meta_transaction;
pub mod rollup_anchor;
pub mod js_rollup_anchor;
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ pub enum RollupAnchorError {
FailedToDecode,
UnsupportedAction,
AccessControlError(AccessControlError),
QueueIndexOverflow,
}

/// convertor from AccessControlError to RollupAnchorError
Expand Down Expand Up @@ -120,7 +121,10 @@ pub trait RollupAnchor:
let encoded_value = data.encode();
self.set_value(&key, Some(&encoded_value));

self.set_queue_tail(id + 1);
self.set_queue_tail(
id.checked_add(1)
.ok_or(RollupAnchorError::QueueIndexOverflow)?,
);
self.emit_event_message_queued(id, encoded_value);

Ok(id)
Expand Down
2 changes: 1 addition & 1 deletion ink/rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[toolchain]
channel = "1.72"
channel = "1.80"
components = [
"rustc",
"cargo",
Expand Down
Loading