Unverified Commit a717a020 authored by vipwzw's avatar vipwzw Committed by GitHub

Merge pull request #736 from jpeng-go/master

#627 去中心化发行借贷合约
parents 1a47e08d d4c38318
......@@ -312,6 +312,12 @@ Enable=0
[fork.sub.jsvm]
Enable=0
[fork.sub.issuance]
Enable=0
[fork.sub.collateralize]
Enable=0
#对已有的平行链如果不是从0开始同步数据,需要设置这个kvmvccmavl的对应平行链高度的fork,如果从0开始同步,statehash会跟以前mavl的不同
[fork.sub.store-kvmvccmavl]
ForkKvmvccmavl=0
......
all:
chmod +x ./build.sh
./build.sh $(OUT) $(FLAG)
\ No newline at end of file
#!/usr/bin/env bash
strpwd=$(pwd)
strcmd=${strpwd##*dapp/}
strapp=${strcmd%/cmd*}
OUT_TESTDIR="${1}/dapptest/$strapp"
mkdir -p "${OUT_TESTDIR}"
cp ./test/test-rpc.sh "${OUT_TESTDIR}"
#!/usr/bin/env bash
# shellcheck disable=SC2128
set -e
set -o pipefail
# shellcheck source=/dev/null
source ../dapp-test-common.sh
function main() {
echo "Collateralize cases has integrated in Issuance test"
}
chain33_debug_function main "$1"
This diff is collapsed.
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package executor
import (
log "github.com/33cn/chain33/common/log/log15"
drivers "github.com/33cn/chain33/system/dapp"
"github.com/33cn/chain33/types"
pty "github.com/33cn/plugin/plugin/dapp/collateralize/types"
)
var clog = log.New("module", "execs.collateralize")
var driverName = pty.CollateralizeX
func InitExecType() {
ety := types.LoadExecutorType(driverName)
ety.InitFuncList(types.ListMethod(&Collateralize{}))
}
// Init collateralize
func Init(name string, cfg *types.Chain33Config, sub []byte) {
driverName := GetName()
if name != driverName {
panic("system dapp can't be rename")
}
if sub != nil {
types.MustDecode(sub, &cfg)
}
drivers.Register(cfg, driverName, newCollateralize, cfg.GetDappFork(driverName, "Enable"))
InitExecType()
}
// GetName for Collateralize
func GetName() string {
return newCollateralize().GetName()
}
// Collateralize driver
type Collateralize struct {
drivers.DriverBase
}
func newCollateralize() drivers.Driver {
c := &Collateralize{}
c.SetChild(c)
c.SetExecutorType(types.LoadExecutorType(driverName))
return c
}
// GetDriverName for Collateralize
func (c *Collateralize) GetDriverName() string {
return pty.CollateralizeX
}
// CheckReceiptExecOk return true to check if receipt ty is ok
func (c *Collateralize) CheckReceiptExecOk() bool {
return true
}
// ExecutorOrder 设置localdb的EnableRead
func (c *Collateralize) ExecutorOrder() int64 {
cfg := c.GetAPI().GetConfig()
if cfg.IsFork(c.GetHeight(), "ForkLocalDBAccess") {
return drivers.ExecLocalSameTime
}
return c.DriverBase.ExecutorOrder()
}
This diff is collapsed.
This diff is collapsed.
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package executor
/*
waiting for update
*/
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package executor
import (
"github.com/33cn/chain33/types"
pty "github.com/33cn/plugin/plugin/dapp/collateralize/types"
)
// Exec_Create Action
func (c *Collateralize) Exec_Create(payload *pty.CollateralizeCreate, tx *types.Transaction, index int) (*types.Receipt, error) {
actiondb := NewCollateralizeAction(c, tx, index)
return actiondb.CollateralizeCreate(payload)
}
// Exec_Borrow Action
func (c *Collateralize) Exec_Borrow(payload *pty.CollateralizeBorrow, tx *types.Transaction, index int) (*types.Receipt, error) {
actiondb := NewCollateralizeAction(c, tx, index)
return actiondb.CollateralizeBorrow(payload)
}
// Exec_Repay Action
func (c *Collateralize) Exec_Repay(payload *pty.CollateralizeRepay, tx *types.Transaction, index int) (*types.Receipt, error) {
actiondb := NewCollateralizeAction(c, tx, index)
return actiondb.CollateralizeRepay(payload)
}
// Exec_Repay Action
func (c *Collateralize) Exec_Append(payload *pty.CollateralizeAppend, tx *types.Transaction, index int) (*types.Receipt, error) {
actiondb := NewCollateralizeAction(c, tx, index)
return actiondb.CollateralizeAppend(payload)
}
// Exec_Feed Action
func (c *Collateralize) Exec_Feed(payload *pty.CollateralizeFeed, tx *types.Transaction, index int) (*types.Receipt, error) {
actiondb := NewCollateralizeAction(c, tx, index)
return actiondb.CollateralizeFeed(payload)
}
// Exec_Retrieve Action
func (c *Collateralize) Exec_Retrieve(payload *pty.CollateralizeRetrieve, tx *types.Transaction, index int) (*types.Receipt, error) {
actiondb := NewCollateralizeAction(c, tx, index)
return actiondb.CollateralizeRetrieve(payload)
}
// Exec_Close Action
func (c *Collateralize) Exec_Manage(payload *pty.CollateralizeManage, tx *types.Transaction, index int) (*types.Receipt, error) {
actiondb := NewCollateralizeAction(c, tx, index)
return actiondb.CollateralizeManage(payload)
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package executor
import (
"github.com/33cn/chain33/types"
pty "github.com/33cn/plugin/plugin/dapp/collateralize/types"
)
func (c *Collateralize) execDelLocal(tx *types.Transaction, receiptData *types.ReceiptData) (*types.LocalDBSet, error) {
kvs, err := c.DelRollbackKV(tx, tx.Execer)
if err != nil {
return nil, err
}
dbSet := &types.LocalDBSet{}
dbSet.KV = append(dbSet.KV, kvs...)
return dbSet, nil
}
// ExecDelLocal_Create Action
func (c *Collateralize) ExecDelLocal_Create(payload *pty.CollateralizeCreate, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execDelLocal(tx, receiptData)
}
// ExecDelLocal_Borrow Action
func (c *Collateralize) ExecDelLocal_Borrow(payload *pty.CollateralizeBorrow, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execDelLocal(tx, receiptData)
}
// ExecDelLocal_Repay Action
func (c *Collateralize) ExecDelLocal_Repay(payload *pty.CollateralizeRepay, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execDelLocal(tx, receiptData)
}
// ExecDelLocal_Append Action
func (c *Collateralize) ExecDelLocal_Append(payload *pty.CollateralizeAppend, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execDelLocal(tx, receiptData)
}
// ExecDelLocal_Feed Action
func (c *Collateralize) ExecDelLocal_Feed(payload *pty.CollateralizeFeed, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execDelLocal(tx, receiptData)
}
// ExecDelLocal_Retrieve Action
func (c *Collateralize) ExecDelLocal_Retrieve(payload *pty.CollateralizeRetrieve, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execDelLocal(tx, receiptData)
}
// ExecDelLocal_Manage Action
func (c *Collateralize) ExecDelLocal_Manage(payload *pty.CollateralizeManage, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execDelLocal(tx, receiptData)
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package executor
import (
//"github.com/33cn/chain33/common"
"github.com/33cn/chain33/types"
pty "github.com/33cn/plugin/plugin/dapp/collateralize/types"
)
func (c *Collateralize) execLocal(tx *types.Transaction, receipt *types.ReceiptData) (*types.LocalDBSet, error) {
set := &types.LocalDBSet{}
for _, item := range receipt.Logs {
if item.Ty >= pty.TyLogCollateralizeCreate && item.Ty <= pty.TyLogCollateralizeRetrieve {
var collateralizeLog pty.ReceiptCollateralize
err := types.Decode(item.Log, &collateralizeLog)
if err != nil {
return nil, err
}
if item.Ty == pty.TyLogCollateralizeCreate || item.Ty == pty.TyLogCollateralizeRetrieve {
collTable := pty.NewCollateralizeTable(c.GetLocalDB())
err = collTable.Replace(&pty.ReceiptCollateralize{CollateralizeId: collateralizeLog.CollateralizeId, Status: collateralizeLog.Status,
AccountAddr: collateralizeLog.AccountAddr})
if err != nil {
return nil, err
}
kvs, err := collTable.Save()
if err != nil {
return nil, err
}
set.KV = append(set.KV, kvs...)
} else {
recordTable := pty.NewRecordTable(c.GetLocalDB())
err = recordTable.Replace(&pty.ReceiptCollateralize{CollateralizeId: collateralizeLog.CollateralizeId, Status: collateralizeLog.Status,
RecordId: collateralizeLog.RecordId, AccountAddr: collateralizeLog.AccountAddr})
if err != nil {
return nil, err
}
kvs, err := recordTable.Save()
if err != nil {
return nil, err
}
set.KV = append(set.KV, kvs...)
}
}
}
set.KV = c.AddRollbackKV(tx, []byte(pty.CollateralizeX), set.KV)
return set, nil
}
// ExecLocal_Create Action
func (c *Collateralize) ExecLocal_Create(payload *pty.CollateralizeCreate, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execLocal(tx, receiptData)
}
// ExecLocal_Borrow Action
func (c *Collateralize) ExecLocal_Borrow(payload *pty.CollateralizeBorrow, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execLocal(tx, receiptData)
}
// ExecLocal_Repay Action
func (c *Collateralize) ExecLocal_Repay(payload *pty.CollateralizeRepay, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execLocal(tx, receiptData)
}
// ExecLocal_Repay Action
func (c *Collateralize) ExecLocal_Append(payload *pty.CollateralizeAppend, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execLocal(tx, receiptData)
}
// ExecLocal_Feed Action
func (c *Collateralize) ExecLocal_Feed(payload *pty.CollateralizeFeed, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execLocal(tx, receiptData)
}
// ExecLocal_Retrieve Action
func (c *Collateralize) ExecLocal_Retrieve(payload *pty.CollateralizeRetrieve, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execLocal(tx, receiptData)
}
// ExecLocal_Manage Action
func (c *Collateralize) ExecLocal_Manage(payload *pty.CollateralizeManage, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execLocal(tx, receiptData)
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package executor
import (
"github.com/33cn/chain33/types"
pty "github.com/33cn/plugin/plugin/dapp/collateralize/types"
)
func (c *Collateralize) Query_CollateralizeInfoByID(req *pty.ReqCollateralizeInfo) (types.Message, error) {
coll, err := queryCollateralizeByID(c.GetStateDB(), req.CollateralizeId)
if err != nil {
clog.Error("Query_CollateralizeInfoByID", "id", req.CollateralizeId, "error", err)
return nil, err
}
info := &pty.RepCollateralizeCurrentInfo{
Status: coll.Status,
TotalBalance: coll.TotalBalance,
DebtCeiling: coll.DebtCeiling,
LiquidationRatio: coll.LiquidationRatio,
StabilityFeeRatio: coll.StabilityFeeRatio,
CreateAddr: coll.CreateAddr,
Balance: coll.Balance,
Period: coll.Period,
CollateralizeId: coll.CollateralizeId,
CollBalance: coll.CollBalance,
}
info.BorrowRecords = append(info.BorrowRecords, coll.BorrowRecords...)
info.BorrowRecords = append(info.BorrowRecords, coll.InvalidRecords...)
return info, nil
}
func (c *Collateralize) Query_CollateralizeInfoByIDs(req *pty.ReqCollateralizeInfos) (types.Message, error) {
infos := &pty.RepCollateralizeCurrentInfos{}
for _, id := range req.CollateralizeIds {
coll, err := queryCollateralizeByID(c.GetStateDB(), id)
if err != nil {
clog.Error("Query_CollateralizeInfoByID", "id", id, "error", err)
return nil, err
}
info := &pty.RepCollateralizeCurrentInfo{
Status: coll.Status,
TotalBalance: coll.TotalBalance,
DebtCeiling: coll.DebtCeiling,
LiquidationRatio: coll.LiquidationRatio,
StabilityFeeRatio: coll.StabilityFeeRatio,
CreateAddr: coll.CreateAddr,
Balance: coll.Balance,
Period: coll.Period,
CollateralizeId: coll.CollateralizeId,
CollBalance: coll.CollBalance,
}
info.BorrowRecords = append(info.BorrowRecords, coll.BorrowRecords...)
info.BorrowRecords = append(info.BorrowRecords, coll.InvalidRecords...)
infos.Infos = append(infos.Infos, info)
}
return infos, nil
}
func (c *Collateralize) Query_CollateralizeByStatus(req *pty.ReqCollateralizeByStatus) (types.Message, error) {
ids := &pty.RepCollateralizeIDs{}
collIDRecords, err := queryCollateralizeByStatus(c.GetLocalDB(), req.Status, req.CollID)
if err != nil {
clog.Error("Query_CollateralizeByStatus", "get collateralize record error", err)
return nil, err
}
ids.IDs = append(ids.IDs, collIDRecords...)
return ids, nil
}
func (c *Collateralize) Query_CollateralizeByAddr(req *pty.ReqCollateralizeByAddr) (types.Message, error) {
ids := &pty.RepCollateralizeIDs{}
collIDRecords, err := queryCollateralizeByAddr(c.GetLocalDB(), req.Addr, req.Status, req.CollID)
if err != nil {
clog.Error("Query_CollateralizeByAddr", "get collateralize record error", err)
return nil, err
}
ids.IDs = append(ids.IDs, collIDRecords...)
return ids, nil
}
func (c *Collateralize) Query_CollateralizeRecordByID(req *pty.ReqCollateralizeRecord) (types.Message, error) {
ret := &pty.RepCollateralizeRecord{}
issuRecord, err := queryCollateralizeRecordByID(c.GetStateDB(), req.CollateralizeId, req.RecordId)
if err != nil {
clog.Error("Query_IssuanceRecordByID", "get collateralize record error", err)
return nil, err
}
ret.Record = issuRecord
return ret, nil
}
func (c *Collateralize) Query_CollateralizeRecordByAddr(req *pty.ReqCollateralizeRecordByAddr) (types.Message, error) {
ret := &pty.RepCollateralizeRecords{}
records, err := queryCollateralizeRecordByAddr(c.GetStateDB(), c.GetLocalDB(), req.Addr, req.Status, req.CollateralizeId, req.RecordId)
if err != nil {
clog.Error("Query_CollateralizeRecordByAddr", "get collateralize record error", err)
return nil, err
}
if req.Status == 0 {
ret.Records = records
} else {
for _, record := range records {
if record.Status == req.Status {
ret.Records = append(ret.Records, record)
}
}
}
return ret, nil
}
func (c *Collateralize) Query_CollateralizeRecordByStatus(req *pty.ReqCollateralizeRecordByStatus) (types.Message, error) {
ret := &pty.RepCollateralizeRecords{}
records, err := queryCollateralizeRecordByStatus(c.GetStateDB(), c.GetLocalDB(), req.Status, req.CollateralizeId, req.RecordId)
if err != nil {
clog.Error("Query_CollateralizeRecordByStatus", "get collateralize record error", err)
return nil, err
}
ret.Records = records
return ret, nil
}
func (c *Collateralize) Query_CollateralizeConfig(req *pty.ReqCollateralizeRecordByAddr) (types.Message, error) {
config, err := getCollateralizeConfig(c.GetStateDB())
if err != nil {
clog.Error("Query_CollateralizeConfig", "get collateralize config error", err)
return nil, err
}
balance, err := getCollBalance(config.TotalBalance, c.GetLocalDB(), c.GetStateDB())
if err != nil {
clog.Error("Query_CollateralizeInfoByID", "error", err)
return nil, err
}
ret := &pty.RepCollateralizeConfig{
TotalBalance: config.TotalBalance,
DebtCeiling: config.DebtCeiling,
LiquidationRatio: config.LiquidationRatio,
StabilityFeeRatio: config.StabilityFeeRatio,
Period: config.Period,
Balance: balance,
CurrentTime: config.CurrentTime,
}
return ret, nil
}
func (c *Collateralize) Query_CollateralizePrice(req *pty.ReqCollateralizeRecordByAddr) (types.Message, error) {
price, err := getLatestPrice(c.GetStateDB())
if err != nil {
clog.Error("Query_CollateralizePrice", "error", err)
return nil, err
}
return &pty.RepCollateralizePrice{Price: price}, nil
}
func (c *Collateralize) Query_CollateralizeUserBalance(req *pty.ReqCollateralizeRecordByAddr) (types.Message, error) {
balance, err := queryCollateralizeUserBalance(c.GetStateDB(), c.GetLocalDB(), req.Addr)
if err != nil {
clog.Error("Query_CollateralizeRecordByAddr", "get collateralize record error", err)
return nil, err
}
return &pty.RepCollateralizeUserBalance{Balance: balance}, nil
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package collateralize
import (
"github.com/33cn/chain33/pluginmgr"
"github.com/33cn/plugin/plugin/dapp/collateralize/commands"
"github.com/33cn/plugin/plugin/dapp/collateralize/executor"
"github.com/33cn/plugin/plugin/dapp/collateralize/types"
)
func init() {
pluginmgr.Register(&pluginmgr.PluginBase{
Name: types.CollateralizeX,
ExecName: executor.GetName(),
Exec: executor.Init,
Cmd: commands.CollateralizeCmd,
})
}
all:
sh ./create_protobuf.sh
syntax = "proto3";
package types;
// 放贷信息
message Collateralize {
string collateralizeId = 1; //放贷ID,一期放贷对应一个ID
int64 totalBalance = 2; //当期放贷的总金额(ccny)
int64 debtCeiling = 3; //单用户可借出的限额(ccny)
int64 liquidationRatio = 4; //清算比例
int64 stabilityFeeRatio = 5; //稳定费率
string createAddr = 6; //创建人地址
int64 balance = 7; //放贷剩余金额(ccny)
repeated BorrowRecord borrowRecords = 8; //借贷记录
repeated BorrowRecord InvalidRecords = 9; //失效的借贷记录
int32 status = 10;//当期借贷的状态,是否关闭
int64 latestLiquidationPrice = 11;//最高清算价格
int64 period = 12;//借贷最大期限
int64 latestExpireTime = 13;//最近超期时间
int64 collBalance = 14;//抵押bty
int32 preStatus = 15;//上一个状态
}
// 借出记录
message BorrowRecord {
string accountAddr = 1; //借贷人地址
int64 startTime = 2; //借贷时间
int64 collateralValue = 3; //抵押物价值(bty)
int64 collateralPrice = 4; //抵押物价格
int64 debtValue = 5; //债务价值(ccny)
int64 liquidationPrice = 6; //抵押物清算价格
int32 status = 7; //抵押状态,是否被清算
int64 liquidateTime = 8; //清算时间
int64 expireTime = 9; //超时清算时间
int32 preStatus = 10;//上一次抵押状态,用于告警恢复
string recordId = 11;//借贷id,标识一次借出记录
string collateralizeId = 12;//放贷id
}
// 资产价格记录
message AssetPriceRecord {
int64 recordTime = 1; //价格记录时间
int64 btyPrice = 2; //bty价格
int64 btcPrice = 3; //btc价格
int64 ethPrice = 4; //eth价格
}
// action
message CollateralizeAction {
oneof value {
CollateralizeCreate create = 1; //创建一期借贷
CollateralizeBorrow borrow = 2; //借贷
CollateralizeRepay repay = 3; //清算
CollateralizeAppend append = 4; //追加
CollateralizeFeed feed = 5; //喂价
CollateralizeRetrieve retrieve = 6; //收回
CollateralizeManage manage = 7; //全局配置
}
int32 ty = 10;
}
message CollateralizeManage {
int64 debtCeiling = 1; //单用户可借出的限额(ccny)
int64 liquidationRatio = 2; //清算比例
int64 stabilityFeeRatio = 3; //稳定费
int64 period = 4; //合约期限
int64 totalBalance = 5; //放贷总量
int64 currentTime = 6; //设置时间
}
message CollateralizeAddr {
repeated string superAddrs = 1; //大户地址
}
// 创建放贷
message CollateralizeCreate {
int64 totalBalance = 1; //可借贷总金额
}
// 质押借出
message CollateralizeBorrow {
string collateralizeId = 1; //借贷期数ID
int64 value = 2; //借贷价值(ccny)
}
// 质押清算
message CollateralizeRepay {
string collateralizeId = 1; //借贷期数ID
string recordId = 2; //借贷ID
}
// 追加抵押物
message CollateralizeAppend {
string collateralizeId = 1; //借贷期数ID
string recordId = 2; //借贷ID
int64 collateralValue = 3; //追加价值(bty)
}
// 喂价
message CollateralizeFeed {
int32 collType = 1; //抵押物价格类型(1,bty,2,btc,3,eth...)
repeated int64 price = 2; //喂价
repeated int64 volume = 3; //成交量
}
// 收回
message CollateralizeRetrieve {
string collateralizeId = 1; //借贷期数ID
int64 balance = 2; //收回金额
}
// exec_local 放贷信息
message ReceiptCollateralize {
string collateralizeId = 1;
string accountAddr = 3;
string recordId = 4;
int32 status = 5;
}
// exec_local 放贷记录信息列表
message CollateralizeRecords {
repeated ReceiptCollateralize records = 1;
}
// 根据ID查询一期放贷信息
message ReqCollateralizeInfo {
string collateralizeId = 1;
}
// 返回一期放贷信息
message RepCollateralizeCurrentInfo {
int32 status = 1;//当期借贷的状态,是否关闭
int64 totalBalance = 2; //当期可借贷的总金额(ccny)
int64 debtCeiling = 3; //单用户可借出的限额(ccny)
int64 liquidationRatio = 4; //清算比例
int64 stabilityFeeRatio = 5; //稳定费
string createAddr = 6; //创建人地址
int64 balance = 7; //剩余可借贷金额(ccny)
int64 period = 8; //合约期限
string collateralizeId = 9; //放贷ID
int64 collBalance = 10;//抵押bty
repeated BorrowRecord borrowRecords = 11;//借贷记录
}
// 根据ID列表查询多期放贷信息
message ReqCollateralizeInfos {
repeated string collateralizeIds = 1;
}
// 返回多期放贷信息
message RepCollateralizeCurrentInfos {
repeated RepCollateralizeCurrentInfo infos = 1;
}
// 根据放贷状态查询
message ReqCollateralizeByStatus {
int32 status = 1;
string collID = 2;
}
// 根据用户地址查询
message ReqCollateralizeByAddr {
string addr = 1;
int32 status = 2;
string collID = 3;
}
// 返回放贷ID列表
message RepCollateralizeIDs {
repeated string IDs = 1;
}
// 根据地址和借贷ID混合查询具体借贷记录
message ReqCollateralizeRecordByAddr {
string collateralizeId = 1;
string addr = 2;
int32 status = 3;
string recordId = 4;
}
// 根据状态和借贷ID混合查询具体借贷记录
message ReqCollateralizeRecordByStatus {
string collateralizeId = 1;
int32 status = 2;
string recordId = 3;
}
// 返回借贷记录
message RepCollateralizeRecords {
repeated BorrowRecord records = 1;
}
// 精确查找借贷记录
message ReqCollateralizeRecord {
string collateralizeId = 1;
string recordId = 2;
}
// 返回借贷记录
message RepCollateralizeRecord {
BorrowRecord record = 1;
}
// 返回放贷配置
message RepCollateralizeConfig {
int64 debtCeiling = 1; //单用户可借出的限额(ccny)
int64 liquidationRatio = 2; //清算比例
int64 stabilityFeeRatio = 3; //稳定费
int64 period = 4; //合约期限
int64 totalBalance = 5; //放贷总量
int64 balance = 6; //剩余放贷额度
int64 currentTime = 7; //设置时间
}
// 返回最新抵押物价格
message RepCollateralizePrice {
int64 price = 1; //当前抵押物最新价格
}
// 返回用户借贷总额
message RepCollateralizeUserBalance {
int64 balance = 1; //返回用户借贷总额
}
\ No newline at end of file
#!/bin/sh
chain33_path=$(go list -f '{{.Dir}}' "github.com/33cn/chain33")
protoc --go_out=plugins=grpc:../types ./*.proto --proto_path=. --proto_path="${chain33_path}/types/proto/"
## 借贷合约表结构
### 放贷表coller表结构
字段名称|类型|说明
---|---|---
collateralizeId|string|放贷ID,主键
accountAddr|string|大户地址
recordId|string|借贷ID
status|int32|放贷状态(1:已放贷 2:已收回)
### 放贷表coller表索引
索引名|说明
---|---
status|根据放贷状态查询放贷ID
addr|根据大户地址查询放贷ID
addr_status|根据放贷状态和大户地址查询放贷ID
### 借贷表borrow表结构
字段名称|类型|说明
---|---|---
recordId|string|借贷ID,主键
collateralizeId|string|放贷ID
accountAddr|string|用户地址
status|int32|借贷状态(1:已发行 2:价格清算告警 3:价格清算 4:超时清算告警 5:超时清算 6:已清算)
### 放贷表borrow表索引
索引名|说明
---|---
status|根据借贷状态查询借贷ID
addr|根据大户地址查询借贷ID
addr_status|根据借贷状态和用户地址查询借贷ID
id_status|根据放贷ID和借贷状态查询借贷ID
id_addr|根据放贷ID和用户地址查询借贷ID
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package types
import "errors"
// Errors for lottery
var (
ErrRiskParam = errors.New("ErrRiskParam")
ErrCollateralizeStatus = errors.New("ErrCollateralizeStatus")
ErrCollateralizeExceedDebtCeiling = errors.New("ErrCollateralizeExceedDebtCeiling")
ErrPriceInvalid = errors.New("ErrPriceInvalid")
ErrAssetType = errors.New("ErrAssetType")
ErrRecordNotExist = errors.New("ErrRecordNotExist")
ErrCollateralizeErrCloser = errors.New("ErrCollateralizeErrCloser")
ErrRepayValueInsufficient = errors.New("ErrRepayValueInsufficient")
ErrCollateralizeAccountExist = errors.New("ErrCollateralizeAccountExist")
ErrCollateralizeLowBalance = errors.New("ErrCollateralizeLowBalance")
ErrCollateralizeBalanceInvalid = errors.New("ErrCollateralizeBalanceInvalid")
ErrPermissionDeny = errors.New("ErrPermissionDeny")
ErrCollateralizeRecordNotEmpty = errors.New("ErrCollateralizeRecordNotEmpty")
)
package types
import (
"fmt"
"github.com/33cn/chain33/common/db"
"github.com/33cn/chain33/common/db/table"
"github.com/33cn/chain33/types"
)
var opt = &table.Option{
Prefix: "LODB-collateralize",
Name: "coller",
Primary: "collateralizeid",
Index: []string{"status", "addr", "addr_status"},
}
//NewTable 新建表
func NewCollateralizeTable(kvdb db.KV) *table.Table {
rowmeta := NewCollatetalizeRow()
table, err := table.NewTable(rowmeta, kvdb, opt)
if err != nil {
panic(err)
}
return table
}
//CollatetalizeRow table meta 结构
type CollatetalizeRow struct {
*ReceiptCollateralize
}
//NewIssuanceRow 新建一个meta 结构
func NewCollatetalizeRow() *CollatetalizeRow {
return &CollatetalizeRow{ReceiptCollateralize: &ReceiptCollateralize{}}
}
//CreateRow 新建数据行
func (tx *CollatetalizeRow) CreateRow() *table.Row {
return &table.Row{Data: &ReceiptCollateralize{}}
}
//SetPayload 设置数据
func (tx *CollatetalizeRow) SetPayload(data types.Message) error {
if txdata, ok := data.(*ReceiptCollateralize); ok {
tx.ReceiptCollateralize = txdata
return nil
}
return types.ErrTypeAsset
}
//Get 按照indexName 查询 indexValue
func (tx *CollatetalizeRow) Get(key string) ([]byte, error) {
if key == "collateralizeid" {
return []byte(tx.CollateralizeId), nil
} else if key == "status" {
return []byte(fmt.Sprintf("%2d", tx.Status)), nil
} else if key == "addr" {
return []byte(tx.AccountAddr), nil
} else if key == "addr_status" {
return []byte(fmt.Sprintf("%s:%2d", tx.AccountAddr, tx.Status)), nil
}
return nil, types.ErrNotFound
}
var optRecord = &table.Option{
Prefix: "LODB-collateralize",
Name: "borrow",
Primary: "borrowid",
Index: []string{"status", "addr", "addr_status", "id_status", "id_addr"},
}
// NewRecordTable 借贷记录表
func NewRecordTable(kvdb db.KV) *table.Table {
rowmeta := NewRecordRow()
table, err := table.NewTable(rowmeta, kvdb, optRecord)
if err != nil {
panic(err)
}
return table
}
//CollatetalizeRow table meta 结构
type CollateralizeRecordRow struct {
*ReceiptCollateralize
}
//NewIssuanceRow 新建一个meta 结构
func NewRecordRow() *CollateralizeRecordRow {
return &CollateralizeRecordRow{ReceiptCollateralize: &ReceiptCollateralize{}}
}
//CreateRow 新建数据行
func (tx *CollateralizeRecordRow) CreateRow() *table.Row {
return &table.Row{Data: &ReceiptCollateralize{}}
}
//SetPayload 设置数据
func (tx *CollateralizeRecordRow) SetPayload(data types.Message) error {
if txdata, ok := data.(*ReceiptCollateralize); ok {
tx.ReceiptCollateralize = txdata
return nil
}
return types.ErrTypeAsset
}
//Get 按照indexName 查询 indexValue
func (tx *CollateralizeRecordRow) Get(key string) ([]byte, error) {
if key == "borrowid" {
return []byte(tx.RecordId), nil
} else if key == "status" {
return []byte(fmt.Sprintf("%2d", tx.Status)), nil
} else if key == "addr" {
return []byte(tx.AccountAddr), nil
} else if key == "addr_status" {
return []byte(fmt.Sprintf("%s:%2d", tx.AccountAddr, tx.Status)), nil
} else if key == "id_status" {
return []byte(fmt.Sprintf("%s:%2d", tx.CollateralizeId, tx.Status)), nil
} else if key == "id_addr" {
return []byte(fmt.Sprintf("%s:%s", tx.CollateralizeId, tx.AccountAddr)), nil
}
return nil, types.ErrNotFound
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package types
// CollateralizeCreateTx for construction
type CollateralizeCreateTx struct {
TotalBalance float64 `json:"totalBalance"`
Fee int64 `json:"fee"`
}
// CollateralizeBorrowTx for construction
type CollateralizeBorrowTx struct {
CollateralizeID string `json:"collateralizeId"`
Value float64 `json:"value"`
Fee int64 `json:"fee"`
}
// CollateralizeRepayTx for construction
type CollateralizeRepayTx struct {
CollateralizeID string `json:"collateralizeId"`
RecordID string `json:"recordID"`
Fee int64 `json:"fee"`
}
// CollateralizeAppednTx for construction
type CollateralizeAppendTx struct {
CollateralizeID string `json:"collateralizeId"`
RecordID string `json:"recordID"`
Value float64 `json:"value"`
Fee int64 `json:"fee"`
}
// CollateralizeFeedTx for construction
type CollateralizeFeedTx struct {
Price []float64 `json:"price"`
Volume []int64 `json:"volume"`
Fee int64 `json:"fee"`
}
// CollateralizeRetrieveTx for construction
type CollateralizeRetrieveTx struct {
CollateralizeID string `json:"collateralizeId"`
Balance float64 `json:"Balance"`
Fee int64 `json:"fee"`
}
// CollateralizeManageTx for construction
type CollateralizeManageTx struct {
DebtCeiling float64 `json:"debtCeiling"`
LiquidationRatio float64 `json:"liquidationRatio"`
StabilityFeeRatio float64 `json:"stabilityFeeRatio"`
Period int64 `json:"period"`
TotalBalance float64 `json:"totalBalance"`
Fee int64 `json:"fee"`
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package types
//Collateralize op
const (
CollateralizeActionCreate = 1 + iota
CollateralizeActionBorrow
CollateralizeActionRepay
CollateralizeActionAppend
CollateralizeActionFeed
CollateralizeActionRetrieve
CollateralizeActionManage
//log for Collateralize
TyLogCollateralizeCreate = 731
TyLogCollateralizeBorrow = 732
TyLogCollateralizeRepay = 733
TyLogCollateralizeAppend = 734
TyLogCollateralizeFeed = 735
TyLogCollateralizeRetrieve = 736
)
// Collateralize name
const (
CollateralizeX = "collateralize"
CCNYTokenName = "CCNY"
CollateralizePreLiquidationRatio = 1.1 * 1e4 //TODO 预清算比例,抵押物价值跌到借出ccny价值110%的时候开始清算
)
//Collateralize status
const (
CollateralizeStatusCreated = 1 + iota
CollateralizeStatusClose
)
//暂时只支持bty
//const (
// CollateralizeAssetTypeBty = 1 + iota
// CollateralizeAssetTypeBtc
// CollateralizeAssetTypeEth
//)
const (
CollateralizeUserStatusCreate = 1 + iota
CollateralizeUserStatusWarning
CollateralizeUserStatusSystemLiquidate
CollateralizeUserStatusExpire
CollateralizeUserStatusExpireLiquidate
CollateralizeUserStatusClose
)
package init
import (
_ "github.com/33cn/plugin/plugin/dapp/autonomy" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/blackwhite" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/cert" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/dposvote" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/echo" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/evm" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/exchange" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/game" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/guess" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/hashlock" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/js" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/lottery" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/multisig" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/norm" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/oracle" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/paracross" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/pokerbull" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/privacy" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/relay" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/retrieve" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/storage" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/ticket" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/token" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/trade" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/unfreeze" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/valnode" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/autonomy" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/blackwhite" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/cert" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/collateralize" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/dposvote" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/echo" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/evm" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/exchange" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/game" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/guess" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/hashlock" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/issuance" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/js" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/lottery" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/multisig" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/norm" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/oracle" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/paracross" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/pokerbull" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/privacy" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/relay" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/retrieve" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/storage" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/ticket" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/token" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/trade" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/unfreeze" //auto gen
_ "github.com/33cn/plugin/plugin/dapp/valnode" //auto gen
)
all:
chmod +x ./build.sh
./build.sh $(OUT) $(FLAG)
\ No newline at end of file
#!/usr/bin/env bash
strpwd=$(pwd)
strcmd=${strpwd##*dapp/}
strapp=${strcmd%/cmd*}
OUT_TESTDIR="${1}/dapptest/$strapp"
mkdir -p "${OUT_TESTDIR}"
cp ./test/test-rpc.sh "${OUT_TESTDIR}"
This diff is collapsed.
This diff is collapsed.
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package executor
/*
waiting for update
*/
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package executor
import (
"github.com/33cn/chain33/types"
pty "github.com/33cn/plugin/plugin/dapp/issuance/types"
)
// Exec_Create Action
func (c *Issuance) Exec_Create(payload *pty.IssuanceCreate, tx *types.Transaction, index int) (*types.Receipt, error) {
actiondb := NewIssuanceAction(c, tx, index)
return actiondb.IssuanceCreate(payload)
}
// Exec_Borrow Action
func (c *Issuance) Exec_Debt(payload *pty.IssuanceDebt, tx *types.Transaction, index int) (*types.Receipt, error) {
actiondb := NewIssuanceAction(c, tx, index)
return actiondb.IssuanceDebt(payload)
}
// Exec_Repay Action
func (c *Issuance) Exec_Repay(payload *pty.IssuanceRepay, tx *types.Transaction, index int) (*types.Receipt, error) {
actiondb := NewIssuanceAction(c, tx, index)
return actiondb.IssuanceRepay(payload)
}
// Exec_Feed Action
func (c *Issuance) Exec_Feed(payload *pty.IssuanceFeed, tx *types.Transaction, index int) (*types.Receipt, error) {
actiondb := NewIssuanceAction(c, tx, index)
return actiondb.IssuanceFeed(payload)
}
// Exec_Close Action
func (c *Issuance) Exec_Close(payload *pty.IssuanceClose, tx *types.Transaction, index int) (*types.Receipt, error) {
actiondb := NewIssuanceAction(c, tx, index)
return actiondb.IssuanceClose(payload)
}
// Exec_Manage Action
func (c *Issuance) Exec_Manage(payload *pty.IssuanceManage, tx *types.Transaction, index int) (*types.Receipt, error) {
actiondb := NewIssuanceAction(c, tx, index)
return actiondb.IssuanceManage(payload)
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package executor
import (
"github.com/33cn/chain33/types"
pty "github.com/33cn/plugin/plugin/dapp/issuance/types"
)
func (c *Issuance) execDelLocal(tx *types.Transaction, receiptData *types.ReceiptData) (*types.LocalDBSet, error) {
kvs, err := c.DelRollbackKV(tx, tx.Execer)
if err != nil {
return nil, err
}
dbSet := &types.LocalDBSet{}
dbSet.KV = append(dbSet.KV, kvs...)
return dbSet, nil
}
// ExecDelLocal_Create Action
func (c *Issuance) ExecDelLocal_Create(payload *pty.IssuanceCreate, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execDelLocal(tx, receiptData)
}
// ExecDelLocal_Debt Action
func (c *Issuance) ExecDelLocal_Debt(payload *pty.IssuanceDebt, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execDelLocal(tx, receiptData)
}
// ExecDelLocal_Repay Action
func (c *Issuance) ExecDelLocal_Repay(payload *pty.IssuanceRepay, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execDelLocal(tx, receiptData)
}
// ExecDelLocal_Feed Action
func (c *Issuance) ExecDelLocal_Feed(payload *pty.IssuanceFeed, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execDelLocal(tx, receiptData)
}
// ExecDelLocal_Close Action
func (c *Issuance) ExecDelLocal_Close(payload *pty.IssuanceClose, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execDelLocal(tx, receiptData)
}
// ExecDelLocal_Manage Action
func (c *Issuance) ExecDelLocal_Manage(payload *pty.IssuanceManage, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execDelLocal(tx, receiptData)
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package executor
import (
//"github.com/33cn/chain33/common"
"github.com/33cn/chain33/types"
pty "github.com/33cn/plugin/plugin/dapp/issuance/types"
)
func (c *Issuance) execLocal(tx *types.Transaction, receipt *types.ReceiptData) (*types.LocalDBSet, error) {
set := &types.LocalDBSet{}
for _, item := range receipt.Logs {
if item.Ty >= pty.TyLogIssuanceCreate && item.Ty <= pty.TyLogIssuanceClose {
var issuanceLog pty.ReceiptIssuance
err := types.Decode(item.Log, &issuanceLog)
if err != nil {
return nil, err
}
if item.Ty == pty.TyLogIssuanceCreate || item.Ty == pty.TyLogIssuanceClose {
IDtable := pty.NewIssuanceTable(c.GetLocalDB())
err = IDtable.Replace(&pty.ReceiptIssuanceID{IssuanceId: issuanceLog.IssuanceId, Status: issuanceLog.Status})
if err != nil {
return nil, err
}
kvs, err := IDtable.Save()
if err != nil {
return nil, err
}
set.KV = append(set.KV, kvs...)
} else {
recordTable := pty.NewRecordTable(c.GetLocalDB())
err = recordTable.Replace(&pty.ReceiptIssuance{IssuanceId: issuanceLog.IssuanceId, Status: issuanceLog.Status,
DebtId: issuanceLog.DebtId, AccountAddr: issuanceLog.AccountAddr})
if err != nil {
return nil, err
}
kvs, err := recordTable.Save()
if err != nil {
return nil, err
}
set.KV = append(set.KV, kvs...)
}
}
}
set.KV = c.AddRollbackKV(tx, []byte(pty.IssuanceX), set.KV)
return set, nil
}
// ExecLocal_Create Action
func (c *Issuance) ExecLocal_Create(payload *pty.IssuanceCreate, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execLocal(tx, receiptData)
}
// ExecLocal_Debt Action
func (c *Issuance) ExecLocal_Debt(payload *pty.IssuanceDebt, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execLocal(tx, receiptData)
}
// ExecLocal_Repay Action
func (c *Issuance) ExecLocal_Repay(payload *pty.IssuanceRepay, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execLocal(tx, receiptData)
}
// ExecLocal_Feed Action
func (c *Issuance) ExecLocal_Feed(payload *pty.IssuanceFeed, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execLocal(tx, receiptData)
}
// ExecLocal_Close Action
func (c *Issuance) ExecLocal_Close(payload *pty.IssuanceClose, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execLocal(tx, receiptData)
}
// ExecLocal_Manage Action
func (c *Issuance) ExecLocal_Manage(payload *pty.IssuanceManage, tx *types.Transaction, receiptData *types.ReceiptData, index int) (*types.LocalDBSet, error) {
return c.execLocal(tx, receiptData)
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package executor
import (
log "github.com/33cn/chain33/common/log/log15"
drivers "github.com/33cn/chain33/system/dapp"
"github.com/33cn/chain33/types"
pty "github.com/33cn/plugin/plugin/dapp/issuance/types"
)
var clog = log.New("module", "execs.issuance")
var driverName = pty.IssuanceX
func InitExecType() {
ety := types.LoadExecutorType(driverName)
ety.InitFuncList(types.ListMethod(&Issuance{}))
}
// Init issuance
func Init(name string, cfg *types.Chain33Config, sub []byte) {
driverName := GetName()
if name != driverName {
panic("system dapp can't be rename")
}
if sub != nil {
types.MustDecode(sub, &cfg)
}
drivers.Register(cfg, driverName, newIssuance, cfg.GetDappFork(driverName, "Enable"))
InitExecType()
}
// GetName for Issuance
func GetName() string {
return newIssuance().GetName()
}
// Issuance driver
type Issuance struct {
drivers.DriverBase
}
func newIssuance() drivers.Driver {
c := &Issuance{}
c.SetChild(c)
c.SetExecutorType(types.LoadExecutorType(driverName))
return c
}
// GetDriverName for Issuance
func (c *Issuance) GetDriverName() string {
return pty.IssuanceX
}
// CheckReceiptExecOk return true to check if receipt ty is ok
func (c *Issuance) CheckReceiptExecOk() bool {
return true
}
// ExecutorOrder 设置localdb的EnableRead
func (c *Issuance) ExecutorOrder() int64 {
cfg := c.GetAPI().GetConfig()
if cfg.IsFork(c.GetHeight(), "ForkLocalDBAccess") {
return drivers.ExecLocalSameTime
}
return c.DriverBase.ExecutorOrder()
}
This diff is collapsed.
This diff is collapsed.
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package executor
import (
"github.com/33cn/chain33/types"
pty "github.com/33cn/plugin/plugin/dapp/issuance/types"
)
func (c *Issuance) Query_IssuanceInfoByID(req *pty.ReqIssuanceInfo) (types.Message, error) {
issu, err := queryIssuanceByID(c.GetStateDB(), req.IssuanceId)
if err != nil {
clog.Error("Query_IssuanceInfoByID", "id", req.IssuanceId, "error", err)
return nil, err
}
return &pty.RepIssuanceCurrentInfo{
Status: issu.Status,
TotalBalance: issu.TotalBalance,
DebtCeiling: issu.DebtCeiling,
LiquidationRatio: issu.LiquidationRatio,
Balance: issu.Balance,
CollateralValue: issu.CollateralValue,
DebtValue: issu.DebtValue,
Period: issu.Period,
IssuId: issu.IssuanceId,
CreateTime: issu.CreateTime,
}, nil
}
func (c *Issuance) Query_IssuanceInfoByIDs(req *pty.ReqIssuanceInfos) (types.Message, error) {
infos := &pty.RepIssuanceCurrentInfos{}
for _, id := range req.IssuanceIds {
issu, err := queryIssuanceByID(c.GetStateDB(), id)
if err != nil {
clog.Error("Query_IssuanceInfoByID", "id", id, "error", err)
return nil, err
}
infos.Infos = append(infos.Infos, &pty.RepIssuanceCurrentInfo{
Status: issu.Status,
TotalBalance: issu.TotalBalance,
DebtCeiling: issu.DebtCeiling,
LiquidationRatio: issu.LiquidationRatio,
Balance: issu.Balance,
CollateralValue: issu.CollateralValue,
DebtValue: issu.DebtValue,
Period: issu.Period,
IssuId: issu.IssuanceId,
CreateTime: issu.CreateTime,
})
}
return infos, nil
}
func (c *Issuance) Query_IssuanceByStatus(req *pty.ReqIssuanceByStatus) (types.Message, error) {
ids := &pty.RepIssuanceIDs{}
issuIDs, err := queryIssuanceByStatus(c.GetLocalDB(), req.Status, req.IssuanceId)
if err != nil {
clog.Error("Query_IssuanceByStatus", "get issuance error", err)
return nil, err
}
ids.IDs = append(ids.IDs, issuIDs...)
return ids, nil
}
func (c *Issuance) Query_IssuanceRecordByID(req *pty.ReqIssuanceRecords) (types.Message, error) {
ret := &pty.RepIssuanceDebtInfo{}
issuRecord, err := queryIssuanceRecordByID(c.GetStateDB(), req.IssuanceId, req.DebtId)
if err != nil {
clog.Error("Query_IssuanceRecordByID", "get issuance record error", err)
return nil, err
}
ret.Record = issuRecord
return ret, nil
}
func (c *Issuance) Query_IssuanceRecordsByAddr(req *pty.ReqIssuanceRecords) (types.Message, error) {
ret := &pty.RepIssuanceRecords{}
records, err := queryIssuanceRecordByAddr(c.GetStateDB(), c.GetLocalDB(), req.Addr, req.Status, req.DebtId)
if err != nil {
clog.Error("Query_IssuanceDebtInfoByAddr", "get issuance record error", err)
return nil, err
}
if req.Status == 0 {
ret.Records = records
} else {
for _, record := range records {
if record.Status == req.Status {
ret.Records = append(ret.Records, record)
}
}
}
return ret, nil
}
func (c *Issuance) Query_IssuanceRecordsByStatus(req *pty.ReqIssuanceRecords) (types.Message, error) {
ret := &pty.RepIssuanceRecords{}
records, err := queryIssuanceRecordsByStatus(c.GetStateDB(), c.GetLocalDB(), req.Status, req.DebtId)
if err != nil {
clog.Error("Query_IssuanceDebtInfoByStatus", "get issuance record error", err)
return nil, err
}
ret.Records = append(ret.Records, records...)
return ret, nil
}
func (c *Issuance) Query_IssuancePrice(req *pty.ReqIssuanceRecords) (types.Message, error) {
price, err := getLatestPrice(c.GetStateDB())
if err != nil {
clog.Error("Query_IssuancePrice", "error", err)
return nil, err
}
return &pty.RepIssuancePrice{Price: price}, nil
}
func (c *Issuance) Query_IssuanceUserBalance(req *pty.ReqIssuanceRecords) (types.Message, error) {
balance, err := queryIssuanceUserBalance(c.GetStateDB(), c.GetLocalDB(), req.Addr)
if err != nil {
clog.Error("Query_IssuanceRecordByAddr", "get issuance record error", err)
return nil, err
}
return &pty.RepIssuanceUserBalance{Balance: balance}, nil
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package issuance
import (
"github.com/33cn/chain33/pluginmgr"
"github.com/33cn/plugin/plugin/dapp/issuance/commands"
"github.com/33cn/plugin/plugin/dapp/issuance/executor"
"github.com/33cn/plugin/plugin/dapp/issuance/types"
)
func init() {
pluginmgr.Register(&pluginmgr.PluginBase{
Name: types.IssuanceX,
ExecName: executor.GetName(),
Exec: executor.Init,
Cmd: commands.IssuanceCmd,
})
}
all:
sh ./create_protobuf.sh
#!/bin/sh
chain33_path=$(go list -f '{{.Dir}}' "github.com/33cn/chain33")
protoc --go_out=plugins=grpc:../types ./*.proto --proto_path=. --proto_path="${chain33_path}/types/proto/"
syntax = "proto3";
package types;
// 发行信息
message Issuance {
string issuanceId = 1; //发行ID,一期发行对应一个ID
int64 totalBalance = 2; //当期发行的总金额(ccny)
int64 debtCeiling = 3; //单用户可借出的限额(ccny)
int64 liquidationRatio = 4; //清算比例
int64 collateralValue = 5; //抵押物总数量(bty)
int64 debtValue = 6; //产生的ccny数量
repeated DebtRecord debtRecords = 7; //大户抵押记录
repeated DebtRecord invalidRecords = 8; //大户抵押记录
int32 status = 9; //当期发行的状态,是否关闭
int64 latestLiquidationPrice = 10;//最高清算价格
int64 period = 11;//发行最大期限
int64 latestExpireTime = 12;//最近超期时间
int64 createTime = 13;//创建时间
int64 balance = 14;//剩余可发行ccny
string issuerAddr = 15;//发行地址
}
// 抵押记录
message DebtRecord {
string accountAddr = 1; //抵押人地址
int64 startTime = 2; //抵押时间
int64 collateralValue = 3; //抵押物价值(bty)
int64 collateralPrice = 4; //抵押物价格
int64 debtValue = 5; //债务价值(ccny)
int64 liquidationPrice = 6; //抵押物清算价格
int32 status = 7; //抵押状态,是否被清算
int64 liquidateTime = 8; //清算时间
int64 expireTime = 9; //超时清算时间
int32 preStatus = 10;//上一次抵押状态,用于告警恢复
string debtId = 11;//借贷id
string issuId = 12;//发行id
}
// 资产价格记录
message IssuanceAssetPriceRecord {
int64 recordTime = 1; //价格记录时间
int64 btyPrice = 2; //bty价格
}
// action
message IssuanceAction {
oneof value {
IssuanceCreate create = 1; //创建一期发行
IssuanceDebt debt = 2; //抵押
IssuanceRepay repay = 3; //清算
IssuanceFeed feed = 4; //喂价
IssuanceClose close = 5; //关闭
IssuanceManage manage = 6; //全局配置
}
int32 ty = 10;
}
message IssuanceManage {
repeated string superAddrs = 1; //大户地址
}
// 创建发行
message IssuanceCreate {
int64 totalBalance = 1; //发行总金额
int64 debtCeiling = 2; //单用户可借出的限额(ccny)
int64 liquidationRatio = 3; //清算比例
int64 period = 4; //发行最大期限
}
// 抵押
message IssuanceDebt {
string issuanceId = 1; //发行ID
int64 value = 2; //借贷金额(ccny)
}
// 质押清算
message IssuanceRepay {
string issuanceId = 1; //发行ID
string debtId = 2; //抵押ID
}
// 喂价
message IssuanceFeed {
int32 collType = 1; //抵押物价格类型(1,bty,2,btc,3,eth...)
repeated int64 price = 2; //喂价
repeated int64 volume = 3; //成交量
}
// 借贷关闭
message IssuanceClose {
string issuanceId = 1; //发行ID
}
// exec_local 发行信息
message ReceiptIssuance {
string issuanceId = 1;
string accountAddr = 2;
string debtId = 3;
int32 status = 4;
}
// exec_local issuid记录信息
message ReceiptIssuanceID {
string issuanceId = 1;
int32 status = 2;
}
// exec_local 抵押记录信息列表
message IssuanceRecords {
repeated ReceiptIssuance records = 1;
}
// 根据ID查询发行信息
message ReqIssuanceInfo {
string issuanceId = 1;
}
// 返回一期发行信息
message RepIssuanceCurrentInfo {
int32 status = 1; //当期发行的状态,是否关闭
int64 totalBalance = 2; //当期发行总金额(ccny)
int64 debtCeiling = 3; //单用户可借出的限额(ccny)
int64 liquidationRatio = 4; //清算比例
int64 balance = 5; //剩余可借贷金额(ccny)
int64 collateralValue = 6; //抵押物总数量(bty)
int64 debtValue = 7; //产生的ccny数量
int64 period = 8; //发行最大期限
string issuId = 9; //发行ID
int64 createTime = 10;//创建时间
}
// 根据ID列表查询多期发行信息
message ReqIssuanceInfos {
repeated string issuanceIds = 1;
}
// 返回多期发行信息
message RepIssuanceCurrentInfos {
repeated RepIssuanceCurrentInfo infos = 1;
}
// 根据发行状态查询
message ReqIssuanceByStatus {
int32 status = 1;
string issuanceId = 2;
}
// 返回发行ID列表
message RepIssuanceIDs {
repeated string IDs = 1;
}
// 根据用户地址查询抵押记录
message ReqIssuanceRecords {
string issuanceId = 1;
string addr = 2;
int32 status = 3;
string debtId = 4;
}
// 返回记录列表
message RepIssuanceRecords {
repeated DebtRecord records = 1;
}
// 返回记录
message RepIssuanceDebtInfo {
DebtRecord record = 1;
}
// 返回最新抵押物价格
message RepIssuancePrice {
int64 price = 1; //当前抵押物最新价格
}
// 返回用户发行总额
message RepIssuanceUserBalance {
int64 balance = 1; //返回用户发行总额
}
\ No newline at end of file
## 发行合约表结构
### 总发行表issuer表结构
字段名称|类型|说明
---|---|---
issuanceId|string|总发行ID,主键
status|int32|发行状态(1:已发行 2:已下线)
### 总发行表issuer表索引
索引名|说明
---|---
status|根据发行状态查询总发行ID
### 大户发行表debt表结构
字段名称|类型|说明
---|---|---
debtId|string|大户发行ID,主键
issuanceId|string|总发行ID
accountAddr|string|用户地址
status|int32|发行状态(1:已发行 2:价格清算告警 3:价格清算 4:超时清算告警 5:超时清算 6:关闭)
### 大户发行表debt表索引
索引名|说明
---|---
status|根据大户发行状态查询大户发行ID
addr|根据大户地址查询大户发行ID
addr_status|根据发行状态和大户地址查询大户发行ID
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package types
import "errors"
// Errors for lottery
var (
ErrRiskParam = errors.New("ErrRiskParam")
ErrIssuanceRepeatHash = errors.New("ErrIssuanceRepeatHash")
ErrIssuanceStatus = errors.New("ErrIssuanceStatus")
ErrIssuanceExceedDebtCeiling = errors.New("ErrIssuanceExceedDebtCeiling")
ErrPriceInvalid = errors.New("ErrPriceInvalid")
ErrAssetType = errors.New("ErrAssetType")
ErrRecordNotExist = errors.New("ErrRecordNotExist")
ErrIssuanceErrCloser = errors.New("ErrIssuanceErrCloser")
ErrRepayValueInsufficient = errors.New("ErrRepayValueInsufficient")
ErrIssuanceAccountExist = errors.New("ErrIssuanceAccountExist")
ErrIssuanceLowBalance = errors.New("ErrIssuanceLowBalance")
ErrIssuanceBalanceInvalid = errors.New("ErrIssuanceBalanceInvalid")
ErrPermissionDeny = errors.New("ErrPermissionDeny")
ErrIssuanceRecordNotEmpty = errors.New("ErrIssuanceRecordNotEmpty")
)
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package types
import (
"encoding/json"
"math"
"reflect"
"github.com/33cn/chain33/common/address"
log "github.com/33cn/chain33/common/log/log15"
"github.com/33cn/chain33/types"
)
var (
llog = log.New("module", "exectype."+IssuanceX)
)
func init() {
types.AllowUserExec = append(types.AllowUserExec, []byte(IssuanceX))
types.RegFork(IssuanceX, InitFork)
types.RegExec(IssuanceX, InitExecutor)
}
func InitFork(cfg *types.Chain33Config) {
cfg.RegisterDappFork(IssuanceX, "Enable", 0)
}
func InitExecutor(cfg *types.Chain33Config) {
types.RegistorExecutor(IssuanceX, NewType(cfg))
}
// IssuanceType def
type IssuanceType struct {
types.ExecTypeBase
}
// NewType method
func NewType(cfg *types.Chain33Config) *IssuanceType {
c := &IssuanceType{}
c.SetChild(c)
c.SetConfig(cfg)
return c
}
// GetName 获取执行器名称
func (issuance *IssuanceType) GetName() string {
return IssuanceX
}
// GetLogMap method
func (issuance *IssuanceType) GetLogMap() map[int64]*types.LogInfo {
return map[int64]*types.LogInfo{
TyLogIssuanceCreate: {Ty: reflect.TypeOf(ReceiptIssuance{}), Name: "LogIssuanceCreate"},
TyLogIssuanceDebt: {Ty: reflect.TypeOf(ReceiptIssuance{}), Name: "LogIssuanceDebt"},
TyLogIssuanceRepay: {Ty: reflect.TypeOf(ReceiptIssuance{}), Name: "LogIssuanceRepay"},
TyLogIssuanceFeed: {Ty: reflect.TypeOf(ReceiptIssuance{}), Name: "LogIssuanceFeed"},
TyLogIssuanceClose: {Ty: reflect.TypeOf(ReceiptIssuance{}), Name: "LogIssuanceClose"},
}
}
// GetPayload method
func (issuance *IssuanceType) GetPayload() types.Message {
return &IssuanceAction{}
}
// CreateTx method
func (issuance IssuanceType) CreateTx(action string, message json.RawMessage) (*types.Transaction, error) {
llog.Debug("Issuance.CreateTx", "action", action)
cfg := issuance.GetConfig()
if action == "IssuanceCreate" {
var param IssuanceCreateTx
err := json.Unmarshal(message, &param)
if err != nil {
llog.Error("CreateTx", "Error", err)
return nil, types.ErrInvalidParam
}
return CreateRawIssuanceCreateTx(cfg, &param)
} else if action == "IssuanceDebt" {
var param IssuanceDebtTx
err := json.Unmarshal(message, &param)
if err != nil {
llog.Error("CreateTx", "Error", err)
return nil, types.ErrInvalidParam
}
return CreateRawIssuanceDebtTx(cfg, &param)
} else if action == "IssuanceRepay" {
var param IssuanceRepayTx
err := json.Unmarshal(message, &param)
if err != nil {
llog.Error("CreateTx", "Error", err)
return nil, types.ErrInvalidParam
}
return CreateRawIssuanceRepayTx(cfg, &param)
} else if action == "IssuancePriceFeed" {
var param IssuanceFeedTx
err := json.Unmarshal(message, &param)
if err != nil {
llog.Error("CreateTx", "Error", err)
return nil, types.ErrInvalidParam
}
return CreateRawIssuanceFeedTx(cfg, &param)
} else if action == "IssuanceClose" {
var param IssuanceCloseTx
err := json.Unmarshal(message, &param)
if err != nil {
llog.Error("CreateTx", "Error", err)
return nil, types.ErrInvalidParam
}
return CreateRawIssuanceCloseTx(cfg, &param)
} else if action == "IssuanceManage" {
var param IssuanceManageTx
err := json.Unmarshal(message, &param)
if err != nil {
llog.Error("CreateTx", "Error", err)
return nil, types.ErrInvalidParam
}
return CreateRawIssuanceManageTx(cfg, &param)
} else {
return nil, types.ErrNotSupport
}
}
// GetTypeMap method
func (issuance IssuanceType) GetTypeMap() map[string]int32 {
return map[string]int32{
"Create": IssuanceActionCreate,
"Debt": IssuanceActionDebt,
"Repay": IssuanceActionRepay,
"Feed": IssuanceActionFeed,
"Close": IssuanceActionClose,
"Manage": IssuanceActionManage,
}
}
// CreateRawIssuanceCreateTx method
func CreateRawIssuanceCreateTx(cfg *types.Chain33Config, parm *IssuanceCreateTx) (*types.Transaction, error) {
if parm == nil {
llog.Error("CreateRawIssuanceCreateTx", "parm", parm)
return nil, types.ErrInvalidParam
}
v := &IssuanceCreate{
TotalBalance: int64(math.Trunc((parm.TotalBalance+0.0000001)*1e4)) * 1e4,
DebtCeiling: int64(math.Trunc((parm.DebtCeiling+0.0000001)*1e4)) * 1e4,
LiquidationRatio: int64(math.Trunc((parm.LiquidationRatio + 0.0000001) * 1e4)),
Period: parm.Period,
}
create := &IssuanceAction{
Ty: IssuanceActionCreate,
Value: &IssuanceAction_Create{v},
}
tx := &types.Transaction{
Execer: []byte(cfg.ExecName(IssuanceX)),
Payload: types.Encode(create),
Fee: parm.Fee,
To: address.ExecAddress(cfg.ExecName(IssuanceX)),
}
name := cfg.ExecName(IssuanceX)
tx, err := types.FormatTx(cfg, name, tx)
if err != nil {
return nil, err
}
return tx, nil
}
// CreateRawIssuanceDebtTx method
func CreateRawIssuanceDebtTx(cfg *types.Chain33Config, parm *IssuanceDebtTx) (*types.Transaction, error) {
if parm == nil {
llog.Error("CreateRawIssuanceBorrowTx", "parm", parm)
return nil, types.ErrInvalidParam
}
v := &IssuanceDebt{
IssuanceId: parm.IssuanceID,
Value: int64(math.Trunc((parm.Value+0.0000001)*1e4)) * 1e4,
}
debt := &IssuanceAction{
Ty: IssuanceActionDebt,
Value: &IssuanceAction_Debt{v},
}
tx := &types.Transaction{
Execer: []byte(cfg.ExecName(IssuanceX)),
Payload: types.Encode(debt),
Fee: parm.Fee,
To: address.ExecAddress(cfg.ExecName(IssuanceX)),
}
name := cfg.ExecName(IssuanceX)
tx, err := types.FormatTx(cfg, name, tx)
if err != nil {
return nil, err
}
return tx, nil
}
// CreateRawIssuanceRepayTx method
func CreateRawIssuanceRepayTx(cfg *types.Chain33Config, parm *IssuanceRepayTx) (*types.Transaction, error) {
if parm == nil {
llog.Error("CreateRawIssuanceRepayTx", "parm", parm)
return nil, types.ErrInvalidParam
}
v := &IssuanceRepay{
IssuanceId: parm.IssuanceID,
DebtId: parm.DebtID,
}
repay := &IssuanceAction{
Ty: IssuanceActionRepay,
Value: &IssuanceAction_Repay{v},
}
tx := &types.Transaction{
Execer: []byte(cfg.ExecName(IssuanceX)),
Payload: types.Encode(repay),
Fee: parm.Fee,
To: address.ExecAddress(cfg.ExecName(IssuanceX)),
}
name := cfg.ExecName(IssuanceX)
tx, err := types.FormatTx(cfg, name, tx)
if err != nil {
return nil, err
}
return tx, nil
}
// CreateRawIssuanceFeedTx method
func CreateRawIssuanceFeedTx(cfg *types.Chain33Config, parm *IssuanceFeedTx) (*types.Transaction, error) {
if parm == nil {
llog.Error("CreateRawIssuancePriceFeedTx", "parm", parm)
return nil, types.ErrInvalidParam
}
v := &IssuanceFeed{
Volume: parm.Volume,
}
for _, r := range parm.Price {
v.Price = append(v.Price, int64(math.Trunc(r*1e4)))
}
feed := &IssuanceAction{
Ty: IssuanceActionFeed,
Value: &IssuanceAction_Feed{v},
}
tx := &types.Transaction{
Execer: []byte(cfg.ExecName(IssuanceX)),
Payload: types.Encode(feed),
Fee: parm.Fee,
To: address.ExecAddress(cfg.ExecName(IssuanceX)),
}
name := cfg.ExecName(IssuanceX)
tx, err := types.FormatTx(cfg, name, tx)
if err != nil {
return nil, err
}
return tx, nil
}
// CreateRawIssuanceCloseTx method
func CreateRawIssuanceCloseTx(cfg *types.Chain33Config, parm *IssuanceCloseTx) (*types.Transaction, error) {
if parm == nil {
llog.Error("CreateRawIssuanceCloseTx", "parm", parm)
return nil, types.ErrInvalidParam
}
v := &IssuanceClose{
IssuanceId: parm.IssuanceID,
}
close := &IssuanceAction{
Ty: IssuanceActionClose,
Value: &IssuanceAction_Close{v},
}
tx := &types.Transaction{
Execer: []byte(cfg.ExecName(IssuanceX)),
Payload: types.Encode(close),
Fee: parm.Fee,
To: address.ExecAddress(cfg.ExecName(IssuanceX)),
}
name := cfg.ExecName(IssuanceX)
tx, err := types.FormatTx(cfg, name, tx)
if err != nil {
return nil, err
}
return tx, nil
}
// CreateRawIssuanceManageTx method
func CreateRawIssuanceManageTx(cfg *types.Chain33Config, parm *IssuanceManageTx) (*types.Transaction, error) {
if parm == nil {
llog.Error("CreateRawIssuanceManageTx", "parm", parm)
return nil, types.ErrInvalidParam
}
v := &IssuanceManage{SuperAddrs: parm.Addr}
manage := &IssuanceAction{
Ty: IssuanceActionManage,
Value: &IssuanceAction_Manage{v},
}
tx := &types.Transaction{
Execer: []byte(cfg.ExecName(IssuanceX)),
Payload: types.Encode(manage),
Fee: parm.Fee,
To: address.ExecAddress(cfg.ExecName(IssuanceX)),
}
name := cfg.ExecName(IssuanceX)
tx, err := types.FormatTx(cfg, name, tx)
if err != nil {
return nil, err
}
return tx, nil
}
This diff is collapsed.
package types
import (
"fmt"
"github.com/33cn/chain33/common/db"
"github.com/33cn/chain33/common/db/table"
"github.com/33cn/chain33/types"
)
var opt = &table.Option{
Prefix: "LODB-issuance",
Name: "issuer",
Primary: "issuanceid",
Index: []string{"status"},
}
//NewTable 新建表
func NewIssuanceTable(kvdb db.KV) *table.Table {
rowmeta := NewIssuanceRow()
table, err := table.NewTable(rowmeta, kvdb, opt)
if err != nil {
panic(err)
}
return table
}
//IssuanceRow table meta 结构
type IssuanceRow struct {
*ReceiptIssuanceID
}
//NewIssuanceRow 新建一个meta 结构
func NewIssuanceRow() *IssuanceRow {
return &IssuanceRow{ReceiptIssuanceID: &ReceiptIssuanceID{}}
}
//CreateRow 新建数据行
func (tx *IssuanceRow) CreateRow() *table.Row {
return &table.Row{Data: &ReceiptIssuanceID{}}
}
//SetPayload 设置数据
func (tx *IssuanceRow) SetPayload(data types.Message) error {
if txdata, ok := data.(*ReceiptIssuanceID); ok {
tx.ReceiptIssuanceID = txdata
return nil
}
return types.ErrTypeAsset
}
//Get 按照indexName 查询 indexValue
func (tx *IssuanceRow) Get(key string) ([]byte, error) {
if key == "issuanceid" {
return []byte(tx.IssuanceId), nil
} else if key == "status" {
return []byte(fmt.Sprintf("%2d", tx.Status)), nil
}
return nil, types.ErrNotFound
}
var optRecord = &table.Option{
Prefix: "LODB-issuance",
Name: "debt",
Primary: "debtid",
Index: []string{"status", "addr", "addr_status"},
}
// NewRecordTable 大户发行记录表
func NewRecordTable(kvdb db.KV) *table.Table {
rowmeta := NewRecordRow()
table, err := table.NewTable(rowmeta, kvdb, optRecord)
if err != nil {
panic(err)
}
return table
}
//IssuanceRow table meta 结构
type IssuanceRecordRow struct {
*ReceiptIssuance
}
//NewIssuanceRow 新建一个meta 结构
func NewRecordRow() *IssuanceRecordRow {
return &IssuanceRecordRow{ReceiptIssuance: &ReceiptIssuance{}}
}
//CreateRow 新建数据行
func (tx *IssuanceRecordRow) CreateRow() *table.Row {
return &table.Row{Data: &ReceiptIssuance{}}
}
//SetPayload 设置数据
func (tx *IssuanceRecordRow) SetPayload(data types.Message) error {
if txdata, ok := data.(*ReceiptIssuance); ok {
tx.ReceiptIssuance = txdata
return nil
}
return types.ErrTypeAsset
}
//Get 按照indexName 查询 indexValue
func (tx *IssuanceRecordRow) Get(key string) ([]byte, error) {
if key == "debtid" {
return []byte(tx.DebtId), nil
} else if key == "status" {
return []byte(fmt.Sprintf("%2d", tx.Status)), nil
} else if key == "addr" {
return []byte(tx.AccountAddr), nil
} else if key == "addr_status" {
return []byte(fmt.Sprintf("%s:%2d", tx.AccountAddr, tx.Status)), nil
}
return nil, types.ErrNotFound
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package types
// IssuanceCreateTx for construction
type IssuanceCreateTx struct {
DebtCeiling float64 `json:"debtCeiling"`
LiquidationRatio float64 `json:"liquidationRatio"`
Period int64 `json:"period"`
TotalBalance float64 `json:"totalBalance"`
Fee int64 `json:"fee"`
}
// IssuanceDebtTx for construction
type IssuanceDebtTx struct {
IssuanceID string `json:"issuanceId"`
Value float64 `json:"value"`
Fee int64 `json:"fee"`
}
// IssuanceRepayTx for construction
type IssuanceRepayTx struct {
IssuanceID string `json:"issuanceId"`
DebtID string `json:"debtId"`
Fee int64 `json:"fee"`
}
// IssuanceFeedTx for construction
type IssuanceFeedTx struct {
Price []float64 `json:"price"`
Volume []int64 `json:"volume"`
Fee int64 `json:"fee"`
}
// IssuanceCloseTx for construction
type IssuanceCloseTx struct {
IssuanceID string `json:"issuanceId"`
Fee int64 `json:"fee"`
}
// IssuanceManageTx for construction
type IssuanceManageTx struct {
Addr []string `json:"addr"`
Fee int64 `json:"fee"`
}
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package types
//Issuance op
const (
IssuanceActionCreate = 1 + iota // 创建借贷
IssuanceActionDebt // 大户抵押
IssuanceActionRepay // 大户清算
IssuanceActionFeed // 发行合约喂价
IssuanceActionClose // 关闭借贷
IssuanceActionManage // 借贷管理
//log for Issuance
TyLogIssuanceCreate = 741
TyLogIssuanceDebt = 742
TyLogIssuanceRepay = 743
TyLogIssuanceFeed = 745
TyLogIssuanceClose = 746
)
// Issuance name
const (
IssuanceX = "issuance"
CCNYTokenName = "CCNY"
IssuancePreLiquidationRatio = 11000 //TODO 预清算比例,抵押物价值跌到借出ccny价值110%的时候开始清算
)
//Issuance status
const (
IssuanceStatusCreated = 1 + iota
IssuanceStatusClose
)
const (
IssuanceUserStatusCreate = 1 + iota
IssuanceUserStatusWarning
IssuanceUserStatusSystemLiquidate
IssuanceUserStatusExpire
IssuanceUserStatusExpireLiquidate
IssuanceUserStatusClose
)
const (
PriceFeedKey = "issuance-price-feed"
GuarantorKey = "issuance-guarantor"
ManageKey = "issuance-manage"
)
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