Skip to content

Commit

Permalink
fix: stamps created by me in wallet
Browse files Browse the repository at this point in the history
  • Loading branch information
reinamora137 committed Dec 16, 2024
1 parent ea2ddb8 commit 5e763d9
Show file tree
Hide file tree
Showing 5 changed files with 89 additions and 59 deletions.
56 changes: 12 additions & 44 deletions routes/api/v2/src20/tick/[tick]/mintData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,54 +11,22 @@ export const handler: Handlers = {
throw new Error("Tick parameter is required");
}

// Debug logging with structured logger
logger.debug("stamps", {
message: "Processing tick request",
data: {
originalTick: tick,
},
});

const decodedTick = decodeURIComponent(tick);
logger.debug("stamps", {
message: "Decoded tick",
data: {
decodedTick,
},
});

const normalizedTick = convertEmojiToTick(decodedTick);
logger.debug("stamps", {
message: "Normalized tick",
data: {
normalizedTick,
},
});

// Fetch mint progress data with normalized tick
const mintStatus = await Src20Controller.handleSrc20MintProgressRequest(
normalizedTick,
);
logger.debug("stamps", {
message: "Mint status retrieved",
data: {
mintStatus,
},
});

// Fetch holders count with normalized tick
const balanceData = await Src20Controller.handleSrc20BalanceRequest({
tick: normalizedTick,
includePagination: true,
limit: 1,
page: 1,
});
const holders = balanceData.total || 0;
const normalizedTick = convertEmojiToTick(decodeURIComponent(tick));

const [mintStatus, balanceData] = await Promise.all([
Src20Controller.handleSrc20MintProgressRequest(normalizedTick),
Src20Controller.handleSrc20BalanceRequest({
tick: normalizedTick,
includePagination: true,
limit: 1,
page: 1,
}),
]);

