feat: submit unsigned transaction

fix crash when runtime call panics
This commit is contained in:
Victor Oliva
2024-12-13 15:34:04 +01:00
parent 319ace5cf1
commit 2bc1cea88c
8 changed files with 143 additions and 86 deletions
@@ -1,66 +0,0 @@
import { unsafeApi$ } from "@/state/chains/chain.state"
import { ActionButton } from "@/components/ActionButton"
import { onNexTx } from "@/pages/Transactions"
import { useStateObservable } from "@react-rxjs/core"
import { Binary } from "polkadot-api"
import { FC, useState } from "react"
import { noop } from "rxjs"
import { AccountProvider, selectedAccount$ } from "./AccountProvider"
import { ExtensionProvider } from "./ExtensionProvider"
import { Spinner } from "@/components/Icons"
import { twMerge } from "tailwind-merge"
const SignAndSubmit: FC<{ callData: string; onClose: () => void }> = ({
callData,
onClose,
}) => {
const account = useStateObservable(selectedAccount$)
const [isSigning, setIsSigning] = useState(false)
if (!account) return null
return (
<ActionButton
onClick={() => {
let nClients = 0
const subscription = unsafeApi$.subscribe((client) => {
nClients++
if (nClients > 1) return subscription.unsubscribe()
setIsSigning(true)
client
.txFromCallData(Binary.fromHex(callData))
.then((x) => {
if (nClients === 1)
return x.sign(account.polkadotSigner).then((s) => {
onClose()
if (nClients === 1) onNexTx(s)
})
}, noop)
.finally(() => {
subscription.unsubscribe()
setIsSigning(false)
})
})
}}
className="flex gap-2 items-center justify-center"
>
<span className={twMerge("ml-4", isSigning ? "" : "mr-6")}>
Sign and Submit
</span>
{isSigning && <Spinner size={16} />}
</ActionButton>
)
}
export default function SelectAccountFromExtension(props: {
callData: string
onClose: () => void
}) {
return (
<>
<ExtensionProvider />
<AccountProvider />
<SignAndSubmit {...props} />
</>
)
}
+2 -4
View File
@@ -9,9 +9,7 @@ import { toHex } from "@polkadot-api/utils"
import { HexString } from "polkadot-api"
import React, { lazy, Suspense, useState } from "react"
const SelectAccountFromExtension = lazy(
() => import("./SelectAccountFromExtension"),
)
const SendTransactionForm = lazy(() => import("./SubmitTxForm"))
export const ExtrinsicModal: React.FC<{
callData: Uint8Array | HexString | undefined
@@ -36,7 +34,7 @@ export const ExtrinsicModal: React.FC<{
>
<DialogTitle>Create TX</DialogTitle>
<Suspense fallback="Loading…">
<SelectAccountFromExtension
<SendTransactionForm
callData={
callData instanceof Uint8Array ? toHex(callData) : callData!
}
@@ -0,0 +1,86 @@
import { ActionButton } from "@/components/ActionButton"
import { Spinner } from "@/components/Icons"
import { trackSignedTx, trackUnsignedTx } from "@/pages/Transactions"
import { unsafeApi$ } from "@/state/chains/chain.state"
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 { 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 }> = ({
callData,
onClose,
}) => {
const account = useStateObservable(selectedAccount$)
const [isSigning, setIsSigning] = useState(false)
return (
<ActionButton
onClick={async () => {
setIsSigning(true)
try {
const unsafeApi = await firstValueFrom(unsafeApi$)
const tx = await unsafeApi.txFromCallData(Binary.fromHex(callData))
const signedExtrinsic = await tx.sign(account!.polkadotSigner)
trackSignedTx(signedExtrinsic)
onClose()
} catch (ex) {
console.error(ex)
}
setIsSigning(false)
}}
className="flex gap-2 items-center justify-center"
disabled={!account}
>
<span className={twMerge("ml-6", isSigning ? "" : "mr-6")}>
Sign and Submit
</span>
{isSigning && <Spinner size={16} />}
</ActionButton>
)
}
const SubmitUnsigned: FC<{ callData: string; onClose: () => void }> = ({
callData,
onClose,
}) => {
return (
<ActionButton
onClick={() => {
const data = fromHex(callData)
const unsignedTx = mergeUint8(
compactNumber.enc(data.length + 1),
new Uint8Array([4]),
data,
)
trackUnsignedTx(toHex(unsignedTx))
onClose()
}}
className="flex gap-2 items-center justify-center"
>
Submit without signing
</ActionButton>
)
}
export default function SubmitTxF(props: {
callData: string
onClose: () => void
}) {
return (
<>
<ExtensionProvider />
<AccountProvider />
<div className="flex flex-col gap-2">
<SignAndSubmit {...props} />
<div className="text-center">Or</div>
<SubmitUnsigned {...props} />
</div>
</>
)
}
@@ -75,6 +75,15 @@ const ResultDisplay: FC<{
runtimeCallResult: RuntimeCallResult
mode: "json" | "decoded"
}> = ({ runtimeCallResult, mode }) => {
if ("error" in runtimeCallResult) {
return (
<div className="text-sm">
<div>The call crashed</div>
<div>Message: {runtimeCallResult.error.message ?? "N/A"}</div>
</div>
)
}
if (!("result" in runtimeCallResult)) {
return <div className="text-sm text-foreground/50">Loading…</div>
}
+22 -5
View File
@@ -5,7 +5,16 @@ import {
partitionByKey,
toKeySet,
} from "@react-rxjs/utils"
import { from, map, Observable, startWith, switchMap, takeUntil } from "rxjs"
import {
catchError,
from,
map,
Observable,
of,
startWith,
switchMap,
takeUntil,
} from "rxjs"
import { v4 as uuid } from "uuid"
export type RuntimeCallMetadataMethod = {
@@ -34,8 +43,8 @@ export const [removeRuntimeCallResult$, removeRuntimeCallResult] =
export type RuntimeCallResult = {
name: string
type: number
} & ({ result: unknown } | {})
const [getStorageSubscription$, storageSubscriptionKeyChange$] = partitionByKey(
} & ({ result: unknown } | { error?: any })
const [getRuntimeCallSubscription$, runtimeCallKeyChange$] = partitionByKey(
newRuntimeCallQuery$,
() => uuid(),
(src$, id) =>
@@ -48,6 +57,13 @@ const [getStorageSubscription$, storageSubscriptionKeyChange$] = partitionByKey(
result,
paused: false,
})),
catchError((ex) => {
console.error(ex)
return of({
...props,
error: ex,
})
}),
startWith(props),
),
),
@@ -56,7 +72,7 @@ const [getStorageSubscription$, storageSubscriptionKeyChange$] = partitionByKey(
)
export const runtimeCallResultKeys$ = state(
storageSubscriptionKeyChange$.pipe(
runtimeCallKeyChange$.pipe(
toKeySet(),
map((keys) => [...keys].reverse()),
),
@@ -64,6 +80,7 @@ export const runtimeCallResultKeys$ = state(
)
export const runtimeCallResult$ = state(
(key: string): Observable<RuntimeCallResult> => getStorageSubscription$(key),
(key: string): Observable<RuntimeCallResult> =>
getRuntimeCallSubscription$(key),
null,
)
+1 -1
View File
@@ -1,5 +1,5 @@
import { grouppedTransactions$ } from "./transactions.state"
export * from "./Transactions"
export { onNexTx } from "./transactions.state"
export { trackSignedTx, trackUnsignedTx } from "./transactions.state"
export const transactions$ = grouppedTransactions$
+12 -6
View File
@@ -1,6 +1,11 @@
import { chainClient$ } from "@/state/chains/chain.state"
import { state } from "@react-rxjs/core"
import { combineKeys, createSignal, partitionByKey } from "@react-rxjs/utils"
import {
combineKeys,
createSignal,
mergeWithKey,
partitionByKey,
} from "@react-rxjs/utils"
import { HexString, InvalidTxError, TxBroadcastEvent } from "polkadot-api"
import {
catchError,
@@ -13,20 +18,21 @@ import {
withLatestFrom,
} from "rxjs"
const [signedTx$, onNexTx] = createSignal<HexString>()
export { onNexTx }
const [signedTx$, trackSignedTx] = createSignal<HexString>()
const [unsignedTx$, trackUnsignedTx] = createSignal<HexString>()
export { trackSignedTx, trackUnsignedTx }
const transactions$ = signedTx$.pipe(
const transactions$ = mergeWithKey({ signedTx$, unsignedTx$ }).pipe(
withLatestFrom(chainClient$),
mergeMap(([tx, { client }]) => {
const submitAndWatch = client.submitAndWatch as (
tx: HexString,
at: string,
withSigned: boolean,
withSigned?: boolean,
) => Observable<TxBroadcastEvent>
let txHash: string = ""
return submitAndWatch(tx, "finalized", true).pipe(
return submitAndWatch(tx.payload, "finalized", true).pipe(
tap((e) => {
txHash = e.txHash
}),
+11 -4
View File
@@ -30,6 +30,7 @@ import {
WebsocketSource,
} from "./websocket"
import { getHashParams, setHashParams } from "@/hashParams"
import { withLogsRecorder } from "polkadot-api/logs-provider"
export type ChainSource = WebsocketSource | SmoldotSource
@@ -44,10 +45,16 @@ export const getChainSource = ({
endpoint === "light-client"
? createSmoldotSource(id, relayChain)
: createWebsocketSource(id, endpoint)
export const getProvider = (source: ChainSource) =>
source.type === "websocket"
? getWebsocketProvider(source)
: getSmoldotProvider(source)
export const getProvider = (source: ChainSource) => {
const provider =
source.type === "websocket"
? getWebsocketProvider(source)
: getSmoldotProvider(source)
return import.meta.env.DEV
? withLogsRecorder(console.debug, provider)
: provider
}
export const [selectedChainChanged$, onChangeChain] =
createSignal<SelectedChain>()