Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Recipes section #33

Merged
merged 24 commits into from
Dec 21, 2023
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
23ac3d2
Add recipes category to the sidebar menu
Pabl0cks Oct 30, 2023
697af22
Reduce h1 font-size
Pabl0cks Oct 30, 2023
c6d1624
First version of GetCurrentBalanceFromAccount
Pabl0cks Oct 30, 2023
1a90fbc
First version of WriteToContractWriteAsyncButton
Pabl0cks Oct 30, 2023
7900a37
First version of WaitTxApprovalReceiptLaunchNextTx
Pabl0cks Oct 30, 2023
87cb805
Adjust title to show on index
Pabl0cks Oct 30, 2023
f9c055c
Add function name on Test
Pabl0cks Oct 30, 2023
08c99cf
First version of ContractInteractionUseTransactor
Pabl0cks Oct 30, 2023
a8d1a1d
Create a simplified version of GetCurrentBalanceFromAccount
Pabl0cks Oct 31, 2023
f0d2891
add highlighted styles
Pabl0cks Nov 2, 2023
97f41ec
Implement highlighted guide and full recipe at end on GetCurrentBalan…
Pabl0cks Nov 2, 2023
bcb3a4b
Simplify the explanations and fix NextPage
Pabl0cks Nov 2, 2023
fb5ebe5
move full code at top and minor tweaks for GetCurrBalance
technophile-04 Nov 3, 2023
a6dd48b
try alternate approch for ContractInteraction
technophile-04 Nov 3, 2023
a8e651b
remove expandable from highlighted examples
technophile-04 Nov 3, 2023
e9d697f
Delete old versions of GetCurrentBalance and ContractInteraction
Pabl0cks Nov 8, 2023
e51539e
Small nitpick tweaks for consistence
Pabl0cks Nov 8, 2023
06f3ff4
Small tweaks
Pabl0cks Nov 8, 2023
2d86afe
Update recipe to a iterative approach
Pabl0cks Nov 8, 2023
f2fb2de
Update WaitTxApprovalReceipt recipe to a iterative approach
Pabl0cks Nov 8, 2023
0b2bb11
Small description tweak
Pabl0cks Nov 8, 2023
890504a
Fix WriteToContractWriteAsyncButton recipe description
Pabl0cks Nov 17, 2023
c83c33d
Put recipe code examples in collapsable content, open by default
Pabl0cks Nov 17, 2023
1eeaf81
remove waitTxApprovalReceipt recipe
technophile-04 Dec 21, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
168 changes: 168 additions & 0 deletions docs/recipes/ContractInteractionUseTransactor.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
---
sidebar_position: 4
title: Contract Interaction with useTransactor and useContractWrite
description: Contract Interaction with useTransactor and useContractWrite
---

# Contract Interaction with useTransactor and useContractWrite

This recipe demonstrates how to create a button for contract interaction using the "useTransactor" and "useContractWrite" hooks from the "wagmi" library. The interaction includes the capability to pass dynamic arguments and provides feedback on the transaction status.

## Before You Begin

Before you proceed with this recipe, make sure you have the [required dependencies installed](/quick-start/installation), and you're familiar with setting up your [Ethereum development environment](/quick-start/environment).

