diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..de04bf9e --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018-2019 Binance + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/ReadMe.md b/ReadMe.md index 783014e3..d7522b07 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -1,8 +1,14 @@ # BNC Chain Go SDK -## Description -Bnc-Go-SDK provides a thin wrapper around the BNC Chain API for readonly endpoints, in addition to creating and submitting different transactions. +The Binance Chain GO SDK provides a thin wrapper around the BNC Chain API for readonly endpoints, in addition to creating and submitting different transactions. +It includes the following core components: + +* **client** - implementations of Binance Chain transaction types and query, such as for transfers and trading. +* **common** - core cryptographic functions, uuid functions and other useful functions. +* **e2e** - end-to-end test package for go-sdk developer. For common users, it is also a good reference to use go-sdk. +* **keys** - implement `KeyManage` to manage private key and accounts. +* **types** - core type of Binance Chain, such as `coin`, `account`, `tx` and `msg`. ## Install @@ -22,7 +28,7 @@ Use go get to install sdk into your `GOPATH`: go get github.com/binance-chain/go-sdk ``` -## Use dep +### Use dep Add dependency to your Gopkg.toml file. Example: ```bash [[override]] @@ -41,18 +47,25 @@ type KeyManager interface { Sign(tx.StdSignMsg) ([]byte, error) GetPrivKey() crypto.PrivKey GetAddr() txmsg.AccAddress + + ExportAsMnemonic() (string, error) + ExportAsPrivateKey() (string, error) + ExportAsKeyStore(password string) (*EncryptedKeyJSON, error) } ``` We provide three construct functions to generate Key Manger: ```go +NewKeyManager() (KeyManager, error) + NewMnemonicKeyManager(mnemonic string) (KeyManager, error) NewKeyStoreKeyManager(file string, auth string) (KeyManager, error) -NewPrivateKeyManager(wifKey string) (KeyManager, error) -``` +NewPrivateKeyManager(priKey string) (KeyManager, error) +``` +- NewKeyManager. You will get a new private key without provide anything, you can export and save this `KeyManager`. - NewMnemonicKeyManager. You should provide your mnemonic, usually is a string of 24 words. - NewKeyStoreKeyManager. You should provide a keybase json file and you password, you can download the key base json file when your create a wallet account. - NewPrivateKeyManager. You should provide a Hex encoded string of your private key. @@ -78,6 +91,27 @@ priv := "9579fff0cab07a4379e845a890105004ba4c8276f8ad9d22082b2acbf02d884b" keyManager, err := NewPrivateKeyManager(priv) ``` +We provide three export functions to persistent a Key Manger: + +```go +ExportAsMnemonic() (string, error) + +ExportAsPrivateKey() (string, error) + +ExportAsKeyStore(password string) (*EncryptedKeyJSON, error) +``` + +Examples: +```go +km, _ := NewKeyManager() +encryPlain1, _ := km.GetPrivKey().Sign([]byte("test plain")) +keyJSONV1, err := km.ExportAsKeyStore("testpassword") +bz, _ := json.Marshal(keyJSONV1) +ioutil.WriteFile("TestGenerateKeyStoreNoError.json", bz, 0660) +newkm, _ := NewKeyStoreKeyManager("TestGenerateKeyStoreNoError.json", "testpassword") +encryPlain2, _ := newkm.GetPrivKey().Sign([]byte("test plain")) +assert.True(t, bytes.Equal(encryPlain1, encryPlain2)) +``` ### Init Client @@ -105,425 +139,11 @@ TestNetwork ChainNetwork = iota If you want broadcast some transactions, like send coins, create orders or cancel orders, you should construct a key manager. -### Read Operations - -#### Get Account - -```GO -account, err := client.GetAccount("Your address") -``` -##### Parameters - -- Address - **string** , The address of query account. - -##### Returns - -- Account - The account object with the following structure: - - - Number **int64** , The account number of this user, which is a global unique number. - - Address **string** , the address of this account, which is hash of public key. - - Balances **[]Coin** , the balances of different kind of tokens. - - PublicKey **[]uint8** , the public key of this user. - - Sequence **int64** , the next expected transaction sequence, which is used to prevent replay accack. - -#### Get Markets -``` -markets, err := client.GetMarkets(api.NewMarketsQuery().WithLimit(1)) -``` - -##### Parameters - -- **MarketsQuery**, The query object. - - Offset **\*uint32** , optional, the offset of the first return symbol pair. - - Limit **\*uint32** , optional, the max length of return symbol pair. -##### Returns - -- **[]SymbolPair** - - **SymbolPair**, - - TradeAsset **string** - - QuoteAsset **string** - - Price **string**, the price of trade assert against quote assert. - - TickSize **string**, the minimum price movement of a trading instrument. - - LotSize **string**, refers to the quantity of an item ordered for delivery on a specific date or manufactured in a single production run. - -#### Get Depth -```go -depth, err := client.GetDepth(api.NewDepthQuery(tradeSymbol, nativeSymbol)) -``` -##### Parameters - -- **DepthQuery**, The query object. - - Symbol **string**, the combination of trade symbol and quote symbol. - - Limit **\*uint32**, optional, the max length of return depth. - -##### Returns -- **MarketDepth** - - Bids **[][]string**, each bid get two string element, the first one is the buy price, the second one is buy quantity. example: `[ [ "0.0024", "10" ] ]`. - - Asks **[][]string**, each ask get two string element, the first one is the sell price, the second one is sell quantity. example:` [ [ "0.0024", "10" ] ]`. - - Height **int64**, the bids and asks is based on a certain height of the chain. -} - -#### Get Kline -```go -kline, err := client.GetKlines(api.NewKlineQuery(tradeSymbol, nativeSymbol, "1h").WithLimit(1)) - -``` -##### Parameters -- **KlineQuery**, The query object. - - Symbol **string** ,the combination of trade symbol and quote symbol. - - Interval **string** interval like: (5m, 1h, 1d, 1w, etc.). - - Limit **\*uint32** , optional. - - StartTime **\*int64** , optional, which is a nano time. - - EndTime **\*int64** , optional, which is a nano time. - - -##### Returns -- **[]Kline** - - **Kline** - - Close **float64**, the close price . - - CloseTime **int64**, the close time. - - High **float64**, the highest price during the time. - - Low **float64**, the lowest price during the time. - - NumberOfTrades **int32**, the number of the trade transactions. - - Open **float64**, the open price. - - OpenTime **int64**, the open time. - - QuoteAssetVolume **float64**, the volume of the quote asset. - - Volume **float64**, the volume of trade asset. - -#### Get Ticker 24h - -```go -ticker24h, err := client.GetTicker24h(api.NewTicker24hQuery().WithSymbol(tradeSymbol, nativeSymbol)) -``` -##### Parameters -- **Ticker24hQuery**, the query object. - - Symbol **string**, the combination of trade symbol and quote symbol. - -##### Returns -- **[]Ticker24h** - - **Ticker24h** - - Symbol **string** - - AskPrice **string** , in decimal form, e.g. 1.00000000 - - AskQuantity **string** in decimal form, e.g. 1.00000000 - - BidPrice **string** in decimal form, e.g. 1.00000000 - - BidQuantity **string** in decimal form, e.g. 1.00000000 - - CloseTime **int64** - - Count **int64** - - FirstID **string** - - HighPrice **string** in decimal form, e.g. 1.00000000 - - LastID **string** - - LastPrice **string** in decimal form, e.g. 1.00000000 - - LastQuantity **string** in decimal form, e.g. 1.00000000 - - LowPrice **string** in decimal form, e.g. 1.00000000 - - OpenPrice **string** in decimal form, e.g. 1.00000000 - - OpenTime **int64** - - PrevClosePrice **string** in decimal form, e.g. 1.00000000 - - PriceChange **string** in decimal form, e.g. 1.00000000 - - PriceChangePercent **string** - - QuoteVolume **string** ,in decimal form, e.g. 1.00000000 - - Volume **string** ,i n decimal form, e.g. 1.00000000 - - WeightedAvgPrice **string** - -#### Get Tokens - -```go -tokens, err := client.GetTokens() -``` -##### Parameters -- No parameters - -##### Returns -- **[]Token** - - **Token** - - Name **string**, the name of the token, which end with three random alphabets. - - TotalSupply **string**, the total supply of this token. - - Owner **string**, who issue this token, which is an address of an account. - - OriginalSymbol **string**, the original symbol, which do not end with three random alphabet. -} - -#### Get Trades -```go -trades, err := client.GetTrades(api.NewTradesQuery(testAccount1.String()).WithSymbol(tradeSymbol, nativeSymbol)) -``` -##### Parameters -- **TradesQuery**, the query object. - - SenderAddress **string**, the address of the trade sender. - - Symbol **string**, the symbol of the trade, combination of trade symbol and quote symbol. - - Offset **\*uint32**, optional. - - Limit **\*uint32**, optional. - - Start **\*int64**, optional. - - End **\*int64**, optional. - - Side **string**, the side of trades, options is ["BUY","SELl""]. -##### Returns -- **Trades** - - Trade **[]Trade** - - BuyerOrderID **string**, the order id of the buyer, which is combination of address and sequence. - - BuyFee **string**, the buy fee charged. - - BuyerId **string**, the buyer id. - - Price **string**, the trade price. - - Quantity **string**, the quantity of the trade. - - SellFee **string**, the sell fee charged. - - SellerId **string**, the seller id. - - SellerOrderID **string**, the order id of the buyer, which is combination of address and sequence. - - Symbol **string**, - - Time **int64**, when the trade happened. - - TradeID **string** - - BlockHeight **int64**, in what height of the chain the trade happened. - - BaseAsset **string** - - QuoteAsset **string** - - Total **int**, the total num of trades. - - - -#### Get Time -```go -time, err := client.GetTime() - -``` -##### Parameters -No parameters. - -##### Returns -- **Time** - - ApTime **string**, the time of access point. - - BlockTime **string**, the time of the block chain. - - -#### Get Order -```go -order, err := client.GetOrder("Your Order Id") -``` -##### Parameters -- OrderId **string**, which is combination of account address and sequence. - -##### Returns -- **Order** - - ID **string**, the order id. - - Owner **string**, the account address who set the order. - - Symbol **string**, the combination of trade symbol and quote symbol. - - Price **string**, the sell price or buy price. - - Quantity **string**, the quantity of this order. - - CumulateQuantity **string**, the total executed quantity. - - Fee **string**, the fee charged. - - Side **int**, 1 for buy and 2 for sell - - Status **string**, options is [ ACK, PARTIALLY_FILLED, IOC_NO_FILL, FULLY_FILLED, CANCELED, EXPIRED, FAIL_BLOCKING, FAIL_MATCH, UNKNOWN ] - - TimeInForce **int**, 1 for Good Till Expire(GTE) order and 3 for Immediate Or Cancel (IOC) - - Type **int**, only 2 is available for now, meaning limit order - - TradeId **string** - - LastExecutedPrice **string**, the price of last executed. - - LastExecutedQuantity **string**, the quantity of last execution. - - TransactionHash **string** - - TransactionTime **string** - - -#### Get Open Orders -```go -openOrders, err := client.GetOpenOrders(api.NewOpenOrdersQuery(testAccount1.String())) - -``` -##### Parameters -- **OpenOrdersQuery** - - SenderAddress **string**,the combination of trade symbol and quote symbol. - - Symbol **string** - - Offset **\*uint32**, optional. - - Limit **\*uint32** , optional. -} -##### Returns -- **OpenOrders** - - Order **[]Orde** - - Total **string** - -#### Get Closed Orders - -```go -closedOrders, err := client.GetClosedOrders(api.NewClosedOrdersQuery(testAccount1.String()).WithSymbol(tradeSymbol, nativeSymbol)) -``` -##### Parameters -- **ClosedOrdersQuery** - - SenderAddress **string**,the combination of trade symbol and quote symbol. - - Symbol **string** - - Offset **\*uint32**, optional. - - Limit **\*uint32** , optional. -} -##### Returns -- **OpenOrders** - - Order **[]Orde** - - Total **string** - -#### Get Tx -```go -tx, err := client.GetTx(openOrders.Order[0].TransactionHash) - -``` -##### Parameters -- TxHash **string**, the hash of the transaction. - -##### Returns -- **TxResult** - - Hash **string** - - Log **string**, log info if the transaction failed. - - Data **string**, the return result of different kind of transactions. - - Code **int32**, the result code of this transaction. Zero represent ok result. - -#### Notice - -For read option, each api will need a Query parameter. Each Query parameter we provide a construct function: `NewXXXQuery`. -We recommend you to use this construct function when you new a Query parameter since the construction only need required parameters, -and for the optional parameters, you can use `WithXXX` to add it. +### Example -### Create & Post Transaction - -There is one most important point you should notice that we use int64 to represent a decimal. -The decimal length is fix 8, which means: -`100000000` is equal to `1` -`150000000` is equal to `1.5` -`1050000000` is equal to `10.5` - -For a common transaction, the response is: - -- **TxCommitResult** - - Ok **bool**, if the transaction accepted by chain. - - Log **string**, the error message of the transaction. - - Hash **string** - - Code **int32**, the result code. Zero represent fine. - - Data **string**, different kind of transaction return different data message. - -#### Create Order +Create a `buy` order: ```go createOrderResult, err := client.CreateOrder(tradeSymbol, nativeSymbol, txmsg.OrderSide.BUY, 100000000, 100000000, true) ``` -##### Parameters -- baseAssetSymbol **string** -- quoteAssetSymbol **string**, -- op **int8**, options is [1,2], 1 means "BUY", 2 means "SELL". -- price **int64** -- quantity **int64** -- sync **bool**, whether wait chain check this transaction. If true, in most case you will get `Data` field of `TxCommitResult`, -otherwise, `Data` field of `TxCommitResult` will be empty. - -##### Return -- **CreateOrderResult** - - **TxCommitResult** - - OrderId **string**, the order id of this order. - - -#### Cancel Order -```go -cancelOrderResult, err := client.CancelOrder(tradeSymbol, nativeSymbol, createOrderResult.OrderId, createOrderResult.OrderId, true) -``` -##### Parameters -- baseAssetSymbol **string** -- quoteAssetSymbol **string** -- id **string**, the order id. -- refId **string**, the order id will be fine. -- sync **bool**, whether wait chain check this transaction. -##### Return -- **CancelOrderResult** - - **TxCommitResult** - - -#### Send token -```go -send, err := client.SendToken(testAccount2, nativeSymbol, 10000000000, true) -``` -##### Parameters -- dest **txmsg.AccAddress**, the account address of user you want to send to. -- symbol **string**, the combination of trade symbol and quote symbol. -- quantity **int64** -- sync **bool**, whether wait chain check this transaction. - -##### Return -- **SendTokenResult** - - **TxCommitResult** - -#### Freeze token -```go -freeze, err := client.FreezeToken(nativeSymbol, 100000000, true) -``` -##### Parameters -- symbol **string**, which kind of token you want to freeze. -- amount **int64** -- sync **bool**, whether wait chain check this transaction. - -##### Return -- **FreezeTokenResult** - - **TxCommitResult** - - -#### UnFreeze token -```go -unFreeze, err := client.UnfreezeToken(nativeSymbol, 100000000, true) -``` -##### Parameters -- symbol **string**, which kind of token you want to unfreeze. -- amount **int64** -- sync **bool**, whether wait chain check this transaction. - -##### Return -- **UnfreezeTokenResult** - - **TxCommitResult** - -#### Issue token -```go -issue, err := client.IssueToken("SDK-Token", "sdk", 10000000000000000, true, false) -``` -##### Parameters -- name **string**, the name of your token. -- symbol **string**, a symbol of your token. -- supply **int64** -- sync **bool**, whether wait chain check this transaction. -- mintable **bool**, whether you want mint token in the future. - -##### Return -- **IssueTokenResult** - - **TxCommitResult** - - Symbol **string**, the actual symbol of you token.(which will end with three random alphabets). - - -#### Submit ListTrade Proposal -```go -listTradingProposal, err := client.SubmitListPairProposal("New trading pair", txmsg.ListTradingPairParams{issue.Symbol, nativeSymbol, 1000000000, "my trade", time2.Now().Add(1 * time2.Hour)}, 200000000000, true) -``` -##### Parameters -- title **string**, -- param **txmsg.ListTradingPairParams** - - BaseAssetSymbol **string** - - QuoteAssetSymbol **string** - - InitPrice **int64** - - Description **string** - - ExpireTime **time.Time**, the expire time you active this list trading pair. -- initialDeposit **int64**, the amount of BNB you want deposit for this proposal. -- sync **bool**, whether wait chain check this transaction. -##### Return -- **SubmitProposalResult** - - *TxCommitResult* - - ProposalId *int64*, the proposal id generated by chain. Useful when you vote or deposit for specified proposal. - -#### Vote Proposal -```go -vote, err := client.VoteProposal(listTradingProposal.ProposalId, txmsg.OptionYes, true) -``` -##### Parameters -- proposalID **int64**, the id of the proposal you want to vote. -- option **txmsg.VoteOption**, vote options: [OptionYes, OptionAbstain, OptionNo,O ptionNoWithVeto] -- sync bool, whether wait chain check this transaction. - -##### Return -- **VoteProposalResult** - - **TxCommitResult** - -#### List Trade pair -```go -lp,err:=client.ListPair(listTradingProposal.ProposalId, issue.Symbol, nativeSymbol, 1000000000, true) -``` -##### Parameters -- proposalId **int64**, the proposal id that propose by you or others that want to create a new list trading pair. Make sure the proposal is passed. -- baseAssetSymbol **string** -- quoteAssetSymbol **string** -- initPrice **int64** -- sync **bool**, whether wait chain check this transaction. - -##### Return -- **ListPairResult** - - **TxCommitResult** \ No newline at end of file +For more API usage documentation, please check the [wiki](https://github.com/binance-chain/go-sdk/wiki).. \ No newline at end of file diff --git a/e2e/e2e_test.go b/e2e/e2e_test.go index 0ee92451..f07b4dbd 100644 --- a/e2e/e2e_test.go +++ b/e2e/e2e_test.go @@ -2,8 +2,6 @@ package e2e import ( "fmt" - "github.com/binance-chain/go-sdk/common/crypto" - "github.com/binance-chain/go-sdk/common/crypto/secp256k1" "testing" time2 "time" @@ -25,7 +23,8 @@ func TestAllProcess(t *testing.T) { keyManager, err := keys.NewMnemonicKeyManager(mnemonic) assert.NoError(t, err) testAccount1 := keyManager.GetAddr() - _, testAccount2 := PrivAndAddr() + testKeyManager2, _ := keys.NewKeyManager() + testAccount2 := testKeyManager2.GetAddr() //----- Init sdk ------------- client, err := sdk.NewDexClient("https://testnet-dex.binance.org", types.TestNetwork, keyManager) @@ -188,10 +187,4 @@ func TestAllProcess(t *testing.T) { //assert.NoError(t, err) //fmt.Printf("New markets: %v \n ", markets) -} - -func PrivAndAddr() (crypto.PrivKey, types.AccAddress) { - priv := secp256k1.GenPrivKey() - addr := types.AccAddress(priv.PubKey().Address()) - return priv, addr -} +} \ No newline at end of file diff --git a/keys/keys.go b/keys/keys.go index 44b21a35..97c5f545 100644 --- a/keys/keys.go +++ b/keys/keys.go @@ -24,12 +24,6 @@ const ( defaultBIP39Passphrase = "" ) -const ( - Save = iota - DomainGroup - DomainOrg -) - type KeyManager interface { Sign(tx.StdSignMsg) ([]byte, error) GetPrivKey() crypto.PrivKey @@ -37,7 +31,7 @@ type KeyManager interface { ExportAsMnemonic() (string, error) ExportAsPrivateKey() (string, error) - ExportAsKeyStore(password string) (*EncryptedKeyJSONV1, error) + ExportAsKeyStore(password string) (*EncryptedKeyJSON, error) } func NewMnemonicKeyManager(mnemonic string) (KeyManager, error) { @@ -79,11 +73,11 @@ func (m *keyManager) ExportAsPrivateKey() (string, error) { return hex.EncodeToString(secpPrivateKey[:]), nil } -func (m *keyManager) ExportAsKeyStore(password string) (*EncryptedKeyJSONV1, error) { +func (m *keyManager) ExportAsKeyStore(password string) (*EncryptedKeyJSON, error) { return generateKeyStore(m.GetPrivKey(), password) } -func NewRawKeyManager() (KeyManager, error) { +func NewKeyManager() (KeyManager, error) { entropy, err := bip39.NewEntropy(256) if err != nil { return nil, err @@ -129,12 +123,12 @@ func (m *keyManager) recoveryFromKeyStore(keystoreFile string, auth string) erro if err != nil { return err } - var encryptedKey EncryptedKeyJSONV1 + var encryptedKey EncryptedKeyJSON err = json.Unmarshal(keyJson, &encryptedKey) if err != nil { return err } - keyBytes, err := decryptKeyV1(&encryptedKey, auth) + keyBytes, err := decryptKey(&encryptedKey, auth) if err != nil { return err } @@ -206,7 +200,7 @@ func (m *keyManager) makeSignature(msg tx.StdSignMsg) (sig tx.StdSignature, err }, nil } -func generateKeyStore(privateKey crypto.PrivKey, password string) (*EncryptedKeyJSONV1, error) { +func generateKeyStore(privateKey crypto.PrivKey, password string) (*EncryptedKeyJSON, error) { addr := types.AccAddress(privateKey.PubKey().Address()) salt, err := common.GenerateRandomBytes(32) if err != nil { @@ -251,7 +245,7 @@ func generateKeyStore(privateKey crypto.PrivKey, password string) (*EncryptedKey KDFParams: scryptParamsJSON, MAC: hex.EncodeToString(mac), } - return &EncryptedKeyJSONV1{ + return &EncryptedKeyJSON{ Address: addr.String(), Crypto: cryptoStruct, Id: id.String(), diff --git a/keys/keys_test.go b/keys/keys_test.go index c43eef12..59a26158 100644 --- a/keys/keys_test.go +++ b/keys/keys_test.go @@ -175,7 +175,7 @@ func TestSignTxNoError(t *testing.T) { func TestExportAsKeyStoreNoError(t *testing.T) { defer os.Remove("TestGenerateKeyStoreNoError.json") - km, err := NewRawKeyManager() + km, err := NewKeyManager() assert.NoError(t, err) encryPlain1, err := km.GetPrivKey().Sign([]byte("test plain")) assert.NoError(t, err) @@ -193,7 +193,7 @@ func TestExportAsKeyStoreNoError(t *testing.T) { } func TestExportAsMnemonicNoError(t *testing.T) { - km, err := NewRawKeyManager() + km, err := NewKeyManager() assert.NoError(t, err) encryPlain1, err := km.GetPrivKey().Sign([]byte("test plain")) assert.NoError(t, err) @@ -209,7 +209,7 @@ func TestExportAsMnemonicNoError(t *testing.T) { } func TestExportAsPrivateKeyNoError(t *testing.T) { - km, err := NewRawKeyManager() + km, err := NewKeyManager() assert.NoError(t, err) encryPlain1, err := km.GetPrivKey().Sign([]byte("test plain")) assert.NoError(t, err) diff --git a/keys/keystore.go b/keys/keystore.go index 345a0916..d225f5c7 100644 --- a/keys/keystore.go +++ b/keys/keystore.go @@ -23,7 +23,7 @@ type PlainKeyJSON struct { Version int `json:"version"` } -type EncryptedKeyJSONV1 struct { +type EncryptedKeyJSON struct { Address string `json:"address"` Crypto CryptoJSON `json:"crypto"` Id string `json:"id"` @@ -42,7 +42,7 @@ type cipherparamsJSON struct { IV string `json:"iv"` } -func decryptKeyV1(keyProtected *EncryptedKeyJSONV1, auth string) ([]byte, error) { +func decryptKey(keyProtected *EncryptedKeyJSON, auth string) ([]byte, error) { mac, err := hex.DecodeString(keyProtected.Crypto.MAC) if err != nil { return nil, err