-
+ {value.startsWith("0x") ? (
+
+ ) : (
+
+ )}
{name && (
@@ -42,3 +47,7 @@ export const AccountIdDisplay: FC<{
)
}
+const getPublicKey = (address: string) => {
+ const info = getSs58AddressInfo(address)
+ return info.isValid ? info.publicKey : null
+}
diff --git a/src/components/AccountIdInput.tsx b/src/components/AccountIdInput.tsx
index c6132c8..f17478a 100644
--- a/src/components/AccountIdInput.tsx
+++ b/src/components/AccountIdInput.tsx
@@ -13,10 +13,8 @@ import {
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover"
-import { groupBy } from "@/lib/groupBy"
-import { accounts$ } from "@/state/accounts.state"
-import { getPublicKey } from "@/state/extension-accounts.state"
import { identity$, isVerified } from "@/state/identity.state"
+import { addrToAccount$, getPublicKey } from "@/state/polkahub"
import { cn } from "@/utils/cn"
import {
getSs58AddressInfo,
@@ -29,13 +27,15 @@ import { Check, ChevronsUpDown } from "lucide-react"
import { FC, useState } from "react"
import { filter, map, switchMap, take } from "rxjs"
-const acconutMap$ = accounts$.pipeState(
- map((accounts) => groupBy(accounts, (acc) => acc.accountId)),
+const acconutMap$ = addrToAccount$.pipeState(
map((groups) =>
Object.fromEntries(
Object.entries(groups)
.filter(([accountId]) => !accountId.startsWith("0x"))
- .map(([accountId, [groupRep]]) => [accountId, groupRep]),
+ .map(([accountId, account]) => [
+ toHex(getPublicKey(accountId)),
+ account,
+ ]),
),
),
)
@@ -49,9 +49,9 @@ const hintedAccounts$ = state(
filter((v) => !!v),
take(1),
switchMap((details) =>
- identity$(details.accountId).pipe(
+ identity$(details.address).pipe(
map((identity) => ({
- address: details.accountId,
+ address: details.address,
name: identity?.displayName ?? details.name,
isVerified: isVerified(identity),
})),
@@ -113,7 +113,6 @@ export const AccountIdInput: FC<{
"flex w-64 justify-between overflow-hidden px-2 border border-border bg-input",
className,
)}
- forceSvgSize={false}
>
{value !== null ? (
@@ -193,7 +192,6 @@ const AccountOption: FC<{
value={account + "_" + name}
onSelect={onSelect}
className="flex flex-row items-center gap-2 p-1"
- forceSvgSize={false}
>
= ({
- address,
- size,
-}) => {
- return
-}
diff --git a/src/components/PolkadotIdenticon.tsx b/src/components/PolkadotIdenticon.tsx
deleted file mode 100644
index 3fd8a30..0000000
--- a/src/components/PolkadotIdenticon.tsx
+++ /dev/null
@@ -1,154 +0,0 @@
-// Based from https://github.com/paritytech/oo7/blob/251ba2b7c45503b68eab4320c270b5afa9bccb60/packages/polkadot-identicon/src/index.jsx
-
-import { blake2b } from "@noble/hashes/blake2.js"
-import { FC, SVGAttributes } from "react"
-
-export const PolkadotIdenticon: FC<
- Omit, "viewBox"> & {
- sixPoint?: boolean
- publicKey: Uint8Array | null
- size?: number
- }
-> = ({ sixPoint, publicKey, ...props }) => {
- const svgProps = {
- ...props,
- width: props.size ?? props.width ?? SIZE,
- height: props.size ?? props.height ?? SIZE,
- viewBox: `0 0 ${SIZE} ${SIZE}`,
- }
- if (!publicKey) {
- return (
-
- )
- }
-
- const colors = getColors(publicKey)
- const circles = getPositions(sixPoint)
-
- return (
-
- )
-}
-
-const SIZE = 64
-const CENTER = SIZE / 2
-
-const z = (SIZE / 64) * 5
-type Schema = { freq: number; colors: number[] }
-const schema: Record = {
- target: {
- freq: 1,
- colors: [0, 28, 0, 0, 28, 0, 0, 28, 0, 0, 28, 0, 0, 28, 0, 0, 28, 0, 1],
- },
- cube: {
- freq: 20,
- colors: [0, 1, 3, 2, 4, 3, 0, 1, 3, 2, 4, 3, 0, 1, 3, 2, 4, 3, 5],
- },
- quazar: {
- freq: 16,
- colors: [1, 2, 3, 1, 2, 4, 5, 5, 4, 1, 2, 3, 1, 2, 4, 5, 5, 4, 0],
- },
- flower: {
- freq: 32,
- colors: [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 3],
- },
- cyclic: {
- freq: 32,
- colors: [0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6],
- },
- vmirror: {
- freq: 128,
- colors: [0, 1, 2, 3, 4, 5, 3, 4, 2, 0, 1, 6, 7, 8, 9, 7, 8, 6, 10],
- },
- hmirror: {
- freq: 128,
- colors: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 8, 6, 7, 5, 3, 4, 2, 11],
- },
-}
-const totalFreq = Object.keys(schema)
- .map((k) => schema[k].freq)
- .reduce((a, b) => a + b)
-
-const findScheme = (d: number) => {
- let cum = 0
- for (const scheme of Object.values(schema)) {
- cum += scheme.freq
- if (d < cum) {
- return scheme
- }
- }
- throw "Unreachable"
-}
-const blake2512 = (input: Uint8Array) => blake2b(input, { dkLen: 64 })
-const zero = blake2512(
- new Uint8Array([
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0,
- ]),
-)
-
-const getColors = (publicKey: Uint8Array) => {
- const id = Array.from(blake2512(publicKey)).map(
- (x, i) => (x + 256 - zero[i]) % 256,
- )
-
- const sat = (Math.floor((id[29] * 70) / 256 + 26) % 80) + 30
- const d = Math.floor((id[30] + id[31] * 256) % totalFreq)
- const scheme = findScheme(d)
- const palette = Array.from(id).map((x, i) => {
- const b = (x + (i % 28) * 58) % 256
- if (b == 0) {
- return "#444"
- }
- if (b == 255) {
- return "transparent"
- }
- const h = Math.floor(((b % 64) * 360) / 64)
- const l = [53, 15, 35, 75][Math.floor(b / 64)]
- return `hsl(${h}, ${sat}%, ${l}%)`
- })
-
- const rot = (id[28] % 6) * 3
-
- return scheme.colors.map(
- (_, i) => palette[scheme.colors[i < 18 ? (i + rot) % 18 : 18]],
- )
-}
-
-const getPositions = (sixPoint = false) => {
- const r = sixPoint ? (SIZE / 2 / 8) * 5 : (SIZE / 2 / 4) * 3
- const rroot3o2 = (r * Math.sqrt(3)) / 2
- const ro2 = r / 2
- const rroot3o4 = (r * Math.sqrt(3)) / 4
- const ro4 = r / 4
- const r3o4 = (r * 3) / 4
-
- return [
- { x: CENTER, y: CENTER - r },
- { x: CENTER, y: CENTER - ro2 },
- { x: CENTER - rroot3o4, y: CENTER - r3o4 },
- { x: CENTER - rroot3o2, y: CENTER - ro2 },
- { x: CENTER - rroot3o4, y: CENTER - ro4 },
- { x: CENTER - rroot3o2, y: CENTER },
- { x: CENTER - rroot3o2, y: CENTER + ro2 },
- { x: CENTER - rroot3o4, y: CENTER + ro4 },
- { x: CENTER - rroot3o4, y: CENTER + r3o4 },
- { x: CENTER, y: CENTER + r },
- { x: CENTER, y: CENTER + ro2 },
- { x: CENTER + rroot3o4, y: CENTER + r3o4 },
- { x: CENTER + rroot3o2, y: CENTER + ro2 },
- { x: CENTER + rroot3o4, y: CENTER + ro4 },
- { x: CENTER + rroot3o2, y: CENTER },
- { x: CENTER + rroot3o2, y: CENTER - ro2 },
- { x: CENTER + rroot3o4, y: CENTER - ro4 },
- { x: CENTER + rroot3o4, y: CENTER - r3o4 },
- { x: CENTER, y: CENTER },
- ]
-}
diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsx
index 20bdfc0..a59ecaf 100644
--- a/src/components/ui/button.tsx
+++ b/src/components/ui/button.tsx
@@ -1,71 +1 @@
-import * as React from "react"
-import { Slot } from "@radix-ui/react-slot"
-import { cva, type VariantProps } from "class-variance-authority"
-
-import { cn } from "@/lib/utils"
-
-const buttonVariants = cva(
- "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
- {
- variants: {
- variant: {
- default: "bg-primary text-primary-foreground hover:bg-primary/90",
- destructive:
- "bg-destructive text-destructive-foreground hover:bg-destructive/90",
- outline:
- "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
- secondary:
- "border bg-secondary text-secondary-foreground hover:bg-secondary/80",
- ghost: "hover:bg-accent hover:text-accent-foreground",
- link: "text-primary underline-offset-4 hover:underline",
- },
- size: {
- default: "h-10 px-4 py-2",
- sm: "h-9 rounded-md px-3",
- lg: "h-11 rounded-md px-8",
- icon: "h-10 w-10",
- },
- },
- defaultVariants: {
- variant: "default",
- size: "default",
- },
- },
-)
-
-export interface ButtonProps
- extends React.ButtonHTMLAttributes,
- VariantProps {
- asChild?: boolean
- forceSvgSize?: boolean
-}
-
-const Button = React.forwardRef(
- (
- {
- className,
- variant,
- size,
- asChild = false,
- forceSvgSize = true,
- ...props
- },
- ref,
- ) => {
- const Comp = asChild ? Slot : "button"
- return (
-
- )
- },
-)
-Button.displayName = "Button"
-
-export { Button, buttonVariants }
+export { Button } from "@polkahub/ui-components"
diff --git a/src/components/ui/command.tsx b/src/components/ui/command.tsx
index b26d306..2065286 100644
--- a/src/components/ui/command.tsx
+++ b/src/components/ui/command.tsx
@@ -1,157 +1,8 @@
-import * as React from "react"
-import { type DialogProps } from "@radix-ui/react-dialog"
-import { Command as CommandPrimitive } from "cmdk"
-import { Search } from "lucide-react"
-
-import { cn } from "@/lib/utils"
-import { Dialog, DialogContent } from "@/components/ui/dialog"
-
-const Command = React.forwardRef<
- React.ElementRef,
- React.ComponentPropsWithoutRef
->(({ className, ...props }, ref) => (
-
-))
-Command.displayName = CommandPrimitive.displayName
-
-interface CommandDialogProps extends DialogProps {}
-
-const CommandDialog = ({ children, ...props }: CommandDialogProps) => {
- return (
-
- )
-}
-
-const CommandInput = React.forwardRef<
- React.ElementRef,
- React.ComponentPropsWithoutRef
->(({ className, ...props }, ref) => (
-
-
-
-
-))
-
-CommandInput.displayName = CommandPrimitive.Input.displayName
-
-const CommandList = React.forwardRef<
- React.ElementRef,
- React.ComponentPropsWithoutRef
->(({ className, ...props }, ref) => (
-
-))
-
-CommandList.displayName = CommandPrimitive.List.displayName
-
-const CommandEmpty = React.forwardRef<
- React.ElementRef,
- React.ComponentPropsWithoutRef
->((props, ref) => (
-
-))
-
-CommandEmpty.displayName = CommandPrimitive.Empty.displayName
-
-const CommandGroup = React.forwardRef<
- React.ElementRef,
- React.ComponentPropsWithoutRef
->(({ className, ...props }, ref) => (
-
-))
-
-CommandGroup.displayName = CommandPrimitive.Group.displayName
-
-const CommandSeparator = React.forwardRef<
- React.ElementRef,
- React.ComponentPropsWithoutRef
->(({ className, ...props }, ref) => (
-
-))
-CommandSeparator.displayName = CommandPrimitive.Separator.displayName
-
-const CommandItem = React.forwardRef<
- React.ElementRef,
- React.ComponentPropsWithoutRef & {
- forceSvgSize?: boolean
- }
->(({ className, forceSvgSize = true, ...props }, ref) => (
-
-))
-
-CommandItem.displayName = CommandPrimitive.Item.displayName
-
-const CommandShortcut = ({
- className,
- ...props
-}: React.HTMLAttributes) => {
- return (
-
- )
-}
-CommandShortcut.displayName = "CommandShortcut"
-
export {
Command,
- CommandDialog,
+ CommandGroup,
CommandInput,
+ CommandItem,
CommandList,
CommandEmpty,
- CommandGroup,
- CommandItem,
- CommandShortcut,
- CommandSeparator,
-}
+} from "@polkahub/ui-components"
diff --git a/src/components/ui/dialog.tsx b/src/components/ui/dialog.tsx
index cedce26..5c39b36 100644
--- a/src/components/ui/dialog.tsx
+++ b/src/components/ui/dialog.tsx
@@ -1,120 +1,20 @@
-import * as React from "react"
-import * as DialogPrimitive from "@radix-ui/react-dialog"
-import { X } from "lucide-react"
-
import { cn } from "@/lib/utils"
-
-const Dialog = DialogPrimitive.Root
-
-const DialogTrigger = DialogPrimitive.Trigger
-
-const DialogPortal = DialogPrimitive.Portal
-
-const DialogClose = DialogPrimitive.Close
-
-const DialogOverlay = React.forwardRef<
- React.ElementRef,
- React.ComponentPropsWithoutRef
->(({ className, ...props }, ref) => (
-
-))
-DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
-
-const DialogContent = React.forwardRef<
- React.ElementRef,
- React.ComponentPropsWithoutRef
->(({ className, children, ...props }, ref) => (
-
-
-
- {children}
-
-
- Close
-
-
-
-))
-DialogContent.displayName = DialogPrimitive.Content.displayName
-
-const DialogHeader = ({
- className,
- ...props
-}: React.HTMLAttributes) => (
-
-)
-DialogHeader.displayName = "DialogHeader"
-
-const DialogFooter = ({
- className,
- ...props
-}: React.HTMLAttributes) => (
-
-)
-DialogFooter.displayName = "DialogFooter"
-
-const DialogTitle = React.forwardRef<
- React.ElementRef,
- React.ComponentPropsWithoutRef
->(({ className, ...props }, ref) => (
-
-))
-DialogTitle.displayName = DialogPrimitive.Title.displayName
-
-const DialogDescription = React.forwardRef<
- React.ElementRef,
- React.ComponentPropsWithoutRef
->(({ className, ...props }, ref) => (
-
-))
-DialogDescription.displayName = DialogPrimitive.Description.displayName
-
export {
Dialog,
- DialogPortal,
- DialogOverlay,
- DialogClose,
- DialogTrigger,
DialogContent,
DialogHeader,
- DialogFooter,
DialogTitle,
- DialogDescription,
+ DialogTrigger,
+} from "@polkahub/ui-components"
+
+export function DialogBody({
+ children,
+ id,
+ className,
+}: React.PropsWithChildren<{ id?: string; className?: string }>) {
+ return (
+
+ {children}
+
+ )
}
diff --git a/src/components/ui/popover.tsx b/src/components/ui/popover.tsx
index c5270e7..d5264bd 100644
--- a/src/components/ui/popover.tsx
+++ b/src/components/ui/popover.tsx
@@ -1,29 +1,5 @@
-import * as React from "react"
-import * as PopoverPrimitive from "@radix-ui/react-popover"
-
-import { cn } from "@/lib/utils"
-
-const Popover = PopoverPrimitive.Root
-
-const PopoverTrigger = PopoverPrimitive.Trigger
-
-const PopoverContent = React.forwardRef<
- React.ElementRef,
- React.ComponentPropsWithoutRef
->(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
-
-
-
-))
-PopoverContent.displayName = PopoverPrimitive.Content.displayName
-
-export { Popover, PopoverTrigger, PopoverContent }
+export {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@polkahub/ui-components"
diff --git a/src/index.css b/src/index.css
index f0950ab..d4f3fbb 100644
--- a/src/index.css
+++ b/src/index.css
@@ -1,4 +1,5 @@
@import 'tailwindcss';
+@import "polkahub";
@custom-variant dark (&:is(.dark *));
diff --git a/src/main.tsx b/src/main.tsx
index ce4489d..f1e913a 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -1,5 +1,6 @@
import { dynamicBuilder$ } from "@/state/chains/chain.state"
import { RemoveSubscribe, Subscribe } from "@react-rxjs/core"
+import { PolkaHubProvider } from "polkahub"
import { StrictMode } from "react"
import { createRoot } from "react-dom/client"
import { BrowserRouter } from "react-router-dom"
@@ -10,6 +11,7 @@ import "./index.css"
import { explorer$ } from "./pages/Explorer"
import { storage$ } from "./pages/Storage/storage.state.ts"
import { transactions$ } from "./pages/Transactions"
+import { polkaHub } from "./state/polkahub.ts"
import { ThemeProvider } from "./ThemeProvider.tsx"
createRoot(document.getElementById("root")!).render(
@@ -19,11 +21,13 @@ createRoot(document.getElementById("root")!).render(
-
-
-
-
-
+
+
+
+
+
+
+
diff --git a/src/pages/Accounts/AccountList.tsx b/src/pages/Accounts/AccountList.tsx
index 8306d89..1965cae 100644
--- a/src/pages/Accounts/AccountList.tsx
+++ b/src/pages/Accounts/AccountList.tsx
@@ -1,12 +1,6 @@
import { AccountIdDisplay } from "@/components/AccountIdDisplay"
import { TokenAmount } from "@/components/TokenAmount"
import { Button } from "@/components/ui/button"
-import {
- Account,
- accounts$,
- AccountSource,
- accountSourceTypeToName,
-} from "@/state/accounts.state"
import { chainProperties$ } from "@/state/chain-props.state"
import { client$ } from "@/state/chains/chain.state"
import { MultiAddress, polkadot_people } from "@polkadot-api/descriptors"
@@ -18,17 +12,54 @@ import {
} from "@react-rxjs/core"
import { Send } from "lucide-react"
import { CompatibilityLevel, SS58String } from "polkadot-api"
+import {
+ Account,
+ ledgerProviderId,
+ PjsWalletAccount,
+ polkadotVaultProviderId,
+ readOnlyProviderId,
+ useAvailableAccounts,
+ walletConnectProviderId,
+} from "polkahub"
import { FC } from "react"
import { Link } from "react-router-dom"
import { catchError, combineLatest, map, switchMap } from "rxjs"
-import { knownExtensions } from "./Providers"
+
+const knownGroupsNames: Record = {
+ "pjs-wallet": "Browser Extensions",
+ [ledgerProviderId]: "Ledger",
+ [readOnlyProviderId]: "Read Only",
+ [polkadotVaultProviderId]: "Polkadot Vault",
+ [walletConnectProviderId]: "Wallet Connect",
+}
+const knownGroupsColors: Record = {
+ "pjs-wallet": "var(--color-lime-700)",
+ [readOnlyProviderId]: "var(--color-orange-700)",
+ [walletConnectProviderId]: "var(--color-blue-700)",
+}
export const AccountList = () => {
- const accounts = useStateObservable(accounts$)
+ const accountGroups = useAvailableAccounts()
return (
Accounts
+ {Object.entries(accountGroups)
+ .filter(([_, accounts]) => accounts.length > 0)
+ .map(([id, accounts]) => (
+
+ ))}
+
+ )
+}
+
+const AccountGroup: FC<{ id: string; accounts: Account[] }> = ({
+ id,
+ accounts,
+}) => {
+ return (
+
+
{getGroupName(id)}
{accounts.map((account, i) => (
@@ -45,24 +76,25 @@ const AccountCard: FC<{
-
- {account.accountId.startsWith("0x") ? null : (
-
+ {account.address.startsWith("0x") ? null : (
+
)}
)
}
-
-const sourceColors: Record = {
- extension: "var(--color-lime-700)",
- walletconnect: "var(--color-blue-700)",
- readonly: "var(--color-orange-700)",
+export const knownExtensions: Record = {
+ "polkadot-js": "Polkadot JS",
+ "nova-wallet": "Nova Wallet",
+ talisman: "Talisman",
+ "subwallet-js": "Subwallet",
}
-const getExtensionName = (id: string) => knownExtensions[id]?.name ?? id
+const getExtensionName = (id: string) => knownExtensions[id] ?? id
+const getGroupName = (id: string) => knownGroupsNames[id] ?? id
const SourceTag: FC<{
account: Account
@@ -70,14 +102,18 @@ const SourceTag: FC<{
return (
- {account.type === "extension"
- ? getExtensionName(account.extensionId)
- : accountSourceTypeToName[account.type]}
+ {account.provider === "pjs-wallet"
+ ? getExtensionName((account as PjsWalletAccount).extensionId)
+ : getGroupName(account.provider)}
)
}
diff --git a/src/pages/Accounts/AddressProvider.tsx b/src/pages/Accounts/AddressProvider.tsx
deleted file mode 100644
index 4ab775a..0000000
--- a/src/pages/Accounts/AddressProvider.tsx
+++ /dev/null
@@ -1,89 +0,0 @@
-import { AccountIdDisplay } from "@/components/AccountIdDisplay"
-import { AccountIdInput } from "@/components/AccountIdInput"
-import { Button } from "@/components/ui/button"
-import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog"
-import { readOnlyAccounts$, setAddresses } from "@/state/accounts.state"
-import { useStateObservable } from "@react-rxjs/core"
-import { Eye, Trash2 } from "lucide-react"
-import { SS58String } from "polkadot-api"
-import { useState } from "react"
-import { SourceButton } from "./SourceButton"
-
-export const AddressProvider = () => (
-
-)
-
-const ManageAddresses = () => {
- const [addressInput, setAddressInput] = useState(null)
- const accounts = useStateObservable(readOnlyAccounts$)
-
- return (
-
-
- {accounts.length ? (
-
-
Added addresses
-
- {accounts.map((account) => (
- -
-
-
-
- ))}
-
-
- ) : null}
-
- )
-}
diff --git a/src/pages/Accounts/Providers.tsx b/src/pages/Accounts/Providers.tsx
index edbc60e..38ad4af 100644
--- a/src/pages/Accounts/Providers.tsx
+++ b/src/pages/Accounts/Providers.tsx
@@ -1,131 +1,83 @@
-import { Spinner } from "@/components/Icons"
import {
- availableExtensions$,
- onToggleExtension,
- selectedExtensions$,
-} from "@/state/extension-accounts.state"
-import { state, useStateObservable } from "@react-rxjs/core"
-import { CircleQuestionMark } from "lucide-react"
-import { FC } from "react"
-import { defer, from, switchMap } from "rxjs"
-import { AddressProvider } from "./AddressProvider"
-import { SourceButton } from "./SourceButton"
+ Button,
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from "@polkahub/ui-components"
+import { ChevronLeft } from "lucide-react"
+import {
+ ManageLedger,
+ ManageReadOnly,
+ ManageVault,
+ ModalContext,
+ PjsWalletButtons,
+ usePolkaHubModalState,
+ WalletConnectButton,
+} from "polkahub"
+import { FC, PropsWithChildren } from "react"
-const lazyWalletConnectStatus$ = state(
- defer(() =>
- from(import("@/state/walletconnect.state")).pipe(
- switchMap(({ walletConnectStatus$ }) => walletConnectStatus$),
- ),
- ),
- {
- type: "disconnected",
- },
-)
-
-export const knownExtensions: Record = {
- "polkadot-js": {
- name: "Polkadot JS",
- logo: import.meta.env.BASE_URL + "providers/polkadotjs.webp",
- },
- "nova-wallet": {
- name: "Nova Wallet",
- logo: import.meta.env.BASE_URL + "providers/novawallet.webp",
- },
- talisman: {
- name: "Talisman",
- logo: import.meta.env.BASE_URL + "providers/talisman.webp",
- },
- "subwallet-js": {
- name: "Subwallet",
- logo: import.meta.env.BASE_URL + "providers/subwallet.webp",
- },
-}
-
-export const Providers = () => {
- const availableExtensions = useStateObservable(availableExtensions$).sort(
- (a, b) => (b in knownExtensions ? 1 : 0) - (a in knownExtensions ? 1 : 0),
- )
- const walletConnectStatus = useStateObservable(lazyWalletConnectStatus$)
+const ManageToDialog: FC = ({ children }) => {
+ const { contentStack, contextValue, setContentStack } =
+ usePolkaHubModalState()
+ const activeContent = contentStack.length
+ ? contentStack[contentStack.length - 1]
+ : null
return (
-
-
Account Providers
-
- {availableExtensions.map((id) => (
- -
-
-
- ))}
-
-
- {/*
-
- */}
- {/*
-
- */}
- {
- const { toggleWalletConnect } = await import(
- "@/state/walletconnect.state"
- )
- toggleWalletConnect()
+ <>
+ {children}
+
+
+ {contentStack.length > 1 ? (
+
+ ) : null}
+ {activeContent?.title}
+
+
+
+ {activeContent?.element}
+
+
+
+
+ >
+ )
+}
+
+export const Providers = () => (
+
+
Account Providers
+
+
+
-
- )
-}
-
-const ExtensionButton: FC<{
- id: string
-}> = ({ id }) => {
- const knownExtension = knownExtensions[id]
- const connectedExtensions = Array.from(
- useStateObservable(selectedExtensions$).keys(),
- )
- const isSelected = connectedExtensions.includes(id)
-
- return (
- onToggleExtension(id)}
- >
- {knownExtension ? (
-
- ) : (
-
-
-
- )}
-
- )
-}
+
+
+)
diff --git a/src/pages/Accounts/SourceButton.tsx b/src/pages/Accounts/SourceButton.tsx
deleted file mode 100644
index e34aeb8..0000000
--- a/src/pages/Accounts/SourceButton.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-import { Button } from "@/components/ui/button"
-import { cn } from "@/utils"
-import { FC, MouseEvent, PropsWithChildren } from "react"
-
-export const SourceButton: FC<
- PropsWithChildren<{
- label: string
- isSelected?: boolean
- className?: string
- onClick?: (evt: MouseEvent) => void
- disabled?: boolean
- }>
-> = ({ label, isSelected, onClick, className, children, disabled }) => (
-
-)
diff --git a/src/pages/Extrinsics/SubmitTx/AccountProvider.tsx b/src/pages/Extrinsics/SubmitTx/AccountProvider.tsx
deleted file mode 100644
index 3ae06e0..0000000
--- a/src/pages/Extrinsics/SubmitTx/AccountProvider.tsx
+++ /dev/null
@@ -1,127 +0,0 @@
-import { AccountIdDisplay } from "@/components/AccountIdDisplay"
-import { EthAccountDisplay } from "@/components/EthAccountDisplay"
-import {
- Select,
- SelectContent,
- SelectGroup,
- SelectItem,
- SelectLabel,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select"
-import { groupBy } from "@/lib/groupBy"
-import { knownExtensions } from "@/pages/Accounts/Providers"
-import {
- Account,
- accounts$,
- AccountSource,
- accountSourceTypeToName,
-} from "@/state/accounts.state"
-import { selectedExtensions$ } from "@/state/extension-accounts.state"
-import { walletConnectStatus$ } from "@/state/walletconnect.state"
-import { state, useStateObservable, withDefault } from "@react-rxjs/core"
-import { createSignal } from "@react-rxjs/utils"
-import React from "react"
-import {
- combineLatest,
- defer,
- distinctUntilChanged,
- map,
- merge,
- of,
- tap,
-} from "rxjs"
-
-const [valueSelected$, selectValue] = createSignal()
-
-const LS_KEY = "selected-signer"
-const selectedValue$ = state(
- merge(
- defer(() => of(localStorage.getItem(LS_KEY))),
- valueSelected$.pipe(tap((v) => localStorage.setItem(LS_KEY, v))),
- ),
- null,
-)
-
-const allAccounts$ = accounts$.pipeState(
- map((v) =>
- v.map((acc) => ({
- ...acc,
- id: `${acc.accountId}-${acc.type === "extension" ? acc.extensionId : acc.type}`,
- })),
- ),
- withDefault([]),
-)
-
-export const selectedAccount$ = state(
- combineLatest([selectedValue$, allAccounts$]).pipe(
- map(([selectedAccount, accounts]): Account | null => {
- if (!selectedAccount) return null
- const account = accounts.find((account) => account.id === selectedAccount)
-
- return account ?? null
- }),
- distinctUntilChanged(),
- ),
- null,
-)
-
-const groupedAccounts$ = allAccounts$.pipeState(
- map((v) =>
- groupBy(
- // Accept only signer accounts for submitting transactions
- v.filter((v) => v.signer != null),
- (acc) => (acc.type === "extension" ? acc.extensionId : acc.type),
- ),
- ),
-)
-
-const groupIdToName = (groupId: string) => {
- if (groupId in knownExtensions) {
- return knownExtensions[groupId].name
- }
- return accountSourceTypeToName[groupId as AccountSource] ?? groupId
-}
-
-export const AccountProvider: React.FC = () => {
- const value = useStateObservable(selectedValue$)
- const extensions = useStateObservable(selectedExtensions$)
- const walletConnect = useStateObservable(walletConnectStatus$)
- const allAccounts = useStateObservable(allAccounts$)
- const groupedAccounts = useStateObservable(groupedAccounts$)
-
- const activeExtensions = [...extensions.values()].filter((v) => !!v)
- const valueExists = value && allAccounts.some((acc) => acc.id === value)
-
- if (!activeExtensions.length && walletConnect.type !== "connected")
- return null
-
- return (
-
- )
-}
diff --git a/src/pages/Extrinsics/SubmitTx/ExtensionProvider.tsx b/src/pages/Extrinsics/SubmitTx/ExtensionProvider.tsx
index 4c8b4b2..82829eb 100644
--- a/src/pages/Extrinsics/SubmitTx/ExtensionProvider.tsx
+++ b/src/pages/Extrinsics/SubmitTx/ExtensionProvider.tsx
@@ -2,14 +2,14 @@ import { Label } from "@/components/ui/label"
import { TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
availableExtensions$,
- onToggleExtension,
selectedExtensions$,
-} from "@/state/extension-accounts.state"
+ toggleExtension,
+} from "@/state/polkahub"
import { useStateObservable } from "@react-rxjs/core"
export const ExtensionProvider: React.FC = () => {
const availableExtensions = useStateObservable(availableExtensions$)
- const selectedExtensions = useStateObservable(selectedExtensions$)
+ const selectedExtensions = new Set(useStateObservable(selectedExtensions$))
return (
<>
@@ -18,7 +18,7 @@ export const ExtensionProvider: React.FC = () => {
{availableExtensions.map((extensionName) => (
onToggleExtension(extensionName)}
+ onClick={() => toggleExtension(extensionName)}
active={selectedExtensions.has(extensionName)}
key={extensionName}
>
diff --git a/src/pages/Extrinsics/SubmitTx/SubmitTxForm.tsx b/src/pages/Extrinsics/SubmitTx/SubmitTxForm.tsx
index c366d2e..d78cd98 100644
--- a/src/pages/Extrinsics/SubmitTx/SubmitTxForm.tsx
+++ b/src/pages/Extrinsics/SubmitTx/SubmitTxForm.tsx
@@ -2,14 +2,15 @@ import { ActionButton } from "@/components/ActionButton"
import { Spinner } from "@/components/Icons"
import { trackSignedTx, trackUnsignedTx } from "@/pages/Transactions"
import { unsafeApi$ } from "@/state/chains/chain.state"
+import { selectedAccount$ } from "@/state/polkahub"
import { compactNumber } from "@polkadot-api/substrate-bindings"
import { fromHex, mergeUint8, toHex } from "@polkadot-api/utils"
import { useStateObservable } from "@react-rxjs/core"
import { Binary } from "polkadot-api"
+import { SelectAccountField } from "polkahub"
import { FC, useState } from "react"
import { firstValueFrom } from "rxjs"
import { twMerge } from "tailwind-merge"
-import { AccountProvider, selectedAccount$ } from "./AccountProvider"
import { ExtensionProvider } from "./ExtensionProvider"
const SignAndSubmit: FC<{ callData: string; onClose: () => void }> = ({
@@ -77,7 +78,7 @@ export default function SubmitTxF(props: {
return (
<>
-
+
diff --git a/src/pages/Network/Network.tsx b/src/pages/Network/Network.tsx
index 3e7ad45..5724853 100644
--- a/src/pages/Network/Network.tsx
+++ b/src/pages/Network/Network.tsx
@@ -12,6 +12,7 @@ import {
} from "@/components/ui/command"
import {
Dialog,
+ DialogBody,
DialogContent,
DialogHeader,
DialogTitle,
@@ -119,7 +120,7 @@ const NetworkSwitchDialogContent: FC<{
return (
{
if (
evt.target instanceof HTMLElement &&
@@ -133,131 +134,136 @@ const NetworkSwitchDialogContent: FC<{
Switch Network
-
-
-
-
- No networks found.
-
-
- {networkCategories.map((category) => (
-
- {category.networks.map((network) => (
- handleNetworkSelect(network)}
- value={
- network.display.includes(category.name)
- ? network.display
- : `${category.name} ${network.display}`
- }
- >
-
- {network.display}
-
- ))}
- {category.name === "Custom" && isValidUri(enteredText) ? (
- {
- handleNetworkSelect({
- id: "custom-network",
- lightclient: false,
- endpoints: { custom: enteredText },
- display: enteredText,
- })
- }}
- >
-
- {enteredText}
-
- ) : null}
-
- ))}
-
-
-
-
- {selectedNetwork ? (
-
-
Network: {selectedNetwork.display}
-
-
- {selectedNetwork.lightclient ? (
-
- ) : null}
- {Object.entries(selectedNetwork.endpoints).map(
- ([rpcName, url]) => (
-
- ),
- )}
-
-
-
- ) : null}
- {selectedRpc && selectedRpc !== "light-client" && (
-
-
-
-
-
-
-
+
+
)
}
diff --git a/src/state/accounts.state.ts b/src/state/accounts.state.ts
deleted file mode 100644
index 72b5614..0000000
--- a/src/state/accounts.state.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-import { createLocalStorageState } from "@/lib/externalState"
-import { state } from "@react-rxjs/core"
-import type { HexString, PolkadotSigner, SS58String } from "polkadot-api"
-import type { InjectedPolkadotAccount } from "polkadot-api/pjs-signer"
-import { combineLatest, defer, from, map, switchMap } from "rxjs"
-import { accountsByExtension$, getPublicKey } from "./extension-accounts.state"
-import { getPolkadotSigner } from "polkadot-api/signer"
-import { canSetStorage$ } from "./chains/chain.state"
-
-export type AccountSource = "extension" | "walletconnect" | "readonly"
-export const accountSourceTypeToName: Record
= {
- extension: "Extension",
- walletconnect: "Wallet Connect",
- readonly: "Read-only",
-}
-
-const lazyWalletConnectAccounts$ = defer(() =>
- from(import("@/state/walletconnect.state")).pipe(
- switchMap(({ walletConnectAccounts$ }) => walletConnectAccounts$),
- ),
-)
-
-interface BaseAccount {
- type: AccountSource
- accountId: SS58String | HexString
- name?: string
-}
-
-interface SignerAccount extends BaseAccount {
- signer: PolkadotSigner
-}
-
-export interface ExtensionAccount extends SignerAccount {
- type: "extension"
- extensionId: string
- injected: InjectedPolkadotAccount
-}
-export const extensionAccounts$ = state(
- accountsByExtension$.pipe(
- map((extensionAccounts) =>
- Array.from(extensionAccounts.entries()).flatMap(([extension, accounts]) =>
- accounts.map(
- (account): ExtensionAccount => ({
- type: "extension",
- accountId: account.address,
- name: account.name,
- extensionId: extension,
- injected: account,
- signer: account.polkadotSigner,
- }),
- ),
- ),
- ),
- ),
- [],
-)
-
-export interface WalletConnectAccount extends SignerAccount {
- type: "walletconnect"
-}
-export const walletConnectAccounts$ = state(
- lazyWalletConnectAccounts$.pipe(
- map((accounts) =>
- Object.entries(accounts).map(
- ([accountId, signer]): WalletConnectAccount => ({
- type: "walletconnect",
- accountId,
- signer,
- }),
- ),
- ),
- ),
- [],
-)
-
-export interface ReadOnlyAccount extends BaseAccount {
- type: "readonly"
- // Chopsticks can fake a signer
- signer?: PolkadotSigner
-}
-const [readOnlyAddresses$, setAddresses] = createLocalStorageState(
- "read-only-addr",
- [] as string[],
-)
-export { setAddresses }
-export const readOnlyAccounts$ = state(
- combineLatest([defer(readOnlyAddresses$), canSetStorage$]).pipe(
- map(([v, isChopsticks]) =>
- v.map(
- (address): ReadOnlyAccount => ({
- type: "readonly",
- accountId: address,
- signer: isChopsticks
- ? getPolkadotSigner(getPublicKey(address)!, "Sr25519", () => {
- // From https://wiki.acala.network/build/sdks/homa
- const signature = new Uint8Array(64)
- signature.fill(0xcd)
- signature.set([0xde, 0xad, 0xbe, 0xef])
- return signature
- })
- : undefined,
- }),
- ),
- ),
- ),
- [],
-)
-
-export type Account = ExtensionAccount | WalletConnectAccount | ReadOnlyAccount
-export const accounts$ = state(
- combineLatest([
- extensionAccounts$,
- walletConnectAccounts$,
- readOnlyAccounts$,
- ]).pipe(map((v): Account[] => v.flat())),
- [],
-)
diff --git a/src/state/extension-accounts.state.ts b/src/state/extension-accounts.state.ts
deleted file mode 100644
index 8789e66..0000000
--- a/src/state/extension-accounts.state.ts
+++ /dev/null
@@ -1,214 +0,0 @@
-import { state, withDefault } from "@react-rxjs/core"
-import { combineKeys, createKeyedSignal } from "@react-rxjs/utils"
-import { Binary, getSs58AddressInfo } from "polkadot-api"
-import {
- connectInjectedExtension,
- getInjectedExtensions,
- InjectedExtension,
- InjectedPolkadotAccount,
-} from "polkadot-api/pjs-signer"
-import {
- catchError,
- concat,
- defer,
- filter,
- interval,
- map,
- NEVER,
- Observable,
- of,
- retry,
- scan,
- startWith,
- switchMap,
- take,
- tap,
- timer,
-} from "rxjs"
-
-export const availableExtensions$ = state(
- concat(
- timer(0, 100).pipe(
- map(getInjectedExtensions),
- filter((v) => v.length > 0),
- take(1),
- ),
- interval(2000).pipe(map(getInjectedExtensions)),
- ),
- [],
-)
-
-const [toggleExtension$, onToggleExtension] = createKeyedSignal()
-export { onToggleExtension }
-
-export const enum ConnectStatus {
- Connecting,
- Disconnected,
- Connected,
-}
-export type ExtensionState =
- | {
- type: ConnectStatus.Disconnected
- }
- | { type: ConnectStatus.Connecting }
- | { type: ConnectStatus.Connected; value: InjectedExtension }
-
-const SELECTED_EXTENSIONS_KEY = "selected-extensions"
-const getPreselectedExtensions = () => {
- try {
- const res = JSON.parse(localStorage.getItem(SELECTED_EXTENSIONS_KEY)!)
- if (Array.isArray(res)) return res
- // eslint-disable-next-line no-empty
- } catch (_) {}
- return null
-}
-const extensionIsPreselected = (extension: string) =>
- getPreselectedExtensions()?.includes(extension) ?? false
-const setPreselectedExtension = (extension: string, selected: boolean) => {
- const preselectedExtensions = getPreselectedExtensions() ?? []
- const result = selected
- ? [...new Set([...preselectedExtensions, extension])]
- : preselectedExtensions.filter((v) => v !== extension)
- localStorage.setItem(SELECTED_EXTENSIONS_KEY, JSON.stringify(result))
-}
-
-const extension$ = (name: string) => {
- const connect$ = defer(() => connectInjectedExtension(name)).pipe(
- // PolkadotJS rejects the promise straight away instead of waiting for user input
- retry({
- delay(error) {
- if (error?.message.includes("pending authorization request")) {
- return timer(1000)
- }
- throw error
- },
- }),
- map((extension) => ({
- type: ConnectStatus.Connected as const,
- extension,
- })),
- catchError((ex) => {
- console.error(ex)
- return of({ type: ConnectStatus.Disconnected as const })
- }),
- startWith({ type: ConnectStatus.Connecting as const }),
- )
-
- const connectWithCleanup$ = defer(() => {
- let disconnected = false
- let extension: InjectedExtension | null = null
- return concat(connect$, NEVER).pipe(
- tap({
- next(value) {
- if (value.type === ConnectStatus.Connected) {
- if (disconnected) {
- value.extension.disconnect()
- } else {
- extension = value.extension
- }
- }
- },
- unsubscribe() {
- if (extension) {
- extension.disconnect()
- } else {
- disconnected = true
- }
- },
- }),
- )
- })
-
- const initialSelected = extensionIsPreselected(name)
- return toggleExtension$(name).pipe(
- scan((acc) => !acc, initialSelected),
- startWith(initialSelected),
- switchMap((selected) =>
- selected
- ? connectWithCleanup$
- : of({
- type: ConnectStatus.Disconnected as const,
- }),
- ),
- tap((v) => {
- if (v.type === ConnectStatus.Connected) {
- setPreselectedExtension(name, true)
- } else if (v.type === ConnectStatus.Disconnected) {
- setPreselectedExtension(name, false)
- }
- }),
- )
-}
-
-export const extensions$ = state(combineKeys(availableExtensions$, extension$))
-
-export const selectedExtensions$ = extensions$.pipeState(
- map(
- (extensions) =>
- new Map(
- [...extensions.entries()]
- .filter(([, v]) => v.type !== ConnectStatus.Disconnected)
- .map(([k, v]) => [
- k,
- v.type === ConnectStatus.Connected ? v.extension : null,
- ]),
- ),
- ),
- withDefault(new Map()),
-)
-
-const extensionAccounts$ = state(
- (name: string) =>
- extension$(name).pipe(
- switchMap((x) => {
- if (x.type !== ConnectStatus.Connected) return of([])
- return new Observable((observer) =>
- x.extension.subscribe((accounts) => {
- observer.next(accounts)
- }),
- )
- }),
- ),
- [],
-)
-
-export const accountsByExtension$ = state(
- combineKeys(availableExtensions$, extensionAccounts$),
- new Map(),
-)
-
-export const getPublicKey = (address: string) => {
- const info = getSs58AddressInfo(address)
- return info.isValid ? info.publicKey : null
-}
-export const getAccountMapKey = (address: string) => {
- const pk = getPublicKey(address)
- return pk ? Binary.fromBytes(pk).asHex() : address
-}
-
-export const accounts$ = state(
- accountsByExtension$.pipe(
- map(
- (extensionAccounts) =>
- new Map(
- Array.from(extensionAccounts.entries()).flatMap(
- ([extension, accounts]) =>
- accounts.map((account) => [
- getAccountMapKey(account.address),
- {
- ...account,
- extension,
- },
- ]),
- ),
- ),
- ),
- ),
- new Map(),
-)
-
-export const accountDetail$ = state(
- (account: string) =>
- accounts$.pipe(map((v) => v.get(getAccountMapKey(account)) ?? null)),
- null,
-)
diff --git a/src/state/polkahub.ts b/src/state/polkahub.ts
new file mode 100644
index 0000000..56df9a3
--- /dev/null
+++ b/src/state/polkahub.ts
@@ -0,0 +1,134 @@
+import { polkadot_people } from "@polkadot-api/descriptors"
+import { state, withDefault } from "@react-rxjs/core"
+import { AccountId, SS58String } from "polkadot-api"
+import {
+ Account,
+ createLedgerProvider,
+ createPjsWalletProvider,
+ createPolkadotVaultProvider,
+ createPolkaHub,
+ createReadOnlyProvider,
+ createSelectedAccountPlugin,
+ createWalletConnectProvider,
+ knownChains,
+ Plugin,
+} from "polkahub"
+import { combineLatest, filter, firstValueFrom, map } from "rxjs"
+import { chainProperties$ } from "./chain-props.state"
+import { canSetStorage$, client$ } from "./chains/chain.state"
+import { getAddressName, isVerified } from "./identity.state"
+
+const selectedAccountPlugin = createSelectedAccountPlugin()
+const pjsWalletProvider = createPjsWalletProvider()
+const polkadotVaultProvider = createPolkadotVaultProvider()
+const readOnlyProvider$ = canSetStorage$.pipe(
+ map((fakeSigner) =>
+ createReadOnlyProvider({
+ fakeSigner,
+ }),
+ ),
+)
+const ledgerAccountProvider = createLedgerProvider(
+ async () => {
+ const module = await import("@ledgerhq/hw-transport-webhid")
+ return module.default.create()
+ },
+ () =>
+ firstValueFrom(
+ chainProperties$.pipe(
+ filter((v) => v != null),
+ map(({ ss58Format, tokenDecimals, tokenSymbol }) => ({
+ decimals: tokenDecimals!,
+ tokenSymbol: tokenSymbol!,
+ ss58Format: ss58Format!,
+ })),
+ ),
+ ),
+)
+const walletConnectProvider = createWalletConnectProvider(
+ import.meta.env.VITE_REOWN_PROJECT_ID,
+ [
+ knownChains.polkadot,
+ knownChains.polkadotAh,
+ knownChains.kusama,
+ knownChains.kusamaAh,
+ knownChains.paseo,
+ knownChains.paseoAh,
+ ],
+)
+
+export const polkaHub = createPolkaHub(
+ combineLatest([
+ [selectedAccountPlugin],
+ [pjsWalletProvider],
+ [polkadotVaultProvider],
+ readOnlyProvider$,
+ [ledgerAccountProvider],
+ [walletConnectProvider],
+ ]).pipe(map((v: (Plugin | null)[]) => v.filter((v) => v != null))),
+ {
+ async getIdentity(address) {
+ const res = await getAddressName(address)
+ return res
+ ? {
+ name: res.displayName,
+ verified: isVerified(res) ?? false,
+ }
+ : null
+ },
+ async getBalance(address) {
+ const client = await firstValueFrom(client$)
+ const [chainProps, balance] = await firstValueFrom(
+ combineLatest([
+ chainProperties$,
+ client
+ .getTypedApi(polkadot_people)
+ .query.System.Account.getValue(address),
+ ]),
+ )
+
+ if (chainProps?.tokenDecimals == null) return null
+
+ return {
+ value: balance.data.reserved + balance.data.free,
+ decimals: chainProps.tokenDecimals,
+ symbol: chainProps.tokenSymbol,
+ }
+ },
+ },
+)
+
+export const addrToAccount$ = polkaHub.availableAccounts$.pipeState(
+ map((groups) =>
+ Object.fromEntries(
+ Object.values(groups).flatMap((group) =>
+ group.map((account) => [account.address, account]),
+ ),
+ ),
+ ),
+ withDefault({} as Record),
+)
+
+export const accountDetail$ = state(
+ (addr: SS58String) =>
+ addrToAccount$.pipe(map((addrToAccount) => addrToAccount[addr] ?? null)),
+ null,
+)
+
+export const getPublicKey = AccountId().enc
+
+export const selectedAccount$ =
+ selectedAccountPlugin.selectedAccount$.pipeState(withDefault(null))
+
+export const availableExtensions$ = pjsWalletProvider.availableExtensions$
+export const selectedExtensions$ = pjsWalletProvider.connectedExtensions$
+export const toggleExtension = async (id: string) => {
+ const extensions = await firstValueFrom(
+ pjsWalletProvider.connectedExtensions$,
+ )
+ pjsWalletProvider.setConnectedExtensions(
+ extensions.includes(id)
+ ? extensions.filter((v) => v != id)
+ : [...extensions, id],
+ )
+}
diff --git a/src/state/walletconnect.state.ts b/src/state/walletconnect.state.ts
deleted file mode 100644
index 0f59b2b..0000000
--- a/src/state/walletconnect.state.ts
+++ /dev/null
@@ -1,258 +0,0 @@
-import { localStorageSubject } from "@/utils/localStorageSubject"
-import { state, withDefault } from "@react-rxjs/core"
-import { createSignal } from "@react-rxjs/utils"
-import { WalletConnectModal } from "@walletconnect/modal"
-import { SessionTypes } from "@walletconnect/types"
-import UniversalProvider from "@walletconnect/universal-provider"
-import { getSdkError } from "@walletconnect/utils"
-import {
- getPolkadotSignerFromPjs,
- PolkadotSigner,
-} from "polkadot-api/pjs-signer"
-import {
- catchError,
- defer,
- EMPTY,
- filter,
- finalize,
- firstValueFrom,
- from,
- fromEventPattern,
- ignoreElements,
- map,
- Observable,
- of,
- scan,
- startWith,
- switchMap,
- take,
- takeUntil,
- tap,
-} from "rxjs"
-
-// https://docs.reown.com/advanced/multichain/polkadot/dapp-integration-guide
-const chains = [
- "polkadot:91b171bb158e2d3848fa23a9f1c25182", // Polkadot
- "polkadot:e143f23803ac50e8f6f8e62695d1ce9e", // Westend
-]
-const projectId = import.meta.env.VITE_REOWN_PROJECT_ID
-const walletConnectModal = new WalletConnectModal({
- projectId,
- chains,
-})
-
-const provider$ = state(
- defer(() =>
- UniversalProvider.init({
- projectId,
- relayUrl: "wss://relay.walletconnect.com",
- }),
- ),
-)
-
-interface InitializedSession {
- uri?: string
- approval: () => Promise
-}
-const initializeSession$ = () =>
- provider$.pipe(
- take(1),
- switchMap(
- (provider): Promise =>
- provider.client.connect({
- requiredNamespaces: {
- polkadot: {
- methods: ["polkadot_signTransaction", "polkadot_signMessage"],
- chains,
- events: ["chainChanged", "accountsChanged"],
- },
- },
- }),
- ),
- )
-
-const sessionSubject = localStorageSubject(
- "wallet-connect",
- JSON,
-)
-
-type WalletConnectStatus =
- | {
- type: "disconnected"
- }
- | {
- type: "connecting"
- }
- | {
- type: "connected"
- session: SessionTypes.Struct
- }
-
-const connect$ = defer(initializeSession$).pipe(
- switchMap(({ uri, approval }) => {
- if (!uri) return approval()
-
- walletConnectModal.openModal({ uri })
- const modal$ = fromEventPattern<{ open: boolean }>(
- (handler) => walletConnectModal.subscribeModal(handler),
- (_, fn) => fn(),
- )
- const closed$ = modal$.pipe(
- tap((v) => console.log("modal event", v)),
- filter(({ open }) => !open),
- )
-
- return from(approval()).pipe(
- takeUntil(closed$),
- finalize(() => walletConnectModal.closeModal()),
- )
- }),
- map((session): WalletConnectStatus => ({ type: "connected", session })),
- catchError((err) => {
- console.log("connect WalletConnect error", err)
- return of(EMPTY) as any as Observable
- }),
- startWith({ type: "connecting" } satisfies WalletConnectStatus),
-)
-const disconnect$ = provider$.pipe(
- take(1),
- switchMap((provider) =>
- provider.session
- ? provider.client.disconnect({
- topic: provider.session.topic,
- reason: getSdkError("USER_DISCONNECTED"),
- })
- : EMPTY,
- ),
- ignoreElements(),
- startWith({
- type: "disconnected",
- } satisfies WalletConnectStatus),
-)
-
-export const [toggleConnect$, toggleWalletConnect] = createSignal()
-
-export const walletConnectStatus$ = state(
- sessionSubject.stream$.pipe(
- take(1),
- switchMap((session): Observable => {
- const connectState$ = toggleConnect$.pipe(
- scan((acc) => !acc, !!session),
- switchMap((connect) =>
- connect
- ? connect$.pipe(
- tapOnLast((v) => {
- // hack! if connect$ didn't actually complete, toggle it off
- if (v?.type !== "connected") {
- toggleWalletConnect()
- }
- }),
- )
- : disconnect$,
- ),
- tap((v) => {
- if (v.type === "connected") {
- sessionSubject.setValue(v.session)
- } else {
- sessionSubject.clear()
- }
- }),
- )
-
- return connectState$.pipe(
- startWith(
- (session
- ? {
- type: "connected",
- session,
- }
- : {
- type: "disconnected",
- }) satisfies WalletConnectStatus,
- ),
- )
- }),
- ),
- {
- type: "disconnected",
- },
-)
-
-const getAccounts = (session: SessionTypes.Struct) =>
- Object.values(session.namespaces)
- .map((namespace) => namespace.accounts)
- .flat()
- .map((wcAccount) => wcAccount.split(":")[2])
-
-const getSigner = (session: SessionTypes.Struct, address: string) =>
- getPolkadotSignerFromPjs(
- address,
- async (transactionPayload) => {
- const provider = await firstValueFrom(provider$)
-
- console.log("Topic to check chainId below", session.topic)
-
- return provider.client.request({
- topic: session.topic,
- chainId: `polkadot:${transactionPayload.genesisHash.substring(2, 34)}`,
- request: {
- method: "polkadot_signTransaction",
- params: {
- address,
- transactionPayload,
- },
- },
- })
- },
- async ({ address, data }) => {
- const provider = await firstValueFrom(provider$)
-
- // const chainId = provider.session.topic.split(":")[1];
- const chainId = session.topic.split(":")[1]
-
- return provider.client.request({
- topic: session.topic,
- chainId: `polkadot:${chainId}`,
- request: {
- method: "polkadot_signMessage",
- params: {
- address,
- message: data,
- },
- },
- })
- },
- )
-
-const getSignersFromSession = (
- session: SessionTypes.Struct,
-): Record => {
- const accounts = getAccounts(session)
- return Object.fromEntries(
- accounts.map((address) => [address, getSigner(session, address)]),
- )
-}
-
-export const walletConnectAccounts$ = walletConnectStatus$.pipeState(
- map((status) =>
- status.type === "connected" ? getSignersFromSession(status.session) : {},
- ),
- withDefault({} as Record),
-)
-
-const tapOnLast =
- (onLast: (value: T | null) => void) =>
- (source$: Observable) =>
- defer(() => {
- let value: T | null = null
- return source$.pipe(
- tap({
- next(v) {
- value = v
- },
- complete() {
- onLast(value)
- },
- }),
- )
- })