This recipe uses [useTransactor](https://wagmi.sh/react/hooks/useAccount) and [useContractWrite](https://wagmi.sh/react/hooks/useAccount) wagmi hooks, and [ParseEther viem utility](https://viem.sh/docs/utilities/parseEther.html#parseether). You can check the details of these hooks and util to acquire more context before implementing this recipe.

## Implementation

### Step 1: Set Up Your Component

Create a new component in the "components" folder called "ContractInteraction.tsx". The component will show a button that will allow users to interact with your smart contract.

Import the necessary libraries and components, adding the following code to the file:

```tsx
import \* as React from "react";
import { useTransactor, useContractWrite } from "wagmi";
import { parseEther } from "viem";
import DeployedContracts from "~~/generated/deployedContracts";

```

Define your functional component, which we'll call ContractInteraction. This component will be exported and used in your application.

```tsx
export const ContractInteraction = () => {
// Your component code will go here.
};
```

### Step 2: Configure the Smart Contract Information

Get the ABI and address of your smart contract from the DeployedContracts object, those will be used to set up the contract interaction. Replace 'YourContract' with the actual contract name, and '31337' with the correct network ID.

```tsx
const yourContractAbi = DeployedContracts[31337][0].contracts.YourContract.abi;
const yourContractAddress = DeployedContracts[31337][0].contracts.YourContract.address;
```

### Step 3: Initialize Hooks for Contract Interaction

Initialize the `useTransactor` hook, which will be used for sending transactions.

```tsx
const writeTx = useTransactor();
```

Use the `useContractWrite` hook to set up the contract interaction.

```tsx
const { writeAsync, isLoading } = useContractWrite({
address: yourContractAddress,
abi: yourContractAbi,
functionName: "setGreeting",
value: parseEther("0.01"),
args: ["Hello world!"],
});
```

### Step 4: Create the Interaction Function

Define the function `handleSetGreeting` to handle the contract interaction.

```tsx
const handleSetGreeting = async () => {
try {
await writeTx(writeAsync, { blockConfirmations: 1 });
} catch (e) {
console.log("Unexpected error in writeTx", e);
}
};
```

### Step 5: Render the User Interface

Create the button that allows users to trigger the contract interaction.

```tsx
return (
<button className="btn btn-primary" onClick={handleSetGreeting} disabled={isLoading}>
{isLoading ? (
<span className="loading loading-spinner loading-sm"></span>
) : (
<>
Send <ArrowSmallRightIcon className="w-3 h-3 mt-0.5" />
</>
)}
</button>
);
```

### Step 6: Add to Your Application

Import the `ContractInteraction` component into your application and include it where you want users to interact with the smart contract.

```tsx
import { ContractInteraction } from "./ContractInteraction";

// Include the ContractInteraction component in your application.
```

### Step 7: Test and Deploy

Test your contract interaction functionality to ensure it works as expected. You can verify if you are getting the same output as executing the Smart Contract `setGreeting` function directly from `Debug` tab.

## Conclusion

By following these steps, you've created a button that allows users to interact with your smart contract. Users can set the greeting message in this example, but you can customize it to suit your contract's specific functionality.

## Full recipe code

<details>
<summary>Here's the complete code for the "ContractInteraction" component:</summary>

```tsx
import { parseEther } from "viem";
import { useContractWrite } from "wagmi";
import { ArrowSmallRightIcon } from "@heroicons/react/24/outline";
import DeployedContracts from "~~/generated/deployedContracts";
import { useTransactor } from "~~/hooks/scaffold-eth";

export const ContractInteraction = () => {
const yourContractAbi = DeployedContracts[31337][0].contracts.YourContract.abi;
const yourContractAddress = DeployedContracts[31337][0].contracts.YourContract.address;

const writeTx = useTransactor();

const { writeAsync, isLoading } = useContractWrite({
address: yourContractAddress,
abi: yourContractAbi,
functionName: "setGreeting",
value: parseEther("0.01"),
args: ["Hello world!"],
});

const handleSetGreeting = async () => {
try {
await writeTx(writeAsync, { blockConfirmations: 1 });
} catch (e) {
console.log("Unexpected error in writeTx", e);
}
};

return (
<button className="btn btn-primary" onClick={handleSetGreeting} disabled={isLoading}>
{isLoading ? (
<span className="loading loading-spinner loading-sm"></span>
) : (
<>
Send <ArrowSmallRightIcon className="w-3 h-3 mt-0.5" />
</>
)}
</button>
);
};
```

</details>
80 changes: 80 additions & 0 deletions docs/recipes/GetCurrentBalanceFromAccount.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
---
sidebar_position: 1
title: Get balance of the connected account
description: Learn how to retrieve and display the ETH balance of the connected account in your dApp.
---

# Get the Current Balance of the Connected Account

This recipe shows how to fetch and display the ETH balance of the currently connected account in your decentralized application.
Pabl0cks marked this conversation as resolved.
Show resolved Hide resolved

<details>
<summary>Here's the complete code for the "ConnectedAddressBalance.tsx" component along with styles:</summary>

```tsx
import { useAccount } from "wagmi";
import { Address, Balance } from "~~/components/scaffold-eth";

export const ConnectedAddressBalance = () => {
const { address: connectedAddress } = useAccount();

return (
<div className="bg-base-300 p-6 rounded-lg max-w-md mx-auto mt-6">
<h2 className="text-lg font-bold mb-2">Your Ethereum Balance</h2>

<div className="text-sm font-semibold mb-2">
Address: <Address address={connectedAddress} />
</div>

<div className="text-sm font-semibold">
Balance: <Balance address={connectedAddress} />
</div>
</div>
);
};
```

</details>

## Implementation guide

### Step 1: Create a new Component

Begin by creating a new component in the `components` folder of your application.

```tsx title="components/ConnectedAddressBalance.tsx"
export const ConnectedAddressBalance = () => {
return (
<div>
<h2>Your Ethereum Balance</h2>
</div>
);
};
```

### Step 2: Retrieve the Connected Account

Fetch the Ethereum address of the currently connected account using the [useAccount wagmi hook](https://wagmi.sh/react/hooks/useAccount) and easily display them using Scaffold ETH-2 [Address](/components/Address) and [Balance](/components/Balance) components

```tsx title="components/ConnectedAddressBalance.tsx"
// highlight-start
import { useAccount } from "wagmi";
import { Address, Balance } from "~~/components/scaffold-eth";
// highlight-end

export const ConnectedAddressBalance = () => {
// highlight-start
const { address: connectedAddress } = useAccount();
// highlight-end

return (
<div>
<h2>Your Ethereum Balance</h2>
{/* highlight-start */}
Address: <Address address={connectedAddress} />
Balance: <Balance address={connectedAddress} />
{/* highlight-end */}
</div>
);
};
```
75 changes: 75 additions & 0 deletions docs/recipes/SimplifiedGetCurrentBalanceFromAccount.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
---
sidebar_position: 1
title: Simplified Get balance of the connected account
description: Learn how to retrieve and display the ETH balance of the connected account in your dApp.
---

# Get the Current Balance of the Connected Account

This recipe shows how to fetch and display the ETH balance of the currently connected account in your decentralized application.

```tsx
import { useAccount } from "wagmi";
import { Address, Balance } from "~~/components/scaffold-eth";

export const ConnectedAddressBalance = () => {
const { address: connectedAddress } = useAccount();

return (
<div className="bg-base-300 p-6 rounded-lg max-w-md mx-auto mt-6">
<h2 className="text-lg font-bold mb-2">Your Ethereum Balance</h2>

<div className="text-sm font-semibold mb-2">
Address: <Address address={connectedAddress} />
</div>

<div className="text-sm font-semibold">
Balance: <Balance address={connectedAddress} />
</div>
</div>
);
};
```

## Implementation guide

### Step 1: Create a new Component

Begin by creating a new component in the "components" folder of your application. We will name it "ConnectedAddressBalance.tsx".

```tsx
import { useAccount } from "wagmi";
import { Address, Balance } from "~~/components/scaffold-eth";

export const ConnectedAddressBalance = () => {
// Your component code will go here.
};
```

### Step 2: Retrieve the Connected Account

Fetch the Ethereum address of the currently connected account using the [useAccount wagmi hook](https://wagmi.sh/react/hooks/useAccount).

```tsx
const { address: connectedAddress } = useAccount();
```

### Step 3: Display the Address and ETH Balance

Now, you can use [Address](/components/Address) and [Balance](/components/Balance) Scaffold ETH-2 components to display the info of your `{connectedAddress}`.

```tsx
return (
<div className="bg-base-300 p-6 rounded-lg max-w-md mx-auto mt-6">
<h2 className="text-lg font-bold mb-2">Your Ethereum Balance</h2>

<div className="text-sm font-semibold mb-2">
Address: <Address address={connectedAddress} />
</div>

<div className="text-sm font-semibold">
Balance: <Balance address={connectedAddress} />
</div>
</div>
);
```
Loading