Skip to content

Commit

Permalink
feat(extension): add contract to showUserPrompt
Browse files Browse the repository at this point in the history
  • Loading branch information
mrcnk committed Nov 9, 2024
1 parent 77d1e00 commit ab88eb0
Show file tree
Hide file tree
Showing 7 changed files with 92 additions and 38 deletions.
24 changes: 19 additions & 5 deletions apps/extension/src/sandbox/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,25 @@
import { Add } from "@palladco/contracts"
import { match } from "ts-pattern"
import { z } from "zod"

const EventTypeSchema = z.enum(["run"])
const ContractTypeSchema = z.enum(["add"])

window.addEventListener("message", async (event) => {
return match(event.data.type)
.with("compile", async () => {
await Add.compile()
window.parent.postMessage({ type: "compiled" }, "*")
// Can also read: payload, form
console.log(event.data)
console.log(event.data.userInput)
const type = EventTypeSchema.parse(event.data.type)
const contract = ContractTypeSchema.parse(event.data.contract)
return match(type)
.with("run", async () => {
return match(contract).with("add", async () => {
await Add.compile()
window.parent.postMessage(
{ type: "compiled", result: "test", userInput: event.data.userInput },
"*",
)
})
})
.run()
.exhaustive()
})
Binary file modified bun.lockb
Binary file not shown.
2 changes: 1 addition & 1 deletion packages/features/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
"webext-bridge": "6.0.1",
"webextension-polyfill": "0.12.0",
"xss": "1.0.15",
"yaml": "2.5.0",
"yaml": "2.6.0",
"zustand": "4.5.4"
},
"devDependencies": {
Expand Down
75 changes: 67 additions & 8 deletions packages/features/src/web-connector/routes/web-connector.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { Json } from "@mina-js/utils"
import { useEffect, useState } from "react"
import type { SubmitHandler } from "react-hook-form"
import { MemoryRouter } from "react-router-dom"
Expand All @@ -14,36 +15,78 @@ const sanitizePayload = async (payload: string) => {
return xss(yamlPayload)
}

const sendSandboxMessage = (payload: Json) => {
const sandbox = document.querySelector(
"#o1sandbox",
) as HTMLIFrameElement | null
if (!sandbox) return
return sandbox.contentWindow?.postMessage(payload, "*")
}

type ActionRequest = {
title: string
submitButtonLabel?: string
rejectButtonLabel?: string
payload: string
inputType: "text" | "password" | "confirmation"
loading: boolean
contract: string | undefined
emitConnected: boolean
}

export const WebConnectorRoute = () => {
const [loading, setLoading] = useState(true)
const [request, setRequest] = useState<ActionRequest>({
title: "",
payload: "",
inputType: "confirmation",
loading: true,
contract: undefined,
emitConnected: false,
})
const onSubmit: SubmitHandler<UserInputForm> = async ({ userInput }) => {
const startSubmitting: SubmitHandler<UserInputForm> = async ({
userInput,
}) => {
if (!request.contract) return onSubmit({ userInput })
setLoading(true)
try {
return sendSandboxMessage({
type: "run",
contract: request.contract,
payload: request.payload,
userInput,
})
} finally {
setLoading(false)
}
}
const onSubmit: SubmitHandler<
UserInputForm & { contractResult?: Json }
> = async ({ userInput, contractResult }) => {
const { id } = await windows.getCurrent()
await runtime.sendMessage({
userInput,
contractResult,
windowId: id,
})
window.close()
}
const confirm = async () => {
const startConfirming = async () => {
if (!request.contract) return confirm({})
setLoading(true)
try {
return sendSandboxMessage({
type: "run",
contract: request.contract,
payload: request.payload,
})
} finally {
setLoading(false)
}
}
const confirm = async ({ contractResult }: { contractResult?: Json }) => {
const { id } = await windows.getCurrent()
await runtime.sendMessage({
userConfirmed: true,
contractResult,
windowId: id,
})
if (request.emitConnected) {
Expand All @@ -67,6 +110,21 @@ export const WebConnectorRoute = () => {
})
window.close()
}
const eventListener = (event: MessageEvent) => {
if (request.inputType === "confirmation")
return confirm({ contractResult: event.data.result })
return onSubmit({
userInput: event.data.userInput,
contractResult: event.data.result,
})
}
// biome-ignore lint/correctness/useExhaustiveDependencies: wontdo
useEffect(() => {
window.addEventListener("message", eventListener)
return () => {
window.removeEventListener("message", eventListener)
}
}, [])
useEffect(() => {
runtime.onMessage.addListener(async (message) => {
if (message.type === "action_request") {
Expand All @@ -75,26 +133,27 @@ export const WebConnectorRoute = () => {
submitButtonLabel: message.params.submitButtonLabel,
rejectButtonLabel: message.params.rejectButtonLabel,
payload: await sanitizePayload(message.params.payload),
contract: message.params.contract,
inputType: message.params.inputType,
loading: false,
emitConnected: message.params.emitConnected,
})
setLoading(false)
}
})
}, [])
return (
<MemoryRouter>
<WebConnectorView
inputType={request.inputType}
onConfirm={confirm}
onConfirm={startConfirming}
onDecline={decline}
rejectButtonLabel={request.rejectButtonLabel}
onReject={reject}
submitButtonLabel={request.submitButtonLabel}
onSubmit={onSubmit}
onSubmit={startSubmitting}
title={request.title}
payload={request.payload}
loading={request.loading}
loading={loading}
/>
</MemoryRouter>
)
Expand Down
24 changes: 0 additions & 24 deletions packages/features/src/web-connector/views/web-connector.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { AppLayout } from "@/components/app-layout"
import { MenuBar } from "@/components/menu-bar"
import { Skeleton } from "@/components/skeleton"
import { useEffect } from "react"
import type { SubmitHandler } from "react-hook-form"
import { ConfirmationForm } from "../components/confirmation-form"
import { InputForm } from "../components/input-form"
Expand All @@ -20,10 +19,6 @@ type WebConnectorViewProps = {
loading: boolean
}

const eventListener = (event: MessageEvent) => {
console.log(">>>P_EVENT", event.data)
}

export const WebConnectorView = ({
title,
payload,
Expand All @@ -40,29 +35,10 @@ export const WebConnectorView = ({
onReject()
onDecline()
}
const compileAdd = async () => {
const sandbox = document.querySelector(
"#o1sandbox",
) as HTMLIFrameElement | null
if (!sandbox) return
sandbox.contentWindow?.postMessage(
{ type: "compile", payload: payload },
"*",
)
}
useEffect(() => {
window.addEventListener("message", eventListener)
return () => {
window.removeEventListener("message", eventListener)
}
}, [])
return (
<div className="flex flex-1 justify-center items-center bg-secondary">
<div className="flex max-w-[480px] max-h-[772px] h-full flex-1 bg-neutral rounded-xl">
<AppLayout>
<button type="button" onClick={compileAdd}>
Compile
</button>
<MenuBar variant="card" onCloseClicked={onClose} />
<div className="flex flex-1 flex-col px-8 pb-8">
<div className="flex flex-col flex-1 gap-4">
Expand Down
2 changes: 2 additions & 0 deletions packages/web-provider/src/mina-network/mina-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,8 @@ export const createMinaProvider = async (): Promise<
async (signatureRequest) => {
const passphrase = await showUserPrompt<string>({
inputType: "password",
// TODO: Testing only
contract: "add",
metadata: {
title: "Signature request",
payload: JSON.stringify(signatureRequest.params),
Expand Down
3 changes: 3 additions & 0 deletions packages/web-provider/src/utils/prompts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@ type Metadata = {
export const showUserPrompt = async <T extends boolean | string = boolean>({
inputType,
metadata,
contract,
emitConnected = false,
}: {
inputType: InputType
metadata: Metadata
contract?: string
emitConnected?: boolean
}): Promise<T> => {
return new Promise<T>((resolve, reject) => {
Expand Down Expand Up @@ -53,6 +55,7 @@ export const showUserPrompt = async <T extends boolean | string = boolean>({
rejectButtonLabel: metadata.rejectButtonLabel,
payload: metadata.payload ?? "{}",
inputType,
contract,
emitConnected,
},
})
Expand Down

0 comments on commit ab88eb0

Please sign in to comment.