feat: update database schema for precision + AMM behavior
This commit is contained in:
parent
a278d0c6a5
commit
930d1f41d7
8 changed files with 893 additions and 108 deletions
|
|
@ -8,7 +8,7 @@
|
|||
import { USER_DATA } from '$lib/stores/user-data';
|
||||
import { toast } from 'svelte-sonner';
|
||||
|
||||
let {
|
||||
let {
|
||||
open = $bindable(false),
|
||||
type,
|
||||
coin,
|
||||
|
|
@ -26,16 +26,45 @@
|
|||
let loading = $state(false);
|
||||
|
||||
let numericAmount = $derived(parseFloat(amount) || 0);
|
||||
let estimatedCost = $derived(numericAmount * coin.currentPrice);
|
||||
let currentPrice = $derived(coin.currentPrice || 0);
|
||||
|
||||
let maxSellableAmount = $derived(
|
||||
type === 'SELL' && coin
|
||||
? Math.min(userHolding, Math.floor(Number(coin.poolCoinAmount) * 0.995))
|
||||
: userHolding
|
||||
);
|
||||
|
||||
let estimatedResult = $derived(calculateEstimate(numericAmount, type, currentPrice));
|
||||
let hasValidAmount = $derived(numericAmount > 0);
|
||||
let userBalance = $derived($USER_DATA ? Number($USER_DATA.baseCurrencyBalance) : 0);
|
||||
let hasEnoughFunds = $derived(
|
||||
type === 'BUY'
|
||||
? estimatedCost <= userBalance
|
||||
: numericAmount <= userHolding
|
||||
type === 'BUY' ? numericAmount <= userBalance : numericAmount <= userHolding
|
||||
);
|
||||
let canTrade = $derived(hasValidAmount && hasEnoughFunds && !loading);
|
||||
|
||||
function calculateEstimate(amount: number, tradeType: 'BUY' | 'SELL', price: number) {
|
||||
if (!amount || !price || !coin) return { result: 0 };
|
||||
|
||||
const poolCoin = Number(coin.poolCoinAmount);
|
||||
const poolBase = Number(coin.poolBaseCurrencyAmount);
|
||||
|
||||
if (poolCoin <= 0 || poolBase <= 0) return { result: 0 };
|
||||
|
||||
const k = poolCoin * poolBase;
|
||||
|
||||
if (tradeType === 'BUY') {
|
||||
// AMM formula: how many coins for spending 'amount' dollars
|
||||
const newPoolBase = poolBase + amount;
|
||||
const newPoolCoin = k / newPoolBase;
|
||||
return { result: poolCoin - newPoolCoin };
|
||||
} else {
|
||||
// AMM formula: how many dollars for selling 'amount' coins
|
||||
const newPoolCoin = poolCoin + amount;
|
||||
const newPoolBase = k / newPoolCoin;
|
||||
return { result: poolBase - newPoolBase };
|
||||
}
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
open = false;
|
||||
amount = '';
|
||||
|
|
@ -65,9 +94,10 @@
|
|||
}
|
||||
|
||||
toast.success(`${type === 'BUY' ? 'Bought' : 'Sold'} successfully!`, {
|
||||
description: type === 'BUY'
|
||||
? `Purchased ${result.coinsBought.toFixed(2)} ${coin.symbol} for $${result.totalCost.toFixed(2)}`
|
||||
: `Sold ${result.coinsSold.toFixed(2)} ${coin.symbol} for $${result.totalReceived.toFixed(2)}`
|
||||
description:
|
||||
type === 'BUY'
|
||||
? `Purchased ${result.coinsBought.toFixed(6)} ${coin.symbol} for $${result.totalCost.toFixed(6)}`
|
||||
: `Sold ${result.coinsSold.toFixed(6)} ${coin.symbol} for $${result.totalReceived.toFixed(6)}`
|
||||
});
|
||||
|
||||
onSuccess?.();
|
||||
|
|
@ -83,10 +113,10 @@
|
|||
|
||||
function setMaxAmount() {
|
||||
if (type === 'SELL') {
|
||||
amount = userHolding.toString();
|
||||
amount = maxSellableAmount.toString();
|
||||
} else if ($USER_DATA) {
|
||||
const maxCoins = Math.floor(userBalance / coin.currentPrice * 100) / 100;
|
||||
amount = maxCoins.toString();
|
||||
// For BUY, max is user's balance
|
||||
amount = userBalance.toString();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
|
@ -111,58 +141,66 @@
|
|||
<div class="space-y-4">
|
||||
<!-- Amount Input -->
|
||||
<div class="space-y-2">
|
||||
<Label for="amount">Amount ({coin.symbol})</Label>
|
||||
<Label for="amount">
|
||||
{type === 'BUY' ? 'Amount to spend ($)' : `Amount (${coin.symbol})`}
|
||||
</Label>
|
||||
<div class="flex gap-2">
|
||||
<Input
|
||||
id="amount"
|
||||
type="number"
|
||||
step="0.01"
|
||||
step={type === 'BUY' ? '0.01' : '1'}
|
||||
min="0"
|
||||
bind:value={amount}
|
||||
placeholder="0.00"
|
||||
class="flex-1"
|
||||
/>
|
||||
<Button variant="outline" size="sm" onclick={setMaxAmount}>
|
||||
Max
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onclick={setMaxAmount}>Max</Button>
|
||||
</div>
|
||||
{#if type === 'SELL'}
|
||||
<p class="text-muted-foreground text-xs">
|
||||
Available: {userHolding.toFixed(2)} {coin.symbol}
|
||||
Available: {userHolding.toFixed(6)}
|
||||
{coin.symbol}
|
||||
{#if maxSellableAmount < userHolding}
|
||||
<br />Max sellable: {maxSellableAmount.toFixed(0)} {coin.symbol} (pool limit)
|
||||
{/if}
|
||||
</p>
|
||||
{:else if $USER_DATA}
|
||||
<p class="text-muted-foreground text-xs">
|
||||
Balance: ${userBalance.toFixed(2)}
|
||||
Balance: ${userBalance.toFixed(6)}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Estimated Cost/Return -->
|
||||
<!-- Estimated Cost/Return with explicit fees -->
|
||||
{#if hasValidAmount}
|
||||
<div class="bg-muted/50 rounded-lg p-3">
|
||||
<div class="flex justify-between items-center">
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="text-sm font-medium">
|
||||
{type === 'BUY' ? 'Total Cost:' : 'You\'ll Receive:'}
|
||||
{type === 'BUY' ? `${coin.symbol} you'll get:` : "You'll receive:"}
|
||||
</span>
|
||||
<span class="font-bold">
|
||||
${estimatedCost.toFixed(2)}
|
||||
{type === 'BUY'
|
||||
? `~${estimatedResult.result.toFixed(6)} ${coin.symbol}`
|
||||
: `~$${estimatedResult.result.toFixed(6)}`}
|
||||
</span>
|
||||
</div>
|
||||
{#if !hasEnoughFunds}
|
||||
<Badge variant="destructive" class="mt-2 text-xs">
|
||||
{type === 'BUY' ? 'Insufficient funds' : 'Insufficient coins'}
|
||||
</Badge>
|
||||
{/if}
|
||||
<p class="text-muted-foreground mt-1 text-xs">
|
||||
AMM estimation - includes slippage from pool impact
|
||||
</p>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if !hasEnoughFunds && hasValidAmount}
|
||||
<Badge variant="destructive" class="text-xs">
|
||||
{type === 'BUY' ? 'Insufficient funds' : 'Insufficient coins'}
|
||||
</Badge>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<Dialog.Footer class="flex gap-2">
|
||||
<Button variant="outline" onclick={handleClose} disabled={loading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onclick={handleTrade}
|
||||
<Button variant="outline" onclick={handleClose} disabled={loading}>Cancel</Button>
|
||||
<Button
|
||||
onclick={handleTrade}
|
||||
disabled={!canTrade}
|
||||
variant={type === 'BUY' ? 'default' : 'destructive'}
|
||||
>
|
||||
|
|
|
|||
|
|
@ -14,9 +14,9 @@ export const user = pgTable("user", {
|
|||
isBanned: boolean("is_banned").default(false),
|
||||
banReason: text("ban_reason"),
|
||||
baseCurrencyBalance: decimal("base_currency_balance", {
|
||||
precision: 19,
|
||||
scale: 4,
|
||||
}).notNull().default("10000.0000"), // 10,000 *BUSS
|
||||
precision: 20,
|
||||
scale: 8,
|
||||
}).notNull().default("10000.00000000"), // 10,000 *BUSS
|
||||
bio: varchar("bio", { length: 160 }).default("Hello am 48 year old man from somalia. Sorry for my bed england. I selled my wife for internet connection for play “conter stirk”"),
|
||||
username: varchar("username", { length: 30 }).notNull().unique(),
|
||||
});
|
||||
|
|
@ -63,14 +63,14 @@ export const coin = pgTable("coin", {
|
|||
symbol: varchar("symbol", { length: 10 }).notNull().unique(),
|
||||
icon: text("icon"), // New field for coin icon
|
||||
creatorId: integer("creator_id").references(() => user.id, { onDelete: "set null", }), // Coin can exist even if creator is deleted
|
||||
initialSupply: decimal("initial_supply", { precision: 28, scale: 8 }).notNull(),
|
||||
circulatingSupply: decimal("circulating_supply", { precision: 28, scale: 8 }).notNull(),
|
||||
currentPrice: decimal("current_price", { precision: 19, scale: 8 }).notNull(), // Price in base currency
|
||||
marketCap: decimal("market_cap", { precision: 28, scale: 4 }).notNull(),
|
||||
volume24h: decimal("volume_24h", { precision: 28, scale: 4 }).default("0.0000"),
|
||||
change24h: decimal("change_24h", { precision: 8, scale: 4 }).default("0.0000"), // Percentage
|
||||
poolCoinAmount: decimal("pool_coin_amount", { precision: 28, scale: 8 }).notNull().default("0.00000000"),
|
||||
poolBaseCurrencyAmount: decimal("pool_base_currency_amount", { precision: 28, scale: 4, }).notNull().default("0.0000"),
|
||||
initialSupply: decimal("initial_supply", { precision: 30, scale: 8 }).notNull(),
|
||||
circulatingSupply: decimal("circulating_supply", { precision: 30, scale: 8 }).notNull(),
|
||||
currentPrice: decimal("current_price", { precision: 20, scale: 8 }).notNull(), // Price in base currency
|
||||
marketCap: decimal("market_cap", { precision: 30, scale: 2 }).notNull(),
|
||||
volume24h: decimal("volume_24h", { precision: 30, scale: 2 }).default("0.00"),
|
||||
change24h: decimal("change_24h", { precision: 10, scale: 4 }).default("0.0000"), // Percentage
|
||||
poolCoinAmount: decimal("pool_coin_amount", { precision: 30, scale: 8 }).notNull().default("0.00000000"),
|
||||
poolBaseCurrencyAmount: decimal("pool_base_currency_amount", { precision: 30, scale: 8, }).notNull().default("0.00000000"),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
isListed: boolean("is_listed").default(true).notNull(),
|
||||
|
|
@ -79,7 +79,7 @@ export const coin = pgTable("coin", {
|
|||
export const userPortfolio = pgTable("user_portfolio", {
|
||||
userId: integer("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
|
||||
coinId: integer("coin_id").notNull().references(() => coin.id, { onDelete: "cascade" }),
|
||||
quantity: decimal("quantity", { precision: 28, scale: 8 }).notNull(),
|
||||
quantity: decimal("quantity", { precision: 30, scale: 8 }).notNull(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
},
|
||||
(table) => {
|
||||
|
|
@ -94,15 +94,15 @@ export const transaction = pgTable("transaction", {
|
|||
userId: integer("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
|
||||
coinId: integer("coin_id").notNull().references(() => coin.id, { onDelete: "cascade" }),
|
||||
type: transactionTypeEnum("type").notNull(),
|
||||
quantity: decimal("quantity", { precision: 28, scale: 8 }).notNull(),
|
||||
pricePerCoin: decimal("price_per_coin", { precision: 19, scale: 8 }).notNull(),
|
||||
totalBaseCurrencyAmount: decimal("total_base_currency_amount", { precision: 28, scale: 4 }).notNull(),
|
||||
quantity: decimal("quantity", { precision: 30, scale: 8 }).notNull(),
|
||||
pricePerCoin: decimal("price_per_coin", { precision: 20, scale: 8 }).notNull(),
|
||||
totalBaseCurrencyAmount: decimal("total_base_currency_amount", { precision: 30, scale: 8 }).notNull(),
|
||||
timestamp: timestamp("timestamp", { withTimezone: true }).notNull().defaultNow(),
|
||||
});
|
||||
|
||||
export const priceHistory = pgTable("price_history", {
|
||||
id: serial("id").primaryKey(),
|
||||
coinId: integer("coin_id").notNull().references(() => coin.id, { onDelete: "cascade" }),
|
||||
price: decimal("price", { precision: 19, scale: 8 }).notNull(),
|
||||
price: decimal("price", { precision: 20, scale: 8 }).notNull(),
|
||||
timestamp: timestamp("timestamp", { withTimezone: true }).notNull().defaultNow(),
|
||||
});
|
||||
|
|
|
|||
|
|
@ -87,23 +87,32 @@ export async function POST({ params, request }) {
|
|||
|
||||
let newPrice: number;
|
||||
let totalCost: number;
|
||||
let priceImpact: number = 0;
|
||||
|
||||
if (poolCoinAmount <= 0 || poolBaseCurrencyAmount <= 0) {
|
||||
throw error(400, 'Liquidity pool is not properly initialized or is empty. Trading halted.');
|
||||
}
|
||||
|
||||
if (type === 'BUY') {
|
||||
// Calculate price impact for buying
|
||||
// AMM BUY: amount = dollars to spend
|
||||
const k = poolCoinAmount * poolBaseCurrencyAmount;
|
||||
const newPoolBaseCurrency = poolBaseCurrencyAmount + (amount * currentPrice);
|
||||
const newPoolBaseCurrency = poolBaseCurrencyAmount + amount;
|
||||
const newPoolCoin = k / newPoolBaseCurrency;
|
||||
const coinsBought = poolCoinAmount - newPoolCoin;
|
||||
|
||||
totalCost = amount * currentPrice;
|
||||
totalCost = amount;
|
||||
newPrice = newPoolBaseCurrency / newPoolCoin;
|
||||
priceImpact = ((newPrice - currentPrice) / currentPrice) * 100;
|
||||
|
||||
if (userBalance < totalCost) {
|
||||
throw error(400, `Insufficient funds. You need $${totalCost.toFixed(2)} but only have $${userBalance.toFixed(2)}`);
|
||||
throw error(400, `Insufficient funds. You need *${totalCost.toFixed(6)} BUSS but only have *${userBalance.toFixed(6)} BUSS`);
|
||||
}
|
||||
|
||||
if (coinsBought <= 0) {
|
||||
throw error(400, 'Trade amount too small - would result in zero tokens');
|
||||
}
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
// Update user balance
|
||||
await tx.update(user)
|
||||
.set({
|
||||
baseCurrencyBalance: (userBalance - totalCost).toString(),
|
||||
|
|
@ -111,7 +120,6 @@ export async function POST({ params, request }) {
|
|||
})
|
||||
.where(eq(user.id, userId));
|
||||
|
||||
// Update user portfolio
|
||||
const [existingHolding] = await tx
|
||||
.select({ quantity: userPortfolio.quantity })
|
||||
.from(userPortfolio)
|
||||
|
|
@ -140,23 +148,20 @@ export async function POST({ params, request }) {
|
|||
});
|
||||
}
|
||||
|
||||
// Record transaction
|
||||
await tx.insert(transaction).values({
|
||||
userId,
|
||||
coinId: coinData.id,
|
||||
type: 'BUY',
|
||||
quantity: coinsBought.toString(),
|
||||
pricePerCoin: currentPrice.toString(),
|
||||
pricePerCoin: (totalCost / coinsBought).toString(),
|
||||
totalBaseCurrencyAmount: totalCost.toString()
|
||||
});
|
||||
|
||||
// Record price history
|
||||
await tx.insert(priceHistory).values({
|
||||
coinId: coinData.id,
|
||||
price: newPrice.toString()
|
||||
});
|
||||
|
||||
// Calculate and update 24h metrics
|
||||
const metrics = await calculate24hMetrics(coinData.id, newPrice);
|
||||
|
||||
await tx.update(coin)
|
||||
|
|
@ -178,11 +183,12 @@ export async function POST({ params, request }) {
|
|||
coinsBought,
|
||||
totalCost,
|
||||
newPrice,
|
||||
priceImpact,
|
||||
newBalance: userBalance - totalCost
|
||||
});
|
||||
|
||||
} else {
|
||||
// SELL logic
|
||||
// AMM SELL: amount = number of coins to sell
|
||||
const [userHolding] = await db
|
||||
.select({ quantity: userPortfolio.quantity })
|
||||
.from(userPortfolio)
|
||||
|
|
@ -196,7 +202,12 @@ export async function POST({ params, request }) {
|
|||
throw error(400, `Insufficient coins. You have ${userHolding ? Number(userHolding.quantity) : 0} but trying to sell ${amount}`);
|
||||
}
|
||||
|
||||
// Calculate price impact for selling
|
||||
// Allow more aggressive selling for rug pull simulation - prevent only mathematical breakdown
|
||||
const maxSellable = Math.floor(poolCoinAmount * 0.995); // 99.5% instead of 99%
|
||||
if (amount > maxSellable) {
|
||||
throw error(400, `Cannot sell more than 99.5% of pool tokens. Max sellable: ${maxSellable} tokens`);
|
||||
}
|
||||
|
||||
const k = poolCoinAmount * poolBaseCurrencyAmount;
|
||||
const newPoolCoin = poolCoinAmount + amount;
|
||||
const newPoolBaseCurrency = k / newPoolCoin;
|
||||
|
|
@ -204,10 +215,18 @@ export async function POST({ params, request }) {
|
|||
|
||||
totalCost = baseCurrencyReceived;
|
||||
newPrice = newPoolBaseCurrency / newPoolCoin;
|
||||
priceImpact = ((newPrice - currentPrice) / currentPrice) * 100;
|
||||
|
||||
// Lower minimum liquidity for more dramatic crashes
|
||||
if (newPoolBaseCurrency < 10) {
|
||||
throw error(400, `Trade would drain pool below minimum liquidity (*10 BUSS). Try selling fewer tokens.`);
|
||||
}
|
||||
|
||||
if (totalCost <= 0) {
|
||||
throw error(400, 'Trade amount results in zero base currency received');
|
||||
}
|
||||
|
||||
// Execute sell transaction
|
||||
await db.transaction(async (tx) => {
|
||||
// Update user balance
|
||||
await tx.update(user)
|
||||
.set({
|
||||
baseCurrencyBalance: (userBalance + totalCost).toString(),
|
||||
|
|
@ -215,9 +234,8 @@ export async function POST({ params, request }) {
|
|||
})
|
||||
.where(eq(user.id, userId));
|
||||
|
||||
// Update user portfolio
|
||||
const newQuantity = Number(userHolding.quantity) - amount;
|
||||
if (newQuantity > 0) {
|
||||
if (newQuantity > 0.000001) {
|
||||
await tx.update(userPortfolio)
|
||||
.set({
|
||||
quantity: newQuantity.toString(),
|
||||
|
|
@ -235,23 +253,20 @@ export async function POST({ params, request }) {
|
|||
));
|
||||
}
|
||||
|
||||
// Record transaction
|
||||
await tx.insert(transaction).values({
|
||||
userId,
|
||||
coinId: coinData.id,
|
||||
type: 'SELL',
|
||||
quantity: amount.toString(),
|
||||
pricePerCoin: currentPrice.toString(),
|
||||
pricePerCoin: (totalCost / amount).toString(),
|
||||
totalBaseCurrencyAmount: totalCost.toString()
|
||||
});
|
||||
|
||||
// Record price history
|
||||
await tx.insert(priceHistory).values({
|
||||
coinId: coinData.id,
|
||||
price: newPrice.toString()
|
||||
});
|
||||
|
||||
// Calculate and update 24h metrics - SINGLE coin table update
|
||||
const metrics = await calculate24hMetrics(coinData.id, newPrice);
|
||||
|
||||
await tx.update(coin)
|
||||
|
|
@ -273,6 +288,7 @@ export async function POST({ params, request }) {
|
|||
coinsSold: amount,
|
||||
totalReceived: totalCost,
|
||||
newPrice,
|
||||
priceImpact,
|
||||
newBalance: userBalance + totalCost
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -115,25 +115,12 @@ export async function POST({ request }) {
|
|||
|
||||
createdCoin = newCoin;
|
||||
|
||||
await tx.insert(userPortfolio).values({
|
||||
userId,
|
||||
coinId: newCoin.id,
|
||||
quantity: FIXED_SUPPLY.toString()
|
||||
});
|
||||
|
||||
await tx.insert(priceHistory).values({
|
||||
coinId: newCoin.id,
|
||||
price: STARTING_PRICE.toString()
|
||||
});
|
||||
|
||||
await tx.insert(transaction).values({
|
||||
userId,
|
||||
coinId: newCoin.id,
|
||||
type: 'BUY',
|
||||
quantity: FIXED_SUPPLY.toString(),
|
||||
pricePerCoin: STARTING_PRICE.toString(),
|
||||
totalBaseCurrencyAmount: (FIXED_SUPPLY * STARTING_PRICE).toString()
|
||||
});
|
||||
});
|
||||
|
||||
return json({
|
||||
|
|
@ -147,6 +134,7 @@ export async function POST({ request }) {
|
|||
feePaid: CREATION_FEE,
|
||||
liquidityDeposited: INITIAL_LIQUIDITY,
|
||||
initialPrice: STARTING_PRICE,
|
||||
supply: FIXED_SUPPLY
|
||||
supply: FIXED_SUPPLY,
|
||||
message: "Coin created! All tokens are in the liquidity pool. Buy some if you want to hold them."
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -112,7 +112,7 @@
|
|||
function generateVolumeData(candlestickData: any[], volumeData: any[]) {
|
||||
return candlestickData.map((candle, index) => {
|
||||
// Find corresponding volume data for this time period
|
||||
const volumePoint = volumeData.find(v => v.time === candle.time);
|
||||
const volumePoint = volumeData.find((v) => v.time === candle.time);
|
||||
const volume = volumePoint ? volumePoint.volume : 0;
|
||||
|
||||
return {
|
||||
|
|
@ -179,10 +179,14 @@
|
|||
priceFormat: { type: 'price', precision: 8, minMove: 0.00000001 }
|
||||
});
|
||||
|
||||
const volumeSeries = chart.addSeries(HistogramSeries, {
|
||||
priceFormat: { type: 'volume' },
|
||||
priceScaleId: 'volume'
|
||||
}, 1);
|
||||
const volumeSeries = chart.addSeries(
|
||||
HistogramSeries,
|
||||
{
|
||||
priceFormat: { type: 'volume' },
|
||||
priceScaleId: 'volume'
|
||||
},
|
||||
1
|
||||
);
|
||||
|
||||
const processedChartData = chartData.map((candle) => {
|
||||
if (candle.open === candle.close) {
|
||||
|
|
@ -224,7 +228,9 @@
|
|||
});
|
||||
|
||||
function formatPrice(price: number): string {
|
||||
if (price < 0.01) {
|
||||
if (price < 0.000001) {
|
||||
return price.toFixed(8);
|
||||
} else if (price < 0.01) {
|
||||
return price.toFixed(6);
|
||||
} else if (price < 1) {
|
||||
return price.toFixed(4);
|
||||
|
|
@ -234,17 +240,21 @@
|
|||
}
|
||||
|
||||
function formatMarketCap(value: number): string {
|
||||
if (value >= 1e9) return `$${(value / 1e9).toFixed(2)}B`;
|
||||
if (value >= 1e6) return `$${(value / 1e6).toFixed(2)}M`;
|
||||
if (value >= 1e3) return `$${(value / 1e3).toFixed(2)}K`;
|
||||
return `$${value.toFixed(2)}`;
|
||||
const num = Number(value);
|
||||
if (isNaN(num)) return '$0.00';
|
||||
if (num >= 1e9) return `$${(num / 1e9).toFixed(2)}B`;
|
||||
if (num >= 1e6) return `$${(num / 1e6).toFixed(2)}M`;
|
||||
if (num >= 1e3) return `$${(num / 1e3).toFixed(2)}K`;
|
||||
return `$${num.toFixed(2)}`;
|
||||
}
|
||||
|
||||
function formatSupply(value: number): string {
|
||||
if (value >= 1e9) return `${(value / 1e9).toFixed(2)}B`;
|
||||
if (value >= 1e6) return `${(value / 1e6).toFixed(2)}M`;
|
||||
if (value >= 1e3) return `${(value / 1e3).toFixed(2)}K`;
|
||||
return value.toLocaleString();
|
||||
const num = Number(value);
|
||||
if (isNaN(num)) return '0';
|
||||
if (num >= 1e9) return `${(num / 1e9).toFixed(2)}B`;
|
||||
if (num >= 1e6) return `${(num / 1e6).toFixed(2)}M`;
|
||||
if (num >= 1e3) return `${(num / 1e3).toFixed(2)}K`;
|
||||
return num.toLocaleString();
|
||||
}
|
||||
</script>
|
||||
|
||||
|
|
@ -314,7 +324,7 @@
|
|||
<TrendingDown class="h-4 w-4 text-red-500" />
|
||||
{/if}
|
||||
<Badge variant={coin.change24h >= 0 ? 'success' : 'destructive'}>
|
||||
{coin.change24h >= 0 ? '+' : ''}{coin.change24h.toFixed(2)}%
|
||||
{coin.change24h >= 0 ? '+' : ''}{Number(coin.change24h).toFixed(2)}%
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -327,7 +337,7 @@
|
|||
|
||||
<HoverCard.Root>
|
||||
<HoverCard.Trigger
|
||||
class="flex cursor-pointer items-center gap-2 rounded-sm underline-offset-4 hover:underline focus-visible:outline-2 focus-visible:outline-offset-8"
|
||||
class="flex cursor-pointer items-center gap-1 rounded-sm underline-offset-4 hover:underline focus-visible:outline-2 focus-visible:outline-offset-8"
|
||||
onclick={() => goto(`/user/${coin.creatorId}`)}
|
||||
>
|
||||
<Avatar.Root class="h-4 w-4">
|
||||
|
|
@ -411,7 +421,7 @@
|
|||
<Card.Title>Trade {coin.symbol}</Card.Title>
|
||||
{#if userHolding > 0}
|
||||
<p class="text-muted-foreground text-sm">
|
||||
You own: {userHolding.toFixed(2)}
|
||||
You own: {formatSupply(userHolding)}
|
||||
{coin.symbol}
|
||||
</p>
|
||||
{/if}
|
||||
|
|
@ -465,9 +475,9 @@
|
|||
</div>
|
||||
<div class="flex justify-between">
|
||||
<span class="text-muted-foreground text-sm">Base Currency:</span>
|
||||
<span class="font-mono text-sm"
|
||||
>${coin.poolBaseCurrencyAmount.toLocaleString()}</span
|
||||
>
|
||||
<span class="font-mono text-sm">
|
||||
${Number(coin.poolBaseCurrencyAmount).toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -476,13 +486,13 @@
|
|||
<div class="space-y-2">
|
||||
<div class="flex justify-between">
|
||||
<span class="text-muted-foreground text-sm">Total Liquidity:</span>
|
||||
<span class="font-mono text-sm"
|
||||
>${(coin.poolBaseCurrencyAmount * 2).toLocaleString()}</span
|
||||
>
|
||||
<span class="font-mono text-sm">
|
||||
${(Number(coin.poolBaseCurrencyAmount) * 2).toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex justify-between">
|
||||
<span class="text-muted-foreground text-sm">Price Impact:</span>
|
||||
<Badge variant="success" class="text-xs">Low</Badge>
|
||||
<span class="text-muted-foreground text-sm">Current Price:</span>
|
||||
<span class="font-mono text-sm">${formatPrice(coin.currentPrice)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -549,7 +559,7 @@
|
|||
<TrendingDown class="h-4 w-4 text-red-500" />
|
||||
{/if}
|
||||
<Badge variant={coin.change24h >= 0 ? 'success' : 'destructive'} class="text-sm">
|
||||
{coin.change24h >= 0 ? '+' : ''}{coin.change24h.toFixed(2)}%
|
||||
{coin.change24h >= 0 ? '+' : ''}{Number(coin.change24h).toFixed(2)}%
|
||||
</Badge>
|
||||
</div>
|
||||
</Card.Content>
|
||||
|
|
|
|||
Reference in a new issue