Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(pilot-app, extension): better optimistic updates and connection handling #622

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Labeled, PrimaryButton } from '@zodiac/ui'

export const ConnectWalletFallback = () => (
<Labeled label="Pilot Account">
<PrimaryButton fluid disabled>
Loading wallet support...
</PrimaryButton>
</Labeled>
)
16 changes: 12 additions & 4 deletions deployables/app/app/components/wallet/WalletProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { getDefaultConfig } from 'connectkit'
import { useEffect, useState, type PropsWithChildren } from 'react'
import {
useEffect,
useState,
type PropsWithChildren,
type ReactNode,
} from 'react'
import { createConfig, injected, WagmiProvider, type Config } from 'wagmi'
import {
arbitrum,
Expand All @@ -19,13 +24,16 @@ const queryClient = new QueryClient()
const WALLETCONNECT_PROJECT_ID = '0f8a5e2cf60430a26274b421418e8a27'
const isServer = typeof document === 'undefined'

export type WalletProviderProps = PropsWithChildren
export type WalletProviderProps = PropsWithChildren<{ fallback?: ReactNode }>

export const WalletProvider = ({ children }: WalletProviderProps) => {
export const WalletProvider = ({
children,
fallback = null,
}: WalletProviderProps) => {
const config = useConfig()

if (config == null) {
return null
return fallback
}

return (
Expand Down
2 changes: 2 additions & 0 deletions deployables/app/app/components/wallet/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,5 @@ export const WalletProvider: ComponentType<WalletProviderProps> = lazy(
return { default: WalletProvider }
},
)

export { ConnectWalletFallback } from './ConnectWalletFallback'
1 change: 1 addition & 0 deletions deployables/app/app/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {

export default [
index('routes/index.tsx'),
route('/connect', 'routes/connect.tsx'),
route('/new-route', 'routes/new-route.ts'),
route('/edit-route/:data', 'routes/edit-route.$data.tsx'),
...prefix('/:account/:chainId', [
Expand Down
14 changes: 14 additions & 0 deletions deployables/app/app/routes/connect.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { PilotType, ZodiacOsPlain } from '@zodiac/ui'

const Connect = () => {
return (
<div className="flex h-full items-center justify-center">
<div className="flex items-center gap-4">
<ZodiacOsPlain className="h-6 lg:h-8" />
<PilotType className="h-8 lg:h-10 dark:invert" />
</div>
</div>
)
}

export default Connect
17 changes: 11 additions & 6 deletions deployables/app/app/routes/edit-route.$data.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,12 @@
randomPrefixedAddress,
} from '@zodiac/test-utils'
import { formatPrefixedAddress, type ChainId } from 'ser-kit'
import { describe, expect, it, vi } from 'vitest'
import { beforeEach, describe, expect, it, vi } from 'vitest'

const { mockGetSafesByOwner } = vi.hoisted(() => ({
mockGetSafesByOwner:
vi.fn<ReturnType<typeof initSafeApiKit>['getSafesByOwner']>(),
mockGetSafesByOwner: vi
.fn<ReturnType<typeof initSafeApiKit>['getSafesByOwner']>()
.mockResolvedValue({ safes: [] }),
}))

vi.mock('@zodiac/safe', async (importOriginal) => {
Expand Down Expand Up @@ -79,6 +80,10 @@
const mockDryRun = vi.mocked(dryRun)

describe('Edit route', () => {
beforeEach(() => {
mockFetchZodiacModules.mockResolvedValue([])
})

describe('Label', () => {
it('shows the name of a route', async () => {
const route = createMockExecutionRoute({ label: 'Test route' })
Expand Down Expand Up @@ -333,7 +338,7 @@
await render(`/edit-route/${btoa(JSON.stringify(route))}`)

await userEvent.click(
screen.getByRole('combobox', { name: 'Zodiac Mod' }),
await screen.findByRole('combobox', { name: 'Zodiac Mod' }),
)
await userEvent.click(screen.getByRole('option', { name: 'Roles v2' }))

Expand Down Expand Up @@ -403,7 +408,7 @@
await render(`/edit-route/${btoa(JSON.stringify(route))}`)

await userEvent.click(
screen.getByRole('combobox', { name: 'Zodiac Mod' }),
await screen.findByRole('combobox', { name: 'Zodiac Mod' }),
)
await userEvent.click(screen.getByRole('option', { name: 'Roles v1' }))

Expand Down Expand Up @@ -468,7 +473,7 @@

await userEvent.click(screen.getByRole('button', { name: 'Save' }))

expect(mockPostMessage).toHaveBeenCalledWith(

Check failure on line 476 in deployables/app/app/routes/edit-route.$data.spec.ts

View workflow job for this annotation

GitHub Actions / pilot-app

app/routes/edit-route.$data.spec.ts > Edit route > Role > V1 > Config > is possible to update the role ID

AssertionError: expected "bound " to be called with arguments: [ { type: 'SAVE_ROUTE', …(1) }, …(1) ] Received: 1st bound call: Array [ Object { "data": Object { "avatar": "eth:0x13E39B38c34C2ae8d8EF7fD53dD197CeEf148dAD", "id": "8b244f0e-6e68-4fa5-b35d-2aedcca8322c", - "initiator": undefined, "label": "", "waypoints": Array [ Object { "account": Object { "address": "0x0000000000000000000000000000000000000000", "prefixedAddress": "eth:0x0000000000000000000000000000000000000000", "type": "EOA", }, }, Object { "account": Object { "address": "0xd51f4d66dd1a8c125296cae1a80a4441ec319678", "chain": 1, "multisend": Array [], "prefixedAddress": "eth:0xd51F4d66DD1a8C125296CAe1A80A4441EC319678", "type": "ROLES", "version": 1, }, "connection": Object { "from": "eth:0x6D2C8e9203a37f485ce66F7Ce805350490A91424", "roles": Array [ - "0x75277242605090d7055cba13d443238a0bb5e776", + "", ], "type": "IS_MEMBER", }, }, ], }, "type": "SAVE_ROUTE", }, - Anything, + "*", ] Number of calls: 1 ❯ app/routes/edit-route.$data.spec.ts:476:35
{
type: CompanionAppMessageType.SAVE_ROUTE,
data: updateRoleId(route, roleId),
Expand Down Expand Up @@ -520,7 +525,7 @@
await render(`/edit-route/${btoa(JSON.stringify(route))}`)

await userEvent.click(
screen.getByRole('combobox', { name: 'Zodiac Mod' }),
await screen.findByRole('combobox', { name: 'Zodiac Mod' }),
)
await userEvent.click(screen.getByRole('option', { name: 'Roles v2' }))

Expand Down Expand Up @@ -586,7 +591,7 @@

await userEvent.click(screen.getByRole('button', { name: 'Save' }))

expect(mockPostMessage).toHaveBeenCalledWith(

Check failure on line 594 in deployables/app/app/routes/edit-route.$data.spec.ts

View workflow job for this annotation

GitHub Actions / pilot-app

app/routes/edit-route.$data.spec.ts > Edit route > Role > V2 > Config > is possible to update the role key

AssertionError: expected "bound " to be called with arguments: [ { type: 'SAVE_ROUTE', …(1) }, …(1) ] Received: 1st bound call: Array [ Object { "data": Object { "avatar": "eth:0xE729E3C0F842d138eC8aCC3631bf6eCFAe5d9c24", "id": "9678380f-bfc2-4295-bd18-9baab647b7f5", - "initiator": undefined, "label": "", "waypoints": Array [ Object { "account": Object { "address": "0x0000000000000000000000000000000000000000", "prefixedAddress": "eth:0x0000000000000000000000000000000000000000", "type": "EOA", }, }, Object { "account": Object { "address": "0xc95342b9d9db5ad86a48ea6901bb3d8539eaf562", "chain": 1, "multisend": Array [], "prefixedAddress": "eth:0xC95342B9D9dB5AD86a48EA6901BB3d8539eAF562", "type": "ROLES", "version": 2, }, "connection": Object { "from": "eth:0x544FcF30e49DE871dC72BC803D42E04FcCE350C8", "roles": Array [ - "0x4d414e4147455200000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", ], "type": "IS_MEMBER", }, }, ], }, "type": "SAVE_ROUTE", }, - Anything, + "*", ] Number of calls: 1 ❯ app/routes/edit-route.$data.spec.ts:594:35
{
type: CompanionAppMessageType.SAVE_ROUTE,
data: updateRoleId(route, encodeRoleKey('MANAGER')),
Expand Down
117 changes: 79 additions & 38 deletions deployables/app/app/routes/edit-route.$data.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ import {
AvatarInput,
ChainSelect,
ConnectWallet,
ConnectWalletFallback,
WalletProvider,
ZodiacMod,
} from '@/components'
import { dryRun, editRoute, jsonRpcProvider, parseRouteData } from '@/utils'
import { invariant } from '@epic-web/invariant'
import { invariant, invariantResponse } from '@epic-web/invariant'
import { Chain, getChainId, verifyChainId, ZERO_ADDRESS } from '@zodiac/chains'
import {
formData,
Expand Down Expand Up @@ -43,12 +44,11 @@ import {
PilotType,
PrimaryButton,
SecondaryButton,
Section,
TextInput,
ZodiacOsPlain,
} from '@zodiac/ui'
import { lazy, Suspense, useState } from 'react'
import { Form, useNavigation, useSubmit } from 'react-router'
import { lazy, Suspense, useEffect, useState } from 'react'
import { Form, useLoaderData, useNavigation, useSubmit } from 'react-router'
import type { Route } from './+types/edit-route.$data'
import { Intent } from './intents'

Expand Down Expand Up @@ -80,6 +80,13 @@ export const action = async ({ request, params }: Route.ActionArgs) => {
const route = parseRouteData(params.data)
const data = await request.formData()

const intent = getString(data, 'intent')

invariantResponse(
intent === Intent.UpdateModule,
`Invalid intent "${intent}" received in server action`,
)

const module = zodiacModuleSchema.parse(JSON.parse(getString(data, 'module')))

const updatedRoute = updateRolesWaypoint(route, {
Expand Down Expand Up @@ -169,21 +176,16 @@ export const clientAction = async ({
}

const EditRoute = ({
loaderData: { chainId, label, avatar, providerType, waypoints },
loaderData: { chainId, label, avatar, waypoints },
actionData,
}: Route.ComponentProps) => {
const submit = useSubmit()

const [optimisticConnection, setOptimisticConnection] = useState({
pilotAddress: getPilotAddress(waypoints),
chainId,
providerType,
})
const optimisticRoute = useOptimisticRoute()

const { state } = useNavigation()

return (
<div className="flex h-full flex-col gap-4">
<div className="flex h-full flex-col gap-8">
<main className="mx-auto flex w-3/4 flex-col gap-4 md:w-1/2 2xl:w-1/4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
Expand All @@ -197,25 +199,13 @@ const EditRoute = ({
<Form method="POST" className="flex flex-col gap-4">
<TextInput label="Label" name="label" defaultValue={label} />

<Suspense
fallback={
<Section title="Pilot Account">
<PrimaryButton disabled>Connect wallet</PrimaryButton>
</Section>
}
>
<WalletProvider>
<Suspense fallback={<ConnectWalletFallback />}>
<WalletProvider fallback={<ConnectWalletFallback />}>
<ConnectWallet
chainId={optimisticConnection.chainId}
pilotAddress={optimisticConnection.pilotAddress}
providerType={optimisticConnection.providerType}
chainId={optimisticRoute.chainId}
pilotAddress={optimisticRoute.pilotAddress}
providerType={optimisticRoute.providerType}
onConnect={({ account, chainId, providerType }) => {
setOptimisticConnection({
pilotAddress: account,
chainId,
providerType,
})

submit(
formData({
intent: Intent.ConnectWallet,
Expand All @@ -227,12 +217,6 @@ const EditRoute = ({
)
}}
onDisconnect={() => {
setOptimisticConnection({
pilotAddress: ZERO_ADDRESS,
chainId: Chain.ETH,
providerType: undefined,
})

submit(formData({ intent: Intent.DisconnectWallet }), {
method: 'POST',
})
Expand Down Expand Up @@ -270,9 +254,15 @@ const EditRoute = ({
avatar={avatar}
waypoints={waypoints}
onSelect={(module) => {
submit(formData({ module: JSON.stringify(module) }), {
method: 'POST',
})
submit(
formData({
intent: Intent.UpdateModule,
module: JSON.stringify(module),
}),
{
method: 'POST',
},
)
}}
/>

Expand Down Expand Up @@ -315,6 +305,57 @@ const EditRoute = ({

export default EditRoute

const useOptimisticRoute = () => {
const { waypoints, chainId, providerType } = useLoaderData<typeof loader>()
const pilotAddress = getPilotAddress(waypoints)

const { formData } = useNavigation()

const [optimisticConnection, setOptimisticConnection] = useState({
pilotAddress,
chainId,
providerType,
})

useEffect(() => {
setOptimisticConnection({ pilotAddress, chainId, providerType })
}, [chainId, pilotAddress, providerType])

useEffect(() => {
if (formData == null) {
return
}

const intent = getOptionalString(formData, 'intent')

if (intent == null) {
return
}

switch (intent) {
case Intent.DisconnectWallet: {
setOptimisticConnection({
pilotAddress: ZERO_ADDRESS,
chainId: Chain.ETH,
providerType: undefined,
})

break
}

case Intent.ConnectWallet: {
setOptimisticConnection({
pilotAddress: getHexString(formData, 'account'),
chainId: verifyChainId(getInt(formData, 'chainId')),
providerType: verifyProviderType(getInt(formData, 'providerType')),
})
}
}
}, [formData])

return optimisticConnection
}

const getPilotAddress = (waypoints?: Waypoints) => {
if (waypoints == null) {
return null
Expand Down
1 change: 1 addition & 0 deletions deployables/app/app/routes/intents.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export enum Intent {
Save = 'Save',
UpdateModule = 'UpdateModule',
UpdateChain = 'UpdateChain',
UpdateAvatar = 'UpdateAvatar',
RemoveAvatar = 'RemoveAvatar',
Expand Down
2 changes: 0 additions & 2 deletions deployables/app/e2e/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,2 @@
export { expect, test } from './fixture'
export { loadExtension } from './loadExtension'
export { defaultMockAccount, mockWeb3 } from './mockWeb3'
export { waitFor } from './waitFor'
1 change: 1 addition & 0 deletions deployables/app/tsconfig.cloudflare.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"include": [
".react-router/types/**/*",
"vitest.setup.ts",
"e2e/**/*",
"app/**/*",
"app/**/.server/**/*",
"app/**/.client/**/*",
Expand Down
6 changes: 1 addition & 5 deletions deployables/extension/manifest-util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@ config()
//
// node manifest-util.js ./public/manifest.json

const getIframeUrl = () => {
return `${getCompanionAppUrl()}/`
}

const updateManifest = (templateFileName, outFileName, version) => {
try {
console.log(chalk.white.bold('Manifest template file:'))
Expand All @@ -25,7 +21,7 @@ const updateManifest = (templateFileName, outFileName, version) => {
const data = fs
.readFileSync(templateFileName)
.toString()
.replaceAll('<COMPANION_APP_URL>', getIframeUrl())
.replaceAll('<COMPANION_APP_URL>', getCompanionAppUrl())

const manifest = JSON.parse(data)
manifest['version'] = version.replace('v', '')
Expand Down
8 changes: 4 additions & 4 deletions deployables/extension/src/connect/contentScripts/dApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@ import {
type ConnectedWalletMessage,
} from '@zodiac/messages'

const companionAppUrl = getCompanionAppUrl()
const connectUrl = `${getCompanionAppUrl()}/connect`

const ensureIframe = () => {
let node: HTMLIFrameElement | null = document.querySelector(
`iframe[src="${companionAppUrl}"]`,
`iframe[src="${connectUrl}"]`,
)

if (!node) {
node = document.createElement('iframe')
node.src = companionAppUrl
node.src = connectUrl
node.style.display = 'none'

const parent = document.body || document.documentElement
Expand All @@ -40,7 +40,7 @@ chrome.runtime.onConnect.addListener((port) => {
'cannot access connect iframe window',
)

iframe.contentWindow.postMessage(message, companionAppUrl)
iframe.contentWindow.postMessage(message, connectUrl)

// wait for response
const handleResponse = (event: MessageEvent<ConnectedWalletMessage>) => {
Expand Down
Loading
Loading