cheque

package
v0.0.0-...-c0cc0bc Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 30, 2024 License: Apache-2.0, MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CashoutStatusSuccess  = "success"
	CashoutStatusFail     = "fail"
	CashoutStatusPending  = "pending"
	CashoutStatusNotFound = "not_found"
)

Variables

View Source
var BatchCashChequeCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Batch cash the cheques by peerIDs.",
	},
	Arguments: []cmds.Argument{
		cmds.StringArg("peer-ids", true, true, "Peer id tobe cashed."),
	},
	Options: []cmds.Option{
		cmds.StringOption(tokencfg.TokenTypeName, "tk", "file storage with token type,default WBTT, other TRX/USDD/USDT.").WithDefault("WBTT"),
	},
	RunTimeout: 5 * time.Minute,
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		peerIDs := req.Arguments
		tokenStr := req.Options[tokencfg.TokenTypeName].(string)
		token, bl := tokencfg.MpTokenAddr[tokenStr]
		if !bl {
			return errors.New("your input token is none. ")
		}

		for _, peerID := range peerIDs {
			tx_hash, err := chain.SettleObject.SwapService.CashCheque(req.Context, peerID, token)
			if err != nil {
				return err
			}
			err = res.Emit(&CashChequeRet{
				TxHash: tx_hash.String(),
			})
			if err != nil {
				return err
			}
		}
		return nil
	},
	Type: CashChequeRet{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *CashChequeRet) error {
			_, err := fmt.Fprintf(w, "the hash of transaction: %s", out.TxHash)
			return err
		}),
	},
}
View Source
var CashChequeCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Cash a cheque by peerID.",
	},
	Arguments: []cmds.Argument{
		cmds.StringArg("peer-id", true, false, "Peer id tobe cashed."),
	},
	Options: []cmds.Option{
		cmds.StringOption(tokencfg.TokenTypeName, "tk", "file storage with token type,default WBTT, other TRX/USDD/USDT.").WithDefault("WBTT"),
	},
	RunTimeout: 5 * time.Minute,
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		peerID := req.Arguments[0]
		tokenStr := req.Options[tokencfg.TokenTypeName].(string)

		token, bl := tokencfg.MpTokenAddr[tokenStr]
		if !bl {
			return errors.New("your input token is none. ")
		}

		tx_hash, err := chain.SettleObject.SwapService.CashCheque(req.Context, peerID, token)
		if err != nil {
			return err
		}

		return cmds.EmitOnce(res, &CashChequeRet{
			TxHash: tx_hash.String(),
		})
	},
	Type: CashChequeRet{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *CashChequeRet) error {
			_, err := fmt.Fprintf(w, "the hash of transaction: %s", out.TxHash)
			return err
		}),
	},
}
View Source
var ChequeAllTokenBalanceCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Get all token balance by addr.",
	},
	Arguments: []cmds.Argument{
		cmds.StringArg("addr", true, false, "bttc account address"),
	},
	RunTimeout: 5 * time.Minute,
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		addr := req.Arguments[0]

		mp := make(map[string]*big.Int, 0)
		for k := range tokencfg.MpTokenAddr {
			balance, err := chain.SettleObject.VaultService.TokenBalanceOf(context.Background(), common.HexToAddress(addr), k)
			if err != nil {
				return err
			}

			mp[k] = balance
		}

		return cmds.EmitOnce(res, &mp)
	},
	Type: &ChequeBttBalanceCmdRet{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *ChequeBttBalanceCmdRet) error {
			_, err := fmt.Fprintf(w, "the balance is: %v\n", out.Balance)
			return err
		}),
	},
}
View Source
var ChequeBttBalanceCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Get btt balance by addr.",
	},
	Arguments: []cmds.Argument{
		cmds.StringArg("addr", true, false, "bttc account address"),
	},
	RunTimeout: 5 * time.Minute,
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		addr := req.Arguments[0]
		balance, err := chain.SettleObject.VaultService.BTTBalanceOf(context.Background(), common.HexToAddress(addr), nil)
		if err != nil {
			return err
		}

		return cmds.EmitOnce(res, &ChequeBttBalanceCmdRet{
			Balance: balance,
		})
	},
	Type: &ChequeBttBalanceCmdRet{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *ChequeBttBalanceCmdRet) error {
			_, err := fmt.Fprintf(w, "the balance is: %v\n", out.Balance)
			return err
		}),
	},
}
View Source
var ChequeCashListCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Get cash status by peerID.",
	},
	RunTimeout: 5 * time.Minute,
	Arguments: []cmds.Argument{
		cmds.StringArg("from", true, false, "page offset"),
		cmds.StringArg("limit", true, false, "page limit."),
	},
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		from, err := strconv.Atoi(req.Arguments[0])
		if err != nil {
			return fmt.Errorf("parse from:%v failed", req.Arguments[0])
		}
		limit, err := strconv.Atoi(req.Arguments[1])
		if err != nil {
			return fmt.Errorf("parse limit:%v failed", req.Arguments[1])
		}
		if from < 0 {
			return fmt.Errorf("invalid from: %d", from)
		}
		if limit < 0 {
			return fmt.Errorf("invalid limit: %d", limit)
		}

		results, err := chain.SettleObject.CashoutService.CashoutResults()
		if err != nil {
			return err
		}
		sort.Slice(results, func(i, j int) bool {
			return results[i].CashTime > results[j].CashTime
		})

		total := len(results)
		ret := make([]ChequeCashListRet, 0, limit)
		if from < len(results) {
			if (from + limit) <= len(results) {
				results = results[from : from+limit]
			} else {
				results = results[from:]
			}
			for _, result := range results {
				peer, known, err := chain.SettleObject.SwapService.VaultPeer(result.Vault)
				if err == nil {
					if !known {
						peer = "unkonwn"
					}
					r := ChequeCashListRet{
						TxHash:   result.TxHash.String(),
						PeerID:   peer,
						Token:    result.Token.String(),
						Vault:    result.Vault.String(),
						Amount:   result.Amount,
						CashTime: result.CashTime,
						Status:   result.Status,
					}
					ret = append(ret, r)
				}
			}
		}

		return cmds.EmitOnce(res, &ChequeCashListRsp{
			Records: ret,
			Total:   total,
		})
	},
	Type: &ChequeCashListRsp{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *ChequeCashListRsp) error {
			marshaled, err := json.MarshalIndent(out, "", "\t")
			if err != nil {
				return err
			}
			marshaled = append(marshaled, byte('\n'))
			fmt.Fprintln(w, string(marshaled))
			return nil
		}),
	},
}
View Source
var ChequeCashStatusCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Get cash status by peerID.",
	},
	Arguments: []cmds.Argument{
		cmds.StringArg("peer-id", true, false, "Peer id tobe cashed."),
	},
	Options: []cmds.Option{
		cmds.StringOption(tokencfg.TokenTypeName, "tk", "file storage with token type,default WBTT, other TRX/USDD/USDT.").WithDefault("WBTT"),
	},
	RunTimeout: 5 * time.Minute,
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		peerID := req.Arguments[0]
		tokenStr := req.Options[tokencfg.TokenTypeName].(string)
		fmt.Printf("peerID:%+v, token:%+v\n", peerID, tokenStr)
		token, bl := tokencfg.MpTokenAddr[tokenStr]
		if !bl {
			return errors.New("your input token is none. ")
		}

		cashStatus, err := chain.SettleObject.SwapService.CashoutStatus(req.Context, peerID, token)
		if err != nil {
			return err
		}

		status := CashoutStatusSuccess
		totalPayout := big.NewInt(0)
		if cashStatus.Last == nil {
			status = CashoutStatusNotFound
		} else if cashStatus.Last.Reverted {
			status = CashoutStatusFail
		} else if cashStatus.Last.Result == nil {
			status = CashoutStatusPending
		} else {
			totalPayout = cashStatus.Last.Result.TotalPayout
		}

		return cmds.EmitOnce(res, &CashOutStatusRet{
			UncashedAmount: cashStatus.UncashedAmount,
			Status:         status,
			TotalPayout:    totalPayout,
		})
	},
	Type: &CashOutStatusRet{},
}
View Source
var ChequeChainInfoCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Show current chain info.",
	},
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		walletImportPrvKey, err := chain.GetWalletImportPrvKey(env)
		if err != nil {
			return err
		}

		return cmds.EmitOnce(res, &ChainInfoRet{
			ChainId:            chain.ChainObject.ChainID,
			NodeAddr:           chain.ChainObject.OverlayAddress.String(),
			VaultAddr:          chain.SettleObject.VaultService.Address().String(),
			WalletImportPrvKey: walletImportPrvKey,
		})
	},
	Type: &ChainInfoRet{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *ChainInfoRet) error {
			_, err := fmt.Fprintf(w, "chain id:\t%d\nnode addr:\t%s\nvault addr:\t%s\nwallet import private key:\t%s\n", out.ChainId,
				out.NodeAddr, out.VaultAddr, out.WalletImportPrvKey)
			return err
		}),
	},
}
View Source
var ChequeCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Interact with vault services on BTFS.",
		ShortDescription: `
Vault services include issue cheque to peer, receive cheque and store operations.`,
	},
	Subcommands: map[string]*cmds.Command{
		"cash":               CashChequeCmd,
		"batch-cash":         BatchCashChequeCmd,
		"cashstatus":         ChequeCashStatusCmd,
		"cashlist":           ChequeCashListCmd,
		"price":              StorePriceCmd,
		"price-all":          StorePriceAllCmd,
		"fix_cheque_cashout": FixChequeCashOutCmd,

		"send":                   SendChequeCmd,
		"sendlist":               ListSendChequesCmd,
		"sendlistall":            ListSendChequesAllCmd,
		"send-history-peer":      ChequeSendHistoryPeerCmd,
		"send-history-list":      ChequeSendHistoryListCmd,
		"send-history-stats":     ChequeSendHistoryStatsCmd,
		"send-history-stats-all": ChequeSendHistoryStatsAllCmd,
		"send-total-count":       SendChequesCountCmd,

		"receive":                   ReceiveChequeCmd,
		"receivelist":               ListReceiveChequeCmd,
		"receivelistall":            ListReceiveChequeAllCmd,
		"receive-history-peer":      ChequeReceiveHistoryPeerCmd,
		"receive-history-list":      ChequeReceiveHistoryListCmd,
		"receive-history-stats":     ChequeReceiveHistoryStatsCmd,
		"receive-history-stats-all": ChequeReceiveHistoryStatsAllCmd,
		"receive-total-count":       ReceiveChequesCountCmd,
		"stats":                     ChequeStatsCmd,
		"stats-all":                 ChequeStatsAllCmd,

		"chaininfo":         ChequeChainInfoCmd,
		"bttbalance":        ChequeBttBalanceCmd,
		"token_balance":     ChequeTokenBalanceCmd,
		"all_token_balance": ChequeAllTokenBalanceCmd,
	},
}
View Source
var ChequeReceiveHistoryListCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Display the received cheques from peer.",
	},
	Arguments: []cmds.Argument{
		cmds.StringArg("from", true, false, "page offset"),
		cmds.StringArg("limit", true, false, "page limit."),
	},
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		from, err := strconv.Atoi(req.Arguments[0])
		if err != nil {
			return fmt.Errorf("parse from:%v failed", req.Arguments[0])
		}
		limit, err := strconv.Atoi(req.Arguments[1])
		if err != nil {
			return fmt.Errorf("parse limit:%v failed", req.Arguments[1])
		}

		if from < 0 {
			return fmt.Errorf("invalid from: %d", from)
		}
		if limit < 0 {
			return fmt.Errorf("invalid limit: %d", limit)
		}

		var listRet chequeReceivedHistoryListRet
		records, err := chain.SettleObject.SwapService.ReceivedChequeRecordsAll()
		if err != nil {
			return err
		}
		sort.Slice(records, func(i, j int) bool {
			return records[i].ReceiveTime > records[j].ReceiveTime
		})
		listRet.Total = len(records)
		ret := make([]chequeRecordRet, 0, limit)
		if from < len(records) {
			if (from + limit) <= len(records) {
				records = records[from : from+limit]
			} else {
				records = records[from:]
			}
			for _, result := range records {
				peer, known, err := chain.SettleObject.SwapService.VaultPeer(result.Vault)
				if err == nil {
					if !known {
						peer = "unknown"
					}
					r := chequeRecordRet{
						PeerId:      peer,
						Token:       result.Token,
						Vault:       result.Vault,
						Beneficiary: result.Beneficiary,
						Amount:      result.Amount,
						Time:        result.ReceiveTime,
					}
					ret = append(ret, r)
				}
			}
		}
		listRet.Records = ret

		return cmds.EmitOnce(res, &listRet)
	},
	Type: chequeReceivedHistoryListRet{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *chequeReceivedHistoryListRet) error {
			marshaled, err := json.MarshalIndent(out, "", "\t")
			if err != nil {
				return err
			}
			marshaled = append(marshaled, byte('\n'))
			fmt.Fprintln(w, string(marshaled))
			return nil
		}),
	},
}
View Source
var ChequeReceiveHistoryPeerCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Display the received cheques from peer.",
	},
	Arguments: []cmds.Argument{
		cmds.StringArg("peer-id", true, false, "The peer id of cheques received."),
	},
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		var listRet ChequeRecords
		peer_id := req.Arguments[0]
		fmt.Println("ChequeReceiveHistoryPeerCmd peer_id = ", peer_id)

		records, err := chain.SettleObject.SwapService.ReceivedChequeRecordsByPeer(peer_id)
		if err != nil {
			return err
		}

		recordsRet := []chequeRecordRet{}
		for _, v := range records {
			recordsRet = append(recordsRet, chequeRecordRet{
				PeerId:      peer_id,
				Token:       v.Token,
				Vault:       v.Vault,
				Beneficiary: v.Beneficiary,
				Amount:      v.Amount,
				Time:        v.ReceiveTime,
			})
		}

		listRet.Records = recordsRet
		listRet.Len = len(recordsRet)

		return cmds.EmitOnce(res, &listRet)
	},
	Type: ChequeRecords{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *ChequeRecords) error {
			var tm time.Time
			fmt.Fprintf(w, "\t%-46s\t%-46s\t%-10s\ttimestamp: \n", "beneficiary:", "vault:", "amount:")
			for index := 0; index < out.Len; index++ {
				tm = time.Unix(out.Records[index].Time, 0)
				year, mon, day := tm.Date()
				h, m, s := tm.Clock()
				fmt.Fprintf(w, "\t%-46s\t%-46s\t%-10d\t%d-%d-%d %02d:%02d:%02d \n",
					out.Records[index].Beneficiary,
					out.Records[index].Vault,
					out.Records[index].Amount.Uint64(),
					year, mon, day, h, m, s)
			}

			return nil
		}),
	},
}
View Source
var ChequeReceiveHistoryStatsAllCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Display the received cheques from peer, of all tokens.",
	},
	Options: []cmds.Option{
		cmds.StringOption(tokencfg.TokenTypeName, "tk", "file storage with token type,default WBTT, other TRX/USDD/USDT.").WithDefault("WBTT"),
	},
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		mp := make(map[string][]chequeReceivedHistoryStats, 0)
		for k, tokenAddr := range tokencfg.MpTokenAddr {

			// now only return 30days cheque received stats
			const receivedStatsDuration = 30
			stats, err := chain.SettleObject.ChequeStore.ReceivedStatsHistory(receivedStatsDuration, tokenAddr)
			if err != nil {
				return err
			}

			ret := make([]chequeReceivedHistoryStats, 0, len(stats))
			for _, stat := range stats {
				ret = append(ret, chequeReceivedHistoryStats{
					TotalReceived:      stat.Amount,
					TotalReceivedCount: stat.Count,
					Date:               stat.Date,
				})
			}

			mp[k] = ret
		}

		return cmds.EmitOnce(res, &mp)
	},
	Type: []chequeReceivedHistoryStats{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *[]chequeReceivedHistoryStats) error {
			marshaled, err := json.MarshalIndent(out, "", "\t")
			if err != nil {
				return err
			}
			marshaled = append(marshaled, byte('\n'))
			fmt.Fprintln(w, string(marshaled))
			return nil
		}),
	},
}
View Source
var ChequeReceiveHistoryStatsCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Display the received cheques from peer.",
	},
	Options: []cmds.Option{
		cmds.StringOption(tokencfg.TokenTypeName, "tk", "file storage with token type,default WBTT, other TRX/USDD/USDT.").WithDefault("WBTT"),
	},
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		tokenStr := req.Options[tokencfg.TokenTypeName].(string)

		token, bl := tokencfg.MpTokenAddr[tokenStr]
		if !bl {
			return errors.New("your input token is none. ")
		}

		// now only return 30days cheque received stats
		const receivedStatsDuration = 30
		stats, err := chain.SettleObject.ChequeStore.ReceivedStatsHistory(receivedStatsDuration, token)
		if err != nil {
			return err
		}

		ret := make([]chequeReceivedHistoryStats, 0, len(stats))
		for _, stat := range stats {
			ret = append(ret, chequeReceivedHistoryStats{
				TotalReceived:      stat.Amount,
				TotalReceivedCount: stat.Count,
				Date:               stat.Date,
			})
		}
		return cmds.EmitOnce(res, &ret)
	},
	Type: []chequeReceivedHistoryStats{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *[]chequeReceivedHistoryStats) error {
			marshaled, err := json.MarshalIndent(out, "", "\t")
			if err != nil {
				return err
			}
			marshaled = append(marshaled, byte('\n'))
			fmt.Fprintln(w, string(marshaled))
			return nil
		}),
	},
}
View Source
var ChequeSendHistoryListCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Display the send cheques from peer.",
	},
	Arguments: []cmds.Argument{
		cmds.StringArg("from", true, false, "page offset"),
		cmds.StringArg("limit", true, false, "page limit."),
	},

	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		from, err := strconv.Atoi(req.Arguments[0])
		if err != nil {
			return fmt.Errorf("parse from:%v failed", req.Arguments[0])
		}
		limit, err := strconv.Atoi(req.Arguments[1])
		if err != nil {
			return fmt.Errorf("parse limit:%v failed", req.Arguments[1])
		}
		if from < 0 {
			return fmt.Errorf("invalid from: %d", from)
		}
		if limit < 0 {
			return fmt.Errorf("invalid limit: %d", limit)
		}

		var listRet chequeReceivedHistoryListRet
		records, err := chain.SettleObject.SwapService.SendChequeRecordsAll()
		if err != nil {
			return err
		}
		sort.Slice(records, func(i, j int) bool {
			return records[i].ReceiveTime > records[j].ReceiveTime
		})
		listRet.Total = len(records)
		ret := make([]chequeRecordRet, 0, limit)
		if from < len(records) {
			if (from + limit) <= len(records) {
				records = records[from : from+limit]
			} else {
				records = records[from:]
			}
			for _, result := range records {
				peer, known, err := chain.SettleObject.SwapService.BeneficiaryPeer(result.Beneficiary)
				if err == nil {
					if !known {
						peer = "unknown"
					}
					r := chequeRecordRet{
						PeerId:      peer,
						Token:       result.Token,
						Vault:       result.Vault,
						Beneficiary: result.Beneficiary,
						Amount:      result.Amount,
						Time:        result.ReceiveTime,
					}
					ret = append(ret, r)
				}
			}
		}
		listRet.Records = ret

		return cmds.EmitOnce(res, &listRet)
	},
	Type: chequeReceivedHistoryListRet{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *chequeReceivedHistoryListRet) error {
			marshaled, err := json.MarshalIndent(out, "", "\t")
			if err != nil {
				return err
			}
			marshaled = append(marshaled, byte('\n'))
			fmt.Fprintln(w, string(marshaled))
			return nil
		}),
	},
}
View Source
var ChequeSendHistoryPeerCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Display the send cheques from peer.",
	},
	Arguments: []cmds.Argument{
		cmds.StringArg("peer-id", true, false, "The peer id of cheques send."),
	},

	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		var listRet ChequeRecords
		peer_id := req.Arguments[0]
		fmt.Println("ChequeReceiveHistoryPeerCmd peer_id = ", peer_id)

		records, err := chain.SettleObject.SwapService.SendChequeRecordsByPeer(peer_id)
		if err != nil {
			return err
		}
		recordsRet := []chequeRecordRet{}
		for _, v := range records {
			recordsRet = append(recordsRet, chequeRecordRet{
				PeerId:      peer_id,
				Token:       v.Token,
				Vault:       v.Vault,
				Beneficiary: v.Beneficiary,
				Amount:      v.Amount,
				Time:        v.ReceiveTime,
			})
		}

		listRet.Records = recordsRet
		listRet.Len = len(recordsRet)

		return cmds.EmitOnce(res, &listRet)
	},
	Type: ChequeRecords{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *ChequeRecords) error {
			var tm time.Time
			fmt.Fprintf(w, "\t%-46s\t%-46s\t%-10s\ttimestamp: \n", "beneficiary:", "vault:", "amount:")
			for index := 0; index < out.Len; index++ {
				tm = time.Unix(out.Records[index].Time, 0)
				year, mon, day := tm.Date()
				h, m, s := tm.Clock()
				fmt.Fprintf(w, "\t%-46s\t%-46s\t%-10d\t%d-%d-%d %02d:%02d:%02d \n",
					out.Records[index].Beneficiary,
					out.Records[index].Vault,
					out.Records[index].Amount.Uint64(),
					year, mon, day, h, m, s)
			}

			return nil
		}),
	},
}
View Source
var ChequeSendHistoryStatsAllCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Display the received cheques from peer, of all tokens",
	},
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		mp := make(map[string][]chequeSentHistoryStats, 0)
		for k, tokenAddr := range tokencfg.MpTokenAddr {
			// now only return 30days cheque sent stats
			const sentStatsDuration = 30
			stats, err := chain.SettleObject.ChequeStore.SentStatsHistory(sentStatsDuration, tokenAddr)
			if err != nil {
				return err
			}

			ret := make([]chequeSentHistoryStats, 0, len(stats))
			for _, stat := range stats {
				ret = append(ret, chequeSentHistoryStats{
					TotalIssued:      stat.Amount,
					TotalIssuedCount: stat.Count,
					Date:             stat.Date,
				})
			}

			mp[k] = ret
		}

		return cmds.EmitOnce(res, &mp)
	},
	Type: []chequeSentHistoryStats{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *[]chequeSentHistoryStats) error {
			marshaled, err := json.MarshalIndent(out, "", "\t")
			if err != nil {
				return err
			}
			marshaled = append(marshaled, byte('\n'))
			fmt.Fprintln(w, string(marshaled))
			return nil
		}),
	},
}
View Source
var ChequeSendHistoryStatsCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Display the received cheques from peer.",
	},
	Options: []cmds.Option{
		cmds.StringOption(tokencfg.TokenTypeName, "tk", "file storage with token type,default WBTT, other TRX/USDD/USDT.").WithDefault("WBTT"),
	},
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		tokenStr := req.Options[tokencfg.TokenTypeName].(string)

		token, bl := tokencfg.MpTokenAddr[tokenStr]
		if !bl {
			return errors.New("your input token is none. ")
		}

		// now only return 30days cheque sent stats
		const sentStatsDuration = 30
		stats, err := chain.SettleObject.ChequeStore.SentStatsHistory(sentStatsDuration, token)
		if err != nil {
			return err
		}

		ret := make([]chequeSentHistoryStats, 0, len(stats))
		for _, stat := range stats {
			ret = append(ret, chequeSentHistoryStats{
				TotalIssued:      stat.Amount,
				TotalIssuedCount: stat.Count,
				Date:             stat.Date,
			})
		}
		return cmds.EmitOnce(res, &ret)
	},
	Type: []chequeSentHistoryStats{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *[]chequeSentHistoryStats) error {
			marshaled, err := json.MarshalIndent(out, "", "\t")
			if err != nil {
				return err
			}
			marshaled = append(marshaled, byte('\n'))
			fmt.Fprintln(w, string(marshaled))
			return nil
		}),
	},
}
View Source
var ChequeStatsAllCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "List cheque(s) received from peers, of all tokens",
	},
	Options: []cmds.Option{
		cmds.StringOption(tokencfg.TokenTypeName, "tk", "file storage with token type,default WBTT, other TRX/USDD/USDT.").WithDefault("WBTT"),
	},
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		mp := make(map[string]*chequeStats, 0)
		for k, tokenAddr := range tokencfg.MpTokenAddr {
			cs := chequeStats{
				TotalIssued:                big.NewInt(0),
				TotalIssuedCashed:          big.NewInt(0),
				TotalReceived:              big.NewInt(0),
				TotalReceivedUncashed:      big.NewInt(0),
				TotalReceivedDailyUncashed: big.NewInt(0),
			}

			err := GetChequeStatsToken(&cs, tokenAddr)
			if err != nil {
				return err
			}

			mp[k] = &cs
		}

		return cmds.EmitOnce(res, &mp)
	},
	Type: &chequeStats{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *chequeStats) error {
			marshaled, err := json.MarshalIndent(out, "", "\t")
			if err != nil {
				return err
			}
			marshaled = append(marshaled, byte('\n'))
			fmt.Fprintln(w, string(marshaled))
			return nil
		}),
	},
}
View Source
var ChequeStatsCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "List cheque(s) received from peers.",
	},
	Options: []cmds.Option{
		cmds.StringOption(tokencfg.TokenTypeName, "tk", "file storage with token type,default WBTT, other TRX/USDD/USDT.").WithDefault("WBTT"),
	},
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		tokenStr := req.Options[tokencfg.TokenTypeName].(string)

		token, bl := tokencfg.MpTokenAddr[tokenStr]
		if !bl {
			return errors.New("your input token is none. ")
		}

		cs := chequeStats{
			TotalIssued:                big.NewInt(0),
			TotalIssuedCashed:          big.NewInt(0),
			TotalReceived:              big.NewInt(0),
			TotalReceivedUncashed:      big.NewInt(0),
			TotalReceivedDailyUncashed: big.NewInt(0),
		}

		err = GetChequeStatsToken(&cs, token)
		if err != nil {

		}

		return cmds.EmitOnce(res, &cs)
	},
	Type: &chequeStats{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *chequeStats) error {
			marshaled, err := json.MarshalIndent(out, "", "\t")
			if err != nil {
				return err
			}
			marshaled = append(marshaled, byte('\n'))
			fmt.Fprintln(w, string(marshaled))
			return nil
		}),
	},
}
View Source
var ChequeTokenBalanceCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Get one token balance by addr.",
	},
	Arguments: []cmds.Argument{
		cmds.StringArg("addr", true, false, "bttc account address"),
	},
	Options: []cmds.Option{
		cmds.StringOption(tokencfg.TokenTypeName, "tk", "file storage with token type,default WBTT, other TRX/USDD/USDT.").WithDefault("WBTT"),
	},
	RunTimeout: 5 * time.Minute,
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		addr := req.Arguments[0]

		tokenStr := req.Options[tokencfg.TokenTypeName].(string)

		_, bl := tokencfg.MpTokenAddr[tokenStr]
		if !bl {
			return errors.New("your input token is none. ")
		}

		balance, err := chain.SettleObject.VaultService.TokenBalanceOf(context.Background(), common.HexToAddress(addr), tokenStr)
		if err != nil {
			return err
		}

		return cmds.EmitOnce(res, &ChequeBttBalanceCmdRet{
			Balance: balance,
		})
	},
	Type: &ChequeBttBalanceCmdRet{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *ChequeBttBalanceCmdRet) error {
			_, err := fmt.Fprintf(w, "the balance is: %v\n", out.Balance)
			return err
		}),
	},
}
View Source
var FixChequeCashOutCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "List cheque(s) received from peers.",
	},
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		listRet := ListFixChequeRet{}
		listRet.FixCheques = make([]fixCheque, 0)

		for _, tokenAddr := range tokencfg.MpTokenAddr {
			cheques, err := chain.SettleObject.SwapService.LastReceivedCheques(tokenAddr)
			if err != nil {
				return err
			}

			for k, v := range cheques {
				totalCashOutAmount, newCashOutAmount, err := chain.SettleObject.CashoutService.AdjustCashCheque(
					context.Background(), v.Vault, v.Beneficiary, tokenAddr)
				if err != nil {
					return err
				}
				if newCashOutAmount != nil && newCashOutAmount.Uint64() > 0 {
					var record fixCheque
					record.PeerID = k
					record.Token = v.Token.String()
					record.Beneficiary = v.Beneficiary.String()
					record.Vault = v.Vault.String()
					record.TotalCashedAmount = totalCashOutAmount
					record.FixCashedAmount = newCashOutAmount

					listRet.FixCheques = append(listRet.FixCheques, record)
				}
			}
		}
		listRet.Len = len(listRet.FixCheques)

		log.Infof("FixChequeCashOutCmd, listRet = %+v", listRet)

		return cmds.EmitOnce(res, &listRet)
	},
	Type: ListFixChequeRet{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *ListFixChequeRet) error {
			fmt.Fprintf(w, "fix: \n\t%-55s\t%-46s\t%-46s\t%-46s\tfix_cash_amount: \n", "peerID:", "vault:", "beneficiary:", "total_cash_amount:")
			for iter := 0; iter < out.Len; iter++ {
				fmt.Fprintf(w, "\t%-55s\t%-46s\t%-46s\t%d\t%d \n",
					out.FixCheques[iter].PeerID,
					out.FixCheques[iter].Vault,
					out.FixCheques[iter].Beneficiary,
					out.FixCheques[iter].TotalCashedAmount.Uint64(),
					out.FixCheques[iter].FixCashedAmount.Uint64(),
				)
			}

			return nil
		}),
	},
}
View Source
var ListReceiveChequeAllCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "List cheque(s) received from peers.",
	},
	Arguments: []cmds.Argument{
		cmds.StringArg("offset", true, false, "page offset"),
		cmds.StringArg("limit", true, false, "page limit."),
	},
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		offset, err := strconv.Atoi(req.Arguments[0])
		if err != nil {
			return fmt.Errorf("parse offset:%v failed", req.Arguments[0])
		}
		limit, err := strconv.Atoi(req.Arguments[1])
		if err != nil {
			return fmt.Errorf("parse limit:%v failed", req.Arguments[1])
		}

		listCheques := make([]ReceiveCheque, 0)
		for _, tokenAddr := range tokencfg.MpTokenAddr {
			cheques, err := chain.SettleObject.SwapService.LastReceivedCheques(tokenAddr)
			if err != nil {
				return err
			}
			for k, v := range cheques {
				var record ReceiveCheque
				record.PeerID = k
				record.Token = tokenAddr
				record.Vault = v.Vault
				record.Beneficiary = v.Beneficiary
				record.CumulativePayout = v.CumulativePayout

				listCheques = append(listCheques, record)
			}
		}

		sort.Slice(listCheques, func(i, j int) bool {
			return listCheques[i].PeerID < listCheques[j].PeerID
		})

		if len(listCheques) < offset+1 {
			listCheques = listCheques[0:0]
		} else {
			listCheques = listCheques[offset:]
		}

		if len(listCheques) > limit {
			listCheques = listCheques[:limit]
		}

		var listRet ListChequeRet
		for _, v := range listCheques {
			k := v.PeerID
			var record cheque
			record.PeerID = k
			record.Token = v.Token.String()
			record.Beneficiary = v.Beneficiary.String()
			record.Vault = v.Vault.String()
			record.Payout = v.CumulativePayout

			cashStatus, err := chain.SettleObject.CashoutService.CashoutStatus(context.Background(), v.Vault, v.Token)
			if err != nil {
				return err
			}
			if cashStatus.UncashedAmount != nil {
				record.CashedAmount = big.NewInt(0).Sub(v.CumulativePayout, cashStatus.UncashedAmount)
			}

			listRet.Cheques = append(listRet.Cheques, record)
		}

		listRet.Len = len(listRet.Cheques)
		return cmds.EmitOnce(res, &listRet)
	},
	Type: ListChequeRet{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *ListChequeRet) error {
			fmt.Fprintf(w, "\t%-55s\t%-46s\t%-46s\t%-46s\tamount: \n", "peerID:", "vault:", "beneficiary:", "cashout_amount:")
			for iter := 0; iter < out.Len; iter++ {
				fmt.Fprintf(w, "\t%-55s\t%-46s\t%-46s\t%d\t%d \n",
					out.Cheques[iter].PeerID,
					out.Cheques[iter].Beneficiary,
					out.Cheques[iter].Vault,
					out.Cheques[iter].Payout.Uint64(),
					out.Cheques[iter].CashedAmount.Uint64(),
				)
			}

			return nil
		}),
	},
}
View Source
var ListReceiveChequeCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "List cheque(s) received from peers.",
	},
	Arguments: []cmds.Argument{
		cmds.StringArg("offset", true, false, "page offset"),
		cmds.StringArg("limit", true, false, "page limit."),
	},
	Options: []cmds.Option{
		cmds.StringOption(tokencfg.TokenTypeName, "tk", "file storage with token type,default WBTT, other TRX/USDD/USDT.").WithDefault("WBTT"),
	},
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		offset, err := strconv.Atoi(req.Arguments[0])
		if err != nil {
			return fmt.Errorf("parse offset:%v failed", req.Arguments[0])
		}
		limit, err := strconv.Atoi(req.Arguments[1])
		if err != nil {
			return fmt.Errorf("parse limit:%v failed", req.Arguments[1])
		}
		tokenStr := req.Options[tokencfg.TokenTypeName].(string)

		token, bl := tokencfg.MpTokenAddr[tokenStr]
		if !bl {
			return errors.New("your input token is none. ")
		}

		var listRet ListChequeRet
		cheques, err := chain.SettleObject.SwapService.LastReceivedCheques(token)

		if err != nil {
			return err
		}
		peerIds := make([]string, 0, len(cheques))
		for key := range cheques {
			peerIds = append(peerIds, key)
		}
		sort.Strings(peerIds)

		if len(peerIds) < offset+1 {
			peerIds = peerIds[0:0]
		} else {
			peerIds = peerIds[offset:]
		}

		if len(peerIds) > limit {
			peerIds = peerIds[:limit]
		}

		for _, k := range peerIds {
			v := cheques[k]
			var record cheque
			record.PeerID = k
			record.Token = v.Token.String()
			record.Beneficiary = v.Beneficiary.String()
			record.Vault = v.Vault.String()
			record.Payout = v.CumulativePayout

			cashStatus, err := chain.SettleObject.CashoutService.CashoutStatus(context.Background(), v.Vault, token)
			if err != nil {
				return err
			}
			if cashStatus.UncashedAmount != nil {
				record.CashedAmount = big.NewInt(0).Sub(v.CumulativePayout, cashStatus.UncashedAmount)
			}

			listRet.Cheques = append(listRet.Cheques, record)
		}
		listRet.Len = len(listRet.Cheques)
		return cmds.EmitOnce(res, &listRet)
	},
	Type: ListChequeRet{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *ListChequeRet) error {
			fmt.Fprintf(w, "\t%-55s\t%-46s\t%-46s\t%-46s\tamount: \n", "peerID:", "vault:", "beneficiary:", "cashout_amount:")
			for iter := 0; iter < out.Len; iter++ {
				fmt.Fprintf(w, "\t%-55s\t%-46s\t%-46s\t%d\t%d \n",
					out.Cheques[iter].PeerID,
					out.Cheques[iter].Beneficiary,
					out.Cheques[iter].Vault,
					out.Cheques[iter].Payout.Uint64(),
					out.Cheques[iter].CashedAmount.Uint64(),
				)
			}

			return nil
		}),
	},
}
View Source
var ListSendChequesAllCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "List cheque(s) send to peers.",
	},
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		listRet := ListChequeRet{}
		listRet.Cheques = make([]cheque, 0, 0)
		listRet.Len = 0

		for _, tokenAddr := range tokencfg.MpTokenAddr {
			cheques, err := chain.SettleObject.SwapService.LastSendCheques(tokenAddr)
			if err != nil {
				return err
			}
			for k, v := range cheques {
				var record cheque
				record.PeerID = k
				record.Token = v.Token.String()
				record.Beneficiary = v.Beneficiary.String()
				record.Vault = v.Vault.String()
				record.Payout = v.CumulativePayout

				listRet.Cheques = append(listRet.Cheques, record)
			}

			listRet.Len += len(cheques)
		}

		return cmds.EmitOnce(res, &listRet)
	},
	Type: ListChequeRet{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *ListChequeRet) error {
			fmt.Fprintf(w, "\t%-55s\t%-46s\t%-46s\tamount: \n", "peerID:", "vault:", "beneficiary:")
			for iter := 0; iter < out.Len; iter++ {
				fmt.Fprintf(w, "\t%-55s\t%-46s\t%-46s\t%d \n",
					out.Cheques[iter].PeerID,
					out.Cheques[iter].Vault,
					out.Cheques[iter].Beneficiary,
					out.Cheques[iter].Payout.Uint64(),
				)
			}

			return nil
		}),
	},
}
View Source
var ListSendChequesCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "List cheque(s) send to peers.",
	},
	Options: []cmds.Option{
		cmds.StringOption(tokencfg.TokenTypeName, "tk", "file storage with token type,default WBTT, other TRX/USDD/USDT.").WithDefault("WBTT"),
	},
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		tokenStr := req.Options[tokencfg.TokenTypeName].(string)

		token, bl := tokencfg.MpTokenAddr[tokenStr]
		if !bl {
			return errors.New("your input token is none. ")
		}

		listRet := ListChequeRet{}
		listRet.Cheques = make([]cheque, 0, 0)
		cheques, err := chain.SettleObject.SwapService.LastSendCheques(token)

		if err != nil {
			return err
		}
		for k, v := range cheques {
			var record cheque
			record.PeerID = k
			record.Token = v.Token.String()
			record.Beneficiary = v.Beneficiary.String()
			record.Vault = v.Vault.String()
			record.Payout = v.CumulativePayout

			listRet.Cheques = append(listRet.Cheques, record)
		}

		listRet.Len = len(listRet.Cheques)

		return cmds.EmitOnce(res, &listRet)
	},
	Type: ListChequeRet{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *ListChequeRet) error {
			fmt.Fprintf(w, "\t%-55s\t%-46s\t%-46s\tamount: \n", "peerID:", "vault:", "beneficiary:")
			for iter := 0; iter < out.Len; iter++ {
				fmt.Fprintf(w, "\t%-55s\t%-46s\t%-46s\t%d \n",
					out.Cheques[iter].PeerID,
					out.Cheques[iter].Vault,
					out.Cheques[iter].Beneficiary,
					out.Cheques[iter].Payout.Uint64(),
				)
			}

			return nil
		}),
	},
}
View Source
var ReceiveChequeCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "List cheque(s) received from peers.",
	},
	Arguments: []cmds.Argument{
		cmds.StringArg("peer-id", true, false, "deposit amount."),
	},
	Options: []cmds.Option{
		cmds.StringOption(tokencfg.TokenTypeName, "tk", "file storage with token type,default WBTT, other TRX/USDD/USDT.").WithDefault("WBTT"),
	},
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		var record cheque
		peer_id := req.Arguments[0]
		tokenStr := req.Options[tokencfg.TokenTypeName].(string)
		fmt.Printf("ReceiveChequeCmd peer_id:%+v, token:%+v\n", peer_id, tokenStr)
		token, bl := tokencfg.MpTokenAddr[tokenStr]
		if !bl {
			return errors.New("your input token is none. ")
		}

		if len(peer_id) > 0 {
			chequeTmp, err := chain.SettleObject.SwapService.LastReceivedCheque(peer_id, token)
			if err != nil {
				return err
			}

			record.Beneficiary = chequeTmp.Beneficiary.String()
			record.Vault = chequeTmp.Vault.String()
			record.Payout = chequeTmp.CumulativePayout
			record.PeerID = peer_id

			cashStatus, err := chain.SettleObject.CashoutService.CashoutStatus(context.Background(), chequeTmp.Vault, token)
			if err != nil {
				return err
			}
			if cashStatus.UncashedAmount != nil {
				record.CashedAmount = big.NewInt(0).Sub(chequeTmp.CumulativePayout, cashStatus.UncashedAmount)
			}
		}

		return cmds.EmitOnce(res, &record)
	},
	Type: cheque{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *cheque) error {

			fmt.Fprintf(w, "\t%-55s\t%-46s\t%-46s\t%-46s\tamount: \n", "peerID:", "vault:", "beneficiary:", "cashout_amount:")
			fmt.Fprintf(w, "\t%-55s\t%-46s\t%-46s\t%d\t%d \n",
				out.PeerID,
				out.Beneficiary,
				out.Vault,
				out.Payout.Uint64(),
				out.CashedAmount.Uint64(),
			)

			return nil
		}),
	},
}
View Source
var ReceiveChequesCountCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "send cheque(s) count",
	},

	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		count, err := chain.SettleObject.SwapService.ReceivedChequeRecordsCount()
		if err != nil {
			return err
		}

		return cmds.EmitOnce(res, &ReceiveTotalCountRet{Count: count})
	},
	Type: ReceiveTotalCountRet{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, c *ReceiveTotalCountRet) error {
			fmt.Println("receive cheque(s) count: ", c.Count)

			return nil
		}),
	},
}
View Source
var SendChequeCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "List cheque send to peers.",
	},
	Arguments: []cmds.Argument{
		cmds.StringArg("peer-id", true, false, "deposit amount."),
	},
	Options: []cmds.Option{
		cmds.StringOption(tokencfg.TokenTypeName, "tk", "file storage with token type,default WBTT, other TRX/USDD/USDT.").WithDefault("WBTT"),
	},
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		var record cheque
		peer_id := req.Arguments[0]
		fmt.Println("SendChequeCmd peer_id = ", peer_id)

		tokenStr := req.Options[tokencfg.TokenTypeName].(string)

		token, bl := tokencfg.MpTokenAddr[tokenStr]
		if !bl {
			return errors.New("your input token is none. ")
		}

		if len(peer_id) > 0 {
			chequeTmp, err := chain.SettleObject.SwapService.LastSendCheque(peer_id, token)
			if err != nil {
				return err
			}

			record.Beneficiary = chequeTmp.Beneficiary.String()
			record.Vault = chequeTmp.Vault.String()
			record.Payout = chequeTmp.CumulativePayout
			record.PeerID = peer_id
		}

		return cmds.EmitOnce(res, &record)
	},
	Type: cheque{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *cheque) error {

			fmt.Fprintf(w, "\t%-55s\t%-46s\t%-46s\tamount: \n", "peerID:", "vault:", "beneficiary:")
			fmt.Fprintf(w, "\t%-55s\t%-46s\t%-46s\t%d \n",
				out.PeerID,
				out.Vault,
				out.Beneficiary,
				out.Payout.Uint64(),
			)

			return nil
		}),
	},
}
View Source
var SendChequesCountCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "send cheque(s) count",
	},
	Options: []cmds.Option{
		cmds.StringOption(tokencfg.TokenTypeName, "tk", "file storage with token type,default WBTT, other TRX/USDD/USDT.").WithDefault("WBTT"),
	},
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		tokenStr := req.Options[tokencfg.TokenTypeName].(string)

		token, bl := tokencfg.MpTokenAddr[tokenStr]
		if !bl {
			return errors.New("your input token is none. ")
		}

		count, err := chain.SettleObject.VaultService.TotalIssuedCount(token)
		if err != nil {
			return err
		}

		return cmds.EmitOnce(res, &SendTotalCountRet{Count: count})
	},
	Type: SendTotalCountRet{},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, c *SendTotalCountRet) error {
			fmt.Println("send cheque(s) count: ", c.Count)

			return nil
		}),
	},
}
View Source
var StorePriceAllCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Get btfs all price.",
	},
	RunTimeout: 5 * time.Minute,
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		mp := make(map[string]*PriceInfo, 0)
		for k, token := range tokencfg.MpTokenAddr {

			price, err := chain.SettleObject.OracleService.CurrentPrice(token)
			if err != nil {
				return err
			}

			rate, err := chain.SettleObject.OracleService.CurrentRate(token)
			if err != nil {
				return err
			}

			totalPrice, err := chain.SettleObject.OracleService.CurrentTotalPrice(token)
			if err != nil {
				return err
			}

			priceInfo := PriceInfo{
				Token:      token.String(),
				TokenStr:   k,
				Price:      price.String(),
				Rate:       rate.String(),
				TotalPrice: totalPrice.String(),
			}

			mp[k] = &priceInfo
		}

		return cmds.EmitOnce(res, &mp)
	},
}
View Source
var StorePriceCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Get btfs token price.",
	},
	Options: []cmds.Option{
		cmds.StringOption(tokencfg.TokenTypeName, "tk", "file storage with token type,default WBTT, other TRX/USDD/USDT.").WithDefault("WBTT"),
	},
	RunTimeout: 5 * time.Minute,
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		err := utils.CheckSimpleMode(env)
		if err != nil {
			return err
		}

		tokenStr := req.Options[tokencfg.TokenTypeName].(string)

		token, bl := tokencfg.MpTokenAddr[tokenStr]
		if !bl {
			return errors.New("your input token is none. ")
		}

		price, err := chain.SettleObject.OracleService.CurrentPrice(token)
		if err != nil {
			return err
		}

		rate, err := chain.SettleObject.OracleService.CurrentRate(token)
		if err != nil {
			return err
		}

		totalPrice, err := chain.SettleObject.OracleService.CurrentTotalPrice(token)
		if err != nil {
			return err
		}

		priceInfo := PriceInfo{
			Token:      token.String(),
			TokenStr:   tokenStr,
			Price:      price.String(),
			Rate:       rate.String(),
			TotalPrice: totalPrice.String(),
		}

		return cmds.EmitOnce(res, &priceInfo)
	},
}

