Skip to content

Commit

Permalink
updates
Browse files Browse the repository at this point in the history
  • Loading branch information
jennyg0 committed Aug 21, 2024
1 parent b8572c6 commit c4a84c9
Show file tree
Hide file tree
Showing 25 changed files with 378 additions and 235 deletions.
56 changes: 32 additions & 24 deletions templates/svelte/vite-ethers/src/components/SendTransaction.svelte
Original file line number Diff line number Diff line change
@@ -1,40 +1,53 @@
<script lang="ts">
import { ethers } from "ethers";
import { stringify } from "../utils/formatters";
import { etherStore } from "../ethers";
import { useAsync } from "../composables/useAsync";
import { stringify } from "../utils/formatters";
const { getSigner, getProvider } = etherStore;
let address: string | null = "";
let value: string | null = "";
const { state: transactionState, execute: sendTransaction } = useAsync(
async () => {
try {
const signer = await getSigner();
if (!signer) {
throw new Error("Failed to get signer");
const { state: transactionState, execute: sendTransaction } = useAsync(
async () => {
try {
const signer = await getSigner();
if (!signer) {
throw new Error("Failed to get signer");
}
const gasPrice = await getProvider()!.getGasPrice();
const gasLimit = await signer.estimateGas({
to: address!,
value: ethers.parseEther(value!),
gasPrice,
});
const result = await signer.sendTransaction({
to: address!,
value: ethers.parseEther(value!),
gasPrice,
gasLimit,
});
waitForReceipt(result.hash);
return result;
} catch (error) {
console.error("Error sending transaction:", error);
throw error;
}
const result = await signer.sendTransaction({
to: address!,
value: ethers.parseEther(value!),
});
waitForReceipt(result.hash);
return result;
} catch (error) {
console.error("Error sending transaction:", error);
throw error;
}
}
);
);
$: ({ result: transaction, inProgress, error } = $transactionState);
const { state: receiptState, execute: waitForReceipt } = useAsync(
async (transactionHash) => {
return await getProvider()!.waitForTransaction(transactionHash);
},
);
$: ({
result: receipt,
inProgress: receiptInProgress,
Expand All @@ -49,7 +62,6 @@
<button type="submit">Send</button>
</form>

<div>
{#if inProgress}
<div>Transaction pending...</div>
{:else if transaction}
Expand All @@ -59,11 +71,8 @@
Transaction Receipt:
{#if receiptInProgress}
<span>pending...</span>
{:else if receipt}
<pre>{stringify(receipt, null, 2)}</pre>
{:else}
<div>No transaction receipt available</div>
{/if}
<pre>{stringify(receipt, null, 2)}</pre>
</div>
</div>
{/if}
Expand All @@ -75,4 +84,3 @@
<div>Receipt Error: {receiptError?.message}</div>
{/if}
</div>
</div>
33 changes: 23 additions & 10 deletions templates/svelte/vite-ethers/src/components/WriteContract.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,32 @@
const { state: transactionState, execute: writeContract } = useAsync(
async () => {
const contract = new Contract(
daiContractConfig.address,
daiContractConfig.abi,
await getSigner()!,
);
try {
const contract = new Contract(
daiContractConfig.address,
daiContractConfig.abi,
await getSigner()!,
);
// random address for testing, replace with contract address that you want to allow to spend your tokens
const spender = "0xa1cf087DB965Ab02Fb3CFaCe1f5c63935815f044";
// random address for testing, replace with contract address that you want to allow to spend your tokens
const spender = "0xa1cf087DB965Ab02Fb3CFaCe1f5c63935815f044";
const transaction = await contract.approve(spender, amount);
const gasPrice = await getProvider()!.getGasPrice();
const gasLimit = await contract
.getFunction("approve")
.estimateGas(spender, amount);
waitForReceipt(transaction.hash);
return transaction;
const transaction = await contract.approve(spender, amount, {
gasPrice,
gasLimit,
});
waitForReceipt(transaction.hash);
return transaction;
} catch (error) {
console.error("Error sending transaction:", error);
throw error;
}
},
);
$: ({ result: transaction, inProgress, error } = $transactionState);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,31 @@
<script lang="ts">
import { watchBlockNumber } from "@wagmi/core";
import { wagmiConfig } from "../wagmi";
import { onDestroy } from "svelte";
let blockNumber: bigint | null = null;
watchBlockNumber({ listen: true }, (block) => {
blockNumber = block;
const unsubscribe = watchBlockNumber(
{
...wagmiConfig,
listen: true,
},
{
onBlockNumber(block) {
blockNumber = block;
},
}
);
onDestroy(() => {
unsubscribe();
});
</script>

<div>
{blockNumber?.toString()}
{#if blockNumber !== null}
{blockNumber.toString()}
{:else}
Loading...
{/if}
</div>
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,12 @@
<form on:submit|preventDefault={handleSubmit}>
<input
bind:value={$to}
placeholder="Address"
placeholder="address"
type="text"
/>
<input
bind:value={$value}
placeholder="Value (ether)"
placeholder="value (ether)"
type="text"
/>
<button disabled={$isSending || !$to || !$value} type="submit">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,41 @@
<script lang="ts" setup>
import { useAsync } from "../composables/useAsync";
import { fetchBalance as wagmiFetchBalance, type Address } from "@wagmi/core";
<script lang="ts">
import { writable, derived } from 'svelte/store';
import { getBalance } from '@wagmi/core';
import type { Address } from 'viem';
import { formatEther } from 'viem';
import { get } from 'svelte/store';
import { useAsync } from '../composables/useAsync';
import { wagmiConfig } from '../wagmi';
const { state: asyncState, execute: fetchBalance } =
useAsync(wagmiFetchBalance);
$: ({ result: balance, error, inProgress } = $asyncState);
let address = writable("");
let address: Address = "0x";
const { state, execute: fetchBalance } = useAsync(async () => {
const addr = get(address);
if (addr) {
return getBalance(wagmiConfig, { address: addr as Address });
}
return null;
});
const balance = derived(state, ($state) => $state?.result || null);
const error = derived(state, ($state) => $state?.error || null);
const inProgress = derived(state, ($state) => $state?.inProgress || false);
const formattedBalance = derived(balance, ($balance) => {
return $balance ? formatEther($balance.value) : '0.0';
});
</script>

<div>
<div>
Find balance:
<input bind:value={address} type="text" placeholder="wallet address" />
<button on:click={() => fetchBalance({ address })}
>{inProgress ? "fetching..." : "fetch"}</button
>
<input bind:value={$address} type="text" placeholder="wallet address" />
<button on:click={() => fetchBalance()} disabled={$inProgress}>
{$inProgress ? 'fetching...' : 'fetch'}
</button>
</div>
<div>{balance?.formatted || ""}</div>
{#if error}
<div>Error: {error?.message}</div>
<div>{$formattedBalance}</div>
{#if $error}
<div>Error: {$error?.message}</div>
{/if}
</div>
Original file line number Diff line number Diff line change
@@ -1,27 +1,42 @@
<script lang="ts" setup>
import { switchNetwork as wagmiSwitchNetwork } from "@wagmi/core";
<script lang="ts">
import { switchChain } from "@wagmi/core";
import { wagmiConfig, wagmiStore } from "../wagmi";
import { get } from "svelte/store";
import { useAsync } from "../composables/useAsync";
import { wagmiStore } from "../wagmi";
import type { Chain } from "viem";
$: ({ network } = $wagmiStore);
$: ({ account } = get(wagmiStore));
const { execute: switchNetwork, state: asyncState } =
useAsync(wagmiSwitchNetwork);
const chains: readonly Chain[] = wagmiConfig.chains;
const { execute: switchNetwork, state: asyncState } = useAsync(switchChain);
$: ({ inProgress, error } = $asyncState);
const handleSwitchNetwork = async (chainId: number) => {
if (account.isConnected) {
try {
await switchNetwork(wagmiConfig, { chainId });
} catch (err) {
console.error("Error switching network:", err);
}
}
};
$: currentChain = chains.find((chain) => chain.id === account.chainId) || null;
</script>

<div>
<div>
Connected to {network.chain?.name ?? network.chain?.id}
{#if network.chain?.unsupported}
<span>(unsupported)</span>
{/if}
Connected to {currentChain?.name ?? currentChain?.id}
</div>
<br />
<div>
Switch to:
{#each network.chains as item (item.id)}
<button on:click={() => switchNetwork({ chainId: item.id })}>
{#each chains as item (item.id)}
<button
on:click={() => handleSwitchNetwork(item.id)}
disabled={!account.isConnected || currentChain?.id === item.id}
>
{item.name}
</button>
{/each}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
$: ({ account } = $wagmiStore);
const { state: asyncState, execute: fetchContracts } = useAsync(async () => {
return await readContracts({
return await readContracts(wagmiConfig, {
contracts: [
{
...daiContractConfig,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<script lang="ts">
import { readContract } from "@wagmi/core";
import { useAsync } from "../composables/useAsync";
import { wagmiStore } from "../wagmi";
import { wagmiConfig, wagmiStore } from "../wagmi";
import { daiContractConfig } from "../utils/contracts";
import { onMount } from "svelte";
Expand All @@ -11,7 +11,7 @@
state: asyncState,
execute: fetchBalance,
} = useAsync(async () => {
return await readContract({
return await readContract(wagmiConfig, {
...daiContractConfig,
functionName: "balanceOf",
args: [account.address!],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
import { useAsync } from "../composables/useAsync";
import { daiContractConfig } from "../utils/contracts";
import { onMount } from "svelte";
import { wagmiConfig } from "../wagmi";
const { state, execute: fetchTotalSupply } = useAsync(async () => {
return await readContract({
return await readContract(wagmiConfig, {
...daiContractConfig,
functionName: "totalSupply",
});
Expand Down
Loading

0 comments on commit c4a84c9

Please sign in to comment.