return new Response(
JSON.stringify({
mintStatus,
holders,
holders: balanceData.total || 0,
}),
{
status: 200,
Expand Down
30 changes: 21 additions & 9 deletions routes/wallet/[address].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ import { Handlers } from "$fresh/server.ts";
import WalletHeader from "$islands/Wallet/details/WalletHeader.tsx";
import WalletDetails from "$islands/Wallet/details/WalletDetails.tsx";
import WalletContent from "$islands/Wallet/details/WalletContent.tsx";
import { serverConfig } from "$server/config/config.ts";
import { Dispenser, WalletData, WalletPageProps } from "$lib/types/index.d.ts";
import { WalletData, WalletPageProps } from "$lib/types/index.d.ts";
import { StampController } from "$server/controller/stampController.ts";
import { getBTCBalanceInfo } from "$lib/utils/balanceUtils.ts";
import { Src20Controller } from "$server/controller/src20Controller.ts";

export const handler: Handlers = {
async GET(req, ctx) {
Expand Down Expand Up @@ -38,13 +38,20 @@ export const handler: Handlers = {
btcInfoResponse,
openDispensersResponse,
closedDispensersResponse,
stampsCreatedCount,
] = await Promise.allSettled([
fetch(
`${url.origin}/api/v2/stamps/balance/${address}?page=${stampsParams.page}&limit=${stampsParams.limit}`,
).then((res) => res.json()),
fetch(
`${url.origin}/api/v2/src20/balance/${address}?page=${src20Params.page}&limit=${src20Params.limit}`,
).then((res) => res.json()),
StampController.getStampBalancesByAddress(
address,
stampsParams.limit,
stampsParams.page,
),
Src20Controller.handleSrc20BalanceRequest({
address,
includePagination: true,
limit: src20Params.limit,
page: src20Params.page,
includeMintData: true,
}),
getBTCBalanceInfo(address, {
includeUSD: true,
apiBaseUrl: url.origin,
Expand All @@ -61,6 +68,7 @@ export const handler: Handlers = {
closedListingsParams.page || 1,
"closed",
),
StampController.getStampsCreatedCount(address),
]);

const stampsData = stampsResponse.status === "fulfilled"
Expand Down Expand Up @@ -157,6 +165,9 @@ export const handler: Handlers = {
walletData,
stampsTotal: stampsData.total || 0,
src20Total: src20Data.total || 0,
stampsCreated: stampsCreatedCount.status === "fulfilled"
? stampsCreatedCount.value
: 0,
anchor: anchor,
});
} catch (error) {
Expand Down Expand Up @@ -196,6 +207,7 @@ export const handler: Handlers = {
},
stampsTotal: 0,
src20Total: 0,
stampsCreated: 0,
});
}
},
Expand All @@ -214,7 +226,7 @@ export default function Wallet(props: WalletPageProps) {
walletData={data.walletData}
stampsTotal={data.stampsTotal}
src20Total={data.src20Total}
stampsCreated={0}
stampsCreated={data.stampsCreated}
setShowItem={() => {}}
/>
<WalletContent
Expand Down
15 changes: 15 additions & 0 deletions server/controller/stampController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -805,4 +805,19 @@ export class StampController {
throw error;
}
}

static async getStampsCreatedCount(address: string): Promise<number> {
try {
// Use a direct count query instead of getStamps
const result = await StampRepository.getStampsCreatedCount(address);
return result.total || 0;
} catch (error) {
logger.error("stamps", {
message: "Error getting stamps created count",
error: error instanceof Error ? error.message : String(error),
address
});
return 0;
}
}
}
33 changes: 33 additions & 0 deletions server/database/stampRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,7 @@ export class StampRepository {
collectionId?: string | string[];
filterBy?: STAMP_FILTER_TYPES[];
suffixFilters?: STAMP_SUFFIX_FILTERS[];
creatorAddress?: string;
}) {
const {
type = "stamps",
Expand All @@ -242,6 +243,7 @@ export class StampRepository {
collectionId,
filterBy,
suffixFilters,
creatorAddress,
} = options;

const whereConditions: string[] = [];
Expand All @@ -259,6 +261,11 @@ export class StampRepository {
suffixFilters
);

if (creatorAddress) {
whereConditions.push("st.creator = ?");
queryParams.push(creatorAddress);
}

const whereClause =
whereConditions.length > 0
? `WHERE ${whereConditions.join(" AND ")}`
Expand Down Expand Up @@ -481,6 +488,7 @@ export class StampRepository {
skipTotalCount?: boolean;
selectColumns?: string[];
includeSecondary?: boolean;
creatorAddress?: string;
}) {
const queryOptions = {
limit: SMALL_LIMIT,
Expand Down Expand Up @@ -518,6 +526,7 @@ export class StampRepository {
skipTotalCount = false,
selectColumns,
includeSecondary = true,
creatorAddress,
} = queryOptions;

const whereConditions: string[] = [];
Expand All @@ -535,6 +544,11 @@ export class StampRepository {
suffixFilters
);

if (creatorAddress) {
whereConditions.push("st.creator = ?");
queryParams.push(creatorAddress);
}

// Core stamp fields that are always needed
const coreColumns = `
st.stamp,
Expand Down Expand Up @@ -919,4 +933,23 @@ export class StampRepository {
};
}
}

static async getStampsCreatedCount(address: string): Promise<{ total: number }> {
const query = `
SELECT COUNT(DISTINCT st.stamp) as total
FROM ${STAMP_TABLE} st
WHERE st.creator = ?
AND st.ident IN ('STAMP', 'SRC-721')
`;

const result = await dbManager.executeQueryWithCache(
query,
[address],
1000 * 60 * 3 // 3 minute cache
);

return {
total: result.rows[0]?.total || 0
};
}
}
14 changes: 8 additions & 6 deletions server/services/stampService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ export class StampService {
groupBySubquery?: boolean;
skipTotalCount?: boolean;
cacheType?: RouteType;
creatorAddress?: string;
}) {
// Create a new options object instead of modifying the input
const queryOptions = {
Expand Down Expand Up @@ -227,21 +228,22 @@ export class StampService {
}));
}

static async getRecentSales(page?: number, limit?: number) { // FIXME: this is temoprorary until we add recent sales in db
static async getRecentSales(page?: number, limit?: number) {
// Fetch dispense events and extract unique asset values
const dispenseEvents = await XcpManager.fetchDispenseEvents(500); // Fetch recent dispense events
const uniqueAssets = [
...new Set(dispenseEvents.map((event) => event.params.asset)),
];
const dispenseEvents = await XcpManager.fetchDispenseEvents(500);
const uniqueAssets = [...new Set(dispenseEvents.map((event) => event.params.asset))];

const stampDetails = await this.getStamps({
identifier: uniqueAssets,
allColumns: false,
noPagination: true,
type: "all",
skipTotalCount: true,
creatorAddress: undefined
});

const stampDetailsMap = new Map(
stampDetails.stamps.map((stamp) => [stamp.cpid, stamp]),
stampDetails.stamps.map((stamp) => [stamp.cpid, stamp])
);

const allRecentSales = dispenseEvents
Expand Down

0 comments on commit 5e763d9

Please sign in to comment.