Commit 100bcc22 authored by mdj33's avatar mdj33 Committed by vipwzw

coin precision support configure

parent 45329fb6
......@@ -408,8 +408,8 @@ func (client *commitMsgClient) isSync() bool {
func (client *commitMsgClient) getSendingTx(startHeight, endHeight int64) (*types.Transaction, int64) {
count := endHeight - startHeight
if count > types.TxGroupMaxCount {
count = types.TxGroupMaxCount
if count > int64(types.MaxTxGroupSize) {
count = int64(types.MaxTxGroupSize)
}
status, err := client.getNodeStatus(startHeight+1, startHeight+count)
if err != nil {
......@@ -706,7 +706,7 @@ func (client *commitMsgClient) getNodeStatus(start, end int64) ([]*pt.ParacrossN
//2,如果20个块都是 commit tx的空块,20个块打包一次发送,尽量减少commit tx造成的空块
//3,如果形如xxoxx的块排列,x代表commit空块,o代表实际的块,即只要不全部是commit块,也要全部打包一起发出去
//如果=0 意味着全部是paracross commit tx,延迟发送
if needSentTxs == 0 && len(ret) < types.TxGroupMaxCount {
if needSentTxs == 0 && len(ret) < int(types.MaxTxGroupSize) {
plog.Debug("para commitmsg all self-consensus commit tx,send delay", "start", start, "end", end)
return nil, nil
}
......
......@@ -7,9 +7,10 @@ package commands
import (
"encoding/json"
"fmt"
"os"
commandtypes "github.com/33cn/chain33/system/dapp/commands/types"
"github.com/pkg/errors"
"os"
"strings"
......
......@@ -7,9 +7,10 @@ package commands
import (
"encoding/json"
"fmt"
"github.com/pkg/errors"
"os"
"github.com/pkg/errors"
"strings"
jsonrpc "github.com/33cn/chain33/rpc/jsonclient"
......
......@@ -26,17 +26,18 @@ const (
minPublicPeriod int32 = 17280 * 7
// 最大公示周期
maxPublicPeriod int32 = 17280 * 14
// 最小重大项目阈值
minLargeProjectAmount = types.Coin * 100 * 10000
// 最大重大项目阈值
maxLargeProjectAmount = types.Coin * 300 * 10000
// 最小提案金
minProposalAmount = types.Coin * 20
// 最大提案金
maxProposalAmount = types.Coin * 2000
// 最小重大项目阈值(coin)
minLargeProjectAmount = 100 * 10000
// 最大重大项目阈值(coin)
maxLargeProjectAmount = 300 * 10000
// 最小提案金(coin)
minProposalAmount = 20
// 最大提案金(coin)
maxProposalAmount = 2000
)
func (a *action) propRule(prob *auty.ProposalRule) (*types.Receipt, error) {
cfg := a.api.GetConfig()
//如果全小于等于0,则说明该提案规则参数不正确
if prob.RuleCfg == nil || prob.RuleCfg.BoardApproveRatio <= 0 && prob.RuleCfg.PubOpposeRatio <= 0 &&
prob.RuleCfg.ProposalAmount <= 0 && prob.RuleCfg.LargeProjectAmount <= 0 && prob.RuleCfg.PublicPeriod <= 0 {
......@@ -46,8 +47,8 @@ func (a *action) propRule(prob *auty.ProposalRule) (*types.Receipt, error) {
if (prob.RuleCfg.BoardApproveRatio > 0 && (prob.RuleCfg.BoardApproveRatio > maxBoardApproveRatio || prob.RuleCfg.BoardApproveRatio < minBoardApproveRatio)) ||
(prob.RuleCfg.PubOpposeRatio > 0 && (prob.RuleCfg.PubOpposeRatio > maxPubOpposeRatio || prob.RuleCfg.PubOpposeRatio < minPubOpposeRatio)) ||
(prob.RuleCfg.PublicPeriod > 0 && (prob.RuleCfg.PublicPeriod > maxPublicPeriod || prob.RuleCfg.PublicPeriod < minPublicPeriod)) ||
(prob.RuleCfg.LargeProjectAmount > 0 && (prob.RuleCfg.LargeProjectAmount > maxLargeProjectAmount || prob.RuleCfg.LargeProjectAmount < minLargeProjectAmount)) ||
(prob.RuleCfg.ProposalAmount > 0 && (prob.RuleCfg.ProposalAmount > maxProposalAmount || prob.RuleCfg.ProposalAmount < minProposalAmount)) {
(prob.RuleCfg.LargeProjectAmount > 0 && (prob.RuleCfg.LargeProjectAmount > maxLargeProjectAmount*cfg.GetCoinPrecision() || prob.RuleCfg.LargeProjectAmount < minLargeProjectAmount*cfg.GetCoinPrecision())) ||
(prob.RuleCfg.ProposalAmount > 0 && (prob.RuleCfg.ProposalAmount > maxProposalAmount*cfg.GetCoinPrecision() || prob.RuleCfg.ProposalAmount < minProposalAmount*cfg.GetCoinPrecision())) {
alog.Error("propRule RuleCfg invaild", "ruleCfg", prob.RuleCfg)
return nil, types.ErrInvalidParam
}
......
......@@ -22,8 +22,8 @@ import (
const (
testBoardApproveRatio int32 = 60
testPubOpposeRatio int32 = 35
testProposalAmount = minProposalAmount * 2
testLargeProjectAmount = minLargeProjectAmount * 2
testProposalAmount = minProposalAmount * types.DefaultCoinPrecision * 2
testLargeProjectAmount = minLargeProjectAmount * 2 * types.DefaultCoinPrecision
testPublicPeriod = minPublicPeriod
)
......@@ -39,8 +39,8 @@ func TestPropRule(t *testing.T) {
RuleCfg: &auty.RuleConfig{
BoardApproveRatio: maxBoardApproveRatio,
PubOpposeRatio: maxPubOpposeRatio,
ProposalAmount: maxProposalAmount,
LargeProjectAmount: maxLargeProjectAmount,
ProposalAmount: maxProposalAmount * types.DefaultCoinPrecision,
LargeProjectAmount: maxLargeProjectAmount * types.DefaultCoinPrecision,
PublicPeriod: maxPublicPeriod,
},
StartBlockHeight: env.blockHeight + 5,
......@@ -50,8 +50,8 @@ func TestPropRule(t *testing.T) {
RuleCfg: &auty.RuleConfig{
BoardApproveRatio: minBoardApproveRatio,
PubOpposeRatio: minPubOpposeRatio,
ProposalAmount: minProposalAmount,
LargeProjectAmount: minLargeProjectAmount,
ProposalAmount: minProposalAmount * types.DefaultCoinPrecision,
LargeProjectAmount: minLargeProjectAmount * types.DefaultCoinPrecision,
PublicPeriod: minPublicPeriod,
},
StartBlockHeight: env.blockHeight + 5,
......@@ -61,8 +61,8 @@ func TestPropRule(t *testing.T) {
RuleCfg: &auty.RuleConfig{
BoardApproveRatio: minBoardApproveRatio - 1,
PubOpposeRatio: minPubOpposeRatio - 1,
ProposalAmount: minProposalAmount - 1,
LargeProjectAmount: minLargeProjectAmount - 1,
ProposalAmount: minProposalAmount*types.DefaultCoinPrecision - 1,
LargeProjectAmount: minLargeProjectAmount*types.DefaultCoinPrecision - 1,
PublicPeriod: minPublicPeriod - 1,
},
StartBlockHeight: env.blockHeight + 5,
......@@ -72,8 +72,8 @@ func TestPropRule(t *testing.T) {
RuleCfg: &auty.RuleConfig{
BoardApproveRatio: maxBoardApproveRatio + 1,
PubOpposeRatio: maxPubOpposeRatio + 1,
ProposalAmount: maxProposalAmount + 1,
LargeProjectAmount: maxLargeProjectAmount + 1,
ProposalAmount: maxProposalAmount*types.DefaultCoinPrecision + 1,
LargeProjectAmount: maxLargeProjectAmount*types.DefaultCoinPrecision + 1,
PublicPeriod: maxPublicPeriod + 1,
},
StartBlockHeight: env.blockHeight + 5,
......@@ -83,8 +83,8 @@ func TestPropRule(t *testing.T) {
RuleCfg: &auty.RuleConfig{
BoardApproveRatio: 1,
PubOpposeRatio: minPubOpposeRatio + 1,
ProposalAmount: minProposalAmount + 1,
LargeProjectAmount: minLargeProjectAmount + 1,
ProposalAmount: minProposalAmount*types.DefaultCoinPrecision + 1,
LargeProjectAmount: minLargeProjectAmount*types.DefaultCoinPrecision + 1,
PublicPeriod: minPublicPeriod + 1,
},
StartBlockHeight: env.blockHeight + 5,
......
......@@ -5,9 +5,14 @@
package commands
import (
"fmt"
"os"
"strconv"
"strings"
cmdtypes "github.com/33cn/chain33/system/dapp/commands/types"
"github.com/pkg/errors"
"github.com/33cn/chain33/common"
jsonrpc "github.com/33cn/chain33/rpc/jsonclient"
rpctypes "github.com/33cn/chain33/rpc/types"
......@@ -66,15 +71,20 @@ func blackwhiteCreate(cmd *cobra.Command, args []string) {
fee, _ := cmd.Flags().GetFloat64("fee")
feeInt64 := int64(fee * 1e4)
amountInt64 := int64(amount)
if timeout == 0 {
timeout = 10
}
timeout = 60 * timeout
cfg, err := cmdtypes.GetChainConfig(rpcLaddr)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "GetChainConfig"))
return
}
params := &gt.BlackwhiteCreateTxReq{
PlayAmount: amountInt64 * types.Coin,
PlayAmount: int64(amount) * cfg.CoinPrecision,
PlayerCount: int32(playerCount),
Timeout: timeout,
GameName: gameName,
......@@ -121,6 +131,11 @@ func blackwhitePlay(cmd *cobra.Command, args []string) {
secret, _ := cmd.Flags().GetString("secret")
fee, _ := cmd.Flags().GetFloat64("fee")
cfg, err := cmdtypes.GetChainConfig(rpcLaddr)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "GetChainConfig"))
return
}
blacks := strings.Split(isBlackStr, "-")
var hashValues [][]byte
......@@ -134,10 +149,10 @@ func blackwhitePlay(cmd *cobra.Command, args []string) {
}
feeInt64 := int64(fee * 1e4)
amountInt64 := int64(amount)
params := &gt.BlackwhitePlayTxReq{
GameID: gameID,
Amount: amountInt64 * types.Coin,
Amount: int64(amount) * cfg.CoinPrecision,
HashValues: hashValues,
Fee: feeInt64,
}
......
......@@ -7,6 +7,8 @@ package executor
import (
"math"
"github.com/pkg/errors"
"bytes"
"strconv"
......@@ -20,14 +22,14 @@ import (
)
const (
maxAmount int64 = 100 * types.Coin
minAmount int64 = 1 * types.Coin
maxAmount int64 = 100
minAmount int64 = 1
minPlayerCount int32 = 3
maxPlayerCount int32 = 100000
lockAmount int64 = types.Coin / 100 //创建者锁定金额
showTimeout int64 = 60 * 5 // 公布密钥超时时间
maxPlayTimeout int64 = 60 * 60 * 24 // 创建交易之后最大超时时间
minPlayTimeout int64 = 60 * 10 // 创建交易之后最小超时时间
lockAmount int64 = 100 //创建者锁定金额 types.coins/lockAmount
showTimeout int64 = 60 * 5 // 公布密钥超时时间
maxPlayTimeout int64 = 60 * 60 * 24 // 创建交易之后最大超时时间
minPlayTimeout int64 = 60 * 10 // 创建交易之后最小超时时间
white = "0"
black = "1"
......@@ -65,7 +67,8 @@ func newAction(t *Blackwhite, tx *types.Transaction, index int32) *action {
}
func (a *action) Create(create *gt.BlackwhiteCreate) (*types.Receipt, error) {
if create.PlayAmount < minAmount || create.PlayAmount > maxAmount {
cfg := a.api.GetConfig()
if create.PlayAmount < minAmount*cfg.GetCoinPrecision() || create.PlayAmount > maxAmount*cfg.GetCoinPrecision() {
return nil, types.ErrAmount
}
if create.PlayerCount < minPlayerCount || create.PlayerCount > maxPlayerCount {
......@@ -75,9 +78,13 @@ func (a *action) Create(create *gt.BlackwhiteCreate) (*types.Receipt, error) {
return nil, types.ErrInvalidParam
}
receipt, err := a.coinsAccount.ExecFrozen(a.fromaddr, a.execaddr, lockAmount)
if cfg.GetCoinPrecision() < lockAmount {
return nil, errors.Wrapf(types.ErrInvalidParam, "coinPrecison=%d < lockAmount=100", cfg.GetCoinPrecision())
}
receipt, err := a.coinsAccount.ExecFrozen(a.fromaddr, a.execaddr, cfg.GetCoinPrecision()/lockAmount)
if err != nil {
clog.Error("blackwhite create ", "addr", a.fromaddr, "execaddr", a.execaddr, "ExecFrozen amount", lockAmount)
clog.Error("blackwhite create ", "addr", a.fromaddr, "execaddr", a.execaddr, "ExecFrozen amount", cfg.GetCoinPrecision()/lockAmount)
return nil, err
}
......@@ -296,6 +303,7 @@ func (a *action) TimeoutDone(done *gt.BlackwhiteTimeoutDone) (*types.Receipt, er
var logs []*types.ReceiptLog
var kv []*types.KeyValue
cfg := a.api.GetConfig()
// 检查当前状态
if gt.BlackwhiteStatusPlay == round.Status {
if a.blocktime >= round.Timeout+round.CreateTime {
......@@ -317,13 +325,16 @@ func (a *action) TimeoutDone(done *gt.BlackwhiteTimeoutDone) (*types.Receipt, er
logs = append(logs, receipt.Logs...)
kv = append(kv, receipt.KV...)
}
if cfg.GetCoinPrecision() < lockAmount {
return nil, errors.Wrapf(types.ErrInvalidParam, "coinPrecison=%d < lockAmount=100", cfg.GetCoinPrecision())
}
// 将创建游戏者解冻
receipt, err := a.coinsAccount.ExecActive(round.CreateAddr, a.execaddr, lockAmount)
receipt, err := a.coinsAccount.ExecActive(round.CreateAddr, a.execaddr, cfg.GetCoinPrecision()/lockAmount)
if err != nil {
for _, addrR := range round.AddrResult {
a.coinsAccount.ExecFrozen(addrR.Addr, a.execaddr, addrR.Amount)
}
clog.Error("blackwhite timeout done", "addr", round.CreateAddr, "execaddr", a.execaddr, "execActive create lockAmount", lockAmount, "err", err)
clog.Error("blackwhite timeout done", "addr", round.CreateAddr, "execaddr", a.execaddr, "execActive create lockAmount", cfg.GetCoinPrecision()/lockAmount, "err", err)
return nil, err
}
logs = append(logs, receipt.Logs...)
......@@ -364,7 +375,6 @@ func (a *action) TimeoutDone(done *gt.BlackwhiteTimeoutDone) (*types.Receipt, er
key1 := calcMavlRoundKey(round.GameID)
value1 := types.Encode(&round)
cfg := a.api.GetConfig()
if cfg.IsDappFork(a.height, gt.BlackwhiteX, "ForkBlackWhiteV2") {
//将当前游戏状态保存,便于同一区块中游戏参数的累加
a.db.Set(key1, value1)
......@@ -492,8 +502,12 @@ func (a *action) StatTransfer(round *gt.BlackwhiteRound) (*types.Receipt, error)
round.Winner = append(round.Winner, winer.addr)
}
cfg := a.api.GetConfig()
if cfg.GetCoinPrecision() < lockAmount {
return nil, errors.Wrapf(types.ErrInvalidParam, "coinPrecison=%d < lockAmount=100", cfg.GetCoinPrecision())
}
// 将创建游戏者解冻
receipt, err := a.coinsAccount.ExecActive(round.CreateAddr, a.execaddr, lockAmount)
receipt, err := a.coinsAccount.ExecActive(round.CreateAddr, a.execaddr, cfg.GetCoinPrecision()/lockAmount)
if err != nil {
// rollback
if len(winers) == 0 {
......@@ -512,7 +526,7 @@ func (a *action) StatTransfer(round *gt.BlackwhiteRound) (*types.Receipt, error)
a.coinsAccount.ExecFrozen(loser.addr, a.execaddr, loser.amount)
}
}
clog.Error("StatTransfer ExecActive create ExecFrozen ", "addr", round.CreateAddr, "execaddr", a.execaddr, "amount", lockAmount)
clog.Error("StatTransfer ExecActive create ExecFrozen ", "addr", round.CreateAddr, "execaddr", a.execaddr, "amount", cfg.GetCoinPrecision()/lockAmount)
return nil, err
}
logs = append(logs, receipt.Logs...)
......
......@@ -27,8 +27,7 @@ const (
//setting
const (
Coin = types.Coin // 1e8
DefaultDebtCeiling = 10000 * Coin // 默认借贷限额
DefaultDebtCeiling = 10000 // 默认借贷限额
DefaultLiquidationRatio = 0.4 * 1e4 // 默认质押比
DefaultStabilityFeeRation = 0.08 * 1e4 // 默认稳定费
DefaultPeriod = 3600 * 24 * 365 // 默认合约限期
......@@ -255,9 +254,10 @@ func (action *Action) CollateralizeManage(manage *pty.CollateralizeManage) (*typ
}
manConfig, _ := getCollateralizeConfig(action.db)
cfg := action.Collateralize.GetAPI().GetConfig()
if manConfig == nil {
manConfig = &pty.CollateralizeManage{
DebtCeiling: DefaultDebtCeiling,
DebtCeiling: DefaultDebtCeiling * cfg.GetCoinPrecision(),
LiquidationRatio: DefaultLiquidationRatio,
StabilityFeeRatio: DefaultStabilityFeeRation,
Period: DefaultPeriod,
......
......@@ -12,8 +12,10 @@ import (
"os"
"time"
cmdtypes "github.com/33cn/chain33/system/dapp/commands/types"
"github.com/pkg/errors"
"encoding/json"
"strconv"
"strings"
"github.com/33cn/chain33/common"
......@@ -154,6 +156,12 @@ func evmBalance(cmd *cobra.Command, args []string) {
return
}
cfg, err := cmdtypes.GetChainConfig(rpcLaddr)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "GetChainConfig"))
return
}
var addrs []string
addrs = append(addrs, addr)
params := types.ReqBalance{
......@@ -163,8 +171,8 @@ func evmBalance(cmd *cobra.Command, args []string) {
}
var res []*rpctypes.Account
ctx := jsonclient.NewRPCCtx(rpcLaddr, "Chain33.GetBalance", params, &res)
ctx.SetResultCb(parseGetBalanceRes)
ctx.Run()
ctx.SetResultCbExt(parseGetBalanceRes)
ctx.RunExt(cfg)
}
// AccountResult 账户余额查询出来之后进行单位转换
......@@ -179,10 +187,11 @@ type AccountResult struct {
Addr string `json:"addr,omitempty"`
}
func parseGetBalanceRes(arg interface{}) (interface{}, error) {
res := *arg.(*[]*rpctypes.Account)
balanceResult := strconv.FormatFloat(float64(res[0].Balance)/float64(types.Coin), 'f', 4, 64)
frozenResult := strconv.FormatFloat(float64(res[0].Frozen)/float64(types.Coin), 'f', 4, 64)
func parseGetBalanceRes(arg ...interface{}) (interface{}, error) {
res := *arg[0].(*[]*rpctypes.Account)
cfg := arg[1].(*rpctypes.ChainConfigInfo)
balanceResult := types.FormatAmount2FloatDisplay(res[0].Balance, cfg.CoinPrecision, true)
frozenResult := types.FormatAmount2FloatDisplay(res[0].Frozen, cfg.CoinPrecision, true)
result := &AccountResult{
Addr: res[0].Addr,
Currency: res[0].Currency,
......
......@@ -58,6 +58,7 @@ func (e *exchange) CheckTx(tx *types.Transaction, index int) error {
//发送交易的时候就检查payload,做严格的参数检查
var exchange exchangetypes.ExchangeAction
types.Decode(tx.GetPayload(), &exchange)
cfg := e.GetAPI().GetConfig()
if exchange.Ty == exchangetypes.TyLimitOrderAction {
limitOrder := exchange.GetLimitOrder()
left := limitOrder.GetLeftAsset()
......@@ -65,13 +66,13 @@ func (e *exchange) CheckTx(tx *types.Transaction, index int) error {
price := limitOrder.GetPrice()
amount := limitOrder.GetAmount()
op := limitOrder.GetOp()
if !CheckExchangeAsset(e.GetAPI().GetConfig().GetCoinExec(), left, right) {
if !CheckExchangeAsset(cfg.GetCoinExec(), left, right) {
return exchangetypes.ErrAsset
}
if !CheckPrice(price) {
return exchangetypes.ErrAssetPrice
}
if !CheckAmount(amount) {
if !CheckAmount(amount, cfg.GetCoinPrecision()) {
return exchangetypes.ErrAssetAmount
}
if !CheckOp(op) {
......
......@@ -895,7 +895,7 @@ func TestKV(t *testing.T) {
}
func TestSafeMul(t *testing.T) {
t.Log(SafeMul(1e8, 1e7))
t.Log(SafeMul(1e10, 1e16))
t.Log(SafeMul(1e7, 1e6))
t.Log(SafeMul(1e8, 1e7, types.DefaultCoinPrecision))
t.Log(SafeMul(1e10, 1e16, types.DefaultCoinPrecision))
t.Log(SafeMul(1e7, 1e6, types.DefaultCoinPrecision))
}
......@@ -55,9 +55,9 @@ func (a *Action) OpSwap(op int32) int32 {
}
//CalcActualCost 计算实际花费
func CalcActualCost(op int32, amount int64, price int64) int64 {
func CalcActualCost(op int32, amount int64, price, coinPrecision int64) int64 {
if op == et.OpBuy {
return SafeMul(amount, price)
return SafeMul(amount, price, coinPrecision)
}
return amount
}
......@@ -83,9 +83,9 @@ func CheckCount(count int32) bool {
return count <= 20 && count >= 0
}
//CheckAmount 最小交易1e8
func CheckAmount(amount int64) bool {
if amount < types.Coin || amount >= types.MaxCoin {
//CheckAmount 最小交易 1coin
func CheckAmount(amount, coinPrecision int64) bool {
if amount < coinPrecision || amount >= types.MaxCoin {
return false
}
return true
......@@ -124,10 +124,11 @@ func (a *Action) LimitOrder(payload *et.LimitOrder) (*types.Receipt, error) {
rightAsset := payload.GetRightAsset()
//TODO 参数要合法,必须有严格的校验,后面统一加入到checkTx里面
//coins执行器下面只有bty
if !CheckExchangeAsset(a.api.GetConfig().GetCoinExec(), leftAsset, rightAsset) {
cfg := a.api.GetConfig()
if !CheckExchangeAsset(cfg.GetCoinExec(), leftAsset, rightAsset) {
return nil, et.ErrAsset
}
if !CheckAmount(payload.GetAmount()) {
if !CheckAmount(payload.GetAmount(), cfg.GetCoinPrecision()) {
return nil, et.ErrAssetAmount
}
if !CheckPrice(payload.GetPrice()) {
......@@ -137,7 +138,6 @@ func (a *Action) LimitOrder(payload *et.LimitOrder) (*types.Receipt, error) {
return nil, et.ErrAssetOp
}
//TODO 这里symbol
cfg := a.api.GetConfig()
leftAssetDB, err := account.NewAccountDB(cfg, leftAsset.GetExecer(), leftAsset.GetSymbol(), a.statedb)
if err != nil {
return nil, err
......@@ -148,7 +148,7 @@ func (a *Action) LimitOrder(payload *et.LimitOrder) (*types.Receipt, error) {
}
//先检查账户余额
if payload.GetOp() == et.OpBuy {
amount := SafeMul(payload.GetAmount(), payload.GetPrice())
amount := SafeMul(payload.GetAmount(), payload.GetPrice(), cfg.GetCoinPrecision())
rightAccount := rightAssetDB.LoadExecAccount(a.fromaddr, a.execaddr)
if rightAccount.Balance < amount {
elog.Error("limit check right balance", "addr", a.fromaddr, "avail", rightAccount.Balance, "need", amount)
......@@ -197,7 +197,7 @@ func (a *Action) RevokeOrder(payload *et.RevokeOrder) (*types.Receipt, error) {
if err != nil {
return nil, err
}
amount := CalcActualCost(et.OpBuy, balance, price)
amount := CalcActualCost(et.OpBuy, balance, price, cfg.GetCoinPrecision())
rightAccount := rightAssetDB.LoadExecAccount(a.fromaddr, a.execaddr)
if rightAccount.Frozen < amount {
elog.Error("revoke check right frozen", "addr", a.fromaddr, "avail", rightAccount.Frozen, "amount", amount)
......@@ -216,7 +216,7 @@ func (a *Action) RevokeOrder(payload *et.RevokeOrder) (*types.Receipt, error) {
if err != nil {
return nil, err
}
amount := CalcActualCost(et.OpSell, balance, price)
amount := CalcActualCost(et.OpSell, balance, price, cfg.GetCoinPrecision())
leftAccount := leftAssetDB.LoadExecAccount(a.fromaddr, a.execaddr)
if leftAccount.Frozen < amount {
elog.Error("revoke check left frozen", "addr", a.fromaddr, "avail", leftAccount.Frozen, "amount", amount)
......@@ -259,6 +259,7 @@ func (a *Action) matchLimitOrder(payload *et.LimitOrder, leftAccountDB, rightAcc
var priceKey string
var count int
cfg := a.api.GetConfig()
or := &et.Order{
OrderID: a.GetIndex(),
Value: &et.Order_LimitOrder{LimitOrder: payload},
......@@ -355,7 +356,7 @@ func (a *Action) matchLimitOrder(payload *et.LimitOrder, leftAccountDB, rightAcc
//未完成的订单需要冻结剩余未成交的资金
if payload.Op == et.OpBuy {
amount := CalcActualCost(et.OpBuy, or.Balance, payload.Price)
amount := CalcActualCost(et.OpBuy, or.Balance, payload.Price, cfg.GetCoinPrecision())
receipt, err := rightAccountDB.ExecFrozen(a.fromaddr, a.execaddr, amount)
if err != nil {
elog.Error("LimitOrder.ExecFrozen", "addr", a.fromaddr, "amount", amount, "err", err.Error())
......@@ -365,7 +366,7 @@ func (a *Action) matchLimitOrder(payload *et.LimitOrder, leftAccountDB, rightAcc
kvs = append(kvs, receipt.KV...)
}
if payload.Op == et.OpSell {
amount := CalcActualCost(et.OpSell, or.Balance, payload.Price)
amount := CalcActualCost(et.OpSell, or.Balance, payload.Price, cfg.GetCoinPrecision())
receipt, err := leftAccountDB.ExecFrozen(a.fromaddr, a.execaddr, amount)
if err != nil {
elog.Error("LimitOrder.ExecFrozen", "addr", a.fromaddr, "amount", amount, "err", err.Error())
......@@ -398,9 +399,10 @@ func (a *Action) matchModel(leftAccountDB, rightAccountDB *account.DB, payload *
elog.Info("try match", "activeId", or.OrderID, "passiveId", matchorder.OrderID, "activeAddr", or.Addr, "passiveAddr",
matchorder.Addr, "amount", matched, "price", payload.Price)
cfg := a.api.GetConfig()
if payload.Op == et.OpSell {
//转移冻结资产
amount := CalcActualCost(matchorder.GetLimitOrder().Op, matched, payload.Price)
amount := CalcActualCost(matchorder.GetLimitOrder().Op, matched, payload.Price, cfg.GetCoinPrecision())
receipt, err := rightAccountDB.ExecTransferFrozen(matchorder.Addr, a.fromaddr, a.execaddr, amount)
if err != nil {
elog.Error("matchModel.ExecTransferFrozen", "from", matchorder.Addr, "to", a.fromaddr, "amount", amount, "err", err)
......@@ -410,7 +412,7 @@ func (a *Action) matchModel(leftAccountDB, rightAccountDB *account.DB, payload *
kvs = append(kvs, receipt.KV...)
//解冻多余资金
if payload.Price < matchorder.GetLimitOrder().Price {
amount := CalcActualCost(matchorder.GetLimitOrder().Op, matched, matchorder.GetLimitOrder().Price-payload.Price)
amount := CalcActualCost(matchorder.GetLimitOrder().Op, matched, matchorder.GetLimitOrder().Price-payload.Price, cfg.GetCoinPrecision())
receipt, err := rightAccountDB.ExecActive(matchorder.Addr, a.execaddr, amount)
if err != nil {
elog.Error("matchModel.ExecActive", "addr", matchorder.Addr, "amount", amount, "err", err.Error())
......@@ -420,7 +422,7 @@ func (a *Action) matchModel(leftAccountDB, rightAccountDB *account.DB, payload *
kvs = append(kvs, receipt.KV...)
}
//将达成交易的相应资产结算
amount = CalcActualCost(payload.Op, matched, payload.Price)
amount = CalcActualCost(payload.Op, matched, payload.Price, cfg.GetCoinPrecision())
receipt, err = leftAccountDB.ExecTransfer(a.fromaddr, matchorder.Addr, a.execaddr, amount)
if err != nil {
elog.Error("matchModel.ExecTransfer", "from", a.fromaddr, "to", matchorder.Addr, "amount", amount, "err", err.Error())
......@@ -436,7 +438,7 @@ func (a *Action) matchModel(leftAccountDB, rightAccountDB *account.DB, payload *
}
if payload.Op == et.OpBuy {
//转移冻结资产
amount := CalcActualCost(matchorder.GetLimitOrder().Op, matched, matchorder.GetLimitOrder().Price)
amount := CalcActualCost(matchorder.GetLimitOrder().Op, matched, matchorder.GetLimitOrder().Price, cfg.GetCoinPrecision())
receipt, err := leftAccountDB.ExecTransferFrozen(matchorder.Addr, a.fromaddr, a.execaddr, amount)
if err != nil {
elog.Error("matchModel.ExecTransferFrozen2", "from", matchorder.Addr, "to", a.fromaddr, "amount", amount, "err", err.Error())
......@@ -445,7 +447,7 @@ func (a *Action) matchModel(leftAccountDB, rightAccountDB *account.DB, payload *
logs = append(logs, receipt.Logs...)
kvs = append(kvs, receipt.KV...)
//将达成交易的相应资产结算
amount = CalcActualCost(payload.Op, matched, matchorder.GetLimitOrder().Price)
amount = CalcActualCost(payload.Op, matched, matchorder.GetLimitOrder().Price, cfg.GetCoinPrecision())
receipt, err = rightAccountDB.ExecTransfer(a.fromaddr, matchorder.Addr, a.execaddr, amount)
if err != nil {
elog.Error("matchModel.ExecTransfer2", "from", a.fromaddr, "to", matchorder.Addr, "amount", amount, "err", err.Error())
......@@ -681,9 +683,9 @@ func queryMarketDepth(localdb dbm.KV, left, right *et.Asset, op int32, price int
}
//SafeMul math库中的安全大数乘法,防溢出
func SafeMul(x, y int64) int64 {
func SafeMul(x, y, coinPrecision int64) int64 {
res := big.NewInt(0).Mul(big.NewInt(x), big.NewInt(y))
res = big.NewInt(0).Div(res, big.NewInt(types.Coin))
res = big.NewInt(0).Div(res, big.NewInt(coinPrecision))
return res.Int64()
}
......
......@@ -269,7 +269,7 @@ func testPlaceLimitOrder(t *testing.T, req *et.LimitOrder, addr string, privkey
assert.Nil(t, err)
t.Log(tokenAfter)
cost := executor.CalcActualCost(req.Op, req.Amount, req.Price)
cost := executor.CalcActualCost(req.Op, req.Amount, req.Price, types.DefaultCoinPrecision)
t.Log(req.Amount, req.Price, cost)
// bty/ccny
if req.Op == et.OpBuy {
......@@ -315,7 +315,7 @@ func testRevokeLimitOrder(t *testing.T, orderID int64, addr string, privkey stri
assert.Nil(t, err)
t.Log(tokenAfter)
cost := executor.CalcActualCost(lo.Op, order.Balance, lo.Price)
cost := executor.CalcActualCost(lo.Op, order.Balance, lo.Price, types.DefaultCoinPrecision)
// bty/ccny
if lo.Op == et.OpBuy {
// bty
......
......@@ -7,6 +7,10 @@ package commands
import (
"encoding/json"
"fmt"
"os"
cmdtypes "github.com/33cn/chain33/system/dapp/commands/types"
"github.com/pkg/errors"
"github.com/33cn/chain33/rpc/jsonclient"
rpctypes "github.com/33cn/chain33/rpc/types"
......@@ -59,9 +63,6 @@ func addHashlockLockCmdFlags(cmd *cobra.Command) {
}
func hashlockLockCmd(cmd *cobra.Command, args []string) {
title, _ := cmd.Flags().GetString("title")
cfg := types.GetCliSysParam(title)
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
secret, _ := cmd.Flags().GetString("secret")
toAddr, _ := cmd.Flags().GetString("to")
......@@ -69,18 +70,31 @@ func hashlockLockCmd(cmd *cobra.Command, args []string) {
delay, _ := cmd.Flags().GetInt64("delay")
amount, _ := cmd.Flags().GetFloat64("amount")
defaultFee := float64(cfg.GetMinTxFeeRate()) / float64(types.Coin)
fee, _ := cmd.Flags().GetFloat64("fee")
if fee < defaultFee {
fee = defaultFee
cfg, err := cmdtypes.GetChainConfig(rpcLaddr)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "GetChainConfig"))
return
}
fee, _ := cmd.Flags().GetFloat64("fee")
if delay < 60 {
fmt.Println("delay period changed to 60")
delay = 60
}
amountInt64 := int64(amount*types.InputPrecision) * types.Multiple1E4
feeInt64 := int64(fee*types.InputPrecision) * types.Multiple1E4
amountInt64, err := types.FormatFloatDisplay2Value(amount, cfg.CoinPrecision)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "FormatFloatDisplay2Value.amount"))
return
}
feeInt64, err := types.FormatFloatDisplay2Value(fee, cfg.CoinPrecision)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "FormatFloatDisplay2Value.fee"))
return
}
if feeInt64 < cfg.MinTxFeeRate {
feeInt64 = cfg.MinTxFeeRate
}
params := pty.HashlockLockTx{
Secret: secret,
Amount: amountInt64,
......@@ -123,19 +137,25 @@ func addHashlockCmdFlags(cmd *cobra.Command) {
}
func hashlockUnlockCmd(cmd *cobra.Command, args []string) {
title, _ := cmd.Flags().GetString("title")
cfg := types.GetCliSysParam(title)
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
secret, _ := cmd.Flags().GetString("secret")
defaultFee := float64(cfg.GetMinTxFeeRate()) / float64(types.Coin)
cfg, err := cmdtypes.GetChainConfig(rpcLaddr)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "GetChainConfig"))
return
}
fee, _ := cmd.Flags().GetFloat64("fee")
if fee < defaultFee {
fee = defaultFee
feeInt64, err := types.FormatFloatDisplay2Value(fee, cfg.CoinPrecision)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "FormatFloatDisplay2Value.fee"))
return
}
if feeInt64 < cfg.MinTxFeeRate {
feeInt64 = cfg.MinTxFeeRate
}
feeInt64 := int64(fee*types.InputPrecision) * types.Multiple1E4
params := pty.HashlockUnlockTx{
Secret: secret,
Fee: feeInt64,
......@@ -166,19 +186,24 @@ func HashlockSendCmd() *cobra.Command {
}
func hashlockSendCmd(cmd *cobra.Command, args []string) {
title, _ := cmd.Flags().GetString("title")
cfg := types.GetCliSysParam(title)
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
secret, _ := cmd.Flags().GetString("secret")
defaultFee := float64(cfg.GetMinTxFeeRate()) / float64(types.Coin)
fee, _ := cmd.Flags().GetFloat64("fee")
if fee < defaultFee {
fee = defaultFee
cfg, err := cmdtypes.GetChainConfig(rpcLaddr)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "GetChainConfig"))
return
}
feeInt64 := int64(fee*types.InputPrecision) * types.Multiple1E4
fee, _ := cmd.Flags().GetFloat64("fee")
feeInt64, err := types.FormatFloatDisplay2Value(fee, cfg.CoinPrecision)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "FormatFloatDisplay2Value.fee"))
return
}
if feeInt64 < cfg.MinTxFeeRate {
feeInt64 = cfg.MinTxFeeRate
}
params := pty.HashlockSendTx{
Secret: secret,
Fee: feeInt64,
......
......@@ -25,8 +25,7 @@ const (
//setting
const (
Coin = types.Coin // 1e8
DefaultDebtCeiling = 100000 * Coin // 默认借贷限额
DefaultDebtCeiling = 100000 // 默认借贷限额
DefaultLiquidationRatio = 0.25 * 1e4 // 默认质押比
DefaultPeriod = 3600 * 24 * 365 // 默认合约限期
PriceWarningRate = 1.3 * 1e4 // 价格提前预警率
......@@ -355,6 +354,7 @@ func (action *Action) IssuanceCreate(create *pty.IssuanceCreate) (*types.Receipt
var kv []*types.KeyValue
var receipt *types.Receipt
cfg := action.Issuance.GetAPI().GetConfig()
// 是否配置管理用户
if !isRightAddr(pty.FundKey, action.fromaddr, action.db) {
clog.Error("IssuanceCreate", "addr", action.fromaddr, "error", "Address has no permission to create")
......@@ -405,7 +405,7 @@ func (action *Action) IssuanceCreate(create *pty.IssuanceCreate) (*types.Receipt
if create.DebtCeiling != 0 {
issu.DebtCeiling = create.DebtCeiling
} else {
issu.DebtCeiling = DefaultDebtCeiling
issu.DebtCeiling = DefaultDebtCeiling * cfg.GetCoinPrecision()
}
if create.Period != 0 {
issu.Period = create.Period
......
......@@ -50,7 +50,6 @@ const (
const (
luckyNumMol = 100000
decimal = types.Coin //1e8
blockNum = 5
)
......@@ -358,7 +357,7 @@ func (action *Action) LotteryBuy(buy *pty.LotteryBuy) (*types.Receipt, error) {
Once ExecTransfer succeed, ExecFrozen succeed, no roolback needed
**********/
receipt, err := action.coinsAccount.ExecTransfer(action.fromaddr, lott.CreateAddr, action.execaddr, buy.GetAmount()*decimal)
receipt, err := action.coinsAccount.ExecTransfer(action.fromaddr, lott.CreateAddr, action.execaddr, buy.GetAmount()*cfg.GetCoinPrecision())
if err != nil {
llog.Error("LotteryBuy.ExecTransfer", "addr", action.fromaddr, "execaddr", action.execaddr, "amount", buy.GetAmount())
return nil, err
......@@ -366,7 +365,7 @@ func (action *Action) LotteryBuy(buy *pty.LotteryBuy) (*types.Receipt, error) {
logs = append(logs, receipt.Logs...)
kv = append(kv, receipt.KV...)
receipt, err = action.coinsAccount.ExecFrozen(lott.CreateAddr, action.execaddr, buy.GetAmount()*decimal)
receipt, err = action.coinsAccount.ExecFrozen(lott.CreateAddr, action.execaddr, buy.GetAmount()*cfg.GetCoinPrecision())
if err != nil {
llog.Error("LotteryBuy.Frozen", "addr", lott.CreateAddr, "execaddr", action.execaddr, "amount", buy.GetAmount())
......@@ -503,16 +502,17 @@ func (action *Action) LotteryClose(draw *pty.LotteryClose) (*types.Receipt, erro
}
llog.Debug("LotteryClose", "totalReturn", totalReturn)
cfg := action.api.GetConfig()
if totalReturn > 0 {
if !action.CheckExecAccount(lott.CreateAddr, decimal*totalReturn, true) {
if !action.CheckExecAccount(lott.CreateAddr, cfg.GetCoinPrecision()*totalReturn, true) {
return nil, pty.ErrLotteryFundNotEnough
}
for _, recs := range lott.PurRecords {
if recs.AmountOneRound > 0 {
receipt, err := action.coinsAccount.ExecTransferFrozen(lott.CreateAddr, recs.Addr, action.execaddr,
decimal*recs.AmountOneRound)
cfg.GetCoinPrecision()*recs.AmountOneRound)
if err != nil {
return nil, err
}
......@@ -621,11 +621,11 @@ func (action *Action) checkDraw(lott *LotteryDB) (*types.Receipt, *pty.LotteryUp
}
llog.Debug("checkDraw", "lenofupdate", len(updateInfo.BuyInfo), "update", updateInfo.BuyInfo)
var factor = decimal
var factor = action.api.GetConfig().GetCoinPrecision()
if totalFund > 0 {
if totalFund > lott.GetFund()/2 {
llog.Debug("checkDraw ajust fund", "lott.Fund", lott.Fund, "totalFund", totalFund)
factor = decimal * (lott.GetFund()) / 2 / (totalFund)
factor = action.api.GetConfig().GetCoinPrecision() * (lott.GetFund()) / 2 / (totalFund)
lott.Fund = lott.Fund / 2
} else {
lott.Fund -= totalFund
......
......@@ -6,14 +6,15 @@ package commands
import (
"fmt"
commandtypes "github.com/33cn/chain33/system/dapp/commands/types"
"github.com/pkg/errors"
"math"
"os"
"strconv"
"strings"
"time"
commandtypes "github.com/33cn/chain33/system/dapp/commands/types"
"github.com/pkg/errors"
"github.com/33cn/chain33/rpc/jsonclient"
rpctypes "github.com/33cn/chain33/rpc/types"
"github.com/33cn/chain33/types"
......@@ -706,8 +707,8 @@ func parseAccInfo(view ...interface{}) (interface{}, error) {
var dailyLimitResults []*mty.DailyLimitResult
for _, dailyLimit := range res.DailyLimits {
dailyLimt := types.GetFormatFloat(int64(dailyLimit.DailyLimit), cfg.CoinPrecision, true)
spentToday := types.GetFormatFloat(int64(dailyLimit.SpentToday), cfg.CoinPrecision, true)
dailyLimt := types.FormatAmount2FloatDisplay(int64(dailyLimit.DailyLimit), cfg.CoinPrecision, true)
spentToday := types.FormatAmount2FloatDisplay(int64(dailyLimit.SpentToday), cfg.CoinPrecision, true)
dailyLimitResult := &mty.DailyLimitResult{
Symbol: dailyLimit.Symbol,
Execer: dailyLimit.Execer,
......@@ -984,7 +985,7 @@ func parseUnSpentToday(view ...interface{}) (interface{}, error) {
var result []*mty.UnSpentAssetsResult
for _, unSpentAssets := range res.UnSpentAssets {
amountResult := types.GetFormatFloat(int64(unSpentAssets.Amount), cfg.CoinPrecision, true)
amountResult := types.FormatAmount2FloatDisplay(int64(unSpentAssets.Amount), cfg.CoinPrecision, true)
unSpentAssetsResult := &mty.UnSpentAssetsResult{
Execer: unSpentAssets.Assets.Execer,
Symbol: unSpentAssets.Assets.Symbol,
......@@ -1052,7 +1053,7 @@ func getMultiSigAccAssets(cmd *cobra.Command, args []string) {
params.Payload = types.MustPBToJSON(&req)
rep = &mty.ReplyAccAssets{}
ctx := jsonclient.NewRPCCtx(rpcLaddr, "Chain33.Query", params, rep)
ctx.RunExt(parseAccAssets)
ctx.SetResultCbExt(parseAccAssets)
ctx.RunExt(cfg)
}
......@@ -1062,9 +1063,9 @@ func parseAccAssets(view ...interface{}) (interface{}, error) {
var result []*mty.AccAssetsResult
for _, accAssets := range res.AccAssets {
balanceResult := types.GetFormatFloat(accAssets.Account.Balance, cfg.CoinPrecision, true)
frozenResult := types.GetFormatFloat(accAssets.Account.Frozen, cfg.CoinPrecision, true)
receiverResult := types.GetFormatFloat(accAssets.RecvAmount, cfg.CoinPrecision, true)
balanceResult := types.FormatAmount2FloatDisplay(accAssets.Account.Balance, cfg.CoinPrecision, true)
frozenResult := types.FormatAmount2FloatDisplay(accAssets.Account.Frozen, cfg.CoinPrecision, true)
receiverResult := types.FormatAmount2FloatDisplay(accAssets.RecvAmount, cfg.CoinPrecision, true)
accAssetsResult := &mty.AccAssetsResult{
Execer: accAssets.Assets.Execer,
......
......@@ -41,8 +41,8 @@ func NewMainAccount(cfg *types.Chain33Config, paraTitle, paraExecName, paraSymbo
}
func assetDepositBalance(acc *account.DB, addr string, amount int64) (*types.Receipt, error) {
if !types.CheckAmount(amount) {
return nil, types.ErrAmount
if err := acc.CheckAmount(amount); err != nil {
return nil, err
}
acc1 := acc.LoadAccount(addr)
copyacc := *acc1
......@@ -66,8 +66,8 @@ func assetDepositBalance(acc *account.DB, addr string, amount int64) (*types.Rec
}
func assetWithdrawBalance(acc *account.DB, addr string, amount int64) (*types.Receipt, error) {
if !types.CheckAmount(amount) {
return nil, types.ErrAmount
if err := acc.CheckAmount(amount); err != nil {
return nil, err
}
acc1 := acc.LoadAccount(addr)
if acc1.Balance-amount < 0 {
......
......@@ -6,8 +6,12 @@ package cmd
import (
"fmt"
"os"
"strconv"
cmdtypes "github.com/33cn/chain33/system/dapp/commands/types"
"github.com/pkg/errors"
jsonrpc "github.com/33cn/chain33/rpc/jsonclient"
rpctypes "github.com/33cn/chain33/rpc/types"
"github.com/33cn/chain33/types"
......@@ -54,17 +58,21 @@ func addPokerbullStartFlags(cmd *cobra.Command) {
}
func pokerbullStart(cmd *cobra.Command, args []string) {
title, _ := cmd.Flags().GetString("title")
cfg := types.GetCliSysParam(title)
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
paraName, _ := cmd.Flags().GetString("paraName")
value, _ := cmd.Flags().GetUint64("value")
playerCount, _ := cmd.Flags().GetUint32("playerCount")
cfg, err := cmdtypes.GetChainConfig(rpcLaddr)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "GetChainConfig"))
return
}
params := &rpctypes.CreateTxIn{
Execer: cfg.ExecName(pkt.PokerBullX),
Execer: types.GetExecName(pkt.PokerBullX, paraName),
ActionName: pkt.CreateStartTx,
Payload: []byte(fmt.Sprintf("{\"value\":%d,\"playerNum\":%d}", int64(value)*types.Coin, int32(playerCount))),
Payload: []byte(fmt.Sprintf("{\"value\":%d,\"playerNum\":%d}", int64(value)*cfg.CoinPrecision, int32(playerCount))),
}
var res string
......@@ -163,25 +171,29 @@ func addPokerbullPlayFlags(cmd *cobra.Command) {
}
func pokerbullPlay(cmd *cobra.Command, args []string) {
title, _ := cmd.Flags().GetString("title")
cfg := types.GetCliSysParam(title)
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
gameID, _ := cmd.Flags().GetString("gameID")
round, _ := cmd.Flags().GetUint32("round")
value, _ := cmd.Flags().GetUint64("value")
address, _ := cmd.Flags().GetStringArray("address")
paraName, _ := cmd.Flags().GetString("paraName")
cfg, err := cmdtypes.GetChainConfig(rpcLaddr)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "GetChainConfig"))
return
}
payload := &pkt.PBGamePlay{
GameId: gameID,
Value: int64(value) * types.Coin,
Value: int64(value) * cfg.CoinPrecision,
Round: int32(round),
}
payload.Address = make([]string, len(address))
copy(payload.Address, address)
params := &rpctypes.CreateTxIn{
Execer: cfg.ExecName(pkt.PokerBullX),
Execer: types.GetExecName(pkt.PokerBullX, paraName),
ActionName: pkt.CreatePlayTx,
Payload: types.MustPBToJSON(payload),
}
......
......@@ -6,10 +6,11 @@ package executor
import (
"fmt"
"github.com/33cn/chain33/client"
"sort"
"strconv"
"github.com/33cn/chain33/client"
"strings"
"github.com/33cn/chain33/account"
......
......@@ -76,7 +76,7 @@ func (g *PokerBull) Query_QueryGameByRound(in *pkt.QueryPBGameByRound) (types.Me
}
cfg := g.GetAPI().GetConfig()
winnerReturn := int64((pkt.DeveloperFee + pkt.PlatformFee) * float64(cfg.GetCoinPrecision()))
winnerReturn := int64((1 - (pkt.DeveloperFee + pkt.PlatformFee)) * float64(cfg.GetCoinPrecision()))
gameInfo := &pkt.ReplyPBGameByRound{
GameId: game.GameId,
Status: game.Status,
......@@ -84,7 +84,7 @@ func (g *PokerBull) Query_QueryGameByRound(in *pkt.QueryPBGameByRound) (types.Me
IsWaiting: game.IsWaiting,
Value: game.Value,
Players: roundPlayers,
Return: (game.Value / cfg.GetCoinPrecision()) * (cfg.GetCoinPrecision() - winnerReturn),
Return: (game.Value / cfg.GetCoinPrecision()) * winnerReturn,
}
return gameInfo, nil
......
This diff is collapsed.
......@@ -236,6 +236,7 @@ func (p *privacy) CheckTx(tx *types.Transaction, index int) error {
return pty.ErrRingSign
}
cfg := p.GetAPI().GetConfig()
totalInput := int64(0)
keyinput := input.GetKeyinput()
keyImages := make([][]byte, len(keyinput))
......@@ -253,7 +254,7 @@ func (p *privacy) CheckTx(tx *types.Transaction, index int) error {
if !res {
if errIndex >= 0 && errIndex < int32(len(keyinput)) {
input := keyinput[errIndex]
privacylog.Error("PrivacyTrading CheckTx", "txhash", txhashstr, "UTXO spent already errindex", errIndex, "utxo amout", input.Amount/types.Coin, "utxo keyimage", common.ToHex(input.KeyImage))
privacylog.Error("PrivacyTrading CheckTx", "txhash", txhashstr, "UTXO spent already errindex", errIndex, "utxo amout", input.Amount/cfg.GetCoinPrecision(), "utxo keyimage", common.ToHex(input.KeyImage))
}
privacylog.Error("PrivacyTrading CheckTx", "txhash", txhashstr, "err", "checkUTXOValid failed ")
return pty.ErrDoubleSpendOccur
......@@ -269,7 +270,7 @@ func (p *privacy) CheckTx(tx *types.Transaction, index int) error {
}
//只有主链coins隐私转账才收取特殊交易费, assertExec空情况适配老版本
cfg := p.GetAPI().GetConfig()
if !cfg.IsPara() && (assertExec == "" || assertExec == cfg.GetCoinExec()) {
totalOutput := int64(0)
......
......@@ -95,7 +95,8 @@ func (c *Jrpc) GetPrivacyTxByAddr(in *pty.ReqPrivacyTransactionList, result *int
return err
}
var txdetails rpctypes.WalletTxDetails
err = rpctypes.ConvertWalletTxDetailToJSON(reply.(*types.WalletTxDetails), &txdetails, c.cli.GetConfig().GetCoinExec())
cfg := c.cli.GetConfig()
err = rpctypes.ConvertWalletTxDetailToJSON(reply.(*types.WalletTxDetails), &txdetails, cfg.GetCoinExec(), cfg.GetCoinPrecision())
if err != nil {
return err
}
......
......@@ -61,7 +61,7 @@ func (policy *privacyPolicy) getWalletOperate() wcom.WalletOperate {
// Init 初始化处理
func (policy *privacyPolicy) Init(walletOperate wcom.WalletOperate, sub []byte) {
policy.setWalletOperate(walletOperate)
policy.store = newStore(walletOperate.GetDBStore(), walletOperate.GetAPI().GetConfig().GetCoinExec())
policy.store = newStore(walletOperate.GetDBStore(), walletOperate.GetAPI().GetConfig())
// 启动定时检查超期FTXO的协程
walletOperate.GetWaitGroup().Add(1)
go policy.checkWalletStoreData()
......
......@@ -23,13 +23,13 @@ const (
PRIVACYDBVERSION int64 = 1
)
func newStore(db db.DB, coinsExec string) *privacyStore {
return &privacyStore{Store: wcom.NewStore(db), coinsExec: coinsExec}
func newStore(db db.DB, cfg *types.Chain33Config) *privacyStore {
return &privacyStore{Store: wcom.NewStore(db), Chain33Config: cfg}
}
// privacyStore 隐私交易数据库存储操作类
type privacyStore struct {
coinsExec string
*types.Chain33Config
*wcom.Store
}
......@@ -257,7 +257,7 @@ func (store *privacyStore) getWalletPrivacyTxDetails(param *privacytypes.ReqPriv
return nil, types.ErrUnmarshal
}
txDetail.Txhash = txDetail.GetTx().Hash()
if txDetail.GetTx().IsWithdraw(store.coinsExec) {
if txDetail.GetTx().IsWithdraw(store.Chain33Config.GetCoinExec()) {
//swap from and to
txDetail.Fromaddr, txDetail.Tx.To = txDetail.Tx.To, txDetail.Fromaddr
}
......@@ -556,7 +556,7 @@ func (store *privacyStore) selectCurrentWalletPrivacyTx(txDetal *types.Transacti
}
if assetExec == "" {
assetExec = store.coinsExec
assetExec = store.Chain33Config.GetCoinExec()
}
//处理output
......@@ -659,7 +659,7 @@ func (store *privacyStore) setUTXO(utxoInfo *privacytypes.PrivacyDBStore, txHash
}
outIndex := int(utxoInfo.OutIndex)
utxoKey := calcUTXOKey(txHash, outIndex)
bizlog.Debug("setUTXO", "addr", utxoInfo.Owner, "tx with hash", txHash, "amount:", utxoInfo.Amount/types.Coin)
bizlog.Debug("setUTXO", "addr", utxoInfo.Owner, "tx with hash", txHash, "amount:", utxoInfo.Amount/store.GetCoinPrecision())
newbatch.Set(calcUTXOKey4TokenAddr(utxoInfo.AssetExec, utxoInfo.Tokenname, utxoInfo.Owner, txHash, outIndex), utxoKey)
newbatch.Set(utxoKey, privacyStorebyte)
return nil
......@@ -854,7 +854,7 @@ func (store *privacyStore) moveFTXO2UTXO(key1 []byte, newbatch db.Batch) {
outindex := int(ftxo.UtxoBasic.UtxoGlobalIndex.Outindex)
key := calcUTXOKey4TokenAddr(ftxosInOneTx.AssetExec, ftxosInOneTx.Tokenname, ftxosInOneTx.Sender, utxohash, outindex)
value := calcUTXOKey(utxohash, int(ftxo.UtxoBasic.UtxoGlobalIndex.Outindex))
bizlog.Debug("moveFTXO2UTXO", "addr", ftxosInOneTx.Sender, "tx with hash", utxohash, "amount", ftxo.Amount/types.Coin)
bizlog.Debug("moveFTXO2UTXO", "addr", ftxosInOneTx.Sender, "tx with hash", utxohash, "amount", ftxo.Amount/store.GetCoinPrecision())
newbatch.Set(key, value)
}
bizlog.Debug("moveFTXO2UTXO", "addr", ftxosInOneTx.Sender, "tx with hash", ftxosInOneTx.Txhash)
......
......@@ -27,7 +27,7 @@ func createStore(t *testing.T) *privacyStore {
util.ResetDatadir(mcfg, "$TEMP/")
cfgWallet := mcfg.Wallet
walletStoreDB := dbm.NewDB("wallet", cfgWallet.Driver, cfgWallet.DbPath, cfgWallet.DbCache)
store := newStore(walletStoreDB, "coins")
store := newStore(walletStoreDB, cfg)
assert.NotNil(t, store)
return store
}
......
......@@ -7,11 +7,12 @@ package commands
import (
"encoding/json"
"fmt"
commandtypes "github.com/33cn/chain33/system/dapp/commands/types"
"github.com/pkg/errors"
"os"
"strings"
commandtypes "github.com/33cn/chain33/system/dapp/commands/types"
"github.com/pkg/errors"
"github.com/33cn/chain33/rpc/jsonclient"
rpctypes "github.com/33cn/chain33/rpc/types"
"github.com/33cn/chain33/types"
......@@ -318,10 +319,10 @@ func parseRelayOrders(res ty.ReplyRelayOrders, coinPrecision int64) {
show.Status = order.Status.String()
show.Creator = order.CreaterAddr
show.CoinOperation = order.Operation
show.Amount = types.GetFormatFloat(int64(order.LocalCoinAmount), coinPrecision, true)
show.Amount = types.FormatAmount2FloatDisplay(int64(order.LocalCoinAmount), coinPrecision, true)
show.Coin = order.XCoin
show.CoinAddr = order.XAddr
show.CoinAmount = types.GetFormatFloat(int64(order.XAmount), coinPrecision, true)
show.CoinAmount = types.FormatAmount2FloatDisplay(int64(order.XAmount), coinPrecision, true)
show.CoinWaits = order.XBlockWaits
show.CreateTime = order.CreateTime
show.AcceptAddr = order.AcceptAddr
......
......@@ -7,8 +7,6 @@ package executor
import (
"time"
"strconv"
"github.com/33cn/chain33/account"
"github.com/33cn/chain33/client"
"github.com/33cn/chain33/common"
......@@ -28,10 +26,11 @@ const (
type relayLog struct {
ty.RelayOrder
*types.Chain33Config
}
func newRelayLog(order *ty.RelayOrder) *relayLog {
return &relayLog{*order}
func newRelayLog(order *ty.RelayOrder, cfg *types.Chain33Config) *relayLog {
return &relayLog{RelayOrder: *order, Chain33Config: cfg}
}
func (r *relayLog) save(db dbm.KV) []*types.KeyValue {
......@@ -65,10 +64,10 @@ func (r *relayLog) receiptLog(relayLogType int32) *types.ReceiptLog {
CurStatus: r.Status.String(),
PreStatus: r.PreStatus.String(),
CreaterAddr: r.CreaterAddr,
LocalCoinAmount: strconv.FormatFloat(float64(r.LocalCoinAmount)/float64(types.Coin), 'f', 4, 64),
LocalCoinAmount: types.FormatAmount2FloatDisplay(int64(r.LocalCoinAmount), r.GetCoinPrecision(), true),
CoinOperation: r.Operation,
XCoin: r.XCoin,
XAmount: strconv.FormatFloat(float64(r.XAmount)/float64(types.Coin), 'f', 4, 64),
XAmount: types.FormatAmount2FloatDisplay(int64(r.XAmount), r.GetCoinPrecision(), true),
XAddr: r.XAddr,
XTxHash: r.XTxHash,
XBlockWaits: r.XBlockWaits,
......@@ -200,7 +199,7 @@ func (action *relayDB) create(order *ty.RelayCreate) (*types.Receipt, error) {
logs = append(logs, receipt.Logs...)
kv = append(kv, receipt.KV...)
relayLog := newRelayLog(uOrder)
relayLog := newRelayLog(uOrder, action.api.GetConfig())
sellOrderKV := relayLog.save(action.db)
logs = append(logs, relayLog.receiptLog(ty.TyLogRelayCreate))
kv = append(kv, sellOrderKV...)
......@@ -305,7 +304,7 @@ func (action *relayDB) revokeCreate(revoke *ty.RelayRevoke) (*types.Receipt, err
order.Status = ty.RelayOrderStatus_canceled
}
relayLog := newRelayLog(order)
relayLog := newRelayLog(order, action.api.GetConfig())
orderKV := relayLog.save(action.db)
var logs []*types.ReceiptLog
......@@ -382,7 +381,7 @@ func (action *relayDB) accept(accept *ty.RelayAccept) (*types.Receipt, error) {
logs = append(logs, receipt.Logs...)
kv = append(kv, receipt.KV...)
relayLog := newRelayLog(order)
relayLog := newRelayLog(order, action.api.GetConfig())
sellOrderKV := relayLog.save(action.db)
logs = append(logs, relayLog.receiptLog(ty.TyLogRelayAccept))
......@@ -461,7 +460,7 @@ func (action *relayDB) revokeAccept(revoke *ty.RelayRevoke) (*types.Receipt, err
logs = append(logs, receiptTransfer.Logs...)
kv = append(kv, receiptTransfer.KV...)
}
relayLog := newRelayLog(order)
relayLog := newRelayLog(order, action.api.GetConfig())
sellOrderKV := relayLog.save(action.db)
logs = append(logs, relayLog.receiptLog(ty.TyLogRelayRevokeAccept))
kv = append(kv, sellOrderKV...)
......@@ -518,7 +517,7 @@ func (action *relayDB) confirmTx(confirm *ty.RelayConfirmTx) (*types.Receipt, er
var logs []*types.ReceiptLog
var kv []*types.KeyValue
relayLog := newRelayLog(order)
relayLog := newRelayLog(order, action.api.GetConfig())
sellOrderKV := relayLog.save(action.db)
logs = append(logs, relayLog.receiptLog(ty.TyLogRelayConfirmTx))
kv = append(kv, sellOrderKV...)
......@@ -591,7 +590,7 @@ func (action *relayDB) verifyTx(verify *ty.RelayVerify) (*types.Receipt, error)
order.FinishTime = action.blockTime
order.FinishTxHash = common.ToHex(action.txHash)
relayLog := newRelayLog(order)
relayLog := newRelayLog(order, action.api.GetConfig())
orderKV := relayLog.save(action.db)
var logs []*types.ReceiptLog
......
......@@ -6,6 +6,10 @@ package cmd
import (
"fmt"
"os"
cmdtypes "github.com/33cn/chain33/system/dapp/commands/types"
"github.com/pkg/errors"
jsonrpc "github.com/33cn/chain33/rpc/jsonclient"
rpctypes "github.com/33cn/chain33/rpc/types"
......@@ -64,25 +68,31 @@ func addBakupCmdFlags(cmd *cobra.Command) {
}
func backupCmd(cmd *cobra.Command, args []string) {
title, _ := cmd.Flags().GetString("title")
cfg := types.GetCliSysParam(title)
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
backup, _ := cmd.Flags().GetString("backup")
defaultAddr, _ := cmd.Flags().GetString("default")
delay, _ := cmd.Flags().GetInt64("delay")
defaultFee := float64(cfg.GetMinTxFeeRate()) / float64(types.Coin)
cfg, err := cmdtypes.GetChainConfig(rpcLaddr)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "GetChainConfig"))
return
}
fee, _ := cmd.Flags().GetFloat64("fee")
if fee < defaultFee {
fee = defaultFee
feeInt64, err := types.FormatFloatDisplay2Value(fee, cfg.CoinPrecision)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "FormatFloatDisplay2Value.fee"))
return
}
if feeInt64 < cfg.MinTxFeeRate {
feeInt64 = cfg.MinTxFeeRate
}
if delay < 60 {
fmt.Println("delay period changed to 60")
delay = 60
}
feeInt64 := int64(fee*types.InputPrecision) * types.Multiple1E4
params := rpc.RetrieveBackupTx{
BackupAddr: backup,
DefaultAddr: defaultAddr,
......@@ -126,20 +136,26 @@ func addPerformCmdFlags(cmd *cobra.Command) {
}
func prepareCmd(cmd *cobra.Command, args []string) {
title, _ := cmd.Flags().GetString("title")
cfg := types.GetCliSysParam(title)
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
backup, _ := cmd.Flags().GetString("backup")
defaultAddr, _ := cmd.Flags().GetString("default")
defaultFee := float64(cfg.GetMinTxFeeRate()) / float64(types.Coin)
cfg, err := cmdtypes.GetChainConfig(rpcLaddr)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "GetChainConfig"))
return
}
fee, _ := cmd.Flags().GetFloat64("fee")
if fee < defaultFee {
fee = defaultFee
feeInt64, err := types.FormatFloatDisplay2Value(fee, cfg.CoinPrecision)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "FormatFloatDisplay2Value.fee"))
return
}
if feeInt64 < cfg.MinTxFeeRate {
feeInt64 = cfg.MinTxFeeRate
}
feeInt64 := int64(fee*types.InputPrecision) * types.Multiple1E4
params := rpc.RetrievePrepareTx{
BackupAddr: backup,
DefaultAddr: defaultAddr,
......@@ -161,23 +177,29 @@ func PerformCmd() *cobra.Command {
}
func performCmd(cmd *cobra.Command, args []string) {
title, _ := cmd.Flags().GetString("title")
cfg := types.GetCliSysParam(title)
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
backup, _ := cmd.Flags().GetString("backup")
defaultAddr, _ := cmd.Flags().GetString("default")
defaultFee := float64(cfg.GetMinTxFeeRate()) / float64(types.Coin)
cfg, err := cmdtypes.GetChainConfig(rpcLaddr)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "GetChainConfig"))
return
}
fee, _ := cmd.Flags().GetFloat64("fee")
if fee < defaultFee {
fee = defaultFee
feeInt64, err := types.FormatFloatDisplay2Value(fee, cfg.CoinPrecision)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "FormatFloatDisplay2Value.fee"))
return
}
if feeInt64 < cfg.MinTxFeeRate {
feeInt64 = cfg.MinTxFeeRate
}
execs, _ := cmd.Flags().GetStringArray("exec")
symbols, _ := cmd.Flags().GetStringArray("symbol")
feeInt64 := int64(fee*types.InputPrecision) * types.Multiple1E4
params := rpc.RetrievePerformTx{
BackupAddr: backup,
DefaultAddr: defaultAddr,
......@@ -208,20 +230,26 @@ func CancelCmd() *cobra.Command {
}
func cancelCmd(cmd *cobra.Command, args []string) {
title, _ := cmd.Flags().GetString("title")
cfg := types.GetCliSysParam(title)
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
backup, _ := cmd.Flags().GetString("backup")
defaultAddr, _ := cmd.Flags().GetString("default")
defaultFee := float64(cfg.GetMinTxFeeRate()) / float64(types.Coin)
cfg, err := cmdtypes.GetChainConfig(rpcLaddr)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "GetChainConfig"))
return
}
fee, _ := cmd.Flags().GetFloat64("fee")
if fee < defaultFee {
fee = defaultFee
feeInt64, err := types.FormatFloatDisplay2Value(fee, cfg.CoinPrecision)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "FormatFloatDisplay2Value.fee"))
return
}
if feeInt64 < cfg.MinTxFeeRate {
feeInt64 = cfg.MinTxFeeRate
}
feeInt64 := int64(fee*types.InputPrecision) * types.Multiple1E4
params := rpc.RetrieveCancelTx{
BackupAddr: backup,
DefaultAddr: defaultAddr,
......
......@@ -61,7 +61,7 @@ func (g *channelClient) CreateBindMiner(ctx context.Context, in *ty.ReqBindMiner
if len(balances) == 0 {
return nil, types.ErrInvalidParam
}
if balances[0].Balance < in.Amount+2*types.Coin {
if balances[0].Balance < in.Amount+2*cfg.GetCoinPrecision() {
return nil, types.ErrNoBalance
}
}
......
......@@ -8,9 +8,11 @@ import (
"encoding/json"
"fmt"
"os"
"strconv"
"strings"
cmdtypes "github.com/33cn/chain33/system/dapp/commands/types"
"github.com/pkg/errors"
"github.com/33cn/chain33/rpc/jsonclient"
rpctypes "github.com/33cn/chain33/rpc/types"
"github.com/33cn/chain33/system/dapp/commands"
......@@ -146,6 +148,13 @@ func GetTokensPreCreatedCmd() *cobra.Command {
func getPreCreatedTokens(cmd *cobra.Command, args []string) {
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
paraName, _ := cmd.Flags().GetString("paraName")
cfg, err := cmdtypes.GetChainConfig(rpcLaddr)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "GetChainConfig"))
return
}
var reqtokens tokenty.ReqTokens
reqtokens.Status = tokenty.TokenStatusPreCreated
reqtokens.QueryAll = true
......@@ -166,8 +175,8 @@ func getPreCreatedTokens(cmd *cobra.Command, args []string) {
}
for _, preCreatedToken := range res.Tokens {
preCreatedToken.Price = preCreatedToken.Price / types.Coin
preCreatedToken.Total = preCreatedToken.Total / types.TokenPrecision
preCreatedToken.Price = preCreatedToken.Price / cfg.CoinPrecision
preCreatedToken.Total = preCreatedToken.Total / cfg.TokenPrecision
data, err := json.MarshalIndent(preCreatedToken, "", " ")
if err != nil {
......@@ -192,6 +201,13 @@ func GetTokensCreatedCmd() *cobra.Command {
func getFinishCreatedTokens(cmd *cobra.Command, args []string) {
rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
paraName, _ := cmd.Flags().GetString("paraName")
cfg, err := cmdtypes.GetChainConfig(rpcLaddr)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "GetChainConfig"))
return
}
var reqtokens tokenty.ReqTokens
reqtokens.Status = tokenty.TokenStatusCreated
reqtokens.QueryAll = true
......@@ -212,8 +228,8 @@ func getFinishCreatedTokens(cmd *cobra.Command, args []string) {
}
for _, createdToken := range res.Tokens {
createdToken.Price = createdToken.Price / types.Coin
createdToken.Total = createdToken.Total / types.TokenPrecision
createdToken.Price = createdToken.Price / cfg.CoinPrecision
createdToken.Total = createdToken.Total / cfg.TokenPrecision
//fmt.Printf("---The %dth Finish Created token is below--------------------\n", i)
data, err := json.MarshalIndent(createdToken, "", " ")
......@@ -250,6 +266,13 @@ func tokenAssets(cmd *cobra.Command, args []string) {
paraName, _ := cmd.Flags().GetString("paraName")
addr, _ := cmd.Flags().GetString("addr")
execer, _ := cmd.Flags().GetString("exec")
cfg, err := cmdtypes.GetChainConfig(rpcLaddr)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "GetChainConfig"))
return
}
execer = getRealExecName(paraName, execer)
req := tokenty.ReqAccountTokenAssets{
Address: addr,
......@@ -262,16 +285,18 @@ func tokenAssets(cmd *cobra.Command, args []string) {
var res tokenty.ReplyAccountTokenAssets
ctx := jsonclient.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res)
ctx.SetResultCb(parseTokenAssetsRes)
ctx.Run()
ctx.SetResultCbExt(parseTokenAssetsRes)
ctx.RunExt(cfg)
}
func parseTokenAssetsRes(arg interface{}) (interface{}, error) {
res := arg.(*tokenty.ReplyAccountTokenAssets)
func parseTokenAssetsRes(arg ...interface{}) (interface{}, error) {
res := arg[0].(*tokenty.ReplyAccountTokenAssets)
cfg := arg[1].(*rpctypes.ChainConfigInfo)
var result []*tokenty.TokenAccountResult
for _, ta := range res.TokenAssets {
balanceResult := strconv.FormatFloat(float64(ta.Account.Balance)/float64(types.TokenPrecision), 'f', 4, 64)
frozenResult := strconv.FormatFloat(float64(ta.Account.Frozen)/float64(types.TokenPrecision), 'f', 4, 64)
balanceResult := types.FormatAmount2FloatDisplay(ta.Account.Balance, cfg.TokenPrecision, true)
frozenResult := types.FormatAmount2FloatDisplay(ta.Account.Frozen, cfg.TokenPrecision, true)
tokenAccount := &tokenty.TokenAccountResult{
Token: ta.Symbol,
Addr: ta.Account.Addr,
......@@ -312,6 +337,12 @@ func tokenBalance(cmd *cobra.Command, args []string) {
token, _ := cmd.Flags().GetString("symbol")
execer, _ := cmd.Flags().GetString("exec")
paraName, _ := cmd.Flags().GetString("paraName")
cfg, err := cmdtypes.GetChainConfig(rpcLaddr)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "GetChainConfig"))
return
}
execer = getRealExecName(paraName, execer)
addresses := strings.Split(addr, " ")
params := tokenty.ReqTokenBalance{
......@@ -321,16 +352,18 @@ func tokenBalance(cmd *cobra.Command, args []string) {
}
var res []*rpctypes.Account
ctx := jsonclient.NewRPCCtx(rpcLaddr, "token.GetTokenBalance", params, &res)
ctx.SetResultCb(parseTokenBalanceRes)
ctx.Run()
ctx.SetResultCbExt(parseTokenBalanceRes)
ctx.RunExt(cfg)
}
func parseTokenBalanceRes(arg interface{}) (interface{}, error) {
res := arg.(*[]*rpctypes.Account)
func parseTokenBalanceRes(arg ...interface{}) (interface{}, error) {
res := arg[0].(*[]*rpctypes.Account)
cfg := arg[1].(*rpctypes.ChainConfigInfo)
var result []*tokenty.TokenAccountResult
for _, one := range *res {
balanceResult := strconv.FormatFloat(float64(one.Balance)/float64(types.TokenPrecision), 'f', 4, 64)
frozenResult := strconv.FormatFloat(float64(one.Frozen)/float64(types.TokenPrecision), 'f', 4, 64)
balanceResult := types.FormatAmount2FloatDisplay(one.Balance, cfg.TokenPrecision, true)
frozenResult := types.FormatAmount2FloatDisplay(one.Frozen, cfg.TokenPrecision, true)
tokenAccount := &tokenty.TokenAccountResult{
Token: tokenSymbol,
Addr: one.Addr,
......@@ -388,14 +421,24 @@ func tokenPrecreated(cmd *cobra.Command, args []string) {
total, _ := cmd.Flags().GetInt64("total")
category, _ := cmd.Flags().GetInt32("category")
priceInt64 := int64((price + 0.000001) * 1e4)
cfg, err := cmdtypes.GetChainConfig(rpcLaddr)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "GetChainConfig"))
return
}
priceInt64, err := types.FormatFloatDisplay2Value(price, cfg.CoinPrecision)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "FormatFloatDisplay2Value"))
return
}
params := &tokenty.TokenPreCreate{
Price: priceInt64 * 1e4,
Price: priceInt64,
Name: name,
Symbol: symbol,
Introduction: introduction,
Owner: ownerAddr,
Total: total * types.TokenPrecision,
Total: total * cfg.TokenPrecision,
Category: category,
}
ctx := jsonclient.NewRPCCtx(rpcLaddr, "token.CreateRawTokenPreCreateTx", params, nil)
......
......@@ -6,11 +6,12 @@ package commands
import (
"fmt"
commandtypes "github.com/33cn/chain33/system/dapp/commands/types"
"github.com/pkg/errors"
"os"
"strings"
commandtypes "github.com/33cn/chain33/system/dapp/commands/types"
"github.com/pkg/errors"
jsonrpc "github.com/33cn/chain33/rpc/jsonclient"
rpctypes "github.com/33cn/chain33/rpc/types"
"github.com/33cn/chain33/types"
......@@ -220,8 +221,8 @@ func parseSellOrders(arg ...interface{}) (interface{}, error) {
TotalBoardlot: o.TotalBoardlot,
TradedBoardlot: o.TradedBoardlot,
}
order.AmountPerBoardlot = types.GetFormatFloat(o.AmountPerBoardlot, cfg.CoinPrecision, true)
order.PricePerBoardlot = types.GetFormatFloat(o.PricePerBoardlot, cfg.CoinPrecision, true)
order.AmountPerBoardlot = types.FormatAmount2FloatDisplay(o.AmountPerBoardlot, cfg.CoinPrecision, true)
order.PricePerBoardlot = types.FormatAmount2FloatDisplay(o.PricePerBoardlot, cfg.CoinPrecision, true)
result.SellOrders = append(result.SellOrders, order)
}
return result, nil
......@@ -392,8 +393,8 @@ func parseBuyOrders(arg ...interface{}) (interface{}, error) {
TotalBoardlot: o.TotalBoardlot,
TradedBoardlot: o.TradedBoardlot,
}
order.AmountPerBoardlot = types.GetFormatFloat(o.AmountPerBoardlot, cfg.CoinPrecision, true)
order.PricePerBoardlot = types.GetFormatFloat(o.PricePerBoardlot, cfg.CoinPrecision, true)
order.AmountPerBoardlot = types.FormatAmount2FloatDisplay(o.AmountPerBoardlot, cfg.CoinPrecision, true)
order.PricePerBoardlot = types.FormatAmount2FloatDisplay(o.PricePerBoardlot, cfg.CoinPrecision, true)
result.BuyOrders = append(result.BuyOrders, order)
}
return result, nil
......@@ -472,8 +473,8 @@ func parseTradeOrders(arg ...interface{}) (interface{}, error) {
TotalBoardlot: o.TotalBoardlot,
TradedBoardlot: o.TradedBoardlot,
}
order.AmountPerBoardlot = types.GetFormatFloat(o.AmountPerBoardlot, cfg.CoinPrecision, true)
order.PricePerBoardlot = types.GetFormatFloat(o.PricePerBoardlot, cfg.CoinPrecision, true)
order.AmountPerBoardlot = types.FormatAmount2FloatDisplay(o.AmountPerBoardlot, cfg.CoinPrecision, true)
order.PricePerBoardlot = types.FormatAmount2FloatDisplay(o.PricePerBoardlot, cfg.CoinPrecision, true)
result.Orders = append(result.Orders, order)
}
return result, nil
......@@ -744,9 +745,9 @@ func buyRevoke(cmd *cobra.Command, args []string) {
return
}
feeInt64, err := types.TransferFloat(fee, cfg.CoinPrecision)
feeInt64, err := types.FormatFloatDisplay2Value(fee, cfg.CoinPrecision)
if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "TransferFloat"))
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "FormatFloatDisplay2Value"))
return
}
params := &pty.TradeRevokeBuyTx{
......
......@@ -254,32 +254,33 @@ func (t *trade) rollBackSellLimit(tx *types.Transaction, sell *pty.ReceiptSellBa
return order
}
func parseOrderAmountFloat(s string) int64 {
func parseOrderAmountFloat(s string, tokenPrecision int64) int64 {
x, err := strconv.ParseFloat(s, 64)
if err != nil {
tradelog.Error("parseOrderAmountFloat", "decode receipt", err)
return 0
}
return int64(x * float64(types.TokenPrecision))
return int64(x * float64(tokenPrecision))
}
func parseOrderPriceFloat(s string) int64 {
func parseOrderPriceFloat(s string, coinPrecision int64) int64 {
x, err := strconv.ParseFloat(s, 64)
if err != nil {
tradelog.Error("parseOrderPriceFloat", "decode receipt", err)
return 0
}
return int64(x * float64(types.Coin))
return int64(x * float64(coinPrecision))
}
func (t *trade) genSellMarket(tx *types.Transaction, sell *pty.ReceiptSellBase, txIndex string) *pty.LocalOrder {
cfg := t.GetAPI().GetConfig()
order := &pty.LocalOrder{
AssetSymbol: sell.TokenSymbol,
TxIndex: txIndex,
Owner: sell.Owner,
AmountPerBoardlot: parseOrderAmountFloat(sell.AmountPerBoardlot),
AmountPerBoardlot: parseOrderAmountFloat(sell.AmountPerBoardlot, cfg.GetTokenPrecision()),
MinBoardlot: sell.MinBoardlot,
PricePerBoardlot: parseOrderPriceFloat(sell.PricePerBoardlot),
PricePerBoardlot: parseOrderPriceFloat(sell.PricePerBoardlot, cfg.GetCoinPrecision()),
TotalBoardlot: sell.TotalBoardlot,
TradedBoardlot: sell.SoldBoardlot,
BuyID: sell.BuyID,
......@@ -300,13 +301,14 @@ func (t *trade) genSellMarket(tx *types.Transaction, sell *pty.ReceiptSellBase,
}
func (t *trade) genBuyLimit(tx *types.Transaction, buy *pty.ReceiptBuyBase, txIndex string) *pty.LocalOrder {
cfg := t.GetAPI().GetConfig()
order := &pty.LocalOrder{
AssetSymbol: buy.TokenSymbol,
TxIndex: txIndex,
Owner: buy.Owner,
AmountPerBoardlot: parseOrderAmountFloat(buy.AmountPerBoardlot),
AmountPerBoardlot: parseOrderAmountFloat(buy.AmountPerBoardlot, cfg.GetTokenPrecision()),
MinBoardlot: buy.MinBoardlot,
PricePerBoardlot: parseOrderPriceFloat(buy.PricePerBoardlot),
PricePerBoardlot: parseOrderPriceFloat(buy.PricePerBoardlot, cfg.GetCoinPrecision()),
TotalBoardlot: buy.TotalBoardlot,
TradedBoardlot: buy.BoughtBoardlot,
BuyID: buy.BuyID,
......@@ -374,13 +376,14 @@ func (t *trade) rollbackBuyLimit(tx *types.Transaction, buy *pty.ReceiptBuyBase,
}
func (t *trade) genBuyMarket(tx *types.Transaction, buy *pty.ReceiptBuyBase, txIndex string) *pty.LocalOrder {
cfg := t.GetAPI().GetConfig()
order := &pty.LocalOrder{
AssetSymbol: buy.TokenSymbol,
TxIndex: txIndex,
Owner: buy.Owner,
AmountPerBoardlot: parseOrderAmountFloat(buy.AmountPerBoardlot),
AmountPerBoardlot: parseOrderAmountFloat(buy.AmountPerBoardlot, cfg.GetTokenPrecision()),
MinBoardlot: buy.MinBoardlot,
PricePerBoardlot: parseOrderPriceFloat(buy.PricePerBoardlot),
PricePerBoardlot: parseOrderPriceFloat(buy.PricePerBoardlot, cfg.GetCoinPrecision()),
TotalBoardlot: buy.TotalBoardlot,
TradedBoardlot: buy.BoughtBoardlot,
BuyID: calcTokenBuyID(hex.EncodeToString(tx.Hash())),
......
......@@ -8,7 +8,6 @@ import (
"encoding/hex"
"errors"
"fmt"
"strconv"
"strings"
"github.com/33cn/chain33/client"
......@@ -39,15 +38,15 @@ func (selldb *sellDB) save(db dbm.KV) []*types.KeyValue {
return set
}
func (selldb *sellDB) getSellLogs(tradeType int32, txhash string) *types.ReceiptLog {
func (selldb *sellDB) getSellLogs(tradeType int32, txhash string, cfg *types.Chain33Config) *types.ReceiptLog {
log := &types.ReceiptLog{}
log.Ty = tradeType
base := &pty.ReceiptSellBase{
TokenSymbol: selldb.TokenSymbol,
Owner: selldb.Address,
AmountPerBoardlot: strconv.FormatFloat(float64(selldb.AmountPerBoardlot)/float64(types.TokenPrecision), 'f', 8, 64),
AmountPerBoardlot: types.FormatAmount2FixPrecisionDisplay(selldb.AmountPerBoardlot, cfg.GetTokenPrecision()),
MinBoardlot: selldb.MinBoardlot,
PricePerBoardlot: strconv.FormatFloat(float64(selldb.PricePerBoardlot)/float64(types.Coin), 'f', 8, 64),
PricePerBoardlot: types.FormatAmount2FixPrecisionDisplay(selldb.PricePerBoardlot, cfg.GetCoinPrecision()),
TotalBoardlot: selldb.TotalBoardlot,
SoldBoardlot: selldb.SoldBoardlot,
Starttime: selldb.Starttime,
......@@ -74,15 +73,15 @@ func (selldb *sellDB) getSellLogs(tradeType int32, txhash string) *types.Receipt
return log
}
func (selldb *sellDB) getBuyLogs(buyerAddr string, boardlotcnt int64, txhash string) *types.ReceiptLog {
func (selldb *sellDB) getBuyLogs(buyerAddr string, boardlotcnt int64, txhash string, cfg *types.Chain33Config) *types.ReceiptLog {
log := &types.ReceiptLog{}
log.Ty = pty.TyLogTradeBuyMarket
base := &pty.ReceiptBuyBase{
TokenSymbol: selldb.TokenSymbol,
Owner: buyerAddr,
AmountPerBoardlot: strconv.FormatFloat(float64(selldb.AmountPerBoardlot)/float64(types.TokenPrecision), 'f', 8, 64),
AmountPerBoardlot: types.FormatAmount2FixPrecisionDisplay(selldb.AmountPerBoardlot, cfg.GetTokenPrecision()),
MinBoardlot: selldb.MinBoardlot,
PricePerBoardlot: strconv.FormatFloat(float64(selldb.PricePerBoardlot)/float64(types.Coin), 'f', 8, 64),
PricePerBoardlot: types.FormatAmount2FixPrecisionDisplay(selldb.PricePerBoardlot, cfg.GetCoinPrecision()),
TotalBoardlot: boardlotcnt,
BoughtBoardlot: boardlotcnt,
BuyID: "",
......@@ -147,15 +146,15 @@ func (buydb *buyDB) getKVSet() (kvset []*types.KeyValue) {
return kvset
}
func (buydb *buyDB) getBuyLogs(tradeType int32, txhash string) *types.ReceiptLog {
func (buydb *buyDB) getBuyLogs(tradeType int32, txhash string, cfg *types.Chain33Config) *types.ReceiptLog {
log := &types.ReceiptLog{}
log.Ty = tradeType
base := &pty.ReceiptBuyBase{
TokenSymbol: buydb.TokenSymbol,
Owner: buydb.Address,
AmountPerBoardlot: strconv.FormatFloat(float64(buydb.AmountPerBoardlot)/float64(types.TokenPrecision), 'f', 8, 64),
AmountPerBoardlot: types.FormatAmount2FixPrecisionDisplay(buydb.AmountPerBoardlot, cfg.GetTokenPrecision()),
MinBoardlot: buydb.MinBoardlot,
PricePerBoardlot: strconv.FormatFloat(float64(buydb.PricePerBoardlot)/float64(types.Coin), 'f', 8, 64),
PricePerBoardlot: types.FormatAmount2FixPrecisionDisplay(buydb.PricePerBoardlot, cfg.GetCoinPrecision()),
TotalBoardlot: buydb.TotalBoardlot,
BoughtBoardlot: buydb.BoughtBoardlot,
BuyID: buydb.BuyID,
......@@ -194,15 +193,15 @@ func getBuyOrderFromID(buyID []byte, db dbm.KV) (*pty.BuyLimitOrder, error) {
return &buy, nil
}
func (buydb *buyDB) getSellLogs(sellerAddr string, sellID string, boardlotCnt int64, txhash string) *types.ReceiptLog {
func (buydb *buyDB) getSellLogs(sellerAddr string, sellID string, boardlotCnt int64, txhash string, cfg *types.Chain33Config) *types.ReceiptLog {
log := &types.ReceiptLog{}
log.Ty = pty.TyLogTradeSellMarket
base := &pty.ReceiptSellBase{
TokenSymbol: buydb.TokenSymbol,
Owner: sellerAddr,
AmountPerBoardlot: strconv.FormatFloat(float64(buydb.AmountPerBoardlot)/float64(types.TokenPrecision), 'f', 8, 64),
AmountPerBoardlot: types.FormatAmount2FixPrecisionDisplay(buydb.AmountPerBoardlot, cfg.GetTokenPrecision()),
MinBoardlot: buydb.MinBoardlot,
PricePerBoardlot: strconv.FormatFloat(float64(buydb.PricePerBoardlot)/float64(types.Coin), 'f', 8, 64),
PricePerBoardlot: types.FormatAmount2FixPrecisionDisplay(buydb.PricePerBoardlot, cfg.GetCoinPrecision()),
TotalBoardlot: boardlotCnt,
SoldBoardlot: boardlotCnt,
Starttime: 0,
......@@ -292,7 +291,7 @@ func (action *tradeAction) tradeSell(sell *pty.TradeForSell) (*types.Receipt, er
tokendb := newSellDB(sellOrder)
sellOrderKV := tokendb.save(action.db)
logs = append(logs, receipt.Logs...)
logs = append(logs, tokendb.getSellLogs(pty.TyLogTradeSellLimit, action.txhash))
logs = append(logs, tokendb.getSellLogs(pty.TyLogTradeSellLimit, action.txhash, cfg))
kv = append(kv, receipt.KV...)
kv = append(kv, sellOrderKV...)
......@@ -373,8 +372,8 @@ func (action *tradeAction) tradeBuy(buyOrder *pty.TradeForBuy) (*types.Receipt,
logs = append(logs, receiptFromAcc.Logs...)
logs = append(logs, receiptFromExecAcc.Logs...)
logs = append(logs, sellTokendb.getSellLogs(pty.TyLogTradeSellLimit, action.txhash))
logs = append(logs, sellTokendb.getBuyLogs(action.fromaddr, buyOrder.BoardlotCnt, action.txhash))
logs = append(logs, sellTokendb.getSellLogs(pty.TyLogTradeSellLimit, action.txhash, cfg))
logs = append(logs, sellTokendb.getBuyLogs(action.fromaddr, buyOrder.BoardlotCnt, action.txhash, cfg))
kv = append(kv, receiptFromAcc.KV...)
kv = append(kv, receiptFromExecAcc.KV...)
kv = append(kv, sellOrderKV...)
......@@ -425,7 +424,7 @@ func (action *tradeAction) tradeRevokeSell(revoke *pty.TradeForRevokeSell) (*typ
sellOrderKV := tokendb.save(action.db)
logs = append(logs, receiptFromExecAcc.Logs...)
logs = append(logs, tokendb.getSellLogs(pty.TyLogTradeSellRevoke, action.txhash))
logs = append(logs, tokendb.getSellLogs(pty.TyLogTradeSellRevoke, action.txhash, cfg))
kv = append(kv, receiptFromExecAcc.KV...)
kv = append(kv, sellOrderKV...)
return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil
......@@ -505,7 +504,7 @@ func (action *tradeAction) tradeBuyLimit(buy *pty.TradeForBuyLimit) (*types.Rece
tokendb := newBuyDB(buyOrder)
buyOrderKV := tokendb.save(action.db)
logs = append(logs, receipt.Logs...)
logs = append(logs, tokendb.getBuyLogs(pty.TyLogTradeBuyLimit, action.txhash))
logs = append(logs, tokendb.getBuyLogs(pty.TyLogTradeBuyLimit, action.txhash, cfg))
kv = append(kv, receipt.KV...)
kv = append(kv, buyOrderKV...)
......@@ -585,8 +584,8 @@ func (action *tradeAction) tradeSellMarket(sellOrder *pty.TradeForSellMarket) (*
logs = append(logs, receiptFromAcc.Logs...)
logs = append(logs, receiptFromExecAcc.Logs...)
logs = append(logs, buyTokendb.getBuyLogs(pty.TyLogTradeBuyLimit, action.txhash))
logs = append(logs, buyTokendb.getSellLogs(action.fromaddr, action.txhash, sellOrder.BoardlotCnt, action.txhash))
logs = append(logs, buyTokendb.getBuyLogs(pty.TyLogTradeBuyLimit, action.txhash, cfg))
logs = append(logs, buyTokendb.getSellLogs(action.fromaddr, action.txhash, sellOrder.BoardlotCnt, action.txhash, cfg))
kv = append(kv, receiptFromAcc.KV...)
kv = append(kv, receiptFromExecAcc.KV...)
kv = append(kv, sellOrderKV...)
......@@ -637,7 +636,7 @@ func (action *tradeAction) tradeRevokeBuyLimit(revoke *pty.TradeForRevokeBuy) (*
sellOrderKV := tokendb.save(action.db)
logs = append(logs, receiptFromExecAcc.Logs...)
logs = append(logs, tokendb.getBuyLogs(pty.TyLogTradeBuyRevoke, action.txhash))
logs = append(logs, tokendb.getBuyLogs(pty.TyLogTradeBuyRevoke, action.txhash, cfg))
kv = append(kv, receiptFromExecAcc.KV...)
kv = append(kv, sellOrderKV...)
return &types.Receipt{Ty: types.ExecOk, KV: kv, Logs: logs}, nil
......
......@@ -43,7 +43,7 @@ func (jrpc *Jrpc) GetLastMemPool(in types.ReqNil, result *interface{}) error {
var txlist rpctypes.ReplyTxList
txs := reply.GetTxs()
for _, tx := range txs {
tran, err := rpctypes.DecodeTx(tx)
tran, err := rpctypes.DecodeTx(tx, jrpc.cli.GetConfig().GetCoinPrecision())
if err != nil {
continue
}
......
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