Skip to content

Commit 50f3a4d

Browse files
committedNov 4, 2024·
use big number
Signed-off-by: MarcoMandar <malicemandar@gmail.com>
1 parent 923ea75 commit 50f3a4d

File tree

1 file changed

+70
-37
lines changed

1 file changed

+70
-37
lines changed
 

‎core/src/actions/swap.ts

+70-37
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
1-
import { Connection, Keypair, PublicKey, Transaction, VersionedTransaction } from "@solana/web3.js";
1+
import {
2+
Connection,
3+
Keypair,
4+
PublicKey,
5+
Transaction,
6+
VersionedTransaction,
7+
} from "@solana/web3.js";
28
import fetch from "cross-fetch";
39
import {
410
ActionExample,
@@ -7,14 +13,15 @@ import {
713
type Action,
814
State,
915
ModelClass,
10-
HandlerCallback
16+
HandlerCallback,
1117
} from "../core/types.ts";
1218
import { walletProvider } from "../providers/wallet.ts";
1319
import { composeContext } from "../core/context.ts";
1420
import { generateObject, generateObjectArray } from "../core/generation.ts";
1521
import { getTokenDecimals } from "./swapUtils.ts";
1622
import settings from "../core/settings.ts";
1723
import { bs58 } from "@coral-xyz/anchor/dist/cjs/utils/bytes/index.js";
24+
import BigNumber from "bignumber.js";
1825

1926
async function swapToken(
2027
connection: Connection,
@@ -25,17 +32,25 @@ async function swapToken(
2532
): Promise<any> {
2633
try {
2734
// Get the decimals for the input token
28-
const decimals = inputTokenCA === settings.SOL_ADDRESS ? 9 :
29-
await getTokenDecimals(connection, inputTokenCA);
30-
31-
console.log("Decimals:", decimals);
32-
33-
const adjustedAmount = amount * (10 ** decimals);
35+
const decimals =
36+
inputTokenCA === settings.SOL_ADDRESS
37+
? new BigNumber(9)
38+
: new BigNumber(
39+
await getTokenDecimals(connection, inputTokenCA)
40+
);
41+
42+
console.log("Decimals:", decimals.toString());
43+
44+
// Use BigNumber for adjustedAmount: amount * (10 ** decimals)
45+
const amountBN = new BigNumber(amount);
46+
const adjustedAmount = amountBN.multipliedBy(
47+
new BigNumber(10).pow(decimals)
48+
);
3449

3550
console.log("Fetching quote with params:", {
3651
inputMint: inputTokenCA,
3752
outputMint: outputTokenCA,
38-
amount: adjustedAmount
53+
amount: adjustedAmount,
3954
});
4055

4156
const quoteResponse = await fetch(
@@ -45,7 +60,9 @@ async function swapToken(
4560

4661
if (!quoteData || quoteData.error) {
4762
console.error("Quote error:", quoteData);
48-
throw new Error(`Failed to get quote: ${quoteData?.error || 'Unknown error'}`);
63+
throw new Error(
64+
`Failed to get quote: ${quoteData?.error || "Unknown error"}`
65+
);
4966
}
5067

5168
console.log("Quote received:", quoteData);
@@ -55,7 +72,7 @@ async function swapToken(
5572
userPublicKey: walletPublicKey.toString(),
5673
wrapAndUnwrapSol: true,
5774
computeUnitPriceMicroLamports: 1000,
58-
dynamicComputeUnitLimit: true
75+
dynamicComputeUnitLimit: true,
5976
};
6077

6178
console.log("Requesting swap with body:", swapRequestBody);
@@ -65,26 +82,26 @@ async function swapToken(
6582
headers: {
6683
"Content-Type": "application/json",
6784
},
68-
body: JSON.stringify(swapRequestBody)
85+
body: JSON.stringify(swapRequestBody),
6986
});
7087

7188
const swapData = await swapResponse.json();
7289

7390
if (!swapData || !swapData.swapTransaction) {
7491
console.error("Swap error:", swapData);
75-
throw new Error(`Failed to get swap transaction: ${swapData?.error || 'No swap transaction returned'}`);
92+
throw new Error(
93+
`Failed to get swap transaction: ${swapData?.error || "No swap transaction returned"}`
94+
);
7695
}
7796

7897
console.log("Swap transaction received");
7998
return swapData;
80-
8199
} catch (error) {
82100
console.error("Error in swapToken:", error);
83101
throw error;
84102
}
85103
}
86104

87-
88105
const swapTemplate = `Respond with a JSON markdown block containing only the extracted values. Use null for any values that cannot be determined.
89106
90107
Example response:
@@ -142,7 +159,6 @@ export const executeSwap: Action = {
142159
_options: { [key: string]: unknown },
143160
callback?: HandlerCallback
144161
): Promise<boolean> => {
145-
146162
// composeState
147163
if (!state) {
148164
state = (await runtime.composeState(message)) as State;
@@ -168,10 +184,10 @@ export const executeSwap: Action = {
168184
console.log("Response:", response);
169185

170186
// Add SOL handling logic
171-
if (response.inputTokenSymbol?.toUpperCase() === 'SOL') {
187+
if (response.inputTokenSymbol?.toUpperCase() === "SOL") {
172188
response.inputTokenCA = settings.SOL_ADDRESS;
173189
}
174-
if (response.outputTokenSymbol?.toUpperCase() === 'SOL') {
190+
if (response.outputTokenSymbol?.toUpperCase() === "SOL") {
175191
response.outputTokenCA = settings.SOL_ADDRESS;
176192
}
177193

@@ -226,12 +242,16 @@ export const executeSwap: Action = {
226242
);
227243

228244
console.log("Deserializing transaction...");
229-
const transactionBuf = Buffer.from(swapResult.swapTransaction, "base64");
230-
const transaction = VersionedTransaction.deserialize(transactionBuf);
231-
245+
const transactionBuf = Buffer.from(
246+
swapResult.swapTransaction,
247+
"base64"
248+
);
249+
const transaction =
250+
VersionedTransaction.deserialize(transactionBuf);
251+
232252
console.log("Preparing to sign transaction...");
233253
const privateKeyString = runtime.getSetting("WALLET_PRIVATE_KEY");
234-
254+
235255
// Handle different private key formats
236256
let secretKey: Uint8Array;
237257
try {
@@ -240,25 +260,31 @@ export const executeSwap: Action = {
240260
} catch (e) {
241261
try {
242262
// If that fails, try base64
243-
secretKey = Uint8Array.from(Buffer.from(privateKeyString, 'base64'));
263+
secretKey = Uint8Array.from(
264+
Buffer.from(privateKeyString, "base64")
265+
);
244266
} catch (e2) {
245-
throw new Error('Invalid private key format');
267+
throw new Error("Invalid private key format");
246268
}
247269
}
248270

249271
// Verify the key length
250272
if (secretKey.length !== 64) {
251273
console.error("Invalid key length:", secretKey.length);
252-
throw new Error(`Invalid private key length: ${secretKey.length}. Expected 64 bytes.`);
274+
throw new Error(
275+
`Invalid private key length: ${secretKey.length}. Expected 64 bytes.`
276+
);
253277
}
254278

255279
console.log("Creating keypair...");
256280
const keypair = Keypair.fromSecretKey(secretKey);
257-
281+
258282
// Verify the public key matches what we expect
259283
const expectedPublicKey = runtime.getSetting("WALLET_PUBLIC_KEY");
260284
if (keypair.publicKey.toBase58() !== expectedPublicKey) {
261-
throw new Error("Generated public key doesn't match expected public key");
285+
throw new Error(
286+
"Generated public key doesn't match expected public key"
287+
);
262288
}
263289

264290
console.log("Signing transaction...");
@@ -271,24 +297,31 @@ export const executeSwap: Action = {
271297
const txid = await connection.sendTransaction(transaction, {
272298
skipPreflight: false,
273299
maxRetries: 3,
274-
preflightCommitment: 'confirmed'
300+
preflightCommitment: "confirmed",
275301
});
276-
302+
277303
console.log("Transaction sent:", txid);
278304

279305
// Confirm transaction using the blockhash
280-
const confirmation = await connection.confirmTransaction({
281-
signature: txid,
282-
blockhash: latestBlockhash.blockhash,
283-
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight
284-
}, 'confirmed');
306+
const confirmation = await connection.confirmTransaction(
307+
{
308+
signature: txid,
309+
blockhash: latestBlockhash.blockhash,
310+
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
311+
},
312+
"confirmed"
313+
);
285314

286315
if (confirmation.value.err) {
287-
throw new Error(`Transaction failed: ${confirmation.value.err}`);
316+
throw new Error(
317+
`Transaction failed: ${confirmation.value.err}`
318+
);
288319
}
289320

290321
if (confirmation.value.err) {
291-
throw new Error(`Transaction failed: ${confirmation.value.err}`);
322+
throw new Error(
323+
`Transaction failed: ${confirmation.value.err}`
324+
);
292325
}
293326

294327
console.log("Swap completed successfully!");
@@ -299,7 +332,7 @@ export const executeSwap: Action = {
299332
};
300333

301334
callback?.(responseMsg);
302-
335+
303336
return true;
304337
} catch (error) {
305338
console.error("Error during token swap:", error);

0 commit comments

Comments
 (0)
Please sign in to comment.