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/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..e353259f1 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 { useDebuggerFrameState } from "@frames.js/render/unstable-use-debugger-frame-state"; +import { useFarcasterIdentity } from "../hooks/useFarcasterIdentity"; +import { useAccount } from "wagmi"; +import { FrameStackDone } from "@frames.js/render/unstable-types"; 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,19 @@ 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, + connectedAddress: account.address, 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 afba6a646..cd390136b 100644 --- a/packages/debugger/app/debugger-page.tsx +++ b/packages/debugger/app/debugger-page.tsx @@ -56,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 { @@ -67,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({ @@ -257,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(); @@ -301,8 +271,6 @@ export default function DebuggerPage({ }, }); - const anonymousFrameContext = {}; - const onConnectWallet: OnConnectWalletFunc = useCallback(async () => { if (!openConnectModal) { throw new Error(`openConnectModal not implemented`); @@ -640,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 c486a7551..b6f987512 100644 --- a/packages/debugger/app/frames/route.ts +++ b/packages/debugger/app/frames/route.ts @@ -1,51 +1,11 @@ -import { type FrameActionPayload } 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 { parseFramesWithReports } from "frames.js/parseFramesWithReports"; -import { z } from "zod"; import type { ParseActionResult } from "../actions/types"; import type { ParseFramesWithReportsResult } from "frames.js/frame-parsers"; -import type { JsonObject } from "frames.js/types"; - -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 CastActionDefinitionResponse = ParseActionResult & { type: "action"; @@ -126,129 +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); - } + await persistMockResponsesForDebugHubRequests(req); - if (!postUrl) { - return Response.json({ message: "Invalid post URL" }, { status: 400 }); - } - - 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 } - ); - } - - // 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 JsonObject; - 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 html = await r.text(); - - const parseResult = parseFramesWithReports({ - html, - fallbackPostUrl: body.untrustedData.url, - fromRequestMethod: "POST", - }); - - return Response.json({ - type: "frame", - ...parseResult, - } satisfies FrameDefinitionResponse); - } catch (err) { - // eslint-disable-next-line no-console -- provide feedback to the user - console.error(err); - return Response.json( - { - message: String(err), - }, - { status: 500 } - ); - } + return handlePOSTRequest(req); } 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/render/package.json b/packages/render/package.json index c97d0099f..41330a3e7 100644 --- a/packages/render/package.json +++ b/packages/render/package.json @@ -130,6 +130,16 @@ "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-debugger-frame-state": { "import": { "types": "./dist/unstable-use-debugger-frame-state.d.ts", @@ -285,6 +295,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/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/farcaster/frames.tsx b/packages/render/src/farcaster/frames.tsx index 7ccb9a013..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,9 +15,45 @@ 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"; +/** + * 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< FarcasterSigner, @@ -104,6 +140,43 @@ export const signFrameAction: SignFrameActionFunc< }; }; +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/signers.tsx b/packages/render/src/farcaster/signers.tsx index 08cd75195..58fe6b2a6 100644 --- a/packages/render/src/farcaster/signers.tsx +++ b/packages/render/src/farcaster/signers.tsx @@ -1,4 +1,5 @@ import type { FrameActionBodyPayload, SignerStateInstance } from "../types"; +import type { SignComposerActionFunc } from "../unstable-types"; import type { FarcasterFrameContext } from "./types"; export type FarcasterSignerState = @@ -6,7 +7,9 @@ export type FarcasterSignerState = TSignerType, FrameActionBodyPayload, FarcasterFrameContext - >; + > & { + signComposerAction: SignComposerActionFunc; + }; export type FarcasterSignerPendingApproval = { status: "pending_approval"; diff --git a/packages/render/src/helpers.ts b/packages/render/src/helpers.ts index 3346cc3ba..c18382b23 100644 --- a/packages/render/src/helpers.ts +++ b/packages/render/src/helpers.ts @@ -2,6 +2,7 @@ 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( @@ -71,3 +72,37 @@ export function isPartialFrame( 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/identity/farcaster/use-farcaster-identity.tsx b/packages/render/src/identity/farcaster/use-farcaster-identity.tsx index a3bcb0226..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,6 +415,7 @@ export function useFarcasterIdentity({ visibilityDetector, setState, enableIdentityPolling, + onLogInRef, ]); return useMemo( @@ -428,6 +426,7 @@ export function useFarcasterIdentity({ farcasterUser?.status === "approved" || farcasterUser?.status === "impersonating", signFrameAction, + signComposerAction, isLoadingSigner: isLoading, impersonateUser, onSignerlessFramePress, 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 1a96b68b9..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; @@ -534,6 +529,7 @@ export function useFarcasterMultiIdentity({ farcasterUser?.status === "approved" || farcasterUser?.status === "impersonating", signFrameAction, + signComposerAction, isLoadingSigner: isLoading, impersonateUser, onSignerlessFramePress, 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/POST.tsx b/packages/render/src/next/POST.tsx index c0d61e9f7..e9f216bb0 100644 --- a/packages/render/src/next/POST.tsx +++ b/packages/render/src/next/POST.tsx @@ -7,9 +7,48 @@ 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 }; @@ -23,15 +62,6 @@ export type POSTResponse = | POSTResponseRedirect | JsonObject; -function isJsonErrorObject(data: JsonValue): data is { message: string } { - return ( - typeof data === "object" && - data !== null && - "message" in data && - typeof data.message === "string" - ); -} - /** Proxies frame actions to avoid CORS issues and preserve user IP privacy */ export async function POST(req: Request | NextRequest): Promise { try { @@ -78,9 +108,11 @@ export async function POST(req: Request | NextRequest): Promise { ); } - if (isJsonErrorObject(jsonError)) { + const result = errorResponseParser.safeParse(jsonError); + + if (result.success) { return Response.json( - { message: jsonError.message } satisfies POSTResponseError, + { message: result.data.message } satisfies POSTResponseError, { status: response.status } ); } @@ -136,9 +168,11 @@ export async function POST(req: Request | NextRequest): Promise { ); } - if (isJsonErrorObject(jsonError)) { + const result = errorResponseParser.safeParse(jsonError); + + if (result.success) { return Response.json( - { message: jsonError.message } satisfies POSTResponseError, + { message: result.data.message } satisfies POSTResponseError, { status: response.status } ); } @@ -178,6 +212,32 @@ export async function POST(req: Request | NextRequest): Promise { 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) { diff --git a/packages/render/src/unstable-types.ts b/packages/render/src/unstable-types.ts index cc0db711d..b6282cc5d 100644 --- a/packages/render/src/unstable-types.ts +++ b/packages/render/src/unstable-types.ts @@ -11,7 +11,10 @@ import type { ParseResultWithFrameworkDetails, } from "frames.js/frame-parsers"; import type { Dispatch } from "react"; -import type { ErrorMessageResponse } from "frames.js/types"; +import type { + ComposerActionState, + ErrorMessageResponse, +} from "frames.js/types"; import type { ButtonPressFunction, FrameContext, @@ -641,3 +644,32 @@ export type FrameState< 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/use-composer-action.ts b/packages/render/src/use-composer-action.ts new file mode 100644 index 000000000..2443cdadb --- /dev/null +++ b/packages/render/src/use-composer-action.ts @@ -0,0 +1,703 @@ +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"; + +export type { MiniAppMessage, MiniAppResponse }; + +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 ResolveAddressFunction = () => Promise<`0x${string}` | null>; + +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; + } +}