Skip to content

Commit

Permalink
Token Governor Updates (polytope-labs#275)
Browse files Browse the repository at this point in the history
Co-authored-by: David Salami <wizdave97@gmail.com>
  • Loading branch information
seunlanlege and Wizdave97 authored Jul 29, 2024
1 parent ccc6d69 commit a5a5df4
Show file tree
Hide file tree
Showing 26 changed files with 511 additions and 425 deletions.
6 changes: 5 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 6 additions & 5 deletions evm/src/modules/Registrar.sol
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ contract TokenRegistrar is BaseIsmpModule {
error UnauthorizedAction();

// @notice A user has initiated the asset registration process
event RegistrationBegun(bytes32 indexed assetId, address indexed owner);
event RegistrationBegun(bytes32 indexed assetId, address indexed owner, uint256 feePaid);

// @notice Governance has updated the registrar parameters
event ParamsUpdated(RegistrarParams oldParams, RegistrarParams newParams);
Expand Down Expand Up @@ -100,7 +100,8 @@ contract TokenRegistrar is BaseIsmpModule {
function registerAsset(bytes32 assetId) public payable {
address feeToken = IIsmpHost(_params.host).feeToken();
uint256 messagingFee = 64 * IIsmpHost(_params.host).perByteFee();
uint256 fee = _params.baseFee + messagingFee;
uint256 baseFee = _params.baseFee;
uint256 fee = baseFee + messagingFee;

// user has provided the native token
if (msg.value > 0) {
Expand All @@ -114,9 +115,9 @@ contract TokenRegistrar is BaseIsmpModule {
address(this),
block.timestamp
);
SafeERC20.safeTransfer(IERC20(feeToken), _params.host, _params.baseFee);
SafeERC20.safeTransfer(IERC20(feeToken), _params.host, baseFee);
} else {
SafeERC20.safeTransferFrom(IERC20(feeToken), msg.sender, _params.host, _params.baseFee);
SafeERC20.safeTransferFrom(IERC20(feeToken), msg.sender, _params.host, baseFee);
SafeERC20.safeTransferFrom(IERC20(feeToken), msg.sender, address(this), messagingFee);
}
bytes memory data = abi.encode(RequestBody({owner: msg.sender, assetId: assetId}));
Expand All @@ -133,7 +134,7 @@ contract TokenRegistrar is BaseIsmpModule {
});
IDispatcher(_params.host).dispatch(request);

emit RegistrationBegun({assetId: assetId, owner: msg.sender});
emit RegistrationBegun({assetId: assetId, owner: msg.sender, feePaid: baseFee });
}

// @notice Governance parameter updates
Expand Down
9 changes: 5 additions & 4 deletions modules/ismp/clients/arbitrum/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ use ismp::{
ConsensusStateId, IntermediateState, StateCommitment, StateMachineHeight, StateMachineId,
},
error::Error,
host::{ethereum, IsmpHost, StateMachine},
host::{ethereum, StateMachine},
messaging::Keccak256,
};

/// Storage layout slot for the nodes map in the Rollup Contract
Expand All @@ -46,7 +47,7 @@ pub struct GlobalState {

impl GlobalState {
/// https://github.com/OffchainLabs/nitro/blob/5e9f4228e6418b114a5aea0aa7f2f0cc161b67c0/contracts/src/state/GlobalState.sol#L16
pub fn hash<H: IsmpHost>(&self) -> H256 {
pub fn hash<H: Keccak256>(&self) -> H256 {
// abi encode packed
let mut buf = Vec::new();
buf.extend_from_slice("Global state:".as_bytes());
Expand Down Expand Up @@ -105,7 +106,7 @@ pub struct ArbitrumPayloadProof {
}

/// https://github.com/OffchainLabs/nitro/blob/5e9f4228e6418b114a5aea0aa7f2f0cc161b67c0/contracts/src/rollup/RollupLib.sol#L59
fn get_state_hash<H: IsmpHost>(
fn get_state_hash<H: Keccak256>(
global_state: GlobalState,
machine_status: MachineStatus,
inbox_max_count: U256,
Expand All @@ -120,7 +121,7 @@ fn get_state_hash<H: IsmpHost>(
H::keccak256(&buf)
}

pub fn verify_arbitrum_payload<H: IsmpHost + Send + Sync>(
pub fn verify_arbitrum_payload<H: Keccak256 + Send + Sync>(
payload: ArbitrumPayloadProof,
root: H256,
rollup_core_address: H160,
Expand Down
4 changes: 3 additions & 1 deletion modules/ismp/clients/bsc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ bsc-verifier = { workspace = true }
sync-committee-primitives = { workspace = true }
geth-primitives = { workspace = true }
evm-common = { workspace = true }
pallet-ismp-host-executive = { workspace = true }

[features]
default = ["std"]
Expand All @@ -31,5 +32,6 @@ std = [
"bsc-verifier/std",
"ismp/std",
"sync-committee-primitives/std",
"evm-common/std"
"evm-common/std",
"pallet-ismp-host-executive/std"
]
57 changes: 10 additions & 47 deletions modules/ismp/clients/bsc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,17 @@ use bsc_verifier::{
verify_bsc_header, NextValidators, VerificationResult,
};
use codec::{Decode, Encode};
use evm_common::{req_res_receipt_keys, verify_membership, verify_state_proof};
use evm_common::EvmStateMachine;
use geth_primitives::Header;
use ismp::{
consensus::{
ConsensusClient, ConsensusClientId, ConsensusStateId, StateCommitment, StateMachineClient,
},
error::Error,
host::{IsmpHost, StateMachine},
messaging::{Proof, StateCommitmentHeight},
router::RequestResponse,
messaging::StateCommitmentHeight,
};
use sp_core::{H160, H256};
use sp_core::H256;
use sync_committee_primitives::constants::BlsPublicKey;

pub const BSC_CONSENSUS_ID: ConsensusStateId = *b"BSCP";
Expand All @@ -34,24 +33,25 @@ pub struct ConsensusState {
pub finalized_height: u64,
pub finalized_hash: H256,
pub current_epoch: u64,
pub ismp_contract_address: H160,
}

pub struct BscClient<H: IsmpHost>(PhantomData<H>);
pub struct BscClient<H: IsmpHost, T: pallet_ismp_host_executive::Config>(PhantomData<(H, T)>);

impl<H: IsmpHost> Default for BscClient<H> {
impl<H: IsmpHost, T: pallet_ismp_host_executive::Config> Default for BscClient<H, T> {
fn default() -> Self {
Self(PhantomData)
}
}

impl<H: IsmpHost> Clone for BscClient<H> {
impl<H: IsmpHost, T: pallet_ismp_host_executive::Config> Clone for BscClient<H, T> {
fn clone(&self) -> Self {
Self(PhantomData)
}
}

impl<H: IsmpHost + Send + Sync + Default + 'static> ConsensusClient for BscClient<H> {
impl<H: IsmpHost + Send + Sync + Default + 'static, T: pallet_ismp_host_executive::Config>
ConsensusClient for BscClient<H, T>
{
fn verify_consensus(
&self,
_host: &dyn IsmpHost,
Expand Down Expand Up @@ -164,46 +164,9 @@ impl<H: IsmpHost + Send + Sync + Default + 'static> ConsensusClient for BscClien
id: ismp::host::StateMachine,
) -> Result<Box<dyn StateMachineClient>, ismp::error::Error> {
match id {
StateMachine::Bsc => Ok(Box::new(<EvmStateMachine<H>>::default())),
StateMachine::Bsc => Ok(Box::new(<EvmStateMachine<H, T>>::default())),
state_machine =>
Err(Error::Custom(alloc::format!("Unsupported state machine: {state_machine:?}"))),
}
}
}

#[derive(Default, Clone)]
pub struct EvmStateMachine<H: IsmpHost>(core::marker::PhantomData<H>);

impl<H: IsmpHost + Send + Sync> StateMachineClient for EvmStateMachine<H> {
fn verify_membership(
&self,
host: &dyn IsmpHost,
item: RequestResponse,
root: StateCommitment,
proof: &Proof,
) -> Result<(), Error> {
let consensus_state = host.consensus_state(proof.height.id.consensus_state_id)?;
let consensus_state = ConsensusState::decode(&mut &consensus_state[..])
.map_err(|_| Error::Custom("Cannot decode consensus state".to_string()))?;

verify_membership::<H>(item, root, proof, consensus_state.ismp_contract_address)
}

fn state_trie_key(&self, items: RequestResponse) -> Vec<Vec<u8>> {
req_res_receipt_keys::<H>(items)
}

fn verify_state_proof(
&self,
host: &dyn IsmpHost,
keys: Vec<Vec<u8>>,
root: StateCommitment,
proof: &Proof,
) -> Result<BTreeMap<Vec<u8>, Option<Vec<u8>>>, Error> {
let consensus_state = host.consensus_state(proof.height.id.consensus_state_id)?;
let consensus_state = ConsensusState::decode(&mut &consensus_state[..])
.map_err(|_| Error::Custom("Cannot decode consensus state".to_string()))?;

verify_state_proof::<H>(keys, root, proof, consensus_state.ismp_contract_address)
}
}
6 changes: 3 additions & 3 deletions modules/ismp/clients/optimism/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use ismp::{
ConsensusStateId, IntermediateState, StateCommitment, StateMachineHeight, StateMachineId,
},
error::Error,
host::{ethereum, IsmpHost, StateMachine},
host::{ethereum, StateMachine},
messaging::Keccak256,
};

Expand Down Expand Up @@ -65,7 +65,7 @@ pub struct OptimismPayloadProof {
pub timestamp: u64,
}

pub fn verify_optimism_payload<H: IsmpHost + Send + Sync>(
pub fn verify_optimism_payload<H: Keccak256 + Send + Sync>(
payload: OptimismPayloadProof,
root: H256,
l2_oracle_address: H160,
Expand Down Expand Up @@ -207,7 +207,7 @@ pub fn calculate_output_root<H: Keccak256>(
pub const CANNON: u32 = 0;
pub const _PERMISSIONED: u32 = 1;

pub fn verify_optimism_dispute_game_proof<H: IsmpHost + Send + Sync>(
pub fn verify_optimism_dispute_game_proof<H: Keccak256 + Send + Sync>(
payload: OptimismDisputeGameProof,
root: H256,
dispute_factory_address: H160,
Expand Down
1 change: 1 addition & 0 deletions modules/ismp/clients/sync-committee/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ geth-primitives = { workspace = true, default-features = false }
evm-common = { workspace = true }
arbitrum-verifier = { workspace = true }
op-verifier = { workspace = true }
pallet-ismp-host-executive = { workspace = true }

# crates.io
hex = { version = "0.4.3", default-features = false }
Expand Down
4 changes: 3 additions & 1 deletion modules/ismp/clients/sync-committee/evm-common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ publish = false
ismp = { workspace = true }
ethereum-triedb = { workspace = true }
geth-primitives = { workspace = true }
pallet-ismp-host-executive = { workspace = true }

# crates.io
trie-db = { workspace = true }
Expand Down Expand Up @@ -39,5 +40,6 @@ std = [
"ethabi/std",
"hash256-std-hasher/std",
"hex/std",
"geth-primitives/std"
"geth-primitives/std",
"pallet-ismp-host-executive/std"
]
55 changes: 54 additions & 1 deletion modules/ismp/clients/sync-committee/evm-common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,13 @@
#![allow(unused_variables)]

extern crate alloc;

use alloc::collections::BTreeMap;
use ethabi::ethereum_types::{H160, H256};
use ismp::{
consensus::StateCommitment,
consensus::{StateCommitment, StateMachineClient},
error::Error,
host::IsmpHost,
messaging::{Keccak256, Proof},
router::RequestResponse,
};
Expand All @@ -32,6 +34,7 @@ pub mod prelude {
pub use alloc::{boxed::Box, string::ToString, vec, vec::Vec};
}

use pallet_ismp_host_executive::EvmHosts;
use prelude::*;

pub mod presets;
Expand Down Expand Up @@ -110,3 +113,53 @@ pub fn verify_state_proof<H: Keccak256 + Send + Sync>(

Ok(map)
}

pub struct EvmStateMachine<H: IsmpHost, T: pallet_ismp_host_executive::Config>(
core::marker::PhantomData<(H, T)>,
);

impl<H: IsmpHost, T: pallet_ismp_host_executive::Config> Default for EvmStateMachine<H, T> {
fn default() -> Self {
Self(core::marker::PhantomData)
}
}

impl<H: IsmpHost, T: pallet_ismp_host_executive::Config> Clone for EvmStateMachine<H, T> {
fn clone(&self) -> Self {
EvmStateMachine::<H, T>::default()
}
}

impl<H: IsmpHost + Send + Sync, T: pallet_ismp_host_executive::Config> StateMachineClient
for EvmStateMachine<H, T>
{
fn verify_membership(
&self,
host: &dyn IsmpHost,
item: RequestResponse,
root: StateCommitment,
proof: &Proof,
) -> Result<(), Error> {
let contract_address = EvmHosts::<T>::get(&proof.height.id.state_id)
.ok_or_else(|| Error::Custom("Ismp contract address not found".to_string()))?;
verify_membership::<H>(item, root, proof, contract_address)
}

fn state_trie_key(&self, items: RequestResponse) -> Vec<Vec<u8>> {
// State trie keys are used to process timeouts from EVM chains
// We return the trie keys for request or response receipts
req_res_receipt_keys::<H>(items)
}

fn verify_state_proof(
&self,
host: &dyn IsmpHost,
keys: Vec<Vec<u8>>,
root: StateCommitment,
proof: &Proof,
) -> Result<BTreeMap<Vec<u8>, Option<Vec<u8>>>, Error> {
let ismp_address = EvmHosts::<T>::get(&proof.height.id.state_id)
.ok_or_else(|| Error::Custom("Ismp contract address not found".to_string()))?;
verify_state_proof::<H>(keys, root, proof, ismp_address)
}
}
Loading

0 comments on commit a5a5df4

Please sign in to comment.