10

Github GitHub - austintgriffith/scaffold-eth: πŸ— forkable Ethereum dev stack focu...

 3 years ago
source link: https://github.com/austintgriffith/scaffold-eth
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

building_construction scaffold-eth

is everything you need to get started building decentralized applications powered by Ethereum


|- - | - -|






running_woman Quick Start

required: Node plus Yarn and Git

git clone https://github.com/austintgriffith/scaffold-eth.git

cd scaffold-eth
yarn install
yarn start

in a second terminal window:

cd scaffold-eth
yarn chain

in a third terminal window:

cd scaffold-eth
yarn deploy

lock_with_ink_pen Edit your smart contract YourContract.sol in packages/hardhat/contracts

memo Edit your frontend App.jsx in packages/react-app/src

briefcase Edit your deployment script deploy.js in packages/hardhat/scripts

iphone Open http://localhost:3000 to see the app

building_construction scaffold-eth is a hackthon stack for quick product prototyping on Ethereum.

woman_scientist This scaffolding leverages state of the art tooling from the ecosystem.

test_tube It is a free standing dapp so you can learn by making small changes.

After installing, your dev environment should look like this:

React dev server, HardHat blockchain, deploy terminal, code IDE, and frontend browser.

pencil2 Make small changes to YourContract.sol and watch your app auto update!

repeat You can yarn deploy any time and get a fresh new contract in the frontend:

dollar Each browser has an account in the top right and you can use the faucet (bottom left) to get fuelpump testnet eth for gas:

hammerOnce you have funds, you can call setPurpose on your contract and "write" to the purpose storage:

Look for the HardHat console.log() output in the yarn chain terminal:

alembic Spend some time tinkering with YourContract.sol


=====================================================


telescope Learning Solidity

closed_book Read the docs: https://docs.soliditylang.org

books Go through each topic from solidity by example editing YourContract.sol in building_construction scaffold-eth

e-mail Learn all the Solidity globals and units

man_teacher Start super simple with a counter: uint8 public count = 1;

arrow_down Then a function dec() public {} that does a count = count - 1;

microscope What happens when you subtract 1 from 0? Try it out in the app to see what happens!

toilet UNDERFLOW!?! (ambulanceSolidity >0.8.0 will catch this!)

petri_dish You can iterate and learn as you go. Test your assumptions!

closed_lock_with_key Global variables like msg.sender and msg.value are cryptographically backed and can be used to make rules

memo Keep this cheat sheet handy

hourglass_flowing_sand Maybe we could use block.timestamp or block.number to track time in our contract

lock_with_ink_pen Or maybe keep track of an address public owner; then make a rule like require( msg.sender == owner ); for an important function

receipt Maybe create a smart contract that keeps track of a mapping ( address => uint256 ) public balance;

bank It could be like a decentralized bank that you function deposit() public payable {} and withdraw()

pager Events are really handy for signaling to the frontend. Read more about events here.

calling Spend some time in App.jsx in packages/react-app/src and learn about the artificial_satelliteProviders

warning Big numbers are stored as objects: formatEther and parseEther (ethers.js) will help with WEI->ETH and ETH->WEI.

luggage The single page (searchable) ethers.js docs are pretty great too.

ant The UI framework Ant Design has a bunch of great components.

page_with_curl Check the console log for your app to see some extra output from hooks like useContractReader and useEventListener.

building_construction You'll notice the <Contract /> component that displays the dynamic form as scaffolding for interacting with your contract.

black_square_button Try making a <Button/> that calls writeContracts.YourContract.setPurpose("πŸ‘‹ Hello World") to explore how your UI might work...

speech_balloon Wrap the call to writeContracts with a tx() helper that uses BlockNative's Notify.js.

dna Next learn about structs in Solidity.

ballot_box Maybe an make an array YourStructName[] public proposals; that could call be voted on with function vote() public {}

telescope Your dev environment is perfect for testing assumptions and learning by prototyping.

memo Next learn about the fallback function

money_with_wings Maybe add a receive() external payable {} so your contract will accept ETH?

