mirror of
https://github.com/alexgo-io/bitcoin-indexer.git
synced 2026-01-12 16:52:57 +08:00
feat: predicate schemas
This commit is contained in:
@@ -3,8 +3,9 @@
|
||||
"version": "1.0.0",
|
||||
"description": "TS client for Chainhook",
|
||||
"main": "./dist/index.js",
|
||||
"typings": "./dist/index.d.ts",
|
||||
"scripts": {
|
||||
"build": "tsc --project tsconfig.build.json",
|
||||
"build": "rimraf ./dist && tsc --project tsconfig.build.json",
|
||||
"test": "jest"
|
||||
},
|
||||
"repository": {
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import { Type, TypeBoxTypeProvider } from '@fastify/type-provider-typebox';
|
||||
import Fastify, {
|
||||
FastifyInstance,
|
||||
FastifyPluginCallback,
|
||||
FastifyReply,
|
||||
FastifyRequest,
|
||||
} from 'fastify';
|
||||
import { Server } from 'http';
|
||||
import { request } from 'undici';
|
||||
import { logger, PINO_CONFIG } from './util/logger';
|
||||
import { timeout } from './util/helpers';
|
||||
import { Payload, PayloadSchema } from './schemas';
|
||||
import { Predicate, ThenThat } from './schemas/predicate';
|
||||
|
||||
export type OnEventCallback = (uuid: string, payload: Payload) => Promise<void>;
|
||||
|
||||
type ServerOptions = {
|
||||
server: {
|
||||
host: string;
|
||||
port: number;
|
||||
auth_token: string;
|
||||
external_hostname: string;
|
||||
};
|
||||
chainhook_node: {
|
||||
hostname: string;
|
||||
port: number;
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Starts the chainhook event server.
|
||||
* @returns Fastify instance
|
||||
*/
|
||||
export async function startServer(
|
||||
opts: ServerOptions,
|
||||
predicates: [Predicate],
|
||||
callback: OnEventCallback
|
||||
) {
|
||||
const base_path = `http://${opts.chainhook_node.hostname}:${opts.chainhook_node.port}`;
|
||||
|
||||
async function waitForNode(this: FastifyInstance) {
|
||||
logger.info(`EventServer connecting to chainhook node...`);
|
||||
while (true) {
|
||||
try {
|
||||
await request(`${base_path}/ping`, { method: 'GET', throwOnError: true });
|
||||
break;
|
||||
} catch (error) {
|
||||
logger.error(error, 'Chainhook node not available, retrying...');
|
||||
await timeout(1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function registerPredicates(this: FastifyInstance) {
|
||||
logger.info(predicates, `EventServer registering predicates on ${base_path}...`);
|
||||
for (const predicate of predicates) {
|
||||
const thenThat: ThenThat = {
|
||||
http_post: {
|
||||
url: `http://${opts.server.external_hostname}/chainhook/${predicate.uuid}`,
|
||||
authorization_header: `Bearer ${opts.server.auth_token}`,
|
||||
},
|
||||
};
|
||||
try {
|
||||
const body = predicate;
|
||||
if ('mainnet' in body.networks) body.networks.mainnet.then_that = thenThat;
|
||||
if ('testnet' in body.networks) body.networks.testnet.then_that = thenThat;
|
||||
await request(`${base_path}/v1/chainhooks`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
headers: { 'content-type': 'application/json' },
|
||||
throwOnError: true,
|
||||
});
|
||||
logger.info(`EventServer registered '${predicate.name}' predicate (${predicate.uuid})`);
|
||||
} catch (error) {
|
||||
logger.error(error, `EventServer unable to register predicate`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function removePredicates(this: FastifyInstance) {
|
||||
logger.info(`EventServer closing predicates...`);
|
||||
for (const predicate of predicates) {
|
||||
try {
|
||||
await request(`${base_path}/v1/chainhooks/${predicate.chain}/${predicate.uuid}`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
throwOnError: true,
|
||||
});
|
||||
logger.info(`EventServer removed '${predicate.name}' predicate (${predicate.uuid})`);
|
||||
} catch (error) {
|
||||
logger.error(error, `EventServer unable to deregister predicate`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function isEventAuthorized(request: FastifyRequest, reply: FastifyReply) {
|
||||
const authHeader = request.headers.authorization;
|
||||
if (authHeader && authHeader === `Bearer ${opts.server.auth_token}`) {
|
||||
return;
|
||||
}
|
||||
await reply.code(403).send();
|
||||
}
|
||||
|
||||
const EventServer: FastifyPluginCallback<Record<never, never>, Server, TypeBoxTypeProvider> = (
|
||||
fastify,
|
||||
options,
|
||||
done
|
||||
) => {
|
||||
fastify.addHook('preHandler', isEventAuthorized);
|
||||
fastify.post(
|
||||
'/chainhook/:uuid',
|
||||
{
|
||||
schema: {
|
||||
params: Type.Object({
|
||||
uuid: Type.String({ format: 'uuid' }),
|
||||
}),
|
||||
body: PayloadSchema,
|
||||
},
|
||||
},
|
||||
async (request, reply) => {
|
||||
try {
|
||||
await callback(request.params.uuid, request.body);
|
||||
} catch (error) {
|
||||
logger.error(error, `EventServer error processing payload`);
|
||||
await reply.code(422).send();
|
||||
}
|
||||
await reply.code(200).send();
|
||||
}
|
||||
);
|
||||
done();
|
||||
};
|
||||
|
||||
const fastify = Fastify({
|
||||
trustProxy: true,
|
||||
logger: PINO_CONFIG,
|
||||
pluginTimeout: 0, // Disable so ping can retry indefinitely
|
||||
bodyLimit: 41943040, // 40 MB
|
||||
}).withTypeProvider<TypeBoxTypeProvider>();
|
||||
|
||||
fastify.addHook('onReady', waitForNode);
|
||||
fastify.addHook('onReady', registerPredicates);
|
||||
fastify.addHook('onClose', removePredicates);
|
||||
await fastify.register(EventServer);
|
||||
|
||||
await fastify.listen({ host: opts.server.host, port: opts.server.port });
|
||||
return fastify;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import { BlockIdentifier, Nullable } from '..';
|
||||
import { Nullable, BlockIdentifier } from '../common';
|
||||
|
||||
const InscriptionRevealed = Type.Object({
|
||||
content_bytes: Type.String(),
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { Type } from '@sinclair/typebox';
|
||||
|
||||
export const BitcoinIfThisTxIdSchema = Type.Object({
|
||||
scope: Type.Literal('txid'),
|
||||
equals: Type.String(),
|
||||
});
|
||||
|
||||
export const BitcoinIfThisOpReturnStartsWithSchema = Type.Object({
|
||||
scope: Type.Literal('outputs'),
|
||||
op_return: Type.Object({
|
||||
starts_with: Type.String(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const BitcoinIfThisOpReturnEqualsSchema = Type.Object({
|
||||
scope: Type.Literal('outputs'),
|
||||
op_return: Type.Object({
|
||||
equals: Type.String(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const BitcoinIfThisOpReturnEndsWithSchema = Type.Object({
|
||||
scope: Type.Literal('outputs'),
|
||||
op_return: Type.Object({
|
||||
ends_with: Type.String(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const BitcoinIfThisP2PKHSchema = Type.Object({
|
||||
scope: Type.Literal('outputs'),
|
||||
p2pkh: Type.String(),
|
||||
});
|
||||
|
||||
export const BitcoinIfThisP2SHSchema = Type.Object({
|
||||
scope: Type.Literal('outputs'),
|
||||
p2sh: Type.String(),
|
||||
});
|
||||
|
||||
export const BitcoinIfThisP2WPKHSchema = Type.Object({
|
||||
scope: Type.Literal('outputs'),
|
||||
p2wpkh: Type.String(),
|
||||
});
|
||||
|
||||
export const BitcoinIfThisP2WSHSchema = Type.Object({
|
||||
scope: Type.Literal('outputs'),
|
||||
p2wsh: Type.String(),
|
||||
});
|
||||
|
||||
export const BitcoinIfThisStacksBlockCommittedSchema = Type.Object({
|
||||
scope: Type.Literal('stacks_protocol'),
|
||||
operation: Type.Literal('block_committed'),
|
||||
});
|
||||
|
||||
export const BitcoinIfThisStacksLeaderKeyRegisteredSchema = Type.Object({
|
||||
scope: Type.Literal('stacks_protocol'),
|
||||
operation: Type.Literal('leader_key_registered'),
|
||||
});
|
||||
|
||||
export const BitcoinIfThisStacksStxTransferredSchema = Type.Object({
|
||||
scope: Type.Literal('stacks_protocol'),
|
||||
operation: Type.Literal('stx_transfered'),
|
||||
});
|
||||
|
||||
export const BitcoinIfThisStacksStxLockedSchema = Type.Object({
|
||||
scope: Type.Literal('stacks_protocol'),
|
||||
operation: Type.Literal('stx_locked'),
|
||||
});
|
||||
|
||||
export const BitcoinIfThisOrdinalsFeedSchema = Type.Object({
|
||||
scope: Type.Literal('ordinals_protocol'),
|
||||
operation: Type.Literal('inscription_feed'),
|
||||
});
|
||||
12
components/client/typescript/src/schemas/common.ts
Normal file
12
components/client/typescript/src/schemas/common.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { TSchema, Type } from '@sinclair/typebox';
|
||||
|
||||
export const Nullable = <T extends TSchema>(type: T) => Type.Union([type, Type.Null()]);
|
||||
|
||||
export const BlockIdentifier = Type.Object({
|
||||
index: Type.Integer(),
|
||||
hash: Type.String(),
|
||||
});
|
||||
|
||||
export const TransactionIdentifier = Type.Object({
|
||||
hash: Type.String(),
|
||||
});
|
||||
@@ -1,59 +1,10 @@
|
||||
import { Static, TSchema, Type } from '@sinclair/typebox';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
import { StacksEvent } from './stacks';
|
||||
import { BitcoinEvent } from './bitcoin';
|
||||
|
||||
export const Nullable = <T extends TSchema>(type: T) => Type.Union([type, Type.Null()]);
|
||||
|
||||
export const BlockIdentifier = Type.Object({
|
||||
index: Type.Integer(),
|
||||
hash: Type.String(),
|
||||
});
|
||||
|
||||
export const TransactionIdentifier = Type.Object({
|
||||
hash: Type.String(),
|
||||
});
|
||||
import { IfThisSchema } from './predicate';
|
||||
|
||||
const EventArray = Type.Union([Type.Array(StacksEvent), Type.Array(BitcoinEvent)]);
|
||||
|
||||
export const IfThisSchema = Type.Object({
|
||||
scope: Type.String(),
|
||||
operation: Type.String(),
|
||||
});
|
||||
export type IfThis = Static<typeof IfThisSchema>;
|
||||
|
||||
export const ThenThatSchema = Type.Union([
|
||||
Type.Object({
|
||||
file_append: Type.Object({
|
||||
path: Type.String(),
|
||||
}),
|
||||
}),
|
||||
Type.Object({
|
||||
http_post: Type.Object({
|
||||
url: Type.String({ format: 'uri' }),
|
||||
authorization_header: Type.String(),
|
||||
}),
|
||||
}),
|
||||
]);
|
||||
|
||||
export const IfThisThenThatSchema = Type.Object({
|
||||
start_block: Type.Optional(Type.Integer()),
|
||||
end_block: Type.Optional(Type.Integer()),
|
||||
if_this: IfThisSchema,
|
||||
then_that: ThenThatSchema,
|
||||
});
|
||||
|
||||
export const PredicateSchema = Type.Object({
|
||||
uuid: Type.String({ format: 'uuid' }),
|
||||
name: Type.String(),
|
||||
version: Type.Integer(),
|
||||
chain: Type.String(),
|
||||
networks: Type.Object({
|
||||
mainnet: Type.Optional(IfThisThenThatSchema),
|
||||
testnet: Type.Optional(IfThisThenThatSchema),
|
||||
}),
|
||||
});
|
||||
export type Predicate = Static<typeof PredicateSchema>;
|
||||
|
||||
export const PayloadSchema = Type.Object({
|
||||
apply: EventArray,
|
||||
rollback: EventArray,
|
||||
|
||||
97
components/client/typescript/src/schemas/predicate.ts
Normal file
97
components/client/typescript/src/schemas/predicate.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
import {
|
||||
BitcoinIfThisTxIdSchema,
|
||||
BitcoinIfThisOpReturnStartsWithSchema,
|
||||
BitcoinIfThisOpReturnEqualsSchema,
|
||||
BitcoinIfThisOpReturnEndsWithSchema,
|
||||
BitcoinIfThisP2PKHSchema,
|
||||
BitcoinIfThisP2SHSchema,
|
||||
BitcoinIfThisP2WPKHSchema,
|
||||
BitcoinIfThisP2WSHSchema,
|
||||
BitcoinIfThisStacksBlockCommittedSchema,
|
||||
BitcoinIfThisStacksLeaderKeyRegisteredSchema,
|
||||
BitcoinIfThisStacksStxTransferredSchema,
|
||||
BitcoinIfThisStacksStxLockedSchema,
|
||||
BitcoinIfThisOrdinalsFeedSchema,
|
||||
} from './bitcoin/predicate';
|
||||
import {
|
||||
StacksIfThisTxIdSchema,
|
||||
StacksIfThisBlockHeightHigherThanSchema,
|
||||
StacksIfThisFtEventSchema,
|
||||
StacksIfThisNftEventSchema,
|
||||
StacksIfThisStxEventSchema,
|
||||
StacksIfThisPrintEventSchema,
|
||||
StacksIfThisContractCallSchema,
|
||||
StacksIfThisContractDeploymentSchema,
|
||||
StacksIfThisContractDeploymentTraitSchema,
|
||||
} from './stacks/predicate';
|
||||
|
||||
export const IfThisSchema = Type.Union([
|
||||
BitcoinIfThisTxIdSchema,
|
||||
BitcoinIfThisOpReturnStartsWithSchema,
|
||||
BitcoinIfThisOpReturnEqualsSchema,
|
||||
BitcoinIfThisOpReturnEndsWithSchema,
|
||||
BitcoinIfThisP2PKHSchema,
|
||||
BitcoinIfThisP2SHSchema,
|
||||
BitcoinIfThisP2WPKHSchema,
|
||||
BitcoinIfThisP2WSHSchema,
|
||||
BitcoinIfThisStacksBlockCommittedSchema,
|
||||
BitcoinIfThisStacksLeaderKeyRegisteredSchema,
|
||||
BitcoinIfThisStacksStxTransferredSchema,
|
||||
BitcoinIfThisStacksStxLockedSchema,
|
||||
BitcoinIfThisOrdinalsFeedSchema,
|
||||
StacksIfThisTxIdSchema,
|
||||
StacksIfThisBlockHeightHigherThanSchema,
|
||||
StacksIfThisFtEventSchema,
|
||||
StacksIfThisNftEventSchema,
|
||||
StacksIfThisStxEventSchema,
|
||||
StacksIfThisPrintEventSchema,
|
||||
StacksIfThisContractCallSchema,
|
||||
StacksIfThisContractDeploymentSchema,
|
||||
StacksIfThisContractDeploymentTraitSchema,
|
||||
]);
|
||||
export type IfThis = Static<typeof IfThisSchema>;
|
||||
|
||||
export const ThenThatSchema = Type.Union([
|
||||
Type.Object({
|
||||
file_append: Type.Object({
|
||||
path: Type.String(),
|
||||
}),
|
||||
}),
|
||||
Type.Object({
|
||||
http_post: Type.Object({
|
||||
url: Type.String({ format: 'uri' }),
|
||||
authorization_header: Type.String(),
|
||||
}),
|
||||
}),
|
||||
]);
|
||||
export type ThenThat = Static<typeof ThenThatSchema>;
|
||||
|
||||
export const IfThisThenThatSchema = Type.Object({
|
||||
start_block: Type.Optional(Type.Integer()),
|
||||
end_block: Type.Optional(Type.Integer()),
|
||||
expire_after_occurrence: Type.Optional(Type.Integer()),
|
||||
include_proof: Type.Optional(Type.Boolean()),
|
||||
include_inputs: Type.Optional(Type.Boolean()),
|
||||
include_outputs: Type.Optional(Type.Boolean()),
|
||||
include_witness: Type.Optional(Type.Boolean()),
|
||||
if_this: IfThisSchema,
|
||||
then_that: ThenThatSchema,
|
||||
});
|
||||
export type IfThisThenThat = Static<typeof IfThisThenThatSchema>;
|
||||
|
||||
export const PredicateSchema = Type.Object({
|
||||
uuid: Type.String({ format: 'uuid' }),
|
||||
name: Type.String(),
|
||||
version: Type.Integer(),
|
||||
chain: Type.String(),
|
||||
networks: Type.Union([
|
||||
Type.Object({
|
||||
mainnet: IfThisThenThatSchema,
|
||||
}),
|
||||
Type.Object({
|
||||
testnet: IfThisThenThatSchema,
|
||||
}),
|
||||
]),
|
||||
});
|
||||
export type Predicate = Static<typeof PredicateSchema>;
|
||||
@@ -16,7 +16,7 @@ const NftTransferEvent = Type.Object({
|
||||
raw_value: Type.String(),
|
||||
asset_identifier: Type.String(),
|
||||
recipient: Principal,
|
||||
sender: Principal
|
||||
sender: Principal,
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -35,7 +35,7 @@ const FtTransferEvent = Type.Object({
|
||||
amount: Type.String(),
|
||||
asset_identifier: Type.String(),
|
||||
recipient: Principal,
|
||||
sender: Principal
|
||||
sender: Principal,
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -62,7 +62,7 @@ const SmartContractEvent = Type.Object({
|
||||
data: Type.Object({
|
||||
contract_identifier: Principal,
|
||||
raw_value: Type.String(),
|
||||
topic: Type.String()
|
||||
topic: Type.String(),
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -72,7 +72,7 @@ const StxTransferEvent = Type.Object({
|
||||
amount: Type.String(),
|
||||
sender: Principal,
|
||||
recipient: Principal,
|
||||
})
|
||||
}),
|
||||
});
|
||||
|
||||
const StxMintEvent = Type.Object({
|
||||
@@ -80,7 +80,7 @@ const StxMintEvent = Type.Object({
|
||||
data: Type.Object({
|
||||
amount: Type.String(),
|
||||
recipient: Principal,
|
||||
})
|
||||
}),
|
||||
});
|
||||
|
||||
const StxLockEvent = Type.Object({
|
||||
@@ -89,7 +89,7 @@ const StxLockEvent = Type.Object({
|
||||
locked_amount: Type.String(),
|
||||
unlock_height: Type.String(),
|
||||
locked_address: Type.String(),
|
||||
})
|
||||
}),
|
||||
});
|
||||
|
||||
const StxBurnEvent = Type.Object({
|
||||
@@ -97,7 +97,7 @@ const StxBurnEvent = Type.Object({
|
||||
data: Type.Object({
|
||||
amount: Type.String(),
|
||||
sender: Principal,
|
||||
})
|
||||
}),
|
||||
});
|
||||
|
||||
const DataVarSetEvent = Type.Object({
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import { BlockIdentifier, Nullable, TransactionIdentifier } from '..';
|
||||
import { Event } from './events';
|
||||
import { Kind } from './kind';
|
||||
import { BlockIdentifier, Nullable, TransactionIdentifier } from '../common';
|
||||
|
||||
export const Principal = Type.String();
|
||||
|
||||
@@ -11,43 +11,45 @@ const OperationIdentifier = Type.Object({
|
||||
|
||||
const Transaction = Type.Object({
|
||||
transaction_identifier: TransactionIdentifier,
|
||||
operations: Type.Array(Type.Object({
|
||||
account: Type.Object({
|
||||
address: Type.String(),
|
||||
sub_account: Type.Optional(Type.String()),
|
||||
}),
|
||||
amount: Type.Optional(
|
||||
Type.Object({
|
||||
currency: Type.Object({
|
||||
decimals: Type.Integer(),
|
||||
symbol: Type.String(),
|
||||
metadata: Type.Object({
|
||||
asset_class_identifier: Type.String(),
|
||||
asset_identifier: Nullable(Type.String()),
|
||||
standard: Type.String(),
|
||||
}),
|
||||
}),
|
||||
value: Type.Integer(),
|
||||
})
|
||||
),
|
||||
metadata: Type.Optional(
|
||||
Type.Object({
|
||||
public_key: Type.Optional(
|
||||
Type.Object({
|
||||
hex_bypes: Type.Optional(Type.String()),
|
||||
curve_type: Type.String(),
|
||||
})
|
||||
),
|
||||
code: Type.Optional(Type.String()),
|
||||
method_name: Type.Optional(Type.String()),
|
||||
args: Type.Optional(Type.String()),
|
||||
operations: Type.Array(
|
||||
Type.Object({
|
||||
account: Type.Object({
|
||||
address: Type.String(),
|
||||
sub_account: Type.Optional(Type.String()),
|
||||
}),
|
||||
),
|
||||
operation_identifier: OperationIdentifier,
|
||||
related_operations: Type.Optional(Type.Array(OperationIdentifier)),
|
||||
status: Type.Optional(Type.Literal('SUCCESS')),
|
||||
type: Type.Union([Type.Literal('CREDIT'), Type.Literal('DEBIT'), Type.Literal('LOCK')]),
|
||||
})),
|
||||
amount: Type.Optional(
|
||||
Type.Object({
|
||||
currency: Type.Object({
|
||||
decimals: Type.Integer(),
|
||||
symbol: Type.String(),
|
||||
metadata: Type.Object({
|
||||
asset_class_identifier: Type.String(),
|
||||
asset_identifier: Nullable(Type.String()),
|
||||
standard: Type.String(),
|
||||
}),
|
||||
}),
|
||||
value: Type.Integer(),
|
||||
})
|
||||
),
|
||||
metadata: Type.Optional(
|
||||
Type.Object({
|
||||
public_key: Type.Optional(
|
||||
Type.Object({
|
||||
hex_bypes: Type.Optional(Type.String()),
|
||||
curve_type: Type.String(),
|
||||
})
|
||||
),
|
||||
code: Type.Optional(Type.String()),
|
||||
method_name: Type.Optional(Type.String()),
|
||||
args: Type.Optional(Type.String()),
|
||||
})
|
||||
),
|
||||
operation_identifier: OperationIdentifier,
|
||||
related_operations: Type.Optional(Type.Array(OperationIdentifier)),
|
||||
status: Type.Optional(Type.Literal('SUCCESS')),
|
||||
type: Type.Union([Type.Literal('CREDIT'), Type.Literal('DEBIT'), Type.Literal('LOCK')]),
|
||||
})
|
||||
),
|
||||
metadata: Type.Object({
|
||||
description: Type.String(),
|
||||
execution_cost: Type.Optional(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import { Principal } from ".";
|
||||
import { Principal } from '.';
|
||||
|
||||
const ContractCall = Type.Object({
|
||||
type: Type.Literal('ContractCall'),
|
||||
@@ -19,11 +19,11 @@ const ContractDeployment = Type.Object({
|
||||
});
|
||||
|
||||
const Coinbase = Type.Object({
|
||||
type: Type.Literal('Coinbase')
|
||||
type: Type.Literal('Coinbase'),
|
||||
});
|
||||
|
||||
const NativeTokenTransfer = Type.Object({
|
||||
type: Type.Literal('NativeTokenTransfer')
|
||||
type: Type.Literal('NativeTokenTransfer'),
|
||||
});
|
||||
|
||||
const BitcoinOpStackStx = Type.Object({
|
||||
@@ -47,7 +47,7 @@ const BitcoinOpDelegateStackStx = Type.Object({
|
||||
});
|
||||
|
||||
const Unsupported = Type.Object({
|
||||
type: Type.Literal('Unsupported')
|
||||
type: Type.Literal('Unsupported'),
|
||||
});
|
||||
|
||||
export const Kind = Type.Union([
|
||||
@@ -57,5 +57,5 @@ export const Kind = Type.Union([
|
||||
NativeTokenTransfer,
|
||||
BitcoinOpStackStx,
|
||||
BitcoinOpDelegateStackStx,
|
||||
Unsupported
|
||||
Unsupported,
|
||||
]);
|
||||
|
||||
51
components/client/typescript/src/schemas/stacks/predicate.ts
Normal file
51
components/client/typescript/src/schemas/stacks/predicate.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { Type } from '@sinclair/typebox';
|
||||
|
||||
export const StacksIfThisTxIdSchema = Type.Object({
|
||||
scope: Type.Literal('txid'),
|
||||
equals: Type.String(),
|
||||
});
|
||||
|
||||
export const StacksIfThisBlockHeightHigherThanSchema = Type.Object({
|
||||
scope: Type.Literal('block_height'),
|
||||
higher_than: Type.Integer(),
|
||||
});
|
||||
|
||||
export const StacksIfThisFtEventSchema = Type.Object({
|
||||
scope: Type.Literal('ft_event'),
|
||||
asset_identifier: Type.String(),
|
||||
actions: Type.Array(Type.String()),
|
||||
});
|
||||
|
||||
export const StacksIfThisNftEventSchema = Type.Object({
|
||||
scope: Type.Literal('nft_event'),
|
||||
asset_identifier: Type.String(),
|
||||
actions: Type.Array(Type.String()),
|
||||
});
|
||||
|
||||
export const StacksIfThisStxEventSchema = Type.Object({
|
||||
scope: Type.Literal('stx_event'),
|
||||
asset_identifier: Type.String(),
|
||||
actions: Type.Array(Type.String()),
|
||||
});
|
||||
|
||||
export const StacksIfThisPrintEventSchema = Type.Object({
|
||||
scope: Type.Literal('print_event'),
|
||||
contract_identifier: Type.String(),
|
||||
contains: Type.String(),
|
||||
});
|
||||
|
||||
export const StacksIfThisContractCallSchema = Type.Object({
|
||||
scope: Type.Literal('contract_call'),
|
||||
contract_identifier: Type.String(),
|
||||
method: Type.String(),
|
||||
});
|
||||
|
||||
export const StacksIfThisContractDeploymentSchema = Type.Object({
|
||||
scope: Type.Literal('contract_deployment'),
|
||||
deployer: Type.String(),
|
||||
});
|
||||
|
||||
export const StacksIfThisContractDeploymentTraitSchema = Type.Object({
|
||||
scope: Type.Literal('contract_deployment'),
|
||||
implement_trait: Type.String(),
|
||||
});
|
||||
@@ -1,165 +0,0 @@
|
||||
import { Type, TypeBoxTypeProvider } from '@fastify/type-provider-typebox';
|
||||
import Fastify, {
|
||||
FastifyInstance,
|
||||
FastifyPluginCallback,
|
||||
FastifyReply,
|
||||
FastifyRequest,
|
||||
} from 'fastify';
|
||||
import { Server } from 'http';
|
||||
import { request } from 'undici';
|
||||
import { logger, PINO_CONFIG } from './logger';
|
||||
import { timeout } from './helpers';
|
||||
import { Payload, PayloadSchema, IfThis, Predicate } from '../schemas';
|
||||
|
||||
type ServerOptions = {
|
||||
server: {
|
||||
host: string;
|
||||
port: number;
|
||||
auth_token: string;
|
||||
external_hostname: string;
|
||||
};
|
||||
chainhook_node: {
|
||||
hostname: string;
|
||||
port: number;
|
||||
};
|
||||
predicates: [
|
||||
{
|
||||
chain: 'stacks' | 'bitcoin';
|
||||
network: 'mainnet' | 'testnet';
|
||||
uuid: string;
|
||||
name: string;
|
||||
start_block?: number;
|
||||
end_block?: number;
|
||||
if_this: IfThis;
|
||||
callback: (payload: Payload) => Promise<void>;
|
||||
}
|
||||
];
|
||||
};
|
||||
|
||||
/**
|
||||
* Starts the chainhook event server.
|
||||
* @returns Fastify instance
|
||||
*/
|
||||
export async function startServer(opts: ServerOptions) {
|
||||
const base_path = `http://${opts.chainhook_node.hostname}:${opts.chainhook_node.port}`;
|
||||
|
||||
async function waitForChainhookNode(this: FastifyInstance) {
|
||||
logger.info(`EventServer connecting to chainhook node...`);
|
||||
while (true) {
|
||||
try {
|
||||
await request(`${base_path}/ping`, { method: 'GET', throwOnError: true });
|
||||
break;
|
||||
} catch (error) {
|
||||
logger.error(error, 'Chainhook node not available, retrying...');
|
||||
await timeout(1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function registerChainhookPredicates(this: FastifyInstance) {
|
||||
logger.info(opts.predicates, `EventServer registering predicates on ${base_path}...`);
|
||||
for (const predicate of opts.predicates) {
|
||||
try {
|
||||
const body: Predicate = {
|
||||
uuid: predicate.uuid,
|
||||
name: predicate.name,
|
||||
version: 1,
|
||||
chain: predicate.chain,
|
||||
networks: {
|
||||
[predicate.network]: {
|
||||
start_block: predicate.start_block,
|
||||
end_block: predicate.end_block,
|
||||
if_this: predicate.if_this,
|
||||
then_that: {
|
||||
http_post: {
|
||||
url: `http://${opts.server.external_hostname}/chainhook/${predicate.uuid}`,
|
||||
authorization_header: `Bearer ${opts.server.auth_token}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
await request(`${base_path}/v1/chainhooks`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
headers: { 'content-type': 'application/json' },
|
||||
throwOnError: true,
|
||||
});
|
||||
logger.info(`EventServer registered '${predicate.name}' predicate (${predicate.uuid})`);
|
||||
} catch (error) {
|
||||
logger.error(error, `EventServer unable to register predicate`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function removeChainhookPredicates(this: FastifyInstance) {
|
||||
logger.info(`EventServer closing predicates...`);
|
||||
for (const predicate of opts.predicates) {
|
||||
try {
|
||||
await request(`${base_path}/v1/chainhooks/${predicate.chain}/${predicate.uuid}`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
throwOnError: true,
|
||||
});
|
||||
logger.info(`EventServer removed '${predicate.name}' predicate (${predicate.uuid})`);
|
||||
} catch (error) {
|
||||
logger.error(error, `EventServer unable to deregister predicate`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function isAuthorizedChainhookEvent(request: FastifyRequest, reply: FastifyReply) {
|
||||
const authHeader = request.headers.authorization;
|
||||
if (authHeader && authHeader === `Bearer ${opts.server.auth_token}`) {
|
||||
return;
|
||||
}
|
||||
await reply.code(403).send();
|
||||
}
|
||||
|
||||
const EventServer: FastifyPluginCallback<Record<never, never>, Server, TypeBoxTypeProvider> = (
|
||||
fastify,
|
||||
options,
|
||||
done
|
||||
) => {
|
||||
fastify.addHook('preHandler', isAuthorizedChainhookEvent);
|
||||
fastify.post(
|
||||
'/chainhook/:uuid',
|
||||
{
|
||||
schema: {
|
||||
params: Type.Object({
|
||||
uuid: Type.String({ format: 'uuid' }),
|
||||
}),
|
||||
body: PayloadSchema,
|
||||
},
|
||||
},
|
||||
async (request, reply) => {
|
||||
try {
|
||||
const predicate = opts.predicates.find(p => p.uuid === request.params.uuid);
|
||||
if (predicate) {
|
||||
await predicate.callback(request.body);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(error, `EventServer error processing payload`);
|
||||
await reply.code(422).send();
|
||||
}
|
||||
await reply.code(200).send();
|
||||
}
|
||||
);
|
||||
done();
|
||||
};
|
||||
|
||||
const fastify = Fastify({
|
||||
trustProxy: true,
|
||||
logger: PINO_CONFIG,
|
||||
pluginTimeout: 0, // Disable so ping can retry indefinitely
|
||||
bodyLimit: 41943040, // 40 MB
|
||||
}).withTypeProvider<TypeBoxTypeProvider>();
|
||||
|
||||
fastify.addHook('onReady', waitForChainhookNode);
|
||||
fastify.addHook('onReady', registerChainhookPredicates);
|
||||
fastify.addHook('onClose', removeChainhookPredicates);
|
||||
await fastify.register(EventServer);
|
||||
|
||||
await fastify.listen({ host: opts.server.host, port: opts.server.port });
|
||||
return fastify;
|
||||
}
|
||||
@@ -1,105 +1,19 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
/* Visit https://aka.ms/tsconfig to read more about this file */
|
||||
|
||||
/* Projects */
|
||||
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
|
||||
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
||||
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
|
||||
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
|
||||
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
||||
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
||||
|
||||
/* Language and Environment */
|
||||
"target": "es2021", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
||||
"lib": [ "es2021" ], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
||||
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
|
||||
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
||||
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
||||
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
||||
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
||||
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
||||
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
||||
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
||||
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
||||
|
||||
/* Modules */
|
||||
"module": "commonjs", /* Specify what module code is generated. */
|
||||
// "rootDir": "./", /* Specify the root folder within your source files. */
|
||||
"moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
|
||||
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
||||
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
||||
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
||||
"typeRoots": [
|
||||
"./node_modules/@types"
|
||||
], /* Specify multiple folders that act like './node_modules/@types'. */
|
||||
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
||||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
||||
// "resolveJsonModule": true, /* Enable importing .json files. */
|
||||
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
||||
|
||||
/* JavaScript Support */
|
||||
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
||||
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
||||
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
||||
|
||||
/* Emit */
|
||||
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
||||
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
||||
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
||||
"declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
||||
"sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
||||
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
||||
"outDir": "./dist", /* Specify an output folder for all emitted files. */
|
||||
// "removeComments": true, /* Disable emitting comments. */
|
||||
// "noEmit": true, /* Disable emitting files from a compilation. */
|
||||
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
||||
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
|
||||
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
||||
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
||||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
||||
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
||||
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
||||
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
||||
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
||||
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
||||
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
||||
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
||||
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
||||
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
|
||||
|
||||
/* Interop Constraints */
|
||||
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
||||
"allowSyntheticDefaultImports": false, /* Allow 'import x from y' when a module doesn't have a default export. */
|
||||
"esModuleInterop": false, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
|
||||
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
||||
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
|
||||
|
||||
/* Type Checking */
|
||||
"strict": true, /* Enable all strict type-checking options. */
|
||||
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
||||
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
||||
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
||||
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
||||
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
||||
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
||||
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
||||
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
||||
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
||||
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
||||
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
||||
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
||||
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
||||
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
||||
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
||||
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
||||
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
||||
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
||||
|
||||
/* Completeness */
|
||||
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
||||
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
||||
},
|
||||
"include": [
|
||||
|
||||
Reference in New Issue
Block a user