@deserialize/swap-sdk 0.0.151 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/swapSDK.d.ts +140 -42
- package/dist/swapSDK.js +145 -38
- package/dist/swapSDK.js.map +1 -1
- package/package.json +2 -2
- package/src/swapSDK.ts +222 -56
package/dist/swapSDK.d.ts
CHANGED
@@ -3,16 +3,16 @@ import web3, { Connection, Keypair, PublicKey, TransactionInstruction, Versioned
|
|
3
3
|
* Parameters to request a swap.
|
4
4
|
*/
|
5
5
|
export interface SwapRequestParams {
|
6
|
-
/** User
|
6
|
+
/** User's public key */
|
7
7
|
publicKey: PublicKey;
|
8
|
-
/** Token A
|
8
|
+
/** Token A's address */
|
9
9
|
tokenA: PublicKey;
|
10
|
-
/** Token B
|
10
|
+
/** Token B's address */
|
11
11
|
tokenB: PublicKey;
|
12
12
|
/** Amount of Token A to swap (in human-readable units) */
|
13
13
|
amountIn: number;
|
14
|
-
/** DEX identifier –
|
15
|
-
dexId:
|
14
|
+
/** DEX identifier – "INVARIANT", "ORCA", or "ALL" */
|
15
|
+
dexId: DexIdTypes;
|
16
16
|
/**
|
17
17
|
* This is used to set options like limit the swap to just two hops to
|
18
18
|
* prevent errors like TooManyAccountLocks
|
@@ -22,27 +22,36 @@ export interface SwapRequestParams {
|
|
22
22
|
export interface RouteOptions {
|
23
23
|
reduceToTwoHops: boolean;
|
24
24
|
}
|
25
|
+
export type GetTokenMintBalanceType = {
|
26
|
+
mint: string;
|
27
|
+
balanceUiAmount: number;
|
28
|
+
};
|
25
29
|
/**
|
26
30
|
* Result from the swapTx method.
|
27
31
|
*/
|
28
32
|
export interface SwapTxResult {
|
29
|
-
/**
|
33
|
+
/** Fully constructed VersionedTransaction ready for signing */
|
30
34
|
transaction: VersionedTransaction;
|
31
|
-
/**
|
35
|
+
/** Raw transaction data in base64 encoding */
|
36
|
+
serializedTransactions: string;
|
37
|
+
/** Output amount in token decimals */
|
32
38
|
amountOut: number;
|
33
|
-
/**
|
39
|
+
/** Human-readable output amount */
|
34
40
|
amountOutUi: number;
|
35
|
-
/**
|
36
|
-
|
41
|
+
/** Price of Token A in terms of Token B */
|
42
|
+
pairPrice: number;
|
43
|
+
/** Swap route details */
|
44
|
+
routePlan: Array<{
|
37
45
|
tokenA: PublicKey;
|
38
46
|
tokenB: PublicKey;
|
39
|
-
dexId:
|
40
|
-
}
|
41
|
-
/**
|
47
|
+
dexId: DexIdTypes;
|
48
|
+
}>;
|
49
|
+
/** Associated lookup accounts */
|
42
50
|
lookupAccounts: PublicKey[];
|
43
|
-
/**
|
51
|
+
/** Required transaction signers */
|
44
52
|
signers: Keypair[];
|
45
|
-
|
53
|
+
/** Protocol fee percentage */
|
54
|
+
feeRate: number;
|
46
55
|
}
|
47
56
|
/**
|
48
57
|
* Structure representing a group of instructions from the API.
|
@@ -76,6 +85,24 @@ export interface SwapIxResult {
|
|
76
85
|
/** Any top-level signers returned (as base64 encoded strings) */
|
77
86
|
signers: string[];
|
78
87
|
}
|
88
|
+
/**
|
89
|
+
* Response from the quote endpoint
|
90
|
+
*/
|
91
|
+
export interface QuoteResponse {
|
92
|
+
tokenA: string;
|
93
|
+
tokenB: string;
|
94
|
+
amountIn: string;
|
95
|
+
amountOut: string;
|
96
|
+
tokenPrice: string;
|
97
|
+
priceImpact: string;
|
98
|
+
feeRate: string;
|
99
|
+
routePlan: Array<{
|
100
|
+
tokenA: string;
|
101
|
+
tokenB: string;
|
102
|
+
dexId: DexIdTypes;
|
103
|
+
}>;
|
104
|
+
dexId: DexIdTypes;
|
105
|
+
}
|
79
106
|
/**
|
80
107
|
* Token details returned from the /tokenList endpoint.
|
81
108
|
*/
|
@@ -89,58 +116,109 @@ export interface Token {
|
|
89
116
|
tokenProgram: string;
|
90
117
|
}
|
91
118
|
/**
|
92
|
-
*
|
119
|
+
* Balance Check Parameters
|
120
|
+
*/
|
121
|
+
export interface BalanceCheckParams {
|
122
|
+
/** User's wallet address in base58 */
|
123
|
+
userAddress: string;
|
124
|
+
/** Token mint addresses to check */
|
125
|
+
tokenMints: string[];
|
126
|
+
}
|
127
|
+
/**
|
128
|
+
* SwapSDK simplifies interaction with the decentralized exchange API, handling swaps, token data, and balance checks.
|
129
|
+
*
|
130
|
+
* Key Features:
|
131
|
+
* - Get swap quotes to preview expected outcomes
|
132
|
+
* - Build swap transactions with automatic route finding
|
133
|
+
* - Get underlying swap instructions for custom transaction handling
|
134
|
+
* - Retrieve token list and price data
|
135
|
+
* - Check token balances
|
136
|
+
* - Transaction simulation
|
93
137
|
*
|
94
138
|
* Usage:
|
95
139
|
* ```ts
|
96
|
-
* import { SwapSDK } from "./SwapSDK";
|
97
|
-
* import { PublicKey } from "@solana/web3.js";
|
140
|
+
* import { SwapSDK, DEX_IDS } from "./SwapSDK";
|
141
|
+
* import { PublicKey, Connection } from "@solana/web3.js";
|
98
142
|
*
|
99
|
-
* const sdk = new SwapSDK(
|
143
|
+
* const sdk = new SwapSDK(); // Uses default production URL
|
144
|
+
* const connection = new Connection("https://api.mainnet-beta.solana.com");
|
100
145
|
*
|
101
|
-
* async function
|
102
|
-
*
|
103
|
-
*
|
146
|
+
* async function fullSwapFlow() {
|
147
|
+
* // Example swap parameters
|
148
|
+
* const swapParams = {
|
149
|
+
* publicKey: new PublicKey("UserPublicKeyBase58"),
|
104
150
|
* tokenA: new PublicKey("GU7NS9xCwgNPiAdJ69iusFrRfawjDDPjeMBovhV1d4kn"),
|
105
151
|
* tokenB: new PublicKey("CEBP3CqAbW4zdZA57H2wfaSG1QNdzQ72GiQEbQXyW9Tm"),
|
106
152
|
* amountIn: 10.0,
|
107
|
-
* dexId:
|
153
|
+
* dexId: DEX_IDS.INVARIANT,
|
154
|
+
* options: { reduceToTwoHops: false }
|
108
155
|
* };
|
109
156
|
*
|
110
|
-
* //
|
111
|
-
* const
|
112
|
-
* console.log("
|
157
|
+
* // Get a quote first to see expected outcome
|
158
|
+
* const quote = await sdk.getSwapQuote(swapParams);
|
159
|
+
* console.log("Expected output amount:", quote.amountOut);
|
160
|
+
* console.log("Price impact:", quote.priceImpact);
|
113
161
|
*
|
114
|
-
* //
|
115
|
-
* const
|
116
|
-
*
|
162
|
+
* // Get complete swap transaction
|
163
|
+
* const txResult = await sdk.swapTx({
|
164
|
+
* ...swapParams,
|
165
|
+
* quote: quote
|
166
|
+
* });
|
167
|
+
* console.log("Serialized Transaction:", txResult.serializedTransactions);
|
117
168
|
*
|
118
|
-
* //
|
169
|
+
* // Simulate transaction before sending
|
170
|
+
* const simulation = await sdk.simulateTransaction(connection, txResult.transaction);
|
171
|
+
* console.log("Simulation Result:", simulation);
|
172
|
+
*
|
173
|
+
* // Get token list
|
119
174
|
* const tokens = await sdk.tokenList();
|
120
|
-
* console.log("Tokens:", tokens);
|
175
|
+
* console.log("Available Tokens:", tokens);
|
176
|
+
*
|
177
|
+
* // Check balances
|
178
|
+
* const balances = await sdk.getTokenMintBalance({
|
179
|
+
* userAddress: swapParams.publicKey.toBase58(),
|
180
|
+
* tokenMints: [swapParams.tokenA.toBase58(), swapParams.tokenB.toBase58()]
|
181
|
+
* });
|
182
|
+
* console.log("User Balances:", balances);
|
121
183
|
*
|
122
|
-
* //
|
123
|
-
* const
|
124
|
-
* console.log("
|
184
|
+
* // Get token price
|
185
|
+
* const solPrice = await sdk.tokenPrice("So11111111111111111111111111111111111111112");
|
186
|
+
* console.log("SOL Price:", solPrice);
|
125
187
|
* }
|
126
188
|
*
|
127
|
-
*
|
189
|
+
* fullSwapFlow();
|
128
190
|
* ```
|
129
191
|
*/
|
130
192
|
export declare class SwapSDK {
|
131
193
|
private baseUrl;
|
132
194
|
constructor(baseUrl?: string);
|
195
|
+
base58: import("base-x").default.BaseConverter;
|
196
|
+
web3: typeof web3;
|
197
|
+
DEX_IDS: {
|
198
|
+
readonly ORCA: "ORCA";
|
199
|
+
readonly INVARIANT: "INVARIANT";
|
200
|
+
readonly ALL: "ALL";
|
201
|
+
};
|
133
202
|
/**
|
134
|
-
*
|
203
|
+
* Gets a swap quote without executing the swap
|
135
204
|
*
|
136
|
-
* @param params Swap parameters
|
137
|
-
* @returns
|
205
|
+
* @param params Swap parameters
|
206
|
+
* @returns Quote information including expected output amount and price impact
|
138
207
|
*/
|
139
|
-
|
140
|
-
|
141
|
-
|
208
|
+
getSwapQuote(params: SwapRequestParams): Promise<QuoteResponse>;
|
209
|
+
/**
|
210
|
+
* Executes a swap based on a previously obtained quote
|
211
|
+
*
|
212
|
+
* @param params Swap parameters including the quote
|
213
|
+
* @returns Transaction and output details
|
214
|
+
*/
|
215
|
+
executeSwap(params: {
|
216
|
+
publicKey: PublicKey;
|
217
|
+
quote: QuoteResponse;
|
218
|
+
}): Promise<any>;
|
142
219
|
/**
|
143
220
|
* Calls the swap endpoint and returns a fully constructed Transaction.
|
221
|
+
* This method is a wrapper that gets a quote first, then executes the swap.
|
144
222
|
*
|
145
223
|
* @param params Swap parameters.
|
146
224
|
* @returns A promise that resolves to a SwapTxResult.
|
@@ -148,6 +226,7 @@ export declare class SwapSDK {
|
|
148
226
|
swapTx(params: SwapRequestParams): Promise<SwapTxResult>;
|
149
227
|
/**
|
150
228
|
* Calls the swap endpoint and returns the raw instructions and related data.
|
229
|
+
* This method is a wrapper that gets a quote first, then executes the swap to get instructions.
|
151
230
|
*
|
152
231
|
* @param params Swap parameters.
|
153
232
|
* @returns A promise that resolves to a SwapIxResult.
|
@@ -166,6 +245,19 @@ export declare class SwapSDK {
|
|
166
245
|
* @returns A promise that resolves to the token's price (number).
|
167
246
|
*/
|
168
247
|
tokenPrice(tokenAddress: string): Promise<number>;
|
248
|
+
/**
|
249
|
+
* Gets the token balances for a given wallet
|
250
|
+
*
|
251
|
+
* @param params User address and token mints to check
|
252
|
+
* @returns Array of token balances
|
253
|
+
*/
|
254
|
+
getTokenMintBalance(params: BalanceCheckParams): Promise<GetTokenMintBalanceType[]>;
|
255
|
+
/**
|
256
|
+
* Health check for the API
|
257
|
+
*
|
258
|
+
* @returns A string "Pong" if the service is operational
|
259
|
+
*/
|
260
|
+
ping(): Promise<string>;
|
169
261
|
/**
|
170
262
|
* Simulates a transaction.
|
171
263
|
* @param connection The connection to use.
|
@@ -182,4 +274,10 @@ export declare class SwapSDK {
|
|
182
274
|
*/
|
183
275
|
private convertAPIInstruction;
|
184
276
|
}
|
185
|
-
export declare const
|
277
|
+
export declare const DEX_IDS: {
|
278
|
+
readonly ORCA: "ORCA";
|
279
|
+
readonly INVARIANT: "INVARIANT";
|
280
|
+
readonly ALL: "ALL";
|
281
|
+
};
|
282
|
+
export type DexIdTypes = (typeof DEX_IDS)[keyof typeof DEX_IDS];
|
283
|
+
export declare const BASE_URL = "https://api.deserialize.xyz";
|
package/dist/swapSDK.js
CHANGED
@@ -36,73 +36,98 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
36
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
37
37
|
};
|
38
38
|
Object.defineProperty(exports, "__esModule", { value: true });
|
39
|
-
exports.BASE_URL = exports.SwapSDK = void 0;
|
39
|
+
exports.BASE_URL = exports.DEX_IDS = exports.SwapSDK = void 0;
|
40
40
|
// SwapSDK.ts
|
41
41
|
const web3_js_1 = __importStar(require("@solana/web3.js"));
|
42
42
|
const bs58_1 = __importDefault(require("bs58"));
|
43
43
|
const errors_1 = require("./errors");
|
44
44
|
/**
|
45
|
-
* SwapSDK simplifies
|
45
|
+
* SwapSDK simplifies interaction with the decentralized exchange API, handling swaps, token data, and balance checks.
|
46
|
+
*
|
47
|
+
* Key Features:
|
48
|
+
* - Get swap quotes to preview expected outcomes
|
49
|
+
* - Build swap transactions with automatic route finding
|
50
|
+
* - Get underlying swap instructions for custom transaction handling
|
51
|
+
* - Retrieve token list and price data
|
52
|
+
* - Check token balances
|
53
|
+
* - Transaction simulation
|
46
54
|
*
|
47
55
|
* Usage:
|
48
56
|
* ```ts
|
49
|
-
* import { SwapSDK } from "./SwapSDK";
|
50
|
-
* import { PublicKey } from "@solana/web3.js";
|
57
|
+
* import { SwapSDK, DEX_IDS } from "./SwapSDK";
|
58
|
+
* import { PublicKey, Connection } from "@solana/web3.js";
|
51
59
|
*
|
52
|
-
* const sdk = new SwapSDK(
|
60
|
+
* const sdk = new SwapSDK(); // Uses default production URL
|
61
|
+
* const connection = new Connection("https://api.mainnet-beta.solana.com");
|
53
62
|
*
|
54
|
-
* async function
|
55
|
-
*
|
56
|
-
*
|
63
|
+
* async function fullSwapFlow() {
|
64
|
+
* // Example swap parameters
|
65
|
+
* const swapParams = {
|
66
|
+
* publicKey: new PublicKey("UserPublicKeyBase58"),
|
57
67
|
* tokenA: new PublicKey("GU7NS9xCwgNPiAdJ69iusFrRfawjDDPjeMBovhV1d4kn"),
|
58
68
|
* tokenB: new PublicKey("CEBP3CqAbW4zdZA57H2wfaSG1QNdzQ72GiQEbQXyW9Tm"),
|
59
69
|
* amountIn: 10.0,
|
60
|
-
* dexId:
|
70
|
+
* dexId: DEX_IDS.INVARIANT,
|
71
|
+
* options: { reduceToTwoHops: false }
|
61
72
|
* };
|
62
73
|
*
|
63
|
-
* //
|
64
|
-
* const
|
65
|
-
* console.log("
|
74
|
+
* // Get a quote first to see expected outcome
|
75
|
+
* const quote = await sdk.getSwapQuote(swapParams);
|
76
|
+
* console.log("Expected output amount:", quote.amountOut);
|
77
|
+
* console.log("Price impact:", quote.priceImpact);
|
78
|
+
*
|
79
|
+
* // Get complete swap transaction
|
80
|
+
* const txResult = await sdk.swapTx({
|
81
|
+
* ...swapParams,
|
82
|
+
* quote: quote
|
83
|
+
* });
|
84
|
+
* console.log("Serialized Transaction:", txResult.serializedTransactions);
|
66
85
|
*
|
67
|
-
* //
|
68
|
-
* const
|
69
|
-
* console.log("
|
86
|
+
* // Simulate transaction before sending
|
87
|
+
* const simulation = await sdk.simulateTransaction(connection, txResult.transaction);
|
88
|
+
* console.log("Simulation Result:", simulation);
|
70
89
|
*
|
71
|
-
* //
|
90
|
+
* // Get token list
|
72
91
|
* const tokens = await sdk.tokenList();
|
73
|
-
* console.log("Tokens:", tokens);
|
92
|
+
* console.log("Available Tokens:", tokens);
|
93
|
+
*
|
94
|
+
* // Check balances
|
95
|
+
* const balances = await sdk.getTokenMintBalance({
|
96
|
+
* userAddress: swapParams.publicKey.toBase58(),
|
97
|
+
* tokenMints: [swapParams.tokenA.toBase58(), swapParams.tokenB.toBase58()]
|
98
|
+
* });
|
99
|
+
* console.log("User Balances:", balances);
|
74
100
|
*
|
75
|
-
* //
|
76
|
-
* const
|
77
|
-
* console.log("
|
101
|
+
* // Get token price
|
102
|
+
* const solPrice = await sdk.tokenPrice("So11111111111111111111111111111111111111112");
|
103
|
+
* console.log("SOL Price:", solPrice);
|
78
104
|
* }
|
79
105
|
*
|
80
|
-
*
|
106
|
+
* fullSwapFlow();
|
81
107
|
* ```
|
82
108
|
*/
|
83
109
|
class SwapSDK {
|
84
110
|
constructor(baseUrl) {
|
85
111
|
this.base58 = bs58_1.default;
|
86
112
|
this.web3 = web3_js_1.default;
|
113
|
+
this.DEX_IDS = exports.DEX_IDS;
|
87
114
|
this.baseUrl = baseUrl || exports.BASE_URL;
|
88
115
|
}
|
89
116
|
/**
|
90
|
-
*
|
117
|
+
* Gets a swap quote without executing the swap
|
91
118
|
*
|
92
|
-
* @param params Swap parameters
|
93
|
-
* @returns
|
119
|
+
* @param params Swap parameters
|
120
|
+
* @returns Quote information including expected output amount and price impact
|
94
121
|
*/
|
95
|
-
async
|
96
|
-
// Prepare the payload by converting PublicKeys to base58 strings
|
122
|
+
async getSwapQuote(params) {
|
97
123
|
const body = {
|
98
|
-
publicKey: params.publicKey.toBase58(),
|
99
124
|
tokenA: params.tokenA.toBase58(),
|
100
125
|
tokenB: params.tokenB.toBase58(),
|
101
126
|
amountIn: params.amountIn.toString(),
|
102
127
|
dexId: params.dexId,
|
103
128
|
options: params.options,
|
104
129
|
};
|
105
|
-
const response = await fetch(`${this.baseUrl}/
|
130
|
+
const response = await fetch(`${this.baseUrl}/quote`, {
|
106
131
|
method: "POST",
|
107
132
|
headers: {
|
108
133
|
"Content-Type": "application/json",
|
@@ -112,52 +137,91 @@ class SwapSDK {
|
|
112
137
|
if (!response.ok) {
|
113
138
|
throw new Error(`API Error: ${response.statusText}`);
|
114
139
|
}
|
115
|
-
return response.json();
|
140
|
+
return await response.json();
|
141
|
+
}
|
142
|
+
/**
|
143
|
+
* Executes a swap based on a previously obtained quote
|
144
|
+
*
|
145
|
+
* @param params Swap parameters including the quote
|
146
|
+
* @returns Transaction and output details
|
147
|
+
*/
|
148
|
+
async executeSwap(params) {
|
149
|
+
const body = {
|
150
|
+
publicKey: params.publicKey.toBase58(),
|
151
|
+
quote: params.quote,
|
152
|
+
};
|
153
|
+
const response = await fetch(`${this.baseUrl}/swap`, {
|
154
|
+
method: "POST",
|
155
|
+
headers: {
|
156
|
+
"Content-Type": "application/json",
|
157
|
+
},
|
158
|
+
body: JSON.stringify(body),
|
159
|
+
});
|
160
|
+
if (!response.ok) {
|
161
|
+
throw new Error(`API Error: ${response.statusText}`);
|
162
|
+
}
|
163
|
+
return await response.json();
|
116
164
|
}
|
117
165
|
/**
|
118
166
|
* Calls the swap endpoint and returns a fully constructed Transaction.
|
167
|
+
* This method is a wrapper that gets a quote first, then executes the swap.
|
119
168
|
*
|
120
169
|
* @param params Swap parameters.
|
121
170
|
* @returns A promise that resolves to a SwapTxResult.
|
122
171
|
*/
|
123
172
|
async swapTx(params) {
|
124
|
-
|
173
|
+
// First get a quote
|
174
|
+
const quote = await this.getSwapQuote(params);
|
175
|
+
// Then execute the swap with the quote
|
176
|
+
const data = await this.executeSwap({
|
177
|
+
publicKey: params.publicKey,
|
178
|
+
quote,
|
179
|
+
});
|
125
180
|
// Convert the base64-encoded transaction into a VersionedTransaction.
|
126
181
|
const txBuffer = Buffer.from(data.transaction, "base64");
|
127
182
|
const transaction = web3_js_1.VersionedTransaction.deserialize(txBuffer);
|
128
183
|
// Convert lookup accounts from strings to PublicKey objects.
|
129
184
|
const lookupAccounts = (data.lookUpAccounts || []).map((addr) => new web3_js_1.PublicKey(addr));
|
130
185
|
// Convert the route plan tokens into PublicKey objects.
|
131
|
-
const routePlan = (
|
186
|
+
const routePlan = (quote.routePlan || []).map((rp) => ({
|
132
187
|
tokenA: new web3_js_1.PublicKey(rp.tokenA),
|
133
188
|
tokenB: new web3_js_1.PublicKey(rp.tokenB),
|
134
189
|
dexId: rp.dexId,
|
135
190
|
}));
|
136
|
-
// Convert each
|
191
|
+
// Convert each base58-encoded signer secret into a Keypair.
|
137
192
|
const signers = data.signers.map((s) => web3_js_1.Keypair.fromSecretKey(bs58_1.default.decode(s)));
|
138
193
|
transaction.sign(signers);
|
139
194
|
return {
|
140
195
|
transaction,
|
141
196
|
serializedTransactions: data.transaction,
|
142
197
|
amountOut: Number(data.amountOut),
|
143
|
-
amountOutUi: Number(
|
198
|
+
amountOutUi: Number(quote.amountOut),
|
199
|
+
pairPrice: Number(quote.tokenPrice),
|
144
200
|
routePlan,
|
145
201
|
lookupAccounts,
|
146
202
|
signers,
|
203
|
+
feeRate: parseFloat(quote.feeRate),
|
147
204
|
};
|
148
205
|
}
|
149
206
|
/**
|
150
207
|
* Calls the swap endpoint and returns the raw instructions and related data.
|
208
|
+
* This method is a wrapper that gets a quote first, then executes the swap to get instructions.
|
151
209
|
*
|
152
210
|
* @param params Swap parameters.
|
153
211
|
* @returns A promise that resolves to a SwapIxResult.
|
154
212
|
*/
|
155
213
|
async swapIx(params) {
|
156
|
-
|
214
|
+
// First get a quote
|
215
|
+
const quote = await this.getSwapQuote(params);
|
216
|
+
// Then execute the swap with the quote
|
217
|
+
const data = await this.executeSwap({
|
218
|
+
publicKey: params.publicKey,
|
219
|
+
quote,
|
220
|
+
});
|
157
221
|
// Convert lookup accounts from strings to PublicKey objects.
|
158
222
|
const lookupAccounts = (data.lookUpAccounts || []).map((addr) => new web3_js_1.PublicKey(addr));
|
159
223
|
// Convert the route plan tokens into PublicKey objects.
|
160
|
-
const routePlan = (
|
224
|
+
const routePlan = (quote.routePlan || []).map((rp) => ({
|
161
225
|
tokenA: new web3_js_1.PublicKey(rp.tokenA),
|
162
226
|
tokenB: new web3_js_1.PublicKey(rp.tokenB),
|
163
227
|
dexId: rp.dexId,
|
@@ -171,7 +235,7 @@ class SwapSDK {
|
|
171
235
|
return {
|
172
236
|
instructionGroups,
|
173
237
|
amountOut: Number(data.amountOut),
|
174
|
-
amountOutUi: Number(
|
238
|
+
amountOutUi: Number(quote.amountOut),
|
175
239
|
routePlan,
|
176
240
|
lookupAccounts,
|
177
241
|
signers: data.signers,
|
@@ -188,7 +252,7 @@ class SwapSDK {
|
|
188
252
|
throw new Error(`API Error: ${response.statusText}`);
|
189
253
|
}
|
190
254
|
const data = await response.json();
|
191
|
-
return data.
|
255
|
+
return data.map((token) => ({
|
192
256
|
name: token.metadata.name,
|
193
257
|
symbol: token.metadata.symbol,
|
194
258
|
address: token.address,
|
@@ -211,6 +275,44 @@ class SwapSDK {
|
|
211
275
|
const data = await response.json();
|
212
276
|
return Number(data.price);
|
213
277
|
}
|
278
|
+
/**
|
279
|
+
* Gets the token balances for a given wallet
|
280
|
+
*
|
281
|
+
* @param params User address and token mints to check
|
282
|
+
* @returns Array of token balances
|
283
|
+
*/
|
284
|
+
async getTokenMintBalance(params) {
|
285
|
+
try {
|
286
|
+
const response = await fetch(`${this.baseUrl}/getMintBalances`, {
|
287
|
+
method: "POST",
|
288
|
+
headers: {
|
289
|
+
"Content-Type": "application/json",
|
290
|
+
},
|
291
|
+
body: JSON.stringify(params),
|
292
|
+
});
|
293
|
+
if (!response.ok) {
|
294
|
+
throw new Error(`HTTP error! status: ${response.status}`);
|
295
|
+
}
|
296
|
+
const data = await response.json();
|
297
|
+
return data;
|
298
|
+
}
|
299
|
+
catch (error) {
|
300
|
+
console.error("Error fetching token balances:", error);
|
301
|
+
throw error;
|
302
|
+
}
|
303
|
+
}
|
304
|
+
/**
|
305
|
+
* Health check for the API
|
306
|
+
*
|
307
|
+
* @returns A string "Pong" if the service is operational
|
308
|
+
*/
|
309
|
+
async ping() {
|
310
|
+
const response = await fetch(`${this.baseUrl}/ping`);
|
311
|
+
if (!response.ok) {
|
312
|
+
throw new Error(`API Error: ${response.statusText}`);
|
313
|
+
}
|
314
|
+
return await response.text();
|
315
|
+
}
|
214
316
|
/**
|
215
317
|
* Simulates a transaction.
|
216
318
|
* @param connection The connection to use.
|
@@ -245,5 +347,10 @@ class SwapSDK {
|
|
245
347
|
}
|
246
348
|
}
|
247
349
|
exports.SwapSDK = SwapSDK;
|
248
|
-
exports.
|
350
|
+
exports.DEX_IDS = {
|
351
|
+
ORCA: "ORCA",
|
352
|
+
INVARIANT: "INVARIANT",
|
353
|
+
ALL: "ALL",
|
354
|
+
};
|
355
|
+
exports.BASE_URL = "https://api.deserialize.xyz";
|
249
356
|
//# sourceMappingURL=swapSDK.js.map
|
package/dist/swapSDK.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"swapSDK.js","sourceRoot":"","sources":["../src/swapSDK.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,aAAa;AACb,2DASyB;AACzB,gDAA0B;AAC1B,qCAAiD;
|
1
|
+
{"version":3,"file":"swapSDK.js","sourceRoot":"","sources":["../src/swapSDK.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,aAAa;AACb,2DASyB;AACzB,gDAA0B;AAC1B,qCAAiD;AAwIjD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgEG;AACH,MAAa,OAAO;IAGlB,YAAY,OAAgB;QAI5B,WAAM,GAAG,cAAM,CAAC;QAChB,SAAI,GAAG,iBAAI,CAAC;QACZ,YAAO,GAAG,eAAO,CAAC;QALhB,IAAI,CAAC,OAAO,GAAG,OAAO,IAAI,gBAAQ,CAAC;IACrC,CAAC;IAMD;;;;;OAKG;IACH,KAAK,CAAC,YAAY,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AAE,WAAW;IACtB,GAAG,EAAE,KAAK;CACF,CAAC;AAIE,QAAA,QAAQ,GAAG,6BAA6B,CAAC"}
|
package/package.json
CHANGED
@@ -1,13 +1,13 @@
|
|
1
1
|
{
|
2
2
|
"name": "@deserialize/swap-sdk",
|
3
|
-
"version": "0.0
|
3
|
+
"version": "1.0.0",
|
4
4
|
"description": "Swap SDK for the deserialize aggregator",
|
5
5
|
"main": "dist/index.js",
|
6
6
|
"types": "dist/index.d.ts",
|
7
7
|
"scripts": {
|
8
8
|
"test": "echo \"Error: no test specified\" && exit 1",
|
9
9
|
"build": "tsc",
|
10
|
-
"publish": "npm run build && npm publish --access=public"
|
10
|
+
"publish:sdk": "npm run build && npm publish --access=public"
|
11
11
|
},
|
12
12
|
"repository": {
|
13
13
|
"type": "git",
|
package/src/swapSDK.ts
CHANGED
@@ -16,16 +16,16 @@ import { handleSimulationError } from "./errors";
|
|
16
16
|
* Parameters to request a swap.
|
17
17
|
*/
|
18
18
|
export interface SwapRequestParams {
|
19
|
-
/** User
|
19
|
+
/** User's public key */
|
20
20
|
publicKey: PublicKey;
|
21
|
-
/** Token A
|
21
|
+
/** Token A's address */
|
22
22
|
tokenA: PublicKey;
|
23
|
-
/** Token B
|
23
|
+
/** Token B's address */
|
24
24
|
tokenB: PublicKey;
|
25
25
|
/** Amount of Token A to swap (in human-readable units) */
|
26
26
|
amountIn: number;
|
27
|
-
/** DEX identifier –
|
28
|
-
dexId:
|
27
|
+
/** DEX identifier – "INVARIANT", "ORCA", or "ALL" */
|
28
|
+
dexId: DexIdTypes;
|
29
29
|
/**
|
30
30
|
* This is used to set options like limit the swap to just two hops to
|
31
31
|
* prevent errors like TooManyAccountLocks
|
@@ -37,28 +37,37 @@ export interface RouteOptions {
|
|
37
37
|
reduceToTwoHops: boolean;
|
38
38
|
}
|
39
39
|
|
40
|
+
export type GetTokenMintBalanceType = {
|
41
|
+
mint: string;
|
42
|
+
balanceUiAmount: number;
|
43
|
+
};
|
44
|
+
|
40
45
|
/**
|
41
46
|
* Result from the swapTx method.
|
42
47
|
*/
|
43
48
|
export interface SwapTxResult {
|
44
|
-
/**
|
49
|
+
/** Fully constructed VersionedTransaction ready for signing */
|
45
50
|
transaction: VersionedTransaction;
|
46
|
-
/**
|
51
|
+
/** Raw transaction data in base64 encoding */
|
52
|
+
serializedTransactions: string;
|
53
|
+
/** Output amount in token decimals */
|
47
54
|
amountOut: number;
|
48
|
-
/**
|
55
|
+
/** Human-readable output amount */
|
49
56
|
amountOutUi: number;
|
50
|
-
/**
|
51
|
-
|
57
|
+
/** Price of Token A in terms of Token B */
|
58
|
+
pairPrice: number;
|
59
|
+
/** Swap route details */
|
60
|
+
routePlan: Array<{
|
52
61
|
tokenA: PublicKey;
|
53
62
|
tokenB: PublicKey;
|
54
|
-
dexId:
|
55
|
-
}
|
56
|
-
/**
|
63
|
+
dexId: DexIdTypes;
|
64
|
+
}>;
|
65
|
+
/** Associated lookup accounts */
|
57
66
|
lookupAccounts: PublicKey[];
|
58
|
-
/**
|
67
|
+
/** Required transaction signers */
|
59
68
|
signers: Keypair[];
|
60
|
-
|
61
|
-
|
69
|
+
/** Protocol fee percentage */
|
70
|
+
feeRate: number;
|
62
71
|
}
|
63
72
|
|
64
73
|
/**
|
@@ -95,6 +104,25 @@ export interface SwapIxResult {
|
|
95
104
|
signers: string[];
|
96
105
|
}
|
97
106
|
|
107
|
+
/**
|
108
|
+
* Response from the quote endpoint
|
109
|
+
*/
|
110
|
+
export interface QuoteResponse {
|
111
|
+
tokenA: string;
|
112
|
+
tokenB: string;
|
113
|
+
amountIn: string;
|
114
|
+
amountOut: string;
|
115
|
+
tokenPrice: string;
|
116
|
+
priceImpact: string;
|
117
|
+
feeRate: string;
|
118
|
+
routePlan: Array<{
|
119
|
+
tokenA: string;
|
120
|
+
tokenB: string;
|
121
|
+
dexId: DexIdTypes;
|
122
|
+
}>;
|
123
|
+
dexId: DexIdTypes;
|
124
|
+
}
|
125
|
+
|
98
126
|
/**
|
99
127
|
* Token details returned from the /tokenList endpoint.
|
100
128
|
*/
|
@@ -109,60 +137,99 @@ export interface Token {
|
|
109
137
|
}
|
110
138
|
|
111
139
|
/**
|
112
|
-
*
|
140
|
+
* Balance Check Parameters
|
141
|
+
*/
|
142
|
+
export interface BalanceCheckParams {
|
143
|
+
/** User's wallet address in base58 */
|
144
|
+
userAddress: string;
|
145
|
+
/** Token mint addresses to check */
|
146
|
+
tokenMints: string[];
|
147
|
+
}
|
148
|
+
|
149
|
+
/**
|
150
|
+
* SwapSDK simplifies interaction with the decentralized exchange API, handling swaps, token data, and balance checks.
|
151
|
+
*
|
152
|
+
* Key Features:
|
153
|
+
* - Get swap quotes to preview expected outcomes
|
154
|
+
* - Build swap transactions with automatic route finding
|
155
|
+
* - Get underlying swap instructions for custom transaction handling
|
156
|
+
* - Retrieve token list and price data
|
157
|
+
* - Check token balances
|
158
|
+
* - Transaction simulation
|
113
159
|
*
|
114
160
|
* Usage:
|
115
161
|
* ```ts
|
116
|
-
* import { SwapSDK } from "./SwapSDK";
|
117
|
-
* import { PublicKey } from "@solana/web3.js";
|
162
|
+
* import { SwapSDK, DEX_IDS } from "./SwapSDK";
|
163
|
+
* import { PublicKey, Connection } from "@solana/web3.js";
|
118
164
|
*
|
119
|
-
* const sdk = new SwapSDK(
|
165
|
+
* const sdk = new SwapSDK(); // Uses default production URL
|
166
|
+
* const connection = new Connection("https://api.mainnet-beta.solana.com");
|
120
167
|
*
|
121
|
-
* async function
|
122
|
-
*
|
123
|
-
*
|
168
|
+
* async function fullSwapFlow() {
|
169
|
+
* // Example swap parameters
|
170
|
+
* const swapParams = {
|
171
|
+
* publicKey: new PublicKey("UserPublicKeyBase58"),
|
124
172
|
* tokenA: new PublicKey("GU7NS9xCwgNPiAdJ69iusFrRfawjDDPjeMBovhV1d4kn"),
|
125
173
|
* tokenB: new PublicKey("CEBP3CqAbW4zdZA57H2wfaSG1QNdzQ72GiQEbQXyW9Tm"),
|
126
174
|
* amountIn: 10.0,
|
127
|
-
* dexId:
|
175
|
+
* dexId: DEX_IDS.INVARIANT,
|
176
|
+
* options: { reduceToTwoHops: false }
|
128
177
|
* };
|
129
178
|
*
|
130
|
-
* //
|
131
|
-
* const
|
132
|
-
* console.log("
|
179
|
+
* // Get a quote first to see expected outcome
|
180
|
+
* const quote = await sdk.getSwapQuote(swapParams);
|
181
|
+
* console.log("Expected output amount:", quote.amountOut);
|
182
|
+
* console.log("Price impact:", quote.priceImpact);
|
183
|
+
*
|
184
|
+
* // Get complete swap transaction
|
185
|
+
* const txResult = await sdk.swapTx({
|
186
|
+
* ...swapParams,
|
187
|
+
* quote: quote
|
188
|
+
* });
|
189
|
+
* console.log("Serialized Transaction:", txResult.serializedTransactions);
|
133
190
|
*
|
134
|
-
* //
|
135
|
-
* const
|
136
|
-
* console.log("
|
191
|
+
* // Simulate transaction before sending
|
192
|
+
* const simulation = await sdk.simulateTransaction(connection, txResult.transaction);
|
193
|
+
* console.log("Simulation Result:", simulation);
|
137
194
|
*
|
138
|
-
* //
|
195
|
+
* // Get token list
|
139
196
|
* const tokens = await sdk.tokenList();
|
140
|
-
* console.log("Tokens:", tokens);
|
197
|
+
* console.log("Available Tokens:", tokens);
|
198
|
+
*
|
199
|
+
* // Check balances
|
200
|
+
* const balances = await sdk.getTokenMintBalance({
|
201
|
+
* userAddress: swapParams.publicKey.toBase58(),
|
202
|
+
* tokenMints: [swapParams.tokenA.toBase58(), swapParams.tokenB.toBase58()]
|
203
|
+
* });
|
204
|
+
* console.log("User Balances:", balances);
|
141
205
|
*
|
142
|
-
* //
|
143
|
-
* const
|
144
|
-
* console.log("
|
206
|
+
* // Get token price
|
207
|
+
* const solPrice = await sdk.tokenPrice("So11111111111111111111111111111111111111112");
|
208
|
+
* console.log("SOL Price:", solPrice);
|
145
209
|
* }
|
146
210
|
*
|
147
|
-
*
|
211
|
+
* fullSwapFlow();
|
148
212
|
* ```
|
149
213
|
*/
|
150
214
|
export class SwapSDK {
|
151
215
|
private baseUrl: string;
|
216
|
+
|
152
217
|
constructor(baseUrl?: string) {
|
153
218
|
this.baseUrl = baseUrl || BASE_URL;
|
154
219
|
}
|
155
220
|
|
221
|
+
base58 = base58;
|
222
|
+
web3 = web3;
|
223
|
+
DEX_IDS = DEX_IDS;
|
224
|
+
|
156
225
|
/**
|
157
|
-
*
|
226
|
+
* Gets a swap quote without executing the swap
|
158
227
|
*
|
159
|
-
* @param params Swap parameters
|
160
|
-
* @returns
|
228
|
+
* @param params Swap parameters
|
229
|
+
* @returns Quote information including expected output amount and price impact
|
161
230
|
*/
|
162
|
-
|
163
|
-
// Prepare the payload by converting PublicKeys to base58 strings
|
231
|
+
async getSwapQuote(params: SwapRequestParams): Promise<QuoteResponse> {
|
164
232
|
const body = {
|
165
|
-
publicKey: params.publicKey.toBase58(),
|
166
233
|
tokenA: params.tokenA.toBase58(),
|
167
234
|
tokenB: params.tokenB.toBase58(),
|
168
235
|
amountIn: params.amountIn.toString(),
|
@@ -170,7 +237,7 @@ export class SwapSDK {
|
|
170
237
|
options: params.options,
|
171
238
|
};
|
172
239
|
|
173
|
-
const response = await fetch(`${this.baseUrl}/
|
240
|
+
const response = await fetch(`${this.baseUrl}/quote`, {
|
174
241
|
method: "POST",
|
175
242
|
headers: {
|
176
243
|
"Content-Type": "application/json",
|
@@ -182,20 +249,55 @@ export class SwapSDK {
|
|
182
249
|
throw new Error(`API Error: ${response.statusText}`);
|
183
250
|
}
|
184
251
|
|
185
|
-
return response.json();
|
252
|
+
return await response.json();
|
186
253
|
}
|
187
254
|
|
188
|
-
|
189
|
-
|
255
|
+
/**
|
256
|
+
* Executes a swap based on a previously obtained quote
|
257
|
+
*
|
258
|
+
* @param params Swap parameters including the quote
|
259
|
+
* @returns Transaction and output details
|
260
|
+
*/
|
261
|
+
async executeSwap(params: {
|
262
|
+
publicKey: PublicKey;
|
263
|
+
quote: QuoteResponse;
|
264
|
+
}): Promise<any> {
|
265
|
+
const body = {
|
266
|
+
publicKey: params.publicKey.toBase58(),
|
267
|
+
quote: params.quote,
|
268
|
+
};
|
269
|
+
|
270
|
+
const response = await fetch(`${this.baseUrl}/swap`, {
|
271
|
+
method: "POST",
|
272
|
+
headers: {
|
273
|
+
"Content-Type": "application/json",
|
274
|
+
},
|
275
|
+
body: JSON.stringify(body),
|
276
|
+
});
|
277
|
+
|
278
|
+
if (!response.ok) {
|
279
|
+
throw new Error(`API Error: ${response.statusText}`);
|
280
|
+
}
|
281
|
+
|
282
|
+
return await response.json();
|
283
|
+
}
|
190
284
|
|
191
285
|
/**
|
192
286
|
* Calls the swap endpoint and returns a fully constructed Transaction.
|
287
|
+
* This method is a wrapper that gets a quote first, then executes the swap.
|
193
288
|
*
|
194
289
|
* @param params Swap parameters.
|
195
290
|
* @returns A promise that resolves to a SwapTxResult.
|
196
291
|
*/
|
197
292
|
async swapTx(params: SwapRequestParams): Promise<SwapTxResult> {
|
198
|
-
|
293
|
+
// First get a quote
|
294
|
+
const quote = await this.getSwapQuote(params);
|
295
|
+
|
296
|
+
// Then execute the swap with the quote
|
297
|
+
const data = await this.executeSwap({
|
298
|
+
publicKey: params.publicKey,
|
299
|
+
quote,
|
300
|
+
});
|
199
301
|
|
200
302
|
// Convert the base64-encoded transaction into a VersionedTransaction.
|
201
303
|
const txBuffer = Buffer.from(data.transaction, "base64");
|
@@ -207,36 +309,48 @@ export class SwapSDK {
|
|
207
309
|
);
|
208
310
|
|
209
311
|
// Convert the route plan tokens into PublicKey objects.
|
210
|
-
const routePlan = (
|
312
|
+
const routePlan = (quote.routePlan || []).map((rp: any) => ({
|
211
313
|
tokenA: new PublicKey(rp.tokenA),
|
212
314
|
tokenB: new PublicKey(rp.tokenB),
|
213
|
-
dexId: rp.dexId,
|
315
|
+
dexId: rp.dexId as DexIdTypes,
|
214
316
|
}));
|
215
317
|
|
216
|
-
// Convert each
|
318
|
+
// Convert each base58-encoded signer secret into a Keypair.
|
217
319
|
const signers = data.signers.map((s: string) =>
|
218
320
|
Keypair.fromSecretKey(base58.decode(s))
|
219
321
|
);
|
322
|
+
|
220
323
|
transaction.sign(signers);
|
324
|
+
|
221
325
|
return {
|
222
326
|
transaction,
|
223
327
|
serializedTransactions: data.transaction,
|
224
328
|
amountOut: Number(data.amountOut),
|
225
|
-
amountOutUi: Number(
|
329
|
+
amountOutUi: Number(quote.amountOut),
|
330
|
+
pairPrice: Number(quote.tokenPrice),
|
226
331
|
routePlan,
|
227
332
|
lookupAccounts,
|
228
333
|
signers,
|
334
|
+
feeRate: parseFloat(quote.feeRate),
|
229
335
|
};
|
230
336
|
}
|
231
337
|
|
232
338
|
/**
|
233
339
|
* Calls the swap endpoint and returns the raw instructions and related data.
|
340
|
+
* This method is a wrapper that gets a quote first, then executes the swap to get instructions.
|
234
341
|
*
|
235
342
|
* @param params Swap parameters.
|
236
343
|
* @returns A promise that resolves to a SwapIxResult.
|
237
344
|
*/
|
238
345
|
async swapIx(params: SwapRequestParams): Promise<SwapIxResult> {
|
239
|
-
|
346
|
+
// First get a quote
|
347
|
+
const quote = await this.getSwapQuote(params);
|
348
|
+
|
349
|
+
// Then execute the swap with the quote
|
350
|
+
const data = await this.executeSwap({
|
351
|
+
publicKey: params.publicKey,
|
352
|
+
quote,
|
353
|
+
});
|
240
354
|
|
241
355
|
// Convert lookup accounts from strings to PublicKey objects.
|
242
356
|
const lookupAccounts: PublicKey[] = (data.lookUpAccounts || []).map(
|
@@ -244,7 +358,7 @@ export class SwapSDK {
|
|
244
358
|
);
|
245
359
|
|
246
360
|
// Convert the route plan tokens into PublicKey objects.
|
247
|
-
const routePlan = (
|
361
|
+
const routePlan = (quote.routePlan || []).map((rp: any) => ({
|
248
362
|
tokenA: new PublicKey(rp.tokenA),
|
249
363
|
tokenB: new PublicKey(rp.tokenB),
|
250
364
|
dexId: rp.dexId,
|
@@ -266,7 +380,7 @@ export class SwapSDK {
|
|
266
380
|
return {
|
267
381
|
instructionGroups,
|
268
382
|
amountOut: Number(data.amountOut),
|
269
|
-
amountOutUi: Number(
|
383
|
+
amountOutUi: Number(quote.amountOut),
|
270
384
|
routePlan,
|
271
385
|
lookupAccounts,
|
272
386
|
signers: data.signers,
|
@@ -284,7 +398,7 @@ export class SwapSDK {
|
|
284
398
|
throw new Error(`API Error: ${response.statusText}`);
|
285
399
|
}
|
286
400
|
const data = await response.json();
|
287
|
-
return data.
|
401
|
+
return data.map((token: any) => ({
|
288
402
|
name: token.metadata.name,
|
289
403
|
symbol: token.metadata.symbol,
|
290
404
|
address: token.address,
|
@@ -308,6 +422,50 @@ export class SwapSDK {
|
|
308
422
|
const data = await response.json();
|
309
423
|
return Number(data.price);
|
310
424
|
}
|
425
|
+
|
426
|
+
/**
|
427
|
+
* Gets the token balances for a given wallet
|
428
|
+
*
|
429
|
+
* @param params User address and token mints to check
|
430
|
+
* @returns Array of token balances
|
431
|
+
*/
|
432
|
+
async getTokenMintBalance(
|
433
|
+
params: BalanceCheckParams
|
434
|
+
): Promise<GetTokenMintBalanceType[]> {
|
435
|
+
try {
|
436
|
+
const response = await fetch(`${this.baseUrl}/getMintBalances`, {
|
437
|
+
method: "POST",
|
438
|
+
headers: {
|
439
|
+
"Content-Type": "application/json",
|
440
|
+
},
|
441
|
+
body: JSON.stringify(params),
|
442
|
+
});
|
443
|
+
|
444
|
+
if (!response.ok) {
|
445
|
+
throw new Error(`HTTP error! status: ${response.status}`);
|
446
|
+
}
|
447
|
+
|
448
|
+
const data = await response.json();
|
449
|
+
return data as GetTokenMintBalanceType[];
|
450
|
+
} catch (error) {
|
451
|
+
console.error("Error fetching token balances:", error);
|
452
|
+
throw error;
|
453
|
+
}
|
454
|
+
}
|
455
|
+
|
456
|
+
/**
|
457
|
+
* Health check for the API
|
458
|
+
*
|
459
|
+
* @returns A string "Pong" if the service is operational
|
460
|
+
*/
|
461
|
+
async ping(): Promise<string> {
|
462
|
+
const response = await fetch(`${this.baseUrl}/ping`);
|
463
|
+
if (!response.ok) {
|
464
|
+
throw new Error(`API Error: ${response.statusText}`);
|
465
|
+
}
|
466
|
+
return await response.text();
|
467
|
+
}
|
468
|
+
|
311
469
|
/**
|
312
470
|
* Simulates a transaction.
|
313
471
|
* @param connection The connection to use.
|
@@ -346,4 +504,12 @@ export class SwapSDK {
|
|
346
504
|
}
|
347
505
|
}
|
348
506
|
|
349
|
-
export const
|
507
|
+
export const DEX_IDS = {
|
508
|
+
ORCA: "ORCA",
|
509
|
+
INVARIANT: "INVARIANT",
|
510
|
+
ALL: "ALL",
|
511
|
+
} as const;
|
512
|
+
|
513
|
+
export type DexIdTypes = (typeof DEX_IDS)[keyof typeof DEX_IDS];
|
514
|
+
|
515
|
+
export const BASE_URL = "https://api.deserialize.xyz";
|