/
jupiter_api.go
215 lines (181 loc) · 5.16 KB
/
jupiter_api.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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
package stream
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/bloXroute-Labs/solana-trader-client-go/benchmark/internal/logger"
"go.uber.org/zap"
"io"
"math"
"net/http"
"strconv"
"time"
)
const (
quoteAPIEndpoint = "https://quote-api.jup.ag/v4/quote"
priceAPIEndpoint = "https://price.jup.ag/v4/price"
defaultAmount = 1
defaultSlippage = 5
defaultDecimals = 8
defaultInterval = time.Second
usdcMint = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
usdcDecimals = 6
)
type JupiterAPIStream struct {
client *http.Client
mint string
amount float64 // amount of USDC to provide for the swap (in $)
adjustedAmount int // amount of USDC to provide for the swap (in units)
decimals int // e.g. Jupiter requires 1000000 to indicate 1 USDC. This one's for the other mint.
priceAdjustment float64 // number to multiply final price by to account for decimals.
slippageBps int64
ticker *time.Ticker
interval time.Duration
}
func NewJupiterAPI(opts ...JupiterOpt) (Source[DurationUpdate[*JupiterPriceResponse], QuoteResult], error) {
j := &JupiterAPIStream{
client: &http.Client{},
amount: defaultAmount,
decimals: defaultDecimals,
slippageBps: defaultSlippage,
interval: defaultInterval,
}
for _, o := range opts {
o(j)
}
if j.mint == "" {
return nil, errors.New("mint token is mandatory")
}
j.adjustedAmount = int(j.amount * math.Pow(10, float64(usdcDecimals)))
j.priceAdjustment = math.Pow(10, float64(j.decimals-usdcDecimals))
return j, nil
}
func (j *JupiterAPIStream) log() *zap.SugaredLogger {
return logger.Log().With("source", "jupiterApi")
}
func (j *JupiterAPIStream) Name() string {
return "jupiter"
}
func (j *JupiterAPIStream) Run(parent context.Context) ([]RawUpdate[DurationUpdate[*JupiterPriceResponse]], error) {
ctx, cancel := context.WithCancel(parent)
defer cancel()
ticker := j.ticker
if ticker == nil {
ticker = time.NewTicker(j.interval)
}
return collectOrderedUpdates(ctx, ticker, func() (*JupiterPriceResponse, error) {
res, err := j.FetchQuote(ctx)
if err != nil {
return nil, err
}
return &res, err
}, nil, func(err error) {
j.log().Errorw("could not fetch price", "err", err)
})
}
func (j *JupiterAPIStream) Process(updates []RawUpdate[DurationUpdate[*JupiterPriceResponse]], removeDuplicates bool) (results map[int][]ProcessedUpdate[QuoteResult], duplicates map[int][]ProcessedUpdate[QuoteResult], err error) {
results = make(map[int][]ProcessedUpdate[QuoteResult])
duplicates = make(map[int][]ProcessedUpdate[QuoteResult])
lastPrice := -1.
for _, update := range updates {
slot := update.Data.Data.ContextSlot
price := update.Data.Data.Price(j.mint)
qr := QuoteResult{
Elapsed: update.Timestamp.Sub(update.Data.Start),
BuyPrice: price,
SellPrice: price,
Source: "jupiter",
}
pu := ProcessedUpdate[QuoteResult]{
Timestamp: update.Data.Start,
Slot: slot,
Data: qr,
}
if price == lastPrice {
duplicates[slot] = append(duplicates[slot], pu)
if removeDuplicates {
continue
}
}
lastPrice = price
results[slot] = append(results[slot], pu)
}
return
}
// FetchQuote is used to specify 1 USDC instead of 0.000001
func (j *JupiterAPIStream) FetchQuote(ctx context.Context) (jr JupiterPriceResponse, err error) {
url := fmt.Sprintf("%v?inputMint=%v&outputMint=%v&amount=%v&slippageBps=%v", quoteAPIEndpoint, usdcMint, j.mint, j.adjustedAmount, j.slippageBps)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return
}
res, err := j.client.Do(req)
if err != nil {
return
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(res.Body)
b, err := io.ReadAll(res.Body)
if err != nil {
return
}
var quoteResponse JupiterQuoteResponse
err = json.Unmarshal(b, "eResponse)
if err != nil {
return
}
if len(quoteResponse.Routes) == 0 {
err = errors.New("no quotes found")
return
}
bestRoute := quoteResponse.Routes[0]
inAmount, err := strconv.ParseFloat(bestRoute.InAmount, 64)
if err != nil {
return
}
outAmount, err := strconv.ParseFloat(bestRoute.OutAmount, 64)
if err != nil {
return
}
price := inAmount / outAmount * j.priceAdjustment
jr = JupiterPriceResponse{
PriceInfo: map[string]JupiterPriceInfo{
j.mint: {
ID: j.mint,
MintSymbol: "",
VsToken: usdcMint,
VsTokenSymbol: "USDC",
Price: price,
},
},
TimeTaken: quoteResponse.TimeTaken,
ContextSlot: int(quoteResponse.ContextSlot),
}
return
}
// FetchPrice returns a price based off of swapping 0.0000001 USDC (the minimum possible unit). Trader API does 1 USDC.
func (j *JupiterAPIStream) FetchPrice(ctx context.Context) (jr JupiterPriceResponse, err error) {
url := fmt.Sprintf("%v?ids=%v", priceAPIEndpoint, j.mint)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return
}
res, err := j.client.Do(req)
if err != nil {
return
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(res.Body)
b, err := io.ReadAll(res.Body)
if err != nil {
return
}
err = json.Unmarshal(b, &jr)
if err != nil {
return
}
return jr, nil
}