Commit bdf8e51e authored by vipwzw's avatar vipwzw

auto ci

parent 5d9da776
...@@ -7,4 +7,3 @@ strapp=${strcmd%/cmd*} ...@@ -7,4 +7,3 @@ strapp=${strcmd%/cmd*}
OUT_TESTDIR="${1}/dapptest/$strapp" OUT_TESTDIR="${1}/dapptest/$strapp"
mkdir -p "${OUT_TESTDIR}" mkdir -p "${OUT_TESTDIR}"
cp ./test/test-rpc.sh "${OUT_TESTDIR}" cp ./test/test-rpc.sh "${OUT_TESTDIR}"
...@@ -7,7 +7,7 @@ set -o pipefail ...@@ -7,7 +7,7 @@ set -o pipefail
source ../dapp-test-common.sh source ../dapp-test-common.sh
function main() { function main() {
echo "Collateralize cases has integrated in Issuance test" echo "Collateralize cases has integrated in Issuance test"
} }
chain33_debug_function main "$1" chain33_debug_function main "$1"
...@@ -2,12 +2,13 @@ package commands ...@@ -2,12 +2,13 @@ package commands
import ( import (
"fmt" "fmt"
"github.com/spf13/cobra" "strconv"
jsonrpc "github.com/33cn/chain33/rpc/jsonclient" jsonrpc "github.com/33cn/chain33/rpc/jsonclient"
rpctypes "github.com/33cn/chain33/rpc/types" rpctypes "github.com/33cn/chain33/rpc/types"
"github.com/33cn/chain33/types" "github.com/33cn/chain33/types"
pkt "github.com/33cn/plugin/plugin/dapp/collateralize/types" pkt "github.com/33cn/plugin/plugin/dapp/collateralize/types"
"strconv" "github.com/spf13/cobra"
) )
// CollateralizeCmd 斗牛游戏命令行 // CollateralizeCmd 斗牛游戏命令行
...@@ -308,7 +309,7 @@ func CollateralizeManage(cmd *cobra.Command, args []string) { ...@@ -308,7 +309,7 @@ func CollateralizeManage(cmd *cobra.Command, args []string) {
params := &rpctypes.CreateTxIn{ params := &rpctypes.CreateTxIn{
Execer: cfg.ExecName(pkt.CollateralizeX), Execer: cfg.ExecName(pkt.CollateralizeX),
ActionName: "CollateralizeManage", ActionName: "CollateralizeManage",
Payload: []byte(fmt.Sprintf("{\"debtCeiling\":%f, \"liquidationRatio\":%f, \"stabilityFeeRatio\":%f, \"period\":%d, \"totalBalance\":%f}", Payload: []byte(fmt.Sprintf("{\"debtCeiling\":%f, \"liquidationRatio\":%f, \"stabilityFeeRatio\":%f, \"period\":%d, \"totalBalance\":%f}",
debtCeiling, liquidationRatio, stabilityFeeRatio, period, totalBalance)), debtCeiling, liquidationRatio, stabilityFeeRatio, period, totalBalance)),
} }
...@@ -416,13 +417,13 @@ func CollateralizeQuery(cmd *cobra.Command, args []string) { ...@@ -416,13 +417,13 @@ func CollateralizeQuery(cmd *cobra.Command, args []string) {
} }
if collateralizeID != "" { if collateralizeID != "" {
if address != "" { if address != "" {
params.FuncName = "CollateralizeRecordByAddr" params.FuncName = "CollateralizeRecordByAddr"
req := &pkt.ReqCollateralizeRecordByAddr{ req := &pkt.ReqCollateralizeRecordByAddr{
CollateralizeId: collateralizeID, CollateralizeId: collateralizeID,
Status: int32(status), Status: int32(status),
Addr: address, Addr: address,
} }
params.Payload = types.MustPBToJSON(req) params.Payload = types.MustPBToJSON(req)
var res pkt.RepCollateralizeRecords var res pkt.RepCollateralizeRecords
...@@ -433,18 +434,18 @@ func CollateralizeQuery(cmd *cobra.Command, args []string) { ...@@ -433,18 +434,18 @@ func CollateralizeQuery(cmd *cobra.Command, args []string) {
req := &pkt.ReqCollateralizeRecordByStatus{ req := &pkt.ReqCollateralizeRecordByStatus{
CollateralizeId: collateralizeID, CollateralizeId: collateralizeID,
Status: int32(status), Status: int32(status),
} }
params.Payload = types.MustPBToJSON(req) params.Payload = types.MustPBToJSON(req)
var res pkt.RepCollateralizeRecords var res pkt.RepCollateralizeRecords
ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res) ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res)
ctx.Run() ctx.Run()
} else if borrowID != ""{ } else if borrowID != "" {
params.FuncName = "CollateralizeRecordByID" params.FuncName = "CollateralizeRecordByID"
req := &pkt.ReqCollateralizeRecord{ req := &pkt.ReqCollateralizeRecord{
CollateralizeId: collateralizeID, CollateralizeId: collateralizeID,
RecordId: borrowID, RecordId: borrowID,
} }
params.Payload = types.MustPBToJSON(req) params.Payload = types.MustPBToJSON(req)
var res pkt.RepCollateralizeRecord var res pkt.RepCollateralizeRecord
...@@ -472,7 +473,7 @@ func CollateralizeQuery(cmd *cobra.Command, args []string) { ...@@ -472,7 +473,7 @@ func CollateralizeQuery(cmd *cobra.Command, args []string) {
} else if statusStr != "" { } else if statusStr != "" {
params.FuncName = "CollateralizeByStatus" params.FuncName = "CollateralizeByStatus"
req := &pkt.ReqCollateralizeByStatus{Status:int32(status)} req := &pkt.ReqCollateralizeByStatus{Status: int32(status)}
params.Payload = types.MustPBToJSON(req) params.Payload = types.MustPBToJSON(req)
var res pkt.RepCollateralizeIDs var res pkt.RepCollateralizeIDs
ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res) ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res)
......
...@@ -63,8 +63,8 @@ func (c *Collateralize) GetDriverName() string { ...@@ -63,8 +63,8 @@ func (c *Collateralize) GetDriverName() string {
func (c *Collateralize) addCollateralizeID(collateralizeId string, index int64) (kvs []*types.KeyValue) { func (c *Collateralize) addCollateralizeID(collateralizeId string, index int64) (kvs []*types.KeyValue) {
key := calcCollateralizeKey(collateralizeId, index) key := calcCollateralizeKey(collateralizeId, index)
record := &pty.CollateralizeRecord{ record := &pty.CollateralizeRecord{
CollateralizeId:collateralizeId, CollateralizeId: collateralizeId,
Index: index, Index: index,
} }
kv := &types.KeyValue{Key: key, Value: types.Encode(record)} kv := &types.KeyValue{Key: key, Value: types.Encode(record)}
...@@ -83,8 +83,8 @@ func (c *Collateralize) deleteCollateralizeID(collateralizeId string, index int6 ...@@ -83,8 +83,8 @@ func (c *Collateralize) deleteCollateralizeID(collateralizeId string, index int6
func (c *Collateralize) addCollateralizeStatus(status int32, collateralizeId string, index int64) (kvs []*types.KeyValue) { func (c *Collateralize) addCollateralizeStatus(status int32, collateralizeId string, index int64) (kvs []*types.KeyValue) {
key := calcCollateralizeStatusKey(status, index) key := calcCollateralizeStatusKey(status, index)
record := &pty.CollateralizeRecord{ record := &pty.CollateralizeRecord{
CollateralizeId:collateralizeId, CollateralizeId: collateralizeId,
Index: index, Index: index,
} }
kv := &types.KeyValue{Key: key, Value: types.Encode(record)} kv := &types.KeyValue{Key: key, Value: types.Encode(record)}
...@@ -103,9 +103,9 @@ func (c *Collateralize) deleteCollateralizeStatus(status int32, index int64) (kv ...@@ -103,9 +103,9 @@ func (c *Collateralize) deleteCollateralizeStatus(status int32, index int64) (kv
func (c *Collateralize) addCollateralizeAddr(addr string, collateralizeId string, status int32, index int64) (kvs []*types.KeyValue) { func (c *Collateralize) addCollateralizeAddr(addr string, collateralizeId string, status int32, index int64) (kvs []*types.KeyValue) {
key := calcCollateralizeAddrKey(addr, index) key := calcCollateralizeAddrKey(addr, index)
record := &pty.CollateralizeRecord{ record := &pty.CollateralizeRecord{
CollateralizeId:collateralizeId, CollateralizeId: collateralizeId,
Status:status, Status: status,
Index: index, Index: index,
} }
kv := &types.KeyValue{Key: key, Value: types.Encode(record)} kv := &types.KeyValue{Key: key, Value: types.Encode(record)}
...@@ -125,9 +125,9 @@ func (c *Collateralize) addCollateralizeRecordStatus(recordStatus int32, collate ...@@ -125,9 +125,9 @@ func (c *Collateralize) addCollateralizeRecordStatus(recordStatus int32, collate
key := calcCollateralizeRecordStatusKey(recordStatus, index) key := calcCollateralizeRecordStatusKey(recordStatus, index)
record := &pty.CollateralizeRecord{ record := &pty.CollateralizeRecord{
CollateralizeId:collateralizeId, CollateralizeId: collateralizeId,
RecordId:recordId, RecordId: recordId,
Index: index, Index: index,
} }
kv := &types.KeyValue{Key: key, Value: types.Encode(record)} kv := &types.KeyValue{Key: key, Value: types.Encode(record)}
...@@ -147,9 +147,9 @@ func (c *Collateralize) addCollateralizeRecordAddr(recordAddr string, collateral ...@@ -147,9 +147,9 @@ func (c *Collateralize) addCollateralizeRecordAddr(recordAddr string, collateral
key := calcCollateralizeRecordAddrKey(recordAddr, index) key := calcCollateralizeRecordAddrKey(recordAddr, index)
record := &pty.CollateralizeRecord{ record := &pty.CollateralizeRecord{
CollateralizeId:collateralizeId, CollateralizeId: collateralizeId,
RecordId:recordId, RecordId: recordId,
Index: index, Index: index,
} }
kv := &types.KeyValue{Key: key, Value: types.Encode(record)} kv := &types.KeyValue{Key: key, Value: types.Encode(record)}
...@@ -177,4 +177,4 @@ func (c *Collateralize) ExecutorOrder() int64 { ...@@ -177,4 +177,4 @@ func (c *Collateralize) ExecutorOrder() int64 {
return drivers.ExecLocalSameTime return drivers.ExecLocalSameTime
} }
return c.DriverBase.ExecutorOrder() return c.DriverBase.ExecutorOrder()
} }
\ No newline at end of file
package executor package executor
import ( import (
"github.com/33cn/chain33/client"
"testing" "testing"
"time" "time"
"github.com/33cn/chain33/client"
"github.com/33cn/chain33/account" "github.com/33cn/chain33/account"
apimock "github.com/33cn/chain33/client/mocks" apimock "github.com/33cn/chain33/client/mocks"
"github.com/33cn/chain33/common" "github.com/33cn/chain33/common"
...@@ -40,7 +41,7 @@ var ( ...@@ -40,7 +41,7 @@ var (
[]byte("1JRNjdEqp4LJ5fqycUBm9ayCKSeeskgMKR"), []byte("1JRNjdEqp4LJ5fqycUBm9ayCKSeeskgMKR"),
[]byte("12evczYyX9ZKPYvwSEvRkRyTjpSrJuLudg"), []byte("12evczYyX9ZKPYvwSEvRkRyTjpSrJuLudg"),
} }
total = 10000 * types.Coin total = 10000 * types.Coin
totalToken = 100000 * types.Coin totalToken = 100000 * types.Coin
) )
...@@ -94,7 +95,7 @@ func initEnv() *execEnv { ...@@ -94,7 +95,7 @@ func initEnv() *execEnv {
Addr: string(Nodes[1]), Addr: string(Nodes[1]),
} }
accountBToken := types.Account{ accountBToken := types.Account{
Balance: types.Coin/10, Balance: types.Coin / 10,
Frozen: 0, Frozen: 0,
Addr: string(Nodes[1]), Addr: string(Nodes[1]),
} }
...@@ -115,14 +116,14 @@ func initEnv() *execEnv { ...@@ -115,14 +116,14 @@ func initEnv() *execEnv {
accA.SaveExecAccount(execAddr, &accountA) accA.SaveExecAccount(execAddr, &accountA)
manageKeySet("issuance-manage", accountA.Addr, stateDB) manageKeySet("issuance-manage", accountA.Addr, stateDB)
addrKeySet(accountA.Addr, stateDB) addrKeySet(accountA.Addr, stateDB)
tokenAccA,_ := account.NewAccountDB(cfg, tokenE.GetName(), pkt.CCNYTokenName, stateDB) tokenAccA, _ := account.NewAccountDB(cfg, tokenE.GetName(), pkt.CCNYTokenName, stateDB)
tokenAccA.SaveExecAccount(execAddr, &accountAToken) tokenAccA.SaveExecAccount(execAddr, &accountAToken)
accB := account.NewCoinsAccount(cfg) accB := account.NewCoinsAccount(cfg)
accB.SetDB(stateDB) accB.SetDB(stateDB)
accB.SaveExecAccount(execAddr, &accountB) accB.SaveExecAccount(execAddr, &accountB)
manageKeySet("issuance-price-feed", accountB.Addr, stateDB) manageKeySet("issuance-price-feed", accountB.Addr, stateDB)
tokenAccB,_ := account.NewAccountDB(cfg, tokenE.GetName(), pkt.CCNYTokenName, stateDB) tokenAccB, _ := account.NewAccountDB(cfg, tokenE.GetName(), pkt.CCNYTokenName, stateDB)
tokenAccB.SaveExecAccount(execAddr, &accountBToken) tokenAccB.SaveExecAccount(execAddr, &accountBToken)
accC := account.NewCoinsAccount(cfg) accC := account.NewCoinsAccount(cfg)
...@@ -131,14 +132,14 @@ func initEnv() *execEnv { ...@@ -131,14 +132,14 @@ func initEnv() *execEnv {
manageKeySet("issuance-guarantor", accountC.Addr, stateDB) manageKeySet("issuance-guarantor", accountC.Addr, stateDB)
return &execEnv{ return &execEnv{
blockTime:time.Now().Unix(), blockTime: time.Now().Unix(),
blockHeight:cfg.GetDappFork(pkt.CollateralizeX, "Enable"), blockHeight: cfg.GetDappFork(pkt.CollateralizeX, "Enable"),
difficulty:1539918074, difficulty: 1539918074,
kvdb:kvdb, kvdb: kvdb,
api: api, api: api,
db: stateDB, db: stateDB,
execAddr: execAddr, execAddr: execAddr,
cfg: cfg, cfg: cfg,
} }
} }
...@@ -185,7 +186,6 @@ func TestCollateralize(t *testing.T) { ...@@ -185,7 +186,6 @@ func TestCollateralize(t *testing.T) {
env.kvdb.Set(kv.Key, kv.Value) env.kvdb.Set(kv.Key, kv.Value)
} }
// collateralize create // collateralize create
p1 := &pkt.CollateralizeCreateTx{ p1 := &pkt.CollateralizeCreateTx{
TotalBalance: 1000, TotalBalance: 1000,
...@@ -216,21 +216,20 @@ func TestCollateralize(t *testing.T) { ...@@ -216,21 +216,20 @@ func TestCollateralize(t *testing.T) {
} }
collateralizeID := createTx.Hash() collateralizeID := createTx.Hash()
// query collateralize by id // query collateralize by id
res, err := exec.Query("CollateralizeInfoByID", types.Encode(&pkt.ReqCollateralizeInfo{CollateralizeId: common.ToHex(collateralizeID),})) res, err := exec.Query("CollateralizeInfoByID", types.Encode(&pkt.ReqCollateralizeInfo{CollateralizeId: common.ToHex(collateralizeID)}))
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
// query collateralize by status // query collateralize by status
res, err = exec.Query("CollateralizeByStatus", types.Encode(&pkt.ReqCollateralizeByStatus{Status:1})) res, err = exec.Query("CollateralizeByStatus", types.Encode(&pkt.ReqCollateralizeByStatus{Status: 1}))
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
// query collateralizes by ids // query collateralizes by ids
var collateralizeIDsS []string var collateralizeIDsS []string
collateralizeIDsS = append(collateralizeIDsS, common.ToHex(collateralizeID)) collateralizeIDsS = append(collateralizeIDsS, common.ToHex(collateralizeID))
res, err = exec.Query("CollateralizeInfoByIDs", types.Encode(&pkt.ReqCollateralizeInfos{CollateralizeIds:collateralizeIDsS})) res, err = exec.Query("CollateralizeInfoByIDs", types.Encode(&pkt.ReqCollateralizeInfos{CollateralizeIds: collateralizeIDsS}))
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
// collateralize price // collateralize price
p2 := &pkt.CollateralizeFeedTx{} p2 := &pkt.CollateralizeFeedTx{}
p2.Price = append(p2.Price, 1) p2.Price = append(p2.Price, 1)
...@@ -265,11 +264,10 @@ func TestCollateralize(t *testing.T) { ...@@ -265,11 +264,10 @@ func TestCollateralize(t *testing.T) {
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
// collateralize borrow // collateralize borrow
p4 := &pkt.CollateralizeBorrowTx{ p4 := &pkt.CollateralizeBorrowTx{
CollateralizeID: common.ToHex(collateralizeID), CollateralizeID: common.ToHex(collateralizeID),
Value: 100, Value: 100,
} }
createTx, err = pkt.CreateRawCollateralizeBorrowTx(env.cfg, p4) createTx, err = pkt.CreateRawCollateralizeBorrowTx(env.cfg, p4)
if err != nil { if err != nil {
...@@ -304,21 +302,20 @@ func TestCollateralize(t *testing.T) { ...@@ -304,21 +302,20 @@ func TestCollateralize(t *testing.T) {
assert.NotNil(t, res) assert.NotNil(t, res)
// query collateralize by status // query collateralize by status
res, err = exec.Query("CollateralizeRecordByStatus", res, err = exec.Query("CollateralizeRecordByStatus",
types.Encode(&pkt.ReqCollateralizeRecordByStatus{CollateralizeId:common.ToHex(collateralizeID), Status:1})) types.Encode(&pkt.ReqCollateralizeRecordByStatus{CollateralizeId: common.ToHex(collateralizeID), Status: 1}))
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
// query collateralize by addr // query collateralize by addr
res, err = exec.Query("CollateralizeRecordByAddr", res, err = exec.Query("CollateralizeRecordByAddr",
types.Encode(&pkt.ReqCollateralizeRecordByAddr{CollateralizeId:common.ToHex(collateralizeID),Addr: string(Nodes[1]), Status:1})) types.Encode(&pkt.ReqCollateralizeRecordByAddr{CollateralizeId: common.ToHex(collateralizeID), Addr: string(Nodes[1]), Status: 1}))
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
// collateralize append // collateralize append
p5 := &pkt.CollateralizeAppendTx{ p5 := &pkt.CollateralizeAppendTx{
CollateralizeID: common.ToHex(collateralizeID), CollateralizeID: common.ToHex(collateralizeID),
RecordID:common.ToHex(borrowID), RecordID: common.ToHex(borrowID),
Value: 100, Value: 100,
} }
createTx, err = pkt.CreateRawCollateralizeAppendTx(env.cfg, p5) createTx, err = pkt.CreateRawCollateralizeAppendTx(env.cfg, p5)
if err != nil { if err != nil {
...@@ -352,20 +349,19 @@ func TestCollateralize(t *testing.T) { ...@@ -352,20 +349,19 @@ func TestCollateralize(t *testing.T) {
assert.NotNil(t, res) assert.NotNil(t, res)
// query collateralize by status // query collateralize by status
res, err = exec.Query("CollateralizeRecordByStatus", res, err = exec.Query("CollateralizeRecordByStatus",
types.Encode(&pkt.ReqCollateralizeRecordByStatus{CollateralizeId:common.ToHex(collateralizeID), Status:1})) types.Encode(&pkt.ReqCollateralizeRecordByStatus{CollateralizeId: common.ToHex(collateralizeID), Status: 1}))
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
// query collateralize by addr // query collateralize by addr
res, err = exec.Query("CollateralizeRecordByAddr", res, err = exec.Query("CollateralizeRecordByAddr",
types.Encode(&pkt.ReqCollateralizeRecordByAddr{CollateralizeId:common.ToHex(collateralizeID),Addr: string(Nodes[1]), Status:1})) types.Encode(&pkt.ReqCollateralizeRecordByAddr{CollateralizeId: common.ToHex(collateralizeID), Addr: string(Nodes[1]), Status: 1}))
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
// collateralize repay // collateralize repay
p6 := &pkt.CollateralizeRepayTx{ p6 := &pkt.CollateralizeRepayTx{
CollateralizeID: common.ToHex(collateralizeID), CollateralizeID: common.ToHex(collateralizeID),
RecordID: common.ToHex(borrowID), RecordID: common.ToHex(borrowID),
} }
createTx, err = pkt.CreateRawCollateralizeRepayTx(env.cfg, p6) createTx, err = pkt.CreateRawCollateralizeRepayTx(env.cfg, p6)
if err != nil { if err != nil {
...@@ -394,20 +390,19 @@ func TestCollateralize(t *testing.T) { ...@@ -394,20 +390,19 @@ func TestCollateralize(t *testing.T) {
} }
// query collateralize by status // query collateralize by status
res, err = exec.Query("CollateralizeRecordByStatus", res, err = exec.Query("CollateralizeRecordByStatus",
types.Encode(&pkt.ReqCollateralizeRecordByStatus{CollateralizeId:common.ToHex(collateralizeID), Status:6})) types.Encode(&pkt.ReqCollateralizeRecordByStatus{CollateralizeId: common.ToHex(collateralizeID), Status: 6}))
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
// query collateralize by addr // query collateralize by addr
res, err = exec.Query("CollateralizeRecordByAddr", res, err = exec.Query("CollateralizeRecordByAddr",
types.Encode(&pkt.ReqCollateralizeRecordByAddr{CollateralizeId:common.ToHex(collateralizeID),Addr: string(Nodes[1]), Status:6})) types.Encode(&pkt.ReqCollateralizeRecordByAddr{CollateralizeId: common.ToHex(collateralizeID), Addr: string(Nodes[1]), Status: 6}))
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
// collateralize liquidate // collateralize liquidate
p7 := &pkt.CollateralizeBorrowTx{ p7 := &pkt.CollateralizeBorrowTx{
CollateralizeID: common.ToHex(collateralizeID), CollateralizeID: common.ToHex(collateralizeID),
Value: 100, Value: 100,
} }
createTx, err = pkt.CreateRawCollateralizeBorrowTx(env.cfg, p7) createTx, err = pkt.CreateRawCollateralizeBorrowTx(env.cfg, p7)
if err != nil { if err != nil {
...@@ -465,15 +460,14 @@ func TestCollateralize(t *testing.T) { ...@@ -465,15 +460,14 @@ func TestCollateralize(t *testing.T) {
} }
// query collateralize by status // query collateralize by status
res, err = exec.Query("CollateralizeRecordByStatus", res, err = exec.Query("CollateralizeRecordByStatus",
types.Encode(&pkt.ReqCollateralizeRecordByStatus{CollateralizeId:common.ToHex(collateralizeID), Status:3})) types.Encode(&pkt.ReqCollateralizeRecordByStatus{CollateralizeId: common.ToHex(collateralizeID), Status: 3}))
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
// expire liquidate // expire liquidate
p9 := &pkt.CollateralizeBorrowTx{ p9 := &pkt.CollateralizeBorrowTx{
CollateralizeID: common.ToHex(collateralizeID), CollateralizeID: common.ToHex(collateralizeID),
Value: 100, Value: 100,
} }
createTx, err = pkt.CreateRawCollateralizeBorrowTx(env.cfg, p9) createTx, err = pkt.CreateRawCollateralizeBorrowTx(env.cfg, p9)
if err != nil { if err != nil {
...@@ -531,15 +525,14 @@ func TestCollateralize(t *testing.T) { ...@@ -531,15 +525,14 @@ func TestCollateralize(t *testing.T) {
} }
// query collateralize by status // query collateralize by status
res, err = exec.Query("CollateralizeRecordByStatus", res, err = exec.Query("CollateralizeRecordByStatus",
types.Encode(&pkt.ReqCollateralizeRecordByStatus{CollateralizeId:common.ToHex(collateralizeID), Status:5})) types.Encode(&pkt.ReqCollateralizeRecordByStatus{CollateralizeId: common.ToHex(collateralizeID), Status: 5}))
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
// collateralize retrieve // collateralize retrieve
p11 := &pkt.CollateralizeRetrieveTx{ p11 := &pkt.CollateralizeRetrieveTx{
CollateralizeID: common.ToHex(collateralizeID), CollateralizeID: common.ToHex(collateralizeID),
Balance:100, Balance: 100,
} }
createTx, err = pkt.CreateRawCollateralizeRetrieveTx(env.cfg, p11) createTx, err = pkt.CreateRawCollateralizeRetrieveTx(env.cfg, p11)
if err != nil { if err != nil {
...@@ -567,7 +560,7 @@ func TestCollateralize(t *testing.T) { ...@@ -567,7 +560,7 @@ func TestCollateralize(t *testing.T) {
env.kvdb.Set(kv.Key, kv.Value) env.kvdb.Set(kv.Key, kv.Value)
} }
// query collateralize by status // query collateralize by status
res, err = exec.Query("CollateralizeByStatus", types.Encode(&pkt.ReqCollateralizeByStatus{Status:1})) res, err = exec.Query("CollateralizeByStatus", types.Encode(&pkt.ReqCollateralizeByStatus{Status: 1}))
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
} }
......
...@@ -6,6 +6,8 @@ package executor ...@@ -6,6 +6,8 @@ package executor
import ( import (
"fmt" "fmt"
"math"
"github.com/33cn/chain33/account" "github.com/33cn/chain33/account"
"github.com/33cn/chain33/common" "github.com/33cn/chain33/common"
dbm "github.com/33cn/chain33/common/db" dbm "github.com/33cn/chain33/common/db"
...@@ -14,7 +16,6 @@ import ( ...@@ -14,7 +16,6 @@ import (
pty "github.com/33cn/plugin/plugin/dapp/collateralize/types" pty "github.com/33cn/plugin/plugin/dapp/collateralize/types"
issuanceE "github.com/33cn/plugin/plugin/dapp/issuance/types" issuanceE "github.com/33cn/plugin/plugin/dapp/issuance/types"
tokenE "github.com/33cn/plugin/plugin/dapp/token/executor" tokenE "github.com/33cn/plugin/plugin/dapp/token/executor"
"math"
) )
// List control // List control
...@@ -83,18 +84,18 @@ func PriceKey() (key []byte) { ...@@ -83,18 +84,18 @@ func PriceKey() (key []byte) {
// Action struct // Action struct
type Action struct { type Action struct {
coinsAccount *account.DB // bty账户 coinsAccount *account.DB // bty账户
tokenAccount *account.DB // ccny账户 tokenAccount *account.DB // ccny账户
db dbm.KV db dbm.KV
localDB dbm.Lister localDB dbm.Lister
txhash []byte txhash []byte
fromaddr string fromaddr string
blocktime int64 blocktime int64
height int64 height int64
execaddr string execaddr string
difficulty uint64 difficulty uint64
index int index int
Collateralize *Collateralize Collateralize *Collateralize
} }
// NewCollateralizeAction generate New Action // NewCollateralizeAction generate New Action
...@@ -109,7 +110,7 @@ func NewCollateralizeAction(c *Collateralize, tx *types.Transaction, index int) ...@@ -109,7 +110,7 @@ func NewCollateralizeAction(c *Collateralize, tx *types.Transaction, index int)
} }
return &Action{ return &Action{
coinsAccount: c.GetCoinsAccount(), tokenAccount:tokenDb, db: c.GetStateDB(), localDB:c.GetLocalDB(), coinsAccount: c.GetCoinsAccount(), tokenAccount: tokenDb, db: c.GetStateDB(), localDB: c.GetLocalDB(),
txhash: hash, fromaddr: fromaddr, blocktime: c.GetBlockTime(), height: c.GetHeight(), txhash: hash, fromaddr: fromaddr, blocktime: c.GetBlockTime(), height: c.GetHeight(),
execaddr: dapp.ExecAddress(string(tx.Execer)), difficulty: c.GetDifficulty(), index: index, Collateralize: c} execaddr: dapp.ExecAddress(string(tx.Execer)), difficulty: c.GetDifficulty(), index: index, Collateralize: c}
} }
...@@ -283,7 +284,7 @@ func (action *Action) CollateralizeManage(manage *pty.CollateralizeManage) (*typ ...@@ -283,7 +284,7 @@ func (action *Action) CollateralizeManage(manage *pty.CollateralizeManage) (*typ
collConfig := &pty.CollateralizeManage{} collConfig := &pty.CollateralizeManage{}
if manage.StabilityFeeRatio != 0 { if manage.StabilityFeeRatio != 0 {
collConfig.StabilityFeeRatio = manage.StabilityFeeRatio collConfig.StabilityFeeRatio = manage.StabilityFeeRatio
} else { } else {
collConfig.StabilityFeeRatio = manConfig.StabilityFeeRatio collConfig.StabilityFeeRatio = manConfig.StabilityFeeRatio
} }
...@@ -336,7 +337,6 @@ func getCollateralizeConfig(db dbm.KV) (*pty.CollateralizeManage, error) { ...@@ -336,7 +337,6 @@ func getCollateralizeConfig(db dbm.KV) (*pty.CollateralizeManage, error) {
return &collCfg, nil return &collCfg, nil
} }
func isSuperAddr(addr string, db dbm.KV) bool { func isSuperAddr(addr string, db dbm.KV) bool {
data, err := db.Get(AddrKey()) data, err := db.Get(AddrKey())
if err != nil { if err != nil {
...@@ -395,25 +395,25 @@ func (action *Action) CollateralizeCreate(create *pty.CollateralizeCreate) (*typ ...@@ -395,25 +395,25 @@ func (action *Action) CollateralizeCreate(create *pty.CollateralizeCreate) (*typ
// 参数检查 // 参数检查
if create.GetTotalBalance() <= 0 { if create.GetTotalBalance() <= 0 {
clog.Error("CollateralizeCreate", "addr", action.fromaddr, "execaddr", action.execaddr, "total balance", create.GetTotalBalance(), "error", types.ErrAmount) clog.Error("CollateralizeCreate", "addr", action.fromaddr, "execaddr", action.execaddr, "total balance", create.GetTotalBalance(), "error", types.ErrAmount)
return nil, types.ErrAmount return nil, types.ErrAmount
} }
// 获取借贷配置 // 获取借贷配置
collcfg, err := getCollateralizeConfig(action.db) collcfg, err := getCollateralizeConfig(action.db)
if err != nil { if err != nil {
clog.Error("CollateralizeCreate.getCollateralizeConfig", "addr", action.fromaddr, "error", err) clog.Error("CollateralizeCreate.getCollateralizeConfig", "addr", action.fromaddr, "error", err)
return nil, err return nil, err
} }
// 判断当前可放贷金额 // 判断当前可放贷金额
reBalance, err := getCollBalance(collcfg.TotalBalance, action.localDB, action.db) reBalance, err := getCollBalance(collcfg.TotalBalance, action.localDB, action.db)
if err != nil { if err != nil {
clog.Error("CollateralizeCreate.getCollBalance", "addr", action.fromaddr, "error", err) clog.Error("CollateralizeCreate.getCollBalance", "addr", action.fromaddr, "error", err)
return nil, err return nil, err
} }
if reBalance < create.GetTotalBalance() { if reBalance < create.GetTotalBalance() {
clog.Error("CollateralizeCreate.getCollBalance", "addr", action.fromaddr, "collBalance", reBalance, "create.balance", create.GetTotalBalance(), "error", pty.ErrCollateralizeLowBalance) clog.Error("CollateralizeCreate.getCollBalance", "addr", action.fromaddr, "collBalance", reBalance, "create.balance", create.GetTotalBalance(), "error", pty.ErrCollateralizeLowBalance)
return nil, pty.ErrCollateralizeLowBalance return nil, pty.ErrCollateralizeLowBalance
} }
// 检查ccny余额 // 检查ccny余额
...@@ -482,15 +482,15 @@ func (action *Action) CollateralizeCreate(create *pty.CollateralizeCreate) (*typ ...@@ -482,15 +482,15 @@ func (action *Action) CollateralizeCreate(create *pty.CollateralizeCreate) (*typ
} }
// 根据最近抵押物价格计算需要冻结的BTY数量 // 根据最近抵押物价格计算需要冻结的BTY数量
func getBtyNumToFrozen(value int64, price float64, ratio float64) (int64,error) { func getBtyNumToFrozen(value int64, price float64, ratio float64) (int64, error) {
if price == 0 { if price == 0 {
clog.Error("Bty price should greate to 0") clog.Error("Bty price should greate to 0")
return 0, pty.ErrPriceInvalid return 0, pty.ErrPriceInvalid
} }
valueReal := float64(value)/1e8 valueReal := float64(value) / 1e8
btyValue := valueReal/(price * ratio) btyValue := valueReal / (price * ratio)
return int64(math.Trunc((btyValue+0.0000001)*1e4)) * 1e4, nil return int64(math.Trunc((btyValue+0.0000001)*1e4)) * 1e4, nil
} }
// 计算清算价格 // 计算清算价格
...@@ -567,7 +567,7 @@ func (action *Action) CollateralizeBorrow(borrow *pty.CollateralizeBorrow) (*typ ...@@ -567,7 +567,7 @@ func (action *Action) CollateralizeBorrow(borrow *pty.CollateralizeBorrow) (*typ
// 借贷金额检查 // 借贷金额检查
if borrow.GetValue() <= 0 { if borrow.GetValue() <= 0 {
clog.Error("CollateralizeBorrow", "CollID", coll.CollateralizeId, "addr", action.fromaddr, "execaddr", action.execaddr, "borrow value", borrow.GetValue(), "error", types.ErrInvalidParam) clog.Error("CollateralizeBorrow", "CollID", coll.CollateralizeId, "addr", action.fromaddr, "execaddr", action.execaddr, "borrow value", borrow.GetValue(), "error", types.ErrInvalidParam)
return nil, types.ErrAmount return nil, types.ErrAmount
} }
// 借贷金额不超过个人限额 // 借贷金额不超过个人限额
...@@ -703,8 +703,8 @@ func (action *Action) CollateralizeRepay(repay *pty.CollateralizeRepay) (*types. ...@@ -703,8 +703,8 @@ func (action *Action) CollateralizeRepay(repay *pty.CollateralizeRepay) (*types.
} }
// 借贷金额+利息 // 借贷金额+利息
fee := (float64(borrowRecord.DebtValue)/1e8) * float64(coll.StabilityFeeRatio) fee := (float64(borrowRecord.DebtValue) / 1e8) * float64(coll.StabilityFeeRatio)
realRepay := borrowRecord.DebtValue + int64(math.Trunc((fee+0.0000001)*1e4)) * 1e4 realRepay := borrowRecord.DebtValue + int64(math.Trunc((fee+0.0000001)*1e4))*1e4
// 检查 // 检查
if !action.CheckExecTokenAccount(action.fromaddr, realRepay, false) { if !action.CheckExecTokenAccount(action.fromaddr, realRepay, false) {
...@@ -770,7 +770,7 @@ func (action *Action) CollateralizeAppend(cAppend *pty.CollateralizeAppend) (*ty ...@@ -770,7 +770,7 @@ func (action *Action) CollateralizeAppend(cAppend *pty.CollateralizeAppend) (*ty
// 参数检查 // 参数检查
if cAppend.GetCollateralValue() <= 0 { if cAppend.GetCollateralValue() <= 0 {
clog.Error("CollateralizeAppend", "addr", action.fromaddr, "execaddr", action.execaddr, "append value", cAppend.GetCollateralValue(), "error", types.ErrAmount) clog.Error("CollateralizeAppend", "addr", action.fromaddr, "execaddr", action.execaddr, "append value", cAppend.GetCollateralValue(), "error", types.ErrAmount)
return nil, types.ErrAmount return nil, types.ErrAmount
} }
// 查找对应的借贷ID // 查找对应的借贷ID
...@@ -838,7 +838,7 @@ func (action *Action) CollateralizeAppend(cAppend *pty.CollateralizeAppend) (*ty ...@@ -838,7 +838,7 @@ func (action *Action) CollateralizeAppend(cAppend *pty.CollateralizeAppend) (*ty
borrowRecord.CollateralValue += cAppend.CollateralValue borrowRecord.CollateralValue += cAppend.CollateralValue
borrowRecord.CollateralPrice = lastPrice borrowRecord.CollateralPrice = lastPrice
borrowRecord.LiquidationPrice = calcLiquidationPrice(borrowRecord.DebtValue, borrowRecord.CollateralValue) borrowRecord.LiquidationPrice = calcLiquidationPrice(borrowRecord.DebtValue, borrowRecord.CollateralValue)
if borrowRecord.LiquidationPrice * PriceWarningRate < lastPrice { if borrowRecord.LiquidationPrice*PriceWarningRate < lastPrice {
// 告警解除 // 告警解除
if borrowRecord.Status == pty.CollateralizeUserStatusWarning { if borrowRecord.Status == pty.CollateralizeUserStatusWarning {
borrowRecord.PreStatus = borrowRecord.Status borrowRecord.PreStatus = borrowRecord.Status
...@@ -927,7 +927,7 @@ func (action *Action) systemLiquidation(coll *pty.Collateralize, price float64) ...@@ -927,7 +927,7 @@ func (action *Action) systemLiquidation(coll *pty.Collateralize, price float64)
var kv []*types.KeyValue var kv []*types.KeyValue
for index, borrowRecord := range coll.BorrowRecords { for index, borrowRecord := range coll.BorrowRecords {
if borrowRecord.LiquidationPrice * PriceWarningRate < price { if borrowRecord.LiquidationPrice*PriceWarningRate < price {
if borrowRecord.Status == pty.CollateralizeUserStatusWarning { if borrowRecord.Status == pty.CollateralizeUserStatusWarning {
borrowRecord.PreStatus = borrowRecord.Status borrowRecord.PreStatus = borrowRecord.Status
borrowRecord.Status = pty.CollateralizeUserStatusCreate borrowRecord.Status = pty.CollateralizeUserStatusCreate
...@@ -990,7 +990,7 @@ func (action *Action) expireLiquidation(coll *pty.Collateralize) (*types.Receipt ...@@ -990,7 +990,7 @@ func (action *Action) expireLiquidation(coll *pty.Collateralize) (*types.Receipt
var kv []*types.KeyValue var kv []*types.KeyValue
for index, borrowRecord := range coll.BorrowRecords { for index, borrowRecord := range coll.BorrowRecords {
if borrowRecord.ExpireTime - ExpireWarningTime > action.blocktime { if borrowRecord.ExpireTime-ExpireWarningTime > action.blocktime {
continue continue
} }
...@@ -1057,7 +1057,7 @@ func pricePolicy(feed *pty.CollateralizeFeed) float64 { ...@@ -1057,7 +1057,7 @@ func pricePolicy(feed *pty.CollateralizeFeed) float64 {
} }
for i, price := range feed.Price { for i, price := range feed.Price {
totalPrice += price * (float64(feed.Volume[i])/float64(totalVolume)) totalPrice += price * (float64(feed.Volume[i]) / float64(totalVolume))
} }
return totalPrice return totalPrice
...@@ -1098,7 +1098,7 @@ func (action *Action) CollateralizeFeed(feed *pty.CollateralizeFeed) (*types.Rec ...@@ -1098,7 +1098,7 @@ func (action *Action) CollateralizeFeed(feed *pty.CollateralizeFeed) (*types.Rec
} }
// 超时清算判断 // 超时清算判断
if coll.LatestExpireTime - ExpireWarningTime <= action.blocktime { if coll.LatestExpireTime-ExpireWarningTime <= action.blocktime {
receipt, err := action.expireLiquidation(coll) receipt, err := action.expireLiquidation(coll)
if err != nil { if err != nil {
clog.Error("CollateralizePriceFeed", "Collateralize ID", coll.CollateralizeId, "expire liquidation error", err) clog.Error("CollateralizePriceFeed", "Collateralize ID", coll.CollateralizeId, "expire liquidation error", err)
...@@ -1153,7 +1153,7 @@ func (action *Action) CollateralizeRetrieve(retrieve *pty.CollateralizeRetrieve) ...@@ -1153,7 +1153,7 @@ func (action *Action) CollateralizeRetrieve(retrieve *pty.CollateralizeRetrieve)
clog.Error("CollateralizeRetrieve", "CollateralizeId", retrieve.CollateralizeId, "error", "balance error", "retrieve balance", retrieve.Balance, "available balance", collateralize.Balance) clog.Error("CollateralizeRetrieve", "CollateralizeId", retrieve.CollateralizeId, "error", "balance error", "retrieve balance", retrieve.Balance, "available balance", collateralize.Balance)
return nil, types.ErrAmount return nil, types.ErrAmount
} }
// 解冻ccny // 解冻ccny
receipt, err = action.tokenAccount.ExecActive(action.fromaddr, action.execaddr, retrieve.Balance) receipt, err = action.tokenAccount.ExecActive(action.fromaddr, action.execaddr, retrieve.Balance)
if err != nil { if err != nil {
...@@ -1248,7 +1248,7 @@ func queryCollateralizeByAddr(localdb dbm.Lister, addr string, status int32, ind ...@@ -1248,7 +1248,7 @@ func queryCollateralizeByAddr(localdb dbm.Lister, addr string, status int32, ind
clog.Debug("queryCollateralizesByAddr", "decode", err) clog.Debug("queryCollateralizesByAddr", "decode", err)
return nil, err return nil, err
} }
if status ==0 || coll.Status == status { if status == 0 || coll.Status == status {
ids = append(ids, coll.CollateralizeId) ids = append(ids, coll.CollateralizeId)
} }
} }
......
...@@ -105,4 +105,4 @@ func (c *Collateralize) ExecDelLocal_Retrieve(payload *pty.CollateralizeRetrieve ...@@ -105,4 +105,4 @@ func (c *Collateralize) ExecDelLocal_Retrieve(payload *pty.CollateralizeRetrieve
// ExecDelLocal_Manage Action // ExecDelLocal_Manage Action
func (c *Collateralize) ExecDelLocal_Manage(payload *pty.CollateralizeManage, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (c *Collateralize) ExecDelLocal_Manage(payload *pty.CollateralizeManage, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execDelLocal(tx, receiptData) return c.execDelLocal(tx, receiptData)
} }
\ No newline at end of file
...@@ -54,4 +54,4 @@ func calcCollateralizeRecordStatusPrefix(status string) []byte { ...@@ -54,4 +54,4 @@ func calcCollateralizeRecordStatusPrefix(status string) []byte {
func calcCollateralizeRecordStatusKey(status int32, index int64) []byte { func calcCollateralizeRecordStatusKey(status int32, index int64) []byte {
key := fmt.Sprintf("LODB-collateralize-record-status:%d:%018d", status, index) key := fmt.Sprintf("LODB-collateralize-record-status:%d:%018d", status, index)
return []byte(key) return []byte(key)
} }
\ No newline at end of file
...@@ -10,23 +10,23 @@ import ( ...@@ -10,23 +10,23 @@ import (
) )
func (c *Collateralize) Query_CollateralizeInfoByID(req *pty.ReqCollateralizeInfo) (types.Message, error) { func (c *Collateralize) Query_CollateralizeInfoByID(req *pty.ReqCollateralizeInfo) (types.Message, error) {
coll,err := queryCollateralizeByID(c.GetStateDB(), req.CollateralizeId) coll, err := queryCollateralizeByID(c.GetStateDB(), req.CollateralizeId)
if err != nil { if err != nil {
clog.Error("Query_CollateralizeInfoByID", "id", req.CollateralizeId, "error", err) clog.Error("Query_CollateralizeInfoByID", "id", req.CollateralizeId, "error", err)
return nil, err return nil, err
} }
info := &pty.RepCollateralizeCurrentInfo{ info := &pty.RepCollateralizeCurrentInfo{
Status: coll.Status, Status: coll.Status,
TotalBalance: coll.TotalBalance, TotalBalance: coll.TotalBalance,
DebtCeiling: coll.DebtCeiling, DebtCeiling: coll.DebtCeiling,
LiquidationRatio: coll.LiquidationRatio, LiquidationRatio: coll.LiquidationRatio,
StabilityFeeRatio: coll.StabilityFeeRatio, StabilityFeeRatio: coll.StabilityFeeRatio,
CreateAddr: coll.CreateAddr, CreateAddr: coll.CreateAddr,
Balance: coll.Balance, Balance: coll.Balance,
Period: coll.Period, Period: coll.Period,
CollateralizeId: coll.CollateralizeId, CollateralizeId: coll.CollateralizeId,
CollBalance: coll.CollBalance, CollBalance: coll.CollBalance,
} }
info.BorrowRecords = append(info.BorrowRecords, coll.BorrowRecords...) info.BorrowRecords = append(info.BorrowRecords, coll.BorrowRecords...)
info.BorrowRecords = append(info.BorrowRecords, coll.InvalidRecords...) info.BorrowRecords = append(info.BorrowRecords, coll.InvalidRecords...)
...@@ -37,23 +37,23 @@ func (c *Collateralize) Query_CollateralizeInfoByID(req *pty.ReqCollateralizeInf ...@@ -37,23 +37,23 @@ func (c *Collateralize) Query_CollateralizeInfoByID(req *pty.ReqCollateralizeInf
func (c *Collateralize) Query_CollateralizeInfoByIDs(req *pty.ReqCollateralizeInfos) (types.Message, error) { func (c *Collateralize) Query_CollateralizeInfoByIDs(req *pty.ReqCollateralizeInfos) (types.Message, error) {
infos := &pty.RepCollateralizeCurrentInfos{} infos := &pty.RepCollateralizeCurrentInfos{}
for _, id := range req.CollateralizeIds { for _, id := range req.CollateralizeIds {
coll,err := queryCollateralizeByID(c.GetStateDB(), id) coll, err := queryCollateralizeByID(c.GetStateDB(), id)
if err != nil { if err != nil {
clog.Error("Query_CollateralizeInfoByID", "id", id, "error", err) clog.Error("Query_CollateralizeInfoByID", "id", id, "error", err)
return nil, err return nil, err
} }
info := &pty.RepCollateralizeCurrentInfo{ info := &pty.RepCollateralizeCurrentInfo{
Status: coll.Status, Status: coll.Status,
TotalBalance: coll.TotalBalance, TotalBalance: coll.TotalBalance,
DebtCeiling: coll.DebtCeiling, DebtCeiling: coll.DebtCeiling,
LiquidationRatio: coll.LiquidationRatio, LiquidationRatio: coll.LiquidationRatio,
StabilityFeeRatio: coll.StabilityFeeRatio, StabilityFeeRatio: coll.StabilityFeeRatio,
CreateAddr: coll.CreateAddr, CreateAddr: coll.CreateAddr,
Balance: coll.Balance, Balance: coll.Balance,
Period: coll.Period, Period: coll.Period,
CollateralizeId: coll.CollateralizeId, CollateralizeId: coll.CollateralizeId,
CollBalance: coll.CollBalance, CollBalance: coll.CollBalance,
} }
info.BorrowRecords = append(info.BorrowRecords, coll.BorrowRecords...) info.BorrowRecords = append(info.BorrowRecords, coll.BorrowRecords...)
info.BorrowRecords = append(info.BorrowRecords, coll.InvalidRecords...) info.BorrowRecords = append(info.BorrowRecords, coll.InvalidRecords...)
...@@ -111,7 +111,7 @@ func (c *Collateralize) Query_CollateralizeRecordByAddr(req *pty.ReqCollateraliz ...@@ -111,7 +111,7 @@ func (c *Collateralize) Query_CollateralizeRecordByAddr(req *pty.ReqCollateraliz
if req.Status == 0 { if req.Status == 0 {
ret.Records = records ret.Records = records
} else { } else {
for _,record := range records { for _, record := range records {
if record.Status == req.Status { if record.Status == req.Status {
ret.Records = append(ret.Records, record) ret.Records = append(ret.Records, record)
} }
...@@ -146,13 +146,13 @@ func (c *Collateralize) Query_CollateralizeConfig(req *pty.ReqCollateralizeRecor ...@@ -146,13 +146,13 @@ func (c *Collateralize) Query_CollateralizeConfig(req *pty.ReqCollateralizeRecor
} }
ret := &pty.RepCollateralizeConfig{ ret := &pty.RepCollateralizeConfig{
TotalBalance:config.TotalBalance, TotalBalance: config.TotalBalance,
DebtCeiling: config.DebtCeiling, DebtCeiling: config.DebtCeiling,
LiquidationRatio: config.LiquidationRatio, LiquidationRatio: config.LiquidationRatio,
StabilityFeeRatio: config.StabilityFeeRatio, StabilityFeeRatio: config.StabilityFeeRatio,
Period: config.Period, Period: config.Period,
Balance: balance, Balance: balance,
CurrentTime: config.CurrentTime, CurrentTime: config.CurrentTime,
} }
return ret, nil return ret, nil
...@@ -165,5 +165,5 @@ func (c *Collateralize) Query_CollateralizePrice(req *pty.ReqCollateralizeRecord ...@@ -165,5 +165,5 @@ func (c *Collateralize) Query_CollateralizePrice(req *pty.ReqCollateralizeRecord
return nil, err return nil, err
} }
return &pty.RepCollateralizePrice{Price:price}, nil return &pty.RepCollateralizePrice{Price: price}, nil
} }
\ No newline at end of file
...@@ -53,12 +53,12 @@ func (collateralize *CollateralizeType) GetName() string { ...@@ -53,12 +53,12 @@ func (collateralize *CollateralizeType) GetName() string {
// GetLogMap method // GetLogMap method
func (collateralize *CollateralizeType) GetLogMap() map[int64]*types.LogInfo { func (collateralize *CollateralizeType) GetLogMap() map[int64]*types.LogInfo {
return map[int64]*types.LogInfo{ return map[int64]*types.LogInfo{
TyLogCollateralizeCreate: {Ty: reflect.TypeOf(ReceiptCollateralize{}), Name: "LogCollateralizeCreate"}, TyLogCollateralizeCreate: {Ty: reflect.TypeOf(ReceiptCollateralize{}), Name: "LogCollateralizeCreate"},
TyLogCollateralizeBorrow: {Ty: reflect.TypeOf(ReceiptCollateralize{}), Name: "LogCollateralizeBorrow"}, TyLogCollateralizeBorrow: {Ty: reflect.TypeOf(ReceiptCollateralize{}), Name: "LogCollateralizeBorrow"},
TyLogCollateralizeRepay: {Ty: reflect.TypeOf(ReceiptCollateralize{}), Name: "LogCollateralizeRepay"}, TyLogCollateralizeRepay: {Ty: reflect.TypeOf(ReceiptCollateralize{}), Name: "LogCollateralizeRepay"},
TyLogCollateralizeAppend: {Ty: reflect.TypeOf(ReceiptCollateralize{}), Name: "LogCollateralizeAppend"}, TyLogCollateralizeAppend: {Ty: reflect.TypeOf(ReceiptCollateralize{}), Name: "LogCollateralizeAppend"},
TyLogCollateralizeFeed: {Ty: reflect.TypeOf(ReceiptCollateralize{}), Name: "LogCollateralizeFeed"}, TyLogCollateralizeFeed: {Ty: reflect.TypeOf(ReceiptCollateralize{}), Name: "LogCollateralizeFeed"},
TyLogCollateralizeRetrieve: {Ty: reflect.TypeOf(ReceiptCollateralize{}), Name: "LogCollateralizeRetrieve"}, TyLogCollateralizeRetrieve: {Ty: reflect.TypeOf(ReceiptCollateralize{}), Name: "LogCollateralizeRetrieve"},
} }
} }
...@@ -136,13 +136,13 @@ func (collateralize CollateralizeType) CreateTx(action string, message json.RawM ...@@ -136,13 +136,13 @@ func (collateralize CollateralizeType) CreateTx(action string, message json.RawM
// GetTypeMap method // GetTypeMap method
func (collateralize CollateralizeType) GetTypeMap() map[string]int32 { func (collateralize CollateralizeType) GetTypeMap() map[string]int32 {
return map[string]int32{ return map[string]int32{
"Create": CollateralizeActionCreate, "Create": CollateralizeActionCreate,
"Borrow": CollateralizeActionBorrow, "Borrow": CollateralizeActionBorrow,
"Repay": CollateralizeActionRepay, "Repay": CollateralizeActionRepay,
"Append": CollateralizeActionAppend, "Append": CollateralizeActionAppend,
"Feed": CollateralizeActionFeed, "Feed": CollateralizeActionFeed,
"Retrieve": CollateralizeActionRetrieve, "Retrieve": CollateralizeActionRetrieve,
"Manage": CollateralizeActionManage, "Manage": CollateralizeActionManage,
} }
} }
...@@ -154,7 +154,7 @@ func CreateRawCollateralizeCreateTx(cfg *types.Chain33Config, parm *Collateraliz ...@@ -154,7 +154,7 @@ func CreateRawCollateralizeCreateTx(cfg *types.Chain33Config, parm *Collateraliz
} }
v := &CollateralizeCreate{ v := &CollateralizeCreate{
TotalBalance: int64(math.Trunc((parm.TotalBalance+0.0000001)*1e4)) * 1e4, TotalBalance: int64(math.Trunc((parm.TotalBalance+0.0000001)*1e4)) * 1e4,
} }
create := &CollateralizeAction{ create := &CollateralizeAction{
Ty: CollateralizeActionCreate, Ty: CollateralizeActionCreate,
...@@ -183,7 +183,7 @@ func CreateRawCollateralizeBorrowTx(cfg *types.Chain33Config, parm *Collateraliz ...@@ -183,7 +183,7 @@ func CreateRawCollateralizeBorrowTx(cfg *types.Chain33Config, parm *Collateraliz
v := &CollateralizeBorrow{ v := &CollateralizeBorrow{
CollateralizeId: parm.CollateralizeID, CollateralizeId: parm.CollateralizeID,
Value: int64(math.Trunc((parm.Value+0.0000001)*1e4)) * 1e4, Value: int64(math.Trunc((parm.Value+0.0000001)*1e4)) * 1e4,
} }
borrow := &CollateralizeAction{ borrow := &CollateralizeAction{
Ty: CollateralizeActionBorrow, Ty: CollateralizeActionBorrow,
...@@ -212,7 +212,7 @@ func CreateRawCollateralizeRepayTx(cfg *types.Chain33Config, parm *Collateralize ...@@ -212,7 +212,7 @@ func CreateRawCollateralizeRepayTx(cfg *types.Chain33Config, parm *Collateralize
v := &CollateralizeRepay{ v := &CollateralizeRepay{
CollateralizeId: parm.CollateralizeID, CollateralizeId: parm.CollateralizeID,
RecordId:parm.RecordID, RecordId: parm.RecordID,
} }
repay := &CollateralizeAction{ repay := &CollateralizeAction{
Ty: CollateralizeActionRepay, Ty: CollateralizeActionRepay,
...@@ -241,7 +241,7 @@ func CreateRawCollateralizeAppendTx(cfg *types.Chain33Config, parm *Collateraliz ...@@ -241,7 +241,7 @@ func CreateRawCollateralizeAppendTx(cfg *types.Chain33Config, parm *Collateraliz
v := &CollateralizeAppend{ v := &CollateralizeAppend{
CollateralizeId: parm.CollateralizeID, CollateralizeId: parm.CollateralizeID,
RecordId:parm.RecordID, RecordId: parm.RecordID,
CollateralValue: int64(math.Trunc((parm.Value+0.0000001)*1e4)) * 1e4, CollateralValue: int64(math.Trunc((parm.Value+0.0000001)*1e4)) * 1e4,
} }
append := &CollateralizeAction{ append := &CollateralizeAction{
...@@ -270,7 +270,7 @@ func CreateRawCollateralizeFeedTx(cfg *types.Chain33Config, parm *CollateralizeF ...@@ -270,7 +270,7 @@ func CreateRawCollateralizeFeedTx(cfg *types.Chain33Config, parm *CollateralizeF
} }
v := &CollateralizeFeed{ v := &CollateralizeFeed{
Price: parm.Price, Price: parm.Price,
Volume: parm.Volume, Volume: parm.Volume,
} }
feed := &CollateralizeAction{ feed := &CollateralizeAction{
...@@ -300,7 +300,7 @@ func CreateRawCollateralizeRetrieveTx(cfg *types.Chain33Config, parm *Collateral ...@@ -300,7 +300,7 @@ func CreateRawCollateralizeRetrieveTx(cfg *types.Chain33Config, parm *Collateral
v := &CollateralizeRetrieve{ v := &CollateralizeRetrieve{
CollateralizeId: parm.CollateralizeID, CollateralizeId: parm.CollateralizeID,
Balance: int64(math.Trunc((parm.Balance+0.0000001)*1e4)) * 1e4, Balance: int64(math.Trunc((parm.Balance+0.0000001)*1e4)) * 1e4,
} }
close := &CollateralizeAction{ close := &CollateralizeAction{
Ty: CollateralizeActionRetrieve, Ty: CollateralizeActionRetrieve,
...@@ -329,11 +329,11 @@ func CreateRawCollateralizeManageTx(cfg *types.Chain33Config, parm *Collateraliz ...@@ -329,11 +329,11 @@ func CreateRawCollateralizeManageTx(cfg *types.Chain33Config, parm *Collateraliz
} }
v := &CollateralizeManage{ v := &CollateralizeManage{
DebtCeiling: int64(math.Trunc((parm.DebtCeiling+0.0000001)*1e4)) * 1e4, DebtCeiling: int64(math.Trunc((parm.DebtCeiling+0.0000001)*1e4)) * 1e4,
LiquidationRatio: parm.LiquidationRatio, LiquidationRatio: parm.LiquidationRatio,
StabilityFeeRatio: parm.StabilityFeeRatio, StabilityFeeRatio: parm.StabilityFeeRatio,
Period: parm.Period, Period: parm.Period,
TotalBalance: int64(math.Trunc((parm.TotalBalance+0.0000001)*1e4)) * 1e4, TotalBalance: int64(math.Trunc((parm.TotalBalance+0.0000001)*1e4)) * 1e4,
} }
manage := &CollateralizeAction{ manage := &CollateralizeAction{
......
...@@ -6,52 +6,52 @@ package types ...@@ -6,52 +6,52 @@ package types
// CollateralizeCreateTx for construction // CollateralizeCreateTx for construction
type CollateralizeCreateTx struct { type CollateralizeCreateTx struct {
TotalBalance float64 `json:"totalBalance"` TotalBalance float64 `json:"totalBalance"`
Fee int64 `json:"fee"` Fee int64 `json:"fee"`
} }
// CollateralizeBorrowTx for construction // CollateralizeBorrowTx for construction
type CollateralizeBorrowTx struct { type CollateralizeBorrowTx struct {
CollateralizeID string `json:"collateralizeId"` CollateralizeID string `json:"collateralizeId"`
Value float64 `json:"value"` Value float64 `json:"value"`
Fee int64 `json:"fee"` Fee int64 `json:"fee"`
} }
// CollateralizeRepayTx for construction // CollateralizeRepayTx for construction
type CollateralizeRepayTx struct { type CollateralizeRepayTx struct {
CollateralizeID string `json:"collateralizeId"` CollateralizeID string `json:"collateralizeId"`
RecordID string `json:"recordID"` RecordID string `json:"recordID"`
Fee int64 `json:"fee"` Fee int64 `json:"fee"`
} }
// CollateralizeAppednTx for construction // CollateralizeAppednTx for construction
type CollateralizeAppendTx struct { type CollateralizeAppendTx struct {
CollateralizeID string `json:"collateralizeId"` CollateralizeID string `json:"collateralizeId"`
RecordID string `json:"recordID"` RecordID string `json:"recordID"`
Value float64 `json:"value"` Value float64 `json:"value"`
Fee int64 `json:"fee"` Fee int64 `json:"fee"`
} }
// CollateralizeFeedTx for construction // CollateralizeFeedTx for construction
type CollateralizeFeedTx struct { type CollateralizeFeedTx struct {
Price []float64 `json:"price"` Price []float64 `json:"price"`
Volume []int64 `json:"volume"` Volume []int64 `json:"volume"`
Fee int64 `json:"fee"` Fee int64 `json:"fee"`
} }
// CollateralizeRetrieveTx for construction // CollateralizeRetrieveTx for construction
type CollateralizeRetrieveTx struct { type CollateralizeRetrieveTx struct {
CollateralizeID string `json:"collateralizeId"` CollateralizeID string `json:"collateralizeId"`
Balance float64 `json:"Balance"` Balance float64 `json:"Balance"`
Fee int64 `json:"fee"` Fee int64 `json:"fee"`
} }
// CollateralizeManageTx for construction // CollateralizeManageTx for construction
type CollateralizeManageTx struct { type CollateralizeManageTx struct {
DebtCeiling float64 `json:"debtCeiling"` DebtCeiling float64 `json:"debtCeiling"`
LiquidationRatio float64 `json:"liquidationRatio"` LiquidationRatio float64 `json:"liquidationRatio"`
StabilityFeeRatio float64 `json:"stabilityFeeRatio"` StabilityFeeRatio float64 `json:"stabilityFeeRatio"`
Period int64 `json:"period"` Period int64 `json:"period"`
TotalBalance float64 `json:"totalBalance"` TotalBalance float64 `json:"totalBalance"`
Fee int64 `json:"fee"` Fee int64 `json:"fee"`
} }
...@@ -15,18 +15,18 @@ const ( ...@@ -15,18 +15,18 @@ const (
CollateralizeActionManage CollateralizeActionManage
//log for Collateralize //log for Collateralize
TyLogCollateralizeCreate = 731 TyLogCollateralizeCreate = 731
TyLogCollateralizeBorrow = 732 TyLogCollateralizeBorrow = 732
TyLogCollateralizeRepay = 733 TyLogCollateralizeRepay = 733
TyLogCollateralizeAppend = 734 TyLogCollateralizeAppend = 734
TyLogCollateralizeFeed = 735 TyLogCollateralizeFeed = 735
TyLogCollateralizeRetrieve = 736 TyLogCollateralizeRetrieve = 736
) )
// Collateralize name // Collateralize name
const ( const (
CollateralizeX = "collateralize" CollateralizeX = "collateralize"
CCNYTokenName = "CCNY" CCNYTokenName = "CCNY"
CollateralizePreLiquidationRatio = 1.1 //TODO 预清算比例,抵押物价值跌到借出ccny价值110%的时候开始清算 CollateralizePreLiquidationRatio = 1.1 //TODO 预清算比例,抵押物价值跌到借出ccny价值110%的时候开始清算
) )
...@@ -50,4 +50,4 @@ const ( ...@@ -50,4 +50,4 @@ const (
CollateralizeUserStatusExpire CollateralizeUserStatusExpire
CollateralizeUserStatusExpireLiquidate CollateralizeUserStatusExpireLiquidate
CollateralizeUserStatusClose CollateralizeUserStatusClose
) )
\ No newline at end of file
...@@ -388,18 +388,18 @@ manage() { ...@@ -388,18 +388,18 @@ manage() {
echo "========== # issuance add issuance-price-feed end ==========" echo "========== # issuance add issuance-price-feed end =========="
chain33_BlockWait 1 ${MAIN_HTTP} chain33_BlockWait 1 ${MAIN_HTTP}
# echo "========== # issuance add issuance-guarantor begin ==========" # echo "========== # issuance add issuance-guarantor begin =========="
# tx=$(curl -ksd '{"method":"Chain33.CreateTransaction","params":[{"execer":"manage","actionName":"Modify","payload":{"key": "issuance-guarantor", "value":"'"${IssuanceAddr3}"'", "op":"add"}}]}' ${MAIN_HTTP} | jq -r ".result") # tx=$(curl -ksd '{"method":"Chain33.CreateTransaction","params":[{"execer":"manage","actionName":"Modify","payload":{"key": "issuance-guarantor", "value":"'"${IssuanceAddr3}"'", "op":"add"}}]}' ${MAIN_HTTP} | jq -r ".result")
# #
# data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]") # data=$(curl -ksd '{"method":"Chain33.DecodeRawTransaction","params":[{"txHex":"'"$tx"'"}]}' ${MAIN_HTTP} | jq -r ".result.txs[0]")
# ok=$(jq '(.execer != "")' <<<"$data") # ok=$(jq '(.execer != "")' <<<"$data")
# #
# [ "$ok" == true ] # [ "$ok" == true ]
# echo_rst "$FUNCNAME" "$?" # echo_rst "$FUNCNAME" "$?"
# #
# chain33_SignRawTx "$tx" ${SystemManager} ${MAIN_HTTP} # chain33_SignRawTx "$tx" ${SystemManager} ${MAIN_HTTP}
# echo "========== # issuance add issuance-guarantor end ==========" # echo "========== # issuance add issuance-guarantor end =========="
# chain33_BlockWait 1 ${MAIN_HTTP} # chain33_BlockWait 1 ${MAIN_HTTP}
} }
token() { token() {
......
...@@ -2,12 +2,13 @@ package commands ...@@ -2,12 +2,13 @@ package commands
import ( import (
"fmt" "fmt"
"strconv"
jsonrpc "github.com/33cn/chain33/rpc/jsonclient" jsonrpc "github.com/33cn/chain33/rpc/jsonclient"
rpctypes "github.com/33cn/chain33/rpc/types" rpctypes "github.com/33cn/chain33/rpc/types"
"github.com/33cn/chain33/types" "github.com/33cn/chain33/types"
pkt "github.com/33cn/plugin/plugin/dapp/issuance/types" pkt "github.com/33cn/plugin/plugin/dapp/issuance/types"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"strconv"
) )
// IssuanceCmd 斗牛游戏命令行 // IssuanceCmd 斗牛游戏命令行
...@@ -66,7 +67,7 @@ func IssuanceCreate(cmd *cobra.Command, args []string) { ...@@ -66,7 +67,7 @@ func IssuanceCreate(cmd *cobra.Command, args []string) {
params := &rpctypes.CreateTxIn{ params := &rpctypes.CreateTxIn{
Execer: cfg.ExecName(pkt.IssuanceX), Execer: cfg.ExecName(pkt.IssuanceX),
ActionName: "IssuanceCreate", ActionName: "IssuanceCreate",
Payload: []byte(fmt.Sprintf("{\"totalBalance\":%f, \"debtCeiling\":%f, \"liquidationRatio\":%f, \"period\":%d}", Payload: []byte(fmt.Sprintf("{\"totalBalance\":%f, \"debtCeiling\":%f, \"liquidationRatio\":%f, \"period\":%d}",
balance, debtCeiling, liquidationRatio, period)), balance, debtCeiling, liquidationRatio, period)),
} }
...@@ -351,8 +352,8 @@ func IssuanceQuery(cmd *cobra.Command, args []string) { ...@@ -351,8 +352,8 @@ func IssuanceQuery(cmd *cobra.Command, args []string) {
req := &pkt.ReqIssuanceRecordsByAddr{ req := &pkt.ReqIssuanceRecordsByAddr{
IssuanceId: issuanceID, IssuanceId: issuanceID,
Status: int32(status), Status: int32(status),
Addr: address, Addr: address,
} }
params.Payload = types.MustPBToJSON(req) params.Payload = types.MustPBToJSON(req)
var res pkt.RepIssuanceRecords var res pkt.RepIssuanceRecords
...@@ -363,18 +364,18 @@ func IssuanceQuery(cmd *cobra.Command, args []string) { ...@@ -363,18 +364,18 @@ func IssuanceQuery(cmd *cobra.Command, args []string) {
req := &pkt.ReqIssuanceRecordsByStatus{ req := &pkt.ReqIssuanceRecordsByStatus{
IssuanceId: issuanceID, IssuanceId: issuanceID,
Status: int32(status), Status: int32(status),
} }
params.Payload = types.MustPBToJSON(req) params.Payload = types.MustPBToJSON(req)
var res pkt.RepIssuanceRecords var res pkt.RepIssuanceRecords
ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res) ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res)
ctx.Run() ctx.Run()
} else if debtID != ""{ } else if debtID != "" {
params.FuncName = "IssuanceRecordByID" params.FuncName = "IssuanceRecordByID"
req := &pkt.ReqIssuanceDebtInfo{ req := &pkt.ReqIssuanceDebtInfo{
IssuanceId: issuanceID, IssuanceId: issuanceID,
DebtId: debtID, DebtId: debtID,
} }
params.Payload = types.MustPBToJSON(req) params.Payload = types.MustPBToJSON(req)
var res pkt.RepIssuanceDebtInfo var res pkt.RepIssuanceDebtInfo
...@@ -394,7 +395,7 @@ func IssuanceQuery(cmd *cobra.Command, args []string) { ...@@ -394,7 +395,7 @@ func IssuanceQuery(cmd *cobra.Command, args []string) {
} else if statusStr != "" { } else if statusStr != "" {
params.FuncName = "IssuanceByStatus" params.FuncName = "IssuanceByStatus"
req := &pkt.ReqIssuanceByStatus{Status:int32(status)} req := &pkt.ReqIssuanceByStatus{Status: int32(status)}
params.Payload = types.MustPBToJSON(req) params.Payload = types.MustPBToJSON(req)
var res pkt.RepIssuanceIDs var res pkt.RepIssuanceIDs
ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res) ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res)
......
...@@ -86,4 +86,4 @@ func (c *Issuance) ExecDelLocal_Close(payload *pty.IssuanceClose, tx *types.Tran ...@@ -86,4 +86,4 @@ func (c *Issuance) ExecDelLocal_Close(payload *pty.IssuanceClose, tx *types.Tran
// ExecDelLocal_Manage Action // ExecDelLocal_Manage Action
func (c *Issuance) ExecDelLocal_Manage(payload *pty.IssuanceManage, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) { func (c *Issuance) ExecDelLocal_Manage(payload *pty.IssuanceManage, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execDelLocal(tx, receiptData) return c.execDelLocal(tx, receiptData)
} }
\ No newline at end of file
...@@ -63,8 +63,8 @@ func (c *Issuance) GetDriverName() string { ...@@ -63,8 +63,8 @@ func (c *Issuance) GetDriverName() string {
func (c *Issuance) addIssuanceID(index int64, issuanceId string) (kvs []*types.KeyValue) { func (c *Issuance) addIssuanceID(index int64, issuanceId string) (kvs []*types.KeyValue) {
key := calcIssuanceKey(issuanceId, index) key := calcIssuanceKey(issuanceId, index)
record := &pty.IssuanceRecord{ record := &pty.IssuanceRecord{
IssuanceId:issuanceId, IssuanceId: issuanceId,
Index: index, Index: index,
} }
kv := &types.KeyValue{Key: key, Value: types.Encode(record)} kv := &types.KeyValue{Key: key, Value: types.Encode(record)}
...@@ -83,8 +83,8 @@ func (c *Issuance) deleteIssuanceID(index int64, issuanceId string) (kvs []*type ...@@ -83,8 +83,8 @@ func (c *Issuance) deleteIssuanceID(index int64, issuanceId string) (kvs []*type
func (c *Issuance) addIssuanceStatus(status int32, index int64, issuanceId string) (kvs []*types.KeyValue) { func (c *Issuance) addIssuanceStatus(status int32, index int64, issuanceId string) (kvs []*types.KeyValue) {
key := calcIssuanceStatusKey(status, index) key := calcIssuanceStatusKey(status, index)
record := &pty.IssuanceRecord{ record := &pty.IssuanceRecord{
IssuanceId:issuanceId, IssuanceId: issuanceId,
Index: index, Index: index,
} }
kv := &types.KeyValue{Key: key, Value: types.Encode(record)} kv := &types.KeyValue{Key: key, Value: types.Encode(record)}
...@@ -103,9 +103,9 @@ func (c *Issuance) deleteIssuanceStatus(status int32, index int64) (kvs []*types ...@@ -103,9 +103,9 @@ func (c *Issuance) deleteIssuanceStatus(status int32, index int64) (kvs []*types
func (c *Issuance) addIssuanceRecordAddr(accountAddr string, index int64, debtId string, issuanceId string) (kvs []*types.KeyValue) { func (c *Issuance) addIssuanceRecordAddr(accountAddr string, index int64, debtId string, issuanceId string) (kvs []*types.KeyValue) {
key := calcIssuanceRecordAddrKey(accountAddr, index) key := calcIssuanceRecordAddrKey(accountAddr, index)
record := &pty.IssuanceRecord{ record := &pty.IssuanceRecord{
IssuanceId:issuanceId, IssuanceId: issuanceId,
DebtId: debtId, DebtId: debtId,
Index: index, Index: index,
} }
kv := &types.KeyValue{Key: key, Value: types.Encode(record)} kv := &types.KeyValue{Key: key, Value: types.Encode(record)}
...@@ -125,10 +125,10 @@ func (c *Issuance) addIssuanceRecordStatus(recordStatus int32, accountAddr strin ...@@ -125,10 +125,10 @@ func (c *Issuance) addIssuanceRecordStatus(recordStatus int32, accountAddr strin
key := calcIssuanceRecordStatusKey(recordStatus, index) key := calcIssuanceRecordStatusKey(recordStatus, index)
record := &pty.IssuanceRecord{ record := &pty.IssuanceRecord{
IssuanceId:issuanceId, IssuanceId: issuanceId,
DebtId: debtId, DebtId: debtId,
Addr: accountAddr, Addr: accountAddr,
Index: index, Index: index,
} }
kv := &types.KeyValue{Key: key, Value: types.Encode(record)} kv := &types.KeyValue{Key: key, Value: types.Encode(record)}
...@@ -148,8 +148,8 @@ func (c *Issuance) addIssuancePriceRecord(recordTime int64, price float64) (kvs ...@@ -148,8 +148,8 @@ func (c *Issuance) addIssuancePriceRecord(recordTime int64, price float64) (kvs
key := calcIssuancePriceKey(string(recordTime)) key := calcIssuancePriceKey(string(recordTime))
record := &pty.IssuanceAssetPriceRecord{ record := &pty.IssuanceAssetPriceRecord{
RecordTime:recordTime, RecordTime: recordTime,
BtyPrice:price, BtyPrice: price,
} }
kv := &types.KeyValue{Key: key, Value: types.Encode(record)} kv := &types.KeyValue{Key: key, Value: types.Encode(record)}
kvs = append(kvs, kv) kvs = append(kvs, kv)
...@@ -159,7 +159,7 @@ func (c *Issuance) addIssuancePriceRecord(recordTime int64, price float64) (kvs ...@@ -159,7 +159,7 @@ func (c *Issuance) addIssuancePriceRecord(recordTime int64, price float64) (kvs
func (c *Issuance) deleteIssuancePriceRecord(recordTime int64) (kvs []*types.KeyValue) { func (c *Issuance) deleteIssuancePriceRecord(recordTime int64) (kvs []*types.KeyValue) {
key := calcIssuancePriceKey(string(recordTime)) key := calcIssuancePriceKey(string(recordTime))
kv := &types.KeyValue{Key: key, Value:nil} kv := &types.KeyValue{Key: key, Value: nil}
kvs = append(kvs, kv) kvs = append(kvs, kv)
return kvs return kvs
} }
...@@ -176,4 +176,4 @@ func (c *Issuance) ExecutorOrder() int64 { ...@@ -176,4 +176,4 @@ func (c *Issuance) ExecutorOrder() int64 {
return drivers.ExecLocalSameTime return drivers.ExecLocalSameTime
} }
return c.DriverBase.ExecutorOrder() return c.DriverBase.ExecutorOrder()
} }
\ No newline at end of file
package executor package executor
import ( import (
"github.com/33cn/chain33/client"
"testing" "testing"
"time" "time"
"github.com/33cn/chain33/client"
"github.com/33cn/chain33/account" "github.com/33cn/chain33/account"
apimock "github.com/33cn/chain33/client/mocks" apimock "github.com/33cn/chain33/client/mocks"
"github.com/33cn/chain33/common" "github.com/33cn/chain33/common"
...@@ -40,7 +41,7 @@ var ( ...@@ -40,7 +41,7 @@ var (
[]byte("1JRNjdEqp4LJ5fqycUBm9ayCKSeeskgMKR"), []byte("1JRNjdEqp4LJ5fqycUBm9ayCKSeeskgMKR"),
[]byte("12evczYyX9ZKPYvwSEvRkRyTjpSrJuLudg"), []byte("12evczYyX9ZKPYvwSEvRkRyTjpSrJuLudg"),
} }
total = 10000 * types.Coin total = 10000 * types.Coin
totalToken = 100000 * types.Coin totalToken = 100000 * types.Coin
) )
...@@ -96,7 +97,7 @@ func initEnv() *execEnv { ...@@ -96,7 +97,7 @@ func initEnv() *execEnv {
accA.SetDB(stateDB) accA.SetDB(stateDB)
accA.SaveExecAccount(execAddr, &accountA) accA.SaveExecAccount(execAddr, &accountA)
manageKeySet("issuance-manage", accountA.Addr, stateDB) manageKeySet("issuance-manage", accountA.Addr, stateDB)
tokenAccA,_ := account.NewAccountDB(cfg, tokenE.GetName(), pkt.CCNYTokenName, stateDB) tokenAccA, _ := account.NewAccountDB(cfg, tokenE.GetName(), pkt.CCNYTokenName, stateDB)
tokenAccA.SaveExecAccount(execAddr, &accountAToken) tokenAccA.SaveExecAccount(execAddr, &accountAToken)
accB := account.NewCoinsAccount(cfg) accB := account.NewCoinsAccount(cfg)
...@@ -110,14 +111,14 @@ func initEnv() *execEnv { ...@@ -110,14 +111,14 @@ func initEnv() *execEnv {
manageKeySet("issuance-guarantor", accountC.Addr, stateDB) manageKeySet("issuance-guarantor", accountC.Addr, stateDB)
return &execEnv{ return &execEnv{
blockTime:time.Now().Unix(), blockTime: time.Now().Unix(),
blockHeight:cfg.GetDappFork(pkt.IssuanceX, "Enable"), blockHeight: cfg.GetDappFork(pkt.IssuanceX, "Enable"),
difficulty:1539918074, difficulty: 1539918074,
kvdb:kvdb, kvdb: kvdb,
api: api, api: api,
db: stateDB, db: stateDB,
execAddr: execAddr, execAddr: execAddr,
cfg: cfg, cfg: cfg,
} }
} }
...@@ -126,10 +127,10 @@ func TestIssuance(t *testing.T) { ...@@ -126,10 +127,10 @@ func TestIssuance(t *testing.T) {
// issuance create // issuance create
p1 := &pkt.IssuanceCreateTx{ p1 := &pkt.IssuanceCreateTx{
TotalBalance: 1000, TotalBalance: 1000,
DebtCeiling: 100, DebtCeiling: 100,
LiquidationRatio: 0.25, LiquidationRatio: 0.25,
Period: 5, Period: 5,
} }
createTx, err := pkt.CreateRawIssuanceCreateTx(env.cfg, p1) createTx, err := pkt.CreateRawIssuanceCreateTx(env.cfg, p1)
if err != nil { if err != nil {
...@@ -163,21 +164,20 @@ func TestIssuance(t *testing.T) { ...@@ -163,21 +164,20 @@ func TestIssuance(t *testing.T) {
} }
issuanceID := createTx.Hash() issuanceID := createTx.Hash()
// query issuance by id // query issuance by id
res, err := exec.Query("IssuanceInfoByID", types.Encode(&pkt.ReqIssuanceInfo{IssuanceId: common.ToHex(issuanceID),})) res, err := exec.Query("IssuanceInfoByID", types.Encode(&pkt.ReqIssuanceInfo{IssuanceId: common.ToHex(issuanceID)}))
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
// query issuance by status // query issuance by status
res, err = exec.Query("IssuanceByStatus", types.Encode(&pkt.ReqIssuanceByStatus{Status:1})) res, err = exec.Query("IssuanceByStatus", types.Encode(&pkt.ReqIssuanceByStatus{Status: 1}))
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
// query issuances by ids // query issuances by ids
var issuanceIDsS []string var issuanceIDsS []string
issuanceIDsS = append(issuanceIDsS, common.ToHex(issuanceID)) issuanceIDsS = append(issuanceIDsS, common.ToHex(issuanceID))
res, err = exec.Query("IssuanceInfoByIDs", types.Encode(&pkt.ReqIssuanceInfos{IssuanceIds:issuanceIDsS})) res, err = exec.Query("IssuanceInfoByIDs", types.Encode(&pkt.ReqIssuanceInfos{IssuanceIds: issuanceIDsS}))
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
// issuance price // issuance price
p2 := &pkt.IssuanceFeedTx{} p2 := &pkt.IssuanceFeedTx{}
p2.Price = append(p2.Price, 1) p2.Price = append(p2.Price, 1)
...@@ -212,7 +212,6 @@ func TestIssuance(t *testing.T) { ...@@ -212,7 +212,6 @@ func TestIssuance(t *testing.T) {
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
// issuance manage // issuance manage
p3 := &pkt.IssuanceManageTx{} p3 := &pkt.IssuanceManageTx{}
p3.Addr = append(p3.Addr, string(Nodes[1])) p3.Addr = append(p3.Addr, string(Nodes[1]))
...@@ -242,11 +241,10 @@ func TestIssuance(t *testing.T) { ...@@ -242,11 +241,10 @@ func TestIssuance(t *testing.T) {
env.kvdb.Set(kv.Key, kv.Value) env.kvdb.Set(kv.Key, kv.Value)
} }
// issuance debt // issuance debt
p4 := &pkt.IssuanceDebtTx{ p4 := &pkt.IssuanceDebtTx{
IssuanceID: common.ToHex(issuanceID), IssuanceID: common.ToHex(issuanceID),
Value: 100, Value: 100,
} }
createTx, err = pkt.CreateRawIssuanceDebtTx(env.cfg, p4) createTx, err = pkt.CreateRawIssuanceDebtTx(env.cfg, p4)
if err != nil { if err != nil {
...@@ -281,20 +279,19 @@ func TestIssuance(t *testing.T) { ...@@ -281,20 +279,19 @@ func TestIssuance(t *testing.T) {
assert.NotNil(t, res) assert.NotNil(t, res)
// query issuance by status // query issuance by status
res, err = exec.Query("IssuanceRecordsByStatus", res, err = exec.Query("IssuanceRecordsByStatus",
types.Encode(&pkt.ReqIssuanceRecordsByStatus{IssuanceId:common.ToHex(issuanceID), Status:1})) types.Encode(&pkt.ReqIssuanceRecordsByStatus{IssuanceId: common.ToHex(issuanceID), Status: 1}))
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
// query issuance by addr // query issuance by addr
res, err = exec.Query("IssuanceRecordsByAddr", res, err = exec.Query("IssuanceRecordsByAddr",
types.Encode(&pkt.ReqIssuanceRecordsByAddr{IssuanceId:common.ToHex(issuanceID),Addr: string(Nodes[1]), Status:1})) types.Encode(&pkt.ReqIssuanceRecordsByAddr{IssuanceId: common.ToHex(issuanceID), Addr: string(Nodes[1]), Status: 1}))
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
// issuance repay // issuance repay
p5 := &pkt.IssuanceRepayTx{ p5 := &pkt.IssuanceRepayTx{
IssuanceID: common.ToHex(issuanceID), IssuanceID: common.ToHex(issuanceID),
DebtID: common.ToHex(debtID), DebtID: common.ToHex(debtID),
} }
createTx, err = pkt.CreateRawIssuanceRepayTx(env.cfg, p5) createTx, err = pkt.CreateRawIssuanceRepayTx(env.cfg, p5)
if err != nil { if err != nil {
...@@ -323,20 +320,19 @@ func TestIssuance(t *testing.T) { ...@@ -323,20 +320,19 @@ func TestIssuance(t *testing.T) {
} }
// query issuance by status // query issuance by status
res, err = exec.Query("IssuanceRecordsByStatus", res, err = exec.Query("IssuanceRecordsByStatus",
types.Encode(&pkt.ReqIssuanceRecordsByStatus{IssuanceId:common.ToHex(issuanceID), Status:6})) types.Encode(&pkt.ReqIssuanceRecordsByStatus{IssuanceId: common.ToHex(issuanceID), Status: 6}))
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
// query issuance by addr // query issuance by addr
res, err = exec.Query("IssuanceRecordsByAddr", res, err = exec.Query("IssuanceRecordsByAddr",
types.Encode(&pkt.ReqIssuanceRecordsByAddr{IssuanceId:common.ToHex(issuanceID),Addr: string(Nodes[1]), Status:6})) types.Encode(&pkt.ReqIssuanceRecordsByAddr{IssuanceId: common.ToHex(issuanceID), Addr: string(Nodes[1]), Status: 6}))
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
// issuance liquidate // issuance liquidate
p6 := &pkt.IssuanceDebtTx{ p6 := &pkt.IssuanceDebtTx{
IssuanceID: common.ToHex(issuanceID), IssuanceID: common.ToHex(issuanceID),
Value: 100, Value: 100,
} }
createTx, err = pkt.CreateRawIssuanceDebtTx(env.cfg, p6) createTx, err = pkt.CreateRawIssuanceDebtTx(env.cfg, p6)
if err != nil { if err != nil {
...@@ -394,14 +390,14 @@ func TestIssuance(t *testing.T) { ...@@ -394,14 +390,14 @@ func TestIssuance(t *testing.T) {
} }
// query issuance by status // query issuance by status
res, err = exec.Query("IssuanceRecordsByStatus", res, err = exec.Query("IssuanceRecordsByStatus",
types.Encode(&pkt.ReqIssuanceRecordsByStatus{IssuanceId:common.ToHex(issuanceID), Status:3})) types.Encode(&pkt.ReqIssuanceRecordsByStatus{IssuanceId: common.ToHex(issuanceID), Status: 3}))
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
// expire liquidate // expire liquidate
p8 := &pkt.IssuanceDebtTx{ p8 := &pkt.IssuanceDebtTx{
IssuanceID: common.ToHex(issuanceID), IssuanceID: common.ToHex(issuanceID),
Value: 100, Value: 100,
} }
createTx, err = pkt.CreateRawIssuanceDebtTx(env.cfg, p8) createTx, err = pkt.CreateRawIssuanceDebtTx(env.cfg, p8)
if err != nil { if err != nil {
...@@ -459,11 +455,10 @@ func TestIssuance(t *testing.T) { ...@@ -459,11 +455,10 @@ func TestIssuance(t *testing.T) {
} }
// query issuance by status // query issuance by status
res, err = exec.Query("IssuanceRecordsByStatus", res, err = exec.Query("IssuanceRecordsByStatus",
types.Encode(&pkt.ReqIssuanceRecordsByStatus{IssuanceId:common.ToHex(issuanceID), Status:5})) types.Encode(&pkt.ReqIssuanceRecordsByStatus{IssuanceId: common.ToHex(issuanceID), Status: 5}))
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
// issuance close // issuance close
p10 := &pkt.IssuanceCloseTx{ p10 := &pkt.IssuanceCloseTx{
IssuanceID: common.ToHex(issuanceID), IssuanceID: common.ToHex(issuanceID),
...@@ -494,7 +489,7 @@ func TestIssuance(t *testing.T) { ...@@ -494,7 +489,7 @@ func TestIssuance(t *testing.T) {
env.kvdb.Set(kv.Key, kv.Value) env.kvdb.Set(kv.Key, kv.Value)
} }
// query issuance by status // query issuance by status
res, err = exec.Query("IssuanceByStatus", types.Encode(&pkt.ReqIssuanceByStatus{Status:2})) res, err = exec.Query("IssuanceByStatus", types.Encode(&pkt.ReqIssuanceByStatus{Status: 2}))
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, res) assert.NotNil(t, res)
} }
......
...@@ -6,6 +6,8 @@ package executor ...@@ -6,6 +6,8 @@ package executor
import ( import (
"fmt" "fmt"
"math"
"github.com/33cn/chain33/account" "github.com/33cn/chain33/account"
"github.com/33cn/chain33/common" "github.com/33cn/chain33/common"
dbm "github.com/33cn/chain33/common/db" dbm "github.com/33cn/chain33/common/db"
...@@ -13,7 +15,6 @@ import ( ...@@ -13,7 +15,6 @@ import (
"github.com/33cn/chain33/types" "github.com/33cn/chain33/types"
pty "github.com/33cn/plugin/plugin/dapp/issuance/types" pty "github.com/33cn/plugin/plugin/dapp/issuance/types"
tokenE "github.com/33cn/plugin/plugin/dapp/token/executor" tokenE "github.com/33cn/plugin/plugin/dapp/token/executor"
"math"
) )
// List control // List control
...@@ -25,12 +26,12 @@ const ( ...@@ -25,12 +26,12 @@ const (
) )
const ( const (
Coin = types.Coin // 1e8 Coin = types.Coin // 1e8
DefaultDebtCeiling = 100000 * Coin // 默认借贷限额 DefaultDebtCeiling = 100000 * Coin // 默认借贷限额
DefaultLiquidationRatio = 0.25 // 默认质押比 DefaultLiquidationRatio = 0.25 // 默认质押比
DefaultPeriod = 3600 * 24 * 365 // 默认合约限期 DefaultPeriod = 3600 * 24 * 365 // 默认合约限期
PriceWarningRate = 1.3 // 价格提前预警率 PriceWarningRate = 1.3 // 价格提前预警率
ExpireWarningTime = 3600 * 24 * 10 // 提前10天超时预警 ExpireWarningTime = 3600 * 24 * 10 // 提前10天超时预警
) )
func getManageKey(key string, db dbm.KV) ([]byte, error) { func getManageKey(key string, db dbm.KV) ([]byte, error) {
...@@ -154,8 +155,8 @@ func PriceKey() (key []byte) { ...@@ -154,8 +155,8 @@ func PriceKey() (key []byte) {
// Action struct // Action struct
type Action struct { type Action struct {
coinsAccount *account.DB // bty账户 coinsAccount *account.DB // bty账户
tokenAccount *account.DB // ccny账户 tokenAccount *account.DB // ccny账户
db dbm.KV db dbm.KV
localDB dbm.Lister localDB dbm.Lister
txhash []byte txhash []byte
...@@ -165,7 +166,7 @@ type Action struct { ...@@ -165,7 +166,7 @@ type Action struct {
execaddr string execaddr string
difficulty uint64 difficulty uint64
index int index int
Issuance *Issuance Issuance *Issuance
} }
// NewIssuanceAction generate New Action // NewIssuanceAction generate New Action
...@@ -180,7 +181,7 @@ func NewIssuanceAction(c *Issuance, tx *types.Transaction, index int) *Action { ...@@ -180,7 +181,7 @@ func NewIssuanceAction(c *Issuance, tx *types.Transaction, index int) *Action {
} }
return &Action{ return &Action{
coinsAccount: c.GetCoinsAccount(), tokenAccount:tokenDb, db: c.GetStateDB(), localDB:c.GetLocalDB(), coinsAccount: c.GetCoinsAccount(), tokenAccount: tokenDb, db: c.GetStateDB(), localDB: c.GetLocalDB(),
txhash: hash, fromaddr: fromaddr, blocktime: c.GetBlockTime(), height: c.GetHeight(), txhash: hash, fromaddr: fromaddr, blocktime: c.GetBlockTime(), height: c.GetHeight(),
execaddr: dapp.ExecAddress(string(tx.Execer)), difficulty: c.GetDifficulty(), index: index, Issuance: c} execaddr: dapp.ExecAddress(string(tx.Execer)), difficulty: c.GetDifficulty(), index: index, Issuance: c}
} }
...@@ -339,7 +340,7 @@ func (action *Action) IssuanceManage(manage *pty.IssuanceManage) (*types.Receipt ...@@ -339,7 +340,7 @@ func (action *Action) IssuanceManage(manage *pty.IssuanceManage) (*types.Receipt
value := types.Encode(&item) value := types.Encode(&item)
action.db.Set(AddrKey(), value) action.db.Set(AddrKey(), value)
kv = append(kv, &types.KeyValue{Key:AddrKey(), Value: value}) kv = append(kv, &types.KeyValue{Key: AddrKey(), Value: value})
} else { } else {
err = types.Decode(data, &item) err = types.Decode(data, &item)
if err != nil { if err != nil {
...@@ -349,7 +350,7 @@ func (action *Action) IssuanceManage(manage *pty.IssuanceManage) (*types.Receipt ...@@ -349,7 +350,7 @@ func (action *Action) IssuanceManage(manage *pty.IssuanceManage) (*types.Receipt
item.GetArr().Value = append(item.GetArr().Value, manage.SuperAddrs...) item.GetArr().Value = append(item.GetArr().Value, manage.SuperAddrs...)
value := types.Encode(&item) value := types.Encode(&item)
action.db.Set(AddrKey(), value) action.db.Set(AddrKey(), value)
kv = append(kv, &types.KeyValue{Key:AddrKey(), Value: value}) kv = append(kv, &types.KeyValue{Key: AddrKey(), Value: value})
} }
receipt = &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: nil} receipt = &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: nil}
...@@ -388,11 +389,11 @@ func (action *Action) IssuanceCreate(create *pty.IssuanceCreate) (*types.Receipt ...@@ -388,11 +389,11 @@ func (action *Action) IssuanceCreate(create *pty.IssuanceCreate) (*types.Receipt
// 参数检查 // 参数检查
if create.GetTotalBalance() <= 0 { if create.GetTotalBalance() <= 0 {
clog.Error("IssuanceCreate", "addr", action.fromaddr, "execaddr", action.execaddr, "total balance", create.GetTotalBalance(), "error", types.ErrAmount) clog.Error("IssuanceCreate", "addr", action.fromaddr, "execaddr", action.execaddr, "total balance", create.GetTotalBalance(), "error", types.ErrAmount)
return nil, types.ErrAmount return nil, types.ErrAmount
} }
if create.DebtCeiling < 0 || create.LiquidationRatio < 0 || create.Period < 0 { if create.DebtCeiling < 0 || create.LiquidationRatio < 0 || create.Period < 0 {
clog.Error("IssuanceCreate", "addr", action.fromaddr, "execaddr", action.execaddr, "error", types.ErrInvalidParam) clog.Error("IssuanceCreate", "addr", action.fromaddr, "execaddr", action.execaddr, "error", types.ErrInvalidParam)
return nil, types.ErrInvalidParam return nil, types.ErrInvalidParam
} }
// 检查ccny余额 // 检查ccny余额
...@@ -456,14 +457,14 @@ func (action *Action) IssuanceCreate(create *pty.IssuanceCreate) (*types.Receipt ...@@ -456,14 +457,14 @@ func (action *Action) IssuanceCreate(create *pty.IssuanceCreate) (*types.Receipt
} }
// 根据最近抵押物价格计算需要冻结的BTY数量 // 根据最近抵押物价格计算需要冻结的BTY数量
func getBtyNumToFrozen(value int64, price float64, ratio float64) (int64,error) { func getBtyNumToFrozen(value int64, price float64, ratio float64) (int64, error) {
if price == 0 { if price == 0 {
clog.Error("Bty price should greate to 0") clog.Error("Bty price should greate to 0")
return 0, pty.ErrPriceInvalid return 0, pty.ErrPriceInvalid
} }
valueReal := float64(value)/1e8 valueReal := float64(value) / 1e8
btyValue := valueReal/(price * ratio) btyValue := valueReal / (price * ratio)
return int64(math.Trunc((btyValue+0.0000001)*1e4)) * 1e4, nil return int64(math.Trunc((btyValue+0.0000001)*1e4)) * 1e4, nil
} }
...@@ -537,7 +538,7 @@ func (action *Action) IssuanceDebt(debt *pty.IssuanceDebt) (*types.Receipt, erro ...@@ -537,7 +538,7 @@ func (action *Action) IssuanceDebt(debt *pty.IssuanceDebt) (*types.Receipt, erro
// 借贷金额检查 // 借贷金额检查
if debt.GetValue() <= 0 { if debt.GetValue() <= 0 {
clog.Error("IssuanceDebt", "CollID", issu.IssuanceId, "addr", action.fromaddr, "execaddr", action.execaddr, "debt value", debt.GetValue(), "error", types.ErrInvalidParam) clog.Error("IssuanceDebt", "CollID", issu.IssuanceId, "addr", action.fromaddr, "execaddr", action.execaddr, "debt value", debt.GetValue(), "error", types.ErrInvalidParam)
return nil, types.ErrInvalidParam return nil, types.ErrInvalidParam
} }
// 借贷金额不超过个人限额 // 借贷金额不超过个人限额
...@@ -735,7 +736,7 @@ func (action *Action) systemLiquidation(issu *pty.Issuance, price float64) (*typ ...@@ -735,7 +736,7 @@ func (action *Action) systemLiquidation(issu *pty.Issuance, price float64) (*typ
var kv []*types.KeyValue var kv []*types.KeyValue
for index, debtRecord := range issu.DebtRecords { for index, debtRecord := range issu.DebtRecords {
if debtRecord.LiquidationPrice * PriceWarningRate < price { if debtRecord.LiquidationPrice*PriceWarningRate < price {
if debtRecord.Status == pty.IssuanceUserStatusWarning { if debtRecord.Status == pty.IssuanceUserStatusWarning {
debtRecord.PreStatus = debtRecord.Status debtRecord.PreStatus = debtRecord.Status
debtRecord.Status = pty.IssuanceUserStatusCreate debtRecord.Status = pty.IssuanceUserStatusCreate
...@@ -797,7 +798,7 @@ func (action *Action) expireLiquidation(issu *pty.Issuance) (*types.Receipt, err ...@@ -797,7 +798,7 @@ func (action *Action) expireLiquidation(issu *pty.Issuance) (*types.Receipt, err
var kv []*types.KeyValue var kv []*types.KeyValue
for index, debtRecord := range issu.DebtRecords { for index, debtRecord := range issu.DebtRecords {
if debtRecord.ExpireTime - ExpireWarningTime > action.blocktime { if debtRecord.ExpireTime-ExpireWarningTime > action.blocktime {
continue continue
} }
...@@ -862,7 +863,7 @@ func pricePolicy(feed *pty.IssuanceFeed) float64 { ...@@ -862,7 +863,7 @@ func pricePolicy(feed *pty.IssuanceFeed) float64 {
return 0 return 0
} }
for i, price := range feed.Price { for i, price := range feed.Price {
totalPrice += price * (float64(feed.Volume[i])/float64(totalVolume)) totalPrice += price * (float64(feed.Volume[i]) / float64(totalVolume))
} }
return totalPrice return totalPrice
...@@ -903,7 +904,7 @@ func (action *Action) IssuanceFeed(feed *pty.IssuanceFeed) (*types.Receipt, erro ...@@ -903,7 +904,7 @@ func (action *Action) IssuanceFeed(feed *pty.IssuanceFeed) (*types.Receipt, erro
} }
// 超时清算判断 // 超时清算判断
if issu.LatestExpireTime - ExpireWarningTime <= action.blocktime { if issu.LatestExpireTime-ExpireWarningTime <= action.blocktime {
receipt, err := action.expireLiquidation(issu) receipt, err := action.expireLiquidation(issu)
if err != nil { if err != nil {
clog.Error("IssuancePriceFeed", "Issuance ID", issu.IssuanceId, "expire liquidation error", err) clog.Error("IssuancePriceFeed", "Issuance ID", issu.IssuanceId, "expire liquidation error", err)
......
...@@ -44,4 +44,4 @@ func calcIssuanceRecordStatusPrefix(status string) []byte { ...@@ -44,4 +44,4 @@ func calcIssuanceRecordStatusPrefix(status string) []byte {
func calcIssuanceRecordStatusKey(status int32, index int64) []byte { func calcIssuanceRecordStatusKey(status int32, index int64) []byte {
key := fmt.Sprintf("LODB-issuance-record-status:%d:%018d", status, index) key := fmt.Sprintf("LODB-issuance-record-status:%d:%018d", status, index)
return []byte(key) return []byte(key)
} }
\ No newline at end of file
...@@ -10,46 +10,46 @@ import ( ...@@ -10,46 +10,46 @@ import (
) )
func (c *Issuance) Query_IssuanceInfoByID(req *pty.ReqIssuanceInfo) (types.Message, error) { func (c *Issuance) Query_IssuanceInfoByID(req *pty.ReqIssuanceInfo) (types.Message, error) {
issu,err := queryIssuanceByID(c.GetStateDB(), req.IssuanceId) issu, err := queryIssuanceByID(c.GetStateDB(), req.IssuanceId)
if err != nil { if err != nil {
clog.Error("Query_IssuanceInfoByID", "id", req.IssuanceId, "error", err) clog.Error("Query_IssuanceInfoByID", "id", req.IssuanceId, "error", err)
return nil, err return nil, err
} }
return &pty.RepIssuanceCurrentInfo{ return &pty.RepIssuanceCurrentInfo{
Status: issu.Status, Status: issu.Status,
TotalBalance: issu.TotalBalance, TotalBalance: issu.TotalBalance,
DebtCeiling: issu.DebtCeiling, DebtCeiling: issu.DebtCeiling,
LiquidationRatio: issu.LiquidationRatio, LiquidationRatio: issu.LiquidationRatio,
Balance: issu.Balance, Balance: issu.Balance,
CollateralValue: issu.CollateralValue, CollateralValue: issu.CollateralValue,
DebtValue: issu.DebtValue, DebtValue: issu.DebtValue,
Period: issu.Period, Period: issu.Period,
IssuId: issu.IssuanceId, IssuId: issu.IssuanceId,
CreateTime: issu.CreateTime, CreateTime: issu.CreateTime,
}, nil }, nil
} }
func (c *Issuance) Query_IssuanceInfoByIDs(req *pty.ReqIssuanceInfos) (types.Message, error) { func (c *Issuance) Query_IssuanceInfoByIDs(req *pty.ReqIssuanceInfos) (types.Message, error) {
infos := &pty.RepIssuanceCurrentInfos{} infos := &pty.RepIssuanceCurrentInfos{}
for _, id := range req.IssuanceIds { for _, id := range req.IssuanceIds {
issu,err := queryIssuanceByID(c.GetStateDB(), id) issu, err := queryIssuanceByID(c.GetStateDB(), id)
if err != nil { if err != nil {
clog.Error("Query_IssuanceInfoByID", "id", id, "error", err) clog.Error("Query_IssuanceInfoByID", "id", id, "error", err)
return nil, err return nil, err
} }
infos.Infos = append(infos.Infos, &pty.RepIssuanceCurrentInfo{ infos.Infos = append(infos.Infos, &pty.RepIssuanceCurrentInfo{
Status: issu.Status, Status: issu.Status,
TotalBalance: issu.TotalBalance, TotalBalance: issu.TotalBalance,
DebtCeiling: issu.DebtCeiling, DebtCeiling: issu.DebtCeiling,
LiquidationRatio: issu.LiquidationRatio, LiquidationRatio: issu.LiquidationRatio,
Balance: issu.Balance, Balance: issu.Balance,
CollateralValue: issu.CollateralValue, CollateralValue: issu.CollateralValue,
DebtValue: issu.DebtValue, DebtValue: issu.DebtValue,
Period: issu.Period, Period: issu.Period,
IssuId: issu.IssuanceId, IssuId: issu.IssuanceId,
CreateTime: issu.CreateTime, CreateTime: issu.CreateTime,
}) })
} }
...@@ -91,7 +91,7 @@ func (c *Issuance) Query_IssuanceRecordsByAddr(req *pty.ReqIssuanceRecordsByAddr ...@@ -91,7 +91,7 @@ func (c *Issuance) Query_IssuanceRecordsByAddr(req *pty.ReqIssuanceRecordsByAddr
if req.Status == 0 { if req.Status == 0 {
ret.Records = records ret.Records = records
} else { } else {
for _,record := range records { for _, record := range records {
if record.Status == req.Status { if record.Status == req.Status {
ret.Records = append(ret.Records, record) ret.Records = append(ret.Records, record)
} }
...@@ -120,5 +120,5 @@ func (c *Issuance) Query_IssuancePrice(req *pty.ReqIssuanceRecordsByStatus) (typ ...@@ -120,5 +120,5 @@ func (c *Issuance) Query_IssuancePrice(req *pty.ReqIssuanceRecordsByStatus) (typ
return nil, err return nil, err
} }
return &pty.RepIssuancePrice{Price:price}, nil return &pty.RepIssuancePrice{Price: price}, nil
} }
\ No newline at end of file
...@@ -54,8 +54,8 @@ func (issuance *IssuanceType) GetName() string { ...@@ -54,8 +54,8 @@ func (issuance *IssuanceType) GetName() string {
func (issuance *IssuanceType) GetLogMap() map[int64]*types.LogInfo { func (issuance *IssuanceType) GetLogMap() map[int64]*types.LogInfo {
return map[int64]*types.LogInfo{ return map[int64]*types.LogInfo{
TyLogIssuanceCreate: {Ty: reflect.TypeOf(ReceiptIssuance{}), Name: "LogIssuanceCreate"}, TyLogIssuanceCreate: {Ty: reflect.TypeOf(ReceiptIssuance{}), Name: "LogIssuanceCreate"},
TyLogIssuanceDebt: {Ty: reflect.TypeOf(ReceiptIssuance{}), Name: "LogIssuanceDebt"}, TyLogIssuanceDebt: {Ty: reflect.TypeOf(ReceiptIssuance{}), Name: "LogIssuanceDebt"},
TyLogIssuanceRepay: {Ty: reflect.TypeOf(ReceiptIssuance{}), Name: "LogIssuanceRepay"}, TyLogIssuanceRepay: {Ty: reflect.TypeOf(ReceiptIssuance{}), Name: "LogIssuanceRepay"},
TyLogIssuanceFeed: {Ty: reflect.TypeOf(ReceiptIssuance{}), Name: "LogIssuanceFeed"}, TyLogIssuanceFeed: {Ty: reflect.TypeOf(ReceiptIssuance{}), Name: "LogIssuanceFeed"},
TyLogIssuanceClose: {Ty: reflect.TypeOf(ReceiptIssuance{}), Name: "LogIssuanceClose"}, TyLogIssuanceClose: {Ty: reflect.TypeOf(ReceiptIssuance{}), Name: "LogIssuanceClose"},
} }
...@@ -128,7 +128,7 @@ func (issuance IssuanceType) CreateTx(action string, message json.RawMessage) (* ...@@ -128,7 +128,7 @@ func (issuance IssuanceType) CreateTx(action string, message json.RawMessage) (*
func (issuance IssuanceType) GetTypeMap() map[string]int32 { func (issuance IssuanceType) GetTypeMap() map[string]int32 {
return map[string]int32{ return map[string]int32{
"Create": IssuanceActionCreate, "Create": IssuanceActionCreate,
"Debt": IssuanceActionDebt, "Debt": IssuanceActionDebt,
"Repay": IssuanceActionRepay, "Repay": IssuanceActionRepay,
"Feed": IssuanceActionFeed, "Feed": IssuanceActionFeed,
"Close": IssuanceActionClose, "Close": IssuanceActionClose,
...@@ -144,10 +144,10 @@ func CreateRawIssuanceCreateTx(cfg *types.Chain33Config, parm *IssuanceCreateTx) ...@@ -144,10 +144,10 @@ func CreateRawIssuanceCreateTx(cfg *types.Chain33Config, parm *IssuanceCreateTx)
} }
v := &IssuanceCreate{ v := &IssuanceCreate{
TotalBalance: int64(math.Trunc((parm.TotalBalance+0.0000001)*1e4)) * 1e4, TotalBalance: int64(math.Trunc((parm.TotalBalance+0.0000001)*1e4)) * 1e4,
DebtCeiling: int64(math.Trunc((parm.DebtCeiling+0.0000001)*1e4)) * 1e4, DebtCeiling: int64(math.Trunc((parm.DebtCeiling+0.0000001)*1e4)) * 1e4,
LiquidationRatio: parm.LiquidationRatio, LiquidationRatio: parm.LiquidationRatio,
Period: parm.Period, Period: parm.Period,
} }
create := &IssuanceAction{ create := &IssuanceAction{
Ty: IssuanceActionCreate, Ty: IssuanceActionCreate,
...@@ -176,7 +176,7 @@ func CreateRawIssuanceDebtTx(cfg *types.Chain33Config, parm *IssuanceDebtTx) (*t ...@@ -176,7 +176,7 @@ func CreateRawIssuanceDebtTx(cfg *types.Chain33Config, parm *IssuanceDebtTx) (*t
v := &IssuanceDebt{ v := &IssuanceDebt{
IssuanceId: parm.IssuanceID, IssuanceId: parm.IssuanceID,
Value: int64(math.Trunc((parm.Value+0.0000001)*1e4)) * 1e4, Value: int64(math.Trunc((parm.Value+0.0000001)*1e4)) * 1e4,
} }
debt := &IssuanceAction{ debt := &IssuanceAction{
Ty: IssuanceActionDebt, Ty: IssuanceActionDebt,
...@@ -205,7 +205,7 @@ func CreateRawIssuanceRepayTx(cfg *types.Chain33Config, parm *IssuanceRepayTx) ( ...@@ -205,7 +205,7 @@ func CreateRawIssuanceRepayTx(cfg *types.Chain33Config, parm *IssuanceRepayTx) (
v := &IssuanceRepay{ v := &IssuanceRepay{
IssuanceId: parm.IssuanceID, IssuanceId: parm.IssuanceID,
DebtId: parm.DebtID, DebtId: parm.DebtID,
} }
repay := &IssuanceAction{ repay := &IssuanceAction{
Ty: IssuanceActionRepay, Ty: IssuanceActionRepay,
...@@ -233,7 +233,7 @@ func CreateRawIssuanceFeedTx(cfg *types.Chain33Config, parm *IssuanceFeedTx) (*t ...@@ -233,7 +233,7 @@ func CreateRawIssuanceFeedTx(cfg *types.Chain33Config, parm *IssuanceFeedTx) (*t
} }
v := &IssuanceFeed{ v := &IssuanceFeed{
Price: parm.Price, Price: parm.Price,
Volume: parm.Volume, Volume: parm.Volume,
} }
feed := &IssuanceAction{ feed := &IssuanceAction{
...@@ -290,7 +290,7 @@ func CreateRawIssuanceManageTx(cfg *types.Chain33Config, parm *IssuanceManageTx) ...@@ -290,7 +290,7 @@ func CreateRawIssuanceManageTx(cfg *types.Chain33Config, parm *IssuanceManageTx)
return nil, types.ErrInvalidParam return nil, types.ErrInvalidParam
} }
v := &IssuanceManage{SuperAddrs:parm.Addr} v := &IssuanceManage{SuperAddrs: parm.Addr}
manage := &IssuanceAction{ manage := &IssuanceAction{
Ty: IssuanceActionManage, Ty: IssuanceActionManage,
...@@ -309,4 +309,4 @@ func CreateRawIssuanceManageTx(cfg *types.Chain33Config, parm *IssuanceManageTx) ...@@ -309,4 +309,4 @@ func CreateRawIssuanceManageTx(cfg *types.Chain33Config, parm *IssuanceManageTx)
return nil, err return nil, err
} }
return tx, nil return tx, nil
} }
\ No newline at end of file
This diff is collapsed.
...@@ -6,42 +6,42 @@ package types ...@@ -6,42 +6,42 @@ package types
// IssuanceCreateTx for construction // IssuanceCreateTx for construction
type IssuanceCreateTx struct { type IssuanceCreateTx struct {
DebtCeiling float64 `json:"debtCeiling"` DebtCeiling float64 `json:"debtCeiling"`
LiquidationRatio float64 `json:"liquidationRatio"` LiquidationRatio float64 `json:"liquidationRatio"`
Period int64 `json:"period"` Period int64 `json:"period"`
TotalBalance float64 `json:"totalBalance"` TotalBalance float64 `json:"totalBalance"`
Fee int64 `json:"fee"` Fee int64 `json:"fee"`
} }
// IssuanceDebtTx for construction // IssuanceDebtTx for construction
type IssuanceDebtTx struct { type IssuanceDebtTx struct {
IssuanceID string `json:"issuanceId"` IssuanceID string `json:"issuanceId"`
Value float64 `json:"value"` Value float64 `json:"value"`
Fee int64 `json:"fee"` Fee int64 `json:"fee"`
} }
// IssuanceRepayTx for construction // IssuanceRepayTx for construction
type IssuanceRepayTx struct { type IssuanceRepayTx struct {
IssuanceID string `json:"issuanceId"` IssuanceID string `json:"issuanceId"`
DebtID string `json:"debtId"` DebtID string `json:"debtId"`
Fee int64 `json:"fee"` Fee int64 `json:"fee"`
} }
// IssuanceFeedTx for construction // IssuanceFeedTx for construction
type IssuanceFeedTx struct { type IssuanceFeedTx struct {
Price []float64 `json:"price"` Price []float64 `json:"price"`
Volume []int64 `json:"volume"` Volume []int64 `json:"volume"`
Fee int64 `json:"fee"` Fee int64 `json:"fee"`
} }
// IssuanceCloseTx for construction // IssuanceCloseTx for construction
type IssuanceCloseTx struct { type IssuanceCloseTx struct {
IssuanceID string `json:"issuanceId"` IssuanceID string `json:"issuanceId"`
Fee int64 `json:"fee"` Fee int64 `json:"fee"`
} }
// IssuanceManageTx for construction // IssuanceManageTx for construction
type IssuanceManageTx struct { type IssuanceManageTx struct {
Addr []string `json:"addr"` Addr []string `json:"addr"`
Fee int64 `json:"fee"` Fee int64 `json:"fee"`
} }
...@@ -14,17 +14,17 @@ const ( ...@@ -14,17 +14,17 @@ const (
IssuanceActionManage // 借贷管理 IssuanceActionManage // 借贷管理
//log for Issuance //log for Issuance
TyLogIssuanceCreate = 741 TyLogIssuanceCreate = 741
TyLogIssuanceDebt = 742 TyLogIssuanceDebt = 742
TyLogIssuanceRepay = 743 TyLogIssuanceRepay = 743
TyLogIssuanceFeed = 745 TyLogIssuanceFeed = 745
TyLogIssuanceClose = 756 TyLogIssuanceClose = 756
) )
// Issuance name // Issuance name
const ( const (
IssuanceX = "issuance" IssuanceX = "issuance"
CCNYTokenName = "CCNY" CCNYTokenName = "CCNY"
IssuancePreLiquidationRatio = 1.1 //TODO 预清算比例,抵押物价值跌到借出ccny价值110%的时候开始清算 IssuancePreLiquidationRatio = 1.1 //TODO 预清算比例,抵押物价值跌到借出ccny价值110%的时候开始清算
) )
...@@ -47,4 +47,4 @@ const ( ...@@ -47,4 +47,4 @@ const (
PriceFeedKey = "issuance-price-feed" PriceFeedKey = "issuance-price-feed"
GuarantorKey = "issuance-guarantor" GuarantorKey = "issuance-guarantor"
ManageKey = "issuance-manage" ManageKey = "issuance-manage"
) )
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment