Skip to content

Commit

Permalink
Merge branch 'price' into dev
Browse files Browse the repository at this point in the history
  • Loading branch information
scorpiotzh committed Sep 18, 2023
2 parents 24bc329 + a168aba commit 97a1f5b
Show file tree
Hide file tree
Showing 11 changed files with 165 additions and 82 deletions.
11 changes: 11 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,14 @@ func GetUnipayAddress(tokenId tables.TokenId) string {
}
return ""
}

func PriceToCKB(price, quote, years uint64) (total uint64) {
log.Info("PriceToCKB:", price, quote, years)
if price > quote {
total = price / quote * common.OneCkb * years
} else {
total = price * common.OneCkb / quote * years
}
log.Info("PriceToCKB:", price, quote, total)
return
}
4 changes: 2 additions & 2 deletions example/api_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func TestInternalSubAccountMint(t *testing.T) {
Account: "10086.bit",
SubAccountList: []handle.CreateSubAccount{
{
Account: "test1.10086.bit",
Account: "test12.10086.bit",
RegisterYears: 1,
ChainTypeAddress: core.ChainTypeAddress{
Type: "blockchain",
Expand All @@ -43,7 +43,7 @@ func TestInternalSubAccountMint(t *testing.T) {
},
},
{
Account: "test2.10086.bit",
Account: "test22.10086.bit",
RegisterYears: 2,
ChainTypeAddress: core.ChainTypeAddress{
Type: "blockchain",
Expand Down
24 changes: 24 additions & 0 deletions example/custom_script_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/dotbitHQ/das-lib/molecule"
"github.com/dotbitHQ/das-lib/witness"
"github.com/nervosnetwork/ckb-sdk-go/types"
"github.com/scorpiotzh/toolib"
"testing"
)

Expand All @@ -34,6 +35,7 @@ func TestCustomScript(t *testing.T) {
5: {1000000, 1000000},
},
}
fmt.Println(toolib.JsonString(&req))
var data handle.RespCustomScript
if err := doReq(url, req, &data); err != nil {
t.Fatal(err)
Expand Down Expand Up @@ -128,3 +130,25 @@ func TestCustomScriptPrice(t *testing.T) {
}

}

func TestPrice(t *testing.T) {
dc, err := getNewDasCoreTestnet2()
if err != nil {
t.Fatal(err)
}
qCell, err := dc.GetQuoteCell()
if err != nil {
t.Fatal(err)
}
fmt.Println(qCell.Quote())
quote := uint64(12632) //0.012632
yearlyPrice := uint64(12000) //uint64(990000) //0.99
if yearlyPrice < quote {
fmt.Println("<", yearlyPrice*common.OneCkb/quote*1)
//fmt.Println(">", yearlyPrice/quote*common.OneCkb*1)
} else {
//fmt.Println("<", yearlyPrice*common.OneCkb/quote*1)
fmt.Println(">", yearlyPrice/quote*common.OneCkb*1)
}

}
19 changes: 18 additions & 1 deletion http_server/handle/auto_order_create.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/dotbitHQ/das-lib/common"
"github.com/dotbitHQ/das-lib/core"
api_code "github.com/dotbitHQ/das-lib/http_api"
"github.com/dotbitHQ/das-lib/molecule"
"github.com/gin-gonic/gin"
"github.com/scorpiotzh/toolib"
"github.com/shopspring/decimal"
Expand Down Expand Up @@ -123,7 +124,6 @@ func (h *HttpHandle) doAutoOrderCreate(req *ReqAutoOrderCreate, apiResp *api_cod
apiResp.ApiRespErr(api_code.ApiCodeBeyondMaxYears, "The main account is valid for less than one year")
return nil
}

// get rule price
usdAmount, err := h.getRulePrice(parentAccount.Account, parentAccountId, req.SubAccount, apiResp)
if err != nil {
Expand All @@ -139,6 +139,23 @@ func (h *HttpHandle) doAutoOrderCreate(req *ReqAutoOrderCreate, apiResp *api_cod
apiResp.ApiRespErr(api_code.ApiCodeTokenIdNotSupported, "payment method not supported")
return nil
}
// check min price 0.99$
builder, err := h.DasCore.ConfigCellDataBuilderByTypeArgsList(common.ConfigCellTypeArgsSubAccount)
if err != nil {
apiResp.ApiRespErr(api_code.ApiCodeError500, "Failed to get config info")
return fmt.Errorf("ConfigCellDataBuilderByTypeArgsList err: %s", err.Error())
}
newSubAccountPrice, _ := molecule.Bytes2GoU64(builder.ConfigCellSubAccount.NewSubAccountPrice().RawData())
minPrice := decimal.NewFromInt(int64(newSubAccountPrice)).DivRound(decimal.NewFromInt(common.UsdRateBase), 2)
if req.ActionType == tables.ActionTypeRenew {
renewSubAccountPrice, _ := molecule.Bytes2GoU64(builder.ConfigCellSubAccount.RenewSubAccountPrice().RawData())
minPrice = decimal.NewFromInt(int64(renewSubAccountPrice)).DivRound(decimal.NewFromInt(common.UsdRateBase), 2)
}
if minPrice.GreaterThan(usdAmount) {
apiResp.ApiRespErr(api_code.ApiCodePriceRulePriceNotBeLessThanMin, err.Error())
return fmt.Errorf("price not be less than min: %s$", minPrice.String())
}

log.Info("usdAmount:", usdAmount.String(), req.Years)
usdAmount = usdAmount.Mul(decimal.NewFromInt(int64(req.Years)))
//log.Info("usdAmount:", usdAmount.String(), req.Years)
Expand Down
25 changes: 18 additions & 7 deletions http_server/handle/config_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,11 @@ type RespConfigInfo struct {
PaymentMinPrice int64 `json:"payment_min_price"`
ServiceFeeRatio string `json:"service_fee_ratio"`
} `json:"auto_mint"`
MintCostsManually uint64 `json:"mint_costs_manually"`
RenewCostsManually uint64 `json:"renew_costs_manually"`
ManagementTimes uint64 `json:"management_times"`
MintCostsManually uint64 `json:"mint_costs_manually"`
RenewCostsManually uint64 `json:"renew_costs_manually"`
ManagementTimes uint64 `json:"management_times"`
MintPrice decimal.Decimal `json:"mint_price"`
RenewPrice decimal.Decimal `json:"renew_price"`
}

func (h *HttpHandle) ConfigInfo(ctx *gin.Context) {
Expand Down Expand Up @@ -57,20 +59,29 @@ func (h *HttpHandle) doConfigInfo(apiResp *api_code.ApiResp) error {
}
resp.SubAccountBasicCapacity, _ = molecule.Bytes2GoU64(builder.ConfigCellSubAccount.BasicCapacity().RawData())
resp.SubAccountPreparedFeeCapacity, _ = molecule.Bytes2GoU64(builder.ConfigCellSubAccount.PreparedFeeCapacity().RawData())
resp.SubAccountNewSubAccountPrice, _ = molecule.Bytes2GoU64(builder.ConfigCellSubAccount.NewSubAccountPrice().RawData())
resp.SubAccountRenewSubAccountPrice, _ = molecule.Bytes2GoU64(builder.ConfigCellSubAccount.RenewSubAccountPrice().RawData())
resp.SubAccountCommonFee, _ = molecule.Bytes2GoU64(builder.ConfigCellSubAccount.CommonFee().RawData())
resp.MintCostsManually, _ = molecule.Bytes2GoU64(builder.ConfigCellSubAccount.NewSubAccountPrice().RawData())
resp.RenewCostsManually, _ = molecule.Bytes2GoU64(builder.ConfigCellSubAccount.RenewSubAccountPrice().RawData())
resp.ManagementTimes = 10000

//resp.MintCostsManually, _ = molecule.Bytes2GoU64(builder.ConfigCellSubAccount.NewSubAccountPrice().RawData())
//resp.RenewCostsManually, _ = molecule.Bytes2GoU64(builder.ConfigCellSubAccount.RenewSubAccountPrice().RawData())
resp.MintCostsManually = 100000000
resp.RenewCostsManually = 100000000

mintPrice, _ := molecule.Bytes2GoU64(builder.ConfigCellSubAccount.CommonFee().RawData())
renewPrice, _ := molecule.Bytes2GoU64(builder.ConfigCellSubAccount.RenewSubAccountPrice().RawData())

resp.MintPrice = decimal.NewFromInt(int64(mintPrice)).DivRound(decimal.NewFromInt(common.UsdRateBase), 2)
resp.RenewPrice = decimal.NewFromInt(int64(renewPrice)).DivRound(decimal.NewFromInt(common.UsdRateBase), 2)

quoteCell, err := h.DasCore.GetQuoteCell()
if err != nil {
apiResp.ApiRespErr(api_code.ApiCodeError500, err.Error())
return nil
}
quote := decimal.NewFromInt(int64(quoteCell.Quote()))
resp.CkbQuote = quote.Div(decimal.NewFromInt(int64(common.OneCkb))).String()
resp.SubAccountNewSubAccountPrice = config.PriceToCKB(mintPrice, quoteCell.Quote(), 1)
resp.SubAccountRenewSubAccountPrice = config.PriceToCKB(renewPrice, quoteCell.Quote(), 1)

resp.AutoMint.PaymentMinPrice = config.Cfg.Das.AutoMint.PaymentMinPrice
resp.AutoMint.ServiceFeeRatio = fmt.Sprintf("%s%%", decimal.NewFromFloat(config.Cfg.Das.AutoMint.ServiceFeeRatio*100).String())
Expand Down
18 changes: 10 additions & 8 deletions http_server/handle/price_rule_update.go
Original file line number Diff line number Diff line change
Expand Up @@ -272,11 +272,11 @@ func (h *HttpHandle) rulesTxAssemble(params RulesTxAssembleParams) (*txbuilder.B
return nil, nil, err
}

token, err := h.DbDao.GetTokenById(tables.TokenIdCkb)
if err != nil {
params.ApiResp.ApiRespErr(api_code.ApiCodeError500, err.Error())
return nil, nil, err
}
//token, err := h.DbDao.GetTokenById(tables.TokenIdCkb)
//if err != nil {
// params.ApiResp.ApiRespErr(api_code.ApiCodeError500, err.Error())
// return nil, nil, err
//}

builder, err := h.DasCore.ConfigCellDataBuilderByTypeArgsList(common.ConfigCellTypeArgsSubAccount)
if err != nil {
Expand All @@ -296,14 +296,16 @@ func (h *HttpHandle) rulesTxAssemble(params RulesTxAssembleParams) (*txbuilder.B
}

if math.Round(v.Price*10000)/10000 != v.Price {
err = errors.New("price most be two decimal places")
err = errors.New("price most be four decimal places")
params.ApiResp.ApiRespErr(api_code.ApiCodePriceMostReserveTwoDecimal, err.Error())
return nil, nil, err
}

price := decimal.NewFromInt(int64(newSubAccountPrice)).Mul(token.Price).Div(decimal.NewFromFloat(math.Pow10(int(token.Decimals))))
// check min price 0.99$
price := decimal.NewFromInt(int64(newSubAccountPrice)).DivRound(decimal.NewFromInt(common.UsdRateBase), 2)
//price := decimal.NewFromInt(int64(newSubAccountPrice)).Mul(token.Price).Div(decimal.NewFromFloat(math.Pow10(int(token.Decimals))))
if price.GreaterThan(decimal.NewFromFloat(v.Price)) {
err = fmt.Errorf("price not be less than min: %s$", price)
err = fmt.Errorf("price not be less than min: %s$", price.String())
params.ApiResp.ApiRespErr(api_code.ApiCodePriceRulePriceNotBeLessThanMin, err.Error())
return nil, nil, err
}
Expand Down
13 changes: 11 additions & 2 deletions http_server/handle/sub_account_create_new.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,10 +145,19 @@ func (h *HttpHandle) doSubAccountCreateNew(req *ReqSubAccountCreate, apiResp *ap
}
newSubAccountPrice, _ := molecule.Bytes2GoU64(configCellBuilder.ConfigCellSubAccount.NewSubAccountPrice().RawData())
totalCapacity := uint64(0)
totalRegisterYears := uint64(0)
for _, v := range req.SubAccountList {
totalCapacity += v.RegisterYears
totalRegisterYears += v.RegisterYears
}
totalCapacity = totalCapacity * newSubAccountPrice

quoteCell, err := h.DasCore.GetQuoteCell()
if err != nil {
apiResp.ApiRespErr(api_code.ApiCodeError500, "failed to get quote cell")
return fmt.Errorf("GetQuoteCell err: %s", err.Error())
}
totalCapacity = config.PriceToCKB(newSubAccountPrice, quoteCell.Quote(), totalRegisterYears)
//totalCapacity = totalRegisterYears * newSubAccountPrice

_, _, err = h.DasCore.GetBalanceCells(&core.ParamGetBalanceCells{
DasCache: nil,
LockScript: balanceDasLock,
Expand Down
11 changes: 9 additions & 2 deletions http_server/handle/sub_account_renew.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,10 +141,17 @@ func (h *HttpHandle) doSubAccountRenew(req *ReqSubAccountRenew, apiResp *api_cod
}

totalCapacity := uint64(0)
totalRenewYears := uint64(0)
for _, v := range req.SubAccountList {
totalCapacity += v.RenewYears
totalRenewYears += v.RenewYears
}
totalCapacity = totalCapacity * renewSubAccountPrice
//totalCapacity = totalRenewYears * renewSubAccountPrice
quoteCell, err := h.DasCore.GetQuoteCell()
if err != nil {
apiResp.ApiRespErr(api_code.ApiCodeError500, "failed to get quote cell")
return fmt.Errorf("GetQuoteCell err: %s", err.Error())
}
totalCapacity = config.PriceToCKB(renewSubAccountPrice, quoteCell.Quote(), totalRenewYears)

_, _, err = h.DasCore.GetBalanceCells(&core.ParamGetBalanceCells{
DasCache: nil,
Expand Down
8 changes: 4 additions & 4 deletions http_server/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ func (h *HttpServer) initRouter() {
v1.POST("/sub/account/edit", api_code.DoMonitorLog("account_edit"), h.H.SubAccountEditNew) // edit_sub_account
v1.POST("/owner/profit", api_code.DoMonitorLog("owner_profit"), h.H.OwnerProfit)
v1.POST("/profit/withdraw", api_code.DoMonitorLog("profit_withdraw"), h.H.ProfitWithdraw)
v1.POST("/custom/script/set", api_code.DoMonitorLog("custom_script"), h.H.CustomScript)
v1.POST("/custom/script/info", api_code.DoMonitorLog("custom_script_info"), h.H.CustomScriptInfo)
v1.POST("/custom/script/price", api_code.DoMonitorLog("mint_price"), cacheHandleShort, h.H.CustomScriptPrice)
//v1.POST("/custom/script/set", api_code.DoMonitorLog("custom_script"), h.H.CustomScript)
//v1.POST("/custom/script/info", api_code.DoMonitorLog("custom_script_info"), h.H.CustomScriptInfo)
//v1.POST("/custom/script/price", api_code.DoMonitorLog("mint_price"), cacheHandleShort, h.H.CustomScriptPrice)
v1.POST("/transaction/send", api_code.DoMonitorLog("tx_send"), h.H.TransactionSendNew)
v1.POST("/mint/config/update", api_code.DoMonitorLog("mint_config_update"), h.H.MintConfigUpdate)
v1.POST("/config/auto_mint/update", api_code.DoMonitorLog("config_auto_mint_update"), h.H.ConfigAutoMintUpdate)
Expand All @@ -79,7 +79,7 @@ func (h *HttpServer) initRouter() {
internalV1.POST("/internal/smt/update", h.H.SmtUpdate)
internalV1.POST("/internal/smt/syncTree", h.H.SmtSync)

internalV1.POST("/internal/sub/account/mint", h.H.InternalSubAccountMintNew)
//internalV1.POST("/internal/sub/account/mint", h.H.InternalSubAccountMintNew)
internalV1.POST("/owner/payment/export", h.H.OwnerPaymentExport)
internalV1.POST("/unipay/notice", h.H.UniPayNotice)
internalV1.POST("/service/provider/withdraw", h.H.ServiceProviderWithdraw)
Expand Down
88 changes: 44 additions & 44 deletions txtool/txtool.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ type ParamBuildTxs struct {
}

type ResultBuildTxs struct {
IsCustomScript bool
//IsCustomScript bool
DasTxBuilderList []*txbuilder.DasTxBuilder
}

Expand All @@ -59,7 +59,7 @@ func (s *SubAccountTxTool) BuildTxsForUpdateSubAccount(p *ParamBuildTxs) (*Resul
subAccountOutpoint := p.SubAccountLiveCell.OutPoint

// account
res.IsCustomScript = s.isCustomScript(p.SubAccountLiveCell.OutputData)
//res.IsCustomScript = s.isCustomScript(p.SubAccountLiveCell.OutputData)
subAccountCellOutput := p.SubAccountLiveCell.Output
subAccountOutputsData := p.SubAccountLiveCell.OutputData
// build txs
Expand All @@ -73,49 +73,49 @@ func (s *SubAccountTxTool) BuildTxsForUpdateSubAccount(p *ParamBuildTxs) (*Resul
case common.DasActionUpdateSubAccount:
var resUpdate *ResultBuildUpdateSubAccountTx
var err error
if res.IsCustomScript {
resUpdate, err = s.BuildUpdateSubAccountTxForCustomScript(&ParamBuildUpdateSubAccountTx{
TaskInfo: &p.TaskList[i],
Account: p.Account,
AccountOutPoint: accountOutPoint,
SubAccountOutpoint: subAccountOutpoint,
SmtRecordInfoList: records,
Tree: p.Tree,
BaseInfo: p.BaseInfo,
SubAccountBuilderMap: p.SubAccountBuilderMap,
NewSubAccountPrice: newSubAccountPrice,
RenewSubAccountPrice: renewSubAccountPrice,
BalanceDasLock: p.BalanceDasLock,
BalanceDasType: p.BalanceDasType,
CommonFee: commonFee,
SubAccountCellOutput: subAccountCellOutput,
SubAccountOutputsData: subAccountOutputsData,
})
if err != nil {
return nil, fmt.Errorf("BuildUpdateSubAccountTxForCustomScript err: %s", err.Error())
}
} else {
resUpdate, err = s.BuildUpdateSubAccountTx(&ParamBuildUpdateSubAccountTx{
TaskInfo: &p.TaskList[i],
Account: p.Account,
AccountOutPoint: accountOutPoint,
SubAccountOutpoint: subAccountOutpoint,
SmtRecordInfoList: records,
Tree: p.Tree,
BaseInfo: p.BaseInfo,
SubAccountBuilderMap: p.SubAccountBuilderMap,
NewSubAccountPrice: newSubAccountPrice,
RenewSubAccountPrice: renewSubAccountPrice,
BalanceDasLock: p.BalanceDasLock,
BalanceDasType: p.BalanceDasType,
CommonFee: commonFee,
SubAccountCellOutput: subAccountCellOutput,
SubAccountOutputsData: subAccountOutputsData,
})
if err != nil {
return nil, fmt.Errorf("BuildUpdateSubAccountTx err: %s", err.Error())
}
//if res.IsCustomScript {
// resUpdate, err = s.BuildUpdateSubAccountTxForCustomScript(&ParamBuildUpdateSubAccountTx{
// TaskInfo: &p.TaskList[i],
// Account: p.Account,
// AccountOutPoint: accountOutPoint,
// SubAccountOutpoint: subAccountOutpoint,
// SmtRecordInfoList: records,
// Tree: p.Tree,
// BaseInfo: p.BaseInfo,
// SubAccountBuilderMap: p.SubAccountBuilderMap,
// NewSubAccountPrice: newSubAccountPrice,
// RenewSubAccountPrice: renewSubAccountPrice,
// BalanceDasLock: p.BalanceDasLock,
// BalanceDasType: p.BalanceDasType,
// CommonFee: commonFee,
// SubAccountCellOutput: subAccountCellOutput,
// SubAccountOutputsData: subAccountOutputsData,
// })
// if err != nil {
// return nil, fmt.Errorf("BuildUpdateSubAccountTxForCustomScript err: %s", err.Error())
// }
//} else {
resUpdate, err = s.BuildUpdateSubAccountTx(&ParamBuildUpdateSubAccountTx{
TaskInfo: &p.TaskList[i],
Account: p.Account,
AccountOutPoint: accountOutPoint,
SubAccountOutpoint: subAccountOutpoint,
SmtRecordInfoList: records,
Tree: p.Tree,
BaseInfo: p.BaseInfo,
SubAccountBuilderMap: p.SubAccountBuilderMap,
NewSubAccountPrice: newSubAccountPrice,
RenewSubAccountPrice: renewSubAccountPrice,
BalanceDasLock: p.BalanceDasLock,
BalanceDasType: p.BalanceDasType,
CommonFee: commonFee,
SubAccountCellOutput: subAccountCellOutput,
SubAccountOutputsData: subAccountOutputsData,
})
if err != nil {
return nil, fmt.Errorf("BuildUpdateSubAccountTx err: %s", err.Error())
}
// }
res.DasTxBuilderList = append(res.DasTxBuilderList, resUpdate.DasTxBuilder)
default:
return nil, fmt.Errorf("not exist action [%s]", task.Action)
Expand Down
Loading

0 comments on commit 97a1f5b

Please sign in to comment.