-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathapp.go
201 lines (171 loc) · 4.82 KB
/
app.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package main
import (
"context"
"crypto/sha256"
"fmt"
"log"
"time"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/vulpemventures/go-elements/address"
"github.com/vulpemventures/go-elements/network"
)
// Network: Map of network names to struct instances
var SupportedNetworks map[string]*network.Network = map[string]*network.Network{
"liquid": &network.Liquid,
"testnet": &network.Testnet,
"regtest": &network.Regtest,
}
func ScriptHashFromAddress(addr string) (string, error) {
script, err := address.ToOutputScript(addr)
if err != nil {
return "", fmt.Errorf("error converting address to output script: %w", err)
}
hashedBuf := sha256.Sum256(script)
hash, err := chainhash.NewHash(hashedBuf[:])
if err != nil {
return "", fmt.Errorf("error creating hash: %w", err)
}
return hash.String(), nil
}
type Market struct {
BaseAsset string
QuoteAsset string
BuyPercentageFee float64
SellPercentageFee float64
BuyLimit uint64
SellLimit uint64
}
func GetMarketsWithLimits(ctx context.Context, walletSvc WalletService) (mkts []*Market, err error) {
markets := GetMarkets()
for _, market := range markets {
market, err := GetMarketWithLimits(ctx, walletSvc, market)
if err != nil {
return nil, fmt.Errorf("error getting market with limits: %w", err)
}
mkts = append(mkts, market)
}
return mkts, nil
}
func GetMarketWithLimits(ctx context.Context, walletSvc WalletService, market *Market) (mkt *Market, err error) {
baseAsset, ok := currencyToAsset[market.BaseAsset]
if !ok {
return nil, fmt.Errorf("asset not found for currency: %s", market.BaseAsset)
}
quoteAsset, ok := currencyToAsset[market.QuoteAsset]
if !ok {
return nil, fmt.Errorf("asset not found for currency: %s", market.QuoteAsset)
}
baseBalance, err := walletSvc.Balance(ctx, baseAsset.AssetHash)
if err != nil {
return nil, fmt.Errorf("error getting balance for asset: %s, error: %w", baseAsset.AssetHash, err)
}
quoteBalance, err := walletSvc.Balance(ctx, quoteAsset.AssetHash)
if err != nil {
return nil, fmt.Errorf("error getting balance for asset: %s, error: %w", quoteAsset.AssetHash, err)
}
market.BuyLimit = baseBalance.AvailableBalance
market.SellLimit = quoteBalance.AvailableBalance
mkt = market
return mkt, nil
}
func GetMarkets() []*Market {
return []*Market{
{
BaseAsset: "L-BTC",
QuoteAsset: "L-BTC",
BuyPercentageFee: 0.1,
SellPercentageFee: 0.1,
BuyLimit: 0,
SellLimit: 0,
},
{
BaseAsset: "L-BTC",
QuoteAsset: "USDT",
BuyPercentageFee: 0.1,
SellPercentageFee: 0.75,
BuyLimit: 0,
SellLimit: 0,
},
// Add more markets here if needed
}
}
func getTradingPair(markets []*Market, pair string) *Market {
for _, market := range markets {
if market.BaseAsset+"/"+market.QuoteAsset == pair {
return market
}
}
return nil
}
func getTransactionsForAddress(addr, networkName string) ([]Transaction, error) {
esplora, err := NewEsplora(networkName)
if err != nil {
return nil, fmt.Errorf("esplora initialization error: %w", err)
}
transactions, err := esplora.FetchTransactionHistory(addr)
if err != nil {
return nil, fmt.Errorf("esplora fetch txs error: %w", err)
}
return transactions, nil
}
func watchForTrades(order *Order, walletSvc WalletService, esplora *Esplora) error {
if duration := time.Since(order.Timestamp); duration > 10*time.Minute {
err := updateOrderStatus(order.ID, "Expired")
if err != nil {
return fmt.Errorf("error updating order status: %w", err)
}
}
utxos, err := esplora.FetchUnspents(order.Address)
if err != nil {
return fmt.Errorf("error fetching unspents: %w", err)
}
// TODO Check also the asset type
if coinsAreMoreThan(utxos, order.Input.Amount) {
updateOrderStatus(order.ID, "Funded")
trades, err := executeTrades(
order,
utxos,
walletSvc,
esplora,
)
if err != nil {
return fmt.Errorf("error executing trade: %v", err)
}
for _, trade := range trades {
log.Printf("executed trade for order ID: %s\n", trade.Order.ID)
}
updateOrderStatus(order.ID, "Fulfilled")
}
return nil
}
func coinsAreMoreThan(utxos []*UTXO, amount uint64) bool {
// Calculate the total value of UTXOs
totalValue := uint64(0)
for _, utxo := range utxos {
totalValue += utxo.Value
}
return totalValue >= amount
}
func executeTrades(order *Order, unspents []*UTXO, walletSvc WalletService, esplora *Esplora) ([]*Trade, error) {
trades := []*Trade{}
for _, unspent := range unspents {
trade, err := FromFundedOrder(
walletSvc,
order,
unspent,
)
if err != nil {
return nil, err
}
if trade.Status != Funded {
return nil, fmt.Errorf("trade is not funded: %v", err)
}
// Execute the trade
err = trade.ExecuteTrade()
if err != nil {
return nil, err
}
trades = append(trades, trade)
}
return trades, nil
}