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

Integrating Dflow Declarative Swaps with Helium Wallet #857

Draft
wants to merge 4 commits into
base: main
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"@babel/preset-typescript": "7.21.0",
"@bonfida/spl-name-service": "1.1.1",
"@coral-xyz/anchor": "0.28.0",
"@dflow-protocol/swap-api-utils": "^0.1.2",
"@gorhom/bottom-sheet": "5.0.4",
"@gorhom/portal": "1.0.14",
"@graphql-codegen/cli": "5.0.0",
Expand Down
199 changes: 199 additions & 0 deletions src/config/storage/DFlowProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
import { useCurrentWallet } from '@hooks/useCurrentWallet'
import {
monitorOrder,
MonitorOrderResult,
SubmitIntentResponse,
} from '@dflow-protocol/swap-api-utils'
import { Transaction, Connection } from '@solana/web3.js'
import React, {
createContext,
useCallback,
useContext,
useMemo,
useState,
} from 'react'
import * as Logger from '@utils/logger'

const AGGREGATOR_API_BASE_URL = 'https://quote-api.dflow.net'

interface IntentParams {
userPublicKey?: string
inputMint: string
outputMint: string
amount: string
slippageBps?: number
wrapAndUnwrapSol?: boolean
feeBudget?: string
}

export interface Intent {
inputMint: string
inAmount: string
outputMint: string
outAmount: string
otherAmountThreshold: string
slippageBps: number
platformFee: { amount: string; feeBps: number; feeAccount: string } | null
feeBudget: number
priceImpactPct: string
openTransaction?: string
lastValidBlockHeight?: number
expiry?: { slotsAfterOpen: number }
requestUrl: string
requestParams: IntentParams
}

interface IDFlowContextState {
loading: boolean
error: unknown
intent?: Intent

getQuote: (opts: {
inputMint: string
outputMint: string
amount: string
slippageBps: number
}) => Promise<Intent | undefined>

signIntent: (intentData: Intent) => Promise<Transaction>

submitIntent: (opts: {
quoteResponse: Intent
signedOpenTransaction: Transaction
}) => Promise<SubmitIntentResponse | undefined>

monitorOrder: (params: {
connection: Connection
intent: Intent
signedOpenTransaction: Transaction
submitIntentResponse: SubmitIntentResponse
}) => Promise<MonitorOrderResult>
}

const DFlowContext = createContext<IDFlowContextState | null>(null)

export const DFlowProvider: React.FC<React.PropsWithChildren> = ({
children,
}) => {
const wallet = useCurrentWallet()
const [loading, setLoading] = useState(false)
const [error, setError] = useState<unknown>()
const [intent, setIntent] = useState<Intent>()

const getQuote = useCallback(
async (opts: {
inputMint: string
outputMint: string
amount: string
slippageBps: number
}) => {
let foundIntent: Intent | undefined

try {
setLoading(true)

const queryParams = new URLSearchParams()
queryParams.append('inputMint', opts.inputMint)
queryParams.append('outputMint', opts.outputMint)
queryParams.append('amount', opts.amount)

if (wallet) {
queryParams.append('userPublicKey', wallet.toBase58())
}

queryParams.append('slippageBps', opts.slippageBps.toString())

const response = await fetch(
`${AGGREGATOR_API_BASE_URL}/intent?${queryParams.toString()}`,
)

if (!response.ok) {
throw new Error(`Failed to get quote: ${response.statusText}`)
}

foundIntent = await response.json()
setIntent(foundIntent)
} catch (err: unknown) {
Logger.error(err)
setError(err)
} finally {
setLoading(false)
}

return foundIntent
},
[wallet],
)

const signIntent = useCallback(
async (intentData: Intent): Promise<Transaction> => {
if (!intentData.openTransaction) {
throw new Error('No open transaction found in intent data')
}

const transactionBytes = Buffer.from(intentData.openTransaction, 'base64')
const openTransaction = Transaction.from(transactionBytes)

return openTransaction
},
[],
)

const submitIntent = useCallback(
async (opts: {
quoteResponse: Intent
signedOpenTransaction: Transaction
}): Promise<SubmitIntentResponse | undefined> => {
try {
const response = await fetch(
`${AGGREGATOR_API_BASE_URL}/submit-intent`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
quoteResponse: opts.quoteResponse,
signedOpenTransaction: Buffer.from(
opts.signedOpenTransaction.serialize(),
).toString('base64'),
}),
},
)

if (!response.ok) {
throw new Error(`Failed to submit intent: ${response.statusText}`)
}

return await response.json()
} catch (err: unknown) {
Logger.error(err)
setError(err)
}
},
[],
)

const value = useMemo(
() => ({
loading,
error,
intent,
getQuote,
signIntent,
submitIntent,
monitorOrder,
}),
[loading, error, intent, getQuote, signIntent, submitIntent],
)

return <DFlowContext.Provider value={value}>{children}</DFlowContext.Provider>
}

export const useDFlow = () => {
const context = useContext(DFlowContext)
if (!context) {
throw new Error('useDFlow must be used within a DFlowProvider')
}
return context
}
124 changes: 0 additions & 124 deletions src/config/storage/JupiterProvider.tsx

This file was deleted.

6 changes: 3 additions & 3 deletions src/features/swaps/SwapNavigator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {
createNativeStackNavigator,
NativeStackNavigationOptions,
} from '@react-navigation/native-stack'
import { JupiterProvider } from '@config/storage/JupiterProvider'
import { DFlowProvider } from '@config/storage/DFlowProvider'
import React, { memo, useMemo } from 'react'
import SwappingScreen from './SwappingScreen'
import SwapScreen from './SwapScreen'
Expand All @@ -19,12 +19,12 @@ const SwapStackScreen = () => {
)

return (
<JupiterProvider>
<DFlowProvider>
<SwapStack.Navigator screenOptions={cardPresentation}>
<SwapStack.Screen name="SwapScreen" component={SwapScreen} />
<SwapStack.Screen name="SwappingScreen" component={SwappingScreen} />
</SwapStack.Navigator>
</JupiterProvider>
</DFlowProvider>
)
}
export default memo(SwapStackScreen)
Loading