Fix simplify buy/sell toggle buttons. Run prettier and lint.

This commit is contained in:
Reckless_Satoshi 2022-09-16 09:24:14 -07:00
parent c770d231d1
commit 91e5db2bb9
No known key found for this signature in database
GPG Key ID: 9C4585B561315571
10 changed files with 257 additions and 361 deletions

View File

@ -1,14 +1,12 @@
import React, { Component } from 'react';
import { withTranslation } from 'react-i18next';
import {
Badge,
Tooltip,
Stack,
Paper,
Button,
FormControlLabel,
Checkbox,
RadioGroup,
ToggleButtonGroup,
ToggleButton,
ListItemButton,
Typography,
Grid,
@ -35,7 +33,6 @@ import { apiClient } from '../services/api/index';
// Icons
import { BarChart, FormatListBulleted, Refresh } from '@mui/icons-material';
import { BuySatsCheckedIcon, BuySatsIcon, SellSatsCheckedIcon, SellSatsIcon } from './Icons';
class BookPage extends Component {
constructor(props) {
@ -52,14 +49,13 @@ class BookPage extends Component {
getOrderDetails(type, currency) {
this.props.setAppState({ bookLoading: true });
apiClient.get('/api/book?currency=' + currency + '&type=' + type)
.then((data) =>
this.props.setAppState({
bookNotFound: data.not_found,
bookLoading: false,
bookOrders: data,
}),
);
apiClient.get('/api/book/').then((data) =>
this.props.setAppState({
bookNotFound: data.not_found,
bookLoading: false,
bookOrders: data,
}),
);
}
handleRowClick = (e) => {
@ -152,12 +148,12 @@ class BookPage extends Component {
bookListTableDesktop = () => {
const { t } = this.props;
return (
<div style={{ height: 422, width: '100%' }}>
<div style={{ height: 424, width: '100%' }}>
<DataGrid
localeText={this.dataGridLocaleText()}
rows={this.props.bookOrders.filter(
(order) =>
(order.type == this.props.type || this.props.type == 2) &&
(order.type == this.props.type || this.props.type == null) &&
(order.currency == this.props.currency || this.props.currency == 0),
)}
loading={this.props.bookLoading}
@ -293,7 +289,7 @@ class BookPage extends Component {
bookListTablePhone = () => {
const { t } = this.props;
return (
<div style={{ height: 422, width: '100%' }}>
<div style={{ height: 424, width: '100%' }}>
<DataGrid
localeText={this.dataGridLocaleText()}
loading={this.props.bookLoading}
@ -437,35 +433,14 @@ class BookPage extends Component {
);
};
handleTypeChange = (buyChecked, sellChecked) => {
this.props.setAppState({ buyChecked, sellChecked });
if (buyChecked & sellChecked || !buyChecked & !sellChecked) {
var type = 2;
} else if (buyChecked) {
var type = 1;
} else if (sellChecked) {
var type = 0;
}
this.props.setAppState({ type });
};
handleClickBuy = (e) => {
const buyChecked = e.target.checked;
const sellChecked = this.props.sellChecked;
this.handleTypeChange(buyChecked, sellChecked);
handleTypeChange = (mouseEvent, val) => {
this.props.setAppState({ type: val });
};
handleClickView = () => {
this.setState({ view: this.state.view == 'depth' ? 'list' : 'depth' });
};
handleClickSell = (e) => {
const buyChecked = this.props.buyChecked;
const sellChecked = e.target.checked;
this.handleTypeChange(buyChecked, sellChecked);
};
NoOrdersFound = () => {
const { t } = this.props;
@ -529,14 +504,14 @@ class BookPage extends Component {
<>
{/* Desktop */}
<MediaQuery minWidth={930}>
<Paper elevation={0} style={{ width: 925, maxHeight: 500, overflow: 'auto' }}>
<div style={{ height: 422, width: '100%' }}>{components[0]}</div>
<Paper elevation={0} style={{ width: 925, maxHeight: 510, overflow: 'auto' }}>
<div style={{ height: 424, width: '100%' }}>{components[0]}</div>
</Paper>
</MediaQuery>
{/* Smartphone */}
<MediaQuery maxWidth={929}>
<Paper elevation={0} style={{ width: 395, maxHeight: 450, overflow: 'auto' }}>
<div style={{ height: 422, width: '100%' }}>{components[1]}</div>
<Paper elevation={0} style={{ width: 395, maxHeight: 460, overflow: 'auto' }}>
<div style={{ height: 424, width: '100%' }}>{components[1]}</div>
</Paper>
</MediaQuery>
</>
@ -576,74 +551,25 @@ class BookPage extends Component {
<Grid item xs={6} align='right'>
<FormControl align='center'>
<FormHelperText
align='center'
sx={{ position: 'relative', left: '10px', textAlign: 'center' }}
>
<FormHelperText align='center' sx={{ textAlign: 'center' }}>
{t('I want to')}
</FormHelperText>
<RadioGroup row>
<div style={{ position: 'relative', left: '20px' }}>
<FormControlLabel
control={
<Checkbox
icon={<BuySatsIcon sx={{ width: '30px', height: '30px' }} color='inherit' />}
checkedIcon={
<BuySatsCheckedIcon
sx={{ width: '30px', height: '30px' }}
color='primary'
/>
}
/>
}
label={
<div style={{ position: 'relative', top: '-13px' }}>
{this.props.buyChecked ? (
<Typography variant='caption' color='primary'>
<b>{t('Buy')}</b>
</Typography>
) : (
<Typography variant='caption' color='text.secondary'>
{t('Buy')}
</Typography>
)}
</div>
}
labelPlacement='bottom'
checked={this.props.buyChecked}
onChange={this.handleClickBuy}
/>
</div>
<FormControlLabel
control={
<Checkbox
icon={<SellSatsIcon sx={{ width: '30px', height: '30px' }} color='inherit' />}
checkedIcon={
<SellSatsCheckedIcon
sx={{ width: '30px', height: '30px' }}
color='secondary'
/>
}
/>
}
label={
<div style={{ position: 'relative', top: '-13px' }}>
{this.props.sellChecked ? (
<Typography variant='caption' color='secondary'>
<b>{t('Sell')}</b>
</Typography>
) : (
<Typography variant='caption' color='text.secondary'>
{t('Sell')}
</Typography>
)}
</div>
}
labelPlacement='bottom'
checked={this.props.sellChecked}
onChange={this.handleClickSell}
/>
</RadioGroup>
<div style={{ textAlign: 'center' }}>
<ToggleButtonGroup
sx={{ height: '3.52em' }}
size='large'
exclusive={true}
value={this.props.type}
onChange={this.handleTypeChange}
>
<ToggleButton value={1} color={'primary'}>
{t('Buy')}
</ToggleButton>
<ToggleButton value={0} color={'secondary'}>
{t('Sell')}
</ToggleButton>
</ToggleButtonGroup>
</div>
</FormControl>
</Grid>

View File

@ -72,23 +72,22 @@ class BottomBar extends Component {
getInfo() {
this.setState(null);
apiClient.get('/api/info/')
.then(
(data) =>
this.setState(data) &
this.props.setAppState({
nickname: data.nickname,
loading: false,
activeOrderId: data.active_order_id ? data.active_order_id : null,
lastOrderId: data.last_order_id ? data.last_order_id : null,
referralCode: data.referral_code,
tgEnabled: data.tg_enabled,
tgBotName: data.tg_bot_name,
tgToken: data.tg_token,
earnedRewards: data.earned_rewards,
lastDayPremium: data.last_day_nonkyc_btc_premium,
}),
);
apiClient.get('/api/info/').then(
(data) =>
this.setState(data) &
this.props.setAppState({
nickname: data.nickname,
loading: false,
activeOrderId: data.active_order_id ? data.active_order_id : null,
lastOrderId: data.last_order_id ? data.last_order_id : null,
referralCode: data.referral_code,
tgEnabled: data.tg_enabled,
tgBotName: data.tg_bot_name,
tgToken: data.tg_token,
earnedRewards: data.earned_rewards,
lastDayPremium: data.last_day_nonkyc_btc_premium,
}),
);
}
handleClickOpenStatsForNerds = () => {
@ -122,9 +121,11 @@ class BottomBar extends Component {
showRewardsSpinner: true,
});
apiClient.post('/api/reward/', {
invoice: rewardInvoice,
}).then(
apiClient
.post('/api/reward/', {
invoice: rewardInvoice,
})
.then(
(data) =>
this.setState({
badInvoice: data.bad_invoice,
@ -140,7 +141,8 @@ class BottomBar extends Component {
};
handleSetStealthInvoice = (wantsStealth) => {
apiClient.put('/api/stealth/', { wantsStealth })
apiClient
.put('/api/stealth/', { wantsStealth })
.then((data) => this.props.setAppState({ stealthInvoices: data.wantsStealth }));
};

View File

@ -63,10 +63,9 @@ const DepthChart: React.FC<DepthChartProps> = ({
useEffect(() => {
if (Object.keys(limits).length === 0) {
apiClient.get('/api/limits/')
.then((data) => {
setAppState({ limits: data });
});
apiClient.get('/api/limits/').then((data) => {
setAppState({ limits: data });
});
}
}, []);

View File

@ -24,7 +24,7 @@ export default class HomePage extends Component {
avatarLoaded: false,
buyChecked: false,
sellChecked: false,
type: 2,
type: null,
currency: 0,
bookCurrencyCode: 'ANY',
bookOrders: new Array(),

View File

@ -3,12 +3,7 @@ import { withTranslation } from 'react-i18next';
import {
InputAdornment,
LinearProgress,
Dialog,
IconButton,
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
ButtonGroup,
Accordion,
AccordionDetails,
AccordionSummary,
@ -47,7 +42,6 @@ import currencyDict from '../../static/assets/currencies.json';
import LockIcon from '@mui/icons-material/Lock';
import HourglassTopIcon from '@mui/icons-material/HourglassTop';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import { BuySatsCheckedIcon, BuySatsIcon, SellSatsCheckedIcon, SellSatsIcon } from './Icons';
import { getCookie } from '../utils/cookies';
import { pn } from '../utils/prettyNumbers';
@ -99,28 +93,26 @@ class MakerPage extends Component {
// if currency or type have changed in HomePage state, change in MakerPage state too.
this.setState({
currency: !this.props.currency === 0 ? this.props.currency : this.state.currency,
type: !this.props.type == 2 ? (this.props.type == 1 ? 0 : 1) : this.state.type,
});
}
getLimits() {
this.setState({ loadingLimits: true });
apiClient.get('/api/limits/')
.then((data) =>
this.setState({
limits: data,
loadingLimits: false,
minAmount: this.state.amount
? parseFloat((this.state.amount / 2).toPrecision(2))
: parseFloat(Number(data[this.state.currency].max_amount * 0.25).toPrecision(2)),
maxAmount: this.state.amount
? this.state.amount
: parseFloat(Number(data[this.state.currency].max_amount * 0.75).toPrecision(2)),
minTradeSats: data['1000'].min_amount * 100000000,
maxTradeSats: data['1000'].max_amount * 100000000,
maxBondlessSats: data['1000'].max_bondless_amount * 100000000,
}),
);
apiClient.get('/api/limits/').then((data) =>
this.setState({
limits: data,
loadingLimits: false,
minAmount: this.state.amount
? parseFloat((this.state.amount / 2).toPrecision(2))
: parseFloat(Number(data[this.state.currency].max_amount * 0.25).toPrecision(2)),
maxAmount: this.state.amount
? this.state.amount
: parseFloat(Number(data[this.state.currency].max_amount * 0.75).toPrecision(2)),
minTradeSats: data['1000'].min_amount * 100000000,
maxTradeSats: data['1000'].max_amount * 100000000,
maxBondlessSats: data['1000'].max_bondless_amount * 100000000,
}),
);
}
recalcBounds = () => {
@ -145,19 +137,6 @@ class MakerPage extends Component {
};
}
handleTypeChange = (e) => {
this.setState({
type: e.target.value,
});
// Share state with HomePage and OrderPage
this.props.setAppState({
// maker and book page type values 0:1 are reversed
type: e.target.value == 1 ? 0 : 1,
buyChecked: e.target.value == 0,
sellChecked: e.target.value == 1,
});
};
handleCurrencyChange = (e) => {
const currencyCode = this.getCurrencyCode(e.target.value);
this.setState({
@ -304,7 +283,7 @@ class MakerPage extends Component {
handleCreateOfferButtonPressed = () => {
this.state.amount == null ? this.setState({ amount: 0 }) : null;
const body = {
type: this.state.type,
type: this.props.type == 0 ? 1 : 0,
currency: this.state.currency,
amount: this.state.has_range ? null : this.state.amount,
has_range: this.state.enableAmountRange,
@ -320,7 +299,8 @@ class MakerPage extends Component {
bond_size: this.state.bondSize,
bondless_taker: this.state.allowBondless,
};
apiClient.post('/api/make/', body)
apiClient
.post('/api/make/', body)
.then(
(data) =>
this.setState({ badRequest: data.bad_request }) &
@ -356,79 +336,46 @@ class MakerPage extends Component {
return (
<Paper elevation={12} style={{ padding: 8, width: `${260 / 16}em`, align: 'center' }}>
<Grid item xs={12} align='center'>
<div style={{ position: 'relative' }}>
<FormControl component='fieldset'>
<FormHelperText sx={{ textAlign: 'center' }}>
{t('Buy or Sell Bitcoin?')}
</FormHelperText>
<RadioGroup row value={this.state.type} onChange={this.handleTypeChange}>
<FormControlLabel
value={0}
control={
<Radio
icon={
<BuySatsIcon
sx={{ width: `${30 / 24}em`, height: `${30 / 24}em` }}
color='text.secondary'
/>
}
checkedIcon={
<BuySatsCheckedIcon
sx={{ width: `${30 / 24}em`, height: `${30 / 24}em` }}
color='primary'
/>
}
/>
<FormControl component='fieldset'>
<FormHelperText sx={{ textAlign: 'center' }}>
{t('Buy or Sell Bitcoin?')}
</FormHelperText>
<div style={{ textAlign: 'center' }}>
<ButtonGroup>
<Button
size='large'
variant='contained'
onClick={() =>
this.props.setAppState({
type: 1,
})
}
label={
this.state.type == 0 ? (
<Typography color='primary'>
<b>{t('Buy')}</b>
</Typography>
) : (
<Typography color='text.secondary'>{t('Buy')}</Typography>
)
disableElevation={this.props.type == 1}
color={this.props.type == 1 ? 'primary' : 'inherit'}
>
{t('Buy')}
</Button>
<Button
size='large'
variant='contained'
onClick={() =>
this.props.setAppState({
type: 0,
})
}
labelPlacement='end'
/>
<FormControlLabel
value={1}
control={
<Radio
color='secondary'
icon={
<SellSatsIcon
sx={{ width: `${30 / 24}em`, height: `${30 / 24}em` }}
color='text.secondary'
/>
}
checkedIcon={
<SellSatsCheckedIcon
sx={{ width: `${30 / 24}em`, height: `${30 / 24}em` }}
color='secondary'
/>
}
/>
}
label={
this.state.type == 1 ? (
<Typography color='secondary'>
<b>{t('Sell')}</b>
</Typography>
) : (
<Typography color='text.secondary'>{t('Sell')}</Typography>
)
}
labelPlacement='end'
/>
</RadioGroup>
</FormControl>
</div>
disableElevation={this.props.type == 0}
color={this.props.type == 0 ? 'secondary' : 'inherit'}
>
{t('Sell')}
</Button>
</ButtonGroup>
</div>
</FormControl>
<div style={{ height: '1em' }} />
</Grid>
<Grid alignItems='stretch' style={{ display: 'flex' }}>
<div style={{}}>
<div>
<Tooltip
placement='top'
enterTouchDelay={500}
@ -501,11 +448,12 @@ class MakerPage extends Component {
listHeaderText={t('You can add new methods')}
addNewButtonText={t('Add New')}
/>
<div style={{ height: '0.3em' }} />
</Grid>
<Grid item xs={12} align='center'>
<FormControl component='fieldset'>
<FormHelperText sx={{ textAlign: 'center' }}>
<FormHelperText sx={{ textAlign: 'center', position: 'relative', top: '0.5em' }}>
{t('Choose a Pricing Method')}
</FormHelperText>
<RadioGroup row defaultValue='relative'>
@ -916,7 +864,7 @@ class MakerPage extends Component {
control={
<Checkbox
disabled
// disabled={this.state.type==0 || this.state.type === null}
// disabled={this.props.type==0 || this.props.type === null}
color='secondary'
checked={this.state.allowBondless}
onChange={() => this.setState({ allowBondless: !this.state.allowBondless })}
@ -989,7 +937,7 @@ class MakerPage extends Component {
<Grid item xs={12} align='center'>
{/* conditions to disable the make button */}
{this.state.type == null ||
{this.props.type == null ||
(this.state.amount == null) &
(this.state.enableAmountRange == false || this.state.loadingLimits) ||
this.state.enableAmountRange & (this.minAmountError() || this.maxAmountError()) ||
@ -1028,9 +976,9 @@ class MakerPage extends Component {
)}
<Typography component='h2' variant='subtitle2'>
<div align='center'>
{this.state.type == null
{this.props.type == null
? t('Create an order for ')
: this.state.type == 0
: this.props.type == 1
? t('Create a BTC buy order for ')
: t('Create a BTC sell order for ')}
{this.state.enableAmountRange & (this.state.minAmount != null)

View File

@ -123,8 +123,7 @@ class OrderPage extends Component {
getOrderDetails = (id) => {
this.setState({ orderId: id });
apiClient.get('/api/order/?order_id=' + id)
.then(this.orderDetailsReceived);
apiClient.get('/api/order/?order_id=' + id).then(this.orderDetailsReceived);
};
orderDetailsReceived = (data) => {
@ -185,10 +184,12 @@ class OrderPage extends Component {
};
sendWeblnInvoice = (invoice) => {
apiClient.post('/api/order/?order_id=' + this.state.orderId, {
action: 'update_invoice',
invoice,
}).then((data) => this.completeSetState(data));
apiClient
.post('/api/order/?order_id=' + this.state.orderId, {
action: 'update_invoice',
invoice,
})
.then((data) => this.completeSetState(data));
};
// Countdown Renderer callback with condition
@ -422,10 +423,11 @@ class OrderPage extends Component {
takeOrder = () => {
this.setState({ loading: true });
apiClient.post('/api/order/?order_id=' + this.state.orderId, {
action: 'take',
amount: this.state.takeAmount,
})
apiClient
.post('/api/order/?order_id=' + this.state.orderId, {
action: 'take',
amount: this.state.takeAmount,
})
.then((data) => this.handleWebln(data) & this.completeSetState(data));
};
@ -441,9 +443,11 @@ class OrderPage extends Component {
handleClickConfirmCancelButton = () => {
this.setState({ loading: true });
apiClient.post('/api/order/?order_id=' + this.state.orderId, {
action: 'cancel',
}).then(() => this.getOrderDetails(this.state.orderId) & this.setState({ status: 4 }));
apiClient
.post('/api/order/?order_id=' + this.state.orderId, {
action: 'cancel',
})
.then(() => this.getOrderDetails(this.state.orderId) & this.setState({ status: 4 }));
this.handleClickCloseConfirmCancelDialog();
};
@ -541,9 +545,11 @@ class OrderPage extends Component {
};
handleClickConfirmCollaborativeCancelButton = () => {
apiClient.post('/api/order/?order_id=' + this.state.orderId, {
action: 'cancel',
}).then(() => this.getOrderDetails(this.state.orderId) & this.setState({ status: 4 }));
apiClient
.post('/api/order/?order_id=' + this.state.orderId, {
action: 'cancel',
})
.then(() => this.getOrderDetails(this.state.orderId) & this.setState({ status: 4 }));
this.handleClickCloseCollaborativeCancelDialog();
};

View File

@ -133,9 +133,11 @@ class TradeBox extends Component {
};
handleClickAgreeDisputeButton = () => {
apiClient.post('/api/order/?order_id=' + this.props.data.id, {
action: 'dispute',
}).then((data) => this.props.completeSetState(data));
apiClient
.post('/api/order/?order_id=' + this.props.data.id, {
action: 'dispute',
})
.then((data) => this.props.completeSetState(data));
this.handleClickCloseConfirmDispute();
};
@ -480,9 +482,11 @@ class TradeBox extends Component {
handleClickPauseOrder = () => {
this.props.completeSetState({ pauseLoading: true });
apiClient.post('/api/order/?order_id=' + this.props.data.id, {
action: 'pause',
}).then((data) => this.props.getOrderDetails(data.id));
apiClient
.post('/api/order/?order_id=' + this.props.data.id, {
action: 'pause',
})
.then((data) => this.props.getOrderDetails(data.id));
};
showMakerWait = () => {
@ -626,10 +630,12 @@ class TradeBox extends Component {
handleClickSubmitInvoiceButton = () => {
this.setState({ badInvoice: false });
apiClient.post('/api/order/?order_id=' + this.props.data.id, {
action: 'update_invoice',
invoice: this.state.invoice,
}).then(
apiClient
.post('/api/order/?order_id=' + this.props.data.id, {
action: 'update_invoice',
invoice: this.state.invoice,
})
.then(
(data) =>
this.setState({ badInvoice: data.bad_invoice }) & this.props.completeSetState(data),
);
@ -656,11 +662,13 @@ class TradeBox extends Component {
handleClickSubmitAddressButton = () => {
this.setState({ badInvoice: false });
apiClient.post('/api/order/?order_id=' + this.props.data.id, {
action: 'update_address',
address: this.state.address,
mining_fee_rate: Math.max(1, this.state.miningFee),
}).then(
apiClient
.post('/api/order/?order_id=' + this.props.data.id, {
action: 'update_address',
address: this.state.address,
mining_fee_rate: Math.max(1, this.state.miningFee),
})
.then(
(data) =>
this.setState({ badAddress: data.bad_address }) & this.props.completeSetState(data),
);
@ -676,13 +684,15 @@ class TradeBox extends Component {
handleClickSubmitStatementButton = () => {
this.setState({ badInvoice: false });
apiClient.post('/api/order/?order_id=' + this.props.data.id, {
action: 'submit_statement',
statement: this.state.statement,
}).then(
(data) =>
this.setState({ badStatement: data.bad_statement }) & this.props.completeSetState(data),
);
apiClient
.post('/api/order/?order_id=' + this.props.data.id, {
action: 'submit_statement',
statement: this.state.statement,
})
.then(
(data) =>
this.setState({ badStatement: data.bad_statement }) & this.props.completeSetState(data),
);
};
handleScan = (data) => {
@ -1179,16 +1189,20 @@ class TradeBox extends Component {
}
handleClickConfirmButton = () => {
apiClient.post('/api/order/?order_id=' + this.props.data.id, {
action: 'confirm',
}).then((data) => this.props.completeSetState(data));
apiClient
.post('/api/order/?order_id=' + this.props.data.id, {
action: 'confirm',
})
.then((data) => this.props.completeSetState(data));
};
handleRatingUserChange = (e) => {
apiClient.post('/api/order/?order_id=' + this.props.data.id, {
action: 'rate_user',
rating: e.target.value,
}).then((data) => this.props.completeSetState(data));
apiClient
.post('/api/order/?order_id=' + this.props.data.id, {
action: 'rate_user',
rating: e.target.value,
})
.then((data) => this.props.completeSetState(data));
};
handleRatingRobosatsChange = (e) => {
@ -1197,10 +1211,12 @@ class TradeBox extends Component {
}
this.setState({ rating_platform: e.target.value });
apiClient.post('/api/order/?order_id=' + this.props.data.id, {
action: 'rate_platform',
rating: e.target.value,
}).then((data) => this.props.completeSetState(data));
apiClient
.post('/api/order/?order_id=' + this.props.data.id, {
action: 'rate_platform',
rating: e.target.value,
})
.then((data) => this.props.completeSetState(data));
};
showFiatSentButton() {
@ -1316,7 +1332,8 @@ class TradeBox extends Component {
bond_size: this.props.data.bond_size,
bondless_taker: this.props.data.bondless_taker,
};
apiClient.post('/api/make/', body)
apiClient
.post('/api/make/', body)
.then(
(data) =>
this.setState({ badRequest: data.bad_request }) &

View File

@ -77,51 +77,49 @@ class UserGenPage extends Component {
});
requestBody.then((body) =>
apiClient.post('/api/user/', body)
.then((data) => {
console.log(data) &
this.setState({
nickname: data.nickname,
bit_entropy: data.token_bits_entropy,
avatarUrl: '/static/assets/avatars/' + data.nickname + '.png',
shannon_entropy: data.token_shannon_entropy,
bad_request: data.bad_request,
found: data.found,
loadingRobot: false,
stealthInvoices: data.wants_stealth,
}) &
// Add nick and token to App state (token only if not a bad request)
(data.bad_request
? this.props.setAppState({
nickname: data.nickname,
avatarLoaded: false,
activeOrderId: data.active_order_id ? data.active_order_id : null,
referralCode: data.referral_code,
earnedRewards: data.earned_rewards,
lastOrderId: data.last_order_id ? data.last_order_id : null,
stealthInvoices: data.wants_stealth,
})
: this.props.setAppState({
nickname: data.nickname,
token,
avatarLoaded: false,
activeOrderId: data.active_order_id ? data.active_order_id : null,
lastOrderId: data.last_order_id ? data.last_order_id : null,
referralCode: data.referral_code,
earnedRewards: data.earned_rewards,
stealthInvoices: data.wants_stealth,
}) &
writeCookie('robot_token', token) &
writeCookie('pub_key', data.public_key.split('\n').join('\\')) &
writeCookie('enc_priv_key', data.encrypted_private_key.split('\n').join('\\'))) &
// If the robot has been found (recovered) we assume the token is backed up
(data.found ? this.props.setAppState({ copiedToken: true }) : null);
}),
apiClient.post('/api/user/', body).then((data) => {
this.setState({
nickname: data.nickname,
bit_entropy: data.token_bits_entropy,
avatarUrl: '/static/assets/avatars/' + data.nickname + '.png',
shannon_entropy: data.token_shannon_entropy,
bad_request: data.bad_request,
found: data.found,
loadingRobot: false,
stealthInvoices: data.wants_stealth,
}) &
// Add nick and token to App state (token only if not a bad request)
(data.bad_request
? this.props.setAppState({
nickname: data.nickname,
avatarLoaded: false,
activeOrderId: data.active_order_id ? data.active_order_id : null,
referralCode: data.referral_code,
earnedRewards: data.earned_rewards,
lastOrderId: data.last_order_id ? data.last_order_id : null,
stealthInvoices: data.wants_stealth,
})
: this.props.setAppState({
nickname: data.nickname,
token,
avatarLoaded: false,
activeOrderId: data.active_order_id ? data.active_order_id : null,
lastOrderId: data.last_order_id ? data.last_order_id : null,
referralCode: data.referral_code,
earnedRewards: data.earned_rewards,
stealthInvoices: data.wants_stealth,
}) &
writeCookie('robot_token', token) &
writeCookie('pub_key', data.public_key.split('\n').join('\\')) &
writeCookie('enc_priv_key', data.encrypted_private_key.split('\n').join('\\'))) &
// If the robot has been found (recovered) we assume the token is backed up
(data.found ? this.props.setAppState({ copiedToken: true }) : null);
}),
);
};
delGeneratedUser() {
apiClient.delete('/api/user')
apiClient.delete('/api/user');
deleteCookie('sessionid');
deleteCookie('robot_token');

View File

@ -1,40 +1,40 @@
import { ApiClient } from "../api"
import { ApiClient } from '../api';
import { getCookie } from '../../../utils/cookies';
class ApiWebClient implements ApiClient {
private getHeaders: () => HeadersInit = () => {
return { 'Content-Type': 'application/json', 'X-CSRFToken': getCookie('csrftoken') || "" }
}
private readonly getHeaders: () => HeadersInit = () => {
return { 'Content-Type': 'application/json', 'X-CSRFToken': getCookie('csrftoken') || '' };
};
public post: (path: string, body: object) => Promise<object> = (path, body) => {
public post: (path: string, body: object) => Promise<object> = async (path, body) => {
const requestOptions = {
method: 'POST',
headers: this.getHeaders(),
body: JSON.stringify(body),
};
return fetch(path, requestOptions).then((response) => response.json())
}
return await fetch(path, requestOptions).then(async (response) => await response.json());
};
public put: (path: string, body: object) => Promise<object> = (path, body) => {
public put: (path: string, body: object) => Promise<object> = async (path, body) => {
const requestOptions = {
method: 'PUT',
headers: this.getHeaders(),
body: JSON.stringify(body),
};
return fetch(path, requestOptions).then((response) => response.json())
}
return await fetch(path, requestOptions).then(async (response) => await response.json());
};
public delete: (path: string) => Promise<object> = (path) => {
public delete: (path: string) => Promise<object> = async (path) => {
const requestOptions = {
method: 'DELETE',
headers: this.getHeaders(),
};
return fetch(path, requestOptions).then((response) => response.json())
}
return await fetch(path, requestOptions).then(async (response) => await response.json());
};
public get: (path: string) => Promise<object> = (path) => {
return fetch(path).then((response) => response.json())
}
public get: (path: string) => Promise<object> = async (path) => {
return await fetch(path).then(async (response) => await response.json());
};
}
export default ApiWebClient
export default ApiWebClient;

View File

@ -1,10 +1,10 @@
import ApiWebClient from './ApiWebClient'
import ApiWebClient from './ApiWebClient';
export interface ApiClient {
post: (path: string, body: object) => Promise<object>
put: (path: string, body: object) => Promise<object>
get: (path: string) => Promise<object>
delete: (path: string) => Promise<object>
post: (path: string, body: object) => Promise<object>;
put: (path: string, body: object) => Promise<object>;
get: (path: string) => Promise<object>;
delete: (path: string) => Promise<object>;
}
export const apiClient: ApiClient = new ApiWebClient()
export const apiClient: ApiClient = new ApiWebClient();