@ape.swap/bonds-sdk 6.2.1 → 6.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/MenuSelect/MenuSelect.d.ts +1 -1
- package/dist/components/MenuSelect/MenuSelect.js.map +1 -1
- package/dist/components/ProgressBar/ProgressBarWrapper.d.ts +1 -1
- package/dist/components/ProgressBar/ProgressBarWrapper.js.map +1 -1
- package/dist/components/TokenInfoAndName/index.d.ts +0 -1
- package/dist/components/TokenInfoAndName/index.js +1 -1
- package/dist/components/TokenInfoAndName/index.js.map +1 -1
- package/dist/components/TokenSelectorModal/TokenRow.js +2 -2
- package/dist/components/TokenSelectorModal/TokenRow.js.map +1 -1
- package/dist/components/TokenSelectorPanel/index.js +3 -3
- package/dist/components/TokenSelectorPanel/index.js.map +1 -1
- package/dist/components/Tooltip/Tooltip.d.ts +1 -1
- package/dist/components/Tooltip/Tooltip.js.map +1 -1
- package/dist/components/uikit-sdk/Button/Button.js +0 -36
- package/dist/components/uikit-sdk/Button/Button.js.map +1 -1
- package/dist/components/uikit-sdk/Button/types.d.ts +6 -10
- package/dist/components/uikit-sdk/Button/types.js +0 -5
- package/dist/components/uikit-sdk/Button/types.js.map +1 -1
- package/dist/components/uikit-sdk/Checkbox/types.d.ts +2 -1
- package/dist/components/uikit-sdk/Checkbox/types.js.map +1 -1
- package/dist/components/uikit-sdk/Skeleton/styles.d.ts +0 -12
- package/dist/components/uikit-sdk/Skeleton/styles.js +1 -1
- package/dist/components/uikit-sdk/Skeleton/styles.js.map +1 -1
- package/dist/components/uikit-sdk/Svg/Icons/ZapIcon.d.ts +2 -2
- package/dist/components/uikit-sdk/Svg/styles.d.ts +0 -2
- package/dist/components/uikit-sdk/Svg/styles.js.map +1 -1
- package/dist/components/uikit-sdk/Text/types.d.ts +1 -1
- package/dist/components/uikit-sdk/Text/types.js +1 -1
- package/dist/components/uikit-sdk/Text/types.js.map +1 -1
- package/dist/components/uikit-sdk/TooltipBubble/types.d.ts +2 -1
- package/dist/components/uikit-sdk/TooltipBubble/types.js.map +1 -1
- package/dist/config/constants/aptosZapTokens.d.ts +0 -9
- package/dist/config/constants/aptosZapTokens.js +1 -2
- package/dist/config/constants/aptosZapTokens.js.map +1 -1
- package/dist/config/constants/networks.d.ts +0 -2
- package/dist/config/constants/networks.js +1 -1
- package/dist/config/constants/networks.js.map +1 -1
- package/dist/config/constants/tokens.d.ts +1 -2
- package/dist/constants/aptosConstants.d.ts +0 -6
- package/dist/constants/aptosConstants.js +15 -1
- package/dist/constants/aptosConstants.js.map +1 -1
- package/dist/constants/solanaConstants.d.ts +0 -6
- package/dist/constants/solanaConstants.js +0 -21
- package/dist/constants/solanaConstants.js.map +1 -1
- package/dist/constants/suiConstants.d.ts +0 -5
- package/dist/constants/suiConstants.js +11 -0
- package/dist/constants/suiConstants.js.map +1 -1
- package/dist/hooks/useSortedZapList.d.ts +1 -1
- package/dist/hooks/useSortedZapList.js +1 -2
- package/dist/hooks/useSortedZapList.js.map +1 -1
- package/dist/hooks/useTokenFromZapList.js +0 -1
- package/dist/hooks/useTokenFromZapList.js.map +1 -1
- package/dist/providers/index.d.ts +11 -0
- package/dist/providers/index.js +0 -6
- package/dist/providers/index.js.map +1 -1
- package/dist/state/allowance/useAllowance.js +2 -3
- package/dist/state/allowance/useAllowance.js.map +1 -1
- package/dist/state/balance/useCurrencyBalance.js +2 -3
- package/dist/state/balance/useCurrencyBalance.js.map +1 -1
- package/dist/state/balance/useCurrencyBalanceAptos.js +5 -5
- package/dist/state/balance/useCurrencyBalanceAptos.js.map +1 -1
- package/dist/state/balance/useCurrencyBalanceSolana.d.ts +0 -2
- package/dist/state/balance/useCurrencyBalanceSolana.js +3 -6
- package/dist/state/balance/useCurrencyBalanceSolana.js.map +1 -1
- package/dist/state/balance/useCurrencyBalanceSui.js +2 -2
- package/dist/state/balance/useCurrencyBalanceSui.js.map +1 -1
- package/dist/state/balance/useUserTokensBalance.js +3 -5
- package/dist/state/balance/useUserTokensBalance.js.map +1 -1
- package/dist/state/bondApiStats/useGetBondApiStats.d.ts +0 -1
- package/dist/state/bondApiStats/useGetBondApiStats.js +1 -1
- package/dist/state/bondApiStats/useGetBondApiStats.js.map +1 -1
- package/dist/state/bonds/fetchBondsData/cleanBillsData.js +16 -13
- package/dist/state/bonds/fetchBondsData/cleanBillsData.js.map +1 -1
- package/dist/state/bonds/fetchBondsData/fetchBondsDataAptos.d.ts +1 -1
- package/dist/state/bonds/fetchBondsData/fetchBondsDataAptos.js +4 -6
- package/dist/state/bonds/fetchBondsData/fetchBondsDataAptos.js.map +1 -1
- package/dist/state/bonds/fetchBondsData/fetchBondsDataEVM.d.ts +1 -1
- package/dist/state/bonds/fetchBondsData/fetchBondsDataEVM.js +4 -3
- package/dist/state/bonds/fetchBondsData/fetchBondsDataEVM.js.map +1 -1
- package/dist/state/bonds/fetchBondsData/fetchBondsDataSOL.d.ts +1 -1
- package/dist/state/bonds/fetchBondsData/fetchBondsDataSOL.js +2 -3
- package/dist/state/bonds/fetchBondsData/fetchBondsDataSOL.js.map +1 -1
- package/dist/state/bonds/fetchBondsData/fetchBondsDataSui.d.ts +1 -1
- package/dist/state/bonds/fetchBondsData/fetchBondsDataSui.js +5 -7
- package/dist/state/bonds/fetchBondsData/fetchBondsDataSui.js.map +1 -1
- package/dist/state/bonds/fetchUsersBonds/fetchUsersBondsEVM.d.ts +1 -2
- package/dist/state/bonds/fetchUsersBonds/fetchUsersBondsEVM.js +2 -5
- package/dist/state/bonds/fetchUsersBonds/fetchUsersBondsEVM.js.map +1 -1
- package/dist/state/bonds/fetchUsersBonds/fetchUsersBondsSOL.js +2 -5
- package/dist/state/bonds/fetchUsersBonds/fetchUsersBondsSOL.js.map +1 -1
- package/dist/state/bonds/useBondsList.d.ts +1 -2
- package/dist/state/bonds/useBondsList.js +1 -1
- package/dist/state/bonds/useBondsList.js.map +1 -1
- package/dist/state/bonds/useBondsListPreTGE.d.ts +1 -2
- package/dist/state/bonds/useBondsListPreTGE.js +1 -1
- package/dist/state/bonds/useBondsListPreTGE.js.map +1 -1
- package/dist/state/bonds/useTierProofSignature.d.ts +0 -1
- package/dist/state/bonds/useTierProofSignature.js +1 -1
- package/dist/state/bonds/useTierProofSignature.js.map +1 -1
- package/dist/state/bonds/useUserBondsPreTGE.d.ts +3 -4
- package/dist/state/bonds/useUserBondsPreTGE.js +4 -7
- package/dist/state/bonds/useUserBondsPreTGE.js.map +1 -1
- package/dist/state/historicalPrice/useHistoricalPrice.d.ts +1 -2
- package/dist/state/historicalPrice/useHistoricalPrice.js +1 -1
- package/dist/state/historicalPrice/useHistoricalPrice.js.map +1 -1
- package/dist/state/hotBonds/useHotBonds.d.ts +0 -2
- package/dist/state/hotBonds/useHotBonds.js +1 -1
- package/dist/state/hotBonds/useHotBonds.js.map +1 -1
- package/dist/state/price/useCurrencyPrice.js +1 -2
- package/dist/state/price/useCurrencyPrice.js.map +1 -1
- package/dist/state/recommendations/useGetBondRecommendations.d.ts +0 -1
- package/dist/state/recommendations/useGetBondRecommendations.js +1 -1
- package/dist/state/recommendations/useGetBondRecommendations.js.map +1 -1
- package/dist/state/tiers/useTierPoints.d.ts +0 -6
- package/dist/state/tiers/useTierPoints.js +16 -17
- package/dist/state/tiers/useTierPoints.js.map +1 -1
- package/dist/state/zap/useAptosZapQuote.d.ts +1 -16
- package/dist/state/zap/useAptosZapQuote.js +4 -4
- package/dist/state/zap/useAptosZapQuote.js.map +1 -1
- package/dist/state/zap/useJupiterSolanaQuote.js +4 -11
- package/dist/state/zap/useJupiterSolanaQuote.js.map +1 -1
- package/dist/state/zap/useSoulZapBondQuote.js +12 -21
- package/dist/state/zap/useSoulZapBondQuote.js.map +1 -1
- package/dist/state/zap/useSuiZapQuote.d.ts +1 -1
- package/dist/state/zap/useSuiZapQuote.js +9 -14
- package/dist/state/zap/useSuiZapQuote.js.map +1 -1
- package/dist/theme/base.d.ts +1 -4
- package/dist/theme/base.js +1 -1
- package/dist/theme/base.js.map +1 -1
- package/dist/theme/components.d.ts +0 -20
- package/dist/theme/components.js +1 -1
- package/dist/theme/components.js.map +1 -1
- package/dist/types/aptosBonds.d.ts +0 -60
- package/dist/types/bondIssuanceCodec.d.ts +0 -1
- package/dist/types/bondIssuanceCodec.js.map +1 -1
- package/dist/types/bondTermCodec.d.ts +0 -1
- package/dist/types/bondTermCodec.js.map +1 -1
- package/dist/types/solanaBonds.d.ts +4 -3
- package/dist/utils/aptosHelpers.d.ts +1 -14
- package/dist/utils/aptosHelpers.js +30 -2
- package/dist/utils/aptosHelpers.js.map +1 -1
- package/dist/utils/bondPriceHelpers.d.ts +1 -1
- package/dist/utils/bondPriceHelpers.js +5 -11
- package/dist/utils/bondPriceHelpers.js.map +1 -1
- package/dist/utils/calculateSolanaTrueBillPrice.d.ts +0 -4
- package/dist/utils/calculateSolanaTrueBillPrice.js +33 -32
- package/dist/utils/calculateSolanaTrueBillPrice.js.map +1 -1
- package/dist/utils/convertToBigish.d.ts +0 -1
- package/dist/utils/convertToBigish.js +3 -18
- package/dist/utils/convertToBigish.js.map +1 -1
- package/dist/utils/displayHelpers.d.ts +3 -9
- package/dist/utils/displayHelpers.js +63 -47
- package/dist/utils/displayHelpers.js.map +1 -1
- package/dist/utils/fixedPoint.d.ts +28 -0
- package/dist/utils/fixedPoint.js +239 -0
- package/dist/utils/fixedPoint.js.map +1 -0
- package/dist/utils/formatNumber.d.ts +0 -7
- package/dist/utils/formatNumber.js +6 -12
- package/dist/utils/formatNumber.js.map +1 -1
- package/dist/utils/getBalanceNumber.d.ts +1 -2
- package/dist/utils/getBalanceNumber.js +5 -3
- package/dist/utils/getBalanceNumber.js.map +1 -1
- package/dist/utils/getNativeTicker.js +0 -1
- package/dist/utils/getNativeTicker.js.map +1 -1
- package/dist/utils/suiHelpers.d.ts +0 -2
- package/dist/utils/suiHelpers.js +13 -15
- package/dist/utils/suiHelpers.js.map +1 -1
- package/dist/views/Bonds/Bonds.d.ts +0 -4
- package/dist/views/Bonds/Bonds.js.map +1 -1
- package/dist/views/Bonds/components/BondRows/ActiveBondRows.d.ts +1 -1
- package/dist/views/Bonds/components/BondRows/ActiveBondRows.js +2 -3
- package/dist/views/Bonds/components/BondRows/ActiveBondRows.js.map +1 -1
- package/dist/views/Bonds/components/BonusComponents/BonusComponent.js +1 -2
- package/dist/views/Bonds/components/BonusComponents/BonusComponent.js.map +1 -1
- package/dist/views/Bonds/components/BonusComponents/BonusTable.js +1 -2
- package/dist/views/Bonds/components/BonusComponents/BonusTable.js.map +1 -1
- package/dist/views/Bonds/components/BuyAgainRow/index.js +2 -4
- package/dist/views/Bonds/components/BuyAgainRow/index.js.map +1 -1
- package/dist/views/Bonds/components/RecommendationCards/SmallRecommendationCard.d.ts +1 -1
- package/dist/views/Bonds/components/RecommendationCards/SmallRecommendationCard.js.map +1 -1
- package/dist/views/Bonds/utils.d.ts +0 -2
- package/dist/views/Bonds/utils.js +2 -3
- package/dist/views/Bonds/utils.js.map +1 -1
- package/dist/views/BuyBond/BuyBondModal.d.ts +1 -1
- package/dist/views/BuyBond/BuyBondModal.js.map +1 -1
- package/dist/views/BuyBond/BuyComponent.js +16 -17
- package/dist/views/BuyBond/BuyComponent.js.map +1 -1
- package/dist/views/BuyBond/BuyComponentAptos.d.ts +1 -1
- package/dist/views/BuyBond/BuyComponentAptos.js +20 -33
- package/dist/views/BuyBond/BuyComponentAptos.js.map +1 -1
- package/dist/views/BuyBond/BuyComponentPreTGE.js +6 -8
- package/dist/views/BuyBond/BuyComponentPreTGE.js.map +1 -1
- package/dist/views/BuyBond/BuyComponentSolana.d.ts +1 -1
- package/dist/views/BuyBond/BuyComponentSolana.js +20 -27
- package/dist/views/BuyBond/BuyComponentSolana.js.map +1 -1
- package/dist/views/BuyBond/BuyComponentSui.d.ts +1 -1
- package/dist/views/BuyBond/BuyComponentSui.js +15 -28
- package/dist/views/BuyBond/BuyComponentSui.js.map +1 -1
- package/dist/views/BuyBond/components/NewRateModal/NewRateModal.js +2 -2
- package/dist/views/BuyBond/components/NewRateModal/NewRateModal.js.map +1 -1
- package/dist/views/BuyBond/components/PointsLeftForNextTier/PointsLeftForNextTier.js +6 -9
- package/dist/views/BuyBond/components/PointsLeftForNextTier/PointsLeftForNextTier.js.map +1 -1
- package/dist/views/ProjectView/components/BondLeaderboard/components/SalesTable.d.ts +1 -1
- package/dist/views/ProjectView/components/BondLeaderboard/components/SalesTable.js.map +1 -1
- package/dist/views/ProjectView/components/BondLeaderboard/components/TopSaleCard.d.ts +1 -1
- package/dist/views/ProjectView/components/BondLeaderboard/components/TopSaleCard.js.map +1 -1
- package/dist/views/ProjectView/components/BondLeaderboard/components/TopThreeSalesCards.d.ts +1 -1
- package/dist/views/ProjectView/components/BondLeaderboard/components/TopThreeSalesCards.js.map +1 -1
- package/dist/views/ProjectView/components/BondStats/index.js +2 -4
- package/dist/views/ProjectView/components/BondStats/index.js.map +1 -1
- package/dist/views/ProjectView/components/BondStats/types.d.ts +2 -1
- package/dist/views/ProjectView/components/BondStats/types.js.map +1 -1
- package/dist/views/SingleBond/SoldOutBuyBondPlaceholder.d.ts +1 -1
- package/dist/views/SingleBond/SoldOutBuyBondPlaceholder.js.map +1 -1
- package/dist/views/YourBonds/components/UserBondRow/UserBondRowPreTGE.js +4 -5
- package/dist/views/YourBonds/components/UserBondRow/UserBondRowPreTGE.js.map +1 -1
- package/dist/views/YourBondsModal/components/LinkShare/htmlToJpeg.d.ts +8 -0
- package/dist/views/YourBondsModal/components/LinkShare/htmlToJpeg.js +43 -0
- package/dist/views/YourBondsModal/components/LinkShare/htmlToJpeg.js.map +1 -0
- package/dist/views/YourBondsModal/components/LinkShare/templateImageShare.d.ts +8 -1
- package/dist/views/YourBondsModal/components/LinkShare/templateImageShare.js +172 -15
- package/dist/views/YourBondsModal/components/LinkShare/templateImageShare.js.map +1 -1
- package/dist/views/YourBondsModal/components/LinkShare/utils.js +19 -10
- package/dist/views/YourBondsModal/components/LinkShare/utils.js.map +1 -1
- package/dist/views/YourBondsModal/components/TransferBondModal/index.js +1 -2
- package/dist/views/YourBondsModal/components/TransferBondModal/index.js.map +1 -1
- package/package.json +6 -8
- package/dist/components/AccordionText/index.d.ts +0 -6
- package/dist/components/RestrictedRegionModal/index.d.ts +0 -5
- package/dist/components/TabNavigation/index.d.ts +0 -8
- package/dist/components/uikit-sdk/Input/NumericInput.d.ts +0 -9
- package/dist/components/uikit-sdk/Modal/ModalFooter.d.ts +0 -4
- package/dist/components/uikit-sdk/Svg/Icons/Audit.d.ts +0 -4
- package/dist/components/uikit-sdk/Svg/Icons/Fire.d.ts +0 -4
- package/dist/components/uikit-sdk/Svg/Icons/FullLogo.d.ts +0 -4
- package/dist/components/uikit-sdk/Svg/Icons/Instagram.d.ts +0 -4
- package/dist/components/uikit-sdk/Svg/Icons/Language.d.ts +0 -4
- package/dist/components/uikit-sdk/Svg/Icons/Medium.d.ts +0 -4
- package/dist/components/uikit-sdk/Svg/Icons/Pool.d.ts +0 -4
- package/dist/components/uikit-sdk/Svg/Icons/Reddit.d.ts +0 -4
- package/dist/components/uikit-sdk/Svg/Icons/Telegram.d.ts +0 -4
- package/dist/components/uikit-sdk/Svg/Icons/Website.d.ts +0 -4
- package/dist/components/uikit-sdk/Svg/tokens/BSC.d.ts +0 -4
- package/dist/components/uikit-sdk/Svg/tokens/CELO.d.ts +0 -4
- package/dist/components/uikit-sdk/Svg/tokens/CRONOS.d.ts +0 -4
- package/dist/components/uikit-sdk/Svg/tokens/FANTOM.d.ts +0 -4
- package/dist/components/uikit-sdk/Svg/tokens/GNOSIS.d.ts +0 -4
- package/dist/components/uikit-sdk/Svg/tokens/OKX.d.ts +0 -4
- package/dist/components/uikit-sdk/Svg/tokens/OPTIMISM.d.ts +0 -4
- package/dist/components/uikit-sdk/Svg/tokens/POLYGONZK.d.ts +0 -4
- package/dist/config/constants/tokens.js +0 -36
- package/dist/config/constants/tokens.js.map +0 -1
- package/dist/contexts/RefreshContext.d.ts +0 -10
- package/dist/hooks/useRefresh.d.ts +0 -6
- package/dist/hooks/useTimer.d.ts +0 -2
- package/dist/state/bondApiStats/useUserApiStats.d.ts +0 -22
- package/dist/state/bonds/aptosBondsConfig.d.ts +0 -4
- package/dist/state/bonds/fetchUsersBonds/getBillNftData.d.ts +0 -9
- package/dist/state/geoFencing/useGeoFencing.d.ts +0 -5
- package/dist/state/zap/useSoulZapTokenQuote.d.ts +0 -3
- package/dist/state/zap/useTierOptimizationPreview.d.ts +0 -27
- package/dist/views/ZapModal/index.d.ts +0 -13
- package/dist/views/ZapModal/styles.d.ts +0 -2
|
@@ -18,17 +18,17 @@ export interface BondIssuance {
|
|
|
18
18
|
collection: string;
|
|
19
19
|
bump: number;
|
|
20
20
|
}
|
|
21
|
-
|
|
21
|
+
interface Status {
|
|
22
22
|
active: Record<string, never>;
|
|
23
23
|
}
|
|
24
|
-
|
|
24
|
+
interface BondPricing {
|
|
25
25
|
totalDebt: string;
|
|
26
26
|
totalPayout: string;
|
|
27
27
|
lastDecay: string;
|
|
28
28
|
lastBcvUpdateTimestamp: string;
|
|
29
29
|
lastBcvUpdateInterval: string;
|
|
30
30
|
}
|
|
31
|
-
|
|
31
|
+
interface BondTerm {
|
|
32
32
|
controlVariable: string;
|
|
33
33
|
vestingEnd: string;
|
|
34
34
|
minimumDebt: string;
|
|
@@ -43,3 +43,4 @@ export interface SolanaBondData extends BondIssuance, BondPricing {
|
|
|
43
43
|
totalPayoutGiven: string;
|
|
44
44
|
trueBillPrice: string;
|
|
45
45
|
}
|
|
46
|
+
export {};
|
|
@@ -1,25 +1,13 @@
|
|
|
1
1
|
import { Aptos } from '@aptos-labs/ts-sdk';
|
|
2
|
-
import type { AptosBillInfo,
|
|
2
|
+
import type { AptosBillInfo, AptosMarketInfoTuple, AptosVestingProgressTuple } from '../types/aptosBonds';
|
|
3
3
|
export declare const getAptosClient: () => Aptos;
|
|
4
4
|
export declare const safeExtractAddress: (input: unknown) => string | undefined;
|
|
5
|
-
export declare const toAtomicUnits: (amount: string | number, decimals: number) => string;
|
|
6
|
-
export declare const buildDepositPayload: (args: AptosDepositPayload) => {
|
|
7
|
-
function: `${string}::${string}::${string}`;
|
|
8
|
-
typeArguments: string[];
|
|
9
|
-
functionArguments: (string | number)[];
|
|
10
|
-
};
|
|
11
|
-
export declare const buildClaimPayload: (args: AptosClaimPayload) => {
|
|
12
|
-
function: `${string}::${string}::${string}`;
|
|
13
|
-
typeArguments: string[];
|
|
14
|
-
functionArguments: (string | number)[];
|
|
15
|
-
};
|
|
16
5
|
interface AptosTxnWithEvents {
|
|
17
6
|
events?: Array<{
|
|
18
7
|
type: string;
|
|
19
8
|
data: Record<string, unknown>;
|
|
20
9
|
}>;
|
|
21
10
|
}
|
|
22
|
-
export declare const extractEventData: <T = Record<string, unknown>>(txn: AptosTxnWithEvents, eventSuffix: string) => T | undefined;
|
|
23
11
|
/**
|
|
24
12
|
* `bond::DepositEvent` — emitted by the deposit entry function.
|
|
25
13
|
* Contains bill_id, bill_address, deposit_amount, payout_amount, price.
|
|
@@ -42,7 +30,6 @@ export declare const extractBillMinted: (txn: AptosTxnWithEvents) => {
|
|
|
42
30
|
bill_id: string;
|
|
43
31
|
owner: string;
|
|
44
32
|
} | undefined;
|
|
45
|
-
export declare const aptosIndexerFetch: <T = unknown>(url: string, query: string, variables?: Record<string, unknown>) => Promise<T>;
|
|
46
33
|
/**
|
|
47
34
|
* `bond::market_info(market)` — returns the 27-element market info tuple.
|
|
48
35
|
*/
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { AptosConfig, Aptos } from '@aptos-labs/ts-sdk';
|
|
2
|
-
import 'bignumber.js';
|
|
3
2
|
import { APTOS_VIEW_USER_BILLS, APTOS_NETWORK, APTOS_FULLNODE_URL, APTOS_VIEW_BOND_MARKET_BY_ID, APTOS_VIEW_NFT_ADDRESS, APTOS_VIEW_BILL_INFO, APTOS_VIEW_VESTING_PROGRESS, getRandomAptosApiKey, APTOS_VIEW_MARKET_INFO } from '../constants/aptosConstants.js';
|
|
4
3
|
|
|
5
4
|
// ---------------------------------------------------------------------------
|
|
@@ -97,6 +96,35 @@ const extractBillMinted = (txn) => {
|
|
|
97
96
|
return { bill_id: deposit.bill_id, owner: deposit.depositor };
|
|
98
97
|
};
|
|
99
98
|
// ---------------------------------------------------------------------------
|
|
99
|
+
// Fetch helper — GraphQL to the Aptos indexer
|
|
100
|
+
// ---------------------------------------------------------------------------
|
|
101
|
+
// Uses the same API key that is configured on the Aptos client. Everything
|
|
102
|
+
// else on the HTTP layer goes through the Aptos ts-sdk, but the indexer
|
|
103
|
+
// needs a raw `fetch` call because GraphQL is not part of the SDK surface.
|
|
104
|
+
// export const aptosIndexerFetch = async <T = unknown>(
|
|
105
|
+
// url: string,
|
|
106
|
+
// query: string,
|
|
107
|
+
// variables?: Record<string, unknown>,
|
|
108
|
+
// ): Promise<T> => {
|
|
109
|
+
// const apiKey = getRandomAptosApiKey()
|
|
110
|
+
// const response = await fetch(url, {
|
|
111
|
+
// method: 'POST',
|
|
112
|
+
// headers: {
|
|
113
|
+
// 'Content-Type': 'application/json',
|
|
114
|
+
// ...(apiKey && { Authorization: `Bearer ${apiKey}` }),
|
|
115
|
+
// },
|
|
116
|
+
// body: JSON.stringify({ query, variables }),
|
|
117
|
+
// })
|
|
118
|
+
// if (!response.ok) {
|
|
119
|
+
// throw new Error(`Aptos indexer request failed: ${response.status}`)
|
|
120
|
+
// }
|
|
121
|
+
// const json = (await response.json()) as { data: T; errors?: Array<{ message: string }> }
|
|
122
|
+
// if (json.errors?.length) {
|
|
123
|
+
// throw new Error(`Aptos indexer returned errors: ${json.errors.map((e) => e.message).join(', ')}`)
|
|
124
|
+
// }
|
|
125
|
+
// return json.data
|
|
126
|
+
// }
|
|
127
|
+
// ---------------------------------------------------------------------------
|
|
100
128
|
// View function readers (PLAN_001 Etapa 5b — real read skeleton)
|
|
101
129
|
// ---------------------------------------------------------------------------
|
|
102
130
|
// Thin wrappers around `aptos.view(...)` for the specific view functions the
|
|
@@ -198,5 +226,5 @@ const readNftAddressByBillId = async (billId) => {
|
|
|
198
226
|
return String(result[0] ?? '');
|
|
199
227
|
};
|
|
200
228
|
|
|
201
|
-
export { extractBillMinted, extractDepositEvent,
|
|
229
|
+
export { extractBillMinted, extractDepositEvent, getAptosClient, readAptosBillInfo, readAptosMarketInfo, readBondMarketByBillId, readNftAddressByBillId, readUserBillIds, readVestingProgress, safeExtractAddress };
|
|
202
230
|
//# sourceMappingURL=aptosHelpers.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aptosHelpers.js","sources":["../../src/utils/aptosHelpers.ts"],"sourcesContent":["import { Aptos, AptosConfig } from '@aptos-labs/ts-sdk'\nimport BigNumber from 'bignumber.js'\nimport {\n APTOS_CLAIM_FUNCTION,\n APTOS_DEPOSIT_FUNCTION,\n APTOS_FULLNODE_URL,\n APTOS_NETWORK,\n APTOS_VIEW_BILL_INFO,\n APTOS_VIEW_BOND_MARKET_BY_ID,\n APTOS_VIEW_MARKET_INFO,\n APTOS_VIEW_NFT_ADDRESS,\n APTOS_VIEW_USER_BILLS,\n APTOS_VIEW_VESTING_PROGRESS,\n getRandomAptosApiKey,\n} from '../constants/aptosConstants'\nimport type {\n AptosBillInfo,\n AptosClaimPayload,\n AptosDepositPayload,\n AptosMarketInfoTuple,\n AptosVestingProgressTuple,\n} from '../types/aptosBonds'\n\n// ---------------------------------------------------------------------------\n// Aptos client — lazy singleton\n// ---------------------------------------------------------------------------\n// We keep one client per (network, api key) pair. The API key is picked with\n// `getRandomAptosApiKey()` on first call, so different sessions hit a\n// different key (very simple load balancing). If the pool is empty we fall\n// back to unauthenticated requests.\nlet _aptosClient: Aptos | undefined\n\nexport const getAptosClient = (): Aptos => {\n if (_aptosClient) return _aptosClient\n const apiKey = getRandomAptosApiKey()\n // The Aptos ts-sdk exposes `API_KEY` directly on `clientConfig`; it adds\n // the `Authorization: Bearer <key>` header internally. This is the\n // idiomatic way to authenticate — no manual header wiring needed.\n const config = new AptosConfig({\n network: APTOS_NETWORK,\n ...(apiKey && { clientConfig: { API_KEY: apiKey } }),\n })\n _aptosClient = new Aptos(config)\n return _aptosClient\n}\n\n// ---------------------------------------------------------------------------\n// Address normalisation\n// ---------------------------------------------------------------------------\n// Aptos wallet adapters can surface account addresses in several shapes:\n// plain string, `{ data: Uint8Array }`, `Uint8Array`, or an `AccountAddress`\n// instance. This helper returns a canonical `0x`-prefixed hex string, or\n// `undefined` if the input cannot be decoded. We keep the interface loose so\n// callers can pass whatever the SDK hands them.\nexport const safeExtractAddress = (input: unknown): string | undefined => {\n if (input == null) return undefined\n\n // Already a string\n if (typeof input === 'string') {\n return input.startsWith('0x') ? input : `0x${input}`\n }\n\n // AccountAddress instance (has `toString()` that returns `0x...`)\n if (typeof input === 'object' && typeof (input as { toString?: () => string }).toString === 'function') {\n const asObject = input as { data?: Uint8Array | number[]; toString: () => string }\n // Prefer `.data` if it looks like a byte array — `.toString()` on\n // AccountAddress already returns the canonical hex, but some wallets\n // return `{ data: Uint8Array }` without the method.\n if (asObject.data instanceof Uint8Array) {\n return bytesToHex(asObject.data)\n }\n if (Array.isArray(asObject.data)) {\n return bytesToHex(new Uint8Array(asObject.data))\n }\n const stringified = asObject.toString()\n if (stringified.startsWith('0x')) return stringified\n }\n\n // Raw Uint8Array\n if (input instanceof Uint8Array) {\n return bytesToHex(input)\n }\n\n // Raw number[]\n if (Array.isArray(input)) {\n return bytesToHex(new Uint8Array(input))\n }\n\n return undefined\n}\n\nconst bytesToHex = (bytes: Uint8Array): string => {\n let out = '0x'\n for (let i = 0; i < bytes.length; i++) {\n out += bytes[i].toString(16).padStart(2, '0')\n }\n return out\n}\n\n// ---------------------------------------------------------------------------\n// Unit conversion\n// ---------------------------------------------------------------------------\n// User inputs live in \"whole tokens\" (e.g. \"1.5 USDC\"). The Aptos ts-sdk\n// serialises numeric function arguments from strings, so we convert to\n// atomic units and return a stringified BigInt.\nexport const toAtomicUnits = (amount: string | number, decimals: number): string => {\n if (amount === '' || amount == null) return '0'\n const bn = new BigNumber(amount).times(new BigNumber(10).pow(decimals))\n // Floor so we never over-spend what the user typed.\n return bn.integerValue(BigNumber.ROUND_FLOOR).toFixed(0)\n}\n\n// ---------------------------------------------------------------------------\n// Payload builders\n// ---------------------------------------------------------------------------\n// These return the `InputEntryFunctionData` shape consumed by\n// `wallet.signAndSubmitTransaction({ sender, data: ... })`. Keeping them in\n// one place means the buy/claim components do not have to repeat the\n// function-name and argument order.\n\nexport const buildDepositPayload = (args: AptosDepositPayload) => ({\n function: APTOS_DEPOSIT_FUNCTION,\n typeArguments: [] as string[],\n functionArguments: [args.market, args.amount, args.max_price, args.depositor] as (string | number)[],\n})\n\nexport const buildClaimPayload = (args: AptosClaimPayload) => ({\n function: APTOS_CLAIM_FUNCTION,\n typeArguments: [] as string[],\n // `apebond::bond::claim(market, bill_id: u64)` — the contract takes the\n // scalar bill_id, NOT the object address.\n functionArguments: [args.market, args.bill_id] as (string | number)[],\n})\n\n// ---------------------------------------------------------------------------\n// Event extractors\n// ---------------------------------------------------------------------------\n// Parse events out of a `waitForTransaction` response. The event `type`\n// format is `${module}::${EventStruct}`. We match by `.endsWith('::Foo')` so\n// we do not have to hard-code the full module path (which contains the\n// contract address).\n\ninterface AptosTxnWithEvents {\n events?: Array<{ type: string; data: Record<string, unknown> }>\n}\n\nexport const extractEventData = <T = Record<string, unknown>>(\n txn: AptosTxnWithEvents,\n eventSuffix: string,\n): T | undefined => {\n const event = txn?.events?.find((e) => e.type.includes(eventSuffix))\n return event?.data as T | undefined\n}\n\n/**\n * `bond::DepositEvent` — emitted by the deposit entry function.\n * Contains bill_id, bill_address, deposit_amount, payout_amount, price.\n */\nexport const extractDepositEvent = (\n txn: AptosTxnWithEvents,\n):\n | {\n bill_id: string\n bill_address: string\n market: string\n deposit_amount: string\n payout_amount: string\n price: string\n depositor: string\n recipient: string\n }\n | undefined => extractEventData(txn, '::DepositEvent')\n\n/**\n * Extract bill_id from transaction events. Checks both `BillMinted` (from bond_nft)\n * and `DepositEvent` (from bond) since the contract emits both.\n */\nexport const extractBillMinted = (txn: AptosTxnWithEvents): { bill_id: string; owner: string } | undefined => {\n // Try BillMinted event first (emitted by bond_nft module)\n const billMinted = extractEventData<{ bill_id: string; owner: string }>(txn, '::BillMinted')\n if (billMinted) return billMinted\n // Fall back to DepositEvent (emitted by bond module)\n const deposit = extractDepositEvent(txn)\n if (!deposit) return undefined\n return { bill_id: deposit.bill_id, owner: deposit.depositor }\n}\n\n// ---------------------------------------------------------------------------\n// Fetch helper — GraphQL to the Aptos indexer\n// ---------------------------------------------------------------------------\n// Uses the same API key that is configured on the Aptos client. Everything\n// else on the HTTP layer goes through the Aptos ts-sdk, but the indexer\n// needs a raw `fetch` call because GraphQL is not part of the SDK surface.\nexport const aptosIndexerFetch = async <T = unknown>(\n url: string,\n query: string,\n variables?: Record<string, unknown>,\n): Promise<T> => {\n const apiKey = getRandomAptosApiKey()\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(apiKey && { Authorization: `Bearer ${apiKey}` }),\n },\n body: JSON.stringify({ query, variables }),\n })\n if (!response.ok) {\n throw new Error(`Aptos indexer request failed: ${response.status}`)\n }\n const json = (await response.json()) as { data: T; errors?: Array<{ message: string }> }\n if (json.errors?.length) {\n throw new Error(`Aptos indexer returned errors: ${json.errors.map((e) => e.message).join(', ')}`)\n }\n return json.data\n}\n\n// ---------------------------------------------------------------------------\n// View function readers (PLAN_001 Etapa 5b — real read skeleton)\n// ---------------------------------------------------------------------------\n// Thin wrappers around `aptos.view(...)` for the specific view functions the\n// SDK needs. Every reader throws on RPC / contract error — callers should\n// wrap in try/catch so a missing deployment degrades gracefully rather than\n// crashing the UI.\n//\n// Shapes are verified against apebond-move-playground pages. See the matching\n// `AptosMarketInfoTuple` / `AptosBillInfo` / `AptosVestingProgressTuple`\n// types for documentation on each field.\n\n/**\n * `bond::market_info(market)` — returns the 27-element market info tuple.\n */\nexport const readAptosMarketInfo = async (marketAddress: string): Promise<AptosMarketInfoTuple> => {\n const aptos = getAptosClient()\n const result = await aptos.view({\n payload: {\n function: APTOS_VIEW_MARKET_INFO,\n functionArguments: [marketAddress],\n },\n })\n return result as unknown as AptosMarketInfoTuple\n}\n\n/**\n * `bond::bill_info(market, bill_id)` — returns the Bill struct for a\n * specific bill. The contract takes `bill_id: u64` (NOT the object address).\n * Uses REST directly to avoid SDK remoteAbi serialisation bug with u64 args.\n */\nexport const readAptosBillInfo = async (marketAddress: string, billId: string): Promise<AptosBillInfo> => {\n const result = await viewViaRest(APTOS_VIEW_BILL_INFO, [marketAddress, billId])\n return result[0] as unknown as AptosBillInfo\n}\n\n/**\n * `bond_nft::user_bills(user)` — returns all bill_ids owned by the user\n * across every deployed market. The view returns `[bill_ids]` (the inner\n * array is at index 0), so we unwrap it here.\n */\nexport const readUserBillIds = async (user: string): Promise<string[]> => {\n const aptos = getAptosClient()\n const result = await aptos.view({\n payload: {\n function: APTOS_VIEW_USER_BILLS,\n functionArguments: [user],\n },\n })\n const ids = (result[0] ?? []) as unknown as Array<string | number>\n return ids.map((id) => String(id))\n}\n\n/**\n * `bond::vesting_progress(market, bill_id)` — returns `[vested_amount, claimable_amount]`.\n * Note: this is in `bond` module (not `bond_nft`), and takes the market as first argument.\n * Uses REST directly to avoid SDK remoteAbi serialisation bug with u64 args.\n */\nexport const readVestingProgress = async (\n marketAddress: string,\n billId: string,\n): Promise<AptosVestingProgressTuple> => {\n const result = await viewViaRest(APTOS_VIEW_VESTING_PROGRESS, [marketAddress, billId])\n return [String(result[0] ?? '0'), String(result[1] ?? '0')] as const\n}\n\n// ---------------------------------------------------------------------------\n// REST-based view call — bypasses the SDK's remoteAbi serialisation which\n// has a bug in v6.x where u64 arguments to functions returning `address` get\n// mis-serialised. The REST endpoint handles string arguments natively.\n// ---------------------------------------------------------------------------\nconst viewViaRest = async (fn: string, args: string[], typeArgs: string[] = []): Promise<unknown[]> => {\n const apiKey = getRandomAptosApiKey()\n const res = await fetch(`${APTOS_FULLNODE_URL}/view`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(apiKey && { Authorization: `Bearer ${apiKey}` }),\n },\n body: JSON.stringify({\n function: fn,\n type_arguments: typeArgs,\n arguments: args,\n }),\n })\n if (!res.ok) {\n const text = await res.text()\n throw new Error(`View call ${fn} failed: ${res.status} ${text}`)\n }\n return (await res.json()) as unknown[]\n}\n\n/**\n * `bond_nft::bond_market_by_id(bill_id)` — which market owns this bill.\n * Uses REST directly — SDK's aptos.view() mis-serialises u64→address functions.\n */\nexport const readBondMarketByBillId = async (billId: string): Promise<string> => {\n const result = await viewViaRest(APTOS_VIEW_BOND_MARKET_BY_ID, [billId])\n return String(result[0] ?? '')\n}\n\n/**\n * `bond_nft::nft_address(bill_id)` — resolve the scalar bill_id to the\n * on-chain NFT object address (aka `bill_addr`). Needed to then call\n * `bond::bill_info(market, bill_addr)` or `bond::claim(market, bill_addr)`.\n * Uses REST directly — SDK's aptos.view() mis-serialises u64→address functions.\n */\nexport const readNftAddressByBillId = async (billId: string): Promise<string> => {\n const result = await viewViaRest(APTOS_VIEW_NFT_ADDRESS, [billId])\n return String(result[0] ?? '')\n}\n"],"names":[],"mappings":";;;;AAuBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,YAA+B;AAE5B,MAAM,cAAc,GAAG,MAAY;AACxC,IAAA,IAAI,YAAY;AAAE,QAAA,OAAO,YAAY;AACrC,IAAA,MAAM,MAAM,GAAG,oBAAoB,EAAE;;;;AAIrC,IAAA,MAAM,MAAM,GAAG,IAAI,WAAW,CAAC;AAC7B,QAAA,OAAO,EAAE,aAAa;AACtB,QAAA,IAAI,MAAM,IAAI,EAAE,YAAY,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE,CAAC;AACrD,KAAA,CAAC;AACF,IAAA,YAAY,GAAG,IAAI,KAAK,CAAC,MAAM,CAAC;AAChC,IAAA,OAAO,YAAY;AACrB;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,kBA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,QAAA,OAAO,EAAE;AACP,YAAA,cAAc,EAAE,kBAAkB;YAClC,IAAI,MAAM,IAAI,EAAE,aAAa,EAAE,CAAA,OAAA,EAAU,MAAM,CAAA,CAAE,EAAE,CAAC;AACrD,SAAA;AACD,QAAA,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC;AACnB,YAAA,QAAQ,EAAE,EAAE;AACZ,YAAA,cAAc,EAAE,QAAQ;AACxB,YAAA,SAAS,EAAE,IAAI;SAChB,CAAC;AACH,KAAA,CAAC;AACF,IAAA,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE;AACX,QAAA,MAAM,IAAI,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE;AAC7B,QAAA,MAAM,IAAI,KAAK,CAAC,CAAA,UAAA,EAAa,EAAE,CAAA,SAAA,EAAY,GAAG,CAAC,MAAM,CAAA,CAAA,EAAI,IAAI,CAAA,CAAE,CAAC;IAClE;AACA,IAAA,QAAQ,MAAM,GAAG,CAAC,IAAI,EAAE;AAC1B,CAAC;AAED;;;AAGG;MACU,sBAAsB,GAAG,OAAO,MAAc,KAAqB;IAC9E,MAAM,MAAM,GAAG,MAAM,WAAW,CAAC,4BAA4B,EAAE,CAAC,MAAM,CAAC,CAAC;IACxE,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;AAChC;AAEA;;;;;AAKG;MACU,sBAAsB,GAAG,OAAO,MAAc,KAAqB;IAC9E,MAAM,MAAM,GAAG,MAAM,WAAW,CAAC,sBAAsB,EAAE,CAAC,MAAM,CAAC,CAAC;IAClE,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;AAChC;;;;"}
|
|
1
|
+
{"version":3,"file":"aptosHelpers.js","sources":["../../src/utils/aptosHelpers.ts"],"sourcesContent":["import { Aptos, AptosConfig } from '@aptos-labs/ts-sdk'\nimport {\n APTOS_FULLNODE_URL,\n APTOS_NETWORK,\n APTOS_VIEW_BILL_INFO,\n APTOS_VIEW_BOND_MARKET_BY_ID,\n APTOS_VIEW_MARKET_INFO,\n APTOS_VIEW_NFT_ADDRESS,\n APTOS_VIEW_USER_BILLS,\n APTOS_VIEW_VESTING_PROGRESS,\n getRandomAptosApiKey,\n} from '../constants/aptosConstants'\nimport type { AptosBillInfo, AptosMarketInfoTuple, AptosVestingProgressTuple } from '../types/aptosBonds'\n\n// ---------------------------------------------------------------------------\n// Aptos client — lazy singleton\n// ---------------------------------------------------------------------------\n// We keep one client per (network, api key) pair. The API key is picked with\n// `getRandomAptosApiKey()` on first call, so different sessions hit a\n// different key (very simple load balancing). If the pool is empty we fall\n// back to unauthenticated requests.\nlet _aptosClient: Aptos | undefined\n\nexport const getAptosClient = (): Aptos => {\n if (_aptosClient) return _aptosClient\n const apiKey = getRandomAptosApiKey()\n // The Aptos ts-sdk exposes `API_KEY` directly on `clientConfig`; it adds\n // the `Authorization: Bearer <key>` header internally. This is the\n // idiomatic way to authenticate — no manual header wiring needed.\n const config = new AptosConfig({\n network: APTOS_NETWORK,\n ...(apiKey && { clientConfig: { API_KEY: apiKey } }),\n })\n _aptosClient = new Aptos(config)\n return _aptosClient\n}\n\n// ---------------------------------------------------------------------------\n// Address normalisation\n// ---------------------------------------------------------------------------\n// Aptos wallet adapters can surface account addresses in several shapes:\n// plain string, `{ data: Uint8Array }`, `Uint8Array`, or an `AccountAddress`\n// instance. This helper returns a canonical `0x`-prefixed hex string, or\n// `undefined` if the input cannot be decoded. We keep the interface loose so\n// callers can pass whatever the SDK hands them.\nexport const safeExtractAddress = (input: unknown): string | undefined => {\n if (input == null) return undefined\n\n // Already a string\n if (typeof input === 'string') {\n return input.startsWith('0x') ? input : `0x${input}`\n }\n\n // AccountAddress instance (has `toString()` that returns `0x...`)\n if (typeof input === 'object' && typeof (input as { toString?: () => string }).toString === 'function') {\n const asObject = input as { data?: Uint8Array | number[]; toString: () => string }\n // Prefer `.data` if it looks like a byte array — `.toString()` on\n // AccountAddress already returns the canonical hex, but some wallets\n // return `{ data: Uint8Array }` without the method.\n if (asObject.data instanceof Uint8Array) {\n return bytesToHex(asObject.data)\n }\n if (Array.isArray(asObject.data)) {\n return bytesToHex(new Uint8Array(asObject.data))\n }\n const stringified = asObject.toString()\n if (stringified.startsWith('0x')) return stringified\n }\n\n // Raw Uint8Array\n if (input instanceof Uint8Array) {\n return bytesToHex(input)\n }\n\n // Raw number[]\n if (Array.isArray(input)) {\n return bytesToHex(new Uint8Array(input))\n }\n\n return undefined\n}\n\nconst bytesToHex = (bytes: Uint8Array): string => {\n let out = '0x'\n for (let i = 0; i < bytes.length; i++) {\n out += bytes[i].toString(16).padStart(2, '0')\n }\n return out\n}\n\n// ---------------------------------------------------------------------------\n// Unit conversion\n// ---------------------------------------------------------------------------\n// User inputs live in \"whole tokens\" (e.g. \"1.5 USDC\"). The Aptos ts-sdk\n// serialises numeric function arguments from strings, so we convert to\n// atomic units and return a stringified BigInt.\n// export const toAtomicUnits = (amount: string | number, decimals: number): string => {\n// if (amount === '' || amount == null) return '0'\n// const bn = new BigNumber(amount).times(new BigNumber(10).pow(decimals))\n// // Floor so we never over-spend what the user typed.\n// return bn.integerValue(BigNumber.ROUND_FLOOR).toFixed(0)\n// }\n\n// ---------------------------------------------------------------------------\n// Payload builders\n// ---------------------------------------------------------------------------\n// These return the `InputEntryFunctionData` shape consumed by\n// `wallet.signAndSubmitTransaction({ sender, data: ... })`. Keeping them in\n// one place means the buy/claim components do not have to repeat the\n// function-name and argument order.\n\n// export const buildDepositPayload = (args: AptosDepositPayload) => ({\n// function: APTOS_DEPOSIT_FUNCTION,\n// typeArguments: [] as string[],\n// functionArguments: [args.market, args.amount, args.max_price, args.depositor] as (string | number)[],\n// })\n//\n// export const buildClaimPayload = (args: AptosClaimPayload) => ({\n// function: APTOS_CLAIM_FUNCTION,\n// typeArguments: [] as string[],\n// // `apebond::bond::claim(market, bill_id: u64)` — the contract takes the\n// // scalar bill_id, NOT the object address.\n// functionArguments: [args.market, args.bill_id] as (string | number)[],\n// })\n\n// ---------------------------------------------------------------------------\n// Event extractors\n// ---------------------------------------------------------------------------\n// Parse events out of a `waitForTransaction` response. The event `type`\n// format is `${module}::${EventStruct}`. We match by `.endsWith('::Foo')` so\n// we do not have to hard-code the full module path (which contains the\n// contract address).\n\ninterface AptosTxnWithEvents {\n events?: Array<{ type: string; data: Record<string, unknown> }>\n}\n\nconst extractEventData = <T = Record<string, unknown>>(txn: AptosTxnWithEvents, eventSuffix: string): T | undefined => {\n const event = txn?.events?.find((e) => e.type.includes(eventSuffix))\n return event?.data as T | undefined\n}\n\n/**\n * `bond::DepositEvent` — emitted by the deposit entry function.\n * Contains bill_id, bill_address, deposit_amount, payout_amount, price.\n */\nexport const extractDepositEvent = (\n txn: AptosTxnWithEvents,\n):\n | {\n bill_id: string\n bill_address: string\n market: string\n deposit_amount: string\n payout_amount: string\n price: string\n depositor: string\n recipient: string\n }\n | undefined => extractEventData(txn, '::DepositEvent')\n\n/**\n * Extract bill_id from transaction events. Checks both `BillMinted` (from bond_nft)\n * and `DepositEvent` (from bond) since the contract emits both.\n */\nexport const extractBillMinted = (txn: AptosTxnWithEvents): { bill_id: string; owner: string } | undefined => {\n // Try BillMinted event first (emitted by bond_nft module)\n const billMinted = extractEventData<{ bill_id: string; owner: string }>(txn, '::BillMinted')\n if (billMinted) return billMinted\n // Fall back to DepositEvent (emitted by bond module)\n const deposit = extractDepositEvent(txn)\n if (!deposit) return undefined\n return { bill_id: deposit.bill_id, owner: deposit.depositor }\n}\n\n// ---------------------------------------------------------------------------\n// Fetch helper — GraphQL to the Aptos indexer\n// ---------------------------------------------------------------------------\n// Uses the same API key that is configured on the Aptos client. Everything\n// else on the HTTP layer goes through the Aptos ts-sdk, but the indexer\n// needs a raw `fetch` call because GraphQL is not part of the SDK surface.\n// export const aptosIndexerFetch = async <T = unknown>(\n// url: string,\n// query: string,\n// variables?: Record<string, unknown>,\n// ): Promise<T> => {\n// const apiKey = getRandomAptosApiKey()\n// const response = await fetch(url, {\n// method: 'POST',\n// headers: {\n// 'Content-Type': 'application/json',\n// ...(apiKey && { Authorization: `Bearer ${apiKey}` }),\n// },\n// body: JSON.stringify({ query, variables }),\n// })\n// if (!response.ok) {\n// throw new Error(`Aptos indexer request failed: ${response.status}`)\n// }\n// const json = (await response.json()) as { data: T; errors?: Array<{ message: string }> }\n// if (json.errors?.length) {\n// throw new Error(`Aptos indexer returned errors: ${json.errors.map((e) => e.message).join(', ')}`)\n// }\n// return json.data\n// }\n\n// ---------------------------------------------------------------------------\n// View function readers (PLAN_001 Etapa 5b — real read skeleton)\n// ---------------------------------------------------------------------------\n// Thin wrappers around `aptos.view(...)` for the specific view functions the\n// SDK needs. Every reader throws on RPC / contract error — callers should\n// wrap in try/catch so a missing deployment degrades gracefully rather than\n// crashing the UI.\n//\n// Shapes are verified against apebond-move-playground pages. See the matching\n// `AptosMarketInfoTuple` / `AptosBillInfo` / `AptosVestingProgressTuple`\n// types for documentation on each field.\n\n/**\n * `bond::market_info(market)` — returns the 27-element market info tuple.\n */\nexport const readAptosMarketInfo = async (marketAddress: string): Promise<AptosMarketInfoTuple> => {\n const aptos = getAptosClient()\n const result = await aptos.view({\n payload: {\n function: APTOS_VIEW_MARKET_INFO,\n functionArguments: [marketAddress],\n },\n })\n return result as unknown as AptosMarketInfoTuple\n}\n\n/**\n * `bond::bill_info(market, bill_id)` — returns the Bill struct for a\n * specific bill. The contract takes `bill_id: u64` (NOT the object address).\n * Uses REST directly to avoid SDK remoteAbi serialisation bug with u64 args.\n */\nexport const readAptosBillInfo = async (marketAddress: string, billId: string): Promise<AptosBillInfo> => {\n const result = await viewViaRest(APTOS_VIEW_BILL_INFO, [marketAddress, billId])\n return result[0] as unknown as AptosBillInfo\n}\n\n/**\n * `bond_nft::user_bills(user)` — returns all bill_ids owned by the user\n * across every deployed market. The view returns `[bill_ids]` (the inner\n * array is at index 0), so we unwrap it here.\n */\nexport const readUserBillIds = async (user: string): Promise<string[]> => {\n const aptos = getAptosClient()\n const result = await aptos.view({\n payload: {\n function: APTOS_VIEW_USER_BILLS,\n functionArguments: [user],\n },\n })\n const ids = (result[0] ?? []) as unknown as Array<string | number>\n return ids.map((id) => String(id))\n}\n\n/**\n * `bond::vesting_progress(market, bill_id)` — returns `[vested_amount, claimable_amount]`.\n * Note: this is in `bond` module (not `bond_nft`), and takes the market as first argument.\n * Uses REST directly to avoid SDK remoteAbi serialisation bug with u64 args.\n */\nexport const readVestingProgress = async (\n marketAddress: string,\n billId: string,\n): Promise<AptosVestingProgressTuple> => {\n const result = await viewViaRest(APTOS_VIEW_VESTING_PROGRESS, [marketAddress, billId])\n return [String(result[0] ?? '0'), String(result[1] ?? '0')] as const\n}\n\n// ---------------------------------------------------------------------------\n// REST-based view call — bypasses the SDK's remoteAbi serialisation which\n// has a bug in v6.x where u64 arguments to functions returning `address` get\n// mis-serialised. The REST endpoint handles string arguments natively.\n// ---------------------------------------------------------------------------\nconst viewViaRest = async (fn: string, args: string[], typeArgs: string[] = []): Promise<unknown[]> => {\n const apiKey = getRandomAptosApiKey()\n const res = await fetch(`${APTOS_FULLNODE_URL}/view`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(apiKey && { Authorization: `Bearer ${apiKey}` }),\n },\n body: JSON.stringify({\n function: fn,\n type_arguments: typeArgs,\n arguments: args,\n }),\n })\n if (!res.ok) {\n const text = await res.text()\n throw new Error(`View call ${fn} failed: ${res.status} ${text}`)\n }\n return (await res.json()) as unknown[]\n}\n\n/**\n * `bond_nft::bond_market_by_id(bill_id)` — which market owns this bill.\n * Uses REST directly — SDK's aptos.view() mis-serialises u64→address functions.\n */\nexport const readBondMarketByBillId = async (billId: string): Promise<string> => {\n const result = await viewViaRest(APTOS_VIEW_BOND_MARKET_BY_ID, [billId])\n return String(result[0] ?? '')\n}\n\n/**\n * `bond_nft::nft_address(bill_id)` — resolve the scalar bill_id to the\n * on-chain NFT object address (aka `bill_addr`). Needed to then call\n * `bond::bill_info(market, bill_addr)` or `bond::claim(market, bill_addr)`.\n * Uses REST directly — SDK's aptos.view() mis-serialises u64→address functions.\n */\nexport const readNftAddressByBillId = async (billId: string): Promise<string> => {\n const result = await viewViaRest(APTOS_VIEW_NFT_ADDRESS, [billId])\n return String(result[0] ?? '')\n}\n"],"names":[],"mappings":";;;AAcA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,YAA+B;AAE5B,MAAM,cAAc,GAAG,MAAY;AACxC,IAAA,IAAI,YAAY;AAAE,QAAA,OAAO,YAAY;AACrC,IAAA,MAAM,MAAM,GAAG,oBAAoB,EAAE;;;;AAIrC,IAAA,MAAM,MAAM,GAAG,IAAI,WAAW,CAAC;AAC7B,QAAA,OAAO,EAAE,aAAa;AACtB,QAAA,IAAI,MAAM,IAAI,EAAE,YAAY,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE,CAAC;AACrD,KAAA,CAAC;AACF,IAAA,YAAY,GAAG,IAAI,KAAK,CAAC,MAAM,CAAC;AAChC,IAAA,OAAO,YAAY;AACrB;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,kBAAkB,GAAG,CAAC,KAAc,KAAwB;IACvE,IAAI,KAAK,IAAI,IAAI;AAAE,QAAA,OAAO,SAAS;;AAGnC,IAAA,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;AAC7B,QAAA,OAAO,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,KAAK,GAAG,CAAA,EAAA,EAAK,KAAK,EAAE;IACtD;;AAGA,IAAA,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,OAAQ,KAAqC,CAAC,QAAQ,KAAK,UAAU,EAAE;QACtG,MAAM,QAAQ,GAAG,KAAiE;;;;AAIlF,QAAA,IAAI,QAAQ,CAAC,IAAI,YAAY,UAAU,EAAE;AACvC,YAAA,OAAO,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC;QAClC;QACA,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,IA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AG,MAAM,GAAG,CAAC,IAAI,EAAE;AAC7B,QAAA,MAAM,IAAI,KAAK,CAAC,CAAA,UAAA,EAAa,EAAE,CAAA,SAAA,EAAY,GAAG,CAAC,MAAM,CAAA,CAAA,EAAI,IAAI,CAAA,CAAE,CAAC;IAClE;AACA,IAAA,QAAQ,MAAM,GAAG,CAAC,IAAI,EAAE;AAC1B,CAAC;AAED;;;AAGG;MACU,sBAAsB,GAAG,OAAO,MAAc,KAAqB;IAC9E,MAAM,MAAM,GAAG,MAAM,WAAW,CAAC,4BAA4B,EAAE,CAAC,MAAM,CAAC,CAAC;IACxE,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;AAChC;AAEA;;;;;AAKG;MACU,sBAAsB,GAAG,OAAO,MAAc,KAAqB;IAC9E,MAAM,MAAM,GAAG,MAAM,WAAW,CAAC,sBAAsB,EAAE,CAAC,MAAM,CAAC,CAAC;IAClE,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;AAChC;;;;"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { BondsData, TrueBondPrices } from '../types/bonds';
|
|
2
2
|
/**
|
|
3
3
|
* Finds the highest TrueBondPrices element where userPoints is higher than points in the array.
|
|
4
|
-
* @param userPoints - The user's points as a string representing
|
|
4
|
+
* @param userPoints - The user's points as a string representing an integer.
|
|
5
5
|
* @param trueBondPrices - Array of TrueBondPrices to analyze.
|
|
6
6
|
* @returns The highest TrueBondPrices element where userPoints is higher than the item's points, or `undefined` if none matches.
|
|
7
7
|
*/
|
|
@@ -1,25 +1,19 @@
|
|
|
1
|
-
import BigNumber from 'bignumber.js';
|
|
2
|
-
|
|
3
1
|
/**
|
|
4
2
|
* Finds the highest TrueBondPrices element where userPoints is higher than points in the array.
|
|
5
|
-
* @param userPoints - The user's points as a string representing
|
|
3
|
+
* @param userPoints - The user's points as a string representing an integer.
|
|
6
4
|
* @param trueBondPrices - Array of TrueBondPrices to analyze.
|
|
7
5
|
* @returns The highest TrueBondPrices element where userPoints is higher than the item's points, or `undefined` if none matches.
|
|
8
6
|
*/
|
|
9
7
|
const findHighestTrueBondPrice = (userPoints, trueBondPrices) => {
|
|
10
8
|
if (!userPoints || !trueBondPrices)
|
|
11
9
|
return undefined;
|
|
12
|
-
const
|
|
10
|
+
const userPointsBigInt = BigInt(userPoints);
|
|
13
11
|
// Filter higher discounts that the user can't access
|
|
14
|
-
const eligiblePrices = trueBondPrices.filter((price) =>
|
|
12
|
+
const eligiblePrices = trueBondPrices.filter((price) => userPointsBigInt >= BigInt(price.points));
|
|
15
13
|
if (!eligiblePrices || eligiblePrices.length === 0)
|
|
16
14
|
return undefined;
|
|
17
15
|
// Find the highest points among the eligible prices
|
|
18
|
-
return eligiblePrices.reduce((highest, current) =>
|
|
19
|
-
const highestPoints = new BigNumber(highest.points);
|
|
20
|
-
const currentPoints = new BigNumber(current.points);
|
|
21
|
-
return currentPoints.isGreaterThan(highestPoints) ? current : highest;
|
|
22
|
-
});
|
|
16
|
+
return eligiblePrices.reduce((highest, current) => (BigInt(current.points) > BigInt(highest.points) ? current : highest));
|
|
23
17
|
};
|
|
24
18
|
/**
|
|
25
19
|
* Finds the TrueBondPrices element with the highest points in the array, regardless of user points.
|
|
@@ -29,7 +23,7 @@ const findHighestTrueBondPrice = (userPoints, trueBondPrices) => {
|
|
|
29
23
|
const findHighestTrueBondPriceUserAgnostic = (bondData) => {
|
|
30
24
|
if (!bondData?.trueBondPrices?.length)
|
|
31
25
|
return undefined;
|
|
32
|
-
return bondData.trueBondPrices.reduce((highest, current) =>
|
|
26
|
+
return bondData.trueBondPrices.reduce((highest, current) => BigInt(current.points) > BigInt(highest.points) ? current : highest);
|
|
33
27
|
};
|
|
34
28
|
|
|
35
29
|
export { findHighestTrueBondPrice, findHighestTrueBondPriceUserAgnostic };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bondPriceHelpers.js","sources":["../../src/utils/bondPriceHelpers.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"bondPriceHelpers.js","sources":["../../src/utils/bondPriceHelpers.ts"],"sourcesContent":["import { BondsData, TrueBondPrices } from '../types/bonds'\n\n/**\n * Finds the highest TrueBondPrices element where userPoints is higher than points in the array.\n * @param userPoints - The user's points as a string representing an integer.\n * @param trueBondPrices - Array of TrueBondPrices to analyze.\n * @returns The highest TrueBondPrices element where userPoints is higher than the item's points, or `undefined` if none matches.\n */\nexport const findHighestTrueBondPrice = (\n userPoints?: string | null,\n trueBondPrices?: TrueBondPrices[],\n): TrueBondPrices | undefined => {\n if (!userPoints || !trueBondPrices) return undefined\n\n const userPointsBigInt = BigInt(userPoints)\n\n // Filter higher discounts that the user can't access\n const eligiblePrices = trueBondPrices.filter((price) => userPointsBigInt >= BigInt(price.points))\n if (!eligiblePrices || eligiblePrices.length === 0) return undefined\n\n // Find the highest points among the eligible prices\n return eligiblePrices.reduce((highest, current) => (BigInt(current.points) > BigInt(highest.points) ? current : highest))\n}\n\n/**\n * Finds the TrueBondPrices element with the highest points in the array, regardless of user points.\n * @param bondData - Bond Data containing an array of TrueBondPrices to analyze.\n * @returns The TrueBondPrices element with the highest points, or `undefined` if no data is available.\n */\nexport const findHighestTrueBondPriceUserAgnostic = (bondData?: BondsData): TrueBondPrices | undefined => {\n if (!bondData?.trueBondPrices?.length) return undefined\n\n return bondData.trueBondPrices.reduce((highest, current) =>\n BigInt(current.points) > BigInt(highest.points) ? current : highest,\n )\n}\n"],"names":[],"mappings":"AAEA;;;;;AAKG;MACU,wBAAwB,GAAG,CACtC,UAA0B,EAC1B,cAAiC,KACH;AAC9B,IAAA,IAAI,CAAC,UAAU,IAAI,CAAC,cAAc;AAAE,QAAA,OAAO,SAAS;AAEpD,IAAA,MAAM,gBAAgB,GAAG,MAAM,CAAC,UAAU,CAAC;;IAG3C,MAAM,cAAc,GAAG,cAAc,CAAC,MAAM,CAAC,CAAC,KAAK,KAAK,gBAAgB,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;AACjG,IAAA,IAAI,CAAC,cAAc,IAAI,cAAc,CAAC,MAAM,KAAK,CAAC;AAAE,QAAA,OAAO,SAAS;;AAGpE,IAAA,OAAO,cAAc,CAAC,MAAM,CAAC,CAAC,OAAO,EAAE,OAAO,MAAM,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,OAAO,GAAG,OAAO,CAAC,CAAC;AAC3H;AAEA;;;;AAIG;AACI,MAAM,oCAAoC,GAAG,CAAC,QAAoB,KAAgC;AACvG,IAAA,IAAI,CAAC,QAAQ,EAAE,cAAc,EAAE,MAAM;AAAE,QAAA,OAAO,SAAS;AAEvD,IAAA,OAAO,QAAQ,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,OAAO,EAAE,OAAO,KACrD,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,OAAO,GAAG,OAAO,CACpE;AACH;;;;"}
|
|
@@ -1,5 +1 @@
|
|
|
1
|
-
export declare function fetchSolanaTrueBillPrice(bondIssuanceAddress: string): Promise<string>;
|
|
2
|
-
/**
|
|
3
|
-
* This is the Typescript implementation of the Rust true_bond_price function since the on-chain program requires a real wallet
|
|
4
|
-
*/
|
|
5
1
|
export declare function calculateTrueBondPrice(bondPricing: any, bondTerm: any, currentTimestamp: number, principalMintDecimals: number, payoutMintDecimals: number, feeInPrincipal: number): string;
|
|
@@ -1,36 +1,38 @@
|
|
|
1
|
-
import '
|
|
2
|
-
import { BigNumber } from 'bignumber.js';
|
|
3
|
-
import '../constants/solanaConstants.js';
|
|
4
|
-
import 'buffer';
|
|
5
|
-
import '../config/constants/networks.js';
|
|
6
|
-
import '@ape.swap/apeswap-lists';
|
|
1
|
+
import { parseUnits, mulDivRound } from './fixedPoint.js';
|
|
7
2
|
|
|
8
3
|
/**
|
|
9
4
|
* This is the Typescript implementation of the Rust true_bond_price function since the on-chain program requires a real wallet
|
|
5
|
+
*
|
|
6
|
+
* Uses native BigInt with truncating division at each step, matching the real on-chain
|
|
7
|
+
* Rust u64/u128 integer arithmetic (see src/utils/suiHelpers.ts for the equivalent Sui/Move
|
|
8
|
+
* implementation of the same formula).
|
|
10
9
|
*/
|
|
10
|
+
const PRECISION_18 = 10n ** 18n;
|
|
11
11
|
function calculateTrueBondPrice(bondPricing, bondTerm, currentTimestamp, principalMintDecimals, payoutMintDecimals, feeInPrincipal) {
|
|
12
12
|
try {
|
|
13
13
|
// Extract values from the account data
|
|
14
|
-
const totalDebt =
|
|
15
|
-
const lastDecay =
|
|
16
|
-
const controlVariable =
|
|
17
|
-
const vestingEnd =
|
|
18
|
-
const minimumDebt =
|
|
19
|
-
const payoutTokenInitialSupply =
|
|
14
|
+
const totalDebt = BigInt(bondPricing.totalDebt?.toString() ?? '0');
|
|
15
|
+
const lastDecay = BigInt(bondPricing.lastDecay?.toString() ?? '0');
|
|
16
|
+
const controlVariable = BigInt(bondTerm.controlVariable?.toString() ?? '0');
|
|
17
|
+
const vestingEnd = BigInt(bondTerm.vestingEnd?.toString() ?? '0');
|
|
18
|
+
const minimumDebt = BigInt(bondTerm.minimumDebt?.toString() ?? '0');
|
|
19
|
+
const payoutTokenInitialSupply = BigInt(bondTerm.payoutTokenInitialSupply?.toString() ?? '0');
|
|
20
20
|
// Constants for price calculation (1e16 and 1e18)
|
|
21
|
-
const e16 =
|
|
22
|
-
const
|
|
23
|
-
const principalDecimalsMultiplier = new BigNumber(10).pow(principalMintDecimals);
|
|
21
|
+
const e16 = 10000000000000000n;
|
|
22
|
+
const principalDecimalsMultiplier = 10n ** BigInt(principalMintDecimals);
|
|
24
23
|
// Calculate debt ratio
|
|
25
|
-
const debtRatio = calculateDebtRatio(totalDebt, lastDecay,
|
|
24
|
+
const debtRatio = calculateDebtRatio(totalDebt, lastDecay, BigInt(currentTimestamp), vestingEnd, payoutMintDecimals, payoutTokenInitialSupply);
|
|
26
25
|
// Calculate price: (control_variable * debt_ratio * 1e16) / principal_decimals / 1e18
|
|
27
|
-
const numerator = controlVariable
|
|
28
|
-
const price = numerator
|
|
26
|
+
const numerator = controlVariable * debtRatio * e16;
|
|
27
|
+
const price = numerator / principalDecimalsMultiplier / PRECISION_18;
|
|
29
28
|
// Apply minimum debt floor
|
|
30
|
-
const priceToUse = price
|
|
29
|
+
const priceToUse = price < minimumDebt ? minimumDebt : price;
|
|
30
|
+
// reverseFee = fee/100 / (1 - fee/100) — feeInPrincipal is a plain percentage (e.g. 0.5).
|
|
31
|
+
// Scaled to 1e18 precision so the huge integer priceToUse never round-trips through a float.
|
|
31
32
|
const feeToUse = feeInPrincipal;
|
|
32
|
-
const
|
|
33
|
-
|
|
33
|
+
const reverseFeeScaled = parseUnits((feeToUse / 100 / (1 - feeToUse / 100)).toString(), 18);
|
|
34
|
+
const feeAdjustment = mulDivRound(priceToUse, reverseFeeScaled, PRECISION_18);
|
|
35
|
+
return (priceToUse + feeAdjustment).toString();
|
|
34
36
|
}
|
|
35
37
|
catch (error) {
|
|
36
38
|
console.error('Error in price calculation:', error);
|
|
@@ -43,26 +45,25 @@ function calculateTrueBondPrice(bondPricing, bondTerm, currentTimestamp, princip
|
|
|
43
45
|
function calculateDebtRatio(totalDebt, lastDecay, currentTimestamp, vestingEnd, payoutDecimals, payoutTokenInitialSupply) {
|
|
44
46
|
try {
|
|
45
47
|
// If vesting term is 0 or initial supply is 0, return 0
|
|
46
|
-
if (vestingEnd
|
|
47
|
-
return
|
|
48
|
+
if (vestingEnd === 0n || payoutTokenInitialSupply === 0n) {
|
|
49
|
+
return 0n;
|
|
48
50
|
}
|
|
49
51
|
// Calculate time elapsed since last decay (with underflow protection)
|
|
50
|
-
const timeSinceLast = currentTimestamp
|
|
52
|
+
const timeSinceLast = currentTimestamp < lastDecay ? 0n : currentTimestamp - lastDecay;
|
|
51
53
|
// Calculate decay amount: (total_debt * time_since_last) / vesting_term
|
|
52
|
-
const decayAmount = totalDebt
|
|
54
|
+
const decayAmount = (totalDebt * timeSinceLast) / vestingEnd;
|
|
53
55
|
// Cap decay amount at total debt
|
|
54
|
-
const finalDecayAmount = decayAmount
|
|
56
|
+
const finalDecayAmount = decayAmount > totalDebt ? totalDebt : decayAmount;
|
|
55
57
|
// Calculate current debt: total_debt - decay_amount
|
|
56
|
-
const currentDebt = totalDebt
|
|
58
|
+
const currentDebt = totalDebt - finalDecayAmount;
|
|
57
59
|
// Calculate debt ratio: (current_debt * payout_decimals_multiplier * 1e18) / initial_supply
|
|
58
|
-
const payoutDecimalsMultiplier =
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
return numerator.dividedBy(payoutTokenInitialSupply);
|
|
60
|
+
const payoutDecimalsMultiplier = 10n ** BigInt(payoutDecimals);
|
|
61
|
+
const numerator = currentDebt * payoutDecimalsMultiplier * PRECISION_18;
|
|
62
|
+
return numerator / payoutTokenInitialSupply;
|
|
62
63
|
}
|
|
63
64
|
catch (error) {
|
|
64
65
|
console.error('Error calculating debt ratio:', error);
|
|
65
|
-
return
|
|
66
|
+
return 0n;
|
|
66
67
|
}
|
|
67
68
|
}
|
|
68
69
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"calculateSolanaTrueBillPrice.js","sources":["../../src/utils/calculateSolanaTrueBillPrice.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"calculateSolanaTrueBillPrice.js","sources":["../../src/utils/calculateSolanaTrueBillPrice.ts"],"sourcesContent":["import { mulDivRound, parseUnits } from './fixedPoint'\n\n/**\n * This is the Typescript implementation of the Rust true_bond_price function since the on-chain program requires a real wallet\n *\n * Uses native BigInt with truncating division at each step, matching the real on-chain\n * Rust u64/u128 integer arithmetic (see src/utils/suiHelpers.ts for the equivalent Sui/Move\n * implementation of the same formula).\n */\nconst PRECISION_18 = 10n ** 18n\n\nexport function calculateTrueBondPrice(\n bondPricing: any,\n bondTerm: any,\n currentTimestamp: number,\n principalMintDecimals: number,\n payoutMintDecimals: number,\n feeInPrincipal: number,\n): string {\n try {\n // Extract values from the account data\n const totalDebt = BigInt(bondPricing.totalDebt?.toString() ?? '0')\n const lastDecay = BigInt(bondPricing.lastDecay?.toString() ?? '0')\n const controlVariable = BigInt(bondTerm.controlVariable?.toString() ?? '0')\n const vestingEnd = BigInt(bondTerm.vestingEnd?.toString() ?? '0')\n const minimumDebt = BigInt(bondTerm.minimumDebt?.toString() ?? '0')\n const payoutTokenInitialSupply = BigInt(bondTerm.payoutTokenInitialSupply?.toString() ?? '0')\n\n // Constants for price calculation (1e16 and 1e18)\n const e16 = 10_000_000_000_000_000n\n const principalDecimalsMultiplier = 10n ** BigInt(principalMintDecimals)\n\n // Calculate debt ratio\n const debtRatio = calculateDebtRatio(\n totalDebt,\n lastDecay,\n BigInt(currentTimestamp),\n vestingEnd,\n payoutMintDecimals,\n payoutTokenInitialSupply,\n )\n\n // Calculate price: (control_variable * debt_ratio * 1e16) / principal_decimals / 1e18\n const numerator = controlVariable * debtRatio * e16\n const price = numerator / principalDecimalsMultiplier / PRECISION_18\n\n // Apply minimum debt floor\n const priceToUse = price < minimumDebt ? minimumDebt : price\n\n // reverseFee = fee/100 / (1 - fee/100) — feeInPrincipal is a plain percentage (e.g. 0.5).\n // Scaled to 1e18 precision so the huge integer priceToUse never round-trips through a float.\n const feeToUse = feeInPrincipal\n const reverseFeeScaled = parseUnits((feeToUse / 100 / (1 - feeToUse / 100)).toString(), 18)\n const feeAdjustment = mulDivRound(priceToUse, reverseFeeScaled, PRECISION_18)\n return (priceToUse + feeAdjustment).toString()\n } catch (error) {\n console.error('Error in price calculation:', error)\n return '0'\n }\n}\n\n/**\n * This is the Typescript implementation of the Rust debt_ratio function\n */\nfunction calculateDebtRatio(\n totalDebt: bigint,\n lastDecay: bigint,\n currentTimestamp: bigint,\n vestingEnd: bigint,\n payoutDecimals: number,\n payoutTokenInitialSupply: bigint,\n): bigint {\n try {\n // If vesting term is 0 or initial supply is 0, return 0\n if (vestingEnd === 0n || payoutTokenInitialSupply === 0n) {\n return 0n\n }\n\n // Calculate time elapsed since last decay (with underflow protection)\n const timeSinceLast = currentTimestamp < lastDecay ? 0n : currentTimestamp - lastDecay\n\n // Calculate decay amount: (total_debt * time_since_last) / vesting_term\n const decayAmount = (totalDebt * timeSinceLast) / vestingEnd\n\n // Cap decay amount at total debt\n const finalDecayAmount = decayAmount > totalDebt ? totalDebt : decayAmount\n\n // Calculate current debt: total_debt - decay_amount\n const currentDebt = totalDebt - finalDecayAmount\n\n // Calculate debt ratio: (current_debt * payout_decimals_multiplier * 1e18) / initial_supply\n const payoutDecimalsMultiplier = 10n ** BigInt(payoutDecimals)\n\n const numerator = currentDebt * payoutDecimalsMultiplier * PRECISION_18\n\n return numerator / payoutTokenInitialSupply\n } catch (error) {\n console.error('Error calculating debt ratio:', error)\n return 0n\n }\n}\n"],"names":[],"mappings":";;AAEA;;;;;;AAMG;AACH,MAAM,YAAY,GAAG,GAAG,IAAI,GAAG;AAEzB,SAAU,sBAAsB,CACpC,WAAgB,EAChB,QAAa,EACb,gBAAwB,EACxB,qBAA6B,EAC7B,kBAA0B,EAC1B,cAAsB,EAAA;AAEtB,IAAA,IAAI;;AAEF,QAAA,MAAM,SAAS,GAAG,MAAM,CAAC,WAAW,CAAC,SAAS,EAAE,QAAQ,EAAE,IAAI,GAAG,CAAC;AAClE,QAAA,MAAM,SAAS,GAAG,MAAM,CAAC,WAAW,CAAC,SAAS,EAAE,QAAQ,EAAE,IAAI,GAAG,CAAC;AAClE,QAAA,MAAM,eAAe,GAAG,MAAM,CAAC,QAAQ,CAAC,eAAe,EAAE,QAAQ,EAAE,IAAI,GAAG,CAAC;AAC3E,QAAA,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,UAAU,EAAE,QAAQ,EAAE,IAAI,GAAG,CAAC;AACjE,QAAA,MAAM,WAAW,GAAG,MAAM,CAAC,QAAQ,CAAC,WAAW,EAAE,QAAQ,EA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ACX;;AAGA,QAAA,MAAM,aAAa,GAAG,gBAAgB,GAAG,SAAS,GAAG,EAAE,GAAG,gBAAgB,GAAG,SAAS;;QAGtF,MAAM,WAAW,GAAG,CAAC,SAAS,GAAG,aAAa,IAAI,UAAU;;AAG5D,QAAA,MAAM,gBAAgB,GAAG,WAAW,GAAG,SAAS,GAAG,SAAS,GAAG,WAAW;;AAG1E,QAAA,MAAM,WAAW,GAAG,SAAS,GAAG,gBAAgB;;QAGhD,MAAM,wBAAwB,GAAG,GAAG,IAAI,MAAM,CAAC,cAAc,CAAC;AAE9D,QAAA,MAAM,SAAS,GAAG,WAAW,GAAG,wBAAwB,GAAG,YAAY;QAEvE,OAAO,SAAS,GAAG,wBAAwB;IAC7C;IAAE,OAAO,KAAK,EAAE;AACd,QAAA,OAAO,CAAC,KAAK,CAAC,+BAA+B,EAAE,KAAK,CAAC;AACrD,QAAA,OAAO,EAAE;IACX;AACF;;;;"}
|
|
@@ -1,25 +1,10 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { parseUnits } from './fixedPoint.js';
|
|
2
2
|
|
|
3
|
-
function adjustDecimals(numStr) {
|
|
4
|
-
const parts = numStr.split('.');
|
|
5
|
-
if (parts.length < 2) {
|
|
6
|
-
// This means the number doesn't have any decimals
|
|
7
|
-
return numStr;
|
|
8
|
-
}
|
|
9
|
-
if (parts[1].length > 18) {
|
|
10
|
-
parts[1] = parts[1].slice(0, 18); // Take the first 18 decimals
|
|
11
|
-
return parts[0] + '.' + parts[1];
|
|
12
|
-
}
|
|
13
|
-
else {
|
|
14
|
-
return numStr;
|
|
15
|
-
}
|
|
16
|
-
}
|
|
17
3
|
const convertToBigish = (numberString, decimals = 18) => {
|
|
18
4
|
if (!numberString || !decimals)
|
|
19
5
|
return '';
|
|
20
|
-
|
|
21
|
-
return new BigNumber(adjustedDecimals).times(new BigNumber(10).pow(decimals)).toFixed(0);
|
|
6
|
+
return parseUnits(numberString, decimals).toString();
|
|
22
7
|
};
|
|
23
8
|
|
|
24
|
-
export {
|
|
9
|
+
export { convertToBigish };
|
|
25
10
|
//# sourceMappingURL=convertToBigish.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"convertToBigish.js","sources":["../../src/utils/convertToBigish.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"convertToBigish.js","sources":["../../src/utils/convertToBigish.ts"],"sourcesContent":["import { parseUnits } from './fixedPoint'\n\nexport const convertToBigish = (numberString?: string, decimals: number = 18) => {\n if (!numberString || !decimals) return ''\n\n return parseUnits(numberString, decimals).toString()\n}\n"],"names":[],"mappings":";;AAEO,MAAM,eAAe,GAAG,CAAC,YAAqB,EAAE,QAAA,GAAmB,EAAE,KAAI;AAC9E,IAAA,IAAI,CAAC,YAAY,IAAI,CAAC,QAAQ;AAAE,QAAA,OAAO,EAAE;IAEzC,OAAO,UAAU,CAAC,YAAY,EAAE,QAAQ,CAAC,CAAC,QAAQ,EAAE;AACtD;;;;"}
|
|
@@ -15,16 +15,10 @@ export declare const getVestingTermsString: (bond?: BondsData | BillsConfig) =>
|
|
|
15
15
|
export declare const getVestingTermsTooltipString: (bond?: BondsData | BillsConfig) => string | undefined;
|
|
16
16
|
export declare const discountEarnTokenPrice: (bond: BondsData, useTiers?: boolean) => string | undefined;
|
|
17
17
|
export declare const discountEarnTokenPriceForUser: (bond: BondsData, useTiers?: boolean, userTier?: LaunchBondTiers) => string;
|
|
18
|
-
export declare const
|
|
19
|
-
export declare const getSafetyAvailable: (bond?: BondsData, allowLowValueBonds?: boolean) => BigNumber;
|
|
20
|
-
export declare const getSafetyPurchaseLimit: (bond?: BondsData, allowLowValueBonds?: boolean) => BigNumber;
|
|
21
|
-
export declare const getMaxBuy: (bond?: BondsData, allowLowValueBonds?: boolean) => BigNumber;
|
|
18
|
+
export declare const getMaxBuy: (bond?: BondsData, allowLowValueBonds?: boolean) => number;
|
|
22
19
|
export declare function formatUSDNumber(input: string): string;
|
|
23
|
-
export declare const youSpendUSD: (bond: BondsData, inputValue: string) => string;
|
|
24
20
|
export declare const getPayoutAmount: (bond?: BondsData, inputValue?: string, userPoints?: string | null) => number;
|
|
25
|
-
export declare const youGetUSD: (bond?: BondsData, inputValue?: string, userPoints?: string) => number;
|
|
26
21
|
export declare const getRawBonus: (bond?: BondsData, inputValue?: string, userPoints?: string) => string;
|
|
27
|
-
export declare const getFeeAmount: (bond?: BondsData, inputValue?: string, userPoints?: string) => number;
|
|
28
22
|
export declare const getBonusColor: (premiumString: string) => string;
|
|
29
23
|
/**
|
|
30
24
|
* Calculates the principal token amount needed to receive a target payout amount.
|
|
@@ -33,8 +27,8 @@ export declare const getBonusColor: (premiumString: string) => string;
|
|
|
33
27
|
* @param bond - The bond data
|
|
34
28
|
* @param targetPayoutAmount - The desired payout amount in payout tokens
|
|
35
29
|
* @param userPoints - User's tier points
|
|
36
|
-
* @returns The principal token amount needed, or
|
|
30
|
+
* @returns The principal token amount needed, or 0 if calculation cannot be performed
|
|
37
31
|
*/
|
|
38
|
-
export declare const getPrincipalAmount: (bond?: BondsData, targetPayoutAmount?: number | string, userPoints?: string | null) =>
|
|
32
|
+
export declare const getPrincipalAmount: (bond?: BondsData, targetPayoutAmount?: number | string, userPoints?: string | null) => number;
|
|
39
33
|
export declare const getRemainingTokensString: (bond: BondsData, allowLowValueBonds?: boolean) => string;
|
|
40
34
|
export declare const remainingPercentage: (bond: BondsData) => number;
|