/
ibc.go
421 lines (380 loc) · 12.6 KB
/
ibc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
package keeper
import (
"encoding/json"
"fmt"
"strconv"
errorsmod "cosmossdk.io/errors"
wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
icatypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/types"
ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types"
channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types"
liquidstakeibctypes "github.com/persistenceOne/pstake-native/v2/x/liquidstakeibc/types"
"github.com/persistenceOne/pstake-native/v2/x/ratesync/types"
)
func (k *Keeper) OnChanOpenAck(
ctx sdk.Context,
portID string,
channelID string,
counterpartyChannelID string,
counterpartyVersion string,
) error {
// get the connection id from the port and channel identifiers
connID, _, err := k.ibcKeeper.ChannelKeeper.GetChannelConnection(ctx, portID, channelID)
if err != nil {
return fmt.Errorf("unable to get connection id using port %s: %w", portID, err)
}
// get interchain account address
address, found := k.icaControllerKeeper.GetInterchainAccountAddress(ctx, connID, portID)
if !found {
return fmt.Errorf("couldn't find address for %s/%s", connID, portID)
}
// get the port owner from the port id, duplicated check as of ibc-go controller stack
portOwner, err := types.OwnerFromPortID(portID)
if err != nil {
return fmt.Errorf("unable to parse port id %s, err: %v", portID, err)
}
// get the chain id using the connection id
chainID, err := k.GetChainID(ctx, connID)
if err != nil {
return fmt.Errorf("unable to get chain id for connection %s: %w", connID, err)
}
id, err := types.IDFromPortID(portID)
if err != nil {
// Port is not related to this module
return nil
}
// get host chain
hc, found := k.GetHostChain(ctx, id)
if !found {
k.Logger(ctx).Info(fmt.Sprintf("host chain with id %v is not registered", id))
return nil
}
switch {
case portOwner == hc.ICAAccount.Owner:
hc.ICAAccount.Address = address
hc.ICAAccount.ChannelState = liquidstakeibctypes.ICAAccount_ICA_CHANNEL_CREATED
default:
k.Logger(ctx).Error("Unrecognized ICA account type for the module", "port-id:", portID, "chain-id", chainID)
return nil
}
// save the changes of the host chain
k.SetHostChain(ctx, hc)
k.Logger(ctx).Info(
"Created new ICA.",
"host chain",
chainID,
"channel",
channelID,
"owner",
portOwner,
"address",
address,
)
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventICAChannelCreated,
sdk.NewAttribute(types.AttributeChainID, hc.ChainID),
sdk.NewAttribute(types.AttributeICAChannelID, channelID),
sdk.NewAttribute(types.AttributeICAPortOwner, portOwner),
sdk.NewAttribute(types.AttributeICAAddress, address),
),
)
return nil
}
func (k *Keeper) OnAcknowledgementPacket(
ctx sdk.Context,
packet channeltypes.Packet,
acknowledgement []byte,
relayer sdk.AccAddress,
) error {
id, err := types.IDFromPortID(packet.SourcePort)
if err != nil {
// Port is not related to this module
return nil
}
// get host chain
hc, found := k.GetHostChain(ctx, id)
if !found {
return errorsmod.Wrapf(sdkerrors.ErrNotFound, "host chain with id %v is not present", id)
}
var ack channeltypes.Acknowledgement
if err := ibctransfertypes.ModuleCdc.UnmarshalJSON(acknowledgement, &ack); err != nil {
return errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "cannot unmarshal packet acknowledgement: %v", err)
}
var icaPacket icatypes.InterchainAccountPacketData
if err := icatypes.ModuleCdc.UnmarshalJSON(packet.GetData(), &icaPacket); err != nil {
return errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "cannot unmarshal ICS-27 packet data: %v", err)
}
var icaMemo types.ICAMemo
err = json.Unmarshal([]byte(icaPacket.Memo), &icaMemo)
if err != nil {
return err
}
if hc.ID != icaMemo.HostChainID {
return errorsmod.Wrapf(types.ErrInvalid, "host chain ID should match ID in memo")
}
switch resp := ack.Response.(type) {
case *channeltypes.Acknowledgement_Error:
err := k.handleUnsuccessfulAck(ctx, icaPacket, packet, icaMemo)
if err != nil {
return err
}
k.Logger(ctx).Info(fmt.Sprintln("ICS-27 tx failed with ack:", ack.String()))
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypePacket,
sdk.NewAttribute(types.AttributeKeyAckError, resp.Error),
),
)
case *channeltypes.Acknowledgement_Result:
err := k.handleSuccessfulAck(ctx, ack, icaPacket, packet, icaMemo)
if err != nil {
return err
}
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypePacket,
sdk.NewAttribute(types.AttributeKeyAckSuccess, fmt.Sprintln(ack.Success())),
),
)
default:
// the acknowledgement succeeded on the receiving chain so nothing
// needs to be executed and no error needs to be returned
return nil
}
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypePacket,
sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName),
sdk.NewAttribute(types.AttributeKeyAck, ack.String()),
),
)
return nil
}
func (k *Keeper) OnTimeoutPacket(
ctx sdk.Context,
packet channeltypes.Packet,
relayer sdk.AccAddress,
) error {
id, err := types.IDFromPortID(packet.SourcePort)
if err != nil {
// Port is not related to this module
return nil
}
// get host chain
hc, found := k.GetHostChain(ctx, id)
if !found {
return errorsmod.Wrapf(sdkerrors.ErrNotFound, "host chain with id %v is not present", id)
}
var icaPacket icatypes.InterchainAccountPacketData
if err := icatypes.ModuleCdc.UnmarshalJSON(packet.GetData(), &icaPacket); err != nil {
return errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "cannot unmarshal ICS-27 tx message data: %v", err)
}
var icaMemo types.ICAMemo
err = json.Unmarshal([]byte(icaPacket.Memo), &icaMemo)
if err != nil {
return err
}
if hc.ID != icaMemo.HostChainID {
return errorsmod.Wrapf(types.ErrInvalid, "host chain ID should match ID in memo")
}
if err := k.handleUnsuccessfulAck(ctx, icaPacket, packet, icaMemo); err != nil {
return err
}
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeTimeout,
sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName),
),
)
k.Logger(ctx).Info(
"ICA transaction timed out.",
"sequence",
packet.Sequence,
"channel",
packet.SourceChannel,
"port",
packet.SourcePort,
)
return nil
}
func (k *Keeper) handleUnsuccessfulAck(
ctx sdk.Context,
icaPacket icatypes.InterchainAccountPacketData,
packet channeltypes.Packet, icaMemo types.ICAMemo,
) error {
messages, err := icatypes.DeserializeCosmosTx(k.cdc, icaPacket.GetData())
if err != nil {
return errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "cannot deserialize ica packet data: %v", err)
}
hc, found := k.GetHostChain(ctx, icaMemo.HostChainID)
if !found {
return errorsmod.Wrapf(sdkerrors.ErrNotFound, "hostchain not found for id %v", icaMemo.HostChainID)
}
for _, msg := range messages {
switch sdk.MsgTypeURL(msg) {
case sdk.MsgTypeURL(&wasmtypes.MsgInstantiateContract{}):
// parse the MsgInstantiateContract to emit the instantiate error event
parsedMsg, ok := msg.(*wasmtypes.MsgInstantiateContract)
if !ok {
k.Logger(ctx).Error(
"Could not parse MsgInstantiateContract while handling unsuccessful ack.",
"channel", packet.SourceChannel, "sequence", packet.Sequence,
)
continue
}
// reset instantiation state so can be retried.
switch icaMemo.FeatureType {
case types.FeatureType_LIQUID_STAKE_IBC:
hc.Features.LiquidStakeIBC.Instantiation = types.InstantiationState_INSTANTIATION_NOT_INITIATED
case types.FeatureType_LIQUID_STAKE:
hc.Features.LiquidStake.Instantiation = types.InstantiationState_INSTANTIATION_NOT_INITIATED
}
// emit an event for the instantiate confirmation
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeUnsuccessfulInstantiateContract,
sdk.NewAttribute(types.AttributeChainID, hc.ChainID),
sdk.NewAttribute(types.AttributeSender, parsedMsg.Sender),
sdk.NewAttribute(channeltypes.AttributeKeySequence, strconv.FormatUint(packet.Sequence, 10)),
sdk.NewAttribute(channeltypes.AttributeKeySrcChannel, packet.SourceChannel),
sdk.NewAttribute(channeltypes.AttributeKeyPortID, packet.SourcePort),
),
)
case sdk.MsgTypeURL(&wasmtypes.MsgExecuteContract{}):
// parse the MsgExecuteContract to emit the execute error event
parsedMsg, ok := msg.(*wasmtypes.MsgExecuteContract)
if !ok {
k.Logger(ctx).Error(
"Could not parse MsgExecuteContract while handling unsuccessful ack.",
"channel", packet.SourceChannel, "sequence", packet.Sequence,
)
continue
}
// Do nothing, relay next epoch
// emit an event for the execution confirmation
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeUnsuccessfulExecuteContract,
sdk.NewAttribute(types.AttributeChainID, hc.ChainID),
sdk.NewAttribute(types.AttributeSender, parsedMsg.Sender),
sdk.NewAttribute(channeltypes.AttributeKeySequence, strconv.FormatUint(packet.Sequence, 10)),
sdk.NewAttribute(channeltypes.AttributeKeySrcChannel, packet.SourceChannel),
sdk.NewAttribute(channeltypes.AttributeKeyPortID, packet.SourcePort),
),
)
}
}
k.SetHostChain(ctx, hc)
return nil
}
func (k *Keeper) handleSuccessfulAck(
ctx sdk.Context,
ack channeltypes.Acknowledgement,
icaPacket icatypes.InterchainAccountPacketData,
packet channeltypes.Packet, icaMemo types.ICAMemo,
) error {
txMsgData := &sdk.TxMsgData{}
if err := k.cdc.Unmarshal(ack.GetResult(), txMsgData); err != nil {
return errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "cannot unmarshal ics-27 tx ack data: %v", err)
}
messages, err := icatypes.DeserializeCosmosTx(k.cdc, icaPacket.GetData())
if err != nil {
return errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "cannot deserialize ica packet data: %v", err)
}
for i, msg := range messages {
switch sdk.MsgTypeURL(msg) {
case sdk.MsgTypeURL(&wasmtypes.MsgInstantiateContract{}):
var data []byte
if len(txMsgData.Data) == 0 {
data = txMsgData.GetMsgResponses()[i].Value
} else {
data = txMsgData.Data[i].Data
}
var msgResponse wasmtypes.MsgInstantiateContractResponse
if err := k.cdc.Unmarshal(data, &msgResponse); err != nil {
return errorsmod.Wrapf(
sdkerrors.ErrJSONUnmarshal, "cannot unmarshal MsgInstantiateContract response message: %s",
err.Error(),
)
}
parsedMsg, ok := msg.(*wasmtypes.MsgInstantiateContract)
if !ok {
return errorsmod.Wrapf(
sdkerrors.ErrInvalidType,
"unable to cast msg of type %s to MsgInstantiateContract",
sdk.MsgTypeURL(msg),
)
}
if err = k.HandleInstantiateContractResponse(ctx, parsedMsg, msgResponse, icaMemo); err != nil {
return err
}
case sdk.MsgTypeURL(&wasmtypes.MsgExecuteContract{}):
var data []byte
if len(txMsgData.Data) == 0 {
data = txMsgData.GetMsgResponses()[i].Value
} else {
data = txMsgData.Data[i].Data
}
var msgResponse wasmtypes.MsgExecuteContractResponse
if err := k.cdc.Unmarshal(data, &msgResponse); err != nil {
return errorsmod.Wrapf(
sdkerrors.ErrJSONUnmarshal, "cannot unmarshal MsgExecuteContract response message: %s",
err.Error(),
)
}
parsedMsg, ok := msg.(*wasmtypes.MsgExecuteContract)
if !ok {
return errorsmod.Wrapf(
sdkerrors.ErrInvalidType,
"unable to cast msg of type %s to MsgExecuteContract",
sdk.MsgTypeURL(msg),
)
}
if err = k.HandleExecuteContractResponse(ctx, parsedMsg, msgResponse); err != nil {
return err
}
}
}
k.Logger(ctx).Info(
"ICA transaction ACK success.",
"sequence",
packet.Sequence,
"channel",
packet.SourceChannel,
"messages",
messages,
)
return nil
}
func (k Keeper) HandleInstantiateContractResponse(ctx sdk.Context,
msg *wasmtypes.MsgInstantiateContract,
resp wasmtypes.MsgInstantiateContractResponse,
icaMemo types.ICAMemo,
) error {
hc, found := k.GetHostChain(ctx, icaMemo.HostChainID)
if !found {
return errorsmod.Wrapf(sdkerrors.ErrNotFound, "hostchain not found for id %v", icaMemo.HostChainID)
}
switch icaMemo.FeatureType {
case types.FeatureType_LIQUID_STAKE_IBC:
hc.Features.LiquidStakeIBC.Instantiation = types.InstantiationState_INSTANTIATION_COMPLETED
hc.Features.LiquidStakeIBC.ContractAddress = resp.Address
hc.Features.LiquidStakeIBC.Enabled = true
case types.FeatureType_LIQUID_STAKE:
hc.Features.LiquidStake.Instantiation = types.InstantiationState_INSTANTIATION_COMPLETED
hc.Features.LiquidStake.ContractAddress = resp.Address
hc.Features.LiquidStake.Enabled = true
}
k.SetHostChain(ctx, hc)
return nil
}
func (k Keeper) HandleExecuteContractResponse(ctx sdk.Context,
msg *wasmtypes.MsgExecuteContract,
resp wasmtypes.MsgExecuteContractResponse,
) error {
// cool do nothing
return nil
}