Skip to content

Commit

Permalink
test: new filters and ordering
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaelcr committed Feb 27, 2023
1 parent ce568a3 commit a851568
Show file tree
Hide file tree
Showing 7 changed files with 675 additions and 378 deletions.
9 changes: 4 additions & 5 deletions src/api/routes/inscriptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Value } from '@sinclair/typebox/value';
import { FastifyPluginCallback } from 'fastify';
import { Server } from 'http';
import {
BitcoinAddressParam,
AddressParam,
BlockHeightParam,
InscriptionResponse,
InscriptionIdParam,
Expand All @@ -27,7 +27,6 @@ import {
parseDbInscriptions,
parseDbInscription,
hexToBuffer,
normalizeHashString,
} from '../util/helpers';

const BlockHashParamCType = TypeCompiler.Compile(BlockHashParam);
Expand All @@ -48,7 +47,7 @@ export const InscriptionRoutes: FastifyPluginCallback<
querystring: Type.Object({
genesis_block: Type.Optional(Type.Union([BlockHashParam, BlockHeightParam])),
output: Type.Optional(OutputParam),
address: Type.Optional(BitcoinAddressParam),
address: Type.Optional(AddressParam),
mime_type: Type.Optional(Type.Array(MimeTypeParam)),
rarity: Type.Optional(SatoshiRarityParam),
// Pagination
Expand All @@ -68,7 +67,7 @@ export const InscriptionRoutes: FastifyPluginCallback<
const limit = request.query.limit ?? DEFAULT_API_LIMIT;
const offset = request.query.offset ?? 0;
const genBlockArg = BlockHashParamCType.Check(request.query.genesis_block)
? { genesis_block_hash: normalizeHashString(request.query.genesis_block) as string }
? { genesis_block_hash: request.query.genesis_block }
: BlockHeightParamCType.Check(request.query.genesis_block)
? { genesis_block_height: request.query.genesis_block }
: {};
Expand Down Expand Up @@ -114,7 +113,7 @@ export const InscriptionRoutes: FastifyPluginCallback<
limit: 1,
offset: 0,
});
if (inscription) {
if (inscription.total > 0) {
await reply.send(parseDbInscription(inscription.results[0]));
} else {
await reply.code(404).send(Value.Create(NotFoundResponse));
Expand Down
6 changes: 4 additions & 2 deletions src/api/types.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Static, TSchema, Type } from '@sinclair/typebox';
import { SatoshiRarity, SAT_SUPPLY } from './util/ordinal-satoshi';

export const BitcoinAddressParam = Type.RegEx(/^(bc1|[13])[a-zA-HJ-NP-Z0-9]{25,39}$/, {
export const AddressParam = Type.String({
title: 'Address',
description: 'Bitcoin address',
examples: ['bc1p8aq8s3z9xl87e74twfk93mljxq6alv4a79yheadx33t9np4g2wkqqt8kc5'],
Expand Down Expand Up @@ -45,7 +45,7 @@ export const SatoshiRarityParam = Type.Enum(SatoshiRarity, {
examples: ['uncommon'],
});

export const OutputParam = Type.RegEx(/^[a-fA-F0-9]{64}\:[0-9]+$/, {
export const OutputParam = Type.RegEx(/^[a-fA-F0-9]{64}:[0-9]+$/, {
title: 'Transaction Output',
description: 'An UTXO for a Bitcoin transaction',
examples: ['8f46f0d4ef685e650727e6faf7e30f23b851a7709714ec774f7909b3fb5e604c:0'],
Expand Down Expand Up @@ -101,6 +101,8 @@ export const InscriptionResponse = Type.Object({
location: Type.String(),
output: Type.String(),
offset: Type.String(),
sat_ordinal: Type.String(),
sat_rarity: Type.String(),
mime_type: Type.String(),
content_type: Type.String(),
content_length: Type.Integer(),
Expand Down
22 changes: 2 additions & 20 deletions src/api/util/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ export function parseDbInscriptions(
location: `${i.output}:${i.offset}`,
output: i.output,
offset: i.offset.toString(),
sat_ordinal: i.sat_ordinal.toString(),
sat_rarity: i.sat_rarity,
mime_type: i.mime_type,
content_type: i.content_type,
content_length: i.content_length,
Expand Down Expand Up @@ -44,23 +46,3 @@ export function hexToBuffer(hex: string): Buffer {
}

export const has0xPrefix = (id: string) => id.substr(0, 2).toLowerCase() === '0x';

/**
* Check if the input is a valid 32-byte hex string. If valid, returns a
* lowercase and 0x-prefixed hex string. If invalid, returns false.
*/
export function normalizeHashString(input: string): string | false {
if (typeof input !== 'string') {
return false;
}
let hashBuffer: Buffer | undefined;
if (input.length === 66 && has0xPrefix(input)) {
hashBuffer = Buffer.from(input.slice(2), 'hex');
} else if (input.length === 64) {
hashBuffer = Buffer.from(input, 'hex');
}
if (hashBuffer === undefined || hashBuffer.length !== 32) {
return false;
}
return `0x${hashBuffer.toString('hex')}`;
}
4 changes: 4 additions & 0 deletions src/bitcoin/inscriptions-importer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ export class InscriptionsImporter {
offset: 0n,
value: btcToSats(tx.vout[0].value),
timestamp: block.time,
sat_ordinal: 257418248345364n,
sat_rarity: 'common',
genesis: true,
current: true,
},
Expand Down Expand Up @@ -102,6 +104,8 @@ export class InscriptionsImporter {
offset: offset,
value: btcToSats(vout.value),
timestamp: block.time,
sat_ordinal: 257418248345364n,
sat_rarity: 'common',
genesis: false,
current: true,
},
Expand Down
2 changes: 1 addition & 1 deletion src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import pino from 'pino';

export const PINO_CONFIG = {
name: 'stx-btc-api',
name: 'ordinals-api',
level: 'info',
timestamp: pino.stdTimeFunctions.isoTime,
formatters: {
Expand Down
3 changes: 2 additions & 1 deletion src/pg/pg-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ export class PgStore extends BasePgStore {
}): Promise<DbPaginatedResult<DbFullyLocatedInscriptionResult>> {
// Sanitize ordering args because we'll use `unsafe` to concatenate them into the query.
let orderBy = 'gen.block_height';
switch (orderBy) {
switch (args.order_by) {
case OrderBy.ordinal:
orderBy = 'loc.sat_ordinal';
break;
Expand Down Expand Up @@ -193,6 +193,7 @@ export class PgStore extends BasePgStore {
: this.sql``
}
${args.output ? this.sql`AND loc.output = ${args.output}` : this.sql``}
${args.sat_rarity ? this.sql`AND loc.sat_rarity = ${args.sat_rarity}` : this.sql``}
ORDER BY ${this.sql.unsafe(orderBy)} ${this.sql.unsafe(order)}
LIMIT ${args.limit}
OFFSET ${args.offset}
Expand Down
Loading

0 comments on commit a851568

Please sign in to comment.