-
Notifications
You must be signed in to change notification settings - Fork 44
/
msg_server_swap_exact_amount_out.go
47 lines (40 loc) · 1.38 KB
/
msg_server_swap_exact_amount_out.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
package keeper
import (
"context"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/elys-network/elys/x/amm/types"
)
func (k msgServer) SwapExactAmountOut(goCtx context.Context, msg *types.MsgSwapExactAmountOut) (*types.MsgSwapExactAmountOutResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)
sender, err := sdk.AccAddressFromBech32(msg.Sender)
if err != nil {
return nil, err
}
recipient, err := sdk.AccAddressFromBech32(msg.Recipient)
if err != nil {
recipient = sender
}
// Try executing the tx on cached context environment, to filter invalid transactions out
cacheCtx, _ := ctx.CacheContext()
tokenInAmount, swapFee, discount, err := k.RouteExactAmountOut(cacheCtx, sender, recipient, msg.Routes, msg.TokenInMaxAmount, msg.TokenOut, msg.Discount)
if err != nil {
return nil, err
}
lastSwapIndex := k.GetLastSwapRequestIndex(ctx)
k.SetSwapExactAmountOutRequests(ctx, msg, lastSwapIndex+1)
k.SetLastSwapRequestIndex(ctx, lastSwapIndex+1)
// Swap event is handled elsewhere
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
sdk.EventTypeMessage,
sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory),
sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender),
),
})
return &types.MsgSwapExactAmountOutResponse{
TokenInAmount: tokenInAmount,
SwapFee: swapFee,
Discount: discount,
Recipient: recipient.String(),
}, nil
}