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

unlocking stake for terra #604

Merged
merged 2 commits into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
10 changes: 6 additions & 4 deletions components/Pages/Trade/Liquidity/hooks/useClosePosition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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: {
Expand Down Expand Up @@ -88,8 +88,10 @@ export const useClosePosition = ({ item, pool }: OpenPosition) => {

return useMemo(() => ({
submit,
onSuccess,
...state,
...tx,

}),
[tx, state, submit])
[tx, state, submit, onSuccess])
}
Original file line number Diff line number Diff line change
@@ -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)
Expand All @@ -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 })) || []
}))

Expand Down Expand Up @@ -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: {
Expand Down Expand Up @@ -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
}
Expand All @@ -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),
},
)
}
116 changes: 57 additions & 59 deletions components/Pages/Trade/Liquidity/hooks/useLockedPositions.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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
Expand All @@ -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,
Expand All @@ -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
Expand All @@ -137,17 +135,17 @@ const useLockedPositions = (pool: PoolEntityType) => {
pool?.staking_address,
pool?.pool_id,
tokens,
pool_assets,
poolAssets,
prices,
alliancePositions,
],
queryFn: (): Promise<Position[]> => fetchPositions(
pool?.pool_id,
walletChainName as WalletChainName,
cosmWasmClient,
prices,
pool?.staking_address,
address,
pool_assets,
poolAssets,
totalReserve,
totalLpSupply,
alliancePositions,
Expand Down
2 changes: 1 addition & 1 deletion constants/tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
9 changes: 4 additions & 5 deletions hooks/useClients.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
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 {
cosmosAminoConverters,
cosmosProtoRegistry,
cosmwasmAminoConverters,
cosmwasmProtoRegistry,
} from '@nick134-bit/nicks-injectivejs/dist/codegen';
} from '@nick134-bit/nicks-injectivejs/dist/codegen'

export const useClients = (walletChainName: string) => {
const {
Expand Down Expand Up @@ -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
}
Expand Down
1 change: 1 addition & 0 deletions hooks/useTxStatus.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ const useTxStatus = ({ signingClient, transactionType }: UseTxStatusProps) => {
'signingClient',
'allianceRewards',
],
exact: false,
})
}, [transactionType, description, toast, queryClient, setTxState])

Expand Down
Loading