├── .gitignore ├── Dockerfile ├── Dockerfile-arm32v7 ├── LICENSE ├── README.md ├── cli ├── bot.go └── cmdui.go ├── client ├── bidderClient.go ├── ddexApiInterface.go └── ddexClient.go ├── docs ├── deposit.png └── screen_snapshot.jpg ├── go.mod ├── go.sum ├── main.go ├── utils ├── const.go ├── converter.go ├── crypto.go ├── crypto_test.go ├── error.go ├── general.go ├── http.go └── sqliteClient.go └── web3 ├── ethrpc.go ├── interface.go ├── options.go ├── types.go └── web3.go /.gitignore: -------------------------------------------------------------------------------- 1 | bin 2 | .idea 3 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.12 2 | 3 | WORKDIR /app 4 | COPY . /app 5 | RUN go mod download 6 | RUN go build -ldflags "-w -linkmode external -extldflags -static" -v -o main 7 | 8 | FROM alpine 9 | RUN apk --no-cache add ca-certificates 10 | COPY --from=0 /app/main /bin/main -------------------------------------------------------------------------------- /Dockerfile-arm32v7: -------------------------------------------------------------------------------- 1 | # compile env 2 | FROM golang:1.12 3 | 4 | ARG GOARM 5 | 6 | ENV CGO_ENABLED 1 7 | ENV GOOS linux 8 | ENV GOARCH arm 9 | ENV CC arm-linux-gnueabihf-gcc 10 | ENV CXX arm-linux-gnueabihf-g++ 11 | 12 | WORKDIR /app 13 | COPY . /app 14 | RUN go mod download 15 | RUN apt update && apt install -y g++-arm-linux-gnueabihf 16 | RUN go build -o main 17 | 18 | FROM arm32v7/alpine 19 | RUN apk --no-cache add ca-certificates 20 | COPY --from=0 /app/main /bin/main 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DDEX Liquidation Bot 2 | 3 | Participate in the liquidation on DDEX to earn money 💰💰💰 4 | 5 | ## Getting Started 6 | 7 | Margin positions will be liquidated if the collateral rate too low. 8 | When a liquidation occurs, the borrowers' assets are sold off in a form of a dutch auction to repay the loan. 9 | This bot help you bid the auction when profitable. 10 | 11 | The bot uses an arbitrage strategy: Sell collateral on DDEX immediately after receive it from an auction. For example: 12 | 13 | - An auction sell *10ETH* at price *160USDT* 14 | - The bot buy *10ETH* 15 | - The bot sell *10ETH* on ddex at price *170USDT* 16 | - Earn *10\*170-10\*160=100USDT* 17 | 18 | ### Prerequisites 19 | 20 | You need to prepare some asset(e.g. ETH, USDT, DAI) in your DDEX spot trading balance. 21 | 22 | ![](docs/deposit.png) 23 | 24 | In order to run this container you'll need docker installed. 25 | 26 | * [Windows](https://docs.docker.com/windows/started) 27 | * [OS X](https://docs.docker.com/mac/started/) 28 | * [Linux](https://docs.docker.com/linux/started/) 29 | 30 | ### Run Container 31 | 32 | Replace `/your/file/path` with your local directory. 33 | 34 | ```shell 35 | docker run -it --rm -v /your/file/path:/workingDir --name=auctionBidder hydroprotocolio/liquidation_bot:latest /bin/main 36 | ``` 37 | 38 | If you want to test on ropsten 39 | 40 | ```shell 41 | docker run -it --rm -v /your/file/path:/workingDir --name=auctionBidder --env NETWORK=ropsten hydroprotocolio/liquidation_bot:latest /bin/main 42 | ``` 43 | 44 | ### Screen Snapshot 45 | 46 | The bot try to fill every current auction when new block listened. It also records your profit and loss and show free trading balance of the address you use. 47 | 48 | ![](docs/screen_snapshot.jpg) 49 | 50 | #### Volumes 51 | 52 | * `/your/file/path` - Where liquidation history, config and logs stored 53 | 54 | ##### Useful File Locations 55 | 56 | * `/your/file/path/auctionBidderSqlite` - Your bid history is recorded in sqlite file 57 | 58 | * `/your/file/path/config.json` - Bot parameters 59 | 60 | * `/your/file/path/log.%Y%m%D` - Logs 61 | 62 | #### Parameters 63 | 64 | The bot will ask for the following parameters for the first run: 65 | 66 | * `PRIVATE_KEY` - Private key of the account to join liquidation 67 | 68 | * `ETHEREUM_NODE_URL` - Ethereum node url. Get a free node at [infura](https://infura.io). 69 | 70 | * `MARKETS` - Which markets' auction I am interested in. Separated by commas. `e.g. ETH-USDT,ETH-DAI` 71 | 72 | * `MIN_AMOUNT_VALUE_USD` - I don't want to participate the auction unless its USD value greater than *X* `e.g. 100` 73 | 74 | * `PROFIT_MARGIN` - I don't want to bid unless the profit margin greater than *X* `e.g. 0.01` (0.01 means 1%) 75 | 76 | * `GAS_PRICE_LEVEL` - `e.g. fast, super-fast or flash-boy` will use *FAST* gas price from [ethgasstation](https://ethgasstation.info/) plus `0Gwei`, `10Gwei` and `25Gwei` respectively to send transactions 77 | 78 | * `MAX_SLIPPAGE` - Don't arbitrage if the slippage greater than *X* `e.g. 0.05` (0.05 means 5%) 79 | 80 | Edit `/your/file/path/config.json` and restart bot to adjust parameters. 81 | 82 | ## Contributing 83 | 84 | 1. Fork it () 85 | 2. Create your feature branch (`git checkout -b feature/fooBar`) 86 | 3. Commit your changes (`git commit -am 'Add some fooBar'`) 87 | 4. Push to the branch (`git push origin feature/fooBar`) 88 | 5. Create a new Pull Request 89 | 90 | ## License 91 | 92 | This project is licensed under the Apache-2.0 License - see the [LICENSE](LICENSE) file for details 93 | -------------------------------------------------------------------------------- /cli/bot.go: -------------------------------------------------------------------------------- 1 | package cli 2 | 3 | import ( 4 | "auctionBidder/client" 5 | "auctionBidder/utils" 6 | "auctionBidder/web3" 7 | "github.com/pkg/errors" 8 | "github.com/shopspring/decimal" 9 | "github.com/sirupsen/logrus" 10 | "strings" 11 | ) 12 | 13 | type BidderBot struct { 14 | BidderClient *client.BidderClient 15 | DdexClient *client.DdexClient 16 | BlockChannel chan int64 17 | MaxSlippage decimal.Decimal 18 | MinOrderValueUSD decimal.Decimal 19 | GasPriceTipsGwei int // send tx using gas price "fast" from ether gas station plus tips 20 | Markets string 21 | ProfitMargin decimal.Decimal 22 | } 23 | 24 | func (b *BidderBot) Run() { 25 | b.updatePnlView() 26 | for true { 27 | UpdateInventoryView(b.DdexClient) 28 | blockNum := <-b.BlockChannel 29 | logrus.Infof("new block %d", blockNum) 30 | allAuctions, err := b.BidderClient.GetAllAuctions() 31 | if err != nil { 32 | continue 33 | } 34 | UpdateAuctionView(allAuctions) 35 | for _, auction := range allAuctions { 36 | err := b.tryFillAuction(auction) 37 | if err != nil { 38 | logrus.Errorf("try fill auction #%d failed: %s", auction.ID, err.Error()) 39 | } 40 | } 41 | } 42 | } 43 | 44 | func (b *BidderBot) tryFillAuction(auction *client.Auction) (err error) { 45 | // check if the market is under monitor 46 | if !strings.Contains(b.Markets, auction.TradingPair) { 47 | logrus.Debugf("auction trading pair %s is not in monitor list %s", auction.TradingPair, b.Markets) 48 | return nil 49 | } 50 | logrus.Debugf("try fill auction %d", auction.ID) 51 | 52 | // truncate order size by free balance 53 | inventory, err := b.DdexClient.GetInventory() 54 | if err != nil { 55 | return 56 | } 57 | freeBalance := inventory[auction.DebtSymbol].Free 58 | if freeBalance.IsZero() { 59 | err = errors.Errorf(`%s balance is zero`, auction.DebtSymbol) 60 | return 61 | } 62 | 63 | var debt = auction.AvailableDebt 64 | var collateral = auction.AvailableCollateral 65 | if freeBalance.LessThan(debt) { 66 | logrus.Warnf(`Balance not enough, you could repay %s %s debt`, freeBalance.String(), auction.DebtSymbol) 67 | debt = freeBalance 68 | collateral = debt.Div(auction.AvailableDebt).Mul(auction.AvailableCollateral) 69 | } 70 | 71 | // amount must greater than min usd size 72 | collateralPrice, err := b.DdexClient.GetAssetUSDPrice(auction.CollateralSymbol) 73 | if err != nil { 74 | return 75 | } 76 | collateralValue := collateral.Mul(collateralPrice) 77 | if collateral.Mul(collateralPrice).LessThanOrEqual(b.MinOrderValueUSD) { 78 | err = errors.Errorf("collateral usd value %s$ too small", collateralValue.String()) 79 | return 80 | } 81 | 82 | // check auction profitable 83 | receive, err := b.DdexClient.QuerySellAssetReceiveAmount(auction.TradingPair, auction.CollateralSymbol, collateral) 84 | if err != nil { 85 | return 86 | } 87 | 88 | if receive.LessThanOrEqual(debt.Add(debt.Mul(b.ProfitMargin))) { 89 | logrus.Warnf("auction price not profitable, wait next block") 90 | return 91 | } else { 92 | logrus.Infof("auction price profitable!") 93 | gasPriceInGwei := web3.GetGasPriceGwei() + int64(b.GasPriceTipsGwei) 94 | logrus.Debugf("use gas price %d gwei", gasPriceInGwei) 95 | txHash, err := b.BidderClient.FillAuction(auction, debt, gasPriceInGwei) 96 | if err != nil { 97 | return err 98 | } 99 | logrus.Infof("send tx %s", txHash) 100 | 101 | bidderRepay, collateralForBidder, gasUsed, err := b.BidderClient.GetFillAuctionRes(txHash, auction) 102 | gasCost := gasUsed.Mul(decimal.New(gasPriceInGwei, -9)) 103 | logrus.Infof( 104 | "fill auction: repayDebt %s%s receiveCollateral %s%s gasCost %sETH", 105 | bidderRepay.String(), 106 | auction.DebtSymbol, 107 | collateralForBidder.String(), 108 | auction.CollateralSymbol, 109 | gasCost.String()) 110 | 111 | if collateralForBidder.IsZero() { 112 | utils.InsertFailedBid(txHash, int(auction.ID), auction.DebtSymbol, auction.CollateralSymbol, gasCost.String()) 113 | b.updatePnlView() 114 | err = errors.New("bid transaction failed") 115 | return err 116 | } 117 | // todo: if hedge failed anyway, give a red alert 118 | ddexOrderId, ddexSellCollateral, ddexReceiveDebt, err := b.DdexClient.PromisedMarketSellAsset(auction.TradingPair, auction.CollateralSymbol, collateralForBidder, b.MaxSlippage) 119 | if err != nil { 120 | return err 121 | } 122 | logrus.Infof("hedge at ddex market: sell %s%s receive %s%s", 123 | ddexSellCollateral.String(), 124 | auction.CollateralSymbol, 125 | ddexReceiveDebt.String(), 126 | auction.DebtSymbol, 127 | ) 128 | 129 | utils.InsertAuctionRes( 130 | txHash, 131 | int(auction.ID), 132 | auction.DebtSymbol, 133 | auction.CollateralSymbol, 134 | bidderRepay.String(), 135 | collateralForBidder.String(), 136 | ddexOrderId, 137 | ddexSellCollateral.String(), 138 | ddexReceiveDebt.String(), 139 | gasCost.String(), 140 | ) 141 | b.updatePnlView() 142 | } 143 | 144 | return 145 | } 146 | 147 | func (b *BidderBot) updatePnlView() { 148 | position, err := utils.QueryPosition() 149 | if err != nil { 150 | return 151 | } 152 | var price = map[string]decimal.Decimal{} 153 | for symbol, _ := range position { 154 | p, err := b.DdexClient.GetAssetUSDPrice(symbol) 155 | if err != nil { 156 | p = decimal.Zero 157 | } 158 | price[symbol] = p 159 | } 160 | UpdatePnlView(position, price) 161 | } 162 | -------------------------------------------------------------------------------- /cli/cmdui.go: -------------------------------------------------------------------------------- 1 | package cli 2 | 3 | import ( 4 | "auctionBidder/client" 5 | "auctionBidder/utils" 6 | "fmt" 7 | "github.com/fatih/color" 8 | "github.com/jroimartin/gocui" 9 | "github.com/lestrrat-go/file-rotatelogs" 10 | "github.com/shopspring/decimal" 11 | "github.com/sirupsen/logrus" 12 | "log" 13 | "os" 14 | "path" 15 | "sort" 16 | "strconv" 17 | "time" 18 | ) 19 | 20 | var DefaultGui *gocui.Gui 21 | var YellowStr = color.New(color.FgYellow).SprintFunc() 22 | var RedStr = color.New(color.FgRed).SprintFunc() 23 | var GreenStr = color.New(color.FgGreen).SprintFunc() 24 | var BlueStr = color.New(color.FgCyan).SprintFunc() 25 | 26 | var pnlStr = func(d decimal.Decimal, unit string) string { 27 | if d.IsPositive() { 28 | return color.New(color.FgGreen).Sprintf("%s%s", utils.SetPrecision(d, 5).String(), unit) 29 | } 30 | if d.IsNegative() { 31 | return color.New(color.FgRed).Sprintf("%s%s", utils.SetPrecision(d, 5).String(), unit) 32 | } 33 | return fmt.Sprintf("%s%s", d.String(), unit) 34 | } 35 | 36 | func StartGui() (err error) { 37 | DefaultGui, err = gocui.NewGui(gocui.OutputNormal) 38 | if err != nil { 39 | log.Panicln(err) 40 | } 41 | defer DefaultGui.Close() 42 | 43 | maxX, maxY := DefaultGui.Size() 44 | infoView, _ := DefaultGui.SetView("info", 0, maxY/3+1, maxX-1, maxY-1) 45 | auctionView, _ := DefaultGui.SetView("auction", 0, 0, maxX/2-1, maxY/3) 46 | pnlView, _ := DefaultGui.SetView("pnl", maxX/2, 0, maxX*3/4-1, maxY/3) 47 | inventoryView, _ := DefaultGui.SetView("inventory", maxX*3/4, 0, maxX-1, maxY/3) 48 | infoView.Title = "INFO" 49 | infoView.Autoscroll = true 50 | infoView.Wrap = true 51 | auctionView.Title = "CURRENT AUCTIONS" 52 | auctionView.Autoscroll = false 53 | auctionView.Wrap = true 54 | pnlView.Title = "PROFFIT & LOSS" 55 | pnlView.Autoscroll = false 56 | pnlView.Wrap = true 57 | inventoryView.Title = "FREE BALANCE" 58 | inventoryView.Autoscroll = false 59 | inventoryView.Wrap = true 60 | 61 | RegisterLogrusHooks() 62 | 63 | if err := DefaultGui.SetKeybinding("", gocui.KeyCtrlC, gocui.ModNone, quit); err != nil { 64 | DefaultGui.Close() 65 | logrus.Panic(err) 66 | } 67 | 68 | if err := DefaultGui.MainLoop(); err != nil && err != gocui.ErrQuit { 69 | logrus.Panic(err) 70 | } 71 | 72 | return 73 | } 74 | 75 | func quit(g *gocui.Gui, v *gocui.View) error { 76 | return gocui.ErrQuit 77 | } 78 | 79 | func UpdateAuctionView(auctions []*client.Auction) { 80 | v, err := DefaultGui.View("auction") 81 | if err != nil { 82 | logrus.Error(err) 83 | return 84 | } 85 | v.Clear() 86 | 87 | if len(auctions) == 0 { 88 | DefaultGui.Update(func(g *gocui.Gui) error { 89 | fmt.Fprintln(v, YellowStr("No Auctions")) 90 | return nil 91 | }) 92 | return 93 | } 94 | 95 | for _, auction := range auctions { 96 | fmt.Fprintln(v, fmt.Sprintf("%s: sell %s %s for %s with price %s", 97 | YellowStr("Auction #"+strconv.Itoa(int(auction.ID))), 98 | auction.AvailableCollateral.String(), 99 | auction.CollateralSymbol, 100 | auction.DebtSymbol, 101 | auction.Price.String(), 102 | )) 103 | } 104 | } 105 | 106 | func UpdatePnlView(position map[string]decimal.Decimal, price map[string]decimal.Decimal) { 107 | DefaultGui.Update(func(g *gocui.Gui) error { 108 | v, _ := g.View("pnl") 109 | v.Clear() 110 | totalValue := decimal.Zero 111 | for symbol, _ := range position { 112 | value := position[symbol].Mul(price[symbol]) 113 | totalValue = totalValue.Add(value) 114 | fmt.Fprintln(v, fmt.Sprintf("%s: %s (%s)", 115 | symbol, 116 | pnlStr(position[symbol], symbol), 117 | pnlStr(value, "$"))) 118 | } 119 | fmt.Fprintln(v, "total:"+pnlStr(totalValue, "$")) 120 | return nil 121 | }) 122 | } 123 | 124 | func UpdateInventoryView(ddexClient *client.DdexClient) { 125 | inventory, err := ddexClient.GetInventory() 126 | if err != nil { 127 | return 128 | } 129 | DefaultGui.Update(func(g *gocui.Gui) error { 130 | v, _ := g.View("inventory") 131 | v.Clear() 132 | fmt.Fprintln(v, fmt.Sprintf("Your address:%s", ddexClient.Address)) 133 | symbolList := []string{} 134 | for symbol, _ := range inventory { 135 | symbolList = append(symbolList, symbol) 136 | } 137 | sort.Strings(symbolList) 138 | for _, symbol := range symbolList { 139 | fmt.Fprintln(v, fmt.Sprintf("[%s] %s", symbol, inventory[symbol].Free.StringFixed(3))) 140 | } 141 | return nil 142 | }) 143 | } 144 | 145 | type viewHook struct{} 146 | 147 | func (hook *viewHook) Levels() []logrus.Level { 148 | return logrus.AllLevels 149 | } 150 | 151 | func (hook *viewHook) Fire(entry *logrus.Entry) error { 152 | DefaultGui.Update(func(g *gocui.Gui) error { 153 | v, _ := g.View("info") 154 | var prefix string 155 | 156 | if entry.Level == logrus.InfoLevel { 157 | prefix = GreenStr("[info]") 158 | } 159 | if entry.Level == logrus.DebugLevel { 160 | prefix = BlueStr("[debug]") 161 | } 162 | if entry.Level == logrus.ErrorLevel { 163 | prefix = RedStr("[error]") 164 | } 165 | if entry.Level == logrus.WarnLevel { 166 | prefix = YellowStr("[warn]") 167 | } 168 | 169 | fmt.Fprintln(v, fmt.Sprintf("%s %s %s", prefix, time.Now().Format("15:04:05"), entry.Message)) 170 | return nil 171 | }) 172 | return nil 173 | } 174 | 175 | func RegisterLogrusHooks() { 176 | logrus.AddHook(&viewHook{}) 177 | rl, err := rotatelogs.New(path.Join(os.Getenv("LOGPATH"), "log.%Y%m%d%H")) 178 | if err != nil { 179 | panic("log path not exist") 180 | } 181 | logrus.SetOutput(rl) 182 | logrus.SetFormatter(&logrus.TextFormatter{ 183 | DisableColors: true, 184 | FullTimestamp: true, 185 | }) 186 | logrus.SetLevel(logrus.DebugLevel) 187 | } 188 | -------------------------------------------------------------------------------- /client/bidderClient.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "auctionBidder/utils" 5 | "auctionBidder/web3" 6 | "fmt" 7 | "github.com/shopspring/decimal" 8 | "math/big" 9 | "os" 10 | "strings" 11 | "time" 12 | ) 13 | 14 | type Auction struct { 15 | ID int64 16 | DebtSymbol string 17 | CollateralSymbol string 18 | TradingPair string 19 | AvailableDebt decimal.Decimal 20 | AvailableCollateral decimal.Decimal 21 | Ratio decimal.Decimal 22 | Price decimal.Decimal 23 | Finished bool 24 | } 25 | 26 | type BidderClient struct { 27 | web3 *web3.Web3 28 | hydroContract *web3.Contract 29 | bidderPrivateKey string 30 | bidderAddress string 31 | assets map[string]*Asset // symbol -> asset 32 | markets map[string]*Market // trading pair -> market 33 | } 34 | 35 | func NewBidderClient(bidderPrivateKey string, assets map[string]*Asset, markets map[string]*Market) (client *BidderClient, err error) { 36 | ethereumNodeUrl := os.Getenv("ETHEREUM_NODE_URL") 37 | hydroContractAddress := os.Getenv("HYDRO_CONTRACT_ADDRESS") 38 | 39 | web3 := web3.NewWeb3(ethereumNodeUrl) 40 | bidderAddress, err := web3.AddPrivateKey(bidderPrivateKey) 41 | if err != nil { 42 | return 43 | } 44 | contract, err := web3.NewContract(utils.HydroAbi, hydroContractAddress) 45 | if err != nil { 46 | return 47 | } 48 | client = &BidderClient{ 49 | web3, 50 | contract, 51 | bidderPrivateKey, 52 | bidderAddress, 53 | assets, 54 | markets, 55 | } 56 | 57 | return 58 | } 59 | 60 | func (client *BidderClient) FillAuction( 61 | auction *Auction, 62 | repayDebt decimal.Decimal, 63 | gasPriceInGwei int64, 64 | ) (txHash string, err error) { 65 | nonce, err := client.web3.Rpc.EthGetTransactionCount(client.bidderAddress, "latest") 66 | if err != nil { 67 | return 68 | } 69 | sendTxParams := &web3.SendTxParams{ 70 | client.bidderAddress, 71 | big.NewInt(500000), 72 | big.NewInt(gasPriceInGwei * 1000000000), 73 | uint64(nonce), 74 | } 75 | 76 | rawRepayDebt := repayDebt.Mul(decimal.New(1, client.assets[auction.DebtSymbol].Decimal)).Floor() 77 | 78 | return client.hydroContract.Send(sendTxParams, big.NewInt(0), "fillAuctionWithAmount", uint32(auction.ID), utils.DecimalToBigInt(rawRepayDebt)) 79 | } 80 | 81 | func (client *BidderClient) GetFillAuctionRes(txHash string, auction *Auction) ( 82 | bidderRepay decimal.Decimal, 83 | collateralForBidder decimal.Decimal, 84 | gasUsed decimal.Decimal, 85 | err error) { 86 | var receipt *web3.TransactionReceipt 87 | for true { 88 | receipt, err = client.web3.Rpc.EthGetTransactionReceipt(txHash) 89 | if err != nil || receipt.BlockNumber == 0 { 90 | time.Sleep(time.Second) 91 | } else { 92 | break 93 | } 94 | } 95 | 96 | gasUsed = decimal.New(int64(receipt.GasUsed), 0) 97 | if receipt.Status == "0x0" { 98 | bidderRepay = decimal.Zero 99 | collateralForBidder = decimal.Zero 100 | return 101 | } 102 | for _, log := range receipt.Logs { 103 | if log.Topics[0] == "0x42a553656a0da7239e70a4a3c864c1ac7d46d7968bfe2e1fb14f42dbb67135e8" { 104 | bidderRepay = utils.HexString2Decimal(log.Data[130:194], -1*client.assets[auction.DebtSymbol].Decimal) 105 | collateralForBidder = utils.HexString2Decimal(log.Data[194:258], -1*client.assets[auction.CollateralSymbol].Decimal) 106 | return 107 | } 108 | } 109 | 110 | return 111 | } 112 | 113 | func (client *BidderClient) GetCurrentAuctionIDs() (auctionIDs []int64, err error) { 114 | resp, err := client.hydroContract.Call("getCurrentAuctions") 115 | if err != nil { 116 | return nil, err 117 | } 118 | auctionNum := (len(resp)-2)/64 - 2 119 | for i := 0; i < auctionNum; i++ { 120 | auctionID, _ := utils.HexString2Int(resp[130+64*i : 194+64*i]) 121 | auctionIDs = append(auctionIDs, int64(auctionID)) 122 | } 123 | 124 | return 125 | } 126 | 127 | func (client *BidderClient) GetSingleAuction(auctionID int64) (auction *Auction, err error) { 128 | resp, err := client.hydroContract.Call("getAuctionDetails", uint32(auctionID)) 129 | if err != nil { 130 | return 131 | } 132 | 133 | if len(resp) != 578 { 134 | err = utils.AuctionNotExist 135 | return 136 | } 137 | 138 | debtAddress := "0x" + strings.ToLower(resp[2+64*2+24:2+64*3]) 139 | collateralAddress := "0x" + strings.ToLower(resp[2+64*3+24:2+64*4]) 140 | 141 | var debtSymbol string 142 | var collateralSymbol string 143 | 144 | for symbol, asset := range client.assets { 145 | if utils.IsAddressEqual(asset.Address, debtAddress) { 146 | debtSymbol = symbol 147 | } 148 | if utils.IsAddressEqual(asset.Address, collateralAddress) { 149 | collateralSymbol = symbol 150 | } 151 | } 152 | 153 | availableCollateral := utils.HexString2Decimal(resp[2+64*5:2+64*6], -1*client.assets[collateralSymbol].Decimal) 154 | availableDetb := utils.HexString2Decimal(resp[2+64*4:2+64*5], -1*client.assets[debtSymbol].Decimal) 155 | availableDetb = availableDetb.Mul(decimal.New(1, 0).Add(decimal.New(1, -5))) // the debt is growing while auction ongoing 156 | 157 | ratio := utils.HexString2Decimal(resp[2+64*6:2+64*7], -18) 158 | finished := utils.HexString2Decimal(resp[2+64*8:2+64*9], 0).IsPositive() 159 | 160 | if ratio.LessThan(decimal.New(1, 0)) { 161 | availableCollateral = availableCollateral.Mul(ratio) 162 | } else { 163 | availableDetb = availableDetb.Div(ratio) 164 | } 165 | 166 | var price decimal.Decimal 167 | if availableCollateral.IsPositive() { 168 | price = availableDetb.Div(availableCollateral) 169 | } else { 170 | price = decimal.Zero 171 | } 172 | 173 | var tradingPair string 174 | if _, ok := client.markets[fmt.Sprintf("%s-%s", debtSymbol, collateralSymbol)]; ok { 175 | tradingPair = fmt.Sprintf("%s-%s", debtSymbol, collateralSymbol) 176 | } else { 177 | tradingPair = fmt.Sprintf("%s-%s", collateralSymbol, debtSymbol) 178 | } 179 | 180 | auction = &Auction{ 181 | auctionID, 182 | debtSymbol, 183 | collateralSymbol, 184 | tradingPair, 185 | availableDetb, 186 | availableCollateral, 187 | ratio, 188 | price, 189 | finished, 190 | } 191 | 192 | return 193 | } 194 | 195 | func (client *BidderClient) GetAllAuctions() (auctions []*Auction, err error) { 196 | auctionIDs, err := client.GetCurrentAuctionIDs() 197 | if err != nil { 198 | return 199 | } 200 | auctions = []*Auction{} 201 | for _, auctionID := range auctionIDs { 202 | auction, err := client.GetSingleAuction(auctionID) 203 | if err == nil { 204 | auctions = append(auctions, auction) 205 | } 206 | } 207 | 208 | return 209 | } 210 | -------------------------------------------------------------------------------- /client/ddexApiInterface.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | type IMarkets struct { 4 | Status int `json:"status"` 5 | Desc string `json:"desc"` 6 | Template string `json:"template"` 7 | Params interface{} `json:"params"` 8 | Data struct { 9 | Markets []struct { 10 | ID string `json:"id"` 11 | MaxSlippage string `json:"maxSlippage"` 12 | MarginMarketID int `json:"marginMarketId"` 13 | IsMarginMarket bool `json:"isMarginMarket"` 14 | BaseAsset string `json:"baseAsset"` 15 | BaseAssetName string `json:"baseAssetName"` 16 | BaseAssetDecimals int `json:"baseAssetDecimals"` 17 | BaseAssetDisplayDecimals int `json:"baseAssetDisplayDecimals"` 18 | BaseAssetAddress string `json:"baseAssetAddress"` 19 | QuoteAsset string `json:"quoteAsset"` 20 | QuoteAssetName string `json:"quoteAssetName"` 21 | QuoteAssetDecimals int `json:"quoteAssetDecimals"` 22 | QuoteAssetDisplayDecimals int `json:"quoteAssetDisplayDecimals"` 23 | QuoteAssetAddress string `json:"quoteAssetAddress"` 24 | MinOrderSize string `json:"minOrderSize"` 25 | PricePrecision int `json:"pricePrecision"` 26 | PriceDecimals int `json:"priceDecimals"` 27 | AmountDecimals int `json:"amountDecimals"` 28 | AsMakerFeeRate string `json:"asMakerFeeRate"` 29 | AsTakerFeeRate string `json:"asTakerFeeRate"` 30 | GasFeeAmount string `json:"gasFeeAmount"` 31 | SupportedOrderTypes []string `json:"supportedOrderTypes"` 32 | LastPriceIncrease string `json:"lastPriceIncrease"` 33 | LastPrice string `json:"lastPrice"` 34 | Price24H string `json:"price24h"` 35 | Amount24H string `json:"amount24h"` 36 | QuoteAssetVolume24H string `json:"quoteAssetVolume24h"` 37 | BaseAssetUSDPrice string `json:"baseAssetUSDPrice"` 38 | QuoteAssetUSDPrice string `json:"quoteAssetUSDPrice"` 39 | MaxLeverageRate string `json:"maxLeverageRate"` 40 | WithdrawRate string `json:"withdrawRate"` 41 | LiquidationRate string `json:"liquidationRate"` 42 | } `json:"markets"` 43 | } `json:"data"` 44 | } 45 | 46 | type IAssets struct { 47 | Status int `json:"status"` 48 | Desc string `json:"desc"` 49 | Template string `json:"template"` 50 | Params interface{} `json:"params"` 51 | Data struct { 52 | Assets []struct { 53 | Address string `json:"address"` 54 | DisplayDecimals int `json:"displayDecimals"` 55 | Symbol string `json:"symbol"` 56 | Name string `json:"name"` 57 | Decimals int `json:"decimals"` 58 | OracleUSDPrice string `json:"oracleUSDPrice"` 59 | BorrowInterestRate string `json:"borrowInterestRate"` 60 | SupplyInterestRate string `json:"supplyInterestRate"` 61 | PoolTokenAddress string `json:"poolTokenAddress"` 62 | } `json:"assets"` 63 | } `json:"data"` 64 | } 65 | 66 | type IOrderResp struct { 67 | ID string `json:"id"` 68 | Type string `json:"type"` 69 | Version string `json:"version"` 70 | Status string `json:"status"` 71 | Amount string `json:"amount"` 72 | AvailableAmount string `json:"availableAmount"` 73 | PendingAmount string `json:"pendingAmount"` 74 | CanceledAmount string `json:"canceledAmount"` 75 | ConfirmedAmount string `json:"confirmedAmount"` 76 | Price string `json:"price"` 77 | AveragePrice string `json:"averagePrice"` 78 | Side string `json:"side"` 79 | MakerFeeRate string `json:"makerFeeRate"` 80 | TakerFeeRate string `json:"takerFeeRate"` 81 | MakerRebateRate string `json:"makerRebateRate"` 82 | GasFeeAmount string `json:"gasFeeAmount"` 83 | Account string `json:"account"` 84 | CreatedAt int64 `json:"createdAt"` 85 | MarketID string `json:"marketId"` 86 | } 87 | 88 | type ILockedBalance struct { 89 | Status int `json:"status"` 90 | Desc string `json:"desc"` 91 | Data struct { 92 | LockedBalances []struct { 93 | Address string `json:"Address"` 94 | Symbol string `json:"symbol"` 95 | AssetAddress string `json:"assetAddress"` 96 | WalletType string `json:"walletType"` 97 | MarginMarketID int `json:"marginMarketId"` 98 | Amount string `json:"amount"` 99 | } `json:"lockedBalances"` 100 | } `json:"data"` 101 | } 102 | 103 | type IOrder struct { 104 | Status int `json:"status"` 105 | Desc string `json:"desc"` 106 | Data struct { 107 | Order IOrderResp `json:"order"` 108 | } `json:"data"` 109 | } 110 | 111 | type IAllPendingOrders struct { 112 | Status int `json:"status"` 113 | Desc string `json:"desc"` 114 | Data struct { 115 | TotalCount int `json:"totalCount"` 116 | TotalPages int `json:"totalPages"` 117 | CurrentPage int `json:"currentPage"` 118 | Orders []IOrderResp `json:"orders"` 119 | } `json:"data"` 120 | } 121 | 122 | type IBuildOrder struct { 123 | Status int `json:"status"` 124 | Desc string `json:"desc"` 125 | Data struct { 126 | Order struct { 127 | ID string `json:"id"` 128 | } `json:"order"` 129 | } `json:"data"` 130 | } 131 | 132 | type IPlaceOrder struct { 133 | Status int `json:"status"` 134 | Desc string `json:"desc"` 135 | } 136 | 137 | type IPlaceOrderSync struct { 138 | Status int `json:"status"` 139 | Desc string `json:"desc"` 140 | Data struct { 141 | Order IOrderResp `json:"order"` 142 | } `json:"data"` 143 | } 144 | 145 | type ICancelOrder struct { 146 | Status int `json:"status"` 147 | Desc string `json:"desc"` 148 | } 149 | 150 | type IOrderbook struct { 151 | Status int `json:"status"` 152 | Desc string `json:"desc"` 153 | Data struct { 154 | OrderBook struct { 155 | MarketID string `json:"marketId"` 156 | Bids []struct { 157 | Price string `json:"price"` 158 | Amount string `json:"amount"` 159 | } `json:"bids"` 160 | Asks []struct { 161 | Price string `json:"price"` 162 | Amount string `json:"amount"` 163 | } `json:"asks"` 164 | } `json:"orderBook"` 165 | } `json:"data"` 166 | } 167 | -------------------------------------------------------------------------------- /client/ddexClient.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "auctionBidder/utils" 5 | "auctionBidder/web3" 6 | "encoding/hex" 7 | "encoding/json" 8 | "errors" 9 | "fmt" 10 | "github.com/ethereum/go-ethereum/common" 11 | "github.com/shopspring/decimal" 12 | "github.com/sirupsen/logrus" 13 | "os" 14 | "strconv" 15 | "strings" 16 | "time" 17 | ) 18 | 19 | type SimpleOrder struct { 20 | Amount decimal.Decimal 21 | Price decimal.Decimal 22 | Side string 23 | } 24 | 25 | type OrderRes struct { 26 | Id string 27 | Status string 28 | Side string 29 | Amount decimal.Decimal 30 | Price decimal.Decimal 31 | AvailableAmount decimal.Decimal 32 | FilledAmount decimal.Decimal 33 | AvgPrice decimal.Decimal 34 | } 35 | 36 | type Balance struct { 37 | Free decimal.Decimal 38 | Lock decimal.Decimal 39 | Total decimal.Decimal 40 | } 41 | 42 | type Inventory map[string]*Balance // symbol -> Balance 43 | 44 | type Asset struct { 45 | Symbol string 46 | Address string 47 | Decimal int32 48 | } 49 | 50 | type Market struct { 51 | Base Asset 52 | Quote Asset 53 | PricePrecision int 54 | PriceDecimal int 55 | AmountDecimal int 56 | } 57 | 58 | type DdexClient struct { 59 | Address string 60 | Assets map[string]*Asset // symbol -> Asset 61 | Markets map[string]*Market // "ETH-DAI" -> Market 62 | hydroContract *web3.Contract 63 | privateKey string 64 | signCache string 65 | lastSignTime int64 66 | baseUrl string 67 | } 68 | 69 | func NewDdexClient(privateKey string) (client *DdexClient, err error) { 70 | ethereumNodeUrl := os.Getenv("ETHEREUM_NODE_URL") 71 | ddexBaseUrl := os.Getenv("DDEX_URL") 72 | hydroContractAddress := os.Getenv("HYDRO_CONTRACT_ADDRESS") 73 | 74 | web3 := web3.NewWeb3(ethereumNodeUrl) 75 | address, err := web3.AddPrivateKey(privateKey) 76 | if err != nil { 77 | return 78 | } 79 | contract, err := web3.NewContract(utils.HydroAbi, hydroContractAddress) 80 | if err != nil { 81 | return 82 | } 83 | 84 | // get market meta data 85 | var dataContainer IMarkets 86 | resp, err := utils.Get( 87 | utils.JoinUrlPath(ddexBaseUrl, fmt.Sprintf("markets")), 88 | "", 89 | utils.EmptyKeyPairList, 90 | []utils.KeyPair{{"Content-Type", "application/json"}}) 91 | if err != nil { 92 | logrus.Error("call " + utils.JoinUrlPath(ddexBaseUrl, fmt.Sprintf("markets")) + " failed") 93 | return 94 | } 95 | json.Unmarshal([]byte(resp), &dataContainer) 96 | if dataContainer.Desc != "success" { 97 | err = errors.New(dataContainer.Desc) 98 | return 99 | } 100 | 101 | assets := map[string]*Asset{} 102 | markets := map[string]*Market{} 103 | 104 | for _, market := range dataContainer.Data.Markets { 105 | if _, ok := assets[market.BaseAssetName]; !ok { 106 | assets[market.BaseAssetName] = &Asset{market.BaseAssetName, market.BaseAssetAddress, int32(market.BaseAssetDecimals)} 107 | } 108 | if _, ok := assets[market.QuoteAssetName]; !ok { 109 | assets[market.QuoteAssetName] = &Asset{market.QuoteAssetName, market.QuoteAssetAddress, int32(market.QuoteAssetDecimals)} 110 | } 111 | markets[fmt.Sprintf("%s-%s", market.BaseAssetName, market.QuoteAssetName)] = &Market{ 112 | *assets[market.BaseAssetName], 113 | *assets[market.QuoteAssetName], 114 | market.PricePrecision, 115 | market.PriceDecimals, 116 | market.AmountDecimals, 117 | } 118 | } 119 | 120 | client = &DdexClient{ 121 | address, 122 | assets, 123 | markets, 124 | contract, 125 | privateKey, 126 | "", 127 | 0, 128 | ddexBaseUrl, 129 | } 130 | 131 | return 132 | } 133 | 134 | func (client *DdexClient) updateSignCache() { 135 | now := utils.MillisecondTimestamp() 136 | if client.lastSignTime < now-200000 { 137 | messageStr := "HYDRO-AUTHENTICATION@" + strconv.Itoa(int(now)) 138 | signRes, _ := utils.PersonalSign([]byte(messageStr), client.privateKey) 139 | client.signCache = fmt.Sprintf("%s#%s#0x%x", strings.ToLower(client.Address), messageStr, signRes) 140 | client.lastSignTime = now 141 | } 142 | } 143 | 144 | func (client *DdexClient) signOrderId(orderId string) string { 145 | orderIdBytes, _ := hex.DecodeString(strings.TrimPrefix(orderId, "0x")) 146 | signature, _ := utils.PersonalSign(orderIdBytes, client.privateKey) 147 | return "0x" + hex.EncodeToString(signature) 148 | } 149 | 150 | func (client *DdexClient) get(path string, params []utils.KeyPair) (string, error) { 151 | client.updateSignCache() 152 | return utils.Get( 153 | utils.JoinUrlPath(client.baseUrl, path), 154 | "", 155 | params, 156 | []utils.KeyPair{ 157 | {"Hydro-Authentication", client.signCache}, 158 | {"Content-Type", "application/json"}, 159 | }, 160 | ) 161 | } 162 | 163 | func (client *DdexClient) post(path string, body string, params []utils.KeyPair) (string, error) { 164 | client.updateSignCache() 165 | return utils.Post( 166 | utils.JoinUrlPath(client.baseUrl, path), 167 | body, 168 | params, 169 | []utils.KeyPair{ 170 | {"Hydro-Authentication", client.signCache}, 171 | {"Content-Type", "application/json"}, 172 | }, 173 | ) 174 | } 175 | 176 | func (client *DdexClient) delete(path string, params []utils.KeyPair) (string, error) { 177 | client.updateSignCache() 178 | return utils.Delete( 179 | utils.JoinUrlPath(client.baseUrl, path), 180 | "", 181 | params, 182 | []utils.KeyPair{ 183 | {"Hydro-Authentication", client.signCache}, 184 | {"Content-Type", "application/json"}, 185 | }, 186 | ) 187 | } 188 | 189 | func (client *DdexClient) buildUnsignedOrder( 190 | tradingPair string, 191 | price decimal.Decimal, 192 | amount decimal.Decimal, 193 | side string, 194 | orderType string, 195 | isMakerOnly bool, 196 | expireTimeInSecond int64) (orderId string, err error) { 197 | var dataContainer IBuildOrder 198 | var body = struct { 199 | MarketId string `json:"marketId"` 200 | Side string `json:"side"` 201 | OrderType string `json:"orderType"` 202 | Price decimal.Decimal `json:"price"` 203 | Amount decimal.Decimal `json:"amount"` 204 | Expires int64 `json:"expires"` 205 | IsMakerOnly bool `json:"isMakerOnly"` 206 | WalletType string `json:"walletType"` 207 | }{ 208 | tradingPair, 209 | side, 210 | orderType, 211 | price, 212 | amount, 213 | expireTimeInSecond, 214 | isMakerOnly, 215 | "trading", 216 | } 217 | bodyBytes, _ := json.Marshal(body) 218 | resp, err := client.post("orders/build", string(bodyBytes), utils.EmptyKeyPairList) 219 | if err != nil { 220 | return "", err 221 | } 222 | json.Unmarshal([]byte(resp), &dataContainer) 223 | if dataContainer.Desc != "success" { 224 | err = errors.New(dataContainer.Desc) 225 | } else { 226 | orderId = dataContainer.Data.Order.ID 227 | } 228 | 229 | return 230 | } 231 | 232 | func (client *DdexClient) placeOrder(orderId string) (res *OrderRes, err error) { 233 | var body = struct { 234 | OrderId string `json:"orderId"` 235 | Signature string `json:"signature"` 236 | }{orderId, client.signOrderId(orderId)} 237 | bodyBytes, _ := json.Marshal(body) 238 | resp, err := client.post("orders", string(bodyBytes), utils.EmptyKeyPairList) 239 | if err != nil { 240 | return 241 | } 242 | var dataContainer IPlaceOrderSync 243 | json.Unmarshal([]byte(resp), &dataContainer) 244 | if dataContainer.Desc != "success" { 245 | err = errors.New(dataContainer.Desc) 246 | } else { 247 | res = client.parseDdexOrderResp(dataContainer.Data.Order) 248 | } 249 | 250 | return 251 | } 252 | 253 | func (client *DdexClient) CreateLimitOrder( 254 | tradingPair string, 255 | price decimal.Decimal, 256 | amount decimal.Decimal, 257 | side string, 258 | isMakerOnly bool, 259 | expireTimeInSecond int64) (orderId string, err error) { 260 | validPrice := utils.SetDecimal(utils.SetPrecision(price, client.Markets[tradingPair].PricePrecision), client.Markets[tradingPair].PriceDecimal) 261 | validAmount := utils.SetDecimal(amount, client.Markets[tradingPair].AmountDecimal) 262 | orderId, err = client.buildUnsignedOrder(tradingPair, validPrice, validAmount, side, "limit", isMakerOnly, expireTimeInSecond) 263 | if err != nil { 264 | return 265 | } 266 | _, err = client.placeOrder(orderId) 267 | if err == nil { 268 | logrus.Debugf("create limit order at %s - price:%s amount:%s side:%s %s", tradingPair, validPrice, validAmount, side, orderId) 269 | } 270 | return 271 | } 272 | 273 | func (client *DdexClient) CreateMarketOrder( 274 | tradingPair string, 275 | priceLimit decimal.Decimal, 276 | amount decimal.Decimal, 277 | side string, 278 | ) (res *OrderRes, err error) { 279 | validPrice := utils.SetDecimal(utils.SetPrecision(priceLimit, client.Markets[tradingPair].PricePrecision), client.Markets[tradingPair].PriceDecimal) 280 | amount = utils.SetDecimal(amount, client.Markets[tradingPair].AmountDecimal) 281 | orderId, err := client.buildUnsignedOrder(tradingPair, validPrice, amount, side, "market", false, 3600) 282 | if err != nil { 283 | return 284 | } 285 | 286 | res, err = client.placeOrder(orderId) 287 | if err == nil { 288 | logrus.Debugf("create market order at %s - price:%s amount:%s side:%s %s", tradingPair, validPrice, amount, side, orderId) 289 | } 290 | return 291 | } 292 | 293 | func (client *DdexClient) MarketSellAsset( 294 | tradingPair string, 295 | assetSymbol string, 296 | amount decimal.Decimal, 297 | maxSlippage decimal.Decimal, 298 | ) ( 299 | orderId string, 300 | sellAmount decimal.Decimal, 301 | receiveAmount decimal.Decimal, 302 | err error, 303 | ) { 304 | orderId = "0x0" 305 | sellAmount = decimal.Zero 306 | receiveAmount = decimal.Zero 307 | _, _, midPrice, err := client.GetMarketPrice(tradingPair) 308 | if err != nil { 309 | return 310 | } 311 | var orderRes *OrderRes 312 | if assetSymbol == strings.Split(tradingPair, "-")[0] { 313 | orderRes, err = client.CreateMarketOrder( 314 | tradingPair, 315 | midPrice.Mul(decimal.New(1, 0).Sub(maxSlippage)), 316 | amount, 317 | utils.SELL, 318 | ) 319 | if err != nil { 320 | return 321 | } else { 322 | orderId = orderRes.Id 323 | sellAmount = orderRes.FilledAmount 324 | receiveAmount = orderRes.FilledAmount.Mul(orderRes.AvgPrice) 325 | } 326 | } else { 327 | orderRes, err = client.CreateMarketOrder( 328 | tradingPair, 329 | midPrice.Mul(decimal.New(1, 0).Add(maxSlippage)), 330 | amount, 331 | utils.BUY, 332 | ) 333 | if err != nil { 334 | return 335 | } else { 336 | orderId = orderRes.Id 337 | sellAmount = orderRes.FilledAmount 338 | receiveAmount = orderRes.FilledAmount.Div(orderRes.AvgPrice) 339 | } 340 | } 341 | 342 | return 343 | } 344 | 345 | func (client *DdexClient) PromisedMarketSellAsset( 346 | tradingPair string, 347 | assetSymbol string, 348 | amount decimal.Decimal, 349 | maxSlippage decimal.Decimal, 350 | ) ( 351 | orderId string, 352 | sellAmount decimal.Decimal, 353 | receiveAmount decimal.Decimal, 354 | err error, 355 | ) { 356 | for { 357 | orderId, sellAmount, receiveAmount, err = client.MarketSellAsset(tradingPair, assetSymbol, amount, maxSlippage) 358 | if err != nil { 359 | time.Sleep(time.Second) 360 | } else { 361 | return 362 | } 363 | } 364 | } 365 | 366 | func (client *DdexClient) CancelOrder(orderId string) error { 367 | resp, err := client.delete("orders/"+orderId, utils.EmptyKeyPairList) 368 | if err != nil { 369 | return err 370 | } 371 | var dataContainer ICancelOrder 372 | json.Unmarshal([]byte(resp), &dataContainer) 373 | if dataContainer.Desc != "success" { 374 | return errors.New(dataContainer.Desc) 375 | } else { 376 | logrus.Infof("cancel order %s ", orderId) 377 | return nil 378 | } 379 | } 380 | 381 | func (client *DdexClient) CancelAllPendingOrders() error { 382 | for tradingPair, _ := range client.Markets { 383 | resp, err := client.delete("orders", []utils.KeyPair{{"marketId", tradingPair}}) 384 | if err != nil { 385 | return err 386 | } 387 | var dataContainer ICancelOrder 388 | json.Unmarshal([]byte(resp), &dataContainer) 389 | if dataContainer.Desc != "success" { 390 | return errors.New(dataContainer.Desc) 391 | } 392 | } 393 | logrus.Infof("cancel all orders") 394 | return nil 395 | } 396 | 397 | func (client *DdexClient) parseDdexOrderResp(orderInfo IOrderResp) *OrderRes { 398 | var orderData = &OrderRes{} 399 | orderData.Id = orderInfo.ID 400 | orderData.Amount, _ = decimal.NewFromString(orderInfo.Amount) 401 | orderData.AvailableAmount, _ = decimal.NewFromString(orderInfo.AvailableAmount) 402 | orderData.Price, _ = decimal.NewFromString(orderInfo.Price) 403 | orderData.AvgPrice, _ = decimal.NewFromString(orderInfo.AveragePrice) 404 | pendingAmount, _ := decimal.NewFromString(orderInfo.PendingAmount) 405 | confirmedAmount, _ := decimal.NewFromString(orderInfo.ConfirmedAmount) 406 | orderData.FilledAmount = pendingAmount.Add(confirmedAmount) 407 | if orderData.AvailableAmount.IsZero() { 408 | orderData.Status = utils.ORDERCLOSE 409 | } else { 410 | orderData.Status = utils.ORDEROPEN 411 | } 412 | if orderInfo.Side == "sell" { 413 | orderData.Side = utils.SELL 414 | } else { 415 | orderData.Side = utils.BUY 416 | } 417 | 418 | return orderData 419 | } 420 | 421 | func (client *DdexClient) GetOrder(orderId string) (res *OrderRes, err error) { 422 | resp, err := client.get("orders/"+orderId, utils.EmptyKeyPairList) 423 | if err != nil { 424 | return 425 | } 426 | var dataContainer IOrder 427 | json.Unmarshal([]byte(resp), &dataContainer) 428 | if dataContainer.Desc != "success" { 429 | err = errors.New(dataContainer.Desc) 430 | } else { 431 | res = client.parseDdexOrderResp(dataContainer.Data.Order) 432 | } 433 | 434 | return 435 | } 436 | 437 | func (client *DdexClient) GetInventory() (inventory Inventory, err error) { 438 | inventory = map[string]*Balance{} 439 | for symbol, asset := range client.Assets { 440 | var amountHex string 441 | amountHex, err = client.hydroContract.Call("balanceOf", common.HexToAddress(asset.Address), common.HexToAddress(client.Address)) 442 | if err != nil { 443 | return 444 | } 445 | amount := utils.HexString2Decimal(amountHex, -1*asset.Decimal) 446 | inventory[symbol] = &Balance{amount, decimal.Zero, amount} 447 | } 448 | 449 | resp, err := client.get("account/lockedBalances", utils.EmptyKeyPairList) 450 | if err != nil { 451 | return 452 | } 453 | var dataContainer ILockedBalance 454 | json.Unmarshal([]byte(resp), &dataContainer) 455 | if dataContainer.Desc != "success" { 456 | err = errors.New(dataContainer.Desc) 457 | return 458 | } 459 | for _, lockedBalance := range dataContainer.Data.LockedBalances { 460 | if _, ok := inventory[lockedBalance.Symbol]; ok && lockedBalance.WalletType == "trading" { 461 | amount, _ := decimal.NewFromString(lockedBalance.Amount) 462 | inventory[lockedBalance.Symbol].Lock = amount.Mul(decimal.New(1, -1*client.Assets[lockedBalance.Symbol].Decimal)) 463 | inventory[lockedBalance.Symbol].Free = inventory[lockedBalance.Symbol].Total.Sub(inventory[lockedBalance.Symbol].Lock) 464 | } 465 | } 466 | 467 | return 468 | } 469 | 470 | func (client *DdexClient) GetMarketPrice(tradingPair string) ( 471 | bestBidPrice decimal.Decimal, 472 | bestAskPrice decimal.Decimal, 473 | midPrice decimal.Decimal, 474 | err error) { 475 | resp, err := client.get( 476 | fmt.Sprintf("markets/%s/orderbook", tradingPair), 477 | []utils.KeyPair{{"level", "1"}}, 478 | ) 479 | if err != nil { 480 | return 481 | } 482 | var dataContainer IOrderbook 483 | json.Unmarshal([]byte(resp), &dataContainer) 484 | if len(dataContainer.Data.OrderBook.Asks) == 0 || len(dataContainer.Data.OrderBook.Bids) == 0 { 485 | err = utils.OrderbookNotComplete 486 | return 487 | } 488 | bestAskPrice, _ = decimal.NewFromString(dataContainer.Data.OrderBook.Asks[0].Price) 489 | bestBidPrice, _ = decimal.NewFromString(dataContainer.Data.OrderBook.Bids[0].Price) 490 | midPrice = bestAskPrice.Add(bestBidPrice).Div(decimal.New(2, 0)) 491 | 492 | return 493 | } 494 | 495 | func (client *DdexClient) QuerySellAssetReceiveAmount( 496 | tradingPair string, 497 | assetSymbol string, 498 | payAmount decimal.Decimal, 499 | ) (receiveAmount decimal.Decimal, err error) { 500 | resp, err := client.get(fmt.Sprintf("markets/%s/orderbook", tradingPair), []utils.KeyPair{{"level", "2"}}) 501 | if err != nil { 502 | return 503 | } 504 | var dataContainer IOrderbook 505 | json.Unmarshal([]byte(resp), &dataContainer) 506 | if dataContainer.Desc != "success" { 507 | err = errors.New(dataContainer.Desc) 508 | return 509 | } 510 | 511 | receiveAmount = decimal.Zero 512 | if assetSymbol == client.Markets[tradingPair].Quote.Symbol { 513 | for _, ask := range dataContainer.Data.OrderBook.Asks { 514 | price, _ := decimal.NewFromString(ask.Price) 515 | amount, _ := decimal.NewFromString(ask.Amount) 516 | if price.Mul(amount).GreaterThanOrEqual(payAmount) { 517 | receiveAmount = receiveAmount.Add(payAmount.Div(price)) 518 | payAmount = decimal.Zero 519 | break 520 | } else { 521 | receiveAmount = receiveAmount.Add(amount) 522 | payAmount = payAmount.Sub(price.Mul(amount)) 523 | } 524 | } 525 | if payAmount.IsPositive() { 526 | err = utils.OrderbookDepthNotEnough 527 | } 528 | } else { 529 | for _, bid := range dataContainer.Data.OrderBook.Bids { 530 | price, _ := decimal.NewFromString(bid.Price) 531 | amount, _ := decimal.NewFromString(bid.Amount) 532 | if amount.GreaterThanOrEqual(payAmount) { 533 | receiveAmount = receiveAmount.Add(payAmount.Mul(price)) 534 | payAmount = decimal.Zero 535 | break 536 | } else { 537 | receiveAmount = receiveAmount.Add(amount.Mul(price)) 538 | payAmount = payAmount.Sub(amount) 539 | } 540 | } 541 | if payAmount.IsPositive() { 542 | err = utils.OrderbookDepthNotEnough 543 | } 544 | } 545 | 546 | return 547 | } 548 | 549 | func (client *DdexClient) GetAssetUSDPrice(assetSymbol string) (price decimal.Decimal, err error) { 550 | price = decimal.New(-1, 0) 551 | resp, err := client.get("assets", utils.EmptyKeyPairList) 552 | if err != nil { 553 | return 554 | } 555 | var dataContainer IAssets 556 | json.Unmarshal([]byte(resp), &dataContainer) 557 | if dataContainer.Desc != "success" { 558 | err = errors.New(dataContainer.Desc) 559 | return 560 | } 561 | for _, asset := range dataContainer.Data.Assets { 562 | if assetSymbol == asset.Symbol { 563 | price, _ = decimal.NewFromString(asset.OracleUSDPrice) 564 | } 565 | } 566 | if price.LessThanOrEqual(decimal.Zero) { 567 | err = errors.New("not find asset usd price") 568 | } 569 | return 570 | } 571 | -------------------------------------------------------------------------------- /docs/deposit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HydroProtocol/liquidation_bot/86b8ace8b00dbefaf58c7b66d98be633fd3cb61e/docs/deposit.png -------------------------------------------------------------------------------- /docs/screen_snapshot.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HydroProtocol/liquidation_bot/86b8ace8b00dbefaf58c7b66d98be633fd3cb61e/docs/screen_snapshot.jpg -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module auctionBidder 2 | 3 | go 1.12 4 | 5 | require ( 6 | github.com/allegro/bigcache v1.2.1 // indirect 7 | github.com/aristanetworks/goarista v0.0.0-20191001182449-186a6201b8ef // indirect 8 | github.com/btcsuite/btcd v0.0.0-20190926002857-ba530c4abb35 9 | github.com/c-bata/go-prompt v0.2.3 // indirect 10 | github.com/davecgh/go-spew v1.1.1 11 | github.com/elastic/gosigar v0.10.5 // indirect 12 | github.com/ethereum/go-ethereum v1.9.6 13 | github.com/fatih/color v1.7.0 14 | github.com/gizak/termui v3.1.0+incompatible // indirect 15 | github.com/gizak/termui/v3 v3.1.0 // indirect 16 | github.com/go-stack/stack v1.8.0 // indirect 17 | github.com/jarcoal/httpmock v1.0.4 18 | github.com/jroimartin/gocui v0.4.0 19 | github.com/lestrrat-go/file-rotatelogs v2.2.0+incompatible 20 | github.com/lestrrat-go/strftime v0.0.0-20190725011945-5c849dd2c51d // indirect 21 | github.com/mattn/go-colorable v0.1.4 // indirect 22 | github.com/mattn/go-isatty v0.0.10 // indirect 23 | github.com/mattn/go-runewidth v0.0.4 // indirect 24 | github.com/mattn/go-sqlite3 v1.11.0 25 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect 26 | github.com/modern-go/reflect2 v1.0.1 // indirect 27 | github.com/pkg/errors v0.8.1 28 | github.com/pkg/term v0.0.0-20190109203006-aa71e9d9e942 // indirect 29 | github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5 30 | github.com/rs/xid v1.2.1 // indirect 31 | github.com/shopspring/decimal v0.0.0-20190905144223-a36b5d85f337 32 | github.com/sirupsen/logrus v1.4.2 33 | github.com/steakknife/bloomfilter v0.0.0-20180922174646-6819c0d2a570 // indirect 34 | github.com/steakknife/hamming v0.0.0-20180906055917-c99c65617cd3 // indirect 35 | github.com/stretchr/testify v1.3.0 36 | github.com/tidwall/gjson v1.3.2 37 | golang.org/x/crypto v0.0.0-20191002192127-34f69633bfdc 38 | ) 39 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= 2 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= 3 | github.com/DataDog/zstd v1.3.6-0.20190409195224-796139022798/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= 4 | github.com/Shopify/sarama v1.23.1/go.mod h1:XLH1GYJnLVE0XCr6KdJGVJRTwY30moWNJ4sERjXX6fs= 5 | github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= 6 | github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII= 7 | github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= 8 | github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= 9 | github.com/allegro/bigcache v1.2.1 h1:hg1sY1raCwic3Vnsvje6TT7/pnZba83LeFck5NrFKSc= 10 | github.com/allegro/bigcache v1.2.1/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= 11 | github.com/aristanetworks/fsnotify v1.4.2/go.mod h1:D/rtu7LpjYM8tRJphJ0hUBYpjai8SfX+aSNsWDTq/Ks= 12 | github.com/aristanetworks/glog v0.0.0-20180419172825-c15b03b3054f/go.mod h1:KASm+qXFKs/xjSoWn30NrWBBvdTTQq+UjkhjEJHfSFA= 13 | github.com/aristanetworks/goarista v0.0.0-20191001182449-186a6201b8ef h1:22UUblKoiHkspXNKISqLtJWM42z+iECvHS9VymhhC7c= 14 | github.com/aristanetworks/goarista v0.0.0-20191001182449-186a6201b8ef/go.mod h1:Z4RTxGAuYhPzcq8+EdRM+R8M48Ssle2TsWtwRKa+vns= 15 | github.com/aristanetworks/splunk-hec-go v0.3.3/go.mod h1:1VHO9r17b0K7WmOlLb9nTk/2YanvOEnLMUgsFrxBROc= 16 | github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= 17 | github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= 18 | github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= 19 | github.com/btcsuite/btcd v0.0.0-20190926002857-ba530c4abb35 h1:o2mPiVrkVzpBg/Q+lSfuf/92pEgsSIJvsQ13DyHs/3A= 20 | github.com/btcsuite/btcd v0.0.0-20190926002857-ba530c4abb35/go.mod h1:3J08xEfcugPacsc34/LKRU2yO7YmuT8yt28J8k2+rrI= 21 | github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA= 22 | github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg= 23 | github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg= 24 | github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVaaLLH7j4eDXPRvw78tMflu7Ie2bzYOH4Y8rRKBY= 25 | github.com/btcsuite/snappy-go v0.0.0-20151229074030-0bdef8d06723/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc= 26 | github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY= 27 | github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs= 28 | github.com/c-bata/go-prompt v0.2.3/go.mod h1:VzqtzE2ksDBcdln8G7mk2RX9QyGjH+OVqOCSiVIqS34= 29 | github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= 30 | github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 31 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 32 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 33 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 34 | github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= 35 | github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU= 36 | github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= 37 | github.com/elastic/gosigar v0.10.5 h1:GzPQ+78RaAb4J63unidA/JavQRKrB6s8IOzN6Ib59jo= 38 | github.com/elastic/gosigar v0.10.5/go.mod h1:cdorVVzy1fhmEqmtgqkoE3bYtCfSCkVyjTyCIo22xvs= 39 | github.com/ethereum/go-ethereum v1.9.6 h1:EacwxMGKZezZi+m3in0Tlyk0veDQgnfZ9BjQqHAaQLM= 40 | github.com/ethereum/go-ethereum v1.9.6/go.mod h1:PwpWDrCLZrV+tfrhqqF6kPknbISMHaJv9Ln3kPCZLwY= 41 | github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= 42 | github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= 43 | github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= 44 | github.com/garyburd/redigo v1.6.0/go.mod h1:NR3MbYisc3/PwhQ00EMzDiPmrwpPxAn5GI05/YaO1SY= 45 | github.com/gizak/termui v3.1.0+incompatible/go.mod h1:PkJoWUt/zacQKysNfQtcw1RW+eK2SxkieVBtl+4ovLA= 46 | github.com/gizak/termui/v3 v3.1.0/go.mod h1:bXQEBkJpzxUAKf0+xq9MSWAvWZlE7c+aidmyFlkYTrY= 47 | github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= 48 | github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= 49 | github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= 50 | github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk= 51 | github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= 52 | github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= 53 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= 54 | github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= 55 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 56 | github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 57 | github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 58 | github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= 59 | github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= 60 | github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 61 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 62 | github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= 63 | github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= 64 | github.com/influxdata/influxdb1-client v0.0.0-20190809212627-fc22c7df067e/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= 65 | github.com/jarcoal/httpmock v1.0.4/go.mod h1:ATjnClrvW/3tijVmpL/va5Z3aAyGvqU3gCT8nX0Txik= 66 | github.com/jcmturner/gofork v0.0.0-20190328161633-dc7c13fece03/go.mod h1:MK8+TM0La+2rjBD4jE12Kj1pCCxK7d2LK/UM3ncEo0o= 67 | github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= 68 | github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ= 69 | github.com/jroimartin/gocui v0.4.0 h1:52jnalstgmc25FmtGcWqa0tcbMEWS6RpFLsOIO+I+E8= 70 | github.com/jroimartin/gocui v0.4.0/go.mod h1:7i7bbj99OgFHzo7kB2zPb8pXLqMBSQegY7azfqXMkyY= 71 | github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= 72 | github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= 73 | github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= 74 | github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4= 75 | github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= 76 | github.com/klauspost/reedsolomon v1.9.2/go.mod h1:CwCi+NUr9pqSVktrkN+Ondf06rkhYZ/pcNv7fu+8Un4= 77 | github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= 78 | github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= 79 | github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= 80 | github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc/go.mod h1:kopuH9ugFRkIXf3YoqHKyrJ9YfUFsckUU9S7B+XP+is= 81 | github.com/lestrrat-go/file-rotatelogs v2.2.0+incompatible h1:eXEwY0f2h6mcobdAxm4VRSWds4tqmlLdUqxu8ybiEEA= 82 | github.com/lestrrat-go/file-rotatelogs v2.2.0+incompatible/go.mod h1:ZQnN8lSECaebrkQytbHj4xNgtg8CR7RYXnPok8e0EHA= 83 | github.com/lestrrat-go/strftime v0.0.0-20190725011945-5c849dd2c51d h1:lNJ1yeRNN0HuKHMY+u10nvgd9cWUS1uXNRyyS4kVGYY= 84 | github.com/lestrrat-go/strftime v0.0.0-20190725011945-5c849dd2c51d/go.mod h1:E1nN3pCbtMSu1yjSVeyuRFVm/U0xoR76fd03sz+Qz4g= 85 | github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA= 86 | github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= 87 | github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= 88 | github.com/mattn/go-isatty v0.0.10 h1:qxFzApOv4WsAL965uUPIsXzAKCZxN2p9UqdhFS4ZW10= 89 | github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= 90 | github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= 91 | github.com/mattn/go-runewidth v0.0.4 h1:2BvfKmzob6Bmd4YsL0zygOqfdFnK7GR4QL06Do4/p7Y= 92 | github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= 93 | github.com/mattn/go-sqlite3 v1.11.0 h1:LDdKkqtYlom37fkvqs8rMPFKAMe8+SgjbwZ6ex1/A/Q= 94 | github.com/mattn/go-sqlite3 v1.11.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= 95 | github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= 96 | github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= 97 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 98 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 99 | github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= 100 | github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= 101 | github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= 102 | github.com/nsf/termbox-go v0.0.0-20190121233118-02980233997d h1:x3S6kxmy49zXVVyhcnrFqxvNVCBPb2KZ9hV2RBdS840= 103 | github.com/nsf/termbox-go v0.0.0-20190121233118-02980233997d/go.mod h1:IuKpRQcYE1Tfu+oAQqaLisqDeXgjyyltCfsaoYN18NQ= 104 | github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= 105 | github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= 106 | github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= 107 | github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= 108 | github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= 109 | github.com/openconfig/gnmi v0.0.0-20190823184014-89b2bf29312c/go.mod h1:t+O9It+LKzfOAhKTT5O0ehDix+MTqbtT0T9t+7zzOvc= 110 | github.com/openconfig/reference v0.0.0-20190727015836-8dfd928c9696/go.mod h1:ym2A+zigScwkSEb/cVQB0/ZMpU3rqiH6X7WRRsxgOGw= 111 | github.com/pierrec/lz4 v0.0.0-20190327172049-315a67e90e41/go.mod h1:3/3N9NVKO0jef7pBehbT1qWhCMrIgbYNnFAZCqQ5LRc= 112 | github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 113 | github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= 114 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 115 | github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA= 116 | github.com/pkg/term v0.0.0-20190109203006-aa71e9d9e942/go.mod h1:eCbImbZ95eXtAUIbLAuAVnBnwf83mjf6QIVH8SHYwqQ= 117 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 118 | github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= 119 | github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= 120 | github.com/prometheus/client_golang v1.1.0/go.mod h1:I1FGZT9+L76gKKOs5djB6ezCbFQP1xR9D75/vuwEF3g= 121 | github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= 122 | github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= 123 | github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= 124 | github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc= 125 | github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= 126 | github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= 127 | github.com/prometheus/procfs v0.0.3/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= 128 | github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= 129 | github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5/go.mod h1:GEXHk5HgEKCvEIIrSpFI3ozzG5xOKA2DVlEX/gGnewM= 130 | github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ= 131 | github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= 132 | github.com/shopspring/decimal v0.0.0-20190905144223-a36b5d85f337 h1:Da9XEUfFxgyDOqUfwgoTDcWzmnlOnCGi6i4iPS+8Fbw= 133 | github.com/shopspring/decimal v0.0.0-20190905144223-a36b5d85f337/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4= 134 | github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= 135 | github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= 136 | github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= 137 | github.com/steakknife/bloomfilter v0.0.0-20180922174646-6819c0d2a570 h1:gIlAHnH1vJb5vwEjIp5kBj/eu99p/bl0Ay2goiPe5xE= 138 | github.com/steakknife/bloomfilter v0.0.0-20180922174646-6819c0d2a570/go.mod h1:8OR4w3TdeIHIh1g6EMY5p0gVNOovcWC+1vpc7naMuAw= 139 | github.com/steakknife/hamming v0.0.0-20180906055917-c99c65617cd3 h1:njlZPzLwU639dk2kqnCPPv+wNjq7Xb6EfUxe/oX0/NM= 140 | github.com/steakknife/hamming v0.0.0-20180906055917-c99c65617cd3/go.mod h1:hpGUWaI9xL8pRQCTXQgocU38Qw1g0Us7n5PxxTwTCYU= 141 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 142 | github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 143 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 144 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 145 | github.com/templexxx/cpufeat v0.0.0-20180724012125-cef66df7f161/go.mod h1:wM7WEvslTq+iOEAMDLSzhVuOt5BRZ05WirO+b09GHQU= 146 | github.com/templexxx/xor v0.0.0-20181023030647-4e92f724b73b/go.mod h1:5XA7W9S6mni3h5uvOC75dA3m9CCCaS83lltmc0ukdi4= 147 | github.com/tidwall/gjson v1.3.2/go.mod h1:P256ACg0Mn+j1RXIDXoss50DeIABTYK1PULOJHhxOls= 148 | github.com/tidwall/match v1.0.1/go.mod h1:LujAq0jyVjBy028G1WhWfIzbpQfMO8bBZ6Tyb0+pL9E= 149 | github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= 150 | github.com/tjfoc/gmsm v1.0.1/go.mod h1:XxO4hdhhrzAd+G4CjDqaOkd0hUzmtPR/d3EiBBMn/wc= 151 | github.com/xdg/scram v0.0.0-20180814205039-7eeb5667e42c/go.mod h1:lB8K/P019DLNhemzwFU4jHLhdvlE6uDZjXFejJXr49I= 152 | github.com/xdg/stringprep v1.0.0/go.mod h1:Jhud4/sHMO4oL310DaZAKk9ZaJ08SJfe+sJh0HrGL1Y= 153 | github.com/xtaci/kcp-go v5.4.5+incompatible/go.mod h1:bN6vIwHQbfHaHtFpEssmWsN45a+AZwO7eyRCmEIbtvE= 154 | github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae/go.mod h1:gXtu8J62kEgmN++bm9BVICuT/e8yiLI2KFobd/TRFsE= 155 | golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= 156 | golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= 157 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 158 | golang.org/x/crypto v0.0.0-20190404164418-38d8ce5564a5/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= 159 | golang.org/x/crypto v0.0.0-20191002192127-34f69633bfdc h1:c0o/qxkaO2LF5t6fQrT4b5hzyggAkLLlCUjqfRxd8Q4= 160 | golang.org/x/crypto v0.0.0-20191002192127-34f69633bfdc/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 161 | golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= 162 | golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 163 | golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 164 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 165 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 166 | golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 167 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 168 | golang.org/x/net v0.0.0-20190912160710-24e19bdeb0f2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 169 | golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= 170 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 171 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 172 | golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 173 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 174 | golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 175 | golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 176 | golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 177 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 178 | golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 179 | golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 180 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 181 | golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 182 | golang.org/x/sys v0.0.0-20190801041406-cbf593c0f2f3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 183 | golang.org/x/sys v0.0.0-20190912141932-bc967efca4b8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 184 | golang.org/x/sys v0.0.0-20191008105621-543471e840be h1:QAcqgptGM8IQBC9K/RC4o+O9YmqEm0diQn9QmZw/0mU= 185 | golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 186 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 187 | golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= 188 | golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= 189 | golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= 190 | golang.org/x/tools v0.0.0-20190912185636-87d9f09c5d89/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 191 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 192 | google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= 193 | google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= 194 | google.golang.org/grpc v1.23.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= 195 | gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= 196 | gopkg.in/bsm/ratelimit.v1 v1.0.0-20160220154919-db14e161995a/go.mod h1:KF9sEfUPAXdG8Oev9e99iLGnl2uJMjc5B+4y3O7x610= 197 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 198 | gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= 199 | gopkg.in/jcmturner/aescts.v1 v1.0.1/go.mod h1:nsR8qBOg+OucoIW+WMhB3GspUQXq9XorLnQb9XtvcOo= 200 | gopkg.in/jcmturner/dnsutils.v1 v1.0.1/go.mod h1:m3v+5svpVOhtFAP/wSz+yzh4Mc0Fg7eRhxkJMWSIz9Q= 201 | gopkg.in/jcmturner/goidentity.v3 v3.0.0/go.mod h1:oG2kH0IvSYNIu80dVAyu/yoefjq1mNfM5bm88whjWx4= 202 | gopkg.in/jcmturner/gokrb5.v7 v7.2.3/go.mod h1:l8VISx+WGYp+Fp7KRbsiUuXTTOnxIc3Tuvyavf11/WM= 203 | gopkg.in/jcmturner/rpc.v1 v1.1.0/go.mod h1:YIdkC4XfD6GXbzje11McwsDuOlZQSb9W4vfLvuNnlv8= 204 | gopkg.in/redis.v4 v4.2.4/go.mod h1:8KREHdypkCEojGKQcjMqAODMICIVwZAONWq8RowTITA= 205 | gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= 206 | gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 207 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 208 | honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= 209 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "auctionBidder/cli" 5 | "auctionBidder/client" 6 | "auctionBidder/utils" 7 | "auctionBidder/web3" 8 | "encoding/json" 9 | "fmt" 10 | "github.com/davecgh/go-spew/spew" 11 | "github.com/shopspring/decimal" 12 | "github.com/sirupsen/logrus" 13 | "io/ioutil" 14 | "os" 15 | ) 16 | 17 | func main() { 18 | var err error 19 | defer func() { 20 | if err != nil { 21 | spew.Dump(err) 22 | } 23 | }() 24 | 25 | setEnv() 26 | 27 | err = checkEnv() 28 | if err != nil { 29 | logrus.Error(err) 30 | return 31 | } 32 | 33 | err = utils.InitDb() 34 | if err != nil { 35 | logrus.Error(err) 36 | return 37 | } 38 | 39 | _, err = startBot() 40 | if err != nil { 41 | logrus.Error(err) 42 | return 43 | } 44 | return 45 | } 46 | 47 | func startBot() (bot *cli.BidderBot, err error) { 48 | 49 | privateKey := os.Getenv("PRIVATE_KEY") 50 | maxSlippage, _ := decimal.NewFromString(os.Getenv("MAX_SLIPPAGE")) 51 | ethereumNodeUrl := os.Getenv("ETHEREUM_NODE_URL") 52 | minOrderValueUSD, _ := decimal.NewFromString(os.Getenv("MIN_ORDER_VALUE_USD")) 53 | profitMargin, _ := decimal.NewFromString(os.Getenv("PROFIT_MARGIN")) 54 | markets := os.Getenv("MARKETS") 55 | 56 | gasPriceLevel := os.Getenv("GAS_PRICE_LEVEL") 57 | gasPriceTipsInGwei := 5 58 | switch gasPriceLevel { 59 | case "fast": 60 | gasPriceTipsInGwei = 0 61 | case "super-fast": 62 | gasPriceTipsInGwei = 10 63 | case "flash-boy": 64 | gasPriceTipsInGwei = 25 65 | } 66 | 67 | ddexClient, err := client.NewDdexClient(privateKey) 68 | if err != nil { 69 | return 70 | } 71 | 72 | bidderClient, err := client.NewBidderClient(privateKey, ddexClient.Assets, ddexClient.Markets) 73 | if err != nil { 74 | return 75 | } 76 | 77 | web3Client := web3.NewWeb3(ethereumNodeUrl) 78 | 79 | bot = &cli.BidderBot{ 80 | bidderClient, 81 | ddexClient, 82 | web3Client.NewBlockChannel(), 83 | maxSlippage, 84 | minOrderValueUSD, 85 | gasPriceTipsInGwei, 86 | markets, 87 | profitMargin, 88 | } 89 | 90 | go bot.Run() 91 | 92 | err = cli.StartGui() 93 | 94 | return 95 | } 96 | 97 | func setEnv() { 98 | os.Setenv("CONFIGPATH", "/workingDir/config.json") 99 | os.Setenv("SQLITEPATH", "/workingDir/auctionBidderSqlite") 100 | os.Setenv("LOGPATH", "/workingDir") 101 | os.Setenv("CHAIN_ID", "1") 102 | os.Setenv("HYDRO_CONTRACT_ADDRESS", "0x241e82C79452F51fbfc89Fac6d912e021dB1a3B7") 103 | os.Setenv("DDEX_URL", "https://api.ddex.io/v4") 104 | 105 | // ropsten 106 | if os.Getenv("NETWORK") == "ropsten" { 107 | os.Setenv("CHAIN_ID", "3") 108 | os.Setenv("HYDRO_CONTRACT_ADDRESS", "0x06898143DF04616a8A8F9614deb3B99Ba12b3096") 109 | os.Setenv("DDEX_URL", "https://bfd-ropsten-59c1702d-api.intra.ddex.io/v4/") 110 | } 111 | 112 | loadEnv(os.Getenv("CONFIGPATH")) 113 | } 114 | 115 | func loadEnv(filePath string) (err error) { 116 | jsonFile, err := os.Open(filePath) 117 | defer jsonFile.Close() 118 | if err != nil { 119 | return 120 | } 121 | byteValue, _ := ioutil.ReadAll(jsonFile) 122 | var envs map[string]string 123 | json.Unmarshal(byteValue, &envs) 124 | for key, value := range envs { 125 | os.Setenv(key, value) 126 | } 127 | return 128 | } 129 | 130 | func checkEnv() (err error) { 131 | requiredEnvDefaultValue := map[string]string{ 132 | "PRIVATE_KEY": "B7A0C9D2786FC4DD080EA5D619D36771AEB0C8C26C290AFD3451B92BA2B7BC2C", 133 | "MAX_SLIPPAGE": "0.05", 134 | "ETHEREUM_NODE_URL": "https://mainnet.infura.io/v3/37851992caeb4289aa749112fe798621", 135 | "MIN_ORDER_VALUE_USD": "100", 136 | "MARKETS": "ETH-USDT,ETH-DAI", 137 | "PROFIT_MARGIN": "0.01", 138 | "GAS_PRICE_LEVEL": "fast", 139 | } 140 | if os.Getenv("NETWORK") == "ropsten" { 141 | requiredEnvDefaultValue["ETHEREUM_NODE_URL"] = "https://ropsten.infura.io/v3/37851992caeb4289aa749112fe798621" 142 | requiredEnvDefaultValue["MARKETS"] = "ETH-USDT6,TETH-DAI" 143 | } 144 | for envName, defaultValue := range requiredEnvDefaultValue { 145 | if os.Getenv(envName) == "" { 146 | fmt.Printf("Enter %s(default %s):", envName, defaultValue) 147 | var input string 148 | fmt.Scanln(&input) 149 | if input == "" { 150 | input = defaultValue 151 | } 152 | os.Setenv(envName, input) 153 | } 154 | requiredEnvDefaultValue[envName] = os.Getenv(envName) 155 | } 156 | 157 | f, err := os.OpenFile(os.Getenv("CONFIGPATH"), os.O_CREATE|os.O_WRONLY, 0600) 158 | defer f.Close() 159 | if err == nil { 160 | envToWrite, _ := json.MarshalIndent(requiredEnvDefaultValue, "", " ") 161 | f.Write(envToWrite) 162 | } 163 | 164 | return 165 | } 166 | -------------------------------------------------------------------------------- /utils/const.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | const ( 4 | BUY = "buy" 5 | SELL = "sell" 6 | ORDERCLOSE = "close" 7 | ORDEROPEN = "open" 8 | ETHERTOKENADDRESS = "0x000000000000000000000000000000000000000e" 9 | ) 10 | 11 | // abis 12 | const Erc20Abi = `[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_upgradedAddress","type":"address"}],"name":"deprecate","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"deprecated","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_evilUser","type":"address"}],"name":"addBlackList","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"upgradedAddress","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balances","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"maximumFee","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"_totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"unpause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_maker","type":"address"}],"name":"getBlackListStatus","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"allowed","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"paused","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"who","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"pause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"newBasisPoints","type":"uint256"},{"name":"newMaxFee","type":"uint256"}],"name":"setParams","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"amount","type":"uint256"}],"name":"issue","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"amount","type":"uint256"}],"name":"redeem","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"basisPointsRate","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"isBlackListed","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_clearedUser","type":"address"}],"name":"removeBlackList","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"MAX_UINT","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_blackListedUser","type":"address"}],"name":"destroyBlackFunds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"_initialSupply","type":"uint256"},{"name":"_name","type":"string"},{"name":"_symbol","type":"string"},{"name":"_decimals","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"amount","type":"uint256"}],"name":"Issue","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"amount","type":"uint256"}],"name":"Redeem","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"newAddress","type":"address"}],"name":"Deprecate","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"feeBasisPoints","type":"uint256"},{"indexed":false,"name":"maxFee","type":"uint256"}],"name":"Params","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_blackListedUser","type":"address"},{"indexed":false,"name":"_balance","type":"uint256"}],"name":"DestroyedBlackFunds","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_user","type":"address"}],"name":"AddedBlackList","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_user","type":"address"}],"name":"RemovedBlackList","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[],"name":"Pause","type":"event"},{"anonymous":false,"inputs":[],"name":"Unpause","type":"event"}]` 13 | const HydroAbi = `[{"constant":false,"inputs":[{"name":"delegate","type":"address"}],"name":"approveDelegate","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"orderHash","type":"bytes32"}],"name":"isOrderCancelled","outputs":[{"name":"isCancelled","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"user","type":"address"},{"name":"marketID","type":"uint16"}],"name":"isAccountLiquidatable","outputs":[{"name":"isLiquidatable","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"asset","type":"address"}],"name":"getPoolCashableAmount","outputs":[{"name":"cashableAmount","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"marketID","type":"uint16"}],"name":"getMarket","outputs":[{"components":[{"name":"baseAsset","type":"address"},{"name":"quoteAsset","type":"address"},{"name":"liquidateRate","type":"uint256"},{"name":"withdrawRate","type":"uint256"},{"name":"auctionRatioStart","type":"uint256"},{"name":"auctionRatioPerBlock","type":"uint256"},{"name":"borrowEnable","type":"bool"}],"name":"market","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"user","type":"address"},{"name":"marketID","type":"uint16"}],"name":"liquidateAccount","outputs":[{"name":"hasAuction","type":"bool"},{"name":"auctionID","type":"uint32"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"marketID","type":"uint16"},{"name":"asset","type":"address"},{"name":"user","type":"address"}],"name":"getMarketTransferableAmount","outputs":[{"name":"amount","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"marketID","type":"uint16"},{"name":"newAuctionRatioStart","type":"uint256"},{"name":"newAuctionRatioPerBlock","type":"uint256"},{"name":"newLiquidateRate","type":"uint256"},{"name":"newWithdrawRate","type":"uint256"}],"name":"updateMarket","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"auctionID","type":"uint32"},{"name":"amount","type":"uint256"}],"name":"fillAuctionWithAmount","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"auctionID","type":"uint32"}],"name":"getAuctionDetails","outputs":[{"components":[{"name":"borrower","type":"address"},{"name":"marketID","type":"uint16"},{"name":"debtAsset","type":"address"},{"name":"collateralAsset","type":"address"},{"name":"leftDebtAmount","type":"uint256"},{"name":"leftCollateralAmount","type":"uint256"},{"name":"ratio","type":"uint256"},{"name":"price","type":"uint256"},{"name":"finished","type":"bool"}],"name":"details","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"assetAddress","type":"address"}],"name":"getAsset","outputs":[{"components":[{"name":"lendingPoolToken","type":"address"},{"name":"priceOracle","type":"address"},{"name":"interestModel","type":"address"}],"name":"asset","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"asset","type":"address"},{"name":"user","type":"address"}],"name":"getAmountSupplied","outputs":[{"name":"amount","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getHydroTokenAddress","outputs":[{"name":"hydroTokenAddress","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"exitIncentiveSystem","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"asset","type":"address"},{"name":"oracleAddress","type":"address"},{"name":"interestModelAddress","type":"address"},{"name":"poolTokenName","type":"string"},{"name":"poolTokenSymbol","type":"string"},{"name":"poolTokenDecimals","type":"uint8"}],"name":"createAsset","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"relayer","type":"address"}],"name":"canMatchOrdersFrom","outputs":[{"name":"canMatch","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"asset","type":"address"},{"name":"extraBorrowAmount","type":"uint256"}],"name":"getInterestRates","outputs":[{"name":"borrowInterestRate","type":"uint256"},{"name":"supplyInterestRate","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"user","type":"address"}],"name":"getDiscountedRate","outputs":[{"name":"rate","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"user","type":"address"},{"name":"marketID","type":"uint16"}],"name":"getAccountDetails","outputs":[{"components":[{"name":"liquidatable","type":"bool"},{"name":"status","type":"uint8"},{"name":"debtsTotalUSDValue","type":"uint256"},{"name":"balancesTotalUSDValue","type":"uint256"}],"name":"details","type":"tuple"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"orderHash","type":"bytes32"}],"name":"getOrderFilledAmount","outputs":[{"name":"amount","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getCurrentAuctions","outputs":[{"name":"","type":"uint32[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"assetAddress","type":"address"}],"name":"getAssetOraclePrice","outputs":[{"name":"price","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"asset","type":"address"}],"name":"getInsuranceBalance","outputs":[{"name":"amount","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"asset","type":"address"}],"name":"getTotalSupply","outputs":[{"name":"amount","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"renounceOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"asset","type":"address"},{"name":"oracleAddress","type":"address"},{"name":"interestModelAddress","type":"address"}],"name":"updateAsset","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"hash","type":"bytes32"},{"name":"signerAddress","type":"address"},{"components":[{"name":"config","type":"bytes32"},{"name":"r","type":"bytes32"},{"name":"s","type":"bytes32"}],"name":"signature","type":"tuple"}],"name":"isValidSignature","outputs":[{"name":"isValid","type":"bool"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":false,"inputs":[{"components":[{"name":"actionType","type":"uint8"},{"name":"encodedParams","type":"bytes"}],"name":"actions","type":"tuple[]"}],"name":"batch","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"name":"asset","type":"address"}],"name":"getTotalBorrow","outputs":[{"name":"amount","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"components":[{"name":"baseAsset","type":"address"},{"name":"quoteAsset","type":"address"},{"name":"liquidateRate","type":"uint256"},{"name":"withdrawRate","type":"uint256"},{"name":"auctionRatioStart","type":"uint256"},{"name":"auctionRatioPerBlock","type":"uint256"},{"name":"borrowEnable","type":"bool"}],"name":"market","type":"tuple"}],"name":"createMarket","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"asset","type":"address"},{"name":"user","type":"address"},{"name":"marketID","type":"uint16"}],"name":"getAmountBorrowed","outputs":[{"name":"amount","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isOwner","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"relayer","type":"address"}],"name":"isParticipant","outputs":[{"name":"result","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getAllMarketsCount","outputs":[{"name":"count","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"components":[{"components":[{"name":"trader","type":"address"},{"name":"baseAssetAmount","type":"uint256"},{"name":"quoteAssetAmount","type":"uint256"},{"name":"gasTokenAmount","type":"uint256"},{"name":"data","type":"bytes32"},{"components":[{"name":"config","type":"bytes32"},{"name":"r","type":"bytes32"},{"name":"s","type":"bytes32"}],"name":"signature","type":"tuple"}],"name":"takerOrderParam","type":"tuple"},{"components":[{"name":"trader","type":"address"},{"name":"baseAssetAmount","type":"uint256"},{"name":"quoteAssetAmount","type":"uint256"},{"name":"gasTokenAmount","type":"uint256"},{"name":"data","type":"bytes32"},{"components":[{"name":"config","type":"bytes32"},{"name":"r","type":"bytes32"},{"name":"s","type":"bytes32"}],"name":"signature","type":"tuple"}],"name":"makerOrderParams","type":"tuple[]"},{"name":"baseAssetFilledAmounts","type":"uint256[]"},{"components":[{"name":"baseAsset","type":"address"},{"name":"quoteAsset","type":"address"},{"name":"relayer","type":"address"}],"name":"orderAddressSet","type":"tuple"}],"name":"params","type":"tuple"}],"name":"matchOrders","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"newInitiatorRewardRatio","type":"uint256"}],"name":"updateAuctionInitiatorRewardRatio","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"asset","type":"address"}],"name":"getIndex","outputs":[{"name":"supplyIndex","type":"uint256"},{"name":"borrowIndex","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"components":[{"name":"trader","type":"address"},{"name":"relayer","type":"address"},{"name":"baseAsset","type":"address"},{"name":"quoteAsset","type":"address"},{"name":"baseAssetAmount","type":"uint256"},{"name":"quoteAssetAmount","type":"uint256"},{"name":"gasTokenAmount","type":"uint256"},{"name":"data","type":"bytes32"}],"name":"order","type":"tuple"}],"name":"cancelOrder","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"joinIncentiveSystem","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"newInsuranceRatio","type":"uint256"}],"name":"updateInsuranceRatio","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"newConfig","type":"bytes32"}],"name":"updateDiscountConfig","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"marketID","type":"uint16"},{"name":"usability","type":"bool"}],"name":"setMarketBorrowUsability","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getAuctionsCount","outputs":[{"name":"count","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"marketID","type":"uint16"},{"name":"asset","type":"address"},{"name":"user","type":"address"}],"name":"marketBalanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"asset","type":"address"},{"name":"user","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"delegate","type":"address"}],"name":"revokeDelegate","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"_hotTokenAddress","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"name":"previousOwner","type":"address"},{"indexed":true,"name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"}]` 14 | -------------------------------------------------------------------------------- /utils/converter.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "encoding/hex" 5 | "fmt" 6 | "github.com/shopspring/decimal" 7 | "math/big" 8 | "strconv" 9 | "strings" 10 | ) 11 | 12 | // hex string <-> int 13 | 14 | func HexString2Int(str string) (int, error) { 15 | str = strings.ToLower(str) 16 | i, err := strconv.ParseInt(strings.TrimPrefix(str, "0x"), 16, 64) 17 | if err != nil { 18 | return 0, err 19 | } 20 | 21 | return int(i), nil 22 | } 23 | 24 | func Int2HexString(i int) string { 25 | return fmt.Sprintf("0x%x", i) 26 | } 27 | 28 | // hex string <-> big int 29 | 30 | func HexString2BigInt(str string) (big.Int, error) { 31 | i := big.Int{} 32 | _, err := fmt.Sscan("0x"+strings.TrimPrefix(strings.ToLower(str), "0x"), &i) 33 | 34 | return i, err 35 | } 36 | 37 | func BigIntToHexString(bigInt big.Int) string { 38 | if bigInt.BitLen() == 0 { 39 | return "0x0" 40 | } 41 | 42 | return "0x" + strings.TrimPrefix(fmt.Sprintf("%x", bigInt.Bytes()), "0") 43 | } 44 | 45 | // hex string -> decimal 46 | 47 | func HexString2Decimal(str string, exp int32) decimal.Decimal { 48 | i, _ := HexString2BigInt(str) 49 | return decimal.NewFromBigInt(&i, exp) 50 | } 51 | 52 | func String2Decimal(str string) decimal.Decimal { 53 | d, _ := decimal.NewFromString(str) 54 | return d 55 | } 56 | 57 | // bytes <-> hex string 58 | 59 | func Bytes2HexString(bytes []byte) string { 60 | return "0x" + hex.EncodeToString(bytes) 61 | } 62 | 63 | func HexString2Bytes(str string) []byte { 64 | str = strings.TrimPrefix(strings.ToLower(str), "0x") 65 | 66 | if len(str)%2 == 1 { 67 | str = "0" + str 68 | } 69 | 70 | b, _ := hex.DecodeString(str) 71 | return b 72 | } 73 | 74 | // decimal <-> big int 75 | 76 | func DecimalToBigInt(d decimal.Decimal) *big.Int { 77 | n := new(big.Int) 78 | n, _ = n.SetString(d.Floor().String(), 0) 79 | return n 80 | } 81 | -------------------------------------------------------------------------------- /utils/crypto.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "bytes" 5 | "crypto/ecdsa" 6 | "crypto/elliptic" 7 | "encoding/hex" 8 | "errors" 9 | "fmt" 10 | "github.com/btcsuite/btcd/btcec" 11 | "github.com/ethereum/go-ethereum/core/types" 12 | "golang.org/x/crypto/sha3" 13 | "math/big" 14 | "strings" 15 | ) 16 | 17 | var bitCurve = btcec.S256() 18 | 19 | func Keccak256(data ...[]byte) []byte { 20 | d := sha3.NewLegacyKeccak256() 21 | for _, b := range data { 22 | d.Write(b) 23 | } 24 | return d.Sum(nil) 25 | } 26 | 27 | func NewPrivateKey(privateKeyBytes []byte) (*ecdsa.PrivateKey, error) { 28 | priv := new(ecdsa.PrivateKey) 29 | priv.PublicKey.Curve = bitCurve 30 | if 8*len(privateKeyBytes) != priv.Params().BitSize { 31 | return nil, fmt.Errorf("invalid length, need %d bits", priv.Params().BitSize) 32 | } 33 | priv.D = new(big.Int).SetBytes(privateKeyBytes) 34 | 35 | // The priv.D must < N 36 | if priv.D.Cmp(bitCurve.N) >= 0 { 37 | return nil, fmt.Errorf("invalid private key, >=N") 38 | } 39 | // The priv.D must not be zero or negative. 40 | if priv.D.Sign() <= 0 { 41 | return nil, fmt.Errorf("invalid private key, zero or negative") 42 | } 43 | 44 | priv.PublicKey.X, priv.PublicKey.Y = priv.PublicKey.Curve.ScalarBaseMult(privateKeyBytes) 45 | if priv.PublicKey.X == nil { 46 | return nil, errors.New("invalid private key") 47 | } 48 | return priv, nil 49 | } 50 | 51 | func NewPrivateKeyByHex(privateKeyHex string) (*ecdsa.PrivateKey, error) { 52 | privateKeyBytes := HexString2Bytes(privateKeyHex) 53 | return NewPrivateKey(privateKeyBytes) 54 | } 55 | 56 | func Sign(hash []byte, prv *ecdsa.PrivateKey) ([]byte, error) { 57 | if len(hash) != 32 { 58 | return nil, fmt.Errorf("hash is required to be exactly 32 bytes (%d)", len(hash)) 59 | } 60 | if prv.Curve != btcec.S256() { 61 | return nil, fmt.Errorf("private key curve is not secp256k1") 62 | } 63 | sig, err := btcec.SignCompact(btcec.S256(), (*btcec.PrivateKey)(prv), hash, false) 64 | if err != nil { 65 | return nil, err 66 | } 67 | // Convert to Ethereum signature format with 'recovery id' v at the end. 68 | v := sig[0] - 27 69 | copy(sig, sig[1:]) 70 | sig[64] = v 71 | return sig, nil 72 | } 73 | 74 | func PersonalSign(message []byte, privateKey string) ([]byte, error) { 75 | personalHash := hashPersonalMessage(message) 76 | 77 | pk, err := NewPrivateKeyByHex(privateKey) 78 | 79 | if err != nil { 80 | return nil, err 81 | } 82 | 83 | singBytes, err := Sign(personalHash, pk) 84 | 85 | if err != nil { 86 | return nil, err 87 | } 88 | 89 | return singBytes, nil 90 | } 91 | 92 | func PersonalSignByPrivateKey(message []byte, privateKey *ecdsa.PrivateKey) ([]byte, error) { 93 | personalHash := hashPersonalMessage(message) 94 | singBytes, err := Sign(personalHash, privateKey) 95 | 96 | if err != nil { 97 | return nil, err 98 | } 99 | 100 | return singBytes, nil 101 | } 102 | 103 | func EcRecover(hash, sig []byte) ([]byte, error) { 104 | pub, err := SigToPub(hash, sig) 105 | if err != nil { 106 | return nil, err 107 | } 108 | bytes := (*btcec.PublicKey)(pub).SerializeUncompressed() 109 | return bytes, err 110 | } 111 | 112 | func PersonalEcRecover(data []byte, sig []byte) (string, error) { 113 | if len(sig) != 65 { 114 | return "", fmt.Errorf("signature must be 65 bytes long") 115 | } 116 | if sig[64] >= 27 { 117 | sig[64] -= 27 118 | } 119 | 120 | rpk, err := SigToPub(hashPersonalMessage(data), sig) 121 | 122 | if err != nil { 123 | return "", err 124 | } 125 | 126 | if rpk == nil || rpk.X == nil || rpk.Y == nil { 127 | return "", errors.New("") 128 | } 129 | pubBytes := elliptic.Marshal(bitCurve, rpk.X, rpk.Y) 130 | return strings.TrimPrefix(Bytes2HexString(Keccak256(pubBytes[1:])[12:]), "0x"), nil 131 | } 132 | 133 | func hashPersonalMessage(data []byte) []byte { 134 | msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), data) 135 | return Keccak256([]byte(msg)) 136 | } 137 | 138 | func PubKey2Bytes(pub *ecdsa.PublicKey) []byte { 139 | if pub == nil || pub.X == nil || pub.Y == nil { 140 | return nil 141 | } 142 | return elliptic.Marshal(bitCurve, pub.X, pub.Y) 143 | } 144 | 145 | func PubKey2Address(p ecdsa.PublicKey) string { 146 | pubBytes := PubKey2Bytes(&p) 147 | return Bytes2HexString(Keccak256(pubBytes[1:])[12:]) 148 | } 149 | 150 | func SigToPub(hash, sig []byte) (*ecdsa.PublicKey, error) { 151 | // Convert to btcec input format with 'recovery id' v at the beginning. 152 | btcSig := make([]byte, 65) 153 | btcSig[0] = sig[64] + 27 154 | copy(btcSig[1:], sig) 155 | 156 | pub, _, err := btcec.RecoverCompact(btcec.S256(), btcSig, hash) 157 | return (*ecdsa.PublicKey)(pub), err 158 | } 159 | 160 | func SignTx(pkString string, chain string, tx *types.Transaction) (string, error) { 161 | if len(chain) == 0 { 162 | panic("need chain id") 163 | } 164 | 165 | privateKey, err := NewPrivateKeyByHex(pkString) 166 | if err != nil { 167 | return "", err 168 | } 169 | 170 | var chainID big.Int 171 | chainID.SetString(chain, 0) 172 | signer := types.NewEIP155Signer(&chainID) 173 | 174 | signTx, err := types.SignTx(tx, signer, privateKey) 175 | if err != nil { 176 | panic(err) 177 | } 178 | 179 | buf := new(bytes.Buffer) 180 | err = signTx.EncodeRLP(buf) 181 | signedTxString := "0x" + hex.EncodeToString(buf.Bytes()) 182 | return signedTxString, err 183 | } 184 | -------------------------------------------------------------------------------- /utils/crypto_test.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "encoding/hex" 5 | "github.com/davecgh/go-spew/spew" 6 | "strings" 7 | "testing" 8 | ) 9 | 10 | func TestPersonalSign(t *testing.T) { 11 | orderIdBytes, _ := hex.DecodeString(strings.TrimPrefix("0x3bfd186e2c45fb9fbfc8039906559d9e4181a5f1e8f45b05c6d673d3636bb949", "0x")) 12 | signature, _ := PersonalSign(orderIdBytes, "") 13 | spew.Dump("0x" + hex.EncodeToString(signature)) 14 | } 15 | -------------------------------------------------------------------------------- /utils/error.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import "fmt" 4 | 5 | var ( 6 | AddressNotExist = fmt.Errorf("address not exist") 7 | AssetNotExist = fmt.Errorf("asset not exist") 8 | OrderbookNotComplete = fmt.Errorf("orderbook not complete") 9 | OrderbookDepthNotEnough = fmt.Errorf("orderbook depth not enough") 10 | TransactionFailed = fmt.Errorf("transaction failed") 11 | TransactionNotFound = fmt.Errorf("transaction not found") 12 | AuctionNotExist = fmt.Errorf("auction not exist") 13 | ) 14 | -------------------------------------------------------------------------------- /utils/general.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "github.com/shopspring/decimal" 5 | "strings" 6 | "time" 7 | ) 8 | 9 | func MillisecondTimestamp() int64 { 10 | return time.Now().UnixNano() / int64(time.Millisecond) 11 | } 12 | 13 | func SetDecimal(d decimal.Decimal, decimalNum int) decimal.Decimal { 14 | return d.Truncate(int32(decimalNum)) 15 | } 16 | 17 | func SetPrecision(d decimal.Decimal, precision int) decimal.Decimal { 18 | numString := d.String() 19 | precisionCount := 0 20 | endPosition := 0 21 | for _, c := range numString { 22 | if c != '.' { 23 | precisionCount += 1 24 | } 25 | if precisionCount > precision { 26 | break 27 | } 28 | endPosition += 1 29 | } 30 | validDecimal, _ := decimal.NewFromString(numString[:endPosition]) 31 | return validDecimal 32 | } 33 | 34 | func IsAddressEqual(a string, b string) bool { 35 | a = strings.TrimPrefix(strings.ToLower(a), "0x") 36 | b = strings.TrimPrefix(strings.ToLower(b), "0x") 37 | return a == b 38 | } 39 | -------------------------------------------------------------------------------- /utils/http.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "bytes" 5 | "crypto/tls" 6 | "errors" 7 | "io/ioutil" 8 | "net/http" 9 | "net/url" 10 | "os" 11 | path2 "path" 12 | "strings" 13 | "time" 14 | ) 15 | 16 | type KeyPair struct { 17 | Key string 18 | Value string 19 | } 20 | 21 | var EmptyKeyPairList = []KeyPair{} 22 | var _HttpClient *http.Client 23 | 24 | func init() { 25 | 26 | // e.g PROXY http://115.215.71.12:808 27 | if os.Getenv("PROXY") != "" { 28 | proxy, _ := url.Parse(os.Getenv("PROXY")) 29 | transport := &http.Transport{ 30 | Proxy: http.ProxyURL(proxy), 31 | TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, 32 | MaxIdleConns: 10, 33 | IdleConnTimeout: 15 * time.Second, 34 | } 35 | _HttpClient = &http.Client{ 36 | Transport: transport, 37 | Timeout: 10 * time.Second, 38 | } 39 | } else { 40 | transport := &http.Transport{ 41 | MaxIdleConns: 10, 42 | IdleConnTimeout: 15 * time.Second, 43 | } 44 | _HttpClient = &http.Client{ 45 | Transport: transport, 46 | Timeout: 10 * time.Second, 47 | } 48 | } 49 | } 50 | 51 | func callHttp(methodType string, url string, requestBody string, params []KeyPair, headers []KeyPair) (string, error) { 52 | 53 | var body string 54 | var errorCatch error 55 | var buffer bytes.Buffer 56 | 57 | buffer.WriteString(url) 58 | if len(params) > 0 && !strings.HasSuffix(url, "?") { 59 | buffer.WriteString("?") 60 | } 61 | for i, param := range params { 62 | buffer.WriteString(param.Key) 63 | buffer.WriteString("=") 64 | buffer.WriteString(param.Value) 65 | if i < len(params)-1 { 66 | buffer.WriteString("&") 67 | } 68 | } 69 | 70 | req, err := http.NewRequest(methodType, buffer.String(), bytes.NewBuffer([]byte(requestBody))) 71 | // spew.Dump(req.Response.StatusCode) 72 | if err != nil { 73 | errorCatch = errors.New("build request failed") 74 | } else { 75 | for _, header := range headers { 76 | req.Header.Set(header.Key, header.Value) 77 | } 78 | resp, err := http.DefaultClient.Do(req) 79 | if err != nil { 80 | errorCatch = err 81 | } else { 82 | bodyBytes, err := ioutil.ReadAll(resp.Body) 83 | if err != nil { 84 | errorCatch = errors.New("read resp failed") 85 | } 86 | body = string(bodyBytes) 87 | } 88 | closeBody(resp) 89 | } 90 | return body, errorCatch 91 | } 92 | 93 | func Post(url string, requestBody string, params []KeyPair, headers []KeyPair) (string, error) { 94 | return callHttp("POST", url, requestBody, params, headers) 95 | } 96 | 97 | func Get(url string, requestBody string, params []KeyPair, headers []KeyPair) (string, error) { 98 | return callHttp("GET", url, requestBody, params, headers) 99 | } 100 | 101 | func Delete(url string, requestBody string, params []KeyPair, headers []KeyPair) (string, error) { 102 | return callHttp("DELETE", url, requestBody, params, headers) 103 | } 104 | 105 | func closeBody(resp *http.Response) { 106 | if resp != nil && resp.Body != nil { 107 | _ = resp.Body.Close() 108 | } 109 | } 110 | 111 | func JoinUrlPath(baseUrl string, path string) string { 112 | u, _ := url.Parse(baseUrl) 113 | u.Path = path2.Join(u.Path, path) 114 | return u.String() 115 | } 116 | -------------------------------------------------------------------------------- /utils/sqliteClient.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "database/sql" 5 | _ "github.com/mattn/go-sqlite3" 6 | "github.com/shopspring/decimal" 7 | "github.com/sirupsen/logrus" 8 | "os" 9 | ) 10 | 11 | func InitDb() (err error) { 12 | dbPath := os.Getenv("SQLITEPATH") 13 | if _, err = os.Stat(dbPath); os.IsNotExist(err) { 14 | var db *sql.DB 15 | db, err = sql.Open("sqlite3", dbPath) 16 | if err != nil { 17 | return err 18 | } 19 | defer db.Close() 20 | 21 | sqlStmt := ` 22 | create table auctions ( 23 | txHash TEXT not null primary key, 24 | auctionId INTEGER not null, 25 | debtSymbol TEXT not null, 26 | collateralSymbol TEXT not null, 27 | repayDebt TEXT not null, 28 | receiveCollateral TEXT not null, 29 | ddexOrderId TEXT not null, 30 | ddexSellCollateral TEXT not null, 31 | ddexReceiveDebt TEXT not null, 32 | gasCost TEXT not null 33 | );` 34 | _, err = db.Exec(sqlStmt) 35 | if err == nil { 36 | logrus.Infof("create sqlite table auctions") 37 | } 38 | } 39 | 40 | return 41 | } 42 | 43 | func InsertAuctionRes( 44 | txHash string, 45 | auctionId int, 46 | debtSymbol string, 47 | collateralSymbol string, 48 | repayDebt string, 49 | receiveCollateral string, 50 | ddexOrderId string, 51 | ddexSellCollateral string, 52 | ddexReceiveDebt string, 53 | gasCost string) (err error) { 54 | db, err := sql.Open("sqlite3", os.Getenv("SQLITEPATH")) 55 | defer db.Close() 56 | if err != nil { 57 | return 58 | } 59 | 60 | tx, err := db.Begin() 61 | if err != nil { 62 | return 63 | } 64 | defer tx.Commit() 65 | 66 | stmt, err := tx.Prepare("insert into auctions(txHash, auctionId, debtSymbol, collateralSymbol, repayDebt, receiveCollateral, ddexOrderId, ddexSellCollateral, ddexReceiveDebt, gasCost) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") 67 | if err != nil { 68 | return 69 | } 70 | defer stmt.Close() 71 | 72 | _, err = stmt.Exec(txHash, auctionId, debtSymbol, collateralSymbol, repayDebt, receiveCollateral, ddexOrderId, ddexSellCollateral, ddexReceiveDebt, gasCost) 73 | 74 | return err 75 | } 76 | 77 | func InsertFailedBid( 78 | txHash string, 79 | auctionId int, 80 | debtSymbol string, 81 | collateralSymbol string, 82 | gasCost string, 83 | ) (err error) { 84 | return InsertAuctionRes( 85 | txHash, 86 | auctionId, 87 | debtSymbol, 88 | collateralSymbol, 89 | "0", 90 | "0", 91 | "0x0", 92 | "0", 93 | "0", 94 | gasCost) 95 | } 96 | 97 | // token symbol -> position 98 | func QueryPosition() (position map[string]decimal.Decimal, err error) { 99 | position = map[string]decimal.Decimal{"ETH": decimal.Zero} 100 | db, err := sql.Open("sqlite3", os.Getenv("SQLITEPATH")) 101 | defer db.Close() 102 | if err != nil { 103 | return 104 | } 105 | rows, err := db.Query("select debtSymbol, collateralSymbol, repayDebt, receiveCollateral, ddexSellCollateral, ddexReceiveDebt, gasCost from auctions") 106 | if err != nil { 107 | return 108 | } 109 | defer rows.Close() 110 | for rows.Next() { 111 | var debtSymbol string 112 | var collateralSymbol string 113 | var repayDebt string 114 | var receiveCollateral string 115 | var ddexSellCollateral string 116 | var ddexReceiveDebt string 117 | var gasCost string 118 | err = rows.Scan(&debtSymbol, &collateralSymbol, &repayDebt, &receiveCollateral, &ddexSellCollateral, &ddexReceiveDebt, &gasCost) 119 | if err != nil { 120 | continue 121 | } 122 | if _, ok := position[debtSymbol]; !ok { 123 | position[debtSymbol] = decimal.Zero 124 | } 125 | if _, ok := position[collateralSymbol]; !ok { 126 | position[collateralSymbol] = decimal.Zero 127 | } 128 | position[collateralSymbol] = position[collateralSymbol].Add(String2Decimal(receiveCollateral)) 129 | position[collateralSymbol] = position[collateralSymbol].Sub(String2Decimal(ddexSellCollateral)) 130 | position[debtSymbol] = position[debtSymbol].Sub(String2Decimal(repayDebt)) 131 | position[debtSymbol] = position[debtSymbol].Add(String2Decimal(ddexReceiveDebt)) 132 | position["ETH"] = position["ETH"].Sub(String2Decimal(gasCost)) 133 | } 134 | return 135 | } 136 | -------------------------------------------------------------------------------- /web3/ethrpc.go: -------------------------------------------------------------------------------- 1 | package web3 2 | 3 | // 6b8e9c0e9a8ffd2154cd4470a6ffb4919885e788 4 | 5 | import ( 6 | "auctionBidder/utils" 7 | "bytes" 8 | "encoding/json" 9 | "fmt" 10 | "io/ioutil" 11 | "log" 12 | "math/big" 13 | "net/http" 14 | "os" 15 | ) 16 | 17 | // EthError - ethereum error 18 | type EthError struct { 19 | Code int `json:"code"` 20 | Message string `json:"message"` 21 | } 22 | 23 | func (err EthError) Error() string { 24 | return fmt.Sprintf("Error %d (%s)", err.Code, err.Message) 25 | } 26 | 27 | type ethResponse struct { 28 | ID int `json:"id"` 29 | JSONRPC string `json:"jsonrpc"` 30 | Result json.RawMessage `json:"result"` 31 | Error *EthError `json:"error"` 32 | } 33 | 34 | type ethRequest struct { 35 | ID int `json:"id"` 36 | JSONRPC string `json:"jsonrpc"` 37 | Method string `json:"method"` 38 | Params []interface{} `json:"params"` 39 | } 40 | 41 | // EthRPC - Ethereum Rpc client 42 | type EthRPC struct { 43 | url string 44 | client httpClient 45 | log logger 46 | Debug bool 47 | } 48 | 49 | // New create new Rpc client with given url 50 | func New(url string, options ...func(rpc *EthRPC)) *EthRPC { 51 | rpc := &EthRPC{ 52 | url: url, 53 | client: http.DefaultClient, 54 | log: log.New(os.Stderr, "", log.LstdFlags), 55 | } 56 | for _, option := range options { 57 | option(rpc) 58 | } 59 | 60 | return rpc 61 | } 62 | 63 | // NewEthRPC create new Rpc client with given url 64 | func NewEthRPC(url string, options ...func(rpc *EthRPC)) *EthRPC { 65 | return New(url, options...) 66 | } 67 | 68 | func (rpc *EthRPC) call(method string, target interface{}, params ...interface{}) error { 69 | result, err := rpc.Call(method, params...) 70 | if err != nil { 71 | return err 72 | } 73 | 74 | if target == nil { 75 | return nil 76 | } 77 | 78 | return json.Unmarshal(result, target) 79 | } 80 | 81 | // URL returns client url 82 | func (rpc *EthRPC) URL() string { 83 | return rpc.url 84 | } 85 | 86 | // Call returns raw response of method call 87 | func (rpc *EthRPC) Call(method string, params ...interface{}) (json.RawMessage, error) { 88 | request := ethRequest{ 89 | ID: 1, 90 | JSONRPC: "2.0", 91 | Method: method, 92 | Params: params, 93 | } 94 | 95 | body, err := json.Marshal(request) 96 | if err != nil { 97 | return nil, err 98 | } 99 | 100 | response, err := rpc.client.Post(rpc.url, "application/json", bytes.NewBuffer(body)) 101 | if response != nil { 102 | defer response.Body.Close() 103 | } 104 | if err != nil { 105 | return nil, err 106 | } 107 | 108 | data, err := ioutil.ReadAll(response.Body) 109 | if err != nil { 110 | return nil, err 111 | } 112 | 113 | if rpc.Debug { 114 | rpc.log.Println(fmt.Sprintf("%s\nRequest: %s\nResponse: %s\n", method, body, data)) 115 | } 116 | 117 | resp := new(ethResponse) 118 | if err := json.Unmarshal(data, resp); err != nil { 119 | return nil, err 120 | } 121 | 122 | if resp.Error != nil { 123 | return nil, *resp.Error 124 | } 125 | 126 | return resp.Result, nil 127 | 128 | } 129 | 130 | // RawCall returns raw response of method call (Deprecated) 131 | func (rpc *EthRPC) RawCall(method string, params ...interface{}) (json.RawMessage, error) { 132 | return rpc.Call(method, params...) 133 | } 134 | 135 | // Web3ClientVersion returns the current client version. 136 | func (rpc *EthRPC) Web3ClientVersion() (string, error) { 137 | var clientVersion string 138 | 139 | err := rpc.call("web3_clientVersion", &clientVersion) 140 | return clientVersion, err 141 | } 142 | 143 | // Web3Sha3 returns Keccak-256 (not the standardized SHA3-256) of the given data. 144 | func (rpc *EthRPC) Web3Sha3(data []byte) (string, error) { 145 | var hash string 146 | 147 | err := rpc.call("web3_sha3", &hash, fmt.Sprintf("0x%x", data)) 148 | return hash, err 149 | } 150 | 151 | // NetVersion returns the current network protocol version. 152 | func (rpc *EthRPC) NetVersion() (string, error) { 153 | var version string 154 | 155 | err := rpc.call("net_version", &version) 156 | return version, err 157 | } 158 | 159 | // NetListening returns true if client is actively listening for network connections. 160 | func (rpc *EthRPC) NetListening() (bool, error) { 161 | var listening bool 162 | 163 | err := rpc.call("net_listening", &listening) 164 | return listening, err 165 | } 166 | 167 | // NetPeerCount returns number of peers currently connected to the client. 168 | func (rpc *EthRPC) NetPeerCount() (int, error) { 169 | var response string 170 | if err := rpc.call("net_peerCount", &response); err != nil { 171 | return 0, err 172 | } 173 | 174 | return utils.HexString2Int(response) 175 | } 176 | 177 | // EthProtocolVersion returns the current ethereum protocol version. 178 | func (rpc *EthRPC) EthProtocolVersion() (string, error) { 179 | var protocolVersion string 180 | 181 | err := rpc.call("eth_protocolVersion", &protocolVersion) 182 | return protocolVersion, err 183 | } 184 | 185 | // EthSyncing returns an object with data about the sync status or false. 186 | func (rpc *EthRPC) EthSyncing() (*Syncing, error) { 187 | result, err := rpc.RawCall("eth_syncing") 188 | if err != nil { 189 | return nil, err 190 | } 191 | syncing := new(Syncing) 192 | if bytes.Equal(result, []byte("false")) { 193 | return syncing, nil 194 | } 195 | err = json.Unmarshal(result, syncing) 196 | return syncing, err 197 | } 198 | 199 | // EthCoinbase returns the client coinbase address 200 | func (rpc *EthRPC) EthCoinbase() (string, error) { 201 | var address string 202 | 203 | err := rpc.call("eth_coinbase", &address) 204 | return address, err 205 | } 206 | 207 | // EthMining returns true if client is actively mining new blocks. 208 | func (rpc *EthRPC) EthMining() (bool, error) { 209 | var mining bool 210 | 211 | err := rpc.call("eth_mining", &mining) 212 | return mining, err 213 | } 214 | 215 | // EthHashrate returns the number of hashes per second that the node is mining with. 216 | func (rpc *EthRPC) EthHashrate() (int, error) { 217 | var response string 218 | 219 | if err := rpc.call("eth_hashrate", &response); err != nil { 220 | return 0, err 221 | } 222 | 223 | return utils.HexString2Int(response) 224 | } 225 | 226 | // EthGasPrice returns the current price per gas in wei. 227 | func (rpc *EthRPC) EthGasPrice() (big.Int, error) { 228 | var response string 229 | if err := rpc.call("eth_gasPrice", &response); err != nil { 230 | return big.Int{}, err 231 | } 232 | 233 | return utils.HexString2BigInt(response) 234 | } 235 | 236 | // EthAccounts returns a list of addresses owned by client. 237 | func (rpc *EthRPC) EthAccounts() ([]string, error) { 238 | accounts := []string{} 239 | 240 | err := rpc.call("eth_accounts", &accounts) 241 | return accounts, err 242 | } 243 | 244 | // EthBlockNumber returns the number of most recent block. 245 | func (rpc *EthRPC) EthBlockNumber() (int, error) { 246 | var response string 247 | if err := rpc.call("eth_blockNumber", &response); err != nil { 248 | return 0, err 249 | } 250 | 251 | return utils.HexString2Int(response) 252 | } 253 | 254 | // EthGetBalance returns the balance of the account of given address in wei. 255 | func (rpc *EthRPC) EthGetBalance(address, block string) (big.Int, error) { 256 | var response string 257 | if err := rpc.call("eth_getBalance", &response, address, block); err != nil { 258 | return big.Int{}, err 259 | } 260 | 261 | return utils.HexString2BigInt(response) 262 | } 263 | 264 | // EthGetStorageAt returns the value from a storage position at a given address. 265 | func (rpc *EthRPC) EthGetStorageAt(data string, position int, tag string) (string, error) { 266 | var result string 267 | 268 | err := rpc.call("eth_getStorageAt", &result, data, utils.Int2HexString(position), tag) 269 | return result, err 270 | } 271 | 272 | // EthGetTransactionCount returns the number of transactions sent from an address. 273 | func (rpc *EthRPC) EthGetTransactionCount(address, block string) (int, error) { 274 | var response string 275 | 276 | if err := rpc.call("eth_getTransactionCount", &response, address, block); err != nil { 277 | return 0, err 278 | } 279 | 280 | return utils.HexString2Int(response) 281 | } 282 | 283 | // EthGetBlockTransactionCountByHash returns the number of transactions in a block from a block matching the given block hash. 284 | func (rpc *EthRPC) EthGetBlockTransactionCountByHash(hash string) (int, error) { 285 | var response string 286 | 287 | if err := rpc.call("eth_getBlockTransactionCountByHash", &response, hash); err != nil { 288 | return 0, err 289 | } 290 | 291 | return utils.HexString2Int(response) 292 | } 293 | 294 | // EthGetBlockTransactionCountByNumber returns the number of transactions in a block from a block matching the given block 295 | func (rpc *EthRPC) EthGetBlockTransactionCountByNumber(number int) (int, error) { 296 | var response string 297 | 298 | if err := rpc.call("eth_getBlockTransactionCountByNumber", &response, utils.Int2HexString(number)); err != nil { 299 | return 0, err 300 | } 301 | 302 | return utils.HexString2Int(response) 303 | } 304 | 305 | // EthGetUncleCountByBlockHash returns the number of uncles in a block from a block matching the given block hash. 306 | func (rpc *EthRPC) EthGetUncleCountByBlockHash(hash string) (int, error) { 307 | var response string 308 | 309 | if err := rpc.call("eth_getUncleCountByBlockHash", &response, hash); err != nil { 310 | return 0, err 311 | } 312 | 313 | return utils.HexString2Int(response) 314 | } 315 | 316 | // EthGetUncleCountByBlockNumber returns the number of uncles in a block from a block matching the given block number. 317 | func (rpc *EthRPC) EthGetUncleCountByBlockNumber(number int) (int, error) { 318 | var response string 319 | 320 | if err := rpc.call("eth_getUncleCountByBlockNumber", &response, utils.Int2HexString(number)); err != nil { 321 | return 0, err 322 | } 323 | 324 | return utils.HexString2Int(response) 325 | } 326 | 327 | // EthGetCode returns code at a given address. 328 | func (rpc *EthRPC) EthGetCode(address, block string) (string, error) { 329 | var code string 330 | 331 | err := rpc.call("eth_getCode", &code, address, block) 332 | return code, err 333 | } 334 | 335 | // EthSign signs data with a given address. 336 | // Calculates an Ethereum specific signature with: sign(keccak256("\x19Ethereum Signed Message:\n" + len(message) + message))) 337 | func (rpc *EthRPC) EthSign(address, data string) (string, error) { 338 | var signature string 339 | 340 | err := rpc.call("eth_sign", &signature, address, data) 341 | return signature, err 342 | } 343 | 344 | // EthSendTransaction creates new message call transaction or a contract creation, if the data field contains code. 345 | func (rpc *EthRPC) EthSendTransaction(transaction T) (string, error) { 346 | var hash string 347 | 348 | err := rpc.call("eth_sendTransaction", &hash, transaction) 349 | return hash, err 350 | } 351 | 352 | // EthSendRawTransaction creates new message call transaction or a contract creation for signed transactions. 353 | func (rpc *EthRPC) EthSendRawTransaction(data string) (string, error) { 354 | var hash string 355 | 356 | err := rpc.call("eth_sendRawTransaction", &hash, data) 357 | return hash, err 358 | } 359 | 360 | // EthCall executes a new message call immediately without creating a transaction on the block chain. 361 | func (rpc *EthRPC) EthCall(transaction T, tag string) (string, error) { 362 | var data string 363 | 364 | err := rpc.call("eth_call", &data, transaction, tag) 365 | return data, err 366 | } 367 | 368 | // EthEstimateGas makes a call or transaction, which won't be added to the blockchain and returns the used gas, which can be used for estimating the used gas. 369 | func (rpc *EthRPC) EthEstimateGas(transaction T) (int, error) { 370 | var response string 371 | 372 | err := rpc.call("eth_estimateGas", &response, transaction) 373 | if err != nil { 374 | return 0, err 375 | } 376 | 377 | return utils.HexString2Int(response) 378 | } 379 | 380 | func (rpc *EthRPC) getBlock(method string, withTransactions bool, params ...interface{}) (*Block, error) { 381 | result, err := rpc.RawCall(method, params...) 382 | if err != nil { 383 | return nil, err 384 | } 385 | if bytes.Equal(result, []byte("null")) { 386 | return nil, nil 387 | } 388 | 389 | var response proxyBlock 390 | if withTransactions { 391 | response = new(proxyBlockWithTransactions) 392 | } else { 393 | response = new(proxyBlockWithoutTransactions) 394 | } 395 | 396 | err = json.Unmarshal(result, response) 397 | if err != nil { 398 | return nil, err 399 | } 400 | 401 | block := response.toBlock() 402 | return &block, nil 403 | } 404 | 405 | // EthGetBlockByHash returns information about a block by hash. 406 | func (rpc *EthRPC) EthGetBlockByHash(hash string, withTransactions bool) (*Block, error) { 407 | return rpc.getBlock("eth_getBlockByHash", withTransactions, hash, withTransactions) 408 | } 409 | 410 | // EthGetBlockByNumber returns information about a block by block number. 411 | func (rpc *EthRPC) EthGetBlockByNumber(number int, withTransactions bool) (*Block, error) { 412 | return rpc.getBlock("eth_getBlockByNumber", withTransactions, utils.Int2HexString(number), withTransactions) 413 | } 414 | 415 | func (rpc *EthRPC) getTransaction(method string, params ...interface{}) (*Transaction, error) { 416 | transaction := new(Transaction) 417 | 418 | err := rpc.call(method, transaction, params...) 419 | return transaction, err 420 | } 421 | 422 | // EthGetTransactionByHash returns the information about a transaction requested by transaction hash. 423 | func (rpc *EthRPC) EthGetTransactionByHash(hash string) (*Transaction, error) { 424 | return rpc.getTransaction("eth_getTransactionByHash", hash) 425 | } 426 | 427 | // EthGetTransactionByBlockHashAndIndex returns information about a transaction by block hash and transaction index position. 428 | func (rpc *EthRPC) EthGetTransactionByBlockHashAndIndex(blockHash string, transactionIndex int) (*Transaction, error) { 429 | return rpc.getTransaction("eth_getTransactionByBlockHashAndIndex", blockHash, utils.Int2HexString(transactionIndex)) 430 | } 431 | 432 | // EthGetTransactionByBlockNumberAndIndex returns information about a transaction by block number and transaction index position. 433 | func (rpc *EthRPC) EthGetTransactionByBlockNumberAndIndex(blockNumber, transactionIndex int) (*Transaction, error) { 434 | return rpc.getTransaction("eth_getTransactionByBlockNumberAndIndex", utils.Int2HexString(blockNumber), utils.Int2HexString(transactionIndex)) 435 | } 436 | 437 | // EthGetTransactionReceipt returns the receipt of a transaction by transaction hash. 438 | // Note That the receipt is not available for pending transactions. 439 | func (rpc *EthRPC) EthGetTransactionReceipt(hash string) (*TransactionReceipt, error) { 440 | transactionReceipt := new(TransactionReceipt) 441 | 442 | err := rpc.call("eth_getTransactionReceipt", transactionReceipt, hash) 443 | if err != nil { 444 | return nil, err 445 | } 446 | 447 | return transactionReceipt, nil 448 | } 449 | 450 | // EthGetCompilers returns a list of available compilers in the client. 451 | func (rpc *EthRPC) EthGetCompilers() ([]string, error) { 452 | compilers := []string{} 453 | 454 | err := rpc.call("eth_getCompilers", &compilers) 455 | return compilers, err 456 | } 457 | 458 | // EthNewFilter creates a new filter object. 459 | func (rpc *EthRPC) EthNewFilter(params FilterParams) (string, error) { 460 | var filterID string 461 | err := rpc.call("eth_newFilter", &filterID, params) 462 | return filterID, err 463 | } 464 | 465 | // EthNewBlockFilter creates a filter in the node, to notify when a new block arrives. 466 | // To check if the state has changed, call EthGetFilterChanges. 467 | func (rpc *EthRPC) EthNewBlockFilter() (string, error) { 468 | var filterID string 469 | err := rpc.call("eth_newBlockFilter", &filterID) 470 | return filterID, err 471 | } 472 | 473 | // EthNewPendingTransactionFilter creates a filter in the node, to notify when new pending transactions arrive. 474 | // To check if the state has changed, call EthGetFilterChanges. 475 | func (rpc *EthRPC) EthNewPendingTransactionFilter() (string, error) { 476 | var filterID string 477 | err := rpc.call("eth_newPendingTransactionFilter", &filterID) 478 | return filterID, err 479 | } 480 | 481 | // EthUninstallFilter uninstalls a filter with given id. 482 | func (rpc *EthRPC) EthUninstallFilter(filterID string) (bool, error) { 483 | var res bool 484 | err := rpc.call("eth_uninstallFilter", &res, filterID) 485 | return res, err 486 | } 487 | 488 | // EthGetFilterChanges polling method for a filter, which returns an array of logs which occurred since last poll. 489 | func (rpc *EthRPC) EthGetFilterChanges(filterID string) ([]Log, error) { 490 | var logs = []Log{} 491 | err := rpc.call("eth_getFilterChanges", &logs, filterID) 492 | return logs, err 493 | } 494 | 495 | // EthGetFilterLogs returns an array of all logs matching filter with given id. 496 | func (rpc *EthRPC) EthGetFilterLogs(filterID string) ([]Log, error) { 497 | var logs = []Log{} 498 | err := rpc.call("eth_getFilterLogs", &logs, filterID) 499 | return logs, err 500 | } 501 | 502 | // EthGetLogs returns an array of all logs matching a given filter object. 503 | func (rpc *EthRPC) EthGetLogs(params FilterParams) ([]Log, error) { 504 | var logs = []Log{} 505 | err := rpc.call("eth_getLogs", &logs, params) 506 | return logs, err 507 | } 508 | 509 | // Eth1 returns 1 ethereum value (10^18 wei) 510 | func (rpc *EthRPC) Eth1() *big.Int { 511 | return Eth1() 512 | } 513 | 514 | // Eth1 returns 1 ethereum value (10^18 wei) 515 | func Eth1() *big.Int { 516 | return big.NewInt(1000000000000000000) 517 | } 518 | -------------------------------------------------------------------------------- /web3/interface.go: -------------------------------------------------------------------------------- 1 | package web3 2 | 3 | import ( 4 | "math/big" 5 | ) 6 | 7 | type EthereumAPI interface { 8 | Web3ClientVersion() (string, error) 9 | Web3Sha3(data []byte) (string, error) 10 | NetVersion() (string, error) 11 | NetListening() (bool, error) 12 | NetPeerCount() (int, error) 13 | EthProtocolVersion() (string, error) 14 | EthSyncing() (*Syncing, error) 15 | EthCoinbase() (string, error) 16 | EthMining() (bool, error) 17 | EthHashrate() (int, error) 18 | EthGasPrice() (big.Int, error) 19 | EthAccounts() ([]string, error) 20 | EthBlockNumber() (int, error) 21 | EthGetBalance(address, block string) (big.Int, error) 22 | EthGetStorageAt(data string, position int, tag string) (string, error) 23 | EthGetTransactionCount(address, block string) (int, error) 24 | EthGetBlockTransactionCountByHash(hash string) (int, error) 25 | EthGetBlockTransactionCountByNumber(number int) (int, error) 26 | EthGetUncleCountByBlockHash(hash string) (int, error) 27 | EthGetUncleCountByBlockNumber(number int) (int, error) 28 | EthGetCode(address, block string) (string, error) 29 | EthSign(address, data string) (string, error) 30 | EthSendTransaction(transaction T) (string, error) 31 | EthSendRawTransaction(data string) (string, error) 32 | EthCall(transaction T, tag string) (string, error) 33 | EthEstimateGas(transaction T) (int, error) 34 | EthGetBlockByHash(hash string, withTransactions bool) (*Block, error) 35 | EthGetBlockByNumber(number int, withTransactions bool) (*Block, error) 36 | EthGetTransactionByHash(hash string) (*Transaction, error) 37 | EthGetTransactionByBlockHashAndIndex(blockHash string, transactionIndex int) (*Transaction, error) 38 | EthGetTransactionByBlockNumberAndIndex(blockNumber, transactionIndex int) (*Transaction, error) 39 | EthGetTransactionReceipt(hash string) (*TransactionReceipt, error) 40 | EthGetCompilers() ([]string, error) 41 | EthNewFilter(params FilterParams) (string, error) 42 | EthNewBlockFilter() (string, error) 43 | EthNewPendingTransactionFilter() (string, error) 44 | EthUninstallFilter(filterID string) (bool, error) 45 | EthGetFilterChanges(filterID string) ([]Log, error) 46 | EthGetFilterLogs(filterID string) ([]Log, error) 47 | EthGetLogs(params FilterParams) ([]Log, error) 48 | } 49 | 50 | var _ EthereumAPI = (*EthRPC)(nil) 51 | -------------------------------------------------------------------------------- /web3/options.go: -------------------------------------------------------------------------------- 1 | package web3 2 | 3 | import ( 4 | "io" 5 | "net/http" 6 | ) 7 | 8 | type httpClient interface { 9 | Post(url string, contentType string, body io.Reader) (*http.Response, error) 10 | } 11 | 12 | type logger interface { 13 | Println(v ...interface{}) 14 | } 15 | 16 | // WithHttpClient set custom http client 17 | func WithHttpClient(client httpClient) func(rpc *EthRPC) { 18 | return func(rpc *EthRPC) { 19 | rpc.client = client 20 | } 21 | } 22 | 23 | // WithLogger set custom logger 24 | func WithLogger(l logger) func(rpc *EthRPC) { 25 | return func(rpc *EthRPC) { 26 | rpc.log = l 27 | } 28 | } 29 | 30 | // WithDebug set debug flag 31 | func WithDebug(enabled bool) func(rpc *EthRPC) { 32 | return func(rpc *EthRPC) { 33 | rpc.Debug = enabled 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /web3/types.go: -------------------------------------------------------------------------------- 1 | package web3 2 | 3 | import ( 4 | "auctionBidder/utils" 5 | "bytes" 6 | "encoding/json" 7 | "math/big" 8 | "unsafe" 9 | ) 10 | 11 | // Syncing - object with syncing data info 12 | type Syncing struct { 13 | IsSyncing bool 14 | StartingBlock int 15 | CurrentBlock int 16 | HighestBlock int 17 | } 18 | 19 | // UnmarshalJSON implements the json.Unmarshaler interface. 20 | func (s *Syncing) UnmarshalJSON(data []byte) error { 21 | proxy := new(proxySyncing) 22 | if err := json.Unmarshal(data, proxy); err != nil { 23 | return err 24 | } 25 | 26 | proxy.IsSyncing = true 27 | *s = *(*Syncing)(unsafe.Pointer(proxy)) 28 | 29 | return nil 30 | } 31 | 32 | // T - input transaction object 33 | type T struct { 34 | From string 35 | To string 36 | Gas int 37 | GasPrice *big.Int 38 | Value *big.Int 39 | Data string 40 | Nonce int 41 | } 42 | type proxyT struct { 43 | From string 44 | To string 45 | Gas int 46 | GasPrice *hexBig 47 | Value *hexBig 48 | Data string 49 | Nonce int 50 | } 51 | 52 | // MarshalJSON implements the json.Unmarshaler interface. 53 | func (t T) MarshalJSON() ([]byte, error) { 54 | params := map[string]interface{}{ 55 | "from": t.From, 56 | } 57 | if t.To != "" { 58 | params["to"] = t.To 59 | } 60 | if t.Gas > 0 { 61 | params["gas"] = utils.Int2HexString(t.Gas) 62 | } 63 | if t.GasPrice != nil { 64 | params["GasPrice"] = utils.BigIntToHexString(*t.GasPrice) 65 | } 66 | if t.Value != nil { 67 | params["value"] = utils.BigIntToHexString(*t.Value) 68 | } 69 | if t.Data != "" { 70 | params["data"] = t.Data 71 | } 72 | if t.Nonce > 0 { 73 | params["Nonce"] = utils.Int2HexString(t.Nonce) 74 | } 75 | 76 | return json.Marshal(params) 77 | } 78 | func (t *T) UnmarshalJSON(bytes []byte) error { 79 | proxy := new(proxyT) 80 | if err := json.Unmarshal(bytes, proxy); err != nil { 81 | return err 82 | } 83 | 84 | *t = *(*T)(unsafe.Pointer(proxy)) 85 | 86 | return nil 87 | } 88 | 89 | // Transaction - transaction object 90 | type Transaction struct { 91 | Hash string 92 | Nonce int 93 | BlockHash string 94 | BlockNumber *int 95 | TransactionIndex *int 96 | From string 97 | To string 98 | Value big.Int 99 | Gas int 100 | GasPrice big.Int 101 | Input string 102 | } 103 | 104 | // UnmarshalJSON implements the json.Unmarshaler interface. 105 | func (t *Transaction) UnmarshalJSON(data []byte) error { 106 | proxy := new(proxyTransaction) 107 | if err := json.Unmarshal(data, proxy); err != nil { 108 | return err 109 | } 110 | 111 | *t = *(*Transaction)(unsafe.Pointer(proxy)) 112 | 113 | return nil 114 | } 115 | 116 | // Log - log object 117 | type Log struct { 118 | Removed bool 119 | LogIndex int 120 | TransactionIndex int 121 | TransactionHash string 122 | BlockNumber int 123 | BlockHash string 124 | Address string 125 | Data string 126 | Topics []string 127 | } 128 | 129 | // UnmarshalJSON implements the json.Unmarshaler interface. 130 | func (log *Log) UnmarshalJSON(data []byte) error { 131 | proxy := new(proxyLog) 132 | if err := json.Unmarshal(data, proxy); err != nil { 133 | return err 134 | } 135 | 136 | *log = *(*Log)(unsafe.Pointer(proxy)) 137 | 138 | return nil 139 | } 140 | 141 | // FilterParams - Filter parameters object 142 | type FilterParams struct { 143 | FromBlock string `json:"fromBlock,omitempty"` 144 | ToBlock string `json:"toBlock,omitempty"` 145 | Address []string `json:"address,omitempty"` 146 | Topics [][]string `json:"topics,omitempty"` 147 | } 148 | 149 | // TransactionReceipt - transaction receipt object 150 | type TransactionReceipt struct { 151 | TransactionHash string 152 | TransactionIndex int 153 | BlockHash string 154 | BlockNumber int 155 | CumulativeGasUsed int 156 | GasUsed int 157 | ContractAddress string 158 | Logs []Log 159 | LogsBloom string 160 | Root string 161 | Status string 162 | } 163 | 164 | // UnmarshalJSON implements the json.Unmarshaler interface. 165 | func (t *TransactionReceipt) UnmarshalJSON(data []byte) error { 166 | proxy := new(proxyTransactionReceipt) 167 | if err := json.Unmarshal(data, proxy); err != nil { 168 | return err 169 | } 170 | 171 | *t = *(*TransactionReceipt)(unsafe.Pointer(proxy)) 172 | 173 | return nil 174 | } 175 | 176 | // Block - block object 177 | type Block struct { 178 | Number int 179 | Hash string 180 | ParentHash string 181 | Nonce string 182 | Sha3Uncles string 183 | LogsBloom string 184 | TransactionsRoot string 185 | StateRoot string 186 | Miner string 187 | Difficulty big.Int 188 | TotalDifficulty big.Int 189 | ExtraData string 190 | Size int 191 | GasLimit int 192 | GasUsed int 193 | Timestamp int 194 | Uncles []string 195 | Transactions []Transaction 196 | } 197 | 198 | type proxySyncing struct { 199 | IsSyncing bool `json:"-"` 200 | StartingBlock hexInt `json:"startingBlock"` 201 | CurrentBlock hexInt `json:"currentBlock"` 202 | HighestBlock hexInt `json:"highestBlock"` 203 | } 204 | 205 | type proxyTransaction struct { 206 | Hash string `json:"hash"` 207 | Nonce hexInt `json:"Nonce"` 208 | BlockHash string `json:"blockHash"` 209 | BlockNumber *hexInt `json:"blockNumber"` 210 | TransactionIndex *hexInt `json:"transactionIndex"` 211 | From string `json:"from"` 212 | To string `json:"to"` 213 | Value hexBig `json:"value"` 214 | Gas hexInt `json:"gas"` 215 | GasPrice hexBig `json:"GasPrice"` 216 | Input string `json:"input"` 217 | } 218 | 219 | type proxyLog struct { 220 | Removed bool `json:"removed"` 221 | LogIndex hexInt `json:"logIndex"` 222 | TransactionIndex hexInt `json:"transactionIndex"` 223 | TransactionHash string `json:"transactionHash"` 224 | BlockNumber hexInt `json:"blockNumber"` 225 | BlockHash string `json:"blockHash"` 226 | Address string `json:"address"` 227 | Data string `json:"data"` 228 | Topics []string `json:"topics"` 229 | } 230 | 231 | type proxyTransactionReceipt struct { 232 | TransactionHash string `json:"transactionHash"` 233 | TransactionIndex hexInt `json:"transactionIndex"` 234 | BlockHash string `json:"blockHash"` 235 | BlockNumber hexInt `json:"blockNumber"` 236 | CumulativeGasUsed hexInt `json:"cumulativeGasUsed"` 237 | GasUsed hexInt `json:"gasUsed"` 238 | ContractAddress string `json:"contractAddress,omitempty"` 239 | Logs []Log `json:"logs"` 240 | LogsBloom string `json:"logsBloom"` 241 | Root string `json:"root"` 242 | Status string `json:"status,omitempty"` 243 | } 244 | 245 | type hexInt int 246 | 247 | func (i *hexInt) UnmarshalJSON(data []byte) error { 248 | result, err := utils.HexString2Int(string(bytes.Trim(data, `"`))) 249 | *i = hexInt(result) 250 | 251 | return err 252 | } 253 | 254 | type hexBig big.Int 255 | 256 | func (i *hexBig) UnmarshalJSON(data []byte) error { 257 | result, err := utils.HexString2BigInt(string(bytes.Trim(data, `"`))) 258 | *i = hexBig(result) 259 | 260 | return err 261 | } 262 | 263 | type proxyBlock interface { 264 | toBlock() Block 265 | } 266 | 267 | type proxyBlockWithTransactions struct { 268 | Number hexInt `json:"number"` 269 | Hash string `json:"hash"` 270 | ParentHash string `json:"parentHash"` 271 | Nonce string `json:"Nonce"` 272 | Sha3Uncles string `json:"sha3Uncles"` 273 | LogsBloom string `json:"logsBloom"` 274 | TransactionsRoot string `json:"transactionsRoot"` 275 | StateRoot string `json:"stateRoot"` 276 | Miner string `json:"miner"` 277 | Difficulty hexBig `json:"difficulty"` 278 | TotalDifficulty hexBig `json:"totalDifficulty"` 279 | ExtraData string `json:"extraData"` 280 | Size hexInt `json:"size"` 281 | GasLimit hexInt `json:"GasLimit"` 282 | GasUsed hexInt `json:"gasUsed"` 283 | Timestamp hexInt `json:"timestamp"` 284 | Uncles []string `json:"uncles"` 285 | Transactions []proxyTransaction `json:"transactions"` 286 | } 287 | 288 | func (proxy *proxyBlockWithTransactions) toBlock() Block { 289 | return *(*Block)(unsafe.Pointer(proxy)) 290 | } 291 | 292 | type proxyBlockWithoutTransactions struct { 293 | Number hexInt `json:"number"` 294 | Hash string `json:"hash"` 295 | ParentHash string `json:"parentHash"` 296 | Nonce string `json:"Nonce"` 297 | Sha3Uncles string `json:"sha3Uncles"` 298 | LogsBloom string `json:"logsBloom"` 299 | TransactionsRoot string `json:"transactionsRoot"` 300 | StateRoot string `json:"stateRoot"` 301 | Miner string `json:"miner"` 302 | Difficulty hexBig `json:"difficulty"` 303 | TotalDifficulty hexBig `json:"totalDifficulty"` 304 | ExtraData string `json:"extraData"` 305 | Size hexInt `json:"size"` 306 | GasLimit hexInt `json:"GasLimit"` 307 | GasUsed hexInt `json:"gasUsed"` 308 | Timestamp hexInt `json:"timestamp"` 309 | Uncles []string `json:"uncles"` 310 | Transactions []string `json:"transactions"` 311 | } 312 | 313 | func (proxy *proxyBlockWithoutTransactions) toBlock() Block { 314 | block := Block{ 315 | Number: int(proxy.Number), 316 | Hash: proxy.Hash, 317 | ParentHash: proxy.ParentHash, 318 | Nonce: proxy.Nonce, 319 | Sha3Uncles: proxy.Sha3Uncles, 320 | LogsBloom: proxy.LogsBloom, 321 | TransactionsRoot: proxy.TransactionsRoot, 322 | StateRoot: proxy.StateRoot, 323 | Miner: proxy.Miner, 324 | Difficulty: big.Int(proxy.Difficulty), 325 | TotalDifficulty: big.Int(proxy.TotalDifficulty), 326 | ExtraData: proxy.ExtraData, 327 | Size: int(proxy.Size), 328 | GasLimit: int(proxy.GasLimit), 329 | GasUsed: int(proxy.GasUsed), 330 | Timestamp: int(proxy.Timestamp), 331 | Uncles: proxy.Uncles, 332 | } 333 | 334 | block.Transactions = make([]Transaction, len(proxy.Transactions)) 335 | for i := range proxy.Transactions { 336 | block.Transactions[i] = Transaction{ 337 | Hash: proxy.Transactions[i], 338 | } 339 | } 340 | 341 | return block 342 | } 343 | -------------------------------------------------------------------------------- /web3/web3.go: -------------------------------------------------------------------------------- 1 | package web3 2 | 3 | import ( 4 | "auctionBidder/utils" 5 | "encoding/json" 6 | "fmt" 7 | "github.com/ethereum/go-ethereum/accounts/abi" 8 | "github.com/ethereum/go-ethereum/common" 9 | "github.com/ethereum/go-ethereum/core/types" 10 | "math/big" 11 | "os" 12 | "strings" 13 | ) 14 | 15 | type Web3 struct { 16 | Rpc *EthRPC 17 | privateKeyMap map[string]string // address -> privateKey 18 | } 19 | 20 | func NewWeb3(ethereumNodeUrl string) *Web3 { 21 | rpc := NewEthRPC(ethereumNodeUrl) 22 | 23 | return &Web3{rpc, map[string]string{}} 24 | } 25 | 26 | func (w *Web3) AddPrivateKey(privateKey string) (newAddress string, err error) { 27 | pk, err := utils.NewPrivateKeyByHex(privateKey) 28 | if err != nil { 29 | return 30 | } 31 | newAddress = utils.PubKey2Address(pk.PublicKey) 32 | w.privateKeyMap[strings.ToLower(newAddress)] = strings.ToLower(privateKey) 33 | 34 | return 35 | } 36 | 37 | func (w *Web3) NewBlockChannel() chan int64 { 38 | c := make(chan int64) 39 | go func() { 40 | blockNum := 0 41 | for true { 42 | newBlockNum, err := w.Rpc.EthBlockNumber() 43 | if err == nil { 44 | if newBlockNum > blockNum { 45 | c <- int64(newBlockNum) 46 | blockNum = newBlockNum 47 | } 48 | } 49 | } 50 | }() 51 | 52 | return c 53 | } 54 | 55 | type SendTxParams struct { 56 | FromAddress string 57 | GasLimit *big.Int 58 | GasPrice *big.Int 59 | Nonce uint64 60 | } 61 | 62 | type Contract struct { 63 | web3 *Web3 64 | abi *abi.ABI 65 | address *common.Address 66 | } 67 | 68 | func (w *Web3) NewContract(abiStr string, address string) (contract *Contract, err error) { 69 | abi, err := abi.JSON(strings.NewReader(abiStr)) 70 | if err != nil { 71 | return 72 | } 73 | 74 | commonAddress := common.HexToAddress(address) 75 | contract = &Contract{ 76 | w, &abi, &commonAddress, 77 | } 78 | 79 | return 80 | } 81 | 82 | func (c *Contract) Call(functionName string, args ...interface{}) (resp string, err error) { 83 | var dataByte []byte 84 | if args != nil { 85 | dataByte, err = c.abi.Pack(functionName, args...) 86 | } else { 87 | dataByte = c.abi.Methods[functionName].ID() 88 | } 89 | if err != nil { 90 | return 91 | } 92 | 93 | return c.web3.Rpc.EthCall(T{ 94 | To: c.address.String(), 95 | From: "0x0000000000000000000000000000000000000000", 96 | Data: fmt.Sprintf("0x%x", dataByte)}, 97 | "latest", 98 | ) 99 | } 100 | 101 | func (c *Contract) Send(params *SendTxParams, amount *big.Int, functionName string, args ...interface{}) (resp string, err error) { 102 | if _, ok := c.web3.privateKeyMap[strings.ToLower(params.FromAddress)]; !ok { 103 | err = utils.AddressNotExist 104 | return 105 | } 106 | 107 | data, err := c.abi.Pack(functionName, args...) 108 | if err != nil { 109 | return 110 | } 111 | 112 | tx := types.NewTransaction( 113 | params.Nonce, 114 | *c.address, 115 | amount, 116 | params.GasLimit.Uint64(), 117 | params.GasPrice, 118 | data, 119 | ) 120 | rawData, _ := utils.SignTx(c.web3.privateKeyMap[strings.ToLower(params.FromAddress)], os.Getenv("CHAIN_ID"), tx) 121 | 122 | return c.web3.Rpc.EthSendRawTransaction(rawData) 123 | } 124 | 125 | func GetGasPriceGwei() (gasPriceInGwei int64) { 126 | resp, err := utils.Get("https://ethgasstation.info/json/ethgasAPI.json", "", utils.EmptyKeyPairList, utils.EmptyKeyPairList) 127 | if err != nil { 128 | return 30 // default 30gwei 129 | } 130 | var dataContainer struct { 131 | Fast float64 `json:"fast"` 132 | Fastest float64 `json:"fastest"` 133 | SafeLow float64 `json:"safeLow"` 134 | Average float64 `json:"average"` 135 | } 136 | json.Unmarshal([]byte(resp), &dataContainer) 137 | gasPriceInGwei = int64(dataContainer.Fast / 10) 138 | if gasPriceInGwei > 300 { 139 | gasPriceInGwei = 300 140 | } 141 | return 142 | } 143 | --------------------------------------------------------------------------------