@deserialize/swap-sdk 0.0.2

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/.env ADDED
@@ -0,0 +1 @@
1
+ DEV_KEY=""
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # deserialize-swap-sdk
@@ -0,0 +1 @@
1
+ export * from "./swapSDK";
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./swapSDK"), exports);
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,4CAA0B"}
@@ -0,0 +1,142 @@
1
+ import web3, { Keypair, PublicKey, TransactionInstruction, VersionedTransaction } from "@solana/web3.js";
2
+ /**
3
+ * Parameters to request a swap.
4
+ */
5
+ export interface SwapRequestParams {
6
+ /** User’s public key */
7
+ publicKey: PublicKey;
8
+ /** Token A’s address */
9
+ tokenA: PublicKey;
10
+ /** Token B’s address */
11
+ tokenB: PublicKey;
12
+ /** Amount of Token A to swap (in human-readable units) */
13
+ amountIn: number;
14
+ /** DEX identifier – currently only "INVARIANT" is supported */
15
+ dexId: string;
16
+ /** This is used to set options like limit the swap to just two hops to
17
+ * prevent errors like TooManyAccountLocks
18
+ */
19
+ options?: RouteOptions;
20
+ }
21
+ export interface RouteOptions {
22
+ reduceToTwoHops: boolean;
23
+ }
24
+ /**
25
+ * Result from the swapTx method.
26
+ */
27
+ export interface SwapTxResult {
28
+ /** The unsigned Transaction object ready to be signed and submitted */
29
+ transaction: VersionedTransaction;
30
+ /** The raw output amount (in the smallest denomination) */
31
+ amountOut: number;
32
+ /** The human-readable output amount (after adjusting decimals) */
33
+ amountOutUi: number;
34
+ /** The swap route plan with tokens converted to PublicKey objects */
35
+ routePlan: {
36
+ tokenA: PublicKey;
37
+ tokenB: PublicKey;
38
+ dexId: string;
39
+ }[];
40
+ /** Lookup accounts converted to PublicKey objects */
41
+ lookupAccounts: PublicKey[];
42
+ /** Any signers returned (encoded as base64 strings) */
43
+ signers: Keypair[];
44
+ }
45
+ /**
46
+ * Structure representing a group of instructions from the API.
47
+ */
48
+ export interface InstructionGroup {
49
+ /** The main instructions (converted to TransactionInstruction objects) */
50
+ instructions: TransactionInstruction[];
51
+ /** Any cleanup instructions (converted to TransactionInstruction objects) */
52
+ cleanupInstructions: TransactionInstruction[];
53
+ /** Signers associated with this group (as base64 encoded strings) */
54
+ signers: string[];
55
+ }
56
+ /**
57
+ * Result from the swapIx method.
58
+ */
59
+ export interface SwapIxResult {
60
+ /** The instruction groups as returned from the API (with instructions converted) */
61
+ instructionGroups: InstructionGroup[];
62
+ /** The raw output amount (in the smallest denomination) */
63
+ amountOut: number;
64
+ /** The human-readable output amount (after adjusting decimals) */
65
+ amountOutUi: number;
66
+ /** The swap route plan with tokens converted to PublicKey objects */
67
+ routePlan: {
68
+ tokenA: PublicKey;
69
+ tokenB: PublicKey;
70
+ dexId: string;
71
+ }[];
72
+ /** Lookup accounts converted to PublicKey objects */
73
+ lookupAccounts: PublicKey[];
74
+ /** Any top-level signers returned (as base64 encoded strings) */
75
+ signers: string[];
76
+ }
77
+ /**
78
+ * SwapSDK simplifies calling the swap endpoint.
79
+ *
80
+ * Usage:
81
+ * ```ts
82
+ * import { SwapSDK } from "./SwapSDK";
83
+ * import { PublicKey } from "@solana/web3.js";
84
+ *
85
+ * const sdk = new SwapSDK("http://localhost:3333");
86
+ *
87
+ * async function runSwap() {
88
+ * const params = {
89
+ * publicKey: new PublicKey("UserPublicKeyInBase58"),
90
+ * tokenA: new PublicKey("GU7NS9xCwgNPiAdJ69iusFrRfawjDDPjeMBovhV1d4kn"),
91
+ * tokenB: new PublicKey("CEBP3CqAbW4zdZA57H2wfaSG1QNdzQ72GiQEbQXyW9Tm"),
92
+ * amountIn: 10.0,
93
+ * dexId: "INVARIANT" as const,
94
+ * };
95
+ *
96
+ * // To get the full transaction:
97
+ * const txResult = await sdk.swapTx(params);
98
+ * console.log("Transaction:", txResult.transaction);
99
+ *
100
+ * // Or, to get the underlying instructions and additional data:
101
+ * const ixResult = await sdk.swapIx(params);
102
+ * console.log("Instructions:", ixResult.instructionGroups);
103
+ * }
104
+ *
105
+ * runSwap();
106
+ * ```
107
+ */
108
+ export declare class SwapSDK {
109
+ private baseUrl;
110
+ constructor(baseUrl?: string);
111
+ /**
112
+ * Calls the bestSwapRoute endpoint with the provided parameters.
113
+ *
114
+ * @param params Swap parameters.
115
+ * @returns The JSON-parsed API response.
116
+ */
117
+ private callSwapEndpoint;
118
+ base58: import("base-x").default.BaseConverter;
119
+ web3: typeof web3;
120
+ /**
121
+ * Calls the swap endpoint and returns a fully constructed Transaction.
122
+ *
123
+ * @param params Swap parameters.
124
+ * @returns A promise that resolves to a SwapTxResult.
125
+ */
126
+ swapTx(params: SwapRequestParams): Promise<SwapTxResult>;
127
+ /**
128
+ * Calls the swap endpoint and returns the raw instructions and related data.
129
+ *
130
+ * @param params Swap parameters.
131
+ * @returns A promise that resolves to a SwapIxResult.
132
+ */
133
+ swapIx(params: SwapRequestParams): Promise<SwapIxResult>;
134
+ /**
135
+ * Converts an API instruction (in plain JSON format) to a TransactionInstruction.
136
+ *
137
+ * @param apiInst The API instruction.
138
+ * @returns A TransactionInstruction.
139
+ */
140
+ private convertAPIInstruction;
141
+ }
142
+ export declare const BASE_URL = "http://170.75.162.89:3333/";
@@ -0,0 +1,191 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.BASE_URL = exports.SwapSDK = void 0;
40
+ // SwapSDK.ts
41
+ const web3_js_1 = __importStar(require("@solana/web3.js"));
42
+ const bs58_1 = __importDefault(require("bs58"));
43
+ /**
44
+ * SwapSDK simplifies calling the swap endpoint.
45
+ *
46
+ * Usage:
47
+ * ```ts
48
+ * import { SwapSDK } from "./SwapSDK";
49
+ * import { PublicKey } from "@solana/web3.js";
50
+ *
51
+ * const sdk = new SwapSDK("http://localhost:3333");
52
+ *
53
+ * async function runSwap() {
54
+ * const params = {
55
+ * publicKey: new PublicKey("UserPublicKeyInBase58"),
56
+ * tokenA: new PublicKey("GU7NS9xCwgNPiAdJ69iusFrRfawjDDPjeMBovhV1d4kn"),
57
+ * tokenB: new PublicKey("CEBP3CqAbW4zdZA57H2wfaSG1QNdzQ72GiQEbQXyW9Tm"),
58
+ * amountIn: 10.0,
59
+ * dexId: "INVARIANT" as const,
60
+ * };
61
+ *
62
+ * // To get the full transaction:
63
+ * const txResult = await sdk.swapTx(params);
64
+ * console.log("Transaction:", txResult.transaction);
65
+ *
66
+ * // Or, to get the underlying instructions and additional data:
67
+ * const ixResult = await sdk.swapIx(params);
68
+ * console.log("Instructions:", ixResult.instructionGroups);
69
+ * }
70
+ *
71
+ * runSwap();
72
+ * ```
73
+ */
74
+ class SwapSDK {
75
+ constructor(baseUrl) {
76
+ this.base58 = bs58_1.default;
77
+ this.web3 = web3_js_1.default;
78
+ this.baseUrl = baseUrl || exports.BASE_URL;
79
+ }
80
+ /**
81
+ * Calls the bestSwapRoute endpoint with the provided parameters.
82
+ *
83
+ * @param params Swap parameters.
84
+ * @returns The JSON-parsed API response.
85
+ */
86
+ async callSwapEndpoint(params) {
87
+ // Prepare the payload by converting PublicKeys to base58 strings
88
+ const body = {
89
+ publicKey: params.publicKey.toBase58(),
90
+ tokenA: params.tokenA.toBase58(),
91
+ tokenB: params.tokenB.toBase58(),
92
+ amountIn: params.amountIn.toString(),
93
+ dexId: params.dexId,
94
+ options: params.options,
95
+ };
96
+ const response = await fetch(`${this.baseUrl}/bestSwapRoute`, {
97
+ method: "POST",
98
+ headers: {
99
+ "Content-Type": "application/json",
100
+ },
101
+ body: JSON.stringify(body),
102
+ });
103
+ if (!response.ok) {
104
+ throw new Error(`API Error: ${response.statusText}`);
105
+ }
106
+ return response.json();
107
+ }
108
+ /**
109
+ * Calls the swap endpoint and returns a fully constructed Transaction.
110
+ *
111
+ * @param params Swap parameters.
112
+ * @returns A promise that resolves to a SwapTxResult.
113
+ */
114
+ async swapTx(params) {
115
+ const data = await this.callSwapEndpoint(params);
116
+ // Convert the base64-encoded transaction into a Transaction object.
117
+ const txBuffer = Buffer.from(data.transaction, "base64");
118
+ const transaction = web3_js_1.VersionedTransaction.deserialize(txBuffer);
119
+ // Convert lookup accounts from strings to PublicKey objects.
120
+ const lookupAccounts = (data.lookUpAccounts || []).map((addr) => new web3_js_1.PublicKey(addr));
121
+ // Convert the route plan tokens into PublicKey objects.
122
+ const routePlan = (data.routePlan || []).map((rp) => ({
123
+ tokenA: new web3_js_1.PublicKey(rp.tokenA),
124
+ tokenB: new web3_js_1.PublicKey(rp.tokenB),
125
+ dexId: rp.dexId,
126
+ }));
127
+ const signers = data.signers.map((s) => {
128
+ return web3_js_1.Keypair.fromSecretKey(bs58_1.default.decode(s));
129
+ });
130
+ transaction.sign(signers);
131
+ return {
132
+ transaction,
133
+ amountOut: Number(data.amountOut),
134
+ amountOutUi: Number(data.amountOutUi),
135
+ routePlan,
136
+ lookupAccounts,
137
+ signers: signers,
138
+ };
139
+ }
140
+ /**
141
+ * Calls the swap endpoint and returns the raw instructions and related data.
142
+ *
143
+ * @param params Swap parameters.
144
+ * @returns A promise that resolves to a SwapIxResult.
145
+ */
146
+ async swapIx(params) {
147
+ const data = await this.callSwapEndpoint(params);
148
+ // Convert lookup accounts from strings to PublicKey objects.
149
+ const lookupAccounts = (data.lookUpAccounts || []).map((addr) => new web3_js_1.PublicKey(addr));
150
+ // Convert the route plan tokens into PublicKey objects.
151
+ const routePlan = (data.routePlan || []).map((rp) => ({
152
+ tokenA: new web3_js_1.PublicKey(rp.tokenA),
153
+ tokenB: new web3_js_1.PublicKey(rp.tokenB),
154
+ dexId: rp.dexId,
155
+ }));
156
+ // Convert each API instruction group into properly formatted objects.
157
+ const instructionGroups = (data.inXs || []).map((group) => ({
158
+ instructions: (group.instructions || []).map((inst) => this.convertAPIInstruction(inst)),
159
+ cleanupInstructions: (group.cleanupInstructions || []).map((inst) => this.convertAPIInstruction(inst)),
160
+ signers: group.signers || [],
161
+ }));
162
+ return {
163
+ instructionGroups,
164
+ amountOut: Number(data.amountOut),
165
+ amountOutUi: Number(data.amountOutUi),
166
+ routePlan,
167
+ lookupAccounts,
168
+ signers: data.signers,
169
+ };
170
+ }
171
+ /**
172
+ * Converts an API instruction (in plain JSON format) to a TransactionInstruction.
173
+ *
174
+ * @param apiInst The API instruction.
175
+ * @returns A TransactionInstruction.
176
+ */
177
+ convertAPIInstruction(apiInst) {
178
+ return new web3_js_1.TransactionInstruction({
179
+ keys: (apiInst.keys || []).map((key) => ({
180
+ pubkey: new web3_js_1.PublicKey(key.pubkey),
181
+ isSigner: key.isSigner,
182
+ isWritable: key.isWritable,
183
+ })),
184
+ programId: new web3_js_1.PublicKey(apiInst.programId),
185
+ data: Buffer.from(apiInst.data),
186
+ });
187
+ }
188
+ }
189
+ exports.SwapSDK = SwapSDK;
190
+ exports.BASE_URL = "http://170.75.162.89:3333/";
191
+ //# sourceMappingURL=swapSDK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"swapSDK.js","sourceRoot":"","sources":["../src/swapSDK.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,aAAa;AACb,2DAOyB;AACzB,gDAA0B;AA+E1B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,MAAa,OAAO;IAElB,YAAY,OAAgB;QAoC5B,WAAM,GAAG,cAAM,CAAC;QAEhB,SAAI,GAAG,iBAAI,CAAC;QArCV,IAAI,CAAC,OAAO,GAAG,OAAO,IAAI,gBAAQ,CAAC;IACrC,CAAC;IAED;;;;;OAKG;IACK,KAAK,CAAC,gBAAgB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,UAAU;aAC3B,CAAC,CAAC;YACH,SAAS,EAAE,IAAI,mBAAS,CAAC,OAAO,CAAC,SAAS,CAAC;YAC3C,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;SAChC,CAAC,CAAC;IACL,CAAC;CACF;AA9ID,0BA8IC;AAEY,QAAA,QAAQ,GAAG,4BAA4B,CAAC"}
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@deserialize/swap-sdk",
3
+ "version": "0.0.2",
4
+ "description": "Swap SDK for the deserialize aggregator",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "scripts": {
8
+ "test": "echo \"Error: no test specified\" && exit 1",
9
+ "build": "tsc"
10
+ },
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/Bravark/deserialize-swap-sdk.git"
14
+ },
15
+ "keywords": [
16
+ "deserialize",
17
+ "deserialise",
18
+ "eclipse",
19
+ "aggregator",
20
+ "jupiter",
21
+ "pouch"
22
+ ],
23
+ "author": "0xazach",
24
+ "license": "MIT",
25
+ "bugs": {
26
+ "url": "https://github.com/Bravark/deserialize-swap-sdk/issues"
27
+ },
28
+ "homepage": "https://github.com/Bravark/deserialize-swap-sdk#readme",
29
+ "dependencies": {
30
+ "@solana/web3.js": "^1.98.0",
31
+ "bs58": "^6.0.0",
32
+ "dotenv": "^16.4.7"
33
+ }
34
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./swapSDK";
package/src/swapSDK.ts ADDED
@@ -0,0 +1,264 @@
1
+ // SwapSDK.ts
2
+ import web3, {
3
+ Keypair,
4
+ PublicKey,
5
+ Transaction,
6
+ TransactionInstruction,
7
+ VersionedMessage,
8
+ VersionedTransaction,
9
+ } from "@solana/web3.js";
10
+ import base58 from "bs58";
11
+ /**
12
+ * Parameters to request a swap.
13
+ */
14
+ export interface SwapRequestParams {
15
+ /** User’s public key */
16
+ publicKey: PublicKey;
17
+ /** Token A’s address */
18
+ tokenA: PublicKey;
19
+ /** Token B’s address */
20
+ tokenB: PublicKey;
21
+ /** Amount of Token A to swap (in human-readable units) */
22
+ amountIn: number;
23
+ /** DEX identifier – currently only "INVARIANT" is supported */
24
+ dexId: string;
25
+ /** This is used to set options like limit the swap to just two hops to
26
+ * prevent errors like TooManyAccountLocks
27
+ */
28
+ options?: RouteOptions;
29
+ }
30
+ export interface RouteOptions {
31
+ reduceToTwoHops: boolean;
32
+ }
33
+ /**
34
+ * Result from the swapTx method.
35
+ */
36
+ export interface SwapTxResult {
37
+ /** The unsigned Transaction object ready to be signed and submitted */
38
+ transaction: VersionedTransaction;
39
+ /** The raw output amount (in the smallest denomination) */
40
+ amountOut: number;
41
+ /** The human-readable output amount (after adjusting decimals) */
42
+ amountOutUi: number;
43
+ /** The swap route plan with tokens converted to PublicKey objects */
44
+ routePlan: {
45
+ tokenA: PublicKey;
46
+ tokenB: PublicKey;
47
+ dexId: string;
48
+ }[];
49
+ /** Lookup accounts converted to PublicKey objects */
50
+ lookupAccounts: PublicKey[];
51
+ /** Any signers returned (encoded as base64 strings) */
52
+ signers: Keypair[];
53
+ }
54
+
55
+ /**
56
+ * Structure representing a group of instructions from the API.
57
+ */
58
+ export interface InstructionGroup {
59
+ /** The main instructions (converted to TransactionInstruction objects) */
60
+ instructions: TransactionInstruction[];
61
+ /** Any cleanup instructions (converted to TransactionInstruction objects) */
62
+ cleanupInstructions: TransactionInstruction[];
63
+ /** Signers associated with this group (as base64 encoded strings) */
64
+ signers: string[];
65
+ }
66
+
67
+ /**
68
+ * Result from the swapIx method.
69
+ */
70
+ export interface SwapIxResult {
71
+ /** The instruction groups as returned from the API (with instructions converted) */
72
+ instructionGroups: InstructionGroup[];
73
+ /** The raw output amount (in the smallest denomination) */
74
+ amountOut: number;
75
+ /** The human-readable output amount (after adjusting decimals) */
76
+ amountOutUi: number;
77
+ /** The swap route plan with tokens converted to PublicKey objects */
78
+ routePlan: {
79
+ tokenA: PublicKey;
80
+ tokenB: PublicKey;
81
+ dexId: string;
82
+ }[];
83
+ /** Lookup accounts converted to PublicKey objects */
84
+ lookupAccounts: PublicKey[];
85
+ /** Any top-level signers returned (as base64 encoded strings) */
86
+ signers: string[];
87
+ }
88
+
89
+ /**
90
+ * SwapSDK simplifies calling the swap endpoint.
91
+ *
92
+ * Usage:
93
+ * ```ts
94
+ * import { SwapSDK } from "./SwapSDK";
95
+ * import { PublicKey } from "@solana/web3.js";
96
+ *
97
+ * const sdk = new SwapSDK("http://localhost:3333");
98
+ *
99
+ * async function runSwap() {
100
+ * const params = {
101
+ * publicKey: new PublicKey("UserPublicKeyInBase58"),
102
+ * tokenA: new PublicKey("GU7NS9xCwgNPiAdJ69iusFrRfawjDDPjeMBovhV1d4kn"),
103
+ * tokenB: new PublicKey("CEBP3CqAbW4zdZA57H2wfaSG1QNdzQ72GiQEbQXyW9Tm"),
104
+ * amountIn: 10.0,
105
+ * dexId: "INVARIANT" as const,
106
+ * };
107
+ *
108
+ * // To get the full transaction:
109
+ * const txResult = await sdk.swapTx(params);
110
+ * console.log("Transaction:", txResult.transaction);
111
+ *
112
+ * // Or, to get the underlying instructions and additional data:
113
+ * const ixResult = await sdk.swapIx(params);
114
+ * console.log("Instructions:", ixResult.instructionGroups);
115
+ * }
116
+ *
117
+ * runSwap();
118
+ * ```
119
+ */
120
+ export class SwapSDK {
121
+ private baseUrl: string;
122
+ constructor(baseUrl?: string) {
123
+ this.baseUrl = baseUrl || BASE_URL;
124
+ }
125
+
126
+ /**
127
+ * Calls the bestSwapRoute endpoint with the provided parameters.
128
+ *
129
+ * @param params Swap parameters.
130
+ * @returns The JSON-parsed API response.
131
+ */
132
+ private async callSwapEndpoint(params: SwapRequestParams): Promise<any> {
133
+ // Prepare the payload by converting PublicKeys to base58 strings
134
+ const body = {
135
+ publicKey: params.publicKey.toBase58(),
136
+ tokenA: params.tokenA.toBase58(),
137
+ tokenB: params.tokenB.toBase58(),
138
+ amountIn: params.amountIn.toString(),
139
+ dexId: params.dexId,
140
+ options: params.options,
141
+ };
142
+
143
+ const response = await fetch(`${this.baseUrl}/bestSwapRoute`, {
144
+ method: "POST",
145
+ headers: {
146
+ "Content-Type": "application/json",
147
+ },
148
+ body: JSON.stringify(body),
149
+ });
150
+
151
+ if (!response.ok) {
152
+ throw new Error(`API Error: ${response.statusText}`);
153
+ }
154
+
155
+ return response.json();
156
+ }
157
+
158
+ base58 = base58;
159
+
160
+ web3 = web3;
161
+
162
+ /**
163
+ * Calls the swap endpoint and returns a fully constructed Transaction.
164
+ *
165
+ * @param params Swap parameters.
166
+ * @returns A promise that resolves to a SwapTxResult.
167
+ */
168
+ async swapTx(params: SwapRequestParams): Promise<SwapTxResult> {
169
+ const data = await this.callSwapEndpoint(params);
170
+
171
+ // Convert the base64-encoded transaction into a Transaction object.
172
+ const txBuffer = Buffer.from(data.transaction, "base64");
173
+ const transaction = VersionedTransaction.deserialize(txBuffer);
174
+
175
+ // Convert lookup accounts from strings to PublicKey objects.
176
+ const lookupAccounts: PublicKey[] = (data.lookUpAccounts || []).map(
177
+ (addr: string) => new PublicKey(addr)
178
+ );
179
+
180
+ // Convert the route plan tokens into PublicKey objects.
181
+ const routePlan = (data.routePlan || []).map((rp: any) => ({
182
+ tokenA: new PublicKey(rp.tokenA),
183
+ tokenB: new PublicKey(rp.tokenB),
184
+ dexId: rp.dexId,
185
+ }));
186
+
187
+ const signers = data.signers.map((s: string) => {
188
+ return Keypair.fromSecretKey(base58.decode(s));
189
+ });
190
+ transaction.sign(signers);
191
+ return {
192
+ transaction,
193
+ amountOut: Number(data.amountOut),
194
+ amountOutUi: Number(data.amountOutUi),
195
+ routePlan,
196
+ lookupAccounts,
197
+ signers: signers,
198
+ };
199
+ }
200
+
201
+ /**
202
+ * Calls the swap endpoint and returns the raw instructions and related data.
203
+ *
204
+ * @param params Swap parameters.
205
+ * @returns A promise that resolves to a SwapIxResult.
206
+ */
207
+ async swapIx(params: SwapRequestParams): Promise<SwapIxResult> {
208
+ const data = await this.callSwapEndpoint(params);
209
+
210
+ // Convert lookup accounts from strings to PublicKey objects.
211
+ const lookupAccounts: PublicKey[] = (data.lookUpAccounts || []).map(
212
+ (addr: string) => new PublicKey(addr)
213
+ );
214
+
215
+ // Convert the route plan tokens into PublicKey objects.
216
+ const routePlan = (data.routePlan || []).map((rp: any) => ({
217
+ tokenA: new PublicKey(rp.tokenA),
218
+ tokenB: new PublicKey(rp.tokenB),
219
+ dexId: rp.dexId,
220
+ }));
221
+
222
+ // Convert each API instruction group into properly formatted objects.
223
+ const instructionGroups: InstructionGroup[] = (data.inXs || []).map(
224
+ (group: any) => ({
225
+ instructions: (group.instructions || []).map((inst: any) =>
226
+ this.convertAPIInstruction(inst)
227
+ ),
228
+ cleanupInstructions: (group.cleanupInstructions || []).map(
229
+ (inst: any) => this.convertAPIInstruction(inst)
230
+ ),
231
+ signers: group.signers || [],
232
+ })
233
+ );
234
+
235
+ return {
236
+ instructionGroups,
237
+ amountOut: Number(data.amountOut),
238
+ amountOutUi: Number(data.amountOutUi),
239
+ routePlan,
240
+ lookupAccounts,
241
+ signers: data.signers,
242
+ };
243
+ }
244
+
245
+ /**
246
+ * Converts an API instruction (in plain JSON format) to a TransactionInstruction.
247
+ *
248
+ * @param apiInst The API instruction.
249
+ * @returns A TransactionInstruction.
250
+ */
251
+ private convertAPIInstruction(apiInst: any): TransactionInstruction {
252
+ return new TransactionInstruction({
253
+ keys: (apiInst.keys || []).map((key: any) => ({
254
+ pubkey: new PublicKey(key.pubkey),
255
+ isSigner: key.isSigner,
256
+ isWritable: key.isWritable,
257
+ })),
258
+ programId: new PublicKey(apiInst.programId),
259
+ data: Buffer.from(apiInst.data),
260
+ });
261
+ }
262
+ }
263
+
264
+ export const BASE_URL = "http://170.75.162.89:3333/";
package/tsconfig.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2019", // or your preferred target
4
+ "module": "commonjs", // or "ESNext" if you prefer
5
+ "declaration": true, // generate .d.ts files
6
+ "outDir": "./dist", // output directory for compiled files
7
+ "strict": true, // enable all strict type-checking options
8
+ "esModuleInterop": true, // for compatibility with commonJS modules
9
+ "skipLibCheck": true, // skip type checking of declaration files
10
+ "forceConsistentCasingInFileNames": true,
11
+ "sourceMap": true // generate source maps (optional)
12
+ },
13
+ "include": ["src/**/*"], // adjust if your source files are in a different folder
14
+ "exclude": ["node_modules", "**/*.spec.ts"] // exclude tests and node_modules
15
+ }