Skip to content

feat: update components to add crosschain redemption #843

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

Draft
wants to merge 2 commits into
base: releases/mainnet/v2.3.x
Choose a base branch
from
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
23 changes: 12 additions & 11 deletions src/components/Modal/tBTC/InitiateUnminting.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,20 +49,21 @@ const InitiateUnmintingBase: FC<InitiateUnmintingProps> = ({
const { estimatedBTCAmount, thresholdNetworkFee } =
useRedemptionEstimatedFees(unmintAmount)
const threshold = useThreshold()
const isCrossChain = threshold.config.crossChain.isCrossChain

const onSuccess: OnSuccessCallback = (receipt, additionalParams) => {
//@ts-ignore
const { walletPublicKey } = additionalParams
if (walletPublicKey) {
navigate(
buildRedemptionDetailsLink(
receipt.transactionHash,
account!,
walletPublicKey,
btcAddress,
threshold.tbtc.bitcoinNetwork
)
)
const { walletPublicKey, chainName } = additionalParams
const link = buildRedemptionDetailsLink(
account!,
btcAddress,
threshold.tbtc.bitcoinNetwork,
!isCrossChain ? receipt.transactionHash : undefined,
walletPublicKey ?? undefined,
chainName ?? undefined
)
if (link) {
navigate(link)
}
closeModal()
}
Expand Down
52 changes: 35 additions & 17 deletions src/contexts/ThresholdContext.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
import { createContext, FC, useContext, useEffect, useRef } from "react"
import {
createContext,
FC,
useContext,
useEffect,
useRef,
useState,
} from "react"
import { getThresholdLibProvider, threshold } from "../utils/getThresholdLib"
import { useLedgerLiveApp } from "./LedgerLiveAppContext"
import { useIsActive } from "../hooks/useIsActive"
import { useIsEmbed } from "../hooks/useIsEmbed"
import { getEthereumDefaultProviderChainId } from "../utils/getEnvVariable"
import { useWeb3React } from "@web3-react/core"
import { ChainName } from "../threshold-ts/types"
import { isL2Network } from "../networks/utils"
import {
getEthereumNetworkNameFromChainId,
isL2Network,
} from "../networks/utils"
import { useNonEVMConnection } from "../hooks/useNonEVMConnection"

const defaultCrossChainConfig = {
Expand All @@ -22,6 +32,7 @@ export const useThreshold = () => {
}

export const ThresholdProvider: FC = ({ children }) => {
const [thresholdState, setThresholdState] = useState(threshold)
const { library } = useWeb3React()
const hasThresholdLibConfigBeenUpdated = useRef(false)
const { ledgerLiveAppEthereumSigner } = useLedgerLiveApp()
Expand All @@ -30,6 +41,13 @@ export const ThresholdProvider: FC = ({ children }) => {
useNonEVMConnection()
const { isEmbed } = useIsEmbed()

useEffect(() => {
const unsubscribe = threshold.subscribe(() =>
setThresholdState(Object.create(threshold))
)
return unsubscribe
}, [])

useEffect(() => {
if (isActive && chainId) {
threshold.updateConfig({
Expand All @@ -44,13 +62,25 @@ export const ThresholdProvider: FC = ({ children }) => {
bitcoin: threshold.config.bitcoin,
crossChain: {
...defaultCrossChainConfig,
chainName: isL2Network(chainId) ? ChainName.Ethereum : null,
chainName: getEthereumNetworkNameFromChainId(chainId) as ChainName,
isCrossChain: isL2Network(chainId),
},
})
hasThresholdLibConfigBeenUpdated.current = true
}

if (isNonEVMActive) {
threshold.updateConfig({
ethereum: threshold.config.ethereum,
bitcoin: threshold.config.bitcoin,
crossChain: {
isCrossChain: true,
chainName: nonEVMChainName as Exclude<ChainName, ChainName.Ethereum>,
nonEVMProvider: nonEVMProvider,
},
})
}

if (!isActive && hasThresholdLibConfigBeenUpdated.current) {
threshold.updateConfig({
ethereum: {
Expand All @@ -61,23 +91,11 @@ export const ThresholdProvider: FC = ({ children }) => {
},
bitcoin: threshold.config.bitcoin,
crossChain: {
...threshold.config.crossChain,
...defaultCrossChainConfig,
},
})
hasThresholdLibConfigBeenUpdated.current = false
}

if (isNonEVMActive) {
threshold.updateConfig({
ethereum: threshold.config.ethereum,
bitcoin: threshold.config.bitcoin,
crossChain: {
isCrossChain: true,
chainName: nonEVMChainName as Exclude<ChainName, ChainName.Ethereum>,
nonEVMProvider: nonEVMProvider,
},
})
}
}, [
isActive,
account,
Expand All @@ -89,7 +107,7 @@ export const ThresholdProvider: FC = ({ children }) => {
])

return (
<ThresholdContext.Provider value={threshold}>
<ThresholdContext.Provider value={thresholdState}>
{children}
</ThresholdContext.Provider>
)
Expand Down
4 changes: 4 additions & 0 deletions src/hooks/tbtc/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
export * from "./useFetchDepositDetails"
export * from "./useFetchTBTCMetrics"
export * from "./useFetchRecentDeposits"
export * from "./useFetchTBTCMetrics"
export * from "./useRedemptionEstimatedFees"
export * from "./useRequestRedemption"
export * from "./useRevealDepositTransaction"
export * from "./useApproveL2TBTCToken"
export * from "./useSubscribeToOptimisticMintingFinalizedEvent"
export * from "./useSubscribeToOptimisticMintingRequestedEvent"
export * from "./useSubscribeToRedemptionRequestedEvent"
Expand All @@ -13,3 +15,5 @@ export * from "./useTBTCVaultContract"
export * from "./useSubscribeToRedemptionsCompletedEvent"
export * from "./useFindRedemptionInBitcoinTx"
export * from "./useStarknetTBTCBalance"
export * from "./useFetchCrossChainRedemptionDetails"
export * from "./useSubscribeToL1BitcoinRedeemerRedemptionRequestedEvent"
22 changes: 22 additions & 0 deletions src/hooks/tbtc/useApproveL2TBTCToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { useThreshold } from "../../contexts/ThresholdContext"
import {
OnErrorCallback,
OnSuccessCallback,
useSendTransactionFromFn,
} from "../../web3/hooks"

export const useApproveL2TBTCToken = (
onSuccess?: OnSuccessCallback,
onError?: OnErrorCallback
) => {
const threshold = useThreshold()
const pendingText =
"Approving tBTC for cross-chain redemption. Please sign in your wallet."

return useSendTransactionFromFn(
threshold.tbtc.approveL2TBTCToken,
onSuccess,
onError,
pendingText
)
}
198 changes: 198 additions & 0 deletions src/hooks/tbtc/useFetchCrossChainRedemptionDetails.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
import { useEffect, useState } from "react"
import { useThreshold } from "../../contexts/ThresholdContext"
import {
isValidType,
fromSatoshiToTokenPrecision,
getContractPastEvents,
} from "../../threshold-ts/utils"
import { useGetBlock } from "../../web3/hooks"
import { isEmptyOrZeroAddress } from "../../web3/utils"
import { useFindRedemptionInBitcoinTx } from "./useFindRedemptionInBitcoinTx"

interface CrossChainRedemptionDetails {
requestedAmount: string // in token precision
receivedAmount?: string // in satoshi
redemptionRequestedTxHash: string
redemptionCompletedTxHash?: {
chain: string
bitcoin: string
}
requestedAt: number
completedAt?: number
treasuryFee: string // in token precision
isTimedOut: boolean
redemptionTimedOutTxHash?: string
btcAddress?: string
walletPublicKeyHash: string
redemptionKey: string
}

type FetchRedemptionDetailsParamType = string | null | undefined

export const useFetchCrossChainRedemptionDetails = (
redeemerOutputScript: FetchRedemptionDetailsParamType,
redeemer: FetchRedemptionDetailsParamType
) => {
const threshold = useThreshold()
const getBlock = useGetBlock()
const findRedemptionInBitcoinTx = useFindRedemptionInBitcoinTx()
const [isFetching, setIsFetching] = useState(false)
const [error, setError] = useState("")
const [redemptionData, setRedemptionData] = useState<
CrossChainRedemptionDetails | undefined
>()

useEffect(() => {
setError("")
if (!redeemer || isEmptyOrZeroAddress(redeemer)) {
setError("Invalid redeemer value.")
return
}

if (!redeemerOutputScript || !isValidType("bytes", redeemerOutputScript)) {
setError("Invalid redeemerOutputScript value.")
return
}

if (!threshold.tbtc.l1BitcoinRedeemerContract) {
setError("L1 Bitcoin Redeemer contract not initialized.")
return
}

const fetch = async () => {
setIsFetching(true)
try {
// Get RedemptionRequested events from L1BTCRedeemerWormhole filtered by redeemerOutputScript
const redemptionRequestedEvents = await getContractPastEvents(
threshold.tbtc.l1BitcoinRedeemerContract!,
{
eventName: "RedemptionRequested",
// Filter by indexed redemptionOutputScript parameter (4th parameter in event)
filterParams: [null, null, null, redeemerOutputScript],
fromBlock: 0, // You might want to optimize this with a more recent block
}
)

if (redemptionRequestedEvents.length === 0) {
throw new Error("Cross-chain redemption not found...")
}

// Get the most recent event
const redemptionRequestedEvent =
redemptionRequestedEvents[redemptionRequestedEvents.length - 1]

// Extract data from event
const redemptionKey = redemptionRequestedEvent.args?.redemptionKey
const walletPublicKeyHash =
redemptionRequestedEvent.args?.walletPubKeyHash
const amount = redemptionRequestedEvent.args?.amount
const mainUtxo = redemptionRequestedEvent.args?.mainUtxo

const { timestamp: redemptionRequestedEventTimestamp } = await getBlock(
redemptionRequestedEvent.blockNumber
)

// Build redemption key to check status
const computedRedemptionKey = threshold.tbtc.buildRedemptionKey(
walletPublicKeyHash,
redeemerOutputScript
)

// Check if the redemption has pending or timedOut status
const { isPending, isTimedOut, requestedAt } =
await threshold.tbtc.getRedemptionRequest(computedRedemptionKey)

// Find timeout event if timed out
const timedOutTxHash: undefined | string = isTimedOut
? (
await threshold.tbtc.getRedemptionTimedOutEvents({
walletPublicKeyHash,
fromBlock: redemptionRequestedEvent.blockNumber,
})
).find(
(event) => event.redeemerOutputScript === redeemerOutputScript
)?.txHash
: undefined

if (
(isTimedOut || isPending) &&
requestedAt === redemptionRequestedEventTimestamp
) {
setRedemptionData({
requestedAmount: fromSatoshiToTokenPrecision(amount).toString(),
redemptionRequestedTxHash: redemptionRequestedEvent.transactionHash,
redemptionCompletedTxHash: undefined,
requestedAt: requestedAt,
redemptionTimedOutTxHash: timedOutTxHash,
treasuryFee: "0", // Treasury fee is not available in L1BTCRedeemerWormhole event
isTimedOut,
walletPublicKeyHash: walletPublicKeyHash,
redemptionKey: computedRedemptionKey,
})
return
}

// If redemption was completed, find the completion event
const redemptionCompletedEvents =
await threshold.tbtc.getRedemptionsCompletedEvents({
walletPublicKeyHash,
fromBlock: redemptionRequestedEvent.blockNumber,
})

for (const {
redemptionBitcoinTxHash,
txHash,
blockNumber: redemptionCompletedBlockNumber,
} of redemptionCompletedEvents) {
const redemptionBitcoinTransfer = await findRedemptionInBitcoinTx(
redemptionBitcoinTxHash,
redemptionCompletedBlockNumber,
redeemerOutputScript
)

if (!redemptionBitcoinTransfer) continue

const { receivedAmount, redemptionCompletedTimestamp, btcAddress } =
redemptionBitcoinTransfer

setRedemptionData({
requestedAmount: fromSatoshiToTokenPrecision(amount).toString(),
receivedAmount,
redemptionRequestedTxHash: redemptionRequestedEvent.transactionHash,
redemptionCompletedTxHash: {
chain: txHash,
bitcoin: redemptionBitcoinTxHash,
},
requestedAt: redemptionRequestedEventTimestamp,
completedAt: redemptionCompletedTimestamp,
treasuryFee: "0",
isTimedOut: false,
btcAddress,
walletPublicKeyHash: walletPublicKeyHash,
redemptionKey: computedRedemptionKey,
})

return
}
} catch (error) {
console.error(
"Could not fetch the cross-chain redemption request details!",
error
)
setError((error as Error).toString())
} finally {
setIsFetching(false)
}
}

fetch()
}, [
redeemerOutputScript,
redeemer,
threshold,
getBlock,
findRedemptionInBitcoinTx,
])

return { isFetching, data: redemptionData, error }
}
Loading