Skip to content

Commit

Permalink
get the widget to compile (WIP, many TODO-s)
Browse files Browse the repository at this point in the history
  • Loading branch information
kasparkallas authored Oct 7, 2024
1 parent 065b24c commit 2b0d03a
Show file tree
Hide file tree
Showing 11 changed files with 238 additions and 143 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
"turbo": "^1.13.4",
"typescript": "^5.6.2"
},
"packageManager": "pnpm@8.6.1",
"packageManager": "pnpm@9.12.0",
"pnpm": {
"overrides": {
"eslint-plugin-react-hooks": "5.0.0-canary-41f0e9dae-20230907",
Expand Down
3 changes: 2 additions & 1 deletion packages/widget/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,8 @@
"typescript": "^5.6.2",
"viem": "^2.21.18",
"vitest": "^0.34.6",
"wagmi": "^2.12.17"
"wagmi": "^2.12.17",
"@wagmi/core": "^2.13.8"
},
"peerDependencies": {
"viem": "^2",
Expand Down
5 changes: 3 additions & 2 deletions packages/widget/src/AccountAddressCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export function AccountAddressCard({
data-testid="ens-avatar"
alt="ENS avatar"
variant="rounded"
src={ensAvatarResult.data}
src={ensAvatarResult.data as string} // TODO?
sx={{ width: 24, height: 24 }}
/>
) : (
Expand All @@ -86,7 +86,8 @@ export function AccountAddressCard({
title={checksumAddress}
flex={1}
>
{ensNameResult.data ?? shortenedAddress}
{/* TODO? */}
{(ensNameResult.data as string | undefined) ?? shortenedAddress}
</Typography>

<IconButton
Expand Down
46 changes: 32 additions & 14 deletions packages/widget/src/CommandMapper.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import { useQuery } from "@tanstack/react-query";
import { nanoid } from "nanoid";
import { useEffect, useMemo } from "react";
import { Abi, ContractFunctionConfig, getAbiItem, GetValue } from "viem";
import {
Abi,
ContractFunctionName,
ContractFunctionParameters,
getAbiItem,
GetValue,
} from "viem";
import {
useBlockNumber,
usePublicClient,
useReadContract,
useReadContracts,
usePublicClient,
} from "wagmi";
import { useQuery } from "@tanstack/react-query";

import {
Command,
Expand Down Expand Up @@ -78,7 +84,7 @@ export function EnableAutoWrapCommandMapper({
args: [cmd.accountAddress, autoWrapStrategyAddress[cmd.chainId]],
},
],
cacheOnBlock: true,
// cacheOnBlock: true, TODO
});

const [wrapScheduleData, allowanceData] = data ?? [];
Expand Down Expand Up @@ -156,7 +162,7 @@ export function WrapIntoSuperTokensCommandMapper({
abi: erc20ABI,
functionName: "allowance",
args: [cmd.accountAddress, cmd.superTokenAddress],
cacheOnBlock: true,
// cacheOnBlock: true, TODO
}
: undefined,
);
Expand All @@ -175,7 +181,7 @@ export function WrapIntoSuperTokensCommandMapper({
abi: nativeAssetSuperTokenABI,
functionName: "upgradeByETH",
address: cmd.superTokenAddress,
value: cmd.amountWeiFromUnderlyingTokenDecimals,
// value: cmd.amountWeiFromUnderlyingTokenDecimals, // TODO
}),
);
} else {
Expand Down Expand Up @@ -276,17 +282,19 @@ export function SubscribeCommandMapper({
abi: cfAv1ForwarderABI,
functionName: "getFlowrate",
args: [cmd.superTokenAddress, cmd.accountAddress, cmd.receiverAddress],
cacheOnBlock: true,
// cacheOnBlock: true, TODO
});

const checkExistingUpfrontTransfer = cmd.transferAmountWei > 0n;
const {
isSuccess: isSuccessForBlockNumber,
isIdle: isIdleForBlockNumber,
isPaused: isIdleForBlockNumber, // TODO
data: blockNumber,
} = useBlockNumber({
chainId: cmd.chainId,
enabled: checkExistingUpfrontTransfer,
query: {
enabled: checkExistingUpfrontTransfer,
},
});

const publicClient = usePublicClient({
Expand Down Expand Up @@ -316,9 +324,10 @@ export function SubscribeCommandMapper({
});
return logs;
},
enabled:
checkExistingUpfrontTransfer && isSuccessForBlockNumber && publicClient,
retry: 10,
enabled: Boolean(
checkExistingUpfrontTransfer && isSuccessForBlockNumber && publicClient,
),
});

const skipTransfer = useMemo(() => {
Expand Down Expand Up @@ -435,13 +444,22 @@ export function SubscribeCommandMapper({
return null;
}

type ExpectedMutability = "payable" | "nonpayable";

const createContractWrite = <
TAbi extends Abi | readonly unknown[] = Abi,
TFunctionName extends string = string,
>(
arg: ContractFunctionConfig<TAbi, TFunctionName, "payable" | "nonpayable"> &
GetValue<TAbi, TFunctionName> &
Pick<ContractWrite, "commandId" | "displayTitle" | "chainId">,
// TODO: FunctionName
arg: ContractFunctionParameters<
TAbi,
ExpectedMutability,
ContractFunctionName<TAbi, ExpectedMutability>
> &
Pick<ContractWrite, "commandId" | "displayTitle" | "chainId"> &
GetValue<TAbi, TFunctionName> & {
value?: bigint;
},
): ContractWrite =>
({
id: nanoid(),
Expand Down
15 changes: 11 additions & 4 deletions packages/widget/src/ContractWrite.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
import { Abi, ContractFunctionConfig, GetValue } from "viem";
import {
Abi,
ContractFunctionName,
ContractFunctionParameters,
GetValue,
} from "viem";

import { ChainId } from "./core/index.js";

export type ContractWrite = ContractFunctionConfig<
type ExpectedMutability = "payable" | "nonpayable";

export type ContractWrite = ContractFunctionParameters<
Abi,
string,
"payable" | "nonpayable"
ExpectedMutability,
ContractFunctionName<Abi, ExpectedMutability>
> &
GetValue<Abi, string> & {
id: string;
Expand Down
17 changes: 9 additions & 8 deletions packages/widget/src/ContractWriteButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,25 +33,26 @@ export default function ContractWriteButton({

const isLoading =
prepareResult.isLoading ||
writeResult.isLoading ||
writeResult.isPending || // TODO?
transactionResult.isLoading;

const expectedChainId = contractWrite.chainId;
const { chain } = useAccount();
const { switchNetwork } = useSwitchChain();
const { switchChain: switchNetwork } = useSwitchChain();
const { connector } = useAccount();
const needsToSwitchNetwork = expectedChainId !== chain?.id;

const onSwitchNetworkButtonClick = useCallback(() => {
eventHandlers.onButtonClick({ type: "switch_network" });
switchNetwork?.(expectedChainId);
switchNetwork?.({ chainId: expectedChainId });
}, [switchNetwork, expectedChainId, eventHandlers.onButtonClick]);

const onContractWriteButtonClick = useCallback(() => {
eventHandlers.onButtonClick({
type: "invoke_transaction",
});
write?.();
// write?.();
write(); // TODO
}, [write, eventHandlers.onButtonClick]);

const onRetryTransactionButtonClick = useCallback(() => {
Expand Down Expand Up @@ -101,20 +102,20 @@ export default function ContractWriteButton({
const showForceSendButton = Boolean(
isPrepareError &&
!prepareResult.isLoading &&
write &&
!writeResult.isLoading,
// write && TODO
!writeResult.isPending, // TODO
);

const isWriteButtonDisabled = Boolean(
isPrepareError || transactionResult.isSuccess || !write,
);
const writeButtonText = transactionResult.isLoading
? "Waiting for transaction..."
: writeResult.isLoading
: writeResult.isPending // TODO
? "Waiting for wallet..."
: "Send transaction";

const showRetryButton = Boolean(isPrepareError && !writeResult.isLoading);
const showRetryButton = Boolean(isPrepareError && !writeResult.isPending); // TODO

return (
<Stack direction="column" spacing={1}>
Expand Down
78 changes: 47 additions & 31 deletions packages/widget/src/ContractWriteManager.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import {
import {
useAccount,
useSimulateContract,
useWriteContract,
useWaitForTransactionReceipt,
useWriteContract,
} from "wagmi";

import { ContractWrite } from "./ContractWrite.js";
Expand All @@ -19,7 +19,10 @@ import { useWidget } from "./WidgetContext.js";
export type ContractWriteResult = {
contractWrite: ContractWrite;
prepareResult: ReturnType<typeof useSimulateContract>;
writeResult: ReturnType<typeof useWriteContract>;
writeResult: Omit<
ReturnType<typeof useWriteContract>,
"write" | "writeAsync"
> & { write: () => void };
transactionResult: ReturnType<typeof useWaitForTransactionReceipt>;
currentError: BaseError | null;
};
Expand Down Expand Up @@ -58,43 +61,52 @@ export function ContractWriteManager({
...contractWrite,
scopeKey: contractWrite.commandId,
staleTime: 120_000,
value: undefined, // TODO
}
: undefined),
onError: console.error,
// onError: console.error, TODO
});

const writeArgs = useMemo(
() => ({
...(prepare
? prepareResult.isError
? {
mode: "prepared",
request: {
account: accountAddress,
chain: chain,
abi: contractWrite.abi,
address: contractWrite.address,
functionName: contractWrite.functionName,
args: contractWrite.args,
value: contractWrite.value,
gas: 2_500_000n, // Set _some_ kind of a limit more reasonable than the default 28_500_000.
},
}
: prepareResult.isSuccess
? prepareResult.data
: {}
: {}),
}),
[prepareResult],
);

// Always have a write ready.
const writeResult = useWriteContract({
...(prepare
? prepareResult.isError
? {
mode: "prepared",
request: {
account: accountAddress,
chain: chain,
abi: contractWrite.abi,
address: contractWrite.address,
functionName: contractWrite.functionName,
args: contractWrite.args,
value: contractWrite.value,
gas: 2_500_000n, // Set _some_ kind of a limit more reasonable than the default 28_500_000.
},
}
: prepareResult.isSuccess
? prepareResult.config
: {}
: {}),
onError: console.error,
onSuccess: ({ hash }: { hash: any }) =>
eventHandlers.onTransactionSent?.({
hash,
functionName: contractWrite.functionName as TxFunctionName,
}),
mutation: {
onError: console.error,
onSuccess: (hash) =>
eventHandlers.onTransactionSent?.({
hash,
functionName: contractWrite.functionName as TxFunctionName,
}),
},
});

const transactionResult = useWaitForTransactionReceipt({
hash: writeResult.data?.hash,
onError: console.error,
hash: writeResult.data,
// onError: console.error, TODO
});

const result: ContractWriteResult = useMemo(() => {
Expand All @@ -113,7 +125,10 @@ export function ContractWriteManager({
return {
contractWrite,
prepareResult: prepareResult as ReturnType<typeof useSimulateContract>,
writeResult,
writeResult: {
...writeResult,
write: () => writeResult.writeContract(writeArgs as any), // TODO
},
transactionResult,
currentError: (transactionResult.error ||
(transactionResult.isSuccess ? null : writeResult.error) ||
Expand All @@ -128,6 +143,7 @@ export function ContractWriteManager({
writeResult.status,
transactionResult.status,
transactionResult.fetchStatus,
writeArgs,
]);

useEffect(() => void onChange?.(result), [result]);
Expand Down
6 changes: 2 additions & 4 deletions packages/widget/src/ContractWriteStatus.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,12 +92,10 @@ export function ContractWriteStatus({
},
}}
secondaryAction={
writeResult?.data?.hash &&
writeResult?.data &&
chain.blockExplorers?.default && (
<IconButton
href={
chain.blockExplorers.default.url + "/tx/" + writeResult.data.hash
}
href={chain.blockExplorers.default.url + "/tx/" + writeResult.data}
target="_blank"
size="small"
title="View on blockchain explorer"
Expand Down
Loading

0 comments on commit 2b0d03a

Please sign in to comment.