11

I've created a simple app to figure out how to use a Phantom wallet to make Solana transactions. I'm trying to follow SolDev course: https://soldev.app/course/interact-with-wallets. When I test the app and I press the button to send Solana to another account I got the following error: Uncaught ReferenceError: Buffer is not defined

enter image description here

This is my Code:

const sendSol = event => {
    event.preventDefault()

    const transaction = new Web3.Transaction()
    const to = Web3.Keypair.generate();

    const sendSolInstruction = Web3.SystemProgram.transfer({
        fromPubkey: publicKey,
        toPubkey: to.publicKey,
        lamports: LAMPORTS_PER_SOL * 0.1
    })

    transaction.add(sendSolInstruction);
    sendTransaction(transaction, connection).then(sig => {
        console.log(sig)
    })
}

I got the error in the line toPubkey: to.publicKey,

Aditional info: I got this warning in the console:

WARNING in ./node_modules/@solana/buffer-layout/lib/Layout.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'D:\Solana\SolanaCourse\solanacourse1\node_modules\@solana\buffer-layout\src\Layout.ts' file: Error: ENOENT: no such file or directory, open 'D:\Solana\SolanaCourse\solanacourse1\node_modules\@solana\buffer-layout\src\Layout.ts'

enter image description here

Hope somebody could help me. If you need extra information please tell me. Thanks!

1
  • Are you using webpack 5 perchance?
    – sohrab
    Commented Jul 15, 2022 at 0:16

5 Answers 5

16

This is happening because the default bundler that comes with create react app(webpack 5) does not polyfill Buffer. The easiest way to fix this is including this code in your app:

import * as buffer from "buffer";
window.Buffer = buffer.Buffer;
2
  • 1
    I try this in a new project without all my settings and can confirm this fix also works for me. Thanks Acheron! Commented Jul 15, 2022 at 16:46
  • Thanks this works for me. I was stuck in solana/web3.js buffer error on a reactjs app. Commented Dec 27, 2022 at 19:47
3

Thanks for trying to help me. I managed to get my code working finally. I've to do a couple of things I want to share:

FIRST: Make sure you've all these dev dependencies installed

"devDependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.3.0",
    "@testing-library/user-event": "^13.5.0",
    "@types/jest": "^28.1.5",
    "@types/node": "^18.0.4",
    "@types/react": "^18.0.15",
    "@types/react-dom": "^18.0.6",
    "process": "^0.11.10",
    "react-app-rewired": "^2.2.1",
    "react-scripts": "5.0.1",
    "source-map-loader": "^4.0.0",
    "typescript": "^4.7.4"
  }

SECOND: Make this change in package.json => "scripts"

"scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject"
  }

THIRD: Create a new file in your project root named "config-overrides.js" with this code in it

const { ProvidePlugin } = require('webpack');

module.exports = function (config, env) {
    return {
        ...config,
        module: {
            ...config.module,
            rules: [
                ...config.module.rules,
                {
                    test: /.(m?js|ts|tsx)$/,
                    enforce: 'pre',
                    use: ['source-map-loader'],
                },
            ],
        },
        plugins: [
            ...config.plugins,
            new ProvidePlugin({
                process: 'process/browser',
            }),
        ],
        resolve: {
            ...config.resolve,
            fallback: {
                assert: require.resolve('assert'),
                buffer: require.resolve('buffer'),
            },
        },
        ignoreWarnings: [/Failed to parse source map/],
    };
};

FOURTH: Create a file in your project root named "tsconfig.js" with this code in it

{
    "compilerOptions": {
        "target": "es5",
        "lib": ["dom", "dom.iterable", "esnext"],
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "noFallthroughCasesInSwitch": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": true,
        "jsx": "react-jsx"
    },
    "include": ["src"]
}

And that's all. I'm not sure if all steps and all dependencies are necessary to solve the issue. I pick a working project from a friend and set mine to have the same settings.

What I could say for sure is that before the THIRD step my code was still not working.

Thanks to people that try to help me. In a new project I will try acheron solution, maybe all my steps are not really needed.

Good luck to all!

1

if you are using Sveltekit after importing the import { Buffer } from 'buffer'; you need to load it in the browser by importing import { browser } from '$app/environment';

if(browser){ window.Buffer = Buffer; }

0

I was using the @solana/web3.js library, client-side version. I got this error suddenly, without any changes to code that was working previously. What worked for me was to use an older version of @solana/web3.js

0

That is webpack5 issue. Because to reduce the size of package webpack5 removed polyfills and you have to manually install them. Easy way to set up is, first install:

npm i node-polyfill-webpack-plugin

Then in your webpack.config.js

const NodePolyfillPlugin = require("node-polyfill-webpack-plugin");

plugins: [
    ....
    new NodePolyfillPlugin(),
   ]

you can fork this repo webpack5-Boilerplate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.