diff --git a/.changeset/cuddly-rivers-hide.md b/.changeset/cuddly-rivers-hide.md new file mode 100644 index 000000000..1b34e3cfd --- /dev/null +++ b/.changeset/cuddly-rivers-hide.md @@ -0,0 +1,5 @@ +--- +"@frames.js/render": patch +--- + +feat: customizable frame state for useFrame hook diff --git a/.changeset/grumpy-berries-love.md b/.changeset/grumpy-berries-love.md new file mode 100644 index 000000000..0969e5b84 --- /dev/null +++ b/.changeset/grumpy-berries-love.md @@ -0,0 +1,6 @@ +--- +"@frames.js/debugger": patch +"@frames.js/render": patch +--- + +feat: useComposerAction hook diff --git a/.changeset/twenty-pugs-roll.md b/.changeset/twenty-pugs-roll.md new file mode 100644 index 000000000..41a0bfcb9 --- /dev/null +++ b/.changeset/twenty-pugs-roll.md @@ -0,0 +1,7 @@ +--- +"frames.js": patch +"@frames.js/debugger": patch +"@frames.js/render": patch +--- + +feat: multi specification support diff --git a/packages/debugger/app/components/action-debugger.tsx b/packages/debugger/app/components/action-debugger.tsx index c6835584b..851358855 100644 --- a/packages/debugger/app/components/action-debugger.tsx +++ b/packages/debugger/app/components/action-debugger.tsx @@ -9,7 +9,6 @@ import { cn } from "@/lib/utils"; import { type FarcasterFrameContext, type FrameActionBodyPayload, - OnComposeFormActionFuncReturnType, defaultTheme, } from "@frames.js/render"; import { ParsingReport } from "frames.js"; @@ -26,7 +25,6 @@ import React, { useEffect, useImperativeHandle, useMemo, - useRef, useState, } from "react"; import { Button } from "../../@/components/ui/button"; @@ -37,12 +35,9 @@ import { useFrame } from "@frames.js/render/use-frame"; import { WithTooltip } from "./with-tooltip"; import { useToast } from "@/components/ui/use-toast"; import type { CastActionDefinitionResponse } from "../frames/route"; -import { ComposerFormActionDialog } from "./composer-form-action-dialog"; -import { AwaitableController } from "../lib/awaitable-controller"; -import type { ComposerActionFormResponse } from "frames.js/types"; -import { CastComposer, CastComposerRef } from "./cast-composer"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import type { FarcasterSigner } from "@frames.js/render/identity/farcaster"; +import { ComposerActionDebugger } from "./composer-action-debugger"; type FrameDebuggerFramePropertiesTableRowsProps = { actionMetadataItem: CastActionDefinitionResponse; @@ -227,47 +222,9 @@ export const ActionDebugger = React.forwardRef< } }, [copySuccess, setCopySuccess]); - const [composeFormActionDialogSignal, setComposerFormActionDialogSignal] = - useState | null>(null); const actionFrameState = useFrame({ ...farcasterFrameConfig, - async onComposerFormAction({ form }) { - try { - const dialogSignal = new AwaitableController< - OnComposeFormActionFuncReturnType, - ComposerActionFormResponse - >(form); - - setComposerFormActionDialogSignal(dialogSignal); - - const result = await dialogSignal; - - // if result is undefined then user closed the dialog window without submitting - // otherwise we have updated data - if (result?.composerActionState) { - castComposerRef.current?.updateState(result.composerActionState); - } - - return result; - } catch (e) { - console.error(e); - toast({ - title: "Error occurred", - description: - e instanceof Error - ? e.message - : "Unexpected error, check the console for more info", - variant: "destructive", - }); - } finally { - setComposerFormActionDialogSignal(null); - } - }, }); - const castComposerRef = useRef(null); const [castActionDefinition, setCastActionDefinition] = useState refreshUrl()} > - { - if (actionMetadataItem.status !== "success") { - console.error(actionMetadataItem); - - toast({ - title: "Invalid action metadata", - description: - "Please check the console for more information", - variant: "destructive", - }); - return; - } - - Promise.resolve( - actionFrameState.onComposerActionButtonPress({ - castAction: { - ...actionMetadataItem.action, - url: actionMetadataItem.url, - }, - composerActionState, - // clear stack, this removes first item that will appear in the debugger - clearStack: true, - }) - ).catch((e: unknown) => { - // eslint-disable-next-line no-console -- provide feedback to the user - console.error(e); - }); + { + setActiveTab("cast-action"); }} /> - - {!!composeFormActionDialogSignal && ( - { - composeFormActionDialogSignal.resolve(undefined); - }} - onSave={({ composerState }) => { - composeFormActionDialogSignal.resolve({ - composerActionState: composerState, - }); - }} - onTransaction={farcasterFrameConfig.onTransaction} - onSignature={farcasterFrameConfig.onSignature} - /> - )} diff --git a/packages/debugger/app/components/cast-composer.tsx b/packages/debugger/app/components/cast-composer.tsx index 8452fa809..957a48bae 100644 --- a/packages/debugger/app/components/cast-composer.tsx +++ b/packages/debugger/app/components/cast-composer.tsx @@ -11,29 +11,21 @@ import { ExternalLinkIcon, } from "lucide-react"; import IconByName from "./octicons"; -import { useFrame } from "@frames.js/render/use-frame"; +import { useFrame_unstable } from "@frames.js/render/use-frame"; import { WithTooltip } from "./with-tooltip"; -import type { - FarcasterFrameContext, - FrameActionBodyPayload, - FrameStackDone, -} from "@frames.js/render"; +import { fallbackFrameContext } from "@frames.js/render"; import { FrameUI } from "./frame-ui"; import { useToast } from "@/components/ui/use-toast"; import { ToastAction } from "@radix-ui/react-toast"; import Link from "next/link"; -import type { FarcasterSigner } from "@frames.js/render/identity/farcaster"; +import { useFarcasterIdentity } from "../hooks/useFarcasterIdentity"; +import { useAccount } from "wagmi"; +import { FrameStackDone } from "@frames.js/render/unstable-types"; +import { useDebuggerFrameState } from "../hooks/useDebuggerFrameState"; type CastComposerProps = { composerAction: Partial; onComposerActionClick: (state: ComposerActionState) => any; - farcasterFrameConfig: Parameters< - typeof useFrame< - FarcasterSigner | null, - FrameActionBodyPayload, - FarcasterFrameContext - > - >[0]; }; export type CastComposerRef = { @@ -43,7 +35,7 @@ export type CastComposerRef = { export const CastComposer = React.forwardRef< CastComposerRef, CastComposerProps ->(({ composerAction, farcasterFrameConfig, onComposerActionClick }, ref) => { +>(({ composerAction, onComposerActionClick }, ref) => { const [state, setState] = useState({ text: "", embeds: [], @@ -79,7 +71,6 @@ export const CastComposer = React.forwardRef< {state.embeds.slice(0, 2).map((embed, index) => (
  • { const filteredEmbeds = state.embeds.filter( (_, i) => i !== index @@ -119,13 +110,6 @@ export const CastComposer = React.forwardRef< CastComposer.displayName = "CastComposer"; type CastEmbedPreviewProps = { - farcasterFrameConfig: Parameters< - typeof useFrame< - FarcasterSigner | null, - FrameActionBodyPayload, - FarcasterFrameContext - > - >[0]; url: string; onRemove: () => void; }; @@ -147,15 +131,21 @@ function isAtLeastPartialFrame(stackItem: FrameStackDone): boolean { ); } -function CastEmbedPreview({ - farcasterFrameConfig, - onRemove, - url, -}: CastEmbedPreviewProps) { +function CastEmbedPreview({ onRemove, url }: CastEmbedPreviewProps) { + const account = useAccount(); const { toast } = useToast(); - const frame = useFrame({ - ...farcasterFrameConfig, + const farcasterIdentity = useFarcasterIdentity(); + const frame = useFrame_unstable({ + frameStateHook: useDebuggerFrameState, + async resolveAddress() { + return account.address ?? null; + }, homeframeUrl: url, + frameActionProxy: "/frames", + frameGetProxy: "/frames", + resolveSigner() { + return farcasterIdentity.withContext(fallbackFrameContext); + }, }); const handleFrameError = useCallback( diff --git a/packages/debugger/app/components/composer-action-debugger.tsx b/packages/debugger/app/components/composer-action-debugger.tsx new file mode 100644 index 000000000..faa620999 --- /dev/null +++ b/packages/debugger/app/components/composer-action-debugger.tsx @@ -0,0 +1,51 @@ +import type { + ComposerActionResponse, + ComposerActionState, +} from "frames.js/types"; +import { CastComposer, CastComposerRef } from "./cast-composer"; +import { useRef, useState } from "react"; +import { ComposerFormActionDialog } from "./composer-form-action-dialog"; +import { useFarcasterIdentity } from "../hooks/useFarcasterIdentity"; + +type ComposerActionDebuggerProps = { + url: string; + actionMetadata: Partial; + onToggleToCastActionDebugger: () => void; +}; + +export function ComposerActionDebugger({ + actionMetadata, + url, + onToggleToCastActionDebugger, +}: ComposerActionDebuggerProps) { + const castComposerRef = useRef(null); + const signer = useFarcasterIdentity(); + const [actionState, setActionState] = useState( + null + ); + + return ( + <> + + {!!actionState && ( + { + setActionState(null); + }} + onSubmit={(newActionState) => { + castComposerRef.current?.updateState(newActionState); + setActionState(null); + }} + onToggleToCastActionDebugger={onToggleToCastActionDebugger} + /> + )} + + ); +} diff --git a/packages/debugger/app/components/composer-form-action-dialog.tsx b/packages/debugger/app/components/composer-form-action-dialog.tsx index abea404db..68b18392b 100644 --- a/packages/debugger/app/components/composer-form-action-dialog.tsx +++ b/packages/debugger/app/components/composer-form-action-dialog.tsx @@ -5,221 +5,158 @@ import { DialogHeader, DialogTitle, } from "@/components/ui/dialog"; -import { OnSignatureFunc, OnTransactionFunc } from "@frames.js/render"; -import type { - ComposerActionFormResponse, - ComposerActionState, -} from "frames.js/types"; -import { useCallback, useEffect, useRef } from "react"; -import { Abi, TypedDataDomain } from "viem"; -import { z } from "zod"; - -const createCastRequestSchemaLegacy = z.object({ - type: z.literal("createCast"), - data: z.object({ - cast: z.object({ - parent: z.string().optional(), - text: z.string(), - embeds: z.array(z.string().min(1).url()).min(1), - }), - }), -}); - -const ethSendTransactionActionSchema = z.object({ - chainId: z.string(), - method: z.literal("eth_sendTransaction"), - attribution: z.boolean().optional(), - params: z.object({ - abi: z.custom(), - to: z.custom<`0x${string}`>( - (val): val is `0x${string}` => - typeof val === "string" && val.startsWith("0x") - ), - value: z.string().optional(), - data: z - .custom<`0x${string}`>( - (val): val is `0x${string}` => - typeof val === "string" && val.startsWith("0x") - ) - .optional(), - }), -}); - -const ethSignTypedDataV4ActionSchema = z.object({ - chainId: z.string(), - method: z.literal("eth_signTypedData_v4"), - params: z.object({ - domain: z.custom(), - types: z.unknown(), - primaryType: z.string(), - message: z.record(z.unknown()), - }), -}); - -const walletActionRequestSchema = z.object({ - jsonrpc: z.literal("2.0"), - id: z.string(), - method: z.literal("fc_requestWalletAction"), - params: z.object({ - action: z.union([ - ethSendTransactionActionSchema, - ethSignTypedDataV4ActionSchema, - ]), - }), -}); - -const createCastRequestSchema = z.object({ - jsonrpc: z.literal("2.0"), - id: z.union([z.string(), z.number(), z.null()]), - method: z.literal("fc_createCast"), - params: z.object({ - cast: z.object({ - parent: z.string().optional(), - text: z.string(), - embeds: z.array(z.string().min(1).url()).min(1), - }), - }), -}); - -const composerActionMessageSchema = z.union([ - createCastRequestSchemaLegacy, - walletActionRequestSchema, - createCastRequestSchema, -]); +import { useComposerAction } from "@frames.js/render/use-composer-action"; +import type { ComposerActionState } from "frames.js/types"; +import { useRef } from "react"; +import { + useAccount, + useChainId, + useSendTransaction, + useSignTypedData, + useSwitchChain, +} from "wagmi"; +import { useConnectModal } from "@rainbow-me/rainbowkit"; +import { useToast } from "@/components/ui/use-toast"; +import { ToastAction } from "@/components/ui/toast"; +import { parseEther } from "viem"; +import { parseChainId } from "../lib/utils"; +import { FarcasterMultiSignerInstance } from "@frames.js/render/identity/farcaster"; +import { AlertTriangleIcon, Loader2Icon } from "lucide-react"; type ComposerFormActionDialogProps = { - composerActionForm: ComposerActionFormResponse; + actionState: ComposerActionState; + url: string; + signer: FarcasterMultiSignerInstance; onClose: () => void; - onSave: (arg: { composerState: ComposerActionState }) => void; - onTransaction?: OnTransactionFunc; - onSignature?: OnSignatureFunc; - // TODO: Consider moving this into return value of onTransaction - connectedAddress?: `0x${string}`; + onSubmit: (actionState: ComposerActionState) => void; + onToggleToCastActionDebugger: () => void; }; -export function ComposerFormActionDialog({ - composerActionForm, +export const ComposerFormActionDialog = ({ + actionState, + signer, + url, onClose, - onSave, - onTransaction, - onSignature, - connectedAddress, -}: ComposerFormActionDialogProps) { - const onSaveRef = useRef(onSave); - onSaveRef.current = onSave; - + onSubmit, + onToggleToCastActionDebugger, +}: ComposerFormActionDialogProps) => { const iframeRef = useRef(null); + const { toast } = useToast(); + const account = useAccount(); + const currentChainId = useChainId(); + const { switchChainAsync } = useSwitchChain(); + const { sendTransactionAsync } = useSendTransaction(); + const { signTypedDataAsync } = useSignTypedData(); + const { openConnectModal } = useConnectModal(); + + const result = useComposerAction({ + url, + enabled: !signer.isLoadingSigner, + proxyUrl: "/frames", + actionState, + signer, + async resolveAddress() { + if (account.address) { + return account.address; + } - const postMessageToIframe = useCallback( - (message: any) => { - if (iframeRef.current && iframeRef.current.contentWindow) { - iframeRef.current.contentWindow.postMessage( - message, - new URL(composerActionForm.url).origin - ); + if (!openConnectModal) { + throw new Error("Connect modal is not available"); } + + openConnectModal(); + + return null; }, - [composerActionForm.url] - ); + onError(error) { + console.error(error); + + if ( + error.message.includes( + "Unexpected composer action response from the server" + ) + ) { + toast({ + title: "Error occurred", + description: + "It seems that you tried to call a cast action in the composer action debugger.", + variant: "destructive", + action: ( + { + onToggleToCastActionDebugger(); + }} + > + Switch + + ), + }); - useEffect(() => { - const handleMessage = (event: MessageEvent) => { - if (event.origin !== new URL(composerActionForm.url).origin) { return; } - const result = composerActionMessageSchema.safeParse(event.data); + toast({ + title: "Error occurred", + description: ( +
    +

    {error.message}

    +

    Please check the console for more information

    +
    + ), + variant: "destructive", + }); + }, + async onCreateCast(arg) { + onSubmit(arg.cast); + }, + async onSignature({ action, address }) { + const { chainId, params } = action; + const requestedChainId = parseChainId(chainId); - // on error is not called here because there can be different messages that don't have anything to do with composer form actions - // instead we are just waiting for the correct message - if (!result.success) { - console.warn("Invalid message received", event.data, result.error); - return; + if (currentChainId !== requestedChainId) { + await switchChainAsync({ chainId: requestedChainId }); } - const message = result.data; + const hash = await signTypedDataAsync(params); - if ("type" in message) { - // Handle legacy messages - onSaveRef.current({ - composerState: message.data.cast, - }); - } else if (message.method === "fc_requestWalletAction") { - if (message.params.action.method === "eth_sendTransaction") { - onTransaction?.({ - transactionData: message.params.action, - }).then((txHash) => { - if (txHash) { - postMessageToIframe({ - jsonrpc: "2.0", - id: message.id, - result: { - address: connectedAddress, - transactionId: txHash, - }, - }); - } else { - postMessageToIframe({ - jsonrpc: "2.0", - id: message.id, - error: { - code: -32000, - message: "User rejected the request", - }, - }); - } - }); - } else if (message.params.action.method === "eth_signTypedData_v4") { - onSignature?.({ - signatureData: { - chainId: message.params.action.chainId, - method: message.params.action.method, - params: { - domain: message.params.action.params.domain, - types: message.params.action.params.types as any, - primaryType: message.params.action.params.primaryType, - message: message.params.action.params.message, - }, - }, - }).then((signature) => { - if (signature) { - postMessageToIframe({ - jsonrpc: "2.0", - id: message.id, - result: { - address: connectedAddress, - transactionId: signature, - }, - }); - } else { - postMessageToIframe({ - jsonrpc: "2.0", - id: message.id, - error: { - code: -32000, - message: "User rejected the request", - }, - }); - } - }); - } - } else if (message.method === "fc_createCast") { - if (message.params.cast.embeds.length > 2) { - console.warn("Only first 2 embeds are shown in the cast"); - } + return { + address, + hash, + }; + }, + async onTransaction({ action, address }) { + const { chainId, params } = action; + const requestedChainId = parseChainId(chainId); - onSaveRef.current({ - composerState: message.params.cast, - }); + if (currentChainId !== requestedChainId) { + await switchChainAsync({ chainId: requestedChainId }); } - }; - window.addEventListener("message", handleMessage); + const hash = await sendTransactionAsync({ + to: params.to, + data: params.data, + value: parseEther(params.value ?? "0"), + }); + + return { + address, + hash, + }; + }, + onMessageRespond(message, form) { + if (iframeRef.current && iframeRef.current.contentWindow) { + iframeRef.current.contentWindow.postMessage( + message, + new URL(form.url).origin + ); + } + }, + }); - return () => { - window.removeEventListener("message", handleMessage); - }; - }, []); + if (result.status === "idle") { + return null; + } return ( - - {composerActionForm.title} - -
    - -
    - - - {new URL(composerActionForm.url).hostname} - - + {result.status === "loading" && ( + <> +
    + +
    + + )} + {result.status === "error" && ( + <> +
    + +

    + Something went wrong +

    +

    Check the console

    +
    + + )} + {result.status === "success" && ( + <> + + {result.data.title} + +
    + +
    + + + {new URL(result.data.url).hostname} + + + + )}
    ); -} +}; + +ComposerFormActionDialog.displayName = "ComposerFormActionDialog"; diff --git a/packages/debugger/app/debugger-page.tsx b/packages/debugger/app/debugger-page.tsx index 90d1e3753..cd390136b 100644 --- a/packages/debugger/app/debugger-page.tsx +++ b/packages/debugger/app/debugger-page.tsx @@ -10,6 +10,8 @@ import { type OnSignatureFunc, type FrameActionBodyPayload, type OnConnectWalletFunc, + type FrameContext, + type FarcasterFrameContext, } from "@frames.js/render"; import { attribution } from "@frames.js/render/farcaster"; import { useFrame } from "@frames.js/render/use-frame"; @@ -38,7 +40,7 @@ import { ActionDebugger, ActionDebuggerRef, } from "./components/action-debugger"; -import type { ParseResult } from "frames.js/frame-parsers"; +import type { ParseFramesWithReportsResult } from "frames.js/frame-parsers"; import { Loader2 } from "lucide-react"; import { useToast } from "@/components/ui/use-toast"; import { ToastAction } from "@/components/ui/toast"; @@ -54,7 +56,6 @@ import type { import { useAnonymousIdentity } from "@frames.js/render/identity/anonymous"; import { useFarcasterFrameContext, - useFarcasterMultiIdentity, type FarcasterSigner, } from "@frames.js/render/identity/farcaster"; import { @@ -65,25 +66,14 @@ import { useXmtpFrameContext, useXmtpIdentity, } from "@frames.js/render/identity/xmtp"; +import { useFarcasterIdentity } from "./hooks/useFarcasterIdentity"; +import { InvalidChainIdError, parseChainId } from "./lib/utils"; const FALLBACK_URL = process.env.NEXT_PUBLIC_DEBUGGER_DEFAULT_URL || "http://localhost:3000"; -class InvalidChainIdError extends Error {} class CouldNotChangeChainError extends Error {} -function isValidChainId(id: string): boolean { - return id.startsWith("eip155:"); -} - -function parseChainId(id: string): number { - if (!isValidChainId(id)) { - throw new InvalidChainIdError(`Invalid chainId ${id}`); - } - - return parseInt(id.split("eip155:")[1]!); -} - const anonymousFrameContext = {}; export default function DebuggerPage({ @@ -120,7 +110,8 @@ export default function DebuggerPage({ return undefined; } }, [searchParams.url]); - const [initialFrame, setInitialFrame] = useState(); + const [initialFrame, setInitialFrame] = + useState(); const [initialAction, setInitialAction] = useState(); const [mockHubContext, setMockHubContext] = useState< @@ -254,26 +245,8 @@ export default function DebuggerPage({ refreshUrl(url); }, [url, protocolConfiguration, refreshUrl, toast, debuggerConsole]); - const farcasterSignerState = useFarcasterMultiIdentity({ - onMissingIdentity() { - toast({ - title: "Please select an identity", - description: - "In order to test the buttons you need to select an identity first", - variant: "destructive", - action: ( - { - selectProtocolButtonRef.current?.click(); - }} - type="button" - > - Select identity - - ), - }); - }, + const farcasterSignerState = useFarcasterIdentity({ + selectProtocolButtonRef, }); const xmtpSignerState = useXmtpIdentity(); const lensSignerState = useLensIdentity(); @@ -298,8 +271,6 @@ export default function DebuggerPage({ }, }); - const anonymousFrameContext = {}; - const onConnectWallet: OnConnectWalletFunc = useCallback(async () => { if (!openConnectModal) { throw new Error(`openConnectModal not implemented`); @@ -425,18 +396,19 @@ export default function DebuggerPage({ ); const useFrameConfig: Omit< - UseFrameOptions, FrameActionBodyPayload>, - "signerState" | "specification" + UseFrameOptions< + Record, + FrameActionBodyPayload, + FrameContext + >, + "signerState" | "specification" | "frameContext" > = useMemo( () => ({ homeframeUrl: url, - frame: initialFrame, + frame: + initialFrame?.[protocolConfiguration?.specification ?? "farcaster"], frameActionProxy: "/frames", frameGetProxy: "/frames", - frameContext: { - ...fallbackFrameContext, - address: account.address || fallbackFrameContext.address, - }, connectedAddress: account.address, extraButtonRequestPayload: { mockData: mockHubContext }, onTransaction, @@ -568,12 +540,14 @@ export default function DebuggerPage({ openConnectModal, toast, url, + protocolConfiguration?.specification, ] ); const farcasterFrameConfig: UseFrameOptions< FarcasterSigner | null, - FrameActionBodyPayload + FrameActionBodyPayload, + FarcasterFrameContext > = useMemo(() => { const attributionData = process.env.NEXT_PUBLIC_FARCASTER_ATTRIBUTION_FID ? attribution(parseInt(process.env.NEXT_PUBLIC_FARCASTER_ATTRIBUTION_FID)) @@ -583,13 +557,12 @@ export default function DebuggerPage({ signerState: farcasterSignerState, specification: "farcaster", frameContext: { + ...fallbackFrameContext, ...farcasterFrameContext.frameContext, - address: account.address || farcasterFrameContext.frameContext.address, }, transactionDataSuffix: attributionData, }; }, [ - account.address, farcasterFrameContext.frameContext, farcasterSignerState, useFrameConfig, @@ -635,7 +608,6 @@ export default function DebuggerPage({ }; }, [ anonymousSignerState, - anonymousFrameContext, farcasterFrameConfig, lensFrameContext.frameContext, lensSignerState, diff --git a/packages/debugger/app/frames/route.ts b/packages/debugger/app/frames/route.ts index e7c4b9cce..b6f987512 100644 --- a/packages/debugger/app/frames/route.ts +++ b/packages/debugger/app/frames/route.ts @@ -1,49 +1,18 @@ -import { type FrameActionPayload, getFrame } from "frames.js"; +import { POST as handlePOSTRequest } from "@frames.js/render/next"; import { type NextRequest } from "next/server"; import { getAction } from "../actions/getAction"; import { persistMockResponsesForDebugHubRequests } from "../utils/mock-hub-utils"; import type { SupportedParsingSpecification } from "frames.js"; -import { z } from "zod"; +import { parseFramesWithReports } from "frames.js/parseFramesWithReports"; import type { ParseActionResult } from "../actions/types"; -import type { ParseResult } from "frames.js/frame-parsers"; - -const castActionMessageParser = z.object({ - type: z.literal("message"), - message: z.string().min(1), -}); - -const castActionFrameParser = z.object({ - type: z.literal("frame"), - frameUrl: z.string().min(1).url(), -}); - -const composerActionFormParser = z.object({ - type: z.literal("form"), - url: z.string().min(1).url(), - title: z.string().min(1), -}); - -const jsonResponseParser = z.preprocess((data) => { - if (typeof data === "object" && data !== null && !("type" in data)) { - return { - type: "message", - ...data, - }; - } - - return data; -}, z.discriminatedUnion("type", [castActionFrameParser, castActionMessageParser, composerActionFormParser])); - -const errorResponseParser = z.object({ - message: z.string().min(1), -}); +import type { ParseFramesWithReportsResult } from "frames.js/frame-parsers"; export type CastActionDefinitionResponse = ParseActionResult & { type: "action"; url: string; }; -export type FrameDefinitionResponse = ParseResult & { +export type FrameDefinitionResponse = ParseFramesWithReportsResult & { type: "frame"; }; @@ -91,17 +60,16 @@ export async function GET(request: NextRequest): Promise { } satisfies CastActionDefinitionResponse); } - const htmlString = await urlRes.text(); + const html = await urlRes.text(); - const result = getFrame({ - htmlString, - url, - specification, + const parseResult = parseFramesWithReports({ + html, + fallbackPostUrl: url, fromRequestMethod: "GET", }); return Response.json({ - ...result, + ...parseResult, type: "frame", } satisfies FrameDefinitionResponse); } catch (err) { @@ -118,122 +86,7 @@ export async function GET(request: NextRequest): Promise { /** Proxies frame actions to avoid CORS issues and preserve user IP privacy */ export async function POST(req: NextRequest): Promise { - const body = (await req.clone().json()) as FrameActionPayload; - const isPostRedirect = - req.nextUrl.searchParams.get("postType") === "post_redirect"; - const isTransactionRequest = - req.nextUrl.searchParams.get("postType") === "tx"; - const postUrl = req.nextUrl.searchParams.get("postUrl"); - const specification = - req.nextUrl.searchParams.get("specification") ?? "farcaster"; - - if (!isSpecificationValid(specification)) { - return Response.json({ message: "Invalid specification" }, { status: 400 }); - } - - // TODO: refactor useful logic back into render package - - if (specification === "farcaster") { - await persistMockResponsesForDebugHubRequests(req); - } - - if (!postUrl) { - return Response.error(); - } - - try { - const r = await fetch(postUrl, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - redirect: isPostRedirect ? "manual" : undefined, - body: JSON.stringify(body), - }); - - if (r.status === 302) { - return Response.json( - { - location: r.headers.get("location"), - }, - { status: 302 } - ); - } + await persistMockResponsesForDebugHubRequests(req); - // this is an error, just return response as is - if (r.status >= 500) { - return Response.json(await r.text(), { status: r.status }); - } - - if (r.status >= 400 && r.status < 500) { - const parseResult = await z - .promise(errorResponseParser) - .safeParseAsync(r.clone().json()); - - if (!parseResult.success) { - return Response.json( - { message: await r.clone().text() }, - { status: r.status } - ); - } - - const headers = new Headers(r.headers); - // Proxied requests could have content-encoding set, which breaks the response - headers.delete("content-encoding"); - return new Response(r.body, { - headers, - status: r.status, - statusText: r.statusText, - }); - } - - if (isPostRedirect && r.status !== 302) { - return Response.json( - { - message: `Invalid response status code for post redirect button, 302 expected, got ${r.status}`, - }, - { status: 400 } - ); - } - - if (isTransactionRequest) { - const transaction = (await r.json()) as JSON; - return Response.json(transaction); - } - - // Content type is JSON, could be an action - if (r.headers.get("content-type")?.includes("application/json")) { - const parseResult = await z - .promise(jsonResponseParser) - .safeParseAsync(r.clone().json()); - - if (!parseResult.success) { - throw new Error("Invalid frame response"); - } - - const headers = new Headers(r.headers); - // Proxied requests could have content-encoding set, which breaks the response - headers.delete("content-encoding"); - return new Response(r.body, { - headers, - status: r.status, - statusText: r.statusText, - }); - } - - const htmlString = await r.text(); - - const result = getFrame({ - htmlString, - url: body.untrustedData.url, - specification, - fromRequestMethod: "POST", - }); - - return Response.json(result); - } catch (err) { - // eslint-disable-next-line no-console -- provide feedback to the user - console.error(err); - return Response.error(); - } + return handlePOSTRequest(req); } diff --git a/packages/debugger/app/hooks/useDebuggerFrameState.ts b/packages/debugger/app/hooks/useDebuggerFrameState.ts new file mode 100644 index 000000000..554343953 --- /dev/null +++ b/packages/debugger/app/hooks/useDebuggerFrameState.ts @@ -0,0 +1,150 @@ +import type { + FrameState, + FrameStateAPI, + UseFrameStateOptions, +} from "@frames.js/render/unstable-types"; +import { useFrameState } from "@frames.js/render/unstable-use-frame-state"; + +function computeDurationInSeconds(start: Date, end: Date): number { + return Number(((end.getTime() - start.getTime()) / 1000).toFixed(2)); +} + +type ExtraPending = { + startTime: Date; + requestDetails: { + body?: object; + searchParams?: URLSearchParams; + }; +}; + +type SharedResponseExtra = { + response: Response; + responseStatus: number; + responseBody: unknown; + /** + * The speed of the response in seconds + */ + speed: number; +}; + +type ExtraDone = SharedResponseExtra; + +type ExtraDoneRedirect = SharedResponseExtra; + +type ExtraRequestError = Pick & { + response: Response | null; + responseStatus: number; + responseBody: unknown; +}; + +type ExtraMessage = SharedResponseExtra; + +type DebuggerFrameState = FrameState< + ExtraPending, + ExtraDone, + ExtraDoneRedirect, + ExtraRequestError, + ExtraMessage +>; +type DebuggerFrameStateAPI = FrameStateAPI< + ExtraPending, + ExtraDone, + ExtraDoneRedirect, + ExtraRequestError, + ExtraMessage +>; + +type DebuggerFrameStateOptions = Omit< + UseFrameStateOptions< + ExtraPending, + ExtraDone, + ExtraDoneRedirect, + ExtraRequestError, + ExtraMessage + >, + "resolveDoneExtra" +>; + +export function useDebuggerFrameState( + options: DebuggerFrameStateOptions +): [DebuggerFrameState, DebuggerFrameStateAPI] { + return useFrameState< + ExtraPending, + ExtraDone, + ExtraDoneRedirect, + ExtraRequestError, + ExtraMessage + >({ + ...options, + resolveGETPendingExtra() { + return { + startTime: new Date(), + requestDetails: {}, + }; + }, + resolvePOSTPendingExtra(arg) { + return { + startTime: new Date(), + requestDetails: { + body: arg.action.body, + searchParams: arg.action.searchParams, + }, + }; + }, + resolveDoneExtra(arg) { + return { + response: arg.response.clone(), + speed: computeDurationInSeconds( + arg.pendingItem.extra.startTime, + arg.endTime + ), + responseBody: arg.responseBody, + responseStatus: arg.response.status, + }; + }, + resolveDoneRedirectExtra(arg) { + return { + speed: computeDurationInSeconds( + arg.pendingItem.extra.startTime, + arg.endTime + ), + response: arg.response.clone(), + responseStatus: arg.response.status, + responseBody: arg.responseBody, + }; + }, + resolveDoneWithErrorMessageExtra(arg) { + return { + speed: computeDurationInSeconds( + arg.pendingItem.extra.startTime, + arg.endTime + ), + response: arg.response.clone(), + responseBody: arg.responseData, + responseStatus: arg.response.status, + }; + }, + resolveFailedExtra(arg) { + return { + speed: computeDurationInSeconds( + arg.pendingItem.extra.startTime, + arg.endTime + ), + response: arg.response?.clone() ?? null, + responseBody: arg.responseBody, + responseStatus: arg.responseStatus, + }; + }, + resolveFailedWithRequestErrorExtra(arg) { + return { + speed: computeDurationInSeconds( + arg.pendingItem.extra.startTime, + arg.endTime + ), + response: arg.response.clone(), + responseBody: arg.responseBody, + responseStatus: arg.response.status, + }; + }, + }); +} diff --git a/packages/debugger/app/hooks/useFarcasterIdentity.tsx b/packages/debugger/app/hooks/useFarcasterIdentity.tsx new file mode 100644 index 000000000..b3a1f544b --- /dev/null +++ b/packages/debugger/app/hooks/useFarcasterIdentity.tsx @@ -0,0 +1,44 @@ +import { ToastAction } from "@/components/ui/toast"; +import { useToast } from "@/components/ui/use-toast"; +import { useFarcasterMultiIdentity } from "@frames.js/render/identity/farcaster"; +import { WebStorage } from "@frames.js/render/identity/storage"; + +const sharedStorage = new WebStorage(); + +type Options = Omit< + Parameters[0], + "onMissingIdentity" +> & { + selectProtocolButtonRef?: React.RefObject; +}; + +export function useFarcasterIdentity({ + selectProtocolButtonRef, + ...options +}: Options = {}) { + const { toast } = useToast(); + + return useFarcasterMultiIdentity({ + ...(options ?? {}), + storage: sharedStorage, + onMissingIdentity() { + toast({ + title: "Please select an identity", + description: + "In order to test the buttons you need to select an identity first", + variant: "destructive", + action: selectProtocolButtonRef?.current ? ( + { + selectProtocolButtonRef?.current?.click(); + }} + type="button" + > + Select identity + + ) : undefined, + }); + }, + }); +} diff --git a/packages/debugger/app/lib/utils.ts b/packages/debugger/app/lib/utils.ts index 0c58f89ad..7d5402eff 100644 --- a/packages/debugger/app/lib/utils.ts +++ b/packages/debugger/app/lib/utils.ts @@ -18,3 +18,17 @@ export function hasWarnings(reports: Record): boolean { report.some((r) => r.level === "warning") ); } + +export class InvalidChainIdError extends Error {} + +export function isValidChainId(id: string): boolean { + return id.startsWith("eip155:"); +} + +export function parseChainId(id: string): number { + if (!isValidChainId(id)) { + throw new InvalidChainIdError(`Invalid chainId ${id}`); + } + + return parseInt(id.split("eip155:")[1]!); +} diff --git a/packages/debugger/app/utils/mock-hub-utils.ts b/packages/debugger/app/utils/mock-hub-utils.ts index 62001f16c..f57c0fab0 100644 --- a/packages/debugger/app/utils/mock-hub-utils.ts +++ b/packages/debugger/app/utils/mock-hub-utils.ts @@ -71,14 +71,17 @@ export async function loadMockResponseForDebugHubRequest( } export async function persistMockResponsesForDebugHubRequests(req: Request) { - const { - mockData, - untrustedData: { fid: requesterFid, castId }, - } = (await req.clone().json()) as { - mockData: MockHubActionContext; - untrustedData: { fid: string; castId: { fid: string; hash: string } }; + const { mockData, untrustedData } = (await req.clone().json()) as { + mockData?: MockHubActionContext; + untrustedData?: { fid: string; castId?: { fid: string; hash: string } }; }; + if (!mockData || !untrustedData?.castId) { + return; + } + + const { fid: requesterFid, castId } = untrustedData; + const requesterFollowsCaster = `/v1/linkById?${sortedSearchParamsString( new URLSearchParams({ fid: requesterFid, diff --git a/packages/frames.js/package.json b/packages/frames.js/package.json index 6121801f2..b7d824f0e 100644 --- a/packages/frames.js/package.json +++ b/packages/frames.js/package.json @@ -267,6 +267,16 @@ "default": "./dist/hono/index.cjs" } }, + "./parseFramesWithReports": { + "import": { + "types": "./dist/parseFramesWithReports.d.ts", + "default": "./dist/parseFramesWithReports.js" + }, + "require": { + "types": "./dist/parseFramesWithReports.d.cts", + "default": "./dist/parseFramesWithReports.cjs" + } + }, "./remix": { "import": { "types": "./dist/remix/index.d.ts", diff --git a/packages/frames.js/src/frame-parsers/farcaster.test.ts b/packages/frames.js/src/frame-parsers/farcaster.test.ts index 78e327847..826a1938a 100644 --- a/packages/frames.js/src/frame-parsers/farcaster.test.ts +++ b/packages/frames.js/src/frame-parsers/farcaster.test.ts @@ -23,6 +23,7 @@ describe("farcaster frame parser", () => { parseFarcasterFrame(document, { reporter, fallbackPostUrl }) ).toEqual({ status: "success", + specification: "farcaster", reports: {}, frame: { image: "http://example.com/image.png", @@ -46,6 +47,7 @@ describe("farcaster frame parser", () => { parseFarcasterFrame(document, { reporter, fallbackPostUrl }) ).toMatchObject({ status: "failure", + specification: "farcaster", frame: {}, reports: expect.objectContaining({ "fc:frame": [ @@ -71,6 +73,7 @@ describe("farcaster frame parser", () => { parseFarcasterFrame(document, { reporter, fallbackPostUrl }) ).toMatchObject({ status: "failure", + specification: "farcaster", frame: {}, reports: expect.objectContaining({ "fc:frame": [ @@ -96,6 +99,7 @@ describe("farcaster frame parser", () => { parseFarcasterFrame(document, { reporter, fallbackPostUrl }) ).toEqual({ status: "success", + specification: "farcaster", frame: { image: "http://example.com/image.png", ogImage: "http://example.com/image.png", @@ -123,6 +127,7 @@ describe("farcaster frame parser", () => { }) ).toEqual({ status: "success", + specification: "farcaster", reports: { title: [ { @@ -153,6 +158,7 @@ describe("farcaster frame parser", () => { expect(parseFarcasterFrame($, { reporter, fallbackPostUrl })).toEqual({ status: "success", + specification: "farcaster", reports: {}, frame: { version: "vNext", @@ -174,6 +180,7 @@ describe("farcaster frame parser", () => { expect(parseFarcasterFrame($, { reporter, fallbackPostUrl })).toEqual({ status: "success", + specification: "farcaster", reports: {}, frame: { version: "vNext", @@ -196,6 +203,7 @@ describe("farcaster frame parser", () => { expect(parseFarcasterFrame($, { reporter, fallbackPostUrl })).toEqual({ status: "success", + specification: "farcaster", reports: { "og:image": [ { @@ -229,6 +237,7 @@ describe("farcaster frame parser", () => { }) ).toEqual({ status: "success", + specification: "farcaster", reports: {}, frame: { version: "vNext", @@ -249,6 +258,7 @@ describe("farcaster frame parser", () => { expect(parseFarcasterFrame($, { reporter, fallbackPostUrl })).toEqual({ status: "success", + specification: "farcaster", reports: {}, frame: { version: "vNext", @@ -273,6 +283,7 @@ describe("farcaster frame parser", () => { parseFarcasterFrame(document, { reporter, fallbackPostUrl }) ).toMatchObject({ status: "failure", + specification: "farcaster", frame: { version: "vNext", ogImage: "http://example.com/image.png", @@ -303,6 +314,7 @@ describe("farcaster frame parser", () => { parseFarcasterFrame(document, { reporter, fallbackPostUrl }) ).toEqual({ status: "success", + specification: "farcaster", frame: { image: "http://example.com/image.png", ogImage: "http://example.com/image.png", @@ -329,6 +341,7 @@ describe("farcaster frame parser", () => { parseFarcasterFrame(document, { reporter, fallbackPostUrl }) ).toEqual({ status: "success", + specification: "farcaster", frame: { image: "http://example.com/image.png", version: "vNext", @@ -356,6 +369,7 @@ describe("farcaster frame parser", () => { parseFarcasterFrame(document, { reporter, fallbackPostUrl }) ).toEqual({ status: "success", + specification: "farcaster", frame: { image: "http://example.com/image.png", version: "vNext", @@ -384,6 +398,7 @@ describe("farcaster frame parser", () => { parseFarcasterFrame(document, { reporter, fallbackPostUrl }) ).toMatchObject({ status: "failure", + specification: "farcaster", frame: { version: "vNext", image: "http://example.com/image.png", @@ -416,6 +431,7 @@ describe("farcaster frame parser", () => { parseFarcasterFrame(document, { reporter, fallbackPostUrl }) ).toEqual({ status: "success", + specification: "farcaster", frame: { image: "http://example.com/image.png", version: "vNext", @@ -442,6 +458,7 @@ describe("farcaster frame parser", () => { parseFarcasterFrame(document, { reporter, fallbackPostUrl }) ).toEqual({ status: "success", + specification: "farcaster", frame: { image: "http://example.com/image.png", ogImage: "http://example.com/image.png", @@ -471,6 +488,7 @@ describe("farcaster frame parser", () => { parseFarcasterFrame(document, { reporter, fallbackPostUrl }) ).toEqual({ status: "success", + specification: "farcaster", frame: { image: "http://example.com/image.png", version: "vNext", diff --git a/packages/frames.js/src/frame-parsers/farcaster.ts b/packages/frames.js/src/frame-parsers/farcaster.ts index e2919fce4..830324150 100644 --- a/packages/frames.js/src/frame-parsers/farcaster.ts +++ b/packages/frames.js/src/frame-parsers/farcaster.ts @@ -143,6 +143,7 @@ export function parseFarcasterFrame( status: "failure", frame, reports: reporter.toObject(), + specification: "farcaster", }; } @@ -150,5 +151,6 @@ export function parseFarcasterFrame( status: "success", frame: frame as unknown as Frame, reports: reporter.toObject(), + specification: "farcaster", }; } diff --git a/packages/frames.js/src/frame-parsers/open-frames.test.ts b/packages/frames.js/src/frame-parsers/open-frames.test.ts index 92633c2cf..87cc171ba 100644 --- a/packages/frames.js/src/frame-parsers/open-frames.test.ts +++ b/packages/frames.js/src/frame-parsers/open-frames.test.ts @@ -24,6 +24,7 @@ describe("open frames frame parser", () => { parseOpenFramesFrame($, { farcasterFrame: {}, reporter, fallbackPostUrl }) ).toEqual({ status: "success", + specification: "openframes", reports: {}, frame: { accepts: [{ id: "some_protocol", version: "vNext" }], @@ -62,6 +63,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "success", + specification: "openframes", reports: {}, frame: { accepts: [{ id: "myproto", version: "1.0.0" }], @@ -98,6 +100,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "failure", + specification: "openframes", reports: { "of:version": [ { @@ -133,6 +136,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "failure", + specification: "openframes", reports: { "of:version": [ { @@ -169,6 +173,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "success", + specification: "openframes", reports: {}, frame: { accepts: [{ id: "some_protocol", version: "vNext" }], @@ -199,6 +204,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "failure", + specification: "openframes", frame: { accepts: [], version: "vNext", @@ -237,6 +243,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "success", + specification: "openframes", reports: {}, frame: { accepts: [{ id: "farcaster", version: "vNext" }], @@ -267,6 +274,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "success", + specification: "openframes", reports: { title: [ { @@ -305,6 +313,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "success", + specification: "openframes", reports: {}, frame: { accepts: [{ id: "farcaster", version: "vNext" }], @@ -334,6 +343,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "success", + specification: "openframes", reports: {}, frame: { accepts: [{ id: "farcaster", version: "vNext" }], @@ -364,6 +374,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "success", + specification: "openframes", reports: { "og:image": [ { @@ -400,6 +411,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "success", + specification: "openframes", reports: {}, frame: { accepts: [{ id: "some_protocol", version: "vNext" }], @@ -428,6 +440,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "success", + specification: "openframes", reports: {}, frame: { accepts: [{ id: "some_protocol", version: "vNext" }], @@ -458,6 +471,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "failure", + specification: "openframes", reports: { "of:image": [ { @@ -495,6 +509,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "success", + specification: "openframes", reports: {}, frame: { accepts: [{ id: "farcaster", version: "vNext" }], @@ -524,6 +539,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "success", + specification: "openframes", reports: {}, frame: { accepts: [{ id: "some_protocol", version: "vNext" }], @@ -557,6 +573,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "success", + specification: "openframes", reports: {}, frame: { accepts: [{ id: "farcaster", version: "vNext" }], @@ -588,6 +605,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "success", + specification: "openframes", reports: {}, frame: { accepts: [{ id: "some_protocol", version: "vNext" }], @@ -622,6 +640,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "success", + specification: "openframes", reports: {}, frame: { accepts: [{ id: "farcaster", version: "vNext" }], @@ -653,6 +672,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "success", + specification: "openframes", frame: { accepts: [{ id: "some_protocol", version: "vNext" }], version: "vNext", @@ -687,6 +707,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "failure", + specification: "openframes", reports: { "of:post_url": [ { @@ -726,6 +747,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "success", + specification: "openframes", reports: {}, frame: { accepts: [{ id: "farcaster", version: "vNext" }], @@ -756,6 +778,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "success", + specification: "openframes", reports: {}, frame: { accepts: [{ id: "some_protocol", version: "vNext" }], @@ -785,6 +808,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "success", + specification: "openframes", reports: {}, frame: { accepts: [{ id: "farcaster", version: "vNext" }], @@ -818,6 +842,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "success", + specification: "openframes", reports: {}, frame: { accepts: [{ id: "farcaster", version: "vNext" }], @@ -849,6 +874,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "success", + specification: "openframes", reports: {}, frame: { accepts: [{ id: "some_protocol", version: "vNext" }], @@ -884,6 +910,7 @@ describe("open frames frame parser", () => { }) ).toEqual({ status: "success", + specification: "openframes", reports: {}, frame: { accepts: [{ id: "some_protocol", version: "vNext" }], diff --git a/packages/frames.js/src/frame-parsers/open-frames.ts b/packages/frames.js/src/frame-parsers/open-frames.ts index 9a04ecbbf..f589379cd 100644 --- a/packages/frames.js/src/frame-parsers/open-frames.ts +++ b/packages/frames.js/src/frame-parsers/open-frames.ts @@ -194,6 +194,7 @@ export function parseOpenFramesFrame( status: "failure", frame, reports: reporter.toObject(), + specification: "openframes", }; } @@ -201,5 +202,6 @@ export function parseOpenFramesFrame( status: "success", frame: frame as unknown as Frame, reports: reporter.toObject(), + specification: "openframes", }; } diff --git a/packages/frames.js/src/frame-parsers/types.ts b/packages/frames.js/src/frame-parsers/types.ts index b815105d5..f47886fae 100644 --- a/packages/frames.js/src/frame-parsers/types.ts +++ b/packages/frames.js/src/frame-parsers/types.ts @@ -51,6 +51,7 @@ export type ParseResult = * Reports contain only warnings that should not have any impact on the frame's functionality. */ reports: Record; + specification: SupportedParsingSpecification; } | { status: "failure"; @@ -59,4 +60,22 @@ export type ParseResult = * Reports contain warnings and errors that should be addressed before the frame can be used. */ reports: Record; + specification: SupportedParsingSpecification; }; + +export type ParsedFrameworkDetails = { + framesVersion?: string; + framesDebugInfo?: { + /** + * Image URL of debug image. + */ + image?: string; + }; +}; + +export type ParseResultWithFrameworkDetails = ParseResult & + ParsedFrameworkDetails; + +export type ParseFramesWithReportsResult = { + [K in SupportedParsingSpecification]: ParseResultWithFrameworkDetails; +}; diff --git a/packages/frames.js/src/getFrame.test.ts b/packages/frames.js/src/getFrame.test.ts index c19bfe1a5..411823aab 100644 --- a/packages/frames.js/src/getFrame.test.ts +++ b/packages/frames.js/src/getFrame.test.ts @@ -25,6 +25,8 @@ describe("getFrame", () => { }) ).toEqual({ status: "success", + framesVersion: undefined, + specification: "farcaster", frame: { version: "vNext", image: "http://example.com/image.png", @@ -83,6 +85,8 @@ describe("getFrame", () => { expect(frame).toEqual({ status: "success", + framesVersion: undefined, + specification: "farcaster", frame: { version: "vNext", image: "http://example.com/image.png", @@ -113,7 +117,6 @@ describe("getFrame", () => { title: "test", }, reports: {}, - framesVersion: undefined, }); }); @@ -162,6 +165,7 @@ describe("getFrame", () => { expect(parsedFrame).toEqual({ status: "success", + specification: "farcaster", frame: { ...exampleFrame, title: "Test", accepts: undefined }, reports: {}, framesVersion, @@ -192,6 +196,8 @@ describe("getFrame", () => { expect(frame).not.toBeNull(); expect(frame).toEqual({ status: "success", + framesVersion: undefined, + specification: "openframes", frame: { accepts: [{ id: "some", version: "vNext" }], version: "vNext", @@ -279,6 +285,8 @@ describe("getFrame", () => { expect(parseResult).toEqual({ status: "success", + framesVersion: undefined, + specification: "farcaster", frame: { version: "vNext", image: "http://example.com/image.png", @@ -337,6 +345,8 @@ describe("getFrame", () => { expect(frame).toEqual({ status: "success", + framesVersion: undefined, + specification: "farcaster", frame: { version: "vNext", image: "http://example.com/image.png", @@ -353,7 +363,6 @@ describe("getFrame", () => { postUrl: "https://example.com/", }, reports: {}, - framesVersion: undefined, }); }); }); diff --git a/packages/frames.js/src/getFrame.ts b/packages/frames.js/src/getFrame.ts index 03383e31a..130c86c07 100644 --- a/packages/frames.js/src/getFrame.ts +++ b/packages/frames.js/src/getFrame.ts @@ -1,18 +1,10 @@ import type { - ParseResult, SupportedParsingSpecification, + ParseResultWithFrameworkDetails, } from "./frame-parsers/types"; import { parseFramesWithReports } from "./parseFramesWithReports"; -type GetFrameResult = ParseResult & { - framesVersion?: string; - framesDebugInfo?: { - /** - * Image URL of debug image. - */ - image?: string; - }; -}; +export type GetFrameResult = ParseResultWithFrameworkDetails; type GetFrameOptions = { htmlString: string; @@ -51,11 +43,5 @@ export function getFrame({ fromRequestMethod, }); - return { - ...parsedFrames[specification], - framesVersion: parsedFrames.framesVersion, - ...(parsedFrames.framesDebugInfo - ? { framesDebugInfo: parsedFrames.framesDebugInfo } - : {}), - }; + return parsedFrames[specification]; } diff --git a/packages/frames.js/src/parseFramesWithReports.test.ts b/packages/frames.js/src/parseFramesWithReports.test.ts index 9f6cbef7b..7a98deb29 100644 --- a/packages/frames.js/src/parseFramesWithReports.test.ts +++ b/packages/frames.js/src/parseFramesWithReports.test.ts @@ -30,6 +30,8 @@ describe("parseFramesWithReports", () => { }, reports: {}, status: "success", + specification: "farcaster", + framesVersion: undefined, }, openframes: { frame: { @@ -43,6 +45,8 @@ describe("parseFramesWithReports", () => { }, reports: {}, status: "success", + specification: "openframes", + framesVersion: undefined, }, }); }); @@ -78,6 +82,8 @@ describe("parseFramesWithReports", () => { title: "Test", }, reports: {}, + specification: "farcaster", + framesVersion: undefined, status: "success", }, openframes: { @@ -92,6 +98,8 @@ describe("parseFramesWithReports", () => { }, reports: {}, status: "success", + framesVersion: undefined, + specification: "openframes", }, }); }); diff --git a/packages/frames.js/src/parseFramesWithReports.ts b/packages/frames.js/src/parseFramesWithReports.ts index 26bee1e24..c9932a8d9 100644 --- a/packages/frames.js/src/parseFramesWithReports.ts +++ b/packages/frames.js/src/parseFramesWithReports.ts @@ -1,8 +1,8 @@ import { load as loadDocument } from "cheerio"; import { createReporter } from "./frame-parsers/reporter"; import type { - ParseResult, - SupportedParsingSpecification, + ParsedFrameworkDetails, + ParseFramesWithReportsResult, } from "./frame-parsers/types"; import { parseFarcasterFrame } from "./frame-parsers/farcaster"; import { parseOpenFramesFrame } from "./frame-parsers/open-frames"; @@ -24,18 +24,6 @@ type ParseFramesWithReportsOptions = { fromRequestMethod?: "GET" | "POST"; }; -export type ParseFramesWithReportsResult = { - [K in SupportedParsingSpecification]: ParseResult; -} & { - framesVersion?: string; - framesDebugInfo?: { - /** - * Image URL of debug image. - */ - image?: string; - }; -}; - /** * Gets all supported frames and validation their respective validation reports. */ @@ -62,14 +50,14 @@ export function parseFramesWithReports({ `meta[name="${FRAMESJS_DEBUG_INFO_IMAGE_KEY}"], meta[property="${FRAMESJS_DEBUG_INFO_IMAGE_KEY}"]` ).attr("content"); - return { - farcaster, - openframes: parseOpenFramesFrame(document, { - farcasterFrame: farcaster.frame, - reporter: openFramesReporter, - fallbackPostUrl, - fromRequestMethod, - }), + const openframes = parseOpenFramesFrame(document, { + farcasterFrame: farcaster.frame, + reporter: openFramesReporter, + fallbackPostUrl, + fromRequestMethod, + }); + + const frameworkDetails: ParsedFrameworkDetails = { framesVersion, ...(debugImageUrl ? { @@ -79,4 +67,15 @@ export function parseFramesWithReports({ } : {}), }; + + return { + farcaster: { + ...farcaster, + ...frameworkDetails, + }, + openframes: { + ...openframes, + ...frameworkDetails, + }, + }; } diff --git a/packages/frames.js/src/types.ts b/packages/frames.js/src/types.ts index b07bb075f..d87bfa96e 100644 --- a/packages/frames.js/src/types.ts +++ b/packages/frames.js/src/types.ts @@ -5,7 +5,7 @@ export type { SupportedParsingSpecification, } from "./frame-parsers/types"; -export type FrameVersion = "vNext" | `${number}-${number}-${number}`; +export type FrameVersion = string; export type ImageAspectRatio = "1.91:1" | "1:1"; @@ -148,12 +148,7 @@ export type FrameButton = /** The permitted types of `buttonIndex` in a Frame POST payload response */ export type ActionIndex = 1 | 2 | 3 | 4; -export type FrameButtonsType = - | [] - | [FrameButton] - | [FrameButton, FrameButton] - | [FrameButton, FrameButton, FrameButton] - | [FrameButton, FrameButton, FrameButton, FrameButton]; +export type FrameButtonsType = FrameButton[]; export type AddressReturnType< Options extends { fallbackToCustodyAddress?: boolean } | undefined diff --git a/packages/frames.js/src/utils.ts b/packages/frames.js/src/utils.ts index e962419a4..c05c7af13 100644 --- a/packages/frames.js/src/utils.ts +++ b/packages/frames.js/src/utils.ts @@ -6,7 +6,6 @@ import type { FrameButtonLink, FrameButtonMint, FrameButtonTx, - FrameVersion, } from "./types"; export function isFrameButtonLink( @@ -69,7 +68,7 @@ export function getFrameMessageFromRequestBody( * @param version - the version string to validate * @returns true if the provided version conforms to the Frames spec */ -export function isValidVersion(version: string): version is FrameVersion { +export function isValidVersion(version: string): boolean { // Check if the input is exactly 'vNext' if (version === "vNext") { return true; @@ -95,7 +94,7 @@ export function isValidVersion(version: string): version is FrameVersion { export function getEnumKeyByEnumValue< TEnumKey extends string, - TEnumVal extends string | number + TEnumVal extends string | number, >( enumDefinition: { [key in TEnumKey]: TEnumVal }, enumValue: TEnumVal diff --git a/packages/render/package.json b/packages/render/package.json index 8b351b861..fe85535c1 100644 --- a/packages/render/package.json +++ b/packages/render/package.json @@ -46,6 +46,16 @@ "default": "./dist/errors.cjs" } }, + "./helpers": { + "import": { + "types": "./dist/helpers.d.ts", + "default": "./dist/helpers.js" + }, + "require": { + "types": "./dist/helpers.d.cts", + "default": "./dist/helpers.cjs" + } + }, "./next": { "import": { "types": "./dist/next/index.d.ts", @@ -120,6 +130,56 @@ "default": "./dist/use-frame.cjs" } }, + "./use-composer-action": { + "import": { + "types": "./dist/use-composer-action.d.ts", + "default": "./dist/use-composer-action.js" + }, + "require": { + "types": "./dist/use-composer-action.d.cts", + "default": "./dist/use-composer-action.cjs" + } + }, + "./unstable-use-frame-state": { + "import": { + "types": "./dist/unstable-use-frame-state.d.ts", + "default": "./dist/unstable-use-frame-state.js" + }, + "require": { + "types": "./dist/unstable-use-frame-state.d.cts", + "default": "./dist/unstable-use-frame-state.cjs" + } + }, + "./unstable-use-fetch-frame": { + "import": { + "types": "./dist/unstable-use-fetch-frame.d.ts", + "default": "./dist/unstable-use-fetch-frame.js" + }, + "require": { + "types": "./dist/unstable-use-fetch-frame.d.cts", + "default": "./dist/unstable-use-fetch-frame.cjs" + } + }, + "./unstable-use-frame": { + "import": { + "types": "./dist/unstable-use-frame.d.ts", + "default": "./dist/unstable-use-frame.js" + }, + "require": { + "types": "./dist/unstable-use-frame.d.cts", + "default": "./dist/unstable-use-frame.cjs" + } + }, + "./unstable-types": { + "import": { + "types": "./dist/unstable-types.d.ts", + "default": "./dist/unstable-types.js" + }, + "require": { + "types": "./dist/unstable-types.d.cts", + "default": "./dist/unstable-types.cjs" + } + }, "./identity/anonymous": { "import": { "types": "./dist/identity/anonymous/index.d.ts", @@ -225,6 +285,7 @@ "dependencies": { "@farcaster/core": "^0.14.7", "@noble/ed25519": "^2.0.0", - "frames.js": "^0.19.5" + "frames.js": "^0.19.5", + "zod": "^3.23.8" } } diff --git a/packages/render/src/collapsed-frame-ui.tsx b/packages/render/src/collapsed-frame-ui.tsx index 661c8e6ca..1360497a0 100644 --- a/packages/render/src/collapsed-frame-ui.tsx +++ b/packages/render/src/collapsed-frame-ui.tsx @@ -2,6 +2,7 @@ import type { ImgHTMLAttributes } from "react"; import React, { useState } from "react"; import type { Frame } from "frames.js"; import type { FrameTheme, FrameState } from "./types"; +import type { UseFrameReturnValue } from "./unstable-types"; const defaultTheme: Required = { buttonBg: "#fff", @@ -20,7 +21,7 @@ const getThemeWithDefaults = (theme: FrameTheme): FrameTheme => { }; export type CollapsedFrameUIProps = { - frameState: FrameState; + frameState: FrameState | UseFrameReturnValue; theme?: FrameTheme; FrameImage?: React.FC & { src: string }>; allowPartialFrame?: boolean; @@ -138,7 +139,7 @@ export function CollapsedFrameUI({ cursor: isLoading ? undefined : "pointer", }} > - {frame.buttons.length === 1 && frame.buttons[0].label.length < 12 + {!!frame.buttons[0] && frame.buttons[0].label.length < 12 ? frame.buttons[0].label : "View"} diff --git a/packages/render/src/errors.ts b/packages/render/src/errors.ts index ad7dd010b..f6f8f74e3 100644 --- a/packages/render/src/errors.ts +++ b/packages/render/src/errors.ts @@ -33,3 +33,9 @@ export class ComposerActionUnexpectedResponseError extends Error { super("Unexpected composer action response from the server"); } } + +export class ComposerActionUserRejectedRequestError extends Error { + constructor() { + super("User rejected the request"); + } +} diff --git a/packages/render/src/fallback-frame-context.ts b/packages/render/src/fallback-frame-context.ts index 8c5ceef3d..7ba5a77dc 100644 --- a/packages/render/src/fallback-frame-context.ts +++ b/packages/render/src/fallback-frame-context.ts @@ -1,9 +1 @@ -import type { FarcasterFrameContext } from "./farcaster"; - -export const fallbackFrameContext: FarcasterFrameContext = { - castId: { - fid: 1, - hash: "0x0000000000000000000000000000000000000000" as const, - }, - address: "0x0000000000000000000000000000000000000001", -}; +export { fallbackFrameContext } from "./identity/farcaster/use-farcaster-context"; diff --git a/packages/render/src/farcaster/frames.tsx b/packages/render/src/farcaster/frames.tsx index 9341fc322..64f3ec037 100644 --- a/packages/render/src/farcaster/frames.tsx +++ b/packages/render/src/farcaster/frames.tsx @@ -7,7 +7,7 @@ import { getFarcasterTime, makeFrameAction, } from "@farcaster/core"; -import { hexToBytes } from "viem"; +import { bytesToHex, hexToBytes } from "viem"; import type { FrameActionBodyPayload, FrameContext, @@ -15,18 +15,51 @@ import type { SignerStateActionContext, SignFrameActionFunc, } from "../types"; +import type { + SignComposerActionFunc, + SignerStateComposerActionContext, +} from "../unstable-types"; +import { tryCallAsync } from "../helpers"; import type { FarcasterSigner } from "./signers"; +import type { FarcasterFrameContext } from "./types"; -export type FarcasterFrameContext = { - /** Connected address of user, only sent with transaction data request */ - address?: `0x${string}`; - castId: { hash: `0x${string}`; fid: number }; -}; +/** + * Creates a singer request payload to fetch composer action url. + */ +export const signComposerAction: SignComposerActionFunc = + async function signComposerAction(signerPrivateKey, actionContext) { + const messageOrError = await tryCallAsync(() => + createComposerActionMessageWithSignerKey(signerPrivateKey, actionContext) + ); + + if (messageOrError instanceof Error) { + throw messageOrError; + } + + const { message, trustedBytes } = messageOrError; + + return { + untrustedData: { + buttonIndex: 1, + fid: actionContext.fid, + messageHash: bytesToHex(message.hash), + network: 1, + state: Buffer.from(message.data.frameActionBody.state).toString(), + timestamp: new Date().getTime(), + url: actionContext.url, + }, + trustedData: { + messageBytes: trustedBytes, + }, + }; + }; /** Creates a frame action for use with `useFrame` and a proxy */ -export const signFrameAction: SignFrameActionFunc = async ( - actionContext -) => { +export const signFrameAction: SignFrameActionFunc< + FarcasterSigner, + FrameActionBodyPayload, + FarcasterFrameContext +> = async (actionContext) => { const { frameButton, signer, @@ -107,6 +140,43 @@ export const signFrameAction: SignFrameActionFunc = async ( }; }; +export async function createComposerActionMessageWithSignerKey( + signerKey: string, + { fid, state, url }: SignerStateComposerActionContext +): Promise<{ + message: FrameActionMessage; + trustedBytes: string; +}> { + const signer = new NobleEd25519Signer(Buffer.from(signerKey.slice(2), "hex")); + + const messageDataOptions = { + fid, + network: FarcasterNetwork.MAINNET, + }; + + const message = await makeFrameAction( + FrameActionBody.create({ + url: Buffer.from(url), + buttonIndex: 1, + state: Buffer.from(encodeURIComponent(JSON.stringify({ cast: state }))), + }), + messageDataOptions, + signer + ); + + if (message.isErr()) { + throw message.error; + } + + const messageData = message.value; + + const trustedBytes = Buffer.from( + Message.encode(message._unsafeUnwrap()).finish() + ).toString("hex"); + + return { message: messageData, trustedBytes }; +} + export async function createFrameActionMessageWithSignerKey( signerKey: string, { diff --git a/packages/render/src/farcaster/index.ts b/packages/render/src/farcaster/index.ts index 6c8b3f2b3..1816ee9fb 100644 --- a/packages/render/src/farcaster/index.ts +++ b/packages/render/src/farcaster/index.ts @@ -1,3 +1,4 @@ export * from "./frames"; export * from "./signers"; export * from "./attribution"; +export * from "./types"; diff --git a/packages/render/src/farcaster/signers.tsx b/packages/render/src/farcaster/signers.tsx index 4c26f5d4d..58fe6b2a6 100644 --- a/packages/render/src/farcaster/signers.tsx +++ b/packages/render/src/farcaster/signers.tsx @@ -1,7 +1,15 @@ -import type { SignerStateInstance } from ".."; +import type { FrameActionBodyPayload, SignerStateInstance } from "../types"; +import type { SignComposerActionFunc } from "../unstable-types"; +import type { FarcasterFrameContext } from "./types"; export type FarcasterSignerState = - SignerStateInstance; + SignerStateInstance< + TSignerType, + FrameActionBodyPayload, + FarcasterFrameContext + > & { + signComposerAction: SignComposerActionFunc; + }; export type FarcasterSignerPendingApproval = { status: "pending_approval"; diff --git a/packages/render/src/farcaster/types.ts b/packages/render/src/farcaster/types.ts new file mode 100644 index 000000000..faa238842 --- /dev/null +++ b/packages/render/src/farcaster/types.ts @@ -0,0 +1,9 @@ +export type FarcasterFrameContext = { + /** + * Connected address of user, only sent with transaction data request. + * + * @deprecated - not used + */ + address?: `0x${string}`; + castId: { hash: `0x${string}`; fid: number }; +}; diff --git a/packages/render/src/helpers.ts b/packages/render/src/helpers.ts index c4b5b0c46..c18382b23 100644 --- a/packages/render/src/helpers.ts +++ b/packages/render/src/helpers.ts @@ -1,3 +1,10 @@ +import type { + ParseFramesWithReportsResult, + ParseResult, +} from "frames.js/frame-parsers"; +import type { ComposerActionFormResponse } from "frames.js/types"; +import type { PartialFrame } from "./ui/types"; + export async function tryCallAsync( promiseFn: () => Promise ): Promise { @@ -25,3 +32,77 @@ export function tryCall(fn: () => TReturn): TReturn | Error { return new TypeError("Unexpected error, check the console for details"); } } + +export function isParseFramesWithReportsResult( + value: unknown +): value is ParseFramesWithReportsResult { + return ( + typeof value === "object" && + value !== null && + "openframes" in value && + "farcaster" in value + ); +} + +export function isParseResult(value: unknown): value is ParseResult { + return ( + typeof value === "object" && + value !== null && + "status" in value && + !("openframes" in value) && + !("farcaster" in value) + ); +} + +export type ParseResultWithPartialFrame = Omit< + Exclude, + "frame" +> & { + frame: PartialFrame; +}; + +// rename +export function isPartialFrame( + value: ParseResult +): value is ParseResultWithPartialFrame { + return ( + value.status === "failure" && + !!value.frame.image && + !!value.frame.buttons && + value.frame.buttons.length > 0 + ); +} + +export function isComposerFormActionResponse( + response: unknown +): response is ComposerActionFormResponse { + return ( + typeof response === "object" && + response !== null && + "type" in response && + response.type === "form" + ); +} + +/** + * Merges all search params in order from left to right into the URL. + * + * @param url - The URL to merge the search params into. Either fully qualified or path only. + */ +export function mergeSearchParamsToUrl( + url: string, + ...searchParams: URLSearchParams[] +): string { + const temporaryDomain = "temporary-for-parsing-purposes.tld"; + const parsedProxyUrl = new URL(url, `http://${temporaryDomain}`); + + searchParams.forEach((params) => { + params.forEach((value, key) => { + parsedProxyUrl.searchParams.set(key, value); + }); + }); + + return parsedProxyUrl.hostname === temporaryDomain + ? `${parsedProxyUrl.pathname}${parsedProxyUrl.search}` + : parsedProxyUrl.toString(); +} diff --git a/packages/render/src/hooks/use-fresh-ref.ts b/packages/render/src/hooks/use-fresh-ref.ts new file mode 100644 index 000000000..e1e2a5686 --- /dev/null +++ b/packages/render/src/hooks/use-fresh-ref.ts @@ -0,0 +1,7 @@ +import { useRef } from "react"; + +export function useFreshRef(value: T): React.MutableRefObject { + const ref = useRef(value); + ref.current = value; + return ref; +} diff --git a/packages/render/src/identity/anonymous/use-anonymous-identity.tsx b/packages/render/src/identity/anonymous/use-anonymous-identity.tsx index 6c9f41afb..c1f1eb2eb 100644 --- a/packages/render/src/identity/anonymous/use-anonymous-identity.tsx +++ b/packages/render/src/identity/anonymous/use-anonymous-identity.tsx @@ -1,5 +1,5 @@ import type { AnonymousOpenFramesRequest } from "frames.js/anonymous"; -import { useCallback, useMemo } from "react"; +import { useMemo } from "react"; import type { SignerStateActionContext, SignerStateInstance, @@ -22,53 +22,58 @@ export type AnonymousSignerInstance = SignerStateInstance< const onSignerlessFramePress = (): Promise => Promise.resolve(); const logout = (): Promise => Promise.resolve(); const signer: AnonymousSigner = {}; +const signFrameAction: SignFrameActionFunction< + SignerStateActionContext, + AnonymousOpenFramesRequest +> = (actionContext) => { + const searchParams = new URLSearchParams({ + postType: + actionContext.type === "tx-post" + ? "post" + : actionContext.frameButton.action, + postUrl: actionContext.target ?? "", + specification: "openframes", + }); -export function useAnonymousIdentity(): AnonymousSignerInstance { - const signFrameAction: SignFrameActionFunction< - SignerStateActionContext, - AnonymousOpenFramesRequest - > = useCallback((actionContext) => { - const searchParams = new URLSearchParams({ - postType: - actionContext.type === "tx-post" - ? "post" - : actionContext.frameButton.action, - postUrl: actionContext.target ?? "", - specification: "openframes", - }); - - return Promise.resolve({ - body: { - untrustedData: { - buttonIndex: actionContext.buttonIndex, - state: actionContext.state, - url: actionContext.url, - inputText: actionContext.inputText, - address: - actionContext.type === "tx-data" || actionContext.type === "tx-post" - ? actionContext.address - : undefined, - transactionId: - actionContext.type === "tx-post" - ? actionContext.transactionId - : undefined, - unixTimestamp: Date.now(), - }, - clientProtocol: "anonymous@1.0", + return Promise.resolve({ + body: { + untrustedData: { + buttonIndex: actionContext.buttonIndex, + state: actionContext.state, + url: actionContext.url, + inputText: actionContext.inputText, + address: + actionContext.type === "tx-data" || actionContext.type === "tx-post" + ? actionContext.address + : undefined, + transactionId: + actionContext.type === "tx-post" + ? actionContext.transactionId + : undefined, + unixTimestamp: Date.now(), }, - searchParams, - }); - }, []); + clientProtocol: "anonymous@1.0", + }, + searchParams, + }); +}; - return useMemo( - () => ({ +export function useAnonymousIdentity(): AnonymousSignerInstance { + return useMemo(() => { + return { + specification: "openframes", hasSigner: true, onSignerlessFramePress, signer, isLoadingSigner: false, logout, signFrameAction, - }), - [signFrameAction] - ); + withContext(frameContext) { + return { + signerState: this, + frameContext, + }; + }, + }; + }, []); } diff --git a/packages/render/src/identity/farcaster/use-farcaster-context.tsx b/packages/render/src/identity/farcaster/use-farcaster-context.tsx index e7485c8ba..f6abbb69c 100644 --- a/packages/render/src/identity/farcaster/use-farcaster-context.tsx +++ b/packages/render/src/identity/farcaster/use-farcaster-context.tsx @@ -1,7 +1,14 @@ -import type { FarcasterFrameContext } from "../../farcaster"; +import type { FarcasterFrameContext } from "../../farcaster/types"; import { createFrameContextHook } from "../create-frame-context-hook"; export const useFarcasterFrameContext = createFrameContextHook({ storageKey: "farcasterFrameContext", }); + +export const fallbackFrameContext: FarcasterFrameContext = { + castId: { + fid: 1, + hash: "0x0000000000000000000000000000000000000000" as const, + }, +}; diff --git a/packages/render/src/identity/farcaster/use-farcaster-identity.tsx b/packages/render/src/identity/farcaster/use-farcaster-identity.tsx index a24b853f1..db3d73b82 100644 --- a/packages/render/src/identity/farcaster/use-farcaster-identity.tsx +++ b/packages/render/src/identity/farcaster/use-farcaster-identity.tsx @@ -8,11 +8,12 @@ import { } from "react"; import { convertKeypairToHex, createKeypairEDDSA } from "../crypto"; import type { FarcasterSignerState } from "../../farcaster"; -import { signFrameAction } from "../../farcaster"; +import { signComposerAction, signFrameAction } from "../../farcaster"; import type { Storage } from "../types"; import { useVisibilityDetection } from "../../hooks/use-visibility-detection"; import { WebStorage } from "../storage"; import { useStorage } from "../../hooks/use-storage"; +import { useFreshRef } from "../../hooks/use-fresh-ref"; import { IdentityPoller } from "./identity-poller"; import type { FarcasterCreateSignerResult, @@ -187,16 +188,12 @@ export function useFarcasterIdentity({ return value; }, }); - const onImpersonateRef = useRef(onImpersonate); - onImpersonateRef.current = onImpersonate; - const onLogInRef = useRef(onLogIn); - onLogInRef.current = onLogIn; - const onLogInStartRef = useRef(onLogInStart); - onLogInStartRef.current = onLogInStart; - const onLogOutRef = useRef(onLogOut); - onLogOutRef.current = onLogOut; - const generateUserIdRef = useRef(generateUserId); - generateUserIdRef.current = generateUserId; + const onImpersonateRef = useFreshRef(onImpersonate); + const onLogInRef = useFreshRef(onLogIn); + const onLogInStartRef = useFreshRef(onLogInStart); + const onLogOutRef = useFreshRef(onLogOut); + const generateUserIdRef = useFreshRef(generateUserId); + const onMissingIdentityRef = useFreshRef(onMissingIdentity); const createFarcasterSigner = useCallback(async (): Promise => { @@ -300,7 +297,7 @@ export function useFarcasterIdentity({ console.error("@frames.js/render: API Call failed", error); throw error; } - }, [setState, signerUrl]); + }, [generateUserIdRef, onLogInStartRef, setState, signerUrl]); const impersonateUser = useCallback( async (fid: number) => { @@ -329,14 +326,14 @@ export function useFarcasterIdentity({ setIsLoading(false); } }, - [setState] + [generateUserIdRef, onImpersonateRef, setState] ); const onSignerlessFramePress = useCallback((): Promise => { - onMissingIdentity(); + onMissingIdentityRef.current(); return Promise.resolve(); - }, [onMissingIdentity]); + }, [onMissingIdentityRef]); const createSigner = useCallback(async () => { setIsLoading(true); @@ -354,7 +351,7 @@ export function useFarcasterIdentity({ return identityReducer(currentState, { type: "LOGOUT" }); }); - }, [setState]); + }, [onLogOutRef, setState]); const farcasterUser = state.status === "init" ? null : state; @@ -418,21 +415,30 @@ export function useFarcasterIdentity({ visibilityDetector, setState, enableIdentityPolling, + onLogInRef, ]); return useMemo( () => ({ + specification: "farcaster", signer: farcasterUser, hasSigner: farcasterUser?.status === "approved" || farcasterUser?.status === "impersonating", signFrameAction, + signComposerAction, isLoadingSigner: isLoading, impersonateUser, onSignerlessFramePress, createSigner, logout, identityPoller, + withContext(frameContext) { + return { + signerState: this, + frameContext, + }; + }, }), [ farcasterUser, diff --git a/packages/render/src/identity/farcaster/use-farcaster-multi-identity.tsx b/packages/render/src/identity/farcaster/use-farcaster-multi-identity.tsx index 4056150e7..b5142bbf2 100644 --- a/packages/render/src/identity/farcaster/use-farcaster-multi-identity.tsx +++ b/packages/render/src/identity/farcaster/use-farcaster-multi-identity.tsx @@ -8,11 +8,12 @@ import { } from "react"; import { convertKeypairToHex, createKeypairEDDSA } from "../crypto"; import type { FarcasterSignerState } from "../../farcaster"; -import { signFrameAction } from "../../farcaster"; +import { signComposerAction, signFrameAction } from "../../farcaster"; import type { Storage } from "../types"; import { useVisibilityDetection } from "../../hooks/use-visibility-detection"; import { WebStorage } from "../storage"; import { useStorage } from "../../hooks/use-storage"; +import { useFreshRef } from "../../hooks/use-fresh-ref"; import { IdentityPoller } from "./identity-poller"; import type { FarcasterCreateSignerResult, @@ -259,20 +260,14 @@ export function useFarcasterMultiIdentity({ identities: [], }, }); - const onImpersonateRef = useRef(onImpersonate); - onImpersonateRef.current = onImpersonate; - const onLogInRef = useRef(onLogIn); - onLogInRef.current = onLogIn; - const onLogInStartRef = useRef(onLogInStart); - onLogInStartRef.current = onLogInStart; - const onLogOutRef = useRef(onLogOut); - onLogOutRef.current = onLogOut; - const onIdentityRemoveRef = useRef(onIdentityRemove); - onIdentityRemoveRef.current = onIdentityRemove; - const onIdentitySelectRef = useRef(onIdentitySelect); - onIdentitySelectRef.current = onIdentitySelect; - const generateUserIdRef = useRef(generateUserId); - generateUserIdRef.current = generateUserId; + const onImpersonateRef = useFreshRef(onImpersonate); + const onLogInRef = useFreshRef(onLogIn); + const onLogInStartRef = useFreshRef(onLogInStart); + const onLogOutRef = useFreshRef(onLogOut); + const onIdentityRemoveRef = useFreshRef(onIdentityRemove); + const onIdentitySelectRef = useFreshRef(onIdentitySelect); + const generateUserIdRef = useFreshRef(generateUserId); + const onMissingIdentityRef = useFreshRef(onMissingIdentity); const createFarcasterSigner = useCallback(async (): Promise => { @@ -388,7 +383,7 @@ export function useFarcasterMultiIdentity({ console.error("@frames.js/render: API Call failed", error); throw error; } - }, [setState, signerUrl]); + }, [generateUserIdRef, onLogInStartRef, setState, signerUrl]); const impersonateUser = useCallback( async (fid: number) => { @@ -417,14 +412,14 @@ export function useFarcasterMultiIdentity({ setIsLoading(false); } }, - [setState] + [generateUserIdRef, onImpersonateRef, setState] ); const onSignerlessFramePress = useCallback((): Promise => { - onMissingIdentity(); + onMissingIdentityRef.current(); return Promise.resolve(); - }, [onMissingIdentity]); + }, [onMissingIdentityRef]); const createSigner = useCallback(async () => { setIsLoading(true); @@ -442,7 +437,7 @@ export function useFarcasterMultiIdentity({ return identityReducer(currentState, { type: "LOGOUT" }); }); - }, [setState]); + }, [onLogOutRef, setState]); const removeIdentity = useCallback(async () => { await setState((currentState) => { @@ -452,7 +447,7 @@ export function useFarcasterMultiIdentity({ return identityReducer(currentState, { type: "REMOVE" }); }); - }, [setState]); + }, [onIdentityRemoveRef, setState]); const farcasterUser = state.activeIdentity; @@ -528,11 +523,13 @@ export function useFarcasterMultiIdentity({ return useMemo( () => ({ + specification: "farcaster", signer: farcasterUser, hasSigner: farcasterUser?.status === "approved" || farcasterUser?.status === "impersonating", signFrameAction, + signComposerAction, isLoadingSigner: isLoading, impersonateUser, onSignerlessFramePress, @@ -542,6 +539,12 @@ export function useFarcasterMultiIdentity({ identities: state.identities, selectIdentity, identityPoller, + withContext(frameContext) { + return { + signerState: this, + frameContext, + }; + }, }), [ farcasterUser, diff --git a/packages/render/src/identity/lens/use-lens-identity.tsx b/packages/render/src/identity/lens/use-lens-identity.tsx index 8fc1cc365..468d703dc 100644 --- a/packages/render/src/identity/lens/use-lens-identity.tsx +++ b/packages/render/src/identity/lens/use-lens-identity.tsx @@ -321,6 +321,7 @@ export function useLensIdentity({ return useMemo( () => ({ + specification: "openframes", signer: lensSigner, hasSigner: !!lensSigner?.accessToken, signFrameAction, @@ -331,6 +332,12 @@ export function useLensIdentity({ closeProfileSelector, availableProfiles, handleSelectProfile, + withContext(frameContext) { + return { + signerState: this, + frameContext, + }; + }, }), [ availableProfiles, diff --git a/packages/render/src/identity/xmtp/use-xmtp-identity.tsx b/packages/render/src/identity/xmtp/use-xmtp-identity.tsx index 71b1471d9..7f0950648 100644 --- a/packages/render/src/identity/xmtp/use-xmtp-identity.tsx +++ b/packages/render/src/identity/xmtp/use-xmtp-identity.tsx @@ -210,12 +210,19 @@ export function useXmtpIdentity({ return useMemo( () => ({ + specification: "openframes", signer: xmtpSigner, hasSigner: !!xmtpSigner?.keys, signFrameAction, isLoadingSigner: isLoading, onSignerlessFramePress, logout, + withContext(frameContext) { + return { + signerState: this, + frameContext, + }; + }, }), [isLoading, logout, onSignerlessFramePress, signFrameAction, xmtpSigner] ); diff --git a/packages/render/src/mini-app-messages.ts b/packages/render/src/mini-app-messages.ts new file mode 100644 index 000000000..d2a55ea0b --- /dev/null +++ b/packages/render/src/mini-app-messages.ts @@ -0,0 +1,139 @@ +import type { Abi, TypedData, TypedDataDomain } from "viem"; +import { z } from "zod"; + +export type TransactionResponse = + | TransactionResponseSuccess + | TransactionResponseFailure; + +export type TransactionResponseSuccess = { + jsonrpc: "2.0"; + id: string | number | null; + result: TransactionSuccessBody; +}; + +export type TransactionSuccessBody = + | EthSendTransactionSuccessBody + | EthSignTypedDataV4SuccessBody; + +export type EthSendTransactionSuccessBody = { + address: `0x${string}`; + transactionHash: `0x${string}`; +}; + +export type EthSignTypedDataV4SuccessBody = { + address: `0x${string}`; + signature: `0x${string}`; +}; + +export type TransactionResponseFailure = { + jsonrpc: "2.0"; + id: string | number | null; + error: { + code: number; + message: string; + }; +}; + +export type CreateCastResponse = { + jsonrpc: "2.0"; + id: string | number | null; + result: { + success: true; + }; +}; + +export type MiniAppResponse = TransactionResponse | CreateCastResponse; + +const createCastRequestSchemaLegacy = z.object({ + type: z.literal("createCast"), + data: z.object({ + cast: z.object({ + parent: z.string().optional(), + text: z.string(), + embeds: z.array(z.string().min(1).url()).min(1), + }), + }), +}); + +export type CreateCastLegacyMessage = z.infer< + typeof createCastRequestSchemaLegacy +>; + +const createCastRequestSchema = z.object({ + jsonrpc: z.literal("2.0"), + id: z.union([z.string(), z.number(), z.null()]), + method: z.literal("fc_createCast"), + params: z.object({ + cast: z.object({ + parent: z.string().optional(), + text: z.string(), + embeds: z.array(z.string().min(1).url()).min(1), + }), + }), +}); + +export type CreateCastMessage = z.infer; + +const ethSendTransactionActionSchema = z.object({ + chainId: z.string(), + method: z.literal("eth_sendTransaction"), + attribution: z.boolean().optional(), + params: z.object({ + abi: z.custom(), + to: z.custom<`0x${string}`>( + (val): val is `0x${string}` => + typeof val === "string" && val.startsWith("0x") + ), + value: z.string().optional(), + data: z + .custom<`0x${string}`>((val): val is `0x${string}` => typeof val === "string" && val.startsWith("0x")) + .optional(), + }), +}); + +export type EthSendTransactionAction = z.infer< + typeof ethSendTransactionActionSchema +>; + +const ethSignTypedDataV4ActionSchema = z.object({ + chainId: z.string(), + method: z.literal("eth_signTypedData_v4"), + params: z.object({ + domain: z.custom(), + types: z.custom((value) => { + const result = z.record(z.unknown()).safeParse(value); + + return result.success; + }), + primaryType: z.string(), + message: z.record(z.unknown()), + }), +}); + +export type EthSignTypedDataV4Action = z.infer< + typeof ethSignTypedDataV4ActionSchema +>; + +const walletActionRequestSchema = z.object({ + jsonrpc: z.literal("2.0"), + id: z.string(), + method: z.literal("fc_requestWalletAction"), + params: z.object({ + action: z.union([ + ethSendTransactionActionSchema, + ethSignTypedDataV4ActionSchema, + ]), + }), +}); + +export type RequestWalletActionMessage = z.infer< + typeof walletActionRequestSchema +>; + +export const miniAppMessageSchema = z.union([ + createCastRequestSchemaLegacy, + walletActionRequestSchema, + createCastRequestSchema, +]); + +export type MiniAppMessage = z.infer; diff --git a/packages/render/src/next/GET.tsx b/packages/render/src/next/GET.tsx index ca1a600d3..12c685251 100644 --- a/packages/render/src/next/GET.tsx +++ b/packages/render/src/next/GET.tsx @@ -1,34 +1,65 @@ -import { getFrame } from "frames.js"; import type { NextRequest } from "next/server"; +import { parseFramesWithReports } from "frames.js/parseFramesWithReports"; +import type { ParseFramesWithReportsResult } from "frames.js/frame-parsers"; +import { getFrame, type GetFrameResult } from "frames.js"; import { isSpecificationValid } from "./validators"; +export type GETResponse = + | ParseFramesWithReportsResult + | GetFrameResult + | { message: string }; + /** Proxies fetching a frame through a backend to avoid CORS issues and preserve user IP privacy */ export async function GET(request: Request | NextRequest): Promise { - const searchParams = - "nextUrl" in request - ? request.nextUrl.searchParams - : new URL(request.url).searchParams; - const url = searchParams.get("url"); - const specification = searchParams.get("specification") ?? "farcaster"; - - if (!url) { - return Response.json({ message: "Invalid URL" }, { status: 400 }); - } + try { + const searchParams = + "nextUrl" in request + ? request.nextUrl.searchParams + : new URL(request.url).searchParams; + const url = searchParams.get("url"); + const specification = searchParams.get("specification") ?? "farcaster"; + const multiSpecificationEnabled = + searchParams.get("multispecification") === "true"; - if (!isSpecificationValid(specification)) { - return Response.json({ message: "Invalid specification" }, { status: 400 }); - } + if (!url) { + return Response.json({ message: "Invalid URL" } satisfies GETResponse, { + status: 400, + }); + } - try { const urlRes = await fetch(url); - const htmlString = await urlRes.text(); + const html = await urlRes.text(); + + if (multiSpecificationEnabled) { + const result: ParseFramesWithReportsResult = parseFramesWithReports({ + html, + fallbackPostUrl: url, + }); + + return Response.json(result satisfies GETResponse); + } + + if (!isSpecificationValid(specification)) { + return Response.json( + { message: "Invalid specification" } satisfies GETResponse, + { + status: 400, + } + ); + } - const result = getFrame({ htmlString, url, specification }); + const result = getFrame({ + htmlString: html, + url, + specification, + }); - return Response.json(result); + return Response.json(result satisfies GETResponse); } catch (err) { // eslint-disable-next-line no-console -- provide feedback to the developer console.error(err); - return Response.json({ message: err }, { status: 500 }); + return Response.json({ message: String(err) } satisfies GETResponse, { + status: 500, + }); } } diff --git a/packages/render/src/next/POST.tsx b/packages/render/src/next/POST.tsx index ac9f63ea7..e9f216bb0 100644 --- a/packages/render/src/next/POST.tsx +++ b/packages/render/src/next/POST.tsx @@ -1,28 +1,92 @@ -import type { FrameActionPayload } from "frames.js"; -import { getFrame } from "frames.js"; +import { + getFrame, + type FrameActionPayload, + type GetFrameResult, +} from "frames.js"; +import { type ParseFramesWithReportsResult } from "frames.js/frame-parsers"; +import { parseFramesWithReports } from "frames.js/parseFramesWithReports"; +import type { JsonObject, JsonValue } from "frames.js/types"; import type { NextRequest } from "next/server"; +import { z } from "zod"; +import { tryCallAsync } from "../helpers"; import { isSpecificationValid } from "./validators"; +const castActionMessageParser = z.object({ + type: z.literal("message"), + message: z.string().min(1), +}); + +const castActionFrameParser = z.object({ + type: z.literal("frame"), + frameUrl: z.string().min(1).url(), +}); + +const composerActionFormParser = z.object({ + type: z.literal("form"), + url: z.string().min(1).url(), + title: z.string().min(1), +}); + +const jsonResponseParser = z.preprocess( + (data) => { + if (typeof data === "object" && data !== null && !("type" in data)) { + return { + type: "message", + ...data, + }; + } + + return data; + }, + z.discriminatedUnion("type", [ + castActionFrameParser, + castActionMessageParser, + composerActionFormParser, + ]) +); + +const errorResponseParser = z.object({ + message: z.string().min(1), +}); + +export type POSTResponseError = { message: string }; + +export type POSTResponseRedirect = { location: string }; + +export type POSTTransactionResponse = JsonObject; + +export type POSTResponse = + | GetFrameResult + | ParseFramesWithReportsResult + | POSTResponseError + | POSTResponseRedirect + | JsonObject; + /** Proxies frame actions to avoid CORS issues and preserve user IP privacy */ export async function POST(req: Request | NextRequest): Promise { - const searchParams = - "nextUrl" in req ? req.nextUrl.searchParams : new URL(req.url).searchParams; - const body = (await req.json()) as FrameActionPayload; - const isPostRedirect = searchParams.get("postType") === "post_redirect"; - const isTransactionRequest = searchParams.get("postType") === "tx"; - const postUrl = searchParams.get("postUrl"); - const specification = searchParams.get("specification") ?? "farcaster"; - - if (!postUrl) { - return Response.error(); - } + try { + const searchParams = + "nextUrl" in req + ? req.nextUrl.searchParams + : new URL(req.url).searchParams; + const body = (await req.json()) as FrameActionPayload; + const isPostRedirect = searchParams.get("postType") === "post_redirect"; + const isTransactionRequest = searchParams.get("postType") === "tx"; + const postUrl = searchParams.get("postUrl"); + const multiSpecificationEnabled = + searchParams.get("multispecification") === "true"; + const specification = searchParams.get("specification") ?? "farcaster"; - if (!isSpecificationValid(specification)) { - return Response.json({ message: "Invalid specification" }, { status: 400 }); - } + if (!postUrl) { + return Response.json( + { message: "postUrl parameter not found" } satisfies POSTResponseError, + { + status: 400, + } + ); + } - try { - const r = await fetch(postUrl, { + const response = await fetch(postUrl, { method: "POST", headers: { Accept: "application/json", @@ -32,53 +96,182 @@ export async function POST(req: Request | NextRequest): Promise { body: JSON.stringify(body), }); - if (r.status >= 500) { - return r; + if (response.status >= 500) { + const jsonError = await tryCallAsync( + () => response.clone().json() as Promise + ); + + if (jsonError instanceof Error) { + return Response.json( + { message: jsonError.message } satisfies POSTResponseError, + { status: response.status } + ); + } + + const result = errorResponseParser.safeParse(jsonError); + + if (result.success) { + return Response.json( + { message: result.data.message } satisfies POSTResponseError, + { status: response.status } + ); + } + + // eslint-disable-next-line no-console -- provide feedback to the user + console.error(jsonError); + + return Response.json( + { + message: `Frame server returned an unexpected error.`, + } satisfies POSTResponseError, + { status: 500 } + ); } - if (r.status === 302) { + if (response.status === 302) { + const location = response.headers.get("location"); + + if (!location) { + return Response.json( + { + message: + "Frame server returned a redirect without a location header", + } satisfies POSTResponseError, + { status: 500 } + ); + } + return Response.json( { - location: r.headers.get("location"), - }, + location, + } satisfies POSTResponseRedirect, { status: 302 } ); + } else if (isPostRedirect) { + return Response.json( + { + message: "Frame server did not return a 302 redirect", + } satisfies POSTResponseError, + { status: 500 } + ); } - if (r.status >= 400 && r.status < 500) { - const json = (await r.json()) as { message?: string }; + if (response.status >= 400 && response.status < 500) { + const jsonError = await tryCallAsync( + () => response.clone().json() as Promise + ); - if ("message" in json) { - return Response.json({ message: json.message }, { status: r.status }); - } else { - return r; + if (jsonError instanceof Error) { + return Response.json( + { message: jsonError.message } satisfies POSTResponseError, + { status: response.status } + ); } + + const result = errorResponseParser.safeParse(jsonError); + + if (result.success) { + return Response.json( + { message: result.data.message } satisfies POSTResponseError, + { status: response.status } + ); + } + + // eslint-disable-next-line no-console -- provide feedback to the user + console.error(jsonError); + + return Response.json( + { + message: `Frame server returned an unexpected error.`, + } satisfies POSTResponseError, + { status: response.status } + ); } - if (isPostRedirect && r.status !== 302) { + if (response.status !== 200) { return Response.json( - { message: "Invalid response for redirect button" }, + { + message: `Frame server returned a non-200 status code: ${response.status}`, + } satisfies POSTResponseError, { status: 500 } ); } if (isTransactionRequest) { - const transaction = (await r.json()) as JSON; - return Response.json(transaction); + const transaction = await tryCallAsync( + () => response.clone().json() as Promise + ); + + if (transaction instanceof Error) { + return Response.json( + { message: transaction.message } satisfies POSTResponseError, + { status: 500 } + ); + } + + return Response.json(transaction satisfies JsonObject); + } + + // Content type is JSON, could be an action + if ( + response.headers + .get("content-type") + ?.toLowerCase() + .includes("application/json") + ) { + const parseResult = await z + .promise(jsonResponseParser) + .safeParseAsync(response.clone().json()); + + if (!parseResult.success) { + throw new Error("Invalid frame response"); + } + + const headers = new Headers(response.headers); + // Proxied requests could have content-encoding set, which breaks the response + headers.delete("content-encoding"); + + return new Response(response.body, { + headers, + status: response.status, + statusText: response.statusText, + }); + } + + const html = await response.text(); + + if (multiSpecificationEnabled) { + const result = parseFramesWithReports({ + html, + fallbackPostUrl: body.untrustedData.url, + fromRequestMethod: "POST", + }); + + return Response.json(result satisfies ParseFramesWithReportsResult); } - const htmlString = await r.text(); + if (!isSpecificationValid(specification)) { + return Response.json( + { + message: "Invalid specification", + } satisfies POSTResponseError, + { status: 400 } + ); + } const result = getFrame({ - htmlString, + htmlString: html, url: body.untrustedData.url, + fromRequestMethod: "POST", specification, }); - return Response.json(result); + return Response.json(result satisfies POSTResponse); } catch (err) { // eslint-disable-next-line no-console -- provide feedback to the user console.error(err); - return Response.error(); + return Response.json({ message: String(err) } satisfies POSTResponseError, { + status: 500, + }); } } diff --git a/packages/render/src/types.ts b/packages/render/src/types.ts index 7ad0310b6..6a524d703 100644 --- a/packages/render/src/types.ts +++ b/packages/render/src/types.ts @@ -17,7 +17,6 @@ import type { ComposerActionFormResponse, ComposerActionState, } from "frames.js/types"; -import type { FarcasterFrameContext } from "./farcaster/frames"; import type { FrameStackAPI } from "./use-frame-stack"; export type OnTransactionArgs = { @@ -78,7 +77,7 @@ export type OnConnectWalletFunc = () => void; export type SignFrameActionFunc< TSignerStorageType = Record, TFrameActionBodyType extends FrameActionBodyPayload = FrameActionBodyPayload, - TFrameContextType extends FrameContext = FarcasterFrameContext + TFrameContextType extends FrameContext = FrameContext, > = ( actionContext: SignerStateActionContext ) => Promise>; @@ -88,7 +87,7 @@ export type UseFetchFrameSignFrameActionFunction< unknown, Record >, - TFrameActionBodyType extends FrameActionBodyPayload = FrameActionBodyPayload + TFrameActionBodyType extends FrameActionBodyPayload = FrameActionBodyPayload, > = (arg: { actionContext: TSignerStateActionContext; /** @@ -100,7 +99,7 @@ export type UseFetchFrameSignFrameActionFunction< export type UseFetchFrameOptions< TSignerStorageType = Record, TFrameActionBodyType extends FrameActionBodyPayload = FrameActionBodyPayload, - TFrameContextType extends FrameContext = FarcasterFrameContext + TFrameContextType extends FrameContext = FrameContext, > = { stackAPI: FrameStackAPI; stackDispatch: React.Dispatch; @@ -216,7 +215,7 @@ export type UseFetchFrameOptions< export type UseFrameOptions< TSignerStorageType = Record, TFrameActionBodyType extends FrameActionBodyPayload = FrameActionBodyPayload, - TFrameContextType extends FrameContext = FarcasterFrameContext + TFrameContextType extends FrameContext = FrameContext, > = { /** skip frame signing, for frames that don't verify signatures */ dangerousSkipSigning?: boolean; @@ -290,7 +289,7 @@ export type UseFrameOptions< type SignerStateActionSharedContext< TSignerStorageType = Record, - TFrameContextType extends FrameContext = FarcasterFrameContext + TFrameContextType extends FrameContext = FrameContext, > = { target?: string; frameButton: FrameButton; @@ -307,14 +306,14 @@ type SignerStateActionSharedContext< export type SignerStateDefaultActionContext< TSignerStorageType = Record, - TFrameContextType extends FrameContext = FarcasterFrameContext + TFrameContextType extends FrameContext = FrameContext, > = { type?: "default"; } & SignerStateActionSharedContext; export type SignerStateTransactionDataActionContext< TSignerStorageType = Record, - TFrameContextType extends FrameContext = FarcasterFrameContext + TFrameContextType extends FrameContext = FrameContext, > = { type: "tx-data"; /** Wallet address used to create the transaction, available only for "tx" button actions */ @@ -323,7 +322,7 @@ export type SignerStateTransactionDataActionContext< export type SignerStateTransactionPostActionContext< TSignerStorageType = Record, - TFrameContextType extends FrameContext = FarcasterFrameContext + TFrameContextType extends FrameContext = FrameContext, > = { type: "tx-post"; /** Wallet address used to create the transaction, available only for "tx" button actions */ @@ -333,7 +332,7 @@ export type SignerStateTransactionPostActionContext< export type SignerStateActionContext< TSignerStorageType = Record, - TFrameContextType extends FrameContext = FarcasterFrameContext + TFrameContextType extends FrameContext = FrameContext, > = | SignerStateDefaultActionContext | SignerStateTransactionDataActionContext< @@ -346,7 +345,7 @@ export type SignerStateActionContext< >; export type SignedFrameAction< - TFrameActionBodyType extends FrameActionBodyPayload = FrameActionBodyPayload + TFrameActionBodyType extends FrameActionBodyPayload = FrameActionBodyPayload, > = { body: TFrameActionBodyType; searchParams: URLSearchParams; @@ -357,7 +356,7 @@ export type SignFrameActionFunction< unknown, Record > = SignerStateActionContext, - TFrameActionBodyType extends FrameActionBodyPayload = FrameActionBodyPayload + TFrameActionBodyType extends FrameActionBodyPayload = FrameActionBodyPayload, > = ( actionContext: TSignerStateActionContext ) => Promise>; @@ -365,8 +364,12 @@ export type SignFrameActionFunction< export interface SignerStateInstance< TSignerStorageType = Record, TFrameActionBodyType extends FrameActionBodyPayload = FrameActionBodyPayload, - TFrameContextType extends FrameContext = FarcasterFrameContext + TFrameContextType extends FrameContext = FrameContext, > { + /** + * For which specification is this signer required. + */ + readonly specification: SupportedParsingSpecification; signer: TSignerStorageType | null; /** * True only if signer is approved or impersonating @@ -381,6 +384,14 @@ export interface SignerStateInstance< /** A function called when a frame button is clicked without a signer */ onSignerlessFramePress: () => Promise; logout: () => Promise; + withContext: (context: TFrameContextType) => { + signerState: SignerStateInstance< + TSignerStorageType, + TFrameActionBodyType, + TFrameContextType + >; + frameContext: TFrameContextType; + }; } export type FrameGETRequest = { @@ -392,7 +403,7 @@ export type FramePOSTRequest< TSignerStateActionContext extends SignerStateActionContext< unknown, Record - > = SignerStateActionContext + > = SignerStateActionContext, > = | { method: "POST"; @@ -418,10 +429,11 @@ export type FrameRequest< TSignerStateActionContext extends SignerStateActionContext< unknown, Record - > = SignerStateActionContext + > = SignerStateActionContext, > = FrameGETRequest | FramePOSTRequest; export type FrameStackBase = { + id: number; timestamp: Date; /** speed in seconds */ speed: number; @@ -435,6 +447,7 @@ export type FrameStackBase = { }; export type FrameStackPostPending = { + id: number; method: "POST"; timestamp: Date; status: "pending"; @@ -447,6 +460,7 @@ export type FrameStackPostPending = { }; export type FrameStackGetPending = { + id: number; method: "GET"; timestamp: Date; status: "pending"; @@ -525,13 +539,14 @@ export type FrameReducerActions = action: "RESET_INITIAL_FRAME"; resultOrFrame: ParseResult | Frame; homeframeUrl: string | null | undefined; + specification: SupportedParsingSpecification; }; -type ButtonPressFunction< +export type ButtonPressFunction< TSignerStateActionContext extends SignerStateActionContext< unknown, Record - > + >, > = ( frame: Frame, frameButton: FrameButton, @@ -574,7 +589,7 @@ export type CastActionRequest< TSignerStateActionContext extends SignerStateActionContext< unknown, Record - > = SignerStateActionContext + > = SignerStateActionContext, > = Omit< FramePOSTRequest, "method" | "frameButton" | "sourceFrame" | "signerStateActionContext" @@ -593,7 +608,7 @@ export type ComposerActionRequest< TSignerStateActionContext extends SignerStateActionContext< unknown, Record - > = SignerStateActionContext + > = SignerStateActionContext, > = Omit< FramePOSTRequest, "method" | "frameButton" | "sourceFrame" | "signerStateActionContext" @@ -613,7 +628,7 @@ export type FetchFrameFunction< TSignerStateActionContext extends SignerStateActionContext< unknown, Record - > = SignerStateActionContext + > = SignerStateActionContext, > = ( request: | FrameRequest @@ -629,7 +644,7 @@ export type FetchFrameFunction< export type FrameState< TSignerStorageType = Record, - TFrameContextType extends FrameContext = FarcasterFrameContext + TFrameContextType extends FrameContext = FrameContext, > = { fetchFrame: FetchFrameFunction< SignerStateActionContext diff --git a/packages/render/src/ui/frame.base.tsx b/packages/render/src/ui/frame.base.tsx index 609cdc730..91e1fd0ec 100644 --- a/packages/render/src/ui/frame.base.tsx +++ b/packages/render/src/ui/frame.base.tsx @@ -6,7 +6,8 @@ import { useRef, useState, } from "react"; -import type { FrameStackDone, FrameState } from "../types"; +import type { FrameState } from "../types"; +import type { UseFrameReturnValue } from "../unstable-types"; import type { FrameMessage, FrameUIComponents as BaseFrameUIComponents, @@ -27,7 +28,9 @@ export type FrameUITheme> = Partial>; export type BaseFrameUIProps> = { - frameState: FrameState; + frameState: + | FrameState + | UseFrameReturnValue; /** * Renders also frames that contain only image and at least one button * @@ -123,9 +126,12 @@ export function BaseFrameUI>({ } let frameUiState: FrameUIState; - const previousFrame = ( - frameState.framesStack[frameState.framesStack.length - 1] as FrameStackDone - )?.frameResult?.frame; + const previousFrameStackItem = + frameState.framesStack[frameState.framesStack.length - 1]; + const previousFrame = + previousFrameStackItem?.status === "done" + ? previousFrameStackItem.frameResult.frame + : null; switch (currentFrameStackItem.status) { case "requestError": { @@ -137,7 +143,7 @@ export function BaseFrameUI>({ status: "complete", frame: currentFrameStackItem.request.sourceFrame, isImageLoading, - id: currentFrameStackItem.timestamp.getTime(), + id: currentFrameStackItem.id, frameState, }; } else { @@ -169,7 +175,7 @@ export function BaseFrameUI>({ status: "complete", frame: currentFrameStackItem.request.sourceFrame, isImageLoading, - id: currentFrameStackItem.timestamp.getTime(), + id: currentFrameStackItem.id, frameState, }; @@ -178,7 +184,7 @@ export function BaseFrameUI>({ if (!currentFrameStackItem.request.sourceFrame) { frameUiState = { status: "loading", - id: currentFrameStackItem.timestamp.getTime(), + id: currentFrameStackItem.id, frameState, }; } else { @@ -186,7 +192,7 @@ export function BaseFrameUI>({ status: "complete", frame: currentFrameStackItem.request.sourceFrame, isImageLoading, - id: currentFrameStackItem.timestamp.getTime(), + id: currentFrameStackItem.id, frameState, }; } @@ -202,7 +208,7 @@ export function BaseFrameUI>({ ? currentFrameStackItem.frameResult.framesDebugInfo?.image : undefined, isImageLoading, - id: currentFrameStackItem.timestamp.getTime(), + id: currentFrameStackItem.id, frameState, }; } else if ( @@ -216,7 +222,7 @@ export function BaseFrameUI>({ ? currentFrameStackItem.frameResult.framesDebugInfo?.image : undefined, isImageLoading, - id: currentFrameStackItem.timestamp.getTime(), + id: currentFrameStackItem.id, frameState, }; } else { @@ -231,7 +237,7 @@ export function BaseFrameUI>({ case "pending": { frameUiState = { status: "loading", - id: currentFrameStackItem.timestamp.getTime(), + id: currentFrameStackItem.id, frameState, }; break; diff --git a/packages/render/src/ui/types.ts b/packages/render/src/ui/types.ts index 059149367..b4ed6562b 100644 --- a/packages/render/src/ui/types.ts +++ b/packages/render/src/ui/types.ts @@ -1,12 +1,13 @@ import type { Frame, FrameButton } from "frames.js"; import type { createElement, ReactElement } from "react"; import type { FrameState } from "../types"; +import type { UseFrameReturnValue } from "../unstable-types"; /** * Allows to override styling props on all component of the Frame UI */ export type FrameUIComponentStylingProps< - TStylingProps extends Record + TStylingProps extends Record, > = { Button: TStylingProps; ButtonsContainer: TStylingProps; @@ -30,12 +31,16 @@ export type PartialFrame = Omit, RequiredFrameProperties> & Required>; export type FrameUIState = - | { status: "loading"; id: number; frameState: FrameState } + | { + status: "loading"; + id: number; + frameState: FrameState | UseFrameReturnValue; + } | { id: number; status: "partial"; frame: PartialFrame; - frameState: FrameState; + frameState: FrameState | UseFrameReturnValue; debugImage?: string; isImageLoading: boolean; } @@ -43,7 +48,7 @@ export type FrameUIState = id: number; status: "complete"; frame: Frame; - frameState: FrameState; + frameState: FrameState | UseFrameReturnValue; debugImage?: string; isImageLoading: boolean; }; diff --git a/packages/render/src/ui/utils.ts b/packages/render/src/ui/utils.ts index c3a6db5c3..4abf00680 100644 --- a/packages/render/src/ui/utils.ts +++ b/packages/render/src/ui/utils.ts @@ -5,6 +5,11 @@ import type { FrameStackMessage, FrameStackRequestError, } from "../types"; +import type { + FramesStackItem as UnstableFramesStackItem, + FrameStackMessage as UnstableFrameStackMessage, + FrameStackRequestError as UnstableFrameStackRequestError, +} from "../unstable-types"; import type { PartialFrame } from "./types"; type FrameResultFailure = Exclude; @@ -16,7 +21,7 @@ type FrameStackItemWithPartialFrame = Omit & { }; export function isPartialFrameStackItem( - stackItem: FramesStackItem + stackItem: FramesStackItem | UnstableFramesStackItem ): stackItem is FrameStackItemWithPartialFrame { return ( stackItem.status === "done" && @@ -28,7 +33,11 @@ export function isPartialFrameStackItem( } export function getErrorMessageFromFramesStackItem( - item: FrameStackMessage | FrameStackRequestError + item: + | FrameStackMessage + | FrameStackRequestError + | UnstableFrameStackMessage + | UnstableFrameStackRequestError ): string { if (item.status === "message") { return item.message; diff --git a/packages/render/src/unstable-types.ts b/packages/render/src/unstable-types.ts new file mode 100644 index 000000000..8433fed8f --- /dev/null +++ b/packages/render/src/unstable-types.ts @@ -0,0 +1,676 @@ +import type { + FrameButtonLink, + FrameButtonTx, + SupportedParsingSpecification, + TransactionTargetResponse, + TransactionTargetResponseSendTransaction, + TransactionTargetResponseSignTypedDataV4, +} from "frames.js"; +import type { + ParseFramesWithReportsResult, + ParseResultWithFrameworkDetails, +} from "frames.js/frame-parsers"; +import type { Dispatch } from "react"; +import type { + ComposerActionState, + ErrorMessageResponse, +} from "frames.js/types"; +import type { + ButtonPressFunction, + FrameContext, + FrameGETRequest, + FramePOSTRequest, + FrameRequest, + OnMintArgs, + OnSignatureFunc, + OnTransactionFunc, + SignedFrameAction, + SignerStateActionContext, + SignerStateInstance, +} from "./types"; + +export type ResolvedSigner = { + /** + * Signer that will be used to sign all actions that require signers. + */ + signerState: SignerStateInstance; + /** + * The context of this frame, used for generating Frame Action payloads + */ + frameContext?: FrameContext; +}; + +export type ResolveSignerFunctionArg = { + parseResult: ParseFramesWithReportsResult; +}; + +export type ResolveSignerFunction = ( + arg: ResolveSignerFunctionArg +) => ResolvedSigner; + +export type ResolveAddressFunction = () => Promise<`0x${string}` | null>; + +export type UseFrameOptions< + TExtraDataPending = unknown, + TExtraDataDone = unknown, + TExtraDataDoneRedirect = unknown, + TExtraDataRequestError = unknown, + TExtraDataMesssage = unknown, +> = { + /** + * The frame state to be used for the frame. Allows to store extra data on stack items. + */ + frameStateHook?: ( + options: Pick< + UseFrameStateOptions< + TExtraDataPending, + TExtraDataDone, + TExtraDataDoneRedirect, + TExtraDataRequestError, + TExtraDataMesssage + >, + "initialFrameUrl" | "initialParseResult" | "resolveSpecification" + > + ) => UseFrameStateReturn< + TExtraDataPending, + TExtraDataDone, + TExtraDataDoneRedirect, + TExtraDataRequestError, + TExtraDataMesssage + >; + /** the route used to POST frame actions. The post_url will be added as a the `url` query parameter */ + frameActionProxy: string; + /** the route used to GET the initial frame via proxy */ + frameGetProxy: string; + /** + * Called on initial frame load. + * + * The function is called again if: + * 1. initial frame changes + * 2. homeframeUrl changes + * 3. reset() method on FrameState is called + */ + resolveSigner: ResolveSignerFunction; + /** + * The url of the homeframe, if null / undefined won't load a frame nor render it. + * + * If the value changes the frame state is reset. + */ + homeframeUrl: string | null | undefined; + /** + * The initial frame. if not specified will fetch it from the homeframeUrl prop. + * + * Value should be memoized otherwise it will reset the frame state. + */ + frame?: ParseFramesWithReportsResult | null; + /** + * Called before onTransaction/onSignature is invoked to obtain an address to use. + * + * If the function returns null onTransaction/onSignature will not be called. + * + * Sent to the frame on transaction requests. + */ + resolveAddress: ResolveAddressFunction; + /** a function to handle mint buttons */ + onMint?: (t: OnMintArgs) => void; + /** a function to handle transaction buttons that returned transaction data from the target, returns the transaction hash or null */ + onTransaction?: OnTransactionFunc; + /** Transaction data suffix */ + transactionDataSuffix?: `0x${string}`; + /** A function to handle transaction buttons that returned signature data from the target, returns signature hash or null */ + onSignature?: OnSignatureFunc; + /** + * Extra data appended to the frame action payload + */ + extraButtonRequestPayload?: Record; + /** + * This function can be used to customize how error is reported to the user. + */ + onError?: (error: Error) => void; + /** + * This function can be used to customize how the link button click is handled. + */ + onLinkButtonClick?: (button: FrameButtonLink) => void; +} & Partial< + Pick< + UseFetchFrameOptions, + | "fetchFn" + | "onRedirect" + | "onTransactionDataError" + | "onTransactionDataStart" + | "onTransactionDataSuccess" + | "onTransactionError" + | "onTransactionStart" + | "onTransactionSuccess" + | "onTransactionProcessingError" + | "onTransactionProcessingStart" + | "onTransactionProcessingSuccess" + > +>; + +export type FrameStackBase = { + id: number; + url: string; +}; + +export type FrameStackPostPending = Omit< + FrameStackBase, + "responseStatus" | "responseBody" +> & { + method: "POST"; + status: "pending"; + request: FramePOSTRequest; + extra: TExtra; +}; + +export type FrameStackGetPending = Omit< + FrameStackBase, + "responseStatus" | "responseBody" +> & { + method: "GET"; + status: "pending"; + request: FrameGETRequest; + extra: TExtra; +}; + +export type FrameStackPending = + | FrameStackGetPending + | FrameStackPostPending; + +export type FrameStackDone = FrameStackBase & { + request: FrameRequest; + frameResult: ParseResultWithFrameworkDetails; + status: "done"; + extra: TExtra; +}; + +export type FrameStackDoneRedirect = FrameStackBase & { + request: FramePOSTRequest; + location: string; + status: "doneRedirect"; + extra: TExtra; +}; + +export type FrameStackRequestError = FrameStackBase & { + request: FrameRequest; + status: "requestError"; + requestError: Error; + extra: TExtra; +}; + +export type FrameStackMessage = FrameStackBase & { + request: FramePOSTRequest; + status: "message"; + message: string; + type: "info" | "error"; + extra: TExtra; +}; + +export type FramesStackItem< + TExtraPending = unknown, + TExtraDone = unknown, + TExtraDoneRedirect = unknown, + TExtraRequestError = unknown, + TExtraMesssage = unknown, +> = + | FrameStackPending + | FrameStackDone + | FrameStackDoneRedirect + | FrameStackRequestError + | FrameStackMessage; + +export type UseFrameReturnValue< + TExtraDataPending = unknown, + TExtraDataDone = unknown, + TExtraDataDoneRedirect = unknown, + TExtraDataRequestError = unknown, + TExtraDataMesssage = unknown, +> = { + /** + * The signer state is set once it is resolved (on initial frame render) + */ + readonly signerState: SignerStateInstance | undefined; + /** + * The specification is set once it is resolved (on initial frame render) + */ + readonly specification: SupportedParsingSpecification | undefined; + fetchFrame: FetchFrameFunction; + clearFrameStack: () => void; + dispatchFrameStack: Dispatch< + FrameReducerActions< + TExtraDataPending, + TExtraDataDone, + TExtraDataDoneRedirect, + TExtraDataRequestError, + TExtraDataMesssage + > + >; + /** The frame at the top of the stack (at index 0) */ + readonly currentFrameStackItem: FramesStackItem | undefined; + /** A stack of frames with additional context, with the most recent frame at index 0 */ + readonly framesStack: FramesStack< + TExtraDataPending, + TExtraDataDone, + TExtraDataDoneRedirect, + TExtraDataRequestError, + TExtraDataMesssage + >; + readonly inputText: string; + setInputText: (s: string) => void; + onButtonPress: ButtonPressFunction>; + readonly homeframeUrl: string | null | undefined; + /** + * Resets the frame state to initial frame and resolves specification and signer again + */ + reset: () => void; +}; + +export type FramesStack< + TExtraPending = unknown, + TExtraDone = unknown, + TExtraDoneRedirect = unknown, + TExtraRequestError = unknown, + TExtraMesssage = unknown, +> = FramesStackItem< + TExtraPending, + TExtraDone, + TExtraDoneRedirect, + TExtraRequestError, + TExtraMesssage +>[]; + +export type FrameReducerActions< + TExtraPending = unknown, + TExtraDone = unknown, + TExtraDoneRedirect = unknown, + TExtraRequestError = unknown, + TExtraMessage = unknown, +> = + | { + action: "LOAD"; + item: FrameStackPending; + } + | { + action: "REQUEST_ERROR"; + pendingItem: FrameStackPending; + item: FrameStackRequestError; + } + | { + action: "DONE_REDIRECT"; + pendingItem: FrameStackPending; + item: FrameStackDoneRedirect; + } + | { + action: "DONE_WITH_ERROR_MESSAGE"; + pendingItem: FrameStackPending; + item: Exclude, { type: "info" }>; + } + | { + action: "DONE"; + pendingItem: FrameStackPending; + parseResult: ParseFramesWithReportsResult; + extra: TExtraDone; + } + | { action: "CLEAR" } + | { + action: "RESET"; + } + | { + action: "RESET_INITIAL_FRAME"; + parseResult: ParseFramesWithReportsResult; + homeframeUrl: string; + extra: TExtraDone; + }; + +export type UseFetchFrameOptions< + TExtraPending = unknown, + TExtraDone = unknown, + TExtraDoneRedirect = unknown, + TExtraRequestError = unknown, + TExtraMesssage = unknown, +> = { + frameState: FrameState; + frameStateAPI: FrameStateAPI< + TExtraPending, + TExtraDone, + TExtraDoneRedirect, + TExtraRequestError, + TExtraMesssage + >; + /** + * URL or path to the frame proxy handling GET requests. + */ + frameGetProxy: string; + /** + * URL or path to the frame proxy handling POST requests. + */ + frameActionProxy: string; + /** + * Extra payload to be sent with the POST request. + */ + extraButtonRequestPayload?: Record; + /** + * Called after transaction data has been returned from the server and user needs to approve the transaction. + */ + onTransaction: OnTransactionFunc; + /** Transaction data suffix */ + transactionDataSuffix?: `0x${string}`; + onSignature: OnSignatureFunc; + /** + * This function can be used to customize how error is reported to the user. + * + * Should be memoized + */ + onError?: (error: Error) => void; + /** + * Custom fetch compatible function used to make requests. + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API + */ + fetchFn: typeof fetch; + /** + * This function is called when the frame returns a redirect in response to post_redirect button click. + */ + onRedirect: (location: URL) => void; + /** + * Called when user presses the tx button just before the action is signed and sent to the server + * to obtain the transaction data. + */ + onTransactionDataStart?: (event: { button: FrameButtonTx }) => void; + /** + * Called when transaction data has been successfully returned from the server. + */ + onTransactionDataSuccess?: (event: { + button: FrameButtonTx; + data: TransactionTargetResponse; + }) => void; + /** + * Called when anything failed between onTransactionDataStart and obtaining the transaction data. + */ + onTransactionDataError?: (error: Error) => void; + /** + * Called before onTransaction() is called + * Called after onTransactionDataSuccess() is called + */ + onTransactionStart?: (event: { + button: FrameButtonTx; + data: TransactionTargetResponseSendTransaction; + }) => void; + /** + * Called when onTransaction() returns a transaction id + */ + onTransactionSuccess?: (event: { button: FrameButtonTx }) => void; + /** + * Called when onTransaction() fails to return a transaction id + */ + onTransactionError?: (error: Error) => void; + /** + * Called before onSignature() is called + * Called after onTransactionDataSuccess() is called + */ + onSignatureStart?: (event: { + button: FrameButtonTx; + data: TransactionTargetResponseSignTypedDataV4; + }) => void; + /** + * Called when onSignature() returns a transaction id + */ + onSignatureSuccess?: (event: { button: FrameButtonTx }) => void; + /** + * Called when onSignature() fails to return a transaction id + */ + onSignatureError?: (error: Error) => void; + /** + * Called after either onSignatureSuccess() or onTransactionSuccess() is called just before the transaction is sent to the server. + */ + onTransactionProcessingStart?: (event: { + button: FrameButtonTx; + transactionId: `0x${string}`; + }) => void; + /** + * Called after the transaction has been successfully sent to the server and returned a success response. + */ + onTransactionProcessingSuccess?: (event: { + button: FrameButtonTx; + transactionId: `0x${string}`; + }) => void; + /** + * Called when the transaction has been sent to the server but the server returned an error. + */ + onTransactionProcessingError?: (error: Error) => void; +}; + +export type FetchFrameFunction = ( + request: FrameRequest, + /** + * If true, the frame stack will be cleared before the new frame is loaded + * + * @defaultValue false + */ + shouldClear?: boolean +) => Promise; + +type MarkAsDoneArg = { + pendingItem: + | FrameStackGetPending + | FrameStackPostPending; + endTime: Date; + response: Response; + parseResult: ParseFramesWithReportsResult; + responseBody: unknown; +}; + +type MarkAsDonwWithRedirectArg = { + pendingItem: FrameStackPostPending; + endTime: Date; + location: string; + response: Response; + responseBody: unknown; +}; + +type MarkAsDoneWithErrorMessageArg = { + pendingItem: FrameStackPostPending; + endTime: Date; + response: Response; + responseData: ErrorMessageResponse; +}; + +type MarkAsFailedArg = { + pendingItem: + | FrameStackGetPending + | FrameStackPostPending; + endTime: Date; + requestError: Error; + response: Response | null; + responseBody: unknown; + responseStatus: number; +}; + +type MarkAsFailedWithRequestErrorArg = { + endTime: Date; + pendingItem: FrameStackPostPending; + error: Error; + response: Response; + responseBody: unknown; +}; + +type CreateGetPendingItemArg = { + request: FrameGETRequest; +}; + +type CreatePOSTPendingItemArg = { + action: SignedFrameAction; + request: FramePOSTRequest; + /** + * Optional, allows to override the start time + * + * @defaultValue new Date() + */ + startTime?: Date; +}; + +export type UseFrameStateOptions< + TExtraPending = unknown, + TExtraDone = unknown, + TExtraDoneRedirect = unknown, + TExtraRequestError = unknown, + TExtraMesssage = unknown, +> = { + initialParseResult?: ParseFramesWithReportsResult | null; + initialFrameUrl?: string | null; + initialPendingExtra?: TExtraPending; + resolveSpecification: ResolveSignerFunction; + resolveGETPendingExtra?: (arg: CreateGetPendingItemArg) => TExtraPending; + resolvePOSTPendingExtra?: (arg: CreatePOSTPendingItemArg) => TExtraPending; + resolveDoneExtra?: (arg: MarkAsDoneArg) => TExtraDone; + resolveDoneRedirectExtra?: ( + arg: MarkAsDonwWithRedirectArg + ) => TExtraDoneRedirect; + resolveDoneWithErrorMessageExtra?: ( + arg: MarkAsDoneWithErrorMessageArg + ) => TExtraMesssage; + resolveFailedExtra?: ( + arg: MarkAsFailedArg + ) => TExtraRequestError; + resolveFailedWithRequestErrorExtra?: ( + arg: MarkAsFailedWithRequestErrorArg + ) => TExtraRequestError; +}; + +export type FrameStateAPI< + TExtraPending = unknown, + TExtraDone = unknown, + TExtraDoneRedirect = unknown, + TExtraRequestError = unknown, + TExtraMesssage = unknown, +> = { + dispatch: React.Dispatch< + FrameReducerActions< + TExtraPending, + TExtraDone, + TExtraDoneRedirect, + TExtraRequestError, + TExtraMesssage + > + >; + clear: () => void; + createGetPendingItem: ( + arg: CreateGetPendingItemArg + ) => FrameStackGetPending; + createPostPendingItem: < + TSignerStateActionContext extends SignerStateActionContext, + >(arg: { + action: SignedFrameAction; + request: FramePOSTRequest; + /** + * Optional, allows to override the start time + * + * @defaultValue new Date() + */ + startTime?: Date; + }) => FrameStackPostPending; + markAsDone: (arg: MarkAsDoneArg) => void; + markAsDoneWithRedirect: ( + arg: MarkAsDonwWithRedirectArg + ) => void; + markAsDoneWithErrorMessage: ( + arg: MarkAsDoneWithErrorMessageArg + ) => void; + markAsFailed: (arg: MarkAsFailedArg) => void; + markAsFailedWithRequestError: ( + arg: MarkAsFailedWithRequestErrorArg + ) => void; + /** + * If arg is omitted it will reset the frame stack to initial frame and resolves the specification again. + * Otherwise it will set the frame state to provided values and resolve the specification. + */ + reset: (arg?: { + homeframeUrl: string; + parseResult: ParseFramesWithReportsResult; + }) => void; +}; + +export type UseFrameStateReturn< + TExtraPending = unknown, + TExtraDone = unknown, + TExtraDoneRedirect = unknown, + TExtraRequestError = unknown, + TExtraMesssage = unknown, +> = [ + FrameState< + TExtraPending, + TExtraDone, + TExtraDoneRedirect, + TExtraRequestError, + TExtraMesssage + >, + FrameStateAPI< + TExtraPending, + TExtraDone, + TExtraDoneRedirect, + TExtraRequestError, + TExtraMesssage + >, +]; + +export type FrameState< + TExtraPending = unknown, + TExtraDone = unknown, + TExtraDoneRedirect = unknown, + TExtraRequestError = unknown, + TExtraMesssage = unknown, +> = + | { + type: "initialized"; + stack: FramesStack< + TExtraPending, + TExtraDone, + TExtraDoneRedirect, + TExtraRequestError, + TExtraMesssage + >; + signerState: SignerStateInstance; + frameContext: FrameContext; + specification: SupportedParsingSpecification; + homeframeUrl: string; + parseResult: ParseFramesWithReportsResult; + } + | { + type: "not-initialized"; + stack: FramesStack< + TExtraPending, + TExtraDone, + TExtraDoneRedirect, + TExtraRequestError, + TExtraMesssage + >; + }; + +export type SignerStateComposerActionContext = { + fid: number; + url: string; + state: ComposerActionState; +}; + +export type SignerComposerActionResult = { + untrustedData: { + fid: number; + url: string; + messageHash: `0x${string}`; + timestamp: number; + network: number; + buttonIndex: 1; + state: string; + }; + trustedData: { + messageBytes: string; + }; +}; + +/** + * Used to sign composer action + */ +export type SignComposerActionFunc = ( + signerPrivateKey: string, + actionContext: SignerStateComposerActionContext +) => Promise; diff --git a/packages/render/src/unstable-use-fetch-frame.ts b/packages/render/src/unstable-use-fetch-frame.ts new file mode 100644 index 000000000..020cb9853 --- /dev/null +++ b/packages/render/src/unstable-use-fetch-frame.ts @@ -0,0 +1,876 @@ +/* eslint-disable no-console -- provide feedback to console */ +import type { TransactionTargetResponse } from "frames.js"; +import type { ErrorMessageResponse } from "frames.js/types"; +import { hexToBytes } from "viem"; +import type { FarcasterFrameContext } from "./farcaster"; +import { + SignatureHandlerDidNotReturnTransactionIdError, + TransactionDataErrorResponseError, + TransactionDataTargetMalformedError, + TransactionHandlerDidNotReturnTransactionIdError, +} from "./errors"; +import { + isParseFramesWithReportsResult, + tryCall, + tryCallAsync, +} from "./helpers"; +import type { + FetchFrameFunction, + FrameStackPending, + FrameStackPostPending, + UseFetchFrameOptions, +} from "./unstable-types"; +import type { + FrameGETRequest, + FramePOSTRequest, + SignedFrameAction, + SignerStateActionContext, + SignerStateInstance, +} from "./types"; + +function isErrorMessageResponse( + response: unknown +): response is ErrorMessageResponse { + return ( + typeof response === "object" && + response !== null && + "message" in response && + typeof response.message === "string" + ); +} + +function defaultErrorHandler(error: Error): void { + console.error(error); +} + +export function useFetchFrame< + TExtraPending = unknown, + TExtraDone = unknown, + TExtraDoneRedirect = unknown, + TExtraRequestError = unknown, + TExtraMesssage = unknown, +>({ + frameStateAPI, + frameState, + frameActionProxy, + frameGetProxy, + extraButtonRequestPayload, + onTransaction, + transactionDataSuffix, + onSignature, + onError = defaultErrorHandler, + fetchFn, + onRedirect, + onTransactionDataError, + onTransactionDataStart, + onTransactionDataSuccess, + onTransactionError, + onTransactionStart, + onTransactionSuccess, + onSignatureError, + onSignatureStart, + onSignatureSuccess, + onTransactionProcessingError, + onTransactionProcessingStart, + onTransactionProcessingSuccess, +}: UseFetchFrameOptions< + TExtraPending, + TExtraDone, + TExtraDoneRedirect, + TExtraRequestError, + TExtraMesssage +>): FetchFrameFunction { + async function handleFailedResponse({ + response, + endTime, + frameStackPendingItem, + onError: onErrorInternal, + }: { + endTime: Date; + response: Response; + frameStackPendingItem: FrameStackPending; + onError?: (error: Error) => void; + }): Promise { + if (response.ok) { + throw new TypeError( + "handleFailedResponse called with a successful response" + ); + } + + const responseBody = await getResponseBody(response); + + if (response.status >= 400 && response.status < 500) { + // handle error message only for actions (POST method) + if ( + frameStackPendingItem.method === "POST" && + isErrorMessageResponse(responseBody) + ) { + frameStateAPI.markAsDoneWithErrorMessage({ + pendingItem: frameStackPendingItem, + endTime, + response, + responseData: responseBody, + }); + const error = new Error(responseBody.message); + tryCall(() => { + onError(error); + }); + tryCall(() => onErrorInternal?.(error)); + + return; + } + } + + const requestError = new Error( + `The server returned an error but it does not contain message property. Status code: ${response.status}` + ); + + frameStateAPI.markAsFailed({ + endTime, + pendingItem: frameStackPendingItem, + requestError, + responseStatus: response.status, + response, + responseBody, + }); + tryCall(() => { + onError(requestError); + }); + tryCall(() => onErrorInternal?.(requestError)); + } + + async function fetchGETRequest( + request: FrameGETRequest, + shouldClear?: boolean + ): Promise { + if (shouldClear) { + // this clears initial frame since that is loading from SSR since we aren't able to finish it. + // not an ideal solution + frameStateAPI.clear(); + } + + const frameStackPendingItem = frameStateAPI.createGetPendingItem({ + request, + }); + + const response = await fetchProxied({ + proxyUrl: frameGetProxy, + fetchFn, + url: request.url, + }); + + const endTime = new Date(); + + if (response instanceof Response) { + if (!response.ok) { + await handleFailedResponse({ + response, + endTime, + frameStackPendingItem, + }); + + return; + } + + const parseResult = await tryCallAsync( + () => response.clone().json() as Promise + ); + + if (parseResult instanceof Error) { + frameStateAPI.markAsFailed({ + pendingItem: frameStackPendingItem, + endTime, + requestError: parseResult, + response, + responseBody: "none", + responseStatus: 500, + }); + + tryCall(() => { + onError(parseResult); + }); + + return; + } + + if (!isParseFramesWithReportsResult(parseResult)) { + const error = new Error("The server returned an unexpected response."); + + frameStateAPI.markAsFailed({ + pendingItem: frameStackPendingItem, + endTime, + requestError: error, + response, + responseBody: "none", + responseStatus: 500, + }); + + tryCall(() => { + onError(error); + }); + + return; + } + + frameStateAPI.markAsDone({ + pendingItem: frameStackPendingItem, + endTime, + parseResult, + responseBody: await response.clone().text(), + response: response.clone(), + }); + + return; + } + + frameStateAPI.markAsFailed({ + pendingItem: frameStackPendingItem, + endTime, + requestError: response, + response: null, + responseBody: "none", + responseStatus: 500, + }); + tryCall(() => { + onError(response); + }); + } + + async function fetchPOSTRequest( + request: FramePOSTRequest, + options?: { + preflightRequest?: { + pendingFrameStackItem: FrameStackPostPending; + startTime: Date; + }; + shouldClear?: boolean; + onError?: (error: Error) => void; + onSuccess?: () => void; + } + ): Promise { + let pendingItem: FrameStackPostPending; + + if (frameState.type === "not-initialized") { + throw new Error( + "POST Request cannot be made before the frame is initialized" + ); + } + + if (options?.shouldClear) { + frameStateAPI.clear(); + } + + // get rid of address from request.signerStateActionContext.frameContext and pass that to sign frame action + const signedDataOrError = await signAndGetFrameActionBodyPayload({ + request, + signerState: frameState.signerState, + }); + + if (signedDataOrError instanceof Error) { + if (options?.preflightRequest) { + // mark preflight request as failed + frameStateAPI.markAsFailed({ + pendingItem: options.preflightRequest.pendingFrameStackItem, + endTime: new Date(), + requestError: signedDataOrError, + response: null, // there is no response because didn't even got to request + responseBody: "none", + responseStatus: 500, + }); + } + tryCall(() => { + onError(signedDataOrError); + }); + tryCall(() => options?.onError?.(signedDataOrError)); + + return; + } + + // if there is no preflight happening (for example in case of transactions we first fetch transaction data and then post it to frame) + // in that case options are passed so we can manipulate the pending item + if (!options?.preflightRequest) { + pendingItem = frameStateAPI.createPostPendingItem({ + action: signedDataOrError, + request, + }); + } else { + pendingItem = options.preflightRequest.pendingFrameStackItem; + } + + const response = await fetchProxied({ + proxyUrl: frameActionProxy, + fetchFn, + frameAction: signedDataOrError, + extraRequestPayload: extraButtonRequestPayload, + }); + + const endTime = new Date(); + + async function handleRedirect({ + response: res, + currentPendingItem, + onError: onErrorInternal, + onSuccess: onSuccessInternal, + }: { + response: Response; + currentPendingItem: FrameStackPostPending; + onError?: (error: Error) => void; + onSuccess?: () => void; + }): Promise { + // check that location is proper fully formatted url + try { + let location = res.headers.get("location"); + + if (!location) { + const responseData = (await res.clone().json()) as + | Record + | string + | null + | number; + + if ( + responseData && + typeof responseData === "object" && + "location" in responseData && + typeof responseData.location === "string" + ) { + location = responseData.location; + } + } + + if (!location) { + throw new Error( + `Response data does not contain 'location' key and no 'location' header is found.` + ); + } + + // check the URL is valid + const locationUrl = new URL(location); + + // Reject non-http(s) URLs + if ( + locationUrl.protocol !== "http:" && + locationUrl.protocol !== "https:" + ) { + throw new Error( + `Redirect location ${location} is not a valid HTTP or HTTPS URL.` + ); + } + + tryCall(() => { + onRedirect(locationUrl); + }); + tryCall(() => onSuccessInternal?.()); + + frameStateAPI.markAsDoneWithRedirect({ + pendingItem: currentPendingItem, + endTime, + location, + response: res.clone(), + responseBody: await res.clone().text(), + }); + } catch (e) { + const error = + e instanceof Error + ? e + : new Error( + "Response body must be a json with 'location' property or response 'Location' header must contain fully qualified URL." + ); + + frameStateAPI.markAsFailedWithRequestError({ + pendingItem: currentPendingItem, + error, + response: res, + endTime, + responseBody: await res.clone().text(), + }); + tryCall(() => onErrorInternal?.(error)); + tryCall(() => { + onError(error); + }); + } + } + + if (response instanceof Response) { + // handle valid redirect + if (response.status === 302) { + await handleRedirect({ + response, + currentPendingItem: pendingItem, + onError: options?.onError, + onSuccess: options?.onSuccess, + }); + + return; + } + + if (!response.ok) { + await handleFailedResponse({ + response, + endTime, + frameStackPendingItem: pendingItem, + onError: options?.onError, + }); + + return; + } + + const responseData = await tryCall( + () => response.clone().json() as Promise + ); + + if (responseData instanceof Error) { + frameStateAPI.markAsFailed({ + endTime, + pendingItem, + requestError: responseData, + response, + responseBody: "none", + responseStatus: 500, + }); + tryCall(() => { + onError(responseData); + }); + tryCall(() => options?.onError?.(responseData)); + + return; + } + + if (!isParseFramesWithReportsResult(responseData)) { + const error = new Error("The server returned an unexpected response."); + + frameStateAPI.markAsFailed({ + endTime, + pendingItem, + requestError: error, + response, + responseBody: responseData, + responseStatus: 500, + }); + tryCall(() => { + onError(error); + }); + tryCall(() => options?.onError?.(error)); + + return; + } + + frameStateAPI.markAsDone({ + endTime, + parseResult: responseData, + pendingItem, + response, + responseBody: await response.clone().text(), + }); + + tryCall(() => options?.onSuccess?.()); + + return; + } + + frameStateAPI.markAsFailed({ + endTime, + pendingItem, + requestError: response, + response: new Response(response.message, { + status: 500, + headers: { "Content-Type": "text/plain" }, + }), + responseBody: "none", + responseStatus: 500, + }); + tryCall(() => { + onError(response); + }); + tryCall(() => options?.onError?.(response)); + } + + async function fetchTransactionRequest( + request: FramePOSTRequest, + shouldClear?: boolean + ): Promise { + if ("source" in request) { + throw new Error( + "Invalid request, transaction should be invoked only from a Frame. It was probably invoked from cast or composer action." + ); + } + + if (frameState.type === "not-initialized") { + throw new Error( + "Transaction Request cannot be made before the frame is initialized" + ); + } + + const button = request.frameButton; + const sourceFrame = request.sourceFrame; + + if (button.action !== "tx") { + throw new Error("Invalid frame button action, tx expected"); + } + + if (request.signerStateActionContext.type !== "tx-data") { + throw new Error( + "Invalid signer state action context type, tx-data expected" + ); + } + + if (shouldClear) { + frameStateAPI.clear(); + } + + tryCall(() => onTransactionDataStart?.({ button })); + + const signedTransactionDataActionOrError = await tryCallAsync(() => + frameState.signerState.signFrameAction(request.signerStateActionContext) + ); + + if (signedTransactionDataActionOrError instanceof Error) { + tryCall(() => { + onError(signedTransactionDataActionOrError); + }); + tryCall(() => + onTransactionDataError?.(signedTransactionDataActionOrError) + ); + return; + } + + const transactionDataStartTime = new Date(); + const transactionDataResponse = await fetchProxied({ + proxyUrl: frameActionProxy, + frameAction: signedTransactionDataActionOrError, + fetchFn, + extraRequestPayload: extraButtonRequestPayload, + }); + const transactionDataEndTime = new Date(); + + if (transactionDataResponse instanceof Error) { + const pendingItem = frameStateAPI.createPostPendingItem({ + action: signedTransactionDataActionOrError, + request, + startTime: transactionDataStartTime, + }); + + frameStateAPI.markAsFailed({ + endTime: transactionDataEndTime, + pendingItem, + requestError: transactionDataResponse, + response: null, + responseBody: "none", + responseStatus: 500, + }); + tryCall(() => onTransactionDataError?.(transactionDataResponse)); + tryCall(() => { + onError(transactionDataResponse); + }); + + return; + } + + if (!transactionDataResponse.ok) { + // show as error + const pendingItem = frameStateAPI.createPostPendingItem({ + action: signedTransactionDataActionOrError, + request, + startTime: transactionDataStartTime, + }); + + await handleFailedResponse({ + response: transactionDataResponse, + endTime: transactionDataEndTime, + frameStackPendingItem: pendingItem, + }); + + tryCall(() => + onTransactionDataError?.( + new TransactionDataErrorResponseError(transactionDataResponse.clone()) + ) + ); + + return; + } + + function isTransactionTargetResponse( + response: unknown + ): response is TransactionTargetResponse { + return ( + typeof response === "object" && + response !== null && + "method" in response + ); + } + + // try to parse and catch the error, this is too optimistic + + const transactionData = await tryCallAsync(() => + transactionDataResponse.clone().json() + ); + + if (!isTransactionTargetResponse(transactionData)) { + const pendingItem = frameStateAPI.createPostPendingItem({ + action: signedTransactionDataActionOrError, + request, + startTime: transactionDataStartTime, + }); + + const error = new TransactionDataTargetMalformedError( + transactionDataResponse.clone() + ); + + frameStateAPI.markAsFailed({ + endTime: transactionDataEndTime, + pendingItem, + requestError: error, + response: transactionDataResponse, + responseBody: transactionData, + responseStatus: 500, + }); + tryCall(() => onTransactionDataError?.(error)); + tryCall(() => { + onError(error); + }); + + return; + } + + tryCall(() => + onTransactionDataSuccess?.({ button, data: transactionData }) + ); + + let transactionIdOrError: `0x${string}` | Error; + + // get transaction id or signature id from transaction data + if (transactionData.method === "eth_sendTransaction") { + // Add transaction data suffix + if ( + transactionData.params.data && + transactionData.attribution !== false && + transactionDataSuffix && + // Has a function signature + hexToBytes(transactionData.params.data).length > 4 + ) { + transactionData.params.data = (transactionData.params.data + + transactionDataSuffix.slice(2)) as `0x${string}`; + } + + tryCall(() => onTransactionStart?.({ button, data: transactionData })); + + transactionIdOrError = await tryCallAsync(() => + onTransaction({ + frame: sourceFrame, + frameButton: request.frameButton, + transactionData, + }).then((transactionId) => { + if (!transactionId) { + return new TransactionHandlerDidNotReturnTransactionIdError(); + } + + return transactionId; + }) + ); + + if (!(transactionIdOrError instanceof Error)) { + tryCall(() => onTransactionSuccess?.({ button })); + } else { + tryCall(() => onTransactionError?.(transactionIdOrError as Error)); + } + } else { + tryCall(() => onSignatureStart?.({ button, data: transactionData })); + + transactionIdOrError = await tryCallAsync(() => + onSignature({ + frame: sourceFrame, + frameButton: request.frameButton, + signatureData: transactionData, + }).then((signatureHash) => { + if (!signatureHash) { + return new SignatureHandlerDidNotReturnTransactionIdError(); + } + + return signatureHash; + }) + ); + + if (!(transactionIdOrError instanceof Error)) { + tryCall(() => onSignatureSuccess?.({ button })); + } else { + tryCall(() => onSignatureError?.(transactionIdOrError as Error)); + } + } + + if (transactionIdOrError instanceof Error) { + const pendingItem = frameStateAPI.createPostPendingItem({ + action: signedTransactionDataActionOrError, + request, + }); + + frameStateAPI.markAsFailed({ + pendingItem, + endTime: new Date(), + requestError: transactionIdOrError, + response: null, + responseBody: "none", + responseStatus: 500, + }); + tryCall(() => { + onError(transactionIdOrError); + }); + + return; + } + + tryCall(() => + onTransactionProcessingStart?.({ + button, + transactionId: transactionIdOrError, + }) + ); + + const startTime = new Date(); + const pendingItem = frameStateAPI.createPostPendingItem({ + action: signedTransactionDataActionOrError, + request, + }); + + await fetchPOSTRequest( + { + ...request, + signerStateActionContext: { + ...request.signerStateActionContext, + type: "tx-post", + // include transactionId in payload + transactionId: transactionIdOrError, + // override target so the the request is sent to proper endpoint + target: button.post_url || sourceFrame.postUrl || button.target, + }, + }, + { + // we are continuing with the same pending item + preflightRequest: { + pendingFrameStackItem: pendingItem, + startTime, + }, + onError(error) { + tryCall(() => onTransactionProcessingError?.(error)); + }, + onSuccess() { + tryCall(() => + onTransactionProcessingSuccess?.({ + button, + transactionId: transactionIdOrError, + }) + ); + }, + } + ); + } + + return (request, shouldClear = false) => { + if (request.method === "GET") { + return fetchGETRequest(request, shouldClear); + } + + if (request.frameButton.action === "tx") { + return fetchTransactionRequest(request, shouldClear); + } + + return fetchPOSTRequest(request, { + shouldClear, + }); + }; +} + +function proxyUrlAndSearchParamsToUrl( + proxyUrl: string, + ...searchParams: URLSearchParams[] +): string { + const temporaryDomain = "temporary-for-parsing-purposes.tld"; + const parsedProxyUrl = new URL(proxyUrl, `http://${temporaryDomain}`); + + searchParams.forEach((params) => { + params.forEach((value, key) => { + parsedProxyUrl.searchParams.set(key, value); + }); + }); + + return parsedProxyUrl.hostname === temporaryDomain + ? `${parsedProxyUrl.pathname}${parsedProxyUrl.search}` + : parsedProxyUrl.toString(); +} + +type FetchProxiedArg = { + proxyUrl: string; + fetchFn: typeof fetch; +} & ( + | { + frameAction: SignedFrameAction; + extraRequestPayload?: Record; + } + | { url: string } +); + +async function fetchProxied( + params: FetchProxiedArg +): Promise { + const searchParams = new URLSearchParams({ + multispecification: "true", + }); + + if ("frameAction" in params) { + const proxyUrl = proxyUrlAndSearchParamsToUrl( + params.proxyUrl, + searchParams, + params.frameAction.searchParams + ); + + return tryCallAsync(() => + params.fetchFn(proxyUrl, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + ...params.extraRequestPayload, + ...params.frameAction.body, + }), + }) + ); + } + + searchParams.set("url", params.url); + + const proxyUrl = proxyUrlAndSearchParamsToUrl(params.proxyUrl, searchParams); + + return tryCallAsync(() => params.fetchFn(proxyUrl, { method: "GET" })); +} + +function getResponseBody(response: Response): Promise { + if (response.headers.get("content-type")?.includes("/json")) { + return response.clone().json(); + } + + return response.clone().text(); +} + +type SignAndGetFrameActionPayloadOptions = { + request: FramePOSTRequest; + signerState: SignerStateInstance; +}; + +/** + * This shouldn't be used for transaction data request + */ +async function signAndGetFrameActionBodyPayload({ + request, + signerState, +}: SignAndGetFrameActionPayloadOptions): Promise { + // Transacting address is not included in post action + const { address: _, ...requiredFrameContext } = request + .signerStateActionContext.frameContext as unknown as FarcasterFrameContext; + + return tryCallAsync(() => + signerState.signFrameAction({ + ...request.signerStateActionContext, + frameContext: requiredFrameContext, + }) + ); +} diff --git a/packages/render/src/unstable-use-frame-state.ts b/packages/render/src/unstable-use-frame-state.ts new file mode 100644 index 000000000..45029b0ef --- /dev/null +++ b/packages/render/src/unstable-use-frame-state.ts @@ -0,0 +1,478 @@ +import type { MutableRefObject } from "react"; +import { useMemo, useReducer, useRef } from "react"; +import type { SupportedParsingSpecification } from "frames.js/frame-parsers"; +import type { FrameContext, SignerStateInstance } from "./types"; +import type { + FrameReducerActions, + FrameStackGetPending, + FrameStackPostPending, + FrameState, + FrameStateAPI, + ResolveSignerFunction, + UseFrameStateOptions, + UseFrameStateReturn, +} from "./unstable-types"; +import { useFreshRef } from "./hooks/use-fresh-ref"; + +function createFramesStackReducer< + TExtraPending = unknown, + TExtraDone = unknown, + TExtraDoneRedirect = unknown, + TExtraRequestError = unknown, + TExtraMesssage = unknown, +>(resolveSignerRef: MutableRefObject) { + return function framesStackReducer( + state: FrameState< + TExtraPending, + TExtraDone, + TExtraDoneRedirect, + TExtraRequestError, + TExtraMesssage + >, + action: FrameReducerActions< + TExtraPending, + TExtraDone, + TExtraDoneRedirect, + TExtraRequestError, + TExtraMesssage + > + ): FrameState< + TExtraPending, + TExtraDone, + TExtraDoneRedirect, + TExtraRequestError, + TExtraMesssage + > { + switch (action.action) { + case "LOAD": + return { + ...state, + stack: [action.item, ...state.stack], + }; + case "DONE_REDIRECT": { + const index = state.stack.findIndex( + (item) => item.id === action.pendingItem.id + ); + + if (index === -1) { + return state; + } + + state.stack[index] = { + ...action.pendingItem, + ...action.item, + status: "doneRedirect", + }; + + return { + ...state, + stack: state.stack.slice(), + }; + } + case "DONE_WITH_ERROR_MESSAGE": { + const index = state.stack.findIndex( + (item) => item.id === action.pendingItem.id + ); + + if (index === -1) { + return state; + } + + state.stack[index] = { + ...action.pendingItem, + ...action.item, + }; + + return { + ...state, + stack: state.stack.slice(), + }; + } + case "DONE": { + const index = state.stack.findIndex( + (item) => item.id === action.pendingItem.id + ); + + if (index === -1) { + return state; + } + + let signerState: SignerStateInstance; + let specification: SupportedParsingSpecification; + let frameContext: FrameContext; + let homeframeUrl: string; + let parseResult = action.parseResult; + + if (state.type === "not-initialized") { + /** + * This is a response for initial request in the stack. We don't care if the request was GET or POST + * because we care only about initializing on initial request. + * + * It can be POST if you have a frame cast action response. Then we load the frame by sending a POST request. + */ + const resolvedSigner = resolveSignerRef.current({ + parseResult: action.parseResult, + }); + + ({ signerState, frameContext = {} } = resolvedSigner); + homeframeUrl = action.pendingItem.url; + specification = signerState.specification; + } else { + ({ + signerState, + specification, + frameContext, + homeframeUrl, + parseResult, + } = state); + } + + state.stack[index] = { + ...action.pendingItem, + status: "done", + frameResult: action.parseResult[specification], + extra: action.extra, + }; + + return { + ...state, + parseResult, + signerState, + frameContext, + homeframeUrl, + specification, + type: "initialized", + stack: state.stack.slice(), + }; + } + case "REQUEST_ERROR": { + const index = state.stack.findIndex( + (item) => item.id === action.pendingItem.id + ); + + if (index === -1) { + return state; + } + + state.stack[index] = action.item; + + return { + ...state, + stack: state.stack.slice(), + }; + } + case "RESET": { + if (state.type === "not-initialized") { + return state; + } + + const { frameContext = {}, signerState } = resolveSignerRef.current({ + parseResult: state.parseResult, + }); + + return { + ...state, + stack: + !!state.stack[0] && state.stack.length > 0 ? [state.stack[0]] : [], + type: "initialized", + frameContext, + signerState, + specification: signerState.specification, + }; + } + case "RESET_INITIAL_FRAME": { + const { frameContext = {}, signerState } = resolveSignerRef.current({ + parseResult: action.parseResult, + }); + const frameResult = action.parseResult[signerState.specification]; + + return { + type: "initialized", + signerState, + frameContext, + specification: signerState.specification, + homeframeUrl: action.homeframeUrl, + parseResult: action.parseResult, + stack: [ + { + request: { + method: "GET", + url: action.homeframeUrl, + }, + url: action.homeframeUrl, + id: Date.now(), + frameResult, + status: "done", + extra: action.extra, + }, + ], + }; + } + case "CLEAR": + return { + type: "not-initialized", + stack: [], + }; + default: + return state; + } + }; +} + +export function useFrameState< + TExtraPending = unknown, + TExtraDone = unknown, + TExtraDoneRedirect = unknown, + TExtraRequestError = unknown, + TExtraMesssage = unknown, +>({ + initialParseResult, + initialFrameUrl, + initialPendingExtra, + resolveSpecification, + resolveGETPendingExtra, + resolvePOSTPendingExtra, + resolveDoneExtra, + resolveDoneRedirectExtra, + resolveDoneWithErrorMessageExtra, + resolveFailedExtra, + resolveFailedWithRequestErrorExtra, +}: UseFrameStateOptions< + TExtraPending, + TExtraDone, + TExtraDoneRedirect, + TExtraRequestError, + TExtraMesssage +>): UseFrameStateReturn< + TExtraPending, + TExtraDone, + TExtraDoneRedirect, + TExtraRequestError, + TExtraMesssage +> { + const idCounterRef = useRef(0); + const resolveSpecificationRef = useFreshRef(resolveSpecification); + const resolveGETPendingExtraRef = useFreshRef(resolveGETPendingExtra); + const resolvePOSTPendingExtraRef = useFreshRef(resolvePOSTPendingExtra); + const resolveDoneExtraRef = useFreshRef(resolveDoneExtra); + const resolveDoneRedirectExtraRef = useFreshRef(resolveDoneRedirectExtra); + const resolveDoneWithErrorMessageExtraRef = useFreshRef( + resolveDoneWithErrorMessageExtra + ); + const resolveFailedExtraRef = useFreshRef(resolveFailedExtra); + const resolveFailedWithRequestErrorExtraRef = useFreshRef( + resolveFailedWithRequestErrorExtra + ); + const reducerRef = useRef( + createFramesStackReducer< + TExtraPending, + TExtraDone, + TExtraDoneRedirect, + TExtraRequestError, + TExtraMesssage + >(resolveSpecificationRef) + ); + const [state, dispatch] = useReducer( + reducerRef.current, + [initialParseResult, initialFrameUrl, initialPendingExtra] as const, + ([parseResult, frameUrl, extra]): FrameState< + TExtraPending, + TExtraDone, + TExtraDoneRedirect, + TExtraRequestError, + TExtraMesssage + > => { + if (parseResult && frameUrl) { + const { frameContext = {}, signerState } = resolveSpecification({ + parseResult, + }); + const frameResult = parseResult[signerState.specification]; + + return { + type: "initialized", + frameContext, + signerState, + specification: signerState.specification, + homeframeUrl: frameUrl, + parseResult, + stack: [ + { + id: idCounterRef.current++, + request: { + method: "GET", + url: frameUrl, + }, + frameResult, + status: "done", + url: frameUrl, + extra: (extra ?? {}) as TExtraDone, + }, + ], + }; + } + + return { + type: "not-initialized", + stack: frameUrl + ? [ + // prevent flash of empty content by adding pending item because initial frame is being loaded + { + id: idCounterRef.current++, + method: "GET", + request: { + method: "GET", + url: frameUrl, + }, + url: frameUrl, + status: "pending", + extra: (extra ?? {}) as TExtraPending, + }, + ] + : [], + }; + } + ); + + const api: FrameStateAPI< + TExtraPending, + TExtraDone, + TExtraDoneRedirect, + TExtraRequestError, + TExtraMesssage + > = useMemo(() => { + return { + dispatch, + clear() { + dispatch({ + action: "CLEAR", + }); + }, + createGetPendingItem(arg) { + const item: FrameStackGetPending = { + id: idCounterRef.current++, + method: "GET", + request: arg.request, + url: arg.request.url, + status: "pending", + extra: + resolveGETPendingExtraRef.current?.(arg) ?? ({} as TExtraPending), + }; + + dispatch({ + action: "LOAD", + item, + }); + + return item; + }, + createPostPendingItem(arg) { + const item: FrameStackPostPending = { + id: idCounterRef.current++, + method: "POST", + request: arg.request, + url: arg.action.searchParams.get("postUrl") ?? "missing postUrl", + status: "pending", + extra: + resolvePOSTPendingExtraRef.current?.(arg) ?? ({} as TExtraPending), + }; + + dispatch({ + action: "LOAD", + item, + }); + + return item; + }, + markAsDone(arg) { + dispatch({ + action: "DONE", + pendingItem: arg.pendingItem, + parseResult: arg.parseResult, + extra: resolveDoneExtraRef.current?.(arg) ?? ({} as TExtraDone), + }); + }, + markAsDoneWithErrorMessage(arg) { + dispatch({ + action: "DONE_WITH_ERROR_MESSAGE", + pendingItem: arg.pendingItem, + item: { + ...arg.pendingItem, + status: "message", + type: "error", + message: arg.responseData.message, + extra: + resolveDoneWithErrorMessageExtraRef.current?.(arg) ?? + ({} as TExtraMesssage), + }, + }); + }, + markAsDoneWithRedirect(arg) { + dispatch({ + action: "DONE_REDIRECT", + pendingItem: arg.pendingItem, + item: { + ...arg.pendingItem, + location: arg.location, + status: "doneRedirect", + extra: + resolveDoneRedirectExtraRef.current?.(arg) ?? + ({} as TExtraDoneRedirect), + }, + }); + }, + markAsFailed(arg) { + dispatch({ + action: "REQUEST_ERROR", + pendingItem: arg.pendingItem, + item: { + request: arg.pendingItem.request, + id: arg.pendingItem.id, + url: arg.pendingItem.url, + requestError: arg.requestError, + status: "requestError", + extra: + resolveFailedExtraRef.current?.(arg) ?? + ({} as TExtraRequestError), + }, + }); + }, + markAsFailedWithRequestError(arg) { + dispatch({ + action: "REQUEST_ERROR", + pendingItem: arg.pendingItem, + item: { + ...arg.pendingItem, + status: "requestError", + requestError: arg.error, + extra: + resolveFailedWithRequestErrorExtraRef.current?.(arg) ?? + ({} as TExtraRequestError), + }, + }); + }, + reset(arg) { + if (!arg) { + dispatch({ action: "RESET" }); + } else { + dispatch({ + action: "RESET_INITIAL_FRAME", + homeframeUrl: arg.homeframeUrl, + parseResult: arg.parseResult, + extra: (initialPendingExtra ?? {}) as TExtraDone, + }); + } + }, + }; + }, [ + initialPendingExtra, + resolveDoneExtraRef, + resolveDoneRedirectExtraRef, + resolveDoneWithErrorMessageExtraRef, + resolveFailedExtraRef, + resolveFailedWithRequestErrorExtraRef, + resolveGETPendingExtraRef, + resolvePOSTPendingExtraRef, + ]); + + return [state, api]; +} diff --git a/packages/render/src/unstable-use-frame.tsx b/packages/render/src/unstable-use-frame.tsx new file mode 100644 index 000000000..6dbc65cc4 --- /dev/null +++ b/packages/render/src/unstable-use-frame.tsx @@ -0,0 +1,548 @@ +/* eslint-disable @typescript-eslint/require-await -- we expect async functions */ +/* eslint-disable no-console -- provide feedback */ +/* eslint-disable no-alert -- provide feedback */ +import { useCallback, useEffect, useMemo, useState } from "react"; +import type { + Frame, + FrameButton, + FrameButtonLink, + FrameButtonPost, + FrameButtonTx, + TransactionTargetResponse, +} from "frames.js"; +import type { OnMintArgs, OnTransactionArgs, OnSignatureArgs } from "./types"; +import type { UseFrameOptions, UseFrameReturnValue } from "./unstable-types"; +import { useFrameState } from "./unstable-use-frame-state"; +import { useFetchFrame } from "./unstable-use-fetch-frame"; +import { useFreshRef } from "./hooks/use-fresh-ref"; +import { tryCallAsync } from "./helpers"; + +function onErrorFallback(e: Error): void { + console.error("@frames.js/render", e); +} + +function onMintFallback({ target }: OnMintArgs): void { + console.log("Please provide your own onMint function to useFrame() hook."); + + const message = `Mint requested: ${target}`; + + if (typeof window !== "undefined") { + window.alert(message); + } else { + console.log(message); + } +} + +function resolveAddressFallback(): never { + throw new Error( + "Please implement this function in order to use transactions" + ); +} + +async function onTransactionFallback({ + transactionData, +}: OnTransactionArgs): Promise { + console.log( + "Please provide your own onTransaction function to useFrame() hook." + ); + + const message = `Requesting a transaction on chain with ID ${ + transactionData.chainId + } with the following params: ${JSON.stringify( + transactionData.params, + null, + 2 + )}`; + + if (typeof window !== "undefined") { + window.alert(message); + } else { + console.log(message); + } + + return null; +} + +async function onSignatureFallback({ + signatureData, +}: OnSignatureArgs): Promise { + console.log( + "Please provide your own onSignature function to useFrame() hook." + ); + + const message = `Requesting a signature on chain with ID ${ + signatureData.chainId + } with the following params: ${JSON.stringify( + signatureData.params, + null, + 2 + )}`; + + if (typeof window !== "undefined") { + window.alert(message); + } else { + console.log(message); + } + + return null; +} + +function handleRedirectFallback(location: URL): void { + console.log( + "Please provide your own onRedirect function to useFetchFrame() hook." + ); + + const message = `You are about to be redirected to ${location.toString()}`; + + if (typeof window !== "undefined") { + if (window.confirm(message)) { + window.open(location, "_blank")?.focus(); + } + } else { + console.log(message); + } +} + +function handleLinkButtonClickFallback(button: FrameButtonLink): void { + console.log( + "Please provide your own onLinkButtonClick function to useFrame() hook." + ); + + if (typeof window !== "undefined") { + if (window.confirm(`You are about to be redirected to ${button.target}`)) { + parent.window.open(button.target, "_blank"); + } + } else { + console.log(`Link button with target ${button.target} clicked.`); + } +} + +/** + * Validates a link button target to ensure it is a valid HTTP or HTTPS URL. + * @param target - The target URL to validate. + * @returns True if the target is a valid HTTP or HTTPS URL, otherwise throws an error. + */ +function validateLinkButtonTarget(target: string): boolean { + // check the URL is valid + const locationUrl = new URL(target); + + // Reject non-http(s) URLs + if (locationUrl.protocol !== "http:" && locationUrl.protocol !== "https:") { + throw new Error( + `Redirect location ${locationUrl.toString()} is not a valid HTTP or HTTPS URL.` + ); + } + + return true; +} + +function defaultFetchFunction( + input: RequestInfo | URL, + init?: RequestInit +): Promise { + return fetch(input, init); +} + +export type { + UseFrameReturnValue as UnstableUseFrameReturnValue, + UseFrameOptions as UnstableUseFrameOptions, +}; + +// eslint-disable-next-line camelcase -- this is only temporary +export function useFrame_unstable< + TExtraDataPending = unknown, + TExtraDataDone = unknown, + TExtraDataDoneRedirect = unknown, + TExtraDataRequestError = unknown, + TExtraDataMesssage = unknown, +>({ + frameStateHook: useFrameStateHook = useFrameState, + homeframeUrl, + onMint = onMintFallback, + onTransaction = onTransactionFallback, + transactionDataSuffix, + onSignature = onSignatureFallback, + resolveAddress = resolveAddressFallback, + frame, + /** Ex: /frames */ + frameActionProxy, + /** Ex: /frames */ + frameGetProxy, + extraButtonRequestPayload, + resolveSigner: resolveSpecification, + onError = onErrorFallback, + onLinkButtonClick = handleLinkButtonClickFallback, + onRedirect = handleRedirectFallback, + fetchFn = defaultFetchFunction, + onTransactionDataError, + onTransactionDataStart, + onTransactionDataSuccess, + onTransactionError, + onTransactionProcessingError, + onTransactionProcessingStart, + onTransactionProcessingSuccess, + onTransactionStart, + onTransactionSuccess, +}: UseFrameOptions< + TExtraDataPending, + TExtraDataDone, + TExtraDataDoneRedirect, + TExtraDataRequestError, + TExtraDataMesssage +>): UseFrameReturnValue< + TExtraDataPending, + TExtraDataDone, + TExtraDataDoneRedirect, + TExtraDataRequestError, + TExtraDataMesssage +> { + const [inputText, setInputText] = useState(""); + const inputTextRef = useFreshRef(inputText); + const [frameState, frameStateAPI] = useFrameStateHook({ + resolveSpecification, + initialFrameUrl: homeframeUrl, + initialParseResult: frame, + }); + const frameStateRef = useFreshRef(frameState); + + const { + clear: clearFrameState, + dispatch: dispatchFrameState, + reset: resetFrameState, + } = frameStateAPI; + + const fetchFrame = useFetchFrame({ + frameState, + frameStateAPI, + frameActionProxy, + frameGetProxy, + onTransaction, + transactionDataSuffix, + onSignature, + extraButtonRequestPayload, + onError, + fetchFn, + onRedirect, + onTransactionDataError, + onTransactionDataStart, + onTransactionDataSuccess, + onTransactionError, + onTransactionProcessingError, + onTransactionProcessingStart, + onTransactionProcessingSuccess, + onTransactionStart, + onTransactionSuccess, + }); + + const fetchFrameRef = useFreshRef(fetchFrame); + const onErrorRef = useFreshRef(onError); + + useEffect(() => { + if (!homeframeUrl) { + // if we don't have an url we don't want to show anything + clearFrameState(); + + return; + } + + if (!frame) { + fetchFrameRef + .current( + { + url: homeframeUrl, + method: "GET", + }, + // tell the fetchFrame function to clear the stack because this is called only on initial render + // and there could potentially be a pending object returned from SSR + true + ) + .catch((e) => { + onErrorRef.current(e instanceof Error ? e : new Error(String(e))); + }); + } else { + resetFrameState({ + homeframeUrl, + parseResult: frame, + }); + } + }, [ + frame, + homeframeUrl, + clearFrameState, + fetchFrameRef, + resetFrameState, + onErrorRef, + ]); + + const onPostButton = useCallback( + async function onPostButton({ + currentFrame, + buttonIndex, + postInputText, + frameButton, + target, + state, + fetchFrameOverride, + }: { + currentFrame: Frame; + frameButton: FrameButtonPost; + buttonIndex: number; + postInputText: string | undefined; + state?: string; + target: string; + fetchFrameOverride?: typeof fetchFrame; + }): Promise { + const currentState = frameStateRef.current; + + if (currentState.type === "not-initialized") { + const error = new Error( + "Cannot perform post/post_redirect without a frame" + ); + + onErrorRef.current(error); + + return; + } + + if (!currentState.signerState.hasSigner) { + await currentState.signerState.onSignerlessFramePress(); + return; + } + + const _fetchFrame = fetchFrameOverride ?? fetchFrameRef.current; + + await _fetchFrame({ + frameButton, + isDangerousSkipSigning: false, + method: "POST", + signerStateActionContext: { + inputText: postInputText, + signer: currentState.signerState.signer, + frameContext: currentState.frameContext, + url: currentState.homeframeUrl, + target, + frameButton, + buttonIndex, + state, + }, + sourceFrame: currentFrame, + }); + }, + [fetchFrameRef, frameStateRef, onErrorRef] + ); + + const resolveAddressRef = useFreshRef(resolveAddress); + + const onTransactionButton = useCallback( + async function onTransactionButton({ + currentFrame, + buttonIndex, + postInputText, + frameButton, + }: { + currentFrame: Frame; + frameButton: FrameButtonTx; + buttonIndex: number; + postInputText: string | undefined; + }): Promise { + const currentState = frameStateRef.current; + + if (currentState.type === "not-initialized") { + const error = new Error("Cannot perform transaction without a frame"); + + onErrorRef.current(error); + + return; + } + + // Send post request to get calldata + if (!currentState.signerState.hasSigner) { + await currentState.signerState.onSignerlessFramePress(); + return; + } + + const addressOrError = await tryCallAsync(() => + resolveAddressRef.current() + ); + + if (addressOrError instanceof Error) { + onErrorRef.current(addressOrError); + return; + } + + if (!addressOrError) { + onErrorRef.current( + new Error( + "Wallet address missing, please check resolveAddress() function passed to useFrame_unstable() hook." + ) + ); + return; + } + + // transaction request always requires address + const frameContext = { + ...currentState.frameContext, + address: addressOrError, + }; + + await fetchFrameRef.current({ + frameButton, + isDangerousSkipSigning: false, + method: "POST", + signerStateActionContext: { + type: "tx-data", + inputText: postInputText, + signer: currentState.signerState.signer, + frameContext, + address: addressOrError, + url: currentState.homeframeUrl, + target: frameButton.target, + frameButton, + buttonIndex, + state: currentFrame.state, + }, + sourceFrame: currentFrame, + }); + }, + [frameStateRef, fetchFrameRef, onErrorRef, resolveAddressRef] + ); + + const onButtonPress = useCallback( + async function onButtonPress( + currentFrame: Frame, + frameButton: FrameButton, + index: number, + fetchFrameOverride?: typeof fetchFrame + ): Promise { + switch (frameButton.action) { + case "link": { + try { + validateLinkButtonTarget(frameButton.target); + } catch (error) { + if (error instanceof Error) { + onErrorRef.current(error); + } + return; + } + + onLinkButtonClick(frameButton); + break; + } + case "mint": { + onMint({ + frameButton, + target: frameButton.target, + frame: currentFrame, + }); + break; + } + case "tx": { + await onTransactionButton({ + frameButton, + buttonIndex: index + 1, + postInputText: + currentFrame.inputText !== undefined + ? inputTextRef.current + : undefined, + currentFrame, + }); + break; + } + case "post": + case "post_redirect": { + try { + const target = + frameButton.target || + frameButton.post_url || + currentFrame.postUrl || + homeframeUrl; + + if (!target) { + onErrorRef.current(new Error(`Missing target`)); + return; + } + + try { + validateLinkButtonTarget(target); + } catch (error) { + if (error instanceof Error) { + onErrorRef.current(error); + } + return; + } + + await onPostButton({ + currentFrame, + frameButton, + /** https://docs.farcaster.xyz/reference/frames/spec#handling-clicks + + POST the packet to fc:frame:button:$idx:action:target if present + POST the packet to fc:frame:post_url if target was not present. + POST the packet to or the frame's embed URL if neither target nor action were present. + */ + target, + buttonIndex: index + 1, + postInputText: + currentFrame.inputText !== undefined + ? inputTextRef.current + : undefined, + state: currentFrame.state, + fetchFrameOverride, + }); + setInputText(""); + } catch (err) { + onErrorRef.current( + err instanceof Error ? err : new Error(String(err)) + ); + } + break; + } + default: + throw new Error("Unrecognized frame button action"); + } + }, + [ + homeframeUrl, + inputTextRef, + onErrorRef, + onLinkButtonClick, + onMint, + onPostButton, + onTransactionButton, + ] + ); + + const { stack } = frameState; + const { signerState, specification } = + frameState.type === "initialized" + ? frameState + : { signerState: undefined, specification: undefined }; + + return useMemo(() => { + return { + signerState, + specification, + inputText, + setInputText, + clearFrameStack: clearFrameState, + dispatchFrameStack: dispatchFrameState, + reset: resetFrameState, + onButtonPress, + fetchFrame, + homeframeUrl, + framesStack: stack, + currentFrameStackItem: stack[0], + }; + }, [ + signerState, + specification, + inputText, + clearFrameState, + dispatchFrameState, + onButtonPress, + resetFrameState, + fetchFrame, + homeframeUrl, + stack, + ]); +} diff --git a/packages/render/src/use-composer-action.ts b/packages/render/src/use-composer-action.ts new file mode 100644 index 000000000..209a1550b --- /dev/null +++ b/packages/render/src/use-composer-action.ts @@ -0,0 +1,702 @@ +import { useCallback, useEffect, useMemo, useReducer, useRef } from "react"; +import type { + ComposerActionFormResponse, + ComposerActionState, +} from "frames.js/types"; +import type { FarcasterSignerState } from "./farcaster"; +import { useFreshRef } from "./hooks/use-fresh-ref"; +import { + isComposerFormActionResponse, + mergeSearchParamsToUrl, + tryCall, + tryCallAsync, +} from "./helpers"; +import { + ComposerActionUnexpectedResponseError, + ComposerActionUserRejectedRequestError, +} from "./errors"; +import type { + EthSendTransactionAction, + EthSignTypedDataV4Action, + MiniAppMessage, + MiniAppResponse, +} from "./mini-app-messages"; +import { miniAppMessageSchema } from "./mini-app-messages"; +import type { FarcasterSigner } from "./identity/farcaster"; +import type { ResolveAddressFunction } from "./unstable-types"; + +export type { MiniAppMessage, MiniAppResponse, ResolveAddressFunction }; + +type FetchComposerActionFunctionArg = { + actionState: ComposerActionState; + proxyUrl: string; + signer: FarcasterSigner | null; + url: string; +}; + +type FetchComposerActionFunction = ( + arg: FetchComposerActionFunctionArg +) => Promise; + +export type RegisterMessageListener = ( + formResponse: ComposerActionFormResponse, + messageListener: MiniAppMessageListener +) => () => void; + +type MiniAppMessageListener = (message: MiniAppMessage) => Promise; + +export type OnTransactionFunctionResult = { + hash: `0x${string}`; + address: `0x${string}`; +}; + +export type OnTransactionFunction = (arg: { + action: EthSendTransactionAction; + address: `0x${string}`; +}) => Promise; + +export type OnSignatureFunctionResult = { + hash: `0x${string}`; + address: `0x${string}`; +}; + +export type OnSignatureFunction = (arg: { + action: EthSignTypedDataV4Action; + address: `0x${string}`; +}) => Promise; + +export type OnCreateCastFunction = (arg: { + cast: ComposerActionState; +}) => Promise; + +export type OnMessageRespondFunction = ( + response: MiniAppResponse, + form: ComposerActionFormResponse +) => unknown; + +export type UseComposerActionOptions = { + /** + * Current action state, value should be memoized. It doesn't cause composer action / mini app to refetch. + */ + actionState: ComposerActionState; + /** + * URL to composer action / mini app server + * + * If value changes it will refetch the composer action / mini app + */ + url: string; + /** + * Signer used to sign the composer action. + * + * If value changes it will refetch the composer action / mini app + */ + signer: FarcasterSignerState; + /** + * URL to the action proxy server. If value changes composer action / mini app will be refetched. + * + * Proxy must handle POST requests. + */ + proxyUrl: string; + /** + * If enabled if will fetch the composer action / mini app on mount. + * + * @defaultValue true + */ + enabled?: boolean; + /** + * Custom fetch function to fetch the composer action / mini app. + */ + fetch?: (url: string, init: RequestInit) => Promise; + /** + * Called before onTransaction/onSignature is invoked to obtain an address to use. + * + * If the function returns null onTransaction/onSignature will not be called. + */ + resolveAddress: ResolveAddressFunction; + onError?: (error: Error) => void; + onCreateCast: OnCreateCastFunction; + onTransaction: OnTransactionFunction; + onSignature: OnSignatureFunction; + /** + * Called with message response to be posted to child (e.g. iframe). + */ + onMessageRespond: OnMessageRespondFunction; + /** + * Allows to override how the message listener is registered. Function must return a function that removes the listener. + * + * Changes in the value aren't reflected so it's recommended to use a memoized function. + * + * By default it uses window.addEventListener("message", ...) + */ + registerMessageListener?: RegisterMessageListener; +}; + +type UseComposerActionResult = { + refetch: () => Promise; +} & ( + | { + status: "idle"; + data: undefined; + error: undefined; + } + | { + status: "loading"; + data: undefined; + error: undefined; + } + | { + status: "error"; + data: undefined; + error: Error; + } + | { + status: "success"; + data: ComposerActionFormResponse; + error: undefined; + } +); + +export function useComposerAction({ + actionState, + enabled = true, + proxyUrl, + signer, + url, + fetch: fetchFunction, + onError, + onCreateCast, + onSignature, + onTransaction, + resolveAddress, + registerMessageListener = defaultRegisterMessageListener, + onMessageRespond, +}: UseComposerActionOptions): UseComposerActionResult { + const onErrorRef = useFreshRef(onError); + const [state, dispatch] = useReducer(composerActionReducer, { + status: "idle", + enabled, + }); + const registerMessageListenerRef = useFreshRef(registerMessageListener); + const actionStateRef = useFreshRef(actionState); + const onCreateCastRef = useFreshRef(onCreateCast); + const onMessageRespondRef = useFreshRef(onMessageRespond); + const onTransactionRef = useFreshRef(onTransaction); + const onSignatureRef = useFreshRef(onSignature); + const resolveAddressRef = useFreshRef(resolveAddress); + const lastFetchActionArgRef = useRef( + null + ); + const signerRef = useFreshRef(signer); + const fetchRef = useFreshRef(fetchFunction); + + const messageListener = useCallback( + async ( + successState: Extract, + message: MiniAppMessage + ) => { + if ("type" in message || message.method === "fc_createCast") { + const cast = + "type" in message ? message.data.cast : message.params.cast; + + const resultOrError = await tryCallAsync(() => + onCreateCastRef.current({ + cast, + }) + ); + + if (resultOrError instanceof Error) { + onMessageRespondRef.current( + { + jsonrpc: "2.0", + id: "method" in message ? message.id : null, + error: { + code: -32000, + message: resultOrError.message, + }, + }, + successState.response + ); + } + + onMessageRespondRef.current( + { + jsonrpc: "2.0", + id: "method" in message ? message.id : null, + result: { + success: true, + }, + }, + successState.response + ); + } else if (message.method === "fc_requestWalletAction") { + const addressOrError = await tryCallAsync(() => + resolveAddressRef.current() + ); + + if (addressOrError instanceof Error) { + tryCall(() => onErrorRef.current?.(addressOrError)); + + onMessageRespondRef.current( + { + jsonrpc: "2.0", + id: message.id, + error: { + code: -32000, + message: addressOrError.message, + }, + }, + successState.response + ); + + return; + } + + if (!addressOrError) { + return; + } + + if (message.params.action.method === "eth_sendTransaction") { + const action = message.params.action; + + const resultOrError = await tryCallAsync(() => + onTransactionRef.current({ + action, + address: addressOrError, + }) + ); + + if (resultOrError instanceof Error) { + tryCall(() => onErrorRef.current?.(resultOrError)); + + onMessageRespondRef.current( + { + jsonrpc: "2.0", + id: message.id, + error: { + code: -32000, + message: resultOrError.message, + }, + }, + successState.response + ); + + return; + } + + if (!resultOrError) { + const error = new ComposerActionUserRejectedRequestError(); + + tryCall(() => onErrorRef.current?.(error)); + + onMessageRespondRef.current( + { + jsonrpc: "2.0", + id: message.id, + error: { + code: -32000, + message: error.message, + }, + }, + successState.response + ); + return; + } + + onMessageRespondRef.current( + { + jsonrpc: "2.0", + id: message.id, + result: { + address: resultOrError.address, + transactionHash: resultOrError.hash, + }, + }, + successState.response + ); + } else if (message.params.action.method === "eth_signTypedData_v4") { + const action = message.params.action; + + const resultOrError = await tryCallAsync(() => + onSignatureRef.current({ + action, + address: addressOrError, + }) + ); + + if (resultOrError instanceof Error) { + tryCall(() => onErrorRef.current?.(resultOrError)); + + onMessageRespondRef.current( + { + jsonrpc: "2.0", + id: message.id, + error: { + code: -32000, + message: resultOrError.message, + }, + }, + successState.response + ); + + return; + } + + if (!resultOrError) { + const error = new ComposerActionUserRejectedRequestError(); + + tryCall(() => onErrorRef.current?.(error)); + + onMessageRespondRef.current( + { + jsonrpc: "2.0", + id: message.id, + error: { + code: -32000, + message: error.message, + }, + }, + successState.response + ); + + return; + } + + onMessageRespondRef.current( + { + jsonrpc: "2.0", + id: message.id, + result: { + address: resultOrError.address, + signature: resultOrError.hash, + }, + }, + successState.response + ); + } else { + tryCall(() => + onErrorRef.current?.( + new Error( + `Unknown fc_requestWalletAction action method: ${message.params.action.method}` + ) + ) + ); + } + } else { + tryCall(() => onErrorRef.current?.(new Error("Unknown message"))); + } + }, + [ + onCreateCastRef, + onErrorRef, + onMessageRespondRef, + onSignatureRef, + onTransactionRef, + resolveAddressRef, + ] + ); + + const fetchAction = useCallback( + async (arg) => { + const currentSigner = arg.signer; + + if ( + currentSigner?.status !== "approved" && + currentSigner?.status !== "impersonating" + ) { + await signerRef.current.onSignerlessFramePress(); + return; + } + + dispatch({ type: "loading-url" }); + + const signedDataOrError = await tryCallAsync(() => + signerRef.current.signComposerAction(currentSigner.privateKey, { + url: arg.url, + state: arg.actionState, + fid: currentSigner.fid, + }) + ); + + if (signedDataOrError instanceof Error) { + tryCall(() => onErrorRef.current?.(signedDataOrError)); + dispatch({ type: "error", error: signedDataOrError }); + + return; + } + + const proxiedUrl = mergeSearchParamsToUrl( + arg.proxyUrl, + new URLSearchParams({ postUrl: arg.url }) + ); + + const actionResponseOrError = await tryCallAsync(() => + (fetchRef.current || fetch)(proxiedUrl, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify(signedDataOrError), + cache: "no-cache", + }) + ); + + if (actionResponseOrError instanceof Error) { + tryCall(() => onErrorRef.current?.(actionResponseOrError)); + dispatch({ type: "error", error: actionResponseOrError }); + + return; + } + + if (!actionResponseOrError.ok) { + const error = new Error( + `Unexpected response status ${actionResponseOrError.status}` + ); + + tryCall(() => onErrorRef.current?.(error)); + dispatch({ type: "error", error }); + + return; + } + + const actionResponseDataOrError = await tryCallAsync( + () => actionResponseOrError.clone().json() as Promise + ); + + if (actionResponseDataOrError instanceof Error) { + tryCall(() => onErrorRef.current?.(actionResponseDataOrError)); + dispatch({ type: "error", error: actionResponseDataOrError }); + + return; + } + + if (!isComposerFormActionResponse(actionResponseDataOrError)) { + const error = new ComposerActionUnexpectedResponseError(); + tryCall(() => onErrorRef.current?.(error)); + dispatch({ type: "error", error }); + + return; + } + + dispatch({ type: "done", response: actionResponseDataOrError }); + }, + [fetchRef, onErrorRef, signerRef] + ); + + const stateRef = useFreshRef(state); + const refetch = useCallback(() => { + if (!stateRef.current.enabled || !lastFetchActionArgRef.current) { + return Promise.resolve(); + } + + return fetchAction(lastFetchActionArgRef.current); + }, [fetchAction, stateRef]); + + useEffect(() => { + dispatch({ type: "enabled-change", enabled }); + }, [enabled]); + + useEffect(() => { + if (!enabled) { + return; + } + + lastFetchActionArgRef.current = { + actionState: actionStateRef.current, + signer: signer.signer as unknown as FarcasterSigner | null, + url, + proxyUrl, + }; + + fetchAction(lastFetchActionArgRef.current).catch((e) => { + onErrorRef.current?.(e instanceof Error ? e : new Error(String(e))); + }); + }, [ + url, + proxyUrl, + signer.signer, + enabled, + fetchAction, + actionStateRef, + onErrorRef, + ]); + + // register message listener when state changes to success + useEffect(() => { + if (state.status === "success") { + return registerMessageListenerRef.current( + state.response, + messageListener.bind(null, state) + ); + } + }, [messageListener, registerMessageListenerRef, state]); + + return useMemo(() => { + switch (state.status) { + case "idle": + return { + status: "idle", + data: undefined, + error: undefined, + refetch, + }; + case "loading": + return { + status: "loading", + data: undefined, + error: undefined, + refetch, + }; + case "error": + return { + status: "error", + data: undefined, + error: state.error, + refetch, + }; + default: + return { + status: "success", + data: state.response, + error: undefined, + refetch, + }; + } + }, [state, refetch]); +} + +export { miniAppMessageSchema }; + +/** + * Default function used to register message listener. Works in browsers only. + */ +export const defaultRegisterMessageListener: RegisterMessageListener = + function defaultRegisterMessageListener(formResponse, messageListener) { + if (typeof window === "undefined") { + // eslint-disable-next-line no-console -- provide feedback + console.warn( + "@frames.js/render: You are using default registerMessageListener in an environment without window object" + ); + + return () => { + // noop + }; + } + + const miniAppOrigin = new URL(formResponse.url).origin; + + const messageParserListener = (event: MessageEvent): void => { + // make sure that we only listen to messages from the mini app + if (event.origin !== miniAppOrigin) { + return; + } + + const result = miniAppMessageSchema.safeParse(event.data); + + if (!result.success) { + // eslint-disable-next-line no-console -- provide feedback + console.warn( + "@frames.js/render: Invalid message received", + event.data, + result.error + ); + return; + } + + const message = result.data; + + messageListener(message).catch((e) => { + // eslint-disable-next-line no-console -- provide feedback + console.error(`@frames.js/render:`, e); + }); + }; + + window.addEventListener("message", messageParserListener); + + return () => { + window.removeEventListener("message", messageParserListener); + }; + }; + +type SharedComposerActionReducerState = { + enabled: boolean; +}; + +type ComposerActionReducerState = SharedComposerActionReducerState & + ( + | { + status: "idle"; + } + | { + status: "loading"; + } + | { + status: "error"; + error: Error; + } + | { + status: "success"; + response: ComposerActionFormResponse; + } + ); + +type ComposerActionReducerAction = + | { + type: "loading-url"; + } + | { + type: "error"; + error: Error; + } + | { + type: "done"; + response: ComposerActionFormResponse; + } + | { + type: "enabled-change"; + enabled: boolean; + }; + +function composerActionReducer( + state: ComposerActionReducerState, + action: ComposerActionReducerAction +): ComposerActionReducerState { + if (action.type === "enabled-change") { + if (action.enabled) { + return { + ...state, + enabled: true, + }; + } + + return { + status: "idle", + enabled: false, + }; + } + + if (!state.enabled) { + return state; + } + + switch (action.type) { + case "done": + return { + ...state, + status: "success", + response: action.response, + }; + case "loading-url": + return { + ...state, + status: "loading", + }; + case "error": + return { + ...state, + status: "error", + error: action.error, + }; + default: + return state; + } +} diff --git a/packages/render/src/use-fetch-frame.ts b/packages/render/src/use-fetch-frame.ts index 32a76465f..8c85f7cb3 100644 --- a/packages/render/src/use-fetch-frame.ts +++ b/packages/render/src/use-fetch-frame.ts @@ -23,14 +23,12 @@ import type { FramePOSTRequest, FrameStackPending, FrameStackPostPending, - GetFrameResult, SignedFrameAction, SignerStateActionContext, SignerStateDefaultActionContext, UseFetchFrameOptions, UseFetchFrameSignFrameActionFunction, } from "./types"; -import { isParseResult } from "./use-frame-stack"; import { SignatureHandlerDidNotReturnTransactionIdError, TransactionDataErrorResponseError, @@ -39,7 +37,12 @@ import { CastActionUnexpectedResponseError, ComposerActionUnexpectedResponseError, } from "./errors"; -import { tryCall, tryCallAsync } from "./helpers"; +import { + isParseFramesWithReportsResult, + isParseResult, + tryCall, + tryCallAsync, +} from "./helpers"; function isErrorMessageResponse( response: unknown @@ -218,13 +221,62 @@ export function useFetchFrame< return; } - const frameResult = (await response.clone().json()) as GetFrameResult; + const parseResult = await tryCallAsync( + () => response.clone().json() as Promise + ); - stackAPI.markAsDone({ - pendingItem: frameStackPendingItem, + if (parseResult instanceof Error) { + stackAPI.markAsFailed({ + endTime, + pendingItem: frameStackPendingItem, + requestError: parseResult, + response, + responseBody: "none", + responseStatus: 500, + }); + + tryCall(() => { + onError(parseResult); + }); + + return; + } + + if (isParseFramesWithReportsResult(parseResult)) { + stackAPI.markAsDone({ + pendingItem: frameStackPendingItem, + endTime, + frameResult: parseResult[specification], + response, + }); + + return; + } + + if (isParseResult(parseResult)) { + stackAPI.markAsDone({ + pendingItem: frameStackPendingItem, + endTime, + frameResult: parseResult, + response, + }); + + return; + } + + const error = new Error("The server returned an unexpected response."); + + stackAPI.markAsFailed({ endTime, - frameResult, + pendingItem: frameStackPendingItem, + requestError: error, response, + responseBody: parseResult, + responseStatus: 500, + }); + + tryCall(() => { + onError(error); }); return; @@ -440,33 +492,46 @@ export function useFetchFrame< return; } - if (!isParseResult(responseData)) { - const error = new Error("The server returned an unexpected response."); - - stackAPI.markAsFailed({ + if (isParseFramesWithReportsResult(responseData)) { + stackAPI.markAsDone({ endTime, + frameResult: responseData[specification], pendingItem, - requestError: error, response, - responseBody: responseData, - responseStatus: 500, }); - tryCall(() => { - onError(error); + + tryCall(() => options?.onSuccess?.()); + + return; + } + + if (isParseResult(responseData)) { + stackAPI.markAsDone({ + endTime, + frameResult: responseData, + pendingItem, + response, }); - tryCall(() => options?.onError?.(error)); + + tryCall(() => options?.onSuccess?.()); return; } - stackAPI.markAsDone({ + const error = new Error("The server returned an unexpected response."); + + stackAPI.markAsFailed({ endTime, - frameResult: responseData, pendingItem, + requestError: error, response, + responseBody: responseData, + responseStatus: 500, }); - - tryCall(() => options?.onSuccess?.()); + tryCall(() => { + onError(error); + }); + tryCall(() => options?.onError?.(error)); return; } diff --git a/packages/render/src/use-frame-stack.ts b/packages/render/src/use-frame-stack.ts index 5c5ac0fc0..8dda97991 100644 --- a/packages/render/src/use-frame-stack.ts +++ b/packages/render/src/use-frame-stack.ts @@ -1,5 +1,5 @@ -import { useMemo, useReducer } from "react"; -import type { Frame } from "frames.js"; +import { type MutableRefObject, useMemo, useReducer, useRef } from "react"; +import type { Frame, SupportedParsingSpecification } from "frames.js"; import type { ParseResult } from "frames.js/frame-parsers"; import type { CastActionMessageResponse, @@ -16,16 +16,14 @@ import type { SignedFrameAction, SignerStateActionContext, } from "./types"; +import { isParseResult } from "./helpers"; function computeDurationInSeconds(start: Date, end: Date): number { return Number(((end.getTime() - start.getTime()) / 1000).toFixed(2)); } -export function isParseResult(result: unknown): result is ParseResult { - return typeof result === "object" && result !== null && "status" in result; -} - function framesStackReducer( + idCounterRef: MutableRefObject, state: FramesStack, action: FrameReducerActions ): FramesStack { @@ -81,10 +79,12 @@ function framesStackReducer( status: "success" as const, reports: {}, frame: action.resultOrFrame, + specification: action.specification, }; return [ { + id: idCounterRef.current++, request: { method: "GET", url: action.homeframeUrl ?? "", @@ -118,6 +118,7 @@ function framesStackReducer( type UseFrameStackOptions = { initialFrame?: Frame | ParseResult; initialFrameUrl?: string | null; + initialSpecification: SupportedParsingSpecification; }; export type FrameStackAPI = { @@ -199,15 +200,17 @@ export type FrameStackAPI = { export function useFrameStack({ initialFrame, initialFrameUrl, + initialSpecification, }: UseFrameStackOptions): [ FramesStack, React.Dispatch, FrameStackAPI, ] { + const idCounterRef = useRef(0); const [stack, dispatch] = useReducer( - framesStackReducer, - [initialFrame, initialFrameUrl] as const, - ([frame, frameUrl]): FramesStack => { + framesStackReducer.bind(null, idCounterRef), + [initialFrame, initialFrameUrl, initialSpecification] as const, + ([frame, frameUrl, specification]): FramesStack => { if (frame) { const frameResult = isParseResult(frame) ? frame @@ -215,9 +218,11 @@ export function useFrameStack({ reports: {}, frame, status: "success" as const, + specification, }; return [ { + id: idCounterRef.current++, response: new Response(JSON.stringify(frameResult), { status: 200, headers: { "Content-Type": "application/json" }, @@ -241,6 +246,7 @@ export function useFrameStack({ // this is then handled by fetchFrame having second argument set to true so the stack is cleared return [ { + id: idCounterRef.current++, method: "GET", request: { method: "GET", @@ -267,6 +273,7 @@ export function useFrameStack({ }, createGetPendingItem(arg) { const item: FrameStackGetPending = { + id: idCounterRef.current++, method: "GET", request: arg.request, requestDetails: {}, @@ -284,6 +291,7 @@ export function useFrameStack({ }, createPostPendingItem(arg) { const item: FrameStackPostPending = { + id: idCounterRef.current++, method: "POST", request: arg.request, requestDetails: { @@ -304,6 +312,7 @@ export function useFrameStack({ }, createCastOrComposerActionPendingItem(arg) { return { + id: idCounterRef.current++, method: "POST", requestDetails: { body: arg.action.body, @@ -404,6 +413,7 @@ export function useFrameStack({ action: "REQUEST_ERROR", pendingItem: arg.pendingItem, item: { + id: arg.pendingItem.id, request: arg.pendingItem.request, requestDetails: arg.pendingItem.requestDetails, timestamp: arg.pendingItem.timestamp, diff --git a/packages/render/src/use-frame.tsx b/packages/render/src/use-frame.tsx index 02ae58151..dedafe433 100644 --- a/packages/render/src/use-frame.tsx +++ b/packages/render/src/use-frame.tsx @@ -24,6 +24,14 @@ import type { import { unsignedFrameAction, type FarcasterFrameContext } from "./farcaster"; import { useFrameStack } from "./use-frame-stack"; import { useFetchFrame } from "./use-fetch-frame"; +import { useFreshRef } from "./hooks/use-fresh-ref"; + +// eslint-disable-next-line camelcase -- this is only temporary +export { useFrame_unstable } from "./unstable-use-frame"; +export type { + UnstableUseFrameOptions, + UnstableUseFrameReturnValue, +} from "./unstable-use-frame"; function onMintFallback({ target }: OnMintArgs): void { console.log("Please provide your own onMint function to useFrame() hook."); @@ -189,6 +197,7 @@ export function useFrame< const [framesStack, dispatch, stackAPI] = useFrameStack({ initialFrame: frame, initialFrameUrl: homeframeUrl, + initialSpecification: specification, }); const fetchFrame = useFetchFrame< @@ -229,10 +238,9 @@ export function useFrame< onTransactionSuccess, }); - const fetchFrameRef = useRef(fetchFrame); - fetchFrameRef.current = fetchFrame; - const onErrorRef = useRef(onError); - onErrorRef.current = onError; + const fetchFrameRef = useFreshRef(fetchFrame); + const onErrorRef = useFreshRef(onError); + const specificationRef = useFreshRef(specification); useEffect(() => { if (!frame && homeframeUrl) { @@ -254,9 +262,10 @@ export function useFrame< action: "RESET_INITIAL_FRAME", resultOrFrame: frame, homeframeUrl, + specification: specificationRef.current, }); } - }, [frame, homeframeUrl, dispatch]); + }, [frame, homeframeUrl, dispatch, fetchFrameRef, specificationRef]); const onPostButton = useCallback( async function onPostButton({