Skip to content

Commit

Permalink
Polishing the tile
Browse files Browse the repository at this point in the history
So there are a number of small code improvements and clean up in this commit to reduce some clutter and make it more efficient.  Possible bug with the balance check due to a type mismatch has been handled with explicit conversion for the check.
  • Loading branch information
cryptopavelsan committed Feb 14, 2024
1 parent 502b680 commit bd1879b
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 59 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "solana-jupiter-bot",
"version": "0.1.71-beta-jupv4",
"version": "0.1.72-beta-jupv4",
"license": "MIT",
"repository": {
"type": "git",
Expand Down
21 changes: 3 additions & 18 deletions src/bot/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,27 +50,16 @@ const pingpongStrategy = async (jupiter, tokenA, tokenB) => {
? cache.currentBalance[cache.sideBuy ? "tokenA" : "tokenB"]
: cache.initialBalance[cache.sideBuy ? "tokenA" : "tokenB"];

// PAV BNS SUPPORT
const baseAmount = cache.lastBalance[cache.sideBuy ? "tokenB" : "tokenA"];

// default slippage
const slippage = typeof cache.config.slippage === "number" ? cache.config.slippage : 5; // 5BPS is 0.05%
const slippage = typeof cache.config.slippage === "number" ? cache.config.slippage : 1; // 1BPS is 0.01%

// set input / output token
const inputToken = cache.sideBuy ? tokenA : tokenB;
const outputToken = cache.sideBuy ? tokenB : tokenA;

const tokdecimals = cache.sideBuy ? inputToken.decimals : outputToken.decimals;

//console.log('amountToTrade '+amountToTrade);
//console.log('slippageBps '+slippage);
//console.log('inputToken.address '+inputToken.address);
//console.log('outputToken.address '+outputToken.address);

//BNI AMT to TRADE
const amountInJSBI = JSBI.BigInt(amountToTrade);

// check current routes
// check current routes via JUP4 SDK
const performanceOfRouteCompStart = performance.now();
const routes = await jupiter.computeRoutes({
inputMint: new PublicKey(inputToken.address),
Expand Down Expand Up @@ -275,7 +264,7 @@ const arbitrageStrategy = async (jupiter, tokenA) => {
//console.log('Amount to trade:'+amountToTrade);

// default slippage
const slippage = typeof cache.config.slippage === "number" ? cache.config.slippage : 4; // 100 is 0.1%
const slippage = typeof cache.config.slippage === "number" ? cache.config.slippage : 1; // 100 is 0.1%

// set input / output token
const inputToken = tokenA;
Expand Down Expand Up @@ -463,7 +452,6 @@ const watcher = async (jupiter, tokenA, tokenB) => {
await pingpongStrategy(jupiter, tokenA, tokenB);
}
if (cache.config.tradingStrategy === "arbitrage") {
console.log('Starting ARB Watcher');
await arbitrageStrategy(jupiter, tokenA);
}
}
Expand Down Expand Up @@ -495,11 +483,9 @@ const run = async () => {
cache.currentBalance.tokenA = cache.initialBalance.tokenA;
cache.lastBalance.tokenA = cache.initialBalance.tokenA;


// Double check the wallet has sufficient amount of tokenA
var realbalanceTokenA = await checkTokenABalance(tokenA,cache.initialBalance.tokenA);


// set initial & last balance for tokenB
cache.initialBalance.tokenB = await getInitialotherAmountThreshold(
jupiter,
Expand All @@ -520,7 +506,6 @@ const run = async () => {
cache.currentBalance.tokenA = cache.initialBalance.tokenA;
cache.lastBalance.tokenA = cache.initialBalance.tokenA;


// Double check the wallet has sufficient amount of tokenA
var realbalanceTokenA = await checkTokenABalance(tokenA,cache.initialBalance.tokenA);

Expand Down
28 changes: 8 additions & 20 deletions src/bot/setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,19 +45,12 @@ const balanceCheck = async (checkToken) => {

tokenAccounts.value.forEach((accountInfo) => {
const parsedInfo = accountInfo.account.data.parsed.info;
//console.log(`Pubkey: ${accountInfo.pubkey.toBase58()}`);
//console.log(`Mint: ${parsedInfo.mint}`);
//console.log(`Owner: ${parsedInfo.owner}`);
//console.log(`Decimals: ${parsedInfo.tokenAmount.decimals}`);
//console.log(`Amount: ${parsedInfo.tokenAmount.amount}`);
totalTokenBalance += BigInt(parsedInfo.tokenAmount.amount);
//console.log("====================");
});

// Convert totalTokenBalance to a regular number
checkBalance = Number(totalTokenBalance);
//console.log("Total Token Balance:", checkBalance);


} catch (error) {
console.error('Error fetching token balance:', error);
}
Expand All @@ -81,10 +74,8 @@ const balanceCheck = async (checkToken) => {
// Handle Balance Errors Messaging
const checkTokenABalance = async (tokenA, initialTradingBalance) => {
try {
// Check the balance of TokenA to make sure there is enough to trade
// Check the balance of TokenA to make sure there is enough to trade with
var realbalanceTokenA = await balanceCheck(tokenA);

// Make the numebers user friendly
bal1 = toDecimal(realbalanceTokenA,tokenA.decimals);
bal2 = toDecimal(initialTradingBalance,tokenA.decimals);

Expand All @@ -94,7 +85,6 @@ const checkTokenABalance = async (tokenA, initialTradingBalance) => {
\nTo run the bot you need \x1b[93m${bal2}\x1b[0m ${tokenA.symbol}.
\nEither add more ${tokenA.symbol} to your wallet or lower the amount below ${bal1}.\n`);
}
// We are gucci
return realbalanceTokenA;
} catch (error) {
// Handle errors gracefully
Expand All @@ -120,24 +110,21 @@ const setup = async () => {
color: "magenta",
}).start();

// read tokens.json file
try {
tokens = JSON.parse(fs.readFileSync("./temp/tokens.json"));
// find tokens full Object
tokenA = tokens.find((t) => t.address === cache.config.tokenA.address);

if (cache.config.tradingStrategy !== "arbitrage")
tokenB = tokens.find((t) => t.address === cache.config.tokenB.address);
} catch (error) {
spinner.text = chalk.black.bgRedBright(
`\n Loading tokens failed!\n Please try to run the Wizard first using ${chalk.bold(
`\n Loading tokens failed!\n Please run the Wizard to generate it using ${chalk.bold(
"`yarn start`"
)}\n`
);
throw error;
}

// check wallet private key again
try {
spinner.text = "Checking wallet...";
if (
Expand All @@ -162,7 +149,7 @@ const setup = async () => {
throw error;
}

spinner.text = "Setting up connection ...";
// Set up the RPC connection
const connection = new Connection(cache.config.rpc[0]);

spinner.text = "Loading the Jupiter V4 SDK and getting ready to trade...";
Expand Down Expand Up @@ -231,10 +218,11 @@ const getInitialotherAmountThreshold = async (
) => {
let spinner;
try {
const tokdecimals = cache.sideBuy ? inputToken.decimals : outputToken.decimals;
const multiplythisbb = JSBI.BigInt(10 ** (tokdecimals));
const tokenDecimals = cache.sideBuy ? inputToken.decimals : outputToken.decimals;
const spinnerText = `Computing routes for the token with amountToTrade ${amountToTrade} with decimals ${tokenDecimals}`;

spinner = ora({
text: "Computing routes for token with amountToTrade "+String(amountToTrade)+" with decimals "+tokdecimals+" and multiply is "+String(multiplythisbb),
text: spinnerText,
discardStdin: false,
color: "magenta",
}).start();
Expand Down
36 changes: 16 additions & 20 deletions src/bot/swap.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const swap = async (jupiter, route) => {
if (process.env.DEBUG) storeItInTempAsJSON("routeInfoBeforeSwap", route);

// pull the trade priority
const priority = typeof cache.config.priority === "number" ? cache.config.priority : 123; //123 default if not set
const priority = typeof cache.config.priority === "number" ? cache.config.priority : 100; //100 BPS default if not set
cache.priority = priority;

const { execute } = await jupiter.exchange({
Expand All @@ -47,36 +47,32 @@ const swap = async (jupiter, route) => {
exports.swap = swap;

const failedSwapHandler = async(tradeEntry, inputToken, tradeAmount) => {
// update counter
// update trade counter
cache.tradeCounter[cache.sideBuy ? "buy" : "sell"].fail++;

// update trade history
cache.config.storeFailedTxInHistory;

// update trade history
let tempHistory = cache.tradeHistory;
tempHistory.push(tradeEntry);
cache.tradeHistory = tempHistory;
// Update trade history if configured
if (cache.config.storeFailedTxInHistory) {
cache.tradeHistory.push(tradeEntry);
}

// Double check the balance is not the issue here. If so end the script to stop endless failed trans
var realbalanceToken = await balanceCheck( inputToken );
// Double check the balance
const realbalanceToken = await balanceCheck(inputToken);

if (realbalanceToken<tradeAmount){
// If balance is insufficient, handle it
if (Number(realbalanceToken) < Number(tradeAmount)) {
cache.tradeCounter.failedbalancecheck++;

if (cache.tradeCounter.failedbalancecheck>3){
// Has to fail for 3 times before it ends the script. This is to cover cases where there is a delay in account updating pull
console.log('Balance Lookup is too low for token: '+realbalanceToken+' < '+tradeAmount);
console.log('Failed For: '+cache.tradeCounter.failedbalancecheck+' times');
if (cache.tradeCounter.failedbalancecheck > 5) {
console.log(`Balance Lookup is too low for token: ${realbalanceToken} < ${tradeAmount}`);
console.log(`Failed For: ${cache.tradeCounter.failedbalancecheck} times`);
process.exit();
}
}

// Add one count to the error
// Increment error count and check if too high
cache.tradeCounter.errorcount += 1;

if (cache.tradeCounter.errorcount>100){
console.log('Error Count is too high for swaps: '+cache.tradeCounter.errorcount);
if (cache.tradeCounter.errorcount > 100) {
console.log(`Error Count is too high for swaps: ${cache.tradeCounter.errorcount}`);
console.log('Ending to stop endless transactions failing');
process.exit();
}
Expand Down

0 comments on commit bd1879b

Please sign in to comment.