/
estimate_coin_sell_all.go
83 lines (66 loc) 路 2.63 KB
/
estimate_coin_sell_all.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
package api
import (
"github.com/MinterTeam/minter-go-node/core/commissions"
"github.com/MinterTeam/minter-go-node/core/transaction"
"github.com/MinterTeam/minter-go-node/core/types"
"github.com/MinterTeam/minter-go-node/formula"
"github.com/MinterTeam/minter-go-node/rpc/lib/types"
"math/big"
)
type EstimateCoinSellAllResponse struct {
WillGet *big.Int `json:"will_get"`
}
func EstimateCoinSellAll(
coinToSellString string, coinToBuyString string, valueToSell *big.Int, gasPrice uint64, height int) (*EstimateCoinSellAllResponse,
error) {
cState, err := GetStateForHeight(height)
if err != nil {
return nil, err
}
if gasPrice < 1 {
gasPrice = 1
}
coinToSell := types.StrToCoinSymbol(coinToSellString)
coinToBuy := types.StrToCoinSymbol(coinToBuyString)
var result *big.Int
if coinToSell == coinToBuy {
return nil, rpctypes.RPCError{Code: 400, Message: "\"From\" coin equals to \"to\" coin"}
}
if !cState.CoinExists(coinToSell) {
return nil, rpctypes.RPCError{Code: 404, Message: "Coin to sell not exists"}
}
if !cState.CoinExists(coinToBuy) {
return nil, rpctypes.RPCError{Code: 404, Message: "Coin to buy not exists"}
}
commissionInBaseCoin := big.NewInt(commissions.ConvertTx)
commissionInBaseCoin.Mul(commissionInBaseCoin, transaction.CommissionMultiplier)
commission := big.NewInt(0).Set(commissionInBaseCoin)
switch {
case coinToSell == types.GetBaseCoin():
coin := cState.GetStateCoin(coinToBuy).Data()
valueToSell.Sub(valueToSell, commission)
if valueToSell.Cmp(big.NewInt(0)) != 1 {
return nil, rpctypes.RPCError{Code: 400, Message: "Not enough coins to pay commission"}
}
result = formula.CalculatePurchaseReturn(coin.Volume, coin.ReserveBalance, coin.Crr, valueToSell)
case coinToBuy == types.GetBaseCoin():
coin := cState.GetStateCoin(coinToSell).Data()
result = formula.CalculateSaleReturn(coin.Volume, coin.ReserveBalance, coin.Crr, valueToSell)
result.Sub(result, commission)
if result.Cmp(big.NewInt(0)) != 1 {
return nil, rpctypes.RPCError{Code: 400, Message: "Not enough coins to pay commission"}
}
default:
coinFrom := cState.GetStateCoin(coinToSell).Data()
coinTo := cState.GetStateCoin(coinToBuy).Data()
basecoinValue := formula.CalculateSaleReturn(coinFrom.Volume, coinFrom.ReserveBalance, coinFrom.Crr, valueToSell)
basecoinValue.Sub(basecoinValue, commission)
if basecoinValue.Cmp(big.NewInt(0)) != 1 {
return nil, rpctypes.RPCError{Code: 400, Message: "Not enough coins to pay commission"}
}
result = formula.CalculatePurchaseReturn(coinTo.Volume, coinTo.ReserveBalance, coinTo.Crr, basecoinValue)
}
return &EstimateCoinSellAllResponse{
WillGet: result,
}, nil
}