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

feat: add swap ui #166

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
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
106 changes: 106 additions & 0 deletions apps/mobile/src/components/TokenSwap/index.tsx
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>
);
};
61 changes: 61 additions & 0 deletions apps/mobile/src/components/TokenSwap/styles.ts
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,
},
}));
134 changes: 134 additions & 0 deletions apps/mobile/src/hooks/api/useAvnu.ts
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';
Copy link
Contributor

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


export async function POST(request: NextRequest) {
Copy link
Contributor

Choose a reason for hiding this comment

The 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);
Copy link
Contributor

Choose a reason for hiding this comment

The 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},
);
}
}
38 changes: 21 additions & 17 deletions apps/mobile/src/screens/Defi/index.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import { useState } from 'react';
import { KeyboardAvoidingView, ScrollView, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import {useState} from 'react';
import {KeyboardAvoidingView, ScrollView, Text, View} from 'react-native';
import {SafeAreaView} from 'react-native-safe-area-context';

import { TextButton } from '../../components';
import { Swap } from '../../components/Swap';
import {TextButton} from '../../components';
import {Swap} from '../../components/Swap';
import {TokenSwap} from '../../components/TokenSwap';
import TabSelector from '../../components/TabSelector';
import { TOKENSMINT } from '../../constants/tokens';
import { useStyles } from '../../hooks';
import { LightningNetworkWalletView } from '../../modules/Lightning';
import { DefiScreenProps } from '../../types';
import { SelectedTab, TABS_DEFI } from '../../types/tab';
import {TOKENSMINT} from '../../constants/tokens';
import {useStyles} from '../../hooks';
import {CashuWalletView} from '../../modules/Cashu';
import {LightningNetworkWalletView} from '../../modules/Lightning';
import {DefiScreenProps} from '../../types';
import {SelectedTab, TABS_DEFI} from '../../types/tab';
import stylesheet from './styles';
import { CashuView, CashuWalletView } from '../../modules/Cashu';

export const Defi: React.FC<DefiScreenProps> = ({ navigation }) => {
export const Defi: React.FC<DefiScreenProps> = ({navigation}) => {
const styles = useStyles(stylesheet);
const [selectedTab, setSelectedTab] = useState<SelectedTab | undefined>(SelectedTab.CASHU_WALLET);

Expand All @@ -32,7 +33,6 @@ export const Defi: React.FC<DefiScreenProps> = ({ navigation }) => {
</TextButton>
</SafeAreaView>
<ScrollView>

<KeyboardAvoidingView behavior="padding" style={styles.content}>
<TabSelector
activeTab={selectedTab}
Expand All @@ -44,7 +44,7 @@ export const Defi: React.FC<DefiScreenProps> = ({ navigation }) => {
{/* <Text style={styles.text}>DeFi, Ramp and more soon. Stay tuned for the AFK Fi</Text> */}

{selectedTab == SelectedTab.BTC_FI_VAULT && (
<View style={{ display: 'flex', alignItems: 'center' }}>
<View style={{display: 'flex', alignItems: 'center'}}>
<Swap
tokensIns={TOKENSMINT}
tokenOut={TOKENSMINT.WBTC}
Expand All @@ -55,6 +55,13 @@ export const Defi: React.FC<DefiScreenProps> = ({ navigation }) => {
/>
</View>
)}
{selectedTab == SelectedTab.SWAP_AVNU && (
<View style={{display: 'flex', alignItems: 'center'}}>
<TokenSwap
onPress={() => console.log('pressed!')}
/>
</View>
)}
{/*
{selectedTab == SelectedTab.BTC_BRIDGE && (
<View>
Expand All @@ -69,7 +76,6 @@ export const Defi: React.FC<DefiScreenProps> = ({ navigation }) => {
</View>
)}


{selectedTab == SelectedTab.CASHU_WALLET && (
<View>
<Text style={styles.text}>Cashu wallet coming soon</Text>
Expand All @@ -78,9 +84,7 @@ export const Defi: React.FC<DefiScreenProps> = ({ navigation }) => {
)}
</SafeAreaView>
</KeyboardAvoidingView>

</ScrollView>

</View>
);
};
Loading