Skip to content

Commit 8c4b624

Browse files
karooolisfrolic
andauthored
feat(entrykit): gas balance withdraw (#3724)
Co-authored-by: Kevin Ingersoll <kingersoll@gmail.com>
1 parent bc95ea0 commit 8c4b624

5 files changed

Lines changed: 122 additions & 14 deletions

File tree

‎.changeset/purple-fishes-ring.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@latticexyz/entrykit": patch
3+
---
4+
5+
You can now withdraw your gas balance from the Quarry paymaster.

‎packages/entrykit/src/onboarding/ConnectedSteps.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ export function ConnectedSteps({ userClient, initialUserAddress }: Props) {
129129
<div
130130
className={twMerge(
131131
"px-8 flex flex-col",
132-
focusedId && "divide-y divide-neutral-800",
132+
"divide-y divide-neutral-800",
133133
"animate-in animate-duration-300 fade-in slide-in-from-bottom-8",
134134
)}
135135
>

‎packages/entrykit/src/onboarding/quarry/GasBalance.tsx‎

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
import { useEffect } from "react";
12
import { Hex } from "viem";
3+
import { useQueryClient } from "@tanstack/react-query";
24
import { PendingIcon } from "../../icons/PendingIcon";
35
import { Button } from "../../ui/Button";
46
import { Balance } from "../../ui/Balance";
@@ -7,9 +9,8 @@ import { useBalance } from "./useBalance";
79
import { DepositFormContainer } from "../deposit/DepositFormContainer";
810
import { ArrowLeftIcon } from "../../icons/ArrowLeftIcon";
911
import { StepContentProps } from "../common";
10-
import { useEffect } from "react";
11-
import { useQueryClient } from "@tanstack/react-query";
1212
import { usePrevious } from "../../errors/usePrevious";
13+
import { WithdrawGasBalanceButton } from "./WithdrawGasBalanceButton";
1314

1415
export type Props = StepContentProps & {
1516
userAddress: Hex;
@@ -29,7 +30,7 @@ export function GasBalance({ isActive, isExpanded, isFocused, setFocused, userAd
2930

3031
if (isFocused) {
3132
return (
32-
<>
33+
<div>
3334
{isFocused && (
3435
<div className="absolute top-0 left-0">
3536
<div
@@ -41,7 +42,7 @@ export function GasBalance({ isActive, isExpanded, isFocused, setFocused, userAd
4142
</div>
4243
)}
4344
<DepositFormContainer />
44-
</>
45+
</div>
4546
);
4647
}
4748

@@ -54,15 +55,20 @@ export function GasBalance({ isActive, isExpanded, isFocused, setFocused, userAd
5455
{balance.data != null ? <Balance wei={balance.data} /> : <PendingIcon className="text-sm" />}
5556
</div>
5657
</div>
57-
<Button
58-
variant={isActive ? "primary" : "tertiary"}
59-
className="flex-shrink-0 text-sm p-1 w-28"
60-
autoFocus={isActive || isExpanded}
61-
pending={balance.status === "pending"}
62-
onClick={() => setFocused(true)}
63-
>
64-
Top up
65-
</Button>
58+
59+
<div className="flex flex-col gap-1 justify-center items-center">
60+
<Button
61+
variant={isActive ? "primary" : "tertiary"}
62+
className="flex-shrink-0 text-sm p-1 w-28"
63+
autoFocus={isActive || isExpanded}
64+
pending={balance.status === "pending"}
65+
onClick={() => setFocused(true)}
66+
>
67+
Top up
68+
</Button>
69+
70+
<WithdrawGasBalanceButton userAddress={userAddress} />
71+
</div>
6672
</div>
6773
{isExpanded ? <p className="text-sm">Your gas balance is used to pay for onchain computation.</p> : null}
6874
</div>
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
import { Address } from "viem";
2+
import { getAction } from "viem/utils";
3+
import { waitForTransactionReceipt } from "viem/actions";
4+
import { useAccount, useClient, useSwitchChain, useWriteContract } from "wagmi";
5+
import { twMerge } from "tailwind-merge";
6+
import { useMutation } from "@tanstack/react-query";
7+
import { getPaymaster } from "../../getPaymaster";
8+
import { paymasterAbi } from "../../quarry/common";
9+
import { useEntryKitConfig } from "../../EntryKitConfigProvider";
10+
import { useQueryClient } from "@tanstack/react-query";
11+
import { useShowQueryError } from "../../errors/useShowQueryError";
12+
import { useBalance } from "./useBalance";
13+
import { PendingIcon } from "../../icons/PendingIcon";
14+
15+
export type Props = {
16+
userAddress: Address;
17+
};
18+
19+
export function WithdrawGasBalanceButton({ userAddress }: Props) {
20+
const { writeContractAsync } = useWriteContract();
21+
const { switchChain } = useSwitchChain();
22+
const { chain, chainId } = useEntryKitConfig();
23+
const { chainId: userChainId } = useAccount();
24+
const queryClient = useQueryClient();
25+
const client = useClient({ chainId });
26+
const paymaster = getPaymaster(chain);
27+
const balance = useShowQueryError(useBalance(userAddress));
28+
const shouldSwitchChain = chainId != null && chainId !== userChainId;
29+
30+
const withdraw = useMutation({
31+
mutationKey: ["withdraw", userAddress],
32+
mutationFn: async () => {
33+
if (!client) throw new Error("Client not ready.");
34+
if (!paymaster) throw new Error("Paymaster not found");
35+
if (!balance.data) throw new Error("No gas balance to withdraw.");
36+
37+
try {
38+
const hash = await writeContractAsync({
39+
address: paymaster.address,
40+
abi: paymasterAbi,
41+
functionName: "withdrawTo",
42+
args: [userAddress, balance.data],
43+
chainId,
44+
});
45+
await getAction(client, waitForTransactionReceipt, "waitForTransactionReceipt")({ hash });
46+
47+
await Promise.all([
48+
queryClient.invalidateQueries({ queryKey: ["balance"] }),
49+
queryClient.invalidateQueries({ queryKey: ["getPrerequisites"] }),
50+
]);
51+
} catch (error) {
52+
console.error("Error while withdrawing", error);
53+
throw error;
54+
}
55+
},
56+
});
57+
58+
if (balance.data == null || balance.data === 0n) {
59+
return null;
60+
}
61+
62+
return (
63+
<button
64+
onClick={() => {
65+
if (shouldSwitchChain) {
66+
return switchChain({ chainId });
67+
}
68+
withdraw.mutate();
69+
}}
70+
className={twMerge(
71+
"text-sm font-medium text-white/50 group whitespace-nowrap",
72+
withdraw.isPending ? "opacity-50 pointer-events-none" : "cursor-pointer hover:text-white",
73+
)}
74+
disabled={withdraw.isPending}
75+
>
76+
<span className="inline-block">
77+
<span
78+
className={twMerge(
79+
"inline-flex items-center gap-1 underline decoration-neutral-500 underline-offset-4",
80+
!withdraw.isPending && "hover:decoration-orange-500",
81+
shouldSwitchChain && "group-hover:hidden",
82+
)}
83+
>
84+
{withdraw.isPending && <PendingIcon className="w-3 h-3" />}
85+
Withdraw
86+
</span>
87+
88+
{shouldSwitchChain && (
89+
<span className="hidden group-hover:inline-block underline decoration-neutral-500 underline-offset-4 hover:decoration-orange-500">
90+
Switch chain
91+
</span>
92+
)}
93+
</span>
94+
</button>
95+
);
96+
}

‎packages/entrykit/src/quarry/common.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ export const paymasterAbi = parseAbi([
1010
"error BalanceSystem_InsufficientBalance(address user, uint256 amount, uint256 balance)",
1111
"function registerSpender(address spender)",
1212
"function depositTo(address to) payable",
13+
"function withdrawTo(address to, uint256 amount)",
1314
]);
1415

1516
export const paymasterConfig = defineStore({

0 commit comments

Comments
 (0)