Skip to content

Commit c5e1a69

Browse files
authored
Merge pull request #62 from bbachain/fix-create-pool-transaction
fix: create pool service
2 parents 0861478 + 521fc97 commit c5e1a69

4 files changed

Lines changed: 57 additions & 31 deletions

File tree

src/app/(walletConnected)/liquidity-pools/create-pool/page.tsx

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,6 @@ import { TCreatePoolPayload, MintInfo } from '@/features/liquidityPool/types'
4444
import {
4545
isBBAPool,
4646
getBBAPositionInPool,
47-
requiresBBAWrapping
4847
} from '@/features/liquidityPool/utils'
4948
import { createPoolValidation } from '@/features/liquidityPool/validation'
5049
import { LoadingDialog } from '@/features/nfts/components/StatusDialog'
@@ -393,13 +392,20 @@ export default function CreatePool() {
393392
setIsTokenDialogOpen(true)
394393
}, [])
395394

395+
const resetTokenAmounts = useCallback(() => {
396+
form.setValue('baseTokenAmount', '')
397+
form.setValue('quoteTokenAmount', '')
398+
}, [form])
399+
396400
// Auto-calculate quote amount based on price ratio
397401
// Initial Price format: "X BaseToken per QuoteToken"
398402
// Example: "1000 SHIB per USDT" means 1 USDT = 1000 SHIB, so 1 SHIB = 1/1000 USDT
399403
const handleBaseAmountChange = useCallback(
400404
(value: string) => {
401405
form.setValue('baseTokenAmount', value, { shouldValidate: true })
402406

407+
if(value === '') return resetTokenAmounts()
408+
403409
// Auto-calculate quote amount if both tokens and initial price are set
404410
const initialPrice = parseFloat(form.getValues('initialPrice'))
405411
if (initialPrice && value && selectedBaseToken && selectedQuoteToken) {
@@ -409,13 +415,15 @@ export default function CreatePool() {
409415
form.setValue('quoteTokenAmount', quoteAmount.toString(), { shouldValidate: true })
410416
}
411417
},
412-
[form, selectedBaseToken, selectedQuoteToken]
418+
[form, resetTokenAmounts, selectedBaseToken, selectedQuoteToken]
413419
)
414420

415421
const handleQuoteAmountChange = useCallback(
416422
(value: string) => {
417423
form.setValue('quoteTokenAmount', value, { shouldValidate: true })
418424

425+
if (value === '') return resetTokenAmounts()
426+
419427
// Auto-calculate base amount if both tokens and initial price are set
420428
const initialPrice = parseFloat(form.getValues('initialPrice'))
421429
if (initialPrice && value && selectedBaseToken && selectedQuoteToken) {
@@ -425,7 +433,7 @@ export default function CreatePool() {
425433
form.setValue('baseTokenAmount', baseAmount.toString(), { shouldValidate: true })
426434
}
427435
},
428-
[form, selectedBaseToken, selectedQuoteToken]
436+
[form, resetTokenAmounts, selectedBaseToken, selectedQuoteToken]
429437
)
430438

431439
// Show loading state for tokens

src/app/(walletConnected)/liquidity-pools/deposit/[poolId]/page.tsx

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,13 +148,20 @@ export default function LiquidityPoolDeposit({ params }: { params: { poolId: str
148148
!hasInsufficientBalanceB &&
149149
!depositMutation.isPending
150150

151+
const resetValue = () => {
152+
setFromAmount('')
153+
setToAmount('')
154+
}
155+
151156
const handleFromAmountChange = (value: string) => {
152157
setFromAmount(value)
158+
if (value === '') return resetValue()
153159
setLastChangedField('from')
154160
}
155161

156162
const handleToAmountChange = (value: string) => {
157163
setToAmount(value)
164+
if (value === '') return resetValue()
158165
setLastChangedField('to')
159166
}
160167

src/app/(walletConnected)/liquidity-pools/detail/[poolId]/page.tsx

Lines changed: 13 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,6 @@ export default function PoolDetail({ params }: { params: { poolId: string } }) {
137137
const router = useRouter()
138138
const poolId = params.poolId
139139

140-
const [isInitialLoad, setIsInitialLoad] = useState<boolean>(true)
141140
const [isOwnerTab, setIsOwnerTab] = useState<boolean>(false)
142141
const isMobile = useIsMobile()
143142

@@ -182,16 +181,7 @@ export default function PoolDetail({ params }: { params: { poolId: string } }) {
182181
}
183182
}, [getTransactionsByPoolId.error, getTransactionsByPoolId.isError])
184183

185-
useEffect(() => {
186-
if (!(getPoolById.isLoading || getTransactionsByPoolId.isLoading)) {
187-
setIsInitialLoad(false)
188-
}
189-
}, [getPoolById.isLoading, getTransactionsByPoolId.isLoading])
190-
191-
if (
192-
isInitialLoad &&
193-
(getPoolById.isLoading || getTransactionsByPoolId.isLoading || getUserStats.isLoading)
194-
)
184+
if (getPoolById.isLoading || getTransactionsByPoolId.isLoading || getUserStats.isLoading)
195185
return (
196186
<div className="w-full mx-auto 2xl:max-w-7xl lg:max-w-5xl md:max-w-2xl px-[15px]">
197187
<Button
@@ -216,7 +206,7 @@ export default function PoolDetail({ params }: { params: { poolId: string } }) {
216206
<HiOutlineArrowNarrowLeft />
217207
<h4>Pools</h4>
218208
</Button>
219-
{getPoolById.isLoading ? (
209+
{getPoolById.isRefetching ? (
220210
<div className="flex flex-wrap items-center justify-between gap-4">
221211
<div className="flex items-center gap-2">
222212
<Skeleton className="h-7 w-7 rounded-full" />
@@ -340,33 +330,33 @@ export default function PoolDetail({ params }: { params: { poolId: string } }) {
340330
mintBAmount={mintBAmount}
341331
mintASymbol={pool?.mintA?.symbol ?? ''}
342332
mintBSymbol={pool?.mintB?.symbol ?? ''}
343-
isLoading={getPoolById.isLoading}
333+
isLoading={getPoolById.isRefetching}
344334
/>
345335
</div>
346336
<div className="md:mt-6 mt-3 grid grid-cols-2 lg:flex lg:gap-y-0 gap-y-3 items-center justify-between">
347337
<StatsItem
348-
isLoading={getPoolById.isLoading}
338+
isLoading={getPoolById.isRefetching}
349339
title="APR(7 days)"
350340
info="Weekly Percentage Rate earned by liquidity providers from trading fees and rewards."
351341
content={`${pool?.apr24h.toFixed(2) ?? 0.0}%`}
352342
/>
353343
<hr className="w-px h-12 lg:block hidden bg-light-grey border-0" />
354344
<StatsItem
355-
isLoading={getPoolById.isLoading}
345+
isLoading={getPoolById.isRefetching}
356346
title="TVL"
357347
info="The total dollar value of assets locked in this liquidity pool."
358348
content={`$${pool?.tvl.toLocaleString() ?? 0}`}
359349
/>
360350
<hr className="w-px h-12 lg:block hidden bg-light-grey border-0" />
361351
<StatsItem
362-
isLoading={getPoolById.isLoading}
352+
isLoading={getPoolById.isRefetching}
363353
title="Fees(24h)"
364354
info="Trading fees generated by this pool in the past 24 hours."
365355
content={`$${pool?.fees24h.toFixed(3) ?? 0}`}
366356
/>
367357
<hr className="w-px h-12 lg:block hidden bg-light-grey border-0" />
368358
<StatsItem
369-
isLoading={getPoolById.isLoading}
359+
isLoading={getPoolById.isRefetching}
370360
title="Volume(24h)"
371361
info="Total swap volume (trades) processed in this pool within the last 24 hours."
372362
content={`$${pool?.volume24h.toFixed(3) ?? 0}`}
@@ -462,33 +452,33 @@ export default function PoolDetail({ params }: { params: { poolId: string } }) {
462452
mintBAmount={userStats?.userReserveB ?? 0}
463453
mintASymbol={pool?.mintA?.symbol ?? ''}
464454
mintBSymbol={pool?.mintB?.symbol ?? ''}
465-
isLoading={getUserStats.isLoading}
455+
isLoading={getUserStats.isRefetching}
466456
/>
467457
</div>
468458
<div className="md:mt-6 mt-3 grid grid-cols-2 lg:flex lg:gap-y-0 gap-y-3 items-center justify-between">
469459
<StatsItem
470-
isLoading={getUserStats.isLoading}
460+
isLoading={getUserStats.isRefetching}
471461
title="My Pool Share (%)"
472462
info="This is the percentage of the total liquidity pool that you currently own."
473463
content={`${((userStats?.userShare ?? 0) * 100).toFixed(2)}%`}
474464
/>
475465
<hr className="w-px h-12 lg:block hidden bg-light-grey border-0" />
476466
<StatsItem
477-
isLoading={getUserStats.isLoading}
467+
isLoading={getUserStats.isRefetching}
478468
title="My Liquidity Value"
479469
info="The estimated dollar value of the tokens you've contributed to this pool."
480470
content={`$${userStats?.userReserveTotalPrice.toLocaleString() ?? 0}`}
481471
/>
482472
<hr className="w-px h-12 lg:block hidden bg-light-grey border-0" />
483473
<StatsItem
484-
isLoading={getUserStats.isLoading}
474+
isLoading={getUserStats.isRefetching}
485475
title="LP Tokens Held"
486476
info="The total number of LP (liquidity provider) tokens you own — including both staked and unstaked."
487477
content={`${userStats?.userLPToken.toLocaleString() ?? 0} LP`}
488478
/>
489479
<hr className="w-px h-12 lg:block hidden bg-light-grey border-0" />
490480
<StatsItem
491-
isLoading={getUserStats.isLoading}
481+
isLoading={getUserStats.isRefetching}
492482
title="Fee Earnings(24h)"
493483
info="Total amount you've earned from trading fees within the last 24 hours."
494484
content={`$${userStats?.dailyFeeEarnings.toFixed(3) ?? 0}`}
@@ -499,7 +489,7 @@ export default function PoolDetail({ params }: { params: { poolId: string } }) {
499489
</div>
500490
<div className="flex flex-col md:space-y-6 space-y-3 md:mt-14 mt-5">
501491
<h2 className="font-semibold lg:text-2xl text-xl text-main-black">Transactions</h2>
502-
{getTransactionsByPoolId.isLoading ? (
492+
{getTransactionsByPoolId.isRefetching ? (
503493
<PoolDetailTransactionSkeleton />
504494
) : (
505495
<TransactionDataTable

src/features/liquidityPool/services.ts

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ export const useGetPools = () => {
7171
const getAllTokenPrices = useGetAllTokenPrices()
7272
const allTokenPrices = getAllTokenPrices.data
7373
const getPoolsWithPrices = useQuery<TGetPoolsResponse>({
74-
queryKey: [SERVICES_KEY.POOL.GET_POOLS, allTokenPrices],
74+
queryKey: [SERVICES_KEY.POOL.GET_POOLS],
7575
queryFn: async () => {
7676
const poolAccounts = await getPoolAccounts(connection)
7777
const batchSize = 10
@@ -122,7 +122,7 @@ export const useGetPoolById = ({ poolId }: { poolId: string }) => {
122122
const allTokenPrices = getAllTokenPrices.data
123123

124124
const getPoolWithPricesQuery = useQuery<TGetPoolByIdResponse>({
125-
queryKey: [SERVICES_KEY.POOL.GET_POOL_BY_ID, poolId, allTokenPrices],
125+
queryKey: [SERVICES_KEY.POOL.GET_POOL_BY_ID, poolId],
126126
queryFn: async () => {
127127
const pubKey = new PublicKey(poolId)
128128
const accountInfo = await connection.getAccountInfo(pubKey)
@@ -805,6 +805,14 @@ export const useCreatePool = () => {
805805
baseAmountDaltons
806806
)
807807

808+
// transaction approval
809+
const approveIx = createApproveInstruction(
810+
userBaseTokenAccount,
811+
ownerAddress,
812+
ownerAddress,
813+
baseAmountDaltons
814+
)
815+
808816
// Transfer BBA to pool (using special BBA handling)
809817
console.log('🔄 Transferring BBA to pool account...')
810818
const transferBBAIx = SystemProgram.transfer({
@@ -817,7 +825,12 @@ export const useCreatePool = () => {
817825
const syncBBAIx = createSyncNativeInstruction(swapTokenBAccount)
818826

819827
// Combine all transfers
820-
const liquidityTx = new Transaction().add(transferBaseIx, transferBBAIx, syncBBAIx)
828+
const liquidityTx = new Transaction().add(
829+
approveIx,
830+
transferBaseIx,
831+
transferBBAIx,
832+
syncBBAIx
833+
)
821834
const liquiditySig = await sendTransactionWithRetry(
822835
liquidityTx,
823836
connection,
@@ -891,8 +904,16 @@ export const useCreatePool = () => {
891904
quoteAmountDaltons
892905
)
893906

907+
// approval instruction
908+
const approveIx = createApproveInstruction(
909+
userQuoteTokenAccount,
910+
ownerAddress,
911+
ownerAddress,
912+
baseAmountDaltons
913+
)
914+
894915
// Send initial liquidity transfer
895-
const liquidityTx = new Transaction().add(transferBaseIx, transferQuoteIx)
916+
const liquidityTx = new Transaction().add(approveIx, transferBaseIx, transferQuoteIx)
896917
const liquiditySig = await sendTransactionWithRetry(
897918
liquidityTx,
898919
connection,
@@ -1454,7 +1475,7 @@ export const useDepositToPool = () => {
14541475
try {
14551476
const signature = await sendTransaction(transaction, connection, {
14561477
skipPreflight: false,
1457-
preflightCommitment: 'confirmed',
1478+
preflightCommitment: 'confirmed'
14581479
})
14591480
console.log('✅ Transaction sent successfully:', signature)
14601481

0 commit comments

Comments
 (0)