Skip to content
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

Fix bitcoin bugs #317

Merged
merged 3 commits into from
Oct 23, 2024
Merged
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
6 changes: 6 additions & 0 deletions .changeset/wicked-beans-reply.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@reservoir0x/relay-sdk': patch
'@reservoir0x/relay-kit-ui': patch
---

Fix bugs with bitcoin implementation
28 changes: 20 additions & 8 deletions packages/sdk/src/utils/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,19 +204,31 @@ export async function sendTransactionSafely(
}
}

//If the time estimate of the tx is greater than the maximum attempts we should skip polling confirmation
const timeEstimateMs =
((details?.timeEstimate ?? 0) + (chainId === 8253038 ? 600 : 0)) * 1000
const maximumWaitTimeInMs = maximumAttempts * pollingInterval

if (timeEstimateMs > maximumWaitTimeInMs) {
//If the origin chain is bitcoin, skip polling for confirmation, because the deposit will take too long
if (chainId === 8253038) {
return true
}

//Sequence internal functions
if (step.id === 'approve') {
// We want synchronous execution in the following cases:
// - Approval Signature step required first
// - Bitcoin is the destination
// - Canonical route used
if (
step.id === 'approve' ||
details?.currencyOut?.currency?.chainId === 8253038 ||
request?.data?.useExternalLiquidity
) {
await waitForTransaction().promise
await pollForConfirmation()
//In the following cases we want to skip polling for confirmation:
// - Bitcoin destination chain, we want to skip polling for confirmation as the block times are lengthy
// - Canonical route, also lengthy fill time
if (
details?.currencyOut?.currency?.chainId !== 8253038 &&
!request?.data?.useExternalLiquidity
) {
await pollForConfirmation()
}
} else {
const { promise: receiptPromise, controller: receiptController } =
waitForTransaction()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export type TokenSelectorProps = {
export type EnhancedCurrencyList = {
chains: (CurrencyList[number] & {
relayChain: RelayChain
balance?: DuneBalanceResponse['balances'][0]
balance?: NonNullable<DuneBalanceResponse>['balances'][0]
})[]
totalValueUsd?: number
totalBalance?: bigint
Expand Down
2 changes: 1 addition & 1 deletion packages/ui/src/components/widgets/SwapWidget/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -857,7 +857,7 @@ const SwapWidget: FC<SwapWidgetProps> = ({
hasInsufficientBalance={hasInsufficientBalance}
error={error}
quote={price}
currency={toToken}
currency={fromToken}
isHighRelayerServiceFee={highRelayerServiceFee}
isCapacityExceededError={isCapacityExceededError}
isCouldNotExecuteError={isCouldNotExecuteError}
Expand Down
3 changes: 2 additions & 1 deletion packages/ui/src/hooks/useBitcoinBalance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ export default (address?: string, queryOptions?: Partial<QueryOptions>) => {
const balanceResponse = response as BitcoinBalanceResponse
const fundedTxo = balanceResponse.chain_stats.funded_txo_sum
const spentTxo = balanceResponse.chain_stats.spent_txo_sum
balance = BigInt(fundedTxo) - BigInt(spentTxo)
const inflightTxo = balanceResponse.mempool_stats.spent_txo_sum
balance = BigInt(fundedTxo) - BigInt(spentTxo) - BigInt(inflightTxo)
}
return balance
})
Expand Down
28 changes: 19 additions & 9 deletions packages/ui/src/hooks/useDuneBalances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import {
type DefaultError,
type QueryKey
} from '@tanstack/react-query'
import { solana, solanaAddressRegex } from '../utils/solana.js'
import { isSolanaAddress, solana } from '../utils/solana.js'
import { isBitcoinAddress } from '../utils/bitcoin.js'

export type DuneBalanceResponse = {
request_time: string
Expand All @@ -22,7 +23,7 @@ export type DuneBalanceResponse = {
price_usd?: number
value_usd?: number
}>
}
} | null

type QueryType = typeof useQuery<
DuneBalanceResponse,
Expand All @@ -35,7 +36,8 @@ type QueryOptions = Parameters<QueryType>['0']
export default (address?: string, queryOptions?: Partial<QueryOptions>) => {
const providerOptions = useContext(ProviderOptionsContext)
const queryKey = ['useDuneBalances', address]
const isSvmAddress = address && solanaAddressRegex.test(address)
const isSvmAddress = isSolanaAddress(address ?? '')
const isBvmAddress = isBitcoinAddress(address ?? '')

const response = (useQuery as QueryType)({
queryKey: ['useDuneBalances', address],
Expand All @@ -45,6 +47,10 @@ export default (address?: string, queryOptions?: Partial<QueryOptions>) => {
url = `https://api.dune.com/api/beta/balance/solana/${address}?chain_ids=all`
}

if (isBvmAddress) {
return null
}

return fetch(url, {
headers: {
'X-DUNE-API-KEY': providerOptions.duneApiKey
Expand All @@ -54,7 +60,7 @@ export default (address?: string, queryOptions?: Partial<QueryOptions>) => {
.then((response) => {
if (response.balances) {
const balances =
response.balances as DuneBalanceResponse['balances']
response.balances as NonNullable<DuneBalanceResponse>['balances']
if (balances) {
balances
.filter((balance) => {
Expand Down Expand Up @@ -88,17 +94,21 @@ export default (address?: string, queryOptions?: Partial<QueryOptions>) => {
return response
})
},
enabled: address !== undefined && providerOptions.duneApiKey !== undefined,
...queryOptions
...queryOptions,
enabled:
address !== undefined &&
providerOptions.duneApiKey !== undefined &&
queryOptions?.enabled &&
!isBvmAddress
})

response.data?.balances?.forEach((balance) => {
response?.data?.balances?.forEach((balance) => {
if (!balance.chain_id && balance.chain === 'solana') {
balance.chain_id = solana.id
}
})

const balanceMap = response.data?.balances?.reduce(
const balanceMap = response?.data?.balances?.reduce(
(balanceMap, balance) => {
if (balance.address === 'native') {
balance.address =
Expand All @@ -114,7 +124,7 @@ export default (address?: string, queryOptions?: Partial<QueryOptions>) => {
balanceMap[`${chainId}:${balance.address}`] = balance
return balanceMap
},
{} as Record<string, DuneBalanceResponse['balances'][0]>
{} as Record<string, NonNullable<DuneBalanceResponse>['balances'][0]>
)

return { ...response, balanceMap, queryKey } as ReturnType<QueryType> & {
Expand Down
21 changes: 5 additions & 16 deletions packages/ui/src/utils/quote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,26 +216,15 @@ export const extractQuoteId = (steps?: Execute['steps']) => {
return ''
}

export const calculateTimeEstimate = (breakdown?: Execute['breakdown']) => {
const time =
breakdown?.reduce((total, breakdown) => {
return total + (breakdown.timeEstimate ?? 0)
}, 0) ?? 0
const formattedTime = formatSeconds(time)

return {
time,
formattedTime
}
}

export const calculatePriceTimeEstimate = (
details?: PriceResponse['details']
) => {
const isBitcoin = details?.currencyIn?.currency?.chainId === bitcoin.id
const isBitcoin =
details?.currencyIn?.currency?.chainId === bitcoin.id ||
details?.currencyOut?.currency?.chainId === bitcoin.id

//Add 10m origin because of the origin deposit time
const time = (details?.timeEstimate ?? 0) + (isBitcoin ? 600 : 0)
//If the relay is interacting with bitcoin we hardcode the time estime to 10m
const time = isBitcoin ? 600 : details?.timeEstimate ?? 0
const formattedTime = formatSeconds(time)

return {
Expand Down