Skip to content

Commit

Permalink
Merge pull request #333 from invariant-labs/dev
Browse files Browse the repository at this point in the history
Update staging
  • Loading branch information
p6te authored Oct 3, 2024
2 parents 6c1b8a5 + 0dd3ea3 commit 5e149ff
Show file tree
Hide file tree
Showing 13 changed files with 73 additions and 30 deletions.
2 changes: 1 addition & 1 deletion src/components/NewPosition/PoolInit/PoolInit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,7 @@ export const PoolInit: React.FC<IPoolInit> = ({
/>
</Grid>
) : (
<Grid container className={classes.buttons}>
<Grid container className={classes.buttons} justifyContent='center' alignItems='center'>
<Button className={classes.button} onClick={resetRange}>
Reset range
</Button>
Expand Down
3 changes: 2 additions & 1 deletion src/components/NewPosition/PoolInit/style.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,9 @@ const useStyles = makeStyles()(theme => {
}
},
buttons: {
marginTop: 38,
marginTop: 4,
width: '100%',
height: 70,
flexDirection: 'row',
gap: 16,
alignItems: 'center'
Expand Down
7 changes: 6 additions & 1 deletion src/components/Swap/ExchangeRate/ExchangeRate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,12 @@ const ExchangeRate: React.FC<iProps> = ({
</Box>
) : (
<Typography className={classes.rateText}>
1 {tokenFromSymbol} = {isNaN(amount) ? 0 : formatNumber(amount.toFixed(tokenToDecimals))}{' '}
1 {tokenFromSymbol} ={' '}
{isNaN(amount)
? 0
: formatNumber(amount.toFixed(tokenToDecimals)) === '0'
? '~0'
: formatNumber(amount.toFixed(tokenToDecimals))}{' '}
{tokenToSymbol}
</Typography>
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ const TransactionDetailsBox: React.FC<IProps> = ({
<Typography className={classes.value}>
{exchangeRate.val === Infinity
? '-'
: `${formatNumber(exchangeRate.val.toFixed(exchangeRate.decimal))} ${exchangeRate.symbol}`}
: `${formatNumber(exchangeRate.val.toFixed(exchangeRate.decimal)) === '0' ? '~0' : formatNumber(exchangeRate.val.toFixed(exchangeRate.decimal))} ${exchangeRate.symbol}`}
</Typography>
)}
</Grid>
Expand Down
26 changes: 18 additions & 8 deletions src/containers/NewPositionWrapper/NewPositionWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -255,14 +255,24 @@ export const NewPositionWrapper: React.FC<IProps> = ({
}, [isWaitingForNewPool, tokenA, tokenB, feeIndex, poolKey, allPoolKeys, allPools.length])

useEffect(() => {
if (poolKey !== '') {
dispatch(
positionsActions.getCurrentPlotTicks({
poolKey: allPoolKeys[poolKey],
isXtoY,
fetchTicksAndTickmap: true
})
)
if (poolKey !== '' && !isWaitingForNewPool) {
const isCurrentTokenX = isXtoY
? allPoolKeys[poolKey].tokenX === tokenA
: allPoolKeys[poolKey].tokenX === tokenB

const isCurrentTokenY = isXtoY
? allPoolKeys[poolKey].tokenY === tokenB
: allPoolKeys[poolKey].tokenY === tokenA

if (isCurrentTokenX && isCurrentTokenY) {
dispatch(
positionsActions.getCurrentPlotTicks({
poolKey: allPoolKeys[poolKey],
isXtoY,
fetchTicksAndTickmap: true
})
)
}
}
}, [isWaitingForNewPool, tokenA, tokenB, poolKey, allPoolKeys])

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ export const SinglePositionWrapper: React.FC<IProps> = ({ id }) => {
}

useEffect(() => {
dispatch(actions.getRemainingPositions())
dispatch(actions.getRemainingPositions({ setLoaded: false }))
const timer = setTimeout(() => {
setIsFinishedDelayRender(true)
}, 1000)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ export const WrappedPositionsList: React.FC = () => {
length={length}
loadedPages={loadedPages}
getRemainingPositions={() => {
dispatch(actions.getRemainingPositions())
dispatch(actions.getRemainingPositions({ setLoaded: true }))
}}
noInitialPositions={list.length === 0}
/>
Expand Down
2 changes: 2 additions & 0 deletions src/hideErrors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ export const messagesToHide: string[] = [
'<path> attribute d: Expected moveto path command'
]

if (process.env.NODE_ENV === 'production') console.log = () => {}

export function filterConsoleMessages(hideMessages: string[]): void {
if (typeof window === 'undefined') {
return
Expand Down
1 change: 1 addition & 0 deletions src/store/reducers/pools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ export interface FetchTicksAndTickMaps {
tokenFrom: string
tokenTo: string
allPools: PoolWithPoolKey[]
poolKey?: PoolKey
}

const network =
Expand Down
2 changes: 1 addition & 1 deletion src/store/reducers/positions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ const positionsSlice = createSlice({
state.positionsList.loading = true
return state
},
getRemainingPositions(state, _action: PayloadAction<void>) {
getRemainingPositions(state, _action: PayloadAction<{ setLoaded: boolean }>) {
state.positionsList.loading = true
return state
},
Expand Down
21 changes: 16 additions & 5 deletions src/store/sagas/pools.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { PoolKey, newPoolKey } from '@invariant-labs/a0-sdk'
import { PayloadAction } from '@reduxjs/toolkit'
import { findPairs, getTokenBalances, getTokenDataByAddresses } from '@utils/utils'
import { findPairs, getTokenBalances, getTokenDataByAddresses, poolKeyToString } from '@utils/utils'
import { FetchTicksAndTickMaps, PairTokens, PoolWithPoolKey, actions } from '@store/reducers/pools'
import { actions as walletActions } from '@store/reducers/wallet'
import { tokens } from '@store/selectors/pools'
import { poolsArraySortedByFees, tokens } from '@store/selectors/pools'
import { address } from '@store/selectors/wallet'
import { all, call, put, select, spawn, takeEvery, takeLatest } from 'typed-redux-saga'
import { all, call, put, select, spawn, take, takeEvery, takeLatest } from 'typed-redux-saga'
import { MAX_POOL_KEYS_RETURNED } from '@invariant-labs/a0-sdk/target/consts'
import { getInvariant, getPSP22 } from './connection'

Expand Down Expand Up @@ -77,11 +77,22 @@ export function* fetchAllPoolsForPairData(action: PayloadAction<PairTokens>) {
}

export function* fetchTicksAndTickMaps(action: PayloadAction<FetchTicksAndTickMaps>) {
const { tokenFrom, tokenTo, allPools } = action.payload
const { tokenFrom, tokenTo, poolKey } = action.payload
let poolsData = yield* select(poolsArraySortedByFees)

if (poolKey) {
let pools = poolsData.filter(pool => poolKeyToString(pool.poolKey) === poolKeyToString(poolKey))

if (pools.length === 0) {
yield* take(actions.addPool)

poolsData = yield* select(poolsArraySortedByFees)
}
}

try {
const invariant = yield* getInvariant()
const pools = findPairs(tokenFrom.toString(), tokenTo.toString(), allPools)
const pools = findPairs(tokenFrom.toString(), tokenTo.toString(), poolsData)

const tickmapCalls = pools.map(pool =>
call([invariant, invariant.getFullTickmap], pool.poolKey)
Expand Down
20 changes: 15 additions & 5 deletions src/store/sagas/positions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
INVARIANT_CREATE_POSITION_OPTIONS,
INVARIANT_REMOVE_POSITION_OPTIONS,
INVARIANT_WITHDRAW_ALL_WAZERO,
POOL_SAFE_TRANSACTION_FEE,
POSITIONS_PER_QUERY,
PSP22_APPROVE_OPTIONS,
U128MAX,
Expand Down Expand Up @@ -122,8 +123,13 @@ function* handleInitPosition(action: PayloadAction<InitPositionData>): Generator
(tokenY === wazeroAddress && tokenYAmount !== 0n)
) {
const isTokenX = tokenX === wazeroAddress
const azeroInputAmount = isTokenX ? tokenXAmount : tokenYAmount

const slippageAmount = isTokenX ? xAmountWithSlippage : yAmountWithSlippage
const azeroAmount = azeroBalance > slippageAmount ? slippageAmount : azeroBalance
const azeroAmount =
azeroBalance - POOL_SAFE_TRANSACTION_FEE > slippageAmount
? slippageAmount
: azeroInputAmount

const depositTx = wazero.depositTx(azeroAmount, WAZERO_DEPOSIT_OPTIONS)
txs.push(depositTx)
Expand Down Expand Up @@ -275,7 +281,8 @@ export function* handleGetCurrentPlotTicks(action: PayloadAction<GetCurrentTicks
payload: {
tokenFrom: allTokens[poolKey.tokenX].address,
tokenTo: allTokens[poolKey.tokenY].address,
allPools
allPools,
poolKey
}
}

Expand Down Expand Up @@ -327,7 +334,8 @@ export function* handleGetCurrentPlotTicks(action: PayloadAction<GetCurrentTicks
yDecimal
)

yield* call(handleGetRemainingPositions)
yield* put(actions.getRemainingPositions({ setLoaded: false }))

const { list } = yield* select(positionsList)
const userRawTicks = getLiquidityTicksByPositionsList(poolKey, list)

Expand Down Expand Up @@ -609,7 +617,9 @@ export function* handleClosePosition(action: PayloadAction<ClosePositionData>) {
}
}

export function* handleGetRemainingPositions(): Generator {
export function* handleGetRemainingPositions(
action: PayloadAction<{ setLoaded: boolean }>
): Generator {
const walletAddress = yield* select(address)
const { length, list, loadedPages } = yield* select(positionsList)

Expand Down Expand Up @@ -641,7 +651,7 @@ export function* handleGetRemainingPositions(): Generator {
yield* put(
actions.setPositionsListLoadedStatus({
indexes: pages.map(({ index }: { index: number }) => index),
isLoaded: true
isLoaded: action.payload.setLoaded
})
)
} catch (error) {
Expand Down
13 changes: 8 additions & 5 deletions src/store/sagas/swap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
ErrorMessage,
INVARIANT_SWAP_OPTIONS,
PSP22_APPROVE_OPTIONS,
SWAP_SAFE_TRANSACTION_FEE,
U128MAX,
WAZERO_DEPOSIT_OPTIONS,
WAZERO_WITHDRAW_OPTIONS
Expand Down Expand Up @@ -98,7 +99,10 @@ export function* handleSwap(action: PayloadAction<Omit<Swap, 'txid'>>): Generato
if ((xToY && poolKey.tokenX === wazeroAddress) || (!xToY && poolKey.tokenY === wazeroAddress)) {
const azeroBalance = yield* select(balance)
const azeroAmountInWithSlippage =
azeroBalance > calculatedAmountIn ? calculatedAmountIn : azeroBalance
azeroBalance - SWAP_SAFE_TRANSACTION_FEE > calculatedAmountIn
? calculatedAmountIn
: amountIn

const depositTx = wazero.depositTx(azeroAmountInWithSlippage, WAZERO_DEPOSIT_OPTIONS)
txs.push(depositTx)
}
Expand Down Expand Up @@ -282,7 +286,6 @@ export function* handleGetSimulateResult(action: PayloadAction<Simulate>) {
let fee = 0n

let swapPossible = false
let insufficientLiquidityPoolKey = null

const errors = []

Expand All @@ -300,7 +303,7 @@ export function* handleGetSimulateResult(action: PayloadAction<Simulate>) {
byAmountIn,
xToY ? MIN_SQRT_PRICE : MAX_SQRT_PRICE
)

console.log(result)
if (result.maxSwapStepsReached || result.globalInsufficientLiquidity) {
if (
byAmountIn
Expand All @@ -309,7 +312,7 @@ export function* handleGetSimulateResult(action: PayloadAction<Simulate>) {
) {
insufficientLiquidityAmountOut = byAmountIn ? result.amountOut : result.amountIn
fee = pool.poolKey.feeTier.fee
insufficientLiquidityPoolKey = pool.poolKey
priceImpact = 1
errors.push(SwapError.MaxSwapStepsReached)
}

Expand Down Expand Up @@ -346,7 +349,7 @@ export function* handleGetSimulateResult(action: PayloadAction<Simulate>) {

yield put(
actions.setSimulateResult({
poolKey: swapPossible ? poolKey : insufficientLiquidityPoolKey,
poolKey: swapPossible ? poolKey : null,
amountOut: validatedAmountOut,
priceImpact,
targetSqrtPrice,
Expand Down

0 comments on commit 5e149ff

Please sign in to comment.