From 5298708155e45d699043f848064ff6454c109a66 Mon Sep 17 00:00:00 2001 From: w0rrex <68468180+worrex@users.noreply.github.com> Date: Tue, 3 Dec 2024 13:14:34 +0100 Subject: [PATCH] unlocking stake for terra (#604) * unlocking stake for terra * linting and invalidate positions query onSuccess --- .../Trade/Liquidity/hooks/useClosePosition.ts | 10 +- .../hooks/useLiquidityAlliancePositions.ts | 19 ++- .../Liquidity/hooks/useLockedPositions.ts | 116 +++++++++--------- constants/tokens.ts | 2 +- hooks/useClients.ts | 9 +- hooks/useTxStatus.tsx | 1 + 6 files changed, 78 insertions(+), 79 deletions(-) diff --git a/components/Pages/Trade/Liquidity/hooks/useClosePosition.ts b/components/Pages/Trade/Liquidity/hooks/useClosePosition.ts index 6f4a7b56..f1495c3b 100644 --- a/components/Pages/Trade/Liquidity/hooks/useClosePosition.ts +++ b/components/Pages/Trade/Liquidity/hooks/useClosePosition.ts @@ -8,10 +8,10 @@ import { TxRaw } from 'cosmjs-types/cosmos/tx/v1beta1/tx'; import { useClients } from 'hooks/useClients' import useTxStatus from 'hooks/useTxStatus' import { useRecoilValue } from 'recoil' +import { isNativeToken } from 'services/asset' import { createGasFee } from 'services/treasuryService' import { chainState } from 'state/chainState' import { createExecuteMessage, validateTransactionSuccess } from 'util/messages/index' -import { isNativeToken } from '../../../../../services/asset' type OpenPosition = { item: any @@ -41,8 +41,8 @@ export const useClosePosition = ({ item, pool }: OpenPosition) => { if (unbonding_duration === -1 && chainId === ChainId.terra && item?.liquidity_alliance) { const tokenInfo = isNativeToken(pool.lp_token) - ? { native: pool.lp_token } - : { cw20: pool.lp_token}; + ? { native: pool.lp_token } + : { cw20: pool.lp_token } msg = createExecuteMessage({ message: { @@ -88,8 +88,10 @@ export const useClosePosition = ({ item, pool }: OpenPosition) => { return useMemo(() => ({ submit, + onSuccess, ...state, ...tx, + }), - [tx, state, submit]) + [tx, state, submit, onSuccess]) } diff --git a/components/Pages/Trade/Liquidity/hooks/useLiquidityAlliancePositions.ts b/components/Pages/Trade/Liquidity/hooks/useLiquidityAlliancePositions.ts index 7e6bea4c..ebadf8f2 100644 --- a/components/Pages/Trade/Liquidity/hooks/useLiquidityAlliancePositions.ts +++ b/components/Pages/Trade/Liquidity/hooks/useLiquidityAlliancePositions.ts @@ -1,12 +1,11 @@ import { useQuery } from 'react-query' import { useChain } from '@cosmos-kit/react-lite' +import { ChainId, TERRA2_BRIBE_MARKETS } from 'constants/index' import { useClients } from 'hooks/useClients' import { useRecoilValue } from 'recoil' import { chainState } from 'state/chainState' -import { TERRA2_BRIBE_MARKETS } from '../../../../../constants' - export const useLiquidityAlliancePositions = (lp_token?: any) => { const { chainId, walletChainName } = useRecoilValue(chainState) const { address } = useChain(walletChainName) @@ -20,10 +19,10 @@ export const useLiquidityAlliancePositions = (lp_token?: any) => { } const result = await Promise.all(Object.values(TERRA2_BRIBE_MARKETS).map(async (bribeMarket) => { - const staked_balances = await cosmWasmClient?.queryContractSmart(bribeMarket, { + const stakedBalances = await cosmWasmClient?.queryContractSmart(bribeMarket, { all_staked_balances: { address }, }) - return staked_balances?.map((position) => ({ ...position, + return stakedBalances?.map((position) => ({ ...position, bribe_market: bribeMarket })) || [] })) @@ -56,15 +55,15 @@ export const queryAllStakedBalances = async ( cosmWasmClient: any, address: string, pool?: any, ) => { const result = await Promise.all(Object.values(TERRA2_BRIBE_MARKETS).map(async (bribeMarket) => { - const staked_balances = await cosmWasmClient?.queryContractSmart(bribeMarket, { + const stakedBalances = await cosmWasmClient?.queryContractSmart(bribeMarket, { all_staked_balances: { address }, }) - return staked_balances?.map((position) => ({ ...position, + return stakedBalances?.map((position) => ({ ...position, bribe_market: bribeMarket })) || [] })) return result. flat(). - filter((position) => (!pool || position.asset.info.native === pool.lp_token || position.asset.info.cw20 === pool.lp_token) && + filter((position) => (!pool || position.asset.info.native === pool.lp_token || position.asset.info.cw20 === pool.lp_token) && position.shares !== '1'). map((position) => ({ open_position: { @@ -139,7 +138,7 @@ export const fetchAllAllianceRewards = async ( asset.reward_asset.bribe_market = bribeMarket if (asset.reward_asset.info.native.endsWith('zluna')) { const claimAddress = asset.reward_asset.info.native.split('/')[1] - //ampLuna + // AmpLuna asset.reward_asset.info.contract_addr = 'terra1ecgazyd0waaj3g7l9cmy5gulhxkps2gmxu9ghducvuypjq68mq2s5lvsct' asset.reward_asset.info.claim_addr = claimAddress } @@ -160,8 +159,8 @@ export const useAllianceRewards = () => { cosmWasmClient, address, chainId, ), { - refetchInterval: 30 * 60 * 1000, - enabled: chainId === 'phoenix-1' && Boolean(address), + refetchInterval: 30 * 60 * 1_000, + enabled: chainId === ChainId.terra && Boolean(address), }, ) } diff --git a/components/Pages/Trade/Liquidity/hooks/useLockedPositions.ts b/components/Pages/Trade/Liquidity/hooks/useLockedPositions.ts index 689b1b7c..957c2fba 100644 --- a/components/Pages/Trade/Liquidity/hooks/useLockedPositions.ts +++ b/components/Pages/Trade/Liquidity/hooks/useLockedPositions.ts @@ -1,9 +1,10 @@ import { useQuery } from 'react-query' -import { CosmWasmClient } from '@cosmjs/cosmwasm-stargate'; +import { CosmWasmClient } from '@cosmjs/cosmwasm-stargate' import { useChain } from '@cosmos-kit/react-lite' import { PoolEntityType, TokenInfo } from 'components/Pages/Trade/Pools/hooks/usePoolsListQuery' import { useQueryPoolLiquidity } from 'components/Pages/Trade/Pools/hooks/useQueryPoolsLiquidity' +import { WalletChainName } from 'constants/index' import { PositionState } from 'constants/state' import dayjs from 'dayjs' import { useClients } from 'hooks/useClients' @@ -15,7 +16,7 @@ import { chainState } from 'state/chainState' import { protectAgainstNaN } from 'util/conversion/index' import { formatSeconds } from 'util/formatSeconds' -import { useLiquidityAlliancePositions } from './useLiquidityAlliancePositions'; +import { useLiquidityAlliancePositions } from './useLiquidityAlliancePositions' export type Position = { poolId: string @@ -40,12 +41,12 @@ export const lpPositionToAssets = ({ protectAgainstNaN(totalAssets[1] * (myLockedLp / totalLpSupply)), ] export const fetchPositions = async ( - poolId: string, + walletChainName: WalletChainName, cosmWasmClient: CosmWasmClient, prices: any, incentiveAddress: string, address: string, - pool_assets: any[], + poolAssets: any[], totalAssets: any, totalLpSupply: any, alliancePositions?: any, @@ -61,65 +62,62 @@ export const fetchPositions = async ( }) } const allPositions = [...data.positions, ...alliancePositions || []] - const positions = allPositions. - map((p) => { - const positions = [] + return allPositions.map((p) => { + const positions = [] - // Open position - const open = { ...(p?.open_position || {}) } - open.formatedTime = formatSeconds(open.unbonding_duration) - open.isOpen = true - if (p?.open_position) { - positions.push(open) - } + // Open position + const open = { ...(p?.open_position || {}) } + open.formatedTime = formatSeconds(open.unbonding_duration) + open.isOpen = true + if (p?.open_position) { + positions.push(open) + } - // Closed position - const close = { ...(p?.closed_position || {}) } - const today = dayjs(new Date()) - const unbonding = dayjs.unix(close.unbonding_timestamp) - const diff = unbonding.diff(today, 'second') - close.formatedTime = formatSeconds(diff) - close.isOpen = false - if (p?.closed_position) { - positions.push(close) - } - return positions.map((position) => { - const lpAssets = lpPositionToAssets({ - totalAssets, - totalLpSupply, - myLockedLp: position.amount, - }) - const assets = pool_assets.map((asset, i) => { - const assetAmount = fromChainAmount(lpAssets[i], asset.decimals) - const dollarValue = Number(assetAmount) * (prices?.[asset.symbol] || 0) - return { - ...asset, - amount: parseFloat(assetAmount), - dollarValue, - } - }) - const isWithdraw = poolId === 'ampLUNA-LUNA' || poolId === 'bLUNA-LUNA' || poolId === 'WHALE-axlUSDC' + // Closed position + const close = { ...(p?.closed_position || {}) } + const today = dayjs(new Date()) + const unbonding = dayjs.unix(close.unbonding_timestamp) + const diff = unbonding.diff(today, 'second') + close.formatedTime = formatSeconds(diff) + close.isOpen = false + if (p?.closed_position) { + positions.push(close) + } + return positions.map((position) => { + const lpAssets = lpPositionToAssets({ + totalAssets, + totalLpSupply, + myLockedLp: position.amount, + }) + const assets = poolAssets.map((asset, i) => { + const assetAmount = fromChainAmount(lpAssets[i], asset.decimals) + const dollarValue = Number(assetAmount) * (prices?.[asset.symbol] || 0) return { - ...position, - duration: position.isOpen ? (open.unbonding_duration == -1 ? 'Alliance' : position.formatedTime) : position.formatedTime, - weight: position.weight, - assets, - value: assets.reduce((acc, asset) => acc + Number(asset.dollarValue), - 0), - state: position.isOpen - ? PositionState.active - : diff <= 0 - ? PositionState.unbonded - : isWithdraw ? PositionState.withdraw : PositionState.unbonding, - action: null, + ...asset, + amount: parseFloat(assetAmount), + dollarValue, } }) - }). - flat() - return positions + const isWithdraw = walletChainName === WalletChainName.terra + return { + ...position, + duration: position.isOpen ? (open.unbonding_duration === -1 ? 'Alliance' : position.formatedTime) : position.formatedTime, + weight: position.weight, + assets, + value: assets.reduce((acc, asset) => acc + Number(asset.dollarValue), + 0), + state: position.isOpen + ? PositionState.active + : diff <= 0 + ? PositionState.unbonded + : isWithdraw ? PositionState.withdraw : PositionState.unbonding, + action: null, + } + }) + }).flat() } const useLockedPositions = (pool: PoolEntityType) => { - const [{ liquidity = {}, pool_assets = [] } = {}] = + const [{ liquidity = {}, pool_assets: poolAssets = [] } = {}] = useQueryPoolLiquidity({ poolId: pool?.pool_id }) const { data: alliancePositions, isLoading } = useLiquidityAlliancePositions(pool?.lp_token) const totalLpSupply = liquidity?.available?.totalLpAmount || 0 @@ -137,17 +135,17 @@ const useLockedPositions = (pool: PoolEntityType) => { pool?.staking_address, pool?.pool_id, tokens, - pool_assets, + poolAssets, prices, alliancePositions, ], queryFn: (): Promise => fetchPositions( - pool?.pool_id, + walletChainName as WalletChainName, cosmWasmClient, prices, pool?.staking_address, address, - pool_assets, + poolAssets, totalReserve, totalLpSupply, alliancePositions, diff --git a/constants/tokens.ts b/constants/tokens.ts index d42b8b13..3ca01511 100644 --- a/constants/tokens.ts +++ b/constants/tokens.ts @@ -6,6 +6,6 @@ export const TERRA2_BRIBE_MARKETS = { project: 'terra1awq6t7jfakg9wfjn40fk3wzwmd57mvrqtt3a39z9rmet7wdjj3ysgw3lpa', bluechip: 'terra14mmvqn0kthw6sre75vku263lafn5655mkjdejqjedjga4cw0qx2qlf4arv', stable: 'terra1v399cx9drllm70wxfsgvfe694tdsd9x96p9ha36w7muffe4znlusqswspq', - single: 'terra1qdz5qgafx88kp5mf6m2tah8742g4u5g2cek0m3jrgssexexk7g4qw6e23k' + single: 'terra1qdz5qgafx88kp5mf6m2tah8742g4u5g2cek0m3jrgssexexk7g4qw6e23k', } export const POOL_TOKENS_DECIMALS = 6 diff --git a/hooks/useClients.ts b/hooks/useClients.ts index f7763244..cd75d4e6 100644 --- a/hooks/useClients.ts +++ b/hooks/useClients.ts @@ -1,7 +1,7 @@ import { useQueries } from 'react-query' -import { GeneratedType, Registry } from '@cosmjs/proto-signing'; -import { AminoTypes } from '@cosmjs/stargate'; +import { GeneratedType, Registry } from '@cosmjs/proto-signing' +import { AminoTypes } from '@cosmjs/stargate' import { useChain } from '@cosmos-kit/react-lite' import { InjectiveSigningStargateClient } from '@injectivelabs/sdk-ts/dist/cjs/core/stargate' import { @@ -9,7 +9,7 @@ import { cosmosProtoRegistry, cosmwasmAminoConverters, cosmwasmProtoRegistry, -} from '@nick134-bit/nicks-injectivejs/dist/codegen'; +} from '@nick134-bit/nicks-injectivejs/dist/codegen' export const useClients = (walletChainName: string) => { const { @@ -56,14 +56,13 @@ export const useClients = (walletChainName: string) => { const registry: any = new Registry(protoRegistry); const aminoTypes = new AminoTypes(aminoConverters); const endpoint = await getRpcEndpoint() - const client = await InjectiveSigningStargateClient.connectWithSigner( + return await InjectiveSigningStargateClient.connectWithSigner( endpoint, offlineSigner, { registry, aminoTypes, }, ) - return client } catch { return null } diff --git a/hooks/useTxStatus.tsx b/hooks/useTxStatus.tsx index dc91f2d8..1e623f62 100644 --- a/hooks/useTxStatus.tsx +++ b/hooks/useTxStatus.tsx @@ -107,6 +107,7 @@ const useTxStatus = ({ signingClient, transactionType }: UseTxStatusProps) => { 'signingClient', 'allianceRewards', ], + exact: false, }) }, [transactionType, description, toast, queryClient, setTxState])