helicopter OH! Programming decentralized money! sunglasses So rad!


=====================================================


satellite Deploy

artificial_satellite Ready to deploy to a testnet? Change the defaultNetwork in packages/hardhat/hardhat.config.js

closed_lock_with_key Generate a deploy account with yarn generate and view it with yarn account

dollar Fund your deployer account (pro tip: use an instant wallet to send funds to the QR code from yarn account)

Deploy your contract:

yarn deploy

=====================================================


tv Frontend

Edit your frontend App.jsx in packages/react-app/src

satellite Make sure your targetNetwork is the same as construction_worker_woman HardHat's defaultNetwork (where you deployed your contracts).

clown_face Adjust your debugging settings as needed:


lock_with_ink_pen Providers:

Providers are your connections to different blockchains.

The frontend has three different providers that provide different levels of access to different chains:

mainnetProvider: (read only) Alchemy or Infura connection to main Ethereum network (and contracts already deployed like DAI or Uniswap).

localProvider: local HardHat accounts, used to read from your contracts (.env file points you at testnet or mainnet)

injectedProvider: your personal MetaMask, WalletConnect via Argent, or other injected wallet (generates burner-provider on page load)


paperclips Hooks:

Commonly used Ethereum hooks located in packages/react-app/src/:

usePoller(fn, delay): runs a function on app load and then on a custom interval

usePoller(() => {
  //do something cool at start and then every three seconds
}, 3000);

useBalance(address, provider, [pollTime]): poll for the balance of an address from a provider

const localBalance = useBalance(address, localProvider);

useBlockNumber(provider,[pollTime]): get current block number from a provider

const blockNumber = useBlockNumber(props.provider);

useGasPrice([speed]): gets current "fast" price from ethgasstation

const gasPrice = useGasPrice();

useExchangePrice(mainnetProvider, [pollTime]): gets current price of Ethereum on the Uniswap exchange

const price = useExchangePrice(mainnetProvider);

useContractLoader(provider): loads your smart contract interface

const readContracts = useContractLoader(localProvider);
const writeContracts = useContractLoader(injectedProvider);

useContractReader(contracts, contractName, variableName, [pollTime]): reads a variable from your contract and keeps it in the state

const title = useContractReader(props.readContracts, contractName, "title");
const owner = useContractReader(props.readContracts, contractName, "owner");

useEventListener(contracts, contractName, eventName, [provider], [startBlock]): listens for events from a smart contract and keeps them in the state

const ownerUpdates = useEventListener(
  readContracts,
  contractName,
  "UpdateOwner",
  props.localProvider,
  1
);

package Components:

Your commonly used React Ethereum components located in packages/react-app/src/:

mailbox_with_mail<Address />: A simple display for an Ethereum address that uses a Blockie, lets you copy, and links to Etherescan.

  <Address value={address} />
  <Address value={address} size="short" />
  <Address value={address} size="long" blockexplorer="https://blockscout.com/poa/xdai/address/"/>
  <Address value={address} ensProvider={mainnetProvider}/>

fountain_pen<AddressInput />: An input box you control with useState for an Ethereum address that uses a Blockie and ENS lookup/display.

  const [ address, setAddress ] = useState("")
  <AddressInput
    value={address}
    ensProvider={props.ensProvider}
    onChange={(address)=>{
      setAddress(address)
    }}
  />

dollar<Balance />: Displays the balance of an address in either dollars or decimal.

<Balance
  address={address}
  provider={injectedProvider}
  dollarMultiplier={price}
/>

bust_in_silhouette<Account />: Allows your users to start with an Ethereum address on page load but upgrade to a more secure, injected provider, using Web3Modal. It will track your address and localProvider in your app's state:

const [address, setAddress] = useState();
const [injectedProvider, setInjectedProvider] = useState();
const price = useExchangePrice(mainnetProvider);
<Account
  address={address}
  setAddress={setAddress}
  localProvider={localProvider}
  injectedProvider={injectedProvider}
  setInjectedProvider={setInjectedProvider}
  dollarMultiplier={price}
/>

