Giter Site home page Giter Site logo

adrianmcli / truffle-next Goto Github PK

View Code? Open in Web Editor NEW
194.0 8.0 50.0 267 KB

🛰️ A boilerplate Truffle Box project with Next.js for rapid Ethereum Dapp development

JavaScript 100.00%
truffle truffle-framework reactjs nextjs solidity ethereum ethereum-contract

truffle-next's Introduction

Truffle and Next.js


comet

Rapid Ethereum Dapp Development

made for ethereum to the moon MIT license


A Minimal Smart Contract Development Boilerplate

Truffle is great for developing Solidity smart contracts, but building a React frontend for a smart contract is often a chore. Next.js is one of the easiest ways to build such a frontend and the integration between Truffle and Next.js is what this boilerplate is trying to demonstrate.

There are two major features:

  • A plain truffle init project is used as the base (along with a SimpleStorage example contract).

  • A Next.js project resides in the client directory with a symlink to the output folder of the contract ABI definitions. The Next.js app also provides a simple skeleton for connecting to and interacting with the smart contract on a network.

For more information on how the frontend works, go read the README.md located in the client directory.

Installation

  1. Install Truffle globally.

    npm install -g truffle
  2. Download the box. This also takes care of installing the necessary dependencies.

    truffle unbox adrianmcli/truffle-next
  3. Run the development console.

    truffle develop
  4. Compile and migrate the smart contracts. Note inside the development console we don't preface commands with truffle.

    compile
    migrate
  5. Run the next.js server for the front-end. Smart contract changes must be manually recompiled and migrated.

    // Change directory to the front-end folder
    cd client
    // Serves the front-end on http://localhost:3000
    npm run dev
  6. Truffle can run tests written in Solidity or JavaScript against your smart contracts. Note the command varies slightly if you're in or outside of the development console.

    // If inside the development console.
    test
    
    // If outside the development console..
    truffle test

Running with MetaMask

Since truffle develop exposes the blockchain onto port 9545, you'll need to add a Custom RPC network of http://localhost:9545 in your MetaMask to make it work.

Running with TestRPC

We highly recommend using truffle develop over testrpc, but if you want to use testrpc, there are a couple things you need to do:

  • Change Line 6 of client/lib/getWeb3.js to use localhost:8545 instead of localhost:9545 so we refer to testrpc instead of truffle develop.

  • Run your testrpc with the following command (because reasons):

    testrpc --gasLimit 6721975 --gasPrice 100000000000
    

truffle-next's People

Contributors

adrianmcli avatar erictherobot avatar hskang9 avatar lightswarm124 avatar markspanbroek avatar onlyonejmjq avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

truffle-next's Issues

Make HOC so each page could easily use Web3

Given issue #6, it may be wise to create an HOC like I did here:

import React from "react";
import getWeb3 from "./getWeb3";
import { getAccounts, getContractInstance } from "./utils";

const withWeb3 = PassedComponent => class extends React.Component {
  state = { web3: null, accounts: null, contractInstance: null };

  async componentDidMount() {
    try {
      const web3 = await getWeb3();
      const accounts = await getAccounts(web3);
      const contractInstance = await getContractInstance(web3);
      this.setState({ web3, accounts, contractInstance });
    } catch (error) {
      alert(`Failed to load web3, accounts, and contract. Check console for details.`);
      console.log(error);
    }
  }

  render() {
    const { web3, accounts, contractInstance } = this.state;
    const appReady = web3 && accounts && contractInstance;
    // Web3 is still loading
    if (!appReady) {
      return <div>Loading web3, accounts, and contract instance.</div>;
    }
    // Web3 is ready
    return (
      <PassedComponent
        web3={web3}
        accounts={accounts}
        contractInstance={contractInstance}
      />
    );
  }
};

export default withWeb3;

no web3 connection

I developed an application based on this truffle box. I installed [email protected] within the client directory and otherwise followed the instruction here for the blank box. That works. (as far as I can remember only with truffle develop on port 9545, not on any ganache version).
But even with an identical getWeb3.js I can't get my application (back) to work. I tried truffle develop , Ganache-cli, Ganache GUI, with Chrome + MetaMask 4.9.3 ... and I have no clue how to debug this. I grabbed some messages from the Chromium Develoer console, no idea if that gives any indication to anybody ...

