/
msg_server.go
334 lines (290 loc) · 9.27 KB
/
msg_server.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
package keeper
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"strings"
sdk "github.com/cosmos/cosmos-sdk/types"
channeltypes "github.com/cosmos/ibc-go/v6/modules/core/04-channel/types"
"github.com/sideprotocol/ibcswap/v6/modules/apps/100-atomic-swap/types"
)
var (
StepSend = 1
StepReceive = 2
StepAcknowledgement = 3
)
var _ types.MsgServer = Keeper{}
// See createOutgoingPacket in spec:https://github.com/cosmos/ibc/tree/master/spec/app/ics-020-fungible-token-transfer#packet-relay
func (k Keeper) fillAtomicOrder(ctx sdk.Context, escrowAddr sdk.AccAddress, order types.Order, msg *types.TakeSwapMsg, step int) error {
switch order.Status {
case types.Status_CANCEL:
return types.ErrOrderCanceled
case types.Status_COMPLETE:
return types.ErrOrderCompleted
default:
// continue
}
if order.Maker.BuyToken.Denom != msg.SellToken.Denom {
return types.ErrOrderDenominationMismatched
}
if msg.SellToken.IsGTE(order.Maker.BuyToken) {
order.Takers = msg // types.NewTakerFromMsg(msg)
order.Status = types.Status_COMPLETE
order.CompleteTimestamp = msg.CreateTimestamp
} else {
return types.ErrOrderInsufficientAmount
}
switch step {
case StepSend:
// executed on the destination chain of make swap,
// lock the taker's sell coin into the module
sender, err1 := sdk.AccAddressFromBech32(msg.TakerAddress)
if err1 != nil {
return err1
}
// lock sell token into module
if err := k.bankKeeper.SendCoins(
ctx, sender, escrowAddr, sdk.NewCoins(msg.SellToken),
); err != nil {
return err
}
break
case StepReceive:
// StepReceive
// executed on the source chain of make swap,
// send maker's sell token to taker
receiver, err1 := sdk.AccAddressFromBech32(msg.TakerReceivingAddress)
if err1 != nil {
return err1
}
// send maker's sell token from module to taker
if err := k.bankKeeper.SendCoins(
ctx, escrowAddr, receiver, sdk.NewCoins(order.Maker.SellToken),
); err != nil {
return err
}
break
case StepAcknowledgement:
// executed on the destination chain of the swap,
// send taker's sell token to maker
receiver, err1 := sdk.AccAddressFromBech32(order.Maker.MakerReceivingAddress)
if err1 != nil {
return err1
}
// send taker's sell token from module to maker
if err := k.bankKeeper.SendCoins(
ctx, escrowAddr, receiver, sdk.NewCoins(msg.SellToken),
); err != nil {
return err
}
break
}
// save updated status
k.SetAtomicOrder(ctx, order)
return nil
}
func (k Keeper) executeCancel(ctx sdk.Context, msg *types.CancelSwapMsg, step int) error {
// check order status
if order, ok2 := k.GetAtomicOrder(ctx, msg.OrderId); ok2 {
if order.Maker.MakerAddress != msg.MakerAddress {
return types.ErrOrderPermissionIsNotAllowed
}
switch order.Status {
case types.Status_CANCEL:
return types.ErrOrderCanceled
case types.Status_COMPLETE:
return types.ErrOrderCompleted
default:
// continue
if step != StepSend {
order.CancelTimestamp = msg.CreateTimestamp
order.Status = types.Status_CANCEL
}
// refund
if step == StepAcknowledgement {
receiver := sdk.MustAccAddressFromBech32(msg.MakerAddress)
escrowAddr := types.GetEscrowAddress(order.Maker.SourcePort, order.Maker.SourceChannel)
k.bankKeeper.SendCoins(ctx, escrowAddr, receiver, sdk.NewCoins(order.Maker.SellToken))
}
}
} else {
return types.ErrOrderDoesNotExists
}
return nil
}
// the following methods are executed On Destination chain.
// OnReceivedMake is the step 3.1 (Save order) from the atomic swap:
// https://github.com/cosmos/ibc/tree/main/spec/app/ics-100-atomic-swap
// The step is executed on the Taker chain.
func (k Keeper) OnReceivedMake(ctx sdk.Context, packet channeltypes.Packet, orderId, path string, msg *types.MakeSwapMsg) (string, error) {
// Check if buyToken is a valid token on the taker chain, could be either native or ibc token
// Disable it for demo at 2023-3-18
//supply := k.bankKeeper.GetSupply(ctx, msg.BuyToken.Denom)
//if supply.Amount.Int64() <= 0 {
// return errors.New("buy token does not exist on the taker chain")
//}
if msg.DesiredTaker != "" {
if _, err := sdk.AccAddressFromBech32(msg.DesiredTaker); err != nil {
return "", err
}
}
order := types.Order{
Id: orderId,
Side: types.REMOTE,
Status: types.Status_SYNC,
Path: path,
Maker: msg,
}
k.AppendAtomicOrder(ctx, order)
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.ModuleName,
sdk.Attribute{
Key: types.AttributeAction,
Value: types.GetEventValueWithSuffix(
types.EventValueActionMakeOrder, types.EventValueSuffixReceived,
),
},
sdk.Attribute{
Key: types.AttributeOrderId,
Value: order.Id,
},
sdk.Attribute{
Key: types.AttributeName,
Value: types.EventOwner,
},
),
)
return order.Id, nil
}
// OnReceivedTake is step 7.1 (Transfer Make Token) of the atomic swap: https://github.com/cosmos/ibc/tree/main/spec/app/ics-100-atomic-swap
// The step is executed on the Maker chain.
func (k Keeper) OnReceivedTake(ctx sdk.Context, packet channeltypes.Packet, msg *types.TakeSwapMsg) (string, error) {
escrowAddr := types.GetEscrowAddress(packet.GetDestPort(), packet.GetDestChannel())
// check order status
order, ok := k.GetAtomicOrder(ctx, msg.OrderId)
if !ok {
return "", types.ErrOrderDoesNotExists
}
if order.Status != types.Status_SYNC {
return "", types.ErrInvalidOrderStatus
}
if msg.SellToken.Denom != order.Maker.BuyToken.Denom || !msg.SellToken.Amount.Equal(order.Maker.BuyToken.Amount) {
return "", types.ErrInvalidSellToken
}
// If `desiredTaker` is set, only the desiredTaker can accept the order.
if order.Maker.DesiredTaker != "" && order.Maker.DesiredTaker != msg.TakerAddress {
return "", types.ErrInvalidTakerAddress
}
takerReceivingAddr, err := sdk.AccAddressFromBech32(msg.TakerReceivingAddress)
if err != nil {
return "", err
}
// Send maker.sellToken to taker's receiving address
if err = k.bankKeeper.SendCoins(ctx, escrowAddr, takerReceivingAddr, sdk.NewCoins(order.Maker.SellToken)); err != nil {
return "", err
}
// Update status of order
order.Status = types.Status_COMPLETE
order.Takers = msg
order.CompleteTimestamp = msg.CreateTimestamp
k.SetAtomicOrder(ctx, order)
// Move Completed assets to bottom
k.MoveOrderToBottom(ctx, order.Id)
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.ModuleName,
sdk.Attribute{
Key: types.AttributeAction,
Value: types.GetEventValueWithSuffix(
types.EventValueActionTakeOrder, types.EventValueSuffixReceived,
),
},
sdk.Attribute{
Key: types.AttributeOrderId,
Value: order.Id,
},
sdk.Attribute{
Key: types.AttributeName,
Value: types.EventOwner,
},
),
)
return order.Id, nil
}
// OnReceivedCancel is the step 12 (Cancel Order) of the atomic swap: https://github.com/cosmos/ibc/tree/main/spec/app/ics-100-atomic-swap.
// This step is executed on the Taker chain.
func (k Keeper) OnReceivedCancel(ctx sdk.Context, packet channeltypes.Packet, msg *types.CancelSwapMsg) (string, error) {
if err := msg.ValidateBasic(); err != nil {
return "", err
}
// check order status
order, ok := k.GetAtomicOrder(ctx, msg.OrderId)
if !ok {
return "", types.ErrOrderDoesNotExists
}
if order.Status != types.Status_SYNC && order.Status != types.Status_INITIAL {
return "", types.ErrInvalidOrderStatus
}
if order.Takers != nil {
return "", types.ErrAlreadyOrderTook
}
// Update status of order
order.Status = types.Status_CANCEL
order.CancelTimestamp = msg.CreateTimestamp
k.SetAtomicOrder(ctx, order)
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.ModuleName,
sdk.Attribute{
Key: types.AttributeAction,
Value: types.GetEventValueWithSuffix(
types.EventValueActionCancelOrder, types.EventValueSuffixReceived,
),
},
sdk.Attribute{
Key: types.AttributeOrderId,
Value: order.Id,
},
sdk.Attribute{
Key: types.AttributeName,
Value: types.EventOwner,
},
),
)
return order.Id, nil
}
func createOrder(ctx sdk.Context, msg *types.MakeSwapMsg, channelKeeper types.ChannelKeeper) (*types.Order, error) {
channel, found := channelKeeper.GetChannel(ctx, msg.SourcePort, msg.SourceChannel)
if !found {
return nil, types.ErrNotFoundChannel
}
pathID := types.GenerateRandomString(ctx.ChainID(), 10)
path := orderPath(msg.SourcePort, msg.SourceChannel, channel.Counterparty.PortId, channel.Counterparty.ChannelId, pathID)
return &types.Order{
Id: generateOrderId(path, msg),
Side: types.NATIVE,
Status: types.Status_INITIAL,
Path: path,
Maker: msg,
}, nil
}
func orderPath(sourcePort, sourceChannel, destPort, destChannel, pathID string) string {
return fmt.Sprintf("channel/%s/port/%s/channel/%s/port/%s/%s", sourceChannel, sourcePort, destChannel, destPort, pathID)
}
func generateOrderId(orderPath string, msg *types.MakeSwapMsg) string {
prefix := []byte(orderPath)
bytes, _ := types.ModuleCdc.MarshalJSON(msg)
hash := sha256.Sum256(append(prefix, bytes...))
// Convert to hex and truncate to desired length.
encoded := hex.EncodeToString(hash[:])
return encoded[:20] // Returns first 20 characters of the hash.
}
func extractSourceChannelForTakerMsg(path string) string {
parts := strings.Split(path, "/")
return parts[5]
}
func extractSourcePortForTakerMsg(path string) string {
parts := strings.Split(path, "/")
return parts[7]
}