Reputation: 11
I have experienced a bug in Typescript with Solana package @solana/web3.js. I have developed a wallet application to the point where I generate new keypair, establish connection, receive an airdrop, get list of transacations for my publicKey. However, i am stuck at sending a transaction to other wallets.
I run the code below and the catch method logs the error: [ReferenceError: Can't find variable: Buffer] My code:
import {
clusterApiUrl,
Connection,
LAMPORTS_PER_SOL,
Keypair,
ParsedTransactionWithMeta,
Transaction,
SystemProgram,
sendAndConfirmTransaction,
PublicKey,
Signer,
} from '@solana/web3.js';
const [keypair, setKeypair] = useState<Keypair>();
const [keypair2, setKeypair2] = useState<Keypair>();
const connection = new Connection(clusterApiUrl('devnet'), 'confirmed');
const generateNewKeys = () => {
console.log('trying to get new keypair');
setKeypair(() => Keypair.generate());
setKeypair2(() => Keypair.generate());
console.log('Generated new keypair');
};
const sendTransaction = async () => {
console.log('initializing sending');
if (keypair && keypair2) {
try {
console.log('Attempting to send');
let transaction = new Transaction().add(
SystemProgram.transfer({
fromPubkey: keypair.publicKey,
toPubkey: keypair2.publicKey,
lamports: amount * LAMPORTS_PER_SOL,
}),
);
console.log('Created transaction');
const signer: Signer = keypair;
await sendAndConfirmTransaction(connection, transaction, [signer]);
updateBalance();
updateTransactions();
} catch (e) {
console.log(e);
}
}
};
When running the sendTransaction function it logs "Attempting to send" but not the "Created transaction" which points to the problem with creating the variable "transaction".
Honestly i'm stuck, I have compared my code to others, and despite no differences it doesn't work.
Upvotes: 0
Views: 1598
Reputation: 554
I assume it's a project made using Create React App (CRA) and Webpack 5. Webpack 5 does not automatically perform Node.js API polyfills as it used to, so you need to manually do it.
In practice it means:
yarn add -D buffer
Also need to override your Webpack config
const webpack = require("webpack");
module.exports = function override(webpackConfig) {
// ..
webpackConfig.resolve.fallback = {
buffer: require.resolve("buffer"),
};
webpackConfig.plugins = [
...webpackConfig.plugins,
new webpack.ProvidePlugin({
Buffer: ["buffer", "Buffer"],
}),
];
return webpackConfig;
};
Here is an example of Solana dApp made with CRA and Webpack 5 https://github.com/Bonfida/serverless-merch/blob/master/ui/config-overrides.js
Upvotes: 0