bulbNotice: the <Account /> component will call setAddress and setInjectedProvider for you.


=====================================================


trackball UI Library

antAnt.design is a fantastic UI library with components like the grids, menus, dates, times, buttons, etc.


rescue_worker_helmet Helpers:

Transactor: The transactor returns a tx() function to make running and tracking transactions as simple and standardized as possible. We will bring in BlockNative's Notify library to track our testnet and mainnet transactions.

const tx = Transactor(props.injectedProvider, props.gasPrice);

Then you can use the tx() function to send funds and write to your smart contracts:

tx({
  to: readContracts[contractName].address,
  value: parseEther("0.001"),
});
tx(writeContracts["SmartContractWallet"].updateOwner(newOwner));

radioactiveWarning: You will need to update the configuration for react-app/src/helpers/Transactor.js to use your BlockNative dappId


level_slider Extras:

key Create wallet links to your app with yarn wallet and yarn fundedwallet

arrow_down Installing a new package to your frontend? You need to cd packages/react-app and then yarn add PACKAGE

arrow_down Installing a new package to your backend? You need to cd packages/harthat and then yarn add PACKAGE


passenger_ship Ship it!

You can deploy your app with:

# packge up the static site:

yarn build

# ship it!

yarn surge

OR

yarn s3

OR

yarn ipfs

rocket Good luck!


=====================================================


triangular_flag_on_post Challenges


=====================================================


satellite Examples and Tutorials

(todo: insert all the cool active branches)

^^^ pickPR your building_construction scaffold-eth branch!!! praypraypray ^^^


=====================================================


hammer Built with building_construction scaffold-eth:

Paintings come to life as you "ink" new creations and trade them on Ethereum. A deep dive into framed_picture NFTs, whale OpenSea, crayon react-canvas-draw, art react-color, and flight_arrival onboarding user experience.

running_man SpeedRun video_camera (TODO)

An instant wallet running on xDAI insired by xdai.io.

Poll your holders! Build an example emoji voting system with building_constructionscaffold-eth. lock_with_ink_pen Cryptographically signed votes but tracked off-chain with satellite Zapier and bookmark_tabs Google Sheets.

^^^ pick PLEASE PR your building_construction scaffold-eth project in above!!! praypraypray ^^^


=====================================================


pager Infrastructure


artificial_satellite Using The Graph


microscope Using Tenderly

Tenderly is a platform for monitoring, alerting and trouble-shooting smart contracts. They also have a hardhat plugin and CLI tool that can be helpful for local development!

Hardhat Tenderly announcement blog for reference.

Verifying contracts on Tenderly

scaffold-eth includes the hardhat-tenderly plugin. When deploying to any of the following networks:

["kovan","goerli","mainnet","rinkeby","ropsten","matic","mumbai","xDai","POA"]

You can verify contracts as part of the deploy.js script. We have created a tenderlyVerify() helper function, which takes your contract name and its deployed address:

await tenderlyVerify(
  {contractName: "YourContract",
   contractAddress: yourContract.address
})

Make sure your target network is present in the hardhat networks config, then either update the default network in hardhat.config.js to your network of choice or run:

yarn deploy --network NETWORK_OF_CHOICE

Once verified, they will then be available to view on Tenderly!

Exporting local Transactions

One of Tenderly's best features for builders is the ability to upload local transactions so that you can use all of Tenderly's tools for analysis and debugging. You will need to create a tenderly account if you haven't already.

Exporting local transactions can be done using the Tenderly CLI. Installing the Tenderly CLI:

brew tap tenderly/tenderly
brew install tenderly

See alternative installation steps here

You need to log in and configure for your local chain (including any forking information) - this can be done from any directory, but it probably makes sense to do under /packages/hardhat to ensure that local contracts are also uploaded with the local transaction (see more below!)

cd packages/hardhat
tenderly login
tenderly export init

You can then take transaction hashes from your local chain and run the following from the packages/hardhat directory:

tenderly export <transactionHash>

Which will upload them to tenderly.co/dashboard!

