/
swap.go
280 lines (245 loc) · 10.9 KB
/
swap.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
package keeper
import (
"fmt"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/furynet/furymod/modules/coinswap/types"
)
func (k Keeper) swapCoins(ctx sdk.Context, sender, recipient sdk.AccAddress, coinSold, coinBought sdk.Coin) error {
lptDenom, err := k.GetLptDenomFromDenoms(ctx, coinSold.Denom, coinBought.Denom)
if err != nil {
return err
}
poolAddr := types.GetReservePoolAddr(lptDenom)
if err := k.bk.SendCoins(ctx, sender, poolAddr, sdk.NewCoins(coinSold)); err != nil {
return err
}
if recipient.Empty() {
recipient = sender
}
return k.bk.SendCoins(ctx, poolAddr, recipient, sdk.NewCoins(coinBought))
}
/**
Calculate the amount of another token to be received based on the exact amount of tokens sold
@param exactSoldCoin : sold coin
@param soldTokenDenom : received token's denom
@return : amount of the token that will be received
*/
func (k Keeper) calculateWithExactInput(ctx sdk.Context, exactSoldCoin sdk.Coin, boughtTokenDenom string) (sdkmath.Int, error) {
lptDenom, err := k.GetLptDenomFromDenoms(ctx, exactSoldCoin.Denom, boughtTokenDenom)
if err != nil {
return sdk.ZeroInt(), err
}
reservePoolAddress := types.GetReservePoolAddr(lptDenom).String()
reservePool, err := k.GetPoolBalances(ctx, reservePoolAddress)
if err != nil {
return sdk.ZeroInt(), err
}
inputReserve := reservePool.AmountOf(exactSoldCoin.Denom)
outputReserve := reservePool.AmountOf(boughtTokenDenom)
if !inputReserve.IsPositive() {
return sdk.ZeroInt(), sdkerrors.Wrap(types.ErrInsufficientFunds, fmt.Sprintf("reserve pool insufficient funds, actual [%s%s]", inputReserve.String(), exactSoldCoin.Denom))
}
if !outputReserve.IsPositive() {
return sdk.ZeroInt(), sdkerrors.Wrap(types.ErrInsufficientFunds, fmt.Sprintf("reserve pool insufficient funds, actual [%s%s]", outputReserve.String(), boughtTokenDenom))
}
param := k.GetParams(ctx)
boughtTokenAmt := GetInputPrice(exactSoldCoin.Amount, inputReserve, outputReserve, param.Fee)
return boughtTokenAmt, nil
}
/**
Sell exact amount of a token for buying another, one of them must be standard token
@param input: exact amount of the token to be sold
@param output: min amount of the token to be bought
@param sender: address of the sender
@param receipt: address of the receiver
@return: actual amount of the token to be bought
*/
func (k Keeper) TradeExactInputForOutput(ctx sdk.Context, input types.Input, output types.Output) (sdkmath.Int, error) {
boughtTokenAmt, err := k.calculateWithExactInput(ctx, input.Coin, output.Coin.Denom)
if err != nil {
return sdk.ZeroInt(), err
}
// assert that the calculated amount is more than the
// minimum amount the buyer is willing to buy.
if boughtTokenAmt.LT(output.Coin.Amount) {
return sdk.ZeroInt(), sdkerrors.Wrap(types.ErrConstraintNotMet, fmt.Sprintf("insufficient amount of %s, user expected: %s, actual: %s", output.Coin.Denom, output.Coin.Amount.String(), boughtTokenAmt.String()))
}
boughtToken := sdk.NewCoin(output.Coin.Denom, boughtTokenAmt)
inputAddress, err := sdk.AccAddressFromBech32(input.Address)
if err != nil {
return sdk.ZeroInt(), err
}
outputAddress, err := sdk.AccAddressFromBech32(output.Address)
if err != nil {
return sdk.ZeroInt(), err
}
if err := k.swapCoins(ctx, inputAddress, outputAddress, input.Coin, boughtToken); err != nil {
return sdk.ZeroInt(), err
}
return boughtTokenAmt, nil
}
/**
Sell exact amount of a token for buying another, non of them are standard token
@param input: exact amount of the token to be sold
@param output: min amount of the token to be bought
@param sender: address of the sender
@param receipt: address of the receiver
@return: actual amount of the token to be bought
*/
func (k Keeper) doubleTradeExactInputForOutput(ctx sdk.Context, input types.Input, output types.Output) (sdkmath.Int, error) {
standardDenom := k.GetStandardDenom(ctx)
standardAmount, err := k.calculateWithExactInput(ctx, input.Coin, standardDenom)
if err != nil {
return sdk.ZeroInt(), err
}
standardCoin := sdk.NewCoin(standardDenom, standardAmount)
inputAddress, err := sdk.AccAddressFromBech32(input.Address)
if err != nil {
return sdk.ZeroInt(), err
}
outputAddress, err := sdk.AccAddressFromBech32(output.Address)
if err != nil {
return sdk.ZeroInt(), err
}
if err := k.swapCoins(ctx, inputAddress, outputAddress, input.Coin, standardCoin); err != nil {
return sdk.ZeroInt(), err
}
boughtAmt, err := k.calculateWithExactInput(ctx, standardCoin, output.Coin.Denom)
if err != nil {
return sdk.ZeroInt(), err
}
boughtToken := sdk.NewCoin(output.Coin.Denom, boughtAmt)
// assert that the calculated amount is less than the
// minimum amount the buyer is willing to buy.
if boughtAmt.LT(output.Coin.Amount) {
return sdk.ZeroInt(), sdkerrors.Wrap(types.ErrConstraintNotMet, fmt.Sprintf("insufficient amount of %s, user expected: %s, actual: %s", output.Coin.Denom, output.Coin.Amount.String(), boughtAmt.String()))
}
if err := k.swapCoins(ctx, inputAddress, outputAddress, standardCoin, boughtToken); err != nil {
return sdk.ZeroInt(), err
}
return boughtAmt, nil
}
/**
Calculate the amount of the token to be paid based on the exact amount of the token to be bought
@param exactBoughtCoin
@param soldTokenDenom
@return: actual amount of the token to be paid
*/
func (k Keeper) calculateWithExactOutput(ctx sdk.Context, exactBoughtCoin sdk.Coin, soldTokenDenom string) (sdkmath.Int, error) {
lptDenom, err := k.GetLptDenomFromDenoms(ctx, exactBoughtCoin.Denom, soldTokenDenom)
if err != nil {
return sdk.ZeroInt(), err
}
poolAddr := types.GetReservePoolAddr(lptDenom).String()
reservePool, err := k.GetPoolBalances(ctx, poolAddr)
if err != nil {
return sdk.ZeroInt(), err
}
outputReserve := reservePool.AmountOf(exactBoughtCoin.Denom)
inputReserve := reservePool.AmountOf(soldTokenDenom)
if !inputReserve.IsPositive() {
return sdk.ZeroInt(), sdkerrors.Wrap(types.ErrInsufficientFunds, fmt.Sprintf("reserve pool insufficient balance: [%s%s]", inputReserve.String(), soldTokenDenom))
}
if !outputReserve.IsPositive() {
return sdk.ZeroInt(), sdkerrors.Wrap(types.ErrInsufficientFunds, fmt.Sprintf("reserve pool insufficient balance: [%s%s]", outputReserve.String(), exactBoughtCoin.Denom))
}
if exactBoughtCoin.Amount.GTE(outputReserve) {
return sdk.ZeroInt(), sdkerrors.Wrap(types.ErrInsufficientFunds, fmt.Sprintf("reserve pool insufficient balance of %s, user expected: %s, actual: %s", exactBoughtCoin.Denom, exactBoughtCoin.Amount.String(), outputReserve.String()))
}
param := k.GetParams(ctx)
soldTokenAmt := GetOutputPrice(exactBoughtCoin.Amount, inputReserve, outputReserve, param.Fee)
return soldTokenAmt, nil
}
/**
Buy exact amount of a token by specifying the max amount of another token, one of them must be standard token
@param input : max amount of the token to be paid
@param output : exact amount of the token to be bought
@param sender : address of the sender
@param receipt : address of the receiver
@return : actual amount of the token to be paid
*/
func (k Keeper) TradeInputForExactOutput(ctx sdk.Context, input types.Input, output types.Output) (sdkmath.Int, error) {
soldTokenAmt, err := k.calculateWithExactOutput(ctx, output.Coin, input.Coin.Denom)
if err != nil {
return sdk.ZeroInt(), err
}
// assert that the calculated amount is less than the
// max amount the buyer is willing to pay.
if soldTokenAmt.GT(input.Coin.Amount) {
return sdk.ZeroInt(), sdkerrors.Wrap(types.ErrConstraintNotMet, fmt.Sprintf("insufficient amount of %s, user expected: %s, actual: %s", input.Coin.Denom, input.Coin.Amount.String(), soldTokenAmt.String()))
}
soldToken := sdk.NewCoin(input.Coin.Denom, soldTokenAmt)
inputAddress, err := sdk.AccAddressFromBech32(input.Address)
if err != nil {
return sdk.ZeroInt(), err
}
outputAddress, err := sdk.AccAddressFromBech32(output.Address)
if err != nil {
return sdk.ZeroInt(), err
}
if err := k.swapCoins(ctx, inputAddress, outputAddress, soldToken, output.Coin); err != nil {
return sdk.ZeroInt(), err
}
return soldTokenAmt, nil
}
/**
Buy exact amount of a token by specifying the max amount of another token, non of them are standard token
@param input : max amount of the token to be paid
@param output : exact amount of the token to be bought
@param sender : address of the sender
@param receipt : address of the receiver
@return : actual amount of the token to be paid
*/
func (k Keeper) doubleTradeInputForExactOutput(ctx sdk.Context, input types.Input, output types.Output) (sdkmath.Int, error) {
standardDenom := k.GetStandardDenom(ctx)
soldStandardAmount, err := k.calculateWithExactOutput(ctx, output.Coin, standardDenom)
if err != nil {
return sdk.ZeroInt(), err
}
soldStandardCoin := sdk.NewCoin(standardDenom, soldStandardAmount)
soldTokenAmt, err := k.calculateWithExactOutput(ctx, soldStandardCoin, input.Coin.Denom)
if err != nil {
return sdk.ZeroInt(), err
}
soldTokenCoin := sdk.NewCoin(input.Coin.Denom, soldTokenAmt)
// assert that the calculated amount is less than the
// max amount the buyer is willing to sell.
if soldTokenAmt.GT(input.Coin.Amount) {
return sdk.ZeroInt(), sdkerrors.Wrap(types.ErrConstraintNotMet, fmt.Sprintf("insufficient amount of %s, user expected: %s, actual: %s", input.Coin.Denom, input.Coin.Amount.String(), soldTokenAmt.String()))
}
inputAddress, err := sdk.AccAddressFromBech32(input.Address)
if err != nil {
return sdk.ZeroInt(), err
}
outputAddress, err := sdk.AccAddressFromBech32(output.Address)
if err != nil {
return sdk.ZeroInt(), err
}
if err := k.swapCoins(ctx, inputAddress, outputAddress, soldTokenCoin, soldStandardCoin); err != nil {
return sdk.ZeroInt(), err
}
if err := k.swapCoins(ctx, inputAddress, outputAddress, soldStandardCoin, output.Coin); err != nil {
return sdk.ZeroInt(), err
}
return soldTokenAmt, nil
}
// GetInputPrice returns the amount of coins bought (calculated) given the input amount being sold (exact)
// The fee is included in the input coins being bought
// https://github.com/runtimeverification/verified-smart-contracts/blob/uniswap/uniswap/x-y-k.pdf
func GetInputPrice(inputAmt, inputReserve, outputReserve sdkmath.Int, fee sdk.Dec) sdkmath.Int {
deltaFee := sdk.OneDec().Sub(fee)
inputAmtWithFee := inputAmt.Mul(sdk.NewIntFromBigInt(deltaFee.BigInt()))
numerator := inputAmtWithFee.Mul(outputReserve)
denominator := inputReserve.Mul(sdkmath.NewIntWithDecimal(1, sdk.Precision)).Add(inputAmtWithFee)
return numerator.Quo(denominator)
}
// GetOutputPrice returns the amount of coins sold (calculated) given the output amount being bought (exact)
// The fee is included in the output coins being bought
func GetOutputPrice(outputAmt, inputReserve, outputReserve sdkmath.Int, fee sdk.Dec) sdkmath.Int {
deltaFee := sdk.OneDec().Sub(fee)
numerator := inputReserve.Mul(outputAmt).Mul(sdkmath.NewIntWithDecimal(1, sdk.Precision))
denominator := (outputReserve.Sub(outputAmt)).Mul(sdk.NewIntFromBigInt(deltaFee.BigInt()))
return numerator.Quo(denominator).Add(sdk.OneInt())
}