diff --git a/CHANGELOG.md b/CHANGELOG.md index cd7e9284a..221127e66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### Features +- (denommetadata) [#907](https://github.com/dymensionxyz/dymension/issues/907) Add IBC middleware to migrate denom metadata to rollappp, remove `CreateDenomMetadata` and `UpdateDenomMetadata` tx handlers - (delayedack) [#849](https://github.com/dymensionxyz/dymension/issues/849) Add demand order filters: type, rollapp id and limit - (delayedack) [#850](https://github.com/dymensionxyz/dymension/issues/850) Add type filter for delayedack - (rollapp) [#829](https://github.com/dymensionxyz/dymension/issues/829) Refactor rollapp cli to be more useful @@ -81,7 +82,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ - (rollapp) [#839](https://github.com/dymensionxyz/dymension/issues/839) Remove rollapp deprecated fields - (eibc) [#836](https://github.com/dymensionxyz/dymension/issues/836) Improve eibc memo error handling - (eibc) [#830](https://github.com/dymensionxyz/dymension/issues/830) Invalid tx should return ackErr -- (eibc) [#828](https://github.com/dymensionxyz/dymension/issues/828) Wrong packet written on delayedack acknowledgment +- (eibc) [#828](https://github.com/dymensionxyz/dymension/issues/828) Wrong packet written on delayedack acknowledgement - (delayedack) [#822](https://github.com/dymensionxyz/dymension/issues/822) Acknowledgement not written in case of ackerr - (rollapp) [#820](https://github.com/dymensionxyz/dymension/issues/820) Invariant block-height-to-finalization-queue fix for freezing rollapp - (delayedack) [#814](https://github.com/dymensionxyz/dymension/issues/814) Proof height ante handler doesn't gurantee uniqueness diff --git a/app/app.go b/app/app.go index 0d5c1ad83..ad6983e7c 100644 --- a/app/app.go +++ b/app/app.go @@ -29,7 +29,7 @@ import ( "github.com/cosmos/cosmos-sdk/server/api" "github.com/cosmos/cosmos-sdk/server/config" servertypes "github.com/cosmos/cosmos-sdk/server/types" - simapp "github.com/cosmos/cosmos-sdk/simapp" + "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/store/streaming" storetypes "github.com/cosmos/cosmos-sdk/store/types" @@ -110,7 +110,7 @@ import ( simappparams "github.com/cosmos/cosmos-sdk/simapp/params" - ante "github.com/dymensionxyz/dymension/v3/app/ante" + "github.com/dymensionxyz/dymension/v3/app/ante" appparams "github.com/dymensionxyz/dymension/v3/app/params" rollappmodule "github.com/dymensionxyz/dymension/v3/x/rollapp" @@ -144,6 +144,8 @@ import ( packetforwardkeeper "github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v6/packetforward/keeper" packetforwardtypes "github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v6/packetforward/types" + "github.com/dymensionxyz/dymension/v3/x/transferinject" + /* ------------------------------ ethermint imports ----------------------------- */ "github.com/evmos/ethermint/ethereum/eip712" @@ -171,14 +173,14 @@ import ( "github.com/osmosis-labs/osmosis/v15/x/gamm" gammkeeper "github.com/osmosis-labs/osmosis/v15/x/gamm/keeper" gammtypes "github.com/osmosis-labs/osmosis/v15/x/gamm/types" - incentives "github.com/osmosis-labs/osmosis/v15/x/incentives" + "github.com/osmosis-labs/osmosis/v15/x/incentives" incentiveskeeper "github.com/osmosis-labs/osmosis/v15/x/incentives/keeper" incentivestypes "github.com/osmosis-labs/osmosis/v15/x/incentives/types" "github.com/osmosis-labs/osmosis/v15/x/poolmanager" poolmanagerkeeper "github.com/osmosis-labs/osmosis/v15/x/poolmanager/keeper" poolmanagertypes "github.com/osmosis-labs/osmosis/v15/x/poolmanager/types" - txfees "github.com/osmosis-labs/osmosis/v15/x/txfees" + "github.com/osmosis-labs/osmosis/v15/x/txfees" txfeeskeeper "github.com/osmosis-labs/osmosis/v15/x/txfees/keeper" txfeestypes "github.com/osmosis-labs/osmosis/v15/x/txfees/types" @@ -597,19 +599,6 @@ func New( nil, ) - // Create Transfer Keepers - app.TransferKeeper = ibctransferkeeper.NewKeeper( - appCodec, - keys[ibctransfertypes.StoreKey], - app.GetSubspace(ibctransfertypes.ModuleName), - app.IBCKeeper.ChannelKeeper, - app.IBCKeeper.ChannelKeeper, - &app.IBCKeeper.PortKeeper, - app.AccountKeeper, - app.BankKeeper, - scopedTransferKeeper, - ) - app.DenomMetadataKeeper = denommetadatamodulekeeper.NewKeeper( app.BankKeeper, ) @@ -626,18 +615,31 @@ func New( keys[rollappmoduletypes.MemStoreKey], app.GetSubspace(rollappmoduletypes.ModuleName), app.IBCKeeper.ClientKeeper, - app.TransferKeeper, app.IBCKeeper.ChannelKeeper, app.BankKeeper, app.DenomMetadataKeeper, ) + // Create Transfer Keepers + app.TransferKeeper = ibctransferkeeper.NewKeeper( + appCodec, + keys[ibctransfertypes.StoreKey], + app.GetSubspace(ibctransfertypes.ModuleName), + transferinject.NewIBCSendMiddleware(app.IBCKeeper.ChannelKeeper, app.RollappKeeper, app.BankKeeper), + app.IBCKeeper.ChannelKeeper, + &app.IBCKeeper.PortKeeper, + app.AccountKeeper, + app.BankKeeper, + scopedTransferKeeper, + ) + + app.RollappKeeper.SetTransferKeeper(app.TransferKeeper) + app.SequencerKeeper = *sequencermodulekeeper.NewKeeper( appCodec, keys[sequencermoduletypes.StoreKey], keys[sequencermoduletypes.MemStoreKey], app.GetSubspace(sequencermoduletypes.ModuleName), - app.BankKeeper, app.RollappKeeper, ) @@ -743,7 +745,14 @@ func New( transferMiddleware := ibctransfer.NewIBCModule(app.TransferKeeper) var transferStack ibcporttypes.IBCModule - transferStack = bridging_fee.NewIBCMiddleware(transferMiddleware, app.IBCKeeper.ChannelKeeper, app.DelayedAckKeeper, app.TransferKeeper, app.AccountKeeper.GetModuleAddress(txfeestypes.ModuleName)) + transferStack = bridging_fee.NewIBCMiddleware( + transferMiddleware, + app.IBCKeeper.ChannelKeeper, + app.DelayedAckKeeper, + app.RollappKeeper, + app.TransferKeeper, + app.AccountKeeper.GetModuleAddress(txfeestypes.ModuleName), + ) transferStack = packetforwardmiddleware.NewIBCMiddleware( transferStack, @@ -752,7 +761,8 @@ func New( packetforwardkeeper.DefaultForwardTransferPacketTimeoutTimestamp, packetforwardkeeper.DefaultRefundTransferPacketTimeoutTimestamp, ) - transferStack = delayedackmodule.NewIBCMiddleware(transferStack, app.DelayedAckKeeper) + delayedAckMiddleware := delayedackmodule.NewIBCMiddleware(transferStack, app.DelayedAckKeeper, app.RollappKeeper) + transferStack = transferinject.NewIBCAckMiddleware(delayedAckMiddleware, app.RollappKeeper) // Create static IBC router, add transfer route, then set and seal it ibcRouter := ibcporttypes.NewRouter() @@ -764,7 +774,7 @@ func New( app.RollappKeeper.SetHooks(rollappmoduletypes.NewMultiRollappHooks( // insert rollapp hooks receivers here app.SequencerKeeper.RollappHooks(), - transferStack.(delayedackmodule.IBCMiddleware), + delayedAckMiddleware, )) /**** Module Options ****/ diff --git a/ibctesting/delayed_ack_test.go b/ibctesting/delayed_ack_test.go index 0edbdf8f2..28ca29fbb 100644 --- a/ibctesting/delayed_ack_test.go +++ b/ibctesting/delayed_ack_test.go @@ -4,6 +4,7 @@ import ( "testing" sdk "github.com/cosmos/cosmos-sdk/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/stretchr/testify/suite" "github.com/cosmos/ibc-go/v6/modules/apps/transfer/types" @@ -25,6 +26,9 @@ func TestDelayedAckTestSuite(t *testing.T) { func (suite *DelayedAckTestSuite) SetupTest() { suite.IBCTestUtilSuite.SetupTest() + ConvertToApp(suite.hubChain).BankKeeper.SetDenomMetaData(suite.hubChain.GetContext(), banktypes.Metadata{ + Base: sdk.DefaultBondDenom, + }) } // Transfer from cosmos chain to the hub. No delay expected diff --git a/ibctesting/eibc_test.go b/ibctesting/eibc_test.go index 197819171..fc5047a52 100644 --- a/ibctesting/eibc_test.go +++ b/ibctesting/eibc_test.go @@ -9,6 +9,7 @@ import ( "testing" sdk "github.com/cosmos/cosmos-sdk/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/stretchr/testify/suite" "github.com/cosmos/ibc-go/v6/modules/apps/transfer/types" @@ -34,6 +35,9 @@ func TestEIBCTestSuite(t *testing.T) { func (suite *EIBCTestSuite) SetupTest() { suite.IBCTestUtilSuite.SetupTest() + ConvertToApp(suite.hubChain).BankKeeper.SetDenomMetaData(suite.hubChain.GetContext(), banktypes.Metadata{ + Base: sdk.DefaultBondDenom, + }) eibcKeeper := ConvertToApp(suite.hubChain).EIBCKeeper suite.msgServer = eibckeeper.NewMsgServerImpl(eibcKeeper) // Change the delayedAck epoch to trigger every month to not diff --git a/ibctesting/utils_test.go b/ibctesting/utils_test.go index 04e9eea00..dd191ebb0 100644 --- a/ibctesting/utils_test.go +++ b/ibctesting/utils_test.go @@ -19,13 +19,15 @@ import ( channeltypes "github.com/cosmos/ibc-go/v6/modules/core/04-channel/types" ibctesting "github.com/cosmos/ibc-go/v6/testing" "github.com/cosmos/ibc-go/v6/testing/mock" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + "github.com/dymensionxyz/dymension/v3/app" "github.com/dymensionxyz/dymension/v3/app/apptesting" common "github.com/dymensionxyz/dymension/v3/x/common/types" + eibctypes "github.com/dymensionxyz/dymension/v3/x/eibc/types" rollappkeeper "github.com/dymensionxyz/dymension/v3/x/rollapp/keeper" rollapptypes "github.com/dymensionxyz/dymension/v3/x/rollapp/types" sequencertypes "github.com/dymensionxyz/dymension/v3/x/sequencer/types" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" @@ -240,7 +242,7 @@ func (suite *IBCTestUtilSuite) NewTransferPath(chainA, chainB *ibctesting.TestCh func (suite *IBCTestUtilSuite) GetRollappToHubIBCDenomFromPacket(packet channeltypes.Packet) string { var data transfertypes.FungibleTokenPacketData - err := transfertypes.ModuleCdc.UnmarshalJSON(packet.GetData(), &data) + err := eibctypes.ModuleCdc.UnmarshalJSON(packet.GetData(), &data) suite.Require().NoError(err) return suite.GetIBCDenomForChannel(packet.GetDestChannel(), data.Denom) } diff --git a/proto/dymension/rollapp/rollapp.proto b/proto/dymension/rollapp/rollapp.proto index caee9a767..412512530 100644 --- a/proto/dymension/rollapp/rollapp.proto +++ b/proto/dymension/rollapp/rollapp.proto @@ -47,6 +47,8 @@ message Rollapp { string channel_id = 8; // frozen is a boolean that indicates if the rollapp is frozen. bool frozen = 9; + // registeredDenoms is a list of registered denom bases on this rollapp + repeated string registeredDenoms = 10; } // Rollapp summary is a compact representation of Rollapp diff --git a/testutil/keeper/delayedack.go b/testutil/keeper/delayedack.go index 39e7f19d4..9d0813239 100644 --- a/testutil/keeper/delayedack.go +++ b/testutil/keeper/delayedack.go @@ -11,19 +11,21 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" typesparams "github.com/cosmos/cosmos-sdk/x/params/types" + transfertypes "github.com/cosmos/ibc-go/v6/modules/apps/transfer/types" clienttypes "github.com/cosmos/ibc-go/v6/modules/core/02-client/types" connectiontypes "github.com/cosmos/ibc-go/v6/modules/core/03-connection/types" channeltypes "github.com/cosmos/ibc-go/v6/modules/core/04-channel/types" "github.com/cosmos/ibc-go/v6/modules/core/exported" ibctypes "github.com/cosmos/ibc-go/v6/modules/light-clients/07-tendermint/types" - "github.com/dymensionxyz/dymension/v3/x/delayedack/keeper" - "github.com/dymensionxyz/dymension/v3/x/delayedack/types" - rollapptypes "github.com/dymensionxyz/dymension/v3/x/rollapp/types" - sequencertypes "github.com/dymensionxyz/dymension/v3/x/sequencer/types" "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/libs/log" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" tmdb "github.com/tendermint/tm-db" + + "github.com/dymensionxyz/dymension/v3/x/delayedack/keeper" + "github.com/dymensionxyz/dymension/v3/x/delayedack/types" + rollapptypes "github.com/dymensionxyz/dymension/v3/x/rollapp/types" + sequencertypes "github.com/dymensionxyz/dymension/v3/x/sequencer/types" ) type ChannelKeeperStub struct{} @@ -113,6 +115,10 @@ func (RollappKeeperStub) GetAllRollapps(ctx sdk.Context) (list []rollapptypes.Ro return []rollapptypes.Rollapp{} } +func (r RollappKeeperStub) ExtractRollappIDAndTransferPacketFromData(sdk.Context, []byte, string, string) (string, *transfertypes.FungibleTokenPacketData, error) { + return "rollappID", &transfertypes.FungibleTokenPacketData{}, nil +} + type SequencerKeeperStub struct{} func (SequencerKeeperStub) GetSequencer(ctx sdk.Context, sequencerAddress string) (val sequencertypes.Sequencer, found bool) { diff --git a/testutil/keeper/rollapp.go b/testutil/keeper/rollapp.go index 469751e8d..9cc97e9a0 100644 --- a/testutil/keeper/rollapp.go +++ b/testutil/keeper/rollapp.go @@ -9,6 +9,7 @@ import ( storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" typesparams "github.com/cosmos/cosmos-sdk/x/params/types" + "github.com/dymensionxyz/dymension/v3/x/rollapp/keeper" "github.com/dymensionxyz/dymension/v3/x/rollapp/types" @@ -46,7 +47,6 @@ func RollappKeeper(t testing.TB) (*keeper.Keeper, sdk.Context) { nil, nil, nil, - nil, ) ctx := sdk.NewContext(stateStore, tmproto.Header{}, false, log.NewNopLogger()) diff --git a/x/bridging_fee/ibc_middleware.go b/x/bridging_fee/ibc_middleware.go index c747da42b..d043f9dc0 100644 --- a/x/bridging_fee/ibc_middleware.go +++ b/x/bridging_fee/ibc_middleware.go @@ -4,13 +4,14 @@ import ( errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - transfer "github.com/cosmos/ibc-go/v6/modules/apps/transfer" + "github.com/cosmos/ibc-go/v6/modules/apps/transfer" transferkeeper "github.com/cosmos/ibc-go/v6/modules/apps/transfer/keeper" channeltypes "github.com/cosmos/ibc-go/v6/modules/core/04-channel/types" porttypes "github.com/cosmos/ibc-go/v6/modules/core/05-port/types" "github.com/cosmos/ibc-go/v6/modules/core/exported" delayedaackkeeper "github.com/dymensionxyz/dymension/v3/x/delayedack/keeper" + rollappkeeper "github.com/dymensionxyz/dymension/v3/x/rollapp/keeper" ) const ( @@ -27,17 +28,26 @@ type BridgingFeeMiddleware struct { transfer.IBCModule porttypes.ICS4Wrapper + rollappKeeper rollappkeeper.Keeper delayedAckKeeper delayedaackkeeper.Keeper transferKeeper transferkeeper.Keeper feeModuleAddr sdk.AccAddress } // NewIBCMiddleware creates a new IBCMiddleware given the keeper and underlying application -func NewIBCMiddleware(transfer transfer.IBCModule, channelKeeper porttypes.ICS4Wrapper, keeper delayedaackkeeper.Keeper, transferKeeper transferkeeper.Keeper, feeModuleAddr sdk.AccAddress) *BridgingFeeMiddleware { +func NewIBCMiddleware( + transfer transfer.IBCModule, + channelKeeper porttypes.ICS4Wrapper, + delayedAckKeeper delayedaackkeeper.Keeper, + rollappKeeper rollappkeeper.Keeper, + transferKeeper transferkeeper.Keeper, + feeModuleAddr sdk.AccAddress, +) *BridgingFeeMiddleware { return &BridgingFeeMiddleware{ IBCModule: transfer, ICS4Wrapper: channelKeeper, - delayedAckKeeper: keeper, + delayedAckKeeper: delayedAckKeeper, + rollappKeeper: rollappKeeper, transferKeeper: transferKeeper, feeModuleAddr: feeModuleAddr, } @@ -59,7 +69,7 @@ func (im *BridgingFeeMiddleware) OnRecvPacket(ctx sdk.Context, packet channeltyp "packet_sequence", packet.Sequence) rollappPortOnHub, rollappChannelOnHub := packet.DestinationPort, packet.DestinationChannel - rollappID, transferPacketData, err := im.delayedAckKeeper.ExtractRollappIDAndTransferPacket(ctx, packet, rollappPortOnHub, rollappChannelOnHub) + rollappID, transferPacketData, err := im.rollappKeeper.ExtractRollappIDAndTransferPacketFromData(ctx, packet.Data, rollappPortOnHub, rollappChannelOnHub) if err != nil { logger.Error("Failed to extract rollapp id from packet", "err", err) return channeltypes.NewErrorAcknowledgement(err) diff --git a/x/delayedack/eibc.go b/x/delayedack/eibc.go index b28dc607c..b5dc8ef9a 100644 --- a/x/delayedack/eibc.go +++ b/x/delayedack/eibc.go @@ -43,9 +43,9 @@ func (im IBCMiddleware) eIBCDemandOrderHandler(ctx sdk.Context, rollappPacket co var feeMultiplier sdk.Dec switch t { case commontypes.RollappPacket_ON_TIMEOUT: - feeMultiplier = im.keeper.TimeoutFee(ctx) + feeMultiplier = im.TimeoutFee(ctx) case commontypes.RollappPacket_ON_ACK: - feeMultiplier = im.keeper.ErrAckFee(ctx) + feeMultiplier = im.ErrAckFee(ctx) } fee := amountDec.Mul(feeMultiplier).TruncateInt() if !fee.IsPositive() { @@ -64,7 +64,7 @@ func (im IBCMiddleware) eIBCDemandOrderHandler(ctx sdk.Context, rollappPacket co return fmt.Errorf("create eibc demand order: %w", err) } - err = im.keeper.SetDemandOrder(ctx, eibcDemandOrder) + err = im.SetDemandOrder(ctx, eibcDemandOrder) if err != nil { return fmt.Errorf("set eibc demand order: %w", err) } @@ -86,7 +86,7 @@ func (im IBCMiddleware) createDemandOrderFromIBCPacket(ctx sdk.Context, fungible return nil, fmt.Errorf("validate eibc metadata: %w", err) } // Verify the original recipient is not a blocked sender otherwise could potentially use eibc to bypass it - if im.keeper.BlockedAddr(fungibleTokenPacketData.Receiver) { + if im.BlockedAddr(fungibleTokenPacketData.Receiver) { return nil, fmt.Errorf("not allowed to receive funds: receiver: %s", fungibleTokenPacketData.Receiver) } // Calculate the demand order price and validate it, @@ -126,7 +126,7 @@ func (im IBCMiddleware) createDemandOrderFromIBCPacket(ctx sdk.Context, fungible demandOrderDenom = trace.IBCDenom() demandOrderRecipient = fungibleTokenPacketData.Sender // and who tried to send it (refund because it failed) case commontypes.RollappPacket_ON_RECV: - bridgingFee := im.keeper.BridgingFeeFromAmt(ctx, amt) + bridgingFee := im.BridgingFeeFromAmt(ctx, amt) if bridgingFee.GT(fee) { // We check that the fee the fulfiller makes is at least as big as the bridging fee they will have to pay later // this is to improve UX and help fulfillers not lose money. diff --git a/x/delayedack/ibc_middleware.go b/x/delayedack/ibc_middleware.go index 566cca383..b2648fb8d 100644 --- a/x/delayedack/ibc_middleware.go +++ b/x/delayedack/ibc_middleware.go @@ -4,10 +4,7 @@ import ( "errors" errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" - clienttypes "github.com/cosmos/ibc-go/v6/modules/core/02-client/types" channeltypes "github.com/cosmos/ibc-go/v6/modules/core/04-channel/types" porttypes "github.com/cosmos/ibc-go/v6/modules/core/05-port/types" "github.com/cosmos/ibc-go/v6/modules/core/exported" @@ -23,14 +20,16 @@ var _ porttypes.Middleware = &IBCMiddleware{} // IBCMiddleware implements the ICS26 callbacks type IBCMiddleware struct { porttypes.IBCModule - keeper keeper.Keeper + keeper.Keeper + rollappKeeper types.RollappKeeper } // NewIBCMiddleware creates a new IBCMiddleware given the keeper and underlying application -func NewIBCMiddleware(app porttypes.IBCModule, keeper keeper.Keeper) IBCMiddleware { +func NewIBCMiddleware(app porttypes.IBCModule, k keeper.Keeper, rollappKeeper types.RollappKeeper) IBCMiddleware { return IBCMiddleware{ - IBCModule: app, - keeper: keeper, + IBCModule: app, + Keeper: k, + rollappKeeper: rollappKeeper, } } @@ -41,7 +40,7 @@ func (im IBCMiddleware) OnRecvPacket( packet channeltypes.Packet, relayer sdk.AccAddress, ) exported.Acknowledgement { - if !im.keeper.IsRollappsEnabled(ctx) { + if !im.IsRollappsEnabled(ctx) { return im.IBCModule.OnRecvPacket(ctx, packet, relayer) } logger := ctx.Logger().With( @@ -52,7 +51,12 @@ func (im IBCMiddleware) OnRecvPacket( rollappPortOnHub, rollappChannelOnHub := packet.DestinationPort, packet.DestinationChannel - rollappID, transferPacketData, err := im.keeper.ExtractRollappIDAndTransferPacket(ctx, packet, rollappPortOnHub, rollappChannelOnHub) + rollappID, transferPacketData, err := im.rollappKeeper.ExtractRollappIDAndTransferPacketFromData( + ctx, + packet.Data, + rollappPortOnHub, + rollappChannelOnHub, + ) if err != nil { logger.Error("Failed to extract rollapp id from packet", "err", err) return channeltypes.NewErrorAcknowledgement(err) @@ -63,7 +67,7 @@ func (im IBCMiddleware) OnRecvPacket( return im.IBCModule.OnRecvPacket(ctx, packet, relayer) } - err = im.keeper.ValidateRollappId(ctx, rollappID, rollappPortOnHub, rollappChannelOnHub) + err = im.ValidateRollappId(ctx, rollappID, rollappPortOnHub, rollappChannelOnHub) if err != nil { logger.Error("Failed to validate rollappID", "rollappID", rollappID, "err", err) return channeltypes.NewErrorAcknowledgement(err) @@ -95,7 +99,7 @@ func (im IBCMiddleware) OnRecvPacket( ProofHeight: proofHeight, Type: commontypes.RollappPacket_ON_RECV, } - im.keeper.SetRollappPacket(ctx, rollappPacket) + im.SetRollappPacket(ctx, rollappPacket) logger.Debug("Set rollapp packet", "rollappID", rollappPacket.RollappId, @@ -117,7 +121,7 @@ func (im IBCMiddleware) OnAcknowledgementPacket( acknowledgement []byte, relayer sdk.AccAddress, ) error { - if !im.keeper.IsRollappsEnabled(ctx) { + if !im.IsRollappsEnabled(ctx) { return im.IBCModule.OnAcknowledgementPacket(ctx, packet, acknowledgement, relayer) } logger := ctx.Logger().With( @@ -134,7 +138,7 @@ func (im IBCMiddleware) OnAcknowledgementPacket( return errorsmod.Wrapf(types.ErrUnknownRequest, "unmarshal ICS-20 transfer packet acknowledgement: %v", err) } - rollappID, transferPacketData, err := im.keeper.ExtractRollappIDAndTransferPacket(ctx, packet, rollappPortOnHub, rollappChannelOnHub) + rollappID, transferPacketData, err := im.rollappKeeper.ExtractRollappIDAndTransferPacketFromData(ctx, packet.Data, rollappPortOnHub, rollappChannelOnHub) if err != nil { logger.Error("Failed to extract rollapp id from channel", "err", err) return err @@ -144,7 +148,7 @@ func (im IBCMiddleware) OnAcknowledgementPacket( logger.Debug("Skipping IBC transfer OnAcknowledgementPacket for non-rollapp chain") return im.IBCModule.OnAcknowledgementPacket(ctx, packet, acknowledgement, relayer) } - err = im.keeper.ValidateRollappId(ctx, rollappID, rollappPortOnHub, rollappChannelOnHub) + err = im.ValidateRollappId(ctx, rollappID, rollappPortOnHub, rollappChannelOnHub) if err != nil { logger.Error("Failed to validate rollappID", "rollappID", rollappID, "err", err) return err @@ -184,7 +188,7 @@ func (im IBCMiddleware) OnAcknowledgementPacket( ProofHeight: proofHeight, Type: commontypes.RollappPacket_ON_ACK, } - im.keeper.SetRollappPacket(ctx, rollappPacket) + im.SetRollappPacket(ctx, rollappPacket) logger.Debug("Set rollapp packet", "rollappID", rollappPacket.RollappId, @@ -209,7 +213,7 @@ func (im IBCMiddleware) OnTimeoutPacket( packet channeltypes.Packet, relayer sdk.AccAddress, ) error { - if !im.keeper.IsRollappsEnabled(ctx) { + if !im.IsRollappsEnabled(ctx) { return im.IBCModule.OnTimeoutPacket(ctx, packet, relayer) } logger := ctx.Logger().With( @@ -220,7 +224,12 @@ func (im IBCMiddleware) OnTimeoutPacket( rollappPortOnHub, rollappChannelOnHub := packet.SourcePort, packet.SourceChannel - rollappID, transferPacketData, err := im.keeper.ExtractRollappIDAndTransferPacket(ctx, packet, rollappPortOnHub, rollappChannelOnHub) + rollappID, transferPacketData, err := im.rollappKeeper.ExtractRollappIDAndTransferPacketFromData( + ctx, + packet.Data, + rollappPortOnHub, + rollappChannelOnHub, + ) if err != nil { logger.Error("Failed to extract rollapp id from channel", "err", err) return err @@ -231,7 +240,7 @@ func (im IBCMiddleware) OnTimeoutPacket( return im.IBCModule.OnTimeoutPacket(ctx, packet, relayer) } - err = im.keeper.ValidateRollappId(ctx, rollappID, rollappPortOnHub, rollappChannelOnHub) + err = im.ValidateRollappId(ctx, rollappID, rollappPortOnHub, rollappChannelOnHub) if err != nil { logger.Error("Failed to validate rollappID", "rollappID", rollappID, "err", err) return err @@ -270,7 +279,7 @@ func (im IBCMiddleware) OnTimeoutPacket( ProofHeight: proofHeight, Type: commontypes.RollappPacket_ON_TIMEOUT, } - im.keeper.SetRollappPacket(ctx, rollappPacket) + im.SetRollappPacket(ctx, rollappPacket) logger.Debug("Set rollapp packet", "rollappID", rollappPacket.RollappId, @@ -285,36 +294,6 @@ func (im IBCMiddleware) OnTimeoutPacket( return nil } -/* ------------------------------- ICS4Wrapper ------------------------------ */ - -// SendPacket implements the ICS4 Wrapper interface -func (im IBCMiddleware) SendPacket( - ctx sdk.Context, - chanCap *capabilitytypes.Capability, - sourcePort string, - sourceChannel string, - timeoutHeight clienttypes.Height, - timeoutTimestamp uint64, - data []byte, -) (sequence uint64, err error) { - return im.keeper.SendPacket(ctx, chanCap, sourcePort, sourceChannel, timeoutHeight, timeoutTimestamp, data) -} - -// WriteAcknowledgement implements the ICS4 Wrapper interface -func (im IBCMiddleware) WriteAcknowledgement( - ctx sdk.Context, - chanCap *capabilitytypes.Capability, - packet exported.PacketI, - ack exported.Acknowledgement, -) error { - return im.keeper.WriteAcknowledgement(ctx, chanCap, packet, ack) -} - -// GetAppVersion returns the application version of the underlying application -func (im IBCMiddleware) GetAppVersion(ctx sdk.Context, portID, channelID string) (string, bool) { - return im.keeper.GetAppVersion(ctx, portID, channelID) -} - // GetProofHeight returns the proof height of the packet func (im IBCMiddleware) GetProofHeight(ctx sdk.Context, packetType commontypes.RollappPacket_Type, rollappPortOnHub string, rollappChannelOnHub string, sequence uint64, @@ -332,7 +311,7 @@ func (im IBCMiddleware) GetProofHeight(ctx sdk.Context, packetType commontypes.R // CheckIfFinalized checks if the packet is finalized and if so, updates the packet status func (im IBCMiddleware) CheckIfFinalized(ctx sdk.Context, rollappID string, proofHeight uint64) (bool, error) { - finalizedHeight, err := im.keeper.GetRollappFinalizedHeight(ctx, rollappID) + finalizedHeight, err := im.GetRollappFinalizedHeight(ctx, rollappID) if err != nil { if errors.Is(err, rollapptypes.ErrNoFinalizedStateYetForRollapp) { return false, nil diff --git a/x/delayedack/keeper/fraud_test.go b/x/delayedack/keeper/fraud_test.go index d5bfe0e43..e552d06d1 100644 --- a/x/delayedack/keeper/fraud_test.go +++ b/x/delayedack/keeper/fraud_test.go @@ -3,14 +3,15 @@ package keeper_test import ( ibctransfer "github.com/cosmos/ibc-go/v6/modules/apps/transfer" channeltypes "github.com/cosmos/ibc-go/v6/modules/core/04-channel/types" + commontypes "github.com/dymensionxyz/dymension/v3/x/common/types" damodule "github.com/dymensionxyz/dymension/v3/x/delayedack" "github.com/dymensionxyz/dymension/v3/x/delayedack/types" ) func (suite *DelayedAckTestSuite) TestHandleFraud() { - keeper, ctx := suite.App.DelayedAckKeeper, suite.Ctx - transferStack := damodule.NewIBCMiddleware(ibctransfer.NewIBCModule(suite.App.TransferKeeper), keeper) + keeper, ctx, rollappKeeper := suite.App.DelayedAckKeeper, suite.Ctx, suite.App.RollappKeeper + transferStack := damodule.NewIBCMiddleware(ibctransfer.NewIBCModule(suite.App.TransferKeeper), keeper, rollappKeeper) rollappId := "testRollappId" pkts := generatePackets(rollappId, 5) @@ -46,8 +47,8 @@ func (suite *DelayedAckTestSuite) TestHandleFraud() { } func (suite *DelayedAckTestSuite) TestDeletionOfRevertedPackets() { - keeper, ctx := suite.App.DelayedAckKeeper, suite.Ctx - transferStack := damodule.NewIBCMiddleware(ibctransfer.NewIBCModule(suite.App.TransferKeeper), keeper) + keeper, ctx, rollappKeeper := suite.App.DelayedAckKeeper, suite.Ctx, suite.App.RollappKeeper + transferStack := damodule.NewIBCMiddleware(ibctransfer.NewIBCModule(suite.App.TransferKeeper), keeper, rollappKeeper) rollappId := "testRollappId" pkts := generatePackets(rollappId, 5) diff --git a/x/delayedack/keeper/invariants_test.go b/x/delayedack/keeper/invariants_test.go index 31b00e34a..ec4363992 100644 --- a/x/delayedack/keeper/invariants_test.go +++ b/x/delayedack/keeper/invariants_test.go @@ -5,6 +5,7 @@ import ( ibctransfer "github.com/cosmos/ibc-go/v6/modules/apps/transfer" channeltypes "github.com/cosmos/ibc-go/v6/modules/core/04-channel/types" + commontypes "github.com/dymensionxyz/dymension/v3/x/common/types" damodule "github.com/dymensionxyz/dymension/v3/x/delayedack" "github.com/dymensionxyz/dymension/v3/x/rollapp/types" @@ -14,8 +15,8 @@ import ( func (suite *DelayedAckTestSuite) TestInvariants() { suite.SetupTest() - keeper := suite.App.DelayedAckKeeper - transferStack := damodule.NewIBCMiddleware(ibctransfer.NewIBCModule(suite.App.TransferKeeper), keeper) + keeper, rollappKeeper := suite.App.DelayedAckKeeper, suite.App.RollappKeeper + transferStack := damodule.NewIBCMiddleware(ibctransfer.NewIBCModule(suite.App.TransferKeeper), keeper, rollappKeeper) initialHeight := int64(10) suite.Ctx = suite.Ctx.WithBlockHeight(initialHeight) diff --git a/x/delayedack/keeper/keeper.go b/x/delayedack/keeper/keeper.go index 6983a5dc3..110510584 100644 --- a/x/delayedack/keeper/keeper.go +++ b/x/delayedack/keeper/keeper.go @@ -5,24 +5,22 @@ import ( "fmt" errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - transfertypes "github.com/cosmos/ibc-go/v6/modules/apps/transfer/types" clienttypes "github.com/cosmos/ibc-go/v6/modules/core/02-client/types" connectiontypes "github.com/cosmos/ibc-go/v6/modules/core/03-connection/types" channeltypes "github.com/cosmos/ibc-go/v6/modules/core/04-channel/types" porttypes "github.com/cosmos/ibc-go/v6/modules/core/05-port/types" "github.com/cosmos/ibc-go/v6/modules/core/exported" - ibctypes "github.com/cosmos/ibc-go/v6/modules/light-clients/07-tendermint/types" tenderminttypes "github.com/cosmos/ibc-go/v6/modules/light-clients/07-tendermint/types" + "github.com/tendermint/tendermint/libs/log" + "github.com/dymensionxyz/dymension/v3/x/delayedack/types" rollapptypes "github.com/dymensionxyz/dymension/v3/x/rollapp/types" sequencertypes "github.com/dymensionxyz/dymension/v3/x/sequencer/types" - "github.com/tendermint/tendermint/libs/log" ) type ( @@ -32,9 +30,9 @@ type ( hooks types.MultiDelayedAckHooks paramstore paramtypes.Subspace - rollappKeeper types.RollappKeeper - sequencerKeeper types.SequencerKeeper - ics4Wrapper porttypes.ICS4Wrapper + rollappKeeper types.RollappKeeper + sequencerKeeper types.SequencerKeeper + porttypes.ICS4Wrapper channelKeeper types.ChannelKeeper connectionKeeper types.ConnectionKeeper clientKeeper types.ClientKeeper @@ -66,7 +64,7 @@ func NewKeeper( paramstore: ps, rollappKeeper: rollappKeeper, sequencerKeeper: sequencerKeeper, - ics4Wrapper: ics4Wrapper, + ICS4Wrapper: ics4Wrapper, channelKeeper: channelKeeper, clientKeeper: clientKeeper, connectionKeeper: connectionKeeper, @@ -79,50 +77,6 @@ func (k Keeper) Logger(ctx sdk.Context) log.Logger { return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) } -// ExtractRollappIDAndTransferPacket extracts the rollapp ID from the packet -func (k Keeper) ExtractRollappIDAndTransferPacket(ctx sdk.Context, packet channeltypes.Packet, rollappPortOnHub string, rollappChannelOnHub string) (string, *transfertypes.FungibleTokenPacketData, error) { - // no-op if the packet is not a fungible token packet - var data transfertypes.FungibleTokenPacketData - if err := transfertypes.ModuleCdc.UnmarshalJSON(packet.GetData(), &data); err != nil { - return "", nil, err - } - // Check if the packet is destined for a rollapp - chainID, err := k.ExtractChainIDFromChannel(ctx, rollappPortOnHub, rollappChannelOnHub) - if err != nil { - return "", &data, err - } - rollapp, found := k.GetRollapp(ctx, chainID) - if !found { - return "", &data, nil - } - if rollapp.ChannelId == "" { - return "", &data, errorsmod.Wrapf(rollapptypes.ErrGenesisEventNotTriggered, "empty channel id: rollap id: %s", chainID) - } - // check if the channelID matches the rollappID's channelID - if rollapp.ChannelId != rollappChannelOnHub { - return "", &data, errorsmod.Wrapf( - rollapptypes.ErrMismatchedChannelID, - "channel id mismatch: expect: %s: got: %s", rollapp.ChannelId, rollappChannelOnHub, - ) - } - - return chainID, &data, nil -} - -func (k Keeper) ExtractChainIDFromChannel(ctx sdk.Context, portID string, channelID string) (string, error) { - _, clientState, err := k.channelKeeper.GetChannelClientState(ctx, portID, channelID) - if err != nil { - return "", fmt.Errorf("failed to extract clientID from channel: %w", err) - } - - tmClientState, ok := clientState.(*ibctypes.ClientState) - if !ok { - return "", nil - } - - return tmClientState.ChainId, nil -} - func (k Keeper) IsRollappsEnabled(ctx sdk.Context) bool { return k.rollappKeeper.GetParams(ctx).RollappsEnabled } @@ -183,33 +137,6 @@ func (k *Keeper) GetHooks() types.MultiDelayedAckHooks { /* ICS4Wrapper */ /* -------------------------------------------------------------------------- */ -// SendPacket wraps IBC ChannelKeeper's SendPacket function -func (k Keeper) SendPacket( - ctx sdk.Context, - chanCap *capabilitytypes.Capability, - sourcePort string, sourceChannel string, - timeoutHeight clienttypes.Height, - timeoutTimestamp uint64, - data []byte, -) (sequence uint64, err error) { - return k.ics4Wrapper.SendPacket(ctx, chanCap, sourcePort, sourceChannel, timeoutHeight, timeoutTimestamp, data) -} - -// WriteAcknowledgement wraps IBC ICS4Wrapper WriteAcknowledgement function. -// ICS29 WriteAcknowledgement is used for asynchronous acknowledgements. -func (k *Keeper) WriteAcknowledgement(ctx sdk.Context, chanCap *capabilitytypes.Capability, packet exported.PacketI, acknowledgement exported.Acknowledgement) error { - return k.ics4Wrapper.WriteAcknowledgement(ctx, chanCap, packet, acknowledgement) -} - -// GetAppVersion wraps IBC ICS4Wrapper GetAppVersion function. -func (k *Keeper) GetAppVersion( - ctx sdk.Context, - portID, - channelID string, -) (string, bool) { - return k.ics4Wrapper.GetAppVersion(ctx, portID, channelID) -} - // LookupModuleByChannel wraps ChannelKeeper LookupModuleByChannel function. func (k *Keeper) LookupModuleByChannel(ctx sdk.Context, portID, channelID string) (string, *capabilitytypes.Capability, error) { return k.channelKeeper.LookupModuleByChannel(ctx, portID, channelID) diff --git a/x/delayedack/keeper/params_test.go b/x/delayedack/keeper/params_test.go index eee9e1b33..9f00835d0 100644 --- a/x/delayedack/keeper/params_test.go +++ b/x/delayedack/keeper/params_test.go @@ -3,9 +3,10 @@ package keeper_test import ( "testing" + "github.com/stretchr/testify/require" + testkeeper "github.com/dymensionxyz/dymension/v3/testutil/keeper" "github.com/dymensionxyz/dymension/v3/x/delayedack/types" - "github.com/stretchr/testify/require" ) func TestGetParams(t *testing.T) { diff --git a/x/delayedack/rollapp_hooks.go b/x/delayedack/rollapp_hooks.go index 75378f267..a36f01344 100644 --- a/x/delayedack/rollapp_hooks.go +++ b/x/delayedack/rollapp_hooks.go @@ -2,6 +2,7 @@ package delayedack import ( sdk "github.com/cosmos/cosmos-sdk/types" + rollapptypes "github.com/dymensionxyz/dymension/v3/x/rollapp/types" ) @@ -15,9 +16,9 @@ func (im IBCMiddleware) BeforeUpdateState(ctx sdk.Context, seqAddr string, rolla func (im IBCMiddleware) AfterStateFinalized(ctx sdk.Context, rollappID string, stateInfo *rollapptypes.StateInfo) error { // Finalize the packets for the rollapp at the given height stateEndHeight := stateInfo.StartHeight + stateInfo.NumBlocks - 1 - return im.keeper.FinalizeRollappPackets(ctx, im.IBCModule, rollappID, stateEndHeight) + return im.FinalizeRollappPackets(ctx, im.IBCModule, rollappID, stateEndHeight) } func (im IBCMiddleware) FraudSubmitted(ctx sdk.Context, rollappID string, height uint64, seqAddr string) error { - return im.keeper.HandleFraud(ctx, rollappID, im.IBCModule) + return im.HandleFraud(ctx, rollappID, im.IBCModule) } diff --git a/x/delayedack/types/expected_keepers.go b/x/delayedack/types/expected_keepers.go index e02bc9709..8ecab004c 100644 --- a/x/delayedack/types/expected_keepers.go +++ b/x/delayedack/types/expected_keepers.go @@ -3,9 +3,11 @@ package types import ( sdk "github.com/cosmos/cosmos-sdk/types" capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" + transfertypes "github.com/cosmos/ibc-go/v6/modules/apps/transfer/types" connectiontypes "github.com/cosmos/ibc-go/v6/modules/core/03-connection/types" channeltypes "github.com/cosmos/ibc-go/v6/modules/core/04-channel/types" "github.com/cosmos/ibc-go/v6/modules/core/exported" + eibctypes "github.com/dymensionxyz/dymension/v3/x/eibc/types" "github.com/dymensionxyz/dymension/v3/x/rollapp/types" rollapptypes "github.com/dymensionxyz/dymension/v3/x/rollapp/types" @@ -36,6 +38,12 @@ type RollappKeeper interface { GetLatestStateInfoIndex(ctx sdk.Context, rollappId string) (val rollapptypes.StateInfoIndex, found bool) GetLatestFinalizedStateIndex(ctx sdk.Context, rollappId string) (val types.StateInfoIndex, found bool) GetAllRollapps(ctx sdk.Context) (list []types.Rollapp) + ExtractRollappIDAndTransferPacketFromData( + ctx sdk.Context, + data []byte, + rollappPortOnHub string, + rollappChannelOnHub string, + ) (string, *transfertypes.FungibleTokenPacketData, error) } type SequencerKeeper interface { diff --git a/x/eibc/genesis_test.go b/x/eibc/genesis_test.go index ff0b9fa86..9ede3c99b 100644 --- a/x/eibc/genesis_test.go +++ b/x/eibc/genesis_test.go @@ -5,12 +5,13 @@ import ( "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" + keepertest "github.com/dymensionxyz/dymension/v3/testutil/keeper" "github.com/dymensionxyz/dymension/v3/testutil/nullify" commontypes "github.com/dymensionxyz/dymension/v3/x/common/types" "github.com/dymensionxyz/dymension/v3/x/eibc" "github.com/dymensionxyz/dymension/v3/x/eibc/types" - "github.com/stretchr/testify/require" ) func TestInitGenesis(t *testing.T) { diff --git a/x/rollapp/keeper/keeper.go b/x/rollapp/keeper/keeper.go index 2b7b0774f..a4fe2c194 100644 --- a/x/rollapp/keeper/keeper.go +++ b/x/rollapp/keeper/keeper.go @@ -11,6 +11,7 @@ import ( storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + "github.com/dymensionxyz/dymension/v3/utils" "github.com/dymensionxyz/dymension/v3/x/rollapp/types" ) @@ -37,7 +38,6 @@ func NewKeeper( memKey storetypes.StoreKey, ps paramtypes.Subspace, ibcclientKeeper types.IBCClientKeeper, - transferKeeper types.TransferKeeper, channelKeeper types.ChannelKeeper, bankKeeper types.BankKeeper, denommetadataKeeper types.DenomMetadataKeeper, @@ -54,7 +54,6 @@ func NewKeeper( paramstore: ps, hooks: nil, ibcclientKeeper: ibcclientKeeper, - transferKeeper: transferKeeper, channelKeeper: channelKeeper, bankKeeper: bankKeeper, denommetadataKeeper: denommetadataKeeper, @@ -160,11 +159,19 @@ func (k Keeper) mintRollappGenesisTokens(ctx sdk.Context, rollapp types.Rollapp) return nil } +// SetTransferKeeper MUST be called to set the IBC client keeper. +func (k *Keeper) SetTransferKeeper(tk types.TransferKeeper) { + if k.transferKeeper != nil { + panic("cannot set transfer keeper twice") + } + k.transferKeeper = tk +} + /* -------------------------------------------------------------------------- */ /* Hooks */ /* -------------------------------------------------------------------------- */ -// Set the rollapp hooks +// SetHooks sets the rollapp hooks func (k *Keeper) SetHooks(sh types.MultiRollappHooks) { if k.hooks != nil { panic("cannot set rollapp hooks twice") diff --git a/x/rollapp/keeper/util.go b/x/rollapp/keeper/util.go new file mode 100644 index 000000000..b0ac4918b --- /dev/null +++ b/x/rollapp/keeper/util.go @@ -0,0 +1,85 @@ +package keeper + +import ( + "fmt" + + errorsmod "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" + transfertypes "github.com/cosmos/ibc-go/v6/modules/apps/transfer/types" + ibctypes "github.com/cosmos/ibc-go/v6/modules/light-clients/07-tendermint/types" + + "github.com/dymensionxyz/dymension/v3/x/rollapp/types" +) + +// ExtractRollappIDAndTransferPacketFromData extracts the rollapp ID and fungible token from the packet data +// Returns an empty string if the rollapp is not found +func (k Keeper) ExtractRollappIDAndTransferPacketFromData( + ctx sdk.Context, + data []byte, + rollappPortOnHub string, + rollappChannelOnHub string, +) (string, *transfertypes.FungibleTokenPacketData, error) { + // no-op if the packet is not a fungible token packet + packet := new(transfertypes.FungibleTokenPacketData) + if err := types.ModuleCdc.UnmarshalJSON(data, packet); err != nil { + return "", packet, errorsmod.Wrapf(err, "unmarshal packet data") + } + + rollapp, err := k.ExtractRollappFromChannel(ctx, rollappPortOnHub, rollappChannelOnHub) + if err != nil { + return "", packet, err + } + + if rollapp == nil { + return "", packet, nil + } + + return rollapp.RollappId, packet, nil +} + +// ExtractRollappFromChannel extracts the rollapp from the IBC port and channel. +// Returns nil if the rollapp is not found. +func (k Keeper) ExtractRollappFromChannel( + ctx sdk.Context, + rollappPortOnHub string, + rollappChannelOnHub string, +) (*types.Rollapp, error) { + // Check if the packet is destined for a rollapp + chainID, err := k.ExtractChainIDFromChannel(ctx, rollappPortOnHub, rollappChannelOnHub) + if err != nil { + return nil, err + } + + rollapp, found := k.GetRollapp(ctx, chainID) + if !found { + return nil, nil + } + + if rollapp.ChannelId == "" { + return nil, errorsmod.Wrapf(types.ErrGenesisEventNotTriggered, "empty channel id: rollap id: %s", chainID) + } + // check if the channelID matches the rollappID's channelID + if rollapp.ChannelId != rollappChannelOnHub { + return nil, errorsmod.Wrapf( + types.ErrMismatchedChannelID, + "channel id mismatch: expect: %s: got: %s", rollapp.ChannelId, rollappChannelOnHub, + ) + } + + return &rollapp, nil +} + +// ExtractChainIDFromChannel extracts the chain ID from the channel +func (k Keeper) ExtractChainIDFromChannel(ctx sdk.Context, portID string, channelID string) (string, error) { + _, clientState, err := k.channelKeeper.GetChannelClientState(ctx, portID, channelID) + if err != nil { + return "", fmt.Errorf("extract clientID from channel: %w", err) + } + + tmClientState, ok := clientState.(*ibctypes.ClientState) + if !ok { + return "", nil + } + + return tmClientState.ChainId, nil +} diff --git a/x/rollapp/types/rollapp.pb.go b/x/rollapp/types/rollapp.pb.go index 7f25bf277..32f82873e 100644 --- a/x/rollapp/types/rollapp.pb.go +++ b/x/rollapp/types/rollapp.pb.go @@ -158,6 +158,8 @@ type Rollapp struct { ChannelId string `protobuf:"bytes,8,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` // frozen is a boolean that indicates if the rollapp is frozen. Frozen bool `protobuf:"varint,9,opt,name=frozen,proto3" json:"frozen,omitempty"` + // registeredDenoms is a list of registered denom bases on this rollapp + RegisteredDenoms []string `protobuf:"bytes,10,rep,name=registeredDenoms,proto3" json:"registeredDenoms,omitempty"` } func (m *Rollapp) Reset() { *m = Rollapp{} } @@ -256,6 +258,13 @@ func (m *Rollapp) GetFrozen() bool { return false } +func (m *Rollapp) GetRegisteredDenoms() []string { + if m != nil { + return m.RegisteredDenoms + } + return nil +} + // Rollapp summary is a compact representation of Rollapp type RollappSummary struct { // The unique identifier of the rollapp chain. @@ -331,43 +340,44 @@ func init() { func init() { proto.RegisterFile("dymension/rollapp/rollapp.proto", fileDescriptor_2c072320fdc0abd9) } var fileDescriptor_2c072320fdc0abd9 = []byte{ - // 566 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x54, 0x3d, 0x6f, 0xd3, 0x40, - 0x18, 0x8e, 0x49, 0x49, 0x9b, 0x2b, 0x0d, 0xd1, 0xf1, 0x21, 0xb7, 0x2a, 0x6e, 0x14, 0x31, 0x78, - 0xe1, 0xac, 0x36, 0x95, 0x98, 0x5b, 0x04, 0x28, 0x03, 0x0c, 0x0e, 0x0b, 0x1d, 0x88, 0x2e, 0xf6, - 0x1b, 0xf7, 0x54, 0xfb, 0x2e, 0xf8, 0x2e, 0x51, 0x92, 0x5f, 0xc1, 0xcc, 0xca, 0x9f, 0xe9, 0xd8, - 0x91, 0x09, 0xa1, 0xe4, 0x4f, 0x30, 0x22, 0x9f, 0xcf, 0x69, 0xa2, 0x14, 0x82, 0x98, 0x72, 0xcf, - 0xfb, 0xf1, 0x3c, 0xef, 0x57, 0x8c, 0x8e, 0xc2, 0x49, 0x02, 0x5c, 0x32, 0xc1, 0xbd, 0x54, 0xc4, - 0x31, 0x1d, 0x0c, 0x8a, 0x5f, 0x32, 0x48, 0x85, 0x12, 0xd8, 0x59, 0x04, 0x8c, 0x27, 0x53, 0xb2, - 0x00, 0xc4, 0x44, 0x1d, 0x3c, 0x8e, 0x44, 0x24, 0x74, 0xa8, 0x97, 0xbd, 0xf2, 0xac, 0x83, 0xe6, - 0x3a, 0xad, 0x54, 0x54, 0x41, 0x97, 0xf1, 0x7e, 0x11, 0x73, 0xb8, 0x1e, 0xd3, 0xa3, 0xfc, 0xca, - 0x78, 0x9d, 0x40, 0xc8, 0x44, 0x48, 0xaf, 0x47, 0x25, 0x78, 0xa3, 0xe3, 0x1e, 0x28, 0x7a, 0xec, - 0x05, 0x82, 0xf1, 0xdc, 0xdf, 0x0c, 0x50, 0xed, 0x2d, 0x70, 0x90, 0x4c, 0x9e, 0x05, 0x81, 0x18, - 0x72, 0x85, 0x5f, 0xa2, 0x0a, 0x4d, 0xb2, 0x97, 0x6d, 0x35, 0x2c, 0x77, 0xf7, 0x64, 0x9f, 0xe4, - 0x14, 0x24, 0xa3, 0x20, 0x86, 0x82, 0xbc, 0x12, 0x8c, 0x9f, 0x6f, 0x5d, 0xff, 0x38, 0x2a, 0xf9, - 0x26, 0x1c, 0xdb, 0x68, 0x9b, 0x86, 0x61, 0x0a, 0x52, 0xda, 0xf7, 0x1a, 0x96, 0x5b, 0xf5, 0x0b, - 0xd8, 0xfc, 0x6a, 0xa1, 0x47, 0x7e, 0x5e, 0x9b, 0x11, 0xeb, 0x64, 0x5d, 0xe0, 0x8f, 0xa8, 0x1e, - 0xe5, 0xb8, 0x4b, 0x73, 0x75, 0x69, 0x5b, 0x8d, 0xb2, 0xbb, 0x7b, 0x42, 0xc8, 0xdf, 0xe7, 0x45, - 0x56, 0x8b, 0xf6, 0x1f, 0x46, 0x2b, 0x58, 0x62, 0x17, 0xd5, 0x99, 0xec, 0x16, 0xec, 0x30, 0x02, - 0xae, 0x74, 0x55, 0x3b, 0x7e, 0x8d, 0x49, 0x93, 0xfc, 0x3a, 0xb3, 0x36, 0xbf, 0x95, 0xd1, 0xb6, - 0x29, 0x0e, 0x1f, 0xa2, 0xaa, 0x11, 0x68, 0x87, 0xba, 0xfd, 0xaa, 0x7f, 0x6b, 0xc8, 0x1a, 0x0c, - 0x52, 0xa0, 0x4a, 0xa4, 0x45, 0x83, 0x06, 0x66, 0x9e, 0x11, 0xa4, 0x59, 0x81, 0x76, 0xb9, 0x61, - 0xb9, 0x5b, 0x7e, 0x01, 0xf1, 0x73, 0xb4, 0x97, 0xd0, 0x71, 0x07, 0x3e, 0x0f, 0x81, 0x07, 0x90, - 0x4a, 0x7b, 0x4b, 0xfb, 0x57, 0x8d, 0xf8, 0x14, 0x3d, 0x19, 0x40, 0x9a, 0x30, 0x99, 0xe5, 0x40, - 0x78, 0x96, 0xcf, 0x0d, 0xa4, 0x7d, 0xbf, 0x51, 0x76, 0xab, 0xfe, 0xdd, 0x4e, 0xdc, 0x41, 0x7b, - 0x4a, 0x5c, 0x01, 0x7f, 0x07, 0x8a, 0x86, 0x54, 0x51, 0xbb, 0xa2, 0x67, 0xf7, 0x62, 0xd3, 0xec, - 0x3e, 0x2c, 0x27, 0xf9, 0xab, 0x1c, 0xf8, 0x13, 0xda, 0x2b, 0xa6, 0xa6, 0x4f, 0xcd, 0xde, 0xd6, - 0x57, 0xd0, 0xda, 0x44, 0x7a, 0xc7, 0x7e, 0xcd, 0x7d, 0x3c, 0x88, 0x96, 0x77, 0xfe, 0x0c, 0xa1, - 0xe0, 0x92, 0x72, 0x0e, 0x71, 0x97, 0x85, 0xf6, 0x4e, 0x3e, 0x63, 0x63, 0x69, 0x87, 0xf8, 0x29, - 0xaa, 0xf4, 0x53, 0x31, 0x05, 0x6e, 0x57, 0xf5, 0xb6, 0x0c, 0x6a, 0xfe, 0xb2, 0x50, 0xcd, 0x48, - 0x74, 0x86, 0x49, 0x42, 0xd3, 0xc9, 0x86, 0x65, 0x5d, 0xa0, 0x7a, 0x4c, 0x15, 0x48, 0xa5, 0x65, - 0xdb, 0x3c, 0x84, 0xb1, 0xde, 0xda, 0x3f, 0xdc, 0x96, 0xc9, 0xe8, 0x0b, 0x9d, 0xe5, 0xaf, 0xf1, - 0xe0, 0x18, 0xed, 0xe7, 0xb6, 0x37, 0x8c, 0xd3, 0x98, 0x4d, 0x21, 0x5c, 0x12, 0x29, 0xff, 0x97, - 0xc8, 0x9f, 0x09, 0xcf, 0xdf, 0x5f, 0xcf, 0x1c, 0xeb, 0x66, 0xe6, 0x58, 0x3f, 0x67, 0x8e, 0xf5, - 0x65, 0xee, 0x94, 0x6e, 0xe6, 0x4e, 0xe9, 0xfb, 0xdc, 0x29, 0x5d, 0x9c, 0x46, 0x4c, 0x5d, 0x0e, - 0x7b, 0x24, 0x10, 0x89, 0xb7, 0x2c, 0x77, 0x0b, 0xbc, 0x51, 0xcb, 0x1b, 0x2f, 0xbe, 0x0b, 0x6a, - 0x32, 0x00, 0xd9, 0xab, 0xe8, 0x7f, 0x7e, 0xeb, 0x77, 0x00, 0x00, 0x00, 0xff, 0xff, 0x3c, 0xcc, - 0x1e, 0xed, 0xb4, 0x04, 0x00, 0x00, + // 586 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x54, 0x4b, 0x6f, 0xd3, 0x40, + 0x10, 0x8e, 0x49, 0x49, 0x9b, 0x2d, 0x2d, 0xd1, 0xf2, 0xd0, 0xb6, 0x2a, 0x6e, 0x14, 0x71, 0xb0, + 0x90, 0xb0, 0xd5, 0x87, 0xc4, 0xb9, 0xe5, 0xa5, 0x1e, 0xe0, 0xe0, 0x70, 0xa1, 0x07, 0xa2, 0x8d, + 0x3d, 0x75, 0x57, 0xb5, 0x77, 0xc3, 0xee, 0x26, 0x4a, 0xfa, 0x2b, 0x38, 0xf3, 0x8b, 0x7a, 0xa3, + 0x47, 0x4e, 0x08, 0x25, 0x7f, 0x82, 0x23, 0xf2, 0x7a, 0x9d, 0x26, 0x4a, 0x21, 0x88, 0x93, 0xfd, + 0xcd, 0xe3, 0x9b, 0x99, 0x6f, 0x46, 0x8b, 0x76, 0xe3, 0x51, 0x06, 0x5c, 0x31, 0xc1, 0x03, 0x29, + 0xd2, 0x94, 0xf6, 0x7a, 0xe5, 0xd7, 0xef, 0x49, 0xa1, 0x05, 0x76, 0xa7, 0x01, 0xc3, 0xd1, 0xa5, + 0x3f, 0x05, 0xbe, 0x8d, 0xda, 0x7e, 0x98, 0x88, 0x44, 0x98, 0xd0, 0x20, 0xff, 0x2b, 0xb2, 0xb6, + 0x5b, 0x8b, 0xb4, 0x4a, 0x53, 0x0d, 0x1d, 0xc6, 0xcf, 0xca, 0x98, 0x9d, 0xc5, 0x98, 0x2e, 0xe5, + 0x17, 0xd6, 0xeb, 0x46, 0x42, 0x65, 0x42, 0x05, 0x5d, 0xaa, 0x20, 0x18, 0xec, 0x75, 0x41, 0xd3, + 0xbd, 0x20, 0x12, 0x8c, 0x17, 0xfe, 0x56, 0x84, 0x36, 0xdf, 0x02, 0x07, 0xc5, 0xd4, 0x51, 0x14, + 0x89, 0x3e, 0xd7, 0xf8, 0x05, 0xaa, 0xd1, 0x2c, 0xff, 0x23, 0x4e, 0xd3, 0xf1, 0xd6, 0xf7, 0xb7, + 0xfc, 0x82, 0xc2, 0xcf, 0x29, 0x7c, 0x4b, 0xe1, 0xbf, 0x14, 0x8c, 0x1f, 0xaf, 0x5c, 0xfd, 0xd8, + 0xad, 0x84, 0x36, 0x1c, 0x13, 0xb4, 0x4a, 0xe3, 0x58, 0x82, 0x52, 0xe4, 0x4e, 0xd3, 0xf1, 0xea, + 0x61, 0x09, 0x5b, 0x5f, 0x1d, 0xf4, 0x20, 0x2c, 0x7a, 0xb3, 0xc5, 0xda, 0xf9, 0x14, 0xf8, 0x23, + 0x6a, 0x24, 0x05, 0xee, 0xd0, 0xa2, 0xba, 0x22, 0x4e, 0xb3, 0xea, 0xad, 0xef, 0xfb, 0xfe, 0xdf, + 0xf5, 0xf2, 0xe7, 0x9b, 0x0e, 0xef, 0x27, 0x73, 0x58, 0x61, 0x0f, 0x35, 0x98, 0xea, 0x94, 0xec, + 0x30, 0x00, 0xae, 0x4d, 0x57, 0x6b, 0xe1, 0x26, 0x53, 0x36, 0xf9, 0x75, 0x6e, 0x6d, 0x7d, 0xab, + 0xa2, 0x55, 0xdb, 0x1c, 0xde, 0x41, 0x75, 0x5b, 0xe0, 0x24, 0x36, 0xe3, 0xd7, 0xc3, 0x1b, 0x43, + 0x3e, 0x60, 0x24, 0x81, 0x6a, 0x21, 0xcb, 0x01, 0x2d, 0xcc, 0x3d, 0x03, 0x90, 0x79, 0x83, 0xa4, + 0xda, 0x74, 0xbc, 0x95, 0xb0, 0x84, 0xf8, 0x29, 0xda, 0xc8, 0xe8, 0xb0, 0x0d, 0x9f, 0xfb, 0xc0, + 0x23, 0x90, 0x8a, 0xac, 0x18, 0xff, 0xbc, 0x11, 0x1f, 0xa2, 0x47, 0x3d, 0x90, 0x19, 0x53, 0x79, + 0x0e, 0xc4, 0x47, 0x85, 0x6e, 0xa0, 0xc8, 0xdd, 0x66, 0xd5, 0xab, 0x87, 0xb7, 0x3b, 0x71, 0x1b, + 0x6d, 0x68, 0x71, 0x01, 0xfc, 0x1d, 0x68, 0x1a, 0x53, 0x4d, 0x49, 0xcd, 0x68, 0xf7, 0x7c, 0x99, + 0x76, 0x1f, 0x66, 0x93, 0xc2, 0x79, 0x0e, 0xfc, 0x09, 0x6d, 0x94, 0xaa, 0x99, 0x53, 0x23, 0xab, + 0xe6, 0x0a, 0x0e, 0x96, 0x91, 0xde, 0xb2, 0x5f, 0x7b, 0x1f, 0xf7, 0x92, 0xd9, 0x9d, 0x3f, 0x41, + 0x28, 0x3a, 0xa7, 0x9c, 0x43, 0xda, 0x61, 0x31, 0x59, 0x2b, 0x34, 0xb6, 0x96, 0x93, 0x18, 0x3f, + 0x46, 0xb5, 0x33, 0x29, 0x2e, 0x81, 0x93, 0xba, 0xd9, 0x96, 0x45, 0xf8, 0x19, 0x6a, 0x48, 0x48, + 0x98, 0xd2, 0x20, 0x21, 0x7e, 0x05, 0x5c, 0x64, 0x8a, 0x20, 0x23, 0xce, 0x82, 0xbd, 0xf5, 0xcb, + 0x41, 0x9b, 0xb6, 0x9d, 0x76, 0x3f, 0xcb, 0xa8, 0x1c, 0x2d, 0x59, 0xec, 0x29, 0x6a, 0xa4, 0x54, + 0x83, 0xd2, 0xa6, 0xc5, 0x13, 0x1e, 0xc3, 0xd0, 0x6c, 0xf8, 0x1f, 0xee, 0xd0, 0x66, 0x9c, 0x09, + 0x93, 0x15, 0x2e, 0xf0, 0xe0, 0x14, 0x6d, 0x15, 0xb6, 0x37, 0x8c, 0xd3, 0x94, 0x5d, 0x42, 0x3c, + 0x53, 0xa4, 0xfa, 0x5f, 0x45, 0xfe, 0x4c, 0x78, 0xfc, 0xfe, 0x6a, 0xec, 0x3a, 0xd7, 0x63, 0xd7, + 0xf9, 0x39, 0x76, 0x9d, 0x2f, 0x13, 0xb7, 0x72, 0x3d, 0x71, 0x2b, 0xdf, 0x27, 0x6e, 0xe5, 0xf4, + 0x30, 0x61, 0xfa, 0xbc, 0xdf, 0xf5, 0x23, 0x91, 0x05, 0xb3, 0xe5, 0x6e, 0x40, 0x30, 0x38, 0x08, + 0x86, 0xd3, 0x37, 0x44, 0x8f, 0x7a, 0xa0, 0xba, 0x35, 0xf3, 0x4a, 0x1c, 0xfc, 0x0e, 0x00, 0x00, + 0xff, 0xff, 0x75, 0x02, 0x7c, 0xc2, 0xe0, 0x04, 0x00, 0x00, } func (m *GenesisAccount) Marshal() (dAtA []byte, err error) { @@ -477,6 +487,15 @@ func (m *Rollapp) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.RegisteredDenoms) > 0 { + for iNdEx := len(m.RegisteredDenoms) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.RegisteredDenoms[iNdEx]) + copy(dAtA[i:], m.RegisteredDenoms[iNdEx]) + i = encodeVarintRollapp(dAtA, i, uint64(len(m.RegisteredDenoms[iNdEx]))) + i-- + dAtA[i] = 0x52 + } + } if m.Frozen { i-- if m.Frozen { @@ -693,6 +712,12 @@ func (m *Rollapp) Size() (n int) { if m.Frozen { n += 2 } + if len(m.RegisteredDenoms) > 0 { + for _, s := range m.RegisteredDenoms { + l = len(s) + n += 1 + l + sovRollapp(uint64(l)) + } + } return n } @@ -1224,6 +1249,38 @@ func (m *Rollapp) Unmarshal(dAtA []byte) error { } } m.Frozen = bool(v != 0) + case 10: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field RegisteredDenoms", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowRollapp + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthRollapp + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthRollapp + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.RegisteredDenoms = append(m.RegisteredDenoms, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipRollapp(dAtA[iNdEx:]) diff --git a/x/transferinject/ibc_middleware.go b/x/transferinject/ibc_middleware.go new file mode 100644 index 000000000..23e33f5b6 --- /dev/null +++ b/x/transferinject/ibc_middleware.go @@ -0,0 +1,169 @@ +// Package transferinject module provides IBC middleware for sending and acknowledging IBC packets with injecting additional packet metadata to IBC packets. +package transferinject + +import ( + . "slices" + + errorsmod "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" + errortypes "github.com/cosmos/cosmos-sdk/types/errors" + capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" + transfertypes "github.com/cosmos/ibc-go/v6/modules/apps/transfer/types" + clienttypes "github.com/cosmos/ibc-go/v6/modules/core/02-client/types" + channeltypes "github.com/cosmos/ibc-go/v6/modules/core/04-channel/types" + porttypes "github.com/cosmos/ibc-go/v6/modules/core/05-port/types" + + "github.com/dymensionxyz/dymension/v3/x/transferinject/types" +) + +type IBCSendMiddleware struct { + porttypes.ICS4Wrapper + + rollappKeeper types.RollappKeeper + bankKeeper types.BankKeeper +} + +// NewIBCSendMiddleware creates a new ICS4Wrapper. +// It intercepts outgoing IBC packets and adds token metadata to the memo if the rollapp doesn't have it. +// This is a solution for adding token metadata to fungible tokens transferred over IBC, +// targeted at rollapps that don't have the token metadata for the token being transferred. +// More info here: https://www.notion.so/dymension/ADR-x-IBC-Denom-Metadata-Transfer-From-Hub-to-Rollapp-d3791f524ac849a9a3eb44d17968a30b +func NewIBCSendMiddleware( + ics porttypes.ICS4Wrapper, + rollappKeeper types.RollappKeeper, + bankKeeper types.BankKeeper, +) *IBCSendMiddleware { + return &IBCSendMiddleware{ + ICS4Wrapper: ics, + rollappKeeper: rollappKeeper, + bankKeeper: bankKeeper, + } +} + +// SendPacket wraps IBC ChannelKeeper's SendPacket function +func (m *IBCSendMiddleware) SendPacket( + ctx sdk.Context, + chanCap *capabilitytypes.Capability, + destinationPort string, destinationChannel string, + timeoutHeight clienttypes.Height, + timeoutTimestamp uint64, + data []byte, +) (sequence uint64, err error) { + packet := new(transfertypes.FungibleTokenPacketData) + if err = types.ModuleCdc.UnmarshalJSON(data, packet); err != nil { + return 0, errorsmod.Wrapf(errortypes.ErrJSONUnmarshal, "unmarshal ICS-20 transfer packet data: %s", err.Error()) + } + + if types.MemoAlreadyHasPacketMetadata(packet.Memo) { + return 0, types.ErrMemoTransferInjectAlreadyExists + } + + rollapp, err := m.rollappKeeper.ExtractRollappFromChannel(ctx, destinationPort, destinationChannel) + if err != nil { + return 0, errorsmod.Wrapf(errortypes.ErrInvalidRequest, "extract rollapp from packet: %s", err.Error()) + } + + // TODO: currently we check if receiving chain is a rollapp, consider that other chains also might want this feature + // meaning, find a better way to check if the receiving chain supports this middleware + if rollapp == nil { + return m.ICS4Wrapper.SendPacket(ctx, chanCap, destinationPort, destinationChannel, timeoutHeight, timeoutTimestamp, data) + } + + if transfertypes.ReceiverChainIsSource(destinationPort, destinationChannel, packet.Denom) { + return m.ICS4Wrapper.SendPacket(ctx, chanCap, destinationPort, destinationChannel, timeoutHeight, timeoutTimestamp, data) + } + + // Check if the rollapp already contains the denom metadata by matching the base of the denom metadata. + // At the first match, we assume that the rollapp already contains the metadata. + // It would be technically possible to have a race condition where the denom metadata is added to the rollapp + // from another packet before this packet is acknowledged. + if Contains(rollapp.RegisteredDenoms, packet.Denom) { + return m.ICS4Wrapper.SendPacket(ctx, chanCap, destinationPort, destinationChannel, timeoutHeight, timeoutTimestamp, data) + } + + // get the denom metadata from the bank keeper, if it doesn't exist, move on to the next middleware in the chain + denomMetadata, ok := m.bankKeeper.GetDenomMetaData(ctx, packet.Denom) + if !ok { + return m.ICS4Wrapper.SendPacket(ctx, chanCap, destinationPort, destinationChannel, timeoutHeight, timeoutTimestamp, data) + } + + packet.Memo, err = types.AddDenomMetadataToMemo(packet.Memo, denomMetadata) + if err != nil { + return 0, errorsmod.Wrapf(errortypes.ErrUnauthorized, "add denom metadata to memo: %s", err.Error()) + } + + data, err = types.ModuleCdc.MarshalJSON(packet) + if err != nil { + return 0, errorsmod.Wrapf(errortypes.ErrJSONMarshal, "marshal ICS-20 transfer packet data: %s", err.Error()) + } + + return m.ICS4Wrapper.SendPacket(ctx, chanCap, destinationPort, destinationChannel, timeoutHeight, timeoutTimestamp, data) +} + +type IBCAckMiddleware struct { + porttypes.IBCModule + + rollappKeeper types.RollappKeeper +} + +// NewIBCAckMiddleware creates a new IBCModule. +// It intercepts acknowledged incoming IBC packets and adds token metadata that had just been registered on the rollapp itself, +// to the local rollapp record. +func NewIBCAckMiddleware( + ibc porttypes.IBCModule, + rollappKeeper types.RollappKeeper, +) *IBCAckMiddleware { + return &IBCAckMiddleware{ + IBCModule: ibc, + rollappKeeper: rollappKeeper, + } +} + +// OnAcknowledgementPacket adds the token metadata to the rollapp if it doesn't exist +func (m *IBCAckMiddleware) OnAcknowledgementPacket( + ctx sdk.Context, + packet channeltypes.Packet, + acknowledgement []byte, + relayer sdk.AccAddress, +) error { + var ack channeltypes.Acknowledgement + if err := types.ModuleCdc.UnmarshalJSON(acknowledgement, &ack); err != nil { + return errorsmod.Wrapf(errortypes.ErrJSONUnmarshal, "unmarshal ICS-20 transfer packet acknowledgement: %v", err) + } + + if !ack.Success() { + return m.IBCModule.OnAcknowledgementPacket(ctx, packet, acknowledgement, relayer) + } + + var data transfertypes.FungibleTokenPacketData + if err := types.ModuleCdc.UnmarshalJSON(packet.GetData(), &data); err != nil { + return errorsmod.Wrapf(errortypes.ErrJSONUnmarshal, "unmarshal ICS-20 transfer packet data: %s", err.Error()) + } + + packetMetadata, err := types.ParsePacketMetadata(data.Memo) + if err != nil { + return m.IBCModule.OnAcknowledgementPacket(ctx, packet, acknowledgement, relayer) + } + + dm := packetMetadata.DenomMetadata + if dm == nil { + return m.IBCModule.OnAcknowledgementPacket(ctx, packet, acknowledgement, relayer) + } + + rollapp, err := m.rollappKeeper.ExtractRollappFromChannel(ctx, packet.SourcePort, packet.SourceChannel) + if err != nil { + return errorsmod.Wrapf(errortypes.ErrInvalidRequest, "extract rollapp from packet: %s", err.Error()) + } + if rollapp == nil { + return errorsmod.Wrapf(errortypes.ErrNotFound, "rollapp not found") + } + + if !Contains(rollapp.RegisteredDenoms, dm.Base) { + // add the new token denom base to the list of rollapp's registered denoms + rollapp.RegisteredDenoms = append(rollapp.RegisteredDenoms, dm.Base) + + m.rollappKeeper.SetRollapp(ctx, *rollapp) + } + + return m.IBCModule.OnAcknowledgementPacket(ctx, packet, acknowledgement, relayer) +} diff --git a/x/transferinject/ibc_middleware_test.go b/x/transferinject/ibc_middleware_test.go new file mode 100644 index 000000000..40976b657 --- /dev/null +++ b/x/transferinject/ibc_middleware_test.go @@ -0,0 +1,478 @@ +package transferinject_test + +import ( + "fmt" + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + errortypes "github.com/cosmos/cosmos-sdk/types/errors" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" + transfertypes "github.com/cosmos/ibc-go/v6/modules/apps/transfer/types" + clienttypes "github.com/cosmos/ibc-go/v6/modules/core/02-client/types" + channeltypes "github.com/cosmos/ibc-go/v6/modules/core/04-channel/types" + porttypes "github.com/cosmos/ibc-go/v6/modules/core/05-port/types" + "github.com/stretchr/testify/require" + + rollapptypes "github.com/dymensionxyz/dymension/v3/x/rollapp/types" + "github.com/dymensionxyz/dymension/v3/x/transferinject" + "github.com/dymensionxyz/dymension/v3/x/transferinject/types" +) + +func TestIBCMiddleware_SendPacket(t *testing.T) { + type fields struct { + ICS4Wrapper porttypes.ICS4Wrapper + rollappKeeper types.RollappKeeper + bankKeeper types.BankKeeper + } + type args struct { + destinationPort string + destinationChannel string + data *transfertypes.FungibleTokenPacketData + } + tests := []struct { + name string + fields fields + args args + wantSentData []byte + wantErr error + }{ + { + name: "success: added denom metadata to memo", + fields: fields{ + ICS4Wrapper: &mockICS4Wrapper{}, + rollappKeeper: &mockRollappKeeper{ + returnRollapp: &rollapptypes.Rollapp{}, + }, + bankKeeper: mockBankKeeper{ + returnMetadata: validDenomMetadata, + }, + }, + args: args{ + destinationPort: "port", + destinationChannel: "channel", + data: &transfertypes.FungibleTokenPacketData{ + Denom: "adym", + }, + }, + wantSentData: types.ModuleCdc.MustMarshalJSON(&transfertypes.FungibleTokenPacketData{ + Denom: "adym", + Memo: addDenomMetadataToPacketData("", validDenomMetadata), + }), + }, { + name: "success: added denom metadata to non-empty user memo", + fields: fields{ + ICS4Wrapper: &mockICS4Wrapper{}, + rollappKeeper: &mockRollappKeeper{ + returnRollapp: &rollapptypes.Rollapp{}, + }, + bankKeeper: mockBankKeeper{ + returnMetadata: validDenomMetadata, + }, + }, + args: args{ + destinationPort: "port", + destinationChannel: "channel", + data: &transfertypes.FungibleTokenPacketData{ + Denom: "adym", + Memo: "thanks for the sweater, grandma!", + }, + }, + wantSentData: types.ModuleCdc.MustMarshalJSON(&transfertypes.FungibleTokenPacketData{ + Denom: "adym", + Memo: addDenomMetadataToPacketData("thanks for the sweater, grandma!", validDenomMetadata), + }), + }, { + name: "error: denom metadata already in memo", + fields: fields{ + ICS4Wrapper: &mockICS4Wrapper{}, + }, + args: args{ + destinationPort: "port", + destinationChannel: "channel", + data: &transfertypes.FungibleTokenPacketData{ + Denom: "adym", + Memo: `{"transferinject":{}}`, + }, + }, + wantSentData: []byte(""), + wantErr: types.ErrMemoTransferInjectAlreadyExists, + }, { + name: "error: extract rollapp from channel", + fields: fields{ + ICS4Wrapper: &mockICS4Wrapper{}, + rollappKeeper: &mockRollappKeeper{ + err: errortypes.ErrInvalidRequest, + }, + }, + args: args{ + destinationPort: "port", + destinationChannel: "channel", + data: &transfertypes.FungibleTokenPacketData{ + Denom: "adym", + }, + }, + wantSentData: []byte(""), + wantErr: errortypes.ErrInvalidRequest, + }, { + name: "send unaltered: rollapp not found", + fields: fields{ + ICS4Wrapper: &mockICS4Wrapper{}, + rollappKeeper: &mockRollappKeeper{}, + }, + args: args{ + destinationPort: "port", + destinationChannel: "channel", + data: &transfertypes.FungibleTokenPacketData{ + Denom: "adym", + Memo: "user memo", + }, + }, + wantSentData: types.ModuleCdc.MustMarshalJSON(&transfertypes.FungibleTokenPacketData{ + Denom: "adym", + Memo: "user memo", + }), + }, { + name: "send unaltered: receiver chain is source", + fields: fields{ + ICS4Wrapper: &mockICS4Wrapper{}, + rollappKeeper: &mockRollappKeeper{ + returnRollapp: &rollapptypes.Rollapp{}, + }, + bankKeeper: mockBankKeeper{ + returnMetadata: validDenomMetadata, + }, + }, + args: args{ + destinationPort: "transfer", + destinationChannel: "channel-56", + data: &transfertypes.FungibleTokenPacketData{ + Denom: "transfer/channel-56/alex", + }, + }, + wantSentData: types.ModuleCdc.MustMarshalJSON(&transfertypes.FungibleTokenPacketData{ + Denom: "transfer/channel-56/alex", + }), + }, { + name: "send unaltered: denom metadata already in rollapp", + fields: fields{ + ICS4Wrapper: &mockICS4Wrapper{}, + rollappKeeper: &mockRollappKeeper{ + returnRollapp: &rollapptypes.Rollapp{ + RegisteredDenoms: []string{"adym"}, + }, + }, + }, + args: args{ + destinationPort: "port", + destinationChannel: "channel", + data: &transfertypes.FungibleTokenPacketData{ + Denom: "adym", + }, + }, + wantSentData: types.ModuleCdc.MustMarshalJSON(&transfertypes.FungibleTokenPacketData{ + Denom: "adym", + }), + }, { + name: "error: get denom metadata", + fields: fields{ + ICS4Wrapper: &mockICS4Wrapper{}, + rollappKeeper: &mockRollappKeeper{ + returnRollapp: &rollapptypes.Rollapp{}, + }, + bankKeeper: mockBankKeeper{}, + }, + args: args{ + destinationPort: "port", + destinationChannel: "channel", + data: &transfertypes.FungibleTokenPacketData{ + Denom: "adym", + }, + }, + wantSentData: types.ModuleCdc.MustMarshalJSON(&transfertypes.FungibleTokenPacketData{ + Denom: "adym", + }), + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + m := transferinject.NewIBCSendMiddleware(tt.fields.ICS4Wrapper, tt.fields.rollappKeeper, tt.fields.bankKeeper) + + data := types.ModuleCdc.MustMarshalJSON(tt.args.data) + + _, err := m.SendPacket( + sdk.Context{}, + &capabilitytypes.Capability{}, + tt.args.destinationPort, + tt.args.destinationChannel, + clienttypes.Height{}, + 0, + data, + ) + if tt.wantErr == nil { + require.NoError(t, err) + } else { + require.ErrorIs(t, err, tt.wantErr) + } + require.Equal(t, string(tt.wantSentData), string(tt.fields.ICS4Wrapper.(*mockICS4Wrapper).sentData)) + }) + } +} + +func TestIBCMiddleware_OnAcknowledgementPacket(t *testing.T) { + type fields struct { + IBCModule porttypes.IBCModule + rollappKeeper types.RollappKeeper + } + type args struct { + packetData *transfertypes.FungibleTokenPacketData + acknowledgement []byte + } + tests := []struct { + name string + fields fields + args args + wantRollapp *rollapptypes.Rollapp + wantErr error + }{ + { + name: "success: added token metadata to rollapp", + fields: fields{ + IBCModule: mockIBCModule{}, + rollappKeeper: &mockRollappKeeper{ + returnRollapp: &rollapptypes.Rollapp{}, + }, + }, + args: args{ + packetData: &transfertypes.FungibleTokenPacketData{ + Denom: "adym", + Memo: addDenomMetadataToPacketData("", validDenomMetadata), + }, + acknowledgement: okAck(), + }, + wantRollapp: &rollapptypes.Rollapp{ + RegisteredDenoms: []string{validDenomMetadata.Base}, + }, + }, { + name: "success: added token metadata to rollapp with user memo", + fields: fields{ + IBCModule: mockIBCModule{}, + rollappKeeper: &mockRollappKeeper{ + returnRollapp: &rollapptypes.Rollapp{}, + }, + }, + args: args{ + packetData: &transfertypes.FungibleTokenPacketData{ + Denom: "adym", + Memo: addDenomMetadataToPacketData("user memo", validDenomMetadata), + }, + acknowledgement: okAck(), + }, + wantRollapp: &rollapptypes.Rollapp{ + RegisteredDenoms: []string{validDenomMetadata.Base}, + }, + }, { + name: "return early: error acknowledgement", + fields: fields{ + rollappKeeper: &mockRollappKeeper{}, + IBCModule: mockIBCModule{}, + }, + args: args{ + acknowledgement: badAck(), + }, + wantRollapp: nil, + }, { + name: "return early: no memo", + fields: fields{ + rollappKeeper: &mockRollappKeeper{}, + IBCModule: mockIBCModule{}, + }, + args: args{ + packetData: &transfertypes.FungibleTokenPacketData{ + Denom: "adym", + }, + acknowledgement: okAck(), + }, + wantRollapp: nil, + }, { + name: "return early: no packet metadata in memo", + fields: fields{ + rollappKeeper: &mockRollappKeeper{}, + IBCModule: mockIBCModule{}, + }, + args: args{ + packetData: &transfertypes.FungibleTokenPacketData{ + Denom: "adym", + Memo: "user memo", + }, + acknowledgement: okAck(), + }, + wantRollapp: nil, + }, { + name: "return early: no denom metadata in memo", + fields: fields{ + rollappKeeper: &mockRollappKeeper{}, + IBCModule: mockIBCModule{}, + }, + args: args{ + packetData: &transfertypes.FungibleTokenPacketData{ + Denom: "adym", + Memo: `{"transferinject":{}}`, + }, + acknowledgement: okAck(), + }, + wantRollapp: nil, + }, { + name: "error: extract rollapp from channel", + fields: fields{ + IBCModule: mockIBCModule{}, + rollappKeeper: &mockRollappKeeper{ + err: errortypes.ErrInvalidRequest, + }, + }, + args: args{ + packetData: &transfertypes.FungibleTokenPacketData{ + Denom: "adym", + Memo: addDenomMetadataToPacketData("", validDenomMetadata), + }, + acknowledgement: okAck(), + }, + wantRollapp: nil, + wantErr: errortypes.ErrInvalidRequest, + }, { + name: "error: rollapp not found", + fields: fields{ + IBCModule: mockIBCModule{}, + rollappKeeper: &mockRollappKeeper{}, + }, + args: args{ + packetData: &transfertypes.FungibleTokenPacketData{ + Denom: "adym", + Memo: addDenomMetadataToPacketData("", validDenomMetadata), + }, + acknowledgement: okAck(), + }, + wantRollapp: nil, + wantErr: errortypes.ErrNotFound, + }, { + name: "return early: rollapp already has token metadata", + fields: fields{ + IBCModule: mockIBCModule{}, + rollappKeeper: &mockRollappKeeper{ + returnRollapp: &rollapptypes.Rollapp{ + RegisteredDenoms: []string{validDenomMetadata.Base}, + }, + }, + }, + args: args{ + packetData: &transfertypes.FungibleTokenPacketData{ + Denom: "adym", + Memo: addDenomMetadataToPacketData("", validDenomMetadata), + }, + acknowledgement: okAck(), + }, + wantRollapp: &rollapptypes.Rollapp{ + RegisteredDenoms: []string{validDenomMetadata.Base}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + m := transferinject.NewIBCAckMiddleware(tt.fields.IBCModule, tt.fields.rollappKeeper) + + packet := channeltypes.Packet{} + + if tt.args.packetData != nil { + packet.Data = types.ModuleCdc.MustMarshalJSON(tt.args.packetData) + } + + err := m.OnAcknowledgementPacket(sdk.Context{}, packet, tt.args.acknowledgement, sdk.AccAddress{}) + + if tt.wantErr == nil { + require.NoError(t, err) + } else { + require.ErrorIs(t, err, tt.wantErr) + } + + require.Equal(t, tt.wantRollapp, tt.fields.rollappKeeper.(*mockRollappKeeper).returnRollapp) + }) + } +} + +var validDenomMetadata = banktypes.Metadata{ + Description: "Denom of the Hub", + Base: "adym", + Display: "DYM", + Name: "DYM", + Symbol: "adym", + DenomUnits: []*banktypes.DenomUnit{ + { + Denom: "adym", + Exponent: 0, + }, { + Denom: "DYM", + Exponent: 18, + }, + }, +} + +func addDenomMetadataToPacketData(memo string, metadata banktypes.Metadata) string { + memo, _ = types.AddDenomMetadataToMemo(memo, metadata) + return memo +} + +func okAck() []byte { + ack := channeltypes.NewResultAcknowledgement([]byte{}) + return types.ModuleCdc.MustMarshalJSON(&ack) +} + +func badAck() []byte { + ack := channeltypes.NewErrorAcknowledgement(fmt.Errorf("unsuccessful")) + return types.ModuleCdc.MustMarshalJSON(&ack) +} + +type mockICS4Wrapper struct { + porttypes.ICS4Wrapper + sentData []byte +} + +func (m *mockICS4Wrapper) SendPacket( + _ sdk.Context, + _ *capabilitytypes.Capability, + _ string, _ string, + _ clienttypes.Height, + _ uint64, + data []byte, +) (sequence uint64, err error) { + m.sentData = data + return 0, nil +} + +type mockIBCModule struct { + porttypes.IBCModule +} + +func (m mockIBCModule) OnAcknowledgementPacket(sdk.Context, channeltypes.Packet, []byte, sdk.AccAddress) error { + return nil +} + +type mockBankKeeper struct { + returnMetadata banktypes.Metadata +} + +func (m mockBankKeeper) GetDenomMetaData(sdk.Context, string) (banktypes.Metadata, bool) { + return m.returnMetadata, m.returnMetadata.Base != "" +} + +type mockRollappKeeper struct { + returnRollapp *rollapptypes.Rollapp + err error +} + +func (m *mockRollappKeeper) SetRollapp(_ sdk.Context, rollapp rollapptypes.Rollapp) { + m.returnRollapp = &rollapp +} + +func (m *mockRollappKeeper) ExtractRollappFromChannel(sdk.Context, string, string) (*rollapptypes.Rollapp, error) { + return m.returnRollapp, m.err +} diff --git a/x/transferinject/types/codec.go b/x/transferinject/types/codec.go new file mode 100644 index 000000000..e4d4b4af5 --- /dev/null +++ b/x/transferinject/types/codec.go @@ -0,0 +1,8 @@ +package types + +import ( + "github.com/cosmos/cosmos-sdk/codec" + cdctypes "github.com/cosmos/cosmos-sdk/codec/types" +) + +var ModuleCdc = codec.NewProtoCodec(cdctypes.NewInterfaceRegistry()) diff --git a/x/transferinject/types/expected_keepers.go b/x/transferinject/types/expected_keepers.go new file mode 100644 index 000000000..b03cf0585 --- /dev/null +++ b/x/transferinject/types/expected_keepers.go @@ -0,0 +1,22 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/bank/types" + + rollapptypes "github.com/dymensionxyz/dymension/v3/x/rollapp/types" +) + +// BankKeeper defines the expected interface needed +type BankKeeper interface { + GetDenomMetaData(ctx sdk.Context, denom string) (types.Metadata, bool) +} + +type RollappKeeper interface { + SetRollapp(ctx sdk.Context, rollapp rollapptypes.Rollapp) + ExtractRollappFromChannel( + ctx sdk.Context, + rollappPortOnHub string, + rollappChannelOnHub string, + ) (*rollapptypes.Rollapp, error) +} diff --git a/x/transferinject/types/packet_metadata.go b/x/transferinject/types/packet_metadata.go new file mode 100644 index 000000000..1ee40bb31 --- /dev/null +++ b/x/transferinject/types/packet_metadata.go @@ -0,0 +1,74 @@ +package types + +import ( + "encoding/json" + "fmt" + + errorsmod "cosmossdk.io/errors" + errortypes "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/cosmos/cosmos-sdk/x/bank/types" +) + +// MemoData represents the structure of the memo with user and hub metadata +type MemoData struct { + TransferInject *TransferInject `json:"transferinject"` +} + +type TransferInject struct { + DenomMetadata *types.Metadata `json:"denom_metadata"` +} + +func (p TransferInject) ValidateBasic() error { + return p.DenomMetadata.Validate() +} + +const memoObjectKeyTransferInject = "transferinject" + +var ( + ErrMemoTransferInjectEmpty = fmt.Errorf("memo 'transferinject' is missing") + ErrMemoTransferInjectAlreadyExists = errorsmod.Wrapf(errortypes.ErrUnauthorized, "'transferinject' already exists in memo") +) + +func ParsePacketMetadata(input string) (*TransferInject, error) { + bz := []byte(input) + + var memo MemoData + if err := json.Unmarshal(bz, &memo); err != nil { + return nil, err + } + + if memo.TransferInject == nil { + return nil, ErrMemoTransferInjectEmpty + } + + return memo.TransferInject, nil +} + +func MemoAlreadyHasPacketMetadata(memo string) bool { + memoMap := make(map[string]any) + err := json.Unmarshal([]byte(memo), &memoMap) + if err != nil { + return false + } + + _, ok := memoMap[memoObjectKeyTransferInject] + return ok +} + +func AddDenomMetadataToMemo(memo string, denomMetadata types.Metadata) (string, error) { + memoMap := make(map[string]any) + // doesn't matter if there is an error, the memo can be empty + _ = json.Unmarshal([]byte(memo), &memoMap) + + if _, ok := memoMap[memoObjectKeyTransferInject]; ok { + return "", ErrMemoTransferInjectAlreadyExists + } + + memoMap[memoObjectKeyTransferInject] = TransferInject{DenomMetadata: &denomMetadata} + bz, err := json.Marshal(memoMap) + if err != nil { + return memo, err + } + + return string(bz), nil +}