Tenderly also allows users to debug smart contracts deployed to a local fork of some network (see yarn fork). To let Tenderly know that we are dealing with a fork, run the following command:

tenderly export init

CLI will ask you for your network's name and whether you are forking a public network. After choosing the right fork, your exporting will look something like this:

tenderly export <transactionHash> --export-network <networkName>

Note that tenderly.yaml file stores information about all networks that you initialized for exporting transactions. There can be multiple of them in a single file. You only need the --export-network if you have more than one network in your tenderly.yaml config!

A quick note on local contracts: if your local contracts are persisted in a place that Tenderly can find them, then they will also be uploaded as part of the local transaction export, which is one of the freshest features! We have added a call to tenderly.persistArtifacts() as part of the scaffold-eth deploy() script, which stores the contracts & meta-information in a deployments folder, so this should work out of the box.

Another pitfall when dealing with a local network (fork or not) is that you will not see the transaction hash if it fails. This happens because the hardhat detects an error while eth_estimateGas is executed. To prevent such behaviour, you can skip this estimation by passing a gasLimit override when making a call - an example of this is demonstrated in the FunctionForm.jsx file of the Contract component:

let overrides = {}
// Uncomment the next line if you want to skip the gas estimation for each transaction
// overrides.gasLimit = hexlify(1200000);
const returned = await tx(contractFunction(...args, overrides));

One gotcha - Tenderly does not (currently) support yarn workspaces, so any imported solidity contracts need to be local to packages/hardhat for your contracts to be exported. You can achieve this by using nohoist - this has been done for hardhat so that we can export console.sol - see the top-level package.json to see how!

"workspaces": {
  "packages": [
    "packages/*"
  ],
  "nohoist": [
    "**/hardhat",
    "**/hardhat/**"
  ]
}

globe_with_meridians Etherscan

Hardhat has a truly wonderful hardhat-etherscan plugin that takes care of contract verification after deployment. You need to add the following to your hardhat.config.js imports:

require("@nomiclabs/hardhat-etherscan");

Then add your etherscan API key to the module.exports:

etherscan: {
  // Your API key for Etherscan
  // Obtain one at https://etherscan.io/
  apiKey: "YOUR-API-KEY-HERE"
}

Verifying is simple, assuming you are verifying a contract that you have just deployed from your hardhat setup - you just need to run the verify script, passing constructor arguments as an array if necessary (there is an example commented out in the deploy.js):

await run("verify:verify", {
  address: yourContract.address,
  // constructorArguments: args // If your contract has constructor arguments, you can pass them as an array
})

You only have to pass the contract because the plugin figures out which of the locally compiled contracts is the right one to verify. Pretty cool stuff!


large_orange_diamond Using Infura

You will need to update the constants.js in packages/react-app/src with your own Infura ID.


purple_square Blocknative

update the BLOCKNATIVE_DAPPID in packages/react-app/src/constants.js with your own Blocknative DappID


=====================================================


fax Legacy Content


Learn the basics of building_constructionscaffold-eth and building on Ethereum. construction_worker_man HardHat, package create-eth-app, fire hot reloading smart contracts, artificial_satellite providers, link hooks, control_knobs components, and building a decentralized application.


Tutorial 2: rosette The Token

Learn about tokens. [coming soon] What is a token? Why is it cool? How can I deploy one? Exotic mechanisms? (todo)


Learn the basics of Automated Market Makers like unicorn Uniswap. Learn how moneybagReserves affect the chart_with_downwards_trend price, balance_scale trading, and sweat_drops slippage from low liquidity.


Build a simple IPFS application in building_constructionscaffold-eth to learn more about distributed file storage and content addressing.


Tutorial 5: fuelpumpGSN and Meta Transactions

Learn about to provide your users with better UX by abstracting away gas fees and blockchain mechanics. (todo)


Learn how to deploy your smart contract to a production blockchain. Then deploy your applicaton to Surge, S3, and IPFS. Finally, register an ENS and point it at the decentralized content!


speech_balloon Support Chat

Join the telegram to ask questions and find others building with building_construction scaffold-eth!


=====================================================



About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK