Skip to content

imp(types): refactor Default implementations with concrete names #1099

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

Merged
merged 40 commits into from
Mar 12, 2024
Merged
Show file tree
Hide file tree
Changes from 35 commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
4f68431
use concrete channel order enum
catconcat Feb 24, 2024
59df516
Merge branch 'main' into tuan/refactor-default
catconcat Feb 24, 2024
f194383
refactor(ics04): remove Version::default()
catconcat Feb 26, 2024
de47605
refactor(ics04): remove TimeoutHeight::default()
catconcat Feb 26, 2024
e384dca
refactor: remove channelId::default()
catconcat Feb 26, 2024
526acde
fix: Version::default() to Version::empty()
catconcat Feb 26, 2024
f4f0dae
remove derive default from Timestamp
catconcat Feb 26, 2024
000959e
refactor default builder
catconcat Feb 26, 2024
2cb0808
remove Sequence::default()
catconcat Feb 26, 2024
6a31d85
remove Memo::default()
catconcat Feb 26, 2024
bab6785
refactor: add ChannelId::zero()
catconcat Feb 29, 2024
332e9e6
Merge branch 'main' into tuan/refactor-default
catconcat Feb 29, 2024
e800ea8
add From<&str> implmentation
catconcat Feb 29, 2024
c957bd9
refactor(ibccore): remove ClientId::default()
catconcat Mar 8, 2024
36fba96
refactor(ibccore): remove version::Default()
catconcat Mar 8, 2024
48656b7
refactor(ibccore): remove ConnectionEnd::default()
catconcat Mar 8, 2024
f1c1f13
refactor(ibc-apps): remove TracePath::default()
catconcat Mar 8, 2024
436703f
refactor(ibc-core): remove ProofSpecs::default()
catconcat Mar 8, 2024
6d41e93
fix(ibc-app): remove upgrade path default
catconcat Mar 8, 2024
04ae141
remove trust threshold default
catconcat Mar 8, 2024
d0562e0
refactor(ibc-testkit): remove Default from client_state initialization
catconcat Mar 8, 2024
8aea66d
refactor(ibc-testkit): remove Default() of ClientId, ConnectionId,...
catconcat Mar 8, 2024
37ce288
chore: add unclog
catconcat Mar 9, 2024
3572e3b
Merge branch 'main' into tuan/refactor-default
catconcat Mar 9, 2024
cd2addd
refactor: add Connection::zero()
catconcat Mar 11, 2024
ec84de5
use into() instead of ::from()
catconcat Mar 11, 2024
7750afd
refactor: add Version::compatibles()
catconcat Mar 11, 2024
f279965
Merge branch 'tuan/refactor-default' of github.com:notional-labs/ibc-…
catconcat Mar 11, 2024
a860979
refactor(ics24-host): make 07-tendermint-0 a constant in tests
catconcat Mar 12, 2024
a206527
chore: remove commented out impl Default
catconcat Mar 12, 2024
596eccb
add dummy ClientId
catconcat Mar 12, 2024
6aba54f
refactor(ics24-host): remove From<&str> to avoid panic on host
catconcat Mar 12, 2024
9f4bd71
remove get_compatible_versions
catconcat Mar 12, 2024
91dedf1
fix syntax error when import Version
catconcat Mar 12, 2024
c7e86e8
chore: run cargo fmt
catconcat Mar 12, 2024
4fd5dca
revert markdown format
catconcat Mar 12, 2024
cd22fb2
Merge branch 'main' into tuan/refactor-default
catconcat Mar 12, 2024
fabc36c
Merge branch 'tuan/refactor-default' of github.com:notional-labs/ibc-…
catconcat Mar 12, 2024
fdf2a7c
various refactor
catconcat Mar 12, 2024
46910f3
chore: update unclog
catconcat Mar 12, 2024
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
- [types] Refactor Default implementations with concrete names
([\#1074](https://github.com/cosmos/ibc-rs/issues/1074))
29 changes: 18 additions & 11 deletions docs/architecture/adr-005-handlers-redesign.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
# ADR 005: Handlers validation and execution separation

## Status

Accepted

## Changelog
* 9/9/2022: initial proposal

- 9/9/2022: initial proposal

## Context

Expand All @@ -15,9 +17,9 @@ Our current `deliver()` entrypoint can then be split into 2 entrypoints: `valida
This ADR will only concern itself with the external-facing API.

The following are out of scope for this ADR:
+ Exposing an `async` API
+ Enabling light clients to define and require the host to implement a set of traits

- Exposing an `async` API
- Enabling light clients to define and require the host to implement a set of traits

## Decision

Expand All @@ -26,7 +28,8 @@ Below is a diagram of how the main components of this ADR fit together.
![Main components](./assets/adr05.jpg)

### Validation vs Execution
Each handler can be split into validation and execution. *Validation* is the set of statements which can make the transaction fail. It comprises all the "checks". Execution is the set of statements which mutate the state. In the IBC standard handlers, validation occurs before execution. Note that execution can fail in practice, if say a write operation fails.

Each handler can be split into validation and execution. _Validation_ is the set of statements which can make the transaction fail. It comprises all the "checks". Execution is the set of statements which mutate the state. In the IBC standard handlers, validation occurs before execution. Note that execution can fail in practice, if say a write operation fails.

As an example, consider the [`UpdateClient` handler](https://github.com/cosmos/ibc/blob/main/spec/core/ics-002-client-semantics/README.md#update).

Expand Down Expand Up @@ -54,6 +57,7 @@ function updateClient(
```

### `ValidationContext` and `ExecutionContext`

Below, we define the `ValidationContext` and `ExecutionContext`.

```rust
Expand All @@ -78,7 +82,7 @@ trait ExecutionContext {
}
```

A useful way to understand how these traits work together is in seeing how they *could* be used to implement `deliver()`.
A useful way to understand how these traits work together is in seeing how they _could_ be used to implement `deliver()`.

```rust
fn deliver<V: ValidationContext, E: ExecutionContext>(val_ctx: &V, exec_ctx: &mut E, message: Any) -> Result<(), Error> {
Expand All @@ -87,6 +91,7 @@ fn deliver<V: ValidationContext, E: ExecutionContext>(val_ctx: &V, exec_ctx: &mu
exec_ctx.execute(message)
}
```

Note however that we will not implement `deliver()` this way for efficiency reasons (see [discussion](https://github.com/informalsystems/ibc-rs/issues/2582#issuecomment-1229988512)).

### Host based API
Expand Down Expand Up @@ -209,18 +214,20 @@ See appendix C for an example of how we intend this to be used.
## Consequences

### Positive
+ Architectures that run "validation" separately from "execution" will now be able to use the handlers

- Architectures that run "validation" separately from "execution" will now be able to use the handlers

### Negative
+ Still no async support
+ Light clients still cannot specify new requirements on the host `Context`

- Still no async support
- Light clients still cannot specify new requirements on the host `Context`

### Neutral

## References

* [Issue #2582: ADR for redesigning the modules' API](https://github.com/informalsystems/ibc-rs/issues/2582)
* [ICS24 spec](https://github.com/cosmos/ibc/blob/1b73c158dcd3b08c6af3917618dce259e30bc21b/spec/core/ics-024-host-requirements/README.md)
- [Issue #2582: ADR for redesigning the modules' API](https://github.com/informalsystems/ibc-rs/issues/2582)
- [ICS24 spec](https://github.com/cosmos/ibc/blob/1b73c158dcd3b08c6af3917618dce259e30bc21b/spec/core/ics-024-host-requirements/README.md)

## Appendices

Expand Down Expand Up @@ -296,7 +303,7 @@ trait ValidationContext {
/// Function required by ICS 03. Returns the list of all possible versions that the connection
/// handshake protocol supports.
fn get_compatible_versions(&self) -> Vec<Version> {
get_compatible_versions()
ConnectionVersion::compatibles()
}

/// Function required by ICS 03. Returns one version out of the supplied list of versions, which the
Expand Down
11 changes: 8 additions & 3 deletions ibc-apps/ics20-transfer/types/src/denom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ impl Display for TracePrefix {
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord, From)]
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, From)]
pub struct TracePath(Vec<TracePrefix>);

impl TracePath {
Expand All @@ -134,6 +134,11 @@ impl TracePath {
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}

/// Return empty trace path
pub fn empty() -> Self {
Self(vec![])
}
}

impl<'a> TryFrom<Vec<&'a str>> for TracePath {
Expand Down Expand Up @@ -294,7 +299,7 @@ impl FromStr for PrefixedDenom {

let (base_denom, trace_path) = {
if last_part == s {
(BaseDenom::from_str(s)?, TracePath::default())
(BaseDenom::from_str(s)?, TracePath::empty())
} else {
let base_denom = BaseDenom::from_str(last_part)?;
let trace_path = TracePath::try_from(parts)?;
Expand Down Expand Up @@ -334,7 +339,7 @@ impl From<PrefixedDenom> for RawDenomTrace {
impl From<BaseDenom> for PrefixedDenom {
fn from(denom: BaseDenom) -> Self {
Self {
trace_path: Default::default(),
trace_path: TracePath::empty(),
base_denom: denom,
}
}
Expand Down
6 changes: 6 additions & 0 deletions ibc-apps/ics20-transfer/types/src/memo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,12 @@ impl From<String> for Memo {
}
}

impl From<&str> for Memo {
fn from(memo: &str) -> Self {
Self(memo.to_owned())
}
}

impl FromStr for Memo {
type Err = Infallible;

Expand Down
10 changes: 5 additions & 5 deletions ibc-apps/ics721-nft-transfer/src/handler/send_transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,14 +81,14 @@ where
&msg.chan_id_on_a,
class_id,
token_id,
&packet_data.memo.clone().unwrap_or_default(),
&packet_data.memo.clone().unwrap_or("".into()),
)?;
} else {
transfer_ctx.burn_nft_validate(
&sender,
class_id,
token_id,
&packet_data.memo.clone().unwrap_or_default(),
&packet_data.memo.clone().unwrap_or("".into()),
)?;
}
let nft = transfer_ctx.get_nft(class_id, token_id)?;
Expand Down Expand Up @@ -184,14 +184,14 @@ where
&msg.chan_id_on_a,
class_id,
token_id,
&packet_data.memo.clone().unwrap_or_default(),
&packet_data.memo.clone().unwrap_or("".into()),
)?;
} else {
transfer_ctx.burn_nft_execute(
&sender,
class_id,
token_id,
&packet_data.memo.clone().unwrap_or_default(),
&packet_data.memo.clone().unwrap_or("".into()),
)?;
}
let nft = transfer_ctx.get_nft(class_id, token_id)?;
Expand Down Expand Up @@ -242,7 +242,7 @@ where
receiver: packet_data.receiver,
class: packet_data.class_id,
tokens: packet_data.token_ids,
memo: packet_data.memo.unwrap_or_default(),
memo: packet_data.memo.unwrap_or("".into()),
};
send_packet_ctx_a.emit_ibc_event(ModuleEvent::from(transfer_event).into())?;

Expand Down
7 changes: 3 additions & 4 deletions ibc-apps/ics721-nft-transfer/src/module.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
//! Provides IBC module callbacks implementation for the ICS-721 transfer.

use ibc_core::channel::types::acknowledgement::{Acknowledgement, AcknowledgementStatus};
use ibc_core::channel::types::channel::{Counterparty, Order};
use ibc_core::channel::types::packet::Packet;
Expand Down Expand Up @@ -194,7 +193,7 @@ pub fn on_recv_packet_execute(
receiver: data.receiver,
class: data.class_id,
tokens: data.token_ids,
memo: data.memo.unwrap_or_default(),
memo: data.memo.unwrap_or("".into()),
success: ack.is_successful(),
};
extras.events.push(recv_event.into());
Expand Down Expand Up @@ -259,7 +258,7 @@ pub fn on_acknowledgement_packet_execute(
receiver: data.receiver,
class: data.class_id,
tokens: data.token_ids,
memo: data.memo.unwrap_or_default(),
memo: data.memo.unwrap_or("".into()),
acknowledgement: acknowledgement.clone(),
};

Expand Down Expand Up @@ -307,7 +306,7 @@ pub fn on_timeout_packet_execute(
refund_receiver: data.sender,
refund_class: data.class_id,
refund_tokens: data.token_ids,
memo: data.memo.unwrap_or_default(),
memo: data.memo.unwrap_or("".into()),
};

let extras = ModuleExtras {
Expand Down
11 changes: 8 additions & 3 deletions ibc-apps/ics721-nft-transfer/types/src/class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ impl Display for TracePrefix {
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord, From)]
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, From)]
pub struct TracePath(Vec<TracePrefix>);

impl TracePath {
Expand All @@ -131,6 +131,11 @@ impl TracePath {
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}

/// Return empty trace path
pub fn empty() -> Self {
Self(vec![])
}
}

impl<'a> TryFrom<Vec<&'a str>> for TracePath {
Expand Down Expand Up @@ -268,7 +273,7 @@ impl FromStr for PrefixedClassId {

let (base_class_id, trace_path) = {
if last_part == s {
(ClassId::from_str(s)?, TracePath::default())
(ClassId::from_str(s)?, TracePath::empty())
} else {
let base_class_id = ClassId::from_str(last_part)?;
let trace_path = TracePath::try_from(parts)?;
Expand Down Expand Up @@ -308,7 +313,7 @@ impl From<PrefixedClassId> for RawClassTrace {
impl From<ClassId> for PrefixedClassId {
fn from(class_id: ClassId) -> Self {
Self {
trace_path: Default::default(),
trace_path: TracePath::empty(),
base_class_id: class_id,
}
}
Expand Down
6 changes: 3 additions & 3 deletions ibc-apps/ics721-nft-transfer/types/src/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use crate::error::NftTransferError;
derive(borsh::BorshSerialize, borsh::BorshDeserialize)
)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Default, PartialEq, Eq, derive_more::From)]
#[derive(Clone, Debug, PartialEq, Eq, derive_more::From)]
pub struct Data(String);

#[cfg(feature = "serde")]
Expand Down Expand Up @@ -88,7 +88,7 @@ impl<'de> serde::Deserialize<'de> for Data {
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Ics721Data(BTreeMap<String, DataValue>);

#[cfg(feature = "serde")]
Expand All @@ -100,7 +100,7 @@ impl FromStr for Ics721Data {
}
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DataValue {
value: String,
mime: Option<Mime>,
Expand Down
8 changes: 7 additions & 1 deletion ibc-apps/ics721-nft-transfer/types/src/memo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use ibc_core::primitives::prelude::*;
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Memo(String);

impl AsRef<str> for Memo {
Expand All @@ -45,6 +45,12 @@ impl From<String> for Memo {
}
}

impl From<&str> for Memo {
fn from(memo: &str) -> Self {
Self(memo.to_owned())
}
}

impl FromStr for Memo {
type Err = Infallible;

Expand Down
4 changes: 2 additions & 2 deletions ibc-clients/ics07-tendermint/src/client_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,8 @@ mod tests {
unbonding_period: Duration::new(128000, 0),
max_clock_drift: Duration::new(3, 0),
latest_height: Height::new(1, 10).expect("Never fails"),
proof_specs: ProofSpecs::default(),
upgrade_path: Default::default(),
proof_specs: ProofSpecs::cosmos(),
upgrade_path: Vec::new(),
allow_update: AllowUpdate {
after_expiry: false,
after_misbehaviour: false,
Expand Down
4 changes: 2 additions & 2 deletions ibc-clients/ics07-tendermint/types/src/client_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -440,8 +440,8 @@ mod tests {
unbonding_period: Duration::new(128000, 0),
max_clock_drift: Duration::new(3, 0),
latest_height: Height::new(0, 10).expect("Never fails"),
proof_specs: ProofSpecs::default(),
upgrade_path: Default::default(),
proof_specs: ProofSpecs::cosmos(),
upgrade_path: Vec::new(),
allow_update: AllowUpdate {
after_expiry: false,
after_misbehaviour: false,
Expand Down
6 changes: 0 additions & 6 deletions ibc-clients/ics07-tendermint/types/src/trust_threshold.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,12 +134,6 @@ impl TryFrom<Fraction> for TrustThreshold {
}
}

impl Default for TrustThreshold {
fn default() -> Self {
Self::ONE_THIRD
}
}

impl Display for TrustThreshold {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
write!(f, "{}/{}", self.numerator, self.denominator)
Expand Down
Loading