-
Notifications
You must be signed in to change notification settings - Fork 26
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
feat: add swap ui #166
Draft
Ayoazeez26
wants to merge
3
commits into
AFK-AlignedFamKernel:main
Choose a base branch
from
Ayoazeez26:feat/swap-avnu
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+195
−17
Draft
feat: add swap ui #166
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
import {useState} from 'react'; | ||
import {StyleProp, TextInput, TextStyle, View, ViewStyle} from 'react-native'; | ||
|
||
import {TokenSymbol} from '../../constants/tokens'; | ||
import {useStyles, useTheme} from '../../hooks'; | ||
import {Button} from '../Button'; | ||
import {Picker} from '../Picker'; | ||
import stylesheet from './styles'; | ||
|
||
export type TokenSwapProps = { | ||
/** | ||
* Error message to be displayed. | ||
* If this prop is not provided or is undefined, no error message will be displayed. | ||
*/ | ||
onPress: () => void; | ||
error?: string; | ||
|
||
left?: React.ReactNode; | ||
right?: React.ReactNode; | ||
|
||
style?: StyleProp<ViewStyle>; | ||
containerStyle?: StyleProp<ViewStyle>; | ||
inputStyle?: StyleProp<TextStyle>; | ||
}; | ||
|
||
export const TokenSwap: React.FC<TokenSwapProps> = (props) => { | ||
const { | ||
onPress, | ||
error, | ||
left, | ||
right, | ||
style: styleProp, | ||
containerStyle: containerStyleProp, | ||
inputStyle: inputStyleProp, | ||
...TokenSwapProps | ||
} = props; | ||
|
||
const {theme} = useTheme(); | ||
const styles = useStyles(stylesheet, !!error, !!left, !!right); | ||
const [token, setToken] = useState<TokenSymbol>(TokenSymbol.ETH); | ||
|
||
const [amount, setAmount] = useState(''); | ||
const handleChangeAmount = (value: string) => { | ||
setAmount(value); | ||
}; | ||
|
||
return ( | ||
<View style={[styles.container, containerStyleProp]}> | ||
<View style={[styles.content, styleProp]}> | ||
<Picker | ||
label="Please select a token" | ||
selectedValue={token} | ||
onValueChange={(itemValue) => setToken(itemValue as TokenSymbol)} | ||
> | ||
{/* {Object.values(tokensIns).map((tkn) => ( | ||
<Picker.Item | ||
key={tkn[CHAIN_ID].symbol} | ||
label={tkn[CHAIN_ID].name} | ||
value={tkn[CHAIN_ID].symbol} | ||
/> | ||
))} */} | ||
</Picker> | ||
<TextInput | ||
keyboardType="numeric" | ||
value={amount} | ||
onChangeText={handleChangeAmount} | ||
placeholder="amount" | ||
style={[styles.input, inputStyleProp]} | ||
placeholderTextColor={theme.colors.inputPlaceholder} | ||
underlineColorAndroid="transparent" | ||
{...TokenSwapProps} | ||
/> | ||
</View> | ||
<View style={[styles.content, styleProp]}> | ||
<Picker | ||
label="Please select a token" | ||
selectedValue={token} | ||
onValueChange={(itemValue) => setToken(itemValue as TokenSymbol)} | ||
> | ||
{/* {Object.values(tokensIns).map((tkn) => ( | ||
<Picker.Item | ||
key={tkn[CHAIN_ID].symbol} | ||
label={tkn[CHAIN_ID].name} | ||
value={tkn[CHAIN_ID].symbol} | ||
/> | ||
))} */} | ||
</Picker> | ||
<TextInput | ||
keyboardType="numeric" | ||
value={amount} | ||
onChangeText={handleChangeAmount} | ||
placeholder="amount" | ||
style={[styles.input, inputStyleProp]} | ||
placeholderTextColor={theme.colors.inputPlaceholder} | ||
underlineColorAndroid="transparent" | ||
{...TokenSwapProps} | ||
/> | ||
</View> | ||
<View style={{display: 'flex', flexDirection: 'column', gap: 10}}> | ||
{/* <View>Amount received in {tokenOut[CHAIN_ID].symbol}:</View> | ||
<View style={[styles.input, inputStyleProp]}>0</View> */} | ||
<Button onPress={onPress}>Swap</Button> | ||
</View> | ||
</View> | ||
); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
import {Spacing, ThemedStyleSheet, Typography} from '../../styles'; | ||
|
||
export default ThemedStyleSheet((theme, error: boolean, left: boolean, right: boolean) => ({ | ||
container: { | ||
width: '100%', | ||
maxWidth: 500, | ||
padding: Spacing.medium, | ||
borderRadius: 10, | ||
backgroundColor: theme.colors.surface, | ||
}, | ||
content: { | ||
flex: 1, | ||
borderRadius: 999, | ||
flexDirection: 'row', | ||
alignItems: 'center', | ||
gap: Spacing.small, | ||
backgroundColor: theme.colors.transparent, | ||
height: 56, | ||
marginBottom: Spacing.medium, | ||
|
||
...(error && { | ||
backgroundColor: theme.colors.errorLight, | ||
borderColor: theme.colors.errorDark, | ||
}), | ||
|
||
...(left && { | ||
paddingLeft: Spacing.small, | ||
}), | ||
|
||
...(right && { | ||
paddingRight: Spacing.small, | ||
}), | ||
}, | ||
|
||
input: { | ||
borderWidth: 1, | ||
borderRadius: 999, | ||
borderColor: theme.colors.inputBorder, | ||
flex: 1, | ||
height: '100%', | ||
paddingHorizontal: Spacing.large, | ||
paddingVertical: Spacing.large, | ||
color: theme.colors.inputText, | ||
backgroundColor: theme.colors.inputBackground, | ||
fontSize: 15, | ||
...Typography.semiBold, | ||
|
||
...(left && { | ||
paddingLeft: Spacing.none, | ||
}), | ||
|
||
...(right && { | ||
paddingRight: Spacing.none, | ||
}), | ||
}, | ||
|
||
errorText: { | ||
marginTop: 3, | ||
color: theme.colors.errorDark, | ||
}, | ||
})); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,134 @@ | ||
import {fetchBuildExecuteTransaction, fetchQuotes} from '@avnu/avnu-sdk'; | ||
import {NextRequest, NextResponse} from 'next/server'; | ||
import {Calldata} from 'starknet'; | ||
|
||
import {ESCROW_ADDRESSES, ETH_ADDRESSES, STRK_ADDRESSES} from '@/constants/contracts'; | ||
import {AVNU_URL, CHAIN_ID, Entrypoint} from '@/constants/misc'; | ||
import {account} from '@/services/account'; | ||
import {ErrorCode} from '@/utils/errors'; | ||
import {HTTPStatus} from '@/utils/http'; | ||
import {ClaimSchema} from '@/utils/validation'; | ||
|
||
import {getClaimCallData} from '../../../../website/src/app/api/deposit/calldata'; | ||
|
||
export async function POST(request: NextRequest) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. NextJS api in the mobile app? Waw |
||
const requestBody = await request.json(); | ||
|
||
const body = ClaimSchema.safeParse(requestBody); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If you want to create an API call, do it in a NextJS api please. Last sprint, maybe just push the UI |
||
if (!body.success) { | ||
return NextResponse.json( | ||
{code: ErrorCode.BAD_REQUEST, error: body.error}, | ||
{status: HTTPStatus.BadRequest}, | ||
); | ||
} | ||
|
||
let claimCallData: Calldata; | ||
let gasTokenAddress: string; | ||
try { | ||
const {calldata, tokenAddress} = await getClaimCallData(body.data); | ||
claimCallData = calldata; | ||
gasTokenAddress = tokenAddress; | ||
} catch (error) { | ||
if (error instanceof Error) { | ||
return NextResponse.json({code: error.message}, {status: HTTPStatus.BadRequest}); | ||
} | ||
|
||
throw error; | ||
} | ||
|
||
try { | ||
if ( | ||
gasTokenAddress === ETH_ADDRESSES[CHAIN_ID] || | ||
gasTokenAddress === STRK_ADDRESSES[CHAIN_ID] | ||
) { | ||
// ETH | STRK fee estimation | ||
|
||
const result = await account.estimateInvokeFee( | ||
[ | ||
{ | ||
contractAddress: ESCROW_ADDRESSES[CHAIN_ID], | ||
entrypoint: Entrypoint.CLAIM, | ||
calldata: claimCallData, | ||
}, | ||
], | ||
{ | ||
version: gasTokenAddress === ETH_ADDRESSES[CHAIN_ID] ? 1 : 3, | ||
}, | ||
); | ||
|
||
// Using 1.1 as a multiplier to ensure the fee is enough | ||
const fee = ((result.overall_fee * BigInt(11)) / BigInt(10)).toString(); | ||
|
||
return NextResponse.json({gasFee: fee, tokenFee: fee}, {status: HTTPStatus.OK}); | ||
} else { | ||
// ERC20 fee estimation | ||
|
||
const quotes = await fetchQuotes( | ||
{ | ||
sellTokenAddress: ETH_ADDRESSES[CHAIN_ID], | ||
buyTokenAddress: gasTokenAddress, | ||
sellAmount: BigInt(1), | ||
takerAddress: account.address, | ||
}, | ||
{baseUrl: AVNU_URL}, | ||
); | ||
const quote = quotes[0]; | ||
|
||
if (!quote) { | ||
return NextResponse.json({code: ErrorCode.NO_ROUTE_FOUND}, {status: HTTPStatus.BadRequest}); | ||
} | ||
|
||
const {calls: swapCalls} = await fetchBuildExecuteTransaction( | ||
quote.quoteId, | ||
account.address, | ||
undefined, | ||
undefined, | ||
{baseUrl: AVNU_URL}, | ||
); | ||
|
||
const result = await account.estimateInvokeFee( | ||
[ | ||
{ | ||
contractAddress: ESCROW_ADDRESSES[CHAIN_ID], | ||
entrypoint: Entrypoint.CLAIM, | ||
calldata: claimCallData, | ||
}, | ||
...swapCalls, | ||
], | ||
{ | ||
version: 1, | ||
}, | ||
); | ||
|
||
// Using 1.1 as a multiplier to ensure the fee is enough | ||
const ethFee = (result.overall_fee * BigInt(11)) / BigInt(10); | ||
|
||
const feeQuotes = await fetchQuotes( | ||
{ | ||
sellTokenAddress: ETH_ADDRESSES[CHAIN_ID], | ||
buyTokenAddress: gasTokenAddress, | ||
sellAmount: ethFee, | ||
takerAddress: account.address, | ||
}, | ||
{baseUrl: AVNU_URL}, | ||
); | ||
const feeQuote = feeQuotes[0]; | ||
|
||
if (!feeQuote) { | ||
return NextResponse.json({code: ErrorCode.NO_ROUTE_FOUND}, {status: HTTPStatus.BadRequest}); | ||
} | ||
|
||
return NextResponse.json( | ||
{gasFee: ethFee, tokenFee: feeQuote.buyAmount}, | ||
{status: HTTPStatus.OK}, | ||
); | ||
} | ||
} catch (error) { | ||
console.error(error); | ||
|
||
return NextResponse.json( | ||
{code: ErrorCode.ESTIMATION_ERROR, error}, | ||
{status: HTTPStatus.InternalServerError}, | ||
); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this is absolutely not correct. It can work in prod. You need to add it in a hooks of the mobile, or in a package already used in the package.json