Skip to content

Commit

Permalink
Add deflation calc (#559)
Browse files Browse the repository at this point in the history
* add deflation calc logic for pool

* add deflation calc logic for swap

* update fetch way

* add owner logic

* update

* feat: add tknx

* feat: add hover tips

* feat:add tknx

* feat: hide tknx tab

---------

Co-authored-by: deep-path <[email protected]>
  • Loading branch information
xieqiancaosissi and deep-path authored Jul 4, 2024
1 parent aadaf5e commit b707a13
Show file tree
Hide file tree
Showing 8 changed files with 177 additions and 23 deletions.
84 changes: 83 additions & 1 deletion src/components/forms/SelectToken.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,7 @@ export default function SelectToken({
const [visible, setVisible] = useState(false);
const [listData, setListData] = useState<TokenMetadata[]>([]);
const [listTknData, setListTknData] = useState<TokenMetadata[]>([]);
const [listTknxData, setListTknxData] = useState<TokenMetadata[]>([]);
const [currentSort, setSort] = useState<string>('down');
const [sortBy, setSortBy] = useState<string>('near');
const [showCommonBasses, setShowCommonBasses] = useState<boolean>(true);
Expand Down Expand Up @@ -507,7 +508,22 @@ export default function SelectToken({
useTokensData(
tokens.filter(
(t) =>
TOKEN_BLACK_LIST.indexOf(t.id) === -1 && t.isRisk && !t.isUserToken
TOKEN_BLACK_LIST.indexOf(t.id) === -1 &&
t.id.indexOf('tknx') == -1 &&
t.isRisk &&
!t.isUserToken
),
balances,
visible
);
const { tokensData: tknxTokensData, loading: loadingTKNXTokensData } =
useTokensData(
tokens.filter(
(t) =>
TOKEN_BLACK_LIST.indexOf(t.id) === -1 &&
t.id.indexOf('tknx') != -1 &&
t.isRisk &&
!t.isUserToken
),
balances,
visible
Expand All @@ -525,6 +541,13 @@ export default function SelectToken({
}
}, [tknTokensData?.length, loadingTKNTokensData, currentSort]);

useEffect(() => {
if (tknTokensData?.length && !loadingTKNXTokensData) {
tknxTokensData.sort(sortTypes[currentSort].fn);
setListTknxData(tknxTokensData);
}
}, [tknxTokensData?.length, loadingTKNXTokensData, currentSort]);

useEffect(() => {
getLatestCommonBassesTokens();
}, [tokensData]);
Expand Down Expand Up @@ -683,6 +706,10 @@ export default function SelectToken({
<div class="text-navHighLightText text-xs text-left w-64 xsm:w-52">
Created by any user on https://tkn.homes with the tkn.near suffix, poses high risks. Ref has not certified it. Exercise caution.
</div>`;
const TknxTip = `
<div class="text-navHighLightText text-xs text-left w-64 xsm:w-52">
Created by any user on https://tkn.homes with the tknx.near suffix, poses high risks. Ref has not certified it. Exercise caution.
</div>`;
return (
<MicroModal
open={visible}
Expand Down Expand Up @@ -843,6 +870,27 @@ export default function SelectToken({
<CustomTooltip id="tknId" />
</div>
</div>
{/* tknx */}
{/* <div
className={`text-center px-2.5 py-2 ${
activeTab === 'TKNX'
? 'text-white bg-primaryOrderly bg-opacity-20 rounded-lg'
: ''
}`}
onClick={() => setActiveTab('TKNX')}
>
TKNX
<div
className="text-white text-right ml-1 inline-block"
data-class="reactTip"
data-tooltip-id="tknId"
data-place="left"
data-tooltip-html={TknxTip}
>
<QuestionMark></QuestionMark>
<CustomTooltip id="tknId" />
</div>
</div> */}
</div>
<div>
{activeTab === 'Default' && (
Expand Down Expand Up @@ -915,6 +963,33 @@ export default function SelectToken({
showRiskTokens={true}
/>
)}

{activeTab === 'TKNX' && (
<SelectTokenTable
sortBy={sortBy}
tokenPriceList={tokenPriceList}
currentSort={currentSort}
onSortChange={onSortChange}
tokens={listTknxData}
onClick={(token) => {
if (token.id != NEARXIDS[0]) {
if (
!(
token.id == WRAP_NEAR_CONTRACT_ID &&
token.symbol == 'wNEAR' &&
!allowWNEAR
)
) {
onSelect && onSelect(token);
}
}
handleClose();
}}
balances={balances}
forCross={forCross}
showRiskTokens={true}
/>
)}
</div>
</localTokens.Provider>
</div>
Expand Down Expand Up @@ -950,6 +1025,13 @@ export default function SelectToken({
</div>
</div>
) : null}
{tknSearchNoData && activeTab === 'TKNX' ? (
<div className="flex flex-col items-center justify-center mt-32 relative z-10">
<div className="text-sm text-farmText">
<FormattedMessage id="no_token_found"></FormattedMessage>
</div>
</div>
) : null}
</section>
)}
</MicroModal>
Expand Down
39 changes: 35 additions & 4 deletions src/components/swap/SwapCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import React, {
import { FormattedMessage, useIntl } from 'react-intl';
import { useHistory, useLocation } from 'react-router-dom';

import { CountdownTimer } from '../../components/icon';
import { DEFLATION_MARK } from '../../utils/token';
import { RateExchangeMobile } from '../../components/icon/Common';
import { useWalletSelector } from '../../context/WalletSelectorContext';
import { TextWrapper } from '../../pages/Orderly/components/UserBoard';
Expand All @@ -28,6 +28,7 @@ import {
ftGetBalance,
REF_META_DATA,
TokenMetadata,
tokenFtMetadata,
} from '../../services/ft-contract';
import { USD_CLASS_STABLE_TOKEN_IDS } from '../../services/near';
import {
Expand Down Expand Up @@ -731,6 +732,8 @@ export default function SwapCard(props: {

const [balanceInDone, setBalanceInDone] = useState<boolean>(false);
const [balanceOutDone, setBalanceOutDone] = useState<boolean>(false);
const [tokenDeflationRateData, setTokenDeflationRateData] =
useState<Record<string, any>>();

const intl = useIntl();
const location = useLocation();
Expand Down Expand Up @@ -910,7 +913,33 @@ export default function SwapCard(props: {
setWrapOperation(false);
}
}, [tokenIn, tokenOut, useNearBalance, isSignedIn, nearBalance]);

useEffect(() => {
if (tokenIn?.id) {
if (tokenIn?.id.includes(DEFLATION_MARK)) {
getTokenDeflationRate();
} else {
setTokenDeflationRateData({
rate: '0',
done: true,
});
}
} else {
setTokenDeflationRateData(undefined);
}
}, [tokenIn?.id]);
async function getTokenDeflationRate() {
setTokenDeflationRateData(undefined);
const tokenMeta = await tokenFtMetadata(tokenIn.id);
const rate =
((tokenMeta?.deflation_strategy?.fee_strategy?.SellFee?.fee_rate ?? 0) +
(tokenMeta?.deflation_strategy?.burn_strategy?.SellBurn?.burn_rate ??
0)) /
1000000;
setTokenDeflationRateData({
rate,
done: true,
});
}
function getStorageTokenId() {
const in_key = localStorage.getItem(SWAP_IN_KEY);
const in_key_symbol = localStorage.getItem(SWAP_IN_KEY_SYMBOL);
Expand Down Expand Up @@ -959,10 +988,11 @@ export default function SwapCard(props: {
useSwapPopUp();

useCrossSwapPopUp();

useRefSwapPro({
tokenIn,
tokenInAmount,
tokenInAmount: Big(1 - (tokenDeflationRateData?.rate || 0))
.mul(tokenInAmount || 0)
.toFixed(),
tokenOut,
slippageTolerance,
setLoadingData,
Expand All @@ -977,6 +1007,7 @@ export default function SwapCard(props: {
setQuoting,
setReEstimateTrigger,
quoting,
tokenDeflationRateData,
});

useEffect(() => {
Expand Down
2 changes: 0 additions & 2 deletions src/pages/SwapPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,6 @@ function getAllTokens(refTokens: TokenMetadata[], triTokens: TokenMetadata[]) {
refTokens.push(tk);
}
});

return refTokens;
}

Expand Down Expand Up @@ -341,7 +340,6 @@ function SwapPage() {
const crossSwapTokens = allTokens.filter(
(token) => token.onTri || token.onRef
);

const SwapNav = (
<ChangeSwapMode
setLimitTokenTrigger={setLimitTokenTrigger}
Expand Down
7 changes: 7 additions & 0 deletions src/services/ft-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,3 +248,10 @@ export const unWrapToken = (token: TokenMetadata, keepId?: boolean) => {
return { ...nearMetadata, id: keepId ? token.id : nearMetadata.id };
else return token;
};

export const tokenFtMetadata = async (tokenId: string) => {
const metadata = await ftViewFunction(tokenId, {
methodName: 'tknx_metadata',
});
return metadata;
};
37 changes: 33 additions & 4 deletions src/services/pool.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import Big from 'big.js';
import {
executeMultipleTransactions,
LP_STORAGE_AMOUNT,
Expand All @@ -13,6 +14,7 @@ import {
ftGetStorageBalance,
TokenMetadata,
native_usdc_has_upgrated,
tokenFtMetadata,
} from './ft-contract';
import {
toNonDivisibleNumber,
Expand Down Expand Up @@ -57,6 +59,7 @@ import { getStablePoolDecimal } from '../pages/stable/StableSwapEntry';
import { cacheAllDCLPools } from './swapV3';
import { REF_DCL_POOL_CACHE_KEY } from '../state/swap';
import getConfigV2 from '../services/configV2';
import { DEFLATION_MARK } from '../utils/token';
const { NO_REQUIRED_REGISTRATION_TOKEN_IDS } = getConfigV2();

const explorerType = getExplorer();
Expand Down Expand Up @@ -774,17 +777,43 @@ export const addLiquidityToPool = async ({
id,
tokenAmounts,
}: AddLiquidityToPoolOptions) => {
// const transactions:Transaction[] = []

const amounts = tokenAmounts.map(({ token, amount }) =>
let amounts = tokenAmounts.map(({ token, amount }) =>
toNonDivisibleNumber(token.decimals, amount)
);

const transactions = await getDepositTransactions({
tokens: tokenAmounts.map(({ token, amount }) => token),
amounts: tokenAmounts.map(({ token, amount }) => amount),
});

// add deflation calc logic
const tknx_tokens = tokenAmounts
.map((item) => item.token)
.filter((token) => token.id.includes(DEFLATION_MARK));
if (tknx_tokens.length > 0) {
const pending = tknx_tokens.map((token) => tokenFtMetadata(token.id));
const tokenFtMetadatas = await Promise.all(pending);
const rate = tokenFtMetadatas.reduce((acc, cur, index) => {
const is_owner =
cur.owner_account_id == getCurrentWallet()?.wallet?.getAccountId();
return {
...acc,
[tknx_tokens[index].id]: is_owner
? 0
: (cur?.deflation_strategy?.fee_strategy?.SellFee?.fee_rate ?? 0) +
(cur?.deflation_strategy?.burn_strategy?.SellBurn?.burn_rate ?? 0),
};
}, {});
amounts = tokenAmounts.map(({ token, amount }) => {
const reforeAmount = toNonDivisibleNumber(token.decimals, amount);
let afterAmount = reforeAmount;
if (rate[token.id]) {
afterAmount = Big(1 - rate[token.id] / 1000000)
.mul(reforeAmount)
.toFixed(0);
}
return afterAmount;
});
}
const actions: RefFiFunctionCallOptions[] = [
{
methodName: 'add_liquidity',
Expand Down
Loading

0 comments on commit b707a13

Please sign in to comment.