Skip to content

Commit

Permalink
Refactor callback (#130)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tbaut authored Sep 13, 2024
1 parent cf2f737 commit 5e9b510
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 75 deletions.
24 changes: 11 additions & 13 deletions src/components/MyDelegations.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { Button } from './ui/button'
import { useAccounts } from '@/contexts/AccountsContext'
import { Transaction } from 'polkadot-api'
import { DelegationByAmountConviction } from './DelegationByAmountConviction'
import { toast } from 'sonner'
import { useGetSigningCallback } from '@/hooks/useGetSigningCallback'

export const MyDelegations = () => {
const { api } = useNetwork()
Expand Down Expand Up @@ -42,6 +42,7 @@ export const MyDelegations = () => {
return result
}, [delegations])

const getSubscriptionCallback = useGetSigningCallback()
const onUndelegate = useCallback(
(delegate: string) => {
if (!api || !selectedAccount || !delegations) return
Expand All @@ -62,23 +63,20 @@ export const MyDelegations = () => {
tx = api.tx.Utility.batch({ calls: batchTx })
}

tx.signSubmitAndWatch(selectedAccount.polkadotSigner).subscribe({
next: (event) => {
console.log(event)
toast.info(`Event ${event.type}`)
if (event.type === 'finalized') {
setDelegatesLoading((prev) => prev.filter((id) => id !== delegate))
refreshLocks()
}
const subscriptionCallback = getSubscriptionCallback({
onError: () => {
setDelegatesLoading((prev) => prev.filter((id) => id !== delegate))
},
error: (error) => {
console.error(error)
toast.info(`Event Error: ${JSON.stringify(error)}`)
onFinalized: () => {
setDelegatesLoading((prev) => prev.filter((id) => id !== delegate))
refreshLocks()
},
})
tx.signSubmitAndWatch(selectedAccount.polkadotSigner).subscribe(
subscriptionCallback,
)
},
[api, delegations, refreshLocks, selectedAccount],
[api, delegations, getSubscriptionCallback, refreshLocks, selectedAccount],
)

return (
Expand Down
41 changes: 41 additions & 0 deletions src/hooks/useGetSigningCallback.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { DispatchError } from '@polkadot-api/descriptors'
import { TxEvent } from 'polkadot-api'
import { toast } from 'sonner'

interface Props {
onInBlock?: () => void
onFinalized?: () => void
onError?: () => void
}

export const useGetSigningCallback =
() =>
({ onError, onFinalized, onInBlock }: Props) => {
return {
next: (event: TxEvent) => {
const promise = () =>
new Promise((resolve) => setTimeout(resolve, 2000))

if (event.type === 'broadcasted') {
toast.promise(promise, {
loading: 'Broadcasting tx',
success: 'Tx broadcasted',
duration: 2000,
})
}
if (event.type === 'txBestBlocksState') {
toast.success(`Tx in block`)
}
onInBlock && onInBlock()
if (event.type === 'finalized') {
toast.success(`Tx finalized in block: ${event.block.number}`)
onFinalized && onFinalized()
}
},
error: (error: DispatchError) => {
console.error(error)
toast.error(`Error: ${JSON.stringify(error)}`)
onError && onError()
},
}
}
59 changes: 26 additions & 33 deletions src/pages/Delegate/MultiTransactionDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { DelegateTxs } from '@/hooks/useGetDelegateTx'
import { useTestTx } from '@/hooks/useTestTx'
import { useState } from 'react'
import { TooLargeDialog } from './TooLargeDialog'
import { useGetSigningCallback } from '@/hooks/useGetSigningCallback'

interface Props {
isOpen: boolean
Expand All @@ -35,6 +36,7 @@ export const MultiTransactionDialog = ({
const { selectedAccount } = useAccounts()
const [waitingForFinalization, setWaitingForFinalization] = useState(false)
const [promptForHelpCallData, setPromptForHelpCallData] = useState('')
const getSubscriptionCallBack = useGetSigningCallback()

const onSign = () => {
step === 1 && onSignStep1()
Expand All @@ -43,6 +45,7 @@ export const MultiTransactionDialog = ({

const onSignStep1 = async () => {
if (!api || !selectedAccount) return
setIsTxInitiated(true)

const step1Txs = api.tx.Utility.batch_all({
calls: [
Expand All @@ -63,24 +66,17 @@ export const MultiTransactionDialog = ({
return
}

setIsTxInitiated(true)
const subscriptionCallBack1 = getSubscriptionCallBack({
onError: () => setIsTxInitiated(false),
onFinalized: () => {
setStep(2)
setIsTxInitiated(false)
},
})

;(await step1Txs)
.signSubmitAndWatch(selectedAccount?.polkadotSigner)
.subscribe((event) => {
console.info(event)

if (event.type === 'txBestBlocksState' && event.found) {
if (event.dispatchError) {
console.error('Tx error', event)
setIsTxInitiated(false)

return
}

setStep(2)
setIsTxInitiated(false)
}
})
.subscribe(subscriptionCallBack1)
}

const onSignStep2 = async () => {
Expand All @@ -106,25 +102,22 @@ export const MultiTransactionDialog = ({
return
}

const subscriptionCallBack2 = getSubscriptionCallBack({
onError: () => {
setIsTxInitiated(false)
setWaitingForFinalization(true)
},
onInBlock: () => setWaitingForFinalization(true),
onFinalized: () => {
onProcessFinished()
setIsTxInitiated(false)
setWaitingForFinalization(false)
},
})

await step2Txs
.signSubmitAndWatch(selectedAccount?.polkadotSigner, { at: 'best' })
.subscribe((event) => {
console.info(event)

if (event.type === 'txBestBlocksState' && event.found) {
if (event.dispatchError) {
console.error('Tx error', event)
setIsTxInitiated(false)
}
setWaitingForFinalization(true)
}

if (event.type === 'finalized') {
onProcessFinished()
setIsTxInitiated(false)
setWaitingForFinalization(false)
}
})
.subscribe(subscriptionCallBack2)
}

if (promptForHelpCallData)
Expand Down
37 changes: 8 additions & 29 deletions src/pages/Delegate/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ import { Button } from '@/components/ui/button'
import { useAccounts } from '@/contexts/AccountsContext'
import { Slider } from '@/components/ui/slider'
import { Link, useLocation, useNavigate, useParams } from 'react-router-dom'
import { toast } from 'sonner'

import { ArrowLeft } from 'lucide-react'
import { msgs } from '@/lib/constants'
import { evalUnits, planckToUnit } from '@polkadot-ui/utils'
Expand All @@ -18,6 +16,7 @@ import { DelegateTxs, useGetDelegateTx } from '@/hooks/useGetDelegateTx'
import { AlertNote } from '@/components/Alert'
import { useTestTx } from '@/hooks/useTestTx'
import { MultiTransactionDialog } from './MultiTransactionDialog'
import { useGetSigningCallback } from '@/hooks/useGetSigningCallback'

export const Delegate = () => {
const { api, assetInfo } = useNetwork()
Expand Down Expand Up @@ -45,6 +44,7 @@ export const Delegate = () => {
const [isMultiTxDialogOpen, setIsMultiTxDialogOpen] = useState(false)
const [delegateTxs, setDelegateTxs] = useState<DelegateTxs>({} as DelegateTxs)
const { refreshLocks } = useLocks()
const getSubscriptionCallBack = useGetSigningCallback()

const { display: convictionTimeDisplay, multiplier: convictionMultiplier } =
getConvictionLockTimeDisplay(convictionNo)
Expand Down Expand Up @@ -165,35 +165,14 @@ export const Delegate = () => {
return
}

const subscriptionCallBack = getSubscriptionCallBack({
onError: () => setIsTxInitiated(false),
onFinalized: () => onProcessFinished(),
})

await allTxs
.signSubmitAndWatch(selectedAccount?.polkadotSigner)
.subscribe((event) => {
let msg: string
switch (event.type) {
case 'signed':
msg = 'Tx signed.'
break
case 'broadcasted':
msg = `Tx broadcasted.`
break
case 'txBestBlocksState':
msg = `Tx in block.`
break
case 'finalized':
msg = `Tx finalized in block: ${event.block.number}`
onProcessFinished()
break
}
toast.info(msg)

if (event.type === 'txBestBlocksState' && event.found) {
if (event.dispatchError) {
console.error('Tx error', event)
toast.error(`Tx error: ${JSON.stringify(event)}`)
setIsTxInitiated(false)
}
}
})
.subscribe(subscriptionCallBack)
}

return (
Expand Down

0 comments on commit 5e9b510

Please sign in to comment.