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 21 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
77 changes: 77 additions & 0 deletions docs/recipes/GetCurrentBalanceFromAccount.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
---
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.

Here is the full code, which we will implement in this section :

```tsx title="components/ConnectedAddressBalance.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.

```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>
);
};
```
159 changes: 159 additions & 0 deletions docs/recipes/WagmiContractWriteWithFeedback.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
---
sidebar_position: 4
title: Wagmi useContractWrite with transaction status
description: Show feedback on transaction status to user by `useContractWrite` along with `useTransactor`
---

# Wagmi `useContractWrite` with transaction status

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 provides feedback on the transaction status when using wagmi `useContractWrite`.

Here is the full code, which we will implement in this section:

```tsx title="components/ContractInteraction.tsx"
import * as React from "react";
import { parseEther } from "viem";
import { useContractWrite } from "wagmi";
import { ArrowSmallRightIcon } from "@heroicons/react/24/outline";
import DeployedContracts from "~~/contracts/deployedContracts";
import { useTransactor } from "~~/hooks/scaffold-eth";

export const ContractInteraction = () => {
const writeTx = useTransactor();

const { writeAsync } = useContractWrite({
address: DeployedContracts[31337].YourContract.address,
abi: DeployedContracts[31337].YourContract.abi,
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>
);
};
```

## Implementation

### Step 1: Set Up Your Component

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

```tsx title="components/ContractInteraction.tsx"
import * as React from "react";

export const ContractInteraction = () => {
return <button>Send</button>;
};
```

### Step 2: Configure wagmi's `useContractWrite` hook

Add wagmi's `useContractWrite` hook and configure it with `abi`, `address`, `functionName` etc. Get the ABI and address of your smart contract from the DeployedContracts or you can grab it from ExternalContracts object, those will be used to set up the contract interaction.

```tsx
import * as React from "react";
// highlight-start
import { parseEther } from "viem";
import { useContractWrite } from "wagmi";
import DeployedContracts from "~~/contracts/deployedContracts";
// highlight-end

export const ContractInteraction = () => {
// highlight-start
const { writeAsync } = useContractWrite({
address: DeployedContracts[31337].YourContract.address,
abi: DeployedContracts[31337].YourContract.abi,
functionName: "setGreeting",
value: parseEther("0.01"),
args: ["Hello world!"],
});
// highlight-end

return <button>Send</button>;
};
```

### Step 3: Initialize `useTransactor` hook and send transaction

Initialize the `useTransactor` hook, and use it to wrap `writeAsync` function which we got from `useContractWrite` to show feedback transaction status to user.

```tsx
import * as React from "react";
import { parseEther } from "viem";
import { useContractWrite } from "wagmi";
import DeployedContracts from "~~/contracts/deployedContracts";
// highlight-start
import { useTransactor } from "~~/hooks/scaffold-eth";
// highlight-end

export const ContractInteraction = () => {
const { writeAsync } = useContractWrite({
address: DeployedContracts[31337].YourContract.address,
abi: DeployedContracts[31337].YourContract.abi,
functionName: "setGreeting",
value: parseEther("0.01"),
args: ["Hello world!"],
});

// highlight-start
const writeTx = useTransactor();
// highlight-end

// highlight-start
return <button onClick={() => writeTx(writeAsync, { blockConfirmations: 1 })}>Send</button>;
// highlight-end
};
```

### Step 4: Bonus adding loading state

We can use `isLoading` returned from `useContractWrite` while the transaction is being mined and also `disable` the button.

```tsx
import * as React from "react";
import { parseEther } from "viem";
import { useContractWrite } from "wagmi";
import DeployedContracts from "~~/contracts/deployedContracts";
import { useTransactor } from "~~/hooks/scaffold-eth";

export const ContractInteraction = () => {
// highlight-start
const { writeAsync, isLoading } = useContractWrite({
// highlight-end
address: DeployedContracts[31337].YourContract.address,
abi: DeployedContracts[31337].YourContract.abi,
functionName: "setGreeting",
value: parseEther("0.01"),
args: ["Hello world!"],
});

const writeTx = useTransactor();

return (
// highlight-start
<button onClick={() => writeTx(writeAsync, { blockConfirmations: 1 })} disabled={isLoading}>
{isLoading ? <span className="loading loading-spinner loading-sm"></span> : <>Send</>}
</button>
// highlight-end
);
};
```
Loading