Getting Started with Scaffold-ETH-2

WebSculpt
2 min readDec 11, 2023

--

Image from Shubham Dhage on Unsplash

Haven’t heard of Scaffold-ETH-2 (SE-2)? Still confused about what exactly it means to “Scaffold” Ethereum? Check out my Intro into Scaffold-Eth-2 post.

SE-2 simplifies interactions with your Smart Contracts. Once you understand exactly how to use the following React Hooks, you are off to the races. Let’s talk about how to read, write, and listen.

I’m showing examples from the contract in the (Crowd Fund project) blog series. For Now, all you really need to know is that these “Fund Runs” (in the code) are Crowd Funds that can take donations.

How to read, with useScaffoldContractRead

  const { data: fundRunNonce } = useScaffoldContractRead({
contractName: "CrowdFund",
functionName: "getNonce",
args: [fundRun.fundRunId],
});

You simply need to provide the Contract Name, Function Name, and any Arguments you are calling this function with. You can then access this particular value via: fundRunNonce (or whatever name you give it).

How to listen, by subscribing to events with useScaffoldEventSubscriber:

useScaffoldEventSubscriber({
contractName: "CrowdFund",
eventName: "FundRunCreated",
listener: logs => {
logs.map(log => {
const { id, owners, title, target } = log.args;
console.log(
"📡 New Fund Run Event \ncreator:",
owners,
"\nID: ",
id,
"\nTitle: ",
title,
"\n with a target of: ",
formatEther(target),
);
});
},
});

Here the listener maps all of the given event logs such that they log to the console with the values emitted from the FundRunCreated event.

How to write (non-payable), with useScaffoldContractWrite:

  const { writeAsync, isLoading } = useScaffoldContractWrite({
contractName: "CrowdFund",
functionName: "createFundRun",
args: [titleInput, descInput, targetInput, deadlineInput, ownersList],
onBlockConfirmation: txnReceipt => {
console.log("📦 Transaction blockHash", txnReceipt.blockHash);
},
});

This code is sending Title, Description, Target, Deadline, and a list of Addresses to the createFundRun function. You call this with writeAsync(); and you can attach a loading spinner to the boolean value of isLoading.

How to write with Ether (payable):

const { writeAsync, isLoading } = useScaffoldContractWrite({
contractName: "CrowdFund",
functionName: "donateToFundRun",
args: [fundRun?.id],
onBlockConfirmation: txnReceipt => {
console.log("📦 Transaction blockHash", txnReceipt.blockHash);
},
value: donationInput,
});

The only difference here is that a ‘value’ is provided (which is the Ether Amount value that we are sending to the donateToFundRun function). You call this with writeAsync(); and you can attach a loading spinner to the boolean value of isLoading.

More about payable vs non-payable functions, here.

Learn more about why I use SE-2 here.

If you are ready to start a project with me, CLICK HERE.

--

--

WebSculpt

Blockchain Development, coding on Ethereum. Condensed notes for learning to code in Solidity faster.