Skip to content

Commit

Permalink
use options
Browse files Browse the repository at this point in the history
  • Loading branch information
unclezoro committed Jun 3, 2019
1 parent eafffc6 commit 3415adc
Show file tree
Hide file tree
Showing 16 changed files with 99 additions and 66 deletions.
2 changes: 1 addition & 1 deletion ReadMe.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ If you want broadcast some transactions, like send coins, create orders or cance

Create a `buy` order:
```go
createOrderResult, err := client.CreateOrder(tradeSymbol, nativeSymbol, txmsg.OrderSide.BUY, 100000000, 100000000, true, "", tx.Source)
createOrderResult, err := client.CreateOrder(tradeSymbol, nativeSymbol, txmsg.OrderSide.BUY, 100000000, 100000000, true)
```

For more API usage documentation, please check the [wiki](https://github.com/binance-chain/go-sdk/wiki)..
Expand Down
34 changes: 23 additions & 11 deletions client/rpc/ws_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -640,6 +640,18 @@ func (c *WSClient) CallWithArrayParams(ctx context.Context, method string, param
return c.Send(ctx, request)
}

func (c *WSClient) GetConnection() *websocket.Conn {
c.mtx.RLock()
defer c.mtx.RUnlock()
return c.conn
}

func (c *WSClient) SetConnection(conn *websocket.Conn) {
c.mtx.Lock()
defer c.mtx.Unlock()
c.conn = conn
}

func (c *WSClient) Codec() *amino.Codec {
return c.cdc
}
Expand Down Expand Up @@ -673,7 +685,7 @@ func (c *WSClient) dial() error {
if err != nil {
return err
}
c.conn = conn
c.SetConnection(conn)
return nil
}

Expand Down Expand Up @@ -781,7 +793,7 @@ func (c *WSClient) writeRoutine() {

defer func() {
ticker.Stop()
if err := c.conn.Close(); err != nil {
if err := c.GetConnection().Close(); err != nil {
// ignore error; it will trigger in tests
// likely because it's closing an already closed connection
}
Expand All @@ -791,28 +803,28 @@ func (c *WSClient) writeRoutine() {
select {
case request := <-c.send:
if c.writeWait > 0 {
if err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {
if err := c.GetConnection().SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {
c.Logger.Error("failed to set write deadline", "err", err)
}
}
if err := c.conn.WriteJSON(request); err != nil {
if err := c.GetConnection().WriteJSON(request); err != nil {
c.Logger.Error("failed to send request", "err", err)
c.reconnectAfter <- err
}
case <-ticker.C:
if c.writeWait > 0 {
if err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {
if err := c.GetConnection().SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {
c.Logger.Error("failed to set write deadline", "err", err)
}
}
if err := c.conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
if err := c.GetConnection().WriteMessage(websocket.PingMessage, []byte{}); err != nil {
c.Logger.Error("failed to write ping", "err", err)
c.reconnectAfter <- err
continue
}
c.Logger.Debug("sent ping")
case <-c.Quit():
if err := c.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")); err != nil {
if err := c.GetConnection().WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")); err != nil {
c.Logger.Error("failed to write message", "err", err)
}
return
Expand All @@ -824,25 +836,25 @@ func (c *WSClient) writeRoutine() {
// executing all reads from this goroutine.
func (c *WSClient) readRoutine() {
defer func() {
if err := c.conn.Close(); err != nil {
if err := c.GetConnection().Close(); err != nil {
// ignore error; it will trigger in tests
// likely because it's closing an already closed connection
}
}()
c.wg.Wait()
c.conn.SetPongHandler(func(string) error {
c.GetConnection().SetPongHandler(func(string) error {
c.Logger.Debug("got pong")
return nil
})

for {
// reset deadline for every message type (control or data)
if c.readWait > 0 {
if err := c.conn.SetReadDeadline(time.Now().Add(c.readWait)); err != nil {
if err := c.GetConnection().SetReadDeadline(time.Now().Add(c.readWait)); err != nil {
c.Logger.Error("failed to set read deadline", "err", err)
}
}
_, data, err := c.conn.ReadMessage()
_, data, err := c.GetConnection().ReadMessage()
if err != nil {
c.Logger.Error("failed to read response", "err", err)
c.reconnectAfter <- err
Expand Down
4 changes: 2 additions & 2 deletions client/transaction/burn_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ type BurnTokenResult struct {
tx.TxCommitResult
}

func (c *client) BurnToken(symbol string, amount int64, sync bool, memo string, source int64) (*BurnTokenResult, error) {
func (c *client) BurnToken(symbol string, amount int64, sync bool, options ...Option) (*BurnTokenResult, error) {
if symbol == "" {
return nil, fmt.Errorf("Burn token symbol can'c be empty ")
}
Expand All @@ -26,7 +26,7 @@ func (c *client) BurnToken(symbol string, amount int64, sync bool, memo string,
if err != nil {
return nil, err
}
commit, err := c.broadcastMsg(burnMsg, sync, memo, source)
commit, err := c.broadcastMsg(burnMsg, sync, options...)
if err != nil {
return nil, err
}
Expand Down
4 changes: 2 additions & 2 deletions client/transaction/cancel_order.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ type CancelOrderResult struct {
tx.TxCommitResult
}

func (c *client) CancelOrder(baseAssetSymbol, quoteAssetSymbol, refId string, sync bool, memo string, source int64) (*CancelOrderResult, error) {
func (c *client) CancelOrder(baseAssetSymbol, quoteAssetSymbol, refId string, sync bool, options ...Option) (*CancelOrderResult, error) {
if baseAssetSymbol == "" || quoteAssetSymbol == "" {
return nil, fmt.Errorf("BaseAssetSymbol or QuoteAssetSymbol is missing. ")
}
Expand All @@ -27,7 +27,7 @@ func (c *client) CancelOrder(baseAssetSymbol, quoteAssetSymbol, refId string, sy
if err != nil {
return nil, err
}
commit, err := c.broadcastMsg(cancelOrderMsg, sync, memo, source)
commit, err := c.broadcastMsg(cancelOrderMsg, sync, options...)
if err != nil {
return nil, err
}
Expand Down
4 changes: 2 additions & 2 deletions client/transaction/create_order.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ type CreateOrderResult struct {
OrderId string
}

func (c *client) CreateOrder(baseAssetSymbol, quoteAssetSymbol string, op int8, price, quantity int64, sync bool, memo string, source int64) (*CreateOrderResult, error) {
func (c *client) CreateOrder(baseAssetSymbol, quoteAssetSymbol string, op int8, price, quantity int64, sync bool, options ...Option) (*CreateOrderResult, error) {
if baseAssetSymbol == "" || quoteAssetSymbol == "" {
return nil, fmt.Errorf("BaseAssetSymbol or QuoteAssetSymbol is missing. ")
}
Expand All @@ -37,7 +37,7 @@ func (c *client) CreateOrder(baseAssetSymbol, quoteAssetSymbol string, op int8,
if err != nil {
return nil, err
}
commit, err := c.broadcastMsg(newOrderMsg, sync, memo, source)
commit, err := c.broadcastMsg(newOrderMsg, sync, options...)
if err != nil {
return nil, err
}
Expand Down
4 changes: 2 additions & 2 deletions client/transaction/deposit_proposal.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ type DepositProposalResult struct {
tx.TxCommitResult
}

func (c *client) DepositProposal(proposalID int64, amount int64, sync bool, memo string, source int64) (*DepositProposalResult, error) {
func (c *client) DepositProposal(proposalID int64, amount int64, sync bool, options ...Option) (*DepositProposalResult, error) {
fromAddr := c.keyManager.GetAddr()
coins := ctypes.Coins{ctypes.Coin{Denom: types.NativeSymbol, Amount: amount}}
depositMsg := msg.NewDepositMsg(fromAddr, proposalID, coins)
err := depositMsg.ValidateBasic()
if err != nil {
return nil, err
}
commit, err := c.broadcastMsg(depositMsg, sync, memo, source)
commit, err := c.broadcastMsg(depositMsg, sync, options...)
if err != nil {
return nil, err
}
Expand Down
4 changes: 2 additions & 2 deletions client/transaction/freeze_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ type FreezeTokenResult struct {
tx.TxCommitResult
}

func (c *client) FreezeToken(symbol string, amount int64, sync bool, memo string, source int64) (*FreezeTokenResult, error) {
func (c *client) FreezeToken(symbol string, amount int64, sync bool, options ...Option) (*FreezeTokenResult, error) {
if symbol == "" {
return nil, fmt.Errorf("Freeze token symbol can'c be empty ")
}
Expand All @@ -26,7 +26,7 @@ func (c *client) FreezeToken(symbol string, amount int64, sync bool, memo string
if err != nil {
return nil, err
}
commit, err := c.broadcastMsg(freezeMsg, sync, memo, source)
commit, err := c.broadcastMsg(freezeMsg, sync, options...)
if err != nil {
return nil, err
}
Expand Down
4 changes: 2 additions & 2 deletions client/transaction/issue_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ type IssueTokenValue struct {
Owner string `json:"owner"`
}

func (c *client) IssueToken(name, symbol string, supply int64, sync bool, mintable bool, memo string, source int64) (*IssueTokenResult, error) {
func (c *client) IssueToken(name, symbol string, supply int64, sync bool, mintable bool, options ...Option) (*IssueTokenResult, error) {
if symbol == "" {
return nil, fmt.Errorf("Freeze token symbol can'c be empty ")
}
Expand All @@ -38,7 +38,7 @@ func (c *client) IssueToken(name, symbol string, supply int64, sync bool, mintab
if err != nil {
return nil, err
}
commit, err := c.broadcastMsg(issueMsg, sync, memo, source)
commit, err := c.broadcastMsg(issueMsg, sync, options...)
if err != nil {
return nil, err
}
Expand Down
4 changes: 2 additions & 2 deletions client/transaction/list_pair.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ type ListPairResult struct {
tx.TxCommitResult
}

func (c *client) ListPair(proposalId int64, baseAssetSymbol string, quoteAssetSymbol string, initPrice int64, sync bool, memo string, source int64) (*ListPairResult, error) {
func (c *client) ListPair(proposalId int64, baseAssetSymbol string, quoteAssetSymbol string, initPrice int64, sync bool, options ...Option) (*ListPairResult, error) {
fromAddr := c.keyManager.GetAddr()

burnMsg := msg.NewDexListMsg(fromAddr, proposalId, baseAssetSymbol, quoteAssetSymbol, initPrice)
err := burnMsg.ValidateBasic()
if err != nil {
return nil, err
}
commit, err := c.broadcastMsg(burnMsg, sync, memo, source)
commit, err := c.broadcastMsg(burnMsg, sync, options...)
if err != nil {
return nil, err
}
Expand Down
4 changes: 2 additions & 2 deletions client/transaction/mint_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ type MintTokenResult struct {
tx.TxCommitResult
}

func (c *client) MintToken(symbol string, amount int64, sync bool, memo string, source int64) (*MintTokenResult, error) {
func (c *client) MintToken(symbol string, amount int64, sync bool, options ...Option) (*MintTokenResult, error) {
if symbol == "" {
return nil, fmt.Errorf("Freeze token symbol can'c be empty ")
}
Expand All @@ -26,7 +26,7 @@ func (c *client) MintToken(symbol string, amount int64, sync bool, memo string,
if err != nil {
return nil, err
}
commit, err := c.broadcastMsg(mintMsg, sync, memo, source)
commit, err := c.broadcastMsg(mintMsg, sync, options...)
if err != nil {
return nil, err
}
Expand Down
4 changes: 2 additions & 2 deletions client/transaction/send_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ type SendTokenResult struct {
tx.TxCommitResult
}

func (c *client) SendToken(transfers []msg.Transfer, sync bool, memo string, source int64) (*SendTokenResult, error) {
func (c *client) SendToken(transfers []msg.Transfer, sync bool, options ...Option) (*SendTokenResult, error) {
fromAddr := c.keyManager.GetAddr()
fromCoins := types.Coins{}
for _, t := range transfers {
Expand All @@ -21,7 +21,7 @@ func (c *client) SendToken(transfers []msg.Transfer, sync bool, memo string, sou
if err != nil {
return nil, err
}
commit, err := c.broadcastMsg(sendMsg, sync, memo, source)
commit, err := c.broadcastMsg(sendMsg, sync, options...)
if err != nil {
return nil, err
}
Expand Down
8 changes: 4 additions & 4 deletions client/transaction/submit_proposal.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,23 @@ type SubmitProposalResult struct {
ProposalId int64 `json:"proposal_id"`
}

func (c *client) SubmitListPairProposal(title string, param msg.ListTradingPairParams, initialDeposit int64, votingPeriod time.Duration, sync bool, memo string, source int64) (*SubmitProposalResult, error) {
func (c *client) SubmitListPairProposal(title string, param msg.ListTradingPairParams, initialDeposit int64, votingPeriod time.Duration, sync bool, options ...Option) (*SubmitProposalResult, error) {
bz, err := json.Marshal(&param)
if err != nil {
return nil, err
}
return c.SubmitProposal(title, string(bz), msg.ProposalTypeListTradingPair, initialDeposit, votingPeriod, sync, memo, source)
return c.SubmitProposal(title, string(bz), msg.ProposalTypeListTradingPair, initialDeposit, votingPeriod, sync, options...)
}

func (c *client) SubmitProposal(title string, description string, proposalType msg.ProposalKind, initialDeposit int64, votingPeriod time.Duration, sync bool, memo string, source int64) (*SubmitProposalResult, error) {
func (c *client) SubmitProposal(title string, description string, proposalType msg.ProposalKind, initialDeposit int64, votingPeriod time.Duration, sync bool, options ...Option) (*SubmitProposalResult, error) {
fromAddr := c.keyManager.GetAddr()
coins := ctypes.Coins{ctypes.Coin{Denom: types.NativeSymbol, Amount: initialDeposit}}
proposalMsg := msg.NewMsgSubmitProposal(title, description, proposalType, fromAddr, coins, votingPeriod)
err := proposalMsg.ValidateBasic()
if err != nil {
return nil, err
}
commit, err := c.broadcastMsg(proposalMsg, sync, memo, source)
commit, err := c.broadcastMsg(proposalMsg, sync, options...)
if err != nil {
return nil, err
}
Expand Down
56 changes: 38 additions & 18 deletions client/transaction/transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,20 @@ import (
)

type TransactionClient interface {
CreateOrder(baseAssetSymbol, quoteAssetSymbol string, op int8, price, quantity int64, sync bool, memo string, source int64) (*CreateOrderResult, error)
CancelOrder(baseAssetSymbol, quoteAssetSymbol, refId string, sync bool, memo string, source int64) (*CancelOrderResult, error)
BurnToken(symbol string, amount int64, sync bool, memo string, source int64) (*BurnTokenResult, error)
ListPair(proposalId int64, baseAssetSymbol string, quoteAssetSymbol string, initPrice int64, sync bool, memo string, source int64) (*ListPairResult, error)
FreezeToken(symbol string, amount int64, sync bool, memo string, source int64) (*FreezeTokenResult, error)
UnfreezeToken(symbol string, amount int64, sync bool, memo string, source int64) (*UnfreezeTokenResult, error)
IssueToken(name, symbol string, supply int64, sync bool, mintable bool, memo string, source int64) (*IssueTokenResult, error)
SendToken(transfers []msg.Transfer, sync bool, memo string, source int64) (*SendTokenResult, error)
MintToken(symbol string, amount int64, sync bool, memo string, source int64) (*MintTokenResult, error)
CreateOrder(baseAssetSymbol, quoteAssetSymbol string, op int8, price, quantity int64, sync bool, options ...Option) (*CreateOrderResult, error)
CancelOrder(baseAssetSymbol, quoteAssetSymbol, refId string, sync bool, options ...Option) (*CancelOrderResult, error)
BurnToken(symbol string, amount int64, sync bool, options ...Option) (*BurnTokenResult, error)
ListPair(proposalId int64, baseAssetSymbol string, quoteAssetSymbol string, initPrice int64, sync bool, options ...Option) (*ListPairResult, error)
FreezeToken(symbol string, amount int64, sync bool, options ...Option) (*FreezeTokenResult, error)
UnfreezeToken(symbol string, amount int64, sync bool, options ...Option) (*UnfreezeTokenResult, error)
IssueToken(name, symbol string, supply int64, sync bool, mintable bool, options ...Option) (*IssueTokenResult, error)
SendToken(transfers []msg.Transfer, sync bool, options ...Option) (*SendTokenResult, error)
MintToken(symbol string, amount int64, sync bool, options ...Option) (*MintTokenResult, error)

SubmitListPairProposal(title string, param msg.ListTradingPairParams, initialDeposit int64, votingPeriod time.Duration, sync bool, memo string, source int64) (*SubmitProposalResult, error)
SubmitProposal(title string, description string, proposalType msg.ProposalKind, initialDeposit int64, votingPeriod time.Duration, sync bool, memo string, source int64) (*SubmitProposalResult, error)
DepositProposal(proposalID int64, amount int64, sync bool, memo string, source int64) (*DepositProposalResult, error)
VoteProposal(proposalID int64, option msg.VoteOption, sync bool, memo string, source int64) (*VoteProposalResult, error)
SubmitListPairProposal(title string, param msg.ListTradingPairParams, initialDeposit int64, votingPeriod time.Duration, sync bool, options ...Option) (*SubmitProposalResult, error)
SubmitProposal(title string, description string, proposalType msg.ProposalKind, initialDeposit int64, votingPeriod time.Duration, sync bool, options ...Option) (*SubmitProposalResult, error)
DepositProposal(proposalID int64, amount int64, sync bool, options ...Option) (*DepositProposalResult, error)
VoteProposal(proposalID int64, option msg.VoteOption, sync bool, options ...Option) (*VoteProposalResult, error)

GetKeyManager() keys.KeyManager
}
Expand All @@ -45,25 +45,45 @@ func (c *client) GetKeyManager() keys.KeyManager {
return c.keyManager
}

func (c *client) broadcastMsg(m msg.Msg, sync bool, memo string, source int64) (*tx.TxCommitResult, error) {
type Option func(*tx.StdSignMsg) *tx.StdSignMsg

func WithSource(source int64) Option {
return func(txMsg *tx.StdSignMsg) *tx.StdSignMsg {
txMsg.Source = source
return txMsg
}
}

func WithMemo(memo string) Option {
return func(txMsg *tx.StdSignMsg) *tx.StdSignMsg {
txMsg.Memo = memo
return txMsg
}
}

func (c *client) broadcastMsg(m msg.Msg, sync bool, options ...Option) (*tx.TxCommitResult, error) {
fromAddr := c.keyManager.GetAddr()
acc, err := c.queryClient.GetAccount(fromAddr.String())
if err != nil {
return nil, err
}
sequence := acc.Sequence
// prepare message to sign
signMsg := tx.StdSignMsg{
signMsg := &tx.StdSignMsg{
ChainID: c.chainId,
AccountNumber: acc.Number,
Sequence: sequence,
Memo: memo,
Memo: "",
Msgs: []msg.Msg{m},
Source: source,
Source: tx.Source,
}

for _, op := range options {
signMsg = op(signMsg)
}

// Hex encoded signed transaction, ready to be posted to BncChain API
hexTx, err := c.keyManager.Sign(signMsg)
hexTx, err := c.keyManager.Sign(*signMsg)
if err != nil {
return nil, err
}
Expand Down
Loading

0 comments on commit 3415adc

Please sign in to comment.