-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathclient.go
266 lines (222 loc) · 7.19 KB
/
client.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package jupiter
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"github.com/mr-tron/base58"
"github.com/pkg/errors"
"github.com/code-payments/code-server/pkg/metrics"
"github.com/code-payments/code-server/pkg/solana"
)
// Reference: https://station.jup.ag/docs/apis/swap-api
const (
DefaultApiBaseUrl = "https://quote-api.jup.ag/v6/"
quoteEndpointName = "quote"
swapInstructionsEndpointName = "swap-instructions"
metricsStructName = "jupiter.client"
)
type Client struct {
baseUrl string
httpClient *http.Client
}
// NewClient returns a new Jupiter client for performing on-chain swaps
func NewClient(baseUrl string) *Client {
return &Client{
baseUrl: baseUrl,
httpClient: http.DefaultClient,
}
}
type Quote struct {
jsonString string
estimatedSwapAmount uint64
useLegacyInstructions bool
}
func (q *Quote) GetEstimatedSwapAmount() uint64 {
return q.estimatedSwapAmount
}
// GetQuote gets an optimal route for performing a swap
func (c *Client) GetQuote(
ctx context.Context,
inputMint string,
outputMint string,
quarksToSwap uint64,
slippageBps uint32,
forceDirectRoute bool,
maxAccounts uint8,
useLegacyInstruction bool,
) (*Quote, error) {
tracer := metrics.TraceMethodCall(ctx, metricsStructName, "GetQuote")
defer tracer.End()
url := fmt.Sprintf(
"%s%s?inputMint=%s&outputMint=%s&amount=%d&slippageBps=%d&onlyDirectRoutes=%v&maxAccounts=%d&asLegacyTransaction=%v",
c.baseUrl,
quoteEndpointName,
inputMint,
outputMint,
quarksToSwap,
slippageBps,
forceDirectRoute,
maxAccounts,
useLegacyInstruction,
)
resp, err := c.httpClient.Get(url)
if err != nil {
return nil, errors.Wrap(err, "error executing http request")
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrap(err, "error reading response body")
}
if resp.StatusCode != http.StatusOK {
return nil, errors.Errorf("received http status %d: %s", resp.StatusCode, string(respBody))
}
var parsed jsonQuote
err = json.Unmarshal(respBody, &parsed)
if err != nil {
return nil, errors.Wrap(err, "error unmarshalling json response")
}
estimatedSwapAmount, err := strconv.ParseUint(parsed.OtherAmountThreshold, 10, 64)
if err != nil {
return nil, errors.Wrap(err, "error parsing estimated swap amount")
}
return &Quote{
jsonString: string(respBody),
estimatedSwapAmount: estimatedSwapAmount,
useLegacyInstructions: useLegacyInstruction,
}, nil
}
type SwapInstructions struct {
TokenLedgerInstruction *solana.Instruction
ComputeBudgetInstructions []solana.Instruction
SetupInstructions []solana.Instruction
SwapInstruction solana.Instruction
CleanupInstruction *solana.Instruction
}
// GetSwapInstructions gets the instructions to construct a transaction to sign
// and execute on chain to perform a swap with a given quote
func (c *Client) GetSwapInstructions(
ctx context.Context,
quote *Quote,
owner string,
destinationTokenAccount string,
) (*SwapInstructions, error) {
tracer := metrics.TraceMethodCall(ctx, metricsStructName, "GetSwapInstructions")
defer tracer.End()
if !quote.useLegacyInstructions {
return nil, errors.New("only legacy transactions are supported")
}
// todo: struct this
reqBody := fmt.Sprintf(
`{"quoteResponse": %s, "userPublicKey": "%s", "destinationTokenAccount": "%s", "prioritizationFeeLamports": "auto", "asLegacyTransaction": %v}`,
quote.jsonString,
owner,
destinationTokenAccount,
quote.useLegacyInstructions,
)
resp, err := http.Post(c.baseUrl+swapInstructionsEndpointName, "application/json", strings.NewReader(reqBody))
if err != nil {
return nil, errors.Wrap(err, "error executing http request")
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrap(err, "error reading response body")
}
if resp.StatusCode != http.StatusOK {
return nil, errors.Errorf("received http status %d: %s", resp.StatusCode, string(respBody))
}
var jsonBody jsonSwapInstructions
err = json.Unmarshal(respBody, &jsonBody)
if err != nil {
return nil, errors.Wrap(err, "error unmarshalling json response")
}
var res SwapInstructions
if res.TokenLedgerInstruction != nil {
res.TokenLedgerInstruction, err = jsonBody.TokenLedgerInstruction.ToSolanaInstruction()
if err != nil {
return nil, errors.Wrap(err, "error decoding token ledger instruction")
}
}
for _, jsonIxn := range jsonBody.ComputeBudgetInstructions {
cbIxn, err := jsonIxn.ToSolanaInstruction()
if err != nil {
return nil, errors.Wrap(err, "error decoding compute budget instruction")
}
res.ComputeBudgetInstructions = append(res.ComputeBudgetInstructions, *cbIxn)
}
for _, jsonIxn := range jsonBody.SetupInstructions {
setupIxn, err := jsonIxn.ToSolanaInstruction()
if err != nil {
return nil, errors.Wrap(err, "error decoding setup instruction")
}
res.SetupInstructions = append(res.SetupInstructions, *setupIxn)
}
if jsonBody.SwapInstruction == nil {
return nil, errors.New("swap instruction not provided")
}
swapIxn, err := jsonBody.SwapInstruction.ToSolanaInstruction()
if err != nil {
return nil, errors.Wrap(err, "error decoding swap instruction")
}
res.SwapInstruction = *swapIxn
if res.CleanupInstruction != nil {
res.CleanupInstruction, err = jsonBody.CleanupInstruction.ToSolanaInstruction()
if err != nil {
return nil, errors.Wrap(err, "error decoding cleanup instruction")
}
}
return &res, nil
}
func (i *jsonInstruction) ToSolanaInstruction() (*solana.Instruction, error) {
decodedProgramKey, err := base58.Decode(i.ProgramId)
if err != nil {
return nil, errors.Wrap(err, "invalid program public key")
}
decodedData, err := base64.StdEncoding.DecodeString(i.Data)
if err != nil {
return nil, errors.Wrap(err, "error decoding base64 instruction data")
}
var accountMetas []solana.AccountMeta
for _, instructionAccount := range i.Accounts {
decodedPubkey, err := base58.Decode(instructionAccount.Pubkey)
if err != nil {
return nil, errors.Wrap(err, "invalid instruction account public key")
}
accountMetas = append(accountMetas, solana.AccountMeta{
PublicKey: decodedPubkey,
IsSigner: instructionAccount.IsSigner,
IsWritable: instructionAccount.IsWritable,
})
}
return &solana.Instruction{
Program: decodedProgramKey,
Accounts: accountMetas,
Data: decodedData,
}, nil
}
type jsonQuote struct {
OtherAmountThreshold string `json:"otherAmountThreshold"`
}
type jsonInstructionAccount struct {
Pubkey string `json:"pubkey"`
IsSigner bool `json:"isSigner"`
IsWritable bool `json:"isWritable"`
}
type jsonInstruction struct {
ProgramId string `json:"programId"`
Accounts []jsonInstructionAccount `json:"accounts"`
Data string `json:"data"`
}
type jsonSwapInstructions struct {
TokenLedgerInstruction *jsonInstruction `json:"tokenLedgerInstruction"`
ComputeBudgetInstructions []*jsonInstruction `json:"computeBudgetInstructions"`
SetupInstructions []*jsonInstruction `json:"setupInstructions"`
SwapInstruction *jsonInstruction `json:"swapInstruction"`
CleanupInstruction *jsonInstruction `json:"cleanupInstruction"`
}