forked from terra-money/classic-core
-
Notifications
You must be signed in to change notification settings - Fork 1
/
keeper.go
68 lines (55 loc) · 1.81 KB
/
keeper.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
package market
import (
"terra/x/oracle"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/bank"
"github.com/cosmos/cosmos-sdk/x/distribution"
)
// StoreKey is string representation of the store key for market
const StoreKey = "market"
//nolint
type Keeper struct {
key sdk.StoreKey
cdc *codec.Codec
ok oracle.Keeper // Read terra & luna prices
bk bank.Keeper
dk distribution.Keeper
}
func NewKeeper(ok oracle.Keeper, bk bank.Keeper, dk distribution.Keeper) Keeper {
return Keeper{
ok: ok,
bk: bk,
dk: dk,
}
}
func (k Keeper) SwapCoins(ctx sdk.Context, offerCoin sdk.Coin, askDenom string) (sdk.Coin, sdk.Error) {
offerRate, err := k.ok.GetPrice(ctx, offerCoin.Denom)
if err != nil {
return sdk.Coin{}, ErrNoEffectivePrice(DefaultCodespace, offerCoin.Denom)
}
askRate, err := k.ok.GetPrice(ctx, askDenom)
if err != nil {
return sdk.Coin{}, ErrNoEffectivePrice(DefaultCodespace, askDenom)
}
retAmount := sdk.NewDecFromInt(offerCoin.Amount).Mul(offerRate).Quo(askRate).RoundInt()
if retAmount.Equal(sdk.ZeroInt()) {
// drop in this scenario
return sdk.Coin{}, ErrInsufficientSwapCoins(DefaultCodespace, offerCoin.Amount)
}
retCoin := sdk.Coin{Denom: askDenom, Amount: retAmount}
return retCoin, nil
}
func (k Keeper) SwapDecCoins(ctx sdk.Context, offerCoin sdk.DecCoin, askDenom string) (sdk.DecCoin, sdk.Error) {
offerRate, err := k.ok.GetPrice(ctx, offerCoin.Denom)
if err != nil {
return sdk.DecCoin{}, ErrNoEffectivePrice(DefaultCodespace, offerCoin.Denom)
}
askRate, err := k.ok.GetPrice(ctx, askDenom)
if err != nil {
return sdk.DecCoin{}, ErrNoEffectivePrice(DefaultCodespace, askDenom)
}
retAmount := offerCoin.Amount.Mul(offerRate).Quo(askRate)
retCoin := sdk.NewDecCoinFromDec(askDenom, retAmount)
return retCoin, nil
}