Functions

func GetChequeStatsToken

func GetChequeStatsToken(cs *chequeStats, token common.Address) error

Types

type CashChequeRet

type CashChequeRet struct {
	TxHash string
}

type CashOutStatusRet

type CashOutStatusRet struct {
	Status         string   `json:"status"` // pending,fail,success,not_found
	TotalPayout    *big.Int `json:"total_payout"`
	UncashedAmount *big.Int `json:"uncashed_amount"` // amount not yet cashed out
}

type ChainInfoRet

type ChainInfoRet struct {
	ChainId            int64  `json:"chain_id"`
	NodeAddr           string `json:"node_addr"`
	VaultAddr          string `json:"vault_addr"`
	WalletImportPrvKey string `json:"wallet_import_prv_key"`
}

type ChequeBttBalanceCmdRet

type ChequeBttBalanceCmdRet struct {
	Balance *big.Int `json:"balance"`
}

type ChequeCashListRet

type ChequeCashListRet struct {
	TxHash   string   `json:"tx_hash"`
	PeerID   string   `json:"peer_id"`
	Token    string   `json:"token"`
	Vault    string   `json:"vault"`
	Amount   *big.Int `json:"amount"`
	CashTime int64    `json:"cash_time"`
	Status   string   `json:"status"`
}

type ChequeCashListRsp

type ChequeCashListRsp struct {
	Records []ChequeCashListRet `json:"records"`
	Total   int                 `json:"total"`
}

type ChequeRecords

type ChequeRecords struct {
	Records []chequeRecordRet
	Len     int
}

type ListChequeRet

type ListChequeRet struct {
	Cheques []cheque
	Len     int
}

type ListFixChequeRet

type ListFixChequeRet struct {
	FixCheques []fixCheque
	Len        int
}

type PriceInfo

type PriceInfo struct {
	Token      string `json:"token"`
	TokenStr   string `json:"token_str"`
	Price      string `json:"price"`
	Rate       string `json:"rate"`
	TotalPrice string `json:"total_price"`
}

type ReceiveCheque

type ReceiveCheque struct {
	PeerID           string
	Token            common.Address
	Vault            common.Address
	Beneficiary      common.Address
	CumulativePayout *big.Int
}

type ReceiveTotalCountRet

type ReceiveTotalCountRet struct {
	Count int `json:"count"`
}

type SendTotalCountRet

type SendTotalCountRet struct {
	Count int `json:"count"`
}

type StorePriceRet

type StorePriceRet struct {
	Price *big.Int `json:"price"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL