I'm trying to perform a token transfer using postman with the script I have, I want the script to be my backend server for token transfers in my unity game.
I have tried multiple debug logs attached to the script and they all come back with the following error:
'Error transferring tokens: Token is not a constructor'
I've been on chatGPT for help but it didn't get me anywhere to be honest I'm not sure if its an issue with the programmes I'm using or if its an issue with the code.
Here is the code (With my keys removed):
const bodyParser = require('body-parser');
const { Connection, PublicKey, Keypair, Transaction, sendAndConfirmTransaction } = require('@solana/web3.js');
const { Token, TOKEN_PROGRAM_ID } = require('@solana/spl-token');
const app = express();
const port = 3001;
app.use(bodyParser.json());
const connection = new Connection('https://api.mainnet-beta.solana.com/');
const privateKeyHex = '';
const senderSecretKey = new Uint8Array((privateKeyHex.match(/.{1,2}/g) || []).map(byte => parseInt(byte, 16)));
const senderKeypair = Keypair.fromSecretKey(senderSecretKey);
const tokenMintAddress = new PublicKey('3XJe9kn4xqKpX94DB5oRz6LvLv3zfqVL59SQs7A19mcP');
app.post('/transfer', async (req, res) => {
const { destination, amount } = req.body;
console.log('Received a request on /transfer with destination:', destination, 'and amount:', amount);
if (!destination || !amount) {
return res.status(400).send('Destination or amount missing!');
}
try {
const destinationAddress = new PublicKey(destination);
const token = new Token(connection, tokenMintAddress, TOKEN_PROGRAM_ID, senderKeypair);
const transactionSignature = await token.transfer(senderKeypair.publicKey, destinationAddress, amount, senderKeypair);
res.send({ transactionSignature });
} catch (error) {
console.error('Error transferring tokens:', error);
res.status(500).send(`Error transferring tokens: ${error.message}`);
}
});
app.listen(port, () => {
console.log(`Server started on http://localhost:${port}`);
});```
I'm fairly new to coding and still learning, so if someone could help me understand the issue and how to fix it would be greatly appreciated.
So far I have tried:
- ensuring the token was correctly imported from the Solana/spl-token
- ensuring spl tokens where in the loaded wallet
- Went through script to check for errors