HMR] bundle rebuilding
client.js:222 [HMR] bundle rebuilt in 225ms
process-update.js:27 [HMR] Checking for updates on the server...
process-update.js:98 [HMR] Nothing hot updated.
process-update.js:107 [HMR] App is up to date.
Web3Container.js:19 TypeError: Cannot read property 'getId' of undefined
    at _callee$ (getContract.js:1)
    at tryCatch (runtime.js:62)
    at Generator.invoke [as _invoke] (runtime.js:296)
    at Generator.prototype.(anonymous function) [as next] (http://localhost:3000/_next/static/commons/main.js:30257:21)
    at step (SimpleStorage.json:1)
    at _next (SimpleStorage.json:1)
    at SimpleStorage.json:1
    at new Promise (<anonymous>)
    at SimpleStorage.json:1
    at getContractInstance (getContract.js:1)
property.js:119 Uncaught TypeError: callback is not a function
    at property.js:119
    at requestmanager.js:89
    at inpage.js:1
    at inpage.js:1
    at i (inpage.js:1)
    at inpage.js:1
    at inpage.js:1
    at u (inpage.js:1)
    at s (inpage.js:1)
    at inpage.js:1
web3.version
{api: "0.20.7", getNode: ƒ, getNetwork: ƒ, …}
client.js:214 [HMR] bundle rebuilding
client.js:222 [HMR] bundle rebuilt in 134ms
process-update.js:27 [HMR] Checking for updates on the server...
process-update.js:98 [HMR] Nothing hot updated.
process-update.js:107 [HMR] App is up to date.

web3.eth.net
undefined
web3.eth
Eth {_requestManager: RequestManager, getBalance: ƒ, getStorageAt: ƒ, getCode: ƒ, getBlock: ƒ, …}

Any help highly appreciated !

Switching pages in Next.js may cause app to lose web3

This is because the script for getting web3 waits for the document load event (to make sure the page is done loading). This is great for first load, but not for page transitions. I have fixed this in another repo here by doing the following:

import Web3 from "web3";

const resolveWeb3 = (resolve) => {
  let { web3 } = window;
  const alreadyInjected = typeof web3 !== `undefined`; // i.e. Mist/Metamask

  if (alreadyInjected) {
    web3 = new Web3(web3.currentProvider);
    console.log(`Injected web3 detected.`);
    resolve(web3);
  } else {
    // Fallback to localhost if no web3 injection.
    const provider = new Web3.providers.HttpProvider(`http://localhost:9545`);
    web3 = new Web3(provider);
    console.log(`No web3 instance injected, using Local web3.`);
    resolve(web3);
  }
};

export default () =>
  new Promise((resolve) => {
    // Wait for loading completion to avoid race conditions with web3 injection timing.
    window.addEventListener(`load`, () => {
      resolveWeb3(resolve);
    });
    // If document has loaded already, try to get Web3 immediately.
    if (document.readyState === `complete`) {
      resolveWeb3(resolve);
    }
});

Probably should implement the same here.

Separate Truffle project from frontend client

It's a little confusing to see a client folder inside a Truffle project, especially since a Truffle project has its own JS environment already.

I made an issue on the repo where the code for unboxing truffle boxes reside, but I have a feeling that support for different folder structures may not be what the Truffle gods want.

It's unlikely that this issue will ever be resolved. Consider closing this.

Install failing on Windows due to fsevents

λ truffle unbox adrianmcli/truffle-next
Downloading...
Unpacking...
Setting up...
Error: Command failed: cd client && npm install && npm run link-contracts
npm WARN client@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

ln: creating symbolic link `contracts' to `../../build/contracts': No such file or directory
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] link-contracts: `cd lib && ln -s ../../build/contracts contracts`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] link-contracts script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Work\AppData\Roaming\npm-cache\_logs\2018-01-14T15_52_15_906Z-debug.log

    at ChildProcess.exithandler (child_process.js:272:12)
    at ChildProcess.emit (events.js:160:13)
    at maybeClose (internal/child_process.js:943:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:220:5)

My Dapp and My Accounts pages are stuck

I downloaded the repository as per the instructions, ran truffle, compiled and deployed the contracts.
Successfully ran npm run dev command and rendered index.js.
But account.js and dapp.js are simply stuck on 'Loading Accounts Page...' and never display anything else when clicked on their respective links on index.js.

Allow injection of custom loading component

This is pretty straight-forward, but I'm thinking of making the withWeb3 HOC a separate project completely, so I might be holding off on this for now. Will (try to remember to) update this issue when I get that rolling.

Add linting for development (but not for end users)

Encouraged by #10, I want to add linting to the development of the project. However, I do not think it is a good idea to put in linting for the end user of the Truffle Box. Because of this, we probably need to do the following:

  • Add a package.json at the project root with devDependencies that give us some linting
  • Setup linting for the project
  • Ignore package.json in the project root by adding an entry inside truffle-box.js so that our end users will not be forced to use linting with this Truffle Box.
  • Make sure we don't end up ignoring the package.json inside the /client directory as well!

I'm probably forgetting something, but I'll leave it at this for now.

Thanks again to @markspanbroek for submitting #10.

License missing

Currently your box (I guess especially the Next.js client) cannot be used freely because people would have to ask you for permission. Would you mind adding a license to clear up the situation?

npm error while installing truffle-next in windows

I recently thought of working on a project using truffle and next-js so wanted to install the truffle-next box
However, I encountered some issues, a big list of npm errors

