Skip to content
Draft
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
@@ -1,6 +1,7 @@
import { useAtomValue } from "jotai"
import { RequestDisabled } from "#src/components/requests/common/RequestDisabled"
import { chainsAtom, currentChainAtom } from "#src/state/chains"
import { currentChainAtom } from "#src/state/chains"
import { getChains } from "#src/state/chains/index"
import { Layout } from "./common/Layout"
import type { RequestConfirmationProps } from "./props"

Expand All @@ -10,7 +11,7 @@ export const WalletSwitchEthereumChain = ({
reject,
accept,
}: RequestConfirmationProps<"wallet_switchEthereumChain">) => {
const chains = useAtomValue(chainsAtom)
const chains = getChains()
const currentChain = useAtomValue(currentChainAtom)
const chain = chains[params[0].chainId]
const headline = "Switch chain"
Expand Down
2 changes: 1 addition & 1 deletion apps/iframe/src/connections/GoogleConnector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { type AuthProvider, GoogleAuthProvider } from "firebase/auth"
import type { EIP1193Provider } from "viem"
import { setUserWithProvider } from "#src/actions/setUserWithProvider"
import { StorageKey, storage } from "#src/services/storage"
import { getChains } from "#src/state/chains"
import { getChains } from "#src/state/chains/index"
import { grantPermissions } from "#src/state/permissions"
import { getUser } from "#src/state/user"
import { getAppURL } from "#src/utils/appURL"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import { requiresApproval } from "@happy.tech/wallet-common"
import { PermissionName } from "#src/constants/permissions"
import { checkAndChecksumAddress, hasNonZeroValue } from "#src/requests/utils/checks"
import { type SessionKeysByHappyUser, StorageKey, storage } from "#src/services/storage"
import { getChains, getCurrentChain } from "#src/state/chains"
import { getChains } from "#src/state/chains/index"
import { getCurrentChain } from "#src/state/chains"
import { hasPermissions } from "#src/state/permissions"
import { getUser } from "#src/state/user"
import type { AppURL } from "#src/utils/appURL"
Expand Down
5 changes: 3 additions & 2 deletions apps/iframe/src/requests/handlers/approved.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import { checkAndChecksumAddress, checkedTx, checkedWatchedAsset } from "#src/re
import { sendToWalletClient } from "#src/requests/utils/sendToClient"
import { installNewSessionKey } from "#src/requests/utils/sessionKeys"
import { eoaSigner } from "#src/requests/utils/signers"
import { getChains, getCurrentChain, setChains, setCurrentChain } from "#src/state/chains"
import { getChains, setChain } from "#src/state/chains/index"
import { getCurrentChain, setCurrentChain } from "#src/state/chains"
import { loadAbiForUser } from "#src/state/loadedAbis"
import { grantPermissions } from "#src/state/permissions"
import { checkUser, getUser } from "#src/state/user"
Expand Down Expand Up @@ -54,7 +55,7 @@ export async function dispatchApprovedRequest(request: PopupMsgs[Msgs.PopupAppro

const response = await sendToWalletClient(request.payload)
// Only add chain if the request is successful.
setChains((prev) => ({ ...prev, [params.chainId]: params }))
setChain(params)
return response
}

Expand Down
5 changes: 3 additions & 2 deletions apps/iframe/src/requests/handlers/injected.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ import {
getTransactionReceipt,
} from "#src/requests/utils/shared"
import { eoaSigner, sessionKeySigner } from "#src/requests/utils/signers"
import { getChains, setChains, setCurrentChain } from "#src/state/chains"
import { setCurrentChain } from "#src/state/chains"
import { getChains, setChain } from "#src/state/chains/index"
import { revokedSessionKeys } from "#src/state/interfaceState"
import { loadAbiForUser } from "#src/state/loadedAbis"
import { getPermissions, grantPermissions, revokePermissions } from "#src/state/permissions"
Expand Down Expand Up @@ -193,7 +194,7 @@ export async function dispatchInjectedRequest(request: ProviderMsgsFromApp[Msgs.

const resp = await sendToWalletClient(request.payload)

setChains((prev) => ({ ...prev, [params.chainId]: params }))
setChain(params)

// Some wallets (Metamask, Rabby, ...) automatically switch to the newly-added chain.
// Normalize behavior by always switching.
Expand Down
32 changes: 1 addition & 31 deletions apps/iframe/src/state/chains.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,11 @@
import { accessorsFromAtom } from "@happy.tech/common"
import { chainDefinitions as defaultChains } from "@happy.tech/wallet-common"
import type { ChainParameters } from "@happy.tech/wallet-common"
import { type WritableAtom, atom } from "jotai"
import { atomWithStorage } from "jotai/utils"
import type { AddEthereumChainParameter } from "viem"
import { StorageKey } from "../services/storage"
import { getChainFromSearchParams } from "./chains/index"

// NOTE: If `HAPPY_RPC_OVERRIDE` is set, the RPC URL of all default chains will be set to that RPC server.

export function getChainFromSearchParams(): ChainParameters {
const chainId = new URLSearchParams(window.location.search).get("chainId")
const chainKey = chainId && `0x${BigInt(chainId).toString(16)}`
const chains = getChains()
return chainKey && chainKey in chains //
? chains[chainKey]
: defaultChains.defaultChain
}

function getDefaultChainsRecord() {
return Object.fromEntries(Object.entries(defaultChains).map(([_, chain]) => [chain.chainId, chain]))
}

/**
* This atom maps chain IDs to their respective chain parameters. Initialized with the officially
* supported chains.
*/
export const chainsAtom = atomWithStorage<
Record<string, AddEthereumChainParameter> //
>(StorageKey.Chains, getDefaultChainsRecord(), undefined, { getOnInit: true })

export const {
/** See {@link chainsAtom} */
getValue: getChains,
/** See {@link chainsAtom} */
setValue: setChains,
} = accessorsFromAtom(chainsAtom)

/**
* This atom stores the current configuration of the chain that the iframe is connected to.
*
Expand Down
20 changes: 20 additions & 0 deletions apps/iframe/src/state/chains/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { chainDefinitions as defaultChains, type ChainParameters } from "@happy.tech/wallet-common"
import { chainsLegend } from "./observable"


export function getChainFromSearchParams(): ChainParameters {
const chainId = new URLSearchParams(window.location.search).get("chainId")
const chainKey = chainId && `0x${BigInt(chainId).toString(16)}`
const chains = chainsLegend.get()
return chainKey && chainKey in chains //
? chains[chainKey]
: defaultChains.defaultChain
}

export function getChains() {
return chainsLegend.get()
}

export function setChain(chain: ChainParameters) {
chainsLegend[chain.chainId].set(chain)
}
108 changes: 108 additions & 0 deletions apps/iframe/src/state/chains/observable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import { observable } from "@legendapp/state"
import { ObservablePersistLocalStorage } from "@legendapp/state/persist-plugins/local-storage"
import { chainDefinitions as defaultChains } from "@happy.tech/wallet-common"
import { syncedCrud } from "@legendapp/state/sync-plugins/crud"
import { deploymentVar } from "#src/env.ts"
import { getUser } from "../user"
import type { AddEthereumChainParameter } from "viem"

const SYNC_SERVICE_URL = deploymentVar("VITE_SYNC_SERVICE_URL")

function getDefaultChainsRecord() {
return Object.fromEntries(Object.entries(defaultChains).map(([_, chain]) => [chain.chainId, chain]))
}

export const chainsLegend = observable(
syncedCrud({
list: async ({ lastSync }) => {
const user = getUser()
if (!user) return []

const response = await fetch(
`${SYNC_SERVICE_URL}/api/v1/settings/list?type=Chain&user=${user.address}${lastSync ? `&lastUpdated=${lastSync}` : ""}`,
)
const data = await response.json()

return data.data as AddEthereumChainParameter[]
},
create: async (data: AddEthereumChainParameter) => {
const user = getUser()
if (!user) return

const response = await fetch(`${SYNC_SERVICE_URL}/api/v1/settings/create`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
...data,
id: `${user.address}-${data.chainId}`,
type: "Chain",
user: user.address,
createdAt: Date.now(),
updatedAt: Date.now(),
deleted: false,
}),
})
await response.json()
},
update: async (data: AddEthereumChainParameter) => {
const user = getUser()
if (!user) return

const response = await fetch(`${SYNC_SERVICE_URL}/api/v1/settings/update`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
...data,
id: `${user.address}-${data.chainId}`,
type: "Chain",
user: user.address,
createdAt: Date.now(),
updatedAt: Date.now(),
deleted: false,
}),
})
await response.json()
},
subscribe: ({ refresh }) => {
const user = getUser()
if (!user) return
const eventSource = new EventSource(`${SYNC_SERVICE_URL}/api/v1/settings/subscribe?user=${user.address}`)
eventSource.addEventListener("config.changed", (event) => {
const data = JSON.parse(event.data)
console.log("Received update", data)
refresh()
})

return () => eventSource.close()
},
delete: async ({ chainId }) => {
const user = getUser()
if (!user) return

const response = await fetch(`${SYNC_SERVICE_URL}/api/v1/settings/delete`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ id: `${user.address}-${chainId}` }),
})
await response.json()
},
persist: {
plugin: ObservablePersistLocalStorage,
name: "chains-legend",
retrySync: true, // Retry sync after reload
},
initial: getDefaultChainsRecord(),
fieldCreatedAt: "createdAt",
fieldUpdatedAt: "updatedAt",
fieldDeleted: "deleted",
changesSince: "last-sync",
updatePartial: true,
}),
)

22 changes: 22 additions & 0 deletions apps/sync-service/src/db/migrations/Migration20250626143000.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import type { Kysely } from "kysely"
import type { Database } from "../types"

export async function up(db: Kysely<Database>) {
await db.schema
.createTable("chains")
.addColumn("user", "text", (col) => col.notNull())
.addColumn("chainId", "text", (col) => col.notNull())
.addColumn("chainName", "text", (col) => col.notNull())
.addColumn("rpcUrls", "text", (col) => col.notNull())
.addColumn("nativeCurrency", "json")
.addColumn("blockExplorerUrls", "json")
.addColumn("iconUrls", "json")
.addColumn("opStack", "boolean")
.addColumn("id", "text", (col) => col.notNull().primaryKey())
.addColumn("updatedAt", "integer", (col) => col.notNull())
.addColumn("createdAt", "integer", (col) => col.notNull())
.addColumn("deleted", "boolean", (col) => col.notNull())
.execute()
}

export const migration20250626143000 = { up }
2 changes: 2 additions & 0 deletions apps/sync-service/src/db/migrations/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { migration20250515123000 } from "./Migration20250515123000"
import { migration20250623143000 } from "./Migration20250623143000"
import { migration20250626143000 } from "./Migration20250626143000"

export const migrations = {
"20250515123000": migration20250515123000,
"20250623143000": migration20250623143000,
"20250626143000": migration20250626143000,
}
20 changes: 20 additions & 0 deletions apps/sync-service/src/db/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,27 @@ export type WatchAssetRow = {
deleted: ColumnType<number, boolean, boolean>
}

export type ChainRow = {
user: Hex
chainId: string
chainName: string
rpcUrls: ColumnType<string[], string, string>;
nativeCurrency?: ColumnType<{
symbol: string;
decimals: number;
name: string;
}, string, string>
blockExplorerUrls?: ColumnType<string[], string, string> | undefined;
iconUrls?: ColumnType<string[], string, string> | undefined;
opStack?: ColumnType<number, boolean, boolean>
id: string
updatedAt: number
createdAt: number
deleted: ColumnType<number, boolean, boolean>
}

export interface Database {
walletPermissions: WalletPermissionRow
watchedAssets: WatchAssetRow
chains: ChainRow
}
42 changes: 42 additions & 0 deletions apps/sync-service/src/dtos.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,45 @@ export const watchAssetUpdate = watchAsset.partial().extend({
})

export type WatchAssetUpdate = z.infer<typeof watchAssetUpdate>

export const chain = z.object({
chainId: z.string().openapi({ example: "0xd8" }),
chainName: z.string().openapi({ example: "HappyChain Sepolia" }),
nativeCurrency: z.object({
name: z.string().openapi({ example: "HappyChain" }),
symbol: z.string().openapi({ example: "HAPPY" }),
decimals: z.number().openapi({ example: 18 })
}).optional(),
rpcUrls: z.array(z.string()),
blockExplorerUrls: z.array(z.string()).optional().openapi({ example: ["https://explorer.testnet.happy.tech"] }),
iconUrls: z.array(z.string()).optional(),
opStack: z.boolean().optional().openapi({ example: true }),
type: z.literal("Chain").openapi({
example: "Chain",
type: "string",
}),
user: z.string().refine(isAddress).transform(checksum).openapi({
example: "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266",
type: "string",
}),
id: z.string().openapi({ example: "78b7d642-e851-4f0f-9cd6-a47c6c2a572a" }),
updatedAt: z.number().openapi({ example: 1715702400 }),
createdAt: z.number().openapi({ example: 1715702400 }),
deleted: z.boolean().openapi({ example: false }),
})

export type Chain = z.infer<typeof chain>

export const chainUpdate = chain.partial().extend({
type: z.literal("Chain").openapi({
example: "Chain",
type: "string",
}),
user: z.string().refine(isAddress).transform(checksum).openapi({
example: "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266",
type: "string",
}),
id: z.string().openapi({ example: "78b7d642-e851-4f0f-9cd6-a47c6c2a572a" }),
})

export type ChainUpdate = z.infer<typeof chainUpdate>
3 changes: 3 additions & 0 deletions apps/sync-service/src/handlers/createConfig/createConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@ import { savePermission } from "../../repositories/permissionsRepository"
import { saveWatchedAsset } from "../../repositories/watchAssetsRepository"
import { notifyUpdates } from "../../services/notifyUpdates"
import type { CreateConfigInput } from "./types"
import { saveChain } from "../../repositories/chainRepository"

export async function createConfig(input: CreateConfigInput): Promise<Result<undefined, Error>> {
if (input.type === "WalletPermissions") {
await savePermission(input)
} else if (input.type === "ERC20") {
await saveWatchedAsset(input)
} else if (input.type === "Chain") {
await saveChain(input)
}

notifyUpdates({
Expand Down
6 changes: 3 additions & 3 deletions apps/sync-service/src/handlers/createConfig/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import { describeRoute } from "hono-openapi"
import { resolver } from "hono-openapi/zod"
import { validator as zv } from "hono-openapi/zod"
import { z } from "zod"
import { walletPermission, watchAsset } from "../../dtos"
import { chain, walletPermission, watchAsset } from "../../dtos"
import { isProduction } from "../../utils/isProduction"

export const inputSchema: z.ZodDiscriminatedUnion<"type", [typeof walletPermission, typeof watchAsset]> =
z.discriminatedUnion("type", [walletPermission, watchAsset])
export const inputSchema: z.ZodDiscriminatedUnion<"type", [typeof walletPermission, typeof watchAsset, typeof chain]> =
z.discriminatedUnion("type", [walletPermission, watchAsset, chain])

export const outputSchema = z.object({
success: z.boolean(),
Expand Down
Loading