Reputation: 57
I'm trying to code a simple code to swap solana tokens that are on the Raydium Defi.
But I have a PublicKey problem. I don't understand what's wrong with my code.
I really want to make a very simple code for tests:
const { Connection, Keypair, PublicKey } = require('@solana/web3.js');
const { Liquidity, TokenAmount, Token, Percent } = require('@raydium-io/raydium-sdk');
const devnetConnection = new Connection('https://api.devnet.solana.com');
const privateKey = []; // PRIVATE KEY HIDDEN
const wallet = Keypair.fromSecretKey(new Uint8Array(privateKey));
const OWNER = '675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8';
const TOKEN = 'EP2ib6dYdEeqD8MfE2ezHCxX3kP3K2eLKkirfPm5eyMx';
const SOL = 'So11111111111111111111111111111111111111112';
const PAIR = 'CQurpF3WS3yEqFEt1Bu8s5zmZqznQG3EJkcYvsyg3sLc';
async function main() {
const poolKeys = {
id: new PublicKey(OWNER),
};
const tokenA = new Token(devnetConnection, new PublicKey(SOL), 9, wallet.publicKey);
const tokenB = new Token(devnetConnection, new PublicKey(TOKEN), 6, wallet.publicKey);
const rawAmountIn = 1;
const amountIn = new TokenAmount(tokenA, rawAmountIn * 10**tokenA.decimals, false);
const slippage = new Percent(50, 10000);
const poolInfo = await Liquidity.fetchInfo(devnetConnection, poolKeys);
const { minAmountOut } = Liquidity.computeAmountOut(poolInfo, amountIn, tokenB, slippage);
const { transaction, signers } = await Liquidity.makeSwapTransaction({
connection: devnetConnection,
poolKeys,
userKeys: {
owner: wallet.publicKey,
},
amountIn,
amountOut: minAmountOut,
fixedSide: 'in',
});
const signature = await devnetConnection.sendTransaction(transaction, [wallet, ...signers]);
console.log(`Transaction hash: ${signature}`);
await devnetConnection.confirmTransaction(signature);
console.log(`Transaction confirmed: ${signature}`);
}
main().catch(error => {
console.error(error);
});
A simple swap code between 2 tokens with an amount. But I get this response when I run the node:
reason: 'invalid public key',
code: 'INVALID_ARGUMENT',
argument: 'publicKey',
Am I missing anything in my code? And if so, where can I find the information?
I looked at raydium's git, but I want something much simpler for my tests with code like I did but that works :) https://github.com/abbylow/raydium-swap
In the end, it shouldn't be complicated:
and that should be enough!
It's so much simpler on Ethereum or BSC, it drives me crazy Solana. On Ethereum we have Uniswap or Pancakeswap which is super well documented, but Raydium or Orca, the docs aren't complete enough. We just have some Git.
Upvotes: 4
Views: 6038
Reputation: 1
const tokenA = new Token(devnetConnection, new PublicKey(SOL), 9, wallet.publicKey);
Must be
const { TOKEN_PROGRAM_ID } = require('@raydium-io/raydium-sdk');
const tokenA = new Token(TOKEN_PROGRAM_ID, new PublicKey(SOL), 9);
Upvotes: 0