I am copy-pasting the entire list of errors below

× Setting up box
Unbox failed!
× Setting up box
Unbox failed!
Error: Command failed: cd client && npm install && npm run link-contracts
npm ERR! code 128
npm ERR! git dep preparation failed
npm ERR! command C:\Program Files\nodejs\node.exe C:\Users\harsh\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js install --force --cache=C:\Users\harsh\AppData\Local\npm-cache --prefer-offline=false --prefer-online=false --offline=false --no-progress --no-save --no-audit
npm ERR! npm WARN using --force Recommended protections disabled.
npm ERR! npm ERR! code 128
npm ERR! npm ERR! command failed
npm ERR! npm ERR! command git --no-replace-objects ls-remote ssh://[email protected]/gulpjs/gulp.git
npm ERR! npm ERR! [email protected]: Permission denied (publickey).
npm ERR! npm ERR! fatal: Could not read from remote repository.
npm ERR! npm ERR!
npm ERR! npm ERR! Please make sure you have the correct access rights
npm ERR! npm ERR! and the repository exists.
npm ERR!
npm ERR! npm ERR! A complete log of this run can be found in:
npm ERR! npm ERR! C:\Users\harsh\AppData\Local\npm-cache_logs\2022-02-06T06_56_50_418Z-debug.log

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\harsh\AppData\Local\npm-cache_logs\2022-02-06T06_56_52_199Z-debug.log

at checkExecSyncError (node:child_process:826:11)
at Object.execSync (node:child_process:900:15)
at Object.installBoxDependencies (C:\Users\harsh\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\box\dist\lib\utils\unbox.js:139:1)
at Object.setUpBox (C:\Users\harsh\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\box\dist\lib\utils\index.js:66:1)
at C:\Users\harsh\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\box\dist\box.js:183:1
at Generator.next (<anonymous>)
at fulfilled (C:\Users\harsh\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\box\dist\box.js:5:42)
at processTicksAndRejections (node:internal/process/task_queues:96:5)

Truffle v5.4.32 (core: 5.4.32)
Node v16.13.2

I am using Windows 11, along with the version of Node and Truffle as specified above
Does anyone have a resolve to this issue?

Why just one HOC? Why not Render Prop? Why not a compound component?

The Render Prop is more flexible and can be clearer to some users. So why don't we use it?

Reasons:

  1. HOCs are in the React.js docs, but not render props, nor the compound components pattern.
  2. This project was designed for beginner React developers, it's easier to explain the fact that the web3 props are magically injected than it is to explain how they need to pass in a function for rendering.
  3. I don't want to be too opinionated for the user's sake. Maybe they hate render props and want to use HOCs for everything. Or maybe it's the other way around. Either way, IMO, one simple HOC requires the least mental load for a React beginner.

We can probably think of ways to better improve this, any discussion is welcomed. Just remember that the goal is to make this project light, extensible, and easily understood by beginners to React.

Web3Container.js not mounting component for TestRPC/Ganache-CLI

Trying to deploy and test the example web app locally on my computer. I've set up a TestRPC instance on "localhost:8545", and changed the default "localProvider" to the same port number on the getWeb3.js file. The error is caught in at Web3Container.js with the async function "componentDidMount", and no error log showed up on console when running "npm run dev". Not sure what configuration is missing or incorrect

Show usage of web3

The dapp page currently does not demonstrate use of web3. Perhaps we can add a getEthBalance() method in the component class to get the amount of ETH stored in the first account. It might look something like this:

getEthBalance = async () => {
  const { web3, accounts } = this.props
  const balanceInWei = await web3.eth.getBalance(accounts[0])
  this.setState({ ethBalance: balanceInWei / 1e18 })
}

Of course, we must remember to pass in web3:

<Web3Container
  renderLoading={() => <div>Loading Dapp Page...</div>}
  render={({ accounts, contract, web3 }) => (
    <Dapp accounts={accounts} contract={contract} web3={web3} />
  )}
/>

error while truffle unbox

Seunghuns-MBP:truffle-nextjs seunghunlee$ truffle unbox adrianmcli/truffle-next
Downloading...
Unpacking...
Setting up...
Error: Command failed: cd client && npm install && npm run link-contracts
npm ERR! code MODULE_NOT_FOUND
npm ERR! Cannot find module 'minizlib'

npm ERR! A complete log of this run can be found in:
npm ERR! /Users/seunghunlee/.npm/_logs/2018-04-13T11_22_24_183Z-debug.log

at ChildProcess.exithandler (child_process.js:275:12)
at emitTwo (events.js:126:13)
at ChildProcess.emit (events.js:214:7)
at maybeClose (internal/child_process.js:925:16)
at Socket.stream.socket.on (internal/child_process.js:346:11)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at Pipe._handle.close [as _onclose] (net.js:554:12)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.