mirror of
https://github.com/fdundjer/solana-sniper-bot.git
synced 2025-11-10 04:22:05 +10:00
feat: create buy script for solana tokens
This commit is contained in:
3
.gitignore
vendored
3
.gitignore
vendored
@ -128,3 +128,6 @@ dist
|
|||||||
.yarn/build-state.yml
|
.yarn/build-state.yml
|
||||||
.yarn/install-state.gz
|
.yarn/install-state.gz
|
||||||
.pnp.*
|
.pnp.*
|
||||||
|
|
||||||
|
|
||||||
|
.idea
|
||||||
4
.prettierrc
Normal file
4
.prettierrc
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"singleQuote": true,
|
||||||
|
"trailingComma": "all"
|
||||||
|
}
|
||||||
22
LICENSE.md
Normal file
22
LICENSE.md
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
Microsoft Public License (Ms-PL)
|
||||||
|
|
||||||
|
This license governs use of the accompanying software. If you use the software, you
|
||||||
|
accept this license. If you do not accept the license, do not use the software.
|
||||||
|
|
||||||
|
1. Definitions
|
||||||
|
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the
|
||||||
|
same meaning here as under U.S. copyright law.
|
||||||
|
A "contribution" is the original software, or any additions or changes to the software.
|
||||||
|
A "contributor" is any person that distributes its contribution under this license.
|
||||||
|
"Licensed patents" are a contributor's patent claims that read directly on its contribution.
|
||||||
|
|
||||||
|
2. Grant of Rights
|
||||||
|
(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
|
||||||
|
(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
|
||||||
|
|
||||||
|
3. Conditions and Limitations
|
||||||
|
(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
|
||||||
|
(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
|
||||||
|
(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
|
||||||
|
(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
|
||||||
|
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
|
||||||
3
README.md
Normal file
3
README.md
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
# Solana Sniper Bot - Proof of concept - 2023-04-20
|
||||||
|
|
||||||
|
TODO
|
||||||
249
buy.ts
Normal file
249
buy.ts
Normal file
@ -0,0 +1,249 @@
|
|||||||
|
import {
|
||||||
|
Liquidity,
|
||||||
|
LIQUIDITY_STATE_LAYOUT_V4,
|
||||||
|
MARKET_STATE_LAYOUT_V2,
|
||||||
|
} from '@raydium-io/raydium-sdk';
|
||||||
|
import { getOrCreateAssociatedTokenAccount } from '@solana/spl-token';
|
||||||
|
import {
|
||||||
|
Keypair,
|
||||||
|
Connection,
|
||||||
|
PublicKey,
|
||||||
|
ComputeBudgetProgram,
|
||||||
|
KeyedAccountInfo,
|
||||||
|
TransactionMessage,
|
||||||
|
VersionedTransaction,
|
||||||
|
} from '@solana/web3.js';
|
||||||
|
import secret from './wallet.json';
|
||||||
|
import {
|
||||||
|
getAllAccountsV4,
|
||||||
|
getTokenAccounts,
|
||||||
|
getAccountPoolKeysFromAccountDataV4,
|
||||||
|
RAYDIUM_LIQUIDITY_PROGRAM_ID_V4,
|
||||||
|
OPENBOOK_PROGRAM_ID,
|
||||||
|
} from './liquidity';
|
||||||
|
import { retry } from './utils';
|
||||||
|
import { USDC_AMOUNT, USDC_TOKEN_ID } from './common';
|
||||||
|
import { getAllMarketsV3 } from './market';
|
||||||
|
import pino from 'pino';
|
||||||
|
|
||||||
|
export const logger = pino(
|
||||||
|
{
|
||||||
|
redact: ['poolKeys'],
|
||||||
|
base: undefined,
|
||||||
|
},
|
||||||
|
pino.destination('buy.log'),
|
||||||
|
);
|
||||||
|
|
||||||
|
const network = 'mainnet-beta';
|
||||||
|
const solanaConnection = new Connection(
|
||||||
|
'ENTER RPC ENDPOINT HERE',
|
||||||
|
{
|
||||||
|
wsEndpoint:
|
||||||
|
'ENTER RPC WEBSOCKET ENDPOINT HERE',
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
export type MinimalTokenAccountData = {
|
||||||
|
mint: PublicKey;
|
||||||
|
address: PublicKey;
|
||||||
|
};
|
||||||
|
|
||||||
|
let existingLiquidityPools: Set<string> = new Set<string>();
|
||||||
|
let existingOpenBookMarkets: Set<string> = new Set<string>();
|
||||||
|
let existingTokenAccounts: Map<string, MinimalTokenAccountData> = new Map<
|
||||||
|
string,
|
||||||
|
MinimalTokenAccountData
|
||||||
|
>();
|
||||||
|
|
||||||
|
let wallet: Keypair;
|
||||||
|
let usdcTokenKey: PublicKey;
|
||||||
|
|
||||||
|
async function init(): Promise<void> {
|
||||||
|
wallet = Keypair.fromSecretKey(new Uint8Array(secret));
|
||||||
|
logger.info(`Wallet Address: ${wallet.publicKey.toString()}`);
|
||||||
|
const allLiquidityPools = await getAllAccountsV4(solanaConnection);
|
||||||
|
existingLiquidityPools = new Set(
|
||||||
|
allLiquidityPools.map((p) => p.id.toString()),
|
||||||
|
);
|
||||||
|
const allMarkets = await getAllMarketsV3(solanaConnection);
|
||||||
|
existingOpenBookMarkets = new Set(allMarkets.map((p) => p.id.toString()));
|
||||||
|
const tokenAccounts = await getTokenAccounts(
|
||||||
|
solanaConnection,
|
||||||
|
wallet.publicKey,
|
||||||
|
);
|
||||||
|
logger.info(`Total USDC markets ${existingOpenBookMarkets.size}`);
|
||||||
|
logger.info(`Total USDC pools ${existingLiquidityPools.size}`);
|
||||||
|
tokenAccounts.forEach((ta) => {
|
||||||
|
existingTokenAccounts.set(ta.accountInfo.mint.toString(), <
|
||||||
|
MinimalTokenAccountData
|
||||||
|
>{
|
||||||
|
mint: ta.accountInfo.mint,
|
||||||
|
address: ta.pubkey,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
const token = tokenAccounts.find(
|
||||||
|
(acc) => acc.accountInfo.mint.toString() === USDC_TOKEN_ID.toString(),
|
||||||
|
)!;
|
||||||
|
usdcTokenKey = token!.pubkey;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function processRaydiumPool(updatedAccountInfo: KeyedAccountInfo) {
|
||||||
|
let accountData: any;
|
||||||
|
try {
|
||||||
|
accountData = LIQUIDITY_STATE_LAYOUT_V4.decode(
|
||||||
|
updatedAccountInfo.accountInfo.data,
|
||||||
|
);
|
||||||
|
await buy(updatedAccountInfo.accountId, accountData);
|
||||||
|
} catch (e) {
|
||||||
|
logger.error({ ...accountData, error: e }, `Failed to process pool`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function processOpenBookMarket(
|
||||||
|
updatedAccountInfo: KeyedAccountInfo,
|
||||||
|
) {
|
||||||
|
let accountData: any;
|
||||||
|
try {
|
||||||
|
accountData = MARKET_STATE_LAYOUT_V2.decode(
|
||||||
|
updatedAccountInfo.accountInfo.data,
|
||||||
|
);
|
||||||
|
|
||||||
|
// to be competitive, we create token account before buying the token...
|
||||||
|
if (existingTokenAccounts.has(accountData.baseMint.toString())) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const destinationAccount = await getOrCreateAssociatedTokenAccount(
|
||||||
|
solanaConnection,
|
||||||
|
wallet,
|
||||||
|
accountData.baseMint,
|
||||||
|
wallet.publicKey,
|
||||||
|
);
|
||||||
|
existingTokenAccounts.set(accountData.baseMint.toString(), <
|
||||||
|
MinimalTokenAccountData
|
||||||
|
>{
|
||||||
|
address: destinationAccount.address,
|
||||||
|
mint: destinationAccount.mint,
|
||||||
|
});
|
||||||
|
logger.info(
|
||||||
|
accountData,
|
||||||
|
`Created destination account: ${destinationAccount.address}`,
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
logger.error({ ...accountData, error: e }, `Failed to process market`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function buy(accountId: PublicKey, accountData: any): Promise<void> {
|
||||||
|
const [poolKeys, latestBlockhash] = await Promise.all([
|
||||||
|
getAccountPoolKeysFromAccountDataV4(
|
||||||
|
solanaConnection,
|
||||||
|
accountId,
|
||||||
|
accountData,
|
||||||
|
),
|
||||||
|
solanaConnection.getLatestBlockhash({ commitment: 'processed' }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const { innerTransaction, address } = Liquidity.makeSwapFixedInInstruction(
|
||||||
|
{
|
||||||
|
poolKeys,
|
||||||
|
userKeys: {
|
||||||
|
tokenAccountIn: usdcTokenKey,
|
||||||
|
tokenAccountOut: existingTokenAccounts.get(
|
||||||
|
poolKeys.baseMint.toString(),
|
||||||
|
)!.address,
|
||||||
|
owner: wallet.publicKey,
|
||||||
|
},
|
||||||
|
amountIn: USDC_AMOUNT * 1000000,
|
||||||
|
minAmountOut: 0,
|
||||||
|
},
|
||||||
|
poolKeys.version,
|
||||||
|
);
|
||||||
|
|
||||||
|
const messageV0 = new TransactionMessage({
|
||||||
|
payerKey: wallet.publicKey,
|
||||||
|
recentBlockhash: latestBlockhash.blockhash,
|
||||||
|
instructions: [
|
||||||
|
ComputeBudgetProgram.setComputeUnitLimit({ units: 400000 }),
|
||||||
|
ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 30000 }),
|
||||||
|
...innerTransaction.instructions,
|
||||||
|
],
|
||||||
|
}).compileToV0Message();
|
||||||
|
const transaction = new VersionedTransaction(messageV0);
|
||||||
|
transaction.sign([wallet, ...innerTransaction.signers]);
|
||||||
|
const rawTransaction = transaction.serialize();
|
||||||
|
const signature = await retry(
|
||||||
|
() =>
|
||||||
|
solanaConnection.sendRawTransaction(rawTransaction, {
|
||||||
|
skipPreflight: true,
|
||||||
|
}),
|
||||||
|
{ retryIntervalMs: 10, retries: 50 }, // TODO handle retries more efficiently
|
||||||
|
);
|
||||||
|
logger.info(
|
||||||
|
{
|
||||||
|
...accountData,
|
||||||
|
url: `https://solscan.io/tx/${signature}?cluster=${network}`,
|
||||||
|
},
|
||||||
|
'Buy',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const runListener = async () => {
|
||||||
|
await init();
|
||||||
|
const raydiumSubscriptionId = solanaConnection.onProgramAccountChange(
|
||||||
|
RAYDIUM_LIQUIDITY_PROGRAM_ID_V4,
|
||||||
|
async (updatedAccountInfo) => {
|
||||||
|
const existing = existingLiquidityPools.has(
|
||||||
|
updatedAccountInfo.accountId.toString(),
|
||||||
|
);
|
||||||
|
if (!existing) {
|
||||||
|
existingLiquidityPools.add(updatedAccountInfo.accountId.toString());
|
||||||
|
const _ = processRaydiumPool(updatedAccountInfo);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
'processed',
|
||||||
|
[
|
||||||
|
{ dataSize: LIQUIDITY_STATE_LAYOUT_V4.span },
|
||||||
|
{
|
||||||
|
memcmp: {
|
||||||
|
offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('quoteMint'),
|
||||||
|
bytes: USDC_TOKEN_ID.toBase58(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
memcmp: {
|
||||||
|
offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('marketProgramId'),
|
||||||
|
bytes: OPENBOOK_PROGRAM_ID.toBase58(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
const openBookSubscriptionId = solanaConnection.onProgramAccountChange(
|
||||||
|
OPENBOOK_PROGRAM_ID,
|
||||||
|
async (updatedAccountInfo) => {
|
||||||
|
const existing = existingOpenBookMarkets.has(
|
||||||
|
updatedAccountInfo.accountId.toString(),
|
||||||
|
);
|
||||||
|
if (!existing) {
|
||||||
|
existingOpenBookMarkets.add(updatedAccountInfo.accountId.toString());
|
||||||
|
const _ = processOpenBookMarket(updatedAccountInfo);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
'processed',
|
||||||
|
[
|
||||||
|
{ dataSize: MARKET_STATE_LAYOUT_V2.span },
|
||||||
|
{
|
||||||
|
memcmp: {
|
||||||
|
offset: MARKET_STATE_LAYOUT_V2.offsetOf('quoteMint'),
|
||||||
|
bytes: USDC_TOKEN_ID.toBase58(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
logger.info(`Listening for raydium changes: ${raydiumSubscriptionId}`);
|
||||||
|
logger.info(`Listening for open book changes: ${openBookSubscriptionId}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
runListener();
|
||||||
6
common/constants.ts
Normal file
6
common/constants.ts
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
import { PublicKey } from "@solana/web3.js";
|
||||||
|
|
||||||
|
export const USDC_AMOUNT = 0.1; // how much do we spend on each token
|
||||||
|
export const USDC_TOKEN_ID = new PublicKey(
|
||||||
|
'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
|
||||||
|
);
|
||||||
1
common/index.ts
Normal file
1
common/index.ts
Normal file
@ -0,0 +1 @@
|
|||||||
|
export * from './constants';
|
||||||
1
liquidity/index.ts
Normal file
1
liquidity/index.ts
Normal file
@ -0,0 +1 @@
|
|||||||
|
export * from './liquidity';
|
||||||
137
liquidity/liquidity.ts
Normal file
137
liquidity/liquidity.ts
Normal file
@ -0,0 +1,137 @@
|
|||||||
|
import { Commitment, Connection, PublicKey } from '@solana/web3.js';
|
||||||
|
import {
|
||||||
|
Liquidity,
|
||||||
|
LIQUIDITY_STATE_LAYOUT_V4,
|
||||||
|
LiquidityPoolKeys,
|
||||||
|
Market,
|
||||||
|
TokenAccount,
|
||||||
|
SPL_ACCOUNT_LAYOUT,
|
||||||
|
publicKey,
|
||||||
|
struct,
|
||||||
|
MAINNET_PROGRAM_ID,
|
||||||
|
} from '@raydium-io/raydium-sdk';
|
||||||
|
import { TOKEN_PROGRAM_ID } from '@solana/spl-token';
|
||||||
|
import { USDC_TOKEN_ID } from '../common';
|
||||||
|
|
||||||
|
export const RAYDIUM_LIQUIDITY_PROGRAM_ID_V4 = MAINNET_PROGRAM_ID.AmmV4;
|
||||||
|
export const OPENBOOK_PROGRAM_ID = MAINNET_PROGRAM_ID.OPENBOOK_MARKET;
|
||||||
|
|
||||||
|
export const MINIMAL_MARKET_STATE_LAYOUT_V3 = struct([
|
||||||
|
publicKey('eventQueue'),
|
||||||
|
publicKey('bids'),
|
||||||
|
publicKey('asks'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
export type MinimalLiquidityAccountData = {
|
||||||
|
id: PublicKey;
|
||||||
|
version: 4;
|
||||||
|
programId: PublicKey;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function getAllAccountsV4(
|
||||||
|
connection: Connection,
|
||||||
|
): Promise<MinimalLiquidityAccountData[]> {
|
||||||
|
const { span } = LIQUIDITY_STATE_LAYOUT_V4;
|
||||||
|
const accounts = await connection.getProgramAccounts(
|
||||||
|
RAYDIUM_LIQUIDITY_PROGRAM_ID_V4,
|
||||||
|
{
|
||||||
|
dataSlice: { offset: 0, length: 0 },
|
||||||
|
commitment: 'processed',
|
||||||
|
filters: [
|
||||||
|
{ dataSize: span },
|
||||||
|
{
|
||||||
|
memcmp: {
|
||||||
|
offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('quoteMint'),
|
||||||
|
bytes: USDC_TOKEN_ID.toBase58(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
memcmp: {
|
||||||
|
offset: LIQUIDITY_STATE_LAYOUT_V4.offsetOf('marketProgramId'),
|
||||||
|
bytes: OPENBOOK_PROGRAM_ID.toBase58(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
return accounts.map(
|
||||||
|
(info) =>
|
||||||
|
<MinimalLiquidityAccountData>{
|
||||||
|
id: info.pubkey,
|
||||||
|
version: 4,
|
||||||
|
programId: RAYDIUM_LIQUIDITY_PROGRAM_ID_V4,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getAccountPoolKeysFromAccountDataV4(
|
||||||
|
connection: Connection,
|
||||||
|
id: PublicKey,
|
||||||
|
accountData: any,
|
||||||
|
commitment?: Commitment,
|
||||||
|
): Promise<LiquidityPoolKeys> {
|
||||||
|
const marketInfo = await connection.getAccountInfo(accountData.marketId, {
|
||||||
|
commitment: commitment ?? 'processed',
|
||||||
|
dataSlice: {
|
||||||
|
offset: 253, // eventQueue
|
||||||
|
length: 32 * 3,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const minimalMarketData = MINIMAL_MARKET_STATE_LAYOUT_V3.decode(
|
||||||
|
marketInfo!.data,
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
baseMint: accountData.baseMint,
|
||||||
|
quoteMint: accountData.quoteMint,
|
||||||
|
lpMint: accountData.lpMint,
|
||||||
|
baseDecimals: accountData.baseDecimal.toNumber(),
|
||||||
|
quoteDecimals: accountData.quoteDecimal.toNumber(),
|
||||||
|
lpDecimals: 5,
|
||||||
|
version: 4,
|
||||||
|
programId: RAYDIUM_LIQUIDITY_PROGRAM_ID_V4,
|
||||||
|
authority: Liquidity.getAssociatedAuthority({
|
||||||
|
programId: RAYDIUM_LIQUIDITY_PROGRAM_ID_V4,
|
||||||
|
}).publicKey,
|
||||||
|
openOrders: accountData.openOrders,
|
||||||
|
targetOrders: accountData.targetOrders,
|
||||||
|
baseVault: accountData.baseVault,
|
||||||
|
quoteVault: accountData.quoteVault,
|
||||||
|
marketVersion: 3,
|
||||||
|
marketProgramId: accountData.marketProgramId,
|
||||||
|
marketId: accountData.marketId,
|
||||||
|
marketAuthority: Market.getAssociatedAuthority({
|
||||||
|
programId: accountData.marketProgramId,
|
||||||
|
marketId: accountData.marketId,
|
||||||
|
}).publicKey,
|
||||||
|
marketBaseVault: accountData.baseVault,
|
||||||
|
marketQuoteVault: accountData.quoteVault,
|
||||||
|
marketBids: minimalMarketData.bids,
|
||||||
|
marketAsks: minimalMarketData.asks,
|
||||||
|
marketEventQueue: minimalMarketData.eventQueue,
|
||||||
|
withdrawQueue: accountData.withdrawQueue,
|
||||||
|
lpVault: accountData.lpVault,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getTokenAccounts(
|
||||||
|
connection: Connection,
|
||||||
|
owner: PublicKey,
|
||||||
|
) {
|
||||||
|
const tokenResp = await connection.getTokenAccountsByOwner(owner, {
|
||||||
|
programId: TOKEN_PROGRAM_ID,
|
||||||
|
});
|
||||||
|
|
||||||
|
const accounts: TokenAccount[] = [];
|
||||||
|
for (const { pubkey, account } of tokenResp.value) {
|
||||||
|
accounts.push({
|
||||||
|
pubkey,
|
||||||
|
accountInfo: SPL_ACCOUNT_LAYOUT.decode(account.data),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return accounts;
|
||||||
|
}
|
||||||
1
market/index.ts
Normal file
1
market/index.ts
Normal file
@ -0,0 +1 @@
|
|||||||
|
export * from './market';
|
||||||
41
market/market.ts
Normal file
41
market/market.ts
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
import { Connection, PublicKey } from '@solana/web3.js';
|
||||||
|
import {
|
||||||
|
MARKET_STATE_LAYOUT_V3,
|
||||||
|
} from '@raydium-io/raydium-sdk';
|
||||||
|
import { USDC_TOKEN_ID } from '../common';
|
||||||
|
import {
|
||||||
|
OPENBOOK_PROGRAM_ID,
|
||||||
|
|
||||||
|
} from '../liquidity';
|
||||||
|
|
||||||
|
export type MinimalOpenBookAccountData = {
|
||||||
|
id: PublicKey;
|
||||||
|
programId: PublicKey;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function getAllMarketsV3(
|
||||||
|
connection: Connection,
|
||||||
|
): Promise<MinimalOpenBookAccountData[]> {
|
||||||
|
const { span } = MARKET_STATE_LAYOUT_V3;
|
||||||
|
const accounts = await connection.getProgramAccounts(OPENBOOK_PROGRAM_ID, {
|
||||||
|
dataSlice: { offset: 0, length: 0 },
|
||||||
|
commitment: 'processed',
|
||||||
|
filters: [
|
||||||
|
{ dataSize: span },
|
||||||
|
{
|
||||||
|
memcmp: {
|
||||||
|
offset: MARKET_STATE_LAYOUT_V3.offsetOf('quoteMint'),
|
||||||
|
bytes: USDC_TOKEN_ID.toBase58(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
return accounts.map(
|
||||||
|
(info) =>
|
||||||
|
<MinimalOpenBookAccountData>{
|
||||||
|
id: info.pubkey,
|
||||||
|
programId: OPENBOOK_PROGRAM_ID,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
1147
package-lock.json
generated
Normal file
1147
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
20
package.json
Normal file
20
package.json
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"name": "solana-sniper-bot",
|
||||||
|
"author": "Filip Dundjer",
|
||||||
|
"scripts": {
|
||||||
|
"buy": "ts-node buy.ts"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@raydium-io/raydium-sdk": "^1.3.0-beta.17",
|
||||||
|
"@solana/spl-token": "^0.3.7",
|
||||||
|
"bigint-buffer": "^1.1.5",
|
||||||
|
"bn.js": "^5.2.1",
|
||||||
|
"pino": "^8.14.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/bn.js": "^5.1.1",
|
||||||
|
"prettier": "^2.8.8",
|
||||||
|
"ts-node": "^10.9.1",
|
||||||
|
"typescript": "^5.0.4"
|
||||||
|
}
|
||||||
|
}
|
||||||
109
tsconfig.json
Normal file
109
tsconfig.json
Normal file
@ -0,0 +1,109 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
/* Visit https://aka.ms/tsconfig to read more about this file */
|
||||||
|
|
||||||
|
/* Projects */
|
||||||
|
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
|
||||||
|
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
||||||
|
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
|
||||||
|
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
|
||||||
|
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
||||||
|
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
||||||
|
|
||||||
|
/* Language and Environment */
|
||||||
|
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
||||||
|
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||||
|
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
||||||
|
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
|
||||||
|
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
||||||
|
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
||||||
|
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
||||||
|
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
||||||
|
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
||||||
|
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
||||||
|
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
||||||
|
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
||||||
|
|
||||||
|
/* Modules */
|
||||||
|
"module": "commonjs", /* Specify what module code is generated. */
|
||||||
|
// "rootDir": "./", /* Specify the root folder within your source files. */
|
||||||
|
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
|
||||||
|
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
||||||
|
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
||||||
|
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
||||||
|
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
||||||
|
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
||||||
|
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||||
|
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
||||||
|
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
|
||||||
|
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
|
||||||
|
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
|
||||||
|
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
|
||||||
|
"resolveJsonModule": true, /* Enable importing .json files. */
|
||||||
|
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
|
||||||
|
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
||||||
|
|
||||||
|
/* JavaScript Support */
|
||||||
|
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
||||||
|
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
||||||
|
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
||||||
|
|
||||||
|
/* Emit */
|
||||||
|
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
||||||
|
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
||||||
|
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
||||||
|
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
||||||
|
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
||||||
|
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
||||||
|
// "outDir": "./", /* Specify an output folder for all emitted files. */
|
||||||
|
// "removeComments": true, /* Disable emitting comments. */
|
||||||
|
// "noEmit": true, /* Disable emitting files from a compilation. */
|
||||||
|
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
||||||
|
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
|
||||||
|
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
||||||
|
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
||||||
|
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||||
|
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
||||||
|
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
||||||
|
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
||||||
|
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
||||||
|
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
||||||
|
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
||||||
|
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
||||||
|
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
||||||
|
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
|
||||||
|
|
||||||
|
/* Interop Constraints */
|
||||||
|
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
||||||
|
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
|
||||||
|
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
||||||
|
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
|
||||||
|
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
||||||
|
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
|
||||||
|
|
||||||
|
/* Type Checking */
|
||||||
|
"strict": true, /* Enable all strict type-checking options. */
|
||||||
|
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
||||||
|
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
||||||
|
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
||||||
|
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
||||||
|
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
||||||
|
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
||||||
|
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
||||||
|
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
||||||
|
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
||||||
|
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
||||||
|
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
||||||
|
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
||||||
|
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
||||||
|
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
||||||
|
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
||||||
|
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
||||||
|
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
||||||
|
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
||||||
|
|
||||||
|
/* Completeness */
|
||||||
|
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
||||||
|
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
||||||
|
}
|
||||||
|
}
|
||||||
1
utils/index.ts
Normal file
1
utils/index.ts
Normal file
@ -0,0 +1 @@
|
|||||||
|
export * from './utils';
|
||||||
25
utils/utils.ts
Normal file
25
utils/utils.ts
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
/**
|
||||||
|
* Runs the function `fn`
|
||||||
|
* and retries automatically if it fails.
|
||||||
|
*
|
||||||
|
* Tries max `1 + retries` times
|
||||||
|
* with `retryIntervalMs` milliseconds between retries.
|
||||||
|
*
|
||||||
|
* From https://mtsknn.fi/blog/js-retry-on-fail/
|
||||||
|
*/
|
||||||
|
export const retry = async <T>(
|
||||||
|
fn: () => Promise<T> | T,
|
||||||
|
{ retries, retryIntervalMs }: { retries: number; retryIntervalMs: number },
|
||||||
|
): Promise<T> => {
|
||||||
|
try {
|
||||||
|
return await fn();
|
||||||
|
} catch (error) {
|
||||||
|
if (retries <= 0) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
await sleep(retryIntervalMs);
|
||||||
|
return retry(fn, { retries: retries - 1, retryIntervalMs });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const sleep = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
1
wallet.json
Normal file
1
wallet.json
Normal file
@ -0,0 +1 @@
|
|||||||
|
[]
|
||||||
Reference in New